-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
pipelinerun_test.go
18045 lines (17124 loc) · 497 KB
/
pipelinerun_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2019 The Tekton Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package pipelinerun
import (
"bytes"
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"strconv"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/sigstore/sigstore/pkg/signature"
"github.com/tektoncd/pipeline/pkg/apis/config"
cfgtesting "github.com/tektoncd/pipeline/pkg/apis/config/testing"
"github.com/tektoncd/pipeline/pkg/apis/pipeline"
pipelinev1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1"
v1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1"
"github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1"
"github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1"
resolutionv1beta1 "github.com/tektoncd/pipeline/pkg/apis/resolution/v1beta1"
"github.com/tektoncd/pipeline/pkg/internal/affinityassistant"
resolutionutil "github.com/tektoncd/pipeline/pkg/internal/resolution"
"github.com/tektoncd/pipeline/pkg/reconciler/events/cloudevent"
"github.com/tektoncd/pipeline/pkg/reconciler/events/k8sevent"
"github.com/tektoncd/pipeline/pkg/reconciler/pipeline/dag"
"github.com/tektoncd/pipeline/pkg/reconciler/pipelinerun/resources"
taskresources "github.com/tektoncd/pipeline/pkg/reconciler/taskrun/resources"
ttesting "github.com/tektoncd/pipeline/pkg/reconciler/testing"
"github.com/tektoncd/pipeline/pkg/reconciler/volumeclaim"
resolutioncommon "github.com/tektoncd/pipeline/pkg/resolution/common"
remoteresource "github.com/tektoncd/pipeline/pkg/resolution/resource"
"github.com/tektoncd/pipeline/pkg/tracing"
"github.com/tektoncd/pipeline/pkg/trustedresources"
"github.com/tektoncd/pipeline/pkg/trustedresources/verifier"
"github.com/tektoncd/pipeline/test"
"github.com/tektoncd/pipeline/test/diff"
"github.com/tektoncd/pipeline/test/names"
"github.com/tektoncd/pipeline/test/parse"
"gomodules.xyz/jsonpatch/v2"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/validation/field"
fakek8s "k8s.io/client-go/kubernetes/fake"
"k8s.io/client-go/kubernetes/typed/core/v1/fake"
ktesting "k8s.io/client-go/testing"
testing2 "k8s.io/client-go/testing"
"k8s.io/client-go/tools/record"
clock "k8s.io/utils/clock/testing"
"knative.dev/pkg/apis"
duckv1 "knative.dev/pkg/apis/duck/v1"
cminformer "knative.dev/pkg/configmap/informer"
"knative.dev/pkg/controller"
"knative.dev/pkg/kmeta"
"knative.dev/pkg/logging"
logtesting "knative.dev/pkg/logging/testing"
"knative.dev/pkg/reconciler"
"knative.dev/pkg/system"
_ "knative.dev/pkg/system/testing" // Setup system.Namespace()
"sigs.k8s.io/yaml"
)
var (
images = pipeline.Images{
EntrypointImage: "override-with-entrypoint:latest",
NopImage: "override-with-nop:latest",
ShellImage: "busybox",
}
ignoreResourceVersion = cmpopts.IgnoreFields(metav1.ObjectMeta{}, "ResourceVersion")
ignoreTypeMeta = cmpopts.IgnoreFields(metav1.TypeMeta{}, "Kind", "APIVersion")
ignoreLastTransitionTime = cmpopts.IgnoreFields(apis.Condition{}, "LastTransitionTime.Inner.Time")
ignoreStartTime = cmpopts.IgnoreFields(v1.PipelineRunStatusFields{}, "StartTime")
ignoreCompletionTime = cmpopts.IgnoreFields(v1.PipelineRunStatusFields{}, "CompletionTime")
ignoreFinallyStartTime = cmpopts.IgnoreFields(v1.PipelineRunStatusFields{}, "FinallyStartTime")
ignoreProvenance = cmpopts.IgnoreFields(v1.PipelineRunStatusFields{}, "Provenance")
trueb = true
simpleHelloWorldTask = &v1.Task{ObjectMeta: baseObjectMeta("hello-world", "foo")}
simpleSomeTask = &v1.Task{ObjectMeta: baseObjectMeta("some-task", "foo")}
simpleHelloWorldPipeline = &v1.Pipeline{
ObjectMeta: baseObjectMeta("test-pipeline", "foo"),
Spec: v1.PipelineSpec{
Tasks: []v1.PipelineTask{{
Name: "hello-world-1",
TaskRef: &v1.TaskRef{
Name: "hello-world",
},
}},
},
}
now = time.Date(2022, time.January, 1, 0, 0, 0, 0, time.UTC)
testClock = clock.NewFakePassiveClock(now)
)
const (
apiFieldsFeatureFlag = "enable-api-fields"
ociBundlesFeatureFlag = "enable-tekton-oci-bundles"
maxMatrixCombinationsCountFlag = "default-max-matrix-combinations-count"
disableAffinityAssistantFlag = "disable-affinity-assistant"
)
type PipelineRunTest struct {
test.Data `json:"inline"`
Test *testing.T
TestAssets test.Assets
Cancel func()
}
// getPipelineRunController returns an instance of the PipelineRun controller/reconciler that has been seeded with
// d, where d represents the state of the system (existing resources) needed for the test.
func getPipelineRunController(t *testing.T, d test.Data) (test.Assets, func()) {
t.Helper()
return initializePipelineRunControllerAssets(t, d, pipeline.Options{Images: images})
}
// initiailizePipelinerunControllerAssets is a shared helper for
// controller initialization.
func initializePipelineRunControllerAssets(t *testing.T, d test.Data, opts pipeline.Options) (test.Assets, func()) {
t.Helper()
ctx, _ := ttesting.SetupFakeContext(t)
ctx = ttesting.SetupFakeCloudClientContext(ctx, d.ExpectedCloudEventCount)
ctx, cancel := context.WithCancel(ctx)
test.EnsureConfigurationConfigMapsExist(&d)
c, informers := test.SeedTestData(t, ctx, d)
configMapWatcher := cminformer.NewInformedWatcher(c.Kube, system.Namespace())
ctl := NewController(&opts, testClock)(ctx, configMapWatcher)
if la, ok := ctl.Reconciler.(reconciler.LeaderAware); ok {
if err := la.Promote(reconciler.UniversalBucket(), func(reconciler.Bucket, types.NamespacedName) {}); err != nil {
t.Fatalf("error promoting reconciler leader: %v", err)
}
}
if err := configMapWatcher.Start(ctx.Done()); err != nil {
t.Fatalf("error starting configmap watcher: %v", err)
}
return test.Assets{
Logger: logging.FromContext(ctx),
Clients: c,
Controller: ctl,
Informers: informers,
Recorder: controller.GetEventRecorder(ctx).(*record.FakeRecorder),
Ctx: ctx,
}, cancel
}
// validateTaskRunsCount ensure that there are `expectedCount` TaskRuns
// It will fatal the test if the number of TaskRuns is not `expectedCount`
func validateTaskRunsCount(t *testing.T, taskRuns map[string]*v1.TaskRun, expectedCount int) {
t.Helper()
actualCount := len(taskRuns)
if actualCount != expectedCount {
t.Fatalf("Expected %d taskruns but it has %d", expectedCount, actualCount)
}
}
// getTaskRunByName retrieves the TaskRun with the specified name from the given TaskRuns
// It will fatal the test if the name does not exist
func getTaskRunByName(t *testing.T, taskRuns map[string]*v1.TaskRun, expectedName string) *v1.TaskRun {
t.Helper()
tr, exist := taskRuns[expectedName]
if !exist {
t.Fatalf("Expected taskrun %s does not exist", expectedName)
}
return tr
}
// getTaskRunsForPipelineRun returns the set of TaskRuns associated with the input PipelineRun.
// It will fatal the test if an error occurred.
func getTaskRunsForPipelineRun(ctx context.Context, t *testing.T, clients test.Clients, namespace string, prName string) map[string]*v1.TaskRun {
t.Helper()
labelSelector := pipeline.PipelineRunLabelKey + "=" + prName
return getTaskRuns(ctx, t, clients, namespace, labelSelector)
}
// getTaskRunsForPipelineTask returns the set of TaskRuns associated with the input PipelineRun and PipelineTask
// It will fatal the test if an error occurred.
func getTaskRunsForPipelineTask(ctx context.Context, t *testing.T, clients test.Clients, namespace string, prName string, ptLabel string) map[string]*v1.TaskRun {
t.Helper()
labelSelector := pipeline.PipelineRunLabelKey + "=" + prName + "," + pipeline.PipelineTaskLabelKey + "=" + ptLabel
return getTaskRuns(ctx, t, clients, namespace, labelSelector)
}
// getTaskRuns returns the set of TaskRuns matching the label selector.
// It will fatal the test if an error occurred.
func getTaskRuns(ctx context.Context, t *testing.T, clients test.Clients, namespace string, labelSelector string) map[string]*v1.TaskRun {
t.Helper()
opt := metav1.ListOptions{
LabelSelector: labelSelector,
}
taskRuns, err := clients.Pipeline.TektonV1().TaskRuns(namespace).List(ctx, opt)
if err != nil {
t.Fatalf("failed to list taskruns, %s", err)
}
outputs := make(map[string]*v1.TaskRun)
for _, item := range taskRuns.Items {
tr := item
outputs[item.Name] = &tr
}
return outputs
}
// runTestReconcile runs "Reconcile" on a PipelineRun with one
// Task that has not been started yet. It verifies that the TaskRun is created,
// it checks the resulting API actions, status and events.
func TestReconcile(t *testing.T) {
namespace := "foo"
prName := "test-pipeline-run-success"
trName := "test-pipeline-run-success-unit-test-1"
prs := []*v1.PipelineRun{parse.MustParseV1PipelineRun(t, `
metadata:
name: test-pipeline-run-success
namespace: foo
uid: bar
spec:
params:
- name: bar
value: somethingmorefun
pipelineRef:
name: test-pipeline
taskRunTemplate:
serviceAccountName: test-sa
`)}
ps := []*v1.Pipeline{parse.MustParseV1Pipeline(t, `
metadata:
name: test-pipeline
namespace: foo
spec:
params:
- default: somethingdifferent
name: pipeline-param
type: string
- default: revision
name: rev-param
type: string
- name: bar
type: string
tasks:
- name: unit-test-2
params:
- name: foo
value: somethingfun
- name: bar
value: $(params.bar)
- name: contextRunParam
value: $(context.pipelineRun.name)
- name: contextPipelineParam
value: $(context.pipeline.name)
- name: contextRetriesParam
value: $(context.pipelineTask.retries)
runAfter:
- unit-test-1
taskRef:
name: unit-test-task
- name: unit-test-1
params:
- name: foo
value: somethingfun
- name: bar
value: $(params.bar)
- name: contextRunParam
value: $(context.pipelineRun.name)
- name: contextPipelineParam
value: $(context.pipeline.name)
- name: contextRetriesParam
value: $(context.pipelineTask.retries)
- name: param-not-found
value: $(params.notfound)
retries: 5
taskRef:
name: unit-test-task
- name: unit-test-cluster-task
params:
- name: foo
value: somethingfun
- name: bar
value: $(params.bar)
- name: contextRunParam
value: $(context.pipelineRun.name)
- name: contextPipelineParam
value: $(context.pipeline.name)
taskRef:
kind: ClusterTask
name: unit-test-cluster-task
`)}
ts := []*v1.Task{
parse.MustParseV1Task(t, `
metadata:
name: unit-test-task
namespace: foo
spec:
params:
- name: foo
type: string
- name: bar
type: string
- name: contextRunParam
type: string
- name: contextPipelineParam
type: string
- name: contextRetriesParam
type: string
`),
}
clusterTasks := []*v1beta1.ClusterTask{
parse.MustParseClusterTask(t, `
metadata:
name: unit-test-cluster-task
spec:
params:
- name: foo
type: string
- name: bar
type: string
- name: contextRunParam
type: string
- name: contextPipelineParam
type: string
`),
}
d := test.Data{
PipelineRuns: prs,
Pipelines: ps,
Tasks: ts,
ClusterTasks: clusterTasks,
ConfigMaps: []*corev1.ConfigMap{newFeatureFlagsConfigMap()},
}
prt := newPipelineRunTest(t, d)
defer prt.Cancel()
wantEvents := []string{
"Normal Started",
"Normal Running Tasks Completed: 0",
}
reconciledRun, clients := prt.reconcileRun(namespace, prName, wantEvents, false)
taskRuns := getTaskRunsForPipelineRun(prt.TestAssets.Ctx, t, clients, namespace, prName)
// Ensure that there are 2 TaskRuns associated with this PipelineRun
validateTaskRunsCount(t, taskRuns, 2)
// Check that the expected TaskRun was created
actual := getTaskRunByName(t, taskRuns, trName)
expectedTaskRun := mustParseTaskRunWithObjectMeta(t,
taskRunObjectMeta(trName, namespace, prName,
"test-pipeline", "unit-test-1", false),
`
spec:
params:
- name: foo
value: somethingfun
- name: bar
value: somethingmorefun
- name: contextRunParam
value: test-pipeline-run-success
- name: contextPipelineParam
value: test-pipeline
- name: contextRetriesParam
value: "5"
- name: param-not-found
value: $(params.notfound)
retries: 5
serviceAccountName: test-sa
taskRef:
name: unit-test-task
kind: Task
`)
expectedTaskRun.Labels["tekton.dev/pipelineRunUID"] = "bar"
expectedTaskRun.OwnerReferences[0].UID = "bar"
// ignore IgnoreUnexported ignore both after and before steps fields
if d := cmp.Diff(expectedTaskRun, actual, ignoreTypeMeta, ignoreResourceVersion); d != "" {
t.Errorf("expected to see TaskRun %v created. Diff %s", expectedTaskRun, diff.PrintWantGot(d))
}
// test taskrun is able to recreate correct pipeline-pvc-name
if expectedTaskRun.GetPipelineRunPVCName() != "test-pipeline-run-success-pvc" {
t.Errorf("expected to see TaskRun PVC name set to %q created but got %s", "test-pipeline-run-success-pvc", expectedTaskRun.GetPipelineRunPVCName())
}
// This PipelineRun is in progress now and the status should reflect that
checkPipelineRunConditionStatusAndReason(t, reconciledRun, corev1.ConditionUnknown, v1.PipelineRunReasonRunning.String())
tr1Name := "test-pipeline-run-success-unit-test-1"
tr2Name := "test-pipeline-run-success-unit-test-cluster-task"
verifyTaskRunStatusesCount(t, reconciledRun.Status, 2)
verifyTaskRunStatusesNames(t, reconciledRun.Status, tr1Name, tr2Name)
}
// TestReconcile_V1Beta1CustomTask runs "Reconcile" on a PipelineRun with one Custom
// Task reference that has not been run yet
// It verifies that the CustomRun is created, it checks the resulting API actions, status and events.
func TestReconcile_V1Beta1CustomTask(t *testing.T) {
names.TestingSeed()
const pipelineRunName = "test-pipelinerun"
const namespace = "namespace"
simpleCustomTaskPRYAML := `metadata:
name: test-pipelinerun
namespace: namespace
uid: bar
spec:
pipelineSpec:
tasks:
- name: custom-task
params:
- name: param1
value: value1
retries: 3
taskRef:
apiVersion: example.dev/v0
kind: Example
`
simpleCustomTaskWantRunYAML := `metadata:
annotations: {}
labels:
tekton.dev/memberOf: tasks
tekton.dev/pipeline: test-pipelinerun
tekton.dev/pipelineRun: test-pipelinerun
tekton.dev/pipelineTask: custom-task
tekton.dev/pipelineRunUID: bar
name: test-pipelinerun-custom-task
namespace: namespace
ownerReferences:
- apiVersion: tekton.dev/v1
blockOwnerDeletion: true
controller: true
kind: PipelineRun
name: test-pipelinerun
uid: bar
spec:
params:
- name: param1
value: value1
customRef:
apiVersion: example.dev/v0
kind: Example
retries: 3
serviceAccountName: default
`
tcs := []struct {
name string
pr *v1.PipelineRun
wantRun *v1beta1.CustomRun
}{{
name: "simple custom task with taskRef",
pr: parse.MustParseV1PipelineRun(t, simpleCustomTaskPRYAML),
wantRun: parse.MustParseCustomRun(t, simpleCustomTaskWantRunYAML),
}, {
name: "simple custom task with taskSpec",
pr: parse.MustParseV1PipelineRun(t, `
metadata:
name: test-pipelinerun
namespace: namespace
spec:
pipelineSpec:
tasks:
- name: custom-task
params:
- name: param1
value: value1
- name: contextPipelineParam
value: $(context.pipeline.name)
taskSpec:
apiVersion: example.dev/v0
kind: Example
metadata:
labels:
test-label: test
spec:
field1: 123
field2: value
`),
wantRun: mustParseCustomRunWithObjectMeta(t,
taskRunObjectMeta("test-pipelinerun-custom-task", "namespace", "test-pipelinerun", "test-pipelinerun", "custom-task", false),
`
spec:
params:
- name: param1
value: value1
- name: contextPipelineParam
value: test-pipelinerun
serviceAccountName: default
customSpec:
apiVersion: example.dev/v0
kind: Example
metadata:
labels:
test-label: test
spec:
field1: 123
field2: value
`),
}, {
name: "custom task with workspace",
pr: parse.MustParseV1PipelineRun(t, `
metadata:
name: test-pipelinerun
namespace: namespace
spec:
pipelineSpec:
tasks:
- name: custom-task
taskRef:
apiVersion: example.dev/v0
kind: Example
workspaces:
- name: taskws
subPath: bar
workspace: pipelinews
workspaces:
- name: pipelinews
workspaces:
- name: pipelinews
persistentVolumeClaim:
claimName: myclaim
subPath: foo
`),
wantRun: mustParseCustomRunWithObjectMeta(t,
taskRunObjectMetaWithAnnotations("test-pipelinerun-custom-task", "namespace", "test-pipelinerun",
"test-pipelinerun", "custom-task", false, map[string]string{
"pipeline.tekton.dev/affinity-assistant": GetAffinityAssistantName("pipelinews", pipelineRunName),
}),
`
spec:
customRef:
apiVersion: example.dev/v0
kind: Example
serviceAccountName: default
workspaces:
- name: taskws
persistentVolumeClaim:
claimName: myclaim
subPath: foo/bar
`),
}}
for _, tc := range tcs {
t.Run(tc.name, func(t *testing.T) {
d := test.Data{
PipelineRuns: []*v1.PipelineRun{tc.pr},
}
prt := newPipelineRunTest(t, d)
defer prt.Cancel()
wantEvents := []string{
"Normal Started",
"Normal Running Tasks Completed: 0",
}
reconciledRun, clients := prt.reconcileRun(namespace, pipelineRunName, wantEvents, false)
actions := clients.Pipeline.Actions()
if len(actions) < 2 {
t.Fatalf("Expected client to have at least two action implementation but it has %d", len(actions))
}
// Check that the expected CustomRun was created.
actual := actions[0].(ktesting.CreateAction).GetObject()
// Ignore the TypeMeta field, because parse.MustParseCustomRun automatically populates it but the "actual" CustomRun won't have it.
if d := cmp.Diff(tc.wantRun, actual, cmpopts.IgnoreFields(v1beta1.CustomRun{}, "TypeMeta"), cmpopts.EquateEmpty()); d != "" {
t.Errorf("expected to see CustomRun created: %s", diff.PrintWantGot(d))
}
// This PipelineRun is in progress now and the status should reflect that
checkPipelineRunConditionStatusAndReason(t, reconciledRun, corev1.ConditionUnknown, v1.PipelineRunReasonRunning.String())
verifyCustomRunOrRunStatusesCount(t, customRun, reconciledRun.Status, 1)
verifyCustomRunOrRunStatusesNames(t, customRun, reconciledRun.Status, tc.wantRun.Name)
})
}
}
func TestReconcile_PipelineSpecTaskSpec(t *testing.T) {
// TestReconcile_PipelineSpecTaskSpec runs "Reconcile" on a PipelineRun that has an embedded PipelineSpec that has an embedded TaskSpec.
// It verifies that a TaskRun is created, it checks the resulting API actions, status and events.
names.TestingSeed()
namespace := "foo"
prName := "test-pipeline-run-success"
trName := "test-pipeline-run-success-unit-test-task-spec"
prs := []*v1.PipelineRun{
parse.MustParseV1PipelineRun(t, `
metadata:
name: test-pipeline-run-success
namespace: foo
spec:
pipelineRef:
name: test-pipeline
`),
}
ps := []*v1.Pipeline{
parse.MustParseV1Pipeline(t, `
metadata:
name: test-pipeline
namespace: foo
spec:
tasks:
- name: unit-test-task-spec
taskSpec:
steps:
- name: mystep
image: myimage
`),
}
d := test.Data{
PipelineRuns: prs,
Pipelines: ps,
ConfigMaps: []*corev1.ConfigMap{newFeatureFlagsConfigMap()},
}
prt := newPipelineRunTest(t, d)
defer prt.Cancel()
wantEvents := []string{
"Normal Started",
"Normal Running Tasks Completed: 0",
}
reconciledRun, clients := prt.reconcileRun(namespace, prName, wantEvents, false)
// Check that the expected TaskRun was created
taskRuns := getTaskRunsForPipelineRun(prt.TestAssets.Ctx, t, clients, namespace, prName)
validateTaskRunsCount(t, taskRuns, 1)
actual := getTaskRunByName(t, taskRuns, trName)
expectedTaskRun := parse.MustParseV1TaskRun(t, fmt.Sprintf(`
spec:
taskSpec:
steps:
- name: mystep
image: myimage
serviceAccountName: %s
`, config.DefaultServiceAccountValue))
expectedTaskRun.ObjectMeta = taskRunObjectMeta(trName, "foo", "test-pipeline-run-success", "test-pipeline", "unit-test-task-spec", false)
// ignore IgnoreUnexported ignore both after and before steps fields
if d := cmp.Diff(expectedTaskRun, actual, ignoreTypeMeta, ignoreResourceVersion, cmpopts.SortSlices(func(x, y v1.TaskSpec) bool { return len(x.Steps) == len(y.Steps) })); d != "" {
t.Errorf("expected to see TaskRun %v created. Diff %s", expectedTaskRun, diff.PrintWantGot(d))
}
// test taskrun is able to recreate correct pipeline-pvc-name
if expectedTaskRun.GetPipelineRunPVCName() != "test-pipeline-run-success-pvc" {
t.Errorf("expected to see TaskRun PVC name set to %q created but got %s", "test-pipeline-run-success-pvc", expectedTaskRun.GetPipelineRunPVCName())
}
verifyTaskRunStatusesCount(t, reconciledRun.Status, 1)
verifyTaskRunStatusesNames(t, reconciledRun.Status, trName)
}
// TestReconcile_InvalidPipelineRuns runs "Reconcile" on several PipelineRuns that are invalid in different ways.
// It verifies that reconcile fails, how it fails and which events are triggered.
func TestReconcile_InvalidPipelineRuns(t *testing.T) {
ts := []*v1.Task{
parse.MustParseV1Task(t, `
metadata:
name: a-task-that-exists
namespace: foo
`),
parse.MustParseV1Task(t, `
metadata:
name: a-task-that-needs-params
namespace: foo
spec:
params:
- name: some-param
`),
parse.MustParseV1Task(t, fmt.Sprintf(`
metadata:
name: a-task-that-needs-array-params
namespace: foo
spec:
params:
- name: some-param
type: %s
`, v1.ParamTypeArray)),
parse.MustParseV1Task(t, fmt.Sprintf(`
metadata:
name: a-task-that-needs-object-params
namespace: foo
spec:
params:
- name: some-param
type: %s
properties:
key1: {}
key2: {}
`, v1.ParamTypeObject)),
}
ps := []*v1.Pipeline{
parse.MustParseV1Pipeline(t, `
metadata:
name: pipeline-missing-tasks
namespace: foo
spec:
tasks:
- name: myspecialtask
taskRef:
name: sometask
`),
parse.MustParseV1Pipeline(t, `
metadata:
name: a-pipeline-without-params
namespace: foo
spec:
tasks:
- name: some-task
taskRef:
name: a-task-that-needs-params
`),
parse.MustParseV1Pipeline(t, `
metadata:
name: a-pipeline-that-should-be-caught-by-admission-control
namespace: foo
spec:
tasks:
- name: some-task
taskRef:
name: a-task-that-exists
`),
parse.MustParseV1Pipeline(t, fmt.Sprintf(`
metadata:
name: a-pipeline-with-array-params
namespace: foo
spec:
params:
- name: some-param
type: %s
tasks:
- name: some-task
taskRef:
name: a-task-that-needs-array-params
`, v1.ParamTypeArray)),
parse.MustParseV1Pipeline(t, fmt.Sprintf(`
metadata:
name: a-pipeline-with-array-indexing-params
namespace: foo
spec:
params:
- name: some-param
type: %s
tasks:
- name: some-task
taskRef:
name: a-task-that-needs-array-params
params:
- name: param
value: "$(params.some-param[2])"
`, v1.ParamTypeArray)),
parse.MustParseV1Pipeline(t, fmt.Sprintf(`
metadata:
name: a-pipeline-with-object-params
namespace: foo
spec:
params:
- name: some-param
type: %s
properties:
key1: {type: string}
key2: {type: string}
tasks:
- name: some-task
taskRef:
name: a-task-that-needs-object-params
`, v1.ParamTypeObject)),
}
for _, tc := range []struct {
name string
pipelineRun *v1.PipelineRun
reason string
hasNoDefaultLabels bool
permanentError bool
wantEvents []string
}{{
name: "invalid-pipeline-shd-be-stop-reconciling",
pipelineRun: parse.MustParseV1PipelineRun(t, `
metadata:
name: invalid-pipeline
namespace: foo
spec:
pipelineRef:
name: pipeline-not-exist
`),
reason: v1.PipelineRunReasonCouldntGetPipeline.String(),
hasNoDefaultLabels: true,
permanentError: true,
wantEvents: []string{
"Normal Started",
"Warning Failed Error retrieving pipeline for pipelinerun",
},
}, {
name: "invalid-pipeline-run-missing-tasks-shd-stop-reconciling",
pipelineRun: parse.MustParseV1PipelineRun(t, `
metadata:
name: pipelinerun-missing-tasks
namespace: foo
spec:
pipelineRef:
name: pipeline-missing-tasks
`),
reason: v1.PipelineRunReasonCouldntGetTask.String(),
permanentError: true,
wantEvents: []string{
"Normal Started",
"Warning Failed Pipeline foo/pipeline-missing-tasks can't be Run",
},
}, {
name: "invalid-pipeline-run-params-dont-exist-shd-stop-reconciling",
pipelineRun: parse.MustParseV1PipelineRun(t, `
metadata:
name: pipeline-params-dont-exist
namespace: foo
spec:
pipelineRef:
name: a-pipeline-without-params
`),
reason: v1.PipelineRunReasonFailedValidation.String(),
permanentError: true,
wantEvents: []string{
"Normal Started",
"Warning Failed [User error] Validation failed for pipelinerun pipeline-params-dont-exist with error invalid input params for task a-task-that-needs-params: missing values for these params which have no default values: [some-param]",
},
}, {
name: "invalid-pipeline-mismatching-parameter-types",
pipelineRun: parse.MustParseV1PipelineRun(t, `
metadata:
name: pipeline-mismatching-param-type
namespace: foo
spec:
pipelineRef:
name: a-pipeline-with-array-params
params:
- name: some-param
value: stringval
`),
reason: v1.PipelineRunReasonParameterTypeMismatch.String(),
permanentError: true,
wantEvents: []string{
"Normal Started",
"Warning Failed [User error] PipelineRun foo/pipeline-mismatching-param-type parameters have mismatching types with Pipeline foo/a-pipeline-with-array-params's parameters: parameters have inconsistent types : [some-param]",
},
}, {
name: "invalid-pipeline-missing-object-keys",
pipelineRun: parse.MustParseV1PipelineRun(t, `
metadata:
name: pipeline-missing-object-param-keys
namespace: foo
spec:
pipelineRef:
name: a-pipeline-with-object-params
params:
- name: some-param
value:
key1: "a"
`),
reason: v1.PipelineRunReasonObjectParameterMissKeys.String(),
permanentError: true,
wantEvents: []string{
"Normal Started",
"Warning Failed [User error] PipelineRun foo/pipeline-missing-object-param-keys parameters is missing object keys required by Pipeline foo/a-pipeline-with-object-params's parameters: pipelineRun missing object keys for parameters: map[some-param:[key2]]",
},
}, {
name: "invalid-pipeline-array-index-out-of-bound",
pipelineRun: parse.MustParseV1PipelineRun(t, `
metadata:
name: pipeline-param-array-out-of-bound
namespace: foo
spec:
pipelineRef:
name: a-pipeline-with-array-indexing-params
params:
- name: some-param
value:
- "a"
- "b"
`),
reason: v1.PipelineRunReasonParamArrayIndexingInvalid.String(),
permanentError: true,
wantEvents: []string{
"Normal Started",
"Warning Failed [User error] PipelineRun foo/pipeline-param-array-out-of-bound failed validation: failed to validate Pipeline foo/a-pipeline-with-array-indexing-params's parameter which has an invalid index while referring to an array: non-existent param references:[$(params.some-param[2])]",
},
}, {
name: "invalid-embedded-pipeline-bad-name-shd-stop-reconciling",
pipelineRun: parse.MustParseV1PipelineRun(t, `
metadata:
name: embedded-pipeline-invalid
namespace: foo
spec:
pipelineSpec:
tasks:
- name: bad-t@$k
taskRef:
name: b@d-t@$k
`),
reason: v1.PipelineRunReasonFailedValidation.String(),
permanentError: true,
wantEvents: []string{
"Normal Started",
`Warning Failed [User error] Pipeline foo/embedded-pipeline-invalid can't be Run; it has an invalid spec: invalid value "bad-t@$k": tasks[0].name
Pipeline Task name must be a valid DNS Label.For more info refer to https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names
invalid value: name part must consist of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character (e.g. 'MyName', or 'my.name', or '123-abc', regex used for validation is '([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]'): tasks[0].taskRef.name`,
},
}, {
name: "invalid-embedded-pipeline-mismatching-parameter-types",
pipelineRun: parse.MustParseV1PipelineRun(t, fmt.Sprintf(`
metadata:
name: embedded-pipeline-mismatching-param-type
namespace: foo
spec:
pipelineSpec:
params:
- name: some-param
type: %s
tasks:
- name: some-task
taskRef:
name: a-task-that-needs-array-params
params:
- name: some-param
value: stringval
`, v1.ParamTypeArray)),
reason: v1.PipelineRunReasonParameterTypeMismatch.String(),
permanentError: true,
wantEvents: []string{
"Normal Started",
"Warning Failed [User error] PipelineRun foo/embedded-pipeline-mismatching-param-type parameters have mismatching types with Pipeline foo/embedded-pipeline-mismatching-param-type's parameters: parameters have inconsistent types : [some-param]",
},
}, {
name: "invalid-pipeline-run-missing-params-with-ref-shd-stop-reconciling",
pipelineRun: parse.MustParseV1PipelineRun(t, `
metadata:
name: pipelinerun-missing-params-1
namespace: foo
spec:
pipelineRef:
name: a-pipeline-with-array-params
`),
reason: v1.PipelineRunReasonParameterMissing.String(),
permanentError: true,
wantEvents: []string{
"Normal Started",
"Warning Failed [User error] PipelineRun foo/pipelinerun-missing-params-1 is missing some parameters required by Pipeline foo/a-pipeline-with-array-params: pipelineRun missing parameters: [some-param]",
},
}, {
name: "invalid-pipeline-run-missing-params-with-spec-shd-stop-reconciling",
pipelineRun: parse.MustParseV1PipelineRun(t, fmt.Sprintf(`
metadata:
name: pipelinerun-missing-params-2
namespace: foo
spec:
pipelineSpec:
params:
- name: some-param
type: %s
tasks:
- name: some-task
taskRef:
name: a-task-that-needs-params
`, v1.ParamTypeString)),
reason: v1.PipelineRunReasonParameterMissing.String(),
permanentError: true,
wantEvents: []string{
"Normal Started",
"Warning Failed [User error] PipelineRun foo/pipelinerun-missing-params-2 is missing some parameters required by Pipeline foo/pipelinerun-missing-params-2: pipelineRun missing parameters: [some-param]",