From f4dae5a2b0116b046a2d386706b752afab8eeb72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Th=C3=A0nh=20Nh=C3=A2n?= <60387689+NhanAZ@users.noreply.github.com> Date: Wed, 10 Jun 2026 00:24:54 +0700 Subject: [PATCH] test(cli): add command path coverage --- tests/cli/cli-commands.test.ts | 74 ++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 tests/cli/cli-commands.test.ts diff --git a/tests/cli/cli-commands.test.ts b/tests/cli/cli-commands.test.ts new file mode 100644 index 0000000..07e63e7 --- /dev/null +++ b/tests/cli/cli-commands.test.ts @@ -0,0 +1,74 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { readFileSync } from 'node:fs'; +import * as path from 'node:path'; + +const CLI_PATH = path.resolve(__dirname, '..', '..', '..', 'bin', 'opk'); +const PACKAGE_JSON_PATH = path.resolve(__dirname, '..', '..', '..', 'package.json'); + +interface CliResult { + stdout: string; + stderr: string; + status: number | null; +} + +interface PackageJson { + version: string; +} + +function runCli(args: string[]): CliResult { + const result = spawnSync(process.execPath, [CLI_PATH, ...args], { + encoding: 'utf8', + }); + + return { + stdout: result.stdout, + stderr: result.stderr, + status: result.status, + }; +} + +function getPackageVersion(): string { + const packageJson = JSON.parse(readFileSync(PACKAGE_JSON_PATH, 'utf8')) as PackageJson; + return packageJson.version; +} + +test('CLI commands', async (t) => { + await t.test('should print help and exit with 0 when no command is provided', () => { + const result = runCli([]); + + assert.strictEqual(result.status, 0); + assert.match(result.stdout, /OpenPolicyKit v\d+\.\d+\.\d+/); + assert.match(result.stdout, /Usage:/); + assert.match(result.stdout, /opk scan \[path\]/); + assert.strictEqual(result.stderr, ''); + }); + + await t.test('should print scan help and exit with 0', () => { + const result = runCli(['scan', '--help']); + + assert.strictEqual(result.status, 0); + assert.match(result.stdout, /Scan options:/); + assert.match(result.stdout, /--json/); + assert.match(result.stdout, /--min-severity /); + assert.strictEqual(result.stderr, ''); + }); + + await t.test('should print the package version and exit with 0', () => { + const result = runCli(['--version']); + + assert.strictEqual(result.status, 0); + assert.strictEqual(result.stdout.trim(), getPackageVersion()); + assert.strictEqual(result.stderr, ''); + }); + + await t.test('should exit with 2 for an unknown command', () => { + const result = runCli(['unknown']); + + assert.strictEqual(result.status, 2); + assert.strictEqual(result.stdout, ''); + assert.match(result.stderr, /Unknown command: unknown/); + assert.match(result.stderr, /Run "opk --help" for usage information\./); + }); +});