-
Notifications
You must be signed in to change notification settings - Fork 181
Expand file tree
/
Copy pathwrite.spec.ts
More file actions
1345 lines (1284 loc) · 54.9 KB
/
write.spec.ts
File metadata and controls
1345 lines (1284 loc) · 54.9 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
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
import * as path from 'path';
import { promises as fs } from 'fs';
import * as cheerio from 'cheerio';
import markdownit from 'markdown-it';
import rimraf from 'rimraf';
import { Config } from '../src/config';
import { Benchmark } from '../src/extract';
import { DataJson, writeBenchmark } from '../src/write';
import { expect } from '@jest/globals';
import { FakedOctokit, fakedRepos } from './fakedOctokit';
import { wrapBodyWithBenchmarkTags } from '../src/comment/benchmarkCommentTags';
const ok: (x: any, msg?: string) => asserts x = (x, msg) => {
try {
expect(x).toBeTruthy();
} catch (err) {
if (msg) {
throw Error(msg);
}
throw err;
}
};
type GitFunc = 'cmd' | 'push' | 'pull' | 'fetch' | 'clone' | 'checkout';
class GitSpy {
history: [GitFunc, unknown[]][];
pushFailure: null | string;
pushFailureCount: number;
constructor() {
this.history = [];
this.pushFailure = null;
this.pushFailureCount = 0;
}
call(func: GitFunc, args: unknown[]) {
this.history.push([func, args]);
}
clear() {
this.history = [];
this.pushFailure = null;
this.pushFailureCount = 0;
}
mayFailPush() {
if (this.pushFailure !== null && this.pushFailureCount > 0) {
--this.pushFailureCount;
throw new Error(this.pushFailure);
}
}
}
const gitSpy = new GitSpy();
interface RepositoryPayloadSubset {
private: boolean;
html_url: string;
}
const gitHubContext = {
repo: {
repo: 'repo',
owner: 'user',
},
payload: {
repository: {
private: false,
html_url: 'https://github.com/user/repo',
} as RepositoryPayloadSubset | null,
},
workflow: 'Workflow name',
};
jest.mock('@actions/core', () => ({
debug: () => {
/* do nothing */
},
warning: () => {
/* do nothing */
},
}));
jest.mock('@actions/github', () => ({
get context() {
return gitHubContext;
},
getOctokit(token: string) {
return new FakedOctokit(token);
},
}));
jest.mock('../src/git', () => ({
...jest.requireActual('../src/git'),
async cmd(...args: unknown[]) {
gitSpy.call('cmd', args);
return '';
},
async push(...args: unknown[]) {
gitSpy.call('push', args);
gitSpy.mayFailPush(); // For testing retry
return '';
},
async pull(...args: unknown[]) {
gitSpy.call('pull', args);
return '';
},
async fetch(...args: unknown[]) {
gitSpy.call('fetch', args);
return '';
},
async clone(...args: unknown[]) {
gitSpy.call('clone', args);
return '';
},
async checkout(...args: unknown[]) {
gitSpy.call('checkout', args);
return '';
},
}));
describe.each(['https://github.com', 'https://github.enterprise.corp'])('writeBenchmark() - %s', function (serverUrl) {
const savedCwd = process.cwd();
beforeAll(function () {
process.chdir(path.join(__dirname, 'data', 'write'));
});
afterAll(function () {
jest.unmock('@actions/core');
jest.unmock('@actions/github');
jest.unmock('../src/git');
process.chdir(savedCwd);
});
afterEach(function () {
fakedRepos.clear();
});
// Utilities for test data
const lastUpdate = Date.now() - 10000;
const user = {
email: 'dummy@example.com',
name: 'User',
username: 'user',
};
const repoUrl = `${serverUrl}/user/repo`;
function commit(id = 'commit id', message = 'dummy message', u = user) {
return {
author: u,
committer: u,
distinct: false,
id,
message,
timestamp: 'dummy stamp',
tree_id: 'dummy tree id',
url: `${serverUrl}/user/repo/commit/` + id,
};
}
function bench(name: string, value: number, range = '± 20', unit = 'ns/iter') {
return {
name,
range,
unit,
value,
};
}
describe('with external json file', function () {
const dataJson = 'data.json';
const defaultCfg: Config = {
name: 'Test benchmark',
tool: 'cargo',
outputFilePath: 'dummy', // Should not affect
ghPagesBranch: 'dummy', // Should not affect
ghRepository: undefined,
benchmarkDataDirPath: 'dummy', // Should not affect
githubToken: undefined,
autoPush: false,
skipFetchGhPages: false, // Should not affect
summaryAlways: false,
commentAlways: false,
saveDataFile: true,
commentOnAlert: false,
alertThreshold: 2.0,
failOnAlert: true,
alertCommentCcUsers: ['@user'],
externalDataJsonPath: dataJson,
maxItemsInChart: null,
failThreshold: 2.0,
ref: undefined,
};
const savedRepository = {
private: false,
html_url: `${serverUrl}/user/repo`,
} as RepositoryPayloadSubset | null;
afterEach(async function () {
try {
await fs.unlink(dataJson);
} catch (_) {
// Ignore
}
gitHubContext.payload.repository = savedRepository;
});
const md2html = markdownit();
const normalCases: Array<{
it: string;
config: Config;
data: DataJson | null;
added: Benchmark;
error?: string[];
commitComment?: string;
repoPayload?: null | RepositoryPayloadSubset;
gitServerUrl?: string;
}> = [
{
it: 'appends new result to existing data',
config: defaultCfg,
data: {
lastUpdate,
repoUrl,
entries: {
'Test benchmark': [
{
commit: commit('prev commit id'),
date: lastUpdate - 1000,
tool: 'cargo',
benches: [bench('bench_fib_10', 100)],
},
],
},
},
added: {
commit: commit('current commit id'),
date: lastUpdate,
tool: 'cargo',
benches: [bench('bench_fib_10', 135)],
},
gitServerUrl: serverUrl,
},
{
it: 'creates new data file',
config: defaultCfg,
data: null,
added: {
commit: commit('current commit id'),
date: lastUpdate,
tool: 'cargo',
benches: [bench('bench_fib_10', 135)],
},
},
{
it: 'creates new result suite to existing data file',
config: defaultCfg,
data: {
lastUpdate,
repoUrl,
entries: {
'Other benchmark': [
{
commit: commit('prev commit id'),
date: lastUpdate - 1000,
tool: 'cargo',
benches: [bench('bench_fib_10', 10)],
},
],
},
},
added: {
commit: commit('current commit id'),
date: lastUpdate,
tool: 'cargo',
benches: [bench('bench_fib_10', 135)],
},
},
{
it: 'appends new result to existing multiple benchmarks data',
config: defaultCfg,
data: {
lastUpdate,
repoUrl,
entries: {
'Test benchmark': [
{
commit: commit('prev commit id'),
date: lastUpdate - 1000,
tool: 'pytest',
benches: [bench('bench_fib_10', 100)],
},
],
'Other benchmark': [
{
commit: commit('prev commit id'),
date: lastUpdate - 1000,
tool: 'cargo',
benches: [bench('bench_fib_10', 10)],
},
],
},
},
added: {
commit: commit('current commit id'),
date: lastUpdate,
tool: 'pytest',
benches: [bench('bench_fib_10', 135)],
},
},
{
it: 'raises an alert when exceeding threshold 2.0',
config: defaultCfg,
data: {
lastUpdate,
repoUrl,
entries: {
'Test benchmark': [
{
commit: commit('prev commit id'),
date: lastUpdate - 1000,
tool: 'go',
benches: [bench('bench_fib_10', 100), bench('bench_fib_20', 10000)],
},
],
},
},
added: {
commit: commit('current commit id'),
date: lastUpdate,
tool: 'go',
benches: [bench('bench_fib_10', 210), bench('bench_fib_20', 25000)], // Exceeds 2.0 threshold
},
error: [
'# :warning: **Performance Alert** :warning:',
'',
"Possible performance regression was detected for benchmark **'Test benchmark'**.",
'Benchmark result of this commit is worse than the previous benchmark result exceeding threshold `2`.',
'',
'| Benchmark suite | Current: current commit id | Previous: prev commit id | Ratio |',
'|-|-|-|-|',
'| `bench_fib_10` | `210ns/iter`<br>(`± 20ns`) | `100ns/iter`<br>(`± 20ns`) | `2.10` |',
'| `bench_fib_20` | `25μs/iter`<br>(`± 20ns`) | `10μs/iter`<br>(`± 20ns`) | `2.50` |',
'',
`This comment was automatically generated by [workflow](${serverUrl}/user/repo/actions?query=workflow%3AWorkflow%20name) using [github-action-benchmark](https://github.com/marketplace/actions/continuous-benchmark).`,
'',
'CC: @user',
],
},
{
it: 'raises an alert with tool whose result value is bigger-is-better',
config: defaultCfg,
data: {
lastUpdate,
repoUrl,
entries: {
'Test benchmark': [
{
commit: commit('prev commit id'),
date: lastUpdate - 1000,
tool: 'benchmarkjs',
benches: [bench('benchFib10', 100, '+-20', 'ops/sec')],
},
],
},
},
added: {
commit: commit('current commit id'),
date: lastUpdate,
tool: 'benchmarkjs',
benches: [bench('benchFib10', 20, '+-20', 'ops/sec')], // ops/sec so bigger is better
},
error: [
'# :warning: **Performance Alert** :warning:',
'',
"Possible performance regression was detected for benchmark **'Test benchmark'**.",
'Benchmark result of this commit is worse than the previous benchmark result exceeding threshold `2`.',
'',
'| Benchmark suite | Current: current commit id | Previous: prev commit id | Ratio |',
'|-|-|-|-|',
'| `benchFib10` | `20 ops/sec`<br>(`+-20`) | `100 ops/sec`<br>(`+-20`) | `5` |',
'',
`This comment was automatically generated by [workflow](${serverUrl}/user/repo/actions?query=workflow%3AWorkflow%20name) using [github-action-benchmark](https://github.com/marketplace/actions/continuous-benchmark).`,
'',
'CC: @user',
],
},
{
it: 'raises an alert without benchmark name with default benchmark name',
config: { ...defaultCfg, name: 'Benchmark' },
data: {
lastUpdate,
repoUrl,
entries: {
Benchmark: [
{
commit: commit('prev commit id'),
date: lastUpdate - 1000,
tool: 'cargo',
benches: [bench('bench_fib_10', 100)],
},
],
},
},
added: {
commit: commit('current commit id'),
date: lastUpdate,
tool: 'cargo',
benches: [bench('bench_fib_10', 210)], // Exceeds 2.0 threshold
},
error: [
'# :warning: **Performance Alert** :warning:',
'',
'Possible performance regression was detected for benchmark.',
'Benchmark result of this commit is worse than the previous benchmark result exceeding threshold `2`.',
'',
'| Benchmark suite | Current: current commit id | Previous: prev commit id | Ratio |',
'|-|-|-|-|',
'| `bench_fib_10` | `210ns/iter`<br>(`± 20ns`) | `100ns/iter`<br>(`± 20ns`) | `2.10` |',
'',
`This comment was automatically generated by [workflow](${serverUrl}/user/repo/actions?query=workflow%3AWorkflow%20name) using [github-action-benchmark](https://github.com/marketplace/actions/continuous-benchmark).`,
'',
'CC: @user',
],
},
{
it: 'raises an alert without CC names',
config: { ...defaultCfg, alertCommentCcUsers: [] },
data: {
lastUpdate,
repoUrl,
entries: {
'Test benchmark': [
{
commit: commit('prev commit id'),
date: lastUpdate - 1000,
tool: 'googlecpp',
benches: [bench('bench_fib_10', 100)],
},
],
},
},
added: {
commit: commit('current commit id'),
date: lastUpdate,
tool: 'googlecpp',
benches: [bench('bench_fib_10', 210)], // Exceeds 2.0 threshold
},
error: [
'# :warning: **Performance Alert** :warning:',
'',
"Possible performance regression was detected for benchmark **'Test benchmark'**.",
'Benchmark result of this commit is worse than the previous benchmark result exceeding threshold `2`.',
'',
'| Benchmark suite | Current: current commit id | Previous: prev commit id | Ratio |',
'|-|-|-|-|',
'| `bench_fib_10` | `210ns/iter`<br>(`± 20ns`) | `100ns/iter`<br>(`± 20ns`) | `2.10` |',
'',
`This comment was automatically generated by [workflow](${serverUrl}/user/repo/actions?query=workflow%3AWorkflow%20name) using [github-action-benchmark](https://github.com/marketplace/actions/continuous-benchmark).`,
],
},
{
it: 'sends commit comment on alert with GitHub API',
config: { ...defaultCfg, commentOnAlert: true, githubToken: 'dummy token' },
data: {
lastUpdate,
repoUrl,
entries: {
'Test benchmark': [
{
commit: commit('prev commit id'),
date: lastUpdate - 1000,
tool: 'cargo',
benches: [bench('bench_fib_10', 100)],
},
],
},
},
added: {
commit: commit('current commit id'),
date: lastUpdate,
tool: 'cargo',
benches: [bench('bench_fib_10', 210)], // Exceeds 2.0 threshold
},
commitComment: 'Comment was generated at https://dummy-comment-url',
},
{
it: 'does not raise an alert when both comment-on-alert and fail-on-alert are disabled',
config: { ...defaultCfg, commentOnAlert: false, failOnAlert: false },
data: {
lastUpdate,
repoUrl,
entries: {
'Test benchmark': [
{
commit: commit('prev commit id'),
date: lastUpdate - 1000,
tool: 'cargo',
benches: [bench('bench_fib_10', 100)],
},
],
},
},
added: {
commit: commit('current commit id'),
date: lastUpdate,
tool: 'cargo',
benches: [bench('bench_fib_10', 210)], // Exceeds 2.0 threshold
},
error: undefined,
commitComment: undefined,
},
{
it: 'ignores other bench case on detecting alerts',
config: defaultCfg,
data: {
lastUpdate,
repoUrl,
entries: {
'Test benchmark': [
{
commit: commit('prev commit id'),
date: lastUpdate - 1000,
tool: 'cargo',
benches: [bench('another_bench', 100)],
},
],
},
},
added: {
commit: commit('current commit id'),
date: lastUpdate,
tool: 'cargo',
benches: [bench('bench_fib_10', 210)], // Exceeds 2.0 threshold
},
error: undefined,
commitComment: undefined,
},
{
it: 'throws an error when GitHub token is not set (though this case should not happen in favor of validation)',
config: { ...defaultCfg, commentOnAlert: true },
data: {
lastUpdate,
repoUrl,
entries: {
'Test benchmark': [
{
commit: commit('prev commit id'),
date: lastUpdate - 1000,
tool: 'cargo',
benches: [bench('bench_fib_10', 100)],
},
],
},
},
added: {
commit: commit('current commit id'),
date: lastUpdate,
tool: 'cargo',
benches: [bench('bench_fib_10', 210)], // Exceeds 2.0 threshold
},
error: ["'comment-on-alert' input is set but 'github-token' input is not set"],
commitComment: undefined,
},
{
it: 'truncates data items if it exceeds max-items-in-chart',
config: { ...defaultCfg, maxItemsInChart: 1 },
data: {
lastUpdate,
repoUrl,
entries: {
'Test benchmark': [
{
commit: commit('prev commit id'),
date: lastUpdate - 1000,
tool: 'go',
benches: [bench('bench_fib_10', 100), bench('bench_fib_20', 10000)],
},
],
},
},
added: {
commit: commit('current commit id'),
date: lastUpdate,
tool: 'go',
benches: [bench('bench_fib_10', 210), bench('bench_fib_20', 25000)], // Exceeds 2.0 threshold
},
// Though first item is truncated due to maxItemsInChart, alert still can be raised since previous data
// is obtained before truncating an array of data items.
error: [
'# :warning: **Performance Alert** :warning:',
'',
"Possible performance regression was detected for benchmark **'Test benchmark'**.",
'Benchmark result of this commit is worse than the previous benchmark result exceeding threshold `2`.',
'',
'| Benchmark suite | Current: current commit id | Previous: prev commit id | Ratio |',
'|-|-|-|-|',
'| `bench_fib_10` | `210ns/iter`<br>(`± 20ns`) | `100ns/iter`<br>(`± 20ns`) | `2.10` |',
'| `bench_fib_20` | `25μs/iter`<br>(`± 20ns`) | `10μs/iter`<br>(`± 20ns`) | `2.50` |',
'',
`This comment was automatically generated by [workflow](${serverUrl}/user/repo/actions?query=workflow%3AWorkflow%20name) using [github-action-benchmark](https://github.com/marketplace/actions/continuous-benchmark).`,
'',
'CC: @user',
],
},
{
it: 'changes title when threshold is zero which means comment always happens',
config: { ...defaultCfg, alertThreshold: 0, failThreshold: 0 },
data: {
lastUpdate,
repoUrl,
entries: {
'Test benchmark': [
{
commit: commit('prev commit id'),
date: lastUpdate - 1000,
tool: 'benchmarkjs',
benches: [bench('benchFib10', 100, '+-20', 'ops/sec')],
},
],
},
},
added: {
commit: commit('current commit id'),
date: lastUpdate,
tool: 'benchmarkjs',
benches: [bench('benchFib10', 100, '+-20', 'ops/sec')],
},
error: [
'# Performance Report',
'',
"Possible performance regression was detected for benchmark **'Test benchmark'**.",
'Benchmark result of this commit is worse than the previous benchmark result exceeding threshold `0`.',
'',
'| Benchmark suite | Current: current commit id | Previous: prev commit id | Ratio |',
'|-|-|-|-|',
'| `benchFib10` | `100 ops/sec`<br>(`+-20`) | `100 ops/sec`<br>(`+-20`) | `1` |',
'',
`This comment was automatically generated by [workflow](${serverUrl}/user/repo/actions?query=workflow%3AWorkflow%20name) using [github-action-benchmark](https://github.com/marketplace/actions/continuous-benchmark).`,
'',
'CC: @user',
],
},
{
it: 'raises an alert with different failure threshold from alert threshold',
config: { ...defaultCfg, failThreshold: 3 },
data: {
lastUpdate,
repoUrl,
entries: {
'Test benchmark': [
{
commit: commit('prev commit id'),
date: lastUpdate - 1000,
tool: 'go',
benches: [bench('bench_fib_10', 100)],
},
],
},
},
added: {
commit: commit('current commit id'),
date: lastUpdate,
tool: 'go',
benches: [bench('bench_fib_10', 350)], // Exceeds 3.0 failure threshold
},
error: [
'1 of 1 alerts exceeded the failure threshold `3` specified by fail-threshold input:',
'',
'# :warning: **Performance Alert** :warning:',
'',
"Possible performance regression was detected for benchmark **'Test benchmark'**.",
'Benchmark result of this commit is worse than the previous benchmark result exceeding threshold `2`.',
'',
'| Benchmark suite | Current: current commit id | Previous: prev commit id | Ratio |',
'|-|-|-|-|',
'| `bench_fib_10` | `350ns/iter`<br>(`± 20ns`) | `100ns/iter`<br>(`± 20ns`) | `3.50` |',
'',
`This comment was automatically generated by [workflow](${serverUrl}/user/repo/actions?query=workflow%3AWorkflow%20name) using [github-action-benchmark](https://github.com/marketplace/actions/continuous-benchmark).`,
'',
'CC: @user',
],
},
{
it: 'does not raise an alert when not exceeding failure threshold',
config: { ...defaultCfg, failThreshold: 3 },
data: {
lastUpdate,
repoUrl,
entries: {
'Test benchmark': [
{
commit: commit('prev commit id'),
date: lastUpdate - 1000,
tool: 'go',
benches: [bench('bench_fib_10', 100)],
},
],
},
},
added: {
commit: commit('current commit id'),
date: lastUpdate,
tool: 'go',
benches: [bench('bench_fib_10', 210)], // Exceeds 2.0 threshold
},
error: undefined,
},
];
it.each(normalCases)('$it', async function (t) {
gitHubContext.payload.repository = {
private: false,
html_url: `${serverUrl}/user/repo`,
} as RepositoryPayloadSubset | null;
if (t.repoPayload !== undefined) {
gitHubContext.payload.repository = t.repoPayload;
}
if (t.data !== null) {
await fs.writeFile(dataJson, JSON.stringify(t.data), 'utf8');
}
let caughtError: Error | null = null;
try {
await writeBenchmark(t.added, t.config);
} catch (err: any) {
if (!t.error && !t.commitComment) {
throw err;
}
caughtError = err;
}
const json: DataJson = JSON.parse(await fs.readFile(dataJson, 'utf8'));
expect('number').toEqual(typeof json.lastUpdate);
expect(json.entries[t.config.name]).toBeTruthy();
const len = json.entries[t.config.name].length;
ok(len > 0);
expect(t.added).toEqual(json.entries[t.config.name][len - 1]); // Check last item is the newest
if (t.data !== null) {
ok(json.lastUpdate > t.data.lastUpdate);
expect(t.data.repoUrl).toEqual(json.repoUrl);
for (const name of Object.keys(t.data.entries)) {
const entries = t.data.entries[name];
if (name === t.config.name) {
if (t.config.maxItemsInChart === null || len < t.config.maxItemsInChart) {
expect(entries.length + 1).toEqual(len);
// Check benchmark data except for the last appended one are not modified
expect(entries).toEqual(json.entries[name].slice(0, -1));
} else {
// When data items was truncated due to max-items-in-chart
expect(entries.length).toEqual(len); // Number of items did not change because first item was shifted
expect(entries.slice(1)).toEqual(json.entries[name].slice(0, -1));
}
} else {
expect(entries).toEqual(json.entries[name]); // eq(json.entries[name], entries, name);
}
}
}
if (t.error) {
ok(caughtError);
const expected = t.error.join('\n');
expect(caughtError.message).toEqual(expected);
}
if (t.commitComment !== undefined) {
ok(caughtError);
// Last line is appended only for failure message
const messageLines = caughtError.message.split('\n');
ok(messageLines.length > 0);
const expectedMessage = wrapBodyWithBenchmarkTags(
'Test benchmark Alert',
messageLines.slice(0, -1).join('\n'),
);
ok(fakedRepos.spyOpts.length > 0, `len: ${fakedRepos.spyOpts.length}, caught: ${caughtError.message}`);
const opts = fakedRepos.lastCall();
expect('user').toEqual(opts.owner);
expect('repo').toEqual(opts.repo);
expect('current commit id').toEqual(opts.commit_sha);
expect(expectedMessage).toEqual(opts.body);
const commentLine = messageLines[messageLines.length - 1];
expect(t.commitComment).toEqual(commentLine);
// Check the body is a correct markdown document by markdown parser
// Validate markdown content via HTML
// TODO: Use Markdown AST instead of DOM API
const html = md2html.render(opts.body);
const query = cheerio.load(html);
const h1 = query('h1');
expect(1).toEqual(h1.length);
expect(':warning: Performance Alert :warning:').toEqual(h1.text());
const tr = query('tbody tr');
expect(t.added.benches.length).toEqual(tr.length);
const a = query('a');
expect(2).toEqual(a.length);
const workflowLink = a.first();
expect('workflow').toEqual(workflowLink.text());
const workflowUrl = workflowLink.attr('href');
ok(workflowUrl?.startsWith(json.repoUrl), workflowUrl);
const actionLink = a.last();
expect('github-action-benchmark').toEqual(actionLink.text());
expect('https://github.com/marketplace/actions/continuous-benchmark').toEqual(actionLink.attr('href'));
}
});
});
// Tests for updating GitHub Pages branch
describe('with gh-pages branch', function () {
beforeEach(async function () {
(global as any).window = {}; // Fake window object on browser
});
afterEach(async function () {
gitSpy.clear();
delete (global as any).window;
for (const p of [
path.join('data-dir', 'data.js'),
path.join('data-dir', 'index.html'),
'new-data-dir',
path.join('with-index-html', 'data.js'),
path.join('benchmark-data-repository', 'data-dir', 'data.js'),
path.join('benchmark-data-repository', 'data-dir', 'index.html'),
path.join('benchmark-data-repository', 'new-data-dir'),
]) {
// Ignore exception
await new Promise((resolve) => rimraf(p, resolve));
}
});
async function isFile(p: string) {
try {
const s = await fs.stat(p);
return s.isFile();
} catch (_) {
return false;
}
}
async function isDir(p: string) {
try {
const s = await fs.stat(p);
return s.isDirectory();
} catch (_) {
return false;
}
}
async function loadDataJs(dataDir: string, serverUrl: string) {
const dataJs = path.join(dataDir, 'data.js');
if (!(await isDir(dataDir)) || !(await isFile(dataJs))) {
return null;
}
let dataSource = await fs.readFile(dataJs, 'utf8');
if (serverUrl !== 'https://github.com') {
dataSource = dataSource.replace(/https:\/\/github.com/gm, serverUrl);
}
eval(dataSource);
return (global as any).window.BENCHMARK_DATA as DataJson;
}
const defaultCfg: Config = {
name: 'Test benchmark',
tool: 'cargo',
outputFilePath: 'dummy', // Should not affect
ghPagesBranch: 'gh-pages',
ghRepository: undefined,
benchmarkDataDirPath: 'data-dir', // Should not affect
githubToken: 'dummy token',
autoPush: true,
skipFetchGhPages: false, // Should not affect
commentAlways: false,
summaryAlways: false,
saveDataFile: true,
commentOnAlert: false,
alertThreshold: 2.0,
failOnAlert: true,
alertCommentCcUsers: [],
externalDataJsonPath: undefined,
maxItemsInChart: null,
failThreshold: 2.0,
ref: undefined,
};
function gitHistory(
cfg: {
dir?: string;
addIndexHtml?: boolean;
autoPush?: boolean;
token?: string | undefined;
fetch?: boolean;
skipFetch?: boolean;
} = {},
): [GitFunc, unknown[]][] {
const dir = cfg.dir ?? 'data-dir';
const token = 'token' in cfg ? cfg.token : 'dummy token';
const fetch = cfg.fetch ?? true;
const addIndexHtml = cfg.addIndexHtml ?? true;
const autoPush = cfg.autoPush ?? true;
const skipFetch = cfg.skipFetch ?? false;
const hist: Array<[GitFunc, unknown[]] | undefined> = [
skipFetch ? undefined : ['fetch', [token, 'gh-pages']],
['cmd', [[], 'switch', 'gh-pages']],
fetch ? ['pull', [token, 'gh-pages']] : undefined,
['cmd', [[], 'add', path.join(dir, 'data.js')]],
addIndexHtml ? ['cmd', [[], 'add', path.join(dir, 'index.html')]] : undefined,
['cmd', [[], 'commit', '-m', 'add Test benchmark (cargo) benchmark result for current commit id']],
autoPush ? ['push', [token, undefined, 'gh-pages', []]] : undefined,
['cmd', [[], 'checkout', '-']], // Return from gh-pages
];
return hist.filter((x: [GitFunc, unknown[]] | undefined): x is [GitFunc, unknown[]] => x !== undefined);
}
const normalCases: Array<{
it: string;
config: Config;
added: Benchmark;
gitServerUrl: string;
gitHistory: [GitFunc, unknown[]][];
privateRepo?: boolean;
error?: string[];
expectedDataBaseDirectory?: string;
}> = [
{
it: 'appends new data',
config: defaultCfg,
added: {
commit: commit('current commit id'),
date: lastUpdate,
tool: 'cargo',
benches: [bench('bench_fib_10', 135)],
},
gitServerUrl: serverUrl,
gitHistory: gitHistory(),
},
{
it: 'creates new data file',
config: { ...defaultCfg, benchmarkDataDirPath: 'new-data-dir' },
added: {
commit: commit('current commit id'),
date: lastUpdate,
tool: 'cargo',
benches: [bench('bench_fib_10', 135)],
},
gitServerUrl: serverUrl,
gitHistory: gitHistory({ dir: 'new-data-dir' }),
},
{
it: 'appends new data in other repository',
config: {
...defaultCfg,
ghRepository: 'https://github.com/user/other-repo',
benchmarkDataDirPath: 'data-dir',
},
added: {
commit: commit('current commit id'),
date: lastUpdate,
tool: 'cargo',
benches: [bench('bench_fib_10', 135)],
},
gitServerUrl: serverUrl,
gitHistory: [
['clone', ['dummy token', 'https://github.com/user/other-repo', './benchmark-data-repository']],
[
'checkout',
[
'gh-pages',
['--work-tree=./benchmark-data-repository', '--git-dir=./benchmark-data-repository/.git'],
],
],
[
'cmd',
[
['--work-tree=./benchmark-data-repository', '--git-dir=./benchmark-data-repository/.git'],
'add',
path.join('data-dir', 'data.js'),
],
],
[
'cmd',
[
['--work-tree=./benchmark-data-repository', '--git-dir=./benchmark-data-repository/.git'],
'add',
path.join('data-dir', 'index.html'),
],
],
[
'cmd',
[
['--work-tree=./benchmark-data-repository', '--git-dir=./benchmark-data-repository/.git'],
'commit',
'-m',
'add Test benchmark (cargo) benchmark result for current commit id',
],