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
Add more code to plumb through all the values needed by moq registry …
…methods

In this commit, we gather all the template data needed by the moq logic to
generate its template. This is untested as of yet.

TODO: need to start testing this works by calling upon `moq` in `.mockery.yaml`.
  • Loading branch information
LandonTClipp committed Dec 23, 2023
commit d66be2c1d3e00173332b4190776743362c973cdb
3 changes: 3 additions & 0 deletions pkg/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package pkg
import (
"go/ast"
"go/types"

"golang.org/x/tools/go/packages"
)

// Interface type represents the target type that we will generate a mock for.
Expand All @@ -14,6 +16,7 @@ type Interface struct {
QualifiedName string // Path to the package of the target type.
FileName string
File *ast.File
PackagesPackage *packages.Package
Pkg TypesPackage
NamedType *types.Named
IsFunction bool // If true, this instance represents a function, otherwise it's an interface.
Expand Down
6 changes: 5 additions & 1 deletion pkg/outputter.go
Original file line number Diff line number Diff line change
Expand Up @@ -326,14 +326,18 @@
return fmt.Errorf("failed to parse config template: %w", err)
}
if interfaceConfig.Style == "mockery" {
o.generateMockery(ctx, iface, interfaceConfig)

Check failure on line 329 in pkg/outputter.go

View workflow job for this annotation

GitHub Actions / build (ubuntu-latest, 1.21)

Error return value of `o.generateMockery` is not checked (errcheck)
continue
}

config := TemplateGeneratorConfig{
Style: interfaceConfig.Style,
}
generator := NewTemplateGenerator(config)
generator, err := NewTemplateGenerator(iface.PackagesPackage, config)
if err != nil {
return fmt.Errorf("creating template generator: %w", err)
}

fmt.Printf("generator: %v\n", generator)

}
Expand Down
22 changes: 10 additions & 12 deletions pkg/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ func (p *Parser) Find(name string) (*Interface, error) {
for _, entry := range p.entries {
for _, iface := range entry.interfaces {
if iface == name {
list := p.packageInterfaces(entry.pkg.Types, entry.fileName, []string{name}, nil)
list := p.packageInterfaces(entry, []string{name}, nil)
if len(list) > 0 {
return list[0], nil
}
Expand All @@ -204,19 +204,18 @@ func (p *Parser) Interfaces() []*Interface {
ifaces := make(sortableIFaceList, 0)
for _, entry := range p.entries {
declaredIfaces := entry.interfaces
ifaces = p.packageInterfaces(entry.pkg.Types, entry.fileName, declaredIfaces, ifaces)
ifaces = p.packageInterfaces(entry, declaredIfaces, ifaces)
}

sort.Sort(ifaces)
return ifaces
}

func (p *Parser) packageInterfaces(
pkg *types.Package,
fileName string,
entry *parserEntry,
declaredInterfaces []string,
ifaces []*Interface) []*Interface {
scope := pkg.Scope()
scope := entry.pkg.Types.Scope()
for _, name := range declaredInterfaces {
obj := scope.Lookup(name)
if obj == nil {
Expand All @@ -235,11 +234,12 @@ func (p *Parser) packageInterfaces(
}

elem := &Interface{
Name: name,
Pkg: pkg,
QualifiedName: pkg.Path(),
FileName: fileName,
NamedType: typ,
Name: name,
PackagesPackage: entry.pkg,
Pkg: entry.pkg.Types,
QualifiedName: entry.pkg.Types.Path(),
FileName: entry.fileName,
NamedType: typ,
}

iface, ok := typ.Underlying().(*types.Interface)
Expand All @@ -266,8 +266,6 @@ type TypesPackage interface {
Path() string
}



type sortableIFaceList []*Interface

func (s sortableIFaceList) Len() int {
Expand Down
2 changes: 1 addition & 1 deletion pkg/registry/method_scope.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ 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)
imports[pkg.Path()] = m.registry.AddImport(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
Expand Down
5 changes: 1 addition & 4 deletions pkg/registry/package.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package registry

import (
"path"
"strings"
)

Expand Down Expand Up @@ -42,7 +41,7 @@ func (p *Package) Path() string {
return ""
}

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

var replacer = strings.NewReplacer(
Expand Down Expand Up @@ -72,8 +71,6 @@ func (p Package) uniqueName(lvl int) string {
return name
}



func min(a, b int) int {
if a < b {
return a
Expand Down
11 changes: 5 additions & 6 deletions pkg/registry/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"sort"
"strings"

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

Expand All @@ -18,19 +17,19 @@ import (
// qualifiers.
type Registry struct {
srcPkgName string
srcPkgPath string
srcPkgTypes *types.Package
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(srcPkg *packages.Package, outputPath *pathlib.Path) (*Registry, error) {
func New(srcPkg *packages.Package) (*Registry, error) {
return &Registry{
srcPkgName: srcPkg.Name,
srcPkgPath: srcPkg.PkgPath,
srcPkgTypes: srcPkg.Types,
outputPath: outputPath,
aliases: parseImportsAliases(srcPkg.Syntax),
imports: make(map[string]*Package),
}, nil
Expand Down Expand Up @@ -79,8 +78,8 @@ func (r *Registry) MethodScope() *MethodScope {
// suitable alias if there are any conflicts with previously imported
// packages.
func (r *Registry) AddImport(pkg *types.Package) *Package {
path := stripVendorPath(pkg.Path())
if pathlib.NewPath(path).Equals(r.outputPath) {
path := pkg.Path()
if pkg.Path() == r.srcPkgPath {
return nil
}

Expand Down
10 changes: 0 additions & 10 deletions pkg/registry/registry_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1 @@
package registry

import (
"testing"
)

func BenchmarkNew(b *testing.B) {
for i := 0; i < b.N; i++ {
New("../../pkg/moq/testpackages/example", "")
}
}
2 changes: 1 addition & 1 deletion pkg/registry/var.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func (v Var) TypeString() string {

// packageQualifier is a types.Qualifier.
func (v Var) packageQualifier(pkg *types.Package) string {
path := stripVendorPath(pkg.Path())
path := pkg.Path()
if v.moqPkgPath != "" && v.moqPkgPath == path {
return ""
}
Expand Down
93 changes: 82 additions & 11 deletions pkg/template_generator.go
Original file line number Diff line number Diff line change
@@ -1,39 +1,110 @@
package pkg

import (
"bytes"
"context"
"fmt"
"go/types"

"github.com/chigopher/pathlib"
"github.com/rs/zerolog"
"github.com/vektra/mockery/v2/pkg/config"
"github.com/vektra/mockery/v2/pkg/registry"
"github.com/vektra/mockery/v2/pkg/template"
"golang.org/x/tools/go/packages"
)

type TemplateGeneratorConfig struct {
Style string
}
type TemplateGenerator struct {
config TemplateGeneratorConfig
config TemplateGeneratorConfig
registry *registry.Registry
}

func NewTemplateGenerator(config TemplateGeneratorConfig) *TemplateGenerator {
return &TemplateGenerator{
config: config,
func NewTemplateGenerator(srcPkg *packages.Package, config TemplateGeneratorConfig) (*TemplateGenerator, error) {
reg, err := registry.New(srcPkg)
if err != nil {
return nil, fmt.Errorf("creating new registry: %w", err)
}

return &TemplateGenerator{
config: config,
registry: reg,
}, nil
}

func (g *TemplateGenerator) Generate(iface *Interface, ifaceConfig *config.Config) error {
templ, err := template.New(g.config.Style)
if err != nil {
return err
}
func (g *TemplateGenerator) Generate(ctx context.Context, iface *Interface, ifaceConfig *config.Config) error {
log := zerolog.Ctx(ctx)
log.Info().Msg("generating mock for interface")

imports := Imports{}
for _, method := range iface.Methods() {
method.populateImports(imports)
}
// TODO: Work on getting these imports into the template
methods := make([]template.MethodData, iface.ActualInterface.NumMethods())

for i := 0; i < iface.ActualInterface.NumMethods(); i++ {
method := iface.ActualInterface.Method(i)
methodScope := g.registry.MethodScope()

signature := method.Type().(*types.Signature)
params := make([]template.ParamData, signature.Params().Len())
for j := 0; j < signature.Params().Len(); j++ {
param := signature.Params().At(j)
params[j] = template.ParamData{
Var: methodScope.AddVar(param, ""),
Variadic: signature.Variadic() && j == signature.Params().Len()-1,
}
}

returns := make([]template.ParamData, signature.Results().Len())
for j := 0; j < signature.Results().Len(); j++ {
param := signature.Results().At(j)
returns[j] = template.ParamData{
Var: methodScope.AddVar(param, "Out"),
Variadic: false,
}
}

methods[i] = template.MethodData{
Name: method.Name(),
Params: params,
Returns: returns,
}

}

// For now, mockery only supports one mock per file, which is why we're creating
// a single-element list. moq seems to have supported multiple mocks per file.
mockData := []template.MockData{
{
InterfaceName: iface.Name,
MockName: ifaceConfig.MockName,
Methods: methods,
},
}
data := template.Data{
PkgName: ifaceConfig.Outpkg,
SrcPkgQualifier: iface.Pkg.Name() + ".",
Imports:
Imports: g.registry.Imports(),
Mocks: mockData,
}

templ, err := template.New(g.config.Style)
if err != nil {
return fmt.Errorf("creating new template: %w", err)
}

var buf bytes.Buffer
if err := templ.Execute(&buf, data); err != nil {
return fmt.Errorf("executing template: %w", err)
}

outPath := pathlib.NewPath(ifaceConfig.Dir).Join(ifaceConfig.FileName)
if err := outPath.WriteFile(buf.Bytes()); err != nil {
log.Error().Err(err).Msg("couldn't write to output file")
return fmt.Errorf("writing to output file: %w", err)
}
return nil
}
Loading