-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathsummary.test.ts
More file actions
375 lines (316 loc) · 10.9 KB
/
summary.test.ts
File metadata and controls
375 lines (316 loc) · 10.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
/**
* Tests for summary command
*/
import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
// Mock process.cwd to return our temp directory
let mockProjectDir: string;
vi.mock('child_process', () => ({
exec: vi.fn(),
execFile: vi.fn(),
execSync: vi.fn(),
spawn: vi.fn(),
}));
vi.mock('@night-watch/core/utils/crontab.js', () => ({
getEntries: vi.fn(() => []),
getProjectEntries: vi.fn(() => []),
generateMarker: vi.fn((name: string) => `# night-watch-cli: ${name}`),
}));
// Mock job-queue module
vi.mock('@night-watch/core/utils/job-queue.js', () => ({
getJobRunsAnalytics: vi.fn(() => ({
recentRuns: [],
byProviderBucket: {},
averageWaitSeconds: null,
oldestPendingAge: null,
})),
getQueueStatus: vi.fn(() => ({
enabled: true,
running: null,
pending: { total: 0, byType: {}, byProviderBucket: {} },
items: [],
averageWaitSeconds: null,
oldestPendingAge: null,
})),
}));
// Mock status-data module
vi.mock('@night-watch/core/utils/status-data.js', () => ({
collectPrInfo: vi.fn(async () => []),
}));
// Mock process.cwd before importing module
const originalCwd = process.cwd;
process.cwd = () => mockProjectDir;
// Import after mocking
import { summaryCommand } from '@/cli/commands/summary.js';
import { Command } from 'commander';
import { getJobRunsAnalytics, getQueueStatus } from '@night-watch/core/utils/job-queue.js';
import { collectPrInfo } from '@night-watch/core/utils/status-data.js';
describe('summary command', () => {
let tempDir: string;
let consoleSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
vi.clearAllMocks();
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'night-watch-summary-test-'));
mockProjectDir = tempDir;
// Create basic package.json
fs.writeFileSync(path.join(tempDir, 'package.json'), JSON.stringify({ name: 'test-project' }));
// Create config file
fs.writeFileSync(
path.join(tempDir, 'night-watch.config.json'),
JSON.stringify(
{
projectName: 'test-project',
defaultBranch: 'main',
provider: 'claude',
reviewerEnabled: true,
prdDir: 'docs/PRDs/night-watch',
maxRuntime: 7200,
reviewerMaxRuntime: 3600,
branchPatterns: ['feat/', 'night-watch/'],
notifications: { webhooks: [] },
},
null,
2,
),
);
// Reset mocks to return default values
vi.mocked(getJobRunsAnalytics).mockReturnValue({
recentRuns: [],
byProviderBucket: {},
averageWaitSeconds: null,
oldestPendingAge: null,
});
vi.mocked(getQueueStatus).mockReturnValue({
enabled: true,
running: null,
pending: { total: 0, byType: {}, byProviderBucket: {} },
items: [],
averageWaitSeconds: null,
oldestPendingAge: null,
});
vi.mocked(collectPrInfo).mockResolvedValue([]);
consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
});
afterEach(() => {
fs.rmSync(tempDir, { recursive: true, force: true });
consoleSpy.mockRestore();
});
afterAll(() => {
process.cwd = originalCwd;
});
describe('help text', () => {
it('should show help text with --help flag', async () => {
const program = new Command();
summaryCommand(program);
program.exitOverride();
let capturedOutput = '';
program.configureOutput({
writeOut: (str: string) => {
capturedOutput += str;
},
});
try {
await program.parseAsync(['node', 'test', 'summary', '--help']);
} catch {
// Help throws by default in commander
}
expect(capturedOutput).toContain('--hours');
expect(capturedOutput).toContain('--json');
});
});
describe('formatted output', () => {
it('should display summary header with time window', async () => {
const program = new Command();
summaryCommand(program);
await program.parseAsync(['node', 'test', 'summary']);
const output = consoleSpy.mock.calls.map((call) => call.join(' ')).join('\n');
expect(output).toContain('Night Watch Summary');
expect(output).toContain('last 12h');
});
});
describe('JSON output', () => {
it('should output valid JSON when --json flag is used', async () => {
const program = new Command();
summaryCommand(program);
await program.parseAsync(['node', 'test', 'summary', '--json']);
const output = consoleSpy.mock.calls[0]?.[0] || '';
const parsed = JSON.parse(output);
expect(parsed).toHaveProperty('windowHours');
expect(parsed).toHaveProperty('jobRuns');
expect(parsed).toHaveProperty('counts');
expect(parsed).toHaveProperty('openPrs');
expect(parsed).toHaveProperty('pendingQueueItems');
expect(parsed).toHaveProperty('actionItems');
});
it('should include correct windowHours in JSON output', async () => {
const program = new Command();
summaryCommand(program);
await program.parseAsync(['node', 'test', 'summary', '--json', '--hours', '8']);
const output = consoleSpy.mock.calls[0]?.[0] || '';
const parsed = JSON.parse(output);
expect(parsed.windowHours).toBe(8);
});
});
describe('job counts', () => {
it('should use default 12 hours when --hours not specified', async () => {
const program = new Command();
summaryCommand(program);
await program.parseAsync(['node', 'test', 'summary']);
expect(vi.mocked(getJobRunsAnalytics)).toHaveBeenCalledWith(12);
});
it('should respect custom --hours value', async () => {
const program = new Command();
summaryCommand(program);
await program.parseAsync(['node', 'test', 'summary', '--hours', '24']);
expect(vi.mocked(getJobRunsAnalytics)).toHaveBeenCalledWith(24);
});
it('should show "No recent activity" when no jobs ran', async () => {
const program = new Command();
summaryCommand(program);
await program.parseAsync(['node', 'test', 'summary']);
const output = consoleSpy.mock.calls.map((call) => call.join(' ')).join('\n');
expect(output).toContain('No recent activity');
});
it('should show job counts from analytics data', async () => {
vi.mocked(getJobRunsAnalytics).mockReturnValue({
recentRuns: [
{
id: 1,
projectPath: '/project',
jobType: 'executor',
providerKey: 'claude',
status: 'success',
startedAt: Math.floor(Date.now() / 1000) - 3600,
finishedAt: Math.floor(Date.now() / 1000),
waitSeconds: 10,
durationSeconds: 300,
throttledCount: 0,
},
{
id: 2,
projectPath: '/project',
jobType: 'reviewer',
providerKey: 'claude',
status: 'failure',
startedAt: Math.floor(Date.now() / 1000) - 3600,
finishedAt: Math.floor(Date.now() / 1000),
waitSeconds: 5,
durationSeconds: 180,
throttledCount: 0,
},
],
byProviderBucket: {},
averageWaitSeconds: 7,
oldestPendingAge: null,
});
const program = new Command();
summaryCommand(program);
await program.parseAsync(['node', 'test', 'summary']);
const output = consoleSpy.mock.calls.map((call) => call.join(' ')).join('\n');
expect(output).toContain('1 succeeded');
expect(output).toContain('1 failed');
});
it('should generate action items for failed jobs', async () => {
vi.mocked(getJobRunsAnalytics).mockReturnValue({
recentRuns: [
{
id: 1,
projectPath: '/project',
jobType: 'executor',
providerKey: 'claude',
status: 'failure',
startedAt: Math.floor(Date.now() / 1000) - 3600,
finishedAt: Math.floor(Date.now() / 1000),
waitSeconds: 10,
durationSeconds: 300,
throttledCount: 0,
},
],
byProviderBucket: {},
averageWaitSeconds: null,
oldestPendingAge: null,
});
const program = new Command();
summaryCommand(program);
await program.parseAsync(['node', 'test', 'summary']);
const output = consoleSpy.mock.calls.map((call) => call.join(' ')).join('\n');
expect(output).toContain('Action needed');
expect(output).toContain('night-watch logs');
});
it('should show "No action needed" when all jobs healthy', async () => {
vi.mocked(getJobRunsAnalytics).mockReturnValue({
recentRuns: [
{
id: 1,
projectPath: '/project',
jobType: 'executor',
providerKey: 'claude',
status: 'success',
startedAt: Math.floor(Date.now() / 1000) - 3600,
finishedAt: Math.floor(Date.now() / 1000),
waitSeconds: 10,
durationSeconds: 300,
throttledCount: 0,
},
],
byProviderBucket: {},
averageWaitSeconds: null,
oldestPendingAge: null,
});
vi.mocked(getQueueStatus).mockReturnValue({
enabled: true,
running: null,
pending: { total: 0, byType: {}, byProviderBucket: {} },
items: [],
averageWaitSeconds: null,
oldestPendingAge: null,
});
const program = new Command();
summaryCommand(program);
await program.parseAsync(['node', 'test', 'summary']);
const output = consoleSpy.mock.calls.map((call) => call.join(' ')).join('\n');
expect(output).toContain('No action needed');
});
});
describe('PR data', () => {
it('should generate action items for PRs with failing CI', async () => {
vi.mocked(getJobRunsAnalytics).mockReturnValue({
recentRuns: [
{
id: 1,
projectPath: '/project',
jobType: 'executor',
providerKey: 'claude',
status: 'success',
startedAt: Math.floor(Date.now() / 1000) - 3600,
finishedAt: Math.floor(Date.now() / 1000),
waitSeconds: 10,
durationSeconds: 300,
throttledCount: 0,
},
],
byProviderBucket: {},
averageWaitSeconds: null,
oldestPendingAge: null,
});
vi.mocked(collectPrInfo).mockResolvedValue([
{
number: 42,
title: 'Test PR',
branch: 'feat/test',
url: 'https://github.com/test/repo/pull/42',
ciStatus: 'fail',
reviewScore: null,
},
]);
const program = new Command();
summaryCommand(program);
await program.parseAsync(['node', 'test', 'summary']);
const output = consoleSpy.mock.calls.map((call) => call.join(' ')).join('\n');
expect(output).toContain('Action needed');
expect(output).toContain('PR #42');
});
});
});