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 option to omit empty/nil variadic slice when unroll-variadic is false #624

Closed
Closed
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
26 changes: 14 additions & 12 deletions cmd/mockery.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ func NewRootCmd() *cobra.Command {
pFlags.Bool("disable-version-string", false, "Do not insert the version string into the generated mock file.")
pFlags.String("boilerplate-file", "", "File to read a boilerplate text from. Text should be a go block comment, i.e. /* ... */")
pFlags.Bool("unroll-variadic", true, "For functions with variadic arguments, do not unroll the arguments into the underlying testify call. Instead, pass variadic slice as-is.")
pFlags.Bool("omit-empty-rolled-variadic", false, "For functions with variadic arguments, omit passing empty slice to underlying testify call. Used in tandem with unroll-variadic set to false.")
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not super happy with the naming here.
Ideally unroll-variadic would be called roll-variadic and defaulted to false. We could then call this new option roll-variadic-omit-empty which feels better.
Curious - how do we feel about deprecating unroll-variadic in place of roll-variadic?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deprecating the variable name is probably a lot of effort. Technically speaking, "unroll" makes more sense as it is "expanding"/"unrolling" the slice into the variadic mock.On( testify call.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A part of me also feels like, if we do add this feature, it doesn’t need to be behind a feature flag. I can’t think of a case where this would break someone relying on the current logic?

pFlags.Bool("exported", false, "Generates public mocks for private interfaces.")
pFlags.Bool("with-expecter", false, "Generate expecter utility around mock's On, Run and Return methods with explicit types. This option is NOT compatible with -unroll-variadic=false")
pFlags.StringArray("replace-type", nil, "Replace types")
Expand Down Expand Up @@ -380,18 +381,19 @@ func (r *RootApp) Run() error {
}

visitor := pkg.NewGeneratorVisitor(pkg.GeneratorVisitorConfig{
Boilerplate: boilerplate,
DisableVersionString: r.Config.DisableVersionString,
Exported: r.Config.Exported,
InPackage: r.Config.InPackage,
KeepTree: r.Config.KeepTree,
Note: r.Config.Note,
PackageName: r.Config.Outpkg,
PackageNamePrefix: r.Config.Packageprefix,
StructName: r.Config.StructName,
UnrollVariadic: r.Config.UnrollVariadic,
WithExpecter: r.Config.WithExpecter,
ReplaceType: r.Config.ReplaceType,
Boilerplate: boilerplate,
DisableVersionString: r.Config.DisableVersionString,
Exported: r.Config.Exported,
InPackage: r.Config.InPackage,
KeepTree: r.Config.KeepTree,
Note: r.Config.Note,
PackageName: r.Config.Outpkg,
PackageNamePrefix: r.Config.Packageprefix,
StructName: r.Config.StructName,
UnrollVariadic: r.Config.UnrollVariadic,
OmitEmptyRolledVariadic: r.Config.OmitEmptyRolledVariadic,
WithExpecter: r.Config.WithExpecter,
ReplaceType: r.Config.ReplaceType,
}, osp, r.Config.DryRun)

generated := walker.Walk(ctx, visitor)
Expand Down

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

13 changes: 7 additions & 6 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,13 @@ type Config struct {
BoilerplateFile string `mapstructure:"boilerplate-file"`
// StructName overrides the name given to the mock struct and should only be nonempty
// when generating for an exact match (non regex expression in -name).
StructName string `mapstructure:"structname"`
TestOnly bool `mapstructure:"testonly"`
UnrollVariadic bool `mapstructure:"unroll-variadic"`
Version bool `mapstructure:"version"`
WithExpecter bool `mapstructure:"with-expecter"`
ReplaceType []string `mapstructure:"replace-type"`
StructName string `mapstructure:"structname"`
TestOnly bool `mapstructure:"testonly"`
UnrollVariadic bool `mapstructure:"unroll-variadic"`
OmitEmptyRolledVariadic bool `mapstructure:"omit-empty-rolled-variadic"`
Version bool `mapstructure:"version"`
WithExpecter bool `mapstructure:"with-expecter"`
ReplaceType []string `mapstructure:"replace-type"`

// Viper throws away case-sensitivity when it marshals into this struct. This
// destroys necessary information we need, specifically around interface names.
Expand Down
36 changes: 23 additions & 13 deletions pkg/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,18 +50,19 @@ func DetermineOutputPackageName(
}

type GeneratorConfig struct {
Boilerplate string
DisableVersionString bool
Exported bool
InPackage bool
KeepTree bool
Note string
PackageName string
PackageNamePrefix string
StructName string
UnrollVariadic bool
WithExpecter bool
ReplaceType []string
Boilerplate string
DisableVersionString bool
Exported bool
InPackage bool
KeepTree bool
Note string
PackageName string
PackageNamePrefix string
StructName string
UnrollVariadic bool
OmitEmptyRolledVariadic bool
WithExpecter bool
ReplaceType []string
}

// Generator is responsible for generating the string containing
Expand Down Expand Up @@ -938,7 +939,16 @@ func {{ .ConstructorName }}{{ .TypeConstraint }}(t {{ .ConstructorTestingInterfa
func (g *Generator) generateCalled(list *paramList) (preamble string, called string) {
namesLen := len(list.Names)
if namesLen == 0 || !list.Variadic || !g.config.UnrollVariadic {
called = "_m.Called(" + strings.Join(list.Names, ", ") + ")"
if !g.config.OmitEmptyRolledVariadic {
called = "_m.Called(" + strings.Join(list.Names, ", ") + ")"
return
}

variadicName := list.Names[namesLen-1]
tmpRet := resolveCollision(list.Names, "tmpRet")

preamble = fmt.Sprintf("\n\tvar " + tmpRet + " mock.Arguments\n\tif len(" + variadicName + ") > 0 {\n\t\t" + tmpRet + " = _m.Called(" + strings.Join(list.Names, ", ") + ")\n\t} else {\n\t\t" + tmpRet + " = _m.Called(" + strings.Join(list.Names[:len(list.Names)-1], ", ") + ")\n\t}\n\n\t")
called = tmpRet
return
}

Expand Down
28 changes: 28 additions & 0 deletions pkg/generator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1566,6 +1566,34 @@ func (s *GeneratorSuite) TestGeneratorVariadicArgsAsOneArg() {
)
}

func (s *GeneratorSuite) TestGeneratorVariadicArgsOmitEmpty() {
expectedBytes, err := os.ReadFile(getMocksPath("RequesterVariadicOmitEmpty.go"))
s.NoError(err)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be require.NoError

expected := string(expectedBytes)
expected = expected[strings.Index(expected, "// RequesterVariadicOmitEmpty is"):]
generator := NewGenerator(
s.ctx, GeneratorConfig{
StructName: "RequesterVariadicOmitEmpty",
InPackage: true,
UnrollVariadic: false,
OmitEmptyRolledVariadic: true,
}, s.getInterfaceFromFile("requester_variadic.go", "RequesterVariadic"), pkg,
)
s.NoError(generator.Generate(s.ctx), "The generator ran without errors.")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The message to NoError is what is displayed if there is an error. You probably don't need any message though.


var actual []byte
actual, fmtErr := format.Source(generator.buf.Bytes())
s.NoError(fmtErr, "The formatter ran without errors.")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ditto


expectedLines := strings.Split(expected, "\n")
actualLines := strings.Split(string(actual), "\n")

s.Equal(
expectedLines, actualLines,
"The generator produced unexpected output.",
)
}

func TestRequesterVariadicOneArgument(t *testing.T) {
t.Run("Get \"1\", \"2\", \"3\"", func(t *testing.T) {
m := mocks.RequesterVariadicOneArgument{}
Expand Down
25 changes: 13 additions & 12 deletions pkg/outputter.go
Original file line number Diff line number Diff line change
Expand Up @@ -271,18 +271,19 @@ func (m *Outputter) Generate(ctx context.Context, iface *Interface) error {
}

g := GeneratorConfig{
Boilerplate: m.boilerplate,
DisableVersionString: interfaceConfig.DisableVersionString,
Exported: interfaceConfig.Exported,
InPackage: interfaceConfig.InPackage,
KeepTree: interfaceConfig.KeepTree,
Note: interfaceConfig.Note,
PackageName: interfaceConfig.Outpkg,
PackageNamePrefix: interfaceConfig.Packageprefix,
StructName: interfaceConfig.MockName,
UnrollVariadic: interfaceConfig.UnrollVariadic,
WithExpecter: interfaceConfig.WithExpecter,
ReplaceType: interfaceConfig.ReplaceType,
Boilerplate: m.boilerplate,
DisableVersionString: interfaceConfig.DisableVersionString,
Exported: interfaceConfig.Exported,
InPackage: interfaceConfig.InPackage,
KeepTree: interfaceConfig.KeepTree,
Note: interfaceConfig.Note,
PackageName: interfaceConfig.Outpkg,
PackageNamePrefix: interfaceConfig.Packageprefix,
StructName: interfaceConfig.MockName,
UnrollVariadic: interfaceConfig.UnrollVariadic,
OmitEmptyRolledVariadic: interfaceConfig.OmitEmptyRolledVariadic,
WithExpecter: interfaceConfig.WithExpecter,
ReplaceType: interfaceConfig.ReplaceType,
}
generator := NewGenerator(ctx, g, iface, "")

Expand Down
38 changes: 20 additions & 18 deletions pkg/walker.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,12 +121,13 @@ type GeneratorVisitorConfig struct {
KeepTree bool
Note string
// The name of the output package, if InPackage is false (defaults to "mocks")
PackageName string
PackageNamePrefix string
StructName string
UnrollVariadic bool
WithExpecter bool
ReplaceType []string
PackageName string
PackageNamePrefix string
StructName string
UnrollVariadic bool
OmitEmptyRolledVariadic bool
WithExpecter bool
ReplaceType []string
}

type GeneratorVisitor struct {
Expand Down Expand Up @@ -175,18 +176,19 @@ func (v *GeneratorVisitor) VisitWalk(ctx context.Context, iface *Interface) erro
}()

generatorConfig := GeneratorConfig{
Boilerplate: v.config.Boilerplate,
DisableVersionString: v.config.DisableVersionString,
Exported: v.config.Exported,
InPackage: v.config.InPackage,
KeepTree: v.config.KeepTree,
Note: v.config.Note,
PackageName: v.config.PackageName,
PackageNamePrefix: v.config.PackageNamePrefix,
StructName: v.config.StructName,
UnrollVariadic: v.config.UnrollVariadic,
WithExpecter: v.config.WithExpecter,
ReplaceType: v.config.ReplaceType,
Boilerplate: v.config.Boilerplate,
DisableVersionString: v.config.DisableVersionString,
Exported: v.config.Exported,
InPackage: v.config.InPackage,
KeepTree: v.config.KeepTree,
Note: v.config.Note,
PackageName: v.config.PackageName,
PackageNamePrefix: v.config.PackageNamePrefix,
StructName: v.config.StructName,
UnrollVariadic: v.config.UnrollVariadic,
OmitEmptyRolledVariadic: v.config.OmitEmptyRolledVariadic,
WithExpecter: v.config.WithExpecter,
ReplaceType: v.config.ReplaceType,
}

gen := NewGenerator(ctx, generatorConfig, iface, "")
Expand Down