test: replace hand-written mocks with gomock (#63)

This commit is contained in:
Daniel Moran
2021-05-06 10:19:41 -04:00
committed by GitHub
parent c44fec7d6d
commit d995f7d182
24 changed files with 1313 additions and 983 deletions

View File

@ -67,6 +67,9 @@ vet:
go vet ./... go vet ./...
# Testing # Testing
mock: ./internal/mock/gen.go
go generate ./internal/mock/
test: test:
$(GO_TEST) $(GO_TEST_PATHS) $(GO_TEST) $(GO_TEST_PATHS)
@ -74,4 +77,4 @@ test-race:
$(GO_TEST) -v -race -count=1 $(GO_TEST_PATHS) $(GO_TEST) -v -race -count=1 $(GO_TEST_PATHS)
### List of all targets that don't produce a file ### 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

View File

@ -193,13 +193,14 @@ func (c *CLI) BucketsDelete(ctx context.Context, client api.BucketsApi, params *
} }
var bucket api.Bucket var bucket api.Bucket
getReq := client.GetBuckets(ctx) var getReq api.ApiGetBucketsRequest
if params.ID != "" { if params.ID != "" {
getReq = getReq.Id(params.ID) getReq = client.GetBuckets(ctx).Id(params.ID)
} else { } else {
if params.OrgID == "" && params.OrgName == "" && c.ActiveConfig.Org == "" { if params.OrgID == "" && params.OrgName == "" && c.ActiveConfig.Org == "" {
return ErrMustSpecifyOrgDeleteByName return ErrMustSpecifyOrgDeleteByName
} }
getReq = client.GetBuckets(ctx)
getReq = getReq.Name(params.Name) getReq = getReq.Name(params.Name)
if params.OrgID != "" { if params.OrgID != "" {
getReq = getReq.OrgID(params.OrgID) getReq = getReq.OrgID(params.OrgID)

File diff suppressed because it is too large Load Diff

View File

@ -5,7 +5,6 @@ import (
"context" "context"
"os" "os"
"path/filepath" "path/filepath"
"regexp"
"strings" "strings"
"testing" "testing"
"time" "time"
@ -21,28 +20,22 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
func matchLines(t *testing.T, lines []string, mockIO *mock.Stdio) { func matchLines(t *testing.T, expectedLines []string, lines []string) {
if len(lines) > 0 { var nonEmptyLines []string
outLines := strings.Split(mockIO.Stdout(), "\n") for _, l := range lines {
expLines := make([]*regexp.Regexp, 0, len(lines)) if l != "" {
for _, expLine := range lines { nonEmptyLines = append(nonEmptyLines, l)
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)
} }
require.Equal(t, len(expectedLines), len(nonEmptyLines))
for i, expected := range expectedLines {
require.Regexp(t, expected, nonEmptyLines[i])
} }
} }
func TestClient_Create(t *testing.T) { func TestClient_Create(t *testing.T) {
t.Parallel()
var ( var (
orgID = "dead" orgID = "dead"
bucketID = "f00d" bucketID = "f00d"
@ -56,7 +49,7 @@ func TestClient_Create(t *testing.T) {
cli *internal.CLI cli *internal.CLI
params bucket_schema.CreateParams params bucket_schema.CreateParams
cols []api.MeasurementSchemaColumn cols []api.MeasurementSchemaColumn
stdio *mock.Stdio stdio *mock.MockStdIO
} }
type optFn func(t *testing.T, a *setupArgs) type optFn func(t *testing.T, a *setupArgs)
@ -186,7 +179,6 @@ func TestClient_Create(t *testing.T) {
name: "bucket not found", name: "bucket not found",
opts: opts( opts: opts(
withArgs(args{OrgName: "my-org", BucketName: "my-bucket", ColumnsFile: "columns.csv"}), withArgs(args{OrgName: "my-org", BucketName: "my-bucket", ColumnsFile: "columns.csv"}),
expGetBuckets(), expGetBuckets(),
), ),
expErr: `bucket "my-bucket" not found`, expErr: `bucket "my-bucket" not found`,
@ -196,7 +188,6 @@ func TestClient_Create(t *testing.T) {
opts: opts( opts: opts(
withArgs(args{OrgName: "my-org", BucketName: "my-bucket", Name: "cpu", ColumnsFile: "columns.csv"}), withArgs(args{OrgName: "my-org", BucketName: "my-bucket", Name: "cpu", ColumnsFile: "columns.csv"}),
withCols("columns.csv"), withCols("columns.csv"),
expGetBuckets("my-bucket"), expGetBuckets("my-bucket"),
expCreate(), expCreate(),
), ),
@ -210,7 +201,6 @@ func TestClient_Create(t *testing.T) {
opts: opts( opts: opts(
withArgs(args{OrgName: "my-org", BucketName: "my-bucket", Name: "cpu", ColumnsFile: "columns.json"}), withArgs(args{OrgName: "my-org", BucketName: "my-bucket", Name: "cpu", ColumnsFile: "columns.json"}),
withCols("columns.csv"), withCols("columns.csv"),
expGetBuckets("my-bucket"), expGetBuckets("my-bucket"),
expCreate(), expCreate(),
), ),
@ -224,7 +214,6 @@ func TestClient_Create(t *testing.T) {
opts: opts( opts: opts(
withArgs(args{OrgName: "my-org", BucketName: "my-bucket", Name: "cpu", ColumnsFile: "columns.ndjson"}), withArgs(args{OrgName: "my-org", BucketName: "my-bucket", Name: "cpu", ColumnsFile: "columns.ndjson"}),
withCols("columns.csv"), withCols("columns.csv"),
expGetBuckets("my-bucket"), expGetBuckets("my-bucket"),
expCreate(), expCreate(),
), ),
@ -238,21 +227,28 @@ func TestClient_Create(t *testing.T) {
opts: opts( opts: opts(
withArgs(args{OrgName: "my-org", BucketName: "my-bucket", Name: "cpu", ColumnsFile: "columns.csv", ExtendedOutput: true}), withArgs(args{OrgName: "my-org", BucketName: "my-bucket", Name: "cpu", ColumnsFile: "columns.csv", ExtendedOutput: true}),
withCols("columns.csv"), withCols("columns.csv"),
expGetBuckets("my-bucket"), expGetBuckets("my-bucket"),
expCreate(), expCreate(),
), ),
expLines: lines( expLines: lines(
`^ID\s+Measurement Name\s+Column Name\s+Column Type\s+Column Data Type\s+Bucket ID$`, `^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 { for _, tc := range cases {
tc := tc
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t) 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{ args := &setupArgs{
buckets: mock.NewMockBucketsApi(ctrl), buckets: mock.NewMockBucketsApi(ctrl),
schemas: mock.NewMockBucketSchemasApi(ctrl), schemas: mock.NewMockBucketSchemasApi(ctrl),
@ -276,13 +272,15 @@ func TestClient_Create(t *testing.T) {
assert.EqualError(t, err, tc.expErr) assert.EqualError(t, err, tc.expErr)
} else { } else {
require.NoError(t, err) require.NoError(t, err)
matchLines(t, tc.expLines, mockIO) matchLines(t, tc.expLines, strings.Split(writtenBytes.String(), "\n"))
} }
}) })
} }
} }
func TestClient_Update(t *testing.T) { func TestClient_Update(t *testing.T) {
t.Parallel()
var ( var (
orgID = "dead" orgID = "dead"
bucketID = "f00d" bucketID = "f00d"
@ -297,7 +295,7 @@ func TestClient_Update(t *testing.T) {
cli *internal.CLI cli *internal.CLI
params bucket_schema.UpdateParams params bucket_schema.UpdateParams
cols []api.MeasurementSchemaColumn cols []api.MeasurementSchemaColumn
stdio *mock.Stdio stdio *mock.MockStdIO
} }
type optFn func(t *testing.T, a *setupArgs) type optFn func(t *testing.T, a *setupArgs)
@ -485,22 +483,30 @@ func TestClient_Update(t *testing.T) {
opts: opts( opts: opts(
withArgs(args{OrgName: "my-org", BucketName: "my-bucket", Name: "cpu", ColumnsFile: "columns.csv", ExtendedOutput: true}), withArgs(args{OrgName: "my-org", BucketName: "my-bucket", Name: "cpu", ColumnsFile: "columns.csv", ExtendedOutput: true}),
withCols("columns.csv"), withCols("columns.csv"),
expGetBuckets("my-bucket"), expGetBuckets("my-bucket"),
expGetMeasurementSchema(), expGetMeasurementSchema(),
expUpdate(), expUpdate(),
), ),
expLines: lines( expLines: lines(
`^ID\s+Measurement Name\s+Column Name\s+Column Type\s+Column Data Type\s+Bucket ID$`, `^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 { for _, tc := range cases {
tc := tc
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t) 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{ args := &setupArgs{
buckets: mock.NewMockBucketsApi(ctrl), buckets: mock.NewMockBucketsApi(ctrl),
schemas: mock.NewMockBucketSchemasApi(ctrl), schemas: mock.NewMockBucketSchemasApi(ctrl),
@ -524,13 +530,15 @@ func TestClient_Update(t *testing.T) {
assert.EqualError(t, err, tc.expErr) assert.EqualError(t, err, tc.expErr)
} else { } else {
require.NoError(t, err) require.NoError(t, err)
matchLines(t, tc.expLines, mockIO) matchLines(t, tc.expLines, strings.Split(writtenBytes.String(), "\n"))
} }
}) })
} }
} }
func TestClient_List(t *testing.T) { func TestClient_List(t *testing.T) {
t.Parallel()
var ( var (
orgID = "dead" orgID = "dead"
bucketID = "f00d" bucketID = "f00d"
@ -545,7 +553,7 @@ func TestClient_List(t *testing.T) {
cli *internal.CLI cli *internal.CLI
params bucket_schema.ListParams params bucket_schema.ListParams
cols []api.MeasurementSchemaColumn cols []api.MeasurementSchemaColumn
stdio *mock.Stdio stdio *mock.MockStdIO
} }
type optFn func(t *testing.T, a *setupArgs) type optFn func(t *testing.T, a *setupArgs)
@ -676,11 +684,10 @@ func TestClient_List(t *testing.T) {
expErr: `bucket "my-bucket" not found`, expErr: `bucket "my-bucket" not found`,
}, },
{ {
name: "update succeeds", name: "list succeeds",
opts: opts( opts: opts(
withArgs(args{OrgName: "my-org", BucketName: "my-bucket", Name: "cpu"}), withArgs(args{OrgName: "my-org", BucketName: "my-bucket", Name: "cpu"}),
withCols("columns.csv"), withCols("columns.csv"),
expGetBuckets("my-bucket"), expGetBuckets("my-bucket"),
expGetMeasurementSchemas(), expGetMeasurementSchemas(),
), ),
@ -690,25 +697,32 @@ func TestClient_List(t *testing.T) {
), ),
}, },
{ {
name: "update succeeds extended output", name: "list succeeds extended output",
opts: opts( opts: opts(
withArgs(args{OrgName: "my-org", BucketName: "my-bucket", Name: "cpu", ExtendedOutput: true}), withArgs(args{OrgName: "my-org", BucketName: "my-bucket", Name: "cpu", ExtendedOutput: true}),
withCols("columns.csv"), withCols("columns.csv"),
expGetBuckets("my-bucket"), expGetBuckets("my-bucket"),
expGetMeasurementSchemas(), expGetMeasurementSchemas(),
), ),
expLines: lines( expLines: lines(
`^ID\s+Measurement Name\s+Column Name\s+Column Type\s+Column Data Type\s+Bucket ID$`, `^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 { for _, tc := range cases {
tc := tc
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t) 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{ args := &setupArgs{
buckets: mock.NewMockBucketsApi(ctrl), buckets: mock.NewMockBucketsApi(ctrl),
schemas: mock.NewMockBucketSchemasApi(ctrl), schemas: mock.NewMockBucketSchemasApi(ctrl),
@ -732,7 +746,7 @@ func TestClient_List(t *testing.T) {
assert.EqualError(t, err, tc.expErr) assert.EqualError(t, err, tc.expErr)
} else { } else {
require.NoError(t, err) require.NoError(t, err)
matchLines(t, tc.expLines, mockIO) matchLines(t, tc.expLines, strings.Split(writtenBytes.String(), "\n"))
} }
}) })
} }

View File

@ -14,9 +14,12 @@ type csvColumn struct {
DataType *api.ColumnDataType `csv:"data_type,omitempty"` DataType *api.ColumnDataType `csv:"data_type,omitempty"`
} }
func init() {
gocsv.FailIfUnmatchedStructTags = true
}
func decodeCSV(r io.Reader) ([]api.MeasurementSchemaColumn, error) { func decodeCSV(r io.Reader) ([]api.MeasurementSchemaColumn, error) {
var cols []csvColumn var cols []csvColumn
gocsv.FailIfUnmatchedStructTags = true
err := gocsv.Unmarshal(r, &cols) err := gocsv.Unmarshal(r, &cols)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to decode CSV: %w", err) return nil, fmt.Errorf("failed to decode CSV: %w", err)

7
internal/mock/README.md Normal file
View File

@ -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

View File

@ -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)
}

View File

@ -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)
}

View File

@ -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)
}

View File

@ -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)
}

View File

@ -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)
}

View File

@ -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)
}

View File

@ -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)
}

View File

@ -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)
}

View File

@ -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)
}

125
internal/mock/config.gen.go Normal file
View File

@ -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)
}

View File

@ -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()
}

View File

@ -1,4 +1,13 @@
package mock package mock
//go:generate mockgen -package mock -destination api_bucket_schemas.gen.go github.com/influxdata/influx-cli/v2/internal/api BucketSchemasApi // HTTP API mocks
//go:generate 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_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

121
internal/mock/stdio.gen.go Normal file
View File

@ -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)
}

View File

@ -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()
}

View File

@ -1,10 +1,12 @@
package internal_test package internal_test
import ( import (
"bytes"
"context" "context"
"errors" "errors"
"testing" "testing"
"github.com/golang/mock/gomock"
"github.com/influxdata/influx-cli/v2/internal" "github.com/influxdata/influx-cli/v2/internal"
"github.com/influxdata/influx-cli/v2/internal/api" "github.com/influxdata/influx-cli/v2/internal/api"
"github.com/influxdata/influx-cli/v2/internal/mock" "github.com/influxdata/influx-cli/v2/internal/mock"
@ -14,28 +16,28 @@ import (
func Test_PingSuccess(t *testing.T) { func Test_PingSuccess(t *testing.T) {
t.Parallel() t.Parallel()
client := &mock.HealthApi{ ctrl := gomock.NewController(t)
GetHealthExecuteFn: func(req api.ApiGetHealthRequest) (api.HealthCheck, error) { client := mock.NewMockHealthApi(ctrl)
return api.HealthCheck{Status: api.HEALTHCHECKSTATUS_PASS}, nil 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} cli := &internal.CLI{StdIO: stdio}
require.NoError(t, cli.Ping(context.Background(), client)) 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) { func Test_PingFailedRequest(t *testing.T) {
t.Parallel() t.Parallel()
e := "the internet is down" e := "the internet is down"
client := &mock.HealthApi{ ctrl := gomock.NewController(t)
GetHealthExecuteFn: func(api.ApiGetHealthRequest) (api.HealthCheck, error) { client := mock.NewMockHealthApi(ctrl)
return api.HealthCheck{}, errors.New(e) client.EXPECT().GetHealth(gomock.Any()).Return(api.ApiGetHealthRequest{ApiService: client})
}, client.EXPECT().GetHealthExecute(gomock.Any()).Return(api.HealthCheck{}, errors.New(e))
}
cli := &internal.CLI{} cli := &internal.CLI{}
err := cli.Ping(context.Background(), client) err := cli.Ping(context.Background(), client)
@ -47,11 +49,11 @@ func Test_PingFailedStatus(t *testing.T) {
t.Parallel() t.Parallel()
e := "I broke" e := "I broke"
client := &mock.HealthApi{ ctrl := gomock.NewController(t)
GetHealthExecuteFn: func(api.ApiGetHealthRequest) (api.HealthCheck, error) { client := mock.NewMockHealthApi(ctrl)
return api.HealthCheck{}, &api.HealthCheck{Status: api.HEALTHCHECKSTATUS_FAIL, Message: &e} 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{} cli := &internal.CLI{}
err := cli.Ping(context.Background(), client) err := cli.Ping(context.Background(), client)
@ -63,11 +65,11 @@ func Test_PingFailedStatusNoMessage(t *testing.T) {
t.Parallel() t.Parallel()
name := "foo" name := "foo"
client := &mock.HealthApi{ ctrl := gomock.NewController(t)
GetHealthExecuteFn: func(api.ApiGetHealthRequest) (api.HealthCheck, error) { client := mock.NewMockHealthApi(ctrl)
return api.HealthCheck{}, &api.HealthCheck{Status: api.HEALTHCHECKSTATUS_FAIL, Name: name} 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{} cli := &internal.CLI{}
err := cli.Ping(context.Background(), client) err := cli.Ping(context.Background(), client)

View File

@ -1,6 +1,7 @@
package internal_test package internal_test
import ( import (
"bytes"
"context" "context"
"errors" "errors"
"fmt" "fmt"
@ -8,29 +9,28 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/golang/mock/gomock"
"github.com/influxdata/influx-cli/v2/internal" "github.com/influxdata/influx-cli/v2/internal"
"github.com/influxdata/influx-cli/v2/internal/api" "github.com/influxdata/influx-cli/v2/internal/api"
"github.com/influxdata/influx-cli/v2/internal/config" "github.com/influxdata/influx-cli/v2/internal/config"
"github.com/influxdata/influx-cli/v2/internal/duration" "github.com/influxdata/influx-cli/v2/internal/duration"
"github.com/influxdata/influx-cli/v2/internal/mock" "github.com/influxdata/influx-cli/v2/internal/mock"
"github.com/stretchr/testify/assert"
tmock "github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
func Test_SetupConfigNameCollision(t *testing.T) { func Test_SetupConfigNameCollision(t *testing.T) {
t.Parallel() t.Parallel()
client := &mock.SetupApi{ ctrl := gomock.NewController(t)
GetSetupExecuteFn: func(api.ApiGetSetupRequest) (api.InlineResponse200, error) { client := mock.NewMockSetupApi(ctrl)
return api.InlineResponse200{Allowed: api.PtrBool(true)}, nil 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" cfg := "foo"
configSvc := &mock.ConfigService{ configSvc := mock.NewMockConfigService(ctrl)
ListConfigsFn: func() (config.Configs, error) { configSvc.EXPECT().ListConfigs().Return(map[string]config.Config{cfg: {}}, nil)
return map[string]config.Config{cfg: {}}, nil
},
}
cli := &internal.CLI{ConfigService: configSvc} cli := &internal.CLI{ConfigService: configSvc}
err := cli.Setup(context.Background(), client, &internal.SetupParams{ConfigName: cfg}) 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) { func Test_SetupConfigNameRequired(t *testing.T) {
t.Parallel() t.Parallel()
client := &mock.SetupApi{ ctrl := gomock.NewController(t)
GetSetupExecuteFn: func(api.ApiGetSetupRequest) (api.InlineResponse200, error) { client := mock.NewMockSetupApi(ctrl)
return api.InlineResponse200{Allowed: api.PtrBool(true)}, nil 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{ configSvc := mock.NewMockConfigService(ctrl)
ListConfigsFn: func() (config.Configs, error) { configSvc.EXPECT().ListConfigs().Return(map[string]config.Config{"foo": {}}, nil)
return map[string]config.Config{"foo": {}}, nil
},
}
cli := &internal.CLI{ConfigService: configSvc} cli := &internal.CLI{ConfigService: configSvc}
err := cli.Setup(context.Background(), client, &internal.SetupParams{}) err := cli.Setup(context.Background(), client, &internal.SetupParams{})
@ -62,18 +58,12 @@ func Test_SetupConfigNameRequired(t *testing.T) {
func Test_SetupAlreadySetup(t *testing.T) { func Test_SetupAlreadySetup(t *testing.T) {
t.Parallel() 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{ configSvc := mock.NewMockConfigService(ctrl)
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
},
}
cli := &internal.CLI{ConfigService: configSvc} cli := &internal.CLI{ConfigService: configSvc}
err := cli.Setup(context.Background(), client, &internal.SetupParams{}) err := cli.Setup(context.Background(), client, &internal.SetupParams{})
@ -85,17 +75,12 @@ func Test_SetupCheckFailed(t *testing.T) {
t.Parallel() t.Parallel()
e := "oh no" e := "oh no"
client := &mock.SetupApi{ ctrl := gomock.NewController(t)
GetSetupExecuteFn: func(api.ApiGetSetupRequest) (api.InlineResponse200, error) { client := mock.NewMockSetupApi(ctrl)
return api.InlineResponse200{}, errors.New(e) client.EXPECT().GetSetup(gomock.Any()).Return(api.ApiGetSetupRequest{ApiService: client})
}, client.EXPECT().GetSetupExecute(gomock.Any()).Return(api.InlineResponse200{}, errors.New(e))
}
configSvc := &mock.ConfigService{ configSvc := mock.NewMockConfigService(ctrl)
ListConfigsFn: func() (config.Configs, error) {
return nil, nil
},
}
cli := &internal.CLI{ConfigService: configSvc} cli := &internal.CLI{ConfigService: configSvc}
err := cli.Setup(context.Background(), client, &internal.SetupParams{}) err := cli.Setup(context.Background(), client, &internal.SetupParams{})
@ -123,40 +108,42 @@ func Test_SetupSuccessNoninteractive(t *testing.T) {
User: &api.UserResponse{Name: params.Username}, User: &api.UserResponse{Name: params.Username},
Bucket: &api.Bucket{Name: params.Bucket}, Bucket: &api.Bucket{Name: params.Bucket},
} }
client := &mock.SetupApi{
GetSetupExecuteFn: func(api.ApiGetSetupRequest) (api.InlineResponse200, error) { ctrl := gomock.NewController(t)
return api.InlineResponse200{Allowed: api.PtrBool(true)}, nil client := mock.NewMockSetupApi(ctrl)
}, client.EXPECT().GetSetup(gomock.Any()).Return(api.ApiGetSetupRequest{ApiService: client})
PostSetupExecuteFn: func(req api.ApiPostSetupRequest) (api.OnboardingResponse, error) { client.EXPECT().GetSetupExecute(gomock.Any()).Return(api.InlineResponse200{Allowed: api.PtrBool(true)}, nil)
body := req.GetOnboardingRequest() client.EXPECT().PostSetup(gomock.Any()).Return(api.ApiPostSetupRequest{ApiService: client})
require.Equal(t, params.Username, body.Username) client.EXPECT().PostSetupExecute(tmock.MatchedBy(func(in api.ApiPostSetupRequest) bool {
require.Equal(t, params.Password, *body.Password) body := in.GetOnboardingRequest()
require.Equal(t, params.AuthToken, *body.Token) return assert.NotNil(t, body) &&
require.Equal(t, params.Org, body.Org) assert.Equal(t, params.Username, body.Username) &&
require.Equal(t, params.Bucket, body.Bucket) assert.Equal(t, params.Password, *body.Password) &&
require.Equal(t, retentionSecs, *body.RetentionPeriodSeconds) assert.Equal(t, params.AuthToken, *body.Token) &&
return resp, nil 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" host := "fake-host"
configSvc := &mock.ConfigService{ configSvc := mock.NewMockConfigService(ctrl)
ListConfigsFn: func() (config.Configs, error) { configSvc.EXPECT().ListConfigs().Return(nil, nil)
return nil, nil configSvc.EXPECT().CreateConfig(tmock.MatchedBy(func(in config.Config) bool {
}, return assert.Equal(t, params.ConfigName, in.Name) &&
CreateConfigFn: func(cfg config.Config) (config.Config, error) { assert.Equal(t, params.AuthToken, in.Token) &&
require.Equal(t, params.ConfigName, cfg.Name) assert.Equal(t, host, in.Host) &&
require.Equal(t, params.AuthToken, cfg.Token) assert.Equal(t, params.Org, in.Org)
require.Equal(t, host, cfg.Host) })).DoAndReturn(func(in config.Config) (config.Config, error) {
require.Equal(t, params.Org, cfg.Org) return in, nil
return cfg, nil })
},
} stdio := mock.NewMockStdIO(ctrl)
stdio := mock.NewMockStdio(nil, true) bytesWritten := bytes.Buffer{}
stdio.EXPECT().Write(gomock.Any()).DoAndReturn(bytesWritten.Write).AnyTimes()
cli := &internal.CLI{ConfigService: configSvc, ActiveConfig: config.Config{Host: host}, StdIO: stdio} cli := &internal.CLI{ConfigService: configSvc, ActiveConfig: config.Config{Host: host}, StdIO: stdio}
require.NoError(t, cli.Setup(context.Background(), client, &params)) require.NoError(t, cli.Setup(context.Background(), client, &params))
outLines := strings.Split(strings.TrimSpace(stdio.Stdout()), "\n") outLines := strings.Split(strings.TrimSpace(bytesWritten.String()), "\n")
require.Len(t, outLines, 2) require.Len(t, outLines, 2)
header, data := outLines[0], outLines[1] header, data := outLines[0], outLines[1]
require.Regexp(t, "User\\s+Organization\\s+Bucket", header) require.Regexp(t, "User\\s+Organization\\s+Bucket", header)
@ -180,47 +167,49 @@ func Test_SetupSuccessInteractive(t *testing.T) {
User: &api.UserResponse{Name: username}, User: &api.UserResponse{Name: username},
Bucket: &api.Bucket{Name: bucket}, Bucket: &api.Bucket{Name: bucket},
} }
client := &mock.SetupApi{ ctrl := gomock.NewController(t)
GetSetupExecuteFn: func(api.ApiGetSetupRequest) (api.InlineResponse200, error) { client := mock.NewMockSetupApi(ctrl)
return api.InlineResponse200{Allowed: api.PtrBool(true)}, nil client.EXPECT().GetSetup(gomock.Any()).Return(api.ApiGetSetupRequest{ApiService: client})
}, client.EXPECT().GetSetupExecute(gomock.Any()).Return(api.InlineResponse200{Allowed: api.PtrBool(true)}, nil)
PostSetupExecuteFn: func(req api.ApiPostSetupRequest) (api.OnboardingResponse, error) { client.EXPECT().PostSetup(gomock.Any()).Return(api.ApiPostSetupRequest{ApiService: client})
body := req.GetOnboardingRequest() client.EXPECT().PostSetupExecute(tmock.MatchedBy(func(in api.ApiPostSetupRequest) bool {
require.Equal(t, username, body.Username) body := in.GetOnboardingRequest()
require.Equal(t, password, *body.Password) return assert.NotNil(t, body) &&
require.Nil(t, body.Token) assert.Equal(t, username, body.Username) &&
require.Equal(t, org, body.Org) assert.Equal(t, password, *body.Password) &&
require.Equal(t, bucket, body.Bucket) assert.Nil(t, body.Token) &&
require.Equal(t, retentionSecs, *body.RetentionPeriodSeconds) assert.Equal(t, org, body.Org) &&
return resp, nil assert.Equal(t, bucket, body.Bucket) &&
}, assert.Equal(t, retentionSecs, *body.RetentionPeriodSeconds)
} })).Return(resp, nil)
host := "fake-host" host := "fake-host"
configSvc := &mock.ConfigService{ configSvc := mock.NewMockConfigService(ctrl)
ListConfigsFn: func() (config.Configs, error) { configSvc.EXPECT().ListConfigs().Return(nil, nil)
return nil, nil configSvc.EXPECT().CreateConfig(tmock.MatchedBy(func(in config.Config) bool {
}, return assert.Equal(t, config.DefaultConfig.Name, in.Name) &&
CreateConfigFn: func(cfg config.Config) (config.Config, error) { assert.Equal(t, token, in.Token) &&
require.Equal(t, config.DefaultConfig.Name, cfg.Name) assert.Equal(t, host, in.Host) &&
require.Equal(t, token, cfg.Token) assert.Equal(t, org, in.Org)
require.Equal(t, host, cfg.Host) })).DoAndReturn(func(in config.Config) (config.Config, error) {
require.Equal(t, org, cfg.Org) return in, nil
return cfg, nil })
},
} stdio := mock.NewMockStdIO(ctrl)
stdio := mock.NewMockStdio(map[string]string{ bytesWritten := bytes.Buffer{}
"Please type your primary username": username, stdio.EXPECT().Write(gomock.Any()).DoAndReturn(bytesWritten.Write).AnyTimes()
"Please type your password": password, stdio.EXPECT().Banner(gomock.Any())
"Please type your password again": password, stdio.EXPECT().GetStringInput(gomock.Eq("Please type your primary username"), gomock.Any()).Return(username, nil)
"Please type your primary organization name": org, stdio.EXPECT().GetPassword(gomock.Eq("Please type your password"), gomock.Any()).Return(password, nil)
"Please type your primary bucket name": bucket, stdio.EXPECT().GetPassword(gomock.Eq("Please type your password again"), gomock.Any()).Return(password, nil)
"Please type your retention period in hours, or 0 for infinite": strconv.Itoa(retentionHrs), stdio.EXPECT().GetStringInput(gomock.Eq("Please type your primary organization name"), gomock.Any()).Return(org, nil)
}, true) 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} cli := &internal.CLI{ConfigService: configSvc, ActiveConfig: config.Config{Host: host}, StdIO: stdio}
require.NoError(t, cli.Setup(context.Background(), client, &internal.SetupParams{})) 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) require.Len(t, outLines, 2)
header, data := outLines[0], outLines[1] header, data := outLines[0], outLines[1]
require.Regexp(t, "User\\s+Organization\\s+Bucket", header) require.Regexp(t, "User\\s+Organization\\s+Bucket", header)
@ -240,19 +229,17 @@ func Test_SetupPasswordParamToShort(t *testing.T) {
Retention: fmt.Sprintf("%ds", retentionSecs), Retention: fmt.Sprintf("%ds", retentionSecs),
Force: false, Force: false,
} }
client := &mock.SetupApi{
GetSetupExecuteFn: func(api.ApiGetSetupRequest) (api.InlineResponse200, error) { ctrl := gomock.NewController(t)
return api.InlineResponse200{Allowed: api.PtrBool(true)}, nil 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" host := "fake-host"
configSvc := &mock.ConfigService{ configSvc := mock.NewMockConfigService(ctrl)
ListConfigsFn: func() (config.Configs, error) { configSvc.EXPECT().ListConfigs().Return(nil, nil)
return nil, nil
}, stdio := mock.NewMockStdIO(ctrl)
}
stdio := mock.NewMockStdio(nil, false)
cli := &internal.CLI{ConfigService: configSvc, ActiveConfig: config.Config{Host: host}, StdIO: stdio} cli := &internal.CLI{ConfigService: configSvc, ActiveConfig: config.Config{Host: host}, StdIO: stdio}
err := cli.Setup(context.Background(), client, &params) err := cli.Setup(context.Background(), client, &params)
require.Equal(t, internal.ErrPasswordIsTooShort, err) require.Equal(t, internal.ErrPasswordIsTooShort, err)
@ -271,19 +258,20 @@ func Test_SetupCancelAtConfirmation(t *testing.T) {
Retention: fmt.Sprintf("%ds", retentionSecs), Retention: fmt.Sprintf("%ds", retentionSecs),
Force: false, Force: false,
} }
client := &mock.SetupApi{
GetSetupExecuteFn: func(api.ApiGetSetupRequest) (api.InlineResponse200, error) { ctrl := gomock.NewController(t)
return api.InlineResponse200{Allowed: api.PtrBool(true)}, nil 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" host := "fake-host"
configSvc := &mock.ConfigService{ configSvc := mock.NewMockConfigService(ctrl)
ListConfigsFn: func() (config.Configs, error) { configSvc.EXPECT().ListConfigs().Return(nil, nil)
return nil, nil
}, stdio := mock.NewMockStdIO(ctrl)
} stdio.EXPECT().Banner(gomock.Any())
stdio := mock.NewMockStdio(nil, false) stdio.EXPECT().GetConfirm(gomock.Any()).Return(false)
cli := &internal.CLI{ConfigService: configSvc, ActiveConfig: config.Config{Host: host}, StdIO: stdio} cli := &internal.CLI{ConfigService: configSvc, ActiveConfig: config.Config{Host: host}, StdIO: stdio}
err := cli.Setup(context.Background(), client, &params) err := cli.Setup(context.Background(), client, &params)
require.Equal(t, internal.ErrSetupCanceled, err) require.Equal(t, internal.ErrSetupCanceled, err)

View File

@ -8,10 +8,13 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/golang/mock/gomock"
"github.com/influxdata/influx-cli/v2/internal" "github.com/influxdata/influx-cli/v2/internal"
"github.com/influxdata/influx-cli/v2/internal/api" "github.com/influxdata/influx-cli/v2/internal/api"
"github.com/influxdata/influx-cli/v2/internal/config" "github.com/influxdata/influx-cli/v2/internal/config"
"github.com/influxdata/influx-cli/v2/internal/mock" "github.com/influxdata/influx-cli/v2/internal/mock"
"github.com/stretchr/testify/assert"
tmock "github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require" "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) { func TestWriteByIDs(t *testing.T) {
t.Parallel()
inLines := []string{"fake line protocol 1", "fake line protocol 2", "fake line protocol 3"} inLines := []string{"fake line protocol 1", "fake line protocol 2", "fake line protocol 3"}
mockReader := bufferReader{} mockReader := bufferReader{}
for _, l := range inLines { for _, l := range inLines {
@ -66,26 +71,25 @@ func TestWriteByIDs(t *testing.T) {
} }
cli := internal.CLI{ActiveConfig: config.Config{Org: "my-default-org"}} cli := internal.CLI{ActiveConfig: config.Config{Org: "my-default-org"}}
ctrl := gomock.NewController(t)
client := mock.NewMockWriteApi(ctrl)
var writtenLines []string var writtenLines []string
client := mock.WriteApi{ client.EXPECT().PostWrite(gomock.Any()).Return(api.ApiPostWriteRequest{ApiService: client}).Times(len(inLines))
PostWriteExecuteFn: func(req api.ApiPostWriteRequest) error { client.EXPECT().PostWriteExecute(tmock.MatchedBy(func(in api.ApiPostWriteRequest) bool {
// Make sure query params are set. return assert.Equal(t, params.OrgID, *in.GetOrg()) &&
require.Equal(t, params.OrgID, *req.GetOrg()) assert.Equal(t, params.BucketID, *in.GetBucket()) &&
require.Equal(t, params.BucketID, *req.GetBucket()) assert.Equal(t, params.Precision, *in.GetPrecision()) &&
require.Equal(t, params.Precision, *req.GetPrecision()) assert.Equal(t, "gzip", *in.GetContentEncoding()) // Make sure the body is properly marked for compression.
})).DoAndReturn(func(in api.ApiPostWriteRequest) error {
// Make sure the body is properly marked for compression, and record what was sent. writtenLines = append(writtenLines, string(in.GetBody()))
require.Equal(t, "gzip", *req.GetContentEncoding())
writtenLines = append(writtenLines, string(req.GetBody()))
return nil return nil
}, }).Times(len(inLines))
}
clients := internal.WriteClients{ clients := internal.WriteClients{
Reader: &mockReader, Reader: &mockReader,
Throttler: &mockThrottler, Throttler: &mockThrottler,
Writer: &mockBatcher, Writer: &mockBatcher,
Client: &client, Client: client,
} }
require.NoError(t, cli.Write(context.Background(), &clients, &params)) require.NoError(t, cli.Write(context.Background(), &clients, &params))
@ -94,6 +98,8 @@ func TestWriteByIDs(t *testing.T) {
} }
func TestWriteByNames(t *testing.T) { func TestWriteByNames(t *testing.T) {
t.Parallel()
inLines := []string{"fake line protocol 1", "fake line protocol 2", "fake line protocol 3"} inLines := []string{"fake line protocol 1", "fake line protocol 2", "fake line protocol 3"}
mockReader := bufferReader{} mockReader := bufferReader{}
for _, l := range inLines { for _, l := range inLines {
@ -110,26 +116,25 @@ func TestWriteByNames(t *testing.T) {
} }
cli := internal.CLI{ActiveConfig: config.Config{Org: "my-default-org"}} cli := internal.CLI{ActiveConfig: config.Config{Org: "my-default-org"}}
ctrl := gomock.NewController(t)
client := mock.NewMockWriteApi(ctrl)
var writtenLines []string var writtenLines []string
client := mock.WriteApi{ client.EXPECT().PostWrite(gomock.Any()).Return(api.ApiPostWriteRequest{ApiService: client}).Times(len(inLines))
PostWriteExecuteFn: func(req api.ApiPostWriteRequest) error { client.EXPECT().PostWriteExecute(tmock.MatchedBy(func(in api.ApiPostWriteRequest) bool {
// Make sure query params are set. return assert.Equal(t, params.OrgName, *in.GetOrg()) &&
require.Equal(t, params.OrgName, *req.GetOrg()) assert.Equal(t, params.BucketName, *in.GetBucket()) &&
require.Equal(t, params.BucketName, *req.GetBucket()) assert.Equal(t, params.Precision, *in.GetPrecision()) &&
require.Equal(t, params.Precision, *req.GetPrecision()) assert.Equal(t, "gzip", *in.GetContentEncoding()) // Make sure the body is properly marked for compression.
})).DoAndReturn(func(in api.ApiPostWriteRequest) error {
// Make sure the body is properly marked for compression, and record what was sent. writtenLines = append(writtenLines, string(in.GetBody()))
require.Equal(t, "gzip", *req.GetContentEncoding())
writtenLines = append(writtenLines, string(req.GetBody()))
return nil return nil
}, }).Times(len(inLines))
}
clients := internal.WriteClients{ clients := internal.WriteClients{
Reader: &mockReader, Reader: &mockReader,
Throttler: &mockThrottler, Throttler: &mockThrottler,
Writer: &mockBatcher, Writer: &mockBatcher,
Client: &client, Client: client,
} }
require.NoError(t, cli.Write(context.Background(), &clients, &params)) require.NoError(t, cli.Write(context.Background(), &clients, &params))
@ -138,6 +143,8 @@ func TestWriteByNames(t *testing.T) {
} }
func TestWriteOrgFromConfig(t *testing.T) { func TestWriteOrgFromConfig(t *testing.T) {
t.Parallel()
inLines := []string{"fake line protocol 1", "fake line protocol 2", "fake line protocol 3"} inLines := []string{"fake line protocol 1", "fake line protocol 2", "fake line protocol 3"}
mockReader := bufferReader{} mockReader := bufferReader{}
for _, l := range inLines { for _, l := range inLines {
@ -153,26 +160,25 @@ func TestWriteOrgFromConfig(t *testing.T) {
} }
cli := internal.CLI{ActiveConfig: config.Config{Org: "my-default-org"}} cli := internal.CLI{ActiveConfig: config.Config{Org: "my-default-org"}}
ctrl := gomock.NewController(t)
client := mock.NewMockWriteApi(ctrl)
var writtenLines []string var writtenLines []string
client := mock.WriteApi{ client.EXPECT().PostWrite(gomock.Any()).Return(api.ApiPostWriteRequest{ApiService: client}).Times(len(inLines))
PostWriteExecuteFn: func(req api.ApiPostWriteRequest) error { client.EXPECT().PostWriteExecute(tmock.MatchedBy(func(in api.ApiPostWriteRequest) bool {
// Make sure query params are set. return assert.Equal(t, cli.ActiveConfig.Org, *in.GetOrg()) &&
require.Equal(t, cli.ActiveConfig.Org, *req.GetOrg()) assert.Equal(t, params.BucketName, *in.GetBucket()) &&
require.Equal(t, params.BucketName, *req.GetBucket()) assert.Equal(t, params.Precision, *in.GetPrecision()) &&
require.Equal(t, params.Precision, *req.GetPrecision()) assert.Equal(t, "gzip", *in.GetContentEncoding()) // Make sure the body is properly marked for compression.
})).DoAndReturn(func(in api.ApiPostWriteRequest) error {
// Make sure the body is properly marked for compression, and record what was sent. writtenLines = append(writtenLines, string(in.GetBody()))
require.Equal(t, "gzip", *req.GetContentEncoding())
writtenLines = append(writtenLines, string(req.GetBody()))
return nil return nil
}, }).Times(len(inLines))
}
clients := internal.WriteClients{ clients := internal.WriteClients{
Reader: &mockReader, Reader: &mockReader,
Throttler: &mockThrottler, Throttler: &mockThrottler,
Writer: &mockBatcher, Writer: &mockBatcher,
Client: &client, Client: client,
} }
require.NoError(t, cli.Write(context.Background(), &clients, &params)) require.NoError(t, cli.Write(context.Background(), &clients, &params))
@ -181,6 +187,8 @@ func TestWriteOrgFromConfig(t *testing.T) {
} }
func TestWriteDryRun(t *testing.T) { func TestWriteDryRun(t *testing.T) {
t.Parallel()
inLines := ` inLines := `
fake line protocol 1 fake line protocol 1
fake line protocol 2 fake line protocol 2
@ -189,9 +197,14 @@ fake line protocol 3
mockReader := bufferReader{} mockReader := bufferReader{}
_, err := io.Copy(&mockReader.buf, strings.NewReader(inLines)) _, err := io.Copy(&mockReader.buf, strings.NewReader(inLines))
require.NoError(t, err) 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} cli := internal.CLI{ActiveConfig: config.Config{Org: "my-default-org"}, StdIO: stdio}
require.NoError(t, cli.WriteDryRun(context.Background(), &mockReader)) require.NoError(t, cli.WriteDryRun(context.Background(), &mockReader))
require.Equal(t, inLines, stdio.Stdout()) require.Equal(t, inLines, bytesWritten.String())
} }

View File

@ -11,6 +11,7 @@ package influxcli
import ( import (
_ "github.com/daixiang0/gci" _ "github.com/daixiang0/gci"
_ "github.com/golang/mock/mockgen"
_ "golang.org/x/tools/cmd/goimports" _ "golang.org/x/tools/cmd/goimports"
_ "honnef.co/go/tools/cmd/staticcheck" _ "honnef.co/go/tools/cmd/staticcheck"
) )