From 789f6b158f6cc2a22adfac13edadcb4a9e954d11 Mon Sep 17 00:00:00 2001 From: oliveromahony Date: Thu, 23 Nov 2023 14:59:13 +0000 Subject: [PATCH] replacing mockgen with newer package (#524) --- COPYRIGHT | 4 + Makefile | 2 +- go.mod | 2 +- go.sum | 4 +- scripts/tools.go | 2 +- .../advanced-metrics/aggregator/aggregator.go | 2 +- .../aggregator/aggregator_test.go | 2 +- .../aggregator/mocks/aggregator_mock.go | 23 +- .../advanced-metrics/ingester/ingester.go | 3 +- .../ingester/ingester_test.go | 2 +- .../ingester/mocks/ingester_mock.go | 21 +- .../reader/mocks/net_mocks.go | 25 +- .../reader/mocks/reader_mock.go | 23 +- .../advanced-metrics/reader/reader.go | 5 +- .../advanced-metrics/reader/reader_test.go | 2 +- .../advanced-metrics/reader/worker_test.go | 2 +- .../tables/mocks/staging_table_mocks.go | 29 +- .../advanced-metrics/tables/staging_table.go | 2 +- .../tables/staging_table_test.go | 2 +- test/integration/go.sum | 2 + .../github.com/nginx/agent/v2/COPYRIGHT | 4 + .../advanced-metrics/aggregator/aggregator.go | 2 +- .../advanced-metrics/ingester/ingester.go | 3 +- .../advanced-metrics/reader/reader.go | 5 +- .../advanced-metrics/tables/staging_table.go | 2 +- test/performance/go.sum | 4 +- .../github.com/nginx/agent/v2/COPYRIGHT | 4 + .../advanced-metrics/aggregator/aggregator.go | 2 +- .../advanced-metrics/ingester/ingester.go | 3 +- .../advanced-metrics/reader/reader.go | 5 +- .../advanced-metrics/tables/staging_table.go | 2 +- .../golang/mock/mockgen/version.1.11.go | 26 -- .../golang => go.uber.org}/mock/AUTHORS | 0 .../golang => go.uber.org}/mock/CONTRIBUTORS | 0 .../golang => go.uber.org}/mock/LICENSE | 0 .../mock/gomock/call.go | 127 +++++-- .../mock/gomock/callset.go | 59 ++- .../mock/gomock/controller.go | 136 +++---- vendor/go.uber.org/mock/gomock/doc.go | 60 +++ .../mock/gomock/matchers.go | 97 +++-- .../go.uber.org/mock/mockgen/generic_go118.go | 116 ++++++ .../mock/mockgen/generic_notgo118.go | 41 +++ .../mock/mockgen/mockgen.go | 303 +++++++++++---- .../mock/mockgen/model/model.go | 70 +++- .../mock/mockgen/parse.go | 346 +++++++++++++----- .../mock/mockgen/reflect.go | 15 +- .../mock/mockgen/version.go} | 6 +- vendor/modules.txt | 10 +- 48 files changed, 1148 insertions(+), 459 deletions(-) create mode 100644 COPYRIGHT create mode 100644 test/integration/vendor/github.com/nginx/agent/v2/COPYRIGHT create mode 100644 test/performance/vendor/github.com/nginx/agent/v2/COPYRIGHT delete mode 100644 vendor/github.com/golang/mock/mockgen/version.1.11.go rename vendor/{github.com/golang => go.uber.org}/mock/AUTHORS (100%) rename vendor/{github.com/golang => go.uber.org}/mock/CONTRIBUTORS (100%) rename vendor/{github.com/golang => go.uber.org}/mock/LICENSE (100%) rename vendor/{github.com/golang => go.uber.org}/mock/gomock/call.go (78%) rename vendor/{github.com/golang => go.uber.org}/mock/gomock/callset.go (70%) rename vendor/{github.com/golang => go.uber.org}/mock/gomock/controller.go (67%) create mode 100644 vendor/go.uber.org/mock/gomock/doc.go rename vendor/{github.com/golang => go.uber.org}/mock/gomock/matchers.go (76%) create mode 100644 vendor/go.uber.org/mock/mockgen/generic_go118.go create mode 100644 vendor/go.uber.org/mock/mockgen/generic_notgo118.go rename vendor/{github.com/golang => go.uber.org}/mock/mockgen/mockgen.go (64%) rename vendor/{github.com/golang => go.uber.org}/mock/mockgen/model/model.go (87%) rename vendor/{github.com/golang => go.uber.org}/mock/mockgen/parse.go (63%) rename vendor/{github.com/golang => go.uber.org}/mock/mockgen/reflect.go (93%) rename vendor/{github.com/golang/mock/mockgen/version.1.12.go => go.uber.org/mock/mockgen/version.go} (94%) diff --git a/COPYRIGHT b/COPYRIGHT new file mode 100644 index 0000000000..1c015a857f --- /dev/null +++ b/COPYRIGHT @@ -0,0 +1,4 @@ + Copyright (c) F5, Inc. + + This source code is licensed under the Apache License, Version 2.0 license found in the + LICENSE file in the root directory of this source tree. diff --git a/Makefile b/Makefile index 64307e785d..fafa9068d1 100644 --- a/Makefile +++ b/Makefile @@ -160,7 +160,7 @@ include Makefile.packaging # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Testing # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # -generate-mocks: ## Regenerate all needed mocks, in order to add new mocks generation add //go:generate mockgen to file from witch mocks should be generated +generate-mocks: ## Regenerate all needed mocks, in order to add new mocks generation add //go:generate to file from witch mocks should be generated GOWORK=off go generate ./... test: unit-test performance-test component-test integration-test ## Run all tests diff --git a/go.mod b/go.mod index e86469695e..1f3065b1e4 100644 --- a/go.mod +++ b/go.mod @@ -6,7 +6,6 @@ require ( github.com/cenkalti/backoff/v4 v4.2.1 // indirect github.com/fsnotify/fsnotify v1.6.0 github.com/gogo/protobuf v1.3.2 - github.com/golang/mock v1.6.0 github.com/golang/protobuf v1.5.3 github.com/google/go-cmp v0.6.0 github.com/google/uuid v1.3.1 @@ -47,6 +46,7 @@ require ( github.com/prometheus/client_golang v1.17.0 github.com/pseudomuto/protoc-gen-doc v1.5.1 github.com/rs/cors v1.10.1 + go.uber.org/mock v0.3.0 golang.org/x/sys v0.14.0 golang.org/x/text v0.13.0 gopkg.in/yaml.v2 v2.4.0 diff --git a/go.sum b/go.sum index 52a5e22f5f..74813400e5 100644 --- a/go.sum +++ b/go.sum @@ -398,8 +398,6 @@ github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= -github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc= -github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= @@ -1021,6 +1019,8 @@ go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0 go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A= go.uber.org/goleak v1.2.1 h1:NBol2c7O1ZokfZ0LEU9K6Whx/KnwvepVetCUhtKja4A= go.uber.org/goleak v1.2.1/go.mod h1:qlT2yGI9QafXHhZZLxlSuNsMw3FFLxBr+tBRlmO1xH4= +go.uber.org/mock v0.3.0 h1:3mUxI1No2/60yUYax92Pt8eNOEecx2D3lcXZh2NEZJo= +go.uber.org/mock v0.3.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc= go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= diff --git a/scripts/tools.go b/scripts/tools.go index bf545e8f0b..48ad7d877f 100644 --- a/scripts/tools.go +++ b/scripts/tools.go @@ -11,12 +11,12 @@ import ( _ "github.com/go-swagger/go-swagger/cmd/swagger" _ "github.com/gogo/protobuf/protoc-gen-gogo" _ "github.com/gogo/protobuf/protoc-gen-gogofast" - _ "github.com/golang/mock/mockgen" _ "github.com/golangci/golangci-lint/cmd/golangci-lint" _ "github.com/goreleaser/nfpm/v2/cmd/nfpm" _ "github.com/maxbrunsfeld/counterfeiter/v6" _ "github.com/mwitkow/go-proto-validators/protoc-gen-govalidators" _ "github.com/pseudomuto/protoc-gen-doc/cmd/protoc-gen-doc" + _ "go.uber.org/mock/mockgen" _ "google.golang.org/grpc/cmd/protoc-gen-go-grpc" _ "mvdan.cc/gofumpt" ) diff --git a/src/extensions/advanced-metrics/aggregator/aggregator.go b/src/extensions/advanced-metrics/aggregator/aggregator.go index c17cd18f5a..9b8ae196de 100644 --- a/src/extensions/advanced-metrics/aggregator/aggregator.go +++ b/src/extensions/advanced-metrics/aggregator/aggregator.go @@ -19,7 +19,7 @@ import ( log "github.com/sirupsen/logrus" ) -//go:generate mockgen -source aggregator.go -destination mocks/aggregator_mock.go -package mocks +//go:generate go run go.uber.org/mock/mockgen -source aggregator.go -destination mocks/aggregator_mock.go -package mocks -copyright_file=../../../../COPYRIGHT type ReadTable interface { ReadSnapshot(resetLookups bool) (tables.SamplesView, tables.LookupSet) diff --git a/src/extensions/advanced-metrics/aggregator/aggregator_test.go b/src/extensions/advanced-metrics/aggregator/aggregator_test.go index 01a6e80978..b26b0e3292 100644 --- a/src/extensions/advanced-metrics/aggregator/aggregator_test.go +++ b/src/extensions/advanced-metrics/aggregator/aggregator_test.go @@ -13,7 +13,6 @@ import ( "testing" "time" - "github.com/golang/mock/gomock" "github.com/nginx/agent/v2/src/extensions/advanced-metrics/aggregator" "github.com/nginx/agent/v2/src/extensions/advanced-metrics/aggregator/mocks" "github.com/nginx/agent/v2/src/extensions/advanced-metrics/tables" @@ -23,6 +22,7 @@ import ( "github.com/nginx/agent/v2/src/extensions/advanced-metrics/tables/sample" "github.com/nginx/agent/v2/src/extensions/advanced-metrics/tables/schema" "github.com/stretchr/testify/assert" + "go.uber.org/mock/gomock" ) func TestAggregatorPublish(t *testing.T) { diff --git a/src/extensions/advanced-metrics/aggregator/mocks/aggregator_mock.go b/src/extensions/advanced-metrics/aggregator/mocks/aggregator_mock.go index 1c628f2c5f..1a308788d6 100644 --- a/src/extensions/advanced-metrics/aggregator/mocks/aggregator_mock.go +++ b/src/extensions/advanced-metrics/aggregator/mocks/aggregator_mock.go @@ -1,13 +1,16 @@ -/** - * Copyright (c) F5, Inc. - * - * This source code is licensed under the Apache License, Version 2.0 license found in the - * LICENSE file in the root directory of this source tree. - */ +// Copyright (c) F5, Inc. +// +// This source code is licensed under the Apache License, Version 2.0 license found in the +// LICENSE file in the root directory of this source tree. +// // Code generated by MockGen. DO NOT EDIT. // Source: aggregator.go - +// +// Generated by this command: +// +// mockgen -source aggregator.go -destination mocks/aggregator_mock.go -package mocks -copyright_file=../../../../COPYRIGHT +// // Package mocks is a generated GoMock package. package mocks @@ -15,10 +18,10 @@ import ( context "context" reflect "reflect" - gomock "github.com/golang/mock/gomock" aggregator "github.com/nginx/agent/v2/src/extensions/advanced-metrics/aggregator" tables "github.com/nginx/agent/v2/src/extensions/advanced-metrics/tables" sample "github.com/nginx/agent/v2/src/extensions/advanced-metrics/tables/sample" + gomock "go.uber.org/mock/gomock" ) // MockReadTable is a mock of ReadTable interface. @@ -54,7 +57,7 @@ func (m *MockReadTable) ReadSnapshot(resetLookups bool) (tables.SamplesView, tab } // ReadSnapshot indicates an expected call of ReadSnapshot. -func (mr *MockReadTableMockRecorder) ReadSnapshot(resetLookups interface{}) *gomock.Call { +func (mr *MockReadTableMockRecorder) ReadSnapshot(resetLookups any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReadSnapshot", reflect.TypeOf((*MockReadTable)(nil).ReadSnapshot), resetLookups) } @@ -128,7 +131,7 @@ func (m *MockPublisher) Publish(arg0 context.Context, arg1 tables.LookupSet, arg } // Publish indicates an expected call of Publish. -func (mr *MockPublisherMockRecorder) Publish(arg0, arg1, arg2 interface{}) *gomock.Call { +func (mr *MockPublisherMockRecorder) Publish(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Publish", reflect.TypeOf((*MockPublisher)(nil).Publish), arg0, arg1, arg2) } diff --git a/src/extensions/advanced-metrics/ingester/ingester.go b/src/extensions/advanced-metrics/ingester/ingester.go index 90c255cde7..2905be41ef 100644 --- a/src/extensions/advanced-metrics/ingester/ingester.go +++ b/src/extensions/advanced-metrics/ingester/ingester.go @@ -16,8 +16,7 @@ import ( log "github.com/sirupsen/logrus" ) -//go:generate mockgen -source ingester.go -destination mocks/ingester_mock.go -package mocks - +//go:generate go run go.uber.org/mock/mockgen -source ingester.go -destination mocks/ingester_mock.go -package mocks -copyright_file=../../../../COPYRIGHT const workers = 3 type StagingTable interface { diff --git a/src/extensions/advanced-metrics/ingester/ingester_test.go b/src/extensions/advanced-metrics/ingester/ingester_test.go index 8f73bbd057..8b103ee23b 100644 --- a/src/extensions/advanced-metrics/ingester/ingester_test.go +++ b/src/extensions/advanced-metrics/ingester/ingester_test.go @@ -13,10 +13,10 @@ import ( "sync" "testing" - "github.com/golang/mock/gomock" "github.com/nginx/agent/v2/src/extensions/advanced-metrics/ingester/mocks" "github.com/nginx/agent/v2/src/extensions/advanced-metrics/reader" readerMock "github.com/nginx/agent/v2/src/extensions/advanced-metrics/reader/mocks" + "go.uber.org/mock/gomock" ) func TestIngesterRunCanProcessIncomingData(t *testing.T) { diff --git a/src/extensions/advanced-metrics/ingester/mocks/ingester_mock.go b/src/extensions/advanced-metrics/ingester/mocks/ingester_mock.go index bc458c3175..936e6dabd4 100644 --- a/src/extensions/advanced-metrics/ingester/mocks/ingester_mock.go +++ b/src/extensions/advanced-metrics/ingester/mocks/ingester_mock.go @@ -1,21 +1,24 @@ -/** - * Copyright (c) F5, Inc. - * - * This source code is licensed under the Apache License, Version 2.0 license found in the - * LICENSE file in the root directory of this source tree. - */ +// Copyright (c) F5, Inc. +// +// This source code is licensed under the Apache License, Version 2.0 license found in the +// LICENSE file in the root directory of this source tree. +// // Code generated by MockGen. DO NOT EDIT. // Source: ingester.go - +// +// Generated by this command: +// +// mockgen -source ingester.go -destination mocks/ingester_mock.go -package mocks -copyright_file=../../../../COPYRIGHT +// // Package mocks is a generated GoMock package. package mocks import ( reflect "reflect" - gomock "github.com/golang/mock/gomock" tables "github.com/nginx/agent/v2/src/extensions/advanced-metrics/tables" + gomock "go.uber.org/mock/gomock" ) // MockStagingTable is a mock of StagingTable interface. @@ -50,7 +53,7 @@ func (m *MockStagingTable) Add(arg0 tables.FieldIterator) error { } // Add indicates an expected call of Add. -func (mr *MockStagingTableMockRecorder) Add(arg0 interface{}) *gomock.Call { +func (mr *MockStagingTableMockRecorder) Add(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Add", reflect.TypeOf((*MockStagingTable)(nil).Add), arg0) } diff --git a/src/extensions/advanced-metrics/reader/mocks/net_mocks.go b/src/extensions/advanced-metrics/reader/mocks/net_mocks.go index aeecb07c75..107f129f47 100644 --- a/src/extensions/advanced-metrics/reader/mocks/net_mocks.go +++ b/src/extensions/advanced-metrics/reader/mocks/net_mocks.go @@ -1,13 +1,10 @@ -/** - * Copyright (c) F5, Inc. - * - * This source code is licensed under the Apache License, Version 2.0 license found in the - * LICENSE file in the root directory of this source tree. - */ - // Code generated by MockGen. DO NOT EDIT. // Source: net (interfaces: Listener,Conn) - +// +// Generated by this command: +// +// mockgen -destination mocks/net_mocks.go -build_flags=--mod=mod -package mocks net Listener,Conn +// // Package mocks is a generated GoMock package. package mocks @@ -16,7 +13,7 @@ import ( reflect "reflect" time "time" - gomock "github.com/golang/mock/gomock" + gomock "go.uber.org/mock/gomock" ) // MockListener is a mock of Listener interface. @@ -146,7 +143,7 @@ func (m *MockConn) Read(arg0 []byte) (int, error) { } // Read indicates an expected call of Read. -func (mr *MockConnMockRecorder) Read(arg0 interface{}) *gomock.Call { +func (mr *MockConnMockRecorder) Read(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Read", reflect.TypeOf((*MockConn)(nil).Read), arg0) } @@ -174,7 +171,7 @@ func (m *MockConn) SetDeadline(arg0 time.Time) error { } // SetDeadline indicates an expected call of SetDeadline. -func (mr *MockConnMockRecorder) SetDeadline(arg0 interface{}) *gomock.Call { +func (mr *MockConnMockRecorder) SetDeadline(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetDeadline", reflect.TypeOf((*MockConn)(nil).SetDeadline), arg0) } @@ -188,7 +185,7 @@ func (m *MockConn) SetReadDeadline(arg0 time.Time) error { } // SetReadDeadline indicates an expected call of SetReadDeadline. -func (mr *MockConnMockRecorder) SetReadDeadline(arg0 interface{}) *gomock.Call { +func (mr *MockConnMockRecorder) SetReadDeadline(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetReadDeadline", reflect.TypeOf((*MockConn)(nil).SetReadDeadline), arg0) } @@ -202,7 +199,7 @@ func (m *MockConn) SetWriteDeadline(arg0 time.Time) error { } // SetWriteDeadline indicates an expected call of SetWriteDeadline. -func (mr *MockConnMockRecorder) SetWriteDeadline(arg0 interface{}) *gomock.Call { +func (mr *MockConnMockRecorder) SetWriteDeadline(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetWriteDeadline", reflect.TypeOf((*MockConn)(nil).SetWriteDeadline), arg0) } @@ -217,7 +214,7 @@ func (m *MockConn) Write(arg0 []byte) (int, error) { } // Write indicates an expected call of Write. -func (mr *MockConnMockRecorder) Write(arg0 interface{}) *gomock.Call { +func (mr *MockConnMockRecorder) Write(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Write", reflect.TypeOf((*MockConn)(nil).Write), arg0) } diff --git a/src/extensions/advanced-metrics/reader/mocks/reader_mock.go b/src/extensions/advanced-metrics/reader/mocks/reader_mock.go index 26451c5430..7713441329 100644 --- a/src/extensions/advanced-metrics/reader/mocks/reader_mock.go +++ b/src/extensions/advanced-metrics/reader/mocks/reader_mock.go @@ -1,13 +1,16 @@ -/** - * Copyright (c) F5, Inc. - * - * This source code is licensed under the Apache License, Version 2.0 license found in the - * LICENSE file in the root directory of this source tree. - */ +// Copyright (c) F5, Inc. +// +// This source code is licensed under the Apache License, Version 2.0 license found in the +// LICENSE file in the root directory of this source tree. +// // Code generated by MockGen. DO NOT EDIT. // Source: reader.go - +// +// Generated by this command: +// +// mockgen -source reader.go -destination mocks/reader_mock.go -package mocks -copyright_file=../../../../COPYRIGHT +// // Package mocks is a generated GoMock package. package mocks @@ -16,7 +19,7 @@ import ( net "net" reflect "reflect" - gomock "github.com/golang/mock/gomock" + gomock "go.uber.org/mock/gomock" ) // MockListenerConfig is a mock of ListenerConfig interface. @@ -52,7 +55,7 @@ func (m *MockListenerConfig) Listen(ctx context.Context, network, address string } // Listen indicates an expected call of Listen. -func (mr *MockListenerConfigMockRecorder) Listen(ctx, network, address interface{}) *gomock.Call { +func (mr *MockListenerConfigMockRecorder) Listen(ctx, network, address any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Listen", reflect.TypeOf((*MockListenerConfig)(nil).Listen), ctx, network, address) } @@ -89,7 +92,7 @@ func (m *MockWorker) Run(ctx context.Context) error { } // Run indicates an expected call of Run. -func (mr *MockWorkerMockRecorder) Run(ctx interface{}) *gomock.Call { +func (mr *MockWorkerMockRecorder) Run(ctx any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Run", reflect.TypeOf((*MockWorker)(nil).Run), ctx) } diff --git a/src/extensions/advanced-metrics/reader/reader.go b/src/extensions/advanced-metrics/reader/reader.go index 762b79b67d..94886b3e5b 100644 --- a/src/extensions/advanced-metrics/reader/reader.go +++ b/src/extensions/advanced-metrics/reader/reader.go @@ -19,9 +19,8 @@ import ( "golang.org/x/sync/errgroup" ) -//go:generate mockgen -source reader.go -destination mocks/reader_mock.go -package mocks -//go:generate mockgen -destination mocks/net_mocks.go -build_flags=--mod=mod -package mocks net Listener,Conn - +//go:generate go run go.uber.org/mock/mockgen -source reader.go -destination mocks/reader_mock.go -package mocks -copyright_file=../../../../COPYRIGHT +//go:generate go run go.uber.org/mock/mockgen -destination mocks/net_mocks.go -build_flags=--mod=mod -package mocks net Listener,Conn const ( networkType = "unix" ) diff --git a/src/extensions/advanced-metrics/reader/reader_test.go b/src/extensions/advanced-metrics/reader/reader_test.go index 34a21ee8a8..a320d08a35 100644 --- a/src/extensions/advanced-metrics/reader/reader_test.go +++ b/src/extensions/advanced-metrics/reader/reader_test.go @@ -14,9 +14,9 @@ import ( "net" "testing" - "github.com/golang/mock/gomock" "github.com/nginx/agent/v2/src/extensions/advanced-metrics/reader/mocks" "github.com/stretchr/testify/assert" + "go.uber.org/mock/gomock" ) const address = "/tmp/advanced-metrics.sr" diff --git a/src/extensions/advanced-metrics/reader/worker_test.go b/src/extensions/advanced-metrics/reader/worker_test.go index 763e69b988..3f87713320 100644 --- a/src/extensions/advanced-metrics/reader/worker_test.go +++ b/src/extensions/advanced-metrics/reader/worker_test.go @@ -15,10 +15,10 @@ import ( "testing" "time" - "github.com/golang/mock/gomock" "github.com/nginx/agent/v2/src/extensions/advanced-metrics/reader/mocks" "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" + "go.uber.org/mock/gomock" ) func TestWorkerStopAndCloseConnectionOnContexCancelation(t *testing.T) { diff --git a/src/extensions/advanced-metrics/tables/mocks/staging_table_mocks.go b/src/extensions/advanced-metrics/tables/mocks/staging_table_mocks.go index 9193957b74..99e34d1159 100644 --- a/src/extensions/advanced-metrics/tables/mocks/staging_table_mocks.go +++ b/src/extensions/advanced-metrics/tables/mocks/staging_table_mocks.go @@ -1,22 +1,25 @@ -/** - * Copyright (c) F5, Inc. - * - * This source code is licensed under the Apache License, Version 2.0 license found in the - * LICENSE file in the root directory of this source tree. - */ +// Copyright (c) F5, Inc. +// +// This source code is licensed under the Apache License, Version 2.0 license found in the +// LICENSE file in the root directory of this source tree. +// // Code generated by MockGen. DO NOT EDIT. // Source: staging_table.go - +// +// Generated by this command: +// +// mockgen -source staging_table.go -destination mocks/staging_table_mocks.go -package mocks -copyright_file=../../../../COPYRIGHT +// // Package mocks is a generated GoMock package. package mocks import ( reflect "reflect" - gomock "github.com/golang/mock/gomock" sample "github.com/nginx/agent/v2/src/extensions/advanced-metrics/tables/sample" schema "github.com/nginx/agent/v2/src/extensions/advanced-metrics/tables/schema" + gomock "go.uber.org/mock/gomock" ) // MockFieldIterator is a mock of FieldIterator interface. @@ -100,7 +103,7 @@ func (m *MockSamplesView) Range(cb func(*sample.Sample)) { } // Range indicates an expected call of Range. -func (mr *MockSamplesViewMockRecorder) Range(cb interface{}) *gomock.Call { +func (mr *MockSamplesViewMockRecorder) Range(cb any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Range", reflect.TypeOf((*MockSamplesView)(nil).Range), cb) } @@ -137,7 +140,7 @@ func (m *MockSamples) Add(s sample.Sample) error { } // Add indicates an expected call of Add. -func (mr *MockSamplesMockRecorder) Add(s interface{}) *gomock.Call { +func (mr *MockSamplesMockRecorder) Add(s any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Add", reflect.TypeOf((*MockSamples)(nil).Add), s) } @@ -175,7 +178,7 @@ func (m *MockSamples) Range(cb func(*sample.Sample)) { } // Range indicates an expected call of Range. -func (mr *MockSamplesMockRecorder) Range(cb interface{}) *gomock.Call { +func (mr *MockSamplesMockRecorder) Range(cb any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Range", reflect.TypeOf((*MockSamples)(nil).Range), cb) } @@ -213,7 +216,7 @@ func (m *MockLookupSet) LookupBytes(arg0 schema.FieldIndex, arg1 []byte) (int, e } // LookupBytes indicates an expected call of LookupBytes. -func (mr *MockLookupSetMockRecorder) LookupBytes(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockLookupSetMockRecorder) LookupBytes(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LookupBytes", reflect.TypeOf((*MockLookupSet)(nil).LookupBytes), arg0, arg1) } @@ -228,7 +231,7 @@ func (m *MockLookupSet) LookupCode(arg0, arg1 int) (string, error) { } // LookupCode indicates an expected call of LookupCode. -func (mr *MockLookupSetMockRecorder) LookupCode(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockLookupSetMockRecorder) LookupCode(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LookupCode", reflect.TypeOf((*MockLookupSet)(nil).LookupCode), arg0, arg1) } diff --git a/src/extensions/advanced-metrics/tables/staging_table.go b/src/extensions/advanced-metrics/tables/staging_table.go index 8e17a19a19..503959c89e 100644 --- a/src/extensions/advanced-metrics/tables/staging_table.go +++ b/src/extensions/advanced-metrics/tables/staging_table.go @@ -20,7 +20,7 @@ import ( log "github.com/sirupsen/logrus" ) -//go:generate mockgen -source staging_table.go -destination mocks/staging_table_mocks.go -package mocks +//go:generate go run go.uber.org/mock/mockgen -source staging_table.go -destination mocks/staging_table_mocks.go -package mocks -copyright_file=../../../../COPYRIGHT const ( hexBase = 16 ) diff --git a/src/extensions/advanced-metrics/tables/staging_table_test.go b/src/extensions/advanced-metrics/tables/staging_table_test.go index 9dae090588..0facd9d2d4 100644 --- a/src/extensions/advanced-metrics/tables/staging_table_test.go +++ b/src/extensions/advanced-metrics/tables/staging_table_test.go @@ -14,13 +14,13 @@ import ( "sync" "testing" - "github.com/golang/mock/gomock" "github.com/nginx/agent/v2/src/extensions/advanced-metrics/tables/limits" "github.com/nginx/agent/v2/src/extensions/advanced-metrics/tables/lookup" "github.com/nginx/agent/v2/src/extensions/advanced-metrics/tables/mocks" "github.com/nginx/agent/v2/src/extensions/advanced-metrics/tables/sample" "github.com/nginx/agent/v2/src/extensions/advanced-metrics/tables/schema" "github.com/stretchr/testify/assert" + "go.uber.org/mock/gomock" ) const ( diff --git a/test/integration/go.sum b/test/integration/go.sum index d4ff5b853a..e873d242f8 100644 --- a/test/integration/go.sum +++ b/test/integration/go.sum @@ -709,6 +709,8 @@ go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A= go.uber.org/goleak v1.2.1 h1:NBol2c7O1ZokfZ0LEU9K6Whx/KnwvepVetCUhtKja4A= go.uber.org/goleak v1.2.1/go.mod h1:qlT2yGI9QafXHhZZLxlSuNsMw3FFLxBr+tBRlmO1xH4= +go.uber.org/mock v0.3.0 h1:3mUxI1No2/60yUYax92Pt8eNOEecx2D3lcXZh2NEZJo= +go.uber.org/mock v0.3.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc= go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= diff --git a/test/integration/vendor/github.com/nginx/agent/v2/COPYRIGHT b/test/integration/vendor/github.com/nginx/agent/v2/COPYRIGHT new file mode 100644 index 0000000000..1c015a857f --- /dev/null +++ b/test/integration/vendor/github.com/nginx/agent/v2/COPYRIGHT @@ -0,0 +1,4 @@ + Copyright (c) F5, Inc. + + This source code is licensed under the Apache License, Version 2.0 license found in the + LICENSE file in the root directory of this source tree. diff --git a/test/integration/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/aggregator/aggregator.go b/test/integration/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/aggregator/aggregator.go index c17cd18f5a..9b8ae196de 100644 --- a/test/integration/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/aggregator/aggregator.go +++ b/test/integration/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/aggregator/aggregator.go @@ -19,7 +19,7 @@ import ( log "github.com/sirupsen/logrus" ) -//go:generate mockgen -source aggregator.go -destination mocks/aggregator_mock.go -package mocks +//go:generate go run go.uber.org/mock/mockgen -source aggregator.go -destination mocks/aggregator_mock.go -package mocks -copyright_file=../../../../COPYRIGHT type ReadTable interface { ReadSnapshot(resetLookups bool) (tables.SamplesView, tables.LookupSet) diff --git a/test/integration/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/ingester/ingester.go b/test/integration/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/ingester/ingester.go index 90c255cde7..2905be41ef 100644 --- a/test/integration/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/ingester/ingester.go +++ b/test/integration/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/ingester/ingester.go @@ -16,8 +16,7 @@ import ( log "github.com/sirupsen/logrus" ) -//go:generate mockgen -source ingester.go -destination mocks/ingester_mock.go -package mocks - +//go:generate go run go.uber.org/mock/mockgen -source ingester.go -destination mocks/ingester_mock.go -package mocks -copyright_file=../../../../COPYRIGHT const workers = 3 type StagingTable interface { diff --git a/test/integration/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/reader/reader.go b/test/integration/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/reader/reader.go index 762b79b67d..94886b3e5b 100644 --- a/test/integration/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/reader/reader.go +++ b/test/integration/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/reader/reader.go @@ -19,9 +19,8 @@ import ( "golang.org/x/sync/errgroup" ) -//go:generate mockgen -source reader.go -destination mocks/reader_mock.go -package mocks -//go:generate mockgen -destination mocks/net_mocks.go -build_flags=--mod=mod -package mocks net Listener,Conn - +//go:generate go run go.uber.org/mock/mockgen -source reader.go -destination mocks/reader_mock.go -package mocks -copyright_file=../../../../COPYRIGHT +//go:generate go run go.uber.org/mock/mockgen -destination mocks/net_mocks.go -build_flags=--mod=mod -package mocks net Listener,Conn const ( networkType = "unix" ) diff --git a/test/integration/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/tables/staging_table.go b/test/integration/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/tables/staging_table.go index 8e17a19a19..503959c89e 100644 --- a/test/integration/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/tables/staging_table.go +++ b/test/integration/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/tables/staging_table.go @@ -20,7 +20,7 @@ import ( log "github.com/sirupsen/logrus" ) -//go:generate mockgen -source staging_table.go -destination mocks/staging_table_mocks.go -package mocks +//go:generate go run go.uber.org/mock/mockgen -source staging_table.go -destination mocks/staging_table_mocks.go -package mocks -copyright_file=../../../../COPYRIGHT const ( hexBase = 16 ) diff --git a/test/performance/go.sum b/test/performance/go.sum index 6fa6694897..759dc516b0 100644 --- a/test/performance/go.sum +++ b/test/performance/go.sum @@ -93,8 +93,6 @@ github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= -github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc= -github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= @@ -319,6 +317,8 @@ go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A= +go.uber.org/mock v0.3.0 h1:3mUxI1No2/60yUYax92Pt8eNOEecx2D3lcXZh2NEZJo= +go.uber.org/mock v0.3.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc= go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= diff --git a/test/performance/vendor/github.com/nginx/agent/v2/COPYRIGHT b/test/performance/vendor/github.com/nginx/agent/v2/COPYRIGHT new file mode 100644 index 0000000000..1c015a857f --- /dev/null +++ b/test/performance/vendor/github.com/nginx/agent/v2/COPYRIGHT @@ -0,0 +1,4 @@ + Copyright (c) F5, Inc. + + This source code is licensed under the Apache License, Version 2.0 license found in the + LICENSE file in the root directory of this source tree. diff --git a/test/performance/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/aggregator/aggregator.go b/test/performance/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/aggregator/aggregator.go index c17cd18f5a..9b8ae196de 100644 --- a/test/performance/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/aggregator/aggregator.go +++ b/test/performance/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/aggregator/aggregator.go @@ -19,7 +19,7 @@ import ( log "github.com/sirupsen/logrus" ) -//go:generate mockgen -source aggregator.go -destination mocks/aggregator_mock.go -package mocks +//go:generate go run go.uber.org/mock/mockgen -source aggregator.go -destination mocks/aggregator_mock.go -package mocks -copyright_file=../../../../COPYRIGHT type ReadTable interface { ReadSnapshot(resetLookups bool) (tables.SamplesView, tables.LookupSet) diff --git a/test/performance/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/ingester/ingester.go b/test/performance/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/ingester/ingester.go index 90c255cde7..2905be41ef 100644 --- a/test/performance/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/ingester/ingester.go +++ b/test/performance/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/ingester/ingester.go @@ -16,8 +16,7 @@ import ( log "github.com/sirupsen/logrus" ) -//go:generate mockgen -source ingester.go -destination mocks/ingester_mock.go -package mocks - +//go:generate go run go.uber.org/mock/mockgen -source ingester.go -destination mocks/ingester_mock.go -package mocks -copyright_file=../../../../COPYRIGHT const workers = 3 type StagingTable interface { diff --git a/test/performance/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/reader/reader.go b/test/performance/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/reader/reader.go index 762b79b67d..94886b3e5b 100644 --- a/test/performance/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/reader/reader.go +++ b/test/performance/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/reader/reader.go @@ -19,9 +19,8 @@ import ( "golang.org/x/sync/errgroup" ) -//go:generate mockgen -source reader.go -destination mocks/reader_mock.go -package mocks -//go:generate mockgen -destination mocks/net_mocks.go -build_flags=--mod=mod -package mocks net Listener,Conn - +//go:generate go run go.uber.org/mock/mockgen -source reader.go -destination mocks/reader_mock.go -package mocks -copyright_file=../../../../COPYRIGHT +//go:generate go run go.uber.org/mock/mockgen -destination mocks/net_mocks.go -build_flags=--mod=mod -package mocks net Listener,Conn const ( networkType = "unix" ) diff --git a/test/performance/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/tables/staging_table.go b/test/performance/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/tables/staging_table.go index 8e17a19a19..503959c89e 100644 --- a/test/performance/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/tables/staging_table.go +++ b/test/performance/vendor/github.com/nginx/agent/v2/src/extensions/advanced-metrics/tables/staging_table.go @@ -20,7 +20,7 @@ import ( log "github.com/sirupsen/logrus" ) -//go:generate mockgen -source staging_table.go -destination mocks/staging_table_mocks.go -package mocks +//go:generate go run go.uber.org/mock/mockgen -source staging_table.go -destination mocks/staging_table_mocks.go -package mocks -copyright_file=../../../../COPYRIGHT const ( hexBase = 16 ) diff --git a/vendor/github.com/golang/mock/mockgen/version.1.11.go b/vendor/github.com/golang/mock/mockgen/version.1.11.go deleted file mode 100644 index e6b25db238..0000000000 --- a/vendor/github.com/golang/mock/mockgen/version.1.11.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2019 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build !go1.12 - -package main - -import ( - "log" -) - -func printModuleVersion() { - log.Printf("No version information is available for Mockgen compiled with " + - "version 1.11") -} diff --git a/vendor/github.com/golang/mock/AUTHORS b/vendor/go.uber.org/mock/AUTHORS similarity index 100% rename from vendor/github.com/golang/mock/AUTHORS rename to vendor/go.uber.org/mock/AUTHORS diff --git a/vendor/github.com/golang/mock/CONTRIBUTORS b/vendor/go.uber.org/mock/CONTRIBUTORS similarity index 100% rename from vendor/github.com/golang/mock/CONTRIBUTORS rename to vendor/go.uber.org/mock/CONTRIBUTORS diff --git a/vendor/github.com/golang/mock/LICENSE b/vendor/go.uber.org/mock/LICENSE similarity index 100% rename from vendor/github.com/golang/mock/LICENSE rename to vendor/go.uber.org/mock/LICENSE diff --git a/vendor/github.com/golang/mock/gomock/call.go b/vendor/go.uber.org/mock/gomock/call.go similarity index 78% rename from vendor/github.com/golang/mock/gomock/call.go rename to vendor/go.uber.org/mock/gomock/call.go index 13c9f44b1e..e1ea826377 100644 --- a/vendor/github.com/golang/mock/gomock/call.go +++ b/vendor/go.uber.org/mock/gomock/call.go @@ -25,7 +25,7 @@ import ( type Call struct { t TestHelper // for triggering test failures on invalid call setup - receiver interface{} // the receiver of the method call + receiver any // the receiver of the method call method string // the name of the method methodType reflect.Type // the type of the method args []Matcher // the args @@ -41,12 +41,12 @@ type Call struct { // actions are called when this Call is called. Each action gets the args and // can set the return values by returning a non-nil slice. Actions run in the // order they are created. - actions []func([]interface{}) []interface{} + actions []func([]any) []any } // newCall creates a *Call. It requires the method type in order to support // unexported methods. -func newCall(t TestHelper, receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call { +func newCall(t TestHelper, receiver any, method string, methodType reflect.Type, args ...any) *Call { t.Helper() // TODO: check arity, types. @@ -67,9 +67,9 @@ func newCall(t TestHelper, receiver interface{}, method string, methodType refle // and this line changes, i.e. this code is wrapped in another anonymous function. // 0 is us, 1 is RecordCallWithMethodType(), 2 is the generated recorder, and 3 is the user's test. origin := callerInfo(3) - actions := []func([]interface{}) []interface{}{func([]interface{}) []interface{} { + actions := []func([]any) []any{func([]any) []any { // Synthesize the zero value for each of the return args' types. - rets := make([]interface{}, methodType.NumOut()) + rets := make([]any, methodType.NumOut()) for i := 0; i < methodType.NumOut(); i++ { rets[i] = reflect.Zero(methodType.Out(i)).Interface() } @@ -107,20 +107,26 @@ func (c *Call) MaxTimes(n int) *Call { // DoAndReturn declares the action to run when the call is matched. // The return values from this function are returned by the mocked function. -// It takes an interface{} argument to support n-arity functions. -func (c *Call) DoAndReturn(f interface{}) *Call { +// It takes an any argument to support n-arity functions. +// The anonymous function must match the function signature mocked method. +func (c *Call) DoAndReturn(f any) *Call { // TODO: Check arity and types here, rather than dying badly elsewhere. v := reflect.ValueOf(f) - c.addAction(func(args []interface{}) []interface{} { + c.addAction(func(args []any) []any { c.t.Helper() - vArgs := make([]reflect.Value, len(args)) ft := v.Type() if c.methodType.NumIn() != ft.NumIn() { - c.t.Fatalf("wrong number of arguments in DoAndReturn func for %T.%v: got %d, want %d [%s]", - c.receiver, c.method, ft.NumIn(), c.methodType.NumIn(), c.origin) + if ft.IsVariadic() { + c.t.Fatalf("wrong number of arguments in DoAndReturn func for %T.%v The function signature must match the mocked method, a variadic function cannot be used.", + c.receiver, c.method) + } else { + c.t.Fatalf("wrong number of arguments in DoAndReturn func for %T.%v: got %d, want %d [%s]", + c.receiver, c.method, ft.NumIn(), c.methodType.NumIn(), c.origin) + } return nil } + vArgs := make([]reflect.Value, len(args)) for i := 0; i < len(args); i++ { if args[i] != nil { vArgs[i] = reflect.ValueOf(args[i]) @@ -130,7 +136,7 @@ func (c *Call) DoAndReturn(f interface{}) *Call { } } vRets := v.Call(vArgs) - rets := make([]interface{}, len(vRets)) + rets := make([]any, len(vRets)) for i, ret := range vRets { rets[i] = ret.Interface() } @@ -142,20 +148,26 @@ func (c *Call) DoAndReturn(f interface{}) *Call { // Do declares the action to run when the call is matched. The function's // return values are ignored to retain backward compatibility. To use the // return values call DoAndReturn. -// It takes an interface{} argument to support n-arity functions. -func (c *Call) Do(f interface{}) *Call { +// It takes an any argument to support n-arity functions. +// The anonymous function must match the function signature mocked method. +func (c *Call) Do(f any) *Call { // TODO: Check arity and types here, rather than dying badly elsewhere. v := reflect.ValueOf(f) - c.addAction(func(args []interface{}) []interface{} { + c.addAction(func(args []any) []any { c.t.Helper() - if c.methodType.NumIn() != v.Type().NumIn() { - c.t.Fatalf("wrong number of arguments in Do func for %T.%v: got %d, want %d [%s]", - c.receiver, c.method, v.Type().NumIn(), c.methodType.NumIn(), c.origin) + ft := v.Type() + if c.methodType.NumIn() != ft.NumIn() { + if ft.IsVariadic() { + c.t.Fatalf("wrong number of arguments in Do func for %T.%v The function signature must match the mocked method, a variadic function cannot be used.", + c.receiver, c.method) + } else { + c.t.Fatalf("wrong number of arguments in Do func for %T.%v: got %d, want %d [%s]", + c.receiver, c.method, ft.NumIn(), c.methodType.NumIn(), c.origin) + } return nil } vArgs := make([]reflect.Value, len(args)) - ft := v.Type() for i := 0; i < len(args); i++ { if args[i] != nil { vArgs[i] = reflect.ValueOf(args[i]) @@ -171,7 +183,7 @@ func (c *Call) Do(f interface{}) *Call { } // Return declares the values to be returned by the mocked function call. -func (c *Call) Return(rets ...interface{}) *Call { +func (c *Call) Return(rets ...any) *Call { c.t.Helper() mt := c.methodType @@ -203,7 +215,7 @@ func (c *Call) Return(rets ...interface{}) *Call { } } - c.addAction(func([]interface{}) []interface{} { + c.addAction(func([]any) []any { return rets }) @@ -217,9 +229,9 @@ func (c *Call) Times(n int) *Call { } // SetArg declares an action that will set the nth argument's value, -// indirected through a pointer. Or, in the case of a slice, SetArg -// will copy value's elements into the nth argument. -func (c *Call) SetArg(n int, value interface{}) *Call { +// indirected through a pointer. Or, in the case of a slice and map, SetArg +// will copy value's elements/key-value pairs into the nth argument. +func (c *Call) SetArg(n int, value any) *Call { c.t.Helper() mt := c.methodType @@ -243,16 +255,20 @@ func (c *Call) SetArg(n int, value interface{}) *Call { // nothing to do case reflect.Slice: // nothing to do + case reflect.Map: + // nothing to do default: - c.t.Fatalf("SetArg(%d, ...) referring to argument of non-pointer non-interface non-slice type %v [%s]", + c.t.Fatalf("SetArg(%d, ...) referring to argument of non-pointer non-interface non-slice non-map type %v [%s]", n, at, c.origin) } - c.addAction(func(args []interface{}) []interface{} { + c.addAction(func(args []any) []any { v := reflect.ValueOf(value) switch reflect.TypeOf(args[n]).Kind() { case reflect.Slice: setSlice(args[n], v) + case reflect.Map: + setMap(args[n], v) default: reflect.ValueOf(args[n]).Elem().Set(v) } @@ -307,7 +323,7 @@ func (c *Call) String() string { // Tests if the given call matches the expected call. // If yes, returns nil. If no, returns error with message explaining why it does not match. -func (c *Call) matches(args []interface{}) error { +func (c *Call) matches(args []any) error { if !c.methodType.IsVariadic() { if len(args) != len(c.args) { return fmt.Errorf("expected call at %s has the wrong number of arguments. Got: %d, want: %d", @@ -413,30 +429,77 @@ func (c *Call) dropPrereqs() (preReqs []*Call) { return } -func (c *Call) call() []func([]interface{}) []interface{} { +func (c *Call) call() []func([]any) []any { c.numCalls++ return c.actions } // InOrder declares that the given calls should occur in order. -func InOrder(calls ...*Call) { +// It panics if the type of any of the arguments isn't *Call or a generated +// mock with an embedded *Call. +func InOrder(args ...any) { + calls := make([]*Call, 0, len(args)) + for i := 0; i < len(args); i++ { + if call := getCall(args[i]); call != nil { + calls = append(calls, call) + continue + } + panic(fmt.Sprintf( + "invalid argument at position %d of type %T, InOrder expects *gomock.Call or generated mock types with an embedded *gomock.Call", + i, + args[i], + )) + } for i := 1; i < len(calls); i++ { calls[i].After(calls[i-1]) } } -func setSlice(arg interface{}, v reflect.Value) { +// getCall checks if the parameter is a *Call or a generated struct +// that wraps a *Call and returns the *Call pointer - if neither, it returns nil. +func getCall(arg any) *Call { + if call, ok := arg.(*Call); ok { + return call + } + t := reflect.ValueOf(arg) + if t.Kind() != reflect.Ptr && t.Kind() != reflect.Interface { + return nil + } + t = t.Elem() + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + if !f.CanInterface() { + continue + } + if call, ok := f.Interface().(*Call); ok { + return call + } + } + return nil +} + +func setSlice(arg any, v reflect.Value) { va := reflect.ValueOf(arg) for i := 0; i < v.Len(); i++ { va.Index(i).Set(v.Index(i)) } } -func (c *Call) addAction(action func([]interface{}) []interface{}) { +func setMap(arg any, v reflect.Value) { + va := reflect.ValueOf(arg) + for _, e := range va.MapKeys() { + va.SetMapIndex(e, reflect.Value{}) + } + for _, e := range v.MapKeys() { + va.SetMapIndex(e, v.MapIndex(e)) + } +} + +func (c *Call) addAction(action func([]any) []any) { c.actions = append(c.actions, action) } -func formatGottenArg(m Matcher, arg interface{}) string { +func formatGottenArg(m Matcher, arg any) string { got := fmt.Sprintf("%v (%T)", arg, arg) if gs, ok := m.(GotFormatter); ok { got = gs.Got(arg) diff --git a/vendor/github.com/golang/mock/gomock/callset.go b/vendor/go.uber.org/mock/gomock/callset.go similarity index 70% rename from vendor/github.com/golang/mock/gomock/callset.go rename to vendor/go.uber.org/mock/gomock/callset.go index 49dba787a4..f5cc592d6f 100644 --- a/vendor/github.com/golang/mock/gomock/callset.go +++ b/vendor/go.uber.org/mock/gomock/callset.go @@ -18,40 +18,69 @@ import ( "bytes" "errors" "fmt" + "sync" ) // callSet represents a set of expected calls, indexed by receiver and method // name. type callSet struct { // Calls that are still expected. - expected map[callSetKey][]*Call + expected map[callSetKey][]*Call + expectedMu *sync.Mutex // Calls that have been exhausted. exhausted map[callSetKey][]*Call + // when set to true, existing call expectations are overridden when new call expectations are made + allowOverride bool } // callSetKey is the key in the maps in callSet type callSetKey struct { - receiver interface{} + receiver any fname string } func newCallSet() *callSet { - return &callSet{make(map[callSetKey][]*Call), make(map[callSetKey][]*Call)} + return &callSet{ + expected: make(map[callSetKey][]*Call), + expectedMu: &sync.Mutex{}, + exhausted: make(map[callSetKey][]*Call), + } +} + +func newOverridableCallSet() *callSet { + return &callSet{ + expected: make(map[callSetKey][]*Call), + expectedMu: &sync.Mutex{}, + exhausted: make(map[callSetKey][]*Call), + allowOverride: true, + } } // Add adds a new expected call. func (cs callSet) Add(call *Call) { key := callSetKey{call.receiver, call.method} + + cs.expectedMu.Lock() + defer cs.expectedMu.Unlock() + m := cs.expected if call.exhausted() { m = cs.exhausted } + if cs.allowOverride { + m[key] = make([]*Call, 0) + } + m[key] = append(m[key], call) } // Remove removes an expected call. func (cs callSet) Remove(call *Call) { key := callSetKey{call.receiver, call.method} + + cs.expectedMu.Lock() + defer cs.expectedMu.Unlock() + calls := cs.expected[key] for i, c := range calls { if c == call { @@ -64,9 +93,12 @@ func (cs callSet) Remove(call *Call) { } // FindMatch searches for a matching call. Returns error with explanation message if no call matched. -func (cs callSet) FindMatch(receiver interface{}, method string, args []interface{}) (*Call, error) { +func (cs callSet) FindMatch(receiver any, method string, args []any) (*Call, error) { key := callSetKey{receiver, method} + cs.expectedMu.Lock() + defer cs.expectedMu.Unlock() + // Search through the expected calls. expected := cs.expected[key] var callsErrors bytes.Buffer @@ -101,6 +133,9 @@ func (cs callSet) FindMatch(receiver interface{}, method string, args []interfac // Failures returns the calls that are not satisfied. func (cs callSet) Failures() []*Call { + cs.expectedMu.Lock() + defer cs.expectedMu.Unlock() + failures := make([]*Call, 0, len(cs.expected)) for _, calls := range cs.expected { for _, call := range calls { @@ -111,3 +146,19 @@ func (cs callSet) Failures() []*Call { } return failures } + +// Satisfied returns true in case all expected calls in this callSet are satisfied. +func (cs callSet) Satisfied() bool { + cs.expectedMu.Lock() + defer cs.expectedMu.Unlock() + + for _, calls := range cs.expected { + for _, call := range calls { + if !call.satisfied() { + return false + } + } + } + + return true +} diff --git a/vendor/github.com/golang/mock/gomock/controller.go b/vendor/go.uber.org/mock/gomock/controller.go similarity index 67% rename from vendor/github.com/golang/mock/gomock/controller.go rename to vendor/go.uber.org/mock/gomock/controller.go index f054200d56..6846d0d053 100644 --- a/vendor/github.com/golang/mock/gomock/controller.go +++ b/vendor/go.uber.org/mock/gomock/controller.go @@ -12,44 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -// Package gomock is a mock framework for Go. -// -// Standard usage: -// (1) Define an interface that you wish to mock. -// type MyInterface interface { -// SomeMethod(x int64, y string) -// } -// (2) Use mockgen to generate a mock from the interface. -// (3) Use the mock in a test: -// func TestMyThing(t *testing.T) { -// mockCtrl := gomock.NewController(t) -// defer mockCtrl.Finish() -// -// mockObj := something.NewMockMyInterface(mockCtrl) -// mockObj.EXPECT().SomeMethod(4, "blah") -// // pass mockObj to a real object and play with it. -// } -// -// By default, expected calls are not enforced to run in any particular order. -// Call order dependency can be enforced by use of InOrder and/or Call.After. -// Call.After can create more varied call order dependencies, but InOrder is -// often more convenient. -// -// The following examples create equivalent call order dependencies. -// -// Example of using Call.After to chain expected call order: -// -// firstCall := mockObj.EXPECT().SomeMethod(1, "first") -// secondCall := mockObj.EXPECT().SomeMethod(2, "second").After(firstCall) -// mockObj.EXPECT().SomeMethod(3, "third").After(secondCall) -// -// Example of using InOrder to declare expected call order: -// -// gomock.InOrder( -// mockObj.EXPECT().SomeMethod(1, "first"), -// mockObj.EXPECT().SomeMethod(2, "second"), -// mockObj.EXPECT().SomeMethod(3, "third"), -// ) package gomock import ( @@ -63,8 +25,8 @@ import ( // A TestReporter is something that can be used to report test failures. It // is satisfied by the standard library's *testing.T. type TestReporter interface { - Errorf(format string, args ...interface{}) - Fatalf(format string, args ...interface{}) + Errorf(format string, args ...any) + Fatalf(format string, args ...any) } // TestHelper is a TestReporter that has the Helper method. It is satisfied @@ -89,24 +51,21 @@ type cleanuper interface { // goroutines. Each test should create a new Controller and invoke Finish via // defer. // -// func TestFoo(t *testing.T) { -// ctrl := gomock.NewController(t) -// defer ctrl.Finish() -// // .. -// } +// func TestFoo(t *testing.T) { +// ctrl := gomock.NewController(t) +// // .. +// } // -// func TestBar(t *testing.T) { -// t.Run("Sub-Test-1", st) { -// ctrl := gomock.NewController(st) -// defer ctrl.Finish() -// // .. -// }) -// t.Run("Sub-Test-2", st) { -// ctrl := gomock.NewController(st) -// defer ctrl.Finish() -// // .. -// }) -// }) +// func TestBar(t *testing.T) { +// t.Run("Sub-Test-1", st) { +// ctrl := gomock.NewController(st) +// // .. +// }) +// t.Run("Sub-Test-2", st) { +// ctrl := gomock.NewController(st) +// // .. +// }) +// }) type Controller struct { // T should only be called within a generated mock. It is not intended to // be used in user code and may be changed in future versions. T is the @@ -119,12 +78,11 @@ type Controller struct { finished bool } -// NewController returns a new Controller. It is the preferred way to create a -// Controller. +// NewController returns a new Controller. It is the preferred way to create a Controller. // -// New in go1.14+, if you are passing a *testing.T into this function you no -// longer need to call ctrl.Finish() in your test methods. -func NewController(t TestReporter) *Controller { +// Passing [*testing.T] registers cleanup function to automatically call [Controller.Finish] +// when the test and all its subtests complete. +func NewController(t TestReporter, opts ...ControllerOption) *Controller { h, ok := t.(TestHelper) if !ok { h = &nopTestHelper{t} @@ -133,6 +91,9 @@ func NewController(t TestReporter) *Controller { T: h, expectedCalls: newCallSet(), } + for _, opt := range opts { + opt.apply(ctrl) + } if c, ok := isCleanuper(ctrl.T); ok { c.Cleanup(func() { ctrl.T.Helper() @@ -143,15 +104,32 @@ func NewController(t TestReporter) *Controller { return ctrl } +// ControllerOption configures how a Controller should behave. +type ControllerOption interface { + apply(*Controller) +} + +type overridableExpectationsOption struct{} + +// WithOverridableExpectations allows for overridable call expectations +// i.e., subsequent call expectations override existing call expectations +func WithOverridableExpectations() overridableExpectationsOption { + return overridableExpectationsOption{} +} + +func (o overridableExpectationsOption) apply(ctrl *Controller) { + ctrl.expectedCalls = newOverridableCallSet() +} + type cancelReporter struct { t TestHelper cancel func() } -func (r *cancelReporter) Errorf(format string, args ...interface{}) { +func (r *cancelReporter) Errorf(format string, args ...any) { r.t.Errorf(format, args...) } -func (r *cancelReporter) Fatalf(format string, args ...interface{}) { +func (r *cancelReporter) Fatalf(format string, args ...any) { defer r.cancel() r.t.Fatalf(format, args...) } @@ -176,17 +154,17 @@ type nopTestHelper struct { t TestReporter } -func (h *nopTestHelper) Errorf(format string, args ...interface{}) { +func (h *nopTestHelper) Errorf(format string, args ...any) { h.t.Errorf(format, args...) } -func (h *nopTestHelper) Fatalf(format string, args ...interface{}) { +func (h *nopTestHelper) Fatalf(format string, args ...any) { h.t.Fatalf(format, args...) } func (h nopTestHelper) Helper() {} // RecordCall is called by a mock. It should not be called by user code. -func (ctrl *Controller) RecordCall(receiver interface{}, method string, args ...interface{}) *Call { +func (ctrl *Controller) RecordCall(receiver any, method string, args ...any) *Call { ctrl.T.Helper() recv := reflect.ValueOf(receiver) @@ -200,7 +178,7 @@ func (ctrl *Controller) RecordCall(receiver interface{}, method string, args ... } // RecordCallWithMethodType is called by a mock. It should not be called by user code. -func (ctrl *Controller) RecordCallWithMethodType(receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call { +func (ctrl *Controller) RecordCallWithMethodType(receiver any, method string, methodType reflect.Type, args ...any) *Call { ctrl.T.Helper() call := newCall(ctrl.T, receiver, method, methodType, args...) @@ -213,11 +191,11 @@ func (ctrl *Controller) RecordCallWithMethodType(receiver interface{}, method st } // Call is called by a mock. It should not be called by user code. -func (ctrl *Controller) Call(receiver interface{}, method string, args ...interface{}) []interface{} { +func (ctrl *Controller) Call(receiver any, method string, args ...any) []any { ctrl.T.Helper() // Nest this code so we can use defer to make sure the lock is released. - actions := func() []func([]interface{}) []interface{} { + actions := func() []func([]any) []any { ctrl.T.Helper() ctrl.mu.Lock() defer ctrl.mu.Unlock() @@ -246,7 +224,7 @@ func (ctrl *Controller) Call(receiver interface{}, method string, args ...interf return actions }() - var rets []interface{} + var rets []any for _, action := range actions { if r := action(args); r != nil { rets = r @@ -256,12 +234,8 @@ func (ctrl *Controller) Call(receiver interface{}, method string, args ...interf return rets } -// Finish checks to see if all the methods that were expected to be called -// were called. It should be invoked for each Controller. It is not idempotent -// and therefore can only be invoked once. -// -// New in go1.14+, if you are passing a *testing.T into NewController function you no -// longer need to call ctrl.Finish() in your test methods. +// Finish checks to see if all the methods that were expected to be called were called. +// It is not idempotent and therefore can only be invoked once. func (ctrl *Controller) Finish() { // If we're currently panicking, probably because this is a deferred call. // This must be recovered in the deferred function. @@ -269,7 +243,13 @@ func (ctrl *Controller) Finish() { ctrl.finish(false, err) } -func (ctrl *Controller) finish(cleanup bool, panicErr interface{}) { +// Satisfied returns whether all expected calls bound to this Controller have been satisfied. +// Calling Finish is then guaranteed to not fail due to missing calls. +func (ctrl *Controller) Satisfied() bool { + return ctrl.expectedCalls.Satisfied() +} + +func (ctrl *Controller) finish(cleanup bool, panicErr any) { ctrl.T.Helper() ctrl.mu.Lock() diff --git a/vendor/go.uber.org/mock/gomock/doc.go b/vendor/go.uber.org/mock/gomock/doc.go new file mode 100644 index 0000000000..696dda3882 --- /dev/null +++ b/vendor/go.uber.org/mock/gomock/doc.go @@ -0,0 +1,60 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package gomock is a mock framework for Go. +// +// Standard usage: +// +// (1) Define an interface that you wish to mock. +// type MyInterface interface { +// SomeMethod(x int64, y string) +// } +// (2) Use mockgen to generate a mock from the interface. +// (3) Use the mock in a test: +// func TestMyThing(t *testing.T) { +// mockCtrl := gomock.NewController(t) +// mockObj := something.NewMockMyInterface(mockCtrl) +// mockObj.EXPECT().SomeMethod(4, "blah") +// // pass mockObj to a real object and play with it. +// } +// +// By default, expected calls are not enforced to run in any particular order. +// Call order dependency can be enforced by use of InOrder and/or Call.After. +// Call.After can create more varied call order dependencies, but InOrder is +// often more convenient. +// +// The following examples create equivalent call order dependencies. +// +// Example of using Call.After to chain expected call order: +// +// firstCall := mockObj.EXPECT().SomeMethod(1, "first") +// secondCall := mockObj.EXPECT().SomeMethod(2, "second").After(firstCall) +// mockObj.EXPECT().SomeMethod(3, "third").After(secondCall) +// +// Example of using InOrder to declare expected call order: +// +// gomock.InOrder( +// mockObj.EXPECT().SomeMethod(1, "first"), +// mockObj.EXPECT().SomeMethod(2, "second"), +// mockObj.EXPECT().SomeMethod(3, "third"), +// ) +// +// The standard TestReporter most users will pass to `NewController` is a +// `*testing.T` from the context of the test. Note that this will use the +// standard `t.Error` and `t.Fatal` methods to report what happened in the test. +// In some cases this can leave your testing package in a weird state if global +// state is used since `t.Fatal` is like calling panic in the middle of a +// function. In these cases it is recommended that you pass in your own +// `TestReporter`. +package gomock diff --git a/vendor/github.com/golang/mock/gomock/matchers.go b/vendor/go.uber.org/mock/gomock/matchers.go similarity index 76% rename from vendor/github.com/golang/mock/gomock/matchers.go rename to vendor/go.uber.org/mock/gomock/matchers.go index 2822fb2c8c..bac4623b1f 100644 --- a/vendor/github.com/golang/mock/gomock/matchers.go +++ b/vendor/go.uber.org/mock/gomock/matchers.go @@ -24,7 +24,7 @@ import ( // It is used to represent the valid or expected arguments to a mocked method. type Matcher interface { // Matches returns whether x is a match. - Matches(x interface{}) bool + Matches(x any) bool // String describes what the matcher matches. String() string @@ -35,7 +35,7 @@ type Matcher interface { // printing . func WantFormatter(s fmt.Stringer, m Matcher) Matcher { type matcher interface { - Matches(x interface{}) bool + Matches(x any) bool } return struct { @@ -63,16 +63,16 @@ func (f StringerFunc) String() string { type GotFormatter interface { // Got is invoked with the received value. The result is used when // printing the failure message. - Got(got interface{}) string + Got(got any) string } // GotFormatterFunc type is an adapter to allow the use of ordinary // functions as a GotFormatter. If f is a function with the appropriate // signature, GotFormatterFunc(f) is a GotFormatter that calls f. -type GotFormatterFunc func(got interface{}) string +type GotFormatterFunc func(got any) string // Got implements GotFormatter. -func (f GotFormatterFunc) Got(got interface{}) string { +func (f GotFormatterFunc) Got(got any) string { return f(got) } @@ -89,7 +89,7 @@ func GotFormatterAdapter(s GotFormatter, m Matcher) Matcher { type anyMatcher struct{} -func (anyMatcher) Matches(interface{}) bool { +func (anyMatcher) Matches(any) bool { return true } @@ -97,11 +97,23 @@ func (anyMatcher) String() string { return "is anything" } +type condMatcher struct { + fn func(x any) bool +} + +func (c condMatcher) Matches(x any) bool { + return c.fn(x) +} + +func (condMatcher) String() string { + return "adheres to a custom condition" +} + type eqMatcher struct { - x interface{} + x any } -func (e eqMatcher) Matches(x interface{}) bool { +func (e eqMatcher) Matches(x any) bool { // In case, some value is nil if e.x == nil || x == nil { return reflect.DeepEqual(e.x, x) @@ -125,7 +137,7 @@ func (e eqMatcher) String() string { type nilMatcher struct{} -func (nilMatcher) Matches(x interface{}) bool { +func (nilMatcher) Matches(x any) bool { if x == nil { return true } @@ -148,7 +160,7 @@ type notMatcher struct { m Matcher } -func (n notMatcher) Matches(x interface{}) bool { +func (n notMatcher) Matches(x any) bool { return !n.m.Matches(x) } @@ -160,7 +172,7 @@ type assignableToTypeOfMatcher struct { targetType reflect.Type } -func (m assignableToTypeOfMatcher) Matches(x interface{}) bool { +func (m assignableToTypeOfMatcher) Matches(x any) bool { return reflect.TypeOf(x).AssignableTo(m.targetType) } @@ -172,7 +184,7 @@ type allMatcher struct { matchers []Matcher } -func (am allMatcher) Matches(x interface{}) bool { +func (am allMatcher) Matches(x any) bool { for _, m := range am.matchers { if !m.Matches(x) { return false @@ -193,7 +205,7 @@ type lenMatcher struct { i int } -func (m lenMatcher) Matches(x interface{}) bool { +func (m lenMatcher) Matches(x any) bool { v := reflect.ValueOf(x) switch v.Kind() { case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String: @@ -208,10 +220,10 @@ func (m lenMatcher) String() string { } type inAnyOrderMatcher struct { - x interface{} + x any } -func (m inAnyOrderMatcher) Matches(x interface{}) bool { +func (m inAnyOrderMatcher) Matches(x any) bool { given, ok := m.prepareValue(x) if !ok { return false @@ -257,7 +269,7 @@ func (m inAnyOrderMatcher) Matches(x interface{}) bool { return extraInGiven == 0 && missingFromWanted == 0 } -func (m inAnyOrderMatcher) prepareValue(x interface{}) (reflect.Value, bool) { +func (m inAnyOrderMatcher) prepareValue(x any) (reflect.Value, bool) { xValue := reflect.ValueOf(x) switch xValue.Kind() { case reflect.Slice, reflect.Array: @@ -280,12 +292,23 @@ func All(ms ...Matcher) Matcher { return allMatcher{ms} } // Any returns a matcher that always matches. func Any() Matcher { return anyMatcher{} } +// Cond returns a matcher that matches when the given function returns true +// after passing it the parameter to the mock function. +// This is particularly useful in case you want to match over a field of a custom struct, or dynamic logic. +// +// Example usage: +// +// Cond(func(x any){return x.(int) == 1}).Matches(1) // returns true +// Cond(func(x any){return x.(int) == 2}).Matches(1) // returns false +func Cond(fn func(x any) bool) Matcher { return condMatcher{fn} } + // Eq returns a matcher that matches on equality. // // Example usage: -// Eq(5).Matches(5) // returns true -// Eq(5).Matches(4) // returns false -func Eq(x interface{}) Matcher { return eqMatcher{x} } +// +// Eq(5).Matches(5) // returns true +// Eq(5).Matches(4) // returns false +func Eq(x any) Matcher { return eqMatcher{x} } // Len returns a matcher that matches on length. This matcher returns false if // is compared to a type that is not an array, chan, map, slice, or string. @@ -296,18 +319,20 @@ func Len(i int) Matcher { // Nil returns a matcher that matches if the received value is nil. // // Example usage: -// var x *bytes.Buffer -// Nil().Matches(x) // returns true -// x = &bytes.Buffer{} -// Nil().Matches(x) // returns false +// +// var x *bytes.Buffer +// Nil().Matches(x) // returns true +// x = &bytes.Buffer{} +// Nil().Matches(x) // returns false func Nil() Matcher { return nilMatcher{} } // Not reverses the results of its given child matcher. // // Example usage: -// Not(Eq(5)).Matches(4) // returns true -// Not(Eq(5)).Matches(5) // returns false -func Not(x interface{}) Matcher { +// +// Not(Eq(5)).Matches(4) // returns true +// Not(Eq(5)).Matches(5) // returns false +func Not(x any) Matcher { if m, ok := x.(Matcher); ok { return notMatcher{m} } @@ -318,13 +343,14 @@ func Not(x interface{}) Matcher { // function is assignable to the type of the parameter to this function. // // Example usage: -// var s fmt.Stringer = &bytes.Buffer{} -// AssignableToTypeOf(s).Matches(time.Second) // returns true -// AssignableToTypeOf(s).Matches(99) // returns false // -// var ctx = reflect.TypeOf((*context.Context)(nil)).Elem() -// AssignableToTypeOf(ctx).Matches(context.Background()) // returns true -func AssignableToTypeOf(x interface{}) Matcher { +// var s fmt.Stringer = &bytes.Buffer{} +// AssignableToTypeOf(s).Matches(time.Second) // returns true +// AssignableToTypeOf(s).Matches(99) // returns false +// +// var ctx = reflect.TypeOf((*context.Context)(nil)).Elem() +// AssignableToTypeOf(ctx).Matches(context.Background()) // returns true +func AssignableToTypeOf(x any) Matcher { if xt, ok := x.(reflect.Type); ok { return assignableToTypeOfMatcher{xt} } @@ -334,8 +360,9 @@ func AssignableToTypeOf(x interface{}) Matcher { // InAnyOrder is a Matcher that returns true for collections of the same elements ignoring the order. // // Example usage: -// InAnyOrder([]int{1, 2, 3}).Matches([]int{1, 3, 2}) // returns true -// InAnyOrder([]int{1, 2, 3}).Matches([]int{1, 2}) // returns false -func InAnyOrder(x interface{}) Matcher { +// +// InAnyOrder([]int{1, 2, 3}).Matches([]int{1, 3, 2}) // returns true +// InAnyOrder([]int{1, 2, 3}).Matches([]int{1, 2}) // returns false +func InAnyOrder(x any) Matcher { return inAnyOrderMatcher{x} } diff --git a/vendor/go.uber.org/mock/mockgen/generic_go118.go b/vendor/go.uber.org/mock/mockgen/generic_go118.go new file mode 100644 index 0000000000..635402dc50 --- /dev/null +++ b/vendor/go.uber.org/mock/mockgen/generic_go118.go @@ -0,0 +1,116 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build go1.18 +// +build go1.18 + +package main + +import ( + "fmt" + "go/ast" + "strings" + + "go.uber.org/mock/mockgen/model" +) + +func getTypeSpecTypeParams(ts *ast.TypeSpec) []*ast.Field { + if ts == nil || ts.TypeParams == nil { + return nil + } + return ts.TypeParams.List +} + +func (p *fileParser) parseGenericType(pkg string, typ ast.Expr, tps map[string]model.Type) (model.Type, error) { + switch v := typ.(type) { + case *ast.IndexExpr: + m, err := p.parseType(pkg, v.X, tps) + if err != nil { + return nil, err + } + nm, ok := m.(*model.NamedType) + if !ok { + return m, nil + } + t, err := p.parseType(pkg, v.Index, tps) + if err != nil { + return nil, err + } + nm.TypeParams = &model.TypeParametersType{TypeParameters: []model.Type{t}} + return m, nil + case *ast.IndexListExpr: + m, err := p.parseType(pkg, v.X, tps) + if err != nil { + return nil, err + } + nm, ok := m.(*model.NamedType) + if !ok { + return m, nil + } + var ts []model.Type + for _, expr := range v.Indices { + t, err := p.parseType(pkg, expr, tps) + if err != nil { + return nil, err + } + ts = append(ts, t) + } + nm.TypeParams = &model.TypeParametersType{TypeParameters: ts} + return m, nil + } + return nil, nil +} + +func getIdentTypeParams(decl any) string { + if decl == nil { + return "" + } + ts, ok := decl.(*ast.TypeSpec) + if !ok { + return "" + } + if ts.TypeParams == nil || len(ts.TypeParams.List) == 0 { + return "" + } + var sb strings.Builder + sb.WriteString("[") + for i, v := range ts.TypeParams.List { + if i != 0 { + sb.WriteString(", ") + } + sb.WriteString(v.Names[0].Name) + } + sb.WriteString("]") + return sb.String() +} + +func (p *fileParser) parseGenericMethod(field *ast.Field, it *namedInterface, iface *model.Interface, pkg string, tps map[string]model.Type) ([]*model.Method, error) { + var indices []ast.Expr + var typ ast.Expr + switch v := field.Type.(type) { + case *ast.IndexExpr: + indices = []ast.Expr{v.Index} + typ = v.X + case *ast.IndexListExpr: + indices = v.Indices + typ = v.X + default: + return nil, fmt.Errorf("don't know how to mock method of type %T", field.Type) + } + + nf := &ast.Field{ + Doc: field.Comment, + Names: field.Names, + Type: typ, + Tag: field.Tag, + Comment: field.Comment, + } + + it.embeddedInstTypeParams = indices + + return p.parseMethod(nf, it, iface, pkg, tps) +} diff --git a/vendor/go.uber.org/mock/mockgen/generic_notgo118.go b/vendor/go.uber.org/mock/mockgen/generic_notgo118.go new file mode 100644 index 0000000000..8a779c8b2d --- /dev/null +++ b/vendor/go.uber.org/mock/mockgen/generic_notgo118.go @@ -0,0 +1,41 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build !go1.18 +// +build !go1.18 + +package main + +import ( + "fmt" + "go/ast" + + "go.uber.org/mock/mockgen/model" +) + +func getTypeSpecTypeParams(ts *ast.TypeSpec) []*ast.Field { + return nil +} + +func (p *fileParser) parseGenericType(pkg string, typ ast.Expr, tps map[string]model.Type) (model.Type, error) { + return nil, nil +} + +func getIdentTypeParams(decl any) string { + return "" +} + +func (p *fileParser) parseGenericMethod(field *ast.Field, it *namedInterface, iface *model.Interface, pkg string, tps map[string]model.Type) ([]*model.Method, error) { + return nil, fmt.Errorf("don't know how to mock method of type %T", field.Type) +} diff --git a/vendor/github.com/golang/mock/mockgen/mockgen.go b/vendor/go.uber.org/mock/mockgen/mockgen.go similarity index 64% rename from vendor/github.com/golang/mock/mockgen/mockgen.go rename to vendor/go.uber.org/mock/mockgen/mockgen.go index 50487070e3..feb747fac5 100644 --- a/vendor/github.com/golang/mock/mockgen/mockgen.go +++ b/vendor/go.uber.org/mock/mockgen/mockgen.go @@ -21,11 +21,11 @@ package main import ( "bytes" "encoding/json" + "errors" "flag" "fmt" "go/token" "io" - "io/ioutil" "log" "os" "os/exec" @@ -36,14 +36,14 @@ import ( "strings" "unicode" - "github.com/golang/mock/mockgen/model" - "golang.org/x/mod/modfile" toolsimports "golang.org/x/tools/imports" + + "go.uber.org/mock/mockgen/model" ) const ( - gomockImportPath = "github.com/golang/mock/gomock" + gomockImportPath = "go.uber.org/mock/gomock" ) var ( @@ -53,13 +53,19 @@ var ( ) var ( - source = flag.String("source", "", "(source mode) Input Go source file; enables source mode.") - destination = flag.String("destination", "", "Output file; defaults to stdout.") - mockNames = flag.String("mock_names", "", "Comma-separated interfaceName=mockName pairs of explicit mock names to use. Mock names default to 'Mock'+ interfaceName suffix.") - packageOut = flag.String("package", "", "Package of the generated code; defaults to the package of the input with a 'mock_' prefix.") - selfPackage = flag.String("self_package", "", "The full package import path for the generated code. The purpose of this flag is to prevent import cycles in the generated code by trying to include its own package. This can happen if the mock's package is set to one of its inputs (usually the main one) and the output is stdio so mockgen cannot detect the final output package. Setting this flag will then tell mockgen which import to exclude.") - writePkgComment = flag.Bool("write_package_comment", true, "Writes package documentation comment (godoc) if true.") - copyrightFile = flag.String("copyright_file", "", "Copyright file used to add copyright header") + source = flag.String("source", "", "(source mode) Input Go source file; enables source mode.") + destination = flag.String("destination", "", "Output file; defaults to stdout.") + mockNames = flag.String("mock_names", "", "Comma-separated interfaceName=mockName pairs of explicit mock names to use. Mock names default to 'Mock'+ interfaceName suffix.") + packageOut = flag.String("package", "", "Package of the generated code; defaults to the package of the input with a 'mock_' prefix.") + selfPackage = flag.String("self_package", "", "The full package import path for the generated code. The purpose of this flag is to prevent import cycles in the generated code by trying to include its own package. This can happen if the mock's package is set to one of its inputs (usually the main one) and the output is stdio so mockgen cannot detect the final output package. Setting this flag will then tell mockgen which import to exclude.") + writePkgComment = flag.Bool("write_package_comment", true, "Writes package documentation comment (godoc) if true.") + writeSourceComment = flag.Bool("write_source_comment", true, "Writes original file (source mode) or interface names (reflect mode) comment if true.") + writeGenerateDirective = flag.Bool("write_generate_directive", false, "Add //go:generate directive to regenerate the mock") + copyrightFile = flag.String("copyright_file", "", "Copyright file used to add copyright header") + typed = flag.Bool("typed", false, "Generate Type-safe 'Return', 'Do', 'DoAndReturn' function") + imports = flag.String("imports", "", "(source mode) Comma-separated name=path pairs of explicit imports to use.") + auxFiles = flag.String("aux_files", "", "(source mode) Comma-separated pkg=path pairs of auxiliary Go source files.") + excludeInterfaces = flag.String("exclude_interfaces", "", "Comma-separated names of interfaces to be excluded") debugParser = flag.Bool("debug_parser", false, "Print out parser results only.") showVersion = flag.Bool("version", false, "Print version.") @@ -107,19 +113,6 @@ func main() { return } - dst := os.Stdout - if len(*destination) > 0 { - if err := os.MkdirAll(filepath.Dir(*destination), os.ModePerm); err != nil { - log.Fatalf("Unable to create directory: %v", err) - } - f, err := os.Create(*destination) - if err != nil { - log.Fatalf("Failed opening destination file: %v", err) - } - defer f.Close() - dst = f - } - outputPackageName := *packageOut if outputPackageName == "" { // pkg.Name in reflect mode is the base name of the import path, @@ -161,7 +154,7 @@ func main() { g.mockNames = parseMockNames(*mockNames) } if *copyrightFile != "" { - header, err := ioutil.ReadFile(*copyrightFile) + header, err := os.ReadFile(*copyrightFile) if err != nil { log.Fatalf("Failed reading copyright file: %v", err) } @@ -171,7 +164,27 @@ func main() { if err := g.Generate(pkg, outputPackageName, outputPackagePath); err != nil { log.Fatalf("Failed generating mock: %v", err) } - if _, err := dst.Write(g.Output()); err != nil { + output := g.Output() + dst := os.Stdout + if len(*destination) > 0 { + if err := os.MkdirAll(filepath.Dir(*destination), os.ModePerm); err != nil { + log.Fatalf("Unable to create directory: %v", err) + } + existing, err := os.ReadFile(*destination) + if err != nil && !errors.Is(err, os.ErrNotExist) { + log.Fatalf("Failed reading pre-exiting destination file: %v", err) + } + if len(existing) == len(output) && bytes.Equal(existing, output) { + return + } + f, err := os.Create(*destination) + if err != nil { + log.Fatalf("Failed opening destination file: %v", err) + } + defer f.Close() + dst = f + } + if _, err := dst.Write(output); err != nil { log.Fatalf("Failed writing to destination: %v", err) } } @@ -188,6 +201,24 @@ func parseMockNames(names string) map[string]string { return mocksMap } +func parseExcludeInterfaces(names string) map[string]struct{} { + splitNames := strings.Split(names, ",") + namesSet := make(map[string]struct{}, len(splitNames)) + for _, name := range splitNames { + if name == "" { + continue + } + + namesSet[name] = struct{}{} + } + + if len(namesSet) == 0 { + return nil + } + + return namesSet +} + func usage() { _, _ = io.WriteString(os.Stderr, usageText) flag.PrintDefaults() @@ -222,7 +253,7 @@ type generator struct { packageMap map[string]string // map from import path to package name } -func (g *generator) p(format string, args ...interface{}) { +func (g *generator) p(format string, args ...any) { fmt.Fprintf(&g.buf, g.indent+format+"\n", args...) } @@ -274,12 +305,17 @@ func (g *generator) Generate(pkg *model.Package, outputPkgName string, outputPac } g.p("// Code generated by MockGen. DO NOT EDIT.") - if g.filename != "" { - g.p("// Source: %v", g.filename) - } else { - g.p("// Source: %v (interfaces: %v)", g.srcPackage, g.srcInterfaces) + if *writeSourceComment { + if g.filename != "" { + g.p("// Source: %v", g.filename) + } else { + g.p("// Source: %v (interfaces: %v)", g.srcPackage, g.srcInterfaces) + } } - g.p("") + g.p("//") + g.p("// Generated by this command:") + // only log the name of the executable, not the full path + g.p("// %v", strings.Join(append([]string{filepath.Base(os.Args[0])}, os.Args[1:]...), " ")) // Get all required imports, and generate unique names for them all. im := pkg.Imports() @@ -305,6 +341,16 @@ func (g *generator) Generate(pkg *model.Package, outputPkgName string, outputPac packagesName := createPackageMap(sortedPaths) + definedImports := make(map[string]string, len(im)) + if *imports != "" { + for _, kv := range strings.Split(*imports, ",") { + eq := strings.Index(kv, "=") + if k, v := kv[:eq], kv[eq+1:]; k != "." { + definedImports[v] = k + } + } + } + g.packageMap = make(map[string]string, len(im)) localNames := make(map[string]bool, len(im)) for _, pth := range sortedPaths { @@ -316,9 +362,14 @@ func (g *generator) Generate(pkg *model.Package, outputPkgName string, outputPac // Local names for an imported package can usually be the basename of the import path. // A couple of situations don't permit that, such as duplicate local names // (e.g. importing "html/template" and "text/template"), or where the basename is - // a keyword (e.g. "foo/case"). + // a keyword (e.g. "foo/case") or when defining a name for that by using the -imports flag. // try base0, base1, ... pkgName := base + + if _, ok := definedImports[base]; ok { + pkgName = definedImports[base] + } + i := 0 for localNames[pkgName] || token.Lookup(pkgName).IsKeyword() { pkgName = base + strconv.Itoa(i) @@ -353,6 +404,10 @@ func (g *generator) Generate(pkg *model.Package, outputPkgName string, outputPac g.out() g.p(")") + if *writeGenerateDirective { + g.p("//go:generate %v", strings.Join(os.Args, " ")) + } + for _, intf := range pkg.Interfaces { if err := g.GenerateMockInterface(intf, outputPackagePath); err != nil { return err @@ -371,32 +426,58 @@ func (g *generator) mockName(typeName string) string { return "Mock" + typeName } +// formattedTypeParams returns a long and short form of type param info used for +// printing. If analyzing a interface with type param [I any, O any] the result +// will be: +// "[I any, O any]", "[I, O]" +func (g *generator) formattedTypeParams(it *model.Interface, pkgOverride string) (string, string) { + if len(it.TypeParams) == 0 { + return "", "" + } + var long, short strings.Builder + long.WriteString("[") + short.WriteString("[") + for i, v := range it.TypeParams { + if i != 0 { + long.WriteString(", ") + short.WriteString(", ") + } + long.WriteString(v.Name) + short.WriteString(v.Name) + long.WriteString(fmt.Sprintf(" %s", v.Type.String(g.packageMap, pkgOverride))) + } + long.WriteString("]") + short.WriteString("]") + return long.String(), short.String() +} + func (g *generator) GenerateMockInterface(intf *model.Interface, outputPackagePath string) error { mockType := g.mockName(intf.Name) + longTp, shortTp := g.formattedTypeParams(intf, outputPackagePath) g.p("") g.p("// %v is a mock of %v interface.", mockType, intf.Name) - g.p("type %v struct {", mockType) + g.p("type %v%v struct {", mockType, longTp) g.in() g.p("ctrl *gomock.Controller") - g.p("recorder *%vMockRecorder", mockType) + g.p("recorder *%vMockRecorder%v", mockType, shortTp) g.out() g.p("}") g.p("") g.p("// %vMockRecorder is the mock recorder for %v.", mockType, mockType) - g.p("type %vMockRecorder struct {", mockType) + g.p("type %vMockRecorder%v struct {", mockType, longTp) g.in() - g.p("mock *%v", mockType) + g.p("mock *%v%v", mockType, shortTp) g.out() g.p("}") g.p("") g.p("// New%v creates a new mock instance.", mockType) - g.p("func New%v(ctrl *gomock.Controller) *%v {", mockType, mockType) + g.p("func New%v%v(ctrl *gomock.Controller) *%v%v {", mockType, longTp, mockType, shortTp) g.in() - g.p("mock := &%v{ctrl: ctrl}", mockType) - g.p("mock.recorder = &%vMockRecorder{mock}", mockType) + g.p("mock := &%v%v{ctrl: ctrl}", mockType, shortTp) + g.p("mock.recorder = &%vMockRecorder%v{mock}", mockType, shortTp) g.p("return mock") g.out() g.p("}") @@ -404,13 +485,13 @@ func (g *generator) GenerateMockInterface(intf *model.Interface, outputPackagePa // XXX: possible name collision here if someone has EXPECT in their interface. g.p("// EXPECT returns an object that allows the caller to indicate expected use.") - g.p("func (m *%v) EXPECT() *%vMockRecorder {", mockType, mockType) + g.p("func (m *%v%v) EXPECT() *%vMockRecorder%v {", mockType, shortTp, mockType, shortTp) g.in() g.p("return m.recorder") g.out() g.p("}") - g.GenerateMockMethods(mockType, intf, outputPackagePath) + g.GenerateMockMethods(mockType, intf, outputPackagePath, longTp, shortTp, *typed) return nil } @@ -421,13 +502,17 @@ func (b byMethodName) Len() int { return len(b) } func (b byMethodName) Swap(i, j int) { b[i], b[j] = b[j], b[i] } func (b byMethodName) Less(i, j int) bool { return b[i].Name < b[j].Name } -func (g *generator) GenerateMockMethods(mockType string, intf *model.Interface, pkgOverride string) { +func (g *generator) GenerateMockMethods(mockType string, intf *model.Interface, pkgOverride, longTp, shortTp string, typed bool) { sort.Sort(byMethodName(intf.Methods)) for _, m := range intf.Methods { g.p("") - _ = g.GenerateMockMethod(mockType, m, pkgOverride) + _ = g.GenerateMockMethod(mockType, m, pkgOverride, shortTp) g.p("") - _ = g.GenerateMockRecorderMethod(mockType, m) + _ = g.GenerateMockRecorderMethod(intf, mockType, m, shortTp, typed) + if typed { + g.p("") + _ = g.GenerateMockReturnCallMethod(intf, m, pkgOverride, longTp, shortTp) + } } } @@ -446,9 +531,9 @@ func makeArgString(argNames, argTypes []string) string { // GenerateMockMethod generates a mock method implementation. // If non-empty, pkgOverride is the package in which unqualified types reside. -func (g *generator) GenerateMockMethod(mockType string, m *model.Method, pkgOverride string) error { - argNames := g.getArgNames(m) - argTypes := g.getArgTypes(m, pkgOverride) +func (g *generator) GenerateMockMethod(mockType string, m *model.Method, pkgOverride, shortTp string) error { + argNames := g.getArgNames(m, true /* in */) + argTypes := g.getArgTypes(m, pkgOverride, true /* in */) argString := makeArgString(argNames, argTypes) rets := make([]string, len(m.Out)) @@ -467,7 +552,7 @@ func (g *generator) GenerateMockMethod(mockType string, m *model.Method, pkgOver idRecv := ia.allocateIdentifier("m") g.p("// %v mocks base method.", m.Name) - g.p("func (%v *%v) %v(%v)%v {", idRecv, mockType, m.Name, argString, retString) + g.p("func (%v *%v%v) %v(%v)%v {", idRecv, mockType, shortTp, m.Name, argString, retString) g.in() g.p("%s.ctrl.T.Helper()", idRecv) @@ -477,11 +562,11 @@ func (g *generator) GenerateMockMethod(mockType string, m *model.Method, pkgOver callArgs = ", " + strings.Join(argNames, ", ") } } else { - // Non-trivial. The generated code must build a []interface{}, + // Non-trivial. The generated code must build a []any, // but the variadic argument may be any type. idVarArgs := ia.allocateIdentifier("varargs") idVArg := ia.allocateIdentifier("a") - g.p("%s := []interface{}{%s}", idVarArgs, strings.Join(argNames[:len(argNames)-1], ", ")) + g.p("%s := []any{%s}", idVarArgs, strings.Join(argNames[:len(argNames)-1], ", ")) g.p("for _, %s := range %s {", idVArg, argNames[len(argNames)-1]) g.in() g.p("%s = append(%s, %s)", idVarArgs, idVarArgs, idVArg) @@ -511,8 +596,8 @@ func (g *generator) GenerateMockMethod(mockType string, m *model.Method, pkgOver return nil } -func (g *generator) GenerateMockRecorderMethod(mockType string, m *model.Method) error { - argNames := g.getArgNames(m) +func (g *generator) GenerateMockRecorderMethod(intf *model.Interface, mockType string, m *model.Method, shortTp string, typed bool) error { + argNames := g.getArgNames(m, true) var argString string if m.Variadic == nil { @@ -521,21 +606,26 @@ func (g *generator) GenerateMockRecorderMethod(mockType string, m *model.Method) argString = strings.Join(argNames[:len(argNames)-1], ", ") } if argString != "" { - argString += " interface{}" + argString += " any" } if m.Variadic != nil { if argString != "" { argString += ", " } - argString += fmt.Sprintf("%s ...interface{}", argNames[len(argNames)-1]) + argString += fmt.Sprintf("%s ...any", argNames[len(argNames)-1]) } ia := newIdentifierAllocator(argNames) idRecv := ia.allocateIdentifier("mr") g.p("// %v indicates an expected call of %v.", m.Name, m.Name) - g.p("func (%s *%vMockRecorder) %v(%v) *gomock.Call {", idRecv, mockType, m.Name, argString) + if typed { + g.p("func (%s *%vMockRecorder%v) %v(%v) *%s%sCall%s {", idRecv, mockType, shortTp, m.Name, argString, intf.Name, m.Name, shortTp) + } else { + g.p("func (%s *%vMockRecorder%v) %v(%v) *gomock.Call {", idRecv, mockType, shortTp, m.Name, argString) + } + g.in() g.p("%s.mock.ctrl.T.Helper()", idRecv) @@ -551,42 +641,121 @@ func (g *generator) GenerateMockRecorderMethod(mockType string, m *model.Method) } else { // Hard: create a temporary slice. idVarArgs := ia.allocateIdentifier("varargs") - g.p("%s := append([]interface{}{%s}, %s...)", + g.p("%s := append([]any{%s}, %s...)", idVarArgs, strings.Join(argNames[:len(argNames)-1], ", "), argNames[len(argNames)-1]) callArgs = ", " + idVarArgs + "..." } } - g.p(`return %s.mock.ctrl.RecordCallWithMethodType(%s.mock, "%s", reflect.TypeOf((*%s)(nil).%s)%s)`, idRecv, idRecv, m.Name, mockType, m.Name, callArgs) + if typed { + g.p(`call := %s.mock.ctrl.RecordCallWithMethodType(%s.mock, "%s", reflect.TypeOf((*%s%s)(nil).%s)%s)`, idRecv, idRecv, m.Name, mockType, shortTp, m.Name, callArgs) + g.p(`return &%s%sCall%s{Call: call}`, intf.Name, m.Name, shortTp) + } else { + g.p(`return %s.mock.ctrl.RecordCallWithMethodType(%s.mock, "%s", reflect.TypeOf((*%s%s)(nil).%s)%s)`, idRecv, idRecv, m.Name, mockType, shortTp, m.Name, callArgs) + } + + g.out() + g.p("}") + return nil +} + +func (g *generator) GenerateMockReturnCallMethod(intf *model.Interface, m *model.Method, pkgOverride, longTp, shortTp string) error { + argNames := g.getArgNames(m, true /* in */) + retNames := g.getArgNames(m, false /* out */) + argTypes := g.getArgTypes(m, pkgOverride, true /* in */) + retTypes := g.getArgTypes(m, pkgOverride, false /* out */) + argString := strings.Join(argTypes, ", ") + + rets := make([]string, len(m.Out)) + for i, p := range m.Out { + rets[i] = p.Type.String(g.packageMap, pkgOverride) + } + var retString string + switch { + case len(rets) == 1: + retString = " " + rets[0] + case len(rets) > 1: + retString = " (" + strings.Join(rets, ", ") + ")" + } + + ia := newIdentifierAllocator(argNames) + idRecv := ia.allocateIdentifier("c") + + recvStructName := intf.Name + m.Name + + g.p("// %s%sCall wrap *gomock.Call", intf.Name, m.Name) + g.p("type %s%sCall%s struct{", intf.Name, m.Name, longTp) + g.in() + g.p("*gomock.Call") + g.out() + g.p("}") + + g.p("// Return rewrite *gomock.Call.Return") + g.p("func (%s *%sCall%s) Return(%v) *%sCall%s {", idRecv, recvStructName, shortTp, makeArgString(retNames, retTypes), recvStructName, shortTp) + g.in() + var retArgs string + if len(retNames) > 0 { + retArgs = strings.Join(retNames, ", ") + } + g.p(`%s.Call = %v.Call.Return(%v)`, idRecv, idRecv, retArgs) + g.p("return %s", idRecv) + g.out() + g.p("}") + + g.p("// Do rewrite *gomock.Call.Do") + g.p("func (%s *%sCall%s) Do(f func(%v)%v) *%sCall%s {", idRecv, recvStructName, shortTp, argString, retString, recvStructName, shortTp) + g.in() + g.p(`%s.Call = %v.Call.Do(f)`, idRecv, idRecv) + g.p("return %s", idRecv) + g.out() + g.p("}") + + g.p("// DoAndReturn rewrite *gomock.Call.DoAndReturn") + g.p("func (%s *%sCall%s) DoAndReturn(f func(%v)%v) *%sCall%s {", idRecv, recvStructName, shortTp, argString, retString, recvStructName, shortTp) + g.in() + g.p(`%s.Call = %v.Call.DoAndReturn(f)`, idRecv, idRecv) + g.p("return %s", idRecv) g.out() g.p("}") return nil } -func (g *generator) getArgNames(m *model.Method) []string { - argNames := make([]string, len(m.In)) - for i, p := range m.In { +func (g *generator) getArgNames(m *model.Method, in bool) []string { + var params []*model.Parameter + if in { + params = m.In + } else { + params = m.Out + } + argNames := make([]string, len(params)) + for i, p := range params { name := p.Name if name == "" || name == "_" { name = fmt.Sprintf("arg%d", i) } argNames[i] = name } - if m.Variadic != nil { + if m.Variadic != nil && in { name := m.Variadic.Name if name == "" { - name = fmt.Sprintf("arg%d", len(m.In)) + name = fmt.Sprintf("arg%d", len(params)) } argNames = append(argNames, name) } return argNames } -func (g *generator) getArgTypes(m *model.Method, pkgOverride string) []string { - argTypes := make([]string, len(m.In)) - for i, p := range m.In { +func (g *generator) getArgTypes(m *model.Method, pkgOverride string, in bool) []string { + var params []*model.Parameter + if in { + params = m.In + } else { + params = m.Out + } + argTypes := make([]string, len(params)) + for i, p := range params { argTypes[i] = p.Type.String(g.packageMap, pkgOverride) } if m.Variadic != nil { @@ -670,7 +839,7 @@ func parsePackageImport(srcDir string) (string, error) { if moduleMode != "off" { currentDir := srcDir for { - dat, err := ioutil.ReadFile(filepath.Join(currentDir, "go.mod")) + dat, err := os.ReadFile(filepath.Join(currentDir, "go.mod")) if os.IsNotExist(err) { if currentDir == filepath.Dir(currentDir) { // at the root diff --git a/vendor/github.com/golang/mock/mockgen/model/model.go b/vendor/go.uber.org/mock/mockgen/model/model.go similarity index 87% rename from vendor/github.com/golang/mock/mockgen/model/model.go rename to vendor/go.uber.org/mock/mockgen/model/model.go index 2c6a62ceb2..e2dde53853 100644 --- a/vendor/github.com/golang/mock/mockgen/model/model.go +++ b/vendor/go.uber.org/mock/mockgen/model/model.go @@ -24,7 +24,7 @@ import ( ) // pkgPath is the importable path for package model -const pkgPath = "github.com/golang/mock/mockgen/model" +const pkgPath = "go.uber.org/mock/mockgen/model" // Package is a Go package. It may be a subset. type Package struct { @@ -47,14 +47,18 @@ func (pkg *Package) Imports() map[string]bool { im := make(map[string]bool) for _, intf := range pkg.Interfaces { intf.addImports(im) + for _, tp := range intf.TypeParams { + tp.Type.addImports(im) + } } return im } // Interface is a Go interface. type Interface struct { - Name string - Methods []*Method + Name string + Methods []*Method + TypeParams []*Parameter } // Print writes the interface name and its methods. @@ -143,12 +147,14 @@ type Type interface { } func init() { - gob.Register(&ArrayType{}) - gob.Register(&ChanType{}) - gob.Register(&FuncType{}) - gob.Register(&MapType{}) - gob.Register(&NamedType{}) - gob.Register(&PointerType{}) + // Call gob.RegisterName with pkgPath as prefix to avoid conflicting with + // github.com/golang/mock/mockgen/model 's registration. + gob.RegisterName(pkgPath+".ArrayType", &ArrayType{}) + gob.RegisterName(pkgPath+".ChanType", &ChanType{}) + gob.RegisterName(pkgPath+".FuncType", &FuncType{}) + gob.RegisterName(pkgPath+".MapType", &MapType{}) + gob.RegisterName(pkgPath+".NamedType", &NamedType{}) + gob.RegisterName(pkgPath+".PointerType", &PointerType{}) // Call gob.RegisterName to make sure it has the consistent name registered // for both gob decoder and encoder. @@ -156,7 +162,7 @@ func init() { // For a non-pointer type, gob.Register will try to get package full path by // calling rt.PkgPath() for a name to register. If your project has vendor // directory, it is possible that PkgPath will get a path like this: - // ../../../vendor/github.com/golang/mock/mockgen/model + // ../../../vendor/go.uber.org/mock/mockgen/model gob.RegisterName(pkgPath+".PredeclaredType", PredeclaredType("")) } @@ -259,26 +265,28 @@ func (mt *MapType) addImports(im map[string]bool) { // NamedType is an exported type in a package. type NamedType struct { - Package string // may be empty - Type string + Package string // may be empty + Type string + TypeParams *TypeParametersType } func (nt *NamedType) String(pm map[string]string, pkgOverride string) string { if pkgOverride == nt.Package { - return nt.Type + return nt.Type + nt.TypeParams.String(pm, pkgOverride) } prefix := pm[nt.Package] if prefix != "" { - return prefix + "." + nt.Type + return prefix + "." + nt.Type + nt.TypeParams.String(pm, pkgOverride) } - return nt.Type + return nt.Type + nt.TypeParams.String(pm, pkgOverride) } func (nt *NamedType) addImports(im map[string]bool) { if nt.Package != "" { im[nt.Package] = true } + nt.TypeParams.addImports(im) } // PointerType is a pointer to another type. @@ -297,6 +305,36 @@ type PredeclaredType string func (pt PredeclaredType) String(map[string]string, string) string { return string(pt) } func (pt PredeclaredType) addImports(map[string]bool) {} +// TypeParametersType contains type paramters for a NamedType. +type TypeParametersType struct { + TypeParameters []Type +} + +func (tp *TypeParametersType) String(pm map[string]string, pkgOverride string) string { + if tp == nil || len(tp.TypeParameters) == 0 { + return "" + } + var sb strings.Builder + sb.WriteString("[") + for i, v := range tp.TypeParameters { + if i != 0 { + sb.WriteString(", ") + } + sb.WriteString(v.String(pm, pkgOverride)) + } + sb.WriteString("]") + return sb.String() +} + +func (tp *TypeParametersType) addImports(im map[string]bool) { + if tp == nil { + return + } + for _, v := range tp.TypeParameters { + v.addImports(im) + } +} + // The following code is intended to be called by the program generated by ../reflect.go. // InterfaceFromInterfaceType returns a pointer to an interface for the @@ -431,7 +469,7 @@ func typeFromType(t reflect.Type) (Type, error) { case reflect.Interface: // Two special interfaces. if t.NumMethod() == 0 { - return PredeclaredType("interface{}"), nil + return PredeclaredType("any"), nil } if t == errorType { return PredeclaredType("error"), nil diff --git a/vendor/github.com/golang/mock/mockgen/parse.go b/vendor/go.uber.org/mock/mockgen/parse.go similarity index 63% rename from vendor/github.com/golang/mock/mockgen/parse.go rename to vendor/go.uber.org/mock/mockgen/parse.go index bf6902cd5b..9521409986 100644 --- a/vendor/github.com/golang/mock/mockgen/parse.go +++ b/vendor/go.uber.org/mock/mockgen/parse.go @@ -18,7 +18,6 @@ package main import ( "errors" - "flag" "fmt" "go/ast" "go/build" @@ -26,19 +25,14 @@ import ( "go/parser" "go/token" "go/types" - "io/ioutil" "log" + "os" "path" "path/filepath" "strconv" "strings" - "github.com/golang/mock/mockgen/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.") + "go.uber.org/mock/mockgen/model" ) // sourceMode generates mocks via source file. @@ -62,8 +56,8 @@ func sourceMode(source string) (*model.Package, error) { p := &fileParser{ fileSet: fs, imports: make(map[string]importedPackage), - importedInterfaces: make(map[string]map[string]*ast.InterfaceType), - auxInterfaces: make(map[string]map[string]*ast.InterfaceType), + importedInterfaces: newInterfaceCache(), + auxInterfaces: newInterfaceCache(), srcDir: srcDir, } @@ -81,6 +75,10 @@ func sourceMode(source string) (*model.Package, error) { } } + if *excludeInterfaces != "" { + p.excludeNamesSet = parseExcludeInterfaces(*excludeInterfaces) + } + // Handle -aux_files. if err := p.parseAuxFiles(*auxFiles); err != nil { return nil, err @@ -127,21 +125,55 @@ func (d duplicateImport) Error() string { func (d duplicateImport) Path() string { log.Fatal(d.Error()); return "" } func (d duplicateImport) Parser() *fileParser { log.Fatal(d.Error()); return nil } -type fileParser struct { - fileSet *token.FileSet - imports map[string]importedPackage // package name => imported package - importedInterfaces map[string]map[string]*ast.InterfaceType // package (or "") => name => interface +type interfaceCache struct { + m map[string]map[string]*namedInterface +} + +func newInterfaceCache() *interfaceCache { + return &interfaceCache{ + m: make(map[string]map[string]*namedInterface), + } +} + +func (i *interfaceCache) Set(pkg, name string, it *namedInterface) { + if _, ok := i.m[pkg]; !ok { + i.m[pkg] = make(map[string]*namedInterface) + } + i.m[pkg][name] = it +} + +func (i *interfaceCache) Get(pkg, name string) *namedInterface { + if _, ok := i.m[pkg]; !ok { + return nil + } + return i.m[pkg][name] +} - auxFiles []*ast.File - auxInterfaces map[string]map[string]*ast.InterfaceType // package (or "") => name => interface +func (i *interfaceCache) GetASTIface(pkg, name string) *ast.InterfaceType { + if _, ok := i.m[pkg]; !ok { + return nil + } + it, ok := i.m[pkg][name] + if !ok { + return nil + } + return it.it +} - srcDir string +type fileParser struct { + fileSet *token.FileSet + imports map[string]importedPackage // package name => imported package + importedInterfaces *interfaceCache + auxFiles []*ast.File + auxInterfaces *interfaceCache + srcDir string + excludeNamesSet map[string]struct{} } -func (p *fileParser) errorf(pos token.Pos, format string, args ...interface{}) error { +func (p *fileParser) errorf(pos token.Pos, format string, args ...any) error { ps := p.fileSet.Position(pos) format = "%s:%d:%d: " + format - args = append([]interface{}{ps.Filename, ps.Line, ps.Column}, args...) + args = append([]any{ps.Filename, ps.Line, ps.Column}, args...) return fmt.Errorf(format, args...) } @@ -168,11 +200,8 @@ func (p *fileParser) parseAuxFiles(auxFiles string) error { } 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 + p.auxInterfaces.Set(pkg, ni.name.Name, ni) } } @@ -199,7 +228,10 @@ func (p *fileParser) parseFile(importPath string, file *ast.File) (*model.Packag var is []*model.Interface for ni := range iterInterfaces(file) { - i, err := p.parseInterface(ni.name.String(), importPath, ni.it) + if _, ok := p.excludeNamesSet[ni.name.String()]; ok { + continue + } + i, err := p.parseInterface(ni.name.String(), importPath, ni) if err != nil { return nil, err } @@ -219,8 +251,8 @@ func (p *fileParser) parsePackage(path string) (*fileParser, error) { newP := &fileParser{ fileSet: token.NewFileSet(), imports: make(map[string]importedPackage), - importedInterfaces: make(map[string]map[string]*ast.InterfaceType), - auxInterfaces: make(map[string]map[string]*ast.InterfaceType), + importedInterfaces: newInterfaceCache(), + auxInterfaces: newInterfaceCache(), srcDir: p.srcDir, } @@ -233,11 +265,8 @@ func (p *fileParser) parsePackage(path string) (*fileParser, error) { for _, pkg := range pkgs { file := ast.MergePackageFiles(pkg, ast.FilterFuncDuplicates|ast.FilterUnassociatedComments|ast.FilterImportDuplicates) - if _, ok := newP.importedInterfaces[path]; !ok { - newP.importedInterfaces[path] = make(map[string]*ast.InterfaceType) - } for ni := range iterInterfaces(file) { - newP.importedInterfaces[path][ni.name.Name] = ni.it + newP.importedInterfaces.Set(path, ni.name.Name, ni) } imports, _ := importsOfFile(file) for pkgName, pkgI := range imports { @@ -247,9 +276,77 @@ func (p *fileParser) parsePackage(path string) (*fileParser, error) { return newP, nil } -func (p *fileParser) parseInterface(name, pkg string, it *ast.InterfaceType) (*model.Interface, error) { +func (p *fileParser) constructInstParams(pkg string, params []*ast.Field, instParams []model.Type, embeddedInstParams []ast.Expr, tps map[string]model.Type) ([]model.Type, error) { + pm := make(map[string]int) + var i int + for _, v := range params { + for _, n := range v.Names { + pm[n.Name] = i + instParams = append(instParams, model.PredeclaredType(n.Name)) + i++ + } + } + + var runtimeInstParams []model.Type + for _, instParam := range embeddedInstParams { + switch t := instParam.(type) { + case *ast.Ident: + if idx, ok := pm[t.Name]; ok { + runtimeInstParams = append(runtimeInstParams, instParams[idx]) + continue + } + } + modelType, err := p.parseType(pkg, instParam, tps) + if err != nil { + return nil, err + } + runtimeInstParams = append(runtimeInstParams, modelType) + } + + return runtimeInstParams, nil +} + +func (p *fileParser) constructTps(it *namedInterface) (tps map[string]model.Type) { + tps = make(map[string]model.Type) + n := 0 + for _, tp := range it.typeParams { + for _, tm := range tp.Names { + tps[tm.Name] = nil + if len(it.instTypes) != 0 { + tps[tm.Name] = it.instTypes[n] + n++ + } + } + } + return tps +} + +// parseInterface loads interface specified by pkg and name, parses it and returns +// a new model with the parsed. +func (p *fileParser) parseInterface(name, pkg string, it *namedInterface) (*model.Interface, error) { iface := &model.Interface{Name: name} - for _, field := range it.Methods.List { + tps := p.constructTps(it) + tp, err := p.parseFieldList(pkg, it.typeParams, tps) + if err != nil { + return nil, fmt.Errorf("unable to parse interface type parameters: %v", name) + } + + iface.TypeParams = tp + for _, field := range it.it.Methods.List { + var methods []*model.Method + if methods, err = p.parseMethod(field, it, iface, pkg, tps); err != nil { + return nil, err + } + for _, m := range methods { + iface.AddMethod(m) + } + } + return iface, nil +} + +func (p *fileParser) parseMethod(field *ast.Field, it *namedInterface, iface *model.Interface, pkg string, tps map[string]model.Type) ([]*model.Method, error) { + // {} for git diff + { switch v := field.Type.(type) { case *ast.FuncType: if nn := len(field.Names); nn != 1 { @@ -259,37 +356,55 @@ func (p *fileParser) parseInterface(name, pkg string, it *ast.InterfaceType) (*m Name: field.Names[0].String(), } var err error - m.In, m.Variadic, m.Out, err = p.parseFunc(pkg, v) + m.In, m.Variadic, m.Out, err = p.parseFunc(pkg, v, tps) if err != nil { return nil, err } - iface.AddMethod(m) + return []*model.Method{m}, nil case *ast.Ident: // Embedded interface in this package. - embeddedIfaceType := p.auxInterfaces[pkg][v.String()] + embeddedIfaceType := p.auxInterfaces.Get(pkg, v.String()) if embeddedIfaceType == nil { - embeddedIfaceType = p.importedInterfaces[pkg][v.String()] + embeddedIfaceType = p.importedInterfaces.Get(pkg, v.String()) } var embeddedIface *model.Interface if embeddedIfaceType != nil { var err error + embeddedIfaceType.instTypes, err = p.constructInstParams(pkg, it.typeParams, it.instTypes, it.embeddedInstTypeParams, tps) + if err != nil { + return nil, err + } embeddedIface, err = p.parseInterface(v.String(), pkg, embeddedIfaceType) if err != nil { return nil, err } + } else { // This is built-in error interface. if v.String() == model.ErrorInterface.Name { embeddedIface = &model.ErrorInterface } else { - return nil, p.errorf(v.Pos(), "unknown embedded interface %s", v.String()) + ip, err := p.parsePackage(pkg) + if err != nil { + return nil, p.errorf(v.Pos(), "could not parse package %s: %v", pkg, err) + } + + if embeddedIfaceType = ip.importedInterfaces.Get(pkg, v.String()); embeddedIfaceType == nil { + return nil, p.errorf(v.Pos(), "unknown embedded interface %s.%s", pkg, v.String()) + } + + embeddedIfaceType.instTypes, err = p.constructInstParams(pkg, it.typeParams, it.instTypes, it.embeddedInstTypeParams, tps) + if err != nil { + return nil, err + } + embeddedIface, err = ip.parseInterface(v.String(), pkg, embeddedIfaceType) + if err != nil { + return nil, err + } } } - // Copy the methods. - for _, m := range embeddedIface.Methods { - iface.AddMethod(m) - } + return embeddedIface.Methods, nil case *ast.SelectorExpr: // Embedded interface in another package. filePkg, sel := v.X.(*ast.Ident).String(), v.Sel.String() @@ -300,8 +415,12 @@ func (p *fileParser) parseInterface(name, pkg string, it *ast.InterfaceType) (*m var embeddedIface *model.Interface var err error - embeddedIfaceType := p.auxInterfaces[filePkg][sel] + embeddedIfaceType := p.auxInterfaces.Get(filePkg, sel) if embeddedIfaceType != nil { + embeddedIfaceType.instTypes, err = p.constructInstParams(pkg, it.typeParams, it.instTypes, it.embeddedInstTypeParams, tps) + if err != nil { + return nil, err + } embeddedIface, err = p.parseInterface(sel, filePkg, embeddedIfaceType) if err != nil { return nil, err @@ -320,46 +439,47 @@ func (p *fileParser) parseInterface(name, pkg string, it *ast.InterfaceType) (*m parser: parser, } } - if embeddedIfaceType = parser.importedInterfaces[path][sel]; embeddedIfaceType == nil { + if embeddedIfaceType = parser.importedInterfaces.Get(path, sel); embeddedIfaceType == nil { return nil, p.errorf(v.Pos(), "unknown embedded interface %s.%s", path, sel) } + + embeddedIfaceType.instTypes, err = p.constructInstParams(pkg, it.typeParams, it.instTypes, it.embeddedInstTypeParams, tps) + if err != nil { + return nil, err + } embeddedIface, err = parser.parseInterface(sel, path, embeddedIfaceType) if err != nil { return nil, err } } - // Copy the methods. // TODO: apply shadowing rules. - for _, m := range embeddedIface.Methods { - iface.AddMethod(m) - } + return embeddedIface.Methods, nil default: - return nil, fmt.Errorf("don't know how to mock method of type %T", field.Type) + return p.parseGenericMethod(field, it, iface, pkg, tps) } } - return iface, nil } -func (p *fileParser) parseFunc(pkg string, f *ast.FuncType) (inParam []*model.Parameter, variadic *model.Parameter, outParam []*model.Parameter, err error) { +func (p *fileParser) parseFunc(pkg string, f *ast.FuncType, tps map[string]model.Type) (inParam []*model.Parameter, variadic *model.Parameter, outParam []*model.Parameter, err error) { if f.Params != nil { regParams := f.Params.List if isVariadic(f) { n := len(regParams) varParams := regParams[n-1:] regParams = regParams[:n-1] - vp, err := p.parseFieldList(pkg, varParams) + vp, err := p.parseFieldList(pkg, varParams, tps) if err != nil { return nil, nil, nil, p.errorf(varParams[0].Pos(), "failed parsing variadic argument: %v", err) } variadic = vp[0] } - inParam, err = p.parseFieldList(pkg, regParams) + inParam, err = p.parseFieldList(pkg, regParams, tps) if err != nil { return nil, nil, nil, p.errorf(f.Pos(), "failed parsing arguments: %v", err) } } if f.Results != nil { - outParam, err = p.parseFieldList(pkg, f.Results.List) + outParam, err = p.parseFieldList(pkg, f.Results.List, tps) if err != nil { return nil, nil, nil, p.errorf(f.Pos(), "failed parsing returns: %v", err) } @@ -367,7 +487,7 @@ func (p *fileParser) parseFunc(pkg string, f *ast.FuncType) (inParam []*model.Pa return } -func (p *fileParser) parseFieldList(pkg string, fields []*ast.Field) ([]*model.Parameter, error) { +func (p *fileParser) parseFieldList(pkg string, fields []*ast.Field, tps map[string]model.Type) ([]*model.Parameter, error) { nf := 0 for _, f := range fields { nn := len(f.Names) @@ -382,7 +502,7 @@ func (p *fileParser) parseFieldList(pkg string, fields []*ast.Field) ([]*model.P ps := make([]*model.Parameter, nf) i := 0 // destination index for _, f := range fields { - t, err := p.parseType(pkg, f.Type) + t, err := p.parseType(pkg, f.Type, tps) if err != nil { return nil, err } @@ -401,44 +521,27 @@ func (p *fileParser) parseFieldList(pkg string, fields []*ast.Field) ([]*model.P return ps, nil } -func (p *fileParser) parseType(pkg string, typ ast.Expr) (model.Type, error) { +func (p *fileParser) parseType(pkg string, typ ast.Expr, tps map[string]model.Type) (model.Type, error) { switch v := typ.(type) { case *ast.ArrayType: ln := -1 if v.Len != nil { - var value string - switch val := v.Len.(type) { - case (*ast.BasicLit): - value = val.Value - case (*ast.Ident): - // when the length is a const defined locally - value = val.Obj.Decl.(*ast.ValueSpec).Values[0].(*ast.BasicLit).Value - case (*ast.SelectorExpr): - // when the length is a const defined in an external package - usedPkg, err := importer.Default().Import(fmt.Sprintf("%s", val.X)) - if err != nil { - return nil, p.errorf(v.Len.Pos(), "unknown package in array length: %v", err) - } - ev, err := types.Eval(token.NewFileSet(), usedPkg, token.NoPos, val.Sel.Name) - if err != nil { - return nil, p.errorf(v.Len.Pos(), "unknown constant in array length: %v", err) - } - value = ev.Value.String() + value, err := p.parseArrayLength(v.Len) + if err != nil { + return nil, err } - - x, err := strconv.Atoi(value) + ln, err = strconv.Atoi(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) + t, err := p.parseType(pkg, v.Elt, tps) if err != nil { return nil, err } return &model.ArrayType{Len: ln, Type: t}, nil case *ast.ChanType: - t, err := p.parseType(pkg, v.Value) + t, err := p.parseType(pkg, v.Value, tps) if err != nil { return nil, err } @@ -452,15 +555,16 @@ func (p *fileParser) parseType(pkg string, typ ast.Expr) (model.Type, error) { return &model.ChanType{Dir: dir, Type: t}, nil case *ast.Ellipsis: // assume we're parsing a variadic argument - return p.parseType(pkg, v.Elt) + return p.parseType(pkg, v.Elt, tps) case *ast.FuncType: - in, variadic, out, err := p.parseFunc(pkg, v) + in, variadic, out, err := p.parseFunc(pkg, v, tps) if err != nil { return nil, err } return &model.FuncType{In: in, Out: out, Variadic: variadic}, nil case *ast.Ident: - if v.IsExported() { + it, ok := tps[v.Name] + if v.IsExported() && !ok { // `pkg` may be an aliased imported pkg // if so, patch the import w/ the fully qualified import maybeImportedPkg, ok := p.imports[pkg] @@ -470,20 +574,22 @@ func (p *fileParser) parseType(pkg string, typ ast.Expr) (model.Type, error) { // assume type in this package return &model.NamedType{Package: pkg, Type: v.Name}, nil } - + if ok && it != nil { + return it, nil + } // assume predeclared type return model.PredeclaredType(v.Name), nil case *ast.InterfaceType: if v.Methods != nil && len(v.Methods.List) > 0 { return nil, p.errorf(v.Pos(), "can't handle non-empty unnamed interface types") } - return model.PredeclaredType("interface{}"), nil + return model.PredeclaredType("any"), nil case *ast.MapType: - key, err := p.parseType(pkg, v.Key) + key, err := p.parseType(pkg, v.Key, tps) if err != nil { return nil, err } - value, err := p.parseType(pkg, v.Value) + value, err := p.parseType(pkg, v.Value, tps) if err != nil { return nil, err } @@ -496,7 +602,7 @@ func (p *fileParser) parseType(pkg string, typ ast.Expr) (model.Type, error) { } return &model.NamedType{Package: pkg.Path(), Type: v.Sel.String()}, nil case *ast.StarExpr: - t, err := p.parseType(pkg, v.X) + t, err := p.parseType(pkg, v.X, tps) if err != nil { return nil, err } @@ -507,12 +613,61 @@ func (p *fileParser) parseType(pkg string, typ ast.Expr) (model.Type, error) { } return model.PredeclaredType("struct{}"), nil case *ast.ParenExpr: - return p.parseType(pkg, v.X) + return p.parseType(pkg, v.X, tps) + default: + mt, err := p.parseGenericType(pkg, typ, tps) + if err != nil { + return nil, err + } + if mt == nil { + break + } + return mt, nil } return nil, fmt.Errorf("don't know how to parse type %T", typ) } +func (p *fileParser) parseArrayLength(expr ast.Expr) (string, error) { + switch val := expr.(type) { + case (*ast.BasicLit): + return val.Value, nil + case (*ast.Ident): + // when the length is a const defined locally + return val.Obj.Decl.(*ast.ValueSpec).Values[0].(*ast.BasicLit).Value, nil + case (*ast.SelectorExpr): + // when the length is a const defined in an external package + usedPkg, err := importer.Default().Import(fmt.Sprintf("%s", val.X)) + if err != nil { + return "", p.errorf(expr.Pos(), "unknown package in array length: %v", err) + } + ev, err := types.Eval(token.NewFileSet(), usedPkg, token.NoPos, val.Sel.Name) + if err != nil { + return "", p.errorf(expr.Pos(), "unknown constant in array length: %v", err) + } + return ev.Value.String(), nil + case (*ast.ParenExpr): + return p.parseArrayLength(val.X) + case (*ast.BinaryExpr): + x, err := p.parseArrayLength(val.X) + if err != nil { + return "", err + } + y, err := p.parseArrayLength(val.Y) + if err != nil { + return "", err + } + biExpr := fmt.Sprintf("%s%v%s", x, val.Op, y) + tv, err := types.Eval(token.NewFileSet(), nil, token.NoPos, biExpr) + if err != nil { + return "", p.errorf(expr.Pos(), "invalid expression in array length: %v", err) + } + return tv.Value.String(), nil + default: + return "", p.errorf(expr.Pos(), "invalid expression in array length: %v", val) + } +} + // importsOfFile returns a map of package name to import path // of the imports in file. func importsOfFile(file *ast.File) (normalImports map[string]importedPackage, dotImports []string) { @@ -575,13 +730,16 @@ func importsOfFile(file *ast.File) (normalImports map[string]importedPackage, do } type namedInterface struct { - name *ast.Ident - it *ast.InterfaceType + name *ast.Ident + it *ast.InterfaceType + typeParams []*ast.Field + embeddedInstTypeParams []ast.Expr + instTypes []model.Type } // Create an iterator over all interfaces in file. -func iterInterfaces(file *ast.File) <-chan namedInterface { - ch := make(chan namedInterface) +func iterInterfaces(file *ast.File) <-chan *namedInterface { + ch := make(chan *namedInterface) go func() { for _, decl := range file.Decls { gd, ok := decl.(*ast.GenDecl) @@ -598,7 +756,7 @@ func iterInterfaces(file *ast.File) <-chan namedInterface { continue } - ch <- namedInterface{ts.Name, it} + ch <- &namedInterface{name: ts.Name, it: it, typeParams: getTypeSpecTypeParams(ts)} } } close(ch) @@ -618,7 +776,7 @@ func isVariadic(f *ast.FuncType) bool { // packageNameOfDir get package import path via dir func packageNameOfDir(srcDir string) (string, error) { - files, err := ioutil.ReadDir(srcDir) + files, err := os.ReadDir(srcDir) if err != nil { log.Fatal(err) } diff --git a/vendor/github.com/golang/mock/mockgen/reflect.go b/vendor/go.uber.org/mock/mockgen/reflect.go similarity index 93% rename from vendor/github.com/golang/mock/mockgen/reflect.go rename to vendor/go.uber.org/mock/mockgen/reflect.go index e24efce0ba..8f519f6a5d 100644 --- a/vendor/github.com/golang/mock/mockgen/reflect.go +++ b/vendor/go.uber.org/mock/mockgen/reflect.go @@ -23,7 +23,6 @@ import ( "fmt" "go/build" "io" - "io/ioutil" "log" "os" "os/exec" @@ -32,7 +31,7 @@ import ( "strings" "text/template" - "github.com/golang/mock/mockgen/model" + "go.uber.org/mock/mockgen/model" ) var ( @@ -92,7 +91,7 @@ func writeProgram(importPath string, symbols []string) ([]byte, error) { // run the given program and parse the output as a model.Package. func run(program string) (*model.Package, error) { - f, err := ioutil.TempFile("", "") + f, err := os.CreateTemp("", "") if err != nil { return nil, err } @@ -133,7 +132,7 @@ func run(program string) (*model.Package, error) { // parses the output as a model.Package. func runInDir(program []byte, dir string) (*model.Package, error) { // We use TempDir instead of TempFile so we can control the filename. - tmpDir, err := ioutil.TempDir(dir, "gomock_reflect_") + tmpDir, err := os.MkdirTemp(dir, "gomock_reflect_") if err != nil { return nil, err } @@ -149,7 +148,7 @@ func runInDir(program []byte, dir string) (*model.Package, error) { progBinary += ".exe" } - if err := ioutil.WriteFile(filepath.Join(tmpDir, progSource), program, 0600); err != nil { + if err := os.WriteFile(filepath.Join(tmpDir, progSource), program, 0600); err != nil { return nil, err } @@ -169,8 +168,8 @@ func runInDir(program []byte, dir string) (*model.Package, error) { if err := cmd.Run(); err != nil { sErr := buf.String() if strings.Contains(sErr, `cannot find package "."`) && - strings.Contains(sErr, "github.com/golang/mock/mockgen/model") { - fmt.Fprint(os.Stderr, "Please reference the steps in the README to fix this error:\n\thttps://github.com/golang/mock#reflect-vendoring-error.") + strings.Contains(sErr, "go.uber.org/mock/mockgen/model") { + fmt.Fprint(os.Stderr, "Please reference the steps in the README to fix this error:\n\thttps://go.uber.org/mock#reflect-vendoring-error.\n") return nil, err } return nil, err @@ -198,7 +197,7 @@ import ( "path" "reflect" - "github.com/golang/mock/mockgen/model" + "go.uber.org/mock/mockgen/model" pkg_ {{printf "%q" .ImportPath}} ) diff --git a/vendor/github.com/golang/mock/mockgen/version.1.12.go b/vendor/go.uber.org/mock/mockgen/version.go similarity index 94% rename from vendor/github.com/golang/mock/mockgen/version.1.12.go rename to vendor/go.uber.org/mock/mockgen/version.go index ad121ae63c..6db160ac28 100644 --- a/vendor/github.com/golang/mock/mockgen/version.1.12.go +++ b/vendor/go.uber.org/mock/mockgen/version.go @@ -1,4 +1,4 @@ -// Copyright 2019 Google LLC +// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -11,9 +11,6 @@ // 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. -// - -// +build go1.12 package main @@ -31,5 +28,4 @@ func printModuleVersion() { "GO111MODULE=on when running 'go get' in order to use specific " + "version of the binary.") } - } diff --git a/vendor/modules.txt b/vendor/modules.txt index 27301a3dcd..500e14410f 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -730,11 +730,6 @@ github.com/gogo/protobuf/vanity/command # github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da ## explicit github.com/golang/groupcache/lru -# github.com/golang/mock v1.6.0 -## explicit; go 1.11 -github.com/golang/mock/gomock -github.com/golang/mock/mockgen -github.com/golang/mock/mockgen/model # github.com/golang/protobuf v1.5.3 ## explicit; go 1.9 github.com/golang/protobuf/jsonpb @@ -1606,6 +1601,11 @@ go.tmz.dev/musttag go.uber.org/atomic # go.uber.org/goleak v1.2.1 ## explicit; go 1.18 +# go.uber.org/mock v0.3.0 +## explicit; go 1.20 +go.uber.org/mock/gomock +go.uber.org/mock/mockgen +go.uber.org/mock/mockgen/model # go.uber.org/multierr v1.11.0 ## explicit; go 1.19 go.uber.org/multierr