pax_global_header00006660000000000000000000000064147043014220014507gustar00rootroot0000000000000052 comment=a9c44d91ce00ef09603d3822452a4f9c8fefd278 golang-go.uber-mock-0.5.0/000077500000000000000000000000001470430142200152465ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/.github/000077500000000000000000000000001470430142200166065ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/.github/CODEOWNERS000066400000000000000000000000351470430142200201770ustar00rootroot00000000000000* @codyoss golang-go.uber-mock-0.5.0/.github/ISSUE_TEMPLATE/000077500000000000000000000000001470430142200207715ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/.github/ISSUE_TEMPLATE/bug_report.md000066400000000000000000000011111470430142200234550ustar00rootroot00000000000000--- name: Bug report about: Report a bug in gomock title: '' labels: '' assignees: '' --- **Actual behavior** A clear and concise description of what the bug is. **Expected behavior** A clear and concise description of what you expected to happen. **To Reproduce** Steps to reproduce the behavior 1. ... 2. ... **Additional Information** - gomock mode (reflect or source): - gomock version or git ref: - golang version: **Triage Notes for the Maintainers** golang-go.uber-mock-0.5.0/.github/ISSUE_TEMPLATE/config.yml000066400000000000000000000004471470430142200227660ustar00rootroot00000000000000blank_issues_enabled: true #contact_links: # - name: GitHub Community Forum # url: https://github.community/ # about: Please ask and answer questions here. # - name: GitHub Security Bug Bounty # url: https://bounty.github.com/ # about: Please report security vulnerabilities here. golang-go.uber-mock-0.5.0/.github/ISSUE_TEMPLATE/feature_request.md000066400000000000000000000007131470430142200245170ustar00rootroot00000000000000--- name: Feature request about: Propose a new feature for gomock title: '' labels: 'type: feature request' assignees: '' --- *Requested feature* A clear description of the desired feature and an example of how it would be used. *Why the feature is needed* A clear description of how this feature is not served by existing functionality in gomock. *(Optional) Proposed solution* A clear description of a proposed method for adding this feature to gomock. golang-go.uber-mock-0.5.0/.github/dependabot.yaml000066400000000000000000000007701470430142200216030ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: "gomod" directory: "/tools" schedule: interval: "daily" open-pull-requests-limit: 5 - package-ecosystem: "gomod" directory: "/mockgen/internal/tests/generics" schedule: interval: "daily" open-pull-requests-limit: 5 - package-ecosystem: "gomod" directory: "/mockgen/internal/tests/typed" schedule: interval: "daily" open-pull-requests-limit: 5 - package-ecosystem: "github-actions" directory: "/" schedule: interval: "weekly" golang-go.uber-mock-0.5.0/.github/workflows/000077500000000000000000000000001470430142200206435ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/.github/workflows/release.yaml000066400000000000000000000024371470430142200231550ustar00rootroot00000000000000name: release on: push: tags: ['v*'] permissions: contents: write jobs: release: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v3 with: fetch-depth: 0 - name: Setup Go uses: actions/setup-go@v4 with: go-version: 1.23.x - name: Prepare release run: | set -eou pipefail make bin/extract-changelog # Extract target version number from the git tag and post it to # GITHUB_ENV to make it accessible via env.VERSION in other steps. VERSION=${{ github.ref }} VERSION="${VERSION#refs/tags/}" # refs/tags/v1.2.3 => v1.2.3 echo "VERSION=$VERSION" >> $GITHUB_ENV echo "Releasing $VERSION" # Place the release notes in changes.v1.2.3.txt to grab them in the # release step. echo "Release notes:" echo "----" bin/extract-changelog $VERSION | tee changes.$VERSION.txt echo "----" - name: Release uses: goreleaser/goreleaser-action@v6 with: distribution: goreleaser version: latest args: release --clean --release-notes changes.${{ env.VERSION }}.txt env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GORELEASER_CURRENT_TAG: ${{ env.VERSION }} golang-go.uber-mock-0.5.0/.github/workflows/test.yaml000066400000000000000000000017361470430142200225150ustar00rootroot00000000000000name: Run tests on: push: branches: ['*'] pull_request: branches: ['*'] permissions: contents: read jobs: test: strategy: matrix: go-version: [1.22.x, 1.23.x] # oldest version that can build go mock and official supported go versions os: [ubuntu-latest] runs-on: ${{ matrix.os }} steps: - name: Checkout code uses: actions/checkout@v3 - name: Install Go uses: actions/setup-go@v4 with: go-version: ${{ matrix.go-version }} cache-dependency-path: '**/go.sum' - name: Vet and build run: | go vet ./... go build ./... - name: Install mockgen run: | go install go.uber.org/mock/mockgen - name: Run test script run: | ./ci/test.sh ./ci/check_panic_handling.sh - name: Run Tests run: | for i in $(find $PWD -name go.mod); do pushd $(dirname $i) go test ./... popd done golang-go.uber-mock-0.5.0/.gitignore000066400000000000000000000003641470430142200172410ustar00rootroot00000000000000# Object files and binaries from go. *.[568] # Library files. *.a # Any file prefixed by an underscore. */_* # System .*.swp .DS_Store # The mockgen binary. mockgen/mockgen # Editors .vscode .idea # vendor directory used for IDEs /vendor golang-go.uber-mock-0.5.0/.goreleaser.yml000066400000000000000000000014051470430142200201770ustar00rootroot00000000000000# Release automation via GoReleaser (goreleaser.com) # Requires a valid GITHUB_TOKEN envar prior to running `goreleaser` # See https://goreleaser.com/environment/ for more info --- release: github: owner: uber-go name: mock builds: - binary: mockgen goos: - darwin - windows - linux goarch: - amd64 - arm64 - 386 env: - CGO_ENABLED=0 - GO111MODULE=on - GOPROXY=https://proxy.golang.org - GOSUMDB=sum.golang.org main: ./mockgen/ archives: - format: tar.gz wrap_in_directory: true files: - LICENSE - README.md checksum: snapshot: name_template: "snap-{{ .Commit }}" changelog: sort: asc filters: exclude: - '^docs:' - '^test:' - 'README' golang-go.uber-mock-0.5.0/AUTHORS000066400000000000000000000005631470430142200163220ustar00rootroot00000000000000# This is the official list of GoMock authors for copyright purposes. # This file is distinct from the CONTRIBUTORS files. # See the latter for an explanation. # Names should be added to this file as # Name or Organization # The email address is not required for organizations. # Please keep the list sorted. Alex Reece Google Inc. golang-go.uber-mock-0.5.0/CHANGELOG.md000066400000000000000000000110701470430142200170560ustar00rootroot00000000000000# Changelog All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). ## 0.5.0 (15 Oct 2024) ### Added - [#153][]: Add `--write_command_comment` flag to specify whether to include `Generated by this command` comment. - [#191][]: Add `--build_constraint` flag to add `//go:build` directives to generated mocks - [#214][]: Add gob mode to support custom package loading techniques in place of --exec_only ### Changed - [#181][]: Made mockgen faster by changing flags passed to `go list`. - [#183][]: Made `Cond` matcher generic. - [#204][]: Removed `ISGOMOCK()` from generated mocks. - [#207][]: Deprecated reflect mode and replaced it with the new package mode. ### Fixed - [#144][]: Fix a deadlock that can happen when mocking an interface that matches `fmt.Stringer`. - [#168][]: Fix an issue where the "generated by" comment was being included in the package comment of generated mocks. [#144]: https://github.com/uber-go/mock/pull/144 [#153]: https://github.com/uber-go/mock/pull/153 [#168]: https://github.com/uber-go/mock/pull/168 [#181]: https://github.com/uber-go/mock/pull/181 [#183]: https://github.com/uber-go/mock/pull/183 [#191]: https://github.com/uber-go/mock/pull/191 [#204]: https://github.com/uber-go/mock/pull/204 [#207]: https://github.com/uber-go/mock/pull/207 [#214]: https://github.com/uber-go/mock/pull/214 Thanks to @tulzke @JacobOaks @ARR4N @sashamelentyev @sywhang @fasmat @eyasy1217 @ghouscht @tie @Neo2308 @carson-brill @alexandear @sodul @nbgraham for their contributions this release. ## 0.4.0 (20 Dec 2023) ### Added - [#63][]: `AnyOf` matcher for values that satisfy at least one matcher. - [#114][]: `Regex` matcher. ### Fixed - [#93][]: Ignore interfaces that contain type constraints. - [#101][]: Fix race condition on Controller.Satisfied. - [#121][]: Fix paths for windows. - [#127][]: Propagate -mock_names to Recorder and ReturnCall types. - [#132][]: Sanitize "any" package names. [#63]: https://github.com/uber-go/mock/pull/63 [#93]: https://github.com/uber-go/mock/pull/93 [#101]: https://github.com/uber-go/mock/pull/101 [#114]: https://github.com/uber-go/mock/pull/114 [#121]: https://github.com/uber-go/mock/pull/121 [#127]: https://github.com/uber-go/mock/pull/127 [#132]: https://github.com/uber-go/mock/pull/132 Thanks to @favonia @hoonmin @pshopper @davidharrigan @dlsniper @merrett010 @craig65535 @chemidy @tulzke @UnAfraid @JacobOaks @sywhang for their contributions this release. ## 0.3.0 (15 Sep 2023) ### Added - [#13][]: Support for embedded generic interfaces. - [#33][]: `-write_source_comment` for writing the original file or interface names in the generated code. - [#46][]: `-write-generate-directive` for generating go:generate directives into the generated mock. - [#60][]: `Cond` matcher for specifying a conditional matcher as the result of a given function. - [#72][]: `exclude_interfaces` flag for specifying list of interfaces to exclude from mock generation. ### Fixed - [#41][]: A bug with specifying local import name with `-imports` flag. - [#52][]: A panic that occurs in `gob.Register` when used in conjunction with golang/mock. - [#78][]: `InOrder` can be used with type-safe mocks generated with `-typed` flag. [#13]: https://github.com/uber-go/mock/pull/13 [#33]: https://github.com/uber-go/mock/pull/33 [#41]: https://github.com/uber-go/mock/pull/41 [#46]: https://github.com/uber-go/mock/pull/46 [#52]: https://github.com/uber-go/mock/pull/52 [#60]: https://github.com/uber-go/mock/pull/60 [#72]: https://github.com/uber-go/mock/pull/72 [#78]: https://github.com/uber-go/mock/pull/78 Thanks to @alexandear, @bcho, @deathiop, @sivchari, @k3forx, @n0trace, @utgwkk, @ErfanMomeniii, @bcho, @damianopetrungaro, @Tulzke, and @EstebanOlmedo for their contributions to this release. ## 0.2.0 (06 Jul 2023) ### Added - `Controller.Satisfied` that lets you check whether all expected calls bound to a Controller have been satisfied. - `NewController` now takes optional `ControllerOption` parameter. - `WithOverridableExpectations` is a `ControllerOption` that configures Controller to override existing expectations upon a new EXPECT(). - `-typed` flag for generating type-safe methods in the generated mock. ## 0.1.0 (29 Jun 2023) This is a minor version that mirrors the original golang/mock project that this project originates from. Any users on golang/mock project should be able to migrate to this project as-is, and expect exact same set of features (apart from supported Go versions. See [README](README.md#supported-go-versions) for more details. golang-go.uber-mock-0.5.0/CONTRIBUTING.md000066400000000000000000000015231470430142200175000ustar00rootroot00000000000000# Contributing First off, thank you for taking an interest to contribute to this project! > **Tip:** You'll need to sign [Uber's CLA](https://cla-assistant.io/uber-go/mock) > before we can accept any of your contributions. > If necessary, a bot will remind > you to accept the CLA when you open your pull request. ## Opening issues When opening a [new issue](https://github.com/uber-go/mock/issues/new/choose) please: 1. Make sure there are no other open/closed issues asking/reporting/requesting the same thing. 1. Choose one of our provided templates and fill out as much information as possible. ## Opening a Pull Requests We gladly accept contributions from the community. Before opening a pull request please make sure to create an issue for discussion first. This helps us decide what action should be taken in regard to the issue. golang-go.uber-mock-0.5.0/LICENSE000066400000000000000000000261361470430142200162630ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. golang-go.uber-mock-0.5.0/MAINTAINERS000066400000000000000000000002561470430142200167460ustar00rootroot00000000000000# This is the current list of maintainers to Uber's fork of gomock repository. Sung Yoon Whang Ryan Hang Zhongpeng Lin golang-go.uber-mock-0.5.0/README.md000066400000000000000000000161031470430142200165260ustar00rootroot00000000000000# gomock [![Build Status][ci-badge]][ci-runs] [![Go Reference][reference-badge]][reference] gomock is a mocking framework for the [Go programming language][golang]. It integrates well with Go's built-in `testing` package, but can be used in other contexts too. This project originates from Google's `golang/mock` repo. Unfortunately, Google no longer maintains this project, and given the heavy usage of gomock project within Uber, we've decided to fork and maintain this going forward at Uber. [Contributions](./CONTRIBUTING.md) are welcome in the form of GitHub issue or PR! ## Supported Go Versions go.uber.org/mock supports all Go versions supported by the official [Go Release Policy](https://go.dev/doc/devel/release#policy). That is, the two most recent releases of Go. ## Installation Install the `mockgen` tool. ``` go install go.uber.org/mock/mockgen@latest ``` To ensure it was installed correctly, use: ``` mockgen -version ``` If that fails, make sure your GOPATH/bin is in your PATH. You can add it with: ``` export PATH=$PATH:$(go env GOPATH)/bin ``` ## Running mockgen `mockgen` has two modes of operation: source and package. ### Source mode Source mode generates mock interfaces from a source file. It is enabled by using the -source flag. Other flags that may be useful in this mode are -imports and -aux_files. Example: ```bash mockgen -source=foo.go [other options] ``` ### Package mode Package mode works by specifying the package and interface names. It is enabled by passing two non-flag arguments: an import path, and a comma-separated list of symbols. You can use "." to refer to the current path's package. Example: ```bash mockgen database/sql/driver Conn,Driver # Convenient for `go:generate`. mockgen . Conn,Driver ``` ### Flags The `mockgen` command is used to generate source code for a mock class given a Go source file containing interfaces to be mocked. It supports the following flags: - `-source`: A file containing interfaces to be mocked. - `-destination`: A file to which to write the resulting source code. If you don't set this, the code is printed to standard output. - `-package`: The package to use for the resulting mock class source code. If you don't set this, the package name is `mock_` concatenated with the package of the input file. - `-imports`: A list of explicit imports that should be used in the resulting source code, specified as a comma-separated list of elements of the form `foo=bar/baz`, where `bar/baz` is the package being imported and `foo` is the identifier to use for the package in the generated source code. - `-aux_files`: A list of additional files that should be consulted to resolve e.g. embedded interfaces defined in a different file. This is specified as a comma-separated list of elements of the form `foo=bar/baz.go`, where `bar/baz.go` is the source file and `foo` is the package name of that file used by the -source file. - `-build_flags`: (package mode only) Flags passed verbatim to `go list`. - `-mock_names`: A list of custom names for generated mocks. This is specified as a comma-separated list of elements of the form `Repository=MockSensorRepository,Endpoint=MockSensorEndpoint`, where `Repository` is the interface name and `MockSensorRepository` is the desired mock name (mock factory method and mock recorder will be named after the mock). If one of the interfaces has no custom name specified, then default naming convention will be used. - `-self_package`: The full package import path for the generated code. The purpose of this flag is to prevent import cycles in the generated code by trying to include its own package. This can happen if the mock's package is set to one of its inputs (usually the main one) and the output is stdio so mockgen cannot detect the final output package. Setting this flag will then tell mockgen which import to exclude. - `-copyright_file`: Copyright file used to add copyright header to the resulting source code. - `-debug_parser`: Print out parser results only. - `-write_package_comment`: Writes package documentation comment (godoc) if true. (default true) - `-write_generate_directive`: Add //go:generate directive to regenerate the mock. (default false) - `-write_source_comment`: Writes original file (source mode) or interface names (package mode) comment if true. (default true) - `-typed`: Generate Type-safe 'Return', 'Do', 'DoAndReturn' function. (default false) - `-exclude_interfaces`: Comma-separated names of interfaces to be excluded For an example of the use of `mockgen`, see the `sample/` directory. In simple cases, you will need only the `-source` flag. ## Building Mocks ```go type Foo interface { Bar(x int) int } func SUT(f Foo) { // ... } ``` ```go func TestFoo(t *testing.T) { ctrl := gomock.NewController(t) m := NewMockFoo(ctrl) // Asserts that the first and only call to Bar() is passed 99. // Anything else will fail. m. EXPECT(). Bar(gomock.Eq(99)). Return(101) SUT(m) } ``` ## Building Stubs ```go type Foo interface { Bar(x int) int } func SUT(f Foo) { // ... } ``` ```go func TestFoo(t *testing.T) { ctrl := gomock.NewController(t) m := NewMockFoo(ctrl) // Does not make any assertions. Executes the anonymous functions and returns // its result when Bar is invoked with 99. m. EXPECT(). Bar(gomock.Eq(99)). DoAndReturn(func(_ int) int { time.Sleep(1*time.Second) return 101 }). AnyTimes() // Does not make any assertions. Returns 103 when Bar is invoked with 101. m. EXPECT(). Bar(gomock.Eq(101)). Return(103). AnyTimes() SUT(m) } ``` ## Modifying Failure Messages When a matcher reports a failure, it prints the received (`Got`) vs the expected (`Want`) value. ```shell Got: [3] Want: is equal to 2 Expected call at user_test.go:33 doesn't match the argument at index 1. Got: [0 1 1 2 3] Want: is equal to 1 ``` ### Modifying `Want` The `Want` value comes from the matcher's `String()` method. If the matcher's default output doesn't meet your needs, then it can be modified as follows: ```go gomock.WantFormatter( gomock.StringerFunc(func() string { return "is equal to fifteen" }), gomock.Eq(15), ) ``` This modifies the `gomock.Eq(15)` matcher's output for `Want:` from `is equal to 15` to `is equal to fifteen`. ### Modifying `Got` The `Got` value comes from the object's `String()` method if it is available. In some cases the output of an object is difficult to read (e.g., `[]byte`) and it would be helpful for the test to print it differently. The following modifies how the `Got` value is formatted: ```go gomock.GotFormatterAdapter( gomock.GotFormatterFunc(func(i any) string { // Leading 0s return fmt.Sprintf("%02d", i) }), gomock.Eq(15), ) ``` If the received value is `3`, then it will be printed as `03`. [golang]: http://go.dev/ [ci-badge]: https://github.com/uber-go/mock/actions/workflows/test.yaml/badge.svg [ci-runs]: https://github.com/uber-go/mock/actions [reference-badge]: https://pkg.go.dev/badge/go.uber.org/mock.svg [reference]: https://pkg.go.dev/go.uber.org/mock golang-go.uber-mock-0.5.0/ci/000077500000000000000000000000001470430142200156415ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/ci/check_panic_handling.sh000077500000000000000000000016111470430142200222720ustar00rootroot00000000000000#!/bin/bash # Copyright 2010 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This script is used to ensure that panics are properly reported in tests. set -eux pushd mockgen/internal/tests/panicing_test go test -v -tags=panictest -run TestDanger_Panics_Explicit | grep "Danger, Will Robinson!" go test -v -tags=panictest -run TestDanger_Panics_Implicit | grep "Danger, Will Robinson!" popd golang-go.uber-mock-0.5.0/ci/test.sh000077500000000000000000000013101470430142200171520ustar00rootroot00000000000000#!/bin/bash # This script is used to ensure that the go.mod file is up to date. set -euo pipefail for i in $(find $PWD -name go.mod); do pushd $(dirname $i) go mod tidy popd done if [ ! -z "$(git status --porcelain)" ]; then git status git diff echo echo "The go.mod is not up to date." exit 1 fi BASE_DIR="$PWD" TEMP_DIR=$(mktemp -d) function cleanup() { rm -rf "${TEMP_DIR}" } trap cleanup EXIT cp -r . "${TEMP_DIR}/" cd $TEMP_DIR for i in $(find $PWD -name go.mod); do pushd $(dirname $i) go generate ./... popd done if ! diff -r . "${BASE_DIR}"; then echo echo "The generated files aren't up to date." echo "Update them with the 'go generate ./...' command." exit 1 fi golang-go.uber-mock-0.5.0/go.mod000066400000000000000000000005571470430142200163630ustar00rootroot00000000000000module go.uber.org/mock go 1.22 require ( github.com/stretchr/testify v1.9.0 golang.org/x/mod v0.18.0 golang.org/x/tools v0.22.0 ) require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/yuin/goldmark v1.4.13 // indirect golang.org/x/sync v0.7.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) golang-go.uber-mock-0.5.0/go.sum000066400000000000000000000027511470430142200164060ustar00rootroot00000000000000github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/yuin/goldmark v1.4.13 h1:fVcFKWvrslecOb/tg+Cc05dkeYx540o0FuFt3nUVDoE= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= golang.org/x/mod v0.18.0 h1:5+9lSbEzPSdWkH32vYPBwEpX8KwDbM52Ud9xBUvNlb0= golang.org/x/mod v0.18.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M= golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/tools v0.22.0 h1:gqSGLZqv+AI9lIQzniJ0nZDRG5GBPsSi+DRNHWNz6yA= golang.org/x/tools v0.22.0/go.mod h1:aCwcsjqvq7Yqt6TNyX7QMU2enbQ/Gt0bo6krSeEri+c= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= golang-go.uber-mock-0.5.0/gomock/000077500000000000000000000000001470430142200165255ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/gomock/call.go000066400000000000000000000375151470430142200200020ustar00rootroot00000000000000// Copyright 2010 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gomock import ( "fmt" "reflect" "strconv" "strings" ) // Call represents an expected call to a mock. type Call struct { t TestHelper // for triggering test failures on invalid call setup receiver any // the receiver of the method call method string // the name of the method methodType reflect.Type // the type of the method args []Matcher // the args origin string // file and line number of call setup preReqs []*Call // prerequisite calls // Expectations minCalls, maxCalls int numCalls int // actual number made // actions are called when this Call is called. Each action gets the args and // can set the return values by returning a non-nil slice. Actions run in the // order they are created. actions []func([]any) []any } // newCall creates a *Call. It requires the method type in order to support // unexported methods. func newCall(t TestHelper, receiver any, method string, methodType reflect.Type, args ...any) *Call { t.Helper() // TODO: check arity, types. mArgs := make([]Matcher, len(args)) for i, arg := range args { if m, ok := arg.(Matcher); ok { mArgs[i] = m } else if arg == nil { // Handle nil specially so that passing a nil interface value // will match the typed nils of concrete args. mArgs[i] = Nil() } else { mArgs[i] = Eq(arg) } } // callerInfo's skip should be updated if the number of calls between the user's test // and this line changes, i.e. this code is wrapped in another anonymous function. // 0 is us, 1 is RecordCallWithMethodType(), 2 is the generated recorder, and 3 is the user's test. origin := callerInfo(3) actions := []func([]any) []any{func([]any) []any { // Synthesize the zero value for each of the return args' types. rets := make([]any, methodType.NumOut()) for i := 0; i < methodType.NumOut(); i++ { rets[i] = reflect.Zero(methodType.Out(i)).Interface() } return rets }} return &Call{ t: t, receiver: receiver, method: method, methodType: methodType, args: mArgs, origin: origin, minCalls: 1, maxCalls: 1, actions: actions, } } // AnyTimes allows the expectation to be called 0 or more times func (c *Call) AnyTimes() *Call { c.minCalls, c.maxCalls = 0, 1e8 // close enough to infinity return c } // MinTimes requires the call to occur at least n times. If AnyTimes or MaxTimes have not been called or if MaxTimes // was previously called with 1, MinTimes also sets the maximum number of calls to infinity. func (c *Call) MinTimes(n int) *Call { c.minCalls = n if c.maxCalls == 1 { c.maxCalls = 1e8 } return c } // MaxTimes limits the number of calls to n times. If AnyTimes or MinTimes have not been called or if MinTimes was // previously called with 1, MaxTimes also sets the minimum number of calls to 0. func (c *Call) MaxTimes(n int) *Call { c.maxCalls = n if c.minCalls == 1 { c.minCalls = 0 } return c } // DoAndReturn declares the action to run when the call is matched. // The return values from this function are returned by the mocked function. // It takes an any argument to support n-arity functions. // The anonymous function must match the function signature mocked method. func (c *Call) DoAndReturn(f any) *Call { // TODO: Check arity and types here, rather than dying badly elsewhere. v := reflect.ValueOf(f) c.addAction(func(args []any) []any { c.t.Helper() ft := v.Type() if c.methodType.NumIn() != ft.NumIn() { if ft.IsVariadic() { c.t.Fatalf("wrong number of arguments in DoAndReturn func for %T.%v The function signature must match the mocked method, a variadic function cannot be used.", c.receiver, c.method) } else { c.t.Fatalf("wrong number of arguments in DoAndReturn func for %T.%v: got %d, want %d [%s]", c.receiver, c.method, ft.NumIn(), c.methodType.NumIn(), c.origin) } return nil } vArgs := make([]reflect.Value, len(args)) for i := 0; i < len(args); i++ { if args[i] != nil { vArgs[i] = reflect.ValueOf(args[i]) } else { // Use the zero value for the arg. vArgs[i] = reflect.Zero(ft.In(i)) } } vRets := v.Call(vArgs) rets := make([]any, len(vRets)) for i, ret := range vRets { rets[i] = ret.Interface() } return rets }) return c } // Do declares the action to run when the call is matched. The function's // return values are ignored to retain backward compatibility. To use the // return values call DoAndReturn. // It takes an any argument to support n-arity functions. // The anonymous function must match the function signature mocked method. func (c *Call) Do(f any) *Call { // TODO: Check arity and types here, rather than dying badly elsewhere. v := reflect.ValueOf(f) c.addAction(func(args []any) []any { c.t.Helper() ft := v.Type() if c.methodType.NumIn() != ft.NumIn() { if ft.IsVariadic() { c.t.Fatalf("wrong number of arguments in Do func for %T.%v The function signature must match the mocked method, a variadic function cannot be used.", c.receiver, c.method) } else { c.t.Fatalf("wrong number of arguments in Do func for %T.%v: got %d, want %d [%s]", c.receiver, c.method, ft.NumIn(), c.methodType.NumIn(), c.origin) } return nil } vArgs := make([]reflect.Value, len(args)) for i := 0; i < len(args); i++ { if args[i] != nil { vArgs[i] = reflect.ValueOf(args[i]) } else { // Use the zero value for the arg. vArgs[i] = reflect.Zero(ft.In(i)) } } v.Call(vArgs) return nil }) return c } // Return declares the values to be returned by the mocked function call. func (c *Call) Return(rets ...any) *Call { c.t.Helper() mt := c.methodType if len(rets) != mt.NumOut() { c.t.Fatalf("wrong number of arguments to Return for %T.%v: got %d, want %d [%s]", c.receiver, c.method, len(rets), mt.NumOut(), c.origin) } for i, ret := range rets { if got, want := reflect.TypeOf(ret), mt.Out(i); got == want { // Identical types; nothing to do. } else if got == nil { // Nil needs special handling. switch want.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: // ok default: c.t.Fatalf("argument %d to Return for %T.%v is nil, but %v is not nillable [%s]", i, c.receiver, c.method, want, c.origin) } } else if got.AssignableTo(want) { // Assignable type relation. Make the assignment now so that the generated code // can return the values with a type assertion. v := reflect.New(want).Elem() v.Set(reflect.ValueOf(ret)) rets[i] = v.Interface() } else { c.t.Fatalf("wrong type of argument %d to Return for %T.%v: %v is not assignable to %v [%s]", i, c.receiver, c.method, got, want, c.origin) } } c.addAction(func([]any) []any { return rets }) return c } // Times declares the exact number of times a function call is expected to be executed. func (c *Call) Times(n int) *Call { c.minCalls, c.maxCalls = n, n return c } // SetArg declares an action that will set the nth argument's value, // indirected through a pointer. Or, in the case of a slice and map, SetArg // will copy value's elements/key-value pairs into the nth argument. func (c *Call) SetArg(n int, value any) *Call { c.t.Helper() mt := c.methodType // TODO: This will break on variadic methods. // We will need to check those at invocation time. if n < 0 || n >= mt.NumIn() { c.t.Fatalf("SetArg(%d, ...) called for a method with %d args [%s]", n, mt.NumIn(), c.origin) } // Permit setting argument through an interface. // In the interface case, we don't (nay, can't) check the type here. at := mt.In(n) switch at.Kind() { case reflect.Ptr: dt := at.Elem() if vt := reflect.TypeOf(value); !vt.AssignableTo(dt) { c.t.Fatalf("SetArg(%d, ...) argument is a %v, not assignable to %v [%s]", n, vt, dt, c.origin) } case reflect.Interface, reflect.Slice, reflect.Map: // nothing to do default: c.t.Fatalf("SetArg(%d, ...) referring to argument of non-pointer non-interface non-slice non-map type %v [%s]", n, at, c.origin) } c.addAction(func(args []any) []any { v := reflect.ValueOf(value) switch reflect.TypeOf(args[n]).Kind() { case reflect.Slice: setSlice(args[n], v) case reflect.Map: setMap(args[n], v) default: reflect.ValueOf(args[n]).Elem().Set(v) } return nil }) return c } // isPreReq returns true if other is a direct or indirect prerequisite to c. func (c *Call) isPreReq(other *Call) bool { for _, preReq := range c.preReqs { if other == preReq || preReq.isPreReq(other) { return true } } return false } // After declares that the call may only match after preReq has been exhausted. func (c *Call) After(preReq *Call) *Call { c.t.Helper() if c == preReq { c.t.Fatalf("A call isn't allowed to be its own prerequisite") } if preReq.isPreReq(c) { c.t.Fatalf("Loop in call order: %v is a prerequisite to %v (possibly indirectly).", c, preReq) } c.preReqs = append(c.preReqs, preReq) return c } // Returns true if the minimum number of calls have been made. func (c *Call) satisfied() bool { return c.numCalls >= c.minCalls } // Returns true if the maximum number of calls have been made. func (c *Call) exhausted() bool { return c.numCalls >= c.maxCalls } func (c *Call) String() string { args := make([]string, len(c.args)) for i, arg := range c.args { args[i] = arg.String() } arguments := strings.Join(args, ", ") return fmt.Sprintf("%T.%v(%s) %s", c.receiver, c.method, arguments, c.origin) } // Tests if the given call matches the expected call. // If yes, returns nil. If no, returns error with message explaining why it does not match. func (c *Call) matches(args []any) error { if !c.methodType.IsVariadic() { if len(args) != len(c.args) { return fmt.Errorf("expected call at %s has the wrong number of arguments. Got: %d, want: %d", c.origin, len(args), len(c.args)) } for i, m := range c.args { if !m.Matches(args[i]) { return fmt.Errorf( "expected call at %s doesn't match the argument at index %d.\nGot: %v\nWant: %v", c.origin, i, formatGottenArg(m, args[i]), m, ) } } } else { if len(c.args) < c.methodType.NumIn()-1 { return fmt.Errorf("expected call at %s has the wrong number of matchers. Got: %d, want: %d", c.origin, len(c.args), c.methodType.NumIn()-1) } if len(c.args) != c.methodType.NumIn() && len(args) != len(c.args) { return fmt.Errorf("expected call at %s has the wrong number of arguments. Got: %d, want: %d", c.origin, len(args), len(c.args)) } if len(args) < len(c.args)-1 { return fmt.Errorf("expected call at %s has the wrong number of arguments. Got: %d, want: greater than or equal to %d", c.origin, len(args), len(c.args)-1) } for i, m := range c.args { if i < c.methodType.NumIn()-1 { // Non-variadic args if !m.Matches(args[i]) { return fmt.Errorf("expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v", c.origin, strconv.Itoa(i), formatGottenArg(m, args[i]), m) } continue } // The last arg has a possibility of a variadic argument, so let it branch // sample: Foo(a int, b int, c ...int) if i < len(c.args) && i < len(args) { if m.Matches(args[i]) { // Got Foo(a, b, c) want Foo(matcherA, matcherB, gomock.Any()) // Got Foo(a, b, c) want Foo(matcherA, matcherB, someSliceMatcher) // Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC) // Got Foo(a, b) want Foo(matcherA, matcherB) // Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD) continue } } // The number of actual args don't match the number of matchers, // or the last matcher is a slice and the last arg is not. // If this function still matches it is because the last matcher // matches all the remaining arguments or the lack of any. // Convert the remaining arguments, if any, into a slice of the // expected type. vArgsType := c.methodType.In(c.methodType.NumIn() - 1) vArgs := reflect.MakeSlice(vArgsType, 0, len(args)-i) for _, arg := range args[i:] { vArgs = reflect.Append(vArgs, reflect.ValueOf(arg)) } if m.Matches(vArgs.Interface()) { // Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, gomock.Any()) // Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, someSliceMatcher) // Got Foo(a, b) want Foo(matcherA, matcherB, gomock.Any()) // Got Foo(a, b) want Foo(matcherA, matcherB, someEmptySliceMatcher) break } // Wrong number of matchers or not match. Fail. // Got Foo(a, b) want Foo(matcherA, matcherB, matcherC, matcherD) // Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC, matcherD) // Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD, matcherE) // Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, matcherC, matcherD) // Got Foo(a, b, c) want Foo(matcherA, matcherB) return fmt.Errorf("expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v", c.origin, strconv.Itoa(i), formatGottenArg(m, args[i:]), c.args[i]) } } // Check that all prerequisite calls have been satisfied. for _, preReqCall := range c.preReqs { if !preReqCall.satisfied() { return fmt.Errorf("expected call at %s doesn't have a prerequisite call satisfied:\n%v\nshould be called before:\n%v", c.origin, preReqCall, c) } } // Check that the call is not exhausted. if c.exhausted() { return fmt.Errorf("expected call at %s has already been called the max number of times", c.origin) } return nil } // dropPrereqs tells the expected Call to not re-check prerequisite calls any // longer, and to return its current set. func (c *Call) dropPrereqs() (preReqs []*Call) { preReqs = c.preReqs c.preReqs = nil return } func (c *Call) call() []func([]any) []any { c.numCalls++ return c.actions } // InOrder declares that the given calls should occur in order. // It panics if the type of any of the arguments isn't *Call or a generated // mock with an embedded *Call. func InOrder(args ...any) { calls := make([]*Call, 0, len(args)) for i := 0; i < len(args); i++ { if call := getCall(args[i]); call != nil { calls = append(calls, call) continue } panic(fmt.Sprintf( "invalid argument at position %d of type %T, InOrder expects *gomock.Call or generated mock types with an embedded *gomock.Call", i, args[i], )) } for i := 1; i < len(calls); i++ { calls[i].After(calls[i-1]) } } // getCall checks if the parameter is a *Call or a generated struct // that wraps a *Call and returns the *Call pointer - if neither, it returns nil. func getCall(arg any) *Call { if call, ok := arg.(*Call); ok { return call } t := reflect.ValueOf(arg) if t.Kind() != reflect.Ptr && t.Kind() != reflect.Interface { return nil } t = t.Elem() for i := 0; i < t.NumField(); i++ { f := t.Field(i) if !f.CanInterface() { continue } if call, ok := f.Interface().(*Call); ok { return call } } return nil } func setSlice(arg any, v reflect.Value) { va := reflect.ValueOf(arg) for i := 0; i < v.Len(); i++ { va.Index(i).Set(v.Index(i)) } } func setMap(arg any, v reflect.Value) { va := reflect.ValueOf(arg) for _, e := range va.MapKeys() { va.SetMapIndex(e, reflect.Value{}) } for _, e := range v.MapKeys() { va.SetMapIndex(e, v.MapIndex(e)) } } func (c *Call) addAction(action func([]any) []any) { c.actions = append(c.actions, action) } func formatGottenArg(m Matcher, arg any) string { got := fmt.Sprintf("%v (%T)", arg, arg) if gs, ok := m.(GotFormatter); ok { got = gs.Got(arg) } return got } golang-go.uber-mock-0.5.0/gomock/call_test.go000066400000000000000000000361261470430142200210360ustar00rootroot00000000000000// Copyright 2020 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gomock import ( "fmt" "reflect" "testing" ) type foo struct{} func (f foo) String() string { return "meow" } type a struct { name string } func (testObj a) Name() string { return testObj.name } type b struct { foo string } type c struct { *Call } func (testObj b) Foo() string { return testObj.foo } type mockTestReporter struct { errorCalls int fatalCalls int } func (o *mockTestReporter) Errorf(format string, args ...any) { o.errorCalls++ } func (o *mockTestReporter) Fatalf(format string, args ...any) { o.fatalCalls++ } func (o *mockTestReporter) Helper() {} func TestCall_After(t *testing.T) { t.Run("SelfPrereqCallsFatalf", func(t *testing.T) { tr1 := &mockTestReporter{} c := &Call{t: tr1} c.After(c) if tr1.fatalCalls != 1 { t.Errorf("number of fatal calls == %v, want 1", tr1.fatalCalls) } }) t.Run("LoopInCallOrderCallsFatalf", func(t *testing.T) { tr1 := &mockTestReporter{} tr2 := &mockTestReporter{} c1 := &Call{t: tr1} c2 := &Call{t: tr2} c1.After(c2) c2.After(c1) if tr1.errorCalls != 0 || tr1.fatalCalls != 0 { t.Error("unexpected errors") } if tr2.fatalCalls != 1 { t.Errorf("number of fatal calls == %v, want 1", tr2.fatalCalls) } }) } func prepareDoCall(doFunc, callFunc any) *Call { tr := &mockTestReporter{} c := &Call{ t: tr, methodType: reflect.TypeOf(callFunc), } c.Do(doFunc) return c } func prepareDoAndReturnCall(doFunc, callFunc any) *Call { tr := &mockTestReporter{} c := &Call{ t: tr, methodType: reflect.TypeOf(callFunc), } c.DoAndReturn(doFunc) return c } type testCase struct { description string doFunc any callFunc any args []any expectPanic bool } var testCases []testCase = []testCase{ { description: "argument to Do is not a function", doFunc: "meow", callFunc: func(x int, y int) {}, args: []any{0, 1}, expectPanic: true, }, { description: "argument to Do is not a function", doFunc: "meow", callFunc: func(x int, y int) bool { return true }, args: []any{0, 1}, expectPanic: true, }, { description: "number of args for Do func don't match Call func", doFunc: func(x int) {}, callFunc: func(x int, y int) {}, args: []any{0, 1}, expectPanic: false, }, { description: "number of args for Do func don't match Call func", doFunc: func(x int) bool { return true }, callFunc: func(x int, y int) bool { return true }, args: []any{0, 1}, expectPanic: false, }, { description: "arg type for Do func incompatible with Call func", doFunc: func(x int) {}, callFunc: func(x string) {}, args: []any{"meow"}, expectPanic: true, }, { description: "arg type for Do func incompatible with Call func", doFunc: func(x int) bool { return true }, callFunc: func(x string) bool { return true }, args: []any{"meow"}, expectPanic: true, }, { description: "Do func(int) Call func(int)", doFunc: func(x int) {}, callFunc: func(x int) {}, args: []any{0}, }, { description: "Do func(int) Call func(any)", doFunc: func(x int) {}, callFunc: func(x any) {}, args: []any{0}, }, { description: "Do func(int) bool Call func(int) bool", doFunc: func(x int) bool { return true }, callFunc: func(x int) bool { return true }, args: []any{0}, }, { description: "Do func(int) bool Call func(any) bool", doFunc: func(x int) bool { return true }, callFunc: func(x any) bool { return true }, args: []any{0}, }, { description: "Do func(string) Call func([]byte)", doFunc: func(x string) {}, callFunc: func(x []byte) {}, args: []any{[]byte("meow")}, expectPanic: true, }, { description: "Do func(string) bool Call func([]byte) bool", doFunc: func(x string) bool { return true }, callFunc: func(x []byte) bool { return true }, args: []any{[]byte("meow")}, expectPanic: true, }, { description: "Do func(map[int]string) Call func(map[any]int)", doFunc: func(x map[int]string) {}, callFunc: func(x map[any]int) {}, args: []any{map[any]int{"meow": 0}}, expectPanic: true, }, { description: "Do func(map[int]string) Call func(map[any]any)", doFunc: func(x map[int]string) {}, callFunc: func(x map[any]any) {}, args: []any{map[any]any{"meow": "meow"}}, expectPanic: true, }, { description: "Do func(map[int]string) bool Call func(map[any]int) bool", doFunc: func(x map[int]string) bool { return true }, callFunc: func(x map[any]int) bool { return true }, args: []any{map[any]int{"meow": 0}}, expectPanic: true, }, { description: "Do func(map[int]string) bool Call func(map[any]any) bool", doFunc: func(x map[int]string) bool { return true }, callFunc: func(x map[any]any) bool { return true }, args: []any{map[any]any{"meow": "meow"}}, expectPanic: true, }, { description: "Do func([]string) Call func([]any)", doFunc: func(x []string) {}, callFunc: func(x []any) {}, args: []any{[]any{0}}, expectPanic: true, }, { description: "Do func([]string) Call func([]int)", doFunc: func(x []string) {}, callFunc: func(x []int) {}, args: []any{[]int{0, 1}}, expectPanic: true, }, { description: "Do func([]int) Call func([]int)", doFunc: func(x []int) {}, callFunc: func(x []int) {}, args: []any{[]int{0, 1}}, }, { description: "Do func([]int) Call func([]any)", doFunc: func(x []int) {}, callFunc: func(x []any) {}, args: []any{[]any{0}}, expectPanic: true, }, { description: "Do func([]int) Call func(...any)", doFunc: func(x []int) {}, callFunc: func(x ...any) {}, args: []any{0, 1}, expectPanic: true, }, { description: "Do func([]int) Call func(...int)", doFunc: func(x []int) {}, callFunc: func(x ...int) {}, args: []any{0, 1}, expectPanic: true, }, { description: "Do func([]string) bool Call func([]any) bool", doFunc: func(x []string) bool { return true }, callFunc: func(x []any) bool { return true }, args: []any{[]any{0}}, expectPanic: true, }, { description: "Do func([]string) bool Call func([]int) bool", doFunc: func(x []string) bool { return true }, callFunc: func(x []int) bool { return true }, args: []any{[]int{0, 1}}, expectPanic: true, }, { description: "Do func([]int) bool Call func([]int) bool", doFunc: func(x []int) bool { return true }, callFunc: func(x []int) bool { return true }, args: []any{[]int{0, 1}}, }, { description: "Do func([]int) bool Call func([]any) bool", doFunc: func(x []int) bool { return true }, callFunc: func(x []any) bool { return true }, args: []any{[]any{0}}, expectPanic: true, }, { description: "Do func([]int) bool Call func(...any) bool", doFunc: func(x []int) bool { return true }, callFunc: func(x ...any) bool { return true }, args: []any{0, 1}, expectPanic: true, }, { description: "Do func([]int) bool Call func(...int) bool", doFunc: func(x []int) bool { return true }, callFunc: func(x ...int) bool { return true }, args: []any{0, 1}, expectPanic: true, }, { description: "Do func(...int) Call func([]int)", doFunc: func(x ...int) {}, callFunc: func(x []int) {}, args: []any{[]int{0, 1}}, expectPanic: true, }, { description: "Do func(...int) Call func([]any)", doFunc: func(x ...int) {}, callFunc: func(x []any) {}, args: []any{[]any{0, 1}}, expectPanic: true, }, { description: "Do func(...int) Call func(...any)", doFunc: func(x ...int) {}, callFunc: func(x ...any) {}, args: []any{0, 1}, }, { description: "Do func(...int) bool Call func(...int) bool", doFunc: func(x ...int) bool { return true }, callFunc: func(x ...int) bool { return true }, args: []any{0, 1}, }, { description: "Do func(...int) bool Call func([]int) bool", doFunc: func(x ...int) bool { return true }, callFunc: func(x []int) bool { return true }, args: []any{[]int{0, 1}}, expectPanic: true, }, { description: "Do func(...int) bool Call func([]any) bool", doFunc: func(x ...int) bool { return true }, callFunc: func(x []any) bool { return true }, args: []any{[]any{0, 1}}, expectPanic: true, }, { description: "Do func(...int) bool Call func(...any) bool", doFunc: func(x ...int) bool { return true }, callFunc: func(x ...any) bool { return true }, args: []any{0, 1}, }, { description: "Do func(...int) Call func(...int)", doFunc: func(x ...int) {}, callFunc: func(x ...int) {}, args: []any{0, 1}, }, { description: "Do func(foo); foo implements interface X Call func(interface X)", doFunc: func(x foo) {}, callFunc: func(x fmt.Stringer) {}, args: []any{foo{}}, }, { description: "Do func(b); b does not implement interface X Call func(interface X)", doFunc: func(x b) {}, callFunc: func(x fmt.Stringer) {}, args: []any{foo{}}, expectPanic: true, }, { description: "Do func(b) Call func(a); a and b are not aliases", doFunc: func(x b) {}, callFunc: func(x a) {}, args: []any{a{}}, expectPanic: true, }, { description: "Do func(foo) bool; foo implements interface X Call func(interface X) bool", doFunc: func(x foo) bool { return true }, callFunc: func(x fmt.Stringer) bool { return true }, args: []any{foo{}}, }, { description: "Do func(b) bool; b does not implement interface X Call func(interface X) bool", doFunc: func(x b) bool { return true }, callFunc: func(x fmt.Stringer) bool { return true }, args: []any{foo{}}, expectPanic: true, }, { description: "Do func(b) bool Call func(a) bool; a and b are not aliases", doFunc: func(x b) bool { return true }, callFunc: func(x a) bool { return true }, args: []any{a{}}, expectPanic: true, }, { description: "Do func(bool) b Call func(bool) a; a and b are not aliases", doFunc: func(x bool) b { return b{} }, callFunc: func(x bool) a { return a{} }, args: []any{true}, }, } func TestCall_Do(t *testing.T) { for _, tc := range testCases { t.Run(tc.description, func(t *testing.T) { c := prepareDoCall(tc.doFunc, tc.callFunc) if len(c.actions) != 1 { t.Errorf("expected %d actions but got %d", 1, len(c.actions)) } action := c.actions[0] if tc.expectPanic { defer func() { if r := recover(); r == nil { t.Error("expected Do to panic") } }() } action(tc.args) }) } } func TestCall_Do_NumArgValidation(t *testing.T) { tests := []struct { name string methodType reflect.Type doFn any args []any wantErr bool }{ { name: "too few", methodType: reflect.TypeOf(func(one, two string) {}), doFn: func(one string) {}, args: []any{"too", "few"}, wantErr: true, }, { name: "too many", methodType: reflect.TypeOf(func(one, two string) {}), doFn: func(one, two, three string) {}, args: []any{"too", "few"}, wantErr: true, }, { name: "just right", methodType: reflect.TypeOf(func(one, two string) {}), doFn: func(one string, two string) {}, args: []any{"just", "right"}, wantErr: false, }, { name: "variadic", methodType: reflect.TypeOf(func(one, two string) {}), doFn: func(args ...any) {}, args: []any{"just", "right"}, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tr := &mockTestReporter{} call := &Call{ t: tr, methodType: tt.methodType, } call.Do(tt.doFn) call.actions[0](tt.args) if tt.wantErr && tr.fatalCalls != 1 { t.Fatalf("expected call to fail") } if !tt.wantErr && tr.fatalCalls != 0 { t.Fatalf("expected call to pass") } }) } } func TestCall_DoAndReturn_NumArgValidation(t *testing.T) { tests := []struct { name string methodType reflect.Type doFn any args []any wantErr bool }{ { name: "too few", methodType: reflect.TypeOf(func(one, two string) string { return "" }), doFn: func(one string) {}, args: []any{"too", "few"}, wantErr: true, }, { name: "too many", methodType: reflect.TypeOf(func(one, two string) string { return "" }), doFn: func(one, two, three string) string { return "" }, args: []any{"too", "few"}, wantErr: true, }, { name: "just right", methodType: reflect.TypeOf(func(one, two string) string { return "" }), doFn: func(one string, two string) string { return "" }, args: []any{"just", "right"}, wantErr: false, }, { name: "variadic", methodType: reflect.TypeOf(func(one, two string) {}), doFn: func(args ...any) string { return "" }, args: []any{"just", "right"}, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tr := &mockTestReporter{} call := &Call{ t: tr, methodType: tt.methodType, } call.DoAndReturn(tt.doFn) call.actions[0](tt.args) if tt.wantErr && tr.fatalCalls != 1 { t.Fatalf("expected call to fail") } if !tt.wantErr && tr.fatalCalls != 0 { t.Fatalf("expected call to pass") } }) } } func TestCall_DoAndReturn(t *testing.T) { for _, tc := range testCases { t.Run(tc.description, func(t *testing.T) { c := prepareDoAndReturnCall(tc.doFunc, tc.callFunc) if len(c.actions) != 1 { t.Errorf("expected %d actions but got %d", 1, len(c.actions)) } action := c.actions[0] if tc.expectPanic { defer func() { if r := recover(); r == nil { t.Error("expected DoAndReturn to panic") } }() } action(tc.args) }) } } func TestInOrder(t *testing.T) { t.Run("process only *Call or its wrappers", func(t *testing.T) { tr1 := &mockTestReporter{} tr2 := &mockTestReporter{} c1 := &Call{t: tr1} c2 := &c{Call: &Call{t: tr2}} InOrder(c1, c2) if len(c2.preReqs) != 1 { t.Fatalf("expected 1 preReq in c2, found %d", len(c2.preReqs)) } if len(c1.preReqs) != 0 { t.Fatalf("expected 0 preReq in c1, found %d", len(c1.preReqs)) } }) t.Run("panic when the argument isn't a *Call or has one embedded", func(t *testing.T) { defer func() { if r := recover(); r == nil { t.Error("expected InOrder to panic") } }() tr := &mockTestReporter{} c := &Call{t: tr} a := &a{ name: "Foo", } InOrder(c, a) }) } golang-go.uber-mock-0.5.0/gomock/callset.go000066400000000000000000000077731470430142200205210ustar00rootroot00000000000000// Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gomock import ( "bytes" "errors" "fmt" "sync" ) // callSet represents a set of expected calls, indexed by receiver and method // name. type callSet struct { // Calls that are still expected. expected map[callSetKey][]*Call expectedMu *sync.Mutex // Calls that have been exhausted. exhausted map[callSetKey][]*Call // when set to true, existing call expectations are overridden when new call expectations are made allowOverride bool } // callSetKey is the key in the maps in callSet type callSetKey struct { receiver any fname string } func newCallSet() *callSet { return &callSet{ expected: make(map[callSetKey][]*Call), expectedMu: &sync.Mutex{}, exhausted: make(map[callSetKey][]*Call), } } func newOverridableCallSet() *callSet { return &callSet{ expected: make(map[callSetKey][]*Call), expectedMu: &sync.Mutex{}, exhausted: make(map[callSetKey][]*Call), allowOverride: true, } } // Add adds a new expected call. func (cs callSet) Add(call *Call) { key := callSetKey{call.receiver, call.method} cs.expectedMu.Lock() defer cs.expectedMu.Unlock() m := cs.expected if call.exhausted() { m = cs.exhausted } if cs.allowOverride { m[key] = make([]*Call, 0) } m[key] = append(m[key], call) } // Remove removes an expected call. func (cs callSet) Remove(call *Call) { key := callSetKey{call.receiver, call.method} cs.expectedMu.Lock() defer cs.expectedMu.Unlock() calls := cs.expected[key] for i, c := range calls { if c == call { // maintain order for remaining calls cs.expected[key] = append(calls[:i], calls[i+1:]...) cs.exhausted[key] = append(cs.exhausted[key], call) break } } } // FindMatch searches for a matching call. Returns error with explanation message if no call matched. func (cs callSet) FindMatch(receiver any, method string, args []any) (*Call, error) { key := callSetKey{receiver, method} cs.expectedMu.Lock() defer cs.expectedMu.Unlock() // Search through the expected calls. expected := cs.expected[key] var callsErrors bytes.Buffer for _, call := range expected { err := call.matches(args) if err != nil { _, _ = fmt.Fprintf(&callsErrors, "\n%v", err) } else { return call, nil } } // If we haven't found a match then search through the exhausted calls so we // get useful error messages. exhausted := cs.exhausted[key] for _, call := range exhausted { if err := call.matches(args); err != nil { _, _ = fmt.Fprintf(&callsErrors, "\n%v", err) continue } _, _ = fmt.Fprintf( &callsErrors, "all expected calls for method %q have been exhausted", method, ) } if len(expected)+len(exhausted) == 0 { _, _ = fmt.Fprintf(&callsErrors, "there are no expected calls of the method %q for that receiver", method) } return nil, errors.New(callsErrors.String()) } // Failures returns the calls that are not satisfied. func (cs callSet) Failures() []*Call { cs.expectedMu.Lock() defer cs.expectedMu.Unlock() failures := make([]*Call, 0, len(cs.expected)) for _, calls := range cs.expected { for _, call := range calls { if !call.satisfied() { failures = append(failures, call) } } } return failures } // Satisfied returns true in case all expected calls in this callSet are satisfied. func (cs callSet) Satisfied() bool { cs.expectedMu.Lock() defer cs.expectedMu.Unlock() for _, calls := range cs.expected { for _, call := range calls { if !call.satisfied() { return false } } } return true } golang-go.uber-mock-0.5.0/gomock/callset_test.go000066400000000000000000000063221470430142200215450ustar00rootroot00000000000000// Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gomock import ( "reflect" "testing" ) type receiverType struct{} func (receiverType) Func() {} func TestCallSetAdd(t *testing.T) { method := "TestMethod" var receiver any = "TestReceiver" cs := newCallSet() numCalls := 10 for i := 0; i < numCalls; i++ { cs.Add(newCall(t, receiver, method, reflect.TypeOf(receiverType{}.Func))) } call, err := cs.FindMatch(receiver, method, []any{}) if err != nil { t.Fatalf("FindMatch: %v", err) } if call == nil { t.Fatalf("FindMatch: Got nil, want non-nil *Call") } } func TestCallSetAdd_WhenOverridable_ClearsPreviousExpectedAndExhausted(t *testing.T) { method := "TestMethod" var receiver any = "TestReceiver" cs := newOverridableCallSet() cs.Add(newCall(t, receiver, method, reflect.TypeOf(receiverType{}.Func))) numExpectedCalls := len(cs.expected[callSetKey{receiver, method}]) if numExpectedCalls != 1 { t.Fatalf("Expected 1 expected call in callset, got %d", numExpectedCalls) } cs.Add(newCall(t, receiver, method, reflect.TypeOf(receiverType{}.Func))) newNumExpectedCalls := len(cs.expected[callSetKey{receiver, method}]) if newNumExpectedCalls != 1 { t.Fatalf("Expected 1 expected call in callset, got %d", newNumExpectedCalls) } } func TestCallSetRemove(t *testing.T) { method := "TestMethod" var receiver any = "TestReceiver" cs := newCallSet() ourCalls := []*Call{} numCalls := 10 for i := 0; i < numCalls; i++ { // NOTE: abuse the `numCalls` value to convey initial ordering of mocked calls generatedCall := &Call{receiver: receiver, method: method, numCalls: i} cs.Add(generatedCall) ourCalls = append(ourCalls, generatedCall) } // validateOrder validates that the calls in the array are ordered as they were added validateOrder := func(calls []*Call) { // lastNum tracks the last `numCalls` (call order) value seen lastNum := -1 for _, c := range calls { if lastNum >= c.numCalls { t.Errorf("found call %d after call %d", c.numCalls, lastNum) } lastNum = c.numCalls } } for _, c := range ourCalls { validateOrder(cs.expected[callSetKey{receiver, method}]) cs.Remove(c) } } func TestCallSetFindMatch(t *testing.T) { t.Run("call is exhausted", func(t *testing.T) { cs := newCallSet() var receiver any = "TestReceiver" method := "TestMethod" args := []any{} c1 := newCall(t, receiver, method, reflect.TypeOf(receiverType{}.Func)) cs.exhausted = map[callSetKey][]*Call{ {receiver: receiver, fname: method}: {c1}, } _, err := cs.FindMatch(receiver, method, args) if err == nil { t.Fatal("expected error, but was nil") } if err.Error() == "" { t.Fatal("expected error to have message, but was empty") } }) } golang-go.uber-mock-0.5.0/gomock/controller.go000066400000000000000000000221631470430142200212430ustar00rootroot00000000000000// Copyright 2010 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gomock import ( "context" "fmt" "reflect" "runtime" "sync" ) // A TestReporter is something that can be used to report test failures. It // is satisfied by the standard library's *testing.T. type TestReporter interface { Errorf(format string, args ...any) Fatalf(format string, args ...any) } // TestHelper is a TestReporter that has the Helper method. It is satisfied // by the standard library's *testing.T. type TestHelper interface { TestReporter Helper() } // cleanuper is used to check if TestHelper also has the `Cleanup` method. A // common pattern is to pass in a `*testing.T` to // `NewController(t TestReporter)`. In Go 1.14+, `*testing.T` has a cleanup // method. This can be utilized to call `Finish()` so the caller of this library // does not have to. type cleanuper interface { Cleanup(func()) } // A Controller represents the top-level control of a mock ecosystem. It // defines the scope and lifetime of mock objects, as well as their // expectations. It is safe to call Controller's methods from multiple // goroutines. Each test should create a new Controller. // // func TestFoo(t *testing.T) { // ctrl := gomock.NewController(t) // // .. // } // // func TestBar(t *testing.T) { // t.Run("Sub-Test-1", st) { // ctrl := gomock.NewController(st) // // .. // }) // t.Run("Sub-Test-2", st) { // ctrl := gomock.NewController(st) // // .. // }) // }) type Controller struct { // T should only be called within a generated mock. It is not intended to // be used in user code and may be changed in future versions. T is the // TestReporter passed in when creating the Controller via NewController. // If the TestReporter does not implement a TestHelper it will be wrapped // with a nopTestHelper. T TestHelper mu sync.Mutex expectedCalls *callSet finished bool } // NewController returns a new Controller. It is the preferred way to create a Controller. // // Passing [*testing.T] registers cleanup function to automatically call [Controller.Finish] // when the test and all its subtests complete. func NewController(t TestReporter, opts ...ControllerOption) *Controller { h, ok := t.(TestHelper) if !ok { h = &nopTestHelper{t} } ctrl := &Controller{ T: h, expectedCalls: newCallSet(), } for _, opt := range opts { opt.apply(ctrl) } if c, ok := isCleanuper(ctrl.T); ok { c.Cleanup(func() { ctrl.T.Helper() ctrl.finish(true, nil) }) } return ctrl } // ControllerOption configures how a Controller should behave. type ControllerOption interface { apply(*Controller) } type overridableExpectationsOption struct{} // WithOverridableExpectations allows for overridable call expectations // i.e., subsequent call expectations override existing call expectations func WithOverridableExpectations() overridableExpectationsOption { return overridableExpectationsOption{} } func (o overridableExpectationsOption) apply(ctrl *Controller) { ctrl.expectedCalls = newOverridableCallSet() } type cancelReporter struct { t TestHelper cancel func() } func (r *cancelReporter) Errorf(format string, args ...any) { r.t.Errorf(format, args...) } func (r *cancelReporter) Fatalf(format string, args ...any) { defer r.cancel() r.t.Fatalf(format, args...) } func (r *cancelReporter) Helper() { r.t.Helper() } // WithContext returns a new Controller and a Context, which is cancelled on any // fatal failure. func WithContext(ctx context.Context, t TestReporter) (*Controller, context.Context) { h, ok := t.(TestHelper) if !ok { h = &nopTestHelper{t: t} } ctx, cancel := context.WithCancel(ctx) return NewController(&cancelReporter{t: h, cancel: cancel}), ctx } type nopTestHelper struct { t TestReporter } func (h *nopTestHelper) Errorf(format string, args ...any) { h.t.Errorf(format, args...) } func (h *nopTestHelper) Fatalf(format string, args ...any) { h.t.Fatalf(format, args...) } func (h nopTestHelper) Helper() {} // RecordCall is called by a mock. It should not be called by user code. func (ctrl *Controller) RecordCall(receiver any, method string, args ...any) *Call { ctrl.T.Helper() recv := reflect.ValueOf(receiver) for i := 0; i < recv.Type().NumMethod(); i++ { if recv.Type().Method(i).Name == method { return ctrl.RecordCallWithMethodType(receiver, method, recv.Method(i).Type(), args...) } } ctrl.T.Fatalf("gomock: failed finding method %s on %T", method, receiver) panic("unreachable") } // RecordCallWithMethodType is called by a mock. It should not be called by user code. func (ctrl *Controller) RecordCallWithMethodType(receiver any, method string, methodType reflect.Type, args ...any) *Call { ctrl.T.Helper() call := newCall(ctrl.T, receiver, method, methodType, args...) ctrl.mu.Lock() defer ctrl.mu.Unlock() ctrl.expectedCalls.Add(call) return call } // Call is called by a mock. It should not be called by user code. func (ctrl *Controller) Call(receiver any, method string, args ...any) []any { ctrl.T.Helper() // Nest this code so we can use defer to make sure the lock is released. actions := func() []func([]any) []any { ctrl.T.Helper() ctrl.mu.Lock() defer ctrl.mu.Unlock() expected, err := ctrl.expectedCalls.FindMatch(receiver, method, args) if err != nil { // callerInfo's skip should be updated if the number of calls between the user's test // and this line changes, i.e. this code is wrapped in another anonymous function. // 0 is us, 1 is controller.Call(), 2 is the generated mock, and 3 is the user's test. origin := callerInfo(3) stringArgs := make([]string, len(args)) for i, arg := range args { stringArgs[i] = getString(arg) } ctrl.T.Fatalf("Unexpected call to %T.%v(%v) at %s because: %s", receiver, method, stringArgs, origin, err) } // Two things happen here: // * the matching call no longer needs to check prerequisite calls, // * and the prerequisite calls are no longer expected, so remove them. preReqCalls := expected.dropPrereqs() for _, preReqCall := range preReqCalls { ctrl.expectedCalls.Remove(preReqCall) } actions := expected.call() if expected.exhausted() { ctrl.expectedCalls.Remove(expected) } return actions }() var rets []any for _, action := range actions { if r := action(args); r != nil { rets = r } } return rets } // Finish checks to see if all the methods that were expected to be called were called. // It is not idempotent and therefore can only be invoked once. // // Note: If you pass a *testing.T into [NewController], you no longer // need to call ctrl.Finish() in your test methods. func (ctrl *Controller) Finish() { // If we're currently panicking, probably because this is a deferred call. // This must be recovered in the deferred function. err := recover() ctrl.finish(false, err) } // Satisfied returns whether all expected calls bound to this Controller have been satisfied. // Calling Finish is then guaranteed to not fail due to missing calls. func (ctrl *Controller) Satisfied() bool { ctrl.mu.Lock() defer ctrl.mu.Unlock() return ctrl.expectedCalls.Satisfied() } func (ctrl *Controller) finish(cleanup bool, panicErr any) { ctrl.T.Helper() ctrl.mu.Lock() defer ctrl.mu.Unlock() if ctrl.finished { if _, ok := isCleanuper(ctrl.T); !ok { ctrl.T.Fatalf("Controller.Finish was called more than once. It has to be called exactly once.") } return } ctrl.finished = true // Short-circuit, pass through the panic. if panicErr != nil { panic(panicErr) } // Check that all remaining expected calls are satisfied. failures := ctrl.expectedCalls.Failures() for _, call := range failures { ctrl.T.Errorf("missing call(s) to %v", call) } if len(failures) != 0 { if !cleanup { ctrl.T.Fatalf("aborting test due to missing call(s)") return } ctrl.T.Errorf("aborting test due to missing call(s)") } } // callerInfo returns the file:line of the call site. skip is the number // of stack frames to skip when reporting. 0 is callerInfo's call site. func callerInfo(skip int) string { if _, file, line, ok := runtime.Caller(skip + 1); ok { return fmt.Sprintf("%s:%d", file, line) } return "unknown file" } // isCleanuper checks it if t's base TestReporter has a Cleanup method. func isCleanuper(t TestReporter) (cleanuper, bool) { tr := unwrapTestReporter(t) c, ok := tr.(cleanuper) return c, ok } // unwrapTestReporter unwraps TestReporter to the base implementation. func unwrapTestReporter(t TestReporter) TestReporter { tr := t switch nt := t.(type) { case *cancelReporter: tr = nt.t if h, check := tr.(*nopTestHelper); check { tr = h.t } case *nopTestHelper: tr = nt.t default: // not wrapped } return tr } golang-go.uber-mock-0.5.0/gomock/controller_test.go000066400000000000000000000627261470430142200223130ustar00rootroot00000000000000// Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gomock_test import ( "fmt" "reflect" "strings" "testing" "go.uber.org/mock/gomock" ) type ErrorReporter struct { t *testing.T log []string failed bool fatalToken struct{} } func NewErrorReporter(t *testing.T) *ErrorReporter { return &ErrorReporter{t: t} } func (e *ErrorReporter) reportLog() { for _, entry := range e.log { e.t.Log(entry) } } func (e *ErrorReporter) assertPass(msg string) { if e.failed { e.t.Errorf("Expected pass, but got failure(s): %s", msg) e.reportLog() } } func (e *ErrorReporter) assertFail(msg string) { if !e.failed { e.t.Errorf("Expected failure, but got pass: %s", msg) } } // Use to check that code triggers a fatal test failure. func (e *ErrorReporter) assertFatal(fn func(), expectedErrMsgs ...string) { defer func() { err := recover() if err == nil { var actual string if e.failed { actual = "non-fatal failure" } else { actual = "pass" } e.t.Error("Expected fatal failure, but got a", actual) } else if token, ok := err.(*struct{}); ok && token == &e.fatalToken { // This is okay - the panic is from Fatalf(). if expectedErrMsgs != nil { // assert that the actual error message // contains expectedErrMsgs // check the last actualErrMsg, because the previous messages come from previous errors actualErrMsg := e.log[len(e.log)-1] for _, expectedErrMsg := range expectedErrMsgs { if !strings.Contains(actualErrMsg, expectedErrMsg) { e.t.Errorf("Error message:\ngot: %q\nwant to contain: %q\n", actualErrMsg, expectedErrMsg) } } } return } else { // Some other panic. panic(err) } }() fn() } // recoverUnexpectedFatal can be used as a deferred call in test cases to // recover from and display a call to ErrorReporter.Fatalf(). func (e *ErrorReporter) recoverUnexpectedFatal() { err := recover() if err == nil { // No panic. } else if token, ok := err.(*struct{}); ok && token == &e.fatalToken { // Unexpected fatal error happened. e.t.Error("Got unexpected fatal error(s). All errors up to this point:") e.reportLog() return } else { // Some other panic. panic(err) } } func (e *ErrorReporter) Log(args ...any) { e.log = append(e.log, fmt.Sprint(args...)) } func (e *ErrorReporter) Logf(format string, args ...any) { e.log = append(e.log, fmt.Sprintf(format, args...)) } func (e *ErrorReporter) Errorf(format string, args ...any) { e.Logf(format, args...) e.failed = true } func (e *ErrorReporter) Fatalf(format string, args ...any) { e.Logf(format, args...) e.failed = true panic(&e.fatalToken) } type HelperReporter struct { gomock.TestReporter helper int } func (h *HelperReporter) Helper() { h.helper++ } // A type purely for use as a receiver in testing the Controller. type Subject struct{} func (s *Subject) FooMethod(arg string) int { return 0 } func (s *Subject) BarMethod(arg string) int { return 0 } func (s *Subject) VariadicMethod(arg int, vararg ...string) {} // A type purely for ActOnTestStructMethod type TestStruct struct { Number int Message string } func (s *Subject) ActOnTestStructMethod(arg TestStruct, arg1 int) int { return 0 } func (s *Subject) SetArgMethod(sliceArg []byte, ptrArg *int, mapArg map[any]any) {} func (s *Subject) SetArgMethodInterface(sliceArg, ptrArg, mapArg any) {} func assertEqual(t *testing.T, expected any, actual any) { if !reflect.DeepEqual(expected, actual) { t.Errorf("Expected %+v, but got %+v", expected, actual) } } func createFixtures(t *testing.T) (reporter *ErrorReporter, ctrl *gomock.Controller) { // reporter acts as a testing.T-like object that we pass to the // Controller. We use it to test that the mock considered tests // successful or failed. reporter = NewErrorReporter(t) ctrl = gomock.NewController(reporter) return } func TestNoCalls(t *testing.T) { reporter, _ := createFixtures(t) reporter.assertPass("No calls expected or made.") } func TestNoRecordedCallsForAReceiver(t *testing.T) { reporter, ctrl := createFixtures(t) subject := new(Subject) reporter.assertFatal(func() { ctrl.Call(subject, "NotRecordedMethod", "argument") }, "Unexpected call to", "there are no expected calls of the method \"NotRecordedMethod\" for that receiver") } func TestNoRecordedMatchingMethodNameForAReceiver(t *testing.T) { reporter, ctrl := createFixtures(t) subject := new(Subject) ctrl.RecordCall(subject, "FooMethod", "argument") reporter.assertFatal(func() { ctrl.Call(subject, "NotRecordedMethod", "argument") }, "Unexpected call to", "there are no expected calls of the method \"NotRecordedMethod\" for that receiver") reporter.assertFatal(func() { // The expected call wasn't made. ctrl.Finish() }) } func TestNoStringerDeadlockOnError(t *testing.T) { reporter, ctrl := createFixtures(t) subject := new(Subject) mockFoo := NewMockFoo(ctrl) var _ fmt.Stringer = mockFoo ctrl.RecordCall(subject, "FooMethod", mockFoo) reporter.assertFatal(func() { ctrl.Call(subject, "NotRecordedMethod", mockFoo) }, "Unexpected call to", "there are no expected calls of the method \"NotRecordedMethod\" for that receiver") reporter.assertFatal(func() { // The expected call wasn't made. ctrl.Finish() }) } // This tests that a call with an arguments of some primitive type matches a recorded call. func TestExpectedMethodCall(t *testing.T) { reporter, ctrl := createFixtures(t) subject := new(Subject) ctrl.RecordCall(subject, "FooMethod", "argument") ctrl.Call(subject, "FooMethod", "argument") reporter.assertPass("Expected method call made.") } func TestUnexpectedMethodCall(t *testing.T) { reporter, ctrl := createFixtures(t) subject := new(Subject) reporter.assertFatal(func() { ctrl.Call(subject, "FooMethod", "argument") }) } func TestRepeatedCall(t *testing.T) { reporter, ctrl := createFixtures(t) subject := new(Subject) ctrl.RecordCall(subject, "FooMethod", "argument").Times(3) ctrl.Call(subject, "FooMethod", "argument") ctrl.Call(subject, "FooMethod", "argument") ctrl.Call(subject, "FooMethod", "argument") reporter.assertPass("After expected repeated method calls.") reporter.assertFatal(func() { ctrl.Call(subject, "FooMethod", "argument") }) reporter.assertFail("After calling one too many times.") } func TestUnexpectedArgCount(t *testing.T) { reporter, ctrl := createFixtures(t) defer reporter.recoverUnexpectedFatal() subject := new(Subject) ctrl.RecordCall(subject, "FooMethod", "argument") reporter.assertFatal(func() { // This call is made with the wrong number of arguments... ctrl.Call(subject, "FooMethod", "argument", "extra_argument") }, "Unexpected call to", "wrong number of arguments", "Got: 2, want: 1") reporter.assertFatal(func() { // ... so is this. ctrl.Call(subject, "FooMethod") }, "Unexpected call to", "wrong number of arguments", "Got: 0, want: 1") reporter.assertFatal(func() { // The expected call wasn't made. ctrl.Finish() }) } // This tests that a call with complex arguments (a struct and some primitive type) matches a recorded call. func TestExpectedMethodCall_CustomStruct(t *testing.T) { reporter, ctrl := createFixtures(t) subject := new(Subject) expectedArg0 := TestStruct{Number: 123, Message: "hello"} ctrl.RecordCall(subject, "ActOnTestStructMethod", expectedArg0, 15) ctrl.Call(subject, "ActOnTestStructMethod", expectedArg0, 15) reporter.assertPass("Expected method call made.") } func TestUnexpectedArgValue_FirstArg(t *testing.T) { reporter, ctrl := createFixtures(t) defer reporter.recoverUnexpectedFatal() subject := new(Subject) expectedArg0 := TestStruct{Number: 123, Message: "hello %s"} ctrl.RecordCall(subject, "ActOnTestStructMethod", expectedArg0, 15) reporter.assertFatal(func() { // the method argument (of TestStruct type) has 1 unexpected value (for the Message field) ctrl.Call(subject, "ActOnTestStructMethod", TestStruct{Number: 123, Message: "no message"}, 15) }, "Unexpected call to", "doesn't match the argument at index 0", "Got: {123 no message} (gomock_test.TestStruct)\nWant: is equal to {123 hello %s} (gomock_test.TestStruct)") reporter.assertFatal(func() { // the method argument (of TestStruct type) has 2 unexpected values (for both fields) ctrl.Call(subject, "ActOnTestStructMethod", TestStruct{Number: 11, Message: "no message"}, 15) }, "Unexpected call to", "doesn't match the argument at index 0", "Got: {11 no message} (gomock_test.TestStruct)\nWant: is equal to {123 hello %s} (gomock_test.TestStruct)") reporter.assertFatal(func() { // The expected call wasn't made. ctrl.Finish() }) } func TestUnexpectedArgValue_SecondArg(t *testing.T) { reporter, ctrl := createFixtures(t) defer reporter.recoverUnexpectedFatal() subject := new(Subject) expectedArg0 := TestStruct{Number: 123, Message: "hello"} ctrl.RecordCall(subject, "ActOnTestStructMethod", expectedArg0, 15) reporter.assertFatal(func() { ctrl.Call(subject, "ActOnTestStructMethod", TestStruct{Number: 123, Message: "hello"}, 3) }, "Unexpected call to", "doesn't match the argument at index 1", "Got: 3 (int)\nWant: is equal to 15 (int)") reporter.assertFatal(func() { // The expected call wasn't made. ctrl.Finish() }) } func TestUnexpectedArgValue_WantFormatter(t *testing.T) { reporter, ctrl := createFixtures(t) defer reporter.recoverUnexpectedFatal() subject := new(Subject) expectedArg0 := TestStruct{Number: 123, Message: "hello"} ctrl.RecordCall( subject, "ActOnTestStructMethod", expectedArg0, gomock.WantFormatter( gomock.StringerFunc(func() string { return "is equal to fifteen" }), gomock.Eq(15), ), ) reporter.assertFatal(func() { ctrl.Call(subject, "ActOnTestStructMethod", TestStruct{Number: 123, Message: "hello"}, 3) }, "Unexpected call to", "doesn't match the argument at index 1", "Got: 3 (int)\nWant: is equal to fifteen") reporter.assertFatal(func() { // The expected call wasn't made. ctrl.Finish() }) } func TestUnexpectedArgValue_GotFormatter(t *testing.T) { reporter, ctrl := createFixtures(t) defer reporter.recoverUnexpectedFatal() subject := new(Subject) expectedArg0 := TestStruct{Number: 123, Message: "hello"} ctrl.RecordCall( subject, "ActOnTestStructMethod", expectedArg0, gomock.GotFormatterAdapter( gomock.GotFormatterFunc(func(i any) string { // Leading 0s return fmt.Sprintf("%02d", i) }), gomock.Eq(15), ), ) reporter.assertFatal(func() { ctrl.Call(subject, "ActOnTestStructMethod", TestStruct{Number: 123, Message: "hello"}, 3) }, "Unexpected call to", "doesn't match the argument at index 1", "Got: 03\nWant: is equal to 15") reporter.assertFatal(func() { // The expected call wasn't made. ctrl.Finish() }) } func TestAnyTimes(t *testing.T) { reporter, ctrl := createFixtures(t) subject := new(Subject) ctrl.RecordCall(subject, "FooMethod", "argument").AnyTimes() for i := 0; i < 100; i++ { ctrl.Call(subject, "FooMethod", "argument") } reporter.assertPass("After 100 method calls.") } func TestMinTimes1(t *testing.T) { // It fails if there are no calls reporter, ctrl := createFixtures(t) subject := new(Subject) ctrl.RecordCall(subject, "FooMethod", "argument").MinTimes(1) reporter.assertFatal(func() { ctrl.Finish() }) // It succeeds if there is one call _, ctrl = createFixtures(t) subject = new(Subject) ctrl.RecordCall(subject, "FooMethod", "argument").MinTimes(1) ctrl.Call(subject, "FooMethod", "argument") ctrl.Finish() // It succeeds if there are many calls _, ctrl = createFixtures(t) subject = new(Subject) ctrl.RecordCall(subject, "FooMethod", "argument").MinTimes(1) for i := 0; i < 100; i++ { ctrl.Call(subject, "FooMethod", "argument") } ctrl.Finish() } func TestMaxTimes1(t *testing.T) { // It succeeds if there are no calls _, ctrl := createFixtures(t) subject := new(Subject) ctrl.RecordCall(subject, "FooMethod", "argument").MaxTimes(1) ctrl.Finish() // It succeeds if there is one call _, ctrl = createFixtures(t) subject = new(Subject) ctrl.RecordCall(subject, "FooMethod", "argument").MaxTimes(1) ctrl.Call(subject, "FooMethod", "argument") ctrl.Finish() // It fails if there are more reporter, ctrl := createFixtures(t) subject = new(Subject) ctrl.RecordCall(subject, "FooMethod", "argument").MaxTimes(1) ctrl.Call(subject, "FooMethod", "argument") reporter.assertFatal(func() { ctrl.Call(subject, "FooMethod", "argument") }) ctrl.Finish() } func TestMinMaxTimes(t *testing.T) { // It fails if there are less calls than specified reporter, ctrl := createFixtures(t) subject := new(Subject) ctrl.RecordCall(subject, "FooMethod", "argument").MinTimes(2).MaxTimes(2) ctrl.Call(subject, "FooMethod", "argument") reporter.assertFatal(func() { ctrl.Finish() }) // It fails if there are more calls than specified reporter, ctrl = createFixtures(t) subject = new(Subject) ctrl.RecordCall(subject, "FooMethod", "argument").MinTimes(2).MaxTimes(2) ctrl.Call(subject, "FooMethod", "argument") ctrl.Call(subject, "FooMethod", "argument") reporter.assertFatal(func() { ctrl.Call(subject, "FooMethod", "argument") }) // It succeeds if there is just the right number of calls _, ctrl = createFixtures(t) subject = new(Subject) ctrl.RecordCall(subject, "FooMethod", "argument").MaxTimes(2).MinTimes(2) ctrl.Call(subject, "FooMethod", "argument") ctrl.Call(subject, "FooMethod", "argument") ctrl.Finish() // If MaxTimes is called after MinTimes is called with 1, MaxTimes takes precedence. reporter, ctrl = createFixtures(t) subject = new(Subject) ctrl.RecordCall(subject, "FooMethod", "argument").MinTimes(1).MaxTimes(2) ctrl.Call(subject, "FooMethod", "argument") ctrl.Call(subject, "FooMethod", "argument") reporter.assertFatal(func() { ctrl.Call(subject, "FooMethod", "argument") }) // If MinTimes is called after MaxTimes is called with 1, MinTimes takes precedence. _, ctrl = createFixtures(t) subject = new(Subject) ctrl.RecordCall(subject, "FooMethod", "argument").MaxTimes(1).MinTimes(2) for i := 0; i < 100; i++ { ctrl.Call(subject, "FooMethod", "argument") } ctrl.Finish() } func TestDo(t *testing.T) { _, ctrl := createFixtures(t) subject := new(Subject) doCalled := false var argument string wantArg := "argument" ctrl.RecordCall(subject, "FooMethod", wantArg).Do( func(arg string) { doCalled = true argument = arg }) if doCalled { t.Error("Do() callback called too early.") } ctrl.Call(subject, "FooMethod", wantArg) if !doCalled { t.Error("Do() callback not called.") } if wantArg != argument { t.Error("Do callback received wrong argument.") } } func TestDoAndReturn(t *testing.T) { _, ctrl := createFixtures(t) subject := new(Subject) doCalled := false var argument string wantArg := "argument" ctrl.RecordCall(subject, "FooMethod", wantArg).DoAndReturn( func(arg string) int { doCalled = true argument = arg return 5 }) if doCalled { t.Error("Do() callback called too early.") } rets := ctrl.Call(subject, "FooMethod", wantArg) if !doCalled { t.Error("Do() callback not called.") } if wantArg != argument { t.Error("Do callback received wrong argument.") } if len(rets) != 1 { t.Fatalf("Return values from Call: got %d, want 1", len(rets)) } if ret, ok := rets[0].(int); !ok { t.Fatalf("Return value is not an int") } else if ret != 5 { t.Errorf("DoAndReturn return value: got %d, want 5", ret) } } func TestSetArgSlice(t *testing.T) { _, ctrl := createFixtures(t) subject := new(Subject) in := []byte{4, 5, 6} set := []byte{1, 2, 3} ctrl.RecordCall(subject, "SetArgMethod", in, nil, nil).SetArg(0, set) ctrl.Call(subject, "SetArgMethod", in, nil, nil) if !reflect.DeepEqual(in, set) { t.Error("Expected SetArg() to modify input slice argument") } ctrl.RecordCall(subject, "SetArgMethodInterface", in, nil, nil).SetArg(0, set) ctrl.Call(subject, "SetArgMethodInterface", in, nil, nil) if !reflect.DeepEqual(in, set) { t.Error("Expected SetArg() to modify input slice argument as any") } } func TestSetArgMap(t *testing.T) { _, ctrl := createFixtures(t) subject := new(Subject) in := map[any]any{"int": 1, "string": "random string", 1: "1", 0: 0} set := map[any]any{"int": 2, 1: "2", 2: 100} ctrl.RecordCall(subject, "SetArgMethod", nil, nil, in).SetArg(2, set) ctrl.Call(subject, "SetArgMethod", nil, nil, in) if !reflect.DeepEqual(in, set) { t.Error("Expected SetArg() to modify input map argument") } ctrl.RecordCall(subject, "SetArgMethodInterface", nil, nil, in).SetArg(2, set) ctrl.Call(subject, "SetArgMethodInterface", nil, nil, in) if !reflect.DeepEqual(in, set) { t.Error("Expected SetArg() to modify input map argument as any") } } func TestSetArgPtr(t *testing.T) { _, ctrl := createFixtures(t) subject := new(Subject) var in int = 43 const set = 42 ctrl.RecordCall(subject, "SetArgMethod", nil, &in, nil).SetArg(1, set) ctrl.Call(subject, "SetArgMethod", nil, &in, nil) if in != set { t.Error("Expected SetArg() to modify value pointed to by argument") } ctrl.RecordCall(subject, "SetArgMethodInterface", nil, &in, nil).SetArg(1, set) ctrl.Call(subject, "SetArgMethodInterface", nil, &in, nil) if in != set { t.Error("Expected SetArg() to modify value pointed to by argument as any") } } func TestReturn(t *testing.T) { _, ctrl := createFixtures(t) subject := new(Subject) // Unspecified return should produce "zero" result. ctrl.RecordCall(subject, "FooMethod", "zero") ctrl.RecordCall(subject, "FooMethod", "five").Return(5) assertEqual( t, []any{0}, ctrl.Call(subject, "FooMethod", "zero")) assertEqual( t, []any{5}, ctrl.Call(subject, "FooMethod", "five")) } func TestUnorderedCalls(t *testing.T) { reporter, ctrl := createFixtures(t) defer reporter.recoverUnexpectedFatal() subjectTwo := new(Subject) subjectOne := new(Subject) ctrl.RecordCall(subjectOne, "FooMethod", "1") ctrl.RecordCall(subjectOne, "BarMethod", "2") ctrl.RecordCall(subjectTwo, "FooMethod", "3") ctrl.RecordCall(subjectTwo, "BarMethod", "4") // Make the calls in a different order, which should be fine. ctrl.Call(subjectOne, "BarMethod", "2") ctrl.Call(subjectTwo, "FooMethod", "3") ctrl.Call(subjectTwo, "BarMethod", "4") ctrl.Call(subjectOne, "FooMethod", "1") reporter.assertPass("After making all calls in different order") ctrl.Finish() reporter.assertPass("After finish") } func commonTestOrderedCalls(t *testing.T) (reporter *ErrorReporter, ctrl *gomock.Controller, subjectOne, subjectTwo *Subject) { reporter, ctrl = createFixtures(t) subjectOne = new(Subject) subjectTwo = new(Subject) gomock.InOrder( ctrl.RecordCall(subjectOne, "FooMethod", "1").AnyTimes(), ctrl.RecordCall(subjectTwo, "FooMethod", "2"), ctrl.RecordCall(subjectTwo, "BarMethod", "3"), ) return } func TestOrderedCallsCorrect(t *testing.T) { reporter, ctrl, subjectOne, subjectTwo := commonTestOrderedCalls(t) ctrl.Call(subjectOne, "FooMethod", "1") ctrl.Call(subjectTwo, "FooMethod", "2") ctrl.Call(subjectTwo, "BarMethod", "3") ctrl.Finish() reporter.assertPass("After finish") } func TestPanicOverridesExpectationChecks(t *testing.T) { ctrl := gomock.NewController(t) reporter := NewErrorReporter(t) reporter.assertFatal(func() { ctrl.RecordCall(new(Subject), "FooMethod", "1") defer ctrl.Finish() reporter.Fatalf("Intentional panic") }) } func TestSetArgWithBadType(t *testing.T) { rep, ctrl := createFixtures(t) s := new(Subject) // This should catch a type error: rep.assertFatal(func() { ctrl.RecordCall(s, "FooMethod", "1").SetArg(0, "blah") }) ctrl.Call(s, "FooMethod", "1") } func TestTimes0(t *testing.T) { rep, ctrl := createFixtures(t) s := new(Subject) ctrl.RecordCall(s, "FooMethod", "arg").Times(0) rep.assertFatal(func() { ctrl.Call(s, "FooMethod", "arg") }) } func TestVariadicMatching(t *testing.T) { rep, ctrl := createFixtures(t) defer rep.recoverUnexpectedFatal() s := new(Subject) ctrl.RecordCall(s, "VariadicMethod", 0, "1", "2") ctrl.Call(s, "VariadicMethod", 0, "1", "2") rep.assertPass("variadic matching works") } func TestVariadicNoMatch(t *testing.T) { rep, ctrl := createFixtures(t) defer rep.recoverUnexpectedFatal() s := new(Subject) ctrl.RecordCall(s, "VariadicMethod", 0) rep.assertFatal(func() { ctrl.Call(s, "VariadicMethod", 1) }, "expected call at", "doesn't match the argument at index 0", "Got: 1 (int)\nWant: is equal to 0 (int)") ctrl.Call(s, "VariadicMethod", 0) } func TestVariadicMatchingWithSlice(t *testing.T) { testCases := [][]string{ {"1"}, {"1", "2"}, } for _, tc := range testCases { t.Run(fmt.Sprintf("%d arguments", len(tc)), func(t *testing.T) { rep, ctrl := createFixtures(t) defer rep.recoverUnexpectedFatal() s := new(Subject) ctrl.RecordCall(s, "VariadicMethod", 1, tc) args := make([]any, len(tc)+1) args[0] = 1 for i, arg := range tc { args[i+1] = arg } ctrl.Call(s, "VariadicMethod", args...) rep.assertPass("slices can be used as matchers for variadic arguments") }) } } func TestVariadicArgumentsGotFormatter(t *testing.T) { rep, ctrl := createFixtures(t) defer rep.recoverUnexpectedFatal() s := new(Subject) ctrl.RecordCall( s, "VariadicMethod", gomock.GotFormatterAdapter( gomock.GotFormatterFunc(func(i any) string { return fmt.Sprintf("test{%v}", i) }), gomock.Eq(0), ), ) rep.assertFatal(func() { ctrl.Call(s, "VariadicMethod", 1) }, "expected call to", "doesn't match the argument at index 0", "Got: test{1}\nWant: is equal to 0") ctrl.Call(s, "VariadicMethod", 0) } func TestVariadicArgumentsGotFormatterTooManyArgsFailure(t *testing.T) { rep, ctrl := createFixtures(t) defer rep.recoverUnexpectedFatal() s := new(Subject) ctrl.RecordCall( s, "VariadicMethod", 0, gomock.GotFormatterAdapter( gomock.GotFormatterFunc(func(i any) string { return fmt.Sprintf("test{%v}", i) }), gomock.Eq("1"), ), ) rep.assertFatal(func() { ctrl.Call(s, "VariadicMethod", 0, "2", "3") }, "expected call to", "doesn't match the argument at index 1", "Got: test{[2 3]}\nWant: is equal to 1") ctrl.Call(s, "VariadicMethod", 0, "1") } func TestNoHelper(t *testing.T) { ctrlNoHelper := gomock.NewController(NewErrorReporter(t)) // doesn't panic ctrlNoHelper.T.Helper() } func TestWithHelper(t *testing.T) { withHelper := &HelperReporter{TestReporter: NewErrorReporter(t)} ctrlWithHelper := gomock.NewController(withHelper) ctrlWithHelper.T.Helper() if withHelper.helper == 0 { t.Fatal("expected Helper to be invoked") } } func (e *ErrorReporter) Cleanup(f func()) { e.t.Helper() e.t.Cleanup(f) } func TestMultipleDefers(t *testing.T) { reporter := NewErrorReporter(t) reporter.Cleanup(func() { reporter.assertPass("No errors for multiple calls to Finish") }) _ = gomock.NewController(reporter) } func TestDeferNotNeededPass(t *testing.T) { reporter := NewErrorReporter(t) subject := new(Subject) var ctrl *gomock.Controller reporter.Cleanup(func() { reporter.assertPass("Expected method call made.") }) ctrl = gomock.NewController(reporter) ctrl.RecordCall(subject, "FooMethod", "argument") ctrl.Call(subject, "FooMethod", "argument") } func TestOrderedCallsInCorrect(t *testing.T) { reporter := NewErrorReporter(t) subjectOne := new(Subject) subjectTwo := new(Subject) var ctrl *gomock.Controller reporter.Cleanup(func() { reporter.assertFatal(func() { gomock.InOrder( ctrl.RecordCall(subjectOne, "FooMethod", "1").AnyTimes(), ctrl.RecordCall(subjectTwo, "FooMethod", "2"), ctrl.RecordCall(subjectTwo, "BarMethod", "3"), ) ctrl.Call(subjectOne, "FooMethod", "1") // FooMethod(2) should be called before BarMethod(3) ctrl.Call(subjectTwo, "BarMethod", "3") }, "Unexpected call to", "Subject.BarMethod([3])", "doesn't have a prerequisite call satisfied") }) ctrl = gomock.NewController(reporter) } // Test that calls that are prerequisites to other calls but have maxCalls > // minCalls are removed from the expected call set. func TestOrderedCallsWithPreReqMaxUnbounded(t *testing.T) { reporter := NewErrorReporter(t) subjectOne := new(Subject) subjectTwo := new(Subject) var ctrl *gomock.Controller reporter.Cleanup(func() { reporter.assertFatal(func() { // Initially we should be able to call FooMethod("1") as many times as we // want. ctrl.Call(subjectOne, "FooMethod", "1") ctrl.Call(subjectOne, "FooMethod", "1") // But calling something that has it as a prerequisite should remove it from // the expected call set. This allows tests to ensure that FooMethod("1") is // *not* called after FooMethod("2"). ctrl.Call(subjectTwo, "FooMethod", "2") ctrl.Call(subjectOne, "FooMethod", "1") }) }) ctrl = gomock.NewController(reporter) } func TestCallAfterLoopPanic(t *testing.T) { reporter := NewErrorReporter(t) subject := new(Subject) var ctrl *gomock.Controller reporter.Cleanup(func() { firstCall := ctrl.RecordCall(subject, "FooMethod", "1") secondCall := ctrl.RecordCall(subject, "FooMethod", "2") thirdCall := ctrl.RecordCall(subject, "FooMethod", "3") gomock.InOrder(firstCall, secondCall, thirdCall) defer func() { err := recover() if err == nil { t.Error("Call.After creation of dependency loop did not panic.") } }() // This should panic due to dependency loop. firstCall.After(thirdCall) }) ctrl = gomock.NewController(reporter) } golang-go.uber-mock-0.5.0/gomock/doc.go000066400000000000000000000046621470430142200176310ustar00rootroot00000000000000// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package gomock is a mock framework for Go. // // Standard usage: // // (1) Define an interface that you wish to mock. // type MyInterface interface { // SomeMethod(x int64, y string) // } // (2) Use mockgen to generate a mock from the interface. // (3) Use the mock in a test: // func TestMyThing(t *testing.T) { // mockCtrl := gomock.NewController(t) // mockObj := something.NewMockMyInterface(mockCtrl) // mockObj.EXPECT().SomeMethod(4, "blah") // // pass mockObj to a real object and play with it. // } // // By default, expected calls are not enforced to run in any particular order. // Call order dependency can be enforced by use of InOrder and/or Call.After. // Call.After can create more varied call order dependencies, but InOrder is // often more convenient. // // The following examples create equivalent call order dependencies. // // Example of using Call.After to chain expected call order: // // firstCall := mockObj.EXPECT().SomeMethod(1, "first") // secondCall := mockObj.EXPECT().SomeMethod(2, "second").After(firstCall) // mockObj.EXPECT().SomeMethod(3, "third").After(secondCall) // // Example of using InOrder to declare expected call order: // // gomock.InOrder( // mockObj.EXPECT().SomeMethod(1, "first"), // mockObj.EXPECT().SomeMethod(2, "second"), // mockObj.EXPECT().SomeMethod(3, "third"), // ) // // The standard TestReporter most users will pass to `NewController` is a // `*testing.T` from the context of the test. Note that this will use the // standard `t.Error` and `t.Fatal` methods to report what happened in the test. // In some cases this can leave your testing package in a weird state if global // state is used since `t.Fatal` is like calling panic in the middle of a // function. In these cases it is recommended that you pass in your own // `TestReporter`. package gomock golang-go.uber-mock-0.5.0/gomock/example_test.go000066400000000000000000000026211470430142200215470ustar00rootroot00000000000000package gomock_test //go:generate mockgen -destination mock_test.go -package gomock_test -source example_test.go import ( "fmt" "testing" "time" "go.uber.org/mock/gomock" ) type Foo interface { Bar(string) string String() string } func ExampleCall_DoAndReturn_latency() { t := &testing.T{} // provided by test ctrl := gomock.NewController(t) mockIndex := NewMockFoo(ctrl) mockIndex.EXPECT().Bar(gomock.Any()).DoAndReturn( func(arg string) string { time.Sleep(1 * time.Millisecond) return "I'm sleepy" }, ) r := mockIndex.Bar("foo") fmt.Println(r) // Output: I'm sleepy } func ExampleCall_DoAndReturn_captureArguments() { t := &testing.T{} // provided by test ctrl := gomock.NewController(t) mockIndex := NewMockFoo(ctrl) var s string mockIndex.EXPECT().Bar(gomock.AssignableToTypeOf(s)).DoAndReturn( func(arg string) any { s = arg return "I'm sleepy" }, ) r := mockIndex.Bar("foo") fmt.Printf("%s %s", r, s) // Output: I'm sleepy foo } func ExampleCall_DoAndReturn_withOverridableExpectations() { t := &testing.T{} // provided by test ctrl := gomock.NewController(t, gomock.WithOverridableExpectations()) mockIndex := NewMockFoo(ctrl) var s string mockIndex.EXPECT().Bar(gomock.AssignableToTypeOf(s)).DoAndReturn( func(arg string) any { s = arg return "I'm sleepy" }, ) r := mockIndex.Bar("foo") fmt.Printf("%s %s", r, s) // Output: I'm sleepy foo } golang-go.uber-mock-0.5.0/gomock/internal/000077500000000000000000000000001470430142200203415ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/gomock/internal/mock_gomock/000077500000000000000000000000001470430142200226315ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/gomock/internal/mock_gomock/mock_matcher.go000066400000000000000000000035011470430142200256130ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: go.uber.org/mock/gomock (interfaces: Matcher) // // Generated by this command: // // mockgen -destination internal/mock_gomock/mock_matcher.go go.uber.org/mock/gomock Matcher // // Package mock_gomock is a generated GoMock package. package mock_gomock import ( reflect "reflect" gomock "go.uber.org/mock/gomock" ) // MockMatcher is a mock of Matcher interface. type MockMatcher struct { ctrl *gomock.Controller recorder *MockMatcherMockRecorder isgomock struct{} } // MockMatcherMockRecorder is the mock recorder for MockMatcher. type MockMatcherMockRecorder struct { mock *MockMatcher } // NewMockMatcher creates a new mock instance. func NewMockMatcher(ctrl *gomock.Controller) *MockMatcher { mock := &MockMatcher{ctrl: ctrl} mock.recorder = &MockMatcherMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockMatcher) EXPECT() *MockMatcherMockRecorder { return m.recorder } // Matches mocks base method. func (m *MockMatcher) Matches(x any) bool { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Matches", x) ret0, _ := ret[0].(bool) return ret0 } // Matches indicates an expected call of Matches. func (mr *MockMatcherMockRecorder) Matches(x any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Matches", reflect.TypeOf((*MockMatcher)(nil).Matches), x) } // String mocks base method. func (m *MockMatcher) String() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "String") ret0, _ := ret[0].(string) return ret0 } // String indicates an expected call of String. func (mr *MockMatcherMockRecorder) String() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "String", reflect.TypeOf((*MockMatcher)(nil).String)) } golang-go.uber-mock-0.5.0/gomock/matchers.go000066400000000000000000000247071470430142200206740ustar00rootroot00000000000000// Copyright 2010 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gomock import ( "fmt" "reflect" "regexp" "strings" ) // A Matcher is a representation of a class of values. // It is used to represent the valid or expected arguments to a mocked method. type Matcher interface { // Matches returns whether x is a match. Matches(x any) bool // String describes what the matcher matches. String() string } // WantFormatter modifies the given Matcher's String() method to the given // Stringer. This allows for control on how the "Want" is formatted when // printing . func WantFormatter(s fmt.Stringer, m Matcher) Matcher { type matcher interface { Matches(x any) bool } return struct { matcher fmt.Stringer }{ matcher: m, Stringer: s, } } // StringerFunc type is an adapter to allow the use of ordinary functions as // a Stringer. If f is a function with the appropriate signature, // StringerFunc(f) is a Stringer that calls f. type StringerFunc func() string // String implements fmt.Stringer. func (f StringerFunc) String() string { return f() } // GotFormatter is used to better print failure messages. If a matcher // implements GotFormatter, it will use the result from Got when printing // the failure message. type GotFormatter interface { // Got is invoked with the received value. The result is used when // printing the failure message. Got(got any) string } // GotFormatterFunc type is an adapter to allow the use of ordinary // functions as a GotFormatter. If f is a function with the appropriate // signature, GotFormatterFunc(f) is a GotFormatter that calls f. type GotFormatterFunc func(got any) string // Got implements GotFormatter. func (f GotFormatterFunc) Got(got any) string { return f(got) } // GotFormatterAdapter attaches a GotFormatter to a Matcher. func GotFormatterAdapter(s GotFormatter, m Matcher) Matcher { return struct { GotFormatter Matcher }{ GotFormatter: s, Matcher: m, } } type anyMatcher struct{} func (anyMatcher) Matches(any) bool { return true } func (anyMatcher) String() string { return "is anything" } type condMatcher[T any] struct { fn func(x T) bool } func (c condMatcher[T]) Matches(x any) bool { typed, ok := x.(T) if !ok { return false } return c.fn(typed) } func (c condMatcher[T]) String() string { return "adheres to a custom condition" } type eqMatcher struct { x any } func (e eqMatcher) Matches(x any) bool { // In case, some value is nil if e.x == nil || x == nil { return reflect.DeepEqual(e.x, x) } // Check if types assignable and convert them to common type x1Val := reflect.ValueOf(e.x) x2Val := reflect.ValueOf(x) if x1Val.Type().AssignableTo(x2Val.Type()) { x1ValConverted := x1Val.Convert(x2Val.Type()) return reflect.DeepEqual(x1ValConverted.Interface(), x2Val.Interface()) } return false } func (e eqMatcher) String() string { return fmt.Sprintf("is equal to %s (%T)", getString(e.x), e.x) } type nilMatcher struct{} func (nilMatcher) Matches(x any) bool { if x == nil { return true } v := reflect.ValueOf(x) switch v.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: return v.IsNil() } return false } func (nilMatcher) String() string { return "is nil" } type notMatcher struct { m Matcher } func (n notMatcher) Matches(x any) bool { return !n.m.Matches(x) } func (n notMatcher) String() string { return "not(" + n.m.String() + ")" } type regexMatcher struct { regex *regexp.Regexp } func (m regexMatcher) Matches(x any) bool { switch t := x.(type) { case string: return m.regex.MatchString(t) case []byte: return m.regex.Match(t) default: return false } } func (m regexMatcher) String() string { return "matches regex " + m.regex.String() } type assignableToTypeOfMatcher struct { targetType reflect.Type } func (m assignableToTypeOfMatcher) Matches(x any) bool { return reflect.TypeOf(x).AssignableTo(m.targetType) } func (m assignableToTypeOfMatcher) String() string { return "is assignable to " + m.targetType.Name() } type anyOfMatcher struct { matchers []Matcher } func (am anyOfMatcher) Matches(x any) bool { for _, m := range am.matchers { if m.Matches(x) { return true } } return false } func (am anyOfMatcher) String() string { ss := make([]string, 0, len(am.matchers)) for _, matcher := range am.matchers { ss = append(ss, matcher.String()) } return strings.Join(ss, " | ") } type allMatcher struct { matchers []Matcher } func (am allMatcher) Matches(x any) bool { for _, m := range am.matchers { if !m.Matches(x) { return false } } return true } func (am allMatcher) String() string { ss := make([]string, 0, len(am.matchers)) for _, matcher := range am.matchers { ss = append(ss, matcher.String()) } return strings.Join(ss, "; ") } type lenMatcher struct { i int } func (m lenMatcher) Matches(x any) bool { v := reflect.ValueOf(x) switch v.Kind() { case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String: return v.Len() == m.i default: return false } } func (m lenMatcher) String() string { return fmt.Sprintf("has length %d", m.i) } type inAnyOrderMatcher struct { x any } func (m inAnyOrderMatcher) Matches(x any) bool { given, ok := m.prepareValue(x) if !ok { return false } wanted, ok := m.prepareValue(m.x) if !ok { return false } if given.Len() != wanted.Len() { return false } usedFromGiven := make([]bool, given.Len()) foundFromWanted := make([]bool, wanted.Len()) for i := 0; i < wanted.Len(); i++ { wantedMatcher := Eq(wanted.Index(i).Interface()) for j := 0; j < given.Len(); j++ { if usedFromGiven[j] { continue } if wantedMatcher.Matches(given.Index(j).Interface()) { foundFromWanted[i] = true usedFromGiven[j] = true break } } } missingFromWanted := 0 for _, found := range foundFromWanted { if !found { missingFromWanted++ } } extraInGiven := 0 for _, used := range usedFromGiven { if !used { extraInGiven++ } } return extraInGiven == 0 && missingFromWanted == 0 } func (m inAnyOrderMatcher) prepareValue(x any) (reflect.Value, bool) { xValue := reflect.ValueOf(x) switch xValue.Kind() { case reflect.Slice, reflect.Array: return xValue, true default: return reflect.Value{}, false } } func (m inAnyOrderMatcher) String() string { return fmt.Sprintf("has the same elements as %v", m.x) } // Constructors // All returns a composite Matcher that returns true if and only all of the // matchers return true. func All(ms ...Matcher) Matcher { return allMatcher{ms} } // Any returns a matcher that always matches. func Any() Matcher { return anyMatcher{} } // Cond returns a matcher that matches when the given function returns true // after passing it the parameter to the mock function. // This is particularly useful in case you want to match over a field of a custom struct, or dynamic logic. // // Example usage: // // Cond(func(x int){return x == 1}).Matches(1) // returns true // Cond(func(x int){return x == 2}).Matches(1) // returns false func Cond[T any](fn func(x T) bool) Matcher { return condMatcher[T]{fn} } // AnyOf returns a composite Matcher that returns true if at least one of the // matchers returns true. // // Example usage: // // AnyOf(1, 2, 3).Matches(2) // returns true // AnyOf(1, 2, 3).Matches(10) // returns false // AnyOf(Nil(), Len(2)).Matches(nil) // returns true // AnyOf(Nil(), Len(2)).Matches("hi") // returns true // AnyOf(Nil(), Len(2)).Matches("hello") // returns false func AnyOf(xs ...any) Matcher { ms := make([]Matcher, 0, len(xs)) for _, x := range xs { if m, ok := x.(Matcher); ok { ms = append(ms, m) } else { ms = append(ms, Eq(x)) } } return anyOfMatcher{ms} } // Eq returns a matcher that matches on equality. // // Example usage: // // Eq(5).Matches(5) // returns true // Eq(5).Matches(4) // returns false func Eq(x any) Matcher { return eqMatcher{x} } // Len returns a matcher that matches on length. This matcher returns false if // is compared to a type that is not an array, chan, map, slice, or string. func Len(i int) Matcher { return lenMatcher{i} } // Nil returns a matcher that matches if the received value is nil. // // Example usage: // // var x *bytes.Buffer // Nil().Matches(x) // returns true // x = &bytes.Buffer{} // Nil().Matches(x) // returns false func Nil() Matcher { return nilMatcher{} } // Not reverses the results of its given child matcher. // // Example usage: // // Not(Eq(5)).Matches(4) // returns true // Not(Eq(5)).Matches(5) // returns false func Not(x any) Matcher { if m, ok := x.(Matcher); ok { return notMatcher{m} } return notMatcher{Eq(x)} } // Regex checks whether parameter matches the associated regex. // // Example usage: // // Regex("[0-9]{2}:[0-9]{2}").Matches("23:02") // returns true // Regex("[0-9]{2}:[0-9]{2}").Matches([]byte{'2', '3', ':', '0', '2'}) // returns true // Regex("[0-9]{2}:[0-9]{2}").Matches("hello world") // returns false // Regex("[0-9]{2}").Matches(21) // returns false as it's not a valid type func Regex(regexStr string) Matcher { return regexMatcher{regex: regexp.MustCompile(regexStr)} } // AssignableToTypeOf is a Matcher that matches if the parameter to the mock // function is assignable to the type of the parameter to this function. // // Example usage: // // var s fmt.Stringer = &bytes.Buffer{} // AssignableToTypeOf(s).Matches(time.Second) // returns true // AssignableToTypeOf(s).Matches(99) // returns false // // var ctx = reflect.TypeOf((*context.Context)(nil)).Elem() // AssignableToTypeOf(ctx).Matches(context.Background()) // returns true func AssignableToTypeOf(x any) Matcher { if xt, ok := x.(reflect.Type); ok { return assignableToTypeOfMatcher{xt} } return assignableToTypeOfMatcher{reflect.TypeOf(x)} } // InAnyOrder is a Matcher that returns true for collections of the same elements ignoring the order. // // Example usage: // // InAnyOrder([]int{1, 2, 3}).Matches([]int{1, 3, 2}) // returns true // InAnyOrder([]int{1, 2, 3}).Matches([]int{1, 2}) // returns false func InAnyOrder(x any) Matcher { return inAnyOrderMatcher{x} } golang-go.uber-mock-0.5.0/gomock/matchers_test.go000066400000000000000000000254551470430142200217340ustar00rootroot00000000000000// Copyright 2010 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gomock_test //go:generate mockgen -destination internal/mock_gomock/mock_matcher.go go.uber.org/mock/gomock Matcher import ( "context" "errors" "reflect" "testing" "go.uber.org/mock/gomock" "go.uber.org/mock/gomock/internal/mock_gomock" ) type ( A []string B struct { Name string } ) func TestMatchers(t *testing.T) { type e any tests := []struct { name string matcher gomock.Matcher yes, no []e }{ {"test Any", gomock.Any(), []e{3, nil, "foo"}, nil}, { "test AnyOf", gomock.AnyOf(gomock.Nil(), gomock.Len(2), 1, 2, 3), []e{nil, "hi", "to", 1, 2, 3}, []e{"s", "", 0, 4, 10}, }, {"test All", gomock.Eq(4), []e{4}, []e{3, "blah", nil, int64(4)}}, { "test Nil", gomock.Nil(), []e{nil, (error)(nil), (chan bool)(nil), (*int)(nil)}, []e{"", 0, make(chan bool), errors.New("err"), new(int)}, }, {"test Not", gomock.Not(gomock.Eq(4)), []e{3, "blah", nil, int64(4)}, []e{4}}, {"test Regex", gomock.Regex("[0-9]{2}:[0-9]{2}"), []e{"23:02", "[23:02]: Hello world", []byte("23:02")}, []e{4, "23-02", "hello world", true, []byte("23-02")}}, {"test All", gomock.All(gomock.Any(), gomock.Eq(4)), []e{4}, []e{3, "blah", nil, int64(4)}}, { "test Len", gomock.Len(2), []e{[]int{1, 2}, "ab", map[string]int{"a": 0, "b": 1}, [2]string{"a", "b"}}, []e{[]int{1}, "a", 42, 42.0, false, [1]string{"a"}}, }, { "test assignable types", gomock.Eq(A{"a", "b"}), []e{[]string{"a", "b"}, A{"a", "b"}}, []e{[]string{"a"}, A{"b"}}, }, {"test Cond", gomock.Cond(func(x B) bool { return x.Name == "Dam" }), []e{B{Name: "Dam"}}, []e{B{Name: "Dave"}}}, {"test Cond wrong type", gomock.Cond(func(x B) bool { return x.Name == "Dam" }), []e{B{Name: "Dam"}}, []e{"Dave"}}, {"test Cond any type", gomock.Cond(func(x any) bool { return x.(B).Name == "Dam" }), []e{B{Name: "Dam"}}, []e{B{Name: "Dave"}}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { for _, x := range tt.yes { if !tt.matcher.Matches(x) { t.Errorf(`"%v %s": got false, want true.`, x, tt.matcher) } } for _, x := range tt.no { if tt.matcher.Matches(x) { t.Errorf(`"%v %s": got true, want false.`, x, tt.matcher) } } }) } } // A more thorough test of notMatcher func TestNotMatcher(t *testing.T) { ctrl := gomock.NewController(t) mockMatcher := mock_gomock.NewMockMatcher(ctrl) notMatcher := gomock.Not(mockMatcher) mockMatcher.EXPECT().Matches(4).Return(true) if match := notMatcher.Matches(4); match { t.Errorf("notMatcher should not match 4") } mockMatcher.EXPECT().Matches(5).Return(false) if match := notMatcher.Matches(5); !match { t.Errorf("notMatcher should match 5") } } // A more thorough test of regexMatcher func TestRegexMatcher(t *testing.T) { tests := []struct { name string regex string input any wantMatch bool wantStringResponse string shouldPanic bool }{ { name: "match for whole num regex with start and end position matching", regex: "^\\d+$", input: "2302", wantMatch: true, wantStringResponse: "matches regex ^\\d+$", }, { name: "match for valid regex with start and end position matching on longer string", regex: "^[0-9]{2}:[0-9]{2}$", input: "[23:02]: Hello world", wantMatch: false, wantStringResponse: "matches regex ^[0-9]{2}:[0-9]{2}$", }, { name: "match for valid regex with struct as bytes", regex: `^{"id":[0-9]{2}}$`, input: []byte{'{', '"', 'i', 'd', '"', ':', '1', '2', '}'}, wantMatch: true, wantStringResponse: `matches regex ^{"id":[0-9]{2}}$`, }, { name: "should panic when regex fails to compile", regex: `^[0-9]\\?{2}:[0-9]{2}$`, shouldPanic: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if tt.shouldPanic { defer func() { _ = recover() }() } matcher := gomock.Regex(tt.regex) if tt.shouldPanic { t.Errorf("test did not panic, and should have") } if got := matcher.Matches(tt.input); got != tt.wantMatch { t.Errorf("got = %v, wantMatch = %v", got, tt.wantMatch) } if gotStr := matcher.String(); gotStr != tt.wantStringResponse { t.Errorf("got string = %v, want string = %v", gotStr, tt.wantStringResponse) } }) } } type Dog struct { Breed, Name string } type ctxKey struct{} // A thorough test of assignableToTypeOfMatcher func TestAssignableToTypeOfMatcher(t *testing.T) { aStr := "def" anotherStr := "ghi" if match := gomock.AssignableToTypeOf("abc").Matches(4); match { t.Errorf(`AssignableToTypeOf("abc") should not match 4`) } if match := gomock.AssignableToTypeOf("abc").Matches(&aStr); match { t.Errorf(`AssignableToTypeOf("abc") should not match &aStr (*string)`) } if match := gomock.AssignableToTypeOf("abc").Matches("def"); !match { t.Errorf(`AssignableToTypeOf("abc") should match "def"`) } if match := gomock.AssignableToTypeOf(&aStr).Matches("abc"); match { t.Errorf(`AssignableToTypeOf(&aStr) should not match "abc"`) } if match := gomock.AssignableToTypeOf(&aStr).Matches(&anotherStr); !match { t.Errorf(`AssignableToTypeOf(&aStr) should match &anotherStr`) } if match := gomock.AssignableToTypeOf(0).Matches(4); !match { t.Errorf(`AssignableToTypeOf(0) should match 4`) } if match := gomock.AssignableToTypeOf(0).Matches("def"); match { t.Errorf(`AssignableToTypeOf(0) should not match "def"`) } if match := gomock.AssignableToTypeOf(Dog{}).Matches(&Dog{}); match { t.Errorf(`AssignableToTypeOf(Dog{}) should not match &Dog{}`) } if match := gomock.AssignableToTypeOf(Dog{}).Matches(Dog{Breed: "pug", Name: "Fido"}); !match { t.Errorf(`AssignableToTypeOf(Dog{}) should match Dog{Breed: "pug", Name: "Fido"}`) } if match := gomock.AssignableToTypeOf(&Dog{}).Matches(Dog{}); match { t.Errorf(`AssignableToTypeOf(&Dog{}) should not match Dog{}`) } if match := gomock.AssignableToTypeOf(&Dog{}).Matches(&Dog{Breed: "pug", Name: "Fido"}); !match { t.Errorf(`AssignableToTypeOf(&Dog{}) should match &Dog{Breed: "pug", Name: "Fido"}`) } ctxInterface := reflect.TypeOf((*context.Context)(nil)).Elem() if match := gomock.AssignableToTypeOf(ctxInterface).Matches(context.Background()); !match { t.Errorf(`AssignableToTypeOf(context.Context) should not match context.Background()`) } ctxWithValue := context.WithValue(context.Background(), ctxKey{}, "val") if match := gomock.AssignableToTypeOf(ctxInterface).Matches(ctxWithValue); !match { t.Errorf(`AssignableToTypeOf(context.Context) should not match ctxWithValue`) } } func TestInAnyOrder(t *testing.T) { tests := []struct { name string wanted any given any wantMatch bool }{ { name: "match for equal slices", wanted: []int{1, 2, 3}, given: []int{1, 2, 3}, wantMatch: true, }, { name: "match for slices with same elements of different order", wanted: []int{1, 2, 3}, given: []int{1, 3, 2}, wantMatch: true, }, { name: "not match for slices with different elements", wanted: []int{1, 2, 3}, given: []int{1, 2, 4}, wantMatch: false, }, { name: "not match for slices with missing elements", wanted: []int{1, 2, 3}, given: []int{1, 2}, wantMatch: false, }, { name: "not match for slices with extra elements", wanted: []int{1, 2, 3}, given: []int{1, 2, 3, 4}, wantMatch: false, }, { name: "match for empty slices", wanted: []int{}, given: []int{}, wantMatch: true, }, { name: "not match for equal slices of different types", wanted: []float64{1, 2, 3}, given: []int{1, 2, 3}, wantMatch: false, }, { name: "match for equal arrays", wanted: [3]int{1, 2, 3}, given: [3]int{1, 2, 3}, wantMatch: true, }, { name: "match for equal arrays of different order", wanted: [3]int{1, 2, 3}, given: [3]int{1, 3, 2}, wantMatch: true, }, { name: "not match for arrays of different elements", wanted: [3]int{1, 2, 3}, given: [3]int{1, 2, 4}, wantMatch: false, }, { name: "not match for arrays with extra elements", wanted: [3]int{1, 2, 3}, given: [4]int{1, 2, 3, 4}, wantMatch: false, }, { name: "not match for arrays with missing elements", wanted: [3]int{1, 2, 3}, given: [2]int{1, 2}, wantMatch: false, }, { name: "not match for equal strings", // matcher shouldn't treat strings as collections wanted: "123", given: "123", wantMatch: false, }, { name: "not match if x type is not iterable", wanted: 123, given: []int{123}, wantMatch: false, }, { name: "not match if in type is not iterable", wanted: []int{123}, given: 123, wantMatch: false, }, { name: "not match if both are not iterable", wanted: 123, given: 123, wantMatch: false, }, { name: "match for equal slices with unhashable elements", wanted: [][]int{{1}, {1, 2}, {1, 2, 3}}, given: [][]int{{1}, {1, 2}, {1, 2, 3}}, wantMatch: true, }, { name: "match for equal slices with unhashable elements of different order", wanted: [][]int{{1}, {1, 2, 3}, {1, 2}}, given: [][]int{{1}, {1, 2}, {1, 2, 3}}, wantMatch: true, }, { name: "not match for different slices with unhashable elements", wanted: [][]int{{1}, {1, 2, 3}, {1, 2}}, given: [][]int{{1}, {1, 2, 4}, {1, 3}}, wantMatch: false, }, { name: "not match for unhashable missing elements", wanted: [][]int{{1}, {1, 2}, {1, 2, 3}}, given: [][]int{{1}, {1, 2}}, wantMatch: false, }, { name: "not match for unhashable extra elements", wanted: [][]int{{1}, {1, 2}}, given: [][]int{{1}, {1, 2}, {1, 2, 3}}, wantMatch: false, }, { name: "match for equal slices of assignable types", wanted: [][]string{{"a", "b"}}, given: []A{{"a", "b"}}, wantMatch: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := gomock.InAnyOrder(tt.wanted).Matches(tt.given); got != tt.wantMatch { t.Errorf("got = %v, wantMatch %v", got, tt.wantMatch) } }) } } golang-go.uber-mock-0.5.0/gomock/mock_test.go000066400000000000000000000032601470430142200210450ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: example_test.go // // Generated by this command: // // mockgen -destination mock_test.go -package gomock_test -source example_test.go // // Package gomock_test is a generated GoMock package. package gomock_test import ( reflect "reflect" "go.uber.org/mock/gomock" ) // MockFoo is a mock of Foo interface. type MockFoo struct { ctrl *gomock.Controller recorder *MockFooMockRecorder isgomock struct{} } // MockFooMockRecorder is the mock recorder for MockFoo. type MockFooMockRecorder struct { mock *MockFoo } // NewMockFoo creates a new mock instance. func NewMockFoo(ctrl *gomock.Controller) *MockFoo { mock := &MockFoo{ctrl: ctrl} mock.recorder = &MockFooMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockFoo) EXPECT() *MockFooMockRecorder { return m.recorder } // Bar mocks base method. func (m *MockFoo) Bar(arg0 string) string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Bar", arg0) ret0, _ := ret[0].(string) return ret0 } // Bar indicates an expected call of Bar. func (mr *MockFooMockRecorder) Bar(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bar", reflect.TypeOf((*MockFoo)(nil).Bar), arg0) } // String mocks base method. func (m *MockFoo) String() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "String") ret0, _ := ret[0].(string) return ret0 } // String indicates an expected call of String. func (mr *MockFooMockRecorder) String() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "String", reflect.TypeOf((*MockFoo)(nil).String)) } golang-go.uber-mock-0.5.0/gomock/overridable_controller_test.go000066400000000000000000000014411470430142200246540ustar00rootroot00000000000000package gomock_test import ( "testing" "go.uber.org/mock/gomock" ) func TestEcho_NoOverride(t *testing.T) { ctrl := gomock.NewController(t, gomock.WithOverridableExpectations()) mockIndex := NewMockFoo(ctrl) mockIndex.EXPECT().Bar(gomock.Any()).Return("foo") res := mockIndex.Bar("input") if res != "foo" { t.Fatalf("expected response to equal 'foo', got %s", res) } } func TestEcho_WithOverride_BaseCase(t *testing.T) { ctrl := gomock.NewController(t, gomock.WithOverridableExpectations()) mockIndex := NewMockFoo(ctrl) // initial expectation set mockIndex.EXPECT().Bar(gomock.Any()).Return("foo") // override mockIndex.EXPECT().Bar(gomock.Any()).Return("bar") res := mockIndex.Bar("input") if res != "bar" { t.Fatalf("expected response to equal 'bar', got %s", res) } } golang-go.uber-mock-0.5.0/gomock/string.go000066400000000000000000000014331470430142200203630ustar00rootroot00000000000000package gomock import ( "fmt" "reflect" ) // getString is a safe way to convert a value to a string for printing results // If the value is a a mock, getString avoids calling the mocked String() method, // which avoids potential deadlocks func getString(x any) string { if isGeneratedMock(x) { return fmt.Sprintf("%T", x) } if s, ok := x.(fmt.Stringer); ok { return s.String() } return fmt.Sprintf("%v", x) } // isGeneratedMock checks if the given type has a "isgomock" field, // indicating it is a generated mock. func isGeneratedMock(x any) bool { typ := reflect.TypeOf(x) if typ == nil { return false } if typ.Kind() == reflect.Ptr { typ = typ.Elem() } if typ.Kind() != reflect.Struct { return false } _, isgomock := typ.FieldByName("isgomock") return isgomock } golang-go.uber-mock-0.5.0/mockgen/000077500000000000000000000000001470430142200166715ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/deprecated.go000066400000000000000000000020661470430142200213240ustar00rootroot00000000000000package main import ( "flag" "log" "os" ) const ( deprecatedFlagProgOnly = "prog_only" deprecatedFlagExecOnly = "exec_only" ) var ( _ = flag.Bool("prog_only", false, "DEPRECATED (reflect mode) Only generate the reflection program; write it to stdout and exit.") _ = flag.String("exec_only", "", "DEPRECATED (reflect mode) If set, execute this reflection program.") ) // notifyAboutDeprecatedFlags prints a warning message for a deprecated flags if they are set. func notifyAboutDeprecatedFlags() { const resetColorPostfix = "\033[0m" logger := initWarningLogger() flag.Visit(func(f *flag.Flag) { switch f.Name { case deprecatedFlagProgOnly: logger.Println("The -prog_only flag is deprecated and has no effect.", resetColorPostfix) case deprecatedFlagExecOnly: logger.Println("The -exec_only flag is deprecated and has no effect.", resetColorPostfix) } }) } func initWarningLogger() *log.Logger { const ( yellowColor = "\033[33m" warningPrefix = yellowColor + "WARNING: " ) return log.New(os.Stdout, warningPrefix, log.Ldate|log.Ltime) } golang-go.uber-mock-0.5.0/mockgen/generic.go000066400000000000000000000047641470430142200206470ustar00rootroot00000000000000// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // See the License for the specific language governing permissions and // limitations under the License. package main import ( "errors" "fmt" "go/ast" "go/token" "go.uber.org/mock/mockgen/model" ) func getTypeSpecTypeParams(ts *ast.TypeSpec) []*ast.Field { if ts == nil || ts.TypeParams == nil { return nil } return ts.TypeParams.List } func (p *fileParser) parseGenericType(pkg string, typ ast.Expr, tps map[string]model.Type) (model.Type, error) { switch v := typ.(type) { case *ast.IndexExpr: m, err := p.parseType(pkg, v.X, tps) if err != nil { return nil, err } nm, ok := m.(*model.NamedType) if !ok { return m, nil } t, err := p.parseType(pkg, v.Index, tps) if err != nil { return nil, err } nm.TypeParams = &model.TypeParametersType{TypeParameters: []model.Type{t}} return m, nil case *ast.IndexListExpr: m, err := p.parseType(pkg, v.X, tps) if err != nil { return nil, err } nm, ok := m.(*model.NamedType) if !ok { return m, nil } var ts []model.Type for _, expr := range v.Indices { t, err := p.parseType(pkg, expr, tps) if err != nil { return nil, err } ts = append(ts, t) } nm.TypeParams = &model.TypeParametersType{TypeParameters: ts} return m, nil } return nil, nil } func (p *fileParser) parseGenericMethod(field *ast.Field, it *namedInterface, iface *model.Interface, pkg string, tps map[string]model.Type) ([]*model.Method, error) { var indices []ast.Expr var typ ast.Expr switch v := field.Type.(type) { case *ast.IndexExpr: indices = []ast.Expr{v.Index} typ = v.X case *ast.IndexListExpr: indices = v.Indices typ = v.X case *ast.UnaryExpr: if v.Op == token.TILDE { return nil, errConstraintInterface } return nil, fmt.Errorf("~T may only appear as constraint for %T", field.Type) case *ast.BinaryExpr: if v.Op == token.OR { return nil, errConstraintInterface } return nil, fmt.Errorf("A|B may only appear as constraint for %T", field.Type) default: return nil, fmt.Errorf("don't know how to mock method of type %T", field.Type) } nf := &ast.Field{ Doc: field.Comment, Names: field.Names, Type: typ, Tag: field.Tag, Comment: field.Comment, } it.embeddedInstTypeParams = indices return p.parseMethod(nf, it, iface, pkg, tps) } var errConstraintInterface = errors.New("interface contains constraints") golang-go.uber-mock-0.5.0/mockgen/gob.go000066400000000000000000000005221470430142200177660ustar00rootroot00000000000000package main import ( "encoding/gob" "os" "go.uber.org/mock/mockgen/model" ) func gobMode(path string) (*model.Package, error) { in, err := os.Open(path) if err != nil { return nil, err } defer in.Close() var pkg model.Package if err := gob.NewDecoder(in).Decode(&pkg); err != nil { return nil, err } return &pkg, nil } golang-go.uber-mock-0.5.0/mockgen/gob_test.go000066400000000000000000000013241470430142200210260ustar00rootroot00000000000000package main import ( "encoding/gob" "os" "path/filepath" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestGobMode(t *testing.T) { // Encode a package to a temporary gob. parser := packageModeParser{} want, err := parser.parsePackage( "go.uber.org/mock/mockgen/internal/tests/package_mode" /* package name */, []string{ "Human", "Earth" } /* ifaces */, ) path := filepath.Join(t.TempDir(), "model.gob") outfile, err := os.Create(path) require.NoError(t, err) require.NoError(t, gob.NewEncoder(outfile).Encode(want)) outfile.Close() // Ensure gobMode loads it correctly. got, err := gobMode(path) require.NoError(t, err) assert.Equal(t, want, got) } golang-go.uber-mock-0.5.0/mockgen/internal/000077500000000000000000000000001470430142200205055ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/000077500000000000000000000000001470430142200216475ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/add_generate_directive/000077500000000000000000000000001470430142200263075ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/add_generate_directive/import.go000066400000000000000000000004061470430142200301500ustar00rootroot00000000000000// Package add_generate_directive makes sure output places the go:generate command as a directive in the generated code. package add_generate_directive type Message struct { Text string } type Foo interface { Bar(channels []string, message chan<- Message) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/add_generate_directive/mock.go000066400000000000000000000030111470430142200275620ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: go.uber.org/mock/mockgen/internal/tests/add_generate_directive (interfaces: Foo) // // Generated by this command: // // mockgen -write_generate_directive -destination mock.go -package add_generate_directive . Foo // // Package add_generate_directive is a generated GoMock package. package add_generate_directive import ( reflect "reflect" gomock "go.uber.org/mock/gomock" ) //go:generate mockgen -write_generate_directive -destination mock.go -package add_generate_directive . Foo // MockFoo is a mock of Foo interface. type MockFoo struct { ctrl *gomock.Controller recorder *MockFooMockRecorder isgomock struct{} } // MockFooMockRecorder is the mock recorder for MockFoo. type MockFooMockRecorder struct { mock *MockFoo } // NewMockFoo creates a new mock instance. func NewMockFoo(ctrl *gomock.Controller) *MockFoo { mock := &MockFoo{ctrl: ctrl} mock.recorder = &MockFooMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockFoo) EXPECT() *MockFooMockRecorder { return m.recorder } // Bar mocks base method. func (m *MockFoo) Bar(channels []string, message chan<- Message) { m.ctrl.T.Helper() m.ctrl.Call(m, "Bar", channels, message) } // Bar indicates an expected call of Bar. func (mr *MockFooMockRecorder) Bar(channels, message any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bar", reflect.TypeOf((*MockFoo)(nil).Bar), channels, message) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/aux_imports_embedded_interface/000077500000000000000000000000001470430142200300525ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/aux_imports_embedded_interface/README.md000066400000000000000000000017161470430142200313360ustar00rootroot00000000000000# Embedded Interfaces in aux_files Embedded interfaces in `aux_files` generate `unknown embedded interface XXX` errors. See below for example of the problem: ```go // source import ( alias "some.org/package/imported" ) type Source interface { alias.Foreign } ``` ```go // some.org/package/imported type Foreign interface { Embedded } type Embedded interface {} ``` Attempting to generate a mock will result in an `unknown embedded interface Embedded`. The issue is that the `fileParser` stores `auxInterfaces` underneath the package name explicitly specified in the `aux_files` flag. In the `parseInterface` method, there is an incorrect assumption about an embedded interface always being in the source file. ```go case *ast.Ident: // Embedded interface in this package. ei := p.auxInterfaces[""][v.String()] if ei == nil { return nil, p.errorf(v.Pos(), "unknown embedded interface %s", v.String()) } ``` golang-go.uber-mock-0.5.0/mockgen/internal/tests/aux_imports_embedded_interface/bugreport.go000066400000000000000000000007251470430142200324160ustar00rootroot00000000000000package bugreport // Reproduce the issue described in the README.md with // $ go:generate mockgen -aux_files faux=faux/faux.go -destination bugreport_mock.go -package bugreport -source=bugreport.go Example import ( "log" "go.uber.org/mock/mockgen/internal/tests/aux_imports_embedded_interface/faux" ) // Source is an interface w/ an embedded foreign interface type Source interface { faux.Foreign } func CallForeignMethod(s Source) { log.Println(s.Method()) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/aux_imports_embedded_interface/bugreport_mock.go000066400000000000000000000035201470430142200334230ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: bugreport.go // // Generated by this command: // // mockgen -aux_files faux=faux/faux.go -destination bugreport_mock.go -package bugreport -source=bugreport.go Example // // Package bugreport is a generated GoMock package. package bugreport import ( reflect "reflect" gomock "go.uber.org/mock/gomock" faux "go.uber.org/mock/mockgen/internal/tests/aux_imports_embedded_interface/faux" ) // MockSource is a mock of Source interface. type MockSource struct { ctrl *gomock.Controller recorder *MockSourceMockRecorder } // MockSourceMockRecorder is the mock recorder for MockSource. type MockSourceMockRecorder struct { mock *MockSource } // NewMockSource creates a new mock instance. func NewMockSource(ctrl *gomock.Controller) *MockSource { mock := &MockSource{ctrl: ctrl} mock.recorder = &MockSourceMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockSource) EXPECT() *MockSourceMockRecorder { return m.recorder } // Error mocks base method. func (m *MockSource) Error() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Error") ret0, _ := ret[0].(string) return ret0 } // Error indicates an expected call of Error. func (mr *MockSourceMockRecorder) Error() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Error", reflect.TypeOf((*MockSource)(nil).Error)) } // Method mocks base method. func (m *MockSource) Method() faux.Return { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Method") ret0, _ := ret[0].(faux.Return) return ret0 } // Method indicates an expected call of Method. func (mr *MockSourceMockRecorder) Method() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Method", reflect.TypeOf((*MockSource)(nil).Method)) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/aux_imports_embedded_interface/bugreport_test.go000066400000000000000000000004551470430142200334550ustar00rootroot00000000000000package bugreport import ( "testing" "go.uber.org/mock/gomock" ) // TestValidInterface assesses whether or not the generated mock is valid func TestValidInterface(t *testing.T) { ctrl := gomock.NewController(t) s := NewMockSource(ctrl) s.EXPECT().Method().Return("") CallForeignMethod(s) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/aux_imports_embedded_interface/faux/000077500000000000000000000000001470430142200310155ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/aux_imports_embedded_interface/faux/faux.go000066400000000000000000000001571470430142200323120ustar00rootroot00000000000000package faux type Foreign interface { Method() Return Embedded error } type Embedded any type Return any golang-go.uber-mock-0.5.0/mockgen/internal/tests/build_constraint/000077500000000000000000000000001470430142200252125ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/build_constraint/input.go000066400000000000000000000003101470430142200266720ustar00rootroot00000000000000package empty_interface //go:generate mockgen -package empty_interface -destination mock.go -source input.go "-build_constraint=(linux && 386) || (darwin && !cgo) || usertag" type Empty interface{} golang-go.uber-mock-0.5.0/mockgen/internal/tests/build_constraint/mock.go000066400000000000000000000020231470430142200264670ustar00rootroot00000000000000//go:build (linux && 386) || (darwin && !cgo) || usertag // Code generated by MockGen. DO NOT EDIT. // Source: input.go // // Generated by this command: // // mockgen -package empty_interface -destination mock.go -source input.go -build_constraint=(linux && 386) || (darwin && !cgo) || usertag // // Package empty_interface is a generated GoMock package. package empty_interface import ( gomock "go.uber.org/mock/gomock" ) // MockEmpty is a mock of Empty interface. type MockEmpty struct { ctrl *gomock.Controller recorder *MockEmptyMockRecorder isgomock struct{} } // MockEmptyMockRecorder is the mock recorder for MockEmpty. type MockEmptyMockRecorder struct { mock *MockEmpty } // NewMockEmpty creates a new mock instance. func NewMockEmpty(ctrl *gomock.Controller) *MockEmpty { mock := &MockEmpty{ctrl: ctrl} mock.recorder = &MockEmptyMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockEmpty) EXPECT() *MockEmptyMockRecorder { return m.recorder } golang-go.uber-mock-0.5.0/mockgen/internal/tests/build_flags/000077500000000000000000000000001470430142200241225ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/build_flags/directive.go000066400000000000000000000004071470430142200264300ustar00rootroot00000000000000package build_flags // one build flag //go:generate mockgen -destination=mock1/interfaces_mock.go -build_flags=-tags=tag1 . Interface // multiple build flags //go:generate mockgen -destination=mock2/interfaces_mock.go "-build_flags=-race -tags=tag2" . Interface golang-go.uber-mock-0.5.0/mockgen/internal/tests/build_flags/interfaces_1.go000066400000000000000000000001301470430142200270060ustar00rootroot00000000000000//go:build tag1 package build_flags type Interface interface { HelloWorld() string } golang-go.uber-mock-0.5.0/mockgen/internal/tests/build_flags/interfaces_2.go000066400000000000000000000001121470430142200270070ustar00rootroot00000000000000//go:build tag2 package build_flags type Interface interface { Foo() } golang-go.uber-mock-0.5.0/mockgen/internal/tests/build_flags/mock1/000077500000000000000000000000001470430142200251345ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/build_flags/mock1/interfaces_mock.go000066400000000000000000000027701470430142200306250ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: go.uber.org/mock/mockgen/internal/tests/build_flags (interfaces: Interface) // // Generated by this command: // // mockgen -destination=mock1/interfaces_mock.go -build_flags=-tags=tag1 . Interface // // Package mock_build_flags is a generated GoMock package. package mock_build_flags import ( reflect "reflect" gomock "go.uber.org/mock/gomock" ) // MockInterface is a mock of Interface interface. type MockInterface struct { ctrl *gomock.Controller recorder *MockInterfaceMockRecorder isgomock struct{} } // MockInterfaceMockRecorder is the mock recorder for MockInterface. type MockInterfaceMockRecorder struct { mock *MockInterface } // NewMockInterface creates a new mock instance. func NewMockInterface(ctrl *gomock.Controller) *MockInterface { mock := &MockInterface{ctrl: ctrl} mock.recorder = &MockInterfaceMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder { return m.recorder } // HelloWorld mocks base method. func (m *MockInterface) HelloWorld() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "HelloWorld") ret0, _ := ret[0].(string) return ret0 } // HelloWorld indicates an expected call of HelloWorld. func (mr *MockInterfaceMockRecorder) HelloWorld() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HelloWorld", reflect.TypeOf((*MockInterface)(nil).HelloWorld)) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/build_flags/mock2/000077500000000000000000000000001470430142200251355ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/build_flags/mock2/interfaces_mock.go000066400000000000000000000026171470430142200306260ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: go.uber.org/mock/mockgen/internal/tests/build_flags (interfaces: Interface) // // Generated by this command: // // mockgen -destination=mock2/interfaces_mock.go -build_flags=-race -tags=tag2 . Interface // // Package mock_build_flags is a generated GoMock package. package mock_build_flags import ( reflect "reflect" gomock "go.uber.org/mock/gomock" ) // MockInterface is a mock of Interface interface. type MockInterface struct { ctrl *gomock.Controller recorder *MockInterfaceMockRecorder isgomock struct{} } // MockInterfaceMockRecorder is the mock recorder for MockInterface. type MockInterfaceMockRecorder struct { mock *MockInterface } // NewMockInterface creates a new mock instance. func NewMockInterface(ctrl *gomock.Controller) *MockInterface { mock := &MockInterface{ctrl: ctrl} mock.recorder = &MockInterfaceMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder { return m.recorder } // Foo mocks base method. func (m *MockInterface) Foo() { m.ctrl.T.Helper() m.ctrl.Call(m, "Foo") } // Foo indicates an expected call of Foo. func (mr *MockInterfaceMockRecorder) Foo() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Foo", reflect.TypeOf((*MockInterface)(nil).Foo)) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/const_array_length/000077500000000000000000000000001470430142200255345ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/const_array_length/input.go000066400000000000000000000004271470430142200272250ustar00rootroot00000000000000package const_length import "math" //go:generate mockgen -package const_length -destination mock.go -source input.go const C = 2 type I interface { Foo() [C]int Bar() [2]int Baz() [math.MaxInt8]int Qux() [1 + 2]int Quux() [(1 + 2)]int Corge() [math.MaxInt8 - 120]int } golang-go.uber-mock-0.5.0/mockgen/internal/tests/const_array_length/mock.go000066400000000000000000000060361470430142200270210ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: input.go // // Generated by this command: // // mockgen -package const_length -destination mock.go -source input.go // // Package const_length is a generated GoMock package. package const_length import ( reflect "reflect" gomock "go.uber.org/mock/gomock" ) // MockI is a mock of I interface. type MockI struct { ctrl *gomock.Controller recorder *MockIMockRecorder isgomock struct{} } // MockIMockRecorder is the mock recorder for MockI. type MockIMockRecorder struct { mock *MockI } // NewMockI creates a new mock instance. func NewMockI(ctrl *gomock.Controller) *MockI { mock := &MockI{ctrl: ctrl} mock.recorder = &MockIMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockI) EXPECT() *MockIMockRecorder { return m.recorder } // Bar mocks base method. func (m *MockI) Bar() [2]int { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Bar") ret0, _ := ret[0].([2]int) return ret0 } // Bar indicates an expected call of Bar. func (mr *MockIMockRecorder) Bar() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bar", reflect.TypeOf((*MockI)(nil).Bar)) } // Baz mocks base method. func (m *MockI) Baz() [127]int { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Baz") ret0, _ := ret[0].([127]int) return ret0 } // Baz indicates an expected call of Baz. func (mr *MockIMockRecorder) Baz() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Baz", reflect.TypeOf((*MockI)(nil).Baz)) } // Corge mocks base method. func (m *MockI) Corge() [7]int { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Corge") ret0, _ := ret[0].([7]int) return ret0 } // Corge indicates an expected call of Corge. func (mr *MockIMockRecorder) Corge() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Corge", reflect.TypeOf((*MockI)(nil).Corge)) } // Foo mocks base method. func (m *MockI) Foo() [2]int { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Foo") ret0, _ := ret[0].([2]int) return ret0 } // Foo indicates an expected call of Foo. func (mr *MockIMockRecorder) Foo() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Foo", reflect.TypeOf((*MockI)(nil).Foo)) } // Quux mocks base method. func (m *MockI) Quux() [3]int { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Quux") ret0, _ := ret[0].([3]int) return ret0 } // Quux indicates an expected call of Quux. func (mr *MockIMockRecorder) Quux() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Quux", reflect.TypeOf((*MockI)(nil).Quux)) } // Qux mocks base method. func (m *MockI) Qux() [3]int { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Qux") ret0, _ := ret[0].([3]int) return ret0 } // Qux indicates an expected call of Qux. func (mr *MockIMockRecorder) Qux() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Qux", reflect.TypeOf((*MockI)(nil).Qux)) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/copyright_file/000077500000000000000000000000001470430142200246565ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/copyright_file/input.go000066400000000000000000000004341470430142200263450ustar00rootroot00000000000000package empty_interface //go:generate mockgen -package empty_interface -destination mock.go -source input.go -copyright_file=mock_copyright_header type Empty interface{} // migrating interface{} -> any does not resolve to an interface type dropping test generation added in b391ab3 golang-go.uber-mock-0.5.0/mockgen/internal/tests/copyright_file/mock.go000066400000000000000000000022441470430142200261400ustar00rootroot00000000000000// This is a mock copyright header. // // Lorem ipsum dolor sit amet, consectetur adipiscing elit, // sed do eiusmod tempor incididunt ut labore et dolore magna // aliqua. Velit ut tortor pretium viverra suspendisse potenti. // // Code generated by MockGen. DO NOT EDIT. // Source: input.go // // Generated by this command: // // mockgen -package empty_interface -destination mock.go -source input.go -copyright_file=mock_copyright_header // // Package empty_interface is a generated GoMock package. package empty_interface import ( gomock "go.uber.org/mock/gomock" ) // MockEmpty is a mock of Empty interface. type MockEmpty struct { ctrl *gomock.Controller recorder *MockEmptyMockRecorder isgomock struct{} } // MockEmptyMockRecorder is the mock recorder for MockEmpty. type MockEmptyMockRecorder struct { mock *MockEmpty } // NewMockEmpty creates a new mock instance. func NewMockEmpty(ctrl *gomock.Controller) *MockEmpty { mock := &MockEmpty{ctrl: ctrl} mock.recorder = &MockEmptyMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockEmpty) EXPECT() *MockEmptyMockRecorder { return m.recorder } golang-go.uber-mock-0.5.0/mockgen/internal/tests/copyright_file/mock_copyright_header000066400000000000000000000003241470430142200311310ustar00rootroot00000000000000This is a mock copyright header. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Velit ut tortor pretium viverra suspendisse potenti. golang-go.uber-mock-0.5.0/mockgen/internal/tests/custom_package_name/000077500000000000000000000000001470430142200256345ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/custom_package_name/README.md000066400000000000000000000017471470430142200271240ustar00rootroot00000000000000# Tests for custom package names This directory contains test for mockgen generating mocks when imported package name does not match import path suffix. For example, package with name "client" is located under import path "github.com/golang/mock/mockgen/internal/tests/custom_package_name/client/v1". Prior to this patch: ```bash $ go generate greeter/greeter.go 2018/03/05 22:44:52 Loading input failed: greeter.go:17:11: failed parsing returns: greeter.go:17:14: unknown package "client" greeter/greeter.go:1: running "mockgen": exit status 1 ``` This can be fixed by manually providing `-imports` flag, like `-imports client=github.com/golang/mock/mockgen/internal/tests/custom_package_name/client/v1`. But, mockgen should be able to automatically resolve package names in such situations. With this patch applied: ```bash $ go generate greeter/greeter.go $ echo $? 0 ``` Mockgen runs successfully, produced output is equal to [greeter_mock_test.go](greeter/greeter_mock_test.go) content. golang-go.uber-mock-0.5.0/mockgen/internal/tests/custom_package_name/client/000077500000000000000000000000001470430142200271125ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/custom_package_name/client/v1/000077500000000000000000000000001470430142200274405ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/custom_package_name/client/v1/client.go000066400000000000000000000002711470430142200312450ustar00rootroot00000000000000package client import "fmt" type Client struct{} func (c *Client) Greet(in GreetInput) string { return fmt.Sprintf("Hello, %s!", in.Name) } type GreetInput struct { Name string } golang-go.uber-mock-0.5.0/mockgen/internal/tests/custom_package_name/greeter/000077500000000000000000000000001470430142200272715ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/custom_package_name/greeter/greeter.go000066400000000000000000000013511470430142200312550ustar00rootroot00000000000000package greeter //go:generate mockgen -source greeter.go -destination greeter_mock_test.go -package greeter import ( // stdlib import "fmt" // non-matching import suffix and package name "go.uber.org/mock/mockgen/internal/tests/custom_package_name/client/v1" // matching import suffix and package name "go.uber.org/mock/mockgen/internal/tests/custom_package_name/validator" ) type InputMaker interface { MakeInput() client.GreetInput } type Greeter struct { InputMaker InputMaker Client *client.Client } func (g *Greeter) Greet() (string, error) { in := g.InputMaker.MakeInput() if err := validator.Validate(in.Name); err != nil { return "", fmt.Errorf("validation failed: %v", err) } return g.Client.Greet(in), nil } golang-go.uber-mock-0.5.0/mockgen/internal/tests/custom_package_name/greeter/greeter_mock_test.go000066400000000000000000000030211470430142200333210ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: greeter.go // // Generated by this command: // // mockgen -source greeter.go -destination greeter_mock_test.go -package greeter // // Package greeter is a generated GoMock package. package greeter import ( reflect "reflect" gomock "go.uber.org/mock/gomock" client "go.uber.org/mock/mockgen/internal/tests/custom_package_name/client/v1" ) // MockInputMaker is a mock of InputMaker interface. type MockInputMaker struct { ctrl *gomock.Controller recorder *MockInputMakerMockRecorder isgomock struct{} } // MockInputMakerMockRecorder is the mock recorder for MockInputMaker. type MockInputMakerMockRecorder struct { mock *MockInputMaker } // NewMockInputMaker creates a new mock instance. func NewMockInputMaker(ctrl *gomock.Controller) *MockInputMaker { mock := &MockInputMaker{ctrl: ctrl} mock.recorder = &MockInputMakerMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockInputMaker) EXPECT() *MockInputMakerMockRecorder { return m.recorder } // MakeInput mocks base method. func (m *MockInputMaker) MakeInput() client.GreetInput { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "MakeInput") ret0, _ := ret[0].(client.GreetInput) return ret0 } // MakeInput indicates an expected call of MakeInput. func (mr *MockInputMakerMockRecorder) MakeInput() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MakeInput", reflect.TypeOf((*MockInputMaker)(nil).MakeInput)) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/custom_package_name/greeter/greeter_test.go000066400000000000000000000012151470430142200323130ustar00rootroot00000000000000package greeter import ( "testing" "go.uber.org/mock/gomock" "go.uber.org/mock/mockgen/internal/tests/custom_package_name/client/v1" ) func TestGreeter_Greet(t *testing.T) { ctrl := gomock.NewController(t) input := client.GreetInput{ Name: "Foo", } inputMaker := NewMockInputMaker(ctrl) inputMaker.EXPECT(). MakeInput(). Return(input) g := &Greeter{ InputMaker: inputMaker, Client: &client.Client{}, } greeting, err := g.Greet() if err != nil { t.Fatalf("Unexpected error: %v", err) } expected := "Hello, Foo!" if greeting != expected { t.Fatalf("Expected greeting to be %v but got %v", expected, greeting) } } golang-go.uber-mock-0.5.0/mockgen/internal/tests/custom_package_name/validator/000077500000000000000000000000001470430142200276215ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/custom_package_name/validator/validate.go000066400000000000000000000001011470430142200317310ustar00rootroot00000000000000package validator func Validate(s string) error { return nil } golang-go.uber-mock-0.5.0/mockgen/internal/tests/defined_import_local_name/000077500000000000000000000000001470430142200270115ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/defined_import_local_name/input.go000066400000000000000000000004321470430142200304760ustar00rootroot00000000000000package defined_import_local_name import ( "bytes" "context" ) //go:generate mockgen -package defined_import_local_name -destination mock.go -source input.go -imports b_mock=bytes,c_mock=context type WithImports interface { Method1() bytes.Buffer Method2() context.Context } golang-go.uber-mock-0.5.0/mockgen/internal/tests/defined_import_local_name/mock.go000066400000000000000000000037441470430142200303010ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: input.go // // Generated by this command: // // mockgen -package defined_import_local_name -destination mock.go -source input.go -imports b_mock=bytes,c_mock=context // // Package defined_import_local_name is a generated GoMock package. package defined_import_local_name import ( b_mock "bytes" c_mock "context" reflect "reflect" gomock "go.uber.org/mock/gomock" ) // MockWithImports is a mock of WithImports interface. type MockWithImports struct { ctrl *gomock.Controller recorder *MockWithImportsMockRecorder isgomock struct{} } // MockWithImportsMockRecorder is the mock recorder for MockWithImports. type MockWithImportsMockRecorder struct { mock *MockWithImports } // NewMockWithImports creates a new mock instance. func NewMockWithImports(ctrl *gomock.Controller) *MockWithImports { mock := &MockWithImports{ctrl: ctrl} mock.recorder = &MockWithImportsMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockWithImports) EXPECT() *MockWithImportsMockRecorder { return m.recorder } // Method1 mocks base method. func (m *MockWithImports) Method1() b_mock.Buffer { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Method1") ret0, _ := ret[0].(b_mock.Buffer) return ret0 } // Method1 indicates an expected call of Method1. func (mr *MockWithImportsMockRecorder) Method1() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Method1", reflect.TypeOf((*MockWithImports)(nil).Method1)) } // Method2 mocks base method. func (m *MockWithImports) Method2() c_mock.Context { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Method2") ret0, _ := ret[0].(c_mock.Context) return ret0 } // Method2 indicates an expected call of Method2. func (mr *MockWithImportsMockRecorder) Method2() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Method2", reflect.TypeOf((*MockWithImports)(nil).Method2)) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/dot_imports/000077500000000000000000000000001470430142200242125ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/dot_imports/input.go000066400000000000000000000003701470430142200257000ustar00rootroot00000000000000package dot_imports //go:generate mockgen -package dot_imports -destination mock.go -source input.go import ( "bytes" . "context" . "net/http" ) type WithDotImports interface { Method1() Request Method2() *bytes.Buffer Method3() Context } golang-go.uber-mock-0.5.0/mockgen/internal/tests/dot_imports/mock.go000066400000000000000000000046061470430142200255000ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: input.go // // Generated by this command: // // mockgen -package dot_imports -destination mock.go -source input.go // // Package dot_imports is a generated GoMock package. package dot_imports import ( bytes "bytes" . "context" . "net/http" reflect "reflect" gomock "go.uber.org/mock/gomock" ) // MockWithDotImports is a mock of WithDotImports interface. type MockWithDotImports struct { ctrl *gomock.Controller recorder *MockWithDotImportsMockRecorder isgomock struct{} } // MockWithDotImportsMockRecorder is the mock recorder for MockWithDotImports. type MockWithDotImportsMockRecorder struct { mock *MockWithDotImports } // NewMockWithDotImports creates a new mock instance. func NewMockWithDotImports(ctrl *gomock.Controller) *MockWithDotImports { mock := &MockWithDotImports{ctrl: ctrl} mock.recorder = &MockWithDotImportsMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockWithDotImports) EXPECT() *MockWithDotImportsMockRecorder { return m.recorder } // Method1 mocks base method. func (m *MockWithDotImports) Method1() Request { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Method1") ret0, _ := ret[0].(Request) return ret0 } // Method1 indicates an expected call of Method1. func (mr *MockWithDotImportsMockRecorder) Method1() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Method1", reflect.TypeOf((*MockWithDotImports)(nil).Method1)) } // Method2 mocks base method. func (m *MockWithDotImports) Method2() *bytes.Buffer { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Method2") ret0, _ := ret[0].(*bytes.Buffer) return ret0 } // Method2 indicates an expected call of Method2. func (mr *MockWithDotImportsMockRecorder) Method2() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Method2", reflect.TypeOf((*MockWithDotImports)(nil).Method2)) } // Method3 mocks base method. func (m *MockWithDotImports) Method3() Context { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Method3") ret0, _ := ret[0].(Context) return ret0 } // Method3 indicates an expected call of Method3. func (mr *MockWithDotImportsMockRecorder) Method3() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Method3", reflect.TypeOf((*MockWithDotImports)(nil).Method3)) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/empty_interface/000077500000000000000000000000001470430142200250255ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/empty_interface/input.go000066400000000000000000000003151470430142200265120ustar00rootroot00000000000000package empty_interface //go:generate mockgen -package empty_interface -destination mock.go -source input.go type Empty interface{} // migrating interface{} -> any does not resolve to an interface type. golang-go.uber-mock-0.5.0/mockgen/internal/tests/empty_interface/mock.go000066400000000000000000000016311470430142200263060ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: input.go // // Generated by this command: // // mockgen -package empty_interface -destination mock.go -source input.go // // Package empty_interface is a generated GoMock package. package empty_interface import ( gomock "go.uber.org/mock/gomock" ) // MockEmpty is a mock of Empty interface. type MockEmpty struct { ctrl *gomock.Controller recorder *MockEmptyMockRecorder isgomock struct{} } // MockEmptyMockRecorder is the mock recorder for MockEmpty. type MockEmptyMockRecorder struct { mock *MockEmpty } // NewMockEmpty creates a new mock instance. func NewMockEmpty(ctrl *gomock.Controller) *MockEmpty { mock := &MockEmpty{ctrl: ctrl} mock.recorder = &MockEmptyMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockEmpty) EXPECT() *MockEmptyMockRecorder { return m.recorder } golang-go.uber-mock-0.5.0/mockgen/internal/tests/exclude/000077500000000000000000000000001470430142200233005ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/exclude/interfaces.go000066400000000000000000000004041470430142200257500ustar00rootroot00000000000000package exclude //go:generate mockgen -source=interfaces.go -destination=mock.go -package=exclude -exclude_interfaces=IgnoreMe,IgnoreMe2 type IgnoreMe interface { A() bool } type IgnoreMe2 interface { ~int } type GenerateMockForMe interface { B() int } golang-go.uber-mock-0.5.0/mockgen/internal/tests/exclude/mock.go000066400000000000000000000030031470430142200245540ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: interfaces.go // // Generated by this command: // // mockgen -source=interfaces.go -destination=mock.go -package=exclude -exclude_interfaces=IgnoreMe,IgnoreMe2 // // Package exclude is a generated GoMock package. package exclude import ( reflect "reflect" gomock "go.uber.org/mock/gomock" ) // MockGenerateMockForMe is a mock of GenerateMockForMe interface. type MockGenerateMockForMe struct { ctrl *gomock.Controller recorder *MockGenerateMockForMeMockRecorder isgomock struct{} } // MockGenerateMockForMeMockRecorder is the mock recorder for MockGenerateMockForMe. type MockGenerateMockForMeMockRecorder struct { mock *MockGenerateMockForMe } // NewMockGenerateMockForMe creates a new mock instance. func NewMockGenerateMockForMe(ctrl *gomock.Controller) *MockGenerateMockForMe { mock := &MockGenerateMockForMe{ctrl: ctrl} mock.recorder = &MockGenerateMockForMeMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockGenerateMockForMe) EXPECT() *MockGenerateMockForMeMockRecorder { return m.recorder } // B mocks base method. func (m *MockGenerateMockForMe) B() int { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "B") ret0, _ := ret[0].(int) return ret0 } // B indicates an expected call of B. func (mr *MockGenerateMockForMeMockRecorder) B() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "B", reflect.TypeOf((*MockGenerateMockForMe)(nil).B)) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/extra_import/000077500000000000000000000000001470430142200243645ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/extra_import/import.go000066400000000000000000000004231470430142200262240ustar00rootroot00000000000000// Package extra_import makes sure output does not import it. See #515. package extra_import //go:generate mockgen -destination mock.go -package extra_import . Foo type Message struct { Text string } type Foo interface { Bar(channels []string, message chan<- Message) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/extra_import/mock.go000066400000000000000000000025331470430142200256470ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: go.uber.org/mock/mockgen/internal/tests/extra_import (interfaces: Foo) // // Generated by this command: // // mockgen -destination mock.go -package extra_import . Foo // // Package extra_import is a generated GoMock package. package extra_import import ( reflect "reflect" gomock "go.uber.org/mock/gomock" ) // MockFoo is a mock of Foo interface. type MockFoo struct { ctrl *gomock.Controller recorder *MockFooMockRecorder isgomock struct{} } // MockFooMockRecorder is the mock recorder for MockFoo. type MockFooMockRecorder struct { mock *MockFoo } // NewMockFoo creates a new mock instance. func NewMockFoo(ctrl *gomock.Controller) *MockFoo { mock := &MockFoo{ctrl: ctrl} mock.recorder = &MockFooMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockFoo) EXPECT() *MockFooMockRecorder { return m.recorder } // Bar mocks base method. func (m *MockFoo) Bar(channels []string, message chan<- Message) { m.ctrl.T.Helper() m.ctrl.Call(m, "Bar", channels, message) } // Bar indicates an expected call of Bar. func (mr *MockFooMockRecorder) Bar(channels, message any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bar", reflect.TypeOf((*MockFoo)(nil).Bar), channels, message) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/generated_identifier_conflict/000077500000000000000000000000001470430142200276705ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/generated_identifier_conflict/README.md000066400000000000000000000014671470430142200311570ustar00rootroot00000000000000# Generated Identifier Conflict The generated mock methods use some hardcoded variable/receiver names that can have conflicts with the argument names that are defined by the code for which the mock is generated when using the source generation method. Example: ```go type Example interface { Method(_m, _mr, m, mr int) } ``` ```go // Method mocks base method func (_m *MockExample) Method(_m int, _mr int, m int, mr int) { _m.ctrl.Call(_m, "Method", _m, _mr, m, mr) } ``` In the above example one of the interface method parameters is called `_m` but unfortunately the generated receiver name is also called `_m` so the mock code won't compile. The generator has to make sure that generated identifiers (e.g.: the receiver names) are always different from the arg names that might come from external sources. golang-go.uber-mock-0.5.0/mockgen/internal/tests/generated_identifier_conflict/bugreport.go000066400000000000000000000012331470430142200322270ustar00rootroot00000000000000package bugreport //go:generate mockgen -destination bugreport_mock.go -package bugreport -source=bugreport.go type Example interface { // _m and _mr were used by the buggy code: the '_' prefix was there hoping // that no one will use method argument names starting with '_' reducing // the chance of collision with generated identifiers. // m and mr are used by the bugfixed new code, the '_' prefix has been // removed because the new code generator changes the names of the // generated identifiers in case they would collide with identifiers // coming from argument names. Method(_m, _mr, m, mr int) VarargMethod(_s, _x, a, ret int, varargs ...int) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/generated_identifier_conflict/bugreport_mock.go000066400000000000000000000040261470430142200332430ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: bugreport.go // // Generated by this command: // // mockgen -destination bugreport_mock.go -package bugreport -source=bugreport.go // // Package bugreport is a generated GoMock package. package bugreport import ( reflect "reflect" gomock "go.uber.org/mock/gomock" ) // MockExample is a mock of Example interface. type MockExample struct { ctrl *gomock.Controller recorder *MockExampleMockRecorder isgomock struct{} } // MockExampleMockRecorder is the mock recorder for MockExample. type MockExampleMockRecorder struct { mock *MockExample } // NewMockExample creates a new mock instance. func NewMockExample(ctrl *gomock.Controller) *MockExample { mock := &MockExample{ctrl: ctrl} mock.recorder = &MockExampleMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockExample) EXPECT() *MockExampleMockRecorder { return m.recorder } // Method mocks base method. func (m_2 *MockExample) Method(_m, _mr, m, mr int) { m_2.ctrl.T.Helper() m_2.ctrl.Call(m_2, "Method", _m, _mr, m, mr) } // Method indicates an expected call of Method. func (mr_2 *MockExampleMockRecorder) Method(_m, _mr, m, mr any) *gomock.Call { mr_2.mock.ctrl.T.Helper() return mr_2.mock.ctrl.RecordCallWithMethodType(mr_2.mock, "Method", reflect.TypeOf((*MockExample)(nil).Method), _m, _mr, m, mr) } // VarargMethod mocks base method. func (m *MockExample) VarargMethod(_s, _x, a, ret int, varargs ...int) { m.ctrl.T.Helper() varargs_2 := []any{_s, _x, a, ret} for _, a_2 := range varargs { varargs_2 = append(varargs_2, a_2) } m.ctrl.Call(m, "VarargMethod", varargs_2...) } // VarargMethod indicates an expected call of VarargMethod. func (mr *MockExampleMockRecorder) VarargMethod(_s, _x, a, ret any, varargs ...any) *gomock.Call { mr.mock.ctrl.T.Helper() varargs_2 := append([]any{_s, _x, a, ret}, varargs...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "VarargMethod", reflect.TypeOf((*MockExample)(nil).VarargMethod), varargs_2...) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/generated_identifier_conflict/bugreport_test.go000066400000000000000000000006351470430142200332730ustar00rootroot00000000000000package bugreport import ( "testing" "go.uber.org/mock/gomock" ) func TestExample_Method(t *testing.T) { ctrl := gomock.NewController(t) m := NewMockExample(ctrl) m.EXPECT().Method(1, 2, 3, 4) m.Method(1, 2, 3, 4) } func TestExample_VarargMethod(t *testing.T) { ctrl := gomock.NewController(t) m := NewMockExample(ctrl) m.EXPECT().VarargMethod(1, 2, 3, 4, 6, 7) m.VarargMethod(1, 2, 3, 4, 6, 7) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/generics/000077500000000000000000000000001470430142200234465ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/generics/external.go000066400000000000000000000020211470430142200256120ustar00rootroot00000000000000package generics import ( "context" "io" "go.uber.org/mock/mockgen/internal/tests/generics/other" "golang.org/x/exp/constraints" ) //go:generate mockgen --source=external.go --destination=source/mock_external_mock.go --package source //go:generate mockgen --destination=package_mode/mock_external_mock.go -package=package_mode . ExternalConstraint,EmbeddingIface,Generator,Group type ExternalConstraint[I constraints.Integer, F any] interface { One(string) string Two(I) string Three(I) F Four(I) Foo[I, F] Five(I) Baz[F] Six(I) *Baz[F] Seven(I) other.One[I] Eight(F) other.Two[I, F] Nine(Iface[I]) Ten(*I) Eleven() map[string]I Twelve(ctx context.Context) <-chan []I Thirteen(...I) *F } type EmbeddingIface[T constraints.Integer, R constraints.Float] interface { io.Reader Generator[R] Earth[Generator[T]] other.Either[R, StructType, other.Five, Generator[T]] ExternalConstraint[T, R] } type Generator[T any] interface { Generate() T } type Group[T Generator[any]] interface { Join(ctx context.Context) []T } golang-go.uber-mock-0.5.0/mockgen/internal/tests/generics/generics.go000066400000000000000000000026541470430142200256030ustar00rootroot00000000000000package generics import ( "go.uber.org/mock/mockgen/internal/tests/generics/other" "golang.org/x/exp/constraints" ) //go:generate mockgen --source=generics.go --destination=source/mock_generics_mock.go --package source //go:generate mockgen --destination=package_mode/mock_test.go --package=package_mode . Bar,Universe,MilkyWay,SolarSystem,Earth,Water type Bar[T any, R any] interface { One(string) string Two(T) string Three(T) R Four(T) Foo[T, R] Five(T) Baz[T] Six(T) *Baz[T] Seven(T) other.One[T] Eight(T) other.Two[T, R] Nine(Iface[T]) Ten(*T) Eleven() (*other.One[T], error) Twelve() (*other.Two[T, R], error) Thirteen() (Baz[StructType], error) Fourteen() (*Foo[StructType, StructType2], error) Fifteen() (Iface[StructType], error) Sixteen() (Baz[other.Three], error) Seventeen() (*Foo[other.Three, other.Four], error) Eighteen() (Iface[*other.Five], error) Nineteen() AliasType } type Foo[T any, R any] struct{} type Baz[T any] struct{} type Iface[T any] any type StructType struct{} type StructType2 struct{} type AliasType Baz[other.Three] type Universe[T constraints.Signed] interface { MilkyWay[T] } type MilkyWay[R constraints.Integer] interface { SolarSystem[R] } type SolarSystem[T constraints.Ordered] interface { Earth[T] } type Earth[R any] interface { Water(R) []R } type Water[R any, C UnsignedInteger] interface { Fish(R) []C } type UnsignedInteger interface { ~uint | ~uint32 | ~uint64 } golang-go.uber-mock-0.5.0/mockgen/internal/tests/generics/go.mod000066400000000000000000000003411470430142200245520ustar00rootroot00000000000000module go.uber.org/mock/mockgen/internal/tests/generics go 1.22 replace go.uber.org/mock => ../../../.. require ( go.uber.org/mock v0.0.0-00010101000000-000000000000 golang.org/x/exp v0.0.0-20240613232115-7f521ea00fb8 ) golang-go.uber-mock-0.5.0/mockgen/internal/tests/generics/go.sum000066400000000000000000000003171470430142200246020ustar00rootroot00000000000000golang.org/x/exp v0.0.0-20240613232115-7f521ea00fb8 h1:yixxcjnhBmY0nkL253HFVIm0JsFHwrHdT3Yh6szTnfY= golang.org/x/exp v0.0.0-20240613232115-7f521ea00fb8/go.mod h1:jj3sYF3dwk5D+ghuXyeI3r5MFf+NT2An6/9dOA95KSI= golang-go.uber-mock-0.5.0/mockgen/internal/tests/generics/other/000077500000000000000000000000001470430142200245675ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/generics/other/other.go000066400000000000000000000003321470430142200262350ustar00rootroot00000000000000package other type One[T any] struct{} type Two[T any, R any] struct{} type Three struct{} type Four struct{} type Five any type Either[T, R, K, V any] interface { First() T Second() R Third() K Fourth() V } golang-go.uber-mock-0.5.0/mockgen/internal/tests/generics/package_mode/000077500000000000000000000000001470430142200260455ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/generics/package_mode/mock_external_mock.go000066400000000000000000000477641470430142200322620ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: go.uber.org/mock/mockgen/internal/tests/generics (interfaces: ExternalConstraint,EmbeddingIface,Generator,Group) // // Generated by this command: // // mockgen --destination=package_mode/mock_external_mock.go -package=package_mode . ExternalConstraint,EmbeddingIface,Generator,Group // // Package package_mode is a generated GoMock package. package package_mode import ( context "context" reflect "reflect" gomock "go.uber.org/mock/gomock" generics "go.uber.org/mock/mockgen/internal/tests/generics" other "go.uber.org/mock/mockgen/internal/tests/generics/other" constraints "golang.org/x/exp/constraints" ) // MockExternalConstraint is a mock of ExternalConstraint interface. type MockExternalConstraint[I constraints.Integer, F any] struct { ctrl *gomock.Controller recorder *MockExternalConstraintMockRecorder[I, F] isgomock struct{} } // MockExternalConstraintMockRecorder is the mock recorder for MockExternalConstraint. type MockExternalConstraintMockRecorder[I constraints.Integer, F any] struct { mock *MockExternalConstraint[I, F] } // NewMockExternalConstraint creates a new mock instance. func NewMockExternalConstraint[I constraints.Integer, F any](ctrl *gomock.Controller) *MockExternalConstraint[I, F] { mock := &MockExternalConstraint[I, F]{ctrl: ctrl} mock.recorder = &MockExternalConstraintMockRecorder[I, F]{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockExternalConstraint[I, F]) EXPECT() *MockExternalConstraintMockRecorder[I, F] { return m.recorder } // Eight mocks base method. func (m *MockExternalConstraint[I, F]) Eight(arg0 F) other.Two[I, F] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Eight", arg0) ret0, _ := ret[0].(other.Two[I, F]) return ret0 } // Eight indicates an expected call of Eight. func (mr *MockExternalConstraintMockRecorder[I, F]) Eight(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Eight", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Eight), arg0) } // Eleven mocks base method. func (m *MockExternalConstraint[I, F]) Eleven() map[string]I { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Eleven") ret0, _ := ret[0].(map[string]I) return ret0 } // Eleven indicates an expected call of Eleven. func (mr *MockExternalConstraintMockRecorder[I, F]) Eleven() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Eleven", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Eleven)) } // Five mocks base method. func (m *MockExternalConstraint[I, F]) Five(arg0 I) generics.Baz[F] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Five", arg0) ret0, _ := ret[0].(generics.Baz[F]) return ret0 } // Five indicates an expected call of Five. func (mr *MockExternalConstraintMockRecorder[I, F]) Five(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Five", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Five), arg0) } // Four mocks base method. func (m *MockExternalConstraint[I, F]) Four(arg0 I) generics.Foo[I, F] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Four", arg0) ret0, _ := ret[0].(generics.Foo[I, F]) return ret0 } // Four indicates an expected call of Four. func (mr *MockExternalConstraintMockRecorder[I, F]) Four(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Four", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Four), arg0) } // Nine mocks base method. func (m *MockExternalConstraint[I, F]) Nine(arg0 generics.Iface[I]) { m.ctrl.T.Helper() m.ctrl.Call(m, "Nine", arg0) } // Nine indicates an expected call of Nine. func (mr *MockExternalConstraintMockRecorder[I, F]) Nine(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Nine", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Nine), arg0) } // One mocks base method. func (m *MockExternalConstraint[I, F]) One(arg0 string) string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "One", arg0) ret0, _ := ret[0].(string) return ret0 } // One indicates an expected call of One. func (mr *MockExternalConstraintMockRecorder[I, F]) One(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "One", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).One), arg0) } // Seven mocks base method. func (m *MockExternalConstraint[I, F]) Seven(arg0 I) other.One[I] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Seven", arg0) ret0, _ := ret[0].(other.One[I]) return ret0 } // Seven indicates an expected call of Seven. func (mr *MockExternalConstraintMockRecorder[I, F]) Seven(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Seven", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Seven), arg0) } // Six mocks base method. func (m *MockExternalConstraint[I, F]) Six(arg0 I) *generics.Baz[F] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Six", arg0) ret0, _ := ret[0].(*generics.Baz[F]) return ret0 } // Six indicates an expected call of Six. func (mr *MockExternalConstraintMockRecorder[I, F]) Six(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Six", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Six), arg0) } // Ten mocks base method. func (m *MockExternalConstraint[I, F]) Ten(arg0 *I) { m.ctrl.T.Helper() m.ctrl.Call(m, "Ten", arg0) } // Ten indicates an expected call of Ten. func (mr *MockExternalConstraintMockRecorder[I, F]) Ten(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Ten", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Ten), arg0) } // Thirteen mocks base method. func (m *MockExternalConstraint[I, F]) Thirteen(arg0 ...I) *F { m.ctrl.T.Helper() varargs := []any{} for _, a := range arg0 { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "Thirteen", varargs...) ret0, _ := ret[0].(*F) return ret0 } // Thirteen indicates an expected call of Thirteen. func (mr *MockExternalConstraintMockRecorder[I, F]) Thirteen(arg0 ...any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Thirteen", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Thirteen), arg0...) } // Three mocks base method. func (m *MockExternalConstraint[I, F]) Three(arg0 I) F { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Three", arg0) ret0, _ := ret[0].(F) return ret0 } // Three indicates an expected call of Three. func (mr *MockExternalConstraintMockRecorder[I, F]) Three(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Three", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Three), arg0) } // Twelve mocks base method. func (m *MockExternalConstraint[I, F]) Twelve(ctx context.Context) <-chan []I { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Twelve", ctx) ret0, _ := ret[0].(<-chan []I) return ret0 } // Twelve indicates an expected call of Twelve. func (mr *MockExternalConstraintMockRecorder[I, F]) Twelve(ctx any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Twelve", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Twelve), ctx) } // Two mocks base method. func (m *MockExternalConstraint[I, F]) Two(arg0 I) string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Two", arg0) ret0, _ := ret[0].(string) return ret0 } // Two indicates an expected call of Two. func (mr *MockExternalConstraintMockRecorder[I, F]) Two(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Two", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Two), arg0) } // MockEmbeddingIface is a mock of EmbeddingIface interface. type MockEmbeddingIface[T constraints.Integer, R constraints.Float] struct { ctrl *gomock.Controller recorder *MockEmbeddingIfaceMockRecorder[T, R] isgomock struct{} } // MockEmbeddingIfaceMockRecorder is the mock recorder for MockEmbeddingIface. type MockEmbeddingIfaceMockRecorder[T constraints.Integer, R constraints.Float] struct { mock *MockEmbeddingIface[T, R] } // NewMockEmbeddingIface creates a new mock instance. func NewMockEmbeddingIface[T constraints.Integer, R constraints.Float](ctrl *gomock.Controller) *MockEmbeddingIface[T, R] { mock := &MockEmbeddingIface[T, R]{ctrl: ctrl} mock.recorder = &MockEmbeddingIfaceMockRecorder[T, R]{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockEmbeddingIface[T, R]) EXPECT() *MockEmbeddingIfaceMockRecorder[T, R] { return m.recorder } // Eight mocks base method. func (m *MockEmbeddingIface[T, R]) Eight(arg0 R) other.Two[T, R] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Eight", arg0) ret0, _ := ret[0].(other.Two[T, R]) return ret0 } // Eight indicates an expected call of Eight. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Eight(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Eight", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Eight), arg0) } // Eleven mocks base method. func (m *MockEmbeddingIface[T, R]) Eleven() map[string]T { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Eleven") ret0, _ := ret[0].(map[string]T) return ret0 } // Eleven indicates an expected call of Eleven. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Eleven() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Eleven", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Eleven)) } // First mocks base method. func (m *MockEmbeddingIface[T, R]) First() R { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "First") ret0, _ := ret[0].(R) return ret0 } // First indicates an expected call of First. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) First() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "First", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).First)) } // Five mocks base method. func (m *MockEmbeddingIface[T, R]) Five(arg0 T) generics.Baz[R] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Five", arg0) ret0, _ := ret[0].(generics.Baz[R]) return ret0 } // Five indicates an expected call of Five. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Five(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Five", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Five), arg0) } // Four mocks base method. func (m *MockEmbeddingIface[T, R]) Four(arg0 T) generics.Foo[T, R] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Four", arg0) ret0, _ := ret[0].(generics.Foo[T, R]) return ret0 } // Four indicates an expected call of Four. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Four(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Four", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Four), arg0) } // Fourth mocks base method. func (m *MockEmbeddingIface[T, R]) Fourth() generics.Generator[T] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Fourth") ret0, _ := ret[0].(generics.Generator[T]) return ret0 } // Fourth indicates an expected call of Fourth. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Fourth() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Fourth", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Fourth)) } // Generate mocks base method. func (m *MockEmbeddingIface[T, R]) Generate() R { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Generate") ret0, _ := ret[0].(R) return ret0 } // Generate indicates an expected call of Generate. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Generate() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Generate", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Generate)) } // Nine mocks base method. func (m *MockEmbeddingIface[T, R]) Nine(arg0 generics.Iface[T]) { m.ctrl.T.Helper() m.ctrl.Call(m, "Nine", arg0) } // Nine indicates an expected call of Nine. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Nine(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Nine", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Nine), arg0) } // One mocks base method. func (m *MockEmbeddingIface[T, R]) One(arg0 string) string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "One", arg0) ret0, _ := ret[0].(string) return ret0 } // One indicates an expected call of One. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) One(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "One", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).One), arg0) } // Read mocks base method. func (m *MockEmbeddingIface[T, R]) Read(p []byte) (int, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Read", p) ret0, _ := ret[0].(int) ret1, _ := ret[1].(error) return ret0, ret1 } // Read indicates an expected call of Read. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Read(p any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Read", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Read), p) } // Second mocks base method. func (m *MockEmbeddingIface[T, R]) Second() generics.StructType { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Second") ret0, _ := ret[0].(generics.StructType) return ret0 } // Second indicates an expected call of Second. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Second() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Second", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Second)) } // Seven mocks base method. func (m *MockEmbeddingIface[T, R]) Seven(arg0 T) other.One[T] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Seven", arg0) ret0, _ := ret[0].(other.One[T]) return ret0 } // Seven indicates an expected call of Seven. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Seven(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Seven", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Seven), arg0) } // Six mocks base method. func (m *MockEmbeddingIface[T, R]) Six(arg0 T) *generics.Baz[R] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Six", arg0) ret0, _ := ret[0].(*generics.Baz[R]) return ret0 } // Six indicates an expected call of Six. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Six(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Six", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Six), arg0) } // Ten mocks base method. func (m *MockEmbeddingIface[T, R]) Ten(arg0 *T) { m.ctrl.T.Helper() m.ctrl.Call(m, "Ten", arg0) } // Ten indicates an expected call of Ten. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Ten(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Ten", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Ten), arg0) } // Third mocks base method. func (m *MockEmbeddingIface[T, R]) Third() other.Five { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Third") ret0, _ := ret[0].(other.Five) return ret0 } // Third indicates an expected call of Third. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Third() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Third", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Third)) } // Thirteen mocks base method. func (m *MockEmbeddingIface[T, R]) Thirteen(arg0 ...T) *R { m.ctrl.T.Helper() varargs := []any{} for _, a := range arg0 { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "Thirteen", varargs...) ret0, _ := ret[0].(*R) return ret0 } // Thirteen indicates an expected call of Thirteen. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Thirteen(arg0 ...any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Thirteen", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Thirteen), arg0...) } // Three mocks base method. func (m *MockEmbeddingIface[T, R]) Three(arg0 T) R { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Three", arg0) ret0, _ := ret[0].(R) return ret0 } // Three indicates an expected call of Three. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Three(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Three", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Three), arg0) } // Twelve mocks base method. func (m *MockEmbeddingIface[T, R]) Twelve(ctx context.Context) <-chan []T { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Twelve", ctx) ret0, _ := ret[0].(<-chan []T) return ret0 } // Twelve indicates an expected call of Twelve. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Twelve(ctx any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Twelve", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Twelve), ctx) } // Two mocks base method. func (m *MockEmbeddingIface[T, R]) Two(arg0 T) string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Two", arg0) ret0, _ := ret[0].(string) return ret0 } // Two indicates an expected call of Two. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Two(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Two", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Two), arg0) } // Water mocks base method. func (m *MockEmbeddingIface[T, R]) Water(arg0 generics.Generator[T]) []generics.Generator[T] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Water", arg0) ret0, _ := ret[0].([]generics.Generator[T]) return ret0 } // Water indicates an expected call of Water. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Water(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Water", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Water), arg0) } // MockGenerator is a mock of Generator interface. type MockGenerator[T any] struct { ctrl *gomock.Controller recorder *MockGeneratorMockRecorder[T] isgomock struct{} } // MockGeneratorMockRecorder is the mock recorder for MockGenerator. type MockGeneratorMockRecorder[T any] struct { mock *MockGenerator[T] } // NewMockGenerator creates a new mock instance. func NewMockGenerator[T any](ctrl *gomock.Controller) *MockGenerator[T] { mock := &MockGenerator[T]{ctrl: ctrl} mock.recorder = &MockGeneratorMockRecorder[T]{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockGenerator[T]) EXPECT() *MockGeneratorMockRecorder[T] { return m.recorder } // Generate mocks base method. func (m *MockGenerator[T]) Generate() T { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Generate") ret0, _ := ret[0].(T) return ret0 } // Generate indicates an expected call of Generate. func (mr *MockGeneratorMockRecorder[T]) Generate() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Generate", reflect.TypeOf((*MockGenerator[T])(nil).Generate)) } // MockGroup is a mock of Group interface. type MockGroup[T generics.Generator[any]] struct { ctrl *gomock.Controller recorder *MockGroupMockRecorder[T] isgomock struct{} } // MockGroupMockRecorder is the mock recorder for MockGroup. type MockGroupMockRecorder[T generics.Generator[any]] struct { mock *MockGroup[T] } // NewMockGroup creates a new mock instance. func NewMockGroup[T generics.Generator[any]](ctrl *gomock.Controller) *MockGroup[T] { mock := &MockGroup[T]{ctrl: ctrl} mock.recorder = &MockGroupMockRecorder[T]{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockGroup[T]) EXPECT() *MockGroupMockRecorder[T] { return m.recorder } // Join mocks base method. func (m *MockGroup[T]) Join(ctx context.Context) []T { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Join", ctx) ret0, _ := ret[0].([]T) return ret0 } // Join indicates an expected call of Join. func (mr *MockGroupMockRecorder[T]) Join(ctx any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Join", reflect.TypeOf((*MockGroup[T])(nil).Join), ctx) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/generics/package_mode/mock_test.go000066400000000000000000000372041470430142200303720ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: go.uber.org/mock/mockgen/internal/tests/generics (interfaces: Bar,Universe,MilkyWay,SolarSystem,Earth,Water) // // Generated by this command: // // mockgen --destination=package_mode/mock_test.go --package=package_mode . Bar,Universe,MilkyWay,SolarSystem,Earth,Water // // Package package_mode is a generated GoMock package. package package_mode import ( reflect "reflect" gomock "go.uber.org/mock/gomock" generics "go.uber.org/mock/mockgen/internal/tests/generics" other "go.uber.org/mock/mockgen/internal/tests/generics/other" constraints "golang.org/x/exp/constraints" ) // MockBar is a mock of Bar interface. type MockBar[T any, R any] struct { ctrl *gomock.Controller recorder *MockBarMockRecorder[T, R] isgomock struct{} } // MockBarMockRecorder is the mock recorder for MockBar. type MockBarMockRecorder[T any, R any] struct { mock *MockBar[T, R] } // NewMockBar creates a new mock instance. func NewMockBar[T any, R any](ctrl *gomock.Controller) *MockBar[T, R] { mock := &MockBar[T, R]{ctrl: ctrl} mock.recorder = &MockBarMockRecorder[T, R]{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockBar[T, R]) EXPECT() *MockBarMockRecorder[T, R] { return m.recorder } // Eight mocks base method. func (m *MockBar[T, R]) Eight(arg0 T) other.Two[T, R] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Eight", arg0) ret0, _ := ret[0].(other.Two[T, R]) return ret0 } // Eight indicates an expected call of Eight. func (mr *MockBarMockRecorder[T, R]) Eight(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Eight", reflect.TypeOf((*MockBar[T, R])(nil).Eight), arg0) } // Eighteen mocks base method. func (m *MockBar[T, R]) Eighteen() (generics.Iface[*other.Five], error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Eighteen") ret0, _ := ret[0].(generics.Iface[*other.Five]) ret1, _ := ret[1].(error) return ret0, ret1 } // Eighteen indicates an expected call of Eighteen. func (mr *MockBarMockRecorder[T, R]) Eighteen() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Eighteen", reflect.TypeOf((*MockBar[T, R])(nil).Eighteen)) } // Eleven mocks base method. func (m *MockBar[T, R]) Eleven() (*other.One[T], error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Eleven") ret0, _ := ret[0].(*other.One[T]) ret1, _ := ret[1].(error) return ret0, ret1 } // Eleven indicates an expected call of Eleven. func (mr *MockBarMockRecorder[T, R]) Eleven() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Eleven", reflect.TypeOf((*MockBar[T, R])(nil).Eleven)) } // Fifteen mocks base method. func (m *MockBar[T, R]) Fifteen() (generics.Iface[generics.StructType], error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Fifteen") ret0, _ := ret[0].(generics.Iface[generics.StructType]) ret1, _ := ret[1].(error) return ret0, ret1 } // Fifteen indicates an expected call of Fifteen. func (mr *MockBarMockRecorder[T, R]) Fifteen() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Fifteen", reflect.TypeOf((*MockBar[T, R])(nil).Fifteen)) } // Five mocks base method. func (m *MockBar[T, R]) Five(arg0 T) generics.Baz[T] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Five", arg0) ret0, _ := ret[0].(generics.Baz[T]) return ret0 } // Five indicates an expected call of Five. func (mr *MockBarMockRecorder[T, R]) Five(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Five", reflect.TypeOf((*MockBar[T, R])(nil).Five), arg0) } // Four mocks base method. func (m *MockBar[T, R]) Four(arg0 T) generics.Foo[T, R] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Four", arg0) ret0, _ := ret[0].(generics.Foo[T, R]) return ret0 } // Four indicates an expected call of Four. func (mr *MockBarMockRecorder[T, R]) Four(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Four", reflect.TypeOf((*MockBar[T, R])(nil).Four), arg0) } // Fourteen mocks base method. func (m *MockBar[T, R]) Fourteen() (*generics.Foo[generics.StructType, generics.StructType2], error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Fourteen") ret0, _ := ret[0].(*generics.Foo[generics.StructType, generics.StructType2]) ret1, _ := ret[1].(error) return ret0, ret1 } // Fourteen indicates an expected call of Fourteen. func (mr *MockBarMockRecorder[T, R]) Fourteen() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Fourteen", reflect.TypeOf((*MockBar[T, R])(nil).Fourteen)) } // Nine mocks base method. func (m *MockBar[T, R]) Nine(arg0 generics.Iface[T]) { m.ctrl.T.Helper() m.ctrl.Call(m, "Nine", arg0) } // Nine indicates an expected call of Nine. func (mr *MockBarMockRecorder[T, R]) Nine(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Nine", reflect.TypeOf((*MockBar[T, R])(nil).Nine), arg0) } // Nineteen mocks base method. func (m *MockBar[T, R]) Nineteen() generics.AliasType { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Nineteen") ret0, _ := ret[0].(generics.AliasType) return ret0 } // Nineteen indicates an expected call of Nineteen. func (mr *MockBarMockRecorder[T, R]) Nineteen() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Nineteen", reflect.TypeOf((*MockBar[T, R])(nil).Nineteen)) } // One mocks base method. func (m *MockBar[T, R]) One(arg0 string) string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "One", arg0) ret0, _ := ret[0].(string) return ret0 } // One indicates an expected call of One. func (mr *MockBarMockRecorder[T, R]) One(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "One", reflect.TypeOf((*MockBar[T, R])(nil).One), arg0) } // Seven mocks base method. func (m *MockBar[T, R]) Seven(arg0 T) other.One[T] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Seven", arg0) ret0, _ := ret[0].(other.One[T]) return ret0 } // Seven indicates an expected call of Seven. func (mr *MockBarMockRecorder[T, R]) Seven(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Seven", reflect.TypeOf((*MockBar[T, R])(nil).Seven), arg0) } // Seventeen mocks base method. func (m *MockBar[T, R]) Seventeen() (*generics.Foo[other.Three, other.Four], error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Seventeen") ret0, _ := ret[0].(*generics.Foo[other.Three, other.Four]) ret1, _ := ret[1].(error) return ret0, ret1 } // Seventeen indicates an expected call of Seventeen. func (mr *MockBarMockRecorder[T, R]) Seventeen() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Seventeen", reflect.TypeOf((*MockBar[T, R])(nil).Seventeen)) } // Six mocks base method. func (m *MockBar[T, R]) Six(arg0 T) *generics.Baz[T] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Six", arg0) ret0, _ := ret[0].(*generics.Baz[T]) return ret0 } // Six indicates an expected call of Six. func (mr *MockBarMockRecorder[T, R]) Six(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Six", reflect.TypeOf((*MockBar[T, R])(nil).Six), arg0) } // Sixteen mocks base method. func (m *MockBar[T, R]) Sixteen() (generics.Baz[other.Three], error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Sixteen") ret0, _ := ret[0].(generics.Baz[other.Three]) ret1, _ := ret[1].(error) return ret0, ret1 } // Sixteen indicates an expected call of Sixteen. func (mr *MockBarMockRecorder[T, R]) Sixteen() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Sixteen", reflect.TypeOf((*MockBar[T, R])(nil).Sixteen)) } // Ten mocks base method. func (m *MockBar[T, R]) Ten(arg0 *T) { m.ctrl.T.Helper() m.ctrl.Call(m, "Ten", arg0) } // Ten indicates an expected call of Ten. func (mr *MockBarMockRecorder[T, R]) Ten(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Ten", reflect.TypeOf((*MockBar[T, R])(nil).Ten), arg0) } // Thirteen mocks base method. func (m *MockBar[T, R]) Thirteen() (generics.Baz[generics.StructType], error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Thirteen") ret0, _ := ret[0].(generics.Baz[generics.StructType]) ret1, _ := ret[1].(error) return ret0, ret1 } // Thirteen indicates an expected call of Thirteen. func (mr *MockBarMockRecorder[T, R]) Thirteen() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Thirteen", reflect.TypeOf((*MockBar[T, R])(nil).Thirteen)) } // Three mocks base method. func (m *MockBar[T, R]) Three(arg0 T) R { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Three", arg0) ret0, _ := ret[0].(R) return ret0 } // Three indicates an expected call of Three. func (mr *MockBarMockRecorder[T, R]) Three(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Three", reflect.TypeOf((*MockBar[T, R])(nil).Three), arg0) } // Twelve mocks base method. func (m *MockBar[T, R]) Twelve() (*other.Two[T, R], error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Twelve") ret0, _ := ret[0].(*other.Two[T, R]) ret1, _ := ret[1].(error) return ret0, ret1 } // Twelve indicates an expected call of Twelve. func (mr *MockBarMockRecorder[T, R]) Twelve() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Twelve", reflect.TypeOf((*MockBar[T, R])(nil).Twelve)) } // Two mocks base method. func (m *MockBar[T, R]) Two(arg0 T) string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Two", arg0) ret0, _ := ret[0].(string) return ret0 } // Two indicates an expected call of Two. func (mr *MockBarMockRecorder[T, R]) Two(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Two", reflect.TypeOf((*MockBar[T, R])(nil).Two), arg0) } // MockUniverse is a mock of Universe interface. type MockUniverse[T constraints.Signed] struct { ctrl *gomock.Controller recorder *MockUniverseMockRecorder[T] isgomock struct{} } // MockUniverseMockRecorder is the mock recorder for MockUniverse. type MockUniverseMockRecorder[T constraints.Signed] struct { mock *MockUniverse[T] } // NewMockUniverse creates a new mock instance. func NewMockUniverse[T constraints.Signed](ctrl *gomock.Controller) *MockUniverse[T] { mock := &MockUniverse[T]{ctrl: ctrl} mock.recorder = &MockUniverseMockRecorder[T]{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockUniverse[T]) EXPECT() *MockUniverseMockRecorder[T] { return m.recorder } // Water mocks base method. func (m *MockUniverse[T]) Water(arg0 T) []T { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Water", arg0) ret0, _ := ret[0].([]T) return ret0 } // Water indicates an expected call of Water. func (mr *MockUniverseMockRecorder[T]) Water(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Water", reflect.TypeOf((*MockUniverse[T])(nil).Water), arg0) } // MockMilkyWay is a mock of MilkyWay interface. type MockMilkyWay[R constraints.Integer] struct { ctrl *gomock.Controller recorder *MockMilkyWayMockRecorder[R] isgomock struct{} } // MockMilkyWayMockRecorder is the mock recorder for MockMilkyWay. type MockMilkyWayMockRecorder[R constraints.Integer] struct { mock *MockMilkyWay[R] } // NewMockMilkyWay creates a new mock instance. func NewMockMilkyWay[R constraints.Integer](ctrl *gomock.Controller) *MockMilkyWay[R] { mock := &MockMilkyWay[R]{ctrl: ctrl} mock.recorder = &MockMilkyWayMockRecorder[R]{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockMilkyWay[R]) EXPECT() *MockMilkyWayMockRecorder[R] { return m.recorder } // Water mocks base method. func (m *MockMilkyWay[R]) Water(arg0 R) []R { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Water", arg0) ret0, _ := ret[0].([]R) return ret0 } // Water indicates an expected call of Water. func (mr *MockMilkyWayMockRecorder[R]) Water(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Water", reflect.TypeOf((*MockMilkyWay[R])(nil).Water), arg0) } // MockSolarSystem is a mock of SolarSystem interface. type MockSolarSystem[T constraints.Ordered] struct { ctrl *gomock.Controller recorder *MockSolarSystemMockRecorder[T] isgomock struct{} } // MockSolarSystemMockRecorder is the mock recorder for MockSolarSystem. type MockSolarSystemMockRecorder[T constraints.Ordered] struct { mock *MockSolarSystem[T] } // NewMockSolarSystem creates a new mock instance. func NewMockSolarSystem[T constraints.Ordered](ctrl *gomock.Controller) *MockSolarSystem[T] { mock := &MockSolarSystem[T]{ctrl: ctrl} mock.recorder = &MockSolarSystemMockRecorder[T]{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockSolarSystem[T]) EXPECT() *MockSolarSystemMockRecorder[T] { return m.recorder } // Water mocks base method. func (m *MockSolarSystem[T]) Water(arg0 T) []T { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Water", arg0) ret0, _ := ret[0].([]T) return ret0 } // Water indicates an expected call of Water. func (mr *MockSolarSystemMockRecorder[T]) Water(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Water", reflect.TypeOf((*MockSolarSystem[T])(nil).Water), arg0) } // MockEarth is a mock of Earth interface. type MockEarth[R any] struct { ctrl *gomock.Controller recorder *MockEarthMockRecorder[R] isgomock struct{} } // MockEarthMockRecorder is the mock recorder for MockEarth. type MockEarthMockRecorder[R any] struct { mock *MockEarth[R] } // NewMockEarth creates a new mock instance. func NewMockEarth[R any](ctrl *gomock.Controller) *MockEarth[R] { mock := &MockEarth[R]{ctrl: ctrl} mock.recorder = &MockEarthMockRecorder[R]{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockEarth[R]) EXPECT() *MockEarthMockRecorder[R] { return m.recorder } // Water mocks base method. func (m *MockEarth[R]) Water(arg0 R) []R { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Water", arg0) ret0, _ := ret[0].([]R) return ret0 } // Water indicates an expected call of Water. func (mr *MockEarthMockRecorder[R]) Water(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Water", reflect.TypeOf((*MockEarth[R])(nil).Water), arg0) } // MockWater is a mock of Water interface. type MockWater[R any, C generics.UnsignedInteger] struct { ctrl *gomock.Controller recorder *MockWaterMockRecorder[R, C] isgomock struct{} } // MockWaterMockRecorder is the mock recorder for MockWater. type MockWaterMockRecorder[R any, C generics.UnsignedInteger] struct { mock *MockWater[R, C] } // NewMockWater creates a new mock instance. func NewMockWater[R any, C generics.UnsignedInteger](ctrl *gomock.Controller) *MockWater[R, C] { mock := &MockWater[R, C]{ctrl: ctrl} mock.recorder = &MockWaterMockRecorder[R, C]{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockWater[R, C]) EXPECT() *MockWaterMockRecorder[R, C] { return m.recorder } // Fish mocks base method. func (m *MockWater[R, C]) Fish(arg0 R) []C { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Fish", arg0) ret0, _ := ret[0].([]C) return ret0 } // Fish indicates an expected call of Fish. func (mr *MockWaterMockRecorder[R, C]) Fish(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Fish", reflect.TypeOf((*MockWater[R, C])(nil).Fish), arg0) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/generics/source/000077500000000000000000000000001470430142200247465ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/generics/source/mock_external_mock.go000066400000000000000000000475311470430142200311530ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: external.go // // Generated by this command: // // mockgen --source=external.go --destination=source/mock_external_mock.go --package source // // Package source is a generated GoMock package. package source import ( context "context" reflect "reflect" gomock "go.uber.org/mock/gomock" generics "go.uber.org/mock/mockgen/internal/tests/generics" other "go.uber.org/mock/mockgen/internal/tests/generics/other" constraints "golang.org/x/exp/constraints" ) // MockExternalConstraint is a mock of ExternalConstraint interface. type MockExternalConstraint[I constraints.Integer, F any] struct { ctrl *gomock.Controller recorder *MockExternalConstraintMockRecorder[I, F] isgomock struct{} } // MockExternalConstraintMockRecorder is the mock recorder for MockExternalConstraint. type MockExternalConstraintMockRecorder[I constraints.Integer, F any] struct { mock *MockExternalConstraint[I, F] } // NewMockExternalConstraint creates a new mock instance. func NewMockExternalConstraint[I constraints.Integer, F any](ctrl *gomock.Controller) *MockExternalConstraint[I, F] { mock := &MockExternalConstraint[I, F]{ctrl: ctrl} mock.recorder = &MockExternalConstraintMockRecorder[I, F]{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockExternalConstraint[I, F]) EXPECT() *MockExternalConstraintMockRecorder[I, F] { return m.recorder } // Eight mocks base method. func (m *MockExternalConstraint[I, F]) Eight(arg0 F) other.Two[I, F] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Eight", arg0) ret0, _ := ret[0].(other.Two[I, F]) return ret0 } // Eight indicates an expected call of Eight. func (mr *MockExternalConstraintMockRecorder[I, F]) Eight(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Eight", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Eight), arg0) } // Eleven mocks base method. func (m *MockExternalConstraint[I, F]) Eleven() map[string]I { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Eleven") ret0, _ := ret[0].(map[string]I) return ret0 } // Eleven indicates an expected call of Eleven. func (mr *MockExternalConstraintMockRecorder[I, F]) Eleven() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Eleven", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Eleven)) } // Five mocks base method. func (m *MockExternalConstraint[I, F]) Five(arg0 I) generics.Baz[F] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Five", arg0) ret0, _ := ret[0].(generics.Baz[F]) return ret0 } // Five indicates an expected call of Five. func (mr *MockExternalConstraintMockRecorder[I, F]) Five(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Five", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Five), arg0) } // Four mocks base method. func (m *MockExternalConstraint[I, F]) Four(arg0 I) generics.Foo[I, F] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Four", arg0) ret0, _ := ret[0].(generics.Foo[I, F]) return ret0 } // Four indicates an expected call of Four. func (mr *MockExternalConstraintMockRecorder[I, F]) Four(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Four", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Four), arg0) } // Nine mocks base method. func (m *MockExternalConstraint[I, F]) Nine(arg0 generics.Iface[I]) { m.ctrl.T.Helper() m.ctrl.Call(m, "Nine", arg0) } // Nine indicates an expected call of Nine. func (mr *MockExternalConstraintMockRecorder[I, F]) Nine(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Nine", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Nine), arg0) } // One mocks base method. func (m *MockExternalConstraint[I, F]) One(arg0 string) string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "One", arg0) ret0, _ := ret[0].(string) return ret0 } // One indicates an expected call of One. func (mr *MockExternalConstraintMockRecorder[I, F]) One(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "One", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).One), arg0) } // Seven mocks base method. func (m *MockExternalConstraint[I, F]) Seven(arg0 I) other.One[I] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Seven", arg0) ret0, _ := ret[0].(other.One[I]) return ret0 } // Seven indicates an expected call of Seven. func (mr *MockExternalConstraintMockRecorder[I, F]) Seven(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Seven", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Seven), arg0) } // Six mocks base method. func (m *MockExternalConstraint[I, F]) Six(arg0 I) *generics.Baz[F] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Six", arg0) ret0, _ := ret[0].(*generics.Baz[F]) return ret0 } // Six indicates an expected call of Six. func (mr *MockExternalConstraintMockRecorder[I, F]) Six(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Six", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Six), arg0) } // Ten mocks base method. func (m *MockExternalConstraint[I, F]) Ten(arg0 *I) { m.ctrl.T.Helper() m.ctrl.Call(m, "Ten", arg0) } // Ten indicates an expected call of Ten. func (mr *MockExternalConstraintMockRecorder[I, F]) Ten(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Ten", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Ten), arg0) } // Thirteen mocks base method. func (m *MockExternalConstraint[I, F]) Thirteen(arg0 ...I) *F { m.ctrl.T.Helper() varargs := []any{} for _, a := range arg0 { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "Thirteen", varargs...) ret0, _ := ret[0].(*F) return ret0 } // Thirteen indicates an expected call of Thirteen. func (mr *MockExternalConstraintMockRecorder[I, F]) Thirteen(arg0 ...any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Thirteen", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Thirteen), arg0...) } // Three mocks base method. func (m *MockExternalConstraint[I, F]) Three(arg0 I) F { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Three", arg0) ret0, _ := ret[0].(F) return ret0 } // Three indicates an expected call of Three. func (mr *MockExternalConstraintMockRecorder[I, F]) Three(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Three", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Three), arg0) } // Twelve mocks base method. func (m *MockExternalConstraint[I, F]) Twelve(ctx context.Context) <-chan []I { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Twelve", ctx) ret0, _ := ret[0].(<-chan []I) return ret0 } // Twelve indicates an expected call of Twelve. func (mr *MockExternalConstraintMockRecorder[I, F]) Twelve(ctx any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Twelve", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Twelve), ctx) } // Two mocks base method. func (m *MockExternalConstraint[I, F]) Two(arg0 I) string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Two", arg0) ret0, _ := ret[0].(string) return ret0 } // Two indicates an expected call of Two. func (mr *MockExternalConstraintMockRecorder[I, F]) Two(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Two", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Two), arg0) } // MockEmbeddingIface is a mock of EmbeddingIface interface. type MockEmbeddingIface[T constraints.Integer, R constraints.Float] struct { ctrl *gomock.Controller recorder *MockEmbeddingIfaceMockRecorder[T, R] isgomock struct{} } // MockEmbeddingIfaceMockRecorder is the mock recorder for MockEmbeddingIface. type MockEmbeddingIfaceMockRecorder[T constraints.Integer, R constraints.Float] struct { mock *MockEmbeddingIface[T, R] } // NewMockEmbeddingIface creates a new mock instance. func NewMockEmbeddingIface[T constraints.Integer, R constraints.Float](ctrl *gomock.Controller) *MockEmbeddingIface[T, R] { mock := &MockEmbeddingIface[T, R]{ctrl: ctrl} mock.recorder = &MockEmbeddingIfaceMockRecorder[T, R]{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockEmbeddingIface[T, R]) EXPECT() *MockEmbeddingIfaceMockRecorder[T, R] { return m.recorder } // Eight mocks base method. func (m *MockEmbeddingIface[T, R]) Eight(arg0 R) other.Two[T, R] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Eight", arg0) ret0, _ := ret[0].(other.Two[T, R]) return ret0 } // Eight indicates an expected call of Eight. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Eight(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Eight", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Eight), arg0) } // Eleven mocks base method. func (m *MockEmbeddingIface[T, R]) Eleven() map[string]T { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Eleven") ret0, _ := ret[0].(map[string]T) return ret0 } // Eleven indicates an expected call of Eleven. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Eleven() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Eleven", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Eleven)) } // First mocks base method. func (m *MockEmbeddingIface[T, R]) First() R { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "First") ret0, _ := ret[0].(R) return ret0 } // First indicates an expected call of First. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) First() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "First", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).First)) } // Five mocks base method. func (m *MockEmbeddingIface[T, R]) Five(arg0 T) generics.Baz[R] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Five", arg0) ret0, _ := ret[0].(generics.Baz[R]) return ret0 } // Five indicates an expected call of Five. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Five(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Five", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Five), arg0) } // Four mocks base method. func (m *MockEmbeddingIface[T, R]) Four(arg0 T) generics.Foo[T, R] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Four", arg0) ret0, _ := ret[0].(generics.Foo[T, R]) return ret0 } // Four indicates an expected call of Four. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Four(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Four", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Four), arg0) } // Fourth mocks base method. func (m *MockEmbeddingIface[T, R]) Fourth() generics.Generator[T] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Fourth") ret0, _ := ret[0].(generics.Generator[T]) return ret0 } // Fourth indicates an expected call of Fourth. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Fourth() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Fourth", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Fourth)) } // Generate mocks base method. func (m *MockEmbeddingIface[T, R]) Generate() R { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Generate") ret0, _ := ret[0].(R) return ret0 } // Generate indicates an expected call of Generate. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Generate() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Generate", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Generate)) } // Nine mocks base method. func (m *MockEmbeddingIface[T, R]) Nine(arg0 generics.Iface[T]) { m.ctrl.T.Helper() m.ctrl.Call(m, "Nine", arg0) } // Nine indicates an expected call of Nine. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Nine(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Nine", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Nine), arg0) } // One mocks base method. func (m *MockEmbeddingIface[T, R]) One(arg0 string) string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "One", arg0) ret0, _ := ret[0].(string) return ret0 } // One indicates an expected call of One. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) One(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "One", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).One), arg0) } // Read mocks base method. func (m *MockEmbeddingIface[T, R]) Read(p []byte) (int, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Read", p) ret0, _ := ret[0].(int) ret1, _ := ret[1].(error) return ret0, ret1 } // Read indicates an expected call of Read. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Read(p any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Read", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Read), p) } // Second mocks base method. func (m *MockEmbeddingIface[T, R]) Second() generics.StructType { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Second") ret0, _ := ret[0].(generics.StructType) return ret0 } // Second indicates an expected call of Second. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Second() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Second", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Second)) } // Seven mocks base method. func (m *MockEmbeddingIface[T, R]) Seven(arg0 T) other.One[T] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Seven", arg0) ret0, _ := ret[0].(other.One[T]) return ret0 } // Seven indicates an expected call of Seven. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Seven(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Seven", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Seven), arg0) } // Six mocks base method. func (m *MockEmbeddingIface[T, R]) Six(arg0 T) *generics.Baz[R] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Six", arg0) ret0, _ := ret[0].(*generics.Baz[R]) return ret0 } // Six indicates an expected call of Six. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Six(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Six", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Six), arg0) } // Ten mocks base method. func (m *MockEmbeddingIface[T, R]) Ten(arg0 *T) { m.ctrl.T.Helper() m.ctrl.Call(m, "Ten", arg0) } // Ten indicates an expected call of Ten. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Ten(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Ten", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Ten), arg0) } // Third mocks base method. func (m *MockEmbeddingIface[T, R]) Third() other.Five { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Third") ret0, _ := ret[0].(other.Five) return ret0 } // Third indicates an expected call of Third. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Third() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Third", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Third)) } // Thirteen mocks base method. func (m *MockEmbeddingIface[T, R]) Thirteen(arg0 ...T) *R { m.ctrl.T.Helper() varargs := []any{} for _, a := range arg0 { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "Thirteen", varargs...) ret0, _ := ret[0].(*R) return ret0 } // Thirteen indicates an expected call of Thirteen. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Thirteen(arg0 ...any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Thirteen", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Thirteen), arg0...) } // Three mocks base method. func (m *MockEmbeddingIface[T, R]) Three(arg0 T) R { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Three", arg0) ret0, _ := ret[0].(R) return ret0 } // Three indicates an expected call of Three. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Three(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Three", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Three), arg0) } // Twelve mocks base method. func (m *MockEmbeddingIface[T, R]) Twelve(ctx context.Context) <-chan []T { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Twelve", ctx) ret0, _ := ret[0].(<-chan []T) return ret0 } // Twelve indicates an expected call of Twelve. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Twelve(ctx any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Twelve", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Twelve), ctx) } // Two mocks base method. func (m *MockEmbeddingIface[T, R]) Two(arg0 T) string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Two", arg0) ret0, _ := ret[0].(string) return ret0 } // Two indicates an expected call of Two. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Two(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Two", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Two), arg0) } // Water mocks base method. func (m *MockEmbeddingIface[T, R]) Water(arg0 generics.Generator[T]) []generics.Generator[T] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Water", arg0) ret0, _ := ret[0].([]generics.Generator[T]) return ret0 } // Water indicates an expected call of Water. func (mr *MockEmbeddingIfaceMockRecorder[T, R]) Water(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Water", reflect.TypeOf((*MockEmbeddingIface[T, R])(nil).Water), arg0) } // MockGenerator is a mock of Generator interface. type MockGenerator[T any] struct { ctrl *gomock.Controller recorder *MockGeneratorMockRecorder[T] isgomock struct{} } // MockGeneratorMockRecorder is the mock recorder for MockGenerator. type MockGeneratorMockRecorder[T any] struct { mock *MockGenerator[T] } // NewMockGenerator creates a new mock instance. func NewMockGenerator[T any](ctrl *gomock.Controller) *MockGenerator[T] { mock := &MockGenerator[T]{ctrl: ctrl} mock.recorder = &MockGeneratorMockRecorder[T]{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockGenerator[T]) EXPECT() *MockGeneratorMockRecorder[T] { return m.recorder } // Generate mocks base method. func (m *MockGenerator[T]) Generate() T { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Generate") ret0, _ := ret[0].(T) return ret0 } // Generate indicates an expected call of Generate. func (mr *MockGeneratorMockRecorder[T]) Generate() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Generate", reflect.TypeOf((*MockGenerator[T])(nil).Generate)) } // MockGroup is a mock of Group interface. type MockGroup[T generics.Generator[any]] struct { ctrl *gomock.Controller recorder *MockGroupMockRecorder[T] isgomock struct{} } // MockGroupMockRecorder is the mock recorder for MockGroup. type MockGroupMockRecorder[T generics.Generator[any]] struct { mock *MockGroup[T] } // NewMockGroup creates a new mock instance. func NewMockGroup[T generics.Generator[any]](ctrl *gomock.Controller) *MockGroup[T] { mock := &MockGroup[T]{ctrl: ctrl} mock.recorder = &MockGroupMockRecorder[T]{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockGroup[T]) EXPECT() *MockGroupMockRecorder[T] { return m.recorder } // Join mocks base method. func (m *MockGroup[T]) Join(ctx context.Context) []T { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Join", ctx) ret0, _ := ret[0].([]T) return ret0 } // Join indicates an expected call of Join. func (mr *MockGroupMockRecorder[T]) Join(ctx any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Join", reflect.TypeOf((*MockGroup[T])(nil).Join), ctx) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/generics/source/mock_external_test.go000066400000000000000000000014411470430142200311670ustar00rootroot00000000000000package source import ( "context" "testing" "go.uber.org/mock/gomock" "go.uber.org/mock/mockgen/internal/tests/generics" ) func TestMockEmbeddingIface_One(t *testing.T) { ctrl := gomock.NewController(t) m := NewMockEmbeddingIface[int, float64](ctrl) m.EXPECT().One("foo").Return("bar") if v := m.One("foo"); v != "bar" { t.Errorf("One() = %v, want %v", v, "bar") } } func TestMockUniverse_Water(t *testing.T) { ctrl := gomock.NewController(t) m := NewMockUniverse[int](ctrl) m.EXPECT().Water(1024) m.Water(1024) } func TestNewMockGroup_Join(t *testing.T) { ctrl := gomock.NewController(t) m := NewMockGroup[generics.Generator[any]](ctrl) ctx := context.TODO() m.EXPECT().Join(ctx).Return(nil) if v := m.Join(ctx); v != nil { t.Errorf("Join() = %v, want %v", v, nil) } } golang-go.uber-mock-0.5.0/mockgen/internal/tests/generics/source/mock_generics_mock.go000066400000000000000000000367711470430142200311340ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: generics.go // // Generated by this command: // // mockgen --source=generics.go --destination=source/mock_generics_mock.go --package source // // Package source is a generated GoMock package. package source import ( reflect "reflect" gomock "go.uber.org/mock/gomock" generics "go.uber.org/mock/mockgen/internal/tests/generics" other "go.uber.org/mock/mockgen/internal/tests/generics/other" constraints "golang.org/x/exp/constraints" ) // MockBar is a mock of Bar interface. type MockBar[T any, R any] struct { ctrl *gomock.Controller recorder *MockBarMockRecorder[T, R] isgomock struct{} } // MockBarMockRecorder is the mock recorder for MockBar. type MockBarMockRecorder[T any, R any] struct { mock *MockBar[T, R] } // NewMockBar creates a new mock instance. func NewMockBar[T any, R any](ctrl *gomock.Controller) *MockBar[T, R] { mock := &MockBar[T, R]{ctrl: ctrl} mock.recorder = &MockBarMockRecorder[T, R]{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockBar[T, R]) EXPECT() *MockBarMockRecorder[T, R] { return m.recorder } // Eight mocks base method. func (m *MockBar[T, R]) Eight(arg0 T) other.Two[T, R] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Eight", arg0) ret0, _ := ret[0].(other.Two[T, R]) return ret0 } // Eight indicates an expected call of Eight. func (mr *MockBarMockRecorder[T, R]) Eight(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Eight", reflect.TypeOf((*MockBar[T, R])(nil).Eight), arg0) } // Eighteen mocks base method. func (m *MockBar[T, R]) Eighteen() (generics.Iface[*other.Five], error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Eighteen") ret0, _ := ret[0].(generics.Iface[*other.Five]) ret1, _ := ret[1].(error) return ret0, ret1 } // Eighteen indicates an expected call of Eighteen. func (mr *MockBarMockRecorder[T, R]) Eighteen() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Eighteen", reflect.TypeOf((*MockBar[T, R])(nil).Eighteen)) } // Eleven mocks base method. func (m *MockBar[T, R]) Eleven() (*other.One[T], error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Eleven") ret0, _ := ret[0].(*other.One[T]) ret1, _ := ret[1].(error) return ret0, ret1 } // Eleven indicates an expected call of Eleven. func (mr *MockBarMockRecorder[T, R]) Eleven() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Eleven", reflect.TypeOf((*MockBar[T, R])(nil).Eleven)) } // Fifteen mocks base method. func (m *MockBar[T, R]) Fifteen() (generics.Iface[generics.StructType], error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Fifteen") ret0, _ := ret[0].(generics.Iface[generics.StructType]) ret1, _ := ret[1].(error) return ret0, ret1 } // Fifteen indicates an expected call of Fifteen. func (mr *MockBarMockRecorder[T, R]) Fifteen() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Fifteen", reflect.TypeOf((*MockBar[T, R])(nil).Fifteen)) } // Five mocks base method. func (m *MockBar[T, R]) Five(arg0 T) generics.Baz[T] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Five", arg0) ret0, _ := ret[0].(generics.Baz[T]) return ret0 } // Five indicates an expected call of Five. func (mr *MockBarMockRecorder[T, R]) Five(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Five", reflect.TypeOf((*MockBar[T, R])(nil).Five), arg0) } // Four mocks base method. func (m *MockBar[T, R]) Four(arg0 T) generics.Foo[T, R] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Four", arg0) ret0, _ := ret[0].(generics.Foo[T, R]) return ret0 } // Four indicates an expected call of Four. func (mr *MockBarMockRecorder[T, R]) Four(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Four", reflect.TypeOf((*MockBar[T, R])(nil).Four), arg0) } // Fourteen mocks base method. func (m *MockBar[T, R]) Fourteen() (*generics.Foo[generics.StructType, generics.StructType2], error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Fourteen") ret0, _ := ret[0].(*generics.Foo[generics.StructType, generics.StructType2]) ret1, _ := ret[1].(error) return ret0, ret1 } // Fourteen indicates an expected call of Fourteen. func (mr *MockBarMockRecorder[T, R]) Fourteen() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Fourteen", reflect.TypeOf((*MockBar[T, R])(nil).Fourteen)) } // Nine mocks base method. func (m *MockBar[T, R]) Nine(arg0 generics.Iface[T]) { m.ctrl.T.Helper() m.ctrl.Call(m, "Nine", arg0) } // Nine indicates an expected call of Nine. func (mr *MockBarMockRecorder[T, R]) Nine(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Nine", reflect.TypeOf((*MockBar[T, R])(nil).Nine), arg0) } // Nineteen mocks base method. func (m *MockBar[T, R]) Nineteen() generics.AliasType { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Nineteen") ret0, _ := ret[0].(generics.AliasType) return ret0 } // Nineteen indicates an expected call of Nineteen. func (mr *MockBarMockRecorder[T, R]) Nineteen() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Nineteen", reflect.TypeOf((*MockBar[T, R])(nil).Nineteen)) } // One mocks base method. func (m *MockBar[T, R]) One(arg0 string) string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "One", arg0) ret0, _ := ret[0].(string) return ret0 } // One indicates an expected call of One. func (mr *MockBarMockRecorder[T, R]) One(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "One", reflect.TypeOf((*MockBar[T, R])(nil).One), arg0) } // Seven mocks base method. func (m *MockBar[T, R]) Seven(arg0 T) other.One[T] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Seven", arg0) ret0, _ := ret[0].(other.One[T]) return ret0 } // Seven indicates an expected call of Seven. func (mr *MockBarMockRecorder[T, R]) Seven(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Seven", reflect.TypeOf((*MockBar[T, R])(nil).Seven), arg0) } // Seventeen mocks base method. func (m *MockBar[T, R]) Seventeen() (*generics.Foo[other.Three, other.Four], error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Seventeen") ret0, _ := ret[0].(*generics.Foo[other.Three, other.Four]) ret1, _ := ret[1].(error) return ret0, ret1 } // Seventeen indicates an expected call of Seventeen. func (mr *MockBarMockRecorder[T, R]) Seventeen() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Seventeen", reflect.TypeOf((*MockBar[T, R])(nil).Seventeen)) } // Six mocks base method. func (m *MockBar[T, R]) Six(arg0 T) *generics.Baz[T] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Six", arg0) ret0, _ := ret[0].(*generics.Baz[T]) return ret0 } // Six indicates an expected call of Six. func (mr *MockBarMockRecorder[T, R]) Six(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Six", reflect.TypeOf((*MockBar[T, R])(nil).Six), arg0) } // Sixteen mocks base method. func (m *MockBar[T, R]) Sixteen() (generics.Baz[other.Three], error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Sixteen") ret0, _ := ret[0].(generics.Baz[other.Three]) ret1, _ := ret[1].(error) return ret0, ret1 } // Sixteen indicates an expected call of Sixteen. func (mr *MockBarMockRecorder[T, R]) Sixteen() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Sixteen", reflect.TypeOf((*MockBar[T, R])(nil).Sixteen)) } // Ten mocks base method. func (m *MockBar[T, R]) Ten(arg0 *T) { m.ctrl.T.Helper() m.ctrl.Call(m, "Ten", arg0) } // Ten indicates an expected call of Ten. func (mr *MockBarMockRecorder[T, R]) Ten(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Ten", reflect.TypeOf((*MockBar[T, R])(nil).Ten), arg0) } // Thirteen mocks base method. func (m *MockBar[T, R]) Thirteen() (generics.Baz[generics.StructType], error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Thirteen") ret0, _ := ret[0].(generics.Baz[generics.StructType]) ret1, _ := ret[1].(error) return ret0, ret1 } // Thirteen indicates an expected call of Thirteen. func (mr *MockBarMockRecorder[T, R]) Thirteen() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Thirteen", reflect.TypeOf((*MockBar[T, R])(nil).Thirteen)) } // Three mocks base method. func (m *MockBar[T, R]) Three(arg0 T) R { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Three", arg0) ret0, _ := ret[0].(R) return ret0 } // Three indicates an expected call of Three. func (mr *MockBarMockRecorder[T, R]) Three(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Three", reflect.TypeOf((*MockBar[T, R])(nil).Three), arg0) } // Twelve mocks base method. func (m *MockBar[T, R]) Twelve() (*other.Two[T, R], error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Twelve") ret0, _ := ret[0].(*other.Two[T, R]) ret1, _ := ret[1].(error) return ret0, ret1 } // Twelve indicates an expected call of Twelve. func (mr *MockBarMockRecorder[T, R]) Twelve() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Twelve", reflect.TypeOf((*MockBar[T, R])(nil).Twelve)) } // Two mocks base method. func (m *MockBar[T, R]) Two(arg0 T) string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Two", arg0) ret0, _ := ret[0].(string) return ret0 } // Two indicates an expected call of Two. func (mr *MockBarMockRecorder[T, R]) Two(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Two", reflect.TypeOf((*MockBar[T, R])(nil).Two), arg0) } // MockUniverse is a mock of Universe interface. type MockUniverse[T constraints.Signed] struct { ctrl *gomock.Controller recorder *MockUniverseMockRecorder[T] isgomock struct{} } // MockUniverseMockRecorder is the mock recorder for MockUniverse. type MockUniverseMockRecorder[T constraints.Signed] struct { mock *MockUniverse[T] } // NewMockUniverse creates a new mock instance. func NewMockUniverse[T constraints.Signed](ctrl *gomock.Controller) *MockUniverse[T] { mock := &MockUniverse[T]{ctrl: ctrl} mock.recorder = &MockUniverseMockRecorder[T]{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockUniverse[T]) EXPECT() *MockUniverseMockRecorder[T] { return m.recorder } // Water mocks base method. func (m *MockUniverse[T]) Water(arg0 T) []T { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Water", arg0) ret0, _ := ret[0].([]T) return ret0 } // Water indicates an expected call of Water. func (mr *MockUniverseMockRecorder[T]) Water(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Water", reflect.TypeOf((*MockUniverse[T])(nil).Water), arg0) } // MockMilkyWay is a mock of MilkyWay interface. type MockMilkyWay[R constraints.Integer] struct { ctrl *gomock.Controller recorder *MockMilkyWayMockRecorder[R] isgomock struct{} } // MockMilkyWayMockRecorder is the mock recorder for MockMilkyWay. type MockMilkyWayMockRecorder[R constraints.Integer] struct { mock *MockMilkyWay[R] } // NewMockMilkyWay creates a new mock instance. func NewMockMilkyWay[R constraints.Integer](ctrl *gomock.Controller) *MockMilkyWay[R] { mock := &MockMilkyWay[R]{ctrl: ctrl} mock.recorder = &MockMilkyWayMockRecorder[R]{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockMilkyWay[R]) EXPECT() *MockMilkyWayMockRecorder[R] { return m.recorder } // Water mocks base method. func (m *MockMilkyWay[R]) Water(arg0 R) []R { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Water", arg0) ret0, _ := ret[0].([]R) return ret0 } // Water indicates an expected call of Water. func (mr *MockMilkyWayMockRecorder[R]) Water(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Water", reflect.TypeOf((*MockMilkyWay[R])(nil).Water), arg0) } // MockSolarSystem is a mock of SolarSystem interface. type MockSolarSystem[T constraints.Ordered] struct { ctrl *gomock.Controller recorder *MockSolarSystemMockRecorder[T] isgomock struct{} } // MockSolarSystemMockRecorder is the mock recorder for MockSolarSystem. type MockSolarSystemMockRecorder[T constraints.Ordered] struct { mock *MockSolarSystem[T] } // NewMockSolarSystem creates a new mock instance. func NewMockSolarSystem[T constraints.Ordered](ctrl *gomock.Controller) *MockSolarSystem[T] { mock := &MockSolarSystem[T]{ctrl: ctrl} mock.recorder = &MockSolarSystemMockRecorder[T]{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockSolarSystem[T]) EXPECT() *MockSolarSystemMockRecorder[T] { return m.recorder } // Water mocks base method. func (m *MockSolarSystem[T]) Water(arg0 T) []T { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Water", arg0) ret0, _ := ret[0].([]T) return ret0 } // Water indicates an expected call of Water. func (mr *MockSolarSystemMockRecorder[T]) Water(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Water", reflect.TypeOf((*MockSolarSystem[T])(nil).Water), arg0) } // MockEarth is a mock of Earth interface. type MockEarth[R any] struct { ctrl *gomock.Controller recorder *MockEarthMockRecorder[R] isgomock struct{} } // MockEarthMockRecorder is the mock recorder for MockEarth. type MockEarthMockRecorder[R any] struct { mock *MockEarth[R] } // NewMockEarth creates a new mock instance. func NewMockEarth[R any](ctrl *gomock.Controller) *MockEarth[R] { mock := &MockEarth[R]{ctrl: ctrl} mock.recorder = &MockEarthMockRecorder[R]{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockEarth[R]) EXPECT() *MockEarthMockRecorder[R] { return m.recorder } // Water mocks base method. func (m *MockEarth[R]) Water(arg0 R) []R { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Water", arg0) ret0, _ := ret[0].([]R) return ret0 } // Water indicates an expected call of Water. func (mr *MockEarthMockRecorder[R]) Water(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Water", reflect.TypeOf((*MockEarth[R])(nil).Water), arg0) } // MockWater is a mock of Water interface. type MockWater[R any, C generics.UnsignedInteger] struct { ctrl *gomock.Controller recorder *MockWaterMockRecorder[R, C] isgomock struct{} } // MockWaterMockRecorder is the mock recorder for MockWater. type MockWaterMockRecorder[R any, C generics.UnsignedInteger] struct { mock *MockWater[R, C] } // NewMockWater creates a new mock instance. func NewMockWater[R any, C generics.UnsignedInteger](ctrl *gomock.Controller) *MockWater[R, C] { mock := &MockWater[R, C]{ctrl: ctrl} mock.recorder = &MockWaterMockRecorder[R, C]{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockWater[R, C]) EXPECT() *MockWaterMockRecorder[R, C] { return m.recorder } // Fish mocks base method. func (m *MockWater[R, C]) Fish(arg0 R) []C { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Fish", arg0) ret0, _ := ret[0].([]C) return ret0 } // Fish indicates an expected call of Fish. func (mr *MockWaterMockRecorder[R, C]) Fish(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Fish", reflect.TypeOf((*MockWater[R, C])(nil).Fish), arg0) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/import_embedded_interface/000077500000000000000000000000001470430142200270125ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/import_embedded_interface/bugreport.go000066400000000000000000000021051470430142200313500ustar00rootroot00000000000000// Copyright 2020 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package bugreport //go:generate mockgen -destination bugreport_mock.go -package bugreport -source=bugreport.go import ( "log" "go.uber.org/mock/mockgen/internal/tests/import_embedded_interface/ersatz" "go.uber.org/mock/mockgen/internal/tests/import_embedded_interface/faux" ) // Source is an interface w/ an embedded foreign interface type Source interface { ersatz.Embedded faux.Foreign error Foo } func CallForeignMethod(s Source) { log.Println(s.Ersatz()) log.Println(s.OtherErsatz()) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/import_embedded_interface/bugreport_mock.go000066400000000000000000000053411470430142200323660ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: bugreport.go // // Generated by this command: // // mockgen -destination bugreport_mock.go -package bugreport -source=bugreport.go // // Package bugreport is a generated GoMock package. package bugreport import ( reflect "reflect" gomock "go.uber.org/mock/gomock" ersatz "go.uber.org/mock/mockgen/internal/tests/import_embedded_interface/ersatz" ersatz0 "go.uber.org/mock/mockgen/internal/tests/import_embedded_interface/other/ersatz" ) // MockSource is a mock of Source interface. type MockSource struct { ctrl *gomock.Controller recorder *MockSourceMockRecorder isgomock struct{} } // MockSourceMockRecorder is the mock recorder for MockSource. type MockSourceMockRecorder struct { mock *MockSource } // NewMockSource creates a new mock instance. func NewMockSource(ctrl *gomock.Controller) *MockSource { mock := &MockSource{ctrl: ctrl} mock.recorder = &MockSourceMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockSource) EXPECT() *MockSourceMockRecorder { return m.recorder } // Bar mocks base method. func (m *MockSource) Bar() Baz { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Bar") ret0, _ := ret[0].(Baz) return ret0 } // Bar indicates an expected call of Bar. func (mr *MockSourceMockRecorder) Bar() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bar", reflect.TypeOf((*MockSource)(nil).Bar)) } // Error mocks base method. func (m *MockSource) Error() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Error") ret0, _ := ret[0].(string) return ret0 } // Error indicates an expected call of Error. func (mr *MockSourceMockRecorder) Error() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Error", reflect.TypeOf((*MockSource)(nil).Error)) } // Ersatz mocks base method. func (m *MockSource) Ersatz() ersatz.Return { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Ersatz") ret0, _ := ret[0].(ersatz.Return) return ret0 } // Ersatz indicates an expected call of Ersatz. func (mr *MockSourceMockRecorder) Ersatz() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Ersatz", reflect.TypeOf((*MockSource)(nil).Ersatz)) } // OtherErsatz mocks base method. func (m *MockSource) OtherErsatz() ersatz0.Return { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "OtherErsatz") ret0, _ := ret[0].(ersatz0.Return) return ret0 } // OtherErsatz indicates an expected call of OtherErsatz. func (mr *MockSourceMockRecorder) OtherErsatz() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OtherErsatz", reflect.TypeOf((*MockSource)(nil).OtherErsatz)) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/import_embedded_interface/bugreport_test.go000066400000000000000000000016361470430142200324170ustar00rootroot00000000000000// Copyright 2020 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package bugreport import ( "testing" "go.uber.org/mock/gomock" ) // TestValidInterface assesses whether or not the generated mock is valid func TestValidInterface(t *testing.T) { ctrl := gomock.NewController(t) s := NewMockSource(ctrl) s.EXPECT().Ersatz().Return("") s.EXPECT().OtherErsatz().Return("") CallForeignMethod(s) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/import_embedded_interface/ersatz/000077500000000000000000000000001470430142200303225ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/import_embedded_interface/ersatz/ersatz.go000066400000000000000000000012331470430142200321600ustar00rootroot00000000000000// Copyright 2020 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package ersatz type Embedded interface { Ersatz() Return } type Return any golang-go.uber-mock-0.5.0/mockgen/internal/tests/import_embedded_interface/faux/000077500000000000000000000000001470430142200277555ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/import_embedded_interface/faux/conflict.go000066400000000000000000000013211470430142200321020ustar00rootroot00000000000000// Copyright 2020 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package faux import "go.uber.org/mock/mockgen/internal/tests/import_embedded_interface/other/log" func Conflict1() { log.Foo() } golang-go.uber-mock-0.5.0/mockgen/internal/tests/import_embedded_interface/faux/faux.go000066400000000000000000000014221470430142200312460ustar00rootroot00000000000000// Copyright 2020 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package faux import ( "log" "go.uber.org/mock/mockgen/internal/tests/import_embedded_interface/other/ersatz" ) type Foreign interface { ersatz.Embedded } func Conflict0() { log.Println() } golang-go.uber-mock-0.5.0/mockgen/internal/tests/import_embedded_interface/foo.go000066400000000000000000000001021470430142200301150ustar00rootroot00000000000000package bugreport type Foo interface { Bar() Baz } type Baz any golang-go.uber-mock-0.5.0/mockgen/internal/tests/import_embedded_interface/net.go000066400000000000000000000014211470430142200301250ustar00rootroot00000000000000// // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package bugreport //go:generate mockgen -destination net_mock.go -package bugreport -source=net.go import "net/http" type Net interface { http.ResponseWriter } func CallResponseWriterMethods(n Net) { n.WriteHeader(10) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/import_embedded_interface/net_mock.go000066400000000000000000000042371470430142200311460ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: net.go // // Generated by this command: // // mockgen -destination net_mock.go -package bugreport -source=net.go // // Package bugreport is a generated GoMock package. package bugreport import ( http "net/http" reflect "reflect" gomock "go.uber.org/mock/gomock" ) // MockNet is a mock of Net interface. type MockNet struct { ctrl *gomock.Controller recorder *MockNetMockRecorder isgomock struct{} } // MockNetMockRecorder is the mock recorder for MockNet. type MockNetMockRecorder struct { mock *MockNet } // NewMockNet creates a new mock instance. func NewMockNet(ctrl *gomock.Controller) *MockNet { mock := &MockNet{ctrl: ctrl} mock.recorder = &MockNetMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockNet) EXPECT() *MockNetMockRecorder { return m.recorder } // Header mocks base method. func (m *MockNet) Header() http.Header { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Header") ret0, _ := ret[0].(http.Header) return ret0 } // Header indicates an expected call of Header. func (mr *MockNetMockRecorder) Header() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Header", reflect.TypeOf((*MockNet)(nil).Header)) } // Write mocks base method. func (m *MockNet) Write(arg0 []byte) (int, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Write", arg0) ret0, _ := ret[0].(int) ret1, _ := ret[1].(error) return ret0, ret1 } // Write indicates an expected call of Write. func (mr *MockNetMockRecorder) Write(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Write", reflect.TypeOf((*MockNet)(nil).Write), arg0) } // WriteHeader mocks base method. func (m *MockNet) WriteHeader(statusCode int) { m.ctrl.T.Helper() m.ctrl.Call(m, "WriteHeader", statusCode) } // WriteHeader indicates an expected call of WriteHeader. func (mr *MockNetMockRecorder) WriteHeader(statusCode any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WriteHeader", reflect.TypeOf((*MockNet)(nil).WriteHeader), statusCode) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/import_embedded_interface/net_test.go000066400000000000000000000015751470430142200311760ustar00rootroot00000000000000// Copyright 2020 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package bugreport import ( "testing" "go.uber.org/mock/gomock" ) // TestValidInterface assesses whether or not the generated mock is valid func TestValidNetInterface(t *testing.T) { ctrl := gomock.NewController(t) s := NewMockNet(ctrl) s.EXPECT().WriteHeader(10) CallResponseWriterMethods(s) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/import_embedded_interface/other/000077500000000000000000000000001470430142200301335ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/import_embedded_interface/other/ersatz/000077500000000000000000000000001470430142200314435ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/import_embedded_interface/other/ersatz/ersatz.go000066400000000000000000000012401470430142200332770ustar00rootroot00000000000000// Copyright 2020 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package ersatz type Embedded interface { OtherErsatz() Return } type Return any golang-go.uber-mock-0.5.0/mockgen/internal/tests/import_embedded_interface/other/log/000077500000000000000000000000001470430142200307145ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/import_embedded_interface/other/log/log.go000066400000000000000000000011501470430142200320210ustar00rootroot00000000000000// Copyright 2020 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package log func Foo() {} golang-go.uber-mock-0.5.0/mockgen/internal/tests/import_source/000077500000000000000000000000001470430142200245415ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/import_source/README.md000066400000000000000000000003411470430142200260160ustar00rootroot00000000000000# Import Source Test the case where the generated code uses a type defined in the source package (in source mode). There are two test cases: - the output is in a new package - the output is in the same package as the input golang-go.uber-mock-0.5.0/mockgen/internal/tests/import_source/definition/000077500000000000000000000000001470430142200266715ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/import_source/definition/source.go000066400000000000000000000003301470430142200305140ustar00rootroot00000000000000package source //go:generate mockgen -destination ../source_mock.go -source=source.go //go:generate mockgen -package source -destination source_mock.go -source=source.go type X struct{} type S interface { F(X) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/import_source/definition/source_mock.go000066400000000000000000000022411470430142200315300ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: source.go // // Generated by this command: // // mockgen -package source -destination source_mock.go -source=source.go // // Package source is a generated GoMock package. package source import ( reflect "reflect" gomock "go.uber.org/mock/gomock" ) // MockS is a mock of S interface. type MockS struct { ctrl *gomock.Controller recorder *MockSMockRecorder isgomock struct{} } // MockSMockRecorder is the mock recorder for MockS. type MockSMockRecorder struct { mock *MockS } // NewMockS creates a new mock instance. func NewMockS(ctrl *gomock.Controller) *MockS { mock := &MockS{ctrl: ctrl} mock.recorder = &MockSMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockS) EXPECT() *MockSMockRecorder { return m.recorder } // F mocks base method. func (m *MockS) F(arg0 X) { m.ctrl.T.Helper() m.ctrl.Call(m, "F", arg0) } // F indicates an expected call of F. func (mr *MockSMockRecorder) F(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "F", reflect.TypeOf((*MockS)(nil).F), arg0) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/import_source/source_mock.go000066400000000000000000000023601470430142200274020ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: source.go // // Generated by this command: // // mockgen -destination ../source_mock.go -source=source.go // // Package mock_source is a generated GoMock package. package mock_source import ( reflect "reflect" gomock "go.uber.org/mock/gomock" source "go.uber.org/mock/mockgen/internal/tests/import_source/definition" ) // MockS is a mock of S interface. type MockS struct { ctrl *gomock.Controller recorder *MockSMockRecorder isgomock struct{} } // MockSMockRecorder is the mock recorder for MockS. type MockSMockRecorder struct { mock *MockS } // NewMockS creates a new mock instance. func NewMockS(ctrl *gomock.Controller) *MockS { mock := &MockS{ctrl: ctrl} mock.recorder = &MockSMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockS) EXPECT() *MockSMockRecorder { return m.recorder } // F mocks base method. func (m *MockS) F(arg0 source.X) { m.ctrl.T.Helper() m.ctrl.Call(m, "F", arg0) } // F indicates an expected call of F. func (mr *MockSMockRecorder) F(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "F", reflect.TypeOf((*MockS)(nil).F), arg0) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/internal_pkg/000077500000000000000000000000001470430142200243245ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/internal_pkg/generate.go000066400000000000000000000002001470430142200264350ustar00rootroot00000000000000package test //go:generate mockgen -source subdir/internal/pkg/input.go -destination subdir/internal/pkg/source_output/mock.go golang-go.uber-mock-0.5.0/mockgen/internal/tests/internal_pkg/subdir/000077500000000000000000000000001470430142200256145ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/internal_pkg/subdir/internal/000077500000000000000000000000001470430142200274305ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/internal_pkg/subdir/internal/pkg/000077500000000000000000000000001470430142200302115ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/internal_pkg/subdir/internal/pkg/input.go000066400000000000000000000001211470430142200316710ustar00rootroot00000000000000package pkg type Arg interface { Foo() int } type Intf interface { F() Arg } golang-go.uber-mock-0.5.0/mockgen/internal/tests/internal_pkg/subdir/internal/pkg/reflect_output/000077500000000000000000000000001470430142200332555ustar00rootroot00000000000000mock.go000066400000000000000000000027211470430142200344600ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/internal_pkg/subdir/internal/pkg/reflect_output// Code generated by MockGen. DO NOT EDIT. // Source: go.uber.org/mock/mockgen/internal/tests/internal_pkg/subdir/internal/pkg (interfaces: Intf) // // Generated by this command: // // mockgen -destination subdir/internal/pkg/reflect_output/mock.go go.uber.org/mock/mockgen/internal/tests/internal_pkg/subdir/internal/pkg Intf // // Package mock_pkg is a generated GoMock package. package mock_pkg import ( reflect "reflect" gomock "go.uber.org/mock/gomock" pkg "go.uber.org/mock/mockgen/internal/tests/internal_pkg/subdir/internal/pkg" ) // MockIntf is a mock of Intf interface. type MockIntf struct { ctrl *gomock.Controller recorder *MockIntfMockRecorder } // MockIntfMockRecorder is the mock recorder for MockIntf. type MockIntfMockRecorder struct { mock *MockIntf } // NewMockIntf creates a new mock instance. func NewMockIntf(ctrl *gomock.Controller) *MockIntf { mock := &MockIntf{ctrl: ctrl} mock.recorder = &MockIntfMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockIntf) EXPECT() *MockIntfMockRecorder { return m.recorder } // F mocks base method. func (m *MockIntf) F() pkg.Arg { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "F") ret0, _ := ret[0].(pkg.Arg) return ret0 } // F indicates an expected call of F. func (mr *MockIntfMockRecorder) F() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "F", reflect.TypeOf((*MockIntf)(nil).F)) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/internal_pkg/subdir/internal/pkg/source_output/000077500000000000000000000000001470430142200331315ustar00rootroot00000000000000mock.go000066400000000000000000000044641470430142200343420ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/internal_pkg/subdir/internal/pkg/source_output// Code generated by MockGen. DO NOT EDIT. // Source: subdir/internal/pkg/input.go // // Generated by this command: // // mockgen -source subdir/internal/pkg/input.go -destination subdir/internal/pkg/source_output/mock.go // // Package mock_pkg is a generated GoMock package. package mock_pkg import ( reflect "reflect" gomock "go.uber.org/mock/gomock" pkg "go.uber.org/mock/mockgen/internal/tests/internal_pkg/subdir/internal/pkg" ) // MockArg is a mock of Arg interface. type MockArg struct { ctrl *gomock.Controller recorder *MockArgMockRecorder isgomock struct{} } // MockArgMockRecorder is the mock recorder for MockArg. type MockArgMockRecorder struct { mock *MockArg } // NewMockArg creates a new mock instance. func NewMockArg(ctrl *gomock.Controller) *MockArg { mock := &MockArg{ctrl: ctrl} mock.recorder = &MockArgMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockArg) EXPECT() *MockArgMockRecorder { return m.recorder } // Foo mocks base method. func (m *MockArg) Foo() int { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Foo") ret0, _ := ret[0].(int) return ret0 } // Foo indicates an expected call of Foo. func (mr *MockArgMockRecorder) Foo() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Foo", reflect.TypeOf((*MockArg)(nil).Foo)) } // MockIntf is a mock of Intf interface. type MockIntf struct { ctrl *gomock.Controller recorder *MockIntfMockRecorder isgomock struct{} } // MockIntfMockRecorder is the mock recorder for MockIntf. type MockIntfMockRecorder struct { mock *MockIntf } // NewMockIntf creates a new mock instance. func NewMockIntf(ctrl *gomock.Controller) *MockIntf { mock := &MockIntf{ctrl: ctrl} mock.recorder = &MockIntfMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockIntf) EXPECT() *MockIntfMockRecorder { return m.recorder } // F mocks base method. func (m *MockIntf) F() pkg.Arg { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "F") ret0, _ := ret[0].(pkg.Arg) return ret0 } // F indicates an expected call of F. func (mr *MockIntfMockRecorder) F() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "F", reflect.TypeOf((*MockIntf)(nil).F)) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/missing_import/000077500000000000000000000000001470430142200247125ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/missing_import/output/000077500000000000000000000000001470430142200262525ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/missing_import/output/source_mock.go000066400000000000000000000024601470430142200311140ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: source.go // // Generated by this command: // // mockgen -package source -destination=../output/source_mock.go -source=source.go // // Package source is a generated GoMock package. package source import ( reflect "reflect" gomock "go.uber.org/mock/gomock" source "go.uber.org/mock/mockgen/internal/tests/missing_import/source" ) // MockBar is a mock of Bar interface. type MockBar struct { ctrl *gomock.Controller recorder *MockBarMockRecorder isgomock struct{} } // MockBarMockRecorder is the mock recorder for MockBar. type MockBarMockRecorder struct { mock *MockBar } // NewMockBar creates a new mock instance. func NewMockBar(ctrl *gomock.Controller) *MockBar { mock := &MockBar{ctrl: ctrl} mock.recorder = &MockBarMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockBar) EXPECT() *MockBarMockRecorder { return m.recorder } // Baz mocks base method. func (m *MockBar) Baz(arg0 source.Foo) { m.ctrl.T.Helper() m.ctrl.Call(m, "Baz", arg0) } // Baz indicates an expected call of Baz. func (mr *MockBarMockRecorder) Baz(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Baz", reflect.TypeOf((*MockBar)(nil).Baz), arg0) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/missing_import/source/000077500000000000000000000000001470430142200262125ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/missing_import/source/source.go000066400000000000000000000003361470430142200300430ustar00rootroot00000000000000// Package source makes sure output imports its. See #505. package source //go:generate mockgen -package source -destination=../output/source_mock.go -source=source.go type Foo struct{} type Bar interface { Baz(Foo) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/mock_in_test_package/000077500000000000000000000000001470430142200260005ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/mock_in_test_package/README.md000066400000000000000000000011221470430142200272530ustar00rootroot00000000000000# Mock in Test Package Test the case where the package has the `_test` suffix. Prior to patch: ```bash $ go generate $ go test # github.com/golang/mock/mockgen/internal/tests/mock_in_test_package_test [github.com/golang/mock/mockgen/internal/tests/mock_in_test_package.test] ./mock_test.go:36:44: undefined: User ./mock_test.go:38:21: undefined: User FAIL github.com/golang/mock/mockgen/internal/tests/mock_in_test_package [build failed] ``` With this patch applied: ```bash $ go generate $ go test ok github.com/golang/mock/mockgen/internal/tests/mock_in_test_package 0.031s ``` golang-go.uber-mock-0.5.0/mockgen/internal/tests/mock_in_test_package/mock_test.go000066400000000000000000000034441470430142200303240ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: user.go // // Generated by this command: // // mockgen --source=user.go --destination=mock_test.go --package=users_test // // Package users_test is a generated GoMock package. package users_test import ( reflect "reflect" gomock "go.uber.org/mock/gomock" users "go.uber.org/mock/mockgen/internal/tests/mock_in_test_package" ) // MockFinder is a mock of Finder interface. type MockFinder struct { ctrl *gomock.Controller recorder *MockFinderMockRecorder isgomock struct{} } // MockFinderMockRecorder is the mock recorder for MockFinder. type MockFinderMockRecorder struct { mock *MockFinder } // NewMockFinder creates a new mock instance. func NewMockFinder(ctrl *gomock.Controller) *MockFinder { mock := &MockFinder{ctrl: ctrl} mock.recorder = &MockFinderMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockFinder) EXPECT() *MockFinderMockRecorder { return m.recorder } // Add mocks base method. func (m *MockFinder) Add(u users.User) { m.ctrl.T.Helper() m.ctrl.Call(m, "Add", u) } // Add indicates an expected call of Add. func (mr *MockFinderMockRecorder) Add(u any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Add", reflect.TypeOf((*MockFinder)(nil).Add), u) } // FindUser mocks base method. func (m *MockFinder) FindUser(name string) users.User { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "FindUser", name) ret0, _ := ret[0].(users.User) return ret0 } // FindUser indicates an expected call of FindUser. func (mr *MockFinderMockRecorder) FindUser(name any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindUser", reflect.TypeOf((*MockFinder)(nil).FindUser), name) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/mock_in_test_package/user.go000066400000000000000000000003151470430142200273040ustar00rootroot00000000000000package users //go:generate mockgen --source=user.go --destination=mock_test.go --package=users_test type User struct { Name string } type Finder interface { FindUser(name string) User Add(u User) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/mock_name/000077500000000000000000000000001470430142200236005ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/mock_name/mocks.go000066400000000000000000000010041470430142200252360ustar00rootroot00000000000000package mock_names //go:generate mockgen -mock_names=Service=UserServiceMock -package mocks -typed -destination mocks/user_service.go -self_package go.uber.org/mock/mockgen/internal/tests/mock_name/mocks go.uber.org/mock/mockgen/internal/tests/mock_name/user Service //go:generate mockgen -mock_names=Service=PostServiceMock -package mocks -typed -destination mocks/post_service.go -self_package go.uber.org/mock/mockgen/internal/tests/mock_name/mocks go.uber.org/mock/mockgen/internal/tests/mock_name/post Service golang-go.uber-mock-0.5.0/mockgen/internal/tests/mock_name/mocks/000077500000000000000000000000001470430142200247145ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/mock_name/mocks/post_service.go000066400000000000000000000052231470430142200277520ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: go.uber.org/mock/mockgen/internal/tests/mock_name/post (interfaces: Service) // // Generated by this command: // // mockgen -mock_names=Service=PostServiceMock -package mocks -typed -destination mocks/post_service.go -self_package go.uber.org/mock/mockgen/internal/tests/mock_name/mocks go.uber.org/mock/mockgen/internal/tests/mock_name/post Service // // Package mocks is a generated GoMock package. package mocks import ( reflect "reflect" gomock "go.uber.org/mock/gomock" post "go.uber.org/mock/mockgen/internal/tests/mock_name/post" user "go.uber.org/mock/mockgen/internal/tests/mock_name/user" ) // PostServiceMock is a mock of Service interface. type PostServiceMock struct { ctrl *gomock.Controller recorder *PostServiceMockMockRecorder isgomock struct{} } // PostServiceMockMockRecorder is the mock recorder for PostServiceMock. type PostServiceMockMockRecorder struct { mock *PostServiceMock } // NewPostServiceMock creates a new mock instance. func NewPostServiceMock(ctrl *gomock.Controller) *PostServiceMock { mock := &PostServiceMock{ctrl: ctrl} mock.recorder = &PostServiceMockMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *PostServiceMock) EXPECT() *PostServiceMockMockRecorder { return m.recorder } // Create mocks base method. func (m *PostServiceMock) Create(title, body string, author *user.User) (*post.Post, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Create", title, body, author) ret0, _ := ret[0].(*post.Post) ret1, _ := ret[1].(error) return ret0, ret1 } // Create indicates an expected call of Create. func (mr *PostServiceMockMockRecorder) Create(title, body, author any) *PostServiceMockCreateCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*PostServiceMock)(nil).Create), title, body, author) return &PostServiceMockCreateCall{Call: call} } // PostServiceMockCreateCall wrap *gomock.Call type PostServiceMockCreateCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *PostServiceMockCreateCall) Return(arg0 *post.Post, arg1 error) *PostServiceMockCreateCall { c.Call = c.Call.Return(arg0, arg1) return c } // Do rewrite *gomock.Call.Do func (c *PostServiceMockCreateCall) Do(f func(string, string, *user.User) (*post.Post, error)) *PostServiceMockCreateCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *PostServiceMockCreateCall) DoAndReturn(f func(string, string, *user.User) (*post.Post, error)) *PostServiceMockCreateCall { c.Call = c.Call.DoAndReturn(f) return c } golang-go.uber-mock-0.5.0/mockgen/internal/tests/mock_name/mocks/user_service.go000066400000000000000000000047451470430142200277530ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: go.uber.org/mock/mockgen/internal/tests/mock_name/user (interfaces: Service) // // Generated by this command: // // mockgen -mock_names=Service=UserServiceMock -package mocks -typed -destination mocks/user_service.go -self_package go.uber.org/mock/mockgen/internal/tests/mock_name/mocks go.uber.org/mock/mockgen/internal/tests/mock_name/user Service // // Package mocks is a generated GoMock package. package mocks import ( reflect "reflect" gomock "go.uber.org/mock/gomock" user "go.uber.org/mock/mockgen/internal/tests/mock_name/user" ) // UserServiceMock is a mock of Service interface. type UserServiceMock struct { ctrl *gomock.Controller recorder *UserServiceMockMockRecorder isgomock struct{} } // UserServiceMockMockRecorder is the mock recorder for UserServiceMock. type UserServiceMockMockRecorder struct { mock *UserServiceMock } // NewUserServiceMock creates a new mock instance. func NewUserServiceMock(ctrl *gomock.Controller) *UserServiceMock { mock := &UserServiceMock{ctrl: ctrl} mock.recorder = &UserServiceMockMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *UserServiceMock) EXPECT() *UserServiceMockMockRecorder { return m.recorder } // Create mocks base method. func (m *UserServiceMock) Create(name string) (*user.User, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Create", name) ret0, _ := ret[0].(*user.User) ret1, _ := ret[1].(error) return ret0, ret1 } // Create indicates an expected call of Create. func (mr *UserServiceMockMockRecorder) Create(name any) *UserServiceMockCreateCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*UserServiceMock)(nil).Create), name) return &UserServiceMockCreateCall{Call: call} } // UserServiceMockCreateCall wrap *gomock.Call type UserServiceMockCreateCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *UserServiceMockCreateCall) Return(arg0 *user.User, arg1 error) *UserServiceMockCreateCall { c.Call = c.Call.Return(arg0, arg1) return c } // Do rewrite *gomock.Call.Do func (c *UserServiceMockCreateCall) Do(f func(string) (*user.User, error)) *UserServiceMockCreateCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *UserServiceMockCreateCall) DoAndReturn(f func(string) (*user.User, error)) *UserServiceMockCreateCall { c.Call = c.Call.DoAndReturn(f) return c } golang-go.uber-mock-0.5.0/mockgen/internal/tests/mock_name/mocks_test.go000066400000000000000000000021431470430142200263020ustar00rootroot00000000000000package mock_names import ( "testing" "go.uber.org/mock/gomock" "go.uber.org/mock/mockgen/internal/tests/mock_name/mocks" "go.uber.org/mock/mockgen/internal/tests/mock_name/post" "go.uber.org/mock/mockgen/internal/tests/mock_name/user" ) func TestMockNames(t *testing.T) { ctrl := gomock.NewController(t) userService := mocks.NewUserServiceMock(ctrl) postService := mocks.NewPostServiceMock(ctrl) gomock.InOrder( userService.EXPECT(). Create("John Doe"). Return(&user.User{Name: "John Doe"}, nil), postService.EXPECT(). Create(gomock.Eq("test title"), gomock.Eq("test body"), gomock.Eq(&user.User{Name: "John Doe"})). Return(&post.Post{ Title: "test title", Body: "test body", Author: &user.User{ Name: "John Doe", }, }, nil)) u, err := userService.Create("John Doe") if err != nil { t.Fatal("unexpected error") } p, err := postService.Create("test title", "test body", u) if err != nil { t.Fatal("unexpected error") } if p.Title != "test title" || p.Body != "test body" || p.Author.Name != u.Name { t.Fatal("unexpected postService.Create result") } } golang-go.uber-mock-0.5.0/mockgen/internal/tests/mock_name/post/000077500000000000000000000000001470430142200245655ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/mock_name/post/service.go000066400000000000000000000003641470430142200265570ustar00rootroot00000000000000package post import ( "go.uber.org/mock/mockgen/internal/tests/mock_name/user" ) type Post struct { Title string Body string Author *user.User } type Service interface { Create(title, body string, author *user.User) (*Post, error) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/mock_name/user/000077500000000000000000000000001470430142200245565ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/mock_name/user/service.go000066400000000000000000000001601470430142200265420ustar00rootroot00000000000000package user type User struct { Name string } type Service interface { Create(name string) (*User, error) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/overlapping_methods/000077500000000000000000000000001470430142200257205ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/overlapping_methods/interfaces.go000066400000000000000000000002441470430142200303720ustar00rootroot00000000000000package overlap type ReadCloser interface { Read([]byte) (int, error) Close() error } type WriteCloser interface { Write([]byte) (int, error) Close() error } golang-go.uber-mock-0.5.0/mockgen/internal/tests/overlapping_methods/mock.go000066400000000000000000000047731470430142200272130ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: overlap.go // // Generated by this command: // // mockgen -package overlap -destination mock.go -source overlap.go -aux_files go.uber.org/mock/mockgen/internal/tests/overlapping_methods=interfaces.go // // Package overlap is a generated GoMock package. package overlap import ( reflect "reflect" gomock "go.uber.org/mock/gomock" ) // MockReadWriteCloser is a mock of ReadWriteCloser interface. type MockReadWriteCloser struct { ctrl *gomock.Controller recorder *MockReadWriteCloserMockRecorder isgomock struct{} } // MockReadWriteCloserMockRecorder is the mock recorder for MockReadWriteCloser. type MockReadWriteCloserMockRecorder struct { mock *MockReadWriteCloser } // NewMockReadWriteCloser creates a new mock instance. func NewMockReadWriteCloser(ctrl *gomock.Controller) *MockReadWriteCloser { mock := &MockReadWriteCloser{ctrl: ctrl} mock.recorder = &MockReadWriteCloserMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockReadWriteCloser) EXPECT() *MockReadWriteCloserMockRecorder { return m.recorder } // Close mocks base method. func (m *MockReadWriteCloser) Close() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Close") ret0, _ := ret[0].(error) return ret0 } // Close indicates an expected call of Close. func (mr *MockReadWriteCloserMockRecorder) Close() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockReadWriteCloser)(nil).Close)) } // Read mocks base method. func (m *MockReadWriteCloser) Read(arg0 []byte) (int, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Read", arg0) ret0, _ := ret[0].(int) ret1, _ := ret[1].(error) return ret0, ret1 } // Read indicates an expected call of Read. func (mr *MockReadWriteCloserMockRecorder) Read(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Read", reflect.TypeOf((*MockReadWriteCloser)(nil).Read), arg0) } // Write mocks base method. func (m *MockReadWriteCloser) Write(arg0 []byte) (int, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Write", arg0) ret0, _ := ret[0].(int) ret1, _ := ret[1].(error) return ret0, ret1 } // Write indicates an expected call of Write. func (mr *MockReadWriteCloserMockRecorder) Write(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Write", reflect.TypeOf((*MockReadWriteCloser)(nil).Write), arg0) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/overlapping_methods/overlap.go000066400000000000000000000003621470430142200277200ustar00rootroot00000000000000package overlap //go:generate mockgen -package overlap -destination mock.go -source overlap.go -aux_files go.uber.org/mock/mockgen/internal/tests/overlapping_methods=interfaces.go type ReadWriteCloser interface { ReadCloser WriteCloser } golang-go.uber-mock-0.5.0/mockgen/internal/tests/overlapping_methods/overlap_test.go000066400000000000000000000005111470430142200307530ustar00rootroot00000000000000package overlap import ( "errors" "testing" gomock "go.uber.org/mock/gomock" ) // TestValidInterface assesses whether or not the generated mock is valid func TestValidInterface(t *testing.T) { ctrl := gomock.NewController(t) s := NewMockReadWriteCloser(ctrl) s.EXPECT().Close().Return(errors.New("test")) s.Close() } golang-go.uber-mock-0.5.0/mockgen/internal/tests/package_comment/000077500000000000000000000000001470430142200247645ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/package_comment/input.go000066400000000000000000000002431470430142200264510ustar00rootroot00000000000000package empty_interface //go:generate mockgen -package empty_interface -destination mock.go -source input.go -write_package_comment=false type Empty interface{} golang-go.uber-mock-0.5.0/mockgen/internal/tests/package_comment/mock.go000066400000000000000000000015741470430142200262530ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: input.go // // Generated by this command: // // mockgen -package empty_interface -destination mock.go -source input.go -write_package_comment=false // package empty_interface import ( gomock "go.uber.org/mock/gomock" ) // MockEmpty is a mock of Empty interface. type MockEmpty struct { ctrl *gomock.Controller recorder *MockEmptyMockRecorder isgomock struct{} } // MockEmptyMockRecorder is the mock recorder for MockEmpty. type MockEmptyMockRecorder struct { mock *MockEmpty } // NewMockEmpty creates a new mock instance. func NewMockEmpty(ctrl *gomock.Controller) *MockEmpty { mock := &MockEmpty{ctrl: ctrl} mock.recorder = &MockEmptyMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockEmpty) EXPECT() *MockEmptyMockRecorder { return m.recorder } golang-go.uber-mock-0.5.0/mockgen/internal/tests/package_mode/000077500000000000000000000000001470430142200242465ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/package_mode/cars/000077500000000000000000000000001470430142200251765ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/package_mode/cars/cars.go000066400000000000000000000013451470430142200264600ustar00rootroot00000000000000package cars import ( "go.uber.org/mock/mockgen/internal/tests/package_mode/fuel" ) type FuelTank[FuelType fuel.Fuel] struct { Fuel FuelType Capacity int } type HyundaiSolaris struct{} func (HyundaiSolaris) Refuel(fuel.Gasoline, int) error { return nil } func (HyundaiSolaris) Brand() string { return "Hyundai" } func (HyundaiSolaris) FuelTank() FuelTank[fuel.Gasoline] { return FuelTank[fuel.Gasoline]{ Fuel: fuel.Gasoline{}, Capacity: 50, } } type FordF150 struct{} func (FordF150) Brand() string { return "Ford" } func (FordF150) Refuel(fuel.Diesel, int) error { return nil } func (FordF150) FuelTank() FuelTank[fuel.Diesel] { return FuelTank[fuel.Diesel]{ Fuel: fuel.Diesel{}, Capacity: 136, } } golang-go.uber-mock-0.5.0/mockgen/internal/tests/package_mode/fuel/000077500000000000000000000000001470430142200252015ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/package_mode/fuel/fuel.go000066400000000000000000000003451470430142200264650ustar00rootroot00000000000000package fuel type Fuel interface { EnergyCapacity() int Diesel | Gasoline } type Diesel struct{} func (Diesel) EnergyCapacity() int { return 48 } type Gasoline struct{} func (Gasoline) EnergyCapacity() int { return 46 } golang-go.uber-mock-0.5.0/mockgen/internal/tests/package_mode/interfaces.go000066400000000000000000000022271470430142200267230ustar00rootroot00000000000000package package_mode //go:generate mockgen -typed -package=mock -destination=mock/interfaces.go . Food,Eater,Animal,Human,Primate,Car,Driver,UrbanResident,Farmer,Earth import ( "time" "go.uber.org/mock/mockgen/internal/tests/package_mode/cars" "go.uber.org/mock/mockgen/internal/tests/package_mode/fuel" ) type Food interface { Calories() int } type Eater interface { Eat(foods ...Food) } type Animal interface { Eater Breathe() Sleep(duration time.Duration) } type Primate Animal type Human = Primate type Car[FuelType fuel.Fuel] interface { Brand() string FuelTank() cars.FuelTank[FuelType] Refuel(fuel FuelType, volume int) error } type Driver[FuelType fuel.Fuel, CarType Car[FuelType]] interface { Wroom() error Drive(car CarType) } type UrbanResident interface { Human Driver[fuel.Gasoline, cars.HyundaiSolaris] Do(work *Work) error LivesInACity() } type Farmer interface { Human Driver[fuel.Diesel, cars.FordF150] Do(work *Work) error LivesInAVillage() } type Work struct { Name string } type Counter interface { int } type HumansCount = int type Earth interface { AddHumans(HumansCount) []Human HumanPopulation() HumansCount } golang-go.uber-mock-0.5.0/mockgen/internal/tests/package_mode/mock/000077500000000000000000000000001470430142200251775ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/package_mode/mock/interfaces.go000066400000000000000000001216711470430142200276610ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: go.uber.org/mock/mockgen/internal/tests/package_mode (interfaces: Food,Eater,Animal,Human,Primate,Car,Driver,UrbanResident,Farmer,Earth) // // Generated by this command: // // mockgen -typed -package=mock -destination=mock/interfaces.go . Food,Eater,Animal,Human,Primate,Car,Driver,UrbanResident,Farmer,Earth // // Package mock is a generated GoMock package. package mock import ( reflect "reflect" time "time" gomock "go.uber.org/mock/gomock" package_mode "go.uber.org/mock/mockgen/internal/tests/package_mode" cars "go.uber.org/mock/mockgen/internal/tests/package_mode/cars" fuel "go.uber.org/mock/mockgen/internal/tests/package_mode/fuel" ) // MockFood is a mock of Food interface. type MockFood struct { ctrl *gomock.Controller recorder *MockFoodMockRecorder isgomock struct{} } // MockFoodMockRecorder is the mock recorder for MockFood. type MockFoodMockRecorder struct { mock *MockFood } // NewMockFood creates a new mock instance. func NewMockFood(ctrl *gomock.Controller) *MockFood { mock := &MockFood{ctrl: ctrl} mock.recorder = &MockFoodMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockFood) EXPECT() *MockFoodMockRecorder { return m.recorder } // Calories mocks base method. func (m *MockFood) Calories() int { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Calories") ret0, _ := ret[0].(int) return ret0 } // Calories indicates an expected call of Calories. func (mr *MockFoodMockRecorder) Calories() *MockFoodCaloriesCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Calories", reflect.TypeOf((*MockFood)(nil).Calories)) return &MockFoodCaloriesCall{Call: call} } // MockFoodCaloriesCall wrap *gomock.Call type MockFoodCaloriesCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockFoodCaloriesCall) Return(arg0 int) *MockFoodCaloriesCall { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockFoodCaloriesCall) Do(f func() int) *MockFoodCaloriesCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockFoodCaloriesCall) DoAndReturn(f func() int) *MockFoodCaloriesCall { c.Call = c.Call.DoAndReturn(f) return c } // MockEater is a mock of Eater interface. type MockEater struct { ctrl *gomock.Controller recorder *MockEaterMockRecorder isgomock struct{} } // MockEaterMockRecorder is the mock recorder for MockEater. type MockEaterMockRecorder struct { mock *MockEater } // NewMockEater creates a new mock instance. func NewMockEater(ctrl *gomock.Controller) *MockEater { mock := &MockEater{ctrl: ctrl} mock.recorder = &MockEaterMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockEater) EXPECT() *MockEaterMockRecorder { return m.recorder } // Eat mocks base method. func (m *MockEater) Eat(foods ...package_mode.Food) { m.ctrl.T.Helper() varargs := []any{} for _, a := range foods { varargs = append(varargs, a) } m.ctrl.Call(m, "Eat", varargs...) } // Eat indicates an expected call of Eat. func (mr *MockEaterMockRecorder) Eat(foods ...any) *MockEaterEatCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Eat", reflect.TypeOf((*MockEater)(nil).Eat), foods...) return &MockEaterEatCall{Call: call} } // MockEaterEatCall wrap *gomock.Call type MockEaterEatCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockEaterEatCall) Return() *MockEaterEatCall { c.Call = c.Call.Return() return c } // Do rewrite *gomock.Call.Do func (c *MockEaterEatCall) Do(f func(...package_mode.Food)) *MockEaterEatCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockEaterEatCall) DoAndReturn(f func(...package_mode.Food)) *MockEaterEatCall { c.Call = c.Call.DoAndReturn(f) return c } // MockAnimal is a mock of Animal interface. type MockAnimal struct { ctrl *gomock.Controller recorder *MockAnimalMockRecorder isgomock struct{} } // MockAnimalMockRecorder is the mock recorder for MockAnimal. type MockAnimalMockRecorder struct { mock *MockAnimal } // NewMockAnimal creates a new mock instance. func NewMockAnimal(ctrl *gomock.Controller) *MockAnimal { mock := &MockAnimal{ctrl: ctrl} mock.recorder = &MockAnimalMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockAnimal) EXPECT() *MockAnimalMockRecorder { return m.recorder } // Breathe mocks base method. func (m *MockAnimal) Breathe() { m.ctrl.T.Helper() m.ctrl.Call(m, "Breathe") } // Breathe indicates an expected call of Breathe. func (mr *MockAnimalMockRecorder) Breathe() *MockAnimalBreatheCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Breathe", reflect.TypeOf((*MockAnimal)(nil).Breathe)) return &MockAnimalBreatheCall{Call: call} } // MockAnimalBreatheCall wrap *gomock.Call type MockAnimalBreatheCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockAnimalBreatheCall) Return() *MockAnimalBreatheCall { c.Call = c.Call.Return() return c } // Do rewrite *gomock.Call.Do func (c *MockAnimalBreatheCall) Do(f func()) *MockAnimalBreatheCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockAnimalBreatheCall) DoAndReturn(f func()) *MockAnimalBreatheCall { c.Call = c.Call.DoAndReturn(f) return c } // Eat mocks base method. func (m *MockAnimal) Eat(foods ...package_mode.Food) { m.ctrl.T.Helper() varargs := []any{} for _, a := range foods { varargs = append(varargs, a) } m.ctrl.Call(m, "Eat", varargs...) } // Eat indicates an expected call of Eat. func (mr *MockAnimalMockRecorder) Eat(foods ...any) *MockAnimalEatCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Eat", reflect.TypeOf((*MockAnimal)(nil).Eat), foods...) return &MockAnimalEatCall{Call: call} } // MockAnimalEatCall wrap *gomock.Call type MockAnimalEatCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockAnimalEatCall) Return() *MockAnimalEatCall { c.Call = c.Call.Return() return c } // Do rewrite *gomock.Call.Do func (c *MockAnimalEatCall) Do(f func(...package_mode.Food)) *MockAnimalEatCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockAnimalEatCall) DoAndReturn(f func(...package_mode.Food)) *MockAnimalEatCall { c.Call = c.Call.DoAndReturn(f) return c } // Sleep mocks base method. func (m *MockAnimal) Sleep(duration time.Duration) { m.ctrl.T.Helper() m.ctrl.Call(m, "Sleep", duration) } // Sleep indicates an expected call of Sleep. func (mr *MockAnimalMockRecorder) Sleep(duration any) *MockAnimalSleepCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Sleep", reflect.TypeOf((*MockAnimal)(nil).Sleep), duration) return &MockAnimalSleepCall{Call: call} } // MockAnimalSleepCall wrap *gomock.Call type MockAnimalSleepCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockAnimalSleepCall) Return() *MockAnimalSleepCall { c.Call = c.Call.Return() return c } // Do rewrite *gomock.Call.Do func (c *MockAnimalSleepCall) Do(f func(time.Duration)) *MockAnimalSleepCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockAnimalSleepCall) DoAndReturn(f func(time.Duration)) *MockAnimalSleepCall { c.Call = c.Call.DoAndReturn(f) return c } // MockHuman is a mock of Human interface. type MockHuman struct { ctrl *gomock.Controller recorder *MockHumanMockRecorder isgomock struct{} } // MockHumanMockRecorder is the mock recorder for MockHuman. type MockHumanMockRecorder struct { mock *MockHuman } // NewMockHuman creates a new mock instance. func NewMockHuman(ctrl *gomock.Controller) *MockHuman { mock := &MockHuman{ctrl: ctrl} mock.recorder = &MockHumanMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockHuman) EXPECT() *MockHumanMockRecorder { return m.recorder } // Breathe mocks base method. func (m *MockHuman) Breathe() { m.ctrl.T.Helper() m.ctrl.Call(m, "Breathe") } // Breathe indicates an expected call of Breathe. func (mr *MockHumanMockRecorder) Breathe() *MockHumanBreatheCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Breathe", reflect.TypeOf((*MockHuman)(nil).Breathe)) return &MockHumanBreatheCall{Call: call} } // MockHumanBreatheCall wrap *gomock.Call type MockHumanBreatheCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockHumanBreatheCall) Return() *MockHumanBreatheCall { c.Call = c.Call.Return() return c } // Do rewrite *gomock.Call.Do func (c *MockHumanBreatheCall) Do(f func()) *MockHumanBreatheCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockHumanBreatheCall) DoAndReturn(f func()) *MockHumanBreatheCall { c.Call = c.Call.DoAndReturn(f) return c } // Eat mocks base method. func (m *MockHuman) Eat(foods ...package_mode.Food) { m.ctrl.T.Helper() varargs := []any{} for _, a := range foods { varargs = append(varargs, a) } m.ctrl.Call(m, "Eat", varargs...) } // Eat indicates an expected call of Eat. func (mr *MockHumanMockRecorder) Eat(foods ...any) *MockHumanEatCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Eat", reflect.TypeOf((*MockHuman)(nil).Eat), foods...) return &MockHumanEatCall{Call: call} } // MockHumanEatCall wrap *gomock.Call type MockHumanEatCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockHumanEatCall) Return() *MockHumanEatCall { c.Call = c.Call.Return() return c } // Do rewrite *gomock.Call.Do func (c *MockHumanEatCall) Do(f func(...package_mode.Food)) *MockHumanEatCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockHumanEatCall) DoAndReturn(f func(...package_mode.Food)) *MockHumanEatCall { c.Call = c.Call.DoAndReturn(f) return c } // Sleep mocks base method. func (m *MockHuman) Sleep(duration time.Duration) { m.ctrl.T.Helper() m.ctrl.Call(m, "Sleep", duration) } // Sleep indicates an expected call of Sleep. func (mr *MockHumanMockRecorder) Sleep(duration any) *MockHumanSleepCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Sleep", reflect.TypeOf((*MockHuman)(nil).Sleep), duration) return &MockHumanSleepCall{Call: call} } // MockHumanSleepCall wrap *gomock.Call type MockHumanSleepCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockHumanSleepCall) Return() *MockHumanSleepCall { c.Call = c.Call.Return() return c } // Do rewrite *gomock.Call.Do func (c *MockHumanSleepCall) Do(f func(time.Duration)) *MockHumanSleepCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockHumanSleepCall) DoAndReturn(f func(time.Duration)) *MockHumanSleepCall { c.Call = c.Call.DoAndReturn(f) return c } // MockPrimate is a mock of Primate interface. type MockPrimate struct { ctrl *gomock.Controller recorder *MockPrimateMockRecorder isgomock struct{} } // MockPrimateMockRecorder is the mock recorder for MockPrimate. type MockPrimateMockRecorder struct { mock *MockPrimate } // NewMockPrimate creates a new mock instance. func NewMockPrimate(ctrl *gomock.Controller) *MockPrimate { mock := &MockPrimate{ctrl: ctrl} mock.recorder = &MockPrimateMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockPrimate) EXPECT() *MockPrimateMockRecorder { return m.recorder } // Breathe mocks base method. func (m *MockPrimate) Breathe() { m.ctrl.T.Helper() m.ctrl.Call(m, "Breathe") } // Breathe indicates an expected call of Breathe. func (mr *MockPrimateMockRecorder) Breathe() *MockPrimateBreatheCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Breathe", reflect.TypeOf((*MockPrimate)(nil).Breathe)) return &MockPrimateBreatheCall{Call: call} } // MockPrimateBreatheCall wrap *gomock.Call type MockPrimateBreatheCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockPrimateBreatheCall) Return() *MockPrimateBreatheCall { c.Call = c.Call.Return() return c } // Do rewrite *gomock.Call.Do func (c *MockPrimateBreatheCall) Do(f func()) *MockPrimateBreatheCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockPrimateBreatheCall) DoAndReturn(f func()) *MockPrimateBreatheCall { c.Call = c.Call.DoAndReturn(f) return c } // Eat mocks base method. func (m *MockPrimate) Eat(foods ...package_mode.Food) { m.ctrl.T.Helper() varargs := []any{} for _, a := range foods { varargs = append(varargs, a) } m.ctrl.Call(m, "Eat", varargs...) } // Eat indicates an expected call of Eat. func (mr *MockPrimateMockRecorder) Eat(foods ...any) *MockPrimateEatCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Eat", reflect.TypeOf((*MockPrimate)(nil).Eat), foods...) return &MockPrimateEatCall{Call: call} } // MockPrimateEatCall wrap *gomock.Call type MockPrimateEatCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockPrimateEatCall) Return() *MockPrimateEatCall { c.Call = c.Call.Return() return c } // Do rewrite *gomock.Call.Do func (c *MockPrimateEatCall) Do(f func(...package_mode.Food)) *MockPrimateEatCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockPrimateEatCall) DoAndReturn(f func(...package_mode.Food)) *MockPrimateEatCall { c.Call = c.Call.DoAndReturn(f) return c } // Sleep mocks base method. func (m *MockPrimate) Sleep(duration time.Duration) { m.ctrl.T.Helper() m.ctrl.Call(m, "Sleep", duration) } // Sleep indicates an expected call of Sleep. func (mr *MockPrimateMockRecorder) Sleep(duration any) *MockPrimateSleepCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Sleep", reflect.TypeOf((*MockPrimate)(nil).Sleep), duration) return &MockPrimateSleepCall{Call: call} } // MockPrimateSleepCall wrap *gomock.Call type MockPrimateSleepCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockPrimateSleepCall) Return() *MockPrimateSleepCall { c.Call = c.Call.Return() return c } // Do rewrite *gomock.Call.Do func (c *MockPrimateSleepCall) Do(f func(time.Duration)) *MockPrimateSleepCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockPrimateSleepCall) DoAndReturn(f func(time.Duration)) *MockPrimateSleepCall { c.Call = c.Call.DoAndReturn(f) return c } // MockCar is a mock of Car interface. type MockCar[FuelType fuel.Fuel] struct { ctrl *gomock.Controller recorder *MockCarMockRecorder[FuelType] isgomock struct{} } // MockCarMockRecorder is the mock recorder for MockCar. type MockCarMockRecorder[FuelType fuel.Fuel] struct { mock *MockCar[FuelType] } // NewMockCar creates a new mock instance. func NewMockCar[FuelType fuel.Fuel](ctrl *gomock.Controller) *MockCar[FuelType] { mock := &MockCar[FuelType]{ctrl: ctrl} mock.recorder = &MockCarMockRecorder[FuelType]{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockCar[FuelType]) EXPECT() *MockCarMockRecorder[FuelType] { return m.recorder } // Brand mocks base method. func (m *MockCar[FuelType]) Brand() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Brand") ret0, _ := ret[0].(string) return ret0 } // Brand indicates an expected call of Brand. func (mr *MockCarMockRecorder[FuelType]) Brand() *MockCarBrandCall[FuelType] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Brand", reflect.TypeOf((*MockCar[FuelType])(nil).Brand)) return &MockCarBrandCall[FuelType]{Call: call} } // MockCarBrandCall wrap *gomock.Call type MockCarBrandCall[FuelType fuel.Fuel] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockCarBrandCall[FuelType]) Return(arg0 string) *MockCarBrandCall[FuelType] { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockCarBrandCall[FuelType]) Do(f func() string) *MockCarBrandCall[FuelType] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockCarBrandCall[FuelType]) DoAndReturn(f func() string) *MockCarBrandCall[FuelType] { c.Call = c.Call.DoAndReturn(f) return c } // FuelTank mocks base method. func (m *MockCar[FuelType]) FuelTank() cars.FuelTank[FuelType] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "FuelTank") ret0, _ := ret[0].(cars.FuelTank[FuelType]) return ret0 } // FuelTank indicates an expected call of FuelTank. func (mr *MockCarMockRecorder[FuelType]) FuelTank() *MockCarFuelTankCall[FuelType] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FuelTank", reflect.TypeOf((*MockCar[FuelType])(nil).FuelTank)) return &MockCarFuelTankCall[FuelType]{Call: call} } // MockCarFuelTankCall wrap *gomock.Call type MockCarFuelTankCall[FuelType fuel.Fuel] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockCarFuelTankCall[FuelType]) Return(arg0 cars.FuelTank[FuelType]) *MockCarFuelTankCall[FuelType] { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockCarFuelTankCall[FuelType]) Do(f func() cars.FuelTank[FuelType]) *MockCarFuelTankCall[FuelType] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockCarFuelTankCall[FuelType]) DoAndReturn(f func() cars.FuelTank[FuelType]) *MockCarFuelTankCall[FuelType] { c.Call = c.Call.DoAndReturn(f) return c } // Refuel mocks base method. func (m *MockCar[FuelType]) Refuel(fuel FuelType, volume int) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Refuel", fuel, volume) ret0, _ := ret[0].(error) return ret0 } // Refuel indicates an expected call of Refuel. func (mr *MockCarMockRecorder[FuelType]) Refuel(fuel, volume any) *MockCarRefuelCall[FuelType] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Refuel", reflect.TypeOf((*MockCar[FuelType])(nil).Refuel), fuel, volume) return &MockCarRefuelCall[FuelType]{Call: call} } // MockCarRefuelCall wrap *gomock.Call type MockCarRefuelCall[FuelType fuel.Fuel] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockCarRefuelCall[FuelType]) Return(arg0 error) *MockCarRefuelCall[FuelType] { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockCarRefuelCall[FuelType]) Do(f func(FuelType, int) error) *MockCarRefuelCall[FuelType] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockCarRefuelCall[FuelType]) DoAndReturn(f func(FuelType, int) error) *MockCarRefuelCall[FuelType] { c.Call = c.Call.DoAndReturn(f) return c } // MockDriver is a mock of Driver interface. type MockDriver[FuelType fuel.Fuel, CarType package_mode.Car[FuelType]] struct { ctrl *gomock.Controller recorder *MockDriverMockRecorder[FuelType, CarType] isgomock struct{} } // MockDriverMockRecorder is the mock recorder for MockDriver. type MockDriverMockRecorder[FuelType fuel.Fuel, CarType package_mode.Car[FuelType]] struct { mock *MockDriver[FuelType, CarType] } // NewMockDriver creates a new mock instance. func NewMockDriver[FuelType fuel.Fuel, CarType package_mode.Car[FuelType]](ctrl *gomock.Controller) *MockDriver[FuelType, CarType] { mock := &MockDriver[FuelType, CarType]{ctrl: ctrl} mock.recorder = &MockDriverMockRecorder[FuelType, CarType]{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockDriver[FuelType, CarType]) EXPECT() *MockDriverMockRecorder[FuelType, CarType] { return m.recorder } // Drive mocks base method. func (m *MockDriver[FuelType, CarType]) Drive(car CarType) { m.ctrl.T.Helper() m.ctrl.Call(m, "Drive", car) } // Drive indicates an expected call of Drive. func (mr *MockDriverMockRecorder[FuelType, CarType]) Drive(car any) *MockDriverDriveCall[FuelType, CarType] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Drive", reflect.TypeOf((*MockDriver[FuelType, CarType])(nil).Drive), car) return &MockDriverDriveCall[FuelType, CarType]{Call: call} } // MockDriverDriveCall wrap *gomock.Call type MockDriverDriveCall[FuelType fuel.Fuel, CarType package_mode.Car[FuelType]] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockDriverDriveCall[FuelType, CarType]) Return() *MockDriverDriveCall[FuelType, CarType] { c.Call = c.Call.Return() return c } // Do rewrite *gomock.Call.Do func (c *MockDriverDriveCall[FuelType, CarType]) Do(f func(CarType)) *MockDriverDriveCall[FuelType, CarType] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockDriverDriveCall[FuelType, CarType]) DoAndReturn(f func(CarType)) *MockDriverDriveCall[FuelType, CarType] { c.Call = c.Call.DoAndReturn(f) return c } // Wroom mocks base method. func (m *MockDriver[FuelType, CarType]) Wroom() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Wroom") ret0, _ := ret[0].(error) return ret0 } // Wroom indicates an expected call of Wroom. func (mr *MockDriverMockRecorder[FuelType, CarType]) Wroom() *MockDriverWroomCall[FuelType, CarType] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Wroom", reflect.TypeOf((*MockDriver[FuelType, CarType])(nil).Wroom)) return &MockDriverWroomCall[FuelType, CarType]{Call: call} } // MockDriverWroomCall wrap *gomock.Call type MockDriverWroomCall[FuelType fuel.Fuel, CarType package_mode.Car[FuelType]] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockDriverWroomCall[FuelType, CarType]) Return(arg0 error) *MockDriverWroomCall[FuelType, CarType] { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockDriverWroomCall[FuelType, CarType]) Do(f func() error) *MockDriverWroomCall[FuelType, CarType] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockDriverWroomCall[FuelType, CarType]) DoAndReturn(f func() error) *MockDriverWroomCall[FuelType, CarType] { c.Call = c.Call.DoAndReturn(f) return c } // MockUrbanResident is a mock of UrbanResident interface. type MockUrbanResident struct { ctrl *gomock.Controller recorder *MockUrbanResidentMockRecorder isgomock struct{} } // MockUrbanResidentMockRecorder is the mock recorder for MockUrbanResident. type MockUrbanResidentMockRecorder struct { mock *MockUrbanResident } // NewMockUrbanResident creates a new mock instance. func NewMockUrbanResident(ctrl *gomock.Controller) *MockUrbanResident { mock := &MockUrbanResident{ctrl: ctrl} mock.recorder = &MockUrbanResidentMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockUrbanResident) EXPECT() *MockUrbanResidentMockRecorder { return m.recorder } // Breathe mocks base method. func (m *MockUrbanResident) Breathe() { m.ctrl.T.Helper() m.ctrl.Call(m, "Breathe") } // Breathe indicates an expected call of Breathe. func (mr *MockUrbanResidentMockRecorder) Breathe() *MockUrbanResidentBreatheCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Breathe", reflect.TypeOf((*MockUrbanResident)(nil).Breathe)) return &MockUrbanResidentBreatheCall{Call: call} } // MockUrbanResidentBreatheCall wrap *gomock.Call type MockUrbanResidentBreatheCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockUrbanResidentBreatheCall) Return() *MockUrbanResidentBreatheCall { c.Call = c.Call.Return() return c } // Do rewrite *gomock.Call.Do func (c *MockUrbanResidentBreatheCall) Do(f func()) *MockUrbanResidentBreatheCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockUrbanResidentBreatheCall) DoAndReturn(f func()) *MockUrbanResidentBreatheCall { c.Call = c.Call.DoAndReturn(f) return c } // Do mocks base method. func (m *MockUrbanResident) Do(work *package_mode.Work) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Do", work) ret0, _ := ret[0].(error) return ret0 } // Do indicates an expected call of Do. func (mr *MockUrbanResidentMockRecorder) Do(work any) *MockUrbanResidentDoCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Do", reflect.TypeOf((*MockUrbanResident)(nil).Do), work) return &MockUrbanResidentDoCall{Call: call} } // MockUrbanResidentDoCall wrap *gomock.Call type MockUrbanResidentDoCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockUrbanResidentDoCall) Return(arg0 error) *MockUrbanResidentDoCall { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockUrbanResidentDoCall) Do(f func(*package_mode.Work) error) *MockUrbanResidentDoCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockUrbanResidentDoCall) DoAndReturn(f func(*package_mode.Work) error) *MockUrbanResidentDoCall { c.Call = c.Call.DoAndReturn(f) return c } // Drive mocks base method. func (m *MockUrbanResident) Drive(car cars.HyundaiSolaris) { m.ctrl.T.Helper() m.ctrl.Call(m, "Drive", car) } // Drive indicates an expected call of Drive. func (mr *MockUrbanResidentMockRecorder) Drive(car any) *MockUrbanResidentDriveCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Drive", reflect.TypeOf((*MockUrbanResident)(nil).Drive), car) return &MockUrbanResidentDriveCall{Call: call} } // MockUrbanResidentDriveCall wrap *gomock.Call type MockUrbanResidentDriveCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockUrbanResidentDriveCall) Return() *MockUrbanResidentDriveCall { c.Call = c.Call.Return() return c } // Do rewrite *gomock.Call.Do func (c *MockUrbanResidentDriveCall) Do(f func(cars.HyundaiSolaris)) *MockUrbanResidentDriveCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockUrbanResidentDriveCall) DoAndReturn(f func(cars.HyundaiSolaris)) *MockUrbanResidentDriveCall { c.Call = c.Call.DoAndReturn(f) return c } // Eat mocks base method. func (m *MockUrbanResident) Eat(foods ...package_mode.Food) { m.ctrl.T.Helper() varargs := []any{} for _, a := range foods { varargs = append(varargs, a) } m.ctrl.Call(m, "Eat", varargs...) } // Eat indicates an expected call of Eat. func (mr *MockUrbanResidentMockRecorder) Eat(foods ...any) *MockUrbanResidentEatCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Eat", reflect.TypeOf((*MockUrbanResident)(nil).Eat), foods...) return &MockUrbanResidentEatCall{Call: call} } // MockUrbanResidentEatCall wrap *gomock.Call type MockUrbanResidentEatCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockUrbanResidentEatCall) Return() *MockUrbanResidentEatCall { c.Call = c.Call.Return() return c } // Do rewrite *gomock.Call.Do func (c *MockUrbanResidentEatCall) Do(f func(...package_mode.Food)) *MockUrbanResidentEatCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockUrbanResidentEatCall) DoAndReturn(f func(...package_mode.Food)) *MockUrbanResidentEatCall { c.Call = c.Call.DoAndReturn(f) return c } // LivesInACity mocks base method. func (m *MockUrbanResident) LivesInACity() { m.ctrl.T.Helper() m.ctrl.Call(m, "LivesInACity") } // LivesInACity indicates an expected call of LivesInACity. func (mr *MockUrbanResidentMockRecorder) LivesInACity() *MockUrbanResidentLivesInACityCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LivesInACity", reflect.TypeOf((*MockUrbanResident)(nil).LivesInACity)) return &MockUrbanResidentLivesInACityCall{Call: call} } // MockUrbanResidentLivesInACityCall wrap *gomock.Call type MockUrbanResidentLivesInACityCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockUrbanResidentLivesInACityCall) Return() *MockUrbanResidentLivesInACityCall { c.Call = c.Call.Return() return c } // Do rewrite *gomock.Call.Do func (c *MockUrbanResidentLivesInACityCall) Do(f func()) *MockUrbanResidentLivesInACityCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockUrbanResidentLivesInACityCall) DoAndReturn(f func()) *MockUrbanResidentLivesInACityCall { c.Call = c.Call.DoAndReturn(f) return c } // Sleep mocks base method. func (m *MockUrbanResident) Sleep(duration time.Duration) { m.ctrl.T.Helper() m.ctrl.Call(m, "Sleep", duration) } // Sleep indicates an expected call of Sleep. func (mr *MockUrbanResidentMockRecorder) Sleep(duration any) *MockUrbanResidentSleepCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Sleep", reflect.TypeOf((*MockUrbanResident)(nil).Sleep), duration) return &MockUrbanResidentSleepCall{Call: call} } // MockUrbanResidentSleepCall wrap *gomock.Call type MockUrbanResidentSleepCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockUrbanResidentSleepCall) Return() *MockUrbanResidentSleepCall { c.Call = c.Call.Return() return c } // Do rewrite *gomock.Call.Do func (c *MockUrbanResidentSleepCall) Do(f func(time.Duration)) *MockUrbanResidentSleepCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockUrbanResidentSleepCall) DoAndReturn(f func(time.Duration)) *MockUrbanResidentSleepCall { c.Call = c.Call.DoAndReturn(f) return c } // Wroom mocks base method. func (m *MockUrbanResident) Wroom() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Wroom") ret0, _ := ret[0].(error) return ret0 } // Wroom indicates an expected call of Wroom. func (mr *MockUrbanResidentMockRecorder) Wroom() *MockUrbanResidentWroomCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Wroom", reflect.TypeOf((*MockUrbanResident)(nil).Wroom)) return &MockUrbanResidentWroomCall{Call: call} } // MockUrbanResidentWroomCall wrap *gomock.Call type MockUrbanResidentWroomCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockUrbanResidentWroomCall) Return(arg0 error) *MockUrbanResidentWroomCall { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockUrbanResidentWroomCall) Do(f func() error) *MockUrbanResidentWroomCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockUrbanResidentWroomCall) DoAndReturn(f func() error) *MockUrbanResidentWroomCall { c.Call = c.Call.DoAndReturn(f) return c } // MockFarmer is a mock of Farmer interface. type MockFarmer struct { ctrl *gomock.Controller recorder *MockFarmerMockRecorder isgomock struct{} } // MockFarmerMockRecorder is the mock recorder for MockFarmer. type MockFarmerMockRecorder struct { mock *MockFarmer } // NewMockFarmer creates a new mock instance. func NewMockFarmer(ctrl *gomock.Controller) *MockFarmer { mock := &MockFarmer{ctrl: ctrl} mock.recorder = &MockFarmerMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockFarmer) EXPECT() *MockFarmerMockRecorder { return m.recorder } // Breathe mocks base method. func (m *MockFarmer) Breathe() { m.ctrl.T.Helper() m.ctrl.Call(m, "Breathe") } // Breathe indicates an expected call of Breathe. func (mr *MockFarmerMockRecorder) Breathe() *MockFarmerBreatheCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Breathe", reflect.TypeOf((*MockFarmer)(nil).Breathe)) return &MockFarmerBreatheCall{Call: call} } // MockFarmerBreatheCall wrap *gomock.Call type MockFarmerBreatheCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockFarmerBreatheCall) Return() *MockFarmerBreatheCall { c.Call = c.Call.Return() return c } // Do rewrite *gomock.Call.Do func (c *MockFarmerBreatheCall) Do(f func()) *MockFarmerBreatheCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockFarmerBreatheCall) DoAndReturn(f func()) *MockFarmerBreatheCall { c.Call = c.Call.DoAndReturn(f) return c } // Do mocks base method. func (m *MockFarmer) Do(work *package_mode.Work) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Do", work) ret0, _ := ret[0].(error) return ret0 } // Do indicates an expected call of Do. func (mr *MockFarmerMockRecorder) Do(work any) *MockFarmerDoCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Do", reflect.TypeOf((*MockFarmer)(nil).Do), work) return &MockFarmerDoCall{Call: call} } // MockFarmerDoCall wrap *gomock.Call type MockFarmerDoCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockFarmerDoCall) Return(arg0 error) *MockFarmerDoCall { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockFarmerDoCall) Do(f func(*package_mode.Work) error) *MockFarmerDoCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockFarmerDoCall) DoAndReturn(f func(*package_mode.Work) error) *MockFarmerDoCall { c.Call = c.Call.DoAndReturn(f) return c } // Drive mocks base method. func (m *MockFarmer) Drive(car cars.FordF150) { m.ctrl.T.Helper() m.ctrl.Call(m, "Drive", car) } // Drive indicates an expected call of Drive. func (mr *MockFarmerMockRecorder) Drive(car any) *MockFarmerDriveCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Drive", reflect.TypeOf((*MockFarmer)(nil).Drive), car) return &MockFarmerDriveCall{Call: call} } // MockFarmerDriveCall wrap *gomock.Call type MockFarmerDriveCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockFarmerDriveCall) Return() *MockFarmerDriveCall { c.Call = c.Call.Return() return c } // Do rewrite *gomock.Call.Do func (c *MockFarmerDriveCall) Do(f func(cars.FordF150)) *MockFarmerDriveCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockFarmerDriveCall) DoAndReturn(f func(cars.FordF150)) *MockFarmerDriveCall { c.Call = c.Call.DoAndReturn(f) return c } // Eat mocks base method. func (m *MockFarmer) Eat(foods ...package_mode.Food) { m.ctrl.T.Helper() varargs := []any{} for _, a := range foods { varargs = append(varargs, a) } m.ctrl.Call(m, "Eat", varargs...) } // Eat indicates an expected call of Eat. func (mr *MockFarmerMockRecorder) Eat(foods ...any) *MockFarmerEatCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Eat", reflect.TypeOf((*MockFarmer)(nil).Eat), foods...) return &MockFarmerEatCall{Call: call} } // MockFarmerEatCall wrap *gomock.Call type MockFarmerEatCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockFarmerEatCall) Return() *MockFarmerEatCall { c.Call = c.Call.Return() return c } // Do rewrite *gomock.Call.Do func (c *MockFarmerEatCall) Do(f func(...package_mode.Food)) *MockFarmerEatCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockFarmerEatCall) DoAndReturn(f func(...package_mode.Food)) *MockFarmerEatCall { c.Call = c.Call.DoAndReturn(f) return c } // LivesInAVillage mocks base method. func (m *MockFarmer) LivesInAVillage() { m.ctrl.T.Helper() m.ctrl.Call(m, "LivesInAVillage") } // LivesInAVillage indicates an expected call of LivesInAVillage. func (mr *MockFarmerMockRecorder) LivesInAVillage() *MockFarmerLivesInAVillageCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LivesInAVillage", reflect.TypeOf((*MockFarmer)(nil).LivesInAVillage)) return &MockFarmerLivesInAVillageCall{Call: call} } // MockFarmerLivesInAVillageCall wrap *gomock.Call type MockFarmerLivesInAVillageCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockFarmerLivesInAVillageCall) Return() *MockFarmerLivesInAVillageCall { c.Call = c.Call.Return() return c } // Do rewrite *gomock.Call.Do func (c *MockFarmerLivesInAVillageCall) Do(f func()) *MockFarmerLivesInAVillageCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockFarmerLivesInAVillageCall) DoAndReturn(f func()) *MockFarmerLivesInAVillageCall { c.Call = c.Call.DoAndReturn(f) return c } // Sleep mocks base method. func (m *MockFarmer) Sleep(duration time.Duration) { m.ctrl.T.Helper() m.ctrl.Call(m, "Sleep", duration) } // Sleep indicates an expected call of Sleep. func (mr *MockFarmerMockRecorder) Sleep(duration any) *MockFarmerSleepCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Sleep", reflect.TypeOf((*MockFarmer)(nil).Sleep), duration) return &MockFarmerSleepCall{Call: call} } // MockFarmerSleepCall wrap *gomock.Call type MockFarmerSleepCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockFarmerSleepCall) Return() *MockFarmerSleepCall { c.Call = c.Call.Return() return c } // Do rewrite *gomock.Call.Do func (c *MockFarmerSleepCall) Do(f func(time.Duration)) *MockFarmerSleepCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockFarmerSleepCall) DoAndReturn(f func(time.Duration)) *MockFarmerSleepCall { c.Call = c.Call.DoAndReturn(f) return c } // Wroom mocks base method. func (m *MockFarmer) Wroom() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Wroom") ret0, _ := ret[0].(error) return ret0 } // Wroom indicates an expected call of Wroom. func (mr *MockFarmerMockRecorder) Wroom() *MockFarmerWroomCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Wroom", reflect.TypeOf((*MockFarmer)(nil).Wroom)) return &MockFarmerWroomCall{Call: call} } // MockFarmerWroomCall wrap *gomock.Call type MockFarmerWroomCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockFarmerWroomCall) Return(arg0 error) *MockFarmerWroomCall { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockFarmerWroomCall) Do(f func() error) *MockFarmerWroomCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockFarmerWroomCall) DoAndReturn(f func() error) *MockFarmerWroomCall { c.Call = c.Call.DoAndReturn(f) return c } // MockEarth is a mock of Earth interface. type MockEarth struct { ctrl *gomock.Controller recorder *MockEarthMockRecorder isgomock struct{} } // MockEarthMockRecorder is the mock recorder for MockEarth. type MockEarthMockRecorder struct { mock *MockEarth } // NewMockEarth creates a new mock instance. func NewMockEarth(ctrl *gomock.Controller) *MockEarth { mock := &MockEarth{ctrl: ctrl} mock.recorder = &MockEarthMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockEarth) EXPECT() *MockEarthMockRecorder { return m.recorder } // AddHumans mocks base method. func (m *MockEarth) AddHumans(arg0 int) []package_mode.Primate { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AddHumans", arg0) ret0, _ := ret[0].([]package_mode.Primate) return ret0 } // AddHumans indicates an expected call of AddHumans. func (mr *MockEarthMockRecorder) AddHumans(arg0 any) *MockEarthAddHumansCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddHumans", reflect.TypeOf((*MockEarth)(nil).AddHumans), arg0) return &MockEarthAddHumansCall{Call: call} } // MockEarthAddHumansCall wrap *gomock.Call type MockEarthAddHumansCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockEarthAddHumansCall) Return(arg0 []package_mode.Primate) *MockEarthAddHumansCall { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockEarthAddHumansCall) Do(f func(int) []package_mode.Primate) *MockEarthAddHumansCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockEarthAddHumansCall) DoAndReturn(f func(int) []package_mode.Primate) *MockEarthAddHumansCall { c.Call = c.Call.DoAndReturn(f) return c } // HumanPopulation mocks base method. func (m *MockEarth) HumanPopulation() int { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "HumanPopulation") ret0, _ := ret[0].(int) return ret0 } // HumanPopulation indicates an expected call of HumanPopulation. func (mr *MockEarthMockRecorder) HumanPopulation() *MockEarthHumanPopulationCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HumanPopulation", reflect.TypeOf((*MockEarth)(nil).HumanPopulation)) return &MockEarthHumanPopulationCall{Call: call} } // MockEarthHumanPopulationCall wrap *gomock.Call type MockEarthHumanPopulationCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockEarthHumanPopulationCall) Return(arg0 int) *MockEarthHumanPopulationCall { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockEarthHumanPopulationCall) Do(f func() int) *MockEarthHumanPopulationCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockEarthHumanPopulationCall) DoAndReturn(f func() int) *MockEarthHumanPopulationCall { c.Call = c.Call.DoAndReturn(f) return c } golang-go.uber-mock-0.5.0/mockgen/internal/tests/package_mode/mock/interfaces_test.go000066400000000000000000000020671470430142200307150ustar00rootroot00000000000000package mock import ( "testing" "go.uber.org/mock/gomock" "go.uber.org/mock/mockgen/internal/tests/package_mode" "go.uber.org/mock/mockgen/internal/tests/package_mode/cars" "go.uber.org/mock/mockgen/internal/tests/package_mode/fuel" ) // checks, that mocks implement interfaces in compile-time. // If something breaks, the tests will not be compiled. var food package_mode.Food = &MockFood{} var eater package_mode.Eater = &MockEater{} var animal package_mode.Animal = &MockAnimal{} var human package_mode.Human = &MockHuman{} var primate package_mode.Primate = &MockPrimate{} var car package_mode.Car[fuel.Gasoline] = &MockCar[fuel.Gasoline]{} var driver package_mode.Driver[fuel.Gasoline, cars.HyundaiSolaris] = &MockDriver[fuel.Gasoline, cars.HyundaiSolaris]{} var urbanResident package_mode.UrbanResident = &MockUrbanResident{} var farmer package_mode.Farmer = &MockFarmer{} func TestInterfaces(t *testing.T) { ctrl := gomock.NewController(t) mock := NewMockFarmer(ctrl) mock.EXPECT().Breathe() farmer := package_mode.Farmer(mock) farmer.Breathe() } golang-go.uber-mock-0.5.0/mockgen/internal/tests/panicing_test/000077500000000000000000000000001470430142200244765ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/panicing_test/mock_test.go000066400000000000000000000031571470430142200270230ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: panic.go // // Generated by this command: // // mockgen --source=panic.go --destination=mock_test.go --package=paniccode // // Package paniccode is a generated GoMock package. package paniccode import ( reflect "reflect" gomock "go.uber.org/mock/gomock" ) // MockFoo is a mock of Foo interface. type MockFoo struct { ctrl *gomock.Controller recorder *MockFooMockRecorder isgomock struct{} } // MockFooMockRecorder is the mock recorder for MockFoo. type MockFooMockRecorder struct { mock *MockFoo } // NewMockFoo creates a new mock instance. func NewMockFoo(ctrl *gomock.Controller) *MockFoo { mock := &MockFoo{ctrl: ctrl} mock.recorder = &MockFooMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockFoo) EXPECT() *MockFooMockRecorder { return m.recorder } // Bar mocks base method. func (m *MockFoo) Bar() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Bar") ret0, _ := ret[0].(string) return ret0 } // Bar indicates an expected call of Bar. func (mr *MockFooMockRecorder) Bar() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bar", reflect.TypeOf((*MockFoo)(nil).Bar)) } // Baz mocks base method. func (m *MockFoo) Baz() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Baz") ret0, _ := ret[0].(string) return ret0 } // Baz indicates an expected call of Baz. func (mr *MockFooMockRecorder) Baz() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Baz", reflect.TypeOf((*MockFoo)(nil).Baz)) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/panicing_test/panic.go000066400000000000000000000014761470430142200261270ustar00rootroot00000000000000// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package paniccode //go:generate mockgen --source=panic.go --destination=mock_test.go --package=paniccode type Foo interface { Bar() string Baz() string } func Danger(f Foo) { if f.Bar() == "Bar" { panic("Danger, Will Robinson!") } } golang-go.uber-mock-0.5.0/mockgen/internal/tests/panicing_test/panic_test.go000066400000000000000000000020771470430142200271640ustar00rootroot00000000000000//go:build panictest // +build panictest // Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package paniccode import ( "testing" "go.uber.org/mock/gomock" ) func TestDanger_Panics_Explicit(t *testing.T) { ctrl := gomock.NewController(t) mock := NewMockFoo(ctrl) mock.EXPECT().Bar().Return("Bar") mock.EXPECT().Bar().Return("Baz") Danger(mock) } func TestDanger_Panics_Implicit(t *testing.T) { ctrl := gomock.NewController(t) mock := NewMockFoo(ctrl) mock.EXPECT().Bar().Return("Bar") mock.EXPECT().Bar().Return("Baz") Danger(mock) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/parenthesized_parameter_type/000077500000000000000000000000001470430142200276155ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/parenthesized_parameter_type/README.md000066400000000000000000000001411470430142200310700ustar00rootroot00000000000000# Parenthesized Parameter Type Test for [Issue#416](https://github.com/golang/mock/issues/416). golang-go.uber-mock-0.5.0/mockgen/internal/tests/parenthesized_parameter_type/input.go000066400000000000000000000001531470430142200313020ustar00rootroot00000000000000package parenthesized_parameter_type type Example interface { ParenthesizedParameterType(param *(int)) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/parenthesized_parameter_type/mock.go000066400000000000000000000026711470430142200311030ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: ./mockgen/internal/tests/parenthesized_parameter_type/input.go // Package parenthesized_parameter_type is a generated GoMock package. package parenthesized_parameter_type import ( gomock "go.uber.org/mock/gomock" reflect "reflect" ) // MockExample is a mock of Example interface. type MockExample struct { ctrl *gomock.Controller recorder *MockExampleMockRecorder } // MockExampleMockRecorder is the mock recorder for MockExample. type MockExampleMockRecorder struct { mock *MockExample } // NewMockExample creates a new mock instance. func NewMockExample(ctrl *gomock.Controller) *MockExample { mock := &MockExample{ctrl: ctrl} mock.recorder = &MockExampleMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockExample) EXPECT() *MockExampleMockRecorder { return m.recorder } // ParenthesizedParameterType mocks base method. func (m *MockExample) ParenthesizedParameterType(param *int) { m.ctrl.T.Helper() m.ctrl.Call(m, "ParenthesizedParameterType", param) } // ParenthesizedParameterType indicates an expected call of ParenthesizedParameterType. func (mr *MockExampleMockRecorder) ParenthesizedParameterType(param any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ParenthesizedParameterType", reflect.TypeOf((*MockExample)(nil).ParenthesizedParameterType), param) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/performance/000077500000000000000000000000001470430142200241505ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/performance/big_interface/000077500000000000000000000000001470430142200267315ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/performance/big_interface/big_interface.go000066400000000000000000000070251470430142200320450ustar00rootroot00000000000000package big_interface type Bar struct{} type BigInterface interface { Foo1(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo2(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo3(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo4(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo5(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo6(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo7(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo8(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo9(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo10(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo11(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo12(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo13(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo14(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo15(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo16(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo17(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo18(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo19(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo20(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo21(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo22(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo23(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo24(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo25(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo26(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo27(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo28(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo29(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo30(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo31(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo32(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo33(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo34(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo35(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo36(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo37(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo38(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo39(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo40(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo41(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo42(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo43(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo44(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo45(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo46(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo47(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo48(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo49(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo50(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo51(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo52(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo53(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo54(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo55(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo56(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo57(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo58(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo59(bool, bool, bool, bool, bool, bool, bool, bool) Bar Foo60(bool, bool, bool, bool, bool, bool, bool, bool) Bar } golang-go.uber-mock-0.5.0/mockgen/internal/tests/sanitization/000077500000000000000000000000001470430142200243635ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/sanitization/any/000077500000000000000000000000001470430142200251525ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/sanitization/any/any.go000066400000000000000000000001741470430142200262720ustar00rootroot00000000000000package any // Any is a type of a package that tests the sanitization of imported packages // named any. type Any struct{} golang-go.uber-mock-0.5.0/mockgen/internal/tests/sanitization/interface.go000066400000000000000000000003371470430142200266550ustar00rootroot00000000000000package sanitization import ( "go.uber.org/mock/mockgen/internal/tests/sanitization/any" ) //go:generate mockgen -destination mockout/mock.go -package mockout . AnyMock type AnyMock interface { Do(a *any.Any, b int) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/sanitization/mockout/000077500000000000000000000000001470430142200260445ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/sanitization/mockout/mock.go000066400000000000000000000026371470430142200273340ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: go.uber.org/mock/mockgen/internal/tests/sanitization (interfaces: AnyMock) // // Generated by this command: // // mockgen -destination mockout/mock.go -package mockout . AnyMock // // Package mockout is a generated GoMock package. package mockout import ( reflect "reflect" gomock "go.uber.org/mock/gomock" any0 "go.uber.org/mock/mockgen/internal/tests/sanitization/any" ) // MockAnyMock is a mock of AnyMock interface. type MockAnyMock struct { ctrl *gomock.Controller recorder *MockAnyMockMockRecorder isgomock struct{} } // MockAnyMockMockRecorder is the mock recorder for MockAnyMock. type MockAnyMockMockRecorder struct { mock *MockAnyMock } // NewMockAnyMock creates a new mock instance. func NewMockAnyMock(ctrl *gomock.Controller) *MockAnyMock { mock := &MockAnyMock{ctrl: ctrl} mock.recorder = &MockAnyMockMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockAnyMock) EXPECT() *MockAnyMockMockRecorder { return m.recorder } // Do mocks base method. func (m *MockAnyMock) Do(a *any0.Any, b int) { m.ctrl.T.Helper() m.ctrl.Call(m, "Do", a, b) } // Do indicates an expected call of Do. func (mr *MockAnyMockMockRecorder) Do(a, b any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Do", reflect.TypeOf((*MockAnyMock)(nil).Do), a, b) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/sanitization/sanitization_test.go000066400000000000000000000005541470430142200304710ustar00rootroot00000000000000package sanitization import ( "testing" "go.uber.org/mock/gomock" any0 "go.uber.org/mock/mockgen/internal/tests/sanitization/any" "go.uber.org/mock/mockgen/internal/tests/sanitization/mockout" ) func TestSanitization(t *testing.T) { ctrl := gomock.NewController(t) m := mockout.NewMockAnyMock(ctrl) m.EXPECT().Do(gomock.Any(), 1) m.Do(&any0.Any{}, 1) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/self_package/000077500000000000000000000000001470430142200242535ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/self_package/mock.go000066400000000000000000000027701470430142200255410ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: go.uber.org/mock/mockgen/internal/tests/self_package (interfaces: Methods) // // Generated by this command: // // mockgen -package core -self_package go.uber.org/mock/mockgen/internal/tests/self_package -destination mock.go go.uber.org/mock/mockgen/internal/tests/self_package Methods // // Package core is a generated GoMock package. package core import ( reflect "reflect" gomock "go.uber.org/mock/gomock" ) // MockMethods is a mock of Methods interface. type MockMethods struct { ctrl *gomock.Controller recorder *MockMethodsMockRecorder isgomock struct{} } // MockMethodsMockRecorder is the mock recorder for MockMethods. type MockMethodsMockRecorder struct { mock *MockMethods } // NewMockMethods creates a new mock instance. func NewMockMethods(ctrl *gomock.Controller) *MockMethods { mock := &MockMethods{ctrl: ctrl} mock.recorder = &MockMethodsMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockMethods) EXPECT() *MockMethodsMockRecorder { return m.recorder } // getInfo mocks base method. func (m *MockMethods) getInfo() Info { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "getInfo") ret0, _ := ret[0].(Info) return ret0 } // getInfo indicates an expected call of getInfo. func (mr *MockMethodsMockRecorder) getInfo() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "getInfo", reflect.TypeOf((*MockMethods)(nil).getInfo)) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/self_package/types.go000066400000000000000000000004071470430142200257470ustar00rootroot00000000000000package core //go:generate mockgen -package core -self_package go.uber.org/mock/mockgen/internal/tests/self_package -destination mock.go go.uber.org/mock/mockgen/internal/tests/self_package Methods type Info struct{} type Methods interface { getInfo() Info } golang-go.uber-mock-0.5.0/mockgen/internal/tests/test_package/000077500000000000000000000000001470430142200243015ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/test_package/foo.go000066400000000000000000000000161470430142200254100ustar00rootroot00000000000000package users golang-go.uber-mock-0.5.0/mockgen/internal/tests/test_package/mock_test.go000066400000000000000000000033261470430142200266240ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: user_test.go // // Generated by this command: // // mockgen --source=user_test.go --destination=mock_test.go --package=users_test // // Package users_test is a generated GoMock package. package users_test import ( reflect "reflect" gomock "go.uber.org/mock/gomock" ) // MockFinder is a mock of Finder interface. type MockFinder struct { ctrl *gomock.Controller recorder *MockFinderMockRecorder isgomock struct{} } // MockFinderMockRecorder is the mock recorder for MockFinder. type MockFinderMockRecorder struct { mock *MockFinder } // NewMockFinder creates a new mock instance. func NewMockFinder(ctrl *gomock.Controller) *MockFinder { mock := &MockFinder{ctrl: ctrl} mock.recorder = &MockFinderMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockFinder) EXPECT() *MockFinderMockRecorder { return m.recorder } // Add mocks base method. func (m *MockFinder) Add(u User) { m.ctrl.T.Helper() m.ctrl.Call(m, "Add", u) } // Add indicates an expected call of Add. func (mr *MockFinderMockRecorder) Add(u any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Add", reflect.TypeOf((*MockFinder)(nil).Add), u) } // FindUser mocks base method. func (m *MockFinder) FindUser(name string) User { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "FindUser", name) ret0, _ := ret[0].(User) return ret0 } // FindUser indicates an expected call of FindUser. func (mr *MockFinderMockRecorder) FindUser(name any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindUser", reflect.TypeOf((*MockFinder)(nil).FindUser), name) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/test_package/user_test.go000066400000000000000000000003271470430142200266470ustar00rootroot00000000000000package users_test //go:generate mockgen --source=user_test.go --destination=mock_test.go --package=users_test type User struct { Name string } type Finder interface { FindUser(name string) User Add(u User) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/typed/000077500000000000000000000000001470430142200227745ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/typed/bugreport.go000066400000000000000000000006011470430142200253310ustar00rootroot00000000000000package typed //go:generate mockgen -typed -aux_files faux=faux/faux.go -destination bugreport_mock.go -package typed -source=bugreport.go Example import ( "log" "go.uber.org/mock/mockgen/internal/tests/typed/faux" ) // Source is an interface w/ an embedded foreign interface type Source interface { faux.Foreign } func CallForeignMethod(s Source) { log.Println(s.Method()) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/typed/bugreport_mock.go000066400000000000000000000060421470430142200263470ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: bugreport.go // // Generated by this command: // // mockgen -typed -aux_files faux=faux/faux.go -destination bugreport_mock.go -package typed -source=bugreport.go Example // // Package typed is a generated GoMock package. package typed import ( reflect "reflect" gomock "go.uber.org/mock/gomock" faux "go.uber.org/mock/mockgen/internal/tests/typed/faux" ) // MockSource is a mock of Source interface. type MockSource struct { ctrl *gomock.Controller recorder *MockSourceMockRecorder isgomock struct{} } // MockSourceMockRecorder is the mock recorder for MockSource. type MockSourceMockRecorder struct { mock *MockSource } // NewMockSource creates a new mock instance. func NewMockSource(ctrl *gomock.Controller) *MockSource { mock := &MockSource{ctrl: ctrl} mock.recorder = &MockSourceMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockSource) EXPECT() *MockSourceMockRecorder { return m.recorder } // Error mocks base method. func (m *MockSource) Error() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Error") ret0, _ := ret[0].(string) return ret0 } // Error indicates an expected call of Error. func (mr *MockSourceMockRecorder) Error() *MockSourceErrorCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Error", reflect.TypeOf((*MockSource)(nil).Error)) return &MockSourceErrorCall{Call: call} } // MockSourceErrorCall wrap *gomock.Call type MockSourceErrorCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockSourceErrorCall) Return(arg0 string) *MockSourceErrorCall { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockSourceErrorCall) Do(f func() string) *MockSourceErrorCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockSourceErrorCall) DoAndReturn(f func() string) *MockSourceErrorCall { c.Call = c.Call.DoAndReturn(f) return c } // Method mocks base method. func (m *MockSource) Method() faux.Return { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Method") ret0, _ := ret[0].(faux.Return) return ret0 } // Method indicates an expected call of Method. func (mr *MockSourceMockRecorder) Method() *MockSourceMethodCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Method", reflect.TypeOf((*MockSource)(nil).Method)) return &MockSourceMethodCall{Call: call} } // MockSourceMethodCall wrap *gomock.Call type MockSourceMethodCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockSourceMethodCall) Return(arg0 faux.Return) *MockSourceMethodCall { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockSourceMethodCall) Do(f func() faux.Return) *MockSourceMethodCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockSourceMethodCall) DoAndReturn(f func() faux.Return) *MockSourceMethodCall { c.Call = c.Call.DoAndReturn(f) return c } golang-go.uber-mock-0.5.0/mockgen/internal/tests/typed/bugreport_test.go000066400000000000000000000004511470430142200263730ustar00rootroot00000000000000package typed import ( "testing" "go.uber.org/mock/gomock" ) // TestValidInterface assesses whether or not the generated mock is valid func TestValidInterface(t *testing.T) { ctrl := gomock.NewController(t) s := NewMockSource(ctrl) s.EXPECT().Method().Return("") CallForeignMethod(s) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/typed/external.go000066400000000000000000000007371470430142200251540ustar00rootroot00000000000000package typed import ( "go.uber.org/mock/mockgen/internal/tests/typed/other" "golang.org/x/exp/constraints" ) //go:generate mockgen --source=external.go --destination=source/mock_external_test.go --package source -typed type ExternalConstraint[I constraints.Integer, F constraints.Float] interface { One(string) string Two(I) string Three(I) F Four(I) Foo[I, F] Five(I) Baz[F] Six(I) *Baz[F] Seven(I) other.One[I] Eight(F) other.Two[I, F] Nine(Iface[I]) Ten(*I) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/typed/faux/000077500000000000000000000000001470430142200237375ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/typed/faux/faux.go000066400000000000000000000001771470430142200252360ustar00rootroot00000000000000package faux type Foreign interface { Method() Return Embedded error } type Embedded interface{} type Return interface{} golang-go.uber-mock-0.5.0/mockgen/internal/tests/typed/generics.go000066400000000000000000000017471470430142200251330ustar00rootroot00000000000000package typed import "go.uber.org/mock/mockgen/internal/tests/typed/other" //go:generate mockgen --source=generics.go --destination=source/mock_generics_test.go --package source -typed ////go:generate mockgen --destination=reflect/mock_test.go --package reflect . Bar,Bar2 type Bar[T any, R any] interface { One(string) string Two(T) string Three(T) R Four(T) Foo[T, R] Five(T) Baz[T] Six(T) *Baz[T] Seven(T) other.One[T] Eight(T) other.Two[T, R] Nine(Iface[T]) Ten(*T) Eleven() (*other.One[T], error) Twelve() (*other.Two[T, R], error) Thirteen() (Baz[StructType], error) Fourteen() (*Foo[StructType, StructType2], error) Fifteen() (Iface[StructType], error) Sixteen() (Baz[other.Three], error) Seventeen() (*Foo[other.Three, other.Four], error) Eighteen() (Iface[*other.Five], error) Nineteen() AliasType } type Foo[T any, R any] struct{} type Baz[T any] struct{} type Iface[T any] any type StructType struct{} type StructType2 struct{} type AliasType Baz[other.Three] golang-go.uber-mock-0.5.0/mockgen/internal/tests/typed/go.mod000066400000000000000000000003361470430142200241040ustar00rootroot00000000000000module go.uber.org/mock/mockgen/internal/tests/typed go 1.22 replace go.uber.org/mock => ../../../.. require ( go.uber.org/mock v0.0.0-00010101000000-000000000000 golang.org/x/exp v0.0.0-20240613232115-7f521ea00fb8 ) golang-go.uber-mock-0.5.0/mockgen/internal/tests/typed/go.sum000066400000000000000000000003171470430142200241300ustar00rootroot00000000000000golang.org/x/exp v0.0.0-20240613232115-7f521ea00fb8 h1:yixxcjnhBmY0nkL253HFVIm0JsFHwrHdT3Yh6szTnfY= golang.org/x/exp v0.0.0-20240613232115-7f521ea00fb8/go.mod h1:jj3sYF3dwk5D+ghuXyeI3r5MFf+NT2An6/9dOA95KSI= golang-go.uber-mock-0.5.0/mockgen/internal/tests/typed/other/000077500000000000000000000000001470430142200241155ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/typed/other/other.go000066400000000000000000000002011470430142200255560ustar00rootroot00000000000000package other type One[T any] struct{} type Two[T any, R any] struct{} type Three struct{} type Four struct{} type Five any golang-go.uber-mock-0.5.0/mockgen/internal/tests/typed/source/000077500000000000000000000000001470430142200242745ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/typed/source/mock_external_test.go000066400000000000000000000340171470430142200305220ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: external.go // // Generated by this command: // // mockgen --source=external.go --destination=source/mock_external_test.go --package source -typed // // Package source is a generated GoMock package. package source import ( reflect "reflect" gomock "go.uber.org/mock/gomock" typed "go.uber.org/mock/mockgen/internal/tests/typed" other "go.uber.org/mock/mockgen/internal/tests/typed/other" constraints "golang.org/x/exp/constraints" ) // MockExternalConstraint is a mock of ExternalConstraint interface. type MockExternalConstraint[I constraints.Integer, F constraints.Float] struct { ctrl *gomock.Controller recorder *MockExternalConstraintMockRecorder[I, F] isgomock struct{} } // MockExternalConstraintMockRecorder is the mock recorder for MockExternalConstraint. type MockExternalConstraintMockRecorder[I constraints.Integer, F constraints.Float] struct { mock *MockExternalConstraint[I, F] } // NewMockExternalConstraint creates a new mock instance. func NewMockExternalConstraint[I constraints.Integer, F constraints.Float](ctrl *gomock.Controller) *MockExternalConstraint[I, F] { mock := &MockExternalConstraint[I, F]{ctrl: ctrl} mock.recorder = &MockExternalConstraintMockRecorder[I, F]{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockExternalConstraint[I, F]) EXPECT() *MockExternalConstraintMockRecorder[I, F] { return m.recorder } // Eight mocks base method. func (m *MockExternalConstraint[I, F]) Eight(arg0 F) other.Two[I, F] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Eight", arg0) ret0, _ := ret[0].(other.Two[I, F]) return ret0 } // Eight indicates an expected call of Eight. func (mr *MockExternalConstraintMockRecorder[I, F]) Eight(arg0 any) *MockExternalConstraintEightCall[I, F] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Eight", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Eight), arg0) return &MockExternalConstraintEightCall[I, F]{Call: call} } // MockExternalConstraintEightCall wrap *gomock.Call type MockExternalConstraintEightCall[I constraints.Integer, F constraints.Float] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockExternalConstraintEightCall[I, F]) Return(arg0 other.Two[I, F]) *MockExternalConstraintEightCall[I, F] { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockExternalConstraintEightCall[I, F]) Do(f func(F) other.Two[I, F]) *MockExternalConstraintEightCall[I, F] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockExternalConstraintEightCall[I, F]) DoAndReturn(f func(F) other.Two[I, F]) *MockExternalConstraintEightCall[I, F] { c.Call = c.Call.DoAndReturn(f) return c } // Five mocks base method. func (m *MockExternalConstraint[I, F]) Five(arg0 I) typed.Baz[F] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Five", arg0) ret0, _ := ret[0].(typed.Baz[F]) return ret0 } // Five indicates an expected call of Five. func (mr *MockExternalConstraintMockRecorder[I, F]) Five(arg0 any) *MockExternalConstraintFiveCall[I, F] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Five", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Five), arg0) return &MockExternalConstraintFiveCall[I, F]{Call: call} } // MockExternalConstraintFiveCall wrap *gomock.Call type MockExternalConstraintFiveCall[I constraints.Integer, F constraints.Float] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockExternalConstraintFiveCall[I, F]) Return(arg0 typed.Baz[F]) *MockExternalConstraintFiveCall[I, F] { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockExternalConstraintFiveCall[I, F]) Do(f func(I) typed.Baz[F]) *MockExternalConstraintFiveCall[I, F] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockExternalConstraintFiveCall[I, F]) DoAndReturn(f func(I) typed.Baz[F]) *MockExternalConstraintFiveCall[I, F] { c.Call = c.Call.DoAndReturn(f) return c } // Four mocks base method. func (m *MockExternalConstraint[I, F]) Four(arg0 I) typed.Foo[I, F] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Four", arg0) ret0, _ := ret[0].(typed.Foo[I, F]) return ret0 } // Four indicates an expected call of Four. func (mr *MockExternalConstraintMockRecorder[I, F]) Four(arg0 any) *MockExternalConstraintFourCall[I, F] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Four", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Four), arg0) return &MockExternalConstraintFourCall[I, F]{Call: call} } // MockExternalConstraintFourCall wrap *gomock.Call type MockExternalConstraintFourCall[I constraints.Integer, F constraints.Float] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockExternalConstraintFourCall[I, F]) Return(arg0 typed.Foo[I, F]) *MockExternalConstraintFourCall[I, F] { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockExternalConstraintFourCall[I, F]) Do(f func(I) typed.Foo[I, F]) *MockExternalConstraintFourCall[I, F] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockExternalConstraintFourCall[I, F]) DoAndReturn(f func(I) typed.Foo[I, F]) *MockExternalConstraintFourCall[I, F] { c.Call = c.Call.DoAndReturn(f) return c } // Nine mocks base method. func (m *MockExternalConstraint[I, F]) Nine(arg0 typed.Iface[I]) { m.ctrl.T.Helper() m.ctrl.Call(m, "Nine", arg0) } // Nine indicates an expected call of Nine. func (mr *MockExternalConstraintMockRecorder[I, F]) Nine(arg0 any) *MockExternalConstraintNineCall[I, F] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Nine", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Nine), arg0) return &MockExternalConstraintNineCall[I, F]{Call: call} } // MockExternalConstraintNineCall wrap *gomock.Call type MockExternalConstraintNineCall[I constraints.Integer, F constraints.Float] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockExternalConstraintNineCall[I, F]) Return() *MockExternalConstraintNineCall[I, F] { c.Call = c.Call.Return() return c } // Do rewrite *gomock.Call.Do func (c *MockExternalConstraintNineCall[I, F]) Do(f func(typed.Iface[I])) *MockExternalConstraintNineCall[I, F] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockExternalConstraintNineCall[I, F]) DoAndReturn(f func(typed.Iface[I])) *MockExternalConstraintNineCall[I, F] { c.Call = c.Call.DoAndReturn(f) return c } // One mocks base method. func (m *MockExternalConstraint[I, F]) One(arg0 string) string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "One", arg0) ret0, _ := ret[0].(string) return ret0 } // One indicates an expected call of One. func (mr *MockExternalConstraintMockRecorder[I, F]) One(arg0 any) *MockExternalConstraintOneCall[I, F] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "One", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).One), arg0) return &MockExternalConstraintOneCall[I, F]{Call: call} } // MockExternalConstraintOneCall wrap *gomock.Call type MockExternalConstraintOneCall[I constraints.Integer, F constraints.Float] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockExternalConstraintOneCall[I, F]) Return(arg0 string) *MockExternalConstraintOneCall[I, F] { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockExternalConstraintOneCall[I, F]) Do(f func(string) string) *MockExternalConstraintOneCall[I, F] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockExternalConstraintOneCall[I, F]) DoAndReturn(f func(string) string) *MockExternalConstraintOneCall[I, F] { c.Call = c.Call.DoAndReturn(f) return c } // Seven mocks base method. func (m *MockExternalConstraint[I, F]) Seven(arg0 I) other.One[I] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Seven", arg0) ret0, _ := ret[0].(other.One[I]) return ret0 } // Seven indicates an expected call of Seven. func (mr *MockExternalConstraintMockRecorder[I, F]) Seven(arg0 any) *MockExternalConstraintSevenCall[I, F] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Seven", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Seven), arg0) return &MockExternalConstraintSevenCall[I, F]{Call: call} } // MockExternalConstraintSevenCall wrap *gomock.Call type MockExternalConstraintSevenCall[I constraints.Integer, F constraints.Float] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockExternalConstraintSevenCall[I, F]) Return(arg0 other.One[I]) *MockExternalConstraintSevenCall[I, F] { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockExternalConstraintSevenCall[I, F]) Do(f func(I) other.One[I]) *MockExternalConstraintSevenCall[I, F] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockExternalConstraintSevenCall[I, F]) DoAndReturn(f func(I) other.One[I]) *MockExternalConstraintSevenCall[I, F] { c.Call = c.Call.DoAndReturn(f) return c } // Six mocks base method. func (m *MockExternalConstraint[I, F]) Six(arg0 I) *typed.Baz[F] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Six", arg0) ret0, _ := ret[0].(*typed.Baz[F]) return ret0 } // Six indicates an expected call of Six. func (mr *MockExternalConstraintMockRecorder[I, F]) Six(arg0 any) *MockExternalConstraintSixCall[I, F] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Six", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Six), arg0) return &MockExternalConstraintSixCall[I, F]{Call: call} } // MockExternalConstraintSixCall wrap *gomock.Call type MockExternalConstraintSixCall[I constraints.Integer, F constraints.Float] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockExternalConstraintSixCall[I, F]) Return(arg0 *typed.Baz[F]) *MockExternalConstraintSixCall[I, F] { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockExternalConstraintSixCall[I, F]) Do(f func(I) *typed.Baz[F]) *MockExternalConstraintSixCall[I, F] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockExternalConstraintSixCall[I, F]) DoAndReturn(f func(I) *typed.Baz[F]) *MockExternalConstraintSixCall[I, F] { c.Call = c.Call.DoAndReturn(f) return c } // Ten mocks base method. func (m *MockExternalConstraint[I, F]) Ten(arg0 *I) { m.ctrl.T.Helper() m.ctrl.Call(m, "Ten", arg0) } // Ten indicates an expected call of Ten. func (mr *MockExternalConstraintMockRecorder[I, F]) Ten(arg0 any) *MockExternalConstraintTenCall[I, F] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Ten", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Ten), arg0) return &MockExternalConstraintTenCall[I, F]{Call: call} } // MockExternalConstraintTenCall wrap *gomock.Call type MockExternalConstraintTenCall[I constraints.Integer, F constraints.Float] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockExternalConstraintTenCall[I, F]) Return() *MockExternalConstraintTenCall[I, F] { c.Call = c.Call.Return() return c } // Do rewrite *gomock.Call.Do func (c *MockExternalConstraintTenCall[I, F]) Do(f func(*I)) *MockExternalConstraintTenCall[I, F] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockExternalConstraintTenCall[I, F]) DoAndReturn(f func(*I)) *MockExternalConstraintTenCall[I, F] { c.Call = c.Call.DoAndReturn(f) return c } // Three mocks base method. func (m *MockExternalConstraint[I, F]) Three(arg0 I) F { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Three", arg0) ret0, _ := ret[0].(F) return ret0 } // Three indicates an expected call of Three. func (mr *MockExternalConstraintMockRecorder[I, F]) Three(arg0 any) *MockExternalConstraintThreeCall[I, F] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Three", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Three), arg0) return &MockExternalConstraintThreeCall[I, F]{Call: call} } // MockExternalConstraintThreeCall wrap *gomock.Call type MockExternalConstraintThreeCall[I constraints.Integer, F constraints.Float] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockExternalConstraintThreeCall[I, F]) Return(arg0 F) *MockExternalConstraintThreeCall[I, F] { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockExternalConstraintThreeCall[I, F]) Do(f func(I) F) *MockExternalConstraintThreeCall[I, F] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockExternalConstraintThreeCall[I, F]) DoAndReturn(f func(I) F) *MockExternalConstraintThreeCall[I, F] { c.Call = c.Call.DoAndReturn(f) return c } // Two mocks base method. func (m *MockExternalConstraint[I, F]) Two(arg0 I) string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Two", arg0) ret0, _ := ret[0].(string) return ret0 } // Two indicates an expected call of Two. func (mr *MockExternalConstraintMockRecorder[I, F]) Two(arg0 any) *MockExternalConstraintTwoCall[I, F] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Two", reflect.TypeOf((*MockExternalConstraint[I, F])(nil).Two), arg0) return &MockExternalConstraintTwoCall[I, F]{Call: call} } // MockExternalConstraintTwoCall wrap *gomock.Call type MockExternalConstraintTwoCall[I constraints.Integer, F constraints.Float] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockExternalConstraintTwoCall[I, F]) Return(arg0 string) *MockExternalConstraintTwoCall[I, F] { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockExternalConstraintTwoCall[I, F]) Do(f func(I) string) *MockExternalConstraintTwoCall[I, F] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockExternalConstraintTwoCall[I, F]) DoAndReturn(f func(I) string) *MockExternalConstraintTwoCall[I, F] { c.Call = c.Call.DoAndReturn(f) return c } golang-go.uber-mock-0.5.0/mockgen/internal/tests/typed/source/mock_generics_test.go000066400000000000000000000550411470430142200304770ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: generics.go // // Generated by this command: // // mockgen --source=generics.go --destination=source/mock_generics_test.go --package source -typed // // Package source is a generated GoMock package. package source import ( reflect "reflect" gomock "go.uber.org/mock/gomock" typed "go.uber.org/mock/mockgen/internal/tests/typed" other "go.uber.org/mock/mockgen/internal/tests/typed/other" ) // MockBar is a mock of Bar interface. type MockBar[T any, R any] struct { ctrl *gomock.Controller recorder *MockBarMockRecorder[T, R] isgomock struct{} } // MockBarMockRecorder is the mock recorder for MockBar. type MockBarMockRecorder[T any, R any] struct { mock *MockBar[T, R] } // NewMockBar creates a new mock instance. func NewMockBar[T any, R any](ctrl *gomock.Controller) *MockBar[T, R] { mock := &MockBar[T, R]{ctrl: ctrl} mock.recorder = &MockBarMockRecorder[T, R]{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockBar[T, R]) EXPECT() *MockBarMockRecorder[T, R] { return m.recorder } // Eight mocks base method. func (m *MockBar[T, R]) Eight(arg0 T) other.Two[T, R] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Eight", arg0) ret0, _ := ret[0].(other.Two[T, R]) return ret0 } // Eight indicates an expected call of Eight. func (mr *MockBarMockRecorder[T, R]) Eight(arg0 any) *MockBarEightCall[T, R] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Eight", reflect.TypeOf((*MockBar[T, R])(nil).Eight), arg0) return &MockBarEightCall[T, R]{Call: call} } // MockBarEightCall wrap *gomock.Call type MockBarEightCall[T any, R any] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockBarEightCall[T, R]) Return(arg0 other.Two[T, R]) *MockBarEightCall[T, R] { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockBarEightCall[T, R]) Do(f func(T) other.Two[T, R]) *MockBarEightCall[T, R] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockBarEightCall[T, R]) DoAndReturn(f func(T) other.Two[T, R]) *MockBarEightCall[T, R] { c.Call = c.Call.DoAndReturn(f) return c } // Eighteen mocks base method. func (m *MockBar[T, R]) Eighteen() (typed.Iface[*other.Five], error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Eighteen") ret0, _ := ret[0].(typed.Iface[*other.Five]) ret1, _ := ret[1].(error) return ret0, ret1 } // Eighteen indicates an expected call of Eighteen. func (mr *MockBarMockRecorder[T, R]) Eighteen() *MockBarEighteenCall[T, R] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Eighteen", reflect.TypeOf((*MockBar[T, R])(nil).Eighteen)) return &MockBarEighteenCall[T, R]{Call: call} } // MockBarEighteenCall wrap *gomock.Call type MockBarEighteenCall[T any, R any] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockBarEighteenCall[T, R]) Return(arg0 typed.Iface[*other.Five], arg1 error) *MockBarEighteenCall[T, R] { c.Call = c.Call.Return(arg0, arg1) return c } // Do rewrite *gomock.Call.Do func (c *MockBarEighteenCall[T, R]) Do(f func() (typed.Iface[*other.Five], error)) *MockBarEighteenCall[T, R] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockBarEighteenCall[T, R]) DoAndReturn(f func() (typed.Iface[*other.Five], error)) *MockBarEighteenCall[T, R] { c.Call = c.Call.DoAndReturn(f) return c } // Eleven mocks base method. func (m *MockBar[T, R]) Eleven() (*other.One[T], error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Eleven") ret0, _ := ret[0].(*other.One[T]) ret1, _ := ret[1].(error) return ret0, ret1 } // Eleven indicates an expected call of Eleven. func (mr *MockBarMockRecorder[T, R]) Eleven() *MockBarElevenCall[T, R] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Eleven", reflect.TypeOf((*MockBar[T, R])(nil).Eleven)) return &MockBarElevenCall[T, R]{Call: call} } // MockBarElevenCall wrap *gomock.Call type MockBarElevenCall[T any, R any] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockBarElevenCall[T, R]) Return(arg0 *other.One[T], arg1 error) *MockBarElevenCall[T, R] { c.Call = c.Call.Return(arg0, arg1) return c } // Do rewrite *gomock.Call.Do func (c *MockBarElevenCall[T, R]) Do(f func() (*other.One[T], error)) *MockBarElevenCall[T, R] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockBarElevenCall[T, R]) DoAndReturn(f func() (*other.One[T], error)) *MockBarElevenCall[T, R] { c.Call = c.Call.DoAndReturn(f) return c } // Fifteen mocks base method. func (m *MockBar[T, R]) Fifteen() (typed.Iface[typed.StructType], error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Fifteen") ret0, _ := ret[0].(typed.Iface[typed.StructType]) ret1, _ := ret[1].(error) return ret0, ret1 } // Fifteen indicates an expected call of Fifteen. func (mr *MockBarMockRecorder[T, R]) Fifteen() *MockBarFifteenCall[T, R] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Fifteen", reflect.TypeOf((*MockBar[T, R])(nil).Fifteen)) return &MockBarFifteenCall[T, R]{Call: call} } // MockBarFifteenCall wrap *gomock.Call type MockBarFifteenCall[T any, R any] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockBarFifteenCall[T, R]) Return(arg0 typed.Iface[typed.StructType], arg1 error) *MockBarFifteenCall[T, R] { c.Call = c.Call.Return(arg0, arg1) return c } // Do rewrite *gomock.Call.Do func (c *MockBarFifteenCall[T, R]) Do(f func() (typed.Iface[typed.StructType], error)) *MockBarFifteenCall[T, R] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockBarFifteenCall[T, R]) DoAndReturn(f func() (typed.Iface[typed.StructType], error)) *MockBarFifteenCall[T, R] { c.Call = c.Call.DoAndReturn(f) return c } // Five mocks base method. func (m *MockBar[T, R]) Five(arg0 T) typed.Baz[T] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Five", arg0) ret0, _ := ret[0].(typed.Baz[T]) return ret0 } // Five indicates an expected call of Five. func (mr *MockBarMockRecorder[T, R]) Five(arg0 any) *MockBarFiveCall[T, R] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Five", reflect.TypeOf((*MockBar[T, R])(nil).Five), arg0) return &MockBarFiveCall[T, R]{Call: call} } // MockBarFiveCall wrap *gomock.Call type MockBarFiveCall[T any, R any] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockBarFiveCall[T, R]) Return(arg0 typed.Baz[T]) *MockBarFiveCall[T, R] { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockBarFiveCall[T, R]) Do(f func(T) typed.Baz[T]) *MockBarFiveCall[T, R] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockBarFiveCall[T, R]) DoAndReturn(f func(T) typed.Baz[T]) *MockBarFiveCall[T, R] { c.Call = c.Call.DoAndReturn(f) return c } // Four mocks base method. func (m *MockBar[T, R]) Four(arg0 T) typed.Foo[T, R] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Four", arg0) ret0, _ := ret[0].(typed.Foo[T, R]) return ret0 } // Four indicates an expected call of Four. func (mr *MockBarMockRecorder[T, R]) Four(arg0 any) *MockBarFourCall[T, R] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Four", reflect.TypeOf((*MockBar[T, R])(nil).Four), arg0) return &MockBarFourCall[T, R]{Call: call} } // MockBarFourCall wrap *gomock.Call type MockBarFourCall[T any, R any] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockBarFourCall[T, R]) Return(arg0 typed.Foo[T, R]) *MockBarFourCall[T, R] { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockBarFourCall[T, R]) Do(f func(T) typed.Foo[T, R]) *MockBarFourCall[T, R] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockBarFourCall[T, R]) DoAndReturn(f func(T) typed.Foo[T, R]) *MockBarFourCall[T, R] { c.Call = c.Call.DoAndReturn(f) return c } // Fourteen mocks base method. func (m *MockBar[T, R]) Fourteen() (*typed.Foo[typed.StructType, typed.StructType2], error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Fourteen") ret0, _ := ret[0].(*typed.Foo[typed.StructType, typed.StructType2]) ret1, _ := ret[1].(error) return ret0, ret1 } // Fourteen indicates an expected call of Fourteen. func (mr *MockBarMockRecorder[T, R]) Fourteen() *MockBarFourteenCall[T, R] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Fourteen", reflect.TypeOf((*MockBar[T, R])(nil).Fourteen)) return &MockBarFourteenCall[T, R]{Call: call} } // MockBarFourteenCall wrap *gomock.Call type MockBarFourteenCall[T any, R any] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockBarFourteenCall[T, R]) Return(arg0 *typed.Foo[typed.StructType, typed.StructType2], arg1 error) *MockBarFourteenCall[T, R] { c.Call = c.Call.Return(arg0, arg1) return c } // Do rewrite *gomock.Call.Do func (c *MockBarFourteenCall[T, R]) Do(f func() (*typed.Foo[typed.StructType, typed.StructType2], error)) *MockBarFourteenCall[T, R] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockBarFourteenCall[T, R]) DoAndReturn(f func() (*typed.Foo[typed.StructType, typed.StructType2], error)) *MockBarFourteenCall[T, R] { c.Call = c.Call.DoAndReturn(f) return c } // Nine mocks base method. func (m *MockBar[T, R]) Nine(arg0 typed.Iface[T]) { m.ctrl.T.Helper() m.ctrl.Call(m, "Nine", arg0) } // Nine indicates an expected call of Nine. func (mr *MockBarMockRecorder[T, R]) Nine(arg0 any) *MockBarNineCall[T, R] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Nine", reflect.TypeOf((*MockBar[T, R])(nil).Nine), arg0) return &MockBarNineCall[T, R]{Call: call} } // MockBarNineCall wrap *gomock.Call type MockBarNineCall[T any, R any] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockBarNineCall[T, R]) Return() *MockBarNineCall[T, R] { c.Call = c.Call.Return() return c } // Do rewrite *gomock.Call.Do func (c *MockBarNineCall[T, R]) Do(f func(typed.Iface[T])) *MockBarNineCall[T, R] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockBarNineCall[T, R]) DoAndReturn(f func(typed.Iface[T])) *MockBarNineCall[T, R] { c.Call = c.Call.DoAndReturn(f) return c } // Nineteen mocks base method. func (m *MockBar[T, R]) Nineteen() typed.AliasType { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Nineteen") ret0, _ := ret[0].(typed.AliasType) return ret0 } // Nineteen indicates an expected call of Nineteen. func (mr *MockBarMockRecorder[T, R]) Nineteen() *MockBarNineteenCall[T, R] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Nineteen", reflect.TypeOf((*MockBar[T, R])(nil).Nineteen)) return &MockBarNineteenCall[T, R]{Call: call} } // MockBarNineteenCall wrap *gomock.Call type MockBarNineteenCall[T any, R any] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockBarNineteenCall[T, R]) Return(arg0 typed.AliasType) *MockBarNineteenCall[T, R] { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockBarNineteenCall[T, R]) Do(f func() typed.AliasType) *MockBarNineteenCall[T, R] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockBarNineteenCall[T, R]) DoAndReturn(f func() typed.AliasType) *MockBarNineteenCall[T, R] { c.Call = c.Call.DoAndReturn(f) return c } // One mocks base method. func (m *MockBar[T, R]) One(arg0 string) string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "One", arg0) ret0, _ := ret[0].(string) return ret0 } // One indicates an expected call of One. func (mr *MockBarMockRecorder[T, R]) One(arg0 any) *MockBarOneCall[T, R] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "One", reflect.TypeOf((*MockBar[T, R])(nil).One), arg0) return &MockBarOneCall[T, R]{Call: call} } // MockBarOneCall wrap *gomock.Call type MockBarOneCall[T any, R any] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockBarOneCall[T, R]) Return(arg0 string) *MockBarOneCall[T, R] { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockBarOneCall[T, R]) Do(f func(string) string) *MockBarOneCall[T, R] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockBarOneCall[T, R]) DoAndReturn(f func(string) string) *MockBarOneCall[T, R] { c.Call = c.Call.DoAndReturn(f) return c } // Seven mocks base method. func (m *MockBar[T, R]) Seven(arg0 T) other.One[T] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Seven", arg0) ret0, _ := ret[0].(other.One[T]) return ret0 } // Seven indicates an expected call of Seven. func (mr *MockBarMockRecorder[T, R]) Seven(arg0 any) *MockBarSevenCall[T, R] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Seven", reflect.TypeOf((*MockBar[T, R])(nil).Seven), arg0) return &MockBarSevenCall[T, R]{Call: call} } // MockBarSevenCall wrap *gomock.Call type MockBarSevenCall[T any, R any] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockBarSevenCall[T, R]) Return(arg0 other.One[T]) *MockBarSevenCall[T, R] { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockBarSevenCall[T, R]) Do(f func(T) other.One[T]) *MockBarSevenCall[T, R] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockBarSevenCall[T, R]) DoAndReturn(f func(T) other.One[T]) *MockBarSevenCall[T, R] { c.Call = c.Call.DoAndReturn(f) return c } // Seventeen mocks base method. func (m *MockBar[T, R]) Seventeen() (*typed.Foo[other.Three, other.Four], error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Seventeen") ret0, _ := ret[0].(*typed.Foo[other.Three, other.Four]) ret1, _ := ret[1].(error) return ret0, ret1 } // Seventeen indicates an expected call of Seventeen. func (mr *MockBarMockRecorder[T, R]) Seventeen() *MockBarSeventeenCall[T, R] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Seventeen", reflect.TypeOf((*MockBar[T, R])(nil).Seventeen)) return &MockBarSeventeenCall[T, R]{Call: call} } // MockBarSeventeenCall wrap *gomock.Call type MockBarSeventeenCall[T any, R any] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockBarSeventeenCall[T, R]) Return(arg0 *typed.Foo[other.Three, other.Four], arg1 error) *MockBarSeventeenCall[T, R] { c.Call = c.Call.Return(arg0, arg1) return c } // Do rewrite *gomock.Call.Do func (c *MockBarSeventeenCall[T, R]) Do(f func() (*typed.Foo[other.Three, other.Four], error)) *MockBarSeventeenCall[T, R] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockBarSeventeenCall[T, R]) DoAndReturn(f func() (*typed.Foo[other.Three, other.Four], error)) *MockBarSeventeenCall[T, R] { c.Call = c.Call.DoAndReturn(f) return c } // Six mocks base method. func (m *MockBar[T, R]) Six(arg0 T) *typed.Baz[T] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Six", arg0) ret0, _ := ret[0].(*typed.Baz[T]) return ret0 } // Six indicates an expected call of Six. func (mr *MockBarMockRecorder[T, R]) Six(arg0 any) *MockBarSixCall[T, R] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Six", reflect.TypeOf((*MockBar[T, R])(nil).Six), arg0) return &MockBarSixCall[T, R]{Call: call} } // MockBarSixCall wrap *gomock.Call type MockBarSixCall[T any, R any] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockBarSixCall[T, R]) Return(arg0 *typed.Baz[T]) *MockBarSixCall[T, R] { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockBarSixCall[T, R]) Do(f func(T) *typed.Baz[T]) *MockBarSixCall[T, R] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockBarSixCall[T, R]) DoAndReturn(f func(T) *typed.Baz[T]) *MockBarSixCall[T, R] { c.Call = c.Call.DoAndReturn(f) return c } // Sixteen mocks base method. func (m *MockBar[T, R]) Sixteen() (typed.Baz[other.Three], error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Sixteen") ret0, _ := ret[0].(typed.Baz[other.Three]) ret1, _ := ret[1].(error) return ret0, ret1 } // Sixteen indicates an expected call of Sixteen. func (mr *MockBarMockRecorder[T, R]) Sixteen() *MockBarSixteenCall[T, R] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Sixteen", reflect.TypeOf((*MockBar[T, R])(nil).Sixteen)) return &MockBarSixteenCall[T, R]{Call: call} } // MockBarSixteenCall wrap *gomock.Call type MockBarSixteenCall[T any, R any] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockBarSixteenCall[T, R]) Return(arg0 typed.Baz[other.Three], arg1 error) *MockBarSixteenCall[T, R] { c.Call = c.Call.Return(arg0, arg1) return c } // Do rewrite *gomock.Call.Do func (c *MockBarSixteenCall[T, R]) Do(f func() (typed.Baz[other.Three], error)) *MockBarSixteenCall[T, R] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockBarSixteenCall[T, R]) DoAndReturn(f func() (typed.Baz[other.Three], error)) *MockBarSixteenCall[T, R] { c.Call = c.Call.DoAndReturn(f) return c } // Ten mocks base method. func (m *MockBar[T, R]) Ten(arg0 *T) { m.ctrl.T.Helper() m.ctrl.Call(m, "Ten", arg0) } // Ten indicates an expected call of Ten. func (mr *MockBarMockRecorder[T, R]) Ten(arg0 any) *MockBarTenCall[T, R] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Ten", reflect.TypeOf((*MockBar[T, R])(nil).Ten), arg0) return &MockBarTenCall[T, R]{Call: call} } // MockBarTenCall wrap *gomock.Call type MockBarTenCall[T any, R any] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockBarTenCall[T, R]) Return() *MockBarTenCall[T, R] { c.Call = c.Call.Return() return c } // Do rewrite *gomock.Call.Do func (c *MockBarTenCall[T, R]) Do(f func(*T)) *MockBarTenCall[T, R] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockBarTenCall[T, R]) DoAndReturn(f func(*T)) *MockBarTenCall[T, R] { c.Call = c.Call.DoAndReturn(f) return c } // Thirteen mocks base method. func (m *MockBar[T, R]) Thirteen() (typed.Baz[typed.StructType], error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Thirteen") ret0, _ := ret[0].(typed.Baz[typed.StructType]) ret1, _ := ret[1].(error) return ret0, ret1 } // Thirteen indicates an expected call of Thirteen. func (mr *MockBarMockRecorder[T, R]) Thirteen() *MockBarThirteenCall[T, R] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Thirteen", reflect.TypeOf((*MockBar[T, R])(nil).Thirteen)) return &MockBarThirteenCall[T, R]{Call: call} } // MockBarThirteenCall wrap *gomock.Call type MockBarThirteenCall[T any, R any] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockBarThirteenCall[T, R]) Return(arg0 typed.Baz[typed.StructType], arg1 error) *MockBarThirteenCall[T, R] { c.Call = c.Call.Return(arg0, arg1) return c } // Do rewrite *gomock.Call.Do func (c *MockBarThirteenCall[T, R]) Do(f func() (typed.Baz[typed.StructType], error)) *MockBarThirteenCall[T, R] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockBarThirteenCall[T, R]) DoAndReturn(f func() (typed.Baz[typed.StructType], error)) *MockBarThirteenCall[T, R] { c.Call = c.Call.DoAndReturn(f) return c } // Three mocks base method. func (m *MockBar[T, R]) Three(arg0 T) R { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Three", arg0) ret0, _ := ret[0].(R) return ret0 } // Three indicates an expected call of Three. func (mr *MockBarMockRecorder[T, R]) Three(arg0 any) *MockBarThreeCall[T, R] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Three", reflect.TypeOf((*MockBar[T, R])(nil).Three), arg0) return &MockBarThreeCall[T, R]{Call: call} } // MockBarThreeCall wrap *gomock.Call type MockBarThreeCall[T any, R any] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockBarThreeCall[T, R]) Return(arg0 R) *MockBarThreeCall[T, R] { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockBarThreeCall[T, R]) Do(f func(T) R) *MockBarThreeCall[T, R] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockBarThreeCall[T, R]) DoAndReturn(f func(T) R) *MockBarThreeCall[T, R] { c.Call = c.Call.DoAndReturn(f) return c } // Twelve mocks base method. func (m *MockBar[T, R]) Twelve() (*other.Two[T, R], error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Twelve") ret0, _ := ret[0].(*other.Two[T, R]) ret1, _ := ret[1].(error) return ret0, ret1 } // Twelve indicates an expected call of Twelve. func (mr *MockBarMockRecorder[T, R]) Twelve() *MockBarTwelveCall[T, R] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Twelve", reflect.TypeOf((*MockBar[T, R])(nil).Twelve)) return &MockBarTwelveCall[T, R]{Call: call} } // MockBarTwelveCall wrap *gomock.Call type MockBarTwelveCall[T any, R any] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockBarTwelveCall[T, R]) Return(arg0 *other.Two[T, R], arg1 error) *MockBarTwelveCall[T, R] { c.Call = c.Call.Return(arg0, arg1) return c } // Do rewrite *gomock.Call.Do func (c *MockBarTwelveCall[T, R]) Do(f func() (*other.Two[T, R], error)) *MockBarTwelveCall[T, R] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockBarTwelveCall[T, R]) DoAndReturn(f func() (*other.Two[T, R], error)) *MockBarTwelveCall[T, R] { c.Call = c.Call.DoAndReturn(f) return c } // Two mocks base method. func (m *MockBar[T, R]) Two(arg0 T) string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Two", arg0) ret0, _ := ret[0].(string) return ret0 } // Two indicates an expected call of Two. func (mr *MockBarMockRecorder[T, R]) Two(arg0 any) *MockBarTwoCall[T, R] { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Two", reflect.TypeOf((*MockBar[T, R])(nil).Two), arg0) return &MockBarTwoCall[T, R]{Call: call} } // MockBarTwoCall wrap *gomock.Call type MockBarTwoCall[T any, R any] struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockBarTwoCall[T, R]) Return(arg0 string) *MockBarTwoCall[T, R] { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockBarTwoCall[T, R]) Do(f func(T) string) *MockBarTwoCall[T, R] { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockBarTwoCall[T, R]) DoAndReturn(f func(T) string) *MockBarTwoCall[T, R] { c.Call = c.Call.DoAndReturn(f) return c } golang-go.uber-mock-0.5.0/mockgen/internal/tests/typed_inorder/000077500000000000000000000000001470430142200245165ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/typed_inorder/input.go000066400000000000000000000005001470430142200261770ustar00rootroot00000000000000package typed_inorder //go:generate mockgen -package typed_inorder -source=input.go -destination=mock.go -typed type Animal interface { GetSound() string Feed(string) error } func Interact(a Animal, food string) (string, error) { if err := a.Feed(food); err != nil { return "", err } return a.GetSound(), nil } golang-go.uber-mock-0.5.0/mockgen/internal/tests/typed_inorder/input_test.go000066400000000000000000000007771470430142200272560ustar00rootroot00000000000000package typed_inorder import ( "fmt" "testing" "go.uber.org/mock/gomock" ) func TestInteract(t *testing.T) { ctrl := gomock.NewController(t) mockAnimal := NewMockAnimal(ctrl) gomock.InOrder( mockAnimal.EXPECT().Feed("burguir").DoAndReturn(func(s string) error { if s != "chocolate" { return nil } return fmt.Errorf("Dogs can't eat chocolate!") }), mockAnimal.EXPECT().GetSound().Return("Woof!"), ) _, err := Interact(mockAnimal, "burguir") if err != nil { t.Fatalf("sad") } } golang-go.uber-mock-0.5.0/mockgen/internal/tests/typed_inorder/mock.go000066400000000000000000000057471470430142200260130ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: input.go // // Generated by this command: // // mockgen -package typed_inorder -source=input.go -destination=mock.go -typed // // Package typed_inorder is a generated GoMock package. package typed_inorder import ( reflect "reflect" gomock "go.uber.org/mock/gomock" ) // MockAnimal is a mock of Animal interface. type MockAnimal struct { ctrl *gomock.Controller recorder *MockAnimalMockRecorder isgomock struct{} } // MockAnimalMockRecorder is the mock recorder for MockAnimal. type MockAnimalMockRecorder struct { mock *MockAnimal } // NewMockAnimal creates a new mock instance. func NewMockAnimal(ctrl *gomock.Controller) *MockAnimal { mock := &MockAnimal{ctrl: ctrl} mock.recorder = &MockAnimalMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockAnimal) EXPECT() *MockAnimalMockRecorder { return m.recorder } // Feed mocks base method. func (m *MockAnimal) Feed(arg0 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Feed", arg0) ret0, _ := ret[0].(error) return ret0 } // Feed indicates an expected call of Feed. func (mr *MockAnimalMockRecorder) Feed(arg0 any) *MockAnimalFeedCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Feed", reflect.TypeOf((*MockAnimal)(nil).Feed), arg0) return &MockAnimalFeedCall{Call: call} } // MockAnimalFeedCall wrap *gomock.Call type MockAnimalFeedCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockAnimalFeedCall) Return(arg0 error) *MockAnimalFeedCall { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockAnimalFeedCall) Do(f func(string) error) *MockAnimalFeedCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockAnimalFeedCall) DoAndReturn(f func(string) error) *MockAnimalFeedCall { c.Call = c.Call.DoAndReturn(f) return c } // GetSound mocks base method. func (m *MockAnimal) GetSound() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetSound") ret0, _ := ret[0].(string) return ret0 } // GetSound indicates an expected call of GetSound. func (mr *MockAnimalMockRecorder) GetSound() *MockAnimalGetSoundCall { mr.mock.ctrl.T.Helper() call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSound", reflect.TypeOf((*MockAnimal)(nil).GetSound)) return &MockAnimalGetSoundCall{Call: call} } // MockAnimalGetSoundCall wrap *gomock.Call type MockAnimalGetSoundCall struct { *gomock.Call } // Return rewrite *gomock.Call.Return func (c *MockAnimalGetSoundCall) Return(arg0 string) *MockAnimalGetSoundCall { c.Call = c.Call.Return(arg0) return c } // Do rewrite *gomock.Call.Do func (c *MockAnimalGetSoundCall) Do(f func() string) *MockAnimalGetSoundCall { c.Call = c.Call.Do(f) return c } // DoAndReturn rewrite *gomock.Call.DoAndReturn func (c *MockAnimalGetSoundCall) DoAndReturn(f func() string) *MockAnimalGetSoundCall { c.Call = c.Call.DoAndReturn(f) return c } golang-go.uber-mock-0.5.0/mockgen/internal/tests/unexported_method/000077500000000000000000000000001470430142200254045ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/unexported_method/README.md000066400000000000000000000001301470430142200266550ustar00rootroot00000000000000# Unexported Method From #52, this tests an unexported method in the mocked interface. golang-go.uber-mock-0.5.0/mockgen/internal/tests/unexported_method/bugreport.go000066400000000000000000000005631470430142200277500ustar00rootroot00000000000000package bugreport //go:generate mockgen -destination bugreport_mock.go -package bugreport -source=bugreport.go Example import "fmt" // Example is an interface with a non exported method type Example interface { someMethod(string) string } // CallExample is a simple function that uses the interface func CallExample(e Example) { fmt.Println(e.someMethod("test")) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/unexported_method/bugreport_mock.go000066400000000000000000000026531470430142200307630ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: bugreport.go // // Generated by this command: // // mockgen -destination bugreport_mock.go -package bugreport -source=bugreport.go Example // // Package bugreport is a generated GoMock package. package bugreport import ( reflect "reflect" gomock "go.uber.org/mock/gomock" ) // MockExample is a mock of Example interface. type MockExample struct { ctrl *gomock.Controller recorder *MockExampleMockRecorder isgomock struct{} } // MockExampleMockRecorder is the mock recorder for MockExample. type MockExampleMockRecorder struct { mock *MockExample } // NewMockExample creates a new mock instance. func NewMockExample(ctrl *gomock.Controller) *MockExample { mock := &MockExample{ctrl: ctrl} mock.recorder = &MockExampleMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockExample) EXPECT() *MockExampleMockRecorder { return m.recorder } // someMethod mocks base method. func (m *MockExample) someMethod(arg0 string) string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "someMethod", arg0) ret0, _ := ret[0].(string) return ret0 } // someMethod indicates an expected call of someMethod. func (mr *MockExampleMockRecorder) someMethod(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "someMethod", reflect.TypeOf((*MockExample)(nil).someMethod), arg0) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/unexported_method/bugreport_test.go000066400000000000000000000003641470430142200310060ustar00rootroot00000000000000package bugreport import ( "testing" "go.uber.org/mock/gomock" ) func TestCallExample(t *testing.T) { ctrl := gomock.NewController(t) e := NewMockExample(ctrl) e.EXPECT().someMethod(gomock.Any()).Return("it works!") CallExample(e) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/vendor_dep/000077500000000000000000000000001470430142200237745ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/vendor_dep/README.md000066400000000000000000000002211470430142200252460ustar00rootroot00000000000000# Vendor Dep Test for [Issue#4](https://github.com/golang/mock/issues/4). Also see discussion on [#28](https://github.com/golang/mock/pull/28). golang-go.uber-mock-0.5.0/mockgen/internal/tests/vendor_dep/doc.go000066400000000000000000000003461470430142200250730ustar00rootroot00000000000000package vendor_dep //go:generate mockgen -package vendor_dep -destination mock.go go.uber.org/mock/mockgen/internal/tests/vendor_dep VendorsDep //go:generate mockgen -destination source_mock_package/mock.go -source=vendor_dep.go golang-go.uber-mock-0.5.0/mockgen/internal/tests/vendor_dep/mock.go000066400000000000000000000030251470430142200252540ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: go.uber.org/mock/mockgen/internal/tests/vendor_dep (interfaces: VendorsDep) // // Generated by this command: // // mockgen -package vendor_dep -destination mock.go go.uber.org/mock/mockgen/internal/tests/vendor_dep VendorsDep // // Package vendor_dep is a generated GoMock package. package vendor_dep import ( reflect "reflect" gomock "go.uber.org/mock/gomock" present "golang.org/x/tools/present" ) // MockVendorsDep is a mock of VendorsDep interface. type MockVendorsDep struct { ctrl *gomock.Controller recorder *MockVendorsDepMockRecorder isgomock struct{} } // MockVendorsDepMockRecorder is the mock recorder for MockVendorsDep. type MockVendorsDepMockRecorder struct { mock *MockVendorsDep } // NewMockVendorsDep creates a new mock instance. func NewMockVendorsDep(ctrl *gomock.Controller) *MockVendorsDep { mock := &MockVendorsDep{ctrl: ctrl} mock.recorder = &MockVendorsDepMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockVendorsDep) EXPECT() *MockVendorsDepMockRecorder { return m.recorder } // Foo mocks base method. func (m *MockVendorsDep) Foo() present.Elem { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Foo") ret0, _ := ret[0].(present.Elem) return ret0 } // Foo indicates an expected call of Foo. func (mr *MockVendorsDepMockRecorder) Foo() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Foo", reflect.TypeOf((*MockVendorsDep)(nil).Foo)) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/vendor_dep/source_mock_package/000077500000000000000000000000001470430142200277605ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/vendor_dep/source_mock_package/mock.go000066400000000000000000000026711470430142200312460ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: vendor_dep.go // // Generated by this command: // // mockgen -destination source_mock_package/mock.go -source=vendor_dep.go // // Package mock_vendor_dep is a generated GoMock package. package mock_vendor_dep import ( reflect "reflect" gomock "go.uber.org/mock/gomock" present "golang.org/x/tools/present" ) // MockVendorsDep is a mock of VendorsDep interface. type MockVendorsDep struct { ctrl *gomock.Controller recorder *MockVendorsDepMockRecorder isgomock struct{} } // MockVendorsDepMockRecorder is the mock recorder for MockVendorsDep. type MockVendorsDepMockRecorder struct { mock *MockVendorsDep } // NewMockVendorsDep creates a new mock instance. func NewMockVendorsDep(ctrl *gomock.Controller) *MockVendorsDep { mock := &MockVendorsDep{ctrl: ctrl} mock.recorder = &MockVendorsDepMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockVendorsDep) EXPECT() *MockVendorsDepMockRecorder { return m.recorder } // Foo mocks base method. func (m *MockVendorsDep) Foo() present.Elem { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Foo") ret0, _ := ret[0].(present.Elem) return ret0 } // Foo indicates an expected call of Foo. func (mr *MockVendorsDepMockRecorder) Foo() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Foo", reflect.TypeOf((*MockVendorsDep)(nil).Foo)) } golang-go.uber-mock-0.5.0/mockgen/internal/tests/vendor_dep/vendor_dep.go000066400000000000000000000001531470430142200264470ustar00rootroot00000000000000package vendor_dep import "golang.org/x/tools/present" type VendorsDep interface { Foo() present.Elem } golang-go.uber-mock-0.5.0/mockgen/internal/tests/vendor_pkg/000077500000000000000000000000001470430142200240055ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/internal/tests/vendor_pkg/README.md000066400000000000000000000001131470430142200252570ustar00rootroot00000000000000# Vendor Pkg Test for [Issue#4](https://github.com/golang/mock/issues/4). golang-go.uber-mock-0.5.0/mockgen/internal/tests/vendor_pkg/doc.go000066400000000000000000000001631470430142200251010ustar00rootroot00000000000000package vendor_pkg //go:generate mockgen -destination mock.go -package vendor_pkg golang.org/x/tools/present Elem golang-go.uber-mock-0.5.0/mockgen/internal/tests/vendor_pkg/mock.go000066400000000000000000000026031470430142200252660ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: golang.org/x/tools/present (interfaces: Elem) // // Generated by this command: // // mockgen -destination mock.go -package vendor_pkg golang.org/x/tools/present Elem // // Package vendor_pkg is a generated GoMock package. package vendor_pkg import ( reflect "reflect" gomock "go.uber.org/mock/gomock" ) // MockElem is a mock of Elem interface. type MockElem struct { ctrl *gomock.Controller recorder *MockElemMockRecorder isgomock struct{} } // MockElemMockRecorder is the mock recorder for MockElem. type MockElemMockRecorder struct { mock *MockElem } // NewMockElem creates a new mock instance. func NewMockElem(ctrl *gomock.Controller) *MockElem { mock := &MockElem{ctrl: ctrl} mock.recorder = &MockElemMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockElem) EXPECT() *MockElemMockRecorder { return m.recorder } // TemplateName mocks base method. func (m *MockElem) TemplateName() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "TemplateName") ret0, _ := ret[0].(string) return ret0 } // TemplateName indicates an expected call of TemplateName. func (mr *MockElemMockRecorder) TemplateName() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TemplateName", reflect.TypeOf((*MockElem)(nil).TemplateName)) } golang-go.uber-mock-0.5.0/mockgen/mockgen.go000066400000000000000000000651711470430142200206550ustar00rootroot00000000000000// Copyright 2010 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // MockGen generates mock implementations of Go interfaces. package main // TODO: This does not support recursive embedded interfaces. // TODO: This does not support embedding package-local interfaces in a separate file. import ( "bytes" "encoding/json" "errors" "flag" "fmt" "go/token" "io" "log" "os" "os/exec" "path" "path/filepath" "runtime" "sort" "strconv" "strings" "unicode" "golang.org/x/mod/modfile" toolsimports "golang.org/x/tools/imports" "go.uber.org/mock/mockgen/model" ) const ( gomockImportPath = "go.uber.org/mock/gomock" ) var ( version = "" commit = "none" date = "unknown" ) var ( source = flag.String("source", "", "(source mode) Input Go source file; enables source mode.") destination = flag.String("destination", "", "Output file; defaults to stdout.") mockNames = flag.String("mock_names", "", "Comma-separated interfaceName=mockName pairs of explicit mock names to use. Mock names default to 'Mock'+ interfaceName suffix.") packageOut = flag.String("package", "", "Package of the generated code; defaults to the package of the input with a 'mock_' prefix.") selfPackage = flag.String("self_package", "", "The full package import path for the generated code. The purpose of this flag is to prevent import cycles in the generated code by trying to include its own package. This can happen if the mock's package is set to one of its inputs (usually the main one) and the output is stdio so mockgen cannot detect the final output package. Setting this flag will then tell mockgen which import to exclude.") writeCmdComment = flag.Bool("write_command_comment", true, "Writes the command used as a comment if true.") writePkgComment = flag.Bool("write_package_comment", true, "Writes package documentation comment (godoc) if true.") writeSourceComment = flag.Bool("write_source_comment", true, "Writes original file (source mode) or interface names (package mode) comment if true.") writeGenerateDirective = flag.Bool("write_generate_directive", false, "Add //go:generate directive to regenerate the mock") copyrightFile = flag.String("copyright_file", "", "Copyright file used to add copyright header") buildConstraint = flag.String("build_constraint", "", "If non-empty, added as //go:build ") typed = flag.Bool("typed", false, "Generate Type-safe 'Return', 'Do', 'DoAndReturn' function") imports = flag.String("imports", "", "(source mode) Comma-separated name=path pairs of explicit imports to use.") auxFiles = flag.String("aux_files", "", "(source mode) Comma-separated pkg=path pairs of auxiliary Go source files.") excludeInterfaces = flag.String("exclude_interfaces", "", "(source mode) Comma-separated names of interfaces to be excluded") modelGob = flag.String("model_gob", "", "Skip package/source loading entirely and use the gob encoded model.Package at the given path") debugParser = flag.Bool("debug_parser", false, "Print out parser results only.") showVersion = flag.Bool("version", false, "Print version.") ) func main() { flag.Usage = usage flag.Parse() notifyAboutDeprecatedFlags() if *showVersion { printVersion() return } var pkg *model.Package var err error var packageName string if *modelGob != "" { pkg, err = gobMode(*modelGob) } else if *source != "" { pkg, err = sourceMode(*source) } else { if flag.NArg() != 2 { usage() log.Fatal("Expected exactly two arguments") } packageName = flag.Arg(0) interfaces := strings.Split(flag.Arg(1), ",") if packageName == "." { dir, err := os.Getwd() if err != nil { log.Fatalf("Get current directory failed: %v", err) } packageName, err = packageNameOfDir(dir) if err != nil { log.Fatalf("Parse package name failed: %v", err) } } parser := packageModeParser{} pkg, err = parser.parsePackage(packageName, interfaces) } if err != nil { log.Fatalf("Loading input failed: %v", err) } if *debugParser { pkg.Print(os.Stdout) return } outputPackageName := *packageOut if outputPackageName == "" { // pkg.Name in package mode is the base name of the import path, // which might have characters that are illegal to have in package names. outputPackageName = "mock_" + sanitize(pkg.Name) } // outputPackagePath represents the fully qualified name of the package of // the generated code. Its purposes are to prevent the module from importing // itself and to prevent qualifying type names that come from its own // package (i.e. if there is a type called X then we want to print "X" not // "package.X" since "package" is this package). This can happen if the mock // is output into an already existing package. outputPackagePath := *selfPackage if outputPackagePath == "" && *destination != "" { dstPath, err := filepath.Abs(filepath.Dir(*destination)) if err == nil { pkgPath, err := parsePackageImport(dstPath) if err == nil { outputPackagePath = pkgPath } else { log.Println("Unable to infer -self_package from destination file path:", err) } } else { log.Println("Unable to determine destination file path:", err) } } g := &generator{ buildConstraint: *buildConstraint, } if *source != "" { g.filename = *source } else { g.srcPackage = packageName g.srcInterfaces = flag.Arg(1) } g.destination = *destination if *mockNames != "" { g.mockNames = parseMockNames(*mockNames) } if *copyrightFile != "" { header, err := os.ReadFile(*copyrightFile) if err != nil { log.Fatalf("Failed reading copyright file: %v", err) } g.copyrightHeader = string(header) } if err := g.Generate(pkg, outputPackageName, outputPackagePath); err != nil { log.Fatalf("Failed generating mock: %v", err) } output := g.Output() dst := os.Stdout if len(*destination) > 0 { if err := os.MkdirAll(filepath.Dir(*destination), os.ModePerm); err != nil { log.Fatalf("Unable to create directory: %v", err) } existing, err := os.ReadFile(*destination) if err != nil && !errors.Is(err, os.ErrNotExist) { log.Fatalf("Failed reading pre-exiting destination file: %v", err) } if len(existing) == len(output) && bytes.Equal(existing, output) { return } f, err := os.Create(*destination) if err != nil { log.Fatalf("Failed opening destination file: %v", err) } defer f.Close() dst = f } if _, err := dst.Write(output); err != nil { log.Fatalf("Failed writing to destination: %v", err) } } func parseMockNames(names string) map[string]string { mocksMap := make(map[string]string) for _, kv := range strings.Split(names, ",") { parts := strings.SplitN(kv, "=", 2) if len(parts) != 2 || parts[1] == "" { log.Fatalf("bad mock names spec: %v", kv) } mocksMap[parts[0]] = parts[1] } return mocksMap } func parseExcludeInterfaces(names string) map[string]struct{} { splitNames := strings.Split(names, ",") namesSet := make(map[string]struct{}, len(splitNames)) for _, name := range splitNames { if name == "" { continue } namesSet[name] = struct{}{} } if len(namesSet) == 0 { return nil } return namesSet } func usage() { _, _ = io.WriteString(os.Stderr, usageText) flag.PrintDefaults() } const usageText = `mockgen has two modes of operation: source and package. Source mode generates mock interfaces from a source file. It is enabled by using the -source flag. Other flags that may be useful in this mode are -imports, -aux_files and -exclude_interfaces. Example: mockgen -source=foo.go [other options] Package mode works by specifying the package and interface names. It is enabled by passing two non-flag arguments: an import path, and a comma-separated list of symbols. You can use "." to refer to the current path's package. Example: mockgen database/sql/driver Conn,Driver mockgen . SomeInterface ` type generator struct { buf bytes.Buffer indent string mockNames map[string]string // may be empty filename string // may be empty destination string // may be empty srcPackage, srcInterfaces string // may be empty copyrightHeader string buildConstraint string // may be empty packageMap map[string]string // map from import path to package name } func (g *generator) p(format string, args ...any) { _, _ = fmt.Fprintf(&g.buf, g.indent+format+"\n", args...) } func (g *generator) in() { g.indent += "\t" } func (g *generator) out() { if len(g.indent) > 0 { g.indent = g.indent[0 : len(g.indent)-1] } } // sanitize cleans up a string to make a suitable package name. func sanitize(s string) string { t := "" for _, r := range s { if t == "" { if unicode.IsLetter(r) || r == '_' { t += string(r) continue } } else { if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' { t += string(r) continue } } t += "_" } if t == "_" { t = "x" } return t } func (g *generator) Generate(pkg *model.Package, outputPkgName string, outputPackagePath string) error { if outputPkgName != pkg.Name && *selfPackage == "" { // reset outputPackagePath if it's not passed in through -self_package outputPackagePath = "" } if g.copyrightHeader != "" { lines := strings.Split(g.copyrightHeader, "\n") for _, line := range lines { g.p("// %s", line) } g.p("") } if g.buildConstraint != "" { g.p("//go:build %s", g.buildConstraint) // https://pkg.go.dev/cmd/go#hdr-Build_constraints:~:text=a%20build%20constraint%20should%20be%20followed%20by%20a%20blank%20line g.p("") } g.p("// Code generated by MockGen. DO NOT EDIT.") if *writeSourceComment { if g.filename != "" { g.p("// Source: %v", g.filename) } else { g.p("// Source: %v (interfaces: %v)", g.srcPackage, g.srcInterfaces) } } if *writeCmdComment { g.p("//") g.p("// Generated by this command:") g.p("//") // only log the name of the executable, not the full path name := filepath.Base(os.Args[0]) if runtime.GOOS == "windows" { name = strings.TrimSuffix(name, ".exe") } g.p("//\t%v", strings.Join(append([]string{name}, os.Args[1:]...), " ")) g.p("//") } // Get all required imports, and generate unique names for them all. im := pkg.Imports() im[gomockImportPath] = true // Only import reflect if it's used. We only use reflect in mocked methods // so only import if any of the mocked interfaces have methods. for _, intf := range pkg.Interfaces { if len(intf.Methods) > 0 { im["reflect"] = true break } } // Sort keys to make import alias generation predictable sortedPaths := make([]string, len(im)) x := 0 for pth := range im { sortedPaths[x] = pth x++ } sort.Strings(sortedPaths) packagesName := createPackageMap(sortedPaths) definedImports := make(map[string]string, len(im)) if *imports != "" { for _, kv := range strings.Split(*imports, ",") { eq := strings.Index(kv, "=") if k, v := kv[:eq], kv[eq+1:]; k != "." { definedImports[v] = k } } } g.packageMap = make(map[string]string, len(im)) localNames := make(map[string]bool, len(im)) for _, pth := range sortedPaths { base, ok := packagesName[pth] if !ok { base = sanitize(path.Base(pth)) } // Local names for an imported package can usually be the basename of the import path. // A couple of situations don't permit that, such as duplicate local names // (e.g. importing "html/template" and "text/template"), or where the basename is // a keyword (e.g. "foo/case") or when defining a name for that by using the -imports flag. // try base0, base1, ... pkgName := base if _, ok := definedImports[base]; ok { pkgName = definedImports[base] } i := 0 for localNames[pkgName] || token.Lookup(pkgName).IsKeyword() || pkgName == "any" { pkgName = base + strconv.Itoa(i) i++ } // Avoid importing package if source pkg == output pkg if pth == pkg.PkgPath && outputPackagePath == pkg.PkgPath { continue } g.packageMap[pth] = pkgName localNames[pkgName] = true } // Ensure there is an empty line between “generated by” block and // package documentation comments to follow the recommendations: // https://go.dev/wiki/CodeReviewComments#package-comments // That is, “generated by” should not be a package comment. g.p("") if *writePkgComment { g.p("// Package %v is a generated GoMock package.", outputPkgName) } g.p("package %v", outputPkgName) g.p("") g.p("import (") g.in() for pkgPath, pkgName := range g.packageMap { if pkgPath == outputPackagePath { continue } g.p("%v %q", pkgName, pkgPath) } for _, pkgPath := range pkg.DotImports { g.p(". %q", pkgPath) } g.out() g.p(")") if *writeGenerateDirective { g.p("//go:generate %v", strings.Join(os.Args, " ")) } for _, intf := range pkg.Interfaces { if err := g.GenerateMockInterface(intf, outputPackagePath); err != nil { return err } } return nil } // The name of the mock type to use for the given interface identifier. func (g *generator) mockName(typeName string) string { if mockName, ok := g.mockNames[typeName]; ok { return mockName } return "Mock" + typeName } // formattedTypeParams returns a long and short form of type param info used for // printing. If analyzing a interface with type param [I any, O any] the result // will be: // "[I any, O any]", "[I, O]" func (g *generator) formattedTypeParams(it *model.Interface, pkgOverride string) (string, string) { if len(it.TypeParams) == 0 { return "", "" } var long, short strings.Builder long.WriteString("[") short.WriteString("[") for i, v := range it.TypeParams { if i != 0 { long.WriteString(", ") short.WriteString(", ") } long.WriteString(v.Name) short.WriteString(v.Name) long.WriteString(fmt.Sprintf(" %s", v.Type.String(g.packageMap, pkgOverride))) } long.WriteString("]") short.WriteString("]") return long.String(), short.String() } func (g *generator) GenerateMockInterface(intf *model.Interface, outputPackagePath string) error { mockType := g.mockName(intf.Name) longTp, shortTp := g.formattedTypeParams(intf, outputPackagePath) g.p("") g.p("// %v is a mock of %v interface.", mockType, intf.Name) g.p("type %v%v struct {", mockType, longTp) g.in() g.p("ctrl *gomock.Controller") g.p("recorder *%vMockRecorder%v", mockType, shortTp) g.p("isgomock struct{}") g.out() g.p("}") g.p("") g.p("// %vMockRecorder is the mock recorder for %v.", mockType, mockType) g.p("type %vMockRecorder%v struct {", mockType, longTp) g.in() g.p("mock *%v%v", mockType, shortTp) g.out() g.p("}") g.p("") g.p("// New%v creates a new mock instance.", mockType) g.p("func New%v%v(ctrl *gomock.Controller) *%v%v {", mockType, longTp, mockType, shortTp) g.in() g.p("mock := &%v%v{ctrl: ctrl}", mockType, shortTp) g.p("mock.recorder = &%vMockRecorder%v{mock}", mockType, shortTp) g.p("return mock") g.out() g.p("}") g.p("") // XXX: possible name collision here if someone has EXPECT in their interface. g.p("// EXPECT returns an object that allows the caller to indicate expected use.") g.p("func (m *%v%v) EXPECT() *%vMockRecorder%v {", mockType, shortTp, mockType, shortTp) g.in() g.p("return m.recorder") g.out() g.p("}") g.GenerateMockMethods(mockType, intf, outputPackagePath, longTp, shortTp, *typed) return nil } type byMethodName []*model.Method func (b byMethodName) Len() int { return len(b) } func (b byMethodName) Swap(i, j int) { b[i], b[j] = b[j], b[i] } func (b byMethodName) Less(i, j int) bool { return b[i].Name < b[j].Name } func (g *generator) GenerateMockMethods(mockType string, intf *model.Interface, pkgOverride, longTp, shortTp string, typed bool) { sort.Sort(byMethodName(intf.Methods)) for _, m := range intf.Methods { g.p("") _ = g.GenerateMockMethod(mockType, m, pkgOverride, shortTp) g.p("") _ = g.GenerateMockRecorderMethod(intf, m, shortTp, typed) if typed { g.p("") _ = g.GenerateMockReturnCallMethod(intf, m, pkgOverride, longTp, shortTp) } } } func makeArgString(argNames, argTypes []string) string { args := make([]string, len(argNames)) for i, name := range argNames { // specify the type only once for consecutive args of the same type if i+1 < len(argTypes) && argTypes[i] == argTypes[i+1] { args[i] = name } else { args[i] = name + " " + argTypes[i] } } return strings.Join(args, ", ") } // GenerateMockMethod generates a mock method implementation. // If non-empty, pkgOverride is the package in which unqualified types reside. func (g *generator) GenerateMockMethod(mockType string, m *model.Method, pkgOverride, shortTp string) error { argNames := g.getArgNames(m, true /* in */) argTypes := g.getArgTypes(m, pkgOverride, true /* in */) argString := makeArgString(argNames, argTypes) rets := make([]string, len(m.Out)) for i, p := range m.Out { rets[i] = p.Type.String(g.packageMap, pkgOverride) } retString := strings.Join(rets, ", ") if len(rets) > 1 { retString = "(" + retString + ")" } if retString != "" { retString = " " + retString } ia := newIdentifierAllocator(argNames) idRecv := ia.allocateIdentifier("m") g.p("// %v mocks base method.", m.Name) g.p("func (%v *%v%v) %v(%v)%v {", idRecv, mockType, shortTp, m.Name, argString, retString) g.in() g.p("%s.ctrl.T.Helper()", idRecv) var callArgs string if m.Variadic == nil { if len(argNames) > 0 { callArgs = ", " + strings.Join(argNames, ", ") } } else { // Non-trivial. The generated code must build a []any, // but the variadic argument may be any type. idVarArgs := ia.allocateIdentifier("varargs") idVArg := ia.allocateIdentifier("a") g.p("%s := []any{%s}", idVarArgs, strings.Join(argNames[:len(argNames)-1], ", ")) g.p("for _, %s := range %s {", idVArg, argNames[len(argNames)-1]) g.in() g.p("%s = append(%s, %s)", idVarArgs, idVarArgs, idVArg) g.out() g.p("}") callArgs = ", " + idVarArgs + "..." } if len(m.Out) == 0 { g.p(`%v.ctrl.Call(%v, %q%v)`, idRecv, idRecv, m.Name, callArgs) } else { idRet := ia.allocateIdentifier("ret") g.p(`%v := %v.ctrl.Call(%v, %q%v)`, idRet, idRecv, idRecv, m.Name, callArgs) // Go does not allow "naked" type assertions on nil values, so we use the two-value form here. // The value of that is either (x.(T), true) or (Z, false), where Z is the zero value for T. // Happily, this coincides with the semantics we want here. retNames := make([]string, len(rets)) for i, t := range rets { retNames[i] = ia.allocateIdentifier(fmt.Sprintf("ret%d", i)) g.p("%s, _ := %s[%d].(%s)", retNames[i], idRet, i, t) } g.p("return " + strings.Join(retNames, ", ")) } g.out() g.p("}") return nil } func (g *generator) GenerateMockRecorderMethod(intf *model.Interface, m *model.Method, shortTp string, typed bool) error { mockType := g.mockName(intf.Name) argNames := g.getArgNames(m, true) var argString string if m.Variadic == nil { argString = strings.Join(argNames, ", ") } else { argString = strings.Join(argNames[:len(argNames)-1], ", ") } if argString != "" { argString += " any" } if m.Variadic != nil { if argString != "" { argString += ", " } argString += fmt.Sprintf("%s ...any", argNames[len(argNames)-1]) } ia := newIdentifierAllocator(argNames) idRecv := ia.allocateIdentifier("mr") g.p("// %v indicates an expected call of %v.", m.Name, m.Name) if typed { g.p("func (%s *%vMockRecorder%v) %v(%v) *%s%sCall%s {", idRecv, mockType, shortTp, m.Name, argString, mockType, m.Name, shortTp) } else { g.p("func (%s *%vMockRecorder%v) %v(%v) *gomock.Call {", idRecv, mockType, shortTp, m.Name, argString) } g.in() g.p("%s.mock.ctrl.T.Helper()", idRecv) var callArgs string if m.Variadic == nil { if len(argNames) > 0 { callArgs = ", " + strings.Join(argNames, ", ") } } else { if len(argNames) == 1 { // Easy: just use ... to push the arguments through. callArgs = ", " + argNames[0] + "..." } else { // Hard: create a temporary slice. idVarArgs := ia.allocateIdentifier("varargs") g.p("%s := append([]any{%s}, %s...)", idVarArgs, strings.Join(argNames[:len(argNames)-1], ", "), argNames[len(argNames)-1]) callArgs = ", " + idVarArgs + "..." } } if typed { g.p(`call := %s.mock.ctrl.RecordCallWithMethodType(%s.mock, "%s", reflect.TypeOf((*%s%s)(nil).%s)%s)`, idRecv, idRecv, m.Name, mockType, shortTp, m.Name, callArgs) g.p(`return &%s%sCall%s{Call: call}`, mockType, m.Name, shortTp) } else { g.p(`return %s.mock.ctrl.RecordCallWithMethodType(%s.mock, "%s", reflect.TypeOf((*%s%s)(nil).%s)%s)`, idRecv, idRecv, m.Name, mockType, shortTp, m.Name, callArgs) } g.out() g.p("}") return nil } func (g *generator) GenerateMockReturnCallMethod(intf *model.Interface, m *model.Method, pkgOverride, longTp, shortTp string) error { mockType := g.mockName(intf.Name) argNames := g.getArgNames(m, true /* in */) retNames := g.getArgNames(m, false /* out */) argTypes := g.getArgTypes(m, pkgOverride, true /* in */) retTypes := g.getArgTypes(m, pkgOverride, false /* out */) argString := strings.Join(argTypes, ", ") rets := make([]string, len(m.Out)) for i, p := range m.Out { rets[i] = p.Type.String(g.packageMap, pkgOverride) } var retString string switch { case len(rets) == 1: retString = " " + rets[0] case len(rets) > 1: retString = " (" + strings.Join(rets, ", ") + ")" } ia := newIdentifierAllocator(argNames) idRecv := ia.allocateIdentifier("c") recvStructName := mockType + m.Name g.p("// %s%sCall wrap *gomock.Call", mockType, m.Name) g.p("type %s%sCall%s struct{", mockType, m.Name, longTp) g.in() g.p("*gomock.Call") g.out() g.p("}") g.p("// Return rewrite *gomock.Call.Return") g.p("func (%s *%sCall%s) Return(%v) *%sCall%s {", idRecv, recvStructName, shortTp, makeArgString(retNames, retTypes), recvStructName, shortTp) g.in() var retArgs string if len(retNames) > 0 { retArgs = strings.Join(retNames, ", ") } g.p(`%s.Call = %v.Call.Return(%v)`, idRecv, idRecv, retArgs) g.p("return %s", idRecv) g.out() g.p("}") g.p("// Do rewrite *gomock.Call.Do") g.p("func (%s *%sCall%s) Do(f func(%v)%v) *%sCall%s {", idRecv, recvStructName, shortTp, argString, retString, recvStructName, shortTp) g.in() g.p(`%s.Call = %v.Call.Do(f)`, idRecv, idRecv) g.p("return %s", idRecv) g.out() g.p("}") g.p("// DoAndReturn rewrite *gomock.Call.DoAndReturn") g.p("func (%s *%sCall%s) DoAndReturn(f func(%v)%v) *%sCall%s {", idRecv, recvStructName, shortTp, argString, retString, recvStructName, shortTp) g.in() g.p(`%s.Call = %v.Call.DoAndReturn(f)`, idRecv, idRecv) g.p("return %s", idRecv) g.out() g.p("}") return nil } func (g *generator) getArgNames(m *model.Method, in bool) []string { var params []*model.Parameter if in { params = m.In } else { params = m.Out } argNames := make([]string, len(params)) for i, p := range params { name := p.Name if name == "" || name == "_" { name = fmt.Sprintf("arg%d", i) } argNames[i] = name } if m.Variadic != nil && in { name := m.Variadic.Name if name == "" { name = fmt.Sprintf("arg%d", len(params)) } argNames = append(argNames, name) } return argNames } func (g *generator) getArgTypes(m *model.Method, pkgOverride string, in bool) []string { var params []*model.Parameter if in { params = m.In } else { params = m.Out } argTypes := make([]string, len(params)) for i, p := range params { argTypes[i] = p.Type.String(g.packageMap, pkgOverride) } if m.Variadic != nil { argTypes = append(argTypes, "..."+m.Variadic.Type.String(g.packageMap, pkgOverride)) } return argTypes } type identifierAllocator map[string]struct{} func newIdentifierAllocator(taken []string) identifierAllocator { a := make(identifierAllocator, len(taken)) for _, s := range taken { a[s] = struct{}{} } return a } func (o identifierAllocator) allocateIdentifier(want string) string { id := want for i := 2; ; i++ { if _, ok := o[id]; !ok { o[id] = struct{}{} return id } id = want + "_" + strconv.Itoa(i) } } // Output returns the generator's output, formatted in the standard Go style. func (g *generator) Output() []byte { src, err := toolsimports.Process(g.destination, g.buf.Bytes(), nil) if err != nil { log.Fatalf("Failed to format generated source code: %s\n%s", err, g.buf.String()) } return src } // createPackageMap returns a map of import path to package name // for specified importPaths. func createPackageMap(importPaths []string) map[string]string { var pkg struct { Name string ImportPath string } pkgMap := make(map[string]string) b := bytes.NewBuffer(nil) args := []string{"list", "-json=ImportPath,Name"} args = append(args, importPaths...) cmd := exec.Command("go", args...) cmd.Stdout = b cmd.Run() dec := json.NewDecoder(b) for dec.More() { err := dec.Decode(&pkg) if err != nil { log.Printf("failed to decode 'go list' output: %v", err) continue } pkgMap[pkg.ImportPath] = pkg.Name } return pkgMap } func printVersion() { if version != "" { fmt.Printf("v%s\nCommit: %s\nDate: %s\n", version, commit, date) } else { printModuleVersion() } } // parseImportPackage get package import path via source file // an alternative implementation is to use: // cfg := &packages.Config{Mode: packages.NeedName, Tests: true, Dir: srcDir} // pkgs, err := packages.Load(cfg, "file="+source) // However, it will call "go list" and slow down the performance func parsePackageImport(srcDir string) (string, error) { moduleMode := os.Getenv("GO111MODULE") // trying to find the module if moduleMode != "off" { currentDir := srcDir for { dat, err := os.ReadFile(filepath.Join(currentDir, "go.mod")) if os.IsNotExist(err) { if currentDir == filepath.Dir(currentDir) { // at the root break } currentDir = filepath.Dir(currentDir) continue } else if err != nil { return "", err } modulePath := modfile.ModulePath(dat) return filepath.ToSlash(filepath.Join(modulePath, strings.TrimPrefix(srcDir, currentDir))), nil } } // fall back to GOPATH mode goPaths := os.Getenv("GOPATH") if goPaths == "" { return "", fmt.Errorf("GOPATH is not set") } goPathList := strings.Split(goPaths, string(os.PathListSeparator)) for _, goPath := range goPathList { sourceRoot := filepath.Join(goPath, "src") + string(os.PathSeparator) if strings.HasPrefix(srcDir, sourceRoot) { return filepath.ToSlash(strings.TrimPrefix(srcDir, sourceRoot)), nil } } return "", errOutsideGoPath } golang-go.uber-mock-0.5.0/mockgen/mockgen_test.go000066400000000000000000000267561470430142200217220ustar00rootroot00000000000000package main import ( "fmt" "os" "path" "path/filepath" "reflect" "regexp" "strings" "testing" "go.uber.org/mock/mockgen/model" ) func TestMakeArgString(t *testing.T) { testCases := []struct { argNames []string argTypes []string argString string }{ { argNames: nil, argTypes: nil, argString: "", }, { argNames: []string{"arg0"}, argTypes: []string{"int"}, argString: "arg0 int", }, { argNames: []string{"arg0", "arg1"}, argTypes: []string{"int", "bool"}, argString: "arg0 int, arg1 bool", }, { argNames: []string{"arg0", "arg1"}, argTypes: []string{"int", "int"}, argString: "arg0, arg1 int", }, { argNames: []string{"arg0", "arg1", "arg2"}, argTypes: []string{"bool", "int", "int"}, argString: "arg0 bool, arg1, arg2 int", }, { argNames: []string{"arg0", "arg1", "arg2"}, argTypes: []string{"int", "bool", "int"}, argString: "arg0 int, arg1 bool, arg2 int", }, { argNames: []string{"arg0", "arg1", "arg2"}, argTypes: []string{"int", "int", "bool"}, argString: "arg0, arg1 int, arg2 bool", }, { argNames: []string{"arg0", "arg1", "arg2"}, argTypes: []string{"int", "int", "int"}, argString: "arg0, arg1, arg2 int", }, { argNames: []string{"arg0", "arg1", "arg2", "arg3"}, argTypes: []string{"bool", "int", "int", "int"}, argString: "arg0 bool, arg1, arg2, arg3 int", }, { argNames: []string{"arg0", "arg1", "arg2", "arg3"}, argTypes: []string{"int", "bool", "int", "int"}, argString: "arg0 int, arg1 bool, arg2, arg3 int", }, { argNames: []string{"arg0", "arg1", "arg2", "arg3"}, argTypes: []string{"int", "int", "bool", "int"}, argString: "arg0, arg1 int, arg2 bool, arg3 int", }, { argNames: []string{"arg0", "arg1", "arg2", "arg3"}, argTypes: []string{"int", "int", "int", "bool"}, argString: "arg0, arg1, arg2 int, arg3 bool", }, { argNames: []string{"arg0", "arg1", "arg2", "arg3", "arg4"}, argTypes: []string{"bool", "int", "int", "int", "bool"}, argString: "arg0 bool, arg1, arg2, arg3 int, arg4 bool", }, { argNames: []string{"arg0", "arg1", "arg2", "arg3", "arg4"}, argTypes: []string{"int", "bool", "int", "int", "bool"}, argString: "arg0 int, arg1 bool, arg2, arg3 int, arg4 bool", }, { argNames: []string{"arg0", "arg1", "arg2", "arg3", "arg4"}, argTypes: []string{"int", "int", "bool", "int", "bool"}, argString: "arg0, arg1 int, arg2 bool, arg3 int, arg4 bool", }, { argNames: []string{"arg0", "arg1", "arg2", "arg3", "arg4"}, argTypes: []string{"int", "int", "int", "bool", "bool"}, argString: "arg0, arg1, arg2 int, arg3, arg4 bool", }, { argNames: []string{"arg0", "arg1", "arg2", "arg3", "arg4"}, argTypes: []string{"int", "int", "bool", "bool", "int"}, argString: "arg0, arg1 int, arg2, arg3 bool, arg4 int", }, } for i, tc := range testCases { t.Run(fmt.Sprintf("#%d", i), func(t *testing.T) { s := makeArgString(tc.argNames, tc.argTypes) if s != tc.argString { t.Errorf("result == %q, want %q", s, tc.argString) } }) } } func TestNewIdentifierAllocator(t *testing.T) { a := newIdentifierAllocator([]string{"taken1", "taken2"}) if len(a) != 2 { t.Fatalf("expected 2 items, got %v", len(a)) } _, ok := a["taken1"] if !ok { t.Errorf("allocator doesn't contain 'taken1': %#v", a) } _, ok = a["taken2"] if !ok { t.Errorf("allocator doesn't contain 'taken2': %#v", a) } } func allocatorContainsIdentifiers(a identifierAllocator, ids []string) bool { if len(a) != len(ids) { return false } for _, id := range ids { _, ok := a[id] if !ok { return false } } return true } func TestIdentifierAllocator_allocateIdentifier(t *testing.T) { a := newIdentifierAllocator([]string{"taken"}) t2 := a.allocateIdentifier("taken_2") if t2 != "taken_2" { t.Fatalf("expected 'taken_2', got %q", t2) } expected := []string{"taken", "taken_2"} if !allocatorContainsIdentifiers(a, expected) { t.Fatalf("allocator doesn't contain the expected items - allocator: %#v, expected items: %#v", a, expected) } t3 := a.allocateIdentifier("taken") if t3 != "taken_3" { t.Fatalf("expected 'taken_3', got %q", t3) } expected = []string{"taken", "taken_2", "taken_3"} if !allocatorContainsIdentifiers(a, expected) { t.Fatalf("allocator doesn't contain the expected items - allocator: %#v, expected items: %#v", a, expected) } t4 := a.allocateIdentifier("taken") if t4 != "taken_4" { t.Fatalf("expected 'taken_4', got %q", t4) } expected = []string{"taken", "taken_2", "taken_3", "taken_4"} if !allocatorContainsIdentifiers(a, expected) { t.Fatalf("allocator doesn't contain the expected items - allocator: %#v, expected items: %#v", a, expected) } id := a.allocateIdentifier("id") if id != "id" { t.Fatalf("expected 'id', got %q", id) } expected = []string{"taken", "taken_2", "taken_3", "taken_4", "id"} if !allocatorContainsIdentifiers(a, expected) { t.Fatalf("allocator doesn't contain the expected items - allocator: %#v, expected items: %#v", a, expected) } } func TestGenerateMockInterface_Helper(t *testing.T) { for _, test := range []struct { Name string Identifier string HelperLine string Methods []*model.Method }{ {Name: "mock", Identifier: "MockSomename", HelperLine: "m.ctrl.T.Helper()"}, {Name: "recorder", Identifier: "MockSomenameMockRecorder", HelperLine: "mr.mock.ctrl.T.Helper()"}, { Name: "mock identifier conflict", Identifier: "MockSomename", HelperLine: "m_2.ctrl.T.Helper()", Methods: []*model.Method{ { Name: "MethodA", In: []*model.Parameter{ { Name: "m", Type: &model.NamedType{Type: "int"}, }, }, }, }, }, { Name: "recorder identifier conflict", Identifier: "MockSomenameMockRecorder", HelperLine: "mr_2.mock.ctrl.T.Helper()", Methods: []*model.Method{ { Name: "MethodA", In: []*model.Parameter{ { Name: "mr", Type: &model.NamedType{Type: "int"}, }, }, }, }, }, } { t.Run(test.Name, func(t *testing.T) { g := generator{} if len(test.Methods) == 0 { test.Methods = []*model.Method{ {Name: "MethodA"}, {Name: "MethodB"}, } } intf := &model.Interface{Name: "Somename"} for _, m := range test.Methods { intf.AddMethod(m) } if err := g.GenerateMockInterface(intf, "somepackage"); err != nil { t.Fatal(err) } lines := strings.Split(g.buf.String(), "\n") // T.Helper() should be the first line for _, method := range test.Methods { if strings.TrimSpace(lines[findMethod(t, test.Identifier, method.Name, lines)+1]) != test.HelperLine { t.Fatalf("method %s.%s did not declare itself a Helper method", test.Identifier, method.Name) } } }) } } func findMethod(t *testing.T, identifier, methodName string, lines []string) int { t.Helper() r := regexp.MustCompile(fmt.Sprintf(`func\s+\(.+%s\)\s*%s`, identifier, methodName)) for i, line := range lines { if r.MatchString(line) { return i } } t.Fatalf("unable to find 'func (m %s) %s'", identifier, methodName) panic("unreachable") } func TestGetArgNames(t *testing.T) { for _, testCase := range []struct { name string method *model.Method expected []string }{ { name: "NamedArg", method: &model.Method{ In: []*model.Parameter{ { Name: "firstArg", Type: &model.NamedType{Type: "int"}, }, { Name: "secondArg", Type: &model.NamedType{Type: "string"}, }, }, }, expected: []string{"firstArg", "secondArg"}, }, { name: "NotNamedArg", method: &model.Method{ In: []*model.Parameter{ { Name: "", Type: &model.NamedType{Type: "int"}, }, { Name: "", Type: &model.NamedType{Type: "string"}, }, }, }, expected: []string{"arg0", "arg1"}, }, { name: "MixedNameArg", method: &model.Method{ In: []*model.Parameter{ { Name: "firstArg", Type: &model.NamedType{Type: "int"}, }, { Name: "_", Type: &model.NamedType{Type: "string"}, }, }, }, expected: []string{"firstArg", "arg1"}, }, } { t.Run(testCase.name, func(t *testing.T) { g := generator{} result := g.getArgNames(testCase.method, true) if !reflect.DeepEqual(result, testCase.expected) { t.Fatalf("expected %s, got %s", result, testCase.expected) } }) } } func Test_createPackageMap(t *testing.T) { tests := []struct { name string importPath string wantPackageName string wantOK bool }{ {"golang package", "context", "context", true}, {"third party", "golang.org/x/tools/present", "present", true}, } var importPaths []string for _, t := range tests { importPaths = append(importPaths, t.importPath) } packages := createPackageMap(importPaths) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gotPackageName, gotOk := packages[tt.importPath] if gotPackageName != tt.wantPackageName { t.Errorf("createPackageMap() gotPackageName = %v, wantPackageName = %v", gotPackageName, tt.wantPackageName) } if gotOk != tt.wantOK { t.Errorf("createPackageMap() gotOk = %v, wantOK = %v", gotOk, tt.wantOK) } }) } } func TestParsePackageImport_FallbackGoPath(t *testing.T) { goPath := t.TempDir() expectedPkgPath := path.Join("example.com", "foo") srcDir := filepath.Join(goPath, "src", expectedPkgPath) err := os.MkdirAll(srcDir, 0o755) if err != nil { t.Fatal(err) } t.Setenv("GOPATH", goPath) t.Setenv("GO111MODULE", "on") pkgPath, err := parsePackageImport(srcDir) if err != nil { t.Fatal(err) } if pkgPath != expectedPkgPath { t.Errorf("expect %s, got %s", expectedPkgPath, pkgPath) } } func TestParsePackageImport_FallbackMultiGoPath(t *testing.T) { // first gopath goPath := t.TempDir() goPathList := []string{goPath} expectedPkgPath := path.Join("example.com", "foo") srcDir := filepath.Join(goPath, "src", expectedPkgPath) err := os.MkdirAll(srcDir, 0o755) if err != nil { t.Fatal(err) } // second gopath goPath = t.TempDir() goPathList = append(goPathList, goPath) goPaths := strings.Join(goPathList, string(os.PathListSeparator)) t.Setenv("GOPATH", goPaths) t.Setenv("GO111MODULE", "on") pkgPath, err := parsePackageImport(srcDir) if err != nil { t.Fatal(err) } if pkgPath != expectedPkgPath { t.Errorf("expect %s, got %s", expectedPkgPath, pkgPath) } } func TestParseExcludeInterfaces(t *testing.T) { testCases := []struct { name string arg string expected map[string]struct{} }{ { name: "empty string", arg: "", expected: nil, }, { name: "string without a comma", arg: "arg1", expected: map[string]struct{}{"arg1": {}}, }, { name: "two names", arg: "arg1,arg2", expected: map[string]struct{}{"arg1": {}, "arg2": {}}, }, { name: "two names with a comma at the end", arg: "arg1,arg2,", expected: map[string]struct{}{"arg1": {}, "arg2": {}}, }, { name: "two names with a comma at the beginning", arg: ",arg1,arg2", expected: map[string]struct{}{"arg1": {}, "arg2": {}}, }, { name: "commas only", arg: ",,,,", expected: nil, }, { name: "duplicates", arg: "arg1,arg2,arg1", expected: map[string]struct{}{"arg1": {}, "arg2": {}}, }, } for _, tt := range testCases { t.Run(tt.name, func(t *testing.T) { actual := parseExcludeInterfaces(tt.arg) if !reflect.DeepEqual(actual, tt.expected) { t.Errorf("expected %v, actual %v", tt.expected, actual) } }) } } golang-go.uber-mock-0.5.0/mockgen/model/000077500000000000000000000000001470430142200177715ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/mockgen/model/model.go000066400000000000000000000314151470430142200214240ustar00rootroot00000000000000// Copyright 2012 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package model contains the data model necessary for generating mock implementations. package model import ( "encoding/gob" "fmt" "io" "reflect" "strings" ) // pkgPath is the importable path for package model const pkgPath = "go.uber.org/mock/mockgen/model" // Package is a Go package. It may be a subset. type Package struct { Name string PkgPath string Interfaces []*Interface DotImports []string } // Print writes the package name and its exported interfaces. func (pkg *Package) Print(w io.Writer) { _, _ = fmt.Fprintf(w, "package %s\n", pkg.Name) for _, intf := range pkg.Interfaces { intf.Print(w) } } // Imports returns the imports needed by the Package as a set of import paths. func (pkg *Package) Imports() map[string]bool { im := make(map[string]bool) for _, intf := range pkg.Interfaces { intf.addImports(im) for _, tp := range intf.TypeParams { tp.Type.addImports(im) } } return im } // Interface is a Go interface. type Interface struct { Name string Methods []*Method TypeParams []*Parameter } // Print writes the interface name and its methods. func (intf *Interface) Print(w io.Writer) { _, _ = fmt.Fprintf(w, "interface %s\n", intf.Name) for _, m := range intf.Methods { m.Print(w) } } func (intf *Interface) addImports(im map[string]bool) { for _, m := range intf.Methods { m.addImports(im) } } // AddMethod adds a new method, de-duplicating by method name. func (intf *Interface) AddMethod(m *Method) { for _, me := range intf.Methods { if me.Name == m.Name { return } } intf.Methods = append(intf.Methods, m) } // Method is a single method of an interface. type Method struct { Name string In, Out []*Parameter Variadic *Parameter // may be nil } // Print writes the method name and its signature. func (m *Method) Print(w io.Writer) { _, _ = fmt.Fprintf(w, " - method %s\n", m.Name) if len(m.In) > 0 { _, _ = fmt.Fprintf(w, " in:\n") for _, p := range m.In { p.Print(w) } } if m.Variadic != nil { _, _ = fmt.Fprintf(w, " ...:\n") m.Variadic.Print(w) } if len(m.Out) > 0 { _, _ = fmt.Fprintf(w, " out:\n") for _, p := range m.Out { p.Print(w) } } } func (m *Method) addImports(im map[string]bool) { for _, p := range m.In { p.Type.addImports(im) } if m.Variadic != nil { m.Variadic.Type.addImports(im) } for _, p := range m.Out { p.Type.addImports(im) } } // Parameter is an argument or return parameter of a method. type Parameter struct { Name string // may be empty Type Type } // Print writes a method parameter. func (p *Parameter) Print(w io.Writer) { n := p.Name if n == "" { n = `""` } _, _ = fmt.Fprintf(w, " - %v: %v\n", n, p.Type.String(nil, "")) } // Type is a Go type. type Type interface { String(pm map[string]string, pkgOverride string) string addImports(im map[string]bool) } func init() { // Call gob.RegisterName with pkgPath as prefix to avoid conflicting with // github.com/golang/mock/mockgen/model 's registration. gob.RegisterName(pkgPath+".ArrayType", &ArrayType{}) gob.RegisterName(pkgPath+".ChanType", &ChanType{}) gob.RegisterName(pkgPath+".FuncType", &FuncType{}) gob.RegisterName(pkgPath+".MapType", &MapType{}) gob.RegisterName(pkgPath+".NamedType", &NamedType{}) gob.RegisterName(pkgPath+".PointerType", &PointerType{}) // Call gob.RegisterName to make sure it has the consistent name registered // for both gob decoder and encoder. // // For a non-pointer type, gob.Register will try to get package full path by // calling rt.PkgPath() for a name to register. If your project has vendor // directory, it is possible that PkgPath will get a path like this: // ../../../vendor/go.uber.org/mock/mockgen/model gob.RegisterName(pkgPath+".PredeclaredType", PredeclaredType("")) } // ArrayType is an array or slice type. type ArrayType struct { Len int // -1 for slices, >= 0 for arrays Type Type } func (at *ArrayType) String(pm map[string]string, pkgOverride string) string { s := "[]" if at.Len > -1 { s = fmt.Sprintf("[%d]", at.Len) } return s + at.Type.String(pm, pkgOverride) } func (at *ArrayType) addImports(im map[string]bool) { at.Type.addImports(im) } // ChanType is a channel type. type ChanType struct { Dir ChanDir // 0, 1 or 2 Type Type } func (ct *ChanType) String(pm map[string]string, pkgOverride string) string { s := ct.Type.String(pm, pkgOverride) if ct.Dir == RecvDir { return "<-chan " + s } if ct.Dir == SendDir { return "chan<- " + s } return "chan " + s } func (ct *ChanType) addImports(im map[string]bool) { ct.Type.addImports(im) } // ChanDir is a channel direction. type ChanDir int // Constants for channel directions. const ( RecvDir ChanDir = 1 SendDir ChanDir = 2 ) // FuncType is a function type. type FuncType struct { In, Out []*Parameter Variadic *Parameter // may be nil } func (ft *FuncType) String(pm map[string]string, pkgOverride string) string { args := make([]string, len(ft.In)) for i, p := range ft.In { args[i] = p.Type.String(pm, pkgOverride) } if ft.Variadic != nil { args = append(args, "..."+ft.Variadic.Type.String(pm, pkgOverride)) } rets := make([]string, len(ft.Out)) for i, p := range ft.Out { rets[i] = p.Type.String(pm, pkgOverride) } retString := strings.Join(rets, ", ") if nOut := len(ft.Out); nOut == 1 { retString = " " + retString } else if nOut > 1 { retString = " (" + retString + ")" } return "func(" + strings.Join(args, ", ") + ")" + retString } func (ft *FuncType) addImports(im map[string]bool) { for _, p := range ft.In { p.Type.addImports(im) } if ft.Variadic != nil { ft.Variadic.Type.addImports(im) } for _, p := range ft.Out { p.Type.addImports(im) } } // MapType is a map type. type MapType struct { Key, Value Type } func (mt *MapType) String(pm map[string]string, pkgOverride string) string { return "map[" + mt.Key.String(pm, pkgOverride) + "]" + mt.Value.String(pm, pkgOverride) } func (mt *MapType) addImports(im map[string]bool) { mt.Key.addImports(im) mt.Value.addImports(im) } // NamedType is an exported type in a package. type NamedType struct { Package string // may be empty Type string TypeParams *TypeParametersType } func (nt *NamedType) String(pm map[string]string, pkgOverride string) string { if pkgOverride == nt.Package { return nt.Type + nt.TypeParams.String(pm, pkgOverride) } prefix := pm[nt.Package] if prefix != "" { return prefix + "." + nt.Type + nt.TypeParams.String(pm, pkgOverride) } return nt.Type + nt.TypeParams.String(pm, pkgOverride) } func (nt *NamedType) addImports(im map[string]bool) { if nt.Package != "" { im[nt.Package] = true } nt.TypeParams.addImports(im) } // PointerType is a pointer to another type. type PointerType struct { Type Type } func (pt *PointerType) String(pm map[string]string, pkgOverride string) string { return "*" + pt.Type.String(pm, pkgOverride) } func (pt *PointerType) addImports(im map[string]bool) { pt.Type.addImports(im) } // PredeclaredType is a predeclared type such as "int". type PredeclaredType string func (pt PredeclaredType) String(map[string]string, string) string { return string(pt) } func (pt PredeclaredType) addImports(map[string]bool) {} // TypeParametersType contains type parameters for a NamedType. type TypeParametersType struct { TypeParameters []Type } func (tp *TypeParametersType) String(pm map[string]string, pkgOverride string) string { if tp == nil || len(tp.TypeParameters) == 0 { return "" } var sb strings.Builder sb.WriteString("[") for i, v := range tp.TypeParameters { if i != 0 { sb.WriteString(", ") } sb.WriteString(v.String(pm, pkgOverride)) } sb.WriteString("]") return sb.String() } func (tp *TypeParametersType) addImports(im map[string]bool) { if tp == nil { return } for _, v := range tp.TypeParameters { v.addImports(im) } } // The following code is intended to be called by the program generated by ../reflect.go. // InterfaceFromInterfaceType returns a pointer to an interface for the // given reflection interface type. func InterfaceFromInterfaceType(it reflect.Type) (*Interface, error) { if it.Kind() != reflect.Interface { return nil, fmt.Errorf("%v is not an interface", it) } intf := &Interface{} for i := 0; i < it.NumMethod(); i++ { mt := it.Method(i) // TODO: need to skip unexported methods? or just raise an error? m := &Method{ Name: mt.Name, } var err error m.In, m.Variadic, m.Out, err = funcArgsFromType(mt.Type) if err != nil { return nil, err } intf.AddMethod(m) } return intf, nil } // t's Kind must be a reflect.Func. func funcArgsFromType(t reflect.Type) (in []*Parameter, variadic *Parameter, out []*Parameter, err error) { nin := t.NumIn() if t.IsVariadic() { nin-- } var p *Parameter for i := 0; i < nin; i++ { p, err = parameterFromType(t.In(i)) if err != nil { return } in = append(in, p) } if t.IsVariadic() { p, err = parameterFromType(t.In(nin).Elem()) if err != nil { return } variadic = p } for i := 0; i < t.NumOut(); i++ { p, err = parameterFromType(t.Out(i)) if err != nil { return } out = append(out, p) } return } func parameterFromType(t reflect.Type) (*Parameter, error) { tt, err := typeFromType(t) if err != nil { return nil, err } return &Parameter{Type: tt}, nil } var errorType = reflect.TypeOf((*error)(nil)).Elem() var byteType = reflect.TypeOf(byte(0)) func typeFromType(t reflect.Type) (Type, error) { // Hack workaround for https://golang.org/issue/3853. // This explicit check should not be necessary. if t == byteType { return PredeclaredType("byte"), nil } if imp := t.PkgPath(); imp != "" { return &NamedType{ Package: impPath(imp), Type: t.Name(), }, nil } // only unnamed or predeclared types after here // Lots of types have element types. Let's do the parsing and error checking for all of them. var elemType Type switch t.Kind() { case reflect.Array, reflect.Chan, reflect.Map, reflect.Ptr, reflect.Slice: var err error elemType, err = typeFromType(t.Elem()) if err != nil { return nil, err } } switch t.Kind() { case reflect.Array: return &ArrayType{ Len: t.Len(), Type: elemType, }, nil case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128, reflect.String: return PredeclaredType(t.Kind().String()), nil case reflect.Chan: var dir ChanDir switch t.ChanDir() { case reflect.RecvDir: dir = RecvDir case reflect.SendDir: dir = SendDir } return &ChanType{ Dir: dir, Type: elemType, }, nil case reflect.Func: in, variadic, out, err := funcArgsFromType(t) if err != nil { return nil, err } return &FuncType{ In: in, Out: out, Variadic: variadic, }, nil case reflect.Interface: // Two special interfaces. if t.NumMethod() == 0 { return PredeclaredType("any"), nil } if t == errorType { return PredeclaredType("error"), nil } case reflect.Map: kt, err := typeFromType(t.Key()) if err != nil { return nil, err } return &MapType{ Key: kt, Value: elemType, }, nil case reflect.Ptr: return &PointerType{ Type: elemType, }, nil case reflect.Slice: return &ArrayType{ Len: -1, Type: elemType, }, nil case reflect.Struct: if t.NumField() == 0 { return PredeclaredType("struct{}"), nil } } // TODO: Struct, UnsafePointer return nil, fmt.Errorf("can't yet turn %v (%v) into a model.Type", t, t.Kind()) } // impPath sanitizes the package path returned by `PkgPath` method of a reflect Type so that // it is importable. PkgPath might return a path that includes "vendor". These paths do not // compile, so we need to remove everything up to and including "/vendor/". // See https://github.com/golang/go/issues/12019. func impPath(imp string) string { if strings.HasPrefix(imp, "vendor/") { imp = "/" + imp } if i := strings.LastIndex(imp, "/vendor/"); i != -1 { imp = imp[i+len("/vendor/"):] } return imp } // ErrorInterface represent built-in error interface. var ErrorInterface = Interface{ Name: "error", Methods: []*Method{ { Name: "Error", Out: []*Parameter{ { Name: "", Type: PredeclaredType("string"), }, }, }, }, } golang-go.uber-mock-0.5.0/mockgen/model/model_test.go000066400000000000000000000014371470430142200224640ustar00rootroot00000000000000package model import ( "fmt" "testing" ) func TestImpPath(t *testing.T) { nonVendor := "github.com/foo/bar" if nonVendor != impPath(nonVendor) { t.Errorf("") } testCases := []struct { input string want string }{ {"foo/bar", "foo/bar"}, {"vendor/foo/bar", "foo/bar"}, {"vendor/foo/vendor/bar", "bar"}, {"/vendor/foo/bar", "foo/bar"}, {"qux/vendor/foo/bar", "foo/bar"}, {"qux/vendor/foo/vendor/bar", "bar"}, {"govendor/foo", "govendor/foo"}, {"foo/govendor/bar", "foo/govendor/bar"}, {"vendors/foo", "vendors/foo"}, {"foo/vendors/bar", "foo/vendors/bar"}, } for _, tc := range testCases { t.Run(fmt.Sprintf("input %s", tc.input), func(t *testing.T) { if got := impPath(tc.input); got != tc.want { t.Errorf("got %s; want %s", got, tc.want) } }) } } golang-go.uber-mock-0.5.0/mockgen/package_mode.go000066400000000000000000000224211470430142200216200ustar00rootroot00000000000000package main import ( "errors" "flag" "fmt" "go/types" "strings" "go.uber.org/mock/mockgen/model" "golang.org/x/tools/go/packages" ) var ( buildFlags = flag.String("build_flags", "", "(package mode) Additional flags for go build.") ) type packageModeParser struct { pkgName string } func (p *packageModeParser) parsePackage(packageName string, ifaces []string) (*model.Package, error) { p.pkgName = packageName pkg, err := p.loadPackage(packageName) if err != nil { return nil, fmt.Errorf("load package: %w", err) } interfaces, err := p.extractInterfacesFromPackage(pkg, ifaces) if err != nil { return nil, fmt.Errorf("extract interfaces from package: %w", err) } return &model.Package{ Name: pkg.Types.Name(), PkgPath: packageName, Interfaces: interfaces, }, nil } func (p *packageModeParser) loadPackage(packageName string) (*packages.Package, error) { var buildFlagsSet []string if *buildFlags != "" { buildFlagsSet = strings.Split(*buildFlags, " ") } cfg := &packages.Config{ Mode: packages.NeedDeps | packages.NeedImports | packages.NeedTypes | packages.NeedTypesInfo | packages.NeedEmbedFiles, BuildFlags: buildFlagsSet, } pkgs, err := packages.Load(cfg, packageName) if err != nil { return nil, fmt.Errorf("load packages: %w", err) } if len(pkgs) != 1 { return nil, fmt.Errorf("packages length must be 1: %d", len(pkgs)) } if len(pkgs[0].Errors) > 0 { errs := make([]error, len(pkgs[0].Errors)) for i, err := range pkgs[0].Errors { errs[i] = err } return nil, errors.Join(errs...) } return pkgs[0], nil } func (p *packageModeParser) extractInterfacesFromPackage(pkg *packages.Package, ifaces []string) ([]*model.Interface, error) { interfaces := make([]*model.Interface, len(ifaces)) for i, iface := range ifaces { obj := pkg.Types.Scope().Lookup(iface) if obj == nil { return nil, fmt.Errorf("interface %s does not exist", iface) } modelIface, err := p.parseInterface(obj) if err != nil { return nil, newParseTypeError("parse interface", obj.Name(), err) } interfaces[i] = modelIface } return interfaces, nil } func (p *packageModeParser) parseInterface(obj types.Object) (*model.Interface, error) { named, ok := types.Unalias(obj.Type()).(*types.Named) if !ok { return nil, fmt.Errorf("%s is not an interface. it is a %T", obj.Name(), obj.Type().Underlying()) } iface, ok := named.Underlying().(*types.Interface) if !ok { return nil, fmt.Errorf("%s is not an interface. it is a %T", obj.Name(), obj.Type().Underlying()) } if p.isConstraint(iface) { return nil, fmt.Errorf("interface %s is a constraint", obj.Name()) } methods := make([]*model.Method, iface.NumMethods()) for i := range iface.NumMethods() { method := iface.Method(i) typedMethod, ok := method.Type().(*types.Signature) if !ok { return nil, fmt.Errorf("method %s is not a signature", method.Name()) } modelFunc, err := p.parseFunc(typedMethod) if err != nil { return nil, newParseTypeError("parse method", typedMethod.String(), err) } methods[i] = &model.Method{ Name: method.Name(), In: modelFunc.In, Out: modelFunc.Out, Variadic: modelFunc.Variadic, } } if named.TypeParams() == nil { return &model.Interface{Name: obj.Name(), Methods: methods}, nil } typeParams := make([]*model.Parameter, named.TypeParams().Len()) for i := range named.TypeParams().Len() { param := named.TypeParams().At(i) typeParam, err := p.parseConstraint(param) if err != nil { return nil, newParseTypeError("parse type parameter", param.String(), err) } typeParams[i] = &model.Parameter{Name: param.Obj().Name(), Type: typeParam} } return &model.Interface{Name: obj.Name(), Methods: methods, TypeParams: typeParams}, nil } func (o *packageModeParser) isConstraint(t *types.Interface) bool { for i := range t.NumEmbeddeds() { embed := t.EmbeddedType(i) if _, ok := embed.Underlying().(*types.Interface); !ok { return true } } return false } func (p *packageModeParser) parseType(t types.Type) (model.Type, error) { switch t := t.(type) { case *types.Array: elementType, err := p.parseType(t.Elem()) if err != nil { return nil, newParseTypeError("parse array type", t.Elem().String(), err) } return &model.ArrayType{Len: int(t.Len()), Type: elementType}, nil case *types.Slice: elementType, err := p.parseType(t.Elem()) if err != nil { return nil, newParseTypeError("parse slice type", t.Elem().String(), err) } return &model.ArrayType{Len: -1, Type: elementType}, nil case *types.Chan: var dir model.ChanDir switch t.Dir() { case types.RecvOnly: dir = model.RecvDir case types.SendOnly: dir = model.SendDir } chanType, err := p.parseType(t.Elem()) if err != nil { return nil, newParseTypeError("parse chan type", t.Elem().String(), err) } return &model.ChanType{Dir: dir, Type: chanType}, nil case *types.Signature: sig, err := p.parseFunc(t) if err != nil { return nil, newParseTypeError("parse signature", t.String(), err) } return sig, nil case *types.Named, *types.Alias: object := t.(interface{ Obj() *types.TypeName }) var pkg string if object.Obj().Pkg() != nil { pkg = object.Obj().Pkg().Path() } // TypeArgs method not available for aliases in go1.22 genericType, ok := t.(interface{ TypeArgs() *types.TypeList }) if !ok || genericType.TypeArgs() == nil { return &model.NamedType{ Package: pkg, Type: object.Obj().Name(), }, nil } typeParams := &model.TypeParametersType{TypeParameters: make([]model.Type, genericType.TypeArgs().Len())} for i := range genericType.TypeArgs().Len() { typeParam := genericType.TypeArgs().At(i) typedParam, err := p.parseType(typeParam) if err != nil { return nil, newParseTypeError("parse type parameter", typeParam.String(), err) } typeParams.TypeParameters[i] = typedParam } return &model.NamedType{ Package: pkg, Type: object.Obj().Name(), TypeParams: typeParams, }, nil case *types.Interface: if t.Empty() { return model.PredeclaredType("any"), nil } return nil, fmt.Errorf("cannot handle non-empty unnamed interfaces") case *types.Map: key, err := p.parseType(t.Key()) if err != nil { return nil, newParseTypeError("parse map key", t.Key().String(), err) } value, err := p.parseType(t.Elem()) if err != nil { return nil, newParseTypeError("parse map value", t.Elem().String(), err) } return &model.MapType{Key: key, Value: value}, nil case *types.Pointer: valueType, err := p.parseType(t.Elem()) if err != nil { return nil, newParseTypeError("parse pointer type", t.Elem().String(), err) } return &model.PointerType{Type: valueType}, nil case *types.Struct: if t.NumFields() > 0 { return nil, fmt.Errorf("cannot handle non-empty unnamed structs") } return model.PredeclaredType("struct{}"), nil case *types.Basic: return model.PredeclaredType(t.Name()), nil case *types.Tuple: panic("tuple field") // TODO case *types.TypeParam: return &model.NamedType{Type: t.Obj().Name()}, nil default: panic("unknown type") // TODO } } func (p *packageModeParser) parseFunc(sig *types.Signature) (*model.FuncType, error) { var variadic *model.Parameter params := make([]*model.Parameter, 0, sig.Params().Len()) for i := range sig.Params().Len() { param := sig.Params().At(i) isVariadicParam := i == sig.Params().Len()-1 && sig.Variadic() parseType := param.Type() if isVariadicParam { sliceType, ok := param.Type().(*types.Slice) if !ok { return nil, newParseTypeError("variadic parameter is not a slice", param.String(), nil) } parseType = sliceType.Elem() } paramType, err := p.parseType(parseType) if err != nil { return nil, newParseTypeError("parse parameter type", parseType.String(), err) } modelParameter := &model.Parameter{Type: paramType, Name: param.Name()} if isVariadicParam { variadic = modelParameter } else { params = append(params, modelParameter) } } if len(params) == 0 { params = nil } results := make([]*model.Parameter, sig.Results().Len()) for i := range sig.Results().Len() { result := sig.Results().At(i) resultType, err := p.parseType(result.Type()) if err != nil { return nil, newParseTypeError("parse result type", result.Type().String(), err) } results[i] = &model.Parameter{Type: resultType, Name: result.Name()} } if len(results) == 0 { results = nil } return &model.FuncType{ In: params, Out: results, Variadic: variadic, }, nil } func (p *packageModeParser) parseConstraint(t *types.TypeParam) (model.Type, error) { if t == nil { return nil, fmt.Errorf("nil type param") } typeParam, err := p.parseType(t.Constraint()) if err != nil { return nil, newParseTypeError("parse constraint type", t.Constraint().String(), err) } return typeParam, nil } type parseTypeError struct { message string typeString string error error } func newParseTypeError(message string, typeString string, error error) *parseTypeError { return &parseTypeError{typeString: typeString, error: error, message: message} } func (p parseTypeError) Error() string { if p.error != nil { return fmt.Sprintf("%s: error parsing %s: %s", p.message, p.typeString, p.error) } return fmt.Sprintf("%s: error parsing type %s", p.message, p.typeString) } func (p parseTypeError) Unwrap() error { return p.error } golang-go.uber-mock-0.5.0/mockgen/package_mode_test.go000066400000000000000000000211331470430142200226560ustar00rootroot00000000000000package main import ( "testing" "github.com/stretchr/testify/assert" "go.uber.org/mock/mockgen/model" ) func Test_packageModeParser_parsePackage(t *testing.T) { type args struct { packageName string ifaces []string } tests := []struct { name string args args expected *model.Package expectedErr string }{ { name: "error: no found package", args: args{ packageName: "foo/bar/another_package", ifaces: []string{"Human"}, }, expectedErr: "load package: -: package foo/bar/another_package is not in std", }, { name: "error: interface does not exist", args: args{ packageName: "go.uber.org/mock/mockgen/internal/tests/package_mode", ifaces: []string{"Alien"}, }, expectedErr: "extract interfaces from package: interface Alien does not exist", }, { name: "error: search for struct instead of interface", args: args{ packageName: "go.uber.org/mock/mockgen/internal/tests/package_mode", ifaces: []string{"Work"}, }, expectedErr: "extract interfaces from package: parse interface: " + "error parsing Work: " + "Work is not an interface. it is a *types.Struct", }, { name: "error: search for constraint instead of interface", args: args{ packageName: "go.uber.org/mock/mockgen/internal/tests/package_mode", ifaces: []string{"Counter"}, }, expectedErr: "extract interfaces from package: parse interface: " + "error parsing Counter: " + "interface Counter is a constraint", }, { name: "success: simple interface", args: args{ packageName: "go.uber.org/mock/mockgen/internal/tests/package_mode", ifaces: []string{"Food"}, }, expected: &model.Package{ Name: "package_mode", PkgPath: "go.uber.org/mock/mockgen/internal/tests/package_mode", Interfaces: []*model.Interface{ { Name: "Food", Methods: []*model.Method{ { Name: "Calories", Out: []*model.Parameter{ {Type: model.PredeclaredType("int")}, }, }, }, }, }, }, }, { name: "success: interface with variadic args", args: args{ packageName: "go.uber.org/mock/mockgen/internal/tests/package_mode", ifaces: []string{"Eater"}, }, expected: &model.Package{ Name: "package_mode", PkgPath: "go.uber.org/mock/mockgen/internal/tests/package_mode", Interfaces: []*model.Interface{ { Name: "Eater", Methods: []*model.Method{ { Name: "Eat", Variadic: &model.Parameter{ Name: "foods", Type: &model.NamedType{ Package: "go.uber.org/mock/mockgen/internal/tests/package_mode", Type: "Food", }, }, }, }, }, }, }, }, { name: "success: interface with generic", args: args{ packageName: "go.uber.org/mock/mockgen/internal/tests/package_mode", ifaces: []string{"Car"}, }, expected: &model.Package{ Name: "package_mode", PkgPath: "go.uber.org/mock/mockgen/internal/tests/package_mode", Interfaces: []*model.Interface{ { Name: "Car", Methods: []*model.Method{ { Name: "Brand", Out: []*model.Parameter{ {Type: model.PredeclaredType("string")}, }, }, { Name: "FuelTank", Out: []*model.Parameter{ { Type: &model.NamedType{ Package: "go.uber.org/mock/mockgen/internal/tests/package_mode/cars", Type: "FuelTank", TypeParams: &model.TypeParametersType{ TypeParameters: []model.Type{ &model.NamedType{ Type: "FuelType", }, }, }, }, }, }, }, { Name: "Refuel", In: []*model.Parameter{ { Name: "fuel", Type: &model.NamedType{Type: "FuelType"}, }, { Name: "volume", Type: model.PredeclaredType("int"), }, }, Out: []*model.Parameter{ {Type: &model.NamedType{Type: "error"}}, }, }, }, TypeParams: []*model.Parameter{ { Name: "FuelType", Type: &model.NamedType{ Package: "go.uber.org/mock/mockgen/internal/tests/package_mode/fuel", Type: "Fuel", }, }, }, }, }, }, }, { name: "success: interface with embedded interfaces", args: args{ packageName: "go.uber.org/mock/mockgen/internal/tests/package_mode", ifaces: []string{"Animal"}, }, expected: &model.Package{ Name: "package_mode", PkgPath: "go.uber.org/mock/mockgen/internal/tests/package_mode", Interfaces: []*model.Interface{ { Name: "Animal", Methods: []*model.Method{ {Name: "Breathe"}, { Name: "Eat", Variadic: &model.Parameter{ Name: "foods", Type: &model.NamedType{ Package: "go.uber.org/mock/mockgen/internal/tests/package_mode", Type: "Food", }, }, }, { Name: "Sleep", In: []*model.Parameter{ { Name: "duration", Type: &model.NamedType{ Package: "time", Type: "Duration", }, }, }, }, }, }, }, }, }, { name: "success: subtype of interface", args: args{ packageName: "go.uber.org/mock/mockgen/internal/tests/package_mode", ifaces: []string{"Primate"}, }, expected: &model.Package{ Name: "package_mode", PkgPath: "go.uber.org/mock/mockgen/internal/tests/package_mode", Interfaces: []*model.Interface{ { Name: "Primate", Methods: []*model.Method{ {Name: "Breathe"}, { Name: "Eat", Variadic: &model.Parameter{ Name: "foods", Type: &model.NamedType{ Package: "go.uber.org/mock/mockgen/internal/tests/package_mode", Type: "Food", }, }, }, { Name: "Sleep", In: []*model.Parameter{ { Name: "duration", Type: &model.NamedType{ Package: "time", Type: "Duration", }, }, }, }, }, }, }, }, }, { name: "success: alias to interface", args: args{ packageName: "go.uber.org/mock/mockgen/internal/tests/package_mode", ifaces: []string{"Human"}, }, expected: &model.Package{ Name: "package_mode", PkgPath: "go.uber.org/mock/mockgen/internal/tests/package_mode", Interfaces: []*model.Interface{ { Name: "Human", Methods: []*model.Method{ {Name: "Breathe"}, { Name: "Eat", Variadic: &model.Parameter{ Name: "foods", Type: &model.NamedType{ Package: "go.uber.org/mock/mockgen/internal/tests/package_mode", Type: "Food", }, }, }, { Name: "Sleep", In: []*model.Parameter{ { Name: "duration", Type: &model.NamedType{ Package: "time", Type: "Duration", }, }, }, }, }, }, }, }, }, { name: "success: interfaces with aliases in params and returns", args: args{ packageName: "go.uber.org/mock/mockgen/internal/tests/package_mode", ifaces: []string{"Earth"}, }, expected: &model.Package{ Name: "package_mode", PkgPath: "go.uber.org/mock/mockgen/internal/tests/package_mode", Interfaces: []*model.Interface{ { Name: "Earth", Methods: []*model.Method{ { Name: "AddHumans", In: []*model.Parameter{ { Type: model.PredeclaredType("int"), }, }, Out: []*model.Parameter{ { Type: &model.ArrayType{ Len: -1, // slice Type: &model.NamedType{ Package: "go.uber.org/mock/mockgen/internal/tests/package_mode", Type: "Primate", }, }, }, }, }, { Name: "HumanPopulation", Out: []*model.Parameter{ { Type: model.PredeclaredType("int"), }, }, }, }, }, }, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { parser := packageModeParser{} actual, err := parser.parsePackage(tt.args.packageName, tt.args.ifaces) if tt.expectedErr != "" { assert.ErrorContains(t, err, tt.expectedErr) } else { assert.NoError(t, err) } assert.Equal(t, tt.expected, actual) }) } } golang-go.uber-mock-0.5.0/mockgen/parse.go000066400000000000000000000536151470430142200203440ustar00rootroot00000000000000// Copyright 2012 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package main // This file contains the model construction by parsing source files. import ( "errors" "fmt" "go/ast" "go/build" "go/importer" "go/parser" "go/token" "go/types" "log" "os" "path" "path/filepath" "strconv" "strings" "go.uber.org/mock/mockgen/model" ) // sourceMode generates mocks via source file. func sourceMode(source string) (*model.Package, error) { srcDir, err := filepath.Abs(filepath.Dir(source)) if err != nil { return nil, fmt.Errorf("failed getting source directory: %v", err) } packageImport, err := parsePackageImport(srcDir) if err != nil { return nil, err } fs := token.NewFileSet() file, err := parser.ParseFile(fs, source, nil, 0) if err != nil { return nil, fmt.Errorf("failed parsing source file %v: %v", source, err) } p := &fileParser{ fileSet: fs, imports: make(map[string]importedPackage), importedInterfaces: newInterfaceCache(), auxInterfaces: newInterfaceCache(), srcDir: srcDir, } // Handle -imports. dotImports := make(map[string]bool) if *imports != "" { for _, kv := range strings.Split(*imports, ",") { eq := strings.Index(kv, "=") k, v := kv[:eq], kv[eq+1:] if k == "." { dotImports[v] = true } else { p.imports[k] = importedPkg{path: v} } } } if *excludeInterfaces != "" { p.excludeNamesSet = parseExcludeInterfaces(*excludeInterfaces) } // Handle -aux_files. if err := p.parseAuxFiles(*auxFiles); err != nil { return nil, err } p.addAuxInterfacesFromFile(packageImport, file) // this file pkg, err := p.parseFile(packageImport, file) if err != nil { return nil, err } for pkgPath := range dotImports { pkg.DotImports = append(pkg.DotImports, pkgPath) } return pkg, nil } type importedPackage interface { Path() string Parser() *fileParser } type importedPkg struct { path string parser *fileParser } func (i importedPkg) Path() string { return i.path } func (i importedPkg) Parser() *fileParser { return i.parser } // duplicateImport is a bit of a misnomer. Currently the parser can't // handle cases of multi-file packages importing different packages // under the same name. Often these imports would not be problematic, // so this type lets us defer raising an error unless the package name // is actually used. type duplicateImport struct { name string duplicates []string } func (d duplicateImport) Error() string { return fmt.Sprintf("%q is ambiguous because of duplicate imports: %v", d.name, d.duplicates) } func (d duplicateImport) Path() string { log.Fatal(d.Error()); return "" } func (d duplicateImport) Parser() *fileParser { log.Fatal(d.Error()); return nil } type interfaceCache struct { m map[string]map[string]*namedInterface } func newInterfaceCache() *interfaceCache { return &interfaceCache{ m: make(map[string]map[string]*namedInterface), } } func (i *interfaceCache) Set(pkg, name string, it *namedInterface) { if _, ok := i.m[pkg]; !ok { i.m[pkg] = make(map[string]*namedInterface) } i.m[pkg][name] = it } func (i *interfaceCache) Get(pkg, name string) *namedInterface { if _, ok := i.m[pkg]; !ok { return nil } return i.m[pkg][name] } func (i *interfaceCache) GetASTIface(pkg, name string) *ast.InterfaceType { if _, ok := i.m[pkg]; !ok { return nil } it, ok := i.m[pkg][name] if !ok { return nil } return it.it } type fileParser struct { fileSet *token.FileSet imports map[string]importedPackage // package name => imported package importedInterfaces *interfaceCache auxFiles []*ast.File auxInterfaces *interfaceCache srcDir string excludeNamesSet map[string]struct{} } func (p *fileParser) errorf(pos token.Pos, format string, args ...any) error { ps := p.fileSet.Position(pos) format = "%s:%d:%d: " + format args = append([]any{ps.Filename, ps.Line, ps.Column}, args...) return fmt.Errorf(format, args...) } func (p *fileParser) parseAuxFiles(auxFiles string) error { auxFiles = strings.TrimSpace(auxFiles) if auxFiles == "" { return nil } for _, kv := range strings.Split(auxFiles, ",") { parts := strings.SplitN(kv, "=", 2) if len(parts) != 2 { return fmt.Errorf("bad aux file spec: %v", kv) } pkg, fpath := parts[0], parts[1] file, err := parser.ParseFile(p.fileSet, fpath, nil, 0) if err != nil { return err } p.auxFiles = append(p.auxFiles, file) p.addAuxInterfacesFromFile(pkg, file) } return nil } func (p *fileParser) addAuxInterfacesFromFile(pkg string, file *ast.File) { for ni := range iterInterfaces(file) { p.auxInterfaces.Set(pkg, ni.name.Name, ni) } } // parseFile loads all file imports and auxiliary files import into the // fileParser, parses all file interfaces and returns package model. func (p *fileParser) parseFile(importPath string, file *ast.File) (*model.Package, error) { allImports, dotImports := importsOfFile(file) // Don't stomp imports provided by -imports. Those should take precedence. for pkg, pkgI := range allImports { if _, ok := p.imports[pkg]; !ok { p.imports[pkg] = pkgI } } // Add imports from auxiliary files, which might be needed for embedded interfaces. // Don't stomp any other imports. for _, f := range p.auxFiles { auxImports, _ := importsOfFile(f) for pkg, pkgI := range auxImports { if _, ok := p.imports[pkg]; !ok { p.imports[pkg] = pkgI } } } var is []*model.Interface for ni := range iterInterfaces(file) { if _, ok := p.excludeNamesSet[ni.name.String()]; ok { continue } i, err := p.parseInterface(ni.name.String(), importPath, ni) if errors.Is(err, errConstraintInterface) { continue } if err != nil { return nil, err } is = append(is, i) } return &model.Package{ Name: file.Name.String(), PkgPath: importPath, Interfaces: is, DotImports: dotImports, }, nil } // parsePackage loads package specified by path, parses it and returns // a new fileParser with the parsed imports and interfaces. func (p *fileParser) parsePackage(path string) (*fileParser, error) { newP := &fileParser{ fileSet: token.NewFileSet(), imports: make(map[string]importedPackage), importedInterfaces: newInterfaceCache(), auxInterfaces: newInterfaceCache(), srcDir: p.srcDir, } var pkgs map[string]*ast.Package if imp, err := build.Import(path, newP.srcDir, build.FindOnly); err != nil { return nil, err } else if pkgs, err = parser.ParseDir(newP.fileSet, imp.Dir, nil, 0); err != nil { return nil, err } for _, pkg := range pkgs { file := ast.MergePackageFiles(pkg, ast.FilterFuncDuplicates|ast.FilterUnassociatedComments|ast.FilterImportDuplicates) for ni := range iterInterfaces(file) { newP.importedInterfaces.Set(path, ni.name.Name, ni) } imports, _ := importsOfFile(file) for pkgName, pkgI := range imports { newP.imports[pkgName] = pkgI } } return newP, nil } func (p *fileParser) constructInstParams(pkg string, params []*ast.Field, instParams []model.Type, embeddedInstParams []ast.Expr, tps map[string]model.Type) ([]model.Type, error) { pm := make(map[string]int) var i int for _, v := range params { for _, n := range v.Names { pm[n.Name] = i instParams = append(instParams, model.PredeclaredType(n.Name)) i++ } } var runtimeInstParams []model.Type for _, instParam := range embeddedInstParams { switch t := instParam.(type) { case *ast.Ident: if idx, ok := pm[t.Name]; ok { runtimeInstParams = append(runtimeInstParams, instParams[idx]) continue } } modelType, err := p.parseType(pkg, instParam, tps) if err != nil { return nil, err } runtimeInstParams = append(runtimeInstParams, modelType) } return runtimeInstParams, nil } func (p *fileParser) constructTps(it *namedInterface) (tps map[string]model.Type) { tps = make(map[string]model.Type) n := 0 for _, tp := range it.typeParams { for _, tm := range tp.Names { tps[tm.Name] = nil if len(it.instTypes) != 0 { tps[tm.Name] = it.instTypes[n] n++ } } } return tps } // parseInterface loads interface specified by pkg and name, parses it and returns // a new model with the parsed. func (p *fileParser) parseInterface(name, pkg string, it *namedInterface) (*model.Interface, error) { iface := &model.Interface{Name: name} tps := p.constructTps(it) tp, err := p.parseFieldList(pkg, it.typeParams, tps) if err != nil { return nil, fmt.Errorf("unable to parse interface type parameters: %v", name) } iface.TypeParams = tp for _, field := range it.it.Methods.List { var methods []*model.Method if methods, err = p.parseMethod(field, it, iface, pkg, tps); err != nil { return nil, err } for _, m := range methods { iface.AddMethod(m) } } return iface, nil } func (p *fileParser) parseMethod(field *ast.Field, it *namedInterface, iface *model.Interface, pkg string, tps map[string]model.Type) ([]*model.Method, error) { // {} for git diff { switch v := field.Type.(type) { case *ast.FuncType: if nn := len(field.Names); nn != 1 { return nil, fmt.Errorf("expected one name for interface %v, got %d", iface.Name, nn) } m := &model.Method{ Name: field.Names[0].String(), } var err error m.In, m.Variadic, m.Out, err = p.parseFunc(pkg, v, tps) if err != nil { return nil, err } return []*model.Method{m}, nil case *ast.Ident: // Embedded interface in this package. embeddedIfaceType := p.auxInterfaces.Get(pkg, v.String()) if embeddedIfaceType == nil { embeddedIfaceType = p.importedInterfaces.Get(pkg, v.String()) } var embeddedIface *model.Interface if embeddedIfaceType != nil { var err error embeddedIfaceType.instTypes, err = p.constructInstParams(pkg, it.typeParams, it.instTypes, it.embeddedInstTypeParams, tps) if err != nil { return nil, err } embeddedIface, err = p.parseInterface(v.String(), pkg, embeddedIfaceType) if err != nil { return nil, err } } else { // This is built-in error interface. if v.String() == model.ErrorInterface.Name { embeddedIface = &model.ErrorInterface } else { ip, err := p.parsePackage(pkg) if err != nil { return nil, p.errorf(v.Pos(), "could not parse package %s: %v", pkg, err) } if embeddedIfaceType = ip.importedInterfaces.Get(pkg, v.String()); embeddedIfaceType == nil { return nil, p.errorf(v.Pos(), "unknown embedded interface %s.%s", pkg, v.String()) } embeddedIfaceType.instTypes, err = p.constructInstParams(pkg, it.typeParams, it.instTypes, it.embeddedInstTypeParams, tps) if err != nil { return nil, err } embeddedIface, err = ip.parseInterface(v.String(), pkg, embeddedIfaceType) if err != nil { return nil, err } } } return embeddedIface.Methods, nil case *ast.SelectorExpr: // Embedded interface in another package. filePkg, sel := v.X.(*ast.Ident).String(), v.Sel.String() embeddedPkg, ok := p.imports[filePkg] if !ok { return nil, p.errorf(v.X.Pos(), "unknown package %s", filePkg) } var embeddedIface *model.Interface var err error embeddedIfaceType := p.auxInterfaces.Get(filePkg, sel) if embeddedIfaceType != nil { embeddedIfaceType.instTypes, err = p.constructInstParams(pkg, it.typeParams, it.instTypes, it.embeddedInstTypeParams, tps) if err != nil { return nil, err } embeddedIface, err = p.parseInterface(sel, filePkg, embeddedIfaceType) if err != nil { return nil, err } } else { path := embeddedPkg.Path() parser := embeddedPkg.Parser() if parser == nil { ip, err := p.parsePackage(path) if err != nil { return nil, p.errorf(v.Pos(), "could not parse package %s: %v", path, err) } parser = ip p.imports[filePkg] = importedPkg{ path: embeddedPkg.Path(), parser: parser, } } if embeddedIfaceType = parser.importedInterfaces.Get(path, sel); embeddedIfaceType == nil { return nil, p.errorf(v.Pos(), "unknown embedded interface %s.%s", path, sel) } embeddedIfaceType.instTypes, err = p.constructInstParams(pkg, it.typeParams, it.instTypes, it.embeddedInstTypeParams, tps) if err != nil { return nil, err } embeddedIface, err = parser.parseInterface(sel, path, embeddedIfaceType) if err != nil { return nil, err } } // TODO: apply shadowing rules. return embeddedIface.Methods, nil default: return p.parseGenericMethod(field, it, iface, pkg, tps) } } } func (p *fileParser) parseFunc(pkg string, f *ast.FuncType, tps map[string]model.Type) (inParam []*model.Parameter, variadic *model.Parameter, outParam []*model.Parameter, err error) { if f.Params != nil { regParams := f.Params.List if isVariadic(f) { n := len(regParams) varParams := regParams[n-1:] regParams = regParams[:n-1] vp, err := p.parseFieldList(pkg, varParams, tps) if err != nil { return nil, nil, nil, p.errorf(varParams[0].Pos(), "failed parsing variadic argument: %v", err) } variadic = vp[0] } inParam, err = p.parseFieldList(pkg, regParams, tps) if err != nil { return nil, nil, nil, p.errorf(f.Pos(), "failed parsing arguments: %v", err) } } if f.Results != nil { outParam, err = p.parseFieldList(pkg, f.Results.List, tps) if err != nil { return nil, nil, nil, p.errorf(f.Pos(), "failed parsing returns: %v", err) } } return } func (p *fileParser) parseFieldList(pkg string, fields []*ast.Field, tps map[string]model.Type) ([]*model.Parameter, error) { nf := 0 for _, f := range fields { nn := len(f.Names) if nn == 0 { nn = 1 // anonymous parameter } nf += nn } if nf == 0 { return nil, nil } ps := make([]*model.Parameter, nf) i := 0 // destination index for _, f := range fields { t, err := p.parseType(pkg, f.Type, tps) if err != nil { return nil, err } if len(f.Names) == 0 { // anonymous arg ps[i] = &model.Parameter{Type: t} i++ continue } for _, name := range f.Names { ps[i] = &model.Parameter{Name: name.Name, Type: t} i++ } } return ps, nil } func (p *fileParser) parseType(pkg string, typ ast.Expr, tps map[string]model.Type) (model.Type, error) { switch v := typ.(type) { case *ast.ArrayType: ln := -1 if v.Len != nil { value, err := p.parseArrayLength(v.Len) if err != nil { return nil, err } ln, err = strconv.Atoi(value) if err != nil { return nil, p.errorf(v.Len.Pos(), "bad array size: %v", err) } } t, err := p.parseType(pkg, v.Elt, tps) if err != nil { return nil, err } return &model.ArrayType{Len: ln, Type: t}, nil case *ast.ChanType: t, err := p.parseType(pkg, v.Value, tps) if err != nil { return nil, err } var dir model.ChanDir if v.Dir == ast.SEND { dir = model.SendDir } if v.Dir == ast.RECV { dir = model.RecvDir } return &model.ChanType{Dir: dir, Type: t}, nil case *ast.Ellipsis: // assume we're parsing a variadic argument return p.parseType(pkg, v.Elt, tps) case *ast.FuncType: in, variadic, out, err := p.parseFunc(pkg, v, tps) if err != nil { return nil, err } return &model.FuncType{In: in, Out: out, Variadic: variadic}, nil case *ast.Ident: it, ok := tps[v.Name] if v.IsExported() && !ok { // `pkg` may be an aliased imported pkg // if so, patch the import w/ the fully qualified import maybeImportedPkg, ok := p.imports[pkg] if ok { pkg = maybeImportedPkg.Path() } // assume type in this package return &model.NamedType{Package: pkg, Type: v.Name}, nil } if ok && it != nil { return it, nil } // assume predeclared type return model.PredeclaredType(v.Name), nil case *ast.InterfaceType: if v.Methods != nil && len(v.Methods.List) > 0 { return nil, p.errorf(v.Pos(), "can't handle non-empty unnamed interface types") } return model.PredeclaredType("any"), nil case *ast.MapType: key, err := p.parseType(pkg, v.Key, tps) if err != nil { return nil, err } value, err := p.parseType(pkg, v.Value, tps) if err != nil { return nil, err } return &model.MapType{Key: key, Value: value}, nil case *ast.SelectorExpr: pkgName := v.X.(*ast.Ident).String() pkg, ok := p.imports[pkgName] if !ok { return nil, p.errorf(v.Pos(), "unknown package %q", pkgName) } return &model.NamedType{Package: pkg.Path(), Type: v.Sel.String()}, nil case *ast.StarExpr: t, err := p.parseType(pkg, v.X, tps) if err != nil { return nil, err } return &model.PointerType{Type: t}, nil case *ast.StructType: if v.Fields != nil && len(v.Fields.List) > 0 { return nil, p.errorf(v.Pos(), "can't handle non-empty unnamed struct types") } return model.PredeclaredType("struct{}"), nil case *ast.ParenExpr: return p.parseType(pkg, v.X, tps) default: mt, err := p.parseGenericType(pkg, typ, tps) if err != nil { return nil, err } if mt == nil { break } return mt, nil } return nil, fmt.Errorf("don't know how to parse type %T", typ) } func (p *fileParser) parseArrayLength(expr ast.Expr) (string, error) { switch val := expr.(type) { case (*ast.BasicLit): return val.Value, nil case (*ast.Ident): // when the length is a const defined locally return val.Obj.Decl.(*ast.ValueSpec).Values[0].(*ast.BasicLit).Value, nil case (*ast.SelectorExpr): // when the length is a const defined in an external package usedPkg, err := importer.Default().Import(fmt.Sprintf("%s", val.X)) if err != nil { return "", p.errorf(expr.Pos(), "unknown package in array length: %v", err) } ev, err := types.Eval(token.NewFileSet(), usedPkg, token.NoPos, val.Sel.Name) if err != nil { return "", p.errorf(expr.Pos(), "unknown constant in array length: %v", err) } return ev.Value.String(), nil case (*ast.ParenExpr): return p.parseArrayLength(val.X) case (*ast.BinaryExpr): x, err := p.parseArrayLength(val.X) if err != nil { return "", err } y, err := p.parseArrayLength(val.Y) if err != nil { return "", err } biExpr := fmt.Sprintf("%s%v%s", x, val.Op, y) tv, err := types.Eval(token.NewFileSet(), nil, token.NoPos, biExpr) if err != nil { return "", p.errorf(expr.Pos(), "invalid expression in array length: %v", err) } return tv.Value.String(), nil default: return "", p.errorf(expr.Pos(), "invalid expression in array length: %v", val) } } // importsOfFile returns a map of package name to import path // of the imports in file. func importsOfFile(file *ast.File) (normalImports map[string]importedPackage, dotImports []string) { var importPaths []string for _, is := range file.Imports { if is.Name != nil { continue } importPath := is.Path.Value[1 : len(is.Path.Value)-1] // remove quotes importPaths = append(importPaths, importPath) } packagesName := createPackageMap(importPaths) normalImports = make(map[string]importedPackage) dotImports = make([]string, 0) for _, is := range file.Imports { var pkgName string importPath := is.Path.Value[1 : len(is.Path.Value)-1] // remove quotes if is.Name != nil { // Named imports are always certain. if is.Name.Name == "_" { continue } pkgName = is.Name.Name } else { pkg, ok := packagesName[importPath] if !ok { // Fallback to import path suffix. Note that this is uncertain. _, last := path.Split(importPath) // If the last path component has dots, the first dot-delimited // field is used as the name. pkgName = strings.SplitN(last, ".", 2)[0] } else { pkgName = pkg } } if pkgName == "." { dotImports = append(dotImports, importPath) } else { if pkg, ok := normalImports[pkgName]; ok { switch p := pkg.(type) { case duplicateImport: normalImports[pkgName] = duplicateImport{ name: p.name, duplicates: append([]string{importPath}, p.duplicates...), } case importedPkg: normalImports[pkgName] = duplicateImport{ name: pkgName, duplicates: []string{p.path, importPath}, } } } else { normalImports[pkgName] = importedPkg{path: importPath} } } } return } type namedInterface struct { name *ast.Ident it *ast.InterfaceType typeParams []*ast.Field embeddedInstTypeParams []ast.Expr instTypes []model.Type } // Create an iterator over all interfaces in file. func iterInterfaces(file *ast.File) <-chan *namedInterface { ch := make(chan *namedInterface) go func() { for _, decl := range file.Decls { gd, ok := decl.(*ast.GenDecl) if !ok || gd.Tok != token.TYPE { continue } for _, spec := range gd.Specs { ts, ok := spec.(*ast.TypeSpec) if !ok { continue } it, ok := ts.Type.(*ast.InterfaceType) if !ok { continue } ch <- &namedInterface{name: ts.Name, it: it, typeParams: getTypeSpecTypeParams(ts)} } } close(ch) }() return ch } // isVariadic returns whether the function is variadic. func isVariadic(f *ast.FuncType) bool { nargs := len(f.Params.List) if nargs == 0 { return false } _, ok := f.Params.List[nargs-1].Type.(*ast.Ellipsis) return ok } // packageNameOfDir get package import path via dir func packageNameOfDir(srcDir string) (string, error) { files, err := os.ReadDir(srcDir) if err != nil { log.Fatal(err) } var goFilePath string for _, file := range files { if !file.IsDir() && strings.HasSuffix(file.Name(), ".go") { goFilePath = file.Name() break } } if goFilePath == "" { return "", fmt.Errorf("go source file not found %s", srcDir) } packageImport, err := parsePackageImport(srcDir) if err != nil { return "", err } return packageImport, nil } var errOutsideGoPath = errors.New("source directory is outside GOPATH") golang-go.uber-mock-0.5.0/mockgen/parse_test.go000066400000000000000000000101701470430142200213700ustar00rootroot00000000000000package main import ( "go/parser" "go/token" "testing" ) func TestFileParser_ParseFile(t *testing.T) { fs := token.NewFileSet() file, err := parser.ParseFile(fs, "internal/tests/custom_package_name/greeter/greeter.go", nil, 0) if err != nil { t.Fatalf("Unexpected error: %v", err) } p := fileParser{ fileSet: fs, imports: make(map[string]importedPackage), importedInterfaces: newInterfaceCache(), } pkg, err := p.parseFile("", file) if err != nil { t.Fatalf("Unexpected error: %v", err) } checkGreeterImports(t, p.imports) expectedName := "greeter" if pkg.Name != expectedName { t.Fatalf("Expected name to be %v but got %v", expectedName, pkg.Name) } expectedInterfaceName := "InputMaker" if pkg.Interfaces[0].Name != expectedInterfaceName { t.Fatalf("Expected interface name to be %v but got %v", expectedInterfaceName, pkg.Interfaces[0].Name) } } func TestFileParser_ParsePackage(t *testing.T) { fs := token.NewFileSet() _, err := parser.ParseFile(fs, "internal/tests/custom_package_name/greeter/greeter.go", nil, 0) if err != nil { t.Fatalf("Unexpected error: %v", err) } p := fileParser{ fileSet: fs, imports: make(map[string]importedPackage), importedInterfaces: newInterfaceCache(), } newP, err := p.parsePackage("go.uber.org/mock/mockgen/internal/tests/custom_package_name/greeter") if err != nil { t.Fatalf("Unexpected error: %v", err) } checkGreeterImports(t, newP.imports) } func TestImportsOfFile(t *testing.T) { fs := token.NewFileSet() file, err := parser.ParseFile(fs, "internal/tests/custom_package_name/greeter/greeter.go", nil, 0) if err != nil { t.Fatalf("Unexpected error: %v", err) } imports, _ := importsOfFile(file) checkGreeterImports(t, imports) } func checkGreeterImports(t *testing.T, imports map[string]importedPackage) { // check that imports have stdlib package "fmt" if fmtPackage, ok := imports["fmt"]; !ok { t.Errorf("Expected imports to have key \"fmt\"") } else { expectedFmtPackage := "fmt" if fmtPackage.Path() != expectedFmtPackage { t.Errorf("Expected fmt key to have value %s but got %s", expectedFmtPackage, fmtPackage.Path()) } } // check that imports have package named "validator" if validatorPackage, ok := imports["validator"]; !ok { t.Errorf("Expected imports to have key \"fmt\"") } else { expectedValidatorPackage := "go.uber.org/mock/mockgen/internal/tests/custom_package_name/validator" if validatorPackage.Path() != expectedValidatorPackage { t.Errorf("Expected validator key to have value %s but got %s", expectedValidatorPackage, validatorPackage.Path()) } } // check that imports have package named "client" if clientPackage, ok := imports["client"]; !ok { t.Errorf("Expected imports to have key \"client\"") } else { expectedClientPackage := "go.uber.org/mock/mockgen/internal/tests/custom_package_name/client/v1" if clientPackage.Path() != expectedClientPackage { t.Errorf("Expected client key to have value %s but got %s", expectedClientPackage, clientPackage.Path()) } } // check that imports don't have package named "v1" if _, ok := imports["v1"]; ok { t.Errorf("Expected import not to have key \"v1\"") } } func Benchmark_parseFile(b *testing.B) { source := "internal/tests/performance/big_interface/big_interface.go" for n := 0; n < b.N; n++ { sourceMode(source) } } func TestParseArrayWithConstLength(t *testing.T) { fs := token.NewFileSet() srcDir := "internal/tests/const_array_length/input.go" file, err := parser.ParseFile(fs, srcDir, nil, 0) if err != nil { t.Fatalf("Unexpected error: %v", err) } p := fileParser{ fileSet: fs, imports: make(map[string]importedPackage), importedInterfaces: newInterfaceCache(), auxInterfaces: newInterfaceCache(), srcDir: srcDir, } pkg, err := p.parseFile("", file) if err != nil { t.Fatalf("Unexpected error: %v", err) } expects := []string{"[2]int", "[2]int", "[127]int", "[3]int", "[3]int", "[7]int"} for i, e := range expects { got := pkg.Interfaces[0].Methods[i].Out[0].Type.String(nil, "") if got != e { t.Fatalf("got %v; expected %v", got, e) } } } golang-go.uber-mock-0.5.0/mockgen/version.go000066400000000000000000000016451470430142200207130ustar00rootroot00000000000000// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package main import ( "fmt" "log" "runtime/debug" ) func printModuleVersion() { if bi, exists := debug.ReadBuildInfo(); exists { fmt.Println(bi.Main.Version) } else { log.Printf("No version information found. Make sure to use " + "GO111MODULE=on when running 'go get' in order to use specific " + "version of the binary.") } } golang-go.uber-mock-0.5.0/sample/000077500000000000000000000000001470430142200165275ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/sample/README.md000066400000000000000000000012731470430142200200110ustar00rootroot00000000000000# Samples This directory contains an example of a package containing a non-trivial interface that can be mocked with GoMock. The interesting files are: * `user.go`: Source code for the sample package, containing interfaces to be mocked. This file depends on the packages named imp[1-4] for various things. * `user_test.go`: A test for the sample package, in which mocks of the interfaces from `user.go` are used. This demonstrates how to create mock objects, set up expectations, and so on. * `mock_user_test.go`: The generated mock code. See ../gomock/matchers.go for the `go:generate` command used to generate it. To run the test, ```bash go test go.uber.org/mock/sample ``` golang-go.uber-mock-0.5.0/sample/concurrent/000077500000000000000000000000001470430142200207115ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/sample/concurrent/README.md000066400000000000000000000002471470430142200221730ustar00rootroot00000000000000# Concurrent This directory contains an example of executing mock calls concurrently. To run the test, ```bash go test -race go.uber.org/mock/sample/concurrent ``` golang-go.uber-mock-0.5.0/sample/concurrent/concurrent.go000066400000000000000000000003511470430142200234210ustar00rootroot00000000000000// Package concurrent demonstrates how to use gomock with goroutines. package concurrent //go:generate mockgen -destination mock/concurrent_mock.go go.uber.org/mock/sample/concurrent Math type Math interface { Sum(a, b int) int } golang-go.uber-mock-0.5.0/sample/concurrent/concurrent_test.go000066400000000000000000000037601470430142200244670ustar00rootroot00000000000000package concurrent import ( "context" "fmt" "testing" "time" "go.uber.org/mock/gomock" mock "go.uber.org/mock/sample/concurrent/mock" ) func call(ctx context.Context, m Math) (int, error) { result := make(chan int) go func() { result <- m.Sum(1, 2) close(result) }() select { case r := <-result: return r, nil case <-ctx.Done(): return 0, ctx.Err() } } func waitForMocks(ctx context.Context, ctrl *gomock.Controller) error { ticker := time.NewTicker(1 * time.Millisecond) defer ticker.Stop() timeout := time.After(3 * time.Millisecond) for { select { case <-ticker.C: if ctrl.Satisfied() { return nil } case <-timeout: return fmt.Errorf("timeout waiting for mocks to be satisfied") case <-ctx.Done(): return fmt.Errorf("context cancelled") } } } // TestConcurrentFails is expected to fail (and is disabled). It // demonstrates how to use gomock.WithContext to interrupt the test // from a different goroutine. func TestConcurrentFails(t *testing.T) { t.Skip("Test is expected to fail, remove skip to trying running yourself.") ctrl, ctx := gomock.WithContext(context.Background(), t) m := mock.NewMockMath(ctrl) if _, err := call(ctx, m); err != nil { t.Error("call failed:", err) } } func TestConcurrentWorks(t *testing.T) { ctrl, ctx := gomock.WithContext(context.Background(), t) m := mock.NewMockMath(ctrl) m.EXPECT().Sum(1, 2).Return(3) if _, err := call(ctx, m); err != nil { t.Error("call failed:", err) } } func TestCancelWhenMocksSatisfied(t *testing.T) { ctrl, ctx := gomock.WithContext(context.Background(), t) m := mock.NewMockMath(ctrl) m.EXPECT().Sum(1, 2).Return(3).MinTimes(1) // This goroutine calls the mock and then waits for the context to be done. go func() { for { m.Sum(1, 2) select { case <-ctx.Done(): return } } }() // waitForMocks spawns another goroutine which blocks until ctrl.Satisfied() is true. if err := waitForMocks(ctx, ctrl); err != nil { t.Error("call failed:", err) } ctrl.Finish() } golang-go.uber-mock-0.5.0/sample/concurrent/mock/000077500000000000000000000000001470430142200216425ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/sample/concurrent/mock/concurrent_mock.go000066400000000000000000000025471470430142200253740ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: go.uber.org/mock/sample/concurrent (interfaces: Math) // // Generated by this command: // // mockgen -destination mock/concurrent_mock.go go.uber.org/mock/sample/concurrent Math // // Package mock_concurrent is a generated GoMock package. package mock_concurrent import ( reflect "reflect" gomock "go.uber.org/mock/gomock" ) // MockMath is a mock of Math interface. type MockMath struct { ctrl *gomock.Controller recorder *MockMathMockRecorder isgomock struct{} } // MockMathMockRecorder is the mock recorder for MockMath. type MockMathMockRecorder struct { mock *MockMath } // NewMockMath creates a new mock instance. func NewMockMath(ctrl *gomock.Controller) *MockMath { mock := &MockMath{ctrl: ctrl} mock.recorder = &MockMathMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockMath) EXPECT() *MockMathMockRecorder { return m.recorder } // Sum mocks base method. func (m *MockMath) Sum(a, b int) int { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Sum", a, b) ret0, _ := ret[0].(int) return ret0 } // Sum indicates an expected call of Sum. func (mr *MockMathMockRecorder) Sum(a, b any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Sum", reflect.TypeOf((*MockMath)(nil).Sum), a, b) } golang-go.uber-mock-0.5.0/sample/imp1/000077500000000000000000000000001470430142200173755ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/sample/imp1/imp1.go000066400000000000000000000006411470430142200205730ustar00rootroot00000000000000package imp1 import "bufio" type Imp1 struct{} type ImpT int type ForeignEmbedded interface { // The return value here also makes sure that // the generated mock picks up the "bufio" import. ForeignEmbeddedMethod() *bufio.Reader // This method uses a type in this package, // which should be qualified when this interface is embedded. ImplicitPackage(s string, t ImpT, st []ImpT, pt *ImpT, ct chan ImpT) } golang-go.uber-mock-0.5.0/sample/imp2/000077500000000000000000000000001470430142200173765ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/sample/imp2/imp2.go000066400000000000000000000000411470430142200205670ustar00rootroot00000000000000package imp2 type Imp2 struct{} golang-go.uber-mock-0.5.0/sample/imp3/000077500000000000000000000000001470430142200173775ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/sample/imp3/imp3.go000066400000000000000000000000411470430142200205710ustar00rootroot00000000000000package imp3 type Imp3 struct{} golang-go.uber-mock-0.5.0/sample/imp4/000077500000000000000000000000001470430142200174005ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/sample/imp4/imp4.go000066400000000000000000000000651470430142200206010ustar00rootroot00000000000000package imp_four type Imp4 struct { Field string } golang-go.uber-mock-0.5.0/sample/mock_user_test.go000066400000000000000000000333201470430142200221050ustar00rootroot00000000000000// Code generated by MockGen. DO NOT EDIT. // Source: go.uber.org/mock/sample (interfaces: Index,Embed,Embedded) // // Generated by this command: // // mockgen -destination mock_user_test.go -package user_test go.uber.org/mock/sample Index,Embed,Embedded // // Package user_test is a generated GoMock package. package user_test import ( bufio "bufio" bytes "bytes" hash "hash" template "html/template" io "io" http "net/http" reflect "reflect" template0 "text/template" gomock "go.uber.org/mock/gomock" imp1 "go.uber.org/mock/sample/imp1" imp2 "go.uber.org/mock/sample/imp2" imp3 "go.uber.org/mock/sample/imp3" imp_four "go.uber.org/mock/sample/imp4" ) // MockIndex is a mock of Index interface. type MockIndex struct { ctrl *gomock.Controller recorder *MockIndexMockRecorder isgomock struct{} } // MockIndexMockRecorder is the mock recorder for MockIndex. type MockIndexMockRecorder struct { mock *MockIndex } // NewMockIndex creates a new mock instance. func NewMockIndex(ctrl *gomock.Controller) *MockIndex { mock := &MockIndex{ctrl: ctrl} mock.recorder = &MockIndexMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockIndex) EXPECT() *MockIndexMockRecorder { return m.recorder } // Anon mocks base method. func (m *MockIndex) Anon(arg0 string) { m.ctrl.T.Helper() m.ctrl.Call(m, "Anon", arg0) } // Anon indicates an expected call of Anon. func (mr *MockIndexMockRecorder) Anon(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Anon", reflect.TypeOf((*MockIndex)(nil).Anon), arg0) } // Chan mocks base method. func (m *MockIndex) Chan(a chan int, b chan<- hash.Hash) { m.ctrl.T.Helper() m.ctrl.Call(m, "Chan", a, b) } // Chan indicates an expected call of Chan. func (mr *MockIndexMockRecorder) Chan(a, b any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Chan", reflect.TypeOf((*MockIndex)(nil).Chan), a, b) } // ConcreteRet mocks base method. func (m *MockIndex) ConcreteRet() chan<- bool { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ConcreteRet") ret0, _ := ret[0].(chan<- bool) return ret0 } // ConcreteRet indicates an expected call of ConcreteRet. func (mr *MockIndexMockRecorder) ConcreteRet() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConcreteRet", reflect.TypeOf((*MockIndex)(nil).ConcreteRet)) } // Ellip mocks base method. func (m *MockIndex) Ellip(fmt string, args ...any) { m.ctrl.T.Helper() varargs := []any{fmt} for _, a := range args { varargs = append(varargs, a) } m.ctrl.Call(m, "Ellip", varargs...) } // Ellip indicates an expected call of Ellip. func (mr *MockIndexMockRecorder) Ellip(fmt any, args ...any) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]any{fmt}, args...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Ellip", reflect.TypeOf((*MockIndex)(nil).Ellip), varargs...) } // EllipOnly mocks base method. func (m *MockIndex) EllipOnly(arg0 ...string) { m.ctrl.T.Helper() varargs := []any{} for _, a := range arg0 { varargs = append(varargs, a) } m.ctrl.Call(m, "EllipOnly", varargs...) } // EllipOnly indicates an expected call of EllipOnly. func (mr *MockIndexMockRecorder) EllipOnly(arg0 ...any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EllipOnly", reflect.TypeOf((*MockIndex)(nil).EllipOnly), arg0...) } // ForeignFour mocks base method. func (m *MockIndex) ForeignFour(arg0 imp_four.Imp4) { m.ctrl.T.Helper() m.ctrl.Call(m, "ForeignFour", arg0) } // ForeignFour indicates an expected call of ForeignFour. func (mr *MockIndexMockRecorder) ForeignFour(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ForeignFour", reflect.TypeOf((*MockIndex)(nil).ForeignFour), arg0) } // ForeignOne mocks base method. func (m *MockIndex) ForeignOne(arg0 imp1.Imp1) { m.ctrl.T.Helper() m.ctrl.Call(m, "ForeignOne", arg0) } // ForeignOne indicates an expected call of ForeignOne. func (mr *MockIndexMockRecorder) ForeignOne(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ForeignOne", reflect.TypeOf((*MockIndex)(nil).ForeignOne), arg0) } // ForeignThree mocks base method. func (m *MockIndex) ForeignThree(arg0 imp3.Imp3) { m.ctrl.T.Helper() m.ctrl.Call(m, "ForeignThree", arg0) } // ForeignThree indicates an expected call of ForeignThree. func (mr *MockIndexMockRecorder) ForeignThree(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ForeignThree", reflect.TypeOf((*MockIndex)(nil).ForeignThree), arg0) } // ForeignTwo mocks base method. func (m *MockIndex) ForeignTwo(arg0 imp2.Imp2) { m.ctrl.T.Helper() m.ctrl.Call(m, "ForeignTwo", arg0) } // ForeignTwo indicates an expected call of ForeignTwo. func (mr *MockIndexMockRecorder) ForeignTwo(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ForeignTwo", reflect.TypeOf((*MockIndex)(nil).ForeignTwo), arg0) } // Func mocks base method. func (m *MockIndex) Func(f func(http.Request) (int, bool)) { m.ctrl.T.Helper() m.ctrl.Call(m, "Func", f) } // Func indicates an expected call of Func. func (mr *MockIndexMockRecorder) Func(f any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Func", reflect.TypeOf((*MockIndex)(nil).Func), f) } // Get mocks base method. func (m *MockIndex) Get(key string) any { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Get", key) ret0, _ := ret[0].(any) return ret0 } // Get indicates an expected call of Get. func (mr *MockIndexMockRecorder) Get(key any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockIndex)(nil).Get), key) } // GetTwo mocks base method. func (m *MockIndex) GetTwo(key1, key2 string) (any, any) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetTwo", key1, key2) ret0, _ := ret[0].(any) ret1, _ := ret[1].(any) return ret0, ret1 } // GetTwo indicates an expected call of GetTwo. func (mr *MockIndexMockRecorder) GetTwo(key1, key2 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTwo", reflect.TypeOf((*MockIndex)(nil).GetTwo), key1, key2) } // Map mocks base method. func (m *MockIndex) Map(a map[int]hash.Hash) { m.ctrl.T.Helper() m.ctrl.Call(m, "Map", a) } // Map indicates an expected call of Map. func (mr *MockIndexMockRecorder) Map(a any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Map", reflect.TypeOf((*MockIndex)(nil).Map), a) } // NillableRet mocks base method. func (m *MockIndex) NillableRet() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "NillableRet") ret0, _ := ret[0].(error) return ret0 } // NillableRet indicates an expected call of NillableRet. func (mr *MockIndexMockRecorder) NillableRet() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NillableRet", reflect.TypeOf((*MockIndex)(nil).NillableRet)) } // Other mocks base method. func (m *MockIndex) Other() hash.Hash { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Other") ret0, _ := ret[0].(hash.Hash) return ret0 } // Other indicates an expected call of Other. func (mr *MockIndexMockRecorder) Other() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Other", reflect.TypeOf((*MockIndex)(nil).Other)) } // Ptr mocks base method. func (m *MockIndex) Ptr(arg *int) { m.ctrl.T.Helper() m.ctrl.Call(m, "Ptr", arg) } // Ptr indicates an expected call of Ptr. func (mr *MockIndexMockRecorder) Ptr(arg any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Ptr", reflect.TypeOf((*MockIndex)(nil).Ptr), arg) } // Put mocks base method. func (m *MockIndex) Put(key string, value any) { m.ctrl.T.Helper() m.ctrl.Call(m, "Put", key, value) } // Put indicates an expected call of Put. func (mr *MockIndexMockRecorder) Put(key, value any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Put", reflect.TypeOf((*MockIndex)(nil).Put), key, value) } // Slice mocks base method. func (m *MockIndex) Slice(a []int, b []byte) [3]int { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Slice", a, b) ret0, _ := ret[0].([3]int) return ret0 } // Slice indicates an expected call of Slice. func (mr *MockIndexMockRecorder) Slice(a, b any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Slice", reflect.TypeOf((*MockIndex)(nil).Slice), a, b) } // Struct mocks base method. func (m *MockIndex) Struct(a struct{}) { m.ctrl.T.Helper() m.ctrl.Call(m, "Struct", a) } // Struct indicates an expected call of Struct. func (mr *MockIndexMockRecorder) Struct(a any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Struct", reflect.TypeOf((*MockIndex)(nil).Struct), a) } // StructChan mocks base method. func (m *MockIndex) StructChan(a chan struct{}) { m.ctrl.T.Helper() m.ctrl.Call(m, "StructChan", a) } // StructChan indicates an expected call of StructChan. func (mr *MockIndexMockRecorder) StructChan(a any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StructChan", reflect.TypeOf((*MockIndex)(nil).StructChan), a) } // Summary mocks base method. func (m *MockIndex) Summary(buf *bytes.Buffer, w io.Writer) { m.ctrl.T.Helper() m.ctrl.Call(m, "Summary", buf, w) } // Summary indicates an expected call of Summary. func (mr *MockIndexMockRecorder) Summary(buf, w any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Summary", reflect.TypeOf((*MockIndex)(nil).Summary), buf, w) } // Templates mocks base method. func (m *MockIndex) Templates(a template.CSS, b template0.FuncMap) { m.ctrl.T.Helper() m.ctrl.Call(m, "Templates", a, b) } // Templates indicates an expected call of Templates. func (mr *MockIndexMockRecorder) Templates(a, b any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Templates", reflect.TypeOf((*MockIndex)(nil).Templates), a, b) } // MockEmbed is a mock of Embed interface. type MockEmbed struct { ctrl *gomock.Controller recorder *MockEmbedMockRecorder isgomock struct{} } // MockEmbedMockRecorder is the mock recorder for MockEmbed. type MockEmbedMockRecorder struct { mock *MockEmbed } // NewMockEmbed creates a new mock instance. func NewMockEmbed(ctrl *gomock.Controller) *MockEmbed { mock := &MockEmbed{ctrl: ctrl} mock.recorder = &MockEmbedMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockEmbed) EXPECT() *MockEmbedMockRecorder { return m.recorder } // EmbeddedMethod mocks base method. func (m *MockEmbed) EmbeddedMethod() { m.ctrl.T.Helper() m.ctrl.Call(m, "EmbeddedMethod") } // EmbeddedMethod indicates an expected call of EmbeddedMethod. func (mr *MockEmbedMockRecorder) EmbeddedMethod() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EmbeddedMethod", reflect.TypeOf((*MockEmbed)(nil).EmbeddedMethod)) } // ForeignEmbeddedMethod mocks base method. func (m *MockEmbed) ForeignEmbeddedMethod() *bufio.Reader { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ForeignEmbeddedMethod") ret0, _ := ret[0].(*bufio.Reader) return ret0 } // ForeignEmbeddedMethod indicates an expected call of ForeignEmbeddedMethod. func (mr *MockEmbedMockRecorder) ForeignEmbeddedMethod() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ForeignEmbeddedMethod", reflect.TypeOf((*MockEmbed)(nil).ForeignEmbeddedMethod)) } // ImplicitPackage mocks base method. func (m *MockEmbed) ImplicitPackage(s string, t imp1.ImpT, st []imp1.ImpT, pt *imp1.ImpT, ct chan imp1.ImpT) { m.ctrl.T.Helper() m.ctrl.Call(m, "ImplicitPackage", s, t, st, pt, ct) } // ImplicitPackage indicates an expected call of ImplicitPackage. func (mr *MockEmbedMockRecorder) ImplicitPackage(s, t, st, pt, ct any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ImplicitPackage", reflect.TypeOf((*MockEmbed)(nil).ImplicitPackage), s, t, st, pt, ct) } // RegularMethod mocks base method. func (m *MockEmbed) RegularMethod() { m.ctrl.T.Helper() m.ctrl.Call(m, "RegularMethod") } // RegularMethod indicates an expected call of RegularMethod. func (mr *MockEmbedMockRecorder) RegularMethod() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegularMethod", reflect.TypeOf((*MockEmbed)(nil).RegularMethod)) } // MockEmbedded is a mock of Embedded interface. type MockEmbedded struct { ctrl *gomock.Controller recorder *MockEmbeddedMockRecorder isgomock struct{} } // MockEmbeddedMockRecorder is the mock recorder for MockEmbedded. type MockEmbeddedMockRecorder struct { mock *MockEmbedded } // NewMockEmbedded creates a new mock instance. func NewMockEmbedded(ctrl *gomock.Controller) *MockEmbedded { mock := &MockEmbedded{ctrl: ctrl} mock.recorder = &MockEmbeddedMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockEmbedded) EXPECT() *MockEmbeddedMockRecorder { return m.recorder } // EmbeddedMethod mocks base method. func (m *MockEmbedded) EmbeddedMethod() { m.ctrl.T.Helper() m.ctrl.Call(m, "EmbeddedMethod") } // EmbeddedMethod indicates an expected call of EmbeddedMethod. func (mr *MockEmbeddedMockRecorder) EmbeddedMethod() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EmbeddedMethod", reflect.TypeOf((*MockEmbedded)(nil).EmbeddedMethod)) } golang-go.uber-mock-0.5.0/sample/user.go000066400000000000000000000053521470430142200200410ustar00rootroot00000000000000// Package user is an example package with an interface. package user //go:generate mockgen -destination mock_user_test.go -package user_test go.uber.org/mock/sample Index,Embed,Embedded // Random bunch of imports to test mockgen. import ( "hash" "io" "log" "net" "net/http" btz "bytes" // Two imports with the same base name. t1 "html/template" t2 "text/template" "go.uber.org/mock/sample/imp1" // Dependencies outside the standard library. renamed2 "go.uber.org/mock/sample/imp2" . "go.uber.org/mock/sample/imp3" imp_four "go.uber.org/mock/sample/imp4" ) // calls itself "imp_four" // A bizarre interface to test corner cases in mockgen. // This would normally be in its own file or package, // separate from the user of it (e.g. io.Reader). type Index interface { Get(key string) any GetTwo(key1, key2 string) (v1, v2 any) Put(key string, value any) // Check that imports are handled correctly. Summary(buf *btz.Buffer, w io.Writer) Other() hash.Hash Templates(a t1.CSS, b t2.FuncMap) // A method with an anonymous argument. Anon(string) // Methods using foreign types outside the standard library. ForeignOne(imp1.Imp1) ForeignTwo(renamed2.Imp2) ForeignThree(Imp3) ForeignFour(imp_four.Imp4) // A method that returns a nillable type. NillableRet() error // A method that returns a non-interface type. ConcreteRet() chan<- bool // Methods with an ellipsis argument. Ellip(fmt string, args ...any) EllipOnly(...string) // A method with a pointer argument that we will set. Ptr(arg *int) // A method with a slice argument and an array return. Slice(a []int, b []byte) [3]int // A method with channel arguments. Chan(a chan int, b chan<- hash.Hash) // A method with a function argument. Func(f func(http.Request) (int, bool)) // A method with a map argument. Map(a map[int]hash.Hash) // Methods with an unnamed empty struct argument. Struct(a struct{}) // not so likely StructChan(a chan struct{}) // a bit more common } // An interface with an embedded interface. type Embed interface { RegularMethod() Embedded imp1.ForeignEmbedded } type Embedded interface { EmbeddedMethod() } // some random use of another package that isn't needed by the interface. var _ net.Addr // A function that we will test that uses the above interface. // It takes a list of keys and values, and puts them in the index. func Remember(index Index, keys []string, values []any) { for i, k := range keys { index.Put(k, values[i]) } err := index.NillableRet() if err != nil { log.Fatalf("Woah! %v", err) } if len(keys) > 0 && keys[0] == "a" { index.Ellip("%d", 0, 1, 1, 2, 3) index.Ellip("%d", 1, 3, 6, 10, 15) index.EllipOnly("arg") } } func GrabPointer(index Index) int { var a int index.Ptr(&a) return a } golang-go.uber-mock-0.5.0/sample/user_test.go000066400000000000000000000123651470430142200211020ustar00rootroot00000000000000// A test that uses a mock. package user_test import ( "testing" "go.uber.org/mock/gomock" user "go.uber.org/mock/sample" "go.uber.org/mock/sample/imp1" imp_four "go.uber.org/mock/sample/imp4" ) func TestRemember(t *testing.T) { ctrl := gomock.NewController(t) mockIndex := NewMockIndex(ctrl) mockIndex.EXPECT().Put("a", 1) // literals work mockIndex.EXPECT().Put("b", gomock.Eq(2)) // matchers work too // NillableRet returns error. Not declaring it should result in a nil return. mockIndex.EXPECT().NillableRet() // Calls that returns something assignable to the return type. boolc := make(chan bool) // In this case, "chan bool" is assignable to "chan<- bool". mockIndex.EXPECT().ConcreteRet().Return(boolc) // In this case, nil is assignable to "chan<- bool". mockIndex.EXPECT().ConcreteRet().Return(nil) // Should be able to place expectations on variadic methods. mockIndex.EXPECT().Ellip("%d", 0, 1, 1, 2, 3) // direct args tri := []any{1, 3, 6, 10, 15} mockIndex.EXPECT().Ellip("%d", tri...) // args from slice mockIndex.EXPECT().EllipOnly(gomock.Eq("arg")) user.Remember(mockIndex, []string{"a", "b"}, []any{1, 2}) // Check the ConcreteRet calls. if c := mockIndex.ConcreteRet(); c != boolc { t.Errorf("ConcreteRet: got %v, want %v", c, boolc) } if c := mockIndex.ConcreteRet(); c != nil { t.Errorf("ConcreteRet: got %v, want nil", c) } // Try one with an action. calledString := "" mockIndex.EXPECT().Put(gomock.Any(), gomock.Any()).Do(func(key string, _ any) { calledString = key }) mockIndex.EXPECT().NillableRet() user.Remember(mockIndex, []string{"blah"}, []any{7}) if calledString != "blah" { t.Fatalf(`Uh oh. %q != "blah"`, calledString) } // Use Do with a nil arg. mockIndex.EXPECT().Put("nil-key", gomock.Any()).Do(func(key string, value any) { if value != nil { t.Errorf("Put did not pass through nil; got %v", value) } }) mockIndex.EXPECT().NillableRet() user.Remember(mockIndex, []string{"nil-key"}, []any{nil}) } func TestVariadicFunction(t *testing.T) { ctrl := gomock.NewController(t) mockIndex := NewMockIndex(ctrl) mockIndex.EXPECT().Ellip("%d", 5, 6, 7, 8).Do(func(format string, nums ...int) { sum := 0 for _, value := range nums { sum += value } if sum != 26 { t.Errorf("Expected 26, got %d", sum) } }) mockIndex.EXPECT().Ellip("%d", gomock.Any()).Do(func(format string, nums ...int) { sum := 0 for _, value := range nums { sum += value } if sum != 10 { t.Errorf("Expected 10, got %d", sum) } }) mockIndex.EXPECT().Ellip("%d", gomock.Any()).Do(func(format string, nums ...int) { sum := 0 for _, value := range nums { sum += value } if sum != 0 { t.Errorf("Expected 0, got %d", sum) } }) mockIndex.EXPECT().Ellip("%d", gomock.Any()).Do(func(format string, nums ...int) { sum := 0 for _, value := range nums { sum += value } if sum != 0 { t.Errorf("Expected 0, got %d", sum) } }) mockIndex.EXPECT().Ellip("%d").Do(func(format string, nums ...int) { sum := 0 for _, value := range nums { sum += value } if sum != 0 { t.Errorf("Expected 0, got %d", sum) } }) mockIndex.Ellip("%d", 1, 2, 3, 4) // Match second matcher. mockIndex.Ellip("%d", 5, 6, 7, 8) // Match first matcher. mockIndex.Ellip("%d", 0) mockIndex.Ellip("%d") mockIndex.Ellip("%d") } func TestGrabPointer(t *testing.T) { ctrl := gomock.NewController(t) mockIndex := NewMockIndex(ctrl) mockIndex.EXPECT().Ptr(gomock.Any()).SetArg(0, 7) // set first argument to 7 i := user.GrabPointer(mockIndex) if i != 7 { t.Errorf("Expected 7, got %d", i) } } func TestEmbeddedInterface(t *testing.T) { ctrl := gomock.NewController(t) mockEmbed := NewMockEmbed(ctrl) mockEmbed.EXPECT().RegularMethod() mockEmbed.EXPECT().EmbeddedMethod() mockEmbed.EXPECT().ForeignEmbeddedMethod() mockEmbed.RegularMethod() mockEmbed.EmbeddedMethod() var emb imp1.ForeignEmbedded = mockEmbed // also does interface check emb.ForeignEmbeddedMethod() } func TestExpectTrueNil(t *testing.T) { // Make sure that passing "nil" to EXPECT (thus as a nil interface value), // will correctly match a nil concrete type. ctrl := gomock.NewController(t) mockIndex := NewMockIndex(ctrl) mockIndex.EXPECT().Ptr(nil) // this nil is a nil any mockIndex.Ptr(nil) // this nil is a nil *int } func TestDoAndReturnSignature(t *testing.T) { t.Run("wrong number of return args", func(t *testing.T) { ctrl := gomock.NewController(t) mockIndex := NewMockIndex(ctrl) mockIndex.EXPECT().Slice(gomock.Any(), gomock.Any()).DoAndReturn( func(_ []int, _ []byte) {}, ) defer func() { if r := recover(); r == nil { t.Error("expected panic") } }() mockIndex.Slice([]int{0}, []byte("meow")) }) t.Run("wrong type of return arg", func(t *testing.T) { ctrl := gomock.NewController(t) mockIndex := NewMockIndex(ctrl) mockIndex.EXPECT().Slice(gomock.Any(), gomock.Any()).DoAndReturn( func(_ []int, _ []byte) bool { return true }) mockIndex.Slice([]int{0}, []byte("meow")) }) } func TestExpectCondForeignFour(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mockIndex := NewMockIndex(ctrl) mockIndex.EXPECT().ForeignFour(gomock.Cond(func(x imp_four.Imp4) bool { return x.Field == "Cool" })) mockIndex.ForeignFour(imp_four.Imp4{Field: "Cool"}) } golang-go.uber-mock-0.5.0/tools/000077500000000000000000000000001470430142200164065ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/tools/cmd/000077500000000000000000000000001470430142200171515ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/tools/cmd/extract-changelog/000077500000000000000000000000001470430142200225505ustar00rootroot00000000000000golang-go.uber-mock-0.5.0/tools/cmd/extract-changelog/main.go000066400000000000000000000051671470430142200240340ustar00rootroot00000000000000// extract-changelog extracts the release notes for a specific version from a // file matching the format prescribed by https://keepachangelog.com/en/1.0.0/. package main import ( "bufio" "bytes" "errors" "flag" "fmt" "io" "os" "strings" ) func main() { cmd := mainCmd{ Stdout: os.Stdout, Stderr: os.Stderr, } if err := cmd.Run(os.Args[1:]); err != nil && err != flag.ErrHelp { fmt.Fprintln(cmd.Stderr, err) os.Exit(1) } } type mainCmd struct { Stdout io.Writer Stderr io.Writer } const _usage = `USAGE %v [OPTIONS] VERSION Retrieves the release notes for VERSION from a CHANGELOG.md file and prints them to stdout. EXAMPLES extract-changelog -i CHANGELOG.md v1.2.3 extract-changelog 0.2.5 OPTIONS ` func (cmd *mainCmd) Run(args []string) error { flag := flag.NewFlagSet("extract-changelog", flag.ContinueOnError) flag.SetOutput(cmd.Stderr) flag.Usage = func() { fmt.Fprintf(flag.Output(), _usage, flag.Name()) flag.PrintDefaults() } file := flag.String("i", "CHANGELOG.md", "input file") if err := flag.Parse(args); err != nil { return err } var version string if args := flag.Args(); len(args) > 0 { version = args[0] } version = strings.TrimPrefix(version, "v") if len(version) == 0 { return errors.New("please provide a version") } f, err := os.Open(*file) if err != nil { return fmt.Errorf("open changelog: %v", err) } defer f.Close() s, err := extract(f, version) if err != nil { return err } _, err = io.WriteString(cmd.Stdout, s) return err } func extract(r io.Reader, version string) (string, error) { type _state int const ( initial _state = iota foundHeader ) var ( state _state buff bytes.Buffer scanner = bufio.NewScanner(r) ) scan: for scanner.Scan() { line := scanner.Text() switch state { case initial: // Version headers take one of the following forms: // // ## 0.1.3 - 2021-08-18 // ## [0.1.3] - 2021-08-18 switch { case strings.HasPrefix(line, "## "+version+" "), strings.HasPrefix(line, "## ["+version+"]"): fmt.Fprintln(&buff, line) state = foundHeader } case foundHeader: // Found a new version header. Stop extracting. if strings.HasPrefix(line, "## ") { break scan } fmt.Fprintln(&buff, line) default: // unreachable but guard against it. return "", fmt.Errorf("unexpected state %v at %q", state, line) } } if err := scanner.Err(); err != nil { return "", err } if state < foundHeader { return "", fmt.Errorf("changelog for %q not found", version) } out := buff.String() out = strings.TrimSpace(out) + "\n" // always end with a single newline return out, nil } golang-go.uber-mock-0.5.0/tools/cmd/extract-changelog/main_test.go000066400000000000000000000052011470430142200250600ustar00rootroot00000000000000package main import ( "bytes" "os" "path/filepath" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) const _changelog = ` # Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## Unreleased ### Added - Upcoming feature ## [1.0.0] - 2021-08-18 Initial stable release. [1.0.0]: http://example.com/1.0.0 ## 0.3.0 - 2020-09-01 ### Removed - deprecated functionality ### Fixed - bug ## [0.2.0] - 2020-08-19 ### Added - Fancy new feature. [0.2.0]: http://example.com/0.2.0 ## 0.1.0 - 2020-08-18 Initial release. ` func TestMain(t *testing.T) { t.Parallel() changelog := filepath.Join(t.TempDir(), "CHANGELOG.md") require.NoError(t, os.WriteFile(changelog, []byte(_changelog), 0o644)) tests := []struct { desc string version string want string // expected changelog wantErr string // expected error, if any }{ { desc: "not found", version: "0.1.1", wantErr: `changelog for "0.1.1" not found`, }, { desc: "missing version", wantErr: "please provide a version", }, { desc: "non-standard body", version: "1.0.0", want: joinLines( "## [1.0.0] - 2021-08-18", "Initial stable release.", "", "[1.0.0]: http://example.com/1.0.0", ), }, { desc: "unlinked", version: "0.3.0", want: joinLines( "## 0.3.0 - 2020-09-01", "### Removed", "- deprecated functionality", "", "### Fixed", "- bug", ), }, { desc: "end of file", version: "0.1.0", want: joinLines( "## 0.1.0 - 2020-08-18", "", "Initial release.", ), }, { desc: "linked", version: "0.2.0", want: joinLines( "## [0.2.0] - 2020-08-19", "### Added", "- Fancy new feature.", "", "[0.2.0]: http://example.com/0.2.0", ), }, } for _, tt := range tests { tt := tt t.Run(tt.desc, func(t *testing.T) { t.Parallel() var stdout, stderr bytes.Buffer defer func() { assert.Empty(t, stderr.String(), "stderr should be empty") }() err := (&mainCmd{ Stdout: &stdout, Stderr: &stderr, }).Run([]string{"-i", changelog, tt.version}) if len(tt.wantErr) > 0 { require.Error(t, err) assert.Contains(t, err.Error(), tt.wantErr) return } require.NoError(t, err) assert.Equal(t, tt.want, stdout.String()) }) } } // Join a bunch of lines with a trailing newline. func joinLines(lines ...string) string { return strings.Join(lines, "\n") + "\n" } golang-go.uber-mock-0.5.0/tools/go.mod000066400000000000000000000003551470430142200175170ustar00rootroot00000000000000module github.com/uber-go/mock/tools go 1.22 require github.com/stretchr/testify v1.9.0 require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) golang-go.uber-mock-0.5.0/tools/go.sum000066400000000000000000000015611470430142200175440ustar00rootroot00000000000000github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=