From d995f7d1826b9f8541e2133b058bc4f45a992e3a Mon Sep 17 00:00:00 2001 From: Daniel Moran Date: Thu, 6 May 2021 10:19:41 -0400 Subject: [PATCH] test: replace hand-written mocks with gomock (#63) --- Makefile | 5 +- internal/bucket.go | 5 +- internal/bucket_test.go | 961 +++++++++++----------- internal/cmd/bucket_schema/client_test.go | 94 ++- internal/cmd/bucket_schema/csv.go | 5 +- internal/mock/README.md | 7 + internal/mock/api_buckets.go | 57 -- internal/mock/api_health.gen.go | 65 ++ internal/mock/api_health.go | 23 - internal/mock/api_organizations.gen.go | 94 +++ internal/mock/api_organizations.go | 30 - internal/mock/api_setup.gen.go | 94 +++ internal/mock/api_setup.go | 31 - internal/mock/api_write.gen.go | 64 ++ internal/mock/api_write.go | 22 - internal/mock/config.gen.go | 125 +++ internal/mock/config.go | 33 - internal/mock/gen.go | 13 +- internal/mock/stdio.gen.go | 121 +++ internal/mock/stdio.go | 55 -- internal/ping_test.go | 46 +- internal/setup_test.go | 244 +++--- internal/write_test.go | 101 ++- tools.go | 1 + 24 files changed, 1313 insertions(+), 983 deletions(-) create mode 100644 internal/mock/README.md delete mode 100644 internal/mock/api_buckets.go create mode 100644 internal/mock/api_health.gen.go delete mode 100644 internal/mock/api_health.go create mode 100644 internal/mock/api_organizations.gen.go delete mode 100644 internal/mock/api_organizations.go create mode 100644 internal/mock/api_setup.gen.go delete mode 100644 internal/mock/api_setup.go create mode 100644 internal/mock/api_write.gen.go delete mode 100644 internal/mock/api_write.go create mode 100644 internal/mock/config.gen.go delete mode 100644 internal/mock/config.go create mode 100644 internal/mock/stdio.gen.go delete mode 100644 internal/mock/stdio.go diff --git a/Makefile b/Makefile index 36848f0..f3f2758 100644 --- a/Makefile +++ b/Makefile @@ -67,6 +67,9 @@ vet: go vet ./... # Testing +mock: ./internal/mock/gen.go + go generate ./internal/mock/ + test: $(GO_TEST) $(GO_TEST_PATHS) @@ -74,4 +77,4 @@ test-race: $(GO_TEST) -v -race -count=1 $(GO_TEST_PATHS) ### List of all targets that don't produce a file -.PHONY: influx openapi fmt build checkfmt checktidy staticcheck vet test test-race +.PHONY: influx openapi fmt build checkfmt checktidy staticcheck vet mock test test-race diff --git a/internal/bucket.go b/internal/bucket.go index 5fd0a39..7358f65 100644 --- a/internal/bucket.go +++ b/internal/bucket.go @@ -193,13 +193,14 @@ func (c *CLI) BucketsDelete(ctx context.Context, client api.BucketsApi, params * } var bucket api.Bucket - getReq := client.GetBuckets(ctx) + var getReq api.ApiGetBucketsRequest if params.ID != "" { - getReq = getReq.Id(params.ID) + getReq = client.GetBuckets(ctx).Id(params.ID) } else { if params.OrgID == "" && params.OrgName == "" && c.ActiveConfig.Org == "" { return ErrMustSpecifyOrgDeleteByName } + getReq = client.GetBuckets(ctx) getReq = getReq.Name(params.Name) if params.OrgID != "" { getReq = getReq.OrgID(params.OrgID) diff --git a/internal/bucket_test.go b/internal/bucket_test.go index e9dbe68..0050188 100644 --- a/internal/bucket_test.go +++ b/internal/bucket_test.go @@ -1,16 +1,18 @@ package internal_test import ( + "bytes" "context" - "errors" "strings" "testing" + "github.com/golang/mock/gomock" "github.com/influxdata/influx-cli/v2/internal" "github.com/influxdata/influx-cli/v2/internal/api" "github.com/influxdata/influx-cli/v2/internal/config" "github.com/influxdata/influx-cli/v2/internal/mock" "github.com/stretchr/testify/assert" + tmock "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" ) @@ -18,13 +20,13 @@ func TestBucketsCreate(t *testing.T) { t.Parallel() var testCases = []struct { - name string - configOrgName string - params internal.BucketsCreateParams - buildOrgLookupFn func(*testing.T) func(api.ApiGetOrgsRequest) (api.Organizations, error) - buildBucketCreateFn func(*testing.T) func(api.ApiPostBucketsRequest) (api.Bucket, error) - expectedStdoutPattern string - expectedInErr string + name string + configOrgName string + params internal.BucketsCreateParams + registerOrgExpectations func(*testing.T, *mock.MockOrganizationsApi) + registerBucketExpectations func(*testing.T, *mock.MockBucketsApi) + expectedStdoutPattern string + expectedInErr string }{ { name: "minimal", @@ -32,26 +34,23 @@ func TestBucketsCreate(t *testing.T) { OrgID: "123", Name: "my-bucket", }, - buildOrgLookupFn: func(t *testing.T) func(api.ApiGetOrgsRequest) (api.Organizations, error) { - return func(api.ApiGetOrgsRequest) (api.Organizations, error) { - return api.Organizations{}, errors.New("unexpected org lookup call") - } - }, - buildBucketCreateFn: func(t *testing.T) func(api.ApiPostBucketsRequest) (api.Bucket, error) { - return func(req api.ApiPostBucketsRequest) (api.Bucket, error) { - body := req.GetPostBucketRequest() - require.NotNil(t, body) - require.Equal(t, "123", body.OrgID) - require.Equal(t, "my-bucket", body.Name) - require.Empty(t, body.RetentionRules) - - return api.Bucket{ + registerBucketExpectations: func(t *testing.T, bucketsApi *mock.MockBucketsApi) { + bucketsApi.EXPECT().PostBuckets(gomock.Any()).Return(api.ApiPostBucketsRequest{ApiService: bucketsApi}) + bucketsApi.EXPECT(). + PostBucketsExecute(tmock.MatchedBy(func(in api.ApiPostBucketsRequest) bool { + body := in.GetPostBucketRequest() + return assert.NotNil(t, body) && + assert.Equal(t, "123", body.OrgID) && + assert.Equal(t, "my-bucket", body.Name) && + assert.Nil(t, body.Description) && + assert.Empty(t, body.RetentionRules) + })). + Return(api.Bucket{ Id: api.PtrString("456"), OrgID: api.PtrString("123"), Name: "my-bucket", RetentionRules: nil, - }, nil - } + }, nil) }, expectedStdoutPattern: "456\\s+my-bucket\\s+infinite\\s+n/a\\s+123", }, @@ -64,29 +63,27 @@ func TestBucketsCreate(t *testing.T) { Retention: "24h", ShardGroupDuration: "1h", }, - buildOrgLookupFn: func(t *testing.T) func(api.ApiGetOrgsRequest) (api.Organizations, error) { - return func(api.ApiGetOrgsRequest) (api.Organizations, error) { - return api.Organizations{}, errors.New("unexpected org lookup call") - } - }, - buildBucketCreateFn: func(t *testing.T) func(api.ApiPostBucketsRequest) (api.Bucket, error) { - return func(req api.ApiPostBucketsRequest) (api.Bucket, error) { - body := req.GetPostBucketRequest() - require.NotNil(t, body) - require.Equal(t, "123", body.OrgID) - require.Equal(t, "my-bucket", body.Name) - require.Equal(t, "my cool bucket", *body.Description) - require.Equal(t, 1, len(body.RetentionRules)) - require.Equal(t, int64(86400), body.RetentionRules[0].EverySeconds) - require.Equal(t, int64(3600), *body.RetentionRules[0].ShardGroupDurationSeconds) - - return api.Bucket{ - Id: api.PtrString("456"), - OrgID: api.PtrString("123"), - Name: "my-bucket", - RetentionRules: body.RetentionRules, - }, nil - } + registerBucketExpectations: func(t *testing.T, bucketsApi *mock.MockBucketsApi) { + bucketsApi.EXPECT().PostBuckets(gomock.Any()).Return(api.ApiPostBucketsRequest{ApiService: bucketsApi}) + bucketsApi.EXPECT(). + PostBucketsExecute(tmock.MatchedBy(func(in api.ApiPostBucketsRequest) bool { + body := in.GetPostBucketRequest() + return assert.NotNil(t, body) && + assert.Equal(t, "123", body.OrgID) && + assert.Equal(t, "my-bucket", body.Name) && + assert.Equal(t, "my cool bucket", *body.Description) && + assert.Len(t, body.RetentionRules, 1) && + assert.Equal(t, int64(86400), body.RetentionRules[0].EverySeconds) && + assert.Equal(t, int64(3600), *body.RetentionRules[0].ShardGroupDurationSeconds) + })). + Return(api.Bucket{ + Id: api.PtrString("456"), + OrgID: api.PtrString("123"), + Name: "my-bucket", + RetentionRules: []api.RetentionRule{ + {EverySeconds: 86400, ShardGroupDurationSeconds: api.PtrInt64(3600)}, + }, + }, nil) }, expectedStdoutPattern: "456\\s+my-bucket\\s+24h0m0s\\s+1h0m0s\\s+123", }, @@ -97,29 +94,25 @@ func TestBucketsCreate(t *testing.T) { Name: "my-bucket", Retention: "24h", }, - buildOrgLookupFn: func(t *testing.T) func(api.ApiGetOrgsRequest) (api.Organizations, error) { - return func(api.ApiGetOrgsRequest) (api.Organizations, error) { - return api.Organizations{}, errors.New("unexpected org lookup call") - } - }, - buildBucketCreateFn: func(t *testing.T) func(api.ApiPostBucketsRequest) (api.Bucket, error) { - return func(req api.ApiPostBucketsRequest) (api.Bucket, error) { - body := req.GetPostBucketRequest() - require.NotNil(t, body) - require.Equal(t, "123", body.OrgID) - require.Equal(t, "my-bucket", body.Name) - require.Nil(t, body.Description) - require.Equal(t, 1, len(body.RetentionRules)) - require.Equal(t, int64(86400), body.RetentionRules[0].EverySeconds) - require.Nil(t, body.RetentionRules[0].ShardGroupDurationSeconds) - - return api.Bucket{ + registerBucketExpectations: func(t *testing.T, bucketsApi *mock.MockBucketsApi) { + bucketsApi.EXPECT().PostBuckets(gomock.Any()).Return(api.ApiPostBucketsRequest{ApiService: bucketsApi}) + bucketsApi.EXPECT(). + PostBucketsExecute(tmock.MatchedBy(func(in api.ApiPostBucketsRequest) bool { + body := in.GetPostBucketRequest() + return assert.NotNil(t, body) && + assert.Equal(t, "123", body.OrgID) && + assert.Equal(t, "my-bucket", body.Name) && + assert.Nil(t, body.Description) && + assert.Len(t, body.RetentionRules, 1) && + assert.Equal(t, int64(86400), body.RetentionRules[0].EverySeconds) && + assert.Nil(t, body.RetentionRules[0].ShardGroupDurationSeconds) + })). + Return(api.Bucket{ Id: api.PtrString("456"), OrgID: api.PtrString("123"), Name: "my-bucket", - RetentionRules: body.RetentionRules, - }, nil - } + RetentionRules: []api.RetentionRule{{EverySeconds: 86400}}, + }, nil) }, }, { @@ -127,32 +120,28 @@ func TestBucketsCreate(t *testing.T) { params: internal.BucketsCreateParams{ OrgID: "123", Name: "my-bucket", - Retention: "24h", SchemaType: api.SCHEMATYPE_EXPLICIT, }, - buildOrgLookupFn: func(t *testing.T) func(api.ApiGetOrgsRequest) (api.Organizations, error) { - return func(api.ApiGetOrgsRequest) (api.Organizations, error) { - return api.Organizations{}, errors.New("unexpected org lookup call") - } + registerBucketExpectations: func(t *testing.T, bucketsApi *mock.MockBucketsApi) { + bucketsApi.EXPECT().PostBuckets(gomock.Any()).Return(api.ApiPostBucketsRequest{ApiService: bucketsApi}) + bucketsApi.EXPECT(). + PostBucketsExecute(tmock.MatchedBy(func(in api.ApiPostBucketsRequest) bool { + body := in.GetPostBucketRequest() + return assert.NotNil(t, body) && + assert.Equal(t, "123", body.OrgID) && + assert.Equal(t, "my-bucket", body.Name) && + assert.Nil(t, body.Description) && + assert.Empty(t, body.RetentionRules) && + assert.Equal(t, api.SCHEMATYPE_EXPLICIT, *body.SchemaType) + })). + Return(api.Bucket{ + Id: api.PtrString("456"), + OrgID: api.PtrString("123"), + Name: "my-bucket", + SchemaType: api.SCHEMATYPE_EXPLICIT.Ptr(), + }, nil) }, - buildBucketCreateFn: func(t *testing.T) func(api.ApiPostBucketsRequest) (api.Bucket, error) { - return func(req api.ApiPostBucketsRequest) (api.Bucket, error) { - body := req.GetPostBucketRequest() - require.NotNil(t, body) - require.Equal(t, "123", body.OrgID) - require.NotNil(t, body.SchemaType) - assert.Equal(t, api.SCHEMATYPE_EXPLICIT, *body.SchemaType) - - return api.Bucket{ - Id: api.PtrString("456"), - OrgID: api.PtrString("123"), - Name: "my-bucket", - RetentionRules: body.RetentionRules, - SchemaType: api.SCHEMATYPE_EXPLICIT.Ptr(), - }, nil - } - }, - expectedStdoutPattern: `456\s+my-bucket\s+24h0m0s\s+n/a\s+123\s+explicit`, + expectedStdoutPattern: `456\s+my-bucket\s+infinite\s+n/a\s+123\s+explicit`, }, { name: "look up org by name", @@ -163,32 +152,36 @@ func TestBucketsCreate(t *testing.T) { Retention: "24h", ShardGroupDuration: "1h", }, - buildOrgLookupFn: func(t *testing.T) func(api.ApiGetOrgsRequest) (api.Organizations, error) { - return func(req api.ApiGetOrgsRequest) (api.Organizations, error) { - require.Equal(t, "my-org", *req.GetOrg()) - return api.Organizations{ + registerOrgExpectations: func(t *testing.T, orgApi *mock.MockOrganizationsApi) { + orgApi.EXPECT().GetOrgs(gomock.Any()).Return(api.ApiGetOrgsRequest{ApiService: orgApi}) + orgApi.EXPECT().GetOrgsExecute(tmock.MatchedBy(func(in api.ApiGetOrgsRequest) bool { + return assert.Equal(t, "my-org", *in.GetOrg()) + })). + Return(api.Organizations{ Orgs: &[]api.Organization{{Id: api.PtrString("123")}}, - }, nil - } + }, nil) }, - buildBucketCreateFn: func(t *testing.T) func(api.ApiPostBucketsRequest) (api.Bucket, error) { - return func(req api.ApiPostBucketsRequest) (api.Bucket, error) { - body := req.GetPostBucketRequest() - require.NotNil(t, body) - require.Equal(t, "123", body.OrgID) - require.Equal(t, "my-bucket", body.Name) - require.Equal(t, "my cool bucket", *body.Description) - require.Equal(t, 1, len(body.RetentionRules)) - require.Equal(t, int64(86400), body.RetentionRules[0].EverySeconds) - require.Equal(t, int64(3600), *body.RetentionRules[0].ShardGroupDurationSeconds) - - return api.Bucket{ - Id: api.PtrString("456"), - OrgID: api.PtrString("123"), - Name: "my-bucket", - RetentionRules: body.RetentionRules, - }, nil - } + registerBucketExpectations: func(t *testing.T, bucketsApi *mock.MockBucketsApi) { + bucketsApi.EXPECT().PostBuckets(gomock.Any()).Return(api.ApiPostBucketsRequest{ApiService: bucketsApi}) + bucketsApi.EXPECT(). + PostBucketsExecute(tmock.MatchedBy(func(in api.ApiPostBucketsRequest) bool { + body := in.GetPostBucketRequest() + return assert.NotNil(t, body) && + assert.Equal(t, "123", body.OrgID) && + assert.Equal(t, "my-bucket", body.Name) && + assert.Equal(t, "my cool bucket", *body.Description) && + assert.Len(t, body.RetentionRules, 1) && + assert.Equal(t, int64(86400), body.RetentionRules[0].EverySeconds) && + assert.Equal(t, int64(3600), *body.RetentionRules[0].ShardGroupDurationSeconds) + })). + Return(api.Bucket{ + Id: api.PtrString("456"), + OrgID: api.PtrString("123"), + Name: "my-bucket", + RetentionRules: []api.RetentionRule{ + {EverySeconds: 86400, ShardGroupDurationSeconds: api.PtrInt64(3600)}, + }, + }, nil) }, expectedStdoutPattern: "456\\s+my-bucket\\s+24h0m0s\\s+1h0m0s\\s+123", }, @@ -201,32 +194,36 @@ func TestBucketsCreate(t *testing.T) { ShardGroupDuration: "1h", }, configOrgName: "my-org", - buildOrgLookupFn: func(t *testing.T) func(api.ApiGetOrgsRequest) (api.Organizations, error) { - return func(req api.ApiGetOrgsRequest) (api.Organizations, error) { - require.Equal(t, "my-org", *req.GetOrg()) - return api.Organizations{ + registerOrgExpectations: func(t *testing.T, orgApi *mock.MockOrganizationsApi) { + orgApi.EXPECT().GetOrgs(gomock.Any()).Return(api.ApiGetOrgsRequest{ApiService: orgApi}) + orgApi.EXPECT().GetOrgsExecute(tmock.MatchedBy(func(in api.ApiGetOrgsRequest) bool { + return assert.Equal(t, "my-org", *in.GetOrg()) + })). + Return(api.Organizations{ Orgs: &[]api.Organization{{Id: api.PtrString("123")}}, - }, nil - } + }, nil) }, - buildBucketCreateFn: func(t *testing.T) func(api.ApiPostBucketsRequest) (api.Bucket, error) { - return func(req api.ApiPostBucketsRequest) (api.Bucket, error) { - body := req.GetPostBucketRequest() - require.NotNil(t, body) - require.Equal(t, "123", body.OrgID) - require.Equal(t, "my-bucket", body.Name) - require.Equal(t, "my cool bucket", *body.Description) - require.Equal(t, 1, len(body.RetentionRules)) - require.Equal(t, int64(86400), body.RetentionRules[0].EverySeconds) - require.Equal(t, int64(3600), *body.RetentionRules[0].ShardGroupDurationSeconds) - - return api.Bucket{ - Id: api.PtrString("456"), - OrgID: api.PtrString("123"), - Name: "my-bucket", - RetentionRules: body.RetentionRules, - }, nil - } + registerBucketExpectations: func(t *testing.T, bucketsApi *mock.MockBucketsApi) { + bucketsApi.EXPECT().PostBuckets(gomock.Any()).Return(api.ApiPostBucketsRequest{ApiService: bucketsApi}) + bucketsApi.EXPECT(). + PostBucketsExecute(tmock.MatchedBy(func(in api.ApiPostBucketsRequest) bool { + body := in.GetPostBucketRequest() + return assert.NotNil(t, body) && + assert.Equal(t, "123", body.OrgID) && + assert.Equal(t, "my-bucket", body.Name) && + assert.Equal(t, "my cool bucket", *body.Description) && + assert.Len(t, body.RetentionRules, 1) && + assert.Equal(t, int64(86400), body.RetentionRules[0].EverySeconds) && + assert.Equal(t, int64(3600), *body.RetentionRules[0].ShardGroupDurationSeconds) + })). + Return(api.Bucket{ + Id: api.PtrString("456"), + OrgID: api.PtrString("123"), + Name: "my-bucket", + RetentionRules: []api.RetentionRule{ + {EverySeconds: 86400, ShardGroupDurationSeconds: api.PtrInt64(3600)}, + }, + }, nil) }, expectedStdoutPattern: "456\\s+my-bucket\\s+24h0m0s\\s+1h0m0s\\s+123", }, @@ -238,16 +235,6 @@ func TestBucketsCreate(t *testing.T) { Retention: "24h", ShardGroupDuration: "1h", }, - buildOrgLookupFn: func(t *testing.T) func(api.ApiGetOrgsRequest) (api.Organizations, error) { - return func(req api.ApiGetOrgsRequest) (api.Organizations, error) { - return api.Organizations{}, errors.New("shouldn't be called") - } - }, - buildBucketCreateFn: func(t *testing.T) func(api.ApiPostBucketsRequest) (api.Bucket, error) { - return func(req api.ApiPostBucketsRequest) (api.Bucket, error) { - return api.Bucket{}, errors.New("shouldn't be called") - } - }, expectedInErr: "must specify org ID or org name", }, { @@ -259,15 +246,9 @@ func TestBucketsCreate(t *testing.T) { Retention: "24h", ShardGroupDuration: "1h", }, - buildOrgLookupFn: func(t *testing.T) func(api.ApiGetOrgsRequest) (api.Organizations, error) { - return func(req api.ApiGetOrgsRequest) (api.Organizations, error) { - return api.Organizations{}, nil - } - }, - buildBucketCreateFn: func(t *testing.T) func(api.ApiPostBucketsRequest) (api.Bucket, error) { - return func(req api.ApiPostBucketsRequest) (api.Bucket, error) { - return api.Bucket{}, errors.New("shouldn't be called") - } + registerOrgExpectations: func(t *testing.T, orgApi *mock.MockOrganizationsApi) { + orgApi.EXPECT().GetOrgs(gomock.Any()).Return(api.ApiGetOrgsRequest{ApiService: orgApi}) + orgApi.EXPECT().GetOrgsExecute(gomock.Any()).Return(api.Organizations{}, nil) }, expectedInErr: "no organization found", }, @@ -278,26 +259,34 @@ func TestBucketsCreate(t *testing.T) { t.Run(tc.name, func(t *testing.T) { t.Parallel() - stdio := mock.NewMockStdio(nil, false) + ctrl := gomock.NewController(t) + stdio := mock.NewMockStdIO(ctrl) + writtenBytes := bytes.Buffer{} + stdio.EXPECT().Write(gomock.Any()).DoAndReturn(writtenBytes.Write).AnyTimes() + + orgApi := mock.NewMockOrganizationsApi(ctrl) + if tc.registerOrgExpectations != nil { + tc.registerOrgExpectations(t, orgApi) + } + bucketApi := mock.NewMockBucketsApi(ctrl) + if tc.registerBucketExpectations != nil { + tc.registerBucketExpectations(t, bucketApi) + } cli := internal.CLI{ActiveConfig: config.Config{Org: tc.configOrgName}, StdIO: stdio} clients := internal.BucketsClients{ - OrgApi: &mock.OrganizationsApi{ - GetOrgsExecuteFn: tc.buildOrgLookupFn(t), - }, - BucketApi: &mock.BucketsApi{ - PostBucketsExecuteFn: tc.buildBucketCreateFn(t), - }, + OrgApi: orgApi, + BucketApi: bucketApi, } err := cli.BucketsCreate(context.Background(), &clients, &tc.params) if tc.expectedInErr != "" { require.Error(t, err) require.Contains(t, err.Error(), tc.expectedInErr) - require.Empty(t, stdio.Stdout()) + require.Empty(t, writtenBytes.String()) return } require.NoError(t, err) - outLines := strings.Split(stdio.Stdout(), "\n") + outLines := strings.Split(writtenBytes.String(), "\n") if outLines[len(outLines)-1] == "" { outLines = outLines[:len(outLines)-1] } @@ -312,12 +301,12 @@ func TestBucketsList(t *testing.T) { t.Parallel() var testCases = []struct { - name string - configOrgName string - params internal.BucketsListParams - buildBucketLookupFn func(*testing.T) func(api.ApiGetBucketsRequest) (api.Buckets, error) - expectedStdoutPatterns []string - expectedInErr string + name string + configOrgName string + params internal.BucketsListParams + registerBucketExpectations func(*testing.T, *mock.MockBucketsApi) + expectedStdoutPatterns []string + expectedInErr string }{ { name: "by ID", @@ -325,25 +314,25 @@ func TestBucketsList(t *testing.T) { ID: "123", }, configOrgName: "my-default-org", - buildBucketLookupFn: func(t *testing.T) func(api.ApiGetBucketsRequest) (api.Buckets, error) { - return func(req api.ApiGetBucketsRequest) (api.Buckets, error) { - require.Equal(t, "123", *req.GetId()) - require.Equal(t, "my-default-org", *req.GetOrg()) - require.Nil(t, req.GetName()) - require.Nil(t, req.GetOrgID()) - return api.Buckets{ - Buckets: &[]api.Bucket{ - { - Id: api.PtrString("123"), - Name: "my-bucket", - OrgID: api.PtrString("456"), - RetentionRules: []api.RetentionRule{ - {EverySeconds: 3600}, - }, + registerBucketExpectations: func(t *testing.T, bucketsApi *mock.MockBucketsApi) { + bucketsApi.EXPECT().GetBuckets(gomock.Any()).Return(api.ApiGetBucketsRequest{ApiService: bucketsApi}) + bucketsApi.EXPECT().GetBucketsExecute(tmock.MatchedBy(func(in api.ApiGetBucketsRequest) bool { + return assert.Equal(t, "123", *in.GetId()) && + assert.Equal(t, "my-default-org", *in.GetOrg()) && + assert.Nil(t, in.GetName()) && + assert.Nil(t, in.GetOrgID()) + })).Return(api.Buckets{ + Buckets: &[]api.Bucket{ + { + Id: api.PtrString("123"), + Name: "my-bucket", + OrgID: api.PtrString("456"), + RetentionRules: []api.RetentionRule{ + {EverySeconds: 3600}, }, }, - }, nil - } + }, + }, nil) }, expectedStdoutPatterns: []string{ "123\\s+my-bucket\\s+1h0m0s\\s+n/a\\s+456", @@ -355,25 +344,25 @@ func TestBucketsList(t *testing.T) { Name: "my-bucket", }, configOrgName: "my-default-org", - buildBucketLookupFn: func(t *testing.T) func(api.ApiGetBucketsRequest) (api.Buckets, error) { - return func(req api.ApiGetBucketsRequest) (api.Buckets, error) { - require.Equal(t, "my-bucket", *req.GetName()) - require.Equal(t, "my-default-org", *req.GetOrg()) - require.Nil(t, req.GetId()) - require.Nil(t, req.GetOrgID()) - return api.Buckets{ - Buckets: &[]api.Bucket{ - { - Id: api.PtrString("123"), - Name: "my-bucket", - OrgID: api.PtrString("456"), - RetentionRules: []api.RetentionRule{ - {EverySeconds: 3600}, - }, + registerBucketExpectations: func(t *testing.T, bucketsApi *mock.MockBucketsApi) { + bucketsApi.EXPECT().GetBuckets(gomock.Any()).Return(api.ApiGetBucketsRequest{ApiService: bucketsApi}) + bucketsApi.EXPECT().GetBucketsExecute(tmock.MatchedBy(func(in api.ApiGetBucketsRequest) bool { + return assert.Equal(t, "my-bucket", *in.GetName()) && + assert.Equal(t, "my-default-org", *in.GetOrg()) && + assert.Nil(t, in.GetId()) && + assert.Nil(t, in.GetOrgID()) + })).Return(api.Buckets{ + Buckets: &[]api.Bucket{ + { + Id: api.PtrString("123"), + Name: "my-bucket", + OrgID: api.PtrString("456"), + RetentionRules: []api.RetentionRule{ + {EverySeconds: 3600}, }, }, - }, nil - } + }, + }, nil) }, expectedStdoutPatterns: []string{ "123\\s+my-bucket\\s+1h0m0s\\s+n/a\\s+456", @@ -385,14 +374,14 @@ func TestBucketsList(t *testing.T) { OrgID: "456", }, configOrgName: "my-default-org", - buildBucketLookupFn: func(t *testing.T) func(api.ApiGetBucketsRequest) (api.Buckets, error) { - return func(req api.ApiGetBucketsRequest) (api.Buckets, error) { - require.Equal(t, "456", *req.GetOrgID()) - require.Nil(t, req.GetId()) - require.Nil(t, req.GetOrg()) - require.Nil(t, req.GetOrg()) - return api.Buckets{}, nil - } + registerBucketExpectations: func(t *testing.T, bucketsApi *mock.MockBucketsApi) { + bucketsApi.EXPECT().GetBuckets(gomock.Any()).Return(api.ApiGetBucketsRequest{ApiService: bucketsApi}) + bucketsApi.EXPECT().GetBucketsExecute(tmock.MatchedBy(func(in api.ApiGetBucketsRequest) bool { + return assert.Equal(t, "456", *in.GetOrgID()) && + assert.Nil(t, in.GetId()) && + assert.Nil(t, in.GetOrg()) && + assert.Nil(t, in.GetName()) + })).Return(api.Buckets{}, nil) }, }, { @@ -401,33 +390,33 @@ func TestBucketsList(t *testing.T) { OrgName: "my-org", }, configOrgName: "my-default-org", - buildBucketLookupFn: func(t *testing.T) func(api.ApiGetBucketsRequest) (api.Buckets, error) { - return func(req api.ApiGetBucketsRequest) (api.Buckets, error) { - require.Equal(t, "my-org", *req.GetOrg()) - require.Nil(t, req.GetId()) - require.Nil(t, req.GetName()) - require.Nil(t, req.GetOrgID()) - return api.Buckets{ - Buckets: &[]api.Bucket{ - { - Id: api.PtrString("123"), - Name: "my-bucket", - OrgID: api.PtrString("456"), - RetentionRules: []api.RetentionRule{ - {EverySeconds: 3600}, - }, - }, - { - Id: api.PtrString("999"), - Name: "bucket2", - OrgID: api.PtrString("456"), - RetentionRules: []api.RetentionRule{ - {EverySeconds: 0, ShardGroupDurationSeconds: api.PtrInt64(60)}, - }, + registerBucketExpectations: func(t *testing.T, bucketsApi *mock.MockBucketsApi) { + bucketsApi.EXPECT().GetBuckets(gomock.Any()).Return(api.ApiGetBucketsRequest{ApiService: bucketsApi}) + bucketsApi.EXPECT().GetBucketsExecute(tmock.MatchedBy(func(in api.ApiGetBucketsRequest) bool { + return assert.Equal(t, "my-org", *in.GetOrg()) && + assert.Nil(t, in.GetId()) && + assert.Nil(t, in.GetName()) && + assert.Nil(t, in.GetOrgID()) + })).Return(api.Buckets{ + Buckets: &[]api.Bucket{ + { + Id: api.PtrString("123"), + Name: "my-bucket", + OrgID: api.PtrString("456"), + RetentionRules: []api.RetentionRule{ + {EverySeconds: 3600}, }, }, - }, nil - } + { + Id: api.PtrString("999"), + Name: "bucket2", + OrgID: api.PtrString("456"), + RetentionRules: []api.RetentionRule{ + {EverySeconds: 0, ShardGroupDurationSeconds: api.PtrInt64(60)}, + }, + }, + }, + }, nil) }, expectedStdoutPatterns: []string{ "123\\s+my-bucket\\s+1h0m0s\\s+n/a\\s+456", @@ -440,43 +429,43 @@ func TestBucketsList(t *testing.T) { OrgName: "my-org", }, configOrgName: "my-default-org", - buildBucketLookupFn: func(t *testing.T) func(api.ApiGetBucketsRequest) (api.Buckets, error) { - return func(req api.ApiGetBucketsRequest) (api.Buckets, error) { - require.Equal(t, "my-org", *req.GetOrg()) - require.Nil(t, req.GetId()) - require.Nil(t, req.GetName()) - require.Nil(t, req.GetOrgID()) - return api.Buckets{ - Buckets: &[]api.Bucket{ - { - Id: api.PtrString("001"), - Name: "omit-schema-type", - OrgID: api.PtrString("456"), - RetentionRules: []api.RetentionRule{ - {EverySeconds: 3600}, - }, - }, - { - Id: api.PtrString("002"), - Name: "implicit-schema-type", - OrgID: api.PtrString("456"), - RetentionRules: []api.RetentionRule{ - {EverySeconds: 3600}, - }, - SchemaType: api.SCHEMATYPE_IMPLICIT.Ptr(), - }, - { - Id: api.PtrString("003"), - Name: "explicit-schema-type", - OrgID: api.PtrString("456"), - RetentionRules: []api.RetentionRule{ - {EverySeconds: 3600}, - }, - SchemaType: api.SCHEMATYPE_EXPLICIT.Ptr(), + registerBucketExpectations: func(t *testing.T, bucketsApi *mock.MockBucketsApi) { + bucketsApi.EXPECT().GetBuckets(gomock.Any()).Return(api.ApiGetBucketsRequest{ApiService: bucketsApi}) + bucketsApi.EXPECT().GetBucketsExecute(tmock.MatchedBy(func(in api.ApiGetBucketsRequest) bool { + return assert.Equal(t, "my-org", *in.GetOrg()) && + assert.Nil(t, in.GetId()) && + assert.Nil(t, in.GetName()) && + assert.Nil(t, in.GetOrgID()) + })).Return(api.Buckets{ + Buckets: &[]api.Bucket{ + { + Id: api.PtrString("001"), + Name: "omit-schema-type", + OrgID: api.PtrString("456"), + RetentionRules: []api.RetentionRule{ + {EverySeconds: 3600}, }, }, - }, nil - } + { + Id: api.PtrString("002"), + Name: "implicit-schema-type", + OrgID: api.PtrString("456"), + RetentionRules: []api.RetentionRule{ + {EverySeconds: 3600}, + }, + SchemaType: api.SCHEMATYPE_IMPLICIT.Ptr(), + }, + { + Id: api.PtrString("003"), + Name: "explicit-schema-type", + OrgID: api.PtrString("456"), + RetentionRules: []api.RetentionRule{ + {EverySeconds: 3600}, + }, + SchemaType: api.SCHEMATYPE_EXPLICIT.Ptr(), + }, + }, + }, nil) }, expectedStdoutPatterns: []string{ `001\s+omit-schema-type\s+1h0m0s\s+n/a\s+456\s+implicit`, @@ -487,11 +476,6 @@ func TestBucketsList(t *testing.T) { { name: "no org specified", expectedInErr: "must specify org ID or org name", - buildBucketLookupFn: func(t *testing.T) func(api.ApiGetBucketsRequest) (api.Buckets, error) { - return func(api.ApiGetBucketsRequest) (api.Buckets, error) { - return api.Buckets{}, errors.New("shouldn't be called") - } - }, }, } @@ -500,21 +484,26 @@ func TestBucketsList(t *testing.T) { t.Run(tc.name, func(t *testing.T) { t.Parallel() - stdio := mock.NewMockStdio(nil, false) + ctrl := gomock.NewController(t) + stdio := mock.NewMockStdIO(ctrl) + bytesWritten := bytes.Buffer{} + stdio.EXPECT().Write(gomock.Any()).DoAndReturn(bytesWritten.Write).AnyTimes() cli := internal.CLI{ActiveConfig: config.Config{Org: tc.configOrgName}, StdIO: stdio} - client := mock.BucketsApi{ - GetBucketsExecuteFn: tc.buildBucketLookupFn(t), + + client := mock.NewMockBucketsApi(ctrl) + if tc.registerBucketExpectations != nil { + tc.registerBucketExpectations(t, client) } - err := cli.BucketsList(context.Background(), &client, &tc.params) + err := cli.BucketsList(context.Background(), client, &tc.params) if tc.expectedInErr != "" { require.Error(t, err) require.Contains(t, err.Error(), tc.expectedInErr) - require.Empty(t, stdio.Stdout()) + require.Empty(t, bytesWritten.String()) return } require.NoError(t, err) - outLines := strings.Split(stdio.Stdout(), "\n") + outLines := strings.Split(bytesWritten.String(), "\n") if outLines[len(outLines)-1] == "" { outLines = outLines[:len(outLines)-1] } @@ -531,10 +520,10 @@ func TestBucketsUpdate(t *testing.T) { t.Parallel() var testCases = []struct { - name string - params internal.BucketsUpdateParams - buildBucketUpdateFn func(*testing.T) func(api.ApiPatchBucketsIDRequest) (api.Bucket, error) - expectedStdoutPattern string + name string + params internal.BucketsUpdateParams + registerBucketExpectations func(*testing.T, *mock.MockBucketsApi) + expectedStdoutPattern string }{ { name: "name", @@ -542,20 +531,21 @@ func TestBucketsUpdate(t *testing.T) { ID: "123", Name: "cold-storage", }, - buildBucketUpdateFn: func(t *testing.T) func(api.ApiPatchBucketsIDRequest) (api.Bucket, error) { - return func(req api.ApiPatchBucketsIDRequest) (api.Bucket, error) { - require.Equal(t, "123", req.GetBucketID()) - body := req.GetPatchBucketRequest() - require.Equal(t, "cold-storage", body.GetName()) - require.Empty(t, body.GetDescription()) - require.Empty(t, body.GetRetentionRules()) - - return api.Bucket{ - Id: api.PtrString("123"), - Name: "cold-storage", - OrgID: api.PtrString("456"), - }, nil - } + registerBucketExpectations: func(t *testing.T, bucketsApi *mock.MockBucketsApi) { + bucketsApi.EXPECT().PatchBucketsID(gomock.Any(), gomock.Eq("123")). + Return(api.ApiPatchBucketsIDRequest{ApiService: bucketsApi}.BucketID("123")) + bucketsApi.EXPECT().PatchBucketsIDExecute(tmock.MatchedBy(func(in api.ApiPatchBucketsIDRequest) bool { + body := in.GetPatchBucketRequest() + return assert.Equal(t, "123", in.GetBucketID()) && + assert.NotNil(t, body) && + assert.Equal(t, "cold-storage", body.GetName()) && + assert.Nil(t, body.Description) && + assert.Empty(t, body.GetRetentionRules()) + })).Return(api.Bucket{ + Id: api.PtrString("123"), + Name: "cold-storage", + OrgID: api.PtrString("456"), + }, nil) }, expectedStdoutPattern: "123\\s+cold-storage\\s+infinite\\s+n/a\\s+456", }, @@ -565,21 +555,22 @@ func TestBucketsUpdate(t *testing.T) { ID: "123", Description: "a very useful description", }, - buildBucketUpdateFn: func(t *testing.T) func(api.ApiPatchBucketsIDRequest) (api.Bucket, error) { - return func(req api.ApiPatchBucketsIDRequest) (api.Bucket, error) { - require.Equal(t, "123", req.GetBucketID()) - body := req.GetPatchBucketRequest() - require.Equal(t, "a very useful description", body.GetDescription()) - require.Empty(t, body.GetName()) - require.Empty(t, body.GetRetentionRules()) - - return api.Bucket{ - Id: api.PtrString("123"), - Name: "my-bucket", - Description: api.PtrString("a very useful description"), - OrgID: api.PtrString("456"), - }, nil - } + registerBucketExpectations: func(t *testing.T, bucketsApi *mock.MockBucketsApi) { + bucketsApi.EXPECT().PatchBucketsID(gomock.Any(), gomock.Eq("123")). + Return(api.ApiPatchBucketsIDRequest{ApiService: bucketsApi}.BucketID("123")) + bucketsApi.EXPECT().PatchBucketsIDExecute(tmock.MatchedBy(func(in api.ApiPatchBucketsIDRequest) bool { + body := in.GetPatchBucketRequest() + return assert.Equal(t, "123", in.GetBucketID()) && + assert.NotNil(t, body) && + assert.Equal(t, "a very useful description", body.GetDescription()) && + assert.Nil(t, body.Name) && + assert.Empty(t, body.GetRetentionRules()) + })).Return(api.Bucket{ + Id: api.PtrString("123"), + Name: "my-bucket", + Description: api.PtrString("a very useful description"), + OrgID: api.PtrString("456"), + }, nil) }, expectedStdoutPattern: "123\\s+my-bucket\\s+infinite\\s+n/a\\s+456", }, @@ -589,26 +580,26 @@ func TestBucketsUpdate(t *testing.T) { ID: "123", Retention: "3w", }, - buildBucketUpdateFn: func(t *testing.T) func(api.ApiPatchBucketsIDRequest) (api.Bucket, error) { - return func(req api.ApiPatchBucketsIDRequest) (api.Bucket, error) { - require.Equal(t, "123", req.GetBucketID()) - body := req.GetPatchBucketRequest() - require.Len(t, body.GetRetentionRules(), 1) - rule := body.GetRetentionRules()[0] - require.Nil(t, rule.ShardGroupDurationSeconds) - require.Equal(t, int64(3*7*24*3600), rule.GetEverySeconds()) - require.Nil(t, body.Name) - require.Nil(t, body.Description) - - return api.Bucket{ - Id: api.PtrString("123"), - Name: "my-bucket", - OrgID: api.PtrString("456"), - RetentionRules: []api.RetentionRule{ - {EverySeconds: rule.GetEverySeconds()}, - }, - }, nil - } + registerBucketExpectations: func(t *testing.T, bucketsApi *mock.MockBucketsApi) { + bucketsApi.EXPECT().PatchBucketsID(gomock.Any(), gomock.Eq("123")). + Return(api.ApiPatchBucketsIDRequest{ApiService: bucketsApi}.BucketID("123")) + bucketsApi.EXPECT().PatchBucketsIDExecute(tmock.MatchedBy(func(in api.ApiPatchBucketsIDRequest) bool { + body := in.GetPatchBucketRequest() + return assert.Equal(t, "123", in.GetBucketID()) && + assert.NotNil(t, body) && + assert.Nil(t, body.Name) && + assert.Nil(t, body.Description) && + assert.Len(t, body.GetRetentionRules(), 1) && + assert.Nil(t, body.GetRetentionRules()[0].ShardGroupDurationSeconds) && + assert.Equal(t, int64(3*7*24*3600), *body.GetRetentionRules()[0].EverySeconds) + })).Return(api.Bucket{ + Id: api.PtrString("123"), + Name: "my-bucket", + OrgID: api.PtrString("456"), + RetentionRules: []api.RetentionRule{ + {EverySeconds: int64(3 * 7 * 24 * 3600)}, + }, + }, nil) }, expectedStdoutPattern: "123\\s+my-bucket\\s+504h0m0s\\s+n/a\\s+456", }, @@ -618,26 +609,26 @@ func TestBucketsUpdate(t *testing.T) { ID: "123", ShardGroupDuration: "10h30m", }, - buildBucketUpdateFn: func(t *testing.T) func(api.ApiPatchBucketsIDRequest) (api.Bucket, error) { - return func(req api.ApiPatchBucketsIDRequest) (api.Bucket, error) { - require.Equal(t, "123", req.GetBucketID()) - body := req.GetPatchBucketRequest() - require.Len(t, body.GetRetentionRules(), 1) - rule := body.GetRetentionRules()[0] - require.Nil(t, rule.EverySeconds) - require.Equal(t, int64(10*3600+30*60), rule.GetShardGroupDurationSeconds()) - require.Nil(t, body.Name) - require.Nil(t, body.Description) - - return api.Bucket{ - Id: api.PtrString("123"), - Name: "my-bucket", - OrgID: api.PtrString("456"), - RetentionRules: []api.RetentionRule{ - {ShardGroupDurationSeconds: rule.ShardGroupDurationSeconds}, - }, - }, nil - } + registerBucketExpectations: func(t *testing.T, bucketsApi *mock.MockBucketsApi) { + bucketsApi.EXPECT().PatchBucketsID(gomock.Any(), gomock.Eq("123")). + Return(api.ApiPatchBucketsIDRequest{ApiService: bucketsApi}.BucketID("123")) + bucketsApi.EXPECT().PatchBucketsIDExecute(tmock.MatchedBy(func(in api.ApiPatchBucketsIDRequest) bool { + body := in.GetPatchBucketRequest() + return assert.Equal(t, "123", in.GetBucketID()) && + assert.NotNil(t, body) && + assert.Nil(t, body.Name) && + assert.Nil(t, body.Description) && + assert.Len(t, body.GetRetentionRules(), 1) && + assert.Nil(t, body.GetRetentionRules()[0].EverySeconds) && + assert.Equal(t, int64(10*3600+30*60), *body.GetRetentionRules()[0].ShardGroupDurationSeconds) + })).Return(api.Bucket{ + Id: api.PtrString("123"), + Name: "my-bucket", + OrgID: api.PtrString("456"), + RetentionRules: []api.RetentionRule{ + {ShardGroupDurationSeconds: api.PtrInt64(10*3600 + 30*60)}, + }, + }, nil) }, expectedStdoutPattern: "123\\s+my-bucket\\s+infinite\\s+10h30m0s\\s+456", }, @@ -648,15 +639,19 @@ func TestBucketsUpdate(t *testing.T) { t.Run(tc.name, func(t *testing.T) { t.Parallel() - stdio := mock.NewMockStdio(nil, false) + ctrl := gomock.NewController(t) + stdio := mock.NewMockStdIO(ctrl) + writtenBytes := bytes.Buffer{} + stdio.EXPECT().Write(gomock.Any()).DoAndReturn(writtenBytes.Write).AnyTimes() cli := internal.CLI{StdIO: stdio} - client := mock.BucketsApi{ - PatchBucketsIDExecuteFn: tc.buildBucketUpdateFn(t), + client := mock.NewMockBucketsApi(ctrl) + if tc.registerBucketExpectations != nil { + tc.registerBucketExpectations(t, client) } - err := cli.BucketsUpdate(context.Background(), &client, &tc.params) + err := cli.BucketsUpdate(context.Background(), client, &tc.params) require.NoError(t, err) - outLines := strings.Split(stdio.Stdout(), "\n") + outLines := strings.Split(writtenBytes.String(), "\n") if outLines[len(outLines)-1] == "" { outLines = outLines[:len(outLines)-1] } @@ -671,13 +666,12 @@ func TestBucketsDelete(t *testing.T) { t.Parallel() var testCases = []struct { - name string - configOrgName string - params internal.BucketsDeleteParams - buildBucketsLookupFn func(*testing.T) func(api.ApiGetBucketsRequest) (api.Buckets, error) - buildBucketDeleteFn func(*testing.T) func(api.ApiDeleteBucketsIDRequest) error - expectedStdoutPattern string - expectedInErr string + name string + configOrgName string + params internal.BucketsDeleteParams + registerBucketExpectations func(*testing.T, *mock.MockBucketsApi) + expectedStdoutPattern string + expectedInErr string }{ { name: "by ID", @@ -685,32 +679,31 @@ func TestBucketsDelete(t *testing.T) { params: internal.BucketsDeleteParams{ ID: "123", }, - buildBucketsLookupFn: func(t *testing.T) func(api.ApiGetBucketsRequest) (api.Buckets, error) { - return func(req api.ApiGetBucketsRequest) (api.Buckets, error) { - require.Equal(t, "123", *req.GetId()) - require.Nil(t, req.GetName()) - require.Nil(t, req.GetOrgID()) - require.Nil(t, req.GetOrg()) - - return api.Buckets{ - Buckets: &[]api.Bucket{ - { - Id: api.PtrString("123"), - Name: "my-bucket", - OrgID: api.PtrString("456"), - RetentionRules: []api.RetentionRule{ - {EverySeconds: 3600}, - }, + registerBucketExpectations: func(t *testing.T, bucketsApi *mock.MockBucketsApi) { + bucketsApi.EXPECT().GetBuckets(gomock.Any()).Return(api.ApiGetBucketsRequest{ApiService: bucketsApi}) + bucketsApi.EXPECT().GetBucketsExecute(tmock.MatchedBy(func(in api.ApiGetBucketsRequest) bool { + return assert.Equal(t, "123", *in.GetId()) && + assert.Nil(t, in.GetName()) && + assert.Nil(t, in.GetOrgID()) && + assert.Nil(t, in.GetOrg()) + })).Return(api.Buckets{ + Buckets: &[]api.Bucket{ + { + Id: api.PtrString("123"), + Name: "my-bucket", + OrgID: api.PtrString("456"), + RetentionRules: []api.RetentionRule{ + {EverySeconds: 3600}, }, }, - }, nil - } - }, - buildBucketDeleteFn: func(t *testing.T) func(api.ApiDeleteBucketsIDRequest) error { - return func(req api.ApiDeleteBucketsIDRequest) error { - assert.Equal(t, "123", req.GetBucketID()) - return nil - } + }, + }, nil) + + bucketsApi.EXPECT().DeleteBucketsID(gomock.Any(), gomock.Eq("123")). + Return(api.ApiDeleteBucketsIDRequest{ApiService: bucketsApi}.BucketID("123")) + bucketsApi.EXPECT().DeleteBucketsIDExecute(tmock.MatchedBy(func(in api.ApiDeleteBucketsIDRequest) bool { + return assert.Equal(t, "123", in.GetBucketID()) + })).Return(nil) }, expectedStdoutPattern: "123\\s+my-bucket\\s+1h0m0s\\s+n/a\\s+456\\s+implicit", }, @@ -721,32 +714,31 @@ func TestBucketsDelete(t *testing.T) { Name: "my-bucket", OrgID: "456", }, - buildBucketsLookupFn: func(t *testing.T) func(api.ApiGetBucketsRequest) (api.Buckets, error) { - return func(req api.ApiGetBucketsRequest) (api.Buckets, error) { - require.Equal(t, "my-bucket", *req.GetName()) - require.Equal(t, "456", *req.GetOrgID()) - require.Nil(t, req.GetId()) - require.Nil(t, req.GetOrg()) - - return api.Buckets{ - Buckets: &[]api.Bucket{ - { - Id: api.PtrString("123"), - Name: "my-bucket", - OrgID: api.PtrString("456"), - RetentionRules: []api.RetentionRule{ - {EverySeconds: 3600}, - }, + registerBucketExpectations: func(t *testing.T, bucketsApi *mock.MockBucketsApi) { + bucketsApi.EXPECT().GetBuckets(gomock.Any()).Return(api.ApiGetBucketsRequest{ApiService: bucketsApi}) + bucketsApi.EXPECT().GetBucketsExecute(tmock.MatchedBy(func(in api.ApiGetBucketsRequest) bool { + return assert.Nil(t, in.GetId()) && + assert.Equal(t, "my-bucket", *in.GetName()) && + assert.Equal(t, "456", *in.GetOrgID()) && + assert.Nil(t, in.GetOrg()) + })).Return(api.Buckets{ + Buckets: &[]api.Bucket{ + { + Id: api.PtrString("123"), + Name: "my-bucket", + OrgID: api.PtrString("456"), + RetentionRules: []api.RetentionRule{ + {EverySeconds: 3600}, }, }, - }, nil - } - }, - buildBucketDeleteFn: func(t *testing.T) func(api.ApiDeleteBucketsIDRequest) error { - return func(req api.ApiDeleteBucketsIDRequest) error { - assert.Equal(t, "123", req.GetBucketID()) - return nil - } + }, + }, nil) + + bucketsApi.EXPECT().DeleteBucketsID(gomock.Any(), gomock.Eq("123")). + Return(api.ApiDeleteBucketsIDRequest{ApiService: bucketsApi}.BucketID("123")) + bucketsApi.EXPECT().DeleteBucketsIDExecute(tmock.MatchedBy(func(in api.ApiDeleteBucketsIDRequest) bool { + return assert.Equal(t, "123", in.GetBucketID()) + })).Return(nil) }, expectedStdoutPattern: "123\\s+my-bucket\\s+1h0m0s\\s+n/a\\s+456\\s+implicit", }, @@ -757,32 +749,31 @@ func TestBucketsDelete(t *testing.T) { Name: "my-bucket", OrgName: "my-org", }, - buildBucketsLookupFn: func(t *testing.T) func(api.ApiGetBucketsRequest) (api.Buckets, error) { - return func(req api.ApiGetBucketsRequest) (api.Buckets, error) { - require.Equal(t, "my-bucket", *req.GetName()) - require.Equal(t, "my-org", *req.GetOrg()) - require.Nil(t, req.GetId()) - require.Nil(t, req.GetOrgID()) - - return api.Buckets{ - Buckets: &[]api.Bucket{ - { - Id: api.PtrString("123"), - Name: "my-bucket", - OrgID: api.PtrString("456"), - RetentionRules: []api.RetentionRule{ - {EverySeconds: 3600}, - }, + registerBucketExpectations: func(t *testing.T, bucketsApi *mock.MockBucketsApi) { + bucketsApi.EXPECT().GetBuckets(gomock.Any()).Return(api.ApiGetBucketsRequest{ApiService: bucketsApi}) + bucketsApi.EXPECT().GetBucketsExecute(tmock.MatchedBy(func(in api.ApiGetBucketsRequest) bool { + return assert.Nil(t, in.GetId()) && + assert.Equal(t, "my-bucket", *in.GetName()) && + assert.Nil(t, in.GetOrgID()) && + assert.Equal(t, "my-org", *in.GetOrg()) + })).Return(api.Buckets{ + Buckets: &[]api.Bucket{ + { + Id: api.PtrString("123"), + Name: "my-bucket", + OrgID: api.PtrString("456"), + RetentionRules: []api.RetentionRule{ + {EverySeconds: 3600}, }, }, - }, nil - } - }, - buildBucketDeleteFn: func(t *testing.T) func(api.ApiDeleteBucketsIDRequest) error { - return func(req api.ApiDeleteBucketsIDRequest) error { - assert.Equal(t, "123", req.GetBucketID()) - return nil - } + }, + }, nil) + + bucketsApi.EXPECT().DeleteBucketsID(gomock.Any(), gomock.Eq("123")). + Return(api.ApiDeleteBucketsIDRequest{ApiService: bucketsApi}.BucketID("123")) + bucketsApi.EXPECT().DeleteBucketsIDExecute(tmock.MatchedBy(func(in api.ApiDeleteBucketsIDRequest) bool { + return assert.Equal(t, "123", in.GetBucketID()) + })).Return(nil) }, expectedStdoutPattern: "123\\s+my-bucket\\s+1h0m0s\\s+n/a\\s+456\\s+implicit", }, @@ -792,32 +783,31 @@ func TestBucketsDelete(t *testing.T) { params: internal.BucketsDeleteParams{ Name: "my-bucket", }, - buildBucketsLookupFn: func(t *testing.T) func(api.ApiGetBucketsRequest) (api.Buckets, error) { - return func(req api.ApiGetBucketsRequest) (api.Buckets, error) { - require.Equal(t, "my-bucket", *req.GetName()) - require.Equal(t, "my-default-org", *req.GetOrg()) - require.Nil(t, req.GetId()) - require.Nil(t, req.GetOrgID()) - - return api.Buckets{ - Buckets: &[]api.Bucket{ - { - Id: api.PtrString("123"), - Name: "my-bucket", - OrgID: api.PtrString("456"), - RetentionRules: []api.RetentionRule{ - {EverySeconds: 3600}, - }, + registerBucketExpectations: func(t *testing.T, bucketsApi *mock.MockBucketsApi) { + bucketsApi.EXPECT().GetBuckets(gomock.Any()).Return(api.ApiGetBucketsRequest{ApiService: bucketsApi}) + bucketsApi.EXPECT().GetBucketsExecute(tmock.MatchedBy(func(in api.ApiGetBucketsRequest) bool { + return assert.Nil(t, in.GetId()) && + assert.Equal(t, "my-bucket", *in.GetName()) && + assert.Nil(t, in.GetOrgID()) && + assert.Equal(t, "my-default-org", *in.GetOrg()) + })).Return(api.Buckets{ + Buckets: &[]api.Bucket{ + { + Id: api.PtrString("123"), + Name: "my-bucket", + OrgID: api.PtrString("456"), + RetentionRules: []api.RetentionRule{ + {EverySeconds: 3600}, }, }, - }, nil - } - }, - buildBucketDeleteFn: func(t *testing.T) func(api.ApiDeleteBucketsIDRequest) error { - return func(req api.ApiDeleteBucketsIDRequest) error { - assert.Equal(t, "123", req.GetBucketID()) - return nil - } + }, + }, nil) + + bucketsApi.EXPECT().DeleteBucketsID(gomock.Any(), gomock.Eq("123")). + Return(api.ApiDeleteBucketsIDRequest{ApiService: bucketsApi}.BucketID("123")) + bucketsApi.EXPECT().DeleteBucketsIDExecute(tmock.MatchedBy(func(in api.ApiDeleteBucketsIDRequest) bool { + return assert.Equal(t, "123", in.GetBucketID()) + })).Return(nil) }, expectedStdoutPattern: "123\\s+my-bucket\\s+1h0m0s\\s+n/a\\s+456\\s+implicit", }, @@ -826,16 +816,6 @@ func TestBucketsDelete(t *testing.T) { params: internal.BucketsDeleteParams{ Name: "my-bucket", }, - buildBucketsLookupFn: func(t *testing.T) func(api.ApiGetBucketsRequest) (api.Buckets, error) { - return func(api.ApiGetBucketsRequest) (api.Buckets, error) { - return api.Buckets{}, errors.New("shouldn't be called") - } - }, - buildBucketDeleteFn: func(t *testing.T) func(api.ApiDeleteBucketsIDRequest) error { - return func(api.ApiDeleteBucketsIDRequest) error { - return errors.New("shouldn't be called") - } - }, expectedInErr: "must specify org ID or org name", }, { @@ -843,15 +823,9 @@ func TestBucketsDelete(t *testing.T) { params: internal.BucketsDeleteParams{ ID: "123", }, - buildBucketsLookupFn: func(t *testing.T) func(api.ApiGetBucketsRequest) (api.Buckets, error) { - return func(api.ApiGetBucketsRequest) (api.Buckets, error) { - return api.Buckets{}, nil - } - }, - buildBucketDeleteFn: func(t *testing.T) func(api.ApiDeleteBucketsIDRequest) error { - return func(api.ApiDeleteBucketsIDRequest) error { - return errors.New("shouldn't be called") - } + registerBucketExpectations: func(t *testing.T, bucketsApi *mock.MockBucketsApi) { + bucketsApi.EXPECT().GetBuckets(gomock.Any()).Return(api.ApiGetBucketsRequest{ApiService: bucketsApi}) + bucketsApi.EXPECT().GetBucketsExecute(gomock.Any()).Return(api.Buckets{}, nil) }, expectedInErr: "not found", }, @@ -862,22 +836,25 @@ func TestBucketsDelete(t *testing.T) { t.Run(tc.name, func(t *testing.T) { t.Parallel() - stdio := mock.NewMockStdio(nil, false) + ctrl := gomock.NewController(t) + stdio := mock.NewMockStdIO(ctrl) + writtenBytes := bytes.Buffer{} + stdio.EXPECT().Write(gomock.Any()).DoAndReturn(writtenBytes.Write).AnyTimes() cli := internal.CLI{ActiveConfig: config.Config{Org: tc.configOrgName}, StdIO: stdio} - client := mock.BucketsApi{ - GetBucketsExecuteFn: tc.buildBucketsLookupFn(t), - DeleteBucketsIDExecuteFn: tc.buildBucketDeleteFn(t), + client := mock.NewMockBucketsApi(ctrl) + if tc.registerBucketExpectations != nil { + tc.registerBucketExpectations(t, client) } - err := cli.BucketsDelete(context.Background(), &client, &tc.params) + err := cli.BucketsDelete(context.Background(), client, &tc.params) if tc.expectedInErr != "" { require.Error(t, err) require.Contains(t, err.Error(), tc.expectedInErr) - require.Empty(t, stdio.Stdout()) + require.Empty(t, writtenBytes.String()) return } require.NoError(t, err) - outLines := strings.Split(stdio.Stdout(), "\n") + outLines := strings.Split(writtenBytes.String(), "\n") if outLines[len(outLines)-1] == "" { outLines = outLines[:len(outLines)-1] } diff --git a/internal/cmd/bucket_schema/client_test.go b/internal/cmd/bucket_schema/client_test.go index 2b207d7..0a6ae9f 100644 --- a/internal/cmd/bucket_schema/client_test.go +++ b/internal/cmd/bucket_schema/client_test.go @@ -5,7 +5,6 @@ import ( "context" "os" "path/filepath" - "regexp" "strings" "testing" "time" @@ -21,28 +20,22 @@ import ( "github.com/stretchr/testify/require" ) -func matchLines(t *testing.T, lines []string, mockIO *mock.Stdio) { - if len(lines) > 0 { - outLines := strings.Split(mockIO.Stdout(), "\n") - expLines := make([]*regexp.Regexp, 0, len(lines)) - for _, expLine := range lines { - expLines = append(expLines, regexp.MustCompile(expLine)) - } - - for _, outLine := range outLines { - if outLine == "" { - continue - } - var any bool - for _, expLine := range expLines { - any = any || expLine.MatchString(outLine) - } - assert.True(t, any, "line %q was unexpected", outLine) +func matchLines(t *testing.T, expectedLines []string, lines []string) { + var nonEmptyLines []string + for _, l := range lines { + if l != "" { + nonEmptyLines = append(nonEmptyLines, l) } } + require.Equal(t, len(expectedLines), len(nonEmptyLines)) + for i, expected := range expectedLines { + require.Regexp(t, expected, nonEmptyLines[i]) + } } func TestClient_Create(t *testing.T) { + t.Parallel() + var ( orgID = "dead" bucketID = "f00d" @@ -56,7 +49,7 @@ func TestClient_Create(t *testing.T) { cli *internal.CLI params bucket_schema.CreateParams cols []api.MeasurementSchemaColumn - stdio *mock.Stdio + stdio *mock.MockStdIO } type optFn func(t *testing.T, a *setupArgs) @@ -186,7 +179,6 @@ func TestClient_Create(t *testing.T) { name: "bucket not found", opts: opts( withArgs(args{OrgName: "my-org", BucketName: "my-bucket", ColumnsFile: "columns.csv"}), - expGetBuckets(), ), expErr: `bucket "my-bucket" not found`, @@ -196,7 +188,6 @@ func TestClient_Create(t *testing.T) { opts: opts( withArgs(args{OrgName: "my-org", BucketName: "my-bucket", Name: "cpu", ColumnsFile: "columns.csv"}), withCols("columns.csv"), - expGetBuckets("my-bucket"), expCreate(), ), @@ -210,7 +201,6 @@ func TestClient_Create(t *testing.T) { opts: opts( withArgs(args{OrgName: "my-org", BucketName: "my-bucket", Name: "cpu", ColumnsFile: "columns.json"}), withCols("columns.csv"), - expGetBuckets("my-bucket"), expCreate(), ), @@ -224,7 +214,6 @@ func TestClient_Create(t *testing.T) { opts: opts( withArgs(args{OrgName: "my-org", BucketName: "my-bucket", Name: "cpu", ColumnsFile: "columns.ndjson"}), withCols("columns.csv"), - expGetBuckets("my-bucket"), expCreate(), ), @@ -238,21 +227,28 @@ func TestClient_Create(t *testing.T) { opts: opts( withArgs(args{OrgName: "my-org", BucketName: "my-bucket", Name: "cpu", ColumnsFile: "columns.csv", ExtendedOutput: true}), withCols("columns.csv"), - expGetBuckets("my-bucket"), expCreate(), ), expLines: lines( `^ID\s+Measurement Name\s+Column Name\s+Column Type\s+Column Data Type\s+Bucket ID$`, - `^1010\s+cpu\s+\w+\s+(timestamp|tag|field)\s+(|float)\s+f00d$`, + `^1010\s+cpu\s+time\s+timestamp\s+f00d$`, + `^1010\s+cpu\s+host\s+tag\s+f00d$`, + `^1010\s+cpu\s+usage_user\s+field\s+float\s+f00d$`, ), }, } for _, tc := range cases { + tc := tc t.Run(tc.name, func(t *testing.T) { + t.Parallel() + ctrl := gomock.NewController(t) - mockIO := mock.NewMockStdio(nil, true) + mockIO := mock.NewMockStdIO(ctrl) + writtenBytes := bytes.Buffer{} + mockIO.EXPECT().Write(gomock.Any()).DoAndReturn(writtenBytes.Write).AnyTimes() + args := &setupArgs{ buckets: mock.NewMockBucketsApi(ctrl), schemas: mock.NewMockBucketSchemasApi(ctrl), @@ -276,13 +272,15 @@ func TestClient_Create(t *testing.T) { assert.EqualError(t, err, tc.expErr) } else { require.NoError(t, err) - matchLines(t, tc.expLines, mockIO) + matchLines(t, tc.expLines, strings.Split(writtenBytes.String(), "\n")) } }) } } func TestClient_Update(t *testing.T) { + t.Parallel() + var ( orgID = "dead" bucketID = "f00d" @@ -297,7 +295,7 @@ func TestClient_Update(t *testing.T) { cli *internal.CLI params bucket_schema.UpdateParams cols []api.MeasurementSchemaColumn - stdio *mock.Stdio + stdio *mock.MockStdIO } type optFn func(t *testing.T, a *setupArgs) @@ -485,22 +483,30 @@ func TestClient_Update(t *testing.T) { opts: opts( withArgs(args{OrgName: "my-org", BucketName: "my-bucket", Name: "cpu", ColumnsFile: "columns.csv", ExtendedOutput: true}), withCols("columns.csv"), - expGetBuckets("my-bucket"), expGetMeasurementSchema(), expUpdate(), ), expLines: lines( `^ID\s+Measurement Name\s+Column Name\s+Column Type\s+Column Data Type\s+Bucket ID$`, - `^1010\s+cpu\s+\w+\s+(timestamp|tag|field)\s+(|float)\s+f00d$`, + `^1010\s+cpu\s+time\s+timestamp\s+f00d$`, + `^1010\s+cpu\s+host\s+tag\s+f00d$`, + `^1010\s+cpu\s+usage_user\s+field\s+float\s+f00d$`, + ), }, } for _, tc := range cases { + tc := tc t.Run(tc.name, func(t *testing.T) { + t.Parallel() + ctrl := gomock.NewController(t) - mockIO := mock.NewMockStdio(nil, true) + mockIO := mock.NewMockStdIO(ctrl) + writtenBytes := bytes.Buffer{} + mockIO.EXPECT().Write(gomock.Any()).DoAndReturn(writtenBytes.Write).AnyTimes() + args := &setupArgs{ buckets: mock.NewMockBucketsApi(ctrl), schemas: mock.NewMockBucketSchemasApi(ctrl), @@ -524,13 +530,15 @@ func TestClient_Update(t *testing.T) { assert.EqualError(t, err, tc.expErr) } else { require.NoError(t, err) - matchLines(t, tc.expLines, mockIO) + matchLines(t, tc.expLines, strings.Split(writtenBytes.String(), "\n")) } }) } } func TestClient_List(t *testing.T) { + t.Parallel() + var ( orgID = "dead" bucketID = "f00d" @@ -545,7 +553,7 @@ func TestClient_List(t *testing.T) { cli *internal.CLI params bucket_schema.ListParams cols []api.MeasurementSchemaColumn - stdio *mock.Stdio + stdio *mock.MockStdIO } type optFn func(t *testing.T, a *setupArgs) @@ -676,11 +684,10 @@ func TestClient_List(t *testing.T) { expErr: `bucket "my-bucket" not found`, }, { - name: "update succeeds", + name: "list succeeds", opts: opts( withArgs(args{OrgName: "my-org", BucketName: "my-bucket", Name: "cpu"}), withCols("columns.csv"), - expGetBuckets("my-bucket"), expGetMeasurementSchemas(), ), @@ -690,25 +697,32 @@ func TestClient_List(t *testing.T) { ), }, { - name: "update succeeds extended output", + name: "list succeeds extended output", opts: opts( withArgs(args{OrgName: "my-org", BucketName: "my-bucket", Name: "cpu", ExtendedOutput: true}), withCols("columns.csv"), - expGetBuckets("my-bucket"), expGetMeasurementSchemas(), ), expLines: lines( `^ID\s+Measurement Name\s+Column Name\s+Column Type\s+Column Data Type\s+Bucket ID$`, - `^1010\s+cpu\s+\w+\s+(timestamp|tag|field)\s+(|float)\s+f00d$`, + `^1010\s+cpu\s+time\s+timestamp\s+f00d$`, + `^1010\s+cpu\s+host\s+tag\s+f00d$`, + `^1010\s+cpu\s+usage_user\s+field\s+float\s+f00d$`, ), }, } for _, tc := range cases { + tc := tc t.Run(tc.name, func(t *testing.T) { + t.Parallel() + ctrl := gomock.NewController(t) - mockIO := mock.NewMockStdio(nil, true) + mockIO := mock.NewMockStdIO(ctrl) + writtenBytes := bytes.Buffer{} + mockIO.EXPECT().Write(gomock.Any()).DoAndReturn(writtenBytes.Write).AnyTimes() + args := &setupArgs{ buckets: mock.NewMockBucketsApi(ctrl), schemas: mock.NewMockBucketSchemasApi(ctrl), @@ -732,7 +746,7 @@ func TestClient_List(t *testing.T) { assert.EqualError(t, err, tc.expErr) } else { require.NoError(t, err) - matchLines(t, tc.expLines, mockIO) + matchLines(t, tc.expLines, strings.Split(writtenBytes.String(), "\n")) } }) } diff --git a/internal/cmd/bucket_schema/csv.go b/internal/cmd/bucket_schema/csv.go index 4df84c4..32b481a 100644 --- a/internal/cmd/bucket_schema/csv.go +++ b/internal/cmd/bucket_schema/csv.go @@ -14,9 +14,12 @@ type csvColumn struct { DataType *api.ColumnDataType `csv:"data_type,omitempty"` } +func init() { + gocsv.FailIfUnmatchedStructTags = true +} + func decodeCSV(r io.Reader) ([]api.MeasurementSchemaColumn, error) { var cols []csvColumn - gocsv.FailIfUnmatchedStructTags = true err := gocsv.Unmarshal(r, &cols) if err != nil { return nil, fmt.Errorf("failed to decode CSV: %w", err) diff --git a/internal/mock/README.md b/internal/mock/README.md new file mode 100644 index 0000000..62e873a --- /dev/null +++ b/internal/mock/README.md @@ -0,0 +1,7 @@ +# Mocks + +The files in this module are generated via `mockgen` for use with [`gomock`](https://github.com/golang/mock). + +To add a new mock: +1. Add a line to `gen.go` in this module +1. Run `make mock` from the project root diff --git a/internal/mock/api_buckets.go b/internal/mock/api_buckets.go deleted file mode 100644 index 50dfc70..0000000 --- a/internal/mock/api_buckets.go +++ /dev/null @@ -1,57 +0,0 @@ -package mock - -import ( - "context" - - "github.com/influxdata/influx-cli/v2/internal/api" -) - -var _ api.BucketsApi = (*BucketsApi)(nil) - -type BucketsApi struct { - DeleteBucketsIDExecuteFn func(api.ApiDeleteBucketsIDRequest) error - GetBucketsExecuteFn func(api.ApiGetBucketsRequest) (api.Buckets, error) - GetBucketsIDExecuteFn func(api.ApiGetBucketsIDRequest) (api.Bucket, error) - PatchBucketsIDExecuteFn func(api.ApiPatchBucketsIDRequest) (api.Bucket, error) - PostBucketsExecuteFn func(api.ApiPostBucketsRequest) (api.Bucket, error) -} - -func (b *BucketsApi) DeleteBucketsID(_ context.Context, bucketID string) api.ApiDeleteBucketsIDRequest { - return api.ApiDeleteBucketsIDRequest{ApiService: b}.BucketID(bucketID) -} - -func (b *BucketsApi) DeleteBucketsIDExecute(r api.ApiDeleteBucketsIDRequest) error { - return b.DeleteBucketsIDExecuteFn(r) -} - -func (b *BucketsApi) GetBuckets(context.Context) api.ApiGetBucketsRequest { - return api.ApiGetBucketsRequest{ApiService: b} -} - -func (b *BucketsApi) GetBucketsExecute(r api.ApiGetBucketsRequest) (api.Buckets, error) { - return b.GetBucketsExecuteFn(r) -} - -func (b *BucketsApi) GetBucketsID(_ context.Context, bucketID string) api.ApiGetBucketsIDRequest { - return api.ApiGetBucketsIDRequest{ApiService: b}.BucketID(bucketID) -} - -func (b *BucketsApi) GetBucketsIDExecute(r api.ApiGetBucketsIDRequest) (api.Bucket, error) { - return b.GetBucketsIDExecuteFn(r) -} - -func (b *BucketsApi) PatchBucketsID(_ context.Context, bucketID string) api.ApiPatchBucketsIDRequest { - return api.ApiPatchBucketsIDRequest{ApiService: b}.BucketID(bucketID) -} - -func (b *BucketsApi) PatchBucketsIDExecute(r api.ApiPatchBucketsIDRequest) (api.Bucket, error) { - return b.PatchBucketsIDExecuteFn(r) -} - -func (b *BucketsApi) PostBuckets(context.Context) api.ApiPostBucketsRequest { - return api.ApiPostBucketsRequest{ApiService: b} -} - -func (b *BucketsApi) PostBucketsExecute(r api.ApiPostBucketsRequest) (api.Bucket, error) { - return b.PostBucketsExecuteFn(r) -} diff --git a/internal/mock/api_health.gen.go b/internal/mock/api_health.gen.go new file mode 100644 index 0000000..b801171 --- /dev/null +++ b/internal/mock/api_health.gen.go @@ -0,0 +1,65 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/influxdata/influx-cli/v2/internal/api (interfaces: HealthApi) + +// Package mock is a generated GoMock package. +package mock + +import ( + context "context" + reflect "reflect" + + gomock "github.com/golang/mock/gomock" + api "github.com/influxdata/influx-cli/v2/internal/api" +) + +// MockHealthApi is a mock of HealthApi interface. +type MockHealthApi struct { + ctrl *gomock.Controller + recorder *MockHealthApiMockRecorder +} + +// MockHealthApiMockRecorder is the mock recorder for MockHealthApi. +type MockHealthApiMockRecorder struct { + mock *MockHealthApi +} + +// NewMockHealthApi creates a new mock instance. +func NewMockHealthApi(ctrl *gomock.Controller) *MockHealthApi { + mock := &MockHealthApi{ctrl: ctrl} + mock.recorder = &MockHealthApiMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockHealthApi) EXPECT() *MockHealthApiMockRecorder { + return m.recorder +} + +// GetHealth mocks base method. +func (m *MockHealthApi) GetHealth(arg0 context.Context) api.ApiGetHealthRequest { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetHealth", arg0) + ret0, _ := ret[0].(api.ApiGetHealthRequest) + return ret0 +} + +// GetHealth indicates an expected call of GetHealth. +func (mr *MockHealthApiMockRecorder) GetHealth(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetHealth", reflect.TypeOf((*MockHealthApi)(nil).GetHealth), arg0) +} + +// GetHealthExecute mocks base method. +func (m *MockHealthApi) GetHealthExecute(arg0 api.ApiGetHealthRequest) (api.HealthCheck, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetHealthExecute", arg0) + ret0, _ := ret[0].(api.HealthCheck) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetHealthExecute indicates an expected call of GetHealthExecute. +func (mr *MockHealthApiMockRecorder) GetHealthExecute(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetHealthExecute", reflect.TypeOf((*MockHealthApi)(nil).GetHealthExecute), arg0) +} diff --git a/internal/mock/api_health.go b/internal/mock/api_health.go deleted file mode 100644 index 9482bc0..0000000 --- a/internal/mock/api_health.go +++ /dev/null @@ -1,23 +0,0 @@ -package mock - -import ( - "context" - - "github.com/influxdata/influx-cli/v2/internal/api" -) - -var _ api.HealthApi = (*HealthApi)(nil) - -type HealthApi struct { - GetHealthExecuteFn func(api.ApiGetHealthRequest) (api.HealthCheck, error) -} - -func (p *HealthApi) GetHealth(context.Context) api.ApiGetHealthRequest { - return api.ApiGetHealthRequest{ - ApiService: p, - } -} - -func (p *HealthApi) GetHealthExecute(req api.ApiGetHealthRequest) (api.HealthCheck, error) { - return p.GetHealthExecuteFn(req) -} diff --git a/internal/mock/api_organizations.gen.go b/internal/mock/api_organizations.gen.go new file mode 100644 index 0000000..0064fab --- /dev/null +++ b/internal/mock/api_organizations.gen.go @@ -0,0 +1,94 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/influxdata/influx-cli/v2/internal/api (interfaces: OrganizationsApi) + +// Package mock is a generated GoMock package. +package mock + +import ( + context "context" + reflect "reflect" + + gomock "github.com/golang/mock/gomock" + api "github.com/influxdata/influx-cli/v2/internal/api" +) + +// MockOrganizationsApi is a mock of OrganizationsApi interface. +type MockOrganizationsApi struct { + ctrl *gomock.Controller + recorder *MockOrganizationsApiMockRecorder +} + +// MockOrganizationsApiMockRecorder is the mock recorder for MockOrganizationsApi. +type MockOrganizationsApiMockRecorder struct { + mock *MockOrganizationsApi +} + +// NewMockOrganizationsApi creates a new mock instance. +func NewMockOrganizationsApi(ctrl *gomock.Controller) *MockOrganizationsApi { + mock := &MockOrganizationsApi{ctrl: ctrl} + mock.recorder = &MockOrganizationsApiMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockOrganizationsApi) EXPECT() *MockOrganizationsApiMockRecorder { + return m.recorder +} + +// GetOrgs mocks base method. +func (m *MockOrganizationsApi) GetOrgs(arg0 context.Context) api.ApiGetOrgsRequest { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetOrgs", arg0) + ret0, _ := ret[0].(api.ApiGetOrgsRequest) + return ret0 +} + +// GetOrgs indicates an expected call of GetOrgs. +func (mr *MockOrganizationsApiMockRecorder) GetOrgs(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetOrgs", reflect.TypeOf((*MockOrganizationsApi)(nil).GetOrgs), arg0) +} + +// GetOrgsExecute mocks base method. +func (m *MockOrganizationsApi) GetOrgsExecute(arg0 api.ApiGetOrgsRequest) (api.Organizations, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetOrgsExecute", arg0) + ret0, _ := ret[0].(api.Organizations) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetOrgsExecute indicates an expected call of GetOrgsExecute. +func (mr *MockOrganizationsApiMockRecorder) GetOrgsExecute(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetOrgsExecute", reflect.TypeOf((*MockOrganizationsApi)(nil).GetOrgsExecute), arg0) +} + +// PostOrgs mocks base method. +func (m *MockOrganizationsApi) PostOrgs(arg0 context.Context) api.ApiPostOrgsRequest { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "PostOrgs", arg0) + ret0, _ := ret[0].(api.ApiPostOrgsRequest) + return ret0 +} + +// PostOrgs indicates an expected call of PostOrgs. +func (mr *MockOrganizationsApiMockRecorder) PostOrgs(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PostOrgs", reflect.TypeOf((*MockOrganizationsApi)(nil).PostOrgs), arg0) +} + +// PostOrgsExecute mocks base method. +func (m *MockOrganizationsApi) PostOrgsExecute(arg0 api.ApiPostOrgsRequest) (api.Organization, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "PostOrgsExecute", arg0) + ret0, _ := ret[0].(api.Organization) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// PostOrgsExecute indicates an expected call of PostOrgsExecute. +func (mr *MockOrganizationsApiMockRecorder) PostOrgsExecute(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PostOrgsExecute", reflect.TypeOf((*MockOrganizationsApi)(nil).PostOrgsExecute), arg0) +} diff --git a/internal/mock/api_organizations.go b/internal/mock/api_organizations.go deleted file mode 100644 index db6c859..0000000 --- a/internal/mock/api_organizations.go +++ /dev/null @@ -1,30 +0,0 @@ -package mock - -import ( - "context" - - "github.com/influxdata/influx-cli/v2/internal/api" -) - -var _ api.OrganizationsApi = (*OrganizationsApi)(nil) - -type OrganizationsApi struct { - GetOrgsExecuteFn func(api.ApiGetOrgsRequest) (api.Organizations, error) - PostOrgsExecuteFn func(api.ApiPostOrgsRequest) (api.Organization, error) -} - -func (o *OrganizationsApi) GetOrgs(context.Context) api.ApiGetOrgsRequest { - return api.ApiGetOrgsRequest{ApiService: o} -} - -func (o *OrganizationsApi) GetOrgsExecute(r api.ApiGetOrgsRequest) (api.Organizations, error) { - return o.GetOrgsExecuteFn(r) -} - -func (o *OrganizationsApi) PostOrgs(context.Context) api.ApiPostOrgsRequest { - return api.ApiPostOrgsRequest{ApiService: o} -} - -func (o *OrganizationsApi) PostOrgsExecute(r api.ApiPostOrgsRequest) (api.Organization, error) { - return o.PostOrgsExecuteFn(r) -} diff --git a/internal/mock/api_setup.gen.go b/internal/mock/api_setup.gen.go new file mode 100644 index 0000000..e5c715f --- /dev/null +++ b/internal/mock/api_setup.gen.go @@ -0,0 +1,94 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/influxdata/influx-cli/v2/internal/api (interfaces: SetupApi) + +// Package mock is a generated GoMock package. +package mock + +import ( + context "context" + reflect "reflect" + + gomock "github.com/golang/mock/gomock" + api "github.com/influxdata/influx-cli/v2/internal/api" +) + +// MockSetupApi is a mock of SetupApi interface. +type MockSetupApi struct { + ctrl *gomock.Controller + recorder *MockSetupApiMockRecorder +} + +// MockSetupApiMockRecorder is the mock recorder for MockSetupApi. +type MockSetupApiMockRecorder struct { + mock *MockSetupApi +} + +// NewMockSetupApi creates a new mock instance. +func NewMockSetupApi(ctrl *gomock.Controller) *MockSetupApi { + mock := &MockSetupApi{ctrl: ctrl} + mock.recorder = &MockSetupApiMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockSetupApi) EXPECT() *MockSetupApiMockRecorder { + return m.recorder +} + +// GetSetup mocks base method. +func (m *MockSetupApi) GetSetup(arg0 context.Context) api.ApiGetSetupRequest { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetSetup", arg0) + ret0, _ := ret[0].(api.ApiGetSetupRequest) + return ret0 +} + +// GetSetup indicates an expected call of GetSetup. +func (mr *MockSetupApiMockRecorder) GetSetup(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSetup", reflect.TypeOf((*MockSetupApi)(nil).GetSetup), arg0) +} + +// GetSetupExecute mocks base method. +func (m *MockSetupApi) GetSetupExecute(arg0 api.ApiGetSetupRequest) (api.InlineResponse200, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetSetupExecute", arg0) + ret0, _ := ret[0].(api.InlineResponse200) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetSetupExecute indicates an expected call of GetSetupExecute. +func (mr *MockSetupApiMockRecorder) GetSetupExecute(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSetupExecute", reflect.TypeOf((*MockSetupApi)(nil).GetSetupExecute), arg0) +} + +// PostSetup mocks base method. +func (m *MockSetupApi) PostSetup(arg0 context.Context) api.ApiPostSetupRequest { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "PostSetup", arg0) + ret0, _ := ret[0].(api.ApiPostSetupRequest) + return ret0 +} + +// PostSetup indicates an expected call of PostSetup. +func (mr *MockSetupApiMockRecorder) PostSetup(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PostSetup", reflect.TypeOf((*MockSetupApi)(nil).PostSetup), arg0) +} + +// PostSetupExecute mocks base method. +func (m *MockSetupApi) PostSetupExecute(arg0 api.ApiPostSetupRequest) (api.OnboardingResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "PostSetupExecute", arg0) + ret0, _ := ret[0].(api.OnboardingResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// PostSetupExecute indicates an expected call of PostSetupExecute. +func (mr *MockSetupApiMockRecorder) PostSetupExecute(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PostSetupExecute", reflect.TypeOf((*MockSetupApi)(nil).PostSetupExecute), arg0) +} diff --git a/internal/mock/api_setup.go b/internal/mock/api_setup.go deleted file mode 100644 index e390a7e..0000000 --- a/internal/mock/api_setup.go +++ /dev/null @@ -1,31 +0,0 @@ -package mock - -import ( - "context" - - "github.com/influxdata/influx-cli/v2/internal/api" -) - -var _ api.SetupApi = (*SetupApi)(nil) - -type SetupApi struct { - GetSetupExecuteFn func(api.ApiGetSetupRequest) (api.InlineResponse200, error) - PostSetupExecuteFn func(api.ApiPostSetupRequest) (api.OnboardingResponse, error) -} - -func (s *SetupApi) GetSetup(context.Context) api.ApiGetSetupRequest { - return api.ApiGetSetupRequest{ - ApiService: s, - } -} -func (s *SetupApi) GetSetupExecute(req api.ApiGetSetupRequest) (api.InlineResponse200, error) { - return s.GetSetupExecuteFn(req) -} -func (s *SetupApi) PostSetup(context.Context) api.ApiPostSetupRequest { - return api.ApiPostSetupRequest{ - ApiService: s, - } -} -func (s *SetupApi) PostSetupExecute(req api.ApiPostSetupRequest) (api.OnboardingResponse, error) { - return s.PostSetupExecuteFn(req) -} diff --git a/internal/mock/api_write.gen.go b/internal/mock/api_write.gen.go new file mode 100644 index 0000000..65a3daa --- /dev/null +++ b/internal/mock/api_write.gen.go @@ -0,0 +1,64 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/influxdata/influx-cli/v2/internal/api (interfaces: WriteApi) + +// Package mock is a generated GoMock package. +package mock + +import ( + context "context" + reflect "reflect" + + gomock "github.com/golang/mock/gomock" + api "github.com/influxdata/influx-cli/v2/internal/api" +) + +// MockWriteApi is a mock of WriteApi interface. +type MockWriteApi struct { + ctrl *gomock.Controller + recorder *MockWriteApiMockRecorder +} + +// MockWriteApiMockRecorder is the mock recorder for MockWriteApi. +type MockWriteApiMockRecorder struct { + mock *MockWriteApi +} + +// NewMockWriteApi creates a new mock instance. +func NewMockWriteApi(ctrl *gomock.Controller) *MockWriteApi { + mock := &MockWriteApi{ctrl: ctrl} + mock.recorder = &MockWriteApiMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockWriteApi) EXPECT() *MockWriteApiMockRecorder { + return m.recorder +} + +// PostWrite mocks base method. +func (m *MockWriteApi) PostWrite(arg0 context.Context) api.ApiPostWriteRequest { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "PostWrite", arg0) + ret0, _ := ret[0].(api.ApiPostWriteRequest) + return ret0 +} + +// PostWrite indicates an expected call of PostWrite. +func (mr *MockWriteApiMockRecorder) PostWrite(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PostWrite", reflect.TypeOf((*MockWriteApi)(nil).PostWrite), arg0) +} + +// PostWriteExecute mocks base method. +func (m *MockWriteApi) PostWriteExecute(arg0 api.ApiPostWriteRequest) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "PostWriteExecute", arg0) + ret0, _ := ret[0].(error) + return ret0 +} + +// PostWriteExecute indicates an expected call of PostWriteExecute. +func (mr *MockWriteApiMockRecorder) PostWriteExecute(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PostWriteExecute", reflect.TypeOf((*MockWriteApi)(nil).PostWriteExecute), arg0) +} diff --git a/internal/mock/api_write.go b/internal/mock/api_write.go deleted file mode 100644 index 9858fd5..0000000 --- a/internal/mock/api_write.go +++ /dev/null @@ -1,22 +0,0 @@ -package mock - -import ( - "context" - - "github.com/influxdata/influx-cli/v2/internal/api" -) - -var _ api.WriteApi = (*WriteApi)(nil) - -type WriteApi struct { - PostWriteExecuteFn func(api.ApiPostWriteRequest) error -} - -func (w *WriteApi) PostWrite(context.Context) api.ApiPostWriteRequest { - return api.ApiPostWriteRequest{ - ApiService: w, - } -} -func (w *WriteApi) PostWriteExecute(req api.ApiPostWriteRequest) error { - return w.PostWriteExecuteFn(req) -} diff --git a/internal/mock/config.gen.go b/internal/mock/config.gen.go new file mode 100644 index 0000000..2bf6c29 --- /dev/null +++ b/internal/mock/config.gen.go @@ -0,0 +1,125 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/influxdata/influx-cli/v2/internal/config (interfaces: Service) + +// Package mock is a generated GoMock package. +package mock + +import ( + reflect "reflect" + + gomock "github.com/golang/mock/gomock" + config "github.com/influxdata/influx-cli/v2/internal/config" +) + +// MockConfigService is a mock of Service interface. +type MockConfigService struct { + ctrl *gomock.Controller + recorder *MockConfigServiceMockRecorder +} + +// MockConfigServiceMockRecorder is the mock recorder for MockConfigService. +type MockConfigServiceMockRecorder struct { + mock *MockConfigService +} + +// NewMockConfigService creates a new mock instance. +func NewMockConfigService(ctrl *gomock.Controller) *MockConfigService { + mock := &MockConfigService{ctrl: ctrl} + mock.recorder = &MockConfigServiceMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockConfigService) EXPECT() *MockConfigServiceMockRecorder { + return m.recorder +} + +// Active mocks base method. +func (m *MockConfigService) Active() (config.Config, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Active") + ret0, _ := ret[0].(config.Config) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Active indicates an expected call of Active. +func (mr *MockConfigServiceMockRecorder) Active() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Active", reflect.TypeOf((*MockConfigService)(nil).Active)) +} + +// CreateConfig mocks base method. +func (m *MockConfigService) CreateConfig(arg0 config.Config) (config.Config, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "CreateConfig", arg0) + ret0, _ := ret[0].(config.Config) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// CreateConfig indicates an expected call of CreateConfig. +func (mr *MockConfigServiceMockRecorder) CreateConfig(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateConfig", reflect.TypeOf((*MockConfigService)(nil).CreateConfig), arg0) +} + +// DeleteConfig mocks base method. +func (m *MockConfigService) DeleteConfig(arg0 string) (config.Config, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "DeleteConfig", arg0) + ret0, _ := ret[0].(config.Config) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// DeleteConfig indicates an expected call of DeleteConfig. +func (mr *MockConfigServiceMockRecorder) DeleteConfig(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteConfig", reflect.TypeOf((*MockConfigService)(nil).DeleteConfig), arg0) +} + +// ListConfigs mocks base method. +func (m *MockConfigService) ListConfigs() (config.Configs, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ListConfigs") + ret0, _ := ret[0].(config.Configs) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ListConfigs indicates an expected call of ListConfigs. +func (mr *MockConfigServiceMockRecorder) ListConfigs() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListConfigs", reflect.TypeOf((*MockConfigService)(nil).ListConfigs)) +} + +// SwitchActive mocks base method. +func (m *MockConfigService) SwitchActive(arg0 string) (config.Config, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SwitchActive", arg0) + ret0, _ := ret[0].(config.Config) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// SwitchActive indicates an expected call of SwitchActive. +func (mr *MockConfigServiceMockRecorder) SwitchActive(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SwitchActive", reflect.TypeOf((*MockConfigService)(nil).SwitchActive), arg0) +} + +// UpdateConfig mocks base method. +func (m *MockConfigService) UpdateConfig(arg0 config.Config) (config.Config, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "UpdateConfig", arg0) + ret0, _ := ret[0].(config.Config) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// UpdateConfig indicates an expected call of UpdateConfig. +func (mr *MockConfigServiceMockRecorder) UpdateConfig(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateConfig", reflect.TypeOf((*MockConfigService)(nil).UpdateConfig), arg0) +} diff --git a/internal/mock/config.go b/internal/mock/config.go deleted file mode 100644 index 8a5628b..0000000 --- a/internal/mock/config.go +++ /dev/null @@ -1,33 +0,0 @@ -package mock - -import "github.com/influxdata/influx-cli/v2/internal/config" - -var _ config.Service = (*ConfigService)(nil) - -type ConfigService struct { - CreateConfigFn func(config.Config) (config.Config, error) - DeleteConfigFn func(string) (config.Config, error) - UpdateConfigFn func(config.Config) (config.Config, error) - SwitchActiveFn func(string) (config.Config, error) - ActiveFn func() (config.Config, error) - ListConfigsFn func() (config.Configs, error) -} - -func (c *ConfigService) CreateConfig(cfg config.Config) (config.Config, error) { - return c.CreateConfigFn(cfg) -} -func (c *ConfigService) DeleteConfig(name string) (config.Config, error) { - return c.DeleteConfigFn(name) -} -func (c *ConfigService) UpdateConfig(cfg config.Config) (config.Config, error) { - return c.UpdateConfigFn(cfg) -} -func (c *ConfigService) SwitchActive(name string) (config.Config, error) { - return c.SwitchActiveFn(name) -} -func (c *ConfigService) Active() (config.Config, error) { - return c.ActiveFn() -} -func (c *ConfigService) ListConfigs() (config.Configs, error) { - return c.ListConfigsFn() -} diff --git a/internal/mock/gen.go b/internal/mock/gen.go index 63d0716..4927b92 100644 --- a/internal/mock/gen.go +++ b/internal/mock/gen.go @@ -1,4 +1,13 @@ package mock -//go:generate mockgen -package mock -destination api_bucket_schemas.gen.go github.com/influxdata/influx-cli/v2/internal/api BucketSchemasApi -//go:generate mockgen -package mock -destination api_buckets.gen.go github.com/influxdata/influx-cli/v2/internal/api BucketsApi +// HTTP API mocks +//go:generate go run github.com/golang/mock/mockgen -package mock -destination api_bucket_schemas.gen.go github.com/influxdata/influx-cli/v2/internal/api BucketSchemasApi +//go:generate go run github.com/golang/mock/mockgen -package mock -destination api_buckets.gen.go github.com/influxdata/influx-cli/v2/internal/api BucketsApi +//go:generate go run github.com/golang/mock/mockgen -package mock -destination api_health.gen.go github.com/influxdata/influx-cli/v2/internal/api HealthApi +//go:generate go run github.com/golang/mock/mockgen -package mock -destination api_organizations.gen.go github.com/influxdata/influx-cli/v2/internal/api OrganizationsApi +//go:generate go run github.com/golang/mock/mockgen -package mock -destination api_setup.gen.go github.com/influxdata/influx-cli/v2/internal/api SetupApi +//go:generate go run github.com/golang/mock/mockgen -package mock -destination api_write.gen.go github.com/influxdata/influx-cli/v2/internal/api WriteApi + +// Other mocks +//go:generate go run github.com/golang/mock/mockgen -package mock -destination config.gen.go -mock_names Service=MockConfigService github.com/influxdata/influx-cli/v2/internal/config Service +//go:generate go run github.com/golang/mock/mockgen -package mock -destination stdio.gen.go github.com/influxdata/influx-cli/v2/internal/stdio StdIO diff --git a/internal/mock/stdio.gen.go b/internal/mock/stdio.gen.go new file mode 100644 index 0000000..d20ee93 --- /dev/null +++ b/internal/mock/stdio.gen.go @@ -0,0 +1,121 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/influxdata/influx-cli/v2/internal/stdio (interfaces: StdIO) + +// Package mock is a generated GoMock package. +package mock + +import ( + reflect "reflect" + + gomock "github.com/golang/mock/gomock" +) + +// MockStdIO is a mock of StdIO interface. +type MockStdIO struct { + ctrl *gomock.Controller + recorder *MockStdIOMockRecorder +} + +// MockStdIOMockRecorder is the mock recorder for MockStdIO. +type MockStdIOMockRecorder struct { + mock *MockStdIO +} + +// NewMockStdIO creates a new mock instance. +func NewMockStdIO(ctrl *gomock.Controller) *MockStdIO { + mock := &MockStdIO{ctrl: ctrl} + mock.recorder = &MockStdIOMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockStdIO) EXPECT() *MockStdIOMockRecorder { + return m.recorder +} + +// Banner mocks base method. +func (m *MockStdIO) Banner(arg0 string) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Banner", arg0) + ret0, _ := ret[0].(error) + return ret0 +} + +// Banner indicates an expected call of Banner. +func (mr *MockStdIOMockRecorder) Banner(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Banner", reflect.TypeOf((*MockStdIO)(nil).Banner), arg0) +} + +// Error mocks base method. +func (m *MockStdIO) Error(arg0 string) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Error", arg0) + ret0, _ := ret[0].(error) + return ret0 +} + +// Error indicates an expected call of Error. +func (mr *MockStdIOMockRecorder) Error(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Error", reflect.TypeOf((*MockStdIO)(nil).Error), arg0) +} + +// GetConfirm mocks base method. +func (m *MockStdIO) GetConfirm(arg0 string) bool { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetConfirm", arg0) + ret0, _ := ret[0].(bool) + return ret0 +} + +// GetConfirm indicates an expected call of GetConfirm. +func (mr *MockStdIOMockRecorder) GetConfirm(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetConfirm", reflect.TypeOf((*MockStdIO)(nil).GetConfirm), arg0) +} + +// GetPassword mocks base method. +func (m *MockStdIO) GetPassword(arg0 string, arg1 int) (string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetPassword", arg0, arg1) + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetPassword indicates an expected call of GetPassword. +func (mr *MockStdIOMockRecorder) GetPassword(arg0, arg1 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPassword", reflect.TypeOf((*MockStdIO)(nil).GetPassword), arg0, arg1) +} + +// GetStringInput mocks base method. +func (m *MockStdIO) GetStringInput(arg0, arg1 string) (string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetStringInput", arg0, arg1) + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetStringInput indicates an expected call of GetStringInput. +func (mr *MockStdIOMockRecorder) GetStringInput(arg0, arg1 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStringInput", reflect.TypeOf((*MockStdIO)(nil).GetStringInput), arg0, arg1) +} + +// Write mocks base method. +func (m *MockStdIO) Write(arg0 []byte) (int, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Write", arg0) + ret0, _ := ret[0].(int) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Write indicates an expected call of Write. +func (mr *MockStdIOMockRecorder) Write(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Write", reflect.TypeOf((*MockStdIO)(nil).Write), arg0) +} diff --git a/internal/mock/stdio.go b/internal/mock/stdio.go deleted file mode 100644 index 21368b8..0000000 --- a/internal/mock/stdio.go +++ /dev/null @@ -1,55 +0,0 @@ -package mock - -import ( - "bytes" - "errors" -) - -type Stdio struct { - answers map[string]string - confirm bool - out bytes.Buffer -} - -func NewMockStdio(promptAnswers map[string]string, confirm bool) *Stdio { - return &Stdio{answers: promptAnswers, confirm: confirm, out: bytes.Buffer{}} -} - -func (m *Stdio) Write(p []byte) (int, error) { - return m.out.Write(p) -} - -func (m *Stdio) Banner(string) error { - return nil -} - -func (m *Stdio) Error(string) error { - return nil -} - -func (m *Stdio) GetStringInput(prompt, defaultValue string) (string, error) { - v, ok := m.answers[prompt] - if !ok { - return defaultValue, nil - } - return v, nil -} - -func (m *Stdio) GetPassword(prompt string, minLen int) (string, error) { - v, ok := m.answers[prompt] - if !ok { - return "", errors.New("no password given") - } - if len(v) < minLen { - return "", errors.New("password too short") - } - return v, nil -} - -func (m *Stdio) GetConfirm(string) bool { - return m.confirm -} - -func (m *Stdio) Stdout() string { - return m.out.String() -} diff --git a/internal/ping_test.go b/internal/ping_test.go index 53a275e..75b292c 100644 --- a/internal/ping_test.go +++ b/internal/ping_test.go @@ -1,10 +1,12 @@ package internal_test import ( + "bytes" "context" "errors" "testing" + "github.com/golang/mock/gomock" "github.com/influxdata/influx-cli/v2/internal" "github.com/influxdata/influx-cli/v2/internal/api" "github.com/influxdata/influx-cli/v2/internal/mock" @@ -14,28 +16,28 @@ import ( func Test_PingSuccess(t *testing.T) { t.Parallel() - client := &mock.HealthApi{ - GetHealthExecuteFn: func(req api.ApiGetHealthRequest) (api.HealthCheck, error) { - return api.HealthCheck{Status: api.HEALTHCHECKSTATUS_PASS}, nil - }, - } + ctrl := gomock.NewController(t) + client := mock.NewMockHealthApi(ctrl) + client.EXPECT().GetHealth(gomock.Any()).Return(api.ApiGetHealthRequest{ApiService: client}) + client.EXPECT().GetHealthExecute(gomock.Any()).Return(api.HealthCheck{Status: api.HEALTHCHECKSTATUS_PASS}, nil) - stdio := mock.NewMockStdio(nil, true) + stdio := mock.NewMockStdIO(ctrl) + bytesWritten := bytes.Buffer{} + stdio.EXPECT().Write(gomock.Any()).DoAndReturn(bytesWritten.Write).AnyTimes() cli := &internal.CLI{StdIO: stdio} require.NoError(t, cli.Ping(context.Background(), client)) - require.Equal(t, "OK\n", stdio.Stdout()) + require.Equal(t, "OK\n", bytesWritten.String()) } func Test_PingFailedRequest(t *testing.T) { t.Parallel() e := "the internet is down" - client := &mock.HealthApi{ - GetHealthExecuteFn: func(api.ApiGetHealthRequest) (api.HealthCheck, error) { - return api.HealthCheck{}, errors.New(e) - }, - } + ctrl := gomock.NewController(t) + client := mock.NewMockHealthApi(ctrl) + client.EXPECT().GetHealth(gomock.Any()).Return(api.ApiGetHealthRequest{ApiService: client}) + client.EXPECT().GetHealthExecute(gomock.Any()).Return(api.HealthCheck{}, errors.New(e)) cli := &internal.CLI{} err := cli.Ping(context.Background(), client) @@ -47,11 +49,11 @@ func Test_PingFailedStatus(t *testing.T) { t.Parallel() e := "I broke" - client := &mock.HealthApi{ - GetHealthExecuteFn: func(api.ApiGetHealthRequest) (api.HealthCheck, error) { - return api.HealthCheck{}, &api.HealthCheck{Status: api.HEALTHCHECKSTATUS_FAIL, Message: &e} - }, - } + ctrl := gomock.NewController(t) + client := mock.NewMockHealthApi(ctrl) + client.EXPECT().GetHealth(gomock.Any()).Return(api.ApiGetHealthRequest{ApiService: client}) + client.EXPECT().GetHealthExecute(gomock.Any()). + Return(api.HealthCheck{}, &api.HealthCheck{Status: api.HEALTHCHECKSTATUS_FAIL, Message: &e}) cli := &internal.CLI{} err := cli.Ping(context.Background(), client) @@ -63,11 +65,11 @@ func Test_PingFailedStatusNoMessage(t *testing.T) { t.Parallel() name := "foo" - client := &mock.HealthApi{ - GetHealthExecuteFn: func(api.ApiGetHealthRequest) (api.HealthCheck, error) { - return api.HealthCheck{}, &api.HealthCheck{Status: api.HEALTHCHECKSTATUS_FAIL, Name: name} - }, - } + ctrl := gomock.NewController(t) + client := mock.NewMockHealthApi(ctrl) + client.EXPECT().GetHealth(gomock.Any()).Return(api.ApiGetHealthRequest{ApiService: client}) + client.EXPECT().GetHealthExecute(gomock.Any()). + Return(api.HealthCheck{}, &api.HealthCheck{Status: api.HEALTHCHECKSTATUS_FAIL, Name: name}) cli := &internal.CLI{} err := cli.Ping(context.Background(), client) diff --git a/internal/setup_test.go b/internal/setup_test.go index 4cea2b6..b2fa001 100644 --- a/internal/setup_test.go +++ b/internal/setup_test.go @@ -1,6 +1,7 @@ package internal_test import ( + "bytes" "context" "errors" "fmt" @@ -8,29 +9,28 @@ import ( "strings" "testing" + "github.com/golang/mock/gomock" "github.com/influxdata/influx-cli/v2/internal" "github.com/influxdata/influx-cli/v2/internal/api" "github.com/influxdata/influx-cli/v2/internal/config" "github.com/influxdata/influx-cli/v2/internal/duration" "github.com/influxdata/influx-cli/v2/internal/mock" + "github.com/stretchr/testify/assert" + tmock "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" ) func Test_SetupConfigNameCollision(t *testing.T) { t.Parallel() - client := &mock.SetupApi{ - GetSetupExecuteFn: func(api.ApiGetSetupRequest) (api.InlineResponse200, error) { - return api.InlineResponse200{Allowed: api.PtrBool(true)}, nil - }, - } + ctrl := gomock.NewController(t) + client := mock.NewMockSetupApi(ctrl) + client.EXPECT().GetSetup(gomock.Any()).Return(api.ApiGetSetupRequest{ApiService: client}) + client.EXPECT().GetSetupExecute(gomock.Any()).Return(api.InlineResponse200{Allowed: api.PtrBool(true)}, nil) cfg := "foo" - configSvc := &mock.ConfigService{ - ListConfigsFn: func() (config.Configs, error) { - return map[string]config.Config{cfg: {}}, nil - }, - } + configSvc := mock.NewMockConfigService(ctrl) + configSvc.EXPECT().ListConfigs().Return(map[string]config.Config{cfg: {}}, nil) cli := &internal.CLI{ConfigService: configSvc} err := cli.Setup(context.Background(), client, &internal.SetupParams{ConfigName: cfg}) @@ -42,17 +42,13 @@ func Test_SetupConfigNameCollision(t *testing.T) { func Test_SetupConfigNameRequired(t *testing.T) { t.Parallel() - client := &mock.SetupApi{ - GetSetupExecuteFn: func(api.ApiGetSetupRequest) (api.InlineResponse200, error) { - return api.InlineResponse200{Allowed: api.PtrBool(true)}, nil - }, - } + ctrl := gomock.NewController(t) + client := mock.NewMockSetupApi(ctrl) + client.EXPECT().GetSetup(gomock.Any()).Return(api.ApiGetSetupRequest{ApiService: client}) + client.EXPECT().GetSetupExecute(gomock.Any()).Return(api.InlineResponse200{Allowed: api.PtrBool(true)}, nil) - configSvc := &mock.ConfigService{ - ListConfigsFn: func() (config.Configs, error) { - return map[string]config.Config{"foo": {}}, nil - }, - } + configSvc := mock.NewMockConfigService(ctrl) + configSvc.EXPECT().ListConfigs().Return(map[string]config.Config{"foo": {}}, nil) cli := &internal.CLI{ConfigService: configSvc} err := cli.Setup(context.Background(), client, &internal.SetupParams{}) @@ -62,18 +58,12 @@ func Test_SetupConfigNameRequired(t *testing.T) { func Test_SetupAlreadySetup(t *testing.T) { t.Parallel() + ctrl := gomock.NewController(t) + client := mock.NewMockSetupApi(ctrl) + client.EXPECT().GetSetup(gomock.Any()).Return(api.ApiGetSetupRequest{ApiService: client}) + client.EXPECT().GetSetupExecute(gomock.Any()).Return(api.InlineResponse200{Allowed: api.PtrBool(false)}, nil) - client := &mock.SetupApi{ - GetSetupExecuteFn: func(api.ApiGetSetupRequest) (api.InlineResponse200, error) { - return api.InlineResponse200{Allowed: api.PtrBool(false)}, nil - }, - } - - configSvc := &mock.ConfigService{ - ListConfigsFn: func() (config.Configs, error) { - return map[string]config.Config{"foo": {}}, nil - }, - } + configSvc := mock.NewMockConfigService(ctrl) cli := &internal.CLI{ConfigService: configSvc} err := cli.Setup(context.Background(), client, &internal.SetupParams{}) @@ -85,17 +75,12 @@ func Test_SetupCheckFailed(t *testing.T) { t.Parallel() e := "oh no" - client := &mock.SetupApi{ - GetSetupExecuteFn: func(api.ApiGetSetupRequest) (api.InlineResponse200, error) { - return api.InlineResponse200{}, errors.New(e) - }, - } + ctrl := gomock.NewController(t) + client := mock.NewMockSetupApi(ctrl) + client.EXPECT().GetSetup(gomock.Any()).Return(api.ApiGetSetupRequest{ApiService: client}) + client.EXPECT().GetSetupExecute(gomock.Any()).Return(api.InlineResponse200{}, errors.New(e)) - configSvc := &mock.ConfigService{ - ListConfigsFn: func() (config.Configs, error) { - return nil, nil - }, - } + configSvc := mock.NewMockConfigService(ctrl) cli := &internal.CLI{ConfigService: configSvc} err := cli.Setup(context.Background(), client, &internal.SetupParams{}) @@ -123,40 +108,42 @@ func Test_SetupSuccessNoninteractive(t *testing.T) { User: &api.UserResponse{Name: params.Username}, Bucket: &api.Bucket{Name: params.Bucket}, } - client := &mock.SetupApi{ - GetSetupExecuteFn: func(api.ApiGetSetupRequest) (api.InlineResponse200, error) { - return api.InlineResponse200{Allowed: api.PtrBool(true)}, nil - }, - PostSetupExecuteFn: func(req api.ApiPostSetupRequest) (api.OnboardingResponse, error) { - body := req.GetOnboardingRequest() - require.Equal(t, params.Username, body.Username) - require.Equal(t, params.Password, *body.Password) - require.Equal(t, params.AuthToken, *body.Token) - require.Equal(t, params.Org, body.Org) - require.Equal(t, params.Bucket, body.Bucket) - require.Equal(t, retentionSecs, *body.RetentionPeriodSeconds) - return resp, nil - }, - } + + ctrl := gomock.NewController(t) + client := mock.NewMockSetupApi(ctrl) + client.EXPECT().GetSetup(gomock.Any()).Return(api.ApiGetSetupRequest{ApiService: client}) + client.EXPECT().GetSetupExecute(gomock.Any()).Return(api.InlineResponse200{Allowed: api.PtrBool(true)}, nil) + client.EXPECT().PostSetup(gomock.Any()).Return(api.ApiPostSetupRequest{ApiService: client}) + client.EXPECT().PostSetupExecute(tmock.MatchedBy(func(in api.ApiPostSetupRequest) bool { + body := in.GetOnboardingRequest() + return assert.NotNil(t, body) && + assert.Equal(t, params.Username, body.Username) && + assert.Equal(t, params.Password, *body.Password) && + assert.Equal(t, params.AuthToken, *body.Token) && + assert.Equal(t, params.Org, body.Org) && + assert.Equal(t, params.Bucket, body.Bucket) && + assert.Equal(t, retentionSecs, *body.RetentionPeriodSeconds) + })).Return(resp, nil) host := "fake-host" - configSvc := &mock.ConfigService{ - ListConfigsFn: func() (config.Configs, error) { - return nil, nil - }, - CreateConfigFn: func(cfg config.Config) (config.Config, error) { - require.Equal(t, params.ConfigName, cfg.Name) - require.Equal(t, params.AuthToken, cfg.Token) - require.Equal(t, host, cfg.Host) - require.Equal(t, params.Org, cfg.Org) - return cfg, nil - }, - } - stdio := mock.NewMockStdio(nil, true) + configSvc := mock.NewMockConfigService(ctrl) + configSvc.EXPECT().ListConfigs().Return(nil, nil) + configSvc.EXPECT().CreateConfig(tmock.MatchedBy(func(in config.Config) bool { + return assert.Equal(t, params.ConfigName, in.Name) && + assert.Equal(t, params.AuthToken, in.Token) && + assert.Equal(t, host, in.Host) && + assert.Equal(t, params.Org, in.Org) + })).DoAndReturn(func(in config.Config) (config.Config, error) { + return in, nil + }) + + stdio := mock.NewMockStdIO(ctrl) + bytesWritten := bytes.Buffer{} + stdio.EXPECT().Write(gomock.Any()).DoAndReturn(bytesWritten.Write).AnyTimes() cli := &internal.CLI{ConfigService: configSvc, ActiveConfig: config.Config{Host: host}, StdIO: stdio} require.NoError(t, cli.Setup(context.Background(), client, ¶ms)) - outLines := strings.Split(strings.TrimSpace(stdio.Stdout()), "\n") + outLines := strings.Split(strings.TrimSpace(bytesWritten.String()), "\n") require.Len(t, outLines, 2) header, data := outLines[0], outLines[1] require.Regexp(t, "User\\s+Organization\\s+Bucket", header) @@ -180,47 +167,49 @@ func Test_SetupSuccessInteractive(t *testing.T) { User: &api.UserResponse{Name: username}, Bucket: &api.Bucket{Name: bucket}, } - client := &mock.SetupApi{ - GetSetupExecuteFn: func(api.ApiGetSetupRequest) (api.InlineResponse200, error) { - return api.InlineResponse200{Allowed: api.PtrBool(true)}, nil - }, - PostSetupExecuteFn: func(req api.ApiPostSetupRequest) (api.OnboardingResponse, error) { - body := req.GetOnboardingRequest() - require.Equal(t, username, body.Username) - require.Equal(t, password, *body.Password) - require.Nil(t, body.Token) - require.Equal(t, org, body.Org) - require.Equal(t, bucket, body.Bucket) - require.Equal(t, retentionSecs, *body.RetentionPeriodSeconds) - return resp, nil - }, - } + ctrl := gomock.NewController(t) + client := mock.NewMockSetupApi(ctrl) + client.EXPECT().GetSetup(gomock.Any()).Return(api.ApiGetSetupRequest{ApiService: client}) + client.EXPECT().GetSetupExecute(gomock.Any()).Return(api.InlineResponse200{Allowed: api.PtrBool(true)}, nil) + client.EXPECT().PostSetup(gomock.Any()).Return(api.ApiPostSetupRequest{ApiService: client}) + client.EXPECT().PostSetupExecute(tmock.MatchedBy(func(in api.ApiPostSetupRequest) bool { + body := in.GetOnboardingRequest() + return assert.NotNil(t, body) && + assert.Equal(t, username, body.Username) && + assert.Equal(t, password, *body.Password) && + assert.Nil(t, body.Token) && + assert.Equal(t, org, body.Org) && + assert.Equal(t, bucket, body.Bucket) && + assert.Equal(t, retentionSecs, *body.RetentionPeriodSeconds) + })).Return(resp, nil) host := "fake-host" - configSvc := &mock.ConfigService{ - ListConfigsFn: func() (config.Configs, error) { - return nil, nil - }, - CreateConfigFn: func(cfg config.Config) (config.Config, error) { - require.Equal(t, config.DefaultConfig.Name, cfg.Name) - require.Equal(t, token, cfg.Token) - require.Equal(t, host, cfg.Host) - require.Equal(t, org, cfg.Org) - return cfg, nil - }, - } - stdio := mock.NewMockStdio(map[string]string{ - "Please type your primary username": username, - "Please type your password": password, - "Please type your password again": password, - "Please type your primary organization name": org, - "Please type your primary bucket name": bucket, - "Please type your retention period in hours, or 0 for infinite": strconv.Itoa(retentionHrs), - }, true) + configSvc := mock.NewMockConfigService(ctrl) + configSvc.EXPECT().ListConfigs().Return(nil, nil) + configSvc.EXPECT().CreateConfig(tmock.MatchedBy(func(in config.Config) bool { + return assert.Equal(t, config.DefaultConfig.Name, in.Name) && + assert.Equal(t, token, in.Token) && + assert.Equal(t, host, in.Host) && + assert.Equal(t, org, in.Org) + })).DoAndReturn(func(in config.Config) (config.Config, error) { + return in, nil + }) + + stdio := mock.NewMockStdIO(ctrl) + bytesWritten := bytes.Buffer{} + stdio.EXPECT().Write(gomock.Any()).DoAndReturn(bytesWritten.Write).AnyTimes() + stdio.EXPECT().Banner(gomock.Any()) + stdio.EXPECT().GetStringInput(gomock.Eq("Please type your primary username"), gomock.Any()).Return(username, nil) + stdio.EXPECT().GetPassword(gomock.Eq("Please type your password"), gomock.Any()).Return(password, nil) + stdio.EXPECT().GetPassword(gomock.Eq("Please type your password again"), gomock.Any()).Return(password, nil) + stdio.EXPECT().GetStringInput(gomock.Eq("Please type your primary organization name"), gomock.Any()).Return(org, nil) + stdio.EXPECT().GetStringInput("Please type your primary bucket name", gomock.Any()).Return(bucket, nil) + stdio.EXPECT().GetStringInput("Please type your retention period in hours, or 0 for infinite", gomock.Any()).Return(strconv.Itoa(retentionHrs), nil) + stdio.EXPECT().GetConfirm(gomock.Any()).Return(true) cli := &internal.CLI{ConfigService: configSvc, ActiveConfig: config.Config{Host: host}, StdIO: stdio} require.NoError(t, cli.Setup(context.Background(), client, &internal.SetupParams{})) - outLines := strings.Split(strings.TrimSpace(stdio.Stdout()), "\n") + outLines := strings.Split(strings.TrimSpace(bytesWritten.String()), "\n") require.Len(t, outLines, 2) header, data := outLines[0], outLines[1] require.Regexp(t, "User\\s+Organization\\s+Bucket", header) @@ -240,19 +229,17 @@ func Test_SetupPasswordParamToShort(t *testing.T) { Retention: fmt.Sprintf("%ds", retentionSecs), Force: false, } - client := &mock.SetupApi{ - GetSetupExecuteFn: func(api.ApiGetSetupRequest) (api.InlineResponse200, error) { - return api.InlineResponse200{Allowed: api.PtrBool(true)}, nil - }, - } + + ctrl := gomock.NewController(t) + client := mock.NewMockSetupApi(ctrl) + client.EXPECT().GetSetup(gomock.Any()).Return(api.ApiGetSetupRequest{ApiService: client}) + client.EXPECT().GetSetupExecute(gomock.Any()).Return(api.InlineResponse200{Allowed: api.PtrBool(true)}, nil) host := "fake-host" - configSvc := &mock.ConfigService{ - ListConfigsFn: func() (config.Configs, error) { - return nil, nil - }, - } - stdio := mock.NewMockStdio(nil, false) + configSvc := mock.NewMockConfigService(ctrl) + configSvc.EXPECT().ListConfigs().Return(nil, nil) + + stdio := mock.NewMockStdIO(ctrl) cli := &internal.CLI{ConfigService: configSvc, ActiveConfig: config.Config{Host: host}, StdIO: stdio} err := cli.Setup(context.Background(), client, ¶ms) require.Equal(t, internal.ErrPasswordIsTooShort, err) @@ -271,19 +258,20 @@ func Test_SetupCancelAtConfirmation(t *testing.T) { Retention: fmt.Sprintf("%ds", retentionSecs), Force: false, } - client := &mock.SetupApi{ - GetSetupExecuteFn: func(api.ApiGetSetupRequest) (api.InlineResponse200, error) { - return api.InlineResponse200{Allowed: api.PtrBool(true)}, nil - }, - } + + ctrl := gomock.NewController(t) + client := mock.NewMockSetupApi(ctrl) + client.EXPECT().GetSetup(gomock.Any()).Return(api.ApiGetSetupRequest{ApiService: client}) + client.EXPECT().GetSetupExecute(gomock.Any()).Return(api.InlineResponse200{Allowed: api.PtrBool(true)}, nil) host := "fake-host" - configSvc := &mock.ConfigService{ - ListConfigsFn: func() (config.Configs, error) { - return nil, nil - }, - } - stdio := mock.NewMockStdio(nil, false) + configSvc := mock.NewMockConfigService(ctrl) + configSvc.EXPECT().ListConfigs().Return(nil, nil) + + stdio := mock.NewMockStdIO(ctrl) + stdio.EXPECT().Banner(gomock.Any()) + stdio.EXPECT().GetConfirm(gomock.Any()).Return(false) + cli := &internal.CLI{ConfigService: configSvc, ActiveConfig: config.Config{Host: host}, StdIO: stdio} err := cli.Setup(context.Background(), client, ¶ms) require.Equal(t, internal.ErrSetupCanceled, err) diff --git a/internal/write_test.go b/internal/write_test.go index d885e56..7557ce2 100644 --- a/internal/write_test.go +++ b/internal/write_test.go @@ -8,10 +8,13 @@ import ( "strings" "testing" + "github.com/golang/mock/gomock" "github.com/influxdata/influx-cli/v2/internal" "github.com/influxdata/influx-cli/v2/internal/api" "github.com/influxdata/influx-cli/v2/internal/config" "github.com/influxdata/influx-cli/v2/internal/mock" + "github.com/stretchr/testify/assert" + tmock "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" ) @@ -50,6 +53,8 @@ func (pb *lineBatcher) WriteBatches(_ context.Context, r io.Reader, writeFn func } func TestWriteByIDs(t *testing.T) { + t.Parallel() + inLines := []string{"fake line protocol 1", "fake line protocol 2", "fake line protocol 3"} mockReader := bufferReader{} for _, l := range inLines { @@ -66,26 +71,25 @@ func TestWriteByIDs(t *testing.T) { } cli := internal.CLI{ActiveConfig: config.Config{Org: "my-default-org"}} + ctrl := gomock.NewController(t) + client := mock.NewMockWriteApi(ctrl) var writtenLines []string - client := mock.WriteApi{ - PostWriteExecuteFn: func(req api.ApiPostWriteRequest) error { - // Make sure query params are set. - require.Equal(t, params.OrgID, *req.GetOrg()) - require.Equal(t, params.BucketID, *req.GetBucket()) - require.Equal(t, params.Precision, *req.GetPrecision()) - - // Make sure the body is properly marked for compression, and record what was sent. - require.Equal(t, "gzip", *req.GetContentEncoding()) - writtenLines = append(writtenLines, string(req.GetBody())) - return nil - }, - } + client.EXPECT().PostWrite(gomock.Any()).Return(api.ApiPostWriteRequest{ApiService: client}).Times(len(inLines)) + client.EXPECT().PostWriteExecute(tmock.MatchedBy(func(in api.ApiPostWriteRequest) bool { + return assert.Equal(t, params.OrgID, *in.GetOrg()) && + assert.Equal(t, params.BucketID, *in.GetBucket()) && + assert.Equal(t, params.Precision, *in.GetPrecision()) && + assert.Equal(t, "gzip", *in.GetContentEncoding()) // Make sure the body is properly marked for compression. + })).DoAndReturn(func(in api.ApiPostWriteRequest) error { + writtenLines = append(writtenLines, string(in.GetBody())) + return nil + }).Times(len(inLines)) clients := internal.WriteClients{ Reader: &mockReader, Throttler: &mockThrottler, Writer: &mockBatcher, - Client: &client, + Client: client, } require.NoError(t, cli.Write(context.Background(), &clients, ¶ms)) @@ -94,6 +98,8 @@ func TestWriteByIDs(t *testing.T) { } func TestWriteByNames(t *testing.T) { + t.Parallel() + inLines := []string{"fake line protocol 1", "fake line protocol 2", "fake line protocol 3"} mockReader := bufferReader{} for _, l := range inLines { @@ -110,26 +116,25 @@ func TestWriteByNames(t *testing.T) { } cli := internal.CLI{ActiveConfig: config.Config{Org: "my-default-org"}} + ctrl := gomock.NewController(t) + client := mock.NewMockWriteApi(ctrl) var writtenLines []string - client := mock.WriteApi{ - PostWriteExecuteFn: func(req api.ApiPostWriteRequest) error { - // Make sure query params are set. - require.Equal(t, params.OrgName, *req.GetOrg()) - require.Equal(t, params.BucketName, *req.GetBucket()) - require.Equal(t, params.Precision, *req.GetPrecision()) - - // Make sure the body is properly marked for compression, and record what was sent. - require.Equal(t, "gzip", *req.GetContentEncoding()) - writtenLines = append(writtenLines, string(req.GetBody())) - return nil - }, - } + client.EXPECT().PostWrite(gomock.Any()).Return(api.ApiPostWriteRequest{ApiService: client}).Times(len(inLines)) + client.EXPECT().PostWriteExecute(tmock.MatchedBy(func(in api.ApiPostWriteRequest) bool { + return assert.Equal(t, params.OrgName, *in.GetOrg()) && + assert.Equal(t, params.BucketName, *in.GetBucket()) && + assert.Equal(t, params.Precision, *in.GetPrecision()) && + assert.Equal(t, "gzip", *in.GetContentEncoding()) // Make sure the body is properly marked for compression. + })).DoAndReturn(func(in api.ApiPostWriteRequest) error { + writtenLines = append(writtenLines, string(in.GetBody())) + return nil + }).Times(len(inLines)) clients := internal.WriteClients{ Reader: &mockReader, Throttler: &mockThrottler, Writer: &mockBatcher, - Client: &client, + Client: client, } require.NoError(t, cli.Write(context.Background(), &clients, ¶ms)) @@ -138,6 +143,8 @@ func TestWriteByNames(t *testing.T) { } func TestWriteOrgFromConfig(t *testing.T) { + t.Parallel() + inLines := []string{"fake line protocol 1", "fake line protocol 2", "fake line protocol 3"} mockReader := bufferReader{} for _, l := range inLines { @@ -153,26 +160,25 @@ func TestWriteOrgFromConfig(t *testing.T) { } cli := internal.CLI{ActiveConfig: config.Config{Org: "my-default-org"}} + ctrl := gomock.NewController(t) + client := mock.NewMockWriteApi(ctrl) var writtenLines []string - client := mock.WriteApi{ - PostWriteExecuteFn: func(req api.ApiPostWriteRequest) error { - // Make sure query params are set. - require.Equal(t, cli.ActiveConfig.Org, *req.GetOrg()) - require.Equal(t, params.BucketName, *req.GetBucket()) - require.Equal(t, params.Precision, *req.GetPrecision()) - - // Make sure the body is properly marked for compression, and record what was sent. - require.Equal(t, "gzip", *req.GetContentEncoding()) - writtenLines = append(writtenLines, string(req.GetBody())) - return nil - }, - } + client.EXPECT().PostWrite(gomock.Any()).Return(api.ApiPostWriteRequest{ApiService: client}).Times(len(inLines)) + client.EXPECT().PostWriteExecute(tmock.MatchedBy(func(in api.ApiPostWriteRequest) bool { + return assert.Equal(t, cli.ActiveConfig.Org, *in.GetOrg()) && + assert.Equal(t, params.BucketName, *in.GetBucket()) && + assert.Equal(t, params.Precision, *in.GetPrecision()) && + assert.Equal(t, "gzip", *in.GetContentEncoding()) // Make sure the body is properly marked for compression. + })).DoAndReturn(func(in api.ApiPostWriteRequest) error { + writtenLines = append(writtenLines, string(in.GetBody())) + return nil + }).Times(len(inLines)) clients := internal.WriteClients{ Reader: &mockReader, Throttler: &mockThrottler, Writer: &mockBatcher, - Client: &client, + Client: client, } require.NoError(t, cli.Write(context.Background(), &clients, ¶ms)) @@ -181,6 +187,8 @@ func TestWriteOrgFromConfig(t *testing.T) { } func TestWriteDryRun(t *testing.T) { + t.Parallel() + inLines := ` fake line protocol 1 fake line protocol 2 @@ -189,9 +197,14 @@ fake line protocol 3 mockReader := bufferReader{} _, err := io.Copy(&mockReader.buf, strings.NewReader(inLines)) require.NoError(t, err) - stdio := mock.NewMockStdio(nil, true) + + ctrl := gomock.NewController(t) + stdio := mock.NewMockStdIO(ctrl) + bytesWritten := bytes.Buffer{} + stdio.EXPECT().Write(gomock.Any()).DoAndReturn(bytesWritten.Write).AnyTimes() + cli := internal.CLI{ActiveConfig: config.Config{Org: "my-default-org"}, StdIO: stdio} require.NoError(t, cli.WriteDryRun(context.Background(), &mockReader)) - require.Equal(t, inLines, stdio.Stdout()) + require.Equal(t, inLines, bytesWritten.String()) } diff --git a/tools.go b/tools.go index 7d25fe3..0015fac 100644 --- a/tools.go +++ b/tools.go @@ -11,6 +11,7 @@ package influxcli import ( _ "github.com/daixiang0/gci" + _ "github.com/golang/mock/mockgen" _ "golang.org/x/tools/cmd/goimports" _ "honnef.co/go/tools/cmd/staticcheck" )