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

feat: Add error handling for nonexistent file case with --file option #5086

Open
wants to merge 20 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
25 changes: 20 additions & 5 deletions lib/cli/collect-files.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
'use strict';

const fs = require('fs');
const path = require('path');
const ansi = require('ansi-colors');
const debug = require('debug')('mocha:cli:run:helpers');
const minimatch = require('minimatch');
const {NO_FILES_MATCH_PATTERN} = require('../errors').constants;
const lookupFiles = require('./lookup-files');
const {castArray} = require('../utils');
const {createNoFilesMatchPatternError} = require('../errors');

/**
* Exports a function that collects test files from CLI parameters.
Expand All @@ -30,7 +32,7 @@ module.exports = ({
sort,
spec
} = {}) => {
const unmatched = [];
const unmatchedSpecFiles = [];
Copy link
Author

Choose a reason for hiding this comment

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

Renamed variable for semantic clarity

const specFiles = spec.reduce((specFiles, arg) => {
try {
const moreSpecFiles = castArray(lookupFiles(arg, extension, recursive))
Expand All @@ -44,14 +46,25 @@ module.exports = ({
return [...specFiles, ...moreSpecFiles];
} catch (err) {
if (err.code === NO_FILES_MATCH_PATTERN) {
unmatched.push({message: err.message, pattern: err.pattern});
unmatchedSpecFiles.push({message: err.message, pattern: err.pattern});
return specFiles;
}

throw err;
}
}, []);

// check that each file passed in to --file exists
fileArgs.forEach(file => {
const fileAbsolutePath = path.resolve(file);
if (!fs.existsSync(fileAbsolutePath)) {
throw createNoFilesMatchPatternError(
`Cannot find any files matching pattern "${fileAbsolutePath}"`,
fileAbsolutePath
);
}
});

// ensure we don't sort the stuff from fileArgs; order is important!
if (sort) {
specFiles.sort();
Expand All @@ -67,14 +80,16 @@ module.exports = ({
if (!files.length) {
// give full message details when only 1 file is missing
const noneFoundMsg =
unmatched.length === 1
? `Error: No test files found: ${JSON.stringify(unmatched[0].pattern)}` // stringify to print escaped characters raw
unmatchedSpecFiles.length === 1
? `Error: No test files found: ${JSON.stringify(
unmatchedSpecFiles[0].pattern
)}` // stringify to print escaped characters raw
: 'Error: No test files found';
console.error(ansi.red(noneFoundMsg));
process.exit(1);
} else {
// print messages as a warning
unmatched.forEach(warning => {
unmatchedSpecFiles.forEach(warning => {
console.warn(ansi.yellow(`Warning: ${warning.message}`));
});
}
Expand Down
9 changes: 9 additions & 0 deletions lib/cli/run.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const {
createInvalidArgumentValueError,
createMissingArgumentError
} = require('../errors');
const {NO_FILES_MATCH_PATTERN} = require('../errors').constants;

const {
list,
Expand Down Expand Up @@ -369,6 +370,14 @@ exports.handler = async function (argv) {
try {
await runMocha(mocha, argv);
} catch (err) {
if (err.code === NO_FILES_MATCH_PATTERN) {
console.error(ansi.yellow(`Warning: ${err.message}`));
console.log(
'No test file found with the given pattern, exiting with code 1'
);
process.exit(1);
}

console.error('\n' + (err.stack || `Error: ${err.message || err}`));
process.exit(1);
}
Expand Down
29 changes: 26 additions & 3 deletions test/integration/options/file.spec.js
JoshuaKGoldberg marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
'use strict';

var path = require('path').posix;
var helpers = require('../helpers');
var runMochaJSON = helpers.runMochaJSON;
var resolvePath = helpers.resolveFixturePath;
const {
runMochaJSON,
resolveFixturePath: resolvePath,
runMocha
} = require('../helpers');

describe('--file', function () {
var args = [];
Expand Down Expand Up @@ -64,4 +66,25 @@ describe('--file', function () {
done();
});
});

it('should log a warning if a nonexistent file is specified', function (done) {
Copy link
Member

Choose a reason for hiding this comment

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

[Naming]

Suggested change
it('should log a warning if a nonexistent file is specified', function (done) {
it('should log a warning if a nonexistent file with an unknown extension is specified', function (done) {

const nonexistentTestFileArg = 'nonexistent.test.ts';
runMocha(
nonexistentTestFileArg,
['--file'],
function (err, res) {
if (err) {
return done(err);
}

expect(
res.output,
'to contain',
'Warning: Cannot find any files matching pattern'
).and('to contain', nonexistentTestFileArg);
done();
},
{stdio: 'pipe'}
);
});
});