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
updates
  • Loading branch information
LandonTClipp committed Dec 23, 2023
commit 860c2c84140f8db8ff2a41bf015645062deafaa5
11 changes: 6 additions & 5 deletions cmd/mockery.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,10 +211,6 @@ func (r *RootApp) Run() error {
return nil
}

var osp pkg.OutputStreamProvider
if r.Config.Print {
osp = &pkg.StdoutStreamProvider{}
}
buildTags := strings.Split(r.Config.BuildTags, " ")

var boilerplate string
Expand Down Expand Up @@ -268,7 +264,7 @@ func (r *RootApp) Run() error {
}
ifaceLog.Debug().Msg("config specifies to generate this interface")

outputter := pkg.NewOutputter(&r.Config, boilerplate, true)
outputter := pkg.NewOutputter(&r.Config, boilerplate)
if err := outputter.Generate(ifaceCtx, iface); err != nil {
return err
}
Expand All @@ -277,6 +273,11 @@ func (r *RootApp) Run() error {
return nil
}

var osp pkg.OutputStreamProvider
if r.Config.Print {
osp = &pkg.StdoutStreamProvider{}
}

if r.Config.Name != "" && r.Config.All {
log.Fatal().Msgf("Specify --name or --all, but not both")
} else if (r.Config.FileName != "" || r.Config.StructName != "") && r.Config.All {
Expand Down
34 changes: 34 additions & 0 deletions pkg/interface.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package pkg

import (
"go/ast"
"go/types"
)

// Interface type represents the target type that we will generate a mock for.
// It could be an interface, or a function type.
// Function type emulates: an interface it has 1 method with the function signature
// and a general name, e.g. "Execute".
type Interface struct {
Name string // Name of the type to be mocked.
QualifiedName string // Path to the package of the target type.
FileName string
File *ast.File
Pkg TypesPackage
NamedType *types.Named
IsFunction bool // If true, this instance represents a function, otherwise it's an interface.
ActualInterface *types.Interface // Holds the actual interface type, in case it's an interface.
SingleFunction *Method // Holds the function type information, in case it's a function type.
}

func (iface *Interface) Methods() []*Method {
if iface.IsFunction {
return []*Method{iface.SingleFunction}
}
methods := make([]*Method, iface.ActualInterface.NumMethods())
for i := 0; i < iface.ActualInterface.NumMethods(); i++ {
fn := iface.ActualInterface.Method(i)
methods[i] = &Method{Name: fn.Name(), Signature: fn.Type().(*types.Signature)}
}
return methods
}
88 changes: 88 additions & 0 deletions pkg/method.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package pkg

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

type Method struct {
Name string
Signature *types.Signature
}

type Imports map[string]*types.Package

func (m Method) populateImports(imports Imports) {
for i := 0; i < m.Signature.Params().Len(); i++ {
m.importsHelper(m.Signature.Params().At(i).Type(), imports)
}
}

// 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:]...), "/")
}

// importsHelper 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 Method) importsHelper(elem types.Type, imports map[string]*types.Package) {
switch t := elem.(type) {
case *types.Named:
if pkg := t.Obj().Pkg(); pkg != nil {
imports[stripVendorPath(pkg.Path())] = pkg
}
// The imports of a Type with a TypeList must be added to the imports list
// For example: Foo[otherpackage.Bar] , must have otherpackage imported
if targs := t.TypeArgs(); targs != nil {
for i := 0; i < targs.Len(); i++ {
m.importsHelper(targs.At(i), imports)
}
}

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

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

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

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

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

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

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

case *types.Interface: // anonymous interface
for i := 0; i < t.NumExplicitMethods(); i++ {
m.importsHelper(t.ExplicitMethod(i).Type(), imports)
}
for i := 0; i < t.NumEmbeddeds(); i++ {
m.importsHelper(t.EmbeddedType(i), imports)
}
}
}
2 changes: 0 additions & 2 deletions pkg/outputter.go
Original file line number Diff line number Diff line change
Expand Up @@ -297,12 +297,10 @@ type Outputter struct {
func NewOutputter(
config *config.Config,
boilerplate string,
dryRun bool,
) *Outputter {
return &Outputter{
boilerplate: boilerplate,
config: config,
dryRun: dryRun,
}
}

Expand Down
31 changes: 0 additions & 31 deletions pkg/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,43 +261,12 @@ func (p *Parser) packageInterfaces(
return ifaces
}

type Method struct {
Name string
Signature *types.Signature
}

type TypesPackage interface {
Name() string
Path() string
}

// Interface type represents the target type that we will generate a mock for.
// It could be an interface, or a function type.
// Function type emulates: an interface it has 1 method with the function signature
// and a general name, e.g. "Execute".
type Interface struct {
Name string // Name of the type to be mocked.
QualifiedName string // Path to the package of the target type.
FileName string
File *ast.File
Pkg TypesPackage
NamedType *types.Named
IsFunction bool // If true, this instance represents a function, otherwise it's an interface.
ActualInterface *types.Interface // Holds the actual interface type, in case it's an interface.
SingleFunction *Method // Holds the function type information, in case it's a function type.
}

func (iface *Interface) Methods() []*Method {
if iface.IsFunction {
return []*Method{iface.SingleFunction}
}
methods := make([]*Method, iface.ActualInterface.NumMethods())
for i := 0; i < iface.ActualInterface.NumMethods(); i++ {
fn := iface.ActualInterface.Method(i)
methods[i] = &Method{Name: fn.Name(), Signature: fn.Type().(*types.Signature)}
}
return methods
}

type sortableIFaceList []*Interface

Expand Down
24 changes: 10 additions & 14 deletions pkg/registry/package.go
Original file line number Diff line number Diff line change
@@ -1,20 +1,26 @@
package registry

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

type TypesPackage interface {
Name() string
Path() string
}

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

Alias string
}

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

// Qualifier returns the qualifier which must be used to refer to types
// declared in the package.
Expand Down Expand Up @@ -66,17 +72,7 @@ func (p Package) uniqueName(lvl int) string {
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 {
Expand Down
32 changes: 5 additions & 27 deletions pkg/registry/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import (
"fmt"
"go/ast"
"go/types"
"path/filepath"
"sort"
"strings"

"github.com/chigopher/pathlib"
"golang.org/x/tools/go/packages"
)

Expand All @@ -19,25 +19,18 @@ import (
type Registry struct {
srcPkgName string
srcPkgTypes *types.Package
moqPkgPath string
outputPath *pathlib.Path
aliases map[string]string
imports map[string]*Package
}

// New loads the source package info and returns a new instance of
// Registry.
func New(srcDir, moqPkg string) (*Registry, error) {
srcPkg, err := pkgInfoFromPath(
srcDir, packages.NeedName|packages.NeedSyntax|packages.NeedTypes,
)
if err != nil {
return nil, fmt.Errorf("couldn't load source package: %s", err)
}

func New(srcPkg *packages.Package, outputPath *pathlib.Path) (*Registry, error) {
return &Registry{
srcPkgName: srcPkg.Name,
srcPkgTypes: srcPkg.Types,
moqPkgPath: findPkgPath(moqPkg, srcPkg.PkgPath),
outputPath: outputPath,
aliases: parseImportsAliases(srcPkg.Syntax),
imports: make(map[string]*Package),
}, nil
Expand Down Expand Up @@ -78,7 +71,6 @@ func (r Registry) LookupInterface(name string) (*types.Interface, *types.TypePar
func (r *Registry) MethodScope() *MethodScope {
return &MethodScope{
registry: r,
moqPkgPath: r.moqPkgPath,
conflicted: map[string]bool{},
}
}
Expand All @@ -88,7 +80,7 @@ func (r *Registry) MethodScope() *MethodScope {
// packages.
func (r *Registry) AddImport(pkg *types.Package) *Package {
path := stripVendorPath(pkg.Path())
if path == r.moqPkgPath {
if pathlib.NewPath(path).Equals(r.outputPath) {
return nil
}

Expand Down Expand Up @@ -176,20 +168,6 @@ func pkgInfoFromPath(srcDir string, mode packages.LoadMode) (*packages.Package,
return pkgs[0], nil
}

func findPkgPath(pkgInputVal string, srcPkgPath string) string {
if pkgInputVal == "" {
return srcPkgPath
}
if pkgInDir(srcPkgPath, pkgInputVal) {
return srcPkgPath
}
subdirectoryPath := filepath.Join(srcPkgPath, pkgInputVal)
if pkgInDir(subdirectoryPath, pkgInputVal) {
return subdirectoryPath
}
return ""
}

func pkgInDir(pkgName, dir string) bool {
currentPkg, err := pkgInfoFromPath(dir, packages.NeedName)
if err != nil {
Expand Down
16 changes: 13 additions & 3 deletions pkg/template_generator.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package pkg

import (
"github.com/vektra/mockery/v2/pkg/registry"
"github.com/vektra/mockery/v2/pkg/config"
"github.com/vektra/mockery/v2/pkg/template"
)

Expand All @@ -18,12 +18,22 @@ func NewTemplateGenerator(config TemplateGeneratorConfig) *TemplateGenerator {
}
}

func (g *TemplateGenerator) Generate() error {
func (g *TemplateGenerator) Generate(iface *Interface, ifaceConfig *config.Config) error {
templ, err := template.New(g.config.Style)
if err != nil {
return err
}
data := registry.
imports := Imports{}
for _, method := range iface.Methods() {
method.populateImports(imports)
}
// TODO: Work on getting these imports into the template

data := template.Data{
PkgName: ifaceConfig.Outpkg,
SrcPkgQualifier: iface.Pkg.Name() + ".",
Imports:
}

return nil
}