Skip to content

Commit

Permalink
Merge branch 'master' into add-constructor-for-mocks
Browse files Browse the repository at this point in the history
  • Loading branch information
LandonTClipp committed Mar 30, 2022
2 parents 01a0f21 + b11695e commit cddc758
Show file tree
Hide file tree
Showing 15 changed files with 1,424 additions and 202 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/testing.yml
Expand Up @@ -12,7 +12,7 @@ jobs:
strategy:
matrix:
os: [ macos-latest, ubuntu-latest]
go_vers: [1.16, 1.17]
go_vers: [1.16, 1.17, 1.18]
steps:
- uses: actions/checkout@v2
with:
Expand Down
33 changes: 29 additions & 4 deletions README.md
Expand Up @@ -16,13 +16,14 @@ Table of Contents
* [Github Release](#github-release)
* [Docker](#docker)
* [Homebrew](#homebrew)
* [go get](#go-get)
* [go install](#go-install)
- [Examples](#examples)
+ [Simplest case](#simplest-case)
+ [Next level case](#next-level-case)
- [Return Value Provider Functions](#return-value-provider-functions)
+ [Requirements](#requirements)
+ [Notes](#notes)
- [Expecter Interfaces](#expecter-interfaces)
- [Extended Flag Descriptions](#extended-flag-descriptions)
- [Mocking interfaces in `main`](#mocking-interfaces-in-main)
- [Configuration](#configuration)
Expand Down Expand Up @@ -51,11 +52,11 @@ Install through [brew](https://brew.sh/)
brew install mockery
brew upgrade mockery

### go get
### go install

Alternatively, you can use the go get method:
Alternatively, you can use the go install method:

go get github.com/vektra/mockery/v2/.../
go install github.com/vektra/mockery/v2@latest

Examples
--------
Expand Down Expand Up @@ -256,6 +257,30 @@ This approach should be used judiciously, as return values should generally
not depend on arguments in mocks; however, this approach can be helpful for
situations like passthroughs or other test-only calculations.

Expecter Interfaces
--------------------

New in [v2.10.0](https://github.com/vektra/mockery/pull/396).

Mockery now supports an "expecter" interface which allows your tests to use type-safe methods to generate call expectations. When enabled through the `with-expecter: True` mockery configuration, you can enter into the expecter interface by simply calling `.EXPECT()` on your mock object.

For example, given an interface such as
```go
type Requester interface {
Get(path string) (string, error)
}
```

You can use the type-safe expecter interface as such:
```go
requesterMock := Requester{}
requesterMock.EXPECT().Get("some path").Return("result", nil)
requesterMock.EXPECT().
Get(mock.Anything).
Run(func(path string) { fmt.Println(path, "was called") }).
// Can still use return functions by getting the embedded mock.Call
Call.Return(func(path string) string { return "result for " + path }, nil)
```

Extended Flag Descriptions
--------------------------
Expand Down
71 changes: 40 additions & 31 deletions cmd/mockery.go
Expand Up @@ -26,7 +26,14 @@ import (

var (
cfgFile = ""
rootCmd = &cobra.Command{
)

func init() {
cobra.OnInitialize(initConfig)
}

func NewRootCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "mockery",
Short: "Generate mock objects for your Golang interfaces",
RunE: func(cmd *cobra.Command, args []string) error {
Expand All @@ -38,34 +45,8 @@ var (
return r.Run()
},
}
)

type stackTracer interface {
StackTrace() errors.StackTrace
}

func printStackTrace(e error) {
fmt.Printf("%v\n", e)
if err, ok := e.(stackTracer); ok {
for _, f := range err.StackTrace() {
fmt.Printf("%+s:%d\n", f, f)
}
}

}

// Execute executes the cobra CLI workflow
func Execute() {
if err := rootCmd.Execute(); err != nil {
//printStackTrace(err)
os.Exit(1)
}
}

func init() {
cobra.OnInitialize(initConfig)

pFlags := rootCmd.PersistentFlags()
pFlags := cmd.PersistentFlags()
pFlags.StringVar(&cfgFile, "config", "", "config file to use")
pFlags.String("name", "", "name or matching regular expression of interface to generate mock for")
pFlags.Bool("print", false, "print the generated mock to stdout")
Expand Down Expand Up @@ -93,14 +74,45 @@ func init() {
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("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")

viper.BindPFlags(pFlags)

cmd.AddCommand(NewShowConfigCmd())
return cmd
}

type stackTracer interface {
StackTrace() errors.StackTrace
}

func printStackTrace(e error) {
fmt.Printf("%v\n", e)
if err, ok := e.(stackTracer); ok {
for _, f := range err.StackTrace() {
fmt.Printf("%+s:%d\n", f, f)
}
}

}

// Execute executes the cobra CLI workflow
func Execute() {
if err := NewRootCmd().Execute(); err != nil {
//printStackTrace(err)
os.Exit(1)
}
}

func initConfig() {
viper.SetEnvPrefix("mockery")
viper.AutomaticEnv()

if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else if viper.IsSet("config") {
viper.SetConfigFile(viper.GetString("config"))
} else {
// Find home directory.
home, err := homedir.Dir()
Expand All @@ -114,9 +126,6 @@ func initConfig() {
viper.SetConfigName(".mockery")
}

viper.SetEnvPrefix("mockery")
viper.AutomaticEnv()

// Note we purposely ignore the error. Don't care if we can't find a config file.
if err := viper.ReadInConfig(); err == nil {
fmt.Fprintf(os.Stderr, "Using config file: %s\n", viper.ConfigFileUsed())
Expand Down
11 changes: 11 additions & 0 deletions cmd/mockery_test.go
@@ -1 +1,12 @@
package cmd

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestNewRootCmd(t *testing.T) {
cmd := NewRootCmd()
assert.Equal(t, "mockery", cmd.Name())
}
43 changes: 20 additions & 23 deletions cmd/showconfig.go
Expand Up @@ -10,27 +10,24 @@ import (
"gopkg.in/yaml.v2"
)

// showconfigCmd represents the showconfig command
var showconfigCmd = &cobra.Command{
Use: "showconfig",
Short: "Show the merged config",
Long: `Print out a yaml representation of the merged config.
This initializes viper and prints out the merged configuration between
config files, environment variables, and CLI flags.`,
RunE: func(cmd *cobra.Command, args []string) error {
config := &config.Config{}
if err := viper.UnmarshalExact(config); err != nil {
return errors.Wrapf(err, "failed to unmarshal config")
}
out, err := yaml.Marshal(config)
if err != nil {
return errors.Wrapf(err, "Failed to marsrhal yaml")
}
fmt.Printf("%s", string(out))
return nil
},
}

func init() {
rootCmd.AddCommand(showconfigCmd)
func NewShowConfigCmd() *cobra.Command {
return &cobra.Command{
Use: "showconfig",
Short: "Show the merged config",
Long: `Print out a yaml representation of the merged config.
This initializes viper and prints out the merged configuration between
config files, environment variables, and CLI flags.`,
RunE: func(cmd *cobra.Command, args []string) error {
config := &config.Config{}
if err := viper.UnmarshalExact(config); err != nil {
return errors.Wrapf(err, "failed to unmarshal config")
}
out, err := yaml.Marshal(config)
if err != nil {
return errors.Wrapf(err, "Failed to marsrhal yaml")
}
fmt.Printf("%s", string(out))
return nil
},
}
}
12 changes: 12 additions & 0 deletions cmd/showconfig_test.go
@@ -0,0 +1,12 @@
package cmd

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestNewShowConfigCmd(t *testing.T) {
cmd := NewShowConfigCmd()
assert.Equal(t, "showconfig", cmd.Name())
}
20 changes: 12 additions & 8 deletions go.mod
Expand Up @@ -4,12 +4,16 @@ go 1.16

require (
github.com/mitchellh/go-homedir v1.1.0
github.com/pkg/errors v0.8.1
github.com/rs/zerolog v1.18.0
github.com/spf13/cobra v1.0.0
github.com/spf13/viper v1.7.0
github.com/stretchr/testify v1.3.0
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550
golang.org/x/tools v0.0.0-20200323144430-8dcfad9e016e
gopkg.in/yaml.v2 v2.2.4
github.com/pkg/errors v0.9.1
github.com/rs/zerolog v1.26.1
github.com/spf13/afero v1.8.0 // indirect
github.com/spf13/cobra v1.3.0
github.com/spf13/viper v1.10.1
github.com/stretchr/testify v1.7.0
golang.org/x/crypto v0.0.0-20220112180741-5e0467b6c7ce
golang.org/x/sys v0.0.0-20220114195835-da31bd327af9 // indirect
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 // indirect
golang.org/x/tools v0.1.8
gopkg.in/ini.v1 v1.66.3 // indirect
gopkg.in/yaml.v2 v2.4.0
)

0 comments on commit cddc758

Please sign in to comment.