-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.html
More file actions
1536 lines (1427 loc) · 80.4 KB
/
Copy pathtest.html
File metadata and controls
1536 lines (1427 loc) · 80.4 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
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>PR 代码变更统计 — 自动化测试</title>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; padding: 20px; max-width: 900px; margin: 0 auto; }
h1 { font-size: 1.3rem; margin-bottom: 16px; }
.suite { margin-bottom: 20px; }
.suite h2 { font-size: 1rem; color: #374151; margin-bottom: 8px; }
.result { padding: 4px 8px; font-size: .85rem; border-left: 3px solid; margin-bottom: 2px; }
.pass { border-color: #16a34a; background: #f0fdf4; }
.fail { border-color: #dc2626; background: #fef2f2; }
.summary { margin-top: 20px; font-weight: 600; font-size: 1rem; }
.summary.all-pass { color: #16a34a; }
.summary.has-fail { color: #dc2626; }
.load-error { color: #dc2626; margin: 20px 0; padding: 12px; background: #fef2f2; border-radius: 6px; }
</style>
</head>
<body>
<h1>PR 代码变更统计 — 自动化测试</h1>
<div id="load-status">正在加载 index.html 生产代码...</div>
<div id="output"></div>
<div id="summary" class="summary"></div>
<!--
FCR-2 fix: Load production code from index.html via a hidden iframe.
Tests run against the REAL production functions (parseRepoUrl, CsvHelper,
StatsEngine, GitHubProvider, GitCodeProvider), not copies.
Requires HTTP server (e.g. python3 -m http.server 8901).
-->
<iframe id="app-frame" src="index.html" style="display:none"></iframe>
<script>
// ========== Minimal test framework ==========
var results = [];
var currentSuite = '';
function suite(name) { currentSuite = name; }
function assert(condition, msg) {
results.push({ suite: currentSuite, msg: msg, pass: !!condition });
}
function assertEqual(actual, expected, msg) {
var pass = JSON.stringify(actual) === JSON.stringify(expected);
results.push({ suite: currentSuite, msg: msg + (pass ? '' : ' — expected ' + JSON.stringify(expected) + ', got ' + JSON.stringify(actual)), pass: pass });
}
// ========== Wait for iframe to load, then run tests against production code ==========
document.getElementById('app-frame').addEventListener('load', async function() {
var app = this.contentWindow;
var loadStatus = document.getElementById('load-status');
// Verify production functions are accessible
var requiredFns = ['parseRepoUrl', 'escapeHtml', 'repoKey'];
var requiredObjs = ['CsvHelper', 'StatsEngine', 'GitHubProvider', 'GitCodeProvider'];
var missing = [];
requiredFns.forEach(function(fn) { if (typeof app[fn] !== 'function') missing.push(fn); });
requiredObjs.forEach(function(obj) { if (typeof app[obj] !== 'object' || app[obj] === null) missing.push(obj); });
if (missing.length > 0) {
loadStatus.className = 'load-error';
loadStatus.textContent = '无法加载生产函数: ' + missing.join(', ') + '。请通过 HTTP 服务器访问(python3 -m http.server 8901)';
return;
}
loadStatus.style.display = 'none';
// Alias production functions
var parseRepoUrl = app.parseRepoUrl;
var CsvHelper = app.CsvHelper;
var escapeHtml = app.escapeHtml;
var repoKey = app.repoKey;
var mapActivitiesToUsers = app.StatsEngine.mapActivitiesToUsers.bind(app.StatsEngine);
var aggregate = app.StatsEngine.aggregate.bind(app.StatsEngine);
var applyDisplayFilters = app.StatsEngine.applyDisplayFilters.bind(app.StatsEngine);
// ==================== Test Suites ====================
// --- parseRepoUrl ---
suite('parseRepoUrl');
assertEqual(parseRepoUrl('https://github.com/org/repo'), {platform:'github',owner:'org',repo:'repo'}, 'basic GitHub HTTPS');
assertEqual(parseRepoUrl('https://gitcode.com/org/repo'), {platform:'gitcode',owner:'org',repo:'repo'}, 'basic GitCode HTTPS');
assertEqual(parseRepoUrl('https://github.com/org/repo.git'), {platform:'github',owner:'org',repo:'repo'}, 'strip .git suffix');
assertEqual(parseRepoUrl('git@github.com:org/repo.git'), {platform:'github',owner:'org',repo:'repo'}, 'SSH with .git');
assertEqual(parseRepoUrl('https://github.com/acme/my.repo.git'), {platform:'github',owner:'acme',repo:'my.repo'}, 'FC-4: dots in repo name');
assertEqual(parseRepoUrl('https://github.com/acme/my.repo'), {platform:'github',owner:'acme',repo:'my.repo'}, 'dots without .git');
assertEqual(parseRepoUrl('https://github.com/a/b.c.d.git'), {platform:'github',owner:'a',repo:'b.c.d'}, 'multiple dots + .git');
assertEqual(parseRepoUrl(''), null, 'empty string');
assertEqual(parseRepoUrl('https://gitlab.com/org/repo'), null, 'unsupported platform');
assertEqual(parseRepoUrl('not a url'), null, 'invalid input');
// --- CsvHelper.parse ---
suite('CsvHelper.parse');
assertEqual(CsvHelper.parse('a,b\n1,2'), [['a','b'],['1','2']], 'simple 2x2');
assertEqual(CsvHelper.parse('a,b\n1,2'), [['a','b'],['1','2']], 'BOM stripped');
assertEqual(CsvHelper.parse('a,"b,c"\n1,"2"'), [['a','b,c'],['1','2']], 'quoted comma');
assertEqual(CsvHelper.parse('a,"b""c"\n1,2'), [['a','b"c'],['1','2']], 'escaped quote');
assertEqual(CsvHelper.parse('"line1\nline2",b'), [['line1\nline2','b']], 'newline in field');
assertEqual(CsvHelper.parse('a,b\r\n1,2\r\n'), [['a','b'],['1','2']], 'CRLF line endings');
assertEqual(CsvHelper.parse('a,b\n1,2\n\n'), [['a','b'],['1','2']], 'trailing empty rows removed');
// --- CsvHelper.sanitize (formula injection) ---
suite('CsvHelper.sanitize');
assertEqual(CsvHelper.sanitize('=SUM(A1)'), "'=SUM(A1)", 'prefix = with quote');
assertEqual(CsvHelper.sanitize('+cmd'), "'+cmd", 'prefix + with quote');
assertEqual(CsvHelper.sanitize('-cmd'), "'-cmd", 'prefix - with quote');
assertEqual(CsvHelper.sanitize('@import'), "'@import", 'prefix @ with quote');
assertEqual(CsvHelper.sanitize('hello'), 'hello', 'no prefix for normal text');
assertEqual(CsvHelper.sanitize(123), 123, 'non-string passthrough');
// --- CsvHelper.generate ---
suite('CsvHelper.generate');
var csv = CsvHelper.generate(['A','B'], [['1','2'],['x,y','=danger']]);
assert(csv.charCodeAt(0) === 0xFEFF, 'starts with BOM');
assert(csv.indexOf('"x,y"') > 0, 'comma in field is quoted');
assert(csv.indexOf("'=danger") > 0, 'formula sanitized');
assert(csv.indexOf('\r\n') > 0, 'uses CRLF');
// --- Activity mapping (platform:login matching) ---
suite('Activity mapping');
var testUsers = [
{ user_key: 'alice', display_name: 'Alice', github_login: 'alice-gh', gitcode_login: '', enabled: true },
{ user_key: 'bob', display_name: 'Bob', github_login: 'bob-gh', gitcode_login: '', enabled: true }
];
var testActivities = [
{ platform: 'github', repository: 'org/repoA', actor_login: 'alice-gh', activity_type: 'development', additions: 10 },
{ platform: 'github', repository: 'org/repoB', actor_login: 'alice-gh', activity_type: 'comment' },
{ platform: 'github', repository: 'org/repoA', actor_login: 'unknown-dev', activity_type: 'development' }
];
mapActivitiesToUsers(testActivities, testUsers);
assert(testActivities[0].matched === true && testActivities[0].user_key === 'alice', 'alice dev matched');
assert(testActivities[1].matched === true && testActivities[1].user_key === 'alice', 'alice comment matched cross-repo');
assert(testActivities[2].matched === false, 'unknown-dev not matched');
// --- Aggregate: A/B/C activity types ---
suite('Aggregate (A/B/C)');
var abcActivities = [
{ platform: 'github', repository: 'org/repo', actor_login: 'alice-gh', user_key: 'alice', display_name: 'Alice', matched: true, activity_type: 'development', additions: 100, deletions: 50, changed_files: 3, completeness: 'full' },
{ platform: 'github', repository: 'org/repo', actor_login: 'bob-gh', user_key: 'bob', display_name: 'Bob', matched: true, activity_type: 'comment', completeness: 'full' },
{ platform: 'github', repository: 'org/repo', actor_login: 'bob-gh', user_key: 'bob', display_name: 'Bob', matched: true, activity_type: 'comment', completeness: 'full' },
{ platform: 'github', repository: 'org/repo', actor_login: 'carol-gh', user_key: 'carol', display_name: 'Carol', matched: true, activity_type: 'approval', completeness: 'full' }
];
var abcAgg = aggregate(abcActivities);
var aliceRow = abcAgg.find(function(r) { return r.userKey === 'alice'; });
var bobRow = abcAgg.find(function(r) { return r.userKey === 'bob'; });
var carolRow = abcAgg.find(function(r) { return r.userKey === 'carol'; });
assert(aliceRow, 'alice row exists');
assertEqual(aliceRow.prCount, 1, 'alice 1 development');
assertEqual(aliceRow.commentCount, 0, 'alice 0 comments');
assertEqual(aliceRow.approveCount, 0, 'alice 0 approvals');
assertEqual(aliceRow.additions, 100, 'alice additions');
assert(bobRow, 'bob row exists');
assertEqual(bobRow.prCount, 0, 'bob 0 development');
assertEqual(bobRow.commentCount, 2, 'bob 2 comments');
assertEqual(bobRow.approveCount, 0, 'bob 0 approvals');
assertEqual(bobRow.additions, 0, 'bob code 0');
assert(carolRow, 'carol row exists');
assertEqual(carolRow.approveCount, 1, 'carol 1 approval');
// --- Display filters ---
suite('Display filters');
var filtered = applyDisplayFilters(abcActivities, { platform: 'github', user: 'bob', repo: 'org/repo' });
assertEqual(filtered.length, 2, 'filter to bob activities');
// --- GitHub fetchCollaboration: comments + approvals ---
suite('GitHub fetchCollaboration');
var ghProvider = app.GitHubProvider;
var ghOrigFetch = ghProvider._fetch;
ghProvider._fetch = function(url) {
if (url.indexOf('/issues/') >= 0) {
return Promise.resolve([
{ id: 1, user: { login: 'bob-gh' }, created_at: '2026-01-10T10:00:00Z', body: 'looks good', html_url: 'https://github.com/org/repo/issues/1' }
]);
}
if (url.indexOf('/pulls/') >= 0 && url.indexOf('/comments') >= 0) {
return Promise.resolve([
{ id: 2, user: { login: 'bob-gh' }, created_at: '2026-01-10T11:00:00Z', body: 'nit', html_url: 'https://github.com/org/repo/pull/1' }
]);
}
if (url.indexOf('/pulls/') >= 0 && url.indexOf('/reviews') >= 0) {
return Promise.resolve([
{ id: 3, user: { login: 'carol-gh' }, submitted_at: '2026-01-10T12:00:00Z', state: 'APPROVED', body: '' },
{ id: 4, user: { login: 'carol-gh' }, submitted_at: '2026-01-10T13:00:00Z', state: 'COMMENTED', body: 'thanks' }
]);
}
return Promise.resolve({});
};
var ghCollab = await ghProvider.fetchCollaboration('tok', 'org', 'repo', { number: 1, title: 'PR One', mergedAt: '2026-01-15T10:00:00Z', url: 'https://github.com/org/repo/pull/1' }, new AbortController().signal, function(){});
ghProvider._fetch = ghOrigFetch;
assert(ghCollab.activities.length === 4, 'github collab: 2 comments + 1 review_body + 1 approval = 4');
var ghComments = ghCollab.activities.filter(function(a) { return a.activity_type === 'comment'; });
var ghApprovals = ghCollab.activities.filter(function(a) { return a.activity_type === 'approval'; });
assertEqual(ghComments.length, 3, '3 comments total');
assertEqual(ghApprovals.length, 1, '1 approval after state collapse');
assertEqual(ghApprovals[0].actor_login, 'carol-gh', 'carol is approver');
assert(ghCollab.partial === false, 'github collab not partial');
// --- GitHub approve state collapse: APPROVED then CHANGES_REQUESTED -> no approve ---
suite('GitHub approve state collapse');
ghProvider._fetch = function(url) {
if (url.indexOf('/reviews') >= 0) {
return Promise.resolve([
{ id: 1, user: { login: 'carol-gh' }, submitted_at: '2026-01-10T12:00:00Z', state: 'APPROVED', body: '' },
{ id: 2, user: { login: 'carol-gh' }, submitted_at: '2026-01-10T13:00:00Z', state: 'CHANGES_REQUESTED', body: '' }
]);
}
return Promise.resolve([]);
};
var ghCollab2 = await ghProvider.fetchCollaboration('tok', 'org', 'repo', { number: 1, title: 'PR', mergedAt: '', url: '' }, new AbortController().signal, function(){});
ghProvider._fetch = ghOrigFetch;
var ghApprovals2 = ghCollab2.activities.filter(function(a) { return a.activity_type === 'approval'; });
assertEqual(ghApprovals2.length, 0, 'APPROVED then CHANGES_REQUESTED -> no approval');
// --- GitHub COMMENTED does not overwrite APPROVED ---
suite('GitHub COMMENTED does not overwrite APPROVED');
ghProvider._fetch = function(url) {
if (url.indexOf('/reviews') >= 0) {
return Promise.resolve([
{ id: 1, user: { login: 'carol-gh' }, submitted_at: '2026-01-10T12:00:00Z', state: 'APPROVED', body: '' },
{ id: 2, user: { login: 'carol-gh' }, submitted_at: '2026-01-10T13:00:00Z', state: 'COMMENTED', body: 'thanks' }
]);
}
return Promise.resolve([]);
};
var ghCollab3 = await ghProvider.fetchCollaboration('tok', 'org', 'repo', { number: 1, title: 'PR', mergedAt: '', url: '' }, new AbortController().signal, function(){});
ghProvider._fetch = ghOrigFetch;
var ghApprovals3 = ghCollab3.activities.filter(function(a) { return a.activity_type === 'approval'; });
var ghComments3 = ghCollab3.activities.filter(function(a) { return a.activity_type === 'comment'; });
assertEqual(ghApprovals3.length, 1, 'COMMENTED after APPROVED still keeps approval');
assertEqual(ghComments3.length, 1, 'COMMENTED body becomes comment');
// --- GitHub collaboration partial propagation ---
suite('GitHub collaboration partial propagation');
ghProvider._fetch = function(url) {
if (url.indexOf('/issues/') >= 0) throw new Error('fail');
return Promise.resolve([]);
};
var ghCollabPartial = await ghProvider.fetchCollaboration('tok', 'org', 'repo', { number: 1, title: 'PR', mergedAt: '', url: '' }, new AbortController().signal, function(){});
ghProvider._fetch = ghOrigFetch;
assert(ghCollabPartial.partial === true, 'failed issue comments -> partial');
assert(ghCollabPartial.partialReason.indexOf('Issue comments') >= 0, 'partial reason mentions issue comments');
// --- GitCode fetchCollaboration: comments + approvals ---
suite('GitCode fetchCollaboration');
var gcProvider = app.GitCodeProvider;
var gcOrigFetch = gcProvider._fetch;
gcProvider._fetch = function(url) {
if (url.indexOf('/comments') >= 0) {
return Promise.resolve([
{ id: 10, user: { login: 'bob-gc' }, created_at: '2026-01-10T10:00:00Z', body: 'ok', type: 'comment', html_url: 'https://gitcode.com/org/repo/pulls/1' }
]);
}
if (url.indexOf('/pulls/1') >= 0 && url.indexOf('/comments') < 0) {
return Promise.resolve({
approval_reviewers: [
{ login: 'carol-gc', accept: true },
{ login: 'dave-gc', accept: false }
],
assignees: [
{ login: 'carol-gc', accept: true }
]
});
}
return Promise.resolve({});
};
var gcCollab = await gcProvider.fetchCollaboration('tok', 'org', 'repo', { number: 1, title: 'PR One', mergedAt: '2026-01-15T10:00:00Z', url: 'https://gitcode.com/org/repo/pulls/1' }, new AbortController().signal, function(){});
gcProvider._fetch = gcOrigFetch;
var gcComments = gcCollab.activities.filter(function(a) { return a.activity_type === 'comment'; });
var gcApprovals = gcCollab.activities.filter(function(a) { return a.activity_type === 'approval'; });
assertEqual(gcComments.length, 1, 'gitcode 1 comment');
assertEqual(gcApprovals.length, 1, 'gitcode 1 approval (carol deduped)');
assertEqual(gcApprovals[0].actor_login, 'carol-gc', 'carol is approver');
assert(gcCollab.partial === false, 'gitcode collab not partial');
// --- GitCode accept=false excluded ---
suite('GitCode accept=false excluded');
gcProvider._fetch = function(url) {
if (url.indexOf('/pulls/1') >= 0 && url.indexOf('/comments') < 0) {
return Promise.resolve({ approval_reviewers: [{ login: 'dave-gc', accept: false }], assignees: [] });
}
return Promise.resolve([]);
};
var gcCollab2 = await gcProvider.fetchCollaboration('tok', 'org', 'repo', { number: 1, title: 'PR', mergedAt: '', url: '' }, new AbortController().signal, function(){});
gcProvider._fetch = gcOrigFetch;
var gcApprovals2 = gcCollab2.activities.filter(function(a) { return a.activity_type === 'approval'; });
assertEqual(gcApprovals2.length, 0, 'accept=false excluded');
// --- Provider regression: GitHub comment dedup by source_type + source_id ---
suite('GitHub comment dedup by source_type:source_id');
ghProvider._fetch = function(url) {
if (url.indexOf('/issues/') >= 0) {
return Promise.resolve([{ id: 42, user: { login: 'bob-gh' }, created_at: '2026-01-10T10:00:00Z', body: 'issue', html_url: 'u1' }]);
}
if (url.indexOf('/pulls/') >= 0 && url.indexOf('/comments') >= 0) {
return Promise.resolve([{ id: 42, user: { login: 'bob-gh' }, created_at: '2026-01-10T11:00:00Z', body: 'review', html_url: 'u2' }]);
}
if (url.indexOf('/reviews') >= 0) return Promise.resolve([]);
return Promise.resolve([]);
};
var ghDedup = await ghProvider.fetchCollaboration('tok', 'org', 'repo', { number: 1, title: 'PR', mergedAt: '', url: '' }, new AbortController().signal, function(){});
ghProvider._fetch = ghOrigFetch;
var issueComments = ghDedup.activities.filter(function(a) { return a.source_type === 'issue_comment'; });
var reviewComments = ghDedup.activities.filter(function(a) { return a.source_type === 'review_comment'; });
assertEqual(issueComments.length, 1, 'duplicate issue_comment id deduped to 1');
assertEqual(reviewComments.length, 1, 'duplicate review_comment id deduped to 1');
assertEqual(ghDedup.activities.length, 2, 'different source_types with same id both kept');
// --- Provider regression: GitCode source_type prefers comment_type ---
suite('GitCode source_type prefers comment_type');
gcProvider._fetch = function(url) {
if (url.indexOf('/comments') >= 0) {
return Promise.resolve([{ id: 1, user: { login: 'bob-gc' }, created_at: '2026-01-10T10:00:00Z', body: 'x', type: 'comment', comment_type: 'pr_comment' }]);
}
return Promise.resolve({ approval_reviewers: [], assignees: [] });
};
var gcType = await gcProvider.fetchCollaboration('tok', 'org', 'repo', { number: 1, title: 'PR', mergedAt: '', url: '' }, new AbortController().signal, function(){});
gcProvider._fetch = gcOrigFetch;
assertEqual(gcType.activities.length, 1, 'one comment activity');
assertEqual(gcType.activities[0].source_type, 'pr_comment', 'comment_type takes priority over type');
// --- Provider regression: GitCode approve case-insensitive dedup ---
suite('GitCode approve case-insensitive dedup');
gcProvider._fetch = function(url) {
if (url.indexOf('/comments') >= 0) return Promise.resolve([]);
return Promise.resolve({ approval_reviewers: [{ login: 'Carol-gc', accept: true }, { login: 'carol-gc', accept: true }], assignees: [] });
};
var gcCase = await gcProvider.fetchCollaboration('tok', 'org', 'repo', { number: 1, title: 'PR', mergedAt: '', url: '' }, new AbortController().signal, function(){});
gcProvider._fetch = gcOrigFetch;
var gcCaseApprovals = gcCase.activities.filter(function(a) { return a.activity_type === 'approval'; });
assertEqual(gcCaseApprovals.length, 1, 'Carol/carol deduped to one approval');
assertEqual(gcCaseApprovals[0].actor_login, 'Carol-gc', 'original casing preserved');
// --- Provider regression: _fetchPaged non-array response propagates partial ---
suite('GitHub _fetchPaged non-array response');
ghProvider._fetch = function(url) {
if (url.indexOf('/issues/') >= 0) return Promise.resolve({ not: 'array' });
return Promise.resolve([]);
};
var ghBad = await ghProvider.fetchCollaboration('tok', 'org', 'repo', { number: 1, title: 'PR', mergedAt: '', url: '' }, new AbortController().signal, function(){});
ghProvider._fetch = ghOrigFetch;
assert(ghBad.partial === true, 'non-array response marks partial');
assert(ghBad.partialReason.indexOf('返回格式异常') >= 0, 'partialReason mentions format error');
// --- Provider regression: createLimiter max concurrency ---
suite('createLimiter max concurrency <= 3');
var limiter = app.createLimiter(3, 0);
var running = 0, maxRunning = 0;
var limiterTasks = [];
for (var i = 0; i < 5; i++) {
limiterTasks.push(limiter(function() {
running++;
if (running > maxRunning) maxRunning = running;
return new Promise(function(resolve) {
setTimeout(function() { running--; resolve(); }, 20);
});
}));
}
await Promise.all(limiterTasks);
assert(maxRunning <= 3, 'max concurrent tasks <= 3');
assert(maxRunning === 3, 'max concurrent tasks reached 3 with 5 tasks');
// --- F003: provider-level request budgets ---
suite('F003 provider request budgets');
assert(typeof app.ProviderRequestBudget === 'object' && app.ProviderRequestBudget !== null, 'ProviderRequestBudget is exposed');
var originalWindowFetch = app.fetch;
var activeRequests = { github: 0, gitcode: 0 };
var maxActiveRequests = { github: 0, gitcode: 0 };
app.fetch = function(url) {
var platform = String(url).indexOf('api.github.com') >= 0 ? 'github' : 'gitcode';
activeRequests[platform]++;
maxActiveRequests[platform] = Math.max(maxActiveRequests[platform], activeRequests[platform]);
return new Promise(function(resolve) {
setTimeout(function() {
activeRequests[platform]--;
resolve({
ok: true,
status: 200,
headers: { get: function() { return null; } },
json: function() { return Promise.resolve({}); }
});
}, 15);
});
};
var budgetCalls = [];
for (var ghBudgetIndex = 0; ghBudgetIndex < 24; ghBudgetIndex++) {
budgetCalls.push(app.GitHubProvider._fetch('https://api.github.com/test/' + ghBudgetIndex, 'tok'));
}
for (var gcBudgetIndex = 0; gcBudgetIndex < 32; gcBudgetIndex++) {
budgetCalls.push(app.GitCodeProvider._fetch('https://api.gitcode.com/test/' + gcBudgetIndex, 'tok'));
}
await Promise.all(budgetCalls);
app.fetch = originalWindowFetch;
assert(maxActiveRequests.github <= 8, 'GitHub request concurrency never exceeds 8 (got ' + maxActiveRequests.github + ')');
assert(maxActiveRequests.github > 3, 'GitHub request concurrency can exceed old PR-task limit 3');
assert(maxActiveRequests.gitcode <= 16, 'GitCode request concurrency never exceeds 16 (got ' + maxActiveRequests.gitcode + ')');
assert(maxActiveRequests.gitcode > 3, 'GitCode request concurrency can exceed old PR-task limit 3');
suite('F003 nested collaboration fan-out request budget');
var fanoutActive = 0;
var fanoutPeak = 0;
app.fetch = function() {
fanoutActive++;
fanoutPeak = Math.max(fanoutPeak, fanoutActive);
return new Promise(function(resolve) {
setTimeout(function() {
fanoutActive--;
resolve({
ok: true,
status: 200,
headers: { get: function() { return null; } },
json: function() { return Promise.resolve([]); }
});
}, 15);
});
};
var fanoutTasks = [];
for (var fanoutIndex = 0; fanoutIndex < 12; fanoutIndex++) {
fanoutTasks.push(app.GitHubProvider.fetchCollaboration(
'tok', 'org', 'repo',
{
number: fanoutIndex + 1,
title: 'Fan-out PR ' + fanoutIndex,
mergedAt: '2026-07-20T00:00:00Z',
url: 'https://github.com/org/repo/pull/' + (fanoutIndex + 1)
},
new AbortController().signal,
function(){}
));
}
await Promise.all(fanoutTasks);
app.fetch = originalWindowFetch;
assert(fanoutPeak <= 8, 'nested GitHub collaboration fan-out never exceeds request budget 8 (got ' + fanoutPeak + ')');
assert(fanoutPeak > 3, 'nested GitHub collaboration fan-out can use more than 3 requests');
// --- F003: merged PR cache contract ---
suite('F003 PR cache key and lifecycle');
assert(typeof app.prCacheKey === 'function', 'prCacheKey is exposed');
assert(typeof app.CacheStore === 'object' && app.CacheStore !== null, 'CacheStore is exposed');
if (typeof app.prCacheKey === 'function' && app.CacheStore) {
assertEqual(
app.prCacheKey('github', 'Org/Repo', 42),
'github:org/repo#42',
'cache key normalizes repository case'
);
var memoryBackend = app.CacheStore.createMemoryBackend();
var memoryCache = app.CacheStore.create(memoryBackend);
var fullEntry = {
schemaVersion: app.CACHE_SCHEMA_VERSION,
cachedAt: '2026-07-26T00:00:00.000Z',
platform: 'github',
repository: 'Org/Repo',
prNumber: 42,
core: {
platform: 'github', repo: 'Org/Repo', number: 42, author: 'alice',
mergedAt: '2026-07-25T00:00:00Z', baseBranch: 'main', additions: 10, deletions: 2,
changedFiles: 1, completeness: 'full', url: 'https://example.test/42'
},
activities: [{
activity_type: 'comment', platform: 'github', repository: 'Org/Repo',
pr_number: 42, actor_login: 'bob', user_key: 'local-bob',
display_name: 'Local Bob', matched: true, completeness: 'full'
}],
completeness: 'full',
partialReason: ''
};
assert(await memoryCache.put(fullEntry) === true, 'full entry is accepted');
var firstHit = await memoryCache.get('github', 'Org/Repo', 42);
assert(firstHit && firstHit.core.additions === 10, 'full current-schema entry hits');
assert(!('user_key' in firstHit.activities[0]), 'user_key projection is stripped before caching');
assert(!('display_name' in firstHit.activities[0]), 'display_name projection is stripped before caching');
assert(!('matched' in firstHit.activities[0]), 'matched projection is stripped before caching');
firstHit.core.additions = 999;
var secondHit = await memoryCache.get('github', 'Org/Repo', 42);
assert(secondHit.core.additions === 10, 'cache reads return a defensive clone');
var partialEntry = Object.assign({}, fullEntry, {
prNumber: 43,
core: Object.assign({}, fullEntry.core, { number: 43 }),
completeness: 'partial',
partialReason: 'Comments 获取失败'
});
assert(await memoryCache.put(partialEntry) === false, 'partial entry is rejected');
assert((await memoryCache.get('github', 'Org/Repo', 43)) === null, 'partial entry never hits');
var staleEntry = Object.assign({}, fullEntry, {
prNumber: 44,
core: Object.assign({}, fullEntry.core, { number: 44 }),
schemaVersion: app.CACHE_SCHEMA_VERSION - 1
});
await memoryBackend.put(app.prCacheKey('github', 'Org/Repo', 44), staleEntry);
assert((await memoryCache.get('github', 'Org/Repo', 44)) === null, 'stale schema is a miss');
assert((await memoryBackend.get(app.prCacheKey('github', 'Org/Repo', 44))) === null, 'stale schema is removed');
await memoryBackend.put(app.prCacheKey('github', 'Org/Repo', 45), { broken: true });
assert((await memoryCache.get('github', 'Org/Repo', 45)) === null, 'corrupt entry is a miss');
var mismatchedEntry = Object.assign({}, fullEntry, {
prNumber: 46,
core: Object.assign({}, fullEntry.core, { number: 999 })
});
await memoryBackend.put(app.prCacheKey('github', 'Org/Repo', 46), mismatchedEntry);
assert((await memoryCache.get('github', 'Org/Repo', 46)) === null, 'key/core identity mismatch is a miss');
var missingBranchEntry = Object.assign({}, fullEntry, {
prNumber: 47,
core: Object.assign({}, fullEntry.core, { number: 47, baseBranch: '' }),
activities: []
});
await memoryBackend.put(app.prCacheKey('github', 'Org/Repo', 47), missingBranchEntry);
assert((await memoryCache.get('github', 'Org/Repo', 47)) === null, 'full cache entry without base branch is a miss');
}
suite('F003 IndexedDB persistence');
if (app.CacheStore && typeof app.CacheStore.openIndexedDbBackend === 'function' && app.indexedDB) {
var cacheDbName = 'code-statistics-test-' + Date.now();
var idbBackendOne = await app.CacheStore.openIndexedDbBackend(cacheDbName);
var idbCacheOne = app.CacheStore.create(idbBackendOne);
var idbEntry = {
schemaVersion: app.CACHE_SCHEMA_VERSION,
cachedAt: '2026-07-26T00:00:00.000Z',
platform: 'gitcode',
repository: 'org/repo',
prNumber: 7,
core: {
platform: 'gitcode', repo: 'org/repo', number: 7, author: 'alice',
mergedAt: '2026-07-25T00:00:00Z', baseBranch: 'main', additions: 1, deletions: 0,
changedFiles: 1, completeness: 'full', url: 'https://example.test/7'
},
activities: [],
completeness: 'full',
partialReason: ''
};
await idbCacheOne.put(idbEntry);
idbBackendOne.close();
var idbBackendTwo = await app.CacheStore.openIndexedDbBackend(cacheDbName);
var idbCacheTwo = app.CacheStore.create(idbBackendTwo);
var reopenedHit = await idbCacheTwo.get('gitcode', 'org/repo', 7);
assert(reopenedHit && reopenedHit.core.number === 7, 'IndexedDB entry survives close and reopen');
idbBackendTwo.close();
await app.CacheStore.deleteIndexedDb(cacheDbName);
} else {
assert(false, 'IndexedDB cache API is available on HTTP');
}
suite('F003 GitHub PR core cache integration');
var ghCacheOriginalFetch = app.GitHubProvider._fetch;
var ghDetailCalls = 0;
app.GitHubProvider._fetch = function(url) {
if (url.indexOf('/search/issues') >= 0) {
return Promise.resolve({ total_count: 1, incomplete_results: false, items: [{ number: 42 }] });
}
if (url.indexOf('/pulls/42') >= 0) {
ghDetailCalls++;
return Promise.resolve({
number: 42, title: 'Cached PR', user: { login: 'alice' },
merged_at: '2026-07-20T00:00:00Z', base: { ref: 'main' },
additions: 10, deletions: 2, changed_files: 1
});
}
return Promise.resolve({});
};
var ghCoreCache = {
get: function() {
return Promise.resolve({
core: {
platform: 'github', repo: 'org/repo', number: 42, title: 'Cached PR',
author: 'alice', mergedAt: '2026-07-20T00:00:00Z', baseBranch: 'main',
additions: 10, deletions: 2, changedFiles: 1, completeness: 'full',
url: 'https://github.com/org/repo/pull/42'
},
activities: [{ activity_type: 'comment', completeness: 'full', actor_login: 'bob' }]
});
}
};
var ghCachedResult = await app.GitHubProvider.fetchMergedPRs(
'tok', 'org', 'repo', 'main', '2026-07-01', '2026-07-31',
new AbortController().signal, function(){}, ghCoreCache
);
assertEqual(ghDetailCalls, 0, 'GitHub cache hit skips PR detail request');
assertEqual(ghCachedResult.cacheHits, 1, 'GitHub result reports one cache hit');
assertEqual(ghCachedResult.networkPRs, 0, 'GitHub result reports zero network PR hydrations');
assert(ghCachedResult.prs[0] && ghCachedResult.prs[0]._cacheHit === true, 'GitHub cached core is marked as hit');
assert(
ghCachedResult.prs[0] && Array.isArray(ghCachedResult.prs[0]._cachedActivities) &&
ghCachedResult.prs[0]._cachedActivities.length === 1,
'GitHub cached activities travel with the core'
);
app.GitHubProvider._fetch = ghCacheOriginalFetch;
suite('F003 GitHub network PR count precision');
app.GitHubProvider._fetch = function(url) {
if (url.indexOf('/search/issues') >= 0) {
return Promise.resolve({
total_count: 2,
incomplete_results: false,
items: [{ number: 50 }, { number: 51 }]
});
}
var number = url.indexOf('/pulls/50') >= 0 ? 50 : 51;
return Promise.resolve({
number: number,
title: 'Network PR ' + number,
user: { login: 'alice' },
merged_at: '2026-07-20T00:00:00Z',
base: { ref: number === 50 ? 'main' : 'release' },
additions: 10,
deletions: 2,
changed_files: 1
});
};
var ghFilteredResult = await app.GitHubProvider.fetchMergedPRs(
'tok', 'org', 'repo', 'main', '2026-07-01', '2026-07-31',
new AbortController().signal, function(){}, { get: function() { return Promise.resolve(null); } }
);
assertEqual(ghFilteredResult.prs.length, 1, 'GitHub branch filtering keeps one selected PR');
assertEqual(ghFilteredResult.networkPRs, 1, 'GitHub network count includes only selected PRs');
assertEqual(
ghFilteredResult.cacheHits + ghFilteredResult.networkPRs,
ghFilteredResult.prs.length,
'GitHub cache/network counts add up to selected PR total'
);
app.GitHubProvider._fetch = ghCacheOriginalFetch;
suite('F003 GitCode PR core cache integration');
var gcCacheOriginalFetch = app.GitCodeProvider._fetch;
var gcStatsCalls = 0;
app.GitCodeProvider._fetch = function(url) {
if (url.indexOf('/pulls?') >= 0) {
return Promise.resolve([{
number: 7, title: 'Cached GC PR', user: { login: 'alice' },
merged_at: '2026-07-20T00:00:00Z', base: { ref: 'main' },
html_url: 'https://gitcode.com/org/repo/pulls/7'
}]);
}
gcStatsCalls++;
return Promise.resolve({ additions: 1, deletions: 0, changed_files: 1 });
};
var gcCoreCache = {
get: function() {
return Promise.resolve({
core: {
platform: 'gitcode', repo: 'org/repo', number: 7, title: 'Cached GC PR',
author: 'alice', mergedAt: '2026-07-20T00:00:00Z', baseBranch: 'main',
additions: 1, deletions: 0, changedFiles: 1, completeness: 'full',
url: 'https://gitcode.com/org/repo/pulls/7'
},
activities: []
});
}
};
var gcCachedResult = await app.GitCodeProvider.fetchMergedPRs(
'tok', 'org', 'repo', 'main', '2026-07-01', '2026-07-31',
new AbortController().signal, function(){}, gcCoreCache
);
assertEqual(gcStatsCalls, 0, 'GitCode cache hit skips code-stat request');
assertEqual(gcCachedResult.cacheHits, 1, 'GitCode result reports one cache hit');
assertEqual(gcCachedResult.networkPRs, 0, 'GitCode result reports zero network PR hydrations');
assert(gcCachedResult.prs[0] && gcCachedResult.prs[0]._cacheHit === true, 'GitCode cached core is marked as hit');
app.GitCodeProvider._fetch = gcCacheOriginalFetch;
suite('F003 collaboration cache integration');
assert(typeof app.fetchCollaborationForPR === 'function', 'fetchCollaborationForPR is exposed');
if (typeof app.fetchCollaborationForPR === 'function') {
var collabProviderCalls = 0;
var collabCacheWrites = 0;
var collabProvider = {
fetchCollaboration: function() {
collabProviderCalls++;
return Promise.resolve({
activities: [{ activity_type: 'comment', completeness: 'full', actor_login: 'bob' }],
partial: false,
partialReason: ''
});
}
};
var collabCache = {
put: function() {
collabCacheWrites++;
return Promise.resolve(true);
}
};
var cachedCollabResult = await app.fetchCollaborationForPR({
provider: collabProvider,
token: 'tok',
r: { platform: 'github', owner: 'org', repo: 'repo' },
pr: {
_cacheHit: true,
_cachedActivities: [{ activity_type: 'approval', completeness: 'full', actor_login: 'carol' }]
}
}, new AbortController().signal, collabCache, function(){});
assertEqual(collabProviderCalls, 0, 'cached collaboration skips Provider');
assertEqual(cachedCollabResult.activities.length, 1, 'cached collaboration returns raw activities');
assert(cachedCollabResult.cacheHit === true, 'cached collaboration reports hit');
var networkPr = {
platform: 'github', repo: 'org/repo', number: 8, title: 'Network PR',
author: 'alice', mergedAt: '2026-07-20T00:00:00Z', baseBranch: 'main',
additions: 2, deletions: 1, changedFiles: 1, completeness: 'full',
url: 'https://github.com/org/repo/pull/8'
};
var partialCacheEntry = app.createPRCacheEntry(
Object.assign({}, networkPr, { completeness: 'partial' }),
[]
);
assertEqual(partialCacheEntry.completeness, 'partial', 'cache entry preserves PR completeness');
var networkCollabResult = await app.fetchCollaborationForPR({
provider: collabProvider, token: 'tok',
r: { platform: 'github', owner: 'org', repo: 'repo' },
pr: networkPr
}, new AbortController().signal, collabCache, function(){});
assertEqual(collabProviderCalls, 1, 'cache miss fetches collaboration once');
assertEqual(collabCacheWrites, 1, 'full collaboration writes one cache entry');
assert(networkCollabResult.cacheHit === false, 'network collaboration reports miss');
var abortedAfterFetch = new AbortController();
abortedAfterFetch.abort();
await app.fetchCollaborationForPR({
provider: collabProvider, token: 'tok',
r: { platform: 'github', owner: 'org', repo: 'repo' },
pr: Object.assign({}, networkPr, { number: 10 })
}, abortedAfterFetch.signal, collabCache, function(){});
assertEqual(
collabCacheWrites,
2,
'completed full PR remains cacheable when query UI is cancelled'
);
collabProvider.fetchCollaboration = function() {
collabProviderCalls++;
return Promise.resolve({ activities: [], partial: true, partialReason: 'Comments 获取失败' });
};
var partialCollabResult = await app.fetchCollaborationForPR({
provider: collabProvider, token: 'tok',
r: { platform: 'github', owner: 'org', repo: 'repo' },
pr: Object.assign({}, networkPr, { number: 9 })
}, new AbortController().signal, collabCache, function(){});
assert(partialCollabResult.partial === true, 'partial collaboration remains partial');
assertEqual(collabCacheWrites, 2, 'partial collaboration is not cached');
}
suite('F003 PR core partial reason propagation');
var corePartialGhOriginalFetch = app.GitHubProvider._fetch;
app.GitHubProvider._fetch = function(url) {
if (url.indexOf('/search/issues') >= 0) {
return Promise.resolve({ total_count: 1, incomplete_results: false, items: [{ number: 99 }] });
}
return Promise.resolve({
number: 99, title: 'Bad metrics', user: { login: 'alice' },
merged_at: '2026-07-20T00:00:00Z', base: { ref: 'main' },
additions: 'bad', deletions: 1, changed_files: 1
});
};
var ghCorePartialResult = await app.GitHubProvider.fetchMergedPRs(
'tok', 'org', 'repo', 'main', '2026-07-01', '2026-07-31',
new AbortController().signal, function(){}, { get: function(){ return Promise.resolve(null); } }
);
app.GitHubProvider._fetch = corePartialGhOriginalFetch;
assert(ghCorePartialResult.partial === true, 'GitHub invalid PR metrics mark repository partial');
assert(
ghCorePartialResult.partialReason.indexOf('1 个 PR 代码量不完整') >= 0,
'GitHub partial reason reports incomplete PR count'
);
var corePartialGcOriginalFetch = app.GitCodeProvider._fetch;
app.GitCodeProvider._fetch = function(url) {
if (url.indexOf('/pulls?') >= 0) {
return Promise.resolve([{
number: 77, title: 'Too large', user: { login: 'alice' },
merged_at: '2026-07-20T00:00:00Z', base: { ref: 'main' }
}]);
}
if (url.indexOf('/files') >= 0) {
// too_large means diff text truncated, but counts are valid → full
return Promise.resolve([{ additions: 1, deletions: 1, too_large: true }]);
}
return Promise.resolve({ additions: null, deletions: null, changed_files: null });
};
var gcCorePartialResult = await app.GitCodeProvider.fetchMergedPRs(
'tok', 'org', 'repo', 'main', '2026-07-01', '2026-07-31',
new AbortController().signal, function(){}, { get: function(){ return Promise.resolve(null); } }
);
app.GitCodeProvider._fetch = corePartialGcOriginalFetch;
// too_large with valid counts is now full (diff text truncated ≠ counts missing)
assert(gcCorePartialResult.partial === false, 'GitCode too_large with valid counts is full');
assertEqual(gcCorePartialResult.prs[0].completeness, 'full', 'too_large PR with valid counts = full');
// GitCode truly unparsable counts → partial
suite('GitCode unparsable file counts');
var gcUnparsableFetch = app.GitCodeProvider._fetch;
app.GitCodeProvider._fetch = function(url) {
if (url.indexOf('/pulls?') >= 0) {
return Promise.resolve([{
number: 88, title: 'Unparsable', user: { login: 'alice' },
merged_at: '2026-07-20T00:00:00Z', base: { ref: 'main' }
}]);
}
if (url.indexOf('/files') >= 0) {
return Promise.resolve([{ additions: null, deletions: null }]);
}
return Promise.resolve({ additions: null, deletions: null, changed_files: null });
};
var gcUnparsableResult = await app.GitCodeProvider.fetchMergedPRs(
'tok', 'org', 'repo', 'main', '2026-07-01', '2026-07-31',
new AbortController().signal, function(){}, { get: function(){ return Promise.resolve(null); } }
);
app.GitCodeProvider._fetch = gcUnparsableFetch;
assert(gcUnparsableResult.partial === true, 'GitCode unparsable counts marks partial');
assert(
gcUnparsableResult.partialReason.indexOf('1 个 PR 代码量不完整') >= 0,
'GitCode partial reason reports incomplete PR count'
);
suite('F003 query progress state machine');
assert(typeof app.createQueryProgress === 'function', 'createQueryProgress is exposed');
assert(typeof app.formatQueryTerminal === 'function', 'formatQueryTerminal is exposed');
assert(typeof app.formatRepoTerminal === 'function', 'formatRepoTerminal is exposed');
if (typeof app.createQueryProgress === 'function' &&
typeof app.formatQueryTerminal === 'function' &&
typeof app.formatRepoTerminal === 'function') {
var queryProgress = app.createQueryProgress(2);
assertEqual(queryProgress.snapshot(), {
total: 2, completed: 0, cacheHits: 0, networkPRs: 0
}, 'new progress starts at zero completed');
assert(queryProgress.settle('github:org/repo#1', 'cache') === true, 'first cache hit settles');
assertEqual(queryProgress.snapshot(), {
total: 2, completed: 1, cacheHits: 1, networkPRs: 0
}, 'cache hit increments completed and cache count');
assert(queryProgress.settle('github:org/repo#1', 'network') === false, 'duplicate settle is ignored');
assertEqual(queryProgress.snapshot().completed, 1, 'duplicate settle does not overcount');
queryProgress.settle('github:org/repo#2', 'network');
assertEqual(queryProgress.snapshot(), {
total: 2, completed: 2, cacheHits: 1, networkPRs: 1
}, 'network settle reaches exact total');
var fullStatuses = [{
repo: { platform: 'github', owner: 'org', repo: 'repo' },
status: 'ok', totalPRs: 2, completedPRs: 2, cacheHits: 1, networkPRs: 1
}];
var fullTitle = app.formatQueryTerminal(queryProgress.snapshot(), fullStatuses, false);
assert(fullTitle.indexOf('查询完成') === 0, 'full query has completed terminal');
assert(fullTitle.indexOf('缓存 1') >= 0 && fullTitle.indexOf('网络 1') >= 0, 'full terminal shows cache/network counts');
assert(fullTitle.indexOf('正在') < 0, 'full terminal is not still running');
var partialStatuses = [{
repo: { platform: 'gitcode', owner: 'org', repo: 'repo' },
status: 'partial', partialReason: 'Comments 获取失败',
totalPRs: 2, completedPRs: 2, cacheHits: 0, networkPRs: 2
}];
var partialTitle = app.formatQueryTerminal(queryProgress.snapshot(), partialStatuses, false);
assert(partialTitle.indexOf('查询完成(部分)') === 0, 'partial query has partial terminal');
var partialRepo = app.formatRepoTerminal(partialStatuses[0]);
assert(partialRepo.icon === '⚠️', 'partial repo uses warning icon');
assert(partialRepo.text.indexOf('Comments 获取失败') >= 0, 'partial repo exposes reason');
assert(partialRepo.text.indexOf('2/2 PR') >= 0, 'partial repo exposes settled PR count');
var failedStatuses = [{
repo: { platform: 'github', owner: 'org', repo: 'broken' },
status: 'failed', error: 'GitHub API 500'
}];
assert(
app.formatQueryTerminal(queryProgress.snapshot(), failedStatuses, false).indexOf('查询完成(有失败)') === 0,
'failed query has failed terminal'
);
assert(app.formatRepoTerminal(failedStatuses[0]).text.indexOf('GitHub API 500') >= 0, 'failed repo exposes reason');
assertEqual(
app.formatQueryTerminal(queryProgress.snapshot(), fullStatuses, true),
'查询已取消',
'cancelled query has unique terminal'
);
}
suite('F003 local user remapping');
assert(
typeof app.remapCurrentResultsAfterUsersChanged === 'function',
'remapCurrentResultsAfterUsersChanged is exposed'
);
if (typeof app.remapCurrentResultsAfterUsersChanged === 'function') {
var remapOriginalFetch = app.fetch;
var remapOriginalLoadUsers = app.Storage.loadUsers;
var remapFetchCalls = 0;
app.fetch = function() {
remapFetchCalls++;
return Promise.reject(new Error('network must not be used'));
};
var remapUsers = [{
user_key: 'mapped-bob', display_name: 'Mapped Bob',
github_login: 'bob-gh', gitcode_login: '', enabled: true
}];
app.Storage.loadUsers = function() { return remapUsers; };
app.StatsEngine.currentActivities = [{
platform: 'github', repository: 'org/repo', actor_login: 'bob-gh',
user_key: '', display_name: 'bob-gh', matched: false,
activity_type: 'comment', completeness: 'full', pr_number: 1,
pr_title: 'PR', merged_at: '2026-07-20T00:00:00Z',
source_type: 'issue_comment', source_id: '1',
event_at: '2026-07-20T00:00:00Z', body_summary: 'hello', activity_url: ''
}];
app.document.getElementById('stat-user-type').value = 'all';
var remapped = app.remapCurrentResultsAfterUsersChanged(remapUsers);
assert(remapped === true, 'current results report local remap');
assert(app.StatsEngine.currentActivities[0].matched === true, 'existing activity becomes matched');
assertEqual(app.StatsEngine.currentActivities[0].user_key, 'mapped-bob', 'existing activity gets current user key');
assert(
app.document.getElementById('summary-tbody').textContent.indexOf('Mapped Bob') >= 0,
'summary DOM rerenders with current display name'
);
assertEqual(remapFetchCalls, 0, 'local remap performs zero network requests');
app.StatsEngine.currentActivities = [];
assert(app.remapCurrentResultsAfterUsersChanged(remapUsers) === false, 'no current activities is a safe no-op');
app.fetch = remapOriginalFetch;
app.Storage.loadUsers = remapOriginalLoadUsers;
}
suite('F003 repository discovery runs in parallel');
var parallelOriginalLoadConfig = app.Storage.loadConfig;
var parallelOriginalLoadUsers = app.Storage.loadUsers;
var parallelOriginalGetDefaultBranch = app.GitHubProvider.getDefaultBranch;
var parallelOriginalFetchMergedPRs = app.GitHubProvider.fetchMergedPRs;
var parallelResolvers = [];
var parallelStarts = 0;
app.Storage.loadConfig = function() {
return {
githubToken: 'tok',
gitcodeToken: '',
repositories: [
'https://github.com/org/repo-a',
'https://github.com/org/repo-b'
]
};
};
app.Storage.loadUsers = function() { return []; };
app.GitHubProvider.getDefaultBranch = function() {
parallelStarts++;
return new Promise(function(resolve) { parallelResolvers.push(resolve); });
};
app.GitHubProvider.fetchMergedPRs = function() {
return Promise.resolve({ prs: [], partial: false, partialReason: '', cacheHits: 0, networkPRs: 0 });
};
app.document.getElementById('stat-start').value = '2026-07-01';
app.document.getElementById('stat-end').value = '2026-07-31';
app.document.getElementById('stat-platform').value = '';
app.document.getElementById('stat-user').value = '';
app.document.getElementById('stat-repo').value = '';
var parallelQuery = app.runQuery();
await new Promise(function(resolve) { setTimeout(resolve, 0); });
assertEqual(parallelStarts, 2, 'both repository discovery tasks start before either resolves');
parallelResolvers.forEach(function(resolve) { resolve('main'); });
await parallelQuery;
app.Storage.loadConfig = parallelOriginalLoadConfig;
app.Storage.loadUsers = parallelOriginalLoadUsers;
app.GitHubProvider.getDefaultBranch = parallelOriginalGetDefaultBranch;
app.GitHubProvider.fetchMergedPRs = parallelOriginalFetchMergedPRs;
suite('F003 user mutations trigger one remap path');
if (typeof app.remapCurrentResultsAfterUsersChanged === 'function') {
var wiringOriginalLoadUsers = app.Storage.loadUsers;
var wiringOriginalSaveUsers = app.Storage.saveUsers;
var wiringOriginalRenderUsers = app.renderUsers;
var wiringOriginalRemap = app.remapCurrentResultsAfterUsersChanged;
var wiringOriginalCloseUser = app.closeUserDialog;
var wiringOriginalCloseImport = app.closeImportDialog;
var wiringOriginalConfirm = app.confirm;
var wiringUsers = [{
user_key: 'alice', display_name: 'Alice', email: '',
github_login: 'alice-gh', gitcode_login: '', enabled: true
}];
var mutationRemaps = 0;
app.Storage.loadUsers = function() { return wiringUsers; };
app.Storage.saveUsers = function(users) { wiringUsers = users; };
app.renderUsers = function() {};
app.remapCurrentResultsAfterUsersChanged = function() { mutationRemaps++; return true; };
app.closeUserDialog = function() {};
app.closeImportDialog = function() {};
app.confirm = function() { return true; };
app.document.getElementById('edit-index').value = '0';
app.document.getElementById('edit-user-key').value = 'alice';
app.document.getElementById('edit-display-name').value = 'Alice Updated';
app.document.getElementById('edit-email').value = '';
app.document.getElementById('edit-github-login').value = 'alice-gh';
app.document.getElementById('edit-gitcode-login').value = '';
app.saveUser({ preventDefault: function() {} });
assertEqual(mutationRemaps, 1, 'save/edit triggers remap helper once');
app.toggleUserEnabled(0, false);
assertEqual(mutationRemaps, 2, 'toggle triggers remap helper once');
app.deleteUser(0);
assertEqual(mutationRemaps, 3, 'delete triggers remap helper once');
app.pendingImportRows = [{
record: {
user_key: 'bob', display_name: 'Bob', email: '',
github_login: 'bob-gh', gitcode_login: '', enabled: true
}
}];
app.confirmImport();
assertEqual(mutationRemaps, 4, 'CSV confirm import triggers remap helper once');