Skip to content

Commit

Permalink
Cleanup and types (#12)
Browse files Browse the repository at this point in the history
* fix 1

* cleanup

* fix

* fix help

* fix 2

* fix types

* fix types 2

* 1.6.4

* fix types

* fix example

* fix default vars

* fix defaults

* fixes

* fix passing env

* 1.6.7

* fix tests
  • Loading branch information
mmisty authored Aug 28, 2023
1 parent 958ebb1 commit 40c1282
Show file tree
Hide file tree
Showing 16 changed files with 120 additions and 91 deletions.
94 changes: 53 additions & 41 deletions .bin/cy-grep.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,30 +48,31 @@ const argv = yargs(process.argv.slice(2))
'show-excluded-tests': {
// sets GREP_showExcludedTests
type: 'boolean',
default: true,
describe: `show excluded tests as skipped or not show them at all`,
default: undefined, // true,
describe: `show excluded tests as skipped or not show them at all (for not showing --no-show-excluded-tests or --not-e)`,
alias: 'e',
},
'show-tags-title': {
// sets GREP_showTagsInTitle
type: 'boolean',
default: false,
default: undefined, // false,
describe: `show tags in test title`,
alias: 't',
},
})
.help('help')
.parseSync();

const { script, grep: grepInput, prefilterFile, deletePrefiltered, onlyPrefilter, onlyRun, showExcludedTests, showTagsTitle } =
argv;

let grep;
if(!grepInput && process.env.CYPRESS_GREP){
grep = process.env.CYPRESS_GREP;
} else{
grep = grepInput;
}
const {
script,
grep: grepInput,
prefilterFile,
deletePrefiltered,
onlyPrefilter,
onlyRun,
showExcludedTests,
showTagsTitle,
} = argv;

const getGrepEnvVariableStr = grepInputT => {
if (grepInputT) {
Expand Down Expand Up @@ -120,75 +121,86 @@ const getSpecPatternVar = (origSpecPattern, grepInputT, onlyRunInput) => {
if (origSpecPattern && onlyRunInput) {
return `CYPRESS_SPEC_PATTERN="[${origSpecPattern}]"`;
}
if(!grepInputT){
return ''

if (!grepInputT) {
return '';
}

return `CYPRESS_SPEC_PATTERN="[]"`;
};

const execute = (vars, scriptInput) => {
const args = `${vars.join(' ')} ${scriptInput}`;
const args = [...vars, scriptInput].filter(t => t !== '').join(' ');
console.log(packagename + ' execute: "' + args + '"');
execSync(`${vars.filter(t => t !== '').join(' ')} ${scriptInput}`, { stdio: 'inherit' });
execSync(`${vars.filter(t => t !== '').join(' ')} ${scriptInput}`, { stdio: 'inherit', env: process.env });
};

try {
let grep;
if (!grepInput && process.env.CYPRESS_GREP) {
grep = process.env.CYPRESS_GREP;
} else {
grep = grepInput;
}

const started = Date.now();
let grepExpression = getGrepEnvVariableStr(grep);
const resultsFileEnvVariableStr = `CYPRESS_GREP_RESULTS_FILE='${prefilterFile}'`;
let resultsFileEnvVariableStr = `CYPRESS_GREP_RESULTS_FILE='${prefilterFile}'`;

if (onlyRun || !grep) {
if (!existsSync(prefilterFile)) {
if (!existsSync(prefilterFile) && !grep) {
console.log(
`${packagename} Will run without prefiltering tests since file ${prefilterFile} doesnt exist\n` +
`${packagename} Prefilter tests for faster filtering first by adding --f (or removing --r) options`,
`${packagename} Will run all tests: prefilter tests by adding \`--grep \` for faster filtering (for help \`cy-grep --help\`)`,
);
resultsFileEnvVariableStr = '';
} else {
if (existsSync(prefilterFile)) {
// run all tests from prefiltered file or all
console.log(`${packagename} Will run tests from ${prefilterFile}`);
} else {
resultsFileEnvVariableStr = '';
console.log(
`${packagename} Will run without pre-filtering tests since file ${prefilterFile} doesn't exist\n` +
`${packagename} -> Prefilter tests for faster filtering first by adding --f (or removing --r) options`,
);
}
}
if (!grep) {
console.log(`${packagename} Prefilter tests by adding \`--grep '@myTag'\` for faster filtering`);
}

// throw new Error('Cannot run prefiltered');
} else {
console.log(`${packagename}: PRE-FILTERING MODE ${onlyPrefilter ? 'only prefilter' : ''}=== `);
console.log(`${packagename} PRE-FILTERING MODE ${onlyPrefilter ? 'only prefilter' : ''}=== `);
execute([grepExpression, resultsFileEnvVariableStr, 'CYPRESS_GREP_PRE_FILTER=true'], script);
const prefilteringDuration = `${(Date.now() - started) / 1000}s`;
if (onlyPrefilter) {
console.log(
`${packagename}: FINISHED pre-filtering only (in ${prefilteringDuration}), results in ${prefilterFile}, to run execute with --r option === `,
`${packagename} FINISHED pre-filtering only (in ${prefilteringDuration}), results in ${prefilterFile}, to run execute with --r option === `,
);
process.exit(0);
} else {
console.log(`${packagename}: pre-filtering done in ${prefilteringDuration}`);
console.log(`${packagename} pre-filtering done in ${prefilteringDuration}`);
}
}

console.log(`${packagename}: running tests === `);
console.log(`${packagename} Running tests === `);

let specPattern = getSpecPattern(fileSpecPatternOriginal);
let specString = getSpecPatternVar(specPattern, grep, onlyRun);

// to use from cypress config when not set
const exclTests =
showExcludedTests !== undefined ? `CYPRESS_GREP_showExcludedTests=${showExcludedTests === true}` : '';
const showTags = showTagsTitle !== undefined ? `CYPRESS_GREP_showTagsInTitle=${showTagsTitle === true}` : '';

execute(
[
grepExpression,
resultsFileEnvVariableStr,
'CYPRESS_GREP_PRE_FILTER=false',
specString,
`CYPRESS_GREP_showExcludedTests=${showExcludedTests === true}`,
`CYPRESS_GREP_showTagsInTitle=${showTagsTitle === true}`,
],
[grepExpression, resultsFileEnvVariableStr, 'CYPRESS_GREP_PRE_FILTER=false', specString, exclTests, showTags],
script,
);

if (!onlyRun && deletePrefiltered && existsSync(prefilterFile)) {
rmSync(prefilterFile);
}

console.log(`${packagename}: FINISHED === `);
console.log(`${packagename} FINISHED === `);
} catch (err) {
console.log(`${packagename}: FINISHED (exit code: 1) === ` + err.message);
console.log(err);
console.log(`${packagename} FINISHED (exit code: 1) === `);
// console.log(err);
process.exit(1);
}
7 changes: 6 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
## Change Log
### 1.6.2
### 1.6.7
- script - fixed defaults for env vars
- script - pass env to script

### 1.6.5
- speedup filtering (filtering from 1000 files for less than 30 seconds)
- added helper script
- fix types

### 1.4.6
- fixed test object to have tags for retried tests
Expand Down
14 changes: 13 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ cy-grep --script 'npm run cy:run' --grep '!@theOne'
1. [Run by Tags](#run-by-tags)
- [Select tests by pseudo regex](#select-tests-by-pseudo-regexp)
- [Select tests by regex](#select-tests-by-regexp)
1. [Examples](#examples)
1. [UI Control](#ui-control)
- [Show tags in title](#show-tags-in-title)
- [Show excluded tests](#show-excluded-tests)
Expand Down Expand Up @@ -166,10 +167,11 @@ describe('login', { tags: '@smoke' }, () => {

Test `01. should login` will have tags [`@smoke`, `@P1`]

Test `02. should have error on login` will have tags [`@smoke`, `@errors`, `@P1`]
Test `02. should have error on login` will have tags [`@smoke`, `@errors`, `@P2`]

Test `03. should do smth on err` will have tags [`@smoke`, `@errors`]


## Run by tags

To run by tags you can use script
Expand Down Expand Up @@ -296,6 +298,16 @@ Examples:
- `GREP='=/(?!.*@smoke)(?=.*@p1)/i'` - runs all tests WITHOUT `@smoke` and WITH `@p1`
- `GREP='=/@P[12]/'` - runs all tests with `@P1` or `@P2`

## Environment variables
- `GREP_addControlToUI` - Add UI control to filter test (only for interactive mode), default true
- `GREP_showTagsInTitle` - Show tags in test title, default true
- `GREP_showExcludedTests` - Show excluded tests as pending or not show at all, default true
- `GREP_failOnNotFound` - Whether to fail run when no tests are found, default true

## Examples
- example [JS project](https://github.com/mmisty/cypress-grep-example)
- example [TS project](https://github.com/mmisty/cypress-grep-example-ts)

## UI Control

Search input will be injected into Cypress UI to filter tests when running Interactive mode
Expand Down
1 change: 1 addition & 0 deletions cypress.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export default defineConfig({
env: {
GREP_addControlToUI: true,
GREP_showTagsInTitle: true,
GREP_showExcludedTests: true,
REDIRECT_BROWSER_LOG: true,
allure: true,
},
Expand Down
1 change: 1 addition & 0 deletions integration/plugins/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ export const setupPlugins = (on: PluginEvents, config: PluginConfigOptions) => {

redirectLog(on, config, ['exception', 'test:log', 'log', 'warn']);
configureAllureAdapterPlugins(on, config);
console.log(config.env);

// It's IMPORTANT to return the config object
// with any changed environment variables
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@mmisty/cypress-grep",
"version": "1.6.2",
"version": "1.6.7",
"description": "Filters tests by tags/title using substring or regular expressions (can find dynamic tags)",
"main": "index.js",
"repository": "[email protected]:mmisty/cypress-grep.git",
Expand Down
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
// eslint-disable-next-line @typescript-eslint/triple-slash-reference
/// <reference path="./cypress/cypress.ts" />
// eslint-disable-next-line @typescript-eslint/triple-slash-reference
/// <reference path="./mocha/index.ts" />

// here export only functions to run in browser
export { registerCypressGrep } from './setup';
8 changes: 0 additions & 8 deletions src/plugins/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,15 +148,7 @@ const changeSpecsForRun = (
absolute: path.resolve(config.projectRoot, s),
}));

/*if (Array.isArray(specPattern)) {
// need to remove everything from existing
config.specPattern = specPattern?.splice(0, specPattern.length);
}*/

config.specPattern = specsNew.map(t => t.relative);
/*
config.specPattern = specsPatterns.length > 0 ? specsPatterns : specPattern;
;*/
console.log(`${pkgName} Spec Pattern: ${config.specPattern}`);
};

Expand Down
14 changes: 9 additions & 5 deletions src/plugins/tasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,15 @@ export const taskWrite = (

const cyan = '\x1b[36m';
const end = '\x1b[0m';
console.log(
`${pkgName} filtered:\n ${cyan}${end} ${contents.tests
.map(t => `${cyan}${`${t.filteredTitle}`.replace(/\/\//g, '/')}${end}`)
.join(`\n ${cyan}${end} `)}\n`,
);

if (contents.tests.length > 0) {
console.log(
`${pkgName} filtered:\n ${cyan}${end} ${contents.tests
.map(t => `${cyan}${`${t.filteredTitle}`.replace(/\/\//g, '/')}${end}`)
.join(`\n ${cyan}${end} `)}\n`,
);
}

console.log(
`${pkgName} filtered ${contents.tests.length} from total ${contents.total} tests by spec pattern: ${config.env['originalSpecPattern']}`,
);
Expand Down
23 changes: 3 additions & 20 deletions src/register.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,9 @@
// eslint-disable-next-line @typescript-eslint/triple-slash-reference
/// <reference path="./cypress/cypress.ts" />
// eslint-disable-next-line @typescript-eslint/triple-slash-reference
/// <reference path="./mocha/index.ts" />
import { registerCypressGrep } from './setup';
import { grepEnvVars } from './common/envVars';

// this is to import with ECMS2015 syntax
// import '@mmisty/cypress-grep/register';
registerCypressGrep({
addControlToUI:
// default true
Cypress.env(grepEnvVars.addControlToUI) === undefined ||
Cypress.env(grepEnvVars.addControlToUI) === 'true' ||
Cypress.env(grepEnvVars.addControlToUI) === true,

showTagsInTitle:
// default true
Cypress.env(grepEnvVars.showTagsInTitle) === undefined ||
Cypress.env(grepEnvVars.showTagsInTitle) === 'true' ||
Cypress.env(grepEnvVars.showTagsInTitle) === true,

showExcludedTests:
// default true
Cypress.env(grepEnvVars.showExcludedTests) === undefined ||
Cypress.env(grepEnvVars.showExcludedTests) === 'true' ||
Cypress.env(grepEnvVars.showExcludedTests) === true,
});
registerCypressGrep();
13 changes: 12 additions & 1 deletion src/setup/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,18 @@ const logCreate = (config?: GrepConfig) => (message: unknown) => {
}
};

export const registerCypressGrep = (config?: GrepConfig) => {
const boolOrDefault = (val: unknown, res: boolean) => {
return val === undefined ? res : val === 'true' || val === true;
};

export const registerCypressGrep = (configInput?: GrepConfig) => {
const defaultConfig = {
addControlToUI: boolOrDefault(Cypress.env(grepEnvVars.addControlToUI), true),
showTagsInTitle: boolOrDefault(Cypress.env(grepEnvVars.showTagsInTitle), true),
showExcludedTests: boolOrDefault(Cypress.env(grepEnvVars.showExcludedTests), true),
};
const config: GrepConfig = configInput ? { ...defaultConfig, ...configInput } : defaultConfig;

const debug = logCreate(config);
const initShowTagsInTitle = config?.showTagsInTitle ?? false;
const initShowExcludedTests = config?.showExcludedTests ?? false;
Expand Down
6 changes: 5 additions & 1 deletion tests/test-folder/integration/many-tests.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,11 @@ describe('many tests', () => {

it('should filter one test from many files', () => {
const started = Date.now();
runTests('specPattern="[reports/tests/**/*.*,reports/tests/one.*]"', ["--g '@oneTag'", '--no-show-excluded-tests']);
runTests('specPattern="[reports/tests/**/*.*,reports/tests/one.*]"', [
"--g '@oneTag'",
'--no-show-excluded-tests',
'--no-t',
]);
const durationSec = (Date.now() - started) / 1000;

expect(resSorted()).toEqual([{ name: 'test with tag', status: 'passed' }]);
Expand Down
Loading

0 comments on commit 40c1282

Please sign in to comment.