-
Notifications
You must be signed in to change notification settings - Fork 41
Open
Description
Example code:
//doc:summary reports that you create mocks in an old-fashioned way
//doc:before mockReader := &iomocks.Reader{}
//doc:after mockReader := iomocks.NewReader(t)
func mockConstructor(m dsl.Matcher) {
m.Import("github.com/stretchr/testify/mock")
m.Match(
`$x := &$y{}`,
`$x := $y{}`,
`$x = &$y{}`,
`$x = $y{}`,
).
Where(
m["x"].Type.Underlying().Is(`struct{$*_; mock.Mock; $*_}`) ||
m["x"].Filter(embedsMock),
).
Report("Use the mock constructor instead of struct initialization")
}
func embedsMock(ctx *dsl.VarFilterContext) bool {
// copy from here - https://github.com/quasilyte/go-ruleguard/blob/7968289708448cdc8ea2fa21d0db203a75d93994/analyzer/testdata/src/quasigo/rules.go#L11-L31
typ := ctx.Type.Underlying()
asPointer := types.AsPointer(typ)
if asPointer != nil {
typ = asPointer.Elem().Underlying()
}
asStruct := types.AsStruct(typ)
if asStruct == nil {
return false
}
mutexType := ctx.GetType(`github.com/stretchr/testify/mock.Mock`)
i := 0
for i < asStruct.NumFields() {
field := asStruct.Field(i)
if field.Embedded() && types.Identical(field.Type(), mutexType) {
return true
}
i++
}
return false
}Before using this rule: ~7m
After this rule: ~14m
Are there any way to improve it?
Metadata
Metadata
Assignees
Labels
No labels