From 0520ff4e05f2c4d21888fbc5afbff347ce096f17 Mon Sep 17 00:00:00 2001 From: Earl Warren Date: Mon, 11 Aug 2025 13:21:42 +0000 Subject: [PATCH] chore: use t.Context for tests, activate usetesting for lint + add t.TempDir and t.Chdir (#844) - other - [PR](https://code.forgejo.org/forgejo/runner/pulls/844): chore: use t.Context for tests, activate usetesting for lint + add t.TempDir and t.Chdir [skip cascade] Reviewed-on: https://code.forgejo.org/forgejo/runner/pulls/844 Reviewed-by: Gusted Co-authored-by: Earl Warren Co-committed-by: Earl Warren --- .golangci.yml | 1 + act/common/executor_test.go | 6 +- act/common/git/git_test.go | 24 +++---- act/container/docker_images_test.go | 5 +- act/container/docker_pull_test.go | 5 +- act/container/docker_run_test.go | 16 ++--- act/container/host_environment_test.go | 17 ++--- ...x_container_environment_extensions_test.go | 9 +-- act/filecollector/file_collector_test.go | 5 +- act/model/github_context_test.go | 6 +- act/runner/action_cache_test.go | 3 +- act/runner/action_test.go | 4 +- act/runner/command_test.go | 17 +++-- act/runner/expression_test.go | 17 +++-- act/runner/job_executor_test.go | 4 +- act/runner/run_context_test.go | 64 +++++++++---------- act/runner/runner_test.go | 26 ++++---- act/runner/step_action_local_test.go | 4 +- act/runner/step_action_remote_test.go | 8 +-- act/runner/step_docker_test.go | 4 +- act/runner/step_run_test.go | 4 +- act/runner/step_test.go | 30 ++++----- 22 files changed, 126 insertions(+), 153 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 2ccb77a5..e3dee875 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -16,6 +16,7 @@ linters: - staticcheck - unconvert - unused + - usetesting - wastedassign settings: depguard: diff --git a/act/common/executor_test.go b/act/common/executor_test.go index e70c638e..75dca49f 100644 --- a/act/common/executor_test.go +++ b/act/common/executor_test.go @@ -12,7 +12,7 @@ import ( func TestNewWorkflow(t *testing.T) { assert := assert.New(t) - ctx := context.Background() + ctx := t.Context() // empty emptyWorkflow := NewPipelineExecutor() @@ -40,7 +40,7 @@ func TestNewWorkflow(t *testing.T) { func TestNewConditionalExecutor(t *testing.T) { assert := assert.New(t) - ctx := context.Background() + ctx := t.Context() trueCount := 0 falseCount := 0 @@ -77,7 +77,7 @@ func TestNewConditionalExecutor(t *testing.T) { func TestNewParallelExecutor(t *testing.T) { assert := assert.New(t) - ctx := context.Background() + ctx := t.Context() count := 0 activeCount := 0 diff --git a/act/common/git/git_test.go b/act/common/git/git_test.go index f03720e9..640c033f 100644 --- a/act/common/git/git_test.go +++ b/act/common/git/git_test.go @@ -1,7 +1,6 @@ package git import ( - "context" "fmt" "os" "os/exec" @@ -54,13 +53,6 @@ func TestFindGitSlug(t *testing.T) { } } -func testDir(t *testing.T) string { - basedir, err := os.MkdirTemp("", "act-test") - require.NoError(t, err) - t.Cleanup(func() { _ = os.RemoveAll(basedir) }) - return basedir -} - func cleanGitHooks(dir string) error { hooksDir := filepath.Join(dir, ".git", "hooks") files, err := os.ReadDir(hooksDir) @@ -85,7 +77,7 @@ func cleanGitHooks(dir string) error { func TestFindGitRemoteURL(t *testing.T) { assert := assert.New(t) - basedir := testDir(t) + basedir := t.TempDir() gitConfig() err := gitCmd("init", basedir) assert.NoError(err) @@ -96,20 +88,20 @@ func TestFindGitRemoteURL(t *testing.T) { err = gitCmd("-C", basedir, "remote", "add", "origin", remoteURL) assert.NoError(err) - u, err := findGitRemoteURL(context.Background(), basedir, "origin") + u, err := findGitRemoteURL(t.Context(), basedir, "origin") assert.NoError(err) assert.Equal(remoteURL, u) remoteURL = "git@github.com/AwesomeOwner/MyAwesomeRepo.git" err = gitCmd("-C", basedir, "remote", "add", "upstream", remoteURL) assert.NoError(err) - u, err = findGitRemoteURL(context.Background(), basedir, "upstream") + u, err = findGitRemoteURL(t.Context(), basedir, "upstream") assert.NoError(err) assert.Equal(remoteURL, u) } func TestGitFindRef(t *testing.T) { - basedir := testDir(t) + basedir := t.TempDir() gitConfig() for name, tt := range map[string]struct { @@ -184,7 +176,7 @@ func TestGitFindRef(t *testing.T) { require.NoError(t, gitCmd("-C", dir, "config", "user.email", "user@example.com")) require.NoError(t, cleanGitHooks(dir)) tt.Prepare(t, dir) - ref, err := FindGitRef(context.Background(), dir) + ref, err := FindGitRef(t.Context(), dir) tt.Assert(t, ref, err) }) } @@ -220,10 +212,10 @@ func TestGitCloneExecutor(t *testing.T) { clone := NewGitCloneExecutor(NewGitCloneExecutorInput{ URL: tt.URL, Ref: tt.Ref, - Dir: testDir(t), + Dir: t.TempDir(), }) - err := clone(context.Background()) + err := clone(t.Context()) if tt.Err != nil { assert.Error(t, err) assert.Equal(t, tt.Err, err) @@ -263,7 +255,7 @@ func gitCmd(args ...string) error { func TestCloneIfRequired(t *testing.T) { tempDir := t.TempDir() - ctx := context.Background() + ctx := t.Context() t.Run("clone", func(t *testing.T) { repo, err := CloneIfRequired(ctx, "refs/heads/main", NewGitCloneExecutorInput{ diff --git a/act/container/docker_images_test.go b/act/container/docker_images_test.go index 3344120d..a7b9babb 100644 --- a/act/container/docker_images_test.go +++ b/act/container/docker_images_test.go @@ -1,7 +1,6 @@ package container import ( - "context" "io" "testing" @@ -19,7 +18,7 @@ func TestImageExistsLocally(t *testing.T) { if testing.Short() { t.Skip("skipping integration test") } - ctx := context.Background() + ctx := t.Context() // to help make this test reliable and not flaky, we need to have // an image that will exist, and onew that won't exist @@ -36,7 +35,7 @@ func TestImageExistsLocally(t *testing.T) { // pull an image cli, err := client.NewClientWithOpts(client.FromEnv) assert.Nil(t, err) - cli.NegotiateAPIVersion(context.Background()) + cli.NegotiateAPIVersion(t.Context()) // Chose alpine latest because it's so small // maybe we should build an image instead so that tests aren't reliable on dockerhub diff --git a/act/container/docker_pull_test.go b/act/container/docker_pull_test.go index bfbe89dd..c0ff1d6f 100644 --- a/act/container/docker_pull_test.go +++ b/act/container/docker_pull_test.go @@ -1,7 +1,6 @@ package container import ( - "context" "testing" "github.com/docker/cli/cli/config" @@ -29,13 +28,13 @@ func TestCleanImage(t *testing.T) { } for _, table := range tables { - imageOut := cleanImage(context.Background(), table.imageIn) + imageOut := cleanImage(t.Context(), table.imageIn) assert.Equal(t, table.imageOut, imageOut) } } func TestGetImagePullOptions(t *testing.T) { - ctx := context.Background() + ctx := t.Context() config.SetDir("/non-existent/docker") diff --git a/act/container/docker_run_test.go b/act/container/docker_run_test.go index 91c579fe..1e93a9f2 100644 --- a/act/container/docker_run_test.go +++ b/act/container/docker_run_test.go @@ -26,7 +26,7 @@ func TestDocker(t *testing.T) { if testing.Short() { t.Skip("skipping integration test") } - ctx := context.Background() + ctx := t.Context() client, err := GetDockerClient(ctx) assert.NoError(t, err) defer client.Close() @@ -152,7 +152,7 @@ func TestDockerExecAbort(t *testing.T) { } func TestDockerExecFailure(t *testing.T) { - ctx := context.Background() + ctx := t.Context() conn := &mockConn{} @@ -183,7 +183,7 @@ func TestDockerExecFailure(t *testing.T) { } func TestDockerCopyTarStream(t *testing.T) { - ctx := context.Background() + ctx := t.Context() conn := &mockConn{} @@ -205,7 +205,7 @@ func TestDockerCopyTarStream(t *testing.T) { } func TestDockerCopyTarStreamErrorInCopyFiles(t *testing.T) { - ctx := context.Background() + ctx := t.Context() conn := &mockConn{} @@ -230,7 +230,7 @@ func TestDockerCopyTarStreamErrorInCopyFiles(t *testing.T) { } func TestDockerCopyTarStreamErrorInMkdir(t *testing.T) { - ctx := context.Background() + ctx := t.Context() conn := &mockConn{} @@ -318,7 +318,7 @@ func TestCheckVolumes(t *testing.T) { for _, tc := range testCases { t.Run(tc.desc, func(t *testing.T) { logger, _ := test.NewNullLogger() - ctx := common.WithLogger(context.Background(), logger) + ctx := common.WithLogger(t.Context(), logger) cr := &containerReference{ input: &NewContainerInput{ ValidVolumes: tc.validVolumes, @@ -379,7 +379,7 @@ func TestMergeJobOptions(t *testing.T) { JobOptions: testCase.options, }, } - config, hostConfig, err := cr.mergeJobOptions(context.Background(), &container.Config{}, &container.HostConfig{}) + config, hostConfig, err := cr.mergeJobOptions(t.Context(), &container.Config{}, &container.HostConfig{}) require.NoError(t, err) assert.EqualValues(t, testCase.config, config) assert.EqualValues(t, testCase.hostConfig, hostConfig) @@ -394,7 +394,7 @@ func TestDockerRun_isHealthy(t *testing.T) { NetworkAliases: []string{"servicename"}, }, } - ctx := context.Background() + ctx := t.Context() makeInspectResponse := func(interval time.Duration, status container.HealthStatus, test []string) container.InspectResponse { return container.InspectResponse{ Config: &container.Config{ diff --git a/act/container/host_environment_test.go b/act/container/host_environment_test.go index 85456288..6efb8560 100644 --- a/act/container/host_environment_test.go +++ b/act/container/host_environment_test.go @@ -2,7 +2,6 @@ package container import ( "archive/tar" - "context" "io" "os" "path" @@ -16,10 +15,8 @@ import ( var _ ExecutionsEnvironment = &HostEnvironment{} func TestCopyDir(t *testing.T) { - dir, err := os.MkdirTemp("", "test-host-env-*") - assert.NoError(t, err) - defer os.RemoveAll(dir) - ctx := context.Background() + dir := t.TempDir() + ctx := t.Context() e := &HostEnvironment{ Path: filepath.Join(dir, "path"), TmpDir: filepath.Join(dir, "tmp"), @@ -32,15 +29,13 @@ func TestCopyDir(t *testing.T) { _ = os.MkdirAll(e.TmpDir, 0o700) _ = os.MkdirAll(e.ToolCache, 0o700) _ = os.MkdirAll(e.ActPath, 0o700) - err = e.CopyDir(e.Workdir, e.Path, true)(ctx) + err := e.CopyDir(e.Workdir, e.Path, true)(ctx) assert.NoError(t, err) } func TestGetContainerArchive(t *testing.T) { - dir, err := os.MkdirTemp("", "test-host-env-*") - assert.NoError(t, err) - defer os.RemoveAll(dir) - ctx := context.Background() + dir := t.TempDir() + ctx := t.Context() e := &HostEnvironment{ Path: filepath.Join(dir, "path"), TmpDir: filepath.Join(dir, "tmp"), @@ -54,7 +49,7 @@ func TestGetContainerArchive(t *testing.T) { _ = os.MkdirAll(e.ToolCache, 0o700) _ = os.MkdirAll(e.ActPath, 0o700) expectedContent := []byte("sdde/7sh") - err = os.WriteFile(filepath.Join(e.Path, "action.yml"), expectedContent, 0o600) + err := os.WriteFile(filepath.Join(e.Path, "action.yml"), expectedContent, 0o600) assert.NoError(t, err) archive, err := e.GetContainerArchive(ctx, e.Path) assert.NoError(t, err) diff --git a/act/container/linux_container_environment_extensions_test.go b/act/container/linux_container_environment_extensions_test.go index 38111714..32034874 100644 --- a/act/container/linux_container_environment_extensions_test.go +++ b/act/container/linux_container_environment_extensions_test.go @@ -35,18 +35,13 @@ func TestContainerPath(t *testing.T) { {fmt.Sprintf("/mnt/%v/act", rootDriveLetter), "act", fmt.Sprintf("%s\\", rootDrive)}, } { if v.workDir != "" { - if err := os.Chdir(v.workDir); err != nil { - log.Error(err) - t.Fail() - } + t.Chdir(v.workDir) } assert.Equal(t, v.destinationPath, linuxcontainerext.ToContainerPath(v.sourcePath)) } - if err := os.Chdir(cwd); err != nil { - log.Error(err) - } + t.Chdir(cwd) } else { cwd, err := os.Getwd() if err != nil { diff --git a/act/filecollector/file_collector_test.go b/act/filecollector/file_collector_test.go index 45ec6594..ec5871e1 100644 --- a/act/filecollector/file_collector_test.go +++ b/act/filecollector/file_collector_test.go @@ -2,7 +2,6 @@ package filecollector import ( "archive/tar" - "context" "io" "path/filepath" "strings" @@ -104,7 +103,7 @@ func TestIgnoredTrackedfile(t *testing.T) { TarWriter: tw, }, } - err := fc.Fs.Walk("mygitrepo", fc.CollectFiles(context.Background(), []string{})) + err := fc.Fs.Walk("mygitrepo", fc.CollectFiles(t.Context(), []string{})) assert.NoError(t, err, "successfully collect files") tw.Close() _, _ = tmpTar.Seek(0, io.SeekStart) @@ -153,7 +152,7 @@ func TestSymlinks(t *testing.T) { TarWriter: tw, }, } - err = fc.Fs.Walk("mygitrepo", fc.CollectFiles(context.Background(), []string{})) + err = fc.Fs.Walk("mygitrepo", fc.CollectFiles(t.Context(), []string{})) assert.NoError(t, err, "successfully collect files") tw.Close() _, _ = tmpTar.Seek(0, io.SeekStart) diff --git a/act/model/github_context_test.go b/act/model/github_context_test.go index ed08e231..8e7ea487 100644 --- a/act/model/github_context_test.go +++ b/act/model/github_context_test.go @@ -99,7 +99,7 @@ func TestSetRef(t *testing.T) { Event: table.event, } - ghc.SetRef(context.Background(), "main", "/some/dir") + ghc.SetRef(t.Context(), "main", "/some/dir") ghc.SetRefTypeAndName() assert.Equal(t, table.ref, ghc.Ref) @@ -117,7 +117,7 @@ func TestSetRef(t *testing.T) { Event: map[string]interface{}{}, } - ghc.SetRef(context.Background(), "", "/some/dir") + ghc.SetRef(t.Context(), "", "/some/dir") assert.Equal(t, "refs/heads/master", ghc.Ref) }) @@ -204,7 +204,7 @@ func TestSetSha(t *testing.T) { Event: table.event, } - ghc.SetSha(context.Background(), "/some/dir") + ghc.SetSha(t.Context(), "/some/dir") assert.Equal(t, table.sha, ghc.Sha) }) diff --git a/act/runner/action_cache_test.go b/act/runner/action_cache_test.go index 286336e9..765eef0d 100644 --- a/act/runner/action_cache_test.go +++ b/act/runner/action_cache_test.go @@ -3,7 +3,6 @@ package runner import ( "archive/tar" "bytes" - "context" "io" "os" "testing" @@ -17,7 +16,7 @@ func TestActionCache(t *testing.T) { cache := &GoGitActionCache{ Path: os.TempDir(), } - ctx := context.Background() + ctx := t.Context() cacheDir := "nektos/act-test-actions" repo := "https://code.forgejo.org/forgejo/act-test-actions" refs := []struct { diff --git a/act/runner/action_test.go b/act/runner/action_test.go index a5d9e1d7..3e1bc27f 100644 --- a/act/runner/action_test.go +++ b/act/runner/action_test.go @@ -130,7 +130,7 @@ runs: closerMock.On("Close") } - action, err := readActionImpl(context.Background(), tt.step, "actionDir", "actionPath", readFile, writeFile) + action, err := readActionImpl(t.Context(), tt.step, "actionDir", "actionPath", readFile, writeFile) assert.Nil(t, err) assert.Equal(t, tt.expected, action) @@ -222,7 +222,7 @@ func TestActionRunner(t *testing.T) { for _, tt := range table { t.Run(tt.name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() cm := &containerMock{} cm.On("CopyDir", "/var/run/act/actions/dir/", "dir/", false).Return(func(ctx context.Context) error { return nil }) diff --git a/act/runner/command_test.go b/act/runner/command_test.go index b2c3824a..75149b11 100644 --- a/act/runner/command_test.go +++ b/act/runner/command_test.go @@ -2,7 +2,6 @@ package runner import ( "bytes" - "context" "io" "os" "testing" @@ -16,7 +15,7 @@ import ( func TestCommandSetEnv(t *testing.T) { a := assert.New(t) - ctx := context.Background() + ctx := t.Context() rc := new(RunContext) handler := rc.commandHandler(ctx) @@ -26,7 +25,7 @@ func TestCommandSetEnv(t *testing.T) { func TestCommandSetOutput(t *testing.T) { a := assert.New(t) - ctx := context.Background() + ctx := t.Context() rc := new(RunContext) rc.StepResults = make(map[string]*model.StepResult) handler := rc.commandHandler(ctx) @@ -56,7 +55,7 @@ func TestCommandSetOutput(t *testing.T) { func TestCommandAddpath(t *testing.T) { a := assert.New(t) - ctx := context.Background() + ctx := t.Context() rc := new(RunContext) handler := rc.commandHandler(ctx) @@ -71,7 +70,7 @@ func TestCommandStopCommands(t *testing.T) { logger, hook := test.NewNullLogger() a := assert.New(t) - ctx := common.WithLogger(context.Background(), logger) + ctx := common.WithLogger(t.Context(), logger) rc := new(RunContext) handler := rc.commandHandler(ctx) @@ -94,7 +93,7 @@ func TestCommandStopCommands(t *testing.T) { func TestCommandAddpathADO(t *testing.T) { a := assert.New(t) - ctx := context.Background() + ctx := t.Context() rc := new(RunContext) handler := rc.commandHandler(ctx) @@ -109,7 +108,7 @@ func TestCommandAddmask(t *testing.T) { logger, hook := test.NewNullLogger() a := assert.New(t) - ctx := context.Background() + ctx := t.Context() loggerCtx := common.WithLogger(ctx, logger) rc := new(RunContext) @@ -163,7 +162,7 @@ func TestCommandAddmaskUsemask(t *testing.T) { } re := captureOutput(t, func() { - ctx := context.Background() + ctx := t.Context() ctx = WithJobLogger(ctx, "0", "testjob", config, &rc.Masks, map[string]interface{}{}) handler := rc.commandHandler(ctx) @@ -180,7 +179,7 @@ func TestCommandSaveState(t *testing.T) { StepResults: map[string]*model.StepResult{}, } - ctx := context.Background() + ctx := t.Context() handler := rc.commandHandler(ctx) handler("::save-state name=state-name::state-value\n") diff --git a/act/runner/expression_test.go b/act/runner/expression_test.go index 3bebc301..8beea50e 100644 --- a/act/runner/expression_test.go +++ b/act/runner/expression_test.go @@ -1,7 +1,6 @@ package runner import ( - "context" "testing" "code.forgejo.org/forgejo/runner/v9/act/exprparser" @@ -76,7 +75,7 @@ func createRunContext(t *testing.T) *RunContext { func TestExpressionEvaluateRunContext(t *testing.T) { rc := createRunContext(t) - ee := rc.NewExpressionEvaluator(context.Background()) + ee := rc.NewExpressionEvaluator(t.Context()) tables := []struct { in string @@ -137,7 +136,7 @@ func TestExpressionEvaluateRunContext(t *testing.T) { table := table t.Run(table.in, func(t *testing.T) { assertObject := assert.New(t) - out, err := ee.evaluate(context.Background(), table.in, exprparser.DefaultStatusCheckNone) + out, err := ee.evaluate(t.Context(), table.in, exprparser.DefaultStatusCheckNone) if table.errMesg == "" { assertObject.NoError(err, table.in) assertObject.Equal(table.out, out, table.in) @@ -155,7 +154,7 @@ func TestExpressionEvaluateStep(t *testing.T) { RunContext: rc, } - ee := rc.NewStepExpressionEvaluator(context.Background(), step) + ee := rc.NewStepExpressionEvaluator(t.Context(), step) tables := []struct { in string @@ -177,7 +176,7 @@ func TestExpressionEvaluateStep(t *testing.T) { table := table t.Run(table.in, func(t *testing.T) { assertObject := assert.New(t) - out, err := ee.evaluate(context.Background(), table.in, exprparser.DefaultStatusCheckNone) + out, err := ee.evaluate(t.Context(), table.in, exprparser.DefaultStatusCheckNone) if table.errMesg == "" { assertObject.NoError(err, table.in) assertObject.Equal(table.out, out, table.in) @@ -217,7 +216,7 @@ func TestExpressionInterpolate(t *testing.T) { }, }, } - ee := rc.NewExpressionEvaluator(context.Background()) + ee := rc.NewExpressionEvaluator(t.Context()) tables := []struct { in string out string @@ -260,7 +259,7 @@ func TestExpressionInterpolate(t *testing.T) { table := table t.Run("interpolate", func(t *testing.T) { assertObject := assert.New(t) - out := ee.Interpolate(context.Background(), table.in) + out := ee.Interpolate(t.Context(), table.in) assertObject.Equal(table.out, out, table.in) }) } @@ -287,7 +286,7 @@ func TestExpressionRewriteSubExpression(t *testing.T) { for _, table := range table { t.Run("TestRewriteSubExpression", func(t *testing.T) { assertObject := assert.New(t) - out, err := rewriteSubExpression(context.Background(), table.in, false) + out, err := rewriteSubExpression(t.Context(), table.in, false) if err != nil { t.Fatal(err) } @@ -311,7 +310,7 @@ func TestExpressionRewriteSubExpressionForceFormat(t *testing.T) { for _, table := range table { t.Run("TestRewriteSubExpressionForceFormat", func(t *testing.T) { assertObject := assert.New(t) - out, err := rewriteSubExpression(context.Background(), table.in, true) + out, err := rewriteSubExpression(t.Context(), table.in, true) if err != nil { t.Fatal(err) } diff --git a/act/runner/job_executor_test.go b/act/runner/job_executor_test.go index f5c6e110..5e113d83 100644 --- a/act/runner/job_executor_test.go +++ b/act/runner/job_executor_test.go @@ -26,7 +26,7 @@ func TestJobExecutor(t *testing.T) { {workdir, "job-nil-step", "push", "invalid Step 0: missing run or uses key", platforms, secrets}, } // These tests are sufficient to only check syntax. - ctx := common.WithDryrun(context.Background(), true) + ctx := common.WithDryrun(t.Context(), true) for _, table := range tables { t.Run(table.workflowPath, func(t *testing.T) { table.runTest(ctx, t, &Config{}) @@ -244,7 +244,7 @@ func TestJobExecutorNewJobExecutor(t *testing.T) { t.Run(tt.name, func(t *testing.T) { fmt.Printf("::group::%s\n", tt.name) - ctx := common.WithJobErrorContainer(context.Background()) + ctx := common.WithJobErrorContainer(t.Context()) jim := &jobInfoMock{} sfm := &stepFactoryMock{} rc := &RunContext{ diff --git a/act/runner/run_context_test.go b/act/runner/run_context_test.go index 0fa41307..52dc86f8 100644 --- a/act/runner/run_context_test.go +++ b/act/runner/run_context_test.go @@ -69,7 +69,7 @@ func TestRunContext_EvalBool(t *testing.T) { }, }, } - rc.ExprEval = rc.NewExpressionEvaluator(context.Background()) + rc.ExprEval = rc.NewExpressionEvaluator(t.Context()) tables := []struct { in string @@ -163,7 +163,7 @@ func TestRunContext_EvalBool(t *testing.T) { table := table t.Run(table.in, func(t *testing.T) { assertObject := assert.New(t) - b, err := EvalBool(context.Background(), rc.ExprEval, table.in, exprparser.DefaultStatusCheckSuccess) + b, err := EvalBool(t.Context(), rc.ExprEval, table.in, exprparser.DefaultStatusCheckSuccess) if table.wantErr { assertObject.Error(err) } @@ -312,7 +312,7 @@ func TestRunContext_GetGitHubContext(t *testing.T) { } rc.Run.JobID = "job1" - ghc := rc.getGithubContext(context.Background()) + ghc := rc.getGithubContext(t.Context()) log.Debugf("%v", ghc) @@ -378,7 +378,7 @@ func TestRunContext_GetGithubContextRef(t *testing.T) { }, } - ghc := rc.getGithubContext(context.Background()) + ghc := rc.getGithubContext(t.Context()) assert.Equal(t, data.ref, ghc.Ref) }) @@ -423,44 +423,44 @@ func TestRunContext_RunsOnPlatformNames(t *testing.T) { rc := createIfTestRunContext(map[string]*model.Job{ "job1": createJob(t, `runs-on: ubuntu-latest`, ""), }) - assertObject.Equal([]string{"ubuntu-latest"}, rc.runsOnPlatformNames(context.Background())) + assertObject.Equal([]string{"ubuntu-latest"}, rc.runsOnPlatformNames(t.Context())) rc = createIfTestRunContext(map[string]*model.Job{ "job1": createJob(t, `runs-on: ${{ 'ubuntu-latest' }}`, ""), }) - assertObject.Equal([]string{"ubuntu-latest"}, rc.runsOnPlatformNames(context.Background())) + assertObject.Equal([]string{"ubuntu-latest"}, rc.runsOnPlatformNames(t.Context())) rc = createIfTestRunContext(map[string]*model.Job{ "job1": createJob(t, `runs-on: [self-hosted, my-runner]`, ""), }) - assertObject.Equal([]string{"self-hosted", "my-runner"}, rc.runsOnPlatformNames(context.Background())) + assertObject.Equal([]string{"self-hosted", "my-runner"}, rc.runsOnPlatformNames(t.Context())) rc = createIfTestRunContext(map[string]*model.Job{ "job1": createJob(t, `runs-on: [self-hosted, "${{ 'my-runner' }}"]`, ""), }) - assertObject.Equal([]string{"self-hosted", "my-runner"}, rc.runsOnPlatformNames(context.Background())) + assertObject.Equal([]string{"self-hosted", "my-runner"}, rc.runsOnPlatformNames(t.Context())) rc = createIfTestRunContext(map[string]*model.Job{ "job1": createJob(t, `runs-on: ${{ fromJSON('["ubuntu-latest"]') }}`, ""), }) - assertObject.Equal([]string{"ubuntu-latest"}, rc.runsOnPlatformNames(context.Background())) + assertObject.Equal([]string{"ubuntu-latest"}, rc.runsOnPlatformNames(t.Context())) // test missing / invalid runs-on rc = createIfTestRunContext(map[string]*model.Job{ "job1": createJob(t, `name: something`, ""), }) - assertObject.Equal([]string{}, rc.runsOnPlatformNames(context.Background())) + assertObject.Equal([]string{}, rc.runsOnPlatformNames(t.Context())) rc = createIfTestRunContext(map[string]*model.Job{ "job1": createJob(t, `runs-on: mapping: value`, ""), }) - assertObject.Equal([]string{}, rc.runsOnPlatformNames(context.Background())) + assertObject.Equal([]string{}, rc.runsOnPlatformNames(t.Context())) rc = createIfTestRunContext(map[string]*model.Job{ "job1": createJob(t, `runs-on: ${{ invalid expression }}`, ""), }) - assertObject.Equal([]string{}, rc.runsOnPlatformNames(context.Background())) + assertObject.Equal([]string{}, rc.runsOnPlatformNames(t.Context())) } func TestRunContext_IsEnabled(t *testing.T) { @@ -472,7 +472,7 @@ func TestRunContext_IsEnabled(t *testing.T) { "job1": createJob(t, `runs-on: ubuntu-latest if: success()`, ""), }) - assertObject.True(rc.isEnabled(context.Background())) + assertObject.True(rc.isEnabled(t.Context())) rc = createIfTestRunContext(map[string]*model.Job{ "job1": createJob(t, `runs-on: ubuntu-latest`, "failure"), @@ -481,7 +481,7 @@ needs: [job1] if: success()`, ""), }) rc.Run.JobID = "job2" - assertObject.False(rc.isEnabled(context.Background())) + assertObject.False(rc.isEnabled(t.Context())) rc = createIfTestRunContext(map[string]*model.Job{ "job1": createJob(t, `runs-on: ubuntu-latest`, "success"), @@ -490,7 +490,7 @@ needs: [job1] if: success()`, ""), }) rc.Run.JobID = "job2" - assertObject.True(rc.isEnabled(context.Background())) + assertObject.True(rc.isEnabled(t.Context())) rc = createIfTestRunContext(map[string]*model.Job{ "job1": createJob(t, `runs-on: ubuntu-latest`, "failure"), @@ -498,14 +498,14 @@ if: success()`, ""), if: success()`, ""), }) rc.Run.JobID = "job2" - assertObject.True(rc.isEnabled(context.Background())) + assertObject.True(rc.isEnabled(t.Context())) // failure() rc = createIfTestRunContext(map[string]*model.Job{ "job1": createJob(t, `runs-on: ubuntu-latest if: failure()`, ""), }) - assertObject.False(rc.isEnabled(context.Background())) + assertObject.False(rc.isEnabled(t.Context())) rc = createIfTestRunContext(map[string]*model.Job{ "job1": createJob(t, `runs-on: ubuntu-latest`, "failure"), @@ -514,7 +514,7 @@ needs: [job1] if: failure()`, ""), }) rc.Run.JobID = "job2" - assertObject.True(rc.isEnabled(context.Background())) + assertObject.True(rc.isEnabled(t.Context())) rc = createIfTestRunContext(map[string]*model.Job{ "job1": createJob(t, `runs-on: ubuntu-latest`, "success"), @@ -523,7 +523,7 @@ needs: [job1] if: failure()`, ""), }) rc.Run.JobID = "job2" - assertObject.False(rc.isEnabled(context.Background())) + assertObject.False(rc.isEnabled(t.Context())) rc = createIfTestRunContext(map[string]*model.Job{ "job1": createJob(t, `runs-on: ubuntu-latest`, "failure"), @@ -531,14 +531,14 @@ if: failure()`, ""), if: failure()`, ""), }) rc.Run.JobID = "job2" - assertObject.False(rc.isEnabled(context.Background())) + assertObject.False(rc.isEnabled(t.Context())) // always() rc = createIfTestRunContext(map[string]*model.Job{ "job1": createJob(t, `runs-on: ubuntu-latest if: always()`, ""), }) - assertObject.True(rc.isEnabled(context.Background())) + assertObject.True(rc.isEnabled(t.Context())) rc = createIfTestRunContext(map[string]*model.Job{ "job1": createJob(t, `runs-on: ubuntu-latest`, "failure"), @@ -547,7 +547,7 @@ needs: [job1] if: always()`, ""), }) rc.Run.JobID = "job2" - assertObject.True(rc.isEnabled(context.Background())) + assertObject.True(rc.isEnabled(t.Context())) rc = createIfTestRunContext(map[string]*model.Job{ "job1": createJob(t, `runs-on: ubuntu-latest`, "success"), @@ -556,7 +556,7 @@ needs: [job1] if: always()`, ""), }) rc.Run.JobID = "job2" - assertObject.True(rc.isEnabled(context.Background())) + assertObject.True(rc.isEnabled(t.Context())) rc = createIfTestRunContext(map[string]*model.Job{ "job1": createJob(t, `runs-on: ubuntu-latest`, "success"), @@ -564,18 +564,18 @@ if: always()`, ""), if: always()`, ""), }) rc.Run.JobID = "job2" - assertObject.True(rc.isEnabled(context.Background())) + assertObject.True(rc.isEnabled(t.Context())) rc = createIfTestRunContext(map[string]*model.Job{ "job1": createJob(t, `uses: ./.github/workflows/reusable.yml`, ""), }) - assertObject.True(rc.isEnabled(context.Background())) + assertObject.True(rc.isEnabled(t.Context())) rc = createIfTestRunContext(map[string]*model.Job{ "job1": createJob(t, `uses: ./.github/workflows/reusable.yml if: false`, ""), }) - assertObject.False(rc.isEnabled(context.Background())) + assertObject.False(rc.isEnabled(t.Context())) } func TestRunContext_GetEnv(t *testing.T) { @@ -652,10 +652,10 @@ func TestRunContext_CreateSimpleContainerName(t *testing.T) { func TestRunContext_SanitizeNetworkAlias(t *testing.T) { same := "same" - assert.Equal(t, same, sanitizeNetworkAlias(context.Background(), same)) + assert.Equal(t, same, sanitizeNetworkAlias(t.Context(), same)) original := "or.igin'A-L" sanitized := "or_igin_a-l" - assert.Equal(t, sanitized, sanitizeNetworkAlias(context.Background(), original)) + assert.Equal(t, sanitized, sanitizeNetworkAlias(t.Context(), original)) } func TestRunContext_PrepareJobContainer(t *testing.T) { @@ -815,7 +815,7 @@ jobs: return newContainer(input) })() - ctx := context.Background() + ctx := t.Context() rc := testCase.step.getRunContext() rc.ExprEval = rc.NewExpressionEvaluator(ctx) @@ -842,7 +842,7 @@ func (o *waitForServiceContainerMock) IsHealthy(ctx context.Context) (time.Durat func Test_waitForServiceContainer(t *testing.T) { t.Run("Wait", func(t *testing.T) { m := &waitForServiceContainerMock{} - ctx := context.Background() + ctx := t.Context() mock.InOrder( m.On("IsHealthy", ctx).Return(1*time.Millisecond, nil).Once(), m.On("IsHealthy", ctx).Return(time.Duration(0), nil).Once(), @@ -853,7 +853,7 @@ func Test_waitForServiceContainer(t *testing.T) { t.Run("Cancel", func(t *testing.T) { m := &waitForServiceContainerMock{} - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) cancel() m.On("IsHealthy", ctx).Return(1*time.Millisecond, nil).Once() require.NoError(t, waitForServiceContainer(ctx, m)) @@ -862,7 +862,7 @@ func Test_waitForServiceContainer(t *testing.T) { t.Run("Error", func(t *testing.T) { m := &waitForServiceContainerMock{} - ctx := context.Background() + ctx := t.Context() m.On("IsHealthy", ctx).Return(time.Duration(0), errors.New("ERROR")) require.ErrorContains(t, waitForServiceContainer(ctx, m), "ERROR") m.AssertExpectations(t) diff --git a/act/runner/runner_test.go b/act/runner/runner_test.go index f930d68d..3811811b 100644 --- a/act/runner/runner_test.go +++ b/act/runner/runner_test.go @@ -229,8 +229,7 @@ func TestRunner_RunEvent(t *testing.T) { t.Skip("skipping integration test") } - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() tables := []TestJobFileInfo{ // Shells @@ -370,8 +369,7 @@ func TestRunner_DryrunEvent(t *testing.T) { t.Skip("skipping integration test") } - ctx, cancel := context.WithCancel(common.WithDryrun(context.Background(), true)) - defer cancel() + ctx := common.WithDryrun(t.Context(), true) tables := []TestJobFileInfo{ // Shells @@ -400,8 +398,7 @@ func TestRunner_DockerActionForcePullForceRebuild(t *testing.T) { t.Skip("skipping integration test") } - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() config := &Config{ ForcePull: true, @@ -434,7 +431,7 @@ func TestRunner_RunDifferentArchitecture(t *testing.T) { platforms: platforms, } - tjfi.runTest(context.Background(), t, &Config{ContainerArchitecture: "linux/arm64"}) + tjfi.runTest(t.Context(), t, &Config{ContainerArchitecture: "linux/arm64"}) } type runSkippedHook struct { @@ -469,7 +466,7 @@ func TestRunner_RunSkipped(t *testing.T) { } h := &runSkippedHook{resultKey: what + "Result"} - ctx := common.WithLoggerHook(context.Background(), h) + ctx := common.WithLoggerHook(t.Context(), h) jobLoggerLevel := log.InfoLevel tjfi.runTest(ctx, t, &Config{ContainerArchitecture: "linux/arm64", JobLoggerLevel: &jobLoggerLevel}) @@ -514,7 +511,7 @@ func TestRunner_MaskValues(t *testing.T) { } logger := &maskJobLoggerFactory{} - tjfi.runTest(WithJobLoggerFactory(common.WithLogger(context.Background(), logger.WithJobLogger()), logger), t, &Config{}) + tjfi.runTest(WithJobLoggerFactory(common.WithLogger(t.Context(), logger.WithJobLogger()), logger), t, &Config{}) output := logger.Output.String() assertNoSecret(output, "secret value") @@ -540,7 +537,7 @@ func TestRunner_RunEventSecrets(t *testing.T) { secrets, _ := godotenv.Read(filepath.Join(workdir, workflowPath, ".secrets")) assert.NoError(t, err, "Failed to read .secrets") - tjfi.runTest(context.Background(), t, &Config{Secrets: secrets, Env: env}) + tjfi.runTest(t.Context(), t, &Config{Secrets: secrets, Env: env}) } func TestRunner_RunWithService(t *testing.T) { @@ -549,8 +546,7 @@ func TestRunner_RunWithService(t *testing.T) { } log.SetLevel(log.DebugLevel) - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() platforms := map[string]string{ "ubuntu-latest": "code.forgejo.org/oci/node:22", @@ -599,7 +595,7 @@ func TestRunner_RunActionInputs(t *testing.T) { "SOME_INPUT": "input", } - tjfi.runTest(context.Background(), t, &Config{Inputs: inputs}) + tjfi.runTest(t.Context(), t, &Config{Inputs: inputs}) } func TestRunner_RunEventPullRequest(t *testing.T) { @@ -617,7 +613,7 @@ func TestRunner_RunEventPullRequest(t *testing.T) { platforms: platforms, } - tjfi.runTest(context.Background(), t, &Config{EventPath: filepath.Join(workdir, workflowPath, "event.json")}) + tjfi.runTest(t.Context(), t, &Config{EventPath: filepath.Join(workdir, workflowPath, "event.json")}) } func TestRunner_RunMatrixWithUserDefinedInclusions(t *testing.T) { @@ -644,5 +640,5 @@ func TestRunner_RunMatrixWithUserDefinedInclusions(t *testing.T) { }, } - tjfi.runTest(context.Background(), t, &Config{Matrix: matrix}) + tjfi.runTest(t.Context(), t, &Config{Matrix: matrix}) } diff --git a/act/runner/step_action_local_test.go b/act/runner/step_action_local_test.go index 3af17d96..8bc5d50b 100644 --- a/act/runner/step_action_local_test.go +++ b/act/runner/step_action_local_test.go @@ -30,7 +30,7 @@ func (salm *stepActionLocalMocks) readAction(_ context.Context, step *model.Step } func TestStepActionLocalTest(t *testing.T) { - ctx := context.Background() + ctx := t.Context() cm := &containerMock{} salm := &stepActionLocalMocks{} @@ -231,7 +231,7 @@ func TestStepActionLocalPost(t *testing.T) { for _, tt := range table { t.Run(tt.name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() cm := &containerMock{} diff --git a/act/runner/step_action_remote_test.go b/act/runner/step_action_remote_test.go index 630c84b2..5287f380 100644 --- a/act/runner/step_action_remote_test.go +++ b/act/runner/step_action_remote_test.go @@ -118,7 +118,7 @@ func TestStepActionRemoteOK(t *testing.T) { for _, tt := range table { t.Run(tt.name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() cm := &containerMock{} sarm := &stepActionRemoteMocks{} @@ -214,7 +214,7 @@ func TestStepActionRemotePre(t *testing.T) { for _, tt := range table { t.Run(tt.name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() clonedAction := false sarm := &stepActionRemoteMocks{} @@ -275,7 +275,7 @@ func TestStepActionRemotePreThroughAction(t *testing.T) { for _, tt := range table { t.Run(tt.name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() clonedAction := false sarm := &stepActionRemoteMocks{} @@ -463,7 +463,7 @@ func TestStepActionRemotePost(t *testing.T) { for _, tt := range table { t.Run(tt.name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() cm := &containerMock{} diff --git a/act/runner/step_docker_test.go b/act/runner/step_docker_test.go index 6b6c11db..c4f2b94f 100644 --- a/act/runner/step_docker_test.go +++ b/act/runner/step_docker_test.go @@ -27,7 +27,7 @@ func TestStepDockerMain(t *testing.T) { ContainerNewContainer = origContainerNewContainer })() - ctx := context.Background() + ctx := t.Context() sd := &stepDocker{ RunContext: &RunContext{ @@ -105,7 +105,7 @@ func TestStepDockerMain(t *testing.T) { } func TestStepDockerPrePost(t *testing.T) { - ctx := context.Background() + ctx := t.Context() sd := &stepDocker{} err := sd.pre()(ctx) diff --git a/act/runner/step_run_test.go b/act/runner/step_run_test.go index 10e8bd19..b49e2405 100644 --- a/act/runner/step_run_test.go +++ b/act/runner/step_run_test.go @@ -72,7 +72,7 @@ func TestStepRun(t *testing.T) { return nil }) - ctx := context.Background() + ctx := t.Context() cm.On("GetContainerArchive", ctx, "/var/run/act/workflow/SUMMARY.md").Return(io.NopCloser(&bytes.Buffer{}), nil) cm.On("GetContainerArchive", ctx, "/var/run/act/workflow/pathcmd.txt").Return(io.NopCloser(&bytes.Buffer{}), nil) @@ -84,7 +84,7 @@ func TestStepRun(t *testing.T) { } func TestStepRunPrePost(t *testing.T) { - ctx := context.Background() + ctx := t.Context() sr := &stepRun{} err := sr.pre()(ctx) diff --git a/act/runner/step_test.go b/act/runner/step_test.go index b7bb31dd..b69c08aa 100644 --- a/act/runner/step_test.go +++ b/act/runner/step_test.go @@ -146,51 +146,51 @@ func TestStep_IsStepEnabled(t *testing.T) { // success() step := createTestStep(t, "if: success()") - assertObject.True(isStepEnabled(context.Background(), step.getIfExpression(context.Background(), stepStageMain), step, stepStageMain)) + assertObject.True(isStepEnabled(t.Context(), step.getIfExpression(t.Context(), stepStageMain), step, stepStageMain)) step = createTestStep(t, "if: success()") step.getRunContext().StepResults["a"] = &model.StepResult{ Conclusion: model.StepStatusSuccess, } - assertObject.True(isStepEnabled(context.Background(), step.getStepModel().If.Value, step, stepStageMain)) + assertObject.True(isStepEnabled(t.Context(), step.getStepModel().If.Value, step, stepStageMain)) step = createTestStep(t, "if: success()") step.getRunContext().StepResults["a"] = &model.StepResult{ Conclusion: model.StepStatusFailure, } - assertObject.False(isStepEnabled(context.Background(), step.getStepModel().If.Value, step, stepStageMain)) + assertObject.False(isStepEnabled(t.Context(), step.getStepModel().If.Value, step, stepStageMain)) // failure() step = createTestStep(t, "if: failure()") - assertObject.False(isStepEnabled(context.Background(), step.getStepModel().If.Value, step, stepStageMain)) + assertObject.False(isStepEnabled(t.Context(), step.getStepModel().If.Value, step, stepStageMain)) step = createTestStep(t, "if: failure()") step.getRunContext().StepResults["a"] = &model.StepResult{ Conclusion: model.StepStatusSuccess, } - assertObject.False(isStepEnabled(context.Background(), step.getStepModel().If.Value, step, stepStageMain)) + assertObject.False(isStepEnabled(t.Context(), step.getStepModel().If.Value, step, stepStageMain)) step = createTestStep(t, "if: failure()") step.getRunContext().StepResults["a"] = &model.StepResult{ Conclusion: model.StepStatusFailure, } - assertObject.True(isStepEnabled(context.Background(), step.getStepModel().If.Value, step, stepStageMain)) + assertObject.True(isStepEnabled(t.Context(), step.getStepModel().If.Value, step, stepStageMain)) // always() step = createTestStep(t, "if: always()") - assertObject.True(isStepEnabled(context.Background(), step.getStepModel().If.Value, step, stepStageMain)) + assertObject.True(isStepEnabled(t.Context(), step.getStepModel().If.Value, step, stepStageMain)) step = createTestStep(t, "if: always()") step.getRunContext().StepResults["a"] = &model.StepResult{ Conclusion: model.StepStatusSuccess, } - assertObject.True(isStepEnabled(context.Background(), step.getStepModel().If.Value, step, stepStageMain)) + assertObject.True(isStepEnabled(t.Context(), step.getStepModel().If.Value, step, stepStageMain)) step = createTestStep(t, "if: always()") step.getRunContext().StepResults["a"] = &model.StepResult{ Conclusion: model.StepStatusFailure, } - assertObject.True(isStepEnabled(context.Background(), step.getStepModel().If.Value, step, stepStageMain)) + assertObject.True(isStepEnabled(t.Context(), step.getStepModel().If.Value, step, stepStageMain)) } func TestStep_IsContinueOnError(t *testing.T) { @@ -228,37 +228,37 @@ func TestStep_IsContinueOnError(t *testing.T) { // absent step := createTestStep(t, "name: test") - continueOnError, err := isContinueOnError(context.Background(), step.getStepModel().RawContinueOnError, step, stepStageMain) + continueOnError, err := isContinueOnError(t.Context(), step.getStepModel().RawContinueOnError, step, stepStageMain) assertObject.False(continueOnError) assertObject.Nil(err) // explicit true step = createTestStep(t, "continue-on-error: true") - continueOnError, err = isContinueOnError(context.Background(), step.getStepModel().RawContinueOnError, step, stepStageMain) + continueOnError, err = isContinueOnError(t.Context(), step.getStepModel().RawContinueOnError, step, stepStageMain) assertObject.True(continueOnError) assertObject.Nil(err) // explicit false step = createTestStep(t, "continue-on-error: false") - continueOnError, err = isContinueOnError(context.Background(), step.getStepModel().RawContinueOnError, step, stepStageMain) + continueOnError, err = isContinueOnError(t.Context(), step.getStepModel().RawContinueOnError, step, stepStageMain) assertObject.False(continueOnError) assertObject.Nil(err) // expression true step = createTestStep(t, "continue-on-error: ${{ 'test' == 'test' }}") - continueOnError, err = isContinueOnError(context.Background(), step.getStepModel().RawContinueOnError, step, stepStageMain) + continueOnError, err = isContinueOnError(t.Context(), step.getStepModel().RawContinueOnError, step, stepStageMain) assertObject.True(continueOnError) assertObject.Nil(err) // expression false step = createTestStep(t, "continue-on-error: ${{ 'test' != 'test' }}") - continueOnError, err = isContinueOnError(context.Background(), step.getStepModel().RawContinueOnError, step, stepStageMain) + continueOnError, err = isContinueOnError(t.Context(), step.getStepModel().RawContinueOnError, step, stepStageMain) assertObject.False(continueOnError) assertObject.Nil(err) // expression parse error step = createTestStep(t, "continue-on-error: ${{ 'test' != test }}") - continueOnError, err = isContinueOnError(context.Background(), step.getStepModel().RawContinueOnError, step, stepStageMain) + continueOnError, err = isContinueOnError(t.Context(), step.getStepModel().RawContinueOnError, step, stepStageMain) assertObject.False(continueOnError) assertObject.NotNil(err) }