From 4add4ccd0e754d489ab23c16dd6d3847b886ce97 Mon Sep 17 00:00:00 2001 From: Michael Brooks Date: Wed, 2 Apr 2025 12:44:21 -0700 Subject: [PATCH 01/13] refactor: Add slackcontext package to DRY context management --- .vscode/settings.json | 1 + cmd/env/list.go | 5 +- cmd/root.go | 30 +- cmd/root_test.go | 6 +- internal/api/activity_test.go | 38 ++- internal/api/app_test.go | 50 ++-- internal/api/auth_test.go | 26 +- internal/api/client.go | 19 +- internal/api/datastore_test.go | 17 +- internal/api/externalauth_test.go | 22 +- internal/api/functiondistribution_test.go | 52 ++-- internal/api/icon.go | 7 +- internal/api/icon_test.go | 14 +- internal/api/s3_upload.go | 7 +- internal/api/s3_upload_test.go | 5 +- internal/api/session_test.go | 38 ++- internal/api/steps_test.go | 14 +- internal/api/teams_test.go | 6 +- internal/api/triggerpermissions_test.go | 50 ++-- internal/api/variables_test.go | 38 ++- internal/api/workflows_test.go | 14 +- internal/auth/auth_test.go | 17 +- internal/auth/revoke_test.go | 4 +- internal/config/context.go | 51 ---- internal/contextutil/contextutil.go | 53 ---- internal/iostreams/logfile.go | 15 +- internal/slackcontext/slackcontext.go | 176 +++++++++++ internal/slackcontext/slackcontext_mock.go | 34 +++ internal/slackcontext/slackcontext_test.go | 331 +++++++++++++++++++++ internal/slackerror/errors.go | 28 +- internal/tracking/tracking.go | 7 +- internal/tracking/tracking_test.go | 5 +- main.go | 29 +- 33 files changed, 894 insertions(+), 315 deletions(-) delete mode 100644 internal/contextutil/contextutil.go create mode 100644 internal/slackcontext/slackcontext.go create mode 100644 internal/slackcontext/slackcontext_mock.go create mode 100644 internal/slackcontext/slackcontext_test.go diff --git a/.vscode/settings.json b/.vscode/settings.json index 118c7363..6810f17c 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -16,6 +16,7 @@ "iostreams", "opentracing", "safeexec", + "slackcontext", "slackdeps", "slackerror", "slackhq", diff --git a/cmd/env/list.go b/cmd/env/list.go index 09b1deca..2bb9a71a 100644 --- a/cmd/env/list.go +++ b/cmd/env/list.go @@ -51,7 +51,7 @@ func NewEnvListCommand(clients *shared.ClientFactory) *cobra.Command { return preRunEnvListCommandFunc(ctx, clients) }, RunE: func(cmd *cobra.Command, args []string) error { - return runEnvListCommandFunc(clients) + return runEnvListCommandFunc(clients, cmd) }, } @@ -74,8 +74,9 @@ func preRunEnvListCommandFunc(ctx context.Context, clients *shared.ClientFactory // runEnvListCommandFunc outputs environment variables for a selected app func runEnvListCommandFunc( clients *shared.ClientFactory, + cmd *cobra.Command, ) error { - ctx := context.Background() + ctx := cmd.Context() selection, err := teamAppSelectPromptFunc( ctx, diff --git a/cmd/root.go b/cmd/root.go index 21e9cf2c..7e9f5d6f 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -22,7 +22,6 @@ import ( "strings" "syscall" - "github.com/opentracing/opentracing-go" "github.com/slackapi/slack-cli/cmd/app" "github.com/slackapi/slack-cli/cmd/auth" "github.com/slackapi/slack-cli/cmd/collaborators" @@ -47,6 +46,7 @@ import ( "github.com/slackapi/slack-cli/internal/iostreams" "github.com/slackapi/slack-cli/internal/pkg/version" "github.com/slackapi/slack-cli/internal/shared" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/slackapi/slack-cli/internal/style" "github.com/slackapi/slack-cli/internal/update" @@ -222,6 +222,7 @@ func Init() (*cobra.Command, *shared.ClientFactory) { // TODO: consider using arguments for this function for certain dependencies, like working directory and other OS-specific strings, that OnInitialize above can provide during actual execution, but that we can override with test values for easier testing. func InitConfig(clients *shared.ClientFactory, rootCmd *cobra.Command) error { ctx := rootCmd.Context() + // Get the current working directory (usually, but not always the project) workingDirPath, err := clients.Os.Getwd() if err != nil { @@ -261,43 +262,35 @@ func InitConfig(clients *shared.ClientFactory, rootCmd *cobra.Command) error { clients.Config.ApiHostResolved = clients.AuthInterface().ResolveApiHost(ctx, clients.Config.ApiHostFlag, nil) clients.Config.LogstashHostResolved = clients.AuthInterface().ResolveLogstashHost(ctx, clients.Config.ApiHostResolved, clients.CliVersion) - // TODO: should we store system ID in config or in context? // Init System ID if systemID, err := clients.Config.SystemConfig.InitSystemID(ctx); err != nil { clients.IO.PrintDebug(ctx, "Error initializing user-level config system_id: %s", err.Error()) } else { // Used by Logstash + // TODO(slackcontext) Consolidate storing SystemID to slackcontext clients.Config.SystemID = systemID - // Used by OpenTracing - if span := opentracing.SpanFromContext(ctx); span != nil { - span.SetTag("system_id", clients.Config.SystemID) - ctx = opentracing.ContextWithSpan(ctx, span) - } - + ctx = slackcontext.SetSystemID(ctx, systemID) + rootCmd.SetContext(ctx) // Debug logging clients.IO.PrintDebug(ctx, "system_id: %s", clients.Config.SystemID) } - // TODO: should we store project ID in config or in context? // Init Project ID, if current directory is a project if projectID, _ := clients.Config.ProjectConfig.InitProjectID(ctx, false); projectID != "" { // Used by Logstash + // TODO(slackcontext) Consolidate storing ProjectID to slackcontext clients.Config.ProjectID = projectID - // Used by OpenTracing - if span := opentracing.SpanFromContext(ctx); span != nil { - span.SetTag("project_id", clients.Config.ProjectID) - ctx = opentracing.ContextWithSpan(ctx, span) - } - + ctx = slackcontext.SetProjectID(ctx, projectID) + rootCmd.SetContext(ctx) // Debug logging clients.IO.PrintDebug(ctx, "project_id: %s", clients.Config.ProjectID) } // Init configurations clients.Config.LoadExperiments(ctx, clients.IO.PrintDebug) - // TODO: consolidate where we store CLI version; here are two locations, plus some code uses `contextutil.ContextFromVersion`, plus pkg/version/version + // TODO(slackcontext) Consolidate storing CLI version to slackcontext clients.Config.Version = clients.CliVersion // The domain auths (token->domain) shouldn't change for the execution of the CLI so preload them into config! @@ -334,10 +327,8 @@ func InitConfig(clients *shared.ClientFactory, rootCmd *cobra.Command) error { // listens for process interrupts and sends to IOStreams' GetInterruptChannel() for use in // in communicating process interrupts elsewhere in the code. func Execute(ctx context.Context, rootCmd *cobra.Command, clients *shared.ClientFactory) { - // TODO: ensure context is only used with setters and not with getters. After investigating, report: - // - internal/contextutil/contextutil.go has a `VersionFromContext` getter method which is used in various API methods when setting the user agent on HTTP requests, and when sending data up to logstash - // - internal/config/context.go has a variety of set and get methods related to app, token, team/enterprise/session/user/trace IDs, domains ctx, cancel := context.WithCancel(ctx) + completedChan := make(chan bool, 1) // completed is used for signalling an end to command exitChan := make(chan bool, 1) // exit blocks the command from exiting until completed interruptChan := make(chan os.Signal, 1) // interrupt catches signals to avoid abrupt exits @@ -366,6 +357,7 @@ func Execute(ctx context.Context, rootCmd *cobra.Command, clients *shared.Client }() case <-ctx.Done(): // No interrupt signal sent, command executed to completion + // FIXME - `.Done()` channel is triggered by `cancel()` and not a successfully completion case <-completedChan: // No canceled context, but command has completed execution exitChan <- true diff --git a/cmd/root_test.go b/cmd/root_test.go index 6c17e8a1..065cb779 100644 --- a/cmd/root_test.go +++ b/cmd/root_test.go @@ -21,12 +21,15 @@ import ( "testing" "github.com/slackapi/slack-cli/internal/shared" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/test/testutil" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestRootCommand(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) + tmp, _ := os.MkdirTemp("", "") _ = os.Chdir(tmp) defer os.RemoveAll(tmp) @@ -38,7 +41,7 @@ func TestRootCommand(t *testing.T) { clientsMock := shared.NewClientsMock() testutil.MockCmdIO(clientsMock.IO, cmd) - err := cmd.Execute() + err := cmd.ExecuteContext(ctx) if err != nil { assert.Fail(t, "cmd.Execute had unexpected error") } @@ -131,6 +134,7 @@ func Test_Aliases(t *testing.T) { tmp, _ := os.MkdirTemp("", "") _ = os.Chdir(tmp) defer os.RemoveAll(tmp) + Init() tests := map[string]struct { diff --git a/internal/api/activity_test.go b/internal/api/activity_test.go index b93c9d75..92e8be71 100644 --- a/internal/api/activity_test.go +++ b/internal/api/activity_test.go @@ -15,10 +15,10 @@ package api import ( - "context" "testing" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/stretchr/testify/require" ) @@ -28,11 +28,12 @@ var fakeResult = `{"ok":true, }` func Test_ApiClient_ActivityErrorsIfAppIdIsEmpty(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: appActivityMethod, }) defer teardown() - _, err := c.Activity(context.Background(), "token", types.ActivityRequest{ + _, err := c.Activity(ctx, "token", types.ActivityRequest{ AppId: "", }) require.Error(t, err) @@ -40,13 +41,14 @@ func Test_ApiClient_ActivityErrorsIfAppIdIsEmpty(t *testing.T) { } func Test_ApiClient_ActivityBasicSuccessfulGET(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: appActivityMethod, ExpectedQuerystring: "app_id=A123", Response: fakeResult, }) defer teardown() - result, err := c.Activity(context.Background(), "token", types.ActivityRequest{ + result, err := c.Activity(ctx, "token", types.ActivityRequest{ AppId: "A123", }) require.NoError(t, err) @@ -54,13 +56,14 @@ func Test_ApiClient_ActivityBasicSuccessfulGET(t *testing.T) { } func Test_ApiClient_ActivityEventType(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: appActivityMethod, ExpectedQuerystring: "app_id=A123&limit=0&log_event_type=silly", Response: fakeResult, }) defer teardown() - result, err := c.Activity(context.Background(), "token", types.ActivityRequest{ + result, err := c.Activity(ctx, "token", types.ActivityRequest{ AppId: "A123", EventType: "silly", }) @@ -69,13 +72,14 @@ func Test_ApiClient_ActivityEventType(t *testing.T) { } func Test_ApiClient_ActivityLogLevel(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: appActivityMethod, ExpectedQuerystring: "app_id=A123&limit=0&min_log_level=silly", Response: fakeResult, }) defer teardown() - result, err := c.Activity(context.Background(), "token", types.ActivityRequest{ + result, err := c.Activity(ctx, "token", types.ActivityRequest{ AppId: "A123", MinimumLogLevel: "silly", }) @@ -84,13 +88,14 @@ func Test_ApiClient_ActivityLogLevel(t *testing.T) { } func Test_ApiClient_ActivityMinDateCreated(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: appActivityMethod, ExpectedQuerystring: "app_id=A123&limit=0&min_date_created=1337", Response: fakeResult, }) defer teardown() - result, err := c.Activity(context.Background(), "token", types.ActivityRequest{ + result, err := c.Activity(ctx, "token", types.ActivityRequest{ AppId: "A123", MinimumDateCreated: 1337, }) @@ -99,13 +104,14 @@ func Test_ApiClient_ActivityMinDateCreated(t *testing.T) { } func Test_ApiClient_ActivityComponentType(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: appActivityMethod, ExpectedQuerystring: "app_id=A123&limit=0&component_type=defirbulator", Response: fakeResult, }) defer teardown() - result, err := c.Activity(context.Background(), "token", types.ActivityRequest{ + result, err := c.Activity(ctx, "token", types.ActivityRequest{ AppId: "A123", ComponentType: "defirbulator", }) @@ -114,13 +120,14 @@ func Test_ApiClient_ActivityComponentType(t *testing.T) { } func Test_ApiClient_ActivityComponentId(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: appActivityMethod, ExpectedQuerystring: "app_id=A123&limit=0&component_id=raspberry", Response: fakeResult, }) defer teardown() - result, err := c.Activity(context.Background(), "token", types.ActivityRequest{ + result, err := c.Activity(ctx, "token", types.ActivityRequest{ AppId: "A123", ComponentId: "raspberry", }) @@ -129,13 +136,14 @@ func Test_ApiClient_ActivityComponentId(t *testing.T) { } func Test_ApiClient_ActivitySource(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: appActivityMethod, ExpectedQuerystring: "app_id=A123&limit=0&source=beer", Response: fakeResult, }) defer teardown() - result, err := c.Activity(context.Background(), "token", types.ActivityRequest{ + result, err := c.Activity(ctx, "token", types.ActivityRequest{ AppId: "A123", Source: "beer", }) @@ -144,13 +152,14 @@ func Test_ApiClient_ActivitySource(t *testing.T) { } func Test_ApiClient_ActivityTraceId(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: appActivityMethod, ExpectedQuerystring: "app_id=A123&limit=0&trace_id=stealth", Response: fakeResult, }) defer teardown() - result, err := c.Activity(context.Background(), "token", types.ActivityRequest{ + result, err := c.Activity(ctx, "token", types.ActivityRequest{ AppId: "A123", TraceId: "stealth", }) @@ -159,13 +168,14 @@ func Test_ApiClient_ActivityTraceId(t *testing.T) { } func Test_ApiClient_ActivityResponseNotOK(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: appActivityMethod, ExpectedQuerystring: "app_id=A123", Response: `{"ok":false, "error": "internal_error"}`, }) defer teardown() - _, err := c.Activity(context.Background(), "token", types.ActivityRequest{ + _, err := c.Activity(ctx, "token", types.ActivityRequest{ AppId: "A123", }) require.Error(t, err) @@ -173,13 +183,14 @@ func Test_ApiClient_ActivityResponseNotOK(t *testing.T) { } func Test_ApiClient_ActivityInvalidResponse(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: appActivityMethod, ExpectedQuerystring: "app_id=A123", Response: `badjson`, }) defer teardown() - _, err := c.Activity(context.Background(), "token", types.ActivityRequest{ + _, err := c.Activity(ctx, "token", types.ActivityRequest{ AppId: "A123", }) require.Error(t, err) @@ -187,13 +198,14 @@ func Test_ApiClient_ActivityInvalidResponse(t *testing.T) { } func Test_ApiClient_ActivityInvalidJSON(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: appActivityMethod, ExpectedQuerystring: "app_id=A123", Response: `badtime`, }) defer teardown() - _, err := c.Activity(context.Background(), "token", types.ActivityRequest{ + _, err := c.Activity(ctx, "token", types.ActivityRequest{ AppId: "A123", }) require.Error(t, err) diff --git a/internal/api/app_test.go b/internal/api/app_test.go index d8215719..4e2bb361 100644 --- a/internal/api/app_test.go +++ b/internal/api/app_test.go @@ -26,6 +26,7 @@ import ( "github.com/slackapi/slack-cli/internal/config" "github.com/slackapi/slack-cli/internal/iostreams" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackdeps" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/stretchr/testify/mock" @@ -33,13 +34,14 @@ import ( ) func TestClient_CreateApp_Ok(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: appManifestCreateMethod, ExpectedRequest: `{"manifest":{"display_information":{"name":"TestApp"}},"enable_distribution":true}`, Response: `{"ok":true,"app_id":"A123"}`, }) defer teardown() - result, err := c.CreateApp(context.Background(), "token", types.AppManifest{ + result, err := c.CreateApp(ctx, "token", types.AppManifest{ DisplayInformation: types.DisplayInformation{ Name: "TestApp", }, @@ -49,39 +51,43 @@ func TestClient_CreateApp_Ok(t *testing.T) { } func TestClient_CreateApp_CommonErrors(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) verifyCommonErrorCases(t, appManifestCreateMethod, func(c *Client) error { - _, err := c.CreateApp(context.Background(), "token", types.AppManifest{}, false) + _, err := c.CreateApp(ctx, "token", types.AppManifest{}, false) return err }) } func TestClient_ExportAppManifest_Ok(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: appManifestExportMethod, ExpectedRequest: `{"app_id":"A0123456789"}`, Response: `{"ok":true,"manifest":{"display_information":{"name":"example"}}}`, }) defer teardown() - result, err := c.ExportAppManifest(context.Background(), "token", "A0123456789") + result, err := c.ExportAppManifest(ctx, "token", "A0123456789") require.NoError(t, err) require.Equal(t, "example", result.Manifest.AppManifest.DisplayInformation.Name) } func TestClient_ExportAppManifest_CommonErrors(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) verifyCommonErrorCases(t, appManifestExportMethod, func(c *Client) error { - _, err := c.ExportAppManifest(context.Background(), "token", "A0000000001") + _, err := c.ExportAppManifest(ctx, "token", "A0000000001") return err }) } func TestClient_UpdateApp_OK(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: appManifestUpdateMethod, ExpectedRequest: `{"manifest":{"display_information":{"name":"TestApp"},"outgoing_domains":[]},"app_id":"A123","force_update":true,"consent_breaking_changes":true}`, Response: `{"ok":true,"app_id":"A123"}`, }) defer teardown() - result, err := c.UpdateApp(context.Background(), "token", "A123", types.AppManifest{ + result, err := c.UpdateApp(ctx, "token", "A123", types.AppManifest{ DisplayInformation: types.DisplayInformation{ Name: "TestApp", }, @@ -94,8 +100,9 @@ func TestClient_UpdateApp_OK(t *testing.T) { } func TestClient_UpdateApp_CommonErrors(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) verifyCommonErrorCases(t, appManifestUpdateMethod, func(c *Client) error { - _, err := c.UpdateApp(context.Background(), "token", "A123", types.AppManifest{}, + _, err := c.UpdateApp(ctx, "token", "A123", types.AppManifest{}, /* forceUpdate= */ true, /* continueWithBreakingChanges= */ true) return err @@ -103,12 +110,13 @@ func TestClient_UpdateApp_CommonErrors(t *testing.T) { } func TestClient_UpdateApp_SchemaCompatibilityError(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: appManifestUpdateMethod, Response: `{"ok": false, "error": "err", "errors": [{"message": "schema_compatibility_error: Following datatstore(s) will be deleted after the deploy: tasks"}]}`, }) defer teardown() - _, err := c.UpdateApp(context.Background(), "token", "A123", types.AppManifest{}, + _, err := c.UpdateApp(ctx, "token", "A123", types.AppManifest{}, /* forceUpdate= */ true, /* continueWithBreakingChanges= */ true) require.Error(t, err) @@ -247,11 +255,13 @@ func TestClient_ValidateAppManifest(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) + var ts = httptest.NewServer(http.HandlerFunc(tt.handlerFunc)) defer ts.Close() c := NewClient(&http.Client{}, ts.URL, nil) - got, err := c.ValidateAppManifest(context.Background(), tt.args.token, tt.args.manifest, tt.args.appID) + got, err := c.ValidateAppManifest(ctx, tt.args.token, tt.args.manifest, tt.args.appID) if tt.wantErr { require.Error(t, err) require.Contains(t, err.Error(), tt.wantErrVal.Error()) @@ -264,13 +274,14 @@ func TestClient_ValidateAppManifest(t *testing.T) { } func TestClient_GetPresignedS3PostParams_Ok(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: appGeneratePresignedPostMethod, ExpectedRequest: `{"app_id":"A123"}`, Response: `{"ok":true,"url":"example.com/upload","file_name":"foo.tar.gz","fields":{"X-Amz-Credential":"cred"}}`, }) defer teardown() - result, err := c.GetPresignedS3PostParams(context.Background(), "token", "A123") + result, err := c.GetPresignedS3PostParams(ctx, "token", "A123") require.NoError(t, err) require.Equal(t, "foo.tar.gz", result.FileName) require.Equal(t, "example.com/upload", result.Url) @@ -278,8 +289,9 @@ func TestClient_GetPresignedS3PostParams_Ok(t *testing.T) { } func TestClient_GetPresignedS3PostParams_CommonErrors(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) verifyCommonErrorCases(t, appGeneratePresignedPostMethod, func(c *Client) error { - _, err := c.GetPresignedS3PostParams(context.Background(), "token", "A123") + _, err := c.GetPresignedS3PostParams(ctx, "token", "A123") return err }) } @@ -298,6 +310,7 @@ func TestClient_CertifiedAppInstall(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) // prepare handlerFunc := func(w http.ResponseWriter, r *http.Request) { @@ -316,7 +329,7 @@ func TestClient_CertifiedAppInstall(t *testing.T) { mockAppId := "A123" // execute - _, err := c.CertifiedAppInstall(context.Background(), "token", mockAppId) + _, err := c.CertifiedAppInstall(ctx, "token", mockAppId) // check if (err != nil) != tt.wantErr { @@ -339,7 +352,7 @@ func TestClient_InstallApp(t *testing.T) { var setup = func(t *testing.T) (context.Context, *iostreams.IOStreamsMock) { // Mocks - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fsMock := slackdeps.NewFsMock() osMock := slackdeps.NewOsMock() osMock.AddDefaultMocks() @@ -368,7 +381,7 @@ func TestClient_InstallApp(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - _, ioMock := setup(t) + ctx, ioMock := setup(t) // prepare handlerFunc := func(w http.ResponseWriter, r *http.Request) { @@ -391,7 +404,7 @@ func TestClient_InstallApp(t *testing.T) { TeamDomain: "mock", } // execute - _, _, err := c.DeveloperAppInstall(context.Background(), ioMock, "token", mockApp, []string{}, []string{}, "", false) + _, _, err := c.DeveloperAppInstall(ctx, ioMock, "token", mockApp, []string{}, []string{}, "", false) // check if (err != nil) != tt.wantErr { @@ -430,6 +443,7 @@ func TestClient_UninstallApp(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) // prepare handlerFunc := func(w http.ResponseWriter, r *http.Request) { @@ -447,7 +461,7 @@ func TestClient_UninstallApp(t *testing.T) { c := NewClient(&http.Client{}, ts.URL, nil) // execute - err := c.UninstallApp(context.Background(), "token", "A123", "T123") + err := c.UninstallApp(ctx, "token", "A123", "T123") // check if (err != nil) != tt.wantErr { @@ -486,6 +500,7 @@ func TestClient_DeleteApp(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) // prepare handlerFunc := func(w http.ResponseWriter, r *http.Request) { @@ -503,7 +518,7 @@ func TestClient_DeleteApp(t *testing.T) { c := NewClient(&http.Client{}, ts.URL, nil) // execute - err := c.DeleteApp(context.Background(), "token", "A123") + err := c.DeleteApp(ctx, "token", "A123") // check if (err != nil) != tt.wantErr { @@ -559,6 +574,7 @@ func TestClient_DeveloperAppInstall_RequestAppApproval(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) // prepare handlerFunc := func(w http.ResponseWriter, r *http.Request) { @@ -590,7 +606,7 @@ func TestClient_DeveloperAppInstall_RequestAppApproval(t *testing.T) { iostreamMock.On("PrintTrace", mock.Anything, mock.Anything, mock.Anything).Return() // execute - _, _, err := c.DeveloperAppInstall(context.Background(), iostreamMock, "token", tt.app, []string{}, []string{}, tt.orgGrantWorkspaceID, true) + _, _, err := c.DeveloperAppInstall(ctx, iostreamMock, "token", tt.app, []string{}, []string{}, tt.orgGrantWorkspaceID, true) require.NoError(t, err) }) } diff --git a/internal/api/auth_test.go b/internal/api/auth_test.go index 71408508..1abc4cbf 100644 --- a/internal/api/auth_test.go +++ b/internal/api/auth_test.go @@ -15,47 +15,50 @@ package api import ( - "context" "testing" "time" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/stretchr/testify/require" ) func TestClient_GenerateAuthTicket_Ok(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: generateAuthTicketMethod, ExpectedRequest: ``, Response: `{"ok":true,"ticket":"valid-ticket"}`, }) defer teardown() - result, err := c.GenerateAuthTicket(context.Background(), "", false) + result, err := c.GenerateAuthTicket(ctx, "", false) require.NoError(t, err) require.Equal(t, "valid-ticket", result.Ticket) } func TestClient_GenerateAuthTicket_Error(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: generateAuthTicketMethod, ExpectedRequest: ``, Response: `{"ok":false,"error":"fatal_error"}`, }) defer teardown() - _, err := c.GenerateAuthTicket(context.Background(), "", false) + _, err := c.GenerateAuthTicket(ctx, "", false) require.Error(t, err) require.Contains(t, err.Error(), "fatal_error") require.Contains(t, err.Error(), generateAuthTicketMethod) } func TestClient_ExchangeAuthTicket_Ok(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: exchangeAuthTicketMethod, ExpectedRequest: `challenge=valid-challenge&slack_cli_version=&ticket=valid-ticket`, Response: `{"ok":true,"is_ready":true,"token":"valid-token","refresh_token":"valid-refresh-token"}`, }) defer teardown() - result, err := c.ExchangeAuthTicket(context.Background(), "valid-ticket", "valid-challenge", "") + result, err := c.ExchangeAuthTicket(ctx, "valid-ticket", "valid-challenge", "") require.NoError(t, err) require.True(t, result.IsReady) require.Equal(t, "valid-token", result.Token) @@ -63,24 +66,26 @@ func TestClient_ExchangeAuthTicket_Ok(t *testing.T) { } func TestClient_ExchangeAuthTicket_Ok_MissingToken(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: exchangeAuthTicketMethod, ExpectedRequest: `challenge=dummychallenge&slack_cli_version=&ticket=valid-ticket`, Response: `{"ok":true,"token":"","refresh_token":""}`, }) defer teardown() - _, err := c.ExchangeAuthTicket(context.Background(), "valid-ticket", "dummychallenge", "") + _, err := c.ExchangeAuthTicket(ctx, "valid-ticket", "dummychallenge", "") require.Error(t, err, "No token returned from the following Slack API method") } func TestClient_ExchangeAuthTicket_Error(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: exchangeAuthTicketMethod, ExpectedRequest: `challenge=valid-challenge&slack_cli_version=&ticket=valid-ticket`, Response: `{"ok":false,"error":"fatal_error"}`, }) defer teardown() - result, err := c.ExchangeAuthTicket(context.Background(), "valid-ticket", "valid-challenge", "") + result, err := c.ExchangeAuthTicket(ctx, "valid-ticket", "valid-challenge", "") require.False(t, result.IsReady) require.Error(t, err) require.Contains(t, err.Error(), "fatal_error") @@ -88,6 +93,7 @@ func TestClient_ExchangeAuthTicket_Error(t *testing.T) { } func TestClient_RotateToken_Ok(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: rotateTokenMethod, ExpectedRequest: `refresh_token=valid-refresh-token`, @@ -95,7 +101,7 @@ func TestClient_RotateToken_Ok(t *testing.T) { }) defer teardown() c.httpClient.Timeout = 60 * time.Second - result, err := c.RotateToken(context.Background(), types.SlackAuth{ + result, err := c.RotateToken(ctx, types.SlackAuth{ Token: `valid-token`, RefreshToken: `valid-refresh-token`, }) @@ -106,6 +112,7 @@ func TestClient_RotateToken_Ok(t *testing.T) { } func TestClient_RotateToken_OkDevHostRestoreTimeout(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: rotateTokenMethod, ExpectedRequest: `refresh_token=valid-refresh-token`, @@ -115,7 +122,7 @@ func TestClient_RotateToken_OkDevHostRestoreTimeout(t *testing.T) { devHost := "https://dev1234.slack.com" c.host = devHost c.httpClient.Timeout = 24 * time.Second - _, err := c.RotateToken(context.Background(), types.SlackAuth{ + _, err := c.RotateToken(ctx, types.SlackAuth{ ApiHost: &devHost, Token: `valid-token`, RefreshToken: `valid-refresh-token`, @@ -125,13 +132,14 @@ func TestClient_RotateToken_OkDevHostRestoreTimeout(t *testing.T) { } func TestClient_RotateToken_Error(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: rotateTokenMethod, ExpectedRequest: `refresh_token=valid-refresh-token`, Response: `{"ok":false,"error":"fatal_error"}`, }) defer teardown() - _, err := c.RotateToken(context.Background(), types.SlackAuth{ + _, err := c.RotateToken(ctx, types.SlackAuth{ Token: `valid-token`, RefreshToken: `valid-refresh-token`, }) diff --git a/internal/api/client.go b/internal/api/client.go index 1e336f5c..a3c3a3f6 100644 --- a/internal/api/client.go +++ b/internal/api/client.go @@ -30,9 +30,9 @@ import ( "github.com/opentracing/opentracing-go" "github.com/pkg/errors" "github.com/slackapi/slack-cli/internal/config" - "github.com/slackapi/slack-cli/internal/contextutil" "github.com/slackapi/slack-cli/internal/goutils" "github.com/slackapi/slack-cli/internal/iostreams" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackdeps" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/uber/jaeger-client-go" @@ -114,7 +114,11 @@ func (c *Client) postForm(ctx context.Context, endpoint string, formValues url.V if err != nil { return nil, err } - cliVersion := contextutil.VersionFromContext(ctx) + + cliVersion, err := slackcontext.Version(ctx) + if err != nil { + return nil, err + } var userAgent = fmt.Sprintf("slack-cli/%s (os: %s)", cliVersion, runtime.GOOS) request.Header.Add("content-type", "application/x-www-form-urlencoded") @@ -162,9 +166,11 @@ func (c *Client) postJSON(ctx context.Context, endpoint, token string, cookie st request.Header.Add("Authorization", "Bearer "+token) } - cliVersion := contextutil.VersionFromContext(ctx) + cliVersion, err := slackcontext.Version(ctx) + if err != nil { + return nil, err + } var userAgent = fmt.Sprintf("slack-cli/%s (os: %s)", cliVersion, runtime.GOOS) - request.Header.Add("User-Agent", userAgent) if jaegerSpanContext, ok := span.Context().(jaeger.SpanContext); ok { request.Header.Add("x-b3-sampled", "0") @@ -213,7 +219,10 @@ func (c *Client) get(ctx context.Context, endpoint, token string, cookie string) request.Header.Add("Authorization", "Bearer "+token) } - cliVersion := contextutil.VersionFromContext(ctx) + cliVersion, err := slackcontext.Version(ctx) + if err != nil { + return nil, err + } var userAgent = fmt.Sprintf("slack-cli/%s (os: %s)", cliVersion, runtime.GOOS) request.Header.Add("User-Agent", userAgent) diff --git a/internal/api/datastore_test.go b/internal/api/datastore_test.go index 151ad7d6..6d6540a2 100644 --- a/internal/api/datastore_test.go +++ b/internal/api/datastore_test.go @@ -15,13 +15,13 @@ package api import ( - "context" "fmt" "net/http" "net/http/httptest" "testing" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/stretchr/testify/require" ) @@ -127,10 +127,11 @@ func TestClient_AppsDatastorePut(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) ts := httptest.NewServer(http.HandlerFunc(tt.testHandler.handlerFunc)) defer ts.Close() apiClient := NewClient(&http.Client{}, ts.URL, nil) - got, err := apiClient.AppsDatastorePut(context.Background(), "shhh", tt.args.request) + got, err := apiClient.AppsDatastorePut(ctx, "shhh", tt.args.request) if (err != nil) != tt.wantErr { t.Errorf("Client.AppsDatastorePut() error = %v, wantErr %v", err, tt.wantErr) return @@ -249,10 +250,11 @@ func TestClient_AppsDatastoreUpdate(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) ts := httptest.NewServer(http.HandlerFunc(tt.testHandler.handlerFunc)) defer ts.Close() apiClient := NewClient(&http.Client{}, ts.URL, nil) - got, err := apiClient.AppsDatastoreUpdate(context.Background(), "shhh", tt.args.request) + got, err := apiClient.AppsDatastoreUpdate(ctx, "shhh", tt.args.request) if (err != nil) != tt.wantErr { t.Errorf("Client.AppsDatastoreUpdate() error = %v, wantErr %v", err, tt.wantErr) return @@ -359,10 +361,11 @@ func TestClient_AppsDatastoreQuery(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) ts := httptest.NewServer(http.HandlerFunc(tt.testHandler.handlerFunc)) defer ts.Close() apiClient := NewClient(&http.Client{}, ts.URL, nil) - got, err := apiClient.AppsDatastoreQuery(context.Background(), "shhh", tt.args.query) + got, err := apiClient.AppsDatastoreQuery(ctx, "shhh", tt.args.query) if (err != nil) != tt.wantErr { t.Errorf("Client.AppsDatastoreQuery() error = %v, wantErr %v", err, tt.wantErr) return @@ -470,10 +473,11 @@ func TestClient_AppsDatastoreDelete(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) ts := httptest.NewServer(http.HandlerFunc(tt.testHandler.handlerFunc)) defer ts.Close() apiClient := NewClient(&http.Client{}, ts.URL, nil) - got, err := apiClient.AppsDatastoreDelete(context.Background(), "shhh", tt.args.request) + got, err := apiClient.AppsDatastoreDelete(ctx, "shhh", tt.args.request) if (err != nil) != tt.wantErr { t.Errorf("Client.AppsDatastoreDelete() error = %v, wantErr %v", err, tt.wantErr) return @@ -583,10 +587,11 @@ func TestClient_AppsDatastoreGet(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) ts := httptest.NewServer(http.HandlerFunc(tt.testHandler.handlerFunc)) defer ts.Close() apiClient := NewClient(&http.Client{}, ts.URL, nil) - got, err := apiClient.AppsDatastoreGet(context.Background(), "shhh", tt.args.request) + got, err := apiClient.AppsDatastoreGet(ctx, "shhh", tt.args.request) if (err != nil) != tt.wantErr { t.Errorf("Client.AppsDatastoreGet() error = %v, wantErr %v", err, tt.wantErr) return diff --git a/internal/api/externalauth_test.go b/internal/api/externalauth_test.go index 8ff82797..df3f6174 100644 --- a/internal/api/externalauth_test.go +++ b/internal/api/externalauth_test.go @@ -15,13 +15,13 @@ package api import ( - "context" "fmt" "net/http" "net/http/httptest" "testing" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/stretchr/testify/require" ) @@ -66,6 +66,8 @@ func Test_API_AppsAuthExternalStart(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) + // Setup HTTP test server httpHandlerFunc := func(w http.ResponseWriter, r *http.Request) { json := tt.httpResponseJSON @@ -77,7 +79,7 @@ func Test_API_AppsAuthExternalStart(t *testing.T) { apiClient := NewClient(&http.Client{}, ts.URL, nil) // Execute test - authorizationURL, err := apiClient.AppsAuthExternalStart(context.Background(), tt.argsToken, tt.argsAppID, tt.argsProviderKey) + authorizationURL, err := apiClient.AppsAuthExternalStart(ctx, tt.argsToken, tt.argsAppID, tt.argsProviderKey) // Assertions require.Equal(t, tt.expectedAuthorizationURL, authorizationURL) @@ -127,6 +129,8 @@ func Test_API_AppsAuthExternalRemove(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) + // Setup HTTP test server httpHandlerFunc := func(w http.ResponseWriter, r *http.Request) { json := tt.httpResponseJSON @@ -138,7 +142,7 @@ func Test_API_AppsAuthExternalRemove(t *testing.T) { apiClient := NewClient(&http.Client{}, ts.URL, nil) // Execute test - err := apiClient.AppsAuthExternalDelete(context.Background(), tt.argsToken, tt.argsAppID, tt.argsProviderKey, "") + err := apiClient.AppsAuthExternalDelete(ctx, tt.argsToken, tt.argsAppID, tt.argsProviderKey, "") // Assertions if tt.expectedErrorContains == "" { @@ -190,6 +194,8 @@ func Test_API_AppsAuthExternalClientSecretAdd(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) + // Setup HTTP test server httpHandlerFunc := func(w http.ResponseWriter, r *http.Request) { json := tt.httpResponseJSON @@ -201,7 +207,7 @@ func Test_API_AppsAuthExternalClientSecretAdd(t *testing.T) { apiClient := NewClient(&http.Client{}, ts.URL, nil) // Execute test - err := apiClient.AppsAuthExternalClientSecretAdd(context.Background(), tt.argsToken, tt.argsAppID, tt.argsProviderKey, tt.argsClientSecret) + err := apiClient.AppsAuthExternalClientSecretAdd(ctx, tt.argsToken, tt.argsAppID, tt.argsProviderKey, tt.argsClientSecret) // Assertions if tt.expectedErrorContains == "" { @@ -367,6 +373,8 @@ func Test_API_AppsAuthExternalList(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) + // Setup HTTP test server httpHandlerFunc := func(w http.ResponseWriter, r *http.Request) { json := tt.httpResponseJSON @@ -378,7 +386,7 @@ func Test_API_AppsAuthExternalList(t *testing.T) { apiClient := NewClient(&http.Client{}, ts.URL, nil) // Execute test - actual, err := apiClient.AppsAuthExternalList(context.Background(), tt.argsToken, tt.argsAppID, false /*include_workflows flag to return workflow auth info*/) + actual, err := apiClient.AppsAuthExternalList(ctx, tt.argsToken, tt.argsAppID, false /*include_workflows flag to return workflow auth info*/) // Assertions if tt.expectedErrorContains == "" { @@ -438,6 +446,8 @@ func Test_API_AppsAuthExternalSelectAuth(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) + // Setup HTTP test server httpHandlerFunc := func(w http.ResponseWriter, r *http.Request) { json := tt.httpResponseJSON @@ -449,7 +459,7 @@ func Test_API_AppsAuthExternalSelectAuth(t *testing.T) { apiClient := NewClient(&http.Client{}, ts.URL, nil) // Execute test - err := apiClient.AppsAuthExternalSelectAuth(context.Background(), tt.argsToken, tt.argsAppID, tt.argsProviderKey, tt.argsWorkflowId, tt.argsExternalTokenId) + err := apiClient.AppsAuthExternalSelectAuth(ctx, tt.argsToken, tt.argsAppID, tt.argsProviderKey, tt.argsWorkflowId, tt.argsExternalTokenId) // Assertions if tt.expectedErrorContains == "" { diff --git a/internal/api/functiondistribution_test.go b/internal/api/functiondistribution_test.go index 3beddae5..b29ad623 100644 --- a/internal/api/functiondistribution_test.go +++ b/internal/api/functiondistribution_test.go @@ -15,13 +15,13 @@ package api import ( - "context" "fmt" "net/http" "net/http/httptest" "testing" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/stretchr/testify/require" ) @@ -30,7 +30,7 @@ func TestClient_AddRemoveSetAccess(t *testing.T) { name string expectedPath string resultJson string - testFunc func(c *Client) error + testFunc func(t *testing.T, c *Client) error want string wantErr bool errMessage string @@ -38,15 +38,17 @@ func TestClient_AddRemoveSetAccess(t *testing.T) { { name: "Add user success", resultJson: `{"ok": true, "distribution_type": "named_entities", "user_ids": ["user1", "user2"]}`, - testFunc: func(c *Client) error { - return c.FunctionDistributionAddUsers(context.Background(), "valid_function", "app", "user1,user2") + testFunc: func(t *testing.T, c *Client) error { + ctx := slackcontext.MockContext(t.Context()) + return c.FunctionDistributionAddUsers(ctx, "valid_function", "app", "user1,user2") }, }, { name: "Add user: validation error", resultJson: `{"ok": false, "error":"user_not_found"}`, - testFunc: func(c *Client) error { - return c.FunctionDistributionAddUsers(context.Background(), "valid_function", "app", "user1,user2") + testFunc: func(t *testing.T, c *Client) error { + ctx := slackcontext.MockContext(t.Context()) + return c.FunctionDistributionAddUsers(ctx, "valid_function", "app", "user1,user2") }, wantErr: true, errMessage: "user_not_found", @@ -54,15 +56,17 @@ func TestClient_AddRemoveSetAccess(t *testing.T) { { name: "Remove user success", resultJson: `{"ok": true, "distribution_type": "named_entities", "user_ids": []}`, - testFunc: func(c *Client) error { - return c.FunctionDistributionRemoveUsers(context.Background(), "valid_function", "app", "user1,user2") + testFunc: func(t *testing.T, c *Client) error { + ctx := slackcontext.MockContext(t.Context()) + return c.FunctionDistributionRemoveUsers(ctx, "valid_function", "app", "user1,user2") }, }, { name: "Remove user: distribution type not named_entitied", resultJson: `{"ok":false,"error":"invalid_distribution_type"}`, - testFunc: func(c *Client) error { - return c.FunctionDistributionRemoveUsers(context.Background(), "valid_function", "app", "user1,user2") + testFunc: func(t *testing.T, c *Client) error { + ctx := slackcontext.MockContext(t.Context()) + return c.FunctionDistributionRemoveUsers(ctx, "valid_function", "app", "user1,user2") }, wantErr: true, errMessage: "invalid_distribution_type", @@ -70,16 +74,18 @@ func TestClient_AddRemoveSetAccess(t *testing.T) { { name: "Set access type success", resultJson: `{"ok": true, "distribution_type": "everyone", "user_ids": []}`, - testFunc: func(c *Client) error { - _, err := c.FunctionDistributionSet(context.Background(), "valid_function", "app", types.EVERYONE, "") + testFunc: func(t *testing.T, c *Client) error { + ctx := slackcontext.MockContext(t.Context()) + _, err := c.FunctionDistributionSet(ctx, "valid_function", "app", types.EVERYONE, "") return err }, }, { name: "Set access type: access type not recognized by backend", resultJson: `{"ok":false,"error":"invalid_arguments"}`, - testFunc: func(c *Client) error { - _, err := c.FunctionDistributionSet(context.Background(), "valid_function", "app", types.EVERYONE, "") + testFunc: func(t *testing.T, c *Client) error { + ctx := slackcontext.MockContext(t.Context()) + _, err := c.FunctionDistributionSet(ctx, "valid_function", "app", types.EVERYONE, "") return err }, wantErr: true, @@ -89,7 +95,6 @@ func TestClient_AddRemoveSetAccess(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - // prepare handlerFunc := func(w http.ResponseWriter, r *http.Request) { result := tt.resultJson @@ -101,7 +106,7 @@ func TestClient_AddRemoveSetAccess(t *testing.T) { c := NewClient(&http.Client{}, ts.URL, nil) // execute - err := tt.testFunc(c) + err := tt.testFunc(t, c) // check if (err != nil) != tt.wantErr { @@ -121,55 +126,60 @@ func TestClient_AddRemoveSetAccess(t *testing.T) { } func TestClient_FunctionDistributionList_Ok(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: functionDistributionsPermissionsListMethod, Response: `{"ok":true,"distribution_type":"everyone","users":[{"user_id":"W123","username":"grace","email":"grace@gmail.com"}]}`, }) defer teardown() - _, _, err := c.FunctionDistributionList(context.Background(), "dummy_callback_id", "dummy_app_id") + _, _, err := c.FunctionDistributionList(ctx, "dummy_callback_id", "dummy_app_id") require.NoError(t, err) } func TestClient_FunctionDistributionList_HTTPRequestFailed(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: functionDistributionsPermissionsListMethod, StatusCode: http.StatusInternalServerError, }) defer teardown() - _, _, err := c.FunctionDistributionList(context.Background(), "dummy_callback_id", "dummy_app_id") + _, _, err := c.FunctionDistributionList(ctx, "dummy_callback_id", "dummy_app_id") require.Error(t, err) require.Contains(t, err.Error(), "http_request_failed") } func TestClient_FunctionDistributionList_HTTPResponseInvalid(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: functionDistributionsPermissionsListMethod, Response: "}{", }) defer teardown() - _, _, err := c.FunctionDistributionList(context.Background(), "dummy_callback_id", "dummy_app_id") + _, _, err := c.FunctionDistributionList(ctx, "dummy_callback_id", "dummy_app_id") require.Error(t, err) require.Contains(t, err.Error(), "http_response_invalid") } func TestClient_FunctionDistributionList_NotOk(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: functionDistributionsPermissionsListMethod, Response: `{"ok":false}`, }) defer teardown() - _, _, err := c.FunctionDistributionList(context.Background(), "dummy_callback_id", "dummy_app_id") + _, _, err := c.FunctionDistributionList(ctx, "dummy_callback_id", "dummy_app_id") require.Error(t, err) require.Contains(t, err.Error(), functionDistributionsPermissionsListMethod) } func TestClient_FunctionDistributionList_InvalidDistType(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: functionDistributionsPermissionsListMethod, Response: `{"ok":true,"distribution_type":"banana"}`, }) defer teardown() - _, _, err := c.FunctionDistributionList(context.Background(), "dummy_callback_id", "dummy_app_id") + _, _, err := c.FunctionDistributionList(ctx, "dummy_callback_id", "dummy_app_id") require.Error(t, err) require.Contains(t, err.Error(), "unrecognized access type banana") } diff --git a/internal/api/icon.go b/internal/api/icon.go index 0fd7ffb6..087e7f58 100644 --- a/internal/api/icon.go +++ b/internal/api/icon.go @@ -27,8 +27,8 @@ import ( "runtime" "github.com/opentracing/opentracing-go" - "github.com/slackapi/slack-cli/internal/contextutil" "github.com/slackapi/slack-cli/internal/image" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/spf13/afero" ) @@ -115,7 +115,10 @@ func (c *Client) Icon(ctx context.Context, fs afero.Fs, token, appID, iconFilePa } request.Header.Add("Content-Type", writer.FormDataContentType()) request.Header.Add("Authorization", "Bearer "+token) - cliVersion := contextutil.VersionFromContext(ctx) + cliVersion, err := slackcontext.Version(ctx) + if err != nil { + return IconResult{}, err + } var userAgent = fmt.Sprintf("slack-cli/%s (os: %s)", cliVersion, runtime.GOOS) request.Header.Add("User-Agent", userAgent) diff --git a/internal/api/icon_test.go b/internal/api/icon_test.go index 711db40b..b5833ba8 100644 --- a/internal/api/icon_test.go +++ b/internal/api/icon_test.go @@ -15,13 +15,13 @@ package api import ( - "context" "image" "image/color" "image/png" "math/rand" "testing" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/spf13/afero" "github.com/stretchr/testify/require" ) @@ -29,28 +29,31 @@ import ( var imgFile = ".assets/icon.png" func TestClient_IconErrorIfMissingArgs(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) fs := afero.NewMemMapFs() c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: appIconMethod, }) defer teardown() - _, err := c.Icon(context.Background(), fs, "token", "", "") + _, err := c.Icon(ctx, fs, "token", "", "") require.Error(t, err) require.Contains(t, err.Error(), "missing required args") } func TestClient_IconErrorNoFile(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) fs := afero.NewMemMapFs() c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: appIconMethod, }) defer teardown() - _, err := c.Icon(context.Background(), fs, "token", "12345", imgFile) + _, err := c.Icon(ctx, fs, "token", "12345", imgFile) require.Error(t, err) require.Contains(t, err.Error(), "file does not exist") } func TestClient_IconErrorWrongFile(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) fs := afero.NewMemMapFs() err := afero.WriteFile(fs, "test.txt", []byte("this is a text file"), 0666) require.NoError(t, err) @@ -58,12 +61,13 @@ func TestClient_IconErrorWrongFile(t *testing.T) { ExpectedMethod: appIconMethod, }) defer teardown() - _, err = c.Icon(context.Background(), fs, "token", "12345", "test.txt") + _, err = c.Icon(ctx, fs, "token", "12345", "test.txt") require.Error(t, err) require.Contains(t, err.Error(), "unknown format") } func TestClient_IconSuccess(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) fs := afero.NewMemMapFs() myimage := image.NewRGBA(image.Rectangle{image.Point{0, 0}, image.Point{100, 100}}) @@ -83,6 +87,6 @@ func TestClient_IconSuccess(t *testing.T) { Response: `{"ok":true}`, }) defer teardown() - _, err = c.Icon(context.Background(), fs, "token", "12345", imgFile) + _, err = c.Icon(ctx, fs, "token", "12345", imgFile) require.NoError(t, err) } diff --git a/internal/api/s3_upload.go b/internal/api/s3_upload.go index 8626317e..fcfbf081 100644 --- a/internal/api/s3_upload.go +++ b/internal/api/s3_upload.go @@ -27,7 +27,7 @@ import ( "runtime" "github.com/opentracing/opentracing-go" - "github.com/slackapi/slack-cli/internal/contextutil" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/spf13/afero" ) @@ -106,7 +106,10 @@ func (c *Client) UploadPackageToS3(ctx context.Context, fs afero.Fs, appID strin } request.Header.Add("Content-Type", writer.FormDataContentType()) request.Header.Add("Content-MD5", md5s) - cliVersion := contextutil.VersionFromContext(ctx) + cliVersion, err := slackcontext.Version(ctx) + if err != nil { + return fileName, err + } var userAgent = fmt.Sprintf("slack-cli/%s (os: %s)", cliVersion, runtime.GOOS) request.Header.Add("User-Agent", userAgent) diff --git a/internal/api/s3_upload_test.go b/internal/api/s3_upload_test.go index f2d6ac61..0aa94f16 100644 --- a/internal/api/s3_upload_test.go +++ b/internal/api/s3_upload_test.go @@ -15,7 +15,6 @@ package api import ( - "context" "io" "mime" "mime/multipart" @@ -23,11 +22,13 @@ import ( "net/http/httptest" "testing" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/spf13/afero" "github.com/stretchr/testify/require" ) func TestClient_UploadPackageToS3(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) fs := afero.NewMemMapFs() err := afero.WriteFile(fs, "foo.txt", []byte("this is the package"), 0666) require.NoError(t, err) @@ -87,7 +88,7 @@ func TestClient_UploadPackageToS3(t *testing.T) { AmzToken: token, }, } - resp, err := client.UploadPackageToS3(context.Background(), fs, "appID", s3Params, "foo.txt") + resp, err := client.UploadPackageToS3(ctx, fs, "appID", s3Params, "foo.txt") require.NoError(t, err) require.Equal(t, "foo.txt", resp) } diff --git a/internal/api/session_test.go b/internal/api/session_test.go index 09600e2a..0c0f40f8 100644 --- a/internal/api/session_test.go +++ b/internal/api/session_test.go @@ -15,20 +15,21 @@ package api import ( - "context" "net/http" "testing" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/stretchr/testify/require" ) func TestClient_ValidateSession_AuthRespOk(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: sessionValidateMethod, Response: `{"ok":true,"url":"https://www.example.com/","team":"Example Workspace", "user":"grace","team_id":"T123","user_id":"W123","enterprise_id":"E123","is_enterprise_install":true}`, }) defer teardown() - resp, err := c.ValidateSession(context.Background(), "token") + resp, err := c.ValidateSession(ctx, "token") require.NoError(t, err) require.Equal(t, *resp.UserName, "grace") require.Equal(t, *resp.UserID, "W123") @@ -40,124 +41,135 @@ func TestClient_ValidateSession_AuthRespOk(t *testing.T) { } func TestClient_ValidateSession_AuthRespOk_MissingUserID(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: sessionValidateMethod, Response: `{"ok":true,"url":"https://www.example.com/","team":"Example Workspace", "user":"grace","team_id":"T123"}`, }) defer teardown() - _, err := c.ValidateSession(context.Background(), "token") + _, err := c.ValidateSession(ctx, "token") require.Error(t, err) require.Contains(t, err.Error(), "http_response_invalid") require.Contains(t, err.Error(), "invalid user_id") } func TestClient_ValidateSession_AuthRespNotOk(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: sessionValidateMethod, Response: `{"ok":false}`, }) defer teardown() - _, err := c.ValidateSession(context.Background(), "token") + _, err := c.ValidateSession(ctx, "token") require.Error(t, err) require.Contains(t, err.Error(), sessionValidateMethod) require.Contains(t, err.Error(), "unknown_error") } func TestClient_ValidateSession_AuthRespNotOk_NotAuthed(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: sessionValidateMethod, Response: `{"ok":false,"error":"not_authed"}`, }) defer teardown() - _, err := c.ValidateSession(context.Background(), "token") + _, err := c.ValidateSession(ctx, "token") require.Error(t, err) require.Contains(t, err.Error(), "not_authed") require.Contains(t, err.Error(), "You are either not logged in or your login session has expired") } func TestClient_ValidateSession_AuthRespNotOk_InvalidAuth(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: sessionValidateMethod, Response: `{"ok":false,"error":"invalid_auth"}`, }) defer teardown() - _, err := c.ValidateSession(context.Background(), "token") + _, err := c.ValidateSession(ctx, "token") require.Error(t, err) require.Contains(t, err.Error(), "invalid_auth") require.Contains(t, err.Error(), "Your user account authorization isn't valid") } func TestClient_ValidateSession_HTTPRequestFailed(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: sessionValidateMethod, StatusCode: http.StatusInternalServerError, }) defer teardown() - _, err := c.ValidateSession(context.Background(), "token") + _, err := c.ValidateSession(ctx, "token") require.Error(t, err) require.Contains(t, err.Error(), "http_request_failed") } func TestClient_RevokeToken_ErrNotLoggedIn(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: revokeTokenMethod, StatusCode: http.StatusInternalServerError, }) defer teardown() - err := c.RevokeToken(context.Background(), "token") + err := c.RevokeToken(ctx, "token") require.Error(t, err) require.Contains(t, err.Error(), "http_request_failed") } func TestClient_ValidateSession_HTTPResponseInvalid(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: sessionValidateMethod, Response: `badresponse`, }) defer teardown() - _, err := c.ValidateSession(context.Background(), "token") + _, err := c.ValidateSession(ctx, "token") require.Error(t, err) require.Contains(t, err.Error(), "http_response_invalid") } func TestClient_RevokeToken_Ok(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: revokeTokenMethod, Response: `{"ok":true,"revoked":true}`, }) defer teardown() - err := c.RevokeToken(context.Background(), "token") + err := c.RevokeToken(ctx, "token") require.NoError(t, err) } func TestClient_RevokeToken_NotOk(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: revokeTokenMethod, Response: `{"ok":false}`, }) defer teardown() - err := c.RevokeToken(context.Background(), "token") + err := c.RevokeToken(ctx, "token") require.Error(t, err) } func TestClient_RevokeToken_NotOk_MappedErrorMsgs(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: revokeTokenMethod, Response: `{"ok":false,"error":"token_expired"}`, }) defer teardown() - err := c.RevokeToken(context.Background(), "token") + err := c.RevokeToken(ctx, "token") require.Error(t, err) require.Contains(t, err.Error(), "token_expired") } func TestClient_RevokeToken_JsonUnmarshalFail(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: revokeTokenMethod, Response: `}{`, }) defer teardown() - err := c.RevokeToken(context.Background(), "token") + err := c.RevokeToken(ctx, "token") require.Error(t, err) require.Contains(t, err.Error(), "http_response_invalid") } diff --git a/internal/api/steps_test.go b/internal/api/steps_test.go index 92a8f9a3..562e1719 100644 --- a/internal/api/steps_test.go +++ b/internal/api/steps_test.go @@ -15,20 +15,21 @@ package api import ( - "context" "testing" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/stretchr/testify/require" ) func TestClient_StepsList_Ok(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: workflowsStepsListMethod, ExpectedRequest: `{"workflow_app_id":"A123","workflow":"#/workflows/my-workflow","function_id":"Fn010N"}`, Response: `{"ok":true,"steps_versions":[{"title":"cool form","workflow_id":"Wf123","step_id":"0","is_deleted":false,"workflow_version_created":"1234"}]}`, }) defer teardown() - versions, err := c.StepsList(context.Background(), "token", "#/workflows/my-workflow", "A123") + versions, err := c.StepsList(ctx, "token", "#/workflows/my-workflow", "A123") require.NoError(t, err) require.ElementsMatch(t, versions, []StepVersion{ { @@ -42,25 +43,28 @@ func TestClient_StepsList_Ok(t *testing.T) { } func TestClient_StepsList_Errors(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) verifyCommonErrorCases(t, workflowsStepsListMethod, func(c *Client) error { - _, err := c.StepsList(context.Background(), "token", "#/workflows/my-workflow", "A123") + _, err := c.StepsList(ctx, "token", "#/workflows/my-workflow", "A123") return err }) } func TestClient_StepsResponsesExport_Ok(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: workflowsStepsResponsesExportMethod, ExpectedRequest: `{"workflow_app_id":"A123","workflow":"#/workflows/my-workflow","step_id":"0"}`, Response: `{"ok":true}`, }) defer teardown() - err := c.StepsResponsesExport(context.Background(), "token", "#/workflows/my-workflow", "A123", "0") + err := c.StepsResponsesExport(ctx, "token", "#/workflows/my-workflow", "A123", "0") require.NoError(t, err) } func TestClient_StepsResponsesExport_Errors(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) verifyCommonErrorCases(t, workflowsStepsResponsesExportMethod, func(c *Client) error { - return c.StepsResponsesExport(context.Background(), "token", "#/workflows/my-workflow", "A123", "0") + return c.StepsResponsesExport(ctx, "token", "#/workflows/my-workflow", "A123", "0") }) } diff --git a/internal/api/teams_test.go b/internal/api/teams_test.go index 3d1f4e30..dd572e7e 100644 --- a/internal/api/teams_test.go +++ b/internal/api/teams_test.go @@ -15,13 +15,13 @@ package api import ( - "context" "fmt" "net/http" "net/http/httptest" "testing" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/stretchr/testify/require" ) @@ -63,6 +63,8 @@ func Test_API_TeamInfoResponse(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) + // Setup HTTP test server httpHandlerFunc := func(w http.ResponseWriter, r *http.Request) { json := tt.httpResponseJSON @@ -74,7 +76,7 @@ func Test_API_TeamInfoResponse(t *testing.T) { apiClient := NewClient(&http.Client{}, ts.URL, nil) // Execute test - actual, err := apiClient.TeamsInfo(context.Background(), tt.argsToken, tt.argsTeamID) + actual, err := apiClient.TeamsInfo(ctx, tt.argsToken, tt.argsTeamID) // Assertions if tt.expectedErrorContains == "" { diff --git a/internal/api/triggerpermissions_test.go b/internal/api/triggerpermissions_test.go index 10c416a6..6f322225 100644 --- a/internal/api/triggerpermissions_test.go +++ b/internal/api/triggerpermissions_test.go @@ -15,10 +15,10 @@ package api import ( - "context" "testing" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/stretchr/testify/require" ) @@ -90,6 +90,7 @@ func TestClient_TriggerPermissionsSet(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) // prepare c, teardown := NewFakeClient(t, FakeClientParams{ @@ -101,7 +102,7 @@ func TestClient_TriggerPermissionsSet(t *testing.T) { // execute if tt.users != "" { - _, err := c.TriggerPermissionsSet(context.Background(), fakeToken, fakeTriggerID, tt.users, tt.permissionType, "users") + _, err := c.TriggerPermissionsSet(ctx, fakeToken, fakeTriggerID, tt.users, tt.permissionType, "users") // check if (err != nil) != tt.wantErr { @@ -117,7 +118,7 @@ func TestClient_TriggerPermissionsSet(t *testing.T) { ) } } else if tt.channels != "" { - _, err := c.TriggerPermissionsSet(context.Background(), fakeToken, fakeTriggerID, tt.channels, tt.permissionType, "channels") + _, err := c.TriggerPermissionsSet(ctx, fakeToken, fakeTriggerID, tt.channels, tt.permissionType, "channels") // check if (err != nil) != tt.wantErr { @@ -133,7 +134,7 @@ func TestClient_TriggerPermissionsSet(t *testing.T) { ) } } else if tt.workspaces != "" { - _, err := c.TriggerPermissionsSet(context.Background(), fakeToken, fakeTriggerID, tt.workspaces, tt.permissionType, "workspaces") + _, err := c.TriggerPermissionsSet(ctx, fakeToken, fakeTriggerID, tt.workspaces, tt.permissionType, "workspaces") // check if (err != nil) != tt.wantErr { @@ -149,7 +150,7 @@ func TestClient_TriggerPermissionsSet(t *testing.T) { ) } } else if tt.organizations != "" { - _, err := c.TriggerPermissionsSet(context.Background(), fakeToken, fakeTriggerID, tt.organizations, tt.permissionType, "organizations") + _, err := c.TriggerPermissionsSet(ctx, fakeToken, fakeTriggerID, tt.organizations, tt.permissionType, "organizations") // check if (err != nil) != tt.wantErr { @@ -169,7 +170,8 @@ func TestClient_TriggerPermissionsSet(t *testing.T) { } verifyCommonErrorCases(t, workflowsTriggersPermissionsSetMethod, func(c *Client) error { - _, err := c.TriggerPermissionsSet(context.Background(), "xoxp-123", "Ft123", "user1", types.APP_COLLABORATORS, "users") + ctx := slackcontext.MockContext(t.Context()) + _, err := c.TriggerPermissionsSet(ctx, "xoxp-123", "Ft123", "user1", types.APP_COLLABORATORS, "users") return err }) } @@ -223,6 +225,7 @@ func TestClient_TriggerPermissionsAddEntities(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) // prepare c, teardown := NewFakeClient(t, FakeClientParams{ @@ -234,7 +237,7 @@ func TestClient_TriggerPermissionsAddEntities(t *testing.T) { // execute if tt.users != "" { - err := c.TriggerPermissionsAddEntities(context.Background(), fakeToken, fakeTriggerID, tt.users, "users") + err := c.TriggerPermissionsAddEntities(ctx, fakeToken, fakeTriggerID, tt.users, "users") // check if (err != nil) != tt.wantErr { t.Errorf("%s test error = %v, wantErr %v", tt.name, err, tt.wantErr) @@ -249,7 +252,7 @@ func TestClient_TriggerPermissionsAddEntities(t *testing.T) { ) } } else if tt.channels != "" { - err := c.TriggerPermissionsAddEntities(context.Background(), fakeToken, fakeTriggerID, tt.channels, "channels") + err := c.TriggerPermissionsAddEntities(ctx, fakeToken, fakeTriggerID, tt.channels, "channels") // check if (err != nil) != tt.wantErr { t.Errorf("%s test error = %v, wantErr %v", tt.name, err, tt.wantErr) @@ -264,7 +267,7 @@ func TestClient_TriggerPermissionsAddEntities(t *testing.T) { ) } } else if tt.workspaces != "" { - err := c.TriggerPermissionsAddEntities(context.Background(), fakeToken, fakeTriggerID, tt.workspaces, "workspaces") + err := c.TriggerPermissionsAddEntities(ctx, fakeToken, fakeTriggerID, tt.workspaces, "workspaces") // check if (err != nil) != tt.wantErr { t.Errorf("%s test error = %v, wantErr %v", tt.name, err, tt.wantErr) @@ -279,7 +282,7 @@ func TestClient_TriggerPermissionsAddEntities(t *testing.T) { ) } } else if tt.organizations != "" { - err := c.TriggerPermissionsAddEntities(context.Background(), fakeToken, fakeTriggerID, tt.organizations, "organizations") + err := c.TriggerPermissionsAddEntities(ctx, fakeToken, fakeTriggerID, tt.organizations, "organizations") // check if (err != nil) != tt.wantErr { t.Errorf("%s test error = %v, wantErr %v", tt.name, err, tt.wantErr) @@ -299,7 +302,8 @@ func TestClient_TriggerPermissionsAddEntities(t *testing.T) { } verifyCommonErrorCases(t, workflowsTriggersPermissionsAddMethod, func(c *Client) error { - return c.TriggerPermissionsAddEntities(context.Background(), "xoxp-123", "Ft123", "user1", "users") + ctx := slackcontext.MockContext(t.Context()) + return c.TriggerPermissionsAddEntities(ctx, "xoxp-123", "Ft123", "user1", "users") }) } @@ -352,6 +356,7 @@ func TestClient_TriggerPermissionsRemoveEntities(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) // prepare c, teardown := NewFakeClient(t, FakeClientParams{ @@ -363,7 +368,7 @@ func TestClient_TriggerPermissionsRemoveEntities(t *testing.T) { // execute if tt.users != "" { - err := c.TriggerPermissionsRemoveEntities(context.Background(), fakeToken, fakeTriggerID, tt.users, "users") + err := c.TriggerPermissionsRemoveEntities(ctx, fakeToken, fakeTriggerID, tt.users, "users") // check if (err != nil) != tt.wantErr { @@ -379,7 +384,7 @@ func TestClient_TriggerPermissionsRemoveEntities(t *testing.T) { ) } } else if tt.channels != "" { - err := c.TriggerPermissionsRemoveEntities(context.Background(), fakeToken, fakeTriggerID, tt.channels, "channels") + err := c.TriggerPermissionsRemoveEntities(ctx, fakeToken, fakeTriggerID, tt.channels, "channels") // check if (err != nil) != tt.wantErr { @@ -395,7 +400,7 @@ func TestClient_TriggerPermissionsRemoveEntities(t *testing.T) { ) } } else if tt.workspaces != "" { - err := c.TriggerPermissionsRemoveEntities(context.Background(), fakeToken, fakeTriggerID, tt.workspaces, "workspaces") + err := c.TriggerPermissionsRemoveEntities(ctx, fakeToken, fakeTriggerID, tt.workspaces, "workspaces") // check if (err != nil) != tt.wantErr { @@ -411,7 +416,7 @@ func TestClient_TriggerPermissionsRemoveEntities(t *testing.T) { ) } } else if tt.organizations != "" { - err := c.TriggerPermissionsRemoveEntities(context.Background(), fakeToken, fakeTriggerID, tt.organizations, "organizations") + err := c.TriggerPermissionsRemoveEntities(ctx, fakeToken, fakeTriggerID, tt.organizations, "organizations") // check if (err != nil) != tt.wantErr { @@ -431,7 +436,8 @@ func TestClient_TriggerPermissionsRemoveEntities(t *testing.T) { } verifyCommonErrorCases(t, workflowsTriggersPermissionsRemoveMethod, func(c *Client) error { - return c.TriggerPermissionsRemoveEntities(context.Background(), "xoxp-123", "Ft123", "user1", "users") + ctx := slackcontext.MockContext(t.Context()) + return c.TriggerPermissionsRemoveEntities(ctx, "xoxp-123", "Ft123", "user1", "users") }) } @@ -504,6 +510,7 @@ func TestClient_TriggerPermissionsList(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) // prepare c, teardown := NewFakeClient(t, FakeClientParams{ @@ -515,7 +522,7 @@ func TestClient_TriggerPermissionsList(t *testing.T) { // execute if len(tt.expectedUsers) != 0 { - actualType, actualUsers, err := c.TriggerPermissionsList(context.Background(), fakeToken, fakeTriggerID) + actualType, actualUsers, err := c.TriggerPermissionsList(ctx, fakeToken, fakeTriggerID) require.Equal(t, tt.expectedPermissionType, actualType) require.Equal(t, tt.expectedUsers, actualUsers) @@ -533,7 +540,7 @@ func TestClient_TriggerPermissionsList(t *testing.T) { ) } } else if len(tt.expectedChannels) != 0 { - actualType, actualChannels, err := c.TriggerPermissionsList(context.Background(), fakeToken, fakeTriggerID) + actualType, actualChannels, err := c.TriggerPermissionsList(ctx, fakeToken, fakeTriggerID) require.Equal(t, tt.expectedPermissionType, actualType) require.Equal(t, tt.expectedChannels, actualChannels) @@ -551,7 +558,7 @@ func TestClient_TriggerPermissionsList(t *testing.T) { ) } } else if len(tt.expectedWorkspaces) != 0 { - actualType, actualWorkspaces, err := c.TriggerPermissionsList(context.Background(), fakeToken, fakeTriggerID) + actualType, actualWorkspaces, err := c.TriggerPermissionsList(ctx, fakeToken, fakeTriggerID) require.Equal(t, tt.expectedPermissionType, actualType) require.Equal(t, tt.expectedWorkspaces, actualWorkspaces) @@ -569,7 +576,7 @@ func TestClient_TriggerPermissionsList(t *testing.T) { ) } } else if len(tt.expectedOrganizations) != 0 { - actualType, actualOrganizations, err := c.TriggerPermissionsList(context.Background(), fakeToken, fakeTriggerID) + actualType, actualOrganizations, err := c.TriggerPermissionsList(ctx, fakeToken, fakeTriggerID) require.Equal(t, tt.expectedPermissionType, actualType) require.Equal(t, tt.expectedOrganizations, actualOrganizations) @@ -591,7 +598,8 @@ func TestClient_TriggerPermissionsList(t *testing.T) { } verifyCommonErrorCases(t, workflowsTriggersPermissionsListMethod, func(c *Client) error { - _, _, err := c.TriggerPermissionsList(context.Background(), "xoxp-123", "Ft123") + ctx := slackcontext.MockContext(t.Context()) + _, _, err := c.TriggerPermissionsList(ctx, "xoxp-123", "Ft123") return err }) } diff --git a/internal/api/variables_test.go b/internal/api/variables_test.go index 130206a6..fbbab617 100644 --- a/internal/api/variables_test.go +++ b/internal/api/variables_test.go @@ -15,141 +15,153 @@ package api import ( - "context" "net/http" "testing" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/stretchr/testify/require" ) func TestClient_AddVariable_Ok(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: varAddMethod, ExpectedRequest: `{"app_id":"A123","variables":[{"name":"dummy_var","value":"dummy_val"}]}`, Response: `{"ok":true}`, }) defer teardown() - err := c.AddVariable(context.Background(), "token", "A123", "dummy_var", "dummy_val") + err := c.AddVariable(ctx, "token", "A123", "dummy_var", "dummy_val") require.NoError(t, err) } func TestClient_AddVariable_NotOk(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: varAddMethod, ExpectedRequest: `{"app_id":"A123","variables":[{"name":"dummy_var","value":"dummy_val"}]}`, Response: `{"ok":false}`, }) defer teardown() - err := c.AddVariable(context.Background(), "token", "A123", "dummy_var", "dummy_val") + err := c.AddVariable(ctx, "token", "A123", "dummy_var", "dummy_val") require.Error(t, err) require.Contains(t, err.Error(), "unknown_error") } func TestClient_AddVariable_HTTPResponseInvalid(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: varAddMethod, }) defer teardown() - err := c.AddVariable(context.Background(), "token", "", "", "") + err := c.AddVariable(ctx, "token", "", "", "") require.Error(t, err) require.Contains(t, err.Error(), "http_response_invalid") } func TestClient_AddVariable_HTTPRequestFailed(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: varAddMethod, StatusCode: http.StatusInternalServerError, }) defer teardown() - err := c.AddVariable(context.Background(), "token", "", "", "") + err := c.AddVariable(ctx, "token", "", "", "") require.Error(t, err) require.Contains(t, err.Error(), "http_request_failed") } func TestClient_ListVariables_Ok(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: varListMethod, ExpectedRequest: `{"app_id":"A123"}`, Response: `{"ok":true,"variable_names":["var1"]}`, }) defer teardown() - VariableNames, err := c.ListVariables(context.Background(), "token", "A123") + VariableNames, err := c.ListVariables(ctx, "token", "A123") require.NoError(t, err) require.Equal(t, VariableNames[0], "var1") } func TestClient_ListVariables_NotOk(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: varListMethod, ExpectedRequest: `{"app_id":"A123"}`, Response: `{"ok":false}`, }) defer teardown() - _, err := c.ListVariables(context.Background(), "token", "A123") + _, err := c.ListVariables(ctx, "token", "A123") require.Error(t, err) require.Contains(t, err.Error(), "unknown_error") } func TestClient_ListVariables_HTTPResponseInvalid(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: varListMethod, }) defer teardown() - _, err := c.ListVariables(context.Background(), "token", "") + _, err := c.ListVariables(ctx, "token", "") require.Error(t, err) require.Contains(t, err.Error(), "http_response_invalid") } func TestClient_ListVariables_HTTPRequestFailed(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: varListMethod, StatusCode: http.StatusInternalServerError, }) defer teardown() - _, err := c.ListVariables(context.Background(), "token", "") + _, err := c.ListVariables(ctx, "token", "") require.Error(t, err) require.Contains(t, err.Error(), "http_request_failed") } func TestClient_RemoveVariable_Ok(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: varRemoveMethod, ExpectedRequest: `{"app_id":"A123","variable_names":["dummy_var_name"]}`, Response: `{"ok":true}`, }) defer teardown() - err := c.RemoveVariable(context.Background(), "token", "A123", "dummy_var_name") + err := c.RemoveVariable(ctx, "token", "A123", "dummy_var_name") require.NoError(t, err) } func TestClient_RemoveVariable_NotOk(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: varRemoveMethod, ExpectedRequest: `{"app_id":"A123","variable_names":["dummy_var_name"]}`, Response: `{"ok":false}`, }) defer teardown() - err := c.RemoveVariable(context.Background(), "token", "A123", "dummy_var_name") + err := c.RemoveVariable(ctx, "token", "A123", "dummy_var_name") require.Error(t, err) } func TestClient_RemoveVariable_HTTPResponseInvalid(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: varRemoveMethod, }) defer teardown() - err := c.RemoveVariable(context.Background(), "token", "", "") + err := c.RemoveVariable(ctx, "token", "", "") require.Error(t, err) require.Contains(t, err.Error(), "http_response_invalid") } func TestClient_RemoveVariable_HTTPRequestFailed(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: varRemoveMethod, StatusCode: http.StatusInternalServerError, }) defer teardown() - err := c.RemoveVariable(context.Background(), "token", "", "") + err := c.RemoveVariable(ctx, "token", "", "") require.Error(t, err) require.Contains(t, err.Error(), "http_request_failed") } diff --git a/internal/api/workflows_test.go b/internal/api/workflows_test.go index bb259244..ad24fd77 100644 --- a/internal/api/workflows_test.go +++ b/internal/api/workflows_test.go @@ -15,7 +15,6 @@ package api import ( - "context" "fmt" "io" "net/http" @@ -23,6 +22,7 @@ import ( "testing" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/stretchr/testify/require" ) @@ -114,6 +114,7 @@ func TestClient_WorkflowsTriggerCreate(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) // prepare handlerFunc := func(w http.ResponseWriter, r *http.Request) { @@ -132,7 +133,7 @@ func TestClient_WorkflowsTriggerCreate(t *testing.T) { c := NewClient(&http.Client{}, ts.URL, nil) // execute - _, err := c.WorkflowsTriggersCreate(context.Background(), "token", tt.inputTrigger) + _, err := c.WorkflowsTriggersCreate(ctx, "token", tt.inputTrigger) // check if (err != nil) != tt.wantErr { @@ -254,6 +255,7 @@ func TestClient_WorkflowsTriggerUpdate(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) // prepare handlerFunc := func(w http.ResponseWriter, r *http.Request) { @@ -272,7 +274,7 @@ func TestClient_WorkflowsTriggerUpdate(t *testing.T) { c := NewClient(&http.Client{}, ts.URL, nil) // execute - _, err := c.WorkflowsTriggersUpdate(context.Background(), "token", tt.input) + _, err := c.WorkflowsTriggersUpdate(ctx, "token", tt.input) // check if (err != nil) != tt.wantErr { @@ -311,6 +313,7 @@ func TestClient_WorkflowsTriggerDelete(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) // prepare handlerFunc := func(w http.ResponseWriter, r *http.Request) { @@ -328,7 +331,7 @@ func TestClient_WorkflowsTriggerDelete(t *testing.T) { c := NewClient(&http.Client{}, ts.URL, nil) // execute - err := c.WorkflowsTriggersDelete(context.Background(), "token", "FtABC") + err := c.WorkflowsTriggersDelete(ctx, "token", "FtABC") // check if (err != nil) != tt.wantErr { @@ -425,6 +428,7 @@ func Test_API_WorkflowTriggersList(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) c, teardown := NewFakeClient(t, FakeClientParams{ ExpectedMethod: workflowsTriggersListMethod, @@ -438,7 +442,7 @@ func Test_API_WorkflowTriggersList(t *testing.T) { Limit: tt.argsLimit, Cursor: tt.argsCursor, } - actual, _, err := c.WorkflowsTriggersList(context.Background(), tt.argsToken, args) + actual, _, err := c.WorkflowsTriggersList(ctx, tt.argsToken, args) // Assertions if tt.expectedErrorContains == "" { diff --git a/internal/auth/auth_test.go b/internal/auth/auth_test.go index b5affa7c..88fd4b25 100644 --- a/internal/auth/auth_test.go +++ b/internal/auth/auth_test.go @@ -27,6 +27,7 @@ import ( "github.com/slackapi/slack-cli/internal/config" "github.com/slackapi/slack-cli/internal/iostreams" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackdeps" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/spf13/afero" @@ -35,7 +36,6 @@ import ( ) func Test_AuthWithToken(t *testing.T) { - ctx := context.Background() os := slackdeps.NewOsMock() os.AddDefaultMocks() fs := slackdeps.NewFsMock() @@ -81,6 +81,7 @@ func Test_AuthWithToken(t *testing.T) { for name, tt := range tests { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) apic, teardown := api.NewFakeClient(t, api.FakeClientParams{ ExpectedMethod: "auth.test", ExpectedRequest: fmt.Sprintf("token=%s", tt.token), @@ -131,7 +132,7 @@ func Test_AuthGettersAndSetters(t *testing.T) { var setup = func(t *testing.T) (context.Context, *Client) { // Mocks - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fsMock := slackdeps.NewFsMock() osMock := slackdeps.NewOsMock() osMock.AddDefaultMocks() @@ -226,7 +227,7 @@ func Test_AuthGettersAndSetters(t *testing.T) { func Test_AuthsRotation(t *testing.T) { // Setup tests var setup = func(t *testing.T) (context.Context, *Client) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fsMock := slackdeps.NewFsMock() osMock := slackdeps.NewOsMock() osMock.AddDefaultMocks() @@ -416,7 +417,7 @@ func Test_AuthsRotation(t *testing.T) { func Test_Auths(t *testing.T) { var setup = func(t *testing.T) (context.Context, *Client) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fsMock := slackdeps.NewFsMock() osMock := slackdeps.NewOsMock() osMock.AddDefaultMocks() @@ -474,7 +475,7 @@ func Test_Auths(t *testing.T) { func Test_migrateToAuthByTeamID(t *testing.T) { var setup = func(t *testing.T) (context.Context, *Client) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fsMock := slackdeps.NewFsMock() osMock := slackdeps.NewOsMock() osMock.AddDefaultMocks() @@ -528,7 +529,7 @@ func Test_migrateToAuthByTeamID(t *testing.T) { func Test_SetSelectedAuth(t *testing.T) { var setup = func(t *testing.T) (context.Context, *Client, *slackdeps.OsMock) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fsMock := slackdeps.NewFsMock() osMock := slackdeps.NewOsMock() osMock.AddDefaultMocks() @@ -567,7 +568,7 @@ func Test_SetSelectedAuth(t *testing.T) { func Test_IsApiHostSlackDev(t *testing.T) { var setup = func(t *testing.T) (context.Context, *Client) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fsMock := slackdeps.NewFsMock() osMock := slackdeps.NewOsMock() osMock.AddDefaultMocks() @@ -642,7 +643,7 @@ func Test_FilterKnownAuthErrors(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) os := slackdeps.NewOsMock() os.AddDefaultMocks() fs := slackdeps.NewFsMock() diff --git a/internal/auth/revoke_test.go b/internal/auth/revoke_test.go index 9c59c893..cf4ce603 100644 --- a/internal/auth/revoke_test.go +++ b/internal/auth/revoke_test.go @@ -15,7 +15,6 @@ package auth import ( - "context" "fmt" "testing" @@ -23,6 +22,7 @@ import ( "github.com/slackapi/slack-cli/internal/app" "github.com/slackapi/slack-cli/internal/config" "github.com/slackapi/slack-cli/internal/iostreams" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackdeps" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/stretchr/testify/assert" @@ -68,7 +68,7 @@ func Test_AuthRevokeToken(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) os := slackdeps.NewOsMock() os.AddDefaultMocks() fs := slackdeps.NewFsMock() diff --git a/internal/config/context.go b/internal/config/context.go index 29aca7a7..319c6e5e 100644 --- a/internal/config/context.go +++ b/internal/config/context.go @@ -16,42 +16,15 @@ package config import ( "context" - - "github.com/slackapi/slack-cli/internal/shared/types" ) type contextKey string -const CONTEXT_ENV contextKey = "env" const CONTEXT_TOKEN contextKey = "token" const CONTEXT_TEAM_ID contextKey = "team_id" const CONTEXT_TEAM_DOMAIN contextKey = "team_domain" // e.g. "subarachnoid" const CONTEXT_USER_ID contextKey = "user_id" -const CONTEXT_SESSION_ID contextKey = "session_id" const CONTEXT_ENTERPRISE_ID contextKey = "enterprise_id" -const CONTEXT_TRACE_ID contextKey = "trace_id" - -// SetContextApp sets the app on the context -// -// [LEGACY] Please do not use and prefer to -// directly pass the app to methods which require -// an app if possible. -func SetContextApp(ctx context.Context, app types.App) context.Context { - return context.WithValue(ctx, CONTEXT_ENV, app) -} - -// GetContextApp gets an app from the context -// -// [LEGACY] Please do not use and prefer to -// directly pass the app to methods which require -// an app if possible. -func GetContextApp(ctx context.Context) types.App { - app, ok := ctx.Value(CONTEXT_ENV).(types.App) - if !ok { - return types.App{} - } - return app -} func SetContextToken(ctx context.Context, token string) context.Context { return context.WithValue(ctx, CONTEXT_TOKEN, token) @@ -111,27 +84,3 @@ func GetContextUserID(ctx context.Context) string { } return userID } - -func GetContextSessionID(ctx context.Context) string { - sessionID, ok := ctx.Value(CONTEXT_SESSION_ID).(string) - if !ok { - return "" - } - return sessionID -} - -func SetContextSessionID(ctx context.Context, sessionID string) context.Context { - return context.WithValue(ctx, CONTEXT_SESSION_ID, sessionID) -} - -func SetContextTraceID(ctx context.Context, traceID string) context.Context { - return context.WithValue(ctx, CONTEXT_TRACE_ID, traceID) -} - -func GetContextTraceID(ctx context.Context) string { - traceID, ok := ctx.Value(CONTEXT_TRACE_ID).(string) - if !ok { - return "" - } - return traceID -} diff --git a/internal/contextutil/contextutil.go b/internal/contextutil/contextutil.go deleted file mode 100644 index f7d03ad7..00000000 --- a/internal/contextutil/contextutil.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2022-2025 Salesforce, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package contextutil - -import ( - "context" - - "github.com/opentracing/opentracing-go" -) - -type ctxKey string - -const ( - TracerCtxKey ctxKey = "__TRACER__" - SpanCtxKey ctxKey = "__SPAN__" - VersionCtxKey ctxKey = "__VERSION__" -) - -// AddTracerToContext adds the given tracer to request context -func AddTracerToContext(ctx context.Context, tracer opentracing.Tracer) context.Context { - return context.WithValue(ctx, TracerCtxKey, tracer) -} - -// AddVersionToContext adds the slack-cli version to request context -func AddVersionToContext(ctx context.Context, version string) context.Context { - return context.WithValue(ctx, VersionCtxKey, version) -} - -// AddSpanToContext adds the given span to request context -func AddSpanToContext(ctx context.Context, span opentracing.Span) context.Context { - return context.WithValue(ctx, SpanCtxKey, span) -} - -// VersionFromContext get the slack-cli version to request context -func VersionFromContext(ctx context.Context) string { - var version, ok = ctx.Value(VersionCtxKey).(string) - if !ok { - version = "" - } - return version -} diff --git a/internal/iostreams/logfile.go b/internal/iostreams/logfile.go index a24df6bc..44c2c4da 100644 --- a/internal/iostreams/logfile.go +++ b/internal/iostreams/logfile.go @@ -26,6 +26,7 @@ import ( "github.com/slackapi/slack-cli/internal/config" "github.com/slackapi/slack-cli/internal/goutils" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/slackapi/slack-cli/internal/style" ) @@ -62,12 +63,22 @@ func (io *IOStreams) InitLogFile(ctx context.Context) error { // Added line break for each session logger.Println("------------------------------------") + traceID, err := slackcontext.OpenTracingTraceID(ctx) + if err != nil { + return err + } + + sessionID, err := slackcontext.SessionID(ctx) + if err != nil { + return err + } + // Log the Slack-CLI version, User's OS, SessionID, TraceID // But format data before writing them to the log file formatAndWriteDataToLogFile(logger, map[string]string{ "Command": goutils.RedactPII(strings.Join(os.Args[0:], " ")), - "SessionID": config.GetContextSessionID(ctx), - "Slack-CLI-TraceID": config.GetContextTraceID(ctx), + "SessionID": sessionID, + "Slack-CLI-TraceID": traceID, "Slack-CLI Version": io.config.Version, "Operating System (OS)": runtime.GOOS, "System ID": io.config.SystemID, diff --git a/internal/slackcontext/slackcontext.go b/internal/slackcontext/slackcontext.go new file mode 100644 index 00000000..03086573 --- /dev/null +++ b/internal/slackcontext/slackcontext.go @@ -0,0 +1,176 @@ +// Copyright 2022-2025 Salesforce, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package slackcontext + +import ( + "context" + + "github.com/opentracing/opentracing-go" + "github.com/slackapi/slack-cli/internal/slackerror" +) + +// contextKey is an unexported type to avoid context key collisions. +// Learn more: https://github.com/golang/net/blob/236b8f043b920452504e263bc21d354427127473/context/context.go#L100 +type contextKey int + +const ( + contextKeyOpenTracingTraceID contextKey = iota + contextKeyOpenTracingTracer + contextKeyProjectID + contextKeySessionID + contextKeySystemID + contextKeyVersion +) + +// OpenTracingSpan returns the `opentracing.Span“ associated with `ctx`, or +// `nil` and `slackerror.ErrContextValueNotFound` if no `Span` could be found. +func OpenTracingSpan(ctx context.Context) (opentracing.Span, error) { + span := opentracing.SpanFromContext(ctx) + if span == nil { + return nil, slackerror.New(slackerror.ErrContextValueNotFound). + WithMessage("The value for OpenTracing Span could not be found") + } + return span, nil +} + +// SetOpenTracingSpan returns a new `context.Context` that holds a reference to +// the span. If span is nil, a new context without an active span is returned. +func SetOpenTracingSpan(ctx context.Context, span opentracing.Span) context.Context { + ctx = opentracing.ContextWithSpan(ctx, span) + return ctx +} + +// OpenTracingTraceID returns the trace ID associated with `ctx`, or +// `""` and `slackerror.ErrContextValueNotFound` if no trace ID could be found. +func OpenTracingTraceID(ctx context.Context) (string, error) { + traceID, ok := ctx.Value(contextKeyOpenTracingTraceID).(string) + if !ok || traceID == "" { + return "", slackerror.New(slackerror.ErrContextValueNotFound). + WithMessage("The value for OpenTracing Trace ID could not be found") + } + return traceID, nil +} + +// SetOpenTracingTraceID returns a new `context.Context` that holds a reference to +// the `traceID`. +func SetOpenTracingTraceID(ctx context.Context, traceID string) context.Context { + ctx = context.WithValue(ctx, contextKeyOpenTracingTraceID, traceID) + return ctx +} + +// OpenTracingTracer returns the `opentracing.Tracer` associated with `ctx`, or +// `nil` and `slackerror.ErrContextValueNotFound` if no `Tracer` could be found. +func OpenTracingTracer(ctx context.Context) (opentracing.Tracer, error) { + var tracer, ok = ctx.Value(contextKeyOpenTracingTracer).(opentracing.Tracer) + if !ok || tracer == nil { + return nil, slackerror.New(slackerror.ErrContextValueNotFound). + WithMessage("The value for OpenTracing Tracer could not be found") + } + return tracer, nil +} + +// SetOpenTracingSpan returns a new `context.Context` that holds a reference to +// the `opentracing.Tracer`. If tracer is nil, a new context without a tracer returned. +func SetOpenTracingTracer(ctx context.Context, tracer opentracing.Tracer) context.Context { + ctx = context.WithValue(ctx, contextKeyOpenTracingTracer, tracer) + return ctx +} + +// ProjectID returns the project ID associated with `ctx`, or +// `""` and `slackerror.ErrContextValueNotFound` if no project ID could be found. +func ProjectID(ctx context.Context) (string, error) { + var projectID, ok = ctx.Value(contextKeyProjectID).(string) + if !ok || projectID == "" { + return "", slackerror.New(slackerror.ErrContextValueNotFound). + WithMessage("The value for Project ID could not be found") + } + return projectID, nil +} + +// SetProjectID returns a new `context.Context` that holds a reference to +// the `projectID` and updates the `opentracing.Span` tag with the `projectID`. +func SetProjectID(ctx context.Context, projectID string) context.Context { + // Set projectID in the context + ctx = context.WithValue(ctx, contextKeyProjectID, projectID) + + // Set projectID in OpenTracing by extracting the span and updating the tag + if span := opentracing.SpanFromContext(ctx); span != nil { + span.SetTag("project_id", projectID) + ctx = opentracing.ContextWithSpan(ctx, span) + } + + return ctx +} + +// SessionID returns the session ID associated with `ctx`, or +// `""` and `slackerror.ErrContextValueNotFound` if no session ID could be found. +func SessionID(ctx context.Context) (string, error) { + sessionID, ok := ctx.Value(contextKeySessionID).(string) + if !ok || sessionID == "" { + return "", slackerror.New(slackerror.ErrContextValueNotFound). + WithMessage("The value for Session ID could not be found") + } + return sessionID, nil +} + +// SetSessionID returns a new `context.Context` that holds a reference to +// the `sessionID`. +func SetSessionID(ctx context.Context, sessionID string) context.Context { + ctx = context.WithValue(ctx, contextKeySessionID, sessionID) + return ctx +} + +// SystemID returns the session ID associated with `ctx`, or +// `""` and `slackerror.ErrContextValueNotFound` if no system ID could be found. +func SystemID(ctx context.Context) (string, error) { + var systemID, ok = ctx.Value(contextKeySystemID).(string) + if !ok || systemID == "" { + return "", slackerror.New(slackerror.ErrContextValueNotFound). + WithMessage("The value for System ID could not be found") + } + return systemID, nil +} + +// SetSystemID returns a new `context.Context` that holds a reference to +// the `systemID` and updates the `opentracing.Span` tag with the `systemID`. +func SetSystemID(ctx context.Context, systemID string) context.Context { + // Set systemID in the context + ctx = context.WithValue(ctx, contextKeySystemID, systemID) + + // Set projectID in OpenTracing by extracting the span and updating the tag + if span := opentracing.SpanFromContext(ctx); span != nil { + span.SetTag("system_id", systemID) + ctx = opentracing.ContextWithSpan(ctx, span) + } + + return ctx +} + +// Version returns the CLI version associated with `ctx`, or +// `""` and `slackerror.ErrContextValueNotFound` if no version could be found. +func Version(ctx context.Context) (string, error) { + var version, ok = ctx.Value(contextKeyVersion).(string) + if !ok || version == "" { + return "", slackerror.New(slackerror.ErrContextValueNotFound). + WithMessage("The value for Version could not be found") + } + return version, nil +} + +// SetVersion adds the slack-cli version to Golang context for trace logging +func SetVersion(ctx context.Context, version string) context.Context { + ctx = context.WithValue(ctx, contextKeyVersion, version) + return ctx +} diff --git a/internal/slackcontext/slackcontext_mock.go b/internal/slackcontext/slackcontext_mock.go new file mode 100644 index 00000000..053d596d --- /dev/null +++ b/internal/slackcontext/slackcontext_mock.go @@ -0,0 +1,34 @@ +// Copyright 2022-2025 Salesforce, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package slackcontext + +import ( + "context" + + "github.com/google/uuid" +) + +const ( + mockCLIVersion = "v1.2.3" +) + +// MockContext sets values in the context that are guaranteed to exist before +// the Cobra root command is executed. +func MockContext(ctx context.Context) context.Context { + ctx = SetOpenTracingTraceID(ctx, uuid.New().String()) + ctx = SetSessionID(ctx, uuid.New().String()) + ctx = SetVersion(ctx, mockCLIVersion) + return ctx +} diff --git a/internal/slackcontext/slackcontext_test.go b/internal/slackcontext/slackcontext_test.go new file mode 100644 index 00000000..d701d83e --- /dev/null +++ b/internal/slackcontext/slackcontext_test.go @@ -0,0 +1,331 @@ +// Copyright 2022-2025 Salesforce, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package slackcontext + +import ( + "context" + "testing" + + "github.com/google/uuid" + "github.com/opentracing/opentracing-go" + "github.com/slackapi/slack-cli/internal/slackerror" + "github.com/slackapi/slack-cli/internal/tracer" + "github.com/stretchr/testify/require" +) + +func Test_SlackContext_OpenTracingSpan(t *testing.T) { + tests := map[string]struct { + expectedSpan opentracing.Span + expectedError error + }{ + "returns span when span exists": { + expectedSpan: opentracing.StartSpan("test.span"), + expectedError: nil, + }, + "returns error when span not found": { + expectedSpan: nil, + expectedError: slackerror.New(slackerror.ErrContextValueNotFound).WithMessage("The value for OpenTracing Span could not be found"), + }, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + ctx := context.Background() + ctx = opentracing.ContextWithSpan(ctx, tt.expectedSpan) + actualSpan, actualError := OpenTracingSpan(ctx) + require.Equal(t, tt.expectedSpan, actualSpan) + require.Equal(t, tt.expectedError, actualError) + }) + } +} + +func Test_SlackContext_SetOpenTracingSpan(t *testing.T) { + tests := map[string]struct { + expectedSpan opentracing.Span + }{ + "sets the span in the context": { + expectedSpan: opentracing.StartSpan("test.span"), + }, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + ctx := context.Background() + ctx = SetOpenTracingSpan(ctx, tt.expectedSpan) + actualSpan := opentracing.SpanFromContext(ctx) + require.Equal(t, tt.expectedSpan, actualSpan) + }) + } +} + +func Test_SlackContext_OpenTracingTraceID(t *testing.T) { + tests := map[string]struct { + expectedTraceID string + expectedError error + }{ + "returns Trace ID when it exists": { + expectedTraceID: uuid.New().String(), + expectedError: nil, + }, + "returns error when Trace ID not found": { + expectedTraceID: "", + expectedError: slackerror.New(slackerror.ErrContextValueNotFound).WithMessage("The value for OpenTracing Trace ID could not be found"), + }, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + ctx := context.Background() + ctx = context.WithValue(ctx, contextKeyOpenTracingTraceID, tt.expectedTraceID) + actualTraceID, actualError := OpenTracingTraceID(ctx) + require.Equal(t, tt.expectedTraceID, actualTraceID) + require.Equal(t, tt.expectedError, actualError) + }) + } +} + +func Test_SlackContext_SetOpenTracingTraceID(t *testing.T) { + tests := map[string]struct { + expectedTraceID string + }{ + "sets the Trace ID in the context": { + expectedTraceID: uuid.New().String(), + }, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + ctx := context.Background() + ctx = SetOpenTracingTraceID(ctx, tt.expectedTraceID) + actualTraceID := ctx.Value(contextKeyOpenTracingTraceID).(string) + require.Equal(t, tt.expectedTraceID, actualTraceID) + }) + } +} + +func Test_SlackContext_OpenTracingTracer(t *testing.T) { + _, _tracer := tracer.SetupTracer(true) + + tests := map[string]struct { + expectedTracer opentracing.Tracer + expectedError error + }{ + "returns Tracer when it exists": { + expectedTracer: _tracer, + expectedError: nil, + }, + "returns error when Tracer not found": { + expectedTracer: nil, + expectedError: slackerror.New(slackerror.ErrContextValueNotFound).WithMessage("The value for OpenTracing Tracer could not be found"), + }, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + ctx := context.Background() + ctx = context.WithValue(ctx, contextKeyOpenTracingTracer, tt.expectedTracer) + actualTracer, actualError := OpenTracingTracer(ctx) + require.Equal(t, tt.expectedTracer, actualTracer) + require.Equal(t, tt.expectedError, actualError) + }) + } +} + +func Test_SlackContext_SetOpenTracingTracer(t *testing.T) { + _, _tracer := tracer.SetupTracer(true) + + tests := map[string]struct { + expectedTracer opentracing.Tracer + }{ + "sets the Tracer in the context": { + expectedTracer: _tracer, + }, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + ctx := context.Background() + ctx = SetOpenTracingTracer(ctx, tt.expectedTracer) + actualTracer := ctx.Value(contextKeyOpenTracingTracer).(opentracing.Tracer) + require.Equal(t, tt.expectedTracer, actualTracer) + }) + } +} + +func Test_SlackContext_ProjectID(t *testing.T) { + tests := map[string]struct { + expectedProjectID string + expectedError error + }{ + "returns Project ID when it exists": { + expectedProjectID: uuid.New().String(), + expectedError: nil, + }, + "returns error when Project ID not found": { + expectedProjectID: "", + expectedError: slackerror.New(slackerror.ErrContextValueNotFound).WithMessage("The value for Project ID could not be found"), + }, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + ctx := context.Background() + ctx = context.WithValue(ctx, contextKeyProjectID, tt.expectedProjectID) + actualProjectID, actualError := ProjectID(ctx) + require.Equal(t, tt.expectedProjectID, actualProjectID) + require.Equal(t, tt.expectedError, actualError) + }) + } +} + +func Test_SlackContext_SetProjectID(t *testing.T) { + tests := map[string]struct { + expectedProjectID string + }{ + "sets the Project ID in the context": { + expectedProjectID: uuid.New().String(), + }, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + ctx := context.Background() + ctx = SetProjectID(ctx, tt.expectedProjectID) + actualProjectID := ctx.Value(contextKeyProjectID).(string) + require.Equal(t, tt.expectedProjectID, actualProjectID) + }) + } +} + +func Test_SlackContext_SessionID(t *testing.T) { + tests := map[string]struct { + expectedSessionID string + expectedError error + }{ + "returns Session ID when it exists": { + expectedSessionID: uuid.New().String(), + expectedError: nil, + }, + "returns error when Session ID not found": { + expectedSessionID: "", + expectedError: slackerror.New(slackerror.ErrContextValueNotFound).WithMessage("The value for Session ID could not be found"), + }, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + ctx := context.Background() + ctx = context.WithValue(ctx, contextKeySessionID, tt.expectedSessionID) + actualSessionID, actualError := SessionID(ctx) + require.Equal(t, tt.expectedSessionID, actualSessionID) + require.Equal(t, tt.expectedError, actualError) + }) + } +} + +func Test_SlackContext_SetSessionID(t *testing.T) { + tests := map[string]struct { + expectedSessionID string + }{ + "sets the Session ID in the context": { + expectedSessionID: uuid.New().String(), + }, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + ctx := context.Background() + ctx = SetSessionID(ctx, tt.expectedSessionID) + actualSessionID := ctx.Value(contextKeySessionID).(string) + require.Equal(t, tt.expectedSessionID, actualSessionID) + }) + } +} + +func Test_SlackContext_SystemID(t *testing.T) { + tests := map[string]struct { + expectedSystemID string + expectedError error + }{ + "returns System ID when it exists": { + expectedSystemID: uuid.New().String(), + expectedError: nil, + }, + "returns error when System ID not found": { + expectedSystemID: "", + expectedError: slackerror.New(slackerror.ErrContextValueNotFound).WithMessage("The value for System ID could not be found"), + }, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + ctx := context.Background() + ctx = context.WithValue(ctx, contextKeySystemID, tt.expectedSystemID) + actualSystemID, actualError := SystemID(ctx) + require.Equal(t, tt.expectedSystemID, actualSystemID) + require.Equal(t, tt.expectedError, actualError) + }) + } +} + +func Test_SlackContext_SetSystemID(t *testing.T) { + tests := map[string]struct { + expectedSystemID string + }{ + "sets the System ID in the context": { + expectedSystemID: uuid.New().String(), + }, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + ctx := context.Background() + ctx = SetSystemID(ctx, tt.expectedSystemID) + actualSystemID := ctx.Value(contextKeySystemID).(string) + require.Equal(t, tt.expectedSystemID, actualSystemID) + }) + } +} + +func Test_SlackContext_Version(t *testing.T) { + tests := map[string]struct { + expectedVersion string + expectedError error + }{ + "returns Version when it exists": { + expectedVersion: "v1.2.3", + expectedError: nil, + }, + "returns error when Version not found": { + expectedVersion: "", + expectedError: slackerror.New(slackerror.ErrContextValueNotFound).WithMessage("The value for Version could not be found"), + }, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + ctx := context.Background() + ctx = context.WithValue(ctx, contextKeyVersion, tt.expectedVersion) + actualVersion, actualError := Version(ctx) + require.Equal(t, tt.expectedVersion, actualVersion) + require.Equal(t, tt.expectedError, actualError) + }) + } +} + +func Test_SlackContext_SetVersion(t *testing.T) { + tests := map[string]struct { + expectedVersion string + }{ + "sets the Version in the context": { + expectedVersion: "v1.2.3", + }, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + ctx := context.Background() + ctx = SetVersion(ctx, tt.expectedVersion) + actualVersion := ctx.Value(contextKeyVersion).(string) + require.Equal(t, tt.expectedVersion, actualVersion) + }) + } +} diff --git a/internal/slackerror/errors.go b/internal/slackerror/errors.go index 50fee84e..db19d0f4 100644 --- a/internal/slackerror/errors.go +++ b/internal/slackerror/errors.go @@ -81,6 +81,7 @@ const ( ErrCommentRequired = "comment_required" ErrConnectedOrgDenied = "connected_org_denied" ErrConnectedTeamDenied = "connected_team_denied" + ErrContextValueNotFound = "context_value_not_found" ErrCredentialsNotFound = "credentials_not_found" ErrCustomizableInputMissingMatchingWorkflowInput = "customizable_input_missing_matching_workflow_input" ErrCustomizableInputsNotAllowedOnOptionalInputs = "customizable_inputs_not_allowed_on_optional_inputs" @@ -595,6 +596,11 @@ Otherwise start your app for local development with: %s`, Message: "The admin does not allow connected teams to be named_entities", }, + ErrContextValueNotFound: { + Code: ErrContextValueNotFound, + Message: "The context value could not be found", + }, + ErrCredentialsNotFound: { Code: ErrCredentialsNotFound, Message: "No authentication found for this team", @@ -806,13 +812,9 @@ Otherwise start your app for local development with: %s`, }, ErrInvalidAppDirectory: { - Code: ErrInvalidAppDirectory, - Message: "This is an invalid Slack app project directory", - Remediation: strings.Join([]string{ - fmt.Sprintf("A valid Slack project includes the Slack hooks file: %s", filepath.Join(".slack", "hooks.json")), - "", - "If this is a Slack project, you can initialize it with " + style.Commandf("init", false), - }, "\n"), + Code: ErrInvalidAppDirectory, + Message: "This is an invalid Slack app project directory", + Remediation: fmt.Sprintf("A valid Slack project includes the Slack hooks file: %s", filepath.Join(".slack", "hooks.json")), }, ErrInvalidAppFlag: { @@ -1296,16 +1298,12 @@ Otherwise start your app for local development with: %s`, Code: ErrSDKHookNotFound, Message: fmt.Sprintf("A script in %s was not found", style.Highlight(filepath.Join(".slack", "hooks.json"))), Remediation: strings.Join([]string{ - "Hook scripts are defined in one of these Slack hooks files:", - "- slack.json", - "- " + filepath.Join(".slack", "hooks.json"), - "", - "Every app requires a Slack hooks file and you can find an example at:", - style.Highlight("https://github.com/slack-samples/deno-starter-template/blob/main/slack.json"), + fmt.Sprintf("Hook scripts are defined in the Slack hooks file ('%s').", filepath.Join(".slack", "hooks.json")), + "Every app requires a Slack hooks file and you can find a working example at:", "", - "You can create a hooks file manually or with the " + style.Commandf("init", false) + " command.", + style.Highlight("https://github.com/slack-samples/deno-starter-template/blob/main/.slack/hooks.json"), "", - "When manually creating the hooks file, you must install the hook dependencies.", + "After creating the hooks file, you must install related hook dependencies.", }, "\n"), }, diff --git a/internal/tracking/tracking.go b/internal/tracking/tracking.go index d9ec7d0b..b393d5b2 100644 --- a/internal/tracking/tracking.go +++ b/internal/tracking/tracking.go @@ -30,6 +30,7 @@ import ( "github.com/slackapi/slack-cli/internal/goutils" "github.com/slackapi/slack-cli/internal/iostreams" "github.com/slackapi/slack-cli/internal/ioutils" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/style" ) @@ -169,7 +170,11 @@ func (e *EventTracker) FlushToLogstash(ctx context.Context, cfg *config.Config, } versionString, _ := strings.CutPrefix(cfg.Version, "v") eventData := e.cleanSessionData(e.getSessionData()) - sessionID := config.GetContextSessionID(ctx) + sessionID, err := slackcontext.SessionID(ctx) + if err != nil { + return err + } + var eventName EventType switch exitCode { case iostreams.ExitCancel: diff --git a/internal/tracking/tracking_test.go b/internal/tracking/tracking_test.go index c5fbd549..865a3312 100644 --- a/internal/tracking/tracking_test.go +++ b/internal/tracking/tracking_test.go @@ -15,7 +15,6 @@ package tracking import ( - "context" "fmt" "io" "net/http" @@ -24,6 +23,7 @@ import ( "github.com/slackapi/slack-cli/internal/config" "github.com/slackapi/slack-cli/internal/iostreams" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackdeps" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -140,6 +140,7 @@ func Test_Tracking_FlushToLogstash(t *testing.T) { for name, tt := range tests { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) et := NewEventTracker() var requestSent = false testServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { @@ -161,7 +162,7 @@ func Test_Tracking_FlushToLogstash(t *testing.T) { } ioMock := iostreams.NewIOStreamsMock(cfg, fs, os) ioMock.AddDefaultMocks() - err := et.FlushToLogstash(context.Background(), cfg, ioMock, tt.exitCode) + err := et.FlushToLogstash(ctx, cfg, ioMock, tt.exitCode) require.NoError(t, err) if tt.shouldNotSendRequest && requestSent { require.Fail(t, "Expected no event tracking request to be sent, but request was sent") diff --git a/main.go b/main.go index 3db3fcd8..de3cf3ec 100644 --- a/main.go +++ b/main.go @@ -23,13 +23,12 @@ import ( "github.com/google/uuid" "github.com/opentracing/opentracing-go" "github.com/slackapi/slack-cli/cmd" - "github.com/slackapi/slack-cli/internal/config" - "github.com/slackapi/slack-cli/internal/contextutil" "github.com/slackapi/slack-cli/internal/goutils" "github.com/slackapi/slack-cli/internal/iostreams" "github.com/slackapi/slack-cli/internal/ioutils" "github.com/slackapi/slack-cli/internal/pkg/version" "github.com/slackapi/slack-cli/internal/shared" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/tracer" "github.com/uber/jaeger-client-go" ) @@ -37,49 +36,55 @@ import ( func main() { defer recoveryFunc() + // Create the parent context for the CLI execution var ctx = context.Background() + // TODO - Could we refactor this to cmd/root.go to initialize open tracing after the CLI flags are parsed? // - This would allow us to choose the correct API host based on flags // - Uncomment `isDevTarget` if we refactor to cmd/root.go and update to call `ResolveApiHost` // var isDevTarget = shared.NewClientFactory().AuthClient().UserDefaultAuthIsProd(ctx) // TODO - hack, remove shared.clients var jaegerCloser, tracer = tracer.SetupTracer(false) // Always setup open tracing on prod - ctx = contextutil.AddTracerToContext(ctx, tracer) defer jaegerCloser.Close() + ctx = slackcontext.SetOpenTracingTracer(ctx, tracer) - // set various metrics we will be tracking on the context - ctx = config.SetContextSessionID(ctx, uuid.New().String()) - // add slack-cli version to context - ctx = contextutil.AddVersionToContext(ctx, version.Get()) + // Set context values + sessionID := uuid.New().String() + cliVersion := version.Get() + ctx = slackcontext.SetSessionID(ctx, sessionID) + ctx = slackcontext.SetVersion(ctx, cliVersion) osStr := os.Args[0:] processName := goutils.RedactPII(strings.Join(osStr, " ")) - var span = tracer.StartSpan("main", opentracing.Tag{Key: "version", Value: version.Get()}) - span.SetTag("slack_cli_sessionID", config.GetContextSessionID(ctx)) + var span = tracer.StartSpan("main", opentracing.Tag{Key: "version", Value: cliVersion}) + span.SetTag("slack_cli_sessionID", sessionID) span.SetTag("hashed_hostname", ioutils.GetHostname()) span.SetTag("slack_cli_process", processName) // system_id is set in root.go initConfig() // project_id is set in root.go initConfig() if jaegerSpanContext, ok := span.Context().(jaeger.SpanContext); ok { - ctx = config.SetContextTraceID(ctx, jaegerSpanContext.TraceID().String()) + ctx = slackcontext.SetOpenTracingTraceID(ctx, jaegerSpanContext.TraceID().String()) } defer span.Finish() // add root span to context - ctx = opentracing.ContextWithSpan(ctx, span) + ctx = slackcontext.SetOpenTracingSpan(ctx, span) rootCmd, clients := cmd.Init() cmd.Execute(ctx, rootCmd, clients) } +// TODO(slackcontext) Use closure to pass in the ctx, which includes the sessionID func recoveryFunc() { // in the event of a panic, log panic if r := recover(); r != nil { var clients = shared.NewClientFactory(shared.SetVersion(version.Raw())) + var ctx = context.Background() - ctx = config.SetContextSessionID(ctx, uuid.New().String()) + ctx = slackcontext.SetSessionID(ctx, uuid.New().String()) + // set host for logging clients.Config.LogstashHostResolved = clients.AuthInterface().ResolveLogstashHost(ctx, clients.Config.ApiHostResolved, clients.Config.Version) clients.IO.PrintError(ctx, "Recovered from panic: %s\n%s", r, string(debug.Stack())) From 6c8907a0e1c0931c4eb846397eaf6a51d9544c67 Mon Sep 17 00:00:00 2001 From: Michael Brooks Date: Wed, 2 Apr 2025 14:12:58 -0700 Subject: [PATCH 02/13] refactor: Revert changes to unrelated error codes --- internal/slackerror/errors.go | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/internal/slackerror/errors.go b/internal/slackerror/errors.go index db19d0f4..8fb060ca 100644 --- a/internal/slackerror/errors.go +++ b/internal/slackerror/errors.go @@ -812,9 +812,13 @@ Otherwise start your app for local development with: %s`, }, ErrInvalidAppDirectory: { - Code: ErrInvalidAppDirectory, - Message: "This is an invalid Slack app project directory", - Remediation: fmt.Sprintf("A valid Slack project includes the Slack hooks file: %s", filepath.Join(".slack", "hooks.json")), + Code: ErrInvalidAppDirectory, + Message: "This is an invalid Slack app project directory", + Remediation: strings.Join([]string{ + fmt.Sprintf("A valid Slack project includes the Slack hooks file: %s", filepath.Join(".slack", "hooks.json")), + "", + "If this is a Slack project, you can initialize it with " + style.Commandf("init", false), + }, "\n"), }, ErrInvalidAppFlag: { @@ -1298,12 +1302,16 @@ Otherwise start your app for local development with: %s`, Code: ErrSDKHookNotFound, Message: fmt.Sprintf("A script in %s was not found", style.Highlight(filepath.Join(".slack", "hooks.json"))), Remediation: strings.Join([]string{ - fmt.Sprintf("Hook scripts are defined in the Slack hooks file ('%s').", filepath.Join(".slack", "hooks.json")), - "Every app requires a Slack hooks file and you can find a working example at:", + "Hook scripts are defined in one of these Slack hooks files:", + "- slack.json", + "- " + filepath.Join(".slack", "hooks.json"), + "", + "Every app requires a Slack hooks file and you can find an example at:", + style.Highlight("https://github.com/slack-samples/deno-starter-template/blob/main/slack.json"), "", - style.Highlight("https://github.com/slack-samples/deno-starter-template/blob/main/.slack/hooks.json"), + "You can create a hooks file manually or with the " + style.Commandf("init", false) + " command.", "", - "After creating the hooks file, you must install related hook dependencies.", + "When manually creating the hooks file, you must install the hook dependencies.", }, "\n"), }, From f7b90149d407c8145d53aa41823070bd1b814c8f Mon Sep 17 00:00:00 2001 From: Michael Brooks Date: Mon, 7 Apr 2025 16:18:46 -0600 Subject: [PATCH 03/13] test: mock context in TableTestCommand --- cmd/app/add_test.go | 22 ++++++++---------- cmd/app/delete_test.go | 9 ++++---- cmd/app/link_test.go | 19 +++++++--------- cmd/app/uninstall_test.go | 8 +++---- cmd/auth/login_test.go | 11 +++++---- cmd/auth/logout_test.go | 19 ++++++++-------- cmd/auth/revoke_test.go | 9 ++++---- cmd/collaborators/add_test.go | 6 ++--- cmd/collaborators/remove_test.go | 7 +++--- cmd/collaborators/update_test.go | 8 +++---- cmd/datastore/bulk_put_test.go | 8 +++---- cmd/datastore/count_test.go | 13 ++++++----- cmd/datastore/query_test.go | 4 ++-- cmd/docgen/docgen_test.go | 13 ++++++----- cmd/env/add_test.go | 8 +++---- cmd/env/list_test.go | 3 ++- cmd/env/remove_test.go | 7 +++--- cmd/externalauth/add_secret_test.go | 10 ++++---- cmd/externalauth/add_test.go | 10 ++++---- cmd/externalauth/remove_test.go | 10 ++++---- cmd/externalauth/select_auth_test.go | 27 +++++++++++----------- cmd/function/access_test.go | 10 ++++---- cmd/manifest/info_test.go | 14 +++++------- cmd/manifest/manifest_test.go | 3 ++- cmd/openformresponse/export_test.go | 7 +++--- cmd/project/init_test.go | 6 ++--- cmd/project/samples_test.go | 2 +- cmd/triggers/access_test.go | 34 ++++++++++++++-------------- cmd/triggers/create_test.go | 30 ++++++++++++------------ cmd/triggers/delete_test.go | 14 ++++++------ cmd/triggers/info_test.go | 18 +++++++-------- cmd/triggers/list_test.go | 9 ++++---- cmd/triggers/update_test.go | 28 +++++++++++------------ test/testutil/commandtests.go | 23 +++++++++++-------- 34 files changed, 219 insertions(+), 210 deletions(-) diff --git a/cmd/app/add_test.go b/cmd/app/add_test.go index 4945057c..678a9208 100644 --- a/cmd/app/add_test.go +++ b/cmd/app/add_test.go @@ -76,12 +76,12 @@ func TestAppAddCommandPreRun(t *testing.T) { testutil.TableTestCommand(t, testutil.CommandTests{ "errors if not run in a project directory": { ExpectedError: slackerror.New(slackerror.ErrInvalidAppDirectory), - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { }, }, "proceeds if run in a project directory": { ExpectedError: nil, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cf.SDKConfig.WorkingDirectory = "." }, }, @@ -100,8 +100,7 @@ func TestAppAddCommandPreRun(t *testing.T) { Message: "Cannot install apps with manifests sourced from app settings", }, }), - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { - ctx := context.Background() + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cf.SDKConfig.WorkingDirectory = "." cm.AddDefaultMocks() cm.Config.ExperimentsFlag = append(cm.Config.ExperimentsFlag, experiment.BoltFrameworks) @@ -113,8 +112,7 @@ func TestAppAddCommandPreRun(t *testing.T) { }, "proceeds if manifest.source is local with the bolt experiment": { ExpectedError: nil, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { - ctx := context.Background() + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cf.SDKConfig.WorkingDirectory = "." cm.AddDefaultMocks() cm.Config.ExperimentsFlag = append(cm.Config.ExperimentsFlag, experiment.BoltFrameworks) @@ -137,7 +135,7 @@ func TestAppAddCommand(t *testing.T) { "adds a new deployed app": { CmdArgs: []string{}, ExpectedOutputs: []string{"Creating app manifest", "Installing"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { prepareAddMocks(t, cf, cm) // Mock TeamSelector prompt to return "team1" @@ -209,7 +207,7 @@ func TestAppAddCommand(t *testing.T) { "updates an existing deployed app": { CmdArgs: []string{}, ExpectedOutputs: []string{"Updated app manifest"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { prepareAddMocks(t, cf, cm) // Mock TeamSelector prompt to return "team1" @@ -291,7 +289,7 @@ func TestAppAddCommand(t *testing.T) { "errors if authentication for the team is missing": { CmdArgs: []string{}, ExpectedError: slackerror.New(slackerror.ErrCredentialsNotFound), - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { prepareAddMocks(t, cf, cm) appSelectMock := prompts.NewAppSelectMock() teamAppSelectPromptFunc = appSelectMock.TeamAppSelectPrompt @@ -301,7 +299,7 @@ func TestAppAddCommand(t *testing.T) { "adds a new deployed app to an org with a workspace grant": { CmdArgs: []string{"--" + cmdutil.OrgGrantWorkspaceFlag, "T123"}, ExpectedOutputs: []string{"Creating app manifest", "Installing"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { prepareAddMocks(t, cf, cm) // Select workspace appSelectMock := prompts.NewAppSelectMock() @@ -361,7 +359,7 @@ func TestAppAddCommand(t *testing.T) { "When admin approval request is pending, outputs instructions": { CmdArgs: []string{"--" + cmdutil.OrgGrantWorkspaceFlag, "T123"}, ExpectedOutputs: []string{"Creating app manifest", "Installing", "Your request to install the app is pending", "complete installation by re-running"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { prepareAddMocks(t, cf, cm) // Select workspace appSelectMock := prompts.NewAppSelectMock() @@ -417,7 +415,7 @@ func TestAppAddCommand(t *testing.T) { "When admin approval request is cancelled, outputs instructions": { CmdArgs: []string{"--" + cmdutil.OrgGrantWorkspaceFlag, "T123"}, ExpectedOutputs: []string{"Creating app manifest", "Installing", "Your request to install the app has been cancelled"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { prepareAddMocks(t, cf, cm) // Select workspace appSelectMock := prompts.NewAppSelectMock() diff --git a/cmd/app/delete_test.go b/cmd/app/delete_test.go index a7015ce5..1d962c27 100644 --- a/cmd/app/delete_test.go +++ b/cmd/app/delete_test.go @@ -15,6 +15,7 @@ package app import ( + "context" "fmt" "testing" @@ -49,7 +50,7 @@ func TestAppsDeleteCommand(t *testing.T) { testutil.TableTestCommand(t, testutil.CommandTests{ "happy path; delete the deployed app": { CmdArgs: []string{}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { prepareCommonDeleteMocks(t, cf, cm) // Mock App Selection appSelectMock := prompts.NewAppSelectMock() @@ -83,7 +84,7 @@ func TestAppsDeleteCommand(t *testing.T) { }, "happy path; delete the local app": { CmdArgs: []string{}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { prepareCommonDeleteMocks(t, cf, cm) // Mock App Selection appSelectMock := prompts.NewAppSelectMock() @@ -116,7 +117,7 @@ func TestAppsDeleteCommand(t *testing.T) { }, "sad path; deleting the deployed app fails": { CmdArgs: []string{}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { prepareCommonDeleteMocks(t, cf, cm) // Mock App Selection appSelectMock := prompts.NewAppSelectMock() @@ -143,7 +144,7 @@ func TestAppsDeleteCommand(t *testing.T) { "errors if authentication for the team is missing": { CmdArgs: []string{}, ExpectedError: slackerror.New(slackerror.ErrCredentialsNotFound), - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { prepareCommonDeleteMocks(t, cf, cm) cm.ApiInterface.On("ValidateSession", mock.Anything, mock.Anything).Return(api.AuthSession{}, nil) appSelectMock := prompts.NewAppSelectMock() diff --git a/cmd/app/link_test.go b/cmd/app/link_test.go index 6224b0ad..b2fd09f4 100644 --- a/cmd/app/link_test.go +++ b/cmd/app/link_test.go @@ -54,7 +54,7 @@ var mockLinkSlackAuth2 = types.SlackAuth{ func Test_Apps_Link(t *testing.T) { testutil.TableTestCommand(t, testutil.CommandTests{ "saves information about the provided deployed app": { - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.AuthInterface.On("Auths", mock.Anything).Return([]types.SlackAuth{ mockLinkSlackAuth2, mockLinkSlackAuth1, @@ -111,7 +111,7 @@ func Test_Apps_Link(t *testing.T) { }, }, "saves information about the provided local app": { - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.AuthInterface.On("Auths", mock.Anything).Return([]types.SlackAuth{ mockLinkSlackAuth2, mockLinkSlackAuth1, @@ -170,8 +170,7 @@ func Test_Apps_Link(t *testing.T) { }, }, "avoids overwriting an app saved in json without confirmation": { - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { - ctx := context.Background() + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.AuthInterface.On("Auths", mock.Anything).Return([]types.SlackAuth{ mockLinkSlackAuth1, mockLinkSlackAuth2, @@ -240,8 +239,7 @@ func Test_Apps_Link(t *testing.T) { WithRemediation("Remove the app from this project or try again with --force"), }, "avoids overwriting a matching app id for the team without confirmation": { - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { - ctx := context.Background() + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.AuthInterface.On("Auths", mock.Anything).Return([]types.SlackAuth{ mockLinkSlackAuth1, mockLinkSlackAuth2, @@ -316,8 +314,7 @@ func Test_Apps_Link(t *testing.T) { WithRemediation("Remove the app from this project or try again with --force"), }, "completes overwriting an app saved in json with confirmation": { - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { - ctx := context.Background() + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.AuthInterface.On("Auths", mock.Anything).Return([]types.SlackAuth{ mockLinkSlackAuth1, mockLinkSlackAuth2, @@ -385,7 +382,7 @@ func Test_Apps_Link(t *testing.T) { }, }, "refuses to write an app with app id not existing upstream": { - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.AuthInterface.On("Auths", mock.Anything).Return([]types.SlackAuth{ mockLinkSlackAuth1, mockLinkSlackAuth2, @@ -433,7 +430,7 @@ func Test_Apps_Link(t *testing.T) { ExpectedError: slackerror.New(slackerror.ErrAppNotFound), }, "accept manifest source prompt and saves information about the provided deployed app": { - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.AuthInterface.On("Auths", mock.Anything).Return([]types.SlackAuth{ mockLinkSlackAuth2, mockLinkSlackAuth1, @@ -506,7 +503,7 @@ func Test_Apps_Link(t *testing.T) { }, }, "decline manifest source prompt should not link app": { - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.AddDefaultMocks() setupAppLinkCommandMocks(t, cm, cf) // Set manifest source to project to trigger confirmation prompt diff --git a/cmd/app/uninstall_test.go b/cmd/app/uninstall_test.go index 64eb27c6..aeb1181e 100644 --- a/cmd/app/uninstall_test.go +++ b/cmd/app/uninstall_test.go @@ -47,7 +47,7 @@ func TestAppsUninstall(t *testing.T) { testutil.TableTestCommand(t, testutil.CommandTests{ "Successfully uninstall": { - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { prepareCommonUninstallMocks(clients, clientsMock) clientsMock.ApiInterface.On("UninstallApp", mock.Anything, mock.Anything, fakeAppID, fakeAppTeamID). Return(nil).Once() @@ -57,7 +57,7 @@ func TestAppsUninstall(t *testing.T) { }, }, "Successfully uninstall with a get-manifest hook error": { - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { prepareCommonUninstallMocks(clients, clientsMock) clientsMock.ApiInterface.On("UninstallApp", mock.Anything, mock.Anything, fakeAppID, fakeAppTeamID). Return(nil).Once() @@ -72,7 +72,7 @@ func TestAppsUninstall(t *testing.T) { }, "Fail to uninstall due to API error": { ExpectedError: slackerror.New("something went wrong"), - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { prepareCommonUninstallMocks(clients, clientsMock) clientsMock.ApiInterface.On("UninstallApp", mock.Anything, mock.Anything, fakeAppID, fakeAppTeamID). Return(slackerror.New("something went wrong")).Once() @@ -81,7 +81,7 @@ func TestAppsUninstall(t *testing.T) { "errors if authentication for the team is missing": { CmdArgs: []string{}, ExpectedError: slackerror.New(slackerror.ErrCredentialsNotFound), - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { prepareCommonUninstallMocks(cf, cm) appSelectMock := prompts.NewAppSelectMock() uninstallAppSelectPromptFunc = appSelectMock.AppSelectPrompt diff --git a/cmd/auth/login_test.go b/cmd/auth/login_test.go index 33fec190..968e83b5 100644 --- a/cmd/auth/login_test.go +++ b/cmd/auth/login_test.go @@ -15,6 +15,7 @@ package auth import ( + "context" "testing" "github.com/slackapi/slack-cli/internal/api" @@ -52,7 +53,7 @@ func TestLoginCommmand(t *testing.T) { "deprecated auth flag is noted in outputs": { CmdArgs: []string{"--auth", "xoxp-example"}, ExpectedOutputs: []string{deprecatedUserTokenMessage}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.ApiInterface.On("ValidateSession", mock.Anything, mock.Anything).Return(api.AuthSession{ UserID: &mockOrgAuth.UserID, TeamID: &mockOrgAuth.TeamID, @@ -79,7 +80,7 @@ func TestLoginCommmand(t *testing.T) { "suggests creating a new app if not in a project": { CmdArgs: []string{"--ticket=example", "--challenge=tictactoe"}, ExpectedStdoutOutputs: []string{"Get started by creating a new app"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.ApiInterface.On( "ExchangeAuthTicket", mock.Anything, @@ -109,7 +110,7 @@ func TestLoginCommmand(t *testing.T) { "suggests listing existing apps from the project": { CmdArgs: []string{"--ticket", "example", "--challenge", "tictactoe"}, ExpectedStdoutOutputs: []string{"Review existing installations of the app"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.ApiInterface.On( "ExchangeAuthTicket", mock.Anything, @@ -139,7 +140,7 @@ func TestLoginCommmand(t *testing.T) { }, "happy path login with prompt flow should pass challenge code to ExchangeAuthTicket API": { CmdArgs: []string{}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.ApiInterface.On("GenerateAuthTicket", mock.Anything, mock.Anything, mock.Anything).Return(api.GenerateAuthTicketResult{}, nil) cm.IO.On("InputPrompt", mock.Anything, "Enter challenge code", iostreams.InputPromptConfig{ Required: true, @@ -162,7 +163,7 @@ func TestLoginCommmand(t *testing.T) { }, "should explode if ExchangeAuthTicket API fails": { CmdArgs: []string{}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.ApiInterface.On("GenerateAuthTicket", mock.Anything, mock.Anything, mock.Anything).Return(api.GenerateAuthTicketResult{}, nil) cm.IO.On("InputPrompt", mock.Anything, "Enter challenge code", iostreams.InputPromptConfig{ Required: true, diff --git a/cmd/auth/logout_test.go b/cmd/auth/logout_test.go index fa9c37a8..445f75ab 100644 --- a/cmd/auth/logout_test.go +++ b/cmd/auth/logout_test.go @@ -15,6 +15,7 @@ package auth import ( + "context" "testing" "github.com/slackapi/slack-cli/internal/iostreams" @@ -34,7 +35,7 @@ func TestLogoutCommand(t *testing.T) { }, "logout of all teams": { CmdArgs: []string{"--all"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.AuthInterface.On("ResolveApiHost", mock.Anything, mock.Anything, mock.Anything).Return("api.slack.com") clientsMock.AuthInterface.On("ResolveLogstashHost", mock.Anything, mock.Anything, mock.Anything).Return("logstash.slack.com") clientsMock.AuthInterface.On("Auths", mock.Anything).Return(fakeAuthsByTeamSlice, nil) @@ -58,7 +59,7 @@ func TestLogoutCommand(t *testing.T) { }, "logout of single team by named domain via flag": { CmdArgs: []string{"--team", "team1"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.AuthInterface.On("ResolveApiHost", mock.Anything, mock.Anything, mock.Anything).Return("api.slack.com") clientsMock.AuthInterface.On("ResolveLogstashHost", mock.Anything, mock.Anything, mock.Anything).Return("logstash.slack.com") clientsMock.AuthInterface.On("Auths", mock.Anything).Return(fakeAuthsByTeamSlice, nil) @@ -82,7 +83,7 @@ func TestLogoutCommand(t *testing.T) { }, "logout of single team by id via flag": { CmdArgs: []string{"--team", "T2"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.AuthInterface.On("ResolveApiHost", mock.Anything, mock.Anything, mock.Anything).Return("api.slack.com") clientsMock.AuthInterface.On("ResolveLogstashHost", mock.Anything, mock.Anything, mock.Anything).Return("logstash.slack.com") clientsMock.IO.On("SelectPrompt", mock.Anything, "Select an authorization to revoke", mock.Anything, iostreams.MatchPromptConfig(iostreams.SelectPromptConfig{ @@ -114,7 +115,7 @@ func TestLogoutCommand(t *testing.T) { }, "require a known team value is used in flag": { CmdArgs: []string{"--team", "randomteamdomain"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clientsFactory *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.AuthInterface.On("Auths", mock.Anything).Return(fakeAuthsByTeamSlice, nil) clientsMock.IO.On("SelectPrompt", mock.Anything, "Select an authorization to revoke", mock.Anything, iostreams.MatchPromptConfig(iostreams.SelectPromptConfig{ Flag: clientsMock.Config.Flags.Lookup("team"), @@ -131,7 +132,7 @@ func TestLogoutCommand(t *testing.T) { }, "logout of a workspace by prompt": { CmdArgs: []string{}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.AuthInterface.On("ResolveApiHost", mock.Anything, mock.Anything, mock.Anything).Return("api.slack.com") clientsMock.AuthInterface.On("ResolveLogstashHost", mock.Anything, mock.Anything, mock.Anything).Return("logstash.slack.com") clientsMock.AuthInterface.On("Auths", mock.Anything).Return(fakeAuthsByTeamSlice, nil) @@ -159,7 +160,7 @@ func TestLogoutCommand(t *testing.T) { }, "automatically logout of the only available workspace available": { CmdArgs: []string{}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.AuthInterface.On("ResolveApiHost", mock.Anything, mock.Anything, mock.Anything).Return("api.slack.com") clientsMock.AuthInterface.On("ResolveLogstashHost", mock.Anything, mock.Anything, mock.Anything).Return("logstash.slack.com") clientsMock.AuthInterface.On("Auths", mock.Anything).Return([]types.SlackAuth{ @@ -179,7 +180,7 @@ func TestLogoutCommand(t *testing.T) { }, "verify the only available auth matches a team flag": { CmdArgs: []string{"--team", "anotherteam"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.AuthInterface.On("Auths", mock.Anything).Return([]types.SlackAuth{ fakeAuthsByTeamSlice[0], }, nil) @@ -198,7 +199,7 @@ func TestLogoutCommand(t *testing.T) { }, "confirm authorizations are revoked if none exist": { CmdArgs: []string{}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.AuthInterface.On("Auths", mock.Anything).Return([]types.SlackAuth{}, nil) }, ExpectedOutputs: []string{"All authorizations successfully revoked"}, @@ -209,7 +210,7 @@ func TestLogoutCommand(t *testing.T) { }, "error if a team flag is provided without auths": { CmdArgs: []string{"--team", "someteam"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.AuthInterface.On("Auths", mock.Anything).Return([]types.SlackAuth{}, nil) clientsMock.IO.On("SelectPrompt", mock.Anything, "Select an authorization to revoke", mock.Anything, iostreams.MatchPromptConfig(iostreams.SelectPromptConfig{ Flag: clientsMock.Config.Flags.Lookup("team"), diff --git a/cmd/auth/revoke_test.go b/cmd/auth/revoke_test.go index cab2bd5c..e0cc37e0 100644 --- a/cmd/auth/revoke_test.go +++ b/cmd/auth/revoke_test.go @@ -15,6 +15,7 @@ package auth import ( + "context" "testing" "github.com/slackapi/slack-cli/internal/iostreams" @@ -30,7 +31,7 @@ func TestRevokeCommand(t *testing.T) { testutil.TableTestCommand(t, testutil.CommandTests{ "revoke a token passed by flag": { CmdArgs: []string{"--token", "xoxp-example-1234"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.IO.On("PasswordPrompt", mock.Anything, "Enter a token to revoke", iostreams.MatchPromptConfig(iostreams.PasswordPromptConfig{ Flag: clientsMock.Config.Flags.Lookup("token"), })).Return(iostreams.PasswordPromptResponse{ @@ -46,7 +47,7 @@ func TestRevokeCommand(t *testing.T) { }, "require a set token value with the flag": { CmdArgs: []string{"--token", ""}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.IO.On("PasswordPrompt", mock.Anything, "Enter a token to revoke", iostreams.MatchPromptConfig(iostreams.PasswordPromptConfig{ Flag: clientsMock.Config.Flags.Lookup("token"), })).Return(iostreams.PasswordPromptResponse{}, slackerror.New(slackerror.ErrMissingFlag)) @@ -58,7 +59,7 @@ func TestRevokeCommand(t *testing.T) { }, "revoke a token input by prompt": { CmdArgs: []string{}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.IO.On("PasswordPrompt", mock.Anything, "Enter a token to revoke", iostreams.MatchPromptConfig(iostreams.PasswordPromptConfig{ Flag: clientsMock.Config.Flags.Lookup("token"), })).Return(iostreams.PasswordPromptResponse{ @@ -74,7 +75,7 @@ func TestRevokeCommand(t *testing.T) { }, "verify errors are gracefully handled during the revoke": { CmdArgs: []string{}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.IO.On("PasswordPrompt", mock.Anything, "Enter a token to revoke", iostreams.MatchPromptConfig(iostreams.PasswordPromptConfig{ Flag: clientsMock.Config.Flags.Lookup("token"), })).Return(iostreams.PasswordPromptResponse{ diff --git a/cmd/collaborators/add_test.go b/cmd/collaborators/add_test.go index c7f1f9be..32945485 100644 --- a/cmd/collaborators/add_test.go +++ b/cmd/collaborators/add_test.go @@ -31,7 +31,7 @@ func TestAddCommand(t *testing.T) { testutil.TableTestCommand(t, testutil.CommandTests{ "add an experimental reader collaborator from user id": { CmdArgs: []string{"U123", "--permission-type", "reader"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.AddDefaultMocks() // Mock App Selection appSelectMock := prompts.NewAppSelectMock() @@ -55,7 +55,7 @@ func TestAddCommand(t *testing.T) { }, "add an owner collaborator from collaborator email": { CmdArgs: []string{"joe.smith@company.com", "--permission-type", "owner"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.AddDefaultMocks() // Mock App Selection appSelectMock := prompts.NewAppSelectMock() @@ -80,7 +80,7 @@ func TestAddCommand(t *testing.T) { }, "default to owner if permission type is not specified": { CmdArgs: []string{"joe.smith@company.com"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.AddDefaultMocks() // Mock App Selection appSelectMock := prompts.NewAppSelectMock() diff --git a/cmd/collaborators/remove_test.go b/cmd/collaborators/remove_test.go index e7cfd87a..70f31076 100644 --- a/cmd/collaborators/remove_test.go +++ b/cmd/collaborators/remove_test.go @@ -15,6 +15,7 @@ package collaborators import ( + "context" "testing" "github.com/slackapi/slack-cli/internal/iostreams" @@ -50,7 +51,7 @@ func TestRemoveCommand(t *testing.T) { testutil.TableTestCommand(t, testutil.CommandTests{ "always attempts to remove the collaborator provided via argument": { CmdArgs: []string{"USLACKBOT"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { appSelectMock := prompts.NewAppSelectMock() teamAppSelectPromptFunc = appSelectMock.TeamAppSelectPrompt appSelectMock.On("TeamAppSelectPrompt"). @@ -69,7 +70,7 @@ func TestRemoveCommand(t *testing.T) { }, "still attempts to remove the collaborator provided via prompt": { CmdArgs: []string{}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { appSelectMock := prompts.NewAppSelectMock() teamAppSelectPromptFunc = appSelectMock.TeamAppSelectPrompt appSelectMock.On("TeamAppSelectPrompt"). @@ -90,7 +91,7 @@ func TestRemoveCommand(t *testing.T) { }, "avoids removing the user performing the command without confirmation": { CmdArgs: []string{}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { appSelectMock := prompts.NewAppSelectMock() teamAppSelectPromptFunc = appSelectMock.TeamAppSelectPrompt appSelectMock.On("TeamAppSelectPrompt"). diff --git a/cmd/collaborators/update_test.go b/cmd/collaborators/update_test.go index c8924c49..7a090ddb 100644 --- a/cmd/collaborators/update_test.go +++ b/cmd/collaborators/update_test.go @@ -31,7 +31,7 @@ func TestUpdateCommand(t *testing.T) { "given user ID, update a collaborator to be a reader": { CmdArgs: []string{"U123", "--permission-type", "reader"}, ExpectedOutputs: []string{"U123 successfully updated as a reader collaborator on this app"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.AddDefaultMocks() // Mock App Selection appSelectMock := prompts.NewAppSelectMock() @@ -49,7 +49,7 @@ func TestUpdateCommand(t *testing.T) { "given email, update a collaborator to be an owner": { CmdArgs: []string{"joe.smith@company.com", "--permission-type", "owner"}, ExpectedOutputs: []string{"joe.smith@company.com successfully updated as an owner collaborator on this app"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.AddDefaultMocks() // Mock App Selection appSelectMock := prompts.NewAppSelectMock() @@ -67,7 +67,7 @@ func TestUpdateCommand(t *testing.T) { "permission type must be specified": { CmdArgs: []string{"joe.smith@company.com"}, ExpectedOutputs: []string{"Specify a permission type for your collaborator"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.AddDefaultMocks() // Set experiment flag clientsMock.Config.ExperimentsFlag = append(clientsMock.Config.ExperimentsFlag, "read-only-collaborators") @@ -77,7 +77,7 @@ func TestUpdateCommand(t *testing.T) { "user ID must be provided": { CmdArgs: []string{}, ExpectedErrorStrings: []string{"accepts 1 arg(s), received 0"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.AddDefaultMocks() // Set experiment flag clientsMock.Config.ExperimentsFlag = append(clientsMock.Config.ExperimentsFlag, "read-only-collaborators") diff --git a/cmd/datastore/bulk_put_test.go b/cmd/datastore/bulk_put_test.go index c9cf6f84..d5749372 100644 --- a/cmd/datastore/bulk_put_test.go +++ b/cmd/datastore/bulk_put_test.go @@ -230,7 +230,7 @@ func TestBulkPutCommandImport(t *testing.T) { `{"datastore":"Todos"}`, `--from-file=my-file`, }, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { *cm = *setupDatastoreMocks() cm.ApiInterface.On("AppsDatastoreBulkPut", mock.Anything, mock.Anything, mock.Anything). Return(types.AppDatastoreBulkPutResult{}, nil) @@ -260,7 +260,7 @@ func TestBulkPutCommandImport(t *testing.T) { `--from-file=my-file`, }, ExpectedOutputs: []string{"Some items failed to be imported"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { *cm = *setupDatastoreMocks() cm.ApiInterface.On("AppsDatastoreBulkPut", mock.Anything, mock.Anything, mock.Anything). Return(types.AppDatastoreBulkPutResult{}, nil) @@ -303,7 +303,7 @@ func TestBulkPutCommandImport(t *testing.T) { `--from-file=my-file`, }, ExpectedOutputs: []string{"Import will be limited to the first 5000 items in the file"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { *cm = *setupDatastoreMocks() cm.ApiInterface.On("AppsDatastoreBulkPut", mock.Anything, mock.Anything, mock.Anything). Return(types.AppDatastoreBulkPutResult{}, nil) @@ -326,7 +326,7 @@ func TestBulkPutCommandImport(t *testing.T) { `{"datastore":"Todos"}`, `--from-file=my-file`, }, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { *cm = *setupDatastoreMocks() itemsFile, err := cm.Fs.Create("my-file") diff --git a/cmd/datastore/count_test.go b/cmd/datastore/count_test.go index 311e501d..c64bd56d 100644 --- a/cmd/datastore/count_test.go +++ b/cmd/datastore/count_test.go @@ -15,6 +15,7 @@ package datastore import ( + "context" "testing" "github.com/slackapi/slack-cli/internal/app" @@ -130,7 +131,7 @@ func TestCountCommand(t *testing.T) { testutil.TableTestCommand(t, testutil.CommandTests{ "default to the empty expression when no expression is passed": { CmdArgs: []string{"--datastore", "tasks"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.ApiInterface.On("AppsDatastoreCount", mock.Anything, mock.Anything, mock.Anything). Return(types.AppDatastoreCountResult{Datastore: "tasks", Count: 12}, nil) }, @@ -149,7 +150,7 @@ func TestCountCommand(t *testing.T) { }, "pass an empty expression through arguments": { CmdArgs: []string{`{"datastore":"tasks"}`}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.ApiInterface.On("AppsDatastoreCount", mock.Anything, mock.Anything, mock.Anything). Return(types.AppDatastoreCountResult{Datastore: "tasks", Count: 12}, nil) }, @@ -170,7 +171,7 @@ func TestCountCommand(t *testing.T) { CmdArgs: []string{ `{"datastore":"tasks","expression":"#task_id < :num","expression_attributes":{"#task_id":"task_id"},"expression_values":{":num":"3"}}`, }, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.ApiInterface.On("AppsDatastoreCount", mock.Anything, mock.Anything, mock.Anything). Return(types.AppDatastoreCountResult{Datastore: "tasks", Count: 12}, nil) }, @@ -201,7 +202,7 @@ func TestCountCommand(t *testing.T) { CmdArgs: []string{ `{"datastore":"Todos","app":"A001","expression":"#task_id < :num AND #status = :progress","expression_attributes":{"#task_id":"task_id","#status":"status"},"expression_values":{":num":"3",":progress":"wip"}}`, }, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.ApiInterface.On("AppsDatastoreCount", mock.Anything, mock.Anything, mock.Anything). Return(types.AppDatastoreCountResult{Datastore: "tasks", Count: 12}, nil) }, @@ -232,7 +233,7 @@ func TestCountCommand(t *testing.T) { }, "pass an empty expression through prompts": { CmdArgs: []string{"--unstable"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { manifestMock := &app.ManifestMockObject{} manifestMock.On("GetManifestRemote", mock.Anything, mock.Anything, mock.Anything).Return(types.SlackYaml{ AppManifest: types.AppManifest{ @@ -271,7 +272,7 @@ func TestCountCommand(t *testing.T) { }, "pass an extended expression through prompts": { CmdArgs: []string{"--unstable"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { manifestMock := &app.ManifestMockObject{} manifestMock.On("GetManifestRemote", mock.Anything, mock.Anything, mock.Anything).Return(types.SlackYaml{ AppManifest: types.AppManifest{ diff --git a/cmd/datastore/query_test.go b/cmd/datastore/query_test.go index 090a3d77..e858fdaf 100644 --- a/cmd/datastore/query_test.go +++ b/cmd/datastore/query_test.go @@ -392,7 +392,7 @@ func TestQueryCommandExport(t *testing.T) { `{"datastore":"Todos"}`, `--to-file=my-file`, }, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { *cm = *setupDatastoreMocks() _, err := prepareExportMockData(cm, 10, 2) assert.NoError(t, err) @@ -421,7 +421,7 @@ func TestQueryCommandExport(t *testing.T) { `--to-file=my-file`, }, ExpectedOutputs: []string{"Export will be limited to the first 10000 items in the datastore"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { *cm = *setupDatastoreMocks() _, err := prepareExportMockData(cm, 10010, 100) assert.NoError(t, err) diff --git a/cmd/docgen/docgen_test.go b/cmd/docgen/docgen_test.go index 994263b9..c283e159 100644 --- a/cmd/docgen/docgen_test.go +++ b/cmd/docgen/docgen_test.go @@ -15,6 +15,7 @@ package docgen import ( + "context" "errors" "path/filepath" "testing" @@ -32,7 +33,7 @@ func TestNewDocsCommand(t *testing.T) { testutil.TableTestCommand(t, testutil.CommandTests{ "when no path argument": { CmdArgs: []string{}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.Fs.On("MkdirAll", mock.Anything, mock.Anything).Return(nil) }, ExpectedOutputs: []string{ @@ -76,7 +77,7 @@ func TestNewDocsCommand(t *testing.T) { }, "when path argument exists": { CmdArgs: []string{"markdown-docs"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.Fs.On("MkdirAll", mock.Anything, mock.Anything).Return(nil) }, ExpectedOutputs: []string{ @@ -118,7 +119,7 @@ func TestNewDocsCommand(t *testing.T) { }, }, "when Getwd returns error": { - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.Fs.On("MkdirAll", mock.Anything, mock.Anything).Return(nil) cm.Os.On("Getwd").Return("", errors.New("somehow there is no cwd")) }, @@ -152,7 +153,7 @@ func TestNewDocsCommand(t *testing.T) { }, }, "when creating the default docs directory fails": { - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.Fs.On( "MkdirAll", filepath.Join(slackdeps.MockWorkingDirectory, "docs"), @@ -165,7 +166,7 @@ func TestNewDocsCommand(t *testing.T) { ExpectedErrorStrings: []string{"no write permission"}, }, "when creating the default commands directory fails": { - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.Fs.On( "MkdirAll", filepath.Join(slackdeps.MockWorkingDirectory, "docs"), @@ -185,7 +186,7 @@ func TestNewDocsCommand(t *testing.T) { ExpectedErrorStrings: []string{"no write permission"}, }, "when generating docs fails": { - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.Cobra.On( "GenMarkdownTree", mock.Anything, diff --git a/cmd/env/add_test.go b/cmd/env/add_test.go index 10a38828..c3aceafe 100644 --- a/cmd/env/add_test.go +++ b/cmd/env/add_test.go @@ -144,7 +144,7 @@ func Test_Env_AddCommand(t *testing.T) { testutil.TableTestCommand(t, testutil.CommandTests{ "add a variable using arguments": { CmdArgs: []string{"ENV_NAME", "ENV_VALUE"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { setupEnvAddCommandMocks(cm, cf) }, ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { @@ -168,7 +168,7 @@ func Test_Env_AddCommand(t *testing.T) { }, "provide a variable name by argument and value by prompt": { CmdArgs: []string{"ENV_NAME"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { setupEnvAddCommandMocks(cm, cf) cm.IO.On( "PasswordPrompt", @@ -199,7 +199,7 @@ func Test_Env_AddCommand(t *testing.T) { }, "provide a variable name by argument and value by flag": { CmdArgs: []string{"ENV_NAME", "--value", "example_value"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { setupEnvAddCommandMocks(cm, cf) cm.IO.On( "PasswordPrompt", @@ -230,7 +230,7 @@ func Test_Env_AddCommand(t *testing.T) { }, "provide both variable name and value by prompt": { CmdArgs: []string{}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { setupEnvAddCommandMocks(cm, cf) cm.IO.On( "InputPrompt", diff --git a/cmd/env/list_test.go b/cmd/env/list_test.go index c7183318..b261f53f 100644 --- a/cmd/env/list_test.go +++ b/cmd/env/list_test.go @@ -15,6 +15,7 @@ package env import ( + "context" "testing" "github.com/slackapi/slack-cli/internal/app" @@ -129,7 +130,7 @@ func Test_Env_ListCommandPreRun(t *testing.T) { func Test_Env_ListCommand(t *testing.T) { testutil.TableTestCommand(t, testutil.CommandTests{ "list variables using arguments": { - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.ApiInterface.On( "ListVariables", mock.Anything, diff --git a/cmd/env/remove_test.go b/cmd/env/remove_test.go index 29051996..b24d1b4e 100644 --- a/cmd/env/remove_test.go +++ b/cmd/env/remove_test.go @@ -15,6 +15,7 @@ package env import ( + "context" "testing" "github.com/slackapi/slack-cli/internal/app" @@ -131,7 +132,7 @@ func Test_Env_RemoveCommand(t *testing.T) { testutil.TableTestCommand(t, testutil.CommandTests{ "remove a variable using arguments": { CmdArgs: []string{"ENV_NAME"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.ApiInterface.On( "ListVariables", mock.Anything, @@ -174,7 +175,7 @@ func Test_Env_RemoveCommand(t *testing.T) { }, "remove a variable using prompt": { CmdArgs: []string{}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.ApiInterface.On( "ListVariables", mock.Anything, @@ -233,7 +234,7 @@ func Test_Env_RemoveCommand(t *testing.T) { }, "exit without errors when prompting zero environment variables": { CmdArgs: []string{}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.ApiInterface.On( "ListVariables", mock.Anything, diff --git a/cmd/externalauth/add_secret_test.go b/cmd/externalauth/add_secret_test.go index 348d4e6d..6ae691e7 100644 --- a/cmd/externalauth/add_secret_test.go +++ b/cmd/externalauth/add_secret_test.go @@ -139,7 +139,7 @@ func TestExternalAuthAddClientSecretCommand(t *testing.T) { testutil.TableTestCommand(t, testutil.CommandTests{ "no params": { CmdArgs: []string{}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("AppsAuthExternalList", mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return(types.ExternalAuthorizationInfoLists{ @@ -173,7 +173,7 @@ func TestExternalAuthAddClientSecretCommand(t *testing.T) { }, "with --provider": { CmdArgs: []string{"--provider", "provider_a"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("AppsAuthExternalList", mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return(types.ExternalAuthorizationInfoLists{ @@ -208,7 +208,7 @@ func TestExternalAuthAddClientSecretCommand(t *testing.T) { }, "with --secret": { CmdArgs: []string{"--secret", "secret"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("AppsAuthExternalList", mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return(types.ExternalAuthorizationInfoLists{ @@ -241,7 +241,7 @@ func TestExternalAuthAddClientSecretCommand(t *testing.T) { }, "with --provider and --secret": { CmdArgs: []string{"--provider", "provider_a", "--secret", "secret"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("AppsAuthExternalList", mock.Anything, mock.Anything, mock.Anything). Return(types.ExternalAuthorizationInfoLists{ @@ -273,7 +273,7 @@ func TestExternalAuthAddClientSecretCommand(t *testing.T) { }, "when list api returns error": { CmdArgs: []string{"--provider", "provider_a", "--secret", "secret"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("AppsAuthExternalList", mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return(types.ExternalAuthorizationInfoLists{ diff --git a/cmd/externalauth/add_test.go b/cmd/externalauth/add_test.go index 691f23ad..b4c93ba2 100644 --- a/cmd/externalauth/add_test.go +++ b/cmd/externalauth/add_test.go @@ -139,7 +139,7 @@ func TestExternalAuthAddCommand(t *testing.T) { "no params": { CmdArgs: []string{}, ExpectedOutputs: []string{}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("AppsAuthExternalList", mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return(types.ExternalAuthorizationInfoLists{ @@ -167,7 +167,7 @@ func TestExternalAuthAddCommand(t *testing.T) { "no params and no client secret set": { CmdArgs: []string{}, ExpectedErrorStrings: []string{"No client secret exists"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("AppsAuthExternalList", mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return(types.ExternalAuthorizationInfoLists{ @@ -195,7 +195,7 @@ func TestExternalAuthAddCommand(t *testing.T) { "with provider_key": { CmdArgs: []string{"--provider", "provider_a"}, ExpectedOutputs: []string{}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("AppsAuthExternalList", mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return(types.ExternalAuthorizationInfoLists{ @@ -223,7 +223,7 @@ func TestExternalAuthAddCommand(t *testing.T) { "with no client secret set": { CmdArgs: []string{"--provider", "provider_a"}, ExpectedErrorStrings: []string{"No client secret exists"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("AppsAuthExternalList", mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return(types.ExternalAuthorizationInfoLists{ @@ -251,7 +251,7 @@ func TestExternalAuthAddCommand(t *testing.T) { }, "when list api returns error": { CmdArgs: []string{"--provider", "provider_a"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("AppsAuthExternalList", mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return(types.ExternalAuthorizationInfoLists{ diff --git a/cmd/externalauth/remove_test.go b/cmd/externalauth/remove_test.go index 1f1b06fd..85ca6210 100644 --- a/cmd/externalauth/remove_test.go +++ b/cmd/externalauth/remove_test.go @@ -140,7 +140,7 @@ func TestExternalAuthRemoveCommand(t *testing.T) { "no params": { CmdArgs: []string{}, ExpectedOutputs: []string{}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("AppsAuthExternalList", mock.Anything, mock.Anything, mock.Anything). Return(types.ExternalAuthorizationInfoLists{ @@ -167,7 +167,7 @@ func TestExternalAuthRemoveCommand(t *testing.T) { "with --provider": { CmdArgs: []string{"--provider", "provider_a"}, ExpectedOutputs: []string{}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("AppsAuthExternalList", mock.Anything, mock.Anything, mock.Anything). Return(types.ExternalAuthorizationInfoLists{ @@ -192,7 +192,7 @@ func TestExternalAuthRemoveCommand(t *testing.T) { "with --all": { CmdArgs: []string{"--all"}, ExpectedOutputs: []string{}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("AppsAuthExternalList", mock.Anything, mock.Anything, mock.Anything). Return(types.ExternalAuthorizationInfoLists{ @@ -217,7 +217,7 @@ func TestExternalAuthRemoveCommand(t *testing.T) { "with --all and --provider": { CmdArgs: []string{"--all", "--provider", "provider_a"}, ExpectedOutputs: []string{}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("AppsAuthExternalList", mock.Anything, mock.Anything, mock.Anything). Return(types.ExternalAuthorizationInfoLists{ @@ -242,7 +242,7 @@ func TestExternalAuthRemoveCommand(t *testing.T) { }, "with --all but no auth present": { CmdArgs: []string{"--all"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("AppsAuthExternalList", mock.Anything, mock.Anything, mock.Anything). Return(types.ExternalAuthorizationInfoLists{ diff --git a/cmd/externalauth/select_auth_test.go b/cmd/externalauth/select_auth_test.go index f7c4c7d8..9a5ff9a9 100644 --- a/cmd/externalauth/select_auth_test.go +++ b/cmd/externalauth/select_auth_test.go @@ -15,6 +15,7 @@ package externalauth import ( + "context" "errors" "testing" @@ -241,7 +242,7 @@ func TestExternalAuthSelectAuthCommand(t *testing.T) { testutil.TableTestCommand(t, testutil.CommandTests{ "list api returns error": { CmdArgs: []string{}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("AppsAuthExternalList", mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return(types.ExternalAuthorizationInfoLists{}, errors.New("test error")) @@ -253,7 +254,7 @@ func TestExternalAuthSelectAuthCommand(t *testing.T) { }, "list with no tokens and no params": { CmdArgs: []string{}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("AppsAuthExternalList", mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return(sampleListReturnWithoutTokens, nil) @@ -268,7 +269,7 @@ func TestExternalAuthSelectAuthCommand(t *testing.T) { }, "list with no tokens and workflow flag": { CmdArgs: []string{"--workflow", "#/workflows/workflow_callback"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("AppsAuthExternalList", mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return(sampleListReturnWithoutTokens, nil) @@ -286,7 +287,7 @@ func TestExternalAuthSelectAuthCommand(t *testing.T) { }, "list with no workflows and no params": { CmdArgs: []string{}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("AppsAuthExternalList", mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return(sampleListReturnWithoutWorkflows, nil) @@ -301,7 +302,7 @@ func TestExternalAuthSelectAuthCommand(t *testing.T) { }, "list with no workflows and workflow flag": { CmdArgs: []string{"--workflow", "#/workflows/workflow_callback"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("AppsAuthExternalList", mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return(sampleListReturnWithoutWorkflows, nil) @@ -319,7 +320,7 @@ func TestExternalAuthSelectAuthCommand(t *testing.T) { }, "list with workflows and no param": { CmdArgs: []string{}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("AppsAuthExternalList", mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return(sampleListReturnWithWorkflows, nil) @@ -345,7 +346,7 @@ func TestExternalAuthSelectAuthCommand(t *testing.T) { }, "list with workflows and invalid workflow param": { CmdArgs: []string{"--workflow", "#/workflows/workflow_callback"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("AppsAuthExternalList", mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return(sampleListReturnWithWorkflows, nil) @@ -377,7 +378,7 @@ func TestExternalAuthSelectAuthCommand(t *testing.T) { }, "list with workflows and valid workflow param": { CmdArgs: []string{"--workflow", "#/workflows/my_callback_id2"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("AppsAuthExternalList", mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return(sampleListReturnWithWorkflows, nil) @@ -402,7 +403,7 @@ func TestExternalAuthSelectAuthCommand(t *testing.T) { }, "list with workflows and valid workflow invalid provider": { CmdArgs: []string{"--workflow", "#/workflows/my_callback_id2", "--provider", "test_provider"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("AppsAuthExternalList", mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return(sampleListReturnWithWorkflows, nil) @@ -426,7 +427,7 @@ func TestExternalAuthSelectAuthCommand(t *testing.T) { }, "list with workflows and valid workflow valid provider": { CmdArgs: []string{"--workflow", "#/workflows/my_callback_id2", "--provider", "provider_b"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("AppsAuthExternalList", mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return(sampleListReturnWithWorkflows, nil) @@ -452,7 +453,7 @@ func TestExternalAuthSelectAuthCommand(t *testing.T) { }, "list with workflows and valid workflow valid provider with tokens": { CmdArgs: []string{"--workflow", "#/workflows/my_callback_id2", "--provider", "provider_a"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("AppsAuthExternalList", mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return(sampleListReturnWithWorkflows, nil) @@ -484,7 +485,7 @@ func TestExternalAuthSelectAuthCommand(t *testing.T) { }, "list with workflows and valid workflow valid provider invalid account": { CmdArgs: []string{"--workflow", "#/workflows/my_callback_id2", "--provider", "provider_a", "--external-account", "test_account"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("AppsAuthExternalList", mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return(sampleListReturnWithWorkflows, nil) @@ -515,7 +516,7 @@ func TestExternalAuthSelectAuthCommand(t *testing.T) { }, "list with workflows and valid workflow valid provider valid account": { CmdArgs: []string{"--workflow", "#/workflows/my_callback_id2", "--provider", "provider_a", "--external-account", "xyz2@salesforce.com"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("AppsAuthExternalList", mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return(sampleListReturnWithWorkflows, nil) diff --git a/cmd/function/access_test.go b/cmd/function/access_test.go index 4325e418..1ffd6947 100644 --- a/cmd/function/access_test.go +++ b/cmd/function/access_test.go @@ -39,7 +39,7 @@ func TestFunctionDistributionCommand(t *testing.T) { ExpectedOutputs: []string{ "Function 'F1234' can be added to workflows by app collaborators", }, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { // set distribution clientsMock.ApiInterface.On("FunctionDistributionSet", mock.Anything, mock.Anything, mock.Anything, types.APP_COLLABORATORS, mock.Anything). Return([]types.FunctionDistributionUser{}, nil).Once() @@ -65,7 +65,7 @@ func TestFunctionDistributionCommand(t *testing.T) { "U00", "U01", }, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { // check if distribution type is named_entities clientsMock.ApiInterface.On("FunctionDistributionList", mock.Anything, mock.Anything, mock.Anything). Return(types.APP_COLLABORATORS, []types.FunctionDistributionUser{}, nil).Once() @@ -96,7 +96,7 @@ func TestFunctionDistributionCommand(t *testing.T) { "Function 'F1234' can be added to workflows by the following users", "U01", }, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { // check if distribution type is named_entities clientsMock.ApiInterface.On("FunctionDistributionList", mock.Anything, mock.Anything, mock.Anything). Return(types.NAMED_ENTITIES, []types.FunctionDistributionUser{{UserName: "user 0", ID: "U00"}, {UserName: "user 1", ID: "U01"}}, nil).Once() @@ -123,7 +123,7 @@ func TestFunctionDistributionCommand(t *testing.T) { "Function 'F1234' can be added to workflows by the following users", "everyone in the workspace", }, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.ApiInterface.On("FunctionDistributionList", mock.Anything, "F1234", fakeApp.AppID). Return(types.EVERYONE, []types.FunctionDistributionUser{}, nil).Once() clientsMock.AddDefaultMocks() @@ -143,7 +143,7 @@ func TestFunctionDistributionCommand(t *testing.T) { }, "attempt to read permissions with the file flag": { CmdArgs: []string{"--file", "permissions.json"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.AddDefaultMocks() appSelectTeardown = setupMockAppSelection(installedProdApp) err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) diff --git a/cmd/manifest/info_test.go b/cmd/manifest/info_test.go index bba763c4..70e730ef 100644 --- a/cmd/manifest/info_test.go +++ b/cmd/manifest/info_test.go @@ -42,7 +42,7 @@ func TestInfoCommand(t *testing.T) { testutil.TableTestCommand(t, testutil.CommandTests{ "errors when the source is project and app id is set": { CmdArgs: []string{"--source", "local", "--app", "A0001"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cf.SDKConfig = hooks.NewSDKConfigMock() }, ExpectedError: slackerror.New(slackerror.ErrMismatchedFlags). @@ -50,7 +50,7 @@ func TestInfoCommand(t *testing.T) { }, "errors when the source is an unexpected value": { CmdArgs: []string{"--source", "paper"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cf.SDKConfig = hooks.NewSDKConfigMock() cm.HookExecutor.On("Execute", mock.Anything).Return("", nil) }, @@ -59,7 +59,7 @@ func TestInfoCommand(t *testing.T) { }, "gathers the --source local from the get-manifest hook": { CmdArgs: []string{"--source", "local"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { manifestMock := &app.ManifestMockObject{} manifestMock.On("GetManifestLocal", mock.Anything, mock.Anything).Return(types.SlackYaml{ AppManifest: types.AppManifest{ @@ -84,7 +84,7 @@ func TestInfoCommand(t *testing.T) { }, "gathers the --source remote from the apps.manifest.export method": { CmdArgs: []string{"--source", "remote"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { appSelectMock := prompts.NewAppSelectMock() appSelectPromptFunc = appSelectMock.AppSelectPrompt appSelectMock.On("AppSelectPrompt").Return( @@ -114,8 +114,7 @@ func TestInfoCommand(t *testing.T) { }, }, "gathers manifest.source from project configurations with the bolt experiment": { - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { - ctx := context.Background() + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { appSelectMock := prompts.NewAppSelectMock() appSelectPromptFunc = appSelectMock.AppSelectPrompt appSelectMock.On("AppSelectPrompt").Return( @@ -159,8 +158,7 @@ func TestInfoCommand(t *testing.T) { fmt.Sprintf("Set \"manifest.source\" to \"%s\" in \"%s\" to continue", config.MANIFEST_SOURCE_LOCAL, filepath.Join(".slack", "config.json")), fmt.Sprintf("Read about manifest sourcing with %s", style.Commandf("manifest info --help", false)), }, "\n")), - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { - ctx := context.Background() + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cf.SDKConfig.WorkingDirectory = "." cm.IO.AddDefaultMocks() cm.Os.AddDefaultMocks() diff --git a/cmd/manifest/manifest_test.go b/cmd/manifest/manifest_test.go index 24e8396a..8c868308 100644 --- a/cmd/manifest/manifest_test.go +++ b/cmd/manifest/manifest_test.go @@ -15,6 +15,7 @@ package manifest import ( + "context" "encoding/json" "testing" @@ -34,7 +35,7 @@ func TestManifestCommand(t *testing.T) { testutil.TableTestCommand(t, testutil.CommandTests{ "calls the manifest info command with a remote --app flag": { CmdArgs: []string{"--app", "A0001"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { appSelectMock := prompts.NewAppSelectMock() appSelectPromptFunc = appSelectMock.AppSelectPrompt appSelectMock.On("AppSelectPrompt").Return( diff --git a/cmd/openformresponse/export_test.go b/cmd/openformresponse/export_test.go index ada48273..58c6dfcb 100644 --- a/cmd/openformresponse/export_test.go +++ b/cmd/openformresponse/export_test.go @@ -15,6 +15,7 @@ package openformresponse import ( + "context" "errors" "testing" @@ -35,7 +36,7 @@ func TestExportCommand(t *testing.T) { testutil.TableTestCommand(t, testutil.CommandTests{ "missing --workflow": { CmdArgs: []string{}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { appSelectTeardown = setupMockCreateAppSelection(installedProdApp) }, Teardown: func() { @@ -46,7 +47,7 @@ func TestExportCommand(t *testing.T) { "with --step-id, API succeeds": { CmdArgs: []string{"--workflow", "#/workflows/my_workflow", "--step-id", "stepId"}, ExpectedOutputs: []string{"Slackbot will DM you with a CSV file once it's ready"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { appSelectTeardown = setupMockCreateAppSelection(installedProdApp) cm.ApiInterface.On("StepsResponsesExport", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil) }, @@ -60,7 +61,7 @@ func TestExportCommand(t *testing.T) { "with --step-id, API fails": { CmdArgs: []string{"--workflow", "#/workflows/my_workflow", "--step-id", "stepId"}, ExpectedErrorStrings: []string{"failed"}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { appSelectTeardown = setupMockCreateAppSelection(installedProdApp) cm.ApiInterface.On("StepsResponsesExport", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(errors.New("failed")) }, diff --git a/cmd/project/init_test.go b/cmd/project/init_test.go index 2b073b5f..530c568c 100644 --- a/cmd/project/init_test.go +++ b/cmd/project/init_test.go @@ -54,7 +54,7 @@ func Test_Project_InitCommand(t *testing.T) { testutil.TableTestCommand(t, testutil.CommandTests{ "requires bolt experiment": { CmdArgs: []string{}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { // Do not set experiment flag setupProjectInitCommandMocks(t, cm, cf, false) }, @@ -62,7 +62,7 @@ func Test_Project_InitCommand(t *testing.T) { }, "init a project and do not link an existing app": { CmdArgs: []string{}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { setupProjectInitCommandMocks(t, cm, cf, true) // Do not link an existing app cm.IO.On("ConfirmPrompt", mock.Anything, app.LinkAppConfirmPromptText, mock.Anything).Return(false, nil) @@ -107,7 +107,7 @@ func Test_Project_InitCommand(t *testing.T) { }, "init a project and link an existing app": { CmdArgs: []string{}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { // Mocks auths to match against team and app cm.AuthInterface.On("Auths", mock.Anything).Return([]types.SlackAuth{ mockLinkSlackAuth2, diff --git a/cmd/project/samples_test.go b/cmd/project/samples_test.go index 8a48a122..2ec13757 100644 --- a/cmd/project/samples_test.go +++ b/cmd/project/samples_test.go @@ -33,7 +33,7 @@ func TestSamplesCommand(t *testing.T) { testutil.TableTestCommand(t, testutil.CommandTests{ "creates a template from a trusted sample": { CmdArgs: []string{}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { createPkg.GetSampleRepos = func(client createPkg.Sampler) ([]createPkg.GithubRepo, error) { repos := []createPkg.GithubRepo{ { diff --git a/cmd/triggers/access_test.go b/cmd/triggers/access_test.go index 8990dcac..9f8c6f12 100644 --- a/cmd/triggers/access_test.go +++ b/cmd/triggers/access_test.go @@ -39,7 +39,7 @@ func TestTriggersAccessCommand(t *testing.T) { "pass flags to set access to app collaborators": { CmdArgs: []string{"--trigger-id", fakeTriggerID, "--app-collaborators"}, ExpectedOutputs: []string{fmt.Sprintf("Trigger '%s'", fakeTriggerID), "app collaborator"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockAccessAppSelection(installedProdApp) // get current access type clientsMock.ApiInterface.On("TriggerPermissionsList", mock.Anything, mock.Anything, mock.Anything). @@ -69,7 +69,7 @@ func TestTriggersAccessCommand(t *testing.T) { "Trigger '%s'", fakeTriggerID), "everyone in the workspace", }, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockAccessAppSelection(installedProdApp) // get current access type clientsMock.ApiInterface.On("TriggerPermissionsList", mock.Anything, mock.Anything, mock.Anything). @@ -99,7 +99,7 @@ func TestTriggersAccessCommand(t *testing.T) { fmt.Sprintf("Trigger '%s'", fakeTriggerID), "everyone in all workspaces in this org granted to this app", }, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockAccessAppSelection(installedProdOrgApp) // get current access type clientsMock.ApiInterface.On("TriggerPermissionsList", mock.Anything, mock.Anything, mock.Anything). @@ -126,7 +126,7 @@ func TestTriggersAccessCommand(t *testing.T) { "pass flags to grant access to specific users (previous access: app collaborators)": { CmdArgs: []string{"--trigger-id", fakeTriggerID, "--users", "user1, user2", "--grant", "--include-app-collaborators=false"}, ExpectedOutputs: []string{"Users added", fmt.Sprintf("Trigger '%s'", fakeTriggerID), "these users", "USER1", "USER2"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockAccessAppSelection(installedProdApp) // get current access type clientsMock.ApiInterface.On("TriggerPermissionsList", mock.Anything, mock.Anything, mock.Anything). @@ -158,7 +158,7 @@ func TestTriggersAccessCommand(t *testing.T) { "pass flags to grant access to specific channels (previous access: app collaborators)": { CmdArgs: []string{"--trigger-id", fakeTriggerID, "--channels", "channel1, channel2", "--grant", "--include-app-collaborators=false"}, ExpectedOutputs: []string{"Channels added", fmt.Sprintf("Trigger '%s'", fakeTriggerID), "all members of these channels", "CHANNEL1", "CHANNEL2"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockAccessAppSelection(installedProdApp) // get current access type clientsMock.ApiInterface.On("TriggerPermissionsList", mock.Anything, mock.Anything, mock.Anything). @@ -189,7 +189,7 @@ func TestTriggersAccessCommand(t *testing.T) { "pass flags to grant access to specific team (previous access: app collaborators)": { CmdArgs: []string{"--trigger-id", fakeTriggerID, "--workspaces", "team1", "--grant"}, ExpectedOutputs: []string{"Workspace added", fmt.Sprintf("Trigger '%s'", fakeTriggerID), "all members of this workspace", "TEAM1"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockAccessAppSelection(installedProdApp) // get current access type clientsMock.ApiInterface.On("TriggerPermissionsList", mock.Anything, mock.Anything, mock.Anything). @@ -226,7 +226,7 @@ func TestTriggersAccessCommand(t *testing.T) { "pass flags to grant access to specific teams with include-app-collaborators flag provided (previous access: app collaborators)": { CmdArgs: []string{"--trigger-id", fakeTriggerID, "--workspaces", "team1", "--grant", "--include-app-collaborators"}, ExpectedOutputs: []string{"Workspace added", fmt.Sprintf("Trigger '%s'", fakeTriggerID), "all members of this workspace", "TEAM1"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockAccessAppSelection(installedProdApp) // get current access type clientsMock.ApiInterface.On("TriggerPermissionsList", mock.Anything, mock.Anything, mock.Anything). @@ -262,7 +262,7 @@ func TestTriggersAccessCommand(t *testing.T) { "pass flags to grant access to specific users and channels (previous access: app collaborators)": { CmdArgs: []string{"--trigger-id", fakeTriggerID, "--users", "user1, user2", "--channels", "channel1, channel2", "--grant"}, ExpectedOutputs: []string{"Users added", "Channels added", fmt.Sprintf("Trigger '%s'", fakeTriggerID), "these users", "all members of these channels", "USER1", "USER2", "CHANNEL1", "CHANNEL2"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockAccessAppSelection(installedProdApp) // get current access type clientsMock.ApiInterface.On("TriggerPermissionsList", mock.Anything, mock.Anything, mock.Anything). @@ -312,7 +312,7 @@ func TestTriggersAccessCommand(t *testing.T) { "pass flags to grant access to specific users (previous access: named_entities)": { CmdArgs: []string{"--trigger-id", fakeTriggerID, "--users", "USER2", "--grant"}, ExpectedOutputs: []string{"User added", fmt.Sprintf("Trigger '%s'", fakeTriggerID), "these users", "USER1", "USER2"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockAccessAppSelection(installedProdApp) // get current access type clientsMock.ApiInterface.On("TriggerPermissionsList", mock.Anything, mock.Anything, mock.Anything). @@ -344,7 +344,7 @@ func TestTriggersAccessCommand(t *testing.T) { "pass flags to grant access to specific channels (previous access: named_entities)": { CmdArgs: []string{"--trigger-id", fakeTriggerID, "--channels", "CHANNEL2", "--grant"}, ExpectedOutputs: []string{"Channel added", fmt.Sprintf("Trigger '%s'", fakeTriggerID), "all members of these channels", "CHANNEL1", "CHANNEL2"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockAccessAppSelection(installedProdApp) // get current access type clientsMock.ApiInterface.On("TriggerPermissionsList", mock.Anything, mock.Anything, mock.Anything). @@ -376,7 +376,7 @@ func TestTriggersAccessCommand(t *testing.T) { "pass flags to grant access to specific users, channels and workspaces (previous access: named_entities)": { CmdArgs: []string{"--trigger-id", fakeTriggerID, "--users", "user1, user2", "--channels", "channel2", "--workspaces", "team1", "--grant"}, ExpectedOutputs: []string{"Users added", "Channel added", fmt.Sprintf("Trigger '%s'", fakeTriggerID), "these users", "all members of these channels", "all members of this workspace", "USER1", "USER2", "CHANNEL1", "CHANNEL2", "TEAM1"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockAccessAppSelection(installedProdApp) // get current access type clientsMock.ApiInterface.On("TriggerPermissionsList", mock.Anything, mock.Anything, mock.Anything). @@ -418,7 +418,7 @@ func TestTriggersAccessCommand(t *testing.T) { "pass flags to revoke access from specific users (previous access: named_entities)": { CmdArgs: []string{"--trigger-id", fakeTriggerID, "--users", "USER2", "--revoke"}, ExpectedOutputs: []string{fmt.Sprintf("Trigger '%s'", fakeTriggerID), "this user", "USER1"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockAccessAppSelection(installedProdApp) // get current access type clientsMock.ApiInterface.On("TriggerPermissionsList", mock.Anything, mock.Anything, mock.Anything). @@ -447,7 +447,7 @@ func TestTriggersAccessCommand(t *testing.T) { "pass flags to revoke access from specific channels (previous access: named_entities)": { CmdArgs: []string{"--trigger-id", fakeTriggerID, "--channels", "CHANNEL2", "--revoke"}, ExpectedOutputs: []string{fmt.Sprintf("Trigger '%s'", fakeTriggerID), "all members of this channel", "CHANNEL1"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockAccessAppSelection(installedProdApp) // get current access type clientsMock.ApiInterface.On("TriggerPermissionsList", mock.Anything, mock.Anything, mock.Anything). @@ -475,7 +475,7 @@ func TestTriggersAccessCommand(t *testing.T) { "pass flags to revoke access from specific workspace (previous access: named_entities)": { CmdArgs: []string{"--trigger-id", fakeTriggerID, "--workspaces", "TEAM2", "--revoke"}, ExpectedOutputs: []string{fmt.Sprintf("Trigger '%s'", fakeTriggerID), "all members of this workspace", "TEAM1"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockAccessAppSelection(installedProdApp) // get current access type clientsMock.ApiInterface.On("TriggerPermissionsList", mock.Anything, mock.Anything, mock.Anything). @@ -503,7 +503,7 @@ func TestTriggersAccessCommand(t *testing.T) { "pass flags to revoke access from specific users and channels (previous access: named_entities)": { CmdArgs: []string{"--trigger-id", fakeTriggerID, "--users", "USER2", "--channels", "CHANNEL2", "--revoke"}, ExpectedOutputs: []string{fmt.Sprintf("Trigger '%s'", fakeTriggerID), "this user", "all members of this channel", "USER1", "CHANNEL1"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockAccessAppSelection(installedProdApp) // get current access type clientsMock.ApiInterface.On("TriggerPermissionsList", mock.Anything, mock.Anything, mock.Anything). @@ -534,7 +534,7 @@ func TestTriggersAccessCommand(t *testing.T) { "set trigger ID through prompt": { CmdArgs: []string{"--everyone"}, ExpectedOutputs: []string{fmt.Sprintf("Trigger '%s'", fakeTriggerID), "everyone"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockAccessAppSelection(installedProdApp) // trigger ID prompt lists available triggers, including current access clientsMock.ApiInterface.On("WorkflowsTriggersList", mock.Anything, mock.Anything, mock.Anything).Return( @@ -578,7 +578,7 @@ func TestTriggersAccessCommand_AppSelection(t *testing.T) { "select an non-installed app": { CmdArgs: []string{"--workflow", "#/workflows/my_workflow"}, ExpectedErrorStrings: []string{cmdutil.DeployedAppNotInstalledMsg}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.AddDefaultMocks() err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) require.NoError(t, err, "Cant write apps.json") diff --git a/cmd/triggers/create_test.go b/cmd/triggers/create_test.go index 64567df5..2733a98f 100644 --- a/cmd/triggers/create_test.go +++ b/cmd/triggers/create_test.go @@ -57,7 +57,7 @@ func TestTriggersCreateCommand(t *testing.T) { "only pass --workflow": { CmdArgs: []string{"--workflow", "#/workflows/my_workflow"}, ExpectedOutputs: []string{"Trigger successfully created!", "My Trigger", "https://app.slack.com/app/" + fakeAppID + "/shortcut/" + fakeTriggerID}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockCreateAppSelection(installedProdApp) // TODO: always a) mock out calls and b) call AddDefaultMocks before making any clients.* calls fakeTrigger := createFakeTrigger(fakeTriggerID, fakeTriggerName, fakeAppID, "shortcut") @@ -90,7 +90,7 @@ func TestTriggersCreateCommand(t *testing.T) { "pass all shortcut parameters": { CmdArgs: []string{"--workflow", "#/workflows/my_workflow", "--title", "unit tests", "--description", "are the best"}, ExpectedOutputs: []string{"Trigger successfully created!", "unit tests", "https://app.slack.com/app/" + fakeAppID + "/shortcut/" + fakeTriggerID}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockCreateAppSelection(installedProdApp) // TODO: always a) mock out calls and b) call AddDefaultMocks before making any clients.* calls fakeTrigger := createFakeTrigger(fakeTriggerID, "unit tests", fakeAppID, "shortcut") @@ -121,7 +121,7 @@ func TestTriggersCreateCommand(t *testing.T) { "pass --interactivity, default name": { CmdArgs: []string{"--workflow", "#/workflows/my_workflow", "--interactivity", "--title", "unit tests", "--description", "are the best"}, ExpectedOutputs: []string{"Trigger successfully created!", "unit tests", "https://app.slack.com/app/" + fakeAppID + "/shortcut/" + fakeTriggerID}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockCreateAppSelection(installedProdApp) // TODO: always a) mock out calls and b) call AddDefaultMocks before making any clients.* calls fakeTrigger := createFakeTrigger(fakeTriggerID, "unit tests", fakeAppID, "shortcut") @@ -157,7 +157,7 @@ func TestTriggersCreateCommand(t *testing.T) { "pass --interactivity, custom name": { CmdArgs: []string{"--workflow", "#/workflows/my_workflow", "--interactivity", "--interactivity-name", "custom-interactivity", "--title", "unit tests", "--description", "are the best"}, ExpectedOutputs: []string{"Trigger successfully created!", "unit tests", "https://app.slack.com/app/" + fakeAppID + "/shortcut/" + fakeTriggerID}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockCreateAppSelection(installedProdApp) // TODO: always a) mock out calls and b) call AddDefaultMocks before making any clients.* calls fakeTrigger := createFakeTrigger(fakeTriggerID, "unit tests", fakeAppID, "shortcut") @@ -193,7 +193,7 @@ func TestTriggersCreateCommand(t *testing.T) { "api call fails": { CmdArgs: []string{"--workflow", "#/workflows/my_workflow"}, ExpectedErrorStrings: []string{"invalid_auth"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockCreateAppSelection(installedProdApp) // TODO: always a) mock out calls and b) call AddDefaultMocks before making any clients.* calls clientsMock.ApiInterface.On("WorkflowsTriggersCreate", mock.Anything, mock.Anything, mock.Anything).Return(types.DeployedTrigger{}, errors.New("invalid_auth")) @@ -209,7 +209,7 @@ func TestTriggersCreateCommand(t *testing.T) { "pass --trigger-def, scheduled trigger": { CmdArgs: []string{"--trigger-def", "trigger_def.json"}, ExpectedOutputs: []string{"Trigger successfully created!", "schedule"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockCreateAppSelection(installedProdApp) // TODO: always a) mock out calls and b) call AddDefaultMocks before making any clients.* calls fakeTrigger := createFakeTrigger(fakeTriggerID, "name", fakeAppID, "scheduled") @@ -251,7 +251,7 @@ func TestTriggersCreateCommand(t *testing.T) { "--trigger-def, file missing": { CmdArgs: []string{"--trigger-def", "foo.json"}, ExpectedErrorStrings: []string{"File not found"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockCreateAppSelection(installedProdApp) // TODO: testing chicken and egg: we need the default mocks in place before we can use any of the `clients` methods clientsMock.AddDefaultMocks() @@ -266,7 +266,7 @@ func TestTriggersCreateCommand(t *testing.T) { "--trigger-def, not json": { CmdArgs: []string{"--trigger-def", "triggers/shortcut.ts"}, ExpectedOutputs: []string{}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockCreateAppSelection(installedProdApp) clientsMock.ApiInterface.On("WorkflowsTriggersCreate", mock.Anything, mock.Anything, mock.Anything).Return(types.DeployedTrigger{}, nil) clientsMock.ApiInterface.On("ListCollaborators", mock.Anything, mock.Anything, mock.Anything).Return([]types.SlackUser{{}}, nil) @@ -293,7 +293,7 @@ func TestTriggersCreateCommand(t *testing.T) { "--trigger-def, not json, `get-trigger` hook missing": { CmdArgs: []string{"--trigger-def", "triggers/shortcut.ts"}, ExpectedErrorStrings: []string{"sdk_hook_get_trigger_not_found"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockCreateAppSelection(installedProdApp) // TODO: testing chicken and egg: we need the default mocks in place before we can use any of the `clients` methods clientsMock.AddDefaultMocks() @@ -352,7 +352,7 @@ func TestTriggersCreateCommand_MissingParameters(t *testing.T) { "initial api call fails, missing interactivity, succeeds on retry": { CmdArgs: []string{"--workflow", "#/workflows/my_workflow"}, ExpectedOutputs: []string{"Trigger successfully created!"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockCreateAppSelection(installedProdApp) promptForInteractivityTeardown = setupMockCreatePromptForInteractivity() // TODO: always a) mock out calls and b) call AddDefaultMocks before making any clients.* calls @@ -387,7 +387,7 @@ func TestTriggersCreateCommand_MissingParameters(t *testing.T) { "initial api call fails, missing interactivity, fails on retry": { CmdArgs: []string{"--workflow", "#/workflows/my_workflow"}, ExpectedErrorStrings: []string{"internal_error"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockCreateAppSelection(installedProdApp) promptForInteractivityTeardown = setupMockCreatePromptForInteractivity() // TODO: always a) mock out calls and b) call AddDefaultMocks before making any clients.* calls @@ -418,7 +418,7 @@ func TestTriggersCreateCommand_MissingParameters(t *testing.T) { "initial api call fails, missing a different type": { CmdArgs: []string{"--workflow", "#/workflows/my_workflow"}, ExpectedErrorStrings: []string{"invalid_trigger_inputs"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockCreateAppSelection(installedProdApp) promptForInteractivityTeardown = setupMockCreatePromptForInteractivity() // TODO: always a) mock out calls and b) call AddDefaultMocks before making any clients.* calls @@ -461,7 +461,7 @@ func TestTriggersCreateCommand_AppSelection(t *testing.T) { "selection error": { CmdArgs: []string{"--workflow", "#/workflows/my_workflow"}, ExpectedErrorStrings: []string{"selection error"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.AddDefaultMocks() appSelectTeardown = setupMockCreateAppSelection(newDevApp) appSelectMock := prompts.NewAppSelectMock() @@ -478,7 +478,7 @@ func TestTriggersCreateCommand_AppSelection(t *testing.T) { }, "select a non-installed local app": { CmdArgs: []string{"--workflow", "#/workflows/my_workflow"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { // Define app selector mock to choose local app appSelectTeardown = setupMockCreateAppSelection(newDevApp) // Define app install mock @@ -506,7 +506,7 @@ func TestTriggersCreateCommand_AppSelection(t *testing.T) { }, "select a non-installed prod app": { CmdArgs: []string{"--workflow", "#/workflows/my_workflow"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { // Define app selector mock to choose production app appSelectTeardown = setupMockCreateAppSelection(newProdApp) // Define workspace install mock diff --git a/cmd/triggers/delete_test.go b/cmd/triggers/delete_test.go index f85878db..2d637fd3 100644 --- a/cmd/triggers/delete_test.go +++ b/cmd/triggers/delete_test.go @@ -37,7 +37,7 @@ func TestTriggersDeleteCommand(t *testing.T) { "no params; use prompts to successfully delete": { CmdArgs: []string{}, ExpectedOutputs: []string{}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockDeleteAppSelection(installedProdApp) clientsMock.AddDefaultMocks() // promptForTriggerID lists available triggers @@ -53,7 +53,7 @@ func TestTriggersDeleteCommand(t *testing.T) { "app not installed": { CmdArgs: []string{"--trigger-id", fakeTriggerID}, ExpectedErrorStrings: []string{cmdutil.DeployedAppNotInstalledMsg}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockDeleteAppSelection(newProdApp) clientsMock.AddDefaultMocks() }, @@ -64,7 +64,7 @@ func TestTriggersDeleteCommand(t *testing.T) { "pass --trigger-id, success": { CmdArgs: []string{"--trigger-id", fakeTriggerID}, ExpectedOutputs: []string{"Trigger '" + fakeTriggerID + "' deleted"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockDeleteAppSelection(installedProdApp) clientsMock.ApiInterface.On("WorkflowsTriggersDelete", mock.Anything, mock.Anything, mock.Anything).Return(nil) // TODO: testing chicken and egg: we need the default mocks in place before we can use any of the `clients` methods @@ -84,7 +84,7 @@ func TestTriggersDeleteCommand(t *testing.T) { "pass --trigger-id, failure": { CmdArgs: []string{"--trigger-id", fakeTriggerID}, ExpectedErrorStrings: []string{"invalid_auth"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockDeleteAppSelection(installedProdApp) clientsMock.ApiInterface.On("WorkflowsTriggersDelete", mock.Anything, mock.Anything, mock.Anything).Return(errors.New("invalid_auth")) // TODO: testing chicken and egg: we need the default mocks in place before we can use any of the `clients` methods @@ -112,7 +112,7 @@ func TestTriggersDeleteCommand_AppSelection(t *testing.T) { "selection error": { CmdArgs: []string{"--trigger-id", "Ft01435GGLBD"}, ExpectedErrorStrings: []string{"selection error"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.AddDefaultMocks() appSelectTeardown = setupMockDeleteAppSelection(installedProdApp) appSelectMock := prompts.NewAppSelectMock() @@ -126,7 +126,7 @@ func TestTriggersDeleteCommand_AppSelection(t *testing.T) { "select a non-installed local app": { CmdArgs: []string{"--trigger-id", "Ft01435GGLBD"}, ExpectedErrorStrings: []string{cmdutil.LocalAppNotInstalledMsg}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.AddDefaultMocks() // TODO this can probably be replaced by a helper that sets up an apps.json file in // the right place on the afero memfs instance @@ -142,7 +142,7 @@ func TestTriggersDeleteCommand_AppSelection(t *testing.T) { "select a non-installed prod app": { CmdArgs: []string{"--trigger-id", "Ft01435GGLBD"}, ExpectedErrorStrings: []string{cmdutil.DeployedAppNotInstalledMsg}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.AddDefaultMocks() // TODO this can probably be replaced by a helper that sets up an apps.json file in // the right place on the afero memfs instance diff --git a/cmd/triggers/info_test.go b/cmd/triggers/info_test.go index bfb39695..c4046e16 100644 --- a/cmd/triggers/info_test.go +++ b/cmd/triggers/info_test.go @@ -36,7 +36,7 @@ func TestTriggersInfoCommand(t *testing.T) { testutil.TableTestCommand(t, testutil.CommandTests{ "no params; use prompts to select a trigger": { CmdArgs: []string{}, - Setup: func(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { appSelectTeardown = setupMockInfoAppSelection(installedProdApp) mockRequestTrigger := createFakeTrigger(fakeTriggerID, "test trigger", "test app", "shortcut") // promptForTriggerID lists available triggers @@ -60,7 +60,7 @@ func TestTriggersInfoCommand(t *testing.T) { "app not installed": { CmdArgs: []string{"--trigger-id", fakeTriggerID}, ExpectedErrorStrings: []string{cmdutil.DeployedAppNotInstalledMsg}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockInfoAppSelection(newProdApp) clientsMock.AddDefaultMocks() }, @@ -75,7 +75,7 @@ func TestTriggersInfoCommand(t *testing.T) { fakeTriggerID, "everyone in the workspace", }, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockInfoAppSelection(installedProdApp) mockRequestTrigger := createFakeTrigger(fakeTriggerID, "test trigger", "test app", "shortcut") clientsMock.ApiInterface.On("WorkflowsTriggersInfo", mock.Anything, mock.Anything, mock.Anything).Return(mockRequestTrigger, nil) @@ -100,7 +100,7 @@ func TestTriggersInfoCommand(t *testing.T) { fakeTriggerID, "everyone in all workspaces in this org granted to this app", }, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockInfoAppSelection(installedProdOrgApp) mockRequestTrigger := createFakeTrigger(fakeTriggerID, "test trigger", "test app", "shortcut") clientsMock.ApiInterface.On("WorkflowsTriggersInfo", mock.Anything, mock.Anything, mock.Anything).Return(mockRequestTrigger, nil) @@ -121,7 +121,7 @@ func TestTriggersInfoCommand(t *testing.T) { "pass --trigger-id, failure": { CmdArgs: []string{"--trigger-id", fakeTriggerID}, ExpectedErrorStrings: []string{"invalid_auth"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockInfoAppSelection(installedProdApp) clientsMock.ApiInterface.On("WorkflowsTriggersInfo", mock.Anything, mock.Anything, mock.Anything).Return(types.DeployedTrigger{}, errors.New("invalid_auth")) // TODO: testing chicken and egg: we need the default mocks in place before we can use any of the `clients` methods @@ -138,7 +138,7 @@ func TestTriggersInfoCommand(t *testing.T) { }, "event trigger displays hints and warnings": { CmdArgs: []string{"--trigger-id", fakeTriggerID}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockInfoAppSelection(installedProdApp) mockRequestTrigger := createFakeTrigger(fakeTriggerID, "test trigger", "test app", "event") clientsMock.ApiInterface.On("WorkflowsTriggersInfo", mock.Anything, mock.Anything, mock.Anything).Return(mockRequestTrigger, nil) @@ -175,7 +175,7 @@ func TestTriggersInfoCommand_AppSelection(t *testing.T) { "selection error": { CmdArgs: []string{"--trigger-id", "Ft01435GGLBD"}, ExpectedErrorStrings: []string{"Error"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.AddDefaultMocks() appSelectTeardown = setupMockInfoAppSelection(newDevApp) appSelectMock := prompts.NewAppSelectMock() @@ -193,7 +193,7 @@ func TestTriggersInfoCommand_AppSelection(t *testing.T) { "select an non-installed local app": { CmdArgs: []string{"--trigger-id", "Ft01435GGLBD"}, ExpectedErrorStrings: []string{cmdutil.LocalAppNotInstalledMsg}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.AddDefaultMocks() // TODO this can probably be replaced by a helper that sets up an apps.json file in // the right place on the afero memfs instance @@ -209,7 +209,7 @@ func TestTriggersInfoCommand_AppSelection(t *testing.T) { "select an non-installed prod app": { CmdArgs: []string{"--trigger-id", "Ft01435GGLBD"}, ExpectedErrorStrings: []string{cmdutil.DeployedAppNotInstalledMsg}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.AddDefaultMocks() // TODO this can probably be replaced by a helper that sets up an apps.json file in // the right place on the afero memfs instance diff --git a/cmd/triggers/list_test.go b/cmd/triggers/list_test.go index 5ebd9c65..96be2299 100644 --- a/cmd/triggers/list_test.go +++ b/cmd/triggers/list_test.go @@ -15,6 +15,7 @@ package triggers import ( + "context" "fmt" "testing" @@ -34,7 +35,7 @@ func TestTriggersListCommand(t *testing.T) { testutil.TableTestCommand(t, testutil.CommandTests{ "list no triggers": { CmdArgs: []string{}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockListAppSelection(installedProdApp) // Mock API responses @@ -62,7 +63,7 @@ func TestTriggersListCommand(t *testing.T) { "list one trigger for a workspace app": { CmdArgs: []string{}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockListAppSelection(installedProdApp) // Mock API responses @@ -99,7 +100,7 @@ func TestTriggersListCommand(t *testing.T) { "list one trigger for an org app": { CmdArgs: []string{}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockListAppSelection(installedProdOrgApp) // Mock API responses @@ -136,7 +137,7 @@ func TestTriggersListCommand(t *testing.T) { "list multiple triggers": { CmdArgs: []string{}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockListAppSelection(installedProdApp) // Mock API responses diff --git a/cmd/triggers/update_test.go b/cmd/triggers/update_test.go index 9bb68bf9..3cd0449d 100644 --- a/cmd/triggers/update_test.go +++ b/cmd/triggers/update_test.go @@ -39,7 +39,7 @@ func TestTriggersUpdateCommand(t *testing.T) { "with prompts": { CmdArgs: []string{}, ExpectedOutputs: []string{"Trigger successfully updated!", fakeTriggerName, "https://app.slack.com/app/" + fakeAppID + "/shortcut/" + fakeTriggerID}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockUpdateAppSelection(installedProdApp) clientsMock.AddDefaultMocks() // Prompt for Trigger ID @@ -75,7 +75,7 @@ func TestTriggersUpdateCommand(t *testing.T) { "hosted app not installed": { CmdArgs: []string{"--trigger-id", fakeTriggerID, "--workflow", "#/workflows/my_workflow"}, ExpectedErrorStrings: []string{cmdutil.DeployedAppNotInstalledMsg}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.AddDefaultMocks() // TODO this can probably be replaced by a helper that sets up an apps.json file in // the right place on the afero memfs instance @@ -91,7 +91,7 @@ func TestTriggersUpdateCommand(t *testing.T) { "local app not installed": { CmdArgs: []string{"--trigger-id", fakeTriggerID, "--workflow", "#/workflows/my_workflow"}, ExpectedErrorStrings: []string{cmdutil.LocalAppNotInstalledMsg}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.AddDefaultMocks() // TODO this can probably be replaced by a helper that sets up an apps.json file in // the right place on the afero memfs instance @@ -107,7 +107,7 @@ func TestTriggersUpdateCommand(t *testing.T) { "only pass --workflow and --trigger-id": { CmdArgs: []string{"--trigger-id", fakeTriggerID, "--workflow", "#/workflows/my_workflow"}, ExpectedOutputs: []string{"Trigger successfully updated!", fakeTriggerName, "https://app.slack.com/app/" + fakeAppID + "/shortcut/" + fakeTriggerID}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockUpdateAppSelection(installedProdApp) // TODO: always a) mock out calls and b) call AddDefaultMocks before making any clients.* calls fakeTrigger := createFakeTrigger(fakeTriggerID, fakeTriggerName, fakeAppID, "shortcut") @@ -143,7 +143,7 @@ func TestTriggersUpdateCommand(t *testing.T) { "only pass --workflow and --trigger-id, with interactivity": { CmdArgs: []string{"--trigger-id", fakeTriggerID, "--workflow", "#/workflows/my_workflow", "--interactivity"}, ExpectedOutputs: []string{"Trigger successfully updated!", fakeTriggerName, "https://app.slack.com/app/" + fakeAppID + "/shortcut/" + fakeTriggerID}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockUpdateAppSelection(installedProdApp) // TODO: always a) mock out calls and b) call AddDefaultMocks before making any clients.* calls fakeTrigger := createFakeTrigger(fakeTriggerID, fakeTriggerName, fakeAppID, "shortcut") @@ -184,7 +184,7 @@ func TestTriggersUpdateCommand(t *testing.T) { "only pass --workflow and --trigger-id, with interactivity and custom name": { CmdArgs: []string{"--trigger-id", fakeTriggerID, "--workflow", "#/workflows/my_workflow", "--interactivity", "--interactivity-name", "custom-interactivity"}, ExpectedOutputs: []string{"Trigger successfully updated!", fakeTriggerName, "https://app.slack.com/app/" + fakeAppID + "/shortcut/" + fakeTriggerID}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockUpdateAppSelection(installedProdApp) // TODO: always a) mock out calls and b) call AddDefaultMocks before making any clients.* calls fakeTrigger := createFakeTrigger(fakeTriggerID, fakeTriggerName, fakeAppID, "shortcut") @@ -225,7 +225,7 @@ func TestTriggersUpdateCommand(t *testing.T) { "pass all shortcut parameters": { CmdArgs: []string{"--trigger-id", fakeTriggerID, "--workflow", "#/workflows/my_workflow", "--title", "unit tests", "--description", "are the best"}, ExpectedOutputs: []string{"Trigger successfully updated!", "unit tests", "https://app.slack.com/app/" + fakeAppID + "/shortcut/" + fakeTriggerID}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockUpdateAppSelection(installedProdApp) // TODO: always a) mock out calls and b) call AddDefaultMocks before making any clients.* calls fakeTrigger := createFakeTrigger(fakeTriggerID, "unit tests", fakeAppID, "shortcut") @@ -259,7 +259,7 @@ func TestTriggersUpdateCommand(t *testing.T) { "api call fails": { CmdArgs: []string{"--trigger-id", fakeTriggerID, "--workflow", "#/workflows/my_workflow"}, ExpectedErrorStrings: []string{"invalid_auth"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockUpdateAppSelection(installedProdApp) clientsMock.ApiInterface.On("WorkflowsTriggersUpdate", mock.Anything, mock.Anything, mock.Anything).Return(types.DeployedTrigger{}, errors.New("invalid_auth")) // TODO: testing chicken and egg: we need the default mocks in place before we can use any of the `clients` methods @@ -274,7 +274,7 @@ func TestTriggersUpdateCommand(t *testing.T) { "pass --trigger-def, scheduled trigger": { CmdArgs: []string{"--trigger-id", fakeTriggerID, "--trigger-def", "trigger_def.json"}, ExpectedOutputs: []string{"Trigger successfully updated!", "schedule"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockUpdateAppSelection(installedProdApp) // TODO: always a) mock out calls and b) call AddDefaultMocks before making any clients.* calls fakeTrigger := createFakeTrigger(fakeTriggerID, "name", fakeAppID, "scheduled") @@ -318,7 +318,7 @@ func TestTriggersUpdateCommand(t *testing.T) { "--trigger-def, file missing": { CmdArgs: []string{"--trigger-id", fakeTriggerID, "--trigger-def", "foo.json"}, ExpectedErrorStrings: []string{"File not found"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockUpdateAppSelection(installedProdApp) // TODO: testing chicken and egg: we need the default mocks in place before we can use any of the `clients` methods clientsMock.AddDefaultMocks() @@ -332,7 +332,7 @@ func TestTriggersUpdateCommand(t *testing.T) { "--trigger-def, not json": { CmdArgs: []string{"--trigger-id", fakeTriggerID, "--trigger-def", "triggers/shortcut.ts"}, ExpectedErrorStrings: []string{"unexpected end of JSON"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockUpdateAppSelection(installedProdApp) clientsMock.ApiInterface.On("WorkflowsTriggersUpdate", mock.Anything, mock.Anything, mock.Anything).Return(types.DeployedTrigger{}, nil) clientsMock.ApiInterface.On("ListCollaborators", mock.Anything, mock.Anything, mock.Anything).Return([]types.SlackUser{}, nil) @@ -404,7 +404,7 @@ func TestTriggersUpdateCommand_MissingParameters(t *testing.T) { "initial api call fails, missing interactivity, succeeds on retry": { CmdArgs: []string{"--trigger-id", fakeTriggerID, "--workflow", "#/workflows/my_workflow"}, ExpectedOutputs: []string{"Trigger successfully updated!"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockUpdateAppSelection(installedProdApp) promptForInteractivityTeardown = setupMockUpdatePromptForInteractivity() // TODO: always a) mock out calls and b) call AddDefaultMocks before making any clients.* calls @@ -439,7 +439,7 @@ func TestTriggersUpdateCommand_MissingParameters(t *testing.T) { "initial api call fails, missing interactivity, fails on retry": { CmdArgs: []string{"--trigger-id", fakeTriggerID, "--workflow", "#/workflows/my_workflow"}, ExpectedErrorStrings: []string{"internal_error"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockUpdateAppSelection(installedProdApp) promptForInteractivityTeardown = setupMockUpdatePromptForInteractivity() // TODO: always a) mock out calls and b) call AddDefaultMocks before making any clients.* calls @@ -470,7 +470,7 @@ func TestTriggersUpdateCommand_MissingParameters(t *testing.T) { "initial api call fails, missing a different type": { CmdArgs: []string{"--trigger-id", fakeTriggerID, "--workflow", "#/workflows/my_workflow"}, ExpectedErrorStrings: []string{"invalid_trigger_inputs"}, - Setup: func(t *testing.T, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { + Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { appSelectTeardown = setupMockUpdateAppSelection(installedProdApp) promptForInteractivityTeardown = setupMockUpdatePromptForInteractivity() // TODO: always a) mock out calls and b) call AddDefaultMocks before making any clients.* calls diff --git a/test/testutil/commandtests.go b/test/testutil/commandtests.go index f9ad04b4..4f5f147c 100644 --- a/test/testutil/commandtests.go +++ b/test/testutil/commandtests.go @@ -15,11 +15,13 @@ package testutil import ( + "context" "fmt" "strings" "testing" "github.com/slackapi/slack-cli/internal/shared" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -27,14 +29,14 @@ import ( // CommandTests describes a single test case for a command. type CommandTests map[string]struct { - Setup func(*testing.T, *shared.ClientsMock, *shared.ClientFactory) // Optional - Teardown func() // Optional - CmdArgs []string // Required, Example: ["my-app", "--template", "slack-samples/deno-starter-template", "--verbose"] - ExpectedOutputs []string // Optional - ExpectedStdoutOutputs []string // Optional - ExpectedAsserts func(*testing.T, *shared.ClientsMock) // Optional - ExpectedError error // Optional - ExpectedErrorStrings []string // Optional + Setup func(*testing.T, context.Context, *shared.ClientsMock, *shared.ClientFactory) // Optional + Teardown func() // Optional + CmdArgs []string // Required, Example: ["my-app", "--template", "slack-samples/deno-starter-template", "--verbose"] + ExpectedOutputs []string // Optional + ExpectedStdoutOutputs []string // Optional + ExpectedAsserts func(*testing.T, *shared.ClientsMock) // Optional + ExpectedError error // Optional + ExpectedErrorStrings []string // Optional } // TableTestCommand will run a table test collection defined by commandTests for a command created by newCommandFunc @@ -42,6 +44,7 @@ func TableTestCommand(t *testing.T, commandTests CommandTests, newCommandFunc fu for name, tt := range commandTests { t.Run(name, func(t *testing.T) { // Create mocks + ctxMock := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() // Create clients that is mocked for testing @@ -54,7 +57,7 @@ func TableTestCommand(t *testing.T, commandTests CommandTests, newCommandFunc fu // Setup custom mocks (higher priority than default mocks) if tt.Setup != nil { - tt.Setup(t, clientsMock, clients) + tt.Setup(t, ctxMock, clientsMock, clients) } // Setup default mock actions @@ -62,7 +65,7 @@ func TableTestCommand(t *testing.T, commandTests CommandTests, newCommandFunc fu // Execute the command cmd.SetArgs(tt.CmdArgs) - err := cmd.Execute() + err := cmd.ExecuteContext(ctxMock) // Test failure mode if tt.ExpectedError != nil || tt.ExpectedErrorStrings != nil { From b8f68e96f415061d627c0e9d097ef5aeab6f3b05 Mon Sep 17 00:00:00 2001 From: Michael Brooks Date: Mon, 7 Apr 2025 19:35:49 -0600 Subject: [PATCH 04/13] test: mock context in TableTestCommand ExpectedAsserts --- cmd/app/add_test.go | 2 +- cmd/app/delete_test.go | 4 ++-- cmd/app/link_test.go | 16 +++++++--------- cmd/auth/login_test.go | 2 +- cmd/auth/logout_test.go | 20 ++++++++++---------- cmd/auth/revoke_test.go | 8 ++++---- cmd/collaborators/add_test.go | 6 +++--- cmd/collaborators/remove_test.go | 6 +++--- cmd/datastore/bulk_put_test.go | 8 ++++---- cmd/datastore/count_test.go | 12 ++++++------ cmd/datastore/query_test.go | 4 ++-- cmd/docgen/docgen_test.go | 6 +++--- cmd/env/add_test.go | 8 ++++---- cmd/env/list_test.go | 2 +- cmd/env/remove_test.go | 6 +++--- cmd/externalauth/add_secret_test.go | 10 +++++----- cmd/externalauth/add_test.go | 10 +++++----- cmd/externalauth/remove_test.go | 10 +++++----- cmd/externalauth/select_auth_test.go | 26 +++++++++++++------------- cmd/function/access_test.go | 2 +- cmd/manifest/info_test.go | 6 +++--- cmd/manifest/manifest_test.go | 2 +- cmd/openformresponse/export_test.go | 4 ++-- cmd/project/init_test.go | 4 ++-- cmd/project/samples_test.go | 2 +- cmd/triggers/create_test.go | 24 ++++++++++++------------ cmd/triggers/delete_test.go | 4 ++-- cmd/triggers/info_test.go | 10 +++++----- cmd/triggers/list_test.go | 8 ++++---- cmd/triggers/update_test.go | 20 ++++++++++---------- internal/pkg/platform/activity_test.go | 19 ++++++++++--------- test/testutil/commandtests.go | 4 ++-- 32 files changed, 137 insertions(+), 138 deletions(-) diff --git a/cmd/app/add_test.go b/cmd/app/add_test.go index 678a9208..1c77c8bc 100644 --- a/cmd/app/add_test.go +++ b/cmd/app/add_test.go @@ -352,7 +352,7 @@ func TestAppAddCommand(t *testing.T) { mockProjectConfig.On("Cache").Return(mockProjectCache) cm.Config.ProjectConfig = mockProjectConfig }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.ApiInterface.AssertCalled(t, "DeveloperAppInstall", mock.Anything, mock.Anything, mockOrgAuth.Token, mock.Anything, mock.Anything, mock.Anything, "T123", mock.Anything) }, }, diff --git a/cmd/app/delete_test.go b/cmd/app/delete_test.go index 1d962c27..a87aaf44 100644 --- a/cmd/app/delete_test.go +++ b/cmd/app/delete_test.go @@ -74,7 +74,7 @@ func TestAppsDeleteCommand(t *testing.T) { appClientMock.On("Remove", mock.Anything, mock.Anything).Return(fakeDeployedApp, nil) cf.AppClient().AppClientInterface = appClientMock }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.ApiInterface.AssertCalled(t, "DeleteApp", mock.Anything, mock.Anything, fakeDeployedApp.AppID) }, ExpectedStdoutOutputs: []string{ @@ -107,7 +107,7 @@ func TestAppsDeleteCommand(t *testing.T) { appClientMock.On("Remove", mock.Anything, mock.Anything).Return(fakeLocalApp, nil) cf.AppClient().AppClientInterface = appClientMock }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.ApiInterface.AssertCalled(t, "DeleteApp", mock.Anything, mock.Anything, fakeLocalApp.AppID) }, ExpectedStdoutOutputs: []string{ diff --git a/cmd/app/link_test.go b/cmd/app/link_test.go index b2fd09f4..c05c441a 100644 --- a/cmd/app/link_test.go +++ b/cmd/app/link_test.go @@ -95,7 +95,7 @@ func Test_Apps_Link(t *testing.T) { ).Return(api.GetAppStatusResult{}, nil) }, CmdArgs: []string{}, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { expectedApp := types.App{ AppID: mockLinkAppID1, TeamDomain: mockLinkSlackAuth1.TeamDomain, @@ -153,7 +153,7 @@ func Test_Apps_Link(t *testing.T) { ).Return(api.GetAppStatusResult{}, nil) }, CmdArgs: []string{}, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { expectedApp := types.App{ AppID: mockLinkAppID2, TeamDomain: mockLinkSlackAuth2.TeamDomain, @@ -220,7 +220,7 @@ func Test_Apps_Link(t *testing.T) { ).Return(api.GetAppStatusResult{}, nil) }, CmdArgs: []string{}, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { expectedApp := types.App{ AppID: mockLinkAppID1, TeamDomain: mockLinkSlackAuth1.TeamDomain, @@ -289,7 +289,7 @@ func Test_Apps_Link(t *testing.T) { ).Return(api.GetAppStatusResult{}, nil) }, CmdArgs: []string{}, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { expectedApp := types.App{ AppID: mockLinkAppID1, TeamDomain: mockLinkSlackAuth1.TeamDomain, @@ -365,7 +365,7 @@ func Test_Apps_Link(t *testing.T) { ).Return(api.GetAppStatusResult{}, nil) }, CmdArgs: []string{"--force"}, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { expectedApp := types.App{ AppID: mockLinkAppID1, TeamDomain: mockLinkSlackAuth2.TeamDomain, @@ -481,7 +481,7 @@ func Test_Apps_Link(t *testing.T) { ).Return(api.GetAppStatusResult{}, nil) }, CmdArgs: []string{}, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { expectedApp := types.App{ AppID: mockLinkAppID1, TeamDomain: mockLinkSlackAuth1.TeamDomain, @@ -518,9 +518,7 @@ func Test_Apps_Link(t *testing.T) { ).Return(false, nil) }, CmdArgs: []string{}, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { - ctx := t.Context() - + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { // Assert manifest confirmation prompt accepted cm.IO.AssertCalled(t, "ConfirmPrompt", mock.Anything, diff --git a/cmd/auth/login_test.go b/cmd/auth/login_test.go index 968e83b5..a085ef09 100644 --- a/cmd/auth/login_test.go +++ b/cmd/auth/login_test.go @@ -157,7 +157,7 @@ func TestLoginCommmand(t *testing.T) { nil, ) }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.ApiInterface.AssertCalled(t, "ExchangeAuthTicket", mock.Anything, mock.Anything, mockChallengeCode, mock.Anything) }, }, diff --git a/cmd/auth/logout_test.go b/cmd/auth/logout_test.go index 445f75ab..9f1b07d0 100644 --- a/cmd/auth/logout_test.go +++ b/cmd/auth/logout_test.go @@ -47,7 +47,7 @@ func TestLogoutCommand(t *testing.T) { clientsMock.AuthInterface.On("DeleteAuth", mock.Anything, fakeAuthsByTeamSlice[1]).Return(types.SlackAuth{}, nil) }, ExpectedOutputs: []string{"Authorization successfully revoked for all teams"}, - ExpectedAsserts: func(t *testing.T, clients *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clients *shared.ClientsMock) { clients.AuthInterface.AssertCalled(t, "RevokeToken", mock.Anything, fakeAuthsByTeamSlice[0].Token) clients.AuthInterface.AssertCalled(t, "RevokeToken", mock.Anything, fakeAuthsByTeamSlice[0].RefreshToken) clients.AuthInterface.AssertCalled(t, "RevokeToken", mock.Anything, fakeAuthsByTeamSlice[1].Token) @@ -74,7 +74,7 @@ func TestLogoutCommand(t *testing.T) { clientsMock.AuthInterface.On("DeleteAuth", mock.Anything, fakeAuthsByTeamSlice[0]).Return(types.SlackAuth{}, nil) }, ExpectedOutputs: []string{"Authorization successfully revoked for team1"}, - ExpectedAsserts: func(t *testing.T, clients *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clients *shared.ClientsMock) { clients.AuthInterface.AssertCalled(t, "RevokeToken", mock.Anything, fakeAuthsByTeamSlice[0].Token) clients.AuthInterface.AssertCalled(t, "RevokeToken", mock.Anything, fakeAuthsByTeamSlice[0].RefreshToken) clients.AuthInterface.AssertCalled(t, "DeleteAuth", mock.Anything, fakeAuthsByTeamSlice[0]) @@ -98,7 +98,7 @@ func TestLogoutCommand(t *testing.T) { clientsMock.AuthInterface.On("DeleteAuth", mock.Anything, fakeAuthsByTeamSlice[1]).Return(types.SlackAuth{}, nil) }, ExpectedOutputs: []string{"Authorization successfully revoked for team2"}, - ExpectedAsserts: func(t *testing.T, clients *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clients *shared.ClientsMock) { clients.AuthInterface.AssertCalled(t, "RevokeToken", mock.Anything, fakeAuthsByTeamSlice[1].Token) clients.AuthInterface.AssertCalled(t, "RevokeToken", mock.Anything, fakeAuthsByTeamSlice[1].RefreshToken) clients.AuthInterface.AssertCalled(t, "DeleteAuth", mock.Anything, fakeAuthsByTeamSlice[1]) @@ -108,7 +108,7 @@ func TestLogoutCommand(t *testing.T) { "require a team value with the flag": { CmdArgs: []string{"--team", ""}, ExpectedErrorStrings: []string{"The argument is missing from the --team flag (missing_flag)"}, - ExpectedAsserts: func(t *testing.T, clients *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clients *shared.ClientsMock) { clients.AuthInterface.AssertNotCalled(t, "RevokeToken") clients.IO.AssertNotCalled(t, "SelectPrompt", mock.Anything, "Select an workspace authorization to revoke", mock.Anything, mock.Anything) }, @@ -125,7 +125,7 @@ func TestLogoutCommand(t *testing.T) { }, nil) }, ExpectedErrorStrings: []string{"invalid_auth", "Cannot revoke authentication tokens for 'randomteamdomain'"}, - ExpectedAsserts: func(t *testing.T, clients *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clients *shared.ClientsMock) { clients.AuthInterface.AssertNotCalled(t, "RevokeToken") clients.IO.AssertCalled(t, "SelectPrompt", mock.Anything, "Select an authorization to revoke", mock.Anything, mock.Anything) }, @@ -151,7 +151,7 @@ func TestLogoutCommand(t *testing.T) { clientsMock.AuthInterface.On("DeleteAuth", mock.Anything, fakeAuthsByTeamSlice[1]).Return(types.SlackAuth{}, nil) }, ExpectedOutputs: []string{"Authorization successfully revoked for team2"}, - ExpectedAsserts: func(t *testing.T, clients *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clients *shared.ClientsMock) { clients.AuthInterface.AssertCalled(t, "RevokeToken", mock.Anything, fakeAuthsByTeamSlice[1].Token) clients.AuthInterface.AssertCalled(t, "RevokeToken", mock.Anything, fakeAuthsByTeamSlice[1].RefreshToken) clients.AuthInterface.AssertCalled(t, "DeleteAuth", mock.Anything, fakeAuthsByTeamSlice[1]) @@ -171,7 +171,7 @@ func TestLogoutCommand(t *testing.T) { clientsMock.AuthInterface.On("DeleteAuth", mock.Anything, fakeAuthsByTeamSlice[0]).Return(types.SlackAuth{}, nil) }, ExpectedOutputs: []string{"Authorization successfully revoked for team1"}, - ExpectedAsserts: func(t *testing.T, clients *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clients *shared.ClientsMock) { clients.AuthInterface.AssertCalled(t, "RevokeToken", mock.Anything, fakeAuthsByTeamSlice[0].Token) clients.AuthInterface.AssertCalled(t, "RevokeToken", mock.Anything, fakeAuthsByTeamSlice[0].RefreshToken) clients.AuthInterface.AssertCalled(t, "DeleteAuth", mock.Anything, fakeAuthsByTeamSlice[0]) @@ -192,7 +192,7 @@ func TestLogoutCommand(t *testing.T) { }, nil) }, ExpectedErrorStrings: []string{"invalid_auth", "Cannot revoke authentication tokens for 'anotherteam'"}, - ExpectedAsserts: func(t *testing.T, clients *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clients *shared.ClientsMock) { clients.AuthInterface.AssertNotCalled(t, "RevokeToken") clients.IO.AssertCalled(t, "SelectPrompt", mock.Anything, "Select an authorization to revoke", mock.Anything, mock.Anything) }, @@ -203,7 +203,7 @@ func TestLogoutCommand(t *testing.T) { clientsMock.AuthInterface.On("Auths", mock.Anything).Return([]types.SlackAuth{}, nil) }, ExpectedOutputs: []string{"All authorizations successfully revoked"}, - ExpectedAsserts: func(t *testing.T, clients *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clients *shared.ClientsMock) { clients.AuthInterface.AssertNotCalled(t, "RevokeToken") clients.IO.AssertNotCalled(t, "SelectPrompt", mock.Anything, "Select an authorization to revoke", mock.Anything, mock.Anything) }, @@ -219,7 +219,7 @@ func TestLogoutCommand(t *testing.T) { Option: "someteam", }, nil) }, - ExpectedAsserts: func(t *testing.T, clients *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clients *shared.ClientsMock) { clients.AuthInterface.AssertNotCalled(t, "RevokeToken") clients.IO.AssertCalled(t, "SelectPrompt", mock.Anything, "Select an authorization to revoke", mock.Anything, mock.Anything) }, diff --git a/cmd/auth/revoke_test.go b/cmd/auth/revoke_test.go index e0cc37e0..997e18a7 100644 --- a/cmd/auth/revoke_test.go +++ b/cmd/auth/revoke_test.go @@ -41,7 +41,7 @@ func TestRevokeCommand(t *testing.T) { clientsMock.AuthInterface.On("RevokeToken", mock.Anything, "xoxp-example-1234").Return(nil) }, ExpectedOutputs: []string{"Authorization successfully revoked"}, - ExpectedAsserts: func(t *testing.T, clients *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clients *shared.ClientsMock) { clients.AuthInterface.AssertCalled(t, "RevokeToken", mock.Anything, "xoxp-example-1234") }, }, @@ -53,7 +53,7 @@ func TestRevokeCommand(t *testing.T) { })).Return(iostreams.PasswordPromptResponse{}, slackerror.New(slackerror.ErrMissingFlag)) }, ExpectedErrorStrings: []string{"Failed to collect a token to revoke", "no_token_found", "missing_flag"}, - ExpectedAsserts: func(t *testing.T, clients *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clients *shared.ClientsMock) { clients.AuthInterface.AssertNotCalled(t, "RevokeToken") }, }, @@ -69,7 +69,7 @@ func TestRevokeCommand(t *testing.T) { clientsMock.AuthInterface.On("RevokeToken", mock.Anything, "xoxp-example-1234").Return(nil) }, ExpectedOutputs: []string{"Authorization successfully revoked"}, - ExpectedAsserts: func(t *testing.T, clients *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clients *shared.ClientsMock) { clients.AuthInterface.AssertCalled(t, "RevokeToken", mock.Anything, "xoxp-example-1234") }, }, @@ -85,7 +85,7 @@ func TestRevokeCommand(t *testing.T) { clientsMock.AuthInterface.On("RevokeToken", mock.Anything, "xoxp-example-1234").Return(slackerror.New(slackerror.ErrNotAuthed)) }, ExpectedError: slackerror.New(slackerror.ErrNotAuthed), - ExpectedAsserts: func(t *testing.T, clients *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clients *shared.ClientsMock) { clients.AuthInterface.AssertCalled(t, "RevokeToken", mock.Anything, "xoxp-example-1234") clients.IO.AssertNotCalled(t, "PrintTrace", mock.Anything, slacktrace.AuthRevokeSuccess) }, diff --git a/cmd/collaborators/add_test.go b/cmd/collaborators/add_test.go index 32945485..05059f62 100644 --- a/cmd/collaborators/add_test.go +++ b/cmd/collaborators/add_test.go @@ -45,7 +45,7 @@ func TestAddCommand(t *testing.T) { "A123", types.SlackUser{ID: "U123", PermissionType: types.READER}).Return(nil) }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.ApiInterface.AssertCalled(t, "AddCollaborator", mock.Anything, mock.Anything, "A123", types.SlackUser{ID: "U123", PermissionType: types.READER}) @@ -70,7 +70,7 @@ func TestAddCommand(t *testing.T) { types.SlackUser{Email: "joe.smith@company.com", PermissionType: types.OWNER}).Return(nil) addFlags.permissionType = "owner" }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.ApiInterface.AssertCalled(t, "AddCollaborator", mock.Anything, mock.Anything, "A123", types.SlackUser{Email: "joe.smith@company.com", PermissionType: types.OWNER}) @@ -90,7 +90,7 @@ func TestAddCommand(t *testing.T) { cm.ApiInterface.On("AddCollaborator", mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return(nil) }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.ApiInterface.AssertCalled(t, "AddCollaborator", mock.Anything, mock.Anything, "A123", types.SlackUser{Email: "joe.smith@company.com", PermissionType: types.OWNER}) diff --git a/cmd/collaborators/remove_test.go b/cmd/collaborators/remove_test.go index 70f31076..338a5bb9 100644 --- a/cmd/collaborators/remove_test.go +++ b/cmd/collaborators/remove_test.go @@ -59,7 +59,7 @@ func TestRemoveCommand(t *testing.T) { cm.ApiInterface.On("RemoveCollaborator", mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return(nil) }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { collaborator := types.SlackUser{ ID: "USLACKBOT", } @@ -83,7 +83,7 @@ func TestRemoveCommand(t *testing.T) { cm.IO.On("SelectPrompt", mock.Anything, "Remove a collaborator", mock.Anything, mock.Anything). Return(iostreams.SelectPromptResponse{Prompt: true, Index: 1}, nil) }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.ApiInterface.AssertCalled(t, "RemoveCollaborator", mock.Anything, mock.Anything, "A001", mockCollaborators[1]) cm.IO.AssertCalled(t, "PrintTrace", mock.Anything, slacktrace.CollaboratorRemoveSuccess, mock.Anything) cm.IO.AssertCalled(t, "PrintTrace", mock.Anything, slacktrace.CollaboratorRemoveCollaborator, []string{"reader@slack.com"}) @@ -106,7 +106,7 @@ func TestRemoveCommand(t *testing.T) { cm.IO.On("ConfirmPrompt", mock.Anything, "Are you sure you want to remove yourself?", mock.Anything, mock.Anything). Return(false, nil) }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.ApiInterface.AssertNotCalled(t, "RemoveCollaborator", mock.Anything, mock.Anything, mock.Anything, mock.Anything) }, ExpectedError: slackerror.New(slackerror.ErrProcessInterrupted), diff --git a/cmd/datastore/bulk_put_test.go b/cmd/datastore/bulk_put_test.go index d5749372..18128f07 100644 --- a/cmd/datastore/bulk_put_test.go +++ b/cmd/datastore/bulk_put_test.go @@ -243,7 +243,7 @@ func TestBulkPutCommandImport(t *testing.T) { *cf = *shared.NewClientFactory(cm.MockClientFactory()) }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { status, _ := importProgressSpinner.Status() assert.Contains(t, status, "Successfully imported (30) items! (0) items failed to be imported. Total processed items is (30)") @@ -273,7 +273,7 @@ func TestBulkPutCommandImport(t *testing.T) { *cf = *shared.NewClientFactory(cm.MockClientFactory()) }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { status, _ := importProgressSpinner.Status() assert.Contains(t, status, "Successfully imported (30) items! (5) items failed to be imported. Total processed items is (35)") @@ -316,7 +316,7 @@ func TestBulkPutCommandImport(t *testing.T) { *cf = *shared.NewClientFactory(cm.MockClientFactory()) }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { status, _ := importProgressSpinner.Status() assert.Contains(t, status, "Successfully imported (5000) items! (0) items failed to be imported. Total processed items is (5000)") }, @@ -343,7 +343,7 @@ func TestBulkPutCommandImport(t *testing.T) { *cf = *shared.NewClientFactory(cm.MockClientFactory()) }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { status, _ := importProgressSpinner.Status() assert.Contains(t, status, "Successfully imported (2) items! (0) items failed to be imported. Total processed items is (2)") diff --git a/cmd/datastore/count_test.go b/cmd/datastore/count_test.go index c64bd56d..65703cbc 100644 --- a/cmd/datastore/count_test.go +++ b/cmd/datastore/count_test.go @@ -135,7 +135,7 @@ func TestCountCommand(t *testing.T) { cm.ApiInterface.On("AppsDatastoreCount", mock.Anything, mock.Anything, mock.Anything). Return(types.AppDatastoreCountResult{Datastore: "tasks", Count: 12}, nil) }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.IO.AssertCalled(t, "PrintTrace", mock.Anything, slacktrace.DatastoreCountSuccess, mock.Anything) cm.IO.AssertCalled(t, "PrintTrace", mock.Anything, slacktrace.DatastoreCountTotal, []string{"12"}) cm.IO.AssertCalled(t, "PrintTrace", mock.Anything, slacktrace.DatastoreCountDatastore, []string{"tasks"}) @@ -154,7 +154,7 @@ func TestCountCommand(t *testing.T) { cm.ApiInterface.On("AppsDatastoreCount", mock.Anything, mock.Anything, mock.Anything). Return(types.AppDatastoreCountResult{Datastore: "tasks", Count: 12}, nil) }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.IO.AssertCalled(t, "PrintTrace", mock.Anything, slacktrace.DatastoreCountSuccess, mock.Anything) cm.IO.AssertCalled(t, "PrintTrace", mock.Anything, slacktrace.DatastoreCountTotal, []string{"12"}) cm.IO.AssertCalled(t, "PrintTrace", mock.Anything, slacktrace.DatastoreCountDatastore, []string{"tasks"}) @@ -175,7 +175,7 @@ func TestCountCommand(t *testing.T) { cm.ApiInterface.On("AppsDatastoreCount", mock.Anything, mock.Anything, mock.Anything). Return(types.AppDatastoreCountResult{Datastore: "tasks", Count: 12}, nil) }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.IO.AssertCalled(t, "PrintTrace", mock.Anything, slacktrace.DatastoreCountSuccess, mock.Anything) cm.IO.AssertCalled(t, "PrintTrace", mock.Anything, slacktrace.DatastoreCountTotal, []string{"12"}) cm.IO.AssertCalled(t, "PrintTrace", mock.Anything, slacktrace.DatastoreCountDatastore, []string{"tasks"}) @@ -206,7 +206,7 @@ func TestCountCommand(t *testing.T) { cm.ApiInterface.On("AppsDatastoreCount", mock.Anything, mock.Anything, mock.Anything). Return(types.AppDatastoreCountResult{Datastore: "tasks", Count: 12}, nil) }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.IO.AssertCalled(t, "PrintTrace", mock.Anything, slacktrace.DatastoreCountSuccess, mock.Anything) cm.IO.AssertCalled(t, "PrintTrace", mock.Anything, slacktrace.DatastoreCountTotal, []string{"12"}) cm.IO.AssertCalled(t, "PrintTrace", mock.Anything, slacktrace.DatastoreCountDatastore, []string{"tasks"}) @@ -254,7 +254,7 @@ func TestCountCommand(t *testing.T) { cm.ApiInterface.On("AppsDatastoreCount", mock.Anything, mock.Anything, mock.Anything). Return(types.AppDatastoreCountResult{Datastore: "numbers", Count: 12}, nil) }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.IO.AssertCalled(t, "PrintTrace", mock.Anything, slacktrace.DatastoreCountSuccess, mock.Anything) cm.IO.AssertCalled(t, "PrintTrace", mock.Anything, slacktrace.DatastoreCountTotal, []string{"12"}) cm.IO.AssertCalled(t, "PrintTrace", mock.Anything, slacktrace.DatastoreCountDatastore, []string{"numbers"}) @@ -310,7 +310,7 @@ func TestCountCommand(t *testing.T) { cm.ApiInterface.On("AppsDatastoreCount", mock.Anything, mock.Anything, mock.Anything). Return(types.AppDatastoreCountResult{Datastore: "numbers", Count: 6}, nil) }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.IO.AssertCalled(t, "PrintTrace", mock.Anything, slacktrace.DatastoreCountSuccess, mock.Anything) cm.IO.AssertCalled(t, "PrintTrace", mock.Anything, slacktrace.DatastoreCountTotal, []string{"6"}) cm.IO.AssertCalled(t, "PrintTrace", mock.Anything, slacktrace.DatastoreCountDatastore, []string{"numbers"}) diff --git a/cmd/datastore/query_test.go b/cmd/datastore/query_test.go index e858fdaf..e7b74363 100644 --- a/cmd/datastore/query_test.go +++ b/cmd/datastore/query_test.go @@ -399,7 +399,7 @@ func TestQueryCommandExport(t *testing.T) { *cf = *shared.NewClientFactory(cm.MockClientFactory()) }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { status, _ := exportProgressSpinner.Status() assert.Contains(t, status, "Successfully exported (10) items!") @@ -428,7 +428,7 @@ func TestQueryCommandExport(t *testing.T) { *cf = *shared.NewClientFactory(cm.MockClientFactory()) }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { status, _ := exportProgressSpinner.Status() assert.Contains(t, status, "Successfully exported (10000) items!") }, diff --git a/cmd/docgen/docgen_test.go b/cmd/docgen/docgen_test.go index c283e159..67752b3c 100644 --- a/cmd/docgen/docgen_test.go +++ b/cmd/docgen/docgen_test.go @@ -39,7 +39,7 @@ func TestNewDocsCommand(t *testing.T) { ExpectedOutputs: []string{ filepath.Join(slackdeps.MockWorkingDirectory, "docs"), }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.Cobra.AssertCalled( t, "GenMarkdownTree", @@ -83,7 +83,7 @@ func TestNewDocsCommand(t *testing.T) { ExpectedOutputs: []string{ filepath.Join(slackdeps.MockWorkingDirectory, "markdown-docs"), }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.Cobra.AssertCalled( t, "GenMarkdownTree", @@ -125,7 +125,7 @@ func TestNewDocsCommand(t *testing.T) { }, CmdArgs: []string{}, ExpectedOutputs: []string{"References saved to: docs"}, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.Cobra.AssertCalled( t, "GenMarkdownTree", diff --git a/cmd/env/add_test.go b/cmd/env/add_test.go index c3aceafe..94ee8178 100644 --- a/cmd/env/add_test.go +++ b/cmd/env/add_test.go @@ -147,7 +147,7 @@ func Test_Env_AddCommand(t *testing.T) { Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { setupEnvAddCommandMocks(cm, cf) }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.ApiInterface.AssertCalled( t, "AddVariable", @@ -185,7 +185,7 @@ func Test_Env_AddCommand(t *testing.T) { nil, ) }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.ApiInterface.AssertCalled( t, "AddVariable", @@ -216,7 +216,7 @@ func Test_Env_AddCommand(t *testing.T) { nil, ) }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.ApiInterface.AssertCalled( t, "AddVariable", @@ -256,7 +256,7 @@ func Test_Env_AddCommand(t *testing.T) { nil, ) }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.ApiInterface.AssertCalled( t, "AddVariable", diff --git a/cmd/env/list_test.go b/cmd/env/list_test.go index b261f53f..07d8787a 100644 --- a/cmd/env/list_test.go +++ b/cmd/env/list_test.go @@ -148,7 +148,7 @@ func Test_Env_ListCommand(t *testing.T) { teamAppSelectPromptFunc = appSelectMock.TeamAppSelectPrompt appSelectMock.On("TeamAppSelectPrompt").Return(prompts.SelectedApp{}, nil) }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.ApiInterface.AssertCalled( t, "ListVariables", diff --git a/cmd/env/remove_test.go b/cmd/env/remove_test.go index b24d1b4e..d75676a7 100644 --- a/cmd/env/remove_test.go +++ b/cmd/env/remove_test.go @@ -155,7 +155,7 @@ func Test_Env_RemoveCommand(t *testing.T) { teamAppSelectPromptFunc = appSelectMock.TeamAppSelectPrompt appSelectMock.On("TeamAppSelectPrompt").Return(prompts.SelectedApp{}, nil) }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.ApiInterface.AssertCalled( t, "RemoveVariable", @@ -214,7 +214,7 @@ func Test_Env_RemoveCommand(t *testing.T) { teamAppSelectPromptFunc = appSelectMock.TeamAppSelectPrompt appSelectMock.On("TeamAppSelectPrompt").Return(prompts.SelectedApp{}, nil) }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.ApiInterface.AssertCalled( t, "ListVariables", @@ -248,7 +248,7 @@ func Test_Env_RemoveCommand(t *testing.T) { teamAppSelectPromptFunc = appSelectMock.TeamAppSelectPrompt appSelectMock.On("TeamAppSelectPrompt").Return(prompts.SelectedApp{}, nil) }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.ApiInterface.AssertCalled( t, "ListVariables", diff --git a/cmd/externalauth/add_secret_test.go b/cmd/externalauth/add_secret_test.go index 6ae691e7..9b43085c 100644 --- a/cmd/externalauth/add_secret_test.go +++ b/cmd/externalauth/add_secret_test.go @@ -167,7 +167,7 @@ func TestExternalAuthAddClientSecretCommand(t *testing.T) { require.NoError(t, err, "Cant write apps.json") }, ExpectedOutputs: []string{}, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "AppsAuthExternalClientSecretAdd", mock.Anything, mock.Anything, fakeAppID, "provider_a", "secret_key_1234") }, }, @@ -202,7 +202,7 @@ func TestExternalAuthAddClientSecretCommand(t *testing.T) { require.NoError(t, err, "Cant write apps.json") }, ExpectedOutputs: []string{}, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "AppsAuthExternalClientSecretAdd", mock.Anything, mock.Anything, fakeAppID, "provider_a", "secret_key_1234") }, }, @@ -235,7 +235,7 @@ func TestExternalAuthAddClientSecretCommand(t *testing.T) { require.NoError(t, err, "Cant write apps.json") }, ExpectedOutputs: []string{}, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "AppsAuthExternalClientSecretAdd", mock.Anything, mock.Anything, fakeAppID, "provider_a", "secret") }, }, @@ -267,7 +267,7 @@ func TestExternalAuthAddClientSecretCommand(t *testing.T) { err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) require.NoError(t, err, "Cant write apps.json") }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "AppsAuthExternalClientSecretAdd", mock.Anything, mock.Anything, fakeAppID, "provider_a", "secret") }, }, @@ -293,7 +293,7 @@ func TestExternalAuthAddClientSecretCommand(t *testing.T) { require.NoError(t, err, "Cant write apps.json") }, ExpectedErrorStrings: []string{"test error"}, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertNotCalled(t, "AppsAuthExternalClientSecretAdd", mock.Anything, mock.Anything, fakeAppID, "provider_a") }, }, diff --git a/cmd/externalauth/add_test.go b/cmd/externalauth/add_test.go index b4c93ba2..383c2aa9 100644 --- a/cmd/externalauth/add_test.go +++ b/cmd/externalauth/add_test.go @@ -159,7 +159,7 @@ func TestExternalAuthAddCommand(t *testing.T) { err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) require.NoError(t, err, "Cant write apps.json") }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "AppsAuthExternalStart", mock.Anything, mock.Anything, fakeAppID, "provider_a") clientsMock.Browser.AssertCalled(t, "OpenURL", "https://authorizationurl1.com") }, @@ -187,7 +187,7 @@ func TestExternalAuthAddCommand(t *testing.T) { err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) require.NoError(t, err, "Cant write apps.json") }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertNotCalled(t, "AppsAuthExternalStart") clientsMock.Browser.AssertNotCalled(t, "OpenURL") }, @@ -215,7 +215,7 @@ func TestExternalAuthAddCommand(t *testing.T) { err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) require.NoError(t, err, "Cant write apps.json") }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "AppsAuthExternalStart", mock.Anything, mock.Anything, fakeAppID, "provider_a") clientsMock.Browser.AssertCalled(t, "OpenURL", "https://authorizationurl3.com/provider") }, @@ -244,7 +244,7 @@ func TestExternalAuthAddCommand(t *testing.T) { err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) require.NoError(t, err, "Cant write apps.json") }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertNotCalled(t, "AppsAuthExternalStart") clientsMock.Browser.AssertNotCalled(t, "OpenURL") }, @@ -265,7 +265,7 @@ func TestExternalAuthAddCommand(t *testing.T) { require.NoError(t, err, "Cant write apps.json") }, ExpectedErrorStrings: []string{"test error"}, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertNotCalled(t, "AppsAuthExternalStart", mock.Anything, mock.Anything, fakeAppID, "provider_a") clientsMock.Browser.AssertNotCalled(t, "OpenURL") }, diff --git a/cmd/externalauth/remove_test.go b/cmd/externalauth/remove_test.go index 85ca6210..ec8edae0 100644 --- a/cmd/externalauth/remove_test.go +++ b/cmd/externalauth/remove_test.go @@ -160,7 +160,7 @@ func TestExternalAuthRemoveCommand(t *testing.T) { err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) require.NoError(t, err, "Cant write apps.json") }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "AppsAuthExternalDelete", mock.Anything, mock.Anything, fakeAppID, "provider_a", "") }, }, @@ -185,7 +185,7 @@ func TestExternalAuthRemoveCommand(t *testing.T) { err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) require.NoError(t, err, "Cant write apps.json") }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "AppsAuthExternalDelete", mock.Anything, mock.Anything, fakeAppID, "provider_a", "") }, }, @@ -210,7 +210,7 @@ func TestExternalAuthRemoveCommand(t *testing.T) { require.NoError(t, err, "Cant write apps.json") clientsMock.IO.On("ConfirmPrompt", mock.Anything, "Are you sure you want to remove all tokens for this app from your current team/org?", mock.Anything).Return(true) }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "AppsAuthExternalDelete", mock.Anything, mock.Anything, fakeAppID, "", "") }, }, @@ -236,7 +236,7 @@ func TestExternalAuthRemoveCommand(t *testing.T) { clientsMock.IO.On("ConfirmPrompt", mock.Anything, "Are you sure you want to remove all tokens for this app relevant to the specified provider from your current team/org?", mock.Anything).Return(true) }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "AppsAuthExternalDelete", mock.Anything, mock.Anything, fakeAppID, "provider_a", "") }, }, @@ -253,7 +253,7 @@ func TestExternalAuthRemoveCommand(t *testing.T) { require.NoError(t, err, "Cant write apps.json") clientsMock.IO.On("ConfirmPrompt", mock.Anything, "Are you sure you want to remove all tokens for this app from your current team/org?", mock.Anything).Return(true) }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "AppsAuthExternalDelete", mock.Anything, mock.Anything, fakeAppID, "", "") }, }, diff --git a/cmd/externalauth/select_auth_test.go b/cmd/externalauth/select_auth_test.go index 9a5ff9a9..2bd276a7 100644 --- a/cmd/externalauth/select_auth_test.go +++ b/cmd/externalauth/select_auth_test.go @@ -248,7 +248,7 @@ func TestExternalAuthSelectAuthCommand(t *testing.T) { Return(types.ExternalAuthorizationInfoLists{}, errors.New("test error")) }, ExpectedErrorStrings: []string{"test error"}, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertNotCalled(t, "AppsAuthExternalSelectAuth", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything) }, }, @@ -263,7 +263,7 @@ func TestExternalAuthSelectAuthCommand(t *testing.T) { })).Return(iostreams.SelectPromptResponse{}, slackerror.New(slackerror.ErrMissingOptions)) }, ExpectedErrorStrings: []string{"No workflows found that require developer authorization"}, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertNotCalled(t, "AppsAuthExternalSelectAuth", mock.Anything, mock.Anything, fakeAppID, mock.Anything, mock.Anything) }, }, @@ -281,7 +281,7 @@ func TestExternalAuthSelectAuthCommand(t *testing.T) { }, nil) }, ExpectedErrorStrings: []string{"Workflow not found"}, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertNotCalled(t, "AppsAuthExternalSelectAuth", mock.Anything, mock.Anything, fakeAppID, mock.Anything, mock.Anything, mock.Anything) }, }, @@ -296,7 +296,7 @@ func TestExternalAuthSelectAuthCommand(t *testing.T) { })).Return(iostreams.SelectPromptResponse{}, slackerror.New(slackerror.ErrMissingOptions)) }, ExpectedErrorStrings: []string{"No workflows found that require developer authorization"}, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertNotCalled(t, "AppsAuthExternalSelectAuth", mock.Anything, mock.Anything, fakeAppID, mock.Anything, mock.Anything, mock.Anything) }, }, @@ -314,7 +314,7 @@ func TestExternalAuthSelectAuthCommand(t *testing.T) { }, nil) }, ExpectedErrorStrings: []string{"Workflow not found"}, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertNotCalled(t, "AppsAuthExternalSelectAuth", mock.Anything, mock.Anything, fakeAppID, mock.Anything, mock.Anything, mock.Anything) }, }, @@ -340,7 +340,7 @@ func TestExternalAuthSelectAuthCommand(t *testing.T) { }, nil) }, ExpectedErrorStrings: []string{"No connected accounts found"}, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertNotCalled(t, "AppsAuthExternalSelectAuth", mock.Anything, mock.Anything, fakeAppID, mock.Anything, mock.Anything, mock.Anything) }, }, @@ -372,7 +372,7 @@ func TestExternalAuthSelectAuthCommand(t *testing.T) { }, nil) }, ExpectedErrorStrings: []string{"Workflow not found"}, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertNotCalled(t, "AppsAuthExternalSelectAuth", mock.Anything, mock.Anything, fakeAppID, mock.Anything, mock.Anything, mock.Anything) }, }, @@ -397,7 +397,7 @@ func TestExternalAuthSelectAuthCommand(t *testing.T) { }, nil) }, ExpectedErrorStrings: []string{"No connected accounts found"}, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertNotCalled(t, "AppsAuthExternalSelectAuth", mock.Anything, mock.Anything, fakeAppID, mock.Anything, mock.Anything, mock.Anything) }, }, @@ -421,7 +421,7 @@ func TestExternalAuthSelectAuthCommand(t *testing.T) { }, nil) }, ExpectedErrorStrings: []string{"Provider is not used in the selected workflow"}, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertNotCalled(t, "AppsAuthExternalSelectAuth", mock.Anything, mock.Anything, fakeAppID, mock.Anything, mock.Anything, mock.Anything) }, }, @@ -447,7 +447,7 @@ func TestExternalAuthSelectAuthCommand(t *testing.T) { }, nil) }, ExpectedErrorStrings: []string{"No connected accounts found"}, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertNotCalled(t, "AppsAuthExternalSelectAuth", mock.Anything, mock.Anything, fakeAppID, mock.Anything, mock.Anything, mock.Anything) }, }, @@ -479,7 +479,7 @@ func TestExternalAuthSelectAuthCommand(t *testing.T) { }, nil) }, ExpectedOutputs: []string{"Workflow #/workflows/my_callback_id2 will use developer account xyz2@salesforce.com when making calls to provider_a APIs"}, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "AppsAuthExternalSelectAuth", mock.Anything, mock.Anything, fakeAppID, mock.Anything, mock.Anything, mock.Anything) }, }, @@ -510,7 +510,7 @@ func TestExternalAuthSelectAuthCommand(t *testing.T) { }, nil) }, ExpectedErrorStrings: []string{"Account is not used in the selected workflow"}, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertNotCalled(t, "AppsAuthExternalSelectAuth", mock.Anything, mock.Anything, fakeAppID, mock.Anything, mock.Anything, mock.Anything) }, }, @@ -541,7 +541,7 @@ func TestExternalAuthSelectAuthCommand(t *testing.T) { }, nil) }, ExpectedOutputs: []string{"Workflow #/workflows/my_callback_id2 will use developer account xyz2@salesforce.com when making calls to provider_a APIs"}, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "AppsAuthExternalSelectAuth", mock.Anything, mock.Anything, fakeAppID, mock.Anything, mock.Anything, mock.Anything) }, }}, func(clients *shared.ClientFactory) *cobra.Command { diff --git a/cmd/function/access_test.go b/cmd/function/access_test.go index 1ffd6947..0df101af 100644 --- a/cmd/function/access_test.go +++ b/cmd/function/access_test.go @@ -132,7 +132,7 @@ func TestFunctionDistributionCommand(t *testing.T) { err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) require.NoError(t, err, "Cant write apps.json") }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.ApiInterface.AssertNotCalled(t, "FunctionDistributionAddUsers") cm.ApiInterface.AssertNotCalled(t, "FunctionDistributionRemoveUsers") cm.ApiInterface.AssertNotCalled(t, "FunctionDistributionSet") diff --git a/cmd/manifest/info_test.go b/cmd/manifest/info_test.go index 70e730ef..48903f0d 100644 --- a/cmd/manifest/info_test.go +++ b/cmd/manifest/info_test.go @@ -71,7 +71,7 @@ func TestInfoCommand(t *testing.T) { cf.AppClient().Manifest = manifestMock cf.SDKConfig = hooks.NewSDKConfigMock() }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { mockManifest := types.AppManifest{ DisplayInformation: types.DisplayInformation{ Name: "app001", @@ -102,7 +102,7 @@ func TestInfoCommand(t *testing.T) { cf.AppClient().Manifest = manifestMock cf.SDKConfig = hooks.NewSDKConfigMock() }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { mockManifest := types.AppManifest{ DisplayInformation: types.DisplayInformation{ Name: "app002", @@ -139,7 +139,7 @@ func TestInfoCommand(t *testing.T) { mockProjectConfig.On("GetManifestSource", mock.Anything).Return(config.MANIFEST_SOURCE_LOCAL, nil) cm.Config.ProjectConfig = mockProjectConfig }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { mockManifest := types.AppManifest{ DisplayInformation: types.DisplayInformation{ Name: "app002", diff --git a/cmd/manifest/manifest_test.go b/cmd/manifest/manifest_test.go index 8c868308..75a30488 100644 --- a/cmd/manifest/manifest_test.go +++ b/cmd/manifest/manifest_test.go @@ -54,7 +54,7 @@ func TestManifestCommand(t *testing.T) { cf.AppClient().Manifest = manifestMock cf.SDKConfig = hooks.NewSDKConfigMock() }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { mockManifest := types.AppManifest{ DisplayInformation: types.DisplayInformation{ Name: "app001", diff --git a/cmd/openformresponse/export_test.go b/cmd/openformresponse/export_test.go index 58c6dfcb..1eb762c5 100644 --- a/cmd/openformresponse/export_test.go +++ b/cmd/openformresponse/export_test.go @@ -54,7 +54,7 @@ func TestExportCommand(t *testing.T) { Teardown: func() { appSelectTeardown() }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.ApiInterface.AssertCalled(t, "StepsResponsesExport", mock.Anything, token, "#/workflows/my_workflow", appId, "stepId") }, }, @@ -68,7 +68,7 @@ func TestExportCommand(t *testing.T) { Teardown: func() { appSelectTeardown() }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.ApiInterface.AssertCalled(t, "StepsResponsesExport", mock.Anything, token, "#/workflows/my_workflow", appId, "stepId") }, }, diff --git a/cmd/project/init_test.go b/cmd/project/init_test.go index 530c568c..06c54591 100644 --- a/cmd/project/init_test.go +++ b/cmd/project/init_test.go @@ -72,7 +72,7 @@ func Test_Project_InitCommand(t *testing.T) { "App Link", // Assert section header "Next steps to begin development", // Assert section header }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { // Assert installing project dependencies output := cm.GetCombinedOutput() require.Contains(t, output, "Installed project dependencies") @@ -161,7 +161,7 @@ func Test_Project_InitCommand(t *testing.T) { "App Link", // Assert section header "Next steps to begin development", // Assert section header }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { // Assert prompt to add existing apps was called cm.IO.AssertCalled(t, "ConfirmPrompt", mock.Anything, diff --git a/cmd/project/samples_test.go b/cmd/project/samples_test.go index 2ec13757..0bc7e96d 100644 --- a/cmd/project/samples_test.go +++ b/cmd/project/samples_test.go @@ -67,7 +67,7 @@ func TestSamplesCommand(t *testing.T) { return "", nil } }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { for _, call := range cm.IO.Calls { switch call.Method { case "SelectPrompt": diff --git a/cmd/triggers/create_test.go b/cmd/triggers/create_test.go index 2733a98f..b4b3e70b 100644 --- a/cmd/triggers/create_test.go +++ b/cmd/triggers/create_test.go @@ -75,7 +75,7 @@ func TestTriggersCreateCommand(t *testing.T) { Teardown: func() { appSelectTeardown() }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { expectedTriggerRequest := api.TriggerRequest{ Type: types.TriggerTypeShortcut, Shortcut: &api.Shortcut{}, @@ -106,7 +106,7 @@ func TestTriggersCreateCommand(t *testing.T) { Teardown: func() { appSelectTeardown() }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { expectedTriggerRequest := api.TriggerRequest{ Type: types.TriggerTypeShortcut, Name: "unit tests", @@ -137,7 +137,7 @@ func TestTriggersCreateCommand(t *testing.T) { Teardown: func() { appSelectTeardown() }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { expectedTriggerRequest := api.TriggerRequest{ Type: types.TriggerTypeShortcut, Name: "unit tests", @@ -173,7 +173,7 @@ func TestTriggersCreateCommand(t *testing.T) { Teardown: func() { appSelectTeardown() }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { expectedTriggerRequest := api.TriggerRequest{ Type: types.TriggerTypeShortcut, Name: "unit tests", @@ -236,7 +236,7 @@ func TestTriggersCreateCommand(t *testing.T) { Teardown: func() { appSelectTeardown() }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { expectedTriggerRequest := api.TriggerRequest{ Type: types.TriggerTypeScheduled, Name: "name", @@ -285,7 +285,7 @@ func TestTriggersCreateCommand(t *testing.T) { Teardown: func() { appSelectTeardown() }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.HookExecutor.AssertCalled(t, "Execute", mock.Anything) clientsMock.ApiInterface.AssertCalled(t, "WorkflowsTriggersCreate", mock.Anything, mock.Anything, mock.Anything) }, @@ -307,7 +307,7 @@ func TestTriggersCreateCommand(t *testing.T) { Teardown: func() { appSelectTeardown() }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertNotCalled(t, "WorkflowsTriggersCreate", mock.Anything, mock.Anything, mock.Anything) }, }, @@ -375,7 +375,7 @@ func TestTriggersCreateCommand_MissingParameters(t *testing.T) { err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) require.NoError(t, err, "Cant write apps.json") }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "WorkflowsTriggersCreate", mock.Anything, mock.Anything, triggerRequestMissingInputs) clientsMock.ApiInterface.AssertCalled(t, "WorkflowsTriggersCreate", mock.Anything, mock.Anything, triggerRequestWithInteractivityInputs) }, @@ -406,7 +406,7 @@ func TestTriggersCreateCommand_MissingParameters(t *testing.T) { err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) require.NoError(t, err, "Cant write apps.json") }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "WorkflowsTriggersCreate", mock.Anything, mock.Anything, triggerRequestMissingInputs) clientsMock.ApiInterface.AssertCalled(t, "WorkflowsTriggersCreate", mock.Anything, mock.Anything, triggerRequestWithInteractivityInputs) }, @@ -435,7 +435,7 @@ func TestTriggersCreateCommand_MissingParameters(t *testing.T) { err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) require.NoError(t, err, "Cant write apps.json") }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "WorkflowsTriggersCreate", mock.Anything, mock.Anything, mock.Anything) }, Teardown: func() { @@ -499,7 +499,7 @@ func TestTriggersCreateCommand_AppSelection(t *testing.T) { appSelectTeardown() workspaceInstallAppTeardown() }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { appCommandMock.AssertCalled(t, "RunAddCommand", mock.Anything, mock.Anything, &newDevApp, mock.Anything) clientsMock.ApiInterface.AssertCalled(t, "WorkflowsTriggersCreate", mock.Anything, mock.Anything, mock.Anything) }, @@ -527,7 +527,7 @@ func TestTriggersCreateCommand_AppSelection(t *testing.T) { appSelectTeardown() workspaceInstallAppTeardown() }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { appCommandMock.AssertCalled(t, "RunAddCommand", mock.Anything, mock.Anything, &newProdApp, mock.Anything) clientsMock.ApiInterface.AssertCalled(t, "WorkflowsTriggersCreate", mock.Anything, mock.Anything, mock.Anything) }, diff --git a/cmd/triggers/delete_test.go b/cmd/triggers/delete_test.go index 2d637fd3..b061708a 100644 --- a/cmd/triggers/delete_test.go +++ b/cmd/triggers/delete_test.go @@ -77,7 +77,7 @@ func TestTriggersDeleteCommand(t *testing.T) { Teardown: func() { appSelectTeardown() }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "WorkflowsTriggersDelete", mock.Anything, mock.Anything, fakeTriggerID) }, }, @@ -95,7 +95,7 @@ func TestTriggersDeleteCommand(t *testing.T) { Teardown: func() { appSelectTeardown() }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "WorkflowsTriggersDelete", mock.Anything, mock.Anything, fakeTriggerID) }, }, diff --git a/cmd/triggers/info_test.go b/cmd/triggers/info_test.go index c4046e16..97109e30 100644 --- a/cmd/triggers/info_test.go +++ b/cmd/triggers/info_test.go @@ -50,7 +50,7 @@ func TestTriggersInfoCommand(t *testing.T) { ExpectedOutputs: []string{ "Trigger Info", }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "WorkflowsTriggersInfo", mock.Anything, mock.Anything, fakeTriggerID) }, Teardown: func() { @@ -89,7 +89,7 @@ func TestTriggersInfoCommand(t *testing.T) { Teardown: func() { appSelectTeardown() }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "WorkflowsTriggersInfo", mock.Anything, mock.Anything, fakeTriggerID) }, }, @@ -114,7 +114,7 @@ func TestTriggersInfoCommand(t *testing.T) { Teardown: func() { appSelectTeardown() }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "WorkflowsTriggersInfo", mock.Anything, mock.Anything, fakeTriggerID) }, }, @@ -132,7 +132,7 @@ func TestTriggersInfoCommand(t *testing.T) { Teardown: func() { appSelectTeardown() }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "WorkflowsTriggersInfo", mock.Anything, mock.Anything, fakeTriggerID) }, }, @@ -158,7 +158,7 @@ func TestTriggersInfoCommand(t *testing.T) { "Hint:\n", "Warning:\n", }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "WorkflowsTriggersInfo", mock.Anything, mock.Anything, fakeTriggerID) }, }, diff --git a/cmd/triggers/list_test.go b/cmd/triggers/list_test.go index 96be2299..236d2324 100644 --- a/cmd/triggers/list_test.go +++ b/cmd/triggers/list_test.go @@ -56,7 +56,7 @@ func TestTriggersListCommand(t *testing.T) { "Listing triggers installed to the app...", "There are no triggers installed for the app", }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "WorkflowsTriggersList", mock.Anything, mock.Anything, triggerListRequestArgs) }, }, @@ -93,7 +93,7 @@ func TestTriggersListCommand(t *testing.T) { fmt.Sprintf("%s %s (%s)", fakeTriggerName, fakeTriggerID, "shortcut"), "everyone in the workspace", }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "WorkflowsTriggersList", mock.Anything, mock.Anything, triggerListRequestArgs) }, }, @@ -130,7 +130,7 @@ func TestTriggersListCommand(t *testing.T) { fmt.Sprintf("%s %s (%s)", fakeTriggerName, fakeTriggerID, "shortcut"), "everyone in all workspaces in this org granted to this app", }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "WorkflowsTriggersList", mock.Anything, mock.Anything, triggerListRequestArgs) }, }, @@ -168,7 +168,7 @@ func TestTriggersListCommand(t *testing.T) { fmt.Sprintf("%s %s (%s)", fakeTriggerName, fakeTriggerID, "shortcut"), fmt.Sprintf("Trigger ID: %s (%s)", fakeTriggerID, "scheduled"), }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "WorkflowsTriggersList", mock.Anything, mock.Anything, triggerListRequestArgs) }, }, diff --git a/cmd/triggers/update_test.go b/cmd/triggers/update_test.go index 3cd0449d..c74c90e8 100644 --- a/cmd/triggers/update_test.go +++ b/cmd/triggers/update_test.go @@ -59,7 +59,7 @@ func TestTriggersUpdateCommand(t *testing.T) { Teardown: func() { appSelectTeardown() }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { expectedTriggerRequest := api.TriggerUpdateRequest{ TriggerId: fakeTriggerID, TriggerRequest: api.TriggerRequest{ @@ -125,7 +125,7 @@ func TestTriggersUpdateCommand(t *testing.T) { Teardown: func() { appSelectTeardown() }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { expectedTriggerRequest := api.TriggerUpdateRequest{ TriggerId: fakeTriggerID, TriggerRequest: api.TriggerRequest{ @@ -161,7 +161,7 @@ func TestTriggersUpdateCommand(t *testing.T) { Teardown: func() { appSelectTeardown() }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { expectedTriggerRequest := api.TriggerUpdateRequest{ TriggerId: fakeTriggerID, TriggerRequest: api.TriggerRequest{ @@ -202,7 +202,7 @@ func TestTriggersUpdateCommand(t *testing.T) { Teardown: func() { appSelectTeardown() }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { expectedTriggerRequest := api.TriggerUpdateRequest{ TriggerId: fakeTriggerID, TriggerRequest: api.TriggerRequest{ @@ -241,7 +241,7 @@ func TestTriggersUpdateCommand(t *testing.T) { Teardown: func() { appSelectTeardown() }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { expectedTriggerRequest := api.TriggerUpdateRequest{ TriggerId: fakeTriggerID, TriggerRequest: api.TriggerRequest{ @@ -300,7 +300,7 @@ func TestTriggersUpdateCommand(t *testing.T) { Teardown: func() { appSelectTeardown() }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { expectedTriggerRequest := api.TriggerUpdateRequest{ TriggerId: fakeTriggerID, TriggerRequest: api.TriggerRequest{ @@ -353,7 +353,7 @@ func TestTriggersUpdateCommand(t *testing.T) { appSelectTeardown() }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.HookExecutor.AssertCalled(t, "Execute", mock.Anything) }, }, @@ -431,7 +431,7 @@ func TestTriggersUpdateCommand_MissingParameters(t *testing.T) { appSelectTeardown() promptForInteractivityTeardown() }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "WorkflowsTriggersUpdate", mock.Anything, mock.Anything, triggerRequestMissingInputs) clientsMock.ApiInterface.AssertCalled(t, "WorkflowsTriggersUpdate", mock.Anything, mock.Anything, triggerRequestWithInteractivityInputs) }, @@ -462,7 +462,7 @@ func TestTriggersUpdateCommand_MissingParameters(t *testing.T) { appSelectTeardown() promptForInteractivityTeardown() }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "WorkflowsTriggersUpdate", mock.Anything, mock.Anything, triggerRequestMissingInputs) clientsMock.ApiInterface.AssertCalled(t, "WorkflowsTriggersUpdate", mock.Anything, mock.Anything, triggerRequestWithInteractivityInputs) }, @@ -491,7 +491,7 @@ func TestTriggersUpdateCommand_MissingParameters(t *testing.T) { appSelectTeardown() promptForInteractivityTeardown() }, - ExpectedAsserts: func(t *testing.T, clientsMock *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { clientsMock.ApiInterface.AssertCalled(t, "WorkflowsTriggersUpdate", mock.Anything, mock.Anything, mock.Anything) }, }, diff --git a/internal/pkg/platform/activity_test.go b/internal/pkg/platform/activity_test.go index ea312a54..1a721e47 100644 --- a/internal/pkg/platform/activity_test.go +++ b/internal/pkg/platform/activity_test.go @@ -24,6 +24,7 @@ import ( "github.com/slackapi/slack-cli/internal/logger" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" @@ -97,8 +98,8 @@ func TestPlatformActivity_StreamingLogs(t *testing.T) { for name, tt := range map[string]struct { Setup func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) context.Context Args types.ActivityArgs - ExpectedAsserts func(*testing.T, *shared.ClientsMock) // Optional - ExpectedError error // Optional + ExpectedAsserts func(*testing.T, context.Context, *shared.ClientsMock) // Optional + ExpectedError error // Optional }{ "should return error if context contains no token": { Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) context.Context { @@ -129,7 +130,7 @@ func TestPlatformActivity_StreamingLogs(t *testing.T) { cm.ApiInterface.On("Activity", mock.Anything, mock.Anything, mock.Anything).Return(api.ActivityResult{}, nil) return ctx }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.ApiInterface.AssertNumberOfCalls(t, "Activity", 1) }, }, @@ -147,29 +148,29 @@ func TestPlatformActivity_StreamingLogs(t *testing.T) { }() return ctx }, - ExpectedAsserts: func(t *testing.T, cm *shared.ClientsMock) { + ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { // with the above polling/canceling setup, expectation is activity called only once. cm.ApiInterface.AssertNumberOfCalls(t, "Activity", 1) }, }, } { t.Run(name, func(t *testing.T) { - ctx := context.Background() - ctx = context.WithValue(ctx, config.CONTEXT_TOKEN, "sometoken") // Create mocks + ctxMock := slackcontext.MockContext(context.Background()) + ctxMock = context.WithValue(ctxMock, config.CONTEXT_TOKEN, "sometoken") clientsMock := shared.NewClientsMock() // Create clients that is mocked for testing clients := shared.NewClientFactory(clientsMock.MockClientFactory()) // Setup custom per-test mocks (higher priority than default mocks) if tt.Setup != nil { - ctx = tt.Setup(t, ctx, clientsMock) + ctxMock = tt.Setup(t, ctxMock, clientsMock) } // Setup generic test suite mocks clientsMock.ApiInterface.On("ValidateSession", mock.Anything, mock.Anything).Return(api.AuthSession{}, nil) // Setup default mock actions clientsMock.AddDefaultMocks() - err := Activity(ctx, clients, &logger.Logger{}, tt.Args) + err := Activity(ctxMock, clients, &logger.Logger{}, tt.Args) if tt.ExpectedError != nil { assert.Contains(t, err.Error(), tt.ExpectedError.Error(), err) } else { @@ -177,7 +178,7 @@ func TestPlatformActivity_StreamingLogs(t *testing.T) { } // Assert mocks or other custom assertions if tt.ExpectedAsserts != nil { - tt.ExpectedAsserts(t, clientsMock) + tt.ExpectedAsserts(t, ctxMock, clientsMock) } }) } diff --git a/test/testutil/commandtests.go b/test/testutil/commandtests.go index 4f5f147c..9ee1d320 100644 --- a/test/testutil/commandtests.go +++ b/test/testutil/commandtests.go @@ -34,7 +34,7 @@ type CommandTests map[string]struct { CmdArgs []string // Required, Example: ["my-app", "--template", "slack-samples/deno-starter-template", "--verbose"] ExpectedOutputs []string // Optional ExpectedStdoutOutputs []string // Optional - ExpectedAsserts func(*testing.T, *shared.ClientsMock) // Optional + ExpectedAsserts func(*testing.T, context.Context, *shared.ClientsMock) // Optional ExpectedError error // Optional ExpectedErrorStrings []string // Optional } @@ -105,7 +105,7 @@ func TableTestCommand(t *testing.T, commandTests CommandTests, newCommandFunc fu // Assert mocks or other custom assertions if tt.ExpectedAsserts != nil { - tt.ExpectedAsserts(t, clientsMock) + tt.ExpectedAsserts(t, ctxMock, clientsMock) } if tt.Teardown != nil { From 9c816be7b9c4938090e00778b8b24cd6b519334a Mon Sep 17 00:00:00 2001 From: Michael Brooks Date: Mon, 7 Apr 2025 20:46:23 -0600 Subject: [PATCH 05/13] test: use ctx in mocked ExpectedAsserts --- cmd/app/link_test.go | 12 ++++++------ cmd/project/init_test.go | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/cmd/app/link_test.go b/cmd/app/link_test.go index c05c441a..d56dbf8a 100644 --- a/cmd/app/link_test.go +++ b/cmd/app/link_test.go @@ -103,7 +103,7 @@ func Test_Apps_Link(t *testing.T) { EnterpriseID: mockLinkSlackAuth1.EnterpriseID, } actualApp, err := cm.AppClient.GetDeployed( - context.Background(), + ctx, mockLinkSlackAuth1.TeamID, ) require.NoError(t, err) @@ -162,7 +162,7 @@ func Test_Apps_Link(t *testing.T) { UserID: mockLinkSlackAuth2.UserID, } actualApp, err := cm.AppClient.GetLocal( - context.Background(), + ctx, mockLinkSlackAuth2.TeamID, ) require.NoError(t, err) @@ -228,7 +228,7 @@ func Test_Apps_Link(t *testing.T) { EnterpriseID: mockLinkSlackAuth1.EnterpriseID, } actualApp, err := cm.AppClient.GetDeployed( - context.Background(), + ctx, mockLinkSlackAuth1.TeamID, ) require.NoError(t, err) @@ -297,7 +297,7 @@ func Test_Apps_Link(t *testing.T) { EnterpriseID: mockLinkSlackAuth1.EnterpriseID, } actualApp, err := cm.AppClient.GetDeployed( - context.Background(), + ctx, mockLinkSlackAuth1.TeamID, ) require.NoError(t, err) @@ -374,7 +374,7 @@ func Test_Apps_Link(t *testing.T) { UserID: mockLinkSlackAuth2.UserID, } actualApp, err := cm.AppClient.GetLocal( - context.Background(), + ctx, mockLinkSlackAuth2.TeamID, ) require.NoError(t, err) @@ -489,7 +489,7 @@ func Test_Apps_Link(t *testing.T) { EnterpriseID: mockLinkSlackAuth1.EnterpriseID, } actualApp, err := cm.AppClient.GetDeployed( - context.Background(), + ctx, mockLinkSlackAuth1.TeamID, ) require.NoError(t, err) diff --git a/cmd/project/init_test.go b/cmd/project/init_test.go index 06c54591..381696b0 100644 --- a/cmd/project/init_test.go +++ b/cmd/project/init_test.go @@ -207,7 +207,7 @@ func Test_Project_InitCommand(t *testing.T) { UserID: mockLinkSlackAuth2.UserID, } actualApp, err := cm.AppClient.GetLocal( - context.Background(), + ctx, mockLinkSlackAuth2.TeamID, ) require.NoError(t, err) From 5f69d230293ec7f0ace977d46a7899d5abde816f Mon Sep 17 00:00:00 2001 From: Michael Brooks Date: Mon, 7 Apr 2025 20:47:39 -0600 Subject: [PATCH 06/13] test: use ctx in mocked ExpectedAsserts to link_test.go --- cmd/app/link_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/app/link_test.go b/cmd/app/link_test.go index d56dbf8a..ccb0d795 100644 --- a/cmd/app/link_test.go +++ b/cmd/app/link_test.go @@ -303,7 +303,7 @@ func Test_Apps_Link(t *testing.T) { require.NoError(t, err) assert.Equal(t, expectedApp, actualApp) unsavedApp, err := cm.AppClient.GetLocal( - context.Background(), + ctx, mockLinkSlackAuth1.TeamID, ) require.NoError(t, err) From c4b769750f5981419c6f115e3ad5be2e558d1bbc Mon Sep 17 00:00:00 2001 From: Michael Brooks Date: Mon, 7 Apr 2025 20:56:00 -0600 Subject: [PATCH 07/13] test: use ctx in mocked ExpectedAsserts to update_test.go --- cmd/collaborators/update_test.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/cmd/collaborators/update_test.go b/cmd/collaborators/update_test.go index 7a090ddb..851b5787 100644 --- a/cmd/collaborators/update_test.go +++ b/cmd/collaborators/update_test.go @@ -39,7 +39,7 @@ func TestUpdateCommand(t *testing.T) { appSelectMock.On("TeamAppSelectPrompt").Return(prompts.SelectedApp{App: types.App{AppID: "A123"}, Auth: types.SlackAuth{}}, nil) // Set experiment flag clientsMock.Config.ExperimentsFlag = append(clientsMock.Config.ExperimentsFlag, "read-only-collaborators") - clientsMock.Config.LoadExperiments(context.Background(), clientsMock.IO.PrintDebug) + clientsMock.Config.LoadExperiments(ctx, clientsMock.IO.PrintDebug) // Mock APi call clientsMock.ApiInterface.On("UpdateCollaborator", mock.Anything, mock.Anything, "A123", @@ -57,7 +57,7 @@ func TestUpdateCommand(t *testing.T) { appSelectMock.On("TeamAppSelectPrompt").Return(prompts.SelectedApp{App: types.App{AppID: "A123"}, Auth: types.SlackAuth{}}, nil) // Set experiment flag clientsMock.Config.ExperimentsFlag = append(clientsMock.Config.ExperimentsFlag, "read-only-collaborators") - clientsMock.Config.LoadExperiments(context.Background(), clientsMock.IO.PrintDebug) + clientsMock.Config.LoadExperiments(ctx, clientsMock.IO.PrintDebug) // Mock APi call clientsMock.ApiInterface.On("UpdateCollaborator", mock.Anything, mock.Anything, "A123", @@ -71,7 +71,7 @@ func TestUpdateCommand(t *testing.T) { clientsMock.AddDefaultMocks() // Set experiment flag clientsMock.Config.ExperimentsFlag = append(clientsMock.Config.ExperimentsFlag, "read-only-collaborators") - clientsMock.Config.LoadExperiments(context.Background(), clientsMock.IO.PrintDebug) + clientsMock.Config.LoadExperiments(ctx, clientsMock.IO.PrintDebug) }, }, "user ID must be provided": { @@ -81,7 +81,7 @@ func TestUpdateCommand(t *testing.T) { clientsMock.AddDefaultMocks() // Set experiment flag clientsMock.Config.ExperimentsFlag = append(clientsMock.Config.ExperimentsFlag, "read-only-collaborators") - clientsMock.Config.LoadExperiments(context.Background(), clientsMock.IO.PrintDebug) + clientsMock.Config.LoadExperiments(ctx, clientsMock.IO.PrintDebug) }, }, }, func(clients *shared.ClientFactory) *cobra.Command { From 63a99c88983617f872625e790a383df7e957bdc0 Mon Sep 17 00:00:00 2001 From: Michael Brooks Date: Tue, 8 Apr 2025 10:52:18 -0700 Subject: [PATCH 08/13] test: use .MockContext(...) instead of context.Background() --- cmd/app/link_test.go | 5 +- cmd/app/uninstall_test.go | 12 +-- cmd/auth/token_test.go | 6 +- cmd/collaborators/collaborators_test.go | 7 +- cmd/doctor/check_test.go | 18 ++-- cmd/doctor/doctor_test.go | 4 +- cmd/env/add_test.go | 12 +-- cmd/feedback/feedback_test.go | 10 +- cmd/function/access_test.go | 5 +- cmd/function/prompt_test.go | 4 +- cmd/help/help_test.go | 5 +- cmd/platform/deploy_test.go | 3 +- cmd/project/create_samples_test.go | 4 +- cmd/project/create_test.go | 4 +- cmd/project/init_test.go | 10 +- cmd/triggers/create_test.go | 18 ++-- cmd/triggers/generate_test.go | 19 ++-- internal/app/app_client_test.go | 41 ++++---- internal/app/manifest_test.go | 4 +- internal/cache/manifest_test.go | 6 +- internal/cmdutil/project_test.go | 4 +- internal/config/config_test.go | 3 +- internal/config/project_test.go | 36 +++---- internal/config/system_test.go | 47 +++++---- internal/iostreams/logfile_test.go | 4 +- internal/iostreams/printer_test.go | 8 +- internal/iostreams/survey_test.go | 4 +- internal/pkg/apps/delete_test.go | 4 +- internal/pkg/apps/install_test.go | 10 +- internal/pkg/apps/list_test.go | 10 +- internal/pkg/auth/list_test.go | 6 +- internal/pkg/create/create_test.go | 6 +- internal/pkg/datastore/bulk_delete_test.go | 5 +- internal/pkg/datastore/bulk_get_test.go | 5 +- internal/pkg/datastore/bulk_put_test.go | 5 +- internal/pkg/datastore/delete_test.go | 5 +- internal/pkg/datastore/get_test.go | 5 +- internal/pkg/datastore/put_test.go | 5 +- internal/pkg/datastore/query_test.go | 5 +- internal/pkg/datastore/update_test.go | 5 +- .../prompt_provider_auth_select_test.go | 8 +- .../prompt_provider_select_test.go | 8 +- .../externalauth/prompt_token_select_test.go | 6 +- .../prompt_workflow_select_test.go | 8 +- internal/pkg/manifest/validate_test.go | 22 ++--- internal/pkg/platform/activity_test.go | 2 +- internal/pkg/platform/localserver_test.go | 5 +- internal/prompts/app_select_test.go | 98 +++++++++---------- internal/runtime/deno/deno_test.go | 6 +- internal/runtime/node/node_test.go | 6 +- internal/runtime/node/npm_test.go | 8 +- internal/runtime/python/python_test.go | 7 +- internal/runtime/runtime_test.go | 4 +- internal/shared/clients_test.go | 31 +++--- internal/slackcontext/slackcontext_test.go | 28 +++--- internal/update/cli_metadata_test.go | 6 +- 56 files changed, 327 insertions(+), 305 deletions(-) diff --git a/cmd/app/link_test.go b/cmd/app/link_test.go index ccb0d795..227f045b 100644 --- a/cmd/app/link_test.go +++ b/cmd/app/link_test.go @@ -24,6 +24,7 @@ import ( "github.com/slackapi/slack-cli/internal/iostreams" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackdeps" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/slackapi/slack-cli/test/testutil" @@ -569,10 +570,8 @@ func Test_Apps_LinkAppHeaderSection(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { - // Setup parameters for test - ctx := context.Background() - // Create mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AddDefaultMocks() diff --git a/cmd/app/uninstall_test.go b/cmd/app/uninstall_test.go index aeb1181e..43b52f5e 100644 --- a/cmd/app/uninstall_test.go +++ b/cmd/app/uninstall_test.go @@ -48,7 +48,7 @@ func TestAppsUninstall(t *testing.T) { testutil.TableTestCommand(t, testutil.CommandTests{ "Successfully uninstall": { Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { - prepareCommonUninstallMocks(clients, clientsMock) + prepareCommonUninstallMocks(ctx, clients, clientsMock) clientsMock.ApiInterface.On("UninstallApp", mock.Anything, mock.Anything, fakeAppID, fakeAppTeamID). Return(nil).Once() }, @@ -58,7 +58,7 @@ func TestAppsUninstall(t *testing.T) { }, "Successfully uninstall with a get-manifest hook error": { Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { - prepareCommonUninstallMocks(clients, clientsMock) + prepareCommonUninstallMocks(ctx, clients, clientsMock) clientsMock.ApiInterface.On("UninstallApp", mock.Anything, mock.Anything, fakeAppID, fakeAppTeamID). Return(nil).Once() manifestMock := &app.ManifestMockObject{} @@ -73,7 +73,7 @@ func TestAppsUninstall(t *testing.T) { "Fail to uninstall due to API error": { ExpectedError: slackerror.New("something went wrong"), Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { - prepareCommonUninstallMocks(clients, clientsMock) + prepareCommonUninstallMocks(ctx, clients, clientsMock) clientsMock.ApiInterface.On("UninstallApp", mock.Anything, mock.Anything, fakeAppID, fakeAppTeamID). Return(slackerror.New("something went wrong")).Once() }, @@ -82,7 +82,7 @@ func TestAppsUninstall(t *testing.T) { CmdArgs: []string{}, ExpectedError: slackerror.New(slackerror.ErrCredentialsNotFound), Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { - prepareCommonUninstallMocks(cf, cm) + prepareCommonUninstallMocks(ctx, cf, cm) appSelectMock := prompts.NewAppSelectMock() uninstallAppSelectPromptFunc = appSelectMock.AppSelectPrompt appSelectMock.On("AppSelectPrompt").Return(prompts.SelectedApp{App: fakeApp}, nil) @@ -95,7 +95,7 @@ func TestAppsUninstall(t *testing.T) { }) } -func prepareCommonUninstallMocks(clients *shared.ClientFactory, clientsMock *shared.ClientsMock) *shared.ClientFactory { +func prepareCommonUninstallMocks(ctx context.Context, clients *shared.ClientFactory, clientsMock *shared.ClientsMock) *shared.ClientFactory { // Mock App Selection appSelectMock := prompts.NewAppSelectMock() @@ -124,7 +124,7 @@ func prepareCommonUninstallMocks(clients *shared.ClientFactory, clientsMock *sha clients.AppClient().AppClientInterface = appClientMock - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) if err != nil { panic("error setting up test; cant write apps.json") } diff --git a/cmd/auth/token_test.go b/cmd/auth/token_test.go index adf8a7b5..b6015de1 100644 --- a/cmd/auth/token_test.go +++ b/cmd/auth/token_test.go @@ -15,18 +15,20 @@ package auth import ( - "context" "testing" "github.com/slackapi/slack-cli/internal/api" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/test/testutil" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" ) func TestTokenCommand(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) + clientsMock := shared.NewClientsMock() clientsMock.ApiInterface.On("ValidateSession", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(api.AuthSession{UserID: &mockOrgAuth.UserID, TeamID: &mockOrgAuth.TeamID, @@ -42,7 +44,7 @@ func TestTokenCommand(t *testing.T) { tokenFlag = "xoxp-example-1234" cmd := NewTokenCommand(clients) - cmd.SetContext(context.Background()) + cmd.SetContext(ctx) testutil.MockCmdIO(clients.IO, cmd) serviceTokenFlag = true diff --git a/cmd/collaborators/collaborators_test.go b/cmd/collaborators/collaborators_test.go index 88a1ff3c..7f391305 100644 --- a/cmd/collaborators/collaborators_test.go +++ b/cmd/collaborators/collaborators_test.go @@ -15,11 +15,11 @@ package collaborators import ( - "context" "testing" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/test/testutil" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" @@ -52,15 +52,12 @@ func TestCollaboratorsCommand(t *testing.T) { } func TestCollaboratorsCommand_PrintSuccess(t *testing.T) { - // Setup - - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) // Execute tests - t.Run("Username will be used if present", func(t *testing.T) { user := types.SlackUser{Email: "joe.smith@company.com", ID: "U1234", PermissionType: types.OWNER} printSuccess(ctx, clients.IO, user, "added") diff --git a/cmd/doctor/check_test.go b/cmd/doctor/check_test.go index acddc73e..da47c83c 100644 --- a/cmd/doctor/check_test.go +++ b/cmd/doctor/check_test.go @@ -15,7 +15,6 @@ package doctor import ( - "context" "fmt" "runtime" "testing" @@ -26,6 +25,7 @@ import ( "github.com/slackapi/slack-cli/internal/pkg/version" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" @@ -34,10 +34,10 @@ import ( func TestDoctorCheckOS(t *testing.T) { t.Run("returns the operating system version", func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() expected := Section{ Label: "Operating System", Value: "the computer conductor", @@ -56,10 +56,10 @@ func TestDoctorCheckOS(t *testing.T) { func TestDoctorCheckCLIVersion(t *testing.T) { t.Run("returns the current version of this tool", func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() expected := Section{ Label: "CLI", Value: "this tool for building Slack apps", @@ -141,13 +141,13 @@ func TestDoctorCheckProjectConfig(t *testing.T) { for name, tt := range tests { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AddDefaultMocks() pcm := &config.ProjectConfigMock{} pcm.On("ReadProjectConfigFile", mock.Anything).Return(tt.projectConfig, nil) clientsMock.Config.ProjectConfig = pcm clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() expected := Section{ Label: "Configurations", Value: "your project's CLI settings", @@ -218,10 +218,10 @@ func TestDoctorCheckProjectDeps(t *testing.T) { for name, tt := range tests { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AddDefaultMocks() clients := tt.mockHookSetup(clientsMock) - ctx := context.Background() expected := Section{ Label: "Dependencies", Value: "requisites for development", @@ -246,6 +246,7 @@ func TestDoctorCheckCLIConfig(t *testing.T) { for name, tt := range tests { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AddDefaultMocks() scm := &config.SystemConfigMock{} @@ -254,7 +255,6 @@ func TestDoctorCheckCLIConfig(t *testing.T) { }, nil) clientsMock.Config.SystemConfig = scm clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() expected := Section{ Label: "Configurations", Value: "any adjustments to settings", @@ -297,10 +297,10 @@ func TestDoctorCheckCLICreds(t *testing.T) { for name := range tests { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() expected := Section{ Label: "Credentials", Value: "your Slack authentication", @@ -391,10 +391,10 @@ func TestDoctorCheckProjectTooling(t *testing.T) { for name, tt := range tests { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AddDefaultMocks() clients := tt.mockHookSetup(clientsMock) - ctx := context.Background() expected := Section{ Label: "Runtime", Value: "foundations for the application", @@ -410,7 +410,7 @@ func TestDoctorCheckProjectTooling(t *testing.T) { func TestDoctorCheckGit(t *testing.T) { t.Run("returns the version of git", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) gitVersion, err := deputil.GetGitVersion() require.NoError(t, err) expected := Section{ diff --git a/cmd/doctor/doctor_test.go b/cmd/doctor/doctor_test.go index 289ddb12..0ea22afb 100644 --- a/cmd/doctor/doctor_test.go +++ b/cmd/doctor/doctor_test.go @@ -16,7 +16,6 @@ package doctor import ( "bytes" - "context" "fmt" "runtime" "testing" @@ -28,6 +27,7 @@ import ( "github.com/slackapi/slack-cli/internal/pkg/version" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/slackapi/slack-cli/test/testutil" "github.com/stretchr/testify/assert" @@ -401,7 +401,7 @@ func TestDoctorHook(t *testing.T) { for name, tt := range tests { t.Run(name, func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AddDefaultMocks() clients := tt.mockHookSetup(clientsMock) diff --git a/cmd/env/add_test.go b/cmd/env/add_test.go index 94ee8178..2a150463 100644 --- a/cmd/env/add_test.go +++ b/cmd/env/add_test.go @@ -145,7 +145,7 @@ func Test_Env_AddCommand(t *testing.T) { "add a variable using arguments": { CmdArgs: []string{"ENV_NAME", "ENV_VALUE"}, Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { - setupEnvAddCommandMocks(cm, cf) + setupEnvAddCommandMocks(ctx, cm, cf) }, ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { cm.ApiInterface.AssertCalled( @@ -169,7 +169,7 @@ func Test_Env_AddCommand(t *testing.T) { "provide a variable name by argument and value by prompt": { CmdArgs: []string{"ENV_NAME"}, Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { - setupEnvAddCommandMocks(cm, cf) + setupEnvAddCommandMocks(ctx, cm, cf) cm.IO.On( "PasswordPrompt", mock.Anything, @@ -200,7 +200,7 @@ func Test_Env_AddCommand(t *testing.T) { "provide a variable name by argument and value by flag": { CmdArgs: []string{"ENV_NAME", "--value", "example_value"}, Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { - setupEnvAddCommandMocks(cm, cf) + setupEnvAddCommandMocks(ctx, cm, cf) cm.IO.On( "PasswordPrompt", mock.Anything, @@ -231,7 +231,7 @@ func Test_Env_AddCommand(t *testing.T) { "provide both variable name and value by prompt": { CmdArgs: []string{}, Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { - setupEnvAddCommandMocks(cm, cf) + setupEnvAddCommandMocks(ctx, cm, cf) cm.IO.On( "InputPrompt", mock.Anything, @@ -276,10 +276,10 @@ func Test_Env_AddCommand(t *testing.T) { } // setupEnvAddCommandMocks prepares common mocks for these tests -func setupEnvAddCommandMocks(cm *shared.ClientsMock, cf *shared.ClientFactory) { +func setupEnvAddCommandMocks(ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cf.SDKConfig = hooks.NewSDKConfigMock() cm.AddDefaultMocks() - _ = cf.AppClient().SaveDeployed(context.Background(), mockApp) + _ = cf.AppClient().SaveDeployed(ctx, mockApp) appSelectMock := prompts.NewAppSelectMock() teamAppSelectPromptFunc = appSelectMock.TeamAppSelectPrompt diff --git a/cmd/feedback/feedback_test.go b/cmd/feedback/feedback_test.go index 1520ef6f..d3ff2c94 100644 --- a/cmd/feedback/feedback_test.go +++ b/cmd/feedback/feedback_test.go @@ -24,6 +24,7 @@ import ( "github.com/slackapi/slack-cli/internal/config" "github.com/slackapi/slack-cli/internal/iostreams" "github.com/slackapi/slack-cli/internal/shared" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/slackapi/slack-cli/internal/style" "github.com/stretchr/testify/assert" @@ -46,6 +47,7 @@ func TestFeedbackCommand(t *testing.T) { } // Prepare mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AddDefaultMocks() @@ -69,7 +71,7 @@ func TestFeedbackCommand(t *testing.T) { // Execute test cmd := NewFeedbackCommand(clients) - err := runFeedbackCommand(context.Background(), clients, cmd) + err := runFeedbackCommand(ctx, clients, cmd) assert.NoError(t, err) clientsMock.Browser.AssertCalled(t, "OpenURL", "https://survey.com?project_id=projectID&system_id=systemID&utm_medium=cli&utm_source=cli") }) @@ -104,6 +106,7 @@ func TestFeedbackCommand(t *testing.T) { } // Prepare mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AddDefaultMocks() @@ -134,7 +137,7 @@ func TestFeedbackCommand(t *testing.T) { // Execute test cmd := NewFeedbackCommand(clients) - err := runFeedbackCommand(context.Background(), clients, cmd) + err := runFeedbackCommand(ctx, clients, cmd) assert.NoError(t, err) clientsMock.Browser.AssertCalled(t, "OpenURL", "https://survey.com?project_id=projectID&system_id=systemID&utm_medium=cli&utm_source=cli") }) @@ -196,6 +199,7 @@ func TestShowSurveyMessages(t *testing.T) { } // Prepare mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AddDefaultMocks() @@ -239,7 +243,7 @@ func TestShowSurveyMessages(t *testing.T) { SurveyStore = surveys // Execute test - err := ShowSurveyMessages(context.Background(), clients) + err := ShowSurveyMessages(ctx, clients) assert.NoError(t, err) clientsMock.Browser.AssertCalled(t, "OpenURL", "https://B.com?project_id=projectID&system_id=systemID&utm_medium=cli&utm_source=cli") clientsMock.Browser.AssertCalled(t, "OpenURL", "https://C.com?project_id=projectID&system_id=systemID&utm_medium=cli&utm_source=cli") diff --git a/cmd/function/access_test.go b/cmd/function/access_test.go index 0df101af..f79c0461 100644 --- a/cmd/function/access_test.go +++ b/cmd/function/access_test.go @@ -21,6 +21,7 @@ import ( "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/slackapi/slack-cli/test/testutil" "github.com/spf13/afero" @@ -326,6 +327,7 @@ func TestFunctionDistributionCommand_PermissionsFile(t *testing.T) { for name, tt := range tests { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.IO.AddDefaultMocks() err := afero.WriteFile(clientsMock.Fs, tt.filename, []byte(tt.data), 0644) @@ -339,7 +341,6 @@ func TestFunctionDistributionCommand_PermissionsFile(t *testing.T) { clientsMock.ApiInterface.On("FunctionDistributionSet", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return([]types.FunctionDistributionUser{}, nil) - ctx := context.Background() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) app := types.App{AppID: "A123"} @@ -400,6 +401,7 @@ func TestFunctionDistributeCommand_UpdateNamedEntitiesDistribution(t *testing.T) for name, tt := range tests { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.ApiInterface.On("FunctionDistributionSet", mock.Anything, mock.Anything, mock.Anything, types.NAMED_ENTITIES, mock.Anything). Return([]types.FunctionDistributionUser{}, nil). @@ -414,7 +416,6 @@ func TestFunctionDistributeCommand_UpdateNamedEntitiesDistribution(t *testing.T) app := types.App{AppID: "A123"} function := "Ft123" - ctx := context.Background() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) err := updateNamedEntitiesDistribution(ctx, clients, app, function, tt.updatedEntities) diff --git a/cmd/function/prompt_test.go b/cmd/function/prompt_test.go index 6cc6e7ee..960957de 100644 --- a/cmd/function/prompt_test.go +++ b/cmd/function/prompt_test.go @@ -15,13 +15,13 @@ package function import ( - "context" "testing" "github.com/slackapi/slack-cli/internal/hooks" "github.com/slackapi/slack-cli/internal/iostreams" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" @@ -61,6 +61,7 @@ func TestFunction_ChooseFunctionPrompt(t *testing.T) { for name, tt := range tests { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.IO.On("SelectPrompt", mock.Anything, "Choose a function", mock.Anything, iostreams.MatchPromptConfig(iostreams.SelectPromptConfig{ Flag: clientsMock.Config.Flags.Lookup("name"), @@ -77,7 +78,6 @@ func TestFunction_ChooseFunctionPrompt(t *testing.T) { clients := shared.NewClientFactory(clientsMock.MockClientFactory(), func(clients *shared.ClientFactory) { clients.SDKConfig = sdkConfigMock }) - ctx := context.Background() functions := []types.Function{ {CallbackID: "alphabet_function"}, {CallbackID: "hello_function"}, diff --git a/cmd/help/help_test.go b/cmd/help/help_test.go index e147b68f..c0686e1f 100644 --- a/cmd/help/help_test.go +++ b/cmd/help/help_test.go @@ -15,11 +15,11 @@ package help import ( - "context" "testing" "github.com/slackapi/slack-cli/internal/experiment" "github.com/slackapi/slack-cli/internal/shared" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/style" "github.com/slackapi/slack-cli/test/testutil" "github.com/spf13/cobra" @@ -75,6 +75,7 @@ func TestHelpFunc(t *testing.T) { experiment.EnabledExperiments = _EnabledExperiments }() + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AddDefaultMocks() clientsMock.Config.ExperimentsFlag = tt.experiments @@ -90,7 +91,7 @@ func TestHelpFunc(t *testing.T) { Run: func(cmd *cobra.Command, args []string) {}, } rootCmd.AddCommand(subCommand) - rootCmd.SetContext(context.Background()) + rootCmd.SetContext(ctx) rootCmd.Flags().Bool("help", true, "mock help flag") clientsMock.Config.SetFlags(rootCmd) testutil.MockCmdIO(clientsMock.IO, rootCmd) diff --git a/cmd/platform/deploy_test.go b/cmd/platform/deploy_test.go index e7349deb..5b1598bf 100644 --- a/cmd/platform/deploy_test.go +++ b/cmd/platform/deploy_test.go @@ -29,6 +29,7 @@ import ( "github.com/slackapi/slack-cli/internal/prompts" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/slackapi/slack-cli/internal/slacktrace" "github.com/slackapi/slack-cli/test/testutil" @@ -145,6 +146,7 @@ func TestDeployCommand_HasValidDeploymentMethod(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clients := shared.NewClientFactory(clientsMock.MockClientFactory(), func(clients *shared.ClientFactory) { manifestMock := &app.ManifestMockObject{} @@ -157,7 +159,6 @@ func TestDeployCommand_HasValidDeploymentMethod(t *testing.T) { clients.SDKConfig = hooks.NewSDKConfigMock() clients.SDKConfig.Hooks.Deploy.Command = tt.deployScript }) - ctx := context.Background() err := hasValidDeploymentMethod(ctx, clients, types.App{}, types.SlackAuth{}) if tt.expectedError != nil { require.Error(t, err) diff --git a/cmd/project/create_samples_test.go b/cmd/project/create_samples_test.go index 8ab6a3d0..3fb5aac2 100644 --- a/cmd/project/create_samples_test.go +++ b/cmd/project/create_samples_test.go @@ -15,7 +15,6 @@ package project import ( - "context" "io" "net/http/httptest" "testing" @@ -23,6 +22,7 @@ import ( "github.com/slackapi/slack-cli/internal/iostreams" "github.com/slackapi/slack-cli/internal/pkg/create" "github.com/slackapi/slack-cli/internal/shared" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" ) @@ -102,6 +102,7 @@ func TestSamples_PromptSampleSelection(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) sampler := create.NewMockSampler() w := httptest.NewRecorder() _, _ = io.WriteString(w, tt.mockSlackHTTPResponse) @@ -118,7 +119,6 @@ func TestSamples_PromptSampleSelection(t *testing.T) { }), ).Return(tt.mockSelection, nil) clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() // Execute test repoName, err := PromptSampleSelection(ctx, clients, sampler) diff --git a/cmd/project/create_test.go b/cmd/project/create_test.go index bdf925a9..3fb1ea17 100644 --- a/cmd/project/create_test.go +++ b/cmd/project/create_test.go @@ -23,6 +23,7 @@ import ( "github.com/slackapi/slack-cli/internal/logger" "github.com/slackapi/slack-cli/internal/pkg/create" "github.com/slackapi/slack-cli/internal/shared" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/slackapi/slack-cli/test/testutil" "github.com/stretchr/testify/assert" @@ -235,6 +236,7 @@ func TestCreateCommand_confirmExternalTemplateSelection(t *testing.T) { func Test_CreateCommand_BoltExperiment(t *testing.T) { // Create mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AddDefaultMocks() @@ -243,7 +245,7 @@ func Test_CreateCommand_BoltExperiment(t *testing.T) { // Set experiment flag clientsMock.Config.ExperimentsFlag = append(clientsMock.Config.ExperimentsFlag, "bolt") - clientsMock.Config.LoadExperiments(context.Background(), clientsMock.IO.PrintDebug) + clientsMock.Config.LoadExperiments(ctx, clientsMock.IO.PrintDebug) // Create the command cmd := NewCreateCommand(clients) diff --git a/cmd/project/init_test.go b/cmd/project/init_test.go index 381696b0..576da4e3 100644 --- a/cmd/project/init_test.go +++ b/cmd/project/init_test.go @@ -56,14 +56,14 @@ func Test_Project_InitCommand(t *testing.T) { CmdArgs: []string{}, Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { // Do not set experiment flag - setupProjectInitCommandMocks(t, cm, cf, false) + setupProjectInitCommandMocks(t, ctx, cm, cf, false) }, ExpectedErrorStrings: []string{"Command requires the Bolt Framework experiment"}, }, "init a project and do not link an existing app": { CmdArgs: []string{}, Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { - setupProjectInitCommandMocks(t, cm, cf, true) + setupProjectInitCommandMocks(t, ctx, cm, cf, true) // Do not link an existing app cm.IO.On("ConfirmPrompt", mock.Anything, app.LinkAppConfirmPromptText, mock.Anything).Return(false, nil) }, @@ -114,7 +114,7 @@ func Test_Project_InitCommand(t *testing.T) { mockLinkSlackAuth1, }, nil) // Default setup - setupProjectInitCommandMocks(t, cm, cf, true) + setupProjectInitCommandMocks(t, ctx, cm, cf, true) // Do not link an existing app cm.IO.On("ConfirmPrompt", mock.Anything, app.LinkAppConfirmPromptText, mock.Anything).Return(true, nil) // Mock prompt to link an existing app @@ -221,7 +221,7 @@ func Test_Project_InitCommand(t *testing.T) { } // setupProjectInitCommandMocks prepares common mocks for these tests -func setupProjectInitCommandMocks(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory, boltExperimentEnabled bool) { +func setupProjectInitCommandMocks(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory, boltExperimentEnabled bool) { // Mocks projectDirPath := "/path/to/project-name" cm.Os.On("Getwd").Return(projectDirPath, nil) @@ -230,7 +230,7 @@ func setupProjectInitCommandMocks(t *testing.T, cm *shared.ClientsMock, cf *shar // Set experiment flag if boltExperimentEnabled { cm.Config.ExperimentsFlag = append(cm.Config.ExperimentsFlag, "bolt") - cm.Config.LoadExperiments(context.Background(), cm.IO.PrintDebug) + cm.Config.LoadExperiments(ctx, cm.IO.PrintDebug) } // Create project directory diff --git a/cmd/triggers/create_test.go b/cmd/triggers/create_test.go index b4b3e70b..3a58e513 100644 --- a/cmd/triggers/create_test.go +++ b/cmd/triggers/create_test.go @@ -26,6 +26,7 @@ import ( "github.com/slackapi/slack-cli/internal/prompts" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/test/testutil" "github.com/spf13/afero" "github.com/spf13/cobra" @@ -546,13 +547,13 @@ func TestTriggersCreateCommand_promptShouldInstallAndRetry(t *testing.T) { testcases := []struct { name string - prepareMocks func(*app.AppMock, *shared.ClientsMock) + prepareMocks func(*testing.T, context.Context, *shared.ClientsMock, *app.AppMock) check func(*testing.T, types.DeployedTrigger, bool, error) }{ { name: "Accept prompt to reinstall and create the trigger successfully", - prepareMocks: func(appCmdMock *app.AppMock, clientsMock *shared.ClientsMock) { - appCmdMock.On("RunAddCommand", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(context.Background(), types.SUCCESS, types.App{}, nil) + prepareMocks: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, appCmdMock *app.AppMock) { + appCmdMock.On("RunAddCommand", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(ctx, types.SUCCESS, types.App{}, nil) clientsMock.ApiInterface.On("WorkflowsTriggersCreate", mock.Anything, mock.Anything, mock.Anything). Return(types.DeployedTrigger{Name: "trigger name", ID: "Ft123", Type: "shortcut"}, nil) clientsMock.IO.On("ConfirmPrompt", mock.Anything, "Re-install app to apply local file changes and try again?", mock.Anything).Return(true, nil) @@ -565,7 +566,7 @@ func TestTriggersCreateCommand_promptShouldInstallAndRetry(t *testing.T) { }, { name: "Decline prompt to reinstall and do nothing", - prepareMocks: func(appCmdMock *app.AppMock, clientsMock *shared.ClientsMock) { + prepareMocks: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, appCmdMock *app.AppMock) { clientsMock.IO.On("ConfirmPrompt", mock.Anything, "Re-install app to apply local file changes and try again?", mock.Anything).Return(false, nil) }, check: func(t *testing.T, trigger types.DeployedTrigger, ok bool, err error) { @@ -575,8 +576,8 @@ func TestTriggersCreateCommand_promptShouldInstallAndRetry(t *testing.T) { }, { name: "Accept prompt to reinstall but fail to create the trigger", - prepareMocks: func(appCmdMock *app.AppMock, clientsMock *shared.ClientsMock) { - appCmdMock.On("RunAddCommand", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(context.Background(), types.SUCCESS, types.App{}, nil) + prepareMocks: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, appCmdMock *app.AppMock) { + appCmdMock.On("RunAddCommand", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(ctx, types.SUCCESS, types.App{}, nil) clientsMock.ApiInterface.On("WorkflowsTriggersCreate", mock.Anything, mock.Anything, mock.Anything). Return(types.DeployedTrigger{}, errors.New("something_else_went_wrong")) clientsMock.Os.On("UserHomeDir").Return("", nil) // Called by clients.IO.PrintError @@ -594,17 +595,16 @@ func TestTriggersCreateCommand_promptShouldInstallAndRetry(t *testing.T) { fmt.Println("Running TriggersCreate test: ", testcase.name) // Prepare mocks - + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) cmd := NewCreateCommand(clients) triggerRequest := api.TriggerRequest{} - ctx := context.Background() appCmdMock := new(app.AppMock) workspaceInstallAppFunc = appCmdMock.RunAddCommand - testcase.prepareMocks(appCmdMock, clientsMock) + testcase.prepareMocks(t, ctx, clientsMock, appCmdMock) // Execute test diff --git a/cmd/triggers/generate_test.go b/cmd/triggers/generate_test.go index 58d30c10..d68f78b7 100644 --- a/cmd/triggers/generate_test.go +++ b/cmd/triggers/generate_test.go @@ -25,6 +25,7 @@ import ( "github.com/slackapi/slack-cli/internal/iostreams" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/spf13/afero" "github.com/stretchr/testify/assert" @@ -54,7 +55,7 @@ func Test_TriggerGenerate_accept_prompt(t *testing.T) { } t.Run(tt.name, func(t *testing.T) { - ctx, clientsMock := prepareMocks(tt.triggersListResponse, tt.globResponse, tt.triggersCreateResponse, nil /*trigger create error*/) + ctx, clientsMock := prepareMocks(t, tt.triggersListResponse, tt.globResponse, tt.triggersCreateResponse, nil /*trigger create error*/) clientsMock.IO.On("SelectPrompt", mock.Anything, "Choose a trigger definition file:", mock.Anything, iostreams.MatchPromptConfig(iostreams.SelectPromptConfig{ Flag: clientsMock.Config.Flags.Lookup("trigger-def"), @@ -94,7 +95,7 @@ func Test_TriggerGenerate_decline_prompt(t *testing.T) { } t.Run(tt.name, func(t *testing.T) { - ctx, clientsMock := prepareMocks(tt.triggersListResponse, tt.globResponse, tt.triggersCreateResponse, nil /*trigger create error*/) + ctx, clientsMock := prepareMocks(t, tt.triggersListResponse, tt.globResponse, tt.triggersCreateResponse, nil /*trigger create error*/) clientsMock.IO.On("SelectPrompt", mock.Anything, "Choose a trigger definition file:", mock.Anything, iostreams.MatchPromptConfig(iostreams.SelectPromptConfig{ Flag: clientsMock.Config.Flags.Lookup("trigger-def"), })).Return(iostreams.SelectPromptResponse{ @@ -127,7 +128,7 @@ func Test_TriggerGenerate_skip_prompt(t *testing.T) { } t.Run(tt.name, func(t *testing.T) { - ctx, clientsMock := prepareMocks(tt.triggersListResponse, tt.globResponse, tt.triggersCreateResponse, nil /*trigger create error*/) + ctx, clientsMock := prepareMocks(t, tt.triggersListResponse, tt.globResponse, tt.triggersCreateResponse, nil /*trigger create error*/) clientsMock.ApiInterface.On("ListCollaborators", mock.Anything, mock.Anything, mock.Anything).Return([]types.SlackUser{}, nil) clientsMock.ApiInterface.On("TriggerPermissionsList", mock.Anything, mock.Anything, mock.Anything). Return(types.EVERYONE, []string{}, nil).Once() @@ -158,7 +159,7 @@ func Test_TriggerGenerate_handle_error(t *testing.T) { } t.Run(tt.name, func(t *testing.T) { - ctx, clientsMock := prepareMocks(tt.triggersListResponse, tt.globResponse, tt.triggersCreateResponse, fmt.Errorf("something went wrong") /*trigger create error*/) + ctx, clientsMock := prepareMocks(t, tt.triggersListResponse, tt.globResponse, tt.triggersCreateResponse, fmt.Errorf("something went wrong") /*trigger create error*/) clientsMock.IO.On("SelectPrompt", mock.Anything, "Choose a trigger definition file:", mock.Anything, iostreams.MatchPromptConfig(iostreams.SelectPromptConfig{ Flag: clientsMock.Config.Flags.Lookup("trigger-def"), })).Return(iostreams.SelectPromptResponse{ @@ -197,7 +198,7 @@ func Test_TriggerGenerate_handle_invalid_paths(t *testing.T) { } t.Run(tt.name, func(t *testing.T) { - ctx, clientsMock := prepareMocks(tt.triggersListResponse, tt.globResponse, tt.triggersCreateResponse, nil) + ctx, clientsMock := prepareMocks(t, tt.triggersListResponse, tt.globResponse, tt.triggersCreateResponse, nil) clients := shared.NewClientFactory(clientsMock.MockClientFactory(), func(clients *shared.ClientFactory) { clients.SDKConfig = hooks.NewSDKConfigMock() @@ -226,7 +227,7 @@ func Test_TriggerGenerate_Config_TriggerPaths_Default(t *testing.T) { } t.Run(tt.name, func(t *testing.T) { - ctx, clientsMock := prepareMocks(tt.triggersListResponse, tt.globResponse, tt.triggersCreateResponse, nil /*trigger create error*/) + ctx, clientsMock := prepareMocks(t, tt.triggersListResponse, tt.globResponse, tt.triggersCreateResponse, nil /*trigger create error*/) clientsMock.IO.On("SelectPrompt", mock.Anything, "Choose a trigger definition file:", mock.Anything, iostreams.MatchPromptConfig(iostreams.SelectPromptConfig{ Flag: clientsMock.Config.Flags.Lookup("trigger-def"), })).Return(iostreams.SelectPromptResponse{ @@ -266,7 +267,7 @@ func Test_TriggerGenerate_Config_TriggerPaths_Custom(t *testing.T) { } t.Run(tt.name, func(t *testing.T) { - ctx, clientsMock := prepareMocks(tt.triggersListResponse, tt.globResponse, tt.triggersCreateResponse, nil /*trigger create error*/) + ctx, clientsMock := prepareMocks(t, tt.triggersListResponse, tt.globResponse, tt.triggersCreateResponse, nil /*trigger create error*/) clientsMock.IO.On("SelectPrompt", mock.Anything, "Choose a trigger definition file:", mock.Anything, iostreams.MatchPromptConfig(iostreams.SelectPromptConfig{ Flag: clientsMock.Config.Flags.Lookup("trigger-def"), })).Return(iostreams.SelectPromptResponse{ @@ -451,8 +452,8 @@ func Test_ShowTriggers(t *testing.T) { } } -func prepareMocks(triggersListResponse []types.DeployedTrigger, globResponse []string, triggersCreateResponse types.DeployedTrigger, triggersCreateResponseError error) (context.Context, *shared.ClientsMock) { - ctx := context.Background() +func prepareMocks(t *testing.T, triggersListResponse []types.DeployedTrigger, globResponse []string, triggersCreateResponse types.DeployedTrigger, triggersCreateResponseError error) (context.Context, *shared.ClientsMock) { + ctx := slackcontext.MockContext(t.Context()) ctx = config.SetContextToken(ctx, "token") clientsMock := shared.NewClientsMock() diff --git a/internal/app/app_client_test.go b/internal/app/app_client_test.go index 1f7c5078..013baba5 100644 --- a/internal/app/app_client_test.go +++ b/internal/app/app_client_test.go @@ -15,7 +15,6 @@ package app import ( - "context" "encoding/json" "errors" "os" @@ -24,6 +23,7 @@ import ( "github.com/slackapi/slack-cli/internal/config" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackdeps" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/spf13/afero" @@ -211,8 +211,9 @@ func Test_AppClient_ReadDevApps_BrokenAppsJSON(t *testing.T) { func Test_AppClient_getDeployedAppTeamDomain_ViaCLIFlag(t *testing.T) { ac, _, _, _, _, teardown := setup(t) defer teardown(t) + ctx := slackcontext.MockContext(t.Context()) ac.config.TeamFlag = "flagname" - name := ac.getDeployedAppTeamDomain(context.Background()) + name := ac.getDeployedAppTeamDomain(ctx) assert.Equal(t, "flagname", name) } @@ -220,7 +221,7 @@ func Test_AppClient_getDeployedAppTeamDomain_ViaCLIFlag(t *testing.T) { func Test_AppClient_getDeployedAppTeamDomain_ViaDefaultDef(t *testing.T) { ac, _, _, _, _, teardown := setup(t) defer teardown(t) - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) err := ac.apps.Set(types.App{ TeamID: "T123", TeamDomain: "shouty-rooster", @@ -235,7 +236,7 @@ func Test_AppClient_getDeployedAppTeamDomain_ViaDefaultDef(t *testing.T) { func Test_AppClient_getDeployedAppTeamDomain_ViaDefaultAppName(t *testing.T) { ac, _, _, _, _, teardown := setup(t) defer teardown(t) - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) name := ac.getDeployedAppTeamDomain(ctx) assert.Equal(t, "prod", name) } @@ -244,7 +245,7 @@ func Test_AppClient_getDeployedAppTeamDomain_ViaDefaultAppName(t *testing.T) { func Test_AppClient_GetDeployed_Empty(t *testing.T) { ac, _, _, _, _, teardown := setup(t) defer teardown(t) - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) // FIXME: This action is unsafely fetching an app. Please explicitly supply a TeamID // This test case is specifically trying to test existing behavior when "" supplied @@ -257,7 +258,7 @@ func Test_AppClient_GetDeployed_Empty(t *testing.T) { func Test_AppClient_GetDeployed_DefaultApp(t *testing.T) { ac, _, _, pathToAppsJSON, _, teardown := setup(t) defer teardown(t) - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) jsonContents := []byte(`{ "apps":{ "twistandshout":{ @@ -281,7 +282,7 @@ func Test_AppClient_GetDeployed_DefaultApp(t *testing.T) { func Test_AppClient_GetDeployed_TeamID_NoDefault(t *testing.T) { ac, _, _, pathToAppsJSON, _, teardown := setup(t) defer teardown(t) - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) jsonContents := []byte(`{ "apps":{ "T1":{ @@ -302,7 +303,7 @@ func Test_AppClient_GetDeployed_TeamID_NoDefault(t *testing.T) { func Test_AppClient_GetLocal_Empty(t *testing.T) { ac, _, _, _, _, teardown := setup(t) defer teardown(t) - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) app, err := ac.GetLocal(ctx, "T123") require.NoError(t, err) assert.True(t, app.IsNew()) @@ -312,7 +313,7 @@ func Test_AppClient_GetLocal_Empty(t *testing.T) { func Test_AppClient_GetLocal_SingleApp(t *testing.T) { ac, _, _, _, pathToDevAppsJSON, teardown := setup(t) defer teardown(t) - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) jsonContents := []byte(`{ "U123":{ "name":"dev", @@ -332,7 +333,7 @@ func Test_AppClient_GetLocal_SingleApp(t *testing.T) { func Test_AppClient_GetDeployedAll_Empty(t *testing.T) { ac, _, _, _, _, teardown := setup(t) defer teardown(t) - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) apps, defaultName, err := ac.GetDeployedAll(ctx) require.NoError(t, err) assert.Equal(t, []types.App{}, apps) @@ -343,7 +344,7 @@ func Test_AppClient_GetDeployedAll_Empty(t *testing.T) { func Test_AppClient_GetDeployedAll_SomeApps(t *testing.T) { ac, _, _, pathToAppsJSON, _, teardown := setup(t) defer teardown(t) - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) jsonContents := []byte(`{ "apps":{ "twistandshout":{ @@ -372,7 +373,7 @@ func Test_AppClient_GetDeployedAll_SomeApps(t *testing.T) { func Test_AppClient_GetLocalAll_Empty(t *testing.T) { ac, _, _, _, _, teardown := setup(t) defer teardown(t) - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) apps, err := ac.GetLocalAll(ctx) require.NoError(t, err) assert.Equal(t, []types.App{}, apps) @@ -382,7 +383,7 @@ func Test_AppClient_GetLocalAll_Empty(t *testing.T) { func Test_AppClient_GetLocalAll_SomeApps(t *testing.T) { ac, _, _, _, pathToDevAppsJSON, teardown := setup(t) defer teardown(t) - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) jsonContents := []byte(`{ "U123":{ "name":"dev", @@ -401,7 +402,7 @@ func Test_AppClient_GetLocalAll_SomeApps(t *testing.T) { func Test_AppClient_Save_Empty(t *testing.T) { ac, _, _, pathToAppsJSON, _, teardown := setup(t) defer teardown(t) - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) app := types.App{ TeamID: "T123", TeamDomain: "shouty-rooster", @@ -430,7 +431,7 @@ func Test_AppClient_Save_Empty(t *testing.T) { func Test_AppClient_Save_NotEmpty(t *testing.T) { ac, _, _, pathToAppsJSON, _, teardown := setup(t) defer teardown(t) - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) app := types.App{ TeamID: "T123", TeamDomain: "shouty-rooster", @@ -467,7 +468,7 @@ func Test_AppClient_Save_NotEmpty(t *testing.T) { func Test_AppClient_SaveLocal_Empty(t *testing.T) { ac, _, _, _, pathToDevAppsJSON, teardown := setup(t) defer teardown(t) - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) appTeamID := "T1" app := types.App{ AppID: "A123", @@ -500,7 +501,7 @@ func Test_AppClient_SaveLocal_Empty(t *testing.T) { func Test_AppClient_SaveLocal_NotEmpty(t *testing.T) { ac, _, _, _, pathToDevAppsJSON, teardown := setup(t) defer teardown(t) - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) appTeamID := "T1" app := types.App{ AppID: "A123", @@ -533,7 +534,7 @@ func Test_AppClient_SaveLocal_NotEmpty(t *testing.T) { func Test_AppClient_RemoveDeployed(t *testing.T) { ac, _, _, _, _, teardown := setup(t) defer teardown(t) - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) app := types.App{ TeamID: "T123", TeamDomain: "shouty-rooster", @@ -557,7 +558,7 @@ func Test_AppClient_RemoveDeployed(t *testing.T) { func Test_AppClient_RemoveLocal(t *testing.T) { ac, _, _, _, _, teardown := setup(t) defer teardown(t) - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) app := types.App{ AppID: "A123", UserID: "U123", @@ -694,7 +695,7 @@ func TestAppClient_CleanupAppsJsonFiles(t *testing.T) { for _, tt := range tests { ac, _, _, pathToAppsJSON, pathToDevAppsJSON, teardown := setup(t) defer teardown(t) - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) err := afero.WriteFile(ac.fs, pathToAppsJSON, tt.appsJSON, 0600) require.NoError(t, err) diff --git a/internal/app/manifest_test.go b/internal/app/manifest_test.go index aaac8a56..8116f34e 100644 --- a/internal/app/manifest_test.go +++ b/internal/app/manifest_test.go @@ -15,13 +15,13 @@ package app import ( - "context" "testing" "github.com/slackapi/slack-cli/internal/api" "github.com/slackapi/slack-cli/internal/config" "github.com/slackapi/slack-cli/internal/hooks" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackdeps" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/stretchr/testify/assert" @@ -177,6 +177,7 @@ func Test_AppManifest_GetManifestRemote(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) fsMock := slackdeps.NewFsMock() osMock := slackdeps.NewOsMock() osMock.AddDefaultMocks() @@ -186,7 +187,6 @@ func Test_AppManifest_GetManifestRemote(t *testing.T) { Return(api.ExportAppResult{Manifest: tt.mockManifestResponse}, tt.mockManifestError) manifestClient := NewManifestClient(apic, configMock) - ctx := context.Background() manifest, err := manifestClient.GetManifestRemote(ctx, tt.mockToken, tt.mockAppID) if tt.expectedError != nil { assert.Equal(t, tt.expectedError, err) diff --git a/internal/cache/manifest_test.go b/internal/cache/manifest_test.go index bddb1200..880e076d 100644 --- a/internal/cache/manifest_test.go +++ b/internal/cache/manifest_test.go @@ -15,11 +15,11 @@ package cache import ( - "context" "path/filepath" "testing" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackdeps" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -43,13 +43,13 @@ func TestCache_Manifest(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) fsMock := slackdeps.NewFsMock() osMock := slackdeps.NewOsMock() projectDirPath := "/path/to/project-name" err := fsMock.MkdirAll(filepath.Dir(projectDirPath), 0o755) require.NoError(t, err) cache := NewCache(fsMock, osMock, projectDirPath) - ctx := context.Background() err = cache.SetManifestHash(ctx, tt.mockAppID, tt.mockCache.Hash) require.NoError(t, err) cache.ManifestCache.Apps = map[string]ManifestCacheApp{ @@ -104,12 +104,12 @@ func TestCache_Manifest_NewManifestHash(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) fsMock := slackdeps.NewFsMock() osMock := slackdeps.NewOsMock() projectDirPath := "/path/to/project-name" err := fsMock.MkdirAll(filepath.Dir(projectDirPath), 0o755) require.NoError(t, err) - ctx := context.Background() cache := NewCache(fsMock, osMock, projectDirPath) hash, err := cache.NewManifestHash(ctx, tt.mockManifest) assert.NoError(t, err) diff --git a/internal/cmdutil/project_test.go b/internal/cmdutil/project_test.go index d0cb35e2..149bfc22 100644 --- a/internal/cmdutil/project_test.go +++ b/internal/cmdutil/project_test.go @@ -15,7 +15,6 @@ package cmdutil import ( - "context" "fmt" "testing" @@ -23,6 +22,7 @@ import ( "github.com/slackapi/slack-cli/internal/config" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" @@ -79,6 +79,7 @@ func TestIsSlackHostedProject(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() manifestMock := &app.ManifestMockObject{} manifestMock.On( @@ -93,7 +94,6 @@ func TestIsSlackHostedProject(t *testing.T) { projectConfigMock := config.NewProjectConfigMock() projectConfigMock.On("GetManifestSource", mock.Anything).Return(tt.mockManifestSource, nil) clientsMock.Config.ProjectConfig = projectConfigMock - ctx := context.Background() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) err := IsSlackHostedProject(ctx, clients) assert.Equal(t, tt.expectedError, err) diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 8338bc05..7cea4538 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -20,6 +20,7 @@ import ( "testing" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackdeps" "github.com/spf13/afero" "github.com/stretchr/testify/assert" @@ -28,7 +29,7 @@ import ( // setup func setup(t *testing.T) (context.Context, *slackdeps.FsMock, *slackdeps.OsMock, *Config, string, func(*testing.T)) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() os.AddDefaultMocks() diff --git a/internal/config/project_test.go b/internal/config/project_test.go index 9423e68d..b53a00bb 100644 --- a/internal/config/project_test.go +++ b/internal/config/project_test.go @@ -15,7 +15,6 @@ package config import ( - "context" "os" "path/filepath" "testing" @@ -23,6 +22,7 @@ import ( "github.com/google/uuid" "github.com/slackapi/slack-cli/internal/cache" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackdeps" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/spf13/afero" @@ -56,7 +56,7 @@ func Test_ProjectConfig_NewProjectConfig(t *testing.T) { func Test_ProjectConfig_InitProjectID(t *testing.T) { t.Run("When not a project directory, should return an error", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -72,7 +72,7 @@ func Test_ProjectConfig_InitProjectID(t *testing.T) { }) t.Run("When project_id is empty, should init project_id", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -90,7 +90,7 @@ func Test_ProjectConfig_InitProjectID(t *testing.T) { }) t.Run("When project_id exists, should not overwrite project_id (overwrite: false)", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -114,7 +114,7 @@ func Test_ProjectConfig_InitProjectID(t *testing.T) { }) t.Run("When project_id exists, should overwrite project_id (overwrite: true)", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -141,7 +141,7 @@ func Test_ProjectConfig_InitProjectID(t *testing.T) { func Test_ProjectConfig_GetProjectID(t *testing.T) { t.Run("When not a project directory, should return an error", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -157,7 +157,7 @@ func Test_ProjectConfig_GetProjectID(t *testing.T) { }) t.Run("When a project directory, should return trimmed project_id", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -183,7 +183,7 @@ func Test_ProjectConfig_GetProjectID(t *testing.T) { func Test_ProjectConfig_SetProjectID(t *testing.T) { t.Run("When not a project directory, should return an error", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -200,7 +200,7 @@ func Test_ProjectConfig_SetProjectID(t *testing.T) { }) t.Run("When a project directory, should update the project_id", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -254,7 +254,7 @@ func Test_ProjectConfig_ManifestSource(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() os.AddDefaultMocks() @@ -274,7 +274,7 @@ func Test_ProjectConfig_ManifestSource(t *testing.T) { func Test_ProjectConfig_ReadProjectConfigFile(t *testing.T) { t.Run("When not a project directory, should return an error", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -289,7 +289,7 @@ func Test_ProjectConfig_ReadProjectConfigFile(t *testing.T) { }) t.Run("When project directory doesn't have a .slack/config.json, should return a default config.json", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -310,7 +310,7 @@ func Test_ProjectConfig_ReadProjectConfigFile(t *testing.T) { }) t.Run("When a project directory has a .slack/config.json, should return config.json", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -335,7 +335,7 @@ func Test_ProjectConfig_ReadProjectConfigFile(t *testing.T) { }) t.Run("errors on invalid formatting of project config file", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -360,7 +360,7 @@ func Test_ProjectConfig_ReadProjectConfigFile(t *testing.T) { func Test_ProjectConfig_WriteProjectConfigFile(t *testing.T) { t.Run("When not a project directory, should return an error", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -379,7 +379,7 @@ func Test_ProjectConfig_WriteProjectConfigFile(t *testing.T) { }) t.Run("When a project directory, should write the .slack/config.json file", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -502,11 +502,11 @@ func Test_ProjectConfig_Cache(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() os.AddDefaultMocks() addProjectMocks(t, fs) - ctx := context.Background() projectConfig := NewProjectConfig(fs, os) cache := projectConfig.Cache() if !tt.mockHash.Equals("") { @@ -563,7 +563,7 @@ func Test_Config_CreateProjectConfigDir(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := afero.NewMemMapFs() if tt.existingDir { err := fs.MkdirAll(tt.projectDirPath+"/.slack", 0755) diff --git a/internal/config/system_test.go b/internal/config/system_test.go index 24729ab0..7035a5be 100644 --- a/internal/config/system_test.go +++ b/internal/config/system_test.go @@ -15,7 +15,6 @@ package config import ( - "context" "encoding/json" "errors" _os "os" @@ -26,6 +25,7 @@ import ( "time" "github.com/google/uuid" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackdeps" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/spf13/afero" @@ -54,7 +54,7 @@ func Test_SystemConfig_SetCustomConfigDirPath(t *testing.T) { func Test_SystemConfig_UserConfig(t *testing.T) { t.Run("Error reading configuration directory", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -70,7 +70,7 @@ func Test_SystemConfig_UserConfig(t *testing.T) { }) t.Run("Error when configuration file does not exist", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -86,7 +86,7 @@ func Test_SystemConfig_UserConfig(t *testing.T) { }) t.Run("Error when configuration file has bad formatting", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -111,7 +111,7 @@ func Test_SystemConfig_UserConfig(t *testing.T) { func Test_Config_SlackConfigDir(t *testing.T) { t.Run("Return home directory by default", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -126,7 +126,7 @@ func Test_Config_SlackConfigDir(t *testing.T) { }) t.Run("Return custom directory when it exists", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -142,9 +142,8 @@ func Test_Config_SlackConfigDir(t *testing.T) { require.NoError(t, err) }) - // TODO(@mbrooks) Uncomment t.Run("Return error when custom directory is missing", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -161,7 +160,7 @@ func Test_Config_SlackConfigDir(t *testing.T) { }) t.Run("Return error when home directory and working directory are unavailable", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -178,7 +177,7 @@ func Test_Config_SlackConfigDir(t *testing.T) { }) t.Run("Return error when creating default config directory fails", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -195,7 +194,7 @@ func Test_Config_SlackConfigDir(t *testing.T) { }) t.Run("Keep existing configuration files", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -215,7 +214,7 @@ func Test_Config_SlackConfigDir(t *testing.T) { func Test_SystemConfig_LogsDir(t *testing.T) { t.Run("Create logs folder in .slack directory", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -233,7 +232,7 @@ func Test_SystemConfig_LogsDir(t *testing.T) { func Test_Config_GetLastUpdateCheckedAt(t *testing.T) { t.Run("Error reading User Configuration file returns current time", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -252,7 +251,7 @@ func Test_Config_GetLastUpdateCheckedAt(t *testing.T) { }) t.Run("Returns LastUpdateCheckedAt from User Configuration File", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -272,7 +271,7 @@ func Test_Config_GetLastUpdateCheckedAt(t *testing.T) { func Test_Config_SetLastUpdateCheckedAt(t *testing.T) { t.Run("Error reading User Configuration file", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -290,7 +289,7 @@ func Test_Config_SetLastUpdateCheckedAt(t *testing.T) { }) t.Run("Writes LastUpdateCheckedAt to User Configuration file", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -311,7 +310,7 @@ func Test_Config_SetLastUpdateCheckedAt(t *testing.T) { func Test_SystemConfig_GetSystemID(t *testing.T) { t.Run("When no system_id is set, should return empty string", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -326,7 +325,7 @@ func Test_SystemConfig_GetSystemID(t *testing.T) { }) t.Run("When system_id is set, should return system_id", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -351,7 +350,7 @@ func Test_SystemConfig_GetSystemID(t *testing.T) { func Test_SystemConfig_SetSystemID(t *testing.T) { t.Run("Should update the system_id", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -385,7 +384,7 @@ func Test_SystemConfig_SetSystemID(t *testing.T) { func Test_SystemConfig_InitSystemID(t *testing.T) { t.Run("When system_id is empty, should generate a new system_id", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -413,7 +412,7 @@ func Test_SystemConfig_InitSystemID(t *testing.T) { }) t.Run("When system_id is not empty, should not overwrite it", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -596,7 +595,7 @@ func Test_SystemConfig_writeConfigFile(t *testing.T) { func Test_SystemConfig_GetTrustUnknownSources(t *testing.T) { t.Run("When no trust_unknown_sources is set, should return false", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -611,7 +610,7 @@ func Test_SystemConfig_GetTrustUnknownSources(t *testing.T) { }) t.Run("When trust_unknown_sources is set, should return true", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() @@ -635,7 +634,7 @@ func Test_SystemConfig_GetTrustUnknownSources(t *testing.T) { func Test_SystemConfig_SetTrustUnknownSources(t *testing.T) { t.Run("Should update the trust_unknown_sources", func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() diff --git a/internal/iostreams/logfile_test.go b/internal/iostreams/logfile_test.go index 89e93843..8ffd02ae 100644 --- a/internal/iostreams/logfile_test.go +++ b/internal/iostreams/logfile_test.go @@ -16,7 +16,6 @@ package iostreams import ( "bytes" - "context" "fmt" "log" "os" @@ -26,6 +25,7 @@ import ( "github.com/slackapi/slack-cli/internal/config" "github.com/slackapi/slack-cli/internal/goutils" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackdeps" "github.com/spf13/afero" "github.com/stretchr/testify/assert" @@ -162,6 +162,7 @@ func Test_FlushToLogFile(t *testing.T) { stderrBuff := bytes.Buffer{} stderrLogger := log.Logger{} stderrLogger.SetOutput(&stderrBuff) + ctx := slackcontext.MockContext(t.Context()) fsMock := slackdeps.NewFsMock() osMock := slackdeps.NewOsMock() osMock.AddDefaultMocks() @@ -173,7 +174,6 @@ func Test_FlushToLogFile(t *testing.T) { io = NewIOStreams(config, fsMock, osMock) io.Stderr = &stderrLogger - ctx := context.Background() err := io.FlushToLogFile(ctx, tt.prefix, tt.errStr) require.NoError(t, err) diff --git a/internal/iostreams/printer_test.go b/internal/iostreams/printer_test.go index 6cb37d92..064ca3e2 100644 --- a/internal/iostreams/printer_test.go +++ b/internal/iostreams/printer_test.go @@ -16,7 +16,6 @@ package iostreams import ( "bytes" - "context" "fmt" "log" "regexp" @@ -24,6 +23,7 @@ import ( "testing" "github.com/slackapi/slack-cli/internal/config" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackdeps" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -59,6 +59,7 @@ func Test_PrintDebug(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) fsMock := slackdeps.NewFsMock() osMock := slackdeps.NewOsMock() osMock.AddDefaultMocks() @@ -69,7 +70,6 @@ func Test_PrintDebug(t *testing.T) { stdoutLogger := log.Logger{} stdoutLogger.SetOutput(&stdoutBuffer) io.Stdout = &stdoutLogger - ctx := context.Background() io.PrintDebug(ctx, tt.format, tt.arguments...) // Assert output lines match the pattern: [YYYY-MM-DD HH:MM:SS] line @@ -127,6 +127,7 @@ func Test_PrintWarning(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) fsMock := slackdeps.NewFsMock() osMock := slackdeps.NewOsMock() osMock.AddDefaultMocks() @@ -136,7 +137,6 @@ func Test_PrintWarning(t *testing.T) { stderrLogger := log.Logger{} stderrLogger.SetOutput(&stderrBuffer) io.Stderr = &stderrLogger - ctx := context.Background() io.PrintWarning(ctx, tt.format, tt.arguments...) assert.Equal(t, tt.expected, stderrBuffer.String()) }) @@ -185,13 +185,13 @@ func Test_IOStreams_PrintTrace(t *testing.T) { for name, tt := range tests { t.Run(name, func(t *testing.T) { // Setup + ctx := slackcontext.MockContext(t.Context()) var fsMock = slackdeps.NewFsMock() var osMock = slackdeps.NewOsMock() var config = config.NewConfig(fsMock, osMock) config.SlackTestTraceFlag = tt.traceEnabled var io = NewIOStreams(config, fsMock, osMock) - var ctx = context.Background() var stdoutBuffer = bytes.Buffer{} var stdoutLogger = log.Logger{} diff --git a/internal/iostreams/survey_test.go b/internal/iostreams/survey_test.go index 14ce7c4a..9fcda057 100644 --- a/internal/iostreams/survey_test.go +++ b/internal/iostreams/survey_test.go @@ -15,11 +15,11 @@ package iostreams import ( - "context" "fmt" "testing" "github.com/slackapi/slack-cli/internal/config" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackdeps" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/spf13/pflag" @@ -74,7 +74,7 @@ func TestPasswordPrompt(t *testing.T) { for name, tt := range tests { t.Run(name, func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fsMock := slackdeps.NewFsMock() osMock := slackdeps.NewOsMock() if tt.IsInteractive { diff --git a/internal/pkg/apps/delete_test.go b/internal/pkg/apps/delete_test.go index a8aa330a..d3ac90dc 100644 --- a/internal/pkg/apps/delete_test.go +++ b/internal/pkg/apps/delete_test.go @@ -15,13 +15,13 @@ package apps import ( - "context" "testing" "github.com/slackapi/slack-cli/internal/api" "github.com/slackapi/slack-cli/internal/logger" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -79,6 +79,7 @@ func TestAppsDelete(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AuthInterface.On("ResolveApiHost", mock.Anything, mock.Anything, mock.Anything).Return("api host") clientsMock.AuthInterface.On("ResolveLogstashHost", mock.Anything, mock.Anything, mock.Anything).Return("logstash host") @@ -89,7 +90,6 @@ func TestAppsDelete(t *testing.T) { clientsMock.ApiInterface.On("DeleteApp", mock.Anything, mock.Anything, tt.app.AppID).Return(nil) clientsMock.AddDefaultMocks() - ctx := context.Background() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) if !tt.unsaved { if !tt.app.IsDev { diff --git a/internal/pkg/apps/install_test.go b/internal/pkg/apps/install_test.go index 1e064dc0..c3890c86 100644 --- a/internal/pkg/apps/install_test.go +++ b/internal/pkg/apps/install_test.go @@ -16,7 +16,6 @@ package apps import ( "bytes" - "context" "testing" "github.com/slackapi/slack-cli/internal/api" @@ -27,6 +26,7 @@ import ( "github.com/slackapi/slack-cli/internal/logger" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" @@ -455,7 +455,7 @@ func TestInstall(t *testing.T) { for name, tt := range tests { t.Run(name, func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.IO.On("IsTTY").Return(tt.mockIsTTY) clientsMock.AddDefaultMocks() @@ -898,7 +898,7 @@ func TestInstallLocalApp(t *testing.T) { for name, tt := range tests { t.Run(name, func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.IO.On("IsTTY").Return(tt.mockIsTTY) clientsMock.AddDefaultMocks() @@ -1144,7 +1144,7 @@ func TestValidateManifestForInstall(t *testing.T) { for name, tt := range tests { t.Run(name, func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() tt.setup(clientsMock) clientsMock.ApiInterface.On("ValidateAppManifest", mock.Anything, mock.Anything, mock.Anything, tt.app.AppID). @@ -1217,6 +1217,7 @@ func TestSetAppEnvironmentTokens(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.IO.AddDefaultMocks() if tt.envAppToken != "" { @@ -1236,7 +1237,6 @@ func TestSetAppEnvironmentTokens(t *testing.T) { clientsMock.IO.Stdout.SetOutput(output) clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() err := setAppEnvironmentTokens(ctx, clients, tt.result) assert.NoError(t, err) assert.Equal(t, tt.expectedAppToken, clients.Os.Getenv("SLACK_APP_TOKEN")) diff --git a/internal/pkg/apps/list_test.go b/internal/pkg/apps/list_test.go index b7865b1c..b64fa9b5 100644 --- a/internal/pkg/apps/list_test.go +++ b/internal/pkg/apps/list_test.go @@ -15,12 +15,12 @@ package apps import ( - "context" "testing" "github.com/slackapi/slack-cli/internal/api" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" @@ -91,11 +91,11 @@ var team2LocalApp = types.App{ } func TestAppsList_FetchInstallStates_NoAuthsShouldReturnUnknownState(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() apps, err := FetchAppInstallStates(ctx, clients, []types.App{team1DeployedApp, team2LocalApp}) require.NoError(t, err) clientsMock.ApiInterface.AssertNotCalled(t, "GetAppStatus") @@ -109,6 +109,7 @@ func TestAppsList_FetchInstallStates_NoAuthsShouldReturnUnknownState(t *testing. func TestAppsList_FetchInstallStates_HasEnterpriseApp_HasEnterpriseAuth(t *testing.T) { // Create mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AuthInterface.On("Auths", mock.Anything).Return([]types.SlackAuth{ @@ -126,7 +127,6 @@ func TestAppsList_FetchInstallStates_HasEnterpriseApp_HasEnterpriseAuth(t *testi }, nil) require.True(t, team1DeployedApp.IsEnterpriseWorkspaceApp()) - ctx := context.Background() // Should successfully fetchAppInstallStates when the auth is enterprise and the app is enterprise workspace app appsWithStatus, _ := FetchAppInstallStates(ctx, clients, []types.App{team1DeployedApp}) @@ -135,6 +135,7 @@ func TestAppsList_FetchInstallStates_HasEnterpriseApp_HasEnterpriseAuth(t *testi } func TestAppsList_FetchInstallStates_TokenFlag(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AuthInterface.On("Auths", mock.Anything). @@ -156,7 +157,6 @@ func TestAppsList_FetchInstallStates_TokenFlag(t *testing.T) { clients.Config.TokenFlag = team2Token - ctx := context.Background() apps, err := FetchAppInstallStates(ctx, clients, []types.App{team1DeployedApp, team2LocalApp}) require.NoError(t, err) require.Len(t, apps, 2) @@ -173,6 +173,7 @@ func TestAppsList_FetchInstallStates_TokenFlag(t *testing.T) { } func TestAppsList_FetchInstallStates_InvalidTokenFlag(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AuthInterface.On("Auths", mock.Anything). Return([]types.SlackAuth{}, nil) @@ -183,7 +184,6 @@ func TestAppsList_FetchInstallStates_InvalidTokenFlag(t *testing.T) { clients.Config.TokenFlag = "xoxp-invalid" - ctx := context.Background() apps, err := FetchAppInstallStates(ctx, clients, []types.App{team1DeployedApp, team2LocalApp}) if assert.Error(t, err) { assert.Equal(t, slackerror.New(slackerror.ErrHttpRequestFailed), err) diff --git a/internal/pkg/auth/list_test.go b/internal/pkg/auth/list_test.go index 909ed892..893c188c 100644 --- a/internal/pkg/auth/list_test.go +++ b/internal/pkg/auth/list_test.go @@ -15,7 +15,6 @@ package auth import ( - "context" "errors" "testing" "time" @@ -24,16 +23,17 @@ import ( "github.com/slackapi/slack-cli/internal/logger" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" ) func TestAuthList(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clients := shared.NewClientFactory(clientsMock.MockClientFactory(), func(clients *shared.ClientFactory) { clients.SDKConfig = hooks.NewSDKConfigMock() }) - ctx := context.Background() authMockA := types.SlackAuth{ Token: "xoxe.xoxp-", @@ -58,11 +58,11 @@ func TestAuthList(t *testing.T) { } func TestAuthList_SortedAuths(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clients := shared.NewClientFactory(clientsMock.MockClientFactory(), func(clients *shared.ClientFactory) { clients.SDKConfig = hooks.NewSDKConfigMock() }) - ctx := context.Background() authZ := types.SlackAuth{ Token: "xoxp-abc", diff --git a/internal/pkg/create/create_test.go b/internal/pkg/create/create_test.go index e2e63d07..9cc3abfd 100644 --- a/internal/pkg/create/create_test.go +++ b/internal/pkg/create/create_test.go @@ -15,7 +15,6 @@ package create import ( - "context" "fmt" "path/filepath" "testing" @@ -23,6 +22,7 @@ import ( "github.com/slackapi/slack-cli/internal/config" "github.com/slackapi/slack-cli/internal/experiment" "github.com/slackapi/slack-cli/internal/shared" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/spf13/afero" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" @@ -220,17 +220,17 @@ func Test_Create_installProjectDependencies(t *testing.T) { }() // Setup parameters for test - ctx := context.Background() projectDirPath := "/path/to/project-name" // Create mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.Os.On("Getwd").Return(projectDirPath, nil) clientsMock.AddDefaultMocks() // Set experiment flag clientsMock.Config.ExperimentsFlag = append(clientsMock.Config.ExperimentsFlag, tt.experiments...) - clientsMock.Config.LoadExperiments(context.Background(), clientsMock.IO.PrintDebug) + clientsMock.Config.LoadExperiments(ctx, clientsMock.IO.PrintDebug) // Create clients that is mocked for testing clients := shared.NewClientFactory(clientsMock.MockClientFactory()) diff --git a/internal/pkg/datastore/bulk_delete_test.go b/internal/pkg/datastore/bulk_delete_test.go index 350d3315..a689baac 100644 --- a/internal/pkg/datastore/bulk_delete_test.go +++ b/internal/pkg/datastore/bulk_delete_test.go @@ -15,12 +15,12 @@ package datastore import ( - "context" "testing" "github.com/slackapi/slack-cli/internal/logger" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" ) @@ -57,6 +57,7 @@ func TestDatastoreBulkDeleteArguments(t *testing.T) { }, } { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() log := logger.Logger{ Data: map[string]interface{}{}, @@ -65,7 +66,7 @@ func TestDatastoreBulkDeleteArguments(t *testing.T) { Return(tt.Results, nil) client := shared.NewClientFactory(clientsMock.MockClientFactory()) - event, err := BulkDelete(context.Background(), client, &log, tt.Query) + event, err := BulkDelete(ctx, client, &log, tt.Query) if assert.NoError(t, err) { assert.Equal(t, tt.Results, event.Data["bulkDeleteResult"]) } diff --git a/internal/pkg/datastore/bulk_get_test.go b/internal/pkg/datastore/bulk_get_test.go index 2bfc7812..8c07f499 100644 --- a/internal/pkg/datastore/bulk_get_test.go +++ b/internal/pkg/datastore/bulk_get_test.go @@ -15,12 +15,12 @@ package datastore import ( - "context" "testing" "github.com/slackapi/slack-cli/internal/logger" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" ) @@ -58,6 +58,7 @@ func TestDatastoreBulkGetArguments(t *testing.T) { }, } { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() log := logger.Logger{ Data: map[string]interface{}{}, @@ -66,7 +67,7 @@ func TestDatastoreBulkGetArguments(t *testing.T) { Return(tt.Results, nil) client := shared.NewClientFactory(clientsMock.MockClientFactory()) - event, err := BulkGet(context.Background(), client, &log, tt.Query) + event, err := BulkGet(ctx, client, &log, tt.Query) if assert.NoError(t, err) { assert.Equal(t, tt.Results, event.Data["bulkGetResult"]) } diff --git a/internal/pkg/datastore/bulk_put_test.go b/internal/pkg/datastore/bulk_put_test.go index 42724be8..db3e8bb0 100644 --- a/internal/pkg/datastore/bulk_put_test.go +++ b/internal/pkg/datastore/bulk_put_test.go @@ -15,12 +15,12 @@ package datastore import ( - "context" "testing" "github.com/slackapi/slack-cli/internal/logger" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" ) @@ -65,6 +65,7 @@ func TestDatastoreBulkPutArguments(t *testing.T) { }, } { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() log := logger.Logger{ Data: map[string]interface{}{}, @@ -73,7 +74,7 @@ func TestDatastoreBulkPutArguments(t *testing.T) { Return(tt.Results, nil) client := shared.NewClientFactory(clientsMock.MockClientFactory()) - event, err := BulkPut(context.Background(), client, &log, tt.Query) + event, err := BulkPut(ctx, client, &log, tt.Query) if assert.NoError(t, err) { assert.Equal(t, tt.Results, event.Data["bulkPutResult"]) } diff --git a/internal/pkg/datastore/delete_test.go b/internal/pkg/datastore/delete_test.go index c0917824..a24cb61b 100644 --- a/internal/pkg/datastore/delete_test.go +++ b/internal/pkg/datastore/delete_test.go @@ -15,12 +15,12 @@ package datastore import ( - "context" "testing" "github.com/slackapi/slack-cli/internal/logger" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" ) @@ -46,6 +46,7 @@ func TestDatastoreDeleteArguments(t *testing.T) { }, } { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() log := logger.Logger{ Data: map[string]interface{}{}, @@ -54,7 +55,7 @@ func TestDatastoreDeleteArguments(t *testing.T) { Return(tt.Results, nil) client := shared.NewClientFactory(clientsMock.MockClientFactory()) - event, err := Delete(context.Background(), client, &log, tt.Query) + event, err := Delete(ctx, client, &log, tt.Query) if assert.NoError(t, err) { assert.Equal(t, tt.Results, event.Data["deleteResult"]) } diff --git a/internal/pkg/datastore/get_test.go b/internal/pkg/datastore/get_test.go index bffef9b2..654c1df7 100644 --- a/internal/pkg/datastore/get_test.go +++ b/internal/pkg/datastore/get_test.go @@ -15,12 +15,12 @@ package datastore import ( - "context" "testing" "github.com/slackapi/slack-cli/internal/logger" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" ) @@ -46,6 +46,7 @@ func TestDatastoreGetArguments(t *testing.T) { }, } { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() log := logger.Logger{ Data: map[string]interface{}{}, @@ -54,7 +55,7 @@ func TestDatastoreGetArguments(t *testing.T) { Return(tt.Results, nil) client := shared.NewClientFactory(clientsMock.MockClientFactory()) - event, err := Get(context.Background(), client, &log, tt.Query) + event, err := Get(ctx, client, &log, tt.Query) if assert.NoError(t, err) { assert.Equal(t, tt.Results, event.Data["getResult"]) } diff --git a/internal/pkg/datastore/put_test.go b/internal/pkg/datastore/put_test.go index d7280d11..945680f1 100644 --- a/internal/pkg/datastore/put_test.go +++ b/internal/pkg/datastore/put_test.go @@ -15,12 +15,12 @@ package datastore import ( - "context" "testing" "github.com/slackapi/slack-cli/internal/logger" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" ) @@ -46,6 +46,7 @@ func TestDatastorePutArguments(t *testing.T) { }, } { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() log := logger.Logger{ Data: map[string]interface{}{}, @@ -54,7 +55,7 @@ func TestDatastorePutArguments(t *testing.T) { Return(tt.Results, nil) client := shared.NewClientFactory(clientsMock.MockClientFactory()) - event, err := Put(context.Background(), client, &log, tt.Query) + event, err := Put(ctx, client, &log, tt.Query) if assert.NoError(t, err) { assert.Equal(t, tt.Results, event.Data["putResult"]) } diff --git a/internal/pkg/datastore/query_test.go b/internal/pkg/datastore/query_test.go index 835a2e14..684e3af4 100644 --- a/internal/pkg/datastore/query_test.go +++ b/internal/pkg/datastore/query_test.go @@ -15,12 +15,12 @@ package datastore import ( - "context" "testing" "github.com/slackapi/slack-cli/internal/logger" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" ) @@ -104,6 +104,7 @@ func TestDatastoreQueryArguments(t *testing.T) { }, } { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() log := logger.Logger{ Data: map[string]interface{}{}, @@ -112,7 +113,7 @@ func TestDatastoreQueryArguments(t *testing.T) { Return(tt.Results, nil) client := shared.NewClientFactory(clientsMock.MockClientFactory()) - event, err := Query(context.Background(), client, &log, tt.Query) + event, err := Query(ctx, client, &log, tt.Query) if assert.NoError(t, err) { assert.Equal(t, tt.Results, event.Data["queryResult"]) } diff --git a/internal/pkg/datastore/update_test.go b/internal/pkg/datastore/update_test.go index e8b0adab..dd18063d 100644 --- a/internal/pkg/datastore/update_test.go +++ b/internal/pkg/datastore/update_test.go @@ -15,12 +15,12 @@ package datastore import ( - "context" "testing" "github.com/slackapi/slack-cli/internal/logger" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" ) @@ -46,6 +46,7 @@ func TestDatastoreUpdateArguments(t *testing.T) { }, } { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() log := logger.Logger{ Data: map[string]interface{}{}, @@ -54,7 +55,7 @@ func TestDatastoreUpdateArguments(t *testing.T) { Return(tt.Results, nil) client := shared.NewClientFactory(clientsMock.MockClientFactory()) - event, err := Update(context.Background(), client, &log, tt.Query) + event, err := Update(ctx, client, &log, tt.Query) if assert.NoError(t, err) { assert.Equal(t, tt.Results, event.Data["updateResult"]) } diff --git a/internal/pkg/externalauth/prompt_provider_auth_select_test.go b/internal/pkg/externalauth/prompt_provider_auth_select_test.go index 43d6e620..f9778b6b 100644 --- a/internal/pkg/externalauth/prompt_provider_auth_select_test.go +++ b/internal/pkg/externalauth/prompt_provider_auth_select_test.go @@ -15,23 +15,23 @@ package externalauth import ( - "context" "testing" "github.com/slackapi/slack-cli/internal/iostreams" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" ) func TestPrompt_ProviderAuthSelectPrompt_empty_list(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) workflowsInfo := types.WorkflowsInfo{} clientsMock.AddDefaultMocks() - ctx := context.Background() selectedProvider, err := ProviderAuthSelectPrompt(ctx, clients, workflowsInfo) require.Empty(t, selectedProvider) require.Error(t, err, slackerror.New("No oauth2 providers found")) @@ -84,6 +84,7 @@ func TestPrompt_ProviderAuthSelectPrompt_no_selected_auth(t *testing.T) { for _, tt := range tests { var mockProviderFlag string + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) clientsMock.Config.Flags.StringVar(&mockProviderFlag, "provider", "", "mock provider flag") @@ -95,7 +96,6 @@ func TestPrompt_ProviderAuthSelectPrompt_no_selected_auth(t *testing.T) { })).Return(tt.Selection, nil) clientsMock.AddDefaultMocks() - ctx := context.Background() selectedProvider, err := ProviderAuthSelectPrompt(ctx, clients, workflowsInfo) require.Equal(t, selectedProvider.ProviderKey, "provider_a") @@ -151,6 +151,7 @@ func TestPrompt_ProviderAuthSelectPrompt_with_selected_auth(t *testing.T) { for _, tt := range tests { var mockProviderFlag string + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) clientsMock.Config.Flags.StringVar(&mockProviderFlag, "provider", "", "mock provider flag") @@ -158,7 +159,6 @@ func TestPrompt_ProviderAuthSelectPrompt_with_selected_auth(t *testing.T) { Flag: clientsMock.Config.Flags.Lookup("provider"), })).Return(tt.Selection, nil) clientsMock.AddDefaultMocks() - ctx := context.Background() selectedProvider, err := ProviderAuthSelectPrompt(ctx, clients, workflowsInfo) require.Equal(t, selectedProvider.ProviderKey, "provider_b") diff --git a/internal/pkg/externalauth/prompt_provider_select_test.go b/internal/pkg/externalauth/prompt_provider_select_test.go index 8e8b4c1d..670b20c1 100644 --- a/internal/pkg/externalauth/prompt_provider_select_test.go +++ b/internal/pkg/externalauth/prompt_provider_select_test.go @@ -15,23 +15,23 @@ package externalauth import ( - "context" "testing" "github.com/slackapi/slack-cli/internal/iostreams" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" ) func TestPrompt_ProviderSelectPrompt_empty_list(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) authorizationInfoLists := types.ExternalAuthorizationInfoLists{} clientsMock.AddDefaultMocks() - ctx := context.Background() selectedProvider, err := ProviderSelectPrompt(ctx, clients, authorizationInfoLists) require.Empty(t, selectedProvider) require.Error(t, err, slackerror.New("No oauth2 providers found")) @@ -74,6 +74,7 @@ func TestPrompt_ProviderSelectPrompt_no_token(t *testing.T) { for _, tt := range tests { var mockProviderFlag string + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) clientsMock.Config.Flags.StringVar(&mockProviderFlag, "provider", "", "mock provider flag") @@ -81,7 +82,6 @@ func TestPrompt_ProviderSelectPrompt_no_token(t *testing.T) { Flag: clientsMock.Config.Flags.Lookup("provider"), })).Return(tt.Selection, nil) clientsMock.AddDefaultMocks() - ctx := context.Background() selectedProvider, err := ProviderSelectPrompt(ctx, clients, authorizationInfoLists) require.Equal(t, selectedProvider.ProviderKey, "provider_a") @@ -136,6 +136,7 @@ func TestPrompt_ProviderSelectPrompt_with_token(t *testing.T) { for _, tt := range tests { var mockProviderFlag string + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) clientsMock.Config.Flags.StringVar(&mockProviderFlag, "provider", "", "mock provider flag") @@ -146,7 +147,6 @@ func TestPrompt_ProviderSelectPrompt_with_token(t *testing.T) { Flag: clientsMock.Config.Flags.Lookup("provider"), })).Return(tt.Selection, nil) clientsMock.AddDefaultMocks() - ctx := context.Background() selectedProvider, err := ProviderSelectPrompt(ctx, clients, authorizationInfoLists) require.Equal(t, selectedProvider.ProviderKey, "provider_a") diff --git a/internal/pkg/externalauth/prompt_token_select_test.go b/internal/pkg/externalauth/prompt_token_select_test.go index c1a64704..971f606d 100644 --- a/internal/pkg/externalauth/prompt_token_select_test.go +++ b/internal/pkg/externalauth/prompt_token_select_test.go @@ -15,23 +15,23 @@ package externalauth import ( - "context" "testing" "github.com/slackapi/slack-cli/internal/iostreams" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" ) func TestPrompt_TokenSelectPrompt_empty_list(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) authorizationInfo := types.ExternalAuthorizationInfo{} clientsMock.AddDefaultMocks() - ctx := context.Background() selectedToken, err := TokenSelectPrompt(ctx, clients, authorizationInfo) require.Empty(t, selectedToken) @@ -83,6 +83,7 @@ func TestPrompt_TokenSelectPrompt_with_token(t *testing.T) { var externalAccountFlag string for _, tt := range tests { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) clientsMock.Config.Flags.StringVar(&externalAccountFlag, "external-account", "", "mock external-account flag") @@ -93,7 +94,6 @@ func TestPrompt_TokenSelectPrompt_with_token(t *testing.T) { Flag: clientsMock.Config.Flags.Lookup("external-account"), })).Return(tt.Selection, nil) clientsMock.AddDefaultMocks() - ctx := context.Background() selectedToken, err := TokenSelectPrompt(ctx, clients, authorizationInfo) require.NoError(t, err) diff --git a/internal/pkg/externalauth/prompt_workflow_select_test.go b/internal/pkg/externalauth/prompt_workflow_select_test.go index e683590c..ae1d4fc6 100644 --- a/internal/pkg/externalauth/prompt_workflow_select_test.go +++ b/internal/pkg/externalauth/prompt_workflow_select_test.go @@ -15,12 +15,12 @@ package externalauth import ( - "context" "testing" "github.com/slackapi/slack-cli/internal/iostreams" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -29,13 +29,13 @@ import ( func TestPrompt_WorkflowSelectPrompt_empty_list(t *testing.T) { authorizationInfoLists := types.ExternalAuthorizationInfoLists{} + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) clientsMock.IO.On("SelectPrompt", mock.Anything, "Select a workflow", mock.Anything, iostreams.MatchPromptConfig(iostreams.SelectPromptConfig{ Flag: clientsMock.Config.Flags.Lookup("workflow"), })).Return(iostreams.SelectPromptResponse{}, slackerror.New(slackerror.ErrMissingOptions)) clientsMock.AddDefaultMocks() - ctx := context.Background() selectedWorkflow, err := WorkflowSelectPrompt(ctx, clients, authorizationInfoLists) require.Empty(t, selectedWorkflow) @@ -55,13 +55,13 @@ func TestPrompt_WorkflowSelectPrompt_with_no_workflows(t *testing.T) { }, }} + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) clientsMock.IO.On("SelectPrompt", mock.Anything, "Select a workflow", mock.Anything, iostreams.MatchPromptConfig(iostreams.SelectPromptConfig{ Flag: clients.Config.Flags.Lookup("workflow"), })).Return(iostreams.SelectPromptResponse{}, slackerror.New(slackerror.ErrMissingOptions)) clientsMock.AddDefaultMocks() - ctx := context.Background() selectedWorkflow, err := WorkflowSelectPrompt(ctx, clients, authorizationInfoLists) require.Empty(t, selectedWorkflow) @@ -144,6 +144,7 @@ func TestPrompt_WorkflowSelectPrompt_with_workflows(t *testing.T) { for _, tt := range tests { var mockWorkflowFlag string + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) clientsMock.Config.Flags.StringVar(&mockWorkflowFlag, "workflow", "", "mock workflow flag") @@ -154,7 +155,6 @@ func TestPrompt_WorkflowSelectPrompt_with_workflows(t *testing.T) { Flag: clientsMock.Config.Flags.Lookup("workflow"), })).Return(tt.Selection, nil) clientsMock.AddDefaultMocks() - ctx := context.Background() selectedWorkflow, err := WorkflowSelectPrompt(ctx, clients, authorizationInfoLists) require.NoError(t, err) diff --git a/internal/pkg/manifest/validate_test.go b/internal/pkg/manifest/validate_test.go index c3f46d2f..2e32c249 100644 --- a/internal/pkg/manifest/validate_test.go +++ b/internal/pkg/manifest/validate_test.go @@ -24,13 +24,14 @@ import ( "github.com/slackapi/slack-cli/internal/logger" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" ) func Test_ManifestValidate_GetManifestLocal_Error(t *testing.T) { - ctx, clients, _, log, appMock, authMock := setupCommonMocks() + ctx, clients, _, log, appMock, authMock := setupCommonMocks(t) // Mock the manifest to return error on get manifestMock := &app.ManifestMockObject{} @@ -47,7 +48,7 @@ func Test_ManifestValidate_GetManifestLocal_Error(t *testing.T) { func Test_ManifestValidate_Success(t *testing.T) { t.Run("should return success when no errors or warnings", func(t *testing.T) { - ctx, clients, clientsMock, log, appMock, authMock := setupCommonMocks() + ctx, clients, clientsMock, log, appMock, authMock := setupCommonMocks(t) // Mock manifest validation api result with no error clientsMock.ApiInterface.On("ValidateAppManifest", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(api.ValidateAppManifestResult{}, nil) @@ -63,7 +64,7 @@ func Test_ManifestValidate_Success(t *testing.T) { func Test_ManifestValidate_Warnings(t *testing.T) { t.Run("should return warnings", func(t *testing.T) { - ctx, clients, clientsMock, log, appMock, authMock := setupCommonMocks() + ctx, clients, clientsMock, log, appMock, authMock := setupCommonMocks(t) // Mock manifest validation api result with no error clientsMock.ApiInterface.On("ValidateAppManifest", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(api.ValidateAppManifestResult{ @@ -87,7 +88,7 @@ func Test_ManifestValidate_Warnings(t *testing.T) { func Test_ManifestValidate_Error(t *testing.T) { t.Run("should return error when there are errors", func(t *testing.T) { - ctx, clients, clientsMock, log, appMock, authMock := setupCommonMocks() + ctx, clients, clientsMock, log, appMock, authMock := setupCommonMocks(t) // Mock manifest validation api result with an error clientsMock.ApiInterface.On("ValidateAppManifest", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return( @@ -108,7 +109,7 @@ func Test_ManifestValidate_Error(t *testing.T) { func Test_ManifestValidate_Error_ErrConnectorNotInstalled(t *testing.T) { t.Run("should try to install connector apps when there are related errors", func(t *testing.T) { - ctx, clients, clientsMock, log, appMock, authMock := setupCommonMocks() + ctx, clients, clientsMock, log, appMock, authMock := setupCommonMocks(t) // Mock manifest validation api result with an error and error details clientsMock.ApiInterface.On("ValidateAppManifest", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(api.ValidateAppManifestResult{ @@ -150,7 +151,7 @@ func Test_HandleConnectorApprovalRequired(t *testing.T) { test_reason := "GIVE IT TO ME!" t.Run("should send request to approve connector", func(t *testing.T) { - ctx, clients, clientsMock, _, _, authMock := setupCommonMocks() + ctx, clients, clientsMock, _, _, authMock := setupCommonMocks(t) testErr := slackerror.New("a dummy error").WithDetails(slackerror.ErrorDetails{ slackerror.ErrorDetail{ Code: slackerror.ErrConnectorApprovalRequired, @@ -187,7 +188,7 @@ func Test_HandleConnectorApprovalRequired(t *testing.T) { }) t.Run("should not send request to approve connector if user refuses", func(t *testing.T) { - ctx, clients, clientsMock, _, _, authMock := setupCommonMocks() + ctx, clients, clientsMock, _, _, authMock := setupCommonMocks(t) testErr := slackerror.New("a dummy error").WithDetails(slackerror.ErrorDetails{ slackerror.ErrorDetail{ Code: slackerror.ErrConnectorApprovalRequired, @@ -208,7 +209,7 @@ func Test_HandleConnectorApprovalRequired(t *testing.T) { }) t.Run("should return error if request RequestAppApproval fails", func(t *testing.T) { - ctx, clients, clientsMock, _, _, authMock := setupCommonMocks() + ctx, clients, clientsMock, _, _, authMock := setupCommonMocks(t) testErr := slackerror.New("a dummy error").WithDetails(slackerror.ErrorDetails{ slackerror.ErrorDetail{ Code: slackerror.ErrConnectorApprovalRequired, @@ -231,8 +232,9 @@ func Test_HandleConnectorApprovalRequired(t *testing.T) { } // Setup -func setupCommonMocks() (ctx context.Context, clients *shared.ClientFactory, clientsMock *shared.ClientsMock, log *logger.Logger, mockApp types.App, mockAuth types.SlackAuth) { +func setupCommonMocks(t *testing.T) (ctx context.Context, clients *shared.ClientFactory, clientsMock *shared.ClientsMock, log *logger.Logger, mockApp types.App, mockAuth types.SlackAuth) { // Create mocks + ctx = slackcontext.MockContext(t.Context()) clientsMock = shared.NewClientsMock() clientsMock.AddDefaultMocks() @@ -241,8 +243,6 @@ func setupCommonMocks() (ctx context.Context, clients *shared.ClientFactory, cli clients.SDKConfig = hooks.NewSDKConfigMock() }) - ctx = context.Background() - // Mock valid auth session clientsMock.ApiInterface.On("ValidateSession", mock.Anything, mock.Anything).Return(api.AuthSession{}, nil) diff --git a/internal/pkg/platform/activity_test.go b/internal/pkg/platform/activity_test.go index 1a721e47..ee15e6ad 100644 --- a/internal/pkg/platform/activity_test.go +++ b/internal/pkg/platform/activity_test.go @@ -156,7 +156,7 @@ func TestPlatformActivity_StreamingLogs(t *testing.T) { } { t.Run(name, func(t *testing.T) { // Create mocks - ctxMock := slackcontext.MockContext(context.Background()) + ctxMock := slackcontext.MockContext(t.Context()) ctxMock = context.WithValue(ctxMock, config.CONTEXT_TOKEN, "sometoken") clientsMock := shared.NewClientsMock() // Create clients that is mocked for testing diff --git a/internal/pkg/platform/localserver_test.go b/internal/pkg/platform/localserver_test.go index ac40e895..bb0c1244 100644 --- a/internal/pkg/platform/localserver_test.go +++ b/internal/pkg/platform/localserver_test.go @@ -28,6 +28,7 @@ import ( "github.com/slackapi/slack-cli/internal/hooks" "github.com/slackapi/slack-cli/internal/logger" "github.com/slackapi/slack-cli/internal/shared" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" @@ -118,8 +119,8 @@ func Test_LocalServer_Start(t *testing.T) { defer ts.Close() wsFakeURL = "ws" + strings.TrimPrefix(ts.URL, "http") } - ctx := context.Background() // Create mocks + ctx := slackcontext.MockContext(t.Context()) conn := NewWebSocketConnMock() clientsMock := shared.NewClientsMock() // Create clients that is mocked for testing @@ -330,8 +331,8 @@ func Test_LocalServer_Listen(t *testing.T) { }, } { t.Run(name, func(t *testing.T) { - ctx := context.Background() // Create mocks + ctx := slackcontext.MockContext(t.Context()) conn := NewWebSocketConnMock() clientsMock := shared.NewClientsMock() // Create clients that is mocked for testing diff --git a/internal/prompts/app_select_test.go b/internal/prompts/app_select_test.go index 54e15337..b33084c4 100644 --- a/internal/prompts/app_select_test.go +++ b/internal/prompts/app_select_test.go @@ -27,6 +27,7 @@ import ( "github.com/slackapi/slack-cli/internal/iostreams" "github.com/slackapi/slack-cli/internal/shared" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/slackapi/slack-cli/internal/style" "github.com/stretchr/testify/assert" @@ -220,6 +221,7 @@ func TestGetTeamApps(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AuthInterface.On( AuthWithToken, @@ -257,7 +259,6 @@ func TestGetTeamApps(t *testing.T) { ) clientsMock.AddDefaultMocks() - ctx := context.Background() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) for _, app := range tt.deployedApps { err := clients.AppClient().SaveDeployed(ctx, app) @@ -369,6 +370,7 @@ func TestGetTokenApp(t *testing.T) { for name, test := range tests { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AuthInterface.On(AuthWithToken, mock.Anything, test.tokenFlag). Return(test.tokenAuth, test.tokenErr) @@ -376,7 +378,6 @@ func TestGetTokenApp(t *testing.T) { Return(test.appStatus, test.statusErr) clientsMock.AddDefaultMocks() - ctx := context.Background() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) for _, app := range test.saveLocal { err := clients.AppClient().SaveLocal(ctx, app) @@ -415,6 +416,7 @@ func TestFilterAuthsByToken_NoLogin(t *testing.T) { } test.expectedAuth.Token = test.TokenFlag // expect the same token + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AuthInterface.On(AuthWithToken, mock.Anything, test.TokenFlag). Return(test.expectedAuth, nil) @@ -423,7 +425,6 @@ func TestFilterAuthsByToken_NoLogin(t *testing.T) { clientsMock.AuthInterface.On(SetAuth, mock.Anything).Return(types.SlackAuth{}, nil) clientsMock.AddDefaultMocks() - ctx := context.Background() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) clients.Config.TokenFlag = test.TokenFlag @@ -438,6 +439,8 @@ func TestFilterAuthsByToken_NoLogin(t *testing.T) { } func Test_FilterAuthsByToken_Flags(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) + mockAuthTeam1 := fakeAuthsByTeamDomain[team1TeamDomain] mockAuthTeam1.Token = team1Token mockAuthTeam2 := fakeAuthsByTeamDomain[team2TeamDomain] @@ -457,7 +460,6 @@ func Test_FilterAuthsByToken_Flags(t *testing.T) { clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() err := clients.AppClient().SaveDeployed(ctx, types.App{ TeamID: team2TeamID, @@ -573,9 +575,8 @@ func Test_FilterAuthsByToken_Flags(t *testing.T) { // func TestPrompt_AppSelectPrompt_SelectedAuthExpired_UserReAuthenticates(t *testing.T) { - // Setup - + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() // Auth is present but invalid clientsMock.AuthInterface.On(Auths, mock.Anything).Return(fakeAuthsByTeamDomainSlice, nil) @@ -601,7 +602,6 @@ func TestPrompt_AppSelectPrompt_SelectedAuthExpired_UserReAuthenticates(t *testi }, nil) clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() err := clients.AppClient().SaveDeployed(ctx, deployedTeam1InstalledApp) require.NoError(t, err) @@ -618,12 +618,12 @@ func TestPrompt_AppSelectPrompt_SelectedAuthExpired_UserReAuthenticates(t *testi func TestPrompt_AppSelectPrompt_AuthsNoApps(t *testing.T) { // Set up mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.ApiInterface.On("ValidateSession", mock.Anything, mock.Anything).Return(api.AuthSession{}, nil) clients := shared.NewClientFactory(clientsMock.MockClientFactory()) clientsMock.AddDefaultMocks() - ctx := context.Background() // Execute test selectedApp, err := AppSelectPrompt(ctx, clients, AppInstallStatus(ShowInstalledAppsOnly)) @@ -691,6 +691,7 @@ func TestPrompt_AppSelectPrompt_TokenAppFlag(t *testing.T) { for name, test := range tests { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AuthInterface.On(AuthWithToken, mock.Anything, test.tokenFlag). Return(test.tokenAuth, nil) @@ -698,7 +699,6 @@ func TestPrompt_AppSelectPrompt_TokenAppFlag(t *testing.T) { Return(test.appStatus, test.statusErr) clientsMock.AddDefaultMocks() - ctx := context.Background() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) clients.Config.TokenFlag = test.tokenFlag clients.Config.AppFlag = test.appFlag @@ -723,6 +723,7 @@ func TestPrompt_AppSelectPrompt_TokenAppFlag(t *testing.T) { func TestPrompt_AppSelectPrompt_AuthsWithDeployedAppInstalled_ShowAllApps(t *testing.T) { // Set up mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.ApiInterface.On(GetAppStatus, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return( api.GetAppStatusResult{ @@ -734,7 +735,6 @@ func TestPrompt_AppSelectPrompt_AuthsWithDeployedAppInstalled_ShowAllApps(t *tes clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() err := clients.AppClient().SaveDeployed(ctx, types.App{ TeamDomain: team1TeamDomain, TeamID: team1TeamID, @@ -770,6 +770,7 @@ func TestPrompt_AppSelectPrompt_AuthsWithDeployedAppInstalled_ShowAllApps(t *tes func TestPrompt_AppSelectPrompt_AuthsWithDeployedAppInstalled_ShowInstalledAppsOnly(t *testing.T) { // Set up mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.ApiInterface.On(GetAppStatus, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return( api.GetAppStatusResult{ @@ -781,7 +782,6 @@ func TestPrompt_AppSelectPrompt_AuthsWithDeployedAppInstalled_ShowInstalledAppsO clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() // Installed app err := clients.AppClient().SaveDeployed(ctx, types.App{ TeamID: team1TeamID, @@ -818,6 +818,7 @@ func TestPrompt_AppSelectPrompt_AuthsWithDeployedAppInstalled_ShowInstalledAppsO func TestPrompt_AppSelectPrompt_AuthsWithDeployedAppInstalled_InstalledAppOnly_Flags(t *testing.T) { // Set up mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.ApiInterface.On(GetAppStatus, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return( api.GetAppStatusResult{ @@ -829,7 +830,6 @@ func TestPrompt_AppSelectPrompt_AuthsWithDeployedAppInstalled_InstalledAppOnly_F clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() // Installed app deployedApp := types.App{ @@ -938,6 +938,8 @@ func TestPrompt_AppSelectPrompt_AuthsWithDeployedAppInstalled_InstalledAppOnly_F } func TestPrompt_AppSelectPrompt_AuthsWithBothEnvsInstalled_InstalledAppOnly_Flags(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) + mockAuthTeam1 := fakeAuthsByTeamDomain[team1TeamDomain] mockAuthTeam1.Token = team1Token mockAuthTeam2 := fakeAuthsByTeamDomain[team2TeamDomain] @@ -970,7 +972,6 @@ func TestPrompt_AppSelectPrompt_AuthsWithBothEnvsInstalled_InstalledAppOnly_Flag }, nil) clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() // Installed app team 1 deployed deployedApp := types.App{ @@ -1095,6 +1096,7 @@ func TestPrompt_AppSelectPrompt_AuthsWithBothEnvsInstalled_InstalledAppOnly_Flag func TestPrompt_AppSelectPrompt_AuthsWithBothEnvsInstalled_MultiWorkspaceAllApps_Flags(t *testing.T) { // Set up mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.ApiInterface.On(GetAppStatus, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return( api.GetAppStatusResult{ @@ -1109,7 +1111,6 @@ func TestPrompt_AppSelectPrompt_AuthsWithBothEnvsInstalled_MultiWorkspaceAllApps clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() // Installed app @@ -1221,6 +1222,7 @@ func TestPrompt_AppSelectPrompt_AuthsWithBothEnvsInstalled_MultiWorkspaceAllApps func TestPrompt_AppSelectPrompt_AuthsWithHostedInstalled_AllApps_CreateNew(t *testing.T) { // Set up mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.ApiInterface.On(GetAppStatus, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return( api.GetAppStatusResult{ @@ -1234,7 +1236,6 @@ func TestPrompt_AppSelectPrompt_AuthsWithHostedInstalled_AllApps_CreateNew(t *te clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() // Installed apps err := clients.AppClient().SaveDeployed(ctx, types.App{ @@ -1477,7 +1478,7 @@ func TestPrompt_AppSelectPrompt_ShowExpectedLabels(t *testing.T) { } for _, test := range tests { - + ctx := slackcontext.MockContext(t.Context()) clientsMock := setupClientsMock() // On select a team, choose @@ -1499,7 +1500,6 @@ func TestPrompt_AppSelectPrompt_ShowExpectedLabels(t *testing.T) { }, nil) clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() saveApps(ctx, clients) selectedApp, err := AppSelectPrompt(ctx, clients, test.status) @@ -1683,6 +1683,7 @@ func TestPrompt_AppSelectPrompt_GetApps(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.ApiInterface.On( GetAppStatus, @@ -1745,7 +1746,6 @@ func TestPrompt_AppSelectPrompt_GetApps(t *testing.T) { ) clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() for _, app := range tt.mockAppsSavedDeployed { err := clients.AppClient().SaveDeployed(ctx, app) require.NoError(t, err) @@ -2277,6 +2277,7 @@ func TestPrompt_AppSelectPrompt_FlatAppSelectPrompt(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AuthInterface.On( Auths, @@ -2486,7 +2487,6 @@ func TestPrompt_AppSelectPrompt_FlatAppSelectPrompt(t *testing.T) { clientsMock.Config.TeamFlag = tt.mockFlagTeam clientsMock.Config.TokenFlag = tt.mockFlagToken clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() for _, app := range tt.mockAppsDeployed { err := clients.AppClient().SaveDeployed(ctx, app) require.NoError(t, err) @@ -2509,9 +2509,8 @@ func TestPrompt_AppSelectPrompt_FlatAppSelectPrompt(t *testing.T) { // func TestPrompt_TeamAppSelectPrompt_SelectedAuthExpired_UserReAuthenticates(t *testing.T) { - // Setup - + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() // Auth is present but invalid clientsMock.AuthInterface.On(Auths, mock.Anything).Return(fakeAuthsByTeamDomainSlice, nil) @@ -2529,7 +2528,6 @@ func TestPrompt_TeamAppSelectPrompt_SelectedAuthExpired_UserReAuthenticates(t *t }, nil) clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() err := clients.AppClient().SaveDeployed(ctx, deployedTeam1InstalledApp) require.NoError(t, err) @@ -2544,9 +2542,8 @@ func TestPrompt_TeamAppSelectPrompt_SelectedAuthExpired_UserReAuthenticates(t *t } func TestPrompt_TeamAppSelectPrompt_NoAuths_UserReAuthenticates(t *testing.T) { - // Setup - + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() // No auths present clientsMock.AuthInterface.On(Auths, mock.Anything).Return([]types.SlackAuth{}, nil) @@ -2564,7 +2561,6 @@ func TestPrompt_TeamAppSelectPrompt_NoAuths_UserReAuthenticates(t *testing.T) { }, nil) clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() err := clients.AppClient().SaveDeployed(ctx, deployedTeam1InstalledApp) require.NoError(t, err) @@ -2680,6 +2676,7 @@ func TestPrompt_TeamAppSelectPrompt_TokenAppFlag(t *testing.T) { for name, test := range tests { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AuthInterface.On(AuthWithToken, mock.Anything, test.tokenFlag). Return(test.tokenAuth, nil) @@ -2687,7 +2684,6 @@ func TestPrompt_TeamAppSelectPrompt_TokenAppFlag(t *testing.T) { Return(test.appStatus, test.statusErr) clientsMock.AddDefaultMocks() - ctx := context.Background() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) for _, app := range test.saveLocal { err := clients.AppClient().SaveLocal(ctx, app) @@ -2715,12 +2711,12 @@ func TestPrompt_TeamAppSelectPrompt_TokenAppFlag(t *testing.T) { func TestPrompt_TeamAppSelectPrompt_TeamNotFoundFor_TeamFlag(t *testing.T) { // Set up mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AuthInterface.On(Auths, mock.Anything).Return(fakeAuthsByTeamDomainSlice, nil) clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() // Perform tests var tests = []struct { @@ -2745,6 +2741,7 @@ func TestPrompt_TeamAppSelectPrompt_TeamNotFoundFor_TeamFlag(t *testing.T) { func TestPrompt_TeamAppSelectPrompt_NoApps(t *testing.T) { // Set up mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AuthInterface.On(Auths, mock.Anything).Return(fakeAuthsByTeamDomainSlice, nil) clientsMock.AuthInterface.On(AuthWithTeamID, mock.Anything, team1TeamID).Return(fakeAuthsByTeamDomain[team1TeamDomain], nil) @@ -2753,7 +2750,6 @@ func TestPrompt_TeamAppSelectPrompt_NoApps(t *testing.T) { clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() // Install the app to team1 clientsMock.IO.On(SelectPrompt, mock.Anything, "Choose a deployed environment", mock.Anything, iostreams.MatchPromptConfig(iostreams.SelectPromptConfig{ @@ -2804,12 +2800,12 @@ func TestPrompt_TeamAppSelectPrompt_NoApps(t *testing.T) { func TestPrompt_TeamAppSelectPrompt_NoInstalls_TeamFlagDomain(t *testing.T) { // Set up mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AuthInterface.On(Auths, mock.Anything).Return(fakeAuthsByTeamDomainSlice, nil) clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() // Perform tests var tests = []struct { @@ -2838,13 +2834,13 @@ func TestPrompt_TeamAppSelectPrompt_NoInstalls_TeamFlagDomain(t *testing.T) { func TestPrompt_TeamAppSelectPrompt_NoInstalls_TeamFlagID(t *testing.T) { // Set up mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AuthInterface.On(Auths, mock.Anything).Return(fakeAuthsByTeamDomainSlice, nil) clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() // Perform tests var tests = []struct { @@ -2872,14 +2868,13 @@ func TestPrompt_TeamAppSelectPrompt_NoInstalls_TeamFlagID(t *testing.T) { } func TestPrompt_TeamAppSelectPrompt_NoInstalls_Flags(t *testing.T) { - // Set up mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AuthInterface.On(Auths, mock.Anything).Return(fakeAuthsByTeamDomainSlice, nil) clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() // Execute tests tests := []struct { @@ -3060,6 +3055,8 @@ func TestPrompt_TeamAppSelectPrompt_TokenFlag(t *testing.T) { } for name, test := range tests { + ctx := slackcontext.MockContext(t.Context()) + mockAuth := fakeAuthsByTeamDomain[test.teamDomain] mockAuth.Token = test.token @@ -3075,7 +3072,6 @@ func TestPrompt_TeamAppSelectPrompt_TokenFlag(t *testing.T) { clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() var err error err = clients.AppClient().SaveDeployed(ctx, installedHostedApp) @@ -3100,6 +3096,7 @@ func TestPrompt_TeamAppSelectPrompt_TokenFlag(t *testing.T) { func TestPrompt_TeamAppSelectPrompt_HostedAppsOnly(t *testing.T) { // Set up mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.ApiInterface.On(GetAppStatus, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return( api.GetAppStatusResult{ @@ -3111,7 +3108,6 @@ func TestPrompt_TeamAppSelectPrompt_HostedAppsOnly(t *testing.T) { clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() // Select team2 clientsMock.IO.On(SelectPrompt, mock.Anything, "Choose a deployed environment", mock.Anything, iostreams.MatchPromptConfig(iostreams.SelectPromptConfig{ @@ -3181,6 +3177,7 @@ func TestPrompt_TeamAppSelectPrompt_HostedAppsOnly(t *testing.T) { func TestPrompt_TeamAppSelectPrompt_HostedAppsOnly_TeamFlagDomain(t *testing.T) { // Set up mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.ApiInterface.On(GetAppStatus, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return( api.GetAppStatusResult{ @@ -3191,7 +3188,6 @@ func TestPrompt_TeamAppSelectPrompt_HostedAppsOnly_TeamFlagDomain(t *testing.T) clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() // Install apps err := clients.AppClient().SaveDeployed(ctx, types.App{ @@ -3229,6 +3225,7 @@ func TestPrompt_TeamAppSelectPrompt_HostedAppsOnly_TeamFlagDomain(t *testing.T) func TestPrompt_TeamAppSelectPrompt_HostedAppsOnly_TeamFlagID(t *testing.T) { // Set up mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.ApiInterface.On(GetAppStatus, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return( api.GetAppStatusResult{ @@ -3239,7 +3236,6 @@ func TestPrompt_TeamAppSelectPrompt_HostedAppsOnly_TeamFlagID(t *testing.T) { clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() // Install apps err := clients.AppClient().SaveDeployed(ctx, types.App{ @@ -3277,6 +3273,7 @@ func TestPrompt_TeamAppSelectPrompt_HostedAppsOnly_TeamFlagID(t *testing.T) { func TestPrompt_TeamAppSelectPrompt_LocalAppsOnly(t *testing.T) { // Set up mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.ApiInterface.On(GetAppStatus, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return( api.GetAppStatusResult{ @@ -3289,7 +3286,6 @@ func TestPrompt_TeamAppSelectPrompt_LocalAppsOnly(t *testing.T) { clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() // Install the app to team1 clientsMock.IO.On(SelectPrompt, mock.Anything, appInstallPromptNew, mock.Anything, iostreams.MatchPromptConfig(iostreams.SelectPromptConfig{ @@ -3361,6 +3357,7 @@ func TestPrompt_TeamAppSelectPrompt_LocalAppsOnly(t *testing.T) { func TestPrompt_TeamAppSelectPrompt_LocalAppsOnly_TeamFlagDomain(t *testing.T) { // Set up mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.ApiInterface.On(GetAppStatus, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return( api.GetAppStatusResult{ @@ -3372,7 +3369,6 @@ func TestPrompt_TeamAppSelectPrompt_LocalAppsOnly_TeamFlagDomain(t *testing.T) { clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() // Install apps err := clients.AppClient().SaveLocal(ctx, types.App{ @@ -3412,6 +3408,7 @@ func TestPrompt_TeamAppSelectPrompt_LocalAppsOnly_TeamFlagDomain(t *testing.T) { func TestPrompt_TeamAppSelectPrompt_LocalAppsOnly_TeamFlagID(t *testing.T) { // Set up mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.ApiInterface.On(GetAppStatus, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return( api.GetAppStatusResult{ @@ -3423,7 +3420,6 @@ func TestPrompt_TeamAppSelectPrompt_LocalAppsOnly_TeamFlagID(t *testing.T) { clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() // Install apps err := clients.AppClient().SaveLocal(ctx, types.App{ @@ -3463,6 +3459,7 @@ func TestPrompt_TeamAppSelectPrompt_LocalAppsOnly_TeamFlagID(t *testing.T) { func TestPrompt_TeamAppSelectPrompt_AllApps(t *testing.T) { // Set up mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.ApiInterface.On(GetAppStatus, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return( api.GetAppStatusResult{ @@ -3479,7 +3476,6 @@ func TestPrompt_TeamAppSelectPrompt_AllApps(t *testing.T) { clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() // Select team2 clientsMock.IO.On(SelectPrompt, mock.Anything, "Choose a deployed environment", mock.Anything, iostreams.MatchPromptConfig(iostreams.SelectPromptConfig{ @@ -3555,6 +3551,7 @@ func TestPrompt_TeamAppSelectPrompt_LegacyDevApps(t *testing.T) { // context is known // Set up mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.ApiInterface.On(GetAppStatus, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return( api.GetAppStatusResult{ @@ -3569,7 +3566,6 @@ func TestPrompt_TeamAppSelectPrompt_LegacyDevApps(t *testing.T) { clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() // Select team2 clientsMock.IO.On(SelectPrompt, mock.Anything, "Choose a deployed environment", mock.Anything, iostreams.MatchPromptConfig(iostreams.SelectPromptConfig{ @@ -3799,7 +3795,7 @@ func TestPrompt_TeamAppSelectPrompt_ShowExpectedLabels(t *testing.T) { } for _, test := range tests { - + ctx := slackcontext.MockContext(t.Context()) clientsMock := setupClientsMock() clientsMock.IO.On(SelectPrompt, mock.Anything, test.promptText, test.expectedTeamLabels, iostreams.MatchPromptConfig(iostreams.SelectPromptConfig{ Flag: clientsMock.Config.Flags.Lookup("team"), @@ -3809,7 +3805,6 @@ func TestPrompt_TeamAppSelectPrompt_ShowExpectedLabels(t *testing.T) { Index: test.selectedTeamIndex, }, nil) clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() saveApps(ctx, clients) selection, err := TeamAppSelectPrompt(ctx, clients, test.env, test.status) @@ -3821,6 +3816,7 @@ func TestPrompt_TeamAppSelectPrompt_ShowExpectedLabels(t *testing.T) { func TestPrompt_TeamAppSelectPrompt_AllApps_TeamFlagID(t *testing.T) { // Set up mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.ApiInterface.On(GetAppStatus, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(api.GetAppStatusResult{}, nil) clientsMock.AuthInterface.On(Auths, mock.Anything).Return(fakeAuthsByTeamDomainSlice, nil) @@ -3828,7 +3824,6 @@ func TestPrompt_TeamAppSelectPrompt_AllApps_TeamFlagID(t *testing.T) { clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() // Install apps err := clients.AppClient().SaveDeployed(ctx, types.App{ @@ -3868,8 +3863,8 @@ func TestPrompt_TeamAppSelectPrompt_AllApps_TeamFlagID(t *testing.T) { } func TestPrompt_TeamAppSelectPrompt_AllApps_Flags(t *testing.T) { - // Set up mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.ApiInterface.On(GetAppStatus, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(api.GetAppStatusResult{}, nil) clientsMock.AuthInterface.On(Auths, mock.Anything).Return(fakeAuthsByTeamDomainSlice, nil) @@ -3877,7 +3872,6 @@ func TestPrompt_TeamAppSelectPrompt_AllApps_Flags(t *testing.T) { clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() // Install apps appTeam1Hosted := types.App{ @@ -4036,6 +4030,7 @@ func TestPrompt_TeamAppSelectPrompt_AllApps_Flags(t *testing.T) { func TestPrompt_TeamAppSelectPrompt_AppSelectPrompt_EnterpriseWorkspaceApps_HasWorkspaceAuth(t *testing.T) { // Set up mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.ApiInterface.On(GetAppStatus, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(api.GetAppStatusResult{}, nil) @@ -4075,7 +4070,6 @@ func TestPrompt_TeamAppSelectPrompt_AppSelectPrompt_EnterpriseWorkspaceApps_HasW clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() // Save apps // Save a hosted and local enterprise workspace-level app @@ -4243,6 +4237,7 @@ func TestPrompt_TeamAppSelectPrompt_AppSelectPrompt_EnterpriseWorkspaceApps_HasW func TestPrompt_TeamAppSelectPrompt_AppSelectPrompt_EnterpriseWorkspaceApps_MissingWorkspaceAuth_MissingOrgAuth_UserReAuthenticates(t *testing.T) { // Set up mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.ApiInterface.On(GetAppStatus, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(api.GetAppStatusResult{}, nil) @@ -4279,7 +4274,6 @@ func TestPrompt_TeamAppSelectPrompt_AppSelectPrompt_EnterpriseWorkspaceApps_Miss clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() // Save apps // Save a hosted and local enterprise workspace-level app @@ -4432,6 +4426,7 @@ func TestPrompt_TeamAppSelectPrompt_AppSelectPrompt_EnterpriseWorkspaceApps_Miss func TestPrompt_TeamAppSelectPrompt_EnterpriseWorkspaceApps_MissingWorkspaceAuth_HasOrgAuth(t *testing.T) { // Set up mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.ApiInterface.On(GetAppStatus, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(api.GetAppStatusResult{}, nil) @@ -4469,7 +4464,6 @@ func TestPrompt_TeamAppSelectPrompt_EnterpriseWorkspaceApps_MissingWorkspaceAuth clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() // Save apps // Save a hosted and local enterprise workspace-level app @@ -4610,6 +4604,7 @@ func TestPrompt_TeamAppSelectPrompt_EnterpriseWorkspaceApps_MissingWorkspaceAuth func TestPrompt_AppSelectPrompt_EnterpriseWorkspaceApps_MissingWorkspaceAuth_HasOrgAuth(t *testing.T) { // Set up mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.ApiInterface.On(GetAppStatus, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(api.GetAppStatusResult{}, nil) @@ -4647,7 +4642,6 @@ func TestPrompt_AppSelectPrompt_EnterpriseWorkspaceApps_MissingWorkspaceAuth_Has clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory()) - ctx := context.Background() // Save apps // Save a hosted and local enterprise workspace-level app @@ -4976,7 +4970,7 @@ func Test_ValidateGetOrgWorkspaceGrant(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AddDefaultMocks() clients := shared.NewClientFactory(clientsMock.MockClientFactory(), func(clients *shared.ClientFactory) { @@ -5089,7 +5083,7 @@ func Test_ValidateAuth(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.ApiInterface.On( "ExchangeAuthTicket", diff --git a/internal/runtime/deno/deno_test.go b/internal/runtime/deno/deno_test.go index fd42c1c8..b0c12af4 100644 --- a/internal/runtime/deno/deno_test.go +++ b/internal/runtime/deno/deno_test.go @@ -15,7 +15,6 @@ package deno import ( - "context" "encoding/json" "fmt" "os/exec" @@ -26,6 +25,7 @@ import ( "github.com/slackapi/slack-cli/internal/hooks" "github.com/slackapi/slack-cli/internal/iostreams" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackdeps" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/spf13/afero" @@ -134,7 +134,7 @@ func Test_Deno_InstallProjectDependencies(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Setup - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) projectDirPath := "/path/to/project-name" fs := slackdeps.NewFsMock() @@ -347,7 +347,7 @@ func Test_Deno_IsRuntimeForProject(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Setup - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() projectDirPath := "/path/to/project-name" diff --git a/internal/runtime/node/node_test.go b/internal/runtime/node/node_test.go index 0a159ac6..f0402d8c 100644 --- a/internal/runtime/node/node_test.go +++ b/internal/runtime/node/node_test.go @@ -15,7 +15,6 @@ package node import ( - "context" "encoding/json" "errors" "fmt" @@ -26,6 +25,7 @@ import ( "github.com/slackapi/slack-cli/internal/hooks" "github.com/slackapi/slack-cli/internal/iostreams" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackdeps" "github.com/spf13/afero" "github.com/stretchr/testify/mock" @@ -191,7 +191,7 @@ func Test_Node_InstallProjectDependencies(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Setup - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) projectDirPath := "/path/to/project-name" fs := slackdeps.NewFsMock() @@ -347,7 +347,7 @@ func Test_Node_IsRuntimeForProject(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Setup - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() projectDirPath := "/path/to/project-name" diff --git a/internal/runtime/node/npm_test.go b/internal/runtime/node/npm_test.go index 9e5be7cd..b8da4771 100644 --- a/internal/runtime/node/npm_test.go +++ b/internal/runtime/node/npm_test.go @@ -15,7 +15,6 @@ package node import ( - "context" "errors" "strings" "testing" @@ -23,6 +22,7 @@ import ( "github.com/slackapi/slack-cli/internal/config" "github.com/slackapi/slack-cli/internal/hooks" "github.com/slackapi/slack-cli/internal/iostreams" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackdeps" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -62,7 +62,7 @@ func Test_NPMClient_InstallAllPackages(t *testing.T) { for name, tt := range tests { t.Run(name, func(t *testing.T) { // Setup - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) projectDirPath := "/path/to/project-name" fs := slackdeps.NewFsMock() @@ -129,7 +129,7 @@ func Test_NPMClient_InstallDevPackage(t *testing.T) { for name, tt := range tests { t.Run(name, func(t *testing.T) { // Setup - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) projectDirPath := "/path/to/project-name" fs := slackdeps.NewFsMock() @@ -203,7 +203,7 @@ func Test_NPMClient_ListPackage(t *testing.T) { for name, tt := range tests { t.Run(name, func(t *testing.T) { // Setup - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) projectDirPath := "/path/to/project-name" fs := slackdeps.NewFsMock() diff --git a/internal/runtime/python/python_test.go b/internal/runtime/python/python_test.go index b6d0e563..75d154f6 100644 --- a/internal/runtime/python/python_test.go +++ b/internal/runtime/python/python_test.go @@ -15,7 +15,6 @@ package python import ( - "context" "encoding/json" "fmt" "path/filepath" @@ -25,6 +24,7 @@ import ( "github.com/slackapi/slack-cli/internal/hooks" "github.com/slackapi/slack-cli/internal/iostreams" "github.com/slackapi/slack-cli/internal/shared/types" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackdeps" "github.com/spf13/afero" "github.com/stretchr/testify/mock" @@ -170,8 +170,7 @@ func Test_Python_InstallProjectDependencies(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Setup - ctx := context.Background() - + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() os := slackdeps.NewOsMock() os.AddDefaultMocks() @@ -350,7 +349,7 @@ func Test_Python_IsRuntimeForProject(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Setup - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := slackdeps.NewFsMock() projectDirPath := "/path/to/project-name" diff --git a/internal/runtime/runtime_test.go b/internal/runtime/runtime_test.go index 465a1791..85c3b7ee 100644 --- a/internal/runtime/runtime_test.go +++ b/internal/runtime/runtime_test.go @@ -15,13 +15,13 @@ package runtime import ( - "context" "testing" "github.com/slackapi/slack-cli/internal/hooks" "github.com/slackapi/slack-cli/internal/runtime/deno" "github.com/slackapi/slack-cli/internal/runtime/node" "github.com/slackapi/slack-cli/internal/runtime/python" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/spf13/afero" "github.com/stretchr/testify/require" ) @@ -92,7 +92,7 @@ func Test_Runtime_NewDetectProject(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Setup - ctx := context.Background() + ctx := slackcontext.MockContext(t.Context()) fs := afero.NewMemMapFs() projectDirPath := "/path/to/project-name" diff --git a/internal/shared/clients_test.go b/internal/shared/clients_test.go index 4ea8ce3c..8944a710 100644 --- a/internal/shared/clients_test.go +++ b/internal/shared/clients_test.go @@ -15,12 +15,12 @@ package shared import ( - "context" "fmt" "os" "path/filepath" "testing" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/internal/slackdeps" "github.com/slackapi/slack-cli/internal/slackerror" "github.com/spf13/afero" @@ -113,6 +113,7 @@ func Test_ClientFactory_InitSDKConfig(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := NewClientsMock() clientsMock.AddDefaultMocks() clients := NewClientFactory(clientsMock.MockClientFactory()) @@ -120,7 +121,6 @@ func Test_ClientFactory_InitSDKConfig(t *testing.T) { require.NoError(t, err) err = afero.WriteFile(clients.Fs, tt.mockHooksJSONFilePath, []byte(tt.mockHooksJSONContent), 0o600) require.NoError(t, err) - ctx := context.Background() err = clients.InitSDKConfig(ctx, tt.mockWorkingDirectory) assert.Equal(t, tt.expectedError, err) assert.Equal(t, tt.expectedGetHooksScript, clients.SDKConfig.Hooks.GetHooks.Command) @@ -130,10 +130,11 @@ func Test_ClientFactory_InitSDKConfig(t *testing.T) { } func Test_ClientFactory_InitSDKConfigFromJSON(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) path := setupGetHooksScript(t) clients := NewClientFactory() getHooksJson := fmt.Sprintf(`{"hooks":{"get-hooks": "%s"}}`, path) - if err := clients.InitSDKConfigFromJSON(context.Background(), []byte(getHooksJson)); err != nil { + if err := clients.InitSDKConfigFromJSON(ctx, []byte(getHooksJson)); err != nil { t.Errorf("error init'ing SDK from JSON %s", err) } require.True(t, clients.SDKConfig.Hooks.GetHooks.IsAvailable()) @@ -143,11 +144,12 @@ func Test_ClientFactory_InitSDKConfigFromJSON(t *testing.T) { func Test_ClientFactory_InitSDKConfigFromJSON_reflectionSetsNameProperty(t *testing.T) { // Setup + ctx := slackcontext.MockContext(t.Context()) path := setupGetHooksScript(t) clients := NewClientFactory() getHooksJson := fmt.Sprintf(`{"hooks":{"get-hooks": "%s", "get-trigger": "echo {}", "": "echo {}"}}`, path) // Execute test - if err := clients.InitSDKConfigFromJSON(context.Background(), []byte(getHooksJson)); err != nil { + if err := clients.InitSDKConfigFromJSON(ctx, []byte(getHooksJson)); err != nil { t.Errorf("error init'ing SDK from JSON %s", err) } // Check @@ -157,11 +159,12 @@ func Test_ClientFactory_InitSDKConfigFromJSON_reflectionSetsNameProperty(t *test } func Test_ClientFactory_InitSDKConfigFromJSON_numberedDevInstance(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) path := setupGetHooksScript(t) clients := NewClientFactory() getHooksJson := fmt.Sprintf(`{"hooks":{"get-hooks": "%s"}}`, path) clients.Config.ApiHostResolved = "https://dev1234.slack.com" - if err := clients.InitSDKConfigFromJSON(context.Background(), []byte(getHooksJson)); err != nil { + if err := clients.InitSDKConfigFromJSON(ctx, []byte(getHooksJson)); err != nil { t.Errorf("error init'ing SDK from JSON %s", err) } require.True(t, clients.SDKConfig.Hooks.GetHooks.IsAvailable()) @@ -170,11 +173,12 @@ func Test_ClientFactory_InitSDKConfigFromJSON_numberedDevInstance(t *testing.T) } func Test_ClientFactory_InitSDKConfigFromJSON_dev(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) path := setupGetHooksScript(t) clients := NewClientFactory() getHooksJson := fmt.Sprintf(`{"hooks":{"get-hooks": "%s"}}`, path) clients.Config.ApiHostResolved = "https://dev.slack.com" - if err := clients.InitSDKConfigFromJSON(context.Background(), []byte(getHooksJson)); err != nil { + if err := clients.InitSDKConfigFromJSON(ctx, []byte(getHooksJson)); err != nil { t.Errorf("error init'ing SDK from JSON %s", err) } require.True(t, clients.SDKConfig.Hooks.GetHooks.IsAvailable()) @@ -183,11 +187,12 @@ func Test_ClientFactory_InitSDKConfigFromJSON_dev(t *testing.T) { } func Test_ClientFactory_InitSDKConfigFromJSON_qa(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) path := setupGetHooksScript(t) clients := NewClientFactory() getHooksJson := fmt.Sprintf(`{"hooks":{"get-hooks": "%s"}}`, path) clients.Config.ApiHostResolved = "https://qa.slack.com" - if err := clients.InitSDKConfigFromJSON(context.Background(), []byte(getHooksJson)); err != nil { + if err := clients.InitSDKConfigFromJSON(ctx, []byte(getHooksJson)); err != nil { t.Errorf("error init'ing SDK from JSON %s", err) } require.True(t, clients.SDKConfig.Hooks.GetHooks.IsAvailable()) @@ -196,10 +201,11 @@ func Test_ClientFactory_InitSDKConfigFromJSON_qa(t *testing.T) { } func Test_ClientFactory_InitSDKConfigFromJSON_mergesExistingFile(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) path := setupGetHooksScript(t) clients := NewClientFactory() getHooksJson := fmt.Sprintf(`{"hooks":{"get-hooks": "%s", "start": "foobar"}}`, path) - if err := clients.InitSDKConfigFromJSON(context.Background(), []byte(getHooksJson)); err != nil { + if err := clients.InitSDKConfigFromJSON(ctx, []byte(getHooksJson)); err != nil { t.Errorf("error init'ing SDK from JSON %s", err) } require.True(t, clients.SDKConfig.Hooks.GetHooks.IsAvailable()) @@ -208,11 +214,12 @@ func Test_ClientFactory_InitSDKConfigFromJSON_mergesExistingFile(t *testing.T) { } func Test_ClientFactory_InitSDKConfigFromJSON_noGetHooks(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clients := NewClientFactory() getHooksJson := `{"hooks":{"start": "foobar"}}` clients.Config.ApiHostResolved = "https://dev1234.slack.com" clients.Config.SlackDevFlag = true - if err := clients.InitSDKConfigFromJSON(context.Background(), []byte(getHooksJson)); err != nil { + if err := clients.InitSDKConfigFromJSON(ctx, []byte(getHooksJson)); err != nil { t.Errorf("error init'ing SDK from JSON %s", err) } require.False(t, clients.SDKConfig.Hooks.GetHooks.IsAvailable()) @@ -221,18 +228,20 @@ func Test_ClientFactory_InitSDKConfigFromJSON_noGetHooks(t *testing.T) { } func Test_ClientFactory_InitSDKConfigFromJSON_brokenGetHooks(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clients := NewClientFactory() getHooksJson := `{"hooks":{"get-hooks": "unknown-command"}}` - err := clients.InitSDKConfigFromJSON(context.Background(), []byte(getHooksJson)) + err := clients.InitSDKConfigFromJSON(ctx, []byte(getHooksJson)) require.Error(t, err) assert.Equal(t, slackerror.New(slackerror.ErrSDKHookInvocationFailed).Code, slackerror.ToSlackError(err).Code) assert.Contains(t, slackerror.ToSlackError(err).Message, "Command for 'GetHooks' returned an error") } func Test_ClientFactory_InitSDKConfigFromJSON_brokenJSONFile(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clients := NewClientFactory() getHooksJson := `{"hooks":{"get-hooks":` - err := clients.InitSDKConfigFromJSON(context.Background(), []byte(getHooksJson)) + err := clients.InitSDKConfigFromJSON(ctx, []byte(getHooksJson)) require.Error(t, err) assert.Equal(t, slackerror.New(slackerror.ErrUnableToParseJson).Code, slackerror.ToSlackError(err).Code) } diff --git a/internal/slackcontext/slackcontext_test.go b/internal/slackcontext/slackcontext_test.go index d701d83e..323a2e75 100644 --- a/internal/slackcontext/slackcontext_test.go +++ b/internal/slackcontext/slackcontext_test.go @@ -41,7 +41,7 @@ func Test_SlackContext_OpenTracingSpan(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = opentracing.ContextWithSpan(ctx, tt.expectedSpan) actualSpan, actualError := OpenTracingSpan(ctx) require.Equal(t, tt.expectedSpan, actualSpan) @@ -60,7 +60,7 @@ func Test_SlackContext_SetOpenTracingSpan(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = SetOpenTracingSpan(ctx, tt.expectedSpan) actualSpan := opentracing.SpanFromContext(ctx) require.Equal(t, tt.expectedSpan, actualSpan) @@ -84,7 +84,7 @@ func Test_SlackContext_OpenTracingTraceID(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = context.WithValue(ctx, contextKeyOpenTracingTraceID, tt.expectedTraceID) actualTraceID, actualError := OpenTracingTraceID(ctx) require.Equal(t, tt.expectedTraceID, actualTraceID) @@ -103,7 +103,7 @@ func Test_SlackContext_SetOpenTracingTraceID(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = SetOpenTracingTraceID(ctx, tt.expectedTraceID) actualTraceID := ctx.Value(contextKeyOpenTracingTraceID).(string) require.Equal(t, tt.expectedTraceID, actualTraceID) @@ -129,7 +129,7 @@ func Test_SlackContext_OpenTracingTracer(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = context.WithValue(ctx, contextKeyOpenTracingTracer, tt.expectedTracer) actualTracer, actualError := OpenTracingTracer(ctx) require.Equal(t, tt.expectedTracer, actualTracer) @@ -150,7 +150,7 @@ func Test_SlackContext_SetOpenTracingTracer(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = SetOpenTracingTracer(ctx, tt.expectedTracer) actualTracer := ctx.Value(contextKeyOpenTracingTracer).(opentracing.Tracer) require.Equal(t, tt.expectedTracer, actualTracer) @@ -174,7 +174,7 @@ func Test_SlackContext_ProjectID(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = context.WithValue(ctx, contextKeyProjectID, tt.expectedProjectID) actualProjectID, actualError := ProjectID(ctx) require.Equal(t, tt.expectedProjectID, actualProjectID) @@ -193,7 +193,7 @@ func Test_SlackContext_SetProjectID(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = SetProjectID(ctx, tt.expectedProjectID) actualProjectID := ctx.Value(contextKeyProjectID).(string) require.Equal(t, tt.expectedProjectID, actualProjectID) @@ -217,7 +217,7 @@ func Test_SlackContext_SessionID(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = context.WithValue(ctx, contextKeySessionID, tt.expectedSessionID) actualSessionID, actualError := SessionID(ctx) require.Equal(t, tt.expectedSessionID, actualSessionID) @@ -236,7 +236,7 @@ func Test_SlackContext_SetSessionID(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = SetSessionID(ctx, tt.expectedSessionID) actualSessionID := ctx.Value(contextKeySessionID).(string) require.Equal(t, tt.expectedSessionID, actualSessionID) @@ -260,7 +260,7 @@ func Test_SlackContext_SystemID(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = context.WithValue(ctx, contextKeySystemID, tt.expectedSystemID) actualSystemID, actualError := SystemID(ctx) require.Equal(t, tt.expectedSystemID, actualSystemID) @@ -279,7 +279,7 @@ func Test_SlackContext_SetSystemID(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = SetSystemID(ctx, tt.expectedSystemID) actualSystemID := ctx.Value(contextKeySystemID).(string) require.Equal(t, tt.expectedSystemID, actualSystemID) @@ -303,7 +303,7 @@ func Test_SlackContext_Version(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = context.WithValue(ctx, contextKeyVersion, tt.expectedVersion) actualVersion, actualError := Version(ctx) require.Equal(t, tt.expectedVersion, actualVersion) @@ -322,7 +322,7 @@ func Test_SlackContext_SetVersion(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = SetVersion(ctx, tt.expectedVersion) actualVersion := ctx.Value(contextKeyVersion).(string) require.Equal(t, tt.expectedVersion, actualVersion) diff --git a/internal/update/cli_metadata_test.go b/internal/update/cli_metadata_test.go index 76ce133f..61ed78c6 100644 --- a/internal/update/cli_metadata_test.go +++ b/internal/update/cli_metadata_test.go @@ -15,13 +15,13 @@ package update import ( - "context" "fmt" "io" "net/http" "net/http/httptest" "testing" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" ) @@ -70,6 +70,8 @@ func Test_CLI_Metadata_CheckForUpdate(t *testing.T) { for name, s := range scenarios { t.Run(name, func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) + // Mock an http.Response for the GitHub API w := httptest.NewRecorder() _, _ = io.WriteString(w, fmt.Sprintf( @@ -84,7 +86,7 @@ func Test_CLI_Metadata_CheckForUpdate(t *testing.T) { // Check for an update md := Metadata{httpClient: httpClientMock} - releaseInfo, err := md.CheckForUpdate(context.Background(), metaDataUrl, s.CurrentVersion) + releaseInfo, err := md.CheckForUpdate(ctx, metaDataUrl, s.CurrentVersion) // Assert expected results if s.ExpectsResult { From ad912926b7b94cedc1b94f77929a4b0ae376598e Mon Sep 17 00:00:00 2001 From: Michael Brooks Date: Tue, 8 Apr 2025 11:34:25 -0700 Subject: [PATCH 09/13] test: update context references for .Setup --- cmd/collaborators/add_test.go | 4 ++-- cmd/externalauth/add_secret_test.go | 10 ++++----- cmd/externalauth/add_test.go | 10 ++++----- cmd/externalauth/remove_test.go | 10 ++++----- cmd/function/access_test.go | 10 ++++----- cmd/triggers/access_test.go | 34 ++++++++++++++--------------- cmd/triggers/create_test.go | 28 ++++++++++++------------ cmd/triggers/delete_test.go | 8 +++---- cmd/triggers/info_test.go | 12 +++++----- cmd/triggers/update_test.go | 26 +++++++++++----------- 10 files changed, 76 insertions(+), 76 deletions(-) diff --git a/cmd/collaborators/add_test.go b/cmd/collaborators/add_test.go index 05059f62..b168c7b6 100644 --- a/cmd/collaborators/add_test.go +++ b/cmd/collaborators/add_test.go @@ -39,7 +39,7 @@ func TestAddCommand(t *testing.T) { appSelectMock.On("TeamAppSelectPrompt").Return(prompts.SelectedApp{App: types.App{AppID: "A123"}, Auth: types.SlackAuth{}}, nil) // Set experiment flag cm.Config.ExperimentsFlag = append(cm.Config.ExperimentsFlag, "read-only-collaborators") - cm.Config.LoadExperiments(context.Background(), cm.IO.PrintDebug) + cm.Config.LoadExperiments(ctx, cm.IO.PrintDebug) // Mock API call cm.ApiInterface.On("AddCollaborator", mock.Anything, mock.Anything, "A123", @@ -63,7 +63,7 @@ func TestAddCommand(t *testing.T) { appSelectMock.On("TeamAppSelectPrompt").Return(prompts.SelectedApp{App: types.App{AppID: "A123"}, Auth: types.SlackAuth{}}, nil) // Set experiment flag cm.Config.ExperimentsFlag = append(cm.Config.ExperimentsFlag, "read-only-collaborators") - cm.Config.LoadExperiments(context.Background(), cm.IO.PrintDebug) + cm.Config.LoadExperiments(ctx, cm.IO.PrintDebug) // Mock API call cm.ApiInterface.On("AddCollaborator", mock.Anything, mock.Anything, "A123", diff --git a/cmd/externalauth/add_secret_test.go b/cmd/externalauth/add_secret_test.go index 9b43085c..ca92aac1 100644 --- a/cmd/externalauth/add_secret_test.go +++ b/cmd/externalauth/add_secret_test.go @@ -163,7 +163,7 @@ func TestExternalAuthAddClientSecretCommand(t *testing.T) { clientsMock.AddDefaultMocks() // TODO this can probably be replaced by a helper that sets up an apps.json file in // the right place on the afero memfs instance - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, ExpectedOutputs: []string{}, @@ -198,7 +198,7 @@ func TestExternalAuthAddClientSecretCommand(t *testing.T) { clientsMock.AddDefaultMocks() // TODO this can probably be replaced by a helper that sets up an apps.json file in // the right place on the afero memfs instance - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, ExpectedOutputs: []string{}, @@ -231,7 +231,7 @@ func TestExternalAuthAddClientSecretCommand(t *testing.T) { clientsMock.AddDefaultMocks() // TODO this can probably be replaced by a helper that sets up an apps.json file in // the right place on the afero memfs instance - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, ExpectedOutputs: []string{}, @@ -264,7 +264,7 @@ func TestExternalAuthAddClientSecretCommand(t *testing.T) { clientsMock.AddDefaultMocks() // TODO this can probably be replaced by a helper that sets up an apps.json file in // the right place on the afero memfs instance - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { @@ -289,7 +289,7 @@ func TestExternalAuthAddClientSecretCommand(t *testing.T) { clientsMock.AddDefaultMocks() // TODO this can probably be replaced by a helper that sets up an apps.json file in // the right place on the afero memfs instance - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, ExpectedErrorStrings: []string{"test error"}, diff --git a/cmd/externalauth/add_test.go b/cmd/externalauth/add_test.go index 383c2aa9..682d0d77 100644 --- a/cmd/externalauth/add_test.go +++ b/cmd/externalauth/add_test.go @@ -156,7 +156,7 @@ func TestExternalAuthAddCommand(t *testing.T) { clientsMock.AddDefaultMocks() // TODO this can probably be replaced by a helper that sets up an apps.json file in // the right place on the afero memfs instance - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { @@ -184,7 +184,7 @@ func TestExternalAuthAddCommand(t *testing.T) { clientsMock.AddDefaultMocks() // TODO this can probably be replaced by a helper that sets up an apps.json file in // the right place on the afero memfs instance - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { @@ -212,7 +212,7 @@ func TestExternalAuthAddCommand(t *testing.T) { clientsMock.AddDefaultMocks() // TODO this can probably be replaced by a helper that sets up an apps.json file in // the right place on the afero memfs instance - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { @@ -241,7 +241,7 @@ func TestExternalAuthAddCommand(t *testing.T) { clientsMock.AddDefaultMocks() // TODO this can probably be replaced by a helper that sets up an apps.json file in // the right place on the afero memfs instance - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { @@ -261,7 +261,7 @@ func TestExternalAuthAddCommand(t *testing.T) { clientsMock.AddDefaultMocks() // TODO this can probably be replaced by a helper that sets up an apps.json file in // the right place on the afero memfs instance - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, ExpectedErrorStrings: []string{"test error"}, diff --git a/cmd/externalauth/remove_test.go b/cmd/externalauth/remove_test.go index ec8edae0..6d891aa6 100644 --- a/cmd/externalauth/remove_test.go +++ b/cmd/externalauth/remove_test.go @@ -157,7 +157,7 @@ func TestExternalAuthRemoveCommand(t *testing.T) { clientsMock.AddDefaultMocks() // TODO this can probably be replaced by a helper that sets up an apps.json file in // the right place on the afero memfs instance - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { @@ -182,7 +182,7 @@ func TestExternalAuthRemoveCommand(t *testing.T) { clientsMock.ApiInterface.On("AppsAuthExternalDelete", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil) clientsMock.AddDefaultMocks() clientsMock.IO.On("ConfirmPrompt", mock.Anything, "Are you sure you want to remove all tokens for this app relevant to the specified provider from your current team/org?", mock.Anything).Return(true) - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { @@ -206,7 +206,7 @@ func TestExternalAuthRemoveCommand(t *testing.T) { }}, nil) clientsMock.ApiInterface.On("AppsAuthExternalDelete", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil) clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") clientsMock.IO.On("ConfirmPrompt", mock.Anything, "Are you sure you want to remove all tokens for this app from your current team/org?", mock.Anything).Return(true) }, @@ -231,7 +231,7 @@ func TestExternalAuthRemoveCommand(t *testing.T) { }}, nil) clientsMock.ApiInterface.On("AppsAuthExternalDelete", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil) clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") clientsMock.IO.On("ConfirmPrompt", mock.Anything, "Are you sure you want to remove all tokens for this app relevant to the specified provider from your current team/org?", mock.Anything).Return(true) @@ -249,7 +249,7 @@ func TestExternalAuthRemoveCommand(t *testing.T) { Authorizations: []types.ExternalAuthorizationInfo{}}, errors.New("test error")) clientsMock.ApiInterface.On("AppsAuthExternalDelete", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil) clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") clientsMock.IO.On("ConfirmPrompt", mock.Anything, "Are you sure you want to remove all tokens for this app from your current team/org?", mock.Anything).Return(true) }, diff --git a/cmd/function/access_test.go b/cmd/function/access_test.go index 0df101af..d5021f1b 100644 --- a/cmd/function/access_test.go +++ b/cmd/function/access_test.go @@ -49,7 +49,7 @@ func TestFunctionDistributionCommand(t *testing.T) { clientsMock.AddDefaultMocks() appSelectTeardown = setupMockAppSelection(installedProdApp) - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -81,7 +81,7 @@ func TestFunctionDistributionCommand(t *testing.T) { clientsMock.AddDefaultMocks() appSelectTeardown = setupMockAppSelection(installedProdApp) - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -109,7 +109,7 @@ func TestFunctionDistributionCommand(t *testing.T) { clientsMock.AddDefaultMocks() appSelectTeardown = setupMockAppSelection(installedProdApp) - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -129,7 +129,7 @@ func TestFunctionDistributionCommand(t *testing.T) { clientsMock.AddDefaultMocks() appSelectTeardown = setupMockAppSelection(installedProdApp) - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, ExpectedAsserts: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock) { @@ -146,7 +146,7 @@ func TestFunctionDistributionCommand(t *testing.T) { Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.AddDefaultMocks() appSelectTeardown = setupMockAppSelection(installedProdApp) - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, ExpectedErrorStrings: []string{"file does not exist"}, diff --git a/cmd/triggers/access_test.go b/cmd/triggers/access_test.go index 9f8c6f12..ae1aa9fc 100644 --- a/cmd/triggers/access_test.go +++ b/cmd/triggers/access_test.go @@ -55,7 +55,7 @@ func TestTriggersAccessCommand(t *testing.T) { Return(&types.UserInfo{}, nil).Once() clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -85,7 +85,7 @@ func TestTriggersAccessCommand(t *testing.T) { Return(types.EVERYONE, []string{}, nil).Once() clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -115,7 +115,7 @@ func TestTriggersAccessCommand(t *testing.T) { Return(types.EVERYONE, []string{}, nil).Once() clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -147,7 +147,7 @@ func TestTriggersAccessCommand(t *testing.T) { Return(&types.UserInfo{RealName: "User Two", Name: "USER2", Profile: user2Profile}, nil).Once() clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -179,7 +179,7 @@ func TestTriggersAccessCommand(t *testing.T) { Return(&types.ChannelInfo{ID: "CHANNEL2", Name: "Channel Two"}, nil).Once() clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -216,7 +216,7 @@ func TestTriggersAccessCommand(t *testing.T) { clientsMock.ApiInterface.On("ListCollaborators", mock.Anything, mock.Anything, mock.Anything).Return([]types.SlackUser{}, nil) clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -251,7 +251,7 @@ func TestTriggersAccessCommand(t *testing.T) { clientsMock.ApiInterface.On("ListCollaborators", mock.Anything, mock.Anything, mock.Anything).Return([]types.SlackUser{}, nil) clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -302,7 +302,7 @@ func TestTriggersAccessCommand(t *testing.T) { clientsMock.ApiInterface.On("ListCollaborators", mock.Anything, mock.Anything, mock.Anything).Return([]types.SlackUser{}, nil) clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -333,7 +333,7 @@ func TestTriggersAccessCommand(t *testing.T) { Return(&types.UserInfo{RealName: "User Two", Name: "USER2", Profile: user2Profile}, nil).Once() clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -365,7 +365,7 @@ func TestTriggersAccessCommand(t *testing.T) { Return(&types.ChannelInfo{ID: "CHANNEL2", Name: "Channel Two"}, nil).Once() clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -407,7 +407,7 @@ func TestTriggersAccessCommand(t *testing.T) { Return(&types.TeamInfo{ID: "TEAM1", Name: "Team One"}, nil).Once() clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -437,7 +437,7 @@ func TestTriggersAccessCommand(t *testing.T) { Return(&types.UserInfo{RealName: "User One", Name: "USER1", Profile: user1Profile}, nil).Once() clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -464,7 +464,7 @@ func TestTriggersAccessCommand(t *testing.T) { Return(&types.ChannelInfo{ID: "CHANNEL1", Name: "Channel One"}, nil).Once() clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -492,7 +492,7 @@ func TestTriggersAccessCommand(t *testing.T) { Return(&types.TeamInfo{ID: "TEAM1", Name: "Team One"}, nil).Once() clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -523,7 +523,7 @@ func TestTriggersAccessCommand(t *testing.T) { // display channel info for updated access clientsMock.ApiInterface.On("ChannelsInfo", mock.Anything, mock.Anything, "CHANNEL1"). Return(&types.ChannelInfo{ID: "CHANNEL1", Name: "Channel One"}, nil).Once() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -558,7 +558,7 @@ func TestTriggersAccessCommand(t *testing.T) { }, nil) clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -580,7 +580,7 @@ func TestTriggersAccessCommand_AppSelection(t *testing.T) { ExpectedErrorStrings: []string{cmdutil.DeployedAppNotInstalledMsg}, Setup: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock, clients *shared.ClientFactory) { clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") appSelectTeardown = setupMockAccessAppSelection( prompts.SelectedApp{Auth: types.SlackAuth{}, App: types.App{}}, diff --git a/cmd/triggers/create_test.go b/cmd/triggers/create_test.go index b4b3e70b..23dbc16b 100644 --- a/cmd/triggers/create_test.go +++ b/cmd/triggers/create_test.go @@ -69,7 +69,7 @@ func TestTriggersCreateCommand(t *testing.T) { clientsMock.AddDefaultMocks() // TODO this can probably be replaced by a helper that sets up an apps.json file in // the right place on the afero memfs instance - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -100,7 +100,7 @@ func TestTriggersCreateCommand(t *testing.T) { Return(types.EVERYONE, []string{}, nil).Once() // TODO: testing chicken and egg: we need the default mocks in place before we can use any of the `clients` methods clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -131,7 +131,7 @@ func TestTriggersCreateCommand(t *testing.T) { Return(types.EVERYONE, []string{}, nil).Once() // TODO: testing chicken and egg: we need the default mocks in place before we can use any of the `clients` methods clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -167,7 +167,7 @@ func TestTriggersCreateCommand(t *testing.T) { Return(types.EVERYONE, []string{}, nil).Once() // TODO: testing chicken and egg: we need the default mocks in place before we can use any of the `clients` methods clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -199,7 +199,7 @@ func TestTriggersCreateCommand(t *testing.T) { clientsMock.ApiInterface.On("WorkflowsTriggersCreate", mock.Anything, mock.Anything, mock.Anything).Return(types.DeployedTrigger{}, errors.New("invalid_auth")) // TODO: testing chicken and egg: we need the default mocks in place before we can use any of the `clients` methods clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -220,7 +220,7 @@ func TestTriggersCreateCommand(t *testing.T) { Return(types.EVERYONE, []string{}, nil).Once() // TODO: testing chicken and egg: we need the default mocks in place before we can use any of the `clients` methods clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") jsonPayload := `{ "type":"scheduled", @@ -256,7 +256,7 @@ func TestTriggersCreateCommand(t *testing.T) { // TODO: testing chicken and egg: we need the default mocks in place before we can use any of the `clients` methods clientsMock.AddDefaultMocks() clientsMock.HookExecutor.On("Execute", mock.Anything).Return("", nil) - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -275,7 +275,7 @@ func TestTriggersCreateCommand(t *testing.T) { // TODO: testing chicken and egg: we need the default mocks in place before we can use any of the `clients` methods clientsMock.AddDefaultMocks() clientsMock.HookExecutor.On("Execute", mock.Anything).Return(`{}`, nil) - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") var content = `export default {}` err = afero.WriteFile(clients.Fs, "triggers/shortcut.ts", []byte(content), 0600) @@ -297,7 +297,7 @@ func TestTriggersCreateCommand(t *testing.T) { appSelectTeardown = setupMockCreateAppSelection(installedProdApp) // TODO: testing chicken and egg: we need the default mocks in place before we can use any of the `clients` methods clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") var content = `export default {}` err = afero.WriteFile(clients.Fs, "triggers/shortcut.ts", []byte(content), 0600) @@ -372,7 +372,7 @@ func TestTriggersCreateCommand_MissingParameters(t *testing.T) { Return(types.EVERYONE, []string{}, nil).Once() // TODO: testing chicken and egg: we need the default mocks in place before we can use any of the `clients` methods clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { @@ -403,7 +403,7 @@ func TestTriggersCreateCommand_MissingParameters(t *testing.T) { clientsMock.ApiInterface.On("WorkflowsTriggersCreate", mock.Anything, mock.Anything, triggerRequestWithInteractivityInputs).Return(types.DeployedTrigger{}, errors.New("internal_error")).Once() // TODO: testing chicken and egg: we need the default mocks in place before we can use any of the `clients` methods clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { @@ -432,7 +432,7 @@ func TestTriggersCreateCommand_MissingParameters(t *testing.T) { clientsMock.ApiInterface.On("WorkflowsTriggersCreate", mock.Anything, mock.Anything, mock.Anything).Return(types.DeployedTrigger{}, extendedErr) // TODO: testing chicken and egg: we need the default mocks in place before we can use any of the `clients` methods clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, ExpectedAsserts: func(t *testing.T, ctx context.Context, clientsMock *shared.ClientsMock) { @@ -489,7 +489,7 @@ func TestTriggersCreateCommand_AppSelection(t *testing.T) { workspaceInstallAppFunc = originalWorkspaceInstallAppFunc } appCommandMock.On("RunAddCommand", mock.Anything, mock.Anything, mock.Anything, mock.Anything). - Return(context.Background(), types.SUCCESS, newDevApp.App, nil) + Return(ctx, types.SUCCESS, newDevApp.App, nil) clientsMock.ApiInterface.On("WorkflowsTriggersCreate", mock.Anything, mock.Anything, mock.Anything). Return(types.DeployedTrigger{}, nil) // Define default mocks @@ -517,7 +517,7 @@ func TestTriggersCreateCommand_AppSelection(t *testing.T) { workspaceInstallAppFunc = originalWorkspaceInstallAppFunc } appCommandMock.On("RunAddCommand", mock.Anything, mock.Anything, mock.Anything, mock.Anything). - Return(context.Background(), types.SUCCESS, newDevApp.App, nil) + Return(ctx, types.SUCCESS, newDevApp.App, nil) clientsMock.ApiInterface.On("WorkflowsTriggersCreate", mock.Anything, mock.Anything, mock.Anything). Return(types.DeployedTrigger{}, nil) // Define default mocks diff --git a/cmd/triggers/delete_test.go b/cmd/triggers/delete_test.go index b061708a..8b76d2af 100644 --- a/cmd/triggers/delete_test.go +++ b/cmd/triggers/delete_test.go @@ -71,7 +71,7 @@ func TestTriggersDeleteCommand(t *testing.T) { clientsMock.AddDefaultMocks() // TODO this can probably be replaced by a helper that sets up an apps.json file in // the right place on the afero memfs instance - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -89,7 +89,7 @@ func TestTriggersDeleteCommand(t *testing.T) { clientsMock.ApiInterface.On("WorkflowsTriggersDelete", mock.Anything, mock.Anything, mock.Anything).Return(errors.New("invalid_auth")) // TODO: testing chicken and egg: we need the default mocks in place before we can use any of the `clients` methods clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -130,7 +130,7 @@ func TestTriggersDeleteCommand_AppSelection(t *testing.T) { clientsMock.AddDefaultMocks() // TODO this can probably be replaced by a helper that sets up an apps.json file in // the right place on the afero memfs instance - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") appSelectTeardown = setupMockDeleteAppSelection(newDevApp) @@ -146,7 +146,7 @@ func TestTriggersDeleteCommand_AppSelection(t *testing.T) { clientsMock.AddDefaultMocks() // TODO this can probably be replaced by a helper that sets up an apps.json file in // the right place on the afero memfs instance - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") appSelectTeardown = setupMockDeleteAppSelection(newProdApp) diff --git a/cmd/triggers/info_test.go b/cmd/triggers/info_test.go index 97109e30..6a6901e1 100644 --- a/cmd/triggers/info_test.go +++ b/cmd/triggers/info_test.go @@ -83,7 +83,7 @@ func TestTriggersInfoCommand(t *testing.T) { clientsMock.ApiInterface.On("TriggerPermissionsList", mock.Anything, mock.Anything, mock.Anything). Return(types.EVERYONE, []string{}, nil).Once() clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -108,7 +108,7 @@ func TestTriggersInfoCommand(t *testing.T) { clientsMock.ApiInterface.On("TriggerPermissionsList", mock.Anything, mock.Anything, mock.Anything). Return(types.EVERYONE, []string{}, nil).Once() clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -126,7 +126,7 @@ func TestTriggersInfoCommand(t *testing.T) { clientsMock.ApiInterface.On("WorkflowsTriggersInfo", mock.Anything, mock.Anything, mock.Anything).Return(types.DeployedTrigger{}, errors.New("invalid_auth")) // TODO: testing chicken and egg: we need the default mocks in place before we can use any of the `clients` methods clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -146,7 +146,7 @@ func TestTriggersInfoCommand(t *testing.T) { clientsMock.ApiInterface.On("TriggerPermissionsList", mock.Anything, mock.Anything, mock.Anything). Return(types.EVERYONE, []string{}, nil).Once() clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -197,7 +197,7 @@ func TestTriggersInfoCommand_AppSelection(t *testing.T) { clientsMock.AddDefaultMocks() // TODO this can probably be replaced by a helper that sets up an apps.json file in // the right place on the afero memfs instance - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") appSelectTeardown = setupMockInfoAppSelection(newDevApp) @@ -213,7 +213,7 @@ func TestTriggersInfoCommand_AppSelection(t *testing.T) { clientsMock.AddDefaultMocks() // TODO this can probably be replaced by a helper that sets up an apps.json file in // the right place on the afero memfs instance - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") appSelectTeardown = setupMockInfoAppSelection(newProdApp) diff --git a/cmd/triggers/update_test.go b/cmd/triggers/update_test.go index c74c90e8..d552bd50 100644 --- a/cmd/triggers/update_test.go +++ b/cmd/triggers/update_test.go @@ -79,7 +79,7 @@ func TestTriggersUpdateCommand(t *testing.T) { clientsMock.AddDefaultMocks() // TODO this can probably be replaced by a helper that sets up an apps.json file in // the right place on the afero memfs instance - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") appSelectTeardown = setupMockUpdateAppSelection(newProdApp) @@ -95,7 +95,7 @@ func TestTriggersUpdateCommand(t *testing.T) { clientsMock.AddDefaultMocks() // TODO this can probably be replaced by a helper that sets up an apps.json file in // the right place on the afero memfs instance - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") appSelectTeardown = setupMockUpdateAppSelection(newDevApp) @@ -119,7 +119,7 @@ func TestTriggersUpdateCommand(t *testing.T) { clientsMock.AddDefaultMocks() // TODO this can probably be replaced by a helper that sets up an apps.json file in // the right place on the afero memfs instance - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -155,7 +155,7 @@ func TestTriggersUpdateCommand(t *testing.T) { clientsMock.AddDefaultMocks() // TODO this can probably be replaced by a helper that sets up an apps.json file in // the right place on the afero memfs instance - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -196,7 +196,7 @@ func TestTriggersUpdateCommand(t *testing.T) { clientsMock.AddDefaultMocks() // TODO this can probably be replaced by a helper that sets up an apps.json file in // the right place on the afero memfs instance - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -235,7 +235,7 @@ func TestTriggersUpdateCommand(t *testing.T) { Return(types.EVERYONE, []string{}, nil).Once() // TODO: testing chicken and egg: we need the default mocks in place before we can use any of the `clients` methods clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -264,7 +264,7 @@ func TestTriggersUpdateCommand(t *testing.T) { clientsMock.ApiInterface.On("WorkflowsTriggersUpdate", mock.Anything, mock.Anything, mock.Anything).Return(types.DeployedTrigger{}, errors.New("invalid_auth")) // TODO: testing chicken and egg: we need the default mocks in place before we can use any of the `clients` methods clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -284,7 +284,7 @@ func TestTriggersUpdateCommand(t *testing.T) { Return(types.EVERYONE, []string{}, nil).Once() // TODO: testing chicken and egg: we need the default mocks in place before we can use any of the `clients` methods clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") jsonPayload := `{ "type":"scheduled", @@ -322,7 +322,7 @@ func TestTriggersUpdateCommand(t *testing.T) { appSelectTeardown = setupMockUpdateAppSelection(installedProdApp) // TODO: testing chicken and egg: we need the default mocks in place before we can use any of the `clients` methods clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -341,7 +341,7 @@ func TestTriggersUpdateCommand(t *testing.T) { // TODO: testing chicken and egg: we need the default mocks in place before we can use any of the `clients` methods clientsMock.AddDefaultMocks() clientsMock.HookExecutor.On("Execute", mock.Anything).Return(`{`, nil) - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") var content = `export default {}` err = afero.WriteFile(clients.Fs, "triggers/shortcut.ts", []byte(content), 0600) @@ -424,7 +424,7 @@ func TestTriggersUpdateCommand_MissingParameters(t *testing.T) { Return(types.EVERYONE, []string{}, nil).Once() // TODO: testing chicken and egg: we need the default mocks in place before we can use any of the `clients` methods clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -455,7 +455,7 @@ func TestTriggersUpdateCommand_MissingParameters(t *testing.T) { clientsMock.ApiInterface.On("WorkflowsTriggersUpdate", mock.Anything, mock.Anything, triggerRequestWithInteractivityInputs).Return(types.DeployedTrigger{}, errors.New("internal_error")) // TODO: testing chicken and egg: we need the default mocks in place before we can use any of the `clients` methods clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { @@ -484,7 +484,7 @@ func TestTriggersUpdateCommand_MissingParameters(t *testing.T) { clientsMock.ApiInterface.On("WorkflowsTriggersUpdate", mock.Anything, mock.Anything, mock.Anything).Return(types.DeployedTrigger{}, extendedErr) // TODO: testing chicken and egg: we need the default mocks in place before we can use any of the `clients` methods clientsMock.AddDefaultMocks() - err := clients.AppClient().SaveDeployed(context.Background(), fakeApp) + err := clients.AppClient().SaveDeployed(ctx, fakeApp) require.NoError(t, err, "Cant write apps.json") }, Teardown: func() { From 47a5bcd91dee762769d03e59166f88e51e8b7940 Mon Sep 17 00:00:00 2001 From: Michael Brooks Date: Thu, 10 Apr 2025 11:35:43 -0700 Subject: [PATCH 10/13] refactor: update .Context() references for consistency --- cmd/app/app.go | 3 ++- cmd/app/link_test.go | 23 +++++++++++------------ cmd/auth/list.go | 12 ++++++++---- cmd/auth/login.go | 3 ++- cmd/collaborators/add.go | 3 ++- cmd/collaborators/list.go | 3 +-- cmd/collaborators/remove.go | 3 ++- cmd/collaborators/update.go | 3 +-- cmd/doctor/doctor_test.go | 3 ++- cmd/fingerprint/fingerprint.go | 5 +++-- cmd/help/help.go | 3 ++- cmd/platform/deploy.go | 5 +++-- cmd/platform/run.go | 2 +- cmd/project/create.go | 5 +++-- cmd/project/create_template.go | 16 +++++++++------- cmd/root.go | 9 +++++---- cmd/triggers/access.go | 10 ++++++---- cmd/triggers/create.go | 6 ++++-- cmd/triggers/info.go | 2 +- cmd/triggers/list.go | 2 +- cmd/upgrade/upgrade.go | 3 ++- cmd/version/version.go | 3 ++- internal/config/project_test.go | 2 +- internal/slacktrace/slacktrace.go | 2 +- internal/update/cli.go | 3 ++- internal/update/sdk.go | 6 ++++-- internal/update/sdk_test.go | 3 ++- internal/update/update.go | 4 +++- 28 files changed, 86 insertions(+), 61 deletions(-) diff --git a/cmd/app/app.go b/cmd/app/app.go index 637e4e5c..42113397 100644 --- a/cmd/app/app.go +++ b/cmd/app/app.go @@ -46,8 +46,9 @@ func NewCommand(clients *shared.ClientFactory) *cobra.Command { return runListCommand(cmd, clients) }, PostRunE: func(cmd *cobra.Command, args []string) error { + ctx := cmd.Context() if cmd.CalledAs() == "workspace" { - clients.IO.PrintInfo(cmd.Context(), false, fmt.Sprintf( + clients.IO.PrintInfo(ctx, false, fmt.Sprintf( "\n%s It looks like you used %s. This command will be deprecated in an upcoming release.\n You can now use %s instead of %s.\n ", style.Emoji("bulb"), style.Commandf("workspace", true), diff --git a/cmd/app/link_test.go b/cmd/app/link_test.go index 227f045b..511b54f7 100644 --- a/cmd/app/link_test.go +++ b/cmd/app/link_test.go @@ -61,7 +61,7 @@ func Test_Apps_Link(t *testing.T) { mockLinkSlackAuth1, }, nil) cm.AddDefaultMocks() - setupAppLinkCommandMocks(t, cm, cf) + setupAppLinkCommandMocks(t, ctx, cm, cf) cm.IO.On("SelectPrompt", mock.Anything, "Select the existing app team", @@ -118,7 +118,7 @@ func Test_Apps_Link(t *testing.T) { mockLinkSlackAuth1, }, nil) cm.AddDefaultMocks() - setupAppLinkCommandMocks(t, cm, cf) + setupAppLinkCommandMocks(t, ctx, cm, cf) cm.IO.On("SelectPrompt", mock.Anything, "Select the existing app team", @@ -177,7 +177,7 @@ func Test_Apps_Link(t *testing.T) { mockLinkSlackAuth2, }, nil) cm.AddDefaultMocks() - setupAppLinkCommandMocks(t, cm, cf) + setupAppLinkCommandMocks(t, ctx, cm, cf) existingApp := types.App{ AppID: mockLinkAppID1, TeamDomain: mockLinkSlackAuth1.TeamDomain, @@ -246,7 +246,7 @@ func Test_Apps_Link(t *testing.T) { mockLinkSlackAuth2, }, nil) cm.AddDefaultMocks() - setupAppLinkCommandMocks(t, cm, cf) + setupAppLinkCommandMocks(t, ctx, cm, cf) existingApp := types.App{ AppID: mockLinkAppID1, TeamDomain: mockLinkSlackAuth1.TeamDomain, @@ -321,7 +321,7 @@ func Test_Apps_Link(t *testing.T) { mockLinkSlackAuth2, }, nil) cm.AddDefaultMocks() - setupAppLinkCommandMocks(t, cm, cf) + setupAppLinkCommandMocks(t, ctx, cm, cf) existingApp := types.App{ AppID: mockLinkAppID2, TeamDomain: mockLinkSlackAuth2.TeamDomain, @@ -389,7 +389,7 @@ func Test_Apps_Link(t *testing.T) { mockLinkSlackAuth2, }, nil) cm.AddDefaultMocks() - setupAppLinkCommandMocks(t, cm, cf) + setupAppLinkCommandMocks(t, ctx, cm, cf) cm.IO.On("SelectPrompt", mock.Anything, "Select the existing app team", @@ -437,9 +437,9 @@ func Test_Apps_Link(t *testing.T) { mockLinkSlackAuth1, }, nil) cm.AddDefaultMocks() - setupAppLinkCommandMocks(t, cm, cf) + setupAppLinkCommandMocks(t, ctx, cm, cf) // Set manifest source to project to trigger confirmation prompt - if err := cm.Config.ProjectConfig.SetManifestSource(t.Context(), config.MANIFEST_SOURCE_LOCAL); err != nil { + if err := cm.Config.ProjectConfig.SetManifestSource(ctx, config.MANIFEST_SOURCE_LOCAL); err != nil { require.FailNow(t, fmt.Sprintf("Failed to set the manifest source in the memory-based file system: %s", err)) } // Accept manifest source confirmation prompt @@ -506,9 +506,9 @@ func Test_Apps_Link(t *testing.T) { "decline manifest source prompt should not link app": { Setup: func(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { cm.AddDefaultMocks() - setupAppLinkCommandMocks(t, cm, cf) + setupAppLinkCommandMocks(t, ctx, cm, cf) // Set manifest source to project to trigger confirmation prompt - if err := cm.Config.ProjectConfig.SetManifestSource(t.Context(), config.MANIFEST_SOURCE_LOCAL); err != nil { + if err := cm.Config.ProjectConfig.SetManifestSource(ctx, config.MANIFEST_SOURCE_LOCAL); err != nil { require.FailNow(t, fmt.Sprintf("Failed to set the manifest source in the memory-based file system: %s", err)) } // Decline manifest source confirmation prompt @@ -593,8 +593,7 @@ func Test_Apps_LinkAppHeaderSection(t *testing.T) { } } -func setupAppLinkCommandMocks(t *testing.T, cm *shared.ClientsMock, cf *shared.ClientFactory) { - ctx := t.Context() +func setupAppLinkCommandMocks(t *testing.T, ctx context.Context, cm *shared.ClientsMock, cf *shared.ClientFactory) { projectDirPath := slackdeps.MockWorkingDirectory cm.Os.On("Getwd").Return(projectDirPath, nil) diff --git a/cmd/auth/list.go b/cmd/auth/list.go index 23e5a834..5809a982 100644 --- a/cmd/auth/list.go +++ b/cmd/auth/list.go @@ -51,8 +51,9 @@ func NewListCommand(clients *shared.ClientFactory) *cobra.Command { // runListCommand will execute the list command func runListCommand(cmd *cobra.Command, clients *shared.ClientFactory) error { + ctx := cmd.Context() log := newListLogger(cmd, clients.IO) - userAuthList, err := listFunc(cmd.Context(), clients, log) + userAuthList, err := listFunc(ctx, clients, log) if err != nil { return err } @@ -87,6 +88,8 @@ func newListLogger(cmd *cobra.Command, IO iostreams.IOStreamer) *logger.Logger { // API Host: https://dev.slack.com (optional, only shown for custom API Hosts) // Last Updated: 2021-03-12 11:18:00 -0700 func printAuthList(cmd *cobra.Command, IO iostreams.IOStreamer, userAuthList []types.SlackAuth) { + ctx := cmd.Context() + // Based on loosely on time.RFC3339 timeFormat := "2006-01-02 15:04:05 Z07:00" @@ -121,7 +124,7 @@ func printAuthList(cmd *cobra.Command, IO iostreams.IOStreamer, userAuthList []t cmd.Println() // Print a trace with info about the authorization - IO.PrintTrace(cmd.Context(), slacktrace.AuthListInfo, authInfo.UserID, authInfo.TeamID) + IO.PrintTrace(ctx, slacktrace.AuthListInfo, authInfo.UserID, authInfo.TeamID) } // When there are no authorizations @@ -130,11 +133,12 @@ func printAuthList(cmd *cobra.Command, IO iostreams.IOStreamer, userAuthList []t } // Print a trace with the total number of authorized workspaces - IO.PrintTrace(cmd.Context(), slacktrace.AuthListCount, fmt.Sprint(len(userAuthList))) + IO.PrintTrace(ctx, slacktrace.AuthListCount, fmt.Sprint(len(userAuthList))) } // printAuthListSuccess is displayed at the very end and helps guide the developer toward next steps. func printAuthListSuccess(cmd *cobra.Command, IO iostreams.IOStreamer, userAuthList []types.SlackAuth) { + ctx := cmd.Context() commandText := style.Commandf("login", true) // When there are no authorizations, guide the user to creating an authorization. @@ -145,5 +149,5 @@ func printAuthListSuccess(cmd *cobra.Command, IO iostreams.IOStreamer, userAuthL ) } - IO.PrintTrace(cmd.Context(), slacktrace.AuthListSuccess) + IO.PrintTrace(ctx, slacktrace.AuthListSuccess) } diff --git a/cmd/auth/login.go b/cmd/auth/login.go index 7a92cd81..4d03329b 100644 --- a/cmd/auth/login.go +++ b/cmd/auth/login.go @@ -127,6 +127,8 @@ func RunLoginCommand(clients *shared.ClientFactory, cmd *cobra.Command) (types.S } func printAuthSuccess(cmd *cobra.Command, IO iostreams.IOStreamer, credentialsPath string, token string) { + ctx := cmd.Context() + var secondaryLog string if credentialsPath != "" { secondaryLog = fmt.Sprintf("Authorization data was saved to %s", style.HomePath(credentialsPath)) @@ -134,7 +136,6 @@ func printAuthSuccess(cmd *cobra.Command, IO iostreams.IOStreamer, credentialsPa secondaryLog = fmt.Sprintf("Service token:\n\n %s\n\nMake sure to copy the token now and save it safely.", token) } - ctx := cmd.Context() IO.PrintInfo(ctx, false, "\n%s", style.Sectionf(style.TextSection{ Emoji: "key", Text: "You've successfully authenticated!", diff --git a/cmd/collaborators/add.go b/cmd/collaborators/add.go index d41219bb..33eb5b33 100644 --- a/cmd/collaborators/add.go +++ b/cmd/collaborators/add.go @@ -58,7 +58,8 @@ func NewAddCommand(clients *shared.ClientFactory) *cobra.Command { return cmdutil.IsValidProjectDirectory(clients) }, RunE: func(cmd *cobra.Command, args []string) error { - return runAddCommandFunc(cmd.Context(), clients, cmd, args) + ctx := cmd.Context() + return runAddCommandFunc(ctx, clients, cmd, args) }, } cmd.Flags().StringVarP(&addFlags.permissionType, "permission-type", "P", "", "collaborator permission type: reader, owner") diff --git a/cmd/collaborators/list.go b/cmd/collaborators/list.go index cd72d4e6..93bf24fe 100644 --- a/cmd/collaborators/list.go +++ b/cmd/collaborators/list.go @@ -53,9 +53,8 @@ func NewListCommand(clients *shared.ClientFactory) *cobra.Command { // runListCommand will execute the list command func runListCommand(cmd *cobra.Command, clients *shared.ClientFactory) error { - var span opentracing.Span ctx := cmd.Context() - span, ctx = opentracing.StartSpanFromContext(ctx, "cmd.Collaborators.List") + span, ctx := opentracing.StartSpanFromContext(ctx, "cmd.Collaborators.List") defer span.Finish() // Get the app auth selection from the flag or prompt diff --git a/cmd/collaborators/remove.go b/cmd/collaborators/remove.go index 5d78852b..bbc4f046 100644 --- a/cmd/collaborators/remove.go +++ b/cmd/collaborators/remove.go @@ -48,7 +48,8 @@ func NewRemoveCommand(clients *shared.ClientFactory) *cobra.Command { return cmdutil.IsValidProjectDirectory(clients) }, RunE: func(cmd *cobra.Command, args []string) error { - return runRemoveCommandFunc(cmd.Context(), clients, cmd, args) + ctx := cmd.Context() + return runRemoveCommandFunc(ctx, clients, cmd, args) }, } } diff --git a/cmd/collaborators/update.go b/cmd/collaborators/update.go index 7cf917d4..a8a2024a 100644 --- a/cmd/collaborators/update.go +++ b/cmd/collaborators/update.go @@ -74,9 +74,8 @@ func NewUpdateCommand(clients *shared.ClientFactory) *cobra.Command { // runUpdateCommand will execute the update command func runUpdateCommand(cmd *cobra.Command, clients *shared.ClientFactory, args []string) error { - var span opentracing.Span ctx := cmd.Context() - span, ctx = opentracing.StartSpanFromContext(ctx, "cmd.Collaborators.Update") + span, ctx := opentracing.StartSpanFromContext(ctx, "cmd.Collaborators.Update") defer span.Finish() var slackUser types.SlackUser diff --git a/cmd/doctor/doctor_test.go b/cmd/doctor/doctor_test.go index 0ea22afb..4964e1e7 100644 --- a/cmd/doctor/doctor_test.go +++ b/cmd/doctor/doctor_test.go @@ -51,6 +51,7 @@ func TestDoctorCommand(t *testing.T) { expectedUpdateTime := "0001-01-01 00:00:00 Z" t.Run("creates a complete report", func(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() clientsMock.AuthInterface.On("Auths", mock.Anything).Return([]types.SlackAuth{expectedCredentials}, nil) clientsMock.AuthInterface.On("ResolveApiHost", mock.Anything, mock.Anything, mock.Anything).Return("api.slack.com") @@ -90,7 +91,7 @@ func TestDoctorCommand(t *testing.T) { err := cmd.Execute() require.NoError(t, err) - report, err := performChecks(cmd.Context(), clients) + report, err := performChecks(ctx, clients) require.NoError(t, err) expectedValues := DoctorReport{ diff --git a/cmd/fingerprint/fingerprint.go b/cmd/fingerprint/fingerprint.go index 47c49e50..353ee203 100644 --- a/cmd/fingerprint/fingerprint.go +++ b/cmd/fingerprint/fingerprint.go @@ -43,10 +43,11 @@ func NewCommand(clients *shared.ClientFactory) *cobra.Command { {Command: "_fingerprint", Meaning: "Print the unique value that identifies the Slack CLI binary"}, }), RunE: func(cmd *cobra.Command, args []string) error { - var span, _ = opentracing.StartSpanFromContext(cmd.Context(), "cmd._fingerprint") + ctx := cmd.Context() + var span, _ = opentracing.StartSpanFromContext(ctx, "cmd._fingerprint") defer span.Finish() - clients.IO.PrintInfo(cmd.Context(), false, fingerprintHash) + clients.IO.PrintInfo(ctx, false, fingerprintHash) return nil }, } diff --git a/cmd/help/help.go b/cmd/help/help.go index 5395249f..c80795c6 100644 --- a/cmd/help/help.go +++ b/cmd/help/help.go @@ -30,9 +30,10 @@ func HelpFunc( aliases map[string]string, ) func(*cobra.Command, []string) { return func(cmd *cobra.Command, args []string) { + ctx := cmd.Context() style.ToggleStyles(clients.IO.IsTTY() && !clients.Config.NoColor) if help, _ := clients.Config.Flags.GetBool("help"); help { - clients.Config.LoadExperiments(cmd.Context(), clients.IO.PrintDebug) + clients.Config.LoadExperiments(ctx, clients.IO.PrintDebug) } experiments := []string{} for _, exp := range clients.Config.GetExperiments() { diff --git a/cmd/platform/deploy.go b/cmd/platform/deploy.go index 70584f5d..3e689f61 100644 --- a/cmd/platform/deploy.go +++ b/cmd/platform/deploy.go @@ -244,6 +244,7 @@ func printDeployHosting(cmd *cobra.Command, event *logger.LogEvent) { } func printDeployHostingCompletion(clients *shared.ClientFactory, cmd *cobra.Command, event *logger.LogEvent) error { + var ctx = cmd.Context() var authSession api.AuthSession appName := event.DataToString("appName") @@ -289,7 +290,7 @@ func printDeployHostingCompletion(clients *shared.ClientFactory, cmd *cobra.Comm deploySpinner.Update(successfulDeployText, "").Stop() - clients.IO.PrintTrace(cmd.Context(), slacktrace.PlatformDeploySuccess) + clients.IO.PrintTrace(ctx, slacktrace.PlatformDeploySuccess) navigateText := style.Sectionf(style.TextSection{ Emoji: "cloud_with_lightning", @@ -300,7 +301,7 @@ func printDeployHostingCompletion(clients *shared.ClientFactory, cmd *cobra.Comm }, }) - clients.IO.PrintInfo(cmd.Context(), false, navigateText) + clients.IO.PrintInfo(ctx, false, navigateText) return nil } diff --git a/cmd/platform/run.go b/cmd/platform/run.go index e2dc88d2..95573feb 100644 --- a/cmd/platform/run.go +++ b/cmd/platform/run.go @@ -167,7 +167,7 @@ func newRunLogger(clients *shared.ClientFactory, cmd *cobra.Command) *logger.Log event.DataToString("teamName"), ))) case "on_cloud_run_connection_connected": - clients.IO.PrintTrace(cmd.Context(), slacktrace.PlatformRunReady) + clients.IO.PrintTrace(ctx, slacktrace.PlatformRunReady) cmd.Println(style.Secondary("Connected, awaiting events")) case "on_cloud_run_connection_message": message := event.DataToString("cloud_run_connection_message") diff --git a/cmd/project/create.go b/cmd/project/create.go index 4a99af68..ff5c67c3 100644 --- a/cmd/project/create.go +++ b/cmd/project/create.go @@ -76,6 +76,7 @@ func NewCreateCommand(clients *shared.ClientFactory) *cobra.Command { } func runCreateCommand(clients *shared.ClientFactory, cmd *cobra.Command, args []string) error { + ctx := cmd.Context() // Set up event logger log := newCreateLogger(clients, cmd) @@ -102,7 +103,6 @@ func runCreateCommand(clients *shared.ClientFactory, cmd *cobra.Command, args [] } clients.EventTracker.SetAppTemplate(template.GetTemplatePath()) - ctx := cmd.Context() appDirPath, err := CreateFunc(ctx, clients, log, createArgs) if err != nil { printAppCreateError(clients, cmd, err) @@ -239,11 +239,12 @@ func printCreateSuccess(ctx context.Context, clients *shared.ClientFactory, appP // printAppCreateError stops the creation spinners and displays the returned error message func printAppCreateError(clients *shared.ClientFactory, cmd *cobra.Command, err error) { + ctx := cmd.Context() switch { case appCreateSpinner.Active(): errorText := fmt.Sprintf("Error creating project directory: %s", err) appCreateSpinner.Update(errorText, "warning").Stop() default: } - clients.IO.PrintTrace(cmd.Context(), slacktrace.CreateError) + clients.IO.PrintTrace(ctx, slacktrace.CreateError) } diff --git a/cmd/project/create_template.go b/cmd/project/create_template.go index 9a98e8cd..c943861b 100644 --- a/cmd/project/create_template.go +++ b/cmd/project/create_template.go @@ -153,10 +153,10 @@ func promptTemplateSelection(cmd *cobra.Command, clients *shared.ClientFactory) templateForCategory := getSelectionTemplate(clients) // Print a trace with info about the category title options provided by CLI - clients.IO.PrintTrace(cmd.Context(), slacktrace.CreateCategoryOptions, strings.Join(titlesForCategory, ", ")) + clients.IO.PrintTrace(ctx, slacktrace.CreateCategoryOptions, strings.Join(titlesForCategory, ", ")) // Prompt to choose a category - selection, err := clients.IO.SelectPrompt(cmd.Context(), promptForCategory, titlesForCategory, iostreams.SelectPromptConfig{ + selection, err := clients.IO.SelectPrompt(ctx, promptForCategory, titlesForCategory, iostreams.SelectPromptConfig{ Description: func(value string, index int) string { return optionsForCategory[index].Description }, @@ -189,10 +189,10 @@ func promptTemplateSelection(cmd *cobra.Command, clients *shared.ClientFactory) template := getSelectionTemplate(clients) // Print a trace with info about the template title options provided by CLI - clients.IO.PrintTrace(cmd.Context(), slacktrace.CreateTemplateOptions, strings.Join(titles, ", ")) + clients.IO.PrintTrace(ctx, slacktrace.CreateTemplateOptions, strings.Join(titles, ", ")) // Prompt to choose a template - selection, err := clients.IO.SelectPrompt(cmd.Context(), prompt, titles, iostreams.SelectPromptConfig{ + selection, err := clients.IO.SelectPrompt(ctx, prompt, titles, iostreams.SelectPromptConfig{ Description: func(value string, index int) string { return options[index].Description }, @@ -238,7 +238,9 @@ func promptTemplateSelection(cmd *cobra.Command, clients *shared.ClientFactory) // confirmExternalTemplateSelection prompts the user to confirm that they want to create an app from // an external template and saves their preference if they choose to ignore future warnings func confirmExternalTemplateSelection(cmd *cobra.Command, clients *shared.ClientFactory, template create.Template) (bool, error) { - trustSources, err := clients.Config.SystemConfig.GetTrustUnknownSources(cmd.Context()) + ctx := cmd.Context() + + trustSources, err := clients.Config.SystemConfig.GetTrustUnknownSources(ctx) if err != nil { return false, err } @@ -254,7 +256,7 @@ func confirmExternalTemplateSelection(cmd *cobra.Command, clients *shared.Client }, })) - selection, err := clients.IO.SelectPrompt(cmd.Context(), "Proceed?", []string{"Yes", "Yes, don't ask again", "No"}, iostreams.SelectPromptConfig{ + selection, err := clients.IO.SelectPrompt(ctx, "Proceed?", []string{"Yes", "Yes, don't ask again", "No"}, iostreams.SelectPromptConfig{ Required: true, Flag: clients.Config.Flags.Lookup("force"), }) @@ -263,7 +265,7 @@ func confirmExternalTemplateSelection(cmd *cobra.Command, clients *shared.Client } else if selection.Option == "No" { return false, nil } else if selection.Option == "Yes, don't ask again" { - err = clients.Config.SystemConfig.SetTrustUnknownSources(cmd.Context(), true) + err = clients.Config.SystemConfig.SetTrustUnknownSources(ctx, true) if err != nil { return true, slackerror.Wrap(err, "failed to set trust_unknown_sources property to config") } diff --git a/cmd/root.go b/cmd/root.go index 7e9f5d6f..b87d21de 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -102,7 +102,9 @@ func NewRootCommand(clients *shared.ClientFactory, updateNotification *update.Up `{{Emoji "books"}}Get started by reading the docs: {{LinkText "https://api.slack.com/automation"}}`, }, "\n"), PersistentPreRunE: func(cmd *cobra.Command, args []string) error { + ctx := cmd.Context() clients.IO.SetCmdIO(cmd) + // Set user-invoked command (for metrics) clients.Config.Command = strings.Join(strings.Split(cmd.CommandPath(), " ")[1:], " ") clients.Config.CommandCanonical = clients.Config.Command @@ -118,9 +120,9 @@ func NewRootCommand(clients *shared.ClientFactory, updateNotification *update.Up clients.Config.RawFlags = append(clients.Config.RawFlags, flag.Name) } }) + // Check for an CLI update in the background while the command runs updateNotification = update.New(clients, version.Get(), "SLACK_SKIP_UPDATE") - ctx := cmd.Context() updateNotification.CheckForUpdateInBackground(ctx, false) return nil }, @@ -204,7 +206,7 @@ func Init() (*cobra.Command, *shared.ClientFactory) { // OnInitialize will execute before any root or child commands' Pre* methods. // This is a good place to house CLI bootup routines. cobra.OnInitialize(func() { - err := InitConfig(clients, rootCmd) + err := InitConfig(rootCmd.Context(), clients, rootCmd) if err != nil { clients.IO.PrintError(rootCmd.Context(), err.Error()) clients.Os.Exit(int(iostreams.ExitError)) @@ -220,8 +222,7 @@ func Init() (*cobra.Command, *shared.ClientFactory) { // InitConfig reads in config files and ENV variables if set and sets up the CLI for functioning. Executes _before_ any Pre* methods from the root or child commands, but after Cobra parses flags and command arguments. // Put global CLI initialization routines that rely on flag and argument parsing in here please! // TODO: consider using arguments for this function for certain dependencies, like working directory and other OS-specific strings, that OnInitialize above can provide during actual execution, but that we can override with test values for easier testing. -func InitConfig(clients *shared.ClientFactory, rootCmd *cobra.Command) error { - ctx := rootCmd.Context() +func InitConfig(ctx context.Context, clients *shared.ClientFactory, rootCmd *cobra.Command) error { // Get the current working directory (usually, but not always the project) workingDirPath, err := clients.Os.Getwd() diff --git a/cmd/triggers/access.go b/cmd/triggers/access.go index e2c03259..fa575e5d 100644 --- a/cmd/triggers/access.go +++ b/cmd/triggers/access.go @@ -559,7 +559,7 @@ func printAccess(cmd *cobra.Command, clients *shared.ClientFactory, token string accessType, userAccessList, err := clients.ApiInterface().TriggerPermissionsList(ctx, token, accessFlags.triggerId) if err != nil { - clients.IO.PrintTrace(cmd.Context(), slacktrace.TriggersAccessError) + clients.IO.PrintTrace(ctx, slacktrace.TriggersAccessError) return err } @@ -572,18 +572,20 @@ func printAccess(cmd *cobra.Command, clients *shared.ClientFactory, token string } else if accessType == types.NAMED_ENTITIES { err = printNamedEntitiesHelper(cmd, clients, token, userAccessList, "list") } - clients.IO.PrintTrace(cmd.Context(), slacktrace.TriggersAccessSuccess) + clients.IO.PrintTrace(ctx, slacktrace.TriggersAccessSuccess) return err } // printCurrentAuthorizedEntities formats and displays current access information func printCurrentAuthorizedEntities(cmd *cobra.Command, clients *shared.ClientFactory, token string, app types.App, currentAccessList []string, currentAccessType types.Permission) error { + ctx := cmd.Context() + cmd.Println() if currentAccessType == types.EVERYONE { var everyoneAccessTypeDescription = types.GetAccessTypeDescriptionForEveryone(app) - clients.IO.PrintInfo(cmd.Context(), false, "Trigger '%s' can be found and run by %s\n", accessFlags.triggerId, everyoneAccessTypeDescription) + clients.IO.PrintInfo(ctx, false, "Trigger '%s' can be found and run by %s\n", accessFlags.triggerId, everyoneAccessTypeDescription) } else if currentAccessType == (types.APP_COLLABORATORS) { - clients.IO.PrintInfo(cmd.Context(), false, "Access is currently granted to %s:", style.Pluralize("app collaborator", "app collaborators", len(currentAccessList))) + clients.IO.PrintInfo(ctx, false, "Access is currently granted to %s:", style.Pluralize("app collaborator", "app collaborators", len(currentAccessList))) err := printAppCollaboratorsHelper(cmd, clients, token, currentAccessList) if err != nil { return err diff --git a/cmd/triggers/create.go b/cmd/triggers/create.go index b59e5610..8f85a283 100644 --- a/cmd/triggers/create.go +++ b/cmd/triggers/create.go @@ -268,12 +268,14 @@ func promptShouldRetryCreateWithInteractivity(cmd *cobra.Command, IO iostreams.I } func promptShouldRetryWithInteractivity(promptMsg string, cmd *cobra.Command, IO iostreams.IOStreamer, triggerArg api.TriggerRequest) (bool, error) { + ctx := cmd.Context() + pretty, err := json.MarshalIndent(triggerArg, "", " ") if err != nil { return false, err } - IO.PrintInfo(cmd.Context(), false, "\n%s", style.Sectionf(style.TextSection{ + IO.PrintInfo(ctx, false, "\n%s", style.Sectionf(style.TextSection{ Emoji: "memo", Text: "Workflow requires interactivity", Secondary: []string{ @@ -282,7 +284,7 @@ func promptShouldRetryWithInteractivity(promptMsg string, cmd *cobra.Command, IO }, })) - return IO.ConfirmPrompt(cmd.Context(), promptMsg, true) + return IO.ConfirmPrompt(ctx, promptMsg, true) } func triggerRequestFromFlags(flags createCmdFlags, isDev bool) api.TriggerRequest { diff --git a/cmd/triggers/info.go b/cmd/triggers/info.go index fd9eb64a..7f65ed95 100644 --- a/cmd/triggers/info.go +++ b/cmd/triggers/info.go @@ -61,7 +61,7 @@ func NewInfoCommand(clients *shared.ClientFactory) *cobra.Command { func runInfoCommand(cmd *cobra.Command, clients *shared.ClientFactory) error { ctx := cmd.Context() - var span, _ = opentracing.StartSpanFromContext(cmd.Context(), "cmd.triggers.info") + var span, _ = opentracing.StartSpanFromContext(ctx, "cmd.triggers.info") defer span.Finish() // Get the app from the flag or prompt diff --git a/cmd/triggers/list.go b/cmd/triggers/list.go index 2d0ebb0d..dfa4da61 100644 --- a/cmd/triggers/list.go +++ b/cmd/triggers/list.go @@ -72,7 +72,7 @@ func NewListCommand(clients *shared.ClientFactory) *cobra.Command { // runListCommand will execute the list command func runListCommand(cmd *cobra.Command, clients *shared.ClientFactory) error { ctx := cmd.Context() - var span, _ = opentracing.StartSpanFromContext(cmd.Context(), "cmd.triggers.list") + var span, _ = opentracing.StartSpanFromContext(ctx, "cmd.triggers.list") defer span.Finish() // Get the app selection and accompanying auth from the flag or prompt diff --git a/cmd/upgrade/upgrade.go b/cmd/upgrade/upgrade.go index bda4c22e..e047bc8c 100644 --- a/cmd/upgrade/upgrade.go +++ b/cmd/upgrade/upgrade.go @@ -54,6 +54,7 @@ func NewCommand(clients *shared.ClientFactory) *cobra.Command { // checkForUpdates will check for CLI/SDK updates and print a message when no updates are available. // When there are updates, the function will *not* print a message because the root command handles printing update notifications. func checkForUpdates(clients *shared.ClientFactory, cmd *cobra.Command) error { + ctx := cmd.Context() updateNotification := update.New(clients, version.Get(), "SLACK_SKIP_UPDATE") // TODO(@mbrooks) This update check is happening at the same time as the root command's `CheckForUpdateInBackground`. @@ -62,7 +63,7 @@ func checkForUpdates(clients *shared.ClientFactory, cmd *cobra.Command) error { // How can we improve this to avoid doing 2 update network requests/checks? // // Force an update check that is blocking and synchronous - if err := updateNotification.CheckForUpdate(cmd.Context(), true); err != nil { + if err := updateNotification.CheckForUpdate(ctx, true); err != nil { return err } diff --git a/cmd/version/version.go b/cmd/version/version.go index 51b0fbaa..4c9282b8 100644 --- a/cmd/version/version.go +++ b/cmd/version/version.go @@ -68,7 +68,8 @@ func NewCommand(clients *shared.ClientFactory) *cobra.Command { }, }), Run: func(cmd *cobra.Command, args []string) { - var span, _ = opentracing.StartSpanFromContext(cmd.Context(), "cmd.version") + ctx := cmd.Context() + span, _ := opentracing.StartSpanFromContext(ctx, "cmd.version") defer span.Finish() cmd.Println(Template()) diff --git a/internal/config/project_test.go b/internal/config/project_test.go index b53a00bb..3594d1cb 100644 --- a/internal/config/project_test.go +++ b/internal/config/project_test.go @@ -619,7 +619,7 @@ func Test_Config_CreateProjectConfigJSONFile(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { - ctx := t.Context() + ctx := slackcontext.MockContext(t.Context()) fs := afero.NewMemMapFs() // Create the project directory and .slack directory diff --git a/internal/slacktrace/slacktrace.go b/internal/slacktrace/slacktrace.go index 6b8185e3..816b9218 100644 --- a/internal/slacktrace/slacktrace.go +++ b/internal/slacktrace/slacktrace.go @@ -35,7 +35,7 @@ package slacktrace // To add trace output to a command: // // use, -// clients.IO.PrintTrace(cmd.Context(), slacktrace.) +// clients.IO.PrintTrace(ctx, slacktrace.) const ( AdminAppApprovalRequestPending = "SLACK_TRACE_ADMIN_APPROVAL_REQUEST_PENDING" AdminAppApprovalRequestReasonSubmitted = "SLACK_TRACE_ADMIN_APPROVAL_REQUEST_REASON_SUBMITTED" diff --git a/internal/update/cli.go b/internal/update/cli.go index 4d2fe8fc..3e6a59db 100644 --- a/internal/update/cli.go +++ b/internal/update/cli.go @@ -69,6 +69,7 @@ func (c *CLIDependency) HasUpdate() (bool, error) { // PrintUpdateNotification notifies the user that a new version is available and provides upgrade instructions for Homebrew. Returns a bool representing whether the user wants the self-update to run func (c *CLIDependency) PrintUpdateNotification(cmd *cobra.Command) (bool, error) { + ctx := cmd.Context() processName := cmdutil.GetProcessName() isHomebrew := IsHomebrew(processName) @@ -92,7 +93,7 @@ func (c *CLIDependency) PrintUpdateNotification(cmd *cobra.Command) (bool, error style.CommandText("https://api.slack.com/automation/cli/install"), ) selfUpdatePrompt := fmt.Sprintf("%sDo you want to auto-update to the latest version now?", style.Emoji("rocket")) - return c.clients.IO.ConfirmPrompt(cmd.Context(), selfUpdatePrompt, false) + return c.clients.IO.ConfirmPrompt(ctx, selfUpdatePrompt, false) } return false, nil diff --git a/internal/update/sdk.go b/internal/update/sdk.go index 07a12b63..076ba2ca 100644 --- a/internal/update/sdk.go +++ b/internal/update/sdk.go @@ -189,6 +189,8 @@ func (c *SDKDependency) InstallUpdate(ctx context.Context) error { // SDK, including formatting and language that indicates if a breaking change // is included or an error has occurred func (c *SDKDependency) PrintUpdateNotification(cmd *cobra.Command) (bool, error) { + ctx := cmd.Context() + if c.releaseInfo.Update { // Standard "update is available" message cmd.Printf( @@ -308,7 +310,7 @@ func (c *SDKDependency) PrintUpdateNotification(cmd *cobra.Command) (bool, error // The update(s) includes an error if c.releaseInfo.Error.Message != "" { - c.clients.IO.PrintError(cmd.Context(), + c.clients.IO.PrintError(ctx, style.Indent("%s\n%s\n"), style.Error("Error:"), style.Indent(c.releaseInfo.Error.Message), @@ -318,7 +320,7 @@ func (c *SDKDependency) PrintUpdateNotification(cmd *cobra.Command) (bool, error // If `install-update` hook available, prompt to auto-update if c.clients.SDKConfig.Hooks.InstallUpdate.IsAvailable() { autoUpdatePrompt := fmt.Sprintf("%sDo you want to auto-update to the latest versions now?", style.Emoji("rocket")) - return c.clients.IO.ConfirmPrompt(cmd.Context(), autoUpdatePrompt, false) + return c.clients.IO.ConfirmPrompt(ctx, autoUpdatePrompt, false) } return false, nil diff --git a/internal/update/sdk_test.go b/internal/update/sdk_test.go index 22865276..76bf796a 100644 --- a/internal/update/sdk_test.go +++ b/internal/update/sdk_test.go @@ -21,6 +21,7 @@ import ( "github.com/slackapi/slack-cli/internal/hooks" "github.com/slackapi/slack-cli/internal/shared" + "github.com/slackapi/slack-cli/internal/slackcontext" "github.com/slackapi/slack-cli/test/testutil" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" @@ -270,6 +271,7 @@ func Test_SDK_HasUpdate(t *testing.T) { func Test_SDK_InstallUpdate(t *testing.T) { for _, s := range installScenarios { // Create mocks + ctx := slackcontext.MockContext(t.Context()) clientsMock := shared.NewClientsMock() // Create clients that is mocked for testing @@ -290,7 +292,6 @@ func Test_SDK_InstallUpdate(t *testing.T) { // Create the command cmd := &cobra.Command{} testutil.MockCmdIO(clients.IO, cmd) - ctx := cmd.Context() // output := clientsMock.GetCombinedOutput() diff --git a/internal/update/update.go b/internal/update/update.go index e1b23968..607ce02d 100644 --- a/internal/update/update.go +++ b/internal/update/update.go @@ -118,6 +118,8 @@ func (u *UpdateNotification) Dependencies() []Dependency { // PrintUpdates displays an update message after the command runs and prompts the user if they want to update, if applicable // Invoked from root command's post-run method. If an error occurs, we return it so it is raised to the user. func (u *UpdateNotification) PrintAndPromptUpdates(cmd *cobra.Command, cliVersion string) error { + ctx := cmd.Context() + if updateNotification.WaitForCheckForUpdateInBackground() { for _, dependency := range updateNotification.Dependencies() { hasUpdate, err := dependency.HasUpdate() @@ -131,7 +133,7 @@ func (u *UpdateNotification) PrintAndPromptUpdates(cmd *cobra.Command, cliVersio return err } if shouldSelfUpdate { - if err := dependency.InstallUpdate(cmd.Context()); err != nil { + if err := dependency.InstallUpdate(ctx); err != nil { return err } } From ca08f10384e1fe3761abac5077ef26e0de667bd1 Mon Sep 17 00:00:00 2001 From: Michael Brooks Date: Thu, 10 Apr 2025 12:04:38 -0700 Subject: [PATCH 11/13] refactor: update span to not return a ctx since it's locally scoped --- cmd/collaborators/list.go | 2 +- cmd/collaborators/update.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/collaborators/list.go b/cmd/collaborators/list.go index 93bf24fe..19633219 100644 --- a/cmd/collaborators/list.go +++ b/cmd/collaborators/list.go @@ -54,7 +54,7 @@ func NewListCommand(clients *shared.ClientFactory) *cobra.Command { // runListCommand will execute the list command func runListCommand(cmd *cobra.Command, clients *shared.ClientFactory) error { ctx := cmd.Context() - span, ctx := opentracing.StartSpanFromContext(ctx, "cmd.Collaborators.List") + span, _ := opentracing.StartSpanFromContext(ctx, "cmd.Collaborators.List") defer span.Finish() // Get the app auth selection from the flag or prompt diff --git a/cmd/collaborators/update.go b/cmd/collaborators/update.go index a8a2024a..f613741a 100644 --- a/cmd/collaborators/update.go +++ b/cmd/collaborators/update.go @@ -75,7 +75,7 @@ func NewUpdateCommand(clients *shared.ClientFactory) *cobra.Command { // runUpdateCommand will execute the update command func runUpdateCommand(cmd *cobra.Command, clients *shared.ClientFactory, args []string) error { ctx := cmd.Context() - span, ctx := opentracing.StartSpanFromContext(ctx, "cmd.Collaborators.Update") + span, _ := opentracing.StartSpanFromContext(ctx, "cmd.Collaborators.Update") defer span.Finish() var slackUser types.SlackUser From 33440d9a58659a8adaa51142b4daa565dff51756 Mon Sep 17 00:00:00 2001 From: Michael Brooks Date: Fri, 11 Apr 2025 11:42:45 -0700 Subject: [PATCH 12/13] refactor: update root.go use to ctx for OnInitialize and OnFinalize --- cmd/root.go | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index 44f42b32..c59cecbf 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -206,15 +206,17 @@ func Init() (*cobra.Command, *shared.ClientFactory) { // OnInitialize will execute before any root or child commands' Pre* methods. // This is a good place to house CLI bootup routines. cobra.OnInitialize(func() { - err := InitConfig(rootCmd.Context(), clients, rootCmd) + ctx := rootCmd.Context() + err := InitConfig(ctx, clients, rootCmd) if err != nil { - clients.IO.PrintError(rootCmd.Context(), err.Error()) + clients.IO.PrintError(ctx, err.Error()) clients.Os.Exit(int(iostreams.ExitError)) } }) // Since we use the *E cobra lifecycle methods, OnFinalize is one of the few ways we can ensure something _always_ runs at the end of any command invocation, regardless if an error is raised or not during execution. cobra.OnFinalize(func() { - cleanup(rootCmd.Context(), clients) + ctx := rootCmd.Context() + cleanup(ctx, clients) }) return rootCmd, clients } From 9f25031ad48e2dce8b57a0c1095b0c2400ba5e1e Mon Sep 17 00:00:00 2001 From: Michael Brooks Date: Mon, 14 Apr 2025 11:50:31 -0700 Subject: [PATCH 13/13] refactor: pass ctx into Init --- cmd/root.go | 4 +--- cmd/root_test.go | 21 ++++++++++++++------- main.go | 2 +- 3 files changed, 16 insertions(+), 11 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index c59cecbf..42fa9dc0 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -139,7 +139,7 @@ func NewRootCommand(clients *shared.ClientFactory, updateNotification *update.Up } // Init bootstraps the CLI process. Put things that do not rely on specific arguments or flags passed to the CLI in here. If you need flag/argument values, InitConfig below. -func Init() (*cobra.Command, *shared.ClientFactory) { +func Init(ctx context.Context) (*cobra.Command, *shared.ClientFactory) { // clients stores shared clients and configurations used across the commands and handlers var clients *shared.ClientFactory // updateNotification will check for an update in the background and print a message after the command runs @@ -206,7 +206,6 @@ func Init() (*cobra.Command, *shared.ClientFactory) { // OnInitialize will execute before any root or child commands' Pre* methods. // This is a good place to house CLI bootup routines. cobra.OnInitialize(func() { - ctx := rootCmd.Context() err := InitConfig(ctx, clients, rootCmd) if err != nil { clients.IO.PrintError(ctx, err.Error()) @@ -215,7 +214,6 @@ func Init() (*cobra.Command, *shared.ClientFactory) { }) // Since we use the *E cobra lifecycle methods, OnFinalize is one of the few ways we can ensure something _always_ runs at the end of any command invocation, regardless if an error is raised or not during execution. cobra.OnFinalize(func() { - ctx := rootCmd.Context() cleanup(ctx, clients) }) return rootCmd, clients diff --git a/cmd/root_test.go b/cmd/root_test.go index 065cb779..7c8936bb 100644 --- a/cmd/root_test.go +++ b/cmd/root_test.go @@ -15,6 +15,7 @@ package cmd import ( + "context" "fmt" "os" "strings" @@ -35,7 +36,7 @@ func TestRootCommand(t *testing.T) { defer os.RemoveAll(tmp) // Get command - cmd, _ := Init() + cmd, _ := Init(ctx) // Create mocks clientsMock := shared.NewClientsMock() @@ -77,6 +78,8 @@ func TestRootCommand(t *testing.T) { // FYI: do not try to run this test in vscode using the run/debug test inline test helper; as the assertions in this test will fail in that context func TestVersionFlags(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) + tmp, _ := os.MkdirTemp("", "") _ = os.Chdir(tmp) defer os.RemoveAll(tmp) @@ -84,7 +87,7 @@ func TestVersionFlags(t *testing.T) { var output string // Get command - cmd, _ := Init() + cmd, _ := Init(ctx) // Create mocks clientsMock := shared.NewClientsMock() @@ -110,12 +113,14 @@ func TestVersionFlags(t *testing.T) { } func Test_NewSuggestion(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) + tmp, _ := os.MkdirTemp("", "") _ = os.Chdir(tmp) defer os.RemoveAll(tmp) // Get command - cmd, clients := Init() + cmd, clients := Init(ctx) // Create mocks clientsMock := shared.NewClientsMock() @@ -131,11 +136,13 @@ func Test_NewSuggestion(t *testing.T) { } func Test_Aliases(t *testing.T) { + ctx := slackcontext.MockContext(t.Context()) + tmp, _ := os.MkdirTemp("", "") _ = os.Chdir(tmp) defer os.RemoveAll(tmp) - Init() + Init(ctx) tests := map[string]struct { args string @@ -176,7 +183,7 @@ func Test_Aliases(t *testing.T) { } for name, tt := range tests { t.Run(name, func(t *testing.T) { - err, output := testExecCmd(strings.Fields(tt.args)) + err, output := testExecCmd(ctx, strings.Fields(tt.args)) require.NoError(t, err) require.Contains(t, output, tt.expected) }) @@ -184,9 +191,9 @@ func Test_Aliases(t *testing.T) { } // testExecCmd will execute the root cobra command with args and return the output -func testExecCmd(args []string) (error, string) { +func testExecCmd(ctx context.Context, args []string) (error, string) { // Get command - cmd, clients := Init() + cmd, clients := Init(ctx) // Create mocks clientsMock := shared.NewClientsMock() diff --git a/main.go b/main.go index de3cf3ec..6eb884de 100644 --- a/main.go +++ b/main.go @@ -72,7 +72,7 @@ func main() { // add root span to context ctx = slackcontext.SetOpenTracingSpan(ctx, span) - rootCmd, clients := cmd.Init() + rootCmd, clients := cmd.Init(ctx) cmd.Execute(ctx, rootCmd, clients) }