From 47f940ac3decc9939ed9973097831294f244d362 Mon Sep 17 00:00:00 2001 From: Vincent Demeester Date: Mon, 10 Jun 2024 18:29:31 +0200 Subject: [PATCH] Update golangci-lint to 1.59.x and fix linting MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This mainly removing the need to copy variable in a for loop to capture rang as it is now "fixed" in go 1.22+. > The copy of the 'for' variable "td" can be deleted (Go 1.22+) (copyloopvar) This also fixes some fatcontext issues, for loop range, … Signed-off-by: Vincent Demeester --- .golangci.yml | 3 +- Makefile | 2 +- .../sidecarlogresults/sidecarlogresults.go | 11 +- pkg/apis/config/feature_flags_test.go | 2 +- pkg/apis/pipeline/v1/merge.go | 2 - pkg/apis/pipeline/v1/param_types_test.go | 3 - .../pipeline/v1/pipeline_validation_test.go | 547 ++++++++++-------- pkg/apis/pipeline/v1/taskrun_types_test.go | 8 +- pkg/apis/pipeline/v1beta1/merge.go | 2 - pkg/apis/pipeline/v1beta1/param_types_test.go | 3 - .../v1beta1/pipeline_validation_test.go | 7 +- pkg/apis/pipeline/v1beta1/task_conversion.go | 2 +- .../pipeline/v1beta1/taskrun_types_test.go | 2 +- pkg/entrypoint/entrypointer_test.go | 265 ++++----- pkg/pipelinerunmetrics/metrics_test.go | 2 +- pkg/pod/entrypoint_lookup_impl_test.go | 8 +- pkg/pod/pod.go | 4 +- pkg/pod/script.go | 2 +- .../cloudevent/cloudeventsfakeclient.go | 2 +- pkg/reconciler/events/k8sevent/events.go | 2 +- pkg/reconciler/pipeline/dag/dag_test.go | 211 +++---- .../pipelinerun/affinity_assistant_test.go | 43 +- pkg/reconciler/pipelinerun/cancel_test.go | 60 +- .../pipelinerun/pipelinerun_test.go | 2 +- pkg/reconciler/pipelinerun/resources/apply.go | 19 +- .../pipelinerun/resources/apply_test.go | 3 - .../pipelinerun/resources/pipelineref_test.go | 5 - .../resources/pipelinerunresolution.go | 2 +- .../resources/pipelinerunresolution_test.go | 4 +- .../resources/resultrefresolution.go | 11 +- .../resources/validate_params_test.go | 2 - pkg/reconciler/pipelinerun/timeout_test.go | 1 - pkg/reconciler/taskrun/resources/apply.go | 7 +- .../taskrun/resources/taskref_test.go | 5 - pkg/reconciler/taskrun/taskrun_test.go | 2 +- pkg/taskrunmetrics/metrics.go | 22 +- pkg/taskrunmetrics/metrics_test.go | 2 +- test/cancel_test.go | 1 - test/duplicate_test.go | 2 +- test/larger_results_sidecar_logs_test.go | 1 - test/pipelinerun_test.go | 4 - test/propagated_params_test.go | 1 - test/propagated_results_test.go | 4 +- test/sidecar_test.go | 1 - test/stepaction_results_test.go | 1 - 45 files changed, 679 insertions(+), 616 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 360f12ddcb3..3dfaf597ef3 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -85,12 +85,13 @@ linters: - gocyclo - godot - godox - - goerr113 + - err113 - gofumpt - gomnd - gomoddirectives - ireturn - lll + - mnd - nestif - nlreturn - nonamedreturns diff --git a/Makefile b/Makefile index 09969e5e834..fd72b60b20d 100644 --- a/Makefile +++ b/Makefile @@ -9,7 +9,7 @@ TESTPKGS = $(shell env GO111MODULE=on $(GO) list -f \ BIN = $(CURDIR)/.bin WOKE ?= go run -modfile go.mod github.com/get-woke/woke -GOLANGCI_VERSION = v1.57.2 +GOLANGCI_VERSION = v1.59.1 WOKE_VERSION = v0.19.0 GO = go diff --git a/internal/sidecarlogresults/sidecarlogresults.go b/internal/sidecarlogresults/sidecarlogresults.go index 1b8516c3a7f..03b5d62fea1 100644 --- a/internal/sidecarlogresults/sidecarlogresults.go +++ b/internal/sidecarlogresults/sidecarlogresults.go @@ -37,8 +37,10 @@ import ( ) // ErrSizeExceeded indicates that the result exceeded its maximum allowed size -var ErrSizeExceeded = errors.New("results size exceeds configured limit") -var stepDir = pipeline.StepsDir +var ( + ErrSizeExceeded = errors.New("results size exceeds configured limit") + stepDir = pipeline.StepsDir +) type SidecarLogResultType string @@ -146,8 +148,6 @@ func LookForResults(w io.Writer, runDir string, resultsDir string, resultNames [ results := make(chan SidecarLogResult) g := new(errgroup.Group) for _, resultFile := range resultNames { - resultFile := resultFile - g.Go(func() error { newResult, err := readResults(resultsDir, resultFile, "", taskResultType) if err != nil { @@ -162,10 +162,7 @@ func LookForResults(w io.Writer, runDir string, resultsDir string, resultNames [ } for sName, sresults := range stepResults { - sresults := sresults - sName := sName for _, resultName := range sresults { - resultName := resultName stepResultsDir := filepath.Join(stepResultsDir, sName, "results") g.Go(func() error { diff --git a/pkg/apis/config/feature_flags_test.go b/pkg/apis/config/feature_flags_test.go index 176a7a5637d..b9e6a588348 100644 --- a/pkg/apis/config/feature_flags_test.go +++ b/pkg/apis/config/feature_flags_test.go @@ -410,7 +410,7 @@ func TestIsSpireEnabled(t *testing.T) { Data: tc.configmap, } store.OnConfigChanged(featureflags) - ctx = store.ToContext(ctx) + ctx := store.ToContext(ctx) got := config.IsSpireEnabled(ctx) if tc.want != got { diff --git a/pkg/apis/pipeline/v1/merge.go b/pkg/apis/pipeline/v1/merge.go index 7c5273bb202..296eaf4b145 100644 --- a/pkg/apis/pipeline/v1/merge.go +++ b/pkg/apis/pipeline/v1/merge.go @@ -81,7 +81,6 @@ func MergeStepsWithSpecs(steps []Step, overrides []TaskRunStepSpec) ([]Step, err stepNameToOverride[o.Name] = o } for i, s := range steps { - s := s o, found := stepNameToOverride[s.Name] if !found { continue @@ -108,7 +107,6 @@ func MergeSidecarsWithSpecs(sidecars []Sidecar, overrides []TaskRunSidecarSpec) sidecarNameToOverride[o.Name] = o } for i, s := range sidecars { - s := s o, found := sidecarNameToOverride[s.Name] if !found { continue diff --git a/pkg/apis/pipeline/v1/param_types_test.go b/pkg/apis/pipeline/v1/param_types_test.go index ae7d779f437..b383d0e4c24 100644 --- a/pkg/apis/pipeline/v1/param_types_test.go +++ b/pkg/apis/pipeline/v1/param_types_test.go @@ -308,7 +308,6 @@ type ParamValuesHolder struct { AOrS v1.ParamValue `json:"val"` } -//nolint:musttag func TestParamValues_UnmarshalJSON(t *testing.T) { cases := []struct { input map[string]interface{} @@ -399,7 +398,6 @@ func TestParamValues_UnmarshalJSON_Directly(t *testing.T) { } } -//nolint:musttag func TestParamValues_UnmarshalJSON_Error(t *testing.T) { cases := []struct { desc string @@ -417,7 +415,6 @@ func TestParamValues_UnmarshalJSON_Error(t *testing.T) { } } -//nolint:musttag func TestParamValues_MarshalJSON(t *testing.T) { cases := []struct { input v1.ParamValue diff --git a/pkg/apis/pipeline/v1/pipeline_validation_test.go b/pkg/apis/pipeline/v1/pipeline_validation_test.go index 236283d2630..e2a67368e36 100644 --- a/pkg/apis/pipeline/v1/pipeline_validation_test.go +++ b/pkg/apis/pipeline/v1/pipeline_validation_test.go @@ -58,7 +58,8 @@ func TestPipeline_Validate_Success(t *testing.T) { p: &Pipeline{ ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, Spec: PipelineSpec{ - Tasks: []PipelineTask{{Name: "foo", + Tasks: []PipelineTask{{ + Name: "foo", TaskSpec: &EmbeddedTask{ TypeMeta: runtime.TypeMeta{ APIVersion: "example.dev/v0", @@ -66,7 +67,8 @@ func TestPipeline_Validate_Success(t *testing.T) { }, Spec: runtime.RawExtension{ Raw: []byte(`{"field1":123,"field2":"value"}`), - }}, + }, + }, }}, }, }, @@ -362,7 +364,8 @@ func TestPipeline_Validate_Failure(t *testing.T) { return cfgtesting.SetFeatureFlags(ctx, t, map[string]string{ "disable-inline-spec": "pipeline", - "enable-api-fields": "alpha"}) + "enable-api-fields": "alpha", + }) }, }, { name: "pipelineSpec when disable-inline-spec all", @@ -382,7 +385,8 @@ func TestPipeline_Validate_Failure(t *testing.T) { return cfgtesting.SetFeatureFlags(ctx, t, map[string]string{ "disable-inline-spec": "pipeline,taskrun,pipelinerun", - "enable-api-fields": "alpha"}) + "enable-api-fields": "alpha", + }) }, }, { name: "taskSpec when disable-inline-spec", @@ -1373,64 +1377,66 @@ func TestFinallyTaskResultsToPipelineResults_Success(t *testing.T) { name string p *Pipeline wc func(context.Context) context.Context - }{{ - name: "valid pipeline with pipeline results", - p: &Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: PipelineSpec{ - Results: []PipelineResult{{ - Name: "initialized", - Value: *NewStructuredValues("$(tasks.clone-app-repo.results.initialized)"), - }}, - Tasks: []PipelineTask{{ - Name: "clone-app-repo", - TaskSpec: &EmbeddedTask{TaskSpec: TaskSpec{ - Results: []TaskResult{{ - Name: "initialized", - Type: "string", - }}, - Steps: []Step{{ - Name: "foo", Image: "bar", + }{ + { + name: "valid pipeline with pipeline results", + p: &Pipeline{ + ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, + Spec: PipelineSpec{ + Results: []PipelineResult{{ + Name: "initialized", + Value: *NewStructuredValues("$(tasks.clone-app-repo.results.initialized)"), + }}, + Tasks: []PipelineTask{{ + Name: "clone-app-repo", + TaskSpec: &EmbeddedTask{TaskSpec: TaskSpec{ + Results: []TaskResult{{ + Name: "initialized", + Type: "string", + }}, + Steps: []Step{{ + Name: "foo", Image: "bar", + }}, }}, }}, - }}, + }, }, - }}, { - name: "referencing existent finally task result", - p: &Pipeline{ - ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, - Spec: PipelineSpec{ - Results: []PipelineResult{{ - Name: "initialized", - Value: *NewStructuredValues("$(finally.check-git-commit.results.init)"), - }}, - Tasks: []PipelineTask{{ - Name: "clone-app-repo", - TaskSpec: &EmbeddedTask{TaskSpec: TaskSpec{ - Results: []TaskResult{{ - Name: "current-date-unix-timestamp", - Type: "string", - }}, - Steps: []Step{{ - Name: "foo", Image: "bar", - }}, + }, { + name: "referencing existent finally task result", + p: &Pipeline{ + ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, + Spec: PipelineSpec{ + Results: []PipelineResult{{ + Name: "initialized", + Value: *NewStructuredValues("$(finally.check-git-commit.results.init)"), }}, - }}, - Finally: []PipelineTask{{ - Name: "check-git-commit", - TaskSpec: &EmbeddedTask{TaskSpec: TaskSpec{ - Results: []TaskResult{{ - Name: "init", - Type: "string", + Tasks: []PipelineTask{{ + Name: "clone-app-repo", + TaskSpec: &EmbeddedTask{TaskSpec: TaskSpec{ + Results: []TaskResult{{ + Name: "current-date-unix-timestamp", + Type: "string", + }}, + Steps: []Step{{ + Name: "foo", Image: "bar", + }}, }}, - Steps: []Step{{ - Name: "foo2", Image: "bar", + }}, + Finally: []PipelineTask{{ + Name: "check-git-commit", + TaskSpec: &EmbeddedTask{TaskSpec: TaskSpec{ + Results: []TaskResult{{ + Name: "init", + Type: "string", + }}, + Steps: []Step{{ + Name: "foo2", Image: "bar", + }}, }}, }}, - }}, + }, }, }, - }, } for _, tt := range tests { @@ -1674,7 +1680,8 @@ func TestValidatePipelineParameterVariables_Success(t *testing.T) { Matrix: &Matrix{ Params: Params{{ Name: "a-param", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"$(params.baz)", "and", "$(params.foo-is-baz)"}}, - }}}, + }}, + }, }}, }, { name: "valid star array parameter variables in matrix", @@ -1689,7 +1696,8 @@ func TestValidatePipelineParameterVariables_Success(t *testing.T) { Matrix: &Matrix{ Params: Params{{ Name: "a-param", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"$(params.baz[*])", "and", "$(params.foo-is-baz[*])"}}, - }}}, + }}, + }, }}, }, { name: "array param - using the whole variable as a param's value that is intended to be array type", @@ -1715,9 +1723,13 @@ func TestValidatePipelineParameterVariables_Success(t *testing.T) { Matrix: &Matrix{ Include: IncludeParamsList{{ Name: "build-1", - Params: Params{{ - Name: "a-param", Value: ParamValue{Type: ParamTypeString, StringVal: "$(params.baz)"}}, - }}}}, + Params: Params{ + { + Name: "a-param", Value: ParamValue{Type: ParamTypeString, StringVal: "$(params.baz)"}, + }, + }, + }}, + }, }}, }, { name: "object param - using single individual variable in string param", @@ -1809,7 +1821,8 @@ func TestValidatePipelineParameterVariables_Success(t *testing.T) { Matrix: &Matrix{ Params: Params{{ Name: "a-param", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"$(params.myObject.key1)", "and", "$(params.myObject.key2)"}}, - }}}, + }}, + }, }}, }, { name: "object param - using the whole variable as a param's value that is intended to be object type", @@ -1991,7 +2004,8 @@ func TestValidatePipelineDeclaredParameterUsage_Failure(t *testing.T) { Matrix: &Matrix{ Params: Params{{ Name: "a-param", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"$(params.does-not-exist)"}}, - }}}, + }}, + }, }}, expectedError: apis.FieldError{ Message: `non-existent variable in "$(params.does-not-exist)"`, @@ -2008,7 +2022,8 @@ func TestValidatePipelineDeclaredParameterUsage_Failure(t *testing.T) { Matrix: &Matrix{ Params: Params{{ Name: "a-param", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"$(params.foo)", "and", "$(params.does-not-exist)"}}, - }}}, + }}, + }, }}, expectedError: apis.FieldError{ Message: `non-existent variable in "$(params.does-not-exist)"`, @@ -2026,7 +2041,9 @@ func TestValidatePipelineDeclaredParameterUsage_Failure(t *testing.T) { Params: Params{{ Name: "a-param", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"$(params.foo)"}}, }, { - Name: "b-param", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"$(params.does-not-exist)"}}}}}, + Name: "b-param", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"$(params.does-not-exist)"}}, + }}, + }, }}, expectedError: apis.FieldError{ Message: `non-existent variable in "$(params.does-not-exist)"`, @@ -2047,7 +2064,8 @@ func TestValidatePipelineDeclaredParameterUsage_Failure(t *testing.T) { }, { Name: "b-param", Value: ParamValue{Type: ParamTypeString, StringVal: "$(params.does-not-exist)"}, }}, - }}}, + }}, + }, }}, expectedError: apis.FieldError{ Message: `non-existent variable in "$(params.does-not-exist)"`, @@ -2186,7 +2204,8 @@ func TestValidatePipelineDeclaredParameterUsage_Failure(t *testing.T) { Name: "a-param", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"$(params.myObject.key1)"}}, }, { Name: "b-param", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"$(params.myObject.non-exist-key)"}}, - }}}, + }}, + }, }}, expectedError: apis.FieldError{ Message: `non-existent variable in "$(params.myObject.non-exist-key)"`, @@ -3327,6 +3346,7 @@ func TestValidateFinalTasks_Failure(t *testing.T) { }) } } + func TestContextValid(t *testing.T) { tests := []struct { name string @@ -3342,7 +3362,8 @@ func TestContextValid(t *testing.T) { Matrix: &Matrix{ Params: Params{{ Name: "a-param-mat", Value: ParamValue{ArrayVal: []string{"$(context.pipeline.name)"}}, - }}}, + }}, + }, }}, }, { name: "valid string context variable for PipelineRun name", @@ -3355,7 +3376,8 @@ func TestContextValid(t *testing.T) { Matrix: &Matrix{ Params: Params{{ Name: "a-param-mat", Value: ParamValue{ArrayVal: []string{"$(context.pipelineRun.name)"}}, - }}}, + }}, + }, }}, }, { name: "valid string context variable for PipelineRun namespace", @@ -3368,7 +3390,8 @@ func TestContextValid(t *testing.T) { Matrix: &Matrix{ Params: Params{{ Name: "a-param-mat", Value: ParamValue{ArrayVal: []string{"$(context.pipelineRun.namespace)"}}, - }}}, + }}, + }, }}, }, { name: "valid string context variable for PipelineRun uid", @@ -3381,7 +3404,8 @@ func TestContextValid(t *testing.T) { Matrix: &Matrix{ Params: Params{{ Name: "a-param-mat", Value: ParamValue{ArrayVal: []string{"$(context.pipelineRun.uid)"}}, - }}}, + }}, + }, }}, }, { name: "valid array context variables for Pipeline and PipelineRun names", @@ -3394,7 +3418,8 @@ func TestContextValid(t *testing.T) { Matrix: &Matrix{ Params: Params{{ Name: "a-param-mat", Value: ParamValue{ArrayVal: []string{"$(context.pipeline.name)", "and", "$(context.pipelineRun.name)"}}, - }}}, + }}, + }, }}, }, { name: "valid string context variable for PipelineTask retries", @@ -3407,7 +3432,8 @@ func TestContextValid(t *testing.T) { Matrix: &Matrix{ Params: Params{{ Name: "a-param", Value: ParamValue{StringVal: "$(context.pipelineTask.retries)"}, - }}}, + }}, + }, }}, }, { name: "valid array context variable for PipelineTask retries", @@ -3420,7 +3446,8 @@ func TestContextValid(t *testing.T) { Matrix: &Matrix{ Params: Params{{ Name: "a-param-mat", Value: ParamValue{ArrayVal: []string{"$(context.pipelineTask.retries)"}}, - }}}, + }}, + }, }}, }, { name: "valid string context variable for Pipeline name in include params", @@ -3434,8 +3461,10 @@ func TestContextValid(t *testing.T) { Include: IncludeParamsList{{ Name: "build-1", Params: Params{{ - Name: "a-param-mat", Value: ParamValue{Type: ParamTypeString, StringVal: "$(context.pipeline.name)"}}}, - }}}, + Name: "a-param-mat", Value: ParamValue{Type: ParamTypeString, StringVal: "$(context.pipeline.name)"}, + }}, + }}, + }, }}, }, { name: "valid string context variable for PipelineTask retries in matrix include", @@ -3449,8 +3478,10 @@ func TestContextValid(t *testing.T) { Include: IncludeParamsList{{ Name: "build-1", Params: Params{{ - Name: "a-param-mat", Value: ParamValue{Type: ParamTypeString, StringVal: "$(context.pipelineTask.retries)"}}}, - }}}, + Name: "a-param-mat", Value: ParamValue{Type: ParamTypeString, StringVal: "$(context.pipelineTask.retries)"}, + }}, + }}, + }, }}, }} for _, tt := range tests { @@ -3478,7 +3509,8 @@ func TestContextInvalid(t *testing.T) { Matrix: &Matrix{ Params: Params{{ Name: "a-param-foo", Value: ParamValue{ArrayVal: []string{"$(context.pipeline.missing-foo)"}}, - }}}, + }}, + }, }}, expectedError: *apis.ErrGeneric("").Also(&apis.FieldError{ Message: `non-existent variable in "$(context.pipeline.missing)"`, @@ -3498,7 +3530,8 @@ func TestContextInvalid(t *testing.T) { Matrix: &Matrix{ Params: Params{{ Name: "a-param-foo", Value: ParamValue{ArrayVal: []string{"$(context.pipelineRun.missing-foo)"}}, - }}}, + }}, + }, }}, expectedError: *apis.ErrGeneric("").Also(&apis.FieldError{ Message: `non-existent variable in "$(context.pipelineRun.missing)"`, @@ -3518,7 +3551,8 @@ func TestContextInvalid(t *testing.T) { Matrix: &Matrix{ Params: Params{{ Name: "a-param-foo", Value: ParamValue{ArrayVal: []string{"$(context.pipelineTask.missing-foo)"}}, - }}}, + }}, + }, }}, expectedError: *apis.ErrGeneric("").Also(&apis.FieldError{ Message: `non-existent variable in "$(context.pipelineTask.missing)"`, @@ -3538,7 +3572,8 @@ func TestContextInvalid(t *testing.T) { Matrix: &Matrix{ Params: Params{{ Name: "a-param", Value: ParamValue{ArrayVal: []string{"$(context.pipeline.missing-foo)", "$(context.pipelineTask.missing-foo)", "$(context.pipelineRun.missing-foo)"}}, - }}}, + }}, + }, }}, expectedError: *apis.ErrGeneric(`non-existent variable in "$(context.pipeline.missing)"`, "value"). Also(apis.ErrGeneric(`non-existent variable in "$(context.pipelineRun.missing)"`, "value")). @@ -3555,8 +3590,10 @@ func TestContextInvalid(t *testing.T) { Include: IncludeParamsList{{ Name: "build-1", Params: Params{{ - Name: "a-param-foo", Value: ParamValue{Type: ParamTypeString, StringVal: "$(context.pipeline.missing)"}}}, - }}}, + Name: "a-param-foo", Value: ParamValue{Type: ParamTypeString, StringVal: "$(context.pipeline.missing)"}, + }}, + }}, + }, }}, expectedError: *apis.ErrGeneric("").Also(&apis.FieldError{ Message: `non-existent variable in "$(context.pipeline.missing)"`, @@ -3571,8 +3608,10 @@ func TestContextInvalid(t *testing.T) { Include: IncludeParamsList{{ Name: "build-1", Params: Params{{ - Name: "a-param-foo", Value: ParamValue{Type: ParamTypeString, StringVal: "$(context.pipelineRun.missing)"}}}, - }}}, + Name: "a-param-foo", Value: ParamValue{Type: ParamTypeString, StringVal: "$(context.pipelineRun.missing)"}, + }}, + }}, + }, }}, expectedError: *apis.ErrGeneric("").Also(&apis.FieldError{ Message: `non-existent variable in "$(context.pipelineRun.missing)"`, @@ -3587,8 +3626,10 @@ func TestContextInvalid(t *testing.T) { Include: IncludeParamsList{{ Name: "build-1", Params: Params{{ - Name: "a-param-foo", Value: ParamValue{Type: ParamTypeString, StringVal: "$(context.pipelineTask.missing)"}}}, - }}}, + Name: "a-param-foo", Value: ParamValue{Type: ParamTypeString, StringVal: "$(context.pipelineTask.missing)"}, + }}, + }}, + }, }}, expectedError: *apis.ErrGeneric("").Also(&apis.FieldError{ Message: `non-existent variable in "$(context.pipelineTask.missing)"`, @@ -3868,7 +3909,8 @@ func TestMatrixIncompatibleAPIVersions(t *testing.T) { Matrix: &Matrix{ Params: Params{{ Name: "a-param", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"foo", "bar"}}, - }}}, + }}, + }, } tests := []struct { name string @@ -3931,7 +3973,8 @@ func Test_validateMatrix(t *testing.T) { Matrix: &Matrix{ Params: Params{{ Name: "foobar", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"foo", "bar"}}, - }}}, + }}, + }, Params: Params{{ Name: "foobar", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"foo", "bar"}}, }}, @@ -3945,7 +3988,8 @@ func Test_validateMatrix(t *testing.T) { Matrix: &Matrix{ Params: Params{{ Name: "foobar", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"foo", "bar"}}, - }}}, + }}, + }, Params: Params{{ Name: "barfoo", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"bar", "foo"}}, }}, @@ -3958,14 +4002,16 @@ func Test_validateMatrix(t *testing.T) { Matrix: &Matrix{ Params: Params{{ Name: "a-param", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"$(tasks.foo-task.results.a-result)"}}, - }}}, + }}, + }, }, { Name: "b-task", TaskRef: &TaskRef{Name: "b-task"}, Matrix: &Matrix{ Params: Params{{ Name: "b-param", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"$(tasks.bar-task.results.b-result)"}}, - }}}, + }}, + }, }}, }, { name: "parameters in matrix contain whole array results references", @@ -3975,7 +4021,8 @@ func Test_validateMatrix(t *testing.T) { Matrix: &Matrix{ Params: Params{{ Name: "a-param", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"$(tasks.foo-task.results.a-task-results[*])"}}, - }}}, + }}, + }, }}, }, { name: "results from matrixed task consumed in tasks through parameters", @@ -3985,7 +4032,8 @@ func Test_validateMatrix(t *testing.T) { Matrix: &Matrix{ Params: Params{{ Name: "a-param", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"foo", "bar"}}, - }}}, + }}, + }, }, { Name: "b-task", TaskRef: &TaskRef{Name: "b-task"}, @@ -4001,7 +4049,8 @@ func Test_validateMatrix(t *testing.T) { Matrix: &Matrix{ Params: Params{{ Name: "a-param", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"foo", "bar"}}, - }}}, + }}, + }, }}, finally: PipelineTaskList{{ Name: "b-task", @@ -4018,7 +4067,8 @@ func Test_validateMatrix(t *testing.T) { Matrix: &Matrix{ Params: Params{{ Name: "a-param", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"foo", "bar"}}, - }}}, + }}, + }, }, { Name: "b-task", TaskRef: &TaskRef{Name: "b-task"}, @@ -4041,7 +4091,8 @@ func Test_validateMatrix(t *testing.T) { Matrix: &Matrix{ Params: Params{{ Name: "a-param", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"foo", "bar"}}, - }}}, + }}, + }, }, { Name: "b-task", TaskRef: &TaskRef{Name: "b-task"}, @@ -4059,7 +4110,8 @@ func Test_validateMatrix(t *testing.T) { Matrix: &Matrix{ Params: Params{{ Name: "a-param", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"foo", "bar"}}, - }}}, + }}, + }, }}, finally: PipelineTaskList{{ Name: "b-task", @@ -4078,7 +4130,8 @@ func Test_validateMatrix(t *testing.T) { Matrix: &Matrix{ Params: Params{{ Name: "a-param", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"foo", "bar"}}, - }}}, + }}, + }, }, { Name: "b-task", TaskRef: &TaskRef{Name: "b-task"}, @@ -4107,7 +4160,8 @@ func Test_validateMatrix(t *testing.T) { Name: "platform", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"linux", "mac"}}, }, { Name: "browser", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"chrome", "safari"}}, - }}}, + }}, + }, }, { Name: "echoarrayurl", TaskSpec: &EmbeddedTask{TaskSpec: TaskSpec{ @@ -4129,7 +4183,8 @@ func Test_validateMatrix(t *testing.T) { Params: ParamSpecs{{ Name: "platform", }, { - Name: "browser"}}, + Name: "browser", + }}, Results: []TaskResult{{ Name: "report-url", Type: ResultsTypeString, @@ -4138,7 +4193,8 @@ func Test_validateMatrix(t *testing.T) { Name: "produce-report-url", Image: "alpine", Script: ` | - echo -n "https://api.example/get-report/$(params.platform)-$(params.browser)" | tee $(results.report-url.path)`}}, + echo -n "https://api.example/get-report/$(params.platform)-$(params.browser)" | tee $(results.report-url.path)`, + }}, }}, }, { Name: "task-consuming-results", @@ -4172,7 +4228,8 @@ func Test_validateMatrix(t *testing.T) { Name: "platform", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"linux", "mac"}}, }, { Name: "browser", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"chrome", "safari"}}, - }}}, + }}, + }, }, { Name: "task-consuming-results", TaskSpec: &EmbeddedTask{TaskSpec: TaskSpec{ @@ -4202,14 +4259,16 @@ func Test_validateMatrix(t *testing.T) { Name: "platform", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"linux", "mac"}}, }, { Name: "browser", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"chrome", "safari"}}, - }}}, + }}, + }, }, { Name: "taskwithresult", TaskSpec: &EmbeddedTask{TaskSpec: TaskSpec{ Params: ParamSpecs{{ Name: "platform", }, { - Name: "browser"}}, + Name: "browser", + }}, Results: []TaskResult{{ Name: "report-url", Type: ResultsTypeString, @@ -4218,7 +4277,8 @@ func Test_validateMatrix(t *testing.T) { Name: "produce-report-url", Image: "alpine", Script: ` | - echo -n "https://api.example/get-report/$(params.platform)-$(params.browser)" | tee $(results.report-url.path)`}}, + echo -n "https://api.example/get-report/$(params.platform)-$(params.browser)" | tee $(results.report-url.path)`, + }}, }}, }, { Name: "task-consuming-results", @@ -4251,7 +4311,8 @@ func Test_validateMatrix(t *testing.T) { Params: ParamSpecs{{ Name: "platform", }, { - Name: "browser"}}, + Name: "browser", + }}, Results: []TaskResult{{ Name: "array-result", Type: ResultsTypeArray, @@ -4260,21 +4321,24 @@ func Test_validateMatrix(t *testing.T) { Name: "produce-array-result", Image: "alpine", Script: ` | - echo -n "[\"${params.platform}\",\"${params.browser}\"]" | tee $(results.array-result.path)`}}, + echo -n "[\"${params.platform}\",\"${params.browser}\"]" | tee $(results.array-result.path)`, + }}, }}, Matrix: &Matrix{ Params: Params{{ Name: "platform", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"linux", "mac"}}, }, { Name: "browser", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"chrome", "safari"}}, - }}}, + }}, + }, }, { Name: "taskwithresult", TaskSpec: &EmbeddedTask{TaskSpec: TaskSpec{ Params: ParamSpecs{{ Name: "platform", }, { - Name: "browser"}}, + Name: "browser", + }}, Results: []TaskResult{{ Name: "array-result", Type: ResultsTypeArray, @@ -4283,7 +4347,8 @@ func Test_validateMatrix(t *testing.T) { Name: "produce-array-result", Image: "alpine", Script: ` | - echo -n "https://api.example/get-report/$(params.platform)-$(params.browser)" | tee $(results.array-result.path)`}}, + echo -n "https://api.example/get-report/$(params.platform)-$(params.browser)" | tee $(results.array-result.path)`, + }}, }}, }, { Name: "task-consuming-results", @@ -4316,7 +4381,8 @@ func Test_validateMatrix(t *testing.T) { Params: ParamSpecs{{ Name: "platform", }, { - Name: "browser"}}, + Name: "browser", + }}, Results: []TaskResult{{ Name: "array-result", Type: ResultsTypeArray, @@ -4325,21 +4391,24 @@ func Test_validateMatrix(t *testing.T) { Name: "produce-array-result", Image: "alpine", Script: ` | - echo -n "[\"${params.platform}\",\"${params.browser}\"]" | tee $(results.array-result.path)`}}, + echo -n "[\"${params.platform}\",\"${params.browser}\"]" | tee $(results.array-result.path)`, + }}, }}, Matrix: &Matrix{ Params: Params{{ Name: "platform", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"linux", "mac"}}, }, { Name: "browser", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"chrome", "safari"}}, - }}}, + }}, + }, }, { Name: "task-consuming-results", TaskSpec: &EmbeddedTask{TaskSpec: TaskSpec{ Params: ParamSpecs{{ Name: "platform", }, { - Name: "browser"}}, + Name: "browser", + }}, Results: []TaskResult{{ Name: "report-url", Type: ResultsTypeString, @@ -4348,7 +4417,8 @@ func Test_validateMatrix(t *testing.T) { Name: "produce-report-url", Image: "alpine", Script: ` | - echo -n "https://api.example/get-report/$(params.platform)-$(params.browser)" | tee $(results.report-url.path)`}}, + echo -n "https://api.example/get-report/$(params.platform)-$(params.browser)" | tee $(results.report-url.path)`, + }}, }}, Params: Params{{ Name: "b-param", Value: ParamValue{Type: ParamTypeString, StringVal: "$(tasks.matrix-emitting-results-embedded.results.report-url[0])"}, @@ -4365,14 +4435,16 @@ func Test_validateMatrix(t *testing.T) { Name: "platform", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"linux", "mac"}}, }, { Name: "browser", Value: ParamValue{Type: ParamTypeArray, ArrayVal: []string{"chrome", "safari"}}, - }}}, + }}, + }, }, { Name: "taskwithresult", TaskSpec: &EmbeddedTask{TaskSpec: TaskSpec{ Params: ParamSpecs{{ Name: "platform", }, { - Name: "browser"}}, + Name: "browser", + }}, Results: []TaskResult{{ Name: "array-result", Type: ResultsTypeArray, @@ -4381,7 +4453,8 @@ func Test_validateMatrix(t *testing.T) { Name: "produce-array-result", Image: "alpine", Script: ` | - echo -n "[\"${params.platform}\",\"${params.browser}\"]" | tee $(results.array-result.path)`}}, + echo -n "[\"${params.platform}\",\"${params.browser}\"]" | tee $(results.array-result.path)`, + }}, }}, }, { Name: "task-consuming-results", @@ -4487,144 +4560,144 @@ func TestGetIndexingReferencesToArrayParams(t *testing.T) { name string spec PipelineSpec want sets.String - }{{ - name: "references in task params", - spec: PipelineSpec{ - Params: []ParamSpec{ - {Name: "first-param", Type: ParamTypeArray, Default: NewStructuredValues("default-value", "default-value-again")}, - {Name: "second-param", Type: ParamTypeString}, - }, - Tasks: []PipelineTask{{ - Params: Params{ - {Name: "first-task-first-param", Value: *NewStructuredValues("$(params.first-param[1])")}, - {Name: "first-task-second-param", Value: *NewStructuredValues("$(params.second-param[0])")}, - {Name: "first-task-third-param", Value: *NewStructuredValues("static value")}, + }{ + { + name: "references in task params", + spec: PipelineSpec{ + Params: []ParamSpec{ + {Name: "first-param", Type: ParamTypeArray, Default: NewStructuredValues("default-value", "default-value-again")}, + {Name: "second-param", Type: ParamTypeString}, }, - }}, - }, - want: sets.NewString("$(params.first-param[1])", "$(params.second-param[0])"), - }, { - name: "references in when expression", - spec: PipelineSpec{ - Params: []ParamSpec{ - {Name: "first-param", Type: ParamTypeArray, Default: NewStructuredValues("default-value", "default-value-again")}, - {Name: "second-param", Type: ParamTypeString}, - }, - Tasks: []PipelineTask{{ - When: []WhenExpression{{ - Input: "$(params.first-param[1])", - Operator: selection.In, - Values: []string{"$(params.second-param[0])"}, + Tasks: []PipelineTask{{ + Params: Params{ + {Name: "first-task-first-param", Value: *NewStructuredValues("$(params.first-param[1])")}, + {Name: "first-task-second-param", Value: *NewStructuredValues("$(params.second-param[0])")}, + {Name: "first-task-third-param", Value: *NewStructuredValues("static value")}, + }, }}, - }}, - }, - want: sets.NewString("$(params.first-param[1])", "$(params.second-param[0])"), - }, { - name: "nested references in task params", - spec: PipelineSpec{ - Params: []ParamSpec{ - {Name: "first-param", Type: ParamTypeArray, Default: NewStructuredValues("default-value", "default-value-again")}, - {Name: "second-param", Type: ParamTypeArray, Default: NewStructuredValues("default-value", "default-value-again")}, }, - Tasks: []PipelineTask{{ - Params: Params{ - {Name: "first-task-first-param", Value: *NewStructuredValues("$(input.workspace.$(params.first-param[0]))")}, - {Name: "first-task-second-param", Value: *NewStructuredValues("$(input.workspace.$(params.second-param[1]))")}, + want: sets.NewString("$(params.first-param[1])", "$(params.second-param[0])"), + }, { + name: "references in when expression", + spec: PipelineSpec{ + Params: []ParamSpec{ + {Name: "first-param", Type: ParamTypeArray, Default: NewStructuredValues("default-value", "default-value-again")}, + {Name: "second-param", Type: ParamTypeString}, }, - }}, - }, - want: sets.NewString("$(params.first-param[0])", "$(params.second-param[1])"), - }, { - name: "array parameter", - spec: PipelineSpec{ - Params: []ParamSpec{ - {Name: "first-param", Type: ParamTypeArray, Default: NewStructuredValues("default", "array", "value")}, - {Name: "second-param", Type: ParamTypeArray}, + Tasks: []PipelineTask{{ + When: []WhenExpression{{ + Input: "$(params.first-param[1])", + Operator: selection.In, + Values: []string{"$(params.second-param[0])"}, + }}, + }}, }, - Tasks: []PipelineTask{{ - Params: Params{ - {Name: "first-task-first-param", Value: *NewStructuredValues("firstelement", "$(params.first-param)")}, - {Name: "first-task-second-param", Value: *NewStructuredValues("firstelement", "$(params.second-param[0])")}, + want: sets.NewString("$(params.first-param[1])", "$(params.second-param[0])"), + }, { + name: "nested references in task params", + spec: PipelineSpec{ + Params: []ParamSpec{ + {Name: "first-param", Type: ParamTypeArray, Default: NewStructuredValues("default-value", "default-value-again")}, + {Name: "second-param", Type: ParamTypeArray, Default: NewStructuredValues("default-value", "default-value-again")}, }, - }}, - }, - want: sets.NewString("$(params.second-param[0])"), - }, { - name: "references in finally params", - spec: PipelineSpec{ - Params: []ParamSpec{ - {Name: "first-param", Type: ParamTypeArray, Default: NewStructuredValues("default-value", "default-value-again")}, - {Name: "second-param", Type: ParamTypeArray}, + Tasks: []PipelineTask{{ + Params: Params{ + {Name: "first-task-first-param", Value: *NewStructuredValues("$(input.workspace.$(params.first-param[0]))")}, + {Name: "first-task-second-param", Value: *NewStructuredValues("$(input.workspace.$(params.second-param[1]))")}, + }, + }}, }, - Finally: []PipelineTask{{ - Params: Params{ - {Name: "final-task-first-param", Value: *NewStructuredValues("$(params.first-param[0])")}, - {Name: "final-task-second-param", Value: *NewStructuredValues("$(params.second-param[1])")}, + want: sets.NewString("$(params.first-param[0])", "$(params.second-param[1])"), + }, { + name: "array parameter", + spec: PipelineSpec{ + Params: []ParamSpec{ + {Name: "first-param", Type: ParamTypeArray, Default: NewStructuredValues("default", "array", "value")}, + {Name: "second-param", Type: ParamTypeArray}, }, - }}, - }, - want: sets.NewString("$(params.first-param[0])", "$(params.second-param[1])"), - }, { - name: "references in finally when expressions", - spec: PipelineSpec{ - Params: []ParamSpec{ - {Name: "first-param", Type: ParamTypeArray, Default: NewStructuredValues("default-value", "default-value-again")}, - {Name: "second-param", Type: ParamTypeArray}, + Tasks: []PipelineTask{{ + Params: Params{ + {Name: "first-task-first-param", Value: *NewStructuredValues("firstelement", "$(params.first-param)")}, + {Name: "first-task-second-param", Value: *NewStructuredValues("firstelement", "$(params.second-param[0])")}, + }, + }}, }, - Finally: []PipelineTask{{ - When: WhenExpressions{{ - Input: "$(params.first-param[0])", - Operator: selection.In, - Values: []string{"$(params.second-param[1])"}, + want: sets.NewString("$(params.second-param[0])"), + }, { + name: "references in finally params", + spec: PipelineSpec{ + Params: []ParamSpec{ + {Name: "first-param", Type: ParamTypeArray, Default: NewStructuredValues("default-value", "default-value-again")}, + {Name: "second-param", Type: ParamTypeArray}, + }, + Finally: []PipelineTask{{ + Params: Params{ + {Name: "final-task-first-param", Value: *NewStructuredValues("$(params.first-param[0])")}, + {Name: "final-task-second-param", Value: *NewStructuredValues("$(params.second-param[1])")}, + }, }}, - }}, - }, - want: sets.NewString("$(params.first-param[0])", "$(params.second-param[1])"), - }, { - name: "parameter references with bracket notation and special characters", - spec: PipelineSpec{ - Params: []ParamSpec{ - {Name: "first.param", Type: ParamTypeArray, Default: NewStructuredValues("default-value", "default-value-again")}, - {Name: "second/param", Type: ParamTypeArray}, - {Name: "third.param", Type: ParamTypeArray, Default: NewStructuredValues("default-value", "default-value-again")}, - {Name: "fourth/param", Type: ParamTypeArray}, }, - Tasks: []PipelineTask{{ - Params: Params{ - {Name: "first-task-first-param", Value: *NewStructuredValues(`$(params["first.param"][0])`)}, - {Name: "first-task-second-param", Value: *NewStructuredValues(`$(params["second.param"][0])`)}, - {Name: "first-task-third-param", Value: *NewStructuredValues(`$(params['third.param'][1])`)}, - {Name: "first-task-fourth-param", Value: *NewStructuredValues(`$(params['fourth/param'][1])`)}, - {Name: "first-task-fifth-param", Value: *NewStructuredValues("static value")}, + want: sets.NewString("$(params.first-param[0])", "$(params.second-param[1])"), + }, { + name: "references in finally when expressions", + spec: PipelineSpec{ + Params: []ParamSpec{ + {Name: "first-param", Type: ParamTypeArray, Default: NewStructuredValues("default-value", "default-value-again")}, + {Name: "second-param", Type: ParamTypeArray}, }, - }}, - }, - want: sets.NewString(`$(params["first.param"][0])`, `$(params["second.param"][0])`, `$(params['third.param'][1])`, `$(params['fourth/param'][1])`), - }, { - name: "single parameter in workspace subpath", - spec: PipelineSpec{ - Params: []ParamSpec{ - {Name: "first-param", Type: ParamTypeArray, Default: NewStructuredValues("default-value", "default-value-again")}, - {Name: "second-param", Type: ParamTypeArray}, + Finally: []PipelineTask{{ + When: WhenExpressions{{ + Input: "$(params.first-param[0])", + Operator: selection.In, + Values: []string{"$(params.second-param[1])"}, + }}, + }}, }, - Tasks: []PipelineTask{{ - Params: Params{ - {Name: "first-task-first-param", Value: *NewStructuredValues("$(params.first-param[0])")}, - {Name: "first-task-second-param", Value: *NewStructuredValues("static value")}, + want: sets.NewString("$(params.first-param[0])", "$(params.second-param[1])"), + }, { + name: "parameter references with bracket notation and special characters", + spec: PipelineSpec{ + Params: []ParamSpec{ + {Name: "first.param", Type: ParamTypeArray, Default: NewStructuredValues("default-value", "default-value-again")}, + {Name: "second/param", Type: ParamTypeArray}, + {Name: "third.param", Type: ParamTypeArray, Default: NewStructuredValues("default-value", "default-value-again")}, + {Name: "fourth/param", Type: ParamTypeArray}, }, - Workspaces: []WorkspacePipelineTaskBinding{ - { - Name: "first-workspace", - Workspace: "first-workspace", - SubPath: "$(params.second-param[1])", + Tasks: []PipelineTask{{ + Params: Params{ + {Name: "first-task-first-param", Value: *NewStructuredValues(`$(params["first.param"][0])`)}, + {Name: "first-task-second-param", Value: *NewStructuredValues(`$(params["second.param"][0])`)}, + {Name: "first-task-third-param", Value: *NewStructuredValues(`$(params['third.param'][1])`)}, + {Name: "first-task-fourth-param", Value: *NewStructuredValues(`$(params['fourth/param'][1])`)}, + {Name: "first-task-fifth-param", Value: *NewStructuredValues("static value")}, }, + }}, + }, + want: sets.NewString(`$(params["first.param"][0])`, `$(params["second.param"][0])`, `$(params['third.param'][1])`, `$(params['fourth/param'][1])`), + }, { + name: "single parameter in workspace subpath", + spec: PipelineSpec{ + Params: []ParamSpec{ + {Name: "first-param", Type: ParamTypeArray, Default: NewStructuredValues("default-value", "default-value-again")}, + {Name: "second-param", Type: ParamTypeArray}, }, - }}, + Tasks: []PipelineTask{{ + Params: Params{ + {Name: "first-task-first-param", Value: *NewStructuredValues("$(params.first-param[0])")}, + {Name: "first-task-second-param", Value: *NewStructuredValues("static value")}, + }, + Workspaces: []WorkspacePipelineTaskBinding{ + { + Name: "first-workspace", + Workspace: "first-workspace", + SubPath: "$(params.second-param[1])", + }, + }, + }}, + }, + want: sets.NewString("$(params.first-param[0])", "$(params.second-param[1])"), }, - want: sets.NewString("$(params.first-param[0])", "$(params.second-param[1])"), - }, } { - tt := tt // capture range variable t.Run(tt.name, func(t *testing.T) { t.Parallel() got := tt.spec.GetIndexingReferencesToArrayParams() diff --git a/pkg/apis/pipeline/v1/taskrun_types_test.go b/pkg/apis/pipeline/v1/taskrun_types_test.go index 63c16ae2a40..6060c15ebab 100644 --- a/pkg/apis/pipeline/v1/taskrun_types_test.go +++ b/pkg/apis/pipeline/v1/taskrun_types_test.go @@ -31,8 +31,10 @@ import ( duckv1 "knative.dev/pkg/apis/duck/v1" ) -var now = time.Date(2022, time.January, 1, 0, 0, 0, 0, time.UTC) -var testClock = clock.NewFakePassiveClock(now) +var ( + now = time.Date(2022, time.January, 1, 0, 0, 0, 0, time.UTC) + testClock = clock.NewFakePassiveClock(now) +) func TestTaskRun_GetPipelineRunPVCName(t *testing.T) { tests := []struct { @@ -511,7 +513,7 @@ func TestTaskRunIsRetriable(t *testing.T) { wantIsRetriable: false, }} { retriesStatus := []v1.TaskRunStatus{} - for i := 0; i < tc.numRetriesStatus; i++ { + for range tc.numRetriesStatus { retriesStatus = append(retriesStatus, retryStatus) } t.Run(tc.name, func(t *testing.T) { diff --git a/pkg/apis/pipeline/v1beta1/merge.go b/pkg/apis/pipeline/v1beta1/merge.go index 9423c8ec058..6d1432d46db 100644 --- a/pkg/apis/pipeline/v1beta1/merge.go +++ b/pkg/apis/pipeline/v1beta1/merge.go @@ -82,7 +82,6 @@ func MergeStepsWithOverrides(steps []Step, overrides []TaskRunStepOverride) ([]S stepNameToOverride[o.Name] = o } for i, s := range steps { - s := s o, found := stepNameToOverride[s.Name] if !found { continue @@ -109,7 +108,6 @@ func MergeSidecarsWithOverrides(sidecars []Sidecar, overrides []TaskRunSidecarOv sidecarNameToOverride[o.Name] = o } for i, s := range sidecars { - s := s o, found := sidecarNameToOverride[s.Name] if !found { continue diff --git a/pkg/apis/pipeline/v1beta1/param_types_test.go b/pkg/apis/pipeline/v1beta1/param_types_test.go index 8f15dae7545..8494a279281 100644 --- a/pkg/apis/pipeline/v1beta1/param_types_test.go +++ b/pkg/apis/pipeline/v1beta1/param_types_test.go @@ -307,7 +307,6 @@ type ParamValuesHolder struct { AOrS v1beta1.ParamValue `json:"val"` } -//nolint:musttag func TestParamValues_UnmarshalJSON(t *testing.T) { cases := []struct { input map[string]interface{} @@ -398,7 +397,6 @@ func TestParamValues_UnmarshalJSON_Directly(t *testing.T) { } } -//nolint:musttag func TestParamValues_UnmarshalJSON_Error(t *testing.T) { cases := []struct { desc string @@ -416,7 +414,6 @@ func TestParamValues_UnmarshalJSON_Error(t *testing.T) { } } -//nolint:musttag func TestParamValues_MarshalJSON(t *testing.T) { cases := []struct { input v1beta1.ParamValue diff --git a/pkg/apis/pipeline/v1beta1/pipeline_validation_test.go b/pkg/apis/pipeline/v1beta1/pipeline_validation_test.go index 80860f7678b..0c4aaa9d7d2 100644 --- a/pkg/apis/pipeline/v1beta1/pipeline_validation_test.go +++ b/pkg/apis/pipeline/v1beta1/pipeline_validation_test.go @@ -364,7 +364,8 @@ func TestPipeline_Validate_Failure(t *testing.T) { return cfgtesting.SetFeatureFlags(ctx, t, map[string]string{ "disable-inline-spec": "pipeline", - "enable-api-fields": "alpha"}) + "enable-api-fields": "alpha", + }) }, }, { name: "pipelineSpec when disable-inline-spec all", @@ -384,7 +385,8 @@ func TestPipeline_Validate_Failure(t *testing.T) { return cfgtesting.SetFeatureFlags(ctx, t, map[string]string{ "disable-inline-spec": "pipeline,taskrun,pipelinerun", - "enable-api-fields": "alpha"}) + "enable-api-fields": "alpha", + }) }, }, { name: "taskSpec when disable-inline-spec", @@ -4741,7 +4743,6 @@ func TestGetIndexingReferencesToArrayParams(t *testing.T) { want: sets.NewString("$(params.first-param[0])", "$(params.second-param[1])"), }, } { - tt := tt // capture range variable t.Run(tt.name, func(t *testing.T) { t.Parallel() got := tt.spec.GetIndexingReferencesToArrayParams() diff --git a/pkg/apis/pipeline/v1beta1/task_conversion.go b/pkg/apis/pipeline/v1beta1/task_conversion.go index 4c026e10b60..452fb545f70 100644 --- a/pkg/apis/pipeline/v1beta1/task_conversion.go +++ b/pkg/apis/pipeline/v1beta1/task_conversion.go @@ -238,7 +238,7 @@ func deserializeTaskDeprecations(meta *metav1.ObjectMeta, spec *TaskSpec, taskNa if len(spec.Steps) != len(td.DeprecatedSteps) { return errors.New("length of deserialized steps mismatch the length of target steps") } - for i := 0; i < len(spec.Steps); i++ { + for i := range len(spec.Steps) { spec.Steps[i].DeprecatedPorts = td.DeprecatedSteps[i].DeprecatedPorts spec.Steps[i].DeprecatedLivenessProbe = td.DeprecatedSteps[i].DeprecatedLivenessProbe spec.Steps[i].DeprecatedReadinessProbe = td.DeprecatedSteps[i].DeprecatedReadinessProbe diff --git a/pkg/apis/pipeline/v1beta1/taskrun_types_test.go b/pkg/apis/pipeline/v1beta1/taskrun_types_test.go index d2aa439e04e..2474740ba9d 100644 --- a/pkg/apis/pipeline/v1beta1/taskrun_types_test.go +++ b/pkg/apis/pipeline/v1beta1/taskrun_types_test.go @@ -571,7 +571,7 @@ func TestTaskRunIsRetriable(t *testing.T) { wantIsRetriable: false, }} { retriesStatus := []v1beta1.TaskRunStatus{} - for i := 0; i < tc.numRetriesStatus; i++ { + for range tc.numRetriesStatus { retriesStatus = append(retriesStatus, retryStatus) } t.Run(tc.name, func(t *testing.T) { diff --git a/pkg/entrypoint/entrypointer_test.go b/pkg/entrypoint/entrypointer_test.go index 40aa53158f3..b15398f32f2 100644 --- a/pkg/entrypoint/entrypointer_test.go +++ b/pkg/entrypoint/entrypointer_test.go @@ -762,31 +762,34 @@ func TestApplyStepResultSubstitutions_Env(t *testing.T) { envValue string want string wantErr bool - }{{ - name: "string param", - stepName: "foo", - resultName: "res", - result: "Hello", - envValue: "$(steps.foo.results.res)", - want: "Hello", - wantErr: false, - }, { - name: "array param", - stepName: "foo", - resultName: "res", - result: "[\"Hello\",\"World\"]", - envValue: "$(steps.foo.results.res[1])", - want: "World", - wantErr: false, - }, { - name: "object param", - stepName: "foo", - resultName: "res", - result: "{\"hello\":\"World\"}", - envValue: "$(steps.foo.results.res.hello)", - want: "World", - wantErr: false, - }, + }{ + { + name: "string param", + stepName: "foo", + resultName: "res", + result: "Hello", + envValue: "$(steps.foo.results.res)", + want: "Hello", + wantErr: false, + }, + { + name: "array param", + stepName: "foo", + resultName: "res", + result: "[\"Hello\",\"World\"]", + envValue: "$(steps.foo.results.res[1])", + want: "World", + wantErr: false, + }, + { + name: "object param", + stepName: "foo", + resultName: "res", + result: "{\"hello\":\"World\"}", + envValue: "$(steps.foo.results.res.hello)", + want: "World", + wantErr: false, + }, { name: "interpolation multiple matches", stepName: "foo", @@ -795,7 +798,8 @@ func TestApplyStepResultSubstitutions_Env(t *testing.T) { envValue: "$(steps.foo.results.res.first)-$(steps.foo.results.res.second)", want: "hello-world", wantErr: false, - }, { + }, + { name: "bad-result-format", stepName: "foo", resultName: "res", @@ -803,7 +807,8 @@ func TestApplyStepResultSubstitutions_Env(t *testing.T) { envValue: "echo $(steps.foo.results.res.hello.bar)", want: "echo $(steps.foo.results.res.hello.bar)", wantErr: true, - }} + }, + } stepDir := createTmpDir(t, "env-steps") for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { @@ -844,71 +849,72 @@ func TestApplyStepResultSubstitutions_Command(t *testing.T) { command []string want []string wantErr bool - }{{ - name: "string param", - stepName: "foo", - resultName: "res1", - result: "Hello", - command: []string{"$(steps.foo.results.res1)"}, - want: []string{"Hello"}, - wantErr: false, - }, { - name: "array param", - stepName: "foo", - resultName: "res", - result: "[\"Hello\",\"World\"]", - command: []string{"$(steps.foo.results.res[1])"}, - want: []string{"World"}, - wantErr: false, - }, { - name: "array param no index", - stepName: "foo", - resultName: "res", - result: "[\"Hello\",\"World\"]", - command: []string{"start", "$(steps.foo.results.res[*])", "stop"}, - want: []string{"start", "Hello", "World", "stop"}, - wantErr: false, - }, { - name: "object param", - stepName: "foo", - resultName: "res", - result: "{\"hello\":\"World\"}", - command: []string{"$(steps.foo.results.res.hello)"}, - want: []string{"World"}, - wantErr: false, - }, { - name: "bad-result-format", - stepName: "foo", - resultName: "res", - result: "{\"hello\":\"World\"}", - command: []string{"echo $(steps.foo.results.res.hello.bar)"}, - want: []string{"echo $(steps.foo.results.res.hello.bar)"}, - wantErr: true, - }, { - name: "array param no index, with extra string", - stepName: "foo", - resultName: "res", - result: "[\"Hello\",\"World\"]", - command: []string{"start", "$(steps.foo.results.res[*])bbb", "stop"}, - want: []string{"start", "$(steps.foo.results.res[*])bbb", "stop"}, - wantErr: true, - }, { - name: "array param, multiple matches", - stepName: "foo", - resultName: "res", - result: "[\"Hello\",\"World\"]", - command: []string{"$(steps.foo.results.res[0])-$(steps.foo.results.res[1])"}, - want: []string{"Hello-World"}, - wantErr: false, - }, { - name: "object param, multiple matches", - stepName: "foo", - resultName: "res", - result: `{"first":"hello", "second":"world"}`, - command: []string{"$(steps.foo.results.res.first)-$(steps.foo.results.res.second)"}, - want: []string{"hello-world"}, - wantErr: false, - }, + }{ + { + name: "string param", + stepName: "foo", + resultName: "res1", + result: "Hello", + command: []string{"$(steps.foo.results.res1)"}, + want: []string{"Hello"}, + wantErr: false, + }, { + name: "array param", + stepName: "foo", + resultName: "res", + result: "[\"Hello\",\"World\"]", + command: []string{"$(steps.foo.results.res[1])"}, + want: []string{"World"}, + wantErr: false, + }, { + name: "array param no index", + stepName: "foo", + resultName: "res", + result: "[\"Hello\",\"World\"]", + command: []string{"start", "$(steps.foo.results.res[*])", "stop"}, + want: []string{"start", "Hello", "World", "stop"}, + wantErr: false, + }, { + name: "object param", + stepName: "foo", + resultName: "res", + result: "{\"hello\":\"World\"}", + command: []string{"$(steps.foo.results.res.hello)"}, + want: []string{"World"}, + wantErr: false, + }, { + name: "bad-result-format", + stepName: "foo", + resultName: "res", + result: "{\"hello\":\"World\"}", + command: []string{"echo $(steps.foo.results.res.hello.bar)"}, + want: []string{"echo $(steps.foo.results.res.hello.bar)"}, + wantErr: true, + }, { + name: "array param no index, with extra string", + stepName: "foo", + resultName: "res", + result: "[\"Hello\",\"World\"]", + command: []string{"start", "$(steps.foo.results.res[*])bbb", "stop"}, + want: []string{"start", "$(steps.foo.results.res[*])bbb", "stop"}, + wantErr: true, + }, { + name: "array param, multiple matches", + stepName: "foo", + resultName: "res", + result: "[\"Hello\",\"World\"]", + command: []string{"$(steps.foo.results.res[0])-$(steps.foo.results.res[1])"}, + want: []string{"Hello-World"}, + wantErr: false, + }, { + name: "object param, multiple matches", + stepName: "foo", + resultName: "res", + result: `{"first":"hello", "second":"world"}`, + command: []string{"$(steps.foo.results.res.first)-$(steps.foo.results.res.second)"}, + want: []string{"hello-world"}, + wantErr: false, + }, } stepDir := createTmpDir(t, "command-steps") for _, tc := range testCases { @@ -1111,7 +1117,6 @@ func TestReadArtifactsFileDoesNotExist(t *testing.T) { dir := createTmpDir(t, "") fp := filepath.Join(dir, "provenance.json") got, err := readArtifacts(fp) - if err != nil { t.Fatalf("Did not expect and error but got: %v", err) } @@ -1127,12 +1132,11 @@ func TestReadArtifactsFileExistNoError(t *testing.T) { t.Run("readArtifact file exist", func(t *testing.T) { dir := createTmpDir(t, "") fp := filepath.Join(dir, "provenance.json") - err := os.WriteFile(fp, []byte{}, 0755) + err := os.WriteFile(fp, []byte{}, 0o755) if err != nil { t.Fatalf("Did not expect and error but got: %v", err) } got, err := readArtifacts(fp) - if err != nil { t.Fatalf("Did not expect and error but got: %v", err) } @@ -1151,7 +1155,7 @@ func TestReadArtifactsFileExistReadError(t *testing.T) { } dir := createTmpDir(t, "") fp := filepath.Join(dir, "provenance.json") - err := os.WriteFile(fp, []byte{}, 0000) + err := os.WriteFile(fp, []byte{}, 0o000) if err != nil { t.Fatalf("Did not expect and error but got: %v", err) } @@ -1199,7 +1203,7 @@ func TestLoadStepArtifacts(t *testing.T) { Uri: "docker:example.registry.com/outputs", }}}}, }, - mode: 0755, + mode: 0o755, }, { desc: "read artifact file doesn't exist, error", @@ -1209,26 +1213,26 @@ func TestLoadStepArtifacts(t *testing.T) { { desc: "read artifact, mal-formatted json, error", fileContent: `{\\`, - mode: 0755, + mode: 0o755, wantErr: true, }, { desc: "read artifact, file cannot be read, error", fileContent: `{"inputs":[{"name":"inputs","values":[{"digest":{"sha256":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"},"uri":"pkg:example.github.com/inputs"}]}],"outputs":[{"name":"output","values":[{"digest":{"sha256":"64d0b157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f134074b0"},"uri":"docker:example.registry.com/outputs"}]}]}`, - mode: 0000, + mode: 0o000, wantErr: true, }, } for _, tc := range tests { t.Run(tc.desc, func(t *testing.T) { - if tc.mode == 0000 && os.Getuid() == 0 { + if tc.mode == 0o000 && os.Getuid() == 0 { t.Skipf("Test doesn't work when running with root") } dir := createTmpDir(t, "") name := "step-name" artifactsPath := getStepArtifactsPath(dir, name) if tc.fileContent != "" { - err := os.MkdirAll(filepath.Dir(artifactsPath), 0755) + err := os.MkdirAll(filepath.Dir(artifactsPath), 0o755) if err != nil { t.Fatalf("fail to create dir %v", err) } @@ -1365,76 +1369,76 @@ func TestGetArtifactValues(t *testing.T) { desc: "read outputs artifact without artifact name, success", fileContent: `{"inputs":[{"name":"inputs","values":[{"digest":{"sha256":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"},"uri":"pkg:example.github.com/inputs"}]}],"outputs":[{"name":"output","values":[{"digest":{"sha256":"64d0b157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f134074b0"},"uri":"docker:example.registry.com/outputs"}]}]}`, want: `[{"digest":{"sha256":"64d0b157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f134074b0"},"uri":"docker:example.registry.com/outputs"}]`, - mode: 0755, + mode: 0o755, template: fmt.Sprintf("$(steps.%s.outputs)", name), }, { desc: "read inputs artifact without artifact name, success", fileContent: `{"inputs":[{"name":"inputs","values":[{"digest":{"sha256":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"},"uri":"pkg:example.github.com/inputs"}]}],"outputs":[{"name":"output","values":[{"digest":{"sha256":"64d0b157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f134074b0"},"uri":"docker:example.registry.com/outputs"}]}]}`, want: `[{"digest":{"sha256":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"},"uri":"pkg:example.github.com/inputs"}]`, - mode: 0755, + mode: 0o755, template: fmt.Sprintf("$(steps.%s.inputs)", name), }, { desc: "read outputs artifact without artifact name, multiple outputs, default to first", fileContent: `{"inputs":[{"name":"inputs","values":[{"digest":{"sha256":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"},"uri":"pkg:example.github.com/inputs"}]}],"outputs":[{"name":"output","values":[{"digest":{"sha256":"64d0b157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f134074b0"},"uri":"docker:example.registry.com/outputs"}]},{"name":"output2","values":[{"digest":{"sha256":"22222157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f13402222"},"uri":"docker2:example.registry.com/outputs"}]}]}`, want: `[{"digest":{"sha256":"64d0b157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f134074b0"},"uri":"docker:example.registry.com/outputs"}]`, - mode: 0755, + mode: 0o755, template: fmt.Sprintf("$(steps.%s.outputs)", name), }, { desc: "read inputs artifact without artifact name, multiple outputs, default to first", fileContent: `{"outputs":[{"name":"out","values":[{"digest":{"sha256":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"},"uri":"pkg:example.github.com/inputs"}]}],"inputs":[{"name":"in","values":[{"digest":{"sha256":"64d0b157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f134074b0"},"uri":"docker:example.registry.com/inputs"}]},{"name":"in2","values":[{"digest":{"sha256":"22222157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f13402222"},"uri":"docker2:example.registry.com/inputs"}]}]}`, want: `[{"digest":{"sha256":"64d0b157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f134074b0"},"uri":"docker:example.registry.com/inputs"}]`, - mode: 0755, + mode: 0o755, template: fmt.Sprintf("$(steps.%s.inputs)", name), }, { desc: "read outputs artifact with artifact name, success", fileContent: `{"inputs":[{"name":"inputs","values":[{"digest":{"sha256":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"},"uri":"pkg:example.github.com/inputs"}]}],"outputs":[{"name":"output","values":[{"digest":{"sha256":"64d0b157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f134074b0"},"uri":"docker:example.registry.com/outputs"}]}]}`, want: `[{"digest":{"sha256":"64d0b157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f134074b0"},"uri":"docker:example.registry.com/outputs"}]`, - mode: 0755, + mode: 0o755, template: fmt.Sprintf("$(steps.%s.outputs.output)", name), }, { desc: "read inputs artifact with artifact name, success", fileContent: `{"outputs":[{"name":"outputs","values":[{"digest":{"sha256":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"},"uri":"pkg:example.github.com/outputs"}]}],"inputs":[{"name":"input","values":[{"digest":{"sha256":"64d0b157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f134074b0"},"uri":"docker:example.registry.com/inputs"}]}]}`, want: `[{"digest":{"sha256":"64d0b157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f134074b0"},"uri":"docker:example.registry.com/inputs"}]`, - mode: 0755, + mode: 0o755, template: fmt.Sprintf("$(steps.%s.inputs.input)", name), }, { desc: "read outputs artifact with artifact name, multiple outputs, success", fileContent: `{"inputs":[{"name":"inputs","values":[{"digest":{"sha256":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"},"uri":"pkg:example.github.com/inputs"}]}],"outputs":[{"name":"output","values":[{"digest":{"sha256":"64d0b157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f134074b0"},"uri":"docker:example.registry.com/outputs"}]},{"name":"output2","values":[{"digest":{"sha256":"22222157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f13402222"},"uri":"docker2:example.registry.com/outputs"}]}]}`, want: `[{"digest":{"sha256":"22222157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f13402222"},"uri":"docker2:example.registry.com/outputs"}]`, - mode: 0755, + mode: 0o755, template: fmt.Sprintf("$(steps.%s.outputs.output2)", name), }, { desc: "read inputs artifact with artifact name, multiple inputs, success", fileContent: `{"outputs":[{"name":"outputs","values":[{"digest":{"sha256":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"},"uri":"pkg:example.github.com/outputs"}]}],"inputs":[{"name":"input","values":[{"digest":{"sha256":"64d0b157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f134074b0"},"uri":"docker:example.registry.com/inputs"}]},{"name":"input2","values":[{"digest":{"sha256":"22222157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f13402222"},"uri":"docker2:example.registry.com/inputs"}]}]}`, want: `[{"digest":{"sha256":"22222157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f13402222"},"uri":"docker2:example.registry.com/inputs"}]`, - mode: 0755, + mode: 0o755, template: fmt.Sprintf("$(steps.%s.inputs.input2)", name), }, { desc: "invalid template", fileContent: `{"inputs":[{"name":"inputs","values":[{"digest":{"sha256":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"},"uri":"pkg:example.github.com/inputs"}]}],"outputs":[{"name":"output","values":[{"digest":{"sha256":"64d0b157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f134074b0"},"uri":"docker:example.registry.com/outputs"}]},{"name":"output2","values":[{"digest":{"sha256":"22222157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f13402222"},"uri":"docker2:example.registry.com/outputs"}]}]}`, - mode: 0755, + mode: 0o755, template: fmt.Sprintf("$(steps.%s.outputs.output2.333)", name), wantErr: true, }, { desc: "fail to load artifacts", fileContent: `{"inputs":[{"name":"inputs","values":[{"digest":{"sha256":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"},"uri":"pkg:example.github.com/inputs"}]}],"outputs":[{"name":"output","values":[{"digest":{"sha256":"64d0b157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f134074b0"},"uri":"docker:example.registry.com/outputs"}]},{"name":"output2","values":[{"digest":{"sha256":"22222157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f13402222"},"uri":"docker2:example.registry.com/outputs"}]}]}`, - mode: 0000, + mode: 0o000, template: fmt.Sprintf("$(steps.%s.outputs.output2.333)", name), wantErr: true, }, { desc: "template not found", fileContent: `{"inputs":[{"name":"inputs","values":[{"digest":{"sha256":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"},"uri":"pkg:example.github.com/inputs"}]}],"outputs":[{"name":"output","values":[{"digest":{"sha256":"64d0b157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f134074b0"},"uri":"docker:example.registry.com/outputs"}]},{"name":"output2","values":[{"digest":{"sha256":"22222157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f13402222"},"uri":"docker2:example.registry.com/outputs"}]}]}`, - mode: 0755, + mode: 0o755, template: fmt.Sprintf("$(steps.%s.outputs.output3)", name), wantErr: true, }, @@ -1442,13 +1446,13 @@ func TestGetArtifactValues(t *testing.T) { for _, tc := range tests { t.Run(tc.desc, func(t *testing.T) { - if tc.mode == 0000 && os.Getuid() == 0 { + if tc.mode == 0o000 && os.Getuid() == 0 { t.Skipf("Test doesn't work when running with root") } dir := createTmpDir(t, "") artifactsPath := getStepArtifactsPath(dir, "step-"+name) if tc.fileContent != "" { - err := os.MkdirAll(filepath.Dir(artifactsPath), 0755) + err := os.MkdirAll(filepath.Dir(artifactsPath), 0o755) if err != nil { t.Fatalf("fail to create dir %v", err) } @@ -1493,7 +1497,7 @@ func TestApplyStepArtifactSubstitutionsCommandSuccess(t *testing.T) { desc: "apply substitution to command from script file, success", fileContent: `{"inputs":[{"name":"inputs","values":[{"digest":{"sha256":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"},"uri":"pkg:example.github.com/inputs"}]}],"outputs":[{"name":"output","values":[{"digest":{"sha256":"64d0b157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f134074b0"},"uri":"docker:example.registry.com/outputs"}]}]}`, want: `echo [{"digest":{"sha256":"64d0b157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f134074b0"},"uri":"docker:example.registry.com/outputs"}]`, - mode: 0755, + mode: 0o755, scriptContent: fmt.Sprintf("echo $(steps.%s.outputs)", stepName), scriptFile: filepath.Join(scriptDir, "foo.sh"), command: []string{filepath.Join(scriptDir, "foo.sh")}, @@ -1504,7 +1508,7 @@ func TestApplyStepArtifactSubstitutionsCommandSuccess(t *testing.T) { stepDir := createTmpDir(t, "") artifactsPath := getStepArtifactsPath(stepDir, "step-"+stepName) if tc.fileContent != "" { - err := os.MkdirAll(filepath.Dir(artifactsPath), 0755) + err := os.MkdirAll(filepath.Dir(artifactsPath), 0o755) if err != nil { t.Fatalf("fail to create stepDir %v", err) } @@ -1514,7 +1518,7 @@ func TestApplyStepArtifactSubstitutionsCommandSuccess(t *testing.T) { } } if tc.scriptContent != "" { - err := os.WriteFile(tc.scriptFile, []byte(tc.scriptContent), 0755) + err := os.WriteFile(tc.scriptFile, []byte(tc.scriptContent), 0o755) if err != nil { t.Fatalf("failed to write script to scriptFile %v", err) } @@ -1535,6 +1539,7 @@ func TestApplyStepArtifactSubstitutionsCommandSuccess(t *testing.T) { }) } } + func TestApplyStepArtifactSubstitutionsCommand(t *testing.T) { stepName := "name" scriptDir := createTmpDir(t, "script") @@ -1558,7 +1563,7 @@ func TestApplyStepArtifactSubstitutionsCommand(t *testing.T) { desc: "apply substitution script, fail to read artifacts", fileContent: `{"inputs":[{"name":"inputs","values":[{"digest":{"sha256":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"},"uri":"pkg:example.github.com/inputs"}]}],"outputs":[{"name":"output","values":[{"digest":{"sha256":"64d0b157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f134074b0"},"uri":"docker:example.registry.com/outputs"}]}]}`, want: []string{filepath.Join(scriptDir, "foo2.sh")}, - mode: 0000, + mode: 0o000, wantErr: true, scriptContent: fmt.Sprintf("echo $(steps.%s.outputs)", stepName), scriptFile: filepath.Join(scriptDir, "foo2.sh"), @@ -1568,7 +1573,7 @@ func TestApplyStepArtifactSubstitutionsCommand(t *testing.T) { desc: "apply substitution to command from script file , no matches success", fileContent: `{"inputs":[{"name":"inputs","values":[{"digest":{"sha256":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"},"uri":"pkg:example.github.com/inputs"}]}],"outputs":[{"name":"output","values":[{"digest":{"sha256":"64d0b157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f134074b0"},"uri":"docker:example.registry.com/outputs"}]}]}`, want: []string{filepath.Join(scriptDir, "bar.sh")}, - mode: 0755, + mode: 0o755, scriptContent: "echo 123", scriptFile: filepath.Join(scriptDir, "bar.sh"), command: []string{filepath.Join(scriptDir, "bar.sh")}, @@ -1577,14 +1582,14 @@ func TestApplyStepArtifactSubstitutionsCommand(t *testing.T) { desc: "apply substitution to inline command, success", fileContent: `{"inputs":[{"name":"inputs","values":[{"digest":{"sha256":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"},"uri":"pkg:example.github.com/inputs"}]}],"outputs":[{"name":"output","values":[{"digest":{"sha256":"64d0b157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f134074b0"},"uri":"docker:example.registry.com/outputs"}]}]}`, want: []string{"echo", `[{"digest":{"sha256":"64d0b157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f134074b0"},"uri":"docker:example.registry.com/outputs"}]`, "|", "jq", "."}, - mode: 0755, + mode: 0o755, command: []string{"echo", fmt.Sprintf("$(steps.%s.outputs)", stepName), "|", "jq", "."}, }, { desc: "apply substitution to inline command, fail to read, command no change", fileContent: `{"inputs":[{"name":"inputs","values":[{"digest":{"sha256":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"},"uri":"pkg:example.github.com/inputs"}]}],"outputs":[{"name":"output","values":[{"digest":{"sha256":"64d0b157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f134074b0"},"uri":"docker:example.registry.com/outputs"}]}]}`, want: []string{"echo", fmt.Sprintf("$(steps.%s.outputs)", stepName), "|", "jq", "."}, - mode: 0000, + mode: 0o000, wantErr: true, command: []string{"echo", fmt.Sprintf("$(steps.%s.outputs)", stepName), "|", "jq", "."}, }, @@ -1592,13 +1597,13 @@ func TestApplyStepArtifactSubstitutionsCommand(t *testing.T) { for _, tc := range tests { t.Run(tc.desc, func(t *testing.T) { - if tc.mode == 0000 && os.Getuid() == 0 { + if tc.mode == 0o000 && os.Getuid() == 0 { t.Skipf("Test doesn't work when running with root") } stepDir := createTmpDir(t, "") artifactsPath := getStepArtifactsPath(stepDir, "step-"+stepName) if tc.fileContent != "" { - err := os.MkdirAll(filepath.Dir(artifactsPath), 0755) + err := os.MkdirAll(filepath.Dir(artifactsPath), 0o755) if err != nil { t.Fatalf("fail to create stepDir %v", err) } @@ -1608,7 +1613,7 @@ func TestApplyStepArtifactSubstitutionsCommand(t *testing.T) { } } if tc.scriptContent != "" { - err := os.WriteFile(tc.scriptFile, []byte(tc.scriptContent), 0755) + err := os.WriteFile(tc.scriptFile, []byte(tc.scriptContent), 0o755) if err != nil { t.Fatalf("failed to write script to scriptFile %v", err) } @@ -1647,7 +1652,7 @@ func TestApplyStepArtifactSubstitutionsEnv(t *testing.T) { { desc: "apply substitution to env, no matches, no changes", fileContent: `{"inputs":[{"name":"inputs","values":[{"digest":{"sha256":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"},"uri":"pkg:example.github.com/inputs"}]}],"outputs":[{"name":"output","values":[{"digest":{"sha256":"64d0b157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f134074b0"},"uri":"docker:example.registry.com/outputs"}]}]}`, - mode: 0755, + mode: 0o755, envKey: "aaa", envValue: "bbb", want: "bbb", @@ -1655,7 +1660,7 @@ func TestApplyStepArtifactSubstitutionsEnv(t *testing.T) { { desc: "apply substitution to env, matches found, has change", fileContent: `{"inputs":[{"name":"inputs","values":[{"digest":{"sha256":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"},"uri":"pkg:example.github.com/inputs"}]}],"outputs":[{"name":"output","values":[{"digest":{"sha256":"64d0b157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f134074b0"},"uri":"docker:example.registry.com/outputs"}]}]}`, - mode: 0755, + mode: 0o755, envKey: "aaa", envValue: fmt.Sprintf("abc-$(steps.%s.outputs)", stepName), want: `abc-[{"digest":{"sha256":"64d0b157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f134074b0"},"uri":"docker:example.registry.com/outputs"}]`, @@ -1663,7 +1668,7 @@ func TestApplyStepArtifactSubstitutionsEnv(t *testing.T) { { desc: "apply substitution to env, matches found, read artifacts failed.", fileContent: `{"inputs":[{"name":"inputs","values":[{"digest":{"sha256":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"},"uri":"pkg:example.github.com/inputs"}]}],"outputs":[{"name":"output","values":[{"digest":{"sha256":"64d0b157fdf2d7f6548836dd82085fd8401c9481a9f59e554f1b337f134074b0"},"uri":"docker:example.registry.com/outputs"}]}]}`, - mode: 0000, + mode: 0o000, envKey: "aaa", envValue: fmt.Sprintf("abc-$(steps.%s.outputs)", stepName), want: fmt.Sprintf("abc-$(steps.%s.outputs)", stepName), @@ -1673,13 +1678,13 @@ func TestApplyStepArtifactSubstitutionsEnv(t *testing.T) { for _, tc := range tests { t.Run(tc.desc, func(t *testing.T) { - if tc.mode == 0000 && os.Getuid() == 0 { + if tc.mode == 0o000 && os.Getuid() == 0 { t.Skipf("Test doesn't work when running with root") } stepDir := createTmpDir(t, "") artifactsPath := getStepArtifactsPath(stepDir, "step-"+stepName) if tc.fileContent != "" { - err := os.MkdirAll(filepath.Dir(artifactsPath), 0755) + err := os.MkdirAll(filepath.Dir(artifactsPath), 0o755) if err != nil { t.Fatalf("fail to create stepDir %v", err) } @@ -1883,7 +1888,7 @@ func getMockSpireClient(ctx context.Context) (spire.EntrypointerAPIClient, spire // bootstrap with about 20 calls to sign which should be enough for testing id := sc.GetIdentity(tr) - for i := 0; i < 20; i++ { + for range 20 { sc.SignIdentities = append(sc.SignIdentities, id) } diff --git a/pkg/pipelinerunmetrics/metrics_test.go b/pkg/pipelinerunmetrics/metrics_test.go index 7ba170a7d2d..cdab8b6c721 100644 --- a/pkg/pipelinerunmetrics/metrics_test.go +++ b/pkg/pipelinerunmetrics/metrics_test.go @@ -554,7 +554,7 @@ func TestRecordRunningPipelineRunsResolutionWaitCounts(t *testing.T) { unregisterMetrics() ctx, _ := ttesting.SetupFakeContext(t) informer := fakepipelineruninformer.Get(ctx) - for i := 0; i < multiplier; i++ { + for range multiplier { pr := &v1.PipelineRun{ ObjectMeta: metav1.ObjectMeta{Name: names.SimpleNameGenerator.RestrictLengthWithRandomSuffix("pipelinerun-")}, Status: v1.PipelineRunStatus{ diff --git a/pkg/pod/entrypoint_lookup_impl_test.go b/pkg/pod/entrypoint_lookup_impl_test.go index 6c6178a8b16..caf0985ed44 100644 --- a/pkg/pod/entrypoint_lookup_impl_test.go +++ b/pkg/pod/entrypoint_lookup_impl_test.go @@ -68,7 +68,7 @@ func (f *fakeHTTP) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } // Check auth if we've fetching the image. - if strings.HasPrefix(r.URL.Path, "/v2/task") && r.Method == "GET" { + if strings.HasPrefix(r.URL.Path, "/v2/task") && r.Method == http.MethodGet { u, p, ok := r.BasicAuth() if !ok || username != u || password != p { w.WriteHeader(http.StatusUnauthorized) @@ -114,9 +114,11 @@ func TestGetImageWithImagePullSecrets(t *testing.T) { task := &pipelinev1.Task{ TypeMeta: metav1.TypeMeta{ APIVersion: "tekton.dev/v1", - Kind: "Task"}, + Kind: "Task", + }, ObjectMeta: metav1.ObjectMeta{ - Name: "test-create-image"}, + Name: "test-create-image", + }, } ref, err := remotetest.CreateImageWithAnnotations(u.Host+"/task/test-create-image", remotetest.DefaultObjectAnnotationMapper, task) diff --git a/pkg/pod/pod.go b/pkg/pod/pod.go index 45400939175..4b7fd542d4f 100644 --- a/pkg/pod/pod.go +++ b/pkg/pod/pod.go @@ -326,7 +326,7 @@ func (b *Builder) Build(ctx context.Context, taskRun *v1.TaskRun, taskSpec v1.Ta // Each step should only mount their own volume as RW, // all other steps should be mounted RO. volumes = append(volumes, runVolume(i)) - for j := 0; j < len(stepContainers); j++ { + for j := range len(stepContainers) { s.VolumeMounts = append(s.VolumeMounts, runMount(j, i != j)) } @@ -352,7 +352,7 @@ func (b *Builder) Build(ctx context.Context, taskRun *v1.TaskRun, taskSpec v1.Ta if s.Name != pipeline.ReservedResultsSidecarName { continue } - for j := 0; j < len(stepContainers); j++ { + for j := range len(stepContainers) { s.VolumeMounts = append(s.VolumeMounts, runMount(j, true)) } requestedVolumeMounts := map[string]bool{} diff --git a/pkg/pod/script.go b/pkg/pod/script.go index e2f3ca5d24d..6b0af47467c 100644 --- a/pkg/pod/script.go +++ b/pkg/pod/script.go @@ -215,7 +215,7 @@ func encodeScript(script string) string { // placeDebugScriptInContainers inserts debug scripts into containers. It capsules those scripts to files in initContainer, // then executes those scripts in target containers. func placeDebugScriptInContainers(containers []corev1.Container, initContainer *corev1.Container) { - for i := 0; i < len(containers); i++ { + for i := range len(containers) { debugInfoVolumeMount := corev1.VolumeMount{ Name: debugInfoVolumeName, MountPath: filepath.Join(debugInfoDir, strconv.Itoa(i)), diff --git a/pkg/reconciler/events/cloudevent/cloudeventsfakeclient.go b/pkg/reconciler/events/cloudevent/cloudeventsfakeclient.go index 92692943918..4eabf274194 100644 --- a/pkg/reconciler/events/cloudevent/cloudeventsfakeclient.go +++ b/pkg/reconciler/events/cloudevent/cloudeventsfakeclient.go @@ -111,7 +111,7 @@ func (c *FakeClient) CheckCloudEventsUnordered(t *testing.T, testName string, wa // extra events are prevented in FakeClient's Send function. // fewer events are detected because we collect all events from channel and compare with wantEvents - for eventCount := 0; eventCount < channelEvents; eventCount++ { + for range channelEvents { event := <-c.events if len(expected) == 0 { t.Errorf("extra event received: %q", event) diff --git a/pkg/reconciler/events/k8sevent/events.go b/pkg/reconciler/events/k8sevent/events.go index 3b35370cea2..15b4eb76790 100644 --- a/pkg/reconciler/events/k8sevent/events.go +++ b/pkg/reconciler/events/k8sevent/events.go @@ -46,7 +46,7 @@ func eventsFromChannel(c chan string, wantEvents []string) error { // on the channel forever if fewer than expected events are received timer := time.After(wait.ForeverTestTimeout) foundEvents := []string{} - for ii := 0; ii < len(wantEvents); ii++ { + for ii := range len(wantEvents) { // We loop over all the events that we expect. Once they are all received // we exit the loop. If we never receive enough events, the timeout takes us // out of the loop. diff --git a/pkg/reconciler/pipeline/dag/dag_test.go b/pkg/reconciler/pipeline/dag/dag_test.go index 056f5b73a39..bf85b7d4f59 100644 --- a/pkg/reconciler/pipeline/dag/dag_test.go +++ b/pkg/reconciler/pipeline/dag/dag_test.go @@ -219,7 +219,8 @@ func TestBuild_JoinMultipleRoots(t *testing.T) { "c": nodeC, "x": nodeX, "y": nodeY, - "z": nodeZ}, + "z": nodeZ, + }, } p := &v1.Pipeline{ ObjectMeta: metav1.ObjectMeta{Name: "pipeline"}, @@ -544,75 +545,76 @@ func TestBuild_InvalidDAG(t *testing.T) { name string spec v1.PipelineSpec err string - }{{ - // a - // | - // a ("a" uses result of "a" as params) - name: "self-link-result", - spec: v1.PipelineSpec{Tasks: []v1.PipelineTask{selfLinkResult}}, - err: "cycle detected", - }, { - // a - // | - // a ("a" runAfter "a") - name: "self-link-after", - spec: v1.PipelineSpec{Tasks: []v1.PipelineTask{selfLinkAfter}}, - err: "cycle detected", - }, { - // a (also "a" depends on resource from "z") - // | - // x ("x" depends on resource from "a") - // | - // z ("z" depends on resource from "x") - name: "cycle-from", - spec: v1.PipelineSpec{Tasks: []v1.PipelineTask{xDependsOnA, zDependsOnX, aDependsOnZ}}, - err: "cycle detected", - }, { - // a (also "a" runAfter "z") - // | - // x ("x" runAfter "a") - // | - // z ("z" runAfter "x") - name: "cycle-runAfter", - spec: v1.PipelineSpec{Tasks: []v1.PipelineTask{xAfterA, zAfterX, aAfterZ}}, - err: "cycle detected", - }, { - // a (also "a" depends on resource from "z") - // | - // x ("x" depends on resource from "a") - // | - // z ("z" runAfter "x") - name: "cycle-both", - spec: v1.PipelineSpec{Tasks: []v1.PipelineTask{xDependsOnA, zAfterX, aDependsOnZ}}, - err: "cycle detected", - }, { - // This test make sure we detect a cyclic branch in a DAG with multiple branches. - // The following DAG is having a cyclic branch with an additional dependency (a runAfter e) - // a - // / \ - // b c - // \ / - // d - // / \ - // e f - // | - // g - name: "multiple-branches-with-one-cyclic-branch", - spec: v1.PipelineSpec{Tasks: []v1.PipelineTask{aRunsAfterE, bDependsOnA, cRunsAfterA, dDependsOnBAndC, eRunsAfterD, fRunsAfterD, gDependsOnF}}, - err: "cycle detected", - }, { - name: "duplicate-tasks", - spec: v1.PipelineSpec{Tasks: []v1.PipelineTask{a, a}}, - err: "duplicate pipeline task", - }, { - name: "invalid-task-result", - spec: v1.PipelineSpec{Tasks: []v1.PipelineTask{invalidTaskResult}}, - err: "wasn't present in Pipeline", - }, { - name: "invalid-task-name-after", - spec: v1.PipelineSpec{Tasks: []v1.PipelineTask{invalidTaskAfter}}, - err: "wasn't present in Pipeline", - }, + }{ + { + // a + // | + // a ("a" uses result of "a" as params) + name: "self-link-result", + spec: v1.PipelineSpec{Tasks: []v1.PipelineTask{selfLinkResult}}, + err: "cycle detected", + }, { + // a + // | + // a ("a" runAfter "a") + name: "self-link-after", + spec: v1.PipelineSpec{Tasks: []v1.PipelineTask{selfLinkAfter}}, + err: "cycle detected", + }, { + // a (also "a" depends on resource from "z") + // | + // x ("x" depends on resource from "a") + // | + // z ("z" depends on resource from "x") + name: "cycle-from", + spec: v1.PipelineSpec{Tasks: []v1.PipelineTask{xDependsOnA, zDependsOnX, aDependsOnZ}}, + err: "cycle detected", + }, { + // a (also "a" runAfter "z") + // | + // x ("x" runAfter "a") + // | + // z ("z" runAfter "x") + name: "cycle-runAfter", + spec: v1.PipelineSpec{Tasks: []v1.PipelineTask{xAfterA, zAfterX, aAfterZ}}, + err: "cycle detected", + }, { + // a (also "a" depends on resource from "z") + // | + // x ("x" depends on resource from "a") + // | + // z ("z" runAfter "x") + name: "cycle-both", + spec: v1.PipelineSpec{Tasks: []v1.PipelineTask{xDependsOnA, zAfterX, aDependsOnZ}}, + err: "cycle detected", + }, { + // This test make sure we detect a cyclic branch in a DAG with multiple branches. + // The following DAG is having a cyclic branch with an additional dependency (a runAfter e) + // a + // / \ + // b c + // \ / + // d + // / \ + // e f + // | + // g + name: "multiple-branches-with-one-cyclic-branch", + spec: v1.PipelineSpec{Tasks: []v1.PipelineTask{aRunsAfterE, bDependsOnA, cRunsAfterA, dDependsOnBAndC, eRunsAfterD, fRunsAfterD, gDependsOnF}}, + err: "cycle detected", + }, { + name: "duplicate-tasks", + spec: v1.PipelineSpec{Tasks: []v1.PipelineTask{a, a}}, + err: "duplicate pipeline task", + }, { + name: "invalid-task-result", + spec: v1.PipelineSpec{Tasks: []v1.PipelineTask{invalidTaskResult}}, + err: "wasn't present in Pipeline", + }, { + name: "invalid-task-name-after", + spec: v1.PipelineSpec{Tasks: []v1.PipelineTask{invalidTaskAfter}}, + err: "wasn't present in Pipeline", + }, } for _, tc := range tcs { t.Run(tc.name, func(t *testing.T) { @@ -636,7 +638,7 @@ func TestBuildGraphWithHundredsOfTasks_Success(t *testing.T) { // .. // b04 - 000 - 001 - ... - 100 nBranches, nTasks := 5, 100 - for branchIdx := 0; branchIdx < nBranches; branchIdx++ { + for branchIdx := range nBranches { var taskDeps []string firstTaskName := fmt.Sprintf("b%02d", branchIdx) firstTask := v1.PipelineTask{ @@ -646,7 +648,7 @@ func TestBuildGraphWithHundredsOfTasks_Success(t *testing.T) { } tasks = append(tasks, firstTask) taskDeps = append(taskDeps, firstTaskName) - for taskIdx := 0; taskIdx < nTasks; taskIdx++ { + for taskIdx := range nTasks { taskName := fmt.Sprintf("%s-%03d", firstTaskName, taskIdx) task := v1.PipelineTask{ Name: taskName, @@ -668,7 +670,7 @@ func TestBuildGraphWithHundredsOfTasks_InvalidDAG(t *testing.T) { var tasks []v1.PipelineTask // branches with circular interdependencies nBranches, nTasks := 5, 100 - for branchIdx := 0; branchIdx < nBranches; branchIdx++ { + for branchIdx := range nBranches { depBranchIdx := branchIdx + 1 if depBranchIdx == nBranches { depBranchIdx = 0 @@ -682,7 +684,7 @@ func TestBuildGraphWithHundredsOfTasks_InvalidDAG(t *testing.T) { } tasks = append(tasks, firstTask) taskDeps = append(taskDeps, firstTaskName) - for taskIdx := 0; taskIdx < nTasks; taskIdx++ { + for taskIdx := range nTasks { taskName := fmt.Sprintf("%s-%03d", firstTaskName, taskIdx) task := v1.PipelineTask{ Name: taskName, @@ -799,37 +801,38 @@ func TestFindCyclesInDependencies(t *testing.T) { name string deps map[string][]string err string - }{{ - name: "valid-empty-deps", - deps: map[string][]string{ - "a": {}, - "b": {"c", "d"}, - "c": {}, - "d": {}, - }, - }, { - name: "self-link", - deps: map[string][]string{ - "a": {"a"}, - }, - err: `task "a" depends on "a"`, - }, { - name: "interdependent-tasks", - deps: map[string][]string{ - "a": {"b"}, - "b": {"a"}, - }, - err: `task "a" depends on "b"`, - }, { - name: "multiple-cycles", - deps: map[string][]string{ - "a": {"b", "c"}, - "b": {"a"}, - "c": {"d"}, - "d": {"a", "b"}, + }{ + { + name: "valid-empty-deps", + deps: map[string][]string{ + "a": {}, + "b": {"c", "d"}, + "c": {}, + "d": {}, + }, + }, { + name: "self-link", + deps: map[string][]string{ + "a": {"a"}, + }, + err: `task "a" depends on "a"`, + }, { + name: "interdependent-tasks", + deps: map[string][]string{ + "a": {"b"}, + "b": {"a"}, + }, + err: `task "a" depends on "b"`, + }, { + name: "multiple-cycles", + deps: map[string][]string{ + "a": {"b", "c"}, + "b": {"a"}, + "c": {"d"}, + "d": {"a", "b"}, + }, + err: `task "a" depends on "b", "c"`, }, - err: `task "a" depends on "b", "c"`, - }, } for _, tc := range tcs { t.Run(tc.name, func(t *testing.T) { diff --git a/pkg/reconciler/pipelinerun/affinity_assistant_test.go b/pkg/reconciler/pipelinerun/affinity_assistant_test.go index d20a18526c0..15c721899a8 100644 --- a/pkg/reconciler/pipelinerun/affinity_assistant_test.go +++ b/pkg/reconciler/pipelinerun/affinity_assistant_test.go @@ -49,11 +49,15 @@ import ( _ "knative.dev/pkg/system/testing" // Setup system.Namespace() ) -var podSpecFilter cmp.Option = cmpopts.IgnoreFields(corev1.PodSpec{}, "Containers", "Affinity") -var podTemplateSpecFilter cmp.Option = cmpopts.IgnoreFields(corev1.PodTemplateSpec{}, "ObjectMeta") +var ( + podSpecFilter cmp.Option = cmpopts.IgnoreFields(corev1.PodSpec{}, "Containers", "Affinity") + podTemplateSpecFilter cmp.Option = cmpopts.IgnoreFields(corev1.PodTemplateSpec{}, "ObjectMeta") +) -var workspacePVCName = "test-workspace-pvc" -var workspaceVolumeClaimTemplateName = "test-workspace-vct" +var ( + workspacePVCName = "test-workspace-pvc" + workspaceVolumeClaimTemplateName = "test-workspace-vct" +) var testPRWithPVC = &v1.PipelineRun{ TypeMeta: metav1.TypeMeta{Kind: "PipelineRun"}, @@ -69,6 +73,7 @@ var testPRWithPVC = &v1.PipelineRun{ }}, }, } + var testPRWithVolumeClaimTemplate = &v1.PipelineRun{ TypeMeta: metav1.TypeMeta{Kind: "PipelineRun"}, ObjectMeta: metav1.ObjectMeta{ @@ -81,23 +86,27 @@ var testPRWithVolumeClaimTemplate = &v1.PipelineRun{ }}, }, } + var testPRWithVolumeClaimTemplateAndPVC = &v1.PipelineRun{ TypeMeta: metav1.TypeMeta{Kind: "PipelineRun"}, ObjectMeta: metav1.ObjectMeta{ Name: "pipelinerun-with-volumeClaimTemplate-and-pvc", }, Spec: v1.PipelineRunSpec{ - Workspaces: []v1.WorkspaceBinding{{ - Name: workspaceVolumeClaimTemplateName, - VolumeClaimTemplate: &corev1.PersistentVolumeClaim{}, - }, { - Name: workspacePVCName, - PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{ - ClaimName: "myclaim", - }}, + Workspaces: []v1.WorkspaceBinding{ + { + Name: workspaceVolumeClaimTemplateName, + VolumeClaimTemplate: &corev1.PersistentVolumeClaim{}, + }, { + Name: workspacePVCName, + PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{ + ClaimName: "myclaim", + }, + }, }, }, } + var testPRWithEmptyDir = &v1.PipelineRun{ ObjectMeta: metav1.ObjectMeta{Name: "pipelinerun-with-emptyDir"}, Spec: v1.PipelineRunSpec{ @@ -317,7 +326,8 @@ func TestCreateOrUpdateAffinityAssistantsAndPVCsPerWorkspaceOrDisabled(t *testin }, }}, }, - }}, { + }, + }, { Replicas: &replicas, Selector: &metav1.LabelSelector{ MatchLabels: map[string]string{ @@ -345,7 +355,6 @@ func TestCreateOrUpdateAffinityAssistantsAndPVCsPerWorkspaceOrDisabled(t *testin }} for _, tc := range tests { - tc := tc t.Run(tc.name, func(t *testing.T) { ctx := context.Background() kubeClientSet := fakek8s.NewSimpleClientset() @@ -684,7 +693,8 @@ func TestMergedPodTemplatesArePropagatedToAffinityAssistant(t *testing.T) { {Name: "reg-creds"}, {Name: "alt-creds"}, }, - }}, + }, + }, }, } @@ -731,7 +741,8 @@ func TestOnlySelectPodTemplateFieldsArePropagatedToAffinityAssistant(t *testing. IP: "1.2.3.4", Hostnames: []string{"localhost"}, }}, - }}, + }, + }, }, } diff --git a/pkg/reconciler/pipelinerun/cancel_test.go b/pkg/reconciler/pipelinerun/cancel_test.go index 72ab2e5ce04..0d1baa7e25d 100644 --- a/pkg/reconciler/pipelinerun/cancel_test.go +++ b/pkg/reconciler/pipelinerun/cancel_test.go @@ -295,7 +295,6 @@ func TestCancelPipelineRun(t *testing.T) { wantErr: true, }} for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { d := test.Data{ PipelineRuns: []*v1.PipelineRun{tc.pipelineRun}, @@ -367,37 +366,38 @@ func TestGetChildObjectsFromPRStatusForTaskNames(t *testing.T) { expectedRunNames []string expectedCustomRunNames []string hasError bool - }{{ - name: "beta custom tasks", - prStatus: v1.PipelineRunStatus{PipelineRunStatusFields: v1.PipelineRunStatusFields{ - ChildReferences: []v1.ChildStatusReference{{ - TypeMeta: runtime.TypeMeta{ - APIVersion: v1beta1.SchemeGroupVersion.String(), - Kind: customRun, - }, - Name: "r1", - PipelineTaskName: "run-1", + }{ + { + name: "beta custom tasks", + prStatus: v1.PipelineRunStatus{PipelineRunStatusFields: v1.PipelineRunStatusFields{ + ChildReferences: []v1.ChildStatusReference{{ + TypeMeta: runtime.TypeMeta{ + APIVersion: v1beta1.SchemeGroupVersion.String(), + Kind: customRun, + }, + Name: "r1", + PipelineTaskName: "run-1", + }}, }}, - }}, - expectedCustomRunNames: []string{"r1"}, - hasError: false, - }, { - name: "unknown kind", - prStatus: v1.PipelineRunStatus{PipelineRunStatusFields: v1.PipelineRunStatusFields{ - ChildReferences: []v1.ChildStatusReference{{ - TypeMeta: runtime.TypeMeta{ - APIVersion: "v1", - Kind: "UnknownKind", - }, - Name: "u1", - PipelineTaskName: "unknown-1", + expectedCustomRunNames: []string{"r1"}, + hasError: false, + }, { + name: "unknown kind", + prStatus: v1.PipelineRunStatus{PipelineRunStatusFields: v1.PipelineRunStatusFields{ + ChildReferences: []v1.ChildStatusReference{{ + TypeMeta: runtime.TypeMeta{ + APIVersion: "v1", + Kind: "UnknownKind", + }, + Name: "u1", + PipelineTaskName: "unknown-1", + }}, }}, - }}, - expectedTRNames: nil, - expectedRunNames: nil, - expectedCustomRunNames: nil, - hasError: true, - }, + expectedTRNames: nil, + expectedRunNames: nil, + expectedCustomRunNames: nil, + hasError: true, + }, } for _, tc := range testCases { diff --git a/pkg/reconciler/pipelinerun/pipelinerun_test.go b/pkg/reconciler/pipelinerun/pipelinerun_test.go index ee053617c36..447fee02d63 100644 --- a/pkg/reconciler/pipelinerun/pipelinerun_test.go +++ b/pkg/reconciler/pipelinerun/pipelinerun_test.go @@ -226,7 +226,7 @@ func getTaskRuns(ctx context.Context, t *testing.T, clients test.Clients, namesp outputs := make(map[string]*v1.TaskRun) for _, item := range taskRuns.Items { tr := item - outputs[tr.Name] = &tr + outputs[item.Name] = &tr } return outputs diff --git a/pkg/reconciler/pipelinerun/resources/apply.go b/pkg/reconciler/pipelinerun/resources/apply.go index b971d94d4f8..046487c2637 100644 --- a/pkg/reconciler/pipelinerun/resources/apply.go +++ b/pkg/reconciler/pipelinerun/resources/apply.go @@ -39,13 +39,11 @@ const ( objectIndividualVariablePattern = "params.%s.%s" ) -var ( - paramPatterns = []string{ - "params.%s", - "params[%q]", - "params['%s']", - } -) +var paramPatterns = []string{ + "params.%s", + "params[%q]", + "params['%s']", +} // ApplyParameters applies the params from a PipelineRun.Params to a PipelineSpec. func ApplyParameters(ctx context.Context, p *v1.PipelineSpec, pr *v1.PipelineRun) *v1.PipelineSpec { @@ -63,7 +61,7 @@ func ApplyParameters(ctx context.Context, p *v1.PipelineSpec, pr *v1.PipelineRun switch p.Default.Type { case v1.ParamTypeArray: for _, pattern := range paramPatterns { - for i := 0; i < len(p.Default.ArrayVal); i++ { + for i := range len(p.Default.ArrayVal) { stringReplacements[fmt.Sprintf(pattern+"[%d]", p.Name, i)] = p.Default.ArrayVal[i] } arrayReplacements[fmt.Sprintf(pattern, p.Name)] = p.Default.ArrayVal @@ -111,7 +109,7 @@ func paramsFromPipelineRun(ctx context.Context, pr *v1.PipelineRun) (map[string] switch p.Value.Type { case v1.ParamTypeArray: for _, pattern := range paramPatterns { - for i := 0; i < len(p.Value.ArrayVal); i++ { + for i := range len(p.Value.ArrayVal) { stringReplacements[fmt.Sprintf(pattern+"[%d]", p.Name, i)] = p.Value.ArrayVal[i] } arrayReplacements[fmt.Sprintf(pattern, p.Name)] = p.Value.ArrayVal @@ -454,7 +452,8 @@ func ApplyTaskResultsToPipelineResults( results []v1.PipelineResult, taskRunResults map[string][]v1.TaskRunResult, customTaskResults map[string][]v1beta1.CustomRunResult, - taskstatus map[string]string) ([]v1.PipelineRunResult, error) { + taskstatus map[string]string, +) ([]v1.PipelineRunResult, error) { var runResults []v1.PipelineRunResult var invalidPipelineResults []string diff --git a/pkg/reconciler/pipelinerun/resources/apply_test.go b/pkg/reconciler/pipelinerun/resources/apply_test.go index e7d40c95d2e..f0ec7ee9beb 100644 --- a/pkg/reconciler/pipelinerun/resources/apply_test.go +++ b/pkg/reconciler/pipelinerun/resources/apply_test.go @@ -1772,7 +1772,6 @@ func TestApplyParameters(t *testing.T) { }, }, } { - tt := tt // capture range variable t.Run(tt.name, func(t *testing.T) { t.Parallel() ctx := context.Background() @@ -2082,7 +2081,6 @@ func TestApplyParameters_ArrayIndexing(t *testing.T) { }, }, } { - tt := tt // capture range variable t.Run(tt.name, func(t *testing.T) { t.Parallel() run := &v1.PipelineRun{ @@ -2335,7 +2333,6 @@ func TestApplyReplacementsMatrix(t *testing.T) { }, }, } { - tt := tt // capture range variable t.Run(tt.name, func(t *testing.T) { t.Parallel() run := &v1.PipelineRun{ diff --git a/pkg/reconciler/pipelinerun/resources/pipelineref_test.go b/pkg/reconciler/pipelinerun/resources/pipelineref_test.go index 87d48306cf5..754ada0a964 100644 --- a/pkg/reconciler/pipelinerun/resources/pipelineref_test.go +++ b/pkg/reconciler/pipelinerun/resources/pipelineref_test.go @@ -563,7 +563,6 @@ func TestGetPipelineFunc_RemoteResolutionInvalidData(t *testing.T) { } } -//nolint:musttag func TestGetPipelineFunc_V1beta1Pipeline_VerifyNoError(t *testing.T) { ctx := context.Background() signer, _, k8sclient, vps := test.SetupVerificationPolicies(t) @@ -768,7 +767,6 @@ func TestGetPipelineFunc_V1beta1Pipeline_VerifyNoError(t *testing.T) { } } -//nolint:musttag func TestGetPipelineFunc_V1beta1Pipeline_VerifyError(t *testing.T) { ctx := context.Background() tektonclient := fake.NewSimpleClientset() @@ -888,7 +886,6 @@ func TestGetPipelineFunc_V1beta1Pipeline_VerifyError(t *testing.T) { } } -//nolint:musttag func TestGetPipelineFunc_V1Pipeline_VerifyNoError(t *testing.T) { ctx := context.Background() signer, _, k8sclient, vps := test.SetupVerificationPolicies(t) @@ -1101,7 +1098,6 @@ func TestGetPipelineFunc_V1Pipeline_VerifyNoError(t *testing.T) { } } -//nolint:musttag func TestGetPipelineFunc_V1Pipeline_VerifyError(t *testing.T) { ctx := context.Background() tektonclient := fake.NewSimpleClientset() @@ -1218,7 +1214,6 @@ func TestGetPipelineFunc_V1Pipeline_VerifyError(t *testing.T) { } } -//nolint:musttag func TestGetPipelineFunc_GetFuncError(t *testing.T) { ctx := context.Background() tektonclient := fake.NewSimpleClientset() diff --git a/pkg/reconciler/pipelinerun/resources/pipelinerunresolution.go b/pkg/reconciler/pipelinerun/resources/pipelinerunresolution.go index 182a347a10c..dde3dd6bc0e 100644 --- a/pkg/reconciler/pipelinerun/resources/pipelinerunresolution.go +++ b/pkg/reconciler/pipelinerun/resources/pipelinerunresolution.go @@ -713,7 +713,7 @@ func getNewRunNames(ptName, prName string, numberOfRuns int) []string { return append(taskRunNames, taskRunName) } // For a matrix we append i to then end of the fanned out TaskRuns "matrixed-pr-taskrun-0" - for i := 0; i < numberOfRuns; i++ { + for i := range numberOfRuns { taskRunName := kmeta.ChildName(prName, fmt.Sprintf("-%s-%d", ptName, i)) // check if the taskRun name ends with a matrix instance count if !strings.HasSuffix(taskRunName, fmt.Sprintf("-%d", i)) { diff --git a/pkg/reconciler/pipelinerun/resources/pipelinerunresolution_test.go b/pkg/reconciler/pipelinerun/resources/pipelinerunresolution_test.go index 4f101c5beac..0e289134efc 100644 --- a/pkg/reconciler/pipelinerun/resources/pipelinerunresolution_test.go +++ b/pkg/reconciler/pipelinerun/resources/pipelinerunresolution_test.go @@ -3680,7 +3680,7 @@ func TestResolvePipelineRunTask_WithMatrix(t *testing.T) { var taskRuns []*v1.TaskRun var taskRunsNames []string taskRunsMap := map[string]*v1.TaskRun{} - for i := 0; i < 9; i++ { + for i := range 9 { trName := fmt.Sprintf("%s-%s-%d", pipelineRunName, pipelineTaskName, i) tr := &v1.TaskRun{ ObjectMeta: metav1.ObjectMeta{ @@ -3838,7 +3838,7 @@ func TestResolvePipelineRunTask_WithMatrixedCustomTask(t *testing.T) { var runs []*v1beta1.CustomRun var runNames []string runsMap := map[string]*v1beta1.CustomRun{} - for i := 0; i < 9; i++ { + for i := range 9 { runName := fmt.Sprintf("%s-%s-%d", pipelineRunName, pipelineTaskName, i) run := &v1beta1.CustomRun{ ObjectMeta: metav1.ObjectMeta{ diff --git a/pkg/reconciler/pipelinerun/resources/resultrefresolution.go b/pkg/reconciler/pipelinerun/resources/resultrefresolution.go index 73d7f9cf29a..5b15b0450e1 100644 --- a/pkg/reconciler/pipelinerun/resources/resultrefresolution.go +++ b/pkg/reconciler/pipelinerun/resources/resultrefresolution.go @@ -26,11 +26,9 @@ import ( "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" ) -var ( - // ErrInvalidTaskResultReference indicates that the reason for the failure status is that there - // is an invalid task result reference - ErrInvalidTaskResultReference = pipelineErrors.WrapUserError(errors.New("Invalid task result reference")) -) +// ErrInvalidTaskResultReference indicates that the reason for the failure status is that there +// is an invalid task result reference +var ErrInvalidTaskResultReference = pipelineErrors.WrapUserError(errors.New("Invalid task result reference")) // ResolvedResultRefs represents all of the ResolvedResultRef for a pipeline task type ResolvedResultRefs []*ResolvedResultRef @@ -195,6 +193,7 @@ func findRunResultForParam(customRun *v1beta1.CustomRun, reference *v1.ResultRef err := fmt.Errorf("%w: Could not find result with name %s for task %s", ErrInvalidTaskResultReference, reference.Result, reference.PipelineTask) return "", err } + func findTaskResultForParam(taskRun *v1.TaskRun, reference *v1.ResultRef) (v1.ResultValue, error) { results := taskRun.Status.TaskRunStatusFields.Results for _, result := range results { @@ -239,7 +238,7 @@ func (rs ResolvedResultRefs) getStringReplacements() map[string]string { for _, r := range rs { switch r.Value.Type { case v1.ParamTypeArray: - for i := 0; i < len(r.Value.ArrayVal); i++ { + for i := range len(r.Value.ArrayVal) { for _, target := range r.getReplaceTargetfromArrayIndex(i) { replacements[target] = r.Value.ArrayVal[i] } diff --git a/pkg/reconciler/pipelinerun/resources/validate_params_test.go b/pkg/reconciler/pipelinerun/resources/validate_params_test.go index 9f32d1d6290..18fcd6241e9 100644 --- a/pkg/reconciler/pipelinerun/resources/validate_params_test.go +++ b/pkg/reconciler/pipelinerun/resources/validate_params_test.go @@ -610,7 +610,6 @@ func TestValidateParamArrayIndex_valid(t *testing.T) { params: v1.Params{{Name: "second-param", Value: *v1.NewStructuredValues("second-value", "second-value-again")}}, }, } { - tt := tt // capture range variable t.Run(tt.name, func(t *testing.T) { t.Parallel() err := resources.ValidateParamArrayIndex(&tt.original, tt.params) @@ -837,7 +836,6 @@ func TestValidateParamArrayIndex_invalid(t *testing.T) { expected: errors.New("non-existent param references:[$(params.first-param[2]) $(params.second-param[3])]"), }, } { - tt := tt // capture range variable t.Run(tt.name, func(t *testing.T) { t.Parallel() err := resources.ValidateParamArrayIndex(&tt.original, tt.params) diff --git a/pkg/reconciler/pipelinerun/timeout_test.go b/pkg/reconciler/pipelinerun/timeout_test.go index a369aeee268..5e6955f7210 100644 --- a/pkg/reconciler/pipelinerun/timeout_test.go +++ b/pkg/reconciler/pipelinerun/timeout_test.go @@ -245,7 +245,6 @@ func TestTimeoutPipelineRun(t *testing.T) { wantErr: true, }} for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { d := test.Data{ PipelineRuns: []*v1.PipelineRun{tc.pipelineRun}, diff --git a/pkg/reconciler/taskrun/resources/apply.go b/pkg/reconciler/taskrun/resources/apply.go index cbcfc42b2ad..a76729c4994 100644 --- a/pkg/reconciler/taskrun/resources/apply.go +++ b/pkg/reconciler/taskrun/resources/apply.go @@ -199,7 +199,7 @@ func replacementsFromDefaultParams(defaults v1.ParamSpecs) (map[string]string, m switch p.Default.Type { case v1.ParamTypeArray: for _, pattern := range paramPatterns { - for i := 0; i < len(p.Default.ArrayVal); i++ { + for i := range len(p.Default.ArrayVal) { stringReplacements[fmt.Sprintf(pattern+"[%d]", p.Name, i)] = p.Default.ArrayVal[i] } arrayReplacements[fmt.Sprintf(pattern, p.Name)] = p.Default.ArrayVal @@ -234,7 +234,7 @@ func replacementsFromParams(params v1.Params) (map[string]string, map[string][]s switch p.Value.Type { case v1.ParamTypeArray: for _, pattern := range paramPatterns { - for i := 0; i < len(p.Value.ArrayVal); i++ { + for i := range len(p.Value.ArrayVal) { stringReplacements[fmt.Sprintf(pattern+"[%d]", p.Name, i)] = p.Value.ArrayVal[i] } arrayReplacements[fmt.Sprintf(pattern, p.Name)] = p.Value.ArrayVal @@ -422,8 +422,7 @@ func ApplyStepExitCodePath(spec *v1.TaskSpec) *v1.TaskSpec { stringReplacements := map[string]string{} for i, step := range spec.Steps { - stringReplacements[fmt.Sprintf("steps.%s.exitCode.path", pod.StepName(step.Name, i))] = - filepath.Join(pipeline.StepsDir, pod.StepName(step.Name, i), "exitCode") + stringReplacements[fmt.Sprintf("steps.%s.exitCode.path", pod.StepName(step.Name, i))] = filepath.Join(pipeline.StepsDir, pod.StepName(step.Name, i), "exitCode") } return ApplyReplacements(spec, stringReplacements, map[string][]string{}, map[string]map[string]string{}) } diff --git a/pkg/reconciler/taskrun/resources/taskref_test.go b/pkg/reconciler/taskrun/resources/taskref_test.go index 9bc388fdb85..b5c370b039f 100644 --- a/pkg/reconciler/taskrun/resources/taskref_test.go +++ b/pkg/reconciler/taskrun/resources/taskref_test.go @@ -1325,7 +1325,6 @@ func TestGetPipelineFunc_RemoteResolutionInvalidData(t *testing.T) { } } -//nolint:musttag func TestGetTaskFunc_V1beta1Task_VerifyNoError(t *testing.T) { ctx := context.Background() signer, _, k8sclient, vps := test.SetupVerificationPolicies(t) @@ -1460,7 +1459,6 @@ func TestGetTaskFunc_V1beta1Task_VerifyNoError(t *testing.T) { } } -//nolint:musttag func TestGetTaskFunc_V1beta1Task_VerifyError(t *testing.T) { ctx := context.Background() signer, _, k8sclient, vps := test.SetupVerificationPolicies(t) @@ -1581,7 +1579,6 @@ func TestGetTaskFunc_V1beta1Task_VerifyError(t *testing.T) { } } -//nolint:musttag func TestGetTaskFunc_V1Task_VerifyNoError(t *testing.T) { ctx := context.Background() signer, _, k8sclient, vps := test.SetupVerificationPolicies(t) @@ -1726,7 +1723,6 @@ func TestGetTaskFunc_V1Task_VerifyNoError(t *testing.T) { } } -//nolint:musttag func TestGetTaskFunc_V1Task_VerifyError(t *testing.T) { ctx := context.Background() signer, _, k8sclient, vps := test.SetupVerificationPolicies(t) @@ -1842,7 +1838,6 @@ func TestGetTaskFunc_V1Task_VerifyError(t *testing.T) { } } -//nolint:musttag func TestGetTaskFunc_GetFuncError(t *testing.T) { ctx := context.Background() _, k8sclient, vps := test.SetupMatchAllVerificationPolicies(t, "trusted-resources") diff --git a/pkg/reconciler/taskrun/taskrun_test.go b/pkg/reconciler/taskrun/taskrun_test.go index bd4c4d150c2..8f4e818f6de 100644 --- a/pkg/reconciler/taskrun/taskrun_test.go +++ b/pkg/reconciler/taskrun/taskrun_test.go @@ -5857,7 +5857,7 @@ func podVolumeMounts(idx, totalSteps int) []corev1.VolumeMount { MountPath: "/tekton/bin", ReadOnly: true, }) - for i := 0; i < totalSteps; i++ { + for i := range totalSteps { mnts = append(mnts, corev1.VolumeMount{ Name: fmt.Sprintf("tekton-internal-run-%d", i), MountPath: filepath.Join("/tekton/run", strconv.Itoa(i)), diff --git a/pkg/taskrunmetrics/metrics.go b/pkg/taskrunmetrics/metrics.go index 594ac04fc3b..b9c705cf7f9 100644 --- a/pkg/taskrunmetrics/metrics.go +++ b/pkg/taskrunmetrics/metrics.go @@ -346,8 +346,10 @@ func MetricsOnStore(logger *zap.SugaredLogger) func(name string, } func pipelinerunInsertTag(pipeline, pipelinerun string) []tag.Mutator { - return []tag.Mutator{tag.Insert(pipelineTag, pipeline), - tag.Insert(pipelinerunTag, pipelinerun)} + return []tag.Mutator{ + tag.Insert(pipelineTag, pipeline), + tag.Insert(pipelinerunTag, pipelinerun), + } } func pipelineInsertTag(pipeline, pipelinerun string) []tag.Mutator { @@ -355,8 +357,10 @@ func pipelineInsertTag(pipeline, pipelinerun string) []tag.Mutator { } func taskrunInsertTag(task, taskrun string) []tag.Mutator { - return []tag.Mutator{tag.Insert(taskTag, task), - tag.Insert(taskrunTag, taskrun)} + return []tag.Mutator{ + tag.Insert(taskTag, task), + tag.Insert(taskrunTag, taskrun), + } } func taskInsertTag(task, taskrun string) []tag.Mutator { @@ -509,14 +513,14 @@ func (r *Recorder) RunningTaskRuns(ctx context.Context, lister listers.TaskRunLi if addNamespaceLabelToQuotaThrottleMetric { mutators = []tag.Mutator{tag.Insert(namespaceTag, ns)} } - ctx, err = tag.New(ctx, mutators...) + ctx, err := tag.New(ctx, mutators...) if err != nil { return err } metrics.Record(ctx, runningTRsThrottledByQuota.M(float64(cnt))) } for ns, cnt := range trsThrottledByNode { - ctx, err = tag.New(ctx, []tag.Mutator{tag.Insert(namespaceTag, ns)}...) + ctx, err := tag.New(ctx, []tag.Mutator{tag.Insert(namespaceTag, ns)}...) if err != nil { return err } @@ -569,8 +573,10 @@ func (r *Recorder) RecordPodLatency(ctx context.Context, pod *corev1.Pod, tr *v1 ctx, err := tag.New( ctx, - append([]tag.Mutator{tag.Insert(namespaceTag, tr.Namespace), - tag.Insert(podTag, pod.Name)}, + append([]tag.Mutator{ + tag.Insert(namespaceTag, tr.Namespace), + tag.Insert(podTag, pod.Name), + }, r.insertTaskTag(taskName, tr.Name)...)...) if err != nil { return err diff --git a/pkg/taskrunmetrics/metrics_test.go b/pkg/taskrunmetrics/metrics_test.go index b38748cb13b..94e739490ef 100644 --- a/pkg/taskrunmetrics/metrics_test.go +++ b/pkg/taskrunmetrics/metrics_test.go @@ -592,7 +592,7 @@ func TestRecordRunningTaskRunsThrottledCounts(t *testing.T) { unregisterMetrics() ctx, _ := ttesting.SetupFakeContext(t) informer := faketaskruninformer.Get(ctx) - for i := 0; i < multiplier; i++ { + for range multiplier { tr := &v1.TaskRun{ ObjectMeta: metav1.ObjectMeta{Name: names.SimpleNameGenerator.RestrictLengthWithRandomSuffix("taskrun-"), Namespace: "test"}, Status: v1.TaskRunStatus{ diff --git a/test/cancel_test.go b/test/cancel_test.go index 5b5fda9d9a3..fe99784862b 100644 --- a/test/cancel_test.go +++ b/test/cancel_test.go @@ -42,7 +42,6 @@ func TestTaskRunPipelineRunCancel(t *testing.T) { // on failure, to ensure that cancelling the PipelineRun doesn't cause // the retrying TaskRun to retry. for _, numRetries := range []int{0, 1} { - numRetries := numRetries // capture range variable specStatus := v1.PipelineRunSpecStatusCancelled t.Run(fmt.Sprintf("retries=%d,status=%s", numRetries, specStatus), func(t *testing.T) { ctx := context.Background() diff --git a/test/duplicate_test.go b/test/duplicate_test.go index 508c80735b4..6e6e4704ac5 100644 --- a/test/duplicate_test.go +++ b/test/duplicate_test.go @@ -47,7 +47,7 @@ func TestDuplicatePodTaskRun(t *testing.T) { // The number of builds generated has a direct impact on test // runtime and is traded off against proving the taskrun // reconciler's efficacy at not duplicating pods. - for i := 0; i < 5; i++ { + for range 5 { wg.Add(1) taskrunName := helpers.ObjectNameForTest(t) t.Logf("Creating taskrun %q.", taskrunName) diff --git a/test/larger_results_sidecar_logs_test.go b/test/larger_results_sidecar_logs_test.go index 5cd4845b8fc..b8482a627b3 100644 --- a/test/larger_results_sidecar_logs_test.go +++ b/test/larger_results_sidecar_logs_test.go @@ -61,7 +61,6 @@ func TestLargerResultsSidecarLogs(t *testing.T) { }} for _, td := range tds { - td := td t.Run(td.name, func(t *testing.T) { ctx := context.Background() ctx, cancel := context.WithCancel(ctx) diff --git a/test/pipelinerun_test.go b/test/pipelinerun_test.go index 64b8534f862..b859d4c3b13 100644 --- a/test/pipelinerun_test.go +++ b/test/pipelinerun_test.go @@ -91,8 +91,6 @@ spec: }} for i, td := range tds { - i := i // capture range variable - td := td // capture range variable t.Run(td.name, func(t *testing.T) { t.Parallel() ctx := context.Background() @@ -297,8 +295,6 @@ spec: }} for i, td := range tds { - i := i // capture range variable - td := td // capture range variable t.Run(td.name, func(t *testing.T) { t.Parallel() ctx := context.Background() diff --git a/test/propagated_params_test.go b/test/propagated_params_test.go index 4e615201124..8a3ebb5f6fc 100644 --- a/test/propagated_params_test.go +++ b/test/propagated_params_test.go @@ -66,7 +66,6 @@ func TestPropagatedParams(t *testing.T) { }} for _, td := range tds { - td := td t.Run(td.name, func(t *testing.T) { t.Parallel() ctx := context.Background() diff --git a/test/propagated_results_test.go b/test/propagated_results_test.go index 57fee1be165..14269c153e6 100644 --- a/test/propagated_results_test.go +++ b/test/propagated_results_test.go @@ -43,7 +43,8 @@ func TestPropagatedResults(t *testing.T) { ignorePipelineRunStatusFields := cmpopts.IgnoreFields(v1.PipelineRunStatusFields{}, "Provenance") ignoreTaskRunStatus := cmpopts.IgnoreFields(v1.TaskRunStatusFields{}, "StartTime", "CompletionTime", "Sidecars", "Provenance") requireAlphaFeatureFlag = requireAnyGate(map[string]string{ - "enable-api-fields": "alpha"}) + "enable-api-fields": "alpha", + }) type tests struct { name string @@ -58,7 +59,6 @@ func TestPropagatedResults(t *testing.T) { }} for _, td := range tds { - td := td t.Run(td.name, func(t *testing.T) { t.Parallel() ctx := context.Background() diff --git a/test/sidecar_test.go b/test/sidecar_test.go index 7e6ccb23a40..85ccf3eaec4 100644 --- a/test/sidecar_test.go +++ b/test/sidecar_test.go @@ -61,7 +61,6 @@ func TestSidecarTaskSupport(t *testing.T) { t.Parallel() for _, test := range tests { - test := test t.Run(test.desc, func(t *testing.T) { t.Parallel() diff --git a/test/stepaction_results_test.go b/test/stepaction_results_test.go index c1dd23a162b..df7ba6e658d 100644 --- a/test/stepaction_results_test.go +++ b/test/stepaction_results_test.go @@ -59,7 +59,6 @@ func TestStepResultsStepActions(t *testing.T) { }} for _, td := range tds { - td := td t.Run(td.name, func(t *testing.T) { ctx := context.Background() ctx, cancel := context.WithCancel(ctx)