-
Notifications
You must be signed in to change notification settings - Fork 451
Expand file tree
/
Copy pathinit-action-post-helper.test.ts
More file actions
858 lines (786 loc) · 24.2 KB
/
init-action-post-helper.test.ts
File metadata and controls
858 lines (786 loc) · 24.2 KB
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
import * as core from "@actions/core";
import test, { ExecutionContext } from "ava";
import * as sinon from "sinon";
import * as actionsUtil from "./actions-util";
import { AnalysisKind } from "./analyses";
import * as apiClient from "./api-client";
import * as codeql from "./codeql";
import * as configUtils from "./config-utils";
import * as debugArtifacts from "./debug-artifacts";
import { EnvVar } from "./environment";
import { Feature } from "./feature-flags";
import * as initActionPostHelper from "./init-action-post-helper";
import { getRunnerLogger } from "./logging";
import { OverlayDatabaseMode } from "./overlay/overlay-database-mode";
import * as overlayStatus from "./overlay/status";
import { parseRepositoryNwo } from "./repository";
import {
createFeatures,
createTestConfig,
DEFAULT_ACTIONS_VARS,
makeVersionInfo,
RecordingLogger,
setupActionsVars,
setupTests,
} from "./testing-utils";
import * as uploadLib from "./upload-lib";
import * as util from "./util";
import * as workflow from "./workflow";
const NUM_BYTES_PER_GIB = 1024 * 1024 * 1024;
setupTests(test);
test.serial("init-post action with debug mode off", async (t) => {
return await util.withTmpDir(async (tmpDir) => {
setupActionsVars(tmpDir, tmpDir);
const gitHubVersion: util.GitHubVersion = {
type: util.GitHubVariant.DOTCOM,
};
sinon.stub(configUtils, "getConfig").resolves(
createTestConfig({
debugMode: false,
gitHubVersion,
languages: [],
}),
);
const uploadAllAvailableDebugArtifactsSpy = sinon.spy();
const printDebugLogsSpy = sinon.spy();
await initActionPostHelper.uploadFailureInfo(
uploadAllAvailableDebugArtifactsSpy,
printDebugLogsSpy,
codeql.createStubCodeQL({}),
createTestConfig({ debugMode: false }),
parseRepositoryNwo("github/codeql-action"),
createFeatures([]),
getRunnerLogger(true),
);
t.assert(uploadAllAvailableDebugArtifactsSpy.notCalled);
t.assert(printDebugLogsSpy.notCalled);
});
});
test.serial("init-post action with debug mode on", async (t) => {
return await util.withTmpDir(async (tmpDir) => {
setupActionsVars(tmpDir, tmpDir);
const uploadAllAvailableDebugArtifactsSpy = sinon.spy();
const printDebugLogsSpy = sinon.spy();
await initActionPostHelper.uploadFailureInfo(
uploadAllAvailableDebugArtifactsSpy,
printDebugLogsSpy,
codeql.createStubCodeQL({}),
createTestConfig({ debugMode: true }),
parseRepositoryNwo("github/codeql-action"),
createFeatures([]),
getRunnerLogger(true),
);
t.assert(uploadAllAvailableDebugArtifactsSpy.called);
t.assert(printDebugLogsSpy.called);
});
});
test.serial(
"uploads failed SARIF run with `diagnostics export` if feature flag is off",
async (t) => {
const actionsWorkflow = createTestWorkflow([
{
name: "Checkout repository",
uses: "actions/checkout@v5",
},
{
name: "Initialize CodeQL",
uses: "github/codeql-action/init@v4",
with: {
languages: "javascript",
},
},
{
name: "Perform CodeQL Analysis",
uses: "github/codeql-action/analyze@v4",
with: {
category: "my-category",
},
},
]);
await testFailedSarifUpload(t, actionsWorkflow, {
category: "my-category",
});
},
);
test.serial(
"uploads failed SARIF run with `diagnostics export` if the database doesn't exist",
async (t) => {
const actionsWorkflow = createTestWorkflow([
{
name: "Checkout repository",
uses: "actions/checkout@v5",
},
{
name: "Initialize CodeQL",
uses: "github/codeql-action/init@v4",
with: {
languages: "javascript",
},
},
{
name: "Perform CodeQL Analysis",
uses: "github/codeql-action/analyze@v4",
with: {
category: "my-category",
},
},
]);
await testFailedSarifUpload(t, actionsWorkflow, {
category: "my-category",
databaseExists: false,
});
},
);
test.serial(
"uploads failed SARIF run with database export-diagnostics if the database exists and feature flag is on",
async (t) => {
const actionsWorkflow = createTestWorkflow([
{
name: "Checkout repository",
uses: "actions/checkout@v5",
},
{
name: "Initialize CodeQL",
uses: "github/codeql-action/init@v4",
with: {
languages: "javascript",
},
},
{
name: "Perform CodeQL Analysis",
uses: "github/codeql-action/analyze@v4",
with: {
category: "my-category",
},
},
]);
await testFailedSarifUpload(t, actionsWorkflow, {
category: "my-category",
exportDiagnosticsEnabled: true,
});
},
);
const UPLOAD_INPUT_TEST_CASES = [
{
uploadInput: "true",
shouldUpload: true,
},
{
uploadInput: "false",
shouldUpload: true,
},
{
uploadInput: "always",
shouldUpload: true,
},
{
uploadInput: "failure-only",
shouldUpload: true,
},
{
uploadInput: "never",
shouldUpload: false,
},
{
uploadInput: "unrecognized-value",
shouldUpload: true,
},
];
for (const { uploadInput, shouldUpload } of UPLOAD_INPUT_TEST_CASES) {
test.serial(
`does ${
shouldUpload ? "" : "not "
}upload failed SARIF run for workflow with upload: ${uploadInput}`,
async (t) => {
const actionsWorkflow = createTestWorkflow([
{
name: "Checkout repository",
uses: "actions/checkout@v5",
},
{
name: "Initialize CodeQL",
uses: "github/codeql-action/init@v4",
with: {
languages: "javascript",
},
},
{
name: "Perform CodeQL Analysis",
uses: "github/codeql-action/analyze@v4",
with: {
category: "my-category",
upload: uploadInput,
},
},
]);
const result = await testFailedSarifUpload(t, actionsWorkflow, {
category: "my-category",
expectUpload: shouldUpload,
});
if (!shouldUpload) {
t.is(
result.upload_failed_run_skipped_because,
"SARIF upload is disabled",
);
}
},
);
}
test.serial(
"uploading failed SARIF run succeeds when workflow uses an input with a matrix var",
async (t) => {
const actionsWorkflow = createTestWorkflow([
{
name: "Checkout repository",
uses: "actions/checkout@v5",
},
{
name: "Initialize CodeQL",
uses: "github/codeql-action/init@v4",
with: {
languages: "javascript",
},
},
{
name: "Perform CodeQL Analysis",
uses: "github/codeql-action/analyze@v4",
with: {
category: "/language:${{ matrix.language }}",
},
},
]);
await testFailedSarifUpload(t, actionsWorkflow, {
category: "/language:csharp",
matrix: { language: "csharp" },
});
},
);
test.serial(
"uploading failed SARIF run fails when workflow uses a complex upload input",
async (t) => {
const actionsWorkflow = createTestWorkflow([
{
name: "Checkout repository",
uses: "actions/checkout@v5",
},
{
name: "Initialize CodeQL",
uses: "github/codeql-action/init@v4",
with: {
languages: "javascript",
},
},
{
name: "Perform CodeQL Analysis",
uses: "github/codeql-action/analyze@v4",
with: {
upload: "${{ matrix.language != 'csharp' }}",
},
},
]);
const result = await testFailedSarifUpload(t, actionsWorkflow, {
expectUpload: false,
});
t.is(
result.upload_failed_run_error,
"Could not get upload input to github/codeql-action/analyze since it contained an " +
"unrecognized dynamic value.",
);
},
);
test.serial(
"uploading failed SARIF run fails when workflow does not reference github/codeql-action",
async (t) => {
const actionsWorkflow = createTestWorkflow([
{
name: "Checkout repository",
uses: "actions/checkout@v5",
},
]);
const result = await testFailedSarifUpload(t, actionsWorkflow, {
expectUpload: false,
});
t.is(
result.upload_failed_run_error,
"Could not get upload input to github/codeql-action/analyze since the analyze job does not " +
"call github/codeql-action/analyze.",
);
t.truthy(result.upload_failed_run_stack_trace);
},
);
test.serial(
"not uploading failed SARIF when `code-scanning` is not an enabled analysis kind",
async (t) => {
const result = await testFailedSarifUpload(t, createTestWorkflow([]), {
analysisKinds: [AnalysisKind.CodeQuality],
expectUpload: false,
});
t.is(
result.upload_failed_run_skipped_because,
"No analysis kind that supports failed SARIF uploads is enabled.",
);
},
);
test.serial(
"saves overlay status when overlay-base analysis did not complete successfully",
async (t) => {
return await util.withTmpDir(async (tmpDir) => {
setupActionsVars(tmpDir, tmpDir);
// Ensure analyze did not complete successfully.
delete process.env[EnvVar.ANALYZE_DID_COMPLETE_SUCCESSFULLY];
const diskUsage: util.DiskUsage = {
numAvailableBytes: 100 * NUM_BYTES_PER_GIB,
numTotalBytes: 200 * NUM_BYTES_PER_GIB,
};
sinon.stub(util, "checkDiskUsage").resolves(diskUsage);
const saveOverlayStatusStub = sinon
.stub(overlayStatus, "saveOverlayStatus")
.resolves(true);
const stubCodeQL = codeql.createStubCodeQL({});
await initActionPostHelper.uploadFailureInfo(
sinon.spy(),
sinon.spy(),
stubCodeQL,
createTestConfig({
debugMode: false,
languages: ["javascript"],
overlayDatabaseMode: OverlayDatabaseMode.OverlayBase,
}),
parseRepositoryNwo("github/codeql-action"),
createFeatures([Feature.OverlayAnalysisStatusSave]),
getRunnerLogger(true),
);
t.true(
saveOverlayStatusStub.calledOnce,
"saveOverlayStatus should be called exactly once",
);
t.deepEqual(
saveOverlayStatusStub.firstCall.args[0],
stubCodeQL,
"first arg should be the CodeQL instance",
);
t.deepEqual(
saveOverlayStatusStub.firstCall.args[1],
["javascript"],
"second arg should be the languages",
);
t.deepEqual(
saveOverlayStatusStub.firstCall.args[2],
diskUsage,
"third arg should be the disk usage",
);
t.deepEqual(
saveOverlayStatusStub.firstCall.args[3],
{
attemptedToBuildOverlayBaseDatabase: true,
builtOverlayBaseDatabase: false,
job: {
checkRunId: undefined,
workflowRunId: Number(DEFAULT_ACTIONS_VARS.GITHUB_RUN_ID),
workflowRunAttempt: Number(DEFAULT_ACTIONS_VARS.GITHUB_RUN_ATTEMPT),
name: DEFAULT_ACTIONS_VARS.GITHUB_JOB,
},
},
"fourth arg should be the overlay status recording an unsuccessful build attempt with job details",
);
});
},
);
test.serial(
"does not save overlay status when OverlayAnalysisStatusSave feature flag is disabled",
async (t) => {
return await util.withTmpDir(async (tmpDir) => {
setupActionsVars(tmpDir, tmpDir);
// Ensure analyze did not complete successfully.
delete process.env[EnvVar.ANALYZE_DID_COMPLETE_SUCCESSFULLY];
sinon.stub(util, "checkDiskUsage").resolves({
numAvailableBytes: 100 * NUM_BYTES_PER_GIB,
numTotalBytes: 200 * NUM_BYTES_PER_GIB,
});
const saveOverlayStatusStub = sinon
.stub(overlayStatus, "saveOverlayStatus")
.resolves(true);
await initActionPostHelper.uploadFailureInfo(
sinon.spy(),
sinon.spy(),
codeql.createStubCodeQL({}),
createTestConfig({
debugMode: false,
languages: ["javascript"],
overlayDatabaseMode: OverlayDatabaseMode.OverlayBase,
}),
parseRepositoryNwo("github/codeql-action"),
createFeatures([]),
getRunnerLogger(true),
);
t.true(
saveOverlayStatusStub.notCalled,
"saveOverlayStatus should not be called when OverlayAnalysisStatusSave feature flag is disabled",
);
});
},
);
test.serial("does not save overlay status when build successful", async (t) => {
return await util.withTmpDir(async (tmpDir) => {
setupActionsVars(tmpDir, tmpDir);
// Mark analyze as having completed successfully.
process.env[EnvVar.ANALYZE_DID_COMPLETE_SUCCESSFULLY] = "true";
sinon.stub(util, "checkDiskUsage").resolves({
numAvailableBytes: 100 * NUM_BYTES_PER_GIB,
numTotalBytes: 200 * NUM_BYTES_PER_GIB,
});
const saveOverlayStatusStub = sinon
.stub(overlayStatus, "saveOverlayStatus")
.resolves(true);
await initActionPostHelper.uploadFailureInfo(
sinon.spy(),
sinon.spy(),
codeql.createStubCodeQL({}),
createTestConfig({
debugMode: false,
languages: ["javascript"],
overlayDatabaseMode: OverlayDatabaseMode.OverlayBase,
}),
parseRepositoryNwo("github/codeql-action"),
createFeatures([Feature.OverlayAnalysisStatusSave]),
getRunnerLogger(true),
);
t.true(
saveOverlayStatusStub.notCalled,
"saveOverlayStatus should not be called when build completed successfully",
);
});
});
test.serial(
"does not save overlay status when overlay not enabled",
async (t) => {
return await util.withTmpDir(async (tmpDir) => {
setupActionsVars(tmpDir, tmpDir);
delete process.env[EnvVar.ANALYZE_DID_COMPLETE_SUCCESSFULLY];
sinon.stub(util, "checkDiskUsage").resolves({
numAvailableBytes: 100 * NUM_BYTES_PER_GIB,
numTotalBytes: 200 * NUM_BYTES_PER_GIB,
});
const saveOverlayStatusStub = sinon
.stub(overlayStatus, "saveOverlayStatus")
.resolves(true);
await initActionPostHelper.uploadFailureInfo(
sinon.spy(),
sinon.spy(),
codeql.createStubCodeQL({}),
createTestConfig({
debugMode: false,
languages: ["javascript"],
overlayDatabaseMode: OverlayDatabaseMode.None,
}),
parseRepositoryNwo("github/codeql-action"),
createFeatures([]),
getRunnerLogger(true),
);
t.true(
saveOverlayStatusStub.notCalled,
"saveOverlayStatus should not be called when overlay is not enabled",
);
});
},
);
function createTestWorkflow(
steps: workflow.WorkflowJobStep[],
): workflow.Workflow {
return {
name: "CodeQL",
on: {
push: {
branches: ["main"],
},
pull_request: {
branches: ["main"],
},
},
jobs: {
analyze: {
name: "CodeQL Analysis",
"runs-on": "ubuntu-latest",
steps,
},
},
};
}
async function testFailedSarifUpload(
t: ExecutionContext<unknown>,
actionsWorkflow: workflow.Workflow,
{
category,
databaseExists = true,
expectUpload = true,
exportDiagnosticsEnabled = false,
matrix = {},
analysisKinds = [AnalysisKind.CodeScanning],
}: {
category?: string;
databaseExists?: boolean;
expectUpload?: boolean;
exportDiagnosticsEnabled?: boolean;
matrix?: { [key: string]: string };
analysisKinds?: AnalysisKind[];
} = {},
): Promise<initActionPostHelper.UploadFailedSarifResult> {
const config = createTestConfig({
analysisKinds,
codeQLCmd: "codeql",
debugMode: true,
languages: [],
});
if (databaseExists) {
config.dbLocation = "path/to/database";
}
process.env["GITHUB_JOB"] = "analyze";
process.env["GITHUB_REPOSITORY"] = DEFAULT_ACTIONS_VARS.GITHUB_REPOSITORY;
process.env["GITHUB_WORKSPACE"] = "/tmp";
sinon
.stub(actionsUtil, "getRequiredInput")
.withArgs("matrix")
.returns(JSON.stringify(matrix));
const codeqlObject = await codeql.getCodeQLForTesting();
sinon.stub(codeql, "getCodeQL").resolves(codeqlObject);
sinon.stub(codeqlObject, "getVersion").resolves(makeVersionInfo("2.17.6"));
const databaseExportDiagnosticsStub = sinon.stub(
codeqlObject,
"databaseExportDiagnostics",
);
const diagnosticsExportStub = sinon.stub(codeqlObject, "diagnosticsExport");
sinon.stub(workflow, "getWorkflow").resolves(actionsWorkflow);
const uploadFiles = sinon.stub(uploadLib, "uploadFiles");
uploadFiles.resolves({
sarifID: "42",
statusReport: { raw_upload_size_bytes: 20, zipped_upload_size_bytes: 10 },
} as uploadLib.UploadResult);
const waitForProcessing = sinon.stub(uploadLib, "waitForProcessing");
const features = [] as Feature[];
if (exportDiagnosticsEnabled) {
features.push(Feature.ExportDiagnosticsEnabled);
}
const result = await initActionPostHelper.tryUploadSarifIfRunFailed(
config,
parseRepositoryNwo("github/codeql-action"),
createFeatures(features),
getRunnerLogger(true),
);
if (expectUpload) {
t.deepEqual(result, {
sarifID: "42",
raw_upload_size_bytes: 20,
zipped_upload_size_bytes: 10,
});
if (databaseExists && exportDiagnosticsEnabled) {
t.true(
databaseExportDiagnosticsStub.calledOnceWith(
config.dbLocation,
sinon.match.string,
category,
),
`Actual args were: ${JSON.stringify(databaseExportDiagnosticsStub.args)}`,
);
} else {
t.true(
diagnosticsExportStub.calledOnceWith(
sinon.match.string,
category,
config,
),
`Actual args were: ${JSON.stringify(diagnosticsExportStub.args)}`,
);
}
t.true(
uploadFiles.calledOnceWith(
sinon.match.string,
sinon.match.string,
category,
sinon.match.any,
sinon.match.any,
),
`Actual args were: ${JSON.stringify(uploadFiles.args)}`,
);
t.true(
waitForProcessing.calledOnceWith(sinon.match.any, "42", sinon.match.any, {
isUnsuccessfulExecution: true,
}),
);
} else {
t.true(diagnosticsExportStub.notCalled);
t.true(uploadFiles.notCalled);
t.true(waitForProcessing.notCalled);
}
return result;
}
const singleLanguageMatrix = JSON.stringify({
language: "javascript",
category: "/language:javascript",
"build-mode": "none",
runner: "ubuntu-latest",
});
async function mockRiskAssessmentEnv(matrix: string) {
process.env[EnvVar.ANALYZE_DID_COMPLETE_SUCCESSFULLY] = "false";
process.env["GITHUB_JOB"] = "analyze";
process.env["GITHUB_REPOSITORY"] = "github/codeql-action-fake-repository";
process.env["GITHUB_WORKSPACE"] =
"/home/runner/work/codeql-action-fake-repository/codeql-action-fake-repository";
sinon
.stub(apiClient, "getGitHubVersion")
.resolves({ type: util.GitHubVariant.GHES, version: "3.0.0" });
const codeqlObject = await codeql.getCodeQLForTesting();
const databaseExportDiagnostics = sinon
.stub(codeqlObject, "databaseExportDiagnostics")
.resolves();
const diagnosticsExport = sinon
.stub(codeqlObject, "diagnosticsExport")
.resolves();
sinon.stub(codeql, "getCodeQL").resolves(codeqlObject);
sinon.stub(core, "getInput").withArgs("matrix").returns(matrix);
const uploadArtifact = sinon.stub().resolves();
const artifactClient = { uploadArtifact };
sinon
.stub(debugArtifacts, "getArtifactUploaderClient")
.value(() => artifactClient);
return { uploadArtifact, databaseExportDiagnostics, diagnosticsExport };
}
test.serial(
"tryUploadSarifIfRunFailed - uploads as artifact for risk assessments (diagnosticsExport)",
async (t) => {
const logger = new RecordingLogger();
const { uploadArtifact, databaseExportDiagnostics, diagnosticsExport } =
await mockRiskAssessmentEnv(singleLanguageMatrix);
const config = createTestConfig({
analysisKinds: [AnalysisKind.RiskAssessment],
codeQLCmd: "codeql-for-testing",
languages: ["javascript"],
});
const features = createFeatures([]);
const result = await initActionPostHelper.tryUploadSarifIfRunFailed(
config,
parseRepositoryNwo("github/codeql-action-fake-repository"),
features,
logger,
);
const expectedName = debugArtifacts.sanitizeArtifactName(
`sarif-artifact-${debugArtifacts.getArtifactSuffix(singleLanguageMatrix)}`,
);
const expectedFilePattern = /codeql-failed-sarif-javascript\.csra\.sarif$/;
t.is(result.upload_failed_run_skipped_because, undefined);
t.is(result.upload_failed_run_error, undefined);
t.is(result.sarifID, expectedName);
t.assert(
uploadArtifact.calledOnceWith(
expectedName,
[sinon.match(expectedFilePattern)],
sinon.match.string,
),
);
t.assert(databaseExportDiagnostics.notCalled);
t.assert(
diagnosticsExport.calledOnceWith(
sinon.match(expectedFilePattern),
"/language:javascript",
config,
),
);
},
);
test.serial(
"tryUploadSarifIfRunFailed - uploads as artifact for risk assessments (databaseExportDiagnostics)",
async (t) => {
const logger = new RecordingLogger();
const { uploadArtifact, databaseExportDiagnostics, diagnosticsExport } =
await mockRiskAssessmentEnv(singleLanguageMatrix);
const dbLocation = "/some/path";
const config = createTestConfig({
analysisKinds: [AnalysisKind.RiskAssessment],
codeQLCmd: "codeql-for-testing",
languages: ["javascript"],
dbLocation: "/some/path",
});
const features = createFeatures([Feature.ExportDiagnosticsEnabled]);
const result = await initActionPostHelper.tryUploadSarifIfRunFailed(
config,
parseRepositoryNwo("github/codeql-action-fake-repository"),
features,
logger,
);
const expectedName = debugArtifacts.sanitizeArtifactName(
`sarif-artifact-${debugArtifacts.getArtifactSuffix(singleLanguageMatrix)}`,
);
const expectedFilePattern = /codeql-failed-sarif-javascript\.csra\.sarif$/;
t.is(result.upload_failed_run_skipped_because, undefined);
t.is(result.upload_failed_run_error, undefined);
t.is(result.sarifID, expectedName);
t.assert(
uploadArtifact.calledOnceWith(
expectedName,
[sinon.match(expectedFilePattern)],
sinon.match.string,
),
);
t.assert(diagnosticsExport.notCalled);
t.assert(
databaseExportDiagnostics.calledOnceWith(
dbLocation,
sinon.match(expectedFilePattern),
"/language:javascript",
),
);
},
);
const skippedUploadTest = test.macro({
exec: async (
t: ExecutionContext<unknown>,
config: Partial<configUtils.Config>,
expectedSkippedReason: string,
) => {
const logger = new RecordingLogger();
const { uploadArtifact, diagnosticsExport } =
await mockRiskAssessmentEnv(singleLanguageMatrix);
const features = createFeatures([]);
const result = await initActionPostHelper.tryUploadSarifIfRunFailed(
createTestConfig(config),
parseRepositoryNwo("github/codeql-action-fake-repository"),
features,
logger,
);
t.is(result.upload_failed_run_skipped_because, expectedSkippedReason);
t.assert(uploadArtifact.notCalled);
t.assert(diagnosticsExport.notCalled);
},
title: (providedTitle: string = "") =>
`tryUploadSarifIfRunFailed - skips upload ${providedTitle}`,
});
test.serial(
"without CodeQL command",
skippedUploadTest,
// No codeQLCmd
{
analysisKinds: [AnalysisKind.RiskAssessment],
languages: ["javascript"],
} satisfies Partial<configUtils.Config>,
"CodeQL command not found",
);
test.serial(
"if no language is configured",
skippedUploadTest,
// No explicit language configuration
{
analysisKinds: [AnalysisKind.RiskAssessment],
codeQLCmd: "codeql-for-testing",
} satisfies Partial<configUtils.Config>,
"Unexpectedly, the configuration is not for a single language.",
);
test.serial(
"if multiple languages is configured",
skippedUploadTest,
// Multiple explicit languages configured
{
analysisKinds: [AnalysisKind.RiskAssessment],
codeQLCmd: "codeql-for-testing",
languages: ["javascript", "python"],
} satisfies Partial<configUtils.Config>,
"Unexpectedly, the configuration is not for a single language.",
);