qai-cli 3.0.1 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/generate.js +495 -0
- package/src/index.js +65 -0
- package/src/providers/anthropic.js +13 -0
- package/src/providers/base.js +10 -0
- package/src/providers/gemini.js +7 -0
- package/src/providers/ollama.js +20 -0
- package/src/providers/openai.js +10 -0
package/package.json
CHANGED
package/src/generate.js
ADDED
|
@@ -0,0 +1,495 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Test Generation Engine
|
|
3
|
+
*
|
|
4
|
+
* Two modes:
|
|
5
|
+
* 1. URL crawl: Navigate a site, record interactions, generate Playwright E2E specs
|
|
6
|
+
* 2. Code analysis: Read source files, generate unit/integration tests
|
|
7
|
+
*
|
|
8
|
+
* Usage:
|
|
9
|
+
* qai generate https://mysite.com # E2E tests from URL
|
|
10
|
+
* qai generate src/billing.ts # Unit tests from source
|
|
11
|
+
* qai generate src/ --pattern "*.service*" # Batch generate
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
const fs = require('fs');
|
|
15
|
+
const path = require('path');
|
|
16
|
+
const { getProvider } = require('./providers');
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Generate tests from a URL (E2E) or source file (unit)
|
|
20
|
+
*
|
|
21
|
+
* @param {Object} options
|
|
22
|
+
* @param {string} options.target - URL or file/directory path
|
|
23
|
+
* @param {string} [options.outDir] - Output directory for generated tests (default: ./tests/generated)
|
|
24
|
+
* @param {string} [options.framework] - Test framework (playwright, jest, vitest)
|
|
25
|
+
* @param {string} [options.pattern] - Glob pattern for batch file mode
|
|
26
|
+
* @param {string} [options.baseUrl] - Base URL for generated E2E tests
|
|
27
|
+
* @param {boolean} [options.dryRun] - Print tests to stdout instead of writing files
|
|
28
|
+
* @returns {Promise<GenerateResult>}
|
|
29
|
+
*/
|
|
30
|
+
async function generateTests(options = {}) {
|
|
31
|
+
const {
|
|
32
|
+
target,
|
|
33
|
+
outDir = './tests/generated',
|
|
34
|
+
framework = 'playwright',
|
|
35
|
+
dryRun = false,
|
|
36
|
+
} = options;
|
|
37
|
+
|
|
38
|
+
if (!target) {
|
|
39
|
+
throw new Error('Target is required (URL or file path)');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Determine mode: URL or file
|
|
43
|
+
const isUrl = target.startsWith('http://') || target.startsWith('https://');
|
|
44
|
+
|
|
45
|
+
if (isUrl) {
|
|
46
|
+
return generateE2ETests({ ...options, url: target, outDir, framework, dryRun });
|
|
47
|
+
} else {
|
|
48
|
+
return generateUnitTests({ ...options, filePath: target, outDir, framework, dryRun });
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Generate E2E tests by crawling a URL
|
|
54
|
+
*/
|
|
55
|
+
async function generateE2ETests(options) {
|
|
56
|
+
const { url, outDir, framework, dryRun } = options;
|
|
57
|
+
|
|
58
|
+
console.log('[1/3] Crawling site...');
|
|
59
|
+
const siteData = await crawlSite(url);
|
|
60
|
+
|
|
61
|
+
console.log(
|
|
62
|
+
` Found ${siteData.pages.length} pages, ${siteData.interactions.length} interactive elements`,
|
|
63
|
+
);
|
|
64
|
+
|
|
65
|
+
console.log('[2/3] Generating tests with AI...');
|
|
66
|
+
const provider = getProvider();
|
|
67
|
+
const prompt = buildE2EPrompt(siteData, framework);
|
|
68
|
+
const result = await provider.generateTests(prompt);
|
|
69
|
+
|
|
70
|
+
console.log('[3/3] Writing test files...');
|
|
71
|
+
const files = parseGeneratedFiles(result);
|
|
72
|
+
|
|
73
|
+
if (dryRun) {
|
|
74
|
+
for (const file of files) {
|
|
75
|
+
console.log(`\n--- ${file.name} ---`);
|
|
76
|
+
console.log(file.content);
|
|
77
|
+
}
|
|
78
|
+
} else {
|
|
79
|
+
writeTestFiles(files, outDir);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return {
|
|
83
|
+
mode: 'e2e',
|
|
84
|
+
url,
|
|
85
|
+
pagesFound: siteData.pages.length,
|
|
86
|
+
testsGenerated: files.length,
|
|
87
|
+
files: files.map((f) => f.name),
|
|
88
|
+
outDir,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Generate unit tests from source file(s)
|
|
94
|
+
*/
|
|
95
|
+
async function generateUnitTests(options) {
|
|
96
|
+
const { filePath, outDir, framework, dryRun, pattern } = options;
|
|
97
|
+
|
|
98
|
+
console.log('[1/3] Reading source files...');
|
|
99
|
+
const sources = readSourceFiles(filePath, pattern);
|
|
100
|
+
console.log(` Found ${sources.length} source files`);
|
|
101
|
+
|
|
102
|
+
if (sources.length === 0) {
|
|
103
|
+
throw new Error(`No source files found at: ${filePath}`);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const allFiles = [];
|
|
107
|
+
|
|
108
|
+
for (const source of sources) {
|
|
109
|
+
console.log(`[2/3] Generating tests for ${source.relativePath}...`);
|
|
110
|
+
const provider = getProvider();
|
|
111
|
+
const prompt = buildUnitTestPrompt(source, framework);
|
|
112
|
+
const result = await provider.generateTests(prompt);
|
|
113
|
+
const files = parseGeneratedFiles(result);
|
|
114
|
+
|
|
115
|
+
allFiles.push(...files);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
console.log('[3/3] Writing test files...');
|
|
119
|
+
if (dryRun) {
|
|
120
|
+
for (const file of allFiles) {
|
|
121
|
+
console.log(`\n--- ${file.name} ---`);
|
|
122
|
+
console.log(file.content);
|
|
123
|
+
}
|
|
124
|
+
} else {
|
|
125
|
+
writeTestFiles(allFiles, outDir);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
return {
|
|
129
|
+
mode: 'unit',
|
|
130
|
+
sourcesAnalyzed: sources.length,
|
|
131
|
+
testsGenerated: allFiles.length,
|
|
132
|
+
files: allFiles.map((f) => f.name),
|
|
133
|
+
outDir,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Crawl a site and gather page data using Playwright
|
|
139
|
+
*/
|
|
140
|
+
async function crawlSite(url) {
|
|
141
|
+
let playwright;
|
|
142
|
+
try {
|
|
143
|
+
playwright = require('playwright');
|
|
144
|
+
} catch {
|
|
145
|
+
throw new Error(
|
|
146
|
+
'Playwright is required for E2E test generation. Install it: npm install playwright',
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const browser = await playwright.chromium.launch({ headless: true });
|
|
151
|
+
const context = await browser.newContext();
|
|
152
|
+
const page = await context.newPage();
|
|
153
|
+
|
|
154
|
+
const pages = [];
|
|
155
|
+
const interactions = [];
|
|
156
|
+
const visited = new Set();
|
|
157
|
+
const baseUrl = new URL(url);
|
|
158
|
+
const toVisit = [url];
|
|
159
|
+
|
|
160
|
+
// Crawl up to 10 pages
|
|
161
|
+
while (toVisit.length > 0 && visited.size < 10) {
|
|
162
|
+
const currentUrl = toVisit.shift();
|
|
163
|
+
if (visited.has(currentUrl)) continue;
|
|
164
|
+
visited.add(currentUrl);
|
|
165
|
+
|
|
166
|
+
try {
|
|
167
|
+
await page.goto(currentUrl, { waitUntil: 'networkidle', timeout: 15000 });
|
|
168
|
+
await page.waitForTimeout(1000);
|
|
169
|
+
|
|
170
|
+
const title = await page.title();
|
|
171
|
+
const pageUrl = page.url();
|
|
172
|
+
|
|
173
|
+
// Gather interactive elements
|
|
174
|
+
/* eslint-disable no-undef */
|
|
175
|
+
const elements = await page.evaluate(() => {
|
|
176
|
+
const result = [];
|
|
177
|
+
|
|
178
|
+
// Buttons
|
|
179
|
+
document.querySelectorAll('button, [role="button"]').forEach((el) => {
|
|
180
|
+
result.push({
|
|
181
|
+
type: 'button',
|
|
182
|
+
text: el.textContent.trim().slice(0, 100),
|
|
183
|
+
selector: getSelector(el),
|
|
184
|
+
});
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
// Links
|
|
188
|
+
document.querySelectorAll('a[href]').forEach((el) => {
|
|
189
|
+
result.push({
|
|
190
|
+
type: 'link',
|
|
191
|
+
text: el.textContent.trim().slice(0, 100),
|
|
192
|
+
href: el.href,
|
|
193
|
+
selector: getSelector(el),
|
|
194
|
+
});
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
// Forms
|
|
198
|
+
document.querySelectorAll('form').forEach((form) => {
|
|
199
|
+
const inputs = [];
|
|
200
|
+
form.querySelectorAll('input, textarea, select').forEach((input) => {
|
|
201
|
+
inputs.push({
|
|
202
|
+
type: input.type || input.tagName.toLowerCase(),
|
|
203
|
+
name: input.name,
|
|
204
|
+
placeholder: input.placeholder,
|
|
205
|
+
required: input.required,
|
|
206
|
+
selector: getSelector(input),
|
|
207
|
+
});
|
|
208
|
+
});
|
|
209
|
+
result.push({
|
|
210
|
+
type: 'form',
|
|
211
|
+
action: form.action,
|
|
212
|
+
method: form.method,
|
|
213
|
+
inputs,
|
|
214
|
+
selector: getSelector(form),
|
|
215
|
+
});
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
// Navigation elements
|
|
219
|
+
document.querySelectorAll('nav a, [role="navigation"] a').forEach((el) => {
|
|
220
|
+
result.push({
|
|
221
|
+
type: 'nav-link',
|
|
222
|
+
text: el.textContent.trim().slice(0, 100),
|
|
223
|
+
href: el.href,
|
|
224
|
+
selector: getSelector(el),
|
|
225
|
+
});
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
function getSelector(el) {
|
|
229
|
+
if (el.id) return `#${el.id}`;
|
|
230
|
+
if (el.getAttribute('data-testid')) {
|
|
231
|
+
return `[data-testid="${el.getAttribute('data-testid')}"]`;
|
|
232
|
+
}
|
|
233
|
+
if (el.getAttribute('aria-label')) {
|
|
234
|
+
return `[aria-label="${el.getAttribute('aria-label')}"]`;
|
|
235
|
+
}
|
|
236
|
+
const text = el.textContent.trim().slice(0, 30);
|
|
237
|
+
if (text && el.tagName) {
|
|
238
|
+
return `${el.tagName.toLowerCase()}:has-text("${text}")`;
|
|
239
|
+
}
|
|
240
|
+
return null;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
return result;
|
|
244
|
+
});
|
|
245
|
+
/* eslint-enable no-undef */
|
|
246
|
+
|
|
247
|
+
pages.push({ url: pageUrl, title, elementCount: elements.length });
|
|
248
|
+
interactions.push(...elements.map((e) => ({ ...e, page: pageUrl })));
|
|
249
|
+
|
|
250
|
+
// Find same-origin links to crawl
|
|
251
|
+
const links = elements
|
|
252
|
+
.filter((e) => e.type === 'link' || e.type === 'nav-link')
|
|
253
|
+
.filter((e) => {
|
|
254
|
+
try {
|
|
255
|
+
const linkUrl = new URL(e.href);
|
|
256
|
+
return linkUrl.origin === baseUrl.origin;
|
|
257
|
+
} catch {
|
|
258
|
+
return false;
|
|
259
|
+
}
|
|
260
|
+
})
|
|
261
|
+
.map((e) => e.href);
|
|
262
|
+
|
|
263
|
+
for (const link of links) {
|
|
264
|
+
if (!visited.has(link)) {
|
|
265
|
+
toVisit.push(link);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
} catch {
|
|
269
|
+
// Skip pages that fail to load
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
await browser.close();
|
|
274
|
+
|
|
275
|
+
return { url, pages, interactions };
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Read source file(s) for unit test generation
|
|
280
|
+
*/
|
|
281
|
+
function readSourceFiles(filePath, pattern) {
|
|
282
|
+
const sources = [];
|
|
283
|
+
const absPath = path.resolve(filePath);
|
|
284
|
+
|
|
285
|
+
if (fs.existsSync(absPath) && fs.statSync(absPath).isFile()) {
|
|
286
|
+
// Single file
|
|
287
|
+
sources.push({
|
|
288
|
+
relativePath: filePath,
|
|
289
|
+
content: fs.readFileSync(absPath, 'utf-8'),
|
|
290
|
+
ext: path.extname(filePath),
|
|
291
|
+
});
|
|
292
|
+
} else if (fs.existsSync(absPath) && fs.statSync(absPath).isDirectory()) {
|
|
293
|
+
// Directory - find source files
|
|
294
|
+
const exts = ['.js', '.ts', '.jsx', '.tsx', '.mjs'];
|
|
295
|
+
const skipDirs = ['node_modules', '.next', 'dist', '.git', '__tests__', 'test', 'tests'];
|
|
296
|
+
|
|
297
|
+
const walk = (dir) => {
|
|
298
|
+
const entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
299
|
+
for (const entry of entries) {
|
|
300
|
+
const fullPath = path.join(dir, entry.name);
|
|
301
|
+
if (entry.isDirectory()) {
|
|
302
|
+
if (!skipDirs.includes(entry.name)) walk(fullPath);
|
|
303
|
+
} else if (entry.isFile()) {
|
|
304
|
+
const ext = path.extname(entry.name);
|
|
305
|
+
if (!exts.includes(ext)) continue;
|
|
306
|
+
// Skip test files
|
|
307
|
+
if (entry.name.includes('.test.') || entry.name.includes('.spec.')) continue;
|
|
308
|
+
// Apply pattern filter if specified
|
|
309
|
+
if (pattern && !entry.name.match(new RegExp(pattern.replace(/\*/g, '.*')))) continue;
|
|
310
|
+
|
|
311
|
+
const content = fs.readFileSync(fullPath, 'utf-8');
|
|
312
|
+
// Skip very large or very small files
|
|
313
|
+
if (content.length > 30000 || content.length < 50) continue;
|
|
314
|
+
|
|
315
|
+
sources.push({
|
|
316
|
+
relativePath: path.relative(process.cwd(), fullPath),
|
|
317
|
+
content,
|
|
318
|
+
ext,
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
walk(absPath);
|
|
325
|
+
// Cap at 10 files
|
|
326
|
+
sources.splice(10);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
return sources;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Build prompt for E2E test generation
|
|
334
|
+
*/
|
|
335
|
+
function buildE2EPrompt(siteData, framework) {
|
|
336
|
+
const frameworkGuide = E2E_FRAMEWORKS[framework] || E2E_FRAMEWORKS.playwright;
|
|
337
|
+
|
|
338
|
+
return `You are a senior QA automation engineer. Generate comprehensive E2E tests for this website.
|
|
339
|
+
|
|
340
|
+
## Site Information
|
|
341
|
+
- URL: ${siteData.url}
|
|
342
|
+
- Pages found: ${siteData.pages.length}
|
|
343
|
+
|
|
344
|
+
## Pages
|
|
345
|
+
${siteData.pages.map((p) => `- ${p.url} (${p.title}) - ${p.elementCount} elements`).join('\n')}
|
|
346
|
+
|
|
347
|
+
## Interactive Elements
|
|
348
|
+
${JSON.stringify(siteData.interactions.slice(0, 100), null, 2)}
|
|
349
|
+
|
|
350
|
+
## Framework
|
|
351
|
+
${frameworkGuide}
|
|
352
|
+
|
|
353
|
+
## Instructions
|
|
354
|
+
Generate test files that cover:
|
|
355
|
+
1. Page navigation (all discovered pages load correctly)
|
|
356
|
+
2. Interactive elements (buttons click, forms submit)
|
|
357
|
+
3. Navigation flow (links work, nav elements route correctly)
|
|
358
|
+
4. Form validation (required fields, error states)
|
|
359
|
+
5. Responsive behavior (test at mobile and desktop viewports)
|
|
360
|
+
|
|
361
|
+
Output format - return ONLY a JSON array of files:
|
|
362
|
+
[
|
|
363
|
+
{
|
|
364
|
+
"name": "homepage.spec.ts",
|
|
365
|
+
"content": "// full test file content here"
|
|
366
|
+
}
|
|
367
|
+
]
|
|
368
|
+
|
|
369
|
+
Write real, runnable tests. Use descriptive test names. Add meaningful assertions.
|
|
370
|
+
Do NOT generate placeholder or skeleton tests.
|
|
371
|
+
Respond with ONLY the JSON array, no markdown code blocks.`;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* Build prompt for unit test generation
|
|
376
|
+
*/
|
|
377
|
+
function buildUnitTestPrompt(source, framework) {
|
|
378
|
+
const frameworkGuide = UNIT_FRAMEWORKS[framework] || UNIT_FRAMEWORKS.jest;
|
|
379
|
+
|
|
380
|
+
return `You are a senior QA automation engineer. Generate comprehensive unit tests for this source file.
|
|
381
|
+
|
|
382
|
+
## Source File: ${source.relativePath}
|
|
383
|
+
\`\`\`${source.ext.replace('.', '')}
|
|
384
|
+
${source.content}
|
|
385
|
+
\`\`\`
|
|
386
|
+
|
|
387
|
+
## Framework
|
|
388
|
+
${frameworkGuide}
|
|
389
|
+
|
|
390
|
+
## Instructions
|
|
391
|
+
Generate thorough unit tests that cover:
|
|
392
|
+
1. All exported functions/classes
|
|
393
|
+
2. Happy path for each function
|
|
394
|
+
3. Edge cases (null, undefined, empty, boundary values)
|
|
395
|
+
4. Error cases (invalid input, thrown errors)
|
|
396
|
+
5. Any async behavior (resolved/rejected promises)
|
|
397
|
+
|
|
398
|
+
Output format - return ONLY a JSON array of files:
|
|
399
|
+
[
|
|
400
|
+
{
|
|
401
|
+
"name": "${getTestFileName(source.relativePath, framework)}",
|
|
402
|
+
"content": "// full test file content here"
|
|
403
|
+
}
|
|
404
|
+
]
|
|
405
|
+
|
|
406
|
+
Write real, runnable tests with meaningful assertions.
|
|
407
|
+
Mock external dependencies where appropriate.
|
|
408
|
+
Do NOT generate placeholder or skeleton tests.
|
|
409
|
+
Respond with ONLY the JSON array, no markdown code blocks.`;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* Parse LLM response into file objects
|
|
414
|
+
*/
|
|
415
|
+
function parseGeneratedFiles(response) {
|
|
416
|
+
try {
|
|
417
|
+
let text = typeof response === 'string' ? response : response.raw || '';
|
|
418
|
+
|
|
419
|
+
// Remove markdown code blocks
|
|
420
|
+
if (text.startsWith('```')) {
|
|
421
|
+
text = text.replace(/```json?\n?/g, '').replace(/```\n?$/g, '');
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
const parsed = JSON.parse(text);
|
|
425
|
+
if (Array.isArray(parsed)) return parsed;
|
|
426
|
+
if (parsed.files) return parsed.files;
|
|
427
|
+
return [parsed];
|
|
428
|
+
} catch {
|
|
429
|
+
// If we can't parse JSON, treat entire response as a single test file
|
|
430
|
+
const text = typeof response === 'string' ? response : response.raw || '';
|
|
431
|
+
return [{ name: 'generated.spec.ts', content: text }];
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* Write test files to disk
|
|
437
|
+
*/
|
|
438
|
+
function writeTestFiles(files, outDir) {
|
|
439
|
+
const absOutDir = path.resolve(outDir);
|
|
440
|
+
if (!fs.existsSync(absOutDir)) {
|
|
441
|
+
fs.mkdirSync(absOutDir, { recursive: true });
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
for (const file of files) {
|
|
445
|
+
const filePath = path.join(absOutDir, file.name);
|
|
446
|
+
fs.writeFileSync(filePath, file.content);
|
|
447
|
+
console.log(` Written: ${filePath}`);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* Get test file name from source file path
|
|
453
|
+
*/
|
|
454
|
+
function getTestFileName(sourcePath, _framework) {
|
|
455
|
+
const ext = path.extname(sourcePath);
|
|
456
|
+
const base = path.basename(sourcePath, ext);
|
|
457
|
+
const testExt = ext === '.ts' || ext === '.tsx' ? '.test.ts' : '.test.js';
|
|
458
|
+
return `${base}${testExt}`;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
const E2E_FRAMEWORKS = {
|
|
462
|
+
playwright: `Use @playwright/test:
|
|
463
|
+
- import { test, expect } from '@playwright/test'
|
|
464
|
+
- Use page.goto(), page.click(), page.fill(), page.locator()
|
|
465
|
+
- Use expect(page).toHaveTitle(), expect(locator).toBeVisible()
|
|
466
|
+
- Use test.describe() for grouping
|
|
467
|
+
- Use page.setViewportSize() for responsive tests`,
|
|
468
|
+
};
|
|
469
|
+
|
|
470
|
+
const UNIT_FRAMEWORKS = {
|
|
471
|
+
jest: `Use Jest:
|
|
472
|
+
- describe/it/expect syntax
|
|
473
|
+
- jest.fn() for mocks
|
|
474
|
+
- beforeEach/afterEach for setup
|
|
475
|
+
- Use .toEqual, .toBe, .toThrow, .toBeNull etc.`,
|
|
476
|
+
vitest: `Use Vitest:
|
|
477
|
+
- import { describe, it, expect, vi } from 'vitest'
|
|
478
|
+
- vi.fn() for mocks
|
|
479
|
+
- Same assertion API as Jest`,
|
|
480
|
+
playwright: `Use @playwright/test:
|
|
481
|
+
- import { test, expect } from '@playwright/test'
|
|
482
|
+
- Same assertion API but for component/integration tests`,
|
|
483
|
+
};
|
|
484
|
+
|
|
485
|
+
module.exports = {
|
|
486
|
+
generateTests,
|
|
487
|
+
generateE2ETests,
|
|
488
|
+
generateUnitTests,
|
|
489
|
+
crawlSite,
|
|
490
|
+
readSourceFiles,
|
|
491
|
+
buildE2EPrompt,
|
|
492
|
+
buildUnitTestPrompt,
|
|
493
|
+
parseGeneratedFiles,
|
|
494
|
+
writeTestFiles,
|
|
495
|
+
};
|
package/src/index.js
CHANGED
|
@@ -4,6 +4,7 @@ const fs = require('fs').promises;
|
|
|
4
4
|
const { capturePage } = require('./capture');
|
|
5
5
|
const { getProvider } = require('./providers');
|
|
6
6
|
const { reviewPR, formatReviewMarkdown } = require('./review');
|
|
7
|
+
const { generateTests } = require('./generate');
|
|
7
8
|
|
|
8
9
|
// Route to the right command
|
|
9
10
|
const command = process.argv[2];
|
|
@@ -13,6 +14,11 @@ if (command === 'review') {
|
|
|
13
14
|
console.error('\nError:', err.message);
|
|
14
15
|
process.exit(1);
|
|
15
16
|
});
|
|
17
|
+
} else if (command === 'generate') {
|
|
18
|
+
runGenerate().catch((err) => {
|
|
19
|
+
console.error('\nError:', err.message);
|
|
20
|
+
process.exit(1);
|
|
21
|
+
});
|
|
16
22
|
} else {
|
|
17
23
|
main();
|
|
18
24
|
}
|
|
@@ -86,6 +92,65 @@ async function runReview() {
|
|
|
86
92
|
}
|
|
87
93
|
}
|
|
88
94
|
|
|
95
|
+
/**
|
|
96
|
+
* Run test generation command
|
|
97
|
+
* Usage: qai generate <url|file> [--out dir] [--framework playwright|jest|vitest] [--dry-run]
|
|
98
|
+
*/
|
|
99
|
+
async function runGenerate() {
|
|
100
|
+
const args = process.argv.slice(3);
|
|
101
|
+
const options = {};
|
|
102
|
+
|
|
103
|
+
for (let i = 0; i < args.length; i++) {
|
|
104
|
+
if (args[i] === '--out' && args[i + 1]) {
|
|
105
|
+
options.outDir = args[++i];
|
|
106
|
+
} else if (args[i] === '--framework' && args[i + 1]) {
|
|
107
|
+
options.framework = args[++i];
|
|
108
|
+
} else if (args[i] === '--pattern' && args[i + 1]) {
|
|
109
|
+
options.pattern = args[++i];
|
|
110
|
+
} else if (args[i] === '--dry-run') {
|
|
111
|
+
options.dryRun = true;
|
|
112
|
+
} else if (args[i] === '--json') {
|
|
113
|
+
options.json = true;
|
|
114
|
+
} else if (!args[i].startsWith('--')) {
|
|
115
|
+
options.target = args[i];
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (!options.target) {
|
|
120
|
+
console.error(
|
|
121
|
+
'Usage: qai generate <url|file> [--out dir] [--framework playwright|jest|vitest] [--dry-run]',
|
|
122
|
+
);
|
|
123
|
+
process.exit(1);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
console.log('='.repeat(60));
|
|
127
|
+
console.log('qai generate');
|
|
128
|
+
console.log('='.repeat(60));
|
|
129
|
+
console.log(`Target: ${options.target}`);
|
|
130
|
+
console.log(`Framework: ${options.framework || 'auto'}`);
|
|
131
|
+
console.log(
|
|
132
|
+
`Output: ${options.dryRun ? 'stdout (dry run)' : options.outDir || './tests/generated'}`,
|
|
133
|
+
);
|
|
134
|
+
console.log('='.repeat(60));
|
|
135
|
+
|
|
136
|
+
const startTime = Date.now();
|
|
137
|
+
const result = await generateTests(options);
|
|
138
|
+
const duration = ((Date.now() - startTime) / 1000).toFixed(1);
|
|
139
|
+
|
|
140
|
+
if (options.json) {
|
|
141
|
+
console.log(JSON.stringify(result, null, 2));
|
|
142
|
+
} else {
|
|
143
|
+
console.log('\n' + '='.repeat(60));
|
|
144
|
+
console.log('Generation Summary');
|
|
145
|
+
console.log('='.repeat(60));
|
|
146
|
+
console.log(`Mode: ${result.mode}`);
|
|
147
|
+
console.log(`Tests generated: ${result.testsGenerated}`);
|
|
148
|
+
console.log(`Files: ${result.files.join(', ')}`);
|
|
149
|
+
console.log(`Duration: ${duration}s`);
|
|
150
|
+
console.log('='.repeat(60));
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
89
154
|
async function main() {
|
|
90
155
|
const startTime = Date.now();
|
|
91
156
|
|
|
@@ -55,6 +55,19 @@ class AnthropicProvider extends BaseProvider {
|
|
|
55
55
|
return this.parseResponse(responseText);
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
+
async generateTests(prompt) {
|
|
59
|
+
const response = await this.client.messages.create({
|
|
60
|
+
model: this.model,
|
|
61
|
+
max_tokens: 8192,
|
|
62
|
+
messages: [{ role: 'user', content: prompt }],
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
return response.content
|
|
66
|
+
.filter((block) => block.type === 'text')
|
|
67
|
+
.map((block) => block.text)
|
|
68
|
+
.join('\n');
|
|
69
|
+
}
|
|
70
|
+
|
|
58
71
|
async reviewCode(diff, context, options = {}) {
|
|
59
72
|
const prompt = this.buildReviewPrompt(diff, context, options);
|
|
60
73
|
|
package/src/providers/base.js
CHANGED
|
@@ -30,6 +30,16 @@ class BaseProvider {
|
|
|
30
30
|
throw new Error('reviewCode() must be implemented by subclass');
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
+
/**
|
|
34
|
+
* Generate tests from a prompt
|
|
35
|
+
* @param {string} prompt - The generation prompt
|
|
36
|
+
* @returns {Promise<string>} Raw LLM response (JSON array of files)
|
|
37
|
+
*/
|
|
38
|
+
// eslint-disable-next-line no-unused-vars
|
|
39
|
+
async generateTests(prompt) {
|
|
40
|
+
throw new Error('generateTests() must be implemented by subclass');
|
|
41
|
+
}
|
|
42
|
+
|
|
33
43
|
/**
|
|
34
44
|
* Build the analysis prompt with focus-specific guidance
|
|
35
45
|
*/
|
package/src/providers/gemini.js
CHANGED
|
@@ -37,6 +37,13 @@ class GeminiProvider extends BaseProvider {
|
|
|
37
37
|
|
|
38
38
|
return this.parseResponse(responseText);
|
|
39
39
|
}
|
|
40
|
+
async generateTests(prompt) {
|
|
41
|
+
const model = this.genAI.getGenerativeModel({ model: this.model });
|
|
42
|
+
const result = await model.generateContent([{ text: prompt }]);
|
|
43
|
+
const response = await result.response;
|
|
44
|
+
return response.text();
|
|
45
|
+
}
|
|
46
|
+
|
|
40
47
|
async reviewCode(diff, context, options = {}) {
|
|
41
48
|
const prompt = this.buildReviewPrompt(diff, context, options);
|
|
42
49
|
const model = this.genAI.getGenerativeModel({ model: this.model });
|
package/src/providers/ollama.js
CHANGED
|
@@ -44,6 +44,26 @@ class OllamaProvider extends BaseProvider {
|
|
|
44
44
|
const data = await response.json();
|
|
45
45
|
return this.parseResponse(data.response || '');
|
|
46
46
|
}
|
|
47
|
+
async generateTests(prompt) {
|
|
48
|
+
const response = await fetch(`${this.baseUrl}/api/generate`, {
|
|
49
|
+
method: 'POST',
|
|
50
|
+
headers: { 'Content-Type': 'application/json' },
|
|
51
|
+
body: JSON.stringify({
|
|
52
|
+
model: this.model,
|
|
53
|
+
prompt,
|
|
54
|
+
stream: false,
|
|
55
|
+
options: { temperature: 0.1 },
|
|
56
|
+
}),
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
if (!response.ok) {
|
|
60
|
+
throw new Error(`Ollama request failed: ${response.status} ${response.statusText}`);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const data = await response.json();
|
|
64
|
+
return data.response || '';
|
|
65
|
+
}
|
|
66
|
+
|
|
47
67
|
async reviewCode(diff, context, options = {}) {
|
|
48
68
|
const prompt = this.buildReviewPrompt(diff, context, options);
|
|
49
69
|
|
package/src/providers/openai.js
CHANGED
|
@@ -49,6 +49,16 @@ class OpenAIProvider extends BaseProvider {
|
|
|
49
49
|
const responseText = response.choices[0]?.message?.content || '';
|
|
50
50
|
return this.parseResponse(responseText);
|
|
51
51
|
}
|
|
52
|
+
async generateTests(prompt) {
|
|
53
|
+
const response = await this.client.chat.completions.create({
|
|
54
|
+
model: this.model,
|
|
55
|
+
max_tokens: 8192,
|
|
56
|
+
messages: [{ role: 'user', content: prompt }],
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
return response.choices[0]?.message?.content || '';
|
|
60
|
+
}
|
|
61
|
+
|
|
52
62
|
async reviewCode(diff, context, options = {}) {
|
|
53
63
|
const prompt = this.buildReviewPrompt(diff, context, options);
|
|
54
64
|
|