From 636fcb68c8c2563a461cdc991b3e4ac616e5e274 Mon Sep 17 00:00:00 2001 From: "prath.shenoy" Date: Mon, 30 Nov 2026 18:46:26 +0000 Subject: [PATCH] refactor(submitqueue): Replace dependency stubs ## Summary **What**: - Replace hand-written dependency stubs with generated mocks across OSS SubmitQueue tests. **Why**: - Make dependency test doubles follow the existing generation convention instead of maintaining hand-written implementations that reviewers repeatedly have to flag. ## Test Plan - [x] Update tests. ## Revert Plan - Revert this PR. These are test-only changes. ## Issue Links - [CODEM-449](https://linear.app/uber/issue/CODEM-449/ktlo-task) --- service/submitqueue/demo/BUILD.bazel | 2 + service/submitqueue/demo/demo.go | 2 + service/submitqueue/demo/demo_mock_test.go | 150 ++++++++++ service/submitqueue/demo/run_test.go | 265 ++++++++++-------- .../submitqueue/gateway/server/BUILD.bazel | 2 +- .../gateway/server/log_consumer_test.go | 32 +-- .../orchestrator/server/BUILD.bazel | 2 + .../orchestrator/server/http_mock_test.go | 56 ++++ .../orchestrator/server/main_test.go | 32 +-- .../orchestrator/server/profiles_test.go | 23 +- submitqueue/client/BUILD.bazel | 2 + submitqueue/client/history_read_test.go | 60 ++-- submitqueue/client/watch.go | 2 + submitqueue/client/watch_mock_test.go | 102 +++++++ submitqueue/core/changeset/BUILD.bazel | 5 +- submitqueue/core/changeset/resolver.go | 2 + .../core/changeset/resolver_mock_test.go | 69 +++++ submitqueue/core/changeset/resolver_test.go | 18 +- .../conflict/tango/tangoclient/BUILD.bazel | 2 + .../tango/tangoclient/tango_mock_test.go | 178 ++++++++++++ .../tango/tangoclient/tangoclient_test.go | 128 +++++---- .../speculation/allocator/sticky/BUILD.bazel | 2 + .../allocator/sticky/sticky_test.go | 55 ++-- .../generator/bestfirst/BUILD.bazel | 2 + .../generator/bestfirst/bestfirst_test.go | 219 +++++++-------- .../speculation/scorer/composite/BUILD.bazel | 2 + .../scorer/composite/scorer_test.go | 84 +++--- .../speculation/scorer/evidence/BUILD.bazel | 2 + .../scorer/evidence/evidence_test.go | 49 ++-- .../speculator/standard/BUILD.bazel | 1 + .../speculator/standard/standard_test.go | 19 +- submitqueue/gateway/controller/land_test.go | 59 ++-- submitqueue/orchestrator/BUILD.bazel | 2 +- .../orchestrator/controller/batch/BUILD.bazel | 1 - .../controller/batch/batch_test.go | 27 +- .../orchestrator/controller/build/BUILD.bazel | 2 - .../controller/build/build_test.go | 28 +- .../controller/buildsignal/BUILD.bazel | 1 - .../buildsignal/buildsignal_test.go | 14 +- .../controller/cancel/cancel_test.go | 15 +- .../controller/conclude/BUILD.bazel | 1 - .../controller/conclude/conclude_test.go | 14 +- .../orchestrator/controller/dlq/batch_test.go | 25 +- .../controller/dlq/buildsignal_test.go | 30 +- .../controller/dlq/conclude_test.go | 10 +- .../controller/dlq/dependencyanalysis_test.go | 5 +- .../orchestrator/controller/dlq/dlq_test.go | 12 - .../controller/dlq/landconflictsignal_test.go | 20 +- .../controller/dlq/landsignal_test.go | 20 +- .../controller/dlq/request_test.go | 60 +++- .../controller/dlq/speculate_test.go | 5 +- .../orchestrator/controller/dlq/start_test.go | 10 +- .../orchestrator/controller/land/BUILD.bazel | 1 - .../orchestrator/controller/land/land_test.go | 14 +- .../controller/landconflictsignal/BUILD.bazel | 1 - .../landconflictsignal_test.go | 34 ++- .../controller/landsignal/BUILD.bazel | 1 - .../controller/landsignal/landsignal_test.go | 16 +- .../controller/speculate/BUILD.bazel | 3 +- .../controller/speculate/run_test.go | 145 +++++----- .../controller/speculate/speculate_test.go | 52 ++-- .../orchestrator/controller/start/BUILD.bazel | 1 - .../controller/start/start_test.go | 15 +- .../controller/validate/BUILD.bazel | 1 - .../controller/validate/validate_test.go | 165 ++++++++--- submitqueue/orchestrator/pipeline_test.go | 23 +- .../submitqueue/core/consumer/BUILD.bazel | 2 + .../core/consumer/consumer_test.go | 138 ++++----- .../extension/storage/mysql/BUILD.bazel | 3 + .../extension/storage/mysql/storage_test.go | 33 +-- .../submitqueue/gateway/BUILD.bazel | 2 + .../submitqueue/gateway/suite_test.go | 18 +- 72 files changed, 1639 insertions(+), 959 deletions(-) create mode 100644 service/submitqueue/demo/demo_mock_test.go create mode 100644 service/submitqueue/orchestrator/server/http_mock_test.go create mode 100644 submitqueue/client/watch_mock_test.go create mode 100644 submitqueue/core/changeset/resolver_mock_test.go create mode 100644 submitqueue/extension/conflict/tango/tangoclient/tango_mock_test.go diff --git a/service/submitqueue/demo/BUILD.bazel b/service/submitqueue/demo/BUILD.bazel index 310683901..de49932ca 100644 --- a/service/submitqueue/demo/BUILD.bazel +++ b/service/submitqueue/demo/BUILD.bazel @@ -27,6 +27,7 @@ go_library( go_test( name = "go_default_test", srcs = [ + "demo_mock_test.go", "run_test.go", "workload_test.go", ], @@ -38,5 +39,6 @@ go_test( "@com_github_stretchr_testify//require:go_default_library", "@org_golang_google_grpc//codes:go_default_library", "@org_golang_google_grpc//status:go_default_library", + "@org_uber_go_mock//gomock:go_default_library", ], ) diff --git a/service/submitqueue/demo/demo.go b/service/submitqueue/demo/demo.go index fdf1a2bb7..8fe608366 100644 --- a/service/submitqueue/demo/demo.go +++ b/service/submitqueue/demo/demo.go @@ -17,6 +17,8 @@ // the calling command. package demo +//go:generate mockgen -source=demo.go -destination=demo_mock_test.go -package=demo + import ( "context" diff --git a/service/submitqueue/demo/demo_mock_test.go b/service/submitqueue/demo/demo_mock_test.go new file mode 100644 index 000000000..0151271bb --- /dev/null +++ b/service/submitqueue/demo/demo_mock_test.go @@ -0,0 +1,150 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: demo.go +// +// Generated by this command: +// +// mockgen -source=demo.go -destination=demo_mock_test.go -package=demo +// + +// Package demo is a generated GoMock package. +package demo + +import ( + context "context" + reflect "reflect" + + protopb "github.com/uber/submitqueue/api/base/mergestrategy/protopb" + protopb0 "github.com/uber/submitqueue/api/submitqueue/gateway/protopb" + gomock "go.uber.org/mock/gomock" +) + +// MockSource is a mock of Source interface. +type MockSource struct { + ctrl *gomock.Controller + recorder *MockSourceMockRecorder + isgomock struct{} +} + +// MockSourceMockRecorder is the mock recorder for MockSource. +type MockSourceMockRecorder struct { + mock *MockSource +} + +// NewMockSource creates a new mock instance. +func NewMockSource(ctrl *gomock.Controller) *MockSource { + mock := &MockSource{ctrl: ctrl} + mock.recorder = &MockSourceMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockSource) EXPECT() *MockSourceMockRecorder { + return m.recorder +} + +// Open mocks base method. +func (m *MockSource) Open(arg0 context.Context, arg1 ChangeSpec) (Change, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Open", arg0, arg1) + ret0, _ := ret[0].(Change) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Open indicates an expected call of Open. +func (mr *MockSourceMockRecorder) Open(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Open", reflect.TypeOf((*MockSource)(nil).Open), arg0, arg1) +} + +// MockGateway is a mock of Gateway interface. +type MockGateway struct { + ctrl *gomock.Controller + recorder *MockGatewayMockRecorder + isgomock struct{} +} + +// MockGatewayMockRecorder is the mock recorder for MockGateway. +type MockGatewayMockRecorder struct { + mock *MockGateway +} + +// NewMockGateway creates a new mock instance. +func NewMockGateway(ctrl *gomock.Controller) *MockGateway { + mock := &MockGateway{ctrl: ctrl} + mock.recorder = &MockGatewayMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockGateway) EXPECT() *MockGatewayMockRecorder { + return m.recorder +} + +// History mocks base method. +func (m *MockGateway) History(ctx context.Context, queue, requestID string) ([]*protopb0.HistoryEvent, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "History", ctx, queue, requestID) + ret0, _ := ret[0].([]*protopb0.HistoryEvent) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// History indicates an expected call of History. +func (mr *MockGatewayMockRecorder) History(ctx, queue, requestID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "History", reflect.TypeOf((*MockGateway)(nil).History), ctx, queue, requestID) +} + +// Land mocks base method. +func (m *MockGateway) Land(ctx context.Context, queue string, uris []string, strategy protopb.Strategy) (string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Land", ctx, queue, uris, strategy) + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Land indicates an expected call of Land. +func (mr *MockGatewayMockRecorder) Land(ctx, queue, uris, strategy any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Land", reflect.TypeOf((*MockGateway)(nil).Land), ctx, queue, uris, strategy) +} + +// MockReadiness is a mock of Readiness interface. +type MockReadiness struct { + ctrl *gomock.Controller + recorder *MockReadinessMockRecorder + isgomock struct{} +} + +// MockReadinessMockRecorder is the mock recorder for MockReadiness. +type MockReadinessMockRecorder struct { + mock *MockReadiness +} + +// NewMockReadiness creates a new mock instance. +func NewMockReadiness(ctrl *gomock.Controller) *MockReadiness { + mock := &MockReadiness{ctrl: ctrl} + mock.recorder = &MockReadinessMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockReadiness) EXPECT() *MockReadinessMockRecorder { + return m.recorder +} + +// Wait mocks base method. +func (m *MockReadiness) Wait(arg0 context.Context, arg1 Change) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Wait", arg0, arg1) + ret0, _ := ret[0].(error) + return ret0 +} + +// Wait indicates an expected call of Wait. +func (mr *MockReadinessMockRecorder) Wait(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Wait", reflect.TypeOf((*MockReadiness)(nil).Wait), arg0, arg1) +} diff --git a/service/submitqueue/demo/run_test.go b/service/submitqueue/demo/run_test.go index 95b88c702..20c3bbbba 100644 --- a/service/submitqueue/demo/run_test.go +++ b/service/submitqueue/demo/run_test.go @@ -26,38 +26,11 @@ import ( "github.com/stretchr/testify/require" mergestrategypb "github.com/uber/submitqueue/api/base/mergestrategy/protopb" pb "github.com/uber/submitqueue/api/submitqueue/gateway/protopb" + "go.uber.org/mock/gomock" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) -type sourceFunc func(context.Context, ChangeSpec) (Change, error) - -func (f sourceFunc) Open(ctx context.Context, spec ChangeSpec) (Change, error) { - return f(ctx, spec) -} - -type readinessFunc func(context.Context, Change) error - -func (f readinessFunc) Wait(ctx context.Context, change Change) error { - return f(ctx, change) -} - -type gatewayFixture struct { - land func(context.Context, string, []string, mergestrategypb.Strategy) (string, error) - history func(context.Context, string, string) ([]*pb.HistoryEvent, error) -} - -func (g gatewayFixture) Land(ctx context.Context, queue string, uris []string, strategy mergestrategypb.Strategy) (string, error) { - return g.land(ctx, queue, uris, strategy) -} - -func (g gatewayFixture) History(ctx context.Context, queue, id string) ([]*pb.HistoryEvent, error) { - if g.history == nil { - return nil, nil - } - return g.history(ctx, queue, id) -} - func fixtureOptions() Options { return Options{ Count: 3, Files: 1, Folders: 2, Concurrency: 1, Prefix: "demo", @@ -72,12 +45,6 @@ func fixtureChange(spec ChangeSpec) Change { } } -func fixtureGateway() gatewayFixture { - return gatewayFixture{land: func(_ context.Context, _ string, uris []string, _ mergestrategypb.Strategy) (string, error) { - return strings.Join(uris, ","), nil - }} -} - func TestWorkloadSubmissionModes(t *testing.T) { tests := []struct { name string @@ -97,21 +64,26 @@ func TestWorkloadSubmissionModes(t *testing.T) { var specs []ChangeSpec var prepared []string var landSizes, createdAtLand []int - src := sourceFunc(func(_ context.Context, spec ChangeSpec) (Change, error) { + src := NewMockSource(gomock.NewController(t)) + src.EXPECT().Open(gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, spec ChangeSpec) (Change, error) { specs = append(specs, spec) return fixtureChange(spec), nil - }) - gateway := fixtureGateway() - gateway.land = func(_ context.Context, _ string, uris []string, _ mergestrategypb.Strategy) (string, error) { + }).AnyTimes() + gateway := NewMockGateway(gomock.NewController(t)) + gateway.EXPECT().History(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() + gateway.EXPECT().Land(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, uris []string, _ mergestrategypb.Strategy) (string, error) { landSizes = append(landSizes, len(uris)) createdAtLand = append(createdAtLand, len(specs)) return fmt.Sprintf("id-%d", len(landSizes)), nil - } + }).AnyTimes() + readiness := NewMockReadiness(gomock.NewController(t)) + readiness.EXPECT().Wait(gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, change Change) error { + prepared = append(prepared, change.URI) + return nil + }).AnyTimes() + result, err := Run(context.Background(), opts, Dependencies{ - Source: src, Gateway: gateway, Readiness: readinessFunc(func(_ context.Context, change Change) error { - prepared = append(prepared, change.URI) - return nil - }), + Source: src, Gateway: gateway, Readiness: readiness, }) require.NoError(t, err) assert.Equal(t, tt.wantLandSizes, landSizes) @@ -134,20 +106,27 @@ func TestBurstWaitsForAllReadiness(t *testing.T) { opts.Burst = true var prepared, calls int expected := errors.New("readiness failed") - gateway := fixtureGateway() - gateway.land = func(context.Context, string, []string, mergestrategypb.Strategy) (string, error) { + gateway := NewMockGateway(gomock.NewController(t)) + gateway.EXPECT().History(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() + gateway.EXPECT().Land(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(context.Context, string, []string, mergestrategypb.Strategy) (string, error) { calls++ return "id", nil - } + }).AnyTimes() + readiness := NewMockReadiness(gomock.NewController(t)) + readiness.EXPECT().Wait(gomock.Any(), gomock.Any()).DoAndReturn(func(context.Context, Change) error { + prepared++ + if prepared == 3 { + return expected + } + return nil + }).AnyTimes() + + source := NewMockSource(gomock.NewController(t)) + source.EXPECT().Open(gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, spec ChangeSpec) (Change, error) { return fixtureChange(spec), nil }).AnyTimes() + result, err := Run(context.Background(), opts, Dependencies{ - Source: sourceFunc(func(_ context.Context, spec ChangeSpec) (Change, error) { return fixtureChange(spec), nil }), - Gateway: gateway, Readiness: readinessFunc(func(context.Context, Change) error { - prepared++ - if prepared == 3 { - return expected - } - return nil - }), + Source: source, + Gateway: gateway, Readiness: readiness, }) require.ErrorIs(t, err, expected) assert.Len(t, result.Changes, 3) @@ -163,7 +142,8 @@ func TestIndependentCreationIsBoundedAndOverlapsSubmission(t *testing.T) { release := make(chan struct{}) landed := make(chan struct{}, 4) done := make(chan error, 1) - src := sourceFunc(func(ctx context.Context, spec ChangeSpec) (Change, error) { + src := NewMockSource(gomock.NewController(t)) + src.EXPECT().Open(gomock.Any(), gomock.Any()).DoAndReturn(func(ctx context.Context, spec ChangeSpec) (Change, error) { entered <- struct{}{} if strings.HasSuffix(spec.Branch, "/1") { return fixtureChange(spec), nil @@ -174,12 +154,13 @@ func TestIndependentCreationIsBoundedAndOverlapsSubmission(t *testing.T) { case <-ctx.Done(): return Change{}, ctx.Err() } - }) - gateway := fixtureGateway() - gateway.land = func(_ context.Context, _ string, uris []string, _ mergestrategypb.Strategy) (string, error) { + }).AnyTimes() + gateway := NewMockGateway(gomock.NewController(t)) + gateway.EXPECT().History(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() + gateway.EXPECT().Land(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, uris []string, _ mergestrategypb.Strategy) (string, error) { landed <- struct{}{} return uris[0], nil - } + }).AnyTimes() go func() { _, err := Run(context.Background(), opts, Dependencies{Source: src, Gateway: gateway}) done <- err @@ -201,15 +182,24 @@ func TestPartialFailurePreservesAcceptedArtifacts(t *testing.T) { opts := fixtureOptions() expected := errors.New("creation failed") calls := 0 + gateway := NewMockGateway(gomock.NewController(t)) + gateway.EXPECT().Land(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, uris []string, _ mergestrategypb.Strategy) (string, error) { + return strings.Join(uris, ","), nil + }).AnyTimes() + gateway.EXPECT().History(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() + + source := NewMockSource(gomock.NewController(t)) + source.EXPECT().Open(gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, spec ChangeSpec) (Change, error) { + calls++ + if calls == 2 { + return Change{Branch: spec.Branch}, expected + } + return fixtureChange(spec), nil + }).AnyTimes() + result, err := Run(context.Background(), opts, Dependencies{ - Gateway: fixtureGateway(), - Source: sourceFunc(func(_ context.Context, spec ChangeSpec) (Change, error) { - calls++ - if calls == 2 { - return Change{Branch: spec.Branch}, expected - } - return fixtureChange(spec), nil - }), + Gateway: gateway, + Source: source, }) require.ErrorIs(t, err, expected) assert.Equal(t, 2, calls) @@ -225,15 +215,19 @@ func TestExistingChangesAreNotCreatedOrMutated(t *testing.T) { changes := []Change{fixtureChange(ChangeSpec{Branch: "first"}), fixtureChange(ChangeSpec{Branch: "second"})} want := append([]Change(nil), changes...) var uris []string - gateway := fixtureGateway() - gateway.land = func(_ context.Context, _ string, in []string, _ mergestrategypb.Strategy) (string, error) { + gateway := NewMockGateway(gomock.NewController(t)) + gateway.EXPECT().History(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() + gateway.EXPECT().Land(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, in []string, _ mergestrategypb.Strategy) (string, error) { uris = append([]string(nil), in...) return "opaque/id", nil - } + }).AnyTimes() + source := NewMockSource(gomock.NewController(t)) + source.EXPECT().Open(gomock.Any(), gomock.Any()).DoAndReturn(func(context.Context, ChangeSpec) (Change, error) { + return Change{}, errors.New("existing changes must not invoke Source") + }).AnyTimes() + result, err := RunExisting(context.Background(), opts, changes, Dependencies{ - Gateway: gateway, Source: sourceFunc(func(context.Context, ChangeSpec) (Change, error) { - return Change{}, errors.New("existing changes must not invoke Source") - }), + Gateway: gateway, Source: source, }) require.NoError(t, err) assert.Equal(t, want, changes) @@ -247,11 +241,17 @@ func TestExistingChangesAreNotCreatedOrMutated(t *testing.T) { func TestCreateOnlySkipsGatewayAndReadiness(t *testing.T) { opts := fixtureOptions() opts.Land, opts.Watch = false, true + readiness := NewMockReadiness(gomock.NewController(t)) + readiness.EXPECT().Wait(gomock.Any(), gomock.Any()).DoAndReturn(func(context.Context, Change) error { + return errors.New("create-only must not wait") + }).AnyTimes() + + source := NewMockSource(gomock.NewController(t)) + source.EXPECT().Open(gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, spec ChangeSpec) (Change, error) { return fixtureChange(spec), nil }).AnyTimes() + result, err := Run(context.Background(), opts, Dependencies{ - Source: sourceFunc(func(_ context.Context, spec ChangeSpec) (Change, error) { return fixtureChange(spec), nil }), - Readiness: readinessFunc(func(context.Context, Change) error { - return errors.New("create-only must not wait") - }), + Source: source, + Readiness: readiness, }) require.NoError(t, err) assert.Len(t, result.Changes, 3) @@ -263,11 +263,17 @@ func TestWatchReturnsHistoryAndTerminalVerdict(t *testing.T) { t.Run(terminal, func(t *testing.T) { opts := fixtureOptions() opts.Count, opts.Watch = 1, true - gateway := fixtureGateway() + gateway := NewMockGateway(gomock.NewController(t)) + gateway.EXPECT().Land(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, uris []string, _ mergestrategypb.Strategy) (string, error) { + return strings.Join(uris, ","), nil + }).AnyTimes() events := []*pb.HistoryEvent{{Status: "accepted"}, {Status: terminal, Metadata: map[string]string{"build_url": "build"}}} - gateway.history = func(context.Context, string, string) ([]*pb.HistoryEvent, error) { return events, nil } + gateway.EXPECT().History(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(context.Context, string, string) ([]*pb.HistoryEvent, error) { return events, nil }).AnyTimes() + source := NewMockSource(gomock.NewController(t)) + source.EXPECT().Open(gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, spec ChangeSpec) (Change, error) { return fixtureChange(spec), nil }).AnyTimes() + result, err := Run(context.Background(), opts, Dependencies{ - Source: sourceFunc(func(_ context.Context, spec ChangeSpec) (Change, error) { return fixtureChange(spec), nil }), + Source: source, Gateway: gateway, }) if terminal == "landed" { @@ -289,21 +295,27 @@ func TestWatchFailureDoesNotCancelCreationOrSubmission(t *testing.T) { opts.Count, opts.Concurrency, opts.Watch = 2, 2, true historyFailed := make(chan struct{}) var once sync.Once - gateway := fixtureGateway() - gateway.history = func(context.Context, string, string) ([]*pb.HistoryEvent, error) { + gateway := NewMockGateway(gomock.NewController(t)) + gateway.EXPECT().Land(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, uris []string, _ mergestrategypb.Strategy) (string, error) { + return strings.Join(uris, ","), nil + }).AnyTimes() + gateway.EXPECT().History(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(context.Context, string, string) ([]*pb.HistoryEvent, error) { once.Do(func() { close(historyFailed) }) return nil, status.Error(codes.PermissionDenied, "denied") - } + }).AnyTimes() + source := NewMockSource(gomock.NewController(t)) + source.EXPECT().Open(gomock.Any(), gomock.Any()).DoAndReturn(func(ctx context.Context, spec ChangeSpec) (Change, error) { + if !strings.HasSuffix(spec.Branch, "/1") { + <-historyFailed + } + if err := ctx.Err(); err != nil { + return Change{}, err + } + return fixtureChange(spec), nil + }).AnyTimes() + result, err := Run(context.Background(), opts, Dependencies{ - Source: sourceFunc(func(ctx context.Context, spec ChangeSpec) (Change, error) { - if !strings.HasSuffix(spec.Branch, "/1") { - <-historyFailed - } - if err := ctx.Err(); err != nil { - return Change{}, err - } - return fixtureChange(spec), nil - }), + Source: source, Gateway: gateway, }) require.Error(t, err) @@ -323,28 +335,35 @@ func TestSiblingFailureDoesNotCancelInFlightLand(t *testing.T) { landStarted := make(chan struct{}) siblingsCancelled := make(chan struct{}) var landErr error - gateway := fixtureGateway() - gateway.land = func(ctx context.Context, _ string, uris []string, _ mergestrategypb.Strategy) (string, error) { + gateway := NewMockGateway(gomock.NewController(t)) + gateway.EXPECT().History(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes() + gateway.EXPECT().Land(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(ctx context.Context, _ string, uris []string, _ mergestrategypb.Strategy) (string, error) { close(landStarted) <-siblingsCancelled landErr = ctx.Err() return strings.Join(uris, ","), nil - } + }).AnyTimes() + readiness := NewMockReadiness(gomock.NewController(t)) + readiness.EXPECT().Wait(gomock.Any(), gomock.Any()).DoAndReturn(func(gate context.Context, change Change) error { + switch { + case strings.HasSuffix(change.Branch, "/1"): + <-landStarted + return fmt.Errorf("not ready") + case strings.HasSuffix(change.Branch, "/3"): + <-gate.Done() + close(siblingsCancelled) + return gate.Err() + } + return nil + }).AnyTimes() + + source := NewMockSource(gomock.NewController(t)) + source.EXPECT().Open(gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, spec ChangeSpec) (Change, error) { return fixtureChange(spec), nil }).AnyTimes() + result, err := Run(context.Background(), opts, Dependencies{ - Source: sourceFunc(func(_ context.Context, spec ChangeSpec) (Change, error) { return fixtureChange(spec), nil }), - Gateway: gateway, - Readiness: readinessFunc(func(gate context.Context, change Change) error { - switch { - case strings.HasSuffix(change.Branch, "/1"): - <-landStarted - return fmt.Errorf("not ready") - case strings.HasSuffix(change.Branch, "/3"): - <-gate.Done() - close(siblingsCancelled) - return gate.Err() - } - return nil - }), + Source: source, + Gateway: gateway, + Readiness: readiness, }) require.Error(t, err) assert.NoError(t, landErr) @@ -374,13 +393,19 @@ func TestCallerCancellationDuringWatch(t *testing.T) { defer cancel() opts := fixtureOptions() opts.Count, opts.Watch = 1, true - gateway := fixtureGateway() - gateway.history = func(context.Context, string, string) ([]*pb.HistoryEvent, error) { + gateway := NewMockGateway(gomock.NewController(t)) + gateway.EXPECT().Land(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, uris []string, _ mergestrategypb.Strategy) (string, error) { + return strings.Join(uris, ","), nil + }).AnyTimes() + gateway.EXPECT().History(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(context.Context, string, string) ([]*pb.HistoryEvent, error) { cancel() return nil, context.Canceled - } + }).AnyTimes() + source := NewMockSource(gomock.NewController(t)) + source.EXPECT().Open(gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, spec ChangeSpec) (Change, error) { return fixtureChange(spec), nil }).AnyTimes() + result, err := Run(ctx, opts, Dependencies{ - Source: sourceFunc(func(_ context.Context, spec ChangeSpec) (Change, error) { return fixtureChange(spec), nil }), + Source: source, Gateway: gateway, }) require.ErrorIs(t, err, context.Canceled) @@ -391,10 +416,13 @@ func TestCallerCancellationDuringWatch(t *testing.T) { func TestWatchRetainsKnownHistoryAfterEmptyRead(t *testing.T) { opts := fixtureOptions() opts.Count, opts.Watch = 1, true - gateway := fixtureGateway() + gateway := NewMockGateway(gomock.NewController(t)) + gateway.EXPECT().Land(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, _ string, uris []string, _ mergestrategypb.Strategy) (string, error) { + return strings.Join(uris, ","), nil + }).AnyTimes() calls := 0 known := []*pb.HistoryEvent{{Status: "started", Metadata: map[string]string{"build_url": "build"}}} - gateway.history = func(context.Context, string, string) ([]*pb.HistoryEvent, error) { + gateway.EXPECT().History(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(context.Context, string, string) ([]*pb.HistoryEvent, error) { calls++ switch calls { case 1: @@ -404,9 +432,12 @@ func TestWatchRetainsKnownHistoryAfterEmptyRead(t *testing.T) { default: return nil, status.Error(codes.PermissionDenied, "denied") } - } + }).AnyTimes() + source := NewMockSource(gomock.NewController(t)) + source.EXPECT().Open(gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, spec ChangeSpec) (Change, error) { return fixtureChange(spec), nil }).AnyTimes() + result, err := Run(context.Background(), opts, Dependencies{ - Source: sourceFunc(func(_ context.Context, spec ChangeSpec) (Change, error) { return fixtureChange(spec), nil }), + Source: source, Gateway: gateway, }) require.Error(t, err) diff --git a/service/submitqueue/gateway/server/BUILD.bazel b/service/submitqueue/gateway/server/BUILD.bazel index 5e1709930..e3fe938ca 100644 --- a/service/submitqueue/gateway/server/BUILD.bazel +++ b/service/submitqueue/gateway/server/BUILD.bazel @@ -96,7 +96,7 @@ go_test( "//api/submitqueue/gateway/protopb:go_default_library", "//platform/base/failure:go_default_library", "//platform/base/messagequeue:go_default_library", - "//platform/consumer:go_default_library", + "//platform/consumer/mock:go_default_library", "//platform/errs:go_default_library", "//platform/extension/consumergate/noop:go_default_library", "//platform/extension/messagequeue:go_default_library", diff --git a/service/submitqueue/gateway/server/log_consumer_test.go b/service/submitqueue/gateway/server/log_consumer_test.go index ad52e957e..fe253cee2 100644 --- a/service/submitqueue/gateway/server/log_consumer_test.go +++ b/service/submitqueue/gateway/server/log_consumer_test.go @@ -24,7 +24,7 @@ import ( "github.com/uber-go/tally" "github.com/uber/submitqueue/platform/base/failure" entityqueue "github.com/uber/submitqueue/platform/base/messagequeue" - "github.com/uber/submitqueue/platform/consumer" + consumermock "github.com/uber/submitqueue/platform/consumer/mock" consumergatenoop "github.com/uber/submitqueue/platform/extension/consumergate/noop" extqueue "github.com/uber/submitqueue/platform/extension/messagequeue" queuemock "github.com/uber/submitqueue/platform/extension/messagequeue/mock" @@ -112,24 +112,6 @@ func TestLogConsumers_RetainFailedRecovery(t *testing.T) { } } -type lifecycleTestConsumer struct { - consumer.Consumer - name string - calls *[]string - startErr error - stopErr error -} - -func (c lifecycleTestConsumer) Start(context.Context) error { - *c.calls = append(*c.calls, "start:"+c.name) - return c.startErr -} - -func (c lifecycleTestConsumer) Stop(timeoutMs int64) error { - *c.calls = append(*c.calls, "stop:"+c.name) - return c.stopErr -} - func TestServeGateway_ConsumerCleanup(t *testing.T) { startErr := errors.New("subscribe unavailable") stopErr := errors.New("stop unavailable") @@ -149,9 +131,17 @@ func TestServeGateway_ConsumerCleanup(t *testing.T) { } { t.Run(tt.name, func(t *testing.T) { var calls []string + primary := consumermock.NewMockConsumer(gomock.NewController(t)) + primary.EXPECT().Start(gomock.Any()).DoAndReturn(func(context.Context) error { calls = append(calls, "start:primary"); return tt.primaryErr }).AnyTimes() + primary.EXPECT().Stop(gomock.Any()).DoAndReturn(func(int64) error { calls = append(calls, "stop:primary"); return tt.stopErr }).AnyTimes() + + recovery := consumermock.NewMockConsumer(gomock.NewController(t)) + recovery.EXPECT().Start(gomock.Any()).DoAndReturn(func(context.Context) error { calls = append(calls, "start:recovery"); return tt.recoveryErr }).AnyTimes() + recovery.EXPECT().Stop(gomock.Any()).DoAndReturn(func(int64) error { calls = append(calls, "stop:recovery"); return tt.stopErr }).AnyTimes() + group := lifecycle.NewGroup( - logConsumerLifecycle{Consumer: lifecycleTestConsumer{name: "primary", calls: &calls, startErr: tt.primaryErr, stopErr: tt.stopErr}}, - logConsumerLifecycle{Consumer: lifecycleTestConsumer{name: "recovery", calls: &calls, startErr: tt.recoveryErr, stopErr: tt.stopErr}}, + logConsumerLifecycle{Consumer: primary}, + logConsumerLifecycle{Consumer: recovery}, ) ctx, cancel := context.WithCancel(context.Background()) defer cancel() diff --git a/service/submitqueue/orchestrator/server/BUILD.bazel b/service/submitqueue/orchestrator/server/BUILD.bazel index 156161059..1fc42d89d 100644 --- a/service/submitqueue/orchestrator/server/BUILD.bazel +++ b/service/submitqueue/orchestrator/server/BUILD.bazel @@ -127,6 +127,7 @@ go_test( name = "go_default_test", srcs = [ "config_test.go", + "http_mock_test.go", "main_test.go", "profiles_test.go", "queuepausegate_test.go", @@ -158,6 +159,7 @@ go_test( "//submitqueue/extension/conflict/tango/tangoclient:go_default_library", "//submitqueue/extension/queuepause/fake:go_default_library", "//submitqueue/extension/speculation/scorer:go_default_library", + "//submitqueue/extension/speculation/scorer/mock:go_default_library", "//submitqueue/extension/speculation/speculator:go_default_library", "//submitqueue/extension/validator:go_default_library", "//submitqueue/orchestrator/extension/storage:go_default_library", diff --git a/service/submitqueue/orchestrator/server/http_mock_test.go b/service/submitqueue/orchestrator/server/http_mock_test.go new file mode 100644 index 000000000..a2cfaf0f6 --- /dev/null +++ b/service/submitqueue/orchestrator/server/http_mock_test.go @@ -0,0 +1,56 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: net/http (interfaces: RoundTripper) +// +// Generated by this command: +// +// mockgen -destination=http_mock_test.go -package=main net/http RoundTripper +// + +// Package main is a generated GoMock package. +package main + +import ( + http "net/http" + reflect "reflect" + + gomock "go.uber.org/mock/gomock" +) + +// MockRoundTripper is a mock of RoundTripper interface. +type MockRoundTripper struct { + ctrl *gomock.Controller + recorder *MockRoundTripperMockRecorder + isgomock struct{} +} + +// MockRoundTripperMockRecorder is the mock recorder for MockRoundTripper. +type MockRoundTripperMockRecorder struct { + mock *MockRoundTripper +} + +// NewMockRoundTripper creates a new mock instance. +func NewMockRoundTripper(ctrl *gomock.Controller) *MockRoundTripper { + mock := &MockRoundTripper{ctrl: ctrl} + mock.recorder = &MockRoundTripperMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockRoundTripper) EXPECT() *MockRoundTripperMockRecorder { + return m.recorder +} + +// RoundTrip mocks base method. +func (m *MockRoundTripper) RoundTrip(arg0 *http.Request) (*http.Response, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "RoundTrip", arg0) + ret0, _ := ret[0].(*http.Response) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// RoundTrip indicates an expected call of RoundTrip. +func (mr *MockRoundTripperMockRecorder) RoundTrip(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RoundTrip", reflect.TypeOf((*MockRoundTripper)(nil).RoundTrip), arg0) +} diff --git a/service/submitqueue/orchestrator/server/main_test.go b/service/submitqueue/orchestrator/server/main_test.go index 1778b9910..ebd080d7b 100644 --- a/service/submitqueue/orchestrator/server/main_test.go +++ b/service/submitqueue/orchestrator/server/main_test.go @@ -14,6 +14,8 @@ package main +//go:generate mockgen -destination=http_mock_test.go -package=main net/http RoundTripper + import ( "context" "database/sql/driver" @@ -30,6 +32,7 @@ import ( "github.com/uber/submitqueue/platform/errs" gitrepo "github.com/uber/submitqueue/platform/git/repo" "github.com/uber/submitqueue/platform/githubactions" + "go.uber.org/mock/gomock" ) func TestPrimaryErrorClassifiers_BuildStatus(t *testing.T) { @@ -50,17 +53,20 @@ func TestPrimaryErrorClassifiers_BuildStatus(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + transport := NewMockRoundTripper(gomock.NewController(t)) + transport.EXPECT().RoundTrip(gomock.Any()).DoAndReturn(func(req *http.Request) (*http.Response, error) { + if tt.transportErr != nil { + return nil, tt.transportErr + } + return &http.Response{ + StatusCode: tt.status, + Body: io.NopCloser(strings.NewReader("upstream failure")), + Request: req, + }, nil + }).AnyTimes() + client := githubactions.NewClient(&http.Client{ - Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) { - if tt.transportErr != nil { - return nil, tt.transportErr - } - return &http.Response{ - StatusCode: tt.status, - Body: io.NopCloser(strings.NewReader("upstream failure")), - Request: req, - }, nil - }), + Transport: transport, }, "owner", "repo", "ci.yml") _, err := client.GetRun(context.Background(), 42) @@ -137,9 +143,3 @@ func TestPrimaryErrorClassifiers_GitFetch(t *testing.T) { }) } } - -type roundTripFunc func(*http.Request) (*http.Response, error) - -func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { - return f(req) -} diff --git a/service/submitqueue/orchestrator/server/profiles_test.go b/service/submitqueue/orchestrator/server/profiles_test.go index f1c7da48b..5f2afa14e 100644 --- a/service/submitqueue/orchestrator/server/profiles_test.go +++ b/service/submitqueue/orchestrator/server/profiles_test.go @@ -15,20 +15,20 @@ package main import ( - "context" "errors" "testing" orchstorage "github.com/uber/submitqueue/submitqueue/orchestrator/extension/storage" + "go.uber.org/mock/gomock" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/uber/submitqueue/submitqueue/entity" "github.com/uber/submitqueue/submitqueue/extension/buildrunner" "github.com/uber/submitqueue/submitqueue/extension/changeprovider" "github.com/uber/submitqueue/submitqueue/extension/conflict" "github.com/uber/submitqueue/submitqueue/extension/speculation/scorer" + scorermock "github.com/uber/submitqueue/submitqueue/extension/speculation/scorer/mock" "github.com/uber/submitqueue/submitqueue/extension/speculation/speculator" "github.com/uber/submitqueue/submitqueue/extension/validator" ) @@ -44,18 +44,13 @@ type recorder struct { scorer string } -// stubScorer stands in wherever a Profile's scorer has to be real rather than -// nil, because something is composed over it. -type stubScorer struct{} - -func (stubScorer) Score(_ context.Context, _ entity.Batch, _ entity.SpeculationPathSet) (float64, error) { - return 0.5, nil -} - // profileRecording returns a Profile whose every factory records the queue name // it receives into rec and returns a nil implementation. Nil is fine: these // tests are about what reaches the factory, not what it builds. -func profileRecording(rec *recorder) Profile { +func profileRecording(t *testing.T, rec *recorder) Profile { + t.Helper() + price := scorermock.NewMockScorer(gomock.NewController(t)) + price.EXPECT().Score(gomock.Any(), gomock.Any(), gomock.Any()).Return(0.5, nil).AnyTimes() return Profile{ ChangeProvider: changeProviderFunc(func(c changeprovider.Config) (changeprovider.ChangeProvider, error) { rec.changeProvider = c.QueueName @@ -79,7 +74,7 @@ func profileRecording(rec *recorder) Profile { }), Scorer: scorerFunc(func(c scorer.Config) (scorer.Scorer, error) { rec.scorer = c.QueueName - return stubScorer{}, nil + return price, nil }), } } @@ -104,7 +99,7 @@ func TestProfilesForwardQueueNameToFactories(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { var rec recorder - profile := profileRecording(&rec) + profile := profileRecording(t, &rec) profiles := Profiles{ defaultProfile: profile, byQueue: map[string]Profile{"listed-queue": profile}, @@ -138,7 +133,7 @@ func TestProfilesForwardQueueNameToFactories(t *testing.T) { // the wrong one. func TestWithSpeculatorResolvesScorerAtSameQueue(t *testing.T) { var rec recorder - profile := withSpeculator(profileRecording(&rec), defaultBuildBudget) + profile := withSpeculator(profileRecording(t, &rec), defaultBuildBudget) profiles := Profiles{defaultProfile: profile} spec, err := profiles.SpeculatorFactory().For(speculator.Config{QueueName: "unlisted-queue"}) diff --git a/submitqueue/client/BUILD.bazel b/submitqueue/client/BUILD.bazel index 8885a75e7..2a87487cc 100644 --- a/submitqueue/client/BUILD.bazel +++ b/submitqueue/client/BUILD.bazel @@ -35,6 +35,7 @@ go_test( "query_test.go", "tui_test.go", "view_test.go", + "watch_mock_test.go", ], embed = [":go_default_library"], deps = [ @@ -46,5 +47,6 @@ go_test( "@org_golang_google_grpc//codes:go_default_library", "@org_golang_google_grpc//metadata:go_default_library", "@org_golang_google_grpc//status:go_default_library", + "@org_uber_go_mock//gomock:go_default_library", ], ) diff --git a/submitqueue/client/history_read_test.go b/submitqueue/client/history_read_test.go index 5c5a16589..fc8ea825e 100644 --- a/submitqueue/client/history_read_test.go +++ b/submitqueue/client/history_read_test.go @@ -22,6 +22,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "go.uber.org/mock/gomock" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -30,31 +31,18 @@ import ( "github.com/uber/submitqueue/platform/errs" ) -type historyReaderFunc func(context.Context, string, string) ([]*pb.HistoryEvent, error) - -func (f historyReaderFunc) History(ctx context.Context, queue, sqid string) ([]*pb.HistoryEvent, error) { - return f(ctx, queue, sqid) -} - -type historySourceFunc func(context.Context, *pb.GetRequestHistoryByIDRequest) (*pb.GetRequestHistoryByIDResponse, error) - -func (f historySourceFunc) GetRequestHistoryByID( - ctx context.Context, request *pb.GetRequestHistoryByIDRequest, _ ...grpc.CallOption, -) (*pb.GetRequestHistoryByIDResponse, error) { - return f(ctx, request) -} - func TestPollHistoryPermanentFailures(t *testing.T) { for _, code := range []codes.Code{codes.PermissionDenied, codes.Unauthenticated, codes.InvalidArgument} { t.Run(code.String(), func(t *testing.T) { row := &Row{SQID: "opaque/id", Status: "speculating", Trail: []string{"accepted", "speculating"}} tracker := NewTracker([]*Row{row}) failure := status.Error(code, "read rejected") - reader := historyReaderFunc(func(_ context.Context, queue, sqid string) ([]*pb.HistoryEvent, error) { + reader := NewMockHistoryReader(gomock.NewController(t)) + reader.EXPECT().History(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, queue, sqid string) ([]*pb.HistoryEvent, error) { assert.Equal(t, "dummy-queue", queue) assert.Equal(t, "opaque/id", sqid) return nil, failure - }) + }).AnyTimes() var err error captureStdout(t, func() { tracker.Seal() @@ -84,13 +72,16 @@ func TestHistoryTransientDiagnosticsPreserveRecordedError(t *testing.T) { t.Run(fmt.Sprintf("%T-%v", failure, status.Code(failure)), func(t *testing.T) { row := &Row{SQID: "1"} tracker := NewTracker([]*Row{row}) - reader := historyReaderFunc(func(context.Context, string, string) ([]*pb.HistoryEvent, error) { - return []*pb.HistoryEvent{{Status: "speculating", LastError: "build failed"}}, nil - }) + events := []*pb.HistoryEvent{{Status: "speculating", LastError: "build failed"}} + var readErr error + reader := NewMockHistoryReader(gomock.NewController(t)) + reader.EXPECT().History(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(context.Context, string, string) ([]*pb.HistoryEvent, error) { + return events, readErr + }).AnyTimes() captureStdout(t, func() { require.NoError(t, tracker.refreshHistory(context.Background(), reader, "queue", true)) }) - reader = func(context.Context, string, string) ([]*pb.HistoryEvent, error) { return nil, failure } + events, readErr = nil, failure captureStdout(t, func() { require.NoError(t, tracker.refreshHistory(context.Background(), reader, "queue", true)) require.NoError(t, tracker.refreshHistory(context.Background(), reader, "queue", true)) @@ -99,9 +90,7 @@ func TestHistoryTransientDiagnosticsPreserveRecordedError(t *testing.T) { assert.Equal(t, "speculating", row.Status) assert.False(t, row.Done) - reader = func(context.Context, string, string) ([]*pb.HistoryEvent, error) { - return []*pb.HistoryEvent{{Status: "landed"}}, nil - } + events, readErr = []*pb.HistoryEvent{{Status: "landed"}}, nil captureStdout(t, func() { tracker.Seal() require.NoError(t, tracker.refreshHistory(context.Background(), reader, "queue", true)) @@ -117,13 +106,14 @@ func TestHistoryTransientDiagnosticsPreserveRecordedError(t *testing.T) { func TestPollHistoryRetriesUntilSettled(t *testing.T) { tracker := NewTracker([]*Row{{SQID: "1"}}) calls := 0 - reader := historyReaderFunc(func(context.Context, string, string) ([]*pb.HistoryEvent, error) { + reader := NewMockHistoryReader(gomock.NewController(t)) + reader.EXPECT().History(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(context.Context, string, string) ([]*pb.HistoryEvent, error) { calls++ if calls == 1 { return nil, status.Error(codes.Unavailable, "retry") } return []*pb.HistoryEvent{{Status: "landed"}}, nil - }) + }).AnyTimes() captureStdout(t, func() { tracker.Seal() require.NoError(t, tracker.PollHistory(context.Background(), reader, "queue")) @@ -137,12 +127,14 @@ func TestHistoryPendingReadPreservesStatus(t *testing.T) { t.Run(status.Code(failure).String(), func(t *testing.T) { row := &Row{SQID: "1", Status: "speculating", Note: "build failed"} tracker := NewTracker([]*Row{row}) - unavailable := historyReaderFunc(func(context.Context, string, string) ([]*pb.HistoryEvent, error) { + unavailable := NewMockHistoryReader(gomock.NewController(t)) + unavailable.EXPECT().History(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(context.Context, string, string) ([]*pb.HistoryEvent, error) { return nil, status.Error(codes.Unavailable, "temporary") - }) - pending := historyReaderFunc(func(context.Context, string, string) ([]*pb.HistoryEvent, error) { + }).AnyTimes() + pending := NewMockHistoryReader(gomock.NewController(t)) + pending.EXPECT().History(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(context.Context, string, string) ([]*pb.HistoryEvent, error) { return nil, failure - }) + }).AnyTimes() captureStdout(t, func() { require.NoError(t, tracker.refreshHistory(context.Background(), unavailable, "queue", true)) require.NoError(t, tracker.refreshHistory(context.Background(), pending, "queue", true)) @@ -161,11 +153,12 @@ func TestPollHistoryContextCancellation(t *testing.T) { defer cancel() tracker := NewTracker([]*Row{{SQID: "1"}}) calls := 0 - reader := historyReaderFunc(func(ctx context.Context, _, _ string) ([]*pb.HistoryEvent, error) { + reader := NewMockHistoryReader(gomock.NewController(t)) + reader.EXPECT().History(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(ctx context.Context, _, _ string) ([]*pb.HistoryEvent, error) { calls++ cancel() return nil, ctx.Err() - }) + }).AnyTimes() if !cancelDuringRead { cancel() } @@ -185,9 +178,10 @@ func TestPollHistoryContextCancellation(t *testing.T) { func TestLegacyRefreshStillToleratesPermanentErrors(t *testing.T) { row := &Row{SQID: "1", Status: "accepted", Note: "existing note"} tracker := NewTracker([]*Row{row}) - source := historySourceFunc(func(context.Context, *pb.GetRequestHistoryByIDRequest) (*pb.GetRequestHistoryByIDResponse, error) { + source := NewMockHistorySource(gomock.NewController(t)) + source.EXPECT().GetRequestHistoryByID(gomock.Any(), gomock.Any()).DoAndReturn(func(context.Context, *pb.GetRequestHistoryByIDRequest, ...grpc.CallOption) (*pb.GetRequestHistoryByIDResponse, error) { return nil, status.Error(codes.PermissionDenied, "legacy ignored") - }) + }).AnyTimes() captureStdout(t, func() { tracker.refresh(context.Background(), source, "queue") }) assert.Equal(t, "accepted", row.Status) assert.Equal(t, "existing note", row.Note) diff --git a/submitqueue/client/watch.go b/submitqueue/client/watch.go index b90a18b42..e1d163990 100644 --- a/submitqueue/client/watch.go +++ b/submitqueue/client/watch.go @@ -14,6 +14,8 @@ package client +//go:generate mockgen -source=watch.go -destination=watch_mock_test.go -package=client + import ( "context" "fmt" diff --git a/submitqueue/client/watch_mock_test.go b/submitqueue/client/watch_mock_test.go new file mode 100644 index 000000000..14ccec530 --- /dev/null +++ b/submitqueue/client/watch_mock_test.go @@ -0,0 +1,102 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: watch.go +// +// Generated by this command: +// +// mockgen -source=watch.go -destination=watch_mock_test.go -package=client +// + +// Package client is a generated GoMock package. +package client + +import ( + context "context" + reflect "reflect" + + protopb "github.com/uber/submitqueue/api/submitqueue/gateway/protopb" + gomock "go.uber.org/mock/gomock" + grpc "google.golang.org/grpc" +) + +// MockHistorySource is a mock of HistorySource interface. +type MockHistorySource struct { + ctrl *gomock.Controller + recorder *MockHistorySourceMockRecorder + isgomock struct{} +} + +// MockHistorySourceMockRecorder is the mock recorder for MockHistorySource. +type MockHistorySourceMockRecorder struct { + mock *MockHistorySource +} + +// NewMockHistorySource creates a new mock instance. +func NewMockHistorySource(ctrl *gomock.Controller) *MockHistorySource { + mock := &MockHistorySource{ctrl: ctrl} + mock.recorder = &MockHistorySourceMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockHistorySource) EXPECT() *MockHistorySourceMockRecorder { + return m.recorder +} + +// GetRequestHistoryByID mocks base method. +func (m *MockHistorySource) GetRequestHistoryByID(ctx context.Context, in *protopb.GetRequestHistoryByIDRequest, opts ...grpc.CallOption) (*protopb.GetRequestHistoryByIDResponse, error) { + m.ctrl.T.Helper() + varargs := []any{ctx, in} + for _, a := range opts { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "GetRequestHistoryByID", varargs...) + ret0, _ := ret[0].(*protopb.GetRequestHistoryByIDResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetRequestHistoryByID indicates an expected call of GetRequestHistoryByID. +func (mr *MockHistorySourceMockRecorder) GetRequestHistoryByID(ctx, in any, opts ...any) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]any{ctx, in}, opts...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRequestHistoryByID", reflect.TypeOf((*MockHistorySource)(nil).GetRequestHistoryByID), varargs...) +} + +// MockHistoryReader is a mock of HistoryReader interface. +type MockHistoryReader struct { + ctrl *gomock.Controller + recorder *MockHistoryReaderMockRecorder + isgomock struct{} +} + +// MockHistoryReaderMockRecorder is the mock recorder for MockHistoryReader. +type MockHistoryReaderMockRecorder struct { + mock *MockHistoryReader +} + +// NewMockHistoryReader creates a new mock instance. +func NewMockHistoryReader(ctrl *gomock.Controller) *MockHistoryReader { + mock := &MockHistoryReader{ctrl: ctrl} + mock.recorder = &MockHistoryReaderMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockHistoryReader) EXPECT() *MockHistoryReaderMockRecorder { + return m.recorder +} + +// History mocks base method. +func (m *MockHistoryReader) History(ctx context.Context, queue, sqid string) ([]*protopb.HistoryEvent, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "History", ctx, queue, sqid) + ret0, _ := ret[0].([]*protopb.HistoryEvent) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// History indicates an expected call of History. +func (mr *MockHistoryReaderMockRecorder) History(ctx, queue, sqid any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "History", reflect.TypeOf((*MockHistoryReader)(nil).History), ctx, queue, sqid) +} diff --git a/submitqueue/core/changeset/BUILD.bazel b/submitqueue/core/changeset/BUILD.bazel index 3a73067f2..8d3000499 100644 --- a/submitqueue/core/changeset/BUILD.bazel +++ b/submitqueue/core/changeset/BUILD.bazel @@ -17,7 +17,10 @@ go_library( go_test( name = "go_default_test", - srcs = ["resolver_test.go"], + srcs = [ + "resolver_mock_test.go", + "resolver_test.go", + ], embed = [":go_default_library"], deps = [ "//platform/base/change:go_default_library", diff --git a/submitqueue/core/changeset/resolver.go b/submitqueue/core/changeset/resolver.go index 0a76a9f81..9559ddeba 100644 --- a/submitqueue/core/changeset/resolver.go +++ b/submitqueue/core/changeset/resolver.go @@ -14,6 +14,8 @@ package changeset +//go:generate mockgen -source=resolver.go -destination=resolver_mock_test.go -package=changeset + import ( "context" "fmt" diff --git a/submitqueue/core/changeset/resolver_mock_test.go b/submitqueue/core/changeset/resolver_mock_test.go new file mode 100644 index 000000000..4149057ab --- /dev/null +++ b/submitqueue/core/changeset/resolver_mock_test.go @@ -0,0 +1,69 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: resolver.go +// +// Generated by this command: +// +// mockgen -source=resolver.go -destination=resolver_mock_test.go -package=changeset +// + +// Package changeset is a generated GoMock package. +package changeset + +import ( + reflect "reflect" + + storage "github.com/uber/submitqueue/submitqueue/extension/storage" + gomock "go.uber.org/mock/gomock" +) + +// MockStores is a mock of Stores interface. +type MockStores struct { + ctrl *gomock.Controller + recorder *MockStoresMockRecorder + isgomock struct{} +} + +// MockStoresMockRecorder is the mock recorder for MockStores. +type MockStoresMockRecorder struct { + mock *MockStores +} + +// NewMockStores creates a new mock instance. +func NewMockStores(ctrl *gomock.Controller) *MockStores { + mock := &MockStores{ctrl: ctrl} + mock.recorder = &MockStoresMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockStores) EXPECT() *MockStoresMockRecorder { + return m.recorder +} + +// GetChangeStore mocks base method. +func (m *MockStores) GetChangeStore() storage.ChangeStore { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetChangeStore") + ret0, _ := ret[0].(storage.ChangeStore) + return ret0 +} + +// GetChangeStore indicates an expected call of GetChangeStore. +func (mr *MockStoresMockRecorder) GetChangeStore() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetChangeStore", reflect.TypeOf((*MockStores)(nil).GetChangeStore)) +} + +// GetRequestStore mocks base method. +func (m *MockStores) GetRequestStore() storage.RequestStore { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetRequestStore") + ret0, _ := ret[0].(storage.RequestStore) + return ret0 +} + +// GetRequestStore indicates an expected call of GetRequestStore. +func (mr *MockStoresMockRecorder) GetRequestStore() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRequestStore", reflect.TypeOf((*MockStores)(nil).GetRequestStore)) +} diff --git a/submitqueue/core/changeset/resolver_test.go b/submitqueue/core/changeset/resolver_test.go index fd5583289..e74f46e0f 100644 --- a/submitqueue/core/changeset/resolver_test.go +++ b/submitqueue/core/changeset/resolver_test.go @@ -29,21 +29,13 @@ import ( storagemock "github.com/uber/submitqueue/submitqueue/extension/storage/mock" ) -// stubStores is the two-accessor slice of an aggregate this package needs, -// which is all Stores asks for — no service aggregate is involved. -type stubStores struct { - reqs storage.RequestStore - changes storage.ChangeStore -} - -func (s stubStores) GetRequestStore() storage.RequestStore { return s.reqs } - -func (s stubStores) GetChangeStore() storage.ChangeStore { return s.changes } - // newTestResolver builds a Resolver that binds every queue to the same stores. -func newTestResolver(_ *gomock.Controller, reqs storage.RequestStore, changes storage.ChangeStore) Resolver { +func newTestResolver(ctrl *gomock.Controller, reqs storage.RequestStore, changes storage.ChangeStore) Resolver { + stores := NewMockStores(ctrl) + stores.EXPECT().GetRequestStore().Return(reqs).AnyTimes() + stores.EXPECT().GetChangeStore().Return(changes).AnyTimes() return New(func(string) (Stores, error) { - return stubStores{reqs: reqs, changes: changes}, nil + return stores, nil }) } diff --git a/submitqueue/extension/conflict/tango/tangoclient/BUILD.bazel b/submitqueue/extension/conflict/tango/tangoclient/BUILD.bazel index a920722c3..afd8643d2 100644 --- a/submitqueue/extension/conflict/tango/tangoclient/BUILD.bazel +++ b/submitqueue/extension/conflict/tango/tangoclient/BUILD.bazel @@ -22,6 +22,7 @@ go_test( name = "go_default_test", srcs = [ "connection_test.go", + "tango_mock_test.go", "tangoclient_test.go", ], embed = [":go_default_library"], @@ -31,6 +32,7 @@ go_test( "@com_github_stretchr_testify//require:go_default_library", "@com_github_uber_go_tally//:go_default_library", "@com_github_uber_tango//tangopb:go_default_library", + "@org_uber_go_mock//gomock:go_default_library", "@org_uber_go_yarpc//:go_default_library", ], ) diff --git a/submitqueue/extension/conflict/tango/tangoclient/tango_mock_test.go b/submitqueue/extension/conflict/tango/tangoclient/tango_mock_test.go new file mode 100644 index 000000000..d92f684d4 --- /dev/null +++ b/submitqueue/extension/conflict/tango/tangoclient/tango_mock_test.go @@ -0,0 +1,178 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/uber/tango/tangopb (interfaces: TangoYARPCClient,TangoServiceGetChangedTargetsYARPCClient) +// +// Generated by this command: +// +// mockgen -destination=tango_mock_test.go -package=tangoclient github.com/uber/tango/tangopb TangoYARPCClient,TangoServiceGetChangedTargetsYARPCClient +// + +// Package tangoclient is a generated GoMock package. +package tangoclient + +import ( + context "context" + reflect "reflect" + + tangopb "github.com/uber/tango/tangopb" + gomock "go.uber.org/mock/gomock" + yarpc "go.uber.org/yarpc" +) + +// MockTangoYARPCClient is a mock of TangoYARPCClient interface. +type MockTangoYARPCClient struct { + ctrl *gomock.Controller + recorder *MockTangoYARPCClientMockRecorder + isgomock struct{} +} + +// MockTangoYARPCClientMockRecorder is the mock recorder for MockTangoYARPCClient. +type MockTangoYARPCClientMockRecorder struct { + mock *MockTangoYARPCClient +} + +// NewMockTangoYARPCClient creates a new mock instance. +func NewMockTangoYARPCClient(ctrl *gomock.Controller) *MockTangoYARPCClient { + mock := &MockTangoYARPCClient{ctrl: ctrl} + mock.recorder = &MockTangoYARPCClientMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockTangoYARPCClient) EXPECT() *MockTangoYARPCClientMockRecorder { + return m.recorder +} + +// GetChangedTargetGraph mocks base method. +func (m *MockTangoYARPCClient) GetChangedTargetGraph(arg0 context.Context, arg1 *tangopb.GetChangedTargetGraphRequest, arg2 ...yarpc.CallOption) (tangopb.TangoServiceGetChangedTargetGraphYARPCClient, error) { + m.ctrl.T.Helper() + varargs := []any{arg0, arg1} + for _, a := range arg2 { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "GetChangedTargetGraph", varargs...) + ret0, _ := ret[0].(tangopb.TangoServiceGetChangedTargetGraphYARPCClient) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetChangedTargetGraph indicates an expected call of GetChangedTargetGraph. +func (mr *MockTangoYARPCClientMockRecorder) GetChangedTargetGraph(arg0, arg1 any, arg2 ...any) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]any{arg0, arg1}, arg2...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetChangedTargetGraph", reflect.TypeOf((*MockTangoYARPCClient)(nil).GetChangedTargetGraph), varargs...) +} + +// GetChangedTargets mocks base method. +func (m *MockTangoYARPCClient) GetChangedTargets(arg0 context.Context, arg1 *tangopb.GetChangedTargetsRequest, arg2 ...yarpc.CallOption) (tangopb.TangoServiceGetChangedTargetsYARPCClient, error) { + m.ctrl.T.Helper() + varargs := []any{arg0, arg1} + for _, a := range arg2 { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "GetChangedTargets", varargs...) + ret0, _ := ret[0].(tangopb.TangoServiceGetChangedTargetsYARPCClient) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetChangedTargets indicates an expected call of GetChangedTargets. +func (mr *MockTangoYARPCClientMockRecorder) GetChangedTargets(arg0, arg1 any, arg2 ...any) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]any{arg0, arg1}, arg2...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetChangedTargets", reflect.TypeOf((*MockTangoYARPCClient)(nil).GetChangedTargets), varargs...) +} + +// GetTargetGraph mocks base method. +func (m *MockTangoYARPCClient) GetTargetGraph(arg0 context.Context, arg1 *tangopb.GetTargetGraphRequest, arg2 ...yarpc.CallOption) (tangopb.TangoServiceGetTargetGraphYARPCClient, error) { + m.ctrl.T.Helper() + varargs := []any{arg0, arg1} + for _, a := range arg2 { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "GetTargetGraph", varargs...) + ret0, _ := ret[0].(tangopb.TangoServiceGetTargetGraphYARPCClient) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetTargetGraph indicates an expected call of GetTargetGraph. +func (mr *MockTangoYARPCClientMockRecorder) GetTargetGraph(arg0, arg1 any, arg2 ...any) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]any{arg0, arg1}, arg2...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTargetGraph", reflect.TypeOf((*MockTangoYARPCClient)(nil).GetTargetGraph), varargs...) +} + +// MockTangoServiceGetChangedTargetsYARPCClient is a mock of TangoServiceGetChangedTargetsYARPCClient interface. +type MockTangoServiceGetChangedTargetsYARPCClient struct { + ctrl *gomock.Controller + recorder *MockTangoServiceGetChangedTargetsYARPCClientMockRecorder + isgomock struct{} +} + +// MockTangoServiceGetChangedTargetsYARPCClientMockRecorder is the mock recorder for MockTangoServiceGetChangedTargetsYARPCClient. +type MockTangoServiceGetChangedTargetsYARPCClientMockRecorder struct { + mock *MockTangoServiceGetChangedTargetsYARPCClient +} + +// NewMockTangoServiceGetChangedTargetsYARPCClient creates a new mock instance. +func NewMockTangoServiceGetChangedTargetsYARPCClient(ctrl *gomock.Controller) *MockTangoServiceGetChangedTargetsYARPCClient { + mock := &MockTangoServiceGetChangedTargetsYARPCClient{ctrl: ctrl} + mock.recorder = &MockTangoServiceGetChangedTargetsYARPCClientMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockTangoServiceGetChangedTargetsYARPCClient) EXPECT() *MockTangoServiceGetChangedTargetsYARPCClientMockRecorder { + return m.recorder +} + +// CloseSend mocks base method. +func (m *MockTangoServiceGetChangedTargetsYARPCClient) CloseSend(arg0 ...yarpc.StreamOption) error { + m.ctrl.T.Helper() + varargs := []any{} + for _, a := range arg0 { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "CloseSend", varargs...) + ret0, _ := ret[0].(error) + return ret0 +} + +// CloseSend indicates an expected call of CloseSend. +func (mr *MockTangoServiceGetChangedTargetsYARPCClientMockRecorder) CloseSend(arg0 ...any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CloseSend", reflect.TypeOf((*MockTangoServiceGetChangedTargetsYARPCClient)(nil).CloseSend), arg0...) +} + +// Context mocks base method. +func (m *MockTangoServiceGetChangedTargetsYARPCClient) Context() context.Context { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Context") + ret0, _ := ret[0].(context.Context) + return ret0 +} + +// Context indicates an expected call of Context. +func (mr *MockTangoServiceGetChangedTargetsYARPCClientMockRecorder) Context() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Context", reflect.TypeOf((*MockTangoServiceGetChangedTargetsYARPCClient)(nil).Context)) +} + +// Recv mocks base method. +func (m *MockTangoServiceGetChangedTargetsYARPCClient) Recv(arg0 ...yarpc.StreamOption) (*tangopb.GetChangedTargetsResponse, error) { + m.ctrl.T.Helper() + varargs := []any{} + for _, a := range arg0 { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "Recv", varargs...) + ret0, _ := ret[0].(*tangopb.GetChangedTargetsResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Recv indicates an expected call of Recv. +func (mr *MockTangoServiceGetChangedTargetsYARPCClientMockRecorder) Recv(arg0 ...any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Recv", reflect.TypeOf((*MockTangoServiceGetChangedTargetsYARPCClient)(nil).Recv), arg0...) +} diff --git a/submitqueue/extension/conflict/tango/tangoclient/tangoclient_test.go b/submitqueue/extension/conflict/tango/tangoclient/tangoclient_test.go index 6099bc2a8..115063e26 100644 --- a/submitqueue/extension/conflict/tango/tangoclient/tangoclient_test.go +++ b/submitqueue/extension/conflict/tango/tangoclient/tangoclient_test.go @@ -14,6 +14,8 @@ package tangoclient +//go:generate mockgen -destination=tango_mock_test.go -package=tangoclient github.com/uber/tango/tangopb TangoYARPCClient,TangoServiceGetChangedTargetsYARPCClient + import ( "context" "errors" @@ -24,6 +26,7 @@ import ( "github.com/stretchr/testify/require" "github.com/uber-go/tally" "github.com/uber/tango/tangopb" + "go.uber.org/mock/gomock" "go.uber.org/yarpc" "github.com/uber/submitqueue/submitqueue/extension/conflict/tango" @@ -33,44 +36,9 @@ const testBaseRevision = "9f2c1d0e3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d" var errTestFailure = errors.New("dependency down") -type fakeTango struct { - tangopb.TangoYARPCClient - stream *fakeStream - openErr error - request *tangopb.GetChangedTargetsRequest -} - -func (f *fakeTango) GetChangedTargets(_ context.Context, request *tangopb.GetChangedTargetsRequest, _ ...yarpc.CallOption) (tangopb.TangoServiceGetChangedTargetsYARPCClient, error) { - f.request = request - if f.openErr != nil { - return nil, f.openErr - } - return f.stream, nil -} - -type fakeStream struct { +type streamFixture struct { responses []*tangopb.GetChangedTargetsResponse endErr error - closed bool -} - -func (s *fakeStream) Context() context.Context { return context.Background() } - -func (s *fakeStream) Recv(...yarpc.StreamOption) (*tangopb.GetChangedTargetsResponse, error) { - if len(s.responses) == 0 { - if s.endErr != nil { - return nil, s.endErr - } - return nil, io.EOF - } - response := s.responses[0] - s.responses = s.responses[1:] - return response, nil -} - -func (s *fakeStream) CloseSend(...yarpc.StreamOption) error { - s.closed = true - return nil } func changedTargets(targets ...*tangopb.ChangedTarget) *tangopb.GetChangedTargetsResponse { @@ -99,14 +67,14 @@ func target(changeType tangopb.ChangeType, oldID, newID, distance int32) *tangop func TestClient_ChangedTargets(t *testing.T) { tests := []struct { name string - stream *fakeStream + stream *streamFixture openErr error want []tango.LabelDistance wantError bool }{ { name: "labels targets across stream chunks", - stream: &fakeStream{responses: []*tangopb.GetChangedTargetsResponse{ + stream: &streamFixture{responses: []*tangopb.GetChangedTargetsResponse{ changedTargets(target(tangopb.CHANGE_TYPE_CHANGED, 1, 1, 0), target(tangopb.CHANGE_TYPE_NEW, 0, 2, 0)), changedTargets(target(tangopb.CHANGE_TYPE_CHANGED, 3, 3, 2)), metadata(map[int32]string{1: "//app:lib", 2: "//app:new", 3: "//app:bin"}), @@ -119,7 +87,7 @@ func TestClient_ChangedTargets(t *testing.T) { }, { name: "deleted target is labeled by its old ID", - stream: &fakeStream{responses: []*tangopb.GetChangedTargetsResponse{ + stream: &streamFixture{responses: []*tangopb.GetChangedTargetsResponse{ changedTargets(target(tangopb.CHANGE_TYPE_DELETED, 7, 0, 0)), metadata(map[int32]string{7: "//app:gone"}), }}, @@ -127,12 +95,12 @@ func TestClient_ChangedTargets(t *testing.T) { }, { name: "empty result is valid", - stream: &fakeStream{}, + stream: &streamFixture{}, want: []tango.LabelDistance{}, }, { name: "metadata alone is an empty result", - stream: &fakeStream{responses: []*tangopb.GetChangedTargetsResponse{ + stream: &streamFixture{responses: []*tangopb.GetChangedTargetsResponse{ metadata(map[int32]string{}), }}, want: []tango.LabelDistance{}, @@ -144,7 +112,7 @@ func TestClient_ChangedTargets(t *testing.T) { }, { name: "stream error fails", - stream: &fakeStream{ + stream: &streamFixture{ responses: []*tangopb.GetChangedTargetsResponse{changedTargets(target(tangopb.CHANGE_TYPE_NEW, 0, 1, 0))}, endErr: errTestFailure, }, @@ -152,14 +120,14 @@ func TestClient_ChangedTargets(t *testing.T) { }, { name: "targets without metadata fail", - stream: &fakeStream{responses: []*tangopb.GetChangedTargetsResponse{ + stream: &streamFixture{responses: []*tangopb.GetChangedTargetsResponse{ changedTargets(target(tangopb.CHANGE_TYPE_NEW, 0, 1, 0)), }}, wantError: true, }, { name: "target missing from the mapping fails", - stream: &fakeStream{responses: []*tangopb.GetChangedTargetsResponse{ + stream: &streamFixture{responses: []*tangopb.GetChangedTargetsResponse{ changedTargets(target(tangopb.CHANGE_TYPE_NEW, 0, 1, 0)), metadata(map[int32]string{2: "//app:other"}), }}, @@ -167,7 +135,7 @@ func TestClient_ChangedTargets(t *testing.T) { }, { name: "changed target without a target fails", - stream: &fakeStream{responses: []*tangopb.GetChangedTargetsResponse{ + stream: &streamFixture{responses: []*tangopb.GetChangedTargetsResponse{ changedTargets(target(tangopb.CHANGE_TYPE_NEW, 0, 0, 0)), metadata(map[int32]string{}), }}, @@ -176,7 +144,29 @@ func TestClient_ChangedTargets(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - fake := &fakeTango{stream: tt.stream, openErr: tt.openErr} + ctrl := gomock.NewController(t) + closed := false + var stream tangopb.TangoServiceGetChangedTargetsYARPCClient + if tt.stream != nil { + responseStream := NewMockTangoServiceGetChangedTargetsYARPCClient(ctrl) + responseStream.EXPECT().Context().Return(context.Background()).AnyTimes() + responseStream.EXPECT().CloseSend().DoAndReturn(func(...yarpc.StreamOption) error { closed = true; return nil }).AnyTimes() + index := 0 + responseStream.EXPECT().Recv().DoAndReturn(func(...yarpc.StreamOption) (*tangopb.GetChangedTargetsResponse, error) { + if index < len(tt.stream.responses) { + response := tt.stream.responses[index] + index++ + return response, nil + } + if tt.stream.endErr != nil { + return nil, tt.stream.endErr + } + return nil, io.EOF + }).AnyTimes() + stream = responseStream + } + fake := NewMockTangoYARPCClient(ctrl) + fake.EXPECT().GetChangedTargets(gomock.Any(), gomock.Any()).Return(stream, tt.openErr).AnyTimes() c := New(fake, Config{Remote: "org/repo", Strategy: tangopb.COMPUTATION_STRATEGY_NATIVE}) got, err := c.ChangedTargets(context.Background(), tango.ChangedTargetsRequest{ @@ -185,7 +175,7 @@ func TestClient_ChangedTargets(t *testing.T) { }) if tt.stream != nil { - assert.True(t, tt.stream.closed) + assert.True(t, closed) } if tt.wantError { require.Error(t, err) @@ -198,7 +188,16 @@ func TestClient_ChangedTargets(t *testing.T) { } func TestClient_ChangedTargets_Request(t *testing.T) { - fake := &fakeTango{stream: &fakeStream{}} + ctrl := gomock.NewController(t) + stream := NewMockTangoServiceGetChangedTargetsYARPCClient(ctrl) + stream.EXPECT().Recv().Return(nil, io.EOF).AnyTimes() + stream.EXPECT().CloseSend().Return(nil).AnyTimes() + var request *tangopb.GetChangedTargetsRequest + fake := NewMockTangoYARPCClient(ctrl) + fake.EXPECT().GetChangedTargets(gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, value *tangopb.GetChangedTargetsRequest, _ ...yarpc.CallOption) (tangopb.TangoServiceGetChangedTargetsYARPCClient, error) { + request = value + return stream, nil + }).AnyTimes() c := New(fake, Config{Remote: "org/repo", Strategy: tangopb.COMPUTATION_STRATEGY_NATIVE}) _, err := c.ChangedTargets(context.Background(), tango.ChangedTargetsRequest{ @@ -221,39 +220,58 @@ func TestClient_ChangedTargets_Request(t *testing.T) { Strategy: tangopb.COMPUTATION_STRATEGY_NATIVE, }, OutputConfig: &tangopb.OutputConfig{MaxDistance: -1}, - }, fake.request) + }, request) } func TestClient_ChangedTargets_Metrics(t *testing.T) { const remote = "remote=org/repo" tests := []struct { name string - fake *fakeTango + responses []*tangopb.GetChangedTargetsResponse + openErr error + streamErr error wantResult string }{ { name: "a successful call", - fake: &fakeTango{stream: &fakeStream{responses: []*tangopb.GetChangedTargetsResponse{ + responses: []*tangopb.GetChangedTargetsResponse{ changedTargets(target(tangopb.CHANGE_TYPE_CHANGED, 1, 1, 0)), metadata(map[int32]string{1: "//app:lib"}), - }}}, + }, wantResult: "success", }, { name: "a request that cannot be opened", - fake: &fakeTango{openErr: errTestFailure}, + openErr: errTestFailure, wantResult: "error", }, { name: "a stream that fails part-way", - fake: &fakeTango{stream: &fakeStream{endErr: errTestFailure}}, + streamErr: errTestFailure, wantResult: "error", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { scope := tally.NewTestScope("", nil) - c := New(tt.fake, Config{Remote: "org/repo", Strategy: tangopb.COMPUTATION_STRATEGY_NATIVE, MetricsScope: scope}) + ctrl := gomock.NewController(t) + stream := NewMockTangoServiceGetChangedTargetsYARPCClient(ctrl) + stream.EXPECT().CloseSend().Return(nil).AnyTimes() + index := 0 + stream.EXPECT().Recv().DoAndReturn(func(...yarpc.StreamOption) (*tangopb.GetChangedTargetsResponse, error) { + if index < len(tt.responses) { + response := tt.responses[index] + index++ + return response, nil + } + if tt.streamErr != nil { + return nil, tt.streamErr + } + return nil, io.EOF + }).AnyTimes() + fake := NewMockTangoYARPCClient(ctrl) + fake.EXPECT().GetChangedTargets(gomock.Any(), gomock.Any()).Return(stream, tt.openErr).AnyTimes() + c := New(fake, Config{Remote: "org/repo", Strategy: tangopb.COMPUTATION_STRATEGY_NATIVE, MetricsScope: scope}) _, _ = c.ChangedTargets(context.Background(), tango.ChangedTargetsRequest{BaseRevision: testBaseRevision}) diff --git a/submitqueue/extension/speculation/allocator/sticky/BUILD.bazel b/submitqueue/extension/speculation/allocator/sticky/BUILD.bazel index e8f9c8543..a3c971fa0 100644 --- a/submitqueue/extension/speculation/allocator/sticky/BUILD.bazel +++ b/submitqueue/extension/speculation/allocator/sticky/BUILD.bazel @@ -18,7 +18,9 @@ go_test( embed = [":go_default_library"], deps = [ "//submitqueue/entity:go_default_library", + "//submitqueue/extension/speculation/generator/mock:go_default_library", "@com_github_stretchr_testify//assert:go_default_library", "@com_github_stretchr_testify//require:go_default_library", + "@org_uber_go_mock//gomock:go_default_library", ], ) diff --git a/submitqueue/extension/speculation/allocator/sticky/sticky_test.go b/submitqueue/extension/speculation/allocator/sticky/sticky_test.go index 412e8b8ac..3adb398fc 100644 --- a/submitqueue/extension/speculation/allocator/sticky/sticky_test.go +++ b/submitqueue/extension/speculation/allocator/sticky/sticky_test.go @@ -22,29 +22,12 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "go.uber.org/mock/gomock" "github.com/uber/submitqueue/submitqueue/entity" + generatormock "github.com/uber/submitqueue/submitqueue/extension/speculation/generator/mock" ) -// fakeIter yields a fixed slice of candidates, optionally failing on the first pull. -type fakeIter struct { - items []entity.CandidatePath - idx int - fail bool -} - -func (f *fakeIter) Next(context.Context) (entity.CandidatePath, bool, error) { - if f.fail { - return entity.CandidatePath{}, false, errors.New("iterator boom") - } - if f.idx >= len(f.items) { - return entity.CandidatePath{}, false, nil - } - c := f.items[f.idx] - f.idx++ - return c, true, nil -} - // candidate builds a one-dependency candidate path for the given head and // assumption. func candidate(head string, assumption entity.DependencyAssumption, dep string) entity.CandidatePath { @@ -184,7 +167,19 @@ func TestSticky_Allocate(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - iter := &fakeIter{items: tt.items, fail: tt.iterFail} + index := 0 + iter := generatormock.NewMockIterator(gomock.NewController(t)) + iter.EXPECT().Next(gomock.Any()).DoAndReturn(func(context.Context) (entity.CandidatePath, bool, error) { + if tt.iterFail { + return entity.CandidatePath{}, false, errors.New("iterator boom") + } + if index >= len(tt.items) { + return entity.CandidatePath{}, false, nil + } + item := tt.items[index] + index++ + return item, true, nil + }).AnyTimes() got, err := New(tt.budget).Allocate(context.Background(), tt.pathSets, iter) if tt.wantErr { require.Error(t, err) @@ -213,7 +208,9 @@ func TestSticky_HonorsCancelledContext(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - got, err := New(5).Allocate(ctx, nil, &fakeIter{items: items}) + iter := generatormock.NewMockIterator(gomock.NewController(t)) + + got, err := New(5).Allocate(ctx, nil, iter) require.ErrorIs(t, err, context.Canceled) assert.Nil(t, got) }) @@ -222,7 +219,9 @@ func TestSticky_HonorsCancelledContext(t *testing.T) { ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Minute)) defer cancel() - got, err := New(5).Allocate(ctx, nil, &fakeIter{items: items}) + iter := generatormock.NewMockIterator(gomock.NewController(t)) + + got, err := New(5).Allocate(ctx, nil, iter) require.ErrorIs(t, err, context.DeadlineExceeded) assert.Nil(t, got) }) @@ -233,15 +232,11 @@ func TestSticky_HonorsCancelledContext(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - got, err := New(5).Allocate(ctx, nil, endlessIter{item: items[0]}) + iter := generatormock.NewMockIterator(gomock.NewController(t)) + iter.EXPECT().Next(gomock.Any()).Return(items[0], true, nil).AnyTimes() + + got, err := New(5).Allocate(ctx, nil, iter) require.ErrorIs(t, err, context.Canceled) assert.Nil(t, got) }) } - -// endlessIter yields the same candidate forever and ignores ctx entirely. -type endlessIter struct{ item entity.CandidatePath } - -func (e endlessIter) Next(context.Context) (entity.CandidatePath, bool, error) { - return e.item, true, nil -} diff --git a/submitqueue/extension/speculation/generator/bestfirst/BUILD.bazel b/submitqueue/extension/speculation/generator/bestfirst/BUILD.bazel index 574e64a60..1dd2a04f5 100644 --- a/submitqueue/extension/speculation/generator/bestfirst/BUILD.bazel +++ b/submitqueue/extension/speculation/generator/bestfirst/BUILD.bazel @@ -21,8 +21,10 @@ go_test( "//submitqueue/extension/speculation/generator:go_default_library", "//submitqueue/extension/speculation/scorer:go_default_library", "//submitqueue/extension/speculation/scorer/evidence:go_default_library", + "//submitqueue/extension/speculation/scorer/mock:go_default_library", "@com_github_stretchr_testify//assert:go_default_library", "@com_github_stretchr_testify//require:go_default_library", "@com_github_uber_go_tally//:go_default_library", + "@org_uber_go_mock//gomock:go_default_library", ], ) diff --git a/submitqueue/extension/speculation/generator/bestfirst/bestfirst_test.go b/submitqueue/extension/speculation/generator/bestfirst/bestfirst_test.go index a5199983b..e20c56aae 100644 --- a/submitqueue/extension/speculation/generator/bestfirst/bestfirst_test.go +++ b/submitqueue/extension/speculation/generator/bestfirst/bestfirst_test.go @@ -27,28 +27,25 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/uber-go/tally" + "go.uber.org/mock/gomock" "github.com/uber/submitqueue/submitqueue/entity" "github.com/uber/submitqueue/submitqueue/extension/speculation/generator" "github.com/uber/submitqueue/submitqueue/extension/speculation/scorer" "github.com/uber/submitqueue/submitqueue/extension/speculation/scorer/evidence" + scorermock "github.com/uber/submitqueue/submitqueue/extension/speculation/scorer/mock" ) -// stubScorer scores each batch by ID, defaulting to 0.5 for unknown batches. -// It is a minimal scorer.Scorer for exercising the generator without a resolver. -type stubScorer struct { - scores map[string]float64 -} - -func (s stubScorer) Score(_ context.Context, b entity.Batch, _ entity.SpeculationPathSet) (float64, error) { - if v, ok := s.scores[b.ID]; ok { - return v, nil - } - return 0.5, nil -} - -func scored(scores map[string]float64) scorer.Scorer { - return stubScorer{scores: scores} +func scored(t *testing.T, scores map[string]float64) scorer.Scorer { + t.Helper() + price := scorermock.NewMockScorer(gomock.NewController(t)) + price.EXPECT().Score(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, batch entity.Batch, _ entity.SpeculationPathSet) (float64, error) { + if value, ok := scores[batch.ID]; ok { + return value, nil + } + return 0.5, nil + }).AnyTimes() + return price } // drainAll pulls every candidate from an iterator. @@ -127,43 +124,9 @@ func iteratorOf(t *testing.T, iter generator.Iterator) *candidateIterator { return it } -// countingScorer records how many times each batch is priced. -type countingScorer struct { - scores map[string]float64 - calls map[string]int - total int -} - -func newCountingScorer(scores map[string]float64) *countingScorer { - return &countingScorer{scores: scores, calls: map[string]int{}} -} - -func (c *countingScorer) Score(_ context.Context, b entity.Batch, _ entity.SpeculationPathSet) (float64, error) { - c.calls[b.ID]++ - c.total++ - if v, ok := c.scores[b.ID]; ok { - return v, nil - } - return 0.5, nil -} - -// errScorer always fails, to exercise error propagation from pricing. -type errScorer struct{} - -func (errScorer) Score(context.Context, entity.Batch, entity.SpeculationPathSet) (float64, error) { - return 0, assert.AnError -} - -// constScorer prices every batch identically, regardless of ID. -type constScorer struct{ v float64 } - -func (c constScorer) Score(context.Context, entity.Batch, entity.SpeculationPathSet) (float64, error) { - return c.v, nil -} - // wideHead builds one Speculating head over n unresolved dependencies, each at a // distinct score so no two combinations tie. -func wideHead(n int) ([]entity.Batch, scorer.Scorer) { +func wideHead(t *testing.T, n int) ([]entity.Batch, scorer.Scorer) { head := entity.Batch{ID: "q/head", State: entity.BatchStateSpeculating} batches := []entity.Batch{} scores := map[string]float64{} @@ -174,7 +137,7 @@ func wideHead(n int) ([]entity.Batch, scorer.Scorer) { batches = append(batches, entity.Batch{ID: dep, State: entity.BatchStateCreated}) scores[dep] = 0.55 + 0.02*float64(i) } - return append(batches, head), scored(scores) + return append(batches, head), scored(t, scores) } func TestBestFirst_OrderingAndEnumeration(t *testing.T) { @@ -183,7 +146,7 @@ func TestBestFirst_OrderingAndEnumeration(t *testing.T) { {ID: "q/B", State: entity.BatchStateSpeculating}, {ID: "q/C", State: entity.BatchStateSpeculating, Dependencies: []string{"q/A", "q/B"}}, } - sc := scored(map[string]float64{"q/A": 0.9, "q/B": 0.8}) + sc := scored(t, map[string]float64{"q/A": 0.9, "q/B": 0.8}) iter, err := New(sc).Generate(context.Background(), batches, nil) require.NoError(t, err) @@ -226,7 +189,7 @@ func TestBestFirst_PinsResolvedDependencies(t *testing.T) { {ID: "q/A", State: tt.state}, {ID: "q/H", State: entity.BatchStateSpeculating, Dependencies: []string{"q/A"}}, } - iter, err := New(scored(nil)).Generate(context.Background(), batches, nil) + iter, err := New(scored(t, nil)).Generate(context.Background(), batches, nil) require.NoError(t, err) cands := forHead(drainAll(t, iter), "q/H") @@ -248,7 +211,7 @@ func TestBestFirst_ResolvedDependenciesDropOutOfSearch(t *testing.T) { {ID: "q/H", State: entity.BatchStateSpeculating, Dependencies: []string{"q/succeeded", "q/failed", "q/open"}}, } - iter, err := New(scored(map[string]float64{"q/open": 0.7})). + iter, err := New(scored(t, map[string]float64{"q/open": 0.7})). Generate(context.Background(), batches, nil) require.NoError(t, err) cands := forHead(drainAll(t, iter), "q/H") @@ -271,7 +234,7 @@ func TestBestFirst_EmitsExactSequenceAcrossHeads(t *testing.T) { {ID: "q/D", State: entity.BatchStateSpeculating}, {ID: "q/C", State: entity.BatchStateSpeculating, Dependencies: []string{"q/A", "q/B"}}, } - sc := scored(map[string]float64{"q/A": 0.9, "q/B": 0.8}) + sc := scored(t, map[string]float64{"q/A": 0.9, "q/B": 0.8}) iter, err := New(sc).Generate(context.Background(), batches, nil) require.NoError(t, err) @@ -306,7 +269,7 @@ func TestBestFirst_PreferredAssumptionFollowsScore(t *testing.T) { {ID: "q/H", State: entity.BatchStateSpeculating, Dependencies: []string{"q/high", "q/low"}}, } - sc := scored(map[string]float64{"q/high": 0.8, "q/low": 0.3}) + sc := scored(t, map[string]float64{"q/high": 0.8, "q/low": 0.3}) iter, err := New(sc).Generate(context.Background(), batches, nil) require.NoError(t, err) @@ -356,7 +319,7 @@ func TestBestFirst_OnlySpeculatingHeadsProduceCandidates(t *testing.T) { t.Run(name, func(t *testing.T) { batches := []entity.Batch{{ID: "q/H", State: tt.state}} - iter, err := New(scored(nil)).Generate(context.Background(), batches, nil) + iter, err := New(scored(t, nil)).Generate(context.Background(), batches, nil) require.NoError(t, err) cands := drainAll(t, iter) @@ -375,7 +338,7 @@ func TestBestFirst_HeadWithNoDependencies(t *testing.T) { {ID: "q/H", State: entity.BatchStateSpeculating}, } - iter, err := New(scored(nil)).Generate(context.Background(), batches, nil) + iter, err := New(scored(t, nil)).Generate(context.Background(), batches, nil) require.NoError(t, err) cands := drainAll(t, iter) @@ -394,7 +357,10 @@ func TestBestFirst_AbsorbsScorerError(t *testing.T) { {ID: "q/H", State: entity.BatchStateSpeculating, Dependencies: []string{"q/A"}}, } - iter, err := New(errScorer{}).Generate(context.Background(), batches, nil) + price := scorermock.NewMockScorer(gomock.NewController(t)) + price.EXPECT().Score(gomock.Any(), gomock.Any(), gomock.Any()).Return(0.0, assert.AnError).AnyTimes() + + iter, err := New(price).Generate(context.Background(), batches, nil) require.NoError(t, err) cands := forHead(drainAll(t, iter), "q/H") @@ -410,27 +376,17 @@ func TestBestFirst_NeverScoresAnAbsentDependency(t *testing.T) { batches := []entity.Batch{ {ID: "q/H", State: entity.BatchStateSpeculating, Dependencies: []string{"q/missing"}}, } - sc := newCountingScorer(map[string]float64{}) + sc, counts := newCountingScorer(t, map[string]float64{}) iter, err := New(sc).Generate(context.Background(), batches, nil) require.NoError(t, err) cands := drainAll(t, iter) require.Len(t, cands, 2, "the absent dependency is still an open question with two sides") - assert.Zero(t, sc.total, "the scorer is never handed a batch the snapshot did not carry") + assert.Zero(t, counts.total, "the scorer is never handed a batch the snapshot did not carry") assert.InDelta(t, math.Log(defaultProbability), cands[0].RankingScore, 1e-9) } -// recordingScorer keeps the path set each batch was priced against. -type recordingScorer struct { - seen map[string]entity.SpeculationPathSet -} - -func (r *recordingScorer) Score(_ context.Context, b entity.Batch, paths entity.SpeculationPathSet) (float64, error) { - r.seen[b.ID] = paths - return 0.5, nil -} - // Each dependency is priced against its own progress, not the queue's. A // dependency with no set has simply never speculated, which is silence rather // than an error. @@ -445,26 +401,26 @@ func TestBestFirst_PricesEachDependencyAgainstItsOwnPathSet(t *testing.T) { Head: "q/built", Paths: []entity.SpeculationPathEntry{{ID: "p1", Status: entity.SpeculationPathStatusPassed}}, } - pred := &recordingScorer{seen: map[string]entity.SpeculationPathSet{}} + seen := map[string]entity.SpeculationPathSet{} + pred := scorermock.NewMockScorer(gomock.NewController(t)) + pred.EXPECT().Score(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, batch entity.Batch, paths entity.SpeculationPathSet) (float64, error) { + seen[batch.ID] = paths + return 0.5, nil + }).AnyTimes() _, err := New(pred).Generate(context.Background(), batches, []entity.SpeculationPathSet{built}) require.NoError(t, err) - assert.Equal(t, built, pred.seen["q/built"], "a dependency is priced against its own set") - assert.Equal(t, entity.SpeculationPathSet{}, pred.seen["q/fresh"], "a dependency that never speculated has no set") -} - -// flatScorer prices every batch the same, so ranking can only move when the -// evidence scorer sees a path set. -type flatScorer struct{} - -func (flatScorer) Score(context.Context, entity.Batch, entity.SpeculationPathSet) (float64, error) { - return 0.5, nil + assert.Equal(t, built, seen["q/built"], "a dependency is priced against its own set") + assert.Equal(t, entity.SpeculationPathSet{}, seen["q/fresh"], "a dependency that never speculated has no set") } func evidenceScorer(t *testing.T, factors evidence.Factors) scorer.Scorer { t.Helper() - s, err := evidence.New(scorer.Config{QueueName: "q"}, flatScorer{}, factors, tally.NoopScope) + price := scorermock.NewMockScorer(gomock.NewController(t)) + price.EXPECT().Score(gomock.Any(), gomock.Any(), gomock.Any()).Return(0.5, nil).AnyTimes() + + s, err := evidence.New(scorer.Config{QueueName: "q"}, price, factors, tally.NoopScope) require.NoError(t, err) return s } @@ -571,7 +527,7 @@ func TestBestFirst_LandingDependencyStaysOpen(t *testing.T) { func TestBestFirst_GeneratesOnlyWhatIsPulled(t *testing.T) { // 12 unresolved dependencies is an outcome space of 4096 paths. const deps, space = 12, 1 << 12 - batches, sc := wideHead(deps) + batches, sc := wideHead(t, deps) iter, err := New(sc).Generate(context.Background(), batches, nil) require.NoError(t, err) @@ -608,7 +564,7 @@ func TestBestFirst_DrainYieldsEveryCombinationOnce(t *testing.T) { {ID: "q/C", State: entity.BatchStateCreated}, {ID: "q/H", State: entity.BatchStateSpeculating, Dependencies: deps}, } - sc := scored(map[string]float64{"q/A": 0.9, "q/B": 0.7, "q/C": 0.6}) + sc := scored(t, map[string]float64{"q/A": 0.9, "q/B": 0.7, "q/C": 0.6}) iter, err := New(sc).Generate(context.Background(), batches, nil) require.NoError(t, err) @@ -658,7 +614,7 @@ func TestBestFirst_ScoresGloballyNonIncreasing(t *testing.T) { {ID: "q/BC", State: entity.BatchStateSpeculating, Dependencies: []string{"q/B", "q/C"}}, {ID: "q/ABC", State: entity.BatchStateSpeculating, Dependencies: []string{"q/A", "q/B", "q/C"}}, } - sc := scored(map[string]float64{"q/A": 0.85, "q/B": 0.3, "q/C": 0.65}) + sc := scored(t, map[string]float64{"q/A": 0.85, "q/B": 0.3, "q/C": 0.65}) iter, err := New(sc).Generate(context.Background(), batches, nil) require.NoError(t, err) @@ -684,7 +640,7 @@ func TestBestFirst_EqualScoresOrderDeterministically(t *testing.T) { {ID: "q/c", State: entity.BatchStateSpeculating}, } - iter, err := New(scored(nil)).Generate(context.Background(), batches, nil) + iter, err := New(scored(t, nil)).Generate(context.Background(), batches, nil) require.NoError(t, err) cands := drainAll(t, iter) @@ -705,7 +661,7 @@ func TestBestFirst_EqualScoresOrderDeterministically(t *testing.T) { {ID: "q/a", State: entity.BatchStateSpeculating, Dependencies: []string{"q/coinA"}}, {ID: "q/b", State: entity.BatchStateSpeculating, Dependencies: []string{"q/coinB"}}, } - sc := scored(map[string]float64{"q/coinA": 0.5, "q/coinB": 0.5}) + sc := scored(t, map[string]float64{"q/coinA": 0.5, "q/coinB": 0.5}) iter, err := New(sc).Generate(context.Background(), batches, nil) require.NoError(t, err) @@ -740,7 +696,7 @@ func TestBestFirst_EqualScoresOrderDeterministically(t *testing.T) { {ID: "q/H", State: entity.BatchStateSpeculating, Dependencies: []string{"q/A", "q/B", "q/C"}}, } - sc := scored(map[string]float64{"q/A": 0.5, "q/B": 0.5, "q/C": 0.5}) + sc := scored(t, map[string]float64{"q/A": 0.5, "q/B": 0.5, "q/C": 0.5}) first, err := New(sc).Generate(context.Background(), batches, nil) require.NoError(t, err) @@ -754,18 +710,18 @@ func TestBestFirst_EqualScoresOrderDeterministically(t *testing.T) { } func TestBestFirst_NextMakesNoScorerCalls(t *testing.T) { - batches, _ := wideHead(6) - sc := newCountingScorer(map[string]float64{}) + batches, _ := wideHead(t, 6) + sc, counts := newCountingScorer(t, map[string]float64{}) iter, err := New(sc).Generate(context.Background(), batches, nil) require.NoError(t, err) - afterGenerate := sc.total + afterGenerate := counts.total require.Positive(t, afterGenerate, "Generate must do the scoring") cands := drainAll(t, iter) require.Len(t, cands, 1<<6) - assert.Equal(t, afterGenerate, sc.total, "Next must never call the scorer") + assert.Equal(t, afterGenerate, counts.total, "Next must never call the scorer") } func TestBestFirst_MemoizesDependencyScoresAcrossHeads(t *testing.T) { @@ -775,12 +731,12 @@ func TestBestFirst_MemoizesDependencyScoresAcrossHeads(t *testing.T) { {ID: "q/H2", State: entity.BatchStateSpeculating, Dependencies: []string{"q/shared"}}, {ID: "q/H3", State: entity.BatchStateSpeculating, Dependencies: []string{"q/shared"}}, } - sc := newCountingScorer(map[string]float64{"q/shared": 0.7}) + sc, counts := newCountingScorer(t, map[string]float64{"q/shared": 0.7}) _, err := New(sc).Generate(context.Background(), batches, nil) require.NoError(t, err) - assert.Equal(t, 1, sc.calls["q/shared"], "a shared dependency is scored once") + assert.Equal(t, 1, counts.calls["q/shared"], "a shared dependency is scored once") } func TestBestFirst_MatchesBruteForceEnumeration(t *testing.T) { @@ -809,7 +765,7 @@ func TestBestFirst_MatchesBruteForceEnumeration(t *testing.T) { ID: "q/H", State: entity.BatchStateSpeculating, Dependencies: deps, }) - iter, err := New(scored(scores)).Generate(context.Background(), batches, nil) + iter, err := New(scored(t, scores)).Generate(context.Background(), batches, nil) require.NoError(t, err) got := drainAll(t, iter) @@ -880,7 +836,10 @@ func TestBestFirst_WideHeadsRankWithoutUnderflow(t *testing.T) { wide("q/narrow", narrowWidth) wide("q/wide", wideWidth) - iter, err := New(constScorer{depScore}).Generate(context.Background(), batches, nil) + price := scorermock.NewMockScorer(gomock.NewController(t)) + price.EXPECT().Score(gomock.Any(), gomock.Any(), gomock.Any()).Return(depScore, nil).AnyTimes() + + iter, err := New(price).Generate(context.Background(), batches, nil) require.NoError(t, err) first, ok, err := iter.Next(context.Background()) @@ -918,7 +877,7 @@ func TestBestFirst_HonorsCancelledContext(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - iter, err := New(scored(nil)).Generate(ctx, batches, nil) + iter, err := New(scored(t, nil)).Generate(ctx, batches, nil) require.ErrorIs(t, err, context.Canceled) assert.Nil(t, iter) }) @@ -927,7 +886,7 @@ func TestBestFirst_HonorsCancelledContext(t *testing.T) { ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Minute)) defer cancel() - _, err := New(scored(nil)).Generate(ctx, batches, nil) + _, err := New(scored(t, nil)).Generate(ctx, batches, nil) require.ErrorIs(t, err, context.DeadlineExceeded) }) @@ -935,7 +894,7 @@ func TestBestFirst_HonorsCancelledContext(t *testing.T) { // Generate on a live context so the stream has candidates waiting; the // cancel lands between pulls, which is where a caller that has given up // actually stops. - iter, err := New(scored(nil)).Generate(context.Background(), batches, nil) + iter, err := New(scored(t, nil)).Generate(context.Background(), batches, nil) require.NoError(t, err) _, ok, err := iter.Next(context.Background()) @@ -959,21 +918,18 @@ func TestBestFirst_HonorsCancelledContext(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - iter, err := New(cancellingScorer{cancel: cancel}).Generate(ctx, batches, nil) + price := scorermock.NewMockScorer(gomock.NewController(t)) + price.EXPECT().Score(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(context.Context, entity.Batch, entity.SpeculationPathSet) (float64, error) { + cancel() + return 0, context.Canceled + }).AnyTimes() + + iter, err := New(price).Generate(ctx, batches, nil) require.ErrorIs(t, err, context.Canceled) assert.Nil(t, iter) }) } -// cancellingScorer kills the context and then fails, the way a scorer -// whose own call was cancelled would. -type cancellingScorer struct{ cancel context.CancelFunc } - -func (s cancellingScorer) Score(context.Context, entity.Batch, entity.SpeculationPathSet) (float64, error) { - s.cancel() - return 0, context.Canceled -} - func TestBestFirst_DefaultsScoreOutsideUnitInterval(t *testing.T) { // Everything downstream treats a score as a probability: its log is the // ranking key and its complement is the other side's probability. Carrying @@ -1000,7 +956,10 @@ func TestBestFirst_DefaultsScoreOutsideUnitInterval(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - iter, err := New(constScorer{tt.score}).Generate(context.Background(), batches, nil) + price := scorermock.NewMockScorer(gomock.NewController(t)) + price.EXPECT().Score(gomock.Any(), gomock.Any(), gomock.Any()).Return(tt.score, nil).AnyTimes() + + iter, err := New(price).Generate(context.Background(), batches, nil) require.NoError(t, err) cands := drainAll(t, iter) @@ -1026,7 +985,7 @@ func TestBestFirst_ImpossibleFlipScoresNegativeInfinity(t *testing.T) { {ID: "q/H1", State: entity.BatchStateSpeculating, Dependencies: []string{"q/certain"}}, {ID: "q/H2", State: entity.BatchStateSpeculating, Dependencies: []string{"q/toss"}}, } - sc := scored(map[string]float64{"q/certain": 1.0, "q/toss": 0.6}) + sc := scored(t, map[string]float64{"q/certain": 1.0, "q/toss": 0.6}) iter, err := New(sc).Generate(context.Background(), batches, nil) require.NoError(t, err) @@ -1060,14 +1019,14 @@ func TestBestFirst_ResolvedDependenciesAreNeverScored(t *testing.T) { {ID: "q/H", State: entity.BatchStateSpeculating, Dependencies: []string{"q/passed", "q/broke", "q/stopped", "q/running"}}, } - sc := newCountingScorer(map[string]float64{"q/running": 0.8}) + sc, counts := newCountingScorer(t, map[string]float64{"q/running": 0.8}) iter, err := New(sc).Generate(context.Background(), batches, nil) require.NoError(t, err) cands := drainAll(t, iter) - assert.Equal(t, 1, sc.total, "only the unresolved dependency is scored") - assert.Equal(t, 1, sc.calls["q/running"]) + assert.Equal(t, 1, counts.total, "only the unresolved dependency is scored") + assert.Equal(t, 1, counts.calls["q/running"]) require.Len(t, cands, 2, "one unresolved dependency, so two paths") // The resolved three keep their forced assumption on both paths. @@ -1081,8 +1040,8 @@ func TestBestFirst_ResolvedDependenciesAreNeverScored(t *testing.T) { func TestBestFirst_ReturnedPathsAreIndependent(t *testing.T) { // Paths are built one at a time from state the head shares, so a caller // scribbling on what it was handed must not reach the paths still to come. - batches, _ := wideHead(3) - iter, err := New(scored(map[string]float64{"q/dep00": 0.9, "q/dep01": 0.8, "q/dep02": 0.7})). + batches, _ := wideHead(t, 3) + iter, err := New(scored(t, map[string]float64{"q/dep00": 0.9, "q/dep01": 0.8, "q/dep02": 0.7})). Generate(context.Background(), batches, nil) require.NoError(t, err) @@ -1140,7 +1099,7 @@ func TestBestFirst_ScoresAreSummedFromTheHeadsBestScore(t *testing.T) { want[s.scoreFor(taken)]++ } - iter, err := New(scored(scores)).Generate(context.Background(), batches, nil) + iter, err := New(scored(t, scores)).Generate(context.Background(), batches, nil) require.NoError(t, err) got := map[float64]int{} for _, c := range drainAll(t, iter) { @@ -1168,7 +1127,7 @@ func TestBestFirst_UntouchedHeadsNeverWorkOutFlips(t *testing.T) { scores[dep] = 0.6 + 0.005*float64(i) } - iter, err := New(scored(scores)).Generate(context.Background(), batches, nil) + iter, err := New(scored(t, scores)).Generate(context.Background(), batches, nil) require.NoError(t, err) it := iteratorOf(t, iter) @@ -1206,7 +1165,7 @@ func TestBestFirst_AFailedPullConsumesNothing(t *testing.T) { {ID: "q/a", State: entity.BatchStateSpeculating, Dependencies: []string{"q/dep"}}, {ID: "q/b", State: entity.BatchStateSpeculating}, } - sc := scored(map[string]float64{"q/dep": 0.8}) + sc := scored(t, map[string]float64{"q/dep": 0.8}) iter, err := New(sc).Generate(context.Background(), batches, nil) require.NoError(t, err) @@ -1222,3 +1181,23 @@ func TestBestFirst_AFailedPullConsumesNothing(t *testing.T) { assert.Len(t, got, 3, "two paths for q/a, one for q/b") assert.ElementsMatch(t, []string{"q/a", "q/a", "q/b"}, heads(got)) } + +type scoreCounts struct { + calls map[string]int + total int +} + +func newCountingScorer(t *testing.T, scores map[string]float64) (*scorermock.MockScorer, *scoreCounts) { + t.Helper() + counts := &scoreCounts{calls: make(map[string]int)} + price := scorermock.NewMockScorer(gomock.NewController(t)) + price.EXPECT().Score(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, batch entity.Batch, _ entity.SpeculationPathSet) (float64, error) { + counts.calls[batch.ID]++ + counts.total++ + if value, ok := scores[batch.ID]; ok { + return value, nil + } + return 0.5, nil + }).AnyTimes() + return price, counts +} diff --git a/submitqueue/extension/speculation/scorer/composite/BUILD.bazel b/submitqueue/extension/speculation/scorer/composite/BUILD.bazel index 2286d51b3..c595f4864 100644 --- a/submitqueue/extension/speculation/scorer/composite/BUILD.bazel +++ b/submitqueue/extension/speculation/scorer/composite/BUILD.bazel @@ -20,8 +20,10 @@ go_test( deps = [ "//submitqueue/entity:go_default_library", "//submitqueue/extension/speculation/scorer:go_default_library", + "//submitqueue/extension/speculation/scorer/mock:go_default_library", "@com_github_stretchr_testify//assert:go_default_library", "@com_github_stretchr_testify//require:go_default_library", "@com_github_uber_go_tally//:go_default_library", + "@org_uber_go_mock//gomock:go_default_library", ], ) diff --git a/submitqueue/extension/speculation/scorer/composite/scorer_test.go b/submitqueue/extension/speculation/scorer/composite/scorer_test.go index c2ae58746..58f0db0fd 100644 --- a/submitqueue/extension/speculation/scorer/composite/scorer_test.go +++ b/submitqueue/extension/speculation/scorer/composite/scorer_test.go @@ -24,75 +24,61 @@ import ( "github.com/uber-go/tally" "github.com/uber/submitqueue/submitqueue/entity" "github.com/uber/submitqueue/submitqueue/extension/speculation/scorer" + scorermock "github.com/uber/submitqueue/submitqueue/extension/speculation/scorer/mock" + "go.uber.org/mock/gomock" ) // testCfg is the per-queue identity used by every case in this file. var testCfg = scorer.Config{QueueName: "test-queue"} -// fixedScorer always returns a fixed score. -type fixedScorer struct { - score float64 -} - -func (f *fixedScorer) Score(_ context.Context, _ entity.Batch, _ entity.SpeculationPathSet) (float64, error) { - return f.score, nil -} - -// errorScorer always returns an error. -type errorScorer struct{} - -func (e *errorScorer) Score(_ context.Context, _ entity.Batch, _ entity.SpeculationPathSet) (float64, error) { - return 0, fmt.Errorf("scorer failed") -} - func TestScorer_Score(t *testing.T) { tests := []struct { name string - scorers map[string]scorer.Scorer + scorers map[string]float64 reduce ReduceFunc want float64 }{ { name: "min of two scorers", - scorers: map[string]scorer.Scorer{ - "files": &fixedScorer{0.9}, - "deps": &fixedScorer{0.6}, + scorers: map[string]float64{ + "files": 0.9, + "deps": 0.6, }, reduce: Min, want: 0.6, }, { name: "max of two scorers", - scorers: map[string]scorer.Scorer{ - "files": &fixedScorer{0.9}, - "deps": &fixedScorer{0.6}, + scorers: map[string]float64{ + "files": 0.9, + "deps": 0.6, }, reduce: Max, want: 0.9, }, { name: "avg of two scorers", - scorers: map[string]scorer.Scorer{ - "files": &fixedScorer{0.9}, - "deps": &fixedScorer{0.6}, + scorers: map[string]float64{ + "files": 0.9, + "deps": 0.6, }, reduce: Avg, want: 0.75, }, { name: "single scorer passthrough", - scorers: map[string]scorer.Scorer{ - "files": &fixedScorer{0.9}, + scorers: map[string]float64{ + "files": 0.9, }, reduce: Avg, want: 0.9, }, { name: "avg of three scorers", - scorers: map[string]scorer.Scorer{ - "files": &fixedScorer{0.9}, - "deps": &fixedScorer{0.95}, - "lines": &fixedScorer{0.85}, + scorers: map[string]float64{ + "files": 0.9, + "deps": 0.95, + "lines": 0.85, }, reduce: Avg, want: 0.9, @@ -101,7 +87,14 @@ func TestScorer_Score(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - s := New(testCfg, tt.scorers, tt.reduce, tally.NoopScope) + ctrl := gomock.NewController(t) + children := make(map[string]scorer.Scorer, len(tt.scorers)) + for name, score := range tt.scorers { + child := scorermock.NewMockScorer(ctrl) + child.EXPECT().Score(gomock.Any(), gomock.Any(), gomock.Any()).Return(score, nil).AnyTimes() + children[name] = child + } + s := New(testCfg, children, tt.reduce, tally.NoopScope) got, err := s.Score(context.Background(), entity.Batch{}, entity.SpeculationPathSet{}) require.NoError(t, err) assert.InDelta(t, tt.want, got, 1e-9) @@ -110,9 +103,15 @@ func TestScorer_Score(t *testing.T) { } func TestScorer_Score_ChildError(t *testing.T) { + price := scorermock.NewMockScorer(gomock.NewController(t)) + price.EXPECT().Score(gomock.Any(), gomock.Any(), gomock.Any()).Return(0.9, nil).AnyTimes() + + failingPrice := scorermock.NewMockScorer(gomock.NewController(t)) + failingPrice.EXPECT().Score(gomock.Any(), gomock.Any(), gomock.Any()).Return(0.0, fmt.Errorf("scorer failed")).AnyTimes() + s := New(testCfg, map[string]scorer.Scorer{ - "error": &errorScorer{}, - "files": &fixedScorer{0.9}, + "error": failingPrice, + "files": price, }, Min, tally.NoopScope) _, err := s.Score(context.Background(), entity.Batch{}, entity.SpeculationPathSet{}) require.Error(t, err) @@ -125,8 +124,11 @@ func TestNew_EmptyScorers(t *testing.T) { } func TestNew_NilReduce(t *testing.T) { + price := scorermock.NewMockScorer(gomock.NewController(t)) + price.EXPECT().Score(gomock.Any(), gomock.Any(), gomock.Any()).Return(0.9, nil).AnyTimes() + assert.Panics(t, func() { - New(testCfg, map[string]scorer.Scorer{"files": &fixedScorer{0.9}}, nil, tally.NoopScope) + New(testCfg, map[string]scorer.Scorer{"files": price}, nil, tally.NoopScope) }) } @@ -139,9 +141,15 @@ func TestReduceFunc_ReceivesNames(t *testing.T) { return scores["files"] } + dependencies := scorermock.NewMockScorer(gomock.NewController(t)) + dependencies.EXPECT().Score(gomock.Any(), gomock.Any(), gomock.Any()).Return(0.95, nil).AnyTimes() + + files := scorermock.NewMockScorer(gomock.NewController(t)) + files.EXPECT().Score(gomock.Any(), gomock.Any(), gomock.Any()).Return(0.9, nil).AnyTimes() + s := New(testCfg, map[string]scorer.Scorer{ - "files": &fixedScorer{0.9}, - "deps": &fixedScorer{0.95}, + "files": files, + "deps": dependencies, }, custom, tally.NoopScope) got, err := s.Score(context.Background(), entity.Batch{}, entity.SpeculationPathSet{}) require.NoError(t, err) diff --git a/submitqueue/extension/speculation/scorer/evidence/BUILD.bazel b/submitqueue/extension/speculation/scorer/evidence/BUILD.bazel index 24875861c..016a86044 100644 --- a/submitqueue/extension/speculation/scorer/evidence/BUILD.bazel +++ b/submitqueue/extension/speculation/scorer/evidence/BUILD.bazel @@ -20,8 +20,10 @@ go_test( deps = [ "//submitqueue/entity:go_default_library", "//submitqueue/extension/speculation/scorer:go_default_library", + "//submitqueue/extension/speculation/scorer/mock:go_default_library", "@com_github_stretchr_testify//assert:go_default_library", "@com_github_stretchr_testify//require:go_default_library", "@com_github_uber_go_tally//:go_default_library", + "@org_uber_go_mock//gomock:go_default_library", ], ) diff --git a/submitqueue/extension/speculation/scorer/evidence/evidence_test.go b/submitqueue/extension/speculation/scorer/evidence/evidence_test.go index 23ee7c13e..e5fb06d76 100644 --- a/submitqueue/extension/speculation/scorer/evidence/evidence_test.go +++ b/submitqueue/extension/speculation/scorer/evidence/evidence_test.go @@ -25,25 +25,13 @@ import ( "github.com/uber-go/tally" "github.com/uber/submitqueue/submitqueue/entity" "github.com/uber/submitqueue/submitqueue/extension/speculation/scorer" + scorermock "github.com/uber/submitqueue/submitqueue/extension/speculation/scorer/mock" + "go.uber.org/mock/gomock" ) // testCfg is the per-queue identity used by every case in this file. var testCfg = scorer.Config{QueueName: "test-queue"} -// fixedScorer always returns the same price. -type fixedScorer struct{ price float64 } - -func (f fixedScorer) Score(_ context.Context, _ entity.Batch, _ entity.SpeculationPathSet) (float64, error) { - return f.price, nil -} - -// errorScorer always fails. -type errorScorer struct{} - -func (errorScorer) Score(_ context.Context, _ entity.Batch, _ entity.SpeculationPathSet) (float64, error) { - return 0, fmt.Errorf("scorer failed") -} - // pathSet builds a set whose entries carry the given statuses, every path // assuming all of its dependencies succeed. func pathSet(statuses ...entity.SpeculationPathStatus) entity.SpeculationPathSet { @@ -64,7 +52,10 @@ func pathSet(statuses ...entity.SpeculationPathStatus) entity.SpeculationPathSet // scoreOnce runs one Score with all-neutral factors except those overridden. func scoreOnce(t *testing.T, price float64, factors Factors, batch entity.Batch, paths entity.SpeculationPathSet) float64 { t.Helper() - s, err := New(testCfg, fixedScorer{price: price}, factors, tally.NoopScope) + base := scorermock.NewMockScorer(gomock.NewController(t)) + base.EXPECT().Score(gomock.Any(), gomock.Any(), gomock.Any()).Return(price, nil).AnyTimes() + + s, err := New(testCfg, base, factors, tally.NoopScope) require.NoError(t, err) got, err := s.Score(context.Background(), batch, paths) require.NoError(t, err) @@ -217,7 +208,10 @@ func TestScore_LargeFactorsDoNotProduceCertainty(t *testing.T) { func TestScore_RejectsAPriceThatIsNotAProbability(t *testing.T) { for _, price := range []float64{-0.1, 1.5, math.NaN()} { t.Run(fmt.Sprintf("price %v", price), func(t *testing.T) { - s, err := New(testCfg, fixedScorer{price: price}, AllOnes(), tally.NoopScope) + base := scorermock.NewMockScorer(gomock.NewController(t)) + base.EXPECT().Score(gomock.Any(), gomock.Any(), gomock.Any()).Return(price, nil).AnyTimes() + + s, err := New(testCfg, base, AllOnes(), tally.NoopScope) require.NoError(t, err) _, err = s.Score(context.Background(), entity.Batch{}, entity.SpeculationPathSet{}) require.Error(t, err) @@ -226,7 +220,10 @@ func TestScore_RejectsAPriceThatIsNotAProbability(t *testing.T) { } func TestScore_PropagatesAScorerError(t *testing.T) { - s, err := New(testCfg, errorScorer{}, AllOnes(), tally.NoopScope) + base := scorermock.NewMockScorer(gomock.NewController(t)) + base.EXPECT().Score(gomock.Any(), gomock.Any(), gomock.Any()).Return(0.0, fmt.Errorf("scorer failed")).AnyTimes() + + s, err := New(testCfg, base, AllOnes(), tally.NoopScope) require.NoError(t, err) _, err = s.Score(context.Background(), entity.Batch{}, entity.SpeculationPathSet{}) require.Error(t, err) @@ -242,18 +239,22 @@ func TestNew_RejectsUnusableConstruction(t *testing.T) { tests := []struct { name string - base scorer.Scorer + nilBase bool factors Factors }{ - {name: "nil base", base: nil, factors: AllOnes()}, - {name: "zero factor", base: fixedScorer{price: 0.5}, factors: zeroed}, - {name: "negative factor", base: fixedScorer{price: 0.5}, factors: negative}, - {name: "infinite factor", base: fixedScorer{price: 0.5}, factors: infinite}, - {name: "unset factors", base: fixedScorer{price: 0.5}, factors: Factors{}}, + {name: "nil base", nilBase: true, factors: AllOnes()}, + {name: "zero factor", factors: zeroed}, + {name: "negative factor", factors: negative}, + {name: "infinite factor", factors: infinite}, + {name: "unset factors", factors: Factors{}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - s, err := New(testCfg, tt.base, tt.factors, tally.NoopScope) + var base scorer.Scorer + if !tt.nilBase { + base = scorermock.NewMockScorer(gomock.NewController(t)) + } + s, err := New(testCfg, base, tt.factors, tally.NoopScope) require.Error(t, err) assert.Nil(t, s) }) diff --git a/submitqueue/extension/speculation/speculator/standard/BUILD.bazel b/submitqueue/extension/speculation/speculator/standard/BUILD.bazel index 1f79c617b..fa02dd8bf 100644 --- a/submitqueue/extension/speculation/speculator/standard/BUILD.bazel +++ b/submitqueue/extension/speculation/speculator/standard/BUILD.bazel @@ -23,6 +23,7 @@ go_test( "//submitqueue/extension/speculation/allocator/sticky:go_default_library", "//submitqueue/extension/speculation/generator/bestfirst:go_default_library", "//submitqueue/extension/speculation/generator/mock:go_default_library", + "//submitqueue/extension/speculation/scorer/mock:go_default_library", "//submitqueue/extension/speculation/speculator:go_default_library", "@com_github_stretchr_testify//assert:go_default_library", "@com_github_stretchr_testify//require:go_default_library", diff --git a/submitqueue/extension/speculation/speculator/standard/standard_test.go b/submitqueue/extension/speculation/speculator/standard/standard_test.go index 7eca64e84..7c86841e5 100644 --- a/submitqueue/extension/speculation/speculator/standard/standard_test.go +++ b/submitqueue/extension/speculation/speculator/standard/standard_test.go @@ -28,6 +28,7 @@ import ( "github.com/uber/submitqueue/submitqueue/extension/speculation/allocator/sticky" "github.com/uber/submitqueue/submitqueue/extension/speculation/generator/bestfirst" generatormock "github.com/uber/submitqueue/submitqueue/extension/speculation/generator/mock" + scorermock "github.com/uber/submitqueue/submitqueue/extension/speculation/scorer/mock" "github.com/uber/submitqueue/submitqueue/extension/speculation/speculator" ) @@ -44,14 +45,6 @@ func assumptionFor(p entity.SpeculationPath, dep string) entity.DependencyAssump return entity.DependencyAssumptionUnknown } -// constScorer is a minimal scorer.Scorer that prices every -// batch identically. -type constScorer struct{ v float64 } - -func (c constScorer) Score(context.Context, entity.Batch, entity.SpeculationPathSet) (float64, error) { - return c.v, nil -} - func TestComposed_EndToEnd_NaivePair(t *testing.T) { batches := []entity.Batch{ {ID: "1", State: entity.BatchStateSpeculating}, @@ -59,7 +52,10 @@ func TestComposed_EndToEnd_NaivePair(t *testing.T) { } // bestfirst generator + sticky allocator with a 2-build budget. - spec := New(testCfg, bestfirst.New(constScorer{0.9}), sticky.New(2)) + price := scorermock.NewMockScorer(gomock.NewController(t)) + price.EXPECT().Score(gomock.Any(), gomock.Any(), gomock.Any()).Return(0.9, nil).AnyTimes() + + spec := New(testCfg, bestfirst.New(price), sticky.New(2)) got, err := spec.Speculate(context.Background(), batches, nil) require.NoError(t, err) @@ -125,7 +121,10 @@ func TestComposed_PropagatesContextCancellation(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - spec := New(testCfg, bestfirst.New(constScorer{0.9}), sticky.New(2)) + price := scorermock.NewMockScorer(gomock.NewController(t)) + price.EXPECT().Score(gomock.Any(), gomock.Any(), gomock.Any()).Return(0.9, nil).AnyTimes() + + spec := New(testCfg, bestfirst.New(price), sticky.New(2)) got, err := spec.Speculate(ctx, batches, nil) require.ErrorIs(t, err, context.Canceled) assert.Nil(t, got) diff --git a/submitqueue/gateway/controller/land_test.go b/submitqueue/gateway/controller/land_test.go index 6f31bf913..3ebfe6d8b 100644 --- a/submitqueue/gateway/controller/land_test.go +++ b/submitqueue/gateway/controller/land_test.go @@ -71,26 +71,13 @@ func newTestRegistryWithNoopPublisher(t *testing.T, ctrl *gomock.Controller) con return registry } -// staticCounterFactory resolves every queue to the same counter, so tests can keep -// setting expectations on one mock regardless of which queue the controller resolves. -// It records the queue it was asked for. -type staticCounterFactory struct { - counter counter.Counter - // forQueue is the queue named in the most recent For call. - forQueue *string -} - -func (f staticCounterFactory) For(config counter.Config) (counter.Counter, error) { - if f.forQueue != nil { - *f.forQueue = config.QueueName - } - return f.counter, nil -} - // noopStorage returns stateful request storage whose writes succeed. func newNoopLandController(t *testing.T, ctrl *gomock.Controller, cnt counter.Counter) LandController { fixture := newControllerStorageFixture(ctrl) - return NewLandController(zap.NewNop().Sugar(), tally.NoopScope, staticCounterFactory{counter: cnt}, fixture.newFactory(ctrl), fixture.newMaterializer(ctrl), noopQueueConfigStore(ctrl), queuepausenoop.New(), newTestRegistryWithNoopPublisher(t, ctrl)) + counterFactory := countermock.NewMockFactory(ctrl) + counterFactory.EXPECT().For(gomock.Any()).Return(cnt, nil).AnyTimes() + + return NewLandController(zap.NewNop().Sugar(), tally.NoopScope, counterFactory, fixture.newFactory(ctrl), fixture.newMaterializer(ctrl), noopQueueConfigStore(ctrl), queuepausenoop.New(), newTestRegistryWithNoopPublisher(t, ctrl)) } // noopQueueConfigStore returns a mock queueconfig.Store that always reports @@ -174,10 +161,16 @@ func TestLand_ResolvesCounterForRequestQueue(t *testing.T) { }, ) fixture := newControllerStorageFixture(ctrl) + counterFactory := countermock.NewMockFactory(ctrl) + counterFactory.EXPECT().For(gomock.Any()).DoAndReturn(func(config counter.Config) (counter.Counter, error) { + capturedQueue = config.QueueName + return cnt, nil + }).AnyTimes() + controller := NewLandController( zap.NewNop().Sugar(), tally.NoopScope, - staticCounterFactory{counter: cnt, forQueue: &capturedQueue}, + counterFactory, fixture.newFactory(ctrl), fixture.newMaterializer(ctrl), noopQueueConfigStore(ctrl), @@ -311,7 +304,10 @@ func TestLand_ReturnsUnrecognizedQueueWhenStoreReportsNotFound(t *testing.T) { qcs.EXPECT().Get(gomock.Any(), "missing-queue").Return(entity.QueueConfig{}, queueconfig.ErrNotFound) fixture := newControllerStorageFixture(ctrl) - controller := NewLandController(zap.NewNop().Sugar(), tally.NoopScope, staticCounterFactory{counter: cnt}, fixture.newFactory(ctrl), fixture.newMaterializer(ctrl), qcs, queuepausenoop.New(), newTestRegistryWithNoopPublisher(t, ctrl)) + counterFactory := countermock.NewMockFactory(ctrl) + counterFactory.EXPECT().For(gomock.Any()).Return(cnt, nil).AnyTimes() + + controller := NewLandController(zap.NewNop().Sugar(), tally.NoopScope, counterFactory, fixture.newFactory(ctrl), fixture.newMaterializer(ctrl), qcs, queuepausenoop.New(), newTestRegistryWithNoopPublisher(t, ctrl)) ctx := context.Background() _, err := controller.Land(ctx, testLandRequest("missing-queue")) @@ -334,7 +330,10 @@ func TestLand_PropagatesQueueConfigStoreError(t *testing.T) { qcs.EXPECT().Get(gomock.Any(), "test-queue").Return(entity.QueueConfig{}, fmt.Errorf("config backend down")) fixture := newControllerStorageFixture(ctrl) - controller := NewLandController(zap.NewNop().Sugar(), tally.NoopScope, staticCounterFactory{counter: cnt}, fixture.newFactory(ctrl), fixture.newMaterializer(ctrl), qcs, queuepausenoop.New(), newTestRegistryWithNoopPublisher(t, ctrl)) + counterFactory := countermock.NewMockFactory(ctrl) + counterFactory.EXPECT().For(gomock.Any()).Return(cnt, nil).AnyTimes() + + controller := NewLandController(zap.NewNop().Sugar(), tally.NoopScope, counterFactory, fixture.newFactory(ctrl), fixture.newMaterializer(ctrl), qcs, queuepausenoop.New(), newTestRegistryWithNoopPublisher(t, ctrl)) ctx := context.Background() _, err := controller.Land(ctx, testLandRequest("test-queue")) @@ -346,7 +345,10 @@ func TestLand_PropagatesQueueConfigStoreError(t *testing.T) { func newLandControllerWithPauseStore(t *testing.T, ctrl *gomock.Controller, cnt counter.Counter, qcs *qcmock.MockStore, pauses queuepause.Store) LandController { fixture := newControllerStorageFixture(ctrl) - return NewLandController(zap.NewNop().Sugar(), tally.NoopScope, staticCounterFactory{counter: cnt}, fixture.newFactory(ctrl), fixture.newMaterializer(ctrl), qcs, pauses, newTestRegistryWithNoopPublisher(t, ctrl)) + counterFactory := countermock.NewMockFactory(ctrl) + counterFactory.EXPECT().For(gomock.Any()).Return(cnt, nil).AnyTimes() + + return NewLandController(zap.NewNop().Sugar(), tally.NoopScope, counterFactory, fixture.newFactory(ctrl), fixture.newMaterializer(ctrl), qcs, pauses, newTestRegistryWithNoopPublisher(t, ctrl)) } func TestLand_QueuePause(t *testing.T) { @@ -493,7 +495,10 @@ func TestLand_PublishesToQueue(t *testing.T) { ), ) - controller := NewLandController(zap.NewNop().Sugar(), tally.NoopScope, staticCounterFactory{counter: cnt}, factoryForStorage(ctrl, store), materializer, noopQueueConfigStore(ctrl), queuepausenoop.New(), registry) + counterFactory := countermock.NewMockFactory(ctrl) + counterFactory.EXPECT().For(gomock.Any()).Return(cnt, nil).AnyTimes() + + controller := NewLandController(zap.NewNop().Sugar(), tally.NoopScope, counterFactory, factoryForStorage(ctrl, store), materializer, noopQueueConfigStore(ctrl), queuepausenoop.New(), registry) ctx := context.Background() req := entity.LandRequest{ @@ -565,7 +570,10 @@ func TestLand_ReturnsErrorWhenPublishFails(t *testing.T) { registry, publisher := newTestRegistry(t, ctrl) publisher.EXPECT().Publish(gomock.Any(), gomock.Any(), gomock.Any()).Return(fmt.Errorf("queue unavailable")) - controller := NewLandController(zap.NewNop().Sugar(), tally.NoopScope, staticCounterFactory{counter: cnt}, factoryForStorage(ctrl, storageWithSummaryStore(ctrl, summaryStore)), newControllerStorageFixture(ctrl).newMaterializer(ctrl), noopQueueConfigStore(ctrl), queuepausenoop.New(), registry) + counterFactory := countermock.NewMockFactory(ctrl) + counterFactory.EXPECT().For(gomock.Any()).Return(cnt, nil).AnyTimes() + + controller := NewLandController(zap.NewNop().Sugar(), tally.NoopScope, counterFactory, factoryForStorage(ctrl, storageWithSummaryStore(ctrl, summaryStore)), newControllerStorageFixture(ctrl).newMaterializer(ctrl), noopQueueConfigStore(ctrl), queuepausenoop.New(), registry) ctx := context.Background() _, err := controller.Land(ctx, testLandRequest("test-queue")) @@ -580,10 +588,13 @@ func TestLand_ReturnsSqidWhenAcceptedLogFailsAfterPublish(t *testing.T) { fixture := newControllerStorageFixture(ctrl) fixture.setLogInsertError(fmt.Errorf("log unavailable")) + counterFactory := countermock.NewMockFactory(ctrl) + counterFactory.EXPECT().For(gomock.Any()).Return(cnt, nil).AnyTimes() + controller := NewLandController( zap.NewNop().Sugar(), tally.NoopScope, - staticCounterFactory{counter: cnt}, + counterFactory, fixture.newFactory(ctrl), fixture.newMaterializer(ctrl), noopQueueConfigStore(ctrl), diff --git a/submitqueue/orchestrator/BUILD.bazel b/submitqueue/orchestrator/BUILD.bazel index b64b0e489..a6208d184 100644 --- a/submitqueue/orchestrator/BUILD.bazel +++ b/submitqueue/orchestrator/BUILD.bazel @@ -48,6 +48,7 @@ go_test( "//platform/base/failure:go_default_library", "//platform/base/messagequeue:go_default_library", "//platform/extension/hook:go_default_library", + "//platform/extension/hook/mock:go_default_library", "//platform/extension/hook/noop:go_default_library", "//platform/extension/messagequeue:go_default_library", "//platform/extension/messagequeue/mock:go_default_library", @@ -57,7 +58,6 @@ go_test( "//submitqueue/entity:go_default_library", "//submitqueue/extension/storage:go_default_library", "//submitqueue/extension/storage/mock:go_default_library", - "//submitqueue/orchestrator/extension/storage:go_default_library", "//submitqueue/orchestrator/extension/storage/mock:go_default_library", "@com_github_stretchr_testify//assert:go_default_library", "@com_github_stretchr_testify//require:go_default_library", diff --git a/submitqueue/orchestrator/controller/batch/BUILD.bazel b/submitqueue/orchestrator/controller/batch/BUILD.bazel index c68fca45b..2dcff5a8c 100644 --- a/submitqueue/orchestrator/controller/batch/BUILD.bazel +++ b/submitqueue/orchestrator/controller/batch/BUILD.bazel @@ -32,7 +32,6 @@ go_test( "//platform/base/messagequeue:go_default_library", "//platform/consumer:go_default_library", "//platform/consumer/mock:go_default_library", - "//platform/extension/counter:go_default_library", "//platform/extension/counter/mock:go_default_library", "//platform/extension/messagequeue/mock:go_default_library", "//submitqueue/core/messagequeue:go_default_library", diff --git a/submitqueue/orchestrator/controller/batch/batch_test.go b/submitqueue/orchestrator/controller/batch/batch_test.go index 8257c9ea2..a5bd62082 100644 --- a/submitqueue/orchestrator/controller/batch/batch_test.go +++ b/submitqueue/orchestrator/controller/batch/batch_test.go @@ -30,7 +30,6 @@ import ( entityqueue "github.com/uber/submitqueue/platform/base/messagequeue" "github.com/uber/submitqueue/platform/consumer" consumermock "github.com/uber/submitqueue/platform/consumer/mock" - "github.com/uber/submitqueue/platform/extension/counter" countermock "github.com/uber/submitqueue/platform/extension/counter/mock" queuemock "github.com/uber/submitqueue/platform/extension/messagequeue/mock" sqmq "github.com/uber/submitqueue/submitqueue/core/messagequeue" @@ -69,12 +68,6 @@ func storageFactoryFor(ctrl *gomock.Controller, store orchstorage.Storage) *orch return f } -// staticCounterFactory resolves every queue to the same counter, so tests can keep -// setting expectations on one mock regardless of which queue the controller resolves. -type staticCounterFactory struct{ counter counter.Counter } - -func (f staticCounterFactory) For(counter.Config) (counter.Counter, error) { return f.counter, nil } - // testRequest returns a standard test request for batch tests. func testRequest() entity.Request { return entity.Request{ @@ -123,7 +116,10 @@ func newTestController(t *testing.T, ctrl *gomock.Controller, cnt *countermock.M mockPub := queuemock.NewMockPublisher(ctrl) mockPub.EXPECT().Publish(gomock.Any(), gomock.Any(), gomock.Any()).Return(handoffPublishErr).AnyTimes() - return NewController(logger, scope, newTestRegistry(t, mockPub, ctrl), staticCounterFactory{counter: cnt}, + counterFactory := countermock.NewMockFactory(ctrl) + counterFactory.EXPECT().For(gomock.Any()).Return(cnt, nil).AnyTimes() + + return NewController(logger, scope, newTestRegistry(t, mockPub, ctrl), counterFactory, storageFactoryFor(ctrl, mockStorage), topickey.TopicKeyBatch, "orchestrator-batch") } @@ -222,9 +218,12 @@ func TestController_Process_StampsQueueOnHandoffPayload(t *testing.T) { store.EXPECT().GetBatchStore().Return(batchStore).AnyTimes() store.EXPECT().GetRequestStore().Return(requestStore).AnyTimes() + counterFactory := countermock.NewMockFactory(ctrl) + counterFactory.EXPECT().For(gomock.Any()).Return(newSequentialCounter(ctrl), nil).AnyTimes() + controller := NewController( zaptest.NewLogger(t).Sugar(), tally.NoopScope, newTestRegistry(t, publisher, ctrl), - staticCounterFactory{counter: newSequentialCounter(ctrl)}, + counterFactory, storageFactoryFor(ctrl, store), topickey.TopicKeyBatch, "orchestrator-batch", ) @@ -360,9 +359,12 @@ func TestController_Process_WritesBatchBeforeHandoff(t *testing.T) { store.EXPECT().GetRequestStore().Return(requestStore).AnyTimes() store.EXPECT().GetBatchStore().Return(batchStore).AnyTimes() + counterFactory := countermock.NewMockFactory(ctrl) + counterFactory.EXPECT().For(gomock.Any()).Return(cnt, nil).AnyTimes() + controller := NewController( zaptest.NewLogger(t).Sugar(), tally.NoopScope, newTestRegistry(t, publisher, ctrl), - staticCounterFactory{counter: cnt}, storageFactoryFor(ctrl, store), + counterFactory, storageFactoryFor(ctrl, store), topickey.TopicKeyBatch, "orchestrator-batch", ) @@ -432,9 +434,12 @@ func TestController_Process_PublishesBatchingStatus(t *testing.T) { }, ).AnyTimes() + counterFactory := countermock.NewMockFactory(ctrl) + counterFactory.EXPECT().For(gomock.Any()).Return(newSequentialCounter(ctrl), nil).AnyTimes() + controller := NewController( zaptest.NewLogger(t).Sugar(), tally.NoopScope, newTestRegistry(t, publisher, ctrl), - staticCounterFactory{counter: newSequentialCounter(ctrl)}, + counterFactory, storageFactoryFor(ctrl, store), topickey.TopicKeyBatch, "orchestrator-batch", ) diff --git a/submitqueue/orchestrator/controller/build/BUILD.bazel b/submitqueue/orchestrator/controller/build/BUILD.bazel index 3879f6899..1db29e132 100644 --- a/submitqueue/orchestrator/controller/build/BUILD.bazel +++ b/submitqueue/orchestrator/controller/build/BUILD.bazel @@ -33,11 +33,9 @@ go_test( "//submitqueue/core/messagequeue:go_default_library", "//submitqueue/core/topickey:go_default_library", "//submitqueue/entity:go_default_library", - "//submitqueue/extension/buildrunner:go_default_library", "//submitqueue/extension/buildrunner/mock:go_default_library", "//submitqueue/extension/storage:go_default_library", "//submitqueue/extension/storage/mock:go_default_library", - "//submitqueue/orchestrator/extension/storage:go_default_library", "//submitqueue/orchestrator/extension/storage/mock:go_default_library", "@com_github_stretchr_testify//assert:go_default_library", "@com_github_stretchr_testify//require:go_default_library", diff --git a/submitqueue/orchestrator/controller/build/build_test.go b/submitqueue/orchestrator/controller/build/build_test.go index 96c9c51e3..08c2f385b 100644 --- a/submitqueue/orchestrator/controller/build/build_test.go +++ b/submitqueue/orchestrator/controller/build/build_test.go @@ -19,8 +19,6 @@ import ( "fmt" "testing" - orchstorage "github.com/uber/submitqueue/submitqueue/orchestrator/extension/storage" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/uber-go/tally" @@ -31,7 +29,6 @@ import ( sqmq "github.com/uber/submitqueue/submitqueue/core/messagequeue" "github.com/uber/submitqueue/submitqueue/core/topickey" "github.com/uber/submitqueue/submitqueue/entity" - "github.com/uber/submitqueue/submitqueue/extension/buildrunner" buildrunnermock "github.com/uber/submitqueue/submitqueue/extension/buildrunner/mock" "github.com/uber/submitqueue/submitqueue/extension/storage" storagemock "github.com/uber/submitqueue/submitqueue/extension/storage/mock" @@ -40,14 +37,6 @@ import ( "go.uber.org/zap/zaptest" ) -// staticStorageFactory resolves every queue to one fixed store aggregate. -type staticStorageFactory struct{ store orchstorage.Storage } - -// For returns the fixed store aggregate for any queue. -func (f staticStorageFactory) For(orchstorage.Config) (orchstorage.Storage, error) { - return f.store, nil -} - const ( headID = "test-queue/batch/head" depA = "test-queue/batch/depA" @@ -55,13 +44,6 @@ const ( depC = "test-queue/batch/depC" ) -// staticBuildRunnerFactory is a test factory that returns a fixed BuildRunner. -type staticBuildRunnerFactory struct{ r buildrunner.BuildRunner } - -func (f staticBuildRunnerFactory) For(buildrunner.Config) (buildrunner.BuildRunner, error) { - return f.r, nil -} - func batchIDPayload(t *testing.T, id string) []byte { t.Helper() payload, err := sqmq.MarshalID(sqmq.TopicKeyBuild, id, "test-queue") @@ -144,9 +126,15 @@ func newTestController(t *testing.T, ctrl *gomock.Controller, batch entity.Batch runner := buildrunnermock.NewMockBuildRunner(ctrl) + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + runnerFactory := buildrunnermock.NewMockFactory(ctrl) + runnerFactory.EXPECT().For(gomock.Any()).Return(runner, nil).AnyTimes() + controller := NewController( - zaptest.NewLogger(t).Sugar(), tally.NoopScope, staticStorageFactory{store: store}, - staticBuildRunnerFactory{r: runner}, registry, topickey.TopicKeyBuild, "orchestrator-build", + zaptest.NewLogger(t).Sugar(), tally.NoopScope, storageFactory, + runnerFactory, registry, topickey.TopicKeyBuild, "orchestrator-build", ) return controller, &testDeps{ diff --git a/submitqueue/orchestrator/controller/buildsignal/BUILD.bazel b/submitqueue/orchestrator/controller/buildsignal/BUILD.bazel index 8815a124e..69b9e7681 100644 --- a/submitqueue/orchestrator/controller/buildsignal/BUILD.bazel +++ b/submitqueue/orchestrator/controller/buildsignal/BUILD.bazel @@ -37,7 +37,6 @@ go_test( "//submitqueue/extension/buildrunner/mock:go_default_library", "//submitqueue/extension/storage:go_default_library", "//submitqueue/extension/storage/mock:go_default_library", - "//submitqueue/orchestrator/extension/storage:go_default_library", "//submitqueue/orchestrator/extension/storage/mock:go_default_library", "@com_github_stretchr_testify//assert:go_default_library", "@com_github_stretchr_testify//require:go_default_library", diff --git a/submitqueue/orchestrator/controller/buildsignal/buildsignal_test.go b/submitqueue/orchestrator/controller/buildsignal/buildsignal_test.go index 74d7fd7f7..583814453 100644 --- a/submitqueue/orchestrator/controller/buildsignal/buildsignal_test.go +++ b/submitqueue/orchestrator/controller/buildsignal/buildsignal_test.go @@ -33,7 +33,6 @@ import ( buildrunnermock "github.com/uber/submitqueue/submitqueue/extension/buildrunner/mock" storage "github.com/uber/submitqueue/submitqueue/extension/storage" storagemock "github.com/uber/submitqueue/submitqueue/extension/storage/mock" - orchstorage "github.com/uber/submitqueue/submitqueue/orchestrator/extension/storage" orchstoragemock "github.com/uber/submitqueue/submitqueue/orchestrator/extension/storage/mock" "go.uber.org/mock/gomock" "go.uber.org/zap/zaptest" @@ -65,14 +64,6 @@ type testHarness struct { logs []entity.RequestLog } -// staticStorageFactory resolves every queue to one fixed store aggregate. -type staticStorageFactory struct{ store orchstorage.Storage } - -// For returns the fixed store aggregate for any queue. -func (f staticStorageFactory) For(orchstorage.Config) (orchstorage.Storage, error) { - return f.store, nil -} - // testRequestID is the one member of the batch under test, so the request-log // fan-out has somebody to report to. const testRequestID = "1" @@ -130,10 +121,13 @@ func newTestHarness(t *testing.T, ctrl *gomock.Controller, batchState entity.Bat store.EXPECT().GetSpeculationPathSetStore().Return(pathSets).AnyTimes() store.EXPECT().GetPathBuildStore().Return(pathBuilds).AnyTimes() + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + c := NewController( zaptest.NewLogger(t).Sugar(), tally.NoopScope, - staticStorageFactory{store: store}, + storageFactory, brFactory, registry, topickey.TopicKeyBuildSignal, diff --git a/submitqueue/orchestrator/controller/cancel/cancel_test.go b/submitqueue/orchestrator/controller/cancel/cancel_test.go index a995fcb08..f7dcbb9c6 100644 --- a/submitqueue/orchestrator/controller/cancel/cancel_test.go +++ b/submitqueue/orchestrator/controller/cancel/cancel_test.go @@ -37,16 +37,6 @@ import ( "go.uber.org/zap/zaptest" ) -// newQueueBatchStateStore returns a QueueBatchStateStore mock that accepts any -// membership-record write; cancel never lists record buckets. -// staticStorageFactory resolves every queue to one fixed store aggregate. -type staticStorageFactory struct{ store orchstorage.Storage } - -// For returns the fixed store aggregate for any queue. -func (f staticStorageFactory) For(orchstorage.Config) (orchstorage.Storage, error) { - return f.store, nil -} - func newQueueBatchStateStore(ctrl *gomock.Controller) *storagemock.MockQueueBatchStateStore { s := storagemock.NewMockQueueBatchStateStore(ctrl) s.EXPECT().Put(gomock.Any(), gomock.Any()).Return(nil).AnyTimes() @@ -91,7 +81,10 @@ func newRegistry(t *testing.T, ctrl *gomock.Controller) (consumer.TopicRegistry, } func newController(t *testing.T, store orchstorage.Storage, registry consumer.TopicRegistry) *Controller { - return NewController(zaptest.NewLogger(t).Sugar(), tally.NoopScope, staticStorageFactory{store: store}, registry, topickey.TopicKeyCancel, "orchestrator-cancel") + storageFactory := orchstoragemock.NewMockFactory(gomock.NewController(t)) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + return NewController(zaptest.NewLogger(t).Sugar(), tally.NoopScope, storageFactory, registry, topickey.TopicKeyCancel, "orchestrator-cancel") } func newDelivery(t *testing.T, ctrl *gomock.Controller, payload []byte, partitionKey string) consumer.Delivery { diff --git a/submitqueue/orchestrator/controller/conclude/BUILD.bazel b/submitqueue/orchestrator/controller/conclude/BUILD.bazel index 5cc270f1f..5bafcd6e2 100644 --- a/submitqueue/orchestrator/controller/conclude/BUILD.bazel +++ b/submitqueue/orchestrator/controller/conclude/BUILD.bazel @@ -33,7 +33,6 @@ go_test( "//submitqueue/entity:go_default_library", "//submitqueue/extension/storage:go_default_library", "//submitqueue/extension/storage/mock:go_default_library", - "//submitqueue/orchestrator/extension/storage:go_default_library", "//submitqueue/orchestrator/extension/storage/mock:go_default_library", "@com_github_stretchr_testify//assert:go_default_library", "@com_github_stretchr_testify//require:go_default_library", diff --git a/submitqueue/orchestrator/controller/conclude/conclude_test.go b/submitqueue/orchestrator/controller/conclude/conclude_test.go index 21c5f1c18..62d1cb162 100644 --- a/submitqueue/orchestrator/controller/conclude/conclude_test.go +++ b/submitqueue/orchestrator/controller/conclude/conclude_test.go @@ -32,20 +32,11 @@ import ( "github.com/uber/submitqueue/submitqueue/entity" storage "github.com/uber/submitqueue/submitqueue/extension/storage" storagemock "github.com/uber/submitqueue/submitqueue/extension/storage/mock" - orchstorage "github.com/uber/submitqueue/submitqueue/orchestrator/extension/storage" orchstoragemock "github.com/uber/submitqueue/submitqueue/orchestrator/extension/storage/mock" "go.uber.org/mock/gomock" "go.uber.org/zap/zaptest" ) -// staticStorageFactory resolves every queue to one fixed store aggregate. -type staticStorageFactory struct{ store orchstorage.Storage } - -// For returns the fixed store aggregate for any queue. -func (f staticStorageFactory) For(orchstorage.Config) (orchstorage.Storage, error) { - return f.store, nil -} - func requestWithState(request entity.Request, state entity.RequestState) entity.Request { request.State = state return request @@ -88,7 +79,10 @@ func newTestController(t *testing.T, ctrl *gomock.Controller, mockStorage *orchs ) require.NoError(t, err) - return NewController(logger, scope, staticStorageFactory{store: mockStorage}, registry, topickey.TopicKeyConclude, "orchestrator-conclude"), mockPub + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(mockStorage, nil).AnyTimes() + + return NewController(logger, scope, storageFactory, registry, topickey.TopicKeyConclude, "orchestrator-conclude"), mockPub } func TestNewController(t *testing.T) { diff --git a/submitqueue/orchestrator/controller/dlq/batch_test.go b/submitqueue/orchestrator/controller/dlq/batch_test.go index 0c0b4c045..a99fdf05a 100644 --- a/submitqueue/orchestrator/controller/dlq/batch_test.go +++ b/submitqueue/orchestrator/controller/dlq/batch_test.go @@ -35,7 +35,10 @@ func TestDLQBatchController_InterfaceAndAccessors(t *testing.T) { store := orchstoragemock.NewMockStorage(ctrl) store.EXPECT().GetQueueBatchStateStore().Return(newQueueBatchStateStore(ctrl)).AnyTimes() - c := NewDLQBatchController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, consumer.TopicRegistry{}, TopicKey(topickey.TopicKeyLand), "orchestrator-land-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQBatchController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, consumer.TopicRegistry{}, TopicKey(topickey.TopicKeyLand), "orchestrator-land-dlq") assert.Equal(t, "submitqueue-land_dlq", c.Name()) assert.Equal(t, consumer.TopicKey("submitqueue-land_dlq"), c.TopicKey()) @@ -69,7 +72,10 @@ func TestDLQBatchController_Process_FailsAndFansOut(t *testing.T) { store.EXPECT().GetBatchStore().Return(batchStore).AnyTimes() store.EXPECT().GetRequestStore().Return(requestStore).AnyTimes() - c := NewDLQBatchController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, registry, TopicKey(topickey.TopicKeyLand), "orchestrator-land-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQBatchController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, registry, TopicKey(topickey.TopicKeyLand), "orchestrator-land-dlq") payload, err := sqmq.MarshalID(sqmq.TopicKeyLand, "9", "q") require.NoError(t, err) @@ -81,7 +87,10 @@ func TestDLQBatchController_Process_FailsAndFansOut(t *testing.T) { func TestDLQBatchController_Process_TenantPayloadQueueMismatchAcks(t *testing.T) { ctrl := gomock.NewController(t) store := orchstoragemock.NewMockStorage(ctrl) - c := NewDLQBatchController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, consumer.TopicRegistry{}, TopicKey(topickey.TopicKeyLand), "orchestrator-land-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQBatchController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, consumer.TopicRegistry{}, TopicKey(topickey.TopicKeyLand), "orchestrator-land-dlq") payload, err := sqmq.MarshalID(sqmq.TopicKeyLand, "9", "q") require.NoError(t, err) @@ -94,7 +103,10 @@ func TestDLQBatchController_Process_MalformedPayloadFails(t *testing.T) { store := orchstoragemock.NewMockStorage(ctrl) store.EXPECT().GetQueueBatchStateStore().Return(newQueueBatchStateStore(ctrl)).AnyTimes() - c := NewDLQBatchController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, consumer.TopicRegistry{}, TopicKey(topickey.TopicKeyLand), "orchestrator-land-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQBatchController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, consumer.TopicRegistry{}, TopicKey(topickey.TopicKeyLand), "orchestrator-land-dlq") delivery := newMockDelivery(ctrl, []byte("garbage")) err := c.Process(context.Background(), delivery) @@ -106,7 +118,10 @@ func TestDLQBatchController_Process_EmptyIDFails(t *testing.T) { store := orchstoragemock.NewMockStorage(ctrl) store.EXPECT().GetQueueBatchStateStore().Return(newQueueBatchStateStore(ctrl)).AnyTimes() - c := NewDLQBatchController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, consumer.TopicRegistry{}, TopicKey(topickey.TopicKeyLand), "orchestrator-land-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQBatchController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, consumer.TopicRegistry{}, TopicKey(topickey.TopicKeyLand), "orchestrator-land-dlq") payload, err := sqmq.MarshalID(sqmq.TopicKeyLand, "", "q") require.NoError(t, err) diff --git a/submitqueue/orchestrator/controller/dlq/buildsignal_test.go b/submitqueue/orchestrator/controller/dlq/buildsignal_test.go index c58b195de..792266bb4 100644 --- a/submitqueue/orchestrator/controller/dlq/buildsignal_test.go +++ b/submitqueue/orchestrator/controller/dlq/buildsignal_test.go @@ -36,7 +36,10 @@ func TestDLQBuildSignalController_InterfaceAndAccessors(t *testing.T) { store := orchstoragemock.NewMockStorage(ctrl) store.EXPECT().GetQueueBatchStateStore().Return(newQueueBatchStateStore(ctrl)).AnyTimes() - c := NewDLQBuildSignalController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, consumer.TopicRegistry{}, TopicKey(topickey.TopicKeyBuildSignal), "orchestrator-buildsignal-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQBuildSignalController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, consumer.TopicRegistry{}, TopicKey(topickey.TopicKeyBuildSignal), "orchestrator-buildsignal-dlq") assert.Equal(t, "buildsignal_dlq", c.Name()) assert.Equal(t, consumer.TopicKey("buildsignal_dlq"), c.TopicKey()) @@ -77,7 +80,10 @@ func TestDLQBuildSignalController_Process_FansOutToBatch(t *testing.T) { store.EXPECT().GetBatchStore().Return(batchStore).AnyTimes() store.EXPECT().GetRequestStore().Return(requestStore).AnyTimes() - c := NewDLQBuildSignalController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, registry, TopicKey(topickey.TopicKeyBuildSignal), "orchestrator-buildsignal-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQBuildSignalController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, registry, TopicKey(topickey.TopicKeyBuildSignal), "orchestrator-buildsignal-dlq") payload, err := sqmq.MarshalID(sqmq.TopicKeyBuildSignal, "build-1", "q") require.NoError(t, err) @@ -89,7 +95,10 @@ func TestDLQBuildSignalController_Process_FansOutToBatch(t *testing.T) { func TestDLQBuildSignalController_Process_TenantPayloadQueueMismatchAcks(t *testing.T) { ctrl := gomock.NewController(t) store := orchstoragemock.NewMockStorage(ctrl) - c := NewDLQBuildSignalController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, consumer.TopicRegistry{}, TopicKey(topickey.TopicKeyBuildSignal), "orchestrator-buildsignal-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQBuildSignalController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, consumer.TopicRegistry{}, TopicKey(topickey.TopicKeyBuildSignal), "orchestrator-buildsignal-dlq") payload, err := sqmq.MarshalID(sqmq.TopicKeyBuildSignal, "build-1", "q") require.NoError(t, err) @@ -107,7 +116,10 @@ func TestDLQBuildSignalController_Process_BuildNotFoundIsNoOp(t *testing.T) { store.EXPECT().GetQueueBatchStateStore().Return(newQueueBatchStateStore(ctrl)).AnyTimes() store.EXPECT().GetBuildStore().Return(buildStore).AnyTimes() - c := NewDLQBuildSignalController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, consumer.TopicRegistry{}, TopicKey(topickey.TopicKeyBuildSignal), "orchestrator-buildsignal-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQBuildSignalController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, consumer.TopicRegistry{}, TopicKey(topickey.TopicKeyBuildSignal), "orchestrator-buildsignal-dlq") payload, err := sqmq.MarshalID(sqmq.TopicKeyBuildSignal, "build-1", "q") require.NoError(t, err) @@ -128,7 +140,10 @@ func TestDLQBuildSignalController_Process_BuildMissingBatchIsNoOp(t *testing.T) store.EXPECT().GetQueueBatchStateStore().Return(newQueueBatchStateStore(ctrl)).AnyTimes() store.EXPECT().GetBuildStore().Return(buildStore).AnyTimes() - c := NewDLQBuildSignalController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, consumer.TopicRegistry{}, TopicKey(topickey.TopicKeyBuildSignal), "orchestrator-buildsignal-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQBuildSignalController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, consumer.TopicRegistry{}, TopicKey(topickey.TopicKeyBuildSignal), "orchestrator-buildsignal-dlq") payload, err := sqmq.MarshalID(sqmq.TopicKeyBuildSignal, "build-1", "q") require.NoError(t, err) @@ -142,7 +157,10 @@ func TestDLQBuildSignalController_Process_MalformedPayloadFails(t *testing.T) { store := orchstoragemock.NewMockStorage(ctrl) store.EXPECT().GetQueueBatchStateStore().Return(newQueueBatchStateStore(ctrl)).AnyTimes() - c := NewDLQBuildSignalController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, consumer.TopicRegistry{}, TopicKey(topickey.TopicKeyBuildSignal), "orchestrator-buildsignal-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQBuildSignalController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, consumer.TopicRegistry{}, TopicKey(topickey.TopicKeyBuildSignal), "orchestrator-buildsignal-dlq") delivery := newMockDelivery(ctrl, []byte("garbage")) err := c.Process(context.Background(), delivery) diff --git a/submitqueue/orchestrator/controller/dlq/conclude_test.go b/submitqueue/orchestrator/controller/dlq/conclude_test.go index b09487469..bd84c2a78 100644 --- a/submitqueue/orchestrator/controller/dlq/conclude_test.go +++ b/submitqueue/orchestrator/controller/dlq/conclude_test.go @@ -77,7 +77,10 @@ func TestDLQConcludeController_TerminalOutcomes(t *testing.T) { assert.Equal(t, "9", log.Metadata["batch_id"]) return nil }) - controller := NewDLQConcludeController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store}, registry, TopicKey(topickey.TopicKeyConclude), "conclude-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + controller := NewDLQConcludeController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, registry, TopicKey(topickey.TopicKeyConclude), "conclude-dlq") require.NoError(t, controller.Process(context.Background(), concludeDelivery(t, ctrl, "merge conflict"))) }) } @@ -119,7 +122,10 @@ func TestDLQConcludeController_ReplaysPartialFanout(t *testing.T) { } return nil }) - controller := NewDLQConcludeController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store}, registry, TopicKey(topickey.TopicKeyConclude), "conclude-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + controller := NewDLQConcludeController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, registry, TopicKey(topickey.TopicKeyConclude), "conclude-dlq") require.ErrorIs(t, controller.Process(context.Background(), concludeDelivery(t, ctrl, "merge conflict")), publishErr) require.NoError(t, controller.Process(context.Background(), concludeDelivery(t, ctrl, "later infrastructure error"))) require.Len(t, logs, 4) diff --git a/submitqueue/orchestrator/controller/dlq/dependencyanalysis_test.go b/submitqueue/orchestrator/controller/dlq/dependencyanalysis_test.go index f73fb012e..2ed3029d5 100644 --- a/submitqueue/orchestrator/controller/dlq/dependencyanalysis_test.go +++ b/submitqueue/orchestrator/controller/dlq/dependencyanalysis_test.go @@ -39,7 +39,10 @@ const ( ) func newDependencyAnalysisController(t *testing.T, store *orchstoragemock.MockStorage, registry consumer.TopicRegistry) consumer.Controller { - return NewDLQDependencyAnalysisController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, registry, + storageFactory := orchstoragemock.NewMockFactory(gomock.NewController(t)) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + return NewDLQDependencyAnalysisController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, registry, TopicKey(topickey.TopicKeyDependencyAnalysis), dependencyAnalysisDLQGroup) } diff --git a/submitqueue/orchestrator/controller/dlq/dlq_test.go b/submitqueue/orchestrator/controller/dlq/dlq_test.go index 02fd82063..a2de04d5a 100644 --- a/submitqueue/orchestrator/controller/dlq/dlq_test.go +++ b/submitqueue/orchestrator/controller/dlq/dlq_test.go @@ -19,8 +19,6 @@ import ( "fmt" "testing" - orchstorage "github.com/uber/submitqueue/submitqueue/orchestrator/extension/storage" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/uber-go/tally" @@ -34,16 +32,6 @@ import ( "go.uber.org/zap/zaptest" ) -// newQueueBatchStateStore returns a QueueBatchStateStore mock that accepts any -// membership-record write; these tests never list record buckets. -// staticStorageFactory resolves every queue to one fixed store aggregate. -type staticStorageFactory struct{ store orchstorage.Storage } - -// For returns the fixed store aggregate for any queue. -func (f staticStorageFactory) For(orchstorage.Config) (orchstorage.Storage, error) { - return f.store, nil -} - // noBatchAssociations answers the owning-batch lookup with nothing, i.e. no // batch ever enrolled the request. func noBatchAssociations(ctrl *gomock.Controller) *storagemock.MockRequestBatchStore { diff --git a/submitqueue/orchestrator/controller/dlq/landconflictsignal_test.go b/submitqueue/orchestrator/controller/dlq/landconflictsignal_test.go index 4c7479438..67bbed6e3 100644 --- a/submitqueue/orchestrator/controller/dlq/landconflictsignal_test.go +++ b/submitqueue/orchestrator/controller/dlq/landconflictsignal_test.go @@ -35,7 +35,10 @@ func TestDLQLandConflictSignalController_InterfaceAndAccessors(t *testing.T) { store := orchstoragemock.NewMockStorage(ctrl) store.EXPECT().GetQueueBatchStateStore().Return(newQueueBatchStateStore(ctrl)).AnyTimes() - c := NewDLQLandConflictSignalController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, consumer.TopicRegistry{}, TopicKey(runwaymq.TopicKeyMergeConflictCheckSignal), "orchestrator-landconflictsignal-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQLandConflictSignalController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, consumer.TopicRegistry{}, TopicKey(runwaymq.TopicKeyMergeConflictCheckSignal), "orchestrator-landconflictsignal-dlq") assert.Equal(t, "merge-conflict-check-signal_dlq", c.Name()) assert.Equal(t, consumer.TopicKey("merge-conflict-check-signal_dlq"), c.TopicKey()) @@ -60,7 +63,10 @@ func TestDLQLandConflictSignalController_Process_ReconcilesRequest(t *testing.T) store.EXPECT().GetQueueBatchStateStore().Return(newQueueBatchStateStore(ctrl)).AnyTimes() store.EXPECT().GetRequestStore().Return(requestStore).AnyTimes() - c := NewDLQLandConflictSignalController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, registry, TopicKey(runwaymq.TopicKeyMergeConflictCheckSignal), "orchestrator-landconflictsignal-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQLandConflictSignalController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, registry, TopicKey(runwaymq.TopicKeyMergeConflictCheckSignal), "orchestrator-landconflictsignal-dlq") payload, err := runwaymq.Marshal(&runwaymq.MergeResult{Id: "1", QueueName: "q", Outcome: runwaypb.Outcome_FAILED, Reason: "boom"}) require.NoError(t, err) @@ -72,7 +78,10 @@ func TestDLQLandConflictSignalController_Process_ReconcilesRequest(t *testing.T) func TestDLQLandConflictSignalController_Process_TenantPayloadQueueMismatchAcks(t *testing.T) { ctrl := gomock.NewController(t) store := orchstoragemock.NewMockStorage(ctrl) - c := NewDLQLandConflictSignalController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, consumer.TopicRegistry{}, TopicKey(runwaymq.TopicKeyMergeConflictCheckSignal), "orchestrator-landconflictsignal-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQLandConflictSignalController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, consumer.TopicRegistry{}, TopicKey(runwaymq.TopicKeyMergeConflictCheckSignal), "orchestrator-landconflictsignal-dlq") payload, err := runwaymq.Marshal(&runwaymq.MergeResult{Id: "1", QueueName: "q", Outcome: runwaypb.Outcome_FAILED, Reason: "boom"}) require.NoError(t, err) @@ -85,7 +94,10 @@ func TestDLQLandConflictSignalController_Process_MalformedPayloadFails(t *testin store := orchstoragemock.NewMockStorage(ctrl) store.EXPECT().GetQueueBatchStateStore().Return(newQueueBatchStateStore(ctrl)).AnyTimes() - c := NewDLQLandConflictSignalController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, consumer.TopicRegistry{}, TopicKey(runwaymq.TopicKeyMergeConflictCheckSignal), "orchestrator-landconflictsignal-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQLandConflictSignalController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, consumer.TopicRegistry{}, TopicKey(runwaymq.TopicKeyMergeConflictCheckSignal), "orchestrator-landconflictsignal-dlq") delivery := newMockDelivery(ctrl, []byte("garbage")) require.Error(t, c.Process(context.Background(), delivery)) diff --git a/submitqueue/orchestrator/controller/dlq/landsignal_test.go b/submitqueue/orchestrator/controller/dlq/landsignal_test.go index 938e3da8c..8725524fe 100644 --- a/submitqueue/orchestrator/controller/dlq/landsignal_test.go +++ b/submitqueue/orchestrator/controller/dlq/landsignal_test.go @@ -35,7 +35,10 @@ func TestDLQLandSignalController_InterfaceAndAccessors(t *testing.T) { store := orchstoragemock.NewMockStorage(ctrl) store.EXPECT().GetQueueBatchStateStore().Return(newQueueBatchStateStore(ctrl)).AnyTimes() - c := NewDLQLandSignalController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, consumer.TopicRegistry{}, TopicKey(runwaymq.TopicKeyMergeSignal), "orchestrator-landsignal-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQLandSignalController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, consumer.TopicRegistry{}, TopicKey(runwaymq.TopicKeyMergeSignal), "orchestrator-landsignal-dlq") assert.Equal(t, "merge-signal_dlq", c.Name()) assert.Equal(t, consumer.TopicKey("merge-signal_dlq"), c.TopicKey()) @@ -71,7 +74,10 @@ func TestDLQLandSignalController_Process_ReconcilesBatch(t *testing.T) { store.EXPECT().GetBatchStore().Return(batchStore).AnyTimes() store.EXPECT().GetRequestStore().Return(requestStore).AnyTimes() - c := NewDLQLandSignalController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, registry, TopicKey(runwaymq.TopicKeyMergeSignal), "orchestrator-landsignal-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQLandSignalController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, registry, TopicKey(runwaymq.TopicKeyMergeSignal), "orchestrator-landsignal-dlq") payload, err := runwaymq.Marshal(&runwaymq.MergeResult{Id: "1", QueueName: "q", Outcome: runwaypb.Outcome_FAILED, Reason: "boom"}) require.NoError(t, err) @@ -83,7 +89,10 @@ func TestDLQLandSignalController_Process_ReconcilesBatch(t *testing.T) { func TestDLQLandSignalController_Process_TenantPayloadQueueMismatchAcks(t *testing.T) { ctrl := gomock.NewController(t) store := orchstoragemock.NewMockStorage(ctrl) - c := NewDLQLandSignalController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, consumer.TopicRegistry{}, TopicKey(runwaymq.TopicKeyMergeSignal), "orchestrator-landsignal-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQLandSignalController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, consumer.TopicRegistry{}, TopicKey(runwaymq.TopicKeyMergeSignal), "orchestrator-landsignal-dlq") payload, err := runwaymq.Marshal(&runwaymq.MergeResult{Id: "1", QueueName: "q", Outcome: runwaypb.Outcome_FAILED, Reason: "boom"}) require.NoError(t, err) @@ -96,7 +105,10 @@ func TestDLQLandSignalController_Process_MalformedPayloadFails(t *testing.T) { store := orchstoragemock.NewMockStorage(ctrl) store.EXPECT().GetQueueBatchStateStore().Return(newQueueBatchStateStore(ctrl)).AnyTimes() - c := NewDLQLandSignalController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, consumer.TopicRegistry{}, TopicKey(runwaymq.TopicKeyMergeSignal), "orchestrator-landsignal-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQLandSignalController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, consumer.TopicRegistry{}, TopicKey(runwaymq.TopicKeyMergeSignal), "orchestrator-landsignal-dlq") delivery := newMockDelivery(ctrl, []byte("garbage")) require.Error(t, c.Process(context.Background(), delivery)) diff --git a/submitqueue/orchestrator/controller/dlq/request_test.go b/submitqueue/orchestrator/controller/dlq/request_test.go index 0e44b57b9..dc60b102d 100644 --- a/submitqueue/orchestrator/controller/dlq/request_test.go +++ b/submitqueue/orchestrator/controller/dlq/request_test.go @@ -39,7 +39,10 @@ func TestDLQRequestController_InterfaceAndAccessors(t *testing.T) { store.EXPECT().GetQueueBatchStateStore().Return(newQueueBatchStateStore(ctrl)).AnyTimes() store.EXPECT().GetRequestBatchStore().Return(noBatchAssociations(ctrl)).AnyTimes() - c := NewDLQRequestController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, consumer.TopicRegistry{}, DecodeRequestID(topickey.TopicKeyValidate), TopicKey(topickey.TopicKeyValidate), "orchestrator-validate-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQRequestController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, consumer.TopicRegistry{}, DecodeRequestID(topickey.TopicKeyValidate), TopicKey(topickey.TopicKeyValidate), "orchestrator-validate-dlq") assert.Equal(t, "validate_dlq", c.Name()) assert.Equal(t, consumer.TopicKey("validate_dlq"), c.TopicKey()) @@ -65,7 +68,10 @@ func TestDLQRequestController_Process_LandRequestPayload(t *testing.T) { store.EXPECT().GetRequestBatchStore().Return(noBatchAssociations(ctrl)).AnyTimes() store.EXPECT().GetRequestStore().Return(requestStore).AnyTimes() - c := NewDLQRequestController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, registry, decodeLandRequestID, TopicKey(topickey.TopicKeyStart), "orchestrator-start-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQRequestController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, registry, decodeLandRequestID, TopicKey(topickey.TopicKeyStart), "orchestrator-start-dlq") payload, err := sqmq.Marshal(sqmq.StartFromLandRequest(entity.LandRequest{ID: "1", Queue: "q"})) require.NoError(t, err) @@ -77,7 +83,10 @@ func TestDLQRequestController_Process_LandRequestPayload(t *testing.T) { func TestDLQRequestController_Process_TenantPayloadQueueMismatchAcks(t *testing.T) { ctrl := gomock.NewController(t) store := orchstoragemock.NewMockStorage(ctrl) - c := NewDLQRequestController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, consumer.TopicRegistry{}, DecodeRequestID(topickey.TopicKeyValidate), TopicKey(topickey.TopicKeyValidate), "orchestrator-validate-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQRequestController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, consumer.TopicRegistry{}, DecodeRequestID(topickey.TopicKeyValidate), TopicKey(topickey.TopicKeyValidate), "orchestrator-validate-dlq") payload, err := sqmq.MarshalID(sqmq.TopicKeyValidate, "1", "q") require.NoError(t, err) @@ -104,7 +113,10 @@ func TestDLQRequestController_Process_CancelRequestPayload(t *testing.T) { store.EXPECT().GetRequestBatchStore().Return(noBatchAssociations(ctrl)).AnyTimes() store.EXPECT().GetRequestStore().Return(requestStore).AnyTimes() - c := NewDLQRequestController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, registry, DecodeCancelRequestID, TopicKey(topickey.TopicKeyCancel), "orchestrator-cancel-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQRequestController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, registry, DecodeCancelRequestID, TopicKey(topickey.TopicKeyCancel), "orchestrator-cancel-dlq") payload, err := sqmq.Marshal(sqmq.CancelFromEntity(entity.CancelRequest{ID: "7", Queue: "q", Reason: "user"})) require.NoError(t, err) @@ -133,7 +145,10 @@ func TestDLQRequestController_Process_RequestIDPayload(t *testing.T) { store.EXPECT().GetRequestBatchStore().Return(noBatchAssociations(ctrl)).AnyTimes() store.EXPECT().GetRequestStore().Return(requestStore).AnyTimes() - c := NewDLQRequestController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, registry, DecodeRequestID(topickey.TopicKeyBatch), TopicKey(topickey.TopicKeyBatch), "orchestrator-batch-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQRequestController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, registry, DecodeRequestID(topickey.TopicKeyBatch), TopicKey(topickey.TopicKeyBatch), "orchestrator-batch-dlq") payload, err := sqmq.MarshalID(sqmq.TopicKeyBatch, "3", "q") require.NoError(t, err) @@ -155,7 +170,10 @@ func TestDLQRequestController_Process_DifferentTerminalOutcomeSkips(t *testing.T store.EXPECT().GetRequestBatchStore().Return(noBatchAssociations(ctrl)).AnyTimes() store.EXPECT().GetRequestStore().Return(requestStore).AnyTimes() - c := NewDLQRequestController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, consumer.TopicRegistry{}, DecodeRequestID(topickey.TopicKeyValidate), TopicKey(topickey.TopicKeyValidate), "orchestrator-validate-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQRequestController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, consumer.TopicRegistry{}, DecodeRequestID(topickey.TopicKeyValidate), TopicKey(topickey.TopicKeyValidate), "orchestrator-validate-dlq") payload, err := sqmq.MarshalID(sqmq.TopicKeyValidate, "1", "q") require.NoError(t, err) @@ -172,7 +190,10 @@ func TestDLQRequestController_Process_MalformedPayloadFails(t *testing.T) { store.EXPECT().GetRequestBatchStore().Return(noBatchAssociations(ctrl)).AnyTimes() // no store calls expected - c := NewDLQRequestController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, consumer.TopicRegistry{}, DecodeRequestID(topickey.TopicKeyValidate), TopicKey(topickey.TopicKeyValidate), "orchestrator-validate-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQRequestController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, consumer.TopicRegistry{}, DecodeRequestID(topickey.TopicKeyValidate), TopicKey(topickey.TopicKeyValidate), "orchestrator-validate-dlq") delivery := newMockDelivery(ctrl, []byte("not json")) err := c.Process(context.Background(), delivery) @@ -187,7 +208,10 @@ func TestDLQRequestController_Process_EmptyIDFails(t *testing.T) { store.EXPECT().GetRequestBatchStore().Return(noBatchAssociations(ctrl)).AnyTimes() // no store calls expected - c := NewDLQRequestController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, consumer.TopicRegistry{}, DecodeRequestID(topickey.TopicKeyValidate), TopicKey(topickey.TopicKeyValidate), "orchestrator-validate-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQRequestController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, consumer.TopicRegistry{}, DecodeRequestID(topickey.TopicKeyValidate), TopicKey(topickey.TopicKeyValidate), "orchestrator-validate-dlq") payload, err := sqmq.MarshalID(sqmq.TopicKeyValidate, "", "q") require.NoError(t, err) @@ -256,7 +280,10 @@ func TestDLQRequestController_Process_SkipsRequestOwnedByLiveBatch(t *testing.T) store.EXPECT().GetBatchStore().Return(batchStore).AnyTimes() store.EXPECT().GetRequestStore().Return(storagemock.NewMockRequestStore(ctrl)).AnyTimes() - c := NewDLQRequestController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQRequestController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, consumer.TopicRegistry{}, DecodeRequestID(topickey.TopicKeyBatch), TopicKey(topickey.TopicKeyBatch), "orchestrator-batch-dlq") payload, err := sqmq.MarshalID(sqmq.TopicKeyBatch, "1", "q") @@ -294,7 +321,10 @@ func TestDLQRequestController_Process_FailsWhenAssociatedBatchFailed(t *testing. store.EXPECT().GetBatchStore().Return(batchStore).AnyTimes() store.EXPECT().GetRequestStore().Return(requestStore).AnyTimes() - c := NewDLQRequestController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQRequestController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, registry, DecodeRequestID(topickey.TopicKeyBatch), TopicKey(topickey.TopicKeyBatch), "orchestrator-batch-dlq") payload, err := sqmq.MarshalID(sqmq.TopicKeyBatch, "1", "q") @@ -338,7 +368,10 @@ func TestDLQRequestController_Process_FailsWhenCreatingBatchNeverClaimed(t *test store.EXPECT().GetBatchStore().Return(batchStore).AnyTimes() store.EXPECT().GetRequestStore().Return(requestStore).AnyTimes() - c := NewDLQRequestController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQRequestController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, registry, DecodeRequestID(topickey.TopicKeyBatch), TopicKey(topickey.TopicKeyBatch), "orchestrator-batch-dlq") payload, err := sqmq.MarshalID(sqmq.TopicKeyBatch, "1", "q") @@ -376,7 +409,10 @@ func TestDLQRequestController_Process_SkipsWhenCreatingBatchAlreadyClaimed(t *te store.EXPECT().GetBatchStore().Return(batchStore).AnyTimes() store.EXPECT().GetRequestStore().Return(requestStore).AnyTimes() - c := NewDLQRequestController(zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + c := NewDLQRequestController(zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, consumer.TopicRegistry{}, DecodeRequestID(topickey.TopicKeyBatch), TopicKey(topickey.TopicKeyBatch), "orchestrator-batch-dlq") payload, err := sqmq.MarshalID(sqmq.TopicKeyBatch, "1", "q") diff --git a/submitqueue/orchestrator/controller/dlq/speculate_test.go b/submitqueue/orchestrator/controller/dlq/speculate_test.go index a9e4479cf..e63f1fad9 100644 --- a/submitqueue/orchestrator/controller/dlq/speculate_test.go +++ b/submitqueue/orchestrator/controller/dlq/speculate_test.go @@ -34,8 +34,11 @@ import ( ) func newSpeculateController(registry consumer.TopicRegistry, store *orchstoragemock.MockStorage, t *testing.T) consumer.Controller { + storageFactory := orchstoragemock.NewMockFactory(gomock.NewController(t)) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + return NewDLQSpeculateController( - zaptest.NewLogger(t).Sugar(), testScope(), staticStorageFactory{store: store}, + zaptest.NewLogger(t).Sugar(), testScope(), storageFactory, registry, TopicKey(topickey.TopicKeySpeculate), "orchestrator-speculate-dlq", ) } diff --git a/submitqueue/orchestrator/controller/dlq/start_test.go b/submitqueue/orchestrator/controller/dlq/start_test.go index 49d9ad0ef..e9d15775a 100644 --- a/submitqueue/orchestrator/controller/dlq/start_test.go +++ b/submitqueue/orchestrator/controller/dlq/start_test.go @@ -123,7 +123,10 @@ func TestDLQStartController_ReconcilesOnlyError(t *testing.T) { return nil }) scope := tally.NewTestScope("", nil) - controller := NewDLQStartController(zaptest.NewLogger(t).Sugar(), scope, staticStorageFactory{store}, registry, TopicKey(topickey.TopicKeyStart), "orchestrator-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + controller := NewDLQStartController(zaptest.NewLogger(t).Sugar(), scope, storageFactory, registry, TopicKey(topickey.TopicKeyStart), "orchestrator-dlq") payload, err := sqmq.Marshal(sqmq.StartFromLandRequest(landRequest)) require.NoError(t, err) tenant := landRequest.Queue @@ -282,7 +285,10 @@ func TestDLQStartController_RejectsMalformedPayload(t *testing.T) { t.Run(payload, func(t *testing.T) { ctrl := gomock.NewController(t) scope := tally.NewTestScope("", nil) - controller := NewDLQStartController(zaptest.NewLogger(t).Sugar(), scope, staticStorageFactory{orchstoragemock.NewMockStorage(ctrl)}, consumer.TopicRegistry{}, TopicKey(topickey.TopicKeyStart), "orchestrator-dlq") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(orchstoragemock.NewMockStorage(ctrl), nil).AnyTimes() + + controller := NewDLQStartController(zaptest.NewLogger(t).Sugar(), scope, storageFactory, consumer.TopicRegistry{}, TopicKey(topickey.TopicKeyStart), "orchestrator-dlq") require.Error(t, controller.Process(context.Background(), newMockDelivery(ctrl, []byte(payload)))) require.Contains(t, scope.Snapshot().Counters(), "start_dlq.process.reconcile_errors+") assert.EqualValues(t, 1, scope.Snapshot().Counters()["start_dlq.process.reconcile_errors+"].Value()) diff --git a/submitqueue/orchestrator/controller/land/BUILD.bazel b/submitqueue/orchestrator/controller/land/BUILD.bazel index 480145ba9..e962212cd 100644 --- a/submitqueue/orchestrator/controller/land/BUILD.bazel +++ b/submitqueue/orchestrator/controller/land/BUILD.bazel @@ -41,7 +41,6 @@ go_test( "//submitqueue/core/topickey:go_default_library", "//submitqueue/entity:go_default_library", "//submitqueue/extension/storage/mock:go_default_library", - "//submitqueue/orchestrator/extension/storage:go_default_library", "//submitqueue/orchestrator/extension/storage/mock:go_default_library", "@com_github_stretchr_testify//assert:go_default_library", "@com_github_stretchr_testify//require:go_default_library", diff --git a/submitqueue/orchestrator/controller/land/land_test.go b/submitqueue/orchestrator/controller/land/land_test.go index 67a8d5ccf..1197886f8 100644 --- a/submitqueue/orchestrator/controller/land/land_test.go +++ b/submitqueue/orchestrator/controller/land/land_test.go @@ -38,18 +38,9 @@ import ( "github.com/uber/submitqueue/submitqueue/core/topickey" "github.com/uber/submitqueue/submitqueue/entity" storagemock "github.com/uber/submitqueue/submitqueue/extension/storage/mock" - orchstorage "github.com/uber/submitqueue/submitqueue/orchestrator/extension/storage" orchstoragemock "github.com/uber/submitqueue/submitqueue/orchestrator/extension/storage/mock" ) -// staticStorageFactory resolves every queue to one fixed store aggregate. -type staticStorageFactory struct{ store orchstorage.Storage } - -// For returns the fixed store aggregate for any queue. -func (f staticStorageFactory) For(orchstorage.Config) (orchstorage.Storage, error) { - return f.store, nil -} - func batchIDPayload(t *testing.T, id, queue string) []byte { payload, err := sqmq.MarshalID(sqmq.TopicKeyLand, id, queue) require.NoError(t, err) @@ -86,10 +77,13 @@ func newDelivery(t *testing.T, ctrl *gomock.Controller, batchID, partitionKey st } func newController(t *testing.T, store *orchstoragemock.MockStorage, registry consumer.TopicRegistry) *Controller { + storageFactory := orchstoragemock.NewMockFactory(gomock.NewController(t)) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + return NewController( zaptest.NewLogger(t).Sugar(), tally.NoopScope, - staticStorageFactory{store: store}, + storageFactory, registry, runwaymq.TopicKeyMerge, topickey.TopicKeyLand, diff --git a/submitqueue/orchestrator/controller/landconflictsignal/BUILD.bazel b/submitqueue/orchestrator/controller/landconflictsignal/BUILD.bazel index 21959708e..79b3481c3 100644 --- a/submitqueue/orchestrator/controller/landconflictsignal/BUILD.bazel +++ b/submitqueue/orchestrator/controller/landconflictsignal/BUILD.bazel @@ -37,7 +37,6 @@ go_test( "//submitqueue/core/topickey:go_default_library", "//submitqueue/entity:go_default_library", "//submitqueue/extension/storage/mock:go_default_library", - "//submitqueue/orchestrator/extension/storage:go_default_library", "//submitqueue/orchestrator/extension/storage/mock:go_default_library", "@com_github_stretchr_testify//assert:go_default_library", "@com_github_stretchr_testify//require:go_default_library", diff --git a/submitqueue/orchestrator/controller/landconflictsignal/landconflictsignal_test.go b/submitqueue/orchestrator/controller/landconflictsignal/landconflictsignal_test.go index 9947651e2..368f4fe06 100644 --- a/submitqueue/orchestrator/controller/landconflictsignal/landconflictsignal_test.go +++ b/submitqueue/orchestrator/controller/landconflictsignal/landconflictsignal_test.go @@ -32,20 +32,11 @@ import ( "github.com/uber/submitqueue/submitqueue/core/topickey" "github.com/uber/submitqueue/submitqueue/entity" storagemock "github.com/uber/submitqueue/submitqueue/extension/storage/mock" - orchstorage "github.com/uber/submitqueue/submitqueue/orchestrator/extension/storage" orchstoragemock "github.com/uber/submitqueue/submitqueue/orchestrator/extension/storage/mock" "go.uber.org/mock/gomock" "go.uber.org/zap/zaptest" ) -// staticStorageFactory resolves every queue to one fixed store aggregate. -type staticStorageFactory struct{ store orchstorage.Storage } - -// For returns the fixed store aggregate for any queue. -func (f staticStorageFactory) For(orchstorage.Config) (orchstorage.Storage, error) { - return f.store, nil -} - func requestWithState(request entity.Request, state entity.RequestState) entity.Request { request.State = state return request @@ -76,7 +67,10 @@ const ( func TestProcess_RejectsTenantPayloadQueueMismatch(t *testing.T) { ctrl := gomock.NewController(t) store := orchstoragemock.NewMockStorage(ctrl) - controller := NewController(zaptest.NewLogger(t).Sugar(), tally.NoopScope, staticStorageFactory{store: store}, consumer.TopicRegistry{}, + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + controller := NewController(zaptest.NewLogger(t).Sugar(), tally.NoopScope, storageFactory, consumer.TopicRegistry{}, runwaymq.TopicKeyMergeConflictCheckSignal, "orchestrator-landconflictsignal") res := runwaymq.MergeResult{Id: testRequestID, Outcome: runwaypb.Outcome_SUCCEEDED} msg := entityqueue.NewMessage(testRequestID, resultPayload(t, res), testQueue, nil) @@ -118,7 +112,10 @@ func TestProcess_LandablePublishesToBatch(t *testing.T) { ) require.NoError(t, err) - controller := NewController(zaptest.NewLogger(t).Sugar(), tally.NoopScope, staticStorageFactory{store: store}, registry, + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + controller := NewController(zaptest.NewLogger(t).Sugar(), tally.NoopScope, storageFactory, registry, runwaymq.TopicKeyMergeConflictCheckSignal, "orchestrator-landconflictsignal") res := runwaymq.MergeResult{Id: testRequestID, Outcome: runwaypb.Outcome_SUCCEEDED} @@ -175,7 +172,10 @@ func TestProcess_NotLandableMarksRequestError(t *testing.T) { ) require.NoError(t, err) - controller := NewController(zaptest.NewLogger(t).Sugar(), tally.NoopScope, staticStorageFactory{store: store}, registry, + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + controller := NewController(zaptest.NewLogger(t).Sugar(), tally.NoopScope, storageFactory, registry, runwaymq.TopicKeyMergeConflictCheckSignal, "orchestrator-landconflictsignal") res := runwaymq.MergeResult{Id: testRequestID, Outcome: runwaypb.Outcome_FAILED, Reason: "conflict in foo.go"} @@ -203,7 +203,10 @@ func TestFailRequest_UpdateFailureLeavesRequestUnchanged(t *testing.T) { store := orchstoragemock.NewMockStorage(ctrl) store.EXPECT().GetRequestStore().Return(reqStore).Times(2) - controller := NewController(zaptest.NewLogger(t).Sugar(), tally.NoopScope, staticStorageFactory{store: store}, consumer.TopicRegistry{}, + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + controller := NewController(zaptest.NewLogger(t).Sugar(), tally.NoopScope, storageFactory, consumer.TopicRegistry{}, runwaymq.TopicKeyMergeConflictCheckSignal, "orchestrator-landconflictsignal") err := controller.failRequest(context.Background(), store, request, "conflict") @@ -231,7 +234,10 @@ func TestProcess_HaltedRequestSkips(t *testing.T) { ) require.NoError(t, err) - controller := NewController(zaptest.NewLogger(t).Sugar(), tally.NoopScope, staticStorageFactory{store: store}, registry, + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + controller := NewController(zaptest.NewLogger(t).Sugar(), tally.NoopScope, storageFactory, registry, runwaymq.TopicKeyMergeConflictCheckSignal, "orchestrator-landconflictsignal") res := runwaymq.MergeResult{Id: testRequestID, Outcome: runwaypb.Outcome_SUCCEEDED} diff --git a/submitqueue/orchestrator/controller/landsignal/BUILD.bazel b/submitqueue/orchestrator/controller/landsignal/BUILD.bazel index 47c734b63..9c806b9e6 100644 --- a/submitqueue/orchestrator/controller/landsignal/BUILD.bazel +++ b/submitqueue/orchestrator/controller/landsignal/BUILD.bazel @@ -36,7 +36,6 @@ go_test( "//submitqueue/core/topickey:go_default_library", "//submitqueue/entity:go_default_library", "//submitqueue/extension/storage/mock:go_default_library", - "//submitqueue/orchestrator/extension/storage:go_default_library", "//submitqueue/orchestrator/extension/storage/mock:go_default_library", "@com_github_stretchr_testify//assert:go_default_library", "@com_github_stretchr_testify//require:go_default_library", diff --git a/submitqueue/orchestrator/controller/landsignal/landsignal_test.go b/submitqueue/orchestrator/controller/landsignal/landsignal_test.go index 08ed5c05f..f4d9d27d7 100644 --- a/submitqueue/orchestrator/controller/landsignal/landsignal_test.go +++ b/submitqueue/orchestrator/controller/landsignal/landsignal_test.go @@ -30,22 +30,11 @@ import ( "github.com/uber/submitqueue/submitqueue/core/topickey" "github.com/uber/submitqueue/submitqueue/entity" storagemock "github.com/uber/submitqueue/submitqueue/extension/storage/mock" - orchstorage "github.com/uber/submitqueue/submitqueue/orchestrator/extension/storage" orchstoragemock "github.com/uber/submitqueue/submitqueue/orchestrator/extension/storage/mock" "go.uber.org/mock/gomock" "go.uber.org/zap/zaptest" ) -// newQueueBatchStateStore returns a QueueBatchStateStore mock that accepts any -// membership-record write; these tests never list record buckets. -// staticStorageFactory resolves every queue to one fixed store aggregate. -type staticStorageFactory struct{ store orchstorage.Storage } - -// For returns the fixed store aggregate for any queue. -func (f staticStorageFactory) For(orchstorage.Config) (orchstorage.Storage, error) { - return f.store, nil -} - func newQueueBatchStateStore(ctrl *gomock.Controller) *storagemock.MockQueueBatchStateStore { s := storagemock.NewMockQueueBatchStateStore(ctrl) s.EXPECT().Put(gomock.Any(), gomock.Any()).Return(nil).AnyTimes() @@ -102,10 +91,13 @@ func recordingRegistry(t *testing.T, ctrl *gomock.Controller, got *[]string) con } func newController(t *testing.T, store *orchstoragemock.MockStorage, registry consumer.TopicRegistry) *Controller { + storageFactory := orchstoragemock.NewMockFactory(gomock.NewController(t)) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + return NewController( zaptest.NewLogger(t).Sugar(), tally.NoopScope, - staticStorageFactory{store: store}, + storageFactory, registry, runwaymq.TopicKeyMergeSignal, "orchestrator-landsignal", diff --git a/submitqueue/orchestrator/controller/speculate/BUILD.bazel b/submitqueue/orchestrator/controller/speculate/BUILD.bazel index a2e877077..4517e4488 100644 --- a/submitqueue/orchestrator/controller/speculate/BUILD.bazel +++ b/submitqueue/orchestrator/controller/speculate/BUILD.bazel @@ -55,10 +55,9 @@ go_test( "//submitqueue/core/messagequeue:go_default_library", "//submitqueue/core/topickey:go_default_library", "//submitqueue/entity:go_default_library", - "//submitqueue/extension/speculation/speculator:go_default_library", + "//submitqueue/extension/speculation/speculator/mock:go_default_library", "//submitqueue/extension/storage:go_default_library", "//submitqueue/extension/storage/mock:go_default_library", - "//submitqueue/orchestrator/extension/storage:go_default_library", "//submitqueue/orchestrator/extension/storage/mock:go_default_library", "@com_github_stretchr_testify//assert:go_default_library", "@com_github_stretchr_testify//require:go_default_library", diff --git a/submitqueue/orchestrator/controller/speculate/run_test.go b/submitqueue/orchestrator/controller/speculate/run_test.go index 9288a545d..3d349509c 100644 --- a/submitqueue/orchestrator/controller/speculate/run_test.go +++ b/submitqueue/orchestrator/controller/speculate/run_test.go @@ -28,7 +28,7 @@ import ( sqmq "github.com/uber/submitqueue/submitqueue/core/messagequeue" "github.com/uber/submitqueue/submitqueue/core/topickey" "github.com/uber/submitqueue/submitqueue/entity" - "github.com/uber/submitqueue/submitqueue/extension/speculation/speculator" + speculatormock "github.com/uber/submitqueue/submitqueue/extension/speculation/speculator/mock" "github.com/uber/submitqueue/submitqueue/extension/storage" storagemock "github.com/uber/submitqueue/submitqueue/extension/storage/mock" orchstoragemock "github.com/uber/submitqueue/submitqueue/orchestrator/extension/storage/mock" @@ -36,8 +36,8 @@ import ( "go.uber.org/zap/zaptest" ) -// scriptedSpeculator returns a fixed answer and records what it was asked. -type scriptedSpeculator struct { +// speculationFixture holds proposals and captured inputs for a run. +type speculationFixture struct { proposals []entity.Speculation err error @@ -46,13 +46,6 @@ type scriptedSpeculator struct { calls int } -func (s *scriptedSpeculator) Speculate(_ context.Context, batches []entity.Batch, sets []entity.SpeculationPathSet) ([]entity.Speculation, error) { - s.calls++ - s.gotBatches = batches - s.gotSets = sets - return s.proposals, s.err -} - // updateTo matches a BatchStore.Update argument by its ID and target state — // the two things an outcome write is asserted on. type updateTo struct { @@ -76,7 +69,7 @@ type runHarness struct { pathSets *storagemock.MockSpeculationPathSetStore pathBuilds *storagemock.MockPathBuildStore builds *storagemock.MockBuildStore - spec *scriptedSpeculator + spec *speculationFixture published []string // filed and unfiled are the queue's membership-record writes: a state // change has to move the record, or the batch stays listed under the @@ -118,10 +111,17 @@ func (h *runHarness) run(triggerID string) error { } // newRunHarness wires a controller whose queue read returns inFlight. -func newRunHarness(t *testing.T, ctrl *gomock.Controller, spec *scriptedSpeculator, inFlight []entity.Batch) *runHarness { +func newRunHarness(t *testing.T, ctrl *gomock.Controller, spec *speculationFixture, inFlight []entity.Batch) *runHarness { t.Helper() h := &runHarness{spec: spec, metrics: tally.NewTestScope("test", nil)} + speculator := speculatormock.NewMockSpeculator(ctrl) + speculator.EXPECT().Speculate(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, batches []entity.Batch, sets []entity.SpeculationPathSet) ([]entity.Speculation, error) { + spec.calls++ + spec.gotBatches = batches + spec.gotSets = sets + return spec.proposals, spec.err + }).AnyTimes() h.batches = storagemock.NewMockBatchStore(ctrl) for _, b := range inFlight { @@ -196,9 +196,15 @@ func newRunHarness(t *testing.T, ctrl *gomock.Controller, spec *scriptedSpeculat }) require.NoError(t, err) + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + speculatorFactory := speculatormock.NewMockFactory(ctrl) + speculatorFactory.EXPECT().For(gomock.Any()).Return(speculator, nil).AnyTimes() + h.controller = NewController( - zaptest.NewLogger(t).Sugar(), h.metrics, staticStorageFactory{store: store}, - staticSpeculatorFactory{s: spec}, registry, topickey.TopicKeySpeculate, "orchestrator-speculate", + zaptest.NewLogger(t).Sugar(), h.metrics, storageFactory, + speculatorFactory, registry, topickey.TopicKeySpeculate, "orchestrator-speculate", ) return h } @@ -222,7 +228,7 @@ func speculatingHead() entity.Batch { func TestRun_FundsProposedPath(t *testing.T) { ctrl := gomock.NewController(t) path := pathOver(entity.DependencyAssumptionSucceeds, entity.DependencyAssumptionFails) - spec := &scriptedSpeculator{proposals: []entity.Speculation{{Path: path, Action: entity.PathActionBuild}}} + spec := &speculationFixture{proposals: []entity.Speculation{{Path: path, Action: entity.PathActionBuild}}} h := newRunHarness(t, ctrl, spec, []entity.Batch{speculatingHead()}) h.noBuildsDispatched() @@ -257,7 +263,7 @@ func TestRun_FundsProposedPath(t *testing.T) { func TestRun_DispatchStampsQueueAndPartitionsByHead(t *testing.T) { ctrl := gomock.NewController(t) path := pathOver(entity.DependencyAssumptionSucceeds, entity.DependencyAssumptionFails) - spec := &scriptedSpeculator{proposals: []entity.Speculation{{Path: path, Action: entity.PathActionBuild}}} + spec := &speculationFixture{proposals: []entity.Speculation{{Path: path, Action: entity.PathActionBuild}}} h := newRunHarness(t, ctrl, spec, []entity.Batch{speculatingHead()}) h.noBuildsDispatched() @@ -280,7 +286,7 @@ func TestRun_DispatchStampsQueueAndPartitionsByHead(t *testing.T) { // The Speculator sees the speculating batches and their path sets. func TestRun_PassesSnapshotToSpeculator(t *testing.T) { ctrl := gomock.NewController(t) - spec := &scriptedSpeculator{} + spec := &speculationFixture{} landing := entity.Batch{ID: "100", Queue: "q", State: entity.BatchStateLanding, Version: 1} h := newRunHarness(t, ctrl, spec, []entity.Batch{speculatingHead(), landing}) @@ -306,7 +312,7 @@ func TestRun_PassesSnapshotToSpeculator(t *testing.T) { func TestRun_CancelsBrokenPath(t *testing.T) { ctrl := gomock.NewController(t) broken := pathOver(entity.DependencyAssumptionSucceeds, entity.DependencyAssumptionFails) - spec := &scriptedSpeculator{} + spec := &speculationFixture{} h := newRunHarness(t, ctrl, spec, []entity.Batch{speculatingHead()}) h.noBuildsDispatched() @@ -336,7 +342,7 @@ func TestRun_CancelsBrokenPath(t *testing.T) { func TestRun_DropsRejectedProposal(t *testing.T) { ctrl := gomock.NewController(t) malformed := pathOver(entity.DependencyAssumptionSucceeds) // missing dep2 - spec := &scriptedSpeculator{proposals: []entity.Speculation{ + spec := &speculationFixture{proposals: []entity.Speculation{ {Path: malformed, Action: entity.PathActionBuild}, }} @@ -355,7 +361,7 @@ func TestRun_DropsRejectedProposal(t *testing.T) { func TestRun_AlreadyFundedPathIsNotRefunded(t *testing.T) { ctrl := gomock.NewController(t) path := pathOver(entity.DependencyAssumptionSucceeds, entity.DependencyAssumptionFails) - spec := &scriptedSpeculator{proposals: []entity.Speculation{{Path: path, Action: entity.PathActionBuild}}} + spec := &speculationFixture{proposals: []entity.Speculation{{Path: path, Action: entity.PathActionBuild}}} h := newRunHarness(t, ctrl, spec, []entity.Batch{speculatingHead()}) h.noBuildsDispatched() @@ -379,7 +385,7 @@ func TestRun_AlreadyFundedPathIsNotRefunded(t *testing.T) { func TestRun_RedispatchesPendingPath(t *testing.T) { ctrl := gomock.NewController(t) path := pathOver(entity.DependencyAssumptionSucceeds, entity.DependencyAssumptionFails) - spec := &scriptedSpeculator{} + spec := &speculationFixture{} h := newRunHarness(t, ctrl, spec, []entity.Batch{speculatingHead()}) h.noBuildsDispatched() @@ -401,7 +407,7 @@ func TestRun_RedispatchesPendingPath(t *testing.T) { func TestRun_LostCASIsNotAnError(t *testing.T) { ctrl := gomock.NewController(t) broken := pathOver(entity.DependencyAssumptionSucceeds, entity.DependencyAssumptionFails) - spec := &scriptedSpeculator{} + spec := &speculationFixture{} h := newRunHarness(t, ctrl, spec, []entity.Batch{speculatingHead()}) h.noBuildsDispatched() @@ -423,7 +429,7 @@ func TestRun_LostCASIsNotAnError(t *testing.T) { // fresh state. func TestRun_SpeculatorFailure(t *testing.T) { ctrl := gomock.NewController(t) - spec := &scriptedSpeculator{err: fmt.Errorf("scorer unavailable")} + spec := &speculationFixture{err: fmt.Errorf("scorer unavailable")} h := newRunHarness(t, ctrl, spec, []entity.Batch{speculatingHead()}) h.noBuildsDispatched() @@ -437,16 +443,13 @@ func TestRun_SpeculatorFailure(t *testing.T) { // A queue with nothing speculating never reaches the Speculator. func TestRun_NoSpeculatingBatches(t *testing.T) { ctrl := gomock.NewController(t) - spec := &scriptedSpeculator{} + spec := &speculationFixture{} h := newRunHarness(t, ctrl, spec, nil) require.NoError(t, h.run(head)) assert.Zero(t, spec.calls) } -// Verify the harness's speculator satisfies the extension contract. -var _ speculator.Speculator = (*scriptedSpeculator)(nil) - // Reading build records is how the run learns what CI did without the build stages writing // the path set. A finished build becomes the path's status in memory, and the // run's own write is what persists it. @@ -466,7 +469,7 @@ func TestRun_RecordsFinishedBuildsOnPaths(t *testing.T) { t.Run(tt.name, func(t *testing.T) { ctrl := gomock.NewController(t) path := pathOver(entity.DependencyAssumptionSucceeds, entity.DependencyAssumptionFails) - spec := &scriptedSpeculator{} + spec := &speculationFixture{} h := newRunHarness(t, ctrl, spec, []entity.Batch{speculatingHead()}) h.batches.EXPECT().Get(gomock.Any(), dep1).Return(entity.Batch{ID: dep1, State: entity.BatchStateSpeculating}, nil) @@ -499,7 +502,7 @@ func TestRun_RecordsFinishedBuildsOnPaths(t *testing.T) { func TestRun_BuildUpdateDoesNotOverrideCancellingIntent(t *testing.T) { ctrl := gomock.NewController(t) path := pathOver(entity.DependencyAssumptionSucceeds, entity.DependencyAssumptionFails) - spec := &scriptedSpeculator{} + spec := &speculationFixture{} h := newRunHarness(t, ctrl, spec, []entity.Batch{speculatingHead()}) h.batches.EXPECT().Get(gomock.Any(), dep1).Return(entity.Batch{ID: dep1, State: entity.BatchStateSpeculating}, nil) @@ -525,7 +528,7 @@ func TestRun_BuildUpdateDoesNotOverrideCancellingIntent(t *testing.T) { func TestRun_DoesNotReReadFinishedPaths(t *testing.T) { ctrl := gomock.NewController(t) path := pathOver(entity.DependencyAssumptionSucceeds, entity.DependencyAssumptionFails) - spec := &scriptedSpeculator{} + spec := &speculationFixture{} h := newRunHarness(t, ctrl, spec, []entity.Batch{speculatingHead()}) // dep1 is unresolved, so the passed path cannot land — this test is about @@ -550,7 +553,7 @@ func TestRun_DoesNotReReadFinishedPaths(t *testing.T) { func TestRun_BrokenPathsAreVisibleToTheSpeculator(t *testing.T) { ctrl := gomock.NewController(t) broken := pathOver(entity.DependencyAssumptionSucceeds, entity.DependencyAssumptionFails) - spec := &scriptedSpeculator{} + spec := &speculationFixture{} h := newRunHarness(t, ctrl, spec, []entity.Batch{speculatingHead()}) h.noBuildsDispatched() @@ -625,7 +628,7 @@ func TestCancelBrokenPathsInSet_LeavesFinishedPaths(t *testing.T) { func TestRun_DecidedHeadIsNotSpeculatedOn(t *testing.T) { ctrl := gomock.NewController(t) passed := pathOver(entity.DependencyAssumptionSucceeds, entity.DependencyAssumptionFails) - spec := &scriptedSpeculator{ + spec := &speculationFixture{ // Would be applied if the head were still offered, creating a pending // path that supersede then cancels in the same write. proposals: []entity.Speculation{{ @@ -668,7 +671,7 @@ func TestRun_LandableHeadGainsNoNewPath(t *testing.T) { ctrl := gomock.NewController(t) passed := pathOver(entity.DependencyAssumptionSucceeds, entity.DependencyAssumptionFails) other := pathOver(entity.DependencyAssumptionFails, entity.DependencyAssumptionFails) - spec := &scriptedSpeculator{ + spec := &speculationFixture{ proposals: []entity.Speculation{{Path: other, Action: entity.PathActionBuild}}, } @@ -712,7 +715,7 @@ func TestRun_LandableHeadDispatchesAfterTheStateWrite(t *testing.T) { ctrl := gomock.NewController(t) passed := pathOver(entity.DependencyAssumptionSucceeds, entity.DependencyAssumptionSucceeds) - h := newRunHarness(t, ctrl, &scriptedSpeculator{}, []entity.Batch{speculatingHead()}) + h := newRunHarness(t, ctrl, &speculationFixture{}, []entity.Batch{speculatingHead()}) h.noBuildsDispatched() h.batches.EXPECT().Get(gomock.Any(), dep1).Return(entity.Batch{ID: dep1, State: entity.BatchStateSucceeded}, nil) h.batches.EXPECT().Get(gomock.Any(), dep2).Return(entity.Batch{ID: dep2, State: entity.BatchStateSucceeded}, nil) @@ -742,7 +745,7 @@ func TestRun_LandableHeadDispatchesNothingWhenTheStateCASLoses(t *testing.T) { ctrl := gomock.NewController(t) passed := pathOver(entity.DependencyAssumptionSucceeds, entity.DependencyAssumptionSucceeds) - h := newRunHarness(t, ctrl, &scriptedSpeculator{}, []entity.Batch{speculatingHead()}) + h := newRunHarness(t, ctrl, &speculationFixture{}, []entity.Batch{speculatingHead()}) h.noBuildsDispatched() h.batches.EXPECT().Get(gomock.Any(), dep1).Return(entity.Batch{ID: dep1, State: entity.BatchStateSucceeded}, nil) h.batches.EXPECT().Get(gomock.Any(), dep2).Return(entity.Batch{ID: dep2, State: entity.BatchStateSucceeded}, nil) @@ -764,7 +767,7 @@ func TestRun_LandableHeadDispatchesNothingWhenTheStateCASLoses(t *testing.T) { // non-terminal one, so it is published only once the terminal write has landed. func TestRun_FailedHeadConcludesAfterTheStateWrite(t *testing.T) { ctrl := gomock.NewController(t) - spec := &scriptedSpeculator{} + spec := &speculationFixture{} failed := pathOver(entity.DependencyAssumptionSucceeds, entity.DependencyAssumptionSucceeds) h := newRunHarness(t, ctrl, spec, []entity.Batch{speculatingHead()}) @@ -799,7 +802,7 @@ func TestRun_FailedHeadConcludesAfterTheStateWrite(t *testing.T) { func TestRun_ProviderCancellationExhaustsHead(t *testing.T) { ctrl := gomock.NewController(t) batch := entity.Batch{ID: head, Queue: "q", State: entity.BatchStateSpeculating, Version: 1} - h := newRunHarness(t, ctrl, &scriptedSpeculator{}, []entity.Batch{batch}) + h := newRunHarness(t, ctrl, &speculationFixture{}, []entity.Batch{batch}) path := entity.SpeculationPath{Head: head} h.pathSets.EXPECT().Get(gomock.Any(), head).Return(entity.SpeculationPathSet{ Head: head, Paths: []entity.SpeculationPathEntry{entryFor(path, entity.SpeculationPathStatusBuilding)}, Version: 1, @@ -833,7 +836,7 @@ func TestRun_ProviderCancellationExhaustsHead(t *testing.T) { // for an unrelated signal to wake the queue again. func TestRun_FailureCascadesWithinOneRun(t *testing.T) { ctrl := gomock.NewController(t) - spec := &scriptedSpeculator{} + spec := &speculationFixture{} // dependent is listed first, so a single forward pass would evaluate it // before the head it is stacked on has failed. @@ -885,7 +888,7 @@ func TestRun_FailureCascadesWithinOneRun(t *testing.T) { // batch is cancelled and its requests reconciled. func TestRun_CancellingBatchFinalizesInTheRun(t *testing.T) { ctrl := gomock.NewController(t) - spec := &scriptedSpeculator{} + spec := &speculationFixture{} cancelling := entity.Batch{ ID: head, Queue: "q", State: entity.BatchStateCancelling, Version: 1, @@ -923,7 +926,7 @@ func TestRun_CancellingBatchFinalizesInTheRun(t *testing.T) { // while CI still held its slots. func TestRun_CancellingBatchWaitsForBuildsToStop(t *testing.T) { ctrl := gomock.NewController(t) - spec := &scriptedSpeculator{} + spec := &speculationFixture{} cancelling := entity.Batch{ ID: head, Queue: "q", State: entity.BatchStateCancelling, Version: 1, @@ -959,7 +962,7 @@ func TestRun_CancellingBatchWaitsForBuildsToStop(t *testing.T) { // forever, so the run marks it cancelled from that absence. func TestRun_CancellingPathWithNoBuildIsCancelled(t *testing.T) { ctrl := gomock.NewController(t) - spec := &scriptedSpeculator{} + spec := &speculationFixture{} cancelling := entity.Batch{ ID: head, Queue: "q", State: entity.BatchStateCancelling, Version: 1, @@ -989,7 +992,7 @@ func TestRun_CancellingPathWithNoBuildIsCancelled(t *testing.T) { // A batch cancelled before anything was funded has no builds to wait on. func TestRun_CancellingBatchWithNoPaths(t *testing.T) { ctrl := gomock.NewController(t) - spec := &scriptedSpeculator{} + spec := &speculationFixture{} cancelling := entity.Batch{ ID: head, Queue: "q", State: entity.BatchStateCancelling, Version: 1, @@ -1009,7 +1012,7 @@ func TestRun_CancellingBatchWithNoPaths(t *testing.T) { // build the winning write knows about. func TestRun_CancellingLostPathSetRaceSkipsTheTerminalWrite(t *testing.T) { ctrl := gomock.NewController(t) - spec := &scriptedSpeculator{} + spec := &speculationFixture{} cancelling := entity.Batch{ ID: head, Queue: "q", State: entity.BatchStateCancelling, Version: 1, @@ -1038,7 +1041,7 @@ func TestRun_CancellingLostPathSetRaceSkipsTheTerminalWrite(t *testing.T) { // those slots as free and oversubscribe CI. func TestRun_SpeculatorSeesPathSetsOfNonOpenHeads(t *testing.T) { ctrl := gomock.NewController(t) - spec := &scriptedSpeculator{} + spec := &speculationFixture{} landing := entity.Batch{ ID: "100", Queue: "q", State: entity.BatchStateLanding, Version: 1, @@ -1079,7 +1082,7 @@ func TestRun_SpeculatorSeesPathSetsOfNonOpenHeads(t *testing.T) { // the path would keep charging the budget. func TestRun_PersistsObservationsWithNoOpenHead(t *testing.T) { ctrl := gomock.NewController(t) - spec := &scriptedSpeculator{} + spec := &speculationFixture{} landing := entity.Batch{ ID: "100", Queue: "q", State: entity.BatchStateLanding, Version: 1, @@ -1132,9 +1135,15 @@ func TestFanout_MintsADistinctMessageIDPerPublish(t *testing.T) { }) require.NoError(t, err) + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(orchstoragemock.NewMockStorage(ctrl), nil).AnyTimes() + + speculatorFactory := speculatormock.NewMockFactory(ctrl) + speculatorFactory.EXPECT().For(gomock.Any()).Return(nil, nil).AnyTimes() + c := NewController( - zaptest.NewLogger(t).Sugar(), tally.NoopScope, staticStorageFactory{store: orchstoragemock.NewMockStorage(ctrl)}, - staticSpeculatorFactory{}, registry, topickey.TopicKeySpeculate, "orchestrator-speculate", + zaptest.NewLogger(t).Sugar(), tally.NoopScope, storageFactory, + speculatorFactory, registry, topickey.TopicKeySpeculate, "orchestrator-speculate", ) require.NoError(t, c.fanout(context.Background(), head, "q")) @@ -1165,9 +1174,15 @@ func TestDispatchLand_ReusesOneMessageIDPerBatch(t *testing.T) { }) require.NoError(t, err) + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(orchstoragemock.NewMockStorage(ctrl), nil).AnyTimes() + + speculatorFactory := speculatormock.NewMockFactory(ctrl) + speculatorFactory.EXPECT().For(gomock.Any()).Return(nil, nil).AnyTimes() + c := NewController( - zaptest.NewLogger(t).Sugar(), tally.NoopScope, staticStorageFactory{store: orchstoragemock.NewMockStorage(ctrl)}, - staticSpeculatorFactory{}, registry, topickey.TopicKeySpeculate, "orchestrator-speculate", + zaptest.NewLogger(t).Sugar(), tally.NoopScope, storageFactory, + speculatorFactory, registry, topickey.TopicKeySpeculate, "orchestrator-speculate", ) batch := entity.Batch{ID: head, Queue: "q"} @@ -1192,7 +1207,7 @@ func cascadePair(t *testing.T, ctrl *gomock.Controller, prerequisiteState entity Dependencies: []string{head}, Version: 1, } - h := newRunHarness(t, ctrl, &scriptedSpeculator{}, []entity.Batch{prerequisite, derived}) + h := newRunHarness(t, ctrl, &speculationFixture{}, []entity.Batch{prerequisite, derived}) derivedPath := entity.SpeculationPath{ Head: derived.ID, @@ -1264,7 +1279,7 @@ func TestRun_UnrelatedOutcomeStillCommitsAfterALostCAS(t *testing.T) { ID: "103", Queue: "q", State: entity.BatchStateSpeculating, Version: 1, } - h := newRunHarness(t, ctrl, &scriptedSpeculator{}, []entity.Batch{losing, independent}) + h := newRunHarness(t, ctrl, &speculationFixture{}, []entity.Batch{losing, independent}) h.noBuildsDispatched() h.pathSets.EXPECT().Get(gomock.Any(), losing.ID). @@ -1298,7 +1313,7 @@ func TestRun_FinalizedBatchPathSetIsWrittenOnce(t *testing.T) { ctrl := gomock.NewController(t) cancelling := entity.Batch{ID: head, Queue: "q", State: entity.BatchStateCancelling, Version: 1} - h := newRunHarness(t, ctrl, &scriptedSpeculator{}, []entity.Batch{cancelling}) + h := newRunHarness(t, ctrl, &speculationFixture{}, []entity.Batch{cancelling}) h.noBuildsDispatched() h.pathSets.EXPECT().Get(gomock.Any(), head).Return(entity.SpeculationPathSet{ @@ -1328,7 +1343,7 @@ func TestRun_CascadeDerivedBatchIsGivenARecoverySignalBeforeItIsTerminal(t *test ctrl := gomock.NewController(t) failing := entity.Batch{ID: "102", Queue: "q", State: entity.BatchStateSpeculating, Version: 1} - h := newRunHarness(t, ctrl, &scriptedSpeculator{}, []entity.Batch{failing}) + h := newRunHarness(t, ctrl, &speculationFixture{}, []entity.Batch{failing}) h.noBuildsDispatched() failedPath := entity.SpeculationPath{Head: failing.ID} @@ -1361,7 +1376,7 @@ func TestRun_TriggerBatchNeedsNoRecoverySignal(t *testing.T) { ctrl := gomock.NewController(t) failing := entity.Batch{ID: head, Queue: "q", State: entity.BatchStateSpeculating, Version: 1} - h := newRunHarness(t, ctrl, &scriptedSpeculator{}, []entity.Batch{failing}) + h := newRunHarness(t, ctrl, &speculationFixture{}, []entity.Batch{failing}) h.noBuildsDispatched() failedPath := entity.SpeculationPath{Head: head} @@ -1383,7 +1398,7 @@ func TestRun_CascadeDerivedBatchIsGivenARecoverySignalBeforeItLands(t *testing.T ctrl := gomock.NewController(t) landing := entity.Batch{ID: "102", Queue: "q", State: entity.BatchStateSpeculating, Version: 1} - h := newRunHarness(t, ctrl, &scriptedSpeculator{}, []entity.Batch{landing}) + h := newRunHarness(t, ctrl, &speculationFixture{}, []entity.Batch{landing}) h.noBuildsDispatched() // No dependencies, so the passed path has nothing left to settle. @@ -1417,7 +1432,7 @@ func TestRun_CancellingPathWithALiveBuildStaysCancelling(t *testing.T) { ctrl := gomock.NewController(t) cancelling := entity.Batch{ID: head, Queue: "q", State: entity.BatchStateCancelling, Version: 1} - h := newRunHarness(t, ctrl, &scriptedSpeculator{}, []entity.Batch{cancelling}) + h := newRunHarness(t, ctrl, &speculationFixture{}, []entity.Batch{cancelling}) h.pathSets.EXPECT().Get(gomock.Any(), head).Return(entity.SpeculationPathSet{ Head: head, @@ -1453,7 +1468,7 @@ func memberHead() entity.Batch { func TestRun_ReportsPassedPathWhileWaiting(t *testing.T) { ctrl := gomock.NewController(t) passed := pathOver(entity.DependencyAssumptionSucceeds, entity.DependencyAssumptionSucceeds) - spec := &scriptedSpeculator{} + spec := &speculationFixture{} h := newRunHarness(t, ctrl, spec, []entity.Batch{memberHead()}) h.noBuildsDispatched() @@ -1485,7 +1500,7 @@ func TestRun_ReportsPassedPathWhileWaiting(t *testing.T) { func TestRun_ReportsInvalidatedWhenPassedPathBreaks(t *testing.T) { ctrl := gomock.NewController(t) passed := pathOver(entity.DependencyAssumptionSucceeds, entity.DependencyAssumptionFails) - spec := &scriptedSpeculator{} + spec := &speculationFixture{} h := newRunHarness(t, ctrl, spec, []entity.Batch{memberHead()}) h.noBuildsDispatched() @@ -1522,7 +1537,7 @@ func TestRun_ReportsInvalidatedWhenTheDependencyFailsInTheSameRun(t *testing.T) State: entity.BatchStateSpeculating, Dependencies: []string{dep1}, Version: 1, } - h := newRunHarness(t, ctrl, &scriptedSpeculator{}, []entity.Batch{leader, followerBatch}) + h := newRunHarness(t, ctrl, &speculationFixture{}, []entity.Batch{leader, followerBatch}) h.noBuildsDispatched() // The leader has nothing left that can pass, so this run fails it. @@ -1565,7 +1580,7 @@ func TestRun_LandingHeadReportsSpeculatedAndNoWait(t *testing.T) { ctrl := gomock.NewController(t) passed := pathOver(entity.DependencyAssumptionSucceeds, entity.DependencyAssumptionSucceeds) - h := newRunHarness(t, ctrl, &scriptedSpeculator{}, []entity.Batch{memberHead()}) + h := newRunHarness(t, ctrl, &speculationFixture{}, []entity.Batch{memberHead()}) h.noBuildsDispatched() h.batches.EXPECT().Get(gomock.Any(), dep1).Return(entity.Batch{ID: dep1, State: entity.BatchStateSucceeded}, nil) h.batches.EXPECT().Get(gomock.Any(), dep2).Return(entity.Batch{ID: dep2, State: entity.BatchStateSucceeded}, nil) @@ -1593,7 +1608,7 @@ func TestRun_BypassesUnsettledDependenciesWithFullCoverage(t *testing.T) { fails = entity.DependencyAssumptionFails ) - h := newRunHarness(t, ctrl, &scriptedSpeculator{}, []entity.Batch{memberHead()}) + h := newRunHarness(t, ctrl, &speculationFixture{}, []entity.Batch{memberHead()}) h.batches.EXPECT().Get(gomock.Any(), dep1).Return(entity.Batch{ID: dep1, State: entity.BatchStateSpeculating}, nil) h.batches.EXPECT().Get(gomock.Any(), dep2).Return(entity.Batch{ID: dep2, State: entity.BatchStateLanding}, nil) h.pathSets.EXPECT().Get(gomock.Any(), head).Return(entity.SpeculationPathSet{ @@ -1632,7 +1647,7 @@ func TestRun_SpeculatedIsReportedBeforeTheLandDispatch(t *testing.T) { ctrl := gomock.NewController(t) passed := pathOver(entity.DependencyAssumptionSucceeds, entity.DependencyAssumptionSucceeds) - h := newRunHarness(t, ctrl, &scriptedSpeculator{}, []entity.Batch{memberHead()}) + h := newRunHarness(t, ctrl, &speculationFixture{}, []entity.Batch{memberHead()}) h.failPublishTo("submitqueue-land") h.noBuildsDispatched() h.batches.EXPECT().Get(gomock.Any(), dep1).Return(entity.Batch{ID: dep1, State: entity.BatchStateSucceeded}, nil) @@ -1655,7 +1670,7 @@ func TestRun_SpeculatedIsReportedBeforeTheLandDispatch(t *testing.T) { // forward, so the run admits it rather than waiting for a message that names it. func TestRun_AdmitsBatchLeftInCreated(t *testing.T) { ctrl := gomock.NewController(t) - spec := &scriptedSpeculator{} + spec := &speculationFixture{} trigger := entity.Batch{ID: head, Queue: "q", State: entity.BatchStateSpeculating, Version: 1} straggler := entity.Batch{ @@ -1683,7 +1698,7 @@ func TestRun_AdmitsBatchLeftInCreated(t *testing.T) { // queue's planning must not be abandoned over it. func TestRun_AdmitLostRaceDoesNotFailRun(t *testing.T) { ctrl := gomock.NewController(t) - spec := &scriptedSpeculator{} + spec := &speculationFixture{} trigger := entity.Batch{ID: head, Queue: "q", State: entity.BatchStateSpeculating, Version: 1} straggler := entity.Batch{ @@ -1705,7 +1720,7 @@ func TestRun_AdmitLostRaceDoesNotFailRun(t *testing.T) { // next run tries again. func TestRun_AdmitStorageErrorDoesNotFailRun(t *testing.T) { ctrl := gomock.NewController(t) - spec := &scriptedSpeculator{} + spec := &speculationFixture{} trigger := entity.Batch{ID: head, Queue: "q", State: entity.BatchStateSpeculating, Version: 1} straggler := entity.Batch{ diff --git a/submitqueue/orchestrator/controller/speculate/speculate_test.go b/submitqueue/orchestrator/controller/speculate/speculate_test.go index b0d88f170..d3ffa3d24 100644 --- a/submitqueue/orchestrator/controller/speculate/speculate_test.go +++ b/submitqueue/orchestrator/controller/speculate/speculate_test.go @@ -19,8 +19,6 @@ import ( "fmt" "testing" - orchstorage "github.com/uber/submitqueue/submitqueue/orchestrator/extension/storage" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/uber-go/tally" @@ -33,7 +31,7 @@ import ( sqmq "github.com/uber/submitqueue/submitqueue/core/messagequeue" "github.com/uber/submitqueue/submitqueue/core/topickey" "github.com/uber/submitqueue/submitqueue/entity" - "github.com/uber/submitqueue/submitqueue/extension/speculation/speculator" + speculatormock "github.com/uber/submitqueue/submitqueue/extension/speculation/speculator/mock" "github.com/uber/submitqueue/submitqueue/extension/storage" storagemock "github.com/uber/submitqueue/submitqueue/extension/storage/mock" orchstoragemock "github.com/uber/submitqueue/submitqueue/orchestrator/extension/storage/mock" @@ -41,33 +39,6 @@ import ( "go.uber.org/zap/zaptest" ) -// quietSpeculator proposes nothing, which is what tests of the message-level -// branches want: the run happens but changes no paths. It records the batches -// it was offered, so a test can assert that a run reached them at all. -type quietSpeculator struct { - saw []entity.Batch -} - -func (s *quietSpeculator) Speculate(_ context.Context, batches []entity.Batch, _ []entity.SpeculationPathSet) ([]entity.Speculation, error) { - s.saw = append(s.saw, batches...) - return nil, nil -} - -// staticSpeculatorFactory returns a fixed Speculator for any queue. -type staticSpeculatorFactory struct{ s speculator.Speculator } - -func (f staticSpeculatorFactory) For(speculator.Config) (speculator.Speculator, error) { - return f.s, nil -} - -// staticStorageFactory resolves every queue to one fixed store aggregate. -type staticStorageFactory struct{ store orchstorage.Storage } - -// For returns the fixed store aggregate for any queue. -func (f staticStorageFactory) For(orchstorage.Config) (orchstorage.Storage, error) { - return f.store, nil -} - // listsInFlight makes the queue read return exactly these batches: each is // filed under its state's membership bucket and hydrated back through the // batch store. With no arguments the run is quiet — the queue lists no @@ -116,7 +87,7 @@ type procHarness struct { pathSets *storagemock.MockSpeculationPathSetStore pathBuilds *storagemock.MockPathBuildStore builds *storagemock.MockBuildStore - spec *quietSpeculator + saw []entity.Batch published []string // logs holds the request-log entries this run reported to batch members, // kept apart from published so pipeline assertions stay about the pipeline. @@ -125,7 +96,12 @@ type procHarness struct { func newProcHarness(t *testing.T, ctrl *gomock.Controller, publishErr error) *procHarness { t.Helper() - h := &procHarness{spec: &quietSpeculator{}} + h := &procHarness{} + spec := speculatormock.NewMockSpeculator(ctrl) + spec.EXPECT().Speculate(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, batches []entity.Batch, _ []entity.SpeculationPathSet) ([]entity.Speculation, error) { + h.saw = append(h.saw, batches...) + return nil, nil + }).AnyTimes() h.batches = storagemock.NewMockBatchStore(ctrl) h.queueStates = storagemock.NewMockQueueBatchStateStore(ctrl) @@ -170,9 +146,15 @@ func newProcHarness(t *testing.T, ctrl *gomock.Controller, publishErr error) *pr }) require.NoError(t, err) + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + speculatorFactory := speculatormock.NewMockFactory(ctrl) + speculatorFactory.EXPECT().For(gomock.Any()).Return(spec, nil).AnyTimes() + h.controller = NewController( - zaptest.NewLogger(t).Sugar(), tally.NoopScope, staticStorageFactory{store: store}, - staticSpeculatorFactory{s: h.spec}, registry, + zaptest.NewLogger(t).Sugar(), tally.NoopScope, storageFactory, + speculatorFactory, registry, topickey.TopicKeySpeculate, "orchestrator-speculate", ) return h @@ -292,7 +274,7 @@ func TestProcess_TerminalReplansQueue(t *testing.T) { Return(entity.SpeculationPathSet{}, storage.ErrNotFound) require.NoError(t, h.process(t, ctrl, batch.ID)) - assert.ElementsMatch(t, []entity.Batch{batch, dependent}, h.spec.saw, + assert.ElementsMatch(t, []entity.Batch{batch, dependent}, h.saw, "the dependent must be re-planned against the terminal outcome, which it can only be weighed against if the terminal batch comes too") } diff --git a/submitqueue/orchestrator/controller/start/BUILD.bazel b/submitqueue/orchestrator/controller/start/BUILD.bazel index 8b11ecc99..a51b1760f 100644 --- a/submitqueue/orchestrator/controller/start/BUILD.bazel +++ b/submitqueue/orchestrator/controller/start/BUILD.bazel @@ -38,7 +38,6 @@ go_test( "//submitqueue/entity:go_default_library", "//submitqueue/extension/storage:go_default_library", "//submitqueue/extension/storage/mock:go_default_library", - "//submitqueue/orchestrator/extension/storage:go_default_library", "//submitqueue/orchestrator/extension/storage/mock:go_default_library", "@com_github_stretchr_testify//assert:go_default_library", "@com_github_stretchr_testify//require:go_default_library", diff --git a/submitqueue/orchestrator/controller/start/start_test.go b/submitqueue/orchestrator/controller/start/start_test.go index 0b7f027be..2f25f763d 100644 --- a/submitqueue/orchestrator/controller/start/start_test.go +++ b/submitqueue/orchestrator/controller/start/start_test.go @@ -34,21 +34,11 @@ import ( "github.com/uber/submitqueue/submitqueue/entity" storage "github.com/uber/submitqueue/submitqueue/extension/storage" storagemock "github.com/uber/submitqueue/submitqueue/extension/storage/mock" - orchstorage "github.com/uber/submitqueue/submitqueue/orchestrator/extension/storage" orchstoragemock "github.com/uber/submitqueue/submitqueue/orchestrator/extension/storage/mock" "go.uber.org/mock/gomock" "go.uber.org/zap/zaptest" ) -// newTestController creates a controller with test dependencies. -// staticStorageFactory resolves every queue to one fixed store aggregate. -type staticStorageFactory struct{ store orchstorage.Storage } - -// For returns the fixed store aggregate for any queue. -func (f staticStorageFactory) For(orchstorage.Config) (orchstorage.Storage, error) { - return f.store, nil -} - func newTestController( t *testing.T, ctrl *gomock.Controller, @@ -76,7 +66,10 @@ func newTestController( ) require.NoError(t, err) - return NewController(logger, scope, staticStorageFactory{store: store}, registry, topickey.TopicKeyStart, "orchestrator-start") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + return NewController(logger, scope, storageFactory, registry, topickey.TopicKeyStart, "orchestrator-start") } // newMockStorage creates a MockStorage with a MockRequestStore that succeeds on Create. diff --git a/submitqueue/orchestrator/controller/validate/BUILD.bazel b/submitqueue/orchestrator/controller/validate/BUILD.bazel index d04383904..ba86188f8 100644 --- a/submitqueue/orchestrator/controller/validate/BUILD.bazel +++ b/submitqueue/orchestrator/controller/validate/BUILD.bazel @@ -49,7 +49,6 @@ go_test( "//submitqueue/extension/storage/mock:go_default_library", "//submitqueue/extension/validator:go_default_library", "//submitqueue/extension/validator/mock:go_default_library", - "//submitqueue/orchestrator/extension/storage:go_default_library", "//submitqueue/orchestrator/extension/storage/mock:go_default_library", "@com_github_stretchr_testify//assert:go_default_library", "@com_github_stretchr_testify//require:go_default_library", diff --git a/submitqueue/orchestrator/controller/validate/validate_test.go b/submitqueue/orchestrator/controller/validate/validate_test.go index 07f543b7e..f74bf527f 100644 --- a/submitqueue/orchestrator/controller/validate/validate_test.go +++ b/submitqueue/orchestrator/controller/validate/validate_test.go @@ -41,20 +41,11 @@ import ( storagemock "github.com/uber/submitqueue/submitqueue/extension/storage/mock" "github.com/uber/submitqueue/submitqueue/extension/validator" validatormock "github.com/uber/submitqueue/submitqueue/extension/validator/mock" - orchstorage "github.com/uber/submitqueue/submitqueue/orchestrator/extension/storage" orchstoragemock "github.com/uber/submitqueue/submitqueue/orchestrator/extension/storage/mock" "go.uber.org/mock/gomock" "go.uber.org/zap/zaptest" ) -// staticStorageFactory resolves every queue to one fixed store aggregate. -type staticStorageFactory struct{ store orchstorage.Storage } - -// For returns the fixed store aggregate for any queue. -func (f staticStorageFactory) For(orchstorage.Config) (orchstorage.Storage, error) { - return f.store, nil -} - func TestToProtoStrategy(t *testing.T) { tests := []struct { name string @@ -87,26 +78,6 @@ func requestIDPayload(t *testing.T, id string) []byte { return payload } -// mockChangeProvider is a simple mock that returns test data. -type mockChangeProvider struct{} - -func (m *mockChangeProvider) Get(ctx context.Context, request entity.Request) ([]entity.ChangeInfo, error) { - return []entity.ChangeInfo{ - { - URI: "github://github.example.com/org/repo/pull/123/abcdef0123456789abcdef0123456789abcdef01", - Details: entity.ChangeDetails{ - Author: entity.Author{ - Name: "Test User", - Email: "test@example.com", - }, - ChangedFiles: []entity.ChangedFile{ - {Path: "main.go"}, - }, - }, - }, - }, nil -} - // newMockStorage creates a MockStorage with a MockRequestStore that returns the given request on Get. // The returned MockRequestStore is exposed so individual tests can layer additional Get expectations. func newMockStorage(ctrl *gomock.Controller, request entity.Request) (*orchstoragemock.MockStorage, *storagemock.MockRequestStore) { @@ -159,11 +130,28 @@ func newTestController( ) require.NoError(t, err) - cp := &mockChangeProvider{} + cp := changeprovidermock.NewMockChangeProvider(ctrl) + cp.EXPECT().Get(gomock.Any(), gomock.Any()).Return([]entity.ChangeInfo{ + { + URI: "github://github.example.com/org/repo/pull/123/abcdef0123456789abcdef0123456789abcdef01", + Details: entity.ChangeDetails{ + Author: entity.Author{ + Name: "Test User", + Email: "test@example.com", + }, + ChangedFiles: []entity.ChangedFile{ + {Path: "main.go"}, + }, + }, + }, + }, nil).AnyTimes() cpFactory := changeprovidermock.NewMockFactory(ctrl) cpFactory.EXPECT().For(gomock.Any()).Return(cp, nil).AnyTimes() - return NewController(logger, scope, staticStorageFactory{store: store}, registry, cpFactory, nil, runwaymq.TopicKeyMergeConflictCheck, topickey.TopicKeyValidate, "orchestrator-validate") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + return NewController(logger, scope, storageFactory, registry, cpFactory, nil, runwaymq.TopicKeyMergeConflictCheck, topickey.TopicKeyValidate, "orchestrator-validate") } func TestNewController(t *testing.T) { @@ -264,9 +252,28 @@ func TestController_Process_PublishesCheckToRunway(t *testing.T) { ) require.NoError(t, err) cpFactory := changeprovidermock.NewMockFactory(ctrl) - cpFactory.EXPECT().For(gomock.Any()).Return(&mockChangeProvider{}, nil).AnyTimes() + cp := changeprovidermock.NewMockChangeProvider(ctrl) + cp.EXPECT().Get(gomock.Any(), gomock.Any()).Return([]entity.ChangeInfo{ + { + URI: "github://github.example.com/org/repo/pull/123/abcdef0123456789abcdef0123456789abcdef01", + Details: entity.ChangeDetails{ + Author: entity.Author{ + Name: "Test User", + Email: "test@example.com", + }, + ChangedFiles: []entity.ChangedFile{ + {Path: "main.go"}, + }, + }, + }, + }, nil).AnyTimes() + + cpFactory.EXPECT().For(gomock.Any()).Return(cp, nil).AnyTimes() - controller := NewController(logger, tally.NoopScope, staticStorageFactory{store: store}, registry, cpFactory, nil, runwaymq.TopicKeyMergeConflictCheck, topickey.TopicKeyValidate, "orchestrator-validate") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + controller := NewController(logger, tally.NoopScope, storageFactory, registry, cpFactory, nil, runwaymq.TopicKeyMergeConflictCheck, topickey.TopicKeyValidate, "orchestrator-validate") msg := entityqueue.NewMessage(request.ID, requestIDPayload(t, request.ID), request.Queue, nil) msg.Tenant = request.Queue @@ -674,7 +681,23 @@ func TestController_Process_CustomValidatorPasses(t *testing.T) { require.NoError(t, err) cpFactory := changeprovidermock.NewMockFactory(ctrl) - cpFactory.EXPECT().For(gomock.Any()).Return(&mockChangeProvider{}, nil).AnyTimes() + cp := changeprovidermock.NewMockChangeProvider(ctrl) + cp.EXPECT().Get(gomock.Any(), gomock.Any()).Return([]entity.ChangeInfo{ + { + URI: "github://github.example.com/org/repo/pull/123/abcdef0123456789abcdef0123456789abcdef01", + Details: entity.ChangeDetails{ + Author: entity.Author{ + Name: "Test User", + Email: "test@example.com", + }, + ChangedFiles: []entity.ChangedFile{ + {Path: "main.go"}, + }, + }, + }, + }, nil).AnyTimes() + + cpFactory.EXPECT().For(gomock.Any()).Return(cp, nil).AnyTimes() mockValidator := validatormock.NewMockValidator(ctrl) // mockValidator returns nil - validation succeeded @@ -684,7 +707,10 @@ func TestController_Process_CustomValidatorPasses(t *testing.T) { QueueName: request.Queue, }).Return(mockValidator, nil) - controller := NewController(logger, tally.NoopScope, staticStorageFactory{store: store}, registry, cpFactory, mockValidatorFactory, runwaymq.TopicKeyMergeConflictCheck, topickey.TopicKeyValidate, "orchestrator-validate") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + controller := NewController(logger, tally.NoopScope, storageFactory, registry, cpFactory, mockValidatorFactory, runwaymq.TopicKeyMergeConflictCheck, topickey.TopicKeyValidate, "orchestrator-validate") msg := entityqueue.NewMessage(request.ID, requestIDPayload(t, request.ID), request.Queue, nil) msg.Tenant = request.Queue @@ -734,7 +760,23 @@ func TestController_Process_CustomValidatorFails(t *testing.T) { require.NoError(t, err) cpFactory := changeprovidermock.NewMockFactory(ctrl) - cpFactory.EXPECT().For(gomock.Any()).Return(&mockChangeProvider{}, nil).AnyTimes() + cp := changeprovidermock.NewMockChangeProvider(ctrl) + cp.EXPECT().Get(gomock.Any(), gomock.Any()).Return([]entity.ChangeInfo{ + { + URI: "github://github.example.com/org/repo/pull/123/abcdef0123456789abcdef0123456789abcdef01", + Details: entity.ChangeDetails{ + Author: entity.Author{ + Name: "Test User", + Email: "test@example.com", + }, + ChangedFiles: []entity.ChangedFile{ + {Path: "main.go"}, + }, + }, + }, + }, nil).AnyTimes() + + cpFactory.EXPECT().For(gomock.Any()).Return(cp, nil).AnyTimes() mockValidator := validatormock.NewMockValidator(ctrl) mockValidator.EXPECT().Validate(gomock.Any(), gomock.Any()).Return(fmt.Errorf("%w: some validation error", validator.ErrRejected)) @@ -743,7 +785,10 @@ func TestController_Process_CustomValidatorFails(t *testing.T) { QueueName: request.Queue, }).Return(mockValidator, nil) - controller := NewController(logger, tally.NoopScope, staticStorageFactory{store: store}, registry, cpFactory, mockValidatorFactory, runwaymq.TopicKeyMergeConflictCheck, topickey.TopicKeyValidate, "orchestrator-validate") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + controller := NewController(logger, tally.NoopScope, storageFactory, registry, cpFactory, mockValidatorFactory, runwaymq.TopicKeyMergeConflictCheck, topickey.TopicKeyValidate, "orchestrator-validate") msg := entityqueue.NewMessage(request.ID, requestIDPayload(t, request.ID), request.Queue, nil) msg.Tenant = request.Queue @@ -810,13 +855,32 @@ func TestController_Process_CustomValidatorCannotValidate(t *testing.T) { require.NoError(t, err) cpFactory := changeprovidermock.NewMockFactory(ctrl) - cpFactory.EXPECT().For(gomock.Any()).Return(&mockChangeProvider{}, nil).AnyTimes() + cp := changeprovidermock.NewMockChangeProvider(ctrl) + cp.EXPECT().Get(gomock.Any(), gomock.Any()).Return([]entity.ChangeInfo{ + { + URI: "github://github.example.com/org/repo/pull/123/abcdef0123456789abcdef0123456789abcdef01", + Details: entity.ChangeDetails{ + Author: entity.Author{ + Name: "Test User", + Email: "test@example.com", + }, + ChangedFiles: []entity.ChangedFile{ + {Path: "main.go"}, + }, + }, + }, + }, nil).AnyTimes() + + cpFactory.EXPECT().For(gomock.Any()).Return(cp, nil).AnyTimes() mockValidator := validatormock.NewMockValidator(ctrl) mockValidator.EXPECT().Validate(gomock.Any(), gomock.Any()).Return(tt.err) mockValidatorFactory := validatormock.NewMockFactory(ctrl) mockValidatorFactory.EXPECT().For(validator.Config{QueueName: request.Queue}).Return(mockValidator, nil) - controller := NewController(zaptest.NewLogger(t).Sugar(), tally.NoopScope, staticStorageFactory{store: store}, registry, cpFactory, mockValidatorFactory, runwaymq.TopicKeyMergeConflictCheck, topickey.TopicKeyValidate, "orchestrator-validate") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + controller := NewController(zaptest.NewLogger(t).Sugar(), tally.NoopScope, storageFactory, registry, cpFactory, mockValidatorFactory, runwaymq.TopicKeyMergeConflictCheck, topickey.TopicKeyValidate, "orchestrator-validate") msg := entityqueue.NewMessage(request.ID, requestIDPayload(t, request.ID), request.Queue, nil) msg.Tenant = request.Queue delivery := consumermock.NewMockDelivery(ctrl) @@ -871,7 +935,23 @@ func TestController_Process_CustomValidatorFailure_TerminationPublishFails(t *te require.NoError(t, err) cpFactory := changeprovidermock.NewMockFactory(ctrl) - cpFactory.EXPECT().For(gomock.Any()).Return(&mockChangeProvider{}, nil).AnyTimes() + cp := changeprovidermock.NewMockChangeProvider(ctrl) + cp.EXPECT().Get(gomock.Any(), gomock.Any()).Return([]entity.ChangeInfo{ + { + URI: "github://github.example.com/org/repo/pull/123/abcdef0123456789abcdef0123456789abcdef01", + Details: entity.ChangeDetails{ + Author: entity.Author{ + Name: "Test User", + Email: "test@example.com", + }, + ChangedFiles: []entity.ChangedFile{ + {Path: "main.go"}, + }, + }, + }, + }, nil).AnyTimes() + + cpFactory.EXPECT().For(gomock.Any()).Return(cp, nil).AnyTimes() mockValidator := validatormock.NewMockValidator(ctrl) mockValidator.EXPECT().Validate(gomock.Any(), gomock.Any()).Return(fmt.Errorf("%w: some validation error", validator.ErrRejected)) @@ -880,7 +960,10 @@ func TestController_Process_CustomValidatorFailure_TerminationPublishFails(t *te QueueName: request.Queue, }).Return(mockValidator, nil) - controller := NewController(zaptest.NewLogger(t).Sugar(), tally.NoopScope, staticStorageFactory{store: store}, registry, cpFactory, mockValidatorFactory, runwaymq.TopicKeyMergeConflictCheck, topickey.TopicKeyValidate, "orchestrator-validate") + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + controller := NewController(zaptest.NewLogger(t).Sugar(), tally.NoopScope, storageFactory, registry, cpFactory, mockValidatorFactory, runwaymq.TopicKeyMergeConflictCheck, topickey.TopicKeyValidate, "orchestrator-validate") msg := entityqueue.NewMessage(request.ID, requestIDPayload(t, request.ID), request.Queue, nil) msg.Tenant = request.Queue delivery := consumermock.NewMockDelivery(ctrl) diff --git a/submitqueue/orchestrator/pipeline_test.go b/submitqueue/orchestrator/pipeline_test.go index e1882d465..8e0e511df 100644 --- a/submitqueue/orchestrator/pipeline_test.go +++ b/submitqueue/orchestrator/pipeline_test.go @@ -26,6 +26,7 @@ import ( "github.com/uber/submitqueue/platform/base/failure" queue "github.com/uber/submitqueue/platform/base/messagequeue" hookext "github.com/uber/submitqueue/platform/extension/hook" + hookmock "github.com/uber/submitqueue/platform/extension/hook/mock" hooknoop "github.com/uber/submitqueue/platform/extension/hook/noop" extqueue "github.com/uber/submitqueue/platform/extension/messagequeue" queuemock "github.com/uber/submitqueue/platform/extension/messagequeue/mock" @@ -35,19 +36,12 @@ import ( "github.com/uber/submitqueue/submitqueue/entity" "github.com/uber/submitqueue/submitqueue/extension/storage" storagemock "github.com/uber/submitqueue/submitqueue/extension/storage/mock" - orchstorage "github.com/uber/submitqueue/submitqueue/orchestrator/extension/storage" orchstoragemock "github.com/uber/submitqueue/submitqueue/orchestrator/extension/storage/mock" "go.uber.org/mock/gomock" "go.uber.org/zap/zaptest" ) -type noopHooks struct{} - -func (noopHooks) For(*basehook.HookEvent) []hookext.Hook { - return []hookext.Hook{hooknoop.New()} -} - func hookStage(t *testing.T) pipeline.Stage[Deps] { t.Helper() for _, s := range Stages { @@ -61,10 +55,12 @@ func hookStage(t *testing.T) pipeline.Stage[Deps] { func TestHookStage(t *testing.T) { deps := func(t *testing.T) Deps { + hooks := hookmock.NewMockHooks(gomock.NewController(t)) + hooks.EXPECT().For(gomock.Any()).Return([]hookext.Hook{hooknoop.New()}).AnyTimes() return Deps{ Logger: zaptest.NewLogger(t).Sugar(), Scope: tally.NoopScope, - Hooks: noopHooks{}, + Hooks: hooks, } } stageContext := func(key string) pipeline.StageContext { @@ -94,12 +90,6 @@ func TestHookStage(t *testing.T) { }) } -type concludeStorageFactory struct{ store orchstorage.Storage } - -func (f concludeStorageFactory) For(orchstorage.Config) (orchstorage.Storage, error) { - return f.store, nil -} - func TestConcludeFinalBinding(t *testing.T) { cases := []struct { name string @@ -184,7 +174,10 @@ func TestConcludeFinalBinding(t *testing.T) { return nil }) } - deps := Deps{Logger: zaptest.NewLogger(t).Sugar(), Scope: tally.NoopScope, Storage: concludeStorageFactory{store}} + storageFactory := orchstoragemock.NewMockFactory(ctrl) + storageFactory.EXPECT().For(gomock.Any()).Return(store, nil).AnyTimes() + + deps := Deps{Logger: zaptest.NewLogger(t).Sugar(), Scope: tally.NoopScope, Storage: storageFactory} component, err := pipeline.Construct(deps.Logger, deps.Scope, backend, "test", deps, []pipeline.Stage[Deps]{stage}, pipeline.PublishOnly(pipeline.PublishOnlyTopic{Key: topickey.TopicKeyLog, Name: "log"})) require.NoError(t, err) require.NoError(t, component.Start(context.Background())) diff --git a/test/integration/submitqueue/core/consumer/BUILD.bazel b/test/integration/submitqueue/core/consumer/BUILD.bazel index b7ec937ff..eb5763c68 100644 --- a/test/integration/submitqueue/core/consumer/BUILD.bazel +++ b/test/integration/submitqueue/core/consumer/BUILD.bazel @@ -14,6 +14,7 @@ go_test( deps = [ "//platform/base/messagequeue:go_default_library", "//platform/consumer:go_default_library", + "//platform/consumer/mock:go_default_library", "//platform/errs:go_default_library", "//platform/extension/consumergate/noop:go_default_library", "//platform/extension/messagequeue:go_default_library", @@ -23,6 +24,7 @@ go_test( "@com_github_stretchr_testify//require:go_default_library", "@com_github_stretchr_testify//suite:go_default_library", "@com_github_uber_go_tally//:go_default_library", + "@org_uber_go_mock//gomock:go_default_library", "@org_uber_go_zap//zaptest:go_default_library", ], ) diff --git a/test/integration/submitqueue/core/consumer/consumer_test.go b/test/integration/submitqueue/core/consumer/consumer_test.go index 010a74bdb..f5ccaf01e 100644 --- a/test/integration/submitqueue/core/consumer/consumer_test.go +++ b/test/integration/submitqueue/core/consumer/consumer_test.go @@ -12,10 +12,12 @@ import ( "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/uber-go/tally" + "go.uber.org/mock/gomock" "go.uber.org/zap/zaptest" entityqueue "github.com/uber/submitqueue/platform/base/messagequeue" "github.com/uber/submitqueue/platform/consumer" + consumermock "github.com/uber/submitqueue/platform/consumer/mock" "github.com/uber/submitqueue/platform/errs" consumergatenoop "github.com/uber/submitqueue/platform/extension/consumergate/noop" extqueue "github.com/uber/submitqueue/platform/extension/messagequeue" @@ -23,31 +25,6 @@ import ( "github.com/uber/submitqueue/test/testutil" ) -// testController implements consumer.Controller for integration tests. -// Each test configures the processFunc to control behavior per partition. -type testController struct { - name string - topicKey consumer.TopicKey - consumerGroup string - processFunc func(ctx context.Context, delivery consumer.Delivery) error -} - -func (c *testController) Process(ctx context.Context, delivery consumer.Delivery) error { - return c.processFunc(ctx, delivery) -} - -func (c *testController) Name() string { - return c.name -} - -func (c *testController) TopicKey() consumer.TopicKey { - return c.topicKey -} - -func (c *testController) ConsumerGroup() string { - return c.consumerGroup -} - // testTimeout is the safety-net duration for channel waits in integration tests. const testTimeout = 10 * time.Second @@ -178,28 +155,29 @@ func (s *ConsumerIntegrationSuite) TestConsumerPerPartitionIsolation() { partAUnblock := make(chan struct{}) // unblocks partition-a processing partBProcessed := make(chan struct{}) // signals partition-b was processed - ctrl := &testController{ - name: "isolation-controller", - topicKey: topicKey, - consumerGroup: consumerGroup, - processFunc: func(ctx context.Context, delivery consumer.Delivery) error { - partition := delivery.Message().PartitionKey - t.Logf("Controller processing: partition=%s id=%s", partition, delivery.Message().ID) - - if partition == "partition-a" { - close(partAStarted) - // Block until test unblocks us - select { - case <-partAUnblock: - case <-ctx.Done(): - return ctx.Err() - } - } else if partition == "partition-b" { - close(partBProcessed) + controller := consumermock.NewMockController(gomock.NewController(t)) + controller.EXPECT().Name().Return("isolation-controller").AnyTimes() + controller.EXPECT().TopicKey().Return(topicKey).AnyTimes() + controller.EXPECT().ConsumerGroup().Return(consumerGroup).AnyTimes() + controller.EXPECT().Process(gomock.Any(), gomock.Any()).DoAndReturn(func(ctx context.Context, delivery consumer.Delivery) error { + partition := delivery.Message().PartitionKey + t.Logf("Controller processing: partition=%s id=%s", partition, delivery.Message().ID) + + if partition == "partition-a" { + close(partAStarted) + // Block until test unblocks us + select { + case <-partAUnblock: + case <-ctx.Done(): + return ctx.Err() } - return nil - }, - } + } else if partition == "partition-b" { + close(partBProcessed) + } + return nil + }).AnyTimes() + + ctrl := controller c := s.newConsumer(t, q, topicKey, topicName, consumerGroup) require.NoError(t, c.Register(ctrl)) @@ -262,27 +240,28 @@ func (s *ConsumerIntegrationSuite) TestConsumerPartitionOrdering() { processedIDs := make([]string, 0, numMessages) allDone := make(chan struct{}) - ctrl := &testController{ - name: "ordering-controller", - topicKey: topicKey, - consumerGroup: consumerGroup, - processFunc: func(ctx context.Context, delivery consumer.Delivery) error { - msgID := delivery.Message().ID - t.Logf("Processing: %s", msgID) - - // Record this message's ID; when all expected messages - // have been processed, signal completion via allDone. - mu.Lock() - processedIDs = append(processedIDs, msgID) - done := len(processedIDs) == numMessages - mu.Unlock() - - if done { - close(allDone) - } - return nil - }, - } + controller := consumermock.NewMockController(gomock.NewController(t)) + controller.EXPECT().Name().Return("ordering-controller").AnyTimes() + controller.EXPECT().TopicKey().Return(topicKey).AnyTimes() + controller.EXPECT().ConsumerGroup().Return(consumerGroup).AnyTimes() + controller.EXPECT().Process(gomock.Any(), gomock.Any()).DoAndReturn(func(ctx context.Context, delivery consumer.Delivery) error { + msgID := delivery.Message().ID + t.Logf("Processing: %s", msgID) + + // Record this message's ID; when all expected messages + // have been processed, signal completion via allDone. + mu.Lock() + processedIDs = append(processedIDs, msgID) + done := len(processedIDs) == numMessages + mu.Unlock() + + if done { + close(allDone) + } + return nil + }).AnyTimes() + + ctrl := controller c := s.newConsumer(t, q, topicKey, topicName, consumerGroup) require.NoError(t, c.Register(ctrl)) @@ -338,18 +317,19 @@ func (s *ConsumerIntegrationSuite) TestConsumerMultiPartitionThroughput() { var done sync.WaitGroup done.Add(numPartitions) - ctrl := &testController{ - name: "throughput-controller", - topicKey: topicKey, - consumerGroup: consumerGroup, - processFunc: func(ctx context.Context, delivery consumer.Delivery) error { - t.Logf("Processing partition=%s", delivery.Message().PartitionKey) - barrier.Done() // signal: this partition started - barrier.Wait() // block until all partitions are processing concurrently - done.Done() - return nil - }, - } + controller := consumermock.NewMockController(gomock.NewController(t)) + controller.EXPECT().Name().Return("throughput-controller").AnyTimes() + controller.EXPECT().TopicKey().Return(topicKey).AnyTimes() + controller.EXPECT().ConsumerGroup().Return(consumerGroup).AnyTimes() + controller.EXPECT().Process(gomock.Any(), gomock.Any()).DoAndReturn(func(ctx context.Context, delivery consumer.Delivery) error { + t.Logf("Processing partition=%s", delivery.Message().PartitionKey) + barrier.Done() // signal: this partition started + barrier.Wait() // block until all partitions are processing concurrently + done.Done() + return nil + }).AnyTimes() + + ctrl := controller c := s.newConsumer(t, q, topicKey, topicName, consumerGroup) require.NoError(t, c.Register(ctrl)) diff --git a/test/integration/submitqueue/extension/storage/mysql/BUILD.bazel b/test/integration/submitqueue/extension/storage/mysql/BUILD.bazel index fc8b7f484..50fb876b4 100644 --- a/test/integration/submitqueue/extension/storage/mysql/BUILD.bazel +++ b/test/integration/submitqueue/extension/storage/mysql/BUILD.bazel @@ -14,8 +14,10 @@ go_test( ], deps = [ "//submitqueue/gateway/extension/storage:go_default_library", + "//submitqueue/gateway/extension/storage/mock:go_default_library", "//submitqueue/gateway/extension/storage/mysql:go_default_library", "//submitqueue/orchestrator/extension/storage:go_default_library", + "//submitqueue/orchestrator/extension/storage/mock:go_default_library", "//submitqueue/orchestrator/extension/storage/mysql:go_default_library", "//test/integration/submitqueue/extension/storage:go_default_library", "//test/testutil:go_default_library", @@ -23,5 +25,6 @@ go_test( "@com_github_stretchr_testify//require:go_default_library", "@com_github_stretchr_testify//suite:go_default_library", "@com_github_uber_go_tally//:go_default_library", + "@org_uber_go_mock//gomock:go_default_library", ], ) diff --git a/test/integration/submitqueue/extension/storage/mysql/storage_test.go b/test/integration/submitqueue/extension/storage/mysql/storage_test.go index bbc0f07a2..c57786726 100644 --- a/test/integration/submitqueue/extension/storage/mysql/storage_test.go +++ b/test/integration/submitqueue/extension/storage/mysql/storage_test.go @@ -20,13 +20,16 @@ import ( "testing" orchstorage "github.com/uber/submitqueue/submitqueue/orchestrator/extension/storage" + "go.uber.org/mock/gomock" _ "github.com/go-sql-driver/mysql" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/uber-go/tally" gwstorage "github.com/uber/submitqueue/submitqueue/gateway/extension/storage" + gwstoragemock "github.com/uber/submitqueue/submitqueue/gateway/extension/storage/mock" gwmysqlstorage "github.com/uber/submitqueue/submitqueue/gateway/extension/storage/mysql" + orchstoragemock "github.com/uber/submitqueue/submitqueue/orchestrator/extension/storage/mock" mysqlstorage "github.com/uber/submitqueue/submitqueue/orchestrator/extension/storage/mysql" storagesuite "github.com/uber/submitqueue/test/integration/submitqueue/extension/storage" "github.com/uber/submitqueue/test/testutil" @@ -87,8 +90,12 @@ func (s *MySQLStorageIntegrationSuite) SetupSuite() { // Provide the storage backend to the contract suite through the // queue-scoped factory adapter. s.SetContext(ctx) - s.SetFactory(mysqlFactory{backend: store}) - s.SetGatewayFactory(gatewayMySQLFactory{backend: gwStore}) + factory := orchstoragemock.NewMockFactory(gomock.NewController(t)) + factory.EXPECT().For(gomock.Any()).DoAndReturn(func(config orchstorage.Config) (orchstorage.Storage, error) { return store.For(config.QueueName) }).AnyTimes() + s.SetFactory(factory) + gatewayFactory := gwstoragemock.NewMockFactory(gomock.NewController(t)) + gatewayFactory.EXPECT().For(gomock.Any()).DoAndReturn(func(config gwstorage.Config) (gwstorage.Storage, error) { return gwStore.For(config.QueueName) }).AnyTimes() + s.SetGatewayFactory(gatewayFactory) s.SetLogger(s.log) t.Cleanup(func() { @@ -105,25 +112,3 @@ func (s *MySQLStorageIntegrationSuite) TearDownSuite() { s.log.Logf("Tearing down MySQL Storage integration test suite") // Cleanup handled automatically by testutil.ComposeStack } - -// mysqlFactory adapts the MySQL storage backend's queue binding to the -// orchstorage.Factory seam for the contract suite, mirroring the host wiring. -type mysqlFactory struct { - backend *mysqlstorage.Storage -} - -// For returns the queue-scoped store aggregate bound to the queue named in config. -func (f mysqlFactory) For(config orchstorage.Config) (orchstorage.Storage, error) { - return f.backend.For(config.QueueName) -} - -// gatewayMySQLFactory adapts the gateway's MySQL storage backend to the -// gateway orchstorage.Factory seam for the contract suite. -type gatewayMySQLFactory struct { - backend *gwmysqlstorage.Storage -} - -// For returns the queue-scoped store aggregate bound to the queue named in config. -func (f gatewayMySQLFactory) For(config gwstorage.Config) (gwstorage.Storage, error) { - return f.backend.For(config.QueueName) -} diff --git a/test/integration/submitqueue/gateway/BUILD.bazel b/test/integration/submitqueue/gateway/BUILD.bazel index 678fbc231..0b1f5b9a6 100644 --- a/test/integration/submitqueue/gateway/BUILD.bazel +++ b/test/integration/submitqueue/gateway/BUILD.bazel @@ -25,6 +25,7 @@ go_test( "//submitqueue/entity:go_default_library", "//submitqueue/gateway/core/request:go_default_library", "//submitqueue/gateway/extension/storage:go_default_library", + "//submitqueue/gateway/extension/storage/mock:go_default_library", "//submitqueue/gateway/extension/storage/mysql:go_default_library", "//submitqueue/orchestrator/core/request:go_default_library", "//test/testutil:go_default_library", @@ -35,6 +36,7 @@ go_test( "@org_golang_google_grpc//:go_default_library", "@org_golang_google_grpc//codes:go_default_library", "@org_golang_google_grpc//status:go_default_library", + "@org_uber_go_mock//gomock:go_default_library", "@org_uber_go_zap//:go_default_library", ], ) diff --git a/test/integration/submitqueue/gateway/suite_test.go b/test/integration/submitqueue/gateway/suite_test.go index 46a27865e..c51cdbe96 100644 --- a/test/integration/submitqueue/gateway/suite_test.go +++ b/test/integration/submitqueue/gateway/suite_test.go @@ -45,9 +45,11 @@ import ( "github.com/uber/submitqueue/submitqueue/entity" corerequest "github.com/uber/submitqueue/submitqueue/gateway/core/request" "github.com/uber/submitqueue/submitqueue/gateway/extension/storage" + storagemock "github.com/uber/submitqueue/submitqueue/gateway/extension/storage/mock" mysqlstorage "github.com/uber/submitqueue/submitqueue/gateway/extension/storage/mysql" orchrequest "github.com/uber/submitqueue/submitqueue/orchestrator/core/request" "github.com/uber/submitqueue/test/testutil" + "go.uber.org/mock/gomock" "go.uber.org/zap" "google.golang.org/grpc" "google.golang.org/grpc/codes" @@ -199,7 +201,10 @@ func (s *GatewayIntegrationSuite) TestListAPI() { t := s.T() store, err := mysqlstorage.NewStorage(s.db, tally.NoopScope) require.NoError(t, err) - materializer := corerequest.NewMaterializer(mysqlFactory{backend: store}) + factory := storagemock.NewMockFactory(gomock.NewController(t)) + factory.EXPECT().For(gomock.Any()).DoAndReturn(func(config storage.Config) (storage.Storage, error) { return store.For(config.QueueName) }).AnyTimes() + + materializer := corerequest.NewMaterializer(factory) queueStore, err := store.For("test-queue") require.NoError(t, err) for _, summary := range []entity.RequestSummary{ @@ -403,14 +408,3 @@ func (s *GatewayIntegrationSuite) TestRequestLogConsumer() { s.log.Logf("Request log consumer test passed: entry persisted and readable via GetRequestSummaryByID") } - -// mysqlFactory adapts the MySQL storage backend's queue binding to the -// storage.Factory seam, mirroring the host wiring. -type mysqlFactory struct { - backend *mysqlstorage.Storage -} - -// For returns the queue-scoped store aggregate bound to the queue named in config. -func (f mysqlFactory) For(config storage.Config) (storage.Storage, error) { - return f.backend.For(config.QueueName) -}