diff --git a/.golangci.yml b/.golangci.yml index 5dc9deb0a..86b4be931 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,9 +1,5 @@ run: - tests: false - -linters: - goimports: - local-prefixes: github.com/stripe/stripe-cli + tests: true linters: enable-all: true @@ -16,3 +12,16 @@ linters: - maligned - unparam - stylecheck + +linters-settings: + goimports: + local-prefixes: github.com/stripe/stripe-cli + misspell: + locale: US + +issues: + exclude-rules: + - path: _test\.go + linters: + - dupl + exclude-use-default: false diff --git a/Makefile b/Makefile index 1b2690ef1..08df7050f 100644 --- a/Makefile +++ b/Makefile @@ -31,7 +31,7 @@ fmt: # Run all the linters lint: - # TODO: fix tests and disabled linter issues + # TODO: fix disabled linter issues ./bin/golangci-lint run ./... ./bin/misspell -error **/*.go .PHONY: lint diff --git a/go.mod b/go.mod index 7c72bff4b..3ca51c2c4 100644 --- a/go.mod +++ b/go.mod @@ -11,6 +11,7 @@ require ( github.com/konsorten/go-windows-terminal-sequences v1.0.2 // indirect github.com/logrusorgru/aurora v0.0.0-20190803045625-94edacc10f9b github.com/magiconair/properties v1.8.1 // indirect + github.com/mattn/go-isatty v0.0.9 // indirect github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b // indirect github.com/mitchellh/go-homedir v1.1.0 github.com/onsi/ginkgo v1.8.0 // indirect diff --git a/go.sum b/go.sum index c37801fa0..8f9597f6f 100644 --- a/go.sum +++ b/go.sum @@ -83,6 +83,8 @@ github.com/mattn/go-colorable v0.1.2 h1:/bC9yWikZXAL9uJdulbSfyVNIR3n3trXl+v8+1sx github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-isatty v0.0.8 h1:HLtExJ+uU2HOZ+wI0Tt5DtUDrx8yhUqDcp7fYERX4CE= github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-isatty v0.0.9 h1:d5US/mDsogSGW37IV293h//ZFaeajb69h+EHFsv2xGg= +github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b h1:j7+1HpAFS1zy5+Q4qx1fWh90gTKwiN4QCGoY9TWyyO4= github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE= diff --git a/pkg/cmd/config.go b/pkg/cmd/config.go index 53b3e6d75..b98a716dc 100644 --- a/pkg/cmd/config.go +++ b/pkg/cmd/config.go @@ -2,6 +2,7 @@ package cmd import ( "github.com/spf13/cobra" + "github.com/stripe/stripe-cli/pkg/config" ) diff --git a/pkg/cmd/listen.go b/pkg/cmd/listen.go index 41f79b047..5d1b67c5c 100644 --- a/pkg/cmd/listen.go +++ b/pkg/cmd/listen.go @@ -62,7 +62,7 @@ to your localhost: RunE: lc.runListenCmd, } - lc.cmd.Flags().StringSliceVarP(&lc.events, "events", "e", []string{"*"}, "A comma-separated list of which webhook events\nto listen for. For a list of all possible events, see:\nhttps://stripe.com/docs/api/events/types") + lc.cmd.Flags().StringSliceVarP(&lc.events, "events", "e", []string{"*"}, "A comma-separated list of which webhook events to listen for. For a list of all possible events, see: https://stripe.com/docs/api/events/types") lc.cmd.Flags().StringVarP(&lc.forwardURL, "forward-to", "f", "", "The URL to forward webhook events to") lc.cmd.Flags().StringVarP(&lc.forwardConnectURL, "forward-connect-to", "c", "", "The URL to forward Connect webhook events to (default: same as normal events)") lc.cmd.Flags().BoolVarP(&lc.latestAPIVersion, "latest", "l", false, "Receive events formatted with the latest API version (default: your account's default API version)") diff --git a/pkg/cmd/listen_test.go b/pkg/cmd/listen_test.go index 76e4cb410..1133b3353 100644 --- a/pkg/cmd/listen_test.go +++ b/pkg/cmd/listen_test.go @@ -3,20 +3,20 @@ package cmd import ( "testing" - assert "github.com/stretchr/testify/require" + "github.com/stretchr/testify/require" "github.com/stripe/stripe-cli/pkg/requests" ) func TestParseUrl(t *testing.T) { - assert.Equal(t, "http://example.com/foo", parseURL("http://example.com/foo")) - assert.Equal(t, "https://example.com/foo", parseURL("https://example.com/foo")) + require.Equal(t, "http://example.com/foo", parseURL("http://example.com/foo")) + require.Equal(t, "https://example.com/foo", parseURL("https://example.com/foo")) - assert.Equal(t, "http://example.com/foo", parseURL("example.com/foo")) + require.Equal(t, "http://example.com/foo", parseURL("example.com/foo")) - assert.Equal(t, "http://localhost/foo", parseURL("/foo")) + require.Equal(t, "http://localhost/foo", parseURL("/foo")) - assert.Equal(t, "http://localhost:3000", parseURL("3000")) + require.Equal(t, "http://localhost:3000", parseURL("3000")) } func TestBuildEndpointRoutes(t *testing.T) { @@ -39,11 +39,11 @@ func TestBuildEndpointRoutes(t *testing.T) { } output := buildEndpointRoutes(endpointList, localURL, localURL) - assert.Equal(t, 2, len(output)) - assert.Equal(t, "http://localhost/hooks", output[0].URL) - assert.Equal(t, false, output[0].Connect) - assert.Equal(t, []string{"*"}, output[0].EventTypes) - assert.Equal(t, "http://localhost/connect-hooks", output[1].URL) - assert.Equal(t, true, output[1].Connect) - assert.Equal(t, []string{"*"}, output[1].EventTypes) + require.Equal(t, 2, len(output)) + require.Equal(t, "http://localhost/hooks", output[0].URL) + require.Equal(t, false, output[0].Connect) + require.Equal(t, []string{"*"}, output[0].EventTypes) + require.Equal(t, "http://localhost/connect-hooks", output[1].URL) + require.Equal(t, true, output[1].Connect) + require.Equal(t, []string{"*"}, output[1].EventTypes) } diff --git a/pkg/cmd/resource/namespace_test.go b/pkg/cmd/resource/namespace_test.go index 1a78d06d7..cf160a7e4 100644 --- a/pkg/cmd/resource/namespace_test.go +++ b/pkg/cmd/resource/namespace_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/spf13/cobra" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestNewNamespaceCmd_NonEmptyName(t *testing.T) { @@ -12,12 +12,12 @@ func TestNewNamespaceCmd_NonEmptyName(t *testing.T) { nsc := NewNamespaceCmd(rootCmd, "foo") - assert.Equal(t, "foo", nsc.Name) - assert.True(t, rootCmd.HasSubCommands()) + require.Equal(t, "foo", nsc.Name) + require.True(t, rootCmd.HasSubCommands()) val, ok := rootCmd.Annotations["foo"] - assert.True(t, ok) - assert.Equal(t, "namespace", val) - assert.Contains(t, nsc.Cmd.UsageTemplate(), "Available Resources") + require.True(t, ok) + require.Equal(t, "namespace", val) + require.Contains(t, nsc.Cmd.UsageTemplate(), "Available Resources") } func TestNewNamespaceCmd_EmptyName(t *testing.T) { @@ -25,9 +25,9 @@ func TestNewNamespaceCmd_EmptyName(t *testing.T) { nsc := NewNamespaceCmd(rootCmd, "") - assert.Equal(t, "", nsc.Name) - assert.False(t, rootCmd.HasSubCommands()) + require.Equal(t, "", nsc.Name) + require.False(t, rootCmd.HasSubCommands()) _, ok := rootCmd.Annotations[""] - assert.False(t, ok) - assert.Contains(t, nsc.Cmd.UsageTemplate(), "Available Resources") + require.False(t, ok) + require.Contains(t, nsc.Cmd.UsageTemplate(), "Available Resources") } diff --git a/pkg/cmd/resource/operation_test.go b/pkg/cmd/resource/operation_test.go index e6cc29787..4eb8ce2e7 100644 --- a/pkg/cmd/resource/operation_test.go +++ b/pkg/cmd/resource/operation_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/spf13/cobra" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/stripe/stripe-cli/pkg/config" ) @@ -14,13 +14,13 @@ func TestNewOperationCmd(t *testing.T) { oc := NewOperationCmd(parentCmd, "foo", "/v1/bars/{id}", "get", &config.Config{}) - assert.Equal(t, "foo", oc.Name) - assert.Equal(t, "/v1/bars/{id}", oc.Path) - assert.Equal(t, "GET", oc.HTTPVerb) - assert.Equal(t, []string{"{id}"}, oc.URLParams) - assert.True(t, parentCmd.HasSubCommands()) + require.Equal(t, "foo", oc.Name) + require.Equal(t, "/v1/bars/{id}", oc.Path) + require.Equal(t, "GET", oc.HTTPVerb) + require.Equal(t, []string{"{id}"}, oc.URLParams) + require.True(t, parentCmd.HasSubCommands()) val, ok := parentCmd.Annotations["foo"] - assert.True(t, ok) - assert.Equal(t, "operation", val) - assert.Contains(t, oc.Cmd.UsageTemplate(), "") + require.True(t, ok) + require.Equal(t, "operation", val) + require.Contains(t, oc.Cmd.UsageTemplate(), "") } diff --git a/pkg/cmd/resource/resource_test.go b/pkg/cmd/resource/resource_test.go index 7a7680c7b..b979d6428 100644 --- a/pkg/cmd/resource/resource_test.go +++ b/pkg/cmd/resource/resource_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/spf13/cobra" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestNewResourceCmd(t *testing.T) { @@ -12,10 +12,10 @@ func TestNewResourceCmd(t *testing.T) { rc := NewResourceCmd(parentCmd, "foo") - assert.Equal(t, "foo", rc.Name) - assert.True(t, parentCmd.HasSubCommands()) + require.Equal(t, "foo", rc.Name) + require.True(t, parentCmd.HasSubCommands()) val, ok := parentCmd.Annotations["foo"] - assert.True(t, ok) - assert.Equal(t, "resource", val) - assert.Contains(t, rc.Cmd.UsageTemplate(), "Available Operations") + require.True(t, ok) + require.Equal(t, "resource", val) + require.Contains(t, rc.Cmd.UsageTemplate(), "Available Operations") } diff --git a/pkg/cmd/resources_test.go b/pkg/cmd/resources_test.go index 07e458b7c..5c2b6c5dc 100644 --- a/pkg/cmd/resources_test.go +++ b/pkg/cmd/resources_test.go @@ -3,14 +3,14 @@ package cmd import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestResources(t *testing.T) { Execute() output, err := executeCommand(rootCmd, "resources") - assert.Contains(t, output, "Available Namespaces:") - assert.Contains(t, output, "Available Resources:") - assert.NoError(t, err) + require.Contains(t, output, "Available Namespaces:") + require.Contains(t, output, "Available Resources:") + require.NoError(t, err) } diff --git a/pkg/cmd/root_test.go b/pkg/cmd/root_test.go index 93df67abb..ddf95752b 100644 --- a/pkg/cmd/root_test.go +++ b/pkg/cmd/root_test.go @@ -6,7 +6,7 @@ import ( "github.com/mitchellh/go-homedir" "github.com/spf13/cobra" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func executeCommand(root *cobra.Command, args ...string) (output string, err error) { @@ -29,21 +29,21 @@ func TestGetPathNoXDG(t *testing.T) { expected, err := homedir.Dir() expected += "/.config/stripe" - assert.Nil(t, err) - assert.Equal(t, actual, expected) + require.Nil(t, err) + require.Equal(t, actual, expected) } func TestGetPathXDG(t *testing.T) { actual := Config.GetProfilesFolder("/some/xdg/path") expected := "/some/xdg/path/stripe" - assert.Equal(t, actual, expected) + require.Equal(t, actual, expected) } func TestHelpFlag(t *testing.T) { Execute() output, err := executeCommand(rootCmd, "--help") - assert.Contains(t, output, "Stripe commands:") - assert.NoError(t, err) + require.Contains(t, output, "Stripe commands:") + require.NoError(t, err) } diff --git a/pkg/cmd/status.go b/pkg/cmd/status.go index 710b069c1..f7af2a74d 100644 --- a/pkg/cmd/status.go +++ b/pkg/cmd/status.go @@ -6,6 +6,7 @@ import ( "time" "github.com/spf13/cobra" + "github.com/stripe/stripe-cli/pkg/ansi" "github.com/stripe/stripe-cli/pkg/status" "github.com/stripe/stripe-cli/pkg/validators" diff --git a/pkg/config/config.go b/pkg/config/config.go index 8a7fad698..741663e04 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -115,6 +115,7 @@ func (c *Config) InitConfig() { } } +// EditConfig opens the configuration file in the default editor. func (c *Config) EditConfig() error { var err error @@ -139,6 +140,7 @@ func (c *Config) EditConfig() error { return err } +// PrintConfig outputs the contents of the configuration file. func (c *Config) PrintConfig() error { if c.Profile.ProfileName == "default" { configFile, err := ioutil.ReadFile(c.ProfilesFile) diff --git a/pkg/config/config_test.go b/pkg/config/config_test.go index 7aabaf716..274adc7fe 100644 --- a/pkg/config/config_test.go +++ b/pkg/config/config_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/spf13/viper" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRemoveKey(t *testing.T) { @@ -13,8 +13,8 @@ func TestRemoveKey(t *testing.T) { v.Set("stay", "here") nv, err := removeKey(v, "remove") - assert.NoError(t, err) + require.NoError(t, err) - assert.EqualValues(t, []string{"stay"}, nv.AllKeys()) - assert.ElementsMatch(t, []string{"stay", "remove"}, v.AllKeys()) + require.EqualValues(t, []string{"stay"}, nv.AllKeys()) + require.ElementsMatch(t, []string{"stay", "remove"}, v.AllKeys()) } diff --git a/pkg/config/profile.go b/pkg/config/profile.go index e5005e7ae..63bf6268b 100644 --- a/pkg/config/profile.go +++ b/pkg/config/profile.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/spf13/viper" + "github.com/stripe/stripe-cli/pkg/validators" ) @@ -75,15 +76,19 @@ func (p *Profile) GetConfigField(field string) string { return p.ProfileName + "." + field } +// RegisterAlias registers an alias for a given key. func (p *Profile) RegisterAlias(alias, key string) { viper.RegisterAlias(p.GetConfigField(alias), p.GetConfigField(key)) } +// WriteConfigField updates a configuration field and writes the updated +// configuration to disk. func (p *Profile) WriteConfigField(field, value string) error { viper.Set(p.GetConfigField(field), value) return viper.WriteConfig() } +// DeleteConfigField deletes a configuration field. func (p *Profile) DeleteConfigField(field string) error { v, err := removeKey(viper.GetViper(), p.GetConfigField(field)) if err != nil { diff --git a/pkg/config/profile_test.go b/pkg/config/profile_test.go index f3dda10e7..fd61354c3 100644 --- a/pkg/config/profile_test.go +++ b/pkg/config/profile_test.go @@ -8,7 +8,7 @@ import ( "testing" "github.com/spf13/viper" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestWriteProfile(t *testing.T) { @@ -31,9 +31,9 @@ func TestWriteProfile(t *testing.T) { fmt.Println(profilesFile) err := p.writeProfile(v) - assert.NoError(t, err) + require.NoError(t, err) - assert.FileExists(t, c.ProfilesFile) + require.FileExists(t, c.ProfilesFile) configValues := helperLoadBytes(t, c.ProfilesFile) expectedConfig := ` @@ -41,7 +41,7 @@ func TestWriteProfile(t *testing.T) { api_key = "sk_test_123" device_name = "st-testing" ` - assert.EqualValues(t, expectedConfig, string(configValues)) + require.EqualValues(t, expectedConfig, string(configValues)) cleanUp(c.ProfilesFile) } @@ -65,13 +65,13 @@ func TestWriteProfilesMerge(t *testing.T) { v := viper.New() writeErr := p.writeProfile(v) - assert.NoError(t, writeErr) - assert.FileExists(t, c.ProfilesFile) + require.NoError(t, writeErr) + require.FileExists(t, c.ProfilesFile) p.ProfileName = "tests-merge" writeErrTwo := p.writeProfile(v) - assert.NoError(t, writeErrTwo) - assert.FileExists(t, c.ProfilesFile) + require.NoError(t, writeErrTwo) + require.FileExists(t, c.ProfilesFile) configValues := helperLoadBytes(t, c.ProfilesFile) expectedConfig := ` @@ -84,7 +84,7 @@ func TestWriteProfilesMerge(t *testing.T) { device_name = "st-testing" ` - assert.EqualValues(t, expectedConfig, string(configValues)) + require.EqualValues(t, expectedConfig, string(configValues)) cleanUp(c.ProfilesFile) } diff --git a/pkg/login/client_login_test.go b/pkg/login/client_login_test.go index 5e0a706a0..60147572e 100644 --- a/pkg/login/client_login_test.go +++ b/pkg/login/client_login_test.go @@ -11,7 +11,7 @@ import ( "strings" "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/stripe/stripe-cli/pkg/config" ) @@ -37,16 +37,17 @@ func TestLogin(t *testing.T) { } c := &config.Config{ - Color: "auto", - LogLevel: "info", - Profile: p, + Color: "auto", + LogLevel: "info", + Profile: p, ProfilesFile: profilesFile, } var pollURL string ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path == "/stripecli/auth" { + switch r.URL.Path { + case "/stripecli/auth": w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") expectedLinks := Links{ @@ -55,15 +56,15 @@ func TestLogin(t *testing.T) { VerificationCode: "dinosaur-pineapple-polkadot", } json.NewEncoder(w).Encode(expectedLinks) - } else if r.URL.Path == "/stripecli/auth/cliauth_123" { - assert.Equal(t, "cliauth_secret", r.URL.Query().Get("secret")) + case "/stripecli/auth/cliauth_123": + require.Equal(t, "cliauth_secret", r.URL.Query().Get("secret")) w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") data := []byte(`{"redeemed": true, "account_id": "acct_123", "testmode_key_secret": "sk_test_1234", "account_display_name": "test_disp_name"}`) fmt.Println(string(data)) w.Write(data) - } else { + default: w.WriteHeader(http.StatusNotFound) } })) @@ -73,7 +74,7 @@ func TestLogin(t *testing.T) { input := strings.NewReader("\n") err := Login(ts.URL, c, input) - assert.NoError(t, err) + require.NoError(t, err) } func TestGetLinks(t *testing.T) { @@ -84,11 +85,11 @@ func TestGetLinks(t *testing.T) { } ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, http.MethodPost, r.Method) - assert.Equal(t, "application/x-www-form-urlencoded", r.Header.Get("Content-Type")) + require.Equal(t, http.MethodPost, r.Method) + require.Equal(t, "application/x-www-form-urlencoded", r.Header.Get("Content-Type")) - assert.NoError(t, r.ParseForm()) - assert.Equal(t, "test", r.PostFormValue("device_name")) + require.NoError(t, r.ParseForm()) + require.Equal(t, "test", r.PostFormValue("device_name")) w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") @@ -97,21 +98,21 @@ func TestGetLinks(t *testing.T) { defer ts.Close() links, err := getLinks(ts.URL, "test") - assert.NoError(t, err) - assert.Equal(t, expectedLinks, *links) + require.NoError(t, err) + require.Equal(t, expectedLinks, *links) } func TestGetLinksHTTPStatusError(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, http.MethodPost, r.Method) - assert.Equal(t, "application/x-www-form-urlencoded", r.Header.Get("Content-Type")) + require.Equal(t, http.MethodPost, r.Method) + require.Equal(t, "application/x-www-form-urlencoded", r.Header.Get("Content-Type")) w.WriteHeader(http.StatusInternalServerError) })) defer ts.Close() links, err := getLinks(ts.URL, "test") - assert.EqualError(t, err, "unexpected http status code: 500 ") - assert.Empty(t, links) + require.EqualError(t, err, "unexpected http status code: 500 ") + require.Empty(t, links) } func TestGetLinksRequestError(t *testing.T) { @@ -120,15 +121,15 @@ func TestGetLinksRequestError(t *testing.T) { ts.Close() links, err := getLinks(ts.URL, "test") - assert.Error(t, err) - assert.Contains(t, err.Error(), "connect: connection refused") - assert.Empty(t, links) + require.Error(t, err) + require.Contains(t, err.Error(), "connect: connection refused") + require.Empty(t, links) } func TestGetLinksParseError(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, http.MethodPost, r.Method) - assert.Equal(t, "application/x-www-form-urlencoded", r.Header.Get("Content-Type")) + require.Equal(t, http.MethodPost, r.Method) + require.Equal(t, "application/x-www-form-urlencoded", r.Header.Get("Content-Type")) w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") @@ -140,6 +141,6 @@ func TestGetLinksParseError(t *testing.T) { defer ts.Close() links, err := getLinks(ts.URL, "test") - assert.EqualError(t, err, "json: cannot unmarshal number into Go struct field Links.browser_url of type string") - assert.Empty(t, links) + require.EqualError(t, err, "json: cannot unmarshal number into Go struct field Links.browser_url of type string") + require.Empty(t, links) } diff --git a/pkg/login/interactive_login_test.go b/pkg/login/interactive_login_test.go index b02ffbfc6..1b1fcf22e 100644 --- a/pkg/login/interactive_login_test.go +++ b/pkg/login/interactive_login_test.go @@ -5,7 +5,7 @@ import ( "strings" "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPIKeyInput(t *testing.T) { @@ -14,8 +14,8 @@ func TestAPIKeyInput(t *testing.T) { keyInput := strings.NewReader(expectedKey + "\n") actualKey, err := getConfigureAPIKey(keyInput) - assert.Equal(t, expectedKey, actualKey) - assert.Nil(t, err) + require.Equal(t, expectedKey, actualKey) + require.Nil(t, err) } func TestAPIKeyInputEmpty(t *testing.T) { @@ -25,9 +25,9 @@ func TestAPIKeyInputEmpty(t *testing.T) { keyInput := strings.NewReader(expectedKey + "\n") actualKey, err := getConfigureAPIKey(keyInput) - assert.Equal(t, expectedKey, actualKey) - assert.NotNil(t, err) - assert.EqualError(t, err, expectedErrorString) + require.Equal(t, expectedKey, actualKey) + require.NotNil(t, err) + require.EqualError(t, err, expectedErrorString) } func TestAPIKeyInputLivemode(t *testing.T) { @@ -38,9 +38,9 @@ func TestAPIKeyInputLivemode(t *testing.T) { keyInput := strings.NewReader(livemodeKey + "\n") actualKey, err := getConfigureAPIKey(keyInput) - assert.Equal(t, expectedKey, actualKey) - assert.NotNil(t, err) - assert.EqualError(t, err, expectedErrorString) + require.Equal(t, expectedKey, actualKey) + require.NotNil(t, err) + require.EqualError(t, err, expectedErrorString) } func TestDeviceNameInput(t *testing.T) { @@ -49,7 +49,7 @@ func TestDeviceNameInput(t *testing.T) { actualDeviceName := getConfigureDeviceName(deviceNameInput) - assert.Equal(t, expectedDeviceName, actualDeviceName) + require.Equal(t, expectedDeviceName, actualDeviceName) } func TestDeviceNameAutoDetect(t *testing.T) { @@ -58,5 +58,5 @@ func TestDeviceNameAutoDetect(t *testing.T) { actualDeviceName := getConfigureDeviceName(deviceNameInput) - assert.Equal(t, hostName, actualDeviceName) + require.Equal(t, hostName, actualDeviceName) } diff --git a/pkg/login/login_message_test.go b/pkg/login/login_message_test.go index b86502211..ad2204b62 100644 --- a/pkg/login/login_message_test.go +++ b/pkg/login/login_message_test.go @@ -6,18 +6,20 @@ import ( "net/http/httptest" "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) +const testDisplayName = "test_disp_name" + func TestSuccessMessage(t *testing.T) { account := &Account{ ID: "acct_123", } - account.Settings.Dashboard.DisplayName = "test_disp_name" + account.Settings.Dashboard.DisplayName = testDisplayName msg, err := SuccessMessage(account, "", "sk_test_123") - assert.Nil(t, err) - assert.Equal( + require.Nil(t, err) + require.Equal( t, "Done! The Stripe CLI is configured for test_disp_name with account id acct_123\n", msg, @@ -30,8 +32,8 @@ func TestSuccessMessageNoDisplayName(t *testing.T) { } msg, err := SuccessMessage(account, "", "sk_test_123") - assert.Nil(t, err) - assert.Equal( + require.Nil(t, err) + require.Equal( t, "Done! The Stripe CLI is configured for your account with account id acct_123\n", msg, @@ -41,8 +43,8 @@ func TestSuccessMessageNoDisplayName(t *testing.T) { func TestSuccessMessageBasicMessage(t *testing.T) { account := &Account{} msg, err := SuccessMessage(account, "", "sk_test_123") - assert.Nil(t, err) - assert.Equal( + require.Nil(t, err) + require.Equal( t, "Done! The Stripe CLI is configured\n", msg, @@ -51,12 +53,12 @@ func TestSuccessMessageBasicMessage(t *testing.T) { func TestSuccessMessageGetAccount(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method) + require.Equal(t, "GET", r.Method) account := &Account{ ID: "acct_123", } - account.Settings.Dashboard.DisplayName = "test_disp_name" + account.Settings.Dashboard.DisplayName = testDisplayName w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") @@ -65,8 +67,8 @@ func TestSuccessMessageGetAccount(t *testing.T) { defer ts.Close() msg, err := SuccessMessage(nil, ts.URL, "sk_test_123") - assert.Nil(t, err) - assert.Equal( + require.Nil(t, err) + require.Equal( t, "Done! The Stripe CLI is configured for test_disp_name with account id acct_123\n", msg, @@ -75,7 +77,7 @@ func TestSuccessMessageGetAccount(t *testing.T) { func TestSuccessMessageGetAccountNoDisplayName(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method) + require.Equal(t, "GET", r.Method) account := &Account{ ID: "acct_123", @@ -88,8 +90,8 @@ func TestSuccessMessageGetAccountNoDisplayName(t *testing.T) { defer ts.Close() msg, err := SuccessMessage(nil, ts.URL, "sk_test_123") - assert.Nil(t, err) - assert.Equal( + require.Nil(t, err) + require.Equal( t, "Done! The Stripe CLI is configured for your account with account id acct_123\n", msg, diff --git a/pkg/login/poll_test.go b/pkg/login/poll_test.go index 4effaa506..46f669d19 100644 --- a/pkg/login/poll_test.go +++ b/pkg/login/poll_test.go @@ -8,14 +8,14 @@ import ( "testing" "time" - assert "github.com/stretchr/testify/require" + "github.com/stretchr/testify/require" ) func TestRedeemed(t *testing.T) { var attempts uint64 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, http.MethodGet, r.Method) + require.Equal(t, http.MethodGet, r.Method) atomic.AddUint64(&attempts, 1) @@ -35,18 +35,18 @@ func TestRedeemed(t *testing.T) { defer ts.Close() apiKey, account, err := PollForKey(ts.URL, 1*time.Millisecond, 3) - assert.NoError(t, err) - assert.Equal(t, "sk_test_123", apiKey) - assert.Equal(t, "acct_123", account.ID) - assert.Equal(t, "test_disp_name", account.Settings.Dashboard.DisplayName) - assert.Equal(t, uint64(2), atomic.LoadUint64(&attempts)) + require.NoError(t, err) + require.Equal(t, "sk_test_123", apiKey) + require.Equal(t, "acct_123", account.ID) + require.Equal(t, "test_disp_name", account.Settings.Dashboard.DisplayName) + require.Equal(t, uint64(2), atomic.LoadUint64(&attempts)) } func TestRedeemedNoDisplayName(t *testing.T) { var attempts uint64 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method) + require.Equal(t, "GET", r.Method) atomic.AddUint64(&attempts, 1) @@ -65,18 +65,18 @@ func TestRedeemedNoDisplayName(t *testing.T) { defer ts.Close() apiKey, account, err := PollForKey(ts.URL, 1*time.Millisecond, 3) - assert.NoError(t, err) - assert.Equal(t, "sk_test_123", apiKey) - assert.Equal(t, "acct_123", account.ID) - assert.Equal(t, "", account.Settings.Dashboard.DisplayName) - assert.Equal(t, uint64(2), atomic.LoadUint64(&attempts)) + require.NoError(t, err) + require.Equal(t, "sk_test_123", apiKey) + require.Equal(t, "acct_123", account.ID) + require.Equal(t, "", account.Settings.Dashboard.DisplayName) + require.Equal(t, uint64(2), atomic.LoadUint64(&attempts)) } func TestExceedMaxAttempts(t *testing.T) { var attempts uint64 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, http.MethodGet, r.Method) + require.Equal(t, http.MethodGet, r.Method) atomic.AddUint64(&attempts, 1) @@ -90,17 +90,17 @@ func TestExceedMaxAttempts(t *testing.T) { defer ts.Close() apiKey, account, err := PollForKey(ts.URL, 1*time.Millisecond, 3) - assert.EqualError(t, err, "exceeded max attempts") - assert.Empty(t, apiKey) - assert.Empty(t, account) - assert.Equal(t, uint64(3), atomic.LoadUint64(&attempts)) + require.EqualError(t, err, "exceeded max attempts") + require.Empty(t, apiKey) + require.Empty(t, account) + require.Equal(t, uint64(3), atomic.LoadUint64(&attempts)) } func TestHTTPStatusError(t *testing.T) { var attempts uint64 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, http.MethodGet, r.Method) + require.Equal(t, http.MethodGet, r.Method) atomic.AddUint64(&attempts, 1) @@ -109,10 +109,10 @@ func TestHTTPStatusError(t *testing.T) { defer ts.Close() apiKey, account, err := PollForKey(ts.URL, 1*time.Millisecond, 3) - assert.EqualError(t, err, "unexpected http status code: 500 ") - assert.Empty(t, apiKey) - assert.Nil(t, account) - assert.Equal(t, uint64(1), atomic.LoadUint64(&attempts)) + require.EqualError(t, err, "unexpected http status code: 500 ") + require.Empty(t, apiKey) + require.Nil(t, account) + require.Equal(t, uint64(1), atomic.LoadUint64(&attempts)) } func TestHTTPRequestError(t *testing.T) { @@ -121,8 +121,8 @@ func TestHTTPRequestError(t *testing.T) { ts.Close() apiKey, account, err := PollForKey(ts.URL, 1*time.Millisecond, 3) - assert.Error(t, err) - assert.Contains(t, err.Error(), "connect: connection refused") - assert.Empty(t, apiKey) - assert.Nil(t, account) + require.Error(t, err) + require.Contains(t, err.Error(), "connect: connection refused") + require.Empty(t, apiKey) + require.Nil(t, account) } diff --git a/pkg/logtailing/tailer_test.go b/pkg/logtailing/tailer_test.go index 4f3ceec00..9b2baded8 100644 --- a/pkg/logtailing/tailer_test.go +++ b/pkg/logtailing/tailer_test.go @@ -4,7 +4,7 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestJsonifyFiltersAll(t *testing.T) { @@ -20,8 +20,8 @@ func TestJsonifyFiltersAll(t *testing.T) { } expected := fmt.Sprintf(`{"filter_account":["my-account"],"filter_ip_address":["my-ip-address"],"filter_http_method":["my-http-method"],"filter_request_path":["my-request-path"],"filter_request_status":["my-request-status"],"filter_source":["my-source"],"filter_status_code":["my-status-code"],"filter_status_code_type":["my-status-code-type"]}`) filtersStr, err := jsonifyFilters(filters) - assert.Nil(t, err) - assert.Equal(t, expected, filtersStr) + require.Nil(t, err) + require.Equal(t, expected, filtersStr) } func TestJsonifyFiltersSome(t *testing.T) { @@ -31,8 +31,8 @@ func TestJsonifyFiltersSome(t *testing.T) { } expected := fmt.Sprintf(`{"filter_http_method":["my-http-method"],"filter_status_code":["my-status-code"]}`) filtersStr, err := jsonifyFilters(filters) - assert.Nil(t, err) - assert.Equal(t, expected, filtersStr) + require.Nil(t, err) + require.Equal(t, expected, filtersStr) } func TestJsonifyFiltersEmpty(t *testing.T) { @@ -47,6 +47,6 @@ func TestJsonifyFiltersEmpty(t *testing.T) { FilterStatusCodeType: []string{}, } filtersStr, err := jsonifyFilters(filters) - assert.Nil(t, err) - assert.Equal(t, "{}", filtersStr) + require.Nil(t, err) + require.Equal(t, "{}", filtersStr) } diff --git a/pkg/proxy/endpoint.go b/pkg/proxy/endpoint.go index 3c0093466..a53ef063a 100644 --- a/pkg/proxy/endpoint.go +++ b/pkg/proxy/endpoint.go @@ -22,12 +22,12 @@ type EndpointConfig struct { ResponseHandler EndpointResponseHandler } -// ResponseHandler handles a response from the endpoint. +// EndpointResponseHandler handles a response from the endpoint. type EndpointResponseHandler interface { ProcessResponse(string, *http.Response) } -// ResponseHandlerFunc is an adapter to allow the use of ordinary +// EndpointResponseHandlerFunc is an adapter to allow the use of ordinary // functions as response handlers. If f is a function with the // appropriate signature, ResponseHandler(f) is a // ResponseHandler that calls f. diff --git a/pkg/proxy/endpoint_test.go b/pkg/proxy/endpoint_test.go index 6fae109d8..de2b99b50 100644 --- a/pkg/proxy/endpoint_test.go +++ b/pkg/proxy/endpoint_test.go @@ -7,7 +7,7 @@ import ( "sync" "testing" - assert "github.com/stretchr/testify/require" + "github.com/stretchr/testify/require" ) func TestClientHandler(t *testing.T) { @@ -19,12 +19,12 @@ func TestClientHandler(t *testing.T) { w.Write([]byte("OK!")) reqBody, err := ioutil.ReadAll(r.Body) - assert.Nil(t, err) + require.Nil(t, err) - assert.Equal(t, http.MethodPost, r.Method) - assert.Equal(t, "TestAgent/v1", r.UserAgent()) - assert.Equal(t, "t=123,v1=hunter2", r.Header.Get("Stripe-Signature")) - assert.Equal(t, "{}", string(reqBody)) + require.Equal(t, http.MethodPost, r.Method) + require.Equal(t, "TestAgent/v1", r.UserAgent()) + require.Equal(t, "t=123,v1=hunter2", r.Header.Get("Stripe-Signature")) + require.Equal(t, "{}", string(reqBody)) })) defer ts.Close() @@ -37,7 +37,7 @@ func TestClientHandler(t *testing.T) { &EndpointConfig{ ResponseHandler: EndpointResponseHandlerFunc(func(webhookID string, resp *http.Response) { buf, err := ioutil.ReadAll(resp.Body) - assert.Nil(t, err) + require.Nil(t, err) rcvBody = string(buf) rcvWebhookID = webhookID @@ -58,7 +58,7 @@ func TestClientHandler(t *testing.T) { wg.Wait() - assert.Nil(t, err) - assert.Equal(t, "OK!", rcvBody) - assert.Equal(t, "wh_123", rcvWebhookID) + require.Nil(t, err) + require.Equal(t, "OK!", rcvBody) + require.Equal(t, "wh_123", rcvWebhookID) } diff --git a/pkg/proxy/proxy_test.go b/pkg/proxy/proxy_test.go index d4454d21c..af1c95717 100644 --- a/pkg/proxy/proxy_test.go +++ b/pkg/proxy/proxy_test.go @@ -3,7 +3,7 @@ package proxy import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/stripe/stripe-cli/pkg/websocket" ) @@ -25,19 +25,19 @@ func TestFilterWebhookEvent(t *testing.T) { }, } - assert.False(t, proxyUseDefault.filterWebhookEvent(evtDefault)) - assert.True(t, proxyUseDefault.filterWebhookEvent(evtLatest)) + require.False(t, proxyUseDefault.filterWebhookEvent(evtDefault)) + require.True(t, proxyUseDefault.filterWebhookEvent(evtLatest)) - assert.True(t, proxyUseLatest.filterWebhookEvent(evtDefault)) - assert.False(t, proxyUseLatest.filterWebhookEvent(evtLatest)) + require.True(t, proxyUseLatest.filterWebhookEvent(evtDefault)) + require.False(t, proxyUseLatest.filterWebhookEvent(evtLatest)) } func TestTruncate(t *testing.T) { - assert.Equal(t, "Hello, World", truncate("Hello, World", 12, false)) - assert.Equal(t, "Hello, Worl", truncate("Hello, World", 11, false)) - assert.Equal(t, "Hello, W...", truncate("Hello, World", 11, true)) + require.Equal(t, "Hello, World", truncate("Hello, World", 12, false)) + require.Equal(t, "Hello, Worl", truncate("Hello, World", 11, false)) + require.Equal(t, "Hello, W...", truncate("Hello, World", 11, true)) - assert.Equal(t, "Hello, 世界", truncate("Hello, 世界", 13, false)) - assert.Equal(t, "Hello, 世", truncate("Hello, 世界", 12, false)) - assert.Equal(t, "Hello, ...", truncate("Hello, 世界", 12, true)) + require.Equal(t, "Hello, 世界", truncate("Hello, 世界", 13, false)) + require.Equal(t, "Hello, 世", truncate("Hello, 世界", 12, false)) + require.Equal(t, "Hello, ...", truncate("Hello, 世界", 12, true)) } diff --git a/pkg/proxy/stripeevent_test.go b/pkg/proxy/stripeevent_test.go index 68a03949a..8f1e00b8e 100644 --- a/pkg/proxy/stripeevent_test.go +++ b/pkg/proxy/stripeevent_test.go @@ -3,29 +3,29 @@ package proxy import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestIsConnect(t *testing.T) { evt1 := &stripeEvent{ID: "evt_123", Type: "customer.created"} - assert.False(t, evt1.isConnect()) + require.False(t, evt1.isConnect()) evt2 := &stripeEvent{ID: "evt_123", Type: "customer.created", Account: "acct_123"} - assert.True(t, evt2.isConnect()) + require.True(t, evt2.isConnect()) } func TestURLForEventID(t *testing.T) { evt1 := &stripeEvent{ID: "evt_123", Type: "customer.created"} - assert.Equal(t, "https://dashboard.stripe.com/test/events/evt_123", evt1.urlForEventID()) + require.Equal(t, "https://dashboard.stripe.com/test/events/evt_123", evt1.urlForEventID()) evt2 := &stripeEvent{ID: "evt_123", Type: "customer.created", Account: "acct_123"} - assert.Equal(t, "https://dashboard.stripe.com/acct_123/test/events/evt_123", evt2.urlForEventID()) + require.Equal(t, "https://dashboard.stripe.com/acct_123/test/events/evt_123", evt2.urlForEventID()) } func TestURLForEventType(t *testing.T) { evt1 := &stripeEvent{ID: "evt_123", Type: "customer.created"} - assert.Equal(t, "https://dashboard.stripe.com/test/events?type=customer.created", evt1.urlForEventType()) + require.Equal(t, "https://dashboard.stripe.com/test/events?type=customer.created", evt1.urlForEventType()) evt2 := &stripeEvent{ID: "evt_123", Type: "customer.created", Account: "acct_123"} - assert.Equal(t, "https://dashboard.stripe.com/acct_123/test/events?type=customer.created", evt2.urlForEventType()) + require.Equal(t, "https://dashboard.stripe.com/acct_123/test/events?type=customer.created", evt2.urlForEventType()) } diff --git a/pkg/requests/base.go b/pkg/requests/base.go index a9e722f65..28727510c 100644 --- a/pkg/requests/base.go +++ b/pkg/requests/base.go @@ -28,6 +28,7 @@ type RequestParameters struct { stripeAccount string } +// AppendData appends data to the request parameters. func (r *RequestParameters) AppendData(data []string) { r.data = append(r.data, data...) } diff --git a/pkg/requests/base_test.go b/pkg/requests/base_test.go index fd971e1d2..95278a8d5 100644 --- a/pkg/requests/base_test.go +++ b/pkg/requests/base_test.go @@ -8,7 +8,7 @@ import ( "strings" "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestBuildDataForRequest(t *testing.T) { @@ -17,7 +17,7 @@ func TestBuildDataForRequest(t *testing.T) { expected := "bender=robot&fry=human" output, _ := rb.buildDataForRequest(params) - assert.Equal(t, expected, output) + require.Equal(t, expected, output) } func TestBuildDataForRequestParamOrdering(t *testing.T) { @@ -26,7 +26,7 @@ func TestBuildDataForRequestParamOrdering(t *testing.T) { expected := "fry=human&bender=robot" output, _ := rb.buildDataForRequest(params) - assert.Equal(t, expected, output) + require.Equal(t, expected, output) } func TestBuildDataForRequestExpand(t *testing.T) { @@ -35,7 +35,7 @@ func TestBuildDataForRequestExpand(t *testing.T) { expected := "expand[]=futurama.employees&expand[]=futurama.ships" output, _ := rb.buildDataForRequest(params) - assert.Equal(t, expected, output) + require.Equal(t, expected, output) } func TestBuildDataForRequestPagination(t *testing.T) { @@ -51,7 +51,7 @@ func TestBuildDataForRequestPagination(t *testing.T) { expected := "limit=10&starting_after=bender&ending_before=leela" output, _ := rb.buildDataForRequest(params) - assert.Equal(t, expected, output) + require.Equal(t, expected, output) } func TestBuildDataForRequestGetOnly(t *testing.T) { @@ -67,7 +67,7 @@ func TestBuildDataForRequestGetOnly(t *testing.T) { expected := "" output, _ := rb.buildDataForRequest(params) - assert.Equal(t, expected, output) + require.Equal(t, expected, output) } func TestBuildDataForRequestInvalidArgument(t *testing.T) { @@ -76,8 +76,8 @@ func TestBuildDataForRequestInvalidArgument(t *testing.T) { expected := "Invalid data argument: fry" data, err := rb.buildDataForRequest(params) - assert.Equal(t, "", data) - assert.Equal(t, expected, err.Error()) + require.Equal(t, "", data) + require.Equal(t, expected, err.Error()) } func TestMakeRequest(t *testing.T) { @@ -86,15 +86,15 @@ func TestMakeRequest(t *testing.T) { w.Write([]byte("OK!")) reqBody, err := ioutil.ReadAll(r.Body) - assert.Nil(t, err) - - assert.Equal(t, http.MethodGet, r.Method) - assert.Equal(t, "/foo/bar", r.URL.Path) - assert.Equal(t, "Bearer sk_test_1234", r.Header.Get("Authorization")) - assert.NotEmpty(t, r.UserAgent()) - assert.NotEmpty(t, r.Header.Get("X-Stripe-Client-User-Agent")) - assert.Equal(t, "bender=robot&fry=human&expand[]=futurama.employees&expand[]=futurama.ships", r.URL.RawQuery) - assert.Equal(t, "", string(reqBody)) + require.Nil(t, err) + + require.Equal(t, http.MethodGet, r.Method) + require.Equal(t, "/foo/bar", r.URL.Path) + require.Equal(t, "Bearer sk_test_1234", r.Header.Get("Authorization")) + require.NotEmpty(t, r.UserAgent()) + require.NotEmpty(t, r.Header.Get("X-Stripe-Client-User-Agent")) + require.Equal(t, "bender=robot&fry=human&expand[]=futurama.employees&expand[]=futurama.ships", r.URL.RawQuery) + require.Equal(t, "", string(reqBody)) })) defer ts.Close() @@ -107,7 +107,7 @@ func TestMakeRequest(t *testing.T) { } _, err := rb.MakeRequest("sk_test_1234", "/foo/bar", params) - assert.Nil(t, err) + require.Nil(t, err) } func TestGetUserConfirmationRequired(t *testing.T) { @@ -118,8 +118,8 @@ func TestGetUserConfirmationRequired(t *testing.T) { rb.autoConfirm = false confirmed, err := rb.getUserConfirmation(reader) - assert.True(t, confirmed) - assert.Nil(t, err) + require.True(t, confirmed) + require.Nil(t, err) } func TestGetUserConfirmationNotRequired(t *testing.T) { @@ -130,8 +130,8 @@ func TestGetUserConfirmationNotRequired(t *testing.T) { rb.autoConfirm = false confirmed, err := rb.getUserConfirmation(reader) - assert.True(t, confirmed) - assert.Nil(t, err) + require.True(t, confirmed) + require.Nil(t, err) } func TestGetUserConfirmationAutoConfirm(t *testing.T) { @@ -142,8 +142,8 @@ func TestGetUserConfirmationAutoConfirm(t *testing.T) { rb.autoConfirm = true confirmed, err := rb.getUserConfirmation(reader) - assert.True(t, confirmed) - assert.Nil(t, err) + require.True(t, confirmed) + require.Nil(t, err) } func TestGetUserConfirmationNoConfirm(t *testing.T) { @@ -154,13 +154,13 @@ func TestGetUserConfirmationNoConfirm(t *testing.T) { rb.autoConfirm = false confirmed, err := rb.getUserConfirmation(reader) - assert.False(t, confirmed) - assert.Nil(t, err) + require.False(t, confirmed) + require.Nil(t, err) } func TestNormalizePath(t *testing.T) { - assert.Equal(t, "/v1/charges", normalizePath("/v1/charges")) - assert.Equal(t, "/v1/charges", normalizePath("v1/charges")) - assert.Equal(t, "/v1/charges", normalizePath("/charges")) - assert.Equal(t, "/v1/charges", normalizePath("charges")) + require.Equal(t, "/v1/charges", normalizePath("/v1/charges")) + require.Equal(t, "/v1/charges", normalizePath("v1/charges")) + require.Equal(t, "/v1/charges", normalizePath("/charges")) + require.Equal(t, "/v1/charges", normalizePath("charges")) } diff --git a/pkg/requests/examples_test.go b/pkg/requests/examples_test.go index 4297085c5..8e4eca7ab 100644 --- a/pkg/requests/examples_test.go +++ b/pkg/requests/examples_test.go @@ -6,7 +6,7 @@ import ( "net/http/httptest" "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func jsonBytes() []byte { @@ -21,8 +21,8 @@ func jsonBytes() []byte { func TestParseResponse(t *testing.T) { bytes := jsonBytes() resp, err := parseResponse(bytes) - assert.Nil(t, err) - assert.Equal(t, "test-id", resp["id"]) + require.Nil(t, err) + require.Equal(t, "test-id", resp["id"]) } func TestBuildRequest(t *testing.T) { @@ -33,8 +33,8 @@ func TestBuildRequest(t *testing.T) { req, params := ex.buildRequest(http.MethodPost, []string{"foo=bar"}) - assert.Equal(t, []string{"foo=bar"}, params.data) - assert.Equal(t, http.MethodPost, req.Method) + require.Equal(t, []string{"foo=bar"}, params.data) + require.Equal(t, http.MethodPost, req.Method) } func TestChargeCaptured(t *testing.T) { @@ -52,7 +52,7 @@ func TestChargeCaptured(t *testing.T) { } err := ex.ChargeCaptured() - assert.Nil(t, err) + require.Nil(t, err) } func TestChargeFailed(t *testing.T) { @@ -70,7 +70,7 @@ func TestChargeFailed(t *testing.T) { } err := ex.ChargeFailed() - assert.Nil(t, err) + require.Nil(t, err) } func TestChargeSucceeded(t *testing.T) { @@ -88,7 +88,7 @@ func TestChargeSucceeded(t *testing.T) { } err := ex.ChargeSucceeded() - assert.Nil(t, err) + require.Nil(t, err) } func TestCustomerCreated(t *testing.T) { @@ -106,7 +106,7 @@ func TestCustomerCreated(t *testing.T) { } err := ex.CustomerCreated() - assert.Nil(t, err) + require.Nil(t, err) } func TestCustomerUpdated(t *testing.T) { @@ -124,7 +124,7 @@ func TestCustomerUpdated(t *testing.T) { } err := ex.CustomerUpdated() - assert.Nil(t, err) + require.Nil(t, err) } func TestCustomerSourceCreated(t *testing.T) { @@ -142,7 +142,7 @@ func TestCustomerSourceCreated(t *testing.T) { } err := ex.CustomerSourceCreated() - assert.Nil(t, err) + require.Nil(t, err) } func TestCustomerSourceUpdated(t *testing.T) { @@ -160,7 +160,7 @@ func TestCustomerSourceUpdated(t *testing.T) { } err := ex.CustomerSourceUpdated() - assert.Nil(t, err) + require.Nil(t, err) } func TestCustomerSubscriptionUpdated(t *testing.T) { @@ -178,7 +178,7 @@ func TestCustomerSubscriptionUpdated(t *testing.T) { } err := ex.CustomerSubscriptionUpdated() - assert.Nil(t, err) + require.Nil(t, err) } func TestInvoiceCreated(t *testing.T) { @@ -196,7 +196,7 @@ func TestInvoiceCreated(t *testing.T) { } err := ex.InvoiceCreated() - assert.Nil(t, err) + require.Nil(t, err) } func TestInvoiceFinalized(t *testing.T) { @@ -214,7 +214,7 @@ func TestInvoiceFinalized(t *testing.T) { } err := ex.InvoiceFinalized() - assert.Nil(t, err) + require.Nil(t, err) } func TestInvoicePaymentSucceeded(t *testing.T) { @@ -232,7 +232,7 @@ func TestInvoicePaymentSucceeded(t *testing.T) { } err := ex.InvoicePaymentSucceeded() - assert.Nil(t, err) + require.Nil(t, err) } func TestInvoiceUpdated(t *testing.T) { @@ -250,7 +250,7 @@ func TestInvoiceUpdated(t *testing.T) { } err := ex.InvoiceUpdated() - assert.Nil(t, err) + require.Nil(t, err) } func TestPaymentIntentCreated(t *testing.T) { @@ -268,7 +268,7 @@ func TestPaymentIntentCreated(t *testing.T) { } err := ex.PaymentIntentCreated() - assert.Nil(t, err) + require.Nil(t, err) } func TestPaymentIntentSucceeded(t *testing.T) { @@ -286,7 +286,7 @@ func TestPaymentIntentSucceeded(t *testing.T) { } err := ex.PaymentIntentSucceeded() - assert.Nil(t, err) + require.Nil(t, err) } func TestPaymentIntentFailed(t *testing.T) { @@ -304,7 +304,7 @@ func TestPaymentIntentFailed(t *testing.T) { } err := ex.PaymentIntentFailed() - assert.Nil(t, err) + require.Nil(t, err) } func TestPaymentMethodAttached(t *testing.T) { @@ -322,5 +322,5 @@ func TestPaymentMethodAttached(t *testing.T) { } err := ex.PaymentMethodAttached() - assert.Nil(t, err) + require.Nil(t, err) } diff --git a/pkg/spec/spec_test.go b/pkg/spec/spec_test.go index 1fc0dd2be..85ffa3427 100644 --- a/pkg/spec/spec_test.go +++ b/pkg/spec/spec_test.go @@ -4,21 +4,21 @@ import ( "encoding/json" "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestLoadSpec(t *testing.T) { data, err := LoadSpec("../../api/openapi-spec/spec3.sdk.json") - assert.NoError(t, err) - assert.NotEmpty(t, data) + require.NoError(t, err) + require.NotEmpty(t, data) } func TestUnmarshal_Simple(t *testing.T) { data := []byte(`{"type": "string"}`) var schema Schema err := json.Unmarshal(data, &schema) - assert.NoError(t, err) - assert.Equal(t, "string", schema.Type) + require.NoError(t, err) + require.Equal(t, "string", schema.Type) } func TestUnmarshal_UnsupportedField(t *testing.T) { @@ -26,5 +26,5 @@ func TestUnmarshal_UnsupportedField(t *testing.T) { data := []byte(`{const: "hello"}`) var schema Schema err := json.Unmarshal(data, &schema) - assert.Error(t, err) + require.Error(t, err) } diff --git a/pkg/status/status_test.go b/pkg/status/status_test.go index e6d10c929..c878f62e5 100644 --- a/pkg/status/status_test.go +++ b/pkg/status/status_test.go @@ -3,7 +3,7 @@ package status import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func buildResponse() Response { @@ -26,25 +26,25 @@ func TestGetMap(t *testing.T) { response := buildResponse() responseMap := response.getMap(false) - assert.Equal(t, responseMap["status"], "up") - assert.Equal(t, responseMap["message"], "All systems operational") - assert.Equal(t, responseMap["time"], "July 21, 4:00 +0:00") - assert.Nil(t, responseMap["statuses"]) + require.Equal(t, responseMap["status"], "up") + require.Equal(t, responseMap["message"], "All systems operational") + require.Equal(t, responseMap["time"], "July 21, 4:00 +0:00") + require.Nil(t, responseMap["statuses"]) } func TestGetMapVerbose(t *testing.T) { response := buildResponse() responseMap := response.getMap(true) - assert.Equal(t, responseMap["status"], "up") - assert.Equal(t, responseMap["message"], "All systems operational") - assert.Equal(t, responseMap["time"], "July 21, 4:00 +0:00") + require.Equal(t, responseMap["status"], "up") + require.Equal(t, responseMap["message"], "All systems operational") + require.Equal(t, responseMap["time"], "July 21, 4:00 +0:00") statuses := responseMap["statuses"].(map[string]string) - assert.Equal(t, statuses["api"], "up") - assert.Equal(t, statuses["dashboard"], "up") - assert.Equal(t, statuses["stripejs"], "up") - assert.Equal(t, statuses["checkoutjs"], "up") + require.Equal(t, statuses["api"], "up") + require.Equal(t, statuses["dashboard"], "up") + require.Equal(t, statuses["stripejs"], "up") + require.Equal(t, statuses["checkoutjs"], "up") } func TestFormatJSON(t *testing.T) { @@ -57,7 +57,7 @@ func TestFormatJSON(t *testing.T) { }` formatted, _ := response.FormattedMessage("json", false) - assert.Equal(t, formatted, expected) + require.Equal(t, formatted, expected) } func TestFormatJSONVerbose(t *testing.T) { @@ -76,7 +76,7 @@ func TestFormatJSONVerbose(t *testing.T) { }` formatted, _ := response.FormattedMessage("json", true) - assert.Equal(t, formatted, expected) + require.Equal(t, formatted, expected) } func TestFormatDefault(t *testing.T) { @@ -86,7 +86,7 @@ func TestFormatDefault(t *testing.T) { As of: July 21, 4:00 +0:00` formatted, _ := response.FormattedMessage("default", false) - assert.Equal(t, formatted, expected) + require.Equal(t, formatted, expected) } func TestFormatDefaultVerbose(t *testing.T) { @@ -100,12 +100,12 @@ func TestFormatDefaultVerbose(t *testing.T) { As of: July 21, 4:00 +0:00` formatted, _ := response.FormattedMessage("default", true) - assert.Equal(t, formatted, expected) + require.Equal(t, formatted, expected) } func TestEmojification(t *testing.T) { - assert.Equal(t, "✔", emojifiedStatus("up")) - assert.Equal(t, "!", emojifiedStatus("degraded")) - assert.Equal(t, "✘", emojifiedStatus("down")) - assert.Equal(t, "", emojifiedStatus("foo")) + require.Equal(t, "✔", emojifiedStatus("up")) + require.Equal(t, "!", emojifiedStatus("degraded")) + require.Equal(t, "✘", emojifiedStatus("down")) + require.Equal(t, "", emojifiedStatus("foo")) } diff --git a/pkg/stripe/client_test.go b/pkg/stripe/client_test.go index 28edc173a..4ca382c57 100644 --- a/pkg/stripe/client_test.go +++ b/pkg/stripe/client_test.go @@ -7,17 +7,17 @@ import ( "net/url" "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPerformRequest_ParamsEncoding_Delete(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "/delete", r.URL.Path) - assert.Equal(t, "key_a=value_a&key_b=value_b", r.URL.RawQuery) + require.Equal(t, "/delete", r.URL.Path) + require.Equal(t, "key_a=value_a&key_b=value_b", r.URL.RawQuery) body, err := ioutil.ReadAll(r.Body) - assert.NoError(t, err) - assert.Equal(t, "", string(body)) + require.NoError(t, err) + require.Equal(t, "", string(body)) })) defer ts.Close() @@ -30,18 +30,19 @@ func TestPerformRequest_ParamsEncoding_Delete(t *testing.T) { params.Add("key_a", "value_a") params.Add("key_b", "value_b") - _, err := client.PerformRequest(http.MethodDelete, "/delete", params.Encode(), nil) - assert.NoError(t, err) + resp, err := client.PerformRequest(http.MethodDelete, "/delete", params.Encode(), nil) + require.NoError(t, err) + defer resp.Body.Close() } func TestPerformRequest_ParamsEncoding_Get(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "/get", r.URL.Path) - assert.Equal(t, "key_a=value_a&key_b=value_b", r.URL.RawQuery) + require.Equal(t, "/get", r.URL.Path) + require.Equal(t, "key_a=value_a&key_b=value_b", r.URL.RawQuery) body, err := ioutil.ReadAll(r.Body) - assert.NoError(t, err) - assert.Equal(t, "", string(body)) + require.NoError(t, err) + require.Equal(t, "", string(body)) })) defer ts.Close() @@ -54,18 +55,19 @@ func TestPerformRequest_ParamsEncoding_Get(t *testing.T) { params.Add("key_a", "value_a") params.Add("key_b", "value_b") - _, err := client.PerformRequest(http.MethodGet, "/get", params.Encode(), nil) - assert.NoError(t, err) + resp, err := client.PerformRequest(http.MethodGet, "/get", params.Encode(), nil) + require.NoError(t, err) + defer resp.Body.Close() } func TestPerformRequest_ParamsEncoding_Post(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "/post", r.URL.Path) - assert.Equal(t, "", r.URL.RawQuery) + require.Equal(t, "/post", r.URL.Path) + require.Equal(t, "", r.URL.RawQuery) body, err := ioutil.ReadAll(r.Body) - assert.NoError(t, err) - assert.Equal(t, "key_a=value_a&key_b=value_b", string(body)) + require.NoError(t, err) + require.Equal(t, "key_a=value_a&key_b=value_b", string(body)) })) defer ts.Close() @@ -78,13 +80,14 @@ func TestPerformRequest_ParamsEncoding_Post(t *testing.T) { params.Add("key_a", "value_a") params.Add("key_b", "value_b") - _, err := client.PerformRequest(http.MethodPost, "/post", params.Encode(), nil) - assert.NoError(t, err) + resp, err := client.PerformRequest(http.MethodPost, "/post", params.Encode(), nil) + require.NoError(t, err) + defer resp.Body.Close() } func TestPerformRequest_ApiKey_Provided(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "Bearer sk_test_1234", r.Header.Get("Authorization")) + require.Equal(t, "Bearer sk_test_1234", r.Header.Get("Authorization")) })) defer ts.Close() @@ -94,13 +97,14 @@ func TestPerformRequest_ApiKey_Provided(t *testing.T) { APIKey: "sk_test_1234", } - _, err := client.PerformRequest(http.MethodGet, "/get", "", nil) - assert.NoError(t, err) + resp, err := client.PerformRequest(http.MethodGet, "/get", "", nil) + require.NoError(t, err) + defer resp.Body.Close() } func TestPerformRequest_ApiKey_Omitted(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "", r.Header.Get("Authorization")) + require.Equal(t, "", r.Header.Get("Authorization")) })) defer ts.Close() @@ -109,13 +113,14 @@ func TestPerformRequest_ApiKey_Omitted(t *testing.T) { BaseURL: baseURL, } - _, err := client.PerformRequest(http.MethodGet, "/get", "", nil) - assert.NoError(t, err) + resp, err := client.PerformRequest(http.MethodGet, "/get", "", nil) + require.NoError(t, err) + defer resp.Body.Close() } func TestPerformRequest_ConfigureFunc(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "2019-07-10", r.Header.Get("Stripe-Version")) + require.Equal(t, "2019-07-10", r.Header.Get("Stripe-Version")) })) defer ts.Close() @@ -124,8 +129,9 @@ func TestPerformRequest_ConfigureFunc(t *testing.T) { BaseURL: baseURL, } - _, err := client.PerformRequest(http.MethodGet, "/get", "", func(r *http.Request) { + resp, err := client.PerformRequest(http.MethodGet, "/get", "", func(r *http.Request) { r.Header.Add("Stripe-Version", "2019-07-10") }) - assert.NoError(t, err) + require.NoError(t, err) + defer resp.Body.Close() } diff --git a/pkg/stripe/verbosetransport_test.go b/pkg/stripe/verbosetransport_test.go index 403c22d1a..28d6901ac 100644 --- a/pkg/stripe/verbosetransport_test.go +++ b/pkg/stripe/verbosetransport_test.go @@ -7,7 +7,7 @@ import ( "regexp" "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestVerboseTransport_Verbose(t *testing.T) { @@ -26,16 +26,19 @@ func TestVerboseTransport_Verbose(t *testing.T) { Out: &b, } client := &http.Client{Transport: tr} - req, _ := http.NewRequest("POST", ts.URL+"/test", nil) + req, err := http.NewRequest("POST", ts.URL+"/test", nil) + require.NoError(t, err) req.Header.Set("Authorization", "Bearer token") req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - client.Do(req) + resp, err := client.Do(req) + require.NoError(t, err) + defer resp.Body.Close() out := b.String() - assert.Regexp(t, regexp.MustCompile("> POST http://(.+)/test\n"), out) - assert.Contains(t, out, "> Authorization: Bearer [REDACTED]\n") - assert.Contains(t, out, "> Content-Type: application/x-www-form-urlencoded\n") - assert.Contains(t, out, "< HTTP 200\n") - assert.Contains(t, out, "< Request-Id: req_123\n") - assert.NotContains(t, out, "Non-Whitelisted-Header") + require.Regexp(t, regexp.MustCompile("> POST http://(.+)/test\n"), out) + require.Contains(t, out, "> Authorization: Bearer [REDACTED]\n") + require.Contains(t, out, "> Content-Type: application/x-www-form-urlencoded\n") + require.Contains(t, out, "< HTTP 200\n") + require.Contains(t, out, "< Request-Id: req_123\n") + require.NotContains(t, out, "Non-Whitelisted-Header") } diff --git a/pkg/stripeauth/client_test.go b/pkg/stripeauth/client_test.go index 61824d3eb..121c0095b 100644 --- a/pkg/stripeauth/client_test.go +++ b/pkg/stripeauth/client_test.go @@ -8,7 +8,7 @@ import ( "regexp" "testing" - assert "github.com/stretchr/testify/require" + "github.com/stretchr/testify/require" ) func TestAuthorize(t *testing.T) { @@ -22,14 +22,14 @@ func TestAuthorize(t *testing.T) { w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(session) - assert.Equal(t, http.MethodPost, r.Method) - assert.Equal(t, "Bearer sk_test_123", r.Header.Get("Authorization")) - assert.NotEmpty(t, r.UserAgent()) - assert.NotEmpty(t, r.Header.Get("X-Stripe-Client-User-Agent")) + require.Equal(t, http.MethodPost, r.Method) + require.Equal(t, "Bearer sk_test_123", r.Header.Get("Authorization")) + require.NotEmpty(t, r.UserAgent()) + require.NotEmpty(t, r.Header.Get("X-Stripe-Client-User-Agent")) body, err := ioutil.ReadAll(r.Body) - assert.NoError(t, err) - assert.Equal(t, "device_name=my-device&websocket_feature=webhooks", string(body)) + require.NoError(t, err) + require.Equal(t, "device_name=my-device&websocket_feature=webhooks", string(body)) })) defer ts.Close() @@ -37,17 +37,17 @@ func TestAuthorize(t *testing.T) { APIBaseURL: ts.URL, }) session, err := client.Authorize("my-device", "webhooks", nil) - assert.NoError(t, err) - assert.Equal(t, "some-id", session.WebSocketID) - assert.Equal(t, "wss://example.com/subscribe/acct_123", session.WebSocketURL) - assert.Equal(t, "webhook-payloads", session.WebSocketAuthorizedFeature) + require.NoError(t, err) + require.Equal(t, "some-id", session.WebSocketID) + require.Equal(t, "wss://example.com/subscribe/acct_123", session.WebSocketURL) + require.Equal(t, "webhook-payloads", session.WebSocketAuthorizedFeature) } func TestUserAgent(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) - assert.Regexp(t, regexp.MustCompile(`^Stripe/v1 stripe-cli/\w+$`), r.Header.Get("User-Agent")) + require.Regexp(t, regexp.MustCompile(`^Stripe/v1 stripe-cli/\w+$`), r.Header.Get("User-Agent")) })) defer ts.Close() @@ -62,15 +62,15 @@ func TestStripeClientUserAgent(t *testing.T) { w.WriteHeader(http.StatusOK) encodedUserAgent := r.Header.Get("X-Stripe-Client-User-Agent") - assert.NotEmpty(t, encodedUserAgent) + require.NotEmpty(t, encodedUserAgent) var userAgent map[string]string err := json.Unmarshal([]byte(encodedUserAgent), &userAgent) - assert.NoError(t, err) + require.NoError(t, err) // Just test a few headers that we know to be stable. - assert.Equal(t, "stripe-cli", userAgent["name"]) - assert.Equal(t, "stripe", userAgent["publisher"]) + require.Equal(t, "stripe-cli", userAgent["name"]) + require.Equal(t, "stripe", userAgent["publisher"]) })) defer ts.Close() diff --git a/pkg/validators/cmds_test.go b/pkg/validators/cmds_test.go index 8d8261958..30bc0b493 100644 --- a/pkg/validators/cmds_test.go +++ b/pkg/validators/cmds_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/spf13/cobra" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestNoArgs(t *testing.T) { @@ -12,7 +12,7 @@ func TestNoArgs(t *testing.T) { args := []string{} result := NoArgs(c, args) - assert.Nil(t, result) + require.Nil(t, result) } func TestNoArgsWithArgs(t *testing.T) { @@ -20,7 +20,7 @@ func TestNoArgsWithArgs(t *testing.T) { args := []string{"foo"} result := NoArgs(c, args) - assert.EqualError(t, result, "c does not take any arguments. See `stripe c --help` for supported flags and usage") + require.EqualError(t, result, "c does not take any arguments. See `stripe c --help` for supported flags and usage") } func TestExactArgs(t *testing.T) { @@ -28,7 +28,7 @@ func TestExactArgs(t *testing.T) { args := []string{"foo"} result := ExactArgs(1)(c, args) - assert.Nil(t, result) + require.Nil(t, result) } func TestExactArgsTooMany(t *testing.T) { @@ -36,7 +36,7 @@ func TestExactArgsTooMany(t *testing.T) { args := []string{"foo", "bar"} result := ExactArgs(1)(c, args) - assert.EqualError(t, result, "c only takes 1 argument. See `stripe c --help` for supported flags and usage") + require.EqualError(t, result, "c only takes 1 argument. See `stripe c --help` for supported flags and usage") } func TestExactArgsTooManyMoreThan1(t *testing.T) { @@ -44,5 +44,5 @@ func TestExactArgsTooManyMoreThan1(t *testing.T) { args := []string{"foo", "bar", "baz"} result := ExactArgs(2)(c, args) - assert.EqualError(t, result, "c only takes 2 arguments. See `stripe c --help` for supported flags and usage") + require.EqualError(t, result, "c only takes 2 arguments. See `stripe c --help` for supported flags and usage") } diff --git a/pkg/validators/validate.go b/pkg/validators/validate.go index 0a0dffa0b..b67edddd8 100644 --- a/pkg/validators/validate.go +++ b/pkg/validators/validate.go @@ -3,14 +3,17 @@ package validators import ( "errors" "fmt" + "net/http" "strconv" "strings" ) +// ArgValidator is an argument validator. It accepts a string and returns an +// error if the string is invalid, or nil otherwise. type ArgValidator func(string) error -// Call allows any validator to be called on a specified string array argument -// If the arg is empty, then the validator is not called. +// CallNonEmptyArray calls an argument validator on all non-empty elements of +// a string array. func CallNonEmptyArray(validator ArgValidator, values []string) error { if len(values) == 0 { return nil @@ -26,6 +29,8 @@ func CallNonEmptyArray(validator ArgValidator, values []string) error { return nil } +// CallNonEmpty calls an argument validator on a string if the string is not +// empty. func CallNonEmpty(validator ArgValidator, value string) error { if value == "" { return nil @@ -34,7 +39,7 @@ func CallNonEmpty(validator ArgValidator, value string) error { return validator(value) } -// APIKey validates an API key. +// APIKey validates that a string looks like an API key. func APIKey(input string) error { if len(input) < 12 { return errors.New("API key is too short, must be at least 12 characters long") @@ -56,7 +61,7 @@ func APIKey(input string) error { return nil } -// Filter argument validators +// Account validates that a string is an acceptable account filter. func Account(account string) error { accountUpper := strings.ToUpper(account) @@ -67,16 +72,18 @@ func Account(account string) error { return fmt.Errorf("%s is not an acceptable account filter (CONNECT_IN, CONNECT_OUT, SELF)", account) } +// HTTPMethod validates that a string is an acceptable HTTP method. func HTTPMethod(method string) error { methodUpper := strings.ToUpper(method) - if methodUpper == "GET" || methodUpper == "POST" || methodUpper == "DELETE" { + if methodUpper == http.MethodGet || methodUpper == http.MethodPost || methodUpper == http.MethodDelete { return nil } return fmt.Errorf("%s is not an acceptable HTTP method (GET, POST, DELETE)", method) } +// RequestSource validates that a string is an acceptable request source. func RequestSource(source string) error { sourceUpper := strings.ToUpper(source) @@ -87,6 +94,7 @@ func RequestSource(source string) error { return fmt.Errorf("%s is not an acceptable source (API, DASHBOARD)", source) } +// RequestStatus validates that a string is an acceptable request status. func RequestStatus(status string) error { statusUpper := strings.ToUpper(status) @@ -97,7 +105,8 @@ func RequestStatus(status string) error { return fmt.Errorf("%s is not an acceptable request status (SUCCEEDED, FAILED)", status) } -// StatusCode validates that a provided status code is within the range of those used in the Stripe API +// StatusCode validates that a provided status code is within the range of +// those used in the Stripe API. func StatusCode(code string) error { num, err := strconv.Atoi(code) if err != nil { @@ -115,7 +124,8 @@ func StatusCode(code string) error { return fmt.Errorf("Provided status code %s is not in the range of acceptable status codes (200's, 400's, 500's)", code) } -// StatusCodeType validates that a provided status code type is one of those used in the Stripe API +// StatusCodeType validates that a provided status code type is one of those +// used in the Stripe API. func StatusCodeType(code string) error { codeUpper := strings.ToUpper(code) diff --git a/pkg/validators/validate_test.go b/pkg/validators/validate_test.go index b0f450cae..54b9c47e2 100644 --- a/pkg/validators/validate_test.go +++ b/pkg/validators/validate_test.go @@ -4,100 +4,100 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestLegacyAPIKeys(t *testing.T) { err := APIKey("sk_123457890abcdef") - assert.EqualError(t, err, "you are using a legacy-style API key which is unsupported by the CLI. Please generate a new test mode API key") + require.EqualError(t, err, "you are using a legacy-style API key which is unsupported by the CLI. Please generate a new test mode API key") } func TestPublishableAPIKey(t *testing.T) { err := APIKey("pk_test_12345") - assert.EqualError(t, err, "the CLI only supports using a secret or restricted key") + require.EqualError(t, err, "the CLI only supports using a secret or restricted key") } func TestLivemodeAPIKey(t *testing.T) { err := APIKey("sk_live_12345") - assert.EqualError(t, err, "the CLI only supports using a test mode key") + require.EqualError(t, err, "the CLI only supports using a test mode key") } func TestTestmodeAPIKey(t *testing.T) { err := APIKey("sk_test_12345") - assert.Nil(t, err) + require.Nil(t, err) } func TestTestmodeRestrictedAPIKey(t *testing.T) { err := APIKey("rk_test_12345") - assert.Nil(t, err) + require.Nil(t, err) } func TestHTTPMethod(t *testing.T) { err := HTTPMethod("GET") - assert.Nil(t, err) + require.Nil(t, err) } func TestHTTPMethodInvalid(t *testing.T) { err := HTTPMethod("invalid") - assert.Equal(t, "invalid is not an acceptable HTTP method (GET, POST, DELETE)", fmt.Sprintf("%s", err)) + require.Equal(t, "invalid is not an acceptable HTTP method (GET, POST, DELETE)", fmt.Sprintf("%s", err)) } func TestHTTPMethodLowercase(t *testing.T) { err := HTTPMethod("post") - assert.Nil(t, err) + require.Nil(t, err) } func TestRequestSourceAPI(t *testing.T) { err := RequestSource("API") - assert.Nil(t, err) + require.Nil(t, err) } func TestRequestSourceDashboard(t *testing.T) { err := RequestSource("dashboard") - assert.Nil(t, err) + require.Nil(t, err) } func TestRequestStatusSucceeded(t *testing.T) { err := RequestStatus("succeeded") - assert.Nil(t, err) + require.Nil(t, err) } func TestRequestStatusFailed(t *testing.T) { err := RequestStatus("failed") - assert.Nil(t, err) + require.Nil(t, err) } func TestRequestStatusInvalid(t *testing.T) { err := RequestStatus("invalid") - assert.Equal(t, "invalid is not an acceptable request status (SUCCEEDED, FAILED)", fmt.Sprintf("%s", err)) + require.Equal(t, "invalid is not an acceptable request status (SUCCEEDED, FAILED)", fmt.Sprintf("%s", err)) } func TestRequestSourceInvalid(t *testing.T) { err := RequestSource("invalid") - assert.Equal(t, "invalid is not an acceptable source (API, DASHBOARD)", fmt.Sprintf("%s", err)) + require.Equal(t, "invalid is not an acceptable source (API, DASHBOARD)", fmt.Sprintf("%s", err)) } func TestStatusCode(t *testing.T) { err := StatusCode("200") - assert.Nil(t, err) + require.Nil(t, err) } func TestStatusCodeUnusedInStripe(t *testing.T) { err := StatusCode("300") - assert.Equal(t, "Provided status code 300 is not in the range of acceptable status codes (200's, 400's, 500's)", fmt.Sprintf("%s", err)) + require.Equal(t, "Provided status code 300 is not in the range of acceptable status codes (200's, 400's, 500's)", fmt.Sprintf("%s", err)) } func TestStatusCodeType(t *testing.T) { err := StatusCodeType("2Xx") - assert.Nil(t, err) + require.Nil(t, err) } func TestStatusCodeTypeUnusedInStripe(t *testing.T) { err := StatusCodeType("3XX") - assert.Equal(t, "Provided status code type 3XX is not a valid type (2XX, 4XX, 5XX)", fmt.Sprintf("%s", err)) + require.Equal(t, "Provided status code type 3XX is not a valid type (2XX, 4XX, 5XX)", fmt.Sprintf("%s", err)) } func TestStatusCodeNotXs(t *testing.T) { err := StatusCodeType("201") - assert.Equal(t, "Provided status code type 201 is not a valid type (2XX, 4XX, 5XX)", fmt.Sprintf("%s", err)) + require.Equal(t, "Provided status code type 201 is not a valid type (2XX, 4XX, 5XX)", fmt.Sprintf("%s", err)) } diff --git a/pkg/version/version.go b/pkg/version/version.go index 580d696e4..3b0840377 100644 --- a/pkg/version/version.go +++ b/pkg/version/version.go @@ -6,10 +6,11 @@ import ( "github.com/stripe/stripe-cli/pkg/ansi" ) -// Version of the CLI -- currently in beta +// Version of the CLI -- currently in beta. // This is set to the actual version by GoReleaser, identify by the -// git tag assigned to the release Versions built from source will +// git tag assigned to the release. Versions built from source will // always show master. var Version = "master" +// Template for the version string. var Template = fmt.Sprintf("stripe version %s %s\n", Version, ansi.Bold("(beta)")) diff --git a/pkg/websocket/client_test.go b/pkg/websocket/client_test.go index da5a1f904..cd51bf650 100644 --- a/pkg/websocket/client_test.go +++ b/pkg/websocket/client_test.go @@ -10,7 +10,7 @@ import ( "time" ws "github.com/gorilla/websocket" - assert "github.com/stretchr/testify/require" + "github.com/stretchr/testify/require" ) func TestClientWebhookEventHandler(t *testing.T) { @@ -19,13 +19,13 @@ func TestClientWebhookEventHandler(t *testing.T) { upgrader := ws.Upgrader{} ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.NotEmpty(t, r.UserAgent()) - assert.NotEmpty(t, r.Header.Get("X-Stripe-Client-User-Agent")) - assert.Equal(t, "websocket-random-id", r.Header.Get("Websocket-Id")) + require.NotEmpty(t, r.UserAgent()) + require.NotEmpty(t, r.Header.Get("X-Stripe-Client-User-Agent")) + require.Equal(t, "websocket-random-id", r.Header.Get("Websocket-Id")) c, err := upgrader.Upgrade(w, r, nil) - assert.Nil(t, err) + require.Nil(t, err) - assert.Equal(t, "websocket_feature=webhook-payloads", r.URL.RawQuery) + require.Equal(t, "websocket_feature=webhook-payloads", r.URL.RawQuery) defer c.Close() @@ -39,10 +39,10 @@ func TestClientWebhookEventHandler(t *testing.T) { } msg, err := json.Marshal(evt) - assert.Nil(t, err) + require.Nil(t, err) err = c.WriteMessage(ws.TextMessage, msg) - assert.Nil(t, err) + require.Nil(t, err) })) defer ts.Close() @@ -72,12 +72,12 @@ func TestClientWebhookEventHandler(t *testing.T) { select { case <-done: case <-time.After(500 * time.Millisecond): - assert.FailNow(t, "Timed out waiting for response from test server") + require.FailNow(t, "Timed out waiting for response from test server") } - assert.Equal(t, "TestAgent/v1", rcvMsg.HTTPHeaders["User-Agent"]) - assert.Equal(t, "t=123,v1=hunter2", rcvMsg.HTTPHeaders["Stripe-Signature"]) - assert.Equal(t, "{}", rcvMsg.EventPayload) + require.Equal(t, "TestAgent/v1", rcvMsg.HTTPHeaders["User-Agent"]) + require.Equal(t, "t=123,v1=hunter2", rcvMsg.HTTPHeaders["Stripe-Signature"]) + require.Equal(t, "{}", rcvMsg.EventPayload) } func TestClientRequestLogEventHandler(t *testing.T) { @@ -86,27 +86,27 @@ func TestClientRequestLogEventHandler(t *testing.T) { upgrader := ws.Upgrader{} ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.NotEmpty(t, r.UserAgent()) - assert.NotEmpty(t, r.Header.Get("X-Stripe-Client-User-Agent")) - assert.Equal(t, "websocket-random-id", r.Header.Get("Websocket-Id")) + require.NotEmpty(t, r.UserAgent()) + require.NotEmpty(t, r.Header.Get("X-Stripe-Client-User-Agent")) + require.Equal(t, "websocket-random-id", r.Header.Get("Websocket-Id")) c, err := upgrader.Upgrade(w, r, nil) - assert.Nil(t, err) + require.Nil(t, err) - assert.Equal(t, "websocket_feature=request-log-payloads", r.URL.RawQuery) + require.Equal(t, "websocket_feature=request-log-payloads", r.URL.RawQuery) defer c.Close() evt := RequestLogEvent{ EventPayload: "{}", RequestLogID: "resp_123", - Type: "request_log_event", + Type: "request_log_event", } msg, err := json.Marshal(evt) - assert.Nil(t, err) + require.Nil(t, err) err = c.WriteMessage(ws.TextMessage, msg) - assert.Nil(t, err) + require.Nil(t, err) })) defer ts.Close() @@ -136,10 +136,10 @@ func TestClientRequestLogEventHandler(t *testing.T) { select { case <-done: case <-time.After(500 * time.Millisecond): - assert.FailNow(t, "Timed out waiting for response from test server") + require.FailNow(t, "Timed out waiting for response from test server") } - assert.Equal(t, "resp_123", rcvMsg.RequestLogID) - assert.Equal(t, "request_log_event", rcvMsg.Type) - assert.Equal(t, "{}", rcvMsg.EventPayload) + require.Equal(t, "resp_123", rcvMsg.RequestLogID) + require.Equal(t, "request_log_event", rcvMsg.Type) + require.Equal(t, "{}", rcvMsg.EventPayload) } diff --git a/pkg/websocket/messages_test.go b/pkg/websocket/messages_test.go index 9fbded121..a8373d2b6 100644 --- a/pkg/websocket/messages_test.go +++ b/pkg/websocket/messages_test.go @@ -4,7 +4,7 @@ import ( "encoding/json" "testing" - assert "github.com/stretchr/testify/require" + "github.com/stretchr/testify/require" "github.com/tidwall/gjson" ) @@ -13,15 +13,15 @@ func TestUnmarshalWebhookEvent(t *testing.T) { var msg IncomingMessage err := json.Unmarshal([]byte(data), &msg) - assert.Nil(t, err) + require.Nil(t, err) - assert.NotNil(t, msg.WebhookEvent) - assert.Nil(t, msg.RequestLogEvent) + require.NotNil(t, msg.WebhookEvent) + require.Nil(t, msg.RequestLogEvent) - assert.Equal(t, "foo", msg.WebhookEvent.EventPayload) - assert.Equal(t, "bar", msg.WebhookEvent.HTTPHeaders["Request-Header"]) - assert.Equal(t, "webhook_event", msg.WebhookEvent.Type) - assert.Equal(t, "wh_123", msg.WebhookEvent.WebhookID) + require.Equal(t, "foo", msg.WebhookEvent.EventPayload) + require.Equal(t, "bar", msg.WebhookEvent.HTTPHeaders["Request-Header"]) + require.Equal(t, "webhook_event", msg.WebhookEvent.Type) + require.Equal(t, "wh_123", msg.WebhookEvent.WebhookID) } func TestUnmarshalRequestLogEvent(t *testing.T) { @@ -29,14 +29,14 @@ func TestUnmarshalRequestLogEvent(t *testing.T) { var msg IncomingMessage err := json.Unmarshal([]byte(data), &msg) - assert.Nil(t, err) + require.Nil(t, err) - assert.NotNil(t, msg.RequestLogEvent) - assert.Nil(t, msg.WebhookEvent) + require.NotNil(t, msg.RequestLogEvent) + require.Nil(t, msg.WebhookEvent) - assert.Equal(t, "foo", msg.RequestLogEvent.EventPayload) - assert.Equal(t, "resp_123", msg.RequestLogEvent.RequestLogID) - assert.Equal(t, "request_log_event", msg.RequestLogEvent.Type) + require.Equal(t, "foo", msg.RequestLogEvent.EventPayload) + require.Equal(t, "resp_123", msg.RequestLogEvent.RequestLogID) + require.Equal(t, "request_log_event", msg.RequestLogEvent.Type) } func TestUnmarshalUnknownIncomingMsg(t *testing.T) { @@ -44,18 +44,18 @@ func TestUnmarshalUnknownIncomingMsg(t *testing.T) { var msg IncomingMessage err := json.Unmarshal([]byte(data), &msg) - assert.EqualError(t, err, "Unexpected message type: unknown_type") + require.EqualError(t, err, "Unexpected message type: unknown_type") } func TestMarshalWebhookResponse(t *testing.T) { msg := NewWebhookResponse("wh_123", 200, "foo", map[string]string{"Response-Header": "bar"}) buf, err := json.Marshal(msg) - assert.Nil(t, err) + require.Nil(t, err) json := string(buf) - assert.Equal(t, "wh_123", gjson.Get(json, "webhook_id").String()) - assert.Equal(t, 200, int(gjson.Get(json, "status").Num)) - assert.Equal(t, "foo", gjson.Get(json, "body").String()) - assert.Equal(t, "bar", gjson.Get(json, "http_headers.Response-Header").String()) + require.Equal(t, "wh_123", gjson.Get(json, "webhook_id").String()) + require.Equal(t, 200, int(gjson.Get(json, "status").Num)) + require.Equal(t, "foo", gjson.Get(json, "body").String()) + require.Equal(t, "bar", gjson.Get(json, "http_headers.Response-Header").String()) } diff --git a/pkg/websocket/webhook_messages_test.go b/pkg/websocket/webhook_messages_test.go index 9aced232d..e9fe88e30 100644 --- a/pkg/websocket/webhook_messages_test.go +++ b/pkg/websocket/webhook_messages_test.go @@ -3,15 +3,15 @@ package websocket import ( "testing" - assert "github.com/stretchr/testify/require" + "github.com/stretchr/testify/require" ) func TestNewWebhookResponse(t *testing.T) { msg := NewWebhookResponse("wh_123", 200, "foo", map[string]string{"Response-Header": "bar"}) - assert.NotNil(t, msg.WebhookResponse) - assert.Equal(t, "webhook_response", msg.Type) - assert.Equal(t, "wh_123", msg.WebhookID) - assert.Equal(t, 200, msg.Status) - assert.Equal(t, "foo", msg.Body) - assert.Equal(t, "bar", msg.HTTPHeaders["Response-Header"]) + require.NotNil(t, msg.WebhookResponse) + require.Equal(t, "webhook_response", msg.Type) + require.Equal(t, "wh_123", msg.WebhookID) + require.Equal(t, 200, msg.Status) + require.Equal(t, "foo", msg.Body) + require.Equal(t, "bar", msg.HTTPHeaders["Response-Header"]) }