Skip to content
Merged
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
295 changes: 207 additions & 88 deletions readme.md → README.md

Large diffs are not rendered by default.

11 changes: 9 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: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
},
"dependencies": {
"keycode": "^2.2.1",
"lodash": "^4.17.21",
"uuid": "^10.0.0"
},
"devDependencies": {
Expand All @@ -40,6 +41,7 @@
"@rollup/plugin-terser": "^0.4.4",
"@rollup/plugin-typescript": "^11.1.6",
"@types/jest": "^29.5.12",
"@types/lodash": "^4.17.6",
"@types/prompts": "^2.4.9",
"@types/uuid": "^10.0.0",
"@types/yargs": "^17.0.32",
Expand Down
6 changes: 4 additions & 2 deletions src/createExecute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,13 @@ export const createExecute =
base: string,
output: Output,
currentProcessRef?: { current: ChildProcessWithoutNullStreams | null },
exitCodeRef?: { current: ExitCode | null }
exitCodeRef?: { current: ExitCode | null },
) =>
(
runner: string,
command: string,
runFrom?: string
runFrom?: string,
env?: Record<string, unknown>
): Promise<ExecResult> => {
return new Promise((accept) => {
output.replaceStrings = {
Expand All @@ -37,6 +38,7 @@ export const createExecute =
args,
{
cwd: runFrom ? path.join(base, runFrom) : path.join(base),
env: { ...process.env, ...env } as NodeJS.ProcessEnv,
}
);

Expand Down
45 changes: 32 additions & 13 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,13 @@ import {
import path from 'path';
import { promisify } from 'util';
import { tmpdir } from 'os';
import { escapeRegExp } from 'lodash';
import { v4 } from 'uuid';
import { CLITestEnvironment, SpawnResult } from './types';
import { Output, OutputType } from './Output';
import { checkRunningProcess } from './utils';
import { createExecute, ExecResult, ExitCode } from './createExecute';
import { keyToHEx, KeyMap } from './keyToHEx';
import { v4 } from 'uuid';

export type * from './types';
export type * from './createExecute';
Expand Down Expand Up @@ -125,8 +126,11 @@ export const prepareEnvironment = async (): Promise<CLITestEnvironment> => {
const execute = async (
runner: string,
command: string,
runFrom?: string,
timeout?: number
options?: Partial<{
runFrom?: string,
timeout?: number,
env: Record<string, unknown>,
}>
) => {
const output = new Output();
const currentProcessRef: {
Expand All @@ -136,24 +140,30 @@ export const prepareEnvironment = async (): Promise<CLITestEnvironment> => {
const scopedExecute = createExecute(
tempDir,
output,
currentProcessRef
currentProcessRef,
undefined,
);

addTasks(jobId, currentProcessRef);

return new Promise<ExecResult>(async (resolve) => {
let timeoutId: NodeJS.Timeout | undefined;
if (timeout) {
if (options?.timeout) {
timeoutId = setTimeout(() => {
resolve({
code: null,
stdout: output.stdout,
stderr: output.stderr,
});
}, timeout);
}, options.timeout);
}

const result = await scopedExecute(runner, command, runFrom);
const result = await scopedExecute(
runner,
command,
options?.runFrom,
options?.env
);
resolve(result);
timeoutId && clearTimeout(timeoutId);
});
Expand All @@ -162,7 +172,10 @@ export const prepareEnvironment = async (): Promise<CLITestEnvironment> => {
const spawn = async (
runner: string,
command: string,
runFrom?: string
options?: Partial<{
runFrom?: string,
env: Record<string, unknown>,
}>
): Promise<SpawnResult> => {
const output = new Output();
const currentProcessRef: {
Expand All @@ -175,31 +188,37 @@ export const prepareEnvironment = async (): Promise<CLITestEnvironment> => {
tempDir,
output,
currentProcessRef,
exitCodeRef
exitCodeRef,
);

addTasks(jobId, currentProcessRef);

currentProcessPromise = scopedExecute(runner, command, runFrom);
currentProcessPromise = scopedExecute(runner, command, options?.runFrom, options?.env);

const waitForText = (
input: string,
options: Partial<{
timeout: number,
ignoreExit: boolean,
checkHistory: boolean,
useRegex: boolean,
}> = {}
): Promise<{ line: string; type: "found" | "timeout" | "exit" }> => {
return new Promise((resolve) => {
const { timeout, ignoreExit, checkHistory } = {
const { timeout, ignoreExit, checkHistory, useRegex } = {
timeout: 5000,
ignoreExit: false,
checkHistory: true,
useRegex: false,
...options,
};
const processExited = exitCodeRef.current !== null;

if (checkHistory && String(output.stdout.join('\n') + output.stderr.join('\n')).includes(input)) {
let expression = new RegExp(escapeRegExp(input), 'g');
if (useRegex) {
expression = new RegExp(input, 'g');
}
if (checkHistory && expression.test(output.stdout.join('\n') + output.stderr.join('\n'))) {
resolve({
type: 'found',
line: input,
Expand All @@ -226,7 +245,7 @@ export const prepareEnvironment = async (): Promise<CLITestEnvironment> => {
}, timeout);

const handler = (value: string) => {
if (value.toString().includes(input)) {
if (expression.test(value)) {
resolve({
type: 'found',
line: input,
Expand Down
13 changes: 10 additions & 3 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export type SpawnResult = {
timeout?: number,
ignoreExit?: boolean,
checkHistory?: boolean,
useRegex?: boolean,
}>,
) => Promise<{ line: string; type: "found" | "timeout" | "exit" }>;
waitForFinish: () => Promise<ExecResult>;
Expand Down Expand Up @@ -36,12 +37,18 @@ export type CLITestEnvironment = {
execute: (
runner: string,
command: string,
runFrom?: string,
timeout?: number,
options?: Partial<{
runFrom?: string,
timeout?: number,
env?: Record<string, unknown>,
}>,
) => Promise<ExecResult>;
spawn: (
runner: string,
command: string,
runFrom?: string
options?: Partial<{
runFrom?: string,
env?: Record<string, unknown>,
}>,
) => Promise<SpawnResult>;
};
52 changes: 50 additions & 2 deletions test/cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ describe('Tests testing the CLI and so, the testing lib itself', () => {
'./test/testing-cli.ts --help'
)).exitCodeToBe(0);

await cleanup();
});
it('runs with execute and captures errors and time outs', async () => {
const { execute, cleanup } = await prepareEnvironment();

expect(await execute(
'ts-node',
'./test/testing-cli.ts error'
Expand All @@ -26,13 +31,36 @@ describe('Tests testing the CLI and so, the testing lib itself', () => {
expect(await execute(
'ts-node',
'./test/testing-cli.ts wait',
undefined,
1000,
{ timeout: 1000 }
)).exitCodeToBeNull();

await cleanup();
});

it('runs with spawn or execute and passes through environmental variables', async () => {
const { execute, spawn, cleanup } = await prepareEnvironment();

const executeResult = await execute(
'node',
'./test/testing-cli-entry.js env',
{ env: { HELLO: 'WORLD' } }
);
expect(executeResult).exitCodeToBe(0);
expect(executeResult.stdout).toContain('- HELLO: WORLD');

const { waitForText, waitForFinish } = await spawn(
'node',
'./test/testing-cli-entry.js env',
{ env: { HELLO: 'UNIVERSE', NODE_ENV: 'Yes' } }
);

expect(await waitForText('- HELLO: UNIVERSE')).toBeFoundInOutput();
expect(await waitForText('- NODE_ENV: Yes')).toBeFoundInOutput();
expect(await waitForFinish()).exitCodeToBe(0);

await cleanup();
});

it('should fail without any params', async () => {
const { execute, cleanup } = await prepareEnvironment();

Expand All @@ -51,6 +79,8 @@ describe('Tests testing the CLI and so, the testing lib itself', () => {
"testing-cli-entry.js error exit with error",
"testing-cli-entry.js select ask select input",
"testing-cli-entry.js wait wait for 5 seconds",
"testing-cli-entry.js env print environment variables",
"testing-cli-entry.js random print a phrase with random number",
"Options:",
"--help Show help [boolean]",
"--version Show version number [boolean]",
Expand Down Expand Up @@ -154,6 +184,8 @@ describe('Tests testing the CLI and so, the testing lib itself', () => {
"testing-cli-entry.js error exit with error",
"testing-cli-entry.js select ask select input",
"testing-cli-entry.js wait wait for 5 seconds",
"testing-cli-entry.js env print environment variables",
"testing-cli-entry.js random print a phrase with random number",
"Options:",
"--help Show help [boolean]",
"--version Show version number [boolean]",
Expand Down Expand Up @@ -264,6 +296,22 @@ describe('Tests testing the CLI and so, the testing lib itself', () => {
await cleanup();
});

it('should ask for text using regular expression', async () => {
const { spawn, cleanup } = await prepareEnvironment();

const {
waitForText,
waitForFinish,
} = await spawn('node', './test/testing-cli-entry.js random');

expect(
await waitForText('\\d+ dogs, \\d+ cats, and \\d+ birds', { useRegex: true })
).toBeFoundInOutput();
expect(await waitForFinish()).exitCodeToBe(0);

await cleanup();
});

it('should ask for text and continue with process exits early', async () => {
const { spawn, cleanup } = await prepareEnvironment();

Expand Down
11 changes: 11 additions & 0 deletions test/testing-cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,17 @@ yargs(hideBin(process.argv))
await new Promise((resolve) => setTimeout(resolve, 5000));
console.log('Done waiting');
})
.command('env', 'print environment variables', () => {
console.log(
`- ${Object.keys(process.env)
.map((key) => `${key}: ${process.env[key]}`)
.join('\n- ')}
`
);
})
.command('random', 'print a phrase with random number', () => {
console.log(`${Math.ceil(Math.random() * 10)} dogs, ${Math.ceil(Math.random() * 20)} cats, and ${Math.ceil(Math.random() * 10)} birds`);
})
.option('verbose', {
alias: 'v',
type: 'boolean',
Expand Down