diff --git a/AGENTS.md b/AGENTS.md index 7712214a51..11883156c8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -134,7 +134,7 @@ func TestApplySomeChangeReturnsDiagnostics(t *testing.T) { } func TestApplySomeChangeFixesThings(t *testing.T) { - ctx := context.Background() + ctx := t.Context() b, err := ...some operation... require.NoError(t, err) ... @@ -202,7 +202,7 @@ log.Errorf(ctx, "...") ``` Note that the 'ctx' variable here is something that should be passed in as -an argument by the caller. We should not use context.Background() like we do in tests. +an argument by the caller. In tests, use `t.Context()` (or `b.Context()` for benchmarks) instead of `context.Background()`. This is enforced by a lint rule. Use cmdio.LogString to print to stdout: diff --git a/acceptance/acceptance_test.go b/acceptance/acceptance_test.go index 4e0ecc38ab..b17ab98806 100644 --- a/acceptance/acceptance_test.go +++ b/acceptance/acceptance_test.go @@ -567,7 +567,7 @@ func runTest(t *testing.T, timeout = time.Duration(float64(timeout) * config.TimeoutCIMultiplier) } - ctx, cancelFunc := context.WithTimeout(context.Background(), timeout) + ctx, cancelFunc := context.WithTimeout(t.Context(), timeout) defer cancelFunc() args := []string{"bash", "-euo", "pipefail", EntryPointScript} cmd := exec.CommandContext(ctx, args[0], args[1:]...) diff --git a/acceptance/dbr_test.go b/acceptance/dbr_test.go index 1a439e1fa4..3fef59f65d 100644 --- a/acceptance/dbr_test.go +++ b/acceptance/dbr_test.go @@ -325,7 +325,7 @@ func runDbrTests(ctx context.Context, t *testing.T, w *databricks.WorkspaceClien // runDbrAcceptanceTests is the main entry point for running DBR acceptance tests. func runDbrAcceptanceTests(t *testing.T, config dbrTestConfig) { - ctx := context.Background() + ctx := t.Context() uniqueID := uuid.New().String() w, f, testDir := setupDbrTestDir(ctx, t, uniqueID) diff --git a/acceptance/internal/cmd_server.go b/acceptance/internal/cmd_server.go index 1d745af975..775dc12de7 100644 --- a/acceptance/internal/cmd_server.go +++ b/acceptance/internal/cmd_server.go @@ -1,7 +1,6 @@ package internal import ( - "context" "encoding/json" "os" "strings" @@ -27,7 +26,7 @@ func StartCmdServer(t *testing.T) *testserver.Server { // Change current working directory to match the callsite. defer chdir(t, q.Get("cwd"))() - c := testcli.NewRunner(t, context.Background(), args...) + c := testcli.NewRunner(t, t.Context(), args...) c.Verbose = false stdout, stderr, err := c.Run() result := map[string]any{ diff --git a/acceptance/internal/prepare_server.go b/acceptance/internal/prepare_server.go index 70983b88c6..996fedddca 100644 --- a/acceptance/internal/prepare_server.go +++ b/acceptance/internal/prepare_server.go @@ -1,7 +1,6 @@ package internal import ( - "context" "encoding/json" "fmt" "net/http" @@ -86,7 +85,7 @@ func PrepareServerAndClient(t *testing.T, config TestConfig, logRequests bool, o w, err := databricks.NewWorkspaceClient() require.NoError(t, err) - user, err := w.CurrentUser.Me(context.Background()) + user, err := w.CurrentUser.Me(t.Context()) require.NoError(t, err, "Failed to get current user") cfg := w.Config diff --git a/bundle/apps/validate_test.go b/bundle/apps/validate_test.go index a16b007be5..5e89de1f1d 100644 --- a/bundle/apps/validate_test.go +++ b/bundle/apps/validate_test.go @@ -1,7 +1,6 @@ package apps import ( - "context" "path/filepath" "testing" @@ -50,7 +49,7 @@ func TestAppsValidateSameSourcePath(t *testing.T) { bundletest.SetLocation(b, ".", []dyn.Location{{File: filepath.Join(tmpDir, "databricks.yml")}}) - diags := bundle.ApplySeq(context.Background(), b, mutator.TranslatePaths(), Validate()) + diags := bundle.ApplySeq(t.Context(), b, mutator.TranslatePaths(), Validate()) require.Len(t, diags, 1) require.Equal(t, "Duplicate app source code path", diags[0].Summary) require.Contains(t, diags[0].Detail, "has the same source code path as app resource") @@ -86,7 +85,7 @@ func TestAppsValidateBothSourceCodePathAndGitSource(t *testing.T) { bundletest.SetLocation(b, ".", []dyn.Location{{File: filepath.Join(tmpDir, "databricks.yml")}}) - diags := bundle.ApplySeq(context.Background(), b, mutator.TranslatePaths(), Validate()) + diags := bundle.ApplySeq(t.Context(), b, mutator.TranslatePaths(), Validate()) require.Len(t, diags, 1) require.Equal(t, "Both source_code_path and git_source fields are set", diags[0].Summary) require.Contains(t, diags[0].Detail, "should have either source_code_path or git_source field, not both") diff --git a/bundle/bundle_test.go b/bundle/bundle_test.go index 5b2aff58e0..45a088aa73 100644 --- a/bundle/bundle_test.go +++ b/bundle/bundle_test.go @@ -1,7 +1,6 @@ package bundle import ( - "context" "io/fs" "os" "path/filepath" @@ -22,7 +21,7 @@ import ( // mustLoad calls MustLoad and returns the bundle and collected diagnostics func mustLoad(t *testing.T) (*Bundle, []diag.Diagnostic) { - ctx := logdiag.InitContext(context.Background()) + ctx := logdiag.InitContext(t.Context()) logdiag.SetCollect(ctx, true) b := MustLoad(ctx) diags := logdiag.FlushCollected(ctx) @@ -31,7 +30,7 @@ func mustLoad(t *testing.T) (*Bundle, []diag.Diagnostic) { // tryLoad calls TryLoad and returns the bundle and collected diagnostics func tryLoad(t *testing.T) (*Bundle, []diag.Diagnostic) { - ctx := logdiag.InitContext(context.Background()) + ctx := logdiag.InitContext(t.Context()) logdiag.SetCollect(ctx, true) b := TryLoad(ctx) diags := logdiag.FlushCollected(ctx) @@ -39,19 +38,19 @@ func tryLoad(t *testing.T) (*Bundle, []diag.Diagnostic) { } func TestLoadNotExists(t *testing.T) { - b, err := Load(context.Background(), "/doesntexist") + b, err := Load(t.Context(), "/doesntexist") assert.ErrorIs(t, err, fs.ErrNotExist) assert.Nil(t, b) } func TestLoadExists(t *testing.T) { - b, err := Load(context.Background(), "./tests/basic") + b, err := Load(t.Context(), "./tests/basic") assert.NoError(t, err) assert.NotNil(t, b) } func TestBundleLocalStateDir(t *testing.T) { - ctx := context.Background() + ctx := t.Context() projectDir := t.TempDir() f1, err := os.Create(filepath.Join(projectDir, "databricks.yml")) require.NoError(t, err) @@ -75,7 +74,7 @@ func TestBundleLocalStateDir(t *testing.T) { } func TestBundleLocalStateDirOverride(t *testing.T) { - ctx := context.Background() + ctx := t.Context() projectDir := t.TempDir() bundleTmpDir := t.TempDir() f1, err := os.Create(filepath.Join(projectDir, "databricks.yml")) diff --git a/bundle/config/loader/entry_point_test.go b/bundle/config/loader/entry_point_test.go index 0723c056c5..b61d3f876a 100644 --- a/bundle/config/loader/entry_point_test.go +++ b/bundle/config/loader/entry_point_test.go @@ -1,7 +1,6 @@ package loader_test import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -12,7 +11,7 @@ import ( func TestEntryPointNoRootPath(t *testing.T) { b := &bundle.Bundle{} - diags := bundle.Apply(context.Background(), b, loader.EntryPoint()) + diags := bundle.Apply(t.Context(), b, loader.EntryPoint()) require.Error(t, diags.Error()) } @@ -20,7 +19,7 @@ func TestEntryPoint(t *testing.T) { b := &bundle.Bundle{ BundleRootPath: "testdata/basic", } - diags := bundle.Apply(context.Background(), b, loader.EntryPoint()) + diags := bundle.Apply(t.Context(), b, loader.EntryPoint()) require.NoError(t, diags.Error()) assert.Equal(t, "loader_test", b.Config.Bundle.Name) } diff --git a/bundle/config/loader/process_include_test.go b/bundle/config/loader/process_include_test.go index ca6aa25d22..c768dc57dc 100644 --- a/bundle/config/loader/process_include_test.go +++ b/bundle/config/loader/process_include_test.go @@ -1,7 +1,6 @@ package loader_test import ( - "context" "path/filepath" "testing" @@ -31,7 +30,7 @@ func TestProcessInclude(t *testing.T) { assert.Equal(t, "foo", b.Config.Workspace.Host) // Apply the mutator and assert that the host value has been updated - diags := bundle.Apply(context.Background(), b, m) + diags := bundle.Apply(t.Context(), b, m) require.NoError(t, diags.Error()) assert.Equal(t, "bar", b.Config.Workspace.Host) } @@ -55,7 +54,7 @@ func TestProcessIncludeFormatMatch(t *testing.T) { } m := loader.ProcessInclude(filepath.Join(b.BundleRootPath, fileName), fileName) - diags := bundle.Apply(context.Background(), b, m) + diags := bundle.Apply(t.Context(), b, m) assert.Empty(t, diags) }) } @@ -210,7 +209,7 @@ func TestProcessIncludeFormatNotMatch(t *testing.T) { } m := loader.ProcessInclude(filepath.Join(b.BundleRootPath, fileName), fileName) - diags := bundle.Apply(context.Background(), b, m) + diags := bundle.Apply(t.Context(), b, m) require.Len(t, diags, 1) assert.Equal(t, expectedDiags, diags) }) diff --git a/bundle/config/loader/process_root_includes_test.go b/bundle/config/loader/process_root_includes_test.go index da418dfcc3..cb98037507 100644 --- a/bundle/config/loader/process_root_includes_test.go +++ b/bundle/config/loader/process_root_includes_test.go @@ -1,7 +1,6 @@ package loader_test import ( - "context" "runtime" "testing" @@ -18,7 +17,7 @@ func TestProcessRootIncludesEmpty(t *testing.T) { b := &bundle.Bundle{ BundleRootPath: ".", } - diags := bundle.Apply(context.Background(), b, loader.ProcessRootIncludes()) + diags := bundle.Apply(t.Context(), b, loader.ProcessRootIncludes()) require.NoError(t, diags.Error()) } @@ -38,7 +37,7 @@ func TestProcessRootIncludesAbs(t *testing.T) { }, }, } - diags := bundle.Apply(context.Background(), b, loader.ProcessRootIncludes()) + diags := bundle.Apply(t.Context(), b, loader.ProcessRootIncludes()) require.True(t, diags.HasError()) assert.ErrorContains(t, diags.Error(), "must be relative paths") } @@ -57,7 +56,7 @@ func TestProcessRootIncludesSingleGlob(t *testing.T) { testutil.Touch(t, b.BundleRootPath, "a.yml") testutil.Touch(t, b.BundleRootPath, "b.yml") - diags := bundle.Apply(context.Background(), b, loader.ProcessRootIncludes()) + diags := bundle.Apply(t.Context(), b, loader.ProcessRootIncludes()) require.NoError(t, diags.Error()) assert.Equal(t, []string{"a.yml", "b.yml"}, b.Config.Include) } @@ -76,7 +75,7 @@ func TestProcessRootIncludesMultiGlob(t *testing.T) { testutil.Touch(t, b.BundleRootPath, "a1.yml") testutil.Touch(t, b.BundleRootPath, "b1.yml") - diags := bundle.Apply(context.Background(), b, loader.ProcessRootIncludes()) + diags := bundle.Apply(t.Context(), b, loader.ProcessRootIncludes()) require.NoError(t, diags.Error()) assert.Equal(t, []string{"a1.yml", "b1.yml"}, b.Config.Include) } @@ -94,7 +93,7 @@ func TestProcessRootIncludesRemoveDups(t *testing.T) { testutil.Touch(t, b.BundleRootPath, "a.yml") - diags := bundle.Apply(context.Background(), b, loader.ProcessRootIncludes()) + diags := bundle.Apply(t.Context(), b, loader.ProcessRootIncludes()) require.NoError(t, diags.Error()) assert.Equal(t, []string{"a.yml"}, b.Config.Include) } @@ -108,7 +107,7 @@ func TestProcessRootIncludesNotExists(t *testing.T) { }, }, } - diags := bundle.Apply(context.Background(), b, loader.ProcessRootIncludes()) + diags := bundle.Apply(t.Context(), b, loader.ProcessRootIncludes()) require.True(t, diags.HasError()) assert.ErrorContains(t, diags.Error(), "notexist.yml defined in 'include' section does not match any files") } @@ -172,7 +171,7 @@ func TestProcessRootIncludesGlobInRootPath(t *testing.T) { BundleRootPath: test.root, } - diags := bundle.Apply(context.Background(), b, loader.ProcessRootIncludes()) + diags := bundle.Apply(t.Context(), b, loader.ProcessRootIncludes()) require.True(t, diags.HasError()) assert.Len(t, diags, 1) assert.Equal(t, test.diag, diags[0]) diff --git a/bundle/config/mutator/apply_source_linked_deployment_preset_test.go b/bundle/config/mutator/apply_source_linked_deployment_preset_test.go index 84708f0387..c037107753 100644 --- a/bundle/config/mutator/apply_source_linked_deployment_preset_test.go +++ b/bundle/config/mutator/apply_source_linked_deployment_preset_test.go @@ -20,7 +20,7 @@ func TestApplyPresetsSourceLinkedDeployment(t *testing.T) { t.Skip("this test is not applicable on Windows because source-linked mode works only in the Databricks Workspace") } - testContext := context.Background() + testContext := t.Context() enabled := true disabled := false workspacePath := "/Workspace/user.name@company.com" diff --git a/bundle/config/mutator/compute_id_compate_test.go b/bundle/config/mutator/compute_id_compate_test.go index e59d37e39b..728bae4319 100644 --- a/bundle/config/mutator/compute_id_compate_test.go +++ b/bundle/config/mutator/compute_id_compate_test.go @@ -1,7 +1,6 @@ package mutator_test import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -20,7 +19,7 @@ func TestComputeIdToClusterId(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, mutator.ComputeIdToClusterId()) + diags := bundle.Apply(t.Context(), b, mutator.ComputeIdToClusterId()) assert.NoError(t, diags.Error()) assert.Equal(t, "compute-id", b.Config.Bundle.ClusterId) assert.Empty(t, b.Config.Bundle.ComputeId) @@ -41,11 +40,11 @@ func TestComputeIdToClusterIdInTargetOverride(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, mutator.ComputeIdToClusterId()) + diags := bundle.Apply(t.Context(), b, mutator.ComputeIdToClusterId()) assert.NoError(t, diags.Error()) assert.Empty(t, b.Config.Targets["dev"].ComputeId) - diags = diags.Extend(bundle.Apply(context.Background(), b, mutator.SelectTarget("dev"))) + diags = diags.Extend(bundle.Apply(t.Context(), b, mutator.SelectTarget("dev"))) assert.NoError(t, diags.Error()) assert.Equal(t, "compute-id-dev", b.Config.Bundle.ClusterId) diff --git a/bundle/config/mutator/configure_wsfs_test.go b/bundle/config/mutator/configure_wsfs_test.go index c7bbf21b6a..bf71faac26 100644 --- a/bundle/config/mutator/configure_wsfs_test.go +++ b/bundle/config/mutator/configure_wsfs_test.go @@ -1,7 +1,6 @@ package mutator_test import ( - "context" "reflect" "runtime" "testing" @@ -37,7 +36,7 @@ func TestConfigureWSFS_SkipsIfNotWorkspacePrefix(t *testing.T) { b := mockBundleForConfigureWSFS(t, "/foo") originalSyncRoot := b.SyncRoot - ctx := context.Background() + ctx := t.Context() diags := bundle.Apply(ctx, b, mutator.ConfigureWSFS()) assert.Empty(t, diags) assert.Equal(t, originalSyncRoot, b.SyncRoot) @@ -47,7 +46,7 @@ func TestConfigureWSFS_SkipsIfNotRunningOnRuntime(t *testing.T) { b := mockBundleForConfigureWSFS(t, "/Workspace/foo") originalSyncRoot := b.SyncRoot - ctx := context.Background() + ctx := t.Context() ctx = dbr.MockRuntime(ctx, dbr.Environment{}) diags := bundle.Apply(ctx, b, mutator.ConfigureWSFS()) assert.Empty(t, diags) @@ -91,7 +90,7 @@ func TestConfigureWSFS_DBRVersions(t *testing.T) { t.Run(tt.name, func(t *testing.T) { b := mockBundleForConfigureWSFS(t, "/Workspace/foo") - ctx := context.Background() + ctx := t.Context() ctx = dbr.MockRuntime(ctx, dbr.Environment{IsDbr: true, Version: tt.version}) diags := bundle.Apply(ctx, b, mutator.ConfigureWSFS()) assert.Empty(t, diags) diff --git a/bundle/config/mutator/default_target_test.go b/bundle/config/mutator/default_target_test.go index d60b14aad8..6474b81978 100644 --- a/bundle/config/mutator/default_target_test.go +++ b/bundle/config/mutator/default_target_test.go @@ -1,7 +1,6 @@ package mutator_test import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -13,7 +12,7 @@ import ( func TestDefaultTarget(t *testing.T) { b := &bundle.Bundle{} - diags := bundle.Apply(context.Background(), b, mutator.DefineDefaultTarget()) + diags := bundle.Apply(t.Context(), b, mutator.DefineDefaultTarget()) require.NoError(t, diags.Error()) env, ok := b.Config.Targets["default"] @@ -29,7 +28,7 @@ func TestDefaultTargetAlreadySpecified(t *testing.T) { }, }, } - diags := bundle.Apply(context.Background(), b, mutator.DefineDefaultTarget()) + diags := bundle.Apply(t.Context(), b, mutator.DefineDefaultTarget()) require.NoError(t, diags.Error()) _, ok := b.Config.Targets["default"] diff --git a/bundle/config/mutator/default_workspace_paths_test.go b/bundle/config/mutator/default_workspace_paths_test.go index 6779c37320..2994b12f29 100644 --- a/bundle/config/mutator/default_workspace_paths_test.go +++ b/bundle/config/mutator/default_workspace_paths_test.go @@ -1,7 +1,6 @@ package mutator_test import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -19,7 +18,7 @@ func TestDefineDefaultWorkspacePaths(t *testing.T) { }, }, } - diags := bundle.Apply(context.Background(), b, mutator.DefineDefaultWorkspacePaths()) + diags := bundle.Apply(t.Context(), b, mutator.DefineDefaultWorkspacePaths()) require.NoError(t, diags.Error()) assert.Equal(t, "/files", b.Config.Workspace.FilePath) assert.Equal(t, "/resources", b.Config.Workspace.ResourcePath) @@ -39,7 +38,7 @@ func TestDefineDefaultWorkspacePathsAlreadySet(t *testing.T) { }, }, } - diags := bundle.Apply(context.Background(), b, mutator.DefineDefaultWorkspacePaths()) + diags := bundle.Apply(t.Context(), b, mutator.DefineDefaultWorkspacePaths()) require.NoError(t, diags.Error()) assert.Equal(t, "/foo/bar", b.Config.Workspace.FilePath) assert.Equal(t, "/foo/bar", b.Config.Workspace.ResourcePath) diff --git a/bundle/config/mutator/default_workspace_root_test.go b/bundle/config/mutator/default_workspace_root_test.go index b05520f62d..ad5dac4e42 100644 --- a/bundle/config/mutator/default_workspace_root_test.go +++ b/bundle/config/mutator/default_workspace_root_test.go @@ -1,7 +1,6 @@ package mutator_test import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -20,7 +19,7 @@ func TestDefaultWorkspaceRoot(t *testing.T) { }, }, } - diags := bundle.Apply(context.Background(), b, mutator.DefineDefaultWorkspaceRoot()) + diags := bundle.Apply(t.Context(), b, mutator.DefineDefaultWorkspaceRoot()) require.NoError(t, diags.Error()) assert.Equal(t, "~/.bundle/name/environment", b.Config.Workspace.RootPath) diff --git a/bundle/config/mutator/environments_compat_test.go b/bundle/config/mutator/environments_compat_test.go index 11facf9fb2..0e7d4caa07 100644 --- a/bundle/config/mutator/environments_compat_test.go +++ b/bundle/config/mutator/environments_compat_test.go @@ -1,7 +1,6 @@ package mutator_test import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -27,7 +26,7 @@ func TestEnvironmentsToTargetsWithBothDefined(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, mutator.EnvironmentsToTargets()) + diags := bundle.Apply(t.Context(), b, mutator.EnvironmentsToTargets()) assert.ErrorContains(t, diags.Error(), `both 'environments' and 'targets' are specified;`) } @@ -42,7 +41,7 @@ func TestEnvironmentsToTargetsWithEnvironmentsDefined(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, mutator.EnvironmentsToTargets()) + diags := bundle.Apply(t.Context(), b, mutator.EnvironmentsToTargets()) require.NoError(t, diags.Error()) assert.Empty(t, b.Config.Environments) assert.Len(t, b.Config.Targets, 1) @@ -59,7 +58,7 @@ func TestEnvironmentsToTargetsWithTargetsDefined(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, mutator.EnvironmentsToTargets()) + diags := bundle.Apply(t.Context(), b, mutator.EnvironmentsToTargets()) require.NoError(t, diags.Error()) assert.Empty(t, b.Config.Environments) assert.Len(t, b.Config.Targets, 1) diff --git a/bundle/config/mutator/expand_workspace_root_test.go b/bundle/config/mutator/expand_workspace_root_test.go index 40bf35ca76..5a2a183321 100644 --- a/bundle/config/mutator/expand_workspace_root_test.go +++ b/bundle/config/mutator/expand_workspace_root_test.go @@ -1,7 +1,6 @@ package mutator_test import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -25,7 +24,7 @@ func TestExpandWorkspaceRoot(t *testing.T) { }, }, } - diags := bundle.Apply(context.Background(), b, mutator.ExpandWorkspaceRoot()) + diags := bundle.Apply(t.Context(), b, mutator.ExpandWorkspaceRoot()) require.NoError(t, diags.Error()) assert.Equal(t, "/Workspace/Users/jane@doe.com/foo", b.Config.Workspace.RootPath) } @@ -43,7 +42,7 @@ func TestExpandWorkspaceRootDoesNothing(t *testing.T) { }, }, } - diags := bundle.Apply(context.Background(), b, mutator.ExpandWorkspaceRoot()) + diags := bundle.Apply(t.Context(), b, mutator.ExpandWorkspaceRoot()) require.NoError(t, diags.Error()) assert.Equal(t, "/Users/charly@doe.com/foo", b.Config.Workspace.RootPath) } @@ -60,7 +59,7 @@ func TestExpandWorkspaceRootWithoutRoot(t *testing.T) { }, }, } - diags := bundle.Apply(context.Background(), b, mutator.ExpandWorkspaceRoot()) + diags := bundle.Apply(t.Context(), b, mutator.ExpandWorkspaceRoot()) require.True(t, diags.HasError()) } @@ -72,6 +71,6 @@ func TestExpandWorkspaceRootWithoutCurrentUser(t *testing.T) { }, }, } - diags := bundle.Apply(context.Background(), b, mutator.ExpandWorkspaceRoot()) + diags := bundle.Apply(t.Context(), b, mutator.ExpandWorkspaceRoot()) require.True(t, diags.HasError()) } diff --git a/bundle/config/mutator/initialize_cache_test.go b/bundle/config/mutator/initialize_cache_test.go index f6381fd906..f62c098923 100644 --- a/bundle/config/mutator/initialize_cache_test.go +++ b/bundle/config/mutator/initialize_cache_test.go @@ -1,7 +1,6 @@ package mutator_test import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -11,7 +10,7 @@ import ( ) func TestInitializeCache(t *testing.T) { - ctx := context.Background() + ctx := t.Context() b := &bundle.Bundle{} // Cache should be nil initially diff --git a/bundle/config/mutator/initialize_variables_test.go b/bundle/config/mutator/initialize_variables_test.go index 3ca4384fa2..53899baf61 100644 --- a/bundle/config/mutator/initialize_variables_test.go +++ b/bundle/config/mutator/initialize_variables_test.go @@ -1,7 +1,6 @@ package mutator_test import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -23,7 +22,7 @@ func TestInitializeVariables(t *testing.T) { }, }, } - diags := bundle.Apply(context.Background(), b, mutator.InitializeVariables()) + diags := bundle.Apply(t.Context(), b, mutator.InitializeVariables()) require.NoError(t, diags.Error()) assert.NotNil(t, b.Config.Variables["foo"]) assert.NotNil(t, b.Config.Variables["bar"]) @@ -36,7 +35,7 @@ func TestInitializeVariablesWithoutVariables(t *testing.T) { Variables: nil, }, } - diags := bundle.Apply(context.Background(), b, mutator.InitializeVariables()) + diags := bundle.Apply(t.Context(), b, mutator.InitializeVariables()) require.NoError(t, diags.Error()) assert.Nil(t, b.Config.Variables) } diff --git a/bundle/config/mutator/load_dbalert_files_test.go b/bundle/config/mutator/load_dbalert_files_test.go index 9e2c03ee91..a1f42c73c9 100644 --- a/bundle/config/mutator/load_dbalert_files_test.go +++ b/bundle/config/mutator/load_dbalert_files_test.go @@ -1,7 +1,6 @@ package mutator_test import ( - "context" "os" "path/filepath" "testing" @@ -73,7 +72,7 @@ func TestLoadDBAlertFiles(t *testing.T) { // Note: This test only verifies that the mutator doesn't error when a file_path is set. // The full functionality is tested in acceptance tests where the bundle is properly initialized. - diags := bundle.Apply(context.Background(), b, mutator.LoadDBAlertFiles()) + diags := bundle.Apply(t.Context(), b, mutator.LoadDBAlertFiles()) require.NoError(t, diags.Error()) assert.Equal(t, "Test Alert", b.Config.Resources.Alerts["my_alert"].DisplayName) diff --git a/bundle/config/mutator/log_resource_references_test.go b/bundle/config/mutator/log_resource_references_test.go index c22b50e9ca..af5100da99 100644 --- a/bundle/config/mutator/log_resource_references_test.go +++ b/bundle/config/mutator/log_resource_references_test.go @@ -1,7 +1,6 @@ package mutator import ( - "context" "testing" "github.com/databricks/cli/bundle/config" @@ -11,7 +10,7 @@ import ( ) func TestConvertReferenceToMetric_Table(t *testing.T) { - ctx := context.Background() + ctx := t.Context() cfg := config.Root{ Resources: config.Resources{ Jobs: map[string]*cres.Job{ diff --git a/bundle/config/mutator/normalize_paths_test.go b/bundle/config/mutator/normalize_paths_test.go index 75f2723dd4..8bee6c5064 100644 --- a/bundle/config/mutator/normalize_paths_test.go +++ b/bundle/config/mutator/normalize_paths_test.go @@ -1,7 +1,6 @@ package mutator import ( - "context" "path/filepath" "testing" @@ -46,7 +45,7 @@ func TestNormalizePaths(t *testing.T) { }) require.NoError(t, err) - diags := bundle.Apply(context.Background(), b, m) + diags := bundle.Apply(t.Context(), b, m) require.NoError(t, diags.Error()) newValue, err := dyn.GetByPath(b.Config.Value(), path) diff --git a/bundle/config/mutator/prepend_workspace_prefix_test.go b/bundle/config/mutator/prepend_workspace_prefix_test.go index d6741f8684..b4c3f4ddaa 100644 --- a/bundle/config/mutator/prepend_workspace_prefix_test.go +++ b/bundle/config/mutator/prepend_workspace_prefix_test.go @@ -1,7 +1,6 @@ package mutator import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -54,7 +53,7 @@ func TestPrependWorkspacePrefix(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, PrependWorkspacePrefix()) + diags := bundle.Apply(t.Context(), b, PrependWorkspacePrefix()) require.Empty(t, diags) require.Equal(t, tc.expected, b.Config.Workspace.RootPath) require.Equal(t, tc.expected, b.Config.Workspace.ArtifactPath) @@ -80,7 +79,7 @@ func TestPrependWorkspaceForDefaultConfig(t *testing.T) { }, }, } - diags := bundle.ApplySeq(context.Background(), b, DefineDefaultWorkspaceRoot(), ExpandWorkspaceRoot(), DefineDefaultWorkspacePaths(), PrependWorkspacePrefix()) + diags := bundle.ApplySeq(t.Context(), b, DefineDefaultWorkspaceRoot(), ExpandWorkspaceRoot(), DefineDefaultWorkspacePaths(), PrependWorkspacePrefix()) require.Empty(t, diags) require.Equal(t, "/Workspace/Users/jane@doe.com/.bundle/test/dev", b.Config.Workspace.RootPath) require.Equal(t, "/Workspace/Users/jane@doe.com/.bundle/test/dev/artifacts", b.Config.Workspace.ArtifactPath) diff --git a/bundle/config/mutator/python/python_mutator_test.go b/bundle/config/mutator/python/python_mutator_test.go index 285d1b3b87..effb7ad93a 100644 --- a/bundle/config/mutator/python/python_mutator_test.go +++ b/bundle/config/mutator/python/python_mutator_test.go @@ -280,7 +280,7 @@ resources: func TestPythonMutator_disabled(t *testing.T) { b := loadYaml("databricks.yml", ``) - ctx := context.Background() + ctx := t.Context() mutator := PythonMutator(PythonMutatorPhaseLoadResources) diag := bundle.Apply(ctx, b, mutator) @@ -298,7 +298,7 @@ experimental: - "resources:load_resources"`) mutator := PythonMutator(PythonMutatorPhaseLoadResources) - diag := bundle.Apply(context.Background(), b, mutator) + diag := bundle.Apply(t.Context(), b, mutator) assert.EqualError(t, diag.Error(), expectedError) } @@ -494,7 +494,7 @@ or activate the environment before running CLI commands: } func withProcessStub(t *testing.T, args []string, output, diagnostics, locations string) context.Context { - ctx := context.Background() + ctx := t.Context() ctx, stub := process.WithStub(ctx) t.Setenv(env.TempDirVariable, t.TempDir()) diff --git a/bundle/config/mutator/resolve_lookup_variables_test.go b/bundle/config/mutator/resolve_lookup_variables_test.go index 03b688a111..322d03e7d0 100644 --- a/bundle/config/mutator/resolve_lookup_variables_test.go +++ b/bundle/config/mutator/resolve_lookup_variables_test.go @@ -1,7 +1,6 @@ package mutator import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -52,7 +51,7 @@ func TestResolveClusterReference(t *testing.T) { {ClusterId: "9876-5432-xywz", ClusterName: clusterRef2}, }, nil) - diags := bundle.Apply(context.Background(), b, ResolveLookupVariables()) + diags := bundle.Apply(t.Context(), b, ResolveLookupVariables()) require.NoError(t, diags.Error()) require.Equal(t, "1234-5678-abcd", b.Config.Variables["my-cluster-id-1"].Value) require.Equal(t, "9876-5432-xywz", b.Config.Variables["my-cluster-id-2"].Value) @@ -87,7 +86,7 @@ func TestResolveNonExistentClusterReference(t *testing.T) { {ClusterId: "1234-5678-abcd", ClusterName: "some other cluster"}, }, nil) - diags := bundle.Apply(context.Background(), b, ResolveLookupVariables()) + diags := bundle.Apply(t.Context(), b, ResolveLookupVariables()) require.ErrorContains(t, diags.Error(), "failed to resolve cluster: Random, err: cluster named 'Random' does not exist") } @@ -111,7 +110,7 @@ func TestNoLookupIfVariableIsSet(t *testing.T) { err := b.Config.Variables["my-cluster-id"].Set("random value") require.NoError(t, err) - diags := bundle.Apply(context.Background(), b, ResolveLookupVariables()) + diags := bundle.Apply(t.Context(), b, ResolveLookupVariables()) require.NoError(t, diags.Error()) require.Equal(t, "random value", b.Config.Variables["my-cluster-id"].Value) } @@ -138,7 +137,7 @@ func TestResolveServicePrincipal(t *testing.T) { ApplicationId: "app-1234", }, nil) - diags := bundle.Apply(context.Background(), b, ResolveLookupVariables()) + diags := bundle.Apply(t.Context(), b, ResolveLookupVariables()) require.NoError(t, diags.Error()) require.Equal(t, "app-1234", b.Config.Variables["my-sp"].Value) } @@ -176,7 +175,7 @@ func TestResolveVariableReferencesInVariableLookups(t *testing.T) { {ClusterId: "9876-5432-xywz", ClusterName: "some other cluster"}, }, nil) - diags := bundle.ApplySeq(context.Background(), b, ResolveVariableReferencesInLookup(), ResolveLookupVariables()) + diags := bundle.ApplySeq(t.Context(), b, ResolveVariableReferencesInLookup(), ResolveLookupVariables()) require.NoError(t, diags.Error()) require.Equal(t, "cluster-bar-dev", b.Config.Variables["lookup"].Lookup.Cluster) require.Equal(t, "1234-5678-abcd", b.Config.Variables["lookup"].Value) @@ -203,7 +202,7 @@ func TestResolveLookupVariableReferencesInVariableLookups(t *testing.T) { m := mocks.NewMockWorkspaceClient(t) b.SetWorkpaceClient(m.WorkspaceClient) - diags := bundle.ApplySeq(context.Background(), b, ResolveVariableReferencesInLookup(), ResolveLookupVariables()) + diags := bundle.ApplySeq(t.Context(), b, ResolveVariableReferencesInLookup(), ResolveLookupVariables()) require.ErrorContains(t, diags.Error(), "lookup variables cannot contain references to another lookup variables") } @@ -226,7 +225,7 @@ func TestNoResolveLookupIfVariableSetWithEnvVariable(t *testing.T) { m := mocks.NewMockWorkspaceClient(t) b.SetWorkpaceClient(m.WorkspaceClient) - ctx := context.Background() + ctx := t.Context() ctx = env.Set(ctx, "BUNDLE_VAR_lookup", "1234-5678-abcd") diags := bundle.ApplySeq(ctx, b, SetVariables(), ResolveVariableReferencesInLookup(), ResolveLookupVariables()) diff --git a/bundle/config/mutator/resolve_variable_references_test.go b/bundle/config/mutator/resolve_variable_references_test.go index 6b390d7c73..876980e948 100644 --- a/bundle/config/mutator/resolve_variable_references_test.go +++ b/bundle/config/mutator/resolve_variable_references_test.go @@ -1,7 +1,6 @@ package mutator import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -59,7 +58,7 @@ func TestResolveVariableReferencesWithSourceLinkedDeployment(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, ResolveVariableReferencesOnlyResources("workspace")) + diags := bundle.Apply(t.Context(), b, ResolveVariableReferencesOnlyResources("workspace")) require.NoError(t, diags.Error()) testCase.assert(t, b) } diff --git a/bundle/config/mutator/resourcemutator/apply_bundle_permissions_test.go b/bundle/config/mutator/resourcemutator/apply_bundle_permissions_test.go index 9afe53fe1d..4923f84f22 100644 --- a/bundle/config/mutator/resourcemutator/apply_bundle_permissions_test.go +++ b/bundle/config/mutator/resourcemutator/apply_bundle_permissions_test.go @@ -1,7 +1,6 @@ package resourcemutator import ( - "context" "fmt" "slices" "testing" @@ -83,7 +82,7 @@ func TestApplyBundlePermissions(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, ApplyBundlePermissions()) + diags := bundle.Apply(t.Context(), b, ApplyBundlePermissions()) require.NoError(t, diags.Error()) require.Len(t, b.Config.Resources.Jobs["job_1"].Permissions, 3) @@ -174,7 +173,7 @@ func TestWarningOnOverlapPermission(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, ApplyBundlePermissions()) + diags := bundle.Apply(t.Context(), b, ApplyBundlePermissions()) require.NoError(t, diags.Error()) require.Contains(t, b.Config.Resources.Jobs["job_1"].Permissions, resources.JobPermission{Level: "CAN_VIEW", UserName: "TestUser"}) diff --git a/bundle/config/mutator/resourcemutator/apply_target_mode_test.go b/bundle/config/mutator/resourcemutator/apply_target_mode_test.go index d4e5123125..804552f56a 100644 --- a/bundle/config/mutator/resourcemutator/apply_target_mode_test.go +++ b/bundle/config/mutator/resourcemutator/apply_target_mode_test.go @@ -1,7 +1,6 @@ package resourcemutator import ( - "context" "reflect" "slices" "testing" @@ -260,7 +259,7 @@ func mockBundle(mode config.Mode) *bundle.Bundle { func TestProcessTargetModeDevelopment(t *testing.T) { b := mockBundle(config.Development) - diags := bundle.ApplySeq(context.Background(), b, ApplyTargetMode(), ApplyPresets()) + diags := bundle.ApplySeq(t.Context(), b, ApplyTargetMode(), ApplyPresets()) require.NoError(t, diags.Error()) // Job 1 @@ -332,7 +331,7 @@ func TestProcessTargetModeDevelopmentTagNormalizationForAws(t *testing.T) { }) b.Config.Workspace.CurrentUser.ShortName = "Héllö wörld?!" - diags := bundle.ApplySeq(context.Background(), b, ApplyTargetMode(), ApplyPresets()) + diags := bundle.ApplySeq(t.Context(), b, ApplyTargetMode(), ApplyPresets()) require.NoError(t, diags.Error()) // Assert that tag normalization took place. @@ -346,7 +345,7 @@ func TestProcessTargetModeDevelopmentTagNormalizationForAzure(t *testing.T) { }) b.Config.Workspace.CurrentUser.ShortName = "Héllö wörld?!" - diags := bundle.ApplySeq(context.Background(), b, ApplyTargetMode(), ApplyPresets()) + diags := bundle.ApplySeq(t.Context(), b, ApplyTargetMode(), ApplyPresets()) require.NoError(t, diags.Error()) // Assert that tag normalization took place (Azure allows more characters than AWS). @@ -360,7 +359,7 @@ func TestProcessTargetModeDevelopmentTagNormalizationForGcp(t *testing.T) { }) b.Config.Workspace.CurrentUser.ShortName = "Héllö wörld?!" - diags := bundle.ApplySeq(context.Background(), b, ApplyTargetMode(), ApplyPresets()) + diags := bundle.ApplySeq(t.Context(), b, ApplyTargetMode(), ApplyPresets()) require.NoError(t, diags.Error()) // Assert that tag normalization took place. @@ -370,7 +369,7 @@ func TestProcessTargetModeDevelopmentTagNormalizationForGcp(t *testing.T) { func TestProcessTargetModeDefault(t *testing.T) { b := mockBundle("") - diags := bundle.ApplySeq(context.Background(), b, ApplyTargetMode(), ApplyPresets()) + diags := bundle.ApplySeq(t.Context(), b, ApplyTargetMode(), ApplyPresets()) require.NoError(t, diags.Error()) assert.Equal(t, "job1", b.Config.Resources.Jobs["job1"].Name) assert.Equal(t, "pipeline1", b.Config.Resources.Pipelines["pipeline1"].Name) @@ -416,7 +415,7 @@ func TestAllNonUcResourcesAreRenamed(t *testing.T) { reflect.TypeOf(&resources.Volume{}), } - diags := bundle.ApplySeq(context.Background(), b, ApplyTargetMode(), ApplyPresets()) + diags := bundle.ApplySeq(t.Context(), b, ApplyTargetMode(), ApplyPresets()) require.NoError(t, diags.Error()) resources := reflect.ValueOf(b.Config.Resources) @@ -450,7 +449,7 @@ func TestAllNonUcResourcesAreRenamed(t *testing.T) { } func TestDisableLocking(t *testing.T) { - ctx := context.Background() + ctx := t.Context() b := mockBundle(config.Development) diags := bundle.ApplySeq(ctx, b, ApplyTargetMode()) @@ -460,7 +459,7 @@ func TestDisableLocking(t *testing.T) { } func TestDisableLockingDisabled(t *testing.T) { - ctx := context.Background() + ctx := t.Context() b := mockBundle(config.Development) explicitlyEnabled := true b.Config.Bundle.Deployment.Lock.Enabled = &explicitlyEnabled @@ -474,7 +473,7 @@ func TestPrefixAlreadySet(t *testing.T) { b := mockBundle(config.Development) b.Config.Presets.NamePrefix = "custom_lennart_deploy_" - diags := bundle.ApplySeq(context.Background(), b, ApplyTargetMode(), ApplyPresets()) + diags := bundle.ApplySeq(t.Context(), b, ApplyTargetMode(), ApplyPresets()) require.NoError(t, diags.Error()) assert.Equal(t, "custom_lennart_deploy_job1", b.Config.Resources.Jobs["job1"].Name) @@ -487,7 +486,7 @@ func TestTagsAlreadySet(t *testing.T) { "dev": "foo", } - diags := bundle.ApplySeq(context.Background(), b, ApplyTargetMode(), ApplyPresets()) + diags := bundle.ApplySeq(t.Context(), b, ApplyTargetMode(), ApplyPresets()) require.NoError(t, diags.Error()) assert.Equal(t, "tag", b.Config.Resources.Jobs["job1"].Tags["custom"]) @@ -498,7 +497,7 @@ func TestTagsNil(t *testing.T) { b := mockBundle(config.Development) b.Config.Presets.Tags = nil - diags := bundle.ApplySeq(context.Background(), b, ApplyTargetMode(), ApplyPresets()) + diags := bundle.ApplySeq(t.Context(), b, ApplyTargetMode(), ApplyPresets()) require.NoError(t, diags.Error()) assert.Equal(t, "lennart", b.Config.Resources.Jobs["job2"].Tags["dev"]) @@ -508,7 +507,7 @@ func TestTagsEmptySet(t *testing.T) { b := mockBundle(config.Development) b.Config.Presets.Tags = map[string]string{} - diags := bundle.ApplySeq(context.Background(), b, ApplyTargetMode(), ApplyPresets()) + diags := bundle.ApplySeq(t.Context(), b, ApplyTargetMode(), ApplyPresets()) require.NoError(t, diags.Error()) assert.Equal(t, "lennart", b.Config.Resources.Jobs["job2"].Tags["dev"]) @@ -518,7 +517,7 @@ func TestJobsMaxConcurrentRunsAlreadySet(t *testing.T) { b := mockBundle(config.Development) b.Config.Presets.JobsMaxConcurrentRuns = 10 - diags := bundle.ApplySeq(context.Background(), b, ApplyTargetMode(), ApplyPresets()) + diags := bundle.ApplySeq(t.Context(), b, ApplyTargetMode(), ApplyPresets()) require.NoError(t, diags.Error()) assert.Equal(t, 10, b.Config.Resources.Jobs["job1"].MaxConcurrentRuns) @@ -528,7 +527,7 @@ func TestJobsMaxConcurrentRunsDisabled(t *testing.T) { b := mockBundle(config.Development) b.Config.Presets.JobsMaxConcurrentRuns = 1 - diags := bundle.ApplySeq(context.Background(), b, ApplyTargetMode(), ApplyPresets()) + diags := bundle.ApplySeq(t.Context(), b, ApplyTargetMode(), ApplyPresets()) require.NoError(t, diags.Error()) assert.Equal(t, 1, b.Config.Resources.Jobs["job1"].MaxConcurrentRuns) @@ -539,7 +538,7 @@ func TestPipelinesDevelopmentDisabled(t *testing.T) { notEnabled := false b.Config.Presets.PipelinesDevelopment = ¬Enabled - diags := bundle.ApplySeq(context.Background(), b, ApplyTargetMode(), ApplyPresets()) + diags := bundle.ApplySeq(t.Context(), b, ApplyTargetMode(), ApplyPresets()) require.NoError(t, diags.Error()) assert.False(t, b.Config.Resources.Pipelines["pipeline1"].Development) diff --git a/bundle/config/mutator/resourcemutator/capture_schema_dependency_test.go b/bundle/config/mutator/resourcemutator/capture_schema_dependency_test.go index 8e37a9ba16..3993f45041 100644 --- a/bundle/config/mutator/resourcemutator/capture_schema_dependency_test.go +++ b/bundle/config/mutator/resourcemutator/capture_schema_dependency_test.go @@ -1,7 +1,6 @@ package resourcemutator import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -77,7 +76,7 @@ func TestCaptureSchemaDependencyForVolume(t *testing.T) { }, } - d := bundle.Apply(context.Background(), b, CaptureSchemaDependency()) + d := bundle.Apply(t.Context(), b, CaptureSchemaDependency()) require.Nil(t, d) assert.Equal(t, "${resources.schemas.schema1.name}", b.Config.Resources.Volumes["volume1"].SchemaName) @@ -167,7 +166,7 @@ func TestCaptureSchemaDependencyForPipelinesWithTarget(t *testing.T) { }, } - d := bundle.Apply(context.Background(), b, CaptureSchemaDependency()) + d := bundle.Apply(t.Context(), b, CaptureSchemaDependency()) require.Nil(t, d) assert.Equal(t, "${resources.schemas.schema1.name}", b.Config.Resources.Pipelines["pipeline1"].Schema) @@ -261,7 +260,7 @@ func TestCaptureSchemaDependencyForPipelinesWithSchema(t *testing.T) { }, } - d := bundle.Apply(context.Background(), b, CaptureSchemaDependency()) + d := bundle.Apply(t.Context(), b, CaptureSchemaDependency()) require.Nil(t, d) assert.Equal(t, "${resources.schemas.schema1.name}", b.Config.Resources.Pipelines["pipeline1"].Target) assert.Equal(t, "${resources.schemas.schema2.name}", b.Config.Resources.Pipelines["pipeline2"].Target) @@ -326,7 +325,7 @@ func TestCaptureCatalogDependencyForSchema(t *testing.T) { }, } - d := bundle.Apply(context.Background(), b, CaptureSchemaDependency()) + d := bundle.Apply(t.Context(), b, CaptureSchemaDependency()) require.Nil(t, d) assert.Equal(t, "${resources.catalogs.catalog1.name}", b.Config.Resources.Schemas["schema1"].CatalogName) diff --git a/bundle/config/mutator/resourcemutator/expand_pipeline_glob_paths_test.go b/bundle/config/mutator/resourcemutator/expand_pipeline_glob_paths_test.go index 08be39c2fd..56440f7cd1 100644 --- a/bundle/config/mutator/resourcemutator/expand_pipeline_glob_paths_test.go +++ b/bundle/config/mutator/resourcemutator/expand_pipeline_glob_paths_test.go @@ -1,7 +1,6 @@ package resourcemutator_test import ( - "context" "os" "path/filepath" "testing" @@ -114,7 +113,7 @@ func TestExpandGlobPathsInPipelines(t *testing.T) { bundletest.SetLocation(b, ".", []dyn.Location{{File: filepath.Join(dir, "resource.yml")}}) bundletest.SetLocation(b, "resources.pipelines.pipeline.libraries[3]", []dyn.Location{{File: filepath.Join(dir, "relative", "resource.yml")}}) - diags := bundle.ApplySeq(context.Background(), b, mutator.NormalizePaths(), resourcemutator.ExpandPipelineGlobPaths()) + diags := bundle.ApplySeq(t.Context(), b, mutator.NormalizePaths(), resourcemutator.ExpandPipelineGlobPaths()) require.NoError(t, diags.Error()) libraries := b.Config.Resources.Pipelines["pipeline"].Libraries diff --git a/bundle/config/mutator/resourcemutator/merge_apps_test.go b/bundle/config/mutator/resourcemutator/merge_apps_test.go index 3952889bd5..d207fc2d7b 100644 --- a/bundle/config/mutator/resourcemutator/merge_apps_test.go +++ b/bundle/config/mutator/resourcemutator/merge_apps_test.go @@ -1,7 +1,6 @@ package resourcemutator_test import ( - "context" "testing" "github.com/databricks/cli/bundle/config/mutator/resourcemutator" @@ -58,7 +57,7 @@ func TestMergeApps(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, resourcemutator.MergeApps()) + diags := bundle.Apply(t.Context(), b, resourcemutator.MergeApps()) assert.NoError(t, diags.Error()) j := b.Config.Resources.Apps["foo"] diff --git a/bundle/config/mutator/resourcemutator/merge_job_clusters_test.go b/bundle/config/mutator/resourcemutator/merge_job_clusters_test.go index 34ce08e9a5..56c5e5ee72 100644 --- a/bundle/config/mutator/resourcemutator/merge_job_clusters_test.go +++ b/bundle/config/mutator/resourcemutator/merge_job_clusters_test.go @@ -1,7 +1,6 @@ package resourcemutator_test import ( - "context" "testing" "github.com/databricks/cli/bundle/config/mutator/resourcemutator" @@ -51,7 +50,7 @@ func TestMergeJobClusters(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, resourcemutator.MergeJobClusters()) + diags := bundle.Apply(t.Context(), b, resourcemutator.MergeJobClusters()) assert.NoError(t, diags.Error()) j := b.Config.Resources.Jobs["foo"] @@ -100,7 +99,7 @@ func TestMergeJobClustersWithNilKey(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, resourcemutator.MergeJobClusters()) + diags := bundle.Apply(t.Context(), b, resourcemutator.MergeJobClusters()) assert.NoError(t, diags.Error()) assert.Len(t, b.Config.Resources.Jobs["foo"].JobClusters, 1) } diff --git a/bundle/config/mutator/resourcemutator/merge_job_parameters_test.go b/bundle/config/mutator/resourcemutator/merge_job_parameters_test.go index 45a3a90818..f616a2e880 100644 --- a/bundle/config/mutator/resourcemutator/merge_job_parameters_test.go +++ b/bundle/config/mutator/resourcemutator/merge_job_parameters_test.go @@ -1,7 +1,6 @@ package resourcemutator_test import ( - "context" "testing" "github.com/databricks/cli/bundle/config/mutator/resourcemutator" @@ -41,7 +40,7 @@ func TestMergeJobParameters(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, resourcemutator.MergeJobParameters()) + diags := bundle.Apply(t.Context(), b, resourcemutator.MergeJobParameters()) assert.NoError(t, diags.Error()) j := b.Config.Resources.Jobs["foo"] @@ -75,7 +74,7 @@ func TestMergeJobParametersWithNilKey(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, resourcemutator.MergeJobParameters()) + diags := bundle.Apply(t.Context(), b, resourcemutator.MergeJobParameters()) assert.NoError(t, diags.Error()) assert.Len(t, b.Config.Resources.Jobs["foo"].Parameters, 1) } diff --git a/bundle/config/mutator/resourcemutator/merge_job_tasks_test.go b/bundle/config/mutator/resourcemutator/merge_job_tasks_test.go index b52f927523..d54b2f17ed 100644 --- a/bundle/config/mutator/resourcemutator/merge_job_tasks_test.go +++ b/bundle/config/mutator/resourcemutator/merge_job_tasks_test.go @@ -1,7 +1,6 @@ package resourcemutator_test import ( - "context" "testing" "github.com/databricks/cli/bundle/config/mutator/resourcemutator" @@ -59,7 +58,7 @@ func TestMergeJobTasks(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, resourcemutator.MergeJobTasks()) + diags := bundle.Apply(t.Context(), b, resourcemutator.MergeJobTasks()) assert.NoError(t, diags.Error()) j := b.Config.Resources.Jobs["foo"] @@ -112,7 +111,7 @@ func TestMergeJobTasksWithNilKey(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, resourcemutator.MergeJobTasks()) + diags := bundle.Apply(t.Context(), b, resourcemutator.MergeJobTasks()) assert.NoError(t, diags.Error()) assert.Len(t, b.Config.Resources.Jobs["foo"].Tasks, 1) } diff --git a/bundle/config/mutator/resourcemutator/merge_pipeline_clusters_test.go b/bundle/config/mutator/resourcemutator/merge_pipeline_clusters_test.go index a07bee08d7..e27d174465 100644 --- a/bundle/config/mutator/resourcemutator/merge_pipeline_clusters_test.go +++ b/bundle/config/mutator/resourcemutator/merge_pipeline_clusters_test.go @@ -1,7 +1,6 @@ package resourcemutator_test import ( - "context" "strings" "testing" @@ -43,7 +42,7 @@ func TestMergePipelineClusters(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, resourcemutator.MergePipelineClusters()) + diags := bundle.Apply(t.Context(), b, resourcemutator.MergePipelineClusters()) assert.NoError(t, diags.Error()) p := b.Config.Resources.Pipelines["foo"] @@ -87,7 +86,7 @@ func TestMergePipelineClustersCaseInsensitive(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, resourcemutator.MergePipelineClusters()) + diags := bundle.Apply(t.Context(), b, resourcemutator.MergePipelineClusters()) assert.NoError(t, diags.Error()) p := b.Config.Resources.Pipelines["foo"] @@ -108,7 +107,7 @@ func TestMergePipelineClustersNilPipelines(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, resourcemutator.MergePipelineClusters()) + diags := bundle.Apply(t.Context(), b, resourcemutator.MergePipelineClusters()) assert.NoError(t, diags.Error()) } @@ -121,6 +120,6 @@ func TestMergePipelineClustersEmptyPipelines(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, resourcemutator.MergePipelineClusters()) + diags := bundle.Apply(t.Context(), b, resourcemutator.MergePipelineClusters()) assert.NoError(t, diags.Error()) } diff --git a/bundle/config/mutator/resourcemutator/override_compute_test.go b/bundle/config/mutator/resourcemutator/override_compute_test.go index ab04c36993..c56456d46a 100644 --- a/bundle/config/mutator/resourcemutator/override_compute_test.go +++ b/bundle/config/mutator/resourcemutator/override_compute_test.go @@ -1,7 +1,6 @@ package resourcemutator_test import ( - "context" "testing" "github.com/databricks/cli/bundle/config/mutator/resourcemutator" @@ -51,7 +50,7 @@ func TestOverrideComputeModeDevelopment(t *testing.T) { } m := resourcemutator.OverrideCompute() - diags := bundle.Apply(context.Background(), b, m) + diags := bundle.Apply(t.Context(), b, m) require.NoError(t, diags.Error()) assert.Nil(t, b.Config.Resources.Jobs["job1"].Tasks[0].NewCluster) assert.Equal(t, "newClusterID", b.Config.Resources.Jobs["job1"].Tasks[0].ExistingClusterId) @@ -90,7 +89,7 @@ func TestOverrideComputeModeDefaultIgnoresVariable(t *testing.T) { } m := resourcemutator.OverrideCompute() - diags := bundle.Apply(context.Background(), b, m) + diags := bundle.Apply(t.Context(), b, m) require.Len(t, diags, 1) assert.Equal(t, "The DATABRICKS_CLUSTER_ID variable is set but is ignored since the current target does not use 'mode: development'", diags[0].Summary) assert.Equal(t, "cluster2", b.Config.Resources.Jobs["job1"].Tasks[1].ExistingClusterId) @@ -116,7 +115,7 @@ func TestOverrideComputePipelineTask(t *testing.T) { } m := resourcemutator.OverrideCompute() - diags := bundle.Apply(context.Background(), b, m) + diags := bundle.Apply(t.Context(), b, m) require.NoError(t, diags.Error()) assert.Empty(t, b.Config.Resources.Jobs["job1"].Tasks[0].ExistingClusterId) } @@ -141,7 +140,7 @@ func TestOverrideComputeForEachTask(t *testing.T) { } m := resourcemutator.OverrideCompute() - diags := bundle.Apply(context.Background(), b, m) + diags := bundle.Apply(t.Context(), b, m) require.NoError(t, diags.Error()) assert.Empty(t, b.Config.Resources.Jobs["job1"].Tasks[0].ForEachTask.Task) } @@ -172,7 +171,7 @@ func TestOverrideComputeModeProduction(t *testing.T) { } m := resourcemutator.OverrideCompute() - diags := bundle.Apply(context.Background(), b, m) + diags := bundle.Apply(t.Context(), b, m) require.Len(t, diags, 1) assert.Equal(t, "Setting a cluster override for a target that uses 'mode: production' is not recommended", diags[0].Summary) assert.Equal(t, diag.Warning, diags[0].Severity) @@ -205,7 +204,7 @@ func TestOverrideComputeModeProductionIgnoresVariable(t *testing.T) { } m := resourcemutator.OverrideCompute() - diags := bundle.Apply(context.Background(), b, m) + diags := bundle.Apply(t.Context(), b, m) require.Len(t, diags, 1) assert.Equal(t, "The DATABRICKS_CLUSTER_ID variable is set but is ignored since the current target does not use 'mode: development'", diags[0].Summary) assert.Equal(t, "cluster2", b.Config.Resources.Jobs["job1"].Tasks[1].ExistingClusterId) diff --git a/bundle/config/mutator/resourcemutator/run_as_test.go b/bundle/config/mutator/resourcemutator/run_as_test.go index 7cc46bfe8c..9d59615201 100644 --- a/bundle/config/mutator/resourcemutator/run_as_test.go +++ b/bundle/config/mutator/resourcemutator/run_as_test.go @@ -1,7 +1,6 @@ package resourcemutator import ( - "context" "slices" "testing" @@ -119,7 +118,7 @@ func TestRunAsWorksForAllowedResources(t *testing.T) { Config: config, } - diags := bundle.Apply(context.Background(), b, SetRunAs()) + diags := bundle.Apply(t.Context(), b, SetRunAs()) assert.NoError(t, diags.Error()) for _, job := range b.Config.Resources.Jobs { @@ -229,7 +228,7 @@ func TestRunAsErrorForUnsupportedResources(t *testing.T) { b := &bundle.Bundle{ Config: *r, } - diags := bundle.Apply(context.Background(), b, SetRunAs()) + diags := bundle.Apply(t.Context(), b, SetRunAs()) require.Error(t, diags.Error()) assert.Contains(t, diags.Error().Error(), "do not support a setting a run_as user that is different from the owner.\n"+ "Current identity: alice. Run as identity: bob.\n"+ @@ -283,7 +282,7 @@ func TestRunAsNoErrorForSupportedResources(t *testing.T) { b := &bundle.Bundle{ Config: *r, } - diags := bundle.Apply(context.Background(), b, SetRunAs()) + diags := bundle.Apply(t.Context(), b, SetRunAs()) require.NoError(t, diags.Error()) } } diff --git a/bundle/config/mutator/resourcemutator/validate_target_mode_test.go b/bundle/config/mutator/resourcemutator/validate_target_mode_test.go index f65d585954..bf82773d9e 100644 --- a/bundle/config/mutator/resourcemutator/validate_target_mode_test.go +++ b/bundle/config/mutator/resourcemutator/validate_target_mode_test.go @@ -1,7 +1,6 @@ package resourcemutator import ( - "context" "testing" "github.com/databricks/cli/libs/diag" @@ -144,7 +143,7 @@ func TestTriggerPauseStatusWhenUnpaused(t *testing.T) { b := mockBundle(config.Development) b.Config.Presets.TriggerPauseStatus = config.Unpaused - diags := bundle.ApplySeq(context.Background(), b, ValidateTargetMode()) + diags := bundle.ApplySeq(t.Context(), b, ValidateTargetMode()) require.ErrorContains(t, diags.Error(), "target with 'mode: development' cannot set trigger pause status to UNPAUSED by default") } diff --git a/bundle/config/mutator/rewrite_sync_paths_test.go b/bundle/config/mutator/rewrite_sync_paths_test.go index 21570e09e2..2b9d291ddd 100644 --- a/bundle/config/mutator/rewrite_sync_paths_test.go +++ b/bundle/config/mutator/rewrite_sync_paths_test.go @@ -1,7 +1,6 @@ package mutator_test import ( - "context" "path/filepath" "testing" @@ -41,7 +40,7 @@ func TestRewriteSyncPathsRelative(t *testing.T) { bundletest.SetLocation(b, "sync.exclude[0]", []dyn.Location{{File: "./a/b/file.yml"}}) bundletest.SetLocation(b, "sync.exclude[1]", []dyn.Location{{File: "./a/b/c/file.yml"}}) - diags := bundle.Apply(context.Background(), b, mutator.RewriteSyncPaths()) + diags := bundle.Apply(t.Context(), b, mutator.RewriteSyncPaths()) assert.NoError(t, diags.Error()) assert.Equal(t, filepath.Clean("."), b.Config.Sync.Paths[0]) @@ -80,7 +79,7 @@ func TestRewriteSyncPathsAbsolute(t *testing.T) { bundletest.SetLocation(b, "sync.exclude[0]", []dyn.Location{{File: "/tmp/dir/a/b/file.yml"}}) bundletest.SetLocation(b, "sync.exclude[1]", []dyn.Location{{File: "/tmp/dir/a/b/c/file.yml"}}) - diags := bundle.Apply(context.Background(), b, mutator.RewriteSyncPaths()) + diags := bundle.Apply(t.Context(), b, mutator.RewriteSyncPaths()) assert.NoError(t, diags.Error()) assert.Equal(t, filepath.Clean("."), b.Config.Sync.Paths[0]) @@ -97,7 +96,7 @@ func TestRewriteSyncPathsErrorPaths(t *testing.T) { BundleRootPath: ".", } - diags := bundle.Apply(context.Background(), b, mutator.RewriteSyncPaths()) + diags := bundle.Apply(t.Context(), b, mutator.RewriteSyncPaths()) assert.NoError(t, diags.Error()) }) @@ -112,7 +111,7 @@ func TestRewriteSyncPathsErrorPaths(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, mutator.RewriteSyncPaths()) + diags := bundle.Apply(t.Context(), b, mutator.RewriteSyncPaths()) assert.NoError(t, diags.Error()) }) } diff --git a/bundle/config/mutator/rewrite_workspace_prefix_test.go b/bundle/config/mutator/rewrite_workspace_prefix_test.go index 28c801e43c..3a51b211bc 100644 --- a/bundle/config/mutator/rewrite_workspace_prefix_test.go +++ b/bundle/config/mutator/rewrite_workspace_prefix_test.go @@ -1,7 +1,6 @@ package mutator import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -61,7 +60,7 @@ func TestNoWorkspacePrefixUsed(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, RewriteWorkspacePrefix()) + diags := bundle.Apply(t.Context(), b, RewriteWorkspacePrefix()) require.Len(t, diags, 3) expectedErrors := map[string]bool{ diff --git a/bundle/config/mutator/select_default_target_test.go b/bundle/config/mutator/select_default_target_test.go index dfea4ff672..850bfd8854 100644 --- a/bundle/config/mutator/select_default_target_test.go +++ b/bundle/config/mutator/select_default_target_test.go @@ -1,7 +1,6 @@ package mutator_test import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -16,7 +15,7 @@ func TestSelectDefaultTargetNoTargets(t *testing.T) { Targets: map[string]*config.Target{}, }, } - diags := bundle.Apply(context.Background(), b, mutator.SelectDefaultTarget()) + diags := bundle.Apply(t.Context(), b, mutator.SelectDefaultTarget()) assert.ErrorContains(t, diags.Error(), "no targets defined") } @@ -28,7 +27,7 @@ func TestSelectDefaultTargetSingleTargets(t *testing.T) { }, }, } - diags := bundle.Apply(context.Background(), b, mutator.SelectDefaultTarget()) + diags := bundle.Apply(t.Context(), b, mutator.SelectDefaultTarget()) assert.NoError(t, diags.Error()) assert.Equal(t, "foo", b.Config.Bundle.Target) } @@ -43,7 +42,7 @@ func TestSelectDefaultTargetNoDefaults(t *testing.T) { }, }, } - diags := bundle.Apply(context.Background(), b, mutator.SelectDefaultTarget()) + diags := bundle.Apply(t.Context(), b, mutator.SelectDefaultTarget()) assert.ErrorContains(t, diags.Error(), "please specify target") } @@ -56,7 +55,7 @@ func TestSelectDefaultTargetNoDefaultsWithNil(t *testing.T) { }, }, } - diags := bundle.Apply(context.Background(), b, mutator.SelectDefaultTarget()) + diags := bundle.Apply(t.Context(), b, mutator.SelectDefaultTarget()) assert.ErrorContains(t, diags.Error(), "please specify target") } @@ -70,7 +69,7 @@ func TestSelectDefaultTargetMultipleDefaults(t *testing.T) { }, }, } - diags := bundle.Apply(context.Background(), b, mutator.SelectDefaultTarget()) + diags := bundle.Apply(t.Context(), b, mutator.SelectDefaultTarget()) assert.ErrorContains(t, diags.Error(), "multiple targets are marked as default") } @@ -84,7 +83,7 @@ func TestSelectDefaultTargetSingleDefault(t *testing.T) { }, }, } - diags := bundle.Apply(context.Background(), b, mutator.SelectDefaultTarget()) + diags := bundle.Apply(t.Context(), b, mutator.SelectDefaultTarget()) assert.NoError(t, diags.Error()) assert.Equal(t, "bar", b.Config.Bundle.Target) } diff --git a/bundle/config/mutator/select_target_test.go b/bundle/config/mutator/select_target_test.go index a7c5ac93c4..14cec05d9b 100644 --- a/bundle/config/mutator/select_target_test.go +++ b/bundle/config/mutator/select_target_test.go @@ -1,7 +1,6 @@ package mutator_test import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -26,7 +25,7 @@ func TestSelectTarget(t *testing.T) { }, }, } - diags := bundle.Apply(context.Background(), b, mutator.SelectTarget("default")) + diags := bundle.Apply(t.Context(), b, mutator.SelectTarget("default")) require.NoError(t, diags.Error()) assert.Equal(t, "bar", b.Config.Workspace.Host) } @@ -39,6 +38,6 @@ func TestSelectTargetNotFound(t *testing.T) { }, }, } - diags := bundle.Apply(context.Background(), b, mutator.SelectTarget("doesnt-exist")) + diags := bundle.Apply(t.Context(), b, mutator.SelectTarget("doesnt-exist")) require.Error(t, diags.Error(), "no targets defined") } diff --git a/bundle/config/mutator/set_variables_test.go b/bundle/config/mutator/set_variables_test.go index 4404f7c89e..e69bbf34c3 100644 --- a/bundle/config/mutator/set_variables_test.go +++ b/bundle/config/mutator/set_variables_test.go @@ -1,7 +1,6 @@ package mutator import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -25,7 +24,7 @@ func TestSetVariableFromProcessEnvVar(t *testing.T) { v, err := convert.FromTyped(variable, dyn.NilValue) require.NoError(t, err) - v, err = setVariable(context.Background(), v, &variable, "foo", dyn.NilValue) + v, err = setVariable(t.Context(), v, &variable, "foo", dyn.NilValue) require.NoError(t, err) err = convert.ToTyped(&variable, v) @@ -43,7 +42,7 @@ func TestSetVariableUsingDefaultValue(t *testing.T) { v, err := convert.FromTyped(variable, dyn.NilValue) require.NoError(t, err) - v, err = setVariable(context.Background(), v, &variable, "foo", dyn.NilValue) + v, err = setVariable(t.Context(), v, &variable, "foo", dyn.NilValue) require.NoError(t, err) err = convert.ToTyped(&variable, v) @@ -65,7 +64,7 @@ func TestSetVariableWhenAlreadyAValueIsAssigned(t *testing.T) { v, err := convert.FromTyped(variable, dyn.NilValue) require.NoError(t, err) - v, err = setVariable(context.Background(), v, &variable, "foo", dyn.NilValue) + v, err = setVariable(t.Context(), v, &variable, "foo", dyn.NilValue) require.NoError(t, err) err = convert.ToTyped(&variable, v) @@ -90,7 +89,7 @@ func TestSetVariableEnvVarValueDoesNotOverridePresetValue(t *testing.T) { v, err := convert.FromTyped(variable, dyn.NilValue) require.NoError(t, err) - v, err = setVariable(context.Background(), v, &variable, "foo", dyn.NilValue) + v, err = setVariable(t.Context(), v, &variable, "foo", dyn.NilValue) require.NoError(t, err) err = convert.ToTyped(&variable, v) @@ -107,7 +106,7 @@ func TestSetVariablesErrorsIfAValueCouldNotBeResolved(t *testing.T) { v, err := convert.FromTyped(variable, dyn.NilValue) require.NoError(t, err) - _, err = setVariable(context.Background(), v, &variable, "foo", dyn.NilValue) + _, err = setVariable(t.Context(), v, &variable, "foo", dyn.NilValue) assert.ErrorContains(t, err, "no value assigned to required variable foo. Variables are usually assigned in databricks.yml, and they can be overridden using \"--var\", the BUNDLE_VAR_foo environment variable, or .databricks/bundle//variable-overrides.json") } @@ -136,7 +135,7 @@ func TestSetVariablesMutator(t *testing.T) { t.Setenv("BUNDLE_VAR_b", "env-var-b") - diags := bundle.Apply(context.Background(), b, SetVariables()) + diags := bundle.Apply(t.Context(), b, SetVariables()) require.NoError(t, diags.Error()) assert.Equal(t, "default-a", b.Config.Variables["a"].Value) assert.Equal(t, "env-var-b", b.Config.Variables["b"].Value) @@ -157,6 +156,6 @@ func TestSetComplexVariablesViaEnvVariablesIsNotAllowed(t *testing.T) { v, err := convert.FromTyped(variable, dyn.NilValue) require.NoError(t, err) - _, err = setVariable(context.Background(), v, &variable, "foo", dyn.NilValue) + _, err = setVariable(t.Context(), v, &variable, "foo", dyn.NilValue) assert.ErrorContains(t, err, "setting via environment variables (BUNDLE_VAR_foo) is not supported for complex variable foo") } diff --git a/bundle/config/mutator/sync_default_path_test.go b/bundle/config/mutator/sync_default_path_test.go index a951ab63bf..c4bd6a65af 100644 --- a/bundle/config/mutator/sync_default_path_test.go +++ b/bundle/config/mutator/sync_default_path_test.go @@ -19,7 +19,7 @@ func TestSyncDefaultPath_DefaultIfUnset(t *testing.T) { Config: config.Root{}, } - ctx := context.Background() + ctx := t.Context() diags := bundle.Apply(ctx, b, mutator.SyncDefaultPath()) require.NoError(t, diags.Error()) assert.Equal(t, []string{"."}, b.Config.Sync.Paths) @@ -55,7 +55,7 @@ func TestSyncDefaultPath_SkipIfSet(t *testing.T) { Config: config.Root{}, } - ctx := logdiag.InitContext(context.Background()) + ctx := logdiag.InitContext(t.Context()) bundle.ApplyFuncContext(ctx, b, func(ctx context.Context, b *bundle.Bundle) { err := b.Config.Mutate(func(v dyn.Value) (dyn.Value, error) { diff --git a/bundle/config/mutator/sync_infer_root_test.go b/bundle/config/mutator/sync_infer_root_test.go index c3bd5eb855..c8f4a09c47 100644 --- a/bundle/config/mutator/sync_infer_root_test.go +++ b/bundle/config/mutator/sync_infer_root_test.go @@ -1,7 +1,6 @@ package mutator_test import ( - "context" "path/filepath" "testing" @@ -34,7 +33,7 @@ func TestSyncInferRoot_NominalAbsolute(t *testing.T) { }, } - ctx := context.Background() + ctx := t.Context() diags := bundle.Apply(ctx, b, mutator.SyncInferRoot()) assert.NoError(t, diags.Error()) assert.Equal(t, filepath.FromSlash("/tmp/some/dir"), b.SyncRootPath) @@ -65,7 +64,7 @@ func TestSyncInferRoot_NominalRelative(t *testing.T) { }, } - ctx := context.Background() + ctx := t.Context() diags := bundle.Apply(ctx, b, mutator.SyncInferRoot()) assert.NoError(t, diags.Error()) assert.Equal(t, filepath.FromSlash("some/dir"), b.SyncRootPath) @@ -96,7 +95,7 @@ func TestSyncInferRoot_ParentDirectory(t *testing.T) { }, } - ctx := context.Background() + ctx := t.Context() diags := bundle.Apply(ctx, b, mutator.SyncInferRoot()) assert.NoError(t, diags.Error()) assert.Equal(t, filepath.FromSlash("/tmp/some"), b.SyncRootPath) @@ -127,7 +126,7 @@ func TestSyncInferRoot_ManyParentDirectories(t *testing.T) { }, } - ctx := context.Background() + ctx := t.Context() diags := bundle.Apply(ctx, b, mutator.SyncInferRoot()) assert.NoError(t, diags.Error()) assert.Equal(t, filepath.FromSlash("/tmp/some"), b.SyncRootPath) @@ -159,7 +158,7 @@ func TestSyncInferRoot_MultiplePaths(t *testing.T) { }, } - ctx := context.Background() + ctx := t.Context() diags := bundle.Apply(ctx, b, mutator.SyncInferRoot()) assert.NoError(t, diags.Error()) assert.Equal(t, filepath.FromSlash("/tmp/some"), b.SyncRootPath) @@ -187,7 +186,7 @@ func TestSyncInferRoot_Error(t *testing.T) { bundletest.SetLocation(b, "sync.paths", []dyn.Location{{File: "databricks.yml"}}) - ctx := context.Background() + ctx := t.Context() diags := bundle.Apply(ctx, b, mutator.SyncInferRoot()) require.Len(t, diags, 2) assert.Equal(t, `invalid sync path "../../../../error"`, diags[0].Summary) diff --git a/bundle/config/mutator/translate_paths_apps_test.go b/bundle/config/mutator/translate_paths_apps_test.go index f1ade17970..331a1a8ab5 100644 --- a/bundle/config/mutator/translate_paths_apps_test.go +++ b/bundle/config/mutator/translate_paths_apps_test.go @@ -1,7 +1,6 @@ package mutator_test import ( - "context" "path/filepath" "testing" @@ -46,7 +45,7 @@ func TestTranslatePathsApps_FilePathRelativeSubDirectory(t *testing.T) { File: filepath.Join(dir, "resources/app.yml"), }}) - diags := bundle.ApplySeq(context.Background(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) + diags := bundle.ApplySeq(t.Context(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) require.NoError(t, diags.Error()) // Assert that the file path for the app has been converted to its local absolute path. diff --git a/bundle/config/mutator/translate_paths_artifacts_test.go b/bundle/config/mutator/translate_paths_artifacts_test.go index f59113eb9b..31f9a0ea4a 100644 --- a/bundle/config/mutator/translate_paths_artifacts_test.go +++ b/bundle/config/mutator/translate_paths_artifacts_test.go @@ -1,7 +1,6 @@ package mutator_test import ( - "context" "os" "path/filepath" "testing" @@ -43,7 +42,7 @@ func TestTranslatePathsArtifacts_InsideSyncRoot(t *testing.T) { File: filepath.Join(dir, "config/artifacts.yml"), }}) - diags := bundle.ApplySeq(context.Background(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) + diags := bundle.ApplySeq(t.Context(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) require.NoError(t, diags.Error()) // Assert that the artifact path has been converted to a local absolute path. @@ -77,7 +76,7 @@ func TestTranslatePathsArtifacts_OutsideSyncRoot(t *testing.T) { File: filepath.Join(dir, "config/artifacts.yml"), }}) - diags := bundle.ApplySeq(context.Background(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) + diags := bundle.ApplySeq(t.Context(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) require.NoError(t, diags.Error()) // Assert that the artifact path has been converted to a local absolute path. diff --git a/bundle/config/mutator/translate_paths_dashboards_test.go b/bundle/config/mutator/translate_paths_dashboards_test.go index bed217879f..8962579880 100644 --- a/bundle/config/mutator/translate_paths_dashboards_test.go +++ b/bundle/config/mutator/translate_paths_dashboards_test.go @@ -1,7 +1,6 @@ package mutator_test import ( - "context" "path/filepath" "testing" @@ -42,7 +41,7 @@ func TestTranslatePathsDashboards_FilePathRelativeSubDirectory(t *testing.T) { File: filepath.Join(dir, "resources/dashboard.yml"), }}) - diags := bundle.ApplySeq(context.Background(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) + diags := bundle.ApplySeq(t.Context(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) require.NoError(t, diags.Error()) // Assert that the file path for the dashboard has been converted to its local absolute path. diff --git a/bundle/config/mutator/translate_paths_test.go b/bundle/config/mutator/translate_paths_test.go index 299aa45046..3b7cc05b2d 100644 --- a/bundle/config/mutator/translate_paths_test.go +++ b/bundle/config/mutator/translate_paths_test.go @@ -86,7 +86,7 @@ func TestTranslatePathsSkippedWithGitSource(t *testing.T) { bundletest.SetLocation(b, ".", []dyn.Location{{File: filepath.Join(dir, "resource.yml")}}) - diags := bundle.ApplySeq(context.Background(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) + diags := bundle.ApplySeq(t.Context(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) require.NoError(t, diags.Error()) assert.Equal( @@ -215,7 +215,7 @@ func TestTranslatePaths(t *testing.T) { bundletest.SetLocation(b, ".", []dyn.Location{{File: filepath.Join(dir, "resource.yml")}}) - diags := bundle.ApplySeq(context.Background(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) + diags := bundle.ApplySeq(t.Context(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) require.NoError(t, diags.Error()) // Assert that the path in the tasks now refer to the artifact. @@ -353,7 +353,7 @@ func TestTranslatePathsInSubdirectories(t *testing.T) { bundletest.SetLocation(b, "resources.jobs", []dyn.Location{{File: filepath.Join(dir, "job/resource.yml")}}) bundletest.SetLocation(b, "resources.pipelines", []dyn.Location{{File: filepath.Join(dir, "pipeline/resource.yml")}}) - diags := bundle.ApplySeq(context.Background(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) + diags := bundle.ApplySeq(t.Context(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) require.NoError(t, diags.Error()) assert.Equal( @@ -415,7 +415,7 @@ func TestTranslatePathsOutsideSyncRoot(t *testing.T) { bundletest.SetLocation(b, ".", []dyn.Location{{File: filepath.Join(dir, "../resource.yml")}}) - diags := bundle.ApplySeq(context.Background(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) + diags := bundle.ApplySeq(t.Context(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) assert.ErrorContains(t, diags.Error(), "is not contained in sync root path") } @@ -447,7 +447,7 @@ func TestJobNotebookDoesNotExistError(t *testing.T) { bundletest.SetLocation(b, ".", []dyn.Location{{File: filepath.Join(dir, "fake.yml")}}) - diags := bundle.ApplySeq(context.Background(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) + diags := bundle.ApplySeq(t.Context(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) assert.EqualError(t, diags.Error(), "notebook doesnt_exist.py not found") } @@ -479,7 +479,7 @@ func TestJobFileDoesNotExistError(t *testing.T) { bundletest.SetLocation(b, ".", []dyn.Location{{File: filepath.Join(dir, "fake.yml")}}) - diags := bundle.ApplySeq(context.Background(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) + diags := bundle.ApplySeq(t.Context(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) assert.EqualError(t, diags.Error(), "file doesnt_exist.py not found") } @@ -511,7 +511,7 @@ func TestPipelineNotebookDoesNotExistError(t *testing.T) { bundletest.SetLocation(b, ".", []dyn.Location{{File: filepath.Join(dir, "fake.yml")}}) - diags := bundle.ApplySeq(context.Background(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) + diags := bundle.ApplySeq(t.Context(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) assert.EqualError(t, diags.Error(), "notebook doesnt_exist.py not found") } @@ -555,7 +555,7 @@ func TestPipelineNotebookDoesNotExistErrorWithoutExtension(t *testing.T) { } bundletest.SetLocation(b, ".", []dyn.Location{{File: filepath.Join(dir, "fake.yml")}}) - diags := bundle.ApplySeq(context.Background(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) + diags := bundle.ApplySeq(t.Context(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) if ext == "" { assert.EqualError(t, diags.Error(), `notebook "foo" not found. Local notebook references are expected @@ -597,7 +597,7 @@ func TestPipelineFileDoesNotExistError(t *testing.T) { bundletest.SetLocation(b, ".", []dyn.Location{{File: filepath.Join(dir, "fake.yml")}}) - diags := bundle.ApplySeq(context.Background(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) + diags := bundle.ApplySeq(t.Context(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) assert.EqualError(t, diags.Error(), "file doesnt_exist.py not found") } @@ -633,7 +633,7 @@ func TestJobSparkPythonTaskWithNotebookSourceError(t *testing.T) { bundletest.SetLocation(b, ".", []dyn.Location{{File: filepath.Join(dir, "resource.yml")}}) - diags := bundle.ApplySeq(context.Background(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) + diags := bundle.ApplySeq(t.Context(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) assert.ErrorContains(t, diags.Error(), `expected a file for "resources.jobs.job.tasks[0].spark_python_task.python_file" but got a notebook`) } @@ -669,7 +669,7 @@ func TestJobNotebookTaskWithFileSourceError(t *testing.T) { bundletest.SetLocation(b, ".", []dyn.Location{{File: filepath.Join(dir, "resource.yml")}}) - diags := bundle.ApplySeq(context.Background(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) + diags := bundle.ApplySeq(t.Context(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) assert.ErrorContains(t, diags.Error(), `expected a notebook for "resources.jobs.job.tasks[0].notebook_task.notebook_path" but got a file`) } @@ -705,7 +705,7 @@ func TestPipelineNotebookLibraryWithFileSourceError(t *testing.T) { bundletest.SetLocation(b, ".", []dyn.Location{{File: filepath.Join(dir, "resource.yml")}}) - diags := bundle.ApplySeq(context.Background(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) + diags := bundle.ApplySeq(t.Context(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) assert.ErrorContains(t, diags.Error(), `expected a notebook for "resources.pipelines.pipeline.libraries[0].notebook.path" but got a file`) } @@ -741,7 +741,7 @@ func TestPipelineFileLibraryWithNotebookSourceError(t *testing.T) { bundletest.SetLocation(b, ".", []dyn.Location{{File: filepath.Join(dir, "resource.yml")}}) - diags := bundle.ApplySeq(context.Background(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) + diags := bundle.ApplySeq(t.Context(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) assert.ErrorContains(t, diags.Error(), `expected a file for "resources.pipelines.pipeline.libraries[0].file.path" but got a notebook`) } @@ -783,7 +783,7 @@ func TestTranslatePathJobEnvironments(t *testing.T) { bundletest.SetLocation(b, "resources.jobs", []dyn.Location{{File: filepath.Join(dir, "job/resource.yml")}}) - diags := bundle.ApplySeq(context.Background(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) + diags := bundle.ApplySeq(t.Context(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) require.NoError(t, diags.Error()) assert.Equal(t, "./job/dist/env1.whl", b.Config.Resources.Jobs["job"].Environments[0].Spec.Dependencies[0]) @@ -831,7 +831,7 @@ func TestTranslatePathWithComplexVariables(t *testing.T) { bundletest.SetLocation(b, "variables", []dyn.Location{{File: filepath.Join(dir, "variables/variables.yml")}}) bundletest.SetLocation(b, "resources.jobs", []dyn.Location{{File: filepath.Join(dir, "job/resource.yml")}}) - ctx := context.Background() + ctx := t.Context() // Assign the variables to the dynamic configuration. bundle.ApplyFuncContext(ctx, b, func(ctx context.Context, b *bundle.Bundle) { err := b.Config.Mutate(func(v dyn.Value) (dyn.Value, error) { @@ -958,7 +958,7 @@ func TestTranslatePathsWithSourceLinkedDeployment(t *testing.T) { } bundletest.SetLocation(b, ".", []dyn.Location{{File: filepath.Join(dir, "resource.yml")}}) - diags := bundle.ApplySeq(context.Background(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) + diags := bundle.ApplySeq(t.Context(), b, mutator.NormalizePaths(), mutator.TranslatePaths()) require.NoError(t, diags.Error()) // updated to source path diff --git a/bundle/config/mutator/validate_git_details_test.go b/bundle/config/mutator/validate_git_details_test.go index 952e0b5721..b29f221edc 100644 --- a/bundle/config/mutator/validate_git_details_test.go +++ b/bundle/config/mutator/validate_git_details_test.go @@ -1,7 +1,6 @@ package mutator import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -22,7 +21,7 @@ func TestValidateGitDetailsMatchingBranches(t *testing.T) { } m := ValidateGitDetails() - diags := bundle.Apply(context.Background(), b, m) + diags := bundle.Apply(t.Context(), b, m) assert.NoError(t, diags.Error()) } @@ -39,7 +38,7 @@ func TestValidateGitDetailsNonMatchingBranches(t *testing.T) { } m := ValidateGitDetails() - diags := bundle.Apply(context.Background(), b, m) + diags := bundle.Apply(t.Context(), b, m) expectedError := "not on the right Git branch:\n expected according to configuration: main\n actual: feature\nuse --force to override" assert.EqualError(t, diags.Error(), expectedError) @@ -58,6 +57,6 @@ func TestValidateGitDetailsNotUsingGit(t *testing.T) { } m := ValidateGitDetails() - diags := bundle.Apply(context.Background(), b, m) + diags := bundle.Apply(t.Context(), b, m) assert.NoError(t, diags.Error()) } diff --git a/bundle/config/mutator/verify_cli_version_test.go b/bundle/config/mutator/verify_cli_version_test.go index 025461292b..b9f896a72b 100644 --- a/bundle/config/mutator/verify_cli_version_test.go +++ b/bundle/config/mutator/verify_cli_version_test.go @@ -1,7 +1,6 @@ package mutator import ( - "context" "fmt" "testing" @@ -132,7 +131,7 @@ func TestVerifyCliVersion(t *testing.T) { }, }, } - diags := bundle.Apply(context.Background(), b, VerifyCliVersion()) + diags := bundle.Apply(t.Context(), b, VerifyCliVersion()) if tc.expectedError != "" { require.NotEmpty(t, diags) require.Contains(t, diags[0].Summary, tc.expectedError) diff --git a/bundle/config/resources/external_location_test.go b/bundle/config/resources/external_location_test.go index 76f82736ad..01b792e048 100644 --- a/bundle/config/resources/external_location_test.go +++ b/bundle/config/resources/external_location_test.go @@ -1,7 +1,6 @@ package resources import ( - "context" "testing" "github.com/databricks/databricks-sdk-go/apierr" @@ -13,7 +12,7 @@ import ( ) func TestExternalLocationExists(t *testing.T) { - ctx := context.Background() + ctx := t.Context() m := mocks.NewMockWorkspaceClient(t) api := m.GetMockExternalLocationsAPI() diff --git a/bundle/config/resources/schema_test.go b/bundle/config/resources/schema_test.go index 73e7de77a4..bb3d313fb2 100644 --- a/bundle/config/resources/schema_test.go +++ b/bundle/config/resources/schema_test.go @@ -1,7 +1,6 @@ package resources import ( - "context" "fmt" "sort" "testing" @@ -15,7 +14,7 @@ import ( ) func TestSchemaNotFound(t *testing.T) { - ctx := context.Background() + ctx := t.Context() m := mocks.NewMockWorkspaceClient(t) m.GetMockSchemasAPI().On("GetByFullName", mock.Anything, "non-existent-schema").Return(nil, &apierr.APIError{ diff --git a/bundle/config/resources/volume_test.go b/bundle/config/resources/volume_test.go index 8efa1b0e16..ef44a2e61d 100644 --- a/bundle/config/resources/volume_test.go +++ b/bundle/config/resources/volume_test.go @@ -1,7 +1,6 @@ package resources import ( - "context" "testing" "github.com/databricks/databricks-sdk-go/apierr" @@ -11,7 +10,7 @@ import ( ) func TestVolumeNotFound(t *testing.T) { - ctx := context.Background() + ctx := t.Context() m := mocks.NewMockWorkspaceClient(t) m.GetMockVolumesAPI().On("Read", mock.Anything, mock.Anything).Return(nil, &apierr.APIError{ diff --git a/bundle/config/resources_test.go b/bundle/config/resources_test.go index b8dd140617..ddc90209e8 100644 --- a/bundle/config/resources_test.go +++ b/bundle/config/resources_test.go @@ -1,7 +1,6 @@ package config import ( - "context" "encoding/json" "reflect" "strings" @@ -245,7 +244,7 @@ func TestResourcesBindSupport(t *testing.T) { "model": true, } - ctx := context.Background() + ctx := t.Context() m := mocks.NewMockWorkspaceClient(t) m.GetMockJobsAPI().EXPECT().Get(mock.Anything, mock.Anything).Return(nil, nil) m.GetMockPipelinesAPI().EXPECT().Get(mock.Anything, mock.Anything).Return(nil, nil) diff --git a/bundle/config/validate/files_to_sync_test.go b/bundle/config/validate/files_to_sync_test.go index 0a5f69727b..1ee11bf7bc 100644 --- a/bundle/config/validate/files_to_sync_test.go +++ b/bundle/config/validate/files_to_sync_test.go @@ -1,7 +1,6 @@ package validate import ( - "context" "path/filepath" "testing" @@ -28,7 +27,7 @@ func TestFilesToSync_NoPaths(t *testing.T) { }, } - ctx := context.Background() + ctx := t.Context() diags := FilesToSync().Apply(ctx, b) assert.Empty(t, diags) } @@ -83,7 +82,7 @@ func TestFilesToSync_EverythingIgnored(t *testing.T) { // Ignore all files. testutil.WriteFile(t, filepath.Join(b.BundleRootPath, ".gitignore"), "*\n.*\n") - ctx := context.Background() + ctx := t.Context() diags := FilesToSync().Apply(ctx, b) require.Len(t, diags, 1) assert.Equal(t, diag.Warning, diags[0].Severity) @@ -96,7 +95,7 @@ func TestFilesToSync_EverythingExcluded(t *testing.T) { // Exclude all files. b.Config.Sync.Exclude = []string{"*"} - ctx := context.Background() + ctx := t.Context() diags := FilesToSync().Apply(ctx, b) require.Len(t, diags, 1) assert.Equal(t, diag.Warning, diags[0].Severity) diff --git a/bundle/config/validate/folder_permissions_test.go b/bundle/config/validate/folder_permissions_test.go index e41d731b3e..394ffee4e2 100644 --- a/bundle/config/validate/folder_permissions_test.go +++ b/bundle/config/validate/folder_permissions_test.go @@ -1,7 +1,6 @@ package validate import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -69,7 +68,7 @@ func TestFolderPermissionsInheritedWhenRootPathDoesNotExist(t *testing.T) { }, nil) b.SetWorkpaceClient(m.WorkspaceClient) - diags := ValidateFolderPermissions().Apply(context.Background(), b) + diags := ValidateFolderPermissions().Apply(t.Context(), b) require.Empty(t, diags) } @@ -116,7 +115,7 @@ func TestValidateFolderPermissionsFailsOnMissingBundlePermission(t *testing.T) { }, nil) b.SetWorkpaceClient(m.WorkspaceClient) - diags := ValidateFolderPermissions().Apply(context.Background(), b) + diags := ValidateFolderPermissions().Apply(t.Context(), b) require.Len(t, diags, 1) require.Equal(t, "workspace folder has permissions not configured in bundle", diags[0].Summary) require.Equal(t, diag.Warning, diags[0].Severity) @@ -164,7 +163,7 @@ func TestValidateFolderPermissionsFailsOnPermissionMismatch(t *testing.T) { }, nil) b.SetWorkpaceClient(m.WorkspaceClient) - diags := ValidateFolderPermissions().Apply(context.Background(), b) + diags := ValidateFolderPermissions().Apply(t.Context(), b) require.Len(t, diags, 1) require.Equal(t, "workspace folder has permissions not configured in bundle", diags[0].Summary) require.Equal(t, diag.Warning, diags[0].Severity) @@ -197,7 +196,7 @@ func TestValidateFolderPermissionsFailsOnNoRootFolder(t *testing.T) { }) b.SetWorkpaceClient(m.WorkspaceClient) - diags := ValidateFolderPermissions().Apply(context.Background(), b) + diags := ValidateFolderPermissions().Apply(t.Context(), b) require.Len(t, diags, 1) require.Equal(t, "folder / and its parent folders do not exist", diags[0].Summary) require.Equal(t, diag.Error, diags[0].Severity) diff --git a/bundle/config/validate/job_cluster_key_defined_test.go b/bundle/config/validate/job_cluster_key_defined_test.go index dbbc6c3b56..4cc35c1ad6 100644 --- a/bundle/config/validate/job_cluster_key_defined_test.go +++ b/bundle/config/validate/job_cluster_key_defined_test.go @@ -1,7 +1,6 @@ package validate import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -33,7 +32,7 @@ func TestJobClusterKeyDefined(t *testing.T) { }, } - diags := JobClusterKeyDefined().Apply(context.Background(), b) + diags := JobClusterKeyDefined().Apply(t.Context(), b) require.Empty(t, diags) require.NoError(t, diags.Error()) } @@ -56,7 +55,7 @@ func TestJobClusterKeyNotDefined(t *testing.T) { }, } - diags := JobClusterKeyDefined().Apply(context.Background(), b) + diags := JobClusterKeyDefined().Apply(t.Context(), b) require.Len(t, diags, 1) require.NoError(t, diags.Error()) require.Equal(t, diag.Warning, diags[0].Severity) @@ -89,7 +88,7 @@ func TestJobClusterKeyDefinedInDifferentJob(t *testing.T) { }, } - diags := JobClusterKeyDefined().Apply(context.Background(), b) + diags := JobClusterKeyDefined().Apply(t.Context(), b) require.Len(t, diags, 1) require.NoError(t, diags.Error()) require.Equal(t, diag.Warning, diags[0].Severity) diff --git a/bundle/config/validate/job_task_cluster_spec_test.go b/bundle/config/validate/job_task_cluster_spec_test.go index 40edef2167..3ba2e841a6 100644 --- a/bundle/config/validate/job_task_cluster_spec_test.go +++ b/bundle/config/validate/job_task_cluster_spec_test.go @@ -1,7 +1,6 @@ package validate import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -174,7 +173,7 @@ Specify one of the following fields: job_cluster_key, environment_key, existing_ } b := createBundle(map[string]*resources.Job{"job1": job}) - diags := JobTaskClusterSpec().Apply(context.Background(), b) + diags := JobTaskClusterSpec().Apply(t.Context(), b) if tc.errorPath != "" || tc.errorDetail != "" || tc.errorSummary != "" { assert.Len(t, diags, 1) diff --git a/bundle/config/validate/single_node_cluster_test.go b/bundle/config/validate/single_node_cluster_test.go index 02f27efcb6..bbda86f2ff 100644 --- a/bundle/config/validate/single_node_cluster_test.go +++ b/bundle/config/validate/single_node_cluster_test.go @@ -1,7 +1,6 @@ package validate import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -90,7 +89,7 @@ func failCases() []struct { } func TestValidateSingleNodeClusterFailForInteractiveClusters(t *testing.T) { - ctx := context.Background() + ctx := t.Context() for _, tc := range failCases() { t.Run(tc.name, func(t *testing.T) { @@ -131,7 +130,7 @@ func TestValidateSingleNodeClusterFailForInteractiveClusters(t *testing.T) { } func TestValidateSingleNodeClusterFailForJobClusters(t *testing.T) { - ctx := context.Background() + ctx := t.Context() for _, tc := range failCases() { t.Run(tc.name, func(t *testing.T) { @@ -180,7 +179,7 @@ func TestValidateSingleNodeClusterFailForJobClusters(t *testing.T) { } func TestValidateSingleNodeClusterFailForJobTaskClusters(t *testing.T) { - ctx := context.Background() + ctx := t.Context() for _, tc := range failCases() { t.Run(tc.name, func(t *testing.T) { @@ -229,7 +228,7 @@ func TestValidateSingleNodeClusterFailForJobTaskClusters(t *testing.T) { } func TestValidateSingleNodeClusterFailForPipelineClusters(t *testing.T) { - ctx := context.Background() + ctx := t.Context() for _, tc := range failCases() { t.Run(tc.name, func(t *testing.T) { @@ -275,7 +274,7 @@ func TestValidateSingleNodeClusterFailForPipelineClusters(t *testing.T) { } func TestValidateSingleNodeClusterFailForJobForEachTaskCluster(t *testing.T) { - ctx := context.Background() + ctx := t.Context() for _, tc := range failCases() { t.Run(tc.name, func(t *testing.T) { @@ -371,7 +370,7 @@ func passCases() []struct { } func TestValidateSingleNodeClusterPassInteractiveClusters(t *testing.T) { - ctx := context.Background() + ctx := t.Context() for _, tc := range passCases() { t.Run(tc.name, func(t *testing.T) { @@ -404,7 +403,7 @@ func TestValidateSingleNodeClusterPassInteractiveClusters(t *testing.T) { } func TestValidateSingleNodeClusterPassJobClusters(t *testing.T) { - ctx := context.Background() + ctx := t.Context() for _, tc := range passCases() { t.Run(tc.name, func(t *testing.T) { @@ -444,7 +443,7 @@ func TestValidateSingleNodeClusterPassJobClusters(t *testing.T) { } func TestValidateSingleNodeClusterPassJobTaskClusters(t *testing.T) { - ctx := context.Background() + ctx := t.Context() for _, tc := range passCases() { t.Run(tc.name, func(t *testing.T) { @@ -484,7 +483,7 @@ func TestValidateSingleNodeClusterPassJobTaskClusters(t *testing.T) { } func TestValidateSingleNodeClusterPassPipelineClusters(t *testing.T) { - ctx := context.Background() + ctx := t.Context() for _, tc := range passCases() { t.Run(tc.name, func(t *testing.T) { @@ -521,7 +520,7 @@ func TestValidateSingleNodeClusterPassPipelineClusters(t *testing.T) { } func TestValidateSingleNodeClusterPassJobForEachTaskCluster(t *testing.T) { - ctx := context.Background() + ctx := t.Context() for _, tc := range passCases() { t.Run(tc.name, func(t *testing.T) { @@ -565,7 +564,7 @@ func TestValidateSingleNodeClusterPassJobForEachTaskCluster(t *testing.T) { } func TestValidateSingleNodeClusterWithIsSingleNode(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // Test that when is_single_node is set to true, no warning is shown // even if the manual single-node configuration is not present. diff --git a/bundle/config/validate/validate_artifact_path_test.go b/bundle/config/validate/validate_artifact_path_test.go index 103380cb8f..08f50e39fb 100644 --- a/bundle/config/validate/validate_artifact_path_test.go +++ b/bundle/config/validate/validate_artifact_path_test.go @@ -1,7 +1,6 @@ package validate import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -41,7 +40,7 @@ func TestValidateArtifactPathWithVolumeInBundle(t *testing.T) { bundletest.SetLocation(b, "workspace.artifact_path", []dyn.Location{{File: "file", Line: 1, Column: 1}}) bundletest.SetLocation(b, "resources.volumes.foo", []dyn.Location{{File: "file", Line: 2, Column: 2}}) - ctx := context.Background() + ctx := t.Context() m := mocks.NewMockWorkspaceClient(t) api := m.GetMockVolumesAPI() api.EXPECT().ReadByName(mock.Anything, "catalogN.schemaN.volumeN").Return(nil, &apierr.APIError{ @@ -88,7 +87,7 @@ func TestValidateArtifactPath(t *testing.T) { }}, diags) } - ctx := context.Background() + ctx := t.Context() tcases := []struct { err error @@ -166,7 +165,7 @@ func TestValidateArtifactPathWithInvalidPaths(t *testing.T) { bundletest.SetLocation(b, "workspace.artifact_path", []dyn.Location{{File: "config.yml", Line: 1, Column: 2}}) - diags := ValidateArtifactPath().Apply(context.Background(), b) + diags := ValidateArtifactPath().Apply(t.Context(), b) require.Equal(t, diag.Diagnostics{{ Severity: diag.Error, Summary: "expected UC volume path to be in the format /Volumes////..., got " + p, diff --git a/bundle/config/variable/lookup_test.go b/bundle/config/variable/lookup_test.go index bcfcb46264..374338349f 100644 --- a/bundle/config/variable/lookup_test.go +++ b/bundle/config/variable/lookup_test.go @@ -1,7 +1,6 @@ package variable import ( - "context" "reflect" "testing" @@ -37,7 +36,7 @@ func TestLookup_Empty(t *testing.T) { var lookup Lookup // Resolve returns an error when no fields are provided - _, err := lookup.Resolve(context.Background(), nil) + _, err := lookup.Resolve(t.Context(), nil) assert.ErrorContains(t, err, "no valid lookup fields provided") // No string representation for an invalid lookup @@ -51,7 +50,7 @@ func TestLookup_Multiple(t *testing.T) { } // Resolve returns an error when multiple fields are provided - _, err := lookup.Resolve(context.Background(), nil) + _, err := lookup.Resolve(t.Context(), nil) assert.ErrorContains(t, err, "exactly one lookup field must be provided") // No string representation for an invalid lookup diff --git a/bundle/config/variable/resolve_alert_test.go b/bundle/config/variable/resolve_alert_test.go index 32f8d641bd..68fd38f08d 100644 --- a/bundle/config/variable/resolve_alert_test.go +++ b/bundle/config/variable/resolve_alert_test.go @@ -1,7 +1,6 @@ package variable import ( - "context" "testing" "github.com/databricks/databricks-sdk-go/apierr" @@ -22,7 +21,7 @@ func TestResolveAlert_ResolveSuccess(t *testing.T) { Id: "1234", }, nil) - ctx := context.Background() + ctx := t.Context() l := resolveAlert{name: "alert"} result, err := l.Resolve(ctx, m.WorkspaceClient) require.NoError(t, err) @@ -37,7 +36,7 @@ func TestResolveAlert_ResolveNotFound(t *testing.T) { GetByDisplayName(mock.Anything, "alert"). Return(nil, &apierr.APIError{StatusCode: 404}) - ctx := context.Background() + ctx := t.Context() l := resolveAlert{name: "alert"} _, err := l.Resolve(ctx, m.WorkspaceClient) require.ErrorIs(t, err, apierr.ErrNotFound) diff --git a/bundle/config/variable/resolve_cluster_policy_test.go b/bundle/config/variable/resolve_cluster_policy_test.go index fb17fad180..574c9b5c59 100644 --- a/bundle/config/variable/resolve_cluster_policy_test.go +++ b/bundle/config/variable/resolve_cluster_policy_test.go @@ -1,7 +1,6 @@ package variable import ( - "context" "testing" "github.com/databricks/databricks-sdk-go/apierr" @@ -22,7 +21,7 @@ func TestResolveClusterPolicy_ResolveSuccess(t *testing.T) { PolicyId: "1234", }, nil) - ctx := context.Background() + ctx := t.Context() l := resolveClusterPolicy{name: "policy"} result, err := l.Resolve(ctx, m.WorkspaceClient) require.NoError(t, err) @@ -37,7 +36,7 @@ func TestResolveClusterPolicy_ResolveNotFound(t *testing.T) { GetByName(mock.Anything, "policy"). Return(nil, &apierr.APIError{StatusCode: 404}) - ctx := context.Background() + ctx := t.Context() l := resolveClusterPolicy{name: "policy"} _, err := l.Resolve(ctx, m.WorkspaceClient) require.ErrorIs(t, err, apierr.ErrNotFound) diff --git a/bundle/config/variable/resolve_cluster_test.go b/bundle/config/variable/resolve_cluster_test.go index 2f3aa27cfd..c99a090fba 100644 --- a/bundle/config/variable/resolve_cluster_test.go +++ b/bundle/config/variable/resolve_cluster_test.go @@ -1,7 +1,6 @@ package variable import ( - "context" "testing" "github.com/databricks/databricks-sdk-go/experimental/mocks" @@ -22,7 +21,7 @@ func TestResolveCluster_ResolveSuccess(t *testing.T) { {ClusterId: "2345", ClusterName: "cluster2"}, }, nil) - ctx := context.Background() + ctx := t.Context() l := resolveCluster{name: "cluster2"} result, err := l.Resolve(ctx, m.WorkspaceClient) require.NoError(t, err) @@ -37,7 +36,7 @@ func TestResolveCluster_ResolveNotFound(t *testing.T) { ListAll(mock.Anything, mock.Anything). Return([]compute.ClusterDetails{}, nil) - ctx := context.Background() + ctx := t.Context() l := resolveCluster{name: "cluster"} _, err := l.Resolve(ctx, m.WorkspaceClient) require.Error(t, err) diff --git a/bundle/config/variable/resolve_dashboard_test.go b/bundle/config/variable/resolve_dashboard_test.go index f882e716be..32c3a22473 100644 --- a/bundle/config/variable/resolve_dashboard_test.go +++ b/bundle/config/variable/resolve_dashboard_test.go @@ -1,7 +1,6 @@ package variable import ( - "context" "testing" "github.com/databricks/databricks-sdk-go/experimental/mocks" @@ -22,7 +21,7 @@ func TestResolveDashboard_ResolveSuccess(t *testing.T) { {Id: "5678", Name: "dashboard2"}, }, nil) - ctx := context.Background() + ctx := t.Context() l := resolveDashboard{name: "dashboard"} result, err := l.Resolve(ctx, m.WorkspaceClient) require.NoError(t, err) @@ -40,7 +39,7 @@ func TestResolveDashboard_ResolveNotFound(t *testing.T) { {Id: "5678", Name: "dashboard2"}, }, nil) - ctx := context.Background() + ctx := t.Context() l := resolveDashboard{name: "dashboard"} _, err := l.Resolve(ctx, m.WorkspaceClient) require.ErrorContains(t, err, "dashboard name 'dashboard' does not exist") diff --git a/bundle/config/variable/resolve_instance_pool_test.go b/bundle/config/variable/resolve_instance_pool_test.go index cfd1ba0154..0cf235f500 100644 --- a/bundle/config/variable/resolve_instance_pool_test.go +++ b/bundle/config/variable/resolve_instance_pool_test.go @@ -1,7 +1,6 @@ package variable import ( - "context" "testing" "github.com/databricks/databricks-sdk-go/apierr" @@ -22,7 +21,7 @@ func TestResolveInstancePool_ResolveSuccess(t *testing.T) { InstancePoolId: "5678", }, nil) - ctx := context.Background() + ctx := t.Context() l := resolveInstancePool{name: "instance_pool"} result, err := l.Resolve(ctx, m.WorkspaceClient) require.NoError(t, err) @@ -37,7 +36,7 @@ func TestResolveInstancePool_ResolveNotFound(t *testing.T) { GetByInstancePoolName(mock.Anything, "instance_pool"). Return(nil, &apierr.APIError{StatusCode: 404}) - ctx := context.Background() + ctx := t.Context() l := resolveInstancePool{name: "instance_pool"} _, err := l.Resolve(ctx, m.WorkspaceClient) require.ErrorIs(t, err, apierr.ErrNotFound) diff --git a/bundle/config/variable/resolve_job_test.go b/bundle/config/variable/resolve_job_test.go index 523d07957b..375d62e783 100644 --- a/bundle/config/variable/resolve_job_test.go +++ b/bundle/config/variable/resolve_job_test.go @@ -1,7 +1,6 @@ package variable import ( - "context" "testing" "github.com/databricks/databricks-sdk-go/apierr" @@ -22,7 +21,7 @@ func TestResolveJob_ResolveSuccess(t *testing.T) { JobId: 5678, }, nil) - ctx := context.Background() + ctx := t.Context() l := resolveJob{name: "job"} result, err := l.Resolve(ctx, m.WorkspaceClient) require.NoError(t, err) @@ -37,7 +36,7 @@ func TestResolveJob_ResolveNotFound(t *testing.T) { GetBySettingsName(mock.Anything, "job"). Return(nil, &apierr.APIError{StatusCode: 404}) - ctx := context.Background() + ctx := t.Context() l := resolveJob{name: "job"} _, err := l.Resolve(ctx, m.WorkspaceClient) require.ErrorIs(t, err, apierr.ErrNotFound) diff --git a/bundle/config/variable/resolve_metastore_test.go b/bundle/config/variable/resolve_metastore_test.go index 05c8929866..759d394278 100644 --- a/bundle/config/variable/resolve_metastore_test.go +++ b/bundle/config/variable/resolve_metastore_test.go @@ -1,7 +1,6 @@ package variable import ( - "context" "testing" "github.com/databricks/databricks-sdk-go/experimental/mocks" @@ -21,7 +20,7 @@ func TestResolveMetastore_ResolveSuccess(t *testing.T) { {MetastoreId: "abcd", Name: "metastore"}, }, nil) - ctx := context.Background() + ctx := t.Context() l := resolveMetastore{name: "metastore"} result, err := l.Resolve(ctx, m.WorkspaceClient) require.NoError(t, err) @@ -38,7 +37,7 @@ func TestResolveMetastore_ResolveNotFound(t *testing.T) { {MetastoreId: "abcd", Name: "different"}, }, nil) - ctx := context.Background() + ctx := t.Context() l := resolveMetastore{name: "metastore"} _, err := l.Resolve(ctx, m.WorkspaceClient) require.ErrorContains(t, err, "metastore named \"metastore\" does not exist") @@ -55,7 +54,7 @@ func TestResolveMetastore_ResolveMultiple(t *testing.T) { {MetastoreId: "efgh", Name: "metastore"}, }, nil) - ctx := context.Background() + ctx := t.Context() l := resolveMetastore{name: "metastore"} _, err := l.Resolve(ctx, m.WorkspaceClient) require.Error(t, err) diff --git a/bundle/config/variable/resolve_notification_destination_test.go b/bundle/config/variable/resolve_notification_destination_test.go index f44b2f3e92..f5e24a94cf 100644 --- a/bundle/config/variable/resolve_notification_destination_test.go +++ b/bundle/config/variable/resolve_notification_destination_test.go @@ -1,7 +1,6 @@ package variable import ( - "context" "errors" "testing" @@ -22,7 +21,7 @@ func TestResolveNotificationDestination_ResolveSuccess(t *testing.T) { {Id: "1234", DisplayName: "destination"}, }, nil) - ctx := context.Background() + ctx := t.Context() l := resolveNotificationDestination{name: "destination"} result, err := l.Resolve(ctx, m.WorkspaceClient) require.NoError(t, err) @@ -37,7 +36,7 @@ func TestResolveNotificationDestination_ResolveError(t *testing.T) { ListAll(mock.Anything, mock.Anything). Return(nil, errors.New("bad")) - ctx := context.Background() + ctx := t.Context() l := resolveNotificationDestination{name: "destination"} _, err := l.Resolve(ctx, m.WorkspaceClient) assert.ErrorContains(t, err, "bad") @@ -51,7 +50,7 @@ func TestResolveNotificationDestination_ResolveNotFound(t *testing.T) { ListAll(mock.Anything, mock.Anything). Return([]settings.ListNotificationDestinationsResult{}, nil) - ctx := context.Background() + ctx := t.Context() l := resolveNotificationDestination{name: "destination"} _, err := l.Resolve(ctx, m.WorkspaceClient) require.Error(t, err) @@ -69,7 +68,7 @@ func TestResolveNotificationDestination_ResolveMultiple(t *testing.T) { {Id: "5678", DisplayName: "destination"}, }, nil) - ctx := context.Background() + ctx := t.Context() l := resolveNotificationDestination{name: "destination"} _, err := l.Resolve(ctx, m.WorkspaceClient) require.Error(t, err) diff --git a/bundle/config/variable/resolve_pipeline_test.go b/bundle/config/variable/resolve_pipeline_test.go index 620d762434..5586b96a2b 100644 --- a/bundle/config/variable/resolve_pipeline_test.go +++ b/bundle/config/variable/resolve_pipeline_test.go @@ -1,7 +1,6 @@ package variable import ( - "context" "testing" "github.com/databricks/databricks-sdk-go/apierr" @@ -22,7 +21,7 @@ func TestResolvePipeline_ResolveSuccess(t *testing.T) { PipelineId: "abcd", }, nil) - ctx := context.Background() + ctx := t.Context() l := resolvePipeline{name: "pipeline"} result, err := l.Resolve(ctx, m.WorkspaceClient) require.NoError(t, err) @@ -37,7 +36,7 @@ func TestResolvePipeline_ResolveNotFound(t *testing.T) { GetByName(mock.Anything, "pipeline"). Return(nil, &apierr.APIError{StatusCode: 404}) - ctx := context.Background() + ctx := t.Context() l := resolvePipeline{name: "pipeline"} _, err := l.Resolve(ctx, m.WorkspaceClient) require.ErrorIs(t, err, apierr.ErrNotFound) diff --git a/bundle/config/variable/resolve_query_test.go b/bundle/config/variable/resolve_query_test.go index 21516e4525..5fb0be05e3 100644 --- a/bundle/config/variable/resolve_query_test.go +++ b/bundle/config/variable/resolve_query_test.go @@ -1,7 +1,6 @@ package variable import ( - "context" "testing" "github.com/databricks/databricks-sdk-go/apierr" @@ -22,7 +21,7 @@ func TestResolveQuery_ResolveSuccess(t *testing.T) { Id: "1234", }, nil) - ctx := context.Background() + ctx := t.Context() l := resolveQuery{name: "query"} result, err := l.Resolve(ctx, m.WorkspaceClient) require.NoError(t, err) @@ -37,7 +36,7 @@ func TestResolveQuery_ResolveNotFound(t *testing.T) { GetByDisplayName(mock.Anything, "query"). Return(nil, &apierr.APIError{StatusCode: 404}) - ctx := context.Background() + ctx := t.Context() l := resolveQuery{name: "query"} _, err := l.Resolve(ctx, m.WorkspaceClient) require.ErrorIs(t, err, apierr.ErrNotFound) diff --git a/bundle/config/variable/resolve_service_principal_test.go b/bundle/config/variable/resolve_service_principal_test.go index c80f9e4a6f..0d062f282b 100644 --- a/bundle/config/variable/resolve_service_principal_test.go +++ b/bundle/config/variable/resolve_service_principal_test.go @@ -1,7 +1,6 @@ package variable import ( - "context" "testing" "github.com/databricks/databricks-sdk-go/apierr" @@ -22,7 +21,7 @@ func TestResolveServicePrincipal_ResolveSuccess(t *testing.T) { ApplicationId: "5678", }, nil) - ctx := context.Background() + ctx := t.Context() l := resolveServicePrincipal{name: "service-principal"} result, err := l.Resolve(ctx, m.WorkspaceClient) require.NoError(t, err) @@ -37,7 +36,7 @@ func TestResolveServicePrincipal_ResolveNotFound(t *testing.T) { GetByDisplayName(mock.Anything, "service-principal"). Return(nil, &apierr.APIError{StatusCode: 404}) - ctx := context.Background() + ctx := t.Context() l := resolveServicePrincipal{name: "service-principal"} _, err := l.Resolve(ctx, m.WorkspaceClient) require.ErrorIs(t, err, apierr.ErrNotFound) diff --git a/bundle/config/variable/resolve_warehouse_test.go b/bundle/config/variable/resolve_warehouse_test.go index 68e3925bc7..e528374de9 100644 --- a/bundle/config/variable/resolve_warehouse_test.go +++ b/bundle/config/variable/resolve_warehouse_test.go @@ -1,7 +1,6 @@ package variable import ( - "context" "testing" "github.com/databricks/databricks-sdk-go/apierr" @@ -22,7 +21,7 @@ func TestResolveWarehouse_ResolveSuccess(t *testing.T) { Id: "abcd", }, nil) - ctx := context.Background() + ctx := t.Context() l := resolveWarehouse{name: "warehouse"} result, err := l.Resolve(ctx, m.WorkspaceClient) require.NoError(t, err) @@ -37,7 +36,7 @@ func TestResolveWarehouse_ResolveNotFound(t *testing.T) { GetByName(mock.Anything, "warehouse"). Return(nil, &apierr.APIError{StatusCode: 404}) - ctx := context.Background() + ctx := t.Context() l := resolveWarehouse{name: "warehouse"} _, err := l.Resolve(ctx, m.WorkspaceClient) require.ErrorIs(t, err, apierr.ErrNotFound) diff --git a/bundle/config/workspace_test.go b/bundle/config/workspace_test.go index 04da0cff56..14947e2894 100644 --- a/bundle/config/workspace_test.go +++ b/bundle/config/workspace_test.go @@ -1,7 +1,6 @@ package config import ( - "context" "io/fs" "path/filepath" "runtime" @@ -43,7 +42,7 @@ func TestWorkspaceResolveProfileFromHost(t *testing.T) { setupWorkspaceTest(t) // This works if there is a config file with a matching profile. - err := databrickscfg.SaveToProfile(context.Background(), &config.Config{ + err := databrickscfg.SaveToProfile(t.Context(), &config.Config{ Profile: "default", Host: "https://abc.cloud.databricks.com", Token: "123", @@ -59,7 +58,7 @@ func TestWorkspaceResolveProfileFromHost(t *testing.T) { home := setupWorkspaceTest(t) // This works if there is a config file with a matching profile. - err := databrickscfg.SaveToProfile(context.Background(), &config.Config{ + err := databrickscfg.SaveToProfile(t.Context(), &config.Config{ ConfigFile: filepath.Join(home, "customcfg"), Profile: "custom", Host: "https://abc.cloud.databricks.com", @@ -93,7 +92,7 @@ func TestWorkspaceVerifyProfileForHost(t *testing.T) { setupWorkspaceTest(t) // This works if there is a config file with a matching profile. - err := databrickscfg.SaveToProfile(context.Background(), &config.Config{ + err := databrickscfg.SaveToProfile(t.Context(), &config.Config{ Profile: "abc", Host: "https://abc.cloud.databricks.com", }) @@ -107,7 +106,7 @@ func TestWorkspaceVerifyProfileForHost(t *testing.T) { setupWorkspaceTest(t) // This works if there is a config file with a matching profile. - err := databrickscfg.SaveToProfile(context.Background(), &config.Config{ + err := databrickscfg.SaveToProfile(t.Context(), &config.Config{ Profile: "abc", Host: "https://def.cloud.databricks.com", }) @@ -121,7 +120,7 @@ func TestWorkspaceVerifyProfileForHost(t *testing.T) { home := setupWorkspaceTest(t) // This works if there is a config file with a matching profile. - err := databrickscfg.SaveToProfile(context.Background(), &config.Config{ + err := databrickscfg.SaveToProfile(t.Context(), &config.Config{ ConfigFile: filepath.Join(home, "customcfg"), Profile: "abc", Host: "https://abc.cloud.databricks.com", @@ -137,7 +136,7 @@ func TestWorkspaceVerifyProfileForHost(t *testing.T) { home := setupWorkspaceTest(t) // This works if there is a config file with a matching profile. - err := databrickscfg.SaveToProfile(context.Background(), &config.Config{ + err := databrickscfg.SaveToProfile(t.Context(), &config.Config{ ConfigFile: filepath.Join(home, "customcfg"), Profile: "abc", Host: "https://def.cloud.databricks.com", diff --git a/bundle/configsync/output_test.go b/bundle/configsync/output_test.go index 1b35b807d8..1f43343c6e 100644 --- a/bundle/configsync/output_test.go +++ b/bundle/configsync/output_test.go @@ -1,7 +1,6 @@ package configsync import ( - "context" "os" "path/filepath" "testing" @@ -12,7 +11,7 @@ import ( ) func TestSaveFiles_Success(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tmpDir := t.TempDir() @@ -47,7 +46,7 @@ func TestSaveFiles_Success(t *testing.T) { } func TestSaveFiles_MultipleFiles(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tmpDir := t.TempDir() @@ -82,7 +81,7 @@ func TestSaveFiles_MultipleFiles(t *testing.T) { } func TestSaveFiles_EmptyList(t *testing.T) { - ctx := context.Background() + ctx := t.Context() err := SaveFiles(ctx, &bundle.Bundle{}, []FileChange{}) require.NoError(t, err) diff --git a/bundle/configsync/patch_test.go b/bundle/configsync/patch_test.go index cc1cb5dd06..b4faea8285 100644 --- a/bundle/configsync/patch_test.go +++ b/bundle/configsync/patch_test.go @@ -1,7 +1,6 @@ package configsync import ( - "context" "os" "path/filepath" "strings" @@ -16,7 +15,7 @@ import ( ) func TestApplyChangesToYAML_PreserveFormatting(t *testing.T) { - ctx := logdiag.InitContext(context.Background()) + ctx := logdiag.InitContext(t.Context()) tmpDir := t.TempDir() diff --git a/bundle/configsync/resolve_test.go b/bundle/configsync/resolve_test.go index e59ed242b1..9264ad7f5d 100644 --- a/bundle/configsync/resolve_test.go +++ b/bundle/configsync/resolve_test.go @@ -1,7 +1,6 @@ package configsync import ( - "context" "os" "path/filepath" "testing" @@ -16,7 +15,7 @@ import ( ) func TestResolveSelectors_NoSelectors(t *testing.T) { - ctx := logdiag.InitContext(context.Background()) + ctx := logdiag.InitContext(t.Context()) tmpDir := t.TempDir() yamlContent := `resources: @@ -39,7 +38,7 @@ func TestResolveSelectors_NoSelectors(t *testing.T) { } func TestResolveSelectors_NumericIndices(t *testing.T) { - ctx := logdiag.InitContext(context.Background()) + ctx := logdiag.InitContext(t.Context()) tmpDir := t.TempDir() yamlContent := `resources: @@ -68,7 +67,7 @@ func TestResolveSelectors_NumericIndices(t *testing.T) { } func TestResolveSelectors_KeyValueSelector(t *testing.T) { - ctx := logdiag.InitContext(context.Background()) + ctx := logdiag.InitContext(t.Context()) tmpDir := t.TempDir() yamlContent := `resources: @@ -101,7 +100,7 @@ func TestResolveSelectors_KeyValueSelector(t *testing.T) { } func TestResolveSelectors_SelectorNotFound(t *testing.T) { - ctx := logdiag.InitContext(context.Background()) + ctx := logdiag.InitContext(t.Context()) tmpDir := t.TempDir() yamlContent := `resources: @@ -127,7 +126,7 @@ func TestResolveSelectors_SelectorNotFound(t *testing.T) { } func TestResolveSelectors_SelectorOnNonArray(t *testing.T) { - ctx := cmdio.MockDiscard(logdiag.InitContext(context.Background())) + ctx := cmdio.MockDiscard(logdiag.InitContext(t.Context())) tmpDir := t.TempDir() yamlContent := `resources: @@ -150,7 +149,7 @@ func TestResolveSelectors_SelectorOnNonArray(t *testing.T) { } func TestResolveSelectors_NestedSelectors(t *testing.T) { - ctx := logdiag.InitContext(context.Background()) + ctx := logdiag.InitContext(t.Context()) tmpDir := t.TempDir() yamlContent := `resources: @@ -181,7 +180,7 @@ func TestResolveSelectors_NestedSelectors(t *testing.T) { } func TestResolveSelectors_WildcardNotSupported(t *testing.T) { - ctx := logdiag.InitContext(context.Background()) + ctx := logdiag.InitContext(t.Context()) tmpDir := t.TempDir() yamlContent := `resources: diff --git a/bundle/context_test.go b/bundle/context_test.go index 89a6df0528..40dfa1b7d1 100644 --- a/bundle/context_test.go +++ b/bundle/context_test.go @@ -1,7 +1,6 @@ package bundle import ( - "context" "testing" "github.com/stretchr/testify/assert" @@ -15,10 +14,10 @@ func TestGetPanics(t *testing.T) { assert.Equal(t, "context not configured with bundle", r) }() - Get(context.Background()) + Get(t.Context()) } func TestGetSuccess(t *testing.T) { - ctx := Context(context.Background(), &Bundle{}) + ctx := Context(t.Context(), &Bundle{}) require.NotNil(t, Get(ctx)) } diff --git a/bundle/deploy/metadata/annotate_jobs_test.go b/bundle/deploy/metadata/annotate_jobs_test.go index 8847f28d0d..767559b19d 100644 --- a/bundle/deploy/metadata/annotate_jobs_test.go +++ b/bundle/deploy/metadata/annotate_jobs_test.go @@ -1,7 +1,6 @@ package metadata import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -37,7 +36,7 @@ func TestAnnotateJobsMutator(t *testing.T) { }, } - ctx := context.Background() + ctx := t.Context() ctx = dbr.MockRuntime(ctx, dbr.Environment{IsDbr: false, Version: ""}) diags := AnnotateJobs().Apply(ctx, b) @@ -73,7 +72,7 @@ func TestAnnotateJobsMutatorJobWithoutSettings(t *testing.T) { }, } - ctx := context.Background() + ctx := t.Context() ctx = dbr.MockRuntime(ctx, dbr.Environment{IsDbr: false, Version: ""}) diags := AnnotateJobs().Apply(ctx, b) @@ -102,7 +101,7 @@ func TestAnnotateJobsWorkspaceWithFlag(t *testing.T) { }, } - ctx := context.Background() + ctx := t.Context() ctx = dbr.MockRuntime(ctx, dbr.Environment{IsDbr: true, Version: "14.0"}) ctx = env.Set(ctx, "DATABRICKS_BUNDLE_ENABLE_EXPERIMENTAL_YAML_SYNC", "1") @@ -135,7 +134,7 @@ func TestAnnotateJobsWorkspaceNonDevelopment(t *testing.T) { }, } - ctx := context.Background() + ctx := t.Context() ctx = dbr.MockRuntime(ctx, dbr.Environment{IsDbr: true, Version: "14.0"}) ctx = env.Set(ctx, "DATABRICKS_BUNDLE_ENABLE_EXPERIMENTAL_YAML_SYNC", "1") @@ -165,7 +164,7 @@ func TestAnnotateJobsWorkspaceWithoutFlag(t *testing.T) { }, } - ctx := context.Background() + ctx := t.Context() ctx = dbr.MockRuntime(ctx, dbr.Environment{IsDbr: true, Version: "14.0"}) diags := AnnotateJobs().Apply(ctx, b) @@ -194,7 +193,7 @@ func TestAnnotateJobsNonWorkspaceWithFlag(t *testing.T) { }, } - ctx := context.Background() + ctx := t.Context() ctx = dbr.MockRuntime(ctx, dbr.Environment{IsDbr: false, Version: ""}) ctx = env.Set(ctx, "DATABRICKS_BUNDLE_ENABLE_EXPERIMENTAL_YAML_SYNC", "1") diff --git a/bundle/deploy/metadata/annotate_pipelines_test.go b/bundle/deploy/metadata/annotate_pipelines_test.go index 018384e819..6a96248d01 100644 --- a/bundle/deploy/metadata/annotate_pipelines_test.go +++ b/bundle/deploy/metadata/annotate_pipelines_test.go @@ -1,7 +1,6 @@ package metadata import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -35,7 +34,7 @@ func TestAnnotatePipelinesMutator(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, AnnotatePipelines()) + diags := bundle.Apply(t.Context(), b, AnnotatePipelines()) require.NoError(t, diags.Error()) assert.Equal(t, @@ -67,6 +66,6 @@ func TestAnnotatePipelinesMutatorPipelineWithoutASpec(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, AnnotatePipelines()) + diags := bundle.Apply(t.Context(), b, AnnotatePipelines()) require.NoError(t, diags.Error()) } diff --git a/bundle/deploy/metadata/compute_test.go b/bundle/deploy/metadata/compute_test.go index afddecf30e..a10f65d72e 100644 --- a/bundle/deploy/metadata/compute_test.go +++ b/bundle/deploy/metadata/compute_test.go @@ -1,7 +1,6 @@ package metadata import ( - "context" "runtime" "testing" @@ -143,7 +142,7 @@ func TestComputeMetadataMutator(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, Compute()) + diags := bundle.Apply(t.Context(), b, Compute()) require.NoError(t, diags.Error()) assert.Equal(t, expectedMetadata, b.Metadata) @@ -164,7 +163,7 @@ func TestComputeMetadataMutatorSourceLinked(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, Compute()) + diags := bundle.Apply(t.Context(), b, Compute()) require.NoError(t, diags.Error()) assert.Equal(t, syncRootPath, b.Metadata.Config.Workspace.FilePath) @@ -184,7 +183,7 @@ func TestComputeMetadataMutatorGitFolderPath(t *testing.T) { WorktreeRoot: path, } - diags := bundle.Apply(context.Background(), b, Compute()) + diags := bundle.Apply(t.Context(), b, Compute()) require.NoError(t, diags.Error()) assert.Equal(t, gitFolderPath, b.Metadata.Extra.GitFolderPath) diff --git a/bundle/deploy/state_pull_test.go b/bundle/deploy/state_pull_test.go index b3d838fce9..f3799aba46 100644 --- a/bundle/deploy/state_pull_test.go +++ b/bundle/deploy/state_pull_test.go @@ -2,7 +2,6 @@ package deploy import ( "bytes" - "context" "encoding/json" "io" "io/fs" @@ -81,7 +80,7 @@ func testStatePull(t *testing.T, opts statePullOpts) { }, }, } - ctx := context.Background() + ctx := t.Context() for _, file := range opts.localFiles { testutil.Touch(t, b.SyncRootPath, "bar", file) @@ -268,7 +267,7 @@ func TestStatePullNoState(t *testing.T) { }, }, } - ctx := context.Background() + ctx := t.Context() diags := bundle.Apply(ctx, b, s) require.NoError(t, diags.Error()) @@ -456,7 +455,7 @@ func TestStatePullNewerDeploymentStateVersion(t *testing.T) { }, }, } - ctx := context.Background() + ctx := t.Context() diags := bundle.Apply(ctx, b, s) require.True(t, diags.HasError()) diff --git a/bundle/deploy/state_push_test.go b/bundle/deploy/state_push_test.go index 3562ec147e..e711e5a3c6 100644 --- a/bundle/deploy/state_push_test.go +++ b/bundle/deploy/state_push_test.go @@ -1,7 +1,6 @@ package deploy import ( - "context" "encoding/json" "io" "os" @@ -56,7 +55,7 @@ func TestStatePush(t *testing.T) { }, } - ctx := context.Background() + ctx := t.Context() statePath, err := getPathToStateFile(ctx, b) require.NoError(t, err) diff --git a/bundle/deploy/state_update_test.go b/bundle/deploy/state_update_test.go index 04c5579a88..d4b24d85b3 100644 --- a/bundle/deploy/state_update_test.go +++ b/bundle/deploy/state_update_test.go @@ -1,7 +1,6 @@ package deploy import ( - "context" "encoding/json" "os" "testing" @@ -50,7 +49,7 @@ func TestStateUpdate(t *testing.T) { s := &stateUpdate{} b := setupBundleForStateUpdate(t) - ctx := context.Background() + ctx := t.Context() diags := bundle.Apply(ctx, b, s) require.NoError(t, diags.Error()) @@ -98,7 +97,7 @@ func TestStateUpdateWithExistingState(t *testing.T) { s := &stateUpdate{} b := setupBundleForStateUpdate(t) - ctx := context.Background() + ctx := t.Context() // Create an existing state file. statePath, err := getPathToStateFile(ctx, b) diff --git a/bundle/deploy/terraform/check_dashboards_modified_remotely_test.go b/bundle/deploy/terraform/check_dashboards_modified_remotely_test.go index 86086573d7..6270e4229f 100644 --- a/bundle/deploy/terraform/check_dashboards_modified_remotely_test.go +++ b/bundle/deploy/terraform/check_dashboards_modified_remotely_test.go @@ -51,18 +51,18 @@ func TestCheckDashboardsModifiedRemotely_NoDashboards(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, CheckDashboardsModifiedRemotely(false, engine.EngineTerraform)) + diags := bundle.Apply(t.Context(), b, CheckDashboardsModifiedRemotely(false, engine.EngineTerraform)) assert.Empty(t, diags) } func TestCheckDashboardsModifiedRemotely_FirstDeployment(t *testing.T) { b := mockDashboardBundle(t) - diags := bundle.Apply(context.Background(), b, CheckDashboardsModifiedRemotely(false, engine.EngineTerraform)) + diags := bundle.Apply(t.Context(), b, CheckDashboardsModifiedRemotely(false, engine.EngineTerraform)) assert.Empty(t, diags) } func TestCheckDashboardsModifiedRemotely_ExistingStateNoChange(t *testing.T) { - ctx := context.Background() + ctx := t.Context() b := mockDashboardBundle(t) writeFakeDashboardState(t, ctx, b) @@ -85,7 +85,7 @@ func TestCheckDashboardsModifiedRemotely_ExistingStateNoChange(t *testing.T) { } func TestCheckDashboardsModifiedRemotely_ExistingStateChange(t *testing.T) { - ctx := context.Background() + ctx := t.Context() b := mockDashboardBundle(t) writeFakeDashboardState(t, ctx, b) @@ -111,7 +111,7 @@ func TestCheckDashboardsModifiedRemotely_ExistingStateChange(t *testing.T) { } func TestCheckDashboardsModifiedRemotely_ExistingStateFailureToGet(t *testing.T) { - ctx := context.Background() + ctx := t.Context() b := mockDashboardBundle(t) writeFakeDashboardState(t, ctx, b) @@ -134,7 +134,7 @@ func TestCheckDashboardsModifiedRemotely_ExistingStateFailureToGet(t *testing.T) } func TestCheckDashboardsModifiedRemotely_ExistingStateChangePlanMode(t *testing.T) { - ctx := context.Background() + ctx := t.Context() b := mockDashboardBundle(t) writeFakeDashboardState(t, ctx, b) diff --git a/bundle/deploy/terraform/convert_test.go b/bundle/deploy/terraform/convert_test.go index 6201c596cf..ffec1cb7b1 100644 --- a/bundle/deploy/terraform/convert_test.go +++ b/bundle/deploy/terraform/convert_test.go @@ -1,7 +1,6 @@ package terraform import ( - "context" "testing" "github.com/databricks/cli/bundle/config" @@ -22,7 +21,7 @@ import ( func produceTerraformConfiguration(t *testing.T, config config.Root) *schema.Root { vin, err := convert.FromTyped(config, dyn.NilValue) require.NoError(t, err) - out, err := BundleToTerraformWithDynValue(context.Background(), vin) + out, err := BundleToTerraformWithDynValue(t.Context(), vin) require.NoError(t, err) return out } @@ -589,7 +588,7 @@ func TestBundleToTerraformDeletedResources(t *testing.T) { vin, err := convert.FromTyped(config, dyn.NilValue) require.NoError(t, err) - out, err := BundleToTerraformWithDynValue(context.Background(), vin) + out, err := BundleToTerraformWithDynValue(t.Context(), vin) require.NoError(t, err) _, ok := out.Resource.Job["my_job1"] diff --git a/bundle/deploy/terraform/init_test.go b/bundle/deploy/terraform/init_test.go index 635f880426..84ad50cc25 100644 --- a/bundle/deploy/terraform/init_test.go +++ b/bundle/deploy/terraform/init_test.go @@ -46,7 +46,7 @@ func TestSetTempDirEnvVarsForUnixWithTmpDirSet(t *testing.T) { // compute env env := make(map[string]string, 0) - err := setTempDirEnvVars(context.Background(), env, b) + err := setTempDirEnvVars(t.Context(), env, b) require.NoError(t, err) // Assert that we pass through TMPDIR. @@ -74,7 +74,7 @@ func TestSetTempDirEnvVarsForUnixWithTmpDirNotSet(t *testing.T) { // compute env env := make(map[string]string, 0) - err := setTempDirEnvVars(context.Background(), env, b) + err := setTempDirEnvVars(t.Context(), env, b) require.NoError(t, err) // Assert that we don't pass through TMPDIR. @@ -102,7 +102,7 @@ func TestSetTempDirEnvVarsForWindowWithAllTmpDirEnvVarsSet(t *testing.T) { // compute env env := make(map[string]string, 0) - err := setTempDirEnvVars(context.Background(), env, b) + err := setTempDirEnvVars(t.Context(), env, b) require.NoError(t, err) // assert that we pass through the highest priority env var value @@ -132,7 +132,7 @@ func TestSetTempDirEnvVarsForWindowWithUserProfileAndTempSet(t *testing.T) { // compute env env := make(map[string]string, 0) - err := setTempDirEnvVars(context.Background(), env, b) + err := setTempDirEnvVars(t.Context(), env, b) require.NoError(t, err) // assert that we pass through the highest priority env var value @@ -162,11 +162,11 @@ func TestSetTempDirEnvVarsForWindowsWithoutAnyTempDirEnvVarsSet(t *testing.T) { // compute env env := make(map[string]string, 0) - err := setTempDirEnvVars(context.Background(), env, b) + err := setTempDirEnvVars(t.Context(), env, b) require.NoError(t, err) // assert TMP is set to b.LocalStateDir("tmp") - tmpDir, err := b.LocalStateDir(context.Background(), "tmp") + tmpDir, err := b.LocalStateDir(t.Context(), "tmp") require.NoError(t, err) assert.Equal(t, map[string]string{ "TMP": tmpDir, @@ -196,7 +196,7 @@ func TestSetProxyEnvVars(t *testing.T) { // No proxy env vars set. clearEnv() env := make(map[string]string, 0) - err := setProxyEnvVars(context.Background(), env, b) + err := setProxyEnvVars(t.Context(), env, b) require.NoError(t, err) assert.Empty(t, env) @@ -206,7 +206,7 @@ func TestSetProxyEnvVars(t *testing.T) { t.Setenv("https_proxy", "foo") t.Setenv("no_proxy", "foo") env = make(map[string]string, 0) - err = setProxyEnvVars(context.Background(), env, b) + err = setProxyEnvVars(t.Context(), env, b) require.NoError(t, err) assert.ElementsMatch(t, []string{"HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY"}, maps.Keys(env)) @@ -216,7 +216,7 @@ func TestSetProxyEnvVars(t *testing.T) { t.Setenv("HTTPS_PROXY", "foo") t.Setenv("NO_PROXY", "foo") env = make(map[string]string, 0) - err = setProxyEnvVars(context.Background(), env, b) + err = setProxyEnvVars(t.Context(), env, b) require.NoError(t, err) assert.ElementsMatch(t, []string{"HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY"}, maps.Keys(env)) } @@ -247,7 +247,7 @@ func TestInheritEnvVars(t *testing.T) { t.Setenv("TF_CLI_CONFIG_FILE", "/tmp/config.tfrc") t.Setenv("AZURE_CONFIG_DIR", "/tmp/foo/bar") - ctx := context.Background() + ctx := t.Context() env := map[string]string{} err := inheritEnvVars(ctx, env) if assert.NoError(t, err) { @@ -262,7 +262,7 @@ func TestInheritOIDCTokenEnvCustom(t *testing.T) { t.Setenv("DATABRICKS_OIDC_TOKEN_ENV", "custom_DATABRICKS_OIDC_TOKEN") t.Setenv("custom_DATABRICKS_OIDC_TOKEN", "foobar") - ctx := context.Background() + ctx := t.Context() env := map[string]string{} err := inheritEnvVars(ctx, env) require.NoError(t, err) @@ -273,7 +273,7 @@ func TestInheritOIDCTokenEnvCustom(t *testing.T) { func TestInheritOIDCTokenEnv(t *testing.T) { t.Setenv("DATABRICKS_OIDC_TOKEN", "foobar") - ctx := context.Background() + ctx := t.Context() env := map[string]string{} err := inheritEnvVars(ctx, env) require.NoError(t, err) @@ -303,7 +303,7 @@ func TestInheritAzureDevOpsSystemVariablesIndividual(t *testing.T) { t.Run(tc.envVar, func(t *testing.T) { t.Setenv(tc.envVar, tc.envValue) - ctx := context.Background() + ctx := t.Context() env := map[string]string{} err := inheritEnvVars(ctx, env) require.NoError(t, err) @@ -332,7 +332,7 @@ func TestInheritAzureDevOpsSystemVariables(t *testing.T) { t.Setenv(k, v) } - ctx := context.Background() + ctx := t.Context() env := map[string]string{} err := inheritEnvVars(ctx, env) require.NoError(t, err) @@ -346,7 +346,7 @@ func TestSetUserProfileFromInheritEnvVars(t *testing.T) { t.Setenv("USERPROFILE", "c:\\foo\\c") env := make(map[string]string, 0) - err := inheritEnvVars(context.Background(), env) + err := inheritEnvVars(t.Context(), env) require.NoError(t, err) assert.Contains(t, env, "USERPROFILE") @@ -354,7 +354,7 @@ func TestSetUserProfileFromInheritEnvVars(t *testing.T) { } func TestInheritEnvVarsWithAbsentTFConfigFile(t *testing.T) { - ctx := context.Background() + ctx := t.Context() envMap := map[string]string{} ctx = env.Set(ctx, "DATABRICKS_TF_PROVIDER_VERSION", schema.ProviderVersion) ctx = env.Set(ctx, "DATABRICKS_TF_CLI_CONFIG_FILE", "/tmp/config.tfrc") @@ -364,7 +364,7 @@ func TestInheritEnvVarsWithAbsentTFConfigFile(t *testing.T) { } func TestInheritEnvVarsWithWrongTFProviderVersion(t *testing.T) { - ctx := context.Background() + ctx := t.Context() envMap := map[string]string{} configFile := createTempFile(t, t.TempDir(), "config.tfrc", false) ctx = env.Set(ctx, "DATABRICKS_TF_PROVIDER_VERSION", "wrong") @@ -375,7 +375,7 @@ func TestInheritEnvVarsWithWrongTFProviderVersion(t *testing.T) { } func TestInheritEnvVarsWithCorrectTFCLIConfigFile(t *testing.T) { - ctx := context.Background() + ctx := t.Context() envMap := map[string]string{} configFile := createTempFile(t, t.TempDir(), "config.tfrc", false) ctx = env.Set(ctx, "DATABRICKS_TF_PROVIDER_VERSION", schema.ProviderVersion) @@ -456,7 +456,7 @@ func (i testInstaller) Install(ctx context.Context, dir string, version *version } func TestFindExecPath_NoBinary(t *testing.T) { - ctx := context.Background() + ctx := t.Context() b := &bundle.Bundle{ BundleRootPath: t.TempDir(), Config: config.Root{ @@ -474,7 +474,7 @@ func TestFindExecPath_NoBinary(t *testing.T) { } func TestFindExecPath_UseExistingBinary(t *testing.T) { - ctx := context.Background() + ctx := t.Context() b := &bundle.Bundle{ BundleRootPath: t.TempDir(), Config: config.Root{ @@ -496,7 +496,7 @@ func TestFindExecPath_UseExistingBinary(t *testing.T) { } func TestFindExecPath_ExecPathWrongVersion(t *testing.T) { - ctx := context.Background() + ctx := t.Context() b := &bundle.Bundle{ BundleRootPath: t.TempDir(), Config: config.Root{ @@ -522,7 +522,7 @@ func TestFindExecPath_ExecPathWrongVersion(t *testing.T) { } func TestFindExecPath_ExecPathMatchingVersion(t *testing.T) { - ctx := context.Background() + ctx := t.Context() b := &bundle.Bundle{ BundleRootPath: t.TempDir(), Config: config.Root{ @@ -544,7 +544,7 @@ func TestFindExecPath_ExecPathMatchingVersion(t *testing.T) { } func TestFindExecPath_Version_NoExecPath(t *testing.T) { - ctx := context.Background() + ctx := t.Context() b := &bundle.Bundle{ BundleRootPath: t.TempDir(), Config: config.Root{ @@ -566,7 +566,7 @@ func TestFindExecPath_Version_NoExecPath(t *testing.T) { } func TestFindExecPath_Version_ExecPathBadFile(t *testing.T) { - ctx := context.Background() + ctx := t.Context() b := &bundle.Bundle{ BundleRootPath: t.TempDir(), Config: config.Root{ @@ -590,7 +590,7 @@ func TestFindExecPath_Version_ExecPathBadFile(t *testing.T) { } func TestFindExecPath_Version_ExecPathWrongVersion(t *testing.T) { - ctx := context.Background() + ctx := t.Context() b := &bundle.Bundle{ BundleRootPath: t.TempDir(), Config: config.Root{ @@ -619,7 +619,7 @@ func TestFindExecPath_Version_ExecPathWrongVersion(t *testing.T) { } func TestFindExecPath_Version_ExecPathMatchingVersion(t *testing.T) { - ctx := context.Background() + ctx := t.Context() b := &bundle.Bundle{ BundleRootPath: t.TempDir(), Config: config.Root{ @@ -709,7 +709,7 @@ func TestGetEnvVarWithMatchingVersion(t *testing.T) { t.Setenv(envVarName, c.envValue) t.Setenv(versionVarName, c.versionValue) - actual, err := getEnvVarWithMatchingVersion(context.Background(), envVarName, versionVarName, c.currentVersion) + actual, err := getEnvVarWithMatchingVersion(t.Context(), envVarName, versionVarName, c.currentVersion) require.NoError(t, err) assert.Equal(t, c.expected, actual) }) diff --git a/bundle/deploy/terraform/interpolate_test.go b/bundle/deploy/terraform/interpolate_test.go index 2d63309746..5d45b4d8fb 100644 --- a/bundle/deploy/terraform/interpolate_test.go +++ b/bundle/deploy/terraform/interpolate_test.go @@ -1,7 +1,6 @@ package terraform import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -61,7 +60,7 @@ func TestInterpolate(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, Interpolate()) + diags := bundle.Apply(t.Context(), b, Interpolate()) require.NoError(t, diags.Error()) j := b.Config.Resources.Jobs["my_job"] @@ -103,7 +102,7 @@ func TestInterpolatePostgresResourcesMapIdToName(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, Interpolate()) + diags := bundle.Apply(t.Context(), b, Interpolate()) require.NoError(t, diags.Error()) j := b.Config.Resources.Jobs["my_job"] @@ -132,6 +131,6 @@ func TestInterpolateUnknownResourceType(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, Interpolate()) + diags := bundle.Apply(t.Context(), b, Interpolate()) assert.ErrorContains(t, diags.Error(), `reference does not exist: ${resources.unknown.other_unknown.id}`) } diff --git a/bundle/deploy/terraform/lifecycle_test.go b/bundle/deploy/terraform/lifecycle_test.go index 802a7f1bd8..b07b488890 100644 --- a/bundle/deploy/terraform/lifecycle_test.go +++ b/bundle/deploy/terraform/lifecycle_test.go @@ -1,7 +1,6 @@ package terraform import ( - "context" "encoding/json" "testing" @@ -12,7 +11,7 @@ import ( func TestConvertLifecycleForAllResources(t *testing.T) { supportedResources := config.SupportedResources() - ctx := context.Background() + ctx := t.Context() // Resources that are only supported in direct mode and should not be converted to Terraform ignoredResources := []string{ diff --git a/bundle/deploy/terraform/pkg_test.go b/bundle/deploy/terraform/pkg_test.go index 2e8e37b26a..2b19e99234 100644 --- a/bundle/deploy/terraform/pkg_test.go +++ b/bundle/deploy/terraform/pkg_test.go @@ -1,7 +1,6 @@ package terraform import ( - "context" "crypto/sha256" "encoding/hex" "fmt" @@ -45,7 +44,7 @@ func downloadAndChecksum(t *testing.T, url, expectedChecksum string) { } func TestTerraformArchiveChecksums(t *testing.T) { - tv, isDefault, err := GetTerraformVersion(context.Background()) + tv, isDefault, err := GetTerraformVersion(t.Context()) require.NoError(t, err) assert.True(t, isDefault) armUrl := fmt.Sprintf("https://releases.hashicorp.com/terraform/%s/terraform_%s_linux_arm64.zip", tv.Version.String(), tv.Version.String()) @@ -57,7 +56,7 @@ func TestTerraformArchiveChecksums(t *testing.T) { func TestGetTerraformVersionDefault(t *testing.T) { // Verify that the default version is used - tv, isDefault, err := GetTerraformVersion(context.Background()) + tv, isDefault, err := GetTerraformVersion(t.Context()) require.NoError(t, err) assert.True(t, isDefault) assert.Equal(t, defaultTerraformVersion.Version.String(), tv.Version.String()) @@ -68,7 +67,7 @@ func TestGetTerraformVersionDefault(t *testing.T) { func TestGetTerraformVersionOverride(t *testing.T) { // Set the override version overrideVersion := "1.12.2" - ctx := env.Set(context.Background(), TerraformVersionEnv, overrideVersion) + ctx := env.Set(t.Context(), TerraformVersionEnv, overrideVersion) // Verify that the override version is used tv, isDefault, err := GetTerraformVersion(ctx) diff --git a/bundle/deploy/terraform/showplanfile_test.go b/bundle/deploy/terraform/showplanfile_test.go index cd7361cf9f..75a2cc6f43 100644 --- a/bundle/deploy/terraform/showplanfile_test.go +++ b/bundle/deploy/terraform/showplanfile_test.go @@ -1,7 +1,6 @@ package terraform import ( - "context" "testing" "github.com/databricks/cli/bundle/deployplan" @@ -10,7 +9,7 @@ import ( ) func TestPopulatePlan(t *testing.T) { - ctx := context.Background() + ctx := t.Context() changes := []*tfjson.ResourceChange{ { Type: "databricks_pipeline", diff --git a/bundle/deploy/terraform/tfdyn/convert_alert_test.go b/bundle/deploy/terraform/tfdyn/convert_alert_test.go index ae222331d9..94c3ca518d 100644 --- a/bundle/deploy/terraform/tfdyn/convert_alert_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_alert_test.go @@ -1,7 +1,6 @@ package tfdyn import ( - "context" "testing" "github.com/databricks/cli/bundle/config/resources" @@ -37,7 +36,7 @@ func TestConvertAlert(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = alertConverter{}.Convert(ctx, "test_alert", vin, out) require.NoError(t, err) @@ -92,7 +91,7 @@ func TestConvertAlertWithThresholdDoubleValue(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = alertConverter{}.Convert(ctx, "test_alert", vin, out) require.NoError(t, err) diff --git a/bundle/deploy/terraform/tfdyn/convert_app_test.go b/bundle/deploy/terraform/tfdyn/convert_app_test.go index 662c172fb9..896d0e52d5 100644 --- a/bundle/deploy/terraform/tfdyn/convert_app_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_app_test.go @@ -1,7 +1,6 @@ package tfdyn import ( - "context" "testing" "github.com/databricks/cli/bundle/config/resources" @@ -51,7 +50,7 @@ func TestConvertApp(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = appConverter{}.Convert(ctx, "my_app", vin, out) require.NoError(t, err) @@ -122,7 +121,7 @@ func TestConvertAppWithNoDescription(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = appConverter{}.Convert(ctx, "my_app", vin, out) require.NoError(t, err) diff --git a/bundle/deploy/terraform/tfdyn/convert_cluster_test.go b/bundle/deploy/terraform/tfdyn/convert_cluster_test.go index 2e1f71f30a..c28e874413 100644 --- a/bundle/deploy/terraform/tfdyn/convert_cluster_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_cluster_test.go @@ -1,7 +1,6 @@ package tfdyn import ( - "context" "testing" "github.com/databricks/cli/bundle/config/resources" @@ -51,7 +50,7 @@ func TestConvertCluster(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = clusterConverter{}.Convert(ctx, "my_cluster", vin, out) require.NoError(t, err) diff --git a/bundle/deploy/terraform/tfdyn/convert_dashboard_test.go b/bundle/deploy/terraform/tfdyn/convert_dashboard_test.go index f9bbdff447..847a609365 100644 --- a/bundle/deploy/terraform/tfdyn/convert_dashboard_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_dashboard_test.go @@ -1,7 +1,6 @@ package tfdyn import ( - "context" "testing" "github.com/databricks/cli/bundle/config/resources" @@ -32,7 +31,7 @@ func TestConvertDashboard(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = dashboardConverter{}.Convert(ctx, "my_dashboard", vin, out) require.NoError(t, err) @@ -67,7 +66,7 @@ func TestConvertDashboardSerializedDashboardString(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = dashboardConverter{}.Convert(ctx, "my_dashboard", vin, out) require.NoError(t, err) @@ -96,7 +95,7 @@ func TestConvertDashboardSerializedDashboardAny(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = dashboardConverter{}.Convert(ctx, "my_dashboard", vin, out) require.NoError(t, err) @@ -125,7 +124,7 @@ func TestConvertDashboardDatasetCatalogSchema(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = dashboardConverter{}.Convert(ctx, "my_dashboard", vin, out) require.NoError(t, err) diff --git a/bundle/deploy/terraform/tfdyn/convert_database_instance_test.go b/bundle/deploy/terraform/tfdyn/convert_database_instance_test.go index 6671282cbf..d29386a24d 100644 --- a/bundle/deploy/terraform/tfdyn/convert_database_instance_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_database_instance_test.go @@ -1,7 +1,6 @@ package tfdyn import ( - "context" "testing" "github.com/databricks/cli/bundle/config/resources" @@ -28,7 +27,7 @@ func TestConvertDatabaseInstance(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = databaseInstanceConverter{}.Convert(ctx, "my_database_instance", vin, out) require.NoError(t, err) @@ -55,7 +54,7 @@ func TestConvertDatabaseInstanceWithMinimalConfig(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = databaseInstanceConverter{}.Convert(ctx, "minimal_database_instance", vin, out) require.NoError(t, err) @@ -90,7 +89,7 @@ func TestConvertDatabaseInstanceWithPermissions(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = databaseInstanceConverter{}.Convert(ctx, "db_with_permissions", vin, out) require.NoError(t, err) diff --git a/bundle/deploy/terraform/tfdyn/convert_experiment_test.go b/bundle/deploy/terraform/tfdyn/convert_experiment_test.go index 9137b89ffb..9140ef13ac 100644 --- a/bundle/deploy/terraform/tfdyn/convert_experiment_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_experiment_test.go @@ -1,7 +1,6 @@ package tfdyn import ( - "context" "testing" "github.com/databricks/cli/bundle/config/resources" @@ -29,7 +28,7 @@ func TestConvertExperiment(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = experimentConverter{}.Convert(ctx, "my_experiment", vin, out) require.NoError(t, err) diff --git a/bundle/deploy/terraform/tfdyn/convert_grants_test.go b/bundle/deploy/terraform/tfdyn/convert_grants_test.go index 0a263b493d..9717529a86 100644 --- a/bundle/deploy/terraform/tfdyn/convert_grants_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_grants_test.go @@ -1,7 +1,6 @@ package tfdyn import ( - "context" "testing" "github.com/databricks/cli/bundle/config/resources" @@ -29,7 +28,7 @@ func TestConvertGrants(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() resource := convertGrantsResource(ctx, vin) require.NotNil(t, resource) assert.Equal(t, []schema.ResourceGrantsGrant{ @@ -52,7 +51,7 @@ func TestConvertGrantsNil(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() resource := convertGrantsResource(ctx, vin) assert.Nil(t, resource) } @@ -65,7 +64,7 @@ func TestConvertGrantsEmpty(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() resource := convertGrantsResource(ctx, vin) assert.Nil(t, resource) } diff --git a/bundle/deploy/terraform/tfdyn/convert_job_test.go b/bundle/deploy/terraform/tfdyn/convert_job_test.go index c28d527294..782075fc7f 100644 --- a/bundle/deploy/terraform/tfdyn/convert_job_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_job_test.go @@ -1,7 +1,6 @@ package tfdyn import ( - "context" "reflect" "slices" "strings" @@ -83,7 +82,7 @@ func TestConvertJob(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = jobConverter{}.Convert(ctx, "my_job", vin, out) require.NoError(t, err) @@ -215,7 +214,7 @@ func TestConvertJobApplyPolicyDefaultValues(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = jobConverter{}.Convert(ctx, "my_job", vin, out) require.NoError(t, err) diff --git a/bundle/deploy/terraform/tfdyn/convert_model_serving_endpoint_test.go b/bundle/deploy/terraform/tfdyn/convert_model_serving_endpoint_test.go index 029478a10a..fbb3d39a72 100644 --- a/bundle/deploy/terraform/tfdyn/convert_model_serving_endpoint_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_model_serving_endpoint_test.go @@ -1,7 +1,6 @@ package tfdyn import ( - "context" "testing" "github.com/databricks/cli/bundle/config/resources" @@ -47,7 +46,7 @@ func TestConvertModelServingEndpoint(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = modelServingEndpointConverter{}.Convert(ctx, "my_model_serving_endpoint", vin, out) require.NoError(t, err) diff --git a/bundle/deploy/terraform/tfdyn/convert_model_test.go b/bundle/deploy/terraform/tfdyn/convert_model_test.go index 0b36034514..3d7e8b22c4 100644 --- a/bundle/deploy/terraform/tfdyn/convert_model_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_model_test.go @@ -1,7 +1,6 @@ package tfdyn import ( - "context" "testing" "github.com/databricks/cli/bundle/config/resources" @@ -40,7 +39,7 @@ func TestConvertModel(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = modelConverter{}.Convert(ctx, "my_model", vin, out) require.NoError(t, err) diff --git a/bundle/deploy/terraform/tfdyn/convert_permissions_test.go b/bundle/deploy/terraform/tfdyn/convert_permissions_test.go index e145419e8a..4d0d2d7481 100644 --- a/bundle/deploy/terraform/tfdyn/convert_permissions_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_permissions_test.go @@ -1,7 +1,6 @@ package tfdyn import ( - "context" "testing" "github.com/databricks/cli/bundle/config/resources" @@ -33,7 +32,7 @@ func TestConvertPermissions(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() resource := convertPermissionsResource(ctx, vin) require.NotNil(t, resource) assert.Equal(t, []schema.ResourcePermissionsAccessControl{ @@ -66,7 +65,7 @@ func TestConvertPermissionsNil(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() resource := convertPermissionsResource(ctx, vin) assert.Nil(t, resource) } @@ -79,7 +78,7 @@ func TestConvertPermissionsEmpty(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() resource := convertPermissionsResource(ctx, vin) assert.Nil(t, resource) } diff --git a/bundle/deploy/terraform/tfdyn/convert_pipeline_test.go b/bundle/deploy/terraform/tfdyn/convert_pipeline_test.go index ed6bd70a08..f16b6b8595 100644 --- a/bundle/deploy/terraform/tfdyn/convert_pipeline_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_pipeline_test.go @@ -1,7 +1,6 @@ package tfdyn import ( - "context" "testing" "github.com/databricks/cli/bundle/config/resources" @@ -76,7 +75,7 @@ func TestConvertPipeline(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = pipelineConverter{}.Convert(ctx, "my_pipeline", vin, out) require.NoError(t, err) diff --git a/bundle/deploy/terraform/tfdyn/convert_postgres_branch_test.go b/bundle/deploy/terraform/tfdyn/convert_postgres_branch_test.go index db30cad2fb..0f8040caf1 100644 --- a/bundle/deploy/terraform/tfdyn/convert_postgres_branch_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_postgres_branch_test.go @@ -1,7 +1,6 @@ package tfdyn import ( - "context" "testing" "time" @@ -30,7 +29,7 @@ func TestConvertPostgresBranch(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = postgresBranchConverter{}.Convert(ctx, "my_postgres_branch", vin, out) require.NoError(t, err) @@ -62,7 +61,7 @@ func TestConvertPostgresBranchWithSourceBranch(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = postgresBranchConverter{}.Convert(ctx, "feature_postgres_branch", vin, out) require.NoError(t, err) @@ -90,7 +89,7 @@ func TestConvertPostgresBranchMinimal(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = postgresBranchConverter{}.Convert(ctx, "minimal_postgres_branch", vin, out) require.NoError(t, err) diff --git a/bundle/deploy/terraform/tfdyn/convert_postgres_endpoint_test.go b/bundle/deploy/terraform/tfdyn/convert_postgres_endpoint_test.go index 4459d7cd42..27f6ec5391 100644 --- a/bundle/deploy/terraform/tfdyn/convert_postgres_endpoint_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_postgres_endpoint_test.go @@ -1,7 +1,6 @@ package tfdyn import ( - "context" "testing" "time" @@ -32,7 +31,7 @@ func TestConvertPostgresEndpoint(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = postgresEndpointConverter{}.Convert(ctx, "my_postgres_endpoint", vin, out) require.NoError(t, err) @@ -65,7 +64,7 @@ func TestConvertPostgresEndpointReadOnly(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = postgresEndpointConverter{}.Convert(ctx, "readonly_postgres_endpoint", vin, out) require.NoError(t, err) @@ -107,7 +106,7 @@ func TestConvertPostgresEndpointWithSettings(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = postgresEndpointConverter{}.Convert(ctx, "settings_postgres_endpoint", vin, out) require.NoError(t, err) diff --git a/bundle/deploy/terraform/tfdyn/convert_postgres_project_test.go b/bundle/deploy/terraform/tfdyn/convert_postgres_project_test.go index d403569b2d..271ac2f985 100644 --- a/bundle/deploy/terraform/tfdyn/convert_postgres_project_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_postgres_project_test.go @@ -1,7 +1,6 @@ package tfdyn import ( - "context" "testing" "time" @@ -35,7 +34,7 @@ func TestConvertPostgresProject(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = postgresProjectConverter{}.Convert(ctx, "my_postgres_project", vin, out) require.NoError(t, err) @@ -80,7 +79,7 @@ func TestConvertPostgresProjectWithPermissions(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = postgresProjectConverter{}.Convert(ctx, "my_postgres_project", vin, out) require.NoError(t, err) @@ -119,7 +118,7 @@ func TestConvertPostgresProjectMinimal(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = postgresProjectConverter{}.Convert(ctx, "minimal_postgres_project", vin, out) require.NoError(t, err) diff --git a/bundle/deploy/terraform/tfdyn/convert_quality_monitor_test.go b/bundle/deploy/terraform/tfdyn/convert_quality_monitor_test.go index 4e457ca3b3..ad14945ff5 100644 --- a/bundle/deploy/terraform/tfdyn/convert_quality_monitor_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_quality_monitor_test.go @@ -1,7 +1,6 @@ package tfdyn import ( - "context" "testing" "github.com/databricks/cli/bundle/config/resources" @@ -28,7 +27,7 @@ func TestConvertQualityMonitor(t *testing.T) { } vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = qualityMonitorConverter{}.Convert(ctx, "my_monitor", vin, out) diff --git a/bundle/deploy/terraform/tfdyn/convert_registered_model_test.go b/bundle/deploy/terraform/tfdyn/convert_registered_model_test.go index 633ec3eee4..04bf331502 100644 --- a/bundle/deploy/terraform/tfdyn/convert_registered_model_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_registered_model_test.go @@ -1,7 +1,6 @@ package tfdyn import ( - "context" "testing" "github.com/databricks/cli/bundle/config/resources" @@ -32,7 +31,7 @@ func TestConvertRegisteredModel(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = registeredModelConverter{}.Convert(ctx, "my_registered_model", vin, out) require.NoError(t, err) diff --git a/bundle/deploy/terraform/tfdyn/convert_schema_test.go b/bundle/deploy/terraform/tfdyn/convert_schema_test.go index cb5ea0d1ca..ec738d3ef0 100644 --- a/bundle/deploy/terraform/tfdyn/convert_schema_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_schema_test.go @@ -1,7 +1,6 @@ package tfdyn import ( - "context" "testing" "github.com/databricks/cli/bundle/config/resources" @@ -44,7 +43,7 @@ func TestConvertSchema(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = schemaConverter{}.Convert(ctx, "my_schema", vin, out) require.NoError(t, err) diff --git a/bundle/deploy/terraform/tfdyn/convert_secret_scope_test.go b/bundle/deploy/terraform/tfdyn/convert_secret_scope_test.go index d63673a1e6..f508ff7526 100644 --- a/bundle/deploy/terraform/tfdyn/convert_secret_scope_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_secret_scope_test.go @@ -1,7 +1,6 @@ package tfdyn import ( - "context" "testing" "github.com/databricks/cli/bundle/config/resources" @@ -25,7 +24,7 @@ func TestConvertSecretScopeWithPermissions(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = secretScopeConverter{}.Convert(ctx, "my_scope", vin, out) require.NoError(t, err) @@ -69,7 +68,7 @@ func TestConvertSecretScopeSinglePermission(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = secretScopeConverter{}.Convert(ctx, "single_scope", vin, out) require.NoError(t, err) @@ -89,7 +88,7 @@ func TestConvertSecretScopeNoPermissions(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = secretScopeConverter{}.Convert(ctx, "no_permissions_scope", vin, out) require.NoError(t, err) diff --git a/bundle/deploy/terraform/tfdyn/convert_sql_warehouse_test.go b/bundle/deploy/terraform/tfdyn/convert_sql_warehouse_test.go index 05e58121bf..a8be3a12d6 100644 --- a/bundle/deploy/terraform/tfdyn/convert_sql_warehouse_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_sql_warehouse_test.go @@ -1,7 +1,6 @@ package tfdyn import ( - "context" "testing" "github.com/databricks/cli/bundle/config/resources" @@ -39,7 +38,7 @@ func TestConvertSqlWarehouse(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = sqlWarehouseConverter{}.Convert(ctx, "test_sql_warehouse", vin, out) require.NoError(t, err) diff --git a/bundle/deploy/terraform/tfdyn/convert_volume_test.go b/bundle/deploy/terraform/tfdyn/convert_volume_test.go index 92c64212b9..6eb344853d 100644 --- a/bundle/deploy/terraform/tfdyn/convert_volume_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_volume_test.go @@ -1,7 +1,6 @@ package tfdyn import ( - "context" "testing" "github.com/databricks/cli/bundle/config/resources" @@ -42,7 +41,7 @@ func TestConvertVolume(t *testing.T) { vin, err := convert.FromTyped(src, dyn.NilValue) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() out := schema.NewResources() err = volumeConverter{}.Convert(ctx, "my_volume", vin, out) require.NoError(t, err) diff --git a/bundle/deploy/terraform/util_test.go b/bundle/deploy/terraform/util_test.go index 5b32fd16d5..3e4e6eb636 100644 --- a/bundle/deploy/terraform/util_test.go +++ b/bundle/deploy/terraform/util_test.go @@ -1,7 +1,6 @@ package terraform import ( - "context" "os" "path/filepath" "testing" @@ -23,13 +22,13 @@ func TestParseResourcesStateWithNoFile(t *testing.T) { }, }, } - state, err := ParseResourcesState(context.Background(), b) + state, err := ParseResourcesState(t.Context(), b) assert.NoError(t, err) assert.Equal(t, ExportedResourcesMap(nil), state) } func TestParseResourcesStateWithExistingStateFile(t *testing.T) { - ctx := context.Background() + ctx := t.Context() b := &bundle.Bundle{ BundleRootPath: t.TempDir(), Config: config.Root{ diff --git a/bundle/direct/dresources/all_test.go b/bundle/direct/dresources/all_test.go index 664f01b7f7..124d9a4ec9 100644 --- a/bundle/direct/dresources/all_test.go +++ b/bundle/direct/dresources/all_test.go @@ -242,12 +242,12 @@ var testConfig map[string]any = map[string]any{ }, } -type prepareWorkspace func(client *databricks.WorkspaceClient) (any, error) +type prepareWorkspace func(ctx context.Context, client *databricks.WorkspaceClient) (any, error) // some resource require other resources to exist var testDeps = map[string]prepareWorkspace{ - "database_catalogs": func(client *databricks.WorkspaceClient) (any, error) { - _, err := client.Database.CreateDatabaseInstance(context.Background(), database.CreateDatabaseInstanceRequest{ + "database_catalogs": func(ctx context.Context, client *databricks.WorkspaceClient) (any, error) { + _, err := client.Database.CreateDatabaseInstance(ctx, database.CreateDatabaseInstanceRequest{ DatabaseInstance: database.DatabaseInstance{ Name: "mydbinstance1", }, @@ -261,8 +261,8 @@ var testDeps = map[string]prepareWorkspace{ }, err }, - "jobs.permissions": func(client *databricks.WorkspaceClient) (any, error) { - resp, err := client.Jobs.Create(context.Background(), jobs.CreateJob{ + "jobs.permissions": func(ctx context.Context, client *databricks.WorkspaceClient) (any, error) { + resp, err := client.Jobs.Create(ctx, jobs.CreateJob{ Name: "job-permissions", Tasks: []jobs.Task{ { @@ -286,8 +286,8 @@ var testDeps = map[string]prepareWorkspace{ }, nil }, - "pipelines.permissions": func(client *databricks.WorkspaceClient) (any, error) { - resp, err := client.Pipelines.Create(context.Background(), pipelines.CreatePipeline{ + "pipelines.permissions": func(ctx context.Context, client *databricks.WorkspaceClient) (any, error) { + resp, err := client.Pipelines.Create(ctx, pipelines.CreatePipeline{ Name: "pipeline-permissions", }) if err != nil { @@ -303,8 +303,8 @@ var testDeps = map[string]prepareWorkspace{ }, nil }, - "models.permissions": func(client *databricks.WorkspaceClient) (any, error) { - resp, err := client.ModelRegistry.CreateModel(context.Background(), ml.CreateModelRequest{ + "models.permissions": func(ctx context.Context, client *databricks.WorkspaceClient) (any, error) { + resp, err := client.ModelRegistry.CreateModel(ctx, ml.CreateModelRequest{ Name: "model-permissions", Description: "model for permissions testing", }) @@ -321,8 +321,8 @@ var testDeps = map[string]prepareWorkspace{ }, nil }, - "experiments.permissions": func(client *databricks.WorkspaceClient) (any, error) { - resp, err := client.Experiments.CreateExperiment(context.Background(), ml.CreateExperiment{ + "experiments.permissions": func(ctx context.Context, client *databricks.WorkspaceClient) (any, error) { + resp, err := client.Experiments.CreateExperiment(ctx, ml.CreateExperiment{ Name: "experiment-permissions", }) if err != nil { @@ -338,7 +338,7 @@ var testDeps = map[string]prepareWorkspace{ }, nil }, - "clusters.permissions": func(client *databricks.WorkspaceClient) (any, error) { + "clusters.permissions": func(ctx context.Context, client *databricks.WorkspaceClient) (any, error) { return &PermissionsState{ ObjectID: "/clusters/cluster-permissions", Permissions: []iam.AccessControlRequest{{ @@ -348,8 +348,8 @@ var testDeps = map[string]prepareWorkspace{ }, nil }, - "apps.permissions": func(client *databricks.WorkspaceClient) (any, error) { - waiter, err := client.Apps.Create(context.Background(), apps.CreateAppRequest{ + "apps.permissions": func(ctx context.Context, client *databricks.WorkspaceClient) (any, error) { + waiter, err := client.Apps.Create(ctx, apps.CreateAppRequest{ App: apps.App{ Name: "app-permissions", }, @@ -367,7 +367,7 @@ var testDeps = map[string]prepareWorkspace{ }, nil }, - "sql_warehouses.permissions": func(client *databricks.WorkspaceClient) (any, error) { + "sql_warehouses.permissions": func(ctx context.Context, client *databricks.WorkspaceClient) (any, error) { return &PermissionsState{ ObjectID: "/sql/warehouses/warehouse-permissions", Permissions: []iam.AccessControlRequest{{ @@ -377,8 +377,8 @@ var testDeps = map[string]prepareWorkspace{ }, nil }, - "database_instances.permissions": func(client *databricks.WorkspaceClient) (any, error) { - waiter, err := client.Database.CreateDatabaseInstance(context.Background(), database.CreateDatabaseInstanceRequest{ + "database_instances.permissions": func(ctx context.Context, client *databricks.WorkspaceClient) (any, error) { + waiter, err := client.Database.CreateDatabaseInstance(ctx, database.CreateDatabaseInstanceRequest{ DatabaseInstance: database.DatabaseInstance{ Name: "dbinstance-permissions", }, @@ -396,14 +396,14 @@ var testDeps = map[string]prepareWorkspace{ }, nil }, - "postgres_projects.permissions": func(client *databricks.WorkspaceClient) (any, error) { - waiter, err := client.Postgres.CreateProject(context.Background(), postgres.CreateProjectRequest{ + "postgres_projects.permissions": func(ctx context.Context, client *databricks.WorkspaceClient) (any, error) { + waiter, err := client.Postgres.CreateProject(ctx, postgres.CreateProjectRequest{ ProjectId: "permissions-project", }) if err != nil { return nil, err } - result, err := waiter.Wait(context.Background()) + result, err := waiter.Wait(ctx) if err != nil { return nil, err } @@ -418,8 +418,7 @@ var testDeps = map[string]prepareWorkspace{ }, nil }, - "dashboards.permissions": func(client *databricks.WorkspaceClient) (any, error) { - ctx := context.Background() + "dashboards.permissions": func(ctx context.Context, client *databricks.WorkspaceClient) (any, error) { parentPath := "/Workspace/Users/user@example.com" // Create parent directory if it doesn't exist @@ -448,8 +447,8 @@ var testDeps = map[string]prepareWorkspace{ }, nil }, - "model_serving_endpoints.permissions": func(client *databricks.WorkspaceClient) (any, error) { - waiter, err := client.ServingEndpoints.Create(context.Background(), serving.CreateServingEndpoint{ + "model_serving_endpoints.permissions": func(ctx context.Context, client *databricks.WorkspaceClient) (any, error) { + waiter, err := client.ServingEndpoints.Create(ctx, serving.CreateServingEndpoint{ Name: "endpoint-permissions", Config: &serving.EndpointCoreConfigInput{ ServedModels: []serving.ServedModelInput{ @@ -475,8 +474,8 @@ var testDeps = map[string]prepareWorkspace{ }, nil }, - "alerts.permissions": func(client *databricks.WorkspaceClient) (any, error) { - resp, err := client.AlertsV2.CreateAlert(context.Background(), sql.CreateAlertV2Request{ + "alerts.permissions": func(ctx context.Context, client *databricks.WorkspaceClient) (any, error) { + resp, err := client.AlertsV2.CreateAlert(ctx, sql.CreateAlertV2Request{ Alert: sql.AlertV2{ DisplayName: "alert-permissions", QueryText: "SELECT 1", @@ -506,7 +505,7 @@ var testDeps = map[string]prepareWorkspace{ }, nil }, - "catalogs.grants": func(client *databricks.WorkspaceClient) (any, error) { + "catalogs.grants": func(ctx context.Context, client *databricks.WorkspaceClient) (any, error) { return &GrantsState{ SecurableType: "catalog", FullName: "mycatalog", @@ -517,7 +516,7 @@ var testDeps = map[string]prepareWorkspace{ }, nil }, - "external_locations.grants": func(client *databricks.WorkspaceClient) (any, error) { + "external_locations.grants": func(ctx context.Context, client *databricks.WorkspaceClient) (any, error) { return &GrantsState{ SecurableType: "external_location", FullName: "myexternallocation", @@ -528,7 +527,7 @@ var testDeps = map[string]prepareWorkspace{ }, nil }, - "schemas.grants": func(client *databricks.WorkspaceClient) (any, error) { + "schemas.grants": func(ctx context.Context, client *databricks.WorkspaceClient) (any, error) { return &GrantsState{ SecurableType: "schema", FullName: "main.myschema", @@ -539,7 +538,7 @@ var testDeps = map[string]prepareWorkspace{ }, nil }, - "volumes.grants": func(client *databricks.WorkspaceClient) (any, error) { + "volumes.grants": func(ctx context.Context, client *databricks.WorkspaceClient) (any, error) { return &GrantsState{ SecurableType: "volume", FullName: "main.myschema.myvolume", @@ -550,7 +549,7 @@ var testDeps = map[string]prepareWorkspace{ }, nil }, - "registered_models.grants": func(client *databricks.WorkspaceClient) (any, error) { + "registered_models.grants": func(ctx context.Context, client *databricks.WorkspaceClient) (any, error) { return &GrantsState{ SecurableType: "registered-model", FullName: "modelid", @@ -561,8 +560,8 @@ var testDeps = map[string]prepareWorkspace{ }, nil }, - "secret_scopes.permissions": func(client *databricks.WorkspaceClient) (any, error) { - err := client.Secrets.CreateScope(context.Background(), workspace.CreateScope{ + "secret_scopes.permissions": func(ctx context.Context, client *databricks.WorkspaceClient) (any, error) { + err := client.Secrets.CreateScope(ctx, workspace.CreateScope{ Scope: "permissions_test_scope", ScopeBackendType: workspace.ScopeBackendTypeAzureKeyvault, BackendAzureKeyvault: &workspace.AzureKeyVaultSecretScopeMetadata{ @@ -585,9 +584,9 @@ var testDeps = map[string]prepareWorkspace{ }, nil }, - "postgres_branches": func(client *databricks.WorkspaceClient) (any, error) { + "postgres_branches": func(ctx context.Context, client *databricks.WorkspaceClient) (any, error) { // Create parent project first - _, err := client.Postgres.CreateProject(context.Background(), postgres.CreateProjectRequest{ + _, err := client.Postgres.CreateProject(ctx, postgres.CreateProjectRequest{ ProjectId: "test-project-for-branch", Project: postgres.Project{ Spec: &postgres.ProjectSpec{ @@ -609,9 +608,9 @@ var testDeps = map[string]prepareWorkspace{ }, nil }, - "postgres_endpoints": func(client *databricks.WorkspaceClient) (any, error) { + "postgres_endpoints": func(ctx context.Context, client *databricks.WorkspaceClient) (any, error) { // Create parent project first - _, err := client.Postgres.CreateProject(context.Background(), postgres.CreateProjectRequest{ + _, err := client.Postgres.CreateProject(ctx, postgres.CreateProjectRequest{ ProjectId: "test-project-for-endpoint", Project: postgres.Project{ Spec: &postgres.ProjectSpec{ @@ -625,7 +624,7 @@ var testDeps = map[string]prepareWorkspace{ } // Create parent branch - _, err = client.Postgres.CreateBranch(context.Background(), postgres.CreateBranchRequest{ + _, err = client.Postgres.CreateBranch(ctx, postgres.CreateBranchRequest{ Parent: "projects/test-project-for-endpoint", BranchId: "test-branch-for-endpoint", Branch: postgres.Branch{}, @@ -724,7 +723,7 @@ func testCRUD(t *testing.T, group string, adapter *Adapter, client *databricks.W prepDeps, hasDeps := testDeps[group] if hasDeps { - inputConfig, err = prepDeps(client) + inputConfig, err = prepDeps(t.Context(), client) require.NoError(t, err) } else { var ok bool @@ -743,7 +742,7 @@ func testCRUD(t *testing.T, group string, adapter *Adapter, client *databricks.W newState, err := adapter.PrepareState(inputConfig) require.NoError(t, err, "PrepareState failed") - ctx := context.Background() + ctx := t.Context() // initial DoRead() cannot find the resource remote, err := adapter.DoRead(ctx, "1234") diff --git a/bundle/direct/dresources/app_test.go b/bundle/direct/dresources/app_test.go index a844ee41e1..e0eeed5b77 100644 --- a/bundle/direct/dresources/app_test.go +++ b/bundle/direct/dresources/app_test.go @@ -1,7 +1,6 @@ package dresources import ( - "context" "testing" "github.com/databricks/cli/libs/testserver" @@ -57,7 +56,7 @@ func TestAppDoCreate_RetriesWhenAppIsDeleting(t *testing.T) { require.NoError(t, err) r := (&ResourceApp{}).New(client) - ctx := context.Background() + ctx := t.Context() name, _, err := r.DoCreate(ctx, &apps.App{Name: "test-app"}) require.NoError(t, err) @@ -113,7 +112,7 @@ func TestAppDoCreate_RetriesWhenGetReturnsNotFound(t *testing.T) { require.NoError(t, err) r := (&ResourceApp{}).New(client) - ctx := context.Background() + ctx := t.Context() name, _, err := r.DoCreate(ctx, &apps.App{Name: "test-app"}) require.NoError(t, err) diff --git a/bundle/direct/dresources/schema_test.go b/bundle/direct/dresources/schema_test.go index 89f1c4d3c2..f22e3d87ce 100644 --- a/bundle/direct/dresources/schema_test.go +++ b/bundle/direct/dresources/schema_test.go @@ -1,7 +1,6 @@ package dresources import ( - "context" "encoding/json" "testing" @@ -14,7 +13,7 @@ func TestResourceSchema_DoUpdate_WithUnsupportedForceSendFields(t *testing.T) { _, client := setupTestServerClient(t) adapter := (*ResourceSchema)(nil).New(client) - ctx := context.Background() + ctx := t.Context() config := &catalog.CreateSchema{ CatalogName: "main", diff --git a/bundle/env/env_test.go b/bundle/env/env_test.go index d900242e0b..57de2c5dc3 100644 --- a/bundle/env/env_test.go +++ b/bundle/env/env_test.go @@ -1,7 +1,6 @@ package env import ( - "context" "testing" "github.com/databricks/cli/internal/testutil" @@ -13,12 +12,12 @@ func TestGetWithRealEnvSingleVariable(t *testing.T) { testutil.CleanupEnvironment(t) t.Setenv("v1", "foo") - v, ok := get(context.Background(), []string{"v1"}) + v, ok := get(t.Context(), []string{"v1"}) require.True(t, ok) assert.Equal(t, "foo", v) // Not set. - v, ok = get(context.Background(), []string{"v2"}) + v, ok = get(t.Context(), []string{"v2"}) require.False(t, ok) assert.Equal(t, "", v) } @@ -32,13 +31,13 @@ func TestGetWithRealEnvMultipleVariables(t *testing.T) { {"v2", "v3", "v1"}, {"v3", "v1", "v2"}, } { - v, ok := get(context.Background(), vars) + v, ok := get(t.Context(), vars) require.True(t, ok) assert.Equal(t, "foo", v) } // Not set. - v, ok := get(context.Background(), []string{"v2", "v3", "v4"}) + v, ok := get(t.Context(), []string{"v2", "v3", "v4"}) require.False(t, ok) assert.Equal(t, "", v) } diff --git a/bundle/env/root_test.go b/bundle/env/root_test.go index fc2d6e2069..5e2e59995b 100644 --- a/bundle/env/root_test.go +++ b/bundle/env/root_test.go @@ -1,7 +1,6 @@ package env import ( - "context" "testing" "github.com/databricks/cli/internal/testutil" @@ -9,7 +8,7 @@ import ( ) func TestRoot(t *testing.T) { - ctx := context.Background() + ctx := t.Context() testutil.CleanupEnvironment(t) diff --git a/bundle/env/target_test.go b/bundle/env/target_test.go index 0c15bf9177..9d9029f92e 100644 --- a/bundle/env/target_test.go +++ b/bundle/env/target_test.go @@ -1,7 +1,6 @@ package env import ( - "context" "testing" "github.com/databricks/cli/internal/testutil" @@ -9,7 +8,7 @@ import ( ) func TestTarget(t *testing.T) { - ctx := context.Background() + ctx := t.Context() testutil.CleanupEnvironment(t) diff --git a/bundle/env/temp_dir_test.go b/bundle/env/temp_dir_test.go index 7659bac6dd..2a39bcc875 100644 --- a/bundle/env/temp_dir_test.go +++ b/bundle/env/temp_dir_test.go @@ -1,7 +1,6 @@ package env import ( - "context" "testing" "github.com/databricks/cli/internal/testutil" @@ -9,7 +8,7 @@ import ( ) func TestTempDir(t *testing.T) { - ctx := context.Background() + ctx := t.Context() testutil.CleanupEnvironment(t) diff --git a/bundle/generate/downloader_test.go b/bundle/generate/downloader_test.go index 3f4dba6aad..d0877ac3d2 100644 --- a/bundle/generate/downloader_test.go +++ b/bundle/generate/downloader_test.go @@ -1,7 +1,6 @@ package generate import ( - "context" "path/filepath" "testing" @@ -12,7 +11,7 @@ import ( ) func TestDownloader_MarkFileReturnsRelativePath(t *testing.T) { - ctx := context.Background() + ctx := t.Context() m := mocks.NewMockWorkspaceClient(t) dir := "base/dir/doesnt/matter" @@ -42,7 +41,7 @@ func TestDownloader_MarkFileReturnsRelativePath(t *testing.T) { } func TestDownloader_DoesNotRecurseIntoNodeModules(t *testing.T) { - ctx := context.Background() + ctx := t.Context() m := mocks.NewMockWorkspaceClient(t) dir := "base/dir" diff --git a/bundle/internal/bundletest/benchmark.go b/bundle/internal/bundletest/benchmark.go index 1041995756..59647d814f 100644 --- a/bundle/internal/bundletest/benchmark.go +++ b/bundle/internal/bundletest/benchmark.go @@ -231,7 +231,7 @@ func BundleV(b *testing.B, numJobs int) dyn.Value { } // Apply noop mutator to initialize the bundle value. - bundle.ApplyFuncContext(context.Background(), &myBundle, func(ctx context.Context, b *bundle.Bundle) {}) + bundle.ApplyFuncContext(b.Context(), &myBundle, func(ctx context.Context, b *bundle.Bundle) {}) return myBundle.Config.Value() } @@ -262,7 +262,7 @@ func Bundle(b *testing.B, numJobs int) *bundle.Bundle { } // Apply noop mutator to initialize the bundle value. - bundle.ApplyFuncContext(context.Background(), &myBundle, func(ctx context.Context, b *bundle.Bundle) {}) + bundle.ApplyFuncContext(b.Context(), &myBundle, func(ctx context.Context, b *bundle.Bundle) {}) return &myBundle } diff --git a/bundle/internal/bundletest/mutate.go b/bundle/internal/bundletest/mutate.go index c549c09833..00adc7d29e 100644 --- a/bundle/internal/bundletest/mutate.go +++ b/bundle/internal/bundletest/mutate.go @@ -10,7 +10,7 @@ import ( ) func Mutate(t *testing.T, b *bundle.Bundle, f func(v dyn.Value) (dyn.Value, error)) { - bundle.ApplyFuncContext(context.Background(), b, func(ctx context.Context, b *bundle.Bundle) { + bundle.ApplyFuncContext(t.Context(), b, func(ctx context.Context, b *bundle.Bundle) { err := b.Config.Mutate(f) require.NoError(t, err) }) diff --git a/bundle/internal/bundletest/mutator_benchmark_test.go b/bundle/internal/bundletest/mutator_benchmark_test.go index d49f644623..03d63dcd07 100644 --- a/bundle/internal/bundletest/mutator_benchmark_test.go +++ b/bundle/internal/bundletest/mutator_benchmark_test.go @@ -16,7 +16,7 @@ func benchmarkRequiredMutator(b *testing.B, numJobs int) { var diags diag.Diagnostics for b.Loop() { - diags = bundle.Apply(context.Background(), myBundle, validate.Required()) + diags = bundle.Apply(b.Context(), myBundle, validate.Required()) } assert.NotEmpty(b, diags) } @@ -26,7 +26,7 @@ func benchmarkEnumMutator(b *testing.B, numJobs int) { var diags diag.Diagnostics for b.Loop() { - diags = bundle.Apply(context.Background(), myBundle, validate.Enum()) + diags = bundle.Apply(b.Context(), myBundle, validate.Enum()) } assert.NotEmpty(b, diags) } @@ -36,7 +36,7 @@ func benchmarkWalkReadOnlyBaseline(b *testing.B, numJobs int) { for b.Loop() { var paths []dyn.Path - bundle.ApplyFuncContext(context.Background(), myBundle, func(ctx context.Context, b *bundle.Bundle) { + bundle.ApplyFuncContext(b.Context(), myBundle, func(ctx context.Context, b *bundle.Bundle) { _ = dyn.WalkReadOnly(b.Config.Value(), func(p dyn.Path, v dyn.Value) error { paths = append(paths, p) return nil @@ -49,7 +49,7 @@ func benchmarkNoopBaseline(b *testing.B, numJobs int) { myBundle := Bundle(b, numJobs) for b.Loop() { - bundle.ApplyFuncContext(context.Background(), myBundle, func(ctx context.Context, b *bundle.Bundle) {}) + bundle.ApplyFuncContext(b.Context(), myBundle, func(ctx context.Context, b *bundle.Bundle) {}) } } diff --git a/bundle/libraries/expand_glob_references_test.go b/bundle/libraries/expand_glob_references_test.go index 47f77717c6..44ffe97a6e 100644 --- a/bundle/libraries/expand_glob_references_test.go +++ b/bundle/libraries/expand_glob_references_test.go @@ -1,7 +1,6 @@ package libraries import ( - "context" "path/filepath" "testing" @@ -66,7 +65,7 @@ func TestGlobReferencesExpandedForTaskLibraries(t *testing.T) { bundletest.SetLocation(b, ".", []dyn.Location{{File: filepath.Join(dir, "resource.yml")}}) - diags := bundle.Apply(context.Background(), b, ExpandGlobReferences()) + diags := bundle.Apply(t.Context(), b, ExpandGlobReferences()) require.Empty(t, diags) job := b.Config.Resources.Jobs["job"] @@ -151,7 +150,7 @@ func TestGlobReferencesExpandedForForeachTaskLibraries(t *testing.T) { bundletest.SetLocation(b, ".", []dyn.Location{{File: filepath.Join(dir, "resource.yml")}}) - diags := bundle.Apply(context.Background(), b, ExpandGlobReferences()) + diags := bundle.Apply(t.Context(), b, ExpandGlobReferences()) require.Empty(t, diags) job := b.Config.Resources.Jobs["job"] @@ -226,7 +225,7 @@ func TestGlobReferencesExpandedForEnvironmentsDeps(t *testing.T) { bundletest.SetLocation(b, ".", []dyn.Location{{File: filepath.Join(dir, "resource.yml")}}) - diags := bundle.Apply(context.Background(), b, ExpandGlobReferences()) + diags := bundle.Apply(t.Context(), b, ExpandGlobReferences()) require.Empty(t, diags) job := b.Config.Resources.Jobs["job"] @@ -280,7 +279,7 @@ func TestExpandGlobReferencesPreservesLocations(t *testing.T) { loc := dyn.Location{File: filepath.Join(dir, "resource.yml"), Line: 10, Column: 5} bundletest.SetLocation(b, ".", []dyn.Location{loc}) - diags := bundle.Apply(context.Background(), b, ExpandGlobReferences()) + diags := bundle.Apply(t.Context(), b, ExpandGlobReferences()) require.Empty(t, diags) libs, err := dyn.GetByPath(b.Config.Value(), dyn.MustPathFromString("resources.jobs.job.tasks[0].libraries")) diff --git a/bundle/libraries/filer_test.go b/bundle/libraries/filer_test.go index 258a88dad1..f3de3e41e7 100644 --- a/bundle/libraries/filer_test.go +++ b/bundle/libraries/filer_test.go @@ -1,7 +1,6 @@ package libraries import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -26,7 +25,7 @@ func TestGetFilerForLibrariesValidWsfs(t *testing.T) { m.WorkspaceClient.Config = &databrickscfg.Config{} b.SetWorkpaceClient(m.WorkspaceClient) - client, uploadPath, diags := GetFilerForLibraries(context.Background(), b) + client, uploadPath, diags := GetFilerForLibraries(t.Context(), b) require.NoError(t, diags.Error()) assert.Equal(t, "/Workspace/foo/bar/artifacts/.internal", uploadPath) @@ -46,7 +45,7 @@ func TestGetFilerForLibrariesCleanupValidWsfs(t *testing.T) { m.WorkspaceClient.Config = &databrickscfg.Config{} b.SetWorkpaceClient(m.WorkspaceClient) - client, uploadPath, diags := GetFilerForLibrariesCleanup(context.Background(), b) + client, uploadPath, diags := GetFilerForLibrariesCleanup(t.Context(), b) require.NoError(t, diags.Error()) assert.Equal(t, "/Workspace/foo/bar/artifacts", uploadPath) @@ -66,7 +65,7 @@ func TestGetFilerForLibrariesValidUcVolume(t *testing.T) { m.WorkspaceClient.Config = &databrickscfg.Config{} b.SetWorkpaceClient(m.WorkspaceClient) - client, uploadPath, diags := GetFilerForLibraries(context.Background(), b) + client, uploadPath, diags := GetFilerForLibraries(t.Context(), b) require.NoError(t, diags.Error()) assert.Equal(t, "/Volumes/main/my_schema/my_volume/.internal", uploadPath) @@ -86,7 +85,7 @@ func TestGetFilerForLibrariesCleanupValidUcVolume(t *testing.T) { m.WorkspaceClient.Config = &databrickscfg.Config{} b.SetWorkpaceClient(m.WorkspaceClient) - client, uploadPath, diags := GetFilerForLibrariesCleanup(context.Background(), b) + client, uploadPath, diags := GetFilerForLibrariesCleanup(t.Context(), b) require.NoError(t, diags.Error()) assert.Equal(t, "/Volumes/main/my_schema/my_volume", uploadPath) @@ -104,6 +103,6 @@ func TestGetFilerForLibrariesRemotePathNotSet(t *testing.T) { m.WorkspaceClient.Config = &databrickscfg.Config{} b.SetWorkpaceClient(m.WorkspaceClient) - _, _, diags := GetFilerForLibraries(context.Background(), b) + _, _, diags := GetFilerForLibraries(t.Context(), b) require.EqualError(t, diags.Error(), "remote artifact path not configured") } diff --git a/bundle/libraries/match_test.go b/bundle/libraries/match_test.go index bf06cb2168..e19b8e1c7c 100644 --- a/bundle/libraries/match_test.go +++ b/bundle/libraries/match_test.go @@ -1,7 +1,6 @@ package libraries import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -42,7 +41,7 @@ func TestValidateEnvironments(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, ExpandGlobReferences()) + diags := bundle.Apply(t.Context(), b, ExpandGlobReferences()) require.Nil(t, diags) } @@ -74,7 +73,7 @@ func TestValidateEnvironmentsNoFile(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, ExpandGlobReferences()) + diags := bundle.Apply(t.Context(), b, ExpandGlobReferences()) require.Len(t, diags, 1) require.Equal(t, "file doesn't exist ./wheel.whl", diags[0].Summary) } @@ -109,7 +108,7 @@ func TestValidateTaskLibraries(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, ExpandGlobReferences()) + diags := bundle.Apply(t.Context(), b, ExpandGlobReferences()) require.Nil(t, diags) } @@ -142,7 +141,7 @@ func TestValidateTaskLibrariesNoFile(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, ExpandGlobReferences()) + diags := bundle.Apply(t.Context(), b, ExpandGlobReferences()) require.Len(t, diags, 1) require.Equal(t, "file doesn't exist ./wheel.whl", diags[0].Summary) } diff --git a/bundle/mutator_test.go b/bundle/mutator_test.go index 95bcf4994b..e4504d657b 100644 --- a/bundle/mutator_test.go +++ b/bundle/mutator_test.go @@ -37,7 +37,7 @@ func TestMutator(t *testing.T) { } b := &Bundle{} - diags := Apply(context.Background(), b, m) + diags := Apply(t.Context(), b, m) assert.NoError(t, diags.Error()) assert.Equal(t, 1, m.applyCalled) diff --git a/bundle/permissions/permission_diagnostics_test.go b/bundle/permissions/permission_diagnostics_test.go index 892f122ded..e5a9214f43 100644 --- a/bundle/permissions/permission_diagnostics_test.go +++ b/bundle/permissions/permission_diagnostics_test.go @@ -1,7 +1,6 @@ package permissions_test import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -18,14 +17,14 @@ func TestPermissionDiagnosticsApplySuccess(t *testing.T) { {Level: "CAN_MANAGE", UserName: "testuser@databricks.com"}, }) - diags := bundle.Apply(context.Background(), b, permissions.PermissionDiagnostics()) + diags := bundle.Apply(t.Context(), b, permissions.PermissionDiagnostics()) require.NoError(t, diags.Error()) } func TestPermissionDiagnosticsEmpty(t *testing.T) { b := mockBundle(nil) - diags := bundle.Apply(context.Background(), b, permissions.PermissionDiagnostics()) + diags := bundle.Apply(t.Context(), b, permissions.PermissionDiagnostics()) require.NoError(t, diags.Error()) } @@ -34,7 +33,7 @@ func TestPermissionDiagnosticsApplyFail(t *testing.T) { {Level: "CAN_VIEW", UserName: "testuser@databricks.com"}, }) - diags := bundle.Apply(context.Background(), b, permissions.PermissionDiagnostics()) + diags := bundle.Apply(t.Context(), b, permissions.PermissionDiagnostics()) require.Equal(t, diag.Recommendation, diags[0].Severity) expectedMsg := "permissions section should explicitly include the current deployment identity " + diff --git a/bundle/permissions/permission_report_test.go b/bundle/permissions/permission_report_test.go index 61592f7e5a..52437aacdf 100644 --- a/bundle/permissions/permission_report_test.go +++ b/bundle/permissions/permission_report_test.go @@ -1,7 +1,6 @@ package permissions_test import ( - "context" "testing" "github.com/databricks/cli/bundle/config/resources" @@ -14,7 +13,7 @@ func TestPermissionsReportPermissionDeniedWithGroup(t *testing.T) { {Level: "CAN_MANAGE", GroupName: "testgroup"}, }) - diags := permissions.ReportPossiblePermissionDenied(context.Background(), b, "testpath") + diags := permissions.ReportPossiblePermissionDenied(t.Context(), b, "testpath") expected := "EPERM3: unable to deploy to testpath as testuser@databricks.com. Cannot apply local deployment permissions.\n" + "For assistance, contact the owners of this project.\n" + "They can redeploy the project to apply the latest set of permissions.\n" + @@ -27,7 +26,7 @@ func TestPermissionsReportPermissionDeniedWithOtherGroup(t *testing.T) { {Level: "CAN_MANAGE", GroupName: "othergroup"}, }) - diags := permissions.ReportPossiblePermissionDenied(context.Background(), b, "testpath") + diags := permissions.ReportPossiblePermissionDenied(t.Context(), b, "testpath") expected := "EPERM1: unable to deploy to testpath as testuser@databricks.com.\n" + "Please make sure the current user or one of their groups is listed under the permissions of this bundle.\n" + "For assistance, users or groups with appropriate permissions may include: othergroup.\n" + @@ -41,7 +40,7 @@ func TestPermissionsReportPermissionDeniedWithoutPermission(t *testing.T) { {Level: "CAN_VIEW", UserName: "testuser@databricks.com"}, }) - diags := permissions.ReportPossiblePermissionDenied(context.Background(), b, "testpath") + diags := permissions.ReportPossiblePermissionDenied(t.Context(), b, "testpath") expected := "EPERM1: unable to deploy to testpath as testuser@databricks.com.\n" + "Please make sure the current user or one of their groups is listed under the permissions of this bundle.\n" + "For assistance, contact the owners of this project.\n" + @@ -53,7 +52,7 @@ func TestPermissionsReportPermissionDeniedWithoutPermission(t *testing.T) { func TestPermissionsReportPermissionDeniedNilPermission(t *testing.T) { b := mockBundle(nil) - diags := permissions.ReportPossiblePermissionDenied(context.Background(), b, "testpath") + diags := permissions.ReportPossiblePermissionDenied(t.Context(), b, "testpath") expected := "EPERM1: unable to deploy to testpath as testuser@databricks.com.\n" + "Please make sure the current user or one of their groups is listed under the permissions of this bundle.\n" + "For assistance, contact the owners of this project.\n" + @@ -68,7 +67,7 @@ func TestPermissionsReportFindOtherOwners(t *testing.T) { {Level: "CAN_MANAGE", UserName: "alice@databricks.com"}, }) - diags := permissions.ReportPossiblePermissionDenied(context.Background(), b, "testpath") + diags := permissions.ReportPossiblePermissionDenied(t.Context(), b, "testpath") require.ErrorContains(t, diags.Error(), "EPERM3: unable to deploy to testpath as testuser@databricks.com. Cannot apply local deployment permissions.\n"+ "For assistance, users or groups with appropriate permissions may include: alice@databricks.com.\n"+ "They can redeploy the project to apply the latest set of permissions.\n"+ diff --git a/bundle/permissions/terraform_errors_test.go b/bundle/permissions/terraform_errors_test.go index c9b5b17860..1ad008e251 100644 --- a/bundle/permissions/terraform_errors_test.go +++ b/bundle/permissions/terraform_errors_test.go @@ -1,7 +1,6 @@ package permissions_test import ( - "context" "errors" "testing" @@ -12,7 +11,7 @@ import ( ) func TestTryExtendTerraformPermissionError1(t *testing.T) { - ctx := context.Background() + ctx := t.Context() b := mockBundle([]resources.Permission{ {Level: "CAN_MANAGE", UserName: "alice@databricks.com"}, }) @@ -33,7 +32,7 @@ func TestTryExtendTerraformPermissionError1(t *testing.T) { } func TestTryExtendTerraformPermissionError2(t *testing.T) { - ctx := context.Background() + ctx := t.Context() b := mockBundle([]resources.Permission{ {Level: "CAN_MANAGE", UserName: "alice@databricks.com"}, {Level: "CAN_MANAGE", UserName: "bob@databricks.com"}, @@ -54,7 +53,7 @@ func TestTryExtendTerraformPermissionError2(t *testing.T) { } func TestTryExtendTerraformPermissionError3(t *testing.T) { - ctx := context.Background() + ctx := t.Context() b := mockBundle([]resources.Permission{ {Level: "CAN_MANAGE", UserName: "testuser@databricks.com"}, }) @@ -74,7 +73,7 @@ func TestTryExtendTerraformPermissionError3(t *testing.T) { } func TestTryExtendTerraformPermissionErrorNotOwner(t *testing.T) { - ctx := context.Background() + ctx := t.Context() b := mockBundle([]resources.Permission{ {Level: "CAN_MANAGE", GroupName: "data_team@databricks.com"}, }) diff --git a/bundle/permissions/validate_test.go b/bundle/permissions/validate_test.go index 16dc8c7056..5cd3f05104 100644 --- a/bundle/permissions/validate_test.go +++ b/bundle/permissions/validate_test.go @@ -1,7 +1,6 @@ package permissions import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -34,7 +33,7 @@ func TestValidateSharedRootPermissionsForShared(t *testing.T) { m := mocks.NewMockWorkspaceClient(t) b.SetWorkpaceClient(m.WorkspaceClient) - diags := bundle.Apply(context.Background(), b, ValidateSharedRootPermissions()) + diags := bundle.Apply(t.Context(), b, ValidateSharedRootPermissions()) require.Empty(t, diags) } @@ -59,7 +58,7 @@ func TestValidateSharedRootPermissionsForSharedError(t *testing.T) { m := mocks.NewMockWorkspaceClient(t) b.SetWorkpaceClient(m.WorkspaceClient) - diags := bundle.Apply(context.Background(), b, ValidateSharedRootPermissions()) + diags := bundle.Apply(t.Context(), b, ValidateSharedRootPermissions()) require.Len(t, diags, 1) require.Equal(t, "the bundle root path /Workspace/Shared/foo/bar is writable by all workspace users", diags[0].Summary) require.Equal(t, diag.Warning, diags[0].Severity) diff --git a/bundle/permissions/workspace_root_test.go b/bundle/permissions/workspace_root_test.go index a03ca90854..1dd1c0cbfa 100644 --- a/bundle/permissions/workspace_root_test.go +++ b/bundle/permissions/workspace_root_test.go @@ -1,7 +1,6 @@ package permissions import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -73,7 +72,7 @@ func TestApplyWorkspaceRootPermissions(t *testing.T) { WorkspaceObjectType: "directories", }).Return(nil, nil) - diags := bundle.ApplySeq(context.Background(), b, ValidateSharedRootPermissions(), ApplyWorkspaceRootPermissions()) + diags := bundle.ApplySeq(t.Context(), b, ValidateSharedRootPermissions(), ApplyWorkspaceRootPermissions()) require.Empty(t, diags) } @@ -186,6 +185,6 @@ func TestApplyWorkspaceRootPermissionsForAllPaths(t *testing.T) { WorkspaceObjectType: "directories", }).Return(nil, nil) - diags := bundle.Apply(context.Background(), b, ApplyWorkspaceRootPermissions()) + diags := bundle.Apply(t.Context(), b, ApplyWorkspaceRootPermissions()) require.NoError(t, diags.Error()) } diff --git a/bundle/phases/plan_test.go b/bundle/phases/plan_test.go index c6d0091c09..28b19d0e1e 100644 --- a/bundle/phases/plan_test.go +++ b/bundle/phases/plan_test.go @@ -28,7 +28,7 @@ func TestCheckPreventDestroyForAllResources(t *testing.T) { }, } - ctx := context.Background() + ctx := t.Context() bundle.ApplyFuncContext(ctx, b, func(ctx context.Context, b *bundle.Bundle) { // Use Mutate to set the configuration dynamically err := b.Config.Mutate(func(v dyn.Value) (dyn.Value, error) { @@ -103,7 +103,7 @@ func TestCheckForPreventDestroyWhenFirstHasNoPreventDestroy(t *testing.T) { }, } - ctx := context.Background() + ctx := t.Context() bundle.ApplyFuncContext(ctx, b, func(ctx context.Context, b *bundle.Bundle) { err := checkForPreventDestroy(b, actions) require.Error(t, err) diff --git a/bundle/render/render_text_output_test.go b/bundle/render/render_text_output_test.go index d1c8094aac..3d42444539 100644 --- a/bundle/render/render_text_output_test.go +++ b/bundle/render/render_text_output_test.go @@ -2,7 +2,6 @@ package render import ( "bytes" - "context" "errors" "io" "testing" @@ -27,7 +26,7 @@ import ( func TestRenderSummaryHeaderTemplate_nilBundle(t *testing.T) { writer := &bytes.Buffer{} - err := renderSummaryHeaderTemplate(context.Background(), writer, nil) + err := renderSummaryHeaderTemplate(t.Context(), writer, nil) require.NoError(t, err) assert.Equal(t, "", writer.String()) @@ -115,7 +114,7 @@ func TestRenderDiagnosticsSummary(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - ctx := logdiag.InitContext(context.Background()) + ctx := logdiag.InitContext(t.Context()) logdiag.SetCollect(ctx, true) // Collect diagnostics instead of outputting to stderr // Simulate diagnostic counts by logging fake diagnostics @@ -276,7 +275,7 @@ func TestRenderDiagnostics(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - ctx, stderr := cmdio.NewTestContextWithStderr(context.Background()) + ctx, stderr := cmdio.NewTestContextWithStderr(t.Context()) err := cmdio.RenderDiagnostics(ctx, tc.diags) require.NoError(t, err) @@ -294,7 +293,7 @@ func TestRenderSummaryTemplate_nilBundle(t *testing.T) { color.NoColor = oldNoColor }() - ctx := logdiag.InitContext(context.Background()) + ctx := logdiag.InitContext(t.Context()) writer := &bytes.Buffer{} err := renderSummaryHeaderTemplate(ctx, writer, nil) @@ -307,7 +306,7 @@ func TestRenderSummaryTemplate_nilBundle(t *testing.T) { } func TestRenderSummary(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // Disable colors for consistent test output oldNoColor := color.NoColor diff --git a/bundle/root_test.go b/bundle/root_test.go index 0752427109..d6312c9b28 100644 --- a/bundle/root_test.go +++ b/bundle/root_test.go @@ -1,7 +1,6 @@ package bundle import ( - "context" "os" "path/filepath" "testing" @@ -13,7 +12,7 @@ import ( ) func TestRootFromEnv(t *testing.T) { - ctx := context.Background() + ctx := t.Context() dir := t.TempDir() t.Setenv(env.RootVariable, dir) @@ -24,7 +23,7 @@ func TestRootFromEnv(t *testing.T) { } func TestRootFromEnvDoesntExist(t *testing.T) { - ctx := context.Background() + ctx := t.Context() dir := t.TempDir() t.Setenv(env.RootVariable, filepath.Join(dir, "doesntexist")) @@ -34,7 +33,7 @@ func TestRootFromEnvDoesntExist(t *testing.T) { } func TestRootFromEnvIsFile(t *testing.T) { - ctx := context.Background() + ctx := t.Context() dir := t.TempDir() f, err := os.Create(filepath.Join(dir, "invalid")) require.NoError(t, err) @@ -47,7 +46,7 @@ func TestRootFromEnvIsFile(t *testing.T) { } func TestRootIfEnvIsEmpty(t *testing.T) { - ctx := context.Background() + ctx := t.Context() dir := "" t.Setenv(env.RootVariable, dir) @@ -57,7 +56,7 @@ func TestRootIfEnvIsEmpty(t *testing.T) { } func TestRootLookup(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // Have to set then unset to allow the testing package to revert it to its original value. t.Setenv(env.RootVariable, "") @@ -82,7 +81,7 @@ func TestRootLookup(t *testing.T) { } func TestRootLookupError(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // Have to set then unset to allow the testing package to revert it to its original value. t.Setenv(env.RootVariable, "") diff --git a/bundle/run/app_test.go b/bundle/run/app_test.go index 55836c4b0a..112fcea28d 100644 --- a/bundle/run/app_test.go +++ b/bundle/run/app_test.go @@ -69,7 +69,7 @@ func setupBundle(t *testing.T) (context.Context, *bundle.Bundle, *mocks.MockWork b.SetWorkpaceClient(mwc.WorkspaceClient) bundletest.SetLocation(b, "resources.apps.my_app", []dyn.Location{{File: filepath.Join(root, "./databricks.yml")}}) - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) diags := bundle.ApplySeq(ctx, b, mutator.DefineDefaultWorkspacePaths(), diff --git a/bundle/run/job_test.go b/bundle/run/job_test.go index 5d6079a87c..078b09a962 100644 --- a/bundle/run/job_test.go +++ b/bundle/run/job_test.go @@ -1,7 +1,6 @@ package run import ( - "context" "testing" "time" @@ -95,7 +94,7 @@ func TestJobRunnerCancel(t *testing.T) { RunId: 2, }).Return(mockWait, nil) - err := runner.Cancel(context.Background()) + err := runner.Cancel(t.Context()) require.NoError(t, err) } @@ -126,7 +125,7 @@ func TestJobRunnerCancelWithNoActiveRuns(t *testing.T) { jobApi.AssertNotCalled(t, "CancelRun") - err := runner.Cancel(context.Background()) + err := runner.Cancel(t.Context()) require.NoError(t, err) } @@ -158,7 +157,7 @@ func TestJobRunnerRestart(t *testing.T) { m := mocks.NewMockWorkspaceClient(t) b.SetWorkpaceClient(m.WorkspaceClient) - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) jobApi := m.GetMockJobsAPI() jobApi.EXPECT().ListRunsAll(mock.Anything, jobs.ListRunsRequest{ @@ -228,7 +227,7 @@ func TestJobRunnerRestartForContinuousUnpausedJobs(t *testing.T) { m := mocks.NewMockWorkspaceClient(t) b.SetWorkpaceClient(m.WorkspaceClient) - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) jobApi := m.GetMockJobsAPI() diff --git a/bundle/run/pipeline_test.go b/bundle/run/pipeline_test.go index 26ee850995..8febf62e4d 100644 --- a/bundle/run/pipeline_test.go +++ b/bundle/run/pipeline_test.go @@ -1,7 +1,6 @@ package run import ( - "context" "testing" "time" @@ -43,11 +42,11 @@ func TestPipelineRunnerCancel(t *testing.T) { } pipelineApi := m.GetMockPipelinesAPI() - pipelineApi.EXPECT().Stop(context.Background(), pipelines.StopRequest{ + pipelineApi.EXPECT().Stop(t.Context(), pipelines.StopRequest{ PipelineId: "123", }).Return(mockWait, nil) - err := runner.Cancel(context.Background()) + err := runner.Cancel(t.Context()) require.NoError(t, err) } @@ -74,7 +73,7 @@ func TestPipelineRunnerRestart(t *testing.T) { } b.SetWorkpaceClient(m.WorkspaceClient) - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) mockWait := &pipelines.WaitGetPipelineIdle[struct{}]{ Poll: func(time.Duration, func(*pipelines.GetPipelineResponse)) (*pipelines.GetPipelineResponse, error) { diff --git a/bundle/statemgmt/check_running_resources_test.go b/bundle/statemgmt/check_running_resources_test.go index c1caff18d0..233dd12181 100644 --- a/bundle/statemgmt/check_running_resources_test.go +++ b/bundle/statemgmt/check_running_resources_test.go @@ -1,7 +1,6 @@ package statemgmt import ( - "context" "errors" "testing" @@ -14,7 +13,7 @@ import ( func TestIsAnyResourceRunningWithEmptyState(t *testing.T) { mock := mocks.NewMockWorkspaceClient(t) - err := checkAnyResourceRunning(context.Background(), mock.WorkspaceClient, nil) + err := checkAnyResourceRunning(t.Context(), mock.WorkspaceClient, nil) require.NoError(t, err) } @@ -32,7 +31,7 @@ func TestIsAnyResourceRunningWithJob(t *testing.T) { {RunId: 1234}, }, nil).Once() - err := checkAnyResourceRunning(context.Background(), m.WorkspaceClient, resources) + err := checkAnyResourceRunning(t.Context(), m.WorkspaceClient, resources) require.ErrorContains(t, err, "job 123 is running") jobsApi.EXPECT().ListRunsAll(mock.Anything, jobs.ListRunsRequest{ @@ -40,7 +39,7 @@ func TestIsAnyResourceRunningWithJob(t *testing.T) { ActiveOnly: true, }).Return([]jobs.BaseRun{}, nil).Once() - err = checkAnyResourceRunning(context.Background(), m.WorkspaceClient, resources) + err = checkAnyResourceRunning(t.Context(), m.WorkspaceClient, resources) require.NoError(t, err) } @@ -58,7 +57,7 @@ func TestIsAnyResourceRunningWithPipeline(t *testing.T) { State: pipelines.PipelineStateRunning, }, nil).Once() - err := checkAnyResourceRunning(context.Background(), m.WorkspaceClient, resources) + err := checkAnyResourceRunning(t.Context(), m.WorkspaceClient, resources) require.ErrorContains(t, err, "pipeline 123 is running") pipelineApi.EXPECT().Get(mock.Anything, pipelines.GetPipelineRequest{ @@ -67,7 +66,7 @@ func TestIsAnyResourceRunningWithPipeline(t *testing.T) { PipelineId: "123", State: pipelines.PipelineStateIdle, }, nil).Once() - err = checkAnyResourceRunning(context.Background(), m.WorkspaceClient, resources) + err = checkAnyResourceRunning(t.Context(), m.WorkspaceClient, resources) require.NoError(t, err) } @@ -83,6 +82,6 @@ func TestIsAnyResourceRunningWithAPIFailure(t *testing.T) { PipelineId: "123", }).Return(nil, errors.New("API failure")).Once() - err := checkAnyResourceRunning(context.Background(), m.WorkspaceClient, resources) + err := checkAnyResourceRunning(t.Context(), m.WorkspaceClient, resources) require.NoError(t, err) } diff --git a/bundle/statemgmt/state_load_test.go b/bundle/statemgmt/state_load_test.go index 466e966550..d86cca7789 100644 --- a/bundle/statemgmt/state_load_test.go +++ b/bundle/statemgmt/state_load_test.go @@ -1,7 +1,6 @@ package statemgmt import ( - "context" "reflect" "testing" @@ -50,7 +49,7 @@ func TestStateToBundleEmptyLocalResources(t *testing.T) { "resources.postgres_branches.test_postgres_branch": {ID: "projects/test-project/branches/main"}, "resources.postgres_endpoints.test_postgres_endpoint": {ID: "projects/test-project/branches/main/endpoints/primary"}, } - err := StateToBundle(context.Background(), state, &config) + err := StateToBundle(t.Context(), state, &config) assert.NoError(t, err) assert.Equal(t, "1", config.Resources.Jobs["test_job"].ID) @@ -291,7 +290,7 @@ func TestStateToBundleEmptyRemoteResources(t *testing.T) { }, } - err := StateToBundle(context.Background(), nil, &config) + err := StateToBundle(t.Context(), nil, &config) assert.NoError(t, err) assert.Equal(t, "", config.Resources.Jobs["test_job"].ID) @@ -691,7 +690,7 @@ func TestStateToBundleModifiedResources(t *testing.T) { "resources.postgres_endpoints.test_postgres_endpoint": {ID: "projects/test-project/branches/main/endpoints/primary"}, "resources.postgres_endpoints.test_postgres_endpoint_old": {ID: "projects/test-project/branches/main/endpoints/old"}, } - err := StateToBundle(context.Background(), state, &config) + err := StateToBundle(t.Context(), state, &config) assert.NoError(t, err) assert.Equal(t, "1", config.Resources.Jobs["test_job"].ID) diff --git a/bundle/tests/bundle_permissions_test.go b/bundle/tests/bundle_permissions_test.go index 1b3f86f4c2..44eed0c153 100644 --- a/bundle/tests/bundle_permissions_test.go +++ b/bundle/tests/bundle_permissions_test.go @@ -1,7 +1,6 @@ package config_tests import ( - "context" "testing" "github.com/databricks/cli/bundle/config/mutator/resourcemutator" @@ -19,7 +18,7 @@ func TestBundlePermissions(t *testing.T) { assert.NotContains(t, b.Config.Permissions, resources.Permission{Level: "CAN_VIEW", ServicePrincipalName: "1234-abcd"}) assert.NotContains(t, b.Config.Permissions, resources.Permission{Level: "CAN_RUN", UserName: "bot@company.com"}) - diags := bundle.Apply(context.Background(), b, resourcemutator.ApplyBundlePermissions()) + diags := bundle.Apply(t.Context(), b, resourcemutator.ApplyBundlePermissions()) require.NoError(t, diags.Error()) pipelinePermissions := b.Config.Resources.Pipelines["nyc_taxi_pipeline"].Permissions @@ -42,7 +41,7 @@ func TestBundlePermissionsDevTarget(t *testing.T) { assert.Contains(t, b.Config.Permissions, resources.Permission{Level: "CAN_VIEW", ServicePrincipalName: "1234-abcd"}) assert.Contains(t, b.Config.Permissions, resources.Permission{Level: "CAN_RUN", UserName: "bot@company.com"}) - diags := bundle.Apply(context.Background(), b, resourcemutator.ApplyBundlePermissions()) + diags := bundle.Apply(t.Context(), b, resourcemutator.ApplyBundlePermissions()) require.NoError(t, diags.Error()) pipelinePermissions := b.Config.Resources.Pipelines["nyc_taxi_pipeline"].Permissions diff --git a/bundle/tests/enviroment_key_test.go b/bundle/tests/enviroment_key_test.go index c220593135..ef28b33d38 100644 --- a/bundle/tests/enviroment_key_test.go +++ b/bundle/tests/enviroment_key_test.go @@ -1,7 +1,6 @@ package config_tests import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -10,9 +9,9 @@ import ( ) func TestEnvironmentKeyProvidedAndNoPanic(t *testing.T) { - b, diags := loadTargetWithDiags("./environment_key_only", "default") + b, diags := loadTargetWithDiags(t, "./environment_key_only", "default") require.Empty(t, diags) - diags = bundle.Apply(context.Background(), b, libraries.ExpandGlobReferences()) + diags = bundle.Apply(t.Context(), b, libraries.ExpandGlobReferences()) require.Empty(t, diags) } diff --git a/bundle/tests/environment_git_test.go b/bundle/tests/environment_git_test.go index 901d2867b7..f7564b707d 100644 --- a/bundle/tests/environment_git_test.go +++ b/bundle/tests/environment_git_test.go @@ -1,7 +1,6 @@ package config_tests import ( - "context" "strings" "testing" @@ -12,14 +11,14 @@ import ( func TestGitAutoLoadWithEnvironment(t *testing.T) { b := load(t, "./environments_autoload_git") - bundle.Apply(context.Background(), b, mutator.LoadGitDetails()) + bundle.Apply(t.Context(), b, mutator.LoadGitDetails()) validUrl := strings.Contains(b.Config.Bundle.Git.OriginURL, "/cli") || strings.Contains(b.Config.Bundle.Git.OriginURL, "/bricks") assert.True(t, validUrl, "Expected URL to contain '/cli' or '/bricks', got %s", b.Config.Bundle.Git.OriginURL) } func TestGitManuallySetBranchWithEnvironment(t *testing.T) { b := loadTarget(t, "./environments_autoload_git", "production") - bundle.Apply(context.Background(), b, mutator.LoadGitDetails()) + bundle.Apply(t.Context(), b, mutator.LoadGitDetails()) assert.Equal(t, "main", b.Config.Bundle.Git.Branch) validUrl := strings.Contains(b.Config.Bundle.Git.OriginURL, "/cli") || strings.Contains(b.Config.Bundle.Git.OriginURL, "/bricks") assert.True(t, validUrl, "Expected URL to contain '/cli' or '/bricks', got %s", b.Config.Bundle.Git.OriginURL) diff --git a/bundle/tests/git_test.go b/bundle/tests/git_test.go index dd79e26a44..bbd469306f 100644 --- a/bundle/tests/git_test.go +++ b/bundle/tests/git_test.go @@ -1,7 +1,6 @@ package config_tests import ( - "context" "strings" "testing" @@ -13,14 +12,14 @@ import ( func TestGitAutoLoad(t *testing.T) { b := load(t, "./autoload_git") - bundle.Apply(context.Background(), b, mutator.LoadGitDetails()) + bundle.Apply(t.Context(), b, mutator.LoadGitDetails()) validUrl := strings.Contains(b.Config.Bundle.Git.OriginURL, "/cli") || strings.Contains(b.Config.Bundle.Git.OriginURL, "/bricks") assert.True(t, validUrl, "Expected URL to contain '/cli' or '/bricks', got %s", b.Config.Bundle.Git.OriginURL) } func TestGitManuallySetBranch(t *testing.T) { b := loadTarget(t, "./autoload_git", "production") - bundle.Apply(context.Background(), b, mutator.LoadGitDetails()) + bundle.Apply(t.Context(), b, mutator.LoadGitDetails()) assert.Equal(t, "main", b.Config.Bundle.Git.Branch) validUrl := strings.Contains(b.Config.Bundle.Git.OriginURL, "/cli") || strings.Contains(b.Config.Bundle.Git.OriginURL, "/bricks") assert.True(t, validUrl, "Expected URL to contain '/cli' or '/bricks', got %s", b.Config.Bundle.Git.OriginURL) @@ -33,10 +32,10 @@ func TestGitBundleBranchValidation(t *testing.T) { }) b := load(t, "./git_branch_validation") - bundle.Apply(context.Background(), b, mutator.LoadGitDetails()) + bundle.Apply(t.Context(), b, mutator.LoadGitDetails()) assert.Equal(t, "feature-a", b.Config.Bundle.Git.Branch) assert.Equal(t, "feature-b", b.Config.Bundle.Git.ActualBranch) - diags := bundle.Apply(context.Background(), b, mutator.ValidateGitDetails()) + diags := bundle.Apply(t.Context(), b, mutator.ValidateGitDetails()) assert.ErrorContains(t, diags.Error(), "not on the right Git branch:") } diff --git a/bundle/tests/include_test.go b/bundle/tests/include_test.go index 548516cc58..c5ad2d58a1 100644 --- a/bundle/tests/include_test.go +++ b/bundle/tests/include_test.go @@ -1,7 +1,6 @@ package config_tests import ( - "context" "path/filepath" "testing" @@ -14,7 +13,7 @@ import ( ) func TestIncludeInvalid(t *testing.T) { - ctx := logdiag.InitContext(context.Background()) + ctx := logdiag.InitContext(t.Context()) logdiag.SetCollect(ctx, true) b, err := bundle.Load(ctx, "./include_invalid") require.NoError(t, err) diff --git a/bundle/tests/interpolation_test.go b/bundle/tests/interpolation_test.go index 1b922e1017..86ca833a6c 100644 --- a/bundle/tests/interpolation_test.go +++ b/bundle/tests/interpolation_test.go @@ -1,7 +1,6 @@ package config_tests import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -13,7 +12,7 @@ import ( func TestInterpolation(t *testing.T) { b := load(t, "./interpolation") diags := bundle.ApplySeq( - context.Background(), + t.Context(), b, mutator.ResolveVariableReferencesOnlyResources( "bundle", @@ -31,7 +30,7 @@ func TestInterpolation(t *testing.T) { func TestInterpolationWithTarget_withoutResources(t *testing.T) { b := loadTarget(t, "./interpolation_target", "development") - diags := bundle.Apply(context.Background(), b, mutator.ResolveVariableReferencesOnlyResources( + diags := bundle.Apply(t.Context(), b, mutator.ResolveVariableReferencesOnlyResources( "bundle", "workspace", )) @@ -42,7 +41,7 @@ func TestInterpolationWithTarget_withoutResources(t *testing.T) { func TestInterpolationWithTarget_onlyResources(t *testing.T) { b := loadTarget(t, "./interpolation_target", "development") - diags := bundle.Apply(context.Background(), b, mutator.ResolveVariableReferencesWithoutResources( + diags := bundle.Apply(t.Context(), b, mutator.ResolveVariableReferencesWithoutResources( "bundle", "workspace", )) diff --git a/bundle/tests/job_cluster_key_test.go b/bundle/tests/job_cluster_key_test.go index 0306bf7b5a..d6a160f1db 100644 --- a/bundle/tests/job_cluster_key_test.go +++ b/bundle/tests/job_cluster_key_test.go @@ -1,7 +1,6 @@ package config_tests import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -13,7 +12,7 @@ import ( func TestJobClusterKeyNotDefinedTest(t *testing.T) { b := loadTarget(t, "./job_cluster_key", "default") - diags := bundle.Apply(context.Background(), b, validate.JobClusterKeyDefined()) + diags := bundle.Apply(t.Context(), b, validate.JobClusterKeyDefined()) require.Len(t, diags, 1) require.NoError(t, diags.Error()) require.Equal(t, diag.Warning, diags[0].Severity) @@ -23,6 +22,6 @@ func TestJobClusterKeyNotDefinedTest(t *testing.T) { func TestJobClusterKeyDefinedTest(t *testing.T) { b := loadTarget(t, "./job_cluster_key", "development") - diags := bundle.Apply(context.Background(), b, validate.JobClusterKeyDefined()) + diags := bundle.Apply(t.Context(), b, validate.JobClusterKeyDefined()) require.Empty(t, diags) } diff --git a/bundle/tests/loader.go b/bundle/tests/loader.go index a106e99baa..1177190790 100644 --- a/bundle/tests/loader.go +++ b/bundle/tests/loader.go @@ -1,7 +1,6 @@ package config_tests import ( - "context" "testing" "github.com/databricks/cli/bundle/config/mutator/resourcemutator" @@ -15,7 +14,7 @@ import ( ) func load(t *testing.T, path string) *bundle.Bundle { - ctx := logdiag.InitContext(context.Background()) + ctx := logdiag.InitContext(t.Context()) logdiag.SetCollect(ctx, true) b, err := bundle.Load(ctx, path) require.NoError(t, err) @@ -26,13 +25,13 @@ func load(t *testing.T, path string) *bundle.Bundle { } func loadTarget(t *testing.T, path, env string) *bundle.Bundle { - b, diags := loadTargetWithDiags(path, env) + b, diags := loadTargetWithDiags(t, path, env) require.NoError(t, diags.Error()) return b } -func loadTargetWithDiags(path, env string) (*bundle.Bundle, diag.Diagnostics) { - ctx := logdiag.InitContext(context.Background()) +func loadTargetWithDiags(t *testing.T, path, env string) (*bundle.Bundle, diag.Diagnostics) { + ctx := logdiag.InitContext(t.Context()) logdiag.SetCollect(ctx, true) b, err := bundle.Load(ctx, path) if err != nil { diff --git a/bundle/tests/relative_path_with_includes_test.go b/bundle/tests/relative_path_with_includes_test.go index 46efd07168..50bb8a776b 100644 --- a/bundle/tests/relative_path_with_includes_test.go +++ b/bundle/tests/relative_path_with_includes_test.go @@ -1,7 +1,6 @@ package config_tests import ( - "context" "path" "testing" @@ -13,7 +12,7 @@ import ( func TestRelativePathsWithIncludes(t *testing.T) { b := loadTarget(t, "./relative_path_with_includes", "default") - diags := bundle.ApplySeq(context.Background(), b, + diags := bundle.ApplySeq(t.Context(), b, mutator.NormalizePaths(), mutator.TranslatePaths(), ) diff --git a/bundle/tests/suggest_target_test.go b/bundle/tests/suggest_target_test.go index 02905d779c..ca678a61c0 100644 --- a/bundle/tests/suggest_target_test.go +++ b/bundle/tests/suggest_target_test.go @@ -1,7 +1,6 @@ package config_tests import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -12,7 +11,7 @@ import ( func TestSuggestTargetIfWrongPassed(t *testing.T) { b := load(t, "target_overrides/workspace") - ctx := context.Background() + ctx := t.Context() diags := bundle.Apply(ctx, b, mutator.SelectTarget("incorrect")) err := diags.Error() require.Error(t, err) diff --git a/bundle/tests/sync_include_exclude_no_matches_test.go b/bundle/tests/sync_include_exclude_no_matches_test.go index 0a5fe3f671..42938266c5 100644 --- a/bundle/tests/sync_include_exclude_no_matches_test.go +++ b/bundle/tests/sync_include_exclude_no_matches_test.go @@ -1,7 +1,6 @@ package config_tests import ( - "context" "fmt" "path" "testing" @@ -16,7 +15,7 @@ import ( func TestSyncIncludeExcludeNoMatchesTest(t *testing.T) { b := loadTarget(t, "./sync/override", "development") - diags := bundle.Apply(context.Background(), b, validate.ValidateSyncPatterns()) + diags := bundle.Apply(t.Context(), b, validate.ValidateSyncPatterns()) require.Len(t, diags, 3) require.NoError(t, diags.Error()) @@ -46,7 +45,7 @@ func TestSyncIncludeExcludeNoMatchesTest(t *testing.T) { func TestSyncIncludeWithNegate(t *testing.T) { b := loadTarget(t, "./sync/negate", "default") - diags := bundle.Apply(context.Background(), b, validate.ValidateSyncPatterns()) + diags := bundle.Apply(t.Context(), b, validate.ValidateSyncPatterns()) require.Empty(t, diags) require.NoError(t, diags.Error()) } @@ -54,7 +53,7 @@ func TestSyncIncludeWithNegate(t *testing.T) { func TestSyncIncludeWithNegateNoMatches(t *testing.T) { b := loadTarget(t, "./sync/negate", "dev") - diags := bundle.Apply(context.Background(), b, validate.ValidateSyncPatterns()) + diags := bundle.Apply(t.Context(), b, validate.ValidateSyncPatterns()) require.Len(t, diags, 1) require.NoError(t, diags.Error()) diff --git a/bundle/tests/validate_test.go b/bundle/tests/validate_test.go index fe19907135..e10f240aaf 100644 --- a/bundle/tests/validate_test.go +++ b/bundle/tests/validate_test.go @@ -1,7 +1,6 @@ package config_tests import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -127,7 +126,7 @@ func TestValidateUniqueResourceIdentifiers(t *testing.T) { for _, tc := range tcases { t.Run(tc.name, func(t *testing.T) { - ctx := logdiag.InitContext(context.Background()) + ctx := logdiag.InitContext(t.Context()) logdiag.SetCollect(ctx, true) b, err := bundle.Load(ctx, "./validate/"+tc.name) require.NoError(t, err) diff --git a/bundle/tests/yaml_anchors_test.go b/bundle/tests/yaml_anchors_test.go index 5c84970514..29681c0840 100644 --- a/bundle/tests/yaml_anchors_test.go +++ b/bundle/tests/yaml_anchors_test.go @@ -26,11 +26,11 @@ func TestYAMLAnchors(t *testing.T) { } func TestYAMLAnchorsNoWarnings(t *testing.T) { - _, diags := loadTargetWithDiags("./yaml_anchors", "default") + _, diags := loadTargetWithDiags(t, "./yaml_anchors", "default") assert.Empty(t, diags) } func TestYAMLAnchorsSeparateBlockNoWarnings(t *testing.T) { - _, diags := loadTargetWithDiags("./yaml_anchors_separate_block", "default") + _, diags := loadTargetWithDiags(t, "./yaml_anchors_separate_block", "default") assert.Empty(t, diags) } diff --git a/bundle/trampoline/conditional_transform_test.go b/bundle/trampoline/conditional_transform_test.go index 0e4517953a..97cfa94df0 100644 --- a/bundle/trampoline/conditional_transform_test.go +++ b/bundle/trampoline/conditional_transform_test.go @@ -1,7 +1,6 @@ package trampoline import ( - "context" "path/filepath" "testing" @@ -50,7 +49,7 @@ func TestNoTransformByDefault(t *testing.T) { } trampoline := TransformWheelTask() - diags := bundle.Apply(context.Background(), b, trampoline) + diags := bundle.Apply(t.Context(), b, trampoline) require.NoError(t, diags.Error()) task := b.Config.Resources.Jobs["job1"].Tasks[0] @@ -103,7 +102,7 @@ func TestTransformWithExperimentalSettingSetToTrue(t *testing.T) { } trampoline := TransformWheelTask() - diags := bundle.Apply(context.Background(), b, trampoline) + diags := bundle.Apply(t.Context(), b, trampoline) require.NoError(t, diags.Error()) task := b.Config.Resources.Jobs["job1"].Tasks[0] diff --git a/bundle/trampoline/python_dbr_warning_test.go b/bundle/trampoline/python_dbr_warning_test.go index 2aa6572999..1e990ed7bd 100644 --- a/bundle/trampoline/python_dbr_warning_test.go +++ b/bundle/trampoline/python_dbr_warning_test.go @@ -1,7 +1,6 @@ package trampoline import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -50,7 +49,7 @@ func TestIncompatibleWheelTasksWithNewCluster(t *testing.T) { }, } - diags := hasIncompatibleWheelTasks(context.Background(), b) + diags := hasIncompatibleWheelTasks(t.Context(), b) require.NotEmpty(t, diags) } @@ -100,10 +99,10 @@ func TestIncompatibleWheelTasksWithJobClusterKey(t *testing.T) { }, } - diags := hasIncompatibleWheelTasks(context.Background(), b) + diags := hasIncompatibleWheelTasks(t.Context(), b) require.NotEmpty(t, diags) - diags = bundle.Apply(context.Background(), b, WrapperWarning()) + diags = bundle.Apply(t.Context(), b, WrapperWarning()) require.ErrorContains(t, diags.Error(), "uses incompatible DBR version 12.2.x-scala2.12") } @@ -149,7 +148,7 @@ func TestIncompatibleWheelTasksWithExistingClusterId(t *testing.T) { SparkVersion: "12.2.x-scala2.12", }, nil) - diags := hasIncompatibleWheelTasks(context.Background(), b) + diags := hasIncompatibleWheelTasks(t.Context(), b) require.NotEmpty(t, diags) require.ErrorContains(t, diags.Error(), "uses cluster with incompatible DBR version 12.2.x-scala2.12") } @@ -256,7 +255,7 @@ func TestNoIncompatibleWheelTasks(t *testing.T) { SparkVersion: "13.2.x-scala2.12", }, nil) - diags := hasIncompatibleWheelTasks(context.Background(), b) + diags := hasIncompatibleWheelTasks(t.Context(), b) require.Empty(t, diags) } @@ -297,7 +296,7 @@ func TestTasksWithPyPiPackageAreCompatible(t *testing.T) { m := mocks.NewMockWorkspaceClient(t) b.SetWorkpaceClient(m.WorkspaceClient) - diags := hasIncompatibleWheelTasks(context.Background(), b) + diags := hasIncompatibleWheelTasks(t.Context(), b) require.Empty(t, diags) } @@ -340,7 +339,7 @@ func TestNoWarningWhenPythonWheelWrapperIsOn(t *testing.T) { }, } - diags := bundle.Apply(context.Background(), b, WrapperWarning()) + diags := bundle.Apply(t.Context(), b, WrapperWarning()) require.NoError(t, diags.Error()) } diff --git a/bundle/trampoline/python_wheel_test.go b/bundle/trampoline/python_wheel_test.go index 4164159dda..8b9669087f 100644 --- a/bundle/trampoline/python_wheel_test.go +++ b/bundle/trampoline/python_wheel_test.go @@ -1,7 +1,6 @@ package trampoline import ( - "context" "strings" "testing" @@ -137,6 +136,6 @@ func TestNoPanicWithNoPythonWheelTasks(t *testing.T) { }, } trampoline := TransformWheelTask() - diags := bundle.Apply(context.Background(), b, trampoline) + diags := bundle.Apply(t.Context(), b, trampoline) require.NoError(t, diags.Error()) } diff --git a/bundle/trampoline/trampoline_test.go b/bundle/trampoline/trampoline_test.go index b020a5ad4f..53b1e3811a 100644 --- a/bundle/trampoline/trampoline_test.go +++ b/bundle/trampoline/trampoline_test.go @@ -1,7 +1,6 @@ package trampoline import ( - "context" "errors" "os" "path/filepath" @@ -77,7 +76,7 @@ func TestGenerateTrampoline(t *testing.T) { }, }, } - ctx := context.Background() + ctx := t.Context() funcs := functions{} trampoline := NewTrampoline("test_trampoline", &funcs, "Hello from {{.MyName}}") diff --git a/cmd/apps/bundle_helpers_test.go b/cmd/apps/bundle_helpers_test.go index 359d365f86..f772d4f545 100644 --- a/cmd/apps/bundle_helpers_test.go +++ b/cmd/apps/bundle_helpers_test.go @@ -1,7 +1,6 @@ package apps import ( - "context" "errors" "testing" @@ -166,7 +165,7 @@ func TestHandleAlreadyInStateError(t *testing.T) { return err } - handled, _ := handleAlreadyInStateError(context.Background(), cmd, err, "test-app", []string{"ACTIVE"}, "is deployed", mockWrapper) + handled, _ := handleAlreadyInStateError(t.Context(), cmd, err, "test-app", []string{"ACTIVE"}, "is deployed", mockWrapper) assert.False(t, handled) }) } diff --git a/cmd/apps/dev_test.go b/cmd/apps/dev_test.go index 8aa0224798..6ce0c039d1 100644 --- a/cmd/apps/dev_test.go +++ b/cmd/apps/dev_test.go @@ -1,7 +1,6 @@ package apps import ( - "context" "net" "os" "testing" @@ -59,7 +58,7 @@ func TestStartViteDevServerNoNode(t *testing.T) { t.Skip("Skipping node-dependent test in CI") } - ctx := context.Background() + ctx := t.Context() ctx = cmdio.MockDiscard(ctx) // Create a temporary directory to act as project root diff --git a/cmd/apps/init_test.go b/cmd/apps/init_test.go index 700cbe602d..b651ad75ac 100644 --- a/cmd/apps/init_test.go +++ b/cmd/apps/init_test.go @@ -2,7 +2,6 @@ package apps import ( "bytes" - "context" "errors" "io" "os" @@ -91,7 +90,7 @@ func testVars() templateVars { } func TestExecuteTemplateBackwardCompat(t *testing.T) { - ctx := context.Background() + ctx := t.Context() vars := testVars() tests := []struct { @@ -166,7 +165,7 @@ func TestExecuteTemplateBackwardCompat(t *testing.T) { } func TestExecuteTemplateNewKeys(t *testing.T) { - ctx := context.Background() + ctx := t.Context() vars := testVars() tests := []struct { @@ -241,7 +240,7 @@ func TestExecuteTemplateNewKeys(t *testing.T) { } func TestExecuteTemplateInvalidSyntaxReturnsOriginal(t *testing.T) { - ctx := context.Background() + ctx := t.Context() vars := templateVars{ProjectName: "my-app"} input := "some content with bad {{ syntax" result, err := executeTemplate(ctx, "test.js", []byte(input), vars) @@ -539,7 +538,7 @@ func TestRunManifestOnlyFound(t *testing.T) { require.NoError(t, err) os.Stdout = w - err = runManifestOnly(context.Background(), dir, "", "") + err = runManifestOnly(t.Context(), dir, "", "") w.Close() os.Stdout = old require.NoError(t, err) @@ -559,7 +558,7 @@ func TestRunManifestOnlyNotFound(t *testing.T) { require.NoError(t, err) os.Stdout = w - err = runManifestOnly(context.Background(), dir, "", "") + err = runManifestOnly(t.Context(), dir, "", "") w.Close() os.Stdout = old require.NoError(t, err) diff --git a/cmd/auth/describe_test.go b/cmd/auth/describe_test.go index de97953a84..1ee8d5122d 100644 --- a/cmd/auth/describe_test.go +++ b/cmd/auth/describe_test.go @@ -1,7 +1,6 @@ package auth import ( - "context" "errors" "testing" @@ -15,7 +14,7 @@ import ( ) func TestGetWorkspaceAuthStatus(t *testing.T) { - ctx := context.Background() + ctx := t.Context() m := mocks.NewMockWorkspaceClient(t) ctx = cmdctx.SetWorkspaceClient(ctx, m.WorkspaceClient) @@ -73,7 +72,7 @@ func TestGetWorkspaceAuthStatus(t *testing.T) { } func TestGetWorkspaceAuthStatusError(t *testing.T) { - ctx := context.Background() + ctx := t.Context() m := mocks.NewMockWorkspaceClient(t) ctx = cmdctx.SetWorkspaceClient(ctx, m.WorkspaceClient) @@ -122,7 +121,7 @@ func TestGetWorkspaceAuthStatusError(t *testing.T) { } func TestGetWorkspaceAuthStatusSensitive(t *testing.T) { - ctx := context.Background() + ctx := t.Context() m := mocks.NewMockWorkspaceClient(t) ctx = cmdctx.SetWorkspaceClient(ctx, m.WorkspaceClient) @@ -167,7 +166,7 @@ func TestGetWorkspaceAuthStatusSensitive(t *testing.T) { } func TestGetAccountAuthStatus(t *testing.T) { - ctx := context.Background() + ctx := t.Context() m := mocks.NewMockAccountClient(t) ctx = cmdctx.SetAccountClient(ctx, m.AccountClient) diff --git a/cmd/auth/login_test.go b/cmd/auth/login_test.go index 8f08e55562..013786c4bf 100644 --- a/cmd/auth/login_test.go +++ b/cmd/auth/login_test.go @@ -20,7 +20,7 @@ func loadTestProfile(t *testing.T, ctx context.Context, profileName string) *pro } func TestSetHostDoesNotFailWithNoDatabrickscfg(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = env.Set(ctx, "DATABRICKS_CONFIG_FILE", "./imaginary-file/databrickscfg") existingProfile, err := loadProfileByName(ctx, "foo", profile.DefaultProfiler) @@ -33,7 +33,7 @@ func TestSetHostDoesNotFailWithNoDatabrickscfg(t *testing.T) { func TestSetHost(t *testing.T) { var authArguments auth.AuthArguments t.Setenv("DATABRICKS_CONFIG_FILE", "./testdata/.databrickscfg") - ctx, _ := cmdio.SetupTest(context.Background(), cmdio.TestOptions{}) + ctx, _ := cmdio.SetupTest(t.Context(), cmdio.TestOptions{}) profile1 := loadTestProfile(t, ctx, "profile-1") profile2 := loadTestProfile(t, ctx, "profile-2") @@ -76,7 +76,7 @@ func TestSetHost(t *testing.T) { func TestSetAccountId(t *testing.T) { var authArguments auth.AuthArguments t.Setenv("DATABRICKS_CONFIG_FILE", "./testdata/.databrickscfg") - ctx, _ := cmdio.SetupTest(context.Background(), cmdio.TestOptions{}) + ctx, _ := cmdio.SetupTest(t.Context(), cmdio.TestOptions{}) accountProfile := loadTestProfile(t, ctx, "account-profile") @@ -104,7 +104,7 @@ func TestSetAccountId(t *testing.T) { func TestSetWorkspaceIDForUnifiedHost(t *testing.T) { var authArguments auth.AuthArguments t.Setenv("DATABRICKS_CONFIG_FILE", "./testdata/.databrickscfg") - ctx, _ := cmdio.SetupTest(context.Background(), cmdio.TestOptions{}) + ctx, _ := cmdio.SetupTest(t.Context(), cmdio.TestOptions{}) unifiedWorkspaceProfile := loadTestProfile(t, ctx, "unified-workspace") unifiedAccountProfile := loadTestProfile(t, ctx, "unified-account") @@ -161,7 +161,7 @@ func TestSetWorkspaceIDForUnifiedHost(t *testing.T) { func TestPromptForWorkspaceIDInNonInteractiveMode(t *testing.T) { // Setup non-interactive context - ctx, _ := cmdio.SetupTest(context.Background(), cmdio.TestOptions{}) + ctx, _ := cmdio.SetupTest(t.Context(), cmdio.TestOptions{}) // Test that promptForWorkspaceID returns empty string (no error) in non-interactive mode workspaceID, err := promptForWorkspaceID(ctx) @@ -231,7 +231,7 @@ func TestLoadProfileByNameAndClusterID(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() if tc.configFileEnv != "" { t.Setenv("DATABRICKS_CONFIG_FILE", tc.configFileEnv) diff --git a/cmd/auth/profiles_test.go b/cmd/auth/profiles_test.go index 91ff4d049f..1dfe662889 100644 --- a/cmd/auth/profiles_test.go +++ b/cmd/auth/profiles_test.go @@ -1,7 +1,6 @@ package auth import ( - "context" "path/filepath" "runtime" "testing" @@ -13,7 +12,7 @@ import ( ) func TestProfiles(t *testing.T) { - ctx := context.Background() + ctx := t.Context() dir := t.TempDir() configFile := filepath.Join(dir, ".databrickscfg") diff --git a/cmd/auth/token_test.go b/cmd/auth/token_test.go index 191b9ca609..e070e9bd15 100644 --- a/cmd/auth/token_test.go +++ b/cmd/auth/token_test.go @@ -661,7 +661,7 @@ func TestToken_loadToken(t *testing.T) { } for _, c := range cases { t.Run(c.name, func(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) if c.setupCtx != nil { ctx = c.setupCtx(ctx) } diff --git a/cmd/bundle/generate/dashboard_test.go b/cmd/bundle/generate/dashboard_test.go index 61929a6926..d7cb53ad46 100644 --- a/cmd/bundle/generate/dashboard_test.go +++ b/cmd/bundle/generate/dashboard_test.go @@ -1,7 +1,6 @@ package generate import ( - "context" "testing" "github.com/databricks/cli/bundle" @@ -35,7 +34,7 @@ func TestDashboard_ErrorOnLegacyDashboard(t *testing.T) { Message: "dbsqlDashboard is not user-facing.", }) - ctx := context.Background() + ctx := t.Context() ctx = logdiag.InitContext(ctx) logdiag.SetCollect(ctx, true) b := &bundle.Bundle{} diff --git a/cmd/configure/configure_test.go b/cmd/configure/configure_test.go index 309c65363c..bd99e6cbe7 100644 --- a/cmd/configure/configure_test.go +++ b/cmd/configure/configure_test.go @@ -1,7 +1,6 @@ package configure_test import ( - "context" "os" "path/filepath" "runtime" @@ -45,7 +44,7 @@ func getTempFileWithContent(t *testing.T, tempHomeDir, content string) *os.File } func TestDefaultConfigureNoInteractive(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tempHomeDir := setup(t) inp := getTempFileWithContent(t, tempHomeDir, "token\n") oldStdin := os.Stdin @@ -77,7 +76,7 @@ func TestDefaultConfigureNoInteractive(t *testing.T) { func TestConfigFileFromEnvNoInteractive(t *testing.T) { // TODO: Replace with similar test code from go SDK, once we start using it directly - ctx := context.Background() + ctx := t.Context() tempHomeDir := setup(t) defaultCfgPath := filepath.Join(tempHomeDir, ".databrickscfg") cfgPath := filepath.Join(tempHomeDir, "overwrite-databricks-cfg") @@ -116,7 +115,7 @@ func TestConfigFileFromEnvNoInteractive(t *testing.T) { } func TestEnvVarsConfigureNoInteractive(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tempHomeDir := setup(t) cfgPath := filepath.Join(tempHomeDir, ".databrickscfg") inp := getTempFileWithContent(t, tempHomeDir, "token\n") @@ -155,7 +154,7 @@ func TestEnvVarsConfigureNoInteractive(t *testing.T) { } func TestEnvVarsConfigureNoArgsNoInteractive(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tempHomeDir := setup(t) cfgPath := filepath.Join(tempHomeDir, ".databrickscfg") @@ -182,7 +181,7 @@ func TestEnvVarsConfigureNoArgsNoInteractive(t *testing.T) { } func TestCustomProfileConfigureNoInteractive(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tempHomeDir := setup(t) cfgPath := filepath.Join(tempHomeDir, ".databrickscfg") inp := getTempFileWithContent(t, tempHomeDir, "token\n") diff --git a/cmd/fs/helpers_test.go b/cmd/fs/helpers_test.go index 57f180829f..d0ccdd4a20 100644 --- a/cmd/fs/helpers_test.go +++ b/cmd/fs/helpers_test.go @@ -17,7 +17,7 @@ import ( func TestFilerForPathForLocalPaths(t *testing.T) { tmpDir := t.TempDir() - ctx := context.Background() + ctx := t.Context() f, path, err := filerForPath(ctx, tmpDir) assert.NoError(t, err) @@ -29,7 +29,7 @@ func TestFilerForPathForLocalPaths(t *testing.T) { } func TestFilerForPathForInvalidScheme(t *testing.T) { - ctx := context.Background() + ctx := t.Context() _, _, err := filerForPath(ctx, "dbf:/a") assert.ErrorContains(t, err, "invalid scheme") @@ -58,7 +58,7 @@ func TestFilerForWindowsLocalPaths(t *testing.T) { t.SkipNow() } - ctx := context.Background() + ctx := t.Context() testWindowsFilerForPath(t, ctx, `c:\abc`) testWindowsFilerForPath(t, ctx, `c:abc`) testWindowsFilerForPath(t, ctx, `d:\abc`) @@ -72,7 +72,7 @@ func mockMustWorkspaceClientFunc(cmd *cobra.Command, args []string) error { func setupCommand(t *testing.T) (*cobra.Command, *mocks.MockWorkspaceClient) { m := mocks.NewMockWorkspaceClient(t) - ctx := context.Background() + ctx := t.Context() ctx = cmdctx.SetWorkspaceClient(ctx, m.WorkspaceClient) cmd := &cobra.Command{} diff --git a/cmd/labs/github/ref_test.go b/cmd/labs/github/ref_test.go index 9668cd7ec8..d8ea17ecd4 100644 --- a/cmd/labs/github/ref_test.go +++ b/cmd/labs/github/ref_test.go @@ -1,7 +1,6 @@ package github import ( - "context" "net/http" "net/http/httptest" "testing" @@ -23,7 +22,7 @@ func TestFileFromRef(t *testing.T) { })) defer server.Close() - ctx := context.Background() + ctx := t.Context() ctx = WithUserContentOverride(ctx, server.URL) raw, err := ReadFileFromRef(ctx, "databrickslabs", "ucx", "main", "README.md") @@ -45,7 +44,7 @@ func TestDownloadZipball(t *testing.T) { })) defer server.Close() - ctx := context.Background() + ctx := t.Context() ctx = WithApiOverride(ctx, server.URL) raw, err := DownloadZipball(ctx, "databrickslabs", "ucx", "main") diff --git a/cmd/labs/github/releases_test.go b/cmd/labs/github/releases_test.go index 88a47b2410..60b1fc54e7 100644 --- a/cmd/labs/github/releases_test.go +++ b/cmd/labs/github/releases_test.go @@ -1,7 +1,6 @@ package github import ( - "context" "net/http" "net/http/httptest" "os" @@ -26,7 +25,7 @@ func TestLoadsReleasesForCLI(t *testing.T) { })) defer server.Close() - ctx := context.Background() + ctx := t.Context() ctx = WithApiOverride(ctx, server.URL) r := NewReleaseCache("databricks", "cli", t.TempDir(), false) @@ -46,7 +45,7 @@ func TestLoadsReleasesWhenOffline(t *testing.T) { err := os.WriteFile(cacheFile, []byte(cache), 0o644) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() r := NewReleaseCache("databricks", "cli", cacheDir, true) all, err := r.Load(ctx) assert.NoError(t, err) @@ -54,7 +53,7 @@ func TestLoadsReleasesWhenOffline(t *testing.T) { } func TestLoadingErrorWhenOffline(t *testing.T) { - ctx := context.Background() + ctx := t.Context() r := NewReleaseCache("databricks", "cli", t.TempDir(), true) all, err := r.Load(ctx) assert.Error(t, err) diff --git a/cmd/labs/github/repositories_test.go b/cmd/labs/github/repositories_test.go index efd6627bac..f30ed9c145 100644 --- a/cmd/labs/github/repositories_test.go +++ b/cmd/labs/github/repositories_test.go @@ -1,7 +1,6 @@ package github import ( - "context" "fmt" "maps" "net/http" @@ -24,7 +23,7 @@ func TestRepositories(t *testing.T) { })) defer server.Close() - ctx := context.Background() + ctx := t.Context() ctx = WithApiOverride(ctx, server.URL) r := NewRepositoryCache("databrickslabs", t.TempDir()) @@ -74,7 +73,7 @@ func TestRepositoriesPagination(t *testing.T) { })) defer server.Close() - ctx := context.Background() + ctx := t.Context() ctx = WithApiOverride(ctx, server.URL) repos, err := getRepositories(ctx, "databrickslabs") diff --git a/cmd/labs/installed_test.go b/cmd/labs/installed_test.go index 3c38e5e11c..0a9a40aaba 100644 --- a/cmd/labs/installed_test.go +++ b/cmd/labs/installed_test.go @@ -1,7 +1,6 @@ package labs_test import ( - "context" "testing" "github.com/databricks/cli/internal/testcli" @@ -9,7 +8,7 @@ import ( ) func TestListsInstalledProjects(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = env.WithUserHomeDir(ctx, "project/testdata/installed-in-home") r := testcli.NewRunner(t, ctx, "labs", "installed") r.RunAndExpectOutput(` diff --git a/cmd/labs/list_test.go b/cmd/labs/list_test.go index 4388fdd0e9..d1f763a7f3 100644 --- a/cmd/labs/list_test.go +++ b/cmd/labs/list_test.go @@ -1,7 +1,6 @@ package labs_test import ( - "context" "testing" "github.com/databricks/cli/internal/testcli" @@ -10,7 +9,7 @@ import ( ) func TestListingWorks(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = env.WithUserHomeDir(ctx, "project/testdata/installed-in-home") c := testcli.NewRunner(t, ctx, "labs", "list") stdout, _, err := c.Run() diff --git a/cmd/labs/localcache/jsonfile_test.go b/cmd/labs/localcache/jsonfile_test.go index 8172b7d14b..02860e3e3d 100644 --- a/cmd/labs/localcache/jsonfile_test.go +++ b/cmd/labs/localcache/jsonfile_test.go @@ -1,7 +1,6 @@ package localcache import ( - "context" "errors" "net/url" "runtime" @@ -12,7 +11,7 @@ import ( ) func TestCreatesDirectoryIfNeeded(t *testing.T) { - ctx := context.Background() + ctx := t.Context() c := NewLocalCache[int64](t.TempDir(), "some/nested/file", 1*time.Minute) thing := []int64{0} tick := func() (int64, error) { @@ -28,7 +27,7 @@ func TestImpossibleToCreateDir(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("No /dev/null on windows") } - ctx := context.Background() + ctx := t.Context() c := NewLocalCache[int64]("/dev/null", "some/nested/file", 1*time.Minute) thing := []int64{0} tick := func() (int64, error) { @@ -43,7 +42,7 @@ func TestRefreshes(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("No /dev/null on windows") } - ctx := context.Background() + ctx := t.Context() c := NewLocalCache[int64](t.TempDir(), "time", 1*time.Minute) thing := []int64{0} tick := func() (int64, error) { @@ -70,7 +69,7 @@ func TestSupportOfflineSystem(t *testing.T) { thing[0] += 1 return thing[0], nil } - ctx := context.Background() + ctx := t.Context() first, err := c.Load(ctx, tick) assert.NoError(t, err) @@ -106,7 +105,7 @@ func TestFolderDisappears(t *testing.T) { t.Log("TICKS") return now, nil } - ctx := context.Background() + ctx := t.Context() _, err := c.Load(ctx, tick) assert.Error(t, err) } @@ -116,14 +115,14 @@ func TestRefreshFails(t *testing.T) { tick := func() (int64, error) { return 0, errors.New("nope") } - ctx := context.Background() + ctx := t.Context() _, err := c.Load(ctx, tick) assert.EqualError(t, err, "refresh: nope") } func TestWrongType(t *testing.T) { c := NewLocalCache[chan int](t.TempDir(), "x", 1*time.Minute) - ctx := context.Background() + ctx := t.Context() _, err := c.Load(ctx, func() (chan int, error) { return make(chan int), nil }) diff --git a/cmd/labs/project/command_test.go b/cmd/labs/project/command_test.go index 453329e1d1..aac2e973a0 100644 --- a/cmd/labs/project/command_test.go +++ b/cmd/labs/project/command_test.go @@ -20,7 +20,7 @@ type echoOut struct { } func devEnvContext(t *testing.T) context.Context { - ctx := context.Background() + ctx := t.Context() ctx = env.WithUserHomeDir(ctx, "testdata/installed-in-home") py, _ := python.DetectExecutable(ctx) py, _ = filepath.Abs(py) diff --git a/cmd/labs/project/installed_test.go b/cmd/labs/project/installed_test.go index e837692d61..9bec83516b 100644 --- a/cmd/labs/project/installed_test.go +++ b/cmd/labs/project/installed_test.go @@ -1,7 +1,6 @@ package project import ( - "context" "testing" "github.com/databricks/cli/libs/env" @@ -9,7 +8,7 @@ import ( ) func TestInstalled(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = env.WithUserHomeDir(ctx, "testdata/installed-in-home") all, err := Installed(ctx) diff --git a/cmd/labs/project/installer_test.go b/cmd/labs/project/installer_test.go index ff1075b149..e192386d73 100644 --- a/cmd/labs/project/installer_test.go +++ b/cmd/labs/project/installer_test.go @@ -104,7 +104,7 @@ func copyTestdata(t *testing.T, name string) string { } func installerContext(t *testing.T, server *httptest.Server) context.Context { - ctx := context.Background() + ctx := t.Context() ctx = github.WithApiOverride(ctx, server.URL) ctx = github.WithUserContentOverride(ctx, server.URL) ctx = env.WithUserHomeDir(ctx, t.TempDir()) diff --git a/cmd/labs/project/interpreters_unix_test.go b/cmd/labs/project/interpreters_unix_test.go index a5bbb64686..11df40fc13 100644 --- a/cmd/labs/project/interpreters_unix_test.go +++ b/cmd/labs/project/interpreters_unix_test.go @@ -3,7 +3,6 @@ package project import ( - "context" "os" "os/exec" "path/filepath" @@ -13,7 +12,7 @@ import ( ) func TestAtLeastOnePythonInstalled(t *testing.T) { - ctx := context.Background() + ctx := t.Context() all, err := DetectInterpreters(ctx) assert.NoError(t, err) a := all.Latest() @@ -24,7 +23,7 @@ func TestAtLeastOnePythonInstalled(t *testing.T) { func TestNoInterpretersFound(t *testing.T) { t.Setenv("PATH", t.TempDir()) - ctx := context.Background() + ctx := t.Context() all, err := DetectInterpreters(ctx) assert.Nil(t, all) assert.Equal(t, ErrNoPythonInterpreters, err) @@ -50,7 +49,7 @@ func TestFilteringInterpreters(t *testing.T) { assert.NoError(t, err) assert.Equal(t, injectedBinary, roguePath) - ctx := context.Background() + ctx := t.Context() all, err := DetectInterpreters(ctx) assert.NoError(t, err) assert.Len(t, all, 3) @@ -64,7 +63,7 @@ func TestFilteringInterpreters(t *testing.T) { func TestInterpretersAtLeastInvalidSemver(t *testing.T) { t.Setenv("PATH", "testdata/other-binaries-filtered") - ctx := context.Background() + ctx := t.Context() all, err := DetectInterpreters(ctx) assert.NoError(t, err) @@ -75,7 +74,7 @@ func TestInterpretersAtLeastInvalidSemver(t *testing.T) { func TestInterpretersAtLeast(t *testing.T) { t.Setenv("PATH", "testdata/other-binaries-filtered") - ctx := context.Background() + ctx := t.Context() all, err := DetectInterpreters(ctx) assert.NoError(t, err) @@ -87,7 +86,7 @@ func TestInterpretersAtLeast(t *testing.T) { func TestInterpretersAtLeastNotSatisfied(t *testing.T) { t.Setenv("PATH", "testdata/other-binaries-filtered") - ctx := context.Background() + ctx := t.Context() all, err := DetectInterpreters(ctx) assert.NoError(t, err) diff --git a/cmd/labs/project/interpreters_win_test.go b/cmd/labs/project/interpreters_win_test.go index 2316daa30b..3bea986c30 100644 --- a/cmd/labs/project/interpreters_win_test.go +++ b/cmd/labs/project/interpreters_win_test.go @@ -3,14 +3,13 @@ package project import ( - "context" "testing" "github.com/stretchr/testify/assert" ) func TestAtLeastOnePythonInstalled(t *testing.T) { - ctx := context.Background() + ctx := t.Context() all, err := DetectInterpreters(ctx) assert.NoError(t, err) a := all.Latest() @@ -21,7 +20,7 @@ func TestAtLeastOnePythonInstalled(t *testing.T) { func TestNoInterpretersFound(t *testing.T) { t.Setenv("PATH", t.TempDir()) - ctx := context.Background() + ctx := t.Context() _, err := DetectInterpreters(ctx) assert.ErrorIs(t, err, ErrNoPythonInterpreters) assert.ErrorContains(t, err, "python.org/downloads") diff --git a/cmd/labs/project/project_test.go b/cmd/labs/project/project_test.go index 79e69bad6e..42f999f414 100644 --- a/cmd/labs/project/project_test.go +++ b/cmd/labs/project/project_test.go @@ -1,7 +1,6 @@ package project import ( - "context" "os" "strings" "testing" @@ -15,7 +14,7 @@ func assertEqualPaths(t *testing.T, expected, actual string) { } func TestLoad(t *testing.T) { - ctx := context.Background() + ctx := t.Context() prj, err := Load(ctx, "testdata/installed-in-home/.databricks/labs/blueprint/lib/labs.yml") assert.NoError(t, err) assertEqualPaths(t, "testdata/installed-in-home/.databricks/labs/blueprint/lib", prj.folder) diff --git a/cmd/pipelines/run_test.go b/cmd/pipelines/run_test.go index b759250bb3..38fc84b3fb 100644 --- a/cmd/pipelines/run_test.go +++ b/cmd/pipelines/run_test.go @@ -1,7 +1,6 @@ package pipelines import ( - "context" "testing" "time" @@ -144,7 +143,7 @@ Pipeline configurations for this update: for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - ctx, stdout := cmdio.NewTestContextWithStdout(context.Background()) + ctx, stdout := cmdio.NewTestContextWithStdout(t.Context()) err := displayPipelineUpdate(ctx, tt.update, tt.pipelineID, tt.events) assert.NoError(t, err) @@ -370,7 +369,7 @@ RUNNING 750ms for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - ctx, stdout := cmdio.NewTestContextWithStdout(context.Background()) + ctx, stdout := cmdio.NewTestContextWithStdout(t.Context()) err := displayProgressEventsDurations(ctx, tt.events) assert.NoError(t, err) diff --git a/cmd/root/auth_options_test.go b/cmd/root/auth_options_test.go index 477c2029e9..3a510ad24d 100644 --- a/cmd/root/auth_options_test.go +++ b/cmd/root/auth_options_test.go @@ -1,14 +1,13 @@ package root import ( - "context" "testing" "github.com/stretchr/testify/assert" ) func TestSkipPrompt(t *testing.T) { - ctx := context.Background() + ctx := t.Context() assert.False(t, shouldSkipPrompt(ctx)) ctx = SkipPrompt(ctx) @@ -16,7 +15,7 @@ func TestSkipPrompt(t *testing.T) { } func TestSkipLoadBundle(t *testing.T) { - ctx := context.Background() + ctx := t.Context() assert.False(t, shouldSkipLoadBundle(ctx)) ctx = SkipLoadBundle(ctx) diff --git a/cmd/root/auth_test.go b/cmd/root/auth_test.go index 78f0dc9c8a..6e03e5687e 100644 --- a/cmd/root/auth_test.go +++ b/cmd/root/auth_test.go @@ -16,7 +16,7 @@ import ( ) func TestEmptyHttpRequest(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) defer cancel() req := emptyHttpRequest(ctx) assert.Equal(t, req.Context(), ctx) @@ -33,7 +33,7 @@ var workspacePromptFn = func(ctx context.Context, cfg *config.Config, retry bool } func expectPrompts(t *testing.T, fn promptFn, config *config.Config) { - ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) + ctx, cancel := context.WithTimeout(t.Context(), 1*time.Second) defer cancel() // Channel to pass errors from the prompting function back to the test. @@ -58,7 +58,7 @@ func expectPrompts(t *testing.T, fn promptFn, config *config.Config) { } func expectReturns(t *testing.T, fn promptFn, config *config.Config) { - ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) + ctx, cancel := context.WithTimeout(t.Context(), 1*time.Second) defer cancel() ctx, _ = cmdio.SetupTest(ctx, cmdio.TestOptions{PromptSupported: true}) @@ -214,7 +214,7 @@ func TestMustAccountClientWorksWithDatabricksCfg(t *testing.T) { 0o755) require.NoError(t, err) - cmd := New(context.Background()) + cmd := New(t.Context()) t.Setenv("DATABRICKS_CONFIG_FILE", configFile) err = MustAccountClient(cmd, []string{}) @@ -224,7 +224,7 @@ func TestMustAccountClientWorksWithDatabricksCfg(t *testing.T) { func TestMustAccountClientWorksWithNoDatabricksCfgButEnvironmentVariables(t *testing.T) { testutil.CleanupEnvironment(t) - ctx, tt := cmdio.SetupTest(context.Background(), cmdio.TestOptions{PromptSupported: true}) + ctx, tt := cmdio.SetupTest(t.Context(), cmdio.TestOptions{PromptSupported: true}) t.Cleanup(tt.Done) cmd := New(ctx) t.Setenv("DATABRICKS_HOST", "https://accounts.azuredatabricks.net/") @@ -238,7 +238,7 @@ func TestMustAccountClientWorksWithNoDatabricksCfgButEnvironmentVariables(t *tes func TestMustAccountClientErrorsWithNoDatabricksCfg(t *testing.T) { testutil.CleanupEnvironment(t) - ctx, tt := cmdio.SetupTest(context.Background(), cmdio.TestOptions{PromptSupported: true}) + ctx, tt := cmdio.SetupTest(t.Context(), cmdio.TestOptions{PromptSupported: true}) t.Cleanup(tt.Done) cmd := New(ctx) @@ -261,7 +261,7 @@ func TestMustAnyClientCanCreateWorkspaceClient(t *testing.T) { 0o755) require.NoError(t, err) - ctx, tt := cmdio.SetupTest(context.Background(), cmdio.TestOptions{PromptSupported: true}) + ctx, tt := cmdio.SetupTest(t.Context(), cmdio.TestOptions{PromptSupported: true}) t.Cleanup(tt.Done) cmd := New(ctx) @@ -290,7 +290,7 @@ func TestMustAnyClientCanCreateAccountClient(t *testing.T) { 0o755) require.NoError(t, err) - ctx, tt := cmdio.SetupTest(context.Background(), cmdio.TestOptions{PromptSupported: true}) + ctx, tt := cmdio.SetupTest(t.Context(), cmdio.TestOptions{PromptSupported: true}) t.Cleanup(tt.Done) cmd := New(ctx) @@ -314,7 +314,7 @@ func TestMustAnyClientWithEmptyDatabricksCfg(t *testing.T) { 0o755) require.NoError(t, err) - ctx, tt := cmdio.SetupTest(context.Background(), cmdio.TestOptions{PromptSupported: true}) + ctx, tt := cmdio.SetupTest(t.Context(), cmdio.TestOptions{PromptSupported: true}) t.Cleanup(tt.Done) cmd := New(ctx) diff --git a/cmd/root/bundle_test.go b/cmd/root/bundle_test.go index 684117cbe3..b4d8e5419a 100644 --- a/cmd/root/bundle_test.go +++ b/cmd/root/bundle_test.go @@ -35,7 +35,7 @@ func setupDatabricksCfg(t *testing.T) { } func emptyCommand(t *testing.T) *cobra.Command { - ctx := context.Background() + ctx := t.Context() ctx = cmdio.MockDiscard(ctx) cmd := &cobra.Command{} cmd.SetContext(ctx) @@ -237,7 +237,7 @@ workspace: err := os.WriteFile(filepath.Join(rootPath, "databricks.yml"), []byte(contents), 0o644) require.NoError(t, err) - ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second) defer cancel() ctx, io := cmdio.SetupTest(ctx, cmdio.TestOptions{PromptSupported: true}) @@ -273,7 +273,7 @@ func TestTargetFlagFull(t *testing.T) { initTargetFlag(cmd) cmd.SetArgs([]string{"version", "--target", "development"}) - ctx := context.Background() + ctx := t.Context() err := Execute(ctx, cmd) assert.NoError(t, err) @@ -285,7 +285,7 @@ func TestTargetFlagShort(t *testing.T) { initTargetFlag(cmd) cmd.SetArgs([]string{"version", "-t", "production"}) - ctx := context.Background() + ctx := t.Context() err := Execute(ctx, cmd) assert.NoError(t, err) @@ -299,7 +299,7 @@ func TestTargetEnvironmentFlag(t *testing.T) { initEnvironmentFlag(cmd) cmd.SetArgs([]string{"version", "--environment", "development"}) - ctx := context.Background() + ctx := t.Context() err := Execute(ctx, cmd) assert.NoError(t, err) diff --git a/cmd/root/root_test.go b/cmd/root/root_test.go index b67c6fcd25..44a0707398 100644 --- a/cmd/root/root_test.go +++ b/cmd/root/root_test.go @@ -2,7 +2,6 @@ package root import ( "bytes" - "context" "testing" "github.com/databricks/cli/libs/cmdctx" @@ -14,7 +13,7 @@ import ( ) func TestExecuteEnrichesAuthErrors(t *testing.T) { - ctx := context.Background() + ctx := t.Context() stderr := &bytes.Buffer{} cmd := &cobra.Command{ @@ -52,7 +51,7 @@ func TestExecuteEnrichesAuthErrors(t *testing.T) { } func TestExecuteNoEnrichmentWithoutConfigUsed(t *testing.T) { - ctx := context.Background() + ctx := t.Context() stderr := &bytes.Buffer{} cmd := &cobra.Command{ @@ -79,7 +78,7 @@ func TestExecuteNoEnrichmentWithoutConfigUsed(t *testing.T) { } func TestExecuteErrAlreadyPrintedNotEnriched(t *testing.T) { - ctx := context.Background() + ctx := t.Context() stderr := &bytes.Buffer{} cmd := &cobra.Command{ diff --git a/cmd/root/user_agent_agent_test.go b/cmd/root/user_agent_agent_test.go index 290cbd021c..0673839c35 100644 --- a/cmd/root/user_agent_agent_test.go +++ b/cmd/root/user_agent_agent_test.go @@ -1,7 +1,6 @@ package root import ( - "context" "testing" "github.com/databricks/cli/libs/agent" @@ -20,7 +19,7 @@ func TestAgentInUserAgent(t *testing.T) { agent.OpenCode, } { t.Run(product, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = agent.Mock(ctx, product) ctx = withAgentInUserAgent(ctx) @@ -30,7 +29,7 @@ func TestAgentInUserAgent(t *testing.T) { } func TestAgentNotSet(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = agent.Mock(ctx, "") ctx = withAgentInUserAgent(ctx) diff --git a/cmd/root/user_agent_command_exec_id_test.go b/cmd/root/user_agent_command_exec_id_test.go index 652d0ddd39..e49d7580a6 100644 --- a/cmd/root/user_agent_command_exec_id_test.go +++ b/cmd/root/user_agent_command_exec_id_test.go @@ -1,7 +1,6 @@ package root import ( - "context" "testing" "github.com/databricks/cli/libs/cmdctx" @@ -10,7 +9,7 @@ import ( ) func TestWithCommandExecIdInUserAgent(t *testing.T) { - ctx := cmdctx.GenerateExecId(context.Background()) + ctx := cmdctx.GenerateExecId(t.Context()) ctx = withCommandExecIdInUserAgent(ctx) // user agent should contain cmd-exec-id/ diff --git a/cmd/root/user_agent_command_test.go b/cmd/root/user_agent_command_test.go index a3f5bbcb1c..9d76d2011c 100644 --- a/cmd/root/user_agent_command_test.go +++ b/cmd/root/user_agent_command_test.go @@ -1,7 +1,6 @@ package root import ( - "context" "testing" "github.com/databricks/databricks-sdk-go/useragent" @@ -29,7 +28,7 @@ func TestWithCommandInUserAgent(t *testing.T) { assert.Equal(t, "hello", commandString(hello)) assert.Equal(t, "hello_world", commandString(world)) - ctx := withCommandInUserAgent(context.Background(), world) + ctx := withCommandInUserAgent(t.Context(), world) ua := useragent.FromContext(ctx) assert.Contains(t, ua, "cmd/hello_world") diff --git a/cmd/root/user_agent_interactive_mode_test.go b/cmd/root/user_agent_interactive_mode_test.go index cac3e8934e..12bcc5e105 100644 --- a/cmd/root/user_agent_interactive_mode_test.go +++ b/cmd/root/user_agent_interactive_mode_test.go @@ -1,7 +1,6 @@ package root import ( - "context" "io" "strings" "testing" @@ -13,7 +12,7 @@ import ( ) func TestInteractiveModeWithCmdIO(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // Initialize cmdio with mock TTY capabilities ctx = cmdio.InContext(ctx, cmdio.NewIO(ctx, flags.OutputText, io.NopCloser(strings.NewReader("")), @@ -28,7 +27,7 @@ func TestInteractiveModeWithCmdIO(t *testing.T) { } func TestInteractiveModeNone(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // MockDiscard sets all TTY flags to false, so InteractiveMode returns "none". ctx = cmdio.MockDiscard(ctx) diff --git a/cmd/root/user_agent_upstream_test.go b/cmd/root/user_agent_upstream_test.go index fc6ea0c75d..2ced4a5ce6 100644 --- a/cmd/root/user_agent_upstream_test.go +++ b/cmd/root/user_agent_upstream_test.go @@ -1,7 +1,6 @@ package root import ( - "context" "testing" "github.com/databricks/databricks-sdk-go/useragent" @@ -10,20 +9,20 @@ import ( func TestUpstreamSet(t *testing.T) { t.Setenv(upstreamEnvVar, "foobar") - ctx := withUpstreamInUserAgent(context.Background()) + ctx := withUpstreamInUserAgent(t.Context()) assert.Contains(t, useragent.FromContext(ctx), "upstream/foobar") } func TestUpstreamSetEmpty(t *testing.T) { t.Setenv(upstreamEnvVar, "") - ctx := withUpstreamInUserAgent(context.Background()) + ctx := withUpstreamInUserAgent(t.Context()) assert.NotContains(t, useragent.FromContext(ctx), "upstream/") } func TestUpstreamVersionSet(t *testing.T) { t.Setenv(upstreamEnvVar, "foobar") t.Setenv(upstreamVersionEnvVar, "0.0.1") - ctx := withUpstreamInUserAgent(context.Background()) + ctx := withUpstreamInUserAgent(t.Context()) assert.Contains(t, useragent.FromContext(ctx), "upstream/foobar") assert.Contains(t, useragent.FromContext(ctx), "upstream-version/0.0.1") } @@ -31,7 +30,7 @@ func TestUpstreamVersionSet(t *testing.T) { func TestUpstreamVersionSetEmpty(t *testing.T) { t.Setenv(upstreamEnvVar, "foobar") t.Setenv(upstreamVersionEnvVar, "") - ctx := withUpstreamInUserAgent(context.Background()) + ctx := withUpstreamInUserAgent(t.Context()) assert.Contains(t, useragent.FromContext(ctx), "upstream/foobar") assert.NotContains(t, useragent.FromContext(ctx), "upstream-version/") } @@ -39,7 +38,7 @@ func TestUpstreamVersionSetEmpty(t *testing.T) { func TestUpstreamVersionSetUpstreamNotSet(t *testing.T) { t.Setenv(upstreamEnvVar, "") t.Setenv(upstreamVersionEnvVar, "0.0.1") - ctx := withUpstreamInUserAgent(context.Background()) + ctx := withUpstreamInUserAgent(t.Context()) assert.NotContains(t, useragent.FromContext(ctx), "upstream/") assert.NotContains(t, useragent.FromContext(ctx), "upstream-version/") } diff --git a/cmd/sync/sync_test.go b/cmd/sync/sync_test.go index fd12125cd4..818c7e013a 100644 --- a/cmd/sync/sync_test.go +++ b/cmd/sync/sync_test.go @@ -1,7 +1,6 @@ package sync import ( - "context" "os" "path/filepath" "strings" @@ -59,7 +58,7 @@ func TestSyncOptionsFromArgs(t *testing.T) { f := syncFlags{} cmd := New() - cmd.SetContext(cmdctx.SetWorkspaceClient(context.Background(), nil)) + cmd.SetContext(cmdctx.SetWorkspaceClient(t.Context(), nil)) opts, err := f.syncOptionsFromArgs(cmd, []string{local, remote}) require.NoError(t, err) assert.Equal(t, local, opts.LocalRoot.Native()) @@ -85,7 +84,7 @@ func TestExcludeFromFlag(t *testing.T) { // Set up the flags f := syncFlags{excludeFrom: excludeFromPath} cmd := New() - cmd.SetContext(cmdctx.SetWorkspaceClient(context.Background(), nil)) + cmd.SetContext(cmdctx.SetWorkspaceClient(t.Context(), nil)) // Test with both exclude flag and exclude-from flag f.exclude = []string{"node_modules/"} diff --git a/experimental/aitools/cmd/query_test.go b/experimental/aitools/cmd/query_test.go index 8b8686aee7..e6580f34aa 100644 --- a/experimental/aitools/cmd/query_test.go +++ b/experimental/aitools/cmd/query_test.go @@ -42,7 +42,7 @@ func TestCleanSQL(t *testing.T) { } func TestExecuteAndPollImmediateSuccess(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) mockAPI := mocksql.NewMockStatementExecutionInterface(t) mockAPI.EXPECT().ExecuteStatement(mock.Anything, mock.MatchedBy(func(req sql.ExecuteStatementRequest) bool { @@ -61,7 +61,7 @@ func TestExecuteAndPollImmediateSuccess(t *testing.T) { } func TestExecuteAndPollImmediateFailure(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) mockAPI := mocksql.NewMockStatementExecutionInterface(t) mockAPI.EXPECT().ExecuteStatement(mock.Anything, mock.Anything).Return(&sql.StatementResponse{ @@ -82,7 +82,7 @@ func TestExecuteAndPollImmediateFailure(t *testing.T) { } func TestExecuteAndPollWithPolling(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) mockAPI := mocksql.NewMockStatementExecutionInterface(t) mockAPI.EXPECT().ExecuteStatement(mock.Anything, mock.Anything).Return(&sql.StatementResponse{ @@ -111,7 +111,7 @@ func TestExecuteAndPollWithPolling(t *testing.T) { } func TestExecuteAndPollFailsDuringPolling(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) mockAPI := mocksql.NewMockStatementExecutionInterface(t) mockAPI.EXPECT().ExecuteStatement(mock.Anything, mock.Anything).Return(&sql.StatementResponse{ @@ -133,7 +133,7 @@ func TestExecuteAndPollFailsDuringPolling(t *testing.T) { } func TestExecuteAndPollCancelledContextCallsCancelExecution(t *testing.T) { - ctx, cancel := context.WithCancel(cmdio.MockDiscard(context.Background())) + ctx, cancel := context.WithCancel(cmdio.MockDiscard(t.Context())) mockAPI := mocksql.NewMockStatementExecutionInterface(t) mockAPI.EXPECT().ExecuteStatement(mock.Anything, mock.Anything).Return(&sql.StatementResponse{ @@ -153,7 +153,7 @@ func TestExecuteAndPollCancelledContextCallsCancelExecution(t *testing.T) { } func TestResolveWarehouseIDWithFlag(t *testing.T) { - ctx := context.Background() + ctx := t.Context() id, err := resolveWarehouseID(ctx, nil, "explicit-id") require.NoError(t, err) assert.Equal(t, "explicit-id", id) @@ -263,7 +263,7 @@ func TestResolveSQLFromFileFlag(t *testing.T) { require.NoError(t, err) cmd := newTestCmd() - result, err := resolveSQL(cmdio.MockDiscard(context.Background()), cmd, nil, path) + result, err := resolveSQL(cmdio.MockDiscard(t.Context()), cmd, nil, path) require.NoError(t, err) assert.Equal(t, "SELECT 1", result) } @@ -275,21 +275,21 @@ func TestResolveSQLFromFileFlagWithComments(t *testing.T) { require.NoError(t, err) cmd := newTestCmd() - result, err := resolveSQL(cmdio.MockDiscard(context.Background()), cmd, nil, path) + result, err := resolveSQL(cmdio.MockDiscard(t.Context()), cmd, nil, path) require.NoError(t, err) assert.Equal(t, "SELECT 1", result) } func TestResolveSQLFileFlagConflictsWithArg(t *testing.T) { cmd := newTestCmd() - _, err := resolveSQL(cmdio.MockDiscard(context.Background()), cmd, []string{"SELECT 1"}, "/some/file.sql") + _, err := resolveSQL(cmdio.MockDiscard(t.Context()), cmd, []string{"SELECT 1"}, "/some/file.sql") require.Error(t, err) assert.Contains(t, err.Error(), "cannot use both --file and a positional SQL argument") } func TestResolveSQLFromPositionalArg(t *testing.T) { cmd := newTestCmd() - result, err := resolveSQL(cmdio.MockDiscard(context.Background()), cmd, []string{"SELECT 42"}, "") + result, err := resolveSQL(cmdio.MockDiscard(t.Context()), cmd, []string{"SELECT 42"}, "") require.NoError(t, err) assert.Equal(t, "SELECT 42", result) } @@ -301,14 +301,14 @@ func TestResolveSQLAutoDetectsSQLFile(t *testing.T) { require.NoError(t, err) cmd := newTestCmd() - result, err := resolveSQL(cmdio.MockDiscard(context.Background()), cmd, []string{path}, "") + result, err := resolveSQL(cmdio.MockDiscard(t.Context()), cmd, []string{path}, "") require.NoError(t, err) assert.Equal(t, "SELECT * FROM sales", result) } func TestResolveSQLNonexistentSQLFileTreatedAsString(t *testing.T) { cmd := newTestCmd() - result, err := resolveSQL(cmdio.MockDiscard(context.Background()), cmd, []string{"nonexistent.sql"}, "") + result, err := resolveSQL(cmdio.MockDiscard(t.Context()), cmd, []string{"nonexistent.sql"}, "") require.NoError(t, err) assert.Equal(t, "nonexistent.sql", result) } @@ -325,7 +325,7 @@ func TestResolveSQLUnreadableSQLFileReturnsError(t *testing.T) { t.Cleanup(func() { _ = os.Chmod(path, 0o644) }) cmd := newTestCmd() - _, err = resolveSQL(cmdio.MockDiscard(context.Background()), cmd, []string{path}, "") + _, err = resolveSQL(cmdio.MockDiscard(t.Context()), cmd, []string{path}, "") require.Error(t, err) assert.Contains(t, err.Error(), "read SQL file") } @@ -334,7 +334,7 @@ func TestResolveSQLFromStdin(t *testing.T) { cmd := newTestCmd() cmd.SetIn(strings.NewReader("SELECT 1 FROM stdin_test")) - result, err := resolveSQL(cmdio.MockDiscard(context.Background()), cmd, nil, "") + result, err := resolveSQL(cmdio.MockDiscard(t.Context()), cmd, nil, "") require.NoError(t, err) assert.Equal(t, "SELECT 1 FROM stdin_test", result) } @@ -346,7 +346,7 @@ func TestResolveSQLEmptyFileReturnsError(t *testing.T) { require.NoError(t, err) cmd := newTestCmd() - _, err = resolveSQL(cmdio.MockDiscard(context.Background()), cmd, nil, path) + _, err = resolveSQL(cmdio.MockDiscard(t.Context()), cmd, nil, path) require.Error(t, err) assert.Contains(t, err.Error(), "empty") } @@ -358,14 +358,14 @@ func TestResolveSQLCommentsOnlyFileReturnsError(t *testing.T) { require.NoError(t, err) cmd := newTestCmd() - _, err = resolveSQL(cmdio.MockDiscard(context.Background()), cmd, nil, path) + _, err = resolveSQL(cmdio.MockDiscard(t.Context()), cmd, nil, path) require.Error(t, err) assert.Contains(t, err.Error(), "empty") } func TestResolveSQLMissingFileReturnsError(t *testing.T) { cmd := newTestCmd() - _, err := resolveSQL(cmdio.MockDiscard(context.Background()), cmd, nil, "/nonexistent/path/query.sql") + _, err := resolveSQL(cmdio.MockDiscard(t.Context()), cmd, nil, "/nonexistent/path/query.sql") require.Error(t, err) assert.Contains(t, err.Error(), "read SQL file") } diff --git a/experimental/aitools/lib/agents/recommend_test.go b/experimental/aitools/lib/agents/recommend_test.go index 1a286faca8..c2c2769921 100644 --- a/experimental/aitools/lib/agents/recommend_test.go +++ b/experimental/aitools/lib/agents/recommend_test.go @@ -33,7 +33,7 @@ func TestRecommendSkillsInstallSkipsWhenSkillsExist(t *testing.T) { } defer func() { Registry = origRegistry }() - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) err := RecommendSkillsInstall(ctx, noopInstall) assert.NoError(t, err) } @@ -45,7 +45,7 @@ func TestRecommendSkillsInstallSkipsWhenNoAgents(t *testing.T) { Registry = []Agent{} defer func() { Registry = origRegistry }() - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) err := RecommendSkillsInstall(ctx, noopInstall) assert.NoError(t, err) } @@ -64,7 +64,7 @@ func TestRecommendSkillsInstallNonInteractive(t *testing.T) { } defer func() { Registry = origRegistry }() - ctx, stderr := cmdio.NewTestContextWithStderr(context.Background()) + ctx, stderr := cmdio.NewTestContextWithStderr(t.Context()) err := RecommendSkillsInstall(ctx, noopInstall) require.NoError(t, err) assert.Contains(t, stderr.String(), "databricks experimental aitools skills install") @@ -84,7 +84,7 @@ func TestRecommendSkillsInstallInteractiveDecline(t *testing.T) { } defer func() { Registry = origRegistry }() - ctx, testIO := cmdio.SetupTest(context.Background(), cmdio.TestOptions{PromptSupported: true}) + ctx, testIO := cmdio.SetupTest(t.Context(), cmdio.TestOptions{PromptSupported: true}) defer testIO.Done() // Drain stderr so the prompt write doesn't block. diff --git a/experimental/aitools/lib/agents/skills_test.go b/experimental/aitools/lib/agents/skills_test.go index e7c15714cf..15baba9c8f 100644 --- a/experimental/aitools/lib/agents/skills_test.go +++ b/experimental/aitools/lib/agents/skills_test.go @@ -15,7 +15,7 @@ func TestHasDatabricksSkillsInstalledNoAgents(t *testing.T) { Registry = []Agent{} defer func() { Registry = origRegistry }() - assert.True(t, HasDatabricksSkillsInstalled(context.Background())) + assert.True(t, HasDatabricksSkillsInstalled(t.Context())) } func TestHasDatabricksSkillsInstalledCanonicalOnly(t *testing.T) { @@ -33,7 +33,7 @@ func TestHasDatabricksSkillsInstalledCanonicalOnly(t *testing.T) { } defer func() { Registry = origRegistry }() - assert.True(t, HasDatabricksSkillsInstalled(context.Background())) + assert.True(t, HasDatabricksSkillsInstalled(t.Context())) } func TestHasDatabricksSkillsInstalledIgnoresAgentDir(t *testing.T) { @@ -53,7 +53,7 @@ func TestHasDatabricksSkillsInstalledIgnoresAgentDir(t *testing.T) { } defer func() { Registry = origRegistry }() - assert.False(t, HasDatabricksSkillsInstalled(context.Background())) + assert.False(t, HasDatabricksSkillsInstalled(t.Context())) } func TestHasDatabricksSkillsInstalledWithOnlyNonDatabricksSkills(t *testing.T) { @@ -73,7 +73,7 @@ func TestHasDatabricksSkillsInstalledWithOnlyNonDatabricksSkills(t *testing.T) { } defer func() { Registry = origRegistry }() - assert.False(t, HasDatabricksSkillsInstalled(context.Background())) + assert.False(t, HasDatabricksSkillsInstalled(t.Context())) } func TestHasDatabricksSkillsInstalledNoSkillsDir(t *testing.T) { @@ -90,7 +90,7 @@ func TestHasDatabricksSkillsInstalledNoSkillsDir(t *testing.T) { } defer func() { Registry = origRegistry }() - assert.False(t, HasDatabricksSkillsInstalled(context.Background())) + assert.False(t, HasDatabricksSkillsInstalled(t.Context())) } func TestHasDatabricksSkillsInstalledCustomSubdirNotChecked(t *testing.T) { @@ -110,7 +110,7 @@ func TestHasDatabricksSkillsInstalledCustomSubdirNotChecked(t *testing.T) { } defer func() { Registry = origRegistry }() - assert.False(t, HasDatabricksSkillsInstalled(context.Background())) + assert.False(t, HasDatabricksSkillsInstalled(t.Context())) } func TestHasDatabricksSkillsInstalledDatabricksAppsCanonical(t *testing.T) { @@ -132,5 +132,5 @@ func TestHasDatabricksSkillsInstalledDatabricksAppsCanonical(t *testing.T) { } defer func() { Registry = origRegistry }() - assert.True(t, HasDatabricksSkillsInstalled(context.Background())) + assert.True(t, HasDatabricksSkillsInstalled(t.Context())) } diff --git a/experimental/aitools/lib/detector/detector_test.go b/experimental/aitools/lib/detector/detector_test.go index 4895605019..3c81f44764 100644 --- a/experimental/aitools/lib/detector/detector_test.go +++ b/experimental/aitools/lib/detector/detector_test.go @@ -1,7 +1,6 @@ package detector_test import ( - "context" "os" "path/filepath" "testing" @@ -13,7 +12,7 @@ import ( func TestDetectorRegistry_EmptyDir(t *testing.T) { dir := t.TempDir() - ctx := context.Background() + ctx := t.Context() registry := detector.NewRegistry() detected := registry.Detect(ctx, dir) @@ -25,7 +24,7 @@ func TestDetectorRegistry_EmptyDir(t *testing.T) { func TestDetectorRegistry_EmptyBundle(t *testing.T) { dir := t.TempDir() - ctx := context.Background() + ctx := t.Context() bundleYml := `bundle: name: empty-project @@ -42,7 +41,7 @@ func TestDetectorRegistry_EmptyBundle(t *testing.T) { func TestDetectorRegistry_BundleWithApps(t *testing.T) { dir := t.TempDir() - ctx := context.Background() + ctx := t.Context() bundleYml := `bundle: name: my-app @@ -62,7 +61,7 @@ resources: func TestDetectorRegistry_BundleWithJobs(t *testing.T) { dir := t.TempDir() - ctx := context.Background() + ctx := t.Context() bundleYml := `bundle: name: my-job @@ -82,7 +81,7 @@ resources: func TestDetectorRegistry_CombinedBundle(t *testing.T) { dir := t.TempDir() - ctx := context.Background() + ctx := t.Context() bundleYml := `bundle: name: my-project @@ -105,7 +104,7 @@ resources: func TestDetectorRegistry_AppkitTemplate(t *testing.T) { dir := t.TempDir() - ctx := context.Background() + ctx := t.Context() // bundle + package.json with appkit marker bundleYml := `bundle: diff --git a/experimental/aitools/lib/installer/installer_test.go b/experimental/aitools/lib/installer/installer_test.go index d570a9853a..5caa1e3b57 100644 --- a/experimental/aitools/lib/installer/installer_test.go +++ b/experimental/aitools/lib/installer/installer_test.go @@ -1,7 +1,6 @@ package installer import ( - "context" "os" "path/filepath" "testing" @@ -12,7 +11,7 @@ import ( ) func TestBackupThirdPartySkillDestDoesNotExist(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) destDir := filepath.Join(t.TempDir(), "nonexistent") err := backupThirdPartySkill(ctx, destDir, "/canonical", "databricks", "Test Agent") @@ -20,7 +19,7 @@ func TestBackupThirdPartySkillDestDoesNotExist(t *testing.T) { } func TestBackupThirdPartySkillSymlinkToCanonical(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) tmp := t.TempDir() canonicalDir := filepath.Join(tmp, "canonical", "databricks") @@ -41,7 +40,7 @@ func TestBackupThirdPartySkillSymlinkToCanonical(t *testing.T) { } func TestBackupThirdPartySkillRegularDir(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) tmp := t.TempDir() destDir := filepath.Join(tmp, "agent", "skills", "databricks") @@ -69,7 +68,7 @@ func TestBackupThirdPartySkillRegularDir(t *testing.T) { } func TestBackupThirdPartySkillSymlinkToOtherTarget(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) tmp := t.TempDir() otherDir := filepath.Join(tmp, "other", "databricks") @@ -96,7 +95,7 @@ func TestBackupThirdPartySkillSymlinkToOtherTarget(t *testing.T) { } func TestBackupThirdPartySkillRegularFile(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) tmp := t.TempDir() // Edge case: destDir is a file, not a directory. diff --git a/experimental/aitools/lib/mcp/middleware_test.go b/experimental/aitools/lib/mcp/middleware_test.go index 34637c10be..a80811c563 100644 --- a/experimental/aitools/lib/mcp/middleware_test.go +++ b/experimental/aitools/lib/mcp/middleware_test.go @@ -81,7 +81,7 @@ func TestMiddlewareChain(t *testing.T) { chain := mcp.Chain([]mcp.Middleware{mw1, mw2}, sessionData, handler) req := &mcp.CallToolRequest{} - result, err := chain(context.Background(), req) + result, err := chain(t.Context(), req) require.NoError(t, err) require.NotNil(t, result) @@ -121,7 +121,7 @@ func TestMiddlewareShortCircuit(t *testing.T) { chain := mcp.Chain([]mcp.Middleware{mw1, mw2}, sessionData, handler) req := &mcp.CallToolRequest{} - result, err := chain(context.Background(), req) + result, err := chain(t.Context(), req) require.NoError(t, err) require.NotNil(t, result) @@ -145,7 +145,7 @@ func TestMiddlewareError(t *testing.T) { chain := mcp.Chain([]mcp.Middleware{mw}, sessionData, handler) req := &mcp.CallToolRequest{} - result, err := chain(context.Background(), req) + result, err := chain(t.Context(), req) assert.Nil(t, result) assert.Equal(t, expectedErr, err) @@ -179,7 +179,7 @@ func TestMiddlewareSession(t *testing.T) { chain := mcp.Chain([]mcp.Middleware{mw1, mw2}, sessionData, handler) req := &mcp.CallToolRequest{} - _, err := chain(context.Background(), req) + _, err := chain(t.Context(), req) require.NoError(t, err) require.NotNil(t, capturedData) @@ -196,7 +196,7 @@ func TestMiddlewareSession(t *testing.T) { func TestMiddlewareContextAccess(t *testing.T) { type contextKey string testKey := contextKey("test-key") - ctx := context.WithValue(context.Background(), testKey, "test-value") + ctx := context.WithValue(t.Context(), testKey, "test-value") mw := mcp.NewMiddleware(func(mwCtx *mcp.MiddlewareContext, next mcp.NextFunc) (*mcp.CallToolResult, error) { val := mwCtx.Ctx.Value(testKey) @@ -319,7 +319,7 @@ func TestServerSessionPersistence(t *testing.T) { // Call the tool 3 times for range 3 { - _, err := toolHandler(context.Background(), &mcp.CallToolRequest{}) + _, err := toolHandler(t.Context(), &mcp.CallToolRequest{}) require.NoError(t, err) } diff --git a/experimental/aitools/lib/providers/clitools/configure_auth_test.go b/experimental/aitools/lib/providers/clitools/configure_auth_test.go index 5d902ae234..1dfd2d3215 100644 --- a/experimental/aitools/lib/providers/clitools/configure_auth_test.go +++ b/experimental/aitools/lib/providers/clitools/configure_auth_test.go @@ -1,7 +1,6 @@ package clitools import ( - "context" "os" "testing" @@ -16,7 +15,7 @@ func TestConfigureAuthWithSkipCheck(t *testing.T) { os.Setenv("DATABRICKS_MCP_SKIP_AUTH_CHECK", "1") defer os.Unsetenv("DATABRICKS_MCP_SKIP_AUTH_CHECK") - ctx := context.Background() + ctx := t.Context() sess := session.NewSession() host := "https://test.cloud.databricks.com" @@ -38,7 +37,7 @@ func TestConfigureAuthStoresClientInSession(t *testing.T) { t.Skip("Skipping test: no Databricks configuration found") } - ctx := context.Background() + ctx := t.Context() sess := session.NewSession() client, err := ConfigureAuth(ctx, sess, nil, nil) @@ -58,7 +57,7 @@ func TestConfigureAuthWithCustomHost(t *testing.T) { t.Skip("Skipping test: DATABRICKS_HOST not set") } - ctx := context.Background() + ctx := t.Context() sess := session.NewSession() host := os.Getenv("DATABRICKS_HOST") @@ -75,7 +74,7 @@ func TestConfigureAuthWithCustomHost(t *testing.T) { } func TestWrapAuthError(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tests := []struct { name string diff --git a/experimental/aitools/lib/session/session_test.go b/experimental/aitools/lib/session/session_test.go index 395d24cf32..890c50a8aa 100644 --- a/experimental/aitools/lib/session/session_test.go +++ b/experimental/aitools/lib/session/session_test.go @@ -1,7 +1,6 @@ package session import ( - "context" "testing" "time" ) @@ -25,7 +24,7 @@ func TestNewSession(t *testing.T) { func TestSession_SetWorkDir(t *testing.T) { s := NewSession() - ctx := WithSession(context.Background(), s) + ctx := WithSession(t.Context(), s) // First set should succeed err := SetWorkDir(ctx, "/tmp/test") @@ -52,7 +51,7 @@ func TestSession_SetWorkDir(t *testing.T) { func TestSession_GetWorkDir_NotSet(t *testing.T) { s := NewSession() - ctx := WithSession(context.Background(), s) + ctx := WithSession(t.Context(), s) _, err := GetWorkDir(ctx) if err == nil { diff --git a/experimental/ssh/internal/setup/setup_test.go b/experimental/ssh/internal/setup/setup_test.go index 975828a3c8..ef1e2490ec 100644 --- a/experimental/ssh/internal/setup/setup_test.go +++ b/experimental/ssh/internal/setup/setup_test.go @@ -1,7 +1,6 @@ package setup import ( - "context" "errors" "fmt" "os" @@ -18,7 +17,7 @@ import ( ) func TestValidateClusterAccess_SingleUser(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) m := mocks.NewMockWorkspaceClient(t) clustersAPI := m.GetMockClustersAPI() @@ -31,7 +30,7 @@ func TestValidateClusterAccess_SingleUser(t *testing.T) { } func TestValidateClusterAccess_InvalidAccessMode(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) m := mocks.NewMockWorkspaceClient(t) clustersAPI := m.GetMockClustersAPI() @@ -45,7 +44,7 @@ func TestValidateClusterAccess_InvalidAccessMode(t *testing.T) { } func TestValidateClusterAccess_ClusterNotFound(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) m := mocks.NewMockWorkspaceClient(t) clustersAPI := m.GetMockClustersAPI() @@ -203,7 +202,7 @@ func TestGenerateHostConfig_PathEscaping(t *testing.T) { } func TestSetup_SuccessfulWithNewConfigFile(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) tmpDir := t.TempDir() t.Setenv("HOME", tmpDir) t.Setenv("USERPROFILE", tmpDir) @@ -258,7 +257,7 @@ func TestSetup_SuccessfulWithNewConfigFile(t *testing.T) { } func TestSetup_SuccessfulWithExistingConfigFile(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) tmpDir := t.TempDir() t.Setenv("HOME", tmpDir) t.Setenv("USERPROFILE", tmpDir) diff --git a/experimental/ssh/internal/sshconfig/sshconfig_test.go b/experimental/ssh/internal/sshconfig/sshconfig_test.go index 5fa13923ee..a455bb7dce 100644 --- a/experimental/ssh/internal/sshconfig/sshconfig_test.go +++ b/experimental/ssh/internal/sshconfig/sshconfig_test.go @@ -1,7 +1,6 @@ package sshconfig import ( - "context" "os" "path/filepath" "testing" @@ -155,7 +154,7 @@ func TestHostConfigExists(t *testing.T) { } func TestCreateOrUpdateHostConfig_NewConfig(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) tmpDir := t.TempDir() t.Setenv("HOME", tmpDir) t.Setenv("USERPROFILE", tmpDir) @@ -173,7 +172,7 @@ func TestCreateOrUpdateHostConfig_NewConfig(t *testing.T) { } func TestCreateOrUpdateHostConfig_ExistingConfigNoRecreate(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) tmpDir := t.TempDir() t.Setenv("HOME", tmpDir) t.Setenv("USERPROFILE", tmpDir) @@ -198,7 +197,7 @@ func TestCreateOrUpdateHostConfig_ExistingConfigNoRecreate(t *testing.T) { } func TestCreateOrUpdateHostConfig_ExistingConfigWithRecreate(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) tmpDir := t.TempDir() t.Setenv("HOME", tmpDir) t.Setenv("USERPROFILE", tmpDir) diff --git a/experimental/ssh/internal/vscode/settings_test.go b/experimental/ssh/internal/vscode/settings_test.go index 439ed1ee07..6bffdef84d 100644 --- a/experimental/ssh/internal/vscode/settings_test.go +++ b/experimental/ssh/internal/vscode/settings_test.go @@ -1,7 +1,6 @@ package vscode import ( - "context" "encoding/json" "os" "path/filepath" @@ -53,7 +52,7 @@ func TestGetDefaultSettingsPath_VSCode_Linux(t *testing.T) { t.Skip("Skipping Linux-specific test") } - ctx := context.Background() + ctx := t.Context() ctx = env.Set(ctx, "HOME", "/home/testuser") path, err := getDefaultSettingsPath(ctx, vscodeIDE) @@ -66,7 +65,7 @@ func TestGetDefaultSettingsPath_Cursor_Linux(t *testing.T) { t.Skip("Skipping Linux-specific test") } - ctx := context.Background() + ctx := t.Context() ctx = env.Set(ctx, "HOME", "/home/testuser") path, err := getDefaultSettingsPath(ctx, cursorIDE) @@ -79,7 +78,7 @@ func TestGetDefaultSettingsPath_VSCode_Darwin(t *testing.T) { t.Skip("Skipping Darwin-specific test") } - ctx := context.Background() + ctx := t.Context() ctx = env.Set(ctx, "HOME", "/Users/testuser") path, err := getDefaultSettingsPath(ctx, vscodeIDE) @@ -92,7 +91,7 @@ func TestGetDefaultSettingsPath_Cursor_Darwin(t *testing.T) { t.Skip("Skipping Darwin-specific test") } - ctx := context.Background() + ctx := t.Context() ctx = env.Set(ctx, "HOME", "/Users/testuser") path, err := getDefaultSettingsPath(ctx, cursorIDE) @@ -105,7 +104,7 @@ func TestGetDefaultSettingsPath_VSCode_Windows(t *testing.T) { t.Skip("Skipping Windows-specific test") } - ctx := context.Background() + ctx := t.Context() ctx = env.Set(ctx, "APPDATA", `C:\Users\testuser\AppData\Roaming`) path, err := getDefaultSettingsPath(ctx, vscodeIDE) @@ -118,7 +117,7 @@ func TestGetDefaultSettingsPath_Cursor_Windows(t *testing.T) { t.Skip("Skipping Windows-specific test") } - ctx := context.Background() + ctx := t.Context() ctx = env.Set(ctx, "APPDATA", `C:\Users\testuser\AppData\Roaming`) path, err := getDefaultSettingsPath(ctx, cursorIDE) @@ -437,7 +436,7 @@ func TestBackupSettings(t *testing.T) { err := os.WriteFile(settingsPath, originalContent, 0o600) require.NoError(t, err) - ctx, _ := cmdio.NewTestContextWithStderr(context.Background()) + ctx, _ := cmdio.NewTestContextWithStderr(t.Context()) // First backup: should create .original.bak err = backupSettings(ctx, settingsPath) diff --git a/integration/bundle/generate_job_test.go b/integration/bundle/generate_job_test.go index f3c4c78296..8c51a55d40 100644 --- a/integration/bundle/generate_job_test.go +++ b/integration/bundle/generate_job_test.go @@ -32,7 +32,7 @@ func TestGenerateFromExistingJobAndDeploy(t *testing.T) { jobId := gt.createTestJob(ctx) t.Cleanup(func() { - gt.destroyJob(ctx, jobId) + gt.destroyJob(context.WithoutCancel(ctx), jobId) }) ctx = env.Set(ctx, "BUNDLE_ROOT", bundleRoot) diff --git a/integration/bundle/generate_pipeline_test.go b/integration/bundle/generate_pipeline_test.go index 3565ab928b..b1f68f79df 100644 --- a/integration/bundle/generate_pipeline_test.go +++ b/integration/bundle/generate_pipeline_test.go @@ -30,7 +30,7 @@ func TestGenerateFromExistingPipelineAndDeploy(t *testing.T) { pipelineId, name := gt.createTestPipeline(ctx) t.Cleanup(func() { - gt.destroyPipeline(ctx, pipelineId) + gt.destroyPipeline(context.WithoutCancel(ctx), pipelineId) }) ctx = env.Set(ctx, "BUNDLE_ROOT", bundleRoot) diff --git a/integration/bundle/init_test.go b/integration/bundle/init_test.go index 7d3b0b1520..6bec010f7b 100644 --- a/integration/bundle/init_test.go +++ b/integration/bundle/init_test.go @@ -1,7 +1,6 @@ package bundle_test import ( - "context" "os" "path/filepath" "strconv" @@ -16,7 +15,7 @@ import ( ) func TestBundleInitErrorOnUnknownFields(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tmpDir := t.TempDir() _, _, err := testcli.RequireErrorRun(t, ctx, "bundle", "init", "./testdata/init/field-does-not-exist", "--output-dir", tmpDir) assert.EqualError(t, err, "failed to compute file content for bar.tmpl. variable \"does_not_exist\" not defined") diff --git a/integration/bundle/spark_jar_test.go b/integration/bundle/spark_jar_test.go index 0829540c16..045af404fa 100644 --- a/integration/bundle/spark_jar_test.go +++ b/integration/bundle/spark_jar_test.go @@ -26,7 +26,7 @@ func runSparkJarTests(t *testing.T, testCases []sparkJarTestCase, testRunner fun testCanRun := make(map[string]bool) atLeastOneCanRun := false for _, tc := range testCases { - if testutil.HasJDK(t, context.Background(), tc.requiredJavaVersion) { + if testutil.HasJDK(t, t.Context(), tc.requiredJavaVersion) { testCanRun[tc.name] = true atLeastOneCanRun = true continue @@ -70,7 +70,7 @@ func runSparkJarTestCommon(t *testing.T, ctx context.Context, sparkVersion, arti deployBundle(t, ctx, bundleRoot) t.Cleanup(func() { - destroyBundle(t, ctx, bundleRoot) + destroyBundle(t, context.WithoutCancel(ctx), bundleRoot) }) if testing.Short() { diff --git a/integration/cmd/alerts/alerts_test.go b/integration/cmd/alerts/alerts_test.go index ca17198138..dc40fb95dd 100644 --- a/integration/cmd/alerts/alerts_test.go +++ b/integration/cmd/alerts/alerts_test.go @@ -1,7 +1,6 @@ package alerts_test import ( - "context" "testing" "github.com/databricks/cli/internal/testcli" @@ -9,7 +8,7 @@ import ( ) func TestAlertsCreateErrWhenNoArguments(t *testing.T) { - ctx := context.Background() + ctx := t.Context() _, _, err := testcli.RequireErrorRun(t, ctx, "alerts-legacy", "create") assert.Equal(t, "please provide command input in JSON format by specifying the --json flag", err.Error()) } diff --git a/integration/cmd/api/api_test.go b/integration/cmd/api/api_test.go index 4cb9b1737c..aa87e31e10 100644 --- a/integration/cmd/api/api_test.go +++ b/integration/cmd/api/api_test.go @@ -1,7 +1,6 @@ package api_test import ( - "context" "encoding/json" "fmt" "path" @@ -17,7 +16,7 @@ import ( ) func TestApiGet(t *testing.T) { - ctx := context.Background() + ctx := t.Context() stdout, _ := testcli.RequireSuccessfulRun(t, ctx, "api", "get", "/api/2.0/preview/scim/v2/Me") @@ -32,7 +31,7 @@ func TestApiGet(t *testing.T) { } func TestApiPost(t *testing.T) { - ctx := context.Background() + ctx := t.Context() if testutil.GetCloud(t) == testutil.GCP { t.Skip("DBFS REST API is disabled on gcp") diff --git a/integration/cmd/auth/describe_test.go b/integration/cmd/auth/describe_test.go index 3d0a9b17d6..1ea843b6b9 100644 --- a/integration/cmd/auth/describe_test.go +++ b/integration/cmd/auth/describe_test.go @@ -1,7 +1,6 @@ package auth_test import ( - "context" "path/filepath" "regexp" "strings" @@ -17,7 +16,7 @@ import ( ) func TestAuthDescribeSuccess(t *testing.T) { - ctx := context.Background() + ctx := t.Context() stdout, _ := testcli.RequireSuccessfulRun(t, ctx, "auth", "describe") outStr := stdout.String() @@ -29,7 +28,7 @@ func TestAuthDescribeSuccess(t *testing.T) { hostWithoutPrefix := strings.TrimPrefix(w.Config.Host, "https://") require.Regexp(t, "Host: (?:https://)?"+regexp.QuoteMeta(hostWithoutPrefix), outStr) - me, err := w.CurrentUser.Me(context.Background()) + me, err := w.CurrentUser.Me(t.Context()) require.NoError(t, err) require.Contains(t, outStr, "User: "+me.UserName) require.Contains(t, outStr, "Authenticated with: "+w.Config.AuthType) @@ -47,12 +46,12 @@ func TestAuthDescribeFailure(t *testing.T) { ConfigFile: filepath.Join(home, "customcfg"), Profile: "profile1", } - err := databrickscfg.SaveToProfile(context.Background(), cfg) + err := databrickscfg.SaveToProfile(t.Context(), cfg) require.NoError(t, err) t.Setenv("DATABRICKS_CONFIG_FILE", filepath.Join(home, "customcfg")) // run the command: - ctx := context.Background() + ctx := t.Context() stdout, _ := testcli.RequireSuccessfulRun(t, ctx, "auth", "describe", "--profile", "nonexistent") outStr := stdout.String() diff --git a/integration/cmd/clusters/clusters_test.go b/integration/cmd/clusters/clusters_test.go index 4e20a05581..33a2aa0b3e 100644 --- a/integration/cmd/clusters/clusters_test.go +++ b/integration/cmd/clusters/clusters_test.go @@ -1,7 +1,6 @@ package clusters_test import ( - "context" "fmt" "regexp" "testing" @@ -15,7 +14,7 @@ import ( ) func TestClustersList(t *testing.T) { - ctx := context.Background() + ctx := t.Context() stdout, stderr := testcli.RequireSuccessfulRun(t, ctx, "clusters", "list") outStr := stdout.String() assert.Contains(t, outStr, "ID") @@ -29,7 +28,7 @@ func TestClustersList(t *testing.T) { } func TestClustersGet(t *testing.T) { - ctx := context.Background() + ctx := t.Context() clusterId := findValidClusterID(t) stdout, stderr := testcli.RequireSuccessfulRun(t, ctx, "clusters", "get", clusterId) outStr := stdout.String() @@ -38,7 +37,7 @@ func TestClustersGet(t *testing.T) { } func TestClusterCreateErrorWhenNoArguments(t *testing.T) { - ctx := context.Background() + ctx := t.Context() _, _, err := testcli.RequireErrorRun(t, ctx, "clusters", "create") assert.Contains(t, err.Error(), "accepts 1 arg(s), received 0") } diff --git a/integration/cmd/fs/cat_test.go b/integration/cmd/fs/cat_test.go index 6f5ea4ded3..49f48974cb 100644 --- a/integration/cmd/fs/cat_test.go +++ b/integration/cmd/fs/cat_test.go @@ -1,7 +1,6 @@ package fs_test import ( - "context" "io/fs" "path" "strings" @@ -21,10 +20,10 @@ func TestFsCat(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() f, tmpDir := testCase.setupFiler(t) - err := f.Write(context.Background(), "hello.txt", strings.NewReader("abcd"), filer.CreateParentDirectories) + err := f.Write(t.Context(), "hello.txt", strings.NewReader("abcd"), filer.CreateParentDirectories) require.NoError(t, err) stdout, stderr := testcli.RequireSuccessfulRun(t, ctx, "fs", "cat", path.Join(tmpDir, "hello.txt")) @@ -41,10 +40,10 @@ func TestFsCatOnADir(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() f, tmpDir := testCase.setupFiler(t) - err := f.Mkdir(context.Background(), "dir1") + err := f.Mkdir(t.Context(), "dir1") require.NoError(t, err) _, _, err = testcli.RequireErrorRun(t, ctx, "fs", "cat", path.Join(tmpDir, "dir1")) @@ -60,7 +59,7 @@ func TestFsCatOnNonExistentFile(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() _, tmpDir := testCase.setupFiler(t) _, _, err := testcli.RequireErrorRun(t, ctx, "fs", "cat", path.Join(tmpDir, "non-existent-file")) @@ -70,7 +69,7 @@ func TestFsCatOnNonExistentFile(t *testing.T) { } func TestFsCatForDbfsInvalidScheme(t *testing.T) { - ctx := context.Background() + ctx := t.Context() _, _, err := testcli.RequireErrorRun(t, ctx, "fs", "cat", "dab:/non-existent-file") assert.ErrorContains(t, err, "invalid scheme: dab") } diff --git a/integration/cmd/fs/completion_test.go b/integration/cmd/fs/completion_test.go index b13bf9d600..80e2ce17a7 100644 --- a/integration/cmd/fs/completion_test.go +++ b/integration/cmd/fs/completion_test.go @@ -1,7 +1,6 @@ package fs_test import ( - "context" "strings" "testing" @@ -13,12 +12,12 @@ import ( ) func setupCompletionFile(t *testing.T, f filer.Filer) { - err := f.Write(context.Background(), "dir1/file1.txt", strings.NewReader("abc"), filer.CreateParentDirectories) + err := f.Write(t.Context(), "dir1/file1.txt", strings.NewReader("abc"), filer.CreateParentDirectories) require.NoError(t, err) } func TestFsCompletion(t *testing.T) { - ctx := context.Background() + ctx := t.Context() f, tmpDir := setupDbfsFiler(t) setupCompletionFile(t, f) diff --git a/integration/cmd/fs/cp_test.go b/integration/cmd/fs/cp_test.go index 7e4784c100..0b22992ea4 100644 --- a/integration/cmd/fs/cp_test.go +++ b/integration/cmd/fs/cp_test.go @@ -131,7 +131,7 @@ func TestFsCpDir(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() sourceFiler, sourceDir := testCase.setupSource(t) targetFiler, targetDir := testCase.setupTarget(t) setupSourceDir(t, ctx, sourceFiler) @@ -150,7 +150,7 @@ func TestFsCpFileToFile(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() sourceFiler, sourceDir := testCase.setupSource(t) targetFiler, targetDir := testCase.setupTarget(t) setupSourceFile(t, ctx, sourceFiler) @@ -168,7 +168,7 @@ func TestFsCpFileToDir(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() sourceFiler, sourceDir := testCase.setupSource(t) targetFiler, targetDir := testCase.setupTarget(t) setupSourceFile(t, ctx, sourceFiler) @@ -185,7 +185,7 @@ func TestFsCpFileToDirForWindowsPaths(t *testing.T) { t.Skip("Skipping test on non-windows OS") } - ctx := context.Background() + ctx := t.Context() sourceFiler, sourceDir := setupLocalFiler(t) targetFiler, targetDir := setupDbfsFiler(t) setupSourceFile(t, ctx, sourceFiler) @@ -203,7 +203,7 @@ func TestFsCpDirToDirFileNotOverwritten(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() sourceFiler, sourceDir := testCase.setupSource(t) targetFiler, targetDir := testCase.setupTarget(t) setupSourceDir(t, ctx, sourceFiler) @@ -227,7 +227,7 @@ func TestFsCpFileToDirFileNotOverwritten(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() sourceFiler, sourceDir := testCase.setupSource(t) targetFiler, targetDir := testCase.setupTarget(t) setupSourceDir(t, ctx, sourceFiler) @@ -249,7 +249,7 @@ func TestFsCpFileToFileFileNotOverwritten(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() sourceFiler, sourceDir := testCase.setupSource(t) targetFiler, targetDir := testCase.setupTarget(t) setupSourceDir(t, ctx, sourceFiler) @@ -271,7 +271,7 @@ func TestFsCpDirToDirWithOverwriteFlag(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() sourceFiler, sourceDir := testCase.setupSource(t) targetFiler, targetDir := testCase.setupTarget(t) setupSourceDir(t, ctx, sourceFiler) @@ -293,7 +293,7 @@ func TestFsCpFileToFileWithOverwriteFlag(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() sourceFiler, sourceDir := testCase.setupSource(t) targetFiler, targetDir := testCase.setupTarget(t) setupSourceDir(t, ctx, sourceFiler) @@ -315,7 +315,7 @@ func TestFsCpFileToDirWithOverwriteFlag(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() sourceFiler, sourceDir := testCase.setupSource(t) targetFiler, targetDir := testCase.setupTarget(t) setupSourceDir(t, ctx, sourceFiler) @@ -337,7 +337,7 @@ func TestFsCpErrorsWhenSourceIsDirWithoutRecursiveFlag(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() _, tmpDir := testCase.setupFiler(t) _, _, err := testcli.RequireErrorRun(t, ctx, "fs", "cp", path.Join(tmpDir), path.Join(tmpDir, "foobar")) @@ -348,7 +348,7 @@ func TestFsCpErrorsWhenSourceIsDirWithoutRecursiveFlag(t *testing.T) { } func TestFsCpErrorsOnInvalidScheme(t *testing.T) { - ctx := context.Background() + ctx := t.Context() _, _, err := testcli.RequireErrorRun(t, ctx, "fs", "cp", "dbfs:/a", "https:/b") assert.Equal(t, "invalid scheme: https", err.Error()) } @@ -360,7 +360,7 @@ func TestFsCpSourceIsDirectoryButTargetIsFile(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() sourceFiler, sourceDir := testCase.setupSource(t) targetFiler, targetDir := testCase.setupTarget(t) setupSourceDir(t, ctx, sourceFiler) @@ -382,7 +382,7 @@ func TestFsCpFileToNonExistentDir(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() sourceFiler, sourceDir := testCase.setupSource(t) targetFiler, targetDir := testCase.setupTarget(t) setupSourceFile(t, ctx, sourceFiler) @@ -411,7 +411,7 @@ func TestFsCpFileToNonExistentDirWindowsPaths(t *testing.T) { t.Skip("Skipping test on non-windows OS") } - ctx := context.Background() + ctx := t.Context() sourceFiler, sourceDir := setupLocalFiler(t) targetFiler, targetDir := setupLocalFiler(t) setupSourceFile(t, ctx, sourceFiler) diff --git a/integration/cmd/fs/ls_test.go b/integration/cmd/fs/ls_test.go index d4d7cedef7..cbb8ed8b3a 100644 --- a/integration/cmd/fs/ls_test.go +++ b/integration/cmd/fs/ls_test.go @@ -1,7 +1,6 @@ package fs_test import ( - "context" "encoding/json" "io/fs" "path" @@ -33,9 +32,9 @@ var fsTests = []fsTest{ } func setupLsFiles(t *testing.T, f filer.Filer) { - err := f.Write(context.Background(), "a/hello.txt", strings.NewReader("abc"), filer.CreateParentDirectories) + err := f.Write(t.Context(), "a/hello.txt", strings.NewReader("abc"), filer.CreateParentDirectories) require.NoError(t, err) - err = f.Write(context.Background(), "bye.txt", strings.NewReader("def")) + err = f.Write(t.Context(), "bye.txt", strings.NewReader("def")) require.NoError(t, err) } @@ -46,7 +45,7 @@ func TestFsLs(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() f, tmpDir := testCase.setupFiler(t) setupLsFiles(t, f) @@ -78,7 +77,7 @@ func TestFsLsWithAbsolutePaths(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() f, tmpDir := testCase.setupFiler(t) setupLsFiles(t, f) @@ -110,7 +109,7 @@ func TestFsLsOnFile(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() f, tmpDir := testCase.setupFiler(t) setupLsFiles(t, f) @@ -128,7 +127,7 @@ func TestFsLsOnEmptyDir(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() _, tmpDir := testCase.setupFiler(t) stdout, stderr := testcli.RequireSuccessfulRun(t, ctx, "fs", "ls", tmpDir, "--output=json") @@ -150,7 +149,7 @@ func TestFsLsForNonexistingDir(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() _, tmpDir := testCase.setupFiler(t) _, _, err := testcli.RequireErrorRun(t, ctx, "fs", "ls", path.Join(tmpDir, "nonexistent"), "--output=json") @@ -163,7 +162,7 @@ func TestFsLsForNonexistingDir(t *testing.T) { func TestFsLsWithoutScheme(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() _, _, err := testcli.RequireErrorRun(t, ctx, "fs", "ls", "/path-without-a-dbfs-scheme", "--output=json") assert.ErrorIs(t, err, fs.ErrNotExist) } diff --git a/integration/cmd/fs/mkdir_test.go b/integration/cmd/fs/mkdir_test.go index 9b78748570..2c1f7d2949 100644 --- a/integration/cmd/fs/mkdir_test.go +++ b/integration/cmd/fs/mkdir_test.go @@ -1,7 +1,6 @@ package fs_test import ( - "context" "io/fs" "path" "regexp" @@ -20,7 +19,7 @@ func TestFsMkdir(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() f, tmpDir := testCase.setupFiler(t) // create directory "a" @@ -29,7 +28,7 @@ func TestFsMkdir(t *testing.T) { assert.Equal(t, "", stdout.String()) // assert directory "a" is created - info, err := f.Stat(context.Background(), "a") + info, err := f.Stat(t.Context(), "a") require.NoError(t, err) assert.Equal(t, "a", info.Name()) assert.True(t, info.IsDir()) @@ -44,7 +43,7 @@ func TestFsMkdirCreatesIntermediateDirectories(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() f, tmpDir := testCase.setupFiler(t) // create directory "a/b/c" @@ -53,19 +52,19 @@ func TestFsMkdirCreatesIntermediateDirectories(t *testing.T) { assert.Equal(t, "", stdout.String()) // assert directory "a" is created - infoA, err := f.Stat(context.Background(), "a") + infoA, err := f.Stat(t.Context(), "a") require.NoError(t, err) assert.Equal(t, "a", infoA.Name()) assert.True(t, infoA.IsDir()) // assert directory "b" is created - infoB, err := f.Stat(context.Background(), "a/b") + infoB, err := f.Stat(t.Context(), "a/b") require.NoError(t, err) assert.Equal(t, "b", infoB.Name()) assert.True(t, infoB.IsDir()) // assert directory "c" is created - infoC, err := f.Stat(context.Background(), "a/b/c") + infoC, err := f.Stat(t.Context(), "a/b/c") require.NoError(t, err) assert.Equal(t, "c", infoC.Name()) assert.True(t, infoC.IsDir()) @@ -80,11 +79,11 @@ func TestFsMkdirWhenDirectoryAlreadyExists(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() f, tmpDir := testCase.setupFiler(t) // create directory "a" - err := f.Mkdir(context.Background(), "a") + err := f.Mkdir(t.Context(), "a") require.NoError(t, err) // assert run is successful without any errors @@ -101,11 +100,11 @@ func TestFsMkdirWhenFileExistsAtPath(t *testing.T) { t.Run("dbfs", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() f, tmpDir := setupDbfsFiler(t) // create file "hello" - err := f.Write(context.Background(), "hello", strings.NewReader("abc")) + err := f.Write(t.Context(), "hello", strings.NewReader("abc")) require.NoError(t, err) // assert mkdir fails @@ -119,11 +118,11 @@ func TestFsMkdirWhenFileExistsAtPath(t *testing.T) { t.Run("uc-volumes", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() f, tmpDir := setupUcVolumesFiler(t) // create file "hello" - err := f.Write(context.Background(), "hello", strings.NewReader("abc")) + err := f.Write(t.Context(), "hello", strings.NewReader("abc")) require.NoError(t, err) // assert mkdir fails diff --git a/integration/cmd/fs/rm_test.go b/integration/cmd/fs/rm_test.go index 736172f94b..ff64196b9c 100644 --- a/integration/cmd/fs/rm_test.go +++ b/integration/cmd/fs/rm_test.go @@ -1,7 +1,6 @@ package fs_test import ( - "context" "io/fs" "path" "strings" @@ -21,13 +20,13 @@ func TestFsRmFile(t *testing.T) { t.Parallel() // Create a file - ctx := context.Background() + ctx := t.Context() f, tmpDir := testCase.setupFiler(t) - err := f.Write(context.Background(), "hello.txt", strings.NewReader("abcd"), filer.CreateParentDirectories) + err := f.Write(t.Context(), "hello.txt", strings.NewReader("abcd"), filer.CreateParentDirectories) require.NoError(t, err) // Check file was created - _, err = f.Stat(context.Background(), "hello.txt") + _, err = f.Stat(t.Context(), "hello.txt") assert.NoError(t, err) // Run rm command @@ -36,7 +35,7 @@ func TestFsRmFile(t *testing.T) { assert.Equal(t, "", stdout.String()) // Assert file was deleted - _, err = f.Stat(context.Background(), "hello.txt") + _, err = f.Stat(t.Context(), "hello.txt") assert.ErrorIs(t, err, fs.ErrNotExist) }) } @@ -50,13 +49,13 @@ func TestFsRmEmptyDir(t *testing.T) { t.Parallel() // Create a directory - ctx := context.Background() + ctx := t.Context() f, tmpDir := testCase.setupFiler(t) - err := f.Mkdir(context.Background(), "a") + err := f.Mkdir(t.Context(), "a") require.NoError(t, err) // Check directory was created - _, err = f.Stat(context.Background(), "a") + _, err = f.Stat(t.Context(), "a") assert.NoError(t, err) // Run rm command @@ -65,7 +64,7 @@ func TestFsRmEmptyDir(t *testing.T) { assert.Equal(t, "", stdout.String()) // Assert directory was deleted - _, err = f.Stat(context.Background(), "a") + _, err = f.Stat(t.Context(), "a") assert.ErrorIs(t, err, fs.ErrNotExist) }) } @@ -79,17 +78,17 @@ func TestFsRmNonEmptyDirectory(t *testing.T) { t.Parallel() // Create a directory - ctx := context.Background() + ctx := t.Context() f, tmpDir := testCase.setupFiler(t) - err := f.Mkdir(context.Background(), "a") + err := f.Mkdir(t.Context(), "a") require.NoError(t, err) // Create a file in the directory - err = f.Write(context.Background(), "a/hello.txt", strings.NewReader("abcd"), filer.CreateParentDirectories) + err = f.Write(t.Context(), "a/hello.txt", strings.NewReader("abcd"), filer.CreateParentDirectories) require.NoError(t, err) // Check file was created - _, err = f.Stat(context.Background(), "a/hello.txt") + _, err = f.Stat(t.Context(), "a/hello.txt") assert.NoError(t, err) // Run rm command @@ -106,7 +105,7 @@ func TestFsRmForNonExistentFile(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() _, tmpDir := testCase.setupFiler(t) // Expect error if file does not exist @@ -123,19 +122,19 @@ func TestFsRmDirRecursively(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() f, tmpDir := testCase.setupFiler(t) // Create a directory - err := f.Mkdir(context.Background(), "a") + err := f.Mkdir(t.Context(), "a") require.NoError(t, err) // Create a file in the directory - err = f.Write(context.Background(), "a/hello.txt", strings.NewReader("abcd"), filer.CreateParentDirectories) + err = f.Write(t.Context(), "a/hello.txt", strings.NewReader("abcd"), filer.CreateParentDirectories) require.NoError(t, err) // Check file was created - _, err = f.Stat(context.Background(), "a/hello.txt") + _, err = f.Stat(t.Context(), "a/hello.txt") assert.NoError(t, err) // Run rm command @@ -144,7 +143,7 @@ func TestFsRmDirRecursively(t *testing.T) { assert.Equal(t, "", stdout.String()) // Assert directory was deleted - _, err = f.Stat(context.Background(), "a") + _, err = f.Stat(t.Context(), "a") assert.ErrorIs(t, err, fs.ErrNotExist) }) } diff --git a/integration/cmd/jobs/jobs_test.go b/integration/cmd/jobs/jobs_test.go index 7ebc135a32..f168cd5315 100644 --- a/integration/cmd/jobs/jobs_test.go +++ b/integration/cmd/jobs/jobs_test.go @@ -1,7 +1,6 @@ package jobs_test import ( - "context" "encoding/json" "strconv" "testing" @@ -14,7 +13,7 @@ import ( func TestCreateJob(t *testing.T) { testutil.Require(t, testutil.Azure) - ctx := context.Background() + ctx := t.Context() stdout, stderr := testcli.RequireSuccessfulRun(t, ctx, "jobs", "create", "--json", "@testdata/create_job_without_workers.json", "--log-level=debug") assert.Empty(t, stderr.String()) var output map[string]int diff --git a/integration/cmd/secrets/secrets_test.go b/integration/cmd/secrets/secrets_test.go index 52f0274215..31ee71d90f 100644 --- a/integration/cmd/secrets/secrets_test.go +++ b/integration/cmd/secrets/secrets_test.go @@ -16,7 +16,7 @@ import ( ) func TestSecretsCreateScopeErrWhenNoArguments(t *testing.T) { - ctx := context.Background() + ctx := t.Context() _, _, err := testcli.RequireErrorRun(t, ctx, "secrets", "create-scope") assert.Contains(t, err.Error(), "accepts 1 arg(s), received 0") } @@ -30,7 +30,7 @@ func temporarySecretScope(ctx context.Context, t *acc.WorkspaceT) string { // Delete the scope after the test. t.Cleanup(func() { - err := t.W.Secrets.DeleteScopeByScope(ctx, scope) + err := t.W.Secrets.DeleteScopeByScope(context.WithoutCancel(ctx), scope) require.NoError(t, err) }) diff --git a/integration/cmd/sync/sync_test.go b/integration/cmd/sync/sync_test.go index b5b06d32f2..4c771258d8 100644 --- a/integration/cmd/sync/sync_test.go +++ b/integration/cmd/sync/sync_test.go @@ -48,7 +48,7 @@ func setupRepo(t *testing.T, wsc *databricks.WorkspaceClient, ctx context.Contex require.NoError(t, err) t.Cleanup(func() { - err := wsc.Repos.DeleteByRepoId(ctx, repoInfo.Id) + err := wsc.Repos.DeleteByRepoId(context.WithoutCancel(ctx), repoInfo.Id) assert.NoError(t, err) }) @@ -104,7 +104,7 @@ func setupSyncTest(t *testing.T, args ...string) (context.Context, *syncTest) { } func (a *syncTest) waitForCompletionMarker() { - ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + ctx, cancel := context.WithTimeout(a.t.Context(), 60*time.Second) defer cancel() for { diff --git a/integration/cmd/unknown_command_test.go b/integration/cmd/unknown_command_test.go index b15f7c9842..8b9ff524b5 100644 --- a/integration/cmd/unknown_command_test.go +++ b/integration/cmd/unknown_command_test.go @@ -1,7 +1,6 @@ package cmd_test import ( - "context" "testing" "github.com/databricks/cli/internal/testcli" @@ -9,7 +8,7 @@ import ( ) func TestUnknownCommand(t *testing.T) { - ctx := context.Background() + ctx := t.Context() stdout, stderr, err := testcli.RequireErrorRun(t, ctx, "unknown-command") assert.Error(t, err, "unknown command", `unknown command "unknown-command" for "databricks"`) diff --git a/integration/cmd/version/version_test.go b/integration/cmd/version/version_test.go index b12974d693..d60f6c920e 100644 --- a/integration/cmd/version/version_test.go +++ b/integration/cmd/version/version_test.go @@ -1,7 +1,6 @@ package version_test import ( - "context" "encoding/json" "fmt" "testing" @@ -14,28 +13,28 @@ import ( var expectedVersion = fmt.Sprintf("Databricks CLI v%s\n", build.GetInfo().Version) func TestVersionFlagShort(t *testing.T) { - ctx := context.Background() + ctx := t.Context() stdout, stderr := testcli.RequireSuccessfulRun(t, ctx, "-v") assert.Equal(t, expectedVersion, stdout.String()) assert.Equal(t, "", stderr.String()) } func TestVersionFlagLong(t *testing.T) { - ctx := context.Background() + ctx := t.Context() stdout, stderr := testcli.RequireSuccessfulRun(t, ctx, "--version") assert.Equal(t, expectedVersion, stdout.String()) assert.Equal(t, "", stderr.String()) } func TestVersionCommand(t *testing.T) { - ctx := context.Background() + ctx := t.Context() stdout, stderr := testcli.RequireSuccessfulRun(t, ctx, "version") assert.Equal(t, expectedVersion, stdout.String()) assert.Equal(t, "", stderr.String()) } func TestVersionCommandWithJSONOutput(t *testing.T) { - ctx := context.Background() + ctx := t.Context() stdout, stderr := testcli.RequireSuccessfulRun(t, ctx, "version", "--output", "json") assert.NotEmpty(t, stdout.String()) assert.Equal(t, "", stderr.String()) diff --git a/integration/cmd/workspace/workspace_test.go b/integration/cmd/workspace/workspace_test.go index b59ffd5a36..3079665cc3 100644 --- a/integration/cmd/workspace/workspace_test.go +++ b/integration/cmd/workspace/workspace_test.go @@ -20,7 +20,7 @@ import ( ) func TestWorkspaceList(t *testing.T) { - ctx := context.Background() + ctx := t.Context() stdout, stderr := testcli.RequireSuccessfulRun(t, ctx, "workspace", "list", "/") outStr := stdout.String() assert.Contains(t, outStr, "ID") @@ -31,13 +31,13 @@ func TestWorkspaceList(t *testing.T) { } func TestWorkpaceListErrorWhenNoArguments(t *testing.T) { - ctx := context.Background() + ctx := t.Context() _, _, err := testcli.RequireErrorRun(t, ctx, "workspace", "list") assert.Contains(t, err.Error(), "accepts 1 arg(s), received 0") } func TestWorkpaceGetStatusErrorWhenNoArguments(t *testing.T) { - ctx := context.Background() + ctx := t.Context() _, _, err := testcli.RequireErrorRun(t, ctx, "workspace", "get-status") assert.Contains(t, err.Error(), "accepts 1 arg(s), received 0") } diff --git a/integration/internal/acc/fixtures.go b/integration/internal/acc/fixtures.go index 2367d228fc..03aada077e 100644 --- a/integration/internal/acc/fixtures.go +++ b/integration/internal/acc/fixtures.go @@ -1,6 +1,7 @@ package acc import ( + "context" "fmt" "github.com/databricks/cli/internal/testutil" @@ -27,7 +28,7 @@ func TemporaryWorkspaceDir(t *WorkspaceT, name ...string) string { // Remove test directory on test completion. t.Cleanup(func() { t.Logf("Removing workspace directory %s", basePath) - err := t.W.Workspace.Delete(ctx, workspace.Delete{ + err := t.W.Workspace.Delete(context.WithoutCancel(ctx), workspace.Delete{ Path: basePath, Recursive: true, }) @@ -53,7 +54,7 @@ func TemporaryDbfsDir(t *WorkspaceT, name ...string) string { t.Cleanup(func() { t.Logf("Removing DBFS directory %s", path) - err := t.W.Dbfs.Delete(ctx, files.Delete{ + err := t.W.Dbfs.Delete(context.WithoutCancel(ctx), files.Delete{ Path: path, Recursive: true, }) @@ -84,7 +85,7 @@ func TemporaryRepo(t *WorkspaceT, url string) string { t.Cleanup(func() { t.Logf("Removing repo: %s", path) - err := t.W.Repos.Delete(ctx, workspace.DeleteRepoRequest{ + err := t.W.Repos.Delete(context.WithoutCancel(ctx), workspace.DeleteRepoRequest{ RepoId: resp.Id, }) if err == nil || apierr.IsMissing(err) { @@ -108,7 +109,7 @@ func TemporaryVolume(t *WorkspaceT) string { }) require.NoError(t, err) t.Cleanup(func() { - err := w.Schemas.Delete(ctx, catalog.DeleteSchemaRequest{ + err := w.Schemas.Delete(context.WithoutCancel(ctx), catalog.DeleteSchemaRequest{ FullName: schema.FullName, }) require.NoError(t, err) @@ -123,7 +124,7 @@ func TemporaryVolume(t *WorkspaceT) string { }) require.NoError(t, err) t.Cleanup(func() { - err := w.Volumes.Delete(ctx, catalog.DeleteVolumeRequest{ + err := w.Volumes.Delete(context.WithoutCancel(ctx), catalog.DeleteVolumeRequest{ Name: volume.FullName, }) require.NoError(t, err) diff --git a/integration/internal/acc/workspace.go b/integration/internal/acc/workspace.go index 7a5becf006..4c58fb3530 100644 --- a/integration/internal/acc/workspace.go +++ b/integration/internal/acc/workspace.go @@ -34,7 +34,7 @@ func WorkspaceTest(t testutil.TestingT) (context.Context, *WorkspaceT) { W: w, - ctx: context.Background(), + ctx: t.Context(), } return wt.ctx, wt @@ -62,7 +62,7 @@ func UcWorkspaceTest(t testutil.TestingT) (context.Context, *WorkspaceT) { W: w, - ctx: context.Background(), + ctx: t.Context(), } return wt.ctx, wt @@ -86,7 +86,7 @@ func (t *WorkspaceT) RunPython(code string) (string, error) { require.NoError(t, err, "Unexpected error from CommandExecution.Start(clusterID=%v)", t.TestClusterID()) t.Cleanup(func() { - err := t.exec.Destroy(t.ctx) + err := t.exec.Destroy(context.WithoutCancel(t.ctx)) require.NoError(t, err) }) } diff --git a/integration/libs/filer/filer_test.go b/integration/libs/filer/filer_test.go index 2222e4b56c..38cdf3c406 100644 --- a/integration/libs/filer/filer_test.go +++ b/integration/libs/filer/filer_test.go @@ -131,7 +131,7 @@ func TestFilerRecursiveDelete(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() f, _ := testCase.f(t) - ctx := context.Background() + ctx := t.Context() // Common tests we run across all filers to ensure consistent behavior. commonFilerRecursiveDeleteTest(t, ctx, f) @@ -233,7 +233,7 @@ func TestFilerReadWrite(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() f, _ := testCase.f(t) - ctx := context.Background() + ctx := t.Context() // Common tests we run across all filers to ensure consistent behavior. commonFilerReadWriteTests(t, ctx, f) @@ -339,7 +339,7 @@ func TestFilerReadDir(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() f, _ := testCase.f(t) - ctx := context.Background() + ctx := t.Context() commonFilerReadDirTest(t, ctx, f) }) @@ -349,7 +349,7 @@ func TestFilerReadDir(t *testing.T) { func TestFilerWorkspaceNotebook(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() var err error tcases := []struct { @@ -488,7 +488,7 @@ func TestFilerWorkspaceFilesExtensionsReadDir(t *testing.T) { basenames[basename] = struct{}{} } - ctx := context.Background() + ctx := t.Context() wf, _ := setupWsfsExtensionsFiler(t) for _, f := range files { @@ -548,7 +548,7 @@ func setupFilerWithExtensionsTest(t *testing.T) filer.Filer { {"scala-notebook.scala", "// Databricks notebook source\nprintln('first upload')"}, } - ctx := context.Background() + ctx := t.Context() wf, _ := setupWsfsExtensionsFiler(t) for _, f := range files { @@ -562,7 +562,7 @@ func setupFilerWithExtensionsTest(t *testing.T) filer.Filer { func TestFilerWorkspaceFilesExtensionsRead(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() wf := setupFilerWithExtensionsTest(t) // Read contents of test fixtures as a sanity check. @@ -599,7 +599,7 @@ func TestFilerWorkspaceFilesExtensionsRead(t *testing.T) { func TestFilerWorkspaceFilesExtensionsDelete(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() wf := setupFilerWithExtensionsTest(t) for _, fileName := range []string{ @@ -648,7 +648,7 @@ func TestFilerWorkspaceFilesExtensionsDelete(t *testing.T) { func TestFilerWorkspaceFilesExtensionsStat(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() wf := setupFilerWithExtensionsTest(t) for _, fileName := range []string{ @@ -695,7 +695,7 @@ func TestFilerWorkspaceFilesExtensionsStat(t *testing.T) { func TestWorkspaceFilesExtensionsDirectoriesAreNotNotebooks(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() wf, _ := setupWsfsExtensionsFiler(t) // Create a directory with an extension @@ -710,7 +710,7 @@ func TestWorkspaceFilesExtensionsDirectoriesAreNotNotebooks(t *testing.T) { func TestWorkspaceFilesExtensionsNotebooksAreNotReadAsFiles(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() wf, _ := setupWsfsExtensionsFiler(t) // Create a notebook @@ -729,7 +729,7 @@ func TestWorkspaceFilesExtensionsNotebooksAreNotReadAsFiles(t *testing.T) { func TestWorkspaceFilesExtensionsNotebooksAreNotStatAsFiles(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() wf, _ := setupWsfsExtensionsFiler(t) // Create a notebook @@ -748,7 +748,7 @@ func TestWorkspaceFilesExtensionsNotebooksAreNotStatAsFiles(t *testing.T) { func TestWorkspaceFilesExtensionsNotebooksAreNotDeletedAsFiles(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() wf, _ := setupWsfsExtensionsFiler(t) // Create a notebook @@ -803,7 +803,7 @@ func TestWorkspaceFilesExtensions_ExportFormatIsPreserved(t *testing.T) { t.Run("source_"+tc.language, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() wf, _ := setupWsfsExtensionsFiler(t) err := wf.Write(ctx, tc.sourceName, strings.NewReader(tc.sourceContent)) @@ -858,7 +858,7 @@ func TestWorkspaceFilesExtensions_ExportFormatIsPreserved(t *testing.T) { t.Run("jupyter_"+tc.language, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() wf, _ := setupWsfsExtensionsFiler(t) err := wf.Write(ctx, tc.jupyterName, strings.NewReader(tc.jupyterContent)) diff --git a/integration/libs/git/git_clone_test.go b/integration/libs/git/git_clone_test.go index cbc2d091dd..216dec270e 100644 --- a/integration/libs/git/git_clone_test.go +++ b/integration/libs/git/git_clone_test.go @@ -1,7 +1,6 @@ package git_test import ( - "context" "os" "path/filepath" "testing" @@ -12,7 +11,7 @@ import ( func TestGitClone(t *testing.T) { tmpDir := t.TempDir() - ctx := context.Background() + ctx := t.Context() var err error err = git.Clone(ctx, "https://github.com/databricks/databricks-empty-ide-project.git", "", tmpDir) @@ -32,7 +31,7 @@ func TestGitClone(t *testing.T) { func TestGitCloneOnNonDefaultBranch(t *testing.T) { tmpDir := t.TempDir() - ctx := context.Background() + ctx := t.Context() var err error err = git.Clone(ctx, "https://github.com/databricks/notebook-best-practices", "dais-2022", tmpDir) @@ -52,7 +51,7 @@ func TestGitCloneOnNonDefaultBranch(t *testing.T) { func TestGitCloneErrorsWhenRepositoryDoesNotExist(t *testing.T) { tmpDir := t.TempDir() - err := git.Clone(context.Background(), "https://github.com/monalisa/doesnot-exist.git", "", tmpDir) + err := git.Clone(t.Context(), "https://github.com/monalisa/doesnot-exist.git", "", tmpDir) // Expect the error to originate from shelling out to `git clone` assert.ErrorContains(t, err, "git clone failed:") } diff --git a/integration/libs/tags/tags_test.go b/integration/libs/tags/tags_test.go index 8a54a966bf..f5b353fc5f 100644 --- a/integration/libs/tags/tags_test.go +++ b/integration/libs/tags/tags_test.go @@ -1,6 +1,7 @@ package tags_test import ( + "context" "strings" "testing" @@ -33,7 +34,7 @@ func testTags(t *testing.T, tags map[string]string) error { if resp != nil { t.Cleanup(func() { - _ = wt.W.Jobs.DeleteByJobId(ctx, resp.JobId) + _ = wt.W.Jobs.DeleteByJobId(context.WithoutCancel(ctx), resp.JobId) // Cannot enable errchecking there, tests fail with: // Error: Received unexpected error: // Job 0 does not exist. diff --git a/integration/python/python_tasks_test.go b/integration/python/python_tasks_test.go index 6164546abf..8862fd5c22 100644 --- a/integration/python/python_tasks_test.go +++ b/integration/python/python_tasks_test.go @@ -2,7 +2,6 @@ package python_test import ( "bytes" - "context" "encoding/base64" "encoding/json" "os" @@ -139,7 +138,7 @@ func runPythonTasks(t *testing.T, tw *testFiles, opts testOpts) { tasks = append(tasks, GenerateWheelTasks(tw.wheelPath, versions, nodeTypeId)...) } - ctx := context.Background() + ctx := t.Context() run, err := w.Jobs.Submit(ctx, jobs.SubmitRun{ RunName: opts.name, Tasks: tasks, diff --git a/internal/testutil/interface.go b/internal/testutil/interface.go index 97441212dd..4e0377e14c 100644 --- a/internal/testutil/interface.go +++ b/internal/testutil/interface.go @@ -1,5 +1,7 @@ package testutil +import "context" + // TestingT is an interface wrapper around *testing.T that provides the methods // that are used by the test package to convey information about test failures. // @@ -21,6 +23,8 @@ type TestingT interface { Cleanup(func()) + Context() context.Context + Setenv(key, value string) TempDir() string diff --git a/libs/agent/agent_test.go b/libs/agent/agent_test.go index f300953614..f25db02bad 100644 --- a/libs/agent/agent_test.go +++ b/libs/agent/agent_test.go @@ -19,7 +19,7 @@ func clearAllAgentEnvVars(ctx context.Context) context.Context { func TestDetectEachAgent(t *testing.T) { for _, a := range knownAgents { t.Run(a.product, func(t *testing.T) { - ctx := clearAllAgentEnvVars(context.Background()) + ctx := clearAllAgentEnvVars(t.Context()) ctx = env.Set(ctx, a.envVar, "1") assert.Equal(t, a.product, detect(ctx)) @@ -28,7 +28,7 @@ func TestDetectEachAgent(t *testing.T) { } func TestDetectViaContext(t *testing.T) { - ctx := clearAllAgentEnvVars(context.Background()) + ctx := clearAllAgentEnvVars(t.Context()) ctx = env.Set(ctx, knownAgents[0].envVar, "1") ctx = Detect(ctx) @@ -37,7 +37,7 @@ func TestDetectViaContext(t *testing.T) { } func TestDetectNoAgent(t *testing.T) { - ctx := clearAllAgentEnvVars(context.Background()) + ctx := clearAllAgentEnvVars(t.Context()) ctx = Detect(ctx) @@ -45,7 +45,7 @@ func TestDetectNoAgent(t *testing.T) { } func TestDetectMultipleAgents(t *testing.T) { - ctx := clearAllAgentEnvVars(context.Background()) + ctx := clearAllAgentEnvVars(t.Context()) for _, a := range knownAgents { ctx = env.Set(ctx, a.envVar, "1") } @@ -54,7 +54,7 @@ func TestDetectMultipleAgents(t *testing.T) { } func TestProductCalledBeforeDetect(t *testing.T) { - ctx := context.Background() + ctx := t.Context() require.Panics(t, func() { Product(ctx) @@ -62,7 +62,7 @@ func TestProductCalledBeforeDetect(t *testing.T) { } func TestMock(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = Mock(ctx, "test-agent") assert.Equal(t, "test-agent", Product(ctx)) diff --git a/libs/appproxy/appproxy_test.go b/libs/appproxy/appproxy_test.go index 3faa8bf525..b19abfe0bc 100644 --- a/libs/appproxy/appproxy_test.go +++ b/libs/appproxy/appproxy_test.go @@ -2,7 +2,6 @@ package appproxy import ( "bytes" - "context" "fmt" "io" "net/http" @@ -35,7 +34,7 @@ func sendTestRequest(t *testing.T, url, path string) (int, []byte) { } func startProxy(t *testing.T, serverAddr string) (*Proxy, string) { - proxy, err := New(context.Background(), "http://"+serverAddr) + proxy, err := New(t.Context(), "http://"+serverAddr) require.NoError(t, err) ln, err := proxy.listen(fmt.Sprintf("localhost:%d", PROXY_PORT)) diff --git a/libs/apps/logstream/backoff_test.go b/libs/apps/logstream/backoff_test.go index eb064d62e3..ec55c5c363 100644 --- a/libs/apps/logstream/backoff_test.go +++ b/libs/apps/logstream/backoff_test.go @@ -43,7 +43,7 @@ func TestBackoffStrategy_Wait(t *testing.T) { b := newBackoffStrategy(50*time.Millisecond, 100*time.Millisecond) start := time.Now() - err := b.Wait(context.Background()) + err := b.Wait(t.Context()) elapsed := time.Since(start) require.NoError(t, err) @@ -54,7 +54,7 @@ func TestBackoffStrategy_Wait(t *testing.T) { t.Run("returns early on cancel", func(t *testing.T) { b := newBackoffStrategy(1*time.Second, 5*time.Second) - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) go func() { time.Sleep(20 * time.Millisecond) cancel() diff --git a/libs/apps/logstream/streamer_test.go b/libs/apps/logstream/streamer_test.go index d0a07434c4..20d1222738 100644 --- a/libs/apps/logstream/streamer_test.go +++ b/libs/apps/logstream/streamer_test.go @@ -48,7 +48,7 @@ func TestLogStreamerTailBufferFlushes(t *testing.T) { formatter: newLogFormatter(false, flags.OutputText), } - require.NoError(t, streamer.Run(context.Background())) + require.NoError(t, streamer.Run(t.Context())) lines := strings.Split(strings.TrimSpace(buf.String()), "\n") require.Len(t, lines, 2, "expected only last two log lines") assert.Contains(t, lines[0], "msg2") @@ -81,7 +81,7 @@ func TestLogStreamerTailFlushErrorPropagates(t *testing.T) { formatter: newLogFormatter(false, flags.OutputText), } - err := streamer.Run(context.Background()) + err := streamer.Run(t.Context()) require.Error(t, err) assert.Equal(t, writerErr, err) } @@ -106,7 +106,7 @@ func TestLogStreamerTrimsCRLFInStructuredEntries(t *testing.T) { formatter: newLogFormatter(false, flags.OutputText), } - require.NoError(t, streamer.Run(context.Background())) + require.NoError(t, streamer.Run(t.Context())) output := buf.String() assert.Contains(t, output, "line with crlf") assert.NotContains(t, output, "\r") @@ -129,7 +129,7 @@ func TestLogStreamerDialErrorIncludesResponseBody(t *testing.T) { formatter: newLogFormatter(false, flags.OutputText), } - err := streamer.Run(context.Background()) + err := streamer.Run(t.Context()) require.Error(t, err) assert.Contains(t, err.Error(), "HTTP 403 Forbidden") assert.Contains(t, err.Error(), "token invalid") @@ -156,7 +156,7 @@ func TestLogStreamerRetriesOnDialFailure(t *testing.T) { formatter: newLogFormatter(false, flags.OutputText), } - ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) + ctx, cancel := context.WithTimeout(t.Context(), 300*time.Millisecond) defer cancel() require.ErrorIs(t, streamer.Run(ctx), context.DeadlineExceeded) @@ -186,7 +186,7 @@ func TestLogStreamerSendsSearchTerm(t *testing.T) { formatter: newLogFormatter(false, flags.OutputText), } - require.NoError(t, streamer.Run(context.Background())) + require.NoError(t, streamer.Run(t.Context())) assert.Contains(t, buf.String(), "boom") } @@ -214,7 +214,7 @@ func TestLogStreamerFiltersSources(t *testing.T) { formatter: newLogFormatter(false, flags.OutputText), } - require.NoError(t, streamer.Run(context.Background())) + require.NoError(t, streamer.Run(t.Context())) output := strings.TrimSpace(buf.String()) assert.Contains(t, output, "app") assert.NotContains(t, output, "sys") @@ -259,7 +259,7 @@ func TestLogStreamerOutputsNDJSON(t *testing.T) { formatter: newLogFormatter(false, flags.OutputJSON), } - require.NoError(t, streamer.Run(context.Background())) + require.NoError(t, streamer.Run(t.Context())) lines := strings.Split(strings.TrimSpace(buf.String()), "\n") require.Len(t, lines, 2, "expected two NDJSON lines") @@ -307,7 +307,7 @@ func TestTailWithoutPrefetchRespectsTailSize(t *testing.T) { formatter: newLogFormatter(false, flags.OutputText), } - require.NoError(t, streamer.Run(context.Background())) + require.NoError(t, streamer.Run(t.Context())) lines := strings.Split(strings.TrimSpace(buf.String()), "\n") require.Len(t, lines, 2) assert.Contains(t, lines[0], "line3") @@ -331,7 +331,7 @@ func TestCloseErrorPropagatesWhenAbnormal(t *testing.T) { formatter: newLogFormatter(false, flags.OutputText), } - err := streamer.Run(context.Background()) + err := streamer.Run(t.Context()) require.Error(t, err) assert.Contains(t, err.Error(), "log stream closed with code 4403") assert.Contains(t, err.Error(), "auth failed") @@ -421,7 +421,7 @@ func TestLogStreamerTailFlushesWithoutFollow(t *testing.T) { formatter: newLogFormatter(false, flags.OutputText), } - ctx, cancel := context.WithTimeout(context.Background(), time.Second) + ctx, cancel := context.WithTimeout(t.Context(), time.Second) defer cancel() done := make(chan error, 1) @@ -462,7 +462,7 @@ func TestLogStreamerFollowTailWithoutPrefetchEmitsRequestedLines(t *testing.T) { formatter: newLogFormatter(false, flags.OutputText), } - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) defer cancel() done := make(chan error, 1) @@ -488,7 +488,7 @@ func TestLogStreamerFollowTailWithoutPrefetchEmitsRequestedLines(t *testing.T) { func TestLogStreamerFollowTailDoesNotReplayAfterReconnect(t *testing.T) { t.Parallel() - stopCtx, stop := context.WithCancel(context.Background()) + stopCtx, stop := context.WithCancel(t.Context()) defer stop() server := newTestLogServer(t, func(id int, conn *websocket.Conn) { @@ -520,7 +520,7 @@ func TestLogStreamerFollowTailDoesNotReplayAfterReconnect(t *testing.T) { formatter: newLogFormatter(false, flags.OutputText), } - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) defer cancel() done := make(chan error, 1) @@ -601,7 +601,7 @@ func TestLogStreamerRefreshesTokenAfterAuthClose(t *testing.T) { formatter: newLogFormatter(false, flags.OutputText), } - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) defer cancel() done := make(chan error, 1) @@ -640,14 +640,14 @@ func TestLogStreamerEmitsPlainTextFrames(t *testing.T) { formatter: newLogFormatter(false, flags.OutputText), } - require.NoError(t, streamer.Run(context.Background())) + require.NoError(t, streamer.Run(t.Context())) assert.Contains(t, buf.String(), "plain text line") } func TestLogStreamerTimeoutStopsQuietFollowStream(t *testing.T) { t.Parallel() - stopCtx, stop := context.WithCancel(context.Background()) + stopCtx, stop := context.WithCancel(t.Context()) defer stop() server := newTestLogServer(t, func(id int, conn *websocket.Conn) { @@ -665,7 +665,7 @@ func TestLogStreamerTimeoutStopsQuietFollowStream(t *testing.T) { formatter: newLogFormatter(false, flags.OutputText), } - ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + ctx, cancel := context.WithTimeout(t.Context(), 100*time.Millisecond) defer cancel() done := make(chan error, 1) @@ -758,7 +758,7 @@ func TestAppStatusCheckerStopsFollowing(t *testing.T) { formatter: newLogFormatter(false, flags.OutputText), } - err := streamer.Run(context.Background()) + err := streamer.Run(t.Context()) require.Error(t, err) assert.Contains(t, err.Error(), "app is no longer available") assert.Contains(t, err.Error(), "app stopped") diff --git a/libs/apps/prompt/prompt_test.go b/libs/apps/prompt/prompt_test.go index 1270535680..caa813df1d 100644 --- a/libs/apps/prompt/prompt_test.go +++ b/libs/apps/prompt/prompt_test.go @@ -103,7 +103,7 @@ func TestValidateProjectName(t *testing.T) { func TestRunWithSpinnerCtx(t *testing.T) { t.Run("successful action", func(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) executed := false err := RunWithSpinnerCtx(ctx, "Testing...", func() error { @@ -116,7 +116,7 @@ func TestRunWithSpinnerCtx(t *testing.T) { }) t.Run("action returns error", func(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) expectedErr := errors.New("action failed") err := RunWithSpinnerCtx(ctx, "Testing...", func() error { @@ -127,7 +127,7 @@ func TestRunWithSpinnerCtx(t *testing.T) { }) t.Run("context cancelled", func(t *testing.T) { - ctx, cancel := context.WithCancel(cmdio.MockDiscard(context.Background())) + ctx, cancel := context.WithCancel(cmdio.MockDiscard(t.Context())) actionStarted := make(chan struct{}) actionDone := make(chan struct{}) @@ -149,7 +149,7 @@ func TestRunWithSpinnerCtx(t *testing.T) { }) t.Run("action panics - recovered", func(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) err := RunWithSpinnerCtx(ctx, "Testing...", func() error { panic("test panic") diff --git a/libs/apps/runlocal/python_test.go b/libs/apps/runlocal/python_test.go index 6699613f77..a3a6fed791 100644 --- a/libs/apps/runlocal/python_test.go +++ b/libs/apps/runlocal/python_test.go @@ -1,7 +1,6 @@ package runlocal import ( - "context" "path/filepath" "testing" @@ -89,7 +88,7 @@ func TestPythonAppGetCommand(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { config, spec := tt.setup() - app := NewPythonApp(context.Background(), config, spec) + app := NewPythonApp(t.Context(), config, spec) cmd, err := app.GetCommand(tt.debug) if !tt.wantErr { diff --git a/libs/apps/runlocal/spec_test.go b/libs/apps/runlocal/spec_test.go index c074d07642..3b3cfde51a 100644 --- a/libs/apps/runlocal/spec_test.go +++ b/libs/apps/runlocal/spec_test.go @@ -136,7 +136,7 @@ func TestAppSpecLoadEnvVars(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() spec, ctx, customEnv := tt.setup(ctx) env, err := spec.LoadEnvVars(ctx, customEnv) diff --git a/libs/apps/vite/bridge_test.go b/libs/apps/vite/bridge_test.go index 60f0aecf00..ade1e7121b 100644 --- a/libs/apps/vite/bridge_test.go +++ b/libs/apps/vite/bridge_test.go @@ -1,7 +1,6 @@ package vite import ( - "context" "encoding/json" "net/http" "net/http/httptest" @@ -155,7 +154,7 @@ func TestBridgeMessageSerialization(t *testing.T) { } func TestBridgeHandleMessage(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) w := &databricks.WorkspaceClient{} @@ -219,7 +218,7 @@ func TestBridgeHandleFileReadRequest(t *testing.T) { require.NoError(t, err) t.Run("successful file read", func(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) w := &databricks.WorkspaceClient{} // Create a mock tunnel connection using httptest @@ -279,7 +278,7 @@ func TestBridgeHandleFileReadRequest(t *testing.T) { }) t.Run("file not found", func(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) w := &databricks.WorkspaceClient{} var lastMessage []byte @@ -335,7 +334,7 @@ func TestBridgeHandleFileReadRequest(t *testing.T) { } func TestBridgeStop(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) w := &databricks.WorkspaceClient{} vb := NewBridge(ctx, w, "test-app", 5173) @@ -355,7 +354,7 @@ func TestBridgeStop(t *testing.T) { } func TestNewBridge(t *testing.T) { - ctx := context.Background() + ctx := t.Context() w := &databricks.WorkspaceClient{} appName := "test-app" diff --git a/libs/apps/vite/validate_dir_test.go b/libs/apps/vite/validate_dir_test.go index b00b2c4123..6b3b28bb5e 100644 --- a/libs/apps/vite/validate_dir_test.go +++ b/libs/apps/vite/validate_dir_test.go @@ -1,7 +1,6 @@ package vite import ( - "context" "encoding/json" "net/http" "net/http/httptest" @@ -131,7 +130,7 @@ func TestBridgeHandleDirListRequest(t *testing.T) { require.NoError(t, err) t.Run("only returns sql files", func(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) w := &databricks.WorkspaceClient{} var lastMessage []byte @@ -196,7 +195,7 @@ func TestBridgeHandleDirListRequest(t *testing.T) { }) t.Run("returns error for invalid path", func(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) w := &databricks.WorkspaceClient{} var lastMessage []byte diff --git a/libs/auth/credentials_test.go b/libs/auth/credentials_test.go index 0d8973f853..11b08fbfbd 100644 --- a/libs/auth/credentials_test.go +++ b/libs/auth/credentials_test.go @@ -163,7 +163,7 @@ func TestCLICredentialsConfigure(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() c := CLICredentials{persistentAuthFn: tt.persistentAuthFn} got, err := c.Configure(ctx, tt.cfg) diff --git a/libs/auth/error_test.go b/libs/auth/error_test.go index 7dd1f309e2..8f93254f7d 100644 --- a/libs/auth/error_test.go +++ b/libs/auth/error_test.go @@ -1,7 +1,6 @@ package auth import ( - "context" "errors" "testing" @@ -37,14 +36,14 @@ func TestAuthTypeDisplayName(t *testing.T) { func TestEnrichAuthError_NonAPIError(t *testing.T) { cfg := &config.Config{Profile: "test", Host: "https://example.com"} original := errors.New("some random error") - result := EnrichAuthError(context.Background(), cfg, original) + result := EnrichAuthError(t.Context(), cfg, original) assert.Equal(t, original, result) } func TestEnrichAuthError_NonAuthStatusCode(t *testing.T) { cfg := &config.Config{Profile: "test", Host: "https://example.com"} original := &apierr.APIError{StatusCode: 404, Message: "not found"} - result := EnrichAuthError(context.Background(), cfg, original) + result := EnrichAuthError(t.Context(), cfg, original) assert.Equal(t, original, result) } @@ -55,7 +54,7 @@ func TestEnrichAuthError_PreservesOriginalError(t *testing.T) { ErrorCode: "PERMISSION_DENIED", Message: "User does not have permission", } - result := EnrichAuthError(context.Background(), cfg, original) + result := EnrichAuthError(t.Context(), cfg, original) var unwrapped *apierr.APIError require.ErrorAs(t, result, &unwrapped) @@ -256,7 +255,7 @@ func TestEnrichAuthError(t *testing.T) { Message: "test error message", } - result := EnrichAuthError(context.Background(), tt.cfg, original) + result := EnrichAuthError(t.Context(), tt.cfg, original) assert.Equal(t, tt.wantMsg, result.Error()) }) } diff --git a/libs/cache/file_cache_env_test.go b/libs/cache/file_cache_env_test.go index 0852385574..6f7e94b4a2 100644 --- a/libs/cache/file_cache_env_test.go +++ b/libs/cache/file_cache_env_test.go @@ -17,7 +17,7 @@ import ( ) func TestCacheEnabledEnvVar(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tempDir := t.TempDir() tests := []struct { @@ -153,7 +153,7 @@ func TestCacheEnabledEnvVar(t *testing.T) { } func TestCacheDirEnvVar(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tempDir := t.TempDir() t.Run("uses DATABRICKS_CACHE_DIR when set", func(t *testing.T) { @@ -203,7 +203,7 @@ func TestCacheDirEnvVar(t *testing.T) { } func TestCacheIsolationByVersion(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tempDir := t.TempDir() t.Setenv("DATABRICKS_CACHE_DIR", tempDir) diff --git a/libs/cache/file_cache_expiry_test.go b/libs/cache/file_cache_expiry_test.go index 6ae55888de..14c9850e93 100644 --- a/libs/cache/file_cache_expiry_test.go +++ b/libs/cache/file_cache_expiry_test.go @@ -13,7 +13,7 @@ import ( // TestFileCacheExpiryBehavior tests that the cache writes files and respects expiry based on mtime func TestFileCacheExpiryBehavior(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tempDir := t.TempDir() // Create cache with 1 minute expiry @@ -71,7 +71,7 @@ func TestFileCacheExpiryBehavior(t *testing.T) { // TestReadFromCacheRespectsExpiry tests that readFromCacheJSON returns false for expired entries based on mtime func TestReadFromCacheRespectsExpiry(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tempDir := t.TempDir() cache, err := newFileCacheWithBaseDir(ctx, tempDir, 1*time.Minute) // 1 minute expiry require.NoError(t, err) diff --git a/libs/cache/file_cache_test.go b/libs/cache/file_cache_test.go index 214c400e7f..93a6f35d60 100644 --- a/libs/cache/file_cache_test.go +++ b/libs/cache/file_cache_test.go @@ -16,7 +16,7 @@ import ( ) func TestNewFileCache(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tempDir := t.TempDir() cacheDir := filepath.Join(tempDir, "cache") ctx = env.Set(ctx, "DATABRICKS_CACHE_ENABLED", "true") @@ -47,7 +47,7 @@ func TestNewFileCache(t *testing.T) { } func TestNewFileCacheWithExistingDirectory(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tempDir := t.TempDir() cacheDir := filepath.Join(tempDir, "existing") @@ -70,7 +70,7 @@ func TestNewFileCacheInvalidPath(t *testing.T) { t.Skip("Skipping invalid path test on Windows") } - ctx := context.Background() + ctx := t.Context() // Try to create cache in a location that should fail invalidPath := "/root/invalid/path/that/should/not/exist" ctx = env.Set(ctx, "DATABRICKS_CACHE_ENABLED", "true") @@ -82,7 +82,7 @@ func TestNewFileCacheInvalidPath(t *testing.T) { } func TestFileCacheGetOrCompute(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tempDir := t.TempDir() cacheDir := filepath.Join(tempDir, "cache") ctx = env.Set(ctx, "DATABRICKS_CACHE_ENABLED", "true") @@ -122,7 +122,7 @@ func TestFileCacheGetOrCompute(t *testing.T) { } func TestFileCacheGetOrComputeError(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tempDir := t.TempDir() cacheDir := filepath.Join(tempDir, "cache") ctx = env.Set(ctx, "DATABRICKS_CACHE_ENABLED", "true") @@ -147,7 +147,7 @@ func TestFileCacheGetOrComputeError(t *testing.T) { } func TestFileCacheGetOrComputeConcurrency(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tempDir := t.TempDir() cacheDir := filepath.Join(tempDir, "cache") ctx = env.Set(ctx, "DATABRICKS_CACHE_ENABLED", "true") @@ -196,7 +196,7 @@ func TestFileCacheGetOrComputeConcurrency(t *testing.T) { } func TestFileCacheCleanupExpiredFiles(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tempDir := t.TempDir() expiry := 60 * time.Minute @@ -234,7 +234,7 @@ func TestFileCacheCleanupExpiredFiles(t *testing.T) { } func TestFileCacheInvalidJSON(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tempDir := t.TempDir() fc, err := newFileCacheWithBaseDir(ctx, tempDir, 60*time.Minute) require.NoError(t, err) @@ -270,7 +270,7 @@ func TestFileCacheInvalidJSON(t *testing.T) { } func TestFileCacheCorruptedData(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tempDir := t.TempDir() fc, err := newFileCacheWithBaseDir(ctx, tempDir, 60*time.Minute) require.NoError(t, err) @@ -306,7 +306,7 @@ func TestFileCacheCorruptedData(t *testing.T) { } func TestFileCacheEmptyFingerprint(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tempDir := t.TempDir() fc, err := newFileCacheWithBaseDir(ctx, tempDir, 60*time.Minute) require.NoError(t, err) @@ -338,7 +338,7 @@ func TestFileCacheEmptyFingerprint(t *testing.T) { } func TestFileCacheMeasurementMode(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tempDir := t.TempDir() fc, err := newFileCacheWithBaseDir(ctx, tempDir, 60*time.Minute) require.NoError(t, err) @@ -387,7 +387,7 @@ func TestFileCacheReadPermissionError(t *testing.T) { t.Skip("Skipping permission test on Windows") } - ctx := context.Background() + ctx := t.Context() tempDir := t.TempDir() fc, err := newFileCacheWithBaseDir(ctx, tempDir, 60*time.Minute) require.NoError(t, err) diff --git a/libs/calladapt/calladapt_test.go b/libs/calladapt/calladapt_test.go index 9f5a1484c5..ceedf2b396 100644 --- a/libs/calladapt/calladapt_test.go +++ b/libs/calladapt/calladapt_test.go @@ -356,7 +356,7 @@ func TestCall(t *testing.T) { DoCreate(ctx context.Context, data *Data) (string, error) }](), method: "DoCreate", - args: []any{context.Background(), &Data{2}}, + args: []any{t.Context(), &Data{2}}, expect: []any{"123"}, }, } diff --git a/libs/cmdctx/account_client_test.go b/libs/cmdctx/account_client_test.go index 0c3a0fa515..6472b1a292 100644 --- a/libs/cmdctx/account_client_test.go +++ b/libs/cmdctx/account_client_test.go @@ -1,7 +1,6 @@ package cmdctx import ( - "context" "testing" "github.com/databricks/databricks-sdk-go" @@ -10,7 +9,7 @@ import ( ) func TestCommandAccountClient(t *testing.T) { - ctx := context.Background() + ctx := t.Context() client := &databricks.AccountClient{ Config: &config.Config{ AccountID: "test-account", @@ -22,7 +21,7 @@ func TestCommandAccountClient(t *testing.T) { AccountClient(ctx) }) - ctx = SetAccountClient(context.Background(), client) + ctx = SetAccountClient(t.Context(), client) // Multiple calls should return a pointer to the same client. a := AccountClient(ctx) diff --git a/libs/cmdctx/config_used_test.go b/libs/cmdctx/config_used_test.go index 4064ee753a..4a8ea02cbb 100644 --- a/libs/cmdctx/config_used_test.go +++ b/libs/cmdctx/config_used_test.go @@ -1,7 +1,6 @@ package cmdctx import ( - "context" "testing" "github.com/databricks/databricks-sdk-go/config" @@ -12,7 +11,7 @@ func TestCommandConfigUsed(t *testing.T) { cfg := &config.Config{ Host: "https://test.com", } - ctx := context.Background() + ctx := t.Context() // Panic if ConfigUsed is called before SetConfigUsed. assert.Panics(t, func() { diff --git a/libs/cmdctx/context_test.go b/libs/cmdctx/context_test.go index 911e60b3fa..6374b10d4d 100644 --- a/libs/cmdctx/context_test.go +++ b/libs/cmdctx/context_test.go @@ -1,7 +1,6 @@ package cmdctx import ( - "context" "testing" "github.com/google/uuid" @@ -9,7 +8,7 @@ import ( ) func TestCommandGenerateExecIdPanics(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // Set the execution ID. ctx = GenerateExecId(ctx) @@ -21,7 +20,7 @@ func TestCommandGenerateExecIdPanics(t *testing.T) { } func TestCommandExecIdPanics(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // Expect a panic if the execution ID is not set. assert.Panics(t, func() { @@ -30,7 +29,7 @@ func TestCommandExecIdPanics(t *testing.T) { } func TestCommandGenerateExecId(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // Set the execution ID. ctx = GenerateExecId(ctx) diff --git a/libs/cmdctx/workspace_client_test.go b/libs/cmdctx/workspace_client_test.go index 3e3cc60f8d..03ef963186 100644 --- a/libs/cmdctx/workspace_client_test.go +++ b/libs/cmdctx/workspace_client_test.go @@ -1,7 +1,6 @@ package cmdctx_test import ( - "context" "testing" "github.com/databricks/cli/libs/cmdctx" @@ -11,7 +10,7 @@ import ( ) func TestCommandWorkspaceClient(t *testing.T) { - ctx := context.Background() + ctx := t.Context() client := &databricks.WorkspaceClient{ Config: &config.Config{ Host: "https://test.com", @@ -23,7 +22,7 @@ func TestCommandWorkspaceClient(t *testing.T) { cmdctx.WorkspaceClient(ctx) }) - ctx = cmdctx.SetWorkspaceClient(context.Background(), client) + ctx = cmdctx.SetWorkspaceClient(t.Context(), client) // Multiple calls should return a pointer to the same client. w := cmdctx.WorkspaceClient(ctx) diff --git a/libs/cmdio/capabilities_test.go b/libs/cmdio/capabilities_test.go index 4c96b36f54..cb3cf5954b 100644 --- a/libs/cmdio/capabilities_test.go +++ b/libs/cmdio/capabilities_test.go @@ -1,7 +1,6 @@ package cmdio import ( - "context" "io" "testing" @@ -137,7 +136,7 @@ func TestCapabilities_SupportsPrompt(t *testing.T) { } func TestDetectGitBash(t *testing.T) { - ctx := context.Background() + ctx := t.Context() assert.False(t, detectGitBash(ctx)) ctx = env.Set(ctx, "MSYSTEM", "MINGW64") diff --git a/libs/cmdio/render_test.go b/libs/cmdio/render_test.go index 51b385b1df..be41f80c38 100644 --- a/libs/cmdio/render_test.go +++ b/libs/cmdio/render_test.go @@ -171,7 +171,7 @@ func TestRender(t *testing.T) { for _, c := range testCases { t.Run(c.name, func(t *testing.T) { output := &bytes.Buffer{} - ctx := context.Background() + ctx := t.Context() cmdIO := NewIO(ctx, c.outputFormat, nil, output, output, c.headerTemplate, c.template) ctx = InContext(ctx, cmdIO) var err error diff --git a/libs/cmdio/spinner_test.go b/libs/cmdio/spinner_test.go index 52a3f28f25..942c7ef75d 100644 --- a/libs/cmdio/spinner_test.go +++ b/libs/cmdio/spinner_test.go @@ -58,7 +58,7 @@ func TestSpinnerModelViewQuitting(t *testing.T) { } func TestSpinnerStructUpdateBeforeClose(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx, _ = NewTestContextWithStderr(ctx) sp := NewSpinner(ctx) @@ -71,7 +71,7 @@ func TestSpinnerStructUpdateBeforeClose(t *testing.T) { } func TestSpinnerStructCloseIdempotent(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx, _ = NewTestContextWithStderr(ctx) sp := NewSpinner(ctx) @@ -82,7 +82,7 @@ func TestSpinnerStructCloseIdempotent(t *testing.T) { } func TestSpinnerStructUpdateAfterClose(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx, _ = NewTestContextWithStderr(ctx) sp := NewSpinner(ctx) @@ -92,7 +92,7 @@ func TestSpinnerStructUpdateAfterClose(t *testing.T) { } func TestSpinnerStructNonInteractive(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // Create context without TTY simulation (non-interactive) ctx, _ = NewTestContextWithStderr(ctx) @@ -104,7 +104,7 @@ func TestSpinnerStructNonInteractive(t *testing.T) { } func TestSpinnerBackwardCompatibility(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx, _ = NewTestContextWithStderr(ctx) // Old API should still work @@ -116,7 +116,7 @@ func TestSpinnerBackwardCompatibility(t *testing.T) { } func TestSpinnerStructContextCancellation(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx, _ = NewTestContextWithStderr(ctx) ctx, cancel := context.WithCancel(ctx) @@ -133,7 +133,7 @@ func TestSpinnerStructContextCancellation(t *testing.T) { } func TestSpinnerStructConcurrentClose(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx, _ = NewTestContextWithStderr(ctx) ctx, cancel := context.WithCancel(ctx) diff --git a/libs/cmdio/testing_test.go b/libs/cmdio/testing_test.go index f214c1d6cf..1af764bee3 100644 --- a/libs/cmdio/testing_test.go +++ b/libs/cmdio/testing_test.go @@ -1,7 +1,6 @@ package cmdio_test import ( - "context" "testing" "github.com/databricks/cli/libs/cmdio" @@ -10,7 +9,7 @@ import ( ) func TestNewTestContextWithStdout(t *testing.T) { - ctx, stdout := cmdio.NewTestContextWithStdout(context.Background()) + ctx, stdout := cmdio.NewTestContextWithStdout(t.Context()) // Render writes to stdout data := map[string]string{"message": "test output"} @@ -21,7 +20,7 @@ func TestNewTestContextWithStdout(t *testing.T) { } func TestNewTestContextWithStderr(t *testing.T) { - ctx, stderr := cmdio.NewTestContextWithStderr(context.Background()) + ctx, stderr := cmdio.NewTestContextWithStderr(t.Context()) require.NotPanics(t, func() { cmdio.LogString(ctx, "test message") diff --git a/libs/databrickscfg/cfgpickers/clusters_test.go b/libs/databrickscfg/cfgpickers/clusters_test.go index 7b574183c8..025a0f4325 100644 --- a/libs/databrickscfg/cfgpickers/clusters_test.go +++ b/libs/databrickscfg/cfgpickers/clusters_test.go @@ -1,7 +1,6 @@ package cfgpickers import ( - "context" "testing" "github.com/databricks/cli/libs/cmdio" @@ -114,7 +113,7 @@ func TestFirstCompatibleCluster(t *testing.T) { defer server.Close() w := databricks.Must(databricks.NewWorkspaceClient((*databricks.Config)(cfg))) - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) clusterID, err := AskForCluster(ctx, w, WithDatabricksConnect("13.1")) require.NoError(t, err) @@ -161,7 +160,7 @@ func TestNoCompatibleClusters(t *testing.T) { defer server.Close() w := databricks.Must(databricks.NewWorkspaceClient((*databricks.Config)(cfg))) - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) _, err := AskForCluster(ctx, w, WithDatabricksConnect("13.1")) require.Equal(t, ErrNoCompatibleClusters, err) } diff --git a/libs/databrickscfg/cfgpickers/warehouses_test.go b/libs/databrickscfg/cfgpickers/warehouses_test.go index d6030b4959..90b076df36 100644 --- a/libs/databrickscfg/cfgpickers/warehouses_test.go +++ b/libs/databrickscfg/cfgpickers/warehouses_test.go @@ -1,7 +1,6 @@ package cfgpickers import ( - "context" "testing" "github.com/databricks/databricks-sdk-go" @@ -35,7 +34,7 @@ func TestFirstCompatibleWarehouse(t *testing.T) { defer server.Close() w := databricks.Must(databricks.NewWorkspaceClient((*databricks.Config)(cfg))) - ctx := context.Background() + ctx := t.Context() clusterID, err := AskForWarehouse(ctx, w, WithWarehouseTypes(sql.EndpointInfoWarehouseTypePro)) require.NoError(t, err) assert.Equal(t, "efg-id", clusterID) @@ -60,7 +59,7 @@ func TestNoCompatibleWarehouses(t *testing.T) { defer server.Close() w := databricks.Must(databricks.NewWorkspaceClient((*databricks.Config)(cfg))) - ctx := context.Background() + ctx := t.Context() _, err := AskForWarehouse(ctx, w, WithWarehouseTypes(sql.EndpointInfoWarehouseTypePro)) assert.Equal(t, ErrNoCompatibleWarehouses, err) } diff --git a/libs/databrickscfg/ops_test.go b/libs/databrickscfg/ops_test.go index c50e796eb3..9032763bb9 100644 --- a/libs/databrickscfg/ops_test.go +++ b/libs/databrickscfg/ops_test.go @@ -1,7 +1,6 @@ package databrickscfg import ( - "context" "os" "path/filepath" "testing" @@ -15,7 +14,7 @@ func TestLoadOrCreate(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "databrickscfg") - file, err := loadOrCreateConfigFile(context.Background(), path) + file, err := loadOrCreateConfigFile(t.Context(), path) assert.NoError(t, err) assert.NotNil(t, file) assert.FileExists(t, path) @@ -23,7 +22,7 @@ func TestLoadOrCreate(t *testing.T) { func TestLoadOrCreate_NotAllowed(t *testing.T) { path := "/dev/databrickscfg" - file, err := loadOrCreateConfigFile(context.Background(), path) + file, err := loadOrCreateConfigFile(t.Context(), path) assert.Error(t, err) assert.Nil(t, file) assert.NoFileExists(t, path) @@ -31,7 +30,7 @@ func TestLoadOrCreate_NotAllowed(t *testing.T) { func TestLoadOrCreate_Bad(t *testing.T) { path := "profile/testdata/badcfg" - file, err := loadOrCreateConfigFile(context.Background(), path) + file, err := loadOrCreateConfigFile(t.Context(), path) assert.Error(t, err) assert.Nil(t, file) } @@ -40,10 +39,10 @@ func TestMatchOrCreateSection_Direct(t *testing.T) { cfg := &config.Config{ Profile: "query", } - file, err := loadOrCreateConfigFile(context.Background(), "profile/testdata/databrickscfg") + file, err := loadOrCreateConfigFile(t.Context(), "profile/testdata/databrickscfg") assert.NoError(t, err) - ctx := context.Background() + ctx := t.Context() section, err := matchOrCreateSection(ctx, file, cfg) assert.NoError(t, err) assert.NotNil(t, section) @@ -54,10 +53,10 @@ func TestMatchOrCreateSection_AccountID(t *testing.T) { cfg := &config.Config{ AccountID: "abc", } - file, err := loadOrCreateConfigFile(context.Background(), "profile/testdata/databrickscfg") + file, err := loadOrCreateConfigFile(t.Context(), "profile/testdata/databrickscfg") assert.NoError(t, err) - ctx := context.Background() + ctx := t.Context() section, err := matchOrCreateSection(ctx, file, cfg) assert.NoError(t, err) assert.NotNil(t, section) @@ -68,10 +67,10 @@ func TestMatchOrCreateSection_NormalizeHost(t *testing.T) { cfg := &config.Config{ Host: "https://query/?o=abracadabra", } - file, err := loadOrCreateConfigFile(context.Background(), "profile/testdata/databrickscfg") + file, err := loadOrCreateConfigFile(t.Context(), "profile/testdata/databrickscfg") assert.NoError(t, err) - ctx := context.Background() + ctx := t.Context() section, err := matchOrCreateSection(ctx, file, cfg) assert.NoError(t, err) assert.NotNil(t, section) @@ -80,10 +79,10 @@ func TestMatchOrCreateSection_NormalizeHost(t *testing.T) { func TestMatchOrCreateSection_NoProfileOrHost(t *testing.T) { cfg := &config.Config{} - file, err := loadOrCreateConfigFile(context.Background(), "profile/testdata/databrickscfg") + file, err := loadOrCreateConfigFile(t.Context(), "profile/testdata/databrickscfg") assert.NoError(t, err) - ctx := context.Background() + ctx := t.Context() _, err = matchOrCreateSection(ctx, file, cfg) assert.EqualError(t, err, "cannot create new profile: empty section name") } @@ -92,10 +91,10 @@ func TestMatchOrCreateSection_MultipleProfiles(t *testing.T) { cfg := &config.Config{ Host: "https://foo", } - file, err := loadOrCreateConfigFile(context.Background(), "profile/testdata/databrickscfg") + file, err := loadOrCreateConfigFile(t.Context(), "profile/testdata/databrickscfg") assert.NoError(t, err) - ctx := context.Background() + ctx := t.Context() _, err = matchOrCreateSection(ctx, file, cfg) assert.EqualError(t, err, "multiple profiles matched: foo1, foo2") } @@ -105,10 +104,10 @@ func TestMatchOrCreateSection_NewProfile(t *testing.T) { Host: "https://bar", Profile: "delirium", } - file, err := loadOrCreateConfigFile(context.Background(), "profile/testdata/databrickscfg") + file, err := loadOrCreateConfigFile(t.Context(), "profile/testdata/databrickscfg") assert.NoError(t, err) - ctx := context.Background() + ctx := t.Context() section, err := matchOrCreateSection(ctx, file, cfg) assert.NoError(t, err) assert.NotNil(t, section) @@ -116,7 +115,7 @@ func TestMatchOrCreateSection_NewProfile(t *testing.T) { } func TestSaveToProfile_ErrorOnLoad(t *testing.T) { - ctx := context.Background() + ctx := t.Context() err := SaveToProfile(ctx, &config.Config{ ConfigFile: "testdata/badcfg", }) @@ -124,7 +123,7 @@ func TestSaveToProfile_ErrorOnLoad(t *testing.T) { } func TestSaveToProfile_ErrorOnMatch(t *testing.T) { - ctx := context.Background() + ctx := t.Context() err := SaveToProfile(ctx, &config.Config{ Host: "https://foo", }) @@ -132,7 +131,7 @@ func TestSaveToProfile_ErrorOnMatch(t *testing.T) { } func TestSaveToProfile_NewFileWithoutDefault(t *testing.T) { - ctx := context.Background() + ctx := t.Context() path := filepath.Join(t.TempDir(), "databrickscfg") err := SaveToProfile(ctx, &config.Config{ @@ -157,7 +156,7 @@ token = xyz } func TestSaveToProfile_NewFileWithDefault(t *testing.T) { - ctx := context.Background() + ctx := t.Context() path := filepath.Join(t.TempDir(), "databrickscfg") err := SaveToProfile(ctx, &config.Config{ @@ -255,7 +254,7 @@ func TestSaveToProfile_MergeSemantics(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() path := filepath.Join(t.TempDir(), "databrickscfg") for _, save := range tc.saves { @@ -264,7 +263,7 @@ func TestSaveToProfile_MergeSemantics(t *testing.T) { require.NoError(t, err) } - file, err := loadOrCreateConfigFile(context.Background(), path) + file, err := loadOrCreateConfigFile(t.Context(), path) require.NoError(t, err) section, err := file.GetSection(tc.profile) diff --git a/libs/databrickscfg/profile/file_test.go b/libs/databrickscfg/profile/file_test.go index 6bcaec4b77..e207877cf4 100644 --- a/libs/databrickscfg/profile/file_test.go +++ b/libs/databrickscfg/profile/file_test.go @@ -1,7 +1,6 @@ package profile import ( - "context" "path/filepath" "testing" @@ -29,7 +28,7 @@ func TestProfilesSearchCaseInsensitive(t *testing.T) { } func TestLoadProfilesReturnsHomedirAsTilde(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = env.WithUserHomeDir(ctx, "testdata") ctx = env.Set(ctx, "DATABRICKS_CONFIG_FILE", "./testdata/databrickscfg") profiler := FileProfilerImpl{} @@ -39,7 +38,7 @@ func TestLoadProfilesReturnsHomedirAsTilde(t *testing.T) { } func TestLoadProfilesReturnsHomedirAsTildeExoticFile(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = env.WithUserHomeDir(ctx, "testdata") ctx = env.Set(ctx, "DATABRICKS_CONFIG_FILE", "~/databrickscfg") profiler := FileProfilerImpl{} @@ -49,7 +48,7 @@ func TestLoadProfilesReturnsHomedirAsTildeExoticFile(t *testing.T) { } func TestLoadProfilesReturnsHomedirAsTildeDefaultFile(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = env.WithUserHomeDir(ctx, "testdata/sample-home") profiler := FileProfilerImpl{} file, err := profiler.GetPath(ctx) @@ -58,7 +57,7 @@ func TestLoadProfilesReturnsHomedirAsTildeDefaultFile(t *testing.T) { } func TestLoadProfilesNoConfiguration(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = env.WithUserHomeDir(ctx, "testdata") profiler := FileProfilerImpl{} _, err := profiler.LoadProfiles(ctx, MatchAllProfiles) @@ -66,7 +65,7 @@ func TestLoadProfilesNoConfiguration(t *testing.T) { } func TestLoadProfilesMatchWorkspace(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = env.Set(ctx, "DATABRICKS_CONFIG_FILE", "./testdata/databrickscfg") profiler := FileProfilerImpl{} profiles, err := profiler.LoadProfiles(ctx, MatchWorkspaceProfiles) @@ -75,7 +74,7 @@ func TestLoadProfilesMatchWorkspace(t *testing.T) { } func TestLoadProfilesMatchAccount(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = env.Set(ctx, "DATABRICKS_CONFIG_FILE", "./testdata/databrickscfg") profiler := FileProfilerImpl{} profiles, err := profiler.LoadProfiles(ctx, MatchAccountProfiles) diff --git a/libs/dbr/context_test.go b/libs/dbr/context_test.go index 79d6edbcdf..b779273838 100644 --- a/libs/dbr/context_test.go +++ b/libs/dbr/context_test.go @@ -1,14 +1,13 @@ package dbr import ( - "context" "testing" "github.com/stretchr/testify/assert" ) func TestContext_DetectRuntimePanics(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // Run detection. ctx = DetectRuntime(ctx) @@ -20,7 +19,7 @@ func TestContext_DetectRuntimePanics(t *testing.T) { } func TestContext_MockRuntimePanics(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // Run detection. ctx = MockRuntime(ctx, Environment{IsDbr: true, Version: "15.4"}) @@ -32,7 +31,7 @@ func TestContext_MockRuntimePanics(t *testing.T) { } func TestContext_RunsOnRuntimePanics(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // Expect a panic if the detection is not run. assert.Panics(t, func() { @@ -41,7 +40,7 @@ func TestContext_RunsOnRuntimePanics(t *testing.T) { } func TestContext_RuntimeVersionPanics(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // Expect a panic if the detection is not run. assert.Panics(t, func() { @@ -50,7 +49,7 @@ func TestContext_RuntimeVersionPanics(t *testing.T) { } func TestContext_RunsOnRuntime(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // Run detection. ctx = DetectRuntime(ctx) @@ -62,7 +61,7 @@ func TestContext_RunsOnRuntime(t *testing.T) { } func TestContext_RuntimeVersion(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // Run detection. ctx = DetectRuntime(ctx) @@ -74,13 +73,13 @@ func TestContext_RuntimeVersion(t *testing.T) { } func TestContext_RunsOnRuntimeWithMock(t *testing.T) { - ctx := context.Background() + ctx := t.Context() assert.True(t, RunsOnRuntime(MockRuntime(ctx, Environment{IsDbr: true, Version: "15.4"}))) assert.False(t, RunsOnRuntime(MockRuntime(ctx, Environment{}))) } func TestContext_RuntimeVersionWithMock(t *testing.T) { - ctx := context.Background() + ctx := t.Context() assert.Equal(t, "15.4", RuntimeVersion(MockRuntime(ctx, Environment{IsDbr: true, Version: "15.4"})).String()) assert.Empty(t, RuntimeVersion(MockRuntime(ctx, Environment{})).String()) } @@ -165,7 +164,7 @@ func TestVersion_String(t *testing.T) { } func TestContext_RuntimeVersionParsed(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // Test serverless version serverlessCtx := MockRuntime(ctx, Environment{IsDbr: true, Version: "client.4.9"}) diff --git a/libs/dbr/detect_test.go b/libs/dbr/detect_test.go index 9716b50f6c..8ead833167 100644 --- a/libs/dbr/detect_test.go +++ b/libs/dbr/detect_test.go @@ -1,7 +1,6 @@ package dbr import ( - "context" "io/fs" "runtime" "testing" @@ -34,7 +33,7 @@ func TestDetect_NotLinux(t *testing.T) { t.Skip("skipping test on Linux OS") } - ctx := context.Background() + ctx := t.Context() assert.Equal(t, Environment{}, detect(ctx)) } @@ -45,12 +44,12 @@ func TestDetect_Env(t *testing.T) { configureStatFunc(t, fakefs.FileInfo{FakeDir: true}, nil) t.Run("empty", func(t *testing.T) { - ctx := env.Set(context.Background(), "DATABRICKS_RUNTIME_VERSION", "") + ctx := env.Set(t.Context(), "DATABRICKS_RUNTIME_VERSION", "") assert.Equal(t, Environment{}, detect(ctx)) }) t.Run("non-empty cluster", func(t *testing.T) { - ctx := env.Set(context.Background(), "DATABRICKS_RUNTIME_VERSION", "15.4") + ctx := env.Set(t.Context(), "DATABRICKS_RUNTIME_VERSION", "15.4") assert.Equal(t, Environment{ IsDbr: true, Version: "15.4", @@ -58,7 +57,7 @@ func TestDetect_Env(t *testing.T) { }) t.Run("non-empty serverless", func(t *testing.T) { - ctx := env.Set(context.Background(), "DATABRICKS_RUNTIME_VERSION", "client.1.13") + ctx := env.Set(t.Context(), "DATABRICKS_RUNTIME_VERSION", "client.1.13") assert.Equal(t, Environment{ IsDbr: true, Version: "client.1.13", @@ -70,7 +69,7 @@ func TestDetect_Stat(t *testing.T) { requireLinux(t) // Configure other checks to pass. - ctx := env.Set(context.Background(), "DATABRICKS_RUNTIME_VERSION", "non-empty") + ctx := env.Set(t.Context(), "DATABRICKS_RUNTIME_VERSION", "non-empty") t.Run("error", func(t *testing.T) { configureStatFunc(t, nil, fs.ErrNotExist) diff --git a/libs/env/context_test.go b/libs/env/context_test.go index 0886961362..b87078e3cb 100644 --- a/libs/env/context_test.go +++ b/libs/env/context_test.go @@ -1,7 +1,6 @@ package env import ( - "context" "testing" "github.com/databricks/cli/internal/testutil" @@ -12,7 +11,7 @@ func TestContext(t *testing.T) { testutil.CleanupEnvironment(t) t.Setenv("FOO", "bar") - ctx0 := context.Background() + ctx0 := t.Context() // Get assert.Equal(t, "bar", Get(ctx0, "FOO")) @@ -49,7 +48,7 @@ func TestContext(t *testing.T) { } func TestHome(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = WithUserHomeDir(ctx, "...") home, err := UserHomeDir(ctx) assert.Equal(t, "...", home) @@ -58,7 +57,7 @@ func TestHome(t *testing.T) { func TestGetBool(t *testing.T) { testutil.CleanupEnvironment(t) - ctx := context.Background() + ctx := t.Context() // Test true values trueValues := []string{"true", "TRUE", "True", "1", "t", "T", "yes", "YES", "Yes", "on", "ON", "On"} @@ -100,12 +99,12 @@ func TestGetBool(t *testing.T) { // Test from actual environment variable t.Setenv("TEST_ENV_BOOL", "true") - val, ok = GetBool(context.Background(), "TEST_ENV_BOOL") + val, ok = GetBool(t.Context(), "TEST_ENV_BOOL") assert.True(t, ok) assert.True(t, val) t.Setenv("TEST_ENV_BOOL_FALSE", "0") - val, ok = GetBool(context.Background(), "TEST_ENV_BOOL_FALSE") + val, ok = GetBool(t.Context(), "TEST_ENV_BOOL_FALSE") assert.True(t, ok) assert.False(t, val) } diff --git a/libs/env/loader_test.go b/libs/env/loader_test.go index 2d1fa4002e..23ab2b0d7f 100644 --- a/libs/env/loader_test.go +++ b/libs/env/loader_test.go @@ -1,7 +1,6 @@ package env import ( - "context" "testing" "github.com/databricks/databricks-sdk-go/config" @@ -9,7 +8,7 @@ import ( ) func TestLoader(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = Set(ctx, "DATABRICKS_WAREHOUSE_ID", "...") ctx = Set(ctx, "DATABRICKS_CONFIG_PROFILE", "...") loader := NewConfigLoader(ctx) diff --git a/libs/exec/exec_test.go b/libs/exec/exec_test.go index 8858e940c8..ffcf7a0a02 100644 --- a/libs/exec/exec_test.go +++ b/libs/exec/exec_test.go @@ -1,7 +1,6 @@ package exec import ( - "context" "errors" "fmt" "io" @@ -18,7 +17,7 @@ import ( func TestExecutorWithSimpleInput(t *testing.T) { executor, err := NewCommandExecutor(".") assert.NoError(t, err) - out, err := executor.Exec(context.Background(), "echo 'Hello'") + out, err := executor.Exec(t.Context(), "echo 'Hello'") assert.NoError(t, err) assert.NotNil(t, out) assert.Equal(t, "Hello\n", string(out)) @@ -27,7 +26,7 @@ func TestExecutorWithSimpleInput(t *testing.T) { func TestExecutorWithComplexInput(t *testing.T) { executor, err := NewCommandExecutor(".") assert.NoError(t, err) - out, err := executor.Exec(context.Background(), "echo 'Hello' && echo 'World'") + out, err := executor.Exec(t.Context(), "echo 'Hello' && echo 'World'") assert.NoError(t, err) assert.NotNil(t, out) assert.Equal(t, "Hello\nWorld\n", string(out)) @@ -36,7 +35,7 @@ func TestExecutorWithComplexInput(t *testing.T) { func TestExecutorWithStderr(t *testing.T) { executor, err := NewCommandExecutor(".") assert.NoError(t, err) - out, err := executor.Exec(context.Background(), "echo 'Hello' && >&2 echo 'Error'") + out, err := executor.Exec(t.Context(), "echo 'Hello' && >&2 echo 'Error'") assert.NoError(t, err) assert.NotNil(t, out) assert.Equal(t, "Hello\nError\n", string(out)) @@ -45,7 +44,7 @@ func TestExecutorWithStderr(t *testing.T) { func TestExecutorWithInvalidCommand(t *testing.T) { executor, err := NewCommandExecutor(".") assert.NoError(t, err) - out, err := executor.Exec(context.Background(), "invalid-command") + out, err := executor.Exec(t.Context(), "invalid-command") assert.Error(t, err) assert.Contains(t, string(out), "invalid-command: command not found") } @@ -57,7 +56,7 @@ func TestExecutorWithInvalidCommandWithWindowsLikePath(t *testing.T) { executor, err := NewCommandExecutor(".") assert.NoError(t, err) - out, err := executor.Exec(context.Background(), `"C:\Program Files\invalid-command.exe"`) + out, err := executor.Exec(t.Context(), `"C:\Program Files\invalid-command.exe"`) assert.Error(t, err) assert.Contains(t, string(out), "C:\\Program Files\\invalid-command.exe: No such file or directory") } @@ -96,7 +95,7 @@ func testExecutorWithShell(t *testing.T, shell string) { executor, err := NewCommandExecutor(".") assert.NoError(t, err) - out, err := executor.Exec(context.Background(), "echo 'Hello from shell'") + out, err := executor.Exec(t.Context(), "echo 'Hello from shell'") assert.NoError(t, err) assert.NotNil(t, out) assert.Contains(t, string(out), "Hello from shell") @@ -124,7 +123,7 @@ func TestExecutorCleanupsTempFiles(t *testing.T) { executor, err := NewCommandExecutorWithExecutable(".", CmdExecutable) assert.NoError(t, err) - cmd, ec, err := executor.prepareCommand(context.Background(), "echo 'Hello'") + cmd, ec, err := executor.prepareCommand(t.Context(), "echo 'Hello'") assert.NoError(t, err) command, err := executor.start(cmd, ec) @@ -147,7 +146,7 @@ func TestMultipleCommandsRunInParrallel(t *testing.T) { var wg sync.WaitGroup for i := range count { - cmd, err := executor.StartCommand(context.Background(), fmt.Sprintf("echo 'Hello %d'", i)) + cmd, err := executor.StartCommand(t.Context(), fmt.Sprintf("echo 'Hello %d'", i)) if !assert.NoError(t, err) { continue } diff --git a/libs/filer/completer/completer_test.go b/libs/filer/completer/completer_test.go index 9a5bc448f8..7ee3ae0b64 100644 --- a/libs/filer/completer/completer_test.go +++ b/libs/filer/completer/completer_test.go @@ -1,7 +1,6 @@ package completer import ( - "context" "runtime" "testing" @@ -14,7 +13,7 @@ import ( ) func setupCompleter(t *testing.T, onlyDirs bool) *completer { - ctx := context.Background() + ctx := t.Context() // Needed to make type context.valueCtx for mockFilerForPath ctx = cmdctx.SetWorkspaceClient(ctx, mocks.NewMockWorkspaceClient(t).WorkspaceClient) diff --git a/libs/filer/fake_filer_test.go b/libs/filer/fake_filer_test.go index fb5364888e..e32c2f4a70 100644 --- a/libs/filer/fake_filer_test.go +++ b/libs/filer/fake_filer_test.go @@ -1,7 +1,6 @@ package filer import ( - "context" "io" "io/fs" "testing" @@ -16,7 +15,7 @@ func TestFakeFiler_Read(t *testing.T) { "file": {}, }) - ctx := context.Background() + ctx := t.Context() r, err := f.Read(ctx, "file") require.NoError(t, err) contents, err := io.ReadAll(r) @@ -31,7 +30,7 @@ func TestFakeFiler_Read_NotFound(t *testing.T) { "foo": {}, }) - ctx := context.Background() + ctx := t.Context() _, err := f.Read(ctx, "bar") assert.ErrorIs(t, err, fs.ErrNotExist) } @@ -41,7 +40,7 @@ func TestFakeFiler_ReadDir_NotFound(t *testing.T) { "dir1": {FakeDir: true}, }) - ctx := context.Background() + ctx := t.Context() _, err := f.ReadDir(ctx, "dir2") assert.ErrorIs(t, err, fs.ErrNotExist) } @@ -51,7 +50,7 @@ func TestFakeFiler_ReadDir_NotADirectory(t *testing.T) { "file": {}, }) - ctx := context.Background() + ctx := t.Context() _, err := f.ReadDir(ctx, "file") assert.ErrorIs(t, err, fs.ErrInvalid) } @@ -63,7 +62,7 @@ func TestFakeFiler_ReadDir(t *testing.T) { "dir1/dir2": {FakeDir: true}, }) - ctx := context.Background() + ctx := t.Context() entries, err := f.ReadDir(ctx, "dir1/") require.NoError(t, err) require.Len(t, entries, 2) @@ -80,7 +79,7 @@ func TestFakeFiler_Stat(t *testing.T) { "file": {}, }) - ctx := context.Background() + ctx := t.Context() info, err := f.Stat(ctx, "file") require.NoError(t, err) @@ -92,7 +91,7 @@ func TestFakeFiler_Stat_NotFound(t *testing.T) { "foo": {}, }) - ctx := context.Background() + ctx := t.Context() _, err := f.Stat(ctx, "bar") assert.ErrorIs(t, err, fs.ErrNotExist) } diff --git a/libs/filer/fs_test.go b/libs/filer/fs_test.go index 6168af39a0..26df56c166 100644 --- a/libs/filer/fs_test.go +++ b/libs/filer/fs_test.go @@ -1,7 +1,6 @@ package filer import ( - "context" "io" "io/fs" "testing" @@ -35,7 +34,7 @@ func TestFsDirImplementsFsReadDirFile(t *testing.T) { var _ fs.ReadDirFile = &fsDir{} } -func fakeFS() fs.FS { +func fakeFS(t *testing.T) fs.FS { fakeFiler := NewFakeFiler(map[string]fakefs.FileInfo{ ".": {FakeName: "root", FakeDir: true}, "dirA": {FakeDir: true}, @@ -43,18 +42,18 @@ func fakeFS() fs.FS { "fileA": {FakeSize: 3}, }) - return NewFS(context.Background(), fakeFiler) + return NewFS(t.Context(), fakeFiler) } func TestFsGlob(t *testing.T) { - fakeFS := fakeFS() + fakeFS := fakeFS(t) matches, err := fs.Glob(fakeFS, "*") require.NoError(t, err) assert.Equal(t, []string{"dirA", "dirB", "fileA"}, matches) } func TestFsOpenFile(t *testing.T) { - fakeFS := fakeFS() + fakeFS := fakeFS(t) fakeFile, err := fakeFS.Open("fileA") require.NoError(t, err) @@ -84,7 +83,7 @@ func TestFsOpenFile(t *testing.T) { } func TestFsOpenDir(t *testing.T) { - fakeFS := fakeFS() + fakeFS := fakeFS(t) fakeFile, err := fakeFS.Open(".") require.NoError(t, err) @@ -144,7 +143,7 @@ func TestFsOpenDir(t *testing.T) { } func TestFsReadDir(t *testing.T) { - fakeFS := fakeFS().(fs.ReadDirFS) + fakeFS := fakeFS(t).(fs.ReadDirFS) entries, err := fakeFS.ReadDir(".") require.NoError(t, err) assert.Len(t, entries, 3) @@ -154,14 +153,14 @@ func TestFsReadDir(t *testing.T) { } func TestFsReadFile(t *testing.T) { - fakeFS := fakeFS().(fs.ReadFileFS) + fakeFS := fakeFS(t).(fs.ReadFileFS) buf, err := fakeFS.ReadFile("fileA") require.NoError(t, err) assert.Equal(t, []byte("foo"), buf) } func TestFsStat(t *testing.T) { - fakeFS := fakeFS().(fs.StatFS) + fakeFS := fakeFS(t).(fs.StatFS) info, err := fakeFS.Stat("fileA") require.NoError(t, err) assert.Equal(t, "fileA", info.Name()) diff --git a/libs/filer/workspace_files_cache_test.go b/libs/filer/workspace_files_cache_test.go index a73f415c19..770a0b9c04 100644 --- a/libs/filer/workspace_files_cache_test.go +++ b/libs/filer/workspace_files_cache_test.go @@ -80,7 +80,7 @@ func TestWorkspaceFilesCache_ReadDirCache(t *testing.T) { }, } - ctx := context.Background() + ctx := t.Context() cache := newWorkspaceFilesReadaheadCache(f) defer cache.Cleanup() @@ -121,7 +121,7 @@ func TestWorkspaceFilesCache_ReadDirCacheIsolation(t *testing.T) { }, } - ctx := context.Background() + ctx := t.Context() cache := newWorkspaceFilesReadaheadCache(f) defer cache.Cleanup() @@ -152,7 +152,7 @@ func TestWorkspaceFilesCache_StatCache(t *testing.T) { }, } - ctx := context.Background() + ctx := t.Context() cache := newWorkspaceFilesReadaheadCache(f) defer cache.Cleanup() @@ -221,7 +221,7 @@ func TestWorkspaceFilesCache_ReadDirPopulatesStatCache(t *testing.T) { }, } - ctx := context.Background() + ctx := t.Context() cache := newWorkspaceFilesReadaheadCache(f) defer cache.Cleanup() @@ -288,7 +288,7 @@ func TestWorkspaceFilesCache_ReadDirTriggersReadahead(t *testing.T) { }, } - ctx := context.Background() + ctx := t.Context() cache := newWorkspaceFilesReadaheadCache(f) defer cache.Cleanup() diff --git a/libs/filer/workspace_files_extensions_client_test.go b/libs/filer/workspace_files_extensions_client_test.go index e9fde47628..b3b4861ee8 100644 --- a/libs/filer/workspace_files_extensions_client_test.go +++ b/libs/filer/workspace_files_extensions_client_test.go @@ -186,7 +186,7 @@ func TestFilerWorkspaceFilesExtensionsErrorsOnDupName(t *testing.T) { wsfs: &workspaceFilesClient, } - _, err := workspaceFilesExtensionsClient.ReadDir(context.Background(), "/") + _, err := workspaceFilesExtensionsClient.ReadDir(t.Context(), "/") if tc.expectedError == "" { assert.NoError(t, err) diff --git a/libs/git/clone_test.go b/libs/git/clone_test.go index bed5fa54ed..b1f2e7a92d 100644 --- a/libs/git/clone_test.go +++ b/libs/git/clone_test.go @@ -1,7 +1,6 @@ package git import ( - "context" "os/exec" "testing" @@ -39,6 +38,6 @@ func TestGitCloneWithGitNotFound(t *testing.T) { t.Setenv("PATH", "") tmpDir := t.TempDir() - err := Clone(context.Background(), "abc", "", tmpDir) + err := Clone(t.Context(), "abc", "", tmpDir) assert.ErrorIs(t, err, exec.ErrNotFound) } diff --git a/libs/gorules/rule_context_background.go b/libs/gorules/rule_context_background.go new file mode 100644 index 0000000000..d72a4f592c --- /dev/null +++ b/libs/gorules/rule_context_background.go @@ -0,0 +1,10 @@ +package gorules + +import "github.com/quasilyte/go-ruleguard/dsl" + +// UseTestContext detects context.Background() in test files and suggests using t.Context(). +func UseTestContext(m dsl.Matcher) { + m.Match(`context.Background()`). + Where(m.File().Name.Matches(`_test\.go$`)). + Report(`Use t.Context() or b.Context() in tests instead of context.Background()`) +} diff --git a/libs/log/handler/friendly_test.go b/libs/log/handler/friendly_test.go index ca6e823e1e..552b51c71c 100644 --- a/libs/log/handler/friendly_test.go +++ b/libs/log/handler/friendly_test.go @@ -2,7 +2,6 @@ package handler import ( "bytes" - "context" "log/slog" "strings" "testing" @@ -37,7 +36,7 @@ func TestFriendlyHandler(t *testing.T) { log.LevelError, } { run(func() { - logger.Log(context.Background(), level, "simple message") + logger.Log(t.Context(), level, "simple message") }) } diff --git a/libs/patchwheel/filter_test.go b/libs/patchwheel/filter_test.go index 2ed2af831b..d8f482f9ae 100644 --- a/libs/patchwheel/filter_test.go +++ b/libs/patchwheel/filter_test.go @@ -1,7 +1,6 @@ package patchwheel import ( - "context" "testing" "github.com/stretchr/testify/require" @@ -21,7 +20,7 @@ func TestFilterLatestWheels(t *testing.T) { "hello-1.2.3+1741091696780123321-py3-none-any.whl", } - filtered := FilterLatestWheels(context.Background(), paths) + filtered := FilterLatestWheels(t.Context(), paths) require.ElementsMatch(t, []string{ "project_name_bvs7tide6bhhpjy4dmcsb2qg44-0.0.1+20250604.74809-py3-none-any.whl", "not-a-wheel.txt", diff --git a/libs/process/background_test.go b/libs/process/background_test.go index 5cc810f5dd..ecc73c657d 100644 --- a/libs/process/background_test.go +++ b/libs/process/background_test.go @@ -24,20 +24,20 @@ func splitLines(b []byte) (lines []string) { } func TestBackgroundUnwrapsNotFound(t *testing.T) { - ctx := context.Background() + ctx := t.Context() _, err := Background(ctx, []string{"meeecho", "1"}) assert.ErrorIs(t, err, exec.ErrNotFound) } func TestBackground(t *testing.T) { - ctx := context.Background() + ctx := t.Context() res, err := Background(ctx, []string{"echo", "1"}, WithDir("/")) assert.NoError(t, err) assert.Equal(t, "1", strings.TrimSpace(res)) } func TestBackgroundOnlyStdoutGetsoutOnSuccess(t *testing.T) { - ctx := context.Background() + ctx := t.Context() res, err := Background(ctx, []string{ "python3", "-c", "import sys; sys.stderr.write('1'); sys.stdout.write('2')", }) @@ -46,7 +46,7 @@ func TestBackgroundOnlyStdoutGetsoutOnSuccess(t *testing.T) { } func TestBackgroundCombinedOutput(t *testing.T) { - ctx := context.Background() + ctx := t.Context() buf := bytes.Buffer{} res, err := Background(ctx, []string{ "python3", "-c", "import sys, time; " + @@ -66,7 +66,7 @@ func TestBackgroundCombinedOutput(t *testing.T) { } func TestBackgroundCombinedOutputFailure(t *testing.T) { - ctx := context.Background() + ctx := t.Context() buf := bytes.Buffer{} res, err := Background(ctx, []string{ "python3", "-c", "import sys, time; " + @@ -86,20 +86,20 @@ func TestBackgroundCombinedOutputFailure(t *testing.T) { } func TestBackgroundNoStdin(t *testing.T) { - ctx := context.Background() + ctx := t.Context() res, err := Background(ctx, []string{"cat"}) assert.NoError(t, err) assert.Equal(t, "", res) } func TestBackgroundFails(t *testing.T) { - ctx := context.Background() + ctx := t.Context() _, err := Background(ctx, []string{"ls", "/dev/null/x"}) assert.Error(t, err) } func TestBackgroundFailsOnOption(t *testing.T) { - ctx := context.Background() + ctx := t.Context() _, err := Background(ctx, []string{"ls", "/dev/null/x"}, func(_ context.Context, c *exec.Cmd) error { return errors.New("nope") }) diff --git a/libs/process/forwarded_test.go b/libs/process/forwarded_test.go index 71f0a6a63b..9f08af6f86 100644 --- a/libs/process/forwarded_test.go +++ b/libs/process/forwarded_test.go @@ -11,7 +11,7 @@ import ( ) func TestForwarded(t *testing.T) { - ctx := context.Background() + ctx := t.Context() var buf bytes.Buffer err := Forwarded(ctx, []string{ "python3", "-c", "print(input('input: '))", @@ -22,7 +22,7 @@ func TestForwarded(t *testing.T) { } func TestForwardedFails(t *testing.T) { - ctx := context.Background() + ctx := t.Context() var buf bytes.Buffer err := Forwarded(ctx, []string{ "_non_existent_", @@ -31,7 +31,7 @@ func TestForwardedFails(t *testing.T) { } func TestForwardedFailsOnStdinPipe(t *testing.T) { - ctx := context.Background() + ctx := t.Context() var buf bytes.Buffer err := Forwarded(ctx, []string{ "_non_existent_", diff --git a/libs/process/opts_test.go b/libs/process/opts_test.go index 8b5d51928a..15c4f94b01 100644 --- a/libs/process/opts_test.go +++ b/libs/process/opts_test.go @@ -1,7 +1,6 @@ package process import ( - "context" "os/exec" "runtime" "sort" @@ -18,7 +17,7 @@ func TestWithEnvs(t *testing.T) { // /bin/sh -c echo $FOO $BAR: exec: "/bin/sh": file does not exist t.SkipNow() } - ctx := context.Background() + ctx := t.Context() ctx2 := env.Set(ctx, "FOO", "foo") res, err := Background(ctx2, []string{"/bin/sh", "-c", "echo $FOO $BAR"}, WithEnvs(map[string]string{ "BAR": "delirium", @@ -29,7 +28,7 @@ func TestWithEnvs(t *testing.T) { func TestWorksWithLibsEnv(t *testing.T) { testutil.CleanupEnvironment(t) - ctx := context.Background() + ctx := t.Context() cmd := &exec.Cmd{} err := WithEnvs(map[string]string{ diff --git a/libs/process/stub_test.go b/libs/process/stub_test.go index 158e8b3a6b..ac63d1febd 100644 --- a/libs/process/stub_test.go +++ b/libs/process/stub_test.go @@ -1,7 +1,6 @@ package process_test import ( - "context" "errors" "os/exec" "testing" @@ -12,7 +11,7 @@ import ( ) func TestStubOutput(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx, stub := process.WithStub(ctx) stub.WithStdout("meeee") @@ -30,7 +29,7 @@ func TestStubOutput(t *testing.T) { } func TestStubFailure(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx, stub := process.WithStub(ctx) stub.WithFailure(errors.New("nope")) @@ -40,7 +39,7 @@ func TestStubFailure(t *testing.T) { } func TestStubCallback(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx, stub := process.WithStub(ctx) stub.WithCallback(func(cmd *exec.Cmd) error { _, err := cmd.Stderr.Write([]byte("something...")) @@ -65,7 +64,7 @@ func TestStubCallback(t *testing.T) { } func TestStubResponses(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx, stub := process.WithStub(ctx) stub. WithStdoutFor("qux 1", "first"). diff --git a/libs/psql/connect_test.go b/libs/psql/connect_test.go index 65f312f231..24461bf0e6 100644 --- a/libs/psql/connect_test.go +++ b/libs/psql/connect_test.go @@ -1,14 +1,13 @@ package psql import ( - "context" "testing" "github.com/stretchr/testify/assert" ) func TestAttemptConnection(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // Test successful execution (exit code 0) args := []string{"echo", "success"} diff --git a/libs/python/detect_unix_test.go b/libs/python/detect_unix_test.go index 1774aa1082..42bedee189 100644 --- a/libs/python/detect_unix_test.go +++ b/libs/python/detect_unix_test.go @@ -3,14 +3,13 @@ package python import ( - "context" "testing" "github.com/stretchr/testify/assert" ) func TestDetectsViaPathLookup(t *testing.T) { - ctx := context.Background() + ctx := t.Context() py, err := DetectExecutable(ctx) assert.NoError(t, err) assert.NotEmpty(t, py) @@ -18,14 +17,14 @@ func TestDetectsViaPathLookup(t *testing.T) { func TestDetectFailsNoInterpreters(t *testing.T) { t.Setenv("PATH", "testdata") - ctx := context.Background() + ctx := t.Context() _, err := DetectExecutable(ctx) assert.Error(t, err) } func TestDetectFailsNoMinimalVersion(t *testing.T) { t.Setenv("PATH", "testdata/no-python3") - ctx := context.Background() + ctx := t.Context() _, err := DetectExecutable(ctx) assert.Error(t, err) } diff --git a/libs/python/detect_win_test.go b/libs/python/detect_win_test.go index 7b2ee281ea..d4f57f22f0 100644 --- a/libs/python/detect_win_test.go +++ b/libs/python/detect_win_test.go @@ -3,14 +3,13 @@ package python import ( - "context" "testing" "github.com/stretchr/testify/assert" ) func TestDetectsViaPathLookup(t *testing.T) { - ctx := context.Background() + ctx := t.Context() py, err := DetectExecutable(ctx) assert.NoError(t, err) assert.NotEmpty(t, py) @@ -18,7 +17,7 @@ func TestDetectsViaPathLookup(t *testing.T) { func TestDetectFailsNoInterpreters(t *testing.T) { t.Setenv("PATH", "testdata") - ctx := context.Background() + ctx := t.Context() _, err := DetectExecutable(ctx) assert.Error(t, err) } diff --git a/libs/python/pythontest/pythontest_test.go b/libs/python/pythontest/pythontest_test.go index 3161092d32..b4f270afff 100644 --- a/libs/python/pythontest/pythontest_test.go +++ b/libs/python/pythontest/pythontest_test.go @@ -1,7 +1,6 @@ package pythontest import ( - "context" "os/exec" "path/filepath" "testing" @@ -14,7 +13,7 @@ func TestVenvSuccess(t *testing.T) { // Test at least two version to ensure we capture a case where venv version does not match system one for _, pythonVersion := range []string{"3.11", "3.12"} { t.Run(pythonVersion, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() dir := t.TempDir() opts := VenvOpts{ PythonVersion: pythonVersion, diff --git a/libs/sync/snapshot_test.go b/libs/sync/snapshot_test.go index 4ba3874aea..8abde630fa 100644 --- a/libs/sync/snapshot_test.go +++ b/libs/sync/snapshot_test.go @@ -1,7 +1,6 @@ package sync import ( - "context" "fmt" "os" "path/filepath" @@ -26,7 +25,7 @@ func assertKeysOfMap[T any](t *testing.T, m map[string]T, expectedKeys []string) } func TestDiff(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // Create temp project dir projectDir := t.TempDir() @@ -90,7 +89,7 @@ func TestDiff(t *testing.T) { } func TestSymlinkDiff(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // Create temp project dir projectDir := t.TempDir() @@ -121,7 +120,7 @@ func TestSymlinkDiff(t *testing.T) { } func TestFolderDiff(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // Create temp project dir projectDir := t.TempDir() @@ -166,7 +165,7 @@ func TestFolderDiff(t *testing.T) { } func TestPythonNotebookDiff(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // Create temp project dir projectDir := t.TempDir() @@ -241,7 +240,7 @@ func TestPythonNotebookDiff(t *testing.T) { } func TestErrorWhenIdenticalRemoteName(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // Create temp project dir projectDir := t.TempDir() @@ -278,7 +277,7 @@ func TestErrorWhenIdenticalRemoteName(t *testing.T) { } func TestNoErrorRenameWithIdenticalRemoteName(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // Create temp project dir projectDir := t.TempDir() @@ -328,7 +327,7 @@ func defaultOptions(t *testing.T) *SyncOptions { func TestNewSnapshotDefaults(t *testing.T) { opts := defaultOptions(t) - snapshot, err := newSnapshot(context.Background(), opts) + snapshot, err := newSnapshot(t.Context(), opts) require.NoError(t, err) assert.Equal(t, LatestSnapshotVersion, snapshot.Version) @@ -357,7 +356,7 @@ func TestOldSnapshotInvalidation(t *testing.T) { snapshotFile.Close(t) // assert snapshot did not get loaded - snapshot, err := loadOrNewSnapshot(context.Background(), opts) + snapshot, err := loadOrNewSnapshot(t.Context(), opts) require.NoError(t, err) assert.True(t, snapshot.New) } @@ -379,7 +378,7 @@ func TestNoVersionSnapshotInvalidation(t *testing.T) { snapshotFile.Close(t) // assert snapshot did not get loaded - snapshot, err := loadOrNewSnapshot(context.Background(), opts) + snapshot, err := loadOrNewSnapshot(t.Context(), opts) require.NoError(t, err) assert.True(t, snapshot.New) } @@ -402,7 +401,7 @@ func TestLatestVersionSnapshotGetsLoaded(t *testing.T) { snapshotFile.Close(t) // assert snapshot gets loaded - snapshot, err := loadOrNewSnapshot(context.Background(), opts) + snapshot, err := loadOrNewSnapshot(t.Context(), opts) require.NoError(t, err) assert.False(t, snapshot.New) assert.Equal(t, LatestSnapshotVersion, snapshot.Version) diff --git a/libs/sync/sync_test.go b/libs/sync/sync_test.go index 1b54982754..4eb3a31dad 100644 --- a/libs/sync/sync_test.go +++ b/libs/sync/sync_test.go @@ -1,7 +1,6 @@ package sync import ( - "context" "testing" "github.com/databricks/cli/internal/testutil" @@ -33,7 +32,7 @@ func setupFiles(t *testing.T) string { } func TestGetFileSet(t *testing.T) { - ctx := context.Background() + ctx := t.Context() dir := setupFiles(t) root := vfs.MustNew(dir) @@ -96,7 +95,7 @@ func TestGetFileSet(t *testing.T) { } func TestRecursiveExclude(t *testing.T) { - ctx := context.Background() + ctx := t.Context() dir := setupFiles(t) root := vfs.MustNew(dir) @@ -123,7 +122,7 @@ func TestRecursiveExclude(t *testing.T) { } func TestNegateExclude(t *testing.T) { - ctx := context.Background() + ctx := t.Context() dir := setupFiles(t) root := vfs.MustNew(dir) diff --git a/libs/telemetry/logger_test.go b/libs/telemetry/logger_test.go index f0f2a10020..59633403b3 100644 --- a/libs/telemetry/logger_test.go +++ b/libs/telemetry/logger_test.go @@ -1,7 +1,6 @@ package telemetry import ( - "context" "testing" "github.com/databricks/cli/libs/cmdctx" @@ -33,7 +32,7 @@ func TestTelemetryUploadRetriesOnPartialSuccess(t *testing.T) { return nil }) - ctx := WithNewLogger(context.Background()) + ctx := WithNewLogger(t.Context()) Log(ctx, protos.DatabricksCliLog{ CliTestEvent: &protos.CliTestEvent{ @@ -83,7 +82,7 @@ func uploadRetriesFor(t *testing.T, statusCode int) { t.Setenv("DATABRICKS_HOST", server.URL) t.Setenv("DATABRICKS_TOKEN", "token") - ctx := WithNewLogger(context.Background()) + ctx := WithNewLogger(t.Context()) Log(ctx, protos.DatabricksCliLog{ CliTestEvent: &protos.CliTestEvent{ @@ -131,7 +130,7 @@ func TestTelemetryUploadMaxRetries(t *testing.T) { t.Setenv("DATABRICKS_HOST", server.URL) t.Setenv("DATABRICKS_TOKEN", "token") - ctx := WithNewLogger(context.Background()) + ctx := WithNewLogger(t.Context()) Log(ctx, protos.DatabricksCliLog{ CliTestEvent: &protos.CliTestEvent{ diff --git a/libs/template/config_test.go b/libs/template/config_test.go index 515a0b9f5b..f141b6f17f 100644 --- a/libs/template/config_test.go +++ b/libs/template/config_test.go @@ -1,7 +1,6 @@ package template import ( - "context" "fmt" "os" "path" @@ -17,7 +16,7 @@ import ( func TestTemplateConfigAssignValuesFromFile(t *testing.T) { testDir := "./testdata/config-assign-from-file" - ctx := context.Background() + ctx := t.Context() c, err := newConfig(ctx, os.DirFS(testDir), "schema.json") require.NoError(t, err) @@ -33,7 +32,7 @@ func TestTemplateConfigAssignValuesFromFile(t *testing.T) { func TestTemplateConfigAssignValuesFromFileDoesNotOverwriteExistingConfigs(t *testing.T) { testDir := "./testdata/config-assign-from-file" - ctx := context.Background() + ctx := t.Context() c, err := newConfig(ctx, os.DirFS(testDir), "schema.json") require.NoError(t, err) @@ -53,7 +52,7 @@ func TestTemplateConfigAssignValuesFromFileDoesNotOverwriteExistingConfigs(t *te func TestTemplateConfigAssignValuesFromFileForInvalidIntegerValue(t *testing.T) { testDir := "./testdata/config-assign-from-file-invalid-int" - ctx := context.Background() + ctx := t.Context() c, err := newConfig(ctx, os.DirFS(testDir), "schema.json") require.NoError(t, err) @@ -64,7 +63,7 @@ func TestTemplateConfigAssignValuesFromFileForInvalidIntegerValue(t *testing.T) func TestTemplateConfigAssignValuesFromFileFiltersPropertiesNotInTheSchema(t *testing.T) { testDir := "./testdata/config-assign-from-file-unknown-property" - ctx := context.Background() + ctx := t.Context() c, err := newConfig(ctx, os.DirFS(testDir), "schema.json") require.NoError(t, err) @@ -79,7 +78,7 @@ func TestTemplateConfigAssignValuesFromFileFiltersPropertiesNotInTheSchema(t *te func TestTemplateConfigAssignValuesFromDefaultValues(t *testing.T) { testDir := "./testdata/config-assign-from-default-value" - ctx := context.Background() + ctx := t.Context() c, err := newConfig(ctx, os.DirFS(testDir), "schema.json") require.NoError(t, err) @@ -98,7 +97,7 @@ func TestTemplateConfigAssignValuesFromDefaultValues(t *testing.T) { func TestTemplateConfigAssignValuesFromTemplatedDefaultValues(t *testing.T) { testDir := "./testdata/config-assign-from-templated-default-value" - ctx := context.Background() + ctx := t.Context() c, err := newConfig(ctx, os.DirFS(testDir), "schema.json") require.NoError(t, err) @@ -117,7 +116,7 @@ func TestTemplateConfigAssignValuesFromTemplatedDefaultValues(t *testing.T) { } func TestTemplateConfigValidateValuesDefined(t *testing.T) { - ctx := context.Background() + ctx := t.Context() c, err := newConfig(ctx, os.DirFS("testdata/config-test-schema"), "test-schema.json") require.NoError(t, err) @@ -132,7 +131,7 @@ func TestTemplateConfigValidateValuesDefined(t *testing.T) { } func TestTemplateConfigValidateTypeForValidConfig(t *testing.T) { - ctx := context.Background() + ctx := t.Context() c, err := newConfig(ctx, os.DirFS("testdata/config-test-schema"), "test-schema.json") require.NoError(t, err) @@ -148,7 +147,7 @@ func TestTemplateConfigValidateTypeForValidConfig(t *testing.T) { } func TestTemplateConfigValidateTypeForUnknownField(t *testing.T) { - ctx := context.Background() + ctx := t.Context() c, err := newConfig(ctx, os.DirFS("testdata/config-test-schema"), "test-schema.json") require.NoError(t, err) @@ -165,7 +164,7 @@ func TestTemplateConfigValidateTypeForUnknownField(t *testing.T) { } func TestTemplateConfigValidateTypeForInvalidType(t *testing.T) { - ctx := context.Background() + ctx := t.Context() c, err := newConfig(ctx, os.DirFS("testdata/config-test-schema"), "test-schema.json") require.NoError(t, err) @@ -273,7 +272,7 @@ func TestTemplateEnumValidation(t *testing.T) { } func TestTemplateSchemaErrorsWithEmptyDescription(t *testing.T) { - ctx := context.Background() + ctx := t.Context() _, err := newConfig(ctx, os.DirFS("./testdata/config-test-schema"), "invalid-test-schema.json") assert.EqualError(t, err, "template property property-without-description is missing a description") } @@ -289,7 +288,7 @@ func testRenderer() *renderer { func TestPromptIsSkippedWhenEmpty(t *testing.T) { c := config{ - ctx: context.Background(), + ctx: t.Context(), values: make(map[string]any), schema: &jsonschema.Schema{ Properties: map[string]*jsonschema.Schema{ @@ -317,7 +316,7 @@ func TestPromptIsSkippedWhenEmpty(t *testing.T) { func TestPromptSkipErrorsWithEmptyDefault(t *testing.T) { c := config{ - ctx: context.Background(), + ctx: t.Context(), values: make(map[string]any), schema: &jsonschema.Schema{ Properties: map[string]*jsonschema.Schema{ @@ -340,7 +339,7 @@ func TestPromptSkipErrorsWithEmptyDefault(t *testing.T) { func TestPromptIsSkippedIfValueIsAssigned(t *testing.T) { c := config{ - ctx: context.Background(), + ctx: t.Context(), values: make(map[string]any), schema: &jsonschema.Schema{ Properties: map[string]*jsonschema.Schema{ @@ -364,7 +363,7 @@ func TestPromptIsSkippedIfValueIsAssigned(t *testing.T) { func TestPromptIsSkipped(t *testing.T) { c := config{ - ctx: context.Background(), + ctx: t.Context(), values: make(map[string]any), schema: &jsonschema.Schema{ Properties: map[string]*jsonschema.Schema{ @@ -449,7 +448,7 @@ func TestPromptIsSkipped(t *testing.T) { func TestPromptIsSkippedAnyOf(t *testing.T) { c := config{ - ctx: context.Background(), + ctx: t.Context(), values: make(map[string]any), schema: &jsonschema.Schema{ Properties: map[string]*jsonschema.Schema{ diff --git a/libs/template/file_test.go b/libs/template/file_test.go index f4bf5652c8..ca0928337c 100644 --- a/libs/template/file_test.go +++ b/libs/template/file_test.go @@ -57,7 +57,7 @@ func TestTemplateInMemoryFilePersistToDisk(t *testing.T) { if runtime.GOOS == "windows" { t.SkipNow() } - ctx := context.Background() + ctx := t.Context() testInMemoryFile(t, ctx, 0o755) } @@ -67,7 +67,7 @@ func TestTemplateInMemoryFilePersistToDiskForWindows(t *testing.T) { } // we have separate tests for windows because of differences in valid // fs.FileMode values we can use for different operating systems. - ctx := context.Background() + ctx := t.Context() testInMemoryFile(t, ctx, 0o666) } @@ -75,7 +75,7 @@ func TestTemplateCopyFilePersistToDisk(t *testing.T) { if runtime.GOOS == "windows" { t.SkipNow() } - ctx := context.Background() + ctx := t.Context() testCopyFile(t, ctx, 0o644) } @@ -85,6 +85,6 @@ func TestTemplateCopyFilePersistToDiskForWindows(t *testing.T) { } // we have separate tests for windows because of differences in valid // fs.FileMode values we can use for different operating systems. - ctx := context.Background() + ctx := t.Context() testCopyFile(t, ctx, 0o666) } diff --git a/libs/template/helpers_test.go b/libs/template/helpers_test.go index 36d0e1cc5b..fed3e336a5 100644 --- a/libs/template/helpers_test.go +++ b/libs/template/helpers_test.go @@ -1,7 +1,6 @@ package template import ( - "context" "os" "strconv" "strings" @@ -17,7 +16,7 @@ import ( ) func TestTemplatePrintStringWithoutProcessing(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = cmdctx.SetWorkspaceClient(ctx, nil) helpers := loadHelpers(ctx) @@ -33,7 +32,7 @@ func TestTemplatePrintStringWithoutProcessing(t *testing.T) { } func TestTemplateBundleUuidFunction(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = cmdctx.SetWorkspaceClient(ctx, nil) helpers := loadHelpers(ctx) @@ -56,7 +55,7 @@ func TestTemplateBundleUuidFunction(t *testing.T) { } func TestTemplateRegexpCompileFunction(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = cmdctx.SetWorkspaceClient(ctx, nil) helpers := loadHelpers(ctx) @@ -73,7 +72,7 @@ func TestTemplateRegexpCompileFunction(t *testing.T) { } func TestTemplateRandIntFunction(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = cmdctx.SetWorkspaceClient(ctx, nil) helpers := loadHelpers(ctx) @@ -90,7 +89,7 @@ func TestTemplateRandIntFunction(t *testing.T) { } func TestTemplateUuidFunction(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = cmdctx.SetWorkspaceClient(ctx, nil) helpers := loadHelpers(ctx) @@ -106,7 +105,7 @@ func TestTemplateUuidFunction(t *testing.T) { } func TestTemplateUrlFunction(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = cmdctx.SetWorkspaceClient(ctx, nil) helpers := loadHelpers(ctx) @@ -122,7 +121,7 @@ func TestTemplateUrlFunction(t *testing.T) { } func TestTemplateMapPairFunction(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = cmdctx.SetWorkspaceClient(ctx, nil) helpers := loadHelpers(ctx) @@ -138,7 +137,7 @@ func TestTemplateMapPairFunction(t *testing.T) { } func TestWorkspaceHost(t *testing.T) { - ctx := context.Background() + ctx := t.Context() w := &databricks.WorkspaceClient{ Config: &workspaceConfig.Config{ @@ -161,7 +160,7 @@ func TestWorkspaceHost(t *testing.T) { } func TestWorkspaceHostNotConfigured(t *testing.T) { - ctx := context.Background() + ctx := t.Context() cmd := cmdio.NewIO(ctx, flags.OutputJSON, strings.NewReader(""), os.Stdout, os.Stderr, "", "template") ctx = cmdio.InContext(ctx, cmd) diff --git a/libs/template/reader_test.go b/libs/template/reader_test.go index 6d8419cdf4..77117786ab 100644 --- a/libs/template/reader_test.go +++ b/libs/template/reader_test.go @@ -23,7 +23,7 @@ func TestBuiltInReader(t *testing.T) { for _, name := range exists { t.Run(name, func(t *testing.T) { r := &builtinReader{name: name} - schema, fsys, err := r.LoadSchemaAndTemplateFS(context.Background()) + schema, fsys, err := r.LoadSchemaAndTemplateFS(t.Context()) assert.NoError(t, err) assert.NotNil(t, fsys) assert.NotNil(t, schema) @@ -35,7 +35,7 @@ func TestBuiltInReader(t *testing.T) { t.Run("doesnotexist", func(t *testing.T) { r := &builtinReader{name: "doesnotexist"} - _, _, err := r.LoadSchemaAndTemplateFS(context.Background()) + _, _, err := r.LoadSchemaAndTemplateFS(t.Context()) assert.EqualError(t, err, "builtin template doesnotexist not found") }) } @@ -44,7 +44,7 @@ func TestBuiltInReaderTemplateDir(t *testing.T) { // Test that template_dir property works correctly // default-python template should use schema from default-python/ but template files from default/ r := &builtinReader{name: "default-python"} - schema, fsys, err := r.LoadSchemaAndTemplateFS(context.Background()) + schema, fsys, err := r.LoadSchemaAndTemplateFS(t.Context()) require.NoError(t, err) assert.NotNil(t, schema) assert.NotNil(t, fsys) @@ -63,7 +63,7 @@ func TestBuiltInReaderTemplateDir(t *testing.T) { // Test that a template without template_dir works normally r2 := &builtinReader{name: "default-sql"} - schema2, fsys2, err := r2.LoadSchemaAndTemplateFS(context.Background()) + schema2, fsys2, err := r2.LoadSchemaAndTemplateFS(t.Context()) require.NoError(t, err) assert.NotNil(t, schema2) assert.NotNil(t, fsys2) @@ -73,7 +73,7 @@ func TestBuiltInReaderTemplateDir(t *testing.T) { // Verify that lakeflow-pipelines also uses template_dir correctly r3 := &builtinReader{name: "lakeflow-pipelines"} - schema3, fsys3, err := r3.LoadSchemaAndTemplateFS(context.Background()) + schema3, fsys3, err := r3.LoadSchemaAndTemplateFS(t.Context()) require.NoError(t, err) assert.NotNil(t, schema3) assert.NotNil(t, fsys3) @@ -84,7 +84,7 @@ func TestBuiltInReaderTemplateDir(t *testing.T) { } func TestGitUrlReader(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) var args []string numCalls := 0 @@ -132,7 +132,7 @@ func TestLocalReader(t *testing.T) { tmpDir := t.TempDir() testutil.WriteFile(t, filepath.Join(tmpDir, "somefile"), "somecontent") testutil.WriteFile(t, filepath.Join(tmpDir, "databricks_template_schema.json"), `{"welcome_message": "test"}`) - ctx := context.Background() + ctx := t.Context() r := &localReader{path: tmpDir} schema, fsys, err := r.LoadSchemaAndTemplateFS(ctx) @@ -160,7 +160,7 @@ func TestLocalReaderWithTemplateDir(t *testing.T) { testutil.WriteFile(t, filepath.Join(templateDir, "template", "somefile"), "content from template_dir") testutil.WriteFile(t, filepath.Join(templateDir, "template", "{{.project_name}}", "test.yml.tmpl"), "test template content") - ctx := context.Background() + ctx := t.Context() r := &localReader{path: schemaDir} schema, fsys, err := r.LoadSchemaAndTemplateFS(ctx) require.NoError(t, err) @@ -179,7 +179,7 @@ func TestLocalReaderWithTemplateDir(t *testing.T) { } func TestGitReaderWithTemplateDir(t *testing.T) { - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) cloneFunc := func(ctx context.Context, url, reference, targetPath string) error { // Create a template with template_dir reference diff --git a/libs/template/renderer_test.go b/libs/template/renderer_test.go index 6c77aedfb6..30e0fbe3e8 100644 --- a/libs/template/renderer_test.go +++ b/libs/template/renderer_test.go @@ -43,7 +43,7 @@ func init() { } func assertBuiltinTemplateValid(t *testing.T, template string, settings map[string]any, target string, isServicePrincipal, build bool, tempDir string) { - ctx := dbr.MockRuntime(context.Background(), dbr.Environment{}) + ctx := dbr.MockRuntime(t.Context(), dbr.Environment{}) templateFS, err := fs.Sub(builtinTemplates, path.Join("templates", template)) require.NoError(t, err) @@ -152,7 +152,7 @@ func TestBuiltinDbtTemplateValid(t *testing.T) { func TestRendererWithAssociatedTemplateInLibrary(t *testing.T) { tmpDir := t.TempDir() - ctx := context.Background() + ctx := t.Context() ctx = cmdctx.SetWorkspaceClient(ctx, nil) helpers := loadHelpers(ctx) r, err := newRenderer(ctx, nil, helpers, os.DirFS("."), "./testdata/email/template", "./testdata/email/library") @@ -281,7 +281,7 @@ func TestRendererIsSkipped(t *testing.T) { func TestRendererPersistToDisk(t *testing.T) { tmpDir := t.TempDir() - ctx := context.Background() + ctx := t.Context() r := &renderer{ ctx: ctx, @@ -325,7 +325,7 @@ func TestRendererPersistToDisk(t *testing.T) { } func TestRendererWalk(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = cmdctx.SetWorkspaceClient(ctx, nil) helpers := loadHelpers(ctx) @@ -356,7 +356,7 @@ func TestRendererWalk(t *testing.T) { } func TestRendererFailFunction(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = cmdctx.SetWorkspaceClient(ctx, nil) helpers := loadHelpers(ctx) @@ -368,7 +368,7 @@ func TestRendererFailFunction(t *testing.T) { } func TestRendererSkipsDirsEagerly(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = cmdctx.SetWorkspaceClient(ctx, nil) helpers := loadHelpers(ctx) @@ -384,7 +384,7 @@ func TestRendererSkipsDirsEagerly(t *testing.T) { } func TestRendererSkipAllFilesInCurrentDirectory(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = cmdctx.SetWorkspaceClient(ctx, nil) tmpDir := t.TempDir() @@ -409,7 +409,7 @@ func TestRendererSkipAllFilesInCurrentDirectory(t *testing.T) { } func TestRendererSkipPatternsAreRelativeToFileDirectory(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = cmdctx.SetWorkspaceClient(ctx, nil) helpers := loadHelpers(ctx) @@ -426,7 +426,7 @@ func TestRendererSkipPatternsAreRelativeToFileDirectory(t *testing.T) { } func TestRendererSkip(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = cmdctx.SetWorkspaceClient(ctx, nil) tmpDir := t.TempDir() @@ -461,7 +461,7 @@ func TestRendererReadsPermissionsBits(t *testing.T) { if runtime.GOOS != "linux" && runtime.GOOS != "darwin" { t.SkipNow() } - ctx := context.Background() + ctx := t.Context() ctx = cmdctx.SetWorkspaceClient(ctx, nil) helpers := loadHelpers(ctx) @@ -496,7 +496,7 @@ func TestRendererReadsPermissionsBits(t *testing.T) { func TestRendererErrorOnConflictingFile(t *testing.T) { tmpDir := t.TempDir() - ctx := context.Background() + ctx := t.Context() f, err := os.Create(filepath.Join(tmpDir, "a")) require.NoError(t, err) @@ -521,7 +521,7 @@ func TestRendererErrorOnConflictingFile(t *testing.T) { func TestRendererNoErrorOnConflictingFileIfSkipped(t *testing.T) { tmpDir := t.TempDir() - ctx := context.Background() + ctx := t.Context() f, err := os.Create(filepath.Join(tmpDir, "a")) require.NoError(t, err) @@ -549,7 +549,7 @@ func TestRendererNoErrorOnConflictingFileIfSkipped(t *testing.T) { } func TestRendererNonTemplatesAreCreatedAsCopyFiles(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = cmdctx.SetWorkspaceClient(ctx, nil) helpers := loadHelpers(ctx) @@ -565,7 +565,7 @@ func TestRendererNonTemplatesAreCreatedAsCopyFiles(t *testing.T) { } func TestRendererFileTreeRendering(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = cmdctx.SetWorkspaceClient(ctx, nil) tmpDir := t.TempDir() @@ -594,7 +594,7 @@ func TestRendererFileTreeRendering(t *testing.T) { } func TestRendererSubTemplateInPath(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx = cmdctx.SetWorkspaceClient(ctx, nil) // Copy the template directory to a temporary directory where we can safely include a templated file path. diff --git a/libs/template/resolver_test.go b/libs/template/resolver_test.go index 6fbe08c863..2174fe1afe 100644 --- a/libs/template/resolver_test.go +++ b/libs/template/resolver_test.go @@ -1,7 +1,6 @@ package template import ( - "context" "testing" "github.com/databricks/cli/libs/cmdio" @@ -15,13 +14,13 @@ func TestTemplateResolverBothTagAndBranch(t *testing.T) { Branch: "branch", } - _, err := r.Resolve(context.Background()) + _, err := r.Resolve(t.Context()) assert.EqualError(t, err, "only one of tag or branch can be specified") } func TestTemplateResolverErrorsWhenPromptingIsNotSupported(t *testing.T) { r := Resolver{} - ctx := cmdio.MockDiscard(context.Background()) + ctx := cmdio.MockDiscard(t.Context()) _, err := r.Resolve(ctx) assert.EqualError(t, err, "prompting is not supported. Please specify the path, name or URL of the template to use") @@ -38,7 +37,7 @@ func TestTemplateResolverForDefaultTemplates(t *testing.T) { TemplatePathOrUrl: name, } - tmpl, err := r.Resolve(context.Background()) + tmpl, err := r.Resolve(t.Context()) require.NoError(t, err) assert.Equal(t, &builtinReader{name: name}, tmpl.Reader) @@ -52,7 +51,7 @@ func TestTemplateResolverForDefaultTemplates(t *testing.T) { ConfigFile: "/config/file", } - tmpl, err := r.Resolve(context.Background()) + tmpl, err := r.Resolve(t.Context()) require.NoError(t, err) // Assert reader and writer configuration @@ -69,7 +68,7 @@ func TestTemplateResolverForCustomUrl(t *testing.T) { ConfigFile: "/config/file", } - tmpl, err := r.Resolve(context.Background()) + tmpl, err := r.Resolve(t.Context()) require.NoError(t, err) assert.Equal(t, Custom, tmpl.name) @@ -89,7 +88,7 @@ func TestTemplateResolverForCustomPath(t *testing.T) { ConfigFile: "/config/file", } - tmpl, err := r.Resolve(context.Background()) + tmpl, err := r.Resolve(t.Context()) require.NoError(t, err) assert.Equal(t, Custom, tmpl.name) diff --git a/libs/template/schema_renderer_test.go b/libs/template/schema_renderer_test.go index d82f0054b6..9e6c1cc1ca 100644 --- a/libs/template/schema_renderer_test.go +++ b/libs/template/schema_renderer_test.go @@ -1,7 +1,6 @@ package template import ( - "context" "path/filepath" "testing" @@ -29,7 +28,7 @@ func TestRenderSchemaWithLocalTemplate(t *testing.T) { inputFile := filepath.Join(tmpDir, "input.json") testutil.WriteFile(t, inputFile, `{"name": "TestUser"}`) - ctx := context.Background() + ctx := t.Context() ctx = cmdctx.SetWorkspaceClient(ctx, &databricks.WorkspaceClient{}) reader := NewLocalReader(tmpDir) @@ -55,7 +54,7 @@ func TestRenderSchemaWithoutInputFile(t *testing.T) { }` testutil.WriteFile(t, filepath.Join(tmpDir, "databricks_template_schema.json"), schemaContent) - ctx := context.Background() + ctx := t.Context() ctx = cmdctx.SetWorkspaceClient(ctx, &databricks.WorkspaceClient{}) reader := NewLocalReader(tmpDir) @@ -76,7 +75,7 @@ func TestRenderSchemaWithMissingVariable(t *testing.T) { inputFile := filepath.Join(tmpDir, "input.json") testutil.WriteFile(t, inputFile, `{}`) - ctx := context.Background() + ctx := t.Context() ctx = cmdctx.SetWorkspaceClient(ctx, &databricks.WorkspaceClient{}) reader := NewLocalReader(tmpDir) @@ -94,7 +93,7 @@ func TestRenderSchemaWithInvalidInputFile(t *testing.T) { schemaContent := `{"welcome_message": "Hello"}` testutil.WriteFile(t, filepath.Join(tmpDir, "databricks_template_schema.json"), schemaContent) - ctx := context.Background() + ctx := t.Context() ctx = cmdctx.SetWorkspaceClient(ctx, &databricks.WorkspaceClient{}) reader := NewLocalReader(tmpDir) @@ -114,7 +113,7 @@ func TestRenderSchemaWithMalformedInputJson(t *testing.T) { inputFile := filepath.Join(tmpDir, "input.json") testutil.WriteFile(t, inputFile, `{invalid json}`) - ctx := context.Background() + ctx := t.Context() ctx = cmdctx.SetWorkspaceClient(ctx, &databricks.WorkspaceClient{}) reader := NewLocalReader(tmpDir) @@ -126,7 +125,7 @@ func TestRenderSchemaWithMalformedInputJson(t *testing.T) { } func TestRenderSchemaWithBuiltinTemplateFS(t *testing.T) { - ctx := context.Background() + ctx := t.Context() reader := NewBuiltinReader(string(DefaultPython)) schemaFS, err := reader.SchemaFS(ctx) require.NoError(t, err) @@ -147,7 +146,7 @@ func TestRenderSchemaWithSimpleBuiltinTemplate(t *testing.T) { }` testutil.WriteFile(t, filepath.Join(tmpDir, "databricks_template_schema.json"), schemaContent) - ctx := context.Background() + ctx := t.Context() ctx = cmdctx.SetWorkspaceClient(ctx, &databricks.WorkspaceClient{ Config: &workspaceConfig.Config{ Host: "https://test.databricks.com", @@ -167,7 +166,7 @@ func TestLocalReaderSchemaFS(t *testing.T) { testutil.WriteFile(t, filepath.Join(tmpDir, "test.txt"), "content") reader := NewLocalReader(tmpDir) - ctx := context.Background() + ctx := t.Context() schemaFS, err := reader.SchemaFS(ctx) require.NoError(t, err) @@ -176,7 +175,7 @@ func TestLocalReaderSchemaFS(t *testing.T) { func TestBuiltinReaderSchemaFS(t *testing.T) { reader := NewBuiltinReader(string(DefaultPython)) - ctx := context.Background() + ctx := t.Context() fs, err := reader.SchemaFS(ctx) require.NoError(t, err) @@ -185,7 +184,7 @@ func TestBuiltinReaderSchemaFS(t *testing.T) { func TestBuiltinReaderSchemaFSNotFound(t *testing.T) { reader := NewBuiltinReader("nonexistent-template") - ctx := context.Background() + ctx := t.Context() _, err := reader.SchemaFS(ctx) require.Error(t, err) diff --git a/libs/template/writer_test.go b/libs/template/writer_test.go index 8b440f34f8..0fa2931f81 100644 --- a/libs/template/writer_test.go +++ b/libs/template/writer_test.go @@ -1,7 +1,6 @@ package template import ( - "context" "runtime" "testing" @@ -17,7 +16,7 @@ import ( func TestDefaultWriterConfigure(t *testing.T) { // Test on local file system. w := &defaultWriter{} - err := w.Configure(context.Background(), "/foo/bar", "/out/abc") + err := w.Configure(t.Context(), "/foo/bar", "/out/abc") assert.NoError(t, err) assert.Equal(t, "/foo/bar", w.configPath) @@ -31,7 +30,7 @@ func TestDefaultWriterConfigureOnDBR(t *testing.T) { t.Skip("Skipping test on Windows") } - ctx := dbr.MockRuntime(context.Background(), dbr.Environment{IsDbr: true, Version: "15.4"}) + ctx := dbr.MockRuntime(t.Context(), dbr.Environment{IsDbr: true, Version: "15.4"}) ctx = cmdctx.SetWorkspaceClient(ctx, &databricks.WorkspaceClient{ Config: &workspaceConfig.Config{Host: "https://myhost.com"}, }) @@ -46,7 +45,7 @@ func TestDefaultWriterConfigureOnDBR(t *testing.T) { func TestMaterializeForNonTemplateDirectory(t *testing.T) { tmpDir1 := t.TempDir() tmpDir2 := t.TempDir() - ctx := context.Background() + ctx := t.Context() w := &defaultWriter{} err := w.Configure(ctx, "/foo/bar", tmpDir1) diff --git a/libs/testdiff/context_test.go b/libs/testdiff/context_test.go index 5a01910094..41e0b0de1d 100644 --- a/libs/testdiff/context_test.go +++ b/libs/testdiff/context_test.go @@ -1,27 +1,26 @@ package testdiff import ( - "context" "testing" "github.com/stretchr/testify/assert" ) func TestGetReplacementsMap_Nil(t *testing.T) { - ctx := context.Background() + ctx := t.Context() repls := GetReplacementsMap(ctx) assert.Nil(t, repls) } func TestGetReplacementsMap_NotNil(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx, _ = WithReplacementsMap(ctx) repls := GetReplacementsMap(ctx) assert.NotNil(t, repls) } func TestWithReplacementsMap_UseExisting(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctx, r1 := WithReplacementsMap(ctx) ctx, r2 := WithReplacementsMap(ctx) repls := GetReplacementsMap(ctx) diff --git a/libs/testproxy/server.go b/libs/testproxy/server.go index 1937d0677d..60e72c67e6 100644 --- a/libs/testproxy/server.go +++ b/libs/testproxy/server.go @@ -2,7 +2,6 @@ package testproxy import ( "bytes" - "context" "encoding/json" "errors" "net/http" @@ -124,7 +123,7 @@ func (s *ProxyServer) proxyToCloud(w http.ResponseWriter, r *http.Request) { visitors = append(visitors, httpclient.WithResponseHeader(header, responseHeaders[header])) } - err := s.apiClient.Do(context.Background(), r.Method, r.URL.Path, + err := s.apiClient.Do(s.t.Context(), r.Method, r.URL.Path, visitors..., ) diff --git a/libs/vfs/filer_test.go b/libs/vfs/filer_test.go index 6987c288ec..c7dbe2e4f0 100644 --- a/libs/vfs/filer_test.go +++ b/libs/vfs/filer_test.go @@ -1,7 +1,6 @@ package vfs import ( - "context" "io/fs" "os" "path/filepath" @@ -14,7 +13,7 @@ import ( ) func TestFilerPath(t *testing.T) { - ctx := context.Background() + ctx := t.Context() wd, err := os.Getwd() require.NoError(t, err) diff --git a/main_test.go b/main_test.go index dea82e9b93..ba40c19746 100644 --- a/main_test.go +++ b/main_test.go @@ -1,7 +1,6 @@ package main import ( - "context" "io/fs" "path/filepath" "testing" @@ -19,7 +18,7 @@ func TestCommandsDontUseUnderscoreInName(t *testing.T) { // This test lives in the main package because this is where // all commands are imported. // - queue := []*cobra.Command{cmd.New(context.Background())} + queue := []*cobra.Command{cmd.New(t.Context())} for len(queue) > 0 { cmd := queue[0] assert.NotContains(t, cmd.Name(), "_")