|
| 1 | +import { strictEqual } from 'node:assert'; |
| 2 | +import { describe, it } from 'node:test'; |
| 3 | +import { fileURLToPath } from 'node:url'; |
| 4 | + |
| 5 | +import { LogLevel } from '../../logger/constants.mjs'; |
| 6 | +import logger from '../../logger/index.mjs'; |
| 7 | +import createWorkerPool from '../index.mjs'; |
| 8 | + |
| 9 | +const reporterSpecifier = fileURLToPath( |
| 10 | + import.meta.resolve('./fixtures/log-level-reporter.mjs') |
| 11 | +); |
| 12 | + |
| 13 | +/** |
| 14 | + * Runs a function with the logger temporarily set to the given level. |
| 15 | + * |
| 16 | + * @template T |
| 17 | + * @param {number} level - Log level to apply for the duration of the callback |
| 18 | + * @param {() => Promise<T>} fn - Callback to run |
| 19 | + * @returns {Promise<T>} |
| 20 | + */ |
| 21 | +const withLogLevel = async (level, fn) => { |
| 22 | + const original = logger.getLogLevel(); |
| 23 | + |
| 24 | + logger.setLogLevel(level); |
| 25 | + |
| 26 | + try { |
| 27 | + return await fn(); |
| 28 | + } finally { |
| 29 | + logger.setLogLevel(original); |
| 30 | + } |
| 31 | +}; |
| 32 | + |
| 33 | +describe('createWorkerPool', () => { |
| 34 | + it('should forward the current log level to workers', async () => { |
| 35 | + await withLogLevel(LogLevel.fatal, async () => { |
| 36 | + const pool = createWorkerPool(1); |
| 37 | + |
| 38 | + try { |
| 39 | + strictEqual(pool.options.workerData.logLevel, LogLevel.fatal); |
| 40 | + } finally { |
| 41 | + await pool.destroy(); |
| 42 | + } |
| 43 | + }); |
| 44 | + }); |
| 45 | + |
| 46 | + it('should apply the forwarded log level inside the worker', async () => { |
| 47 | + await withLogLevel(LogLevel.fatal, async () => { |
| 48 | + const pool = createWorkerPool(1); |
| 49 | + |
| 50 | + try { |
| 51 | + const [levelInWorker] = await pool.run({ |
| 52 | + generatorSpecifier: reporterSpecifier, |
| 53 | + input: [null], |
| 54 | + itemIndices: [0], |
| 55 | + extra: {}, |
| 56 | + configuration: {}, |
| 57 | + }); |
| 58 | + |
| 59 | + strictEqual(levelInWorker, LogLevel.fatal); |
| 60 | + } finally { |
| 61 | + await pool.destroy(); |
| 62 | + } |
| 63 | + }); |
| 64 | + }); |
| 65 | + |
| 66 | + it('should leave workers at the default level when it is not changed', async () => { |
| 67 | + const pool = createWorkerPool(1); |
| 68 | + |
| 69 | + try { |
| 70 | + const [levelInWorker] = await pool.run({ |
| 71 | + generatorSpecifier: reporterSpecifier, |
| 72 | + input: [null], |
| 73 | + itemIndices: [0], |
| 74 | + extra: {}, |
| 75 | + configuration: {}, |
| 76 | + }); |
| 77 | + |
| 78 | + strictEqual(levelInWorker, LogLevel.info); |
| 79 | + } finally { |
| 80 | + await pool.destroy(); |
| 81 | + } |
| 82 | + }); |
| 83 | +}); |
0 commit comments