-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathissues.test.ts
More file actions
637 lines (573 loc) · 16.5 KB
/
issues.test.ts
File metadata and controls
637 lines (573 loc) · 16.5 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
import { describe, it, expect, vi, beforeEach } from "vitest";
import { Command } from "commander";
import { registerIssuesCommand } from "./issues";
import { AnalysisService } from "../api/client/services/AnalysisService";
vi.mock("../api/client/services/AnalysisService");
vi.mock("../utils/credentials", () => ({ loadCredentials: vi.fn(() => null) }));
vi.spyOn(console, "log").mockImplementation(() => {});
function createProgram(): Command {
const program = new Command();
program.option("-o, --output <format>", "output format", "table");
registerIssuesCommand(program);
return program;
}
const mockIssues = [
{
issueId: "issue-1",
resultDataId: 9901,
filePath: "src/auth.ts",
fileId: 1,
patternInfo: {
id: "sql-injection",
title: "SQL Injection",
category: "Security",
subCategory: "Injection",
severityLevel: "Error",
level: "Error",
},
toolInfo: { uuid: "tool-1", name: "Semgrep" },
lineNumber: 20,
message: "Potential SQL injection vulnerability",
language: "TypeScript",
lineText: ' db.query(`SELECT * FROM users WHERE id = ${id}`);',
falsePositiveThreshold: 0.3,
},
{
issueId: "issue-2",
resultDataId: 9902,
filePath: "src/utils.ts",
fileId: 2,
patternInfo: {
id: "no-unused",
title: "no unused variables",
category: "Code Style",
severityLevel: "Warning",
level: "Warning",
},
toolInfo: { uuid: "tool-1", name: "ESLint" },
lineNumber: 5,
message: "Unused variable 'helper'",
language: "TypeScript",
lineText: " const helper = 42;",
falsePositiveThreshold: 0.5,
},
];
const mockOverview = {
data: {
counts: {
categories: [
{ name: "Security", total: 5 },
{ name: "Code Style", total: 3 },
],
levels: [
{ name: "Error", total: 5 },
{ name: "Warning", total: 3 },
],
languages: [{ name: "TypeScript", total: 8 }],
tags: [{ name: "owasp", total: 5 }],
patterns: [
{ id: "sql-injection", title: "SQL Injection", total: 5 },
{ id: "no-undef", title: "No Undefined Variables", total: 3 },
],
authors: [{ name: "dev@example.com", total: 4 }],
},
},
};
function getAllOutput(): string {
return (console.log as ReturnType<typeof vi.fn>).mock.calls
.map((c) => c[0])
.join("\n");
}
describe("issues command", () => {
beforeEach(() => {
vi.clearAllMocks();
process.env.CODACY_API_TOKEN = "test-token";
});
it("should fetch and display issues in card format", async () => {
vi.mocked(AnalysisService.searchRepositoryIssues).mockResolvedValue({
data: mockIssues,
} as any);
const program = createProgram();
await program.parseAsync([
"node",
"test",
"issues",
"gh",
"test-org",
"test-repo",
]);
expect(AnalysisService.searchRepositoryIssues).toHaveBeenCalledWith(
"gh",
"test-org",
"test-repo",
undefined,
100,
{},
);
const output = getAllOutput();
// Section title includes count
expect(output).toContain("Issues — Found 2 issues");
expect(output).toContain("Potential SQL injection vulnerability");
expect(output).toContain("src/auth.ts:20");
expect(output).toContain("Unused variable 'helper'");
expect(output).toContain("src/utils.ts:5");
// Each card shows the stable issue ID on the first line
expect(output).toContain("#9901");
expect(output).toContain("#9902");
});
it("should show 'No issues found' when there are no issues", async () => {
vi.mocked(AnalysisService.searchRepositoryIssues).mockResolvedValue({
data: [],
} as any);
const program = createProgram();
await program.parseAsync([
"node",
"test",
"issues",
"gh",
"test-org",
"test-repo",
]);
const output = getAllOutput();
expect(output).toContain("No issues found");
});
it("should show overview when --overview flag is set", async () => {
vi.mocked(AnalysisService.issuesOverview).mockResolvedValue(
mockOverview as any,
);
const program = createProgram();
await program.parseAsync([
"node",
"test",
"issues",
"gh",
"test-org",
"test-repo",
"--overview",
]);
expect(AnalysisService.issuesOverview).toHaveBeenCalledWith(
"gh",
"test-org",
"test-repo",
{},
);
const output = getAllOutput();
expect(output).toContain("Issues Overview");
expect(output).toContain("Security");
expect(output).toContain("Category");
expect(output).toContain("Severity");
expect(output).toContain("Language");
expect(output).toContain("Tag");
expect(output).toContain("Pattern");
expect(output).toContain("SQL Injection");
expect(output).toContain("sql-injection");
expect(output).toContain("Author");
expect(output).toContain("dev@example.com");
});
it("should pass filter options to the API body", async () => {
vi.mocked(AnalysisService.searchRepositoryIssues).mockResolvedValue({
data: [],
} as any);
const program = createProgram();
await program.parseAsync([
"node",
"test",
"issues",
"gh",
"test-org",
"test-repo",
"--branch",
"main",
"--severities",
"Error,Warning",
"--categories",
"Security",
"--languages",
"TypeScript",
"--tags",
"owasp",
"--authors",
"dev@example.com",
]);
expect(AnalysisService.searchRepositoryIssues).toHaveBeenCalledWith(
"gh",
"test-org",
"test-repo",
undefined,
100,
{
branchName: "main",
levels: ["Error", "Warning"],
categories: ["Security"],
languages: ["TypeScript"],
tags: ["owasp"],
authorEmails: ["dev@example.com"],
},
);
});
it("should normalize severity display labels to enum values (case-insensitive)", async () => {
vi.mocked(AnalysisService.searchRepositoryIssues).mockResolvedValue({
data: [],
} as any);
const program = createProgram();
// "critical" → Error, "medium" → Warning, "minor" → Info
await program.parseAsync([
"node",
"test",
"issues",
"gh",
"test-org",
"test-repo",
"--severities",
"Critical,medium,MINOR",
]);
expect(AnalysisService.searchRepositoryIssues).toHaveBeenCalledWith(
"gh",
"test-org",
"test-repo",
undefined,
100,
{ levels: ["Error", "Warning", "Info"] },
);
});
it("should normalize category names case-insensitively and accept spaces", async () => {
vi.mocked(AnalysisService.searchRepositoryIssues).mockResolvedValue({
data: [],
} as any);
const program = createProgram();
// "security" → "Security", "code style" isn't supported as multi-word via CLI
// but "codestyle" → "CodeStyle", "error prone" → but spaces stripped → "errorprone" → "ErrorProne"
await program.parseAsync([
"node",
"test",
"issues",
"gh",
"test-org",
"test-repo",
"--categories",
"security,ErrorProne,bestpractice",
]);
expect(AnalysisService.searchRepositoryIssues).toHaveBeenCalledWith(
"gh",
"test-org",
"test-repo",
undefined,
100,
{ categories: ["Security", "ErrorProne", "BestPractice"] },
);
});
it("should pass pattern filter to the API body", async () => {
vi.mocked(AnalysisService.searchRepositoryIssues).mockResolvedValue({
data: [],
} as any);
const program = createProgram();
await program.parseAsync([
"node",
"test",
"issues",
"gh",
"test-org",
"test-repo",
"--patterns",
"no-undef,no-unused",
]);
expect(AnalysisService.searchRepositoryIssues).toHaveBeenCalledWith(
"gh",
"test-org",
"test-repo",
undefined,
100,
{ patternIds: ["no-undef", "no-unused"] },
);
});
it("should sort issues by severity (Error before Warning)", async () => {
const unsortedIssues = [
{
issueId: "i1",
resultDataId: 1,
filePath: "a.ts",
fileId: 1,
patternInfo: {
id: "p1",
category: "Style",
severityLevel: "Warning",
level: "Warning",
},
toolInfo: { uuid: "t1", name: "Tool" },
lineNumber: 1,
message: "Warning issue",
language: "TypeScript",
lineText: "let x = 1;",
falsePositiveThreshold: 0.5,
},
{
issueId: "i2",
resultDataId: 2,
filePath: "b.ts",
fileId: 2,
patternInfo: {
id: "p2",
category: "Error Prone",
severityLevel: "Error",
level: "Error",
},
toolInfo: { uuid: "t1", name: "Tool" },
lineNumber: 2,
message: "Error issue",
language: "TypeScript",
lineText: "let y = 2;",
falsePositiveThreshold: 0.5,
},
];
vi.mocked(AnalysisService.searchRepositoryIssues).mockResolvedValue({
data: unsortedIssues,
} as any);
const program = createProgram();
await program.parseAsync([
"node",
"test",
"issues",
"gh",
"test-org",
"test-repo",
]);
const output = getAllOutput();
const errorIdx = output.indexOf("Error issue");
const warningIdx = output.indexOf("Warning issue");
expect(errorIdx).toBeLessThan(warningIdx);
});
it("should show subcategory for security issues", async () => {
vi.mocked(AnalysisService.searchRepositoryIssues).mockResolvedValue({
data: mockIssues,
} as any);
const program = createProgram();
await program.parseAsync([
"node",
"test",
"issues",
"gh",
"test-org",
"test-repo",
]);
const output = getAllOutput();
expect(output).toContain("Security");
expect(output).toContain("Injection");
});
it("should show false positive warning when probability exceeds threshold", async () => {
const issueWithFalsePositive = {
issueId: "fp1",
resultDataId: 100,
filePath: "src/fp.ts",
fileId: 100,
patternInfo: {
id: "rule1",
category: "Error Prone",
severityLevel: "Warning",
level: "Warning",
},
toolInfo: { uuid: "t1", name: "Tool" },
lineNumber: 5,
message: "Possible issue here",
language: "TypeScript",
lineText: " doSomething();",
falsePositiveProbability: 0.9,
falsePositiveThreshold: 0.5,
falsePositiveReason: "Common pattern that is usually intentional",
};
vi.mocked(AnalysisService.searchRepositoryIssues).mockResolvedValue({
data: [issueWithFalsePositive],
} as any);
const program = createProgram();
await program.parseAsync([
"node",
"test",
"issues",
"gh",
"test-org",
"test-repo",
]);
const output = getAllOutput();
expect(output).toContain("Potential false positive");
expect(output).toContain("Common pattern that is usually intentional");
});
it("should show pagination total in Issues section title", async () => {
vi.mocked(AnalysisService.searchRepositoryIssues).mockResolvedValue({
data: mockIssues,
pagination: { cursor: "next-cursor", limit: 100, total: 45000 },
} as any);
const program = createProgram();
await program.parseAsync([
"node",
"test",
"issues",
"gh",
"test-org",
"test-repo",
]);
const output = getAllOutput();
expect(output).toContain("Issues — Found 45k issues");
// Pagination warning should also appear
expect(output).toContain("Showing the first 100 results");
});
it("should output JSON for issues list when --output json is specified", async () => {
vi.mocked(AnalysisService.searchRepositoryIssues).mockResolvedValue({
data: mockIssues,
} as any);
const program = createProgram();
await program.parseAsync([
"node",
"test",
"--output",
"json",
"issues",
"gh",
"test-org",
"test-repo",
]);
const jsonOutput = (console.log as ReturnType<typeof vi.fn>).mock.calls[0][0];
expect(jsonOutput).toContain('"Potential SQL injection vulnerability"');
expect(jsonOutput).toContain('"sql-injection"');
});
it("should output JSON for overview when --overview --output json is specified", async () => {
vi.mocked(AnalysisService.issuesOverview).mockResolvedValue(
mockOverview as any,
);
const program = createProgram();
await program.parseAsync([
"node",
"test",
"--output",
"json",
"issues",
"gh",
"test-org",
"test-repo",
"--overview",
]);
expect(console.log).toHaveBeenCalledWith(
expect.stringContaining('"Security"'),
);
});
it("should pass a custom limit <= 100 directly to the API", async () => {
vi.mocked(AnalysisService.searchRepositoryIssues).mockResolvedValue({
data: [],
} as any);
const program = createProgram();
await program.parseAsync([
"node",
"test",
"issues",
"gh",
"test-org",
"test-repo",
"--limit",
"50",
]);
expect(AnalysisService.searchRepositoryIssues).toHaveBeenCalledWith(
"gh",
"test-org",
"test-repo",
undefined,
50,
{},
);
});
it("should paginate when limit > 100", async () => {
const page1Issues = Array.from({ length: 100 }, (_, i) => ({
issueId: `issue-${i}`,
resultDataId: i,
filePath: `file-${i}.ts`,
fileId: i,
patternInfo: { id: "p1", category: "Style", severityLevel: "Warning", level: "Warning" },
toolInfo: { uuid: "t1", name: "Tool" },
lineNumber: 1,
message: `Issue ${i}`,
language: "TypeScript",
lineText: "x",
falsePositiveThreshold: 0.5,
}));
const page2Issues = Array.from({ length: 50 }, (_, i) => ({
issueId: `issue-${100 + i}`,
resultDataId: 100 + i,
filePath: `file-${100 + i}.ts`,
fileId: 100 + i,
patternInfo: { id: "p1", category: "Style", severityLevel: "Warning", level: "Warning" },
toolInfo: { uuid: "t1", name: "Tool" },
lineNumber: 1,
message: `Issue ${100 + i}`,
language: "TypeScript",
lineText: "x",
falsePositiveThreshold: 0.5,
}));
vi.mocked(AnalysisService.searchRepositoryIssues)
.mockResolvedValueOnce({
data: page1Issues,
pagination: { cursor: "cursor-2", limit: 100, total: 250 },
} as any)
.mockResolvedValueOnce({
data: page2Issues,
pagination: { cursor: undefined, limit: 100, total: 250 },
} as any);
const program = createProgram();
await program.parseAsync([
"node",
"test",
"issues",
"gh",
"test-org",
"test-repo",
"--limit",
"150",
]);
expect(AnalysisService.searchRepositoryIssues).toHaveBeenCalledTimes(2);
// First call: no cursor
expect(AnalysisService.searchRepositoryIssues).toHaveBeenNthCalledWith(
1, "gh", "test-org", "test-repo", undefined, 100, {},
);
// Second call: with cursor from first response
expect(AnalysisService.searchRepositoryIssues).toHaveBeenNthCalledWith(
2, "gh", "test-org", "test-repo", "cursor-2", 100, {},
);
const output = getAllOutput();
expect(output).toContain("Issues — Found 250 issues");
});
it("should cap limit at 1000", async () => {
vi.mocked(AnalysisService.searchRepositoryIssues).mockResolvedValue({
data: [],
} as any);
const program = createProgram();
await program.parseAsync([
"node",
"test",
"issues",
"gh",
"test-org",
"test-repo",
"--limit",
"5000",
]);
// Should use pageSize 100 (min of 1000, 100)
expect(AnalysisService.searchRepositoryIssues).toHaveBeenCalledWith(
"gh", "test-org", "test-repo", undefined, 100, {},
);
});
it("should fail when CODACY_API_TOKEN is not set", async () => {
delete process.env.CODACY_API_TOKEN;
const mockExit = vi.spyOn(process, "exit").mockImplementation(() => {
throw new Error("process.exit called");
});
vi.spyOn(console, "error").mockImplementation(() => {});
const program = createProgram();
await expect(
program.parseAsync([
"node",
"test",
"issues",
"gh",
"test-org",
"test-repo",
]),
).rejects.toThrow("process.exit called");
mockExit.mockRestore();
});
});