From 3dcb62024a7932b8f22de8384f48aa739cad064a Mon Sep 17 00:00:00 2001 From: "renovate-update-app[bot]" <291053684+renovate-update-app[bot]@users.noreply.github.com> Date: Sat, 24 Oct 2026 01:23:23 +0000 Subject: [PATCH 1/3] Update CI tools --- .github/workflows/ci.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 10237838..8f10e55c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -62,7 +62,7 @@ jobs: # Require: The version of golangci-lint to use. # When `install-mode` is `binary` (default) the value can be v1.2 or v1.2.3 or `latest` to use the latest version. # When `install-mode` is `goinstall` the value can be v1.2.3, `latest`, or the hash of a commit. - version: v2.9.0 + version: v2.15.0 check-license: name: License scan @@ -115,7 +115,7 @@ jobs: # either 'goreleaser' (default) or 'goreleaser-pro' distribution: goreleaser # 'latest', 'nightly', or a semver - version: v1.25.1 + version: v1.26.2 args: check test: @@ -187,7 +187,7 @@ jobs: # either 'goreleaser' (default) or 'goreleaser-pro' distribution: goreleaser # 'latest', 'nightly', or a semver - version: v1.25.1 + version: v1.26.2 args: release - name: Write latest version to file run: mkdir -p dist && printf '%s\n' "${TAG}" > dist/LATEST_VERSION From ba2c89d6319fe4029f78faff7dabb60dbfaf07f4 Mon Sep 17 00:00:00 2001 From: Remco Beckers Date: Mon, 16 Nov 2026 11:18:23 +0000 Subject: [PATCH 2/3] Fix lint findings exposed by the CI tools upgrade Extract repeated output keys and test fixture strings without changing their values. Replace the reflect.Ptr alias with reflect.Pointer for the newer vet analyzer. Validated with golangci-lint 2.15.0, go test ./..., Zizmor, and an AST comparison preserving existing expressions and literal values. --- cmd/context/context_delete_test.go | 11 +- cmd/context/context_save.go | 5 +- cmd/context/context_save_test.go | 71 ++++--- cmd/context/context_set.go | 2 +- cmd/context/context_set_test.go | 6 +- cmd/context/context_show.go | 2 +- cmd/context/context_show_test.go | 2 +- cmd/context/context_validate_test.go | 2 +- cmd/dashboard/common_test.go | 10 +- cmd/dashboard/dashboard_apply.go | 10 +- cmd/dashboard/dashboard_apply_test.go | 6 +- cmd/dashboard/dashboard_clone.go | 2 +- cmd/dashboard/dashboard_delete_test.go | 4 +- cmd/dashboard/dashboard_describe_test.go | 2 +- cmd/dashboard/dashboard_edit.go | 4 +- cmd/dashboard/dashboard_edit_test.go | 4 +- cmd/dashboard/dashboard_list_test.go | 10 +- cmd/health/health_delete_test.go | 10 +- cmd/health/health_list_test.go | 21 +- cmd/health/health_status.go | 19 +- cmd/health/health_status_test.go | 86 ++++---- cmd/license/common.go | 10 +- cmd/monitor/monitor_apply.go | 14 +- cmd/monitor/monitor_clone.go | 6 +- cmd/monitor/monitor_disable.go | 2 +- cmd/monitor/monitor_disable_test.go | 4 +- cmd/monitor/monitor_edit.go | 6 +- cmd/monitor/monitor_enable.go | 2 +- cmd/monitor/monitor_enable_test.go | 4 +- cmd/monitor/monitor_list.go | 2 +- cmd/monitor/monitor_status_test.go | 26 ++- .../otelcomponentmapping_apply_test.go | 17 +- .../otelrelationmapping_apply_test.go | 17 +- .../otelrelationmapping_edit_test.go | 10 +- cmd/rbac/rbac_describe_permissions.go | 14 +- cmd/rbac/rbac_describe_permissions_test.go | 36 ++-- cmd/rbac/rbac_describe_subjects_test.go | 26 ++- cmd/rbac/rbac_grant.go | 4 +- cmd/rbac/rbac_list_permissions.go | 2 +- cmd/rbac/rbac_list_permissions_test.go | 8 +- cmd/rbac/rbac_revoke.go | 4 +- cmd/script/script_run_test.go | 13 +- cmd/servicetoken/servicetoken_create_test.go | 44 ++-- cmd/servicetoken/servicetoken_list_test.go | 10 +- cmd/settings/settings_apply.go | 8 +- cmd/settings/settings_apply_test.go | 2 +- cmd/settings/settings_edit.go | 2 +- cmd/settings/settings_list.go | 2 +- cmd/settings/settings_list_test.go | 22 +- cmd/settings/settings_list_types_test.go | 15 +- cmd/stackpack/common.go | 10 +- cmd/stackpack/common_test.go | 18 +- .../stackpack_confirm_manual_steps.go | 6 +- .../stackpack_confirm_manual_steps_test.go | 12 +- .../stackpack_delete_version_test.go | 8 +- .../stackpack_delete_versions_test.go | 27 ++- cmd/stackpack/stackpack_describe.go | 11 +- cmd/stackpack/stackpack_describe_test.go | 38 ++-- cmd/stackpack/stackpack_downgrade.go | 2 +- cmd/stackpack/stackpack_downgrade_test.go | 12 +- cmd/stackpack/stackpack_install.go | 14 +- cmd/stackpack/stackpack_install_test.go | 35 ++-- cmd/stackpack/stackpack_list.go | 2 +- cmd/stackpack/stackpack_list_instances.go | 2 +- .../stackpack_list_instances_test.go | 6 +- cmd/stackpack/stackpack_list_parameters.go | 2 +- .../stackpack_list_parameters_test.go | 8 +- cmd/stackpack/stackpack_list_test.go | 4 +- cmd/stackpack/stackpack_list_versions.go | 2 +- cmd/stackpack/stackpack_list_versions_test.go | 28 +-- cmd/stackpack/stackpack_package.go | 2 +- cmd/stackpack/stackpack_package_test.go | 42 ++-- cmd/stackpack/stackpack_scaffold.go | 8 +- cmd/stackpack/stackpack_scaffold_test.go | 193 +++++++++--------- cmd/stackpack/stackpack_test_deploy.go | 10 +- cmd/stackpack/stackpack_test_deploy_test.go | 51 ++--- cmd/stackpack/stackpack_uninstall.go | 4 +- cmd/stackpack/stackpack_uninstall_test.go | 16 +- cmd/stackpack/stackpack_upgrade.go | 6 +- cmd/stackpack/stackpack_upgrade_test.go | 30 +-- cmd/stackpack/stackpack_upload.go | 2 +- cmd/stackpack/stackpack_upload_test.go | 20 +- cmd/stackpack/stackpack_validate.go | 4 +- cmd/stackpack/stackpack_validate_test.go | 16 +- cmd/topic/topic_describe_test.go | 12 +- cmd/topology/topology_inspect.go | 27 ++- cmd/topology/topology_inspect_test.go | 76 ++++--- cmd/topology/topology_state.go | 12 +- cmd/topology/topology_state_test.go | 102 ++++----- cmd/topology/topology_test_helper.go | 18 +- .../topologysync_describe_test.go | 9 +- cmd/topologysync/topologysync_list_test.go | 6 +- internal/client/client_test.go | 36 ++-- internal/config/config_test.go | 48 +++-- internal/printer/printer.go | 4 +- internal/printer/printer_test.go | 34 +-- internal/util/string_util.go | 2 +- internal/util/string_util_test.go | 23 ++- main_test.go | 32 +-- pkg/pflags/duration_flag_test.go | 6 +- pkg/pflags/relative_time_flag_test.go | 2 +- pkg/scaffold/github_source_test.go | 121 ++++++----- pkg/scaffold/scaffolder_test.go | 103 ++++++---- pkg/scaffold/template_source_test.go | 18 +- 104 files changed, 1133 insertions(+), 830 deletions(-) diff --git a/cmd/context/context_delete_test.go b/cmd/context/context_delete_test.go index 4d758532..ba2d91e2 100644 --- a/cmd/context/context_delete_test.go +++ b/cmd/context/context_delete_test.go @@ -8,12 +8,17 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + testBar = "bar" + nameFlagArg = "--name" +) + func TestDeleteCurrentContext(t *testing.T) { cli := di.NewMockDeps(t) setupConfig(t, &cli) cmd := DeleteCommand(&cli.Deps) - _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "--name", "foo") + _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, nameFlagArg, "foo") assert.Errorf(t, err, "cannot delete the current context (foo)") } @@ -22,7 +27,7 @@ func TestDeleteNonExistingContext(t *testing.T) { setupConfig(t, &cli) cmd := DeleteCommand(&cli.Deps) - _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "--name", "x") + _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, nameFlagArg, "x") assert.Errorf(t, err, "context with name 'x' not found") } @@ -31,7 +36,7 @@ func TestDeleteContext(t *testing.T) { setupConfig(t, &cli) cmd := DeleteCommand(&cli.Deps) - _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "--name", "bar") + _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, nameFlagArg, testBar) assert.NoError(t, err) cfg, err := config.ReadConfig(cli.ConfigPath) diff --git a/cmd/context/context_save.go b/cmd/context/context_save.go index e05b28b0..a8708d35 100644 --- a/cmd/context/context_save.go +++ b/cmd/context/context_save.go @@ -12,7 +12,8 @@ import ( ) const ( - APIPathFlag = "api-path" + currentContextKey = "current-context" + APIPathFlag = "api-path" ) type SaveArgs struct { @@ -112,7 +113,7 @@ func RunContextSaveCommand(args *SaveArgs) func(cli *di.Deps, cmd *cobra.Command if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "current-context": cfg.CurrentContext, + currentContextKey: cfg.CurrentContext, "context": namedCtx.Context, }) } else { diff --git a/cmd/context/context_save_test.go b/cmd/context/context_save_test.go index a6f68a17..faab2008 100644 --- a/cmd/context/context_save_test.go +++ b/cmd/context/context_save_test.go @@ -11,6 +11,17 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + testToken = "my-token" + testContextURL = "http://bar.com" + urlFlagArg = "--url" + testCACertContext = "cacertdata" + testAPIPath = "/api" + serviceTokenFlagArg = "--service-token" + caCertPathFlagArg = "--ca-cert-path" + caCertBase64DataFlagArg = "--ca-cert-base64-data" +) + func setupSaveCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { cli := di.NewMockDeps(t) cmd := SaveCommand(&cli.Deps) @@ -29,13 +40,13 @@ func TestSaveContext(t *testing.T) { //nolint:funlen }{ { name: "new context", - args: []string{"--name", "baz", "--url", "http://baz.com", "--api-token", "my-token"}, + args: []string{nameFlagArg, "baz", urlFlagArg, "http://baz.com", "--api-token", testToken}, expectedContext: config.NamedContext{ Name: "baz", Context: &config.StsContext{ URL: "http://baz.com", - APIToken: "my-token", - APIPath: "/api", + APIToken: testToken, + APIPath: testAPIPath, }, }, totalContextInConfig: 7, @@ -43,13 +54,13 @@ func TestSaveContext(t *testing.T) { //nolint:funlen }, { name: "existing context", - args: []string{"--name", "bar", "--url", "http://bar.com", "--service-token", "my-token"}, + args: []string{nameFlagArg, testBar, urlFlagArg, testContextURL, serviceTokenFlagArg, testToken}, expectedContext: config.NamedContext{ - Name: "bar", + Name: testBar, Context: &config.StsContext{ - URL: "http://bar.com", - ServiceToken: "my-token", - APIPath: "/api", + URL: testContextURL, + ServiceToken: testToken, + APIPath: testAPIPath, }, }, totalContextInConfig: 6, @@ -57,13 +68,13 @@ func TestSaveContext(t *testing.T) { //nolint:funlen }, { name: "existing context ca-cert is set with ca-cert-path", - args: []string{"--name", "bar", "--url", "http://bar.com", "--service-token", "my-token", "--ca-cert-path", "testdata/selfSignedCert.crt"}, + args: []string{nameFlagArg, testBar, urlFlagArg, testContextURL, serviceTokenFlagArg, testToken, caCertPathFlagArg, "testdata/selfSignedCert.crt"}, expectedContext: config.NamedContext{ - Name: "bar", + Name: testBar, Context: &config.StsContext{ - URL: "http://bar.com", - ServiceToken: "my-token", - APIPath: "/api", + URL: testContextURL, + ServiceToken: testToken, + APIPath: testAPIPath, CaCertBase64Data: selfSignedBase64Cert, }, }, @@ -72,13 +83,13 @@ func TestSaveContext(t *testing.T) { //nolint:funlen }, { name: "new context ca-cert is set with ca-cert-path", - args: []string{"--name", "cacertdata", "--url", "http://bar.com", "--service-token", "my-token", "--ca-cert-base64-data", privateCaBase64Cert}, + args: []string{nameFlagArg, testCACertContext, urlFlagArg, testContextURL, serviceTokenFlagArg, testToken, caCertBase64DataFlagArg, privateCaBase64Cert}, expectedContext: config.NamedContext{ - Name: "cacertdata", + Name: testCACertContext, Context: &config.StsContext{ - URL: "http://bar.com", - ServiceToken: "my-token", - APIPath: "/api", + URL: testContextURL, + ServiceToken: testToken, + APIPath: testAPIPath, CaCertBase64Data: privateCaBase64Cert, }, }, @@ -87,13 +98,13 @@ func TestSaveContext(t *testing.T) { //nolint:funlen }, { name: "ca-cert-path takes precedence over ca-cert-base64-data", - args: []string{"--name", "cacertdata", "--url", "http://bar.com", "--service-token", "my-token", "--ca-cert-path", "testdata/selfSignedCert.crt", "--ca-cert-base64-data", privateCaBase64Cert}, + args: []string{nameFlagArg, testCACertContext, urlFlagArg, testContextURL, serviceTokenFlagArg, testToken, caCertPathFlagArg, "testdata/selfSignedCert.crt", caCertBase64DataFlagArg, privateCaBase64Cert}, expectedContext: config.NamedContext{ - Name: "cacertdata", + Name: testCACertContext, Context: &config.StsContext{ - URL: "http://bar.com", - ServiceToken: "my-token", - APIPath: "/api", + URL: testContextURL, + ServiceToken: testToken, + APIPath: testAPIPath, CaCertBase64Data: selfSignedBase64Cert, }, }, @@ -102,13 +113,13 @@ func TestSaveContext(t *testing.T) { //nolint:funlen }, { name: "ca-cert ignored if skip-ssl is set", - args: []string{"--name", "bar", "--url", "http://bar.com", "--service-token", "my-token", "--skip-ssl", "--ca-cert-path", "/path/to/ca.crt", "--ca-cert-base64-data", "base64-data"}, + args: []string{nameFlagArg, testBar, urlFlagArg, testContextURL, serviceTokenFlagArg, testToken, "--skip-ssl", caCertPathFlagArg, "/path/to/ca.crt", caCertBase64DataFlagArg, "base64-data"}, expectedContext: config.NamedContext{ - Name: "bar", + Name: testBar, Context: &config.StsContext{ - URL: "http://bar.com", - ServiceToken: "my-token", - APIPath: "/api", + URL: testContextURL, + ServiceToken: testToken, + APIPath: testAPIPath, SkipSSL: true, CaCertBase64Data: "", CaCertPath: "", @@ -119,14 +130,14 @@ func TestSaveContext(t *testing.T) { //nolint:funlen }, { name: "no save on missing tokens", - args: []string{"--name", "bar", "--url", "http://my-bar.com"}, + args: []string{nameFlagArg, testBar, urlFlagArg, "http://my-bar.com"}, expectedContext: config.NamedContext{}, wantErr: true, errorMessage: "one of the required flags {api-token | service-token} not set", }, { name: "ca-cert-path is not found", - args: []string{"--name", "bar", "--url", "http://my-bar.com", "--service-token", "my-token", "--ca-cert-path", "/path/to/ca.crt"}, + args: []string{nameFlagArg, testBar, urlFlagArg, "http://my-bar.com", serviceTokenFlagArg, testToken, caCertPathFlagArg, "/path/to/ca.crt"}, expectedContext: config.NamedContext{}, wantErr: true, errorMessage: "no such file or directory", diff --git a/cmd/context/context_set.go b/cmd/context/context_set.go index 6ced7136..f89f0d74 100644 --- a/cmd/context/context_set.go +++ b/cmd/context/context_set.go @@ -47,7 +47,7 @@ func RunContextSetCommand(args *SetArgs, cli *di.Deps) func(cli *di.Deps, cmd *c if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "current-context": args.Name, + currentContextKey: args.Name, }) } else { cli.Printer.PrintLn(fmt.Sprintf("Current context set to %s", args.Name)) diff --git a/cmd/context/context_set_test.go b/cmd/context/context_set_test.go index d733e389..8deae131 100644 --- a/cmd/context/context_set_test.go +++ b/cmd/context/context_set_test.go @@ -13,12 +13,12 @@ func TestSetContext(t *testing.T) { setupConfig(t, &cli) cmd := SetCommand(&cli.Deps) - _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "--name", "bar") + _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, nameFlagArg, testBar) assert.NoError(t, err) cfg, err := config.ReadConfig(cli.ConfigPath) assert.NoError(t, err) - assert.Equal(t, "bar", cfg.CurrentContext) + assert.Equal(t, testBar, cfg.CurrentContext) } func TestSetUnknownContext(t *testing.T) { @@ -26,7 +26,7 @@ func TestSetUnknownContext(t *testing.T) { setupConfig(t, &cli) cmd := SetCommand(&cli.Deps) - _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "--name", "x") + _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, nameFlagArg, "x") assert.Errorf(t, err, "context with name 'x' not found") cfg, err := config.ReadConfig(cli.ConfigPath) diff --git a/cmd/context/context_show.go b/cmd/context/context_show.go index d064b27b..601bc4bb 100644 --- a/cmd/context/context_show.go +++ b/cmd/context/context_show.go @@ -31,7 +31,7 @@ func RunContextShowCommand(cli *di.Deps, cmd *cobra.Command, cfg *config.Config) if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "current-context": ctx.Context, + currentContextKey: ctx.Context, "name": cfg.CurrentContext, }) } else { diff --git a/cmd/context/context_show_test.go b/cmd/context/context_show_test.go index d0860d25..4c6d178b 100644 --- a/cmd/context/context_show_test.go +++ b/cmd/context/context_show_test.go @@ -24,7 +24,7 @@ func TestShowContextJSON(t *testing.T) { assert.Equal(t, &config.StsContext{ URL: "http://foo.com", APIToken: "apiToken", - APIPath: "/api", + APIPath: testAPIPath, }, calls[0]["current-context"]) } diff --git a/cmd/context/context_validate_test.go b/cmd/context/context_validate_test.go index 491dbc48..722b6f03 100644 --- a/cmd/context/context_validate_test.go +++ b/cmd/context/context_validate_test.go @@ -32,7 +32,7 @@ func TestValidationToJson(t *testing.T) { di.ExecuteCommandWithContextUnsafe( &cli.Deps, cmd, - "--url", + urlFlagArg, "https://test.stackstate.io/", "--api-token", "blaat", diff --git a/cmd/dashboard/common_test.go b/cmd/dashboard/common_test.go index cb27cf7e..fdf38974 100644 --- a/cmd/dashboard/common_test.go +++ b/cmd/dashboard/common_test.go @@ -6,6 +6,10 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + testDashboardURN = "urn:custom:dashboard:test" +) + func TestResolveDashboardIdOrUrn(t *testing.T) { tests := []struct { name string @@ -24,14 +28,14 @@ func TestResolveDashboardIdOrUrn(t *testing.T) { { name: "Should resolve valid identifier", id: 0, - identifier: "urn:custom:dashboard:test", - expectedResult: "urn:custom:dashboard:test", + identifier: testDashboardURN, + expectedResult: testDashboardURN, expectedError: "", }, { name: "Should prioritize ID when both are provided", id: 456, - identifier: "urn:custom:dashboard:test", + identifier: testDashboardURN, expectedResult: "456", expectedError: "", }, diff --git a/cmd/dashboard/dashboard_apply.go b/cmd/dashboard/dashboard_apply.go index a3128319..545c2d29 100644 --- a/cmd/dashboard/dashboard_apply.go +++ b/cmd/dashboard/dashboard_apply.go @@ -13,6 +13,10 @@ import ( "sigs.k8s.io/kustomize/kyaml/yaml" ) +const ( + dashboardKey = "dashboard" +) + // ApplyArgs contains arguments for dashboard apply command type ApplyArgs struct { File string @@ -93,7 +97,7 @@ func createDashboard(cli *di.Deps, api *stackstate_api.APIClient, fileBytes []by if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "dashboard": dashboard, + dashboardKey: dashboard, }) } else { cli.Printer.Success(fmt.Sprintf("Dashboard created successfully! ID: %d, Name: %s", dashboard.GetId(), dashboard.GetName())) @@ -118,7 +122,7 @@ func updateDashboard(cli *di.Deps, api *stackstate_api.APIClient, dashboardId st patchSchema.SetScope(*scope) } } - if dashboardContent, ok := dashboardData["dashboard"]; ok { + if dashboardContent, ok := dashboardData[dashboardKey]; ok { // Convert dashboard content to PersesDashboard dashboardBytes, err := yaml.Marshal(dashboardContent) if err == nil { @@ -137,7 +141,7 @@ func updateDashboard(cli *di.Deps, api *stackstate_api.APIClient, dashboardId st if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "dashboard": dashboard, + dashboardKey: dashboard, }) } else { cli.Printer.Success(fmt.Sprintf("Dashboard updated successfully! ID: %d, Name: %s", dashboard.GetId(), dashboard.GetName())) diff --git a/cmd/dashboard/dashboard_apply_test.go b/cmd/dashboard/dashboard_apply_test.go index 3e9b3aaa..f1660dbf 100644 --- a/cmd/dashboard/dashboard_apply_test.go +++ b/cmd/dashboard/dashboard_apply_test.go @@ -10,6 +10,10 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + testGrid = "Grid" +) + func setDashboardApplyCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { cli := di.NewMockDeps(t) cmd := DashboardApplyCommand(&cli.Deps) @@ -27,7 +31,7 @@ func createTestApplyResult() sts.DashboardReadFullSchema { Spec: &sts.PersesDashboardSpec{ Layouts: []sts.PersesLayout{ { - Kind: "Grid", + Kind: testGrid, Spec: sts.PersesLayoutSpec{ Items: []sts.PersesGridItem{}, }, diff --git a/cmd/dashboard/dashboard_clone.go b/cmd/dashboard/dashboard_clone.go index 05209a37..156d015d 100644 --- a/cmd/dashboard/dashboard_clone.go +++ b/cmd/dashboard/dashboard_clone.go @@ -85,7 +85,7 @@ func RunDashboardCloneCommand(args *CloneArgs) di.CmdWithApiFn { if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "dashboard": clonedDashboard, + dashboardKey: clonedDashboard, }) } else { cli.Printer.Success(fmt.Sprintf("Dashboard cloned successfully! New dashboard ID: %d, Name: %s", clonedDashboard.GetId(), clonedDashboard.GetName())) diff --git a/cmd/dashboard/dashboard_delete_test.go b/cmd/dashboard/dashboard_delete_test.go index 90789ea6..51ca9b63 100644 --- a/cmd/dashboard/dashboard_delete_test.go +++ b/cmd/dashboard/dashboard_delete_test.go @@ -28,11 +28,11 @@ func TestShouldDeleteDashboard(t *testing.T) { func TestShouldDeleteDashboardWithIdentifier(t *testing.T) { cli, cmd := setDashboardDeleteCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--identifier", "urn:custom:dashboard:test") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--identifier", testDashboardURN) assert.Len(t, *cli.MockClient.ApiMocks.DashboardsApi.DeleteDashboardCalls, 1) deleteCall := (*cli.MockClient.ApiMocks.DashboardsApi.DeleteDashboardCalls)[0] - assert.Equal(t, "urn:custom:dashboard:test", deleteCall.PdashboardIdOrUrn) + assert.Equal(t, testDashboardURN, deleteCall.PdashboardIdOrUrn) assert.Equal(t, "Dashboard deleted: urn:custom:dashboard:test", (*cli.MockPrinter.SuccessCalls)[0]) } diff --git a/cmd/dashboard/dashboard_describe_test.go b/cmd/dashboard/dashboard_describe_test.go index c6de4ca7..e785d8b3 100644 --- a/cmd/dashboard/dashboard_describe_test.go +++ b/cmd/dashboard/dashboard_describe_test.go @@ -27,7 +27,7 @@ func createTestDashboard() sts.DashboardReadSchema { Spec: &sts.PersesDashboardSpec{ Layouts: []sts.PersesLayout{ { - Kind: "Grid", + Kind: testGrid, Spec: sts.PersesLayoutSpec{ Items: []sts.PersesGridItem{}, }, diff --git a/cmd/dashboard/dashboard_edit.go b/cmd/dashboard/dashboard_edit.go index d3a71dd7..bc230b47 100644 --- a/cmd/dashboard/dashboard_edit.go +++ b/cmd/dashboard/dashboard_edit.go @@ -99,7 +99,7 @@ func RunDashboardEditCommand(args *EditArgs) di.CmdWithApiFn { patchSchema.SetScope(*scope) } } - if dashboardContent, ok := editedDashboard["dashboard"]; ok { + if dashboardContent, ok := editedDashboard[dashboardKey]; ok { // Convert dashboard content to PersesDashboard dashboardBytes, err := json.Marshal(dashboardContent) if err == nil { @@ -118,7 +118,7 @@ func RunDashboardEditCommand(args *EditArgs) di.CmdWithApiFn { if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "dashboard": updatedDashboard, + dashboardKey: updatedDashboard, }) } else { cli.Printer.Success(fmt.Sprintf("Dashboard updated successfully! ID: %d, Name: %s", updatedDashboard.GetId(), updatedDashboard.GetName())) diff --git a/cmd/dashboard/dashboard_edit_test.go b/cmd/dashboard/dashboard_edit_test.go index eac581cf..65a74824 100644 --- a/cmd/dashboard/dashboard_edit_test.go +++ b/cmd/dashboard/dashboard_edit_test.go @@ -41,7 +41,7 @@ func createEditTestDashboard() sts.DashboardReadSchema { Spec: &sts.PersesDashboardSpec{ Layouts: []sts.PersesLayout{ { - Kind: "Grid", + Kind: testGrid, Spec: sts.PersesLayoutSpec{ Items: []sts.PersesGridItem{}, }, @@ -65,7 +65,7 @@ func createEditResult() sts.DashboardReadFullSchema { Spec: &sts.PersesDashboardSpec{ Layouts: []sts.PersesLayout{ { - Kind: "Grid", + Kind: testGrid, Spec: sts.PersesLayoutSpec{ Items: []sts.PersesGridItem{}, }, diff --git a/cmd/dashboard/dashboard_list_test.go b/cmd/dashboard/dashboard_list_test.go index c7833810..2c4b18d2 100644 --- a/cmd/dashboard/dashboard_list_test.go +++ b/cmd/dashboard/dashboard_list_test.go @@ -10,6 +10,10 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + testDashboards = "dashboards" +) + var ( firstDashboardName = "aDashboard" firstDashboardId = int64(1) @@ -83,7 +87,7 @@ func TestDashboardListPrintToTable(t *testing.T) { Data: [][]interface{}{ {firstDashboardId, firstDashboardIdentifier, firstDashboardName, firstDashboardDescription, firstDashboardScope}, {secondDashboardId, secondDashboardIdentifier, secondDashboardName, secondDashboardDescription, secondDashboardScope}}, - MissingTableDataMsg: printer.NotFoundMsg{Types: "dashboards"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: testDashboards}, }, } assert.Equal(t, expectedTableCall, *cli.MockPrinter.TableCalls) @@ -96,7 +100,7 @@ func TestDashboardListPrintToJson(t *testing.T) { di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list", "--output", "json") expectedJsonCall := []map[string]interface{}{ { - "dashboards": orderedArray, + testDashboards: orderedArray, }, } assert.Equal(t, expectedJsonCall, *cli.MockPrinter.PrintJsonCalls) @@ -112,7 +116,7 @@ func TestDashboardListEmptyResults(t *testing.T) { { Header: []string{"Id", "Identifier", "Name", "Description", "Scope"}, Data: [][]interface{}{}, - MissingTableDataMsg: printer.NotFoundMsg{Types: "dashboards"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: testDashboards}, }, } assert.Equal(t, expectedTableCall, *cli.MockPrinter.TableCalls) diff --git a/cmd/health/health_delete_test.go b/cmd/health/health_delete_test.go index 222eaa24..b0b25848 100644 --- a/cmd/health/health_delete_test.go +++ b/cmd/health/health_delete_test.go @@ -9,6 +9,10 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + testHealthStreamURN = "urn:health:self_monitoring:self_monitoring_scraper" +) + func setupHealthDeleteCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { cli := di.NewMockDeps(t) cmd := HealthDeleteCommand(&cli.Deps) @@ -19,7 +23,7 @@ func setupHealthDeleteCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { func TestHealthDeletePrintToTable(t *testing.T) { cli, cmd := setupHealthDeleteCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete", "--urn", "urn:health:self_monitoring:self_monitoring_scraper") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete", "--urn", testHealthStreamURN) assert.Equal(t, []string{"Stream deleted: urn:health:self_monitoring:self_monitoring_scraper"}, *cli.MockPrinter.SuccessCalls) assert.True(t, cli.MockPrinter.HasNonJsonCalls) @@ -27,10 +31,10 @@ func TestHealthDeletePrintToTable(t *testing.T) { func TestHealthDeletePrintToJson(t *testing.T) { cli, cmd := setupHealthDeleteCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete", "--urn", "urn:health:self_monitoring:self_monitoring_scraper", "-o", "json") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete", "--urn", testHealthStreamURN, "-o", "json") assert.Equal(t, []map[string]interface{}{{ - "deleted-stream-urn": "urn:health:self_monitoring:self_monitoring_scraper", + "deleted-stream-urn": testHealthStreamURN, }}, *cli.MockPrinter.PrintJsonCalls, ) diff --git a/cmd/health/health_list_test.go b/cmd/health/health_list_test.go index bf3c5008..1e756037 100644 --- a/cmd/health/health_list_test.go +++ b/cmd/health/health_list_test.go @@ -10,19 +10,24 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + testRepeatSnapshots = "REPEAT_SNAPSHOTS" + testServerName = "SUSE Observability Server" +) + func setupHealthListCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { cli := di.NewMockDeps(t) cmd := HealthListCommand(&cli.Deps) cli.MockClient.ApiMocks.HealthSynchronizationApi.GetHealthSynchronizationStreamsOverviewResponse.Result = stackstate_api.StreamList{ Items: []stackstate_api.StreamListItem{{ - Urn: "urn:health:self_monitoring:self_monitoring_scraper", - ConsistencyModel: "REPEAT_SNAPSHOTS", + Urn: testHealthStreamURN, + ConsistencyModel: testRepeatSnapshots, SubStreams: 1, }}, } cli.MockClient.ApiMocks.HealthSynchronizationApi.GetHealthSynchronizationSubStreamOverviewResponse.Result = stackstate_api.SubStreamList{ SubStreams: []stackstate_api.SubStreamListItem{{ - SubStreamId: "SUSE Observability Server", + SubStreamId: testServerName, CheckStateCount: 36, }}, } @@ -36,7 +41,7 @@ func TestHealthListPrintToTable(t *testing.T) { expectedTableCall := []printer.TableData{ { Header: []string{"Stream urn", "Stream consistency model", "Sub stream count"}, - Data: [][]interface{}{{"urn:health:self_monitoring:self_monitoring_scraper", "REPEAT_SNAPSHOTS", int32(1)}}, + Data: [][]interface{}{{testHealthStreamURN, testRepeatSnapshots, int32(1)}}, MissingTableDataMsg: printer.NotFoundMsg{Types: "health stream"}, }, } @@ -50,8 +55,8 @@ func TestHealthListPrintToJson(t *testing.T) { assert.Equal(t, []map[string]interface{}{{ "streams": []map[string]interface{}{{ - "stream_urn": "urn:health:self_monitoring:self_monitoring_scraper", - "stream_consistency_model": "REPEAT_SNAPSHOTS", + "stream_urn": testHealthStreamURN, + "stream_consistency_model": testRepeatSnapshots, "sub_stream_count": int32(1), }}, }}, @@ -66,7 +71,7 @@ func TestHealthListUrnPrintToTable(t *testing.T) { expectedTableCall := []printer.TableData{ { Header: []string{"Sub stream id", "Check state count"}, - Data: [][]interface{}{{"SUSE Observability Server", int32(36)}}, + Data: [][]interface{}{{testServerName, int32(36)}}, MissingTableDataMsg: printer.NotFoundMsg{Types: "health sub-stream"}, }, } @@ -80,7 +85,7 @@ func TestHealthListUrnPrintToJson(t *testing.T) { assert.Equal(t, []map[string]interface{}{{ "sub-stream": []map[string]interface{}{{ - "sub_stream_id": "SUSE Observability Server", + "sub_stream_id": testServerName, "check_state_count": int32(36), }}, }}, diff --git a/cmd/health/health_status.go b/cmd/health/health_status.go index 7fe283ee..093a6508 100644 --- a/cmd/health/health_status.go +++ b/cmd/health/health_status.go @@ -11,6 +11,11 @@ import ( "github.com/stackvista/stackstate-cli/internal/printer" ) +const ( + metricsKey = "metrics" + errorsKey = "errors" +) + type StatusArgs struct { Urn string SubStream string @@ -105,8 +110,8 @@ func RunStreamStatus(cli *di.Deps, api *stackstate_api.APIClient, args *StatusAr if cli.IsJson() { json := map[string]interface{}{ "consistency-model": status.ConsistencyModel, - "metrics": streamMetricsToJson(status.AggregateMetrics), - "errors": streamErrorsToJson(status.GlobalErrors), + metricsKey: streamMetricsToJson(status.AggregateMetrics), + errorsKey: streamErrorsToJson(status.GlobalErrors), } if status.HasMainStreamStatus() { json["main-stream"] = subStreamStatusToJson(*status.MainStreamStatus) @@ -148,7 +153,7 @@ func streamMetricsToTable(metrics stackstate_api.HealthStreamMetrics) printer.Ta printer.MetricBucketToRow("updates per seconds", metrics.UpdatesPerSecond), printer.MetricBucketToRow("deletes per seconds", metrics.DeletesPerSecond), }, - MissingTableDataMsg: printer.NotFoundMsg{Types: "metrics"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: metricsKey}, } } @@ -174,7 +179,7 @@ func streamErrorsToTable(errors []stackstate_api.HealthStreamError) printer.Tabl return printer.TableData{ Header: []string{"Message", "Count"}, Data: data, - MissingTableDataMsg: printer.NotFoundMsg{Types: "errors"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: errorsKey}, } } @@ -233,7 +238,7 @@ func streamConsistencyStateToTable(state stackstate_api.HealthSubStreamConsisten Data: [][]interface{}{ {repeatInterval, expiryInterval, snapshotRepeatInterval, snapshotExpiryInterval, checkpointOffset, checkpointBatchIndex}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: "errors"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: errorsKey}, } } @@ -251,8 +256,8 @@ func subStreamStatusToJson(status stackstate_api.HealthSubStreamStatus) map[stri return map[string]interface{}{ "check-state-count": status.CheckStateCount, "consistency-state": streamConsistencyStateToJson(status.SubStreamState), - "metrics": streamMetricsToJson(status.Metrics), - "errors": streamErrorsToJson(status.Errors), + metricsKey: streamMetricsToJson(status.Metrics), + errorsKey: streamErrorsToJson(status.Errors), } } diff --git a/cmd/health/health_status_test.go b/cmd/health/health_status_test.go index d8a6a8a9..cdbcfa94 100644 --- a/cmd/health/health_status_test.go +++ b/cmd/health/health_status_test.go @@ -10,6 +10,16 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + testUnknownHealthState = ":shrug:" + testHealthStreamError = "health stream error" + testName = "name" + testLastTenSeconds = "now-10" + testFirstMetricRange = "10-20" + testSecondMetricRange = "20-30" + testMetricLatency = "2000 ms" +) + var ( recoveryMessage = "status recovery message" @@ -30,62 +40,62 @@ var ( } SomeErrors = []stackstate_api.HealthStreamError{ { - Error: ":shrug:", + Error: testUnknownHealthState, }, { - Error: "health stream error", + Error: testHealthStreamError, }, } ExpectedErrorsJson = []map[string]interface{}{ { "count": int32(0), - "message": ":shrug:", + "message": testUnknownHealthState, }, { "count": int32(0), - "message": "health stream error", + "message": testHealthStreamError, }, } ExpectedErrorsTable = printer.TableData{ Header: []string{"Message", "Count"}, Data: [][]interface{}{ - {":shrug:", int32(0)}, - {"health stream error", int32(0)}, + {testUnknownHealthState, int32(0)}, + {testHealthStreamError, int32(0)}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: "errors"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: errorsKey}, } ExpectedMetricsJson = []map[string]interface{}{ { - "name": "latency seconds", - "now-10": float64(23.5), - "10-20": float64(23.5), - "20-30": float64(23.5), + testName: "latency seconds", + testLastTenSeconds: float64(23.5), + testFirstMetricRange: float64(23.5), + testSecondMetricRange: float64(23.5), }, { - "name": "messages per seconds", - "now-10": float64(23.5), - "10-20": float64(23.5), - "20-30": "-", + testName: "messages per seconds", + testLastTenSeconds: float64(23.5), + testFirstMetricRange: float64(23.5), + testSecondMetricRange: "-", }, { - "name": "creates per seconds", - "now-10": float64(23.5), - "10-20": "-", - "20-30": "-", + testName: "creates per seconds", + testLastTenSeconds: float64(23.5), + testFirstMetricRange: "-", + testSecondMetricRange: "-", }, { - "name": "updates per seconds", - "now-10": "-", - "10-20": "-", - "20-30": "-", + testName: "updates per seconds", + testLastTenSeconds: "-", + testFirstMetricRange: "-", + testSecondMetricRange: "-", }, { - "name": "deletes per seconds", - "now-10": "-", - "10-20": "-", - "20-30": "-", + testName: "deletes per seconds", + testLastTenSeconds: "-", + testFirstMetricRange: "-", + testSecondMetricRange: "-", }, } ExpectedMetricsTable = printer.TableData{ @@ -97,7 +107,7 @@ var ( {"updates per seconds", "-", "-", "-"}, {"deletes per seconds", "-", "-", "-"}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: "metrics"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: metricsKey}, } ) @@ -185,9 +195,9 @@ func TestHealthStatusWithSubStreamPrintToText(t *testing.T) { { Header: []string{"Repeat Interval", "Expiry Interval", "Snapshot Repeat Interval", "Snapshot Expiry Interval", "Checkpoint Offset", "Checkpoint Batch Index"}, Data: [][]interface{}{ - {"2000 ms", "2000 ms", "-", "-", "-", "-"}, + {testMetricLatency, testMetricLatency, "-", "-", "-", "-"}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: "errors"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: errorsKey}, }, ExpectedMetricsTable, ExpectedErrorsTable, @@ -206,8 +216,8 @@ func TestHealthStatusWithSubStreamPrintToJson(t *testing.T) { "expiry-interval": int32(2000), "repeat-interval": int32(2000), }, - "errors": ExpectedErrorsJson, - "metrics": ExpectedMetricsJson, + errorsKey: ExpectedErrorsJson, + metricsKey: ExpectedMetricsJson, }, }, *cli.MockPrinter.PrintJsonCalls) } @@ -232,9 +242,9 @@ func TestHealthStatusStreamPrintToText(t *testing.T) { { Header: []string{"Repeat Interval", "Expiry Interval", "Snapshot Repeat Interval", "Snapshot Expiry Interval", "Checkpoint Offset", "Checkpoint Batch Index"}, Data: [][]interface{}{ - {"2000 ms", "2000 ms", "-", "-", "-", "-"}, + {testMetricLatency, testMetricLatency, "-", "-", "-", "-"}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: "errors"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: errorsKey}, }, ExpectedMetricsTable, ExpectedErrorsTable, @@ -255,11 +265,11 @@ func TestHealthStatusStreamPrintToJson(t *testing.T) { "expiry-interval": int32(2000), "repeat-interval": int32(2000), }, - "errors": ExpectedErrorsJson, - "metrics": ExpectedMetricsJson, + errorsKey: ExpectedErrorsJson, + metricsKey: ExpectedMetricsJson, }, - "errors": ExpectedErrorsJson, - "metrics": ExpectedMetricsJson, + errorsKey: ExpectedErrorsJson, + metricsKey: ExpectedMetricsJson, }, }, *cli.MockPrinter.PrintJsonCalls) } diff --git a/cmd/license/common.go b/cmd/license/common.go index b4f19184..99535dd2 100644 --- a/cmd/license/common.go +++ b/cmd/license/common.go @@ -5,18 +5,22 @@ import ( "github.com/stackvista/stackstate-cli/internal/printer" ) +const ( + stateKey = "state" +) + func subscriptionAsTable(subscription *stackstate_api.SubscriptionState) printer.TableData { var header []string data := make([][]interface{}, 0) switch l := subscription.GetActualInstance().(type) { case *stackstate_api.ExpiredSubscription: - header = []string{"state", "tenant", "expiration", "plan"} + header = []string{stateKey, "tenant", "expiration", "plan"} data = append(data, []interface{}{"expired", l.Subscription.Tenant, expiration(l.Subscription.ExpiryTimestampMs), l.Subscription.Plan}) case *stackstate_api.LicensedSubscription: - header = []string{"state", "tenant", "expiration", "plan"} + header = []string{stateKey, "tenant", "expiration", "plan"} data = append(data, []interface{}{"valid", l.Subscription.Tenant, expiration(l.Subscription.ExpiryTimestampMs), l.Subscription.Plan}) case *stackstate_api.UnlicensedSubscription: - header = []string{"state", "reason"} + header = []string{stateKey, "reason"} data = append(data, []interface{}{"unlicensed", l.Reason}) } diff --git a/cmd/monitor/monitor_apply.go b/cmd/monitor/monitor_apply.go index 8e1ea99c..cd72ec52 100644 --- a/cmd/monitor/monitor_apply.go +++ b/cmd/monitor/monitor_apply.go @@ -11,6 +11,16 @@ import ( "github.com/stackvista/stackstate-cli/internal/printer" ) +const ( + statusColumn = "Status" +) + +const ( + nameKey = "Name" + nodesKey = "nodes" + identifierKey = "Identifier" +) + type ApplyArgs struct { File string } @@ -45,7 +55,7 @@ func RunMonitorApplyCommand(args *ApplyArgs) di.CmdWithApiFn { if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "nodes": nodes, + nodesKey: nodes, }) } else { if len(nodes) == 0 { @@ -61,7 +71,7 @@ func RunMonitorApplyCommand(args *ApplyArgs) di.CmdWithApiFn { cli.Printer.Success(fmt.Sprintf("Applied %d monitor(s).", len(nodes))) if len(nodes) > 0 { cli.Printer.Table(printer.TableData{ - Header: []string{"Type", "Id", "Status", "Identifier", "Name"}, + Header: []string{"Type", "Id", statusColumn, identifierKey, nameKey}, Data: tableData, }) } diff --git a/cmd/monitor/monitor_clone.go b/cmd/monitor/monitor_clone.go index cfbc71e3..bec35d07 100644 --- a/cmd/monitor/monitor_clone.go +++ b/cmd/monitor/monitor_clone.go @@ -10,6 +10,10 @@ import ( "github.com/stackvista/stackstate-cli/internal/di" ) +const ( + monitorKey = "monitor" +) + type CloneArgs struct { IdArgs NewName string @@ -53,7 +57,7 @@ func RunMonitorCloneCommand(args *CloneArgs) di.CmdWithApiFn { if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "monitor": clonedMonitor, + monitorKey: clonedMonitor, }) } else { cli.Printer.Success(fmt.Sprintf("Monitor %d has been created", clonedMonitor.GetId())) diff --git a/cmd/monitor/monitor_disable.go b/cmd/monitor/monitor_disable.go index d0c762ab..ba439974 100644 --- a/cmd/monitor/monitor_disable.go +++ b/cmd/monitor/monitor_disable.go @@ -48,7 +48,7 @@ func RunMonitorDisableCommand(args *IdArgs, status *sts.MonitorStatusValue) di.C if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "monitor": monitorPatchResult, + monitorKey: monitorPatchResult, }) } else { cli.Printer.Success(fmt.Sprintf("Monitor %s has been disabled", identifier)) diff --git a/cmd/monitor/monitor_disable_test.go b/cmd/monitor/monitor_disable_test.go index b9604fda..55175e7c 100644 --- a/cmd/monitor/monitor_disable_test.go +++ b/cmd/monitor/monitor_disable_test.go @@ -27,7 +27,7 @@ func TestMonitorDisableByIdJson(t *testing.T) { checkMonitorPatchStatusCall(t, cli.MockClient.ApiMocks.MonitorApi.PatchMonitorCalls, sts.MONITORSTATUSVALUE_DISABLED.Ptr()) expectedJsonCalls := []map[string]interface{}{{ - "monitor": &monitor, + monitorKey: &monitor, }} assert.Equal(t, expectedJsonCalls, *cli.MockPrinter.PrintJsonCalls) assert.False(t, cli.MockPrinter.HasNonJsonCalls) @@ -53,7 +53,7 @@ func TestMonitorDisableByIdentifierJson(t *testing.T) { checkMonitorPatchStatusCall(t, cli.MockClient.ApiMocks.MonitorApi.PatchMonitorCalls, sts.MONITORSTATUSVALUE_DISABLED.Ptr()) checkMonitorPatchStatusCall(t, cli.MockClient.ApiMocks.MonitorApi.PatchMonitorCalls, sts.MONITORSTATUSVALUE_DISABLED.Ptr()) expectedJsonCalls := []map[string]interface{}{{ - "monitor": &monitor, + monitorKey: &monitor, }} assert.Equal(t, expectedJsonCalls, *cli.MockPrinter.PrintJsonCalls) assert.False(t, cli.MockPrinter.HasNonJsonCalls) diff --git a/cmd/monitor/monitor_edit.go b/cmd/monitor/monitor_edit.go index 722faf9a..b96f6127 100644 --- a/cmd/monitor/monitor_edit.go +++ b/cmd/monitor/monitor_edit.go @@ -97,7 +97,7 @@ func RunMonitorEditCommand(args *EditArgs) di.CmdWithApiFn { if strings.Compare(orig, string(c)) == 0 { if cli.IsJson() { - cli.Printer.PrintJson(map[string]interface{}{"nodes": []string{}, "message": "No changes made"}) + cli.Printer.PrintJson(map[string]interface{}{nodesKey: []string{}, "message": "No changes made"}) } else { cli.Printer.PrintWarn("No changes made") } @@ -119,7 +119,7 @@ func RunMonitorEditCommand(args *EditArgs) di.CmdWithApiFn { if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "nodes": nodes, + nodesKey: nodes, }) } else { tableData := make([][]interface{}, 0) @@ -130,7 +130,7 @@ func RunMonitorEditCommand(args *EditArgs) di.CmdWithApiFn { cli.Printer.Success(fmt.Sprintf("Updated %d monitor(s).", len(nodes))) if len(nodes) > 0 { cli.Printer.Table(printer.TableData{ - Header: []string{"Type", "Id", "Status", "Identifier", "Name"}, + Header: []string{"Type", "Id", statusColumn, identifierKey, nameKey}, Data: tableData, }) } diff --git a/cmd/monitor/monitor_enable.go b/cmd/monitor/monitor_enable.go index 69db2cda..f4dcabd8 100644 --- a/cmd/monitor/monitor_enable.go +++ b/cmd/monitor/monitor_enable.go @@ -47,7 +47,7 @@ func RunMonitorEnableCommand(args *IdArgs) di.CmdWithApiFn { if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "monitor": monitorPatchResult, + monitorKey: monitorPatchResult, }) } else { cli.Printer.Success(fmt.Sprintf("Monitor %s has been enabled", identifier)) diff --git a/cmd/monitor/monitor_enable_test.go b/cmd/monitor/monitor_enable_test.go index 3bc19fc6..95f57b76 100644 --- a/cmd/monitor/monitor_enable_test.go +++ b/cmd/monitor/monitor_enable_test.go @@ -27,7 +27,7 @@ func TestMonitorEnableByIdJson(t *testing.T) { checkMonitorPatchStatusCall(t, cli.MockClient.ApiMocks.MonitorApi.PatchMonitorCalls, sts.MONITORSTATUSVALUE_ENABLED.Ptr()) expectedJsonCalls := []map[string]interface{}{{ - "monitor": &monitor, + monitorKey: &monitor, }} assert.Equal(t, expectedJsonCalls, *cli.MockPrinter.PrintJsonCalls) assert.False(t, cli.MockPrinter.HasNonJsonCalls) @@ -52,7 +52,7 @@ func TestMonitorEnableByIdentifierJson(t *testing.T) { checkMonitorPatchStatusCall(t, cli.MockClient.ApiMocks.MonitorApi.PatchMonitorCalls, sts.MONITORSTATUSVALUE_ENABLED.Ptr()) expectedJsonCalls := []map[string]interface{}{{ - "monitor": &monitor, + monitorKey: &monitor, }} assert.Equal(t, expectedJsonCalls, *cli.MockPrinter.PrintJsonCalls) assert.False(t, cli.MockPrinter.HasNonJsonCalls) diff --git a/cmd/monitor/monitor_list.go b/cmd/monitor/monitor_list.go index 1ee374ed..98e6384c 100644 --- a/cmd/monitor/monitor_list.go +++ b/cmd/monitor/monitor_list.go @@ -50,7 +50,7 @@ func RunMonitorListCommand( tableData = append(tableData, []interface{}{monitor.Id, monitor.Status, *monitor.Identifier, monitor.Name, monitor.FunctionId, monitor.Tags}) } cli.Printer.Table(printer.TableData{ - Header: []string{"Id", "Status", "Identifier", "Name", "Function Id", "Tags"}, + Header: []string{"Id", statusColumn, identifierKey, nameKey, "Function Id", "Tags"}, Data: tableData, MissingTableDataMsg: printer.NotFoundMsg{Types: "monitors"}, }) diff --git a/cmd/monitor/monitor_status_test.go b/cmd/monitor/monitor_status_test.go index eaedcc9b..9b851e33 100644 --- a/cmd/monitor/monitor_status_test.go +++ b/cmd/monitor/monitor_status_test.go @@ -10,6 +10,12 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + testError = "Error" + testMonitorErrorStatus = "Monitor Status: ERROR" + testMonitorTimeWindow = "value between 0 and 0 seconds ago" +) + var ( count = int32(3) lastRunTimestamp = int64(1663079675007) @@ -28,7 +34,7 @@ var ( healthStateCount int32 = 10 unmappedHealthStateCount int32 = 1 monitorError = sts.MonitorError{ - Error: "Error", + Error: testError, Count: 11, } metrics = sts.MonitorMetrics{ @@ -108,16 +114,16 @@ func TestMonitorStatusPrintsToTable(t *testing.T) { di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "-i", "211684343791306") - expectedPrintlnCalls := []string{"", "Monitor Health State count: 10", "Monitor Status: ERROR", "", "Monitor Stream errors:", "", "Monitor Stream metrics:", "", + expectedPrintlnCalls := []string{"", "Monitor Health State count: 10", testMonitorErrorStatus, "", "Monitor Stream errors:", "", "Monitor Stream metrics:", "", "Monitor health states with identifier matching exactly 1 topology element: 0"} expectedTableCall := []printer.TableData{ { Header: []string{"message", "occurrence count"}, - Data: [][]interface{}{{"Error", int32(11)}}, + Data: [][]interface{}{{testError, int32(11)}}, }, { - Header: []string{"metric", "value between now and 0 seconds ago", "value between 0 and 0 seconds ago", - "value between 0 and 0 seconds ago"}, + Header: []string{"metric", "value between now and 0 seconds ago", testMonitorTimeWindow, + testMonitorTimeWindow}, Data: [][]interface{}{{"latency (Seconds)"}, {"messages processed (per second)"}, {"monitor health states created (per second)"}, {"monitor health states updated (per second)"}, {"monitor health states deleted (per second)"}}, @@ -134,7 +140,7 @@ func TestMonitorStatusWithHealthStatesCountsPrintsToTable(t *testing.T) { di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "-i", "211684343791306") - expectedPrintlnCalls := []string{"", "Monitor Health State count: 10", "Monitor Status: ERROR", "Monitor last run: 2022-09-13 14:34:35.007 +0000 UTC", + expectedPrintlnCalls := []string{"", "Monitor Health State count: 10", testMonitorErrorStatus, "Monitor last run: 2022-09-13 14:34:35.007 +0000 UTC", "", "Monitor Stream errors:", "", "Monitor health states mapped to topology:", "", "Monitor Stream metrics:", "", "Monitor health states with identifier matching exactly 1 topology element: 0", "", "Monitor health states with identifier which has no matching topology element (1):"} @@ -142,15 +148,15 @@ func TestMonitorStatusWithHealthStatesCountsPrintsToTable(t *testing.T) { expectedTableCall := []printer.TableData{ { Header: []string{"message", "occurrence count"}, - Data: [][]interface{}{{"Error", int32(11)}}, + Data: [][]interface{}{{testError, int32(11)}}, }, { Header: []string{"HealthState", "count"}, Data: [][]interface{}{{"CLEAR", count}, {"DEVIATING", count}, {"CRITICAL", count}, {"UNKNOWN", count}}, }, { - Header: []string{"metric", "value between now and 0 seconds ago", "value between 0 and 0 seconds ago", - "value between 0 and 0 seconds ago"}, + Header: []string{"metric", "value between now and 0 seconds ago", testMonitorTimeWindow, + testMonitorTimeWindow}, Data: [][]interface{}{{"latency (Seconds)"}, {"messages processed (per second)"}, {"monitor health states created (per second)"}, {"monitor health states updated (per second)"}, {"monitor health states deleted (per second)"}}, @@ -171,7 +177,7 @@ func TestMonitorStatusForDisabled(t *testing.T) { di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "-i", "211684343791306") - expectedPrintlnCalls := []string{"", "Monitor Health State count: -", "Monitor Status: ERROR"} + expectedPrintlnCalls := []string{"", "Monitor Health State count: -", testMonitorErrorStatus} expectedTableCall := []printer.TableData{} assert.Equal(t, expectedPrintlnCalls, *cli.MockPrinter.PrintLnCalls) diff --git a/cmd/otelcomponentmapping/otelcomponentmapping_apply_test.go b/cmd/otelcomponentmapping/otelcomponentmapping_apply_test.go index 923df0a4..b26d5902 100644 --- a/cmd/otelcomponentmapping/otelcomponentmapping_apply_test.go +++ b/cmd/otelcomponentmapping/otelcomponentmapping_apply_test.go @@ -13,6 +13,11 @@ import ( "gopkg.in/yaml.v2" ) +const ( + testMappingName = "my-mapping" + testMappingURN = "urn:otel:component:foo" +) + func createTempYamlFile(t *testing.T, content string) string { t.Helper() tmpfile, err := os.CreateTemp(os.TempDir(), "test_componentmapping_*.yaml") @@ -37,8 +42,8 @@ func TestOtelComponentMappingApply_SuccessYaml(t *testing.T) { cli := di.NewMockDeps(t) cmd := otelcomponentmapping.OtelComponentMappingApplyCommand(&cli.Deps) mapping := stackstate_api.OtelComponentMapping{ - Name: "my-mapping", - Identifier: "urn:otel:component:foo", + Name: testMappingName, + Identifier: testMappingURN, } yamlContent, err := yaml.Marshal(mapping) assert.NoError(t, err) @@ -60,8 +65,8 @@ func TestOtelComponentMappingApply_SuccessJson(t *testing.T) { cli := di.NewMockDeps(t) cmd := otelcomponentmapping.OtelComponentMappingApplyCommand(&cli.Deps) mapping := stackstate_api.OtelComponentMapping{ - Name: "my-mapping", - Identifier: "urn:otel:component:foo", + Name: testMappingName, + Identifier: testMappingURN, } yamlContent, err := yaml.Marshal(mapping) assert.NoError(t, err) @@ -125,8 +130,8 @@ func TestOtelComponentMappingApply_ApiError(t *testing.T) { cli := di.NewMockDeps(t) cmd := otelcomponentmapping.OtelComponentMappingApplyCommand(&cli.Deps) mapping := stackstate_api.OtelComponentMapping{ - Name: "my-mapping", - Identifier: "urn:otel:component:foo", + Name: testMappingName, + Identifier: testMappingURN, } yamlContent, err := yaml.Marshal(mapping) assert.NoError(t, err) diff --git a/cmd/otelrelationmapping/otelrelationmapping_apply_test.go b/cmd/otelrelationmapping/otelrelationmapping_apply_test.go index 80e5481f..b4cd7afd 100644 --- a/cmd/otelrelationmapping/otelrelationmapping_apply_test.go +++ b/cmd/otelrelationmapping/otelrelationmapping_apply_test.go @@ -13,6 +13,11 @@ import ( "gopkg.in/yaml.v2" ) +const ( + testMappingName = "my-relation-mapping" + testMappingURN = "urn:otel:relation:foo" +) + func createTempYamlFile(t *testing.T, content string) string { t.Helper() tmpfile, err := os.CreateTemp(os.TempDir(), "test_relationmapping_*.yaml") @@ -37,8 +42,8 @@ func TestOtelRelationMappingApply_SuccessYaml(t *testing.T) { cli := di.NewMockDeps(t) cmd := otelrelationmapping.OtelRelationMappingApplyCommand(&cli.Deps) mapping := stackstate_api.UpsertOtelRelationMappingsRequest{ - Name: "my-relation-mapping", - Identifier: "urn:otel:relation:foo", + Name: testMappingName, + Identifier: testMappingURN, } yamlContent, err := yaml.Marshal(mapping) assert.NoError(t, err) @@ -60,8 +65,8 @@ func TestOtelRelationMappingApply_SuccessJson(t *testing.T) { cli := di.NewMockDeps(t) cmd := otelrelationmapping.OtelRelationMappingApplyCommand(&cli.Deps) mapping := stackstate_api.UpsertOtelRelationMappingsRequest{ - Name: "my-relation-mapping", - Identifier: "urn:otel:relation:foo", + Name: testMappingName, + Identifier: testMappingURN, } yamlContent, err := yaml.Marshal(mapping) assert.NoError(t, err) @@ -112,8 +117,8 @@ func TestOtelRelationMappingApply_ApiError(t *testing.T) { cli := di.NewMockDeps(t) cmd := otelrelationmapping.OtelRelationMappingApplyCommand(&cli.Deps) mapping := stackstate_api.UpsertOtelRelationMappingsRequest{ - Name: "my-relation-mapping", - Identifier: "urn:otel:relation:foo", + Name: testMappingName, + Identifier: testMappingURN, } yamlContent, err := yaml.Marshal(mapping) assert.NoError(t, err) diff --git a/cmd/otelrelationmapping/otelrelationmapping_edit_test.go b/cmd/otelrelationmapping/otelrelationmapping_edit_test.go index 8be9fdaf..101ca921 100644 --- a/cmd/otelrelationmapping/otelrelationmapping_edit_test.go +++ b/cmd/otelrelationmapping/otelrelationmapping_edit_test.go @@ -13,6 +13,10 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + testOrig = "orig" +) + type mockEditorStub struct { content []byte err error @@ -31,7 +35,7 @@ func TestOtelRelationMappingEdit_SuccessYAML(t *testing.T) { mockIdentifier := "urn:otel:relation:edit-success" orig := stackstate_api.OtelRelationMapping{ Identifier: mockIdentifier, - Name: "orig", + Name: testOrig, } cli.MockClient.ApiMocks.OtelMappingApi.GetOtelRelationMappingResponse.Result = orig // YAML of edited mapping @@ -115,7 +119,7 @@ func TestOtelRelationMappingEdit_EditorError(t *testing.T) { cli := di.NewMockDeps(t) cmd := otelrelationmapping.OtelRelationMappingEditCommand(&cli.Deps) mockIdentifier := "urn:otel:relation:editorfail" - orig := stackstate_api.OtelRelationMapping{Identifier: mockIdentifier, Name: "orig"} + orig := stackstate_api.OtelRelationMapping{Identifier: mockIdentifier, Name: testOrig} cli.MockClient.ApiMocks.OtelMappingApi.GetOtelRelationMappingResponse.Result = orig cli.Editor = &mockEditorStub{err: errors.New("editor failure")} @@ -132,7 +136,7 @@ func TestOtelRelationMappingEdit_InvalidYAML(t *testing.T) { cli := di.NewMockDeps(t) cmd := otelrelationmapping.OtelRelationMappingEditCommand(&cli.Deps) mockIdentifier := "urn:otel:relation:bad-yaml" - orig := stackstate_api.OtelRelationMapping{Identifier: mockIdentifier, Name: "orig"} + orig := stackstate_api.OtelRelationMapping{Identifier: mockIdentifier, Name: testOrig} cli.MockClient.ApiMocks.OtelMappingApi.GetOtelRelationMappingResponse.Result = orig cli.Editor = &mockEditorStub{content: []byte("not: valid:: yaml::")} diff --git a/cmd/rbac/rbac_describe_permissions.go b/cmd/rbac/rbac_describe_permissions.go index 8631f1f3..a8dd3b57 100644 --- a/cmd/rbac/rbac_describe_permissions.go +++ b/cmd/rbac/rbac_describe_permissions.go @@ -13,6 +13,10 @@ import ( "github.com/stackvista/stackstate-cli/pkg/pflags" ) +const ( + permissionsKey = "permissions" +) + type DescribePermissionsArgs struct { Subject string Permission string @@ -69,14 +73,14 @@ func RunDescribePermissionsCommand(args *DescribePermissionsArgs) di.CmdWithApiF if cli.IsJson() { if sourceStrings != nil { cli.Printer.PrintJson(map[string]interface{}{ - "subject": description.SubjectHandle, - "permissions": description.Permissions, - "sources": sourceStrings, + Subject: description.SubjectHandle, + permissionsKey: description.Permissions, + "sources": sourceStrings, }) } else { cli.Printer.PrintJson(map[string]interface{}{ - "subject": description.SubjectHandle, - "permissions": description.Permissions, + Subject: description.SubjectHandle, + permissionsKey: description.Permissions, }) } } else { diff --git a/cmd/rbac/rbac_describe_permissions_test.go b/cmd/rbac/rbac_describe_permissions_test.go index ef19706f..18009a2b 100644 --- a/cmd/rbac/rbac_describe_permissions_test.go +++ b/cmd/rbac/rbac_describe_permissions_test.go @@ -9,14 +9,20 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + testFoo = "foo" + testBar = "bar" + testBaz = "baz" +) + var ( - Set1 = []string{"foo", "bar", "baz"} + Set1 = []string{testFoo, testBar, testBaz} Resource1 = "some-view" Permissions1 = map[string][]string{ Resource1: Set1, } - Set2 = []string{"foo", "fai", "fum"} + Set2 = []string{testFoo, "fai", "fum"} Resource2 = "system" Permissions2 = map[string][]string{ Resource2: Set2, @@ -31,23 +37,23 @@ var ( ExpectedTable = printer.TableData{ Header: []string{"permission", "resource"}, Data: [][]interface{}{ - {"bar", Resource1}, - {"baz", Resource1}, - {"foo", Resource1}, + {testBar, Resource1}, + {testBaz, Resource1}, + {testFoo, Resource1}, {"fai", Resource2}, - {"foo", Resource2}, + {testFoo, Resource2}, {"fum", Resource2}, }, MissingTableDataMsg: printer.NotFoundMsg{Types: "matching permissions"}, } ExpectedJson = map[string]interface{}{ - "subject": SubjectHandle, - "permissions": AllPermissions, + "subject": SubjectHandle, + permissionsKey: AllPermissions, } ExpectedSourcesJson = map[string]interface{}{ - "subject": SubjectHandle, - "permissions": AllPermissions, - "sources": []string{"Static"}, + "subject": SubjectHandle, + permissionsKey: AllPermissions, + "sources": []string{"Static"}, } ) @@ -108,12 +114,12 @@ func TestPermissionsDescribeFilterPermission(t *testing.T) { cli.MockClient.ApiMocks.PermissionsApi.DescribePermissionsResponse.Result = *Description - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--subject", SubjectHandle, "--permission", "foo") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--subject", SubjectHandle, "--permission", testFoo) calls := *cli.MockClient.ApiMocks.PermissionsApi.DescribePermissionsCalls assert.Len(t, calls, 1) assert.Equal(t, SubjectHandle, calls[0].Psubject) - assert.Equal(t, "foo", *calls[0].Ppermission) + assert.Equal(t, testFoo, *calls[0].Ppermission) assert.Nil(t, calls[0].Presource) } @@ -139,12 +145,12 @@ func TestPermissionsDescribeFilterResourceAndPermission(t *testing.T) { cli.MockClient.ApiMocks.PermissionsApi.DescribePermissionsResponse.Result = *Description - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--subject", SubjectHandle, "--resource", Resource1, "--permission", "foo") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--subject", SubjectHandle, "--resource", Resource1, "--permission", testFoo) calls := *cli.MockClient.ApiMocks.PermissionsApi.DescribePermissionsCalls assert.Len(t, calls, 1) assert.Equal(t, SubjectHandle, calls[0].Psubject) - assert.Equal(t, "foo", *calls[0].Ppermission) + assert.Equal(t, testFoo, *calls[0].Ppermission) assert.Equal(t, Resource1, *calls[0].Presource) } diff --git a/cmd/rbac/rbac_describe_subjects_test.go b/cmd/rbac/rbac_describe_subjects_test.go index 3b7cb82b..67f4b340 100644 --- a/cmd/rbac/rbac_describe_subjects_test.go +++ b/cmd/rbac/rbac_describe_subjects_test.go @@ -10,6 +10,12 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + testSubject = "Subject" + testSource = "Source" + testSubjects = "subjects" +) + var ( SomeScopeVar = SomeScope SubjectConfig1 = stackstate_api.SubjectConfig{ @@ -47,13 +53,13 @@ func TestDescribeSubjectsTable(t *testing.T) { expected := []printer.TableData{ { - Header: []string{"Subject", "Source"}, + Header: []string{testSubject, testSource}, Data: [][]interface{}{ {SubjectConfig1.Handle, SubjectConfig1.Source}, {SubjectConfig2.Handle, SubjectConfig2.Source}, {SubjectConfig3.Handle, SubjectConfig3.Source}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: "subjects"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: testSubjects}, }, } @@ -79,7 +85,7 @@ func TestDescribeSubjectsJson(t *testing.T) { expectedJson := []map[string]interface{}{ { - "subjects": result, + testSubjects: result, }, } @@ -105,11 +111,11 @@ func TestDescribeSubjectsTableWithFilter(t *testing.T) { expected := []printer.TableData{ { - Header: []string{"Subject", "Source"}, + Header: []string{testSubject, testSource}, Data: [][]interface{}{ {SubjectConfig1.Handle, SubjectConfig1.Source}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: "subjects"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: testSubjects}, }, } @@ -135,7 +141,7 @@ func TestDescribeSubjectsJsonWithFilter(t *testing.T) { expectedJson := []map[string]interface{}{ { - "subjects": []stackstate_api.SubjectConfig{SubjectConfig1}, + testSubjects: []stackstate_api.SubjectConfig{SubjectConfig1}, }, } @@ -161,11 +167,11 @@ func TestDescribeSubjectsTableWithSourceFilter(t *testing.T) { expected := []printer.TableData{ { - Header: []string{"Subject", "Source"}, + Header: []string{testSubject, testSource}, Data: [][]interface{}{ {SubjectConfig1.Handle, SubjectConfig1.Source}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: "subjects"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: testSubjects}, }, } @@ -187,9 +193,9 @@ func TestProduceEmptyWhenNoSubjectFilter(t *testing.T) { expected := []printer.TableData{ { - Header: []string{"Subject", "Source"}, + Header: []string{testSubject, testSource}, Data: [][]interface{}{}, - MissingTableDataMsg: printer.NotFoundMsg{Types: "subjects"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: testSubjects}, }, } diff --git a/cmd/rbac/rbac_grant.go b/cmd/rbac/rbac_grant.go index b0877718..880a4137 100644 --- a/cmd/rbac/rbac_grant.go +++ b/cmd/rbac/rbac_grant.go @@ -62,8 +62,8 @@ func RunGrantPermissionsCommand(args *GrantPermissionsArgs) di.CmdWithApiFn { if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "subject": description.SubjectHandle, - "permissions": description.Permissions, + Subject: description.SubjectHandle, + permissionsKey: description.Permissions, }) } else { cli.Printer.Successf("Granted permission '%s' on '%s' to subject '%s'", args.Permission, args.Resource, args.Subject) diff --git a/cmd/rbac/rbac_list_permissions.go b/cmd/rbac/rbac_list_permissions.go index 7bd88162..722f563e 100644 --- a/cmd/rbac/rbac_list_permissions.go +++ b/cmd/rbac/rbac_list_permissions.go @@ -31,7 +31,7 @@ func RunListPermissionsCommand(cmd *cobra.Command, cli *di.Deps, api *stackstate if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "permissions": permissions.Permissions, + permissionsKey: permissions.Permissions, }) } else { cli.Printer.Successf("Available permissions: %s", strings.Join(permissions.Permissions, ", ")) diff --git a/cmd/rbac/rbac_list_permissions_test.go b/cmd/rbac/rbac_list_permissions_test.go index 4d00ea8b..310eb8c1 100644 --- a/cmd/rbac/rbac_list_permissions_test.go +++ b/cmd/rbac/rbac_list_permissions_test.go @@ -9,9 +9,9 @@ import ( ) var SomePermissions = []string{ - "foo", - "bar", - "baz", + testFoo, + testBar, + testBaz, } func TestPermissionsList(t *testing.T) { @@ -32,7 +32,7 @@ func TestPermissionsList(t *testing.T) { expected := []map[string]interface{}{ { - "permissions": SomePermissions, + permissionsKey: SomePermissions, }, } diff --git a/cmd/rbac/rbac_revoke.go b/cmd/rbac/rbac_revoke.go index c8b135ef..aa5270a1 100644 --- a/cmd/rbac/rbac_revoke.go +++ b/cmd/rbac/rbac_revoke.go @@ -62,8 +62,8 @@ func RunRevokePermissionsCommand(args *RevokePermissionsArgs) di.CmdWithApiFn { if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "subject": description.SubjectHandle, - "permissions": description.Permissions, + Subject: description.SubjectHandle, + permissionsKey: description.Permissions, }) } else { cli.Printer.Successf("Revoked permission '%s' on '%s' from subject '%s'", args.Permission, args.Resource, args.Subject) diff --git a/cmd/script/script_run_test.go b/cmd/script/script_run_test.go index d2e7ce6b..24211242 100644 --- a/cmd/script/script_run_test.go +++ b/cmd/script/script_run_test.go @@ -14,6 +14,11 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + testValue = "value" + testHelloTest = "hello test" +) + func setupScriptExecuteCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { cli := di.NewMockDeps(t) cmd := ScriptRunCommand(&cli.Deps) @@ -23,7 +28,7 @@ func setupScriptExecuteCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { func TestExecuteSuccess(t *testing.T) { cli, cmd := setupScriptExecuteCmd(t) cli.MockClient.ApiMocks.ScriptingApi.ScriptExecuteResponse.Result = sts.ExecuteScriptResponse{ - Result: map[string]interface{}{"value": "hello test"}, + Result: map[string]interface{}{testValue: testHelloTest}, } di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--script", "test script") @@ -34,20 +39,20 @@ func TestExecuteSuccess(t *testing.T) { }, *cli.MockClient.ApiMocks.ScriptingApi.ScriptExecuteCalls, ) - assert.Equal(t, []interface{}{"hello test"}, *cli.MockPrinter.PrintStructCalls) + assert.Equal(t, []interface{}{testHelloTest}, *cli.MockPrinter.PrintStructCalls) } func TestExecuteSuccessJson(t *testing.T) { cli, cmd := setupScriptExecuteCmd(t) cli.MockClient.ApiMocks.ScriptingApi.ScriptExecuteResponse.Result = sts.ExecuteScriptResponse{ - Result: map[string]interface{}{"value": "hello test"}, + Result: map[string]interface{}{testValue: testHelloTest}, } di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--script", "test script", "-o", "json") assert.Equal(t, []map[string]interface{}{{ - "result": map[string]interface{}{"value": "hello test"}, + "result": map[string]interface{}{testValue: testHelloTest}, }}, *cli.MockPrinter.PrintJsonCalls, ) diff --git a/cmd/servicetoken/servicetoken_create_test.go b/cmd/servicetoken/servicetoken_create_test.go index 01093590..091dc597 100644 --- a/cmd/servicetoken/servicetoken_create_test.go +++ b/cmd/servicetoken/servicetoken_create_test.go @@ -8,20 +8,28 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + testTokenName = "test-token" + testTokenValue = "test-token-token" + testRole = "test-role" + testTokenCreatedMessage = "Service token created: \x1b[37mtest-token-token\x1b[0m\n" + testAnotherRole = "another-role" +) + func TestServiceTokenCreate(t *testing.T) { cli := di.NewMockDeps(t) cmd := CreateCommand(&cli.Deps) cli.MockClient.ApiMocks.ServiceTokenApi.CreateNewServiceTokenResponse.Result = stackstate_api.ServiceTokenCreatedResponse{ - Name: "test-token", - Token: "test-token-token", + Name: testTokenName, + Token: testTokenValue, Expiration: int64p(100000000), } - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--name", "test-token", "--roles", "test-role", "--expiration", "2020-05-22") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--name", testTokenName, "--roles", testRole, "--expiration", "2020-05-22") - checkCreateCall(t, cli.MockClient.ApiMocks.ServiceTokenApi.CreateNewServiceTokenCalls, "test-token", []string{"test-role"}, int64p(1590105600000)) - assert.Equal(t, []string{"Service token created: \x1b[37mtest-token-token\x1b[0m\n"}, *cli.MockPrinter.SuccessCalls) + checkCreateCall(t, cli.MockClient.ApiMocks.ServiceTokenApi.CreateNewServiceTokenCalls, testTokenName, []string{testRole}, int64p(1590105600000)) + assert.Equal(t, []string{testTokenCreatedMessage}, *cli.MockPrinter.SuccessCalls) } func TestServiceTokenCreateExpirationOptional(t *testing.T) { @@ -29,15 +37,15 @@ func TestServiceTokenCreateExpirationOptional(t *testing.T) { cmd := CreateCommand(&cli.Deps) cli.MockClient.ApiMocks.ServiceTokenApi.CreateNewServiceTokenResponse.Result = stackstate_api.ServiceTokenCreatedResponse{ - Name: "test-token", - Token: "test-token-token", + Name: testTokenName, + Token: testTokenValue, Expiration: int64p(100000000), } - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--name", "test-token", "--roles", "test-role") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--name", testTokenName, "--roles", testRole) - checkCreateCall(t, cli.MockClient.ApiMocks.ServiceTokenApi.CreateNewServiceTokenCalls, "test-token", []string{"test-role"}, nil) - assert.Equal(t, []string{"Service token created: \x1b[37mtest-token-token\x1b[0m\n"}, *cli.MockPrinter.SuccessCalls) + checkCreateCall(t, cli.MockClient.ApiMocks.ServiceTokenApi.CreateNewServiceTokenCalls, testTokenName, []string{testRole}, nil) + assert.Equal(t, []string{testTokenCreatedMessage}, *cli.MockPrinter.SuccessCalls) } func TestServiceTokenCreateMultipleRoles(t *testing.T) { @@ -45,15 +53,15 @@ func TestServiceTokenCreateMultipleRoles(t *testing.T) { cmd := CreateCommand(&cli.Deps) cli.MockClient.ApiMocks.ServiceTokenApi.CreateNewServiceTokenResponse.Result = stackstate_api.ServiceTokenCreatedResponse{ - Name: "test-token", - Token: "test-token-token", + Name: testTokenName, + Token: testTokenValue, Expiration: int64p(100000000), } - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--name", "test-token", "--roles", "test-role,another-role", "--roles", "third-role") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--name", testTokenName, "--roles", "test-role,another-role", "--roles", "third-role") - checkCreateCall(t, cli.MockClient.ApiMocks.ServiceTokenApi.CreateNewServiceTokenCalls, "test-token", []string{"test-role", "another-role", "third-role"}, nil) - assert.Equal(t, []string{"Service token created: \x1b[37mtest-token-token\x1b[0m\n"}, *cli.MockPrinter.SuccessCalls) + checkCreateCall(t, cli.MockClient.ApiMocks.ServiceTokenApi.CreateNewServiceTokenCalls, testTokenName, []string{testRole, testAnotherRole, "third-role"}, nil) + assert.Equal(t, []string{testTokenCreatedMessage}, *cli.MockPrinter.SuccessCalls) } func TestServiceTokenCreateJSON(t *testing.T) { @@ -61,13 +69,13 @@ func TestServiceTokenCreateJSON(t *testing.T) { cmd := CreateCommand(&cli.Deps) r := &stackstate_api.ServiceTokenCreatedResponse{ - Name: "test-token", - Token: "test-token-token", + Name: testTokenName, + Token: testTokenValue, } cli.MockClient.ApiMocks.ServiceTokenApi.CreateNewServiceTokenResponse.Result = *r - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--name", "test-token", "--roles", "test-role", "-o", "json") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--name", testTokenName, "--roles", testRole, "-o", "json") assert.Equal(t, []map[string]interface{}{{ diff --git a/cmd/servicetoken/servicetoken_list_test.go b/cmd/servicetoken/servicetoken_list_test.go index c995f630..b2ff61f8 100644 --- a/cmd/servicetoken/servicetoken_list_test.go +++ b/cmd/servicetoken/servicetoken_list_test.go @@ -18,8 +18,8 @@ func TestServiceTokenList(t *testing.T) { Id: int64p(1), Name: "test", Roles: []string{ - "test-role", - "another-role", + testRole, + testAnotherRole, }, Expiration: int64p(1590105600000), }, @@ -27,7 +27,7 @@ func TestServiceTokenList(t *testing.T) { Id: int64p(2), Name: "test2", Roles: []string{ - "test-role", + testRole, }, Expiration: nil, }, @@ -39,8 +39,8 @@ func TestServiceTokenList(t *testing.T) { { Header: []string{"id", "name", "expiration", "roles", "dedicated_Subject"}, Data: [][]interface{}{ - {int64(1), "test", "2020-05-22", []string{"test-role", "another-role"}, (*string)(nil)}, - {int64(2), "test2", "", []string{"test-role"}, (*string)(nil)}, + {int64(1), "test", "2020-05-22", []string{testRole, testAnotherRole}, (*string)(nil)}, + {int64(2), "test2", "", []string{testRole}, (*string)(nil)}, }, MissingTableDataMsg: printer.NotFoundMsg{Types: "service tokens"}, }, diff --git a/cmd/settings/settings_apply.go b/cmd/settings/settings_apply.go index 7f26f6da..4da77b08 100644 --- a/cmd/settings/settings_apply.go +++ b/cmd/settings/settings_apply.go @@ -13,6 +13,12 @@ import ( "github.com/stackvista/stackstate-cli/pkg/pflags" ) +const ( + typeKey = "Type" + nameKey = "Name" + identifierColumn = "Identifier" +) + var ( UnlockedStrategyChoices = []string{"fail", "skip", "overwrite"} LockedStrategyChoices = []string{"fail", "skip", "overwrite"} @@ -89,7 +95,7 @@ func RunSettingsApplyCommand(args *ApplyArgs) di.CmdWithApiFn { cli.Printer.Success(fmt.Sprintf("Applied %d setting node(s).\n", len(nodes))) if len(nodes) > 0 { cli.Printer.Table(printer.TableData{ - Header: []string{"Type", "Id", "Identifier", "Name"}, + Header: []string{typeKey, "Id", identifierColumn, nameKey}, Data: tableData, }) } diff --git a/cmd/settings/settings_apply_test.go b/cmd/settings/settings_apply_test.go index 6710aafa..18fbb6d9 100644 --- a/cmd/settings/settings_apply_test.go +++ b/cmd/settings/settings_apply_test.go @@ -54,7 +54,7 @@ func TestSetingsApplyFromFileNoOptionalArgs(t *testing.T) { assert.Nil(t, (*cli.MockClient.ApiMocks.ImportApi.ImportSettingsCalls)[0].Punlocked) expectedTableCall := []printer.TableData{ { - Header: []string{"Type", "Id", "Identifier", "Name"}, + Header: []string{typeKey, "Id", identifierColumn, nameKey}, Data: [][]interface{}{{"Layer", 12345, "urn:stackpack:test:layer:test", "test"}}, }, } diff --git a/cmd/settings/settings_edit.go b/cmd/settings/settings_edit.go index cf816077..b4af1f31 100644 --- a/cmd/settings/settings_edit.go +++ b/cmd/settings/settings_edit.go @@ -114,7 +114,7 @@ func RunSettingsEditCommand(args *EditArgs) di.CmdWithApiFn { cli.Printer.Success(fmt.Sprintf("Updated %d setting node(s).\n", len(nodes))) if len(nodes) > 0 { cli.Printer.Table(printer.TableData{ - Header: []string{"Type", "Id", "Identifier", "Name"}, + Header: []string{typeKey, "Id", identifierColumn, nameKey}, Data: tableData, }) } diff --git a/cmd/settings/settings_list.go b/cmd/settings/settings_list.go index a5d23298..cee87346 100644 --- a/cmd/settings/settings_list.go +++ b/cmd/settings/settings_list.go @@ -82,7 +82,7 @@ func RunSettingsListCommand(args *ListArgs) di.CmdWithApiFn { }) } cli.Printer.Table(printer.TableData{ - Header: []string{"Type", "Id", "Identifier", "Name", "owned by", "last updated"}, + Header: []string{typeKey, "Id", identifierColumn, nameKey, "owned by", "last updated"}, Data: data, MissingTableDataMsg: printer.NotFoundMsg{Types: fmt.Sprintf("settings of type \"%s\"", args.TypeName)}, }) diff --git a/cmd/settings/settings_list_test.go b/cmd/settings/settings_list_test.go index 46e7354e..a35151da 100644 --- a/cmd/settings/settings_list_test.go +++ b/cmd/settings/settings_list_test.go @@ -11,6 +11,10 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + testComponentType = "ComponentType" +) + var ( name = "One" otherName = "Two" @@ -21,7 +25,7 @@ var ( nodeApiResult = []sts.Node{ { Id: 1, - TypeName: "ComponentType", + TypeName: testComponentType, Identifier: &identifier, Name: &name, Description: &description, @@ -30,7 +34,7 @@ var ( }, { Id: 2, - TypeName: "ComponentType", + TypeName: testComponentType, Identifier: &otherIdentifier, Name: &otherName, Description: &description, @@ -51,12 +55,12 @@ func setupSettingsListCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { func TestSettingsListPrintsToTable(t *testing.T) { cli, cmd := setupSettingsListCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--type", "ComponentType") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--type", testComponentType) expectedTableCall := []printer.TableData{ { - Header: []string{"Type", "Id", "Identifier", "Name", "owned by", "last updated"}, - Data: [][]interface{}{{"ComponentType", int64(1), identifier, name, owner, expectedUpdateTime}, {"ComponentType", int64(2), otherIdentifier, otherName, owner, expectedUpdateTime}}, + Header: []string{typeKey, "Id", identifierColumn, nameKey, "owned by", "last updated"}, + Data: [][]interface{}{{testComponentType, int64(1), identifier, name, owner, expectedUpdateTime}, {testComponentType, int64(2), otherIdentifier, otherName, owner, expectedUpdateTime}}, MissingTableDataMsg: printer.NotFoundMsg{Types: "settings of type \"ComponentType\""}, }, } @@ -67,14 +71,14 @@ func TestSettingsListPrintsToTable(t *testing.T) { func TestSettingsListWithNamespaeAndOwnerPrintsToTable(t *testing.T) { cli, cmd := setupSettingsListCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--type", "ComponentType", + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--type", testComponentType, "--namespace", "component", "--owned-by", "urn:stackpack:stackstate-self-health:shared") expectedTableCall := []printer.TableData{ { - Header: []string{"Type", "Id", "Identifier", "Name", "owned by", "last updated"}, - Data: [][]interface{}{{"ComponentType", int64(1), identifier, name, owner, expectedUpdateTime}, {"ComponentType", int64(2), otherIdentifier, otherName, owner, expectedUpdateTime}}, + Header: []string{typeKey, "Id", identifierColumn, nameKey, "owned by", "last updated"}, + Data: [][]interface{}{{testComponentType, int64(1), identifier, name, owner, expectedUpdateTime}, {testComponentType, int64(2), otherIdentifier, otherName, owner, expectedUpdateTime}}, MissingTableDataMsg: printer.NotFoundMsg{Types: "settings of type \"ComponentType\""}, }, } @@ -85,7 +89,7 @@ func TestSettingsListWithNamespaeAndOwnerPrintsToTable(t *testing.T) { func TestSettingsListPrintsToJson(t *testing.T) { cli, cmd := setupSettingsListCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--type", "ComponentType", "-o", "json") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--type", testComponentType, "-o", "json") assert.Equal(t, []map[string]interface{}{{ diff --git a/cmd/settings/settings_list_types_test.go b/cmd/settings/settings_list_types_test.go index 03fa0a1a..4013ec50 100644 --- a/cmd/settings/settings_list_types_test.go +++ b/cmd/settings/settings_list_types_test.go @@ -10,13 +10,18 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + testWorld = "world" + testHello = "hello" +) + func setupSettingListTypesCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { cli := di.NewMockDeps(t) cmd := SettingsListTypesCommand(&cli.Deps) nodeApiResult := sts.NodeTypes{ NodeTypes: []sts.NodeTypesNodeTypesInner{ - {TypeName: "world", Description: "hello"}, - {TypeName: "hello", Description: "world"}, + {TypeName: testWorld, Description: testHello}, + {TypeName: testHello, Description: testWorld}, }, } cli.MockClient.ApiMocks.NodeApi.NodeListTypesResponse.Result = nodeApiResult @@ -30,7 +35,7 @@ func TestListTypesPrintsToTable(t *testing.T) { expectedTableCall := []printer.TableData{{ Header: []string{"name", "description"}, - Data: [][]interface{}{{"hello", "world"}, {"world", "hello"}}, + Data: [][]interface{}{{testHello, testWorld}, {testWorld, testHello}}, MissingTableDataMsg: printer.NotFoundMsg{Types: "setting types"}, }} @@ -44,8 +49,8 @@ func TestListTypesPrintsToJson(t *testing.T) { ordered := sts.NodeTypes{ NodeTypes: []sts.NodeTypesNodeTypesInner{ - {TypeName: "hello", Description: "world"}, - {TypeName: "world", Description: "hello"}, + {TypeName: testHello, Description: testWorld}, + {TypeName: testWorld, Description: testHello}, }, } diff --git a/cmd/stackpack/common.go b/cmd/stackpack/common.go index c9901340..25d83a72 100644 --- a/cmd/stackpack/common.go +++ b/cmd/stackpack/common.go @@ -14,6 +14,10 @@ import ( ) const ( + stackpackKey = "stackpack" + statusKey = "status" + versionKey = "version" + lastUpdatedColumn = "last updated" // StackPack configuration status constants for wait operations StatusInstalled = "INSTALLED" // Configuration is successfully installed StatusProvisioning = "PROVISIONING" // Configuration is still being processed @@ -147,8 +151,8 @@ func waitAndDisplayResult(cli *di.Deps, api *stackstate_api.APIClient, stackPack if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "stackpack": finalStackPack, - "status": "completed", + stackpackKey: finalStackPack, + statusKey: "completed", "current-version": finalStackPack.GetVersion(), }) } else { @@ -167,7 +171,7 @@ func waitAndDisplayResult(cli *di.Deps, api *stackstate_api.APIClient, stackPack } cli.Printer.Table(printer.TableData{ - Header: []string{"id", "name", "status", "version", "last updated"}, + Header: []string{"id", NameFlag, statusKey, versionKey, lastUpdatedColumn}, Data: data, MissingTableDataMsg: printer.NotFoundMsg{Types: "configurations for " + stackPackName}, }) diff --git a/cmd/stackpack/common_test.go b/cmd/stackpack/common_test.go index 208456fa..3e9fd5d8 100644 --- a/cmd/stackpack/common_test.go +++ b/cmd/stackpack/common_test.go @@ -12,6 +12,10 @@ import ( ) const ( + testWait = "--wait" + testInitialVersion = "1.0.0" + testZabbix = "zabbix" + timeoutFlagArg = "--timeout" testStackPackName = "test-stackpack" successfulResponseResult = "successful" ) @@ -32,7 +36,7 @@ func TestOperationWaiter_WaitForCompletion_Success(t *testing.T) { { Id: &configID, Status: StatusInstalled, - StackPackVersion: "1.0.0", + StackPackVersion: testInitialVersion, LastUpdateTimestamp: ×tamp, Config: map[string]interface{}{}, }, @@ -77,7 +81,7 @@ func TestOperationWaiter_WaitForCompletion_Error(t *testing.T) { { Id: &configID, Status: StatusError, - StackPackVersion: "1.0.0", + StackPackVersion: testInitialVersion, LastUpdateTimestamp: ×tamp, Config: map[string]interface{}{}, Error: &stackPackError, @@ -116,7 +120,7 @@ func TestOperationWaiter_WaitForCompletion_Timeout(t *testing.T) { { Id: &configID, Status: StatusProvisioning, - StackPackVersion: "1.0.0", + StackPackVersion: testInitialVersion, LastUpdateTimestamp: ×tamp, Config: map[string]interface{}{}, }, @@ -177,14 +181,14 @@ func TestOperationWaiter_WaitForCompletion_MultipleConfigurations(t *testing.T) { Id: &configID1, Status: StatusInstalled, - StackPackVersion: "1.0.0", + StackPackVersion: testInitialVersion, LastUpdateTimestamp: ×tamp, Config: map[string]interface{}{}, }, { Id: &configID2, Status: StatusProvisioning, - StackPackVersion: "1.0.0", + StackPackVersion: testInitialVersion, LastUpdateTimestamp: ×tamp, Config: map[string]interface{}{}, }, @@ -207,7 +211,7 @@ func TestOperationWaiter_WaitForCompletion_MultipleConfigurations(t *testing.T) } func TestFindStackPackByName_Found(t *testing.T) { - stackpackName := "zabbix" + stackpackName := testZabbix stacks := []stackstate_api.FullStackPack{ {Name: "mysql"}, {Name: stackpackName}, @@ -256,7 +260,7 @@ func validateWaitFlags(t *testing.T, cmd *cobra.Command) { assert.Equal(t, "1m0s", timeoutFlag.DefValue, "timeout flag default should be 1m0s") // Verify the flags can be set - err := cmd.ParseFlags([]string{"--wait", "--timeout", "30s"}) + err := cmd.ParseFlags([]string{testWait, timeoutFlagArg, "30s"}) assert.NoError(t, err) waitValue, err := cmd.Flags().GetBool("wait") diff --git a/cmd/stackpack/stackpack_confirm_manual_steps.go b/cmd/stackpack/stackpack_confirm_manual_steps.go index d7c5a76e..de1a3c6e 100644 --- a/cmd/stackpack/stackpack_confirm_manual_steps.go +++ b/cmd/stackpack/stackpack_confirm_manual_steps.go @@ -9,6 +9,10 @@ import ( "github.com/stackvista/stackstate-cli/internal/di" ) +const ( + successKey = "success" +) + type ManualStepsArgs struct { TypeName string ID int64 @@ -42,7 +46,7 @@ func RunStackpackConfirmManualStepsCommand(args *ManualStepsArgs) di.CmdWithApiF } if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "success": true, + successKey: true, "stackpack-name": args.TypeName, "stackpack-instance-id": args.ID, }) diff --git a/cmd/stackpack/stackpack_confirm_manual_steps_test.go b/cmd/stackpack/stackpack_confirm_manual_steps_test.go index 3b9a72d9..5a687e95 100644 --- a/cmd/stackpack/stackpack_confirm_manual_steps_test.go +++ b/cmd/stackpack/stackpack_confirm_manual_steps_test.go @@ -10,6 +10,10 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + nameFlagArg = "--name" +) + func setupStackPacConfirmManualStepsCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { cli := di.NewMockDeps(t) cmd := StackpackConfirmManualStepsCommand(&cli.Deps) @@ -19,7 +23,7 @@ func setupStackPacConfirmManualStepsCmd(t *testing.T) (*di.MockDeps, *cobra.Comm func TestStackpackConfirmManualStepsPrintsToTable(t *testing.T) { cli, cmd := setupStackPacConfirmManualStepsCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "confirm-manual-steps", "--name", "zabbix", + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "confirm-manual-steps", nameFlagArg, testZabbix, "--id", "1234", ) assert.True(t, cli.MockPrinter.HasNonJsonCalls) @@ -37,12 +41,12 @@ func TestStackpackConfirmManualStepsPrintsToTable(t *testing.T) { func TestStackpackConfirmManualStepsPrintsToJson(t *testing.T) { cli, cmd := setupStackPacConfirmManualStepsCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "confirm-manual-steps", "--name", "zabbix", + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "confirm-manual-steps", nameFlagArg, testZabbix, "--id", "1234", "-o", "json", ) expectedJsonCalls := []map[string]interface{}{{ - "success": true, - "stackpack-name": "zabbix", + successKey: true, + "stackpack-name": testZabbix, "stackpack-instance-id": int64(1234), }} assert.Equal(t, expectedJsonCalls, *cli.MockPrinter.PrintJsonCalls) diff --git a/cmd/stackpack/stackpack_delete_version_test.go b/cmd/stackpack/stackpack_delete_version_test.go index 32847589..0e782df5 100644 --- a/cmd/stackpack/stackpack_delete_version_test.go +++ b/cmd/stackpack/stackpack_delete_version_test.go @@ -16,7 +16,7 @@ func setupStackPackDeleteVersionCmd(t *testing.T) (*di.MockDeps, *cobra.Command) func TestStackpackDeleteVersionPrintToConsole(t *testing.T) { cli, cmd := setupStackPackDeleteVersionCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete-version", "--name", "kubernetes", "--stackpack-version", "1.0.0") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete-version", nameFlagArg, "kubernetes", "--stackpack-version", testInitialVersion) expectedSuccessMessage := []string{"Successfully deleted version 1.0.0 of StackPack kubernetes"} assert.True(t, cli.MockPrinter.HasNonJsonCalls) @@ -25,15 +25,15 @@ func TestStackpackDeleteVersionPrintToConsole(t *testing.T) { assert.Equal(t, 1, len(*cli.MockClient.ApiMocks.StackpackApi.StackPackDeleteVersionCalls)) call := (*cli.MockClient.ApiMocks.StackpackApi.StackPackDeleteVersionCalls)[0] assert.Equal(t, "kubernetes", call.PstackPackName) - assert.Equal(t, "1.0.0", call.Pversion) + assert.Equal(t, testInitialVersion, call.Pversion) } func TestStackpackDeleteVersionPrintToJson(t *testing.T) { cli, cmd := setupStackPackDeleteVersionCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete-version", "--name", "kubernetes", "--stackpack-version", "1.0.0", "-o", "json") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete-version", nameFlagArg, "kubernetes", "--stackpack-version", testInitialVersion, "-o", "json") expectedJsonCalls := []map[string]interface{}{{ - "deleted": "1.0.0", + "deleted": testInitialVersion, }} assert.False(t, cli.MockPrinter.HasNonJsonCalls) assert.Equal(t, expectedJsonCalls, *cli.MockPrinter.PrintJsonCalls) diff --git a/cmd/stackpack/stackpack_delete_versions_test.go b/cmd/stackpack/stackpack_delete_versions_test.go index e359682f..9a95aa5a 100644 --- a/cmd/stackpack/stackpack_delete_versions_test.go +++ b/cmd/stackpack/stackpack_delete_versions_test.go @@ -9,11 +9,16 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + testNextVersion = "1.1.0" + testMajorVersion = "2.0.0" +) + func setupStackPackDeleteVersionsCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { cli := di.NewMockDeps(t) cmd := StackpackDeleteVersionsCommand(&cli.Deps) cli.MockClient.ApiMocks.StackpackApi.StackPackDeleteVersionsResponse.Result = stackstate_api.DeleteVersionsResult{ - Deleted: []string{"1.0.0", "1.1.0"}, + Deleted: []string{testInitialVersion, testNextVersion}, SkippedInUse: []string{"1.2.0"}, } return &cli, cmd @@ -21,7 +26,7 @@ func setupStackPackDeleteVersionsCmd(t *testing.T) (*di.MockDeps, *cobra.Command func TestStackpackDeleteVersionsWithTo(t *testing.T) { cli, cmd := setupStackPackDeleteVersionsCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete-versions", "--name", "kubernetes", "--to", "1.5.0") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete-versions", nameFlagArg, "kubernetes", "--to", "1.5.0") assert.True(t, cli.MockPrinter.HasNonJsonCalls) assert.Equal(t, []string{"Deleted versions: 1.0.0, 1.1.0"}, *cli.MockPrinter.SuccessCalls) @@ -37,12 +42,12 @@ func TestStackpackDeleteVersionsWithTo(t *testing.T) { func TestStackpackDeleteVersionsWithRange(t *testing.T) { cli, cmd := setupStackPackDeleteVersionsCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete-versions", "--name", "kubernetes", "--from", "1.0.0", "--to", "1.5.0") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete-versions", nameFlagArg, "kubernetes", "--from", testInitialVersion, "--to", "1.5.0") assert.Equal(t, 1, len(*cli.MockClient.ApiMocks.StackpackApi.StackPackDeleteVersionsCalls)) call := (*cli.MockClient.ApiMocks.StackpackApi.StackPackDeleteVersionsCalls)[0] assert.Equal(t, "kubernetes", call.PstackPackName) - assert.Equal(t, "1.0.0", *call.Pfrom) + assert.Equal(t, testInitialVersion, *call.Pfrom) assert.Equal(t, "1.5.0", *call.Pto) assert.Nil(t, call.Pall) assert.Nil(t, call.Pdev) @@ -50,7 +55,7 @@ func TestStackpackDeleteVersionsWithRange(t *testing.T) { func TestStackpackDeleteVersionsWithAll(t *testing.T) { cli, cmd := setupStackPackDeleteVersionsCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete-versions", "--name", "kubernetes", "--all") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete-versions", nameFlagArg, "kubernetes", "--all") assert.Equal(t, 1, len(*cli.MockClient.ApiMocks.StackpackApi.StackPackDeleteVersionsCalls)) call := (*cli.MockClient.ApiMocks.StackpackApi.StackPackDeleteVersionsCalls)[0] @@ -63,7 +68,7 @@ func TestStackpackDeleteVersionsWithAll(t *testing.T) { func TestStackpackDeleteVersionsWithAllAndDevOnly(t *testing.T) { cli, cmd := setupStackPackDeleteVersionsCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete-versions", "--name", "kubernetes", "--all", "--dev-only") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete-versions", nameFlagArg, "kubernetes", "--all", "--dev-only") assert.Equal(t, 1, len(*cli.MockClient.ApiMocks.StackpackApi.StackPackDeleteVersionsCalls)) call := (*cli.MockClient.ApiMocks.StackpackApi.StackPackDeleteVersionsCalls)[0] @@ -76,10 +81,10 @@ func TestStackpackDeleteVersionsWithAllAndDevOnly(t *testing.T) { func TestStackpackDeleteVersionsPrintToJson(t *testing.T) { cli, cmd := setupStackPackDeleteVersionsCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete-versions", "--name", "kubernetes", "--to", "2.0.0", "-o", "json") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete-versions", nameFlagArg, "kubernetes", "--to", testMajorVersion, "-o", "json") expectedJsonCalls := []map[string]interface{}{{ - "deleted": []string{"1.0.0", "1.1.0"}, + "deleted": []string{testInitialVersion, testNextVersion}, "skippedInUse": []string{"1.2.0"}, }} assert.False(t, cli.MockPrinter.HasNonJsonCalls) @@ -89,20 +94,20 @@ func TestStackpackDeleteVersionsPrintToJson(t *testing.T) { func TestStackpackDeleteVersionsNoFlags(t *testing.T) { cli := di.NewMockDeps(t) cmd := StackpackDeleteVersionsCommand(&cli.Deps) - _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "delete-versions", "--name", "kubernetes") + _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "delete-versions", nameFlagArg, "kubernetes") assert.Error(t, err) } func TestStackpackDeleteVersionsAllWithFrom(t *testing.T) { cli := di.NewMockDeps(t) cmd := StackpackDeleteVersionsCommand(&cli.Deps) - _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "delete-versions", "--name", "kubernetes", "--all", "--from", "1.0.0") + _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "delete-versions", nameFlagArg, "kubernetes", "--all", "--from", testInitialVersion) assert.Error(t, err) } func TestStackpackDeleteVersionsAllWithTo(t *testing.T) { cli := di.NewMockDeps(t) cmd := StackpackDeleteVersionsCommand(&cli.Deps) - _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "delete-versions", "--name", "kubernetes", "--all", "--to", "1.5.0") + _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "delete-versions", nameFlagArg, "kubernetes", "--all", "--to", "1.5.0") assert.Error(t, err) } diff --git a/cmd/stackpack/stackpack_describe.go b/cmd/stackpack/stackpack_describe.go index ab0c2f68..2fea10e9 100644 --- a/cmd/stackpack/stackpack_describe.go +++ b/cmd/stackpack/stackpack_describe.go @@ -12,8 +12,9 @@ import ( ) const ( - Name = "name" - NameUsage = "StackPack name" + displayNameColumn = "display name" + Name = "name" + NameUsage = "StackPack name" ) type DescribeArgs struct { @@ -52,7 +53,7 @@ func RunStackpackDescribeCommand(args *DescribeArgs) di.CmdWithApiFn { if stackpack.Name == args.Name { if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "stackpack": stackpack, + stackpackKey: stackpack, }) } else { cli.Printer.PrintLn(fmt.Sprintf("StackPack %s v%s (latest available is v%s)", stackpack.DisplayName, stackpack.Version, stackpack.LatestVersion.Version)) @@ -71,14 +72,14 @@ func RunStackpackDescribeCommand(args *DescribeArgs) di.CmdWithApiFn { if len(stackpack.Steps) > 0 { cli.Printer.PrintLn("\nInstance configuration parameters:") cli.Printer.Table(printer.TableData{ - Header: []string{"name", "display name", "type"}, + Header: []string{NameFlag, displayNameColumn, "type"}, Data: formatParametersTable(stackpack), MissingTableDataMsg: printer.NotFoundMsg{Types: "instance parameters"}, }) } cli.Printer.PrintLn("\nInstalled instances:") cli.Printer.Table(printer.TableData{ - Header: []string{"id", "status", "version", "last updated"}, + Header: []string{"id", statusKey, versionKey, lastUpdatedColumn}, Data: formatInstancesTable(stackpack), MissingTableDataMsg: printer.NotFoundMsg{Types: "installed StackPack instances"}, }) diff --git a/cmd/stackpack/stackpack_describe_test.go b/cmd/stackpack/stackpack_describe_test.go index dac35129..d6336c78 100644 --- a/cmd/stackpack/stackpack_describe_test.go +++ b/cmd/stackpack/stackpack_describe_test.go @@ -11,6 +11,14 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + testType = "type" +) + +const ( + installedInstancesTitle = "installed StackPack instances" +) + var ( testDisplayName = "Test StackPack" testCurrVersion = "1.2.3" @@ -77,8 +85,8 @@ func TestStackpackDescribeNotFound(t *testing.T) { cli.MockClient.ApiMocks.StackpackApi.StackPackListResponse.Result = mockResponse - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "describe", "--name", "foobar") - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "describe", "--name", "foobar", "-o", "json") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "describe", nameFlagArg, "foobar") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "describe", nameFlagArg, "foobar", "-o", "json") expected := []error{ fmt.Errorf("StackPack 'foobar' not found."), @@ -94,7 +102,7 @@ func TestStackpackDescribeJson(t *testing.T) { cli.MockClient.ApiMocks.StackpackApi.StackPackListResponse.Result = mockResponse - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "describe", "--name", awsName, "-o", "json") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "describe", nameFlagArg, awsName, "-o", "json") expected := []map[string]interface{}{ { @@ -111,7 +119,7 @@ func TestStackpackDescribeText(t *testing.T) { cli.MockClient.ApiMocks.StackpackApi.StackPackListResponse.Result = []stackstate_api.FullStackPack{testStackPack} - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "describe", "--name", testName) + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "describe", nameFlagArg, testName) expectedLines := []string{ fmt.Sprintf("StackPack %s v%s (latest available is v%s)", testDisplayName, testCurrVersion, testLatestVersion), @@ -123,7 +131,7 @@ func TestStackpackDescribeText(t *testing.T) { expectedTables := []printer.TableData{ { - Header: []string{"name", "display name", "type"}, + Header: []string{NameFlag, displayNameColumn, testType}, Data: [][]interface{}{ {&testStep1Name, &testStep1Name, &testStepType}, {&testStep2Name, &testStep2Name, &testStepType}, @@ -131,11 +139,11 @@ func TestStackpackDescribeText(t *testing.T) { MissingTableDataMsg: printer.NotFoundMsg{Types: "instance parameters"}, }, { - Header: []string{"id", "status", "version", "last updated"}, + Header: []string{"id", statusKey, versionKey, lastUpdatedColumn}, Data: [][]interface{}{ {&testId, testStatus, testCurrVersion, testTimestamp}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: "installed StackPack instances"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: installedInstancesTitle}, }, } @@ -152,7 +160,7 @@ func TestStackpackDescribeTextNoCategories(t *testing.T) { cli.MockClient.ApiMocks.StackpackApi.StackPackListResponse.Result = []stackstate_api.FullStackPack{newTest} - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "describe", "--name", testName) + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "describe", nameFlagArg, testName) expectedLines := []string{ fmt.Sprintf("StackPack %s v%s (latest available is v%s)", testDisplayName, testCurrVersion, testLatestVersion), @@ -173,15 +181,15 @@ func TestStackpackDescribeTextNoSteps(t *testing.T) { cli.MockClient.ApiMocks.StackpackApi.StackPackListResponse.Result = []stackstate_api.FullStackPack{newTest} - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "describe", "--name", testName) + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "describe", nameFlagArg, testName) expectedTables := []printer.TableData{ { - Header: []string{"id", "status", "version", "last updated"}, + Header: []string{"id", statusKey, versionKey, lastUpdatedColumn}, Data: [][]interface{}{ {&testId, testStatus, testCurrVersion, testTimestamp}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: "installed StackPack instances"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: installedInstancesTitle}, }, } @@ -197,11 +205,11 @@ func TestStackpackDescribeTextNoInstances(t *testing.T) { cli.MockClient.ApiMocks.StackpackApi.StackPackListResponse.Result = []stackstate_api.FullStackPack{newTest} - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "describe", "--name", testName) + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "describe", nameFlagArg, testName) expectedTables := []printer.TableData{ { - Header: []string{"name", "display name", "type"}, + Header: []string{NameFlag, displayNameColumn, testType}, Data: [][]interface{}{ {&testStep1Name, &testStep1Name, &testStepType}, {&testStep2Name, &testStep2Name, &testStepType}, @@ -210,9 +218,9 @@ func TestStackpackDescribeTextNoInstances(t *testing.T) { }, // NOTE Still printed. { - Header: []string{"id", "status", "version", "last updated"}, + Header: []string{"id", statusKey, versionKey, lastUpdatedColumn}, Data: [][]interface{}{}, - MissingTableDataMsg: printer.NotFoundMsg{Types: "installed StackPack instances"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: installedInstancesTitle}, }, } assert.Equal(t, expectedTables, *cli.MockPrinter.TableCalls) diff --git a/cmd/stackpack/stackpack_downgrade.go b/cmd/stackpack/stackpack_downgrade.go index 3fb2c885..d6c7413b 100644 --- a/cmd/stackpack/stackpack_downgrade.go +++ b/cmd/stackpack/stackpack_downgrade.go @@ -61,7 +61,7 @@ func RunStackpackDowngradeCommand(args *DowngradeArgs) di.CmdWithApiFn { } else { if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "success": true, + successKey: true, "target-version": args.Version, }) } else { diff --git a/cmd/stackpack/stackpack_downgrade_test.go b/cmd/stackpack/stackpack_downgrade_test.go index 3f21b28b..6a69c865 100644 --- a/cmd/stackpack/stackpack_downgrade_test.go +++ b/cmd/stackpack/stackpack_downgrade_test.go @@ -22,13 +22,13 @@ func setupStackPackDowngradeCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { func TestStackpackDowngradePrintToTable(t *testing.T) { cli, cmd := setupStackPackDowngradeCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "downgrade", "--name", "zabbix", + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "downgrade", nameFlagArg, testZabbix, "--stackpack-version", downgradeVersion, ) assert.Equal(t, []stackstate_api.DowngradeStackPackCall{{ - PstackPackName: "zabbix", + PstackPackName: testZabbix, Pversion: &downgradeVersion, }}, *cli.MockClient.ApiMocks.StackpackApi.DowngradeStackPackCalls) @@ -38,19 +38,19 @@ func TestStackpackDowngradePrintToTable(t *testing.T) { func TestStackpackDowngradePrintToJson(t *testing.T) { cli, cmd := setupStackPackDowngradeCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "downgrade", "--name", "zabbix", + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "downgrade", nameFlagArg, testZabbix, "--stackpack-version", downgradeVersion, "-o", "json", ) assert.Equal(t, []stackstate_api.DowngradeStackPackCall{{ - PstackPackName: "zabbix", + PstackPackName: testZabbix, Pversion: &downgradeVersion, }}, *cli.MockClient.ApiMocks.StackpackApi.DowngradeStackPackCalls) expectedJsonCalls := []map[string]interface{}{{ - "success": true, + successKey: true, "target-version": downgradeVersion, }} assert.Equal(t, expectedJsonCalls, *cli.MockPrinter.PrintJsonCalls) @@ -60,7 +60,7 @@ func TestStackpackDowngradeRequiresVersion(t *testing.T) { cli := di.NewMockDeps(t) cmd := StackpackDowngradeCommand(&cli.Deps) - _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "downgrade", "--name", "zabbix") + _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "downgrade", nameFlagArg, testZabbix) assert.Error(t, err) assert.Contains(t, err.Error(), "stackpack-version") diff --git a/cmd/stackpack/stackpack_install.go b/cmd/stackpack/stackpack_install.go index 69b4e4f8..0dfe9d7e 100644 --- a/cmd/stackpack/stackpack_install.go +++ b/cmd/stackpack/stackpack_install.go @@ -13,6 +13,10 @@ import ( "github.com/stackvista/stackstate-cli/pkg/pflags" ) +const ( + failKey = "fail" +) + type InstallArgs struct { Name string UnlockedStrategy string @@ -43,7 +47,7 @@ sts stackpack install --name example --stackpack-version 1.2.3 -p "full_name=Fir common.AddRequiredNameFlagVar(cmd, &args.Name, "Name of the StackPack") pflags.EnumVar(cmd.Flags(), &args.UnlockedStrategy, UnlockedStrategyFlag, - "fail", + failKey, UnlockedStrategyChoices, "Strategy use to upgrade StackPack instance"+ fmt.Sprintf(" (must be { %s })", strings.Join(UnlockedStrategyChoices, " | ")), @@ -103,8 +107,8 @@ func RunStackpackInstallCommand(args *InstallArgs) di.CmdWithApiFn { // Display final status if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "stackpack": finalStackPack, - "status": "completed", + stackpackKey: finalStackPack, + statusKey: "completed", }) } else { cli.Printer.Success("StackPack installation completed successfully") @@ -124,7 +128,7 @@ func RunStackpackInstallCommand(args *InstallArgs) di.CmdWithApiFn { cli.Printer.Table( printer.TableData{ - Header: []string{"id", "name", "status", "version", "last updated"}, + Header: []string{"id", NameFlag, statusKey, versionKey, lastUpdatedColumn}, Data: data, MissingTableDataMsg: printer.NotFoundMsg{Types: "configurations for " + args.Name}, }, @@ -141,7 +145,7 @@ func RunStackpackInstallCommand(args *InstallArgs) di.CmdWithApiFn { cli.Printer.Success("StackPack instance installation triggered") cli.Printer.Table( printer.TableData{ - Header: []string{"id", "name", "status", "version", "last updated"}, + Header: []string{"id", NameFlag, statusKey, versionKey, lastUpdatedColumn}, Data: [][]interface{}{{instance.Id, instance.Name, instance.Status, instance.StackPackVersion, lastUpdateTime}}, MissingTableDataMsg: printer.NotFoundMsg{Types: "provision details of " + args.Name}, }, diff --git a/cmd/stackpack/stackpack_install_test.go b/cmd/stackpack/stackpack_install_test.go index f00aa689..625eda7e 100644 --- a/cmd/stackpack/stackpack_install_test.go +++ b/cmd/stackpack/stackpack_install_test.go @@ -12,11 +12,12 @@ import ( ) const ( - FailStrategy = "fail" + testUploadName = "test" + FailStrategy = "fail" ) var ( - name = "zabbix" + name = testZabbix provisionID = int64(1234) provisionName = "provision_name" provisionStatus = "PROVISIONING" @@ -42,7 +43,7 @@ func setupStackPackInstallCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { func TestStackpackInstallPrintsToTable(t *testing.T) { cli, cmd := setupStackPackInstallCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "install", "--name", "zabbix", + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "install", nameFlagArg, testZabbix, "--parameter", "zabbix_instance_name=test_name", "--parameter", "zabbix_instance_url=test_url", ) @@ -50,7 +51,7 @@ func TestStackpackInstallPrintsToTable(t *testing.T) { strategyFlag := FailStrategy assert.Equal(t, stackstate_api.ProvisionDetailsCall{ - PstackPackName: "zabbix", + PstackPackName: testZabbix, Punlocked: &strategyFlag, PrequestBody: &map[string]string{ "zabbix_instance_name": "test_name", @@ -61,7 +62,7 @@ func TestStackpackInstallPrintsToTable(t *testing.T) { ) expectedTableCall := []printer.TableData{ { - Header: []string{"id", "name", "status", "version", "last updated"}, + Header: []string{"id", NameFlag, statusKey, versionKey, lastUpdatedColumn}, Data: [][]interface{}{{&provisionID, &provisionName, &provisionStatus, &provisionVersion, expectedUpdateTime}}, MissingTableDataMsg: printer.NotFoundMsg{Types: "provision details of " + name}, }, @@ -72,7 +73,7 @@ func TestStackpackInstallPrintsToTable(t *testing.T) { func TestStackpackInstallComplexParameters(t *testing.T) { cli, cmd := setupStackPackInstallCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "install", "--name", "zabbix", + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "install", nameFlagArg, testZabbix, "--parameter", "one=foo,two=bar", "--parameter", "i=am=complex", "--parameter", "empty=", @@ -82,7 +83,7 @@ func TestStackpackInstallComplexParameters(t *testing.T) { strategyFlag := FailStrategy assert.Equal(t, stackstate_api.ProvisionDetailsCall{ - PstackPackName: "zabbix", + PstackPackName: testZabbix, Punlocked: &strategyFlag, PrequestBody: &map[string]string{ "one": "foo", @@ -99,12 +100,12 @@ func TestStackpackInstallComplexParameters(t *testing.T) { func TestStackpackInstallNoParameters(t *testing.T) { cli, cmd := setupStackPackInstallCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "install", "--name", "zabbix") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "install", nameFlagArg, testZabbix) strategyFlag := FailStrategy assert.Equal(t, stackstate_api.ProvisionDetailsCall{ - PstackPackName: "zabbix", + PstackPackName: testZabbix, Punlocked: &strategyFlag, PrequestBody: &map[string]string{}, }, @@ -115,7 +116,7 @@ func TestStackpackInstallNoParameters(t *testing.T) { func TestStackpackInstallWithVersion(t *testing.T) { cli, cmd := setupStackPackInstallCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "install", "--name", "zabbix", + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "install", nameFlagArg, testZabbix, "--stackpack-version", "3.2.0", ) @@ -123,7 +124,7 @@ func TestStackpackInstallWithVersion(t *testing.T) { versionFlag := "3.2.0" assert.Equal(t, stackstate_api.ProvisionDetailsCall{ - PstackPackName: "zabbix", + PstackPackName: testZabbix, Punlocked: &strategyFlag, Pversion: &versionFlag, PrequestBody: &map[string]string{}, @@ -135,7 +136,7 @@ func TestStackpackInstallWithVersion(t *testing.T) { func TestStackpackInstallWithoutVersion(t *testing.T) { cli, cmd := setupStackPackInstallCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "install", "--name", "zabbix") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "install", nameFlagArg, testZabbix) assert.Nil(t, (*cli.MockClient.ApiMocks.StackpackApi.ProvisionDetailsCalls)[0].Pversion) } @@ -143,7 +144,7 @@ func TestStackpackInstallWithoutVersion(t *testing.T) { func TestStackpackInstallPrintsToJson(t *testing.T) { cli, cmd := setupStackPackInstallCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "install", "--name", "zabbix", "-o", "json") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "install", nameFlagArg, testZabbix, "-o", "json") assert.Equal(t, []map[string]interface{}{{ @@ -201,7 +202,7 @@ func TestStackpackInstallWithWaitTimeout(t *testing.T) { }, } - _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "install", "--name", name, "--wait", "--timeout", "50ms") + _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "install", nameFlagArg, name, testWait, timeoutFlagArg, "50ms") // Should return timeout error assert.Error(t, err) @@ -213,7 +214,7 @@ func TestStackpackInstallWithWaitJsonFlags(t *testing.T) { cmd := StackpackInstallCommand(&cli.Deps) // Test that wait and timeout flags can be parsed with other flags - err := cmd.ParseFlags([]string{"--name", "test", "--wait", "--timeout", "100ms"}) + err := cmd.ParseFlags([]string{nameFlagArg, testUploadName, testWait, timeoutFlagArg, "100ms"}) assert.NoError(t, err) // Verify flag values @@ -225,7 +226,7 @@ func TestStackpackInstallWithWaitJsonFlags(t *testing.T) { assert.NoError(t, err) assert.Equal(t, 100*time.Millisecond, timeoutValue) - nameValue, err := cmd.Flags().GetString("name") + nameValue, err := cmd.Flags().GetString(NameFlag) assert.NoError(t, err) - assert.Equal(t, "test", nameValue) + assert.Equal(t, testUploadName, nameValue) } diff --git a/cmd/stackpack/stackpack_list.go b/cmd/stackpack/stackpack_list.go index 15d47f2e..e19c76f5 100644 --- a/cmd/stackpack/stackpack_list.go +++ b/cmd/stackpack/stackpack_list.go @@ -66,7 +66,7 @@ func RunStackpackListCommand(args *ListArgs) di.CmdWithApiFn { }) } else { cli.Printer.Table(printer.TableData{ - Header: []string{"name", "display name", "installed version", "next version", "latest version", "instance count"}, + Header: []string{NameFlag, displayNameColumn, "installed version", "next version", "latest version", "instance count"}, Data: data, MissingTableDataMsg: printer.NotFoundMsg{Types: "StackPacks"}, }) diff --git a/cmd/stackpack/stackpack_list_instances.go b/cmd/stackpack/stackpack_list_instances.go index 6a9d3243..7486aa10 100644 --- a/cmd/stackpack/stackpack_list_instances.go +++ b/cmd/stackpack/stackpack_list_instances.go @@ -85,7 +85,7 @@ func RunStackpackListInstanceCommand(args *ListPropertiesArgs) di.CmdWithApiFn { }) } else { cli.Printer.Table(printer.TableData{ - Header: []string{"id", "status", "version", "last updated"}, + Header: []string{"id", statusKey, versionKey, lastUpdatedColumn}, Data: data, MissingTableDataMsg: printer.NotFoundMsg{Types: "installed StackPack instances"}, }) diff --git a/cmd/stackpack/stackpack_list_instances_test.go b/cmd/stackpack/stackpack_list_instances_test.go index 8626faae..51c922fc 100644 --- a/cmd/stackpack/stackpack_list_instances_test.go +++ b/cmd/stackpack/stackpack_list_instances_test.go @@ -68,12 +68,12 @@ func TestStackpackListInstancePrintToTable(t *testing.T) { di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list-instances", "-n", testName) expectedTableCall := []printer.TableData{ { - Header: []string{"id", "status", "version", "last updated"}, + Header: []string{"id", statusKey, versionKey, lastUpdatedColumn}, Data: [][]interface{}{ {&id, statusInstalled, testVersion, expectedUpdateTimeLi}, {&id, statusInstalled, testVersion, beforeUpdateTimeLi}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: "installed StackPack instances"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: installedInstancesTitle}, }, } assert.Equal(t, expectedTableCall, *cli.MockPrinter.TableCalls) @@ -81,7 +81,7 @@ func TestStackpackListInstancePrintToTable(t *testing.T) { func TestStackpackListInstancePrintToJson(t *testing.T) { cli, cmd := setupStackpackListInstanceFn(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list-instances", "--name", testName, "-o", "json") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list-instances", nameFlagArg, testName, "-o", "json") expectedJsonCalls := []map[string]interface{}{{ "instances": []stackstate_api.StackPackConfiguration{ { diff --git a/cmd/stackpack/stackpack_list_parameters.go b/cmd/stackpack/stackpack_list_parameters.go index 5a66af6e..ca48d364 100644 --- a/cmd/stackpack/stackpack_list_parameters.go +++ b/cmd/stackpack/stackpack_list_parameters.go @@ -78,7 +78,7 @@ func RunStackpackListParameterCommand(args *ListPropertiesArgs) di.CmdWithApiFn }) } else { cli.Printer.Table(printer.TableData{ - Header: []string{"name", "display name", "type"}, + Header: []string{NameFlag, displayNameColumn, "type"}, Data: data, MissingTableDataMsg: printer.NotFoundMsg{Types: fmt.Sprintf("StackPack \"%s\"", args.Name)}, }) diff --git a/cmd/stackpack/stackpack_list_parameters_test.go b/cmd/stackpack/stackpack_list_parameters_test.go index a63ca80c..da107338 100644 --- a/cmd/stackpack/stackpack_list_parameters_test.go +++ b/cmd/stackpack/stackpack_list_parameters_test.go @@ -12,7 +12,7 @@ import ( ) var ( - parameterName = "zabbix" + parameterName = testZabbix stepName = "zabbix_instance_name" stepDisplayName = "Zabbix Instance Name" stepType = "Text" @@ -50,10 +50,10 @@ func setupStackpackListParametersFn(t *testing.T) (*di.MockDeps, *cobra.Command) func TestStackpackListParameterPrintToTable(t *testing.T) { cli, cmd := setupStackpackListParametersFn(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list-parameters", "--name", parameterName) + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list-parameters", nameFlagArg, parameterName) expectedTableCall := []printer.TableData{ { - Header: []string{"name", "display name", "type"}, + Header: []string{NameFlag, displayNameColumn, testType}, Data: [][]interface{}{{&firstStepName, &stepDisplayName, &stepType}, {&stepName, &stepDisplayName, &stepType}}, MissingTableDataMsg: printer.NotFoundMsg{Types: fmt.Sprintf("StackPack \"%s\"", parameterName)}, }, @@ -63,7 +63,7 @@ func TestStackpackListParameterPrintToTable(t *testing.T) { func TestStackpackListParameterPrintToJson(t *testing.T) { cli, cmd := setupStackpackListParametersFn(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list-parameters", "--name", parameterName, "-o", "json") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list-parameters", nameFlagArg, parameterName, "-o", "json") expectedJsonCalls := []map[string]interface{}{{ "parameters": []stackstate_api.StackPackStep{ { diff --git a/cmd/stackpack/stackpack_list_test.go b/cmd/stackpack/stackpack_list_test.go index 7372126f..bee689ff 100644 --- a/cmd/stackpack/stackpack_list_test.go +++ b/cmd/stackpack/stackpack_list_test.go @@ -62,7 +62,7 @@ func TestStackpackListPrintToTable(t *testing.T) { di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list") expectedTableCall := []printer.TableData{ { - Header: []string{"name", "display name", "installed version", "next version", "latest version", "instance count"}, + Header: []string{NameFlag, displayNameColumn, "installed version", "next version", "latest version", "instance count"}, Data: [][]interface{}{ {awsName, ucmdDisplayName, ucmdbVersion, ucmdbVersion, ucmdbVersion, 1}, {ucmdbName, ucmdDisplayName, ucmdbVersion, ucmdbVersion, ucmdbVersion, 1}}, @@ -120,7 +120,7 @@ func TestStackpackListWithInstalledPrintToTable(t *testing.T) { di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list", "--installed") expectedTableCall := []printer.TableData{ { - Header: []string{"name", "display name", "installed version", "next version", "latest version", "instance count"}, + Header: []string{NameFlag, displayNameColumn, "installed version", "next version", "latest version", "instance count"}, Data: [][]interface{}{{name, displayName, version, nextVersion, latestVersion, 1}}, MissingTableDataMsg: printer.NotFoundMsg{Types: "StackPacks"}, }, diff --git a/cmd/stackpack/stackpack_list_versions.go b/cmd/stackpack/stackpack_list_versions.go index ff99c336..171a163a 100644 --- a/cmd/stackpack/stackpack_list_versions.go +++ b/cmd/stackpack/stackpack_list_versions.go @@ -61,7 +61,7 @@ func RunStackpackListVersionsCommand(args *ListVersionsArgs) di.CmdWithApiFn { }) } cli.Printer.Table(printer.TableData{ - Header: []string{"version", "dev", "in use"}, + Header: []string{versionKey, "dev", "in use"}, Data: data, MissingTableDataMsg: printer.NotFoundMsg{Types: "versions"}, }) diff --git a/cmd/stackpack/stackpack_list_versions_test.go b/cmd/stackpack/stackpack_list_versions_test.go index 40cfebfe..7accfd99 100644 --- a/cmd/stackpack/stackpack_list_versions_test.go +++ b/cmd/stackpack/stackpack_list_versions_test.go @@ -10,9 +10,13 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + testVersions = "versions" +) + var listVersionsMockResponse = []stackstate_api.StackPackVersionInfo{ - {Version: "1.0.0", IsDev: false, IsInUse: true}, - {Version: "1.1.0", IsDev: false, IsInUse: false}, + {Version: testInitialVersion, IsDev: false, IsInUse: true}, + {Version: testNextVersion, IsDev: false, IsInUse: false}, {Version: "2.0.0-SNAPSHOT.1", IsDev: true, IsInUse: false}, } @@ -25,17 +29,17 @@ func setupStackPackListVersionsCmd(t *testing.T) (*di.MockDeps, *cobra.Command) func TestStackpackListVersionsPrintToTable(t *testing.T) { cli, cmd := setupStackPackListVersionsCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list-versions", "--name", "kubernetes") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list-versions", nameFlagArg, "kubernetes") assert.Equal(t, []printer.TableData{ { - Header: []string{"version", "dev", "in use"}, + Header: []string{versionKey, "dev", "in use"}, Data: [][]interface{}{ - {"1.0.0", false, true}, - {"1.1.0", false, false}, + {testInitialVersion, false, true}, + {testNextVersion, false, false}, {"2.0.0-SNAPSHOT.1", true, false}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: "versions"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: testVersions}, }, }, *cli.MockPrinter.TableCalls) @@ -45,10 +49,10 @@ func TestStackpackListVersionsPrintToTable(t *testing.T) { func TestStackpackListVersionsPrintToJson(t *testing.T) { cli, cmd := setupStackPackListVersionsCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list-versions", "--name", "kubernetes", "-o", "json") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list-versions", nameFlagArg, "kubernetes", "-o", "json") expectedJsonCalls := []map[string]interface{}{{ - "versions": listVersionsMockResponse, + testVersions: listVersionsMockResponse, }} assert.Equal(t, expectedJsonCalls, *cli.MockPrinter.PrintJsonCalls) assert.False(t, cli.MockPrinter.HasNonJsonCalls) @@ -58,13 +62,13 @@ func TestStackpackListVersionsEmpty(t *testing.T) { cli := di.NewMockDeps(t) cmd := StackpackListVersionsCommand(&cli.Deps) cli.MockClient.ApiMocks.StackpackApi.StackPackListVersionsResponse.Result = []stackstate_api.StackPackVersionInfo{} - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list-versions", "--name", "kubernetes") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list-versions", nameFlagArg, "kubernetes") assert.Equal(t, []printer.TableData{ { - Header: []string{"version", "dev", "in use"}, + Header: []string{versionKey, "dev", "in use"}, Data: [][]interface{}{}, - MissingTableDataMsg: printer.NotFoundMsg{Types: "versions"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: testVersions}, }, }, *cli.MockPrinter.TableCalls) } diff --git a/cmd/stackpack/stackpack_package.go b/cmd/stackpack/stackpack_package.go index 85d69ec7..984baf8e 100644 --- a/cmd/stackpack/stackpack_package.go +++ b/cmd/stackpack/stackpack_package.go @@ -182,7 +182,7 @@ func RunStackpackPackageCommand(args *PackageArgs) func(cli *di.Deps, cmd *cobra if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "success": true, + successKey: true, "stackpack_name": stackpackInfo.Name, "stackpack_version": stackpackInfo.Version, "zip_file": args.ArchiveFile, diff --git a/cmd/stackpack/stackpack_package_test.go b/cmd/stackpack/stackpack_package_test.go index 773b89bb..a2b9cd74 100644 --- a/cmd/stackpack/stackpack_package_test.go +++ b/cmd/stackpack/stackpack_package_test.go @@ -12,6 +12,12 @@ import ( "github.com/stretchr/testify/require" ) +const ( + testMyStackpack = "my-stackpack" + missingManifestNameError = "name not found in stackpack.yaml" + missingManifestVersionError = "version not found in stackpack.yaml" +) + // setupStackPackPackageCmd creates a test command with mock dependencies func setupStackPackPackageCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { cli := di.NewMockDeps(t) @@ -52,9 +58,9 @@ func TestStackpackPackageCommand_DefaultBehavior(t *testing.T) { require.NoError(t, err) defer os.RemoveAll(tempDir) - stackpackDir := filepath.Join(tempDir, "test-stackpack") + stackpackDir := filepath.Join(tempDir, testStackPackName) require.NoError(t, os.MkdirAll(stackpackDir, 0755)) - createTestStackpack(t, stackpackDir, "test-stackpack", "1.0.0") + createTestStackpack(t, stackpackDir, testStackPackName, testInitialVersion) // Change to temp directory to test default current directory behavior originalWd, err := os.Getwd() @@ -93,9 +99,9 @@ func TestStackpackPackageCommand_CustomArchiveFile(t *testing.T) { require.NoError(t, err) defer os.RemoveAll(tempDir) - stackpackDir := filepath.Join(tempDir, "my-stackpack") + stackpackDir := filepath.Join(tempDir, testMyStackpack) require.NoError(t, os.MkdirAll(stackpackDir, 0755)) - createTestStackpack(t, stackpackDir, "my-stackpack", "2.1.0") + createTestStackpack(t, stackpackDir, testMyStackpack, "2.1.0") customZipPath := filepath.Join(tempDir, "custom-name.sts") cli, cmd := setupStackPackPackageCmd(t) @@ -118,9 +124,9 @@ func TestStackpackPackageCommand_ForceFlag(t *testing.T) { require.NoError(t, err) defer os.RemoveAll(tempDir) - stackpackDir := filepath.Join(tempDir, "test-stackpack") + stackpackDir := filepath.Join(tempDir, testStackPackName) require.NoError(t, os.MkdirAll(stackpackDir, 0755)) - createTestStackpack(t, stackpackDir, "test-stackpack", "1.0.0") + createTestStackpack(t, stackpackDir, testStackPackName, testInitialVersion) zipPath := filepath.Join(tempDir, "test-stackpack-1.0.0.sts") @@ -175,7 +181,7 @@ func TestStackpackPackageCommand_JSONOutput(t *testing.T) { jsonOutput := (*cli.MockPrinter.PrintJsonCalls)[0] // Check JSON structure - assert.Equal(t, true, jsonOutput["success"]) + assert.Equal(t, true, jsonOutput[successKey]) assert.Equal(t, "json-test", jsonOutput["stackpack_name"]) assert.Equal(t, "3.0.0", jsonOutput["stackpack_version"]) assert.Contains(t, jsonOutput["zip_file"], "json-test-3.0.0.sts") @@ -262,24 +268,24 @@ func TestStackpackPackageCommand_InvalidStackpackConf(t *testing.T) { { name: "missing name field", confContent: `version: "1.0.0"`, - expectedError: "name not found in stackpack.yaml", + expectedError: missingManifestNameError, }, { name: "missing version field", confContent: `name: "test"`, - expectedError: "version not found in stackpack.yaml", + expectedError: missingManifestVersionError, }, { name: "empty name field", confContent: `name: "" version: "1.0.0"`, - expectedError: "name not found in stackpack.yaml", + expectedError: missingManifestNameError, }, { name: "empty version field", confContent: `name: "test" version: ""`, - expectedError: "version not found in stackpack.yaml", + expectedError: missingManifestVersionError, }, } @@ -323,9 +329,9 @@ func TestStackpackPackageCommand_CreateOutputDirectory(t *testing.T) { require.NoError(t, err) defer os.RemoveAll(tempDir) - stackpackDir := filepath.Join(tempDir, "test-stackpack") + stackpackDir := filepath.Join(tempDir, testStackPackName) require.NoError(t, os.MkdirAll(stackpackDir, 0755)) - createTestStackpack(t, stackpackDir, "test-stackpack", "1.0.0") + createTestStackpack(t, stackpackDir, testStackPackName, testInitialVersion) // Create nested output directory path that doesn't exist outputDir := filepath.Join(tempDir, "output", "nested", "path") @@ -358,7 +364,7 @@ func TestYamlParser_Parse(t *testing.T) { name: "valid YAML with quotes", content: `name: "my-stackpack" version: "1.2.3"`, - expectedName: "my-stackpack", + expectedName: testMyStackpack, expectedVer: "1.2.3", expectError: false, }, @@ -366,7 +372,7 @@ version: "1.2.3"`, name: "valid YAML without quotes", content: `name: my-stackpack version: "1.2.3"`, - expectedName: "my-stackpack", + expectedName: testMyStackpack, expectedVer: "1.2.3", expectError: false, }, @@ -377,20 +383,20 @@ name: "test-app" # Another comment version: "2.0.0"`, expectedName: "test-app", - expectedVer: "2.0.0", + expectedVer: testMajorVersion, expectError: false, }, { name: "missing name", content: `version: "1.0.0"`, expectError: true, - errorContains: "name not found in stackpack.yaml", + errorContains: missingManifestNameError, }, { name: "missing version", content: `name: "test"`, expectError: true, - errorContains: "version not found in stackpack.yaml", + errorContains: missingManifestVersionError, }, { name: "invalid YAML syntax", diff --git a/cmd/stackpack/stackpack_scaffold.go b/cmd/stackpack/stackpack_scaffold.go index 90da66ad..d52f8e76 100644 --- a/cmd/stackpack/stackpack_scaffold.go +++ b/cmd/stackpack/stackpack_scaffold.go @@ -70,13 +70,13 @@ sts stackpack scaffold --template-github-repo stackvista/my-templates --name my- // Common flags cmd.Flags().StringVar(&args.DestinationDir, "destination-dir", "", "Target directory where scaffolded files will be created. If not specified, creates a directory with the stackpack name in the current working directory") - cmd.Flags().StringVar(&args.Name, "name", "", "Name of the stackpack (required). Must start with [a-z] and contain only lowercase letters, digits, and hyphens") + cmd.Flags().StringVar(&args.Name, NameFlag, "", "Name of the stackpack (required). Must start with [a-z] and contain only lowercase letters, digits, and hyphens") cmd.Flags().StringVar(&args.DisplayName, "display-name", "", "Name that's displayed on both the StackPack listing page and on the title of the StackPack page. If not provided, the value of --name will be used") cmd.Flags().StringVar(&args.TemplateName, "template-name", defaultTemplateName, fmt.Sprintf("Name of the template subdirectory to use (default: %s)", defaultTemplateName)) cmd.Flags().BoolVar(&args.Force, "force", false, "Overwrite existing files without prompting") // Mark required flags - cmd.MarkFlagRequired("name") //nolint:errcheck + cmd.MarkFlagRequired(NameFlag) //nolint:errcheck // Template sources are mutually exclusive but not required (will use default GitHub repo if none specified) stscobra.MarkMutexFlags(cmd, []string{"template-local-dir", "template-github-repo"}, "template-source", false) @@ -145,10 +145,10 @@ func RunStackpackScaffoldCommand(args *ScaffoldArgs) func(cli *di.Deps, cmd *cob if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "success": result.Success, + successKey: result.Success, "source": result.Source, "destination": result.Destination, - "name": result.Name, + NameFlag: result.Name, "template": result.Template, "files_count": result.FilesCount, "files": result.Files, diff --git a/cmd/stackpack/stackpack_scaffold_test.go b/cmd/stackpack/stackpack_scaffold_test.go index 91623a4f..59889381 100644 --- a/cmd/stackpack/stackpack_scaffold_test.go +++ b/cmd/stackpack/stackpack_scaffold_test.go @@ -12,6 +12,15 @@ import ( "github.com/stretchr/testify/require" ) +const ( + templateLocalDirFlagArg = "--template-local-dir" + testDefaultValue = "default-value" + templateNameFlagArg = "--template-name" + destinationDirFlagArg = "--destination-dir" + invalidNamePrefixError = "must start with a lowercase letter [a-z]" + invalidNameCharactersError = "lowercase letters, digits, and hyphens" +) + func setupStackpackScaffoldCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { cli := di.NewMockDeps(t) cmd := StackpackScaffoldCommand(&cli.Deps) @@ -33,7 +42,7 @@ func TestStackpackScaffoldCommand_RequiredFlags(t *testing.T) { }, { name: "valid minimal args with defaults", - args: []string{"--name", "test-stackpack"}, + args: []string{nameFlagArg, testStackPackName}, wantErr: false, }, } @@ -77,8 +86,8 @@ func TestStackpackScaffoldCommand_MutuallyExclusiveFlags(t *testing.T) { cli, cmd := setupStackpackScaffoldCmd(t) _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, - "--name", "test-stackpack", - "--template-local-dir", "./templates", + nameFlagArg, testStackPackName, + templateLocalDirFlagArg, "./templates", "--template-github-repo", "owner/repo", ) require.Error(t, err) @@ -167,19 +176,19 @@ func TestDefaultIfEmptyString(t *testing.T) { { name: "empty value returns default", value: "", - defaultValue: "default-value", - expected: "default-value", + defaultValue: testDefaultValue, + expected: testDefaultValue, }, { name: "non-empty value returns value", value: "custom-value", - defaultValue: "default-value", + defaultValue: testDefaultValue, expected: "custom-value", }, { name: "whitespace value returns whitespace", value: " ", - defaultValue: "default-value", + defaultValue: testDefaultValue, expected: " ", }, } @@ -200,7 +209,7 @@ func TestStackpackScaffoldCommand_LocalDirSource(t *testing.T) { // Create a mock template structure templateDir := filepath.Join(tempDir, "templates") - genericTemplateDir := filepath.Join(templateDir, "generic") + genericTemplateDir := filepath.Join(templateDir, defaultTemplateName) err = os.MkdirAll(genericTemplateDir, 0755) require.NoError(t, err) @@ -222,30 +231,30 @@ func TestStackpackScaffoldCommand_LocalDirSource(t *testing.T) { { name: "local directory source success", args: []string{ - "--name", "test-stackpack", - "--template-local-dir", templateDir, - "--template-name", "generic", - "--destination-dir", destDir, + nameFlagArg, testStackPackName, + templateLocalDirFlagArg, templateDir, + templateNameFlagArg, defaultTemplateName, + destinationDirFlagArg, destDir, }, wantErr: false, }, { name: "local directory source with non-existent template", args: []string{ - "--name", "test-stackpack", - "--template-local-dir", templateDir, - "--template-name", "non-existent", - "--destination-dir", destDir, + nameFlagArg, testStackPackName, + templateLocalDirFlagArg, templateDir, + templateNameFlagArg, "non-existent", + destinationDirFlagArg, destDir, }, wantErr: true, }, { name: "local directory source with non-existent directory", args: []string{ - "--name", "test-stackpack", - "--template-local-dir", "/non/existent/path", - "--template-name", "generic", - "--destination-dir", destDir, + nameFlagArg, testStackPackName, + templateLocalDirFlagArg, "/non/existent/path", + templateNameFlagArg, defaultTemplateName, + destinationDirFlagArg, destDir, }, wantErr: true, }, @@ -282,7 +291,7 @@ func TestStackpackScaffoldCommand_JSONOutput(t *testing.T) { // Create a mock template structure templateDir := filepath.Join(tempDir, "templates") - genericTemplateDir := filepath.Join(templateDir, "generic") + genericTemplateDir := filepath.Join(templateDir, defaultTemplateName) err = os.MkdirAll(genericTemplateDir, 0755) require.NoError(t, err) @@ -305,10 +314,10 @@ func TestStackpackScaffoldCommand_JSONOutput(t *testing.T) { { name: "regular text output", args: []string{ - "--name", "test-stackpack", - "--template-local-dir", templateDir, - "--template-name", "generic", - "--destination-dir", destDir, + nameFlagArg, testStackPackName, + templateLocalDirFlagArg, templateDir, + templateNameFlagArg, defaultTemplateName, + destinationDirFlagArg, destDir, }, expectJson: false, expectText: true, @@ -316,10 +325,10 @@ func TestStackpackScaffoldCommand_JSONOutput(t *testing.T) { { name: "JSON output", args: []string{ - "--name", "test-stackpack", - "--template-local-dir", templateDir, - "--template-name", "generic", - "--destination-dir", destDir, + nameFlagArg, testStackPackName, + templateLocalDirFlagArg, templateDir, + templateNameFlagArg, defaultTemplateName, + destinationDirFlagArg, destDir, "-o", "json", }, expectJson: true, @@ -339,7 +348,7 @@ func TestStackpackScaffoldCommand_JSONOutput(t *testing.T) { require.Len(t, *cli.MockPrinter.PrintJsonCalls, 1) jsonOutput := (*cli.MockPrinter.PrintJsonCalls)[0] // The JSON output should contain the scaffold result - assert.Contains(t, jsonOutput, "success") + assert.Contains(t, jsonOutput, successKey) // Verify no regular text calls were made for success messages assert.False(t, cli.MockPrinter.HasNonJsonCalls) @@ -367,7 +376,7 @@ func TestStackpackScaffoldCommand_ForceFlag(t *testing.T) { // Create a mock template structure templateDir := filepath.Join(tempDir, "templates") - genericTemplateDir := filepath.Join(templateDir, "generic") + genericTemplateDir := filepath.Join(templateDir, defaultTemplateName) err = os.MkdirAll(genericTemplateDir, 0755) require.NoError(t, err) @@ -389,10 +398,10 @@ func TestStackpackScaffoldCommand_ForceFlag(t *testing.T) { cli, cmd := setupStackpackScaffoldCmd(t) _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, - "--name", "test-stackpack", - "--template-local-dir", templateDir, - "--template-name", "generic", - "--destination-dir", destDir, + nameFlagArg, testStackPackName, + templateLocalDirFlagArg, templateDir, + templateNameFlagArg, defaultTemplateName, + destinationDirFlagArg, destDir, ) require.Error(t, err) assert.Contains(t, err.Error(), "conflicting files exist") @@ -402,10 +411,10 @@ func TestStackpackScaffoldCommand_ForceFlag(t *testing.T) { cli, cmd := setupStackpackScaffoldCmd(t) _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, - "--name", "test-stackpack", - "--template-local-dir", templateDir, - "--template-name", "generic", - "--destination-dir", destDir, + nameFlagArg, testStackPackName, + templateLocalDirFlagArg, templateDir, + templateNameFlagArg, defaultTemplateName, + destinationDirFlagArg, destDir, "--force", ) @@ -447,10 +456,10 @@ template: <<.TemplateName>> cli, cmd := setupStackpackScaffoldCmd(t) _, err = di.ExecuteCommandWithContext(&cli.Deps, cmd, - "--name", "my-awesome-stackpack", - "--template-local-dir", templateDir, - "--template-name", "custom-template", - "--destination-dir", destDir, + nameFlagArg, "my-awesome-stackpack", + templateLocalDirFlagArg, templateDir, + templateNameFlagArg, "custom-template", + destinationDirFlagArg, destDir, ) require.NoError(t, err) @@ -477,16 +486,16 @@ func TestRunStackpackScaffoldCommand_SourceSelection(t *testing.T) { name: "local directory source selected", args: ScaffoldArgs{ TemplateLocalDir: "/path/to/templates", - Name: "test-stackpack", - TemplateName: "generic", + Name: testStackPackName, + TemplateName: defaultTemplateName, }, expected: "local", }, { name: "github source selected with defaults", args: ScaffoldArgs{ - Name: "test-stackpack", - TemplateName: "generic", + Name: testStackPackName, + TemplateName: defaultTemplateName, }, expected: "github-default", }, @@ -494,8 +503,8 @@ func TestRunStackpackScaffoldCommand_SourceSelection(t *testing.T) { name: "github source selected with custom repo", args: ScaffoldArgs{ TemplateGitHubRepo: "custom/repo", - Name: "test-stackpack", - TemplateName: "generic", + Name: testStackPackName, + TemplateName: defaultTemplateName, }, expected: "github-custom", }, @@ -540,7 +549,7 @@ func TestDisplayNextSteps(t *testing.T) { cli := di.NewMockDeps(t) args := &ScaffoldArgs{ DestinationDir: "/path/to/destination", - Name: "test-stackpack", + Name: testStackPackName, } displayNextSteps(&cli.Deps, args) @@ -591,11 +600,11 @@ display_name: <<.DisplayName>> { name: "with display-name flag provided", args: []string{ - "--name", "my-stackpack", + nameFlagArg, testMyStackpack, "--display-name", "My Awesome StackPack", - "--template-local-dir", templateDir, - "--template-name", "custom-template", - "--destination-dir", destDir, + templateLocalDirFlagArg, templateDir, + templateNameFlagArg, "custom-template", + destinationDirFlagArg, destDir, }, expectedDisplayName: "My Awesome StackPack", description: "Should use provided display name", @@ -603,10 +612,10 @@ display_name: <<.DisplayName>> { name: "without display-name flag - should fallback to name", args: []string{ - "--name", "my-stackpack-fallback", - "--template-local-dir", templateDir, - "--template-name", "custom-template", - "--destination-dir", destDir, + nameFlagArg, "my-stackpack-fallback", + templateLocalDirFlagArg, templateDir, + templateNameFlagArg, "custom-template", + destinationDirFlagArg, destDir, }, expectedDisplayName: "my-stackpack-fallback", description: "Should fallback to name when display-name not provided", @@ -656,7 +665,7 @@ func TestValidateStackpackName(t *testing.T) { }, { name: "valid name with hyphens", - stackName: "my-stackpack", + stackName: testMyStackpack, wantErr: false, }, { @@ -674,83 +683,83 @@ func TestValidateStackpackName(t *testing.T) { name: "invalid starts with digit", stackName: "1-stackpack", wantErr: true, - errorSubstr: "must start with a lowercase letter [a-z]", + errorSubstr: invalidNamePrefixError, }, { name: "invalid starts with number", stackName: "2app", wantErr: true, - errorSubstr: "must start with a lowercase letter [a-z]", + errorSubstr: invalidNamePrefixError, }, // Invalid names - starts with hyphen { name: "invalid starts with hyphen", stackName: "-stackpack", wantErr: true, - errorSubstr: "must start with a lowercase letter [a-z]", + errorSubstr: invalidNamePrefixError, }, // Invalid names - uppercase letters { name: "invalid uppercase first letter", stackName: "My-Stackpack", wantErr: true, - errorSubstr: "must start with a lowercase letter [a-z]", + errorSubstr: invalidNamePrefixError, }, { name: "invalid camelCase", stackName: "myApp", wantErr: true, - errorSubstr: "lowercase letters, digits, and hyphens", + errorSubstr: invalidNameCharactersError, }, { name: "invalid all uppercase", stackName: "APP", wantErr: true, - errorSubstr: "must start with a lowercase letter [a-z]", + errorSubstr: invalidNamePrefixError, }, // Invalid names - spaces { name: "invalid with spaces", stackName: "my stackpack", wantErr: true, - errorSubstr: "lowercase letters, digits, and hyphens", + errorSubstr: invalidNameCharactersError, }, { name: "invalid app name with space", stackName: "app name", wantErr: true, - errorSubstr: "lowercase letters, digits, and hyphens", + errorSubstr: invalidNameCharactersError, }, // Invalid names - special characters { name: "invalid underscore", stackName: "my_stackpack", wantErr: true, - errorSubstr: "lowercase letters, digits, and hyphens", + errorSubstr: invalidNameCharactersError, }, { name: "invalid at symbol", stackName: "app@domain", wantErr: true, - errorSubstr: "lowercase letters, digits, and hyphens", + errorSubstr: invalidNameCharactersError, }, { name: "invalid dot", stackName: "stack.pack", wantErr: true, - errorSubstr: "lowercase letters, digits, and hyphens", + errorSubstr: invalidNameCharactersError, }, { name: "invalid slash", stackName: "my/app", wantErr: true, - errorSubstr: "lowercase letters, digits, and hyphens", + errorSubstr: invalidNameCharactersError, }, { name: "invalid colon", stackName: "app:v1", wantErr: true, - errorSubstr: "lowercase letters, digits, and hyphens", + errorSubstr: invalidNameCharactersError, }, } @@ -778,7 +787,7 @@ func TestStackpackScaffoldCommand_NameValidation(t *testing.T) { // Create a mock template structure templateDir := filepath.Join(tempDir, "templates") - genericTemplateDir := filepath.Join(templateDir, "generic") + genericTemplateDir := filepath.Join(templateDir, defaultTemplateName) err = os.MkdirAll(genericTemplateDir, 0755) require.NoError(t, err) @@ -801,51 +810,51 @@ func TestStackpackScaffoldCommand_NameValidation(t *testing.T) { { name: "valid name passes validation", args: []string{ - "--name", "my-stackpack", - "--template-local-dir", templateDir, - "--destination-dir", destDir, + nameFlagArg, testMyStackpack, + templateLocalDirFlagArg, templateDir, + destinationDirFlagArg, destDir, }, wantErr: false, }, { name: "invalid name with uppercase fails", args: []string{ - "--name", "My-Stackpack", - "--template-local-dir", templateDir, - "--destination-dir", destDir, + nameFlagArg, "My-Stackpack", + templateLocalDirFlagArg, templateDir, + destinationDirFlagArg, destDir, }, wantErr: true, - errorSubstr: "must start with a lowercase letter [a-z]", + errorSubstr: invalidNamePrefixError, }, { name: "invalid name with spaces fails", args: []string{ - "--name", "my stackpack", - "--template-local-dir", templateDir, - "--destination-dir", destDir, + nameFlagArg, "my stackpack", + templateLocalDirFlagArg, templateDir, + destinationDirFlagArg, destDir, }, wantErr: true, - errorSubstr: "lowercase letters, digits, and hyphens", + errorSubstr: invalidNameCharactersError, }, { name: "invalid name starting with number fails", args: []string{ - "--name", "1-app", - "--template-local-dir", templateDir, - "--destination-dir", destDir, + nameFlagArg, "1-app", + templateLocalDirFlagArg, templateDir, + destinationDirFlagArg, destDir, }, wantErr: true, - errorSubstr: "must start with a lowercase letter [a-z]", + errorSubstr: invalidNamePrefixError, }, { name: "invalid name with underscore fails", args: []string{ - "--name", "my_app", - "--template-local-dir", templateDir, - "--destination-dir", destDir, + nameFlagArg, "my_app", + templateLocalDirFlagArg, templateDir, + destinationDirFlagArg, destDir, }, wantErr: true, - errorSubstr: "lowercase letters, digits, and hyphens", + errorSubstr: invalidNameCharactersError, }, } diff --git a/cmd/stackpack/stackpack_test_deploy.go b/cmd/stackpack/stackpack_test_deploy.go index dd9ba478..7c616ea9 100644 --- a/cmd/stackpack/stackpack_test_deploy.go +++ b/cmd/stackpack/stackpack_test_deploy.go @@ -147,7 +147,7 @@ func RunStackpackTestDeployCommand(args *TestDeployArgs) di.CmdWithApiFn { } }() - tempStackpackDir := filepath.Join(tempDir, "stackpack") + tempStackpackDir := filepath.Join(tempDir, stackpackKey) if err := copyDirectory(args.StackpackDir, tempStackpackDir); err != nil { return common.NewRuntimeError(fmt.Errorf("failed to copy stackpack to temporary directory: %w", err)) } @@ -205,7 +205,7 @@ func RunStackpackTestDeployCommand(args *TestDeployArgs) di.CmdWithApiFn { if installedVersion != "" { upgradeArgs := &UpgradeArgs{ TypeName: originalInfo.Name, - UnlockedStrategy: "fail", + UnlockedStrategy: failKey, Wait: true, Timeout: DefaultTimeout, } @@ -217,7 +217,7 @@ func RunStackpackTestDeployCommand(args *TestDeployArgs) di.CmdWithApiFn { } else { installArgs := &InstallArgs{ Name: originalInfo.Name, - UnlockedStrategy: "fail", + UnlockedStrategy: failKey, Params: args.Params, Wait: true, Timeout: DefaultTimeout, @@ -237,8 +237,8 @@ func RunStackpackTestDeployCommand(args *TestDeployArgs) di.CmdWithApiFn { printMsg(cli, fmt.Sprintf("Note: Could not clean up .sts file %s: %v", packageArgs.ArchiveFile, err)) } else if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "stackpack": originalInfo.Name, - "version": newVersion, + stackpackKey: originalInfo.Name, + versionKey: newVersion, }) } diff --git a/cmd/stackpack/stackpack_test_deploy_test.go b/cmd/stackpack/stackpack_test_deploy_test.go index b832c7b5..96aa1e44 100644 --- a/cmd/stackpack/stackpack_test_deploy_test.go +++ b/cmd/stackpack/stackpack_test_deploy_test.go @@ -14,6 +14,11 @@ import ( "github.com/stretchr/testify/require" ) +const ( + testDeployVersion = "1.0.0-cli-test.1" + testUpgrade = "upgrade" +) + // setupStackpackTestDeployCmd creates a test command with mock dependencies func setupStackpackTestDeployCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { cli := di.NewMockDeps(t) @@ -54,12 +59,12 @@ func TestBumpSnapshotVersion(t *testing.T) { }{ { name: "first cli-test version", - currentVersion: "1.0.0", + currentVersion: testInitialVersion, expectedVersion: "1.0.0-cli-test.10000", }, { name: "increment existing cli-test", - currentVersion: "1.0.0-cli-test.1", + currentVersion: testDeployVersion, expectedVersion: "1.0.0-cli-test.2", }, { @@ -108,7 +113,7 @@ func TestUpdateVersionInYaml(t *testing.T) { defer os.RemoveAll(tempDir) configPath := filepath.Join(tempDir, "stackpack.yaml") - originalVersion := "2.0.0" + originalVersion := testMajorVersion newVersion := "2.0.0-cli-test.1" // Create config with original version @@ -126,7 +131,7 @@ displayName: "Test StackPack"`, originalVersion) updatedInfo, err := parser.Parse(configPath) require.NoError(t, err) assert.Equal(t, newVersion, updatedInfo.Version) - assert.Equal(t, "test-stackpack", updatedInfo.Name) + assert.Equal(t, testStackPackName, updatedInfo.Name) } func TestCopyDirectory(t *testing.T) { @@ -204,12 +209,12 @@ func TestStackpackTestDeployCommand_DirectoryHandling(t *testing.T) { require.NoError(t, err) defer os.RemoveAll(tempDir) - stackpackDir := filepath.Join(tempDir, "test-stackpack") + stackpackDir := filepath.Join(tempDir, testStackPackName) require.NoError(t, os.MkdirAll(stackpackDir, 0755)) // Create required files - stackpackName := "test-stackpack" - stackPackCurrentVersion := "1.0.0" + stackpackName := testStackPackName + stackPackCurrentVersion := testInitialVersion createTestStackpack(t, stackpackDir, stackpackName, stackPackCurrentVersion) stackpackTestArchive := fmt.Sprintf("%s-%s-cli-test.10000.sts", stackpackName, stackPackCurrentVersion) @@ -253,15 +258,15 @@ func TestVersionRegexPatterns(t *testing.T) { }{ { name: "regular version", - version: "1.0.0", + version: testInitialVersion, expectedBase: "", expectedNumber: 0, isSnapshot: false, }, { name: "first cli-test", - version: "1.0.0-cli-test.1", - expectedBase: "1.0.0", + version: testDeployVersion, + expectedBase: testInitialVersion, expectedNumber: 1, isSnapshot: true, }, @@ -275,7 +280,7 @@ func TestVersionRegexPatterns(t *testing.T) { { name: "complex base version", version: "1.0.0-beta.1.cli-test.3", - expectedBase: "1.0.0", + expectedBase: testInitialVersion, expectedNumber: 3, isSnapshot: true, }, @@ -340,32 +345,32 @@ func TestCompareVersionsSemver(t *testing.T) { }{ { name: "equal versions", - v1: "1.0.0", - v2: "1.0.0", + v1: testInitialVersion, + v2: testInitialVersion, expected: 0, }, { name: "v1 less than v2", - v1: "1.0.0", - v2: "1.1.0", + v1: testInitialVersion, + v2: testNextVersion, expected: -1, }, { name: "v1 greater than v2", - v1: "2.0.0", + v1: testMajorVersion, v2: "1.9.9", expected: 1, }, { name: "pre-release versions - cli-test comparison", - v1: "1.0.0-cli-test.1", + v1: testDeployVersion, v2: "1.0.0-cli-test.2", expected: -1, }, { name: "pre-release vs release", - v1: "1.0.0-cli-test.1", - v2: "1.0.0", + v1: testDeployVersion, + v2: testInitialVersion, expected: -1, }, { @@ -397,13 +402,13 @@ func TestStackpackTestDeployCommand_InstallUpgradeLogic(t *testing.T) { }, { name: "already installed - should upgrade", - installedVersion: "1.0.0", - expectedAction: "upgrade", + installedVersion: testInitialVersion, + expectedAction: testUpgrade, }, { name: "already installed with pre-release - should upgrade", installedVersion: "1.0.0-beta.1", - expectedAction: "upgrade", + expectedAction: testUpgrade, }, } @@ -416,7 +421,7 @@ func TestStackpackTestDeployCommand_InstallUpgradeLogic(t *testing.T) { shouldUpgrade = true } - if tt.expectedAction == "upgrade" { + if tt.expectedAction == testUpgrade { assert.True(t, shouldUpgrade, "Should choose upgrade when stackpack is already installed") } else { assert.False(t, shouldUpgrade, "Should choose install when stackpack is not installed") diff --git a/cmd/stackpack/stackpack_uninstall.go b/cmd/stackpack/stackpack_uninstall.go index 81de70e2..683459c9 100644 --- a/cmd/stackpack/stackpack_uninstall.go +++ b/cmd/stackpack/stackpack_uninstall.go @@ -44,8 +44,8 @@ func RunStackpackUninstallCommand(args *UninstallArgs) di.CmdWithApiFn { if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "success": true, - "result": result, + successKey: true, + "result": result, }) } else { cli.Printer.Success(fmt.Sprintf("Successfully uninstalled StackPack: name=%s id=%d", args.Name, args.Id)) diff --git a/cmd/stackpack/stackpack_uninstall_test.go b/cmd/stackpack/stackpack_uninstall_test.go index ce5e866a..e962a8a8 100644 --- a/cmd/stackpack/stackpack_uninstall_test.go +++ b/cmd/stackpack/stackpack_uninstall_test.go @@ -8,18 +8,22 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + testUninstallMessage = "Successfully uninstalled StackPack: name=zabbix id=39206337488300" +) + func setupStackpackUninstallFn(t *testing.T) (*di.MockDeps, *cobra.Command) { cli := di.NewMockDeps(t) cmd := StackpackUninstallCommand(&cli.Deps) - cli.MockClient.ApiMocks.StackpackApi.ProvisionUninstallResponse.Result = "Successfully uninstalled StackPack: name=zabbix id=39206337488300" + cli.MockClient.ApiMocks.StackpackApi.ProvisionUninstallResponse.Result = testUninstallMessage return &cli, cmd } func TestStackpackUninstallCommandPrintToConsole(t *testing.T) { cli, cmd := setupStackpackUninstallFn(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "uninstall", "--name", "zabbix", "--id", "39206337488300") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "uninstall", nameFlagArg, testZabbix, "--id", "39206337488300") - expectedSuccessMessage := []string{"Successfully uninstalled StackPack: name=zabbix id=39206337488300"} + expectedSuccessMessage := []string{testUninstallMessage} assert.True(t, cli.MockPrinter.HasNonJsonCalls) assert.Equal(t, expectedSuccessMessage, *cli.MockPrinter.SuccessCalls) @@ -27,11 +31,11 @@ func TestStackpackUninstallCommandPrintToConsole(t *testing.T) { func TestStackpackUninstallCommandPrintToJson(t *testing.T) { cli, cmd := setupStackpackUninstallFn(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "uninstall", "--name", "zabbix", "-i", "39206337488300", "-o", "json") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "uninstall", nameFlagArg, testZabbix, "-i", "39206337488300", "-o", "json") expectedJsonCalls := []map[string]interface{}{{ - "success": true, - "result": "Successfully uninstalled StackPack: name=zabbix id=39206337488300", + successKey: true, + "result": testUninstallMessage, }} assert.False(t, cli.MockPrinter.HasNonJsonCalls) diff --git a/cmd/stackpack/stackpack_upgrade.go b/cmd/stackpack/stackpack_upgrade.go index e504a71a..572931ff 100644 --- a/cmd/stackpack/stackpack_upgrade.go +++ b/cmd/stackpack/stackpack_upgrade.go @@ -14,7 +14,7 @@ import ( ) var ( - UnlockedStrategyChoices = []string{"fail", "skip", "overwrite"} + UnlockedStrategyChoices = []string{failKey, "skip", "overwrite"} ) type UpgradeArgs struct { @@ -40,7 +40,7 @@ sts stackpack upgrade --name kubernetes --wait`, common.AddRequiredNameFlagVar(cmd, &args.TypeName, "Name of the StackPack") pflags.EnumVar(cmd.Flags(), &args.UnlockedStrategy, UnlockedStrategyFlag, - "fail", + failKey, UnlockedStrategyChoices, "Strategy use to upgrade StackPack instance"+ fmt.Sprintf(" (must be { %s })", strings.Join(UnlockedStrategyChoices, " | ")), @@ -79,7 +79,7 @@ func RunStackpackUpgradeCommand(args *UpgradeArgs) di.CmdWithApiFn { } else { if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "success": true, + successKey: true, "current-version": stack.GetVersion(), "next-version": stack.NextVersion.GetVersion(), }) diff --git a/cmd/stackpack/stackpack_upgrade_test.go b/cmd/stackpack/stackpack_upgrade_test.go index b8e4f7dc..00f5374e 100644 --- a/cmd/stackpack/stackpack_upgrade_test.go +++ b/cmd/stackpack/stackpack_upgrade_test.go @@ -11,9 +11,9 @@ import ( ) var ( - stackPackName = "zabbix" - stackPackNextVersion = "2.0.0" - stackPackCurrentVersion = "1.0.0" + stackPackName = testZabbix + stackPackNextVersion = testMajorVersion + stackPackCurrentVersion = testInitialVersion strategyFlag = "overwrite" ) @@ -35,13 +35,13 @@ func setupStackPackUpgradeCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { func TestStackpackUpgradePrintToTable(t *testing.T) { cli, cmd := setupStackPackUpgradeCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "upgrade", "--name", "zabbix", + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, testUpgrade, nameFlagArg, testZabbix, "--unlocked-strategy", strategyFlag, ) assert.Equal(t, []stackstate_api.UpgradeStackPackCall{{ - PstackPackName: "zabbix", + PstackPackName: testZabbix, Punlocked: &strategyFlag, }}, *cli.MockClient.ApiMocks.StackpackApi.UpgradeStackPackCalls) @@ -51,19 +51,19 @@ func TestStackpackUpgradePrintToTable(t *testing.T) { func TestStackpackUpgradePrintToJson(t *testing.T) { cli, cmd := setupStackPackUpgradeCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "upgrade", "--name", "zabbix", + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, testUpgrade, nameFlagArg, testZabbix, "--unlocked-strategy", strategyFlag, "-o", "json", ) assert.Equal(t, []stackstate_api.UpgradeStackPackCall{{ - PstackPackName: "zabbix", + PstackPackName: testZabbix, Punlocked: &strategyFlag, }}, *cli.MockClient.ApiMocks.StackpackApi.UpgradeStackPackCalls) expectedJsonCalls := []map[string]interface{}{{ - "success": true, + successKey: true, "current-version": stackPackCurrentVersion, "next-version": stackPackNextVersion, }} @@ -72,12 +72,12 @@ func TestStackpackUpgradePrintToJson(t *testing.T) { func TestStackpackUpgradeDefaultsUnlockedStrategy(t *testing.T) { cli, cmd := setupStackPackUpgradeCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "upgrade", "--name", "zabbix") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, testUpgrade, nameFlagArg, testZabbix) defaultStrategy := "fail" assert.Equal(t, []stackstate_api.UpgradeStackPackCall{{ - PstackPackName: "zabbix", + PstackPackName: testZabbix, Punlocked: &defaultStrategy, }}, *cli.MockClient.ApiMocks.StackpackApi.UpgradeStackPackCalls) @@ -132,8 +132,8 @@ func TestStackpackUpgradeWithWaitTimeout(t *testing.T) { cli.MockClient.ApiMocks.StackpackApi.StackPackListResponse.Result = []stackstate_api.FullStackPack{provisioningStackPack} cli.MockClient.ApiMocks.StackpackApi.UpgradeStackPackResponse.Result = successfulResponseResult - _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "upgrade", "--name", stackPackName, - "--unlocked-strategy", strategyFlag, "--wait", "--timeout", "50ms") + _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, testUpgrade, nameFlagArg, stackPackName, + "--unlocked-strategy", strategyFlag, testWait, timeoutFlagArg, "50ms") // Should return timeout error assert.Error(t, err) @@ -145,7 +145,7 @@ func TestStackpackUpgradeWithWaitJsonFlags(t *testing.T) { cmd := StackpackUpgradeCommand(&cli.Deps) // Test that wait and timeout flags can be parsed - err := cmd.ParseFlags([]string{"--name", "test", "--wait", "--timeout", "100ms"}) + err := cmd.ParseFlags([]string{nameFlagArg, testUploadName, testWait, timeoutFlagArg, "100ms"}) assert.NoError(t, err) // Verify flag values @@ -157,7 +157,7 @@ func TestStackpackUpgradeWithWaitJsonFlags(t *testing.T) { assert.NoError(t, err) assert.Equal(t, 100*time.Millisecond, timeoutValue) - nameValue, err := cmd.Flags().GetString("name") + nameValue, err := cmd.Flags().GetString(NameFlag) assert.NoError(t, err) - assert.Equal(t, "test", nameValue) + assert.Equal(t, testUploadName, nameValue) } diff --git a/cmd/stackpack/stackpack_upload.go b/cmd/stackpack/stackpack_upload.go index 0731642d..4f10782f 100644 --- a/cmd/stackpack/stackpack_upload.go +++ b/cmd/stackpack/stackpack_upload.go @@ -55,7 +55,7 @@ func RunStackpackUploadCommand(args *UploadArgs) di.CmdWithApiFn { } else { cli.Printer.Success(fmt.Sprintf("uploaded StackPack: %s", args.FilePath)) cli.Printer.Table(printer.TableData{ - Header: []string{"name", "display name", "version"}, + Header: []string{NameFlag, displayNameColumn, versionKey}, Data: [][]interface{}{{stackpack.Name, stackpack.DisplayName, stackpack.Version}}, }) } diff --git a/cmd/stackpack/stackpack_upload_test.go b/cmd/stackpack/stackpack_upload_test.go index 2ac8d7fc..0f593858 100644 --- a/cmd/stackpack/stackpack_upload_test.go +++ b/cmd/stackpack/stackpack_upload_test.go @@ -11,6 +11,10 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + testDisplayTest = "display test" +) + func setupStackPackUploadCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { cli := di.NewMockDeps(t) cmd := StackpackUploadCommand(&cli.Deps) @@ -33,9 +37,9 @@ func TestUploadStackPackPrintsToTable(t *testing.T) { cli, cmd := setupStackPackUploadCmd(t) file := createTempFile() - name := "test" - displayName := "display test" - version := "1.0.0" + name := testUploadName + displayName := testDisplayTest + version := testInitialVersion stackpack := sts.StackPack{ Name: name, DisplayName: displayName, @@ -47,8 +51,8 @@ func TestUploadStackPackPrintsToTable(t *testing.T) { expectedTableCall := []printer.TableData{ { - Header: []string{"name", "display name", "version"}, - Data: [][]interface{}{{"test", "display test", "1.0.0"}}, + Header: []string{NameFlag, displayNameColumn, versionKey}, + Data: [][]interface{}{{testUploadName, testDisplayTest, testInitialVersion}}, }, } @@ -60,9 +64,9 @@ func TestUploadStackPackPrintToJson(t *testing.T) { file := createTempFile() stackpack := &sts.StackPack{ - Name: "test", - DisplayName: "display test", - Version: "1.0.0", + Name: testUploadName, + DisplayName: testDisplayTest, + Version: testInitialVersion, } cli.MockClient.ApiMocks.StackpackApi.StackPackUploadResponse.Result = *stackpack diff --git a/cmd/stackpack/stackpack_validate.go b/cmd/stackpack/stackpack_validate.go index 5924c398..58c9ff13 100644 --- a/cmd/stackpack/stackpack_validate.go +++ b/cmd/stackpack/stackpack_validate.go @@ -84,8 +84,8 @@ func RunStackpackValidateCommand(args *ValidateArgs) di.CmdWithApiFn { if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "success": true, - "result": result, + successKey: true, + "result": result, }) } else { cli.Printer.Success("Stackpack validation successful!") diff --git a/cmd/stackpack/stackpack_validate_test.go b/cmd/stackpack/stackpack_validate_test.go index f65bdbd0..f7269020 100644 --- a/cmd/stackpack/stackpack_validate_test.go +++ b/cmd/stackpack/stackpack_validate_test.go @@ -57,9 +57,9 @@ func TestValidate_WithDirectory_AutoPackages(t *testing.T) { require.NoError(t, err) defer os.RemoveAll(tempDir) - stackpackDir := filepath.Join(tempDir, "test-stackpack") + stackpackDir := filepath.Join(tempDir, testStackPackName) require.NoError(t, os.MkdirAll(stackpackDir, 0755)) - createTestStackpackDir(t, stackpackDir, "test-stackpack", "1.0.0") + createTestStackpackDir(t, stackpackDir, testStackPackName, testInitialVersion) _, err = di.ExecuteCommandWithContext(&cli.Deps, cmd, "--directory", stackpackDir) require.NoError(t, err) @@ -93,10 +93,10 @@ func TestValidate_WithDirectory_MissingStackpackYaml(t *testing.T) { require.NoError(t, err) defer os.RemoveAll(tempDir) - stackpackDir := filepath.Join(tempDir, "test-stackpack") + stackpackDir := filepath.Join(tempDir, testStackPackName) require.NoError(t, os.MkdirAll(filepath.Join(stackpackDir, "settings"), 0755)) require.NoError(t, os.MkdirAll(filepath.Join(stackpackDir, "resources"), 0755)) - require.NoError(t, os.WriteFile(filepath.Join(stackpackDir, "README.md"), []byte("test"), 0644)) + require.NoError(t, os.WriteFile(filepath.Join(stackpackDir, "README.md"), []byte(testUploadName), 0644)) _, err = di.ExecuteCommandWithContext(&cli.Deps, cmd, "--directory", stackpackDir) require.Error(t, err) @@ -140,7 +140,7 @@ func TestValidate_JSONOutput(t *testing.T) { require.Len(t, *cli.MockPrinter.PrintJsonCalls, 1) jsonOutput := (*cli.MockPrinter.PrintJsonCalls)[0] - assert.Equal(t, true, jsonOutput["success"]) + assert.Equal(t, true, jsonOutput[successKey]) } func TestValidate_MissingPath(t *testing.T) { @@ -162,7 +162,7 @@ func TestValidate_MutuallyExclusive(t *testing.T) { require.NoError(t, os.MkdirAll(stackpackDir, 0755)) stackpackFile := filepath.Join(tempDir, "test.sts") - require.NoError(t, os.WriteFile(stackpackFile, []byte("test"), 0644)) + require.NoError(t, os.WriteFile(stackpackFile, []byte(testUploadName), 0644)) _, err = di.ExecuteCommandWithContext(&cli.Deps, cmd, "-d", stackpackDir, @@ -186,9 +186,9 @@ func TestValidate_WithDirectory_IncludingOptionalItems(t *testing.T) { require.NoError(t, err) defer os.RemoveAll(tempDir) - stackpackDir := filepath.Join(tempDir, "test-stackpack") + stackpackDir := filepath.Join(tempDir, testStackPackName) require.NoError(t, os.MkdirAll(stackpackDir, 0755)) - createTestStackpackDir(t, stackpackDir, "test-stackpack", "1.0.0") + createTestStackpackDir(t, stackpackDir, testStackPackName, testInitialVersion) // Add optional items require.NoError(t, os.MkdirAll(filepath.Join(stackpackDir, "icons"), 0755)) diff --git a/cmd/topic/topic_describe_test.go b/cmd/topic/topic_describe_test.go index 11e337f8..1993f579 100644 --- a/cmd/topic/topic_describe_test.go +++ b/cmd/topic/topic_describe_test.go @@ -12,6 +12,10 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + messagesKey = "messages" +) + var ( MessageContents = map[string]interface{}{"test": "value"} MessageContentsJson = "{\"test\":\"value\"}" @@ -61,7 +65,7 @@ func TestTopicDescribeJson(t *testing.T) { expectedJson := []map[string]interface{}{ { - "messages": Part0MessagesList, + messagesKey: Part0MessagesList, }, } @@ -86,7 +90,7 @@ func TestTopicDescribeTable(t *testing.T) { {Message2.Key, Message2.Partition, Message2.Offset, MessageContentsJson}, {Message3.Key, Message3.Partition, Message3.Offset, MessageContentsJson}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: "messages"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: messagesKey}, }, } @@ -114,7 +118,7 @@ func TestTopicDescribeTableSorting(t *testing.T) { {Message4.Key, Message4.Partition, Message4.Offset, MessageContentsJson}, {Message5.Key, Message5.Partition, Message5.Offset, MessageContentsJson}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: "messages"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: messagesKey}, }, } @@ -225,7 +229,7 @@ func TestTopicDescribeMoreThanAvailable(t *testing.T) { expectedJson := []map[string]interface{}{ { - "messages": AllMessagesListSorted, + messagesKey: AllMessagesListSorted, }, } diff --git a/cmd/topology/topology_inspect.go b/cmd/topology/topology_inspect.go index 46979240..21ffd87a 100644 --- a/cmd/topology/topology_inspect.go +++ b/cmd/topology/topology_inspect.go @@ -13,6 +13,13 @@ import ( "github.com/stackvista/stackstate-cli/internal/printer" ) +const ( + identifierKey = "identifier" + componentsKey = "components" + viewSnapshotType = "ViewSnapshot" + nameKey = "name" +) + const UNKNOWN = "unknown" type InspectArgs struct { @@ -56,7 +63,7 @@ sts topology inspect --type "otel service instance" -o json`, cmd.Flags().StringVar(&args.ComponentType, "type", "", "Component type (required)") cmd.MarkFlagRequired("type") //nolint:errcheck cmd.Flags().StringSliceVar(&args.Tags, "tag", []string{}, "Filter by tags in format 'tag-name:tag-value' (multiple allowed, ANDed together)") - cmd.Flags().StringSliceVar(&args.Identifiers, "identifier", []string{}, "Filter by component identifiers (multiple allowed, ANDed together)") + cmd.Flags().StringSliceVar(&args.Identifiers, identifierKey, []string{}, "Filter by component identifiers (multiple allowed, ANDed together)") cmd.Flags().IntVar(&args.Limit, "limit", 0, "Maximum number of components to output (must be positive)") return cmd @@ -118,7 +125,7 @@ func RunInspectCommand( if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "components": components, + componentsKey: components, }) return nil } else { @@ -231,7 +238,7 @@ func parseSnapshotResponse( // Note: the `View` prefix on response type comes from the existing (Scala) DTO types // If it's not a ViewSnapshot, it's an error type - return empty components and let error handler deal with it - if respType != "ViewSnapshot" { + if respType != viewSnapshotType { return nil, fmt.Errorf("response is an error type: %s", respType) } @@ -239,7 +246,7 @@ func parseSnapshotResponse( // Parse components from the already-unmarshalled components field var components []Component - if componentsSlice, ok := respMap["components"].([]interface{}); ok { + if componentsSlice, ok := respMap[componentsKey].([]interface{}); ok { for _, comp := range componentsSlice { if compMap, ok := comp.(map[string]interface{}); ok { components = append(components, parseComponentFromMap(compMap, metadata, baseURL)) @@ -300,8 +307,8 @@ func parseMetadataByIdentifier(metadataValue interface{}) map[string]string { for _, item := range items { if itemMap, ok := item.(map[string]interface{}); ok { - identifier, idOk := itemMap["identifier"].(string) - name, nameOk := itemMap["name"].(string) + identifier, idOk := itemMap[identifierKey].(string) + name, nameOk := itemMap[nameKey].(string) if idOk && nameOk { result[identifier] = name } @@ -322,7 +329,7 @@ func parseComponentFromMap(compMap map[string]interface{}, metadata ComponentMet if id, ok := compMap["id"].(float64); ok { comp.ID = int64(id) } - if name, ok := compMap["name"].(string); ok { + if name, ok := compMap[nameKey].(string); ok { comp.Name = name } @@ -380,8 +387,8 @@ func parseComponentReference(compMap map[string]interface{}, identifierFieldName refName = name } return map[string]interface{}{ - "identifier": refIdentifier, - "name": refName, + identifierKey: refIdentifier, + nameKey: refName, } } return nil @@ -409,6 +416,6 @@ func printTableOutput( cli.Printer.Table(printer.TableData{ Header: []string{"Name", "Type", "Identifiers"}, Data: tableData, - MissingTableDataMsg: printer.NotFoundMsg{Types: "components"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: componentsKey}, }) } diff --git a/cmd/topology/topology_inspect_test.go b/cmd/topology/topology_inspect_test.go index 62d40503..1e5b5353 100644 --- a/cmd/topology/topology_inspect_test.go +++ b/cmd/topology/topology_inspect_test.go @@ -10,6 +10,20 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + typeColumn = "Type" +) + +const ( + testName = "Name" + testTypeKey = "_type" + identifiersColumn = "Identifiers" + querySnapshotResultType = "QuerySnapshotResult" + testMetadata = "metadata" + testComponentTypes = "componentTypes" + testIdentifiers = "identifiers" +) + const baseURL = "https://suse-observability-instance.com" func setInspectCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { @@ -35,7 +49,7 @@ func TestTopologyInspectJson(t *testing.T) { jsonData := jsonCalls[0] // Components are serialized from []Component struct - assert.NotNil(t, jsonData["components"]) + assert.NotNil(t, jsonData[componentsKey]) assert.True(t, len(calls) > 0, "API should have been called") } @@ -56,7 +70,7 @@ func TestTopologyInspectTable(t *testing.T) { assert.Len(t, tableCalls, 1) table := tableCalls[0] - assert.Equal(t, []string{"Name", "Type", "Identifiers"}, table.Header) + assert.Equal(t, []string{testName, typeColumn, identifiersColumn}, table.Header) assert.Len(t, table.Data, 1) row := table.Data[0] @@ -108,14 +122,14 @@ func TestTopologyInspectWithIdentifiers(t *testing.T) { func TestTopologyInspectNoResults(t *testing.T) { cli, cmd := setInspectCmd(t) cli.MockClient.ApiMocks.SnapshotApi.QuerySnapshotResponse.Result = sts.QuerySnapshotResult{ - Type: "QuerySnapshotResult", + Type: querySnapshotResultType, ViewSnapshotResponse: map[string]interface{}{ - "_type": "ViewSnapshot", - "components": []interface{}{}, - "metadata": map[string]interface{}{ - "componentTypes": []interface{}{}, - "layers": []interface{}{}, - "domains": []interface{}{}, + testTypeKey: viewSnapshotType, + componentsKey: []interface{}{}, + testMetadata: map[string]interface{}{ + testComponentTypes: []interface{}{}, + "layers": []interface{}{}, + "domains": []interface{}{}, }, }, } @@ -128,18 +142,18 @@ func TestTopologyInspectNoResults(t *testing.T) { assert.Len(t, tableCalls, 1) table := tableCalls[0] - assert.Equal(t, []string{"Name", "Type", "Identifiers"}, table.Header) + assert.Equal(t, []string{testName, typeColumn, identifiersColumn}, table.Header) assert.Len(t, table.Data, 0) - assert.Equal(t, printer.NotFoundMsg{Types: "components"}, table.MissingTableDataMsg) + assert.Equal(t, printer.NotFoundMsg{Types: componentsKey}, table.MissingTableDataMsg) } func TestTopologyInspectMultipleIdentifiers(t *testing.T) { cli, cmd := setInspectCmd(t) responseData := mockSnapshotResponse() // Modify to include multiple identifiers - components := responseData.ViewSnapshotResponse["components"].([]interface{}) + components := responseData.ViewSnapshotResponse[componentsKey].([]interface{}) comp := components[0].(map[string]interface{}) - comp["identifiers"] = []interface{}{"urn:test:1", "urn:test:2", "urn:test:3"} + comp[testIdentifiers] = []interface{}{"urn:test:1", "urn:test:2", "urn:test:3"} cli.MockClient.ApiMocks.SnapshotApi.QuerySnapshotResponse.Result = responseData cli.CurrentContext.URL = baseURL @@ -158,9 +172,9 @@ func TestTopologyInspectURLEncoding(t *testing.T) { cli, cmd := setInspectCmd(t) responseData := mockSnapshotResponse() // Set identifier with special characters - components := responseData.ViewSnapshotResponse["components"].([]interface{}) + components := responseData.ViewSnapshotResponse[componentsKey].([]interface{}) comp := components[0].(map[string]interface{}) - comp["identifiers"] = []interface{}{"urn:opentelemetry:namespace/service:component/name"} + comp[testIdentifiers] = []interface{}{"urn:opentelemetry:namespace/service:component/name"} cli.MockClient.ApiMocks.SnapshotApi.QuerySnapshotResponse.Result = responseData cli.CurrentContext.URL = baseURL @@ -168,7 +182,7 @@ func TestTopologyInspectURLEncoding(t *testing.T) { // Verify URL encoding in link jsonCalls := *cli.MockPrinter.PrintJsonCalls - returnedComponents := jsonCalls[0]["components"].([]Component) + returnedComponents := jsonCalls[0][componentsKey].([]Component) // url.PathEscape encodes / to %2F, but : is not encoded, and base URL is prefixed expectedLink := baseURL + "/#/components/urn:opentelemetry:namespace%2Fservice:component%2Fname" assert.Equal(t, expectedLink, returnedComponents[0].Link) @@ -178,15 +192,15 @@ func TestTopologyInspectWithEnvironment(t *testing.T) { cli, cmd := setInspectCmd(t) responseData := mockSnapshotResponse() // Add environment to component - components := responseData.ViewSnapshotResponse["components"].([]interface{}) + components := responseData.ViewSnapshotResponse[componentsKey].([]interface{}) comp := components[0].(map[string]interface{}) comp["environment"] = float64(123) // Add environment to metadata - metadata := responseData.ViewSnapshotResponse["metadata"].(map[string]interface{}) + metadata := responseData.ViewSnapshotResponse[testMetadata].(map[string]interface{}) metadata["environments"] = []interface{}{ map[string]interface{}{ - "id": float64(123), - "name": "Production", + "id": float64(123), + nameKey: "Production", }, } cli.MockClient.ApiMocks.SnapshotApi.QuerySnapshotResponse.Result = responseData @@ -198,7 +212,7 @@ func TestTopologyInspectWithEnvironment(t *testing.T) { jsonCalls := *cli.MockPrinter.PrintJsonCalls assert.Len(t, jsonCalls, 1) jsonData := jsonCalls[0] - assert.NotNil(t, jsonData["components"]) + assert.NotNil(t, jsonData[componentsKey]) } func TestTopologyInspectTypeRequired(t *testing.T) { @@ -240,7 +254,7 @@ func TestTopologyInspectWithBaseURL(t *testing.T) { jsonData := jsonCalls[0] // Components are serialized from []Component struct - components := jsonData["components"].([]Component) + components := jsonData[componentsKey].([]Component) assert.NotNil(t, components) expectedLink := "https://stackstate.example.com:8080/#/components/urn:test:component:1" @@ -250,9 +264,9 @@ func TestTopologyInspectWithBaseURL(t *testing.T) { func TestTopologyInspectFetchTimeout(t *testing.T) { cli, cmd := setInspectCmd(t) cli.MockClient.ApiMocks.SnapshotApi.QuerySnapshotResponse.Result = sts.QuerySnapshotResult{ - Type: "QuerySnapshotResult", + Type: querySnapshotResultType, ViewSnapshotResponse: map[string]interface{}{ - "_type": "ViewSnapshotFetchTimeout", + testTypeKey: "ViewSnapshotFetchTimeout", "usedTimeoutSeconds": float64(30), }, } @@ -268,9 +282,9 @@ func TestTopologyInspectFetchTimeout(t *testing.T) { func TestTopologyInspectTooManyActiveQueries(t *testing.T) { cli, cmd := setInspectCmd(t) cli.MockClient.ApiMocks.SnapshotApi.QuerySnapshotResponse.Result = sts.QuerySnapshotResult{ - Type: "QuerySnapshotResult", + Type: querySnapshotResultType, ViewSnapshotResponse: map[string]interface{}{ - "_type": "ViewSnapshotTooManyActiveQueries", + testTypeKey: "ViewSnapshotTooManyActiveQueries", }, } cli.CurrentContext.URL = baseURL @@ -285,10 +299,10 @@ func TestTopologyInspectTooManyActiveQueries(t *testing.T) { func TestTopologyInspectTopologySizeOverflow(t *testing.T) { cli, cmd := setInspectCmd(t) cli.MockClient.ApiMocks.SnapshotApi.QuerySnapshotResponse.Result = sts.QuerySnapshotResult{ - Type: "QuerySnapshotResult", + Type: querySnapshotResultType, ViewSnapshotResponse: map[string]interface{}{ - "_type": "ViewSnapshotTopologySizeOverflow", - "maxSize": float64(10000), + testTypeKey: "ViewSnapshotTopologySizeOverflow", + "maxSize": float64(10000), }, } cli.CurrentContext.URL = baseURL @@ -303,9 +317,9 @@ func TestTopologyInspectTopologySizeOverflow(t *testing.T) { func TestTopologyInspectDataUnavailable(t *testing.T) { cli, cmd := setInspectCmd(t) cli.MockClient.ApiMocks.SnapshotApi.QuerySnapshotResponse.Result = sts.QuerySnapshotResult{ - Type: "QuerySnapshotResult", + Type: querySnapshotResultType, ViewSnapshotResponse: map[string]interface{}{ - "_type": "ViewSnapshotDataUnavailable", + testTypeKey: "ViewSnapshotDataUnavailable", "unavailableAtEpochMs": float64(1000000), "availableSinceEpochMs": float64(1609459200000), }, diff --git a/cmd/topology/topology_state.go b/cmd/topology/topology_state.go index dcda10f6..3ef74452 100644 --- a/cmd/topology/topology_state.go +++ b/cmd/topology/topology_state.go @@ -51,7 +51,7 @@ sts topology state --type "otel service instance" -o json`, cmd.Flags().StringVar(&args.ComponentType, "type", "", "Component type") cmd.Flags().StringSliceVar(&args.Tags, "tag", []string{}, "Filter by tags in format 'tag-name:tag-value' (multiple allowed, ANDed together)") - cmd.Flags().StringSliceVar(&args.Identifiers, "identifier", []string{}, "Filter by component identifiers (multiple allowed, ANDed together)") + cmd.Flags().StringSliceVar(&args.Identifiers, identifierKey, []string{}, "Filter by component identifiers (multiple allowed, ANDed together)") cmd.Flags().IntVar(&args.Limit, "limit", 0, "Maximum number of components to output (must be positive)") return cmd @@ -111,7 +111,7 @@ func RunStateCommand( if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "components": componentStates, + componentsKey: componentStates, }) return nil } else { @@ -141,14 +141,14 @@ func parseStateResponse(result *stackstate_api.QuerySnapshotResult) ([]Component return nil, fmt.Errorf("response has no _type discriminator") } - if respType != "ViewSnapshot" { + if respType != viewSnapshotType { return nil, fmt.Errorf("response is an error type: %s", respType) } metadata := parseMetadata(respMap) var componentStates []ComponentState - if componentsSlice, ok := respMap["components"].([]interface{}); ok { + if componentsSlice, ok := respMap[componentsKey].([]interface{}); ok { for _, comp := range componentsSlice { if compMap, ok := comp.(map[string]interface{}); ok { componentStates = append(componentStates, parseComponentStateFromMap(compMap, metadata)) @@ -169,7 +169,7 @@ func parseComponentStateFromMap(compMap map[string]interface{}, metadata Compone if id, ok := compMap["id"].(float64); ok { cs.ID = int64(id) } - if name, ok := compMap["name"].(string); ok { + if name, ok := compMap[nameKey].(string); ok { cs.Name = name } @@ -216,6 +216,6 @@ func printStateTableOutput(cli *di.Deps, componentStates []ComponentState) { cli.Printer.Table(printer.TableData{ Header: []string{"Name", "Type", "Health State", "Identifiers"}, Data: tableData, - MissingTableDataMsg: printer.NotFoundMsg{Types: "components"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: componentsKey}, }) } diff --git a/cmd/topology/topology_state_test.go b/cmd/topology/topology_state_test.go index dec8ef46..a731fd8e 100644 --- a/cmd/topology/topology_state_test.go +++ b/cmd/topology/topology_state_test.go @@ -10,6 +10,12 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + testType = "type" + testState = "state" + testHealthState = "healthState" +) + func setStateCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { cli := di.NewMockDeps(t) cmd := StateCommand(&cli.Deps) @@ -31,10 +37,10 @@ func TestTopologyStateJson(t *testing.T) { assert.Len(t, jsonCalls, 1) jsonData := jsonCalls[0] - assert.NotNil(t, jsonData["components"]) + assert.NotNil(t, jsonData[componentsKey]) // Check the component has the health state - components := jsonData["components"].([]ComponentState) + components := jsonData[componentsKey].([]ComponentState) assert.Len(t, components, 1) assert.Equal(t, "CRITICAL", components[0].HealthState) } @@ -54,7 +60,7 @@ func TestTopologyStateTable(t *testing.T) { assert.Len(t, tableCalls, 1) table := tableCalls[0] - assert.Equal(t, []string{"Name", "Type", "Health State", "Identifiers"}, table.Header) + assert.Equal(t, []string{testName, typeColumn, "Health State", identifiersColumn}, table.Header) assert.Len(t, table.Data, 1) row := table.Data[0] @@ -105,14 +111,14 @@ func TestTopologyStateWithIdentifiers(t *testing.T) { func TestTopologyStateNoResults(t *testing.T) { cli, cmd := setStateCmd(t) cli.MockClient.ApiMocks.SnapshotApi.QuerySnapshotResponse.Result = sts.QuerySnapshotResult{ - Type: "QuerySnapshotResult", + Type: querySnapshotResultType, ViewSnapshotResponse: map[string]interface{}{ - "_type": "ViewSnapshot", - "components": []interface{}{}, - "metadata": map[string]interface{}{ - "componentTypes": []interface{}{}, - "layers": []interface{}{}, - "domains": []interface{}{}, + testTypeKey: viewSnapshotType, + componentsKey: []interface{}{}, + testMetadata: map[string]interface{}{ + testComponentTypes: []interface{}{}, + "layers": []interface{}{}, + "domains": []interface{}{}, }, }, } @@ -124,32 +130,32 @@ func TestTopologyStateNoResults(t *testing.T) { assert.Len(t, tableCalls, 1) table := tableCalls[0] - assert.Equal(t, []string{"Name", "Type", "Health State", "Identifiers"}, table.Header) + assert.Equal(t, []string{testName, typeColumn, "Health State", identifiersColumn}, table.Header) assert.Len(t, table.Data, 0) - assert.Equal(t, printer.NotFoundMsg{Types: "components"}, table.MissingTableDataMsg) + assert.Equal(t, printer.NotFoundMsg{Types: componentsKey}, table.MissingTableDataMsg) } func TestTopologyStateDefaultsToUnknown(t *testing.T) { cli, cmd := setStateCmd(t) // Response without state field cli.MockClient.ApiMocks.SnapshotApi.QuerySnapshotResponse.Result = sts.QuerySnapshotResult{ - Type: "QuerySnapshotResult", + Type: querySnapshotResultType, ViewSnapshotResponse: map[string]interface{}{ - "_type": "ViewSnapshot", - "components": []interface{}{ + testTypeKey: viewSnapshotType, + componentsKey: []interface{}{ map[string]interface{}{ - "id": float64(229404307680647), - "name": "test-component", - "type": float64(239975151751041), - "identifiers": []interface{}{"urn:test:component:1"}, + "id": float64(229404307680647), + nameKey: "test-component", + testType: float64(239975151751041), + testIdentifiers: []interface{}{"urn:test:component:1"}, // No state field }, }, - "metadata": map[string]interface{}{ - "componentTypes": []interface{}{ + testMetadata: map[string]interface{}{ + testComponentTypes: []interface{}{ map[string]interface{}{ - "id": float64(239975151751041), - "name": "test type", + "id": float64(239975151751041), + nameKey: "test type", }, }, }, @@ -169,43 +175,43 @@ func TestTopologyStateDefaultsToUnknown(t *testing.T) { func TestTopologyStateLimit(t *testing.T) { cli, cmd := setStateCmd(t) cli.MockClient.ApiMocks.SnapshotApi.QuerySnapshotResponse.Result = sts.QuerySnapshotResult{ - Type: "QuerySnapshotResult", + Type: querySnapshotResultType, ViewSnapshotResponse: map[string]interface{}{ - "_type": "ViewSnapshot", - "components": []interface{}{ + testTypeKey: viewSnapshotType, + componentsKey: []interface{}{ map[string]interface{}{ - "id": float64(1), - "name": "component-1", - "type": float64(239975151751041), - "identifiers": []interface{}{"urn:test:1"}, - "state": map[string]interface{}{ - "healthState": "CLEAR", + "id": float64(1), + nameKey: "component-1", + testType: float64(239975151751041), + testIdentifiers: []interface{}{"urn:test:1"}, + testState: map[string]interface{}{ + testHealthState: "CLEAR", }, }, map[string]interface{}{ - "id": float64(2), - "name": "component-2", - "type": float64(239975151751041), - "identifiers": []interface{}{"urn:test:2"}, - "state": map[string]interface{}{ - "healthState": "CRITICAL", + "id": float64(2), + nameKey: "component-2", + testType: float64(239975151751041), + testIdentifiers: []interface{}{"urn:test:2"}, + testState: map[string]interface{}{ + testHealthState: "CRITICAL", }, }, map[string]interface{}{ - "id": float64(3), - "name": "component-3", - "type": float64(239975151751041), - "identifiers": []interface{}{"urn:test:3"}, - "state": map[string]interface{}{ - "healthState": "DEVIATING", + "id": float64(3), + nameKey: "component-3", + testType: float64(239975151751041), + testIdentifiers: []interface{}{"urn:test:3"}, + testState: map[string]interface{}{ + testHealthState: "DEVIATING", }, }, }, - "metadata": map[string]interface{}{ - "componentTypes": []interface{}{ + testMetadata: map[string]interface{}{ + testComponentTypes: []interface{}{ map[string]interface{}{ - "id": float64(239975151751041), - "name": "test type", + "id": float64(239975151751041), + nameKey: "test type", }, }, }, diff --git a/cmd/topology/topology_test_helper.go b/cmd/topology/topology_test_helper.go index f25d1932..15013683 100644 --- a/cmd/topology/topology_test_helper.go +++ b/cmd/topology/topology_test_helper.go @@ -9,11 +9,11 @@ func mockSnapshotResponse() sts.QuerySnapshotResult { return sts.QuerySnapshotResult{ Type: "QuerySnapshotResult", ViewSnapshotResponse: map[string]interface{}{ - "_type": "ViewSnapshot", - "components": []interface{}{ + "_type": viewSnapshotType, + componentsKey: []interface{}{ map[string]interface{}{ "id": float64(229404307680647), - "name": "test-component", + nameKey: "test-component", "typeIdentifier": "urn:test:component-type:test", "layerIdentifier": "urn:test:layer:test", "domainIdentifier": "urn:test:domain:test", @@ -27,20 +27,20 @@ func mockSnapshotResponse() sts.QuerySnapshotResult { "metadata": map[string]interface{}{ "componentTypes": []interface{}{ map[string]interface{}{ - "identifier": "urn:test:component-type:test", - "name": "test type", + identifierKey: "urn:test:component-type:test", + nameKey: "test type", }, }, "layers": []interface{}{ map[string]interface{}{ - "identifier": "urn:test:layer:test", - "name": "Test Layer", + identifierKey: "urn:test:layer:test", + nameKey: "Test Layer", }, }, "domains": []interface{}{ map[string]interface{}{ - "identifier": "urn:test:domain:test", - "name": "Test Domain", + identifierKey: "urn:test:domain:test", + nameKey: "Test Domain", }, }, }, diff --git a/cmd/topologysync/topologysync_describe_test.go b/cmd/topologysync/topologysync_describe_test.go index 44edccc5..ff10c06a 100644 --- a/cmd/topologysync/topologysync_describe_test.go +++ b/cmd/topologysync/topologysync_describe_test.go @@ -10,6 +10,11 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + testNoChanges = "+0 -0" + testSynchronizations = "synchronizations" +) + var ( Error1 = stackstate_api.NewTopologyStreamError(stackstate_api.MESSAGELEVEL_WARN, "Oops") Error2 = stackstate_api.NewTopologyStreamError(stackstate_api.MESSAGELEVEL_ERROR, "Welp, better leave the premises quickly.") @@ -87,9 +92,9 @@ func TestTopologySyncDescribeErrors(t *testing.T) { { Header: []string{"Id", "Name", "Identifier", "Status", "Components", "Relations", "Errors"}, Data: [][]interface{}{ - {Topo1.NodeId, Topo1.Name, "-", Topo1.Status, "+0 -0", "+0 -0", int64(0)}, + {Topo1.NodeId, Topo1.Name, "-", Topo1.Status, testNoChanges, testNoChanges, int64(0)}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: "synchronizations"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: testSynchronizations}, }, { Header: []string{"External ID", "Level", "Message"}, diff --git a/cmd/topologysync/topologysync_list_test.go b/cmd/topologysync/topologysync_list_test.go index cd567dcb..69494679 100644 --- a/cmd/topologysync/topologysync_list_test.go +++ b/cmd/topologysync/topologysync_list_test.go @@ -33,12 +33,12 @@ func TestTopologySyncListTable(t *testing.T) { { Header: []string{"Id", "Name", "Identifier", "Status", "Components", "Relations", "Errors"}, Data: [][]interface{}{ - {Topo1.NodeId, Topo1.Name, "-", Topo1.Status, "+0 -0", "+0 -0", int64(0)}, + {Topo1.NodeId, Topo1.Name, "-", Topo1.Status, testNoChanges, testNoChanges, int64(0)}, {Topo2.NodeId, Topo2.Name, "-", Topo2.Status, "+23 -5", "+23 -5", int64(0)}, {Topo3.NodeId, Topo3.Name, "-", Topo3.Status, "+23 -12345", "+12345 -23", int64(1)}, {Topo4.NodeId, Topo4.Name, "-", Topo4.Status, "+12345 -12345", "+12345 -12345", int64(23)}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: "synchronizations"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: testSynchronizations}, }, } @@ -54,7 +54,7 @@ func TestTopologySyncListJson(t *testing.T) { expected := []map[string]interface{}{ { - "synchronizations": AllTopos, + testSynchronizations: AllTopos, }, } diff --git a/internal/client/client_test.go b/internal/client/client_test.go index 1ba1407b..03861a2a 100644 --- a/internal/client/client_test.go +++ b/internal/client/client_test.go @@ -12,6 +12,12 @@ import ( "github.com/stretchr/testify/require" ) +const ( + testVersion = "1.2.3" + testVersionDiff = "c0ffee23" + testVersionCommit = "yes" +) + func setupClient() (StackStateClient, *stackstate_api.ServerApiMock) { serverApi := stackstate_api.NewServerApiMock() api := stackstate_api.APIClient{ @@ -54,13 +60,13 @@ func TestCombineURLAndApi(t *testing.T) { } func TestVersionToString(t *testing.T) { - assert.Equal(t, "1.2.3", VersionToString(stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3})) - assert.Equal(t, "1.2.3+c0ffee23", VersionToString(stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3, Diff: "c0ffee23"})) - assert.Equal(t, "1.2.3+c0ffee23-yes", VersionToString(stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3, Diff: "c0ffee23", Commit: "yes"})) - assert.Equal(t, "1.2.3+c0ffee23-yes-dev", VersionToString(stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3, Diff: "c0ffee23", Commit: "yes", IsDev: true})) + assert.Equal(t, testVersion, VersionToString(stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3})) + assert.Equal(t, "1.2.3+c0ffee23", VersionToString(stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3, Diff: testVersionDiff})) + assert.Equal(t, "1.2.3+c0ffee23-yes", VersionToString(stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3, Diff: testVersionDiff, Commit: testVersionCommit})) + assert.Equal(t, "1.2.3+c0ffee23-yes-dev", VersionToString(stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3, Diff: testVersionDiff, Commit: testVersionCommit, IsDev: true})) assert.Equal(t, "1.2.3-dev", VersionToString(stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3, IsDev: true})) - assert.Equal(t, "1.2.3-yes-dev", VersionToString(stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3, Commit: "yes", IsDev: true})) - assert.Equal(t, "1.2.3-yes", VersionToString(stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3, Commit: "yes"})) + assert.Equal(t, "1.2.3-yes-dev", VersionToString(stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3, Commit: testVersionCommit, IsDev: true})) + assert.Equal(t, "1.2.3-yes", VersionToString(stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3, Commit: testVersionCommit})) } type VersionTest struct { @@ -82,7 +88,7 @@ func TestVersionCompatibilityCheck(t *testing.T) { {Server: V(1, 2, 3), Cmd: "1.0.0", Result: nil}, {Server: V(1, 2, 3), Cmd: "1.0.6", Result: nil}, {Server: V(1, 2, 3), Cmd: "1.2.0", Result: nil}, - {Server: V(1, 2, 3), Cmd: "1.2.3", Result: nil}, + {Server: V(1, 2, 3), Cmd: testVersion, Result: nil}, // Server version really only needs to be greater than or equal to the command minimum version, even newer major versions are fine {Server: V(2, 2, 3), Cmd: "1.2.4", Result: nil}, @@ -91,25 +97,25 @@ func TestVersionCompatibilityCheck(t *testing.T) { {Server: V(1, 2, 3), Cmd: "1.2.2-alpha.preview+123", Result: nil}, { Server: stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3, Diff: "diff", Commit: "deadbeef"}, - Cmd: "1.2.3", + Cmd: testVersion, // FIXME Should be NewAPIVersionMismatchError("1.2.3+diff-deadbeef", "1.2.3"), Result: nil, }, // Incompatible versions are detected. {Server: V(1, 2, 3), Cmd: "1.2.3-alpha.preview+123", Result: nil}, - {Server: V(1, 2, 3), Cmd: "1.2.4", Result: NewAPIVersionMismatchError("1.2.3", "1.2.4")}, - {Server: V(1, 2, 3), Cmd: "1.3.3", Result: NewAPIVersionMismatchError("1.2.3", "1.3.3")}, - {Server: V(1, 2, 3), Cmd: "2.2.4", Result: NewAPIVersionMismatchError("1.2.3", "2.2.4")}, + {Server: V(1, 2, 3), Cmd: "1.2.4", Result: NewAPIVersionMismatchError(testVersion, "1.2.4")}, + {Server: V(1, 2, 3), Cmd: "1.3.3", Result: NewAPIVersionMismatchError(testVersion, "1.3.3")}, + {Server: V(1, 2, 3), Cmd: "2.2.4", Result: NewAPIVersionMismatchError(testVersion, "2.2.4")}, // Pre-release versions are less than the released version, so they are not sufficient { Server: stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3, Commit: "deadbeef"}, - Cmd: "1.2.3", - Result: NewAPIVersionMismatchError("1.2.3-deadbeef", "1.2.3"), + Cmd: testVersion, + Result: NewAPIVersionMismatchError("1.2.3-deadbeef", testVersion), }, { Server: stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3, IsDev: true}, - Cmd: "1.2.3", - Result: NewAPIVersionMismatchError("1.2.3-dev", "1.2.3"), + Cmd: testVersion, + Result: NewAPIVersionMismatchError("1.2.3-dev", testVersion), }, // Invalid versions are detected. { diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 0d537844..9ad47e68 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -9,6 +9,10 @@ import ( ) const ( + testLocalURL = "http://localhost:8080" + testAPIToken = "foo" + testOtherURL = "http://other:8080" + malformedCertificateError = "x509: malformed certificate" //nolint:lll selfSignedBase64Cert = "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUNKekNDQWRHZ0F3SUJBZ0lVVi9hSmoxZkVjQ2dOVTJGYWZZMHVSTHF5N21Bd0RRWUpLb1pJaHZjTkFRRUwKQlFBd0tURW5NQ1VHQTFVRUF3d2VkbWxzYVdGcmIzWXVjMkZ1WkdKdmVDNXpkR0ZqYTNOMFlYUmxMbWx2TUNBWApEVEkxTURjeU1USXdORFUxTmxvWUR6SXhNalV3TmpJM01qQTBOVFUyV2pBcE1TY3dKUVlEVlFRRERCNTJhV3hwCllXdHZkaTV6WVc1a1ltOTRMbk4wWVdOcmMzUmhkR1V1YVc4d1hEQU5CZ2txaGtpRzl3MEJBUUVGQUFOTEFEQkkKQWtFQW9wUXVPSmZJa0xDV0pLVDcwaGdiSEpwVWtFQitaYTJwOXVBMUlOUktNNEFyN2RjVjltdXhOS09jSloycwpWdCtiK1lTS1c4cnRteE5QUVh1RTJENHRlUUlEQVFBQm80SE9NSUhMTUIwR0ExVWREZ1FXQkJRVTBPTFZRRzEyCndNb0VLSGdxSG1aeVhTelozekFmQmdOVkhTTUVHREFXZ0JRVTBPTFZRRzEyd01vRUtIZ3FIbVp5WFN6WjN6QVAKQmdOVkhSTUJBZjhFQlRBREFRSC9NSGdHQTFVZEVRUnhNRytDSG5acGJHbGhhMjkyTG5OaGJtUmliM2d1YzNSaApZMnR6ZEdGMFpTNXBiNElqYjNSc2NDMTJhV3hwWVd0dmRpNXpZVzVrWW05NExuTjBZV05yYzNSaGRHVXVhVytDCktHOTBiSEF0YUhSMGNDMTJhV3hwWVd0dmRpNXpZVzVrWW05NExuTjBZV05yYzNSaGRHVXVhVzh3RFFZSktvWkkKaHZjTkFRRUxCUUFEUVFBZllBVk1lTVJHbFcrR1prellPeGRIaVhYNEFISHA5SWxvWlBMbUJHNExtdlpDODBoVgpLNGNSVUVHSGtSeGdrMGgwYzl3RDhOZFZSM1FuRTBubjZXUEUKLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo=" ) @@ -34,14 +38,14 @@ current-context: prod assert.NoError(t, err) assert.Len(t, cfg.Contexts, 2) assert.Equal(t, "prod", cfg.CurrentContext) - assert.Equal(t, "http://localhost:8080", cfg.Contexts[0].Context.URL) - assert.Equal(t, "foo", cfg.Contexts[0].Context.APIToken) + assert.Equal(t, testLocalURL, cfg.Contexts[0].Context.URL) + assert.Equal(t, testAPIToken, cfg.Contexts[0].Context.APIToken) assert.Empty(t, cfg.Contexts[0].Context.ServiceToken) assert.Equal(t, "/api", cfg.Contexts[0].Context.APIPath) assert.Equal(t, "/admin", cfg.Contexts[0].Context.AdminAPIPath) assert.Equal(t, selfSignedBase64Cert, cfg.Contexts[0].Context.CaCertBase64Data) assert.Equal(t, "http://prod:8080", cfg.Contexts[1].Context.URL) - assert.Equal(t, "foo", cfg.Contexts[1].Context.ServiceToken) + assert.Equal(t, testAPIToken, cfg.Contexts[1].Context.ServiceToken) assert.Equal(t, "/hidden/api", cfg.Contexts[1].Context.APIPath) assert.Equal(t, "/admin/api", cfg.Contexts[1].Context.AdminAPIPath) assert.Empty(t, cfg.Contexts[1].Context.APIToken) @@ -75,8 +79,8 @@ api-token: foo assert.NoError(t, err) assert.Len(t, cfg.Contexts, 1) assert.Equal(t, "default", cfg.CurrentContext) - assert.Equal(t, "http://localhost:8080", cfg.Contexts[0].Context.URL) - assert.Equal(t, "foo", cfg.Contexts[0].Context.APIToken) + assert.Equal(t, testLocalURL, cfg.Contexts[0].Context.URL) + assert.Equal(t, testAPIToken, cfg.Contexts[0].Context.APIToken) assert.Empty(t, cfg.Contexts[0].Context.ServiceToken) assert.Equal(t, "/api", cfg.Contexts[0].Context.APIPath) assert.Equal(t, "/admin", cfg.Contexts[0].Context.AdminAPIPath) @@ -186,45 +190,45 @@ current-context: default func TestMergeWithNoTokenOverride(t *testing.T) { c := &StsContext{ - URL: "http://localhost:8080", + URL: testLocalURL, } f := &StsContext{ - URL: "http://other:8080", - APIToken: "foo", + URL: testOtherURL, + APIToken: testAPIToken, } n := c.Merge(f) - assert.Equal(t, "http://localhost:8080", n.URL) - assert.Equal(t, "foo", n.APIToken) + assert.Equal(t, testLocalURL, n.URL) + assert.Equal(t, testAPIToken, n.APIToken) } func TestMergeWithSameTokenOverride(t *testing.T) { c := &StsContext{ - URL: "http://localhost:8080", + URL: testLocalURL, APIToken: "bar", } f := &StsContext{ - URL: "http://other:8080", - APIToken: "foo", + URL: testOtherURL, + APIToken: testAPIToken, } n := c.Merge(f) - assert.Equal(t, "http://localhost:8080", n.URL) + assert.Equal(t, testLocalURL, n.URL) assert.Equal(t, "bar", n.APIToken) } func TestMergeWithOtherTokenOverride(t *testing.T) { c := &StsContext{ - URL: "http://localhost:8080", + URL: testLocalURL, ServiceToken: "bar", } f := &StsContext{ - URL: "http://other:8080", - APIToken: "foo", + URL: testOtherURL, + APIToken: testAPIToken, } n := c.Merge(f) - assert.Equal(t, "http://localhost:8080", n.URL) + assert.Equal(t, testLocalURL, n.URL) assert.Equal(t, "bar", n.ServiceToken) assert.Equal(t, "", n.APIToken) } @@ -272,13 +276,13 @@ invalid-cert-data name: "empty certificate data", certData: []byte{}, expectError: true, - errorMsg: "x509: malformed certificate", + errorMsg: malformedCertificateError, }, { name: "nil certificate data", certData: nil, expectError: true, - errorMsg: "x509: malformed certificate", + errorMsg: malformedCertificateError, }, { name: "invalid PEM block type", @@ -290,13 +294,13 @@ invalid-cert-data name: "invalid PEM certificate data", certData: invalidPEMData, expectError: true, - errorMsg: "x509: malformed certificate", + errorMsg: malformedCertificateError, }, { name: "plain text data", certData: []byte("not a certificate"), expectError: true, - errorMsg: "x509: malformed certificate", + errorMsg: malformedCertificateError, }, } diff --git a/internal/printer/printer.go b/internal/printer/printer.go index 23fecdb8..6cb1aed3 100644 --- a/internal/printer/printer.go +++ b/internal/printer/printer.go @@ -45,9 +45,7 @@ type TableData struct { MissingTableDataMsg MissingTableDataMsg } -const ( - YamlIndent = 2 -) +const YamlIndent = 2 type StopPrinterFn func() diff --git a/internal/printer/printer_test.go b/internal/printer/printer_test.go index 57a66f8e..80604d04 100644 --- a/internal/printer/printer_test.go +++ b/internal/printer/printer_test.go @@ -15,6 +15,16 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + testWorld = "World" + testNestedValue = "foobarbaz" + testHello = "Hello" + testFoo = "foo" + testBar = "bar" + testBaz = "baz" + testCapitalizedFoo = "Foo" +) + func setupPrinter() (*StdPrinter, *bytes.Buffer, *bytes.Buffer) { var stdOut, stdErr bytes.Buffer p := NewStdPrinter("linux", &stdOut, &stdErr) @@ -59,9 +69,9 @@ func TestPrintWithoutSymbolButWithColorOnWindows(t *testing.T) { func TestPrintStructAsJsonWithoutColor(t *testing.T) { testStruct := map[string]interface{}{ - "foo": 1, - "bar": map[string]interface{}{ - "baz": "foobarbaz", + testFoo: 1, + testBar: map[string]interface{}{ + testBaz: testNestedValue, "in": map[string]interface{}{ "out": 1, }, @@ -104,9 +114,9 @@ func TestPrintErrJson(t *testing.T) { func TestPrintStructAsYamlWithoutColor(t *testing.T) { testStruct := map[string]interface{}{ - "foo": 1, - "bar": map[string]interface{}{ - "baz": "foobarbaz", + testFoo: 1, + testBar: map[string]interface{}{ + testBaz: testNestedValue, }, } const expectedYaml = `bar: @@ -120,9 +130,9 @@ foo: 1 func TestPrintStructAsYamlWithColor(t *testing.T) { testStruct := map[string]interface{}{ - "foo": 1, - "bar": map[string]interface{}{ - "baz": "foobarbaz", + testFoo: 1, + testBar: map[string]interface{}{ + testBaz: testNestedValue, }, } //nolint:lll @@ -226,7 +236,7 @@ func TestPrintTableWrapEqualColumnTreatment(t *testing.T) { p.SetUseColor(false) p.MaxWidth = 25 p.Table(TableData{ - Header: []string{"Hello", "Foo", "World"}, + Header: []string{testHello, testCapitalizedFoo, testWorld}, Data: [][]interface{}{ {"1", "2", "3"}, {"hello darkness my old friend", "I've come to talk to you again", "Because a vision softly creeping"}, @@ -243,7 +253,7 @@ func TestPrintTableWrapUnequalColumnTreatment(t *testing.T) { p.SetUseColor(false) p.MaxWidth = 30 p.Table(TableData{ - Header: []string{"Hello", "Foo", "World"}, + Header: []string{testHello, testCapitalizedFoo, testWorld}, Data: [][]interface{}{ {"hello", "darkness my old friend", "Because a vision softly creeping"}, }, @@ -259,7 +269,7 @@ func TestTableDoesNotRenderBiggerThanMaxWidth(t *testing.T) { p.SetUseColor(false) data := []string{"hello", "fooba", "world"} - header1 := []string{"Hello", "Foo", "World"} + header1 := []string{testHello, testCapitalizedFoo, testWorld} header2 := []string{"x", "y", "z"} header3 := []string{"Wooot", "Woot", "It's the sound Of da Police"} for i := 0; i < 100; i++ { diff --git a/internal/util/string_util.go b/internal/util/string_util.go index cf672e69..a4023794 100644 --- a/internal/util/string_util.go +++ b/internal/util/string_util.go @@ -69,7 +69,7 @@ func ToString(x interface{}) string { k := r.Kind() // this is the only way to check whether `x == nill`, because nil is specific to the type in Golang :( - isPointer := k == reflect.Chan || k == reflect.Func || k == reflect.Map || k == reflect.Ptr || + isPointer := k == reflect.Chan || k == reflect.Func || k == reflect.Map || k == reflect.Pointer || k == reflect.UnsafePointer || k == reflect.Slice || k == reflect.Interface if k == reflect.Invalid || (isPointer && r.IsNil()) { return "-" diff --git a/internal/util/string_util_test.go b/internal/util/string_util_test.go index bcd90942..2a0e3445 100644 --- a/internal/util/string_util_test.go +++ b/internal/util/string_util_test.go @@ -8,6 +8,13 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + testFoo = "foo" + testBar = "bar" + testGreeting = "hello world" + testDecimal = "3.14" +) + func TestUcFirst(t *testing.T) { assert.Equal(t, UcFirst(""), "") assert.Equal(t, UcFirst("test"), "Test") @@ -15,7 +22,7 @@ func TestUcFirst(t *testing.T) { } func TestUniqueString(t *testing.T) { - assert.Equal(t, []string{"foo", "bar"}, UniqueStrings([]string{"foo", "bar", "foo", "bar"})) + assert.Equal(t, []string{testFoo, testBar}, UniqueStrings([]string{testFoo, testBar, testFoo, testBar})) } func TestToString(t *testing.T) { @@ -35,7 +42,7 @@ func TestToString(t *testing.T) { f32 := float32(3.14) f64 := float32(3.14) unixEpoch := time.UnixMilli(0).In(time.UTC) - str := "hello world" + str := testGreeting EST, err := time.LoadLocation("EST") if err != nil { t.Fatal(err) @@ -61,11 +68,11 @@ func TestToString(t *testing.T) { "pint64": {input: &i64, expected: "-42"}, "uint64": {input: uint64(42), expected: "42"}, "puint64": {input: &ui64, expected: "42"}, - "float32": {input: float32(3.14), expected: "3.14"}, - "pfloat32": {input: &f32, expected: "3.14"}, + "float32": {input: float32(3.14), expected: testDecimal}, + "pfloat32": {input: &f32, expected: testDecimal}, "float32 round": {input: float32(3), expected: "3"}, - "float64": {input: float64(3.14), expected: "3.14"}, - "pfloat64": {input: &f64, expected: "3.14"}, + "float64": {input: float64(3.14), expected: testDecimal}, + "pfloat64": {input: &f64, expected: testDecimal}, "float64 round": {input: float64(3), expected: "3"}, "float64 round large no scientific notation": { input: float64(107915343054010.0), expected: "107915343054010", @@ -81,8 +88,8 @@ func TestToString(t *testing.T) { "map nil": {input: mapnil, expected: "-"}, "str nil": {input: strnil, expected: "-"}, "slice nil": {input: slicenil, expected: "-"}, - "string": {input: "hello world", expected: "hello world"}, - "pstring": {input: &str, expected: "hello world"}, + "string": {input: testGreeting, expected: testGreeting}, + "pstring": {input: &str, expected: testGreeting}, } for name, tc := range tests { diff --git a/main_test.go b/main_test.go index 8df1cd85..f511a0d1 100644 --- a/main_test.go +++ b/main_test.go @@ -14,9 +14,15 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + testError = "test-error" + testVersion = "version" + testJSON = "json" +) + func setupSTSCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { errorCmd := cobra.Command{ - Use: "test-error", + Use: testError, Short: "some short help text for ErrorCmd", Long: "Some long help text for ErrorCmd.", RunE: func(cmd *cobra.Command, args []string) error { @@ -53,7 +59,7 @@ func TestHelpWhenRunningHelp(t *testing.T) { func TestVersionRun(t *testing.T) { cli, cmd := setupSTSCmd(t) - cmd.SetArgs([]string{"version"}) + cmd.SetArgs([]string{testVersion}) exitCode := execute(cli.Context, &cli.Deps, cmd) assert.Equal(t, 0, exitCode) assert.Equal(t, []printer.TableData{{ @@ -65,19 +71,19 @@ func TestVersionRun(t *testing.T) { func TestVersionJsonRun(t *testing.T) { cli, cmd := setupSTSCmd(t) - cmd.SetArgs([]string{"version", "-o", "json"}) + cmd.SetArgs([]string{testVersion, "-o", testJSON}) exitCode := execute(cli.Context, &cli.Deps, cmd) assert.Equal(t, 0, exitCode) assert.Equal(t, []map[string]interface{}{{ - "commit": "123124", "build-date": "1-1-2022", "version": "1.0.0", + "commit": "123124", "build-date": "1-1-2022", testVersion: "1.0.0", }}, *cli.MockPrinter.PrintJsonCalls) } func TestSetFlagErrorFuncSetsCLIArgParseError(t *testing.T) { cli, sts := setupSTSCmd(t) - sts.SetArgs([]string{"version", "--wrongflag"}) + sts.SetArgs([]string{testVersion, "--wrongflag"}) exitCode := execute(cli.Context, &cli.Deps, sts) assert.Equal(t, common.CommandFailedRequirementExitCode, exitCode) @@ -88,7 +94,7 @@ func TestSetFlagErrorFuncSetsCLIArgParseError(t *testing.T) { func TestErrHandling(t *testing.T) { cli, sts := setupSTSCmd(t) - sts.SetArgs([]string{"test-error"}) + sts.SetArgs([]string{testError}) exitCode := execute(cli.Context, &cli.Deps, sts) assert.Equal(t, common.CommandFailedRequirementExitCode, exitCode) @@ -100,7 +106,7 @@ func TestErrHandling(t *testing.T) { func TestErrToJson(t *testing.T) { cli, sts := setupSTSCmd(t) - sts.SetArgs([]string{"test-error", "-o", "json"}) + sts.SetArgs([]string{testError, "-o", testJSON}) exitCode := execute(cli.Context, &cli.Deps, sts) assert.Equal(t, common.CommandFailedRequirementExitCode, exitCode) @@ -123,7 +129,7 @@ func TestColorUsedByDefault(t *testing.T) { cli, cmd := setupSTSCmd(t) - cmd.SetArgs([]string{"version"}) + cmd.SetArgs([]string{testVersion}) execute(cli.Context, &cli.Deps, cmd) assert.True(t, cli.MockPrinter.UseColor) @@ -132,7 +138,7 @@ func TestColorUsedByDefault(t *testing.T) { func TestNoColorFlag(t *testing.T) { cli, cmd := setupSTSCmd(t) - cmd.SetArgs([]string{"version", "--no-color"}) + cmd.SetArgs([]string{testVersion, "--no-color"}) execute(cli.Context, &cli.Deps, cmd) assert.False(t, cli.MockPrinter.UseColor) assert.True(t, cli.NoColor) @@ -144,7 +150,7 @@ func TestNoColorWhenDumbTerminal(t *testing.T) { os.Setenv("TERM", "Dumb") cli, cmd := setupSTSCmd(t) - cmd.SetArgs([]string{"version"}) + cmd.SetArgs([]string{testVersion}) execute(cli.Context, &cli.Deps, cmd) assert.False(t, cli.MockPrinter.UseColor) assert.True(t, cli.NoColor) @@ -156,7 +162,7 @@ func TestNoColorWhenNoColorEnvExists(t *testing.T) { os.Setenv("NO_COLOR", "false") cli, cmd := setupSTSCmd(t) - cmd.SetArgs([]string{"version"}) + cmd.SetArgs([]string{testVersion}) execute(cli.Context, &cli.Deps, cmd) assert.False(t, cli.MockPrinter.UseColor) assert.True(t, cli.NoColor) @@ -164,7 +170,7 @@ func TestNoColorWhenNoColorEnvExists(t *testing.T) { func TestNoColorWhenJsonOutput(t *testing.T) { cli, cmd := setupSTSCmd(t) - cmd.SetArgs([]string{"version", "-o", "json"}) + cmd.SetArgs([]string{testVersion, "-o", testJSON}) execute(cli.Context, &cli.Deps, cmd) assert.False(t, cli.MockPrinter.UseColor) assert.True(t, cli.NoColor) @@ -172,7 +178,7 @@ func TestNoColorWhenJsonOutput(t *testing.T) { func TestVerbose(t *testing.T) { cli, cmd := setupSTSCmd(t) - cmd.SetArgs([]string{"version", "--verbose"}) + cmd.SetArgs([]string{testVersion, "--verbose"}) execute(cli.Context, &cli.Deps, cmd) assert.True(t, cli.IsVerBose) } diff --git a/pkg/pflags/duration_flag_test.go b/pkg/pflags/duration_flag_test.go index ca48018b..b5cbb95c 100644 --- a/pkg/pflags/duration_flag_test.go +++ b/pkg/pflags/duration_flag_test.go @@ -10,6 +10,10 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + invalidFlagValue = "garbage" +) + var durationTests = map[string]struct { input string outDuration time.Duration @@ -22,7 +26,7 @@ var durationTests = map[string]struct { "2 day": {input: "2d", outDuration: 48 * time.Hour, outErr: nil}, "1 week": {input: "1w", outDuration: 24 * time.Hour * 7, outErr: nil}, "empty string": {input: "", outDuration: 0, outErr: newInvalidDurationStringError()}, - "garbage": {input: "woot", outDuration: 0, outErr: newInvalidDurationStringError()}, + invalidFlagValue: {input: "woot", outDuration: 0, outErr: newInvalidDurationStringError()}, "missing unit single": {input: "1", outDuration: 0, outErr: newInvalidDurationStringError()}, "missing unit multi": {input: "122", outDuration: 0, outErr: newInvalidDurationStringError()}, "wrong unit": {input: "1j", outDuration: 0, outErr: newUnknownDurationUnitError("j")}, diff --git a/pkg/pflags/relative_time_flag_test.go b/pkg/pflags/relative_time_flag_test.go index 38b5fdd6..926838da 100644 --- a/pkg/pflags/relative_time_flag_test.go +++ b/pkg/pflags/relative_time_flag_test.go @@ -22,7 +22,7 @@ var timeTests = map[string]struct { "iso date": {input: "2022-05-09T15:04:05Z", outTime: int64(1652108645000), outErr: nil}, "relative time": {input: "-2d", outTime: int64(1652108645000 - 2*86400000), outErr: nil}, "unix time": {input: "1652108645000", outTime: int64(1652108645000), outErr: nil}, - "garbage": {input: "garbage", outTime: TimeZero, outErr: newTimeParseError("garbage")}, + invalidFlagValue: {input: invalidFlagValue, outTime: TimeZero, outErr: newTimeParseError(invalidFlagValue)}, "empty ": {input: "", outTime: TimeZero, outErr: newTimeParseError("")}, "invalid relative time": {input: "-2j", outTime: TimeZero, outErr: newInvalidRelativeTimeError("-2j", newUnknownDurationUnitError("j"))}, } diff --git a/pkg/scaffold/github_source_test.go b/pkg/scaffold/github_source_test.go index 54ad0f5a..ca2a2e45 100644 --- a/pkg/scaffold/github_source_test.go +++ b/pkg/scaffold/github_source_test.go @@ -13,6 +13,19 @@ import ( "testing" ) +const ( + testArchiveFilePath = "test-repo-main/templates/generic/file.txt" + testOwner = "testowner" + testRepo = "testrepo" + testTemplatesPath = "templates" + testGenericTemplate = "generic" + testRef = "main" + emptyTemplateNameCase = "empty template name" + templateNameRequiredError = "template name is required" + testRepositoryDir = "test-repo" + testFileContent = "content" +) + func TestGitHubSource_NewGitHubSource(t *testing.T) { tests := []struct { name string @@ -25,21 +38,21 @@ func TestGitHubSource_NewGitHubSource(t *testing.T) { }{ { name: "all parameters provided", - owner: "testowner", - repo: "testrepo", + owner: testOwner, + repo: testRepo, ref: "v1.0.0", - path: "templates", - templateName: "generic", + path: testTemplatesPath, + templateName: testGenericTemplate, expectedRef: "v1.0.0", }, { name: "empty ref defaults to main", - owner: "testowner", - repo: "testrepo", + owner: testOwner, + repo: testRepo, ref: "", - path: "templates", - templateName: "generic", - expectedRef: "main", + path: testTemplatesPath, + templateName: testGenericTemplate, + expectedRef: testRef, }, } @@ -74,12 +87,12 @@ func TestGitHubSource_String(t *testing.T) { }{ { name: "with path", - source: NewGitHubSource("owner", "repo", "main", "templates", "generic"), + source: NewGitHubSource("owner", "repo", testRef, testTemplatesPath, testGenericTemplate), expectedStr: "github:owner/repo@main:templates", }, { name: "without path", - source: NewGitHubSource("owner", "repo", "v1.0", "", "generic"), + source: NewGitHubSource("owner", "repo", "v1.0", "", testGenericTemplate), expectedStr: "github:owner/repo@v1.0", }, } @@ -105,40 +118,40 @@ func TestGitHubSource_Validate(t *testing.T) { }{ { name: "valid source", - owner: "testowner", - repo: "testrepo", - templateName: "generic", + owner: testOwner, + repo: testRepo, + templateName: testGenericTemplate, wantErr: false, }, { name: "empty owner", owner: "", - repo: "testrepo", - templateName: "generic", + repo: testRepo, + templateName: testGenericTemplate, wantErr: true, expectedErr: "GitHub repository owner is required", }, { name: "empty repo", - owner: "testowner", + owner: testOwner, repo: "", - templateName: "generic", + templateName: testGenericTemplate, wantErr: true, expectedErr: "GitHub repository name is required", }, { - name: "empty template name", - owner: "testowner", - repo: "testrepo", + name: emptyTemplateNameCase, + owner: testOwner, + repo: testRepo, templateName: "", wantErr: true, - expectedErr: "template name is required", + expectedErr: templateNameRequiredError, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - source := NewGitHubSource(tt.owner, tt.repo, "main", "templates", tt.templateName) + source := NewGitHubSource(tt.owner, tt.repo, testRef, testTemplatesPath, tt.templateName) err := source.Validate() if tt.wantErr { @@ -158,7 +171,7 @@ func TestGitHubSource_Validate(t *testing.T) { func TestGitHubSource_Cleanup(t *testing.T) { // Test cleanup when no temp directory is set - source := NewGitHubSource("owner", "repo", "main", "", "generic") + source := NewGitHubSource("owner", "repo", testRef, "", testGenericTemplate) err := source.Cleanup() if err != nil { t.Errorf("Expected no error when tempDir is empty, got: %v", err) @@ -208,7 +221,7 @@ func TestGitHubSource_extractZip(t *testing.T) { } extractDir := filepath.Join(tempDir, "extracted") - source := NewGitHubSource("owner", "repo", "main", "", "generic") + source := NewGitHubSource("owner", "repo", testRef, "", testGenericTemplate) err = source.extractZip(zipFile, extractDir) if err != nil { @@ -243,68 +256,68 @@ func TestGitHubSource_findTemplateDirectory(t *testing.T) { }{ { name: "find template with path", - repo: "test-repo", - ref: "main", - path: "templates", - templateName: "generic", + repo: testRepositoryDir, + ref: testRef, + path: testTemplatesPath, + templateName: testGenericTemplate, setupFiles: map[string]string{ - "test-repo-main/templates/generic/file.txt": "content", + testArchiveFilePath: testFileContent, }, wantErr: false, }, { name: "find template without path", - repo: "test-repo", - ref: "main", + repo: testRepositoryDir, + ref: testRef, path: "", - templateName: "generic", + templateName: testGenericTemplate, setupFiles: map[string]string{ - "test-repo-main/generic/file.txt": "content", + "test-repo-main/generic/file.txt": testFileContent, }, wantErr: false, }, { name: "repo directory not found", - repo: "test-repo", - ref: "main", + repo: testRepositoryDir, + ref: testRef, path: "", - templateName: "generic", + templateName: testGenericTemplate, setupFiles: map[string]string{ - "wrong-repo-main/generic/file.txt": "content", + "wrong-repo-main/generic/file.txt": testFileContent, }, wantErr: true, expectedErr: "could not find repository directory in extracted archive", }, { name: "template base directory not found", - repo: "test-repo", - ref: "main", + repo: testRepositoryDir, + ref: testRef, path: "nonexistent", - templateName: "generic", + templateName: testGenericTemplate, setupFiles: map[string]string{ - "test-repo-main/templates/generic/file.txt": "content", + testArchiveFilePath: testFileContent, }, wantErr: true, expectedErr: "template base directory not found at path 'nonexistent'", }, { name: "template not found", - repo: "test-repo", - ref: "main", - path: "templates", + repo: testRepositoryDir, + ref: testRef, + path: testTemplatesPath, templateName: "nonexistent", setupFiles: map[string]string{ - "test-repo-main/templates/generic/file.txt": "content", + testArchiveFilePath: testFileContent, }, wantErr: true, expectedErr: "template 'nonexistent' not found in directory", }, { name: "template is file not directory", - repo: "test-repo", - ref: "main", - path: "templates", - templateName: "generic", + repo: testRepositoryDir, + ref: testRef, + path: testTemplatesPath, + templateName: testGenericTemplate, setupFiles: map[string]string{ "test-repo-main/templates/generic": "file content", }, @@ -376,10 +389,10 @@ func TestGitHubSource_findTemplateDirectory(t *testing.T) { func TestGitHubSource_Fetch_Integration(t *testing.T) { // Create a mock HTTP server that serves a ZIP file zipData := createTestZipFile(t, map[string]string{ - "test-repo-main/": "", - "test-repo-main/templates/": "", - "test-repo-main/templates/generic/": "", - "test-repo-main/templates/generic/file.txt": "template content", + "test-repo-main/": "", + "test-repo-main/templates/": "", + "test-repo-main/templates/generic/": "", + testArchiveFilePath: "template content", }) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/pkg/scaffold/scaffolder_test.go b/pkg/scaffold/scaffolder_test.go index 76b693ac..9927a1c6 100644 --- a/pkg/scaffold/scaffolder_test.go +++ b/pkg/scaffold/scaffolder_test.go @@ -10,6 +10,19 @@ import ( "github.com/stretchr/testify/assert" ) +const ( + testNameTemplate = "name=<<.Name>>" + testSecondFileName = "file2.txt" + testMockSource = "mock-source" + testName = "test-name" + testTemplateName = "test-template" + testConfigFile = "test.conf" + testWebappTemplate = "webapp" + testConfigPath = "config.conf" + testPackName = "test-pack" + testFileName = "file1.txt" +) + // MockTemplateSource for testing type MockTemplateSource struct { fetchResult string @@ -54,8 +67,8 @@ func (m *MockPrinter) PrintWarn(message string) { } func TestNewScaffolder(t *testing.T) { - mockSource := &MockTemplateSource{stringResult: "mock-source"} - context := TemplateContext{Name: "test-name", DisplayName: "test-name", TemplateName: "test-template"} + mockSource := &MockTemplateSource{stringResult: testMockSource} + context := TemplateContext{Name: testName, DisplayName: testName, TemplateName: testTemplateName} mockPrinter := &MockPrinter{} scaffolder := NewScaffolder(mockSource, "/test/dest", context, true, mockPrinter, false) @@ -66,7 +79,7 @@ func TestNewScaffolder(t *testing.T) { if scaffolder.destination != "/test/dest" { t.Errorf("Expected destination to be '/test/dest', got '%s'", scaffolder.destination) } - if scaffolder.context.Name != "test-name" { + if scaffolder.context.Name != testName { t.Errorf("Expected context.Name to be 'test-name', got '%s'", scaffolder.context.Name) } if scaffolder.force != true { @@ -87,30 +100,30 @@ func TestScaffolder_validateArgs(t *testing.T) { }{ { name: "valid args", - context: TemplateContext{Name: "test-name", DisplayName: "test-name", TemplateName: "test-template"}, + context: TemplateContext{Name: testName, DisplayName: testName, TemplateName: testTemplateName}, sourceErr: nil, wantErr: false, }, { name: "source validation error", - context: TemplateContext{Name: "test-name", TemplateName: "test-template"}, + context: TemplateContext{Name: testName, TemplateName: testTemplateName}, sourceErr: os.ErrInvalid, wantErr: true, expectedErr: "invalid argument", }, { name: "empty name", - context: TemplateContext{Name: "", TemplateName: "test-template"}, + context: TemplateContext{Name: "", TemplateName: testTemplateName}, sourceErr: nil, wantErr: true, expectedErr: "stackpack name is required", }, { - name: "empty template name", - context: TemplateContext{Name: "test-name", TemplateName: ""}, + name: emptyTemplateNameCase, + context: TemplateContext{Name: testName, TemplateName: ""}, sourceErr: nil, wantErr: true, - expectedErr: "template name is required", + expectedErr: templateNameRequiredError, }, } @@ -118,7 +131,7 @@ func TestScaffolder_validateArgs(t *testing.T) { t.Run(tt.name, func(t *testing.T) { mockSource := &MockTemplateSource{ validateError: tt.sourceErr, - stringResult: "mock-source", + stringResult: testMockSource, } mockPrinter := &MockPrinter{} @@ -175,9 +188,9 @@ func TestScaffolder_checkDestinationDirectory(t *testing.T) { tt.destination = destination } - mockSource := &MockTemplateSource{stringResult: "mock-source"} + mockSource := &MockTemplateSource{stringResult: testMockSource} mockPrinter := &MockPrinter{} - context := TemplateContext{Name: "test-name", TemplateName: "test-template"} + context := TemplateContext{Name: testName, TemplateName: testTemplateName} scaffolder := NewScaffolder(mockSource, tt.destination, context, false, mockPrinter, false) err := scaffolder.checkDestinationDirectory() @@ -217,7 +230,7 @@ func TestScaffolder_processTemplate(t *testing.T) { { name: "no template variables", content: "plain text content", - context: TemplateContext{Name: "test-name", TemplateName: "test-template"}, + context: TemplateContext{Name: testName, TemplateName: testTemplateName}, filename: "test.txt", expectedResult: "plain text content", wantErr: false, @@ -225,16 +238,16 @@ func TestScaffolder_processTemplate(t *testing.T) { { name: "template with Name variable", content: "name: <<.Name>>", - context: TemplateContext{Name: "my-stackpack", TemplateName: "generic"}, - filename: "test.conf", + context: TemplateContext{Name: "my-stackpack", TemplateName: testGenericTemplate}, + filename: testConfigFile, expectedResult: "name: my-stackpack", wantErr: false, }, { name: "template with TemplateName variable", content: "template: <<.TemplateName>>", - context: TemplateContext{Name: "my-stackpack", TemplateName: "webapp"}, - filename: "test.conf", + context: TemplateContext{Name: "my-stackpack", TemplateName: testWebappTemplate}, + filename: testConfigFile, expectedResult: "template: webapp", wantErr: false, }, @@ -249,16 +262,16 @@ func TestScaffolder_processTemplate(t *testing.T) { { name: "invalid template syntax", content: "name: <<.InvalidField>>", - context: TemplateContext{Name: "test-name", TemplateName: "test-template"}, - filename: "test.conf", + context: TemplateContext{Name: testName, TemplateName: testTemplateName}, + filename: testConfigFile, wantErr: true, expectedErr: "template execution error", }, { name: "malformed template delimiters", content: "name: <<.Name", - context: TemplateContext{Name: "test-name", TemplateName: "test-template"}, - filename: "test.conf", + context: TemplateContext{Name: testName, TemplateName: testTemplateName}, + filename: testConfigFile, wantErr: false, // Go templates are more permissive, this actually works as literal text expectedResult: "name: <<.Name", }, @@ -266,7 +279,7 @@ func TestScaffolder_processTemplate(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - mockSource := &MockTemplateSource{stringResult: "mock-source"} + mockSource := &MockTemplateSource{stringResult: testMockSource} mockPrinter := &MockPrinter{} scaffolder := NewScaffolder(mockSource, "/test/dest", tt.context, false, mockPrinter, false) @@ -305,11 +318,11 @@ func TestScaffolder_renderTemplates(t *testing.T) { { name: "render text files with templates", setupFiles: map[string]string{ - "config.conf": "name=<<.Name>>", - "readme.md": "# <<.Name>> StackPack\nTemplate: <<.TemplateName>>", - "data.json": `{"name": "<<.Name>>", "template": "<<.TemplateName>>"}`, + testConfigPath: testNameTemplate, + "readme.md": "# <<.Name>> StackPack\nTemplate: <<.TemplateName>>", + "data.json": `{"name": "<<.Name>>", "template": "<<.TemplateName>>"}`, }, - context: TemplateContext{Name: "my-pack", TemplateName: "webapp"}, + context: TemplateContext{Name: "my-pack", TemplateName: testWebappTemplate}, wantErr: false, }, { @@ -318,17 +331,17 @@ func TestScaffolder_renderTemplates(t *testing.T) { "plain.txt": "no template variables here", "script.sh": "#!/bin/bash\necho 'hello world'", }, - context: TemplateContext{Name: "my-pack", TemplateName: "webapp"}, + context: TemplateContext{Name: "my-pack", TemplateName: testWebappTemplate}, wantErr: false, }, { name: "mixed template and non-template files", setupFiles: map[string]string{ - "config.conf": "name=<<.Name>>", + testConfigPath: testNameTemplate, "plain.txt": "static content", "subdir/nested.conf": "template=<<.TemplateName>>", }, - context: TemplateContext{Name: "test-pack", TemplateName: "generic"}, + context: TemplateContext{Name: testPackName, TemplateName: testGenericTemplate}, wantErr: false, }, } @@ -353,7 +366,7 @@ func TestScaffolder_renderTemplates(t *testing.T) { } } - mockSource := &MockTemplateSource{stringResult: "mock-source"} + mockSource := &MockTemplateSource{stringResult: testMockSource} mockPrinter := &MockPrinter{} scaffolder := NewScaffolder(mockSource, "/test/dest", tt.context, false, mockPrinter, false) @@ -424,22 +437,22 @@ func TestScaffolder_checkForConflicts(t *testing.T) { }{ { name: "no conflicts", - sourceFiles: []string{"file1.txt", "file2.txt"}, + sourceFiles: []string{testFileName, testSecondFileName}, destFiles: []string{"other.txt"}, expectedCount: 0, wantErr: false, }, { name: "some conflicts", - sourceFiles: []string{"file1.txt", "file2.txt", "file3.txt"}, - destFiles: []string{"file1.txt", "file3.txt"}, + sourceFiles: []string{testFileName, testSecondFileName, "file3.txt"}, + destFiles: []string{testFileName, "file3.txt"}, expectedCount: 2, wantErr: false, }, { name: "all conflicts", - sourceFiles: []string{"file1.txt", "file2.txt"}, - destFiles: []string{"file1.txt", "file2.txt"}, + sourceFiles: []string{testFileName, testSecondFileName}, + destFiles: []string{testFileName, testSecondFileName}, expectedCount: 2, wantErr: false, }, @@ -477,9 +490,9 @@ func TestScaffolder_checkForConflicts(t *testing.T) { } } - mockSource := &MockTemplateSource{stringResult: "mock-source"} + mockSource := &MockTemplateSource{stringResult: testMockSource} mockPrinter := &MockPrinter{} - context := TemplateContext{Name: "test-name", TemplateName: "test-template"} + context := TemplateContext{Name: testName, TemplateName: testTemplateName} scaffolder := NewScaffolder(mockSource, destDir, context, false, mockPrinter, false) conflicts, err := scaffolder.checkForConflicts(sourceDir, destDir) @@ -504,9 +517,9 @@ func TestScaffolder_checkForConflicts(t *testing.T) { func TestScaffolder_JSONOutput(t *testing.T) { // Create test files map testFiles := map[string]string{ - "config.conf": "name=<<.Name>>", - "readme.md": "# <<.Name>> StackPack", - "static.txt": "no template variables here", + testConfigPath: testNameTemplate, + "readme.md": "# <<.Name>> StackPack", + "static.txt": "no template variables here", } tests := []struct { @@ -552,10 +565,10 @@ func TestScaffolder_JSONOutput(t *testing.T) { mockSource := &MockTemplateSource{ fetchResult: sourceDir, - stringResult: "mock-source", + stringResult: testMockSource, } mockPrinter := &MockPrinter{} - templateCtx := TemplateContext{Name: "test-pack", TemplateName: "test-template"} + templateCtx := TemplateContext{Name: testPackName, TemplateName: testTemplateName} scaffolder := NewScaffolder(mockSource, destDir, templateCtx, false, mockPrinter, tt.jsonOutput) result, cleanup, err := scaffolder.Scaffold(context.TODO()) @@ -569,13 +582,13 @@ func TestScaffolder_JSONOutput(t *testing.T) { if result.Success != true { t.Errorf("Expected success=true, got %v", result.Success) } - if result.Name != "test-pack" { + if result.Name != testPackName { t.Errorf("Expected name='test-pack', got %s", result.Name) } - if result.Template != "test-template" { + if result.Template != testTemplateName { t.Errorf("Expected template='test-template', got %s", result.Template) } - if result.Source != "mock-source" { + if result.Source != testMockSource { t.Errorf("Expected source='mock-source', got %s", result.Source) } if result.FilesCount != len(testFiles) { diff --git a/pkg/scaffold/template_source_test.go b/pkg/scaffold/template_source_test.go index d31d59cb..80248e5f 100644 --- a/pkg/scaffold/template_source_test.go +++ b/pkg/scaffold/template_source_test.go @@ -41,32 +41,32 @@ func TestLocalDirSource_Validate(t *testing.T) { { name: "valid directory with template", path: "", - templateName: "test-template", + templateName: testTemplateName, setupFunc: func(tempDir string) error { - return os.MkdirAll(filepath.Join(tempDir, "test-template"), 0755) + return os.MkdirAll(filepath.Join(tempDir, testTemplateName), 0755) }, wantErr: false, }, { name: "empty path", path: "", - templateName: "test-template", + templateName: testTemplateName, setupFunc: func(tempDir string) error { return nil }, wantErr: true, expectedErr: "template path is required", }, { - name: "empty template name", + name: emptyTemplateNameCase, path: "/test/path", templateName: "", setupFunc: func(tempDir string) error { return nil }, wantErr: true, - expectedErr: "template name is required", + expectedErr: templateNameRequiredError, }, { name: "non-existent directory", path: "/non/existent/path", - templateName: "test-template", + templateName: testTemplateName, setupFunc: func(tempDir string) error { return nil }, wantErr: true, expectedErr: "template directory does not exist: /non/existent/path", @@ -74,7 +74,7 @@ func TestLocalDirSource_Validate(t *testing.T) { { name: "path is a file not directory", path: "", - templateName: "test-template", + templateName: testTemplateName, setupFunc: func(tempDir string) error { return os.WriteFile(tempDir+"/file.txt", []byte("test"), 0644) }, @@ -133,9 +133,9 @@ func TestLocalDirSource_Fetch(t *testing.T) { }{ { name: "successful fetch", - templateName: "test-template", + templateName: testTemplateName, setupFunc: func(tempDir string) error { - return os.MkdirAll(filepath.Join(tempDir, "test-template"), 0755) + return os.MkdirAll(filepath.Join(tempDir, testTemplateName), 0755) }, wantErr: false, }, From 403e2dccf3dee5db81fa395ad7cd1fcba228bed9 Mon Sep 17 00:00:00 2001 From: Remco Beckers Date: Mon, 16 Nov 2026 12:25:27 +0000 Subject: [PATCH 3/3] Keep test literals readable and exclude goconst from tests --- .golangci.yml | 4 + cmd/context/context_delete_test.go | 11 +- cmd/context/context_save_test.go | 71 +++---- cmd/context/context_set_test.go | 6 +- cmd/context/context_show_test.go | 2 +- cmd/context/context_validate_test.go | 2 +- cmd/dashboard/common_test.go | 10 +- cmd/dashboard/dashboard_apply_test.go | 6 +- cmd/dashboard/dashboard_delete_test.go | 4 +- cmd/dashboard/dashboard_describe_test.go | 2 +- cmd/dashboard/dashboard_edit_test.go | 4 +- cmd/dashboard/dashboard_list_test.go | 10 +- cmd/health/health_delete_test.go | 10 +- cmd/health/health_list_test.go | 21 +- cmd/health/health_status_test.go | 86 ++++---- cmd/monitor/monitor_disable_test.go | 4 +- cmd/monitor/monitor_enable_test.go | 4 +- cmd/monitor/monitor_status_test.go | 26 +-- .../otelcomponentmapping_apply_test.go | 17 +- .../otelrelationmapping_apply_test.go | 17 +- .../otelrelationmapping_edit_test.go | 10 +- cmd/rbac/rbac_describe_permissions_test.go | 36 ++-- cmd/rbac/rbac_describe_subjects_test.go | 26 +-- cmd/rbac/rbac_list_permissions_test.go | 8 +- cmd/script/script_run_test.go | 13 +- cmd/servicetoken/servicetoken_create_test.go | 44 ++-- cmd/servicetoken/servicetoken_list_test.go | 10 +- cmd/settings/settings_apply_test.go | 2 +- cmd/settings/settings_list_test.go | 22 +- cmd/settings/settings_list_types_test.go | 15 +- cmd/stackpack/common_test.go | 18 +- .../stackpack_confirm_manual_steps_test.go | 12 +- .../stackpack_delete_version_test.go | 8 +- .../stackpack_delete_versions_test.go | 27 +-- cmd/stackpack/stackpack_describe_test.go | 38 ++-- cmd/stackpack/stackpack_downgrade_test.go | 12 +- cmd/stackpack/stackpack_install_test.go | 35 ++-- .../stackpack_list_instances_test.go | 6 +- .../stackpack_list_parameters_test.go | 8 +- cmd/stackpack/stackpack_list_test.go | 4 +- cmd/stackpack/stackpack_list_versions_test.go | 28 ++- cmd/stackpack/stackpack_package_test.go | 42 ++-- cmd/stackpack/stackpack_scaffold_test.go | 193 +++++++++--------- cmd/stackpack/stackpack_test_deploy_test.go | 51 +++-- cmd/stackpack/stackpack_uninstall_test.go | 16 +- cmd/stackpack/stackpack_upgrade_test.go | 30 +-- cmd/stackpack/stackpack_upload_test.go | 20 +- cmd/stackpack/stackpack_validate_test.go | 16 +- cmd/topic/topic_describe_test.go | 12 +- cmd/topology/topology_inspect_test.go | 76 +++---- cmd/topology/topology_state_test.go | 102 +++++---- cmd/topology/topology_test_helper.go | 18 +- .../topologysync_describe_test.go | 9 +- cmd/topologysync/topologysync_list_test.go | 6 +- internal/client/client_test.go | 36 ++-- internal/config/config_test.go | 48 ++--- internal/printer/printer_test.go | 34 ++- internal/util/string_util_test.go | 23 +-- main_test.go | 32 ++- pkg/pflags/duration_flag_test.go | 6 +- pkg/pflags/relative_time_flag_test.go | 2 +- pkg/scaffold/github_source_test.go | 121 +++++------ pkg/scaffold/scaffolder_test.go | 103 ++++------ pkg/scaffold/template_source_test.go | 18 +- 64 files changed, 735 insertions(+), 978 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 8b9d40e8..b732deef 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -60,6 +60,10 @@ linters: allow-unused: true exclusions: generated: lax + rules: + - path: '(_test|test_helper)\.go$' + linters: + - goconst presets: - comments - common-false-positives diff --git a/cmd/context/context_delete_test.go b/cmd/context/context_delete_test.go index ba2d91e2..4d758532 100644 --- a/cmd/context/context_delete_test.go +++ b/cmd/context/context_delete_test.go @@ -8,17 +8,12 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - testBar = "bar" - nameFlagArg = "--name" -) - func TestDeleteCurrentContext(t *testing.T) { cli := di.NewMockDeps(t) setupConfig(t, &cli) cmd := DeleteCommand(&cli.Deps) - _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, nameFlagArg, "foo") + _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "--name", "foo") assert.Errorf(t, err, "cannot delete the current context (foo)") } @@ -27,7 +22,7 @@ func TestDeleteNonExistingContext(t *testing.T) { setupConfig(t, &cli) cmd := DeleteCommand(&cli.Deps) - _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, nameFlagArg, "x") + _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "--name", "x") assert.Errorf(t, err, "context with name 'x' not found") } @@ -36,7 +31,7 @@ func TestDeleteContext(t *testing.T) { setupConfig(t, &cli) cmd := DeleteCommand(&cli.Deps) - _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, nameFlagArg, testBar) + _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "--name", "bar") assert.NoError(t, err) cfg, err := config.ReadConfig(cli.ConfigPath) diff --git a/cmd/context/context_save_test.go b/cmd/context/context_save_test.go index faab2008..a6f68a17 100644 --- a/cmd/context/context_save_test.go +++ b/cmd/context/context_save_test.go @@ -11,17 +11,6 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - testToken = "my-token" - testContextURL = "http://bar.com" - urlFlagArg = "--url" - testCACertContext = "cacertdata" - testAPIPath = "/api" - serviceTokenFlagArg = "--service-token" - caCertPathFlagArg = "--ca-cert-path" - caCertBase64DataFlagArg = "--ca-cert-base64-data" -) - func setupSaveCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { cli := di.NewMockDeps(t) cmd := SaveCommand(&cli.Deps) @@ -40,13 +29,13 @@ func TestSaveContext(t *testing.T) { //nolint:funlen }{ { name: "new context", - args: []string{nameFlagArg, "baz", urlFlagArg, "http://baz.com", "--api-token", testToken}, + args: []string{"--name", "baz", "--url", "http://baz.com", "--api-token", "my-token"}, expectedContext: config.NamedContext{ Name: "baz", Context: &config.StsContext{ URL: "http://baz.com", - APIToken: testToken, - APIPath: testAPIPath, + APIToken: "my-token", + APIPath: "/api", }, }, totalContextInConfig: 7, @@ -54,13 +43,13 @@ func TestSaveContext(t *testing.T) { //nolint:funlen }, { name: "existing context", - args: []string{nameFlagArg, testBar, urlFlagArg, testContextURL, serviceTokenFlagArg, testToken}, + args: []string{"--name", "bar", "--url", "http://bar.com", "--service-token", "my-token"}, expectedContext: config.NamedContext{ - Name: testBar, + Name: "bar", Context: &config.StsContext{ - URL: testContextURL, - ServiceToken: testToken, - APIPath: testAPIPath, + URL: "http://bar.com", + ServiceToken: "my-token", + APIPath: "/api", }, }, totalContextInConfig: 6, @@ -68,13 +57,13 @@ func TestSaveContext(t *testing.T) { //nolint:funlen }, { name: "existing context ca-cert is set with ca-cert-path", - args: []string{nameFlagArg, testBar, urlFlagArg, testContextURL, serviceTokenFlagArg, testToken, caCertPathFlagArg, "testdata/selfSignedCert.crt"}, + args: []string{"--name", "bar", "--url", "http://bar.com", "--service-token", "my-token", "--ca-cert-path", "testdata/selfSignedCert.crt"}, expectedContext: config.NamedContext{ - Name: testBar, + Name: "bar", Context: &config.StsContext{ - URL: testContextURL, - ServiceToken: testToken, - APIPath: testAPIPath, + URL: "http://bar.com", + ServiceToken: "my-token", + APIPath: "/api", CaCertBase64Data: selfSignedBase64Cert, }, }, @@ -83,13 +72,13 @@ func TestSaveContext(t *testing.T) { //nolint:funlen }, { name: "new context ca-cert is set with ca-cert-path", - args: []string{nameFlagArg, testCACertContext, urlFlagArg, testContextURL, serviceTokenFlagArg, testToken, caCertBase64DataFlagArg, privateCaBase64Cert}, + args: []string{"--name", "cacertdata", "--url", "http://bar.com", "--service-token", "my-token", "--ca-cert-base64-data", privateCaBase64Cert}, expectedContext: config.NamedContext{ - Name: testCACertContext, + Name: "cacertdata", Context: &config.StsContext{ - URL: testContextURL, - ServiceToken: testToken, - APIPath: testAPIPath, + URL: "http://bar.com", + ServiceToken: "my-token", + APIPath: "/api", CaCertBase64Data: privateCaBase64Cert, }, }, @@ -98,13 +87,13 @@ func TestSaveContext(t *testing.T) { //nolint:funlen }, { name: "ca-cert-path takes precedence over ca-cert-base64-data", - args: []string{nameFlagArg, testCACertContext, urlFlagArg, testContextURL, serviceTokenFlagArg, testToken, caCertPathFlagArg, "testdata/selfSignedCert.crt", caCertBase64DataFlagArg, privateCaBase64Cert}, + args: []string{"--name", "cacertdata", "--url", "http://bar.com", "--service-token", "my-token", "--ca-cert-path", "testdata/selfSignedCert.crt", "--ca-cert-base64-data", privateCaBase64Cert}, expectedContext: config.NamedContext{ - Name: testCACertContext, + Name: "cacertdata", Context: &config.StsContext{ - URL: testContextURL, - ServiceToken: testToken, - APIPath: testAPIPath, + URL: "http://bar.com", + ServiceToken: "my-token", + APIPath: "/api", CaCertBase64Data: selfSignedBase64Cert, }, }, @@ -113,13 +102,13 @@ func TestSaveContext(t *testing.T) { //nolint:funlen }, { name: "ca-cert ignored if skip-ssl is set", - args: []string{nameFlagArg, testBar, urlFlagArg, testContextURL, serviceTokenFlagArg, testToken, "--skip-ssl", caCertPathFlagArg, "/path/to/ca.crt", caCertBase64DataFlagArg, "base64-data"}, + args: []string{"--name", "bar", "--url", "http://bar.com", "--service-token", "my-token", "--skip-ssl", "--ca-cert-path", "/path/to/ca.crt", "--ca-cert-base64-data", "base64-data"}, expectedContext: config.NamedContext{ - Name: testBar, + Name: "bar", Context: &config.StsContext{ - URL: testContextURL, - ServiceToken: testToken, - APIPath: testAPIPath, + URL: "http://bar.com", + ServiceToken: "my-token", + APIPath: "/api", SkipSSL: true, CaCertBase64Data: "", CaCertPath: "", @@ -130,14 +119,14 @@ func TestSaveContext(t *testing.T) { //nolint:funlen }, { name: "no save on missing tokens", - args: []string{nameFlagArg, testBar, urlFlagArg, "http://my-bar.com"}, + args: []string{"--name", "bar", "--url", "http://my-bar.com"}, expectedContext: config.NamedContext{}, wantErr: true, errorMessage: "one of the required flags {api-token | service-token} not set", }, { name: "ca-cert-path is not found", - args: []string{nameFlagArg, testBar, urlFlagArg, "http://my-bar.com", serviceTokenFlagArg, testToken, caCertPathFlagArg, "/path/to/ca.crt"}, + args: []string{"--name", "bar", "--url", "http://my-bar.com", "--service-token", "my-token", "--ca-cert-path", "/path/to/ca.crt"}, expectedContext: config.NamedContext{}, wantErr: true, errorMessage: "no such file or directory", diff --git a/cmd/context/context_set_test.go b/cmd/context/context_set_test.go index 8deae131..d733e389 100644 --- a/cmd/context/context_set_test.go +++ b/cmd/context/context_set_test.go @@ -13,12 +13,12 @@ func TestSetContext(t *testing.T) { setupConfig(t, &cli) cmd := SetCommand(&cli.Deps) - _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, nameFlagArg, testBar) + _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "--name", "bar") assert.NoError(t, err) cfg, err := config.ReadConfig(cli.ConfigPath) assert.NoError(t, err) - assert.Equal(t, testBar, cfg.CurrentContext) + assert.Equal(t, "bar", cfg.CurrentContext) } func TestSetUnknownContext(t *testing.T) { @@ -26,7 +26,7 @@ func TestSetUnknownContext(t *testing.T) { setupConfig(t, &cli) cmd := SetCommand(&cli.Deps) - _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, nameFlagArg, "x") + _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "--name", "x") assert.Errorf(t, err, "context with name 'x' not found") cfg, err := config.ReadConfig(cli.ConfigPath) diff --git a/cmd/context/context_show_test.go b/cmd/context/context_show_test.go index 4c6d178b..d0860d25 100644 --- a/cmd/context/context_show_test.go +++ b/cmd/context/context_show_test.go @@ -24,7 +24,7 @@ func TestShowContextJSON(t *testing.T) { assert.Equal(t, &config.StsContext{ URL: "http://foo.com", APIToken: "apiToken", - APIPath: testAPIPath, + APIPath: "/api", }, calls[0]["current-context"]) } diff --git a/cmd/context/context_validate_test.go b/cmd/context/context_validate_test.go index 722b6f03..491dbc48 100644 --- a/cmd/context/context_validate_test.go +++ b/cmd/context/context_validate_test.go @@ -32,7 +32,7 @@ func TestValidationToJson(t *testing.T) { di.ExecuteCommandWithContextUnsafe( &cli.Deps, cmd, - urlFlagArg, + "--url", "https://test.stackstate.io/", "--api-token", "blaat", diff --git a/cmd/dashboard/common_test.go b/cmd/dashboard/common_test.go index fdf38974..cb27cf7e 100644 --- a/cmd/dashboard/common_test.go +++ b/cmd/dashboard/common_test.go @@ -6,10 +6,6 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - testDashboardURN = "urn:custom:dashboard:test" -) - func TestResolveDashboardIdOrUrn(t *testing.T) { tests := []struct { name string @@ -28,14 +24,14 @@ func TestResolveDashboardIdOrUrn(t *testing.T) { { name: "Should resolve valid identifier", id: 0, - identifier: testDashboardURN, - expectedResult: testDashboardURN, + identifier: "urn:custom:dashboard:test", + expectedResult: "urn:custom:dashboard:test", expectedError: "", }, { name: "Should prioritize ID when both are provided", id: 456, - identifier: testDashboardURN, + identifier: "urn:custom:dashboard:test", expectedResult: "456", expectedError: "", }, diff --git a/cmd/dashboard/dashboard_apply_test.go b/cmd/dashboard/dashboard_apply_test.go index f1660dbf..3e9b3aaa 100644 --- a/cmd/dashboard/dashboard_apply_test.go +++ b/cmd/dashboard/dashboard_apply_test.go @@ -10,10 +10,6 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - testGrid = "Grid" -) - func setDashboardApplyCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { cli := di.NewMockDeps(t) cmd := DashboardApplyCommand(&cli.Deps) @@ -31,7 +27,7 @@ func createTestApplyResult() sts.DashboardReadFullSchema { Spec: &sts.PersesDashboardSpec{ Layouts: []sts.PersesLayout{ { - Kind: testGrid, + Kind: "Grid", Spec: sts.PersesLayoutSpec{ Items: []sts.PersesGridItem{}, }, diff --git a/cmd/dashboard/dashboard_delete_test.go b/cmd/dashboard/dashboard_delete_test.go index 51ca9b63..90789ea6 100644 --- a/cmd/dashboard/dashboard_delete_test.go +++ b/cmd/dashboard/dashboard_delete_test.go @@ -28,11 +28,11 @@ func TestShouldDeleteDashboard(t *testing.T) { func TestShouldDeleteDashboardWithIdentifier(t *testing.T) { cli, cmd := setDashboardDeleteCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--identifier", testDashboardURN) + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--identifier", "urn:custom:dashboard:test") assert.Len(t, *cli.MockClient.ApiMocks.DashboardsApi.DeleteDashboardCalls, 1) deleteCall := (*cli.MockClient.ApiMocks.DashboardsApi.DeleteDashboardCalls)[0] - assert.Equal(t, testDashboardURN, deleteCall.PdashboardIdOrUrn) + assert.Equal(t, "urn:custom:dashboard:test", deleteCall.PdashboardIdOrUrn) assert.Equal(t, "Dashboard deleted: urn:custom:dashboard:test", (*cli.MockPrinter.SuccessCalls)[0]) } diff --git a/cmd/dashboard/dashboard_describe_test.go b/cmd/dashboard/dashboard_describe_test.go index e785d8b3..c6de4ca7 100644 --- a/cmd/dashboard/dashboard_describe_test.go +++ b/cmd/dashboard/dashboard_describe_test.go @@ -27,7 +27,7 @@ func createTestDashboard() sts.DashboardReadSchema { Spec: &sts.PersesDashboardSpec{ Layouts: []sts.PersesLayout{ { - Kind: testGrid, + Kind: "Grid", Spec: sts.PersesLayoutSpec{ Items: []sts.PersesGridItem{}, }, diff --git a/cmd/dashboard/dashboard_edit_test.go b/cmd/dashboard/dashboard_edit_test.go index 65a74824..eac581cf 100644 --- a/cmd/dashboard/dashboard_edit_test.go +++ b/cmd/dashboard/dashboard_edit_test.go @@ -41,7 +41,7 @@ func createEditTestDashboard() sts.DashboardReadSchema { Spec: &sts.PersesDashboardSpec{ Layouts: []sts.PersesLayout{ { - Kind: testGrid, + Kind: "Grid", Spec: sts.PersesLayoutSpec{ Items: []sts.PersesGridItem{}, }, @@ -65,7 +65,7 @@ func createEditResult() sts.DashboardReadFullSchema { Spec: &sts.PersesDashboardSpec{ Layouts: []sts.PersesLayout{ { - Kind: testGrid, + Kind: "Grid", Spec: sts.PersesLayoutSpec{ Items: []sts.PersesGridItem{}, }, diff --git a/cmd/dashboard/dashboard_list_test.go b/cmd/dashboard/dashboard_list_test.go index 2c4b18d2..c7833810 100644 --- a/cmd/dashboard/dashboard_list_test.go +++ b/cmd/dashboard/dashboard_list_test.go @@ -10,10 +10,6 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - testDashboards = "dashboards" -) - var ( firstDashboardName = "aDashboard" firstDashboardId = int64(1) @@ -87,7 +83,7 @@ func TestDashboardListPrintToTable(t *testing.T) { Data: [][]interface{}{ {firstDashboardId, firstDashboardIdentifier, firstDashboardName, firstDashboardDescription, firstDashboardScope}, {secondDashboardId, secondDashboardIdentifier, secondDashboardName, secondDashboardDescription, secondDashboardScope}}, - MissingTableDataMsg: printer.NotFoundMsg{Types: testDashboards}, + MissingTableDataMsg: printer.NotFoundMsg{Types: "dashboards"}, }, } assert.Equal(t, expectedTableCall, *cli.MockPrinter.TableCalls) @@ -100,7 +96,7 @@ func TestDashboardListPrintToJson(t *testing.T) { di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list", "--output", "json") expectedJsonCall := []map[string]interface{}{ { - testDashboards: orderedArray, + "dashboards": orderedArray, }, } assert.Equal(t, expectedJsonCall, *cli.MockPrinter.PrintJsonCalls) @@ -116,7 +112,7 @@ func TestDashboardListEmptyResults(t *testing.T) { { Header: []string{"Id", "Identifier", "Name", "Description", "Scope"}, Data: [][]interface{}{}, - MissingTableDataMsg: printer.NotFoundMsg{Types: testDashboards}, + MissingTableDataMsg: printer.NotFoundMsg{Types: "dashboards"}, }, } assert.Equal(t, expectedTableCall, *cli.MockPrinter.TableCalls) diff --git a/cmd/health/health_delete_test.go b/cmd/health/health_delete_test.go index b0b25848..222eaa24 100644 --- a/cmd/health/health_delete_test.go +++ b/cmd/health/health_delete_test.go @@ -9,10 +9,6 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - testHealthStreamURN = "urn:health:self_monitoring:self_monitoring_scraper" -) - func setupHealthDeleteCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { cli := di.NewMockDeps(t) cmd := HealthDeleteCommand(&cli.Deps) @@ -23,7 +19,7 @@ func setupHealthDeleteCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { func TestHealthDeletePrintToTable(t *testing.T) { cli, cmd := setupHealthDeleteCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete", "--urn", testHealthStreamURN) + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete", "--urn", "urn:health:self_monitoring:self_monitoring_scraper") assert.Equal(t, []string{"Stream deleted: urn:health:self_monitoring:self_monitoring_scraper"}, *cli.MockPrinter.SuccessCalls) assert.True(t, cli.MockPrinter.HasNonJsonCalls) @@ -31,10 +27,10 @@ func TestHealthDeletePrintToTable(t *testing.T) { func TestHealthDeletePrintToJson(t *testing.T) { cli, cmd := setupHealthDeleteCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete", "--urn", testHealthStreamURN, "-o", "json") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete", "--urn", "urn:health:self_monitoring:self_monitoring_scraper", "-o", "json") assert.Equal(t, []map[string]interface{}{{ - "deleted-stream-urn": testHealthStreamURN, + "deleted-stream-urn": "urn:health:self_monitoring:self_monitoring_scraper", }}, *cli.MockPrinter.PrintJsonCalls, ) diff --git a/cmd/health/health_list_test.go b/cmd/health/health_list_test.go index 1e756037..bf3c5008 100644 --- a/cmd/health/health_list_test.go +++ b/cmd/health/health_list_test.go @@ -10,24 +10,19 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - testRepeatSnapshots = "REPEAT_SNAPSHOTS" - testServerName = "SUSE Observability Server" -) - func setupHealthListCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { cli := di.NewMockDeps(t) cmd := HealthListCommand(&cli.Deps) cli.MockClient.ApiMocks.HealthSynchronizationApi.GetHealthSynchronizationStreamsOverviewResponse.Result = stackstate_api.StreamList{ Items: []stackstate_api.StreamListItem{{ - Urn: testHealthStreamURN, - ConsistencyModel: testRepeatSnapshots, + Urn: "urn:health:self_monitoring:self_monitoring_scraper", + ConsistencyModel: "REPEAT_SNAPSHOTS", SubStreams: 1, }}, } cli.MockClient.ApiMocks.HealthSynchronizationApi.GetHealthSynchronizationSubStreamOverviewResponse.Result = stackstate_api.SubStreamList{ SubStreams: []stackstate_api.SubStreamListItem{{ - SubStreamId: testServerName, + SubStreamId: "SUSE Observability Server", CheckStateCount: 36, }}, } @@ -41,7 +36,7 @@ func TestHealthListPrintToTable(t *testing.T) { expectedTableCall := []printer.TableData{ { Header: []string{"Stream urn", "Stream consistency model", "Sub stream count"}, - Data: [][]interface{}{{testHealthStreamURN, testRepeatSnapshots, int32(1)}}, + Data: [][]interface{}{{"urn:health:self_monitoring:self_monitoring_scraper", "REPEAT_SNAPSHOTS", int32(1)}}, MissingTableDataMsg: printer.NotFoundMsg{Types: "health stream"}, }, } @@ -55,8 +50,8 @@ func TestHealthListPrintToJson(t *testing.T) { assert.Equal(t, []map[string]interface{}{{ "streams": []map[string]interface{}{{ - "stream_urn": testHealthStreamURN, - "stream_consistency_model": testRepeatSnapshots, + "stream_urn": "urn:health:self_monitoring:self_monitoring_scraper", + "stream_consistency_model": "REPEAT_SNAPSHOTS", "sub_stream_count": int32(1), }}, }}, @@ -71,7 +66,7 @@ func TestHealthListUrnPrintToTable(t *testing.T) { expectedTableCall := []printer.TableData{ { Header: []string{"Sub stream id", "Check state count"}, - Data: [][]interface{}{{testServerName, int32(36)}}, + Data: [][]interface{}{{"SUSE Observability Server", int32(36)}}, MissingTableDataMsg: printer.NotFoundMsg{Types: "health sub-stream"}, }, } @@ -85,7 +80,7 @@ func TestHealthListUrnPrintToJson(t *testing.T) { assert.Equal(t, []map[string]interface{}{{ "sub-stream": []map[string]interface{}{{ - "sub_stream_id": testServerName, + "sub_stream_id": "SUSE Observability Server", "check_state_count": int32(36), }}, }}, diff --git a/cmd/health/health_status_test.go b/cmd/health/health_status_test.go index cdbcfa94..d8a6a8a9 100644 --- a/cmd/health/health_status_test.go +++ b/cmd/health/health_status_test.go @@ -10,16 +10,6 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - testUnknownHealthState = ":shrug:" - testHealthStreamError = "health stream error" - testName = "name" - testLastTenSeconds = "now-10" - testFirstMetricRange = "10-20" - testSecondMetricRange = "20-30" - testMetricLatency = "2000 ms" -) - var ( recoveryMessage = "status recovery message" @@ -40,62 +30,62 @@ var ( } SomeErrors = []stackstate_api.HealthStreamError{ { - Error: testUnknownHealthState, + Error: ":shrug:", }, { - Error: testHealthStreamError, + Error: "health stream error", }, } ExpectedErrorsJson = []map[string]interface{}{ { "count": int32(0), - "message": testUnknownHealthState, + "message": ":shrug:", }, { "count": int32(0), - "message": testHealthStreamError, + "message": "health stream error", }, } ExpectedErrorsTable = printer.TableData{ Header: []string{"Message", "Count"}, Data: [][]interface{}{ - {testUnknownHealthState, int32(0)}, - {testHealthStreamError, int32(0)}, + {":shrug:", int32(0)}, + {"health stream error", int32(0)}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: errorsKey}, + MissingTableDataMsg: printer.NotFoundMsg{Types: "errors"}, } ExpectedMetricsJson = []map[string]interface{}{ { - testName: "latency seconds", - testLastTenSeconds: float64(23.5), - testFirstMetricRange: float64(23.5), - testSecondMetricRange: float64(23.5), + "name": "latency seconds", + "now-10": float64(23.5), + "10-20": float64(23.5), + "20-30": float64(23.5), }, { - testName: "messages per seconds", - testLastTenSeconds: float64(23.5), - testFirstMetricRange: float64(23.5), - testSecondMetricRange: "-", + "name": "messages per seconds", + "now-10": float64(23.5), + "10-20": float64(23.5), + "20-30": "-", }, { - testName: "creates per seconds", - testLastTenSeconds: float64(23.5), - testFirstMetricRange: "-", - testSecondMetricRange: "-", + "name": "creates per seconds", + "now-10": float64(23.5), + "10-20": "-", + "20-30": "-", }, { - testName: "updates per seconds", - testLastTenSeconds: "-", - testFirstMetricRange: "-", - testSecondMetricRange: "-", + "name": "updates per seconds", + "now-10": "-", + "10-20": "-", + "20-30": "-", }, { - testName: "deletes per seconds", - testLastTenSeconds: "-", - testFirstMetricRange: "-", - testSecondMetricRange: "-", + "name": "deletes per seconds", + "now-10": "-", + "10-20": "-", + "20-30": "-", }, } ExpectedMetricsTable = printer.TableData{ @@ -107,7 +97,7 @@ var ( {"updates per seconds", "-", "-", "-"}, {"deletes per seconds", "-", "-", "-"}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: metricsKey}, + MissingTableDataMsg: printer.NotFoundMsg{Types: "metrics"}, } ) @@ -195,9 +185,9 @@ func TestHealthStatusWithSubStreamPrintToText(t *testing.T) { { Header: []string{"Repeat Interval", "Expiry Interval", "Snapshot Repeat Interval", "Snapshot Expiry Interval", "Checkpoint Offset", "Checkpoint Batch Index"}, Data: [][]interface{}{ - {testMetricLatency, testMetricLatency, "-", "-", "-", "-"}, + {"2000 ms", "2000 ms", "-", "-", "-", "-"}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: errorsKey}, + MissingTableDataMsg: printer.NotFoundMsg{Types: "errors"}, }, ExpectedMetricsTable, ExpectedErrorsTable, @@ -216,8 +206,8 @@ func TestHealthStatusWithSubStreamPrintToJson(t *testing.T) { "expiry-interval": int32(2000), "repeat-interval": int32(2000), }, - errorsKey: ExpectedErrorsJson, - metricsKey: ExpectedMetricsJson, + "errors": ExpectedErrorsJson, + "metrics": ExpectedMetricsJson, }, }, *cli.MockPrinter.PrintJsonCalls) } @@ -242,9 +232,9 @@ func TestHealthStatusStreamPrintToText(t *testing.T) { { Header: []string{"Repeat Interval", "Expiry Interval", "Snapshot Repeat Interval", "Snapshot Expiry Interval", "Checkpoint Offset", "Checkpoint Batch Index"}, Data: [][]interface{}{ - {testMetricLatency, testMetricLatency, "-", "-", "-", "-"}, + {"2000 ms", "2000 ms", "-", "-", "-", "-"}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: errorsKey}, + MissingTableDataMsg: printer.NotFoundMsg{Types: "errors"}, }, ExpectedMetricsTable, ExpectedErrorsTable, @@ -265,11 +255,11 @@ func TestHealthStatusStreamPrintToJson(t *testing.T) { "expiry-interval": int32(2000), "repeat-interval": int32(2000), }, - errorsKey: ExpectedErrorsJson, - metricsKey: ExpectedMetricsJson, + "errors": ExpectedErrorsJson, + "metrics": ExpectedMetricsJson, }, - errorsKey: ExpectedErrorsJson, - metricsKey: ExpectedMetricsJson, + "errors": ExpectedErrorsJson, + "metrics": ExpectedMetricsJson, }, }, *cli.MockPrinter.PrintJsonCalls) } diff --git a/cmd/monitor/monitor_disable_test.go b/cmd/monitor/monitor_disable_test.go index 55175e7c..b9604fda 100644 --- a/cmd/monitor/monitor_disable_test.go +++ b/cmd/monitor/monitor_disable_test.go @@ -27,7 +27,7 @@ func TestMonitorDisableByIdJson(t *testing.T) { checkMonitorPatchStatusCall(t, cli.MockClient.ApiMocks.MonitorApi.PatchMonitorCalls, sts.MONITORSTATUSVALUE_DISABLED.Ptr()) expectedJsonCalls := []map[string]interface{}{{ - monitorKey: &monitor, + "monitor": &monitor, }} assert.Equal(t, expectedJsonCalls, *cli.MockPrinter.PrintJsonCalls) assert.False(t, cli.MockPrinter.HasNonJsonCalls) @@ -53,7 +53,7 @@ func TestMonitorDisableByIdentifierJson(t *testing.T) { checkMonitorPatchStatusCall(t, cli.MockClient.ApiMocks.MonitorApi.PatchMonitorCalls, sts.MONITORSTATUSVALUE_DISABLED.Ptr()) checkMonitorPatchStatusCall(t, cli.MockClient.ApiMocks.MonitorApi.PatchMonitorCalls, sts.MONITORSTATUSVALUE_DISABLED.Ptr()) expectedJsonCalls := []map[string]interface{}{{ - monitorKey: &monitor, + "monitor": &monitor, }} assert.Equal(t, expectedJsonCalls, *cli.MockPrinter.PrintJsonCalls) assert.False(t, cli.MockPrinter.HasNonJsonCalls) diff --git a/cmd/monitor/monitor_enable_test.go b/cmd/monitor/monitor_enable_test.go index 95f57b76..3bc19fc6 100644 --- a/cmd/monitor/monitor_enable_test.go +++ b/cmd/monitor/monitor_enable_test.go @@ -27,7 +27,7 @@ func TestMonitorEnableByIdJson(t *testing.T) { checkMonitorPatchStatusCall(t, cli.MockClient.ApiMocks.MonitorApi.PatchMonitorCalls, sts.MONITORSTATUSVALUE_ENABLED.Ptr()) expectedJsonCalls := []map[string]interface{}{{ - monitorKey: &monitor, + "monitor": &monitor, }} assert.Equal(t, expectedJsonCalls, *cli.MockPrinter.PrintJsonCalls) assert.False(t, cli.MockPrinter.HasNonJsonCalls) @@ -52,7 +52,7 @@ func TestMonitorEnableByIdentifierJson(t *testing.T) { checkMonitorPatchStatusCall(t, cli.MockClient.ApiMocks.MonitorApi.PatchMonitorCalls, sts.MONITORSTATUSVALUE_ENABLED.Ptr()) expectedJsonCalls := []map[string]interface{}{{ - monitorKey: &monitor, + "monitor": &monitor, }} assert.Equal(t, expectedJsonCalls, *cli.MockPrinter.PrintJsonCalls) assert.False(t, cli.MockPrinter.HasNonJsonCalls) diff --git a/cmd/monitor/monitor_status_test.go b/cmd/monitor/monitor_status_test.go index 9b851e33..eaedcc9b 100644 --- a/cmd/monitor/monitor_status_test.go +++ b/cmd/monitor/monitor_status_test.go @@ -10,12 +10,6 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - testError = "Error" - testMonitorErrorStatus = "Monitor Status: ERROR" - testMonitorTimeWindow = "value between 0 and 0 seconds ago" -) - var ( count = int32(3) lastRunTimestamp = int64(1663079675007) @@ -34,7 +28,7 @@ var ( healthStateCount int32 = 10 unmappedHealthStateCount int32 = 1 monitorError = sts.MonitorError{ - Error: testError, + Error: "Error", Count: 11, } metrics = sts.MonitorMetrics{ @@ -114,16 +108,16 @@ func TestMonitorStatusPrintsToTable(t *testing.T) { di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "-i", "211684343791306") - expectedPrintlnCalls := []string{"", "Monitor Health State count: 10", testMonitorErrorStatus, "", "Monitor Stream errors:", "", "Monitor Stream metrics:", "", + expectedPrintlnCalls := []string{"", "Monitor Health State count: 10", "Monitor Status: ERROR", "", "Monitor Stream errors:", "", "Monitor Stream metrics:", "", "Monitor health states with identifier matching exactly 1 topology element: 0"} expectedTableCall := []printer.TableData{ { Header: []string{"message", "occurrence count"}, - Data: [][]interface{}{{testError, int32(11)}}, + Data: [][]interface{}{{"Error", int32(11)}}, }, { - Header: []string{"metric", "value between now and 0 seconds ago", testMonitorTimeWindow, - testMonitorTimeWindow}, + Header: []string{"metric", "value between now and 0 seconds ago", "value between 0 and 0 seconds ago", + "value between 0 and 0 seconds ago"}, Data: [][]interface{}{{"latency (Seconds)"}, {"messages processed (per second)"}, {"monitor health states created (per second)"}, {"monitor health states updated (per second)"}, {"monitor health states deleted (per second)"}}, @@ -140,7 +134,7 @@ func TestMonitorStatusWithHealthStatesCountsPrintsToTable(t *testing.T) { di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "-i", "211684343791306") - expectedPrintlnCalls := []string{"", "Monitor Health State count: 10", testMonitorErrorStatus, "Monitor last run: 2022-09-13 14:34:35.007 +0000 UTC", + expectedPrintlnCalls := []string{"", "Monitor Health State count: 10", "Monitor Status: ERROR", "Monitor last run: 2022-09-13 14:34:35.007 +0000 UTC", "", "Monitor Stream errors:", "", "Monitor health states mapped to topology:", "", "Monitor Stream metrics:", "", "Monitor health states with identifier matching exactly 1 topology element: 0", "", "Monitor health states with identifier which has no matching topology element (1):"} @@ -148,15 +142,15 @@ func TestMonitorStatusWithHealthStatesCountsPrintsToTable(t *testing.T) { expectedTableCall := []printer.TableData{ { Header: []string{"message", "occurrence count"}, - Data: [][]interface{}{{testError, int32(11)}}, + Data: [][]interface{}{{"Error", int32(11)}}, }, { Header: []string{"HealthState", "count"}, Data: [][]interface{}{{"CLEAR", count}, {"DEVIATING", count}, {"CRITICAL", count}, {"UNKNOWN", count}}, }, { - Header: []string{"metric", "value between now and 0 seconds ago", testMonitorTimeWindow, - testMonitorTimeWindow}, + Header: []string{"metric", "value between now and 0 seconds ago", "value between 0 and 0 seconds ago", + "value between 0 and 0 seconds ago"}, Data: [][]interface{}{{"latency (Seconds)"}, {"messages processed (per second)"}, {"monitor health states created (per second)"}, {"monitor health states updated (per second)"}, {"monitor health states deleted (per second)"}}, @@ -177,7 +171,7 @@ func TestMonitorStatusForDisabled(t *testing.T) { di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "-i", "211684343791306") - expectedPrintlnCalls := []string{"", "Monitor Health State count: -", testMonitorErrorStatus} + expectedPrintlnCalls := []string{"", "Monitor Health State count: -", "Monitor Status: ERROR"} expectedTableCall := []printer.TableData{} assert.Equal(t, expectedPrintlnCalls, *cli.MockPrinter.PrintLnCalls) diff --git a/cmd/otelcomponentmapping/otelcomponentmapping_apply_test.go b/cmd/otelcomponentmapping/otelcomponentmapping_apply_test.go index b26d5902..923df0a4 100644 --- a/cmd/otelcomponentmapping/otelcomponentmapping_apply_test.go +++ b/cmd/otelcomponentmapping/otelcomponentmapping_apply_test.go @@ -13,11 +13,6 @@ import ( "gopkg.in/yaml.v2" ) -const ( - testMappingName = "my-mapping" - testMappingURN = "urn:otel:component:foo" -) - func createTempYamlFile(t *testing.T, content string) string { t.Helper() tmpfile, err := os.CreateTemp(os.TempDir(), "test_componentmapping_*.yaml") @@ -42,8 +37,8 @@ func TestOtelComponentMappingApply_SuccessYaml(t *testing.T) { cli := di.NewMockDeps(t) cmd := otelcomponentmapping.OtelComponentMappingApplyCommand(&cli.Deps) mapping := stackstate_api.OtelComponentMapping{ - Name: testMappingName, - Identifier: testMappingURN, + Name: "my-mapping", + Identifier: "urn:otel:component:foo", } yamlContent, err := yaml.Marshal(mapping) assert.NoError(t, err) @@ -65,8 +60,8 @@ func TestOtelComponentMappingApply_SuccessJson(t *testing.T) { cli := di.NewMockDeps(t) cmd := otelcomponentmapping.OtelComponentMappingApplyCommand(&cli.Deps) mapping := stackstate_api.OtelComponentMapping{ - Name: testMappingName, - Identifier: testMappingURN, + Name: "my-mapping", + Identifier: "urn:otel:component:foo", } yamlContent, err := yaml.Marshal(mapping) assert.NoError(t, err) @@ -130,8 +125,8 @@ func TestOtelComponentMappingApply_ApiError(t *testing.T) { cli := di.NewMockDeps(t) cmd := otelcomponentmapping.OtelComponentMappingApplyCommand(&cli.Deps) mapping := stackstate_api.OtelComponentMapping{ - Name: testMappingName, - Identifier: testMappingURN, + Name: "my-mapping", + Identifier: "urn:otel:component:foo", } yamlContent, err := yaml.Marshal(mapping) assert.NoError(t, err) diff --git a/cmd/otelrelationmapping/otelrelationmapping_apply_test.go b/cmd/otelrelationmapping/otelrelationmapping_apply_test.go index b4cd7afd..80e5481f 100644 --- a/cmd/otelrelationmapping/otelrelationmapping_apply_test.go +++ b/cmd/otelrelationmapping/otelrelationmapping_apply_test.go @@ -13,11 +13,6 @@ import ( "gopkg.in/yaml.v2" ) -const ( - testMappingName = "my-relation-mapping" - testMappingURN = "urn:otel:relation:foo" -) - func createTempYamlFile(t *testing.T, content string) string { t.Helper() tmpfile, err := os.CreateTemp(os.TempDir(), "test_relationmapping_*.yaml") @@ -42,8 +37,8 @@ func TestOtelRelationMappingApply_SuccessYaml(t *testing.T) { cli := di.NewMockDeps(t) cmd := otelrelationmapping.OtelRelationMappingApplyCommand(&cli.Deps) mapping := stackstate_api.UpsertOtelRelationMappingsRequest{ - Name: testMappingName, - Identifier: testMappingURN, + Name: "my-relation-mapping", + Identifier: "urn:otel:relation:foo", } yamlContent, err := yaml.Marshal(mapping) assert.NoError(t, err) @@ -65,8 +60,8 @@ func TestOtelRelationMappingApply_SuccessJson(t *testing.T) { cli := di.NewMockDeps(t) cmd := otelrelationmapping.OtelRelationMappingApplyCommand(&cli.Deps) mapping := stackstate_api.UpsertOtelRelationMappingsRequest{ - Name: testMappingName, - Identifier: testMappingURN, + Name: "my-relation-mapping", + Identifier: "urn:otel:relation:foo", } yamlContent, err := yaml.Marshal(mapping) assert.NoError(t, err) @@ -117,8 +112,8 @@ func TestOtelRelationMappingApply_ApiError(t *testing.T) { cli := di.NewMockDeps(t) cmd := otelrelationmapping.OtelRelationMappingApplyCommand(&cli.Deps) mapping := stackstate_api.UpsertOtelRelationMappingsRequest{ - Name: testMappingName, - Identifier: testMappingURN, + Name: "my-relation-mapping", + Identifier: "urn:otel:relation:foo", } yamlContent, err := yaml.Marshal(mapping) assert.NoError(t, err) diff --git a/cmd/otelrelationmapping/otelrelationmapping_edit_test.go b/cmd/otelrelationmapping/otelrelationmapping_edit_test.go index 101ca921..8be9fdaf 100644 --- a/cmd/otelrelationmapping/otelrelationmapping_edit_test.go +++ b/cmd/otelrelationmapping/otelrelationmapping_edit_test.go @@ -13,10 +13,6 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - testOrig = "orig" -) - type mockEditorStub struct { content []byte err error @@ -35,7 +31,7 @@ func TestOtelRelationMappingEdit_SuccessYAML(t *testing.T) { mockIdentifier := "urn:otel:relation:edit-success" orig := stackstate_api.OtelRelationMapping{ Identifier: mockIdentifier, - Name: testOrig, + Name: "orig", } cli.MockClient.ApiMocks.OtelMappingApi.GetOtelRelationMappingResponse.Result = orig // YAML of edited mapping @@ -119,7 +115,7 @@ func TestOtelRelationMappingEdit_EditorError(t *testing.T) { cli := di.NewMockDeps(t) cmd := otelrelationmapping.OtelRelationMappingEditCommand(&cli.Deps) mockIdentifier := "urn:otel:relation:editorfail" - orig := stackstate_api.OtelRelationMapping{Identifier: mockIdentifier, Name: testOrig} + orig := stackstate_api.OtelRelationMapping{Identifier: mockIdentifier, Name: "orig"} cli.MockClient.ApiMocks.OtelMappingApi.GetOtelRelationMappingResponse.Result = orig cli.Editor = &mockEditorStub{err: errors.New("editor failure")} @@ -136,7 +132,7 @@ func TestOtelRelationMappingEdit_InvalidYAML(t *testing.T) { cli := di.NewMockDeps(t) cmd := otelrelationmapping.OtelRelationMappingEditCommand(&cli.Deps) mockIdentifier := "urn:otel:relation:bad-yaml" - orig := stackstate_api.OtelRelationMapping{Identifier: mockIdentifier, Name: testOrig} + orig := stackstate_api.OtelRelationMapping{Identifier: mockIdentifier, Name: "orig"} cli.MockClient.ApiMocks.OtelMappingApi.GetOtelRelationMappingResponse.Result = orig cli.Editor = &mockEditorStub{content: []byte("not: valid:: yaml::")} diff --git a/cmd/rbac/rbac_describe_permissions_test.go b/cmd/rbac/rbac_describe_permissions_test.go index 18009a2b..ef19706f 100644 --- a/cmd/rbac/rbac_describe_permissions_test.go +++ b/cmd/rbac/rbac_describe_permissions_test.go @@ -9,20 +9,14 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - testFoo = "foo" - testBar = "bar" - testBaz = "baz" -) - var ( - Set1 = []string{testFoo, testBar, testBaz} + Set1 = []string{"foo", "bar", "baz"} Resource1 = "some-view" Permissions1 = map[string][]string{ Resource1: Set1, } - Set2 = []string{testFoo, "fai", "fum"} + Set2 = []string{"foo", "fai", "fum"} Resource2 = "system" Permissions2 = map[string][]string{ Resource2: Set2, @@ -37,23 +31,23 @@ var ( ExpectedTable = printer.TableData{ Header: []string{"permission", "resource"}, Data: [][]interface{}{ - {testBar, Resource1}, - {testBaz, Resource1}, - {testFoo, Resource1}, + {"bar", Resource1}, + {"baz", Resource1}, + {"foo", Resource1}, {"fai", Resource2}, - {testFoo, Resource2}, + {"foo", Resource2}, {"fum", Resource2}, }, MissingTableDataMsg: printer.NotFoundMsg{Types: "matching permissions"}, } ExpectedJson = map[string]interface{}{ - "subject": SubjectHandle, - permissionsKey: AllPermissions, + "subject": SubjectHandle, + "permissions": AllPermissions, } ExpectedSourcesJson = map[string]interface{}{ - "subject": SubjectHandle, - permissionsKey: AllPermissions, - "sources": []string{"Static"}, + "subject": SubjectHandle, + "permissions": AllPermissions, + "sources": []string{"Static"}, } ) @@ -114,12 +108,12 @@ func TestPermissionsDescribeFilterPermission(t *testing.T) { cli.MockClient.ApiMocks.PermissionsApi.DescribePermissionsResponse.Result = *Description - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--subject", SubjectHandle, "--permission", testFoo) + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--subject", SubjectHandle, "--permission", "foo") calls := *cli.MockClient.ApiMocks.PermissionsApi.DescribePermissionsCalls assert.Len(t, calls, 1) assert.Equal(t, SubjectHandle, calls[0].Psubject) - assert.Equal(t, testFoo, *calls[0].Ppermission) + assert.Equal(t, "foo", *calls[0].Ppermission) assert.Nil(t, calls[0].Presource) } @@ -145,12 +139,12 @@ func TestPermissionsDescribeFilterResourceAndPermission(t *testing.T) { cli.MockClient.ApiMocks.PermissionsApi.DescribePermissionsResponse.Result = *Description - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--subject", SubjectHandle, "--resource", Resource1, "--permission", testFoo) + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--subject", SubjectHandle, "--resource", Resource1, "--permission", "foo") calls := *cli.MockClient.ApiMocks.PermissionsApi.DescribePermissionsCalls assert.Len(t, calls, 1) assert.Equal(t, SubjectHandle, calls[0].Psubject) - assert.Equal(t, testFoo, *calls[0].Ppermission) + assert.Equal(t, "foo", *calls[0].Ppermission) assert.Equal(t, Resource1, *calls[0].Presource) } diff --git a/cmd/rbac/rbac_describe_subjects_test.go b/cmd/rbac/rbac_describe_subjects_test.go index 67f4b340..3b7cb82b 100644 --- a/cmd/rbac/rbac_describe_subjects_test.go +++ b/cmd/rbac/rbac_describe_subjects_test.go @@ -10,12 +10,6 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - testSubject = "Subject" - testSource = "Source" - testSubjects = "subjects" -) - var ( SomeScopeVar = SomeScope SubjectConfig1 = stackstate_api.SubjectConfig{ @@ -53,13 +47,13 @@ func TestDescribeSubjectsTable(t *testing.T) { expected := []printer.TableData{ { - Header: []string{testSubject, testSource}, + Header: []string{"Subject", "Source"}, Data: [][]interface{}{ {SubjectConfig1.Handle, SubjectConfig1.Source}, {SubjectConfig2.Handle, SubjectConfig2.Source}, {SubjectConfig3.Handle, SubjectConfig3.Source}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: testSubjects}, + MissingTableDataMsg: printer.NotFoundMsg{Types: "subjects"}, }, } @@ -85,7 +79,7 @@ func TestDescribeSubjectsJson(t *testing.T) { expectedJson := []map[string]interface{}{ { - testSubjects: result, + "subjects": result, }, } @@ -111,11 +105,11 @@ func TestDescribeSubjectsTableWithFilter(t *testing.T) { expected := []printer.TableData{ { - Header: []string{testSubject, testSource}, + Header: []string{"Subject", "Source"}, Data: [][]interface{}{ {SubjectConfig1.Handle, SubjectConfig1.Source}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: testSubjects}, + MissingTableDataMsg: printer.NotFoundMsg{Types: "subjects"}, }, } @@ -141,7 +135,7 @@ func TestDescribeSubjectsJsonWithFilter(t *testing.T) { expectedJson := []map[string]interface{}{ { - testSubjects: []stackstate_api.SubjectConfig{SubjectConfig1}, + "subjects": []stackstate_api.SubjectConfig{SubjectConfig1}, }, } @@ -167,11 +161,11 @@ func TestDescribeSubjectsTableWithSourceFilter(t *testing.T) { expected := []printer.TableData{ { - Header: []string{testSubject, testSource}, + Header: []string{"Subject", "Source"}, Data: [][]interface{}{ {SubjectConfig1.Handle, SubjectConfig1.Source}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: testSubjects}, + MissingTableDataMsg: printer.NotFoundMsg{Types: "subjects"}, }, } @@ -193,9 +187,9 @@ func TestProduceEmptyWhenNoSubjectFilter(t *testing.T) { expected := []printer.TableData{ { - Header: []string{testSubject, testSource}, + Header: []string{"Subject", "Source"}, Data: [][]interface{}{}, - MissingTableDataMsg: printer.NotFoundMsg{Types: testSubjects}, + MissingTableDataMsg: printer.NotFoundMsg{Types: "subjects"}, }, } diff --git a/cmd/rbac/rbac_list_permissions_test.go b/cmd/rbac/rbac_list_permissions_test.go index 310eb8c1..4d00ea8b 100644 --- a/cmd/rbac/rbac_list_permissions_test.go +++ b/cmd/rbac/rbac_list_permissions_test.go @@ -9,9 +9,9 @@ import ( ) var SomePermissions = []string{ - testFoo, - testBar, - testBaz, + "foo", + "bar", + "baz", } func TestPermissionsList(t *testing.T) { @@ -32,7 +32,7 @@ func TestPermissionsList(t *testing.T) { expected := []map[string]interface{}{ { - permissionsKey: SomePermissions, + "permissions": SomePermissions, }, } diff --git a/cmd/script/script_run_test.go b/cmd/script/script_run_test.go index 24211242..d2e7ce6b 100644 --- a/cmd/script/script_run_test.go +++ b/cmd/script/script_run_test.go @@ -14,11 +14,6 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - testValue = "value" - testHelloTest = "hello test" -) - func setupScriptExecuteCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { cli := di.NewMockDeps(t) cmd := ScriptRunCommand(&cli.Deps) @@ -28,7 +23,7 @@ func setupScriptExecuteCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { func TestExecuteSuccess(t *testing.T) { cli, cmd := setupScriptExecuteCmd(t) cli.MockClient.ApiMocks.ScriptingApi.ScriptExecuteResponse.Result = sts.ExecuteScriptResponse{ - Result: map[string]interface{}{testValue: testHelloTest}, + Result: map[string]interface{}{"value": "hello test"}, } di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--script", "test script") @@ -39,20 +34,20 @@ func TestExecuteSuccess(t *testing.T) { }, *cli.MockClient.ApiMocks.ScriptingApi.ScriptExecuteCalls, ) - assert.Equal(t, []interface{}{testHelloTest}, *cli.MockPrinter.PrintStructCalls) + assert.Equal(t, []interface{}{"hello test"}, *cli.MockPrinter.PrintStructCalls) } func TestExecuteSuccessJson(t *testing.T) { cli, cmd := setupScriptExecuteCmd(t) cli.MockClient.ApiMocks.ScriptingApi.ScriptExecuteResponse.Result = sts.ExecuteScriptResponse{ - Result: map[string]interface{}{testValue: testHelloTest}, + Result: map[string]interface{}{"value": "hello test"}, } di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--script", "test script", "-o", "json") assert.Equal(t, []map[string]interface{}{{ - "result": map[string]interface{}{testValue: testHelloTest}, + "result": map[string]interface{}{"value": "hello test"}, }}, *cli.MockPrinter.PrintJsonCalls, ) diff --git a/cmd/servicetoken/servicetoken_create_test.go b/cmd/servicetoken/servicetoken_create_test.go index 091dc597..01093590 100644 --- a/cmd/servicetoken/servicetoken_create_test.go +++ b/cmd/servicetoken/servicetoken_create_test.go @@ -8,28 +8,20 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - testTokenName = "test-token" - testTokenValue = "test-token-token" - testRole = "test-role" - testTokenCreatedMessage = "Service token created: \x1b[37mtest-token-token\x1b[0m\n" - testAnotherRole = "another-role" -) - func TestServiceTokenCreate(t *testing.T) { cli := di.NewMockDeps(t) cmd := CreateCommand(&cli.Deps) cli.MockClient.ApiMocks.ServiceTokenApi.CreateNewServiceTokenResponse.Result = stackstate_api.ServiceTokenCreatedResponse{ - Name: testTokenName, - Token: testTokenValue, + Name: "test-token", + Token: "test-token-token", Expiration: int64p(100000000), } - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--name", testTokenName, "--roles", testRole, "--expiration", "2020-05-22") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--name", "test-token", "--roles", "test-role", "--expiration", "2020-05-22") - checkCreateCall(t, cli.MockClient.ApiMocks.ServiceTokenApi.CreateNewServiceTokenCalls, testTokenName, []string{testRole}, int64p(1590105600000)) - assert.Equal(t, []string{testTokenCreatedMessage}, *cli.MockPrinter.SuccessCalls) + checkCreateCall(t, cli.MockClient.ApiMocks.ServiceTokenApi.CreateNewServiceTokenCalls, "test-token", []string{"test-role"}, int64p(1590105600000)) + assert.Equal(t, []string{"Service token created: \x1b[37mtest-token-token\x1b[0m\n"}, *cli.MockPrinter.SuccessCalls) } func TestServiceTokenCreateExpirationOptional(t *testing.T) { @@ -37,15 +29,15 @@ func TestServiceTokenCreateExpirationOptional(t *testing.T) { cmd := CreateCommand(&cli.Deps) cli.MockClient.ApiMocks.ServiceTokenApi.CreateNewServiceTokenResponse.Result = stackstate_api.ServiceTokenCreatedResponse{ - Name: testTokenName, - Token: testTokenValue, + Name: "test-token", + Token: "test-token-token", Expiration: int64p(100000000), } - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--name", testTokenName, "--roles", testRole) + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--name", "test-token", "--roles", "test-role") - checkCreateCall(t, cli.MockClient.ApiMocks.ServiceTokenApi.CreateNewServiceTokenCalls, testTokenName, []string{testRole}, nil) - assert.Equal(t, []string{testTokenCreatedMessage}, *cli.MockPrinter.SuccessCalls) + checkCreateCall(t, cli.MockClient.ApiMocks.ServiceTokenApi.CreateNewServiceTokenCalls, "test-token", []string{"test-role"}, nil) + assert.Equal(t, []string{"Service token created: \x1b[37mtest-token-token\x1b[0m\n"}, *cli.MockPrinter.SuccessCalls) } func TestServiceTokenCreateMultipleRoles(t *testing.T) { @@ -53,15 +45,15 @@ func TestServiceTokenCreateMultipleRoles(t *testing.T) { cmd := CreateCommand(&cli.Deps) cli.MockClient.ApiMocks.ServiceTokenApi.CreateNewServiceTokenResponse.Result = stackstate_api.ServiceTokenCreatedResponse{ - Name: testTokenName, - Token: testTokenValue, + Name: "test-token", + Token: "test-token-token", Expiration: int64p(100000000), } - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--name", testTokenName, "--roles", "test-role,another-role", "--roles", "third-role") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--name", "test-token", "--roles", "test-role,another-role", "--roles", "third-role") - checkCreateCall(t, cli.MockClient.ApiMocks.ServiceTokenApi.CreateNewServiceTokenCalls, testTokenName, []string{testRole, testAnotherRole, "third-role"}, nil) - assert.Equal(t, []string{testTokenCreatedMessage}, *cli.MockPrinter.SuccessCalls) + checkCreateCall(t, cli.MockClient.ApiMocks.ServiceTokenApi.CreateNewServiceTokenCalls, "test-token", []string{"test-role", "another-role", "third-role"}, nil) + assert.Equal(t, []string{"Service token created: \x1b[37mtest-token-token\x1b[0m\n"}, *cli.MockPrinter.SuccessCalls) } func TestServiceTokenCreateJSON(t *testing.T) { @@ -69,13 +61,13 @@ func TestServiceTokenCreateJSON(t *testing.T) { cmd := CreateCommand(&cli.Deps) r := &stackstate_api.ServiceTokenCreatedResponse{ - Name: testTokenName, - Token: testTokenValue, + Name: "test-token", + Token: "test-token-token", } cli.MockClient.ApiMocks.ServiceTokenApi.CreateNewServiceTokenResponse.Result = *r - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--name", testTokenName, "--roles", testRole, "-o", "json") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--name", "test-token", "--roles", "test-role", "-o", "json") assert.Equal(t, []map[string]interface{}{{ diff --git a/cmd/servicetoken/servicetoken_list_test.go b/cmd/servicetoken/servicetoken_list_test.go index b2ff61f8..c995f630 100644 --- a/cmd/servicetoken/servicetoken_list_test.go +++ b/cmd/servicetoken/servicetoken_list_test.go @@ -18,8 +18,8 @@ func TestServiceTokenList(t *testing.T) { Id: int64p(1), Name: "test", Roles: []string{ - testRole, - testAnotherRole, + "test-role", + "another-role", }, Expiration: int64p(1590105600000), }, @@ -27,7 +27,7 @@ func TestServiceTokenList(t *testing.T) { Id: int64p(2), Name: "test2", Roles: []string{ - testRole, + "test-role", }, Expiration: nil, }, @@ -39,8 +39,8 @@ func TestServiceTokenList(t *testing.T) { { Header: []string{"id", "name", "expiration", "roles", "dedicated_Subject"}, Data: [][]interface{}{ - {int64(1), "test", "2020-05-22", []string{testRole, testAnotherRole}, (*string)(nil)}, - {int64(2), "test2", "", []string{testRole}, (*string)(nil)}, + {int64(1), "test", "2020-05-22", []string{"test-role", "another-role"}, (*string)(nil)}, + {int64(2), "test2", "", []string{"test-role"}, (*string)(nil)}, }, MissingTableDataMsg: printer.NotFoundMsg{Types: "service tokens"}, }, diff --git a/cmd/settings/settings_apply_test.go b/cmd/settings/settings_apply_test.go index 18fbb6d9..6710aafa 100644 --- a/cmd/settings/settings_apply_test.go +++ b/cmd/settings/settings_apply_test.go @@ -54,7 +54,7 @@ func TestSetingsApplyFromFileNoOptionalArgs(t *testing.T) { assert.Nil(t, (*cli.MockClient.ApiMocks.ImportApi.ImportSettingsCalls)[0].Punlocked) expectedTableCall := []printer.TableData{ { - Header: []string{typeKey, "Id", identifierColumn, nameKey}, + Header: []string{"Type", "Id", "Identifier", "Name"}, Data: [][]interface{}{{"Layer", 12345, "urn:stackpack:test:layer:test", "test"}}, }, } diff --git a/cmd/settings/settings_list_test.go b/cmd/settings/settings_list_test.go index a35151da..46e7354e 100644 --- a/cmd/settings/settings_list_test.go +++ b/cmd/settings/settings_list_test.go @@ -11,10 +11,6 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - testComponentType = "ComponentType" -) - var ( name = "One" otherName = "Two" @@ -25,7 +21,7 @@ var ( nodeApiResult = []sts.Node{ { Id: 1, - TypeName: testComponentType, + TypeName: "ComponentType", Identifier: &identifier, Name: &name, Description: &description, @@ -34,7 +30,7 @@ var ( }, { Id: 2, - TypeName: testComponentType, + TypeName: "ComponentType", Identifier: &otherIdentifier, Name: &otherName, Description: &description, @@ -55,12 +51,12 @@ func setupSettingsListCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { func TestSettingsListPrintsToTable(t *testing.T) { cli, cmd := setupSettingsListCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--type", testComponentType) + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--type", "ComponentType") expectedTableCall := []printer.TableData{ { - Header: []string{typeKey, "Id", identifierColumn, nameKey, "owned by", "last updated"}, - Data: [][]interface{}{{testComponentType, int64(1), identifier, name, owner, expectedUpdateTime}, {testComponentType, int64(2), otherIdentifier, otherName, owner, expectedUpdateTime}}, + Header: []string{"Type", "Id", "Identifier", "Name", "owned by", "last updated"}, + Data: [][]interface{}{{"ComponentType", int64(1), identifier, name, owner, expectedUpdateTime}, {"ComponentType", int64(2), otherIdentifier, otherName, owner, expectedUpdateTime}}, MissingTableDataMsg: printer.NotFoundMsg{Types: "settings of type \"ComponentType\""}, }, } @@ -71,14 +67,14 @@ func TestSettingsListPrintsToTable(t *testing.T) { func TestSettingsListWithNamespaeAndOwnerPrintsToTable(t *testing.T) { cli, cmd := setupSettingsListCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--type", testComponentType, + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--type", "ComponentType", "--namespace", "component", "--owned-by", "urn:stackpack:stackstate-self-health:shared") expectedTableCall := []printer.TableData{ { - Header: []string{typeKey, "Id", identifierColumn, nameKey, "owned by", "last updated"}, - Data: [][]interface{}{{testComponentType, int64(1), identifier, name, owner, expectedUpdateTime}, {testComponentType, int64(2), otherIdentifier, otherName, owner, expectedUpdateTime}}, + Header: []string{"Type", "Id", "Identifier", "Name", "owned by", "last updated"}, + Data: [][]interface{}{{"ComponentType", int64(1), identifier, name, owner, expectedUpdateTime}, {"ComponentType", int64(2), otherIdentifier, otherName, owner, expectedUpdateTime}}, MissingTableDataMsg: printer.NotFoundMsg{Types: "settings of type \"ComponentType\""}, }, } @@ -89,7 +85,7 @@ func TestSettingsListWithNamespaeAndOwnerPrintsToTable(t *testing.T) { func TestSettingsListPrintsToJson(t *testing.T) { cli, cmd := setupSettingsListCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--type", testComponentType, "-o", "json") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "--type", "ComponentType", "-o", "json") assert.Equal(t, []map[string]interface{}{{ diff --git a/cmd/settings/settings_list_types_test.go b/cmd/settings/settings_list_types_test.go index 4013ec50..03fa0a1a 100644 --- a/cmd/settings/settings_list_types_test.go +++ b/cmd/settings/settings_list_types_test.go @@ -10,18 +10,13 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - testWorld = "world" - testHello = "hello" -) - func setupSettingListTypesCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { cli := di.NewMockDeps(t) cmd := SettingsListTypesCommand(&cli.Deps) nodeApiResult := sts.NodeTypes{ NodeTypes: []sts.NodeTypesNodeTypesInner{ - {TypeName: testWorld, Description: testHello}, - {TypeName: testHello, Description: testWorld}, + {TypeName: "world", Description: "hello"}, + {TypeName: "hello", Description: "world"}, }, } cli.MockClient.ApiMocks.NodeApi.NodeListTypesResponse.Result = nodeApiResult @@ -35,7 +30,7 @@ func TestListTypesPrintsToTable(t *testing.T) { expectedTableCall := []printer.TableData{{ Header: []string{"name", "description"}, - Data: [][]interface{}{{testHello, testWorld}, {testWorld, testHello}}, + Data: [][]interface{}{{"hello", "world"}, {"world", "hello"}}, MissingTableDataMsg: printer.NotFoundMsg{Types: "setting types"}, }} @@ -49,8 +44,8 @@ func TestListTypesPrintsToJson(t *testing.T) { ordered := sts.NodeTypes{ NodeTypes: []sts.NodeTypesNodeTypesInner{ - {TypeName: testHello, Description: testWorld}, - {TypeName: testWorld, Description: testHello}, + {TypeName: "hello", Description: "world"}, + {TypeName: "world", Description: "hello"}, }, } diff --git a/cmd/stackpack/common_test.go b/cmd/stackpack/common_test.go index 3e9fd5d8..208456fa 100644 --- a/cmd/stackpack/common_test.go +++ b/cmd/stackpack/common_test.go @@ -12,10 +12,6 @@ import ( ) const ( - testWait = "--wait" - testInitialVersion = "1.0.0" - testZabbix = "zabbix" - timeoutFlagArg = "--timeout" testStackPackName = "test-stackpack" successfulResponseResult = "successful" ) @@ -36,7 +32,7 @@ func TestOperationWaiter_WaitForCompletion_Success(t *testing.T) { { Id: &configID, Status: StatusInstalled, - StackPackVersion: testInitialVersion, + StackPackVersion: "1.0.0", LastUpdateTimestamp: ×tamp, Config: map[string]interface{}{}, }, @@ -81,7 +77,7 @@ func TestOperationWaiter_WaitForCompletion_Error(t *testing.T) { { Id: &configID, Status: StatusError, - StackPackVersion: testInitialVersion, + StackPackVersion: "1.0.0", LastUpdateTimestamp: ×tamp, Config: map[string]interface{}{}, Error: &stackPackError, @@ -120,7 +116,7 @@ func TestOperationWaiter_WaitForCompletion_Timeout(t *testing.T) { { Id: &configID, Status: StatusProvisioning, - StackPackVersion: testInitialVersion, + StackPackVersion: "1.0.0", LastUpdateTimestamp: ×tamp, Config: map[string]interface{}{}, }, @@ -181,14 +177,14 @@ func TestOperationWaiter_WaitForCompletion_MultipleConfigurations(t *testing.T) { Id: &configID1, Status: StatusInstalled, - StackPackVersion: testInitialVersion, + StackPackVersion: "1.0.0", LastUpdateTimestamp: ×tamp, Config: map[string]interface{}{}, }, { Id: &configID2, Status: StatusProvisioning, - StackPackVersion: testInitialVersion, + StackPackVersion: "1.0.0", LastUpdateTimestamp: ×tamp, Config: map[string]interface{}{}, }, @@ -211,7 +207,7 @@ func TestOperationWaiter_WaitForCompletion_MultipleConfigurations(t *testing.T) } func TestFindStackPackByName_Found(t *testing.T) { - stackpackName := testZabbix + stackpackName := "zabbix" stacks := []stackstate_api.FullStackPack{ {Name: "mysql"}, {Name: stackpackName}, @@ -260,7 +256,7 @@ func validateWaitFlags(t *testing.T, cmd *cobra.Command) { assert.Equal(t, "1m0s", timeoutFlag.DefValue, "timeout flag default should be 1m0s") // Verify the flags can be set - err := cmd.ParseFlags([]string{testWait, timeoutFlagArg, "30s"}) + err := cmd.ParseFlags([]string{"--wait", "--timeout", "30s"}) assert.NoError(t, err) waitValue, err := cmd.Flags().GetBool("wait") diff --git a/cmd/stackpack/stackpack_confirm_manual_steps_test.go b/cmd/stackpack/stackpack_confirm_manual_steps_test.go index 5a687e95..3b9a72d9 100644 --- a/cmd/stackpack/stackpack_confirm_manual_steps_test.go +++ b/cmd/stackpack/stackpack_confirm_manual_steps_test.go @@ -10,10 +10,6 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - nameFlagArg = "--name" -) - func setupStackPacConfirmManualStepsCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { cli := di.NewMockDeps(t) cmd := StackpackConfirmManualStepsCommand(&cli.Deps) @@ -23,7 +19,7 @@ func setupStackPacConfirmManualStepsCmd(t *testing.T) (*di.MockDeps, *cobra.Comm func TestStackpackConfirmManualStepsPrintsToTable(t *testing.T) { cli, cmd := setupStackPacConfirmManualStepsCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "confirm-manual-steps", nameFlagArg, testZabbix, + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "confirm-manual-steps", "--name", "zabbix", "--id", "1234", ) assert.True(t, cli.MockPrinter.HasNonJsonCalls) @@ -41,12 +37,12 @@ func TestStackpackConfirmManualStepsPrintsToTable(t *testing.T) { func TestStackpackConfirmManualStepsPrintsToJson(t *testing.T) { cli, cmd := setupStackPacConfirmManualStepsCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "confirm-manual-steps", nameFlagArg, testZabbix, + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "confirm-manual-steps", "--name", "zabbix", "--id", "1234", "-o", "json", ) expectedJsonCalls := []map[string]interface{}{{ - successKey: true, - "stackpack-name": testZabbix, + "success": true, + "stackpack-name": "zabbix", "stackpack-instance-id": int64(1234), }} assert.Equal(t, expectedJsonCalls, *cli.MockPrinter.PrintJsonCalls) diff --git a/cmd/stackpack/stackpack_delete_version_test.go b/cmd/stackpack/stackpack_delete_version_test.go index 0e782df5..32847589 100644 --- a/cmd/stackpack/stackpack_delete_version_test.go +++ b/cmd/stackpack/stackpack_delete_version_test.go @@ -16,7 +16,7 @@ func setupStackPackDeleteVersionCmd(t *testing.T) (*di.MockDeps, *cobra.Command) func TestStackpackDeleteVersionPrintToConsole(t *testing.T) { cli, cmd := setupStackPackDeleteVersionCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete-version", nameFlagArg, "kubernetes", "--stackpack-version", testInitialVersion) + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete-version", "--name", "kubernetes", "--stackpack-version", "1.0.0") expectedSuccessMessage := []string{"Successfully deleted version 1.0.0 of StackPack kubernetes"} assert.True(t, cli.MockPrinter.HasNonJsonCalls) @@ -25,15 +25,15 @@ func TestStackpackDeleteVersionPrintToConsole(t *testing.T) { assert.Equal(t, 1, len(*cli.MockClient.ApiMocks.StackpackApi.StackPackDeleteVersionCalls)) call := (*cli.MockClient.ApiMocks.StackpackApi.StackPackDeleteVersionCalls)[0] assert.Equal(t, "kubernetes", call.PstackPackName) - assert.Equal(t, testInitialVersion, call.Pversion) + assert.Equal(t, "1.0.0", call.Pversion) } func TestStackpackDeleteVersionPrintToJson(t *testing.T) { cli, cmd := setupStackPackDeleteVersionCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete-version", nameFlagArg, "kubernetes", "--stackpack-version", testInitialVersion, "-o", "json") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete-version", "--name", "kubernetes", "--stackpack-version", "1.0.0", "-o", "json") expectedJsonCalls := []map[string]interface{}{{ - "deleted": testInitialVersion, + "deleted": "1.0.0", }} assert.False(t, cli.MockPrinter.HasNonJsonCalls) assert.Equal(t, expectedJsonCalls, *cli.MockPrinter.PrintJsonCalls) diff --git a/cmd/stackpack/stackpack_delete_versions_test.go b/cmd/stackpack/stackpack_delete_versions_test.go index 9a95aa5a..e359682f 100644 --- a/cmd/stackpack/stackpack_delete_versions_test.go +++ b/cmd/stackpack/stackpack_delete_versions_test.go @@ -9,16 +9,11 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - testNextVersion = "1.1.0" - testMajorVersion = "2.0.0" -) - func setupStackPackDeleteVersionsCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { cli := di.NewMockDeps(t) cmd := StackpackDeleteVersionsCommand(&cli.Deps) cli.MockClient.ApiMocks.StackpackApi.StackPackDeleteVersionsResponse.Result = stackstate_api.DeleteVersionsResult{ - Deleted: []string{testInitialVersion, testNextVersion}, + Deleted: []string{"1.0.0", "1.1.0"}, SkippedInUse: []string{"1.2.0"}, } return &cli, cmd @@ -26,7 +21,7 @@ func setupStackPackDeleteVersionsCmd(t *testing.T) (*di.MockDeps, *cobra.Command func TestStackpackDeleteVersionsWithTo(t *testing.T) { cli, cmd := setupStackPackDeleteVersionsCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete-versions", nameFlagArg, "kubernetes", "--to", "1.5.0") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete-versions", "--name", "kubernetes", "--to", "1.5.0") assert.True(t, cli.MockPrinter.HasNonJsonCalls) assert.Equal(t, []string{"Deleted versions: 1.0.0, 1.1.0"}, *cli.MockPrinter.SuccessCalls) @@ -42,12 +37,12 @@ func TestStackpackDeleteVersionsWithTo(t *testing.T) { func TestStackpackDeleteVersionsWithRange(t *testing.T) { cli, cmd := setupStackPackDeleteVersionsCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete-versions", nameFlagArg, "kubernetes", "--from", testInitialVersion, "--to", "1.5.0") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete-versions", "--name", "kubernetes", "--from", "1.0.0", "--to", "1.5.0") assert.Equal(t, 1, len(*cli.MockClient.ApiMocks.StackpackApi.StackPackDeleteVersionsCalls)) call := (*cli.MockClient.ApiMocks.StackpackApi.StackPackDeleteVersionsCalls)[0] assert.Equal(t, "kubernetes", call.PstackPackName) - assert.Equal(t, testInitialVersion, *call.Pfrom) + assert.Equal(t, "1.0.0", *call.Pfrom) assert.Equal(t, "1.5.0", *call.Pto) assert.Nil(t, call.Pall) assert.Nil(t, call.Pdev) @@ -55,7 +50,7 @@ func TestStackpackDeleteVersionsWithRange(t *testing.T) { func TestStackpackDeleteVersionsWithAll(t *testing.T) { cli, cmd := setupStackPackDeleteVersionsCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete-versions", nameFlagArg, "kubernetes", "--all") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete-versions", "--name", "kubernetes", "--all") assert.Equal(t, 1, len(*cli.MockClient.ApiMocks.StackpackApi.StackPackDeleteVersionsCalls)) call := (*cli.MockClient.ApiMocks.StackpackApi.StackPackDeleteVersionsCalls)[0] @@ -68,7 +63,7 @@ func TestStackpackDeleteVersionsWithAll(t *testing.T) { func TestStackpackDeleteVersionsWithAllAndDevOnly(t *testing.T) { cli, cmd := setupStackPackDeleteVersionsCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete-versions", nameFlagArg, "kubernetes", "--all", "--dev-only") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete-versions", "--name", "kubernetes", "--all", "--dev-only") assert.Equal(t, 1, len(*cli.MockClient.ApiMocks.StackpackApi.StackPackDeleteVersionsCalls)) call := (*cli.MockClient.ApiMocks.StackpackApi.StackPackDeleteVersionsCalls)[0] @@ -81,10 +76,10 @@ func TestStackpackDeleteVersionsWithAllAndDevOnly(t *testing.T) { func TestStackpackDeleteVersionsPrintToJson(t *testing.T) { cli, cmd := setupStackPackDeleteVersionsCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete-versions", nameFlagArg, "kubernetes", "--to", testMajorVersion, "-o", "json") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "delete-versions", "--name", "kubernetes", "--to", "2.0.0", "-o", "json") expectedJsonCalls := []map[string]interface{}{{ - "deleted": []string{testInitialVersion, testNextVersion}, + "deleted": []string{"1.0.0", "1.1.0"}, "skippedInUse": []string{"1.2.0"}, }} assert.False(t, cli.MockPrinter.HasNonJsonCalls) @@ -94,20 +89,20 @@ func TestStackpackDeleteVersionsPrintToJson(t *testing.T) { func TestStackpackDeleteVersionsNoFlags(t *testing.T) { cli := di.NewMockDeps(t) cmd := StackpackDeleteVersionsCommand(&cli.Deps) - _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "delete-versions", nameFlagArg, "kubernetes") + _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "delete-versions", "--name", "kubernetes") assert.Error(t, err) } func TestStackpackDeleteVersionsAllWithFrom(t *testing.T) { cli := di.NewMockDeps(t) cmd := StackpackDeleteVersionsCommand(&cli.Deps) - _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "delete-versions", nameFlagArg, "kubernetes", "--all", "--from", testInitialVersion) + _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "delete-versions", "--name", "kubernetes", "--all", "--from", "1.0.0") assert.Error(t, err) } func TestStackpackDeleteVersionsAllWithTo(t *testing.T) { cli := di.NewMockDeps(t) cmd := StackpackDeleteVersionsCommand(&cli.Deps) - _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "delete-versions", nameFlagArg, "kubernetes", "--all", "--to", "1.5.0") + _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "delete-versions", "--name", "kubernetes", "--all", "--to", "1.5.0") assert.Error(t, err) } diff --git a/cmd/stackpack/stackpack_describe_test.go b/cmd/stackpack/stackpack_describe_test.go index d6336c78..dac35129 100644 --- a/cmd/stackpack/stackpack_describe_test.go +++ b/cmd/stackpack/stackpack_describe_test.go @@ -11,14 +11,6 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - testType = "type" -) - -const ( - installedInstancesTitle = "installed StackPack instances" -) - var ( testDisplayName = "Test StackPack" testCurrVersion = "1.2.3" @@ -85,8 +77,8 @@ func TestStackpackDescribeNotFound(t *testing.T) { cli.MockClient.ApiMocks.StackpackApi.StackPackListResponse.Result = mockResponse - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "describe", nameFlagArg, "foobar") - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "describe", nameFlagArg, "foobar", "-o", "json") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "describe", "--name", "foobar") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "describe", "--name", "foobar", "-o", "json") expected := []error{ fmt.Errorf("StackPack 'foobar' not found."), @@ -102,7 +94,7 @@ func TestStackpackDescribeJson(t *testing.T) { cli.MockClient.ApiMocks.StackpackApi.StackPackListResponse.Result = mockResponse - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "describe", nameFlagArg, awsName, "-o", "json") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "describe", "--name", awsName, "-o", "json") expected := []map[string]interface{}{ { @@ -119,7 +111,7 @@ func TestStackpackDescribeText(t *testing.T) { cli.MockClient.ApiMocks.StackpackApi.StackPackListResponse.Result = []stackstate_api.FullStackPack{testStackPack} - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "describe", nameFlagArg, testName) + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "describe", "--name", testName) expectedLines := []string{ fmt.Sprintf("StackPack %s v%s (latest available is v%s)", testDisplayName, testCurrVersion, testLatestVersion), @@ -131,7 +123,7 @@ func TestStackpackDescribeText(t *testing.T) { expectedTables := []printer.TableData{ { - Header: []string{NameFlag, displayNameColumn, testType}, + Header: []string{"name", "display name", "type"}, Data: [][]interface{}{ {&testStep1Name, &testStep1Name, &testStepType}, {&testStep2Name, &testStep2Name, &testStepType}, @@ -139,11 +131,11 @@ func TestStackpackDescribeText(t *testing.T) { MissingTableDataMsg: printer.NotFoundMsg{Types: "instance parameters"}, }, { - Header: []string{"id", statusKey, versionKey, lastUpdatedColumn}, + Header: []string{"id", "status", "version", "last updated"}, Data: [][]interface{}{ {&testId, testStatus, testCurrVersion, testTimestamp}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: installedInstancesTitle}, + MissingTableDataMsg: printer.NotFoundMsg{Types: "installed StackPack instances"}, }, } @@ -160,7 +152,7 @@ func TestStackpackDescribeTextNoCategories(t *testing.T) { cli.MockClient.ApiMocks.StackpackApi.StackPackListResponse.Result = []stackstate_api.FullStackPack{newTest} - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "describe", nameFlagArg, testName) + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "describe", "--name", testName) expectedLines := []string{ fmt.Sprintf("StackPack %s v%s (latest available is v%s)", testDisplayName, testCurrVersion, testLatestVersion), @@ -181,15 +173,15 @@ func TestStackpackDescribeTextNoSteps(t *testing.T) { cli.MockClient.ApiMocks.StackpackApi.StackPackListResponse.Result = []stackstate_api.FullStackPack{newTest} - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "describe", nameFlagArg, testName) + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "describe", "--name", testName) expectedTables := []printer.TableData{ { - Header: []string{"id", statusKey, versionKey, lastUpdatedColumn}, + Header: []string{"id", "status", "version", "last updated"}, Data: [][]interface{}{ {&testId, testStatus, testCurrVersion, testTimestamp}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: installedInstancesTitle}, + MissingTableDataMsg: printer.NotFoundMsg{Types: "installed StackPack instances"}, }, } @@ -205,11 +197,11 @@ func TestStackpackDescribeTextNoInstances(t *testing.T) { cli.MockClient.ApiMocks.StackpackApi.StackPackListResponse.Result = []stackstate_api.FullStackPack{newTest} - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "describe", nameFlagArg, testName) + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "describe", "--name", testName) expectedTables := []printer.TableData{ { - Header: []string{NameFlag, displayNameColumn, testType}, + Header: []string{"name", "display name", "type"}, Data: [][]interface{}{ {&testStep1Name, &testStep1Name, &testStepType}, {&testStep2Name, &testStep2Name, &testStepType}, @@ -218,9 +210,9 @@ func TestStackpackDescribeTextNoInstances(t *testing.T) { }, // NOTE Still printed. { - Header: []string{"id", statusKey, versionKey, lastUpdatedColumn}, + Header: []string{"id", "status", "version", "last updated"}, Data: [][]interface{}{}, - MissingTableDataMsg: printer.NotFoundMsg{Types: installedInstancesTitle}, + MissingTableDataMsg: printer.NotFoundMsg{Types: "installed StackPack instances"}, }, } assert.Equal(t, expectedTables, *cli.MockPrinter.TableCalls) diff --git a/cmd/stackpack/stackpack_downgrade_test.go b/cmd/stackpack/stackpack_downgrade_test.go index 6a69c865..3f21b28b 100644 --- a/cmd/stackpack/stackpack_downgrade_test.go +++ b/cmd/stackpack/stackpack_downgrade_test.go @@ -22,13 +22,13 @@ func setupStackPackDowngradeCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { func TestStackpackDowngradePrintToTable(t *testing.T) { cli, cmd := setupStackPackDowngradeCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "downgrade", nameFlagArg, testZabbix, + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "downgrade", "--name", "zabbix", "--stackpack-version", downgradeVersion, ) assert.Equal(t, []stackstate_api.DowngradeStackPackCall{{ - PstackPackName: testZabbix, + PstackPackName: "zabbix", Pversion: &downgradeVersion, }}, *cli.MockClient.ApiMocks.StackpackApi.DowngradeStackPackCalls) @@ -38,19 +38,19 @@ func TestStackpackDowngradePrintToTable(t *testing.T) { func TestStackpackDowngradePrintToJson(t *testing.T) { cli, cmd := setupStackPackDowngradeCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "downgrade", nameFlagArg, testZabbix, + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "downgrade", "--name", "zabbix", "--stackpack-version", downgradeVersion, "-o", "json", ) assert.Equal(t, []stackstate_api.DowngradeStackPackCall{{ - PstackPackName: testZabbix, + PstackPackName: "zabbix", Pversion: &downgradeVersion, }}, *cli.MockClient.ApiMocks.StackpackApi.DowngradeStackPackCalls) expectedJsonCalls := []map[string]interface{}{{ - successKey: true, + "success": true, "target-version": downgradeVersion, }} assert.Equal(t, expectedJsonCalls, *cli.MockPrinter.PrintJsonCalls) @@ -60,7 +60,7 @@ func TestStackpackDowngradeRequiresVersion(t *testing.T) { cli := di.NewMockDeps(t) cmd := StackpackDowngradeCommand(&cli.Deps) - _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "downgrade", nameFlagArg, testZabbix) + _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "downgrade", "--name", "zabbix") assert.Error(t, err) assert.Contains(t, err.Error(), "stackpack-version") diff --git a/cmd/stackpack/stackpack_install_test.go b/cmd/stackpack/stackpack_install_test.go index 625eda7e..f00aa689 100644 --- a/cmd/stackpack/stackpack_install_test.go +++ b/cmd/stackpack/stackpack_install_test.go @@ -12,12 +12,11 @@ import ( ) const ( - testUploadName = "test" - FailStrategy = "fail" + FailStrategy = "fail" ) var ( - name = testZabbix + name = "zabbix" provisionID = int64(1234) provisionName = "provision_name" provisionStatus = "PROVISIONING" @@ -43,7 +42,7 @@ func setupStackPackInstallCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { func TestStackpackInstallPrintsToTable(t *testing.T) { cli, cmd := setupStackPackInstallCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "install", nameFlagArg, testZabbix, + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "install", "--name", "zabbix", "--parameter", "zabbix_instance_name=test_name", "--parameter", "zabbix_instance_url=test_url", ) @@ -51,7 +50,7 @@ func TestStackpackInstallPrintsToTable(t *testing.T) { strategyFlag := FailStrategy assert.Equal(t, stackstate_api.ProvisionDetailsCall{ - PstackPackName: testZabbix, + PstackPackName: "zabbix", Punlocked: &strategyFlag, PrequestBody: &map[string]string{ "zabbix_instance_name": "test_name", @@ -62,7 +61,7 @@ func TestStackpackInstallPrintsToTable(t *testing.T) { ) expectedTableCall := []printer.TableData{ { - Header: []string{"id", NameFlag, statusKey, versionKey, lastUpdatedColumn}, + Header: []string{"id", "name", "status", "version", "last updated"}, Data: [][]interface{}{{&provisionID, &provisionName, &provisionStatus, &provisionVersion, expectedUpdateTime}}, MissingTableDataMsg: printer.NotFoundMsg{Types: "provision details of " + name}, }, @@ -73,7 +72,7 @@ func TestStackpackInstallPrintsToTable(t *testing.T) { func TestStackpackInstallComplexParameters(t *testing.T) { cli, cmd := setupStackPackInstallCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "install", nameFlagArg, testZabbix, + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "install", "--name", "zabbix", "--parameter", "one=foo,two=bar", "--parameter", "i=am=complex", "--parameter", "empty=", @@ -83,7 +82,7 @@ func TestStackpackInstallComplexParameters(t *testing.T) { strategyFlag := FailStrategy assert.Equal(t, stackstate_api.ProvisionDetailsCall{ - PstackPackName: testZabbix, + PstackPackName: "zabbix", Punlocked: &strategyFlag, PrequestBody: &map[string]string{ "one": "foo", @@ -100,12 +99,12 @@ func TestStackpackInstallComplexParameters(t *testing.T) { func TestStackpackInstallNoParameters(t *testing.T) { cli, cmd := setupStackPackInstallCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "install", nameFlagArg, testZabbix) + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "install", "--name", "zabbix") strategyFlag := FailStrategy assert.Equal(t, stackstate_api.ProvisionDetailsCall{ - PstackPackName: testZabbix, + PstackPackName: "zabbix", Punlocked: &strategyFlag, PrequestBody: &map[string]string{}, }, @@ -116,7 +115,7 @@ func TestStackpackInstallNoParameters(t *testing.T) { func TestStackpackInstallWithVersion(t *testing.T) { cli, cmd := setupStackPackInstallCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "install", nameFlagArg, testZabbix, + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "install", "--name", "zabbix", "--stackpack-version", "3.2.0", ) @@ -124,7 +123,7 @@ func TestStackpackInstallWithVersion(t *testing.T) { versionFlag := "3.2.0" assert.Equal(t, stackstate_api.ProvisionDetailsCall{ - PstackPackName: testZabbix, + PstackPackName: "zabbix", Punlocked: &strategyFlag, Pversion: &versionFlag, PrequestBody: &map[string]string{}, @@ -136,7 +135,7 @@ func TestStackpackInstallWithVersion(t *testing.T) { func TestStackpackInstallWithoutVersion(t *testing.T) { cli, cmd := setupStackPackInstallCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "install", nameFlagArg, testZabbix) + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "install", "--name", "zabbix") assert.Nil(t, (*cli.MockClient.ApiMocks.StackpackApi.ProvisionDetailsCalls)[0].Pversion) } @@ -144,7 +143,7 @@ func TestStackpackInstallWithoutVersion(t *testing.T) { func TestStackpackInstallPrintsToJson(t *testing.T) { cli, cmd := setupStackPackInstallCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "install", nameFlagArg, testZabbix, "-o", "json") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "install", "--name", "zabbix", "-o", "json") assert.Equal(t, []map[string]interface{}{{ @@ -202,7 +201,7 @@ func TestStackpackInstallWithWaitTimeout(t *testing.T) { }, } - _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "install", nameFlagArg, name, testWait, timeoutFlagArg, "50ms") + _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "install", "--name", name, "--wait", "--timeout", "50ms") // Should return timeout error assert.Error(t, err) @@ -214,7 +213,7 @@ func TestStackpackInstallWithWaitJsonFlags(t *testing.T) { cmd := StackpackInstallCommand(&cli.Deps) // Test that wait and timeout flags can be parsed with other flags - err := cmd.ParseFlags([]string{nameFlagArg, testUploadName, testWait, timeoutFlagArg, "100ms"}) + err := cmd.ParseFlags([]string{"--name", "test", "--wait", "--timeout", "100ms"}) assert.NoError(t, err) // Verify flag values @@ -226,7 +225,7 @@ func TestStackpackInstallWithWaitJsonFlags(t *testing.T) { assert.NoError(t, err) assert.Equal(t, 100*time.Millisecond, timeoutValue) - nameValue, err := cmd.Flags().GetString(NameFlag) + nameValue, err := cmd.Flags().GetString("name") assert.NoError(t, err) - assert.Equal(t, testUploadName, nameValue) + assert.Equal(t, "test", nameValue) } diff --git a/cmd/stackpack/stackpack_list_instances_test.go b/cmd/stackpack/stackpack_list_instances_test.go index 51c922fc..8626faae 100644 --- a/cmd/stackpack/stackpack_list_instances_test.go +++ b/cmd/stackpack/stackpack_list_instances_test.go @@ -68,12 +68,12 @@ func TestStackpackListInstancePrintToTable(t *testing.T) { di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list-instances", "-n", testName) expectedTableCall := []printer.TableData{ { - Header: []string{"id", statusKey, versionKey, lastUpdatedColumn}, + Header: []string{"id", "status", "version", "last updated"}, Data: [][]interface{}{ {&id, statusInstalled, testVersion, expectedUpdateTimeLi}, {&id, statusInstalled, testVersion, beforeUpdateTimeLi}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: installedInstancesTitle}, + MissingTableDataMsg: printer.NotFoundMsg{Types: "installed StackPack instances"}, }, } assert.Equal(t, expectedTableCall, *cli.MockPrinter.TableCalls) @@ -81,7 +81,7 @@ func TestStackpackListInstancePrintToTable(t *testing.T) { func TestStackpackListInstancePrintToJson(t *testing.T) { cli, cmd := setupStackpackListInstanceFn(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list-instances", nameFlagArg, testName, "-o", "json") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list-instances", "--name", testName, "-o", "json") expectedJsonCalls := []map[string]interface{}{{ "instances": []stackstate_api.StackPackConfiguration{ { diff --git a/cmd/stackpack/stackpack_list_parameters_test.go b/cmd/stackpack/stackpack_list_parameters_test.go index da107338..a63ca80c 100644 --- a/cmd/stackpack/stackpack_list_parameters_test.go +++ b/cmd/stackpack/stackpack_list_parameters_test.go @@ -12,7 +12,7 @@ import ( ) var ( - parameterName = testZabbix + parameterName = "zabbix" stepName = "zabbix_instance_name" stepDisplayName = "Zabbix Instance Name" stepType = "Text" @@ -50,10 +50,10 @@ func setupStackpackListParametersFn(t *testing.T) (*di.MockDeps, *cobra.Command) func TestStackpackListParameterPrintToTable(t *testing.T) { cli, cmd := setupStackpackListParametersFn(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list-parameters", nameFlagArg, parameterName) + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list-parameters", "--name", parameterName) expectedTableCall := []printer.TableData{ { - Header: []string{NameFlag, displayNameColumn, testType}, + Header: []string{"name", "display name", "type"}, Data: [][]interface{}{{&firstStepName, &stepDisplayName, &stepType}, {&stepName, &stepDisplayName, &stepType}}, MissingTableDataMsg: printer.NotFoundMsg{Types: fmt.Sprintf("StackPack \"%s\"", parameterName)}, }, @@ -63,7 +63,7 @@ func TestStackpackListParameterPrintToTable(t *testing.T) { func TestStackpackListParameterPrintToJson(t *testing.T) { cli, cmd := setupStackpackListParametersFn(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list-parameters", nameFlagArg, parameterName, "-o", "json") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list-parameters", "--name", parameterName, "-o", "json") expectedJsonCalls := []map[string]interface{}{{ "parameters": []stackstate_api.StackPackStep{ { diff --git a/cmd/stackpack/stackpack_list_test.go b/cmd/stackpack/stackpack_list_test.go index bee689ff..7372126f 100644 --- a/cmd/stackpack/stackpack_list_test.go +++ b/cmd/stackpack/stackpack_list_test.go @@ -62,7 +62,7 @@ func TestStackpackListPrintToTable(t *testing.T) { di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list") expectedTableCall := []printer.TableData{ { - Header: []string{NameFlag, displayNameColumn, "installed version", "next version", "latest version", "instance count"}, + Header: []string{"name", "display name", "installed version", "next version", "latest version", "instance count"}, Data: [][]interface{}{ {awsName, ucmdDisplayName, ucmdbVersion, ucmdbVersion, ucmdbVersion, 1}, {ucmdbName, ucmdDisplayName, ucmdbVersion, ucmdbVersion, ucmdbVersion, 1}}, @@ -120,7 +120,7 @@ func TestStackpackListWithInstalledPrintToTable(t *testing.T) { di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list", "--installed") expectedTableCall := []printer.TableData{ { - Header: []string{NameFlag, displayNameColumn, "installed version", "next version", "latest version", "instance count"}, + Header: []string{"name", "display name", "installed version", "next version", "latest version", "instance count"}, Data: [][]interface{}{{name, displayName, version, nextVersion, latestVersion, 1}}, MissingTableDataMsg: printer.NotFoundMsg{Types: "StackPacks"}, }, diff --git a/cmd/stackpack/stackpack_list_versions_test.go b/cmd/stackpack/stackpack_list_versions_test.go index 7accfd99..40cfebfe 100644 --- a/cmd/stackpack/stackpack_list_versions_test.go +++ b/cmd/stackpack/stackpack_list_versions_test.go @@ -10,13 +10,9 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - testVersions = "versions" -) - var listVersionsMockResponse = []stackstate_api.StackPackVersionInfo{ - {Version: testInitialVersion, IsDev: false, IsInUse: true}, - {Version: testNextVersion, IsDev: false, IsInUse: false}, + {Version: "1.0.0", IsDev: false, IsInUse: true}, + {Version: "1.1.0", IsDev: false, IsInUse: false}, {Version: "2.0.0-SNAPSHOT.1", IsDev: true, IsInUse: false}, } @@ -29,17 +25,17 @@ func setupStackPackListVersionsCmd(t *testing.T) (*di.MockDeps, *cobra.Command) func TestStackpackListVersionsPrintToTable(t *testing.T) { cli, cmd := setupStackPackListVersionsCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list-versions", nameFlagArg, "kubernetes") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list-versions", "--name", "kubernetes") assert.Equal(t, []printer.TableData{ { - Header: []string{versionKey, "dev", "in use"}, + Header: []string{"version", "dev", "in use"}, Data: [][]interface{}{ - {testInitialVersion, false, true}, - {testNextVersion, false, false}, + {"1.0.0", false, true}, + {"1.1.0", false, false}, {"2.0.0-SNAPSHOT.1", true, false}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: testVersions}, + MissingTableDataMsg: printer.NotFoundMsg{Types: "versions"}, }, }, *cli.MockPrinter.TableCalls) @@ -49,10 +45,10 @@ func TestStackpackListVersionsPrintToTable(t *testing.T) { func TestStackpackListVersionsPrintToJson(t *testing.T) { cli, cmd := setupStackPackListVersionsCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list-versions", nameFlagArg, "kubernetes", "-o", "json") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list-versions", "--name", "kubernetes", "-o", "json") expectedJsonCalls := []map[string]interface{}{{ - testVersions: listVersionsMockResponse, + "versions": listVersionsMockResponse, }} assert.Equal(t, expectedJsonCalls, *cli.MockPrinter.PrintJsonCalls) assert.False(t, cli.MockPrinter.HasNonJsonCalls) @@ -62,13 +58,13 @@ func TestStackpackListVersionsEmpty(t *testing.T) { cli := di.NewMockDeps(t) cmd := StackpackListVersionsCommand(&cli.Deps) cli.MockClient.ApiMocks.StackpackApi.StackPackListVersionsResponse.Result = []stackstate_api.StackPackVersionInfo{} - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list-versions", nameFlagArg, "kubernetes") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "list-versions", "--name", "kubernetes") assert.Equal(t, []printer.TableData{ { - Header: []string{versionKey, "dev", "in use"}, + Header: []string{"version", "dev", "in use"}, Data: [][]interface{}{}, - MissingTableDataMsg: printer.NotFoundMsg{Types: testVersions}, + MissingTableDataMsg: printer.NotFoundMsg{Types: "versions"}, }, }, *cli.MockPrinter.TableCalls) } diff --git a/cmd/stackpack/stackpack_package_test.go b/cmd/stackpack/stackpack_package_test.go index a2b9cd74..773b89bb 100644 --- a/cmd/stackpack/stackpack_package_test.go +++ b/cmd/stackpack/stackpack_package_test.go @@ -12,12 +12,6 @@ import ( "github.com/stretchr/testify/require" ) -const ( - testMyStackpack = "my-stackpack" - missingManifestNameError = "name not found in stackpack.yaml" - missingManifestVersionError = "version not found in stackpack.yaml" -) - // setupStackPackPackageCmd creates a test command with mock dependencies func setupStackPackPackageCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { cli := di.NewMockDeps(t) @@ -58,9 +52,9 @@ func TestStackpackPackageCommand_DefaultBehavior(t *testing.T) { require.NoError(t, err) defer os.RemoveAll(tempDir) - stackpackDir := filepath.Join(tempDir, testStackPackName) + stackpackDir := filepath.Join(tempDir, "test-stackpack") require.NoError(t, os.MkdirAll(stackpackDir, 0755)) - createTestStackpack(t, stackpackDir, testStackPackName, testInitialVersion) + createTestStackpack(t, stackpackDir, "test-stackpack", "1.0.0") // Change to temp directory to test default current directory behavior originalWd, err := os.Getwd() @@ -99,9 +93,9 @@ func TestStackpackPackageCommand_CustomArchiveFile(t *testing.T) { require.NoError(t, err) defer os.RemoveAll(tempDir) - stackpackDir := filepath.Join(tempDir, testMyStackpack) + stackpackDir := filepath.Join(tempDir, "my-stackpack") require.NoError(t, os.MkdirAll(stackpackDir, 0755)) - createTestStackpack(t, stackpackDir, testMyStackpack, "2.1.0") + createTestStackpack(t, stackpackDir, "my-stackpack", "2.1.0") customZipPath := filepath.Join(tempDir, "custom-name.sts") cli, cmd := setupStackPackPackageCmd(t) @@ -124,9 +118,9 @@ func TestStackpackPackageCommand_ForceFlag(t *testing.T) { require.NoError(t, err) defer os.RemoveAll(tempDir) - stackpackDir := filepath.Join(tempDir, testStackPackName) + stackpackDir := filepath.Join(tempDir, "test-stackpack") require.NoError(t, os.MkdirAll(stackpackDir, 0755)) - createTestStackpack(t, stackpackDir, testStackPackName, testInitialVersion) + createTestStackpack(t, stackpackDir, "test-stackpack", "1.0.0") zipPath := filepath.Join(tempDir, "test-stackpack-1.0.0.sts") @@ -181,7 +175,7 @@ func TestStackpackPackageCommand_JSONOutput(t *testing.T) { jsonOutput := (*cli.MockPrinter.PrintJsonCalls)[0] // Check JSON structure - assert.Equal(t, true, jsonOutput[successKey]) + assert.Equal(t, true, jsonOutput["success"]) assert.Equal(t, "json-test", jsonOutput["stackpack_name"]) assert.Equal(t, "3.0.0", jsonOutput["stackpack_version"]) assert.Contains(t, jsonOutput["zip_file"], "json-test-3.0.0.sts") @@ -268,24 +262,24 @@ func TestStackpackPackageCommand_InvalidStackpackConf(t *testing.T) { { name: "missing name field", confContent: `version: "1.0.0"`, - expectedError: missingManifestNameError, + expectedError: "name not found in stackpack.yaml", }, { name: "missing version field", confContent: `name: "test"`, - expectedError: missingManifestVersionError, + expectedError: "version not found in stackpack.yaml", }, { name: "empty name field", confContent: `name: "" version: "1.0.0"`, - expectedError: missingManifestNameError, + expectedError: "name not found in stackpack.yaml", }, { name: "empty version field", confContent: `name: "test" version: ""`, - expectedError: missingManifestVersionError, + expectedError: "version not found in stackpack.yaml", }, } @@ -329,9 +323,9 @@ func TestStackpackPackageCommand_CreateOutputDirectory(t *testing.T) { require.NoError(t, err) defer os.RemoveAll(tempDir) - stackpackDir := filepath.Join(tempDir, testStackPackName) + stackpackDir := filepath.Join(tempDir, "test-stackpack") require.NoError(t, os.MkdirAll(stackpackDir, 0755)) - createTestStackpack(t, stackpackDir, testStackPackName, testInitialVersion) + createTestStackpack(t, stackpackDir, "test-stackpack", "1.0.0") // Create nested output directory path that doesn't exist outputDir := filepath.Join(tempDir, "output", "nested", "path") @@ -364,7 +358,7 @@ func TestYamlParser_Parse(t *testing.T) { name: "valid YAML with quotes", content: `name: "my-stackpack" version: "1.2.3"`, - expectedName: testMyStackpack, + expectedName: "my-stackpack", expectedVer: "1.2.3", expectError: false, }, @@ -372,7 +366,7 @@ version: "1.2.3"`, name: "valid YAML without quotes", content: `name: my-stackpack version: "1.2.3"`, - expectedName: testMyStackpack, + expectedName: "my-stackpack", expectedVer: "1.2.3", expectError: false, }, @@ -383,20 +377,20 @@ name: "test-app" # Another comment version: "2.0.0"`, expectedName: "test-app", - expectedVer: testMajorVersion, + expectedVer: "2.0.0", expectError: false, }, { name: "missing name", content: `version: "1.0.0"`, expectError: true, - errorContains: missingManifestNameError, + errorContains: "name not found in stackpack.yaml", }, { name: "missing version", content: `name: "test"`, expectError: true, - errorContains: missingManifestVersionError, + errorContains: "version not found in stackpack.yaml", }, { name: "invalid YAML syntax", diff --git a/cmd/stackpack/stackpack_scaffold_test.go b/cmd/stackpack/stackpack_scaffold_test.go index 59889381..91623a4f 100644 --- a/cmd/stackpack/stackpack_scaffold_test.go +++ b/cmd/stackpack/stackpack_scaffold_test.go @@ -12,15 +12,6 @@ import ( "github.com/stretchr/testify/require" ) -const ( - templateLocalDirFlagArg = "--template-local-dir" - testDefaultValue = "default-value" - templateNameFlagArg = "--template-name" - destinationDirFlagArg = "--destination-dir" - invalidNamePrefixError = "must start with a lowercase letter [a-z]" - invalidNameCharactersError = "lowercase letters, digits, and hyphens" -) - func setupStackpackScaffoldCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { cli := di.NewMockDeps(t) cmd := StackpackScaffoldCommand(&cli.Deps) @@ -42,7 +33,7 @@ func TestStackpackScaffoldCommand_RequiredFlags(t *testing.T) { }, { name: "valid minimal args with defaults", - args: []string{nameFlagArg, testStackPackName}, + args: []string{"--name", "test-stackpack"}, wantErr: false, }, } @@ -86,8 +77,8 @@ func TestStackpackScaffoldCommand_MutuallyExclusiveFlags(t *testing.T) { cli, cmd := setupStackpackScaffoldCmd(t) _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, - nameFlagArg, testStackPackName, - templateLocalDirFlagArg, "./templates", + "--name", "test-stackpack", + "--template-local-dir", "./templates", "--template-github-repo", "owner/repo", ) require.Error(t, err) @@ -176,19 +167,19 @@ func TestDefaultIfEmptyString(t *testing.T) { { name: "empty value returns default", value: "", - defaultValue: testDefaultValue, - expected: testDefaultValue, + defaultValue: "default-value", + expected: "default-value", }, { name: "non-empty value returns value", value: "custom-value", - defaultValue: testDefaultValue, + defaultValue: "default-value", expected: "custom-value", }, { name: "whitespace value returns whitespace", value: " ", - defaultValue: testDefaultValue, + defaultValue: "default-value", expected: " ", }, } @@ -209,7 +200,7 @@ func TestStackpackScaffoldCommand_LocalDirSource(t *testing.T) { // Create a mock template structure templateDir := filepath.Join(tempDir, "templates") - genericTemplateDir := filepath.Join(templateDir, defaultTemplateName) + genericTemplateDir := filepath.Join(templateDir, "generic") err = os.MkdirAll(genericTemplateDir, 0755) require.NoError(t, err) @@ -231,30 +222,30 @@ func TestStackpackScaffoldCommand_LocalDirSource(t *testing.T) { { name: "local directory source success", args: []string{ - nameFlagArg, testStackPackName, - templateLocalDirFlagArg, templateDir, - templateNameFlagArg, defaultTemplateName, - destinationDirFlagArg, destDir, + "--name", "test-stackpack", + "--template-local-dir", templateDir, + "--template-name", "generic", + "--destination-dir", destDir, }, wantErr: false, }, { name: "local directory source with non-existent template", args: []string{ - nameFlagArg, testStackPackName, - templateLocalDirFlagArg, templateDir, - templateNameFlagArg, "non-existent", - destinationDirFlagArg, destDir, + "--name", "test-stackpack", + "--template-local-dir", templateDir, + "--template-name", "non-existent", + "--destination-dir", destDir, }, wantErr: true, }, { name: "local directory source with non-existent directory", args: []string{ - nameFlagArg, testStackPackName, - templateLocalDirFlagArg, "/non/existent/path", - templateNameFlagArg, defaultTemplateName, - destinationDirFlagArg, destDir, + "--name", "test-stackpack", + "--template-local-dir", "/non/existent/path", + "--template-name", "generic", + "--destination-dir", destDir, }, wantErr: true, }, @@ -291,7 +282,7 @@ func TestStackpackScaffoldCommand_JSONOutput(t *testing.T) { // Create a mock template structure templateDir := filepath.Join(tempDir, "templates") - genericTemplateDir := filepath.Join(templateDir, defaultTemplateName) + genericTemplateDir := filepath.Join(templateDir, "generic") err = os.MkdirAll(genericTemplateDir, 0755) require.NoError(t, err) @@ -314,10 +305,10 @@ func TestStackpackScaffoldCommand_JSONOutput(t *testing.T) { { name: "regular text output", args: []string{ - nameFlagArg, testStackPackName, - templateLocalDirFlagArg, templateDir, - templateNameFlagArg, defaultTemplateName, - destinationDirFlagArg, destDir, + "--name", "test-stackpack", + "--template-local-dir", templateDir, + "--template-name", "generic", + "--destination-dir", destDir, }, expectJson: false, expectText: true, @@ -325,10 +316,10 @@ func TestStackpackScaffoldCommand_JSONOutput(t *testing.T) { { name: "JSON output", args: []string{ - nameFlagArg, testStackPackName, - templateLocalDirFlagArg, templateDir, - templateNameFlagArg, defaultTemplateName, - destinationDirFlagArg, destDir, + "--name", "test-stackpack", + "--template-local-dir", templateDir, + "--template-name", "generic", + "--destination-dir", destDir, "-o", "json", }, expectJson: true, @@ -348,7 +339,7 @@ func TestStackpackScaffoldCommand_JSONOutput(t *testing.T) { require.Len(t, *cli.MockPrinter.PrintJsonCalls, 1) jsonOutput := (*cli.MockPrinter.PrintJsonCalls)[0] // The JSON output should contain the scaffold result - assert.Contains(t, jsonOutput, successKey) + assert.Contains(t, jsonOutput, "success") // Verify no regular text calls were made for success messages assert.False(t, cli.MockPrinter.HasNonJsonCalls) @@ -376,7 +367,7 @@ func TestStackpackScaffoldCommand_ForceFlag(t *testing.T) { // Create a mock template structure templateDir := filepath.Join(tempDir, "templates") - genericTemplateDir := filepath.Join(templateDir, defaultTemplateName) + genericTemplateDir := filepath.Join(templateDir, "generic") err = os.MkdirAll(genericTemplateDir, 0755) require.NoError(t, err) @@ -398,10 +389,10 @@ func TestStackpackScaffoldCommand_ForceFlag(t *testing.T) { cli, cmd := setupStackpackScaffoldCmd(t) _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, - nameFlagArg, testStackPackName, - templateLocalDirFlagArg, templateDir, - templateNameFlagArg, defaultTemplateName, - destinationDirFlagArg, destDir, + "--name", "test-stackpack", + "--template-local-dir", templateDir, + "--template-name", "generic", + "--destination-dir", destDir, ) require.Error(t, err) assert.Contains(t, err.Error(), "conflicting files exist") @@ -411,10 +402,10 @@ func TestStackpackScaffoldCommand_ForceFlag(t *testing.T) { cli, cmd := setupStackpackScaffoldCmd(t) _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, - nameFlagArg, testStackPackName, - templateLocalDirFlagArg, templateDir, - templateNameFlagArg, defaultTemplateName, - destinationDirFlagArg, destDir, + "--name", "test-stackpack", + "--template-local-dir", templateDir, + "--template-name", "generic", + "--destination-dir", destDir, "--force", ) @@ -456,10 +447,10 @@ template: <<.TemplateName>> cli, cmd := setupStackpackScaffoldCmd(t) _, err = di.ExecuteCommandWithContext(&cli.Deps, cmd, - nameFlagArg, "my-awesome-stackpack", - templateLocalDirFlagArg, templateDir, - templateNameFlagArg, "custom-template", - destinationDirFlagArg, destDir, + "--name", "my-awesome-stackpack", + "--template-local-dir", templateDir, + "--template-name", "custom-template", + "--destination-dir", destDir, ) require.NoError(t, err) @@ -486,16 +477,16 @@ func TestRunStackpackScaffoldCommand_SourceSelection(t *testing.T) { name: "local directory source selected", args: ScaffoldArgs{ TemplateLocalDir: "/path/to/templates", - Name: testStackPackName, - TemplateName: defaultTemplateName, + Name: "test-stackpack", + TemplateName: "generic", }, expected: "local", }, { name: "github source selected with defaults", args: ScaffoldArgs{ - Name: testStackPackName, - TemplateName: defaultTemplateName, + Name: "test-stackpack", + TemplateName: "generic", }, expected: "github-default", }, @@ -503,8 +494,8 @@ func TestRunStackpackScaffoldCommand_SourceSelection(t *testing.T) { name: "github source selected with custom repo", args: ScaffoldArgs{ TemplateGitHubRepo: "custom/repo", - Name: testStackPackName, - TemplateName: defaultTemplateName, + Name: "test-stackpack", + TemplateName: "generic", }, expected: "github-custom", }, @@ -549,7 +540,7 @@ func TestDisplayNextSteps(t *testing.T) { cli := di.NewMockDeps(t) args := &ScaffoldArgs{ DestinationDir: "/path/to/destination", - Name: testStackPackName, + Name: "test-stackpack", } displayNextSteps(&cli.Deps, args) @@ -600,11 +591,11 @@ display_name: <<.DisplayName>> { name: "with display-name flag provided", args: []string{ - nameFlagArg, testMyStackpack, + "--name", "my-stackpack", "--display-name", "My Awesome StackPack", - templateLocalDirFlagArg, templateDir, - templateNameFlagArg, "custom-template", - destinationDirFlagArg, destDir, + "--template-local-dir", templateDir, + "--template-name", "custom-template", + "--destination-dir", destDir, }, expectedDisplayName: "My Awesome StackPack", description: "Should use provided display name", @@ -612,10 +603,10 @@ display_name: <<.DisplayName>> { name: "without display-name flag - should fallback to name", args: []string{ - nameFlagArg, "my-stackpack-fallback", - templateLocalDirFlagArg, templateDir, - templateNameFlagArg, "custom-template", - destinationDirFlagArg, destDir, + "--name", "my-stackpack-fallback", + "--template-local-dir", templateDir, + "--template-name", "custom-template", + "--destination-dir", destDir, }, expectedDisplayName: "my-stackpack-fallback", description: "Should fallback to name when display-name not provided", @@ -665,7 +656,7 @@ func TestValidateStackpackName(t *testing.T) { }, { name: "valid name with hyphens", - stackName: testMyStackpack, + stackName: "my-stackpack", wantErr: false, }, { @@ -683,83 +674,83 @@ func TestValidateStackpackName(t *testing.T) { name: "invalid starts with digit", stackName: "1-stackpack", wantErr: true, - errorSubstr: invalidNamePrefixError, + errorSubstr: "must start with a lowercase letter [a-z]", }, { name: "invalid starts with number", stackName: "2app", wantErr: true, - errorSubstr: invalidNamePrefixError, + errorSubstr: "must start with a lowercase letter [a-z]", }, // Invalid names - starts with hyphen { name: "invalid starts with hyphen", stackName: "-stackpack", wantErr: true, - errorSubstr: invalidNamePrefixError, + errorSubstr: "must start with a lowercase letter [a-z]", }, // Invalid names - uppercase letters { name: "invalid uppercase first letter", stackName: "My-Stackpack", wantErr: true, - errorSubstr: invalidNamePrefixError, + errorSubstr: "must start with a lowercase letter [a-z]", }, { name: "invalid camelCase", stackName: "myApp", wantErr: true, - errorSubstr: invalidNameCharactersError, + errorSubstr: "lowercase letters, digits, and hyphens", }, { name: "invalid all uppercase", stackName: "APP", wantErr: true, - errorSubstr: invalidNamePrefixError, + errorSubstr: "must start with a lowercase letter [a-z]", }, // Invalid names - spaces { name: "invalid with spaces", stackName: "my stackpack", wantErr: true, - errorSubstr: invalidNameCharactersError, + errorSubstr: "lowercase letters, digits, and hyphens", }, { name: "invalid app name with space", stackName: "app name", wantErr: true, - errorSubstr: invalidNameCharactersError, + errorSubstr: "lowercase letters, digits, and hyphens", }, // Invalid names - special characters { name: "invalid underscore", stackName: "my_stackpack", wantErr: true, - errorSubstr: invalidNameCharactersError, + errorSubstr: "lowercase letters, digits, and hyphens", }, { name: "invalid at symbol", stackName: "app@domain", wantErr: true, - errorSubstr: invalidNameCharactersError, + errorSubstr: "lowercase letters, digits, and hyphens", }, { name: "invalid dot", stackName: "stack.pack", wantErr: true, - errorSubstr: invalidNameCharactersError, + errorSubstr: "lowercase letters, digits, and hyphens", }, { name: "invalid slash", stackName: "my/app", wantErr: true, - errorSubstr: invalidNameCharactersError, + errorSubstr: "lowercase letters, digits, and hyphens", }, { name: "invalid colon", stackName: "app:v1", wantErr: true, - errorSubstr: invalidNameCharactersError, + errorSubstr: "lowercase letters, digits, and hyphens", }, } @@ -787,7 +778,7 @@ func TestStackpackScaffoldCommand_NameValidation(t *testing.T) { // Create a mock template structure templateDir := filepath.Join(tempDir, "templates") - genericTemplateDir := filepath.Join(templateDir, defaultTemplateName) + genericTemplateDir := filepath.Join(templateDir, "generic") err = os.MkdirAll(genericTemplateDir, 0755) require.NoError(t, err) @@ -810,51 +801,51 @@ func TestStackpackScaffoldCommand_NameValidation(t *testing.T) { { name: "valid name passes validation", args: []string{ - nameFlagArg, testMyStackpack, - templateLocalDirFlagArg, templateDir, - destinationDirFlagArg, destDir, + "--name", "my-stackpack", + "--template-local-dir", templateDir, + "--destination-dir", destDir, }, wantErr: false, }, { name: "invalid name with uppercase fails", args: []string{ - nameFlagArg, "My-Stackpack", - templateLocalDirFlagArg, templateDir, - destinationDirFlagArg, destDir, + "--name", "My-Stackpack", + "--template-local-dir", templateDir, + "--destination-dir", destDir, }, wantErr: true, - errorSubstr: invalidNamePrefixError, + errorSubstr: "must start with a lowercase letter [a-z]", }, { name: "invalid name with spaces fails", args: []string{ - nameFlagArg, "my stackpack", - templateLocalDirFlagArg, templateDir, - destinationDirFlagArg, destDir, + "--name", "my stackpack", + "--template-local-dir", templateDir, + "--destination-dir", destDir, }, wantErr: true, - errorSubstr: invalidNameCharactersError, + errorSubstr: "lowercase letters, digits, and hyphens", }, { name: "invalid name starting with number fails", args: []string{ - nameFlagArg, "1-app", - templateLocalDirFlagArg, templateDir, - destinationDirFlagArg, destDir, + "--name", "1-app", + "--template-local-dir", templateDir, + "--destination-dir", destDir, }, wantErr: true, - errorSubstr: invalidNamePrefixError, + errorSubstr: "must start with a lowercase letter [a-z]", }, { name: "invalid name with underscore fails", args: []string{ - nameFlagArg, "my_app", - templateLocalDirFlagArg, templateDir, - destinationDirFlagArg, destDir, + "--name", "my_app", + "--template-local-dir", templateDir, + "--destination-dir", destDir, }, wantErr: true, - errorSubstr: invalidNameCharactersError, + errorSubstr: "lowercase letters, digits, and hyphens", }, } diff --git a/cmd/stackpack/stackpack_test_deploy_test.go b/cmd/stackpack/stackpack_test_deploy_test.go index 96aa1e44..b832c7b5 100644 --- a/cmd/stackpack/stackpack_test_deploy_test.go +++ b/cmd/stackpack/stackpack_test_deploy_test.go @@ -14,11 +14,6 @@ import ( "github.com/stretchr/testify/require" ) -const ( - testDeployVersion = "1.0.0-cli-test.1" - testUpgrade = "upgrade" -) - // setupStackpackTestDeployCmd creates a test command with mock dependencies func setupStackpackTestDeployCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { cli := di.NewMockDeps(t) @@ -59,12 +54,12 @@ func TestBumpSnapshotVersion(t *testing.T) { }{ { name: "first cli-test version", - currentVersion: testInitialVersion, + currentVersion: "1.0.0", expectedVersion: "1.0.0-cli-test.10000", }, { name: "increment existing cli-test", - currentVersion: testDeployVersion, + currentVersion: "1.0.0-cli-test.1", expectedVersion: "1.0.0-cli-test.2", }, { @@ -113,7 +108,7 @@ func TestUpdateVersionInYaml(t *testing.T) { defer os.RemoveAll(tempDir) configPath := filepath.Join(tempDir, "stackpack.yaml") - originalVersion := testMajorVersion + originalVersion := "2.0.0" newVersion := "2.0.0-cli-test.1" // Create config with original version @@ -131,7 +126,7 @@ displayName: "Test StackPack"`, originalVersion) updatedInfo, err := parser.Parse(configPath) require.NoError(t, err) assert.Equal(t, newVersion, updatedInfo.Version) - assert.Equal(t, testStackPackName, updatedInfo.Name) + assert.Equal(t, "test-stackpack", updatedInfo.Name) } func TestCopyDirectory(t *testing.T) { @@ -209,12 +204,12 @@ func TestStackpackTestDeployCommand_DirectoryHandling(t *testing.T) { require.NoError(t, err) defer os.RemoveAll(tempDir) - stackpackDir := filepath.Join(tempDir, testStackPackName) + stackpackDir := filepath.Join(tempDir, "test-stackpack") require.NoError(t, os.MkdirAll(stackpackDir, 0755)) // Create required files - stackpackName := testStackPackName - stackPackCurrentVersion := testInitialVersion + stackpackName := "test-stackpack" + stackPackCurrentVersion := "1.0.0" createTestStackpack(t, stackpackDir, stackpackName, stackPackCurrentVersion) stackpackTestArchive := fmt.Sprintf("%s-%s-cli-test.10000.sts", stackpackName, stackPackCurrentVersion) @@ -258,15 +253,15 @@ func TestVersionRegexPatterns(t *testing.T) { }{ { name: "regular version", - version: testInitialVersion, + version: "1.0.0", expectedBase: "", expectedNumber: 0, isSnapshot: false, }, { name: "first cli-test", - version: testDeployVersion, - expectedBase: testInitialVersion, + version: "1.0.0-cli-test.1", + expectedBase: "1.0.0", expectedNumber: 1, isSnapshot: true, }, @@ -280,7 +275,7 @@ func TestVersionRegexPatterns(t *testing.T) { { name: "complex base version", version: "1.0.0-beta.1.cli-test.3", - expectedBase: testInitialVersion, + expectedBase: "1.0.0", expectedNumber: 3, isSnapshot: true, }, @@ -345,32 +340,32 @@ func TestCompareVersionsSemver(t *testing.T) { }{ { name: "equal versions", - v1: testInitialVersion, - v2: testInitialVersion, + v1: "1.0.0", + v2: "1.0.0", expected: 0, }, { name: "v1 less than v2", - v1: testInitialVersion, - v2: testNextVersion, + v1: "1.0.0", + v2: "1.1.0", expected: -1, }, { name: "v1 greater than v2", - v1: testMajorVersion, + v1: "2.0.0", v2: "1.9.9", expected: 1, }, { name: "pre-release versions - cli-test comparison", - v1: testDeployVersion, + v1: "1.0.0-cli-test.1", v2: "1.0.0-cli-test.2", expected: -1, }, { name: "pre-release vs release", - v1: testDeployVersion, - v2: testInitialVersion, + v1: "1.0.0-cli-test.1", + v2: "1.0.0", expected: -1, }, { @@ -402,13 +397,13 @@ func TestStackpackTestDeployCommand_InstallUpgradeLogic(t *testing.T) { }, { name: "already installed - should upgrade", - installedVersion: testInitialVersion, - expectedAction: testUpgrade, + installedVersion: "1.0.0", + expectedAction: "upgrade", }, { name: "already installed with pre-release - should upgrade", installedVersion: "1.0.0-beta.1", - expectedAction: testUpgrade, + expectedAction: "upgrade", }, } @@ -421,7 +416,7 @@ func TestStackpackTestDeployCommand_InstallUpgradeLogic(t *testing.T) { shouldUpgrade = true } - if tt.expectedAction == testUpgrade { + if tt.expectedAction == "upgrade" { assert.True(t, shouldUpgrade, "Should choose upgrade when stackpack is already installed") } else { assert.False(t, shouldUpgrade, "Should choose install when stackpack is not installed") diff --git a/cmd/stackpack/stackpack_uninstall_test.go b/cmd/stackpack/stackpack_uninstall_test.go index e962a8a8..ce5e866a 100644 --- a/cmd/stackpack/stackpack_uninstall_test.go +++ b/cmd/stackpack/stackpack_uninstall_test.go @@ -8,22 +8,18 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - testUninstallMessage = "Successfully uninstalled StackPack: name=zabbix id=39206337488300" -) - func setupStackpackUninstallFn(t *testing.T) (*di.MockDeps, *cobra.Command) { cli := di.NewMockDeps(t) cmd := StackpackUninstallCommand(&cli.Deps) - cli.MockClient.ApiMocks.StackpackApi.ProvisionUninstallResponse.Result = testUninstallMessage + cli.MockClient.ApiMocks.StackpackApi.ProvisionUninstallResponse.Result = "Successfully uninstalled StackPack: name=zabbix id=39206337488300" return &cli, cmd } func TestStackpackUninstallCommandPrintToConsole(t *testing.T) { cli, cmd := setupStackpackUninstallFn(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "uninstall", nameFlagArg, testZabbix, "--id", "39206337488300") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "uninstall", "--name", "zabbix", "--id", "39206337488300") - expectedSuccessMessage := []string{testUninstallMessage} + expectedSuccessMessage := []string{"Successfully uninstalled StackPack: name=zabbix id=39206337488300"} assert.True(t, cli.MockPrinter.HasNonJsonCalls) assert.Equal(t, expectedSuccessMessage, *cli.MockPrinter.SuccessCalls) @@ -31,11 +27,11 @@ func TestStackpackUninstallCommandPrintToConsole(t *testing.T) { func TestStackpackUninstallCommandPrintToJson(t *testing.T) { cli, cmd := setupStackpackUninstallFn(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "uninstall", nameFlagArg, testZabbix, "-i", "39206337488300", "-o", "json") + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "uninstall", "--name", "zabbix", "-i", "39206337488300", "-o", "json") expectedJsonCalls := []map[string]interface{}{{ - successKey: true, - "result": testUninstallMessage, + "success": true, + "result": "Successfully uninstalled StackPack: name=zabbix id=39206337488300", }} assert.False(t, cli.MockPrinter.HasNonJsonCalls) diff --git a/cmd/stackpack/stackpack_upgrade_test.go b/cmd/stackpack/stackpack_upgrade_test.go index 00f5374e..b8e4f7dc 100644 --- a/cmd/stackpack/stackpack_upgrade_test.go +++ b/cmd/stackpack/stackpack_upgrade_test.go @@ -11,9 +11,9 @@ import ( ) var ( - stackPackName = testZabbix - stackPackNextVersion = testMajorVersion - stackPackCurrentVersion = testInitialVersion + stackPackName = "zabbix" + stackPackNextVersion = "2.0.0" + stackPackCurrentVersion = "1.0.0" strategyFlag = "overwrite" ) @@ -35,13 +35,13 @@ func setupStackPackUpgradeCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { func TestStackpackUpgradePrintToTable(t *testing.T) { cli, cmd := setupStackPackUpgradeCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, testUpgrade, nameFlagArg, testZabbix, + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "upgrade", "--name", "zabbix", "--unlocked-strategy", strategyFlag, ) assert.Equal(t, []stackstate_api.UpgradeStackPackCall{{ - PstackPackName: testZabbix, + PstackPackName: "zabbix", Punlocked: &strategyFlag, }}, *cli.MockClient.ApiMocks.StackpackApi.UpgradeStackPackCalls) @@ -51,19 +51,19 @@ func TestStackpackUpgradePrintToTable(t *testing.T) { func TestStackpackUpgradePrintToJson(t *testing.T) { cli, cmd := setupStackPackUpgradeCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, testUpgrade, nameFlagArg, testZabbix, + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "upgrade", "--name", "zabbix", "--unlocked-strategy", strategyFlag, "-o", "json", ) assert.Equal(t, []stackstate_api.UpgradeStackPackCall{{ - PstackPackName: testZabbix, + PstackPackName: "zabbix", Punlocked: &strategyFlag, }}, *cli.MockClient.ApiMocks.StackpackApi.UpgradeStackPackCalls) expectedJsonCalls := []map[string]interface{}{{ - successKey: true, + "success": true, "current-version": stackPackCurrentVersion, "next-version": stackPackNextVersion, }} @@ -72,12 +72,12 @@ func TestStackpackUpgradePrintToJson(t *testing.T) { func TestStackpackUpgradeDefaultsUnlockedStrategy(t *testing.T) { cli, cmd := setupStackPackUpgradeCmd(t) - di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, testUpgrade, nameFlagArg, testZabbix) + di.ExecuteCommandWithContextUnsafe(&cli.Deps, cmd, "upgrade", "--name", "zabbix") defaultStrategy := "fail" assert.Equal(t, []stackstate_api.UpgradeStackPackCall{{ - PstackPackName: testZabbix, + PstackPackName: "zabbix", Punlocked: &defaultStrategy, }}, *cli.MockClient.ApiMocks.StackpackApi.UpgradeStackPackCalls) @@ -132,8 +132,8 @@ func TestStackpackUpgradeWithWaitTimeout(t *testing.T) { cli.MockClient.ApiMocks.StackpackApi.StackPackListResponse.Result = []stackstate_api.FullStackPack{provisioningStackPack} cli.MockClient.ApiMocks.StackpackApi.UpgradeStackPackResponse.Result = successfulResponseResult - _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, testUpgrade, nameFlagArg, stackPackName, - "--unlocked-strategy", strategyFlag, testWait, timeoutFlagArg, "50ms") + _, err := di.ExecuteCommandWithContext(&cli.Deps, cmd, "upgrade", "--name", stackPackName, + "--unlocked-strategy", strategyFlag, "--wait", "--timeout", "50ms") // Should return timeout error assert.Error(t, err) @@ -145,7 +145,7 @@ func TestStackpackUpgradeWithWaitJsonFlags(t *testing.T) { cmd := StackpackUpgradeCommand(&cli.Deps) // Test that wait and timeout flags can be parsed - err := cmd.ParseFlags([]string{nameFlagArg, testUploadName, testWait, timeoutFlagArg, "100ms"}) + err := cmd.ParseFlags([]string{"--name", "test", "--wait", "--timeout", "100ms"}) assert.NoError(t, err) // Verify flag values @@ -157,7 +157,7 @@ func TestStackpackUpgradeWithWaitJsonFlags(t *testing.T) { assert.NoError(t, err) assert.Equal(t, 100*time.Millisecond, timeoutValue) - nameValue, err := cmd.Flags().GetString(NameFlag) + nameValue, err := cmd.Flags().GetString("name") assert.NoError(t, err) - assert.Equal(t, testUploadName, nameValue) + assert.Equal(t, "test", nameValue) } diff --git a/cmd/stackpack/stackpack_upload_test.go b/cmd/stackpack/stackpack_upload_test.go index 0f593858..2ac8d7fc 100644 --- a/cmd/stackpack/stackpack_upload_test.go +++ b/cmd/stackpack/stackpack_upload_test.go @@ -11,10 +11,6 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - testDisplayTest = "display test" -) - func setupStackPackUploadCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { cli := di.NewMockDeps(t) cmd := StackpackUploadCommand(&cli.Deps) @@ -37,9 +33,9 @@ func TestUploadStackPackPrintsToTable(t *testing.T) { cli, cmd := setupStackPackUploadCmd(t) file := createTempFile() - name := testUploadName - displayName := testDisplayTest - version := testInitialVersion + name := "test" + displayName := "display test" + version := "1.0.0" stackpack := sts.StackPack{ Name: name, DisplayName: displayName, @@ -51,8 +47,8 @@ func TestUploadStackPackPrintsToTable(t *testing.T) { expectedTableCall := []printer.TableData{ { - Header: []string{NameFlag, displayNameColumn, versionKey}, - Data: [][]interface{}{{testUploadName, testDisplayTest, testInitialVersion}}, + Header: []string{"name", "display name", "version"}, + Data: [][]interface{}{{"test", "display test", "1.0.0"}}, }, } @@ -64,9 +60,9 @@ func TestUploadStackPackPrintToJson(t *testing.T) { file := createTempFile() stackpack := &sts.StackPack{ - Name: testUploadName, - DisplayName: testDisplayTest, - Version: testInitialVersion, + Name: "test", + DisplayName: "display test", + Version: "1.0.0", } cli.MockClient.ApiMocks.StackpackApi.StackPackUploadResponse.Result = *stackpack diff --git a/cmd/stackpack/stackpack_validate_test.go b/cmd/stackpack/stackpack_validate_test.go index f7269020..f65bdbd0 100644 --- a/cmd/stackpack/stackpack_validate_test.go +++ b/cmd/stackpack/stackpack_validate_test.go @@ -57,9 +57,9 @@ func TestValidate_WithDirectory_AutoPackages(t *testing.T) { require.NoError(t, err) defer os.RemoveAll(tempDir) - stackpackDir := filepath.Join(tempDir, testStackPackName) + stackpackDir := filepath.Join(tempDir, "test-stackpack") require.NoError(t, os.MkdirAll(stackpackDir, 0755)) - createTestStackpackDir(t, stackpackDir, testStackPackName, testInitialVersion) + createTestStackpackDir(t, stackpackDir, "test-stackpack", "1.0.0") _, err = di.ExecuteCommandWithContext(&cli.Deps, cmd, "--directory", stackpackDir) require.NoError(t, err) @@ -93,10 +93,10 @@ func TestValidate_WithDirectory_MissingStackpackYaml(t *testing.T) { require.NoError(t, err) defer os.RemoveAll(tempDir) - stackpackDir := filepath.Join(tempDir, testStackPackName) + stackpackDir := filepath.Join(tempDir, "test-stackpack") require.NoError(t, os.MkdirAll(filepath.Join(stackpackDir, "settings"), 0755)) require.NoError(t, os.MkdirAll(filepath.Join(stackpackDir, "resources"), 0755)) - require.NoError(t, os.WriteFile(filepath.Join(stackpackDir, "README.md"), []byte(testUploadName), 0644)) + require.NoError(t, os.WriteFile(filepath.Join(stackpackDir, "README.md"), []byte("test"), 0644)) _, err = di.ExecuteCommandWithContext(&cli.Deps, cmd, "--directory", stackpackDir) require.Error(t, err) @@ -140,7 +140,7 @@ func TestValidate_JSONOutput(t *testing.T) { require.Len(t, *cli.MockPrinter.PrintJsonCalls, 1) jsonOutput := (*cli.MockPrinter.PrintJsonCalls)[0] - assert.Equal(t, true, jsonOutput[successKey]) + assert.Equal(t, true, jsonOutput["success"]) } func TestValidate_MissingPath(t *testing.T) { @@ -162,7 +162,7 @@ func TestValidate_MutuallyExclusive(t *testing.T) { require.NoError(t, os.MkdirAll(stackpackDir, 0755)) stackpackFile := filepath.Join(tempDir, "test.sts") - require.NoError(t, os.WriteFile(stackpackFile, []byte(testUploadName), 0644)) + require.NoError(t, os.WriteFile(stackpackFile, []byte("test"), 0644)) _, err = di.ExecuteCommandWithContext(&cli.Deps, cmd, "-d", stackpackDir, @@ -186,9 +186,9 @@ func TestValidate_WithDirectory_IncludingOptionalItems(t *testing.T) { require.NoError(t, err) defer os.RemoveAll(tempDir) - stackpackDir := filepath.Join(tempDir, testStackPackName) + stackpackDir := filepath.Join(tempDir, "test-stackpack") require.NoError(t, os.MkdirAll(stackpackDir, 0755)) - createTestStackpackDir(t, stackpackDir, testStackPackName, testInitialVersion) + createTestStackpackDir(t, stackpackDir, "test-stackpack", "1.0.0") // Add optional items require.NoError(t, os.MkdirAll(filepath.Join(stackpackDir, "icons"), 0755)) diff --git a/cmd/topic/topic_describe_test.go b/cmd/topic/topic_describe_test.go index 1993f579..11e337f8 100644 --- a/cmd/topic/topic_describe_test.go +++ b/cmd/topic/topic_describe_test.go @@ -12,10 +12,6 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - messagesKey = "messages" -) - var ( MessageContents = map[string]interface{}{"test": "value"} MessageContentsJson = "{\"test\":\"value\"}" @@ -65,7 +61,7 @@ func TestTopicDescribeJson(t *testing.T) { expectedJson := []map[string]interface{}{ { - messagesKey: Part0MessagesList, + "messages": Part0MessagesList, }, } @@ -90,7 +86,7 @@ func TestTopicDescribeTable(t *testing.T) { {Message2.Key, Message2.Partition, Message2.Offset, MessageContentsJson}, {Message3.Key, Message3.Partition, Message3.Offset, MessageContentsJson}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: messagesKey}, + MissingTableDataMsg: printer.NotFoundMsg{Types: "messages"}, }, } @@ -118,7 +114,7 @@ func TestTopicDescribeTableSorting(t *testing.T) { {Message4.Key, Message4.Partition, Message4.Offset, MessageContentsJson}, {Message5.Key, Message5.Partition, Message5.Offset, MessageContentsJson}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: messagesKey}, + MissingTableDataMsg: printer.NotFoundMsg{Types: "messages"}, }, } @@ -229,7 +225,7 @@ func TestTopicDescribeMoreThanAvailable(t *testing.T) { expectedJson := []map[string]interface{}{ { - messagesKey: AllMessagesListSorted, + "messages": AllMessagesListSorted, }, } diff --git a/cmd/topology/topology_inspect_test.go b/cmd/topology/topology_inspect_test.go index 1e5b5353..62d40503 100644 --- a/cmd/topology/topology_inspect_test.go +++ b/cmd/topology/topology_inspect_test.go @@ -10,20 +10,6 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - typeColumn = "Type" -) - -const ( - testName = "Name" - testTypeKey = "_type" - identifiersColumn = "Identifiers" - querySnapshotResultType = "QuerySnapshotResult" - testMetadata = "metadata" - testComponentTypes = "componentTypes" - testIdentifiers = "identifiers" -) - const baseURL = "https://suse-observability-instance.com" func setInspectCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { @@ -49,7 +35,7 @@ func TestTopologyInspectJson(t *testing.T) { jsonData := jsonCalls[0] // Components are serialized from []Component struct - assert.NotNil(t, jsonData[componentsKey]) + assert.NotNil(t, jsonData["components"]) assert.True(t, len(calls) > 0, "API should have been called") } @@ -70,7 +56,7 @@ func TestTopologyInspectTable(t *testing.T) { assert.Len(t, tableCalls, 1) table := tableCalls[0] - assert.Equal(t, []string{testName, typeColumn, identifiersColumn}, table.Header) + assert.Equal(t, []string{"Name", "Type", "Identifiers"}, table.Header) assert.Len(t, table.Data, 1) row := table.Data[0] @@ -122,14 +108,14 @@ func TestTopologyInspectWithIdentifiers(t *testing.T) { func TestTopologyInspectNoResults(t *testing.T) { cli, cmd := setInspectCmd(t) cli.MockClient.ApiMocks.SnapshotApi.QuerySnapshotResponse.Result = sts.QuerySnapshotResult{ - Type: querySnapshotResultType, + Type: "QuerySnapshotResult", ViewSnapshotResponse: map[string]interface{}{ - testTypeKey: viewSnapshotType, - componentsKey: []interface{}{}, - testMetadata: map[string]interface{}{ - testComponentTypes: []interface{}{}, - "layers": []interface{}{}, - "domains": []interface{}{}, + "_type": "ViewSnapshot", + "components": []interface{}{}, + "metadata": map[string]interface{}{ + "componentTypes": []interface{}{}, + "layers": []interface{}{}, + "domains": []interface{}{}, }, }, } @@ -142,18 +128,18 @@ func TestTopologyInspectNoResults(t *testing.T) { assert.Len(t, tableCalls, 1) table := tableCalls[0] - assert.Equal(t, []string{testName, typeColumn, identifiersColumn}, table.Header) + assert.Equal(t, []string{"Name", "Type", "Identifiers"}, table.Header) assert.Len(t, table.Data, 0) - assert.Equal(t, printer.NotFoundMsg{Types: componentsKey}, table.MissingTableDataMsg) + assert.Equal(t, printer.NotFoundMsg{Types: "components"}, table.MissingTableDataMsg) } func TestTopologyInspectMultipleIdentifiers(t *testing.T) { cli, cmd := setInspectCmd(t) responseData := mockSnapshotResponse() // Modify to include multiple identifiers - components := responseData.ViewSnapshotResponse[componentsKey].([]interface{}) + components := responseData.ViewSnapshotResponse["components"].([]interface{}) comp := components[0].(map[string]interface{}) - comp[testIdentifiers] = []interface{}{"urn:test:1", "urn:test:2", "urn:test:3"} + comp["identifiers"] = []interface{}{"urn:test:1", "urn:test:2", "urn:test:3"} cli.MockClient.ApiMocks.SnapshotApi.QuerySnapshotResponse.Result = responseData cli.CurrentContext.URL = baseURL @@ -172,9 +158,9 @@ func TestTopologyInspectURLEncoding(t *testing.T) { cli, cmd := setInspectCmd(t) responseData := mockSnapshotResponse() // Set identifier with special characters - components := responseData.ViewSnapshotResponse[componentsKey].([]interface{}) + components := responseData.ViewSnapshotResponse["components"].([]interface{}) comp := components[0].(map[string]interface{}) - comp[testIdentifiers] = []interface{}{"urn:opentelemetry:namespace/service:component/name"} + comp["identifiers"] = []interface{}{"urn:opentelemetry:namespace/service:component/name"} cli.MockClient.ApiMocks.SnapshotApi.QuerySnapshotResponse.Result = responseData cli.CurrentContext.URL = baseURL @@ -182,7 +168,7 @@ func TestTopologyInspectURLEncoding(t *testing.T) { // Verify URL encoding in link jsonCalls := *cli.MockPrinter.PrintJsonCalls - returnedComponents := jsonCalls[0][componentsKey].([]Component) + returnedComponents := jsonCalls[0]["components"].([]Component) // url.PathEscape encodes / to %2F, but : is not encoded, and base URL is prefixed expectedLink := baseURL + "/#/components/urn:opentelemetry:namespace%2Fservice:component%2Fname" assert.Equal(t, expectedLink, returnedComponents[0].Link) @@ -192,15 +178,15 @@ func TestTopologyInspectWithEnvironment(t *testing.T) { cli, cmd := setInspectCmd(t) responseData := mockSnapshotResponse() // Add environment to component - components := responseData.ViewSnapshotResponse[componentsKey].([]interface{}) + components := responseData.ViewSnapshotResponse["components"].([]interface{}) comp := components[0].(map[string]interface{}) comp["environment"] = float64(123) // Add environment to metadata - metadata := responseData.ViewSnapshotResponse[testMetadata].(map[string]interface{}) + metadata := responseData.ViewSnapshotResponse["metadata"].(map[string]interface{}) metadata["environments"] = []interface{}{ map[string]interface{}{ - "id": float64(123), - nameKey: "Production", + "id": float64(123), + "name": "Production", }, } cli.MockClient.ApiMocks.SnapshotApi.QuerySnapshotResponse.Result = responseData @@ -212,7 +198,7 @@ func TestTopologyInspectWithEnvironment(t *testing.T) { jsonCalls := *cli.MockPrinter.PrintJsonCalls assert.Len(t, jsonCalls, 1) jsonData := jsonCalls[0] - assert.NotNil(t, jsonData[componentsKey]) + assert.NotNil(t, jsonData["components"]) } func TestTopologyInspectTypeRequired(t *testing.T) { @@ -254,7 +240,7 @@ func TestTopologyInspectWithBaseURL(t *testing.T) { jsonData := jsonCalls[0] // Components are serialized from []Component struct - components := jsonData[componentsKey].([]Component) + components := jsonData["components"].([]Component) assert.NotNil(t, components) expectedLink := "https://stackstate.example.com:8080/#/components/urn:test:component:1" @@ -264,9 +250,9 @@ func TestTopologyInspectWithBaseURL(t *testing.T) { func TestTopologyInspectFetchTimeout(t *testing.T) { cli, cmd := setInspectCmd(t) cli.MockClient.ApiMocks.SnapshotApi.QuerySnapshotResponse.Result = sts.QuerySnapshotResult{ - Type: querySnapshotResultType, + Type: "QuerySnapshotResult", ViewSnapshotResponse: map[string]interface{}{ - testTypeKey: "ViewSnapshotFetchTimeout", + "_type": "ViewSnapshotFetchTimeout", "usedTimeoutSeconds": float64(30), }, } @@ -282,9 +268,9 @@ func TestTopologyInspectFetchTimeout(t *testing.T) { func TestTopologyInspectTooManyActiveQueries(t *testing.T) { cli, cmd := setInspectCmd(t) cli.MockClient.ApiMocks.SnapshotApi.QuerySnapshotResponse.Result = sts.QuerySnapshotResult{ - Type: querySnapshotResultType, + Type: "QuerySnapshotResult", ViewSnapshotResponse: map[string]interface{}{ - testTypeKey: "ViewSnapshotTooManyActiveQueries", + "_type": "ViewSnapshotTooManyActiveQueries", }, } cli.CurrentContext.URL = baseURL @@ -299,10 +285,10 @@ func TestTopologyInspectTooManyActiveQueries(t *testing.T) { func TestTopologyInspectTopologySizeOverflow(t *testing.T) { cli, cmd := setInspectCmd(t) cli.MockClient.ApiMocks.SnapshotApi.QuerySnapshotResponse.Result = sts.QuerySnapshotResult{ - Type: querySnapshotResultType, + Type: "QuerySnapshotResult", ViewSnapshotResponse: map[string]interface{}{ - testTypeKey: "ViewSnapshotTopologySizeOverflow", - "maxSize": float64(10000), + "_type": "ViewSnapshotTopologySizeOverflow", + "maxSize": float64(10000), }, } cli.CurrentContext.URL = baseURL @@ -317,9 +303,9 @@ func TestTopologyInspectTopologySizeOverflow(t *testing.T) { func TestTopologyInspectDataUnavailable(t *testing.T) { cli, cmd := setInspectCmd(t) cli.MockClient.ApiMocks.SnapshotApi.QuerySnapshotResponse.Result = sts.QuerySnapshotResult{ - Type: querySnapshotResultType, + Type: "QuerySnapshotResult", ViewSnapshotResponse: map[string]interface{}{ - testTypeKey: "ViewSnapshotDataUnavailable", + "_type": "ViewSnapshotDataUnavailable", "unavailableAtEpochMs": float64(1000000), "availableSinceEpochMs": float64(1609459200000), }, diff --git a/cmd/topology/topology_state_test.go b/cmd/topology/topology_state_test.go index a731fd8e..dec8ef46 100644 --- a/cmd/topology/topology_state_test.go +++ b/cmd/topology/topology_state_test.go @@ -10,12 +10,6 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - testType = "type" - testState = "state" - testHealthState = "healthState" -) - func setStateCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { cli := di.NewMockDeps(t) cmd := StateCommand(&cli.Deps) @@ -37,10 +31,10 @@ func TestTopologyStateJson(t *testing.T) { assert.Len(t, jsonCalls, 1) jsonData := jsonCalls[0] - assert.NotNil(t, jsonData[componentsKey]) + assert.NotNil(t, jsonData["components"]) // Check the component has the health state - components := jsonData[componentsKey].([]ComponentState) + components := jsonData["components"].([]ComponentState) assert.Len(t, components, 1) assert.Equal(t, "CRITICAL", components[0].HealthState) } @@ -60,7 +54,7 @@ func TestTopologyStateTable(t *testing.T) { assert.Len(t, tableCalls, 1) table := tableCalls[0] - assert.Equal(t, []string{testName, typeColumn, "Health State", identifiersColumn}, table.Header) + assert.Equal(t, []string{"Name", "Type", "Health State", "Identifiers"}, table.Header) assert.Len(t, table.Data, 1) row := table.Data[0] @@ -111,14 +105,14 @@ func TestTopologyStateWithIdentifiers(t *testing.T) { func TestTopologyStateNoResults(t *testing.T) { cli, cmd := setStateCmd(t) cli.MockClient.ApiMocks.SnapshotApi.QuerySnapshotResponse.Result = sts.QuerySnapshotResult{ - Type: querySnapshotResultType, + Type: "QuerySnapshotResult", ViewSnapshotResponse: map[string]interface{}{ - testTypeKey: viewSnapshotType, - componentsKey: []interface{}{}, - testMetadata: map[string]interface{}{ - testComponentTypes: []interface{}{}, - "layers": []interface{}{}, - "domains": []interface{}{}, + "_type": "ViewSnapshot", + "components": []interface{}{}, + "metadata": map[string]interface{}{ + "componentTypes": []interface{}{}, + "layers": []interface{}{}, + "domains": []interface{}{}, }, }, } @@ -130,32 +124,32 @@ func TestTopologyStateNoResults(t *testing.T) { assert.Len(t, tableCalls, 1) table := tableCalls[0] - assert.Equal(t, []string{testName, typeColumn, "Health State", identifiersColumn}, table.Header) + assert.Equal(t, []string{"Name", "Type", "Health State", "Identifiers"}, table.Header) assert.Len(t, table.Data, 0) - assert.Equal(t, printer.NotFoundMsg{Types: componentsKey}, table.MissingTableDataMsg) + assert.Equal(t, printer.NotFoundMsg{Types: "components"}, table.MissingTableDataMsg) } func TestTopologyStateDefaultsToUnknown(t *testing.T) { cli, cmd := setStateCmd(t) // Response without state field cli.MockClient.ApiMocks.SnapshotApi.QuerySnapshotResponse.Result = sts.QuerySnapshotResult{ - Type: querySnapshotResultType, + Type: "QuerySnapshotResult", ViewSnapshotResponse: map[string]interface{}{ - testTypeKey: viewSnapshotType, - componentsKey: []interface{}{ + "_type": "ViewSnapshot", + "components": []interface{}{ map[string]interface{}{ - "id": float64(229404307680647), - nameKey: "test-component", - testType: float64(239975151751041), - testIdentifiers: []interface{}{"urn:test:component:1"}, + "id": float64(229404307680647), + "name": "test-component", + "type": float64(239975151751041), + "identifiers": []interface{}{"urn:test:component:1"}, // No state field }, }, - testMetadata: map[string]interface{}{ - testComponentTypes: []interface{}{ + "metadata": map[string]interface{}{ + "componentTypes": []interface{}{ map[string]interface{}{ - "id": float64(239975151751041), - nameKey: "test type", + "id": float64(239975151751041), + "name": "test type", }, }, }, @@ -175,43 +169,43 @@ func TestTopologyStateDefaultsToUnknown(t *testing.T) { func TestTopologyStateLimit(t *testing.T) { cli, cmd := setStateCmd(t) cli.MockClient.ApiMocks.SnapshotApi.QuerySnapshotResponse.Result = sts.QuerySnapshotResult{ - Type: querySnapshotResultType, + Type: "QuerySnapshotResult", ViewSnapshotResponse: map[string]interface{}{ - testTypeKey: viewSnapshotType, - componentsKey: []interface{}{ + "_type": "ViewSnapshot", + "components": []interface{}{ map[string]interface{}{ - "id": float64(1), - nameKey: "component-1", - testType: float64(239975151751041), - testIdentifiers: []interface{}{"urn:test:1"}, - testState: map[string]interface{}{ - testHealthState: "CLEAR", + "id": float64(1), + "name": "component-1", + "type": float64(239975151751041), + "identifiers": []interface{}{"urn:test:1"}, + "state": map[string]interface{}{ + "healthState": "CLEAR", }, }, map[string]interface{}{ - "id": float64(2), - nameKey: "component-2", - testType: float64(239975151751041), - testIdentifiers: []interface{}{"urn:test:2"}, - testState: map[string]interface{}{ - testHealthState: "CRITICAL", + "id": float64(2), + "name": "component-2", + "type": float64(239975151751041), + "identifiers": []interface{}{"urn:test:2"}, + "state": map[string]interface{}{ + "healthState": "CRITICAL", }, }, map[string]interface{}{ - "id": float64(3), - nameKey: "component-3", - testType: float64(239975151751041), - testIdentifiers: []interface{}{"urn:test:3"}, - testState: map[string]interface{}{ - testHealthState: "DEVIATING", + "id": float64(3), + "name": "component-3", + "type": float64(239975151751041), + "identifiers": []interface{}{"urn:test:3"}, + "state": map[string]interface{}{ + "healthState": "DEVIATING", }, }, }, - testMetadata: map[string]interface{}{ - testComponentTypes: []interface{}{ + "metadata": map[string]interface{}{ + "componentTypes": []interface{}{ map[string]interface{}{ - "id": float64(239975151751041), - nameKey: "test type", + "id": float64(239975151751041), + "name": "test type", }, }, }, diff --git a/cmd/topology/topology_test_helper.go b/cmd/topology/topology_test_helper.go index 15013683..f25d1932 100644 --- a/cmd/topology/topology_test_helper.go +++ b/cmd/topology/topology_test_helper.go @@ -9,11 +9,11 @@ func mockSnapshotResponse() sts.QuerySnapshotResult { return sts.QuerySnapshotResult{ Type: "QuerySnapshotResult", ViewSnapshotResponse: map[string]interface{}{ - "_type": viewSnapshotType, - componentsKey: []interface{}{ + "_type": "ViewSnapshot", + "components": []interface{}{ map[string]interface{}{ "id": float64(229404307680647), - nameKey: "test-component", + "name": "test-component", "typeIdentifier": "urn:test:component-type:test", "layerIdentifier": "urn:test:layer:test", "domainIdentifier": "urn:test:domain:test", @@ -27,20 +27,20 @@ func mockSnapshotResponse() sts.QuerySnapshotResult { "metadata": map[string]interface{}{ "componentTypes": []interface{}{ map[string]interface{}{ - identifierKey: "urn:test:component-type:test", - nameKey: "test type", + "identifier": "urn:test:component-type:test", + "name": "test type", }, }, "layers": []interface{}{ map[string]interface{}{ - identifierKey: "urn:test:layer:test", - nameKey: "Test Layer", + "identifier": "urn:test:layer:test", + "name": "Test Layer", }, }, "domains": []interface{}{ map[string]interface{}{ - identifierKey: "urn:test:domain:test", - nameKey: "Test Domain", + "identifier": "urn:test:domain:test", + "name": "Test Domain", }, }, }, diff --git a/cmd/topologysync/topologysync_describe_test.go b/cmd/topologysync/topologysync_describe_test.go index ff10c06a..44edccc5 100644 --- a/cmd/topologysync/topologysync_describe_test.go +++ b/cmd/topologysync/topologysync_describe_test.go @@ -10,11 +10,6 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - testNoChanges = "+0 -0" - testSynchronizations = "synchronizations" -) - var ( Error1 = stackstate_api.NewTopologyStreamError(stackstate_api.MESSAGELEVEL_WARN, "Oops") Error2 = stackstate_api.NewTopologyStreamError(stackstate_api.MESSAGELEVEL_ERROR, "Welp, better leave the premises quickly.") @@ -92,9 +87,9 @@ func TestTopologySyncDescribeErrors(t *testing.T) { { Header: []string{"Id", "Name", "Identifier", "Status", "Components", "Relations", "Errors"}, Data: [][]interface{}{ - {Topo1.NodeId, Topo1.Name, "-", Topo1.Status, testNoChanges, testNoChanges, int64(0)}, + {Topo1.NodeId, Topo1.Name, "-", Topo1.Status, "+0 -0", "+0 -0", int64(0)}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: testSynchronizations}, + MissingTableDataMsg: printer.NotFoundMsg{Types: "synchronizations"}, }, { Header: []string{"External ID", "Level", "Message"}, diff --git a/cmd/topologysync/topologysync_list_test.go b/cmd/topologysync/topologysync_list_test.go index 69494679..cd567dcb 100644 --- a/cmd/topologysync/topologysync_list_test.go +++ b/cmd/topologysync/topologysync_list_test.go @@ -33,12 +33,12 @@ func TestTopologySyncListTable(t *testing.T) { { Header: []string{"Id", "Name", "Identifier", "Status", "Components", "Relations", "Errors"}, Data: [][]interface{}{ - {Topo1.NodeId, Topo1.Name, "-", Topo1.Status, testNoChanges, testNoChanges, int64(0)}, + {Topo1.NodeId, Topo1.Name, "-", Topo1.Status, "+0 -0", "+0 -0", int64(0)}, {Topo2.NodeId, Topo2.Name, "-", Topo2.Status, "+23 -5", "+23 -5", int64(0)}, {Topo3.NodeId, Topo3.Name, "-", Topo3.Status, "+23 -12345", "+12345 -23", int64(1)}, {Topo4.NodeId, Topo4.Name, "-", Topo4.Status, "+12345 -12345", "+12345 -12345", int64(23)}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: testSynchronizations}, + MissingTableDataMsg: printer.NotFoundMsg{Types: "synchronizations"}, }, } @@ -54,7 +54,7 @@ func TestTopologySyncListJson(t *testing.T) { expected := []map[string]interface{}{ { - testSynchronizations: AllTopos, + "synchronizations": AllTopos, }, } diff --git a/internal/client/client_test.go b/internal/client/client_test.go index 03861a2a..1ba1407b 100644 --- a/internal/client/client_test.go +++ b/internal/client/client_test.go @@ -12,12 +12,6 @@ import ( "github.com/stretchr/testify/require" ) -const ( - testVersion = "1.2.3" - testVersionDiff = "c0ffee23" - testVersionCommit = "yes" -) - func setupClient() (StackStateClient, *stackstate_api.ServerApiMock) { serverApi := stackstate_api.NewServerApiMock() api := stackstate_api.APIClient{ @@ -60,13 +54,13 @@ func TestCombineURLAndApi(t *testing.T) { } func TestVersionToString(t *testing.T) { - assert.Equal(t, testVersion, VersionToString(stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3})) - assert.Equal(t, "1.2.3+c0ffee23", VersionToString(stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3, Diff: testVersionDiff})) - assert.Equal(t, "1.2.3+c0ffee23-yes", VersionToString(stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3, Diff: testVersionDiff, Commit: testVersionCommit})) - assert.Equal(t, "1.2.3+c0ffee23-yes-dev", VersionToString(stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3, Diff: testVersionDiff, Commit: testVersionCommit, IsDev: true})) + assert.Equal(t, "1.2.3", VersionToString(stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3})) + assert.Equal(t, "1.2.3+c0ffee23", VersionToString(stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3, Diff: "c0ffee23"})) + assert.Equal(t, "1.2.3+c0ffee23-yes", VersionToString(stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3, Diff: "c0ffee23", Commit: "yes"})) + assert.Equal(t, "1.2.3+c0ffee23-yes-dev", VersionToString(stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3, Diff: "c0ffee23", Commit: "yes", IsDev: true})) assert.Equal(t, "1.2.3-dev", VersionToString(stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3, IsDev: true})) - assert.Equal(t, "1.2.3-yes-dev", VersionToString(stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3, Commit: testVersionCommit, IsDev: true})) - assert.Equal(t, "1.2.3-yes", VersionToString(stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3, Commit: testVersionCommit})) + assert.Equal(t, "1.2.3-yes-dev", VersionToString(stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3, Commit: "yes", IsDev: true})) + assert.Equal(t, "1.2.3-yes", VersionToString(stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3, Commit: "yes"})) } type VersionTest struct { @@ -88,7 +82,7 @@ func TestVersionCompatibilityCheck(t *testing.T) { {Server: V(1, 2, 3), Cmd: "1.0.0", Result: nil}, {Server: V(1, 2, 3), Cmd: "1.0.6", Result: nil}, {Server: V(1, 2, 3), Cmd: "1.2.0", Result: nil}, - {Server: V(1, 2, 3), Cmd: testVersion, Result: nil}, + {Server: V(1, 2, 3), Cmd: "1.2.3", Result: nil}, // Server version really only needs to be greater than or equal to the command minimum version, even newer major versions are fine {Server: V(2, 2, 3), Cmd: "1.2.4", Result: nil}, @@ -97,25 +91,25 @@ func TestVersionCompatibilityCheck(t *testing.T) { {Server: V(1, 2, 3), Cmd: "1.2.2-alpha.preview+123", Result: nil}, { Server: stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3, Diff: "diff", Commit: "deadbeef"}, - Cmd: testVersion, + Cmd: "1.2.3", // FIXME Should be NewAPIVersionMismatchError("1.2.3+diff-deadbeef", "1.2.3"), Result: nil, }, // Incompatible versions are detected. {Server: V(1, 2, 3), Cmd: "1.2.3-alpha.preview+123", Result: nil}, - {Server: V(1, 2, 3), Cmd: "1.2.4", Result: NewAPIVersionMismatchError(testVersion, "1.2.4")}, - {Server: V(1, 2, 3), Cmd: "1.3.3", Result: NewAPIVersionMismatchError(testVersion, "1.3.3")}, - {Server: V(1, 2, 3), Cmd: "2.2.4", Result: NewAPIVersionMismatchError(testVersion, "2.2.4")}, + {Server: V(1, 2, 3), Cmd: "1.2.4", Result: NewAPIVersionMismatchError("1.2.3", "1.2.4")}, + {Server: V(1, 2, 3), Cmd: "1.3.3", Result: NewAPIVersionMismatchError("1.2.3", "1.3.3")}, + {Server: V(1, 2, 3), Cmd: "2.2.4", Result: NewAPIVersionMismatchError("1.2.3", "2.2.4")}, // Pre-release versions are less than the released version, so they are not sufficient { Server: stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3, Commit: "deadbeef"}, - Cmd: testVersion, - Result: NewAPIVersionMismatchError("1.2.3-deadbeef", testVersion), + Cmd: "1.2.3", + Result: NewAPIVersionMismatchError("1.2.3-deadbeef", "1.2.3"), }, { Server: stackstate_api.ServerVersion{Major: 1, Minor: 2, Patch: 3, IsDev: true}, - Cmd: testVersion, - Result: NewAPIVersionMismatchError("1.2.3-dev", testVersion), + Cmd: "1.2.3", + Result: NewAPIVersionMismatchError("1.2.3-dev", "1.2.3"), }, // Invalid versions are detected. { diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 9ad47e68..0d537844 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -9,10 +9,6 @@ import ( ) const ( - testLocalURL = "http://localhost:8080" - testAPIToken = "foo" - testOtherURL = "http://other:8080" - malformedCertificateError = "x509: malformed certificate" //nolint:lll selfSignedBase64Cert = "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUNKekNDQWRHZ0F3SUJBZ0lVVi9hSmoxZkVjQ2dOVTJGYWZZMHVSTHF5N21Bd0RRWUpLb1pJaHZjTkFRRUwKQlFBd0tURW5NQ1VHQTFVRUF3d2VkbWxzYVdGcmIzWXVjMkZ1WkdKdmVDNXpkR0ZqYTNOMFlYUmxMbWx2TUNBWApEVEkxTURjeU1USXdORFUxTmxvWUR6SXhNalV3TmpJM01qQTBOVFUyV2pBcE1TY3dKUVlEVlFRRERCNTJhV3hwCllXdHZkaTV6WVc1a1ltOTRMbk4wWVdOcmMzUmhkR1V1YVc4d1hEQU5CZ2txaGtpRzl3MEJBUUVGQUFOTEFEQkkKQWtFQW9wUXVPSmZJa0xDV0pLVDcwaGdiSEpwVWtFQitaYTJwOXVBMUlOUktNNEFyN2RjVjltdXhOS09jSloycwpWdCtiK1lTS1c4cnRteE5QUVh1RTJENHRlUUlEQVFBQm80SE9NSUhMTUIwR0ExVWREZ1FXQkJRVTBPTFZRRzEyCndNb0VLSGdxSG1aeVhTelozekFmQmdOVkhTTUVHREFXZ0JRVTBPTFZRRzEyd01vRUtIZ3FIbVp5WFN6WjN6QVAKQmdOVkhSTUJBZjhFQlRBREFRSC9NSGdHQTFVZEVRUnhNRytDSG5acGJHbGhhMjkyTG5OaGJtUmliM2d1YzNSaApZMnR6ZEdGMFpTNXBiNElqYjNSc2NDMTJhV3hwWVd0dmRpNXpZVzVrWW05NExuTjBZV05yYzNSaGRHVXVhVytDCktHOTBiSEF0YUhSMGNDMTJhV3hwWVd0dmRpNXpZVzVrWW05NExuTjBZV05yYzNSaGRHVXVhVzh3RFFZSktvWkkKaHZjTkFRRUxCUUFEUVFBZllBVk1lTVJHbFcrR1prellPeGRIaVhYNEFISHA5SWxvWlBMbUJHNExtdlpDODBoVgpLNGNSVUVHSGtSeGdrMGgwYzl3RDhOZFZSM1FuRTBubjZXUEUKLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo=" ) @@ -38,14 +34,14 @@ current-context: prod assert.NoError(t, err) assert.Len(t, cfg.Contexts, 2) assert.Equal(t, "prod", cfg.CurrentContext) - assert.Equal(t, testLocalURL, cfg.Contexts[0].Context.URL) - assert.Equal(t, testAPIToken, cfg.Contexts[0].Context.APIToken) + assert.Equal(t, "http://localhost:8080", cfg.Contexts[0].Context.URL) + assert.Equal(t, "foo", cfg.Contexts[0].Context.APIToken) assert.Empty(t, cfg.Contexts[0].Context.ServiceToken) assert.Equal(t, "/api", cfg.Contexts[0].Context.APIPath) assert.Equal(t, "/admin", cfg.Contexts[0].Context.AdminAPIPath) assert.Equal(t, selfSignedBase64Cert, cfg.Contexts[0].Context.CaCertBase64Data) assert.Equal(t, "http://prod:8080", cfg.Contexts[1].Context.URL) - assert.Equal(t, testAPIToken, cfg.Contexts[1].Context.ServiceToken) + assert.Equal(t, "foo", cfg.Contexts[1].Context.ServiceToken) assert.Equal(t, "/hidden/api", cfg.Contexts[1].Context.APIPath) assert.Equal(t, "/admin/api", cfg.Contexts[1].Context.AdminAPIPath) assert.Empty(t, cfg.Contexts[1].Context.APIToken) @@ -79,8 +75,8 @@ api-token: foo assert.NoError(t, err) assert.Len(t, cfg.Contexts, 1) assert.Equal(t, "default", cfg.CurrentContext) - assert.Equal(t, testLocalURL, cfg.Contexts[0].Context.URL) - assert.Equal(t, testAPIToken, cfg.Contexts[0].Context.APIToken) + assert.Equal(t, "http://localhost:8080", cfg.Contexts[0].Context.URL) + assert.Equal(t, "foo", cfg.Contexts[0].Context.APIToken) assert.Empty(t, cfg.Contexts[0].Context.ServiceToken) assert.Equal(t, "/api", cfg.Contexts[0].Context.APIPath) assert.Equal(t, "/admin", cfg.Contexts[0].Context.AdminAPIPath) @@ -190,45 +186,45 @@ current-context: default func TestMergeWithNoTokenOverride(t *testing.T) { c := &StsContext{ - URL: testLocalURL, + URL: "http://localhost:8080", } f := &StsContext{ - URL: testOtherURL, - APIToken: testAPIToken, + URL: "http://other:8080", + APIToken: "foo", } n := c.Merge(f) - assert.Equal(t, testLocalURL, n.URL) - assert.Equal(t, testAPIToken, n.APIToken) + assert.Equal(t, "http://localhost:8080", n.URL) + assert.Equal(t, "foo", n.APIToken) } func TestMergeWithSameTokenOverride(t *testing.T) { c := &StsContext{ - URL: testLocalURL, + URL: "http://localhost:8080", APIToken: "bar", } f := &StsContext{ - URL: testOtherURL, - APIToken: testAPIToken, + URL: "http://other:8080", + APIToken: "foo", } n := c.Merge(f) - assert.Equal(t, testLocalURL, n.URL) + assert.Equal(t, "http://localhost:8080", n.URL) assert.Equal(t, "bar", n.APIToken) } func TestMergeWithOtherTokenOverride(t *testing.T) { c := &StsContext{ - URL: testLocalURL, + URL: "http://localhost:8080", ServiceToken: "bar", } f := &StsContext{ - URL: testOtherURL, - APIToken: testAPIToken, + URL: "http://other:8080", + APIToken: "foo", } n := c.Merge(f) - assert.Equal(t, testLocalURL, n.URL) + assert.Equal(t, "http://localhost:8080", n.URL) assert.Equal(t, "bar", n.ServiceToken) assert.Equal(t, "", n.APIToken) } @@ -276,13 +272,13 @@ invalid-cert-data name: "empty certificate data", certData: []byte{}, expectError: true, - errorMsg: malformedCertificateError, + errorMsg: "x509: malformed certificate", }, { name: "nil certificate data", certData: nil, expectError: true, - errorMsg: malformedCertificateError, + errorMsg: "x509: malformed certificate", }, { name: "invalid PEM block type", @@ -294,13 +290,13 @@ invalid-cert-data name: "invalid PEM certificate data", certData: invalidPEMData, expectError: true, - errorMsg: malformedCertificateError, + errorMsg: "x509: malformed certificate", }, { name: "plain text data", certData: []byte("not a certificate"), expectError: true, - errorMsg: malformedCertificateError, + errorMsg: "x509: malformed certificate", }, } diff --git a/internal/printer/printer_test.go b/internal/printer/printer_test.go index 80604d04..57a66f8e 100644 --- a/internal/printer/printer_test.go +++ b/internal/printer/printer_test.go @@ -15,16 +15,6 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - testWorld = "World" - testNestedValue = "foobarbaz" - testHello = "Hello" - testFoo = "foo" - testBar = "bar" - testBaz = "baz" - testCapitalizedFoo = "Foo" -) - func setupPrinter() (*StdPrinter, *bytes.Buffer, *bytes.Buffer) { var stdOut, stdErr bytes.Buffer p := NewStdPrinter("linux", &stdOut, &stdErr) @@ -69,9 +59,9 @@ func TestPrintWithoutSymbolButWithColorOnWindows(t *testing.T) { func TestPrintStructAsJsonWithoutColor(t *testing.T) { testStruct := map[string]interface{}{ - testFoo: 1, - testBar: map[string]interface{}{ - testBaz: testNestedValue, + "foo": 1, + "bar": map[string]interface{}{ + "baz": "foobarbaz", "in": map[string]interface{}{ "out": 1, }, @@ -114,9 +104,9 @@ func TestPrintErrJson(t *testing.T) { func TestPrintStructAsYamlWithoutColor(t *testing.T) { testStruct := map[string]interface{}{ - testFoo: 1, - testBar: map[string]interface{}{ - testBaz: testNestedValue, + "foo": 1, + "bar": map[string]interface{}{ + "baz": "foobarbaz", }, } const expectedYaml = `bar: @@ -130,9 +120,9 @@ foo: 1 func TestPrintStructAsYamlWithColor(t *testing.T) { testStruct := map[string]interface{}{ - testFoo: 1, - testBar: map[string]interface{}{ - testBaz: testNestedValue, + "foo": 1, + "bar": map[string]interface{}{ + "baz": "foobarbaz", }, } //nolint:lll @@ -236,7 +226,7 @@ func TestPrintTableWrapEqualColumnTreatment(t *testing.T) { p.SetUseColor(false) p.MaxWidth = 25 p.Table(TableData{ - Header: []string{testHello, testCapitalizedFoo, testWorld}, + Header: []string{"Hello", "Foo", "World"}, Data: [][]interface{}{ {"1", "2", "3"}, {"hello darkness my old friend", "I've come to talk to you again", "Because a vision softly creeping"}, @@ -253,7 +243,7 @@ func TestPrintTableWrapUnequalColumnTreatment(t *testing.T) { p.SetUseColor(false) p.MaxWidth = 30 p.Table(TableData{ - Header: []string{testHello, testCapitalizedFoo, testWorld}, + Header: []string{"Hello", "Foo", "World"}, Data: [][]interface{}{ {"hello", "darkness my old friend", "Because a vision softly creeping"}, }, @@ -269,7 +259,7 @@ func TestTableDoesNotRenderBiggerThanMaxWidth(t *testing.T) { p.SetUseColor(false) data := []string{"hello", "fooba", "world"} - header1 := []string{testHello, testCapitalizedFoo, testWorld} + header1 := []string{"Hello", "Foo", "World"} header2 := []string{"x", "y", "z"} header3 := []string{"Wooot", "Woot", "It's the sound Of da Police"} for i := 0; i < 100; i++ { diff --git a/internal/util/string_util_test.go b/internal/util/string_util_test.go index 2a0e3445..bcd90942 100644 --- a/internal/util/string_util_test.go +++ b/internal/util/string_util_test.go @@ -8,13 +8,6 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - testFoo = "foo" - testBar = "bar" - testGreeting = "hello world" - testDecimal = "3.14" -) - func TestUcFirst(t *testing.T) { assert.Equal(t, UcFirst(""), "") assert.Equal(t, UcFirst("test"), "Test") @@ -22,7 +15,7 @@ func TestUcFirst(t *testing.T) { } func TestUniqueString(t *testing.T) { - assert.Equal(t, []string{testFoo, testBar}, UniqueStrings([]string{testFoo, testBar, testFoo, testBar})) + assert.Equal(t, []string{"foo", "bar"}, UniqueStrings([]string{"foo", "bar", "foo", "bar"})) } func TestToString(t *testing.T) { @@ -42,7 +35,7 @@ func TestToString(t *testing.T) { f32 := float32(3.14) f64 := float32(3.14) unixEpoch := time.UnixMilli(0).In(time.UTC) - str := testGreeting + str := "hello world" EST, err := time.LoadLocation("EST") if err != nil { t.Fatal(err) @@ -68,11 +61,11 @@ func TestToString(t *testing.T) { "pint64": {input: &i64, expected: "-42"}, "uint64": {input: uint64(42), expected: "42"}, "puint64": {input: &ui64, expected: "42"}, - "float32": {input: float32(3.14), expected: testDecimal}, - "pfloat32": {input: &f32, expected: testDecimal}, + "float32": {input: float32(3.14), expected: "3.14"}, + "pfloat32": {input: &f32, expected: "3.14"}, "float32 round": {input: float32(3), expected: "3"}, - "float64": {input: float64(3.14), expected: testDecimal}, - "pfloat64": {input: &f64, expected: testDecimal}, + "float64": {input: float64(3.14), expected: "3.14"}, + "pfloat64": {input: &f64, expected: "3.14"}, "float64 round": {input: float64(3), expected: "3"}, "float64 round large no scientific notation": { input: float64(107915343054010.0), expected: "107915343054010", @@ -88,8 +81,8 @@ func TestToString(t *testing.T) { "map nil": {input: mapnil, expected: "-"}, "str nil": {input: strnil, expected: "-"}, "slice nil": {input: slicenil, expected: "-"}, - "string": {input: testGreeting, expected: testGreeting}, - "pstring": {input: &str, expected: testGreeting}, + "string": {input: "hello world", expected: "hello world"}, + "pstring": {input: &str, expected: "hello world"}, } for name, tc := range tests { diff --git a/main_test.go b/main_test.go index f511a0d1..8df1cd85 100644 --- a/main_test.go +++ b/main_test.go @@ -14,15 +14,9 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - testError = "test-error" - testVersion = "version" - testJSON = "json" -) - func setupSTSCmd(t *testing.T) (*di.MockDeps, *cobra.Command) { errorCmd := cobra.Command{ - Use: testError, + Use: "test-error", Short: "some short help text for ErrorCmd", Long: "Some long help text for ErrorCmd.", RunE: func(cmd *cobra.Command, args []string) error { @@ -59,7 +53,7 @@ func TestHelpWhenRunningHelp(t *testing.T) { func TestVersionRun(t *testing.T) { cli, cmd := setupSTSCmd(t) - cmd.SetArgs([]string{testVersion}) + cmd.SetArgs([]string{"version"}) exitCode := execute(cli.Context, &cli.Deps, cmd) assert.Equal(t, 0, exitCode) assert.Equal(t, []printer.TableData{{ @@ -71,19 +65,19 @@ func TestVersionRun(t *testing.T) { func TestVersionJsonRun(t *testing.T) { cli, cmd := setupSTSCmd(t) - cmd.SetArgs([]string{testVersion, "-o", testJSON}) + cmd.SetArgs([]string{"version", "-o", "json"}) exitCode := execute(cli.Context, &cli.Deps, cmd) assert.Equal(t, 0, exitCode) assert.Equal(t, []map[string]interface{}{{ - "commit": "123124", "build-date": "1-1-2022", testVersion: "1.0.0", + "commit": "123124", "build-date": "1-1-2022", "version": "1.0.0", }}, *cli.MockPrinter.PrintJsonCalls) } func TestSetFlagErrorFuncSetsCLIArgParseError(t *testing.T) { cli, sts := setupSTSCmd(t) - sts.SetArgs([]string{testVersion, "--wrongflag"}) + sts.SetArgs([]string{"version", "--wrongflag"}) exitCode := execute(cli.Context, &cli.Deps, sts) assert.Equal(t, common.CommandFailedRequirementExitCode, exitCode) @@ -94,7 +88,7 @@ func TestSetFlagErrorFuncSetsCLIArgParseError(t *testing.T) { func TestErrHandling(t *testing.T) { cli, sts := setupSTSCmd(t) - sts.SetArgs([]string{testError}) + sts.SetArgs([]string{"test-error"}) exitCode := execute(cli.Context, &cli.Deps, sts) assert.Equal(t, common.CommandFailedRequirementExitCode, exitCode) @@ -106,7 +100,7 @@ func TestErrHandling(t *testing.T) { func TestErrToJson(t *testing.T) { cli, sts := setupSTSCmd(t) - sts.SetArgs([]string{testError, "-o", testJSON}) + sts.SetArgs([]string{"test-error", "-o", "json"}) exitCode := execute(cli.Context, &cli.Deps, sts) assert.Equal(t, common.CommandFailedRequirementExitCode, exitCode) @@ -129,7 +123,7 @@ func TestColorUsedByDefault(t *testing.T) { cli, cmd := setupSTSCmd(t) - cmd.SetArgs([]string{testVersion}) + cmd.SetArgs([]string{"version"}) execute(cli.Context, &cli.Deps, cmd) assert.True(t, cli.MockPrinter.UseColor) @@ -138,7 +132,7 @@ func TestColorUsedByDefault(t *testing.T) { func TestNoColorFlag(t *testing.T) { cli, cmd := setupSTSCmd(t) - cmd.SetArgs([]string{testVersion, "--no-color"}) + cmd.SetArgs([]string{"version", "--no-color"}) execute(cli.Context, &cli.Deps, cmd) assert.False(t, cli.MockPrinter.UseColor) assert.True(t, cli.NoColor) @@ -150,7 +144,7 @@ func TestNoColorWhenDumbTerminal(t *testing.T) { os.Setenv("TERM", "Dumb") cli, cmd := setupSTSCmd(t) - cmd.SetArgs([]string{testVersion}) + cmd.SetArgs([]string{"version"}) execute(cli.Context, &cli.Deps, cmd) assert.False(t, cli.MockPrinter.UseColor) assert.True(t, cli.NoColor) @@ -162,7 +156,7 @@ func TestNoColorWhenNoColorEnvExists(t *testing.T) { os.Setenv("NO_COLOR", "false") cli, cmd := setupSTSCmd(t) - cmd.SetArgs([]string{testVersion}) + cmd.SetArgs([]string{"version"}) execute(cli.Context, &cli.Deps, cmd) assert.False(t, cli.MockPrinter.UseColor) assert.True(t, cli.NoColor) @@ -170,7 +164,7 @@ func TestNoColorWhenNoColorEnvExists(t *testing.T) { func TestNoColorWhenJsonOutput(t *testing.T) { cli, cmd := setupSTSCmd(t) - cmd.SetArgs([]string{testVersion, "-o", testJSON}) + cmd.SetArgs([]string{"version", "-o", "json"}) execute(cli.Context, &cli.Deps, cmd) assert.False(t, cli.MockPrinter.UseColor) assert.True(t, cli.NoColor) @@ -178,7 +172,7 @@ func TestNoColorWhenJsonOutput(t *testing.T) { func TestVerbose(t *testing.T) { cli, cmd := setupSTSCmd(t) - cmd.SetArgs([]string{testVersion, "--verbose"}) + cmd.SetArgs([]string{"version", "--verbose"}) execute(cli.Context, &cli.Deps, cmd) assert.True(t, cli.IsVerBose) } diff --git a/pkg/pflags/duration_flag_test.go b/pkg/pflags/duration_flag_test.go index b5cbb95c..ca48018b 100644 --- a/pkg/pflags/duration_flag_test.go +++ b/pkg/pflags/duration_flag_test.go @@ -10,10 +10,6 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - invalidFlagValue = "garbage" -) - var durationTests = map[string]struct { input string outDuration time.Duration @@ -26,7 +22,7 @@ var durationTests = map[string]struct { "2 day": {input: "2d", outDuration: 48 * time.Hour, outErr: nil}, "1 week": {input: "1w", outDuration: 24 * time.Hour * 7, outErr: nil}, "empty string": {input: "", outDuration: 0, outErr: newInvalidDurationStringError()}, - invalidFlagValue: {input: "woot", outDuration: 0, outErr: newInvalidDurationStringError()}, + "garbage": {input: "woot", outDuration: 0, outErr: newInvalidDurationStringError()}, "missing unit single": {input: "1", outDuration: 0, outErr: newInvalidDurationStringError()}, "missing unit multi": {input: "122", outDuration: 0, outErr: newInvalidDurationStringError()}, "wrong unit": {input: "1j", outDuration: 0, outErr: newUnknownDurationUnitError("j")}, diff --git a/pkg/pflags/relative_time_flag_test.go b/pkg/pflags/relative_time_flag_test.go index 926838da..38b5fdd6 100644 --- a/pkg/pflags/relative_time_flag_test.go +++ b/pkg/pflags/relative_time_flag_test.go @@ -22,7 +22,7 @@ var timeTests = map[string]struct { "iso date": {input: "2022-05-09T15:04:05Z", outTime: int64(1652108645000), outErr: nil}, "relative time": {input: "-2d", outTime: int64(1652108645000 - 2*86400000), outErr: nil}, "unix time": {input: "1652108645000", outTime: int64(1652108645000), outErr: nil}, - invalidFlagValue: {input: invalidFlagValue, outTime: TimeZero, outErr: newTimeParseError(invalidFlagValue)}, + "garbage": {input: "garbage", outTime: TimeZero, outErr: newTimeParseError("garbage")}, "empty ": {input: "", outTime: TimeZero, outErr: newTimeParseError("")}, "invalid relative time": {input: "-2j", outTime: TimeZero, outErr: newInvalidRelativeTimeError("-2j", newUnknownDurationUnitError("j"))}, } diff --git a/pkg/scaffold/github_source_test.go b/pkg/scaffold/github_source_test.go index ca2a2e45..54ad0f5a 100644 --- a/pkg/scaffold/github_source_test.go +++ b/pkg/scaffold/github_source_test.go @@ -13,19 +13,6 @@ import ( "testing" ) -const ( - testArchiveFilePath = "test-repo-main/templates/generic/file.txt" - testOwner = "testowner" - testRepo = "testrepo" - testTemplatesPath = "templates" - testGenericTemplate = "generic" - testRef = "main" - emptyTemplateNameCase = "empty template name" - templateNameRequiredError = "template name is required" - testRepositoryDir = "test-repo" - testFileContent = "content" -) - func TestGitHubSource_NewGitHubSource(t *testing.T) { tests := []struct { name string @@ -38,21 +25,21 @@ func TestGitHubSource_NewGitHubSource(t *testing.T) { }{ { name: "all parameters provided", - owner: testOwner, - repo: testRepo, + owner: "testowner", + repo: "testrepo", ref: "v1.0.0", - path: testTemplatesPath, - templateName: testGenericTemplate, + path: "templates", + templateName: "generic", expectedRef: "v1.0.0", }, { name: "empty ref defaults to main", - owner: testOwner, - repo: testRepo, + owner: "testowner", + repo: "testrepo", ref: "", - path: testTemplatesPath, - templateName: testGenericTemplate, - expectedRef: testRef, + path: "templates", + templateName: "generic", + expectedRef: "main", }, } @@ -87,12 +74,12 @@ func TestGitHubSource_String(t *testing.T) { }{ { name: "with path", - source: NewGitHubSource("owner", "repo", testRef, testTemplatesPath, testGenericTemplate), + source: NewGitHubSource("owner", "repo", "main", "templates", "generic"), expectedStr: "github:owner/repo@main:templates", }, { name: "without path", - source: NewGitHubSource("owner", "repo", "v1.0", "", testGenericTemplate), + source: NewGitHubSource("owner", "repo", "v1.0", "", "generic"), expectedStr: "github:owner/repo@v1.0", }, } @@ -118,40 +105,40 @@ func TestGitHubSource_Validate(t *testing.T) { }{ { name: "valid source", - owner: testOwner, - repo: testRepo, - templateName: testGenericTemplate, + owner: "testowner", + repo: "testrepo", + templateName: "generic", wantErr: false, }, { name: "empty owner", owner: "", - repo: testRepo, - templateName: testGenericTemplate, + repo: "testrepo", + templateName: "generic", wantErr: true, expectedErr: "GitHub repository owner is required", }, { name: "empty repo", - owner: testOwner, + owner: "testowner", repo: "", - templateName: testGenericTemplate, + templateName: "generic", wantErr: true, expectedErr: "GitHub repository name is required", }, { - name: emptyTemplateNameCase, - owner: testOwner, - repo: testRepo, + name: "empty template name", + owner: "testowner", + repo: "testrepo", templateName: "", wantErr: true, - expectedErr: templateNameRequiredError, + expectedErr: "template name is required", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - source := NewGitHubSource(tt.owner, tt.repo, testRef, testTemplatesPath, tt.templateName) + source := NewGitHubSource(tt.owner, tt.repo, "main", "templates", tt.templateName) err := source.Validate() if tt.wantErr { @@ -171,7 +158,7 @@ func TestGitHubSource_Validate(t *testing.T) { func TestGitHubSource_Cleanup(t *testing.T) { // Test cleanup when no temp directory is set - source := NewGitHubSource("owner", "repo", testRef, "", testGenericTemplate) + source := NewGitHubSource("owner", "repo", "main", "", "generic") err := source.Cleanup() if err != nil { t.Errorf("Expected no error when tempDir is empty, got: %v", err) @@ -221,7 +208,7 @@ func TestGitHubSource_extractZip(t *testing.T) { } extractDir := filepath.Join(tempDir, "extracted") - source := NewGitHubSource("owner", "repo", testRef, "", testGenericTemplate) + source := NewGitHubSource("owner", "repo", "main", "", "generic") err = source.extractZip(zipFile, extractDir) if err != nil { @@ -256,68 +243,68 @@ func TestGitHubSource_findTemplateDirectory(t *testing.T) { }{ { name: "find template with path", - repo: testRepositoryDir, - ref: testRef, - path: testTemplatesPath, - templateName: testGenericTemplate, + repo: "test-repo", + ref: "main", + path: "templates", + templateName: "generic", setupFiles: map[string]string{ - testArchiveFilePath: testFileContent, + "test-repo-main/templates/generic/file.txt": "content", }, wantErr: false, }, { name: "find template without path", - repo: testRepositoryDir, - ref: testRef, + repo: "test-repo", + ref: "main", path: "", - templateName: testGenericTemplate, + templateName: "generic", setupFiles: map[string]string{ - "test-repo-main/generic/file.txt": testFileContent, + "test-repo-main/generic/file.txt": "content", }, wantErr: false, }, { name: "repo directory not found", - repo: testRepositoryDir, - ref: testRef, + repo: "test-repo", + ref: "main", path: "", - templateName: testGenericTemplate, + templateName: "generic", setupFiles: map[string]string{ - "wrong-repo-main/generic/file.txt": testFileContent, + "wrong-repo-main/generic/file.txt": "content", }, wantErr: true, expectedErr: "could not find repository directory in extracted archive", }, { name: "template base directory not found", - repo: testRepositoryDir, - ref: testRef, + repo: "test-repo", + ref: "main", path: "nonexistent", - templateName: testGenericTemplate, + templateName: "generic", setupFiles: map[string]string{ - testArchiveFilePath: testFileContent, + "test-repo-main/templates/generic/file.txt": "content", }, wantErr: true, expectedErr: "template base directory not found at path 'nonexistent'", }, { name: "template not found", - repo: testRepositoryDir, - ref: testRef, - path: testTemplatesPath, + repo: "test-repo", + ref: "main", + path: "templates", templateName: "nonexistent", setupFiles: map[string]string{ - testArchiveFilePath: testFileContent, + "test-repo-main/templates/generic/file.txt": "content", }, wantErr: true, expectedErr: "template 'nonexistent' not found in directory", }, { name: "template is file not directory", - repo: testRepositoryDir, - ref: testRef, - path: testTemplatesPath, - templateName: testGenericTemplate, + repo: "test-repo", + ref: "main", + path: "templates", + templateName: "generic", setupFiles: map[string]string{ "test-repo-main/templates/generic": "file content", }, @@ -389,10 +376,10 @@ func TestGitHubSource_findTemplateDirectory(t *testing.T) { func TestGitHubSource_Fetch_Integration(t *testing.T) { // Create a mock HTTP server that serves a ZIP file zipData := createTestZipFile(t, map[string]string{ - "test-repo-main/": "", - "test-repo-main/templates/": "", - "test-repo-main/templates/generic/": "", - testArchiveFilePath: "template content", + "test-repo-main/": "", + "test-repo-main/templates/": "", + "test-repo-main/templates/generic/": "", + "test-repo-main/templates/generic/file.txt": "template content", }) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/pkg/scaffold/scaffolder_test.go b/pkg/scaffold/scaffolder_test.go index 9927a1c6..76b693ac 100644 --- a/pkg/scaffold/scaffolder_test.go +++ b/pkg/scaffold/scaffolder_test.go @@ -10,19 +10,6 @@ import ( "github.com/stretchr/testify/assert" ) -const ( - testNameTemplate = "name=<<.Name>>" - testSecondFileName = "file2.txt" - testMockSource = "mock-source" - testName = "test-name" - testTemplateName = "test-template" - testConfigFile = "test.conf" - testWebappTemplate = "webapp" - testConfigPath = "config.conf" - testPackName = "test-pack" - testFileName = "file1.txt" -) - // MockTemplateSource for testing type MockTemplateSource struct { fetchResult string @@ -67,8 +54,8 @@ func (m *MockPrinter) PrintWarn(message string) { } func TestNewScaffolder(t *testing.T) { - mockSource := &MockTemplateSource{stringResult: testMockSource} - context := TemplateContext{Name: testName, DisplayName: testName, TemplateName: testTemplateName} + mockSource := &MockTemplateSource{stringResult: "mock-source"} + context := TemplateContext{Name: "test-name", DisplayName: "test-name", TemplateName: "test-template"} mockPrinter := &MockPrinter{} scaffolder := NewScaffolder(mockSource, "/test/dest", context, true, mockPrinter, false) @@ -79,7 +66,7 @@ func TestNewScaffolder(t *testing.T) { if scaffolder.destination != "/test/dest" { t.Errorf("Expected destination to be '/test/dest', got '%s'", scaffolder.destination) } - if scaffolder.context.Name != testName { + if scaffolder.context.Name != "test-name" { t.Errorf("Expected context.Name to be 'test-name', got '%s'", scaffolder.context.Name) } if scaffolder.force != true { @@ -100,30 +87,30 @@ func TestScaffolder_validateArgs(t *testing.T) { }{ { name: "valid args", - context: TemplateContext{Name: testName, DisplayName: testName, TemplateName: testTemplateName}, + context: TemplateContext{Name: "test-name", DisplayName: "test-name", TemplateName: "test-template"}, sourceErr: nil, wantErr: false, }, { name: "source validation error", - context: TemplateContext{Name: testName, TemplateName: testTemplateName}, + context: TemplateContext{Name: "test-name", TemplateName: "test-template"}, sourceErr: os.ErrInvalid, wantErr: true, expectedErr: "invalid argument", }, { name: "empty name", - context: TemplateContext{Name: "", TemplateName: testTemplateName}, + context: TemplateContext{Name: "", TemplateName: "test-template"}, sourceErr: nil, wantErr: true, expectedErr: "stackpack name is required", }, { - name: emptyTemplateNameCase, - context: TemplateContext{Name: testName, TemplateName: ""}, + name: "empty template name", + context: TemplateContext{Name: "test-name", TemplateName: ""}, sourceErr: nil, wantErr: true, - expectedErr: templateNameRequiredError, + expectedErr: "template name is required", }, } @@ -131,7 +118,7 @@ func TestScaffolder_validateArgs(t *testing.T) { t.Run(tt.name, func(t *testing.T) { mockSource := &MockTemplateSource{ validateError: tt.sourceErr, - stringResult: testMockSource, + stringResult: "mock-source", } mockPrinter := &MockPrinter{} @@ -188,9 +175,9 @@ func TestScaffolder_checkDestinationDirectory(t *testing.T) { tt.destination = destination } - mockSource := &MockTemplateSource{stringResult: testMockSource} + mockSource := &MockTemplateSource{stringResult: "mock-source"} mockPrinter := &MockPrinter{} - context := TemplateContext{Name: testName, TemplateName: testTemplateName} + context := TemplateContext{Name: "test-name", TemplateName: "test-template"} scaffolder := NewScaffolder(mockSource, tt.destination, context, false, mockPrinter, false) err := scaffolder.checkDestinationDirectory() @@ -230,7 +217,7 @@ func TestScaffolder_processTemplate(t *testing.T) { { name: "no template variables", content: "plain text content", - context: TemplateContext{Name: testName, TemplateName: testTemplateName}, + context: TemplateContext{Name: "test-name", TemplateName: "test-template"}, filename: "test.txt", expectedResult: "plain text content", wantErr: false, @@ -238,16 +225,16 @@ func TestScaffolder_processTemplate(t *testing.T) { { name: "template with Name variable", content: "name: <<.Name>>", - context: TemplateContext{Name: "my-stackpack", TemplateName: testGenericTemplate}, - filename: testConfigFile, + context: TemplateContext{Name: "my-stackpack", TemplateName: "generic"}, + filename: "test.conf", expectedResult: "name: my-stackpack", wantErr: false, }, { name: "template with TemplateName variable", content: "template: <<.TemplateName>>", - context: TemplateContext{Name: "my-stackpack", TemplateName: testWebappTemplate}, - filename: testConfigFile, + context: TemplateContext{Name: "my-stackpack", TemplateName: "webapp"}, + filename: "test.conf", expectedResult: "template: webapp", wantErr: false, }, @@ -262,16 +249,16 @@ func TestScaffolder_processTemplate(t *testing.T) { { name: "invalid template syntax", content: "name: <<.InvalidField>>", - context: TemplateContext{Name: testName, TemplateName: testTemplateName}, - filename: testConfigFile, + context: TemplateContext{Name: "test-name", TemplateName: "test-template"}, + filename: "test.conf", wantErr: true, expectedErr: "template execution error", }, { name: "malformed template delimiters", content: "name: <<.Name", - context: TemplateContext{Name: testName, TemplateName: testTemplateName}, - filename: testConfigFile, + context: TemplateContext{Name: "test-name", TemplateName: "test-template"}, + filename: "test.conf", wantErr: false, // Go templates are more permissive, this actually works as literal text expectedResult: "name: <<.Name", }, @@ -279,7 +266,7 @@ func TestScaffolder_processTemplate(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - mockSource := &MockTemplateSource{stringResult: testMockSource} + mockSource := &MockTemplateSource{stringResult: "mock-source"} mockPrinter := &MockPrinter{} scaffolder := NewScaffolder(mockSource, "/test/dest", tt.context, false, mockPrinter, false) @@ -318,11 +305,11 @@ func TestScaffolder_renderTemplates(t *testing.T) { { name: "render text files with templates", setupFiles: map[string]string{ - testConfigPath: testNameTemplate, - "readme.md": "# <<.Name>> StackPack\nTemplate: <<.TemplateName>>", - "data.json": `{"name": "<<.Name>>", "template": "<<.TemplateName>>"}`, + "config.conf": "name=<<.Name>>", + "readme.md": "# <<.Name>> StackPack\nTemplate: <<.TemplateName>>", + "data.json": `{"name": "<<.Name>>", "template": "<<.TemplateName>>"}`, }, - context: TemplateContext{Name: "my-pack", TemplateName: testWebappTemplate}, + context: TemplateContext{Name: "my-pack", TemplateName: "webapp"}, wantErr: false, }, { @@ -331,17 +318,17 @@ func TestScaffolder_renderTemplates(t *testing.T) { "plain.txt": "no template variables here", "script.sh": "#!/bin/bash\necho 'hello world'", }, - context: TemplateContext{Name: "my-pack", TemplateName: testWebappTemplate}, + context: TemplateContext{Name: "my-pack", TemplateName: "webapp"}, wantErr: false, }, { name: "mixed template and non-template files", setupFiles: map[string]string{ - testConfigPath: testNameTemplate, + "config.conf": "name=<<.Name>>", "plain.txt": "static content", "subdir/nested.conf": "template=<<.TemplateName>>", }, - context: TemplateContext{Name: testPackName, TemplateName: testGenericTemplate}, + context: TemplateContext{Name: "test-pack", TemplateName: "generic"}, wantErr: false, }, } @@ -366,7 +353,7 @@ func TestScaffolder_renderTemplates(t *testing.T) { } } - mockSource := &MockTemplateSource{stringResult: testMockSource} + mockSource := &MockTemplateSource{stringResult: "mock-source"} mockPrinter := &MockPrinter{} scaffolder := NewScaffolder(mockSource, "/test/dest", tt.context, false, mockPrinter, false) @@ -437,22 +424,22 @@ func TestScaffolder_checkForConflicts(t *testing.T) { }{ { name: "no conflicts", - sourceFiles: []string{testFileName, testSecondFileName}, + sourceFiles: []string{"file1.txt", "file2.txt"}, destFiles: []string{"other.txt"}, expectedCount: 0, wantErr: false, }, { name: "some conflicts", - sourceFiles: []string{testFileName, testSecondFileName, "file3.txt"}, - destFiles: []string{testFileName, "file3.txt"}, + sourceFiles: []string{"file1.txt", "file2.txt", "file3.txt"}, + destFiles: []string{"file1.txt", "file3.txt"}, expectedCount: 2, wantErr: false, }, { name: "all conflicts", - sourceFiles: []string{testFileName, testSecondFileName}, - destFiles: []string{testFileName, testSecondFileName}, + sourceFiles: []string{"file1.txt", "file2.txt"}, + destFiles: []string{"file1.txt", "file2.txt"}, expectedCount: 2, wantErr: false, }, @@ -490,9 +477,9 @@ func TestScaffolder_checkForConflicts(t *testing.T) { } } - mockSource := &MockTemplateSource{stringResult: testMockSource} + mockSource := &MockTemplateSource{stringResult: "mock-source"} mockPrinter := &MockPrinter{} - context := TemplateContext{Name: testName, TemplateName: testTemplateName} + context := TemplateContext{Name: "test-name", TemplateName: "test-template"} scaffolder := NewScaffolder(mockSource, destDir, context, false, mockPrinter, false) conflicts, err := scaffolder.checkForConflicts(sourceDir, destDir) @@ -517,9 +504,9 @@ func TestScaffolder_checkForConflicts(t *testing.T) { func TestScaffolder_JSONOutput(t *testing.T) { // Create test files map testFiles := map[string]string{ - testConfigPath: testNameTemplate, - "readme.md": "# <<.Name>> StackPack", - "static.txt": "no template variables here", + "config.conf": "name=<<.Name>>", + "readme.md": "# <<.Name>> StackPack", + "static.txt": "no template variables here", } tests := []struct { @@ -565,10 +552,10 @@ func TestScaffolder_JSONOutput(t *testing.T) { mockSource := &MockTemplateSource{ fetchResult: sourceDir, - stringResult: testMockSource, + stringResult: "mock-source", } mockPrinter := &MockPrinter{} - templateCtx := TemplateContext{Name: testPackName, TemplateName: testTemplateName} + templateCtx := TemplateContext{Name: "test-pack", TemplateName: "test-template"} scaffolder := NewScaffolder(mockSource, destDir, templateCtx, false, mockPrinter, tt.jsonOutput) result, cleanup, err := scaffolder.Scaffold(context.TODO()) @@ -582,13 +569,13 @@ func TestScaffolder_JSONOutput(t *testing.T) { if result.Success != true { t.Errorf("Expected success=true, got %v", result.Success) } - if result.Name != testPackName { + if result.Name != "test-pack" { t.Errorf("Expected name='test-pack', got %s", result.Name) } - if result.Template != testTemplateName { + if result.Template != "test-template" { t.Errorf("Expected template='test-template', got %s", result.Template) } - if result.Source != testMockSource { + if result.Source != "mock-source" { t.Errorf("Expected source='mock-source', got %s", result.Source) } if result.FilesCount != len(testFiles) { diff --git a/pkg/scaffold/template_source_test.go b/pkg/scaffold/template_source_test.go index 80248e5f..d31d59cb 100644 --- a/pkg/scaffold/template_source_test.go +++ b/pkg/scaffold/template_source_test.go @@ -41,32 +41,32 @@ func TestLocalDirSource_Validate(t *testing.T) { { name: "valid directory with template", path: "", - templateName: testTemplateName, + templateName: "test-template", setupFunc: func(tempDir string) error { - return os.MkdirAll(filepath.Join(tempDir, testTemplateName), 0755) + return os.MkdirAll(filepath.Join(tempDir, "test-template"), 0755) }, wantErr: false, }, { name: "empty path", path: "", - templateName: testTemplateName, + templateName: "test-template", setupFunc: func(tempDir string) error { return nil }, wantErr: true, expectedErr: "template path is required", }, { - name: emptyTemplateNameCase, + name: "empty template name", path: "/test/path", templateName: "", setupFunc: func(tempDir string) error { return nil }, wantErr: true, - expectedErr: templateNameRequiredError, + expectedErr: "template name is required", }, { name: "non-existent directory", path: "/non/existent/path", - templateName: testTemplateName, + templateName: "test-template", setupFunc: func(tempDir string) error { return nil }, wantErr: true, expectedErr: "template directory does not exist: /non/existent/path", @@ -74,7 +74,7 @@ func TestLocalDirSource_Validate(t *testing.T) { { name: "path is a file not directory", path: "", - templateName: testTemplateName, + templateName: "test-template", setupFunc: func(tempDir string) error { return os.WriteFile(tempDir+"/file.txt", []byte("test"), 0644) }, @@ -133,9 +133,9 @@ func TestLocalDirSource_Fetch(t *testing.T) { }{ { name: "successful fetch", - templateName: testTemplateName, + templateName: "test-template", setupFunc: func(tempDir string) error { - return os.MkdirAll(filepath.Join(tempDir, testTemplateName), 0755) + return os.MkdirAll(filepath.Join(tempDir, "test-template"), 0755) }, wantErr: false, },