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

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

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

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

View File

@ -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, &params))
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, &params)
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, &params)
require.Equal(t, internal.ErrSetupCanceled, err)

View File

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