Skip to content

Commit

Permalink
Refactor mock name generation
Browse files Browse the repository at this point in the history
  • Loading branch information
grongor committed Apr 20, 2022
1 parent 4af1288 commit 749b2d6
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 25 deletions.
2 changes: 1 addition & 1 deletion mocks/pkg/fixtures/RequesterVariadicOneArgument.go

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

45 changes: 21 additions & 24 deletions pkg/generator.go
Expand Up @@ -16,6 +16,7 @@ import (
"strings"
"text/template"
"unicode"
"unicode/utf8"

"github.com/rs/zerolog"
"github.com/vektra/mockery/v2/pkg/config"
Expand Down Expand Up @@ -195,15 +196,22 @@ func (g *Generator) getLocalizedPath(ctx context.Context, path string) string {
return toReturn
}

func upperFirstOnly(s string) string {
first := true
return strings.Map(func(r rune) rune {
if first {
first = false
return unicode.ToUpper(r)
}
return r
}, s)
func (g *Generator) maybeMakeNameExported(name string, export bool) string {
if export && !ast.IsExported(name) {
return g.makeNameExported(name)
}

return name
}

func (g *Generator) makeNameExported(name string) string {
r, n := utf8.DecodeRuneInString(name)

if unicode.IsUpper(r) {
return name
}

return string(unicode.ToUpper(r)) + name[n:]
}

func (g *Generator) mockName() string {
Expand All @@ -216,13 +224,10 @@ func (g *Generator) mockName() string {
return "Mock" + g.iface.Name
}

return "mock" + upperFirstOnly(g.iface.Name)
}
if g.Exported || ast.IsExported(g.iface.Name) {
return upperFirstOnly(g.iface.Name)
return "mock" + g.makeNameExported(g.iface.Name)
}

return g.iface.Name
return g.maybeMakeNameExported(g.iface.Name, g.Exported)
}

func (g *Generator) expecterName() string {
Expand Down Expand Up @@ -715,18 +720,10 @@ func %[1]s(t testing.TB) *%[2]s {
}
`

funcFirstLetter := "N"
mockName := g.mockName()
constructorName := g.maybeMakeNameExported("new"+g.makeNameExported(mockName), ast.IsExported(mockName))

for _, firstLetter := range mockName {
if unicode.IsLower(firstLetter) {
funcFirstLetter = "n"
}

break
}

g.printf(constructor, funcFirstLetter+"ew"+upperFirstOnly(mockName), mockName)
g.printf(constructor, constructorName, mockName)
}

// generateCalled returns the Mock.Called invocation string and, if necessary, prints the
Expand Down

0 comments on commit 749b2d6

Please sign in to comment.