ortoni-report 4.0.2-beta.1 → 4.0.2

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.
@@ -1,637 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
- }) : x)(function(x) {
6
- if (typeof require !== "undefined") return require.apply(this, arguments);
7
- throw Error('Dynamic require of "' + x + '" is not supported');
8
- });
9
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
10
-
11
- // src/helpers/fileManager.ts
12
- import fs from "fs";
13
- import path from "path";
14
- var FileManager = class {
15
- constructor(folderPath) {
16
- this.folderPath = folderPath;
17
- }
18
- ensureReportDirectory() {
19
- const ortoniDataFolder = path.join(this.folderPath, "ortoni-data");
20
- if (!fs.existsSync(this.folderPath)) {
21
- fs.mkdirSync(this.folderPath, { recursive: true });
22
- } else {
23
- if (fs.existsSync(ortoniDataFolder)) {
24
- fs.rmSync(ortoniDataFolder, { recursive: true, force: true });
25
- }
26
- }
27
- }
28
- writeReportFile(filename, data) {
29
- const templatePath = path.join(__dirname, "..", "index.html");
30
- console.log(templatePath);
31
- let html = fs.readFileSync(templatePath, "utf-8");
32
- const reportJSON = JSON.stringify({
33
- data
34
- });
35
- html = html.replace("__ORTONI_TEST_REPORTDATA__", reportJSON);
36
- const outputDir = path.isAbsolute(this.folderPath) ? this.folderPath : path.join(process.cwd(), this.folderPath);
37
- if (!fs.existsSync(outputDir)) {
38
- fs.mkdirSync(outputDir, { recursive: true });
39
- }
40
- const outputPath = path.join(outputDir, filename);
41
- fs.writeFileSync(outputPath, html);
42
- return outputPath;
43
- }
44
- writeRawFile(filename, data) {
45
- const outputPath = path.join(process.cwd(), this.folderPath, filename);
46
- fs.mkdirSync(path.dirname(outputPath), { recursive: true });
47
- const content = typeof data === "string" ? data : JSON.stringify(data, null, 2);
48
- fs.writeFileSync(outputPath, content, "utf-8");
49
- return outputPath;
50
- }
51
- copyTraceViewerAssets(skip) {
52
- if (skip) return;
53
- const traceViewerFolder = path.join(
54
- __require.resolve("playwright-core"),
55
- "..",
56
- "lib",
57
- "vite",
58
- "traceViewer"
59
- );
60
- const traceViewerTargetFolder = path.join(this.folderPath, "trace");
61
- const traceViewerAssetsTargetFolder = path.join(
62
- traceViewerTargetFolder,
63
- "assets"
64
- );
65
- fs.mkdirSync(traceViewerAssetsTargetFolder, { recursive: true });
66
- for (const file of fs.readdirSync(traceViewerFolder)) {
67
- if (file.endsWith(".map") || file.includes("watch") || file.includes("assets"))
68
- continue;
69
- fs.copyFileSync(
70
- path.join(traceViewerFolder, file),
71
- path.join(traceViewerTargetFolder, file)
72
- );
73
- }
74
- const assetsFolder = path.join(traceViewerFolder, "assets");
75
- for (const file of fs.readdirSync(assetsFolder)) {
76
- if (file.endsWith(".map") || file.includes("xtermModule")) continue;
77
- fs.copyFileSync(
78
- path.join(assetsFolder, file),
79
- path.join(traceViewerAssetsTargetFolder, file)
80
- );
81
- }
82
- }
83
- };
84
-
85
- // src/utils/groupProjects.ts
86
- function groupResults(config, results) {
87
- if (config.showProject) {
88
- const groupedResults = results.reduce((acc, result, index) => {
89
- const testId = `${result.filePath}:${result.projectName}:${result.title}`;
90
- const key = `${testId}-${result.key}-${result.retryAttemptCount}`;
91
- const { filePath, suite, projectName } = result;
92
- acc[filePath] = acc[filePath] || {};
93
- acc[filePath][suite] = acc[filePath][suite] || {};
94
- acc[filePath][suite][projectName] = acc[filePath][suite][projectName] || [];
95
- acc[filePath][suite][projectName].push({ ...result, index, testId, key });
96
- return acc;
97
- }, {});
98
- return groupedResults;
99
- } else {
100
- const groupedResults = results.reduce((acc, result, index) => {
101
- const testId = `${result.filePath}:${result.projectName}:${result.title}`;
102
- const key = `${testId}-${result.key}-${result.retryAttemptCount}`;
103
- const { filePath, suite } = result;
104
- acc[filePath] = acc[filePath] || {};
105
- acc[filePath][suite] = acc[filePath][suite] || [];
106
- acc[filePath][suite].push({ ...result, index, testId, key });
107
- return acc;
108
- }, {});
109
- return groupedResults;
110
- }
111
- }
112
-
113
- // src/helpers/HTMLGenerator.ts
114
- var HTMLGenerator = class {
115
- constructor(ortoniConfig, dbManager) {
116
- this.ortoniConfig = ortoniConfig;
117
- this.dbManager = dbManager;
118
- }
119
- async generateFinalReport(filteredResults, totalDuration, results, projectSet) {
120
- const data = await this.prepareReportData(
121
- filteredResults,
122
- totalDuration,
123
- results,
124
- projectSet
125
- );
126
- return data;
127
- }
128
- async getReportData() {
129
- return {
130
- summary: await this.dbManager.getSummaryData(),
131
- trends: await this.dbManager.getTrends(),
132
- flakyTests: await this.dbManager.getFlakyTests(),
133
- slowTests: await this.dbManager.getSlowTests()
134
- };
135
- }
136
- async prepareReportData(filteredResults, totalDuration, results, projectSet) {
137
- const totalTests = filteredResults.length;
138
- const passedTests = results.filter((r) => r.status === "passed").length;
139
- const flakyTests = results.filter((r) => r.status === "flaky").length;
140
- const failed = filteredResults.filter(
141
- (r) => r.status === "failed" || r.status === "timedOut"
142
- ).length;
143
- const successRate = ((passedTests + flakyTests) / totalTests * 100).toFixed(2);
144
- const allTags = /* @__PURE__ */ new Set();
145
- results.forEach(
146
- (result) => result.testTags.forEach((tag) => allTags.add(tag))
147
- );
148
- const projectResults = this.calculateProjectResults(
149
- filteredResults,
150
- results,
151
- projectSet
152
- );
153
- const lastRunDate = (/* @__PURE__ */ new Date()).toLocaleString();
154
- const testHistories = await Promise.all(
155
- results.map(async (result) => {
156
- const testId = `${result.filePath}:${result.projectName}:${result.title}`;
157
- const history = await this.dbManager.getTestHistory(testId);
158
- return {
159
- testId,
160
- history
161
- };
162
- })
163
- );
164
- return {
165
- summary: {
166
- overAllResult: {
167
- pass: passedTests,
168
- fail: failed,
169
- skip: results.filter((r) => r.status === "skipped").length,
170
- retry: results.filter((r) => r.retryAttemptCount).length,
171
- flaky: flakyTests,
172
- total: filteredResults.length
173
- },
174
- successRate,
175
- lastRunDate,
176
- totalDuration,
177
- stats: this.extractProjectStats(projectResults)
178
- },
179
- testResult: {
180
- tests: groupResults(this.ortoniConfig, results),
181
- testHistories,
182
- allTags: Array.from(allTags),
183
- set: projectSet
184
- },
185
- userConfig: {
186
- projectName: this.ortoniConfig.projectName,
187
- authorName: this.ortoniConfig.authorName,
188
- type: this.ortoniConfig.testType,
189
- title: this.ortoniConfig.title
190
- },
191
- userMeta: {
192
- meta: this.ortoniConfig.meta
193
- },
194
- preferences: {
195
- logo: this.ortoniConfig.logo || void 0,
196
- showProject: this.ortoniConfig.showProject || false
197
- },
198
- analytics: {
199
- reportData: await this.getReportData()
200
- }
201
- };
202
- }
203
- calculateProjectResults(filteredResults, results, projectSet) {
204
- return Array.from(projectSet).map((projectName) => {
205
- const projectTests = filteredResults.filter(
206
- (r) => r.projectName === projectName
207
- );
208
- const allProjectTests = results.filter(
209
- (r) => r.projectName === projectName
210
- );
211
- return {
212
- projectName,
213
- passedTests: projectTests.filter((r) => r.status === "passed").length,
214
- failedTests: projectTests.filter(
215
- (r) => r.status === "failed" || r.status === "timedOut"
216
- ).length,
217
- skippedTests: allProjectTests.filter((r) => r.status === "skipped").length,
218
- retryTests: allProjectTests.filter((r) => r.retryAttemptCount).length,
219
- flakyTests: allProjectTests.filter((r) => r.status === "flaky").length,
220
- totalTests: projectTests.length
221
- };
222
- });
223
- }
224
- extractProjectStats(projectResults) {
225
- return {
226
- projectNames: projectResults.map((result) => result.projectName),
227
- totalTests: projectResults.map((result) => result.totalTests),
228
- passedTests: projectResults.map((result) => result.passedTests),
229
- failedTests: projectResults.map((result) => result.failedTests),
230
- skippedTests: projectResults.map((result) => result.skippedTests),
231
- retryTests: projectResults.map((result) => result.retryTests),
232
- flakyTests: projectResults.map((result) => result.flakyTests)
233
- };
234
- }
235
- };
236
-
237
- // src/utils/utils.ts
238
- import path2 from "path";
239
- function normalizeFilePath(filePath) {
240
- const normalizedPath = path2.normalize(filePath);
241
- return path2.basename(normalizedPath);
242
- }
243
- function ensureHtmlExtension(filename) {
244
- const ext = path2.extname(filename);
245
- if (ext && ext.toLowerCase() === ".html") {
246
- return filename;
247
- }
248
- return `${filename}.html`;
249
- }
250
- function escapeHtml(unsafe) {
251
- if (typeof unsafe !== "string") {
252
- return String(unsafe);
253
- }
254
- return unsafe.replace(/[&<"']/g, function(match) {
255
- const escapeMap = {
256
- "&": "&amp;",
257
- "<": "&lt;",
258
- ">": "&gt;",
259
- '"': "&quot;",
260
- "'": "&#039;"
261
- };
262
- return escapeMap[match] || match;
263
- });
264
- }
265
- function formatDateLocal(dateInput) {
266
- const date = typeof dateInput === "string" ? new Date(dateInput) : dateInput;
267
- const options = {
268
- year: "numeric",
269
- month: "short",
270
- day: "2-digit",
271
- hour: "2-digit",
272
- minute: "2-digit",
273
- hour12: true,
274
- timeZoneName: "short"
275
- // or "Asia/Kolkata"
276
- };
277
- return new Intl.DateTimeFormat(void 0, options).format(date);
278
- }
279
- function extractSuites(titlePath) {
280
- const tagPattern = /@[\w]+/g;
281
- const suiteParts = titlePath.slice(3, titlePath.length - 1).map((p) => p.replace(tagPattern, "").trim());
282
- return {
283
- hierarchy: suiteParts.join(" > "),
284
- // full hierarchy
285
- topLevelSuite: suiteParts[0] ?? "",
286
- // first suite
287
- parentSuite: suiteParts[suiteParts.length - 1] ?? ""
288
- // last suite
289
- };
290
- }
291
-
292
- // src/utils/expressServer.ts
293
- import express from "express";
294
- import path3 from "path";
295
- import { spawn } from "child_process";
296
- function startReportServer(reportFolder, reportFilename, port = 2004, open2) {
297
- const app = express();
298
- app.use(express.static(reportFolder));
299
- app.get("/", (_req, res) => {
300
- try {
301
- res.sendFile(path3.resolve(reportFolder, reportFilename));
302
- } catch (error) {
303
- console.error("Ortoni-Report: Error sending report file:", error);
304
- res.status(500).send("Error loading report");
305
- }
306
- });
307
- try {
308
- const server = app.listen(port, () => {
309
- console.log(
310
- `Server is running at http://localhost:${port}
311
- Press Ctrl+C to stop.`
312
- );
313
- if (open2 === "always" || open2 === "on-failure") {
314
- try {
315
- openBrowser(`http://localhost:${port}`);
316
- } catch (error) {
317
- console.error("Ortoni-Report: Error opening browser:", error);
318
- }
319
- }
320
- });
321
- server.on("error", (error) => {
322
- if (error.code === "EADDRINUSE") {
323
- console.error(
324
- `Ortoni-Report: Port ${port} is already in use. Trying a different port...`
325
- );
326
- } else {
327
- console.error("Ortoni-Report: Server error:", error);
328
- }
329
- });
330
- } catch (error) {
331
- console.error("Ortoni-Report: Error starting the server:", error);
332
- }
333
- }
334
- function openBrowser(url) {
335
- const platform = process.platform;
336
- let command;
337
- try {
338
- if (platform === "win32") {
339
- command = "cmd";
340
- spawn(command, ["/c", "start", url]);
341
- } else if (platform === "darwin") {
342
- command = "open";
343
- spawn(command, [url]);
344
- } else {
345
- command = "xdg-open";
346
- spawn(command, [url]);
347
- }
348
- } catch (error) {
349
- console.error("Ortoni-Report: Error opening the browser:", error);
350
- }
351
- }
352
-
353
- // src/helpers/databaseManager.ts
354
- import { open } from "sqlite";
355
- import sqlite3 from "sqlite3";
356
- var DatabaseManager = class {
357
- constructor() {
358
- this.db = null;
359
- }
360
- async initialize(dbPath) {
361
- try {
362
- this.db = await open({
363
- filename: dbPath,
364
- driver: sqlite3.Database
365
- });
366
- await this.createTables();
367
- await this.createIndexes();
368
- } catch (error) {
369
- console.error("OrtoniReport: Error initializing database:", error);
370
- }
371
- }
372
- async createTables() {
373
- if (!this.db) {
374
- console.error("OrtoniReport: Database not initialized");
375
- return;
376
- }
377
- try {
378
- await this.db.exec(`
379
- CREATE TABLE IF NOT EXISTS test_runs (
380
- id INTEGER PRIMARY KEY AUTOINCREMENT,
381
- run_date TEXT
382
- );
383
-
384
- CREATE TABLE IF NOT EXISTS test_results (
385
- id INTEGER PRIMARY KEY AUTOINCREMENT,
386
- run_id INTEGER,
387
- test_id TEXT,
388
- status TEXT,
389
- duration INTEGER, -- store duration as raw ms
390
- error_message TEXT,
391
- FOREIGN KEY (run_id) REFERENCES test_runs (id)
392
- );
393
- `);
394
- } catch (error) {
395
- console.error("OrtoniReport: Error creating tables:", error);
396
- }
397
- }
398
- async createIndexes() {
399
- if (!this.db) {
400
- console.error("OrtoniReport: Database not initialized");
401
- return;
402
- }
403
- try {
404
- await this.db.exec(`
405
- CREATE INDEX IF NOT EXISTS idx_test_id ON test_results (test_id);
406
- CREATE INDEX IF NOT EXISTS idx_run_id ON test_results (run_id);
407
- `);
408
- } catch (error) {
409
- console.error("OrtoniReport: Error creating indexes:", error);
410
- }
411
- }
412
- async saveTestRun() {
413
- if (!this.db) {
414
- console.error("OrtoniReport: Database not initialized");
415
- return null;
416
- }
417
- try {
418
- const runDate = (/* @__PURE__ */ new Date()).toISOString();
419
- const { lastID } = await this.db.run(
420
- `
421
- INSERT INTO test_runs (run_date)
422
- VALUES (?)
423
- `,
424
- [runDate]
425
- );
426
- return lastID;
427
- } catch (error) {
428
- console.error("OrtoniReport: Error saving test run:", error);
429
- return null;
430
- }
431
- }
432
- async saveTestResults(runId, results) {
433
- if (!this.db) {
434
- console.error("OrtoniReport: Database not initialized");
435
- return;
436
- }
437
- try {
438
- await this.db.exec("BEGIN TRANSACTION;");
439
- const stmt = await this.db.prepare(`
440
- INSERT INTO test_results (run_id, test_id, status, duration, error_message)
441
- VALUES (?, ?, ?, ?, ?)
442
- `);
443
- for (const result of results) {
444
- await stmt.run([
445
- runId,
446
- `${result.filePath}:${result.projectName}:${result.title}`,
447
- result.status,
448
- result.duration,
449
- // store raw ms
450
- result.errors.join("\n")
451
- ]);
452
- }
453
- await stmt.finalize();
454
- await this.db.exec("COMMIT;");
455
- } catch (error) {
456
- await this.db.exec("ROLLBACK;");
457
- console.error("OrtoniReport: Error saving test results:", error);
458
- }
459
- }
460
- async getTestHistory(testId, limit = 10) {
461
- if (!this.db) {
462
- console.error("OrtoniReport: Database not initialized");
463
- return [];
464
- }
465
- try {
466
- const results = await this.db.all(
467
- `
468
- SELECT tr.status, tr.duration, tr.error_message, trun.run_date
469
- FROM test_results tr
470
- JOIN test_runs trun ON tr.run_id = trun.id
471
- WHERE tr.test_id = ?
472
- ORDER BY trun.run_date DESC
473
- LIMIT ?
474
- `,
475
- [testId, limit]
476
- );
477
- return results.map((result) => ({
478
- ...result,
479
- run_date: formatDateLocal(result.run_date)
480
- }));
481
- } catch (error) {
482
- console.error("OrtoniReport: Error getting test history:", error);
483
- return [];
484
- }
485
- }
486
- async close() {
487
- if (this.db) {
488
- try {
489
- await this.db.close();
490
- } catch (error) {
491
- console.error("OrtoniReport: Error closing database:", error);
492
- } finally {
493
- this.db = null;
494
- }
495
- }
496
- }
497
- async getSummaryData() {
498
- if (!this.db) {
499
- console.error("OrtoniReport: Database not initialized");
500
- return {
501
- totalRuns: 0,
502
- totalTests: 0,
503
- passed: 0,
504
- failed: 0,
505
- passRate: 0,
506
- avgDuration: 0
507
- };
508
- }
509
- try {
510
- const summary = await this.db.get(`
511
- SELECT
512
- (SELECT COUNT(*) FROM test_runs) as totalRuns,
513
- (SELECT COUNT(*) FROM test_results) as totalTests,
514
- (SELECT COUNT(*) FROM test_results WHERE status = 'passed') as passed,
515
- (SELECT COUNT(*) FROM test_results WHERE status = 'failed') as failed,
516
- (SELECT AVG(duration) FROM test_results) as avgDuration
517
- `);
518
- const passRate = summary.totalTests ? (summary.passed / summary.totalTests * 100).toFixed(2) : 0;
519
- return {
520
- totalRuns: summary.totalRuns,
521
- totalTests: summary.totalTests,
522
- passed: summary.passed,
523
- failed: summary.failed,
524
- passRate: parseFloat(passRate.toString()),
525
- avgDuration: Math.round(summary.avgDuration || 0)
526
- // raw ms avg
527
- };
528
- } catch (error) {
529
- console.error("OrtoniReport: Error getting summary data:", error);
530
- return {
531
- totalRuns: 0,
532
- totalTests: 0,
533
- passed: 0,
534
- failed: 0,
535
- passRate: 0,
536
- avgDuration: 0
537
- };
538
- }
539
- }
540
- async getTrends(limit = 100) {
541
- if (!this.db) {
542
- console.error("OrtoniReport: Database not initialized");
543
- return [];
544
- }
545
- try {
546
- const rows = await this.db.all(
547
- `
548
- SELECT trun.run_date,
549
- SUM(CASE WHEN tr.status = 'passed' THEN 1 ELSE 0 END) AS passed,
550
- SUM(CASE WHEN tr.status = 'failed' THEN 1 ELSE 0 END) AS failed,
551
- AVG(tr.duration) AS avg_duration
552
- FROM test_results tr
553
- JOIN test_runs trun ON tr.run_id = trun.id
554
- GROUP BY trun.run_date
555
- ORDER BY trun.run_date DESC
556
- LIMIT ?
557
- `,
558
- [limit]
559
- );
560
- return rows.reverse().map((row) => ({
561
- ...row,
562
- run_date: formatDateLocal(row.run_date),
563
- avg_duration: Math.round(row.avg_duration || 0)
564
- // raw ms avg
565
- }));
566
- } catch (error) {
567
- console.error("OrtoniReport: Error getting trends data:", error);
568
- return [];
569
- }
570
- }
571
- async getFlakyTests(limit = 10) {
572
- if (!this.db) {
573
- console.error("OrtoniReport: Database not initialized");
574
- return [];
575
- }
576
- try {
577
- return await this.db.all(
578
- `
579
- SELECT
580
- test_id,
581
- COUNT(*) AS total,
582
- SUM(CASE WHEN status = 'flaky' THEN 1 ELSE 0 END) AS flaky,
583
- AVG(duration) AS avg_duration
584
- FROM test_results
585
- GROUP BY test_id
586
- HAVING flaky > 0
587
- ORDER BY flaky DESC
588
- LIMIT ?
589
- `,
590
- [limit]
591
- );
592
- } catch (error) {
593
- console.error("OrtoniReport: Error getting flaky tests:", error);
594
- return [];
595
- }
596
- }
597
- async getSlowTests(limit = 10) {
598
- if (!this.db) {
599
- console.error("OrtoniReport: Database not initialized");
600
- return [];
601
- }
602
- try {
603
- const rows = await this.db.all(
604
- `
605
- SELECT
606
- test_id,
607
- AVG(duration) AS avg_duration
608
- FROM test_results
609
- GROUP BY test_id
610
- ORDER BY avg_duration DESC
611
- LIMIT ?
612
- `,
613
- [limit]
614
- );
615
- return rows.map((row) => ({
616
- test_id: row.test_id,
617
- avg_duration: Math.round(row.avg_duration || 0)
618
- // raw ms avg
619
- }));
620
- } catch (error) {
621
- console.error("OrtoniReport: Error getting slow tests:", error);
622
- return [];
623
- }
624
- }
625
- };
626
-
627
- export {
628
- __publicField,
629
- FileManager,
630
- HTMLGenerator,
631
- normalizeFilePath,
632
- ensureHtmlExtension,
633
- escapeHtml,
634
- extractSuites,
635
- startReportServer,
636
- DatabaseManager
637
- };