Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 8 additions & 15 deletions internal/template/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,22 +48,15 @@ import (
{{- if not $.SkipEnsure -}}
// Ensure, that {{.MockName}} does implement {{$.SrcPkgQualifier}}{{.InterfaceName}}.
// If this is not the case, regenerate this file with moq.
{{if .TypeParams -}}
func _[{{range $index, $param := .TypeParams}}{{if $index}}, {{end}}{{$param.Name | Exported}} {{$param.TypeString}}{{end}}]() {
{{end -}}
var _ {{$.SrcPkgQualifier}}{{.InterfaceName -}}
{{- if .TypeParams }}[
{{- range $index, $param := .TypeParams}}
{{- if $index}}, {{end -}}
{{if $param.Constraint}}{{$param.Constraint.String}}{{else}}{{$param.TypeString}}{{end}}
{{- end -}}
]
{{- end }} = &{{.MockName}}
{{- if .TypeParams }}[
{{- range $index, $param := .TypeParams}}
{{- if $index}}, {{end -}}
{{if $param.Constraint}}{{$param.Constraint.String}}{{else}}{{$param.TypeString}}{{end}}
{{- end -}}
]
{{- end -}}
{}
{{- if .TypeParams }}[{{range $index, $param := .TypeParams}}{{if $index}}, {{end}}{{$param.Name | Exported}}{{end}}]{{end}} = &{{.MockName -}}
{{- if .TypeParams }}[{{range $index, $param := .TypeParams}}{{if $index}}, {{end}}{{$param.Name | Exported}}{{end}}]{{end}}{}
{{- if .TypeParams}}
}
{{- end}}
{{- end}}

// {{.MockName}} is a mock implementation of {{$.SrcPkgQualifier}}{{.InterfaceName}}.
Expand Down
9 changes: 1 addition & 8 deletions internal/template/template_data.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package template

import (
"fmt"
"go/types"
"strings"

"github.com/matryer/moq/internal/registry"
Expand Down Expand Up @@ -35,7 +34,7 @@ func (d Data) MocksSomeMethod() bool {
type MockData struct {
InterfaceName string
MockName string
TypeParams []TypeParamData
TypeParams []ParamData
Methods []MethodData
}

Expand Down Expand Up @@ -90,12 +89,6 @@ func (m MethodData) ReturnArgNameList() string {
return strings.Join(params, ", ")
}

// TypeParamData extends ParamData with a constraint.
type TypeParamData struct {
ParamData
Constraint types.Type
}

// ParamData is the data which represents a parameter to some method of
// an interface.
type ParamData struct {
Expand Down
67 changes: 67 additions & 0 deletions pkg/moq/generic_constraints_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package moq

import (
"bytes"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)

func TestGenericConstraintEnsure(t *testing.T) {
for _, skipEnsure := range []bool{false, true} {
name := "ensure"
if skipEnsure {
name = "skip-ensure"
}
t.Run(name, func(t *testing.T) {
m, err := New(Config{SrcDir: "testpackages/genericconstraints", SkipEnsure: skipEnsure})
if err != nil {
t.Fatal(err)
}
var generated bytes.Buffer
if err := m.Mock(&generated, "Sorter", "Store"); err != nil {
t.Fatal(err)
}
source, err := os.ReadFile("testpackages/genericconstraints/genericconstraints.go")
if err != nil {
t.Fatal(err)
}
dir := t.TempDir()
for file, contents := range map[string][]byte{
"go.mod": []byte("module genericconstraints\n\ngo 1.26.0\n"),
"source.go": source,
"mock.go": generated.Bytes(),
} {
if err := os.WriteFile(filepath.Join(dir, file), contents, 0o600); err != nil {
t.Fatal(err)
}
}
compile := func() ([]byte, error) {
cmd := exec.Command("go", "test", "./...")
cmd.Dir = dir
return cmd.CombinedOutput()
}
if out, err := compile(); err != nil {
t.Fatalf("generated code did not compile: %v\n%s", err, out)
}
// A broken implementation must be rejected by the ensure, even when
// its generic function is never instantiated or called.
broken := strings.Replace(generated.String(), ") Sort(", ") sort(", 1)
if broken == generated.String() {
t.Fatal("generated Sort method not found")
}
if err := os.WriteFile(filepath.Join(dir, "mock.go"), []byte(broken), 0o600); err != nil {
t.Fatal(err)
}
out, err := compile()
if skipEnsure && err != nil {
t.Fatalf("skip-ensure unexpectedly checked implementation: %v\n%s", err, out)
}
if !skipEnsure && (err == nil || !bytes.Contains(out, []byte("missing method Sort"))) {
t.Fatalf("ensure did not reject missing Sort method: %v\n%s", err, out)
}
})
}
}
27 changes: 4 additions & 23 deletions pkg/moq/moq.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,43 +114,24 @@ func (m *Mocker) Mock(w io.Writer, namePairs ...string) error {
return nil
}

func (m *Mocker) typeParams(tparams *types.TypeParamList) []template.TypeParamData {
var tpd []template.TypeParamData
func (m *Mocker) typeParams(tparams *types.TypeParamList) []template.ParamData {
var tpd []template.ParamData
if tparams == nil {
return tpd
}

tpd = make([]template.TypeParamData, tparams.Len())
tpd = make([]template.ParamData, tparams.Len())

scope := m.registry.MethodScope()
for i := 0; i < len(tpd); i++ {
tp := tparams.At(i)
typeParam := types.NewParam(token.Pos(i), tp.Obj().Pkg(), tp.Obj().Name(), tp.Constraint())
tpd[i] = template.TypeParamData{
ParamData: template.ParamData{Var: scope.AddVar(typeParam, "")},
Constraint: explicitConstraintType(typeParam),
}
tpd[i] = template.ParamData{Var: scope.AddVar(typeParam, "")}
}

return tpd
}

func explicitConstraintType(typeParam *types.Var) (t types.Type) {
underlying := typeParam.Type().Underlying().(*types.Interface)
// check if any of the embedded types is either a basic type or a union,
// because the generic type has to be an alias for one of those types then
for j := 0; j < underlying.NumEmbeddeds(); j++ {
t := underlying.EmbeddedType(j)
switch t := t.(type) {
case *types.Basic:
return t
case *types.Union: // only unions of basic types are allowed, so just take the first one as a valid type constraint
return t.Term(0).Type()
}
}
return nil
}

func (m *Mocker) methodData(f *types.Func) template.MethodData {
sig := f.Type().(*types.Signature)

Expand Down
19 changes: 19 additions & 0 deletions pkg/moq/testpackages/genericconstraints/genericconstraints.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package genericconstraints

import "fmt"

// Sorter exercises the comparable constraint reported in issue #200.
type Sorter[T comparable] interface {
Sort([]T) []T
}

// StringKey combines a type set with a method requirement.
type StringKey interface {
~string
fmt.Stringer
}

// Store exercises dependent and method-bearing constraints without choosing instances.
type Store[K StringKey, V ~map[K]string] interface {
Get(K) V
}
8 changes: 6 additions & 2 deletions pkg/moq/testpackages/generics/generics_moq.golden.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion pkg/moq/testpackages/withresets/withresets_moq.golden.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.