Skip to content

Commit

Permalink
[WIP] feat: implement status report
Browse files Browse the repository at this point in the history
  • Loading branch information
puskuruk committed Jul 13, 2022
1 parent a6293df commit 1bbbede
Show file tree
Hide file tree
Showing 3 changed files with 131 additions and 11 deletions.
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@
}
},
"dependencies": {
"cli-table3": "^0.6.2",
"colors": "^1.4.0",
"yargs": "17.5.1"
}
}
84 changes: 81 additions & 3 deletions src/CLIUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,13 @@

import { parse, createRunner } from '../lib/main.js';
import { readFileSync, readdirSync, lstatSync } from 'fs';
import { join, isAbsolute, extname } from 'path';
import { join, isAbsolute, extname, relative } from 'path';
import { pathToFileURL } from 'url';
import { cwd } from 'process';
import { PuppeteerRunnerOwningBrowserExtension } from '../lib/main.js';
import { Browser } from 'puppeteer';
import Table from 'cli-table3';
import colors from 'colors';

export function getJSONFilesFromFolder(path: string): string[] {
return readdirSync(path)
Expand Down Expand Up @@ -75,13 +77,67 @@ export function getHeadlessEnvVar(headless?: string) {
}
}

type Result = {
startedAt: Date;
file: string;
finishedAt: Date;
passed: boolean;
title: string;
};

export function createStatusReport(results: Result[]): Table.Table {
const table = new Table({
head: ['Title', 'Status', 'File', 'Duration'],
chars: {
top: '═',
'top-mid': '╤',
'top-left': '╔',
'top-right': '╗',
bottom: '═',
'bottom-mid': '╧',
'bottom-left': '╚',
'bottom-right': '╝',
left: '║',
'left-mid': '╟',
mid: '─',
'mid-mid': '┼',
right: '║',
'right-mid': '╢',
middle: '│',
},
style: {
head: ['bold'],
},
});

const resultTextColor = colors.white;
for (const result of results) {
const row: string[] = [];

const duration =
result.finishedAt?.getTime()! - result.startedAt.getTime() || 0;
const status = result.passed
? resultTextColor.bgGreen(' Passed ')
: resultTextColor.bgRed(' Failed ');

row.push(result.title);
row.push(status);
row.push(relative(process.cwd(), result.file));
row.push(`${duration}ms`);

table.push(row);
}

return table;
}

export async function runFiles(
files: string[],
opts: { log: boolean; headless: boolean | 'chrome'; extension?: string } = {
log: false,
headless: true,
}
): Promise<void> {
): Promise<boolean> {
let Extension = PuppeteerRunnerOwningBrowserExtension;
let browser: Browser | undefined;

Expand All @@ -95,12 +151,24 @@ export async function runFiles(
);
Extension = module.default;
}

const results: Result[] = [];
for (const file of files) {
const result: Result = {
title: '',
startedAt: new Date(),
finishedAt: new Date(),
file,
passed: true,
};

opts.log && console.log(`Running ${file}...`);
try {
const content = readFileSync(file, 'utf-8');
const object = JSON.parse(content);
const recording = parse(object);
result['title'] = recording.title;

const { default: puppeteer } = await import('puppeteer');
browser = await puppeteer.launch({
headless: opts.headless,
Expand All @@ -112,9 +180,19 @@ export async function runFiles(
opts.log && console.log(`Finished running ${file}`);
} catch (err) {
opts.log && console.error(`Error running ${file}`, err);
throw err;
result['passed'] = false;
} finally {
result['finishedAt'] = new Date();
results.push(result);

await browser?.close();
}
}

if (opts.log) {
const statusReport = createStatusReport(results);
console.log(statusReport.toString());
}

return results.every((result) => result.passed);
}
56 changes: 48 additions & 8 deletions test/cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/

import {
createStatusReport,
runFiles,
getHeadlessEnvVar,
getRecordingPaths,
Expand All @@ -23,6 +24,8 @@ import {
import { assert } from 'chai';
import path from 'path';
import url from 'url';
import { HorizontalTableRow } from 'cli-table3';
import colors from 'colors';

const __dirname = path.dirname(url.fileURLToPath(import.meta.url));

Expand All @@ -34,14 +37,11 @@ enum Status {
async function getStatus(
asyncFn: () => Promise<unknown>
): Promise<typeof Status['Success'] | typeof Status['Error']> {
let error = undefined;
try {
await asyncFn();
} catch (err) {
error = err;
}

return error ? Status.Error : Status.Success;
const result = await asyncFn();

if (!result) return Status.Error;

return Status.Success;
}

describe('cli', () => {
Expand Down Expand Up @@ -114,4 +114,44 @@ describe('cli', () => {
assert.isTrue(files.every((file) => file.endsWith('.json')));
});
});

describe('createStatusReport', () => {
it('is able to create a successful status report', () => {
const date = new Date();
const result = {
startedAt: date,
file: path.join(__dirname, 'resources', 'replay-fail.json'),
finishedAt: new Date(date.getTime() + 1000),
passed: true,
title: 'Test run',
};
const [statusReport] = createStatusReport([result]);
const [title, status, file, duration] =
statusReport as HorizontalTableRow;

assert.strictEqual(status, colors.white.bgGreen(' Passed '));
assert.strictEqual(duration, '1000ms');
assert.isString(file);
assert.strictEqual(title, result.title);
});

it('is able to create a failed status report', () => {
const date = new Date();
const result = {
startedAt: date,
file: path.join(__dirname, 'resources', 'replay-fail.json'),
finishedAt: date,
passed: false,
title: 'Test run',
};
const [statusReport] = createStatusReport([result]);
const [title, status, file, duration] =
statusReport as HorizontalTableRow;

assert.strictEqual(status, colors.white.bgRed(' Failed '));
assert.strictEqual(duration, '0ms');
assert.isString(file);
assert.strictEqual(title, result.title);
});
});
});

0 comments on commit 1bbbede

Please sign in to comment.