Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add github.com/matryer/moq style mocks into mockery #725

Open
wants to merge 54 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
54 commits
Select commit Hold shift + click to select a range
e06c157
Internal registry for disambiguated imports, vars (#141)
sudo-suhas Feb 1, 2021
36a85ce
feat: support generic interface generation (#175)
cgorenflo Oct 1, 2022
d1b2fd4
Go version independent moq output with consistent whitespace
sudo-suhas Nov 13, 2022
d411b15
Add flag to enable mock reset methods (#181)
cbaker Mar 8, 2023
0028a34
updates
LandonTClipp Oct 19, 2023
d16ef1b
Internal registry for disambiguated imports, vars (#141)
sudo-suhas Feb 1, 2021
5ea7cda
Fix var name generation to avoid conflict (#145)
sudo-suhas Feb 14, 2021
2c9d05c
Ignore anonymous imports when resolving import aliases (#150)
maneac Jul 4, 2021
9e0e5d0
Fix issue with custom types shadowing basic types (#163)
dedalusj Dec 18, 2021
92a6e93
Added packages.NeedDeps bit to packages.LoadMode to fix error (#171)
metalrex100 Mar 29, 2022
4468afa
feat: support generic interface generation (#175)
cgorenflo Oct 1, 2022
fb12cf9
Recursively check unique pkg names against existing imports
sudo-suhas Nov 13, 2022
ebe7652
Add imports for Named Type's type arguments (#199)
TimVosch Jun 21, 2023
222a8a9
Do not load unnecessary package information (#203)
samherrmann Aug 13, 2023
1d04e7d
Add registry package from moq
LandonTClipp Oct 19, 2023
e68ee26
updates
LandonTClipp Oct 19, 2023
3eb17fe
updates
LandonTClipp Oct 19, 2023
860c2c8
updates
LandonTClipp Oct 20, 2023
d66be2c
Add more code to plumb through all the values needed by moq registry …
LandonTClipp Nov 20, 2023
1edd82f
Successfully created first moq
LandonTClipp Dec 23, 2023
f19f1f1
add config for moq
LandonTClipp Dec 23, 2023
852b19e
add formatter back
LandonTClipp Dec 23, 2023
9d89443
fix
LandonTClipp Dec 23, 2023
9aa5b53
change moq.templ comment
LandonTClipp Feb 12, 2024
1f078dc
Merge branch 'master' into moq
LandonTClipp Feb 12, 2024
e3fe47c
fix formatting issue with master merge
LandonTClipp Feb 12, 2024
62ef480
Add generics plumbing through moq
LandonTClipp Feb 12, 2024
5d37c18
update mocks with new features
LandonTClipp Feb 12, 2024
f9bee27
Move generator to separate package
LandonTClipp Feb 13, 2024
2ded465
Add moq configuration to Taskfile
LandonTClipp Feb 13, 2024
f144fb5
fix config
LandonTClipp Feb 13, 2024
4a1905b
Add mocks for moq
LandonTClipp Feb 13, 2024
d25b5da
fix config
LandonTClipp Feb 13, 2024
63653e0
fix taskfile
LandonTClipp Feb 13, 2024
a0f012b
Split out warn logs to logging package
LandonTClipp Feb 13, 2024
19b9718
Add template-map config param.
LandonTClipp Feb 13, 2024
db5f5a6
check err of generateMockery
LandonTClipp Feb 13, 2024
05f2c4d
update moq mocks
LandonTClipp Feb 13, 2024
587f197
update docs and moq config
LandonTClipp Feb 13, 2024
1805cf2
fix tests
LandonTClipp Feb 13, 2024
0aa59fb
Merge branch 'master' into moq
LandonTClipp Feb 13, 2024
cdd540b
Fix issue with ordering of filesystem walk
LandonTClipp Feb 13, 2024
ddf4a43
Merge branch 'moq' of github.com:LandonTClipp/mockery into moq
LandonTClipp Feb 13, 2024
7f4d02d
fix to go.mod logic
LandonTClipp Feb 13, 2024
78eb414
Add context.Context to more moq functions for logging
LandonTClipp Feb 21, 2024
f0de03c
Change name of moq mocks
LandonTClipp Feb 21, 2024
a82b265
Fix moq generation when inpackage=True
LandonTClipp Feb 21, 2024
a9aac88
Fix issue with registry not importing original package
LandonTClipp Feb 21, 2024
f57f7b1
update moqs
LandonTClipp Feb 21, 2024
dd61c0f
Merge branch 'master' into moq
LandonTClipp Feb 21, 2024
c8a2304
change codecov threshold to 0
LandonTClipp Feb 21, 2024
37562c5
updates
LandonTClipp Feb 21, 2024
4ddd30b
reduce codecov patch requirement to 0
LandonTClipp Feb 21, 2024
8ff0a85
fix codecov project target
LandonTClipp Feb 21, 2024
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
Prev Previous commit
Next Next commit
Internal registry for disambiguated imports, vars (#141)
* Internal registry for disambiguated imports, vars
- Move functionality in the moq package partially into
  internal/{registry,template}.
- Leverage registry to assign unique package and variable/method
  parameter names. Use import aliases if present in interface source
  package.
BREAKING CHANGE: When the interface definition does not mention the
parameter names, the field names in call info anonymous struct will be
different.
The new field names are generated using the type info (string -> s,
int -> n, chan int -> intCh, []MyType -> myTypes, map[string]int ->
stringToInt etc.).
For example, for a string parameter previously if the field name was
'In1', the new field could be 'S' or 'S1' (depends on number of
string method parameters).
* Refactor golden file tests to be table-driven
* Fix sync pkg alias handling for moq generation
* Improve, add tests (increase coverage)
* Use $.Foo in template, avoid declaring variables
$ is set to the data argument passed to Execute, that is, to the
starting value of dot.
Variables were declared to be able to refer to the parent context.
* Consistent template field formatting
* Use tabs in generated Godoc comments' example code
* Minor simplification
* go generate
* Fix conflict for generated param name of pointer type

Excellent work by @sudo-suhas.
  • Loading branch information
sudo-suhas authored and LandonTClipp committed Dec 23, 2023
commit d16ef1bb36911f93ba89d62aa46e06ed3526f7a4
155 changes: 155 additions & 0 deletions internal/registry/method_scope.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
package registry

import (
"go/types"
"strconv"
)

// MethodScope is the sub-registry for allocating variables present in
// the method scope.
//
// It should be created using a registry instance.
type MethodScope struct {
registry *Registry
moqPkgPath string

vars []*Var
conflicted map[string]bool
}

// AddVar allocates a variable instance and adds it to the method scope.
//
// Variables names are generated if required and are ensured to be
// without conflict with other variables and imported packages. It also
// adds the relevant imports to the registry for each added variable.
func (m *MethodScope) AddVar(vr *types.Var, suffix string) *Var {
name := vr.Name()
if name == "" || name == "_" {
name = generateVarName(vr.Type())
}

name += suffix

switch name {
case "mock", "callInfo", "break", "default", "func", "interface", "select", "case", "defer", "go", "map", "struct",
"chan", "else", "goto", "package", "switch", "const", "fallthrough", "if", "range", "type", "continue", "for",
"import", "return", "var":
name += "MoqParam"
}

if _, ok := m.searchVar(name); ok || m.conflicted[name] {
return m.addDisambiguatedVar(vr, name)
}

return m.addVar(vr, name)
}

func (m *MethodScope) addDisambiguatedVar(vr *types.Var, suggested string) *Var {
n := 1
for {
// Keep incrementing the suffix until we find a name which is unused.
if _, ok := m.searchVar(suggested + strconv.Itoa(n)); !ok {
break
}
n++
}

name := suggested + strconv.Itoa(n)
if n == 1 {
conflict, _ := m.searchVar(suggested)
conflict.Name += "1"
name = suggested + "2"
m.conflicted[suggested] = true
}

return m.addVar(vr, name)
}

func (m *MethodScope) addVar(vr *types.Var, name string) *Var {
imports := make(map[string]*Package)
m.populateImports(vr.Type(), imports)

v := Var{
vr: vr,
imports: imports,
moqPkgPath: m.moqPkgPath,
Name: name,
}
m.vars = append(m.vars, &v)
m.resolveImportVarConflicts(&v)
return &v
}

func (m MethodScope) searchVar(name string) (*Var, bool) {
for _, v := range m.vars {
if v.Name == name {
return v, true
}
}

return nil, false
}

// populateImports extracts all the package imports for a given type
// recursively. The imported packages by a single type can be more than
// one (ex: map[a.Type]b.Type).
func (m MethodScope) populateImports(t types.Type, imports map[string]*Package) {
switch t := t.(type) {
case *types.Named:
if pkg := t.Obj().Pkg(); pkg != nil {
imports[stripVendorPath(pkg.Path())] = m.registry.AddImport(pkg)
}

case *types.Array:
m.populateImports(t.Elem(), imports)

case *types.Slice:
m.populateImports(t.Elem(), imports)

case *types.Signature:
for i := 0; i < t.Params().Len(); i++ {
m.populateImports(t.Params().At(i).Type(), imports)
}
for i := 0; i < t.Results().Len(); i++ {
m.populateImports(t.Results().At(i).Type(), imports)
}

case *types.Map:
m.populateImports(t.Key(), imports)
m.populateImports(t.Elem(), imports)

case *types.Chan:
m.populateImports(t.Elem(), imports)

case *types.Pointer:
m.populateImports(t.Elem(), imports)

case *types.Struct: // anonymous struct
for i := 0; i < t.NumFields(); i++ {
m.populateImports(t.Field(i).Type(), imports)
}

case *types.Interface: // anonymous interface
for i := 0; i < t.NumExplicitMethods(); i++ {
m.populateImports(t.ExplicitMethod(i).Type(), imports)
}
for i := 0; i < t.NumEmbeddeds(); i++ {
m.populateImports(t.EmbeddedType(i), imports)
}
}
}

func (m MethodScope) resolveImportVarConflicts(v *Var) {
// Ensure that the newly added var does not conflict with a package import
// which was added earlier.
if _, ok := m.registry.searchImport(v.Name); ok {
v.Name += "MoqParam"
}
// Ensure that all the newly added imports do not conflict with any of the
// existing vars.
for _, imprt := range v.imports {
if v, ok := m.searchVar(imprt.Qualifier()); ok {
v.Name += "MoqParam"
}
}
}
93 changes: 93 additions & 0 deletions internal/registry/package.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package registry

import (
"go/types"
"path"
"strings"
)

// Package represents an imported package.
type Package struct {
pkg *types.Package

Alias string
}

// NewPackage creates a new instance of Package.
func NewPackage(pkg *types.Package) *Package { return &Package{pkg: pkg} }

// Qualifier returns the qualifier which must be used to refer to types
// declared in the package.
func (p *Package) Qualifier() string {
if p == nil {
return ""
}

if p.Alias != "" {
return p.Alias
}

return p.pkg.Name()
}

// Path is the full package import path (without vendor).
func (p *Package) Path() string {
if p == nil {
return ""
}

return stripVendorPath(p.pkg.Path())
}

var replacer = strings.NewReplacer(
"go-", "",
"-go", "",
"-", "",
"_", "",
".", "",
"@", "",
"+", "",
"~", "",
)

// uniqueName generates a unique name for a package by concatenating
// path components. The generated name is guaranteed to unique with an
// appropriate level because the full package import paths themselves
// are unique.
func (p Package) uniqueName(lvl int) string {
pp := strings.Split(p.Path(), "/")
reverse(pp)

var name string
for i := 0; i < min(len(pp), lvl+1); i++ {
name = strings.ToLower(replacer.Replace(pp[i])) + name
}

return name
}

// stripVendorPath strips the vendor dir prefix from a package path.
// For example we might encounter an absolute path like
// github.com/foo/bar/vendor/github.com/pkg/errors which is resolved
// to github.com/pkg/errors.
func stripVendorPath(p string) string {
parts := strings.Split(p, "/vendor/")
if len(parts) == 1 {
return p
}
return strings.TrimLeft(path.Join(parts[1:]...), "/")
}

func min(a, b int) int {
if a < b {
return a
}
return b
}

func reverse(a []string) {
for i := len(a)/2 - 1; i >= 0; i-- {
opp := len(a) - 1 - i
a[i], a[opp] = a[opp], a[i]
}
}
Loading