From 082910ceaf75047cd48d11591e073991662e786b Mon Sep 17 00:00:00 2001 From: Peter Goetz Date: Thu, 11 May 2023 15:32:09 +0200 Subject: [PATCH] Remove deprecated matcher options, remove legacy mock generation This makes the golang.org/x/tools/go/packages based generation the default generation method and also the only one. Because this could, in theory, be a behavioral breaking change, bumping major version. --- README.md | 14 +- dsl.go | 2 +- dsl_test.go | 11 +- .../gomock_reflect/generate_test.go | 32 -- .../gomock_source/generate_test.go | 32 -- .../xtools_go_loader/generate_test.go | 10 +- ginkgo_compatible/in_order_context.go | 2 - ginkgo_compatible/matchers.go | 2 +- ginkgo_compatible/matchers_generic.go | 2 - ginkgo_compatible/option.go | 4 - ginkgo_compatible/whenever.go | 4 - go.mod | 2 +- .../generate_matchers/matcher_generation.go | 52 +- matcher.go | 2 +- matcher_factories.go | 432 -------------- matchers/http_request.go | 33 -- matchers/io_readcloser.go | 33 -- matchers/map_of_http_file_to_http_file.go | 33 -- matchers/map_of_int_to_int.go | 31 - .../map_of_string_to_empty_unnamed_struct.go | 31 - matchers/map_of_string_to_http_request.go | 33 -- matchers/map_of_string_to_interface.go | 31 - matchers/ptr_to_http_request.go | 33 -- matchers/recv_chan_of_string.go | 31 - matchers/send_chan_of_error.go | 31 - matchers/slice_of_string.go | 31 - matchers/time_time.go | 33 -- mockgen/mockgen.go | 188 +----- mockgen/mockgen_suite_test.go | 13 - mockgen/mockgen_test.go | 64 --- mockgen/util/sort.go | 13 - mockgen/util/util_test.go | 34 -- modelgen/gomock/parse.go | 457 --------------- modelgen/gomock/reflect.go | 159 ------ modelgen/gomock/reflect_helpers.go | 182 ------ modelgen/gomock/reflect_test.go | 38 -- modelgen/modelgen_test.go | 43 +- modelgen/xtools_loader/loader.go | 197 ------- modelgen/xtools_loader/loader_suite_test.go | 13 - modelgen/xtools_loader/loader_test.go | 34 -- modelgen/xtools_packages/packages.go | 2 +- modelgen/xtools_packages/packages_test.go | 8 +- panic_with_message_matcher_test.go | 2 +- panic_with_message_to_matcher_test.go | 2 +- pegomock/filehandling/filehandling.go | 73 +-- pegomock/main.go | 34 +- pegomock/main_test.go | 538 +++++++----------- pegomock/package_name_test.go | 4 +- pegomock/testutil/gomega_file_matcher.go | 2 +- pegomock/testutil/io.go | 4 +- pegomock/util/input.go | 67 +-- pegomock/watch/watch.go | 19 +- pegomock/watch/watch_test.go | 4 +- scripts/run_tests.sh | 16 +- 54 files changed, 303 insertions(+), 2894 deletions(-) delete mode 100644 generate_test_mocks/gomock_reflect/generate_test.go delete mode 100644 generate_test_mocks/gomock_source/generate_test.go delete mode 100644 matchers/http_request.go delete mode 100644 matchers/io_readcloser.go delete mode 100644 matchers/map_of_http_file_to_http_file.go delete mode 100644 matchers/map_of_int_to_int.go delete mode 100644 matchers/map_of_string_to_empty_unnamed_struct.go delete mode 100644 matchers/map_of_string_to_http_request.go delete mode 100644 matchers/map_of_string_to_interface.go delete mode 100644 matchers/ptr_to_http_request.go delete mode 100644 matchers/recv_chan_of_string.go delete mode 100644 matchers/send_chan_of_error.go delete mode 100644 matchers/slice_of_string.go delete mode 100644 matchers/time_time.go delete mode 100644 mockgen/mockgen_suite_test.go delete mode 100644 mockgen/mockgen_test.go delete mode 100644 mockgen/util/sort.go delete mode 100644 mockgen/util/util_test.go delete mode 100644 modelgen/gomock/parse.go delete mode 100644 modelgen/gomock/reflect.go delete mode 100644 modelgen/gomock/reflect_helpers.go delete mode 100644 modelgen/gomock/reflect_test.go delete mode 100644 modelgen/xtools_loader/loader.go delete mode 100644 modelgen/xtools_loader/loader_suite_test.go delete mode 100644 modelgen/xtools_loader/loader_test.go diff --git a/README.md b/README.md index d52a0b7..9eda42b 100644 --- a/README.md +++ b/README.md @@ -14,8 +14,8 @@ Installing Pegomock Pegomock consists of a binary `pegomock` and a package. Install both via: ```shell -go install github.com/petergtz/pegomock/v3/pegomock@latest -go get github.com/petergtz/pegomock/v3@latest +go install github.com/petergtz/pegomock/v4/pegomock@latest +go get github.com/petergtz/pegomock/v4@latest ``` 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. @@ -37,7 +37,7 @@ The preferred way is: ```go import ( - "github.com/petergtz/pegomock/v3" + "github.com/petergtz/pegomock/v4" "testing" ) @@ -86,7 +86,7 @@ package some_test import ( . "github.com/onsi/ginkgo" - . "github.com/petergtz/pegomock/v3/ginkgo_compatible" + . "github.com/petergtz/pegomock/v4/ginkgo_compatible" ) var _ = Describe("Some function", func() { @@ -406,7 +406,7 @@ Installation Install it via: ```shell -go install github.com/petergtz/pegomock/v3/pegomock@latest +go install github.com/petergtz/pegomock/v4/pegomock@latest ``` Tracking the pegomock tool in your project @@ -425,7 +425,7 @@ Go modules allow to pin not only a package but also a tool (that is, an executab package tools import ( - _ "github.com/petergtz/pegomock/v3/pegomock" + _ "github.com/petergtz/pegomock/v4/pegomock" ) ``` 2. Set `$GOBIN` to a `bin` directory relative to your repo (this defines where tool dependencies will be installed). @@ -433,7 +433,7 @@ import ( ```console $ cd /path/to/myproject $ export GOBIN=$PWD/bin -$ go install github.com/petergtz/pegomock/v3/pegomock +$ go install github.com/petergtz/pegomock/v4/pegomock ``` 3. Use that `$GOBIN` when invoking `pegomock` for that project: ```console diff --git a/dsl.go b/dsl.go index 1bac347..d29f9b3 100644 --- a/dsl.go +++ b/dsl.go @@ -24,7 +24,7 @@ import ( "time" "github.com/onsi/gomega/format" - "github.com/petergtz/pegomock/v3/internal/verify" + "github.com/petergtz/pegomock/v4/internal/verify" ) var GlobalFailHandler FailHandler diff --git a/dsl_test.go b/dsl_test.go index fc2752c..213b0da 100644 --- a/dsl_test.go +++ b/dsl_test.go @@ -22,12 +22,11 @@ import ( "testing" "time" - . "github.com/petergtz/pegomock/v3" - "github.com/onsi/ginkgo/v2" "github.com/onsi/gomega" - "github.com/petergtz/pegomock/v3" - "github.com/petergtz/pegomock/v3/test_interface" + "github.com/petergtz/pegomock/v4" + . "github.com/petergtz/pegomock/v4" + "github.com/petergtz/pegomock/v4/test_interface" "github.com/samber/lo" ) @@ -195,7 +194,7 @@ var _ = Describe("MockDisplay", func() { }) }) - Describe("https://github.com/petergtz/pegomock/v3/issues/24", func() { + Describe("https://github.com/petergtz/pegomock/v4/issues/24", func() { Context("Stubbing with nil value", func() { It("does not panic when return type is interface{}", func() { When(display.InterfaceReturnValue()).ThenReturn(nil) @@ -343,7 +342,7 @@ var _ = Describe("MockDisplay", func() { Context("Never calling Flash", func() { It("succeeds during verification when using Never() and argument matchers", func() { - // https://github.com/petergtz/pegomock/v3/issues/34 + // https://github.com/petergtz/pegomock/v4/issues/34 Expect(func() { display.VerifyWasCalled(Never()).Flash(Any[string](), Any[int]()) }).NotTo(Panic()) }) }) diff --git a/generate_test_mocks/gomock_reflect/generate_test.go b/generate_test_mocks/gomock_reflect/generate_test.go deleted file mode 100644 index e8e521d..0000000 --- a/generate_test_mocks/gomock_reflect/generate_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2015 Peter Goetz -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package mockgen_test - -import ( - "os" - "testing" - - . "github.com/onsi/ginkgo/v2" - "github.com/petergtz/pegomock/v3/pegomock/filehandling" -) - -func TestMockGeneration(t *testing.T) { RunSpecs(t, "Generating mocks with GoMock-reflect") } - -var _ = It("Generate mocks", func() { - filehandling.GenerateMockFile( - []string{"github.com/petergtz/pegomock/v3/test_interface", "Display"}, - "../../mock_display_test.go", "MockDisplay", "pegomock_test", - "", false, os.Stdout, false, true, "") -}) diff --git a/generate_test_mocks/gomock_source/generate_test.go b/generate_test_mocks/gomock_source/generate_test.go deleted file mode 100644 index 2a4435e..0000000 --- a/generate_test_mocks/gomock_source/generate_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2015 Peter Goetz -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package mockgen_test - -import ( - "os" - "testing" - - . "github.com/onsi/ginkgo/v2" - "github.com/petergtz/pegomock/v3/pegomock/filehandling" -) - -func TestMockGeneration(t *testing.T) { RunSpecs(t, "Generating mocks with GoMock-source") } - -var _ = It("Generate mocks", func() { - filehandling.GenerateMockFile( - []string{"../../test_interface/display.go"}, - "../../mock_display_test.go", "MockDisplay", "pegomock_test", - "", false, os.Stdout, false, true, "") -}) diff --git a/generate_test_mocks/xtools_go_loader/generate_test.go b/generate_test_mocks/xtools_go_loader/generate_test.go index 2401614..a93d55d 100644 --- a/generate_test_mocks/xtools_go_loader/generate_test.go +++ b/generate_test_mocks/xtools_go_loader/generate_test.go @@ -19,7 +19,7 @@ import ( "testing" . "github.com/onsi/ginkgo/v2" - "github.com/petergtz/pegomock/v3/pegomock/filehandling" + "github.com/petergtz/pegomock/v4/pegomock/filehandling" ) func TestMockGeneration(t *testing.T) { @@ -28,12 +28,12 @@ func TestMockGeneration(t *testing.T) { var _ = It("Generate mocks", func() { filehandling.GenerateMockFile( - []string{"github.com/petergtz/pegomock/v3/test_interface", "Display"}, + []string{"github.com/petergtz/pegomock/v4/test_interface", "Display"}, "../../mock_display_test.go", "MockDisplay", "pegomock_test", - "", false, os.Stdout, true, true, "") + "", false, os.Stdout) filehandling.GenerateMockFile( - []string{"github.com/petergtz/pegomock/v3/test_interface", "GenericDisplay"}, + []string{"github.com/petergtz/pegomock/v4/test_interface", "GenericDisplay"}, "../../mock_generic_display_test.go", "MockGenericDisplay", "pegomock_test", - "", false, os.Stdout, true, false, "") + "", false, os.Stdout) }) diff --git a/ginkgo_compatible/in_order_context.go b/ginkgo_compatible/in_order_context.go index 13032ea..f7416c7 100644 --- a/ginkgo_compatible/in_order_context.go +++ b/ginkgo_compatible/in_order_context.go @@ -1,5 +1,3 @@ package mock -import "github.com/petergtz/pegomock/v3" - type InOrderContext = pegomock.InOrderContext diff --git a/ginkgo_compatible/matchers.go b/ginkgo_compatible/matchers.go index 573f6db..6bd0996 100644 --- a/ginkgo_compatible/matchers.go +++ b/ginkgo_compatible/matchers.go @@ -1,7 +1,7 @@ package mock import ( - "github.com/petergtz/pegomock/v3" + "github.com/petergtz/pegomock/v4" ) var ( diff --git a/ginkgo_compatible/matchers_generic.go b/ginkgo_compatible/matchers_generic.go index 2542387..81e38d0 100644 --- a/ginkgo_compatible/matchers_generic.go +++ b/ginkgo_compatible/matchers_generic.go @@ -1,7 +1,5 @@ package mock -import "github.com/petergtz/pegomock/v3" - func Eq[T any](value T) T { return pegomock.Eq(value) } func NotEq[T any](value T) T { return pegomock.NotEq(value) } func Any[T any]() T { return pegomock.Any[T]() } diff --git a/ginkgo_compatible/option.go b/ginkgo_compatible/option.go index 49a3239..0f54752 100644 --- a/ginkgo_compatible/option.go +++ b/ginkgo_compatible/option.go @@ -1,7 +1,3 @@ package mock -import ( - "github.com/petergtz/pegomock/v3" -) - var OptionWithT = pegomock.WithT diff --git a/ginkgo_compatible/whenever.go b/ginkgo_compatible/whenever.go index 2e333d0..cd3d7c5 100644 --- a/ginkgo_compatible/whenever.go +++ b/ginkgo_compatible/whenever.go @@ -1,7 +1,3 @@ package mock -import ( - "github.com/petergtz/pegomock/v3" -) - var Whenever = pegomock.When diff --git a/go.mod b/go.mod index a41b94b..8d05a33 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module github.com/petergtz/pegomock/v3 +module github.com/petergtz/pegomock/v4 go 1.18 diff --git a/internal/generate_matchers/matcher_generation.go b/internal/generate_matchers/matcher_generation.go index 199fd9f..823a1c1 100644 --- a/internal/generate_matchers/matcher_generation.go +++ b/internal/generate_matchers/matcher_generation.go @@ -9,7 +9,7 @@ import ( // Generate matchers: // -// go generate github.com/petergtz/pegomock/v3/internal/generate_matchers +// go generate github.com/petergtz/pegomock/v4/internal/generate_matchers //go:generate go run matcher_generation.go //go:generate go fmt ../../matcher_factories.go @@ -37,18 +37,6 @@ import ( for _, kind := range primitiveKinds { contents += fmt.Sprintf(` -// Deprecated: Use Eq[T any](value T) instead. -func Eq%[1]s(value %[2]s) %[2]s { - RegisterMatcher(&EqMatcher{Value: value}) - return %[4]s -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEq%[1]s(value %[2]s) %[2]s { - RegisterMatcher(&NotEqMatcher{Value: value}) - return %[4]s -} - // Deprecated: Use Any[T any]() instead. func Any%[1]s() %[2]s { RegisterMatcher(NewAnyMatcher(reflect.TypeOf(%[3]s))) @@ -61,18 +49,6 @@ func %[1]sThat(matcher ArgumentMatcher) %[2]s { return %[4]s } -// Deprecated: Use Eq[T any](value T) instead. -func Eq%[1]sSlice(value []%[2]s) []%[2]s { - RegisterMatcher(&EqMatcher{Value: value}) - return nil -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEq%[1]sSlice(value []%[2]s) []%[2]s { - RegisterMatcher(&NotEqMatcher{Value: value}) - return nil -} - // Deprecated: Use Any[T any]() instead. func Any%[1]sSlice() []%[2]s { RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf(%[3]s)))) @@ -89,18 +65,6 @@ func %[1]sSliceThat(matcher ArgumentMatcher) []%[2]s { // hard-coding this for now as interface{} overall works slightly different than other types. return contents + ` -// Deprecated: Use Eq[T any](value T) instead. -func EqInterface(value interface{}) interface{} { - RegisterMatcher(&EqMatcher{Value: value}) - return nil -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqInterface(value interface{}) interface{} { - RegisterMatcher(&NotEqMatcher{Value: value}) - return nil -} - // Deprecated: Use Any[T any]() instead. func AnyInterface() interface{} { RegisterMatcher(NewAnyMatcher(reflect.TypeOf((*interface{})(nil)).Elem())) @@ -113,18 +77,6 @@ func InterfaceThat(matcher ArgumentMatcher) interface{} { return nil } -// Deprecated: Use Eq[T any](value T) instead. -func EqInterfaceSlice(value []interface{}) []interface{} { - RegisterMatcher(&EqMatcher{Value: value}) - return nil -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqInterfaceSlice(value []interface{}) []interface{} { - RegisterMatcher(&NotEqMatcher{Value: value}) - return nil -} - // Deprecated: Use Any[T any]() instead. func AnyInterfaceSlice() []interface{} { RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((*interface{})(nil)).Elem()))) @@ -143,7 +95,7 @@ func GenerateGinkgoMatchersFile() string { contents := `package mock import ( - "github.com/petergtz/pegomock/v3" + "github.com/petergtz/pegomock/v4" ) var (` diff --git a/matcher.go b/matcher.go index f43c5b3..d54fcc9 100644 --- a/matcher.go +++ b/matcher.go @@ -6,7 +6,7 @@ import ( "sync" - "github.com/petergtz/pegomock/v3/internal/verify" + "github.com/petergtz/pegomock/v4/internal/verify" ) type EqMatcher struct { diff --git a/matcher_factories.go b/matcher_factories.go index 83b03d0..9f0afe9 100644 --- a/matcher_factories.go +++ b/matcher_factories.go @@ -4,18 +4,6 @@ import ( "reflect" ) -// Deprecated: Use Eq[T any](value T) instead. -func EqBool(value bool) bool { - RegisterMatcher(&EqMatcher{Value: value}) - return false -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqBool(value bool) bool { - RegisterMatcher(&NotEqMatcher{Value: value}) - return false -} - // Deprecated: Use Any[T any]() instead. func AnyBool() bool { RegisterMatcher(NewAnyMatcher(reflect.TypeOf(false))) @@ -28,18 +16,6 @@ func BoolThat(matcher ArgumentMatcher) bool { return false } -// Deprecated: Use Eq[T any](value T) instead. -func EqBoolSlice(value []bool) []bool { - RegisterMatcher(&EqMatcher{Value: value}) - return nil -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqBoolSlice(value []bool) []bool { - RegisterMatcher(&NotEqMatcher{Value: value}) - return nil -} - // Deprecated: Use Any[T any]() instead. func AnyBoolSlice() []bool { RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf(false)))) @@ -52,18 +28,6 @@ func BoolSliceThat(matcher ArgumentMatcher) []bool { return nil } -// Deprecated: Use Eq[T any](value T) instead. -func EqInt(value int) int { - RegisterMatcher(&EqMatcher{Value: value}) - return 0 -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqInt(value int) int { - RegisterMatcher(&NotEqMatcher{Value: value}) - return 0 -} - // Deprecated: Use Any[T any]() instead. func AnyInt() int { RegisterMatcher(NewAnyMatcher(reflect.TypeOf(0))) @@ -76,18 +40,6 @@ func IntThat(matcher ArgumentMatcher) int { return 0 } -// Deprecated: Use Eq[T any](value T) instead. -func EqIntSlice(value []int) []int { - RegisterMatcher(&EqMatcher{Value: value}) - return nil -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqIntSlice(value []int) []int { - RegisterMatcher(&NotEqMatcher{Value: value}) - return nil -} - // Deprecated: Use Any[T any]() instead. func AnyIntSlice() []int { RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf(0)))) @@ -100,18 +52,6 @@ func IntSliceThat(matcher ArgumentMatcher) []int { return nil } -// Deprecated: Use Eq[T any](value T) instead. -func EqInt8(value int8) int8 { - RegisterMatcher(&EqMatcher{Value: value}) - return 0 -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqInt8(value int8) int8 { - RegisterMatcher(&NotEqMatcher{Value: value}) - return 0 -} - // Deprecated: Use Any[T any]() instead. func AnyInt8() int8 { RegisterMatcher(NewAnyMatcher(reflect.TypeOf((int8)(0)))) @@ -124,18 +64,6 @@ func Int8That(matcher ArgumentMatcher) int8 { return 0 } -// Deprecated: Use Eq[T any](value T) instead. -func EqInt8Slice(value []int8) []int8 { - RegisterMatcher(&EqMatcher{Value: value}) - return nil -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqInt8Slice(value []int8) []int8 { - RegisterMatcher(&NotEqMatcher{Value: value}) - return nil -} - // Deprecated: Use Any[T any]() instead. func AnyInt8Slice() []int8 { RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((int8)(0))))) @@ -148,18 +76,6 @@ func Int8SliceThat(matcher ArgumentMatcher) []int8 { return nil } -// Deprecated: Use Eq[T any](value T) instead. -func EqInt16(value int16) int16 { - RegisterMatcher(&EqMatcher{Value: value}) - return 0 -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqInt16(value int16) int16 { - RegisterMatcher(&NotEqMatcher{Value: value}) - return 0 -} - // Deprecated: Use Any[T any]() instead. func AnyInt16() int16 { RegisterMatcher(NewAnyMatcher(reflect.TypeOf((int16)(0)))) @@ -172,18 +88,6 @@ func Int16That(matcher ArgumentMatcher) int16 { return 0 } -// Deprecated: Use Eq[T any](value T) instead. -func EqInt16Slice(value []int16) []int16 { - RegisterMatcher(&EqMatcher{Value: value}) - return nil -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqInt16Slice(value []int16) []int16 { - RegisterMatcher(&NotEqMatcher{Value: value}) - return nil -} - // Deprecated: Use Any[T any]() instead. func AnyInt16Slice() []int16 { RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((int16)(0))))) @@ -196,18 +100,6 @@ func Int16SliceThat(matcher ArgumentMatcher) []int16 { return nil } -// Deprecated: Use Eq[T any](value T) instead. -func EqInt32(value int32) int32 { - RegisterMatcher(&EqMatcher{Value: value}) - return 0 -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqInt32(value int32) int32 { - RegisterMatcher(&NotEqMatcher{Value: value}) - return 0 -} - // Deprecated: Use Any[T any]() instead. func AnyInt32() int32 { RegisterMatcher(NewAnyMatcher(reflect.TypeOf((int32)(0)))) @@ -220,18 +112,6 @@ func Int32That(matcher ArgumentMatcher) int32 { return 0 } -// Deprecated: Use Eq[T any](value T) instead. -func EqInt32Slice(value []int32) []int32 { - RegisterMatcher(&EqMatcher{Value: value}) - return nil -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqInt32Slice(value []int32) []int32 { - RegisterMatcher(&NotEqMatcher{Value: value}) - return nil -} - // Deprecated: Use Any[T any]() instead. func AnyInt32Slice() []int32 { RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((int32)(0))))) @@ -244,18 +124,6 @@ func Int32SliceThat(matcher ArgumentMatcher) []int32 { return nil } -// Deprecated: Use Eq[T any](value T) instead. -func EqInt64(value int64) int64 { - RegisterMatcher(&EqMatcher{Value: value}) - return 0 -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqInt64(value int64) int64 { - RegisterMatcher(&NotEqMatcher{Value: value}) - return 0 -} - // Deprecated: Use Any[T any]() instead. func AnyInt64() int64 { RegisterMatcher(NewAnyMatcher(reflect.TypeOf((int64)(0)))) @@ -268,18 +136,6 @@ func Int64That(matcher ArgumentMatcher) int64 { return 0 } -// Deprecated: Use Eq[T any](value T) instead. -func EqInt64Slice(value []int64) []int64 { - RegisterMatcher(&EqMatcher{Value: value}) - return nil -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqInt64Slice(value []int64) []int64 { - RegisterMatcher(&NotEqMatcher{Value: value}) - return nil -} - // Deprecated: Use Any[T any]() instead. func AnyInt64Slice() []int64 { RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((int64)(0))))) @@ -292,18 +148,6 @@ func Int64SliceThat(matcher ArgumentMatcher) []int64 { return nil } -// Deprecated: Use Eq[T any](value T) instead. -func EqUint(value uint) uint { - RegisterMatcher(&EqMatcher{Value: value}) - return 0 -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqUint(value uint) uint { - RegisterMatcher(&NotEqMatcher{Value: value}) - return 0 -} - // Deprecated: Use Any[T any]() instead. func AnyUint() uint { RegisterMatcher(NewAnyMatcher(reflect.TypeOf((uint)(0)))) @@ -316,18 +160,6 @@ func UintThat(matcher ArgumentMatcher) uint { return 0 } -// Deprecated: Use Eq[T any](value T) instead. -func EqUintSlice(value []uint) []uint { - RegisterMatcher(&EqMatcher{Value: value}) - return nil -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqUintSlice(value []uint) []uint { - RegisterMatcher(&NotEqMatcher{Value: value}) - return nil -} - // Deprecated: Use Any[T any]() instead. func AnyUintSlice() []uint { RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((uint)(0))))) @@ -340,18 +172,6 @@ func UintSliceThat(matcher ArgumentMatcher) []uint { return nil } -// Deprecated: Use Eq[T any](value T) instead. -func EqUint8(value uint8) uint8 { - RegisterMatcher(&EqMatcher{Value: value}) - return 0 -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqUint8(value uint8) uint8 { - RegisterMatcher(&NotEqMatcher{Value: value}) - return 0 -} - // Deprecated: Use Any[T any]() instead. func AnyUint8() uint8 { RegisterMatcher(NewAnyMatcher(reflect.TypeOf((uint8)(0)))) @@ -364,18 +184,6 @@ func Uint8That(matcher ArgumentMatcher) uint8 { return 0 } -// Deprecated: Use Eq[T any](value T) instead. -func EqUint8Slice(value []uint8) []uint8 { - RegisterMatcher(&EqMatcher{Value: value}) - return nil -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqUint8Slice(value []uint8) []uint8 { - RegisterMatcher(&NotEqMatcher{Value: value}) - return nil -} - // Deprecated: Use Any[T any]() instead. func AnyUint8Slice() []uint8 { RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((uint8)(0))))) @@ -388,18 +196,6 @@ func Uint8SliceThat(matcher ArgumentMatcher) []uint8 { return nil } -// Deprecated: Use Eq[T any](value T) instead. -func EqUint16(value uint16) uint16 { - RegisterMatcher(&EqMatcher{Value: value}) - return 0 -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqUint16(value uint16) uint16 { - RegisterMatcher(&NotEqMatcher{Value: value}) - return 0 -} - // Deprecated: Use Any[T any]() instead. func AnyUint16() uint16 { RegisterMatcher(NewAnyMatcher(reflect.TypeOf((uint16)(0)))) @@ -412,18 +208,6 @@ func Uint16That(matcher ArgumentMatcher) uint16 { return 0 } -// Deprecated: Use Eq[T any](value T) instead. -func EqUint16Slice(value []uint16) []uint16 { - RegisterMatcher(&EqMatcher{Value: value}) - return nil -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqUint16Slice(value []uint16) []uint16 { - RegisterMatcher(&NotEqMatcher{Value: value}) - return nil -} - // Deprecated: Use Any[T any]() instead. func AnyUint16Slice() []uint16 { RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((uint16)(0))))) @@ -436,18 +220,6 @@ func Uint16SliceThat(matcher ArgumentMatcher) []uint16 { return nil } -// Deprecated: Use Eq[T any](value T) instead. -func EqUint32(value uint32) uint32 { - RegisterMatcher(&EqMatcher{Value: value}) - return 0 -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqUint32(value uint32) uint32 { - RegisterMatcher(&NotEqMatcher{Value: value}) - return 0 -} - // Deprecated: Use Any[T any]() instead. func AnyUint32() uint32 { RegisterMatcher(NewAnyMatcher(reflect.TypeOf((uint32)(0)))) @@ -460,18 +232,6 @@ func Uint32That(matcher ArgumentMatcher) uint32 { return 0 } -// Deprecated: Use Eq[T any](value T) instead. -func EqUint32Slice(value []uint32) []uint32 { - RegisterMatcher(&EqMatcher{Value: value}) - return nil -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqUint32Slice(value []uint32) []uint32 { - RegisterMatcher(&NotEqMatcher{Value: value}) - return nil -} - // Deprecated: Use Any[T any]() instead. func AnyUint32Slice() []uint32 { RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((uint32)(0))))) @@ -484,18 +244,6 @@ func Uint32SliceThat(matcher ArgumentMatcher) []uint32 { return nil } -// Deprecated: Use Eq[T any](value T) instead. -func EqUint64(value uint64) uint64 { - RegisterMatcher(&EqMatcher{Value: value}) - return 0 -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqUint64(value uint64) uint64 { - RegisterMatcher(&NotEqMatcher{Value: value}) - return 0 -} - // Deprecated: Use Any[T any]() instead. func AnyUint64() uint64 { RegisterMatcher(NewAnyMatcher(reflect.TypeOf((uint64)(0)))) @@ -508,18 +256,6 @@ func Uint64That(matcher ArgumentMatcher) uint64 { return 0 } -// Deprecated: Use Eq[T any](value T) instead. -func EqUint64Slice(value []uint64) []uint64 { - RegisterMatcher(&EqMatcher{Value: value}) - return nil -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqUint64Slice(value []uint64) []uint64 { - RegisterMatcher(&NotEqMatcher{Value: value}) - return nil -} - // Deprecated: Use Any[T any]() instead. func AnyUint64Slice() []uint64 { RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((uint64)(0))))) @@ -532,18 +268,6 @@ func Uint64SliceThat(matcher ArgumentMatcher) []uint64 { return nil } -// Deprecated: Use Eq[T any](value T) instead. -func EqUintptr(value uintptr) uintptr { - RegisterMatcher(&EqMatcher{Value: value}) - return 0 -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqUintptr(value uintptr) uintptr { - RegisterMatcher(&NotEqMatcher{Value: value}) - return 0 -} - // Deprecated: Use Any[T any]() instead. func AnyUintptr() uintptr { RegisterMatcher(NewAnyMatcher(reflect.TypeOf((uintptr)(0)))) @@ -556,18 +280,6 @@ func UintptrThat(matcher ArgumentMatcher) uintptr { return 0 } -// Deprecated: Use Eq[T any](value T) instead. -func EqUintptrSlice(value []uintptr) []uintptr { - RegisterMatcher(&EqMatcher{Value: value}) - return nil -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqUintptrSlice(value []uintptr) []uintptr { - RegisterMatcher(&NotEqMatcher{Value: value}) - return nil -} - // Deprecated: Use Any[T any]() instead. func AnyUintptrSlice() []uintptr { RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((uintptr)(0))))) @@ -580,18 +292,6 @@ func UintptrSliceThat(matcher ArgumentMatcher) []uintptr { return nil } -// Deprecated: Use Eq[T any](value T) instead. -func EqFloat32(value float32) float32 { - RegisterMatcher(&EqMatcher{Value: value}) - return 0 -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqFloat32(value float32) float32 { - RegisterMatcher(&NotEqMatcher{Value: value}) - return 0 -} - // Deprecated: Use Any[T any]() instead. func AnyFloat32() float32 { RegisterMatcher(NewAnyMatcher(reflect.TypeOf((float32)(0)))) @@ -604,18 +304,6 @@ func Float32That(matcher ArgumentMatcher) float32 { return 0 } -// Deprecated: Use Eq[T any](value T) instead. -func EqFloat32Slice(value []float32) []float32 { - RegisterMatcher(&EqMatcher{Value: value}) - return nil -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqFloat32Slice(value []float32) []float32 { - RegisterMatcher(&NotEqMatcher{Value: value}) - return nil -} - // Deprecated: Use Any[T any]() instead. func AnyFloat32Slice() []float32 { RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((float32)(0))))) @@ -628,18 +316,6 @@ func Float32SliceThat(matcher ArgumentMatcher) []float32 { return nil } -// Deprecated: Use Eq[T any](value T) instead. -func EqFloat64(value float64) float64 { - RegisterMatcher(&EqMatcher{Value: value}) - return 0 -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqFloat64(value float64) float64 { - RegisterMatcher(&NotEqMatcher{Value: value}) - return 0 -} - // Deprecated: Use Any[T any]() instead. func AnyFloat64() float64 { RegisterMatcher(NewAnyMatcher(reflect.TypeOf((float64)(0)))) @@ -652,18 +328,6 @@ func Float64That(matcher ArgumentMatcher) float64 { return 0 } -// Deprecated: Use Eq[T any](value T) instead. -func EqFloat64Slice(value []float64) []float64 { - RegisterMatcher(&EqMatcher{Value: value}) - return nil -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqFloat64Slice(value []float64) []float64 { - RegisterMatcher(&NotEqMatcher{Value: value}) - return nil -} - // Deprecated: Use Any[T any]() instead. func AnyFloat64Slice() []float64 { RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((float64)(0))))) @@ -676,18 +340,6 @@ func Float64SliceThat(matcher ArgumentMatcher) []float64 { return nil } -// Deprecated: Use Eq[T any](value T) instead. -func EqComplex64(value complex64) complex64 { - RegisterMatcher(&EqMatcher{Value: value}) - return 0 -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqComplex64(value complex64) complex64 { - RegisterMatcher(&NotEqMatcher{Value: value}) - return 0 -} - // Deprecated: Use Any[T any]() instead. func AnyComplex64() complex64 { RegisterMatcher(NewAnyMatcher(reflect.TypeOf((complex64)(0)))) @@ -700,18 +352,6 @@ func Complex64That(matcher ArgumentMatcher) complex64 { return 0 } -// Deprecated: Use Eq[T any](value T) instead. -func EqComplex64Slice(value []complex64) []complex64 { - RegisterMatcher(&EqMatcher{Value: value}) - return nil -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqComplex64Slice(value []complex64) []complex64 { - RegisterMatcher(&NotEqMatcher{Value: value}) - return nil -} - // Deprecated: Use Any[T any]() instead. func AnyComplex64Slice() []complex64 { RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((complex64)(0))))) @@ -724,18 +364,6 @@ func Complex64SliceThat(matcher ArgumentMatcher) []complex64 { return nil } -// Deprecated: Use Eq[T any](value T) instead. -func EqComplex128(value complex128) complex128 { - RegisterMatcher(&EqMatcher{Value: value}) - return 0 -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqComplex128(value complex128) complex128 { - RegisterMatcher(&NotEqMatcher{Value: value}) - return 0 -} - // Deprecated: Use Any[T any]() instead. func AnyComplex128() complex128 { RegisterMatcher(NewAnyMatcher(reflect.TypeOf((complex128)(0)))) @@ -748,18 +376,6 @@ func Complex128That(matcher ArgumentMatcher) complex128 { return 0 } -// Deprecated: Use Eq[T any](value T) instead. -func EqComplex128Slice(value []complex128) []complex128 { - RegisterMatcher(&EqMatcher{Value: value}) - return nil -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqComplex128Slice(value []complex128) []complex128 { - RegisterMatcher(&NotEqMatcher{Value: value}) - return nil -} - // Deprecated: Use Any[T any]() instead. func AnyComplex128Slice() []complex128 { RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((complex128)(0))))) @@ -772,18 +388,6 @@ func Complex128SliceThat(matcher ArgumentMatcher) []complex128 { return nil } -// Deprecated: Use Eq[T any](value T) instead. -func EqString(value string) string { - RegisterMatcher(&EqMatcher{Value: value}) - return "" -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqString(value string) string { - RegisterMatcher(&NotEqMatcher{Value: value}) - return "" -} - // Deprecated: Use Any[T any]() instead. func AnyString() string { RegisterMatcher(NewAnyMatcher(reflect.TypeOf(""))) @@ -796,18 +400,6 @@ func StringThat(matcher ArgumentMatcher) string { return "" } -// Deprecated: Use Eq[T any](value T) instead. -func EqStringSlice(value []string) []string { - RegisterMatcher(&EqMatcher{Value: value}) - return nil -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqStringSlice(value []string) []string { - RegisterMatcher(&NotEqMatcher{Value: value}) - return nil -} - // Deprecated: Use Any[T any]() instead. func AnyStringSlice() []string { RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf("")))) @@ -820,18 +412,6 @@ func StringSliceThat(matcher ArgumentMatcher) []string { return nil } -// Deprecated: Use Eq[T any](value T) instead. -func EqInterface(value interface{}) interface{} { - RegisterMatcher(&EqMatcher{Value: value}) - return nil -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqInterface(value interface{}) interface{} { - RegisterMatcher(&NotEqMatcher{Value: value}) - return nil -} - // Deprecated: Use Any[T any]() instead. func AnyInterface() interface{} { RegisterMatcher(NewAnyMatcher(reflect.TypeOf((*interface{})(nil)).Elem())) @@ -844,18 +424,6 @@ func InterfaceThat(matcher ArgumentMatcher) interface{} { return nil } -// Deprecated: Use Eq[T any](value T) instead. -func EqInterfaceSlice(value []interface{}) []interface{} { - RegisterMatcher(&EqMatcher{Value: value}) - return nil -} - -// Deprecated: Use NotEq[T any](value T) instead. -func NotEqInterfaceSlice(value []interface{}) []interface{} { - RegisterMatcher(&NotEqMatcher{Value: value}) - return nil -} - // Deprecated: Use Any[T any]() instead. func AnyInterfaceSlice() []interface{} { RegisterMatcher(NewAnyMatcher(reflect.SliceOf(reflect.TypeOf((*interface{})(nil)).Elem()))) diff --git a/matchers/http_request.go b/matchers/http_request.go deleted file mode 100644 index 1fde92a..0000000 --- a/matchers/http_request.go +++ /dev/null @@ -1,33 +0,0 @@ -// Code generated by pegomock. DO NOT EDIT. -package matchers - -import ( - "github.com/petergtz/pegomock/v3" - "reflect" - - http "net/http" -) - -func AnyHttpRequest() http.Request { - pegomock.RegisterMatcher(pegomock.NewAnyMatcher(reflect.TypeOf((*(http.Request))(nil)).Elem())) - var nullValue http.Request - return nullValue -} - -func EqHttpRequest(value http.Request) http.Request { - pegomock.RegisterMatcher(&pegomock.EqMatcher{Value: value}) - var nullValue http.Request - return nullValue -} - -func NotEqHttpRequest(value http.Request) http.Request { - pegomock.RegisterMatcher(&pegomock.NotEqMatcher{Value: value}) - var nullValue http.Request - return nullValue -} - -func HttpRequestThat(matcher pegomock.ArgumentMatcher) http.Request { - pegomock.RegisterMatcher(matcher) - var nullValue http.Request - return nullValue -} diff --git a/matchers/io_readcloser.go b/matchers/io_readcloser.go deleted file mode 100644 index d633b5b..0000000 --- a/matchers/io_readcloser.go +++ /dev/null @@ -1,33 +0,0 @@ -// Code generated by pegomock. DO NOT EDIT. -package matchers - -import ( - "github.com/petergtz/pegomock/v3" - "reflect" - - io "io" -) - -func AnyIoReadCloser() io.ReadCloser { - pegomock.RegisterMatcher(pegomock.NewAnyMatcher(reflect.TypeOf((*(io.ReadCloser))(nil)).Elem())) - var nullValue io.ReadCloser - return nullValue -} - -func EqIoReadCloser(value io.ReadCloser) io.ReadCloser { - pegomock.RegisterMatcher(&pegomock.EqMatcher{Value: value}) - var nullValue io.ReadCloser - return nullValue -} - -func NotEqIoReadCloser(value io.ReadCloser) io.ReadCloser { - pegomock.RegisterMatcher(&pegomock.NotEqMatcher{Value: value}) - var nullValue io.ReadCloser - return nullValue -} - -func IoReadCloserThat(matcher pegomock.ArgumentMatcher) io.ReadCloser { - pegomock.RegisterMatcher(matcher) - var nullValue io.ReadCloser - return nullValue -} diff --git a/matchers/map_of_http_file_to_http_file.go b/matchers/map_of_http_file_to_http_file.go deleted file mode 100644 index 5fc9093..0000000 --- a/matchers/map_of_http_file_to_http_file.go +++ /dev/null @@ -1,33 +0,0 @@ -// Code generated by pegomock. DO NOT EDIT. -package matchers - -import ( - "github.com/petergtz/pegomock/v3" - "reflect" - - http "net/http" -) - -func AnyMapOfHttpFileToHttpFile() map[http.File]http.File { - pegomock.RegisterMatcher(pegomock.NewAnyMatcher(reflect.TypeOf((*(map[http.File]http.File))(nil)).Elem())) - var nullValue map[http.File]http.File - return nullValue -} - -func EqMapOfHttpFileToHttpFile(value map[http.File]http.File) map[http.File]http.File { - pegomock.RegisterMatcher(&pegomock.EqMatcher{Value: value}) - var nullValue map[http.File]http.File - return nullValue -} - -func NotEqMapOfHttpFileToHttpFile(value map[http.File]http.File) map[http.File]http.File { - pegomock.RegisterMatcher(&pegomock.NotEqMatcher{Value: value}) - var nullValue map[http.File]http.File - return nullValue -} - -func MapOfHttpFileToHttpFileThat(matcher pegomock.ArgumentMatcher) map[http.File]http.File { - pegomock.RegisterMatcher(matcher) - var nullValue map[http.File]http.File - return nullValue -} diff --git a/matchers/map_of_int_to_int.go b/matchers/map_of_int_to_int.go deleted file mode 100644 index d7152d8..0000000 --- a/matchers/map_of_int_to_int.go +++ /dev/null @@ -1,31 +0,0 @@ -// Code generated by pegomock. DO NOT EDIT. -package matchers - -import ( - "github.com/petergtz/pegomock/v3" - "reflect" -) - -func AnyMapOfIntToInt() map[int]int { - pegomock.RegisterMatcher(pegomock.NewAnyMatcher(reflect.TypeOf((*(map[int]int))(nil)).Elem())) - var nullValue map[int]int - return nullValue -} - -func EqMapOfIntToInt(value map[int]int) map[int]int { - pegomock.RegisterMatcher(&pegomock.EqMatcher{Value: value}) - var nullValue map[int]int - return nullValue -} - -func NotEqMapOfIntToInt(value map[int]int) map[int]int { - pegomock.RegisterMatcher(&pegomock.NotEqMatcher{Value: value}) - var nullValue map[int]int - return nullValue -} - -func MapOfIntToIntThat(matcher pegomock.ArgumentMatcher) map[int]int { - pegomock.RegisterMatcher(matcher) - var nullValue map[int]int - return nullValue -} diff --git a/matchers/map_of_string_to_empty_unnamed_struct.go b/matchers/map_of_string_to_empty_unnamed_struct.go deleted file mode 100644 index 30769d2..0000000 --- a/matchers/map_of_string_to_empty_unnamed_struct.go +++ /dev/null @@ -1,31 +0,0 @@ -// Code generated by pegomock. DO NOT EDIT. -package matchers - -import ( - "github.com/petergtz/pegomock/v3" - "reflect" -) - -func AnyMapOfStringToEmptyUnnamedStruct() map[string]struct{} { - pegomock.RegisterMatcher(pegomock.NewAnyMatcher(reflect.TypeOf((*(map[string]struct{}))(nil)).Elem())) - var nullValue map[string]struct{} - return nullValue -} - -func EqMapOfStringToEmptyUnnamedStruct(value map[string]struct{}) map[string]struct{} { - pegomock.RegisterMatcher(&pegomock.EqMatcher{Value: value}) - var nullValue map[string]struct{} - return nullValue -} - -func NotEqMapOfStringToEmptyUnnamedStruct(value map[string]struct{}) map[string]struct{} { - pegomock.RegisterMatcher(&pegomock.NotEqMatcher{Value: value}) - var nullValue map[string]struct{} - return nullValue -} - -func MapOfStringToEmptyUnnamedStructThat(matcher pegomock.ArgumentMatcher) map[string]struct{} { - pegomock.RegisterMatcher(matcher) - var nullValue map[string]struct{} - return nullValue -} diff --git a/matchers/map_of_string_to_http_request.go b/matchers/map_of_string_to_http_request.go deleted file mode 100644 index 118f393..0000000 --- a/matchers/map_of_string_to_http_request.go +++ /dev/null @@ -1,33 +0,0 @@ -// Code generated by pegomock. DO NOT EDIT. -package matchers - -import ( - "github.com/petergtz/pegomock/v3" - "reflect" - - http "net/http" -) - -func AnyMapOfStringToHttpRequest() map[string]http.Request { - pegomock.RegisterMatcher(pegomock.NewAnyMatcher(reflect.TypeOf((*(map[string]http.Request))(nil)).Elem())) - var nullValue map[string]http.Request - return nullValue -} - -func EqMapOfStringToHttpRequest(value map[string]http.Request) map[string]http.Request { - pegomock.RegisterMatcher(&pegomock.EqMatcher{Value: value}) - var nullValue map[string]http.Request - return nullValue -} - -func NotEqMapOfStringToHttpRequest(value map[string]http.Request) map[string]http.Request { - pegomock.RegisterMatcher(&pegomock.NotEqMatcher{Value: value}) - var nullValue map[string]http.Request - return nullValue -} - -func MapOfStringToHttpRequestThat(matcher pegomock.ArgumentMatcher) map[string]http.Request { - pegomock.RegisterMatcher(matcher) - var nullValue map[string]http.Request - return nullValue -} diff --git a/matchers/map_of_string_to_interface.go b/matchers/map_of_string_to_interface.go deleted file mode 100644 index 7207281..0000000 --- a/matchers/map_of_string_to_interface.go +++ /dev/null @@ -1,31 +0,0 @@ -// Code generated by pegomock. DO NOT EDIT. -package matchers - -import ( - "github.com/petergtz/pegomock/v3" - "reflect" -) - -func AnyMapOfStringToInterface() map[string]interface{} { - pegomock.RegisterMatcher(pegomock.NewAnyMatcher(reflect.TypeOf((*(map[string]interface{}))(nil)).Elem())) - var nullValue map[string]interface{} - return nullValue -} - -func EqMapOfStringToInterface(value map[string]interface{}) map[string]interface{} { - pegomock.RegisterMatcher(&pegomock.EqMatcher{Value: value}) - var nullValue map[string]interface{} - return nullValue -} - -func NotEqMapOfStringToInterface(value map[string]interface{}) map[string]interface{} { - pegomock.RegisterMatcher(&pegomock.NotEqMatcher{Value: value}) - var nullValue map[string]interface{} - return nullValue -} - -func MapOfStringToInterfaceThat(matcher pegomock.ArgumentMatcher) map[string]interface{} { - pegomock.RegisterMatcher(matcher) - var nullValue map[string]interface{} - return nullValue -} diff --git a/matchers/ptr_to_http_request.go b/matchers/ptr_to_http_request.go deleted file mode 100644 index becfbbf..0000000 --- a/matchers/ptr_to_http_request.go +++ /dev/null @@ -1,33 +0,0 @@ -// Code generated by pegomock. DO NOT EDIT. -package matchers - -import ( - "github.com/petergtz/pegomock/v3" - "reflect" - - http "net/http" -) - -func AnyPtrToHttpRequest() *http.Request { - pegomock.RegisterMatcher(pegomock.NewAnyMatcher(reflect.TypeOf((*(*http.Request))(nil)).Elem())) - var nullValue *http.Request - return nullValue -} - -func EqPtrToHttpRequest(value *http.Request) *http.Request { - pegomock.RegisterMatcher(&pegomock.EqMatcher{Value: value}) - var nullValue *http.Request - return nullValue -} - -func NotEqPtrToHttpRequest(value *http.Request) *http.Request { - pegomock.RegisterMatcher(&pegomock.NotEqMatcher{Value: value}) - var nullValue *http.Request - return nullValue -} - -func PtrToHttpRequestThat(matcher pegomock.ArgumentMatcher) *http.Request { - pegomock.RegisterMatcher(matcher) - var nullValue *http.Request - return nullValue -} diff --git a/matchers/recv_chan_of_string.go b/matchers/recv_chan_of_string.go deleted file mode 100644 index 8bc12ba..0000000 --- a/matchers/recv_chan_of_string.go +++ /dev/null @@ -1,31 +0,0 @@ -// Code generated by pegomock. DO NOT EDIT. -package matchers - -import ( - "github.com/petergtz/pegomock/v3" - "reflect" -) - -func AnyRecvChanOfString() <-chan string { - pegomock.RegisterMatcher(pegomock.NewAnyMatcher(reflect.TypeOf((*(<-chan string))(nil)).Elem())) - var nullValue <-chan string - return nullValue -} - -func EqRecvChanOfString(value <-chan string) <-chan string { - pegomock.RegisterMatcher(&pegomock.EqMatcher{Value: value}) - var nullValue <-chan string - return nullValue -} - -func NotEqRecvChanOfString(value <-chan string) <-chan string { - pegomock.RegisterMatcher(&pegomock.NotEqMatcher{Value: value}) - var nullValue <-chan string - return nullValue -} - -func RecvChanOfStringThat(matcher pegomock.ArgumentMatcher) <-chan string { - pegomock.RegisterMatcher(matcher) - var nullValue <-chan string - return nullValue -} diff --git a/matchers/send_chan_of_error.go b/matchers/send_chan_of_error.go deleted file mode 100644 index f1330f8..0000000 --- a/matchers/send_chan_of_error.go +++ /dev/null @@ -1,31 +0,0 @@ -// Code generated by pegomock. DO NOT EDIT. -package matchers - -import ( - "github.com/petergtz/pegomock/v3" - "reflect" -) - -func AnySendChanOfError() chan<- error { - pegomock.RegisterMatcher(pegomock.NewAnyMatcher(reflect.TypeOf((*(chan<- error))(nil)).Elem())) - var nullValue chan<- error - return nullValue -} - -func EqSendChanOfError(value chan<- error) chan<- error { - pegomock.RegisterMatcher(&pegomock.EqMatcher{Value: value}) - var nullValue chan<- error - return nullValue -} - -func NotEqSendChanOfError(value chan<- error) chan<- error { - pegomock.RegisterMatcher(&pegomock.NotEqMatcher{Value: value}) - var nullValue chan<- error - return nullValue -} - -func SendChanOfErrorThat(matcher pegomock.ArgumentMatcher) chan<- error { - pegomock.RegisterMatcher(matcher) - var nullValue chan<- error - return nullValue -} diff --git a/matchers/slice_of_string.go b/matchers/slice_of_string.go deleted file mode 100644 index de3956a..0000000 --- a/matchers/slice_of_string.go +++ /dev/null @@ -1,31 +0,0 @@ -// Code generated by pegomock. DO NOT EDIT. -package matchers - -import ( - "github.com/petergtz/pegomock/v3" - "reflect" -) - -func AnySliceOfString() []string { - pegomock.RegisterMatcher(pegomock.NewAnyMatcher(reflect.TypeOf((*([]string))(nil)).Elem())) - var nullValue []string - return nullValue -} - -func EqSliceOfString(value []string) []string { - pegomock.RegisterMatcher(&pegomock.EqMatcher{Value: value}) - var nullValue []string - return nullValue -} - -func NotEqSliceOfString(value []string) []string { - pegomock.RegisterMatcher(&pegomock.NotEqMatcher{Value: value}) - var nullValue []string - return nullValue -} - -func SliceOfStringThat(matcher pegomock.ArgumentMatcher) []string { - pegomock.RegisterMatcher(matcher) - var nullValue []string - return nullValue -} diff --git a/matchers/time_time.go b/matchers/time_time.go deleted file mode 100644 index 8184103..0000000 --- a/matchers/time_time.go +++ /dev/null @@ -1,33 +0,0 @@ -// Code generated by pegomock. DO NOT EDIT. -package matchers - -import ( - "github.com/petergtz/pegomock/v3" - "reflect" - - time "time" -) - -func AnyTimeTime() time.Time { - pegomock.RegisterMatcher(pegomock.NewAnyMatcher(reflect.TypeOf((*(time.Time))(nil)).Elem())) - var nullValue time.Time - return nullValue -} - -func EqTimeTime(value time.Time) time.Time { - pegomock.RegisterMatcher(&pegomock.EqMatcher{Value: value}) - var nullValue time.Time - return nullValue -} - -func NotEqTimeTime(value time.Time) time.Time { - pegomock.RegisterMatcher(&pegomock.NotEqMatcher{Value: value}) - var nullValue time.Time - return nullValue -} - -func TimeTimeThat(matcher pegomock.ArgumentMatcher) time.Time { - pegomock.RegisterMatcher(matcher) - var nullValue time.Time - return nullValue -} diff --git a/mockgen/mockgen.go b/mockgen/mockgen.go index 5b699c4..1c9db55 100644 --- a/mockgen/mockgen.go +++ b/mockgen/mockgen.go @@ -15,39 +15,35 @@ // Based on the work done in // https://github.com/golang/mock/blob/d581abfc04272f381d7a05e4b80163ea4e2b9447/mockgen/mockgen.go -// MockGen generates mock implementations of Go interfaces. +// Package mockgen generates mock implementations of Go interfaces. package mockgen -// TODO: This does not support recursive embedded interfaces. -// TODO: This does not support embedding package-local interfaces in a separate file. - import ( "bytes" "fmt" "go/format" "go/token" "path" + "sort" "strconv" "strings" "unicode" - "github.com/petergtz/pegomock/v3/mockgen/util" - - "github.com/petergtz/pegomock/v3/model" + "github.com/petergtz/pegomock/v4/model" + "github.com/samber/lo" ) -const mockFrameworkImportPath = "github.com/petergtz/pegomock/v3" +const mockFrameworkImportPath = "github.com/petergtz/pegomock/v4" -func GenerateOutput(ast *model.Package, source, nameOut, packageOut, selfPackage string) ([]byte, map[string]string) { - g := generator{typesSet: make(map[string]string)} +func GenerateOutput(ast *model.Package, source, nameOut, packageOut, selfPackage string) []byte { + g := generator{} g.generateCode(source, ast, nameOut, packageOut, selfPackage) - return g.formattedOutput(), g.typesSet + return g.formattedOutput() } type generator struct { buf bytes.Buffer packageMap map[string]string // map from import path to package name - typesSet map[string]string } func (g *generator) generateCode(source string, pkg *model.Package, structName, pkgName, selfPackage string) { @@ -89,7 +85,8 @@ func generateUniquePackageNamesFor(importPaths map[string]bool) (packageMap, non nonVendorPackageMap = make(map[string]string, len(importPaths)) packageNamesAlreadyUsed := make(map[string]bool, len(importPaths)) - sortedImportPaths := util.SortedKeys(importPaths) + sortedImportPaths := lo.Keys(importPaths) + sort.Strings(sortedImportPaths) for _, importPath := range sortedImportPaths { sanitizedPackagePathBaseName := sanitize(path.Base(importPath)) @@ -156,12 +153,6 @@ func (g *generator) generateMockFor(iface *model.Interface, mockTypeName, selfPa for _, method := range iface.Methods { g.generateMockMethod(mockTypeName, typeParamNames, method, selfPackage) g.emptyLine() - - addTypesFromMethodParamsTo(g.typesSet, method.In, g.packageMap) - addTypesFromMethodParamsTo(g.typesSet, method.Out, g.packageMap) - if method.Variadic != nil { - addTypesFromMethodParamsTo(g.typesSet, []*model.Parameter{method.Variadic}, g.packageMap) - } } g.generateMockVerifyMethods(mockTypeName, typeParamNames) g.generateVerifierType(mockTypeName, typeParams, typeParamNames) @@ -432,165 +423,6 @@ func stringSliceFrom(types []model.Type, packageMap map[string]string, pkgOverri return result } -func addTypesFromMethodParamsTo(typesSet map[string]string, params []*model.Parameter, packageMap map[string]string) { - for _, param := range params { - switch typedType := param.Type.(type) { - case *model.NamedType, *model.PointerType, *model.ArrayType, *model.MapType, *model.ChanType: - if _, exists := typesSet[underscoreNameFor(typedType, packageMap)]; !exists { - typesSet[underscoreNameFor(typedType, packageMap)] = generateMatcherSourceCode(typedType, packageMap) - } - case *model.FuncType: - // matcher generation for funcs not supported yet - // TODO implement - case model.PredeclaredType: - // skip. These come as part of pegomock. - default: - panic("Should not get here") - } - } -} - -func generateMatcherSourceCode(t model.Type, packageMap map[string]string) string { - typePackage := optionalPackageOf(t, packageMap) - if typePackage != "" { - // By having an additional newline here 'go fmt' will treat this import as a separate list - // from a sorting perspective and should leave the file alone. - typePackage = fmt.Sprintf("\n\n\t%s", typePackage) - } - return fmt.Sprintf(`// Code generated by pegomock. DO NOT EDIT. -package matchers - -import ( - "github.com/petergtz/pegomock/v3" - "reflect"%v -) - -func Any%v() %v { - pegomock.RegisterMatcher(pegomock.NewAnyMatcher(reflect.TypeOf((*(%v))(nil)).Elem())) - var nullValue %v - return nullValue -} - -func Eq%v(value %v) %v { - pegomock.RegisterMatcher(&pegomock.EqMatcher{Value: value}) - var nullValue %v - return nullValue -} - -func NotEq%v(value %v) %v { - pegomock.RegisterMatcher(&pegomock.NotEqMatcher{Value: value}) - var nullValue %v - return nullValue -} - -func %vThat(matcher pegomock.ArgumentMatcher) %v { - pegomock.RegisterMatcher(matcher) - var nullValue %v - return nullValue -} -`, - typePackage, - camelcaseNameFor(t, packageMap), - t.String(packageMap, ""), - t.String(packageMap, ""), - t.String(packageMap, ""), - - camelcaseNameFor(t, packageMap), - t.String(packageMap, ""), - t.String(packageMap, ""), - t.String(packageMap, ""), - - camelcaseNameFor(t, packageMap), - t.String(packageMap, ""), - t.String(packageMap, ""), - t.String(packageMap, ""), - - camelcaseNameFor(t, packageMap), - t.String(packageMap, ""), - t.String(packageMap, ""), - ) -} - -func optionalPackageOf(t model.Type, packageMap map[string]string) string { - switch typedType := t.(type) { - case model.PredeclaredType: - return "" - case *model.NamedType: - return fmt.Sprintf("%v \"%v\"", packageMap[typedType.Package], vendorCleaned(typedType.Package)) - case *model.PointerType: - return optionalPackageOf(typedType.Type, packageMap) - case *model.ArrayType: - return optionalPackageOf(typedType.Type, packageMap) - case *model.MapType: - keyPackage := optionalPackageOf(typedType.Key, packageMap) - valuePackage := optionalPackageOf(typedType.Value, packageMap) - if keyPackage == valuePackage || valuePackage == "" { - return keyPackage - } else if keyPackage == "" { - return valuePackage - } - return keyPackage + "\n\n\t" + valuePackage - case *model.ChanType: - return optionalPackageOf(typedType.Type, packageMap) - // TODO: - // case *model.FuncType: - default: - panic(fmt.Sprintf("TODO implement optionalPackageOf for: %v\nis type of %T\n", typedType, typedType)) - } -} - -func spaceSeparatedNameFor(t model.Type, packageMap map[string]string) string { - switch typedType := t.(type) { - case model.PredeclaredType: - tt := typedType.String(packageMap, "") - switch tt { - case "interface{}": - // if a predeclared type is interface - // return a string type without curly brackets - return "interface" - case "struct{}": - // if a predeclared type is an empty unnamed struct - // return a string type without curly brackets - return "empty unnamed struct" - default: - return tt - } - case *model.NamedType: - return strings.Replace((typedType.String(packageMap, "")), ".", " ", -1) - case *model.PointerType: - return "ptr to " + spaceSeparatedNameFor(typedType.Type, packageMap) - case *model.ArrayType: - if typedType.Len == -1 { - return "slice of " + spaceSeparatedNameFor(typedType.Type, packageMap) - } else { - return "array of " + spaceSeparatedNameFor(typedType.Type, packageMap) - } - case *model.MapType: - return "map of " + spaceSeparatedNameFor(typedType.Key, packageMap) + " to " + spaceSeparatedNameFor(typedType.Value, packageMap) - case *model.ChanType: - switch typedType.Dir { - case model.RecvDir: - return "recv chan of " + spaceSeparatedNameFor(typedType.Type, packageMap) - case model.SendDir: - return "send chan of " + spaceSeparatedNameFor(typedType.Type, packageMap) - default: - return "chan of " + spaceSeparatedNameFor(typedType.Type, packageMap) - } - // TODO: - // case *model.FuncType: - default: - return fmt.Sprintf("TODO implement matcher for: %v\nis type of %T\n", typedType, typedType) - } -} - -func camelcaseNameFor(t model.Type, packageMap map[string]string) string { - return strings.Replace(strings.Title(strings.Replace(spaceSeparatedNameFor(t, packageMap), "_", " ", -1)), " ", "", -1) -} - -func underscoreNameFor(t model.Type, packageMap map[string]string) string { - return strings.ToLower(strings.Replace(spaceSeparatedNameFor(t, packageMap), " ", "_", -1)) -} - func (g *generator) p(format string, args ...interface{}) *generator { fmt.Fprintf(&g.buf, format+"\n", args...) return g diff --git a/mockgen/mockgen_suite_test.go b/mockgen/mockgen_suite_test.go deleted file mode 100644 index 68c83e5..0000000 --- a/mockgen/mockgen_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package mockgen_test - -import ( - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" - - "testing" -) - -func TestMockgen(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Mockgen Suite") -} diff --git a/mockgen/mockgen_test.go b/mockgen/mockgen_test.go deleted file mode 100644 index e847c90..0000000 --- a/mockgen/mockgen_test.go +++ /dev/null @@ -1,64 +0,0 @@ -package mockgen_test - -import ( - "github.com/petergtz/pegomock/v3/mockgen" - "github.com/petergtz/pegomock/v3/modelgen/xtools_packages" - - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" -) - -var _ = Describe("Mockgen", func() { - Context("matcherSourceCodes", func() { - It("uses correct naming pattern with underscores for keys, and correct types etc. in source code", func() { - ast, e := xtools_packages.GenerateModel("github.com/petergtz/pegomock/v3/test_interface", "Display") - Expect(e).NotTo(HaveOccurred()) - _, matcherSourceCodes := mockgen.GenerateOutput(ast, "irrelevant", "MockDisplay", "test_package", "") - - Expect(matcherSourceCodes).To(SatisfyAll( - HaveLen(12), - HaveKeyWithValue("http_request", SatisfyAll( - ContainSubstring("http \"net/http\""), - ContainSubstring("func AnyHttpRequest() http.Request"), - )), - HaveKeyWithValue("ptr_to_http_request", SatisfyAll( - ContainSubstring("http \"net/http\""), - ContainSubstring("func AnyPtrToHttpRequest() *http.Request"), - )), - HaveKeyWithValue("slice_of_string", - ContainSubstring("func AnySliceOfString() []string"), - ), - HaveKeyWithValue("map_of_string_to_http_request", SatisfyAll( - ContainSubstring("http \"net/http\""), - ContainSubstring("func AnyMapOfStringToHttpRequest() map[string]http.Request"), - )), - HaveKeyWithValue("io_readcloser", SatisfyAll( - ContainSubstring("func AnyIoReadCloser() io.ReadCloser"), - )), - HaveKeyWithValue("map_of_string_to_interface", SatisfyAll( - ContainSubstring("func AnyMapOfStringToInterface() map[string]interface{}"), - )), - HaveKeyWithValue("time_time", SatisfyAll( - ContainSubstring("time \"time\""), - ContainSubstring("func AnyTimeTime() time.Time"), - )), - HaveKeyWithValue("recv_chan_of_string", SatisfyAll( - ContainSubstring("func AnyRecvChanOfString() <-chan string"), - )), - HaveKeyWithValue("send_chan_of_error", SatisfyAll( - ContainSubstring("func AnySendChanOfError() chan<- error"), - )), - HaveKeyWithValue("map_of_int_to_int", SatisfyAll( - ContainSubstring("func AnyMapOfIntToInt() map[int]int"), - )), - HaveKeyWithValue("map_of_http_file_to_http_file", SatisfyAll( - ContainSubstring("http \"net/http\""), - Not(MatchRegexp("http \"net/http\"\\s+http \"net/http\"")), - )), - HaveKeyWithValue("map_of_string_to_empty_unnamed_struct", SatisfyAll( - ContainSubstring("func AnyMapOfStringToEmptyUnnamedStruct() map[string]struct{}"), - )), - )) - }) - }) -}) diff --git a/mockgen/util/sort.go b/mockgen/util/sort.go deleted file mode 100644 index 73b0105..0000000 --- a/mockgen/util/sort.go +++ /dev/null @@ -1,13 +0,0 @@ -package util - -import "sort" - -// SortedKeys returns the keys of a map in alphabetical order. -func SortedKeys(m map[string]bool) []string { - var keys []string - for k := range m { - keys = append(keys, k) - } - sort.Strings(keys) - return keys -} diff --git a/mockgen/util/util_test.go b/mockgen/util/util_test.go deleted file mode 100644 index e935f2c..0000000 --- a/mockgen/util/util_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package util_test - -import ( - "testing" - - "github.com/onsi/ginkgo/v2" - . "github.com/onsi/ginkgo/v2" - "github.com/onsi/gomega" - . "github.com/onsi/gomega" - "github.com/petergtz/pegomock/v3/mockgen/util" -) - -func TestUtil(t *testing.T) { - gomega.RegisterFailHandler(ginkgo.Fail) - ginkgo.RunSpecs(t, "Util Suite") -} - -var _ = Describe("util", func() { - Context("sort", func() { - It("SortedKeys returns map keys in alphabetical order", func() { - importPaths := map[string]bool{ - "github.com/b/mypackage": true, - "github.com/c/mypackage": true, - "github.com/a/mypackage": true, - } - - sortedImportPaths := util.SortedKeys(importPaths) - Expect(sortedImportPaths).To(HaveLen(3)) - Expect(sortedImportPaths[0]).To(Equal("github.com/a/mypackage")) - Expect(sortedImportPaths[1]).To(Equal("github.com/b/mypackage")) - Expect(sortedImportPaths[2]).To(Equal("github.com/c/mypackage")) - }) - }) -}) diff --git a/modelgen/gomock/parse.go b/modelgen/gomock/parse.go deleted file mode 100644 index b9eb09a..0000000 --- a/modelgen/gomock/parse.go +++ /dev/null @@ -1,457 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package gomock - -// This file contains the model construction by parsing source files. - -import ( - "flag" - "fmt" - "go/ast" - "go/parser" - "go/token" - "log" - "os" - "path" - "strconv" - "strings" - - "github.com/petergtz/pegomock/v3/model" -) - -var ( - imports = flag.String("imports", "", "(source mode) Comma-separated name=path pairs of explicit imports to use.") - auxFiles = flag.String("aux_files", "", "(source mode) Comma-separated pkg=path pairs of auxiliary Go source files.") -) - -// TODO: simplify error reporting - -func ParseFile(source string) (*model.Package, error) { - fmt.Fprintln(os.Stderr, "WARNING: The gomock package is deprecated and will be removed in a future version.") - - fs := token.NewFileSet() - file, err := parser.ParseFile(fs, source, nil, 0) - if err != nil { - return nil, fmt.Errorf("failed parsing source file %v: %v", source, err) - } - - p := &fileParser{ - fileSet: fs, - imports: make(map[string]string), - auxInterfaces: make(map[string]map[string]*ast.InterfaceType), - } - - // Handle -imports. - dotImports := make(map[string]bool) - if *imports != "" { - for _, kv := range strings.Split(*imports, ",") { - eq := strings.Index(kv, "=") - k, v := kv[:eq], kv[eq+1:] - if k == "." { - // TODO: Catch dupes? - dotImports[v] = true - } else { - // TODO: Catch dupes? - p.imports[k] = v - } - } - } - - // Handle -aux_files. - if err := p.parseAuxFiles(*auxFiles); err != nil { - return nil, err - } - p.addAuxInterfacesFromFile("", file) // this file - - pkg, err := p.parseFile(file) - if err != nil { - return nil, err - } - pkg.DotImports = make([]string, 0, len(dotImports)) - for path := range dotImports { - pkg.DotImports = append(pkg.DotImports, path) - } - return pkg, nil -} - -type fileParser struct { - fileSet *token.FileSet - imports map[string]string // package name => import path - - auxFiles []*ast.File - auxInterfaces map[string]map[string]*ast.InterfaceType // package (or "") => name => interface -} - -func (p *fileParser) errorf(pos token.Pos, format string, args ...interface{}) error { - ps := p.fileSet.Position(pos) - format = "%s:%d:%d: " + format - args = append([]interface{}{ps.Filename, ps.Line, ps.Column}, args...) - return fmt.Errorf(format, args...) -} - -func (p *fileParser) parseAuxFiles(auxFiles string) error { - auxFiles = strings.TrimSpace(auxFiles) - if auxFiles == "" { - return nil - } - for _, kv := range strings.Split(auxFiles, ",") { - parts := strings.SplitN(kv, "=", 2) - if len(parts) != 2 { - return fmt.Errorf("bad aux file spec: %v", kv) - } - file, err := parser.ParseFile(p.fileSet, parts[1], nil, 0) - if err != nil { - return err - } - p.auxFiles = append(p.auxFiles, file) - p.addAuxInterfacesFromFile(parts[0], file) - } - return nil -} - -func (p *fileParser) addAuxInterfacesFromFile(pkg string, file *ast.File) { - if _, ok := p.auxInterfaces[pkg]; !ok { - p.auxInterfaces[pkg] = make(map[string]*ast.InterfaceType) - } - for ni := range iterInterfaces(file) { - p.auxInterfaces[pkg][ni.name.Name] = ni.it - } -} - -func (p *fileParser) parseFile(file *ast.File) (*model.Package, error) { - allImports := importsOfFile(file) - // Don't stomp imports provided by -imports. Those should take precedence. - for pkg, path := range allImports { - if _, ok := p.imports[pkg]; !ok { - p.imports[pkg] = path - } - } - // Add imports from auxiliary files, which might be needed for embedded interfaces. - // Don't stomp any other imports. - for _, f := range p.auxFiles { - for pkg, path := range importsOfFile(f) { - if _, ok := p.imports[pkg]; !ok { - p.imports[pkg] = path - } - } - } - - var is []*model.Interface - for ni := range iterInterfaces(file) { - i, err := p.parseInterface(ni.name.String(), "", ni.it) - if err != nil { - return nil, err - } - is = append(is, i) - } - return &model.Package{ - Name: file.Name.String(), - Interfaces: is, - }, nil -} - -func (p *fileParser) parseInterface(name, pkg string, it *ast.InterfaceType) (*model.Interface, error) { - intf := &model.Interface{Name: name} - for _, field := range it.Methods.List { - switch v := field.Type.(type) { - case *ast.FuncType: - if nn := len(field.Names); nn != 1 { - return nil, fmt.Errorf("expected one name for interface %v, got %d", intf.Name, nn) - } - m := &model.Method{ - Name: field.Names[0].String(), - } - var err error - m.In, m.Variadic, m.Out, err = p.parseFunc(pkg, v) - if err != nil { - return nil, err - } - intf.Methods = append(intf.Methods, m) - case *ast.Ident: - // Embedded interface in this package. - ei := p.auxInterfaces[""][v.String()] - if ei == nil { - return nil, p.errorf(v.Pos(), "unknown embedded interface %s", v.String()) - } - eintf, err := p.parseInterface(v.String(), pkg, ei) - if err != nil { - return nil, err - } - // Copy the methods. - // TODO: apply shadowing rules. - for _, m := range eintf.Methods { - intf.Methods = append(intf.Methods, m) - } - case *ast.SelectorExpr: - // Embedded interface in another package. - fpkg, sel := v.X.(*ast.Ident).String(), v.Sel.String() - ei := p.auxInterfaces[fpkg][sel] - if ei == nil { - return nil, p.errorf(v.Pos(), "unknown embedded interface %s.%s", fpkg, sel) - } - epkg, ok := p.imports[fpkg] - if !ok { - return nil, p.errorf(v.X.Pos(), "unknown package %s", fpkg) - } - eintf, err := p.parseInterface(sel, epkg, ei) - if err != nil { - return nil, err - } - // Copy the methods. - // TODO: apply shadowing rules. - for _, m := range eintf.Methods { - intf.Methods = append(intf.Methods, m) - } - default: - return nil, fmt.Errorf("don't know how to mock method of type %T", field.Type) - } - } - return intf, nil -} - -func (p *fileParser) parseFunc(pkg string, f *ast.FuncType) (in []*model.Parameter, variadic *model.Parameter, out []*model.Parameter, err error) { - if f.Params != nil { - regParams := f.Params.List - if isVariadic(f) { - n := len(regParams) - varParams := regParams[n-1:] - regParams = regParams[:n-1] - vp, err := p.parseFieldList(pkg, varParams) - if err != nil { - return nil, nil, nil, p.errorf(varParams[0].Pos(), "failed parsing variadic argument: %v", err) - } - variadic = vp[0] - } - in, err = p.parseFieldList(pkg, regParams) - if err != nil { - return nil, nil, nil, p.errorf(f.Pos(), "failed parsing arguments: %v", err) - } - } - if f.Results != nil { - out, err = p.parseFieldList(pkg, f.Results.List) - if err != nil { - return nil, nil, nil, p.errorf(f.Pos(), "failed parsing returns: %v", err) - } - } - return -} - -func (p *fileParser) parseFieldList(pkg string, fields []*ast.Field) ([]*model.Parameter, error) { - nf := 0 - for _, f := range fields { - nn := len(f.Names) - if nn == 0 { - nn = 1 // anonymous parameter - } - nf += nn - } - if nf == 0 { - return nil, nil - } - ps := make([]*model.Parameter, nf) - i := 0 // destination index - for _, f := range fields { - t, err := p.parseType(pkg, f.Type) - if err != nil { - return nil, err - } - - if len(f.Names) == 0 { - // anonymous arg - ps[i] = &model.Parameter{Type: t} - i++ - continue - } - for _, name := range f.Names { - ps[i] = &model.Parameter{Name: name.Name, Type: t} - i++ - } - } - return ps, nil -} - -func (p *fileParser) parseType(pkg string, typ ast.Expr) (model.Type, error) { - switch v := typ.(type) { - case *ast.ArrayType: - ln := -1 - if v.Len != nil { - x, err := strconv.Atoi(v.Len.(*ast.BasicLit).Value) - if err != nil { - return nil, p.errorf(v.Len.Pos(), "bad array size: %v", err) - } - ln = x - } - t, err := p.parseType(pkg, v.Elt) - if err != nil { - return nil, err - } - return &model.ArrayType{Len: ln, Type: t}, nil - case *ast.ChanType: - t, err := p.parseType(pkg, v.Value) - if err != nil { - return nil, err - } - var dir model.ChanDir - if v.Dir == ast.SEND { - dir = model.SendDir - } - if v.Dir == ast.RECV { - dir = model.RecvDir - } - return &model.ChanType{Dir: dir, Type: t}, nil - case *ast.Ellipsis: - // assume we're parsing a variadic argument - return p.parseType(pkg, v.Elt) - case *ast.FuncType: - in, variadic, out, err := p.parseFunc(pkg, v) - if err != nil { - return nil, err - } - return &model.FuncType{In: in, Out: out, Variadic: variadic}, nil - case *ast.Ident: - if v.IsExported() { - // assume type in this package - return &model.NamedType{Package: pkg, Type: v.Name}, nil - } else { - // assume predeclared type - return model.PredeclaredType(v.Name), nil - } - case *ast.InterfaceType: - if v.Methods != nil && len(v.Methods.List) > 0 { - return nil, p.errorf(v.Pos(), "can't handle non-empty unnamed interface types") - } - return model.PredeclaredType("interface{}"), nil - case *ast.MapType: - key, err := p.parseType(pkg, v.Key) - if err != nil { - return nil, err - } - value, err := p.parseType(pkg, v.Value) - if err != nil { - return nil, err - } - return &model.MapType{Key: key, Value: value}, nil - case *ast.SelectorExpr: - pkgName := v.X.(*ast.Ident).String() - pkg, ok := p.imports[pkgName] - if !ok { - return nil, p.errorf(v.Pos(), "unknown package %q", pkgName) - } - return &model.NamedType{Package: pkg, Type: v.Sel.String()}, nil - case *ast.StarExpr: - t, err := p.parseType(pkg, v.X) - if err != nil { - return nil, err - } - return &model.PointerType{Type: t}, nil - case *ast.StructType: - if v.Fields != nil && len(v.Fields.List) > 0 { - return nil, p.errorf(v.Pos(), "can't handle non-empty unnamed struct types") - } - return model.PredeclaredType("struct{}"), nil - } - - return nil, fmt.Errorf("don't know how to parse type %T", typ) -} - -// importsOfFile returns a map of package name to import path -// of the imports in file. -func importsOfFile(file *ast.File) map[string]string { - /* We have to make guesses about some imports, because imports are not required - * to have names. Named imports are always certain. Unnamed imports are guessed - * to have a name of the last path component; if the last path component has dots, - * the first dot-delimited field is used as the name. - */ - - m := make(map[string]string) - for _, decl := range file.Decls { - gd, ok := decl.(*ast.GenDecl) - if !ok || gd.Tok != token.IMPORT { - continue - } - for _, spec := range gd.Specs { - is, ok := spec.(*ast.ImportSpec) - if !ok { - continue - } - pkg, importPath := "", string(is.Path.Value) - importPath = importPath[1 : len(importPath)-1] // remove quotes - - if is.Name != nil { - if is.Name.Name == "_" { - continue - } - pkg = removeDot(is.Name.Name) - } else { - _, last := path.Split(importPath) - pkg = strings.SplitN(last, ".", 2)[0] - } - if _, ok := m[pkg]; ok { - log.Fatalf("imported package collision: %q imported twice", pkg) - } - m[pkg] = importPath - } - } - return m -} - -func removeDot(s string) string { - if len(s) > 0 && s[len(s)-1] == '.' { - return s[0 : len(s)-1] - } - return s -} - -type namedInterface struct { - name *ast.Ident - it *ast.InterfaceType -} - -// Create an iterator over all interfaces in file. -func iterInterfaces(file *ast.File) <-chan namedInterface { - ch := make(chan namedInterface) - go func() { - for _, decl := range file.Decls { - gd, ok := decl.(*ast.GenDecl) - if !ok || gd.Tok != token.TYPE { - continue - } - for _, spec := range gd.Specs { - ts, ok := spec.(*ast.TypeSpec) - if !ok { - continue - } - it, ok := ts.Type.(*ast.InterfaceType) - if !ok { - continue - } - - ch <- namedInterface{ts.Name, it} - } - } - close(ch) - }() - return ch -} - -// isVariadic returns whether the function is variadic. -func isVariadic(f *ast.FuncType) bool { - nargs := len(f.Params.List) - if nargs == 0 { - return false - } - _, ok := f.Params.List[nargs-1].Type.(*ast.Ellipsis) - return ok -} diff --git a/modelgen/gomock/reflect.go b/modelgen/gomock/reflect.go deleted file mode 100644 index 9d8cc9c..0000000 --- a/modelgen/gomock/reflect.go +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package gomock - -// This file contains the model construction by reflection. - -import ( - "bytes" - "encoding/gob" - "flag" - "fmt" - "io" - "io/ioutil" - "os" - "os/exec" - "path/filepath" - "runtime" - "text/template" - - "github.com/petergtz/pegomock/v3/model" -) - -var ( - progOnly = flag.Bool("prog_only", false, "(reflect mode) Only generate the reflection program; write it to stdout.") - execOnly = flag.String("exec_only", "", "(reflect mode) If set, execute this reflection program.") -) - -func Reflect(importPath string, symbols []string) (*model.Package, error) { - // TODO: sanity check arguments - progPath := *execOnly - if *execOnly == "" { - workingDir, err := os.Getwd() - if err != nil { - return nil, err - } - tmpDir, err := ioutil.TempDir(workingDir, ".tmp_gomock_reflect_") - if err != nil { - return nil, err - } - defer func() { os.RemoveAll(tmpDir) }() - const progSource = "prog.go" - var progBinary = "prog.bin" - if runtime.GOOS == "windows" { - // Windows won't execute a program unless it has a ".exe" suffix. - progBinary += ".exe" - } - - // Generate program. - var program bytes.Buffer - data := reflectData{ - ImportPath: importPath, - Symbols: symbols, - } - if err := reflectProgram.Execute(&program, &data); err != nil { - return nil, err - } - if *progOnly { - io.Copy(os.Stdout, &program) - os.Exit(0) - } - if err := ioutil.WriteFile(filepath.Join(tmpDir, progSource), program.Bytes(), 0600); err != nil { - return nil, err - } - - // Build the program. - cmd := exec.Command("go", "build", "-mod=mod", "-o", progBinary, progSource) - cmd.Dir = tmpDir - stderr := &bytes.Buffer{} - cmd.Stderr = stderr - if err := cmd.Run(); err != nil { - return nil, fmt.Errorf("%v caused by:\n%v", err, stderr.String()) - } - progPath = filepath.Join(tmpDir, progBinary) - } - - // Run it. - cmd := exec.Command(progPath) - var stdout bytes.Buffer - cmd.Stdout = &stdout - cmd.Stderr = os.Stderr - if err := cmd.Run(); err != nil { - return nil, err - } - - // Process output. - var pkg model.Package - if err := gob.NewDecoder(&stdout).Decode(&pkg); err != nil { - return nil, err - } - return &pkg, nil -} - -type reflectData struct { - ImportPath string - Symbols []string -} - -// This program reflects on an interface value, and prints the -// gob encoding of a model.Package to standard output. -// JSON doesn't work because of the model.Type interface. -var reflectProgram = template.Must(template.New("program").Parse(` -package main - -import ( - "encoding/gob" - "fmt" - "os" - "path" - "reflect" - - "github.com/petergtz/pegomock/v3/model" - "github.com/petergtz/pegomock/v3/modelgen/gomock" - - pkg_ {{printf "%q" .ImportPath}} -) - -func main() { - its := []struct{ - sym string - typ reflect.Type - }{ - {{range .Symbols}} - { {{printf "%q" .}}, reflect.TypeOf((*pkg_.{{.}})(nil)).Elem()}, - {{end}} - } - pkg := &model.Package{ - // NOTE: This behaves contrary to documented behaviour if the - // package name is not the final component of the import path. - // The reflect package doesn't expose the package name, though. - Name: path.Base({{printf "%q" .ImportPath}}), - } - - for _, it := range its { - intf, err := gomock.InterfaceFromInterfaceType(it.typ) - if err != nil { - fmt.Fprintf(os.Stderr, "Reflection: %v\n", err) - os.Exit(1) - } - intf.Name = it.sym - pkg.Interfaces = append(pkg.Interfaces, intf) - } - if err := gob.NewEncoder(os.Stdout).Encode(pkg); err != nil { - fmt.Fprintf(os.Stderr, "gob encode: %v\n", err) - os.Exit(1) - } -} -`)) diff --git a/modelgen/gomock/reflect_helpers.go b/modelgen/gomock/reflect_helpers.go deleted file mode 100644 index 2ea3ee6..0000000 --- a/modelgen/gomock/reflect_helpers.go +++ /dev/null @@ -1,182 +0,0 @@ -package gomock - -import ( - "encoding/gob" - "fmt" - "reflect" - - "github.com/petergtz/pegomock/v3/model" -) - -func init() { - gob.Register(&model.ArrayType{}) - gob.Register(&model.ChanType{}) - gob.Register(&model.FuncType{}) - gob.Register(&model.MapType{}) - gob.Register(&model.NamedType{}) - gob.Register(&model.PointerType{}) - gob.Register(model.PredeclaredType("")) -} - -func InterfaceFromInterfaceType(it reflect.Type) (*model.Interface, error) { - if it.Kind() != reflect.Interface { - return nil, fmt.Errorf("%v is not an interface", it) - } - intf := &model.Interface{} - - for i := 0; i < it.NumMethod(); i++ { - mt := it.Method(i) - // TODO: need to skip unexported methods? or just raise an error? - m := &model.Method{ - Name: mt.Name, - } - - var err error - m.In, m.Variadic, m.Out, err = funcArgsFromType(mt.Type) - if err != nil { - return nil, err - } - - intf.Methods = append(intf.Methods, m) - } - - return intf, nil -} - -// t's Kind must be a reflect.Func. -func funcArgsFromType(t reflect.Type) (in []*model.Parameter, variadic *model.Parameter, out []*model.Parameter, err error) { - nin := t.NumIn() - if t.IsVariadic() { - nin-- - } - var p *model.Parameter - for i := 0; i < nin; i++ { - p, err = parameterFromType(t.In(i)) - if err != nil { - return - } - in = append(in, p) - } - if t.IsVariadic() { - p, err = parameterFromType(t.In(nin).Elem()) - if err != nil { - return - } - variadic = p - } - for i := 0; i < t.NumOut(); i++ { - p, err = parameterFromType(t.Out(i)) - if err != nil { - return - } - out = append(out, p) - } - return -} - -func parameterFromType(t reflect.Type) (*model.Parameter, error) { - tt, err := typeFromType(t) - if err != nil { - return nil, err - } - return &model.Parameter{Type: tt}, nil -} - -var errorType = reflect.TypeOf((*error)(nil)).Elem() - -var byteType = reflect.TypeOf(byte(0)) - -func typeFromType(t reflect.Type) (model.Type, error) { - // Hack workaround for https://golang.org/issue/3853. - // This explicit check should not be necessary. - if t == byteType { - return model.PredeclaredType("byte"), nil - } - - if imp := t.PkgPath(); imp != "" { - return &model.NamedType{ - Package: imp, - Type: t.Name(), - }, nil - } - - // only unnamed or predeclared types after here - - // Lots of types have element types. Let's do the parsing and error checking for all of them. - var elemType model.Type - switch t.Kind() { - case reflect.Array, reflect.Chan, reflect.Map, reflect.Ptr, reflect.Slice: - var err error - elemType, err = typeFromType(t.Elem()) - if err != nil { - return nil, err - } - } - - switch t.Kind() { - case reflect.Array: - return &model.ArrayType{ - Len: t.Len(), - Type: elemType, - }, nil - case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, - reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, - reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128, reflect.String: - return model.PredeclaredType(t.Kind().String()), nil - case reflect.Chan: - var dir model.ChanDir - switch t.ChanDir() { - case reflect.RecvDir: - dir = model.RecvDir - case reflect.SendDir: - dir = model.SendDir - } - return &model.ChanType{ - Dir: dir, - Type: elemType, - }, nil - case reflect.Func: - in, variadic, out, err := funcArgsFromType(t) - if err != nil { - return nil, err - } - return &model.FuncType{ - In: in, - Out: out, - Variadic: variadic, - }, nil - case reflect.Interface: - // Two special interfaces. - if t.NumMethod() == 0 { - return model.PredeclaredType("interface{}"), nil - } - if t == errorType { - return model.PredeclaredType("error"), nil - } - case reflect.Map: - kt, err := typeFromType(t.Key()) - if err != nil { - return nil, err - } - return &model.MapType{ - Key: kt, - Value: elemType, - }, nil - case reflect.Ptr: - return &model.PointerType{ - Type: elemType, - }, nil - case reflect.Slice: - return &model.ArrayType{ - Len: -1, - Type: elemType, - }, nil - case reflect.Struct: - if t.NumField() == 0 { - return model.PredeclaredType("struct{}"), nil - } - } - - // TODO: Struct, UnsafePointer - return nil, fmt.Errorf("can't yet turn %v (%v) into a model.Type", t, t.Kind()) -} diff --git a/modelgen/gomock/reflect_test.go b/modelgen/gomock/reflect_test.go deleted file mode 100644 index 5fc5efb..0000000 --- a/modelgen/gomock/reflect_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package gomock_test - -import ( - "io" - "os" - "testing" - - "github.com/onsi/ginkgo/v2" - . "github.com/onsi/ginkgo/v2" - "github.com/onsi/gomega" - . "github.com/onsi/gomega" - "github.com/petergtz/pegomock/v3/modelgen/gomock" -) - -func TestGomock(t *testing.T) { - gomega.RegisterFailHandler(ginkgo.Fail) - ginkgo.RunSpecs(t, "gomock Suite") -} - -var _ = XDescribe("reflect", func() { - AfterEach(func() { - os.RemoveAll("../../vendor") - }) - - It("can generate mocks for interfaces taken from vendored packages", func() { - e := os.MkdirAll("../../vendor/github.com/petergtz/vendored_package/", 0755) - Expect(e).NotTo(HaveOccurred()) - - file, e := os.Create("../../vendor/github.com/petergtz/vendored_package/iface.go") - Expect(e).NotTo(HaveOccurred()) - - _, e = io.WriteString(file, "package vendored_package\n\ntype Interface interface{}") - Expect(e).NotTo(HaveOccurred()) - - _, e = gomock.Reflect("github.com/petergtz/vendored_package", []string{"Interface"}) - Expect(e).NotTo(HaveOccurred()) - }) -}) diff --git a/modelgen/modelgen_test.go b/modelgen/modelgen_test.go index f3495d5..d706f72 100644 --- a/modelgen/modelgen_test.go +++ b/modelgen/modelgen_test.go @@ -15,13 +15,10 @@ package modelgen_test import ( - "fmt" - "sort" "testing" - "github.com/petergtz/pegomock/v3/model" - "github.com/petergtz/pegomock/v3/modelgen/gomock" - "github.com/petergtz/pegomock/v3/modelgen/xtools_packages" + "github.com/petergtz/pegomock/v4/model" + "github.com/petergtz/pegomock/v4/modelgen/xtools_packages" "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2" @@ -41,26 +38,9 @@ func (a alphabetically) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a alphabetically) Less(i, j int) bool { return a[i].Name < a[j].Name } var _ = Describe("xtools_packages", func() { - It("generates an equivalent model as gomock/reflect does", func() { - pkgFromReflect, e := gomock.Reflect("github.com/petergtz/pegomock/v3/test_interface", []string{"Display"}) - Expect(e).NotTo(HaveOccurred()) - sort.Sort(alphabetically(pkgFromReflect.Interfaces[0].Methods)) - - pkgFromLoader, e := xtools_packages.GenerateModel("github.com/petergtz/pegomock/v3/test_interface", "Display") - Expect(e).NotTo(HaveOccurred()) - sort.Sort(alphabetically(pkgFromLoader.Interfaces[0].Methods)) - - Expect(pkgFromLoader.Name).To(Equal(pkgFromReflect.Name)) - Expect(pkgFromLoader.Interfaces).To(HaveLen(1)) - Expect(pkgFromLoader.Interfaces[0].Name).To(Equal("Display")) - - for i := range pkgFromReflect.Interfaces[0].Methods { - expectMethodsEqual(pkgFromLoader.Interfaces[0].Methods[i], pkgFromReflect.Interfaces[0].Methods[i]) - } - }) It("generates a model with the basic properties", func() { - pkg, e := xtools_packages.GenerateModel("github.com/petergtz/pegomock/v3/modelgen/test_data/default_test_interface", "Display") + pkg, e := xtools_packages.GenerateModel("github.com/petergtz/pegomock/v4/modelgen/test_data/default_test_interface", "Display") Expect(e).NotTo(HaveOccurred()) Expect(pkg.Name).To(Equal("test_interface")) @@ -71,7 +51,7 @@ var _ = Describe("xtools_packages", func() { &model.Method{ Name: "Show", In: []*model.Parameter{ - &model.Parameter{ + { Name: "_param0", Type: model.PredeclaredType("string"), }, @@ -82,18 +62,3 @@ var _ = Describe("xtools_packages", func() { // TODO add more test cases }) }) - -func expectMethodsEqual(actual, expected *model.Method) { - Expect(actual.Name).To(Equal(expected.Name)) - expectParamsEqual(actual.Name, actual.In, expected.In) - expectParamsEqual(actual.Name, actual.Out, expected.Out) -} - -func expectParamsEqual(methodName string, actual, expected []*model.Parameter) { - for i := range expected { - if actual[i].Name != expected[i].Name { - fmt.Printf("Note: In method %v, param names differ \"%v\" != \"%v\"\n", methodName, actual[i].Name, expected[i].Name) - } - Expect(actual[i].Type).To(Equal(expected[i].Type)) - } -} diff --git a/modelgen/xtools_loader/loader.go b/modelgen/xtools_loader/loader.go deleted file mode 100644 index e645141..0000000 --- a/modelgen/xtools_loader/loader.go +++ /dev/null @@ -1,197 +0,0 @@ -package xtools_loader - -import ( - "errors" - "fmt" - "go/ast" - "go/types" - - "github.com/petergtz/pegomock/v3/model" - "golang.org/x/tools/go/loader" -) - -func GenerateModel(importPath string, interfaceName string) (*model.Package, error) { - panic("DEPRECATED: Use GenerateModelViaPackages instead") - - var conf loader.Config - conf.Import(importPath) - program, e := conf.Load() - if e != nil { - panic(e) - } - info := program.Imported[importPath] - - for def := range info.Defs { - if def.Name == interfaceName && def.Obj.Kind == ast.Typ { - interfacetype, ok := def.Obj.Decl.(*ast.TypeSpec).Type.(*ast.InterfaceType) - if ok { - g := &modelGenerator{info: info} - iface := &model.Interface{ - Name: interfaceName, - Methods: g.modelMethodsFrom(interfacetype.Methods), - } - return &model.Package{ - Name: info.Pkg.Name(), - Interfaces: []*model.Interface{iface}, - }, nil - } - } - } - - return nil, errors.New("Did not find interface name \"" + interfaceName + "\"") -} - -type modelGenerator struct { - info *loader.PackageInfo -} - -func (g *modelGenerator) modelMethodsFrom(fields *ast.FieldList) (modelMethods []*model.Method) { - for _, field := range fields.List { - switch field.Type.(type) { - case *ast.FuncType: - modelMethods = append(modelMethods, g.modelMethodFrom(field)) - case *ast.Ident: - modelMethods = append(modelMethods, g.modelMethodsFrom(field.Type.(*ast.Ident).Obj.Decl.(*ast.TypeSpec).Type.(*ast.InterfaceType).Methods)...) - default: - panic(fmt.Sprintf("Unexpected expression in interface definition. Only methods and embedded interfaces are allowed, but got: %#v", field.Type)) - } - } - return -} - -func (g *modelGenerator) modelMethodFrom(astMethod *ast.Field) *model.Method { - in, out, variadic := g.signatureFrom(astMethod.Type.(*ast.FuncType)) - return &model.Method{Name: astMethod.Names[0].Name, In: in, Variadic: variadic, Out: out} -} - -func (g *modelGenerator) signatureFrom(astFuncType *ast.FuncType) (in, out []*model.Parameter, variadic *model.Parameter) { - in, variadic = g.inParamsFrom(astFuncType.Params) - out = g.outParamsFrom(astFuncType.Results) - return -} - -func (g *modelGenerator) inParamsFrom(params *ast.FieldList) (in []*model.Parameter, variadic *model.Parameter) { - for _, param := range params.List { - for _, name := range param.Names { - if ellipsisType, isEllipsisType := param.Type.(*ast.Ellipsis); isEllipsisType { - variadic = g.newParam(name.Name, ellipsisType.Elt) - } else { - in = append(in, g.newParam(name.Name, param.Type)) - } - } - if len(param.Names) == 0 { - if ellipsisType, isEllipsisType := param.Type.(*ast.Ellipsis); isEllipsisType { - variadic = g.newParam("", ellipsisType.Elt) - } else { - in = append(in, g.newParam("", param.Type)) - } - } - } - return -} - -func (g *modelGenerator) outParamsFrom(results *ast.FieldList) (out []*model.Parameter) { - if results != nil { - for _, param := range results.List { - for _, name := range param.Names { - out = append(out, g.newParam(name.Name, param.Type)) - } - if len(param.Names) == 0 { - out = append(out, g.newParam("", param.Type)) - } - } - } - return -} - -func (g *modelGenerator) newParam(name string, typ ast.Expr) *model.Parameter { - return &model.Parameter{ - Name: name, - Type: g.modelTypeFrom(g.info.TypeOf(typ)), - } -} - -func (g *modelGenerator) modelTypeFrom(typesType types.Type) model.Type { - switch typedTyp := typesType.(type) { - case *types.Basic: - if !predeclared(typedTyp.Kind()) { - panic(fmt.Sprintf("Unexpected Basic Type %v", typedTyp.Name())) - } - return model.PredeclaredType(typedTyp.Name()) - case *types.Pointer: - return &model.PointerType{ - Type: g.modelTypeFrom(typedTyp.Elem()), - } - case *types.Array: - return &model.ArrayType{ - Len: int(typedTyp.Len()), - Type: g.modelTypeFrom(typedTyp.Elem()), - } - case *types.Slice: - return &model.ArrayType{ - Len: -1, - Type: g.modelTypeFrom(typedTyp.Elem()), - } - case *types.Map: - return &model.MapType{ - Key: g.modelTypeFrom(typedTyp.Key()), - Value: g.modelTypeFrom(typedTyp.Elem()), - } - case *types.Chan: - var dir model.ChanDir - switch typedTyp.Dir() { - case types.SendOnly: - dir = model.SendDir - case types.RecvOnly: - dir = model.RecvDir - default: - dir = 0 - } - return &model.ChanType{ - Dir: dir, - Type: g.modelTypeFrom(typedTyp.Elem()), - } - case *types.Named: - if typedTyp.Obj().Pkg() == nil { - return model.PredeclaredType(typedTyp.Obj().Name()) - } - return &model.NamedType{ - Package: typedTyp.Obj().Pkg().Path(), - Type: typedTyp.Obj().Name(), - } - case *types.Interface, *types.Struct: - return model.PredeclaredType(typedTyp.String()) - case *types.Signature: - in, variadic := g.generateInParamsFrom(typedTyp.Params()) - out := g.generateOutParamsFrom(typedTyp.Results()) - return &model.FuncType{In: in, Out: out, Variadic: variadic} - default: - panic(fmt.Sprintf("Unknown types.Type: %v (%T)", typesType, typesType)) - } -} - -func (g *modelGenerator) generateInParamsFrom(params *types.Tuple) (in []*model.Parameter, variadic *model.Parameter) { - // TODO: variadic - - for i := 0; i < params.Len(); i++ { - in = append(in, &model.Parameter{ - Name: params.At(i).Name(), - Type: g.modelTypeFrom(params.At(i).Type()), - }) - } - return -} - -func (g *modelGenerator) generateOutParamsFrom(params *types.Tuple) (out []*model.Parameter) { - for i := 0; i < params.Len(); i++ { - out = append(out, &model.Parameter{ - Name: params.At(i).Name(), - Type: g.modelTypeFrom(params.At(i).Type()), - }) - } - return -} - -func predeclared(basicKind types.BasicKind) bool { - return basicKind >= types.Bool && basicKind <= types.String -} diff --git a/modelgen/xtools_loader/loader_suite_test.go b/modelgen/xtools_loader/loader_suite_test.go deleted file mode 100644 index 65520f7..0000000 --- a/modelgen/xtools_loader/loader_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package xtools_loader_test - -import ( - "testing" - - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" -) - -func TestLoader(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "xtools_loader_test Suite") -} diff --git a/modelgen/xtools_loader/loader_test.go b/modelgen/xtools_loader/loader_test.go deleted file mode 100644 index 31f57ee..0000000 --- a/modelgen/xtools_loader/loader_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package xtools_loader_test - -import ( - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" - - . "github.com/petergtz/pegomock/v3/modelgen/xtools_loader" -) - -var _ = XDescribe("Loader", func() { - Describe("GenerateModel", func() { - It("finds all methods within interface", func() { - pkg, e := GenerateModel("io", "Reader") - Expect(e).NotTo(HaveOccurred()) - Expect(pkg.Interfaces).To(HaveLen(1)) - Expect(pkg.Interfaces[0].Name).To(Equal("Reader")) - Expect(pkg.Interfaces[0].Methods).To(HaveLen(1)) - Expect(pkg.Interfaces[0].Methods[0].Name).To(Equal("Read")) - }) - - Context("using an interface with embedded interfaces", func() { - It("finds all methods", func() { - pkg, e := GenerateModel("io", "ReadCloser") - Expect(e).NotTo(HaveOccurred()) - Expect(pkg.Interfaces).To(HaveLen(1)) - Expect(pkg.Interfaces[0].Name).To(Equal("ReadCloser")) - Expect(pkg.Interfaces[0].Methods).To(HaveLen(2)) - Expect(pkg.Interfaces[0].Methods[0].Name).To(Equal("Read")) - Expect(pkg.Interfaces[0].Methods[1].Name).To(Equal("Close")) - - }) - }) - }) -}) diff --git a/modelgen/xtools_packages/packages.go b/modelgen/xtools_packages/packages.go index 06e3ec0..7f915c3 100644 --- a/modelgen/xtools_packages/packages.go +++ b/modelgen/xtools_packages/packages.go @@ -6,7 +6,7 @@ import ( "go/types" "path" - "github.com/petergtz/pegomock/v3/model" + "github.com/petergtz/pegomock/v4/model" "golang.org/x/tools/go/packages" ) diff --git a/modelgen/xtools_packages/packages_test.go b/modelgen/xtools_packages/packages_test.go index cfa5841..da4418e 100644 --- a/modelgen/xtools_packages/packages_test.go +++ b/modelgen/xtools_packages/packages_test.go @@ -3,9 +3,9 @@ package xtools_packages_test import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - "github.com/petergtz/pegomock/v3/model" + "github.com/petergtz/pegomock/v4/model" - . "github.com/petergtz/pegomock/v3/modelgen/xtools_packages" + . "github.com/petergtz/pegomock/v4/modelgen/xtools_packages" ) var _ = Describe("Packages", func() { @@ -40,7 +40,7 @@ var _ = Describe("Packages", func() { Expect(pkg.Interfaces[0].Methods).To(HaveLen(1)) Expect(pkg.Interfaces[0].Methods[0].Name).To(Equal("Read")) - pkg, e = GenerateModel("github.com/petergtz/pegomock/v3/modelgen/xtools_packages", "Bla") + pkg, e = GenerateModel("github.com/petergtz/pegomock/v4/modelgen/xtools_packages", "Bla") Expect(e).NotTo(HaveOccurred()) Expect(pkg.Interfaces).To(HaveLen(1)) Expect(pkg.Interfaces[0].Name).To(Equal("Bla")) @@ -52,7 +52,7 @@ var _ = Describe("Packages", func() { &model.Parameter{ Name: "V", Type: &model.NamedType{ - Package: "github.com/petergtz/pegomock/v3/modelgen/xtools_packages", + Package: "github.com/petergtz/pegomock/v4/modelgen/xtools_packages", Type: "Number", }, }, diff --git a/panic_with_message_matcher_test.go b/panic_with_message_matcher_test.go index 60badd8..e20a336 100644 --- a/panic_with_message_matcher_test.go +++ b/panic_with_message_matcher_test.go @@ -6,7 +6,7 @@ import ( "github.com/onsi/gomega/format" "github.com/onsi/gomega/types" - "github.com/petergtz/pegomock/v3/internal/verify" + "github.com/petergtz/pegomock/v4/internal/verify" ) type PanicWithMatcher struct { diff --git a/panic_with_message_to_matcher_test.go b/panic_with_message_to_matcher_test.go index fd1e583..c7f9bc2 100644 --- a/panic_with_message_to_matcher_test.go +++ b/panic_with_message_to_matcher_test.go @@ -6,7 +6,7 @@ import ( "github.com/onsi/gomega/format" "github.com/onsi/gomega/types" - "github.com/petergtz/pegomock/v3/internal/verify" + "github.com/petergtz/pegomock/v4/internal/verify" ) type PanicWithMessageToMatcher struct { diff --git a/pegomock/filehandling/filehandling.go b/pegomock/filehandling/filehandling.go index 5dc92c3..55e74d6 100644 --- a/pegomock/filehandling/filehandling.go +++ b/pegomock/filehandling/filehandling.go @@ -3,17 +3,13 @@ package filehandling import ( "fmt" "io" - "io/ioutil" "log" "os" "path/filepath" "strings" - "github.com/petergtz/pegomock/v3/mockgen" - "github.com/petergtz/pegomock/v3/model" - "github.com/petergtz/pegomock/v3/modelgen/gomock" - "github.com/petergtz/pegomock/v3/modelgen/xtools_packages" - "github.com/petergtz/pegomock/v3/pegomock/util" + "github.com/petergtz/pegomock/v4/mockgen" + "github.com/petergtz/pegomock/v4/modelgen/xtools_packages" ) func GenerateMockFileInOutputDir( @@ -24,16 +20,13 @@ func GenerateMockFileInOutputDir( packageOut string, selfPackage string, debugParser bool, - out io.Writer, - useExperimentalModelGen bool, - shouldGenerateMatchers bool, - matchersDestination string) { + out io.Writer) { // if a file path override is specified // ensure all directories in the path are created if outputFilePathOverride != "" { if err := os.MkdirAll(filepath.Dir(outputFilePathOverride), 0755); err != nil { - panic(fmt.Errorf("Failed to make output directory, error: %v", err)) + panic(fmt.Errorf("failed to make output directory, error: %v", err)) } } @@ -44,74 +37,38 @@ func GenerateMockFileInOutputDir( packageOut, selfPackage, debugParser, - out, - useExperimentalModelGen, - shouldGenerateMatchers, - matchersDestination) + out) } func OutputFilePath(args []string, outputDirPath string, outputFilePathOverride string) string { if outputFilePathOverride != "" { return outputFilePathOverride - } else if util.SourceMode(args) { - return filepath.Join(outputDirPath, "mock_"+strings.TrimSuffix(args[0], ".go")+"_test.go") } else { return filepath.Join(outputDirPath, "mock_"+strings.ToLower(args[len(args)-1])+"_test.go") } } -func GenerateMockFile(args []string, outputFilePath string, nameOut string, packageOut string, selfPackage string, debugParser bool, out io.Writer, useExperimentalModelGen bool, shouldGenerateMatchers bool, matchersDestination string) { - mockSourceCode, matcherSourceCodes := GenerateMockSourceCode(args, nameOut, packageOut, selfPackage, debugParser, out, useExperimentalModelGen) +func GenerateMockFile(args []string, outputFilePath string, nameOut string, packageOut string, selfPackage string, debugParser bool, out io.Writer) { + mockSourceCode := GenerateMockSourceCode(args, nameOut, packageOut, selfPackage, debugParser, out) - err := ioutil.WriteFile(outputFilePath, mockSourceCode, 0664) + err := os.WriteFile(outputFilePath, mockSourceCode, 0664) if err != nil { - panic(fmt.Errorf("Failed writing to destination: %v", err)) - } - - if shouldGenerateMatchers { - matchersPath := filepath.Join(filepath.Dir(outputFilePath), "matchers") - if matchersDestination != "" { - matchersPath = matchersDestination - } - err = os.MkdirAll(matchersPath, 0755) - if err != nil { - panic(fmt.Errorf("Failed making dirs \"%v\": %v", matchersPath, err)) - } - for matcherTypeName, matcherSourceCode := range matcherSourceCodes { - err := ioutil.WriteFile(filepath.Join(matchersPath, matcherTypeName+".go"), []byte(matcherSourceCode), 0664) - if err != nil { - panic(fmt.Errorf("Failed writing to destination: %v", err)) - } - } + panic(fmt.Errorf("failed writing to destination: %v", err)) } } -func GenerateMockSourceCode(args []string, nameOut string, packageOut string, selfPackage string, debugParser bool, out io.Writer, useExperimentalModelGen bool) ([]byte, map[string]string) { - var err error - - var ast *model.Package - var src string - if util.SourceMode(args) { - ast, err = gomock.ParseFile(args[0]) - src = args[0] - } else { - if len(args) != 2 { - log.Fatal("Expected exactly two arguments, but got " + fmt.Sprint(args)) - } - if useExperimentalModelGen { - ast, err = xtools_packages.GenerateModel(args[0], args[1]) - } else { - ast, err = gomock.Reflect(args[0], strings.Split(args[1], ",")) - } - src = fmt.Sprintf("%v (interfaces: %v)", args[0], args[1]) +func GenerateMockSourceCode(args []string, nameOut string, packageOut string, selfPackage string, debugParser bool, out io.Writer) []byte { + if len(args) != 2 { + log.Fatal("Expected exactly two arguments, but got " + fmt.Sprint(args)) } + ast, err := xtools_packages.GenerateModel(args[0], args[1]) + src := fmt.Sprintf("%v (interfaces: %v)", args[0], args[1]) if err != nil { - panic(fmt.Errorf("Loading input failed: %v", err)) + panic(fmt.Errorf("loading input failed: %v", err)) } if debugParser { ast.Print(out) } - return mockgen.GenerateOutput(ast, src, nameOut, packageOut, selfPackage) } diff --git a/pegomock/main.go b/pegomock/main.go index 76dc8c6..42def5f 100644 --- a/pegomock/main.go +++ b/pegomock/main.go @@ -22,12 +22,12 @@ import ( "strings" "time" - kingpin "github.com/alecthomas/kingpin/v2" + "github.com/alecthomas/kingpin/v2" - "github.com/petergtz/pegomock/v3/pegomock/filehandling" - "github.com/petergtz/pegomock/v3/pegomock/remove" - "github.com/petergtz/pegomock/v3/pegomock/util" - "github.com/petergtz/pegomock/v3/pegomock/watch" + "github.com/petergtz/pegomock/v4/pegomock/filehandling" + "github.com/petergtz/pegomock/v4/pegomock/remove" + "github.com/petergtz/pegomock/v4/pegomock/util" + "github.com/petergtz/pegomock/v4/pegomock/watch" ) var ( @@ -52,17 +52,8 @@ func Run(cliArgs []string, out io.Writer, in io.Reader, app *kingpin.Application // TODO: self_package was taken as is from GoMock. // Still don't understand what it's really there for. // So for now it's not tested. - selfPackage = generateCmd.Flag("self_package", "If set, the package this mock will be part of.").String() - debugParser = generateCmd.Flag("debug", "Print debug information.").Short('d').Bool() - shouldGenerateMatchers = generateCmd.Flag("generate-matchers", "Generate matchers for all non built-in types in a \"matchers\" "+ - "directory in the same directory where the mock file gets generated.").Short('m').Default("false").Bool() - matchersDestination = generateCmd.Flag("matchers-dir", "Generate matchers in the specified directory; defaults to "+ - filepath.Join("", "matchers")).Short('p').String() - useExperimentalModelGen = generateCmd.Flag("use-experimental-model-gen", "pegomock includes a new experimental source parser based on "+ - "golang.org/x/tools/go/loader. It's currently experimental, but should be more powerful "+ - "than the current reflect-based modelgen. E.g. reflect cannot detect method parameter names,"+ - " and has to generate them based on a pattern. In a code editor with code assistence, this doesn't provide good help. "+ - "\n\nThis option only works when specifying package path + interface, not with .go source files. Also, you can only specify *one* interface. This option cannot be used with the watch command.").Bool() + selfPackage = generateCmd.Flag("self_package", "If set, the package this mock will be part of.").String() + debugParser = generateCmd.Flag("debug", "Print debug information.").Short('d').Bool() generateCmdArgs = generateCmd.Arg("args", "A (optional) Go package path + space-separated interface or a .go file").Required().Strings() watchCmd = app.Command("watch", "Watch over changes in interfaces and regenerate mocks if changes are detected.") @@ -107,11 +98,7 @@ func Run(cliArgs []string, out io.Writer, in io.Reader, app *kingpin.Application if *packageOut == "" { realPackageOut = filepath.Base(*destinationDir) } - if util.SourceMode(sourceArgs) { - realDestination = filepath.Join(*destinationDir, "mock_"+strings.TrimSuffix(sourceArgs[0], ".go")+".go") - } else { - realDestination = filepath.Join(*destinationDir, "mock_"+strings.ToLower(sourceArgs[len(sourceArgs)-1])+".go") - } + realDestination = filepath.Join(*destinationDir, "mock_"+strings.ToLower(sourceArgs[len(sourceArgs)-1])+".go") } filehandling.GenerateMockFileInOutputDir( @@ -122,10 +109,7 @@ func Run(cliArgs []string, out io.Writer, in io.Reader, app *kingpin.Application realPackageOut, *selfPackage, *debugParser, - out, - *useExperimentalModelGen, - *shouldGenerateMatchers, - *matchersDestination) + out) case watchCmd.FullCommand(): var targetPaths []string diff --git a/pegomock/main_test.go b/pegomock/main_test.go index 0bb9f64..d2a7000 100644 --- a/pegomock/main_test.go +++ b/pegomock/main_test.go @@ -17,19 +17,18 @@ package main_test import ( "bytes" "context" - "go/build" "os" "path/filepath" "strings" "time" - kingpin "github.com/alecthomas/kingpin/v2" + "github.com/alecthomas/kingpin/v2" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - main "github.com/petergtz/pegomock/v3/pegomock" + main "github.com/petergtz/pegomock/v4/pegomock" - . "github.com/petergtz/pegomock/v3/pegomock/testutil" + . "github.com/petergtz/pegomock/v4/pegomock/testutil" "testing" ) @@ -43,424 +42,307 @@ func TestPegomock(t *testing.T) { RunSpecs(t, "CLI Suite") } -var ( - // _ = describeCLIWithGoModulesEnabled(false) - _ = describeCLIWithGoModulesEnabled(true) -) - -func describeCLIWithGoModulesEnabled(useGoModules bool) interface{} { - mode := "with GOPATH" - if useGoModules { - mode = "with Go modules" - } - - Describe("CLI "+mode, func() { - - var ( - packageDir, subPackageDir, vendorPackageDir string - app *kingpin.Application - origWorkingDir string - ) - - BeforeEach(func() { - if !useGoModules { - packageDir = joinPath(build.Default.GOPATH, "src", "pegomocktest") - } else { - tmpDir, e := filepath.EvalSymlinks(os.TempDir()) - Expect(e).NotTo(HaveOccurred()) - packageDir = filepath.Join(tmpDir, "pegomocktest") - } - Expect(os.MkdirAll(packageDir, 0755)).To(Succeed()) - subPackageDir = joinPath(packageDir, "subpackage") - Expect(os.MkdirAll(subPackageDir, 0755)).To(Succeed()) - vendorPackageDir = joinPath(packageDir, "vendor", "github.com", "petergtz", "vendored_package") - Expect(os.MkdirAll(vendorPackageDir, 0755)).To(Succeed()) - - var e error - origWorkingDir, e = os.Getwd() - Expect(e).NotTo(HaveOccurred()) - os.Chdir(packageDir) - - if useGoModules { - WriteFile(joinPath(packageDir, "go.mod"), - `module pegomocktest +var _ = Describe("CLI", func() { + + var ( + packageDir, subPackageDir string + app *kingpin.Application + origWorkingDir string + ) + + BeforeEach(func() { + tmpDir, e := filepath.EvalSymlinks(os.TempDir()) + Expect(e).NotTo(HaveOccurred()) + packageDir = filepath.Join(tmpDir, "pegomocktest") + Expect(os.MkdirAll(packageDir, 0755)).To(Succeed()) + subPackageDir = joinPath(packageDir, "subpackage") + Expect(os.MkdirAll(subPackageDir, 0755)).To(Succeed()) + //vendorPackageDir = joinPath(packageDir, "vendor", "github.com", "petergtz", "vendored_package") + //Expect(os.MkdirAll(vendorPackageDir, 0755)).To(Succeed()) + + origWorkingDir, e = os.Getwd() + Expect(e).NotTo(HaveOccurred()) + e = os.Chdir(packageDir) + Expect(e).NotTo(HaveOccurred()) + + WriteFile(joinPath(packageDir, "go.mod"), + `module pegomocktest go 1.18 require ( github.com/onsi/gomega v1.27.6 // indirect - github.com/petergtz/pegomock/v3 v3.0.0 + github.com/petergtz/pegomock/v4 v4.0.0 )`) - } - - WriteFile(joinPath(packageDir, "mydisplay.go"), - "package pegomocktest; type MyDisplay interface { Show(something string) }") - WriteFile(joinPath(packageDir, "http_request_handler.go"), - `package pegomocktest; import "net/http"; type RequestHandler interface { Handler(r *http.Request) }`) - WriteFile(joinPath(subPackageDir, "subdisplay.go"), - "package subpackage; type SubDisplay interface { ShowMe() }") - if !useGoModules { - WriteFile(joinPath(vendorPackageDir, "iface.go"), - `package vendored_package; type Interface interface{ Foobar() }`) - WriteFile(joinPath(packageDir, "vendordisplay.go"), `package pegomocktest - import ( "github.com/petergtz/vendored_package" ) - type VendorDisplay interface { Show(something vendored_package.Interface) }`) - } - - app = kingpin.New("pegomock", "Generates mocks based on interfaces.") - app.Terminate(func(int) { panic("Unexpected terminate") }) - }) - AfterEach(func() { - Expect(os.RemoveAll(packageDir)).To(Succeed()) - os.Chdir(origWorkingDir) - }) + WriteFile(joinPath(packageDir, "mydisplay.go"), + "package pegomocktest; type MyDisplay interface { Show(something string) }") + WriteFile(joinPath(packageDir, "http_request_handler.go"), + `package pegomocktest; import "net/http"; type RequestHandler interface { Handler(r *http.Request) }`) + WriteFile(joinPath(subPackageDir, "subdisplay.go"), + "package subpackage; type SubDisplay interface { ShowMe() }") - Describe(`"generate" command`, func() { + app = kingpin.New("pegomock", "Generates mocks based on interfaces.") + app.Terminate(func(int) { panic("Unexpected terminate") }) + }) - Context(`with args "MyDisplay"`, func() { + AfterEach(func() { + Expect(os.RemoveAll(packageDir)).To(Succeed()) + _ = os.Chdir(origWorkingDir) + }) - It(`generates a file mock_mydisplay_test.go that contains "package pegomocktest_test"`, func() { - // The rationale behind this is: - // mocks should always be part of test packages, because we don't - // want them to be part of the production code. - // But to be useful, they must still reside in the package, where - // they are actually used. + Describe(`"generate" command`, func() { - main.Run(cmd("pegomock generate MyDisplay"), os.Stdout, os.Stdin, app, context.Background()) + Context(`with args "MyDisplay"`, func() { - Expect(joinPath(packageDir, "mock_mydisplay_test.go")).To(SatisfyAll( - BeAnExistingFile(), - BeAFileContainingSubString("package pegomocktest_test"))) - }) + It(`generates a file mock_mydisplay_test.go that contains "package pegomocktest_test"`, func() { + // The rationale behind this is: + // mocks should always be part of test packages, because we don't + // want them to be part of the production code. + // But to be useful, they must still reside in the package, where + // they are actually used. - It(`sets the default mock name "DisplayMock"`, func() { - main.Run(cmd("pegomock generate MyDisplay"), os.Stdout, os.Stdin, app, context.Background()) + main.Run(cmd("pegomock generate MyDisplay"), os.Stdout, os.Stdin, app, context.Background()) - Expect(joinPath(packageDir, "mock_mydisplay_test.go")).To(SatisfyAll( - BeAnExistingFile(), - BeAFileContainingSubString("MockMyDisplay"))) - }) + Expect(joinPath(packageDir, "mock_mydisplay_test.go")).To(SatisfyAll( + BeAnExistingFile(), + BeAFileContainingSubString("package pegomocktest_test"))) }) - Context(`with args "VendorDisplay""`, func() { + It(`sets the default mock name "DisplayMock"`, func() { + main.Run(cmd("pegomock generate MyDisplay"), os.Stdout, os.Stdin, app, context.Background()) - It(`generates a file mock_vendordisplay_test.go that contains 'import ( vendored_package "github.com/petergtz/vendored_package" )'`, func() { - if useGoModules { - Skip("Vendoring not supported with Go modules yet") - } - - main.Run(cmd("pegomock generate -m VendorDisplay"), os.Stdout, os.Stdin, app, context.Background()) - Expect(joinPath(packageDir, "mock_vendordisplay_test.go")).To(SatisfyAll( - BeAnExistingFile(), - BeAFileContainingSubString(`vendored_package "github.com/petergtz/vendored_package"`))) - Expect(joinPath(packageDir, "matchers", "vendored_package_interface.go")).To(SatisfyAll( - BeAnExistingFile(), - BeAFileContainingSubString(`vendored_package "github.com/petergtz/vendored_package"`))) - }) + Expect(joinPath(packageDir, "mock_mydisplay_test.go")).To(SatisfyAll( + BeAnExistingFile(), + BeAFileContainingSubString("MockMyDisplay"))) }) + }) - Context(`with args "pegomocktest/subpackage SubDisplay"`, func() { - It(`generates a file mock_subdisplay_test.go in "pegomocktest" that contains "package pegomocktest_test"`, func() { - main.Run(cmd("pegomock generate pegomocktest/subpackage SubDisplay"), os.Stdout, os.Stdin, app, context.Background()) + Context(`with args "pegomocktest/subpackage SubDisplay"`, func() { + It(`generates a file mock_subdisplay_test.go in "pegomocktest" that contains "package pegomocktest_test"`, func() { + main.Run(cmd("pegomock generate pegomocktest/subpackage SubDisplay"), os.Stdout, os.Stdin, app, context.Background()) - Expect(joinPath(packageDir, "mock_subdisplay_test.go")).To(SatisfyAll( - BeAnExistingFile(), - BeAFileContainingSubString("package pegomocktest_test"))) - }) + Expect(joinPath(packageDir, "mock_subdisplay_test.go")).To(SatisfyAll( + BeAnExistingFile(), + BeAFileContainingSubString("package pegomocktest_test"))) }) + }) - Context("with args mydisplay.go", func() { - It(`generates a file mock_mydisplay_test.go that contains "package pegomocktest_test"`, func() { - main.Run(cmd("pegomock generate mydisplay.go"), os.Stdout, os.Stdin, app, context.Background()) - - Expect(joinPath(packageDir, "mock_mydisplay_test.go")).To(SatisfyAll( - BeAnExistingFile(), - BeAFileContainingSubString("package pegomocktest_test"), - BeAFileContainingSubString("MockMyDisplay"), - )) - }) + Context("with args -o where output override is a path with a non-existing directory", func() { + It(`creates an output directory before code generation`, func() { + var buf bytes.Buffer + main.Run(cmd("pegomock generate MyDisplay -o testoutput/test.go"), &buf, os.Stdin, app, context.Background()) + Expect(joinPath(packageDir, "testoutput/test.go")).To(SatisfyAll( + BeAnExistingFile(), + BeAFileContainingSubString("package pegomocktest_test"))) }) + }) - Context("with args -d mydisplay.go", func() { - It(`prints out debug information on stdout`, func() { - var buf bytes.Buffer - main.Run(cmd("pegomock generate -d mydisplay.go"), &buf, os.Stdin, app, context.Background()) - Expect(buf.String()).To(ContainSubstring("- method Show")) - }) + Context("with args --output-dir", func() { + It(`creates the mocks in output dir with the dir's basename as package name`, func() { + var buf bytes.Buffer + main.Run(cmd("pegomock generate MyDisplay --output-dir fakes"), &buf, os.Stdin, app, context.Background()) + Expect(joinPath(packageDir, "fakes/mock_mydisplay.go")).To(SatisfyAll( + BeAnExistingFile(), + BeAFileContainingSubString("package fakes"))) }) + }) - Context("with args -o where output override is a path with a non-existing directory", func() { - It(`creates an output directory before code generation`, func() { - var buf bytes.Buffer - main.Run(cmd("pegomock generate mydisplay.go -o testoutput/test.go"), &buf, os.Stdin, app, context.Background()) - Expect(joinPath(packageDir, "testoutput/test.go")).To(SatisfyAll( - BeAnExistingFile(), - BeAFileContainingSubString("package pegomocktest_test"))) - }) - }) + Context("with args --output-dir and --package", func() { + It(`creates the mocks in output dir with the specified package name`, func() { + var buf bytes.Buffer + main.Run(cmd("pegomock generate MyDisplay --output-dir fakes --package other"), &buf, os.Stdin, app, context.Background()) - Context("with args --output-dir", func() { - It(`creates the mocks in output dir with the dir's basename as package name`, func() { - var buf bytes.Buffer - main.Run(cmd("pegomock generate MyDisplay --output-dir fakes"), &buf, os.Stdin, app, context.Background()) - Expect(joinPath(packageDir, "fakes/mock_mydisplay.go")).To(SatisfyAll( - BeAnExistingFile(), - BeAFileContainingSubString("package fakes"))) - }) + Expect(joinPath(packageDir, "fakes/mock_mydisplay.go")).To(SatisfyAll( + BeAnExistingFile(), + BeAFileContainingSubString("package other"))) }) + }) - Context("with args --output-dir and --package", func() { - It(`creates the mocks in output dir with the specified package name`, func() { - var buf bytes.Buffer - main.Run(cmd("pegomock generate MyDisplay --output-dir fakes --package other"), &buf, os.Stdin, app, context.Background()) + Context("with args --mock-name", func() { + It(`sets the mock name as given`, func() { + main.Run(cmd("pegomock generate MyDisplay --mock-name RenamedMock"), os.Stdout, os.Stdin, app, context.Background()) - Expect(joinPath(packageDir, "fakes/mock_mydisplay.go")).To(SatisfyAll( - BeAnExistingFile(), - BeAFileContainingSubString("package other"))) - }) + Expect(joinPath(packageDir, "mock_mydisplay_test.go")).To(SatisfyAll( + BeAnExistingFile(), + BeAFileContainingSubString("RenamedMock"))) }) + }) - Context("with args --mock-name", func() { - It(`sets the mock name as given`, func() { - main.Run(cmd("pegomock generate MyDisplay --mock-name RenamedMock"), os.Stdout, os.Stdin, app, context.Background()) + Context("with too many args", func() { - Expect(joinPath(packageDir, "mock_mydisplay_test.go")).To(SatisfyAll( - BeAnExistingFile(), - BeAFileContainingSubString("RenamedMock"))) - }) + It(`reports an error and the usage`, func() { + var buf bytes.Buffer + Expect(func() { + main.Run(cmd("pegomock generate with too many args"), &buf, os.Stdin, app, context.Background()) + }).To(Panic()) + + Expect(buf.String()).To(ContainSubstring("Please provide exactly 1 interface or 1 package + 1 interface")) + Expect(buf.String()).To(ContainSubstring("usage")) }) + }) - Context("with args for specifying matcher directory", func() { - It(`creates matchers in the specified directory`, func() { - if useGoModules { - Skip("Vendoring not supported with Go modules yet") - } - var buf bytes.Buffer - main.Run(cmd("pegomock generate --generate-matchers --matchers-dir custom/matcher/dir VendorDisplay"), &buf, os.Stdin, app, context.Background()) + }) - Expect(joinPath(packageDir, "custom/matcher/dir")).To(BeADirectory()) - Expect(joinPath(packageDir, "custom/matcher/dir/vendored_package_interface.go")).To(BeAnExistingFile()) - }) - }) + Describe(`"watch" command`, func() { - Context("with too many args", func() { + Context("with no further action", func() { + It(`Creates a template file interfaces_to_mock in the current directory`, func(ctx SpecContext) { + go main.Run(cmd("pegomock watch"), os.Stdout, os.Stdin, app, ctx) + Eventually(func() string { return "interfaces_to_mock" }, "3s").Should(BeAnExistingFile()) + }, NodeTimeout(4*time.Second)) + }) - It(`reports an error and the usage`, func() { - var buf bytes.Buffer - Expect(func() { - main.Run(cmd("pegomock generate with too many args"), &buf, os.Stdin, app, context.Background()) - }).To(Panic()) + Context("after populating interfaces_to_mock with an actual interface", func() { + It(`Eventually creates a file mock_mydisplay_test.go starting with "package pegomocktest_test"`, func(ctx SpecContext) { + WriteFile(joinPath(packageDir, "interfaces_to_mock"), "MyDisplay") - Expect(buf.String()).To(ContainSubstring("Please provide exactly 1 interface or 1 package + 1 interface")) - Expect(buf.String()).To(ContainSubstring("usage")) - }) - }) + go main.Run(cmd("pegomock watch"), os.Stdout, os.Stdin, app, ctx) + Eventually(joinPath(packageDir, "mock_mydisplay_test.go"), "3s").Should(SatisfyAll( + BeAnExistingFile(), + BeAFileContainingSubString("package pegomocktest_test"))) + }, NodeTimeout(4*time.Second)) }) - Describe(`"watch" command`, func() { - - Context("with no further action", func() { - It(`Creates a template file interfaces_to_mock in the current directory`, func(ctx SpecContext) { - go main.Run(cmd("pegomock watch"), os.Stdout, os.Stdin, app, ctx) - Eventually(func() string { return "interfaces_to_mock" }, "3s").Should(BeAnExistingFile()) - }, NodeTimeout(4*time.Second)) - }) + }) - Context("after populating interfaces_to_mock with an actual interface", func() { - It(`Eventually creates a file mock_mydisplay_test.go starting with "package pegomocktest_test"`, func(ctx SpecContext) { - WriteFile(joinPath(packageDir, "interfaces_to_mock"), "MyDisplay") + Describe(`"remove" command`, func() { + Context("there are no mock files", func() { + It("removes mock files in current directory only", func() { + var buf bytes.Buffer - go main.Run(cmd("pegomock watch"), os.Stdout, os.Stdin, app, ctx) + main.Run(cmd("pegomock remove -n"), &buf, os.Stdin, app, context.Background()) - Eventually(joinPath(packageDir, "mock_mydisplay_test.go"), "3s").Should(SatisfyAll( - BeAnExistingFile(), - BeAFileContainingSubString("package pegomocktest_test"))) - }, NodeTimeout(4*time.Second)) + Expect(buf.String()).To(ContainSubstring(`No files to remove.`)) }) - }) - Describe(`"remove" command`, func() { - Context("there are no mock files", func() { - It("removes mock files in current directory only", func() { - var buf bytes.Buffer + Context("there are some mock files", func() { + BeforeEach(func() { + main.Run(cmd("pegomock generate MyDisplay"), os.Stdout, os.Stdin, app, context.Background()) + Expect(joinPath(packageDir, "mock_mydisplay_test.go")).To(SatisfyAll( + BeAnExistingFile(), + BeAFileContainingSubString("package pegomocktest_test"))) - main.Run(cmd("pegomock remove -n"), &buf, os.Stdin, app, context.Background()) + main.Run(cmd("pegomock generate --output-dir "+subPackageDir+" pegomocktest/subpackage SubDisplay"), os.Stdout, os.Stdin, app, context.Background()) - Expect(buf.String()).To(ContainSubstring(`No files to remove.`)) - }) + Expect(joinPath(subPackageDir, "mock_subdisplay.go")).To(SatisfyAll( + BeAnExistingFile(), + BeAFileContainingSubString("package subpackage"))) }) - Context("there are some mock files", func() { - BeforeEach(func() { - main.Run(cmd("pegomock generate MyDisplay"), os.Stdout, os.Stdin, app, context.Background()) - Expect(joinPath(packageDir, "mock_mydisplay_test.go")).To(SatisfyAll( - BeAnExistingFile(), - BeAFileContainingSubString("package pegomocktest_test"))) - - main.Run(cmd("pegomock generate --output-dir "+subPackageDir+" pegomocktest/subpackage SubDisplay"), os.Stdout, os.Stdin, app, context.Background()) - - Expect(joinPath(subPackageDir, "mock_subdisplay.go")).To(SatisfyAll( - BeAnExistingFile(), - BeAFileContainingSubString("package subpackage"))) - }) - - Context("Non-interactive", func() { - Context("non-recursive", func() { - It("removes mock files in current directory only", func() { - var buf bytes.Buffer + Context("Non-interactive", func() { + Context("non-recursive", func() { + It("removes mock files in current directory only", func() { + var buf bytes.Buffer - main.Run(cmd("pegomock remove -n"), &buf, os.Stdin, app, context.Background()) + main.Run(cmd("pegomock remove -n"), &buf, os.Stdin, app, context.Background()) - Expect(buf.String()).To(ContainSubstring(`Deleting the following files: + Expect(buf.String()).To(ContainSubstring(`Deleting the following files: ` + packageDir + `/mock_mydisplay_test.go`)) - Expect(joinPath(packageDir, "mock_mydisplay_test.go")).NotTo(BeAnExistingFile()) - Expect(joinPath(subPackageDir, "mock_subdisplay.go")).To(BeAnExistingFile()) - }) + Expect(joinPath(packageDir, "mock_mydisplay_test.go")).NotTo(BeAnExistingFile()) + Expect(joinPath(subPackageDir, "mock_subdisplay.go")).To(BeAnExistingFile()) }) + }) - Context("recursive", func() { - It("removes mock files recursively", func() { - var buf bytes.Buffer + Context("recursive", func() { + It("removes mock files recursively", func() { + var buf bytes.Buffer - main.Run(cmd("pegomock remove -n -r"), &buf, os.Stdin, app, context.Background()) + main.Run(cmd("pegomock remove -n -r"), &buf, os.Stdin, app, context.Background()) - Expect(buf.String()).To(ContainSubstring(`Deleting the following files: + Expect(buf.String()).To(ContainSubstring(`Deleting the following files: ` + packageDir + `/mock_mydisplay_test.go ` + packageDir + `/subpackage/mock_subdisplay.go`)) - Expect(joinPath(packageDir, "mock_mydisplay_test.go")).NotTo(BeAnExistingFile()) - Expect(joinPath(subPackageDir, "mock_subdisplay.go")).NotTo(BeAnExistingFile()) - }) - - Context("custom matchers were generated", func() { - BeforeEach(func() { - main.Run(cmd("pegomock generate -m RequestHandler"), os.Stdout, os.Stdin, app, context.Background()) - Expect(joinPath(packageDir, "mock_requesthandler_test.go")).To(SatisfyAll( - BeAnExistingFile(), - BeAFileContainingSubString("package pegomocktest_test"))) - - Expect(joinPath(packageDir, "matchers", "ptr_to_http_request.go")).To(SatisfyAll( - BeAnExistingFile(), - BeAFileContainingSubString("package matchers"), - )) - main.Run(cmd("pegomock generate -m --output-dir "+subPackageDir+" RequestHandler"), os.Stdout, os.Stdin, app, context.Background()) - - Expect(joinPath(subPackageDir, "mock_requesthandler.go")).To(SatisfyAll( - BeAnExistingFile(), - BeAFileContainingSubString("package subpackage"))) - Expect(joinPath(subPackageDir, "matchers", "ptr_to_http_request.go")).To(SatisfyAll( - BeAnExistingFile(), - BeAFileContainingSubString("package matchers"), - )) - - }) - - It("removes matchers and matchers dir too", func() { - var buf bytes.Buffer - - main.Run(cmd("pegomock remove -n -r"), &buf, os.Stdin, app, context.Background()) - - Expect(buf.String()).To(Equal(`Deleting the following files: -`+packageDir+`/matchers -`+packageDir+`/matchers/ptr_to_http_request.go -`+packageDir+`/mock_mydisplay_test.go -`+packageDir+`/mock_requesthandler_test.go -`+packageDir+`/subpackage/matchers -`+packageDir+`/subpackage/matchers/ptr_to_http_request.go -`+packageDir+`/subpackage/mock_requesthandler.go -`+packageDir+`/subpackage/mock_subdisplay.go -`), buf.String()) - Expect(joinPath(packageDir, "mock_mydisplay_test.go")).NotTo(BeAnExistingFile()) - Expect(joinPath(subPackageDir, "mock_subdisplay.go")).NotTo(BeAnExistingFile()) - }) - }) + Expect(joinPath(packageDir, "mock_mydisplay_test.go")).NotTo(BeAnExistingFile()) + Expect(joinPath(subPackageDir, "mock_subdisplay.go")).NotTo(BeAnExistingFile()) }) - Context("Silent", func() { - It("removes mock files, but provides no output", func() { - var buf bytes.Buffer + }) - main.Run(cmd("pegomock remove -n --silent"), &buf, os.Stdin, app, context.Background()) + Context("Silent", func() { + It("removes mock files, but provides no output", func() { + var buf bytes.Buffer + + main.Run(cmd("pegomock remove -n --silent"), &buf, os.Stdin, app, context.Background()) - Expect(buf.String()).To(BeEmpty()) - Expect(joinPath(packageDir, "mock_mydisplay_test.go")).NotTo(BeAnExistingFile()) - Expect(joinPath(subPackageDir, "mock_subdisplay.go")).To(BeAnExistingFile()) - }) + Expect(buf.String()).To(BeEmpty()) + Expect(joinPath(packageDir, "mock_mydisplay_test.go")).NotTo(BeAnExistingFile()) + Expect(joinPath(subPackageDir, "mock_subdisplay.go")).To(BeAnExistingFile()) }) + }) - Context("with path", func() { - It("removes mock files in path", func() { - var buf bytes.Buffer + Context("with path", func() { + It("removes mock files in path", func() { + var buf bytes.Buffer - main.Run(cmd("pegomock remove -n "+subPackageDir), &buf, os.Stdin, app, context.Background()) + main.Run(cmd("pegomock remove -n "+subPackageDir), &buf, os.Stdin, app, context.Background()) - Expect(buf.String()).To(ContainSubstring(`Deleting the following files: + Expect(buf.String()).To(ContainSubstring(`Deleting the following files: ` + packageDir + `/subpackage/mock_subdisplay.go`)) - Expect(joinPath(packageDir, "mock_mydisplay_test.go")).To(BeAnExistingFile()) - Expect(joinPath(subPackageDir, "mock_subdisplay.go")).NotTo(BeAnExistingFile()) - }) + Expect(joinPath(packageDir, "mock_mydisplay_test.go")).To(BeAnExistingFile()) + Expect(joinPath(subPackageDir, "mock_subdisplay.go")).NotTo(BeAnExistingFile()) }) }) + }) - Context("Interactive", func() { - Context("confirming with yes", func() { - It("removes mock files", func() { - var buf bytes.Buffer + Context("Interactive", func() { + Context("confirming with yes", func() { + It("removes mock files", func() { + var buf bytes.Buffer - main.Run(cmd("pegomock remove"), &buf, strings.NewReader("yes\n"), app, context.Background()) + main.Run(cmd("pegomock remove"), &buf, strings.NewReader("yes\n"), app, context.Background()) - Expect(buf.String()).To(ContainSubstring(`Will delete the following files: + Expect(buf.String()).To(ContainSubstring(`Will delete the following files: ` + packageDir + `/mock_mydisplay_test.go Continue? [y/n]:`)) - Expect(joinPath(packageDir, "mock_mydisplay_test.go")).NotTo(BeAnExistingFile()) - Expect(joinPath(subPackageDir, "mock_subdisplay.go")).To(BeAnExistingFile()) - }) + Expect(joinPath(packageDir, "mock_mydisplay_test.go")).NotTo(BeAnExistingFile()) + Expect(joinPath(subPackageDir, "mock_subdisplay.go")).To(BeAnExistingFile()) }) + }) - Context("confirming with no", func() { - It("does not remove mock files", func() { - var buf bytes.Buffer + Context("confirming with no", func() { + It("does not remove mock files", func() { + var buf bytes.Buffer - main.Run(cmd("pegomock remove"), &buf, strings.NewReader("no\n"), app, context.Background()) + main.Run(cmd("pegomock remove"), &buf, strings.NewReader("no\n"), app, context.Background()) - Expect(buf.String()).To(ContainSubstring(`Will delete the following files: + Expect(buf.String()).To(ContainSubstring(`Will delete the following files: ` + packageDir + `/mock_mydisplay_test.go Continue? [y/n]:`)) - Expect(joinPath(packageDir, "mock_mydisplay_test.go")).To(BeAnExistingFile()) - Expect(joinPath(subPackageDir, "mock_subdisplay.go")).To(BeAnExistingFile()) - }) + Expect(joinPath(packageDir, "mock_mydisplay_test.go")).To(BeAnExistingFile()) + Expect(joinPath(subPackageDir, "mock_subdisplay.go")).To(BeAnExistingFile()) }) }) + }) - Context("dry-run", func() { - It("removes no mock files, but provides files that would be deleted", func() { - var buf bytes.Buffer + Context("dry-run", func() { + It("removes no mock files, but provides files that would be deleted", func() { + var buf bytes.Buffer - main.Run(cmd("pegomock remove --dry-run"), &buf, os.Stdin, app, context.Background()) + main.Run(cmd("pegomock remove --dry-run"), &buf, os.Stdin, app, context.Background()) - Expect(buf.String()).To(ContainSubstring(`Would delete the following files: + Expect(buf.String()).To(ContainSubstring(`Would delete the following files: ` + packageDir + `/mock_mydisplay_test.go`)) - Expect(joinPath(packageDir, "mock_mydisplay_test.go")).To(BeAnExistingFile()) - Expect(joinPath(subPackageDir, "mock_subdisplay.go")).To(BeAnExistingFile()) - }) + Expect(joinPath(packageDir, "mock_mydisplay_test.go")).To(BeAnExistingFile()) + Expect(joinPath(subPackageDir, "mock_subdisplay.go")).To(BeAnExistingFile()) }) }) }) + }) - Context("with some unknown command", func() { - It(`reports an error and the usage`, func() { - var buf bytes.Buffer - kingpin.CommandLine.Terminate(nil) - kingpin.CommandLine.Writer(&buf) + Context("with some unknown command", func() { + It(`reports an error and the usage`, func() { + var buf bytes.Buffer + kingpin.CommandLine.Terminate(nil) + kingpin.CommandLine.Writer(&buf) - main.Run(cmd("pegomock some unknown command"), &buf, os.Stdin, app, context.Background()) - Expect(buf.String()).To(ContainSubstring("error")) - }) + main.Run(cmd("pegomock some unknown command"), &buf, os.Stdin, app, context.Background()) + Expect(buf.String()).To(ContainSubstring("error")) }) - }) - return nil -} + +}) + func cmd(line string) []string { return strings.Split(line, " ") } diff --git a/pegomock/package_name_test.go b/pegomock/package_name_test.go index 0c94891..489c82a 100644 --- a/pegomock/package_name_test.go +++ b/pegomock/package_name_test.go @@ -4,11 +4,11 @@ import ( "go/build" "os" - . "github.com/petergtz/pegomock/v3/pegomock/testutil" + . "github.com/petergtz/pegomock/v4/pegomock/testutil" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - main "github.com/petergtz/pegomock/v3/pegomock" + main "github.com/petergtz/pegomock/v4/pegomock" ) var _ = Describe("DetermineBla", func() { diff --git a/pegomock/testutil/gomega_file_matcher.go b/pegomock/testutil/gomega_file_matcher.go index 624fede..3337799 100644 --- a/pegomock/testutil/gomega_file_matcher.go +++ b/pegomock/testutil/gomega_file_matcher.go @@ -32,7 +32,7 @@ func BeAFileContainingSubString(substring string) *fileContentSubStringMatcher { func (matcher *fileContentSubStringMatcher) Match(actual interface{}) (bool, error) { actualFilePath, ok := actual.(string) if !ok { - return false, fmt.Errorf("Matcher expects the actual file path as string") + return false, fmt.Errorf("matcher expects the actual file path as string") } var err error matcher.fileContent, err = ioutil.ReadFile(actualFilePath) diff --git a/pegomock/testutil/io.go b/pegomock/testutil/io.go index 704fd93..244e79f 100644 --- a/pegomock/testutil/io.go +++ b/pegomock/testutil/io.go @@ -1,11 +1,11 @@ package testutil import ( - "io/ioutil" + "os" . "github.com/onsi/gomega" ) func WriteFile(filepath string, content string) { - Expect(ioutil.WriteFile(filepath, []byte(content), 0644)).To(Succeed()) + Expect(os.WriteFile(filepath, []byte(content), 0644)).To(Succeed()) } diff --git a/pegomock/util/input.go b/pegomock/util/input.go index fc8cd64..847cdfd 100644 --- a/pegomock/util/input.go +++ b/pegomock/util/input.go @@ -3,8 +3,6 @@ package util import ( "errors" "fmt" - "go/build" - "io/ioutil" "os" "path/filepath" "regexp" @@ -29,10 +27,8 @@ func ValidateArgs(args []string) error { } func SourceArgs(args []string) ([]string, error) { - if SourceMode(args) { - return args[:], nil - } else if len(args) == 1 { - packagePath, err := packagePathFromWorkingDirectoryAndGoPathOrGoModule() + if len(args) == 1 { + packagePath, err := packagePathFromWorkingDirectoryAndGoModule() if err != nil { return nil, fmt.Errorf("Couldn't determine package path from directory: %v", err) } @@ -44,49 +40,11 @@ func SourceArgs(args []string) ([]string, error) { } } -func SourceMode(args []string) bool { - if len(args) == 1 && strings.HasSuffix(args[0], ".go") { - return true - } - return false -} - -func packagePathFromWorkingDirectoryAndGoPathOrGoModule() (string, error) { +func packagePathFromWorkingDirectoryAndGoModule() (string, error) { dir, e := os.Getwd() if e != nil { return "", e } - if os.Getenv("GO111MODULE") == "on" { - return packagePathFromDirUsingGoMod(dir) - } - if os.Getenv("GO111MODULE") == "off" { - return packagePathFromDirUsingGopath(dir) - } - - if os.Getenv("GO111MODULE") == "auto" || os.Getenv("GO111MODULE") == "" { - if withinGopath(dir) { - return packagePathFromDirUsingGopath(dir) - } - return packagePathFromDirUsingGoMod(dir) - } - - return "", errors.New("Not a valid value for $GO111MODULE: " + os.Getenv("GO111MODULE") + " \n" + - "Valid values are \"on\", \"off\", \"auto\", or \"\"") -} - -func packagePathFromDirUsingGopath(dir string) (string, error) { - gopaths := filepath.SplitList(build.Default.GOPATH) - if len(gopaths) == 0 || gopaths[0] == "" { - return "", errors.New("GO111MODULE=off, but no $GOPATH defined") - } - relativePackagePath, err := filepath.Rel(filepath.Join(gopaths[0], "src"), dir) - if err != nil || strings.HasPrefix(relativePackagePath, "..") { - return "", errors.New("Directory is not within a Go package path. GOPATH:" + gopaths[0] + "; dir: " + dir) - } - return relativePackagePath, nil -} - -func packagePathFromDirUsingGoMod(dir string) (string, error) { gomodDir := findModuleRoot(dir) subPackage, e := filepath.Rel(gomodDir, dir) if e != nil { @@ -94,7 +52,7 @@ func packagePathFromDirUsingGoMod(dir string) (string, error) { } gomodFilepath := filepath.Join(gomodDir, "go.mod") - content, e := ioutil.ReadFile(gomodFilepath) + content, e := os.ReadFile(gomodFilepath) if e != nil { return "", errors.New("Could not read file " + gomodFilepath) } @@ -108,23 +66,6 @@ func packagePathFromDirUsingGoMod(dir string) (string, error) { nil } -func withinGopath(dir string) bool { - gopaths := filepath.SplitList(build.Default.GOPATH) - if len(gopaths) == 0 || gopaths[0] == "" { - return false - } - - relPath, err := filepath.Rel(gopaths[0], dir) - if err != nil { - return false - } - - if strings.HasPrefix(relPath, "..") { - return false - } - return true -} - // copied from https://github.com/golang/go/blob/ab724d43efe7e1a7516c1d13e40b55dca26a61b4/src/cmd/go/internal/modload/init.go#L480-L495: func findModuleRoot(dir string) (root string) { dir = filepath.Clean(dir) diff --git a/pegomock/watch/watch.go b/pegomock/watch/watch.go index 3c6af39..93ab681 100644 --- a/pegomock/watch/watch.go +++ b/pegomock/watch/watch.go @@ -16,7 +16,6 @@ package watch import ( "fmt" - "io/ioutil" "os" "path/filepath" "regexp" @@ -24,8 +23,8 @@ import ( "github.com/alecthomas/kingpin/v2" - "github.com/petergtz/pegomock/v3/pegomock/filehandling" - "github.com/petergtz/pegomock/v3/pegomock/util" + "github.com/petergtz/pegomock/v4/pegomock/filehandling" + "github.com/petergtz/pegomock/v4/pegomock/util" ) const wellKnownInterfaceListFile = "interfaces_to_mock" @@ -49,12 +48,15 @@ func NewMockFileUpdater(targetPaths []string, recursive bool) *MockFileUpdater { func (updater *MockFileUpdater) Update() { for _, targetPath := range updater.targetPaths { if updater.recursive { - filepath.Walk(targetPath, func(path string, info os.FileInfo, err error) error { + e := filepath.Walk(targetPath, func(path string, info os.FileInfo, err error) error { if err == nil && info.IsDir() { util.WithinWorkingDir(path, updater.updateMockFiles) } return nil }) + if e != nil { + panic(e) + } } else { util.WithinWorkingDir(targetPath, updater.updateMockFiles) } @@ -92,7 +94,7 @@ func (updater *MockFileUpdater) updateMockFiles(targetPath string) { sourceArgs, err := util.SourceArgs(*lineArgs) util.PanicOnError(err) - generatedMockSourceCode, _ := filehandling.GenerateMockSourceCode(sourceArgs, *nameOut, *packageOut, *selfPackage, false, os.Stdout, false) + generatedMockSourceCode := filehandling.GenerateMockSourceCode(sourceArgs, *nameOut, *packageOut, *selfPackage, false, os.Stdout) mockFilePath := filehandling.OutputFilePath(sourceArgs, ".", *destination) hasChanged := util.WriteFileIfChanged(mockFilePath, generatedMockSourceCode) @@ -122,11 +124,14 @@ func CreateWellKnownInterfaceListFileIfNecessary(targetPath string) { panic(err) } defer file.Close() - file.WriteString("### List here all interfaces you would like to mock. One per line.\n") + _, e := file.WriteString("### List here all interfaces you would like to mock. One per line.\n") + if e != nil { + panic(e) + } } func linesIn(file string) (result [][]string) { - content, err := ioutil.ReadFile(file) + content, err := os.ReadFile(file) util.PanicOnError(err) for _, line := range strings.Split(string(content), "\n") { if strings.HasPrefix(strings.TrimSpace(line), "#") || line == "" { diff --git a/pegomock/watch/watch_test.go b/pegomock/watch/watch_test.go index 8342ea5..b5b8584 100644 --- a/pegomock/watch/watch_test.go +++ b/pegomock/watch/watch_test.go @@ -22,8 +22,8 @@ import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - . "github.com/petergtz/pegomock/v3/pegomock/testutil" - "github.com/petergtz/pegomock/v3/pegomock/watch" + . "github.com/petergtz/pegomock/v4/pegomock/testutil" + "github.com/petergtz/pegomock/v4/pegomock/watch" ) var ( diff --git a/scripts/run_tests.sh b/scripts/run_tests.sh index 48dd6e8..90b288f 100755 --- a/scripts/run_tests.sh +++ b/scripts/run_tests.sh @@ -3,19 +3,7 @@ set -ex cd $(dirname $0)/.. -PACKAGES_TO_SKIP='generate_test_mocks/xtools_go_loader,generate_test_mocks/gomock_reflect,generate_test_mocks/gomock_source' rm -f mock_display_test.go -rm -rf matchers +rm -f mock_generic_display_test.go ginkgo -succinct generate_test_mocks/xtools_go_loader -ginkgo -r --skip-package=$PACKAGES_TO_SKIP,pegomock/watch --randomize-all --randomize-suites --race --trace -cover - -rm -f mock_display_test.go -rm -rf matchers -ginkgo -succinct generate_test_mocks/gomock_reflect -ginkgo --skip-package=pegomock/watch --randomize-all --randomize-suites --race --trace -cover - -# DEPRECATED: gomock_source is deprecated and will be removed in a future release. -#rm -f mock_display_test.go -#rm -rf matchers -#ginkgo -succinct generate_test_mocks/gomock_source -#ginkgo --skip-package=pegomock/watch --randomize-all --randomize-suites --race --trace -cover +ginkgo -r --skip-package=generate_test_mocks/xtools_go_loader,pegomock/watch --randomize-all --randomize-suites --race --trace -cover