Skip to content

Fix/bootstrap starting for def #1270

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

Merged
merged 12 commits into from
Oct 23, 2018
Merged
Show file tree
Hide file tree
Changes from 10 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
26 changes: 17 additions & 9 deletions lib/codecept.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,20 +28,20 @@ class Codecept {
* Initialize CodeceptJS at specific directory.
* If async initialization is required, pass callback as second parameter.
*
* @param {*} dir
* @param {*} callback
* @param {string} dir
* @param {() => any} [callback]
*/
init(dir, callback) {
this.initGlobals(dir);
// initializing listeners
Container.create(this.config, this.opts);
this.bootstrap(callback);
this.runHooks(callback);
}

/**
* Creates global variables
*
* @param {*} dir
* @param {string} dir
*/
initGlobals(dir) {
global.codecept_dir = dir;
Expand All @@ -66,12 +66,11 @@ class Codecept {
}

/**
* Executes hooks and bootstrap.
* If bootstrap is async, second parameter is required.
* Executes hooks.
*
* @param {*} done
* @param {() => any} [done]
*/
bootstrap(done) {
runHooks(done) {
Copy link
Contributor

Choose a reason for hiding this comment

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

looks like runHooks are synchronous now, so done is not needed and callback functions.
Also I'm going to deprecate custom hooks in config so this code should be 100% synchronous

// default hooks
runHook(require('./listener/steps'));
runHook(require('./listener/config'));
Expand All @@ -82,7 +81,16 @@ class Codecept {
// custom hooks
this.config.hooks.forEach(hook => runHook(hook));

// bootstrap
if (done) done();
}

/**
* Executes bootstrap.
* If bootstrap is async, second parameter is required.
*
* @param {() => any} [done]
*/
runBootstrap(done) {
runHook(this.config.bootstrap, done, 'bootstrap');
}

Expand Down
4 changes: 1 addition & 3 deletions lib/command/definitions.js
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ module.exports = function (genPath, options) {
const codecept = new Codecept(config, {});
codecept.init(testsPath, (err) => {
if (err) {
output.error(`Error while running bootstrap file :${err}`);
output.error(`Error while running init :${err}`);
return;
}

Expand Down Expand Up @@ -206,8 +206,6 @@ module.exports = function (genPath, options) {
output.print('Definitions were generated in steps.d.ts');
output.print('Load them by adding at the top of a test file:');
output.print(output.colors.grey('\n/// <reference path="./steps.d.ts" />'));

codecept.teardown();
});
};

Expand Down
124 changes: 65 additions & 59 deletions lib/command/gherkin/snippets.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ module.exports = function (genPath, options) {

const codecept = new Codecept(config, {});
codecept.init(testsPath, (err) => {
if (err) throw new Error(`Error while running init :${err}`);

if (!config.gherkin) {
output.error('Gherkin is not enabled in config. Run `codecept gherkin:init` to enable it');
process.exit(1);
Expand All @@ -34,77 +36,81 @@ module.exports = function (genPath, options) {
process.exit(1);
}

const files = [];
glob.sync(config.gherkin.features, { cwd: global.codecept_dir }).forEach((file) => {
if (!fsPath.isAbsolute(file)) {
file = fsPath.join(global.codecept_dir, file);
}
files.push(fsPath.resolve(file));
});
output.print(`Loaded ${files.length} files`);
codecept.runBootstrap((err) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

gherkin:snippets should not execute bootstrap (as it's omitted for def/list commands as well)

if (err) throw new Error(`Error while running bootstrap file :${err}`);

let newSteps = [];

const parseSteps = (steps) => {
const newSteps = [];
let currentKeyword = '';
for (const step of steps) {
if (step.keyword.trim() === 'And') {
if (!currentKeyword) throw new Error(`There is no active keyword for step '${step.text}'`);
step.keyword = currentKeyword;
const files = [];
glob.sync(config.gherkin.features, { cwd: global.codecept_dir }).forEach((file) => {
if (!fsPath.isAbsolute(file)) {
file = fsPath.join(global.codecept_dir, file);
}
currentKeyword = step.keyword;
try {
matchStep(step.text);
} catch (err) {
let stepLine = step.text
.replace(/\"(.*?)\"/g, '{string}')
.replace(/(\d+\.\d+)/, '{float}')
.replace(/ (\d+) /, ' {int} ');
stepLine = Object.assign(stepLine, { type: step.keyword.trim(), location: step.location });
newSteps.push(stepLine);
files.push(fsPath.resolve(file));
});
output.print(`Loaded ${files.length} files`);

let newSteps = [];

const parseSteps = (steps) => {
const newSteps = [];
let currentKeyword = '';
for (const step of steps) {
if (step.keyword.trim() === 'And') {
if (!currentKeyword) throw new Error(`There is no active keyword for step '${step.text}'`);
step.keyword = currentKeyword;
}
currentKeyword = step.keyword;
try {
matchStep(step.text);
} catch (err) {
let stepLine = step.text
.replace(/\"(.*?)\"/g, '{string}')
.replace(/(\d+\.\d+)/, '{float}')
.replace(/ (\d+) /, ' {int} ');
stepLine = Object.assign(stepLine, { type: step.keyword.trim(), location: step.location });
newSteps.push(stepLine);
}
}
}
return newSteps;
};
return newSteps;
};

const parseFile = (file) => {
const ast = parser.parse(fs.readFileSync(file).toString());
for (const child of ast.feature.children) {
if (child.type === 'ScenarioOutline') continue; // skip scenario outline
newSteps = newSteps.concat(parseSteps(child.steps).map((step) => {
return Object.assign(step, { file: file.replace(global.codecept_dir, '').slice(1) });
}));
}
};
const parseFile = (file) => {
const ast = parser.parse(fs.readFileSync(file).toString());
for (const child of ast.feature.children) {
if (child.type === 'ScenarioOutline') continue; // skip scenario outline
newSteps = newSteps.concat(parseSteps(child.steps).map((step) => {
return Object.assign(step, { file: file.replace(global.codecept_dir, '').slice(1) });
}));
}
};

files.forEach(file => parseFile(file));
files.forEach(file => parseFile(file));

let stepFile = config.gherkin.steps[0];
if (!fsPath.isAbsolute(stepFile)) {
stepFile = fsPath.join(global.codecept_dir, stepFile);
}
let stepFile = config.gherkin.steps[0];
if (!fsPath.isAbsolute(stepFile)) {
stepFile = fsPath.join(global.codecept_dir, stepFile);
}

const snippets = newSteps
.filter((value, index, self) => self.indexOf(value) === index)
.map((step) => {
return `
const snippets = newSteps
.filter((value, index, self) => self.indexOf(value) === index)
.map((step) => {
return `
${step.type}('${step}', () => {
// From "${step.file}" ${JSON.stringify(step.location)}
throw new Error('Not implemented yet');
});`;
});
});

if (!snippets.length) {
output.print('No new snippets found');
return;
}
output.success(`Snippets generated: ${snippets.length}`);
output.print(snippets.join('\n'));
if (!snippets.length) {
output.print('No new snippets found');
return;
}
output.success(`Snippets generated: ${snippets.length}`);
output.print(snippets.join('\n'));

if (!options.dryRun) {
output.success(`Snippets added to ${output.colors.bold(stepFile)}`);
fs.writeFileSync(stepFile, fs.readFileSync(stepFile).toString() + snippets.join('\n') + '\n'); // eslint-disable-line
}
if (!options.dryRun) {
output.success(`Snippets added to ${output.colors.bold(stepFile)}`);
fs.writeFileSync(stepFile, fs.readFileSync(stepFile).toString() + snippets.join('\n') + '\n'); // eslint-disable-line
}
});
});
};
26 changes: 16 additions & 10 deletions lib/command/gherkin/steps.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,22 @@ module.exports = function (genPath, options) {

const codecept = new Codecept(config, {});
codecept.init(testsPath, (err) => {
output.print('Gherkin Step definitions:');
output.print();
const steps = getSteps();
for (const step of Object.keys(steps)) {
output.print(` ${output.colors.bold(step)} \n => ${output.colors.green(steps[step].line || '')}`);
}
output.print();
if (!Object.keys(steps).length) {
output.error('No Gherkin steps defined');
}
if (err) throw new Error(`Error while running init :${err}`);

codecept.runBootstrap((err) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

bootstrap should not be run for listing steps definition (as it's not executed for def)

if (err) throw new Error(`Error while running bootstrap file :${err}`);

output.print('Gherkin Step definitions:');
output.print();
const steps = getSteps();
for (const step of Object.keys(steps)) {
output.print(` ${output.colors.bold(step)} \n => ${output.colors.green(steps[step].line || '')}`);
}
output.print();
if (!Object.keys(steps).length) {
output.error('No Gherkin steps defined');
}
});
});
};

27 changes: 17 additions & 10 deletions lib/command/interactive.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,26 @@ module.exports = function (path, options) {
const codecept = new Codecept(config, options);
codecept.init(testsPath, (err) => {
if (err) {
output.error(`Error while running bootstrap file :${err}`);
output.error(`Error while running init :${err}`);
return;
}

if (options.verbose) output.level(3);
codecept.runBootstrap((err) => {
if (err) {
output.error(`Error while running bootstrap file :${err}`);
return;
}

output.print('String interactive shell for current suite...');
recorder.start();
event.emit(event.suite.before, {});
event.emit(event.test.before);
require('../pause')();
recorder.add(() => event.emit(event.test.after));
recorder.add(() => event.emit(event.suite.after, {}));
recorder.add(() => codecept.teardown());
if (options.verbose) output.level(3);

output.print('String interactive shell for current suite...');
recorder.start();
event.emit(event.suite.before, {});
event.emit(event.test.before);
require('../pause')();
recorder.add(() => event.emit(event.test.after));
recorder.add(() => event.emit(event.suite.after, {}));
recorder.add(() => codecept.teardown());
});
});
};
4 changes: 1 addition & 3 deletions lib/command/list.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ module.exports = function (path) {
const codecept = new Codecept(config, {});
codecept.init(testsPath, (err) => {
if (err) {
output.error(`Error while running bootstrap file :${err}`);
output.error(`Error while running init :${err}`);
return;
}

Expand All @@ -38,7 +38,5 @@ module.exports = function (path) {
}
output.print('PS: Actions are retrieved from enabled helpers. ');
output.print('Implement custom actions in your helper classes.');

codecept.teardown();
});
};
10 changes: 7 additions & 3 deletions lib/command/run.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,13 @@ module.exports = function (test, options) {
try {
codecept = new Codecept(config, options);
codecept.init(testRoot, (err) => {
if (err) throw new Error(`Error while running bootstrap file :${err}`);
codecept.loadTests();
codecept.run(test);
if (err) throw new Error(`Error while running init :${err}`);

codecept.runBootstrap((err) => {
if (err) throw new Error(`Error while running bootstrap file :${err}`);
codecept.loadTests();
codecept.run(test);
});
});
} catch (err) {
output.print('');
Expand Down