Skip to content

Commit bedadd4

Browse files
committed
refactor(utils): replace console.log with info, warn and error, add mock setup
1 parent 2698c51 commit bedadd4

12 files changed

Lines changed: 49 additions & 83 deletions

packages/utils/perf/index.ts

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -53,12 +53,12 @@ const NUM_GROUPS_P2 = PROCESS_ARGUMENT_NUM_GROUPS_P2 || NUM_AUDITS_P2 / 2;
5353
// Add listener
5454
const listeners = {
5555
cycle: function (event: Benchmark.Event) {
56-
console.log(String(event.target));
56+
console.info(String(event.target));
5757
},
5858
complete: () => {
5959
if (typeof suite.filter === 'function') {
60-
console.log(' ');
61-
console.log('Fastest is ' + suite.filter('fastest').map('name'));
60+
console.info(' ');
61+
console.info('Fastest is ' + suite.filter('fastest').map('name'));
6262
}
6363
},
6464
};
@@ -91,15 +91,15 @@ console.info(
9191
console.info(
9292
`numGroupRefs2 Number of groups refs in plugin 2. --numGroupRefs2=${NUM_GROUPS_P2}`,
9393
);
94-
console.log(' ');
95-
console.log('Start benchmark...');
96-
console.log(' ');
94+
console.info(' ');
95+
console.info('Start benchmark...');
96+
console.info(' ');
9797

9898
const start = performance.now();
9999

100100
suite.run();
101101

102-
console.log(
102+
console.info(
103103
`Total Duration: ${((performance.now() - start) / 1000).toFixed(2)} sec`,
104104
);
105105

packages/utils/src/lib/execute-process.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ export type ProcessConfig = {
9494
*
9595
* @example
9696
* const observer = {
97-
* onStdout: (stdout) => console.log(stdout)
97+
* onStdout: (stdout) => console.info(stdout)
9898
* }
9999
*/
100100
export type ProcessObserver = {
@@ -114,7 +114,7 @@ export type ProcessObserver = {
114114
* args: ['--version']
115115
* });
116116
*
117-
* console.log(result);
117+
* console.info(result);
118118
*
119119
* // async process execution
120120
* const result = await executeProcess({
@@ -127,7 +127,7 @@ export type ProcessObserver = {
127127
* }
128128
* });
129129
*
130-
* console.log(result);
130+
* console.info(result);
131131
*
132132
* @param cfg - see {@link ProcessConfig}
133133
*/

packages/utils/src/lib/file-system.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ export async function ensureDirectoryExists(baseDir: string) {
2222
await mkdir(baseDir, { recursive: true });
2323
return;
2424
} catch (error) {
25-
console.log((error as { code: string; message: string }).message);
25+
console.error((error as { code: string; message: string }).message);
2626
if ((error as { code: string }).code !== 'EEXIST') {
2727
throw error;
2828
}
@@ -48,13 +48,13 @@ export function logMultipleFileResults(
4848
): void {
4949
const succeededCallback = (result: PromiseFulfilledResult<FileResult>) => {
5050
const [fileName, size] = result.value;
51-
console.log(
51+
console.info(
5252
`- ${chalk.bold(fileName)}` +
5353
(size ? ` (${chalk.gray(formatBytes(size))})` : ''),
5454
);
5555
};
5656
const failedCallback = (result: PromiseRejectedResult) => {
57-
console.log(`- ${chalk.bold(result.reason)}`);
57+
console.warn(`- ${chalk.bold(result.reason)}`);
5858
};
5959

6060
logMultipleResults<FileResult>(

packages/utils/src/lib/log-results.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,12 @@ export function logPromiseResults<
3434
T extends PromiseFulfilledResult<unknown> | PromiseRejectedResult,
3535
>(results: T[], logMessage: string, callback: (result: T) => void): void {
3636
if (results.length) {
37-
console.log(logMessage);
37+
if (results[0]?.status === 'fulfilled') {
38+
console.info(logMessage);
39+
} else {
40+
console.warn(logMessage);
41+
}
42+
3843
results.forEach(callback);
3944
}
4045
}

packages/utils/src/lib/log-results.unit.test.ts

Lines changed: 14 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,19 @@
11
import chalk from 'chalk';
22
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
3-
import { mockConsole, unmockConsole } from '../../test';
43
import { FileResult } from './file-system';
54
import { logMultipleResults, logPromiseResults } from './log-results';
65
import { formatBytes } from './report';
76

87
const succeededCallback = (result: PromiseFulfilledResult<FileResult>) => {
98
const [fileName, size] = result.value;
10-
console.log(
9+
console.info(
1110
`- ${chalk.bold(fileName)}` +
1211
(size ? ` (${chalk.gray(formatBytes(size))})` : ''),
1312
);
1413
};
1514

1615
const failedCallback = (result: PromiseRejectedResult) => {
17-
console.log(`- ${chalk.bold(result.reason)}`);
16+
console.warn(`- ${chalk.bold(result.reason)}`);
1817
};
1918

2019
describe('logMultipleResults', () => {
@@ -79,25 +78,6 @@ describe('logMultipleResults', () => {
7978
});
8079

8180
describe('logPromiseResults', () => {
82-
let logs: string[];
83-
const setupConsole = async () => {
84-
logs = [];
85-
mockConsole(msg => logs.push(msg));
86-
};
87-
const teardownConsole = async () => {
88-
logs = [];
89-
unmockConsole();
90-
};
91-
92-
beforeEach(async () => {
93-
logs = [];
94-
setupConsole();
95-
});
96-
97-
afterEach(() => {
98-
teardownConsole();
99-
});
100-
10181
it('should log on success', async () => {
10282
logPromiseResults(
10383
[
@@ -110,9 +90,12 @@ describe('logPromiseResults', () => {
11090
succeededCallback,
11191
);
11292

113-
expect(logs).toHaveLength(2);
114-
expect(logs[0]).toContain('Uploaded reports successfully: ');
115-
expect(logs[1]).toContain('- out.json');
93+
expect(console.info).toHaveBeenCalledWith(
94+
expect.stringContaining('Uploaded reports successfully: '),
95+
);
96+
expect(console.info).toHaveBeenCalledWith(
97+
expect.stringContaining('- out.json'),
98+
);
11699
});
117100

118101
it('should log on fail', async () => {
@@ -122,8 +105,11 @@ describe('logPromiseResults', () => {
122105
failedCallback,
123106
);
124107

125-
expect(logs).toHaveLength(2);
126-
expect(logs[0]).toContain('Generated reports failed: ');
127-
expect(logs[1]).toContain('- fail');
108+
expect(console.warn).toHaveBeenCalledWith(
109+
expect.stringContaining('Generated reports failed: '),
110+
);
111+
expect(console.warn).toHaveBeenCalledWith(
112+
expect.stringContaining('- fail'),
113+
);
128114
});
129115
});

packages/utils/src/lib/verbose-utils.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
function getLogVerbose(verbose: boolean) {
22
return (...args: unknown[]) => {
33
if (verbose) {
4-
console.log(...args);
4+
console.info(...args);
55
}
66
};
77
}
Lines changed: 5 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,31 @@
1-
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
2-
import { mockConsole, unmockConsole } from '../../test';
1+
import { describe, expect, it } from 'vitest';
32
import { verboseUtils } from './verbose-utils';
43

54
const verboseHelper = verboseUtils(true);
65
const noVerboseHelper = verboseUtils(false);
7-
let logs: string[];
86

97
describe('verbose-utils', () => {
10-
beforeEach(() => {
11-
logs = [];
12-
mockConsole(args => logs.push(args));
13-
});
14-
afterEach(() => {
15-
unmockConsole();
16-
});
17-
188
it('exec should work verbose', () => {
199
const spy = vi.fn();
2010
verboseHelper.exec(spy);
2111
expect(spy).toHaveBeenCalled();
22-
expect(logs).toHaveLength(0);
12+
expect(console.info).not.toHaveBeenCalled();
2313
});
2414

2515
it('exec should work no-verbose', () => {
2616
const spy = vi.fn();
2717
noVerboseHelper.exec(spy);
2818
expect(spy).not.toHaveBeenCalled();
29-
expect(logs).toHaveLength(0);
19+
expect(console.info).not.toHaveBeenCalled();
3020
});
3121

3222
it('log should work verbose', () => {
3323
verboseHelper.log('42');
34-
expect(logs).toHaveLength(1);
35-
expect(logs[0]).toBe('42');
24+
expect(console.info).toHaveBeenCalledWith('42');
3625
});
3726

3827
it('log should work no-verbose', () => {
3928
noVerboseHelper.log('42');
40-
expect(logs).toHaveLength(0);
29+
expect(console.info).not.toHaveBeenCalled();
4130
});
4231
});

packages/utils/test/console.mock.ts

Lines changed: 0 additions & 17 deletions
This file was deleted.

packages/utils/test/fixtures/execute-process.mock.mjs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ let outputFile = process.argv[5] || './tmp/out-async-runner.json';
1616
* @arg throwError: '1' | '0' - if the process completes or throws; defaults to '0'
1717
**/
1818
(async () => {
19-
console.log(
19+
console.info(
2020
`process:start with interval: ${interval}, runs: ${runs}, throwError: ${throwError}, outputFile: ${outputFile}`,
2121
);
2222
await new Promise(resolve => {
@@ -30,11 +30,11 @@ let outputFile = process.argv[5] || './tmp/out-async-runner.json';
3030
}
3131
} else {
3232
runs--;
33-
console.log('process:update');
33+
console.info('process:update');
3434
}
3535
}, interval);
3636
});
3737

38-
console.log('process:complete');
38+
console.info('process:complete');
3939
writeFileSync(outputFile, JSON.stringify({ audits: ['dummy-result'] }));
4040
})();

packages/utils/test/fixtures/execute-progress.mock.mjs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ const verbose = Boolean(_arg('verbose', false));
2626
**/
2727
(async () => {
2828
verbose &&
29-
console.log(
29+
console.info(
3030
chalk.gray(
3131
`Start progress with duration: ${chalk.bold(
3232
duration,
@@ -39,7 +39,7 @@ const verbose = Boolean(_arg('verbose', false));
3939
const id = setInterval(() => {
4040
if (i < steps) {
4141
progress.incrementInSteps(steps);
42-
verbose && console.log('Step: ', i);
42+
verbose && console.info('Step: ', i);
4343
} else {
4444
clearInterval(id);
4545
progress.endProgress();

0 commit comments

Comments
 (0)