Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Force redirecting stdout to stderr if useStderr is passed #8091

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 44 additions & 12 deletions e2e/__tests__/useStderr.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,26 +13,58 @@ import {cleanup, writeFiles} from '../Utils';
const DIR = path.resolve(os.tmpdir(), 'use-stderr-test');

beforeEach(() => cleanup(DIR));
afterEach(() => cleanup(DIR));
afterAll(() => cleanup(DIR));

const NUMBER_OF_TESTS_TO_FORCE_USING_WORKERS = 25;

function runTest(useStderr: boolean, forceWorkers: boolean) {
const additionalTests = {};

if (forceWorkers) {
for (let i = 0; i < NUMBER_OF_TESTS_TO_FORCE_USING_WORKERS; i++) {
additionalTests[
`__tests__/test${i}.test.js`
] = `test('test ${i}', () => {});`;
}
}

test('no tests found message is redirected to stderr', () => {
writeFiles(DIR, {
...additionalTests,
'__tests__/test.test.js': `
require('../file1');
test('file1', () => {
console.log('Hello from console');
process.stdout.write('Hello from stdout\\n');
process.stderr.write('Hello from stderr\\n');
});
`,
'.watchmanconfig': '',
'file1.js': 'module.exports = {}',
'package.json': JSON.stringify({jest: {testEnvironment: 'node'}}),
});
let stderr;
let stdout;

({stdout, stderr} = runJest(DIR, ['--useStderr']));
expect(stdout).toBe('');
expect(stderr).toMatch('No tests found');
const {stdout, stderr} = runJest(DIR, [
'--verbose',
useStderr ? '--useStderr' : '',
forceWorkers ? '--maxWorkers=2' : '--runInBand',
]);

writeFiles(DIR, {
'__tests__/test.test.js': `require('../file1'); test('file1', () => {});`,
});
if (useStderr) {
expect(stdout).toBe('');
}

({stdout, stderr} = runJest(DIR, ['--useStderr']));
expect(stdout).toBe('');
const generalOutput = useStderr ? stderr : stdout;
expect(generalOutput).toContain('Hello from stdout');
expect(generalOutput).toContain('Hello from console');
expect(stderr).toMatch(/PASS.*test\.test\.js/);
expect(stderr).toContain('Hello from stderr');
}

test.each([
[true, 'in band'],
[false, 'in band'],
[true, 'with workers'],
[false, 'with workers'],
])('passes when useStderr is %s, running %s', (useStderr, runMode) => {
runTest(useStderr, runMode === 'with workers');
});
10 changes: 8 additions & 2 deletions packages/jest-runner/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,14 @@ class TestRunner {
numWorkers: this._globalConfig.maxWorkers,
}) as WorkerInterface;

if (worker.getStdout()) worker.getStdout().pipe(process.stdout);
if (worker.getStderr()) worker.getStderr().pipe(process.stderr);
if (worker.getStdout()) {
worker
.getStdout()
.pipe(this._globalConfig.useStderr ? process.stderr : process.stdout);
}
if (worker.getStderr()) {
worker.getStderr().pipe(process.stderr);
}

const mutex = throat(this._globalConfig.maxWorkers);

Expand Down
54 changes: 32 additions & 22 deletions packages/jest-runner/src/runTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,31 +194,41 @@ async function runTestInternal(
// For runtime errors
sourcemapSupport.install(sourcemapOptions);

if (
environment.global &&
environment.global.process &&
environment.global.process.exit
) {
const realExit = environment.global.process.exit;
const globalProcess = environment.global && environment.global.process;

if (globalProcess) {
if (globalProcess.exit) {
const realExit = environment.global.process.exit;

environment.global.process.exit = function exit(...args: Array<any>) {
const error = new ErrorWithStack(
`process.exit called with "${args.join(', ')}"`,
exit,
);

const formattedError = formatExecError(
error,
config,
{noStackTrace: false},
undefined,
true,
);

process.stderr.write(formattedError);

return realExit(...args);
};
}

environment.global.process.exit = function exit(...args: Array<any>) {
const error = new ErrorWithStack(
`process.exit called with "${args.join(', ')}"`,
exit,
);
if (globalProcess.stderr) {
globalProcess.stderr.pipe(process.stderr);
}

const formattedError = formatExecError(
error,
config,
{noStackTrace: false},
undefined,
true,
if (globalProcess.stdout) {
globalProcess.stdout.pipe(
globalConfig.useStderr ? process.stderr : process.stdout,
);

process.stderr.write(formattedError);

return realExit(...args);
};
}
}

try {
Expand Down
16 changes: 16 additions & 0 deletions packages/jest-util/src/createProcessObject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/

import {PassThrough} from 'stream';
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we import from readable-stream instead to avoid inconsistencies between node versions?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, we can do that, given that we're already depending on that module transitively.

import deepCyclicCopy from './deepCyclicCopy';

const BLACKLIST = new Set(['env', 'mainModule', '_events']);
Expand Down Expand Up @@ -68,6 +69,18 @@ function createProcessEnv(): NodeJS.ProcessEnv {
return Object.assign(proxy, process.env);
}

function overrideProcessStream(
newProcess: NodeJS.Process,
streamName: 'stdout' | 'stderr',
) {
const newStream = new PassThrough();
Object.defineProperty(newProcess, streamName, {
...Object.getOwnPropertyDescriptor(newProcess, streamName),
get: () => newStream,
});
newProcess[streamName].isTTY = newProcess[streamName].isTTY;
}

export default function() {
const process = require('process');
const newProcess = deepCyclicCopy(process, {
Expand Down Expand Up @@ -101,5 +114,8 @@ export default function() {
newProcess.env = createProcessEnv();
newProcess.send = () => {};

overrideProcessStream(newProcess, 'stdout');
overrideProcessStream(newProcess, 'stderr');

return newProcess;
}