-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathstatus_test.go
775 lines (697 loc) · 30.8 KB
/
status_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
/*
Copyright 2022 Red Hat Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package status_test
import (
"context"
"fmt"
"os"
"strconv"
"time"
"github.com/go-logr/logr"
applicationapiv1alpha1 "github.com/konflux-ci/application-api/api/v1alpha1"
"github.com/konflux-ci/operator-toolkit/metadata"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
pacv1alpha1 "github.com/openshift-pipelines/pipelines-as-code/pkg/apis/pipelinesascode/v1alpha1"
tektonv1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1"
"go.uber.org/mock/gomock"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/konflux-ci/integration-service/gitops"
"github.com/konflux-ci/integration-service/helpers"
"github.com/konflux-ci/integration-service/pkg/integrationteststatus"
"github.com/konflux-ci/integration-service/status"
"k8s.io/apimachinery/pkg/api/errors"
)
// Custom matcher for gomock, to match expected summary in TestReport
type hasSummary struct {
expectedSummary string
}
// Matches do exact match of TestResult.Summary
func (m hasSummary) Matches(arg interface{}) bool {
report, ok := arg.(status.TestReport)
if !ok {
return false
}
return report.Summary == m.expectedSummary
}
// String prints what we expected
func (m hasSummary) String() string {
return fmt.Sprintf("TestReport.Summary: \"%s\"", m.expectedSummary)
}
// HasSummary matches if TestRepor.Summary has the expected value
func HasSummary(value string) gomock.Matcher {
return hasSummary{expectedSummary: value}
}
func newIntegrationTestStatusDetail(expectedScenarioStatus integrationteststatus.IntegrationTestStatus) integrationteststatus.IntegrationTestStatusDetail {
ts, _ := time.Parse(time.RFC3339, "2023-07-26T16:57:49+02:00")
tc, _ := time.Parse(time.RFC3339, "2023-07-26T17:57:49+02:00")
return integrationteststatus.IntegrationTestStatusDetail{
ScenarioName: "scenario1",
Status: expectedScenarioStatus,
LastUpdateTime: time.Now().UTC(),
Details: "failed",
StartTime: &ts,
CompletionTime: &tc,
TestPipelineRunName: "test-pipelinerun",
}
}
var _ = Describe("Status Adapter", func() {
var (
githubSnapshot *applicationapiv1alpha1.Snapshot
hasSnapshot *applicationapiv1alpha1.Snapshot
hasComSnapshot2 *applicationapiv1alpha1.Snapshot
hasComSnapshot3 *applicationapiv1alpha1.Snapshot
groupSnapshot *applicationapiv1alpha1.Snapshot
mockReporter *status.MockReporterInterface
pipelineRun *tektonv1.PipelineRun
successfulTaskRun *tektonv1.TaskRun
failedTaskRun *tektonv1.TaskRun
skippedTaskRun *tektonv1.TaskRun
mockK8sClient *MockK8sClient
repo pacv1alpha1.Repository
hasComSnapshot2Name = "hascomsnapshot2-sample"
hasComSnapshot3Name = "hascomsnapshot3-sample"
prGroup = "feature1"
prGroupSha = "feature1hash"
plrstarttime = 1775992257
SampleImage = "quay.io/redhat-appstudio/sample-image@sha256:841328df1b9f8c4087adbdcfec6cc99ac8308805dea83f6d415d6fb8d40227c1"
SampleDigest = "sha256:841328df1b9f8c4087adbdcfec6cc99ac8308805dea83f6d415d6fb8d40227c1"
)
BeforeEach(func() {
now := time.Now()
os.Setenv("CONSOLE_URL", "https://definetly.not.prod/preview/application-pipeline/ns/{{ .Namespace }}/pipelinerun/{{ .PipelineRunName }}")
os.Setenv("CONSOLE_URL_TASKLOG", "https://definetly.not.prod/preview/application-pipeline/ns/{{ .Namespace }}/pipelinerun/{{ .PipelineRunName }}/logs/{{ .TaskName }}")
successfulTaskRun = &tektonv1.TaskRun{
ObjectMeta: metav1.ObjectMeta{
Name: "test-taskrun-pass",
Namespace: "default",
},
Spec: tektonv1.TaskRunSpec{
TaskRef: &tektonv1.TaskRef{
Name: "test-taskrun-pass",
ResolverRef: tektonv1.ResolverRef{
Resolver: "bundle",
Params: tektonv1.Params{
{
Name: "bundle",
Value: tektonv1.ParamValue{Type: "string", StringVal: "quay.io/redhat-appstudio/example-tekton-bundle:test"},
},
{
Name: "name",
Value: tektonv1.ParamValue{Type: "string", StringVal: "test-task"},
},
},
},
},
},
Status: tektonv1.TaskRunStatus{
TaskRunStatusFields: tektonv1.TaskRunStatusFields{
StartTime: &metav1.Time{Time: now},
CompletionTime: &metav1.Time{Time: now.Add(5 * time.Minute)},
Results: []tektonv1.TaskRunResult{
{
Name: "TEST_OUTPUT",
Value: *tektonv1.NewStructuredValues(`{
"result": "SUCCESS",
"timestamp": "2024-05-22T06:42:21+00:00",
"failures": 0,
"successes": 10,
"warnings": 0
}`),
},
},
},
},
}
failedTaskRun = &tektonv1.TaskRun{
ObjectMeta: metav1.ObjectMeta{
Name: "test-taskrun-fail",
Namespace: "default",
},
Spec: tektonv1.TaskRunSpec{
TaskRef: &tektonv1.TaskRef{
Name: "test-taskrun-fail",
ResolverRef: tektonv1.ResolverRef{
Resolver: "bundle",
Params: tektonv1.Params{
{
Name: "bundle",
Value: tektonv1.ParamValue{Type: "string", StringVal: "quay.io/redhat-appstudio/example-tekton-bundle:test"},
},
{
Name: "name",
Value: tektonv1.ParamValue{Type: "string", StringVal: "test-task"},
},
},
},
},
},
Status: tektonv1.TaskRunStatus{
TaskRunStatusFields: tektonv1.TaskRunStatusFields{
StartTime: &metav1.Time{Time: now},
CompletionTime: &metav1.Time{Time: now.Add(5 * time.Minute)},
Results: []tektonv1.TaskRunResult{
{
Name: "TEST_OUTPUT",
Value: *tektonv1.NewStructuredValues(`{
"result": "FAILURE",
"timestamp": "2024-05-22T06:42:21+00:00",
"failures": 1,
"successes": 0,
"warnings": 0
}`),
},
},
},
},
}
skippedTaskRun = &tektonv1.TaskRun{
ObjectMeta: metav1.ObjectMeta{
Name: "test-taskrun-skip",
Namespace: "default",
},
Spec: tektonv1.TaskRunSpec{
TaskRef: &tektonv1.TaskRef{
Name: "test-taskrun-skip",
ResolverRef: tektonv1.ResolverRef{
Resolver: "bundle",
Params: tektonv1.Params{
{
Name: "bundle",
Value: tektonv1.ParamValue{Type: "string", StringVal: "quay.io/redhat-appstudio/example-tekton-bundle:test"},
},
{
Name: "name",
Value: tektonv1.ParamValue{Type: "string", StringVal: "test-task"},
},
},
},
},
},
Status: tektonv1.TaskRunStatus{
TaskRunStatusFields: tektonv1.TaskRunStatusFields{
StartTime: &metav1.Time{Time: now.Add(5 * time.Minute)},
CompletionTime: &metav1.Time{Time: now.Add(10 * time.Minute)},
Results: []tektonv1.TaskRunResult{
{
Name: "TEST_OUTPUT",
Value: *tektonv1.NewStructuredValues(`{
"result": "SKIPPED",
"timestamp": "2024-05-22T06:42:21+00:00",
"failures": 0,
"successes": 0,
"warnings": 0
}`),
},
},
},
},
}
pipelineRun = &tektonv1.PipelineRun{
ObjectMeta: metav1.ObjectMeta{
Name: "test-pipelinerun",
Namespace: "default",
Labels: map[string]string{
"appstudio.openshift.io/component": "devfile-sample-go-basic",
"test.appstudio.openshift.io/scenario": "example-pass",
"pac.test.appstudio.openshift.io/git-provider": "github",
"pac.test.appstudio.openshift.io/url-org": "devfile-sample",
"pac.test.appstudio.openshift.io/url-repository": "devfile-sample-go-basic",
"pac.test.appstudio.openshift.io/sha": "12a4a35ccd08194595179815e4646c3a6c08bb77",
"pac.test.appstudio.openshift.io/event-type": "pull_request",
},
Annotations: map[string]string{
"pac.test.appstudio.openshift.io/repo-url": "https://github.com/devfile-sample/devfile-sample-go-basic",
},
},
Status: tektonv1.PipelineRunStatus{
PipelineRunStatusFields: tektonv1.PipelineRunStatusFields{
StartTime: &metav1.Time{Time: time.Now()},
ChildReferences: []tektonv1.ChildStatusReference{
{
Name: successfulTaskRun.Name,
PipelineTaskName: "pipeline1-task1",
},
{
Name: skippedTaskRun.Name,
PipelineTaskName: "pipeline1-task2",
},
},
},
},
}
hasSnapshot = &applicationapiv1alpha1.Snapshot{
ObjectMeta: metav1.ObjectMeta{
Name: "snapshot-sample",
Namespace: "default",
Labels: map[string]string{
"test.appstudio.openshift.io/type": "component",
"appstudio.openshift.io/component": "component-sample",
"build.appstudio.redhat.com/pipeline": "enterprise-contract",
"pac.test.appstudio.openshift.io/git-provider": "github",
"pac.test.appstudio.openshift.io/url-org": "devfile-sample",
"pac.test.appstudio.openshift.io/url-repository": "devfile-sample-go-basic",
"pac.test.appstudio.openshift.io/sha": "12a4a35ccd08194595179815e4646c3a6c08bb77",
"pac.test.appstudio.openshift.io/event-type": "pull_request",
},
Annotations: map[string]string{
"build.appstudio.redhat.com/commit_sha": "6c65b2fcaea3e1a0a92476c8b5dc89e92a85f025",
"appstudio.redhat.com/updateComponentOnSuccess": "false",
"pac.test.appstudio.openshift.io/repo-url": "https://github.com/devfile-sample/devfile-sample-go-basic",
},
},
Spec: applicationapiv1alpha1.SnapshotSpec{
Application: "application-sample",
Components: []applicationapiv1alpha1.SnapshotComponent{
{
Name: "component-sample",
ContainerImage: "sample_image",
Source: applicationapiv1alpha1.ComponentSource{
ComponentSourceUnion: applicationapiv1alpha1.ComponentSourceUnion{
GitSource: &applicationapiv1alpha1.GitSource{
Revision: "sample_revision",
},
},
},
},
},
},
}
hasComSnapshot2 = &applicationapiv1alpha1.Snapshot{
ObjectMeta: metav1.ObjectMeta{
Name: hasComSnapshot2Name,
Namespace: "default",
Labels: map[string]string{
gitops.SnapshotTypeLabel: gitops.SnapshotComponentType,
gitops.SnapshotComponentLabel: hasComSnapshot2Name,
gitops.PipelineAsCodeEventTypeLabel: gitops.PipelineAsCodePullRequestType,
gitops.PRGroupHashLabel: prGroupSha,
"pac.test.appstudio.openshift.io/url-org": "testorg",
"pac.test.appstudio.openshift.io/url-repository": "testrepo",
gitops.PipelineAsCodeSHALabel: "sha",
gitops.PipelineAsCodePullRequestAnnotation: "1",
},
Annotations: map[string]string{
"test.appstudio.openshift.io/pr-last-update": "2023-08-26T17:57:50+02:00",
gitops.BuildPipelineRunStartTime: strconv.Itoa(plrstarttime + 100),
gitops.PRGroupAnnotation: prGroup,
gitops.PipelineAsCodeGitProviderAnnotation: "github",
gitops.PipelineAsCodeInstallationIDAnnotation: "123",
},
},
Spec: applicationapiv1alpha1.SnapshotSpec{
Application: "application-sample",
Components: []applicationapiv1alpha1.SnapshotComponent{
{
Name: hasComSnapshot2Name,
ContainerImage: SampleImage + "@" + SampleDigest,
},
{
Name: hasComSnapshot3Name,
ContainerImage: SampleImage + "@" + SampleDigest,
},
},
},
}
hasComSnapshot3 = &applicationapiv1alpha1.Snapshot{
ObjectMeta: metav1.ObjectMeta{
Name: hasComSnapshot3Name,
Namespace: "default",
Labels: map[string]string{
gitops.SnapshotTypeLabel: gitops.SnapshotComponentType,
gitops.SnapshotComponentLabel: hasComSnapshot3Name,
gitops.PipelineAsCodeEventTypeLabel: gitops.PipelineAsCodePullRequestType,
gitops.PRGroupHashLabel: prGroupSha,
"pac.test.appstudio.openshift.io/url-org": "testorg",
"pac.test.appstudio.openshift.io/url-repository": "testrepo",
gitops.PipelineAsCodeSHALabel: "sha",
gitops.PipelineAsCodePullRequestAnnotation: "1",
},
Annotations: map[string]string{
"test.appstudio.openshift.io/pr-last-update": "2023-08-26T17:57:50+02:00",
gitops.BuildPipelineRunStartTime: strconv.Itoa(plrstarttime + 200),
gitops.PRGroupAnnotation: prGroup,
gitops.PipelineAsCodeGitProviderAnnotation: "github",
gitops.PipelineAsCodePullRequestAnnotation: "1",
gitops.PipelineAsCodeInstallationIDAnnotation: "123",
},
},
Spec: applicationapiv1alpha1.SnapshotSpec{
Application: "application-sample",
Components: []applicationapiv1alpha1.SnapshotComponent{
{
Name: hasComSnapshot2Name,
ContainerImage: SampleImage + "@" + SampleDigest,
},
{
Name: hasComSnapshot3Name,
ContainerImage: SampleImage + "@" + SampleDigest,
},
},
},
}
groupSnapshot = &applicationapiv1alpha1.Snapshot{
ObjectMeta: metav1.ObjectMeta{
Name: "groupsnapshot",
Namespace: "default",
Labels: map[string]string{
gitops.SnapshotTypeLabel: gitops.SnapshotGroupType,
gitops.PipelineAsCodeEventTypeLabel: gitops.PipelineAsCodePullRequestType,
gitops.PRGroupHashLabel: prGroupSha,
},
Annotations: map[string]string{
gitops.PRGroupAnnotation: prGroup,
gitops.GroupSnapshotInfoAnnotation: "[{\"namespace\":\"default\",\"component\":\"component1-sample\",\"buildPipelineRun\":\"\",\"snapshot\":\"hascomsnapshot2-sample\"},{\"namespace\":\"default\",\"component\":\"component3-sample\",\"buildPipelineRun\":\"\",\"snapshot\":\"hascomsnapshot3-sample\"}]",
gitops.SnapshotTestsStatusAnnotation: "[{\"scenario\":\"scenario-1\",\"status\":\"EnvironmentProvisionError\",\"startTime\":\"2023-07-26T16:57:49+02:00\",\"completionTime\":\"2023-07-26T17:57:49+02:00\",\"lastUpdateTime\":\"2023-08-26T17:57:49+02:00\",\"details\":\"Failed to find deploymentTargetClass with right provisioner for copy of existingEnvironment\"}]",
},
},
Spec: applicationapiv1alpha1.SnapshotSpec{
Application: "application-sample",
Components: []applicationapiv1alpha1.SnapshotComponent{
{
Name: hasComSnapshot2Name,
ContainerImage: SampleImage + "@" + SampleDigest,
},
{
Name: hasComSnapshot3Name,
ContainerImage: SampleImage + "@" + SampleDigest,
},
},
},
}
mockK8sClient = &MockK8sClient{
getInterceptor: func(key client.ObjectKey, obj client.Object) {
if taskRun, ok := obj.(*tektonv1.TaskRun); ok {
if key.Name == successfulTaskRun.Name {
taskRun.Status = successfulTaskRun.Status
} else if key.Name == failedTaskRun.Name {
taskRun.Status = failedTaskRun.Status
} else if key.Name == skippedTaskRun.Name {
taskRun.Status = skippedTaskRun.Status
}
}
if plr, ok := obj.(*tektonv1.PipelineRun); ok {
if key.Name == pipelineRun.Name {
plr.Status = pipelineRun.Status
}
}
if snapshot, ok := obj.(*applicationapiv1alpha1.Snapshot); ok {
if key.Name == hasComSnapshot2.Name {
snapshot.Name = hasComSnapshot2.Name
}
if key.Name == hasComSnapshot3.Name {
snapshot.Name = hasComSnapshot3.Name
}
}
},
listInterceptor: func(list client.ObjectList) {
if repoList, ok := list.(*pacv1alpha1.RepositoryList); ok {
repoList.Items = []pacv1alpha1.Repository{repo}
}
},
}
hasSnapshot = &applicationapiv1alpha1.Snapshot{
ObjectMeta: metav1.ObjectMeta{
Name: "snapshot-sample",
Namespace: "default",
Labels: map[string]string{
"test.appstudio.openshift.io/type": "component",
"appstudio.openshift.io/component": "component-sample",
"build.appstudio.redhat.com/pipeline": "enterprise-contract",
"pac.test.appstudio.openshift.io/git-provider": "github",
"pac.test.appstudio.openshift.io/url-org": "devfile-sample",
"pac.test.appstudio.openshift.io/url-repository": "devfile-sample-go-basic",
"pac.test.appstudio.openshift.io/sha": "12a4a35ccd08194595179815e4646c3a6c08bb77",
"pac.test.appstudio.openshift.io/event-type": "pull_request",
},
Annotations: map[string]string{
"build.appstudio.redhat.com/commit_sha": "6c65b2fcaea3e1a0a92476c8b5dc89e92a85f025",
"appstudio.redhat.com/updateComponentOnSuccess": "false",
"pac.test.appstudio.openshift.io/repo-url": "https://github.com/devfile-sample/devfile-sample-go-basic",
},
},
Spec: applicationapiv1alpha1.SnapshotSpec{
Application: "application-sample",
Components: []applicationapiv1alpha1.SnapshotComponent{
{
Name: "component-sample",
ContainerImage: "sample_image",
Source: applicationapiv1alpha1.ComponentSource{
ComponentSourceUnion: applicationapiv1alpha1.ComponentSourceUnion{
GitSource: &applicationapiv1alpha1.GitSource{
Revision: "sample_revision",
},
},
},
},
},
},
}
githubSnapshot = &applicationapiv1alpha1.Snapshot{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
"pac.test.appstudio.openshift.io/git-provider": "github",
},
},
}
ctrl := gomock.NewController(GinkgoT())
mockReporter = status.NewMockReporterInterface(ctrl)
mockReporter.EXPECT().GetReporterName().Return("mocked-reporter").AnyTimes()
mockReporter.EXPECT().Initialize(gomock.Any(), gomock.Any()).Return(nil).AnyTimes()
os.Setenv("CONSOLE_NAME", "Red Hat Konflux")
})
AfterEach(func() {
os.Setenv("CONSOLE_URL", "")
os.Setenv("CONSOLE_NAME", "")
})
It("can get reporters from a snapshot", func() {
st := status.NewStatus(logr.Discard(), nil)
reporter := st.GetReporter(githubSnapshot)
Expect(reporter).ToNot(BeNil())
Expect(reporter.GetReporterName()).To(Equal("GithubReporter"))
})
It("can migrate snapshot to reportStatus in old way - migration test)", func() {
hasSnapshot.Annotations["test.appstudio.openshift.io/status"] = "[{\"scenario\":\"scenario1\",\"status\":\"InProgress\",\"startTime\":\"2023-07-26T16:57:49+02:00\",\"lastUpdateTime\":\"2023-08-26T17:57:50+02:00\",\"details\":\"Test in progress\"}]"
hasSnapshot.Annotations["test.appstudio.openshift.io/pr-last-update"] = "2023-08-26T17:57:50+02:00"
statuses, err := gitops.NewSnapshotIntegrationTestStatusesFromSnapshot(hasSnapshot)
Expect(err).NotTo(HaveOccurred())
integrationTestStatusDetails := statuses.GetStatuses()
status.MigrateSnapshotToReportStatus(hasSnapshot, integrationTestStatusDetails)
Expect(hasSnapshot.Annotations[gitops.SnapshotStatusReportAnnotation]).Should(ContainSubstring("lastUpdateTime"))
})
It("report status for TestPassed test scenario", func() {
hasSnapshot.Annotations["test.appstudio.openshift.io/status"] = "[{\"scenario\":\"scenario1\",\"status\":\"TestPassed\",\"testPipelineRunName\":\"test-pipelinerun\",\"startTime\":\"2023-07-26T16:57:49+02:00\",\"completionTime\":\"2023-07-26T17:57:49+02:00\",\"lastUpdateTime\":\"2023-08-26T17:57:55+02:00\",\"details\":\"failed\"}]"
integrationTestStatusDetail := newIntegrationTestStatusDetail(integrationteststatus.IntegrationTestStatusTestPassed)
delete(hasSnapshot.Labels, "appstudio.openshift.io/component")
ts, err := time.Parse(time.RFC3339, "2023-07-26T16:57:49+02:00")
Expect(err).NotTo(HaveOccurred())
tc, err := time.Parse(time.RFC3339, "2023-07-26T17:57:49+02:00")
Expect(err).NotTo(HaveOccurred())
text := `<ul>
<li><b>Pipelinerun</b>: <a href="https://definetly.not.prod/preview/application-pipeline/ns/default/pipelinerun/test-pipelinerun">test-pipelinerun</a></li>
</ul>
<hr>
| Task | Duration | Test Suite | Status | Details |
| --- | --- | --- | --- | --- |
| <a href="https://definetly.not.prod/preview/application-pipeline/ns/default/pipelinerun/test-pipelinerun/logs/pipeline1-task1">pipeline1-task1</a> | 5m0s | | :heavy_check_mark: SUCCESS | :heavy_check_mark: 10 success(es) |
| <a href="https://definetly.not.prod/preview/application-pipeline/ns/default/pipelinerun/test-pipelinerun/logs/pipeline1-task2">pipeline1-task2</a> | 5m0s | | :white_check_mark: SKIPPED | |
`
expectedTestReport := status.TestReport{
FullName: "Red Hat Konflux / scenario1",
ScenarioName: "scenario1",
SnapshotName: "snapshot-sample",
ComponentName: "",
Text: text,
Summary: "Integration test for snapshot snapshot-sample and scenario scenario1 has passed",
Status: integrationteststatus.IntegrationTestStatusTestPassed,
StartTime: &ts,
CompletionTime: &tc,
TestPipelineRunName: "test-pipelinerun",
}
testReport, err := status.GenerateTestReport(context.Background(), mockK8sClient, integrationTestStatusDetail, hasSnapshot, "")
Expect(err).NotTo(HaveOccurred())
Expect(testReport).To(Equal(&expectedTestReport))
})
DescribeTable(
"report right summary per status",
func(expectedScenarioStatus integrationteststatus.IntegrationTestStatus, expectedTextEnding string) {
integrationTestStatusDetail := newIntegrationTestStatusDetail(expectedScenarioStatus)
expectedSummary := fmt.Sprintf("Integration test for snapshot snapshot-sample and scenario scenario1 %s", expectedTextEnding)
testReport, err := status.GenerateTestReport(context.Background(), mockK8sClient, integrationTestStatusDetail, hasSnapshot, "component-sample")
Expect(err).NotTo(HaveOccurred())
Expect(testReport.Summary).To(Equal(expectedSummary))
},
Entry("Passed", integrationteststatus.IntegrationTestStatusTestPassed, "has passed"),
Entry("Failed", integrationteststatus.IntegrationTestStatusTestFail, "has failed"),
Entry("Provisioning error", integrationteststatus.IntegrationTestStatusEnvironmentProvisionError_Deprecated, "experienced an error when provisioning environment"),
Entry("Deployment error", integrationteststatus.IntegrationTestStatusDeploymentError_Deprecated, "experienced an error when deploying snapshotEnvironmentBinding"),
Entry("Deleted", integrationteststatus.IntegrationTestStatusDeleted, "was deleted before the pipelineRun could finish"),
Entry("Pending", integrationteststatus.IntegrationTestStatusPending, "is pending"),
Entry("In progress", integrationteststatus.IntegrationTestStatusInProgress, "is in progress"),
Entry("Invalid", integrationteststatus.IntegrationTestStatusTestInvalid, "is invalid"),
)
DescribeTable(
"report right summary per status",
func(expectedScenarioStatus integrationteststatus.IntegrationTestStatus, expectedTextEnding string) {
integrationTestStatusDetail := newIntegrationTestStatusDetail(expectedScenarioStatus)
expectedSummary := fmt.Sprintf("Integration test for scenario scenario1 %s", expectedTextEnding)
testReport, err := status.GenerateTestReport(context.Background(), mockK8sClient, integrationTestStatusDetail, hasSnapshot, "component-sample")
Expect(err).NotTo(HaveOccurred())
Expect(testReport.Summary).To(Equal(expectedSummary))
},
Entry("BuildPLRInProgress", integrationteststatus.BuildPLRInProgress, "is pending because build pipelinerun is still running and snapshot has not been created"),
Entry("SnapshotCreationFailed", integrationteststatus.SnapshotCreationFailed, "has not run and is considered as failed because the snapshot was not created"),
Entry("BuildPLRFailed", integrationteststatus.BuildPLRFailed, "has not run and is considered as failed because the build pipelinerun failed and snapshot was not created"),
)
It("check if GenerateSummary supports all integration test statuses", func() {
for _, teststatus := range integrationteststatus.IntegrationTestStatusValues() {
_, err := status.GenerateSummary(teststatus, "yolo", "yolo")
Expect(err).NotTo(HaveOccurred())
}
})
It("check getting component snapshots from group snapshot", func() {
componentSnapshots, err := status.GetComponentSnapshotsFromGroupSnapshot(context.Background(), mockK8sClient, groupSnapshot)
Expect(err).NotTo(HaveOccurred())
Expect(componentSnapshots).To(HaveLen(2))
})
Describe("SnapshotReportStatus (SRS)", func() {
const (
scenarioName = "test-scenario"
)
var (
hasSRS *status.SnapshotReportStatus
now time.Time
)
BeforeEach(func() {
var err error
now = time.Now().UTC()
hasSRS, err = status.NewSnapshotReportStatus("")
Expect(err).ToNot(HaveOccurred())
})
It("New SRS is not dirty", func() {
Expect(hasSRS.IsDirty()).To(BeFalse())
})
It("Reseting dirty bit works", func() {
Expect(mockK8sClient.Create(context.Background(), hasSnapshot)).Should(Succeed())
hasSRS.SetLastUpdateTime(scenarioName, hasSnapshot.Name, now)
Expect(hasSRS.IsDirty()).To(BeTrue())
hasSRS.ResetDirty()
Expect(hasSRS.IsDirty()).To(BeFalse())
// must keep scenarios
Expect(hasSRS.Scenarios).To(
HaveKeyWithValue(scenarioName+"-"+hasSnapshot.Name, &status.ScenarioReportStatus{
LastUpdateTime: &now,
}))
Expect(hasSnapshot.Annotations[gitops.SnapshotStatusReportAnnotation]).To(Equal(""))
err := status.WriteSnapshotReportStatus(context.Background(), mockK8sClient, hasSnapshot, hasSRS)
Expect(err).ToNot(HaveOccurred())
Expect(hasSnapshot.Annotations[gitops.SnapshotStatusReportAnnotation]).NotTo(BeNil())
err = mockK8sClient.Delete(context.Background(), hasSnapshot)
Expect(err == nil || errors.IsNotFound(err)).To(BeTrue())
})
It("New scenario can be added to SRS", func() {
Expect(mockK8sClient.Create(context.Background(), hasSnapshot)).Should(Succeed())
hasSRS.SetLastUpdateTime(scenarioName, hasSnapshot.Name, now)
Expect(hasSRS.IsDirty()).To(BeTrue())
Expect(hasSRS.Scenarios).To(
HaveKeyWithValue(scenarioName+"-"+hasSnapshot.Name, &status.ScenarioReportStatus{
LastUpdateTime: &now,
}))
Expect(hasSnapshot.Annotations[gitops.SnapshotStatusReportAnnotation]).To(Equal(""))
err := status.WriteSnapshotReportStatus(context.Background(), mockK8sClient, hasSnapshot, hasSRS)
Expect(err).ToNot(HaveOccurred())
Expect(hasSnapshot.Annotations[gitops.SnapshotStatusReportAnnotation]).NotTo(BeNil())
err = mockK8sClient.Delete(context.Background(), hasSnapshot)
Expect(err == nil || errors.IsNotFound(err)).To(BeTrue())
})
It("Additional scenario can be added to SRS", func() {
extraScenarioName := "test-scenario-2"
hasSRS.SetLastUpdateTime(scenarioName, hasSnapshot.Name, now)
hasSRS.SetLastUpdateTime(extraScenarioName, hasSnapshot.Name, now)
Expect(hasSRS.Scenarios).To(HaveLen(2))
})
It("New last updated time can be assigned to existing scenario", func() {
tNew := now.Add(1 * time.Minute)
hasSRS.SetLastUpdateTime(scenarioName, hasSnapshot.Name, now)
hasSRS.ResetDirty()
hasSRS.SetLastUpdateTime(scenarioName, hasSnapshot.Name, tNew)
Expect(hasSRS.Scenarios).To(
HaveKeyWithValue(scenarioName+"-"+hasSnapshot.Name, &status.ScenarioReportStatus{
LastUpdateTime: &tNew,
}))
Expect(hasSRS.Scenarios).To(HaveLen(1))
})
It("Detect newer update", func() {
tNew := now.Add(1 * time.Minute)
hasSRS.SetLastUpdateTime(scenarioName, hasSnapshot.Name, now)
Expect(hasSRS.IsNewer(scenarioName, hasSnapshot.Name, tNew)).To(BeTrue())
})
It("Detect no new update", func() {
tOld := now.Add(-1 * time.Minute)
hasSRS.SetLastUpdateTime(scenarioName, hasSnapshot.Name, now)
Expect(hasSRS.IsNewer(scenarioName, hasSnapshot.Name, tOld)).To(BeFalse())
})
It("Can export valid annotation", func() {
hasSRS.SetLastUpdateTime(scenarioName, hasSnapshot.Name, now)
annotation, err := hasSRS.ToAnnotationString()
Expect(err).ToNot(HaveOccurred())
Expect(annotation).ToNot(BeEmpty())
newSRS, err := status.NewSnapshotReportStatus(annotation)
Expect(err).ToNot(HaveOccurred())
Expect(newSRS.Scenarios).To(HaveKey(scenarioName + "-" + hasSnapshot.Name))
// comparing string because it was trying to compare pointer address and it changed
Expect(newSRS.Scenarios[scenarioName+"-"+hasSnapshot.Name].LastUpdateTime.UnixMicro()).To(Equal(now.UnixMicro()))
Expect(newSRS.Scenarios).To(HaveLen(1))
})
It("Can read annotation from snapshot", func() {
hasSnapshot.Annotations["test.appstudio.openshift.io/git-reporter-status"] = "{\"scenarios\":{\"test-scenario-snapshot-sample\":{\"lastUpdateTime\":\"2023-08-26T17:57:49+02:00\"}}}"
newSRS, err := status.NewSnapshotReportStatusFromSnapshot(hasSnapshot)
Expect(err).ToNot(HaveOccurred())
Expect(newSRS.Scenarios).To(HaveKey(scenarioName + "-" + hasSnapshot.Name))
Expect(newSRS.Scenarios).To(HaveLen(1))
})
It("can return unrecoverable error when label is not defined for githubReporter", func() {
err := metadata.DeleteLabel(hasSnapshot, gitops.PipelineAsCodeURLOrgLabel)
Expect(err).ToNot(HaveOccurred())
githubReporter := status.NewGitHubReporter(logr.Discard(), mockK8sClient)
err = githubReporter.Initialize(context.Background(), hasSnapshot)
Expect(helpers.IsUnrecoverableMetadataError(err)).To(BeTrue())
err = metadata.SetLabel(hasSnapshot, gitops.PipelineAsCodeURLOrgLabel, "org")
Expect(err).ToNot(HaveOccurred())
err = metadata.DeleteLabel(hasSnapshot, gitops.PipelineAsCodeURLRepositoryLabel)
Expect(err).ToNot(HaveOccurred())
err = githubReporter.Initialize(context.Background(), hasSnapshot)
Expect(helpers.IsUnrecoverableMetadataError(err)).To(BeTrue())
err = metadata.SetLabel(hasSnapshot, gitops.PipelineAsCodeURLRepositoryLabel, "repo")
Expect(err).ToNot(HaveOccurred())
err = metadata.DeleteLabel(hasSnapshot, gitops.PipelineAsCodeSHALabel)
Expect(err).ToNot(HaveOccurred())
err = githubReporter.Initialize(context.Background(), hasSnapshot)
Expect(helpers.IsUnrecoverableMetadataError(err)).To(BeTrue())
})
It("can return unrecoverable error when label/annotation is not defined for gitlabReporter", func() {
err := metadata.DeleteAnnotation(hasSnapshot, gitops.PipelineAsCodeRepoURLAnnotation)
Expect(err).ToNot(HaveOccurred())
gitlabReporter := status.NewGitLabReporter(logr.Discard(), mockK8sClient)
err = gitlabReporter.Initialize(context.Background(), hasSnapshot)
Expect(helpers.IsUnrecoverableMetadataError(err)).To(BeTrue())
err = metadata.SetAnnotation(hasSnapshot, gitops.PipelineAsCodeRepoURLAnnotation, "https://test-repo.example.com")
Expect(err).ToNot(HaveOccurred())
err = metadata.SetAnnotation(hasSnapshot, gitops.PipelineAsCodeSourceProjectIDAnnotation, "qqq")
Expect(err).ToNot(HaveOccurred())
err = gitlabReporter.Initialize(context.Background(), hasSnapshot)
Expect(helpers.IsUnrecoverableMetadataError(err)).To(BeTrue())
})
})
})