Skip to content

Commit d0d706b

Browse files
authored
Add flag to enable mock reset methods (#181)
The optional with-resets flag adds methods to reset method calls. Calls can be reset individually or all at once with these.
1 parent a464ccc commit d0d706b

File tree

9 files changed

+299
-28
lines changed

9 files changed

+299
-28
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@ moq [flags] source-dir interface [interface2 [interface3 [...]]]
4343
-skip-ensure
4444
suppress mock implementation check, avoid import cycle if mocks
4545
generated outside of the tested package
46+
-with-resets
47+
generate functions to facilitate resetting calls made to a mock
4648
4749
Specifying an alias for the mock is also supported with the format 'interface:alias'
4850
@@ -120,6 +122,7 @@ The mocked structure implements the interface, where each method calls the assoc
120122
* Name arguments in the interface for a better experience
121123
* Use closured variables inside your test function to capture details about the calls to the methods
122124
* Use `.MethodCalls()` to track the calls
125+
* Use `.ResetCalls()` to reset calls within an invidual mock's context
123126
* Use `go:generate` to invoke the `moq` command
124127
* If Moq fails with a `go/format` error, it indicates the generated code was not valid.
125128
You can run the same command with `-fmt noop` to print the generated source code without attempting to format it.

internal/template/template.go

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,8 +182,27 @@ func (mock *{{$mock.MockName}}
182182
mock.lock{{.Name}}.RUnlock()
183183
return calls
184184
}
185+
{{- if $.WithResets}}
186+
// Reset{{.Name}}Calls reset all the calls that were made to {{.Name}}.
187+
func (mock *{{$mock.MockName}}) Reset{{.Name}}Calls() {
188+
mock.lock{{.Name}}.Lock()
189+
mock.calls.{{.Name}} = nil
190+
mock.lock{{.Name}}.Unlock()
191+
}
192+
{{end}}
193+
{{end -}}
194+
{{- if $.WithResets}}
195+
// ResetCalls reset all the calls that were made to all mocked methods.
196+
func (mock *{{$mock.MockName}}) ResetCalls() {
197+
{{- range .Methods}}
198+
mock.lock{{.Name}}.Lock()
199+
mock.calls.{{.Name}} = nil
200+
mock.lock{{.Name}}.Unlock()
201+
{{end -}}
202+
}
203+
{{end -}}
185204
{{end -}}
186-
{{end -}}`
205+
`
187206

188207
// This list comes from the golint codebase. Golint will complain about any of
189208
// these being mixed-case, like "Id" instead of "ID".

internal/template/template_data.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ type Data struct {
1616
Mocks []MockData
1717
StubImpl bool
1818
SkipEnsure bool
19+
WithResets bool
1920
}
2021

2122
// MocksSomeMethod returns true of any one of the Mocks has at least 1

main.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ type userFlags struct {
2222
formatter string
2323
stubImpl bool
2424
skipEnsure bool
25+
withResets bool
2526
remove bool
2627
args []string
2728
}
@@ -37,6 +38,8 @@ func main() {
3738
flag.BoolVar(&flags.skipEnsure, "skip-ensure", false,
3839
"suppress mock implementation check, avoid import cycle if mocks generated outside of the tested package")
3940
flag.BoolVar(&flags.remove, "rm", false, "first remove output file, if it exists")
41+
flag.BoolVar(&flags.withResets, "with-resets", false,
42+
"generate functions to facilitate resetting calls made to a mock")
4043

4144
flag.Usage = func() {
4245
fmt.Println(`moq [flags] source-dir interface [interface2 [interface3 [...]]]`)
@@ -86,6 +89,7 @@ func run(flags userFlags) error {
8689
Formatter: flags.formatter,
8790
StubImpl: flags.stubImpl,
8891
SkipEnsure: flags.skipEnsure,
92+
WithResets: flags.withResets,
8993
})
9094
if err != nil {
9195
return err
@@ -100,10 +104,10 @@ func run(flags userFlags) error {
100104
}
101105

102106
// create the file
103-
err = os.MkdirAll(filepath.Dir(flags.outFile), 0750)
107+
err = os.MkdirAll(filepath.Dir(flags.outFile), 0o750)
104108
if err != nil {
105109
return err
106110
}
107111

108-
return ioutil.WriteFile(flags.outFile, buf.Bytes(), 0600)
112+
return ioutil.WriteFile(flags.outFile, buf.Bytes(), 0o600)
109113
}

pkg/moq/moq.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ type Config struct {
2828
Formatter string
2929
StubImpl bool
3030
SkipEnsure bool
31+
WithResets bool
3132
}
3233

3334
// New makes a new Mocker for the specified package directory.
@@ -81,6 +82,7 @@ func (m *Mocker) Mock(w io.Writer, namePairs ...string) error {
8182
Mocks: mocks,
8283
StubImpl: m.cfg.StubImpl,
8384
SkipEnsure: m.cfg.SkipEnsure,
85+
WithResets: m.cfg.WithResets,
8486
}
8587

8688
if data.MocksSomeMethod() {

pkg/moq/moq_test.go

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ func TestMoq(t *testing.T) {
2929
}
3030
s := buf.String()
3131
// assertions of things that should be mentioned
32-
var strs = []string{
32+
strs := []string{
3333
"package example",
3434
"type PersonStoreMock struct",
3535
"CreateFunc func(ctx context.Context, person *Person, confirm bool) error",
@@ -62,7 +62,7 @@ func TestMoqWithStaticCheck(t *testing.T) {
6262
}
6363
s := buf.String()
6464
// assertions of things that should be mentioned
65-
var strs = []string{
65+
strs := []string{
6666
"package example",
6767
"var _ PersonStore = &PersonStoreMock{}",
6868
"type PersonStoreMock struct",
@@ -96,7 +96,7 @@ func TestMoqWithAlias(t *testing.T) {
9696
}
9797
s := buf.String()
9898
// assertions of things that should be mentioned
99-
var strs = []string{
99+
strs := []string{
100100
"package example",
101101
"type AnotherPersonStoreMock struct",
102102
"CreateFunc func(ctx context.Context, person *Person, confirm bool) error",
@@ -129,7 +129,7 @@ func TestMoqExplicitPackage(t *testing.T) {
129129
}
130130
s := buf.String()
131131
// assertions of things that should be mentioned
132-
var strs = []string{
132+
strs := []string{
133133
"package different",
134134
"type PersonStoreMock struct",
135135
"CreateFunc func(ctx context.Context, person *example.Person, confirm bool) error",
@@ -156,7 +156,7 @@ func TestMoqExplicitPackageWithStaticCheck(t *testing.T) {
156156
}
157157
s := buf.String()
158158
// assertions of things that should be mentioned
159-
var strs = []string{
159+
strs := []string{
160160
"package different",
161161
"var _ example.PersonStore = &PersonStoreMock{}",
162162
"type PersonStoreMock struct",
@@ -184,7 +184,7 @@ func TestMoqSkipEnsure(t *testing.T) {
184184
}
185185
s := buf.String()
186186
// assertions of things that should be mentioned
187-
var strs = []string{
187+
strs := []string{
188188
"package different",
189189
"type PersonStoreMock struct",
190190
"CreateFunc func(ctx context.Context, person *example.Person, confirm bool) error",
@@ -233,7 +233,7 @@ func TestVariadicArguments(t *testing.T) {
233233
}
234234
s := buf.String()
235235
// assertions of things that should be mentioned
236-
var strs = []string{
236+
strs := []string{
237237
"package variadic",
238238
"type GreeterMock struct",
239239
"GreetFunc func(ctx context.Context, names ...string) string",
@@ -261,7 +261,7 @@ func TestNothingToReturn(t *testing.T) {
261261
t.Errorf("should not have return for items that have no return arguments")
262262
}
263263
// assertions of things that should be mentioned
264-
var strs = []string{
264+
strs := []string{
265265
"mock.ClearCacheFunc(id)",
266266
}
267267
for _, str := range strs {
@@ -282,7 +282,7 @@ func TestImports(t *testing.T) {
282282
t.Errorf("m.Mock: %s", err)
283283
}
284284
s := buf.String()
285-
var strs = []string{
285+
strs := []string{
286286
` "sync"`,
287287
` "github.com/matryer/moq/pkg/moq/testpackages/imports/one"`,
288288
}
@@ -395,6 +395,12 @@ func TestMockGolden(t *testing.T) {
395395
interfaces: []string{"Transient"},
396396
goldenFile: filepath.Join("testpackages/transientimport", "transient_moq.golden.go"),
397397
},
398+
{
399+
name: "WithResets",
400+
cfg: Config{SrcDir: "testpackages/withresets", WithResets: true},
401+
interfaces: []string{"ResetStore"},
402+
goldenFile: filepath.Join("testpackages/withresets", "withresets_moq.golden.go"),
403+
},
398404
}
399405
for _, tc := range cases {
400406
t.Run(tc.name, func(t *testing.T) {
@@ -449,10 +455,10 @@ func matchGoldenFile(goldenFile string, actual []byte) error {
449455
// To update golden files, run the following:
450456
// go test -v -run '^<Test-Name>$' github.com/matryer/moq/pkg/moq -update
451457
if *update {
452-
if err := os.MkdirAll(filepath.Dir(goldenFile), 0750); err != nil {
458+
if err := os.MkdirAll(filepath.Dir(goldenFile), 0o750); err != nil {
453459
return fmt.Errorf("create dir: %s", err)
454460
}
455-
if err := ioutil.WriteFile(goldenFile, actual, 0600); err != nil {
461+
if err := ioutil.WriteFile(goldenFile, actual, 0o600); err != nil {
456462
return fmt.Errorf("write: %s", err)
457463
}
458464

@@ -495,7 +501,7 @@ func TestVendoredPackages(t *testing.T) {
495501
}
496502
s := buf.String()
497503
// assertions of things that should be mentioned
498-
var strs = []string{
504+
strs := []string{
499505
`"github.com/sudo-suhas/moq-test-pkgs/somerepo"`,
500506
}
501507
for _, str := range strs {
@@ -520,7 +526,7 @@ func TestVendoredInterface(t *testing.T) {
520526
}
521527
s := buf.String()
522528
// assertions of things that should be mentioned
523-
var strs = []string{
529+
strs := []string{
524530
`"github.com/sudo-suhas/moq-test-pkgs/somerepo"`,
525531
}
526532
for _, str := range strs {
@@ -546,7 +552,7 @@ func TestVendoredBuildConstraints(t *testing.T) {
546552
}
547553
s := buf.String()
548554
// assertions of things that should be mentioned
549-
var strs = []string{
555+
strs := []string{
550556
`"github.com/sudo-suhas/moq-test-pkgs/buildconstraints"`,
551557
}
552558
for _, str := range strs {

pkg/moq/testpackages/dotimport/service_moq_test.go

Lines changed: 12 additions & 11 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package withresets
2+
3+
import "context"
4+
5+
// Reset is a reset.
6+
type Reset struct {
7+
ID string
8+
Name string
9+
Company string
10+
Website string
11+
}
12+
13+
// ResetStore stores resets.
14+
type ResetStore interface {
15+
Get(ctx context.Context, id string) (*Reset, error)
16+
Create(ctx context.Context, person *Reset, confirm bool) error
17+
ClearCache(id string)
18+
}

0 commit comments

Comments
 (0)