├── .github
├── pull_request_template.md
└── workflows
│ └── run-tests.yml
├── .gitignore
├── .goreleaser.yml
├── LICENSE
├── README.md
├── _config.yml
├── dsl.go
├── dsl_test.go
├── generate_test_mocks
└── xtools_go_loader
│ └── generate_test.go
├── ginkgo_compatible
├── in_order_context.go
├── matchers.go
├── matchers_generic.go
├── option.go
└── whenever.go
├── go.mod
├── go.sum
├── internal
├── generate_matchers
│ └── matcher_generation.go
└── verify
│ └── verify.go
├── invocation_count_matchers.go
├── logo.svg
├── matcher.go
├── matcher_factories.go
├── matchers_generic.go
├── mockgen
└── mockgen.go
├── model
└── model.go
├── modelgen
├── modelgen_test.go
├── test_data
│ └── default_test_interface
│ │ └── display.go
└── xtools_packages
│ ├── packages.go
│ ├── packages_suite_test.go
│ └── packages_test.go
├── panic_with_message_matcher_test.go
├── panic_with_message_to_matcher_test.go
├── pegomock
├── filehandling
│ └── filehandling.go
├── main.go
├── main_test.go
├── package_name.go
├── package_name_test.go
├── remove
│ └── remove.go
├── testutil
│ ├── gomega_file_matcher.go
│ └── io.go
├── util
│ ├── error.go
│ ├── input.go
│ ├── io.go
│ └── time.go
└── watch
│ ├── watch.go
│ └── watch_test.go
├── scripts
├── ginkgo-watch-gomock-reflect
├── ginkgo-watch-gomock-source
├── ginkgo-watch-recursive
└── run_tests.sh
├── test_interface
└── display.go
├── testing_t_support.go
└── types.go
/.github/pull_request_template.md:
--------------------------------------------------------------------------------
1 | Thank you for your contribution to **Pegomock**.
2 |
3 | Please make sure to open your PR against the `develop` branch.
--------------------------------------------------------------------------------
/.github/workflows/run-tests.yml:
--------------------------------------------------------------------------------
1 | name: Go
2 |
3 | on: [push, pull_request]
4 |
5 | jobs:
6 | build:
7 |
8 | runs-on: ubuntu-latest
9 | strategy:
10 | matrix:
11 | go-version: [ '1.18', '1.19', '1.20' ]
12 |
13 | steps:
14 | - uses: actions/checkout@v3
15 | - name: Setup Go ${{ matrix.go-version }}
16 | uses: actions/setup-go@v4
17 | with:
18 | go-version: ${{ matrix.go-version }}
19 |
20 | - name: Display Go version
21 | run: go version
22 |
23 | - name: Install Ginkgo
24 | run: go install github.com/onsi/ginkgo/v2/ginkgo@latest
25 |
26 | - name: Run tests
27 | run: ./scripts/run_tests.sh
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | mock_display_test.go
2 | mock_generic_display_test.go
3 | debug.test
4 | .vscode
5 | *.coverprofile
6 | coverprofile.out
7 | .idea
8 | *.iml
9 | dist
10 | pegomock/pegomock
11 |
--------------------------------------------------------------------------------
/.goreleaser.yml:
--------------------------------------------------------------------------------
1 | # This is an example goreleaser.yaml file with some sane defaults.
2 | # Make sure to check the documentation at http://goreleaser.com
3 | builds:
4 | - main: ./pegomock
5 | env:
6 | - CGO_ENABLED=0
7 | goos:
8 | - darwin
9 | - linux
10 | - windows
11 | goarch:
12 | - amd64
13 |
14 | archives:
15 | - replacements:
16 | # darwin: Darwin
17 | # linux: Linux
18 | # windows: Windows
19 | amd64: x86_64
20 | files:
21 | - none*
22 | format: binary
23 | checksum:
24 | name_template: 'checksums.txt'
25 | changelog:
26 | skip: true
27 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | [](https://github.com/petergtz/pegomock/actions/workflows/run-tests.yml)
4 |
5 |
6 |
7 |
8 |
9 | PegoMock is a mocking framework for the [Go programming language](http://golang.org/). It integrates well with Go's built-in `testing` package, but can be used in other contexts too. It is based on [golang/mock](https://github.com/golang/mock), but uses a DSL closely related to [Mockito](http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html).
10 |
11 | Installing Pegomock
12 | ===================
13 |
14 | Pegomock consists of a binary `pegomock` and a package. Install both via:
15 |
16 | ```shell
17 | go install github.com/petergtz/pegomock/v4/pegomock@latest
18 | go get github.com/petergtz/pegomock/v4@latest
19 | ```
20 |
21 | This will download the package and install an executable `pegomock` in the directory named by the `$GOBIN` environment variable, which defaults to `$GOPATH/bin` or `$HOME/go/bin` if the `$GOPATH` environment variable is not set.
22 |
23 | The `pegomock` binary is used to generate mocks and to watch over changes in interfaces. The package is used in your tests to create and verify mocks.
24 |
25 |
26 | See also section [Tracking the pegomock tool in your project](#tracking-the-pegomock-tool-in-your-project) for a per-project control of the tool version.
27 |
28 | For migration from Pegomock v1/v2 to v3, see [Migration notes in v3 release description](https://github.com/petergtz/pegomock/releases/tag/v3.0.0).
29 |
30 | For migration from Pegomock v3 to v4, see [Migration notes in v4 release description](https://github.com/petergtz/pegomock/releases/tag/v4.0.0).
31 |
32 | Getting Started
33 | ===============
34 |
35 | Using Pegomock with Golang’s XUnit-style Tests
36 | ----------------------------------------------
37 |
38 | The preferred way is:
39 |
40 | ```go
41 | import (
42 | "github.com/petergtz/pegomock/v4"
43 | "testing"
44 | )
45 |
46 | func TestUsingMocks(t *testing.T) {
47 | mock := NewMockPhoneBook(pegomock.WithT(t))
48 |
49 | // use your mock here
50 | }
51 | ```
52 |
53 |
54 | Alternatively, you can set a global fail handler within your test:
55 |
56 | ```go
57 | func TestUsingMocks(t *testing.T) {
58 | pegomock.RegisterMockTestingT(t)
59 |
60 | mock := NewMockPhoneBook()
61 |
62 | // use your mock here
63 | }
64 | ```
65 | **Note:** In this case, Pegomock uses a global (singleton) fail handler. This has the benefit that you don’t need to pass the fail handler down to each test, but does mean that you cannot run your XUnit style tests in parallel with Pegomock.
66 |
67 | If you configure both a global fail handler and a specific one for your mock, the specific one overrides the global fail handler.
68 |
69 | Using Pegomock with Ginkgo
70 | --------------------------
71 |
72 | When a Pegomock verification fails, it calls a `FailHandler`. This is a function that you must provide using `pegomock.RegisterMockFailHandler()`.
73 |
74 | If you’re using [Ginkgo](http://onsi.github.io/ginkgo/), all you need to do is:
75 |
76 | ```go
77 | pegomock.RegisterMockFailHandler(ginkgo.Fail)
78 | ```
79 |
80 | before you start your test suite.
81 |
82 | ### Avoiding Ginkgo Naming Collision with `When` Function
83 |
84 | Ginkgo introduced a new keyword in its DSL: `When`. This causes name collisions when dot-importing both Ginkgo and Pegomock. To avoid this, you can use a different dot-import for Pegomock which uses `Whenever` instead of `When`. Example:
85 |
86 | ```go
87 | package some_test
88 |
89 | import (
90 | . "github.com/onsi/ginkgo"
91 | . "github.com/petergtz/pegomock/v4/ginkgo_compatible"
92 | )
93 |
94 | var _ = Describe("Some function", func() {
95 | When("certain condition", func() {
96 | It("succeeds", func() {
97 | mock := NewMockPhoneBook()
98 | Whenever(mock.GetPhoneNumber(Eq("Tom"))).ThenReturn("123-456-789")
99 | })
100 | })
101 | })
102 | ```
103 |
104 | Generating Your First Mock and Using It
105 | ---------------------------------------
106 |
107 | Let's assume you have:
108 |
109 | ```go
110 | type Display interface {
111 | Show(text string)
112 | }
113 | ```
114 |
115 | The simplest way is to call `pegomock` from within your go package specifying the interface by its name:
116 |
117 | ```
118 | cd path/to/package
119 | pegomock generate Display
120 | ```
121 |
122 | This will generate a `mock_display_test.go` file which you can now use in your tests:
123 |
124 | ```go
125 | // creating mock
126 | display := NewMockDisplay()
127 |
128 | // using the mock
129 | display.Show("Hello World!")
130 |
131 | // verifying
132 | display.VerifyWasCalledOnce().Show("Hello World!")
133 | ```
134 |
135 | Why yet Another Mocking Framework for Go?
136 | =========================================
137 |
138 | I've looked at some of the other frameworks, but found none of them satisfying:
139 | - [GoMock](https://github.com/golang/mock) seemed overly complicated when setting up mocks and verifying them. The command line interface is also not quite intuitive. That said, Pegomock is based on the GoMock, reusing mostly the mockgen code.
140 | - [Counterfeiter](https://github.com/maxbrunsfeld/counterfeiter) uses a DSL that I didn't find expressive enough. It often seems to need more lines of code too. In one of its samples, it uses e.g.:
141 |
142 | ```go
143 | fake.DoThings("stuff", 5)
144 | Expect(fake.DoThingsCallCount()).To(Equal(1))
145 |
146 | str, num := fake.DoThingsArgsForCall(0)
147 | Expect(str).To(Equal("stuff"))
148 | Expect(num).To(Equal(uint64(5)))
149 | ```
150 |
151 | In Pegomock, this can be written as simple as:
152 |
153 | ```go
154 | fake.DoThings("stuff", 5)
155 | fake.VerifyWasCalledOnce().DoThings("stuff", 5)
156 | ```
157 |
158 | In addition, Pegomock provides a "watch" command similar to [Ginkgo](http://onsi.github.io/ginkgo/), which constantly watches over changes in an interface and updates its mocks. It gives the framework a much more dynamic feel, similar to mocking frameworks in Ruby or Java.
159 |
160 | Using Mocks In Your Tests
161 | =========================
162 |
163 | Verifying Behavior
164 | ------------------
165 |
166 | Interface:
167 |
168 | ```go
169 | type Display interface {
170 | Show(text string)
171 | }
172 | ```
173 |
174 | Test:
175 |
176 | ```go
177 | // creating mock:
178 | display := NewMockDisplay()
179 |
180 | // using the mock:
181 | display.Show("Hello World!")
182 |
183 | // verifying:
184 | display.VerifyWasCalledOnce().Show("Hello World!")
185 | ```
186 |
187 | Stubbing
188 | --------
189 |
190 | Interface:
191 |
192 | ```go
193 | type PhoneBook interface {
194 | GetPhoneNumber(name string) string
195 | }
196 | ```
197 |
198 | Test:
199 |
200 | ```go
201 | // creating the mock
202 | phoneBook := NewMockPhoneBook()
203 |
204 | // stubbing:
205 | When(phoneBook.GetPhoneNumber("Tom")).ThenReturn("345-123-789")
206 | When(phoneBook.GetPhoneNumber("Invalid")).ThenPanic("Invalid Name")
207 |
208 | // prints "345-123-789":
209 | fmt.Println(phoneBook.GetPhoneNumber("Tom"))
210 |
211 | // panics:
212 | fmt.Println(phoneBook.GetPhoneNumber("Invalid"))
213 |
214 | // prints "", because GetPhoneNumber("Dan") was not stubbed
215 | fmt.Println(phoneBook.GetPhoneNumber("Dan"))
216 |
217 | // Although it is possible to verify a stubbed invocation, usually it's redundant
218 | // If your code cares what GetPhoneNumber("Tom") returns, then something else breaks (often even before a verification gets executed).
219 | // If your code doesn't care what GetPhoneNumber("Tom") returns, then it should not be stubbed.
220 |
221 | // Not convinced? See http://monkeyisland.pl/2008/04/26/asking-and-telling.
222 | phoneBook.VerifyWasCalledOnce().GetPhoneNumber("Tom")
223 | ```
224 |
225 | - By default, for all methods that return a value, a mock will return zero values.
226 | - Once stubbed, the method will always return a stubbed value, regardless of how many times it is called.
227 | - `ThenReturn` supports chaining, i.e. `ThenReturn(...).ThenReturn(...)` etc. The mock will return the values in the same order the chaining was done. The values from the last `ThenReturn` will be returned indefinitely when the number of call exceeds the `ThenReturn`s.
228 |
229 | Stubbing Functions That Have no Return Value
230 | --------------------------------------------
231 |
232 | Stubbing functions that have no return value requires a slightly different approach, because such functions cannot be passed directly to another function. However, we can wrap them in an anonymous function:
233 |
234 | ```go
235 | // creating mock:
236 | display := NewMockDisplay()
237 |
238 | // stubbing
239 | When(func() { display.Show("Hello World!") }).ThenPanic("Panicking")
240 |
241 | // panics:
242 | display.Show("Hello World!")
243 | ```
244 |
245 | Argument Matchers
246 | -----------------
247 |
248 | Pegomock provides matchers for stubbing and verification.
249 |
250 | Verification:
251 |
252 | ```go
253 | display := NewMockDisplay()
254 |
255 | // Calling mock
256 | display.Show("Hello again!")
257 |
258 | // Verification:
259 | display.VerifyWasCalledOnce().Show(AnyString())
260 | ```
261 |
262 | Stubbing:
263 |
264 | ```go
265 | phoneBook := NewMockPhoneBook()
266 |
267 | // Stubbing:
268 | When(phoneBook.GetPhoneNumber(AnyString())).ThenReturn("123-456-789")
269 |
270 | // Prints "123-456-789":
271 | fmt.Println(phoneBook.GetPhoneNumber("Dan"))
272 | // Also prints "123-456-789":
273 | fmt.Println(phoneBook.GetPhoneNumber("Tom"))
274 | ```
275 |
276 | **Important**: When you use argument matchers, you must always use them for all arguments:
277 |
278 | ```go
279 | // Incorrect, panics:
280 | When(contactList.getContactByFullName("Dan", AnyString())).thenReturn(Contact{...})
281 | // Correct:
282 | When(contactList.getContactByFullName(Eq("Dan"), AnyString())).thenReturn(Contact{...})
283 | ```
284 |
285 | Matching custom types:
286 |
287 | ```go
288 | type SearchQuery struct { ... }
289 |
290 | When(contactList.searchContacts(Eq(SearchQuery{...}))).thenReturn([]Contact{...})
291 |
292 | When(contactList.searchContacts(Any[SearchQuery]())).thenReturn([]Contact{...})
293 | ```
294 |
295 |
296 | Verifying the Number of Invocations
297 | -----------------------------------
298 |
299 | ```go
300 | display := NewMockDisplay()
301 |
302 | // Calling mock
303 | display.Show("Hello")
304 | display.Show("Hello, again")
305 | display.Show("And again")
306 |
307 | // Verification:
308 | display.VerifyWasCalled(Times(3)).Show(AnyString())
309 | // or:
310 | display.VerifyWasCalled(AtLeast(3)).Show(AnyString())
311 | // or:
312 | display.VerifyWasCalled(Never()).Show("This one was never called")
313 | ```
314 |
315 | Verifying in Order
316 | ------------------
317 |
318 | ```go
319 | display1 := NewMockDisplay()
320 | display2 := NewMockDisplay()
321 |
322 | // Calling mocks
323 | display1.Show("One")
324 | display1.Show("Two")
325 | display2.Show("Another two")
326 | display1.Show("Three")
327 |
328 | // Verification:
329 | inOrderContext := new(InOrderContext)
330 | display1.VerifyWasCalledInOrder(Once(), inOrderContext).Show("One")
331 | display2.VerifyWasCalledInOrder(Once(), inOrderContext).Show("Another two")
332 | display1.VerifyWasCalledInOrder(Once(), inOrderContext).Show("Three")
333 | ```
334 |
335 | Note that it's not necessary to verify the call for `display.Show("Two")` if that one is not of any interested. An `InOrderContext` only verifies that the verifications that are done, are in order.
336 |
337 | Stubbing with Callbacks
338 | ------------------------
339 |
340 | ```go
341 | phoneBook := NewMockPhoneBook()
342 |
343 | // Stubbing:
344 | When(phoneBook.GetPhoneNumber(AnyString())).Then(func(params []Param) ReturnValues {
345 | return []ReturnValue{fmt.Sprintf("1-800-CALL-%v", strings.ToUpper(params[0]))}
346 | },
347 |
348 |
349 | // Prints "1-800-CALL-DAN":
350 | fmt.Println(phoneBook.GetPhoneNumber("Dan"))
351 | // Prints "1-800-CALL-TOM":
352 | fmt.Println(phoneBook.GetPhoneNumber("Tom"))
353 | ```
354 |
355 |
356 | Verifying with Argument Capture
357 | --------------------------------
358 |
359 | In some cases it can be useful to capture the arguments from mock invocations and assert on them separately. This method is only recommended if the techniques using matchers are not sufficient.
360 |
361 | ```go
362 | display := NewMockDisplay()
363 |
364 | // Calling mock
365 | display.Show("Hello")
366 | display.Show("Hello, again")
367 | display.Show("And again")
368 |
369 | // Verification and getting captured arguments
370 | text := display.VerifyWasCalled(AtLeast(1)).Show(AnyString()).GetCapturedArguments()
371 |
372 | // Captured arguments are from last invocation
373 | Expect(text).To(Equal("And again"))
374 | ```
375 |
376 | You can also get all captured arguments:
377 |
378 | ```go
379 | // Verification and getting all captured arguments
380 | texts := display.VerifyWasCalled(AtLeast(1)).Show(AnyString()).GetAllCapturedArguments()
381 |
382 | // Captured arguments are a slice
383 | Expect(texts).To(ConsistOf("Hello", "Hello, again", "And again"))
384 | ```
385 |
386 | Verifying with Asynchronous Mock Invocations
387 | --------------------------------------------
388 |
389 | When the code exercising the mock is run as part of a Goroutine, it's necessary to verify in a polling fashion until a timeout kicks in. `VerifyWasCalledEventually` can help here:
390 | ```go
391 | display := NewMockDisplay()
392 |
393 | go func() {
394 | doSomething()
395 | display.Show("Hello")
396 | }()
397 |
398 | display.VerifyWasCalledEventually(Once(), 2*time.Second).Show("Hello")
399 | ```
400 |
401 |
402 | The Pegomock CLI
403 | ================
404 |
405 | Installation
406 | ------------
407 |
408 | Install it via:
409 |
410 | ```shell
411 | go install github.com/petergtz/pegomock/v4/pegomock@latest
412 | ```
413 |
414 | Tracking the pegomock tool in your project
415 | ------------------------------------------
416 |
417 | Go modules allow to pin not only a package but also a tool (that is, an executable). The steps are:
418 |
419 | 1. Use a file named `tools.go` with contents similar to this:
420 | ```go
421 | // +build tools
422 |
423 | // This file will never be compiled (see the build constraint above); it is
424 | // used to record dependencies on build tools with the Go modules machinery.
425 | // See https://github.com/go-modules-by-example/index/blob/master/010_tools/README.md
426 |
427 | package tools
428 |
429 | import (
430 | _ "github.com/petergtz/pegomock/v4/pegomock"
431 | )
432 | ```
433 | 2. Set `$GOBIN` to a `bin` directory relative to your repo (this defines where tool dependencies will be installed).
434 | 2. Install the tool with `go install`:
435 | ```console
436 | $ cd /path/to/myproject
437 | $ export GOBIN=$PWD/bin
438 | $ go install github.com/petergtz/pegomock/v4/pegomock
439 | ```
440 | 3. Use that `$GOBIN` when invoking `pegomock` for that project:
441 | ```console
442 | $ $GOBIN/pegomock ...
443 | ```
444 | or
445 | ```console
446 | $ export PATH=$GOBIN:$PATH
447 | $ pegomock ...
448 | ```
449 |
450 | See [Tools as dependencies] for details.
451 |
452 | [Tools as dependencies]: https://github.com/go-modules-by-example/index/blob/master/010_tools/README.md
453 |
454 | Generating Mocks
455 | ----------------
456 |
457 | To generate mocks, invoke Pegomock like this:
458 |
459 | ```shell
460 | pegomock generate [] []
461 | ```
462 |
463 | Flags can be any of the following:
464 |
465 | - `--output,-o`: Output file; defaults to mock__test.go.
466 |
467 | - `--package`: Package of the generated code; defaults to the package from which pegomock was executed suffixed with _test
468 |
469 | For more flags, run:
470 |
471 | ```shell
472 | pegomock --help
473 | ```
474 |
475 | Generating Mocks with `--use-experimental-model-gen`
476 | ----------------------------------------------------
477 |
478 | There are a number of shortcomings in the current reflection-based implementation.
479 | To overcome these, there is now an option to use a new, experimental implementation that is based on [golang.org/x/tools/go/loader](https://godoc.org/golang.org/x/tools/go/loader).
480 | To use it when generating your mocks, invoke `pegomock` like this:
481 |
482 | ```shell
483 | pegomock generate --use-experimental-model-gen [] []
484 | ```
485 |
486 | What are the benefits?
487 | - The current default uses the [reflect](https://golang.org/pkg/reflect/) package to introspect the interface for which a mock should be generated. But reflection cannot determine method parameter names, only types. This forces the generator to generate them based on a pattern. In a code editor with code assistence, those pattern-based names (such as `_param0`, `_param1`) are non-descriptive and provide less help while writing code. The new implementation properly parses the source (including *all* dependent packages) and subsequently uses the same names as used in the interface definition.
488 | - With the current default you cannot generate an interface that lives in the `main` package. It's due to the way this implementation works: it imports the interface's package into temporarily generated code that gets compiled on the fly. This compilation fails, because there are now two `main` functions.
489 | - The new implementation is simpler and will probably become the default in the future, because it will be easier to maintain.
490 |
491 | What are the drawbacks?
492 | - There is only one drawback: maturity. The new implementation is not complete yet, and also might have some bugs that still need to be fixed.
493 |
494 | Users of Pegomock are encouraged to use this new option and report any problems by [opening an issue](https://github.com/petergtz/pegomock/issues/new). Help to stabilize it is greatly appreciated.
495 |
496 | Generating mocks with `go generate`
497 | ----------------------------------
498 |
499 | `pegomock` can be used with `go generate`. Simply add the directive to your source file.
500 |
501 | Here's an example for a Display interface used by a calculator program:
502 |
503 | ```go
504 | // package/path/to/display/display.go
505 |
506 | package display
507 |
508 | type Display interface {
509 | Show(text string)
510 | }
511 | ```
512 |
513 | ```go
514 | // package/path/to/calculator/calculator_test.go
515 |
516 | package calculator_test
517 |
518 | //go:generate pegomock generate package/path/to/display Display
519 |
520 | // Use generated mock
521 | mockDisplay := NewMockDisplay()
522 | ...
523 | ```
524 |
525 | Generating it:
526 | ```shell
527 | cd package/path/to/calculator
528 | go generate
529 | ```
530 |
531 | **Note:** While you could add the directive adjacent to the interface definition, the author's opinion is that this violates clean dependency management and would pollute the package of the interface.
532 | It's better to generate the mock in the same package, where it is used (if this coincides with the interface package, that's fine). That way, not only stays the interface's package clean, the tests also don't need to prefix the mock with a package, or use a dot-import.
533 |
534 | Continuously Generating Mocks
535 | -----------------------------
536 |
537 | The `watch` command lets Pegomock generate mocks continuously on every change to an interface:
538 |
539 | ```shell
540 | pegomock watch
541 | ```
542 |
543 | For this, Pegomock expects an `interfaces_to_mock` file in the package directory where the mocks should be generated. In fact, `pegomock watch` will create it for you if it doesn't exist yet. The contents of the file are similar to the ones of the `generate` command:
544 |
545 | ```
546 | # Any line starting with a # is treated as comment.
547 |
548 | # interface name without package specifies an Interface in the current package:
549 | PhoneBook
550 |
551 | # generates a mock for SomeInterfacetaken from mypackage:
552 | path/to/my/mypackage SomeInterface
553 |
554 | # you can also specify a Go file:
555 | display.go
556 |
557 | # and use most of the flags from the "generate" command
558 | --output my_special_output.go MyInterface
559 | ```
560 |
561 | Flags can be:
562 |
563 | - `--recursive,-r`: Recursively watch sub-directories as well.
564 |
565 | Removing Generated Mocks
566 | -----------------------------
567 |
568 | Sometimes it can be useful to systematically remove all mocks and matcher files generated by Pegomock. For this purpose, there is the `remove` command. By simply calling it from the current directory
569 | ```shell
570 | pegomock remove
571 | ```
572 | it will remove all Pegomock-generated files in the current directory. It supports additional flags, such as `--recursive` to recursively remove all Pegomock-generated files in sub-directories as well. To see all possible options, run:
573 | ```shell
574 | pegomock remove --help
575 | ```
576 |
--------------------------------------------------------------------------------
/_config.yml:
--------------------------------------------------------------------------------
1 | theme: jekyll-theme-cayman
--------------------------------------------------------------------------------
/dsl.go:
--------------------------------------------------------------------------------
1 | // Copyright 2015 Peter Goetz
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | package pegomock
16 |
17 | import (
18 | "bytes"
19 | "fmt"
20 | "reflect"
21 | "sort"
22 | "sync"
23 | "testing"
24 | "time"
25 |
26 | "github.com/onsi/gomega/format"
27 | "github.com/petergtz/pegomock/v4/internal/verify"
28 | )
29 |
30 | var GlobalFailHandler FailHandler
31 |
32 | func RegisterMockFailHandler(handler FailHandler) {
33 | GlobalFailHandler = handler
34 | }
35 | func RegisterMockTestingT(t *testing.T) {
36 | RegisterMockFailHandler(BuildTestingTFailHandler(t))
37 | }
38 |
39 | var (
40 | lastInvocation *invocation
41 | lastInvocationMutex sync.Mutex
42 | )
43 |
44 | var globalArgMatchers Matchers
45 |
46 | func RegisterMatcher(matcher ArgumentMatcher) {
47 | globalArgMatchers.append(matcher)
48 | }
49 |
50 | type invocation struct {
51 | genericMock *GenericMock
52 | MethodName string
53 | Params []Param
54 | ReturnTypes []reflect.Type
55 | }
56 |
57 | type GenericMock struct {
58 | sync.Mutex
59 | mockedMethods map[string]*mockedMethod
60 | fail FailHandler
61 | }
62 |
63 | func (genericMock *GenericMock) Invoke(methodName string, params []Param, returnTypes []reflect.Type) ReturnValues {
64 | lastInvocationMutex.Lock()
65 | lastInvocation = &invocation{
66 | genericMock: genericMock,
67 | MethodName: methodName,
68 | Params: params,
69 | ReturnTypes: returnTypes,
70 | }
71 | lastInvocationMutex.Unlock()
72 | return genericMock.getOrCreateMockedMethod(methodName).Invoke(params)
73 | }
74 |
75 | func (genericMock *GenericMock) stub(methodName string, paramMatchers []ArgumentMatcher, returnValues ReturnValues) {
76 | genericMock.stubWithCallback(methodName, paramMatchers, func([]Param) ReturnValues { return returnValues })
77 | }
78 |
79 | func (genericMock *GenericMock) stubWithCallback(methodName string, paramMatchers []ArgumentMatcher, callback func([]Param) ReturnValues) {
80 | genericMock.getOrCreateMockedMethod(methodName).stub(paramMatchers, callback)
81 | }
82 |
83 | func (genericMock *GenericMock) getOrCreateMockedMethod(methodName string) *mockedMethod {
84 | genericMock.Lock()
85 | defer genericMock.Unlock()
86 | if _, ok := genericMock.mockedMethods[methodName]; !ok {
87 | genericMock.mockedMethods[methodName] = &mockedMethod{name: methodName}
88 | }
89 | return genericMock.mockedMethods[methodName]
90 | }
91 |
92 | func (genericMock *GenericMock) reset(methodName string, paramMatchers []ArgumentMatcher) {
93 | genericMock.getOrCreateMockedMethod(methodName).reset(paramMatchers)
94 | }
95 |
96 | func (genericMock *GenericMock) Verify(
97 | inOrderContext *InOrderContext,
98 | invocationCountMatcher InvocationCountMatcher,
99 | methodName string,
100 | params []Param,
101 | options ...interface{},
102 | ) []MethodInvocation {
103 | var timeout time.Duration
104 | if len(options) == 1 {
105 | timeout = options[0].(time.Duration)
106 | }
107 | if genericMock.fail == nil && GlobalFailHandler == nil {
108 | panic("No FailHandler set. Please use either RegisterMockFailHandler or RegisterMockTestingT or TODO to set a fail handler.")
109 | }
110 | fail := GlobalFailHandler
111 | if genericMock.fail != nil {
112 | fail = genericMock.fail
113 | }
114 | defer func() { globalArgMatchers = nil }() // We don't want a panic somewhere during verification screw our global argMatchers
115 |
116 | if len(globalArgMatchers) != 0 {
117 | verifyArgMatcherUse(globalArgMatchers, params)
118 | }
119 | startTime := time.Now()
120 | // timeoutLoop:
121 | for {
122 | genericMock.Lock()
123 | methodInvocations := genericMock.methodInvocations(methodName, params, globalArgMatchers)
124 | genericMock.Unlock()
125 | if inOrderContext != nil {
126 | for _, methodInvocation := range methodInvocations {
127 | if methodInvocation.orderingInvocationNumber <= inOrderContext.invocationCounter {
128 | // TODO: should introduce the following, in case we decide support "inorder" and "eventually"
129 | // if time.Since(startTime) < timeout {
130 | // continue timeoutLoop
131 | // }
132 | fail(fmt.Sprintf("Expected function call %v(%v) before function call %v(%v)",
133 | methodName, formatParams(params), inOrderContext.lastInvokedMethodName, formatParams(inOrderContext.lastInvokedMethodParams)))
134 | }
135 | inOrderContext.invocationCounter = methodInvocation.orderingInvocationNumber
136 | inOrderContext.lastInvokedMethodName = methodName
137 | inOrderContext.lastInvokedMethodParams = params
138 | }
139 | }
140 | if !invocationCountMatcher.Matches(len(methodInvocations)) {
141 | if time.Since(startTime) < timeout {
142 | time.Sleep(10 * time.Millisecond)
143 | continue
144 | }
145 | var paramsOrMatchers interface{} = formatParams(params)
146 | if len(globalArgMatchers) != 0 {
147 | paramsOrMatchers = formatMatchers(globalArgMatchers)
148 | }
149 | timeoutInfo := ""
150 | if timeout > 0 {
151 | timeoutInfo = fmt.Sprintf(" after timeout of %v", timeout)
152 | }
153 | fail(fmt.Sprintf(
154 | "Mock invocation count for %v(%v) does not match expectation%v.\n\n\t%v\n\n\t%v",
155 | methodName, paramsOrMatchers, timeoutInfo, invocationCountMatcher.FailureMessage(), formatInteractions(genericMock.allInteractions())))
156 | }
157 | return methodInvocations
158 | }
159 | }
160 |
161 | // TODO this doesn't need to be a method, can be a free function
162 | func (genericMock *GenericMock) GetInvocationParams(methodInvocations []MethodInvocation) [][]Param {
163 | if len(methodInvocations) == 0 {
164 | return nil
165 | }
166 | result := make([][]Param, len(methodInvocations[len(methodInvocations)-1].params))
167 | for i, invocation := range methodInvocations {
168 | for u, param := range invocation.params {
169 | if result[u] == nil {
170 | result[u] = make([]Param, len(methodInvocations))
171 | }
172 | result[u][i] = param
173 | }
174 | }
175 | return result
176 | }
177 |
178 | func (genericMock *GenericMock) methodInvocations(methodName string, params []Param, matchers []ArgumentMatcher) []MethodInvocation {
179 | var invocations []MethodInvocation
180 | if method, exists := genericMock.mockedMethods[methodName]; exists {
181 | method.Lock()
182 | for _, invocation := range method.invocations {
183 | if len(matchers) != 0 {
184 | if Matchers(matchers).Matches(invocation.params) {
185 | invocations = append(invocations, invocation)
186 | }
187 | } else {
188 | if reflect.DeepEqual(params, invocation.params) ||
189 | (len(params) == 0 && len(invocation.params) == 0) {
190 | invocations = append(invocations, invocation)
191 | }
192 | }
193 | }
194 | method.Unlock()
195 | }
196 | return invocations
197 | }
198 |
199 | func formatInteractions(interactions map[string][]MethodInvocation) string {
200 | if len(interactions) == 0 {
201 | return "There were no other interactions with this mock"
202 | }
203 | result := "Actual interactions with this mock were:\n"
204 | for _, methodName := range sortedMethodNames(interactions) {
205 | result += formatInvocations(methodName, interactions[methodName])
206 | }
207 | return result
208 | }
209 |
210 | func formatInvocations(methodName string, invocations []MethodInvocation) (result string) {
211 | for _, invocation := range invocations {
212 | result += "\t" + methodName + "(" + formatParams(invocation.params) + ")\n"
213 | }
214 | return
215 | }
216 |
217 | func formatParams(params []Param) (result string) {
218 | for i, param := range params {
219 | if i > 0 {
220 | result += ", "
221 | }
222 | result += fmt.Sprintf("%#v", param)
223 | }
224 | return
225 | }
226 |
227 | func formatMatchers(matchers []ArgumentMatcher) (result string) {
228 | for i, matcher := range matchers {
229 | if i > 0 {
230 | result += ", "
231 | }
232 | result += fmt.Sprintf("%v", matcher)
233 | }
234 | return
235 | }
236 |
237 | func sortedMethodNames(interactions map[string][]MethodInvocation) []string {
238 | methodNames := make([]string, len(interactions))
239 | i := 0
240 | for key := range interactions {
241 | methodNames[i] = key
242 | i++
243 | }
244 | sort.Strings(methodNames)
245 | return methodNames
246 | }
247 |
248 | func (genericMock *GenericMock) allInteractions() map[string][]MethodInvocation {
249 | interactions := make(map[string][]MethodInvocation)
250 | for methodName := range genericMock.mockedMethods {
251 | for _, invocation := range genericMock.mockedMethods[methodName].invocations {
252 | interactions[methodName] = append(interactions[methodName], invocation)
253 | }
254 | }
255 | return interactions
256 | }
257 |
258 | type mockedMethod struct {
259 | sync.Mutex
260 | name string
261 | invocations []MethodInvocation
262 | stubbings Stubbings
263 | }
264 |
265 | func (method *mockedMethod) Invoke(params []Param) ReturnValues {
266 | method.Lock()
267 | method.invocations = append(method.invocations, MethodInvocation{params, globalInvocationCounter.nextNumber()})
268 | method.Unlock()
269 | stubbing := method.stubbings.find(params)
270 | if stubbing == nil {
271 | return ReturnValues{}
272 | }
273 | return stubbing.Invoke(params)
274 | }
275 |
276 | func (method *mockedMethod) stub(paramMatchers Matchers, callback func([]Param) ReturnValues) {
277 | stubbing := method.stubbings.findByMatchers(paramMatchers)
278 | if stubbing == nil {
279 | stubbing = &Stubbing{paramMatchers: paramMatchers}
280 | method.stubbings = append(method.stubbings, stubbing)
281 | }
282 | stubbing.callbackSequence = append(stubbing.callbackSequence, callback)
283 | }
284 |
285 | func (method *mockedMethod) removeLastInvocation() {
286 | method.invocations = method.invocations[:len(method.invocations)-1]
287 | }
288 |
289 | func (method *mockedMethod) reset(paramMatchers Matchers) {
290 | method.stubbings.removeByMatchers(paramMatchers)
291 | }
292 |
293 | type Counter struct {
294 | count int
295 | sync.Mutex
296 | }
297 |
298 | func (counter *Counter) nextNumber() (nextNumber int) {
299 | counter.Lock()
300 | defer counter.Unlock()
301 |
302 | nextNumber = counter.count
303 | counter.count++
304 | return
305 | }
306 |
307 | var globalInvocationCounter = Counter{count: 1}
308 |
309 | type MethodInvocation struct {
310 | params []Param
311 | orderingInvocationNumber int
312 | }
313 |
314 | type Stubbings []*Stubbing
315 |
316 | func (stubbings Stubbings) find(params []Param) *Stubbing {
317 | for i := len(stubbings) - 1; i >= 0; i-- {
318 | if stubbings[i].paramMatchers.Matches(params) {
319 | return stubbings[i]
320 | }
321 | }
322 | return nil
323 | }
324 |
325 | func (stubbings Stubbings) findByMatchers(paramMatchers Matchers) *Stubbing {
326 | for _, stubbing := range stubbings {
327 | if matchersEqual(stubbing.paramMatchers, paramMatchers) {
328 | return stubbing
329 | }
330 | }
331 | return nil
332 | }
333 |
334 | func (stubbings *Stubbings) removeByMatchers(paramMatchers Matchers) {
335 | for i, stubbing := range *stubbings {
336 | if matchersEqual(stubbing.paramMatchers, paramMatchers) {
337 | *stubbings = append((*stubbings)[:i], (*stubbings)[i+1:]...)
338 | }
339 | }
340 | }
341 |
342 | func matchersEqual(a, b Matchers) bool {
343 | if len(a) != len(b) {
344 | return false
345 | }
346 | for i := range a {
347 | if !reflect.DeepEqual(a[i], b[i]) {
348 | return false
349 | }
350 | }
351 | return true
352 | }
353 |
354 | type Stubbing struct {
355 | paramMatchers Matchers
356 | callbackSequence []func([]Param) ReturnValues
357 | sequencePointer int
358 | }
359 |
360 | func (stubbing *Stubbing) Invoke(params []Param) ReturnValues {
361 | defer func() {
362 | if stubbing.sequencePointer < len(stubbing.callbackSequence)-1 {
363 | stubbing.sequencePointer++
364 | }
365 | }()
366 | return stubbing.callbackSequence[stubbing.sequencePointer](params)
367 | }
368 |
369 | type Matchers []ArgumentMatcher
370 |
371 | func (matchers Matchers) Matches(params []Param) bool {
372 | if len(matchers) != len(params) { // Technically, this is not an error. Variadic arguments can cause this
373 | return false
374 | }
375 |
376 | for i := range params {
377 | if !matchers[i].Matches(params[i]) {
378 | return false
379 | }
380 | }
381 | return true
382 | }
383 |
384 | func (matchers *Matchers) append(matcher ArgumentMatcher) {
385 | *matchers = append(*matchers, matcher)
386 | }
387 |
388 | type ongoingStubbing struct {
389 | genericMock *GenericMock
390 | MethodName string
391 | ParamMatchers []ArgumentMatcher
392 | returnTypes []reflect.Type
393 | }
394 |
395 | func When(invocation ...interface{}) *ongoingStubbing {
396 | callIfIsFunc(invocation)
397 | verify.Argument(lastInvocation != nil,
398 | "When() requires an argument which has to be 'a method call on a mock'.")
399 | defer func() {
400 | lastInvocationMutex.Lock()
401 | lastInvocation = nil
402 | lastInvocationMutex.Unlock()
403 |
404 | globalArgMatchers = nil
405 | }()
406 | lastInvocation.genericMock.mockedMethods[lastInvocation.MethodName].removeLastInvocation()
407 |
408 | paramMatchers := paramMatchersFromArgMatchersOrParams(globalArgMatchers, lastInvocation.Params)
409 | lastInvocation.genericMock.reset(lastInvocation.MethodName, paramMatchers)
410 | return &ongoingStubbing{
411 | genericMock: lastInvocation.genericMock,
412 | MethodName: lastInvocation.MethodName,
413 | ParamMatchers: paramMatchers,
414 | returnTypes: lastInvocation.ReturnTypes,
415 | }
416 | }
417 |
418 | func callIfIsFunc(invocation []interface{}) {
419 | if len(invocation) == 1 {
420 | actualType := actualTypeOf(invocation[0])
421 | if actualType != nil && actualType.Kind() == reflect.Func && !reflect.ValueOf(invocation[0]).IsNil() {
422 | if !(actualType.NumIn() == 0 && actualType.NumOut() == 0) {
423 | panic("When using 'When' with function that does not return a value, " +
424 | "it expects a function with no arguments and no return value.")
425 | }
426 | reflect.ValueOf(invocation[0]).Call([]reflect.Value{})
427 | }
428 | }
429 | }
430 |
431 | // Deals with nils without panicking
432 | func actualTypeOf(iface interface{}) reflect.Type {
433 | defer func() { recover() }()
434 | return reflect.TypeOf(iface)
435 | }
436 |
437 | func paramMatchersFromArgMatchersOrParams(argMatchers []ArgumentMatcher, params []Param) []ArgumentMatcher {
438 | if len(argMatchers) != 0 {
439 | verifyArgMatcherUse(argMatchers, params)
440 | return argMatchers
441 | }
442 | return transformParamsIntoEqMatchers(params)
443 | }
444 |
445 | func verifyArgMatcherUse(argMatchers []ArgumentMatcher, params []Param) {
446 | verify.Argument(len(argMatchers) == len(params),
447 | "Invalid use of matchers!\n\n %v matchers expected, %v recorded.\n\n"+
448 | "This error may occur if matchers are combined with raw values:\n"+
449 | " //incorrect:\n"+
450 | " someFunc(Any[int](), \"raw String\")\n"+
451 | "When using matchers, all arguments have to be provided by matchers.\n"+
452 | "For example:\n"+
453 | " //correct:\n"+
454 | " someFunc(Any[int](), Eq(\"String by matcher\"))",
455 | len(params), len(argMatchers),
456 | )
457 | }
458 |
459 | func transformParamsIntoEqMatchers(params []Param) []ArgumentMatcher {
460 | paramMatchers := make([]ArgumentMatcher, len(params))
461 | for i, param := range params {
462 | paramMatchers[i] = &EqMatcher{Value: param}
463 | }
464 | return paramMatchers
465 | }
466 |
467 | var (
468 | genericMocksMutex sync.Mutex
469 | genericMocks = make(map[Mock]*GenericMock)
470 | )
471 |
472 | func GetGenericMockFrom(mock Mock) *GenericMock {
473 | genericMocksMutex.Lock()
474 | defer genericMocksMutex.Unlock()
475 | if genericMocks[mock] == nil {
476 | genericMocks[mock] = &GenericMock{
477 | mockedMethods: make(map[string]*mockedMethod),
478 | fail: mock.FailHandler(),
479 | }
480 | }
481 | return genericMocks[mock]
482 | }
483 |
484 | func (stubbing *ongoingStubbing) ThenReturn(values ...ReturnValue) *ongoingStubbing {
485 | checkAssignabilityOf(values, stubbing.returnTypes)
486 | stubbing.genericMock.stub(stubbing.MethodName, stubbing.ParamMatchers, values)
487 | return stubbing
488 | }
489 |
490 | func checkAssignabilityOf(stubbedReturnValues []ReturnValue, expectedReturnTypes []reflect.Type) {
491 | verify.Argument(len(stubbedReturnValues) == len(expectedReturnTypes),
492 | "Different number of return values")
493 | for i := range stubbedReturnValues {
494 | if stubbedReturnValues[i] == nil {
495 | switch expectedReturnTypes[i].Kind() {
496 | case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint,
497 | reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32,
498 | reflect.Float64, reflect.Complex64, reflect.Complex128, reflect.Array, reflect.String,
499 | reflect.Struct:
500 | panic("Return value 'nil' not assignable to return type " + expectedReturnTypes[i].Kind().String())
501 | }
502 | } else {
503 | verify.Argument(reflect.TypeOf(stubbedReturnValues[i]).AssignableTo(expectedReturnTypes[i]),
504 | "Return value of type %T not assignable to return type %v", stubbedReturnValues[i], expectedReturnTypes[i])
505 | }
506 | }
507 | }
508 |
509 | func (stubbing *ongoingStubbing) ThenPanic(v interface{}) *ongoingStubbing {
510 | stubbing.genericMock.stubWithCallback(
511 | stubbing.MethodName,
512 | stubbing.ParamMatchers,
513 | func([]Param) ReturnValues { panic(v) })
514 | return stubbing
515 | }
516 |
517 | func (stubbing *ongoingStubbing) Then(callback func([]Param) ReturnValues) *ongoingStubbing {
518 | stubbing.genericMock.stubWithCallback(
519 | stubbing.MethodName,
520 | stubbing.ParamMatchers,
521 | callback)
522 | return stubbing
523 | }
524 |
525 | type InOrderContext struct {
526 | invocationCounter int
527 | lastInvokedMethodName string
528 | lastInvokedMethodParams []Param
529 | }
530 |
531 | // ArgumentMatcher can be used to match arguments.
532 | type ArgumentMatcher interface {
533 | Matches(param Param) bool
534 | fmt.Stringer
535 | }
536 |
537 | // InvocationCountMatcher can be used to match invocation counts. It is guaranteed that
538 | // FailureMessage will always be called after Matches so an implementation can save state.
539 | type InvocationCountMatcher interface {
540 | Matches(param Param) bool
541 | FailureMessage() string
542 | }
543 |
544 | // Matcher can be used to match arguments as well as invocation counts.
545 | // Note that support for overlapping embedded interfaces was added in Go 1.14, which is why
546 | // ArgumentMatcher and InvocationCountMatcher are not embedded here.
547 | type Matcher interface {
548 | Matches(param Param) bool
549 | FailureMessage() string
550 | fmt.Stringer
551 | }
552 |
553 | func DumpInvocationsFor(mock Mock) {
554 | fmt.Print(SDumpInvocationsFor(mock))
555 | }
556 |
557 | func SDumpInvocationsFor(mock Mock) string {
558 | result := &bytes.Buffer{}
559 | for _, mockedMethod := range GetGenericMockFrom(mock).mockedMethods {
560 | for _, invocation := range mockedMethod.invocations {
561 | fmt.Fprintf(result, "Method invocation: %v (\n", mockedMethod.name)
562 | for _, param := range invocation.params {
563 | fmt.Fprint(result, format.Object(param, 1), ",\n")
564 | }
565 | fmt.Fprintln(result, ")")
566 | }
567 | }
568 | return result.String()
569 | }
570 |
571 | // InterceptMockFailures runs a given callback and returns an array of
572 | // failure messages generated by any Pegomock verifications within the callback.
573 | //
574 | // This is accomplished by temporarily replacing the *global* fail handler
575 | // with a fail handler that simply annotates failures. The original fail handler
576 | // is reset when InterceptMockFailures returns.
577 | func InterceptMockFailures(f func()) []string {
578 | originalHandler := GlobalFailHandler
579 | failures := []string{}
580 | RegisterMockFailHandler(func(message string, callerSkip ...int) {
581 | failures = append(failures, message)
582 | })
583 | f()
584 | RegisterMockFailHandler(originalHandler)
585 | return failures
586 | }
587 |
--------------------------------------------------------------------------------
/generate_test_mocks/xtools_go_loader/generate_test.go:
--------------------------------------------------------------------------------
1 | // Copyright 2015 Peter Goetz
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | package mockgen_test
16 |
17 | import (
18 | "os"
19 | "testing"
20 |
21 | . "github.com/onsi/ginkgo/v2"
22 | "github.com/petergtz/pegomock/v4/pegomock/filehandling"
23 | )
24 |
25 | func TestMockGeneration(t *testing.T) {
26 | RunSpecs(t, "Generating mocks with golang.org/x/tools/go/packages")
27 | }
28 |
29 | var _ = It("Generate mocks", func() {
30 | filehandling.GenerateMockFile(
31 | []string{"github.com/petergtz/pegomock/v4/test_interface", "Display"},
32 | "../../mock_display_test.go", "MockDisplay", "pegomock_test",
33 | "", false, os.Stdout)
34 |
35 | filehandling.GenerateMockFile(
36 | []string{"github.com/petergtz/pegomock/v4/test_interface", "GenericDisplay"},
37 | "../../mock_generic_display_test.go", "MockGenericDisplay", "pegomock_test",
38 | "", false, os.Stdout)
39 | })
40 |
--------------------------------------------------------------------------------
/ginkgo_compatible/in_order_context.go:
--------------------------------------------------------------------------------
1 | package mock
2 |
3 | type InOrderContext = pegomock.InOrderContext
4 |
--------------------------------------------------------------------------------
/ginkgo_compatible/matchers.go:
--------------------------------------------------------------------------------
1 | package mock
2 |
3 | import (
4 | "github.com/petergtz/pegomock/v4"
5 | )
6 |
7 | var (
8 | EqBool = pegomock.EqBool // Deprecated: Use Eq[T any](value T) instead.
9 | NotEqBool = pegomock.NotEqBool // Deprecated: Use NotEq[T any](value T) instead.
10 | AnyBool = pegomock.AnyBool // Deprecated: Use Any[T any]() instead.
11 | BoolThat = pegomock.BoolThat // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
12 | EqBoolSlice = pegomock.EqBoolSlice // Deprecated: Use Eq[T any](value T) instead.
13 | NotEqBoolSlice = pegomock.NotEqBoolSlice // Deprecated: Use NotEq[T any](value T) instead.
14 | AnyBoolSlice = pegomock.AnyBoolSlice // Deprecated: Use Any[T any]() instead.
15 | BoolSliceThat = pegomock.BoolSliceThat // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
16 |
17 | EqInt = pegomock.EqInt // Deprecated: Use Eq[T any](value T) instead.
18 | NotEqInt = pegomock.NotEqInt // Deprecated: Use NotEq[T any](value T) instead.
19 | AnyInt = pegomock.AnyInt // Deprecated: Use Any[T any]() instead.
20 | IntThat = pegomock.IntThat // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
21 | EqIntSlice = pegomock.EqIntSlice // Deprecated: Use Eq[T any](value T) instead.
22 | NotEqIntSlice = pegomock.NotEqIntSlice // Deprecated: Use NotEq[T any](value T) instead.
23 | AnyIntSlice = pegomock.AnyIntSlice // Deprecated: Use Any[T any]() instead.
24 | IntSliceThat = pegomock.IntSliceThat // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
25 |
26 | EqInt8 = pegomock.EqInt8 // Deprecated: Use Eq[T any](value T) instead.
27 | NotEqInt8 = pegomock.NotEqInt8 // Deprecated: Use NotEq[T any](value T) instead.
28 | AnyInt8 = pegomock.AnyInt8 // Deprecated: Use Any[T any]() instead.
29 | Int8That = pegomock.Int8That // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
30 | EqInt8Slice = pegomock.EqInt8Slice // Deprecated: Use Eq[T any](value T) instead.
31 | NotEqInt8Slice = pegomock.NotEqInt8Slice // Deprecated: Use NotEq[T any](value T) instead.
32 | AnyInt8Slice = pegomock.AnyInt8Slice // Deprecated: Use Any[T any]() instead.
33 | Int8SliceThat = pegomock.Int8SliceThat // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
34 |
35 | EqInt16 = pegomock.EqInt16 // Deprecated: Use Eq[T any](value T) instead.
36 | NotEqInt16 = pegomock.NotEqInt16 // Deprecated: Use NotEq[T any](value T) instead.
37 | AnyInt16 = pegomock.AnyInt16 // Deprecated: Use Any[T any]() instead.
38 | Int16That = pegomock.Int16That // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
39 | EqInt16Slice = pegomock.EqInt16Slice // Deprecated: Use Eq[T any](value T) instead.
40 | NotEqInt16Slice = pegomock.NotEqInt16Slice // Deprecated: Use NotEq[T any](value T) instead.
41 | AnyInt16Slice = pegomock.AnyInt16Slice // Deprecated: Use Any[T any]() instead.
42 | Int16SliceThat = pegomock.Int16SliceThat // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
43 |
44 | EqInt32 = pegomock.EqInt32 // Deprecated: Use Eq[T any](value T) instead.
45 | NotEqInt32 = pegomock.NotEqInt32 // Deprecated: Use NotEq[T any](value T) instead.
46 | AnyInt32 = pegomock.AnyInt32 // Deprecated: Use Any[T any]() instead.
47 | Int32That = pegomock.Int32That // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
48 | EqInt32Slice = pegomock.EqInt32Slice // Deprecated: Use Eq[T any](value T) instead.
49 | NotEqInt32Slice = pegomock.NotEqInt32Slice // Deprecated: Use NotEq[T any](value T) instead.
50 | AnyInt32Slice = pegomock.AnyInt32Slice // Deprecated: Use Any[T any]() instead.
51 | Int32SliceThat = pegomock.Int32SliceThat // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
52 |
53 | EqInt64 = pegomock.EqInt64 // Deprecated: Use Eq[T any](value T) instead.
54 | NotEqInt64 = pegomock.NotEqInt64 // Deprecated: Use NotEq[T any](value T) instead.
55 | AnyInt64 = pegomock.AnyInt64 // Deprecated: Use Any[T any]() instead.
56 | Int64That = pegomock.Int64That // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
57 | EqInt64Slice = pegomock.EqInt64Slice // Deprecated: Use Eq[T any](value T) instead.
58 | NotEqInt64Slice = pegomock.NotEqInt64Slice // Deprecated: Use NotEq[T any](value T) instead.
59 | AnyInt64Slice = pegomock.AnyInt64Slice // Deprecated: Use Any[T any]() instead.
60 | Int64SliceThat = pegomock.Int64SliceThat // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
61 |
62 | EqUint = pegomock.EqUint // Deprecated: Use Eq[T any](value T) instead.
63 | NotEqUint = pegomock.NotEqUint // Deprecated: Use NotEq[T any](value T) instead.
64 | AnyUint = pegomock.AnyUint // Deprecated: Use Any[T any]() instead.
65 | UintThat = pegomock.UintThat // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
66 | EqUintSlice = pegomock.EqUintSlice // Deprecated: Use Eq[T any](value T) instead.
67 | NotEqUintSlice = pegomock.NotEqUintSlice // Deprecated: Use NotEq[T any](value T) instead.
68 | AnyUintSlice = pegomock.AnyUintSlice // Deprecated: Use Any[T any]() instead.
69 | UintSliceThat = pegomock.UintSliceThat // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
70 |
71 | EqUint8 = pegomock.EqUint8 // Deprecated: Use Eq[T any](value T) instead.
72 | NotEqUint8 = pegomock.NotEqUint8 // Deprecated: Use NotEq[T any](value T) instead.
73 | AnyUint8 = pegomock.AnyUint8 // Deprecated: Use Any[T any]() instead.
74 | Uint8That = pegomock.Uint8That // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
75 | EqUint8Slice = pegomock.EqUint8Slice // Deprecated: Use Eq[T any](value T) instead.
76 | NotEqUint8Slice = pegomock.NotEqUint8Slice // Deprecated: Use NotEq[T any](value T) instead.
77 | AnyUint8Slice = pegomock.AnyUint8Slice // Deprecated: Use Any[T any]() instead.
78 | Uint8SliceThat = pegomock.Uint8SliceThat // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
79 |
80 | EqUint16 = pegomock.EqUint16 // Deprecated: Use Eq[T any](value T) instead.
81 | NotEqUint16 = pegomock.NotEqUint16 // Deprecated: Use NotEq[T any](value T) instead.
82 | AnyUint16 = pegomock.AnyUint16 // Deprecated: Use Any[T any]() instead.
83 | Uint16That = pegomock.Uint16That // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
84 | EqUint16Slice = pegomock.EqUint16Slice // Deprecated: Use Eq[T any](value T) instead.
85 | NotEqUint16Slice = pegomock.NotEqUint16Slice // Deprecated: Use NotEq[T any](value T) instead.
86 | AnyUint16Slice = pegomock.AnyUint16Slice // Deprecated: Use Any[T any]() instead.
87 | Uint16SliceThat = pegomock.Uint16SliceThat // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
88 |
89 | EqUint32 = pegomock.EqUint32 // Deprecated: Use Eq[T any](value T) instead.
90 | NotEqUint32 = pegomock.NotEqUint32 // Deprecated: Use NotEq[T any](value T) instead.
91 | AnyUint32 = pegomock.AnyUint32 // Deprecated: Use Any[T any]() instead.
92 | Uint32That = pegomock.Uint32That // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
93 | EqUint32Slice = pegomock.EqUint32Slice // Deprecated: Use Eq[T any](value T) instead.
94 | NotEqUint32Slice = pegomock.NotEqUint32Slice // Deprecated: Use NotEq[T any](value T) instead.
95 | AnyUint32Slice = pegomock.AnyUint32Slice // Deprecated: Use Any[T any]() instead.
96 | Uint32SliceThat = pegomock.Uint32SliceThat // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
97 |
98 | EqUint64 = pegomock.EqUint64 // Deprecated: Use Eq[T any](value T) instead.
99 | NotEqUint64 = pegomock.NotEqUint64 // Deprecated: Use NotEq[T any](value T) instead.
100 | AnyUint64 = pegomock.AnyUint64 // Deprecated: Use Any[T any]() instead.
101 | Uint64That = pegomock.Uint64That // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
102 | EqUint64Slice = pegomock.EqUint64Slice // Deprecated: Use Eq[T any](value T) instead.
103 | NotEqUint64Slice = pegomock.NotEqUint64Slice // Deprecated: Use NotEq[T any](value T) instead.
104 | AnyUint64Slice = pegomock.AnyUint64Slice // Deprecated: Use Any[T any]() instead.
105 | Uint64SliceThat = pegomock.Uint64SliceThat // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
106 |
107 | EqUintptr = pegomock.EqUintptr // Deprecated: Use Eq[T any](value T) instead.
108 | NotEqUintptr = pegomock.NotEqUintptr // Deprecated: Use NotEq[T any](value T) instead.
109 | AnyUintptr = pegomock.AnyUintptr // Deprecated: Use Any[T any]() instead.
110 | UintptrThat = pegomock.UintptrThat // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
111 | EqUintptrSlice = pegomock.EqUintptrSlice // Deprecated: Use Eq[T any](value T) instead.
112 | NotEqUintptrSlice = pegomock.NotEqUintptrSlice // Deprecated: Use NotEq[T any](value T) instead.
113 | AnyUintptrSlice = pegomock.AnyUintptrSlice // Deprecated: Use Any[T any]() instead.
114 | UintptrSliceThat = pegomock.UintptrSliceThat // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
115 |
116 | EqFloat32 = pegomock.EqFloat32 // Deprecated: Use Eq[T any](value T) instead.
117 | NotEqFloat32 = pegomock.NotEqFloat32 // Deprecated: Use NotEq[T any](value T) instead.
118 | AnyFloat32 = pegomock.AnyFloat32 // Deprecated: Use Any[T any]() instead.
119 | Float32That = pegomock.Float32That // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
120 | EqFloat32Slice = pegomock.EqFloat32Slice // Deprecated: Use Eq[T any](value T) instead.
121 | NotEqFloat32Slice = pegomock.NotEqFloat32Slice // Deprecated: Use NotEq[T any](value T) instead.
122 | AnyFloat32Slice = pegomock.AnyFloat32Slice // Deprecated: Use Any[T any]() instead.
123 | Float32SliceThat = pegomock.Float32SliceThat // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
124 |
125 | EqFloat64 = pegomock.EqFloat64 // Deprecated: Use Eq[T any](value T) instead.
126 | NotEqFloat64 = pegomock.NotEqFloat64 // Deprecated: Use NotEq[T any](value T) instead.
127 | AnyFloat64 = pegomock.AnyFloat64 // Deprecated: Use Any[T any]() instead.
128 | Float64That = pegomock.Float64That // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
129 | EqFloat64Slice = pegomock.EqFloat64Slice // Deprecated: Use Eq[T any](value T) instead.
130 | NotEqFloat64Slice = pegomock.NotEqFloat64Slice // Deprecated: Use NotEq[T any](value T) instead.
131 | AnyFloat64Slice = pegomock.AnyFloat64Slice // Deprecated: Use Any[T any]() instead.
132 | Float64SliceThat = pegomock.Float64SliceThat // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
133 |
134 | EqComplex64 = pegomock.EqComplex64 // Deprecated: Use Eq[T any](value T) instead.
135 | NotEqComplex64 = pegomock.NotEqComplex64 // Deprecated: Use NotEq[T any](value T) instead.
136 | AnyComplex64 = pegomock.AnyComplex64 // Deprecated: Use Any[T any]() instead.
137 | Complex64That = pegomock.Complex64That // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
138 | EqComplex64Slice = pegomock.EqComplex64Slice // Deprecated: Use Eq[T any](value T) instead.
139 | NotEqComplex64Slice = pegomock.NotEqComplex64Slice // Deprecated: Use NotEq[T any](value T) instead.
140 | AnyComplex64Slice = pegomock.AnyComplex64Slice // Deprecated: Use Any[T any]() instead.
141 | Complex64SliceThat = pegomock.Complex64SliceThat // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
142 |
143 | EqComplex128 = pegomock.EqComplex128 // Deprecated: Use Eq[T any](value T) instead.
144 | NotEqComplex128 = pegomock.NotEqComplex128 // Deprecated: Use NotEq[T any](value T) instead.
145 | AnyComplex128 = pegomock.AnyComplex128 // Deprecated: Use Any[T any]() instead.
146 | Complex128That = pegomock.Complex128That // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
147 | EqComplex128Slice = pegomock.EqComplex128Slice // Deprecated: Use Eq[T any](value T) instead.
148 | NotEqComplex128Slice = pegomock.NotEqComplex128Slice // Deprecated: Use NotEq[T any](value T) instead.
149 | AnyComplex128Slice = pegomock.AnyComplex128Slice // Deprecated: Use Any[T any]() instead.
150 | Complex128SliceThat = pegomock.Complex128SliceThat // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
151 |
152 | EqString = pegomock.EqString // Deprecated: Use Eq[T any](value T) instead.
153 | NotEqString = pegomock.NotEqString // Deprecated: Use NotEq[T any](value T) instead.
154 | AnyString = pegomock.AnyString // Deprecated: Use Any[T any]() instead.
155 | StringThat = pegomock.StringThat // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
156 | EqStringSlice = pegomock.EqStringSlice // Deprecated: Use Eq[T any](value T) instead.
157 | NotEqStringSlice = pegomock.NotEqStringSlice // Deprecated: Use NotEq[T any](value T) instead.
158 | AnyStringSlice = pegomock.AnyStringSlice // Deprecated: Use Any[T any]() instead.
159 | StringSliceThat = pegomock.StringSliceThat // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
160 |
161 | EqInterface = pegomock.EqInterface // Deprecated: Use Eq[T any](value T) instead.
162 | NotEqInterface = pegomock.NotEqInterface // Deprecated: Use NotEq[T any](value T) instead.
163 | AnyInterface = pegomock.AnyInterface // Deprecated: Use Any[T any]() instead.
164 | InterfaceThat = pegomock.InterfaceThat // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
165 | EqInterfaceSlice = pegomock.EqInterfaceSlice // Deprecated: Use Eq[T any](value T) instead.
166 | NotEqInterfaceSlice = pegomock.NotEqInterfaceSlice // Deprecated: Use NotEq[T any](value T) instead.
167 | AnyInterfaceSlice = pegomock.AnyInterfaceSlice // Deprecated: Use Any[T any]() instead.
168 | InterfaceSliceThat = pegomock.InterfaceSliceThat // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
169 |
170 | Times = pegomock.Times
171 | AtLeast = pegomock.AtLeast
172 | AtMost = pegomock.AtMost
173 | Never = pegomock.Never
174 | Once = pegomock.Once
175 | Twice = pegomock.Twice
176 | )
177 |
--------------------------------------------------------------------------------
/ginkgo_compatible/matchers_generic.go:
--------------------------------------------------------------------------------
1 | package mock
2 |
3 | func Eq[T any](value T) T { return pegomock.Eq(value) }
4 | func NotEq[T any](value T) T { return pegomock.NotEq(value) }
5 | func Any[T any]() T { return pegomock.Any[T]() }
6 |
7 | func ArgThat[T any](matcher pegomock.ArgumentMatcher) T { return pegomock.ArgThat[T](matcher) }
8 |
--------------------------------------------------------------------------------
/ginkgo_compatible/option.go:
--------------------------------------------------------------------------------
1 | package mock
2 |
3 | var OptionWithT = pegomock.WithT
4 |
--------------------------------------------------------------------------------
/ginkgo_compatible/whenever.go:
--------------------------------------------------------------------------------
1 | package mock
2 |
3 | var Whenever = pegomock.When
4 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/petergtz/pegomock/v4
2 |
3 | go 1.18
4 |
5 | require (
6 | github.com/alecthomas/kingpin/v2 v2.3.2
7 | github.com/onsi/ginkgo/v2 v2.9.2
8 | github.com/onsi/gomega v1.27.6
9 | github.com/samber/lo v1.38.1
10 | golang.org/x/tools v0.8.0
11 | )
12 |
13 | require (
14 | github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137 // indirect
15 | github.com/go-logr/logr v1.2.3 // indirect
16 | github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 // indirect
17 | github.com/google/go-cmp v0.5.9 // indirect
18 | github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38 // indirect
19 | github.com/xhit/go-str2duration/v2 v2.1.0 // indirect
20 | golang.org/x/exp v0.0.0-20220303212507-bbda1eaf7a17 // indirect
21 | golang.org/x/mod v0.10.0 // indirect
22 | golang.org/x/net v0.9.0 // indirect
23 | golang.org/x/sys v0.7.0 // indirect
24 | golang.org/x/text v0.9.0 // indirect
25 | gopkg.in/yaml.v3 v3.0.1 // indirect
26 | )
27 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/alecthomas/kingpin/v2 v2.3.2 h1:H0aULhgmSzN8xQ3nX1uxtdlTHYoPLu5AhHxWrKI6ocU=
2 | github.com/alecthomas/kingpin/v2 v2.3.2/go.mod h1:0gyi0zQnjuFk8xrkNKamJoyUo382HRL7ATRpFZCw6tE=
3 | github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137 h1:s6gZFSlWYmbqAuRjVTiNNhvNRfY2Wxp9nhfyel4rklc=
4 | github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE=
5 | github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
6 | github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
7 | github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
8 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
9 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
10 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
11 | github.com/go-logr/logr v1.2.3 h1:2DntVwHkVopvECVRSlL5PSo9eG+cAkDCuckLubN+rq0=
12 | github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
13 | github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI=
14 | github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572/go.mod h1:9Pwr4B2jHnOSGXyyzV8ROjYa2ojvAY6HCGYYfMoC3Ls=
15 | github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
16 | github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
17 | github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
18 | github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38 h1:yAJXTCF9TqKcTiHJAE8dj7HMvPfh66eeA2JYW7eFpSE=
19 | github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
20 | github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
21 | github.com/onsi/ginkgo/v2 v2.9.2 h1:BA2GMJOtfGAfagzYtrAlufIP0lq6QERkFmHLMLPwFSU=
22 | github.com/onsi/ginkgo/v2 v2.9.2/go.mod h1:WHcJJG2dIlcCqVfBAwUCrJxSPFb6v4azBwgxeMeDuts=
23 | github.com/onsi/gomega v1.27.6 h1:ENqfyGeS5AX/rlXDd/ETokDz93u0YufY1Pgxuy/PvWE=
24 | github.com/onsi/gomega v1.27.6/go.mod h1:PIQNjfQwkP3aQAH7lf7j87O/5FiNr+ZR8+ipb+qQlhg=
25 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
26 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
27 | github.com/samber/lo v1.38.1 h1:j2XEAqXKb09Am4ebOg31SpvzUTTs6EN3VfgeLUhPdXM=
28 | github.com/samber/lo v1.38.1/go.mod h1:+m/ZKRl6ClXCE2Lgf3MsQlWfh4bn1bz6CXEOxnEXnEA=
29 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
30 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
31 | github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
32 | github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
33 | github.com/xhit/go-str2duration/v2 v2.1.0 h1:lxklc02Drh6ynqX+DdPyp5pCKLUQpRT8bp8Ydu2Bstc=
34 | github.com/xhit/go-str2duration/v2 v2.1.0/go.mod h1:ohY8p+0f07DiV6Em5LKB0s2YpLtXVyJfNt1+BlmyAsU=
35 | golang.org/x/exp v0.0.0-20220303212507-bbda1eaf7a17 h1:3MTrJm4PyNL9NBqvYDSj3DHl46qQakyfqfWo4jgfaEM=
36 | golang.org/x/exp v0.0.0-20220303212507-bbda1eaf7a17/go.mod h1:lgLbSvA5ygNOMpwM/9anMpWVlVJ7Z+cHWq/eFuinpGE=
37 | golang.org/x/mod v0.10.0 h1:lFO9qtOdlre5W1jxS3r/4szv2/6iXxScdzjoBMXNhYk=
38 | golang.org/x/mod v0.10.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
39 | golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM=
40 | golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns=
41 | golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
42 | golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
43 | golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU=
44 | golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
45 | golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE=
46 | golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
47 | golang.org/x/tools v0.8.0 h1:vSDcovVPld282ceKgDimkRSC8kpaH1dgyc9UMzlt84Y=
48 | golang.org/x/tools v0.8.0/go.mod h1:JxBZ99ISMI5ViVkT1tr6tdNmXeTrcpVSD3vZ1RsRdN4=
49 | google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw=
50 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
51 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
52 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
53 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
54 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
55 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
56 |
--------------------------------------------------------------------------------
/internal/generate_matchers/matcher_generation.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | "reflect"
7 | "strings"
8 | )
9 |
10 | // Generate matchers:
11 | //
12 | // go generate github.com/petergtz/pegomock/v4/internal/generate_matchers
13 |
14 | //go:generate go run matcher_generation.go
15 | //go:generate go fmt ../../matcher_factories.go
16 | //go:generate go fmt ../../ginkgo_compatible/matchers.go
17 |
18 | func main() {
19 | mustWriteFile("../../matcher_factories.go", GenerateDefaultMatchersFile())
20 | mustWriteFile("../../ginkgo_compatible/matchers.go", GenerateGinkgoMatchersFile())
21 | }
22 |
23 | func mustWriteFile(path string, contents string) {
24 | err := os.WriteFile(path, []byte(contents), 0644)
25 | if err != nil {
26 | panic(err)
27 | }
28 | }
29 |
30 | func GenerateDefaultMatchersFile() string {
31 | contents := `package pegomock
32 |
33 | import (
34 | "reflect"
35 | )
36 | `
37 |
38 | for _, kind := range primitiveKinds {
39 | contents += fmt.Sprintf(`
40 | // Deprecated: Use Any[T any]() instead.
41 | func Any%[1]s() %[2]s {
42 | RegisterMatcher(NewAnyMatcher(reflect.TypeOf(%[3]s)))
43 | return %[4]s
44 | }
45 |
46 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
47 | func %[1]sThat(matcher ArgumentMatcher) %[2]s {
48 | RegisterMatcher(matcher)
49 | return %[4]s
50 | }
51 |
52 | // Deprecated: Use Any[T any]() instead.
53 | func Any%[1]sSlice() []%[2]s {
54 | RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf(%[3]s))))
55 | return nil
56 | }
57 |
58 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
59 | func %[1]sSliceThat(matcher ArgumentMatcher) []%[2]s {
60 | RegisterMatcher(matcher)
61 | return nil
62 | }
63 | `, strings.Title(kind.String()), kind.String(), exampleValue(kind), zeroValue(kind))
64 | }
65 |
66 | // hard-coding this for now as interface{} overall works slightly different than other types.
67 | return contents + `
68 | // Deprecated: Use Any[T any]() instead.
69 | func AnyInterface() interface{} {
70 | RegisterMatcher(NewAnyMatcher(reflect.TypeOf((*interface{})(nil)).Elem()))
71 | return nil
72 | }
73 |
74 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
75 | func InterfaceThat(matcher ArgumentMatcher) interface{} {
76 | RegisterMatcher(matcher)
77 | return nil
78 | }
79 |
80 | // Deprecated: Use Any[T any]() instead.
81 | func AnyInterfaceSlice() []interface{} {
82 | RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((*interface{})(nil)).Elem())))
83 | return nil
84 | }
85 |
86 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
87 | func InterfaceSliceThat(matcher ArgumentMatcher) []interface{} {
88 | RegisterMatcher(matcher)
89 | return nil
90 | }
91 | `
92 | }
93 |
94 | func GenerateGinkgoMatchersFile() string {
95 | contents := `package mock
96 |
97 | import (
98 | "github.com/petergtz/pegomock/v4"
99 | )
100 |
101 | var (`
102 |
103 | for _, kind := range append(primitiveKinds, reflect.Interface) {
104 | contents += fmt.Sprintf(`
105 | Eq%[1]s = pegomock.Eq%[1]s // Deprecated: Use Eq[T any](value T) instead.
106 | NotEq%[1]s = pegomock.NotEq%[1]s // Deprecated: Use NotEq[T any](value T) instead.
107 | Any%[1]s = pegomock.Any%[1]s // Deprecated: Use Any[T any]() instead.
108 | %[1]sThat = pegomock.%[1]sThat // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
109 | Eq%[1]sSlice = pegomock.Eq%[1]sSlice // Deprecated: Use Eq[T any](value T) instead.
110 | NotEq%[1]sSlice = pegomock.NotEq%[1]sSlice // Deprecated: Use NotEq[T any](value T) instead.
111 | Any%[1]sSlice = pegomock.Any%[1]sSlice // Deprecated: Use Any[T any]() instead.
112 | %[1]sSliceThat = pegomock.%[1]sSliceThat // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
113 | `, strings.Title(kind.String()))
114 | }
115 |
116 | return contents + `
117 | Times = pegomock.Times
118 | AtLeast = pegomock.AtLeast
119 | AtMost = pegomock.AtMost
120 | Never = pegomock.Never
121 | Once = pegomock.Once
122 | Twice = pegomock.Twice
123 | )
124 | `
125 | }
126 |
127 | var primitiveKinds = []reflect.Kind{
128 | reflect.Bool,
129 | reflect.Int,
130 | reflect.Int8,
131 | reflect.Int16,
132 | reflect.Int32,
133 | reflect.Int64,
134 | reflect.Uint,
135 | reflect.Uint8,
136 | reflect.Uint16,
137 | reflect.Uint32,
138 | reflect.Uint64,
139 | reflect.Uintptr,
140 | reflect.Float32,
141 | reflect.Float64,
142 | reflect.Complex64,
143 | reflect.Complex128,
144 | reflect.String,
145 | }
146 |
147 | // TODO generate: chan, func matchers
148 |
149 | func zeroValue(kind reflect.Kind) string {
150 | switch {
151 | case kind == reflect.Bool:
152 | return `false`
153 | case reflect.Int <= kind && kind <= reflect.Complex128:
154 | return `0`
155 | case kind == reflect.String:
156 | return `""`
157 | default:
158 | return `nil`
159 | }
160 | }
161 |
162 | func exampleValue(kind reflect.Kind) string {
163 | if kind == reflect.Bool || kind == reflect.Int || kind == reflect.String {
164 | return zeroValue(kind)
165 | }
166 | return fmt.Sprintf("(%s)(%s)", kind.String(), zeroValue(kind))
167 | }
168 |
--------------------------------------------------------------------------------
/internal/verify/verify.go:
--------------------------------------------------------------------------------
1 | package verify
2 |
3 | import "fmt"
4 |
5 | func Argument(arg bool, message string, a ...interface{}) {
6 | if !arg {
7 | panic(fmt.Sprintf(message, a...))
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/invocation_count_matchers.go:
--------------------------------------------------------------------------------
1 | // Copyright 2015 Peter Goetz
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | package pegomock
16 |
17 | func Times(numDesiredInvocations int) *EqMatcher {
18 | return &EqMatcher{Value: numDesiredInvocations}
19 | }
20 |
21 | func AtLeast(numDesiredInvocations int) *AtLeastIntMatcher {
22 | return &AtLeastIntMatcher{Value: numDesiredInvocations}
23 | }
24 |
25 | func AtMost(numDesiredInvocations int) *AtMostIntMatcher {
26 | return &AtMostIntMatcher{Value: numDesiredInvocations}
27 | }
28 |
29 | func Never() *EqMatcher {
30 | return &EqMatcher{Value: 0}
31 | }
32 |
33 | func Once() *EqMatcher {
34 | return &EqMatcher{Value: 1}
35 | }
36 |
37 | func Twice() *EqMatcher {
38 | return &EqMatcher{Value: 2}
39 | }
40 |
--------------------------------------------------------------------------------
/matcher.go:
--------------------------------------------------------------------------------
1 | package pegomock
2 |
3 | import (
4 | "fmt"
5 | "reflect"
6 |
7 | "sync"
8 |
9 | "github.com/petergtz/pegomock/v4/internal/verify"
10 | )
11 |
12 | type EqMatcher struct {
13 | Value Param
14 | actual Param
15 | sync.Mutex
16 | }
17 |
18 | func (matcher *EqMatcher) Matches(param Param) bool {
19 | matcher.Lock()
20 | defer matcher.Unlock()
21 |
22 | matcher.actual = param
23 | return reflect.DeepEqual(matcher.Value, param)
24 | }
25 |
26 | func (matcher *EqMatcher) FailureMessage() string {
27 | return fmt.Sprintf("Expected: %v; but got: %v", matcher.Value, matcher.actual)
28 | }
29 |
30 | func (matcher *EqMatcher) String() string {
31 | return fmt.Sprintf("Eq(%#v)", matcher.Value)
32 | }
33 |
34 | type NotEqMatcher struct {
35 | Value Param
36 | }
37 |
38 | func (matcher *NotEqMatcher) Matches(param Param) bool {
39 | return !reflect.DeepEqual(matcher.Value, param)
40 | }
41 |
42 | func (matcher *NotEqMatcher) FailureMessage() string {
43 | return fmt.Sprintf("Expected: not %v; but got: %v", matcher.Value, matcher.Value)
44 | }
45 |
46 | func (matcher *NotEqMatcher) String() string {
47 | return fmt.Sprintf("NotEq(%#v)", matcher.Value)
48 | }
49 |
50 | type AnyMatcher struct {
51 | Type reflect.Type
52 | actual reflect.Type
53 | sync.Mutex
54 | }
55 |
56 | func NewAnyMatcher(typ reflect.Type) *AnyMatcher {
57 | verify.Argument(typ != nil, "Must provide a non-nil type")
58 | return &AnyMatcher{Type: typ}
59 | }
60 |
61 | func (matcher *AnyMatcher) Matches(param Param) bool {
62 | matcher.Lock()
63 | defer matcher.Unlock()
64 |
65 | matcher.actual = reflect.TypeOf(param)
66 | if matcher.actual == nil {
67 | switch matcher.Type.Kind() {
68 | case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map,
69 | reflect.Ptr, reflect.Slice, reflect.UnsafePointer:
70 | return true
71 | default:
72 | return false
73 | }
74 | }
75 | return matcher.actual.AssignableTo(matcher.Type)
76 | }
77 |
78 | func (matcher *AnyMatcher) FailureMessage() string {
79 | return fmt.Sprintf("Expected: %v; but got: %v", matcher.Type, matcher.actual)
80 | }
81 |
82 | func (matcher *AnyMatcher) String() string {
83 | return fmt.Sprintf("Any(%v)", matcher.Type)
84 | }
85 |
86 | type AtLeastIntMatcher struct {
87 | Value int
88 | actual int
89 | }
90 |
91 | func (matcher *AtLeastIntMatcher) Matches(param Param) bool {
92 | matcher.actual = param.(int)
93 | return param.(int) >= matcher.Value
94 | }
95 |
96 | func (matcher *AtLeastIntMatcher) FailureMessage() string {
97 | return fmt.Sprintf("Expected: at least %v; but got: %v", matcher.Value, matcher.actual)
98 | }
99 |
100 | func (matcher *AtLeastIntMatcher) String() string {
101 | return fmt.Sprintf("AtLeast(%v)", matcher.Value)
102 | }
103 |
104 | type AtMostIntMatcher struct {
105 | Value int
106 | actual int
107 | }
108 |
109 | func (matcher *AtMostIntMatcher) Matches(param Param) bool {
110 | matcher.actual = param.(int)
111 | return param.(int) <= matcher.Value
112 | }
113 |
114 | func (matcher *AtMostIntMatcher) FailureMessage() string {
115 | return fmt.Sprintf("Expected: at most %v; but got: %v", matcher.Value, matcher.actual)
116 | }
117 |
118 | func (matcher *AtMostIntMatcher) String() string {
119 | return fmt.Sprintf("AtMost(%v)", matcher.Value)
120 | }
121 |
--------------------------------------------------------------------------------
/matcher_factories.go:
--------------------------------------------------------------------------------
1 | package pegomock
2 |
3 | import (
4 | "reflect"
5 | )
6 |
7 | // Deprecated: Use Any[T any]() instead.
8 | func AnyBool() bool {
9 | RegisterMatcher(NewAnyMatcher(reflect.TypeOf(false)))
10 | return false
11 | }
12 |
13 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
14 | func BoolThat(matcher ArgumentMatcher) bool {
15 | RegisterMatcher(matcher)
16 | return false
17 | }
18 |
19 | // Deprecated: Use Any[T any]() instead.
20 | func AnyBoolSlice() []bool {
21 | RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf(false))))
22 | return nil
23 | }
24 |
25 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
26 | func BoolSliceThat(matcher ArgumentMatcher) []bool {
27 | RegisterMatcher(matcher)
28 | return nil
29 | }
30 |
31 | // Deprecated: Use Any[T any]() instead.
32 | func AnyInt() int {
33 | RegisterMatcher(NewAnyMatcher(reflect.TypeOf(0)))
34 | return 0
35 | }
36 |
37 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
38 | func IntThat(matcher ArgumentMatcher) int {
39 | RegisterMatcher(matcher)
40 | return 0
41 | }
42 |
43 | // Deprecated: Use Any[T any]() instead.
44 | func AnyIntSlice() []int {
45 | RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf(0))))
46 | return nil
47 | }
48 |
49 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
50 | func IntSliceThat(matcher ArgumentMatcher) []int {
51 | RegisterMatcher(matcher)
52 | return nil
53 | }
54 |
55 | // Deprecated: Use Any[T any]() instead.
56 | func AnyInt8() int8 {
57 | RegisterMatcher(NewAnyMatcher(reflect.TypeOf((int8)(0))))
58 | return 0
59 | }
60 |
61 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
62 | func Int8That(matcher ArgumentMatcher) int8 {
63 | RegisterMatcher(matcher)
64 | return 0
65 | }
66 |
67 | // Deprecated: Use Any[T any]() instead.
68 | func AnyInt8Slice() []int8 {
69 | RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((int8)(0)))))
70 | return nil
71 | }
72 |
73 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
74 | func Int8SliceThat(matcher ArgumentMatcher) []int8 {
75 | RegisterMatcher(matcher)
76 | return nil
77 | }
78 |
79 | // Deprecated: Use Any[T any]() instead.
80 | func AnyInt16() int16 {
81 | RegisterMatcher(NewAnyMatcher(reflect.TypeOf((int16)(0))))
82 | return 0
83 | }
84 |
85 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
86 | func Int16That(matcher ArgumentMatcher) int16 {
87 | RegisterMatcher(matcher)
88 | return 0
89 | }
90 |
91 | // Deprecated: Use Any[T any]() instead.
92 | func AnyInt16Slice() []int16 {
93 | RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((int16)(0)))))
94 | return nil
95 | }
96 |
97 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
98 | func Int16SliceThat(matcher ArgumentMatcher) []int16 {
99 | RegisterMatcher(matcher)
100 | return nil
101 | }
102 |
103 | // Deprecated: Use Any[T any]() instead.
104 | func AnyInt32() int32 {
105 | RegisterMatcher(NewAnyMatcher(reflect.TypeOf((int32)(0))))
106 | return 0
107 | }
108 |
109 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
110 | func Int32That(matcher ArgumentMatcher) int32 {
111 | RegisterMatcher(matcher)
112 | return 0
113 | }
114 |
115 | // Deprecated: Use Any[T any]() instead.
116 | func AnyInt32Slice() []int32 {
117 | RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((int32)(0)))))
118 | return nil
119 | }
120 |
121 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
122 | func Int32SliceThat(matcher ArgumentMatcher) []int32 {
123 | RegisterMatcher(matcher)
124 | return nil
125 | }
126 |
127 | // Deprecated: Use Any[T any]() instead.
128 | func AnyInt64() int64 {
129 | RegisterMatcher(NewAnyMatcher(reflect.TypeOf((int64)(0))))
130 | return 0
131 | }
132 |
133 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
134 | func Int64That(matcher ArgumentMatcher) int64 {
135 | RegisterMatcher(matcher)
136 | return 0
137 | }
138 |
139 | // Deprecated: Use Any[T any]() instead.
140 | func AnyInt64Slice() []int64 {
141 | RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((int64)(0)))))
142 | return nil
143 | }
144 |
145 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
146 | func Int64SliceThat(matcher ArgumentMatcher) []int64 {
147 | RegisterMatcher(matcher)
148 | return nil
149 | }
150 |
151 | // Deprecated: Use Any[T any]() instead.
152 | func AnyUint() uint {
153 | RegisterMatcher(NewAnyMatcher(reflect.TypeOf((uint)(0))))
154 | return 0
155 | }
156 |
157 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
158 | func UintThat(matcher ArgumentMatcher) uint {
159 | RegisterMatcher(matcher)
160 | return 0
161 | }
162 |
163 | // Deprecated: Use Any[T any]() instead.
164 | func AnyUintSlice() []uint {
165 | RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((uint)(0)))))
166 | return nil
167 | }
168 |
169 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
170 | func UintSliceThat(matcher ArgumentMatcher) []uint {
171 | RegisterMatcher(matcher)
172 | return nil
173 | }
174 |
175 | // Deprecated: Use Any[T any]() instead.
176 | func AnyUint8() uint8 {
177 | RegisterMatcher(NewAnyMatcher(reflect.TypeOf((uint8)(0))))
178 | return 0
179 | }
180 |
181 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
182 | func Uint8That(matcher ArgumentMatcher) uint8 {
183 | RegisterMatcher(matcher)
184 | return 0
185 | }
186 |
187 | // Deprecated: Use Any[T any]() instead.
188 | func AnyUint8Slice() []uint8 {
189 | RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((uint8)(0)))))
190 | return nil
191 | }
192 |
193 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
194 | func Uint8SliceThat(matcher ArgumentMatcher) []uint8 {
195 | RegisterMatcher(matcher)
196 | return nil
197 | }
198 |
199 | // Deprecated: Use Any[T any]() instead.
200 | func AnyUint16() uint16 {
201 | RegisterMatcher(NewAnyMatcher(reflect.TypeOf((uint16)(0))))
202 | return 0
203 | }
204 |
205 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
206 | func Uint16That(matcher ArgumentMatcher) uint16 {
207 | RegisterMatcher(matcher)
208 | return 0
209 | }
210 |
211 | // Deprecated: Use Any[T any]() instead.
212 | func AnyUint16Slice() []uint16 {
213 | RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((uint16)(0)))))
214 | return nil
215 | }
216 |
217 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
218 | func Uint16SliceThat(matcher ArgumentMatcher) []uint16 {
219 | RegisterMatcher(matcher)
220 | return nil
221 | }
222 |
223 | // Deprecated: Use Any[T any]() instead.
224 | func AnyUint32() uint32 {
225 | RegisterMatcher(NewAnyMatcher(reflect.TypeOf((uint32)(0))))
226 | return 0
227 | }
228 |
229 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
230 | func Uint32That(matcher ArgumentMatcher) uint32 {
231 | RegisterMatcher(matcher)
232 | return 0
233 | }
234 |
235 | // Deprecated: Use Any[T any]() instead.
236 | func AnyUint32Slice() []uint32 {
237 | RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((uint32)(0)))))
238 | return nil
239 | }
240 |
241 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
242 | func Uint32SliceThat(matcher ArgumentMatcher) []uint32 {
243 | RegisterMatcher(matcher)
244 | return nil
245 | }
246 |
247 | // Deprecated: Use Any[T any]() instead.
248 | func AnyUint64() uint64 {
249 | RegisterMatcher(NewAnyMatcher(reflect.TypeOf((uint64)(0))))
250 | return 0
251 | }
252 |
253 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
254 | func Uint64That(matcher ArgumentMatcher) uint64 {
255 | RegisterMatcher(matcher)
256 | return 0
257 | }
258 |
259 | // Deprecated: Use Any[T any]() instead.
260 | func AnyUint64Slice() []uint64 {
261 | RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((uint64)(0)))))
262 | return nil
263 | }
264 |
265 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
266 | func Uint64SliceThat(matcher ArgumentMatcher) []uint64 {
267 | RegisterMatcher(matcher)
268 | return nil
269 | }
270 |
271 | // Deprecated: Use Any[T any]() instead.
272 | func AnyUintptr() uintptr {
273 | RegisterMatcher(NewAnyMatcher(reflect.TypeOf((uintptr)(0))))
274 | return 0
275 | }
276 |
277 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
278 | func UintptrThat(matcher ArgumentMatcher) uintptr {
279 | RegisterMatcher(matcher)
280 | return 0
281 | }
282 |
283 | // Deprecated: Use Any[T any]() instead.
284 | func AnyUintptrSlice() []uintptr {
285 | RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((uintptr)(0)))))
286 | return nil
287 | }
288 |
289 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
290 | func UintptrSliceThat(matcher ArgumentMatcher) []uintptr {
291 | RegisterMatcher(matcher)
292 | return nil
293 | }
294 |
295 | // Deprecated: Use Any[T any]() instead.
296 | func AnyFloat32() float32 {
297 | RegisterMatcher(NewAnyMatcher(reflect.TypeOf((float32)(0))))
298 | return 0
299 | }
300 |
301 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
302 | func Float32That(matcher ArgumentMatcher) float32 {
303 | RegisterMatcher(matcher)
304 | return 0
305 | }
306 |
307 | // Deprecated: Use Any[T any]() instead.
308 | func AnyFloat32Slice() []float32 {
309 | RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((float32)(0)))))
310 | return nil
311 | }
312 |
313 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
314 | func Float32SliceThat(matcher ArgumentMatcher) []float32 {
315 | RegisterMatcher(matcher)
316 | return nil
317 | }
318 |
319 | // Deprecated: Use Any[T any]() instead.
320 | func AnyFloat64() float64 {
321 | RegisterMatcher(NewAnyMatcher(reflect.TypeOf((float64)(0))))
322 | return 0
323 | }
324 |
325 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
326 | func Float64That(matcher ArgumentMatcher) float64 {
327 | RegisterMatcher(matcher)
328 | return 0
329 | }
330 |
331 | // Deprecated: Use Any[T any]() instead.
332 | func AnyFloat64Slice() []float64 {
333 | RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((float64)(0)))))
334 | return nil
335 | }
336 |
337 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
338 | func Float64SliceThat(matcher ArgumentMatcher) []float64 {
339 | RegisterMatcher(matcher)
340 | return nil
341 | }
342 |
343 | // Deprecated: Use Any[T any]() instead.
344 | func AnyComplex64() complex64 {
345 | RegisterMatcher(NewAnyMatcher(reflect.TypeOf((complex64)(0))))
346 | return 0
347 | }
348 |
349 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
350 | func Complex64That(matcher ArgumentMatcher) complex64 {
351 | RegisterMatcher(matcher)
352 | return 0
353 | }
354 |
355 | // Deprecated: Use Any[T any]() instead.
356 | func AnyComplex64Slice() []complex64 {
357 | RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((complex64)(0)))))
358 | return nil
359 | }
360 |
361 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
362 | func Complex64SliceThat(matcher ArgumentMatcher) []complex64 {
363 | RegisterMatcher(matcher)
364 | return nil
365 | }
366 |
367 | // Deprecated: Use Any[T any]() instead.
368 | func AnyComplex128() complex128 {
369 | RegisterMatcher(NewAnyMatcher(reflect.TypeOf((complex128)(0))))
370 | return 0
371 | }
372 |
373 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
374 | func Complex128That(matcher ArgumentMatcher) complex128 {
375 | RegisterMatcher(matcher)
376 | return 0
377 | }
378 |
379 | // Deprecated: Use Any[T any]() instead.
380 | func AnyComplex128Slice() []complex128 {
381 | RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((complex128)(0)))))
382 | return nil
383 | }
384 |
385 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
386 | func Complex128SliceThat(matcher ArgumentMatcher) []complex128 {
387 | RegisterMatcher(matcher)
388 | return nil
389 | }
390 |
391 | // Deprecated: Use Any[T any]() instead.
392 | func AnyString() string {
393 | RegisterMatcher(NewAnyMatcher(reflect.TypeOf("")))
394 | return ""
395 | }
396 |
397 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
398 | func StringThat(matcher ArgumentMatcher) string {
399 | RegisterMatcher(matcher)
400 | return ""
401 | }
402 |
403 | // Deprecated: Use Any[T any]() instead.
404 | func AnyStringSlice() []string {
405 | RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf(""))))
406 | return nil
407 | }
408 |
409 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
410 | func StringSliceThat(matcher ArgumentMatcher) []string {
411 | RegisterMatcher(matcher)
412 | return nil
413 | }
414 |
415 | // Deprecated: Use Any[T any]() instead.
416 | func AnyInterface() interface{} {
417 | RegisterMatcher(NewAnyMatcher(reflect.TypeOf((*interface{})(nil)).Elem()))
418 | return nil
419 | }
420 |
421 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
422 | func InterfaceThat(matcher ArgumentMatcher) interface{} {
423 | RegisterMatcher(matcher)
424 | return nil
425 | }
426 |
427 | // Deprecated: Use Any[T any]() instead.
428 | func AnyInterfaceSlice() []interface{} {
429 | RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((*interface{})(nil)).Elem())))
430 | return nil
431 | }
432 |
433 | // Deprecated: Use ArgThat[T any](matcher ArgumentMatcher) instead.
434 | func InterfaceSliceThat(matcher ArgumentMatcher) []interface{} {
435 | RegisterMatcher(matcher)
436 | return nil
437 | }
438 |
--------------------------------------------------------------------------------
/matchers_generic.go:
--------------------------------------------------------------------------------
1 | package pegomock
2 |
3 | import "reflect"
4 |
5 | func Eq[T any](value T) T {
6 | RegisterMatcher(&EqMatcher{Value: value})
7 | var t T
8 | return t
9 | }
10 |
11 | func NotEq[T any](value T) T {
12 | RegisterMatcher(&NotEqMatcher{Value: value})
13 | var t T
14 | return t
15 | }
16 |
17 | func Any[T any]() T {
18 | var t T
19 | RegisterMatcher(NewAnyMatcher(reflect.TypeOf(&t).Elem()))
20 | return t
21 | }
22 |
23 | func ArgThat[T any](matcher ArgumentMatcher) T {
24 | RegisterMatcher(matcher)
25 | var t T
26 | return t
27 | }
28 |
--------------------------------------------------------------------------------
/mockgen/mockgen.go:
--------------------------------------------------------------------------------
1 | // Copyright 2015 Peter Goetz
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | // Based on the work done in
16 | // https://github.com/golang/mock/blob/d581abfc04272f381d7a05e4b80163ea4e2b9447/mockgen/mockgen.go
17 |
18 | // Package mockgen generates mock implementations of Go interfaces.
19 | package mockgen
20 |
21 | import (
22 | "bytes"
23 | "fmt"
24 | "go/format"
25 | "go/token"
26 | "path"
27 | "sort"
28 | "strconv"
29 | "strings"
30 | "unicode"
31 |
32 | "github.com/petergtz/pegomock/v4/model"
33 | "github.com/samber/lo"
34 | )
35 |
36 | const mockFrameworkImportPath = "github.com/petergtz/pegomock/v4"
37 |
38 | func GenerateOutput(ast *model.Package, source, nameOut, packageOut, selfPackage string) []byte {
39 | g := generator{}
40 | g.generateCode(source, ast, nameOut, packageOut, selfPackage)
41 | return g.formattedOutput()
42 | }
43 |
44 | type generator struct {
45 | buf bytes.Buffer
46 | packageMap map[string]string // map from import path to package name
47 | }
48 |
49 | func (g *generator) generateCode(source string, pkg *model.Package, structName, pkgName, selfPackage string) {
50 | g.p("// Code generated by pegomock. DO NOT EDIT.")
51 | g.p("// Source: %v", source)
52 | g.emptyLine()
53 |
54 | importPaths := pkg.Imports()
55 | importPaths[mockFrameworkImportPath] = true
56 | packageMap, nonVendorPackageMap := generateUniquePackageNamesFor(importPaths)
57 | g.packageMap = packageMap
58 |
59 | g.p("package %v", pkgName)
60 | g.emptyLine()
61 | g.p("import (")
62 | g.p("\"reflect\"")
63 | g.p("\"time\"")
64 | for packagePath, packageName := range nonVendorPackageMap {
65 | if packagePath != selfPackage && packagePath != "time" && packagePath != "reflect" {
66 | g.p("%v %q", packageName, packagePath)
67 | }
68 | }
69 | for _, packagePath := range pkg.DotImports {
70 | g.p(". %q", packagePath)
71 | }
72 | g.p(")")
73 |
74 | for _, iface := range pkg.Interfaces {
75 | sName := structName
76 | if sName == "" {
77 | sName = "Mock" + iface.Name
78 | }
79 | g.generateMockFor(iface, sName, selfPackage)
80 | }
81 | }
82 |
83 | func generateUniquePackageNamesFor(importPaths map[string]bool) (packageMap, nonVendorPackageMap map[string]string) {
84 | packageMap = make(map[string]string, len(importPaths))
85 | nonVendorPackageMap = make(map[string]string, len(importPaths))
86 | packageNamesAlreadyUsed := make(map[string]bool, len(importPaths))
87 |
88 | sortedImportPaths := lo.Keys(importPaths)
89 | sort.Strings(sortedImportPaths)
90 | for _, importPath := range sortedImportPaths {
91 | sanitizedPackagePathBaseName := sanitize(path.Base(importPath))
92 |
93 | // Local names for an imported package can usually be the basename of the import path.
94 | // A couple of situations don't permit that, such as duplicate local names
95 | // (e.g. importing "html/template" and "text/template"), or where the basename is
96 | // a keyword (e.g. "foo/case").
97 | // try base0, base1, ...
98 | packageName := sanitizedPackagePathBaseName
99 | for i := 0; packageNamesAlreadyUsed[packageName] || token.Lookup(packageName).IsKeyword(); i++ {
100 | packageName = sanitizedPackagePathBaseName + strconv.Itoa(i)
101 | }
102 |
103 | // hardcode package name for pegomock, because it's hardcoded in the generated code too
104 | if importPath == mockFrameworkImportPath {
105 | packageName = "pegomock"
106 | }
107 |
108 | packageMap[importPath] = packageName
109 | packageNamesAlreadyUsed[packageName] = true
110 |
111 | nonVendorPackageMap[vendorCleaned(importPath)] = packageName
112 | }
113 | return
114 | }
115 |
116 | func vendorCleaned(importPath string) string {
117 | if split := strings.Split(importPath, "/vendor/"); len(split) > 1 {
118 | return split[1]
119 | }
120 | return importPath
121 | }
122 |
123 | // sanitize cleans up a string to make a suitable package name.
124 | // pkgName in reflect mode is the base name of the import path,
125 | // which might have characters that are illegal to have in package names.
126 | func sanitize(s string) string {
127 | t := ""
128 | for _, r := range s {
129 | if t == "" {
130 | if unicode.IsLetter(r) || r == '_' {
131 | t += string(r)
132 | continue
133 | }
134 | } else {
135 | if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' {
136 | t += string(r)
137 | continue
138 | }
139 | }
140 | t += "_"
141 | }
142 | if t == "_" {
143 | t = "x"
144 | }
145 | return t
146 | }
147 |
148 | func (g *generator) generateMockFor(iface *model.Interface, mockTypeName, selfPackage string) {
149 | typeParamNames := typeParamsStringFrom(iface.TypeParams, g.packageMap, selfPackage, false)
150 | typeParams := typeParamsStringFrom(iface.TypeParams, g.packageMap, selfPackage, true)
151 | g.generateMockType(mockTypeName, typeParams,
152 | typeParamNames)
153 | for _, method := range iface.Methods {
154 | g.generateMockMethod(mockTypeName, typeParamNames, method, selfPackage)
155 | g.emptyLine()
156 | }
157 | g.generateMockVerifyMethods(mockTypeName, typeParamNames)
158 | g.generateVerifierType(mockTypeName, typeParams, typeParamNames)
159 | for _, method := range iface.Methods {
160 | ongoingVerificationTypeName := fmt.Sprintf("%v_%v_OngoingVerification", mockTypeName, method.Name)
161 | args, argNames, argTypes, _ := argDataFor(method, g.packageMap, selfPackage)
162 | g.generateVerifierMethod(mockTypeName, typeParamNames, method, selfPackage, ongoingVerificationTypeName, args, argNames)
163 | g.generateOngoingVerificationType(mockTypeName, typeParams, typeParamNames, ongoingVerificationTypeName)
164 | g.generateOngoingVerificationGetCapturedArguments(ongoingVerificationTypeName, argNames, argTypes, typeParamNames)
165 | g.generateOngoingVerificationGetAllCapturedArguments(ongoingVerificationTypeName, typeParamNames, argTypes, method.Variadic != nil)
166 | }
167 | }
168 |
169 | func typeParamsStringFrom(params []*model.Parameter, packageMap map[string]string, pkgOverride string, withTypes bool) string {
170 | if len(params) == 0 {
171 | return ""
172 | }
173 | result := "["
174 | for i, param := range params {
175 | if i > 0 {
176 | result += ", "
177 | }
178 | result += param.Name
179 | if withTypes {
180 | result += " " + param.Type.String(packageMap, pkgOverride)
181 | }
182 | }
183 | return result + "]"
184 | }
185 |
186 | func (g *generator) generateMockType(mockTypeName string, typeParams string, typeParamNames string) {
187 | g.
188 | emptyLine().
189 | p("type %v%v struct {", mockTypeName, typeParams).
190 | p(" fail func(message string, callerSkip ...int)").
191 | p("}").
192 | emptyLine().
193 | p("func New%v%v(options ...pegomock.Option) *%v%v {", mockTypeName, typeParams, mockTypeName, typeParamNames).
194 | p(" mock := &%v%v{}", mockTypeName, typeParamNames).
195 | p(" for _, option := range options {").
196 | p(" option.Apply(mock)").
197 | p(" }").
198 | p(" return mock").
199 | p("}").
200 | emptyLine().
201 | p("func (mock *%v%v) SetFailHandler(fh pegomock.FailHandler) { mock.fail = fh }", mockTypeName, typeParamNames).
202 | p("func (mock *%v%v) FailHandler() pegomock.FailHandler { return mock.fail }", mockTypeName, typeParamNames).
203 | emptyLine()
204 | }
205 |
206 | // If non-empty, pkgOverride is the package in which unqualified types reside.
207 | func (g *generator) generateMockMethod(mockType string, typeParamNames string, method *model.Method, pkgOverride string) *generator {
208 | args, argNames, _, returnTypes := argDataFor(method, g.packageMap, pkgOverride)
209 | g.p("func (mock *%v%v) %v(%v) (%v) {", mockType, typeParamNames, method.Name, join(args), join(stringSliceFrom(returnTypes, g.packageMap, pkgOverride)))
210 | g.p("if mock == nil {").
211 | p(" panic(\"mock must not be nil. Use myMock := New%v().\")", mockType).
212 | p("}")
213 | g.GenerateParamsDeclaration(argNames, method.Variadic != nil)
214 | reflectReturnTypes := make([]string, len(returnTypes))
215 | for i, returnType := range returnTypes {
216 | reflectReturnTypes[i] = fmt.Sprintf("reflect.TypeOf((*%v)(nil)).Elem()", returnType.String(g.packageMap, pkgOverride))
217 | }
218 | resultAssignment := ""
219 | if len(method.Out) > 0 {
220 | resultAssignment = "_result :="
221 | }
222 | g.p("%v pegomock.GetGenericMockFrom(mock).Invoke(\"%v\", _params, []reflect.Type{%v})",
223 | resultAssignment, method.Name, strings.Join(reflectReturnTypes, ", "))
224 | if len(method.Out) > 0 {
225 | // TODO: translate LastInvocation into a Matcher so it can be used as key for Stubbings
226 | for i, returnType := range returnTypes {
227 | g.p("var _ret%v %v", i, returnType.String(g.packageMap, pkgOverride))
228 | }
229 | g.p("if len(_result) != 0 {")
230 | returnValues := make([]string, len(returnTypes))
231 | for i, returnType := range returnTypes {
232 | g.p("if _result[%v] != nil {", i)
233 | if chanType, isChanType := returnType.(*model.ChanType); isChanType && chanType.Dir != 0 {
234 | undirectedChanType := *chanType
235 | undirectedChanType.Dir = 0
236 | g.p("var ok bool").
237 | p(" _ret%v, ok = _result[%v].(%v)", i, i, undirectedChanType.String(g.packageMap, pkgOverride))
238 | g.p("if !ok{").
239 | p("_ret%v = _result[%v].(%v)", i, i, chanType.String(g.packageMap, pkgOverride)).
240 | p("}")
241 | } else {
242 | g.p("_ret%v = _result[%v].(%v)", i, i, returnType.String(g.packageMap, pkgOverride))
243 | }
244 | g.p("}")
245 | returnValues[i] = fmt.Sprintf("_ret%v", i)
246 | }
247 | g.p("}")
248 | g.p("return %v", strings.Join(returnValues, ", "))
249 | }
250 | g.p("}")
251 | return g
252 | }
253 |
254 | func (g *generator) generateVerifierType(interfaceName string, typeParams string, typeParamNames string) *generator {
255 | return g.
256 | p("type Verifier%v%v struct {", interfaceName, typeParams).
257 | p(" mock *%v%v", interfaceName, typeParamNames).
258 | p(" invocationCountMatcher pegomock.InvocationCountMatcher").
259 | p(" inOrderContext *pegomock.InOrderContext").
260 | p(" timeout time.Duration").
261 | p("}").
262 | emptyLine()
263 | }
264 |
265 | func (g *generator) generateMockVerifyMethods(interfaceName string, typeParamNames string) {
266 | g.
267 | p("func (mock *%v%v) VerifyWasCalledOnce() *Verifier%v%v {", interfaceName, typeParamNames, interfaceName, typeParamNames).
268 | p(" return &Verifier%v%v{", interfaceName, typeParamNames).
269 | p(" mock: mock,").
270 | p(" invocationCountMatcher: pegomock.Times(1),").
271 | p(" }").
272 | p("}").
273 | emptyLine().
274 | p("func (mock *%v%v) VerifyWasCalled(invocationCountMatcher pegomock.InvocationCountMatcher) *Verifier%v%v {", interfaceName, typeParamNames, interfaceName, typeParamNames).
275 | p(" return &Verifier%v%v{", interfaceName, typeParamNames).
276 | p(" mock: mock,").
277 | p(" invocationCountMatcher: invocationCountMatcher,").
278 | p(" }").
279 | p("}").
280 | emptyLine().
281 | p("func (mock *%v%v) VerifyWasCalledInOrder(invocationCountMatcher pegomock.InvocationCountMatcher, inOrderContext *pegomock.InOrderContext) *Verifier%v%v {", interfaceName, typeParamNames, interfaceName, typeParamNames).
282 | p(" return &Verifier%v%v{", interfaceName, typeParamNames).
283 | p(" mock: mock,").
284 | p(" invocationCountMatcher: invocationCountMatcher,").
285 | p(" inOrderContext: inOrderContext,").
286 | p(" }").
287 | p("}").
288 | emptyLine().
289 | p("func (mock *%v%v) VerifyWasCalledEventually(invocationCountMatcher pegomock.InvocationCountMatcher, timeout time.Duration) *Verifier%v%v {", interfaceName, typeParamNames, interfaceName, typeParamNames).
290 | p(" return &Verifier%v%v{", interfaceName, typeParamNames).
291 | p(" mock: mock,").
292 | p(" invocationCountMatcher: invocationCountMatcher,").
293 | p(" timeout: timeout,").
294 | p(" }").
295 | p("}").
296 | emptyLine()
297 | }
298 |
299 | func (g *generator) generateVerifierMethod(interfaceName string, typeParamNames string, method *model.Method, pkgOverride string, returnTypeString string, args []string, argNames []string) *generator {
300 | return g.
301 | p("func (verifier *Verifier%v%v) %v(%v) *%v%v {", interfaceName, typeParamNames, method.Name, join(args), returnTypeString, typeParamNames).
302 | GenerateParamsDeclaration(argNames, method.Variadic != nil).
303 | p("methodInvocations := pegomock.GetGenericMockFrom(verifier.mock).Verify(verifier.inOrderContext, verifier.invocationCountMatcher, \"%v\", _params, verifier.timeout)", method.Name).
304 | p("return &%v%v{mock: verifier.mock, methodInvocations: methodInvocations}", returnTypeString, typeParamNames).
305 | p("}")
306 | }
307 |
308 | func (g *generator) GenerateParamsDeclaration(argNames []string, isVariadic bool) *generator {
309 | if isVariadic {
310 | return g.
311 | p("_params := []pegomock.Param{%v}", strings.Join(argNames[0:len(argNames)-1], ", ")).
312 | p("for _, param := range %v {", argNames[len(argNames)-1]).
313 | p("_params = append(_params, param)").
314 | p("}")
315 | } else {
316 | return g.p("_params := []pegomock.Param{%v}", join(argNames))
317 | }
318 | }
319 |
320 | func (g *generator) generateOngoingVerificationType(interfaceName string, typeParams string, typeParamNames string, ongoingVerificationStructName string) *generator {
321 | return g.
322 | p("type %v%v struct {", ongoingVerificationStructName, typeParams).
323 | p("mock *%v%v", interfaceName, typeParamNames).
324 | p(" methodInvocations []pegomock.MethodInvocation").
325 | p("}").
326 | emptyLine()
327 | }
328 |
329 | func (g *generator) generateOngoingVerificationGetCapturedArguments(ongoingVerificationStructName string, argNames []string, argTypes []string, typeParamNames string) *generator {
330 | g.p("func (c *%v%v) GetCapturedArguments() (%v) {", ongoingVerificationStructName, typeParamNames, join(argTypes))
331 | if len(argNames) > 0 {
332 | indexedArgNames := make([]string, len(argNames))
333 | for i, argName := range argNames {
334 | indexedArgNames[i] = argName + "[len(" + argName + ")-1]"
335 | }
336 | g.p("%v := c.GetAllCapturedArguments()", join(argNames))
337 | g.p("return %v", strings.Join(indexedArgNames, ", "))
338 | }
339 | g.p("}")
340 | g.emptyLine()
341 | return g
342 | }
343 |
344 | func (g *generator) generateOngoingVerificationGetAllCapturedArguments(ongoingVerificationStructName string, typeParamNames string, argTypes []string, isVariadic bool) *generator {
345 | numArgs := len(argTypes)
346 | argsAsArray := make([]string, numArgs)
347 | for i, argType := range argTypes {
348 | argsAsArray[i] = fmt.Sprintf("_param%v []%v", i, argType)
349 | }
350 | g.p("func (c *%v%v) GetAllCapturedArguments() (%v) {", ongoingVerificationStructName, typeParamNames, strings.Join(argsAsArray, ", "))
351 | if numArgs > 0 {
352 | g.p("_params := pegomock.GetGenericMockFrom(c.mock).GetInvocationParams(c.methodInvocations)")
353 | g.p("if len(_params) > 0 {")
354 | for i, argType := range argTypes {
355 | if isVariadic && i == numArgs-1 {
356 | variadicBasicType := strings.Replace(argType, "[]", "", 1)
357 | g.
358 | p("_param%v = make([]%v, len(c.methodInvocations))", i, argType).
359 | p("for u := 0; u < len(c.methodInvocations); u++ {").
360 | p("_param%v[u] = make([]%v, len(_params)-%v)", i, variadicBasicType, i).
361 | p("for x := %v; x < len(_params); x++ {", i).
362 | p("if _params[x][u] != nil {").
363 | p("_param%v[u][x-%v] = _params[x][u].(%v)", i, i, variadicBasicType).
364 | p("}").
365 | p("}").
366 | p("}")
367 | break
368 | } else {
369 | // explicitly validate the length of the params slice to avoid out of bounds code smells
370 | g.p("if len(_params) > %v {", i)
371 | g.p("_param%v = make([]%v, len(c.methodInvocations))", i, argType)
372 | g.p("for u, param := range _params[%v] {", i)
373 | g.p("_param%v[u]=param.(%v)", i, argType)
374 | g.p("}")
375 | g.p("}")
376 | }
377 | }
378 | g.p("}")
379 | g.p("return")
380 | }
381 | g.p("}")
382 | g.emptyLine()
383 | return g
384 | }
385 |
386 | func argDataFor(method *model.Method, packageMap map[string]string, pkgOverride string) (
387 | args []string,
388 | argNames []string,
389 | argTypes []string,
390 | returnTypes []model.Type,
391 | ) {
392 | args = make([]string, len(method.In))
393 | argNames = make([]string, len(method.In))
394 | argTypes = make([]string, len(args))
395 | for i, arg := range method.In {
396 | argName := arg.Name
397 | if argName == "" {
398 | argName = fmt.Sprintf("_param%d", i)
399 | }
400 | argType := arg.Type.String(packageMap, pkgOverride)
401 | args[i] = argName + " " + argType
402 | argNames[i] = argName
403 | argTypes[i] = argType
404 | }
405 | if method.Variadic != nil {
406 | argName := method.Variadic.Name
407 | if argName == "" {
408 | argName = fmt.Sprintf("_param%d", len(method.In))
409 | }
410 | argType := method.Variadic.Type.String(packageMap, pkgOverride)
411 | args = append(args, argName+" ..."+argType)
412 | argNames = append(argNames, argName)
413 | argTypes = append(argTypes, "[]"+argType)
414 | }
415 | returnTypes = make([]model.Type, len(method.Out))
416 | for i, ret := range method.Out {
417 | returnTypes[i] = ret.Type
418 | }
419 | return
420 | }
421 |
422 | func stringSliceFrom(types []model.Type, packageMap map[string]string, pkgOverride string) []string {
423 | result := make([]string, len(types))
424 | for i, t := range types {
425 | result[i] = t.String(packageMap, pkgOverride)
426 | }
427 | return result
428 | }
429 |
430 | func (g *generator) p(format string, args ...interface{}) *generator {
431 | fmt.Fprintf(&g.buf, format+"\n", args...)
432 | return g
433 | }
434 |
435 | func (g *generator) emptyLine() *generator { return g.p("") }
436 |
437 | func (g *generator) formattedOutput() []byte {
438 | src, err := format.Source(g.buf.Bytes())
439 | if err != nil {
440 | panic(fmt.Errorf("Failed to format generated source code: %s\n%s", err, g.buf.String()))
441 | }
442 | return src
443 | }
444 |
445 | func join(s []string) string { return strings.Join(s, ", ") }
446 |
--------------------------------------------------------------------------------
/model/model.go:
--------------------------------------------------------------------------------
1 | // Copyright 2012 Google Inc.
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | // Package model contains the data model necessary for generating mock implementations.
16 | package model
17 |
18 | import (
19 | "fmt"
20 | "io"
21 | "strings"
22 | )
23 |
24 | // Package is a Go package. It may be a subset.
25 | type Package struct {
26 | Name string
27 | Interfaces []*Interface
28 | DotImports []string
29 | }
30 |
31 | func (pkg *Package) Print(w io.Writer) {
32 | fmt.Fprintf(w, "package %s\n", pkg.Name)
33 | for _, intf := range pkg.Interfaces {
34 | intf.Print(w)
35 | }
36 | }
37 |
38 | // Imports returns the imports needed by the Package as a set of import paths.
39 | func (pkg *Package) Imports() map[string]bool {
40 | im := make(map[string]bool)
41 | for _, intf := range pkg.Interfaces {
42 | intf.addImports(im)
43 | }
44 | return im
45 | }
46 |
47 | // Interface is a Go interface.
48 | type Interface struct {
49 | Name string
50 | TypeParams []*Parameter
51 | Methods []*Method
52 | }
53 |
54 | func (intf *Interface) Print(w io.Writer) {
55 | fmt.Fprintf(w, "interface %s\n", intf.Name)
56 | for _, m := range intf.Methods {
57 | m.Print(w)
58 | }
59 | }
60 |
61 | func (intf *Interface) addImports(im map[string]bool) {
62 | for _, tp := range intf.TypeParams {
63 | tp.Type.addImports(im)
64 | }
65 | for _, m := range intf.Methods {
66 | m.addImports(im)
67 | }
68 | }
69 |
70 | // Method is a single method of an interface.
71 | type Method struct {
72 | Name string
73 | In, Out []*Parameter
74 | Variadic *Parameter // may be nil
75 | }
76 |
77 | func (m *Method) Print(w io.Writer) {
78 | fmt.Fprintf(w, " - method %s\n", m.Name)
79 | if len(m.In) > 0 {
80 | fmt.Fprintf(w, " in:\n")
81 | for _, p := range m.In {
82 | p.Print(w)
83 | }
84 | }
85 | if m.Variadic != nil {
86 | fmt.Fprintf(w, " ...:\n")
87 | m.Variadic.Print(w)
88 | }
89 | if len(m.Out) > 0 {
90 | fmt.Fprintf(w, " out:\n")
91 | for _, p := range m.Out {
92 | p.Print(w)
93 | }
94 | }
95 | }
96 |
97 | func (m *Method) addImports(im map[string]bool) {
98 | for _, p := range m.In {
99 | p.Type.addImports(im)
100 | }
101 | if m.Variadic != nil {
102 | m.Variadic.Type.addImports(im)
103 | }
104 | for _, p := range m.Out {
105 | p.Type.addImports(im)
106 | }
107 | }
108 |
109 | // Parameter is an argument or return parameter of a method.
110 | type Parameter struct {
111 | Name string // may be empty
112 | Type Type
113 | }
114 |
115 | func (p *Parameter) Print(w io.Writer) {
116 | n := p.Name
117 | if n == "" {
118 | n = `""`
119 | }
120 | fmt.Fprintf(w, " - %v: %v\n", n, p.Type.String(nil, ""))
121 | }
122 |
123 | // Type is a Go type.
124 | type Type interface {
125 | String(pm map[string]string, pkgOverride string) string
126 | addImports(im map[string]bool)
127 | }
128 |
129 | // ArrayType is an array or slice type.
130 | type ArrayType struct {
131 | Len int // -1 for slices, >= 0 for arrays
132 | Type Type
133 | }
134 |
135 | func (at *ArrayType) String(pm map[string]string, pkgOverride string) string {
136 | s := "[]"
137 | if at.Len > -1 {
138 | s = fmt.Sprintf("[%d]", at.Len)
139 | }
140 | return s + at.Type.String(pm, pkgOverride)
141 | }
142 |
143 | func (at *ArrayType) addImports(im map[string]bool) { at.Type.addImports(im) }
144 |
145 | // ChanType is a channel type.
146 | type ChanType struct {
147 | Dir ChanDir // 0, 1 or 2
148 | Type Type
149 | }
150 |
151 | func (ct *ChanType) String(pm map[string]string, pkgOverride string) string {
152 | s := ct.Type.String(pm, pkgOverride)
153 | if ct.Dir == RecvDir {
154 | return "<-chan " + s
155 | }
156 | if ct.Dir == SendDir {
157 | return "chan<- " + s
158 | }
159 | return "chan " + s
160 | }
161 |
162 | func (ct *ChanType) addImports(im map[string]bool) { ct.Type.addImports(im) }
163 |
164 | // ChanDir is a channel direction.
165 | type ChanDir int
166 |
167 | const (
168 | RecvDir ChanDir = 1
169 | SendDir ChanDir = 2
170 | )
171 |
172 | // FuncType is a function type.
173 | type FuncType struct {
174 | In, Out []*Parameter
175 | Variadic *Parameter // may be nil
176 | }
177 |
178 | func (ft *FuncType) String(pm map[string]string, pkgOverride string) string {
179 | args := make([]string, len(ft.In))
180 | for i, p := range ft.In {
181 | args[i] = p.Type.String(pm, pkgOverride)
182 | }
183 | if ft.Variadic != nil {
184 | args = append(args, "..."+ft.Variadic.Type.String(pm, pkgOverride))
185 | }
186 | rets := make([]string, len(ft.Out))
187 | for i, p := range ft.Out {
188 | rets[i] = p.Type.String(pm, pkgOverride)
189 | }
190 | retString := strings.Join(rets, ", ")
191 | if nOut := len(ft.Out); nOut == 1 {
192 | retString = " " + retString
193 | } else if nOut > 1 {
194 | retString = " (" + retString + ")"
195 | }
196 | return "func(" + strings.Join(args, ", ") + ")" + retString
197 | }
198 |
199 | func (ft *FuncType) addImports(im map[string]bool) {
200 | for _, p := range ft.In {
201 | p.Type.addImports(im)
202 | }
203 | if ft.Variadic != nil {
204 | ft.Variadic.Type.addImports(im)
205 | }
206 | for _, p := range ft.Out {
207 | p.Type.addImports(im)
208 | }
209 | }
210 |
211 | // MapType is a map type.
212 | type MapType struct {
213 | Key, Value Type
214 | }
215 |
216 | func (mt *MapType) String(pm map[string]string, pkgOverride string) string {
217 | return "map[" + mt.Key.String(pm, pkgOverride) + "]" + mt.Value.String(pm, pkgOverride)
218 | }
219 |
220 | func (mt *MapType) addImports(im map[string]bool) {
221 | mt.Key.addImports(im)
222 | mt.Value.addImports(im)
223 | }
224 |
225 | // NamedType is an exported type in a package.
226 | type NamedType struct {
227 | Package string // may be empty
228 | Type string // TODO: should this be typed Type?
229 | }
230 |
231 | func (nt *NamedType) String(pm map[string]string, pkgOverride string) string {
232 | // TODO: is this right?
233 | if pkgOverride == nt.Package {
234 | return nt.Type
235 | }
236 | return pm[nt.Package] + "." + nt.Type
237 | }
238 | func (nt *NamedType) addImports(im map[string]bool) {
239 | if nt.Package != "" {
240 | im[nt.Package] = true
241 | }
242 | }
243 |
244 | // PointerType is a pointer to another type.
245 | type PointerType struct {
246 | Type Type
247 | }
248 |
249 | func (pt *PointerType) String(pm map[string]string, pkgOverride string) string {
250 | return "*" + pt.Type.String(pm, pkgOverride)
251 | }
252 | func (pt *PointerType) addImports(im map[string]bool) { pt.Type.addImports(im) }
253 |
254 | // PredeclaredType is a predeclared type such as "int".
255 | type PredeclaredType string
256 |
257 | func (pt PredeclaredType) String(pm map[string]string, pkgOverride string) string { return string(pt) }
258 | func (pt PredeclaredType) addImports(im map[string]bool) {}
259 |
--------------------------------------------------------------------------------
/modelgen/modelgen_test.go:
--------------------------------------------------------------------------------
1 | // Copyright 2015 Peter Goetz
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | package modelgen_test
16 |
17 | import (
18 | "testing"
19 |
20 | "github.com/petergtz/pegomock/v4/model"
21 | "github.com/petergtz/pegomock/v4/modelgen/xtools_packages"
22 |
23 | "github.com/onsi/ginkgo/v2"
24 | . "github.com/onsi/ginkgo/v2"
25 | "github.com/onsi/gomega"
26 | . "github.com/onsi/gomega"
27 | )
28 |
29 | func TestDSL(t *testing.T) {
30 | gomega.RegisterFailHandler(ginkgo.Fail)
31 | ginkgo.RunSpecs(t, "modelgen Suite")
32 | }
33 |
34 | type alphabetically []*model.Method
35 |
36 | func (a alphabetically) Len() int { return len(a) }
37 | func (a alphabetically) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
38 | func (a alphabetically) Less(i, j int) bool { return a[i].Name < a[j].Name }
39 |
40 | var _ = Describe("xtools_packages", func() {
41 |
42 | It("generates a model with the basic properties", func() {
43 | pkg, e := xtools_packages.GenerateModel("github.com/petergtz/pegomock/v4/modelgen/test_data/default_test_interface", "Display")
44 | Expect(e).NotTo(HaveOccurred())
45 |
46 | Expect(pkg.Name).To(Equal("test_interface"))
47 | Expect(pkg.Interfaces).To(HaveLen(1))
48 | Expect(pkg.Interfaces[0].Name).To(Equal("Display"))
49 |
50 | Expect(pkg.Interfaces[0].Methods).To(ContainElement(
51 | &model.Method{
52 | Name: "Show",
53 | In: []*model.Parameter{
54 | {
55 | Name: "_param0",
56 | Type: model.PredeclaredType("string"),
57 | },
58 | },
59 | },
60 | ))
61 |
62 | // TODO add more test cases
63 | })
64 | })
65 |
--------------------------------------------------------------------------------
/modelgen/test_data/default_test_interface/display.go:
--------------------------------------------------------------------------------
1 | // Copyright 2015 Peter Goetz
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | package test_interface
16 |
17 | import "net/http"
18 |
19 | // Display is some sample interface to be mocked.
20 | type Display interface {
21 | Flash(_param0 string, _param1 int)
22 | Show(_param0 string)
23 | SomeValue() string
24 | MultipleValues() (string, int, float32)
25 | MultipleParamsAndReturnValue(s string, i int) string
26 | ArrayParam(array []string)
27 | FloatParam(float32)
28 | InterfaceParam(interface{})
29 | InterfaceReturnValue() interface{}
30 | ErrorReturnValue() error
31 | ErrorParam(e error)
32 | NetHttpRequestParam(r http.Request)
33 | NetHttpRequestPtrParam(r *http.Request)
34 | FuncReturnValue() func()
35 | VariadicParam(v ...string)
36 | NormalAndVariadicParam(s string, i int, v ...string)
37 | }
38 |
--------------------------------------------------------------------------------
/modelgen/xtools_packages/packages.go:
--------------------------------------------------------------------------------
1 | package xtools_packages
2 |
3 | import (
4 | "errors"
5 | "fmt"
6 | "go/types"
7 | "path"
8 |
9 | "github.com/petergtz/pegomock/v4/model"
10 | "golang.org/x/tools/go/packages"
11 | )
12 |
13 | type Bla[K comparable, V Number] interface {
14 | SumNumbers(m map[K]V, i int, s string, a []float32, sss ...string) V
15 | }
16 |
17 | type Number interface {
18 | int64 | float64
19 | }
20 |
21 | type Blub[V Number, K comparable] struct{}
22 |
23 | func (b *Blub[V, K]) SumNumbers(m map[K]V, i int, _ string, a []float32, sss ...string) V {
24 | var s V
25 | for _, v := range m {
26 | s += v
27 | }
28 | return s
29 | }
30 |
31 | func NewBlub[K1 comparable, V1 Number]() Bla[K1, V1] {
32 | return &Blub[V1, K1]{}
33 | }
34 |
35 | func GenerateModel(importPath string, interfaceName string) (*model.Package, error) {
36 |
37 | pkgs, e := packages.Load(&packages.Config{Mode: packages.NeedTypes}, importPath)
38 | if e != nil {
39 | return nil, e
40 | }
41 | for _, pkg := range pkgs {
42 | scope := pkg.Types.Scope()
43 | obj := scope.Lookup(interfaceName)
44 | if obj == nil {
45 | continue
46 | }
47 |
48 | // from here, things follow the spec in https://tip.golang.org/ref/spec
49 | if iface, isIface := obj.Type().Underlying().(*types.Interface); isIface {
50 | return &model.Package{
51 | Name: path.Base(pkg.Types.Name()),
52 | Interfaces: []*model.Interface{{
53 | Name: interfaceName,
54 | Methods: modelMethodsFrom(iface),
55 | TypeParams: typeParamsFrom(obj.Type().(*types.Named).TypeParams()),
56 | }},
57 | }, nil
58 |
59 | }
60 | }
61 |
62 | return nil, errors.New("Did not find interface name \"" + interfaceName + "\"")
63 | }
64 |
65 | func modelMethodsFrom(iface *types.Interface) (modelMethods []*model.Method) {
66 | for i := 0; i < iface.NumMethods(); i++ {
67 | modelMethods = append(modelMethods, modelMethodFrom(iface.Method(i)))
68 | }
69 | return
70 | }
71 |
72 | func modelMethodFrom(method *types.Func) *model.Method {
73 | signature := method.Type().(*types.Signature)
74 | in, variadic := inParamsFrom(signature)
75 | return &model.Method{
76 | Name: method.Name(),
77 | In: in,
78 | Variadic: variadic,
79 | Out: outParamsFrom(signature),
80 | }
81 | }
82 |
83 | func inParamsFrom(signature *types.Signature) (in []*model.Parameter, variadic *model.Parameter) {
84 | for u := 0; u < signature.Params().Len(); u++ {
85 | if signature.Variadic() && u == signature.Params().Len()-1 {
86 | variadic = &model.Parameter{
87 | Name: signature.Params().At(u).Name(),
88 | Type: modelTypeFrom(signature.Params().At(u).Type().(*types.Slice).Elem()),
89 | }
90 | break
91 | }
92 | in = append(in, &model.Parameter{
93 | Name: signature.Params().At(u).Name(),
94 | Type: modelTypeFrom(signature.Params().At(u).Type()),
95 | })
96 | }
97 | return
98 | }
99 |
100 | func outParamsFrom(signature *types.Signature) (out []*model.Parameter) {
101 | if signature.Results() != nil {
102 | for u := 0; u < signature.Results().Len(); u++ {
103 | out = append(out, &model.Parameter{
104 | Name: signature.Results().At(u).Name(),
105 | Type: modelTypeFrom(signature.Results().At(u).Type()),
106 | })
107 | }
108 | }
109 | return
110 | }
111 |
112 | func modelTypeFrom(typesType types.Type) model.Type {
113 | switch typedTyp := typesType.(type) {
114 | case *types.Basic:
115 | if !predeclared(typedTyp.Kind()) {
116 | panic(fmt.Sprintf("Unexpected Basic Type %v", typedTyp.Name()))
117 | }
118 | return model.PredeclaredType(typedTyp.Name())
119 | case *types.Pointer:
120 | return &model.PointerType{
121 | Type: modelTypeFrom(typedTyp.Elem()),
122 | }
123 | case *types.Array:
124 | return &model.ArrayType{
125 | Len: int(typedTyp.Len()),
126 | Type: modelTypeFrom(typedTyp.Elem()),
127 | }
128 | case *types.Slice:
129 | return &model.ArrayType{
130 | Len: -1,
131 | Type: modelTypeFrom(typedTyp.Elem()),
132 | }
133 | case *types.Map:
134 | return &model.MapType{
135 | Key: modelTypeFrom(typedTyp.Key()),
136 | Value: modelTypeFrom(typedTyp.Elem()),
137 | }
138 | case *types.Chan:
139 | var dir model.ChanDir
140 | switch typedTyp.Dir() {
141 | case types.SendOnly:
142 | dir = model.SendDir
143 | case types.RecvOnly:
144 | dir = model.RecvDir
145 | default:
146 | dir = 0
147 | }
148 | return &model.ChanType{
149 | Dir: dir,
150 | Type: modelTypeFrom(typedTyp.Elem()),
151 | }
152 | case *types.Named:
153 | if typedTyp.Obj().Pkg() == nil {
154 | return model.PredeclaredType(typedTyp.Obj().Name())
155 | }
156 | return &model.NamedType{
157 | Package: typedTyp.Obj().Pkg().Path(),
158 | Type: typedTyp.Obj().Name(),
159 | }
160 | case *types.Interface, *types.Struct:
161 | return model.PredeclaredType(typedTyp.String())
162 | case *types.Signature:
163 | in, variadic := inParamsFrom(typedTyp)
164 | return &model.FuncType{In: in, Out: outParamsFrom(typedTyp), Variadic: variadic}
165 | case *types.TypeParam:
166 | return model.PredeclaredType(typedTyp.Obj().Name())
167 | default:
168 | panic(fmt.Sprintf("Unknown types.Type: %v (%T)", typesType, typesType))
169 | }
170 | }
171 |
172 | func typeParamsFrom(typeParams *types.TypeParamList) (result []*model.Parameter) {
173 | for i := 0; i < typeParams.Len(); i++ {
174 | result = append(result, &model.Parameter{
175 | Name: typeParams.At(i).Obj().Name(),
176 | Type: modelTypeFrom(typeParams.At(i).Constraint()),
177 | })
178 | }
179 | return
180 | }
181 |
182 | func predeclared(basicKind types.BasicKind) bool {
183 | return basicKind >= types.Bool && basicKind <= types.String
184 | }
185 |
--------------------------------------------------------------------------------
/modelgen/xtools_packages/packages_suite_test.go:
--------------------------------------------------------------------------------
1 | package xtools_packages_test
2 |
3 | import (
4 | "testing"
5 |
6 | . "github.com/onsi/ginkgo/v2"
7 | . "github.com/onsi/gomega"
8 | )
9 |
10 | func TestLoader(t *testing.T) {
11 | RegisterFailHandler(Fail)
12 | RunSpecs(t, "xtools_packages_test Suite")
13 | }
14 |
--------------------------------------------------------------------------------
/modelgen/xtools_packages/packages_test.go:
--------------------------------------------------------------------------------
1 | package xtools_packages_test
2 |
3 | import (
4 | . "github.com/onsi/ginkgo/v2"
5 | . "github.com/onsi/gomega"
6 | "github.com/petergtz/pegomock/v4/model"
7 |
8 | . "github.com/petergtz/pegomock/v4/modelgen/xtools_packages"
9 | )
10 |
11 | var _ = Describe("Packages", func() {
12 | Describe("GenerateModel", func() {
13 |
14 | It("finds all methods within interface", func() {
15 | pkg, e := GenerateModel("io", "Reader")
16 | Expect(e).NotTo(HaveOccurred())
17 | Expect(pkg.Interfaces).To(HaveLen(1))
18 | Expect(pkg.Interfaces[0].Name).To(Equal("Reader"))
19 | Expect(pkg.Interfaces[0].Methods).To(HaveLen(1))
20 | Expect(pkg.Interfaces[0].Methods[0].Name).To(Equal("Read"))
21 | })
22 |
23 | Context("using an interface with embedded interfaces", func() {
24 | It("finds all methods", func() {
25 | pkg, e := GenerateModel("io", "ReadCloser")
26 | Expect(e).NotTo(HaveOccurred())
27 | Expect(pkg.Interfaces).To(HaveLen(1))
28 | Expect(pkg.Interfaces[0].Name).To(Equal("ReadCloser"))
29 | Expect(pkg.Interfaces[0].Methods).To(HaveLen(2))
30 | Expect([]string{pkg.Interfaces[0].Methods[0].Name, pkg.Interfaces[0].Methods[1].Name}).To(
31 | ConsistOf("Read", "Close"))
32 | })
33 | })
34 |
35 | It("finds correct generic parameters in an interface", func() {
36 | pkg, e := GenerateModel("io", "Reader")
37 | Expect(e).NotTo(HaveOccurred())
38 | Expect(pkg.Interfaces).To(HaveLen(1))
39 | Expect(pkg.Interfaces[0].Name).To(Equal("Reader"))
40 | Expect(pkg.Interfaces[0].Methods).To(HaveLen(1))
41 | Expect(pkg.Interfaces[0].Methods[0].Name).To(Equal("Read"))
42 |
43 | pkg, e = GenerateModel("github.com/petergtz/pegomock/v4/modelgen/xtools_packages", "Bla")
44 | Expect(e).NotTo(HaveOccurred())
45 | Expect(pkg.Interfaces).To(HaveLen(1))
46 | Expect(pkg.Interfaces[0].Name).To(Equal("Bla"))
47 | Expect(pkg.Interfaces[0].TypeParams).To(ConsistOf(
48 | &model.Parameter{
49 | Name: "K",
50 | Type: model.PredeclaredType("comparable"),
51 | },
52 | &model.Parameter{
53 | Name: "V",
54 | Type: &model.NamedType{
55 | Package: "github.com/petergtz/pegomock/v4/modelgen/xtools_packages",
56 | Type: "Number",
57 | },
58 | },
59 | ))
60 | Expect(pkg.Interfaces[0].Methods).To(HaveLen(1))
61 | Expect(pkg.Interfaces[0].Methods[0].Name).To(Equal("SumNumbers"))
62 | })
63 |
64 | })
65 | })
66 |
--------------------------------------------------------------------------------
/panic_with_message_matcher_test.go:
--------------------------------------------------------------------------------
1 | package pegomock_test
2 |
3 | import (
4 | "fmt"
5 | "reflect"
6 |
7 | "github.com/onsi/gomega/format"
8 | "github.com/onsi/gomega/types"
9 | "github.com/petergtz/pegomock/v4/internal/verify"
10 | )
11 |
12 | type PanicWithMatcher struct {
13 | expectedWith interface{}
14 | actualWith interface{}
15 | }
16 |
17 | func PanicWith(object interface{}) types.GomegaMatcher {
18 | verify.Argument(object != nil, "You must provide a non-nil object to PanicWith")
19 | return &PanicWithMatcher{expectedWith: object}
20 | }
21 |
22 | func (matcher *PanicWithMatcher) Match(actual interface{}) (success bool, err error) {
23 | if actual == nil {
24 | return false, fmt.Errorf("PanicWithMatcher expects a non-nil actual.")
25 | }
26 |
27 | actualType := reflect.TypeOf(actual)
28 | if actualType.Kind() != reflect.Func {
29 | return false, fmt.Errorf("PanicWithMatcher expects a function. Got:\n%s", format.Object(actual, 1))
30 | }
31 | if !(actualType.NumIn() == 0 && actualType.NumOut() == 0) {
32 | return false, fmt.Errorf("PanicWithMatcher expects a function with no arguments and no return value. Got:\n%s", format.Object(actual, 1))
33 | }
34 |
35 | success = false
36 | defer func() {
37 | if object := recover(); object == matcher.expectedWith {
38 | success = true
39 | } else {
40 | matcher.actualWith = object
41 | }
42 | }()
43 |
44 | reflect.ValueOf(actual).Call([]reflect.Value{})
45 |
46 | return
47 | }
48 |
49 | func (matcher *PanicWithMatcher) FailureMessage(actual interface{}) (message string) {
50 | if matcher.actualWith == "" {
51 | return format.Message(actual, "to panic")
52 | } else {
53 | // TODO: can we reuse format.Message somehow?
54 | return fmt.Sprintf("Expected\n\t: %v\n\tpanicking with <%T>: %v\n\nto panic with\n\t<%T>: %v",
55 | actual, matcher.actualWith, matcher.actualWith, matcher.expectedWith, matcher.expectedWith)
56 | }
57 | }
58 |
59 | func (matcher *PanicWithMatcher) NegatedFailureMessage(actual interface{}) (message string) {
60 | if matcher.actualWith == "" {
61 | return format.Message(actual, "not to panic")
62 | } else {
63 | return fmt.Sprintf("Expected\n\t: %v\n\tpanicking with <%T>: %v\n\nnot to panic with\n\t<%T>: %v",
64 | actual, matcher.actualWith, matcher.actualWith, matcher.expectedWith, matcher.expectedWith)
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/panic_with_message_to_matcher_test.go:
--------------------------------------------------------------------------------
1 | package pegomock_test
2 |
3 | import (
4 | "fmt"
5 | "reflect"
6 |
7 | "github.com/onsi/gomega/format"
8 | "github.com/onsi/gomega/types"
9 | "github.com/petergtz/pegomock/v4/internal/verify"
10 | )
11 |
12 | type PanicWithMessageToMatcher struct {
13 | expectedWith types.GomegaMatcher
14 | actualWith interface{}
15 | }
16 |
17 | func PanicWithMessageTo(object types.GomegaMatcher) types.GomegaMatcher {
18 | verify.Argument(object != nil, "You must provide a non-nil object to PanicWith")
19 | return &PanicWithMessageToMatcher{expectedWith: object}
20 | }
21 |
22 | func (matcher *PanicWithMessageToMatcher) Match(actual interface{}) (success bool, err error) {
23 | if actual == nil {
24 | return false, fmt.Errorf("PanicWithMatcher expects a non-nil actual.")
25 | }
26 |
27 | actualType := reflect.TypeOf(actual)
28 | if actualType.Kind() != reflect.Func {
29 | return false, fmt.Errorf("PanicWithMatcher expects a function. Got:\n%s", format.Object(actual, 1))
30 | }
31 | if !(actualType.NumIn() == 0 && actualType.NumOut() == 0) {
32 | return false, fmt.Errorf("PanicWithMatcher expects a function with no arguments and no return value. Got:\n%s", format.Object(actual, 1))
33 | }
34 |
35 | success = false
36 | defer func() {
37 | if object := recover(); object != nil {
38 | var e error
39 | success, e = matcher.expectedWith.Match(object)
40 | if e != nil {
41 | // TODO is there something needed here?
42 | }
43 | if !success {
44 | matcher.actualWith = object
45 | }
46 | } else {
47 | matcher.actualWith = object
48 | }
49 | }()
50 |
51 | reflect.ValueOf(actual).Call([]reflect.Value{})
52 |
53 | return
54 | }
55 |
56 | func (matcher *PanicWithMessageToMatcher) FailureMessage(actual interface{}) (message string) {
57 | if matcher.actualWith == nil {
58 | return format.Message(actual, "to panic")
59 | } else {
60 | return fmt.Sprintf("Panic message does not match.\n\n%v", matcher.expectedWith.FailureMessage(matcher.actualWith))
61 | }
62 | }
63 |
64 | func (matcher *PanicWithMessageToMatcher) NegatedFailureMessage(actual interface{}) (message string) {
65 | panic("Not implemented")
66 | }
67 |
--------------------------------------------------------------------------------
/pegomock/filehandling/filehandling.go:
--------------------------------------------------------------------------------
1 | package filehandling
2 |
3 | import (
4 | "fmt"
5 | "io"
6 | "log"
7 | "os"
8 | "path/filepath"
9 | "strings"
10 |
11 | "github.com/petergtz/pegomock/v4/mockgen"
12 | "github.com/petergtz/pegomock/v4/modelgen/xtools_packages"
13 | )
14 |
15 | func GenerateMockFileInOutputDir(
16 | args []string,
17 | outputDirPath string,
18 | outputFilePathOverride string,
19 | nameOut string,
20 | packageOut string,
21 | selfPackage string,
22 | debugParser bool,
23 | out io.Writer) {
24 |
25 | // if a file path override is specified
26 | // ensure all directories in the path are created
27 | if outputFilePathOverride != "" {
28 | if err := os.MkdirAll(filepath.Dir(outputFilePathOverride), 0755); err != nil {
29 | panic(fmt.Errorf("failed to make output directory, error: %v", err))
30 | }
31 | }
32 |
33 | GenerateMockFile(
34 | args,
35 | OutputFilePath(args, outputDirPath, outputFilePathOverride),
36 | nameOut,
37 | packageOut,
38 | selfPackage,
39 | debugParser,
40 | out)
41 | }
42 |
43 | func OutputFilePath(args []string, outputDirPath string, outputFilePathOverride string) string {
44 | if outputFilePathOverride != "" {
45 | return outputFilePathOverride
46 | } else {
47 | return filepath.Join(outputDirPath, "mock_"+strings.ToLower(args[len(args)-1])+"_test.go")
48 | }
49 | }
50 |
51 | func GenerateMockFile(args []string, outputFilePath string, nameOut string, packageOut string, selfPackage string, debugParser bool, out io.Writer) {
52 | mockSourceCode := GenerateMockSourceCode(args, nameOut, packageOut, selfPackage, debugParser, out)
53 |
54 | err := os.WriteFile(outputFilePath, mockSourceCode, 0664)
55 | if err != nil {
56 | panic(fmt.Errorf("failed writing to destination: %v", err))
57 | }
58 | }
59 |
60 | func GenerateMockSourceCode(args []string, nameOut string, packageOut string, selfPackage string, debugParser bool, out io.Writer) []byte {
61 | if len(args) != 2 {
62 | log.Fatal("Expected exactly two arguments, but got " + fmt.Sprint(args))
63 | }
64 | ast, err := xtools_packages.GenerateModel(args[0], args[1])
65 | src := fmt.Sprintf("%v (interfaces: %v)", args[0], args[1])
66 | if err != nil {
67 | panic(fmt.Errorf("loading input failed: %v", err))
68 | }
69 |
70 | if debugParser {
71 | ast.Print(out)
72 | }
73 | return mockgen.GenerateOutput(ast, src, nameOut, packageOut, selfPackage)
74 | }
75 |
--------------------------------------------------------------------------------
/pegomock/main.go:
--------------------------------------------------------------------------------
1 | // Copyright 2016 Peter Goetz
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | package main
16 |
17 | import (
18 | "context"
19 | "io"
20 | "os"
21 | "path/filepath"
22 | "strings"
23 | "time"
24 |
25 | "github.com/alecthomas/kingpin/v2"
26 |
27 | "github.com/petergtz/pegomock/v4/pegomock/filehandling"
28 | "github.com/petergtz/pegomock/v4/pegomock/remove"
29 | "github.com/petergtz/pegomock/v4/pegomock/util"
30 | "github.com/petergtz/pegomock/v4/pegomock/watch"
31 | )
32 |
33 | var (
34 | app = kingpin.New("pegomock", "Generates mocks based on interfaces.")
35 | )
36 |
37 | func main() {
38 | Run(os.Args, os.Stderr, os.Stdin, app, context.Background())
39 | }
40 |
41 | func Run(cliArgs []string, out io.Writer, in io.Reader, app *kingpin.Application, ctx context.Context) {
42 |
43 | workingDir, err := os.Getwd()
44 | app.FatalIfError(err, "")
45 |
46 | var (
47 | generateCmd = app.Command("generate", "Generate mocks based on the args provided. ")
48 | destination = generateCmd.Flag("output", "Output file; defaults to mock__test.go.").Short('o').String()
49 | destinationDir = generateCmd.Flag("output-dir", "Output directory; defaults to current directory. If set, package name defaults to this directory, unless explicitly overridden.").String()
50 | mockNameOut = generateCmd.Flag("mock-name", "Struct name of the generated mock; defaults to the interface prefixed with Mock").String()
51 | packageOut = generateCmd.Flag("package", "Package of the generated code; defaults to the package from which pegomock was executed suffixed with _test").String()
52 | // TODO: self_package was taken as is from GoMock.
53 | // Still don't understand what it's really there for.
54 | // So for now it's not tested.
55 | selfPackage = generateCmd.Flag("self_package", "If set, the package this mock will be part of.").String()
56 | debugParser = generateCmd.Flag("debug", "Print debug information.").Short('d').Bool()
57 | generateCmdArgs = generateCmd.Arg("args", "A (optional) Go package path + space-separated interface or a .go file").Required().Strings()
58 |
59 | watchCmd = app.Command("watch", "Watch over changes in interfaces and regenerate mocks if changes are detected.")
60 | watchRecursive = watchCmd.Flag("recursive", "Recursively watch sub-directories as well.").Short('r').Bool()
61 | watchPackages = watchCmd.Arg("directories...", "One or more directories of Go packages to watch").Strings()
62 |
63 | removeMocks = app.Command("remove", "Remove mocks generated by Pegomock")
64 | removeRecursive = removeMocks.Flag("recursive", "Remove recursively in all sub-directories").Default("false").Short('r').Bool()
65 | removeNonInteractive = removeMocks.Flag("non-interactive", "Don't ask for confirmation. Useful for scripts.").Default("false").Short('n').Bool()
66 | removeDryRun = removeMocks.Flag("dry-run", "Just show what would be done. Don't delete anything.").Default("false").Short('d').Bool()
67 | removeSilent = removeMocks.Flag("silent", "Don't write anything to standard out.").Default("false").Short('s').Bool()
68 | removePath = removeMocks.Arg("path", "Use as root directory instead of current working directory.").Default("").String()
69 | )
70 |
71 | app.Writer(out)
72 | switch kingpin.MustParse(app.Parse(cliArgs[1:])) {
73 |
74 | case generateCmd.FullCommand():
75 | if err := util.ValidateArgs(*generateCmdArgs); err != nil {
76 | app.FatalUsage(err.Error())
77 | }
78 | sourceArgs, err := util.SourceArgs(*generateCmdArgs)
79 | if err != nil {
80 | app.FatalUsage(err.Error())
81 | }
82 |
83 | if *destination != "" && *destinationDir != "" {
84 | app.FatalUsage("Cannot use --output and --output-dir together")
85 | }
86 |
87 | realPackageOut := *packageOut
88 | if *packageOut == "" {
89 | realPackageOut, err = DeterminePackageNameIn(workingDir)
90 | app.FatalIfError(err, "Could not determine package name.")
91 | }
92 |
93 | realDestination := *destination
94 | realDestinationDir := workingDir
95 | if *destinationDir != "" {
96 | realDestinationDir, err = filepath.Abs(*destinationDir)
97 | app.FatalIfError(err, "")
98 | if *packageOut == "" {
99 | realPackageOut = filepath.Base(*destinationDir)
100 | }
101 | realDestination = filepath.Join(*destinationDir, "mock_"+strings.ToLower(sourceArgs[len(sourceArgs)-1])+".go")
102 | }
103 |
104 | filehandling.GenerateMockFileInOutputDir(
105 | sourceArgs,
106 | realDestinationDir,
107 | realDestination,
108 | *mockNameOut,
109 | realPackageOut,
110 | *selfPackage,
111 | *debugParser,
112 | out)
113 |
114 | case watchCmd.FullCommand():
115 | var targetPaths []string
116 | if len(*watchPackages) == 0 {
117 | targetPaths = []string{workingDir}
118 | } else {
119 | targetPaths = *watchPackages
120 | }
121 | watch.CreateWellKnownInterfaceListFilesIfNecessary(targetPaths)
122 | util.Ticker(watch.NewMockFileUpdater(targetPaths, *watchRecursive).Update, 2*time.Second, ctx)
123 |
124 | case removeMocks.FullCommand():
125 | path := *removePath
126 | if path == "" {
127 | var e error
128 | path, e = os.Getwd()
129 | app.FatalIfError(e, "Could not get current working directory")
130 | }
131 | remove.Remove(path, *removeRecursive, !*removeNonInteractive, *removeDryRun, *removeSilent, out, in, os.Remove)
132 | }
133 | }
134 |
--------------------------------------------------------------------------------
/pegomock/main_test.go:
--------------------------------------------------------------------------------
1 | // Copyright 2016 Peter Goetz
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | package main_test
16 |
17 | import (
18 | "bytes"
19 | "context"
20 | "os"
21 | "path/filepath"
22 | "strings"
23 | "time"
24 |
25 | "github.com/alecthomas/kingpin/v2"
26 |
27 | . "github.com/onsi/ginkgo/v2"
28 | . "github.com/onsi/gomega"
29 | main "github.com/petergtz/pegomock/v4/pegomock"
30 |
31 | . "github.com/petergtz/pegomock/v4/pegomock/testutil"
32 |
33 | "testing"
34 | )
35 |
36 | var (
37 | joinPath = filepath.Join
38 | )
39 |
40 | func TestPegomock(t *testing.T) {
41 | RegisterFailHandler(Fail)
42 | RunSpecs(t, "CLI Suite")
43 | }
44 |
45 | var _ = Describe("CLI", func() {
46 |
47 | var (
48 | packageDir, subPackageDir string
49 | app *kingpin.Application
50 | origWorkingDir string
51 | )
52 |
53 | BeforeEach(func() {
54 | tmpDir, e := filepath.EvalSymlinks(os.TempDir())
55 | Expect(e).NotTo(HaveOccurred())
56 | packageDir = filepath.Join(tmpDir, "pegomocktest")
57 | Expect(os.MkdirAll(packageDir, 0755)).To(Succeed())
58 | subPackageDir = joinPath(packageDir, "subpackage")
59 | Expect(os.MkdirAll(subPackageDir, 0755)).To(Succeed())
60 | //vendorPackageDir = joinPath(packageDir, "vendor", "github.com", "petergtz", "vendored_package")
61 | //Expect(os.MkdirAll(vendorPackageDir, 0755)).To(Succeed())
62 |
63 | origWorkingDir, e = os.Getwd()
64 | Expect(e).NotTo(HaveOccurred())
65 | e = os.Chdir(packageDir)
66 | Expect(e).NotTo(HaveOccurred())
67 |
68 | WriteFile(joinPath(packageDir, "go.mod"),
69 | `module pegomocktest
70 | go 1.18
71 | require (
72 | github.com/onsi/gomega v1.27.6 // indirect
73 | github.com/petergtz/pegomock/v4 v4.0.0
74 | )`)
75 |
76 | WriteFile(joinPath(packageDir, "mydisplay.go"),
77 | "package pegomocktest; type MyDisplay interface { Show(something string) }")
78 | WriteFile(joinPath(packageDir, "http_request_handler.go"),
79 | `package pegomocktest; import "net/http"; type RequestHandler interface { Handler(r *http.Request) }`)
80 | WriteFile(joinPath(subPackageDir, "subdisplay.go"),
81 | "package subpackage; type SubDisplay interface { ShowMe() }")
82 |
83 | app = kingpin.New("pegomock", "Generates mocks based on interfaces.")
84 | app.Terminate(func(int) { panic("Unexpected terminate") })
85 | })
86 |
87 | AfterEach(func() {
88 | Expect(os.RemoveAll(packageDir)).To(Succeed())
89 | _ = os.Chdir(origWorkingDir)
90 | })
91 |
92 | Describe(`"generate" command`, func() {
93 |
94 | Context(`with args "MyDisplay"`, func() {
95 |
96 | It(`generates a file mock_mydisplay_test.go that contains "package pegomocktest_test"`, func() {
97 | // The rationale behind this is:
98 | // mocks should always be part of test packages, because we don't
99 | // want them to be part of the production code.
100 | // But to be useful, they must still reside in the package, where
101 | // they are actually used.
102 |
103 | main.Run(cmd("pegomock generate MyDisplay"), os.Stdout, os.Stdin, app, context.Background())
104 |
105 | Expect(joinPath(packageDir, "mock_mydisplay_test.go")).To(SatisfyAll(
106 | BeAnExistingFile(),
107 | BeAFileContainingSubString("package pegomocktest_test")))
108 | })
109 |
110 | It(`sets the default mock name "DisplayMock"`, func() {
111 | main.Run(cmd("pegomock generate MyDisplay"), os.Stdout, os.Stdin, app, context.Background())
112 |
113 | Expect(joinPath(packageDir, "mock_mydisplay_test.go")).To(SatisfyAll(
114 | BeAnExistingFile(),
115 | BeAFileContainingSubString("MockMyDisplay")))
116 | })
117 | })
118 |
119 | Context(`with args "pegomocktest/subpackage SubDisplay"`, func() {
120 | It(`generates a file mock_subdisplay_test.go in "pegomocktest" that contains "package pegomocktest_test"`, func() {
121 | main.Run(cmd("pegomock generate pegomocktest/subpackage SubDisplay"), os.Stdout, os.Stdin, app, context.Background())
122 |
123 | Expect(joinPath(packageDir, "mock_subdisplay_test.go")).To(SatisfyAll(
124 | BeAnExistingFile(),
125 | BeAFileContainingSubString("package pegomocktest_test")))
126 | })
127 | })
128 |
129 | Context("with args -o where output override is a path with a non-existing directory", func() {
130 | It(`creates an output directory before code generation`, func() {
131 | var buf bytes.Buffer
132 | main.Run(cmd("pegomock generate MyDisplay -o testoutput/test.go"), &buf, os.Stdin, app, context.Background())
133 | Expect(joinPath(packageDir, "testoutput/test.go")).To(SatisfyAll(
134 | BeAnExistingFile(),
135 | BeAFileContainingSubString("package pegomocktest_test")))
136 | })
137 | })
138 |
139 | Context("with args --output-dir", func() {
140 | It(`creates the mocks in output dir with the dir's basename as package name`, func() {
141 | var buf bytes.Buffer
142 | main.Run(cmd("pegomock generate MyDisplay --output-dir fakes"), &buf, os.Stdin, app, context.Background())
143 | Expect(joinPath(packageDir, "fakes/mock_mydisplay.go")).To(SatisfyAll(
144 | BeAnExistingFile(),
145 | BeAFileContainingSubString("package fakes")))
146 | })
147 | })
148 |
149 | Context("with args --output-dir and --package", func() {
150 | It(`creates the mocks in output dir with the specified package name`, func() {
151 | var buf bytes.Buffer
152 | main.Run(cmd("pegomock generate MyDisplay --output-dir fakes --package other"), &buf, os.Stdin, app, context.Background())
153 |
154 | Expect(joinPath(packageDir, "fakes/mock_mydisplay.go")).To(SatisfyAll(
155 | BeAnExistingFile(),
156 | BeAFileContainingSubString("package other")))
157 | })
158 | })
159 |
160 | Context("with args --mock-name", func() {
161 | It(`sets the mock name as given`, func() {
162 | main.Run(cmd("pegomock generate MyDisplay --mock-name RenamedMock"), os.Stdout, os.Stdin, app, context.Background())
163 |
164 | Expect(joinPath(packageDir, "mock_mydisplay_test.go")).To(SatisfyAll(
165 | BeAnExistingFile(),
166 | BeAFileContainingSubString("RenamedMock")))
167 | })
168 | })
169 |
170 | Context("with too many args", func() {
171 |
172 | It(`reports an error and the usage`, func() {
173 | var buf bytes.Buffer
174 | Expect(func() {
175 | main.Run(cmd("pegomock generate with too many args"), &buf, os.Stdin, app, context.Background())
176 | }).To(Panic())
177 |
178 | Expect(buf.String()).To(ContainSubstring("Please provide exactly 1 interface or 1 package + 1 interface"))
179 | Expect(buf.String()).To(ContainSubstring("usage"))
180 | })
181 | })
182 |
183 | })
184 |
185 | Describe(`"watch" command`, func() {
186 |
187 | Context("with no further action", func() {
188 | It(`Creates a template file interfaces_to_mock in the current directory`, func(ctx SpecContext) {
189 | go main.Run(cmd("pegomock watch"), os.Stdout, os.Stdin, app, ctx)
190 | Eventually(func() string { return "interfaces_to_mock" }, "3s").Should(BeAnExistingFile())
191 | }, NodeTimeout(4*time.Second))
192 | })
193 |
194 | Context("after populating interfaces_to_mock with an actual interface", func() {
195 | It(`Eventually creates a file mock_mydisplay_test.go starting with "package pegomocktest_test"`, func(ctx SpecContext) {
196 | WriteFile(joinPath(packageDir, "interfaces_to_mock"), "MyDisplay")
197 |
198 | go main.Run(cmd("pegomock watch"), os.Stdout, os.Stdin, app, ctx)
199 |
200 | Eventually(joinPath(packageDir, "mock_mydisplay_test.go"), "3s").Should(SatisfyAll(
201 | BeAnExistingFile(),
202 | BeAFileContainingSubString("package pegomocktest_test")))
203 | }, NodeTimeout(4*time.Second))
204 | })
205 |
206 | })
207 |
208 | Describe(`"remove" command`, func() {
209 | Context("there are no mock files", func() {
210 | It("removes mock files in current directory only", func() {
211 | var buf bytes.Buffer
212 |
213 | main.Run(cmd("pegomock remove -n"), &buf, os.Stdin, app, context.Background())
214 |
215 | Expect(buf.String()).To(ContainSubstring(`No files to remove.`))
216 | })
217 | })
218 |
219 | Context("there are some mock files", func() {
220 | BeforeEach(func() {
221 | main.Run(cmd("pegomock generate MyDisplay"), os.Stdout, os.Stdin, app, context.Background())
222 | Expect(joinPath(packageDir, "mock_mydisplay_test.go")).To(SatisfyAll(
223 | BeAnExistingFile(),
224 | BeAFileContainingSubString("package pegomocktest_test")))
225 |
226 | main.Run(cmd("pegomock generate --output-dir "+subPackageDir+" pegomocktest/subpackage SubDisplay"), os.Stdout, os.Stdin, app, context.Background())
227 |
228 | Expect(joinPath(subPackageDir, "mock_subdisplay.go")).To(SatisfyAll(
229 | BeAnExistingFile(),
230 | BeAFileContainingSubString("package subpackage")))
231 | })
232 |
233 | Context("Non-interactive", func() {
234 | Context("non-recursive", func() {
235 | It("removes mock files in current directory only", func() {
236 | var buf bytes.Buffer
237 |
238 | main.Run(cmd("pegomock remove -n"), &buf, os.Stdin, app, context.Background())
239 |
240 | Expect(buf.String()).To(ContainSubstring(`Deleting the following files:
241 | ` + packageDir + `/mock_mydisplay_test.go`))
242 | Expect(joinPath(packageDir, "mock_mydisplay_test.go")).NotTo(BeAnExistingFile())
243 | Expect(joinPath(subPackageDir, "mock_subdisplay.go")).To(BeAnExistingFile())
244 | })
245 | })
246 |
247 | Context("recursive", func() {
248 | It("removes mock files recursively", func() {
249 | var buf bytes.Buffer
250 |
251 | main.Run(cmd("pegomock remove -n -r"), &buf, os.Stdin, app, context.Background())
252 |
253 | Expect(buf.String()).To(ContainSubstring(`Deleting the following files:
254 | ` + packageDir + `/mock_mydisplay_test.go
255 | ` + packageDir + `/subpackage/mock_subdisplay.go`))
256 | Expect(joinPath(packageDir, "mock_mydisplay_test.go")).NotTo(BeAnExistingFile())
257 | Expect(joinPath(subPackageDir, "mock_subdisplay.go")).NotTo(BeAnExistingFile())
258 | })
259 |
260 | })
261 |
262 | Context("Silent", func() {
263 | It("removes mock files, but provides no output", func() {
264 | var buf bytes.Buffer
265 |
266 | main.Run(cmd("pegomock remove -n --silent"), &buf, os.Stdin, app, context.Background())
267 |
268 | Expect(buf.String()).To(BeEmpty())
269 | Expect(joinPath(packageDir, "mock_mydisplay_test.go")).NotTo(BeAnExistingFile())
270 | Expect(joinPath(subPackageDir, "mock_subdisplay.go")).To(BeAnExistingFile())
271 | })
272 | })
273 |
274 | Context("with path", func() {
275 | It("removes mock files in path", func() {
276 | var buf bytes.Buffer
277 |
278 | main.Run(cmd("pegomock remove -n "+subPackageDir), &buf, os.Stdin, app, context.Background())
279 |
280 | Expect(buf.String()).To(ContainSubstring(`Deleting the following files:
281 | ` + packageDir + `/subpackage/mock_subdisplay.go`))
282 | Expect(joinPath(packageDir, "mock_mydisplay_test.go")).To(BeAnExistingFile())
283 | Expect(joinPath(subPackageDir, "mock_subdisplay.go")).NotTo(BeAnExistingFile())
284 | })
285 | })
286 | })
287 |
288 | Context("Interactive", func() {
289 | Context("confirming with yes", func() {
290 | It("removes mock files", func() {
291 | var buf bytes.Buffer
292 |
293 | main.Run(cmd("pegomock remove"), &buf, strings.NewReader("yes\n"), app, context.Background())
294 |
295 | Expect(buf.String()).To(ContainSubstring(`Will delete the following files:
296 | ` + packageDir + `/mock_mydisplay_test.go
297 | Continue? [y/n]:`))
298 | Expect(joinPath(packageDir, "mock_mydisplay_test.go")).NotTo(BeAnExistingFile())
299 | Expect(joinPath(subPackageDir, "mock_subdisplay.go")).To(BeAnExistingFile())
300 | })
301 | })
302 |
303 | Context("confirming with no", func() {
304 | It("does not remove mock files", func() {
305 | var buf bytes.Buffer
306 |
307 | main.Run(cmd("pegomock remove"), &buf, strings.NewReader("no\n"), app, context.Background())
308 |
309 | Expect(buf.String()).To(ContainSubstring(`Will delete the following files:
310 | ` + packageDir + `/mock_mydisplay_test.go
311 | Continue? [y/n]:`))
312 | Expect(joinPath(packageDir, "mock_mydisplay_test.go")).To(BeAnExistingFile())
313 | Expect(joinPath(subPackageDir, "mock_subdisplay.go")).To(BeAnExistingFile())
314 | })
315 | })
316 | })
317 |
318 | Context("dry-run", func() {
319 | It("removes no mock files, but provides files that would be deleted", func() {
320 | var buf bytes.Buffer
321 |
322 | main.Run(cmd("pegomock remove --dry-run"), &buf, os.Stdin, app, context.Background())
323 |
324 | Expect(buf.String()).To(ContainSubstring(`Would delete the following files:
325 | ` + packageDir + `/mock_mydisplay_test.go`))
326 | Expect(joinPath(packageDir, "mock_mydisplay_test.go")).To(BeAnExistingFile())
327 | Expect(joinPath(subPackageDir, "mock_subdisplay.go")).To(BeAnExistingFile())
328 | })
329 | })
330 | })
331 | })
332 |
333 | Context("with some unknown command", func() {
334 | It(`reports an error and the usage`, func() {
335 | var buf bytes.Buffer
336 | kingpin.CommandLine.Terminate(nil)
337 | kingpin.CommandLine.Writer(&buf)
338 |
339 | main.Run(cmd("pegomock some unknown command"), &buf, os.Stdin, app, context.Background())
340 | Expect(buf.String()).To(ContainSubstring("error"))
341 | })
342 | })
343 |
344 | })
345 |
346 | func cmd(line string) []string {
347 | return strings.Split(line, " ")
348 | }
349 |
--------------------------------------------------------------------------------
/pegomock/package_name.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "path/filepath"
5 | "strings"
6 | )
7 |
8 | func DeterminePackageNameIn(dir string) (string, error) {
9 | return strings.Replace(filepath.Base(dir), "-", "_", -1) + "_test", nil
10 | }
11 |
--------------------------------------------------------------------------------
/pegomock/package_name_test.go:
--------------------------------------------------------------------------------
1 | package main_test
2 |
3 | import (
4 | "go/build"
5 | "os"
6 |
7 | . "github.com/petergtz/pegomock/v4/pegomock/testutil"
8 |
9 | . "github.com/onsi/ginkgo/v2"
10 | . "github.com/onsi/gomega"
11 | main "github.com/petergtz/pegomock/v4/pegomock"
12 | )
13 |
14 | var _ = Describe("DetermineBla", func() {
15 | var (
16 | packageDir string
17 | )
18 | BeforeEach(func() {
19 | packageDir = joinPath(build.Default.GOPATH, "src", "package_dir")
20 | })
21 |
22 | JustBeforeEach(func() {
23 | Expect(os.MkdirAll(packageDir, 0755)).To(Succeed())
24 | })
25 |
26 | AfterEach(func() {
27 | Expect(os.RemoveAll(packageDir)).To(Succeed())
28 | })
29 |
30 | XContext("only one go file", func() {
31 | It("names the package name after package name + _test suffix", func() {
32 | WriteFile(joinPath(packageDir, "mydisplay.go"), "package package_name")
33 |
34 | Expect(main.DeterminePackageNameIn(packageDir)).To(Equal("package_name_test"))
35 | })
36 | })
37 |
38 | XContext("multiple go files with different package names", func() {
39 | It("fails", func() {
40 | WriteFile(joinPath(packageDir, "mydisplay.go"), "package package_name")
41 | WriteFile(joinPath(packageDir, "other.go"), "package other_package_name")
42 |
43 | _, e := main.DeterminePackageNameIn(packageDir)
44 | Expect(e).To(MatchError(ContainSubstring("Error while determining Go package")))
45 | })
46 | })
47 |
48 | XContext("go file and go test file", func() {
49 | It("determines the package name from the test file", func() {
50 | WriteFile(joinPath(packageDir, "mydisplay.go"), "package package_name")
51 | WriteFile(joinPath(packageDir, "mydisplay_test.go"), "package non_conventional_package_name_test")
52 |
53 | Expect(main.DeterminePackageNameIn(packageDir)).To(Equal("non_conventional_package_name_test"))
54 | })
55 | })
56 |
57 | Context("no files", func() {
58 | It("names the package after the directory name base", func() {
59 | Expect(main.DeterminePackageNameIn(packageDir)).To(Equal("package_dir_test"))
60 | })
61 |
62 | Context("current dir with dashes in name", func() {
63 | BeforeEach(func() {
64 | packageDir = joinPath(build.Default.GOPATH, "src", "package-dir-with-dashes")
65 | })
66 |
67 | It("names the package after the directory name base, but replace dashes with underscores", func() {
68 | Expect(main.DeterminePackageNameIn(packageDir)).To(Equal("package_dir_with_dashes_test"))
69 | })
70 | })
71 | })
72 |
73 | })
74 |
--------------------------------------------------------------------------------
/pegomock/remove/remove.go:
--------------------------------------------------------------------------------
1 | package remove
2 |
3 | import (
4 | "bufio"
5 | "fmt"
6 | "io"
7 | "io/ioutil"
8 | "os"
9 | "path/filepath"
10 | "sort"
11 | "strings"
12 |
13 | "errors"
14 | )
15 |
16 | func Remove(
17 | path string,
18 | recursive bool,
19 | shouldConfirm bool,
20 | dryRun bool,
21 | silent bool,
22 | out io.Writer,
23 | in io.Reader,
24 | removeFn func(path string) error,
25 | ) {
26 | filepaths, matchersDirPaths, e := getFilePaths(recursive, path, out)
27 | if e != nil {
28 | fmt.Fprintln(out, e.Error())
29 | return
30 | }
31 | if len(filepaths) == 0 {
32 | fmt.Fprintln(out, "No files to remove.")
33 | return
34 | }
35 |
36 | allFilepathsSorted := make([]string, len(filepaths))
37 | copy(allFilepathsSorted, filepaths)
38 | for matchersDirPath := range matchersDirPaths {
39 | if containsOnlyGeneratedFiles(matchersDirPath, allFilepathsSorted) {
40 | allFilepathsSorted = append(allFilepathsSorted, matchersDirPath)
41 | }
42 | }
43 | sort.Strings(allFilepathsSorted)
44 |
45 | if dryRun {
46 | fmt.Fprintln(out, "This is a dry-run. Would delete the following files:")
47 | fmt.Fprintln(out, strings.Join(allFilepathsSorted, "\n"))
48 | return
49 | }
50 |
51 | if shouldConfirm {
52 | fmt.Fprintln(out, "Will delete the following files:")
53 | fmt.Fprintln(out, strings.Join(allFilepathsSorted, "\n"))
54 | if !askForConfirmation("Continue?", in, out) {
55 | return
56 | }
57 | } else if !silent {
58 | fmt.Fprintln(out, "Deleting the following files:")
59 | fmt.Fprintln(out, strings.Join(allFilepathsSorted, "\n"))
60 | }
61 |
62 | var errs []error
63 | for _, filepath := range filepaths {
64 | e := removeFn(filepath)
65 | if e != nil {
66 | errs = append(errs, e)
67 | }
68 | }
69 | for matcherPath := range matchersDirPaths {
70 | if dirEmpty(matcherPath) {
71 | e := removeFn(matcherPath)
72 | if e != nil {
73 | errs = append(errs, e)
74 | }
75 | }
76 | }
77 | if len(errs) > 0 {
78 | fmt.Fprintf(out, "There were some errors when trying to delete files: %v", errs)
79 | }
80 | }
81 | func containsOnlyGeneratedFiles(matchersDirPath string, generatedFilenames []string) bool {
82 | f, e := os.Open(matchersDirPath)
83 | if e != nil {
84 | return false
85 | }
86 | defer f.Close()
87 | filenamesInMatchersDir, e := f.Readdirnames(-1)
88 | if e != nil {
89 | return false
90 | }
91 | if len(difference(matchersDirPath, filenamesInMatchersDir, generatedFilenames)) == 0 {
92 | return true
93 | }
94 | return false
95 | }
96 |
97 | func difference(root string, a, b []string) map[string]bool {
98 | m := make(map[string]bool, len(b))
99 | for _, s := range a {
100 | m[filepath.Join(root, s)] = true
101 | }
102 | for _, s := range b {
103 | delete(m, s)
104 | }
105 | return m
106 | }
107 |
108 | func dirEmpty(path string) bool {
109 | f, e := os.Open(path)
110 | if e != nil {
111 | return false
112 | }
113 | defer f.Close()
114 |
115 | _, e = f.Readdirnames(1)
116 | return e == io.EOF
117 | }
118 |
119 | func getFilePaths(recursive bool, path string, out io.Writer) ([]string, map[string]bool, error) {
120 | matcherPaths := make(map[string]bool)
121 | var walk func(root string, walkFn filepath.WalkFunc) error
122 | if recursive {
123 | walk = filepath.Walk
124 | } else {
125 | walk = walkFilesInDir
126 | }
127 | filepaths := make([]string, 0)
128 | e := walk(path, func(path string, info os.FileInfo, err error) error {
129 | if !info.IsDir() && filepath.Ext(path) == ".go" && isPegomockGenerated(path, out) {
130 | filepaths = append(filepaths, path)
131 | if filepath.Base(filepath.Dir(path)) == "matchers" {
132 | matcherPaths[filepath.Dir(path)] = true
133 | }
134 | }
135 | return nil
136 | })
137 | if e != nil {
138 | return nil, nil, errors.New("Could not get files in path " + path)
139 | }
140 | return filepaths, matcherPaths, nil
141 | }
142 |
143 | func walkFilesInDir(path string, walk filepath.WalkFunc) error {
144 | fileInfos, e := ioutil.ReadDir(path)
145 | if e != nil {
146 | errors.New("Could not get files in path " + path)
147 | }
148 | for _, info := range fileInfos {
149 | walk(filepath.Join(path, info.Name()), info, nil)
150 | }
151 | return nil
152 | }
153 |
154 | func isPegomockGenerated(path string, out io.Writer) bool {
155 | file, e := os.Open(path)
156 | if e != nil {
157 | fmt.Fprintf(out, "Could not open file %v. Error: %v\n", path, e)
158 | return false
159 | }
160 | defer func() {
161 | if closeErr := file.Close(); closeErr != nil {
162 | fmt.Fprintf(out, "Could not close file %v. Error: %v\n", path, closeErr)
163 | }
164 | }()
165 |
166 | b := make([]byte, 50)
167 | _, e = file.Read(b)
168 | if e != nil {
169 | fmt.Fprintf(out, "Could not read from file %v. Error: %v\n", path, e)
170 | return false
171 | }
172 | if strings.Contains(string(b), "// Code generated by pegomock. DO NOT EDIT.") {
173 | return true
174 | }
175 | return false
176 | }
177 |
178 | func askForConfirmation(s string, in io.Reader, out io.Writer) bool {
179 | reader := bufio.NewReader(in)
180 |
181 | for {
182 | fmt.Fprintf(out, "%s [y/n]: ", s)
183 |
184 | response, err := reader.ReadString('\n')
185 | if err != nil {
186 | fmt.Fprintln(out, "Could not get confirmation from StdIn", err)
187 | return false
188 | }
189 |
190 | response = strings.ToLower(strings.TrimSpace(response))
191 |
192 | if response == "y" || response == "yes" {
193 | return true
194 | } else if response == "n" || response == "no" {
195 | return false
196 | }
197 | }
198 | }
199 |
--------------------------------------------------------------------------------
/pegomock/testutil/gomega_file_matcher.go:
--------------------------------------------------------------------------------
1 | // Copyright 2016 Peter Goetz
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | package testutil
16 |
17 | import (
18 | "fmt"
19 | "io/ioutil"
20 | "strings"
21 | )
22 |
23 | type fileContentSubStringMatcher struct {
24 | substring string
25 | fileContent []byte
26 | }
27 |
28 | func BeAFileContainingSubString(substring string) *fileContentSubStringMatcher {
29 | return &fileContentSubStringMatcher{substring: substring}
30 | }
31 |
32 | func (matcher *fileContentSubStringMatcher) Match(actual interface{}) (bool, error) {
33 | actualFilePath, ok := actual.(string)
34 | if !ok {
35 | return false, fmt.Errorf("matcher expects the actual file path as string")
36 | }
37 | var err error
38 | matcher.fileContent, err = ioutil.ReadFile(actualFilePath)
39 | if err != nil {
40 | return false, fmt.Errorf("File content could not be read due to: %v", err)
41 | }
42 | return strings.Contains(string(matcher.fileContent), matcher.substring), nil
43 | }
44 |
45 | func (matcher *fileContentSubStringMatcher) FailureMessage(actual interface{}) string {
46 | return fmt.Sprintf("Expected:\n\t%s to contain a substring '%s'\n\nBut got:\n%s",
47 | actual, matcher.substring, matcher.fileContent)
48 | }
49 |
50 | func (matcher *fileContentSubStringMatcher) NegatedFailureMessage(actual interface{}) string {
51 | return fmt.Sprintf("Expected:\n\t%s not to contain a substring '%s'\n\nBut got:\n%s",
52 | actual, matcher.substring, matcher.fileContent)
53 | }
54 |
--------------------------------------------------------------------------------
/pegomock/testutil/io.go:
--------------------------------------------------------------------------------
1 | package testutil
2 |
3 | import (
4 | "os"
5 |
6 | . "github.com/onsi/gomega"
7 | )
8 |
9 | func WriteFile(filepath string, content string) {
10 | Expect(os.WriteFile(filepath, []byte(content), 0644)).To(Succeed())
11 | }
12 |
--------------------------------------------------------------------------------
/pegomock/util/error.go:
--------------------------------------------------------------------------------
1 | package util
2 |
3 | // PanicOnError panics if err is not nil
4 | func PanicOnError(err error) {
5 | if err != nil {
6 | panic(err)
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/pegomock/util/input.go:
--------------------------------------------------------------------------------
1 | package util
2 |
3 | import (
4 | "errors"
5 | "fmt"
6 | "os"
7 | "path/filepath"
8 | "regexp"
9 | "strings"
10 | )
11 |
12 | func ValidateArgs(args []string) error {
13 | if len(args) == 0 {
14 | return errors.New("You must specify either exactly one source filename ending with .go, or at least one go interface name.")
15 | }
16 | if len(args) == 1 {
17 | return nil
18 | }
19 | if len(args) >= 2 {
20 | for _, arg := range args {
21 | if strings.HasSuffix(arg, ".go") {
22 | return errors.New("You can specify at most one go source file.")
23 | }
24 | }
25 | }
26 | return nil
27 | }
28 |
29 | func SourceArgs(args []string) ([]string, error) {
30 | if len(args) == 1 {
31 | packagePath, err := packagePathFromWorkingDirectoryAndGoModule()
32 | if err != nil {
33 | return nil, fmt.Errorf("Couldn't determine package path from directory: %v", err)
34 | }
35 | return []string{packagePath, args[0]}, nil
36 | } else if len(args) == 2 {
37 | return args[:], nil
38 | } else {
39 | return nil, errors.New("Please provide exactly 1 interface or 1 package + 1 interface in the interfaces_to_mock file")
40 | }
41 | }
42 |
43 | func packagePathFromWorkingDirectoryAndGoModule() (string, error) {
44 | dir, e := os.Getwd()
45 | if e != nil {
46 | return "", e
47 | }
48 | gomodDir := findModuleRoot(dir)
49 | subPackage, e := filepath.Rel(gomodDir, dir)
50 | if e != nil {
51 | return "", errors.New("Could not get a relative path for " + dir + " based on path " + gomodDir)
52 | }
53 | gomodFilepath := filepath.Join(gomodDir, "go.mod")
54 |
55 | content, e := os.ReadFile(gomodFilepath)
56 | if e != nil {
57 | return "", errors.New("Could not read file " + gomodFilepath)
58 | }
59 | modulePathMatches := regexp.MustCompile(`^module (.*)\n`).FindSubmatch(content)
60 | if len(modulePathMatches) != 2 {
61 | return "", errors.New("Cannot parse" + gomodFilepath + "file. File does not start with 'module'")
62 | }
63 | return filepath.Join(
64 | string(modulePathMatches[1]),
65 | subPackage),
66 | nil
67 | }
68 |
69 | // copied from https://github.com/golang/go/blob/ab724d43efe7e1a7516c1d13e40b55dca26a61b4/src/cmd/go/internal/modload/init.go#L480-L495:
70 | func findModuleRoot(dir string) (root string) {
71 | dir = filepath.Clean(dir)
72 |
73 | // Look for enclosing go.mod.
74 | for {
75 | if fi, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil && !fi.IsDir() {
76 | return dir
77 | }
78 | d := filepath.Dir(dir)
79 | if d == dir {
80 | break
81 | }
82 | dir = d
83 | }
84 | return ""
85 | }
86 |
--------------------------------------------------------------------------------
/pegomock/util/io.go:
--------------------------------------------------------------------------------
1 | package util
2 |
3 | import "os"
4 |
5 | // WithinWorkingDir changes the current working directory temporarily and
6 | // executes cb within that context.
7 | func WithinWorkingDir(targetPath string, cb func(workingDir string)) {
8 | origWorkingDir, e := os.Getwd()
9 | PanicOnError(e)
10 | e = os.Chdir(targetPath)
11 | PanicOnError(e)
12 | defer func() { _ = os.Chdir(origWorkingDir) }()
13 | cb(targetPath)
14 | }
15 |
16 | func WriteFileIfChanged(outputFilepath string, output []byte) bool {
17 | existingFileContent, e := os.ReadFile(outputFilepath)
18 | if os.IsNotExist(e) {
19 | e = os.WriteFile(outputFilepath, output, 0664)
20 | PanicOnError(e)
21 | return true
22 | }
23 | PanicOnError(e)
24 |
25 | if string(existingFileContent) == string(output) {
26 | return false
27 | }
28 | e = os.WriteFile(outputFilepath, output, 0664)
29 | PanicOnError(e)
30 | return true
31 | }
32 |
--------------------------------------------------------------------------------
/pegomock/util/time.go:
--------------------------------------------------------------------------------
1 | package util
2 |
3 | import (
4 | "context"
5 | "time"
6 | )
7 |
8 | // Ticker repeatedly calls cb with a delay in between calls. It stops doing This
9 | // When a element is sent to the done channel.
10 | func Ticker(cb func(), delay time.Duration, ctx context.Context) {
11 | for {
12 | select {
13 | case <-ctx.Done():
14 | return
15 |
16 | default:
17 | cb()
18 | time.Sleep(delay)
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/pegomock/watch/watch.go:
--------------------------------------------------------------------------------
1 | // Copyright 2016 Peter Goetz
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | package watch
16 |
17 | import (
18 | "fmt"
19 | "os"
20 | "path/filepath"
21 | "regexp"
22 | "strings"
23 |
24 | "github.com/alecthomas/kingpin/v2"
25 |
26 | "github.com/petergtz/pegomock/v4/pegomock/filehandling"
27 | "github.com/petergtz/pegomock/v4/pegomock/util"
28 | )
29 |
30 | const wellKnownInterfaceListFile = "interfaces_to_mock"
31 |
32 | var join = strings.Join
33 |
34 | type MockFileUpdater struct {
35 | recursive bool
36 | targetPaths []string
37 | lastErrors map[string]string
38 | }
39 |
40 | func NewMockFileUpdater(targetPaths []string, recursive bool) *MockFileUpdater {
41 | return &MockFileUpdater{
42 | targetPaths: targetPaths,
43 | recursive: recursive,
44 | lastErrors: make(map[string]string),
45 | }
46 | }
47 |
48 | func (updater *MockFileUpdater) Update() {
49 | for _, targetPath := range updater.targetPaths {
50 | if updater.recursive {
51 | e := filepath.Walk(targetPath, func(path string, info os.FileInfo, err error) error {
52 | if err == nil && info.IsDir() {
53 | util.WithinWorkingDir(path, updater.updateMockFiles)
54 | }
55 | return nil
56 | })
57 | if e != nil {
58 | panic(e)
59 | }
60 | } else {
61 | util.WithinWorkingDir(targetPath, updater.updateMockFiles)
62 | }
63 | }
64 | }
65 |
66 | func (updater *MockFileUpdater) updateMockFiles(targetPath string) {
67 | if _, err := os.Stat(wellKnownInterfaceListFile); os.IsNotExist(err) {
68 | return
69 | }
70 | for _, lineParts := range linesIn(wellKnownInterfaceListFile) {
71 | lineCmd := kingpin.New("What should go in here", "And what should go in here")
72 | destination := lineCmd.Flag("output", "Output file; defaults to mock__test.go.").Short('o').String()
73 | nameOut := lineCmd.Flag("name", "Struct name of the generated code; defaults to the name of the interface prefixed with Mock").Default(filepath.Base(targetPath) + "_test").String()
74 | packageOut := lineCmd.Flag("package", "Package of the generated code; defaults to the package from which pegomock was executed suffixed with _test").Default(filepath.Base(targetPath) + "_test").String()
75 | selfPackage := lineCmd.Flag("self_package", "If set, the package this mock will be part of.").String()
76 | lineArgs := lineCmd.Arg("args", "A (optional) Go package path + space-separated interface or a .go file").Required().Strings()
77 |
78 | _, parseErr := lineCmd.Parse(lineParts)
79 | if parseErr != nil {
80 | fmt.Println("Error while trying to generate mock for line", join(lineParts, " "), ":", parseErr)
81 | continue
82 | }
83 | defer func() {
84 | err := recover()
85 | if err != nil {
86 | if updater.lastErrors[errorKey(*lineArgs)] != fmt.Sprint(err) {
87 | fmt.Println("Error while trying to generate mock for", join(lineParts, " "), ":", err)
88 | updater.lastErrors[errorKey(*lineArgs)] = fmt.Sprint(err)
89 | }
90 | }
91 | }()
92 |
93 | util.PanicOnError(util.ValidateArgs(*lineArgs))
94 | sourceArgs, err := util.SourceArgs(*lineArgs)
95 | util.PanicOnError(err)
96 |
97 | generatedMockSourceCode := filehandling.GenerateMockSourceCode(sourceArgs, *nameOut, *packageOut, *selfPackage, false, os.Stdout)
98 | mockFilePath := filehandling.OutputFilePath(sourceArgs, ".", *destination)
99 | hasChanged := util.WriteFileIfChanged(mockFilePath, generatedMockSourceCode)
100 |
101 | if hasChanged || updater.lastErrors[errorKey(*lineArgs)] != "" {
102 | fmt.Println("(Re)generated mock for", errorKey(*lineArgs), "in", mockFilePath)
103 | }
104 | delete(updater.lastErrors, errorKey(*lineArgs))
105 | }
106 | }
107 |
108 | func errorKey(args []string) string {
109 | return join(args, "_")
110 | }
111 |
112 | func CreateWellKnownInterfaceListFilesIfNecessary(targetPaths []string) {
113 | for _, targetPath := range targetPaths {
114 | CreateWellKnownInterfaceListFileIfNecessary(targetPath)
115 | }
116 | }
117 |
118 | func CreateWellKnownInterfaceListFileIfNecessary(targetPath string) {
119 | file, err := os.OpenFile(filepath.Join(targetPath, wellKnownInterfaceListFile), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0666)
120 | if err != nil {
121 | if os.IsExist(err) {
122 | return
123 | }
124 | panic(err)
125 | }
126 | defer file.Close()
127 | _, e := file.WriteString("### List here all interfaces you would like to mock. One per line.\n")
128 | if e != nil {
129 | panic(e)
130 | }
131 | }
132 |
133 | func linesIn(file string) (result [][]string) {
134 | content, err := os.ReadFile(file)
135 | util.PanicOnError(err)
136 | for _, line := range strings.Split(string(content), "\n") {
137 | if strings.HasPrefix(strings.TrimSpace(line), "#") || line == "" {
138 | continue
139 | }
140 | parts := regexp.MustCompile(`\s`).Split(line, -1)
141 | // TODO: do validation here like in main
142 | result = append(result, parts)
143 | }
144 | return
145 | }
146 |
--------------------------------------------------------------------------------
/pegomock/watch/watch_test.go:
--------------------------------------------------------------------------------
1 | // Copyright 2016 Peter Goetz
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | package watch_test
16 |
17 | import (
18 | "go/build"
19 | "os"
20 | "path/filepath"
21 | "testing"
22 |
23 | . "github.com/onsi/ginkgo/v2"
24 | . "github.com/onsi/gomega"
25 | . "github.com/petergtz/pegomock/v4/pegomock/testutil"
26 | "github.com/petergtz/pegomock/v4/pegomock/watch"
27 | )
28 |
29 | var (
30 | joinPath = filepath.Join
31 | )
32 |
33 | func TestWatchCommand(t *testing.T) {
34 | RegisterFailHandler(Fail)
35 | RunSpecs(t, "Watch Suite")
36 | }
37 |
38 | var _ = Describe("NewMockFileUpdater", func() {
39 | var (
40 | packageDir, subPackageDir, vendorPackageDir string
41 | origWorkingDir string
42 | )
43 |
44 | BeforeEach(func() {
45 | packageDir = joinPath(build.Default.GOPATH, "src", "pegomocktest")
46 | Expect(os.MkdirAll(packageDir, 0755)).To(Succeed())
47 | subPackageDir = joinPath(packageDir, "subpackage")
48 | Expect(os.MkdirAll(subPackageDir, 0755)).To(Succeed())
49 | vendorPackageDir = joinPath(packageDir, "vendor", "github.com", "petergtz", "vendored_package")
50 | Expect(os.MkdirAll(vendorPackageDir, 0755)).To(Succeed())
51 |
52 | var e error
53 | origWorkingDir, e = os.Getwd()
54 | Expect(e).NotTo(HaveOccurred())
55 | os.Chdir(packageDir)
56 |
57 | WriteFile(joinPath(packageDir, "mydisplay.go"),
58 | "package pegomocktest; type MyDisplay interface { Show() }")
59 | WriteFile(joinPath(subPackageDir, "subdisplay.go"),
60 | "package subpackage; type SubDisplay interface { ShowMe() }")
61 | WriteFile(joinPath(vendorPackageDir, "iface.go"),
62 | `package vendored_package; type Interface interface{ Foobar() }`)
63 | WriteFile(joinPath(packageDir, "vendordisplay.go"), `package pegomocktest
64 | import ( "github.com/petergtz/vendored_package" )
65 | type VendorDisplay interface { Show(something vendored_package.Interface) }`)
66 |
67 | })
68 |
69 | AfterEach(func() {
70 | Expect(os.RemoveAll(packageDir)).To(Succeed())
71 | os.Chdir(origWorkingDir)
72 | })
73 |
74 | Context("after populating interfaces_to_mock with an actual interface", func() {
75 | It(`Eventually creates a file mock_mydisplay_test.go starting with "package pegomocktest_test"`, func() {
76 | WriteFile(joinPath(packageDir, "interfaces_to_mock"), "MyDisplay")
77 |
78 | watch.NewMockFileUpdater([]string{packageDir}, false).Update()
79 |
80 | Eventually(joinPath(packageDir, "mock_mydisplay_test.go"), "3s").Should(SatisfyAll(
81 | BeAnExistingFile(),
82 | BeAFileContainingSubString("package pegomocktest_test")))
83 | })
84 |
85 | Context("and overriding the output filepath", func() {
86 | It(`Eventually creates a file foo.go starting with "package pegomocktest_test"`, func() {
87 | WriteFile(joinPath(packageDir, "interfaces_to_mock"), "-o foo.go MyDisplay")
88 |
89 | watch.NewMockFileUpdater([]string{packageDir}, false).Update()
90 |
91 | Eventually(joinPath(packageDir, "foo.go"), "3s").Should(SatisfyAll(
92 | BeAnExistingFile(),
93 | BeAFileContainingSubString("package pegomocktest_test")))
94 | })
95 | })
96 |
97 | Context("and overriding the package name", func() {
98 | It(`Eventually creates a file starting with "package the_overriden_test_package"`, func() {
99 | WriteFile(joinPath(packageDir, "interfaces_to_mock"), "--package the_overriden_test_package MyDisplay")
100 |
101 | watch.NewMockFileUpdater([]string{packageDir}, false).Update()
102 |
103 | Eventually(joinPath(packageDir, "mock_mydisplay_test.go"), "3s").Should(SatisfyAll(
104 | BeAnExistingFile(),
105 | BeAFileContainingSubString("package the_overriden_test_package")))
106 | })
107 | })
108 |
109 | Context(`and specifying the vendor path`, func() {
110 |
111 | It(`Eventually creates a file containing the import ( vendored_package "github.com/petergtz/vendored_package" )'`, func() {
112 | WriteFile(joinPath(packageDir, "interfaces_to_mock"), "VendorDisplay")
113 |
114 | watch.NewMockFileUpdater([]string{packageDir}, false).Update()
115 |
116 | Expect(joinPath(packageDir, "mock_vendordisplay_test.go")).To(SatisfyAll(
117 | BeAnExistingFile(),
118 | BeAFileContainingSubString(`vendored_package "github.com/petergtz/vendored_package"`)))
119 | })
120 | })
121 |
122 | Context("in multiple packages and providing those packages to watch", func() {
123 | It(`Eventually creates correct files in respective directories`, func() {
124 | os.Chdir("..")
125 | WriteFile(joinPath(packageDir, "interfaces_to_mock"), "MyDisplay")
126 | WriteFile(joinPath(subPackageDir, "interfaces_to_mock"), "SubDisplay")
127 |
128 | watch.NewMockFileUpdater([]string{"pegomocktest", "pegomocktest/subpackage"}, false).Update()
129 |
130 | Eventually(joinPath(packageDir, "mock_mydisplay_test.go"), "3s").Should(SatisfyAll(
131 | BeAnExistingFile(),
132 | BeAFileContainingSubString("package pegomocktest_test")))
133 | Eventually(joinPath(subPackageDir, "mock_subdisplay_test.go"), "3s").Should(SatisfyAll(
134 | BeAnExistingFile(),
135 | BeAFileContainingSubString("package subpackage_test")))
136 | })
137 | })
138 |
139 | Context("in one package, but providing multiple packages to create mocks from", func() {
140 | It(`Eventually creates correct files in respective directories`, func() {
141 | os.Chdir("..")
142 | WriteFile(joinPath(packageDir, "interfaces_to_mock"), "MyDisplay\npegomocktest/subpackage SubDisplay")
143 |
144 | watch.NewMockFileUpdater([]string{"pegomocktest", "pegomocktest/subpackage"}, false).Update()
145 |
146 | Eventually(joinPath(packageDir, "mock_mydisplay_test.go"), "3s").Should(SatisfyAll(
147 | BeAnExistingFile(),
148 | BeAFileContainingSubString("package pegomocktest_test")))
149 | Eventually(joinPath(packageDir, "mock_subdisplay_test.go"), "3s").Should(SatisfyAll(
150 | BeAnExistingFile(),
151 | BeAFileContainingSubString("package pegomocktest_test")))
152 | })
153 | })
154 |
155 | Context("in multiple packages and watching --recursive", func() {
156 | It(`Eventually creates correct files in respective directories`, func() {
157 | WriteFile(joinPath(packageDir, "interfaces_to_mock"), "MyDisplay")
158 | WriteFile(joinPath(subPackageDir, "interfaces_to_mock"), "SubDisplay")
159 |
160 | watch.NewMockFileUpdater([]string{packageDir}, true).Update()
161 |
162 | Eventually(joinPath(packageDir, "mock_mydisplay_test.go"), "3s").Should(SatisfyAll(
163 | BeAnExistingFile(),
164 | BeAFileContainingSubString("package pegomocktest_test")))
165 | Eventually(joinPath(subPackageDir, "mock_subdisplay_test.go"), "3s").Should(SatisfyAll(
166 | BeAnExistingFile(),
167 | BeAFileContainingSubString("package subpackage_test")))
168 | })
169 | })
170 |
171 | })
172 |
173 | Context("after populating interfaces_to_mock with a Go file", func() {
174 | It(`Eventually creates a file mock_mydisplay_test.go starting with "package pegomocktest_test"`, func() {
175 | WriteFile(joinPath(packageDir, "interfaces_to_mock"), "mydisplay.go")
176 |
177 | watch.NewMockFileUpdater([]string{packageDir}, false).Update()
178 |
179 | Eventually(joinPath(packageDir, "mock_mydisplay_test.go"), "3s").Should(SatisfyAll(
180 | BeAnExistingFile(),
181 | BeAFileContainingSubString("package pegomocktest_test")))
182 | })
183 | })
184 |
185 | })
186 |
--------------------------------------------------------------------------------
/scripts/ginkgo-watch-gomock-reflect:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | $GOPATH/bin/ginkgo watch -succinct -notify -progress --depth=3 generate_test_mocks/gomock_reflect .
3 |
--------------------------------------------------------------------------------
/scripts/ginkgo-watch-gomock-source:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | $GOPATH/bin/ginkgo watch -succinct -notify -progress --depth=3 generate_test_mocks/gomock_source .
3 |
--------------------------------------------------------------------------------
/scripts/ginkgo-watch-recursive:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | $GOPATH/bin/ginkgo -succinct generate_test_mocks/gomock_reflect
3 | $GOPATH/bin/ginkgo watch -succinct -r -notify -progress --depth=3
4 |
--------------------------------------------------------------------------------
/scripts/run_tests.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | set -ex
4 | cd $(dirname $0)/..
5 |
6 | rm -f mock_display_test.go
7 | rm -f mock_generic_display_test.go
8 | ginkgo -succinct generate_test_mocks/xtools_go_loader
9 | ginkgo -r --skip-package=generate_test_mocks/xtools_go_loader,pegomock/watch --randomize-all --randomize-suites --race --trace -cover
10 |
--------------------------------------------------------------------------------
/test_interface/display.go:
--------------------------------------------------------------------------------
1 | // Copyright 2015 Peter Goetz
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | package test_interface
16 |
17 | import (
18 | "io"
19 | "net/http"
20 | "time"
21 | )
22 |
23 | // Display is some sample interface to be mocked.
24 | type Display interface {
25 | Flash(_param0 string, _param1 int)
26 | Show(_param0 string)
27 | SomeValue() string
28 | MultipleValues() (string, int, float32)
29 | MultipleParamsAndReturnValue(s string, i int) string
30 | ArrayParam(array []string)
31 | MapParam(m map[string]http.Request)
32 | FloatParam(float32)
33 | InterfaceParam(interface{})
34 | InterfaceReturnValue() interface{}
35 | ErrorReturnValue() error
36 | ErrorParam(e error)
37 | NetHttpRequestParam(r http.Request)
38 | NetHttpRequestPtrParam(r *http.Request)
39 | FuncReturnValue() func()
40 | VariadicParam(v ...string)
41 | NormalAndVariadicParam(s string, i int, v ...string)
42 | CamelCaseTypeParam(camelCaseParam io.ReadCloser)
43 | MapOfStringToInterfaceParam(m map[string]interface{})
44 | UseTime(t time.Time)
45 | ChanParams(<-chan string, chan<- error)
46 | ChanReturnValues() (<-chan string, chan<- error)
47 | VariadicWithNonPrimitiveType(m ...map[int]int)
48 | MapWithRedundantImports(m map[http.File]http.File)
49 | MapOfStringToEmptyUnnamedStruct(m map[string]struct{})
50 | }
51 |
52 | type GenericDisplay[N comparable, V Number] interface {
53 | GenericParams(m map[N]V) V
54 | }
55 |
56 | type Number interface {
57 | int64 | float64
58 | }
59 |
--------------------------------------------------------------------------------
/testing_t_support.go:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2013-2014 Onsi Fakhouri
2 | //
3 | // Permission is hereby granted, free of charge, to any person obtaining
4 | // a copy of this software and associated documentation files (the
5 | // "Software"), to deal in the Software without restriction, including
6 | // without limitation the rights to use, copy, modify, merge, publish,
7 | // distribute, sublicense, and/or sell copies of the Software, and to
8 | // permit persons to whom the Software is furnished to do so, subject to
9 | // the following conditions:
10 | //
11 | // The above copyright notice and this permission notice shall be
12 | // included in all copies or substantial portions of the Software.
13 | //
14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 |
22 | package pegomock
23 |
24 | import (
25 | "regexp"
26 | "runtime/debug"
27 | "strings"
28 | )
29 |
30 | type testingT interface {
31 | Errorf(format string, args ...interface{})
32 | }
33 |
34 | func BuildTestingTFailHandler(t testingT) FailHandler {
35 | return func(message string, callerSkip ...int) {
36 | skip := 1
37 | if len(callerSkip) > 0 {
38 | skip = callerSkip[0]
39 | }
40 | stackTrace := pruneStack(string(debug.Stack()), skip)
41 | t.Errorf("\n%s\n%s", stackTrace, message)
42 | }
43 | }
44 |
45 | func pruneStack(fullStackTrace string, skip int) string {
46 | stack := strings.Split(fullStackTrace, "\n")
47 | if len(stack) > 2*(skip+1) {
48 | stack = stack[2*(skip+1):]
49 | }
50 | prunedStack := []string{}
51 | re := regexp.MustCompile(`\/ginkgo\/|\/pkg\/testing\/|\/pkg\/runtime\/`)
52 | for i := 0; i < len(stack)/2; i++ {
53 | if !re.Match([]byte(stack[i*2])) {
54 | prunedStack = append(prunedStack, stack[i*2])
55 | prunedStack = append(prunedStack, stack[i*2+1])
56 | }
57 | }
58 | return strings.Join(prunedStack, "\n")
59 | }
60 |
61 | func WithT(t testingT) Option {
62 | return WithFailHandler(BuildTestingTFailHandler(t))
63 | }
64 |
--------------------------------------------------------------------------------
/types.go:
--------------------------------------------------------------------------------
1 | package pegomock
2 |
3 | type FailHandler func(message string, callerSkip ...int)
4 |
5 | type Mock interface {
6 | SetFailHandler(FailHandler)
7 | FailHandler() FailHandler
8 | }
9 | type Param interface{}
10 | type ReturnValue interface{}
11 | type ReturnValues []ReturnValue
12 |
13 | type Option interface{ Apply(Mock) }
14 |
15 | type OptionFunc func(mock Mock)
16 |
17 | func (f OptionFunc) Apply(mock Mock) { f(mock) }
18 |
19 | func WithFailHandler(fail FailHandler) Option {
20 | return OptionFunc(func(mock Mock) { mock.SetFailHandler(fail) })
21 | }
22 |
--------------------------------------------------------------------------------