Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: vektra/mockery
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: v2.9.4
Choose a base ref
...
head repository: vektra/mockery
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: v2.22.1
Choose a head ref

Commits on Sep 20, 2021

  1. Add mock generation with expecter

    Gevrai Jodoin-Tremblay committed Sep 20, 2021
    Copy the full SHA
    95b8d4d View commit details

Commits on Jan 25, 2022

  1. Upgrade all dependencies

    This fixes #425, #416, #423
    LandonTClipp committed Jan 25, 2022

    Unverified

    This commit is not signed, but one or more authors requires that any commit attributed to them is signed.
    Copy the full SHA
    21d2728 View commit details
  2. Adding more dependencies

    LandonTClipp committed Jan 25, 2022

    Unverified

    This commit is not signed, but one or more authors requires that any commit attributed to them is signed.
    Copy the full SHA
    ff24d35 View commit details
  3. Merge pull request #427 from vektra/update_deps

    Upgrade all dependencies
    LandonTClipp authored Jan 25, 2022

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    5626edf View commit details
  4. Update README.md

    LandonTClipp authored Jan 25, 2022

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    b702d89 View commit details
  5. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    e5889c6 View commit details
  6. Merge pull request #396 from Gevrai/gejo-expecter-support

    Add mock generation with expecter
    LandonTClipp authored Jan 25, 2022

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    66d6564 View commit details
  7. Update README.md

    LandonTClipp authored Jan 25, 2022

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    fa2d82d View commit details
  8. Update README.md

    LandonTClipp authored Jan 25, 2022

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    4fc5912 View commit details
  9. Update README.md

    LandonTClipp authored Jan 25, 2022

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    5f5570d View commit details
  10. Update README.md

    LandonTClipp authored Jan 25, 2022

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    adda07f View commit details

Commits on Mar 17, 2022

  1. Load packages with dependencies for Go 1.18

    Without the additional `NeedDeps` mockery fails with:
    "Unexpected package creation during export data loading"
    
    Refs #434
    emmanuel099 committed Mar 17, 2022

    Verified

    This commit was signed with the committer’s verified signature.
    emmanuel099 Emmanuel Pescosta
    Copy the full SHA
    4e181be View commit details

Commits on Mar 28, 2022

  1. Test with Go 1.18

    emmanuel099 committed Mar 28, 2022

    Verified

    This commit was signed with the committer’s verified signature.
    emmanuel099 Emmanuel Pescosta
    Copy the full SHA
    e0e183b View commit details
  2. Fix config.GetSemverInfo() for Go 1.18

    In Go 1.18 debug.ReadBuildInfo() may successfully return a build
    info where the main version is empty. Return the default SemVer
    in this case.
    emmanuel099 committed Mar 28, 2022

    Verified

    This commit was signed with the committer’s verified signature.
    emmanuel099 Emmanuel Pescosta
    Copy the full SHA
    fa0080c View commit details

Commits on Mar 30, 2022

  1. Merge pull request #435 from emmanuel099/master

    Load packages with dependencies for Go 1.18
    LandonTClipp authored Mar 30, 2022

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    232f954 View commit details
  2. Merge pull request #436 from emmanuel099/test_with_3.18

    Test with Go 1.18 and fix GetSemverInfo()
    LandonTClipp authored Mar 30, 2022

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    b11695e View commit details

Commits on Mar 31, 2022

  1. fix: allow configuring flags with "-" as Env var

    For example MOCKERY_DISABLE_VERSION_STRING
    Claus Strasburger committed Mar 31, 2022
    Copy the full SHA
    ed87cf6 View commit details
  2. Copy the full SHA
    a0d98e4 View commit details
  3. Copy the full SHA
    09de88a View commit details
  4. Copy the full SHA
    9489caf View commit details
  5. Fix panic in tests

    actualLines may be longer than expectedLines -> index out of range
    grongor committed Mar 31, 2022
    Copy the full SHA
    b4d8eef View commit details

Commits on Apr 1, 2022

  1. fix: golang build version

    Evgenii Orlov committed Apr 1, 2022
    Copy the full SHA
    408740d View commit details
  2. Merge pull request #443 from OrlovEvgeny/fix-build-go-version

    fix: golang build version 1.18 (issue #434)
    LandonTClipp authored Apr 1, 2022

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    8384e25 View commit details

Commits on Apr 4, 2022

  1. test: add test for env var configurations

    Claus Strasburger committed Apr 4, 2022
    Copy the full SHA
    53114cf View commit details
  2. fix: unused config field Tags

    Claus Strasburger committed Apr 4, 2022
    Copy the full SHA
    17abd96 View commit details

Commits on Apr 5, 2022

  1. Remove packages.NeedDeps

    This was introduced #435 but it wasn't the correct solution.
    LandonTClipp committed Apr 5, 2022

    Unverified

    This commit is not signed, but one or more authors requires that any commit attributed to them is signed.
    Copy the full SHA
    ba1f213 View commit details
  2. Add/update mocks

    LandonTClipp committed Apr 5, 2022

    Unverified

    This commit is not signed, but one or more authors requires that any commit attributed to them is signed.
    Copy the full SHA
    ee25bcf View commit details
  3. Update go.sum

    LandonTClipp committed Apr 5, 2022

    Unverified

    This commit is not signed, but one or more authors requires that any commit attributed to them is signed.
    Copy the full SHA
    ed38b20 View commit details
  4. Merge pull request #444 from vektra/remove_need_deps

    Remove packages.NeedDeps
    LandonTClipp authored Apr 5, 2022

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    4703d1a View commit details
  5. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    a328a65 View commit details
  6. Fix import

    LandonTClipp committed Apr 5, 2022

    Unverified

    This commit is not signed, but one or more authors requires that any commit attributed to them is signed.
    Copy the full SHA
    eddf049 View commit details
  7. Merge pull request #441 from cfstras/fix/support-more-env-keys

    fix: allow configuring flags with "-" as environment variables
    LandonTClipp authored Apr 5, 2022

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    c943e69 View commit details

Commits on Apr 8, 2022

  1. Add PR/issue templates

    LandonTClipp committed Apr 8, 2022

    Unverified

    This commit is not signed, but one or more authors requires that any commit attributed to them is signed.
    Copy the full SHA
    df6e689 View commit details
  2. Add golang-1.18 note

    LandonTClipp committed Apr 8, 2022

    Unverified

    This commit is not signed, but one or more authors requires that any commit attributed to them is signed.
    Copy the full SHA
    e8bf201 View commit details

Commits on Apr 11, 2022

  1. Copy the full SHA
    aa25af0 View commit details

Commits on Apr 13, 2022

  1. Merge pull request #445 from bigbluedisco/fix/bump-golang-org-x-tools

    fix: bump golang.org/x/tools to v0.1.10 to fix some go 1.18 issues
    LandonTClipp authored Apr 13, 2022

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    54589be View commit details

Commits on Apr 18, 2022

  1. Merge pull request #406 from grongor/add-constructor-for-mocks

    Add constructor for mocks
    LandonTClipp authored Apr 18, 2022

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    32dd223 View commit details
  2. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    43880c1 View commit details
  3. Merge pull request #448 from vektra/add-code-of-conduct-1

    Create CODE_OF_CONDUCT.md
    LandonTClipp authored Apr 18, 2022

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    3ceee82 View commit details
  4. Unverified

    This commit is not signed, but one or more authors requires that any commit attributed to them is signed.
    Copy the full SHA
    f564b10 View commit details
  5. Merge pull request #449 from LandonTClipp/update_mocks

    Update mocks with latest mockery version
    LandonTClipp authored Apr 18, 2022

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    4af1288 View commit details

Commits on Apr 19, 2022

  1. Copy the full SHA
    ec87efa View commit details
  2. Merge pull request #450 from grongor/update-readme

    Update readme (new constructors, mention expecter, small improvements)
    LandonTClipp authored Apr 19, 2022

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    aad3571 View commit details
  3. Add --inpackage-suffix option

    This allows users to choose whether they prefer mock_name.go or
    name_mock.go for their filenames.
    grongor committed Apr 19, 2022
    Copy the full SHA
    c98782f View commit details

Commits on Apr 20, 2022

  1. Add testing.TB to mock.Mock in constructors

    Gevrai Jodoin-Tremblay committed Apr 20, 2022
    Copy the full SHA
    81502be View commit details
  2. update docstring and readme

    Gevrai Jodoin-Tremblay committed Apr 20, 2022
    Copy the full SHA
    c7e7f4f View commit details
  3. Refactor mock name generation

    grongor committed Apr 20, 2022
    Copy the full SHA
    749b2d6 View commit details

Commits on Apr 21, 2022

  1. fix readme formatting

    Gevrai Jodoin-Tremblay committed Apr 21, 2022
    Copy the full SHA
    bf007ff View commit details
  2. Merge pull request #455 from Gevrai/add-testingT-mock-constructor

    Add testing.TB to mock.Mock in constructors
    LandonTClipp authored Apr 21, 2022

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    8174e46 View commit details
  3. Merge pull request #452 from grongor/refactor-first-letter-helper

    Refactor mock name generation
    LandonTClipp authored Apr 21, 2022

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    58a7f18 View commit details
Showing with 6,701 additions and 2,215 deletions.
  1. +48 −0 .github/ISSUE_TEMPLATE.md
  2. +44 −0 .github/PULL_REQUEST_TEMPLATE.md
  3. +10 −1 .github/workflows/release.yml
  4. +22 −0 .github/workflows/static.yml
  5. +1 −1 .github/workflows/testing.yml
  6. +3 −0 .gitignore
  7. +34 −7 .goreleaser.yml
  8. +22 −1 .mockery.yaml
  9. +128 −0 CODE_OF_CONDUCT.md
  10. +1 −1 Dockerfile
  11. +9 −10 Makefile
  12. +8 −323 README.md
  13. +257 −143 cmd/mockery.go
  14. +256 −0 cmd/mockery_test.go
  15. +10 −3 cmd/showconfig.go
  16. +11 −0 codecov.yml
  17. +104 −0 docs/changelog.md
  18. +49 −0 docs/configuration.md
  19. +121 −0 docs/examples.md
  20. +273 −0 docs/features.md
  21. +86 −0 docs/index.md
  22. +39 −0 docs/installation.md
  23. +85 −0 docs/notes.md
  24. +4 −0 docs/requirements.txt
  25. +47 −0 docs/running.md
  26. +5 −0 docs/stylesheets/extra.css
  27. +37 −9 go.mod
  28. +364 −181 go.sum
  29. +75 −0 mkdocs.yml
  30. +115 −0 mocks/github.com/vektra/mockery/v2/pkg/TypesPackage.go
  31. +271 −0 mocks/github.com/vektra/mockery/v2/pkg/fixtures/Expecter.go
  32. +81 −0 mocks/github.com/vektra/mockery/v2/pkg/fixtures/RequesterArgSameAsNamedImport.go
  33. +151 −0 mocks/github.com/vektra/mockery/v2/pkg/fixtures/RequesterReturnElided.go
  34. +16 −1 mocks/{ → github.com/vektra/mockery/v2}/pkg/fixtures/RequesterVariadic.go
  35. +16 −1 mocks/{ → github.com/vektra/mockery/v2}/pkg/fixtures/RequesterVariadicOneArgument.go
  36. +0 −34 mocks/pkg/fixtures/A.go
  37. +0 −58 mocks/pkg/fixtures/AsyncProducer.go
  38. +0 −24 mocks/pkg/fixtures/Blank.go
  39. +0 −47 mocks/pkg/fixtures/ConsulLock.go
  40. +0 −46 mocks/pkg/fixtures/Example.go
  41. +0 −45 mocks/pkg/fixtures/Fooer.go
  42. +0 −24 mocks/pkg/fixtures/FuncArgsCollision.go
  43. +0 −51 mocks/pkg/fixtures/HasConflictingNestedImports.go
  44. +0 −50 mocks/pkg/fixtures/ImportsSameAsPackage.go
  45. +0 −38 mocks/pkg/fixtures/KeyManager.go
  46. +0 −24 mocks/pkg/fixtures/MapFunc.go
  47. +0 −21 mocks/pkg/fixtures/MapToInterface.go
  48. +0 −31 mocks/pkg/fixtures/MyReader.go
  49. +0 −31 mocks/pkg/fixtures/Requester.go
  50. +0 −24 mocks/pkg/fixtures/Requester2.go
  51. +0 −24 mocks/pkg/fixtures/Requester3.go
  52. +0 −15 mocks/pkg/fixtures/Requester4.go
  53. +0 −30 mocks/pkg/fixtures/RequesterArgSameAsImport.go
  54. +0 −30 mocks/pkg/fixtures/RequesterArgSameAsNamedImport.go
  55. +0 −15 mocks/pkg/fixtures/RequesterArgSameAsPkg.go
  56. +0 −33 mocks/pkg/fixtures/RequesterArray.go
  57. +0 −24 mocks/pkg/fixtures/RequesterElided.go
  58. +0 −30 mocks/pkg/fixtures/RequesterIface.go
  59. +0 −35 mocks/pkg/fixtures/RequesterNS.go
  60. +0 −33 mocks/pkg/fixtures/RequesterPtr.go
  61. +0 −45 mocks/pkg/fixtures/RequesterReturnElided.go
  62. +0 −33 mocks/pkg/fixtures/RequesterSlice.go
  63. +0 −35 mocks/pkg/fixtures/SendFunc.go
  64. +0 −15 mocks/pkg/fixtures/Sibling.go
  65. +0 −18 mocks/pkg/fixtures/UsesOtherPkgIface.go
  66. +0 −27 mocks/pkg/fixtures/buildtag/comment/IfaceWithBuildTagInComment.go
  67. +0 −27 mocks/pkg/fixtures/buildtag/filename/IfaceWithBuildTagInFilename.go
  68. +0 −41 mocks/pkg/fixtures/example_project/Root.go
  69. +0 −50 mocks/pkg/fixtures/example_project/foo/Foo.go
  70. +0 −15 mocks/pkg/fixtures/requester_unexported.go
  71. +2 −2 pkg/compat_test.go
  72. +331 −43 pkg/config/config.go
  73. +650 −0 pkg/config/config_test.go
  74. +1 −0 pkg/fixtures/buildtag/comment/custom2_iface.go
  75. +1 −0 pkg/fixtures/buildtag/comment/custom_iface.go
  76. +1 −0 pkg/fixtures/buildtag/comment/darwin_iface.go
  77. +1 −0 pkg/fixtures/buildtag/comment/freebsd_iface.go
  78. +1 −0 pkg/fixtures/buildtag/comment/linux_iface.go
  79. +1 −0 pkg/fixtures/buildtag/comment/windows_iface.go
  80. +9 −0 pkg/fixtures/constraints/constraints.go
  81. +5 −0 pkg/fixtures/example_project/bar/foo/client.go
  82. +9 −0 pkg/fixtures/example_project/context/context.go
  83. +7 −0 pkg/fixtures/example_project/foo/pkg_name_same_as_import.go
  84. +69 −0 pkg/fixtures/example_project/mock_Stringer_test.go
  85. +5 −0 pkg/fixtures/example_project/string.go
  86. +17 −0 pkg/fixtures/example_project/string_test.go
  87. +9 −0 pkg/fixtures/expecter.go
  88. +38 −0 pkg/fixtures/generic.go
  89. 0 pkg/fixtures/{MapToInterface.go → map_to_interface.go}
  90. +196 −0 pkg/fixtures/mocks/expecter_test.go
  91. +1 −0 pkg/fixtures/requester_ret_elided.go
  92. +11 −0 pkg/fixtures/struct_with_tag.go
  93. +7 −0 pkg/fixtures/unsafe.go
  94. +506 −194 pkg/generator.go
  95. +1,517 −54 pkg/generator_test.go
  96. +56 −0 pkg/logging/logging.go
  97. +0 −1 pkg/mockery.go
  98. +8 −1 pkg/mockery_test.go
  99. +164 −1 pkg/outputter.go
  100. +86 −0 pkg/outputter_test.go
  101. +121 −76 pkg/parse.go
  102. +8 −0 pkg/parse_test.go
  103. +57 −34 pkg/walker.go
  104. +3 −4 pkg/walker_test.go
48 changes: 48 additions & 0 deletions .github/ISSUE_TEMPLATE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
PLEASE READ
-------------

DO NOT submit tickets without _first_ using the latest version of Golang, clearing your local golang package cache, and re-building mockery using the _latest_ Golang version and the _latest_ version of mockery. Please provide evidence this has been done in your issue. Failure to provide this evidence will likely result in your issue being closed.

Description
-------------

[Description of the bug or feature]

Mockery Version
--------

[version of mockery being used]

Golang Version
--------------

[version of golang being used]

```
NOTE: Please upgrade to the latest golang version before submitting tickets!
```

Installation Method
-------------------

- [ ] Binary Distribution
- [ ] Docker
- [ ] brew
- [ ] go install
- [ ] Other: [specify]

Steps to Reproduce
------------------

1. [First Step]
2. [Second Step]
3. [etc]

### Expected Behavior

[what you expect to happen]

### Actual Behavior

[what actually happened]

44 changes: 44 additions & 0 deletions .github/PULL_REQUEST_TEMPLATE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
Description
-------------

Please include a summary of the changes and the related issue. Please also include relevant motivation and context.

- Fixes # (issue)

## Type of change

- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
- [ ] This change requires a documentation update

Version of Golang used when building/testing:
---------------------------------------------

- [ ] 1.11
- [ ] 1.12
- [ ] 1.13
- [ ] 1.14
- [ ] 1.15
- [ ] 1.16
- [ ] 1.17
- [ ] 1.18
- [ ] 1.19
- [ ] 1.20

How Has This Been Tested?
---------------------------

Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration

Checklist
-----------

- [ ] My code follows the style guidelines of this project
- [ ] I have performed a self-review of my code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings
- [ ] I have added tests that prove my fix is effective or that my feature works
- [ ] New and existing unit tests pass locally with my changes

11 changes: 10 additions & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -8,6 +8,9 @@ on:
jobs:
release:
runs-on: ubuntu-latest
env:
DOCKER_CLI_EXPERIMENTAL: "enabled"

steps:
- uses: actions/checkout@v2
with:
@@ -16,7 +19,13 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.16
go-version: '1.20'

- name: Set up QEMU
uses: docker/setup-qemu-action@v2

- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2

- name: Login to DockerHub
uses: docker/login-action@v1
22 changes: 22 additions & 0 deletions .github/workflows/static.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
name: static pages
on:
push:
branches:
- master
permissions:
contents: write
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-python@v4
with:
python-version: 3.x
- uses: actions/cache@v2
with:
key: ${{ github.ref }}
path: .cache
- run: sudo apt-get install -y libcairo2-dev libfreetype6-dev libffi-dev libjpeg-dev libpng-dev libz-dev
- run: pip install -r docs/requirements.txt
- run: mkdocs gh-deploy --force
2 changes: 1 addition & 1 deletion .github/workflows/testing.yml
Original file line number Diff line number Diff line change
@@ -12,7 +12,7 @@ jobs:
strategy:
matrix:
os: [ macos-latest, ubuntu-latest]
go_vers: [1.16, 1.17]
go_vers: ['1.20']
steps:
- uses: actions/checkout@v2
with:
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
mockery.prof
dist
.idea
docs/ve
ve
.cache
41 changes: 34 additions & 7 deletions .goreleaser.yml
Original file line number Diff line number Diff line change
@@ -7,7 +7,7 @@ builds:
- main: ./main.go
binary: mockery
ldflags:
- -s -w -X github.com/vektra/mockery/v2/pkg/config.SemVer=v{{.Version}}
- -s -w -X github.com/vektra/mockery/v2/pkg/logging.SemVer=v{{.Version}}
env:
- CGO_ENABLED=0
goos:
@@ -34,20 +34,47 @@ snapshot:
changelog:
sort: asc
dockers:
- goos: linux
- image_templates: ["vektra/mockery:{{ .Tag }}-amd64"]
goarch: amd64
image_templates:
- 'vektra/mockery:{{ .Tag }}'
- 'vektra/mockery:v{{ .Major }}'
- 'vektra/mockery:v{{ .Major }}.{{ .Minor }}'
- 'vektra/mockery:latest'
dockerfile: Dockerfile
use: buildx
build_flag_templates:
- "--pull"
- "--label=org.opencontainers.image.created={{.Date}}"
- "--label=org.opencontainers.image.name={{.ProjectName}}"
- "--label=org.opencontainers.image.revision={{.FullCommit}}"
- "--label=org.opencontainers.image.version={{.Version}}"
- "--label=org.opencontainers.image.source={{.GitURL}}"
- "--platform=linux/amd64"
- image_templates: ["vektra/mockery:{{ .Tag }}-arm64"]
goarch: arm64
dockerfile: Dockerfile
use: buildx
build_flag_templates:
- "--pull"
- "--label=org.opencontainers.image.created={{.Date}}"
- "--label=org.opencontainers.image.name={{.ProjectName}}"
- "--label=org.opencontainers.image.revision={{.FullCommit}}"
- "--label=org.opencontainers.image.version={{.Version}}"
- "--label=org.opencontainers.image.source={{.GitURL}}"
- "--platform=linux/arm64"
docker_manifests:
- name_template: vektra/mockery:{{ .Tag }}
image_templates:
- vektra/mockery:{{ .Tag }}-amd64
- vektra/mockery:{{ .Tag }}-arm64
- name_template: vektra/mockery:v{{ .Major }}
image_templates:
- vektra/mockery:{{ .Tag }}-amd64
- vektra/mockery:{{ .Tag }}-arm64
- name_template: vektra/mockery:v{{ .Major }}.{{ .Minor }}
image_templates:
- vektra/mockery:{{ .Tag }}-amd64
- vektra/mockery:{{ .Tag }}-arm64
- name_template: vektra/mockery:latest
image_templates:
- vektra/mockery:{{ .Tag }}-amd64
- vektra/mockery:{{ .Tag }}-arm64
brews:
- homepage: https://github.com/vektra/mockery
description: "A mock code autogenerator for Go"
23 changes: 22 additions & 1 deletion .mockery.yaml
Original file line number Diff line number Diff line change
@@ -1,3 +1,24 @@
quiet: False
all: True
keeptree: True
disable-version-string: True
with-expecter: True
filename: "{{.MockName}}.go"
packages:
github.com/vektra/mockery/v2/pkg:
interfaces:
TypesPackage:
github.com/vektra/mockery/v2/pkg/fixtures:
interfaces:
RequesterArgSameAsNamedImport:
RequesterVariadic:
config:
with-expecter: False
configs:
- structname: RequesterVariadicOneArgument
unroll-variadic: False
- structname: RequesterVariadic
Expecter:
RequesterReturnElided:



128 changes: 128 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
# Contributor Covenant Code of Conduct

## Our Pledge

We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.

We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.

## Our Standards

Examples of behavior that contributes to a positive environment for our
community include:

* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community

Examples of unacceptable behavior include:

* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting

## Enforcement Responsibilities

Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.

Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.

## Scope

This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
landonclipp@gmail.com.
All complaints will be reviewed and investigated promptly and fairly.

All community leaders are obligated to respect the privacy and security of the
reporter of any incident.

## Enforcement Guidelines

Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:

### 1. Correction

**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.

**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.

### 2. Warning

**Community Impact**: A violation through a single incident or series
of actions.

**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.

### 3. Temporary Ban

**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.

**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.

### 4. Permanent Ban

**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.

**Consequence**: A permanent ban from any sort of public interaction within
the community.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.

Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).

[homepage]: https://www.contributor-covenant.org

For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM golang:1.16-alpine as builder
FROM golang:1.20-alpine as builder

COPY mockery /usr/local/bin

19 changes: 9 additions & 10 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,24 +1,19 @@
SHELL=bash

.PHONY: all
all: clean fmt mocks test install docker integration

.PHONY: clean
clean:
rm -rf mocks
all: fmt mocks test install docker integration

.PHONY: fmt
fmt:
go fmt ./...

.PHONY: test
test: mocks
test:
go test ./...

mocks: $(shell find . -type f -name '*.go' -not -name '*_test.go')
go run . --dir pkg/fixtures --output mocks/pkg/fixtures
go run . --all=false --print --dir pkg/fixtures --name RequesterVariadic --structname RequesterVariadicOneArgument --unroll-variadic=False > mocks/pkg/fixtures/RequesterVariadicOneArgument.go
@touch mocks
.PHONY: mocks
mocks:
go run .

.PHONY: install
install:
@@ -31,3 +26,7 @@ docker:
.PHONY: integration
integration: docker install
./hack/run-e2e.sh

.PHONY: clean
clean:
rm -rf mocks
331 changes: 8 additions & 323 deletions README.md
Original file line number Diff line number Diff line change
@@ -3,349 +3,34 @@ mockery
=======
[![Release](https://github.com/vektra/mockery/actions/workflows/release.yml/badge.svg)](https://github.com/vektra/mockery/actions/workflows/release.yml) [![go.dev reference](https://img.shields.io/badge/go.dev-reference-007d9c?logo=go&logoColor=white&style=flat-square)](https://pkg.go.dev/github.com/vektra/mockery/v2?tab=overview) ![GitHub go.mod Go version](https://img.shields.io/github/go-mod/go-version/vektra/mockery) ![GitHub release (latest SemVer)](https://img.shields.io/github/v/release/vektra/mockery) [![Go Report Card](https://goreportcard.com/badge/github.com/vektra/mockery)](https://goreportcard.com/report/github.com/vektra/mockery) [![codecov](https://codecov.io/gh/vektra/mockery/branch/master/graph/badge.svg)](https://codecov.io/gh/vektra/mockery)

mockery provides the ability to easily generate mocks for Golang interfaces using the [stretchr/testify/mock](https://pkg.go.dev/github.com/stretchr/testify/mock?tab=doc) package. It removes the boilerplate coding required to use mocks.



mockery provides the ability to easily generate mocks for golang interfaces using the [stretchr/testify/mock](https://pkg.go.dev/github.com/stretchr/testify/mock?tab=doc) package. It removes
the boilerplate coding required to use mocks.

Table of Contents
-----------------

- [Installation](#installation)
* [Github Release](#github-release)
* [Docker](#docker)
* [Homebrew](#homebrew)
* [go get](#go-get)
- [Examples](#examples)
+ [Simplest case](#simplest-case)
+ [Next level case](#next-level-case)
- [Return Value Provider Functions](#return-value-provider-functions)
+ [Requirements](#requirements)
+ [Notes](#notes)
- [Extended Flag Descriptions](#extended-flag-descriptions)
- [Mocking interfaces in `main`](#mocking-interfaces-in-main)
- [Configuration](#configuration)
* [Example](#example)
- [Semantic Versioning](#semantic-versioning)
- [Stargazers](#stargazers)


Installation
------------

### Github Release

Visit the [releases page](https://github.com/vektra/mockery/releases) to download one of the pre-built binaries for your platform.

### Docker

Use the [Docker image](https://hub.docker.com/r/vektra/mockery)

docker pull vektra/mockery

### Homebrew

Install through [brew](https://brew.sh/)

brew install mockery
brew upgrade mockery

### go get

Alternatively, you can use the go get method:

go get github.com/vektra/mockery/v2/.../

Examples
--------

![](https://raw.githubusercontent.com/vektra/mockery/master/docs/Peek%202020-06-28%2000-08.gif)

#### Simplest case

Given this is in `string.go`

```go
package test

type Stringer interface {
String() string
}
```

Run: `mockery --name=Stringer` and the following will be output to `mocks/Stringer.go`:

```go
package mocks

import "github.com/stretchr/testify/mock"

type Stringer struct {
mock.Mock
}

func (m *Stringer) String() string {
ret := m.Called()

var r0 string
if rf, ok := ret.Get(0).(func() string); ok {
r0 = rf()
} else {
r0 = ret.Get(0).(string)
}

return r0
}
```

#### Function type case

Given this is in `send.go`

```go
package test

type SendFunc func(data string) (int, error)
```

Run: `mockery --name=SendFunc` and the following will be output to `mocks/SendFunc.go`:

```go
package mocks

import "github.com/stretchr/testify/mock"

type SendFunc struct {
mock.Mock
}

func (_m *SendFunc) Execute(data string) (int, error) {
ret := _m.Called(data)

var r0 int
if rf, ok := ret.Get(0).(func(string) int); ok {
r0 = rf(data)
} else {
r0 = ret.Get(0).(int)
}

var r1 error
if rf, ok := ret.Get(1).(func(string) error); ok {
r1 = rf(data)
} else {
r1 = ret.Error(1)
}

return r0, r1
}
```

#### Next level case

See [github.com/jaytaylor/mockery-example](https://github.com/jaytaylor/mockery-example)
for the fully runnable version of the outline below.

```go
package main

import (
"fmt"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/jaytaylor/mockery-example/mocks"
"github.com/stretchr/testify/mock"
)

func main() {
mockS3 := &mocks.S3API{}

mockResultFn := func(input *s3.ListObjectsInput) *s3.ListObjectsOutput {
output := &s3.ListObjectsOutput{}
output.SetCommonPrefixes([]*s3.CommonPrefix{
&s3.CommonPrefix{
Prefix: aws.String("2017-01-01"),
},
})
return output
}

// NB: .Return(...) must return the same signature as the method being mocked.
// In this case it's (*s3.ListObjectsOutput, error).
mockS3.On("ListObjects", mock.MatchedBy(func(input *s3.ListObjectsInput) bool {
return input.Delimiter != nil && *input.Delimiter == "/" && input.Prefix == nil
})).Return(mockResultFn, nil)

listingInput := &s3.ListObjectsInput{
Bucket: aws.String("foo"),
Delimiter: aws.String("/"),
}
listingOutput, err := mockS3.ListObjects(listingInput)
if err != nil {
panic(err)
}

for _, x := range listingOutput.CommonPrefixes {
fmt.Printf("common prefix: %+v\n", *x)
}
}
```


Return Value Provider Functions
--------------------------------

If your tests need access to the arguments to calculate the return values,
set the return value to a function that takes the method's arguments as its own
arguments and returns the return value. For example, given this interface:

```go
package test

type Proxy interface {
passthrough(ctx context.Context, s string) string
}
```

The argument can be passed through as the return value:

```go
import . "github.com/stretchr/testify/mock"

Mock.On("passthrough", mock.AnythingOfType("context.Context"), mock.AnythingOfType("string")).Return(func(ctx context.Context, s string) string {
return s
})
```

#### Requirements

`Return` must be passed the same argument count and types as expected by the interface. Then, for each of the return values of the mocked function, `Return` needs a function which takes the same arguments as the mocked function, and returns one of the return values. For example, if the return argument signature of `passthrough` in the above example was instead `(string, error)` in the interface, `Return` would also need a second function argument to define the error value:

```go
type Proxy interface {
passthrough(ctx context.Context, s string) (string, error)
}
```

```go
Mock.On("passthrough", mock.AnythingOfType("context.Context"), mock.AnythingOfType("string")).Return(
func(ctx context.Context, s string) string {
return s
},
func(ctx context.Context, s string) error {
return nil
})
```

Note that the following is incorrect (you can't return all the return values with one function):
```go
Mock.On("passthrough", mock.AnythingOfType("context.Context"), mock.AnythingOfType("string")).Return(
func(ctx context.Context, s string) (string, error) {
return s, nil
})
```

If any return argument is missing, `github.com/stretchr/testify/mock.Arguments.Get` will emit a panic.

For example, `panic: assert: arguments: Cannot call Get(0) because there are 0 argument(s). [recovered]` indicates that `Return` was not provided any arguments but (at least one) was expected based on the interface. `Get(1)` would indicate that the `Return` call is missing a second argument, and so on.

#### Notes

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.


Extended Flag Descriptions
--------------------------

The following descriptions provide additional elaboration on a few common parameters.

| flag name | description |
|---|---|
| `--name` | The `--name` option takes either the name or matching regular expression of interface to generate mock(s) for. |
| `--all` | It's common for a big package to have a lot of interfaces, so mockery provides `--all`. This option will tell mockery to scan all files under the directory named by `--dir` ("." by default) and generates mocks for any interfaces it finds. This option implies `--recursive=true`. |
| `--recursive` | Use the `--recursive` option to search subdirectories for the interface(s). This option is only compatible with `--name`. The `--all` option implies `--recursive=true`. |
| `--output` | mockery always generates files with the package `mocks` to keep things clean and simple. You can control which mocks directory is used by using `--output`, which defaults to `./mocks`. |
| `--inpackage` and `--keeptree` | For some complex repositories, there could be multiple interfaces with the same name but in different packages. In that case, `--inpackage` allows generating the mocked interfaces directly in the package that it mocks. In the case you don't want to generate the mocks into the package but want to keep a similar structure, use the option `--keeptree`. |
| `--filename` | Use the `--filename` and `--structname` to override the default generated file and struct name. These options are only compatible with non-regular expressions in `--name`, where only one mock is generated. |
| `--case` | mockery generates files using the casing of the original interface name. This can be modified by specifying `--case underscore` to format the generated file name using underscore casing. |
| `--print` | Use `mockery --print` to have the resulting code printed out instead of written to disk. |
| `--exported` | Use `mockery --exported` to generate public mocks for private interfaces. |

Mocking interfaces in `main`
----------------------------

When your interfaces are in the main package you should supply the `--inpackage` flag.
This will generate mocks in the same package as the target code avoiding import issues.

Configuration
Documentation
--------------

mockery uses [spf13/viper](https://github.com/spf13/viper) under the hood for its configuration parsing. It is bound to three different configuration sources, in order of decreasing precedence:

1. Command line
2. Environment variables
3. Configuration file

### Example

$ export MOCKERY_STRUCTNAME=config_from_env
$ echo $MOCKERY_STRUCTNAME
config_from_env
$ grep structname .mockery.yaml
structname: config_from_file
$ ./mockery showconfig --structname config_from_cli | grep structname
Using config file: /home/ltclipp/git/vektra/mockery/.mockery.yaml
structname: config_from_cli
$ ./mockery showconfig | grep structname
Using config file: /home/ltclipp/git/vektra/mockery/.mockery.yaml
structname: config_from_env
$ unset MOCKERY_STRUCTNAME
$ ./mockery showconfig | grep structname
Using config file: /home/ltclipp/git/vektra/mockery/.mockery.yaml
structname: config_from_file

By default it searches the current working directory for a file named `.mockery.[extension]` where [extension] is any of the [recognized extensions](https://pkg.go.dev/github.com/spf13/viper@v1.7.0?tab=doc#pkg-variables).

Semantic Versioning
-------------------

The versioning in this project applies only to the behavior of the mockery binary itself. This project explicitly does not promise a stable internal API, but rather a stable executable. The versioning applies to the following:

1. CLI arguments.
2. Parsing of Golang code. New features in the Golang language will be supported in a backwards-compatible manner, except during major version bumps.
3. Behavior of mock objects. Mock objects can be considered to be part of the public API.
4. Behavior of mockery given a set of arguments.

What the version does _not_ track:
1. The interfaces, objects, methods etc. in the vektra/mockery package.
2. Compatibility of `go get`-ing mockery with new or old versions of Golang.
Documentation is found at out [Github Pages site](https://vektra.github.io/mockery/).

Development Efforts
-------------------

> v2 is in a soft change freeze due to the complexity of the software and the fact that functionality addition generally requires messing with logic that has been thoroughly tested, but is sensitive to change.
### v1

v1 is the original version of the software, and is no longer supported.

### v2

`mockery` is currently in v2, which iterates on v1 and includes mostly cosmetic and configuration improvements.
`mockery` is currently in v2, which originally included cosmetic and configuration improvements over v1, but also implements a number of quality-of-life additions.

### v3

[v3](https://github.com/vektra/mockery/projects/3) will include a ground-up overhaul of the entire codebase and will completely change how mockery works internally and externally. The highlights of the project are:
- Moving towards a package-based model instead of a file-based model. `mockery` currently iterates over every file in a project and calls `package.Load` on each one, which is time consuming. Moving towards a model where the entire package is loaded at once will dramtically reduce runtime, and will simplify logic. Additionally, supporting only a single mode of operation (package mode) will greatly increase the intuitiveness of the software.
- Moving towards a package-based model instead of a file-based model. `mockery` currently iterates over every file in a project and calls `package.Load` on each one, which is time-consuming. Moving towards a model where the entire package is loaded at once will dramatically reduce runtime, and will simplify logic. Additionally, supporting only a single mode of operation (package mode) will greatly increase the intuitiveness of the software.
- Configuration-driven generation. `v3` will be entirely driven by configuration, meaning:
* You specify the packages you want mocked, instead of relying on it auto-discovering your package. Auto-discovery in theory sounds great, but in practice it leads to a great amount of complexity for very little benefit.
* Package- or interface-specific overrides can be given that change mock generation settings on a granular level. This will allow your mocks to be generated in a heterogenous manner, and will be made explicit by yaml configuration.
* Package- or interface-specific overrides can be given that change mock generation settings on a granular level. This will allow your mocks to be generated in a heterogeneous manner, and will be made explicit by YAML configuration.
- Proper error reporting. Errors across the board will be done in accordance with modern Golang practices
- Variables in generated mocks will be given meaningful names.
- Variables in generated mocks will be given meaningful names.



Stargazers
400 changes: 257 additions & 143 deletions cmd/mockery.go

Large diffs are not rendered by default.

256 changes: 256 additions & 0 deletions cmd/mockery_test.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,268 @@
package cmd

import (
"fmt"
"os"
"strings"
"testing"

"github.com/chigopher/pathlib"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestNewRootCmd(t *testing.T) {
cmd := NewRootCmd()
assert.Equal(t, "mockery", cmd.Name())
}

func Test_initConfig(t *testing.T) {
tests := []struct {
name string
base_path string
configPath string
}{
{
name: "test config at base directory",
base_path: "1/2/3/4",
configPath: "1/2/3/4/.mockery.yaml",
},
{
name: "test config at upper directory",
base_path: "1/2/3/4",
configPath: "1/.mockery.yaml",
},
{
name: "no config file found",
base_path: "1/2/3/4",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tmpDir := pathlib.NewPath(t.TempDir())
baseDir := tmpDir.Join(strings.Split(tt.base_path, "/")...)
require.NoError(t, baseDir.MkdirAll())

configPath := pathlib.NewPath("")
if tt.configPath != "" {
configPath = tmpDir.Join(strings.Split(tt.configPath, "/")...)
configPath.WriteFile([]byte("all: True"))
}

viperObj := viper.New()

initConfig(baseDir, viperObj, nil)

assert.Equal(t, configPath.String(), viperObj.ConfigFileUsed())
})
}
}

type Writer interface {
Foo()
}

func TestRunLegacyGenerationNonExistent(t *testing.T) {
tmpDir := t.TempDir()
config := `
name: Foo
`
configPath := pathlib.NewPath(tmpDir).Join("config.yaml")
require.NoError(t, configPath.WriteFile([]byte(config)))

v := viper.New()
initConfig(nil, v, configPath)
app, err := GetRootAppFromViper(v)
require.NoError(t, err)
assert.Error(t, app.Run())
}

func newViper(tmpDir string) *viper.Viper {
v := viper.New()
v.Set("dir", tmpDir)
return v
}

func TestRunPackagesGenerationGlobalDefaults(t *testing.T) {
tmpDir := t.TempDir()
configFmt := `
log-level: info
filename: "hello_{{.InterfaceName}}.go"
packages:
io:
config:
outpkg: mock_io
dir: %s
interfaces:
Writer:`
config := fmt.Sprintf(configFmt, tmpDir)
configPath := pathlib.NewPath(tmpDir).Join("config.yaml")
require.NoError(t, configPath.WriteFile([]byte(config)))
mockPath := pathlib.NewPath(tmpDir).Join("hello_Writer.go")

v := newViper(tmpDir)
initConfig(nil, v, configPath)
app, err := GetRootAppFromViper(v)
require.NoError(t, err)
require.NoError(t, app.Run())

exists, err := mockPath.Exists()
require.NoError(t, err)
assert.True(t, exists)
}

func TestRunPackagesGeneration(t *testing.T) {
tmpDir := t.TempDir()
configFmt := `
with-expecter: true
log-level: info
packages:
io:
config:
outpkg: mock_io
dir: %s
interfaces:
Writer:`
config := fmt.Sprintf(configFmt, tmpDir)
configPath := pathlib.NewPath(tmpDir).Join("config.yaml")
require.NoError(t, configPath.WriteFile([]byte(config)))
mockPath := pathlib.NewPath(tmpDir).Join("mock_Writer.go")

v := newViper(tmpDir)
initConfig(nil, v, configPath)
app, err := GetRootAppFromViper(v)
require.NoError(t, err)
require.NoError(t, app.Run())

exists, err := mockPath.Exists()
require.NoError(t, err)
assert.True(t, exists)
}

func TestIssue565(t *testing.T) {
// An issue was posed in https://github.com/vektra/mockery/issues/565
// where mockery wasn't entering the `packages` config section. I think
// this is some kind of bug with viper. We should instead parse the yaml
// directly instead of relying on the struct unmarshalling from viper,
// which is kind of buggy.
tmpDir := t.TempDir()
config := `
with-expecter: True
inpackage: True
testonly: True
log-level: debug
packages:
github.com/testuser/testpackage/internal/foopkg:
interfaces:
FooInterface:
`
//config := fmt.Sprintf(configFmt, tmpDir)
configPath := pathlib.NewPath(tmpDir).Join("config.yaml")
require.NoError(t, configPath.WriteFile([]byte(config)))

goModPath := pathlib.NewPath(tmpDir).Join("go.mod")
err := goModPath.WriteFile([]byte(`
module github.com/testuser/testpackage
go 1.20`))
require.NoError(t, err)

interfacePath := pathlib.NewPath(tmpDir).Join("internal", "foopkg", "interface.go")
require.NoError(t, interfacePath.Parent().MkdirAll())
interfacePath.WriteFile([]byte(`
package foopkg
type FooInterface interface {
Foo()
Bar()
}`))

mockPath := pathlib.NewPath(tmpDir).Join(
"mocks",
"github.com",
"testuser",
"testpackage",
"internal",
"foopkg",
"mock_FooInterface.go")

os.Chdir(tmpDir)

v := viper.New()
initConfig(nil, v, configPath)
app, err := GetRootAppFromViper(v)
require.NoError(t, err)
require.NoError(t, app.Run())

exists, err := mockPath.Exists()
require.NoError(t, err)
assert.True(t, exists)
}

func TestRunLegacyNoConfig(t *testing.T) {
tmpDir := pathlib.NewPath(t.TempDir())

mockPath := tmpDir.Join("Foo.go")
codePath := tmpDir.Join("foo.go")
codePath.WriteFile([]byte(`
package test
type Foo interface {
Get(str string) string
}`))

v := viper.New()
v.Set("log-level", "debug")
v.Set("outpkg", "foobar")
v.Set("name", "Foo")
v.Set("output", tmpDir.String())
v.Set("disable-config-search", true)
os.Chdir(tmpDir.String())

initConfig(nil, v, nil)
app, err := GetRootAppFromViper(v)
require.NoError(t, err)
require.NoError(t, app.Run())

exists, err := mockPath.Exists()
require.NoError(t, err)
assert.True(t, exists)
}

func TestRunLegacyNoConfigDirSet(t *testing.T) {
tmpDir := pathlib.NewPath(t.TempDir())

subdir := tmpDir.Join("subdir")
require.NoError(t, subdir.MkdirAll())

mockPath := subdir.Join("Foo.go")
codePath := subdir.Join("foo.go")

err := codePath.WriteFile([]byte(`
package test
type Foo interface {
Get(str string) string
}`))
require.NoError(t, err, "failed to write go file")

v := viper.New()
v.Set("log-level", "debug")
v.Set("outpkg", "foobar")
v.Set("name", "Foo")
v.Set("output", subdir.String())
v.Set("disable-config-search", true)
v.Set("dir", subdir.String())
v.Set("recursive", true)
os.Chdir(tmpDir.String())

initConfig(nil, v, nil)
app, err := GetRootAppFromViper(v)
require.NoError(t, err)
require.NoError(t, app.Run())

exists, err := mockPath.Exists()
require.NoError(t, err)
assert.True(t, exists)
}
13 changes: 10 additions & 3 deletions cmd/showconfig.go
Original file line number Diff line number Diff line change
@@ -5,8 +5,8 @@ import (

"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/vektra/mockery/v2/pkg/config"
"github.com/vektra/mockery/v2/pkg/logging"
"gopkg.in/yaml.v2"
)

@@ -18,14 +18,21 @@ func NewShowConfigCmd() *cobra.Command {
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 {
if err := viperCfg.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")
return errors.Wrapf(err, "Failed to marshal yaml")
}
log, err := logging.GetLogger(config.LogLevel)
if err != nil {
panic(err)
}
log.Info().Msgf("Using config: %s", config.Config)

fmt.Printf("%s", string(out))
return nil
},
11 changes: 11 additions & 0 deletions codecov.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
coverage:
precision: 5
round: down
range: "65...100"
status:
patch:
default:
target: 65%
threshold: 5%
base: auto

104 changes: 104 additions & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
Changelog
=========

This changelog describes major feature additions. Please view the `releases` page for more details on commits and minor changes.

### :octicons-tag-24: [`v2.21.0`](https://github.com/vektra/mockery/releases/tag/v2.21.0): `#!yaml packages` configuration

In this version we release the `#!yaml packages` configuration section. This new parameter allows defining specific packages to generate mocks for, while also giving fine-grained control over which interfaces are mocked, where they are located, and how they are configured. Details are provided [here](/mockery/features/#packages-configuration).

Community input is desired before we consider deprecations of dynamic walking (via `#!yaml all: True`): https://github.com/vektra/mockery/discussions/549

### :octicons-tag-24: [`v2.20.0`](https://github.com/vektra/mockery/pull/538): Improved Return Value Functions

Return value functions that return an entire method's return value signature can now be provided.

```go
proxyMock := mocks.NewProxy(t)
proxyMock.On("passthrough", mock.AnythingOfType("context.Context"), mock.AnythingOfType("string")).
Return(
func(ctx context.Context, s string) (string, error) {
return s, nil
}
)
```

You may still use the old way where one function is provided for each return value:

```go
proxyMock := mocks.NewProxy(t)
proxyMock.On("passthrough", mock.AnythingOfType("context.Context"), mock.AnythingOfType("string")).
Return(
func(ctx context.Context, s string) string {
return s
},
func(ctx context.Context, s string) error {
return nil
},
)
```

### :octicons-tag-24: [`2.19.0`](https://github.com/vektra/mockery/releases/tag/v2.19.0): `inpackage-suffix` option

When `inpackage-suffix` is set to `True`, mock files are suffixed with `_mock` instead of being prefixed with `mock_` for InPackage mocks


### :octicons-tag-24: [`v2.16.0`](https://github.com/vektra/mockery/pull/527): Config Search Path

Mockery will iteratively search every directory from the current working directory up to the root path for a `.mockery.yaml` file, if one is not explicitly provided.

### :octicons-tag-24: [`v2.13.0`](https://github.com/vektra/mockery/pull/456): Generics support

Mocks are now capable of supporting Golang generics.

### :octicons-tag-24: [`v2.11.0`](https://github.com/vektra/mockery/pull/406): Mock constructors

Mockery v2.11 introduces constructors for all mocks. This makes instantiation and mock registration a bit easier and
less error-prone (you won't have to worry about forgetting the `AssertExpectations` method call anymore).

Before v2.11:
```go
factory := &mocks.Factory{}
factory.Test(t) // so that mock does not panic when a method is unexpected
defer factory.AssertExpectations(t)
```

After v2.11:
```go
factory := mocks.NewFactory(t)
```

The constructor sets up common functionalities automatically
- The `AssertExpectations` method is registered to be called at the end of the tests via `t.Cleanup()` method.
- The testing.TB interface is registered on the `mock.Mock` so that tests don't panic when a call on the mock is unexpected.

### :octicons-tag-24: [`v2.10.0`](https://github.com/vektra/mockery/pull/396): Expecter Structs

Mockery now supports an "expecter" struct, 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 := mocks.NewRequester(t)
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)
```

### :octicons-tag-24: [`v2.0.0`](https://github.com/vektra/mockery/releases/tag/v2.0.0): Major Update

This is the first major update of mockery. Version 2 brings a handful of improvements to mockery:

- Structured and pretty console logging
- CLI now switches over to sp13/cobra
- Use of viper configuration parsing. You can now use a .mockery.yaml config file in your repository
- Various CI fixes and improvements
49 changes: 49 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
Configuration
==============

mockery uses [spf13/viper](https://github.com/spf13/viper) under the hood for its configuration parsing. It is bound to three different configuration sources, in order of decreasing precedence:

1. Command line
2. Environment variables
3. Configuration file

If a parameter is named `with-expecter` and we want a value of `True`, then these are the formats for each source:

| source | value |
|--------|-------|
| command line | `--with-expecter=true` |
| Environment variable | `MOCKERY_WITH_EXPECTER=True` |
| yaml | `with-expecter: True` |

Recommended Basic Config
-------------------------

Copy the recommended basic configuration to a file called `.mockery.yaml` at the top-level of your repo:

```yaml title=".mockery.yaml"
inpackage: True
testonly: True
with-expecter: True
keeptree: False
```
mockery will search upwards from your current-working-directory up to the root path, so the same configuration should be able to follow you within your project.
Parameter Descriptions
-----------------------
| name | description |
|------|-------------|
| `name` | The `name` option takes either the name or matching regular expression of the interface to generate mock(s) for. |
| `all` | It's common for a big package to have a lot of interfaces, so mockery provides `all`. This option will tell mockery to scan all files under the directory named by `--dir` ("." by default) and generates mocks for any interfaces it finds. This option implies `recursive: True`. |
| `recursive` | Use the `recursive` option to search subdirectories for the interface(s). This option is only compatible with `name`. The `all` option implies `recursive: True`. |
| `output` | mockery always generates files with the package `mocks` to keep things clean and simple. You can control which mocks directory is used by using `output`, which defaults to `./mocks`. |
|`outpkg`| Use `outpkg` to specify the package name of the generated mocks.|
| `inpackage` and `keeptree` | For some complex repositories, there could be multiple interfaces with the same name but in different packages. In that case, `inpackage` allows generating the mocked interfaces directly in the package that it mocks. In the case you don't want to generate the mocks into the package but want to keep a similar structure, use the option `keeptree`. |
| `filename` | Use the `filename` and `structname` to override the default generated file and struct name. These options are only compatible with non-regular expressions in `name`, where only one mock is generated. |
| `case` | mockery generates files using the casing of the original interface name. This can be modified by specifying `case: underscore` to format the generated file name using underscore casing. |
| `print` | Use `print: True` to have the resulting code printed out instead of written to disk. |
| `exported` | Use `exported: True` to generate public mocks for private interfaces. |
| `with-expecter` | Use `with-expecter: True` to generate `EXPECT()` methods for your mocks. This is the preferred way to setup your mocks. |
| `testonly` | Prepend every mock file with `_test.go`. This is useful in cases where you are generating mocks `inpackage` but don't want the mocks to be visible to code outside of tests. |
| `inpackage-suffix` | When `inpackage-suffix` is set to `True`, mock files are suffixed with `_mock` instead of being prefixed with `mock_` for InPackage mocks |
121 changes: 121 additions & 0 deletions docs/examples.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
Examples
========

### Simple case

Given this interface:

```go title="string.go"
package example_project

//go:generate --name Stringer
type Stringer interface {
String() string
}
```

Run: `go generate` (using the recommended config) and the the file `mock_Stringer_test.go` will be generated. You can now use this mock to create assertions and expectations.

```go title="string_test.go"
package example_project

import (
"testing"

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

func Foo(s Stringer) string {
return s.String()
}

func TestString(t *testing.T) {
mockStringer := NewMockStringer(t)
mockStringer.EXPECT().String().Return("mockery")
assert.Equal(t, "mockery", Foo(mockStringer))
}
```

Note that in combination with using the mock's constructor and the `.EXPECT()` directives, your test will automatically fail if the expected call is not made.

### Function type case

Given this is in `send.go`

```go
package test

type SendFunc func(data string) (int, error)
```

Run: `mockery --name=SendFunc` and the following will be output:

```go title="mock_SendFunc_test.go"
package mocks

import (
"github.com/stretchr/testify/mock"

testing "testing"
)

type SendFunc struct {
mock.Mock
}

func (_m *SendFunc) Execute(data string) (int, error) {
ret := _m.Called(data)

var r0 int
if rf, ok := ret.Get(0).(func(string) int); ok {
r0 = rf(data)
} else {
r0 = ret.Get(0).(int)
}

var r1 error
if rf, ok := ret.Get(1).(func(string) error); ok {
r1 = rf(data)
} else {
r1 = ret.Error(1)
}

return r0, r1
}

// NewSendFunc creates a new instance of SendFunc. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
func NewSendFunc(t testing.TB) *SendFunc {
mock := &SendFunc{}
mock.Mock.Test(t)

t.Cleanup(func() { mock.AssertExpectations(t) })

return mock
}
```

### Return Value Provider Functions

If your tests need access to the arguments to calculate the return values,
set the return value to a function that takes the method's arguments as its own
arguments and returns the return value. For example, given this interface:

```go
package test

type Proxy interface {
passthrough(ctx context.Context, s string) string
}
```

The argument can be passed through as the return value:

```go
import . "github.com/stretchr/testify/mock"

proxyMock := mocks.NewProxy(t)
proxyMock.On("passthrough", mock.AnythingOfType("context.Context"), mock.AnythingOfType("string")).
Return(func(ctx context.Context, s string) string {
return s
})
```
273 changes: 273 additions & 0 deletions docs/features.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,273 @@
Features
========

`packages` configuration
------------------------
:octicons-tag-24: 2.21.0 · :material-test-tube: Alpha Feature

!!! danger
This feature is considered alpha. It is likely that bugs exist, and subfeatures may be added/subtracted/modified at any time. Use at your own risk. This warning will be updated as this feature matures.

Mockery has a configuration parameter called `packages`. This config represents a huge paradigm shift that is highly recommended for the large amount of flexibility it grants you.

In this config section, you define the packages and the intefaces you want mocks generated for. The packages can be any arbitrary package, either your own project or anything within the Go ecosystem. You may provide package-level or interface-level overrides to the default config you provide.

Usage of the `packages` config section is desirable for mutiple reasons:

1. Up to 5x increase in mock generation speed over the legacy method
2. Granular control over interface generation, location, and file names
3. Singular location for all config, instead of spread around by `//go:generate` statements
4. Clean, easy to understand.

### Examples

Here is an example configuration set:

```yaml
with-expecter: True
packages:
github.com/vektra/mockery/v2/pkg: # (1)!
interfaces:
TypesPackage:
RequesterVariadic:
config: # (2)!
with-expecter: False
configs:
- structname: RequesterVariadicOneArgument
unroll-variadic: False
- structname: RequesterVariadic
io:
config:
all: True # (3)!
interfaces:
Writer:
config:
with-expecter: False # (4)!
```
1. For this package, we provide no package-level config (which means we inherit the deafults at the top-level). Since our default of `all:` is `False`, mockery will only generate the interfaces we specify. We tell it which interface to generate by using the `interfaces` section and specifying an empty map, one for each interface.
2. There might be cases where you want multiple mocks generated from the same interface. To do this, you can define a default `config` section for the interface, and further `configs` (plural) section, one for each mock. You _must_ specify a `structname` for the mocks in this section to differentiate them.
3. This is telling mockery to generate _all_ interfaces in the `io` package.
4. We can provide interface-specifc overrides to the generation config.

### Templated variables

Included with this feature is the ability to use templated strings for various configuration options. This is useful to define where your mocks are placed and how to name them.

These are various strategies you may want to adopt:

#### Strategies

!!! info "Strategies"

=== "defaults"

```yaml
filename: "mock_{{.InterfaceName}}.go"
dir: "mocks/{{.PackagePath}}"
structname: "Mock{{.InterfaceName}}"
outpkg: "{{.PackageName}}"
```

If these variables aren't specified, the above values will be applied to the config options. This strategy places your mocks into a separate `mocks/` directory.

**Interface Description**

| name | value |
|------|-------|
| `InterfaceName` | `MyDatabase` |
| `PackagePath` | `github.com/user/project/pkgName` |
| `PackageName` | `pkgName` |

**Output**

The mock will be generated at:

```
mocks/github.com/user/project/pkgName/mock_MyDatabase.go
```

The mock file will look like:

```go
package pkgName
import mock "github.com/stretchr/testify/mock"
type MockMyDatabase struct {
mock.Mock
}
```
=== "adjacent to interface"

!!! failure

This strategy is not yet functional.

```yaml
filename: "mock_{{.InterfaceName}}.go"
dir: "{{.PackagePathRelative}}"
structname: "Mock{{.InterfaceName}}"
outpkg: "{{.PackageName}}"
```

Instead of the mocks being generated in a different folder, you may elect to generate the mocks alongside the original interface in your package. This may be the way most people define their configs, as it removes circular import issues that can happen with the default config.

For example, the mock might be generated along side the original source file like this:

```
./path/to/pkg/db.go
./path/to/pkg/mock_MyDatabase.go
```

**Interface Description**

| name | value |
|------|-------|
| `InterfaceName` | `MyDatabase` |
| `PackagePath` | `github.com/user/project/path/to/pkg`
| `PackagePathRelative` | `path/to/pkg` |
| `PackageName` | `pkgName` |
| `SourceFile` | `./path/to/pkg/db.go` |

**Output**

Mock file will be generated at:

```
./path/to/pkg/mock_MyDatabase.go
```

The mock file will look like:

```go
package pkgName
import mock "github.com/stretchr/testify/mock"
type MockMyDatabase struct {
mock.Mock
}
```




#### Template Variable Descriptions

The template variables available for your use are:

| name | description |
|------|-------------|
| InterfaceDir | The path of the original interface being mocked. This can be used as `#!yaml dir: "{{.InterfaceDir}}"` to place your mocks adjacent to the original interface. This should not be used for external interfaces. |
| InterfaceName | The name of the original interface being mocked |
| InterfaceNameCamel | Converts a string `interface_name` to `InterfaceName` |
| InterfaceNameLowerCamel | Converts `InterfaceName` to `interfaceName` |
| InterfaceNameSnake | Converts `InterfaceName` to `interface_name` |
| PackageName | The name of the package from the original interface |
| PackagePath | The fully qualified package path of the original interface |


!!! warning
Many of the config options when using `packages` have either changed meanings or are no longer used. It's recommended to delete all previous configuration you have as their meanings may have changed.

Mock Constructors
-----------------

:octicons-tag-24: 2.11.0

All mock objects have constructor functions. These constructors do basic test setup so that the expectations you set in the code are asserted before the test exist.

Previously something like this would need to be done:
```go
factory := &mocks.Factory{}
factory.Test(t) // so that mock does not panic when a method is unexpected
defer factory.AssertExpectations(t)
```

Instead, you may simply use the constructor:
```go
factory := mocks.NewFactory(t)
```

The constructor sets up common functionalities automatically
- The `AssertExpectations` method is registered to be called at the end of the tests via `t.Cleanup()` method.
- The testing.TB interface is registered on the `mock.Mock` so that tests don't panic when a call on the mock is unexpected.


Expecter Structs
----------------

:octicons-tag-24: 2.10.0 · `with-expecter: True`

Mockery now supports an "expecter" struct, 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 expecter interface as such:
```go
requesterMock := mocks.NewRequester(t)
requesterMock.EXPECT().Get("some path").Return("result", nil)
```

A `RunAndReturn` method is also available on the expecter struct that allows you to dynamically set a return value based on the input to the mock's call.

```go
requesterMock.EXPECT().
Get(mock.Anything).
RunAndReturn(func(path string) string {
fmt.Println(path, "was called")
return "result for " + path
})
```

!!! note

Note that the types of the arguments on the `EXPECT` methods are `interface{}`, not the actual type of your interface. The reason for this is that you may want to pass `mock.Any` as an argument, which means that the argument you pass may be an arbitrary type. The types are still provided in the expecter method docstrings.


Return Value Providers
----------------------

:octicons-tag-24: 2.20.0

Return Value Providers can be used one of two ways. You may either define a single function with the exact same signature (number and type of input and return parameters) and pass that as a single value to `Return`, or you may pass multiple values to `Return` (one for each return parameter of the mocked function.) If you are using the second form, for each of the return values of the mocked function, `Return` needs a function which takes the same arguments as the mocked function, and returns one of the return values. For example, if the return argument signature of `passthrough` in the above example was instead `(string, error)` in the interface, `Return` would also need a second function argument to define the error value:

```go
type Proxy interface {
passthrough(ctx context.Context, s string) (string, error)
}
```

First form:

```go
proxyMock := mocks.NewProxy(t)
proxyMock.On("passthrough", mock.AnythingOfType("context.Context"), mock.AnythingOfType("string")).
Return(
func(ctx context.Context, s string) (string, error) {
return s, nil
}
)
```


Second form:

```go
proxyMock := mocks.NewProxy(t)
proxyMock.On("passthrough", mock.AnythingOfType("context.Context"), mock.AnythingOfType("string")).
Return(
func(ctx context.Context, s string) string {
return s
},
func(ctx context.Context, s string) error {
return nil
},
)
```
86 changes: 86 additions & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
mockery
========

Mockery is a project that aims to make the generation of mock implementations of Golang interfaces. The mocks generated in this project are based off of the `github.com/stretchr/testify` suite of packages.

![](https://raw.githubusercontent.com/vektra/mockery/master/docs/Peek%202020-06-28%2000-08.gif)

Why mockery?
-------------

When you have an interface like this:

```golang title="db.go"
type DB interface {
Get(val string) string
}
```

and a function that takes this interface:

```golang title="db_getter.go"
func getFromDB(db DB) string {
return db.Get("ice cream")
}
```

You can test `getFromDB` by either instantiating a testing database, or you can simply create a mock implementation of `DB` using mockery. Mockery can autogenerate a mock implementation that allows us to define assertions on how the mock was used, what to return, and other useful tidbits. We can add a `//go:generate` directive above our interface:

```golang title="db.go"
//go:generate mockery --name DB
type DB interface {
Get(val string) string
}
```

```yaml title=".mockery.yaml"
inpackage: True # (1)!
with-expecter: True # (2)!
testonly: True # (3)!
```
1. Generate our mocks next to the original interface
2. Create [expecter methods](/mockery/features/#expecter-structs)
3. Append `_test.go` to the filename so the mock object is not packaged

```bash
$ go generate
05 Mar 23 21:49 CST INF Starting mockery dry-run=false version=v2.20.0
05 Mar 23 21:49 CST INF Using config: .mockery.yaml dry-run=false version=v2.20.0
05 Mar 23 21:49 CST INF Walking dry-run=false version=v2.20.0
05 Mar 23 21:49 CST INF Generating mock dry-run=false interface=DB qualified-name=github.com/vektra/mockery/v2/pkg/fixtures/example_project version=v2.20.0
```

We can then use the mock object in a test:

```go title="db_getter_test.go"
import (
"testing"
"github.com/stretchr/testify/assert"
)
func Test_getFromDB(t *testing.T) {
mockDB := NewMockDB(t)
mockDB.EXPECT().Get("ice cream").Return("chocolate").Once()
flavor := getFromDB(mockDB)
assert.Equal(t, "chocolate", flavor)
}
```

Why use mockery over gomock?
-----------------------------

1. mockery provides a much more user-friendly API and is less confusing to use
2. mockery utilizes `testify` which is a robust and highly feature-rich testing framework
3. mockery has rich configuration options that allow fine-grained control over how your mocks are generated
4. mockery's CLI is more robust, user-friendly, and provides many more options
5. mockery supports generics (this may no longer be an advantage if/when gomock supports generics)

Who uses mockery?
------------------

:simple-grafana: [grafana](https://github.com/grafana/grafana) · :simple-google: [Google Skia](https://github.com/google/skia) · [Hashicorp](https://github.com/search?q=org%3Ahashicorp%20mockery&type=code) · :simple-google: [Google Skyzkaller](https://github.com/google/syzkaller) · :fontawesome-brands-uber: [Uber Cadence](https://github.com/uber/cadence) · [Jaeger](https://github.com/jaegertracing/jaeger) · [Splunk](https://github.com/splunk/kafka-mq-go) · [Ignite CLI](https://github.com/ignite/cli) · [Tendermint](https://github.com/tendermint/tendermint) · [Datadog](https://github.com/DataDog/datadog-agent)


[Get Started](/mockery/installation/){ .md-button .md-button--primary .md-button--stretch }
39 changes: 39 additions & 0 deletions docs/installation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
Getting Started
================

Installation
-------------

### GitHub Release

<small>recommended</small>

Visit the [releases page](https://github.com/vektra/mockery/releases) to download one of the pre-built binaries for your platform.

### go install

Supported, but not recommended: [see wiki page](https://github.com/vektra/mockery/wiki/Installation-Methods#go-install) and [related discussions](https://github.com/vektra/mockery/pull/456).

go install github.com/vektra/mockery/v2@v2.20.0

!!! warning

Do _not_ use `@latest` as this will pull from the latest, potentially untagged, commit on master.

### Docker

Use the [Docker image](https://hub.docker.com/r/vektra/mockery)

docker pull vektra/mockery

Generate all the mocks for your project:

docker run -v "$PWD":/src -w /src vektra/mockery --all

### Homebrew

Install through [brew](https://brew.sh/)

brew install mockery
brew upgrade mockery

85 changes: 85 additions & 0 deletions docs/notes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
Additional Notes
================

Variadic Arguments
------------------

When mocking methods with variadic arguments, some complexities are introduced. Before this PR: https://github.com/vektra/mockery/pull/123, mocking a variadic method looked like this:

```go
type Foo interface {
Bar(s ...string) error
}

func TestFoo(t *testing.T) {
m := NewMockFoo(t)
m.On("Bar", []string{"hello", "world"}).Return(nil)
}
```

After the PR, you could use this syntax:

```go
func TestFoo(t *testing.T) {
m := NewMockFoo(t)
m.On("Bar", "hello", "world").Return(nil)
```
This introduces ambiguities because if you want to do something like this:
```
m.On("Bar", mock.Anything).Return(nil)
```
This is impossible to distinguish between these two intentions:
1. Any number of variadic arguments of any value
2. A single variadic argument of any value
This is fixed in https://github.com/vektra/mockery/pull/359 where you can provide `unroll-variadic: False` to get back to the old behavior. Thus, if you want to assert the first case, you can then do:
```
m.On("Bar", mock.Anything).Return(nil)
```
If you want to specify the second case, you must set `unroll-variadic: True`. Then this assertion's intention will be modified to mean the second case:
```
m.On("Bar", mock.Anything).Return(nil)
```
An upstream patch to `testify` is currently underway to allow passing `mock.Anything` directly to the variadic slice: https://github.com/stretchr/testify/pull/1348
If this is merged, it would become possible to describe the above two cases respectively:
```go
// case 1
m.On("Bar", mock.Anything).Return(nil)
// case 2
m.On("Bar", []interface{}{mock.Anything}).Return(nil)
```
References:
- https://github.com/vektra/mockery/pull/359
- https://github.com/vektra/mockery/pull/123
- https://github.com/vektra/mockery/pull/550
- https://github.com/vektra/mockery/issues/541
Semantic Versioning
-------------------
The versioning in this project applies only to the behavior of the mockery binary itself. This project explicitly does not promise a stable internal API, but rather a stable executable. The versioning applies to the following:
1. CLI arguments.
2. Parsing of Golang code. New features in the Golang language will be supported in a backwards-compatible manner, except during major version bumps.
3. Behavior of mock objects. Mock objects can be considered to be part of the public API.
4. Behavior of mockery given a set of arguments.
What the version does _not_ track:
1. The interfaces, objects, methods etc. in the vektra/mockery package.
2. Compatibility of `go get`-ing mockery with new or old versions of Golang.
Mocking interfaces in `main`
----------------------------
When your interfaces are in the main package, you should supply the `--inpackage` flag.
This will generate mocks in the same package as the target code, avoiding import issues.
4 changes: 4 additions & 0 deletions docs/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
mkdocs-material
pillow
cairosvg
mkdocs-glightbox
47 changes: 47 additions & 0 deletions docs/running.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
Running
========

Using `go generate` <small>recommended</small>
--------------------

`go generate` is often preferred as it give you more targeted generation of specific interfaces. Use `generate` as a directive above the interface you want to generate a mock for.

``` golang
package example_project

//go:generate mockery --name Root
type Root interface {
Foobar(s string) error
}
```

Then simply:

``` bash
$ go generate
09 Feb 23 22:55 CST INF Starting mockery dry-run=false version=v2.18.0
09 Feb 23 22:55 CST INF Using config: /Users/landonclipp/git/LandonTClipp/mockery/.mockery.yaml dry-run=false version=v2.18.0
09 Feb 23 22:55 CST INF Walking dry-run=false version=v2.18.0
09 Feb 23 22:55 CST INF Generating mock dry-run=false interface=Root qualified-name=github.com/vektra/mockery/v2/pkg/fixtures/example_project version=v2.18.0
```

For all interfaces in project
------------------------------

If you provide `all: True`, you can generate mocks for the entire project. This is not recommended for larger projects as it can take a large amount of time parsing packages to generate mocks that you might never use.

```bash
$ mockery
09 Feb 23 22:47 CST INF Starting mockery dry-run=false version=v2.18.0
09 Feb 23 22:47 CST INF Using config: /Users/landonclipp/git/LandonTClipp/mockery/.mockery.yaml dry-run=false version=v2.18.0
09 Feb 23 22:47 CST INF Walking dry-run=false version=v2.18.0
09 Feb 23 22:47 CST INF Generating mock dry-run=false interface=A qualified-name=github.com/vektra/mockery/v2/pkg/fixtures version=v2.18.0
```

!!! note

Note that in some cases, using `//go:generate` may turn out to be slower than running for entire packages. `go:generate` calls mockery once for each `generate` directive, which means that mockery may need to parse the package multiple times, which is wasteful. Good judgement is recommended when determining the best option for your own project.

!!! note

For mockery to correctly generate mocks, the command has to be run on a module (i.e. your project has to have a go.mod file)
5 changes: 5 additions & 0 deletions docs/stylesheets/extra.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.md-button--stretch {
width: 100%;
text-align: center;
}

46 changes: 37 additions & 9 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,15 +1,43 @@
module github.com/vektra/mockery/v2

go 1.16
go 1.19

require (
github.com/chigopher/pathlib v0.12.0
github.com/jinzhu/copier v0.3.5
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/mitchellh/mapstructure v1.5.0
github.com/pkg/errors v0.9.1
github.com/rs/zerolog v1.29.0
github.com/spf13/cobra v1.6.1
github.com/spf13/viper v1.15.0
github.com/stretchr/testify v1.8.1
golang.org/x/crypto v0.6.0
golang.org/x/tools v0.6.0
gopkg.in/yaml.v2 v2.4.0
gopkg.in/yaml.v3 v3.0.1
)

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/fsnotify/fsnotify v1.6.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/iancoleman/strcase v0.2.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.17 // indirect
github.com/pelletier/go-toml/v2 v2.0.6 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/spf13/afero v1.9.3 // indirect
github.com/spf13/cast v1.5.0 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/stretchr/objx v0.5.0 // indirect
github.com/subosito/gotenv v1.4.2 // indirect
golang.org/x/mod v0.8.0 // indirect
golang.org/x/sys v0.5.0 // indirect
golang.org/x/term v0.5.0 // indirect
golang.org/x/text v0.7.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
)
545 changes: 364 additions & 181 deletions go.sum

Large diffs are not rendered by default.

75 changes: 75 additions & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
site_name: mockery
site_url: https://vektra.github.io/mockery/
site_description: >-
Create mock implementations of your Golang interfaces using mockery and testify.
repo_name: vektra/mockery
repo_url: https://github.com/vektra/mockery

theme:
name: material
palette:
# Palette toggle for light mode
- media: "(prefers-color-scheme: light)"
scheme: default
primary: light blue
toggle:
icon: material/brightness-7
name: Switch to dark mode
# Palette toggle for dark mode
- media: "(prefers-color-scheme: dark)"
scheme: slate
primary: light blue
toggle:
icon: material/brightness-4
name: Switch to light mode
features:
- content.code.annotate
- content.code.copy
- content.action.edit
- content.action.view
- navigation.indexes
- navigation.sections
- navigation.tabs
- navigation.tabs.sticky
- navigation.tracking
- toc.follow
markdown_extensions:
- admonition
- attr_list
- md_in_html
- pymdownx.emoji:
emoji_index: !!python/name:materialx.emoji.twemoji
emoji_generator: !!python/name:materialx.emoji.to_svg
- pymdownx.highlight:
anchor_linenums: true
auto_title: true
- pymdownx.inlinehilite
- pymdownx.details
- pymdownx.superfences
- pymdownx.tabbed:
alternate_style: true
- toc:
permalink: true


nav:
- Home: index.md
- Getting Started:
- Installation: installation.md
- Configuration: configuration.md
- Running: running.md
- Using Mocks:
- Examples: examples.md
- Features: features.md
- Notes:
- Additional Notes: notes.md
- Changelog: changelog.md

extra_css:
- stylesheets/extra.css

plugins:
- glightbox
- social
- search
115 changes: 115 additions & 0 deletions mocks/github.com/vektra/mockery/v2/pkg/TypesPackage.go
271 changes: 271 additions & 0 deletions mocks/github.com/vektra/mockery/v2/pkg/fixtures/Expecter.go
34 changes: 0 additions & 34 deletions mocks/pkg/fixtures/A.go

This file was deleted.

58 changes: 0 additions & 58 deletions mocks/pkg/fixtures/AsyncProducer.go

This file was deleted.

24 changes: 0 additions & 24 deletions mocks/pkg/fixtures/Blank.go

This file was deleted.

47 changes: 0 additions & 47 deletions mocks/pkg/fixtures/ConsulLock.go

This file was deleted.

46 changes: 0 additions & 46 deletions mocks/pkg/fixtures/Example.go

This file was deleted.

45 changes: 0 additions & 45 deletions mocks/pkg/fixtures/Fooer.go

This file was deleted.

24 changes: 0 additions & 24 deletions mocks/pkg/fixtures/FuncArgsCollision.go

This file was deleted.

51 changes: 0 additions & 51 deletions mocks/pkg/fixtures/HasConflictingNestedImports.go

This file was deleted.

50 changes: 0 additions & 50 deletions mocks/pkg/fixtures/ImportsSameAsPackage.go

This file was deleted.

38 changes: 0 additions & 38 deletions mocks/pkg/fixtures/KeyManager.go

This file was deleted.

24 changes: 0 additions & 24 deletions mocks/pkg/fixtures/MapFunc.go

This file was deleted.

21 changes: 0 additions & 21 deletions mocks/pkg/fixtures/MapToInterface.go

This file was deleted.

31 changes: 0 additions & 31 deletions mocks/pkg/fixtures/MyReader.go

This file was deleted.

31 changes: 0 additions & 31 deletions mocks/pkg/fixtures/Requester.go

This file was deleted.

24 changes: 0 additions & 24 deletions mocks/pkg/fixtures/Requester2.go

This file was deleted.

24 changes: 0 additions & 24 deletions mocks/pkg/fixtures/Requester3.go

This file was deleted.

15 changes: 0 additions & 15 deletions mocks/pkg/fixtures/Requester4.go

This file was deleted.

30 changes: 0 additions & 30 deletions mocks/pkg/fixtures/RequesterArgSameAsImport.go

This file was deleted.

Loading