-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgenerate-news-breaking-errors.test.ts
More file actions
167 lines (139 loc) · 5.61 KB
/
Copy pathgenerate-news-breaking-errors.test.ts
File metadata and controls
167 lines (139 loc) · 5.61 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
/**
* Tests that generateNews() correctly increments stats.errors when the
* 'breaking' article type fails — either via a returned {success: false}
* or a thrown exception.
*
* This covers the exit-code-critical behavior: runCli() uses stats.errors > 0
* to decide exit code 1 vs 0, which the agent relies on to detect failures.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
import type { GenerationStats, GenerationResult } from '../scripts/types/article.js';
// ---------------------------------------------------------------------------
// Hoisted mocks — vi.hoisted() runs before vi.mock() calls
// ---------------------------------------------------------------------------
const { mockGenerateBreakingNews, mockStats, mockGetSharedClient } = vi.hoisted(() => {
const mockGenerateBreakingNews = vi.fn<(...args: unknown[]) => Promise<GenerationResult>>();
const mockStats: GenerationStats = {
generated: 0,
errors: 0,
articles: [],
timestamp: new Date().toISOString(),
qualityScores: []
};
const mockGetSharedClient = vi.fn().mockResolvedValue({
fetchVotingRecords: vi.fn().mockResolvedValue([{ doktyp: 'prop', titel: 'Test Prop' }]),
searchDocuments: vi.fn().mockResolvedValue([{ doktyp: 'prop', titel: 'Test Prop' }])
});
return { mockGenerateBreakingNews, mockStats, mockGetSharedClient };
});
// Mock fs module at the module level (hoisted before imports) to prevent file writes
vi.mock('fs', async (importOriginal) => {
const original = await importOriginal<typeof import('fs')>();
return {
...original,
default: {
...original,
writeFileSync: vi.fn(),
mkdirSync: vi.fn(),
existsSync: vi.fn().mockReturnValue(false),
readdirSync: vi.fn().mockReturnValue([]),
},
writeFileSync: vi.fn(),
mkdirSync: vi.fn(),
existsSync: vi.fn().mockReturnValue(false),
readdirSync: vi.fn().mockReturnValue([]),
};
});
// Mock the breaking-news module
vi.mock('../scripts/news-types/breaking-news.js', () => ({
generateBreakingNews: mockGenerateBreakingNews
}));
// Mock the config module — set articleTypes to ['breaking'] and expose stats
vi.mock('../scripts/generate-news-enhanced/config.js', async (importOriginal) => {
const original = await importOriginal<typeof import('../scripts/generate-news-enhanced/config.js')>();
return {
...original,
articleTypes: ['breaking'],
stats: mockStats,
getSharedClient: mockGetSharedClient,
// Provide stable values for other config exports
languages: ['en'],
allRequestedLanguages: ['en'],
batchSize: undefined,
skipExistingArg: false,
requireMcp: false,
};
});
// Mock MCP client
vi.mock('../scripts/mcp-client.js', () => ({
MCPClient: vi.fn().mockImplementation(() => ({
fetchVotingRecords: vi.fn().mockResolvedValue([]),
searchDocuments: vi.fn().mockResolvedValue([])
})),
getDefaultClient: vi.fn()
}));
// ---------------------------------------------------------------------------
// Import after mocks
// ---------------------------------------------------------------------------
interface GenerateNewsModule {
readonly generateNews: () => Promise<GenerationStats>;
}
let moduleExports: GenerateNewsModule;
beforeAll(async () => {
moduleExports = await import('../scripts/generate-news-enhanced/index.js') as unknown as GenerateNewsModule;
});
afterAll(() => {
vi.restoreAllMocks();
});
describe('generateNews() — breaking news error tracking', () => {
beforeEach(() => {
// Reset stats before each test
mockStats.errors = 0;
mockStats.generated = 0;
mockStats.articles = [];
mockStats.qualityScores = [];
vi.clearAllMocks();
// Re-setup shared client mock after clearAllMocks
mockGetSharedClient.mockResolvedValue({
fetchVotingRecords: vi.fn().mockResolvedValue([{ doktyp: 'prop', titel: 'Test Prop' }]),
searchDocuments: vi.fn().mockResolvedValue([{ doktyp: 'prop', titel: 'Test Prop' }])
});
});
it('should increment stats.errors when generateBreakingNews returns success=false', async () => {
mockGenerateBreakingNews.mockResolvedValueOnce({
success: false,
error: 'MCP server unreachable'
});
const result = await moduleExports.generateNews();
expect(mockGenerateBreakingNews).toHaveBeenCalled();
expect(result.errors).toBe(1);
});
it('should increment stats.errors when generateBreakingNews throws an exception', async () => {
// Make getSharedClient itself throw so the catch block fires
mockGetSharedClient.mockRejectedValueOnce(new Error('Connection timeout'));
const result = await moduleExports.generateNews();
expect(result.errors).toBe(1);
});
it('should NOT increment stats.errors when generateBreakingNews returns success=true', async () => {
mockGenerateBreakingNews.mockResolvedValueOnce({
success: true,
articles: [{ lang: 'en', html: '<p>Breaking</p>', slug: 'test', filename: 'test.html' }]
});
const result = await moduleExports.generateNews();
expect(mockGenerateBreakingNews).toHaveBeenCalled();
expect(result.errors).toBe(0);
});
it('should log the error message from failed generation result', async () => {
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
mockGenerateBreakingNews.mockResolvedValueOnce({
success: false,
error: 'Breaking: no significant events today'
});
await moduleExports.generateNews();
expect(consoleSpy).toHaveBeenCalledWith(
expect.stringContaining('Breaking news generation failed'),
expect.stringContaining('no significant events today')
);
consoleSpy.mockRestore();
});
});