-
Notifications
You must be signed in to change notification settings - Fork 260
Expand file tree
/
Copy pathlistCommitsApi.test.ts
More file actions
587 lines (497 loc) · 19.6 KB
/
listCommitsApi.test.ts
File metadata and controls
587 lines (497 loc) · 19.6 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
import { describe, it, expect, vi, beforeEach, type Mock } from 'vitest';
import { listCommits } from './listCommitsApi';
import * as dateUtils from './dateUtils';
// Mock dependencies
vi.mock('simple-git');
vi.mock('fs');
vi.mock('@sourcebot/shared', () => ({
REPOS_CACHE_DIR: '/mock/cache/dir',
getRepoPath: (repo: { id: number }) => ({
path: `/mock/cache/dir/${repo.id}`,
}),
createLogger: () => ({
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
}),
}));
vi.mock('@/lib/serviceError', () => ({
unexpectedError: (message: string) => ({
errorCode: 'UNEXPECTED_ERROR',
message,
}),
notFound: (message: string) => ({
errorCode: 'NOT_FOUND',
message,
}),
invalidGitRef: (ref: string) => ({
errorCode: 'INVALID_GIT_REF',
message: `Invalid git reference: "${ref}". Git refs cannot start with '-'.`,
}),
}));
vi.mock('@/actions', () => ({
sew: async <T>(fn: () => Promise<T> | T): Promise<T> => {
try {
return await fn();
} catch (error) {
// Mock sew to convert thrown errors to ServiceError
return {
errorCode: 'UNEXPECTED_ERROR',
message: error instanceof Error ? error.message : String(error),
} as T;
}
},
}));
// Create a mock findFirst function that we can configure per-test
const mockFindFirst = vi.fn();
vi.mock('@/withAuthV2', () => ({
withOptionalAuthV2: async <T>(fn: (args: { org: { id: number; name: string }; prisma: unknown }) => Promise<T>): Promise<T> => {
// Mock withOptionalAuthV2 to provide org and prisma context
const mockOrg = { id: 1, name: 'test-org' };
const mockPrisma = {
repo: {
findFirst: mockFindFirst,
},
};
return await fn({ org: mockOrg, prisma: mockPrisma });
},
}));
vi.mock('@/lib/utils', () => ({
isServiceError: (obj: unknown): obj is { errorCode: string } => {
return obj !== null && typeof obj === 'object' && 'errorCode' in obj;
},
}));
// Import mocked modules
import { simpleGit } from 'simple-git';
import { existsSync } from 'fs';
describe('searchCommits', () => {
const mockGitLog = vi.fn();
const mockGitRaw = vi.fn();
const mockCwd = vi.fn();
const mockSimpleGit = simpleGit as unknown as Mock;
const mockExistsSync = existsSync as unknown as Mock;
beforeEach(() => {
vi.clearAllMocks();
// Reset mockFindFirst before each test
mockFindFirst.mockReset();
// Setup default mocks
mockExistsSync.mockReturnValue(true);
mockCwd.mockReturnValue({
log: mockGitLog,
raw: mockGitRaw,
});
mockSimpleGit.mockReturnValue({
cwd: mockCwd,
});
// Setup default repo mock
mockFindFirst.mockResolvedValue({ id: 123, name: 'github.com/test/repo' });
// Setup default raw mock for rev-list count
mockGitRaw.mockResolvedValue('10');
});
describe('repository validation', () => {
it('should return error when repository is not found in database', async () => {
mockFindFirst.mockResolvedValue(null);
const result = await listCommits({
repo: 'github.com/nonexistent/repo',
});
expect(result).toMatchObject({
errorCode: 'NOT_FOUND',
message: expect.stringContaining('Repository "github.com/nonexistent/repo" not found'),
});
});
it('should query database with correct repository name', async () => {
mockFindFirst.mockResolvedValue({ id: 456, name: 'github.com/test/repo' });
mockGitLog.mockResolvedValue({ all: [] });
await listCommits({
repo: 'github.com/test/repo',
});
expect(mockFindFirst).toHaveBeenCalledWith({
where: {
name: 'github.com/test/repo',
orgId: 1,
},
});
});
});
describe('date range validation', () => {
it('should validate date range and return error for invalid range', async () => {
vi.spyOn(dateUtils, 'validateDateRange').mockReturnValue(
'Invalid date range: since must be before until'
);
const result = await listCommits({
repo: 'github.com/test/repo',
since: '2024-12-31',
until: '2024-01-01',
});
expect(result).toMatchObject({
errorCode: 'UNEXPECTED_ERROR',
message: 'Invalid date range: since must be before until',
});
});
it('should proceed when date range is valid', async () => {
vi.spyOn(dateUtils, 'validateDateRange').mockReturnValue(null);
vi.spyOn(dateUtils, 'toGitDate').mockImplementation((date) => date);
mockGitLog.mockResolvedValue({ all: [] });
const result = await listCommits({
repo: 'github.com/test/repo',
since: '2024-01-01',
until: '2024-12-31',
});
expect(result).toMatchObject({ commits: [], totalCount: expect.any(Number) });
});
});
describe('date parsing', () => {
it('should parse dates using toGitDate', async () => {
const toGitDateSpy = vi.spyOn(dateUtils, 'toGitDate');
toGitDateSpy.mockImplementation((date) => date);
mockGitLog.mockResolvedValue({ all: [] });
await listCommits({
repo: 'github.com/test/repo',
since: '30 days ago',
until: 'yesterday',
});
expect(toGitDateSpy).toHaveBeenCalledWith('30 days ago');
expect(toGitDateSpy).toHaveBeenCalledWith('yesterday');
});
it('should pass parsed dates to git log', async () => {
vi.spyOn(dateUtils, 'toGitDate')
.mockReturnValueOnce('2024-01-01')
.mockReturnValueOnce('2024-12-31');
mockGitLog.mockResolvedValue({ all: [] });
await listCommits({
repo: 'github.com/test/repo',
since: '30 days ago',
until: 'yesterday',
});
expect(mockGitLog).toHaveBeenCalledWith(
expect.objectContaining({
'--since': '2024-01-01',
'--until': '2024-12-31',
})
);
});
});
describe('git log options', () => {
beforeEach(() => {
vi.spyOn(dateUtils, 'toGitDate').mockImplementation((date) => date);
mockGitLog.mockResolvedValue({ all: [] });
});
it('should set default maxCount', async () => {
await listCommits({
repo: 'github.com/test/repo',
});
expect(mockGitLog).toHaveBeenCalledWith(
expect.objectContaining({
maxCount: 50,
HEAD: null,
})
);
});
it('should use custom maxCount', async () => {
await listCommits({
repo: 'github.com/test/repo',
maxCount: 100,
});
expect(mockGitLog).toHaveBeenCalledWith(
expect.objectContaining({
maxCount: 100,
HEAD: null,
})
);
});
it('should add --since when since is provided', async () => {
await listCommits({
repo: 'github.com/test/repo',
since: '30 days ago',
});
expect(mockGitLog).toHaveBeenCalledWith(
expect.objectContaining({
'--since': '30 days ago',
HEAD: null,
})
);
});
it('should add --until when until is provided', async () => {
await listCommits({
repo: 'github.com/test/repo',
until: 'yesterday',
});
expect(mockGitLog).toHaveBeenCalledWith(
expect.objectContaining({
'--until': 'yesterday',
HEAD: null,
})
);
});
it('should add --author when author is provided', async () => {
await listCommits({
repo: 'github.com/test/repo',
author: 'john@example.com',
});
expect(mockGitLog).toHaveBeenCalledWith(
expect.objectContaining({
'--author': 'john@example.com',
'--regexp-ignore-case': null,
HEAD: null,
})
);
});
it('should add --grep and --regexp-ignore-case when query is provided', async () => {
await listCommits({
repo: 'github.com/test/repo',
query: 'fix bug',
});
expect(mockGitLog).toHaveBeenCalledWith(
expect.objectContaining({
'--grep': 'fix bug',
'--regexp-ignore-case': null,
HEAD: null,
})
);
});
it('should combine all options', async () => {
await listCommits({
repo: 'github.com/test/repo',
query: 'feature',
since: '2024-01-01',
until: '2024-12-31',
author: 'jane@example.com',
maxCount: 25,
});
expect(mockGitLog).toHaveBeenCalledWith({
maxCount: 25,
HEAD: null,
'--since': '2024-01-01',
'--until': '2024-12-31',
'--author': 'jane@example.com',
'--regexp-ignore-case': null,
'--grep': 'feature',
});
});
});
describe('successful responses', () => {
it('should return commits and totalCount from git log', async () => {
const mockCommits = [
{
hash: 'abc123',
date: '2024-06-15',
message: 'feat: add feature',
refs: 'HEAD -> main',
body: '',
author_name: 'John Doe',
author_email: 'john@example.com',
},
{
hash: 'def456',
date: '2024-06-14',
message: 'fix: bug fix',
refs: '',
body: '',
author_name: 'Jane Smith',
author_email: 'jane@example.com',
},
];
mockGitLog.mockResolvedValue({ all: mockCommits });
mockGitRaw.mockResolvedValue('2');
const result = await listCommits({
repo: 'github.com/test/repo',
});
expect(result).toEqual({ commits: mockCommits, totalCount: 2 });
});
it('should return empty commits array when no commits match', async () => {
mockGitLog.mockResolvedValue({ all: [] });
mockGitRaw.mockResolvedValue('0');
const result = await listCommits({
repo: 'github.com/test/repo',
query: 'nonexistent',
});
expect(result).toEqual({ commits: [], totalCount: 0 });
});
});
describe('error handling', () => {
it('should return error for "not a git repository"', async () => {
mockGitLog.mockRejectedValue(new Error('not a git repository'));
const result = await listCommits({
repo: 'github.com/test/repo',
});
expect(result).toMatchObject({
errorCode: 'UNEXPECTED_ERROR',
message: expect.stringContaining('not a valid git repository'),
});
});
it('should return error for "ambiguous argument"', async () => {
mockGitLog.mockRejectedValue(new Error('ambiguous argument'));
const result = await listCommits({
repo: 'github.com/test/repo',
since: 'invalid-date',
});
expect(result).toMatchObject({
errorCode: 'UNEXPECTED_ERROR',
message: expect.stringContaining('Invalid git reference or date format'),
});
});
it('should return error for timeout', async () => {
mockGitLog.mockRejectedValue(new Error('timeout exceeded'));
const result = await listCommits({
repo: 'github.com/test/repo',
});
expect(result).toMatchObject({
errorCode: 'UNEXPECTED_ERROR',
message: expect.stringContaining('timed out'),
});
});
it('should return ServiceError for other Error instances', async () => {
mockGitLog.mockRejectedValue(new Error('some other error'));
const result = await listCommits({
repo: 'github.com/test/repo',
});
expect(result).toMatchObject({
errorCode: 'UNEXPECTED_ERROR',
message: expect.stringContaining('Failed to search commits in repository github.com/test/repo'),
});
});
it('should return ServiceError for non-Error exceptions', async () => {
mockGitLog.mockRejectedValue('string error');
const result = await listCommits({
repo: 'github.com/test/repo',
});
expect(result).toMatchObject({
errorCode: 'UNEXPECTED_ERROR',
message: expect.stringContaining('Failed to search commits in repository github.com/test/repo'),
});
});
});
describe('git client configuration', () => {
it('should set working directory using cwd', async () => {
mockGitLog.mockResolvedValue({ all: [] });
await listCommits({
repo: 'github.com/test/repo',
});
expect(mockCwd).toHaveBeenCalledWith('/mock/cache/dir/123');
});
it('should use correct repository path from database', async () => {
mockFindFirst.mockResolvedValue({ id: 456, name: 'github.com/other/repo' });
mockGitLog.mockResolvedValue({ all: [] });
await listCommits({
repo: 'github.com/other/repo',
});
expect(mockCwd).toHaveBeenCalledWith('/mock/cache/dir/456');
});
});
describe('integration scenarios', () => {
it('should handle a typical commit search with filters', async () => {
const mockCommits = [
{
hash: 'abc123',
date: '2024-06-10T14:30:00Z',
message: 'fix: resolve authentication bug',
refs: 'HEAD -> main',
body: 'Fixed issue with JWT token validation',
author_name: 'Security Team',
author_email: 'security@example.com',
},
];
vi.spyOn(dateUtils, 'validateDateRange').mockReturnValue(null);
vi.spyOn(dateUtils, 'toGitDate').mockImplementation((date) => date);
mockGitLog.mockResolvedValue({ all: mockCommits });
mockGitRaw.mockResolvedValue('1');
const result = await listCommits({
repo: 'github.com/test/repo',
query: 'authentication',
since: '30 days ago',
until: 'yesterday',
author: 'security',
maxCount: 20,
});
expect(result).toEqual({ commits: mockCommits, totalCount: 1 });
expect(mockGitLog).toHaveBeenCalledWith({
maxCount: 20,
HEAD: null,
'--since': '30 days ago',
'--until': 'yesterday',
'--author': 'security',
'--regexp-ignore-case': null,
'--grep': 'authentication',
});
});
it('should handle repository not found in database', async () => {
mockFindFirst.mockResolvedValue(null);
const result = await listCommits({
repo: 'github.com/nonexistent/repo',
query: 'feature',
});
expect(result).toMatchObject({
errorCode: 'NOT_FOUND',
});
expect(result).toHaveProperty('message');
const message = (result as { message: string }).message;
expect(message).toContain('github.com/nonexistent/repo');
expect(message).toContain('not found');
});
});
describe('repository lookup', () => {
beforeEach(() => {
// Reset mockFindFirst before each test in this suite
mockFindFirst.mockReset();
});
it('should query database for repository by name', async () => {
mockFindFirst.mockResolvedValue({ id: 456, name: 'github.com/owner/repo' });
mockGitLog.mockResolvedValue({ all: [] });
const result = await listCommits({
repo: 'github.com/owner/repo',
});
expect(result).toMatchObject({ commits: [], totalCount: expect.any(Number) });
expect(mockFindFirst).toHaveBeenCalledWith({
where: {
name: 'github.com/owner/repo',
orgId: 1,
},
});
});
it('should return NOT_FOUND error when repository is not found', async () => {
mockFindFirst.mockResolvedValue(null);
const result = await listCommits({
repo: 'github.com/nonexistent/repo',
});
expect(result).toMatchObject({
errorCode: 'NOT_FOUND',
message: expect.stringContaining('Repository "github.com/nonexistent/repo" not found'),
});
});
it('should use repository ID from database to determine path', async () => {
mockFindFirst.mockResolvedValue({ id: 789, name: 'github.com/example/project' });
mockGitLog.mockResolvedValue({ all: [] });
await listCommits({
repo: 'github.com/example/project',
});
expect(mockCwd).toHaveBeenCalledWith('/mock/cache/dir/789');
});
it('should work end-to-end with repository lookup', async () => {
const mockCommits = [
{
hash: 'xyz789',
date: '2024-06-20T10:00:00Z',
message: 'feat: new feature',
refs: 'main',
body: 'Added new functionality',
author_name: 'Developer',
author_email: 'dev@example.com',
},
];
mockFindFirst.mockResolvedValue({ id: 555, name: 'github.com/test/repository' });
vi.spyOn(dateUtils, 'validateDateRange').mockReturnValue(null);
vi.spyOn(dateUtils, 'toGitDate').mockImplementation((date) => date);
mockGitLog.mockResolvedValue({ all: mockCommits });
mockGitRaw.mockResolvedValue('1');
const result = await listCommits({
repo: 'github.com/test/repository',
query: 'feature',
since: '7 days ago',
author: 'Developer',
});
expect(result).toEqual({ commits: mockCommits, totalCount: 1 });
expect(mockCwd).toHaveBeenCalledWith('/mock/cache/dir/555');
});
});
});