From 92505fc431565e1a5123f9bddd2d47a11c9011b2 Mon Sep 17 00:00:00 2001 From: jdalton Date: Tue, 24 Nov 2026 11:53:30 -0500 Subject: [PATCH] test(cli): use one terminal backend for CLI screenshots --- .config/vitest.terminal.config.mts | 1 + .github/workflows/ci.yml | 23 ++++++ package.json | 2 +- patches/@termless__core@0.11.0.patch | 13 +++ pnpm-lock.yaml | 33 ++------ scripts/refresh/snapshots.mts | 8 +- scripts/test/native.mts | 3 +- src/commands/scan/cmd-scan-reach.test.mts | 49 ++++++++--- test/e2e/termless.test.mts | 73 +++++++++++------ test/lib/termless/animation.mts | 81 +++++++++++-------- test/lib/termless/build-cli.mts | 8 ++ .../termless.node-e-fixture.after-enter.svg | 9 --- .../termless.node-e-fixture.prompt.svg | 9 --- .../termless.npm-scan-setup.canceled.svg | 58 +++++++++++++ .../termless/termless.npm-scan-setup.menu.svg | 58 +++++++++++++ test/unit/lib/termless/animation.test.mts | 80 +++++++++--------- 16 files changed, 352 insertions(+), 156 deletions(-) create mode 100644 patches/@termless__core@0.11.0.patch create mode 100644 test/lib/termless/build-cli.mts delete mode 100644 test/snapshots/termless/termless.node-e-fixture.after-enter.svg delete mode 100644 test/snapshots/termless/termless.node-e-fixture.prompt.svg create mode 100644 test/snapshots/termless/termless.npm-scan-setup.canceled.svg create mode 100644 test/snapshots/termless/termless.npm-scan-setup.menu.svg diff --git a/.config/vitest.terminal.config.mts b/.config/vitest.terminal.config.mts index 3e04d8a35..063691615 100644 --- a/.config/vitest.terminal.config.mts +++ b/.config/vitest.terminal.config.mts @@ -9,6 +9,7 @@ export default defineConfig({ resolve: { preserveSymlinks: false }, test: { resolveSnapshotPath, + globalSetup: ['./test/lib/termless/build-cli.mts'], env: process.argv.some(arg => arg === '--update' || arg === '-u') ? { SOCKET_CLI_NATIVE_TEST_UPDATE_SNAPSHOTS: 'true' } : {}, diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 014ff1352..5ade96685 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -884,11 +884,34 @@ jobs: sea-downloads-v1-${{ matrix.target }}- - name: Test screenshot and signing helpers + id: terminal-helpers + env: + SOCKET_CLI_NATIVE_TEST_ARTIFACTS: &terminal_artifacts build/terminal-test-artifacts/${{ matrix.target }} + NODE_OPTIONS: ${{ matrix.target == 'darwin-arm64' && '--max-old-space-size=4096' || '' }} shell: bash run: | pnpm exec vitest run --config .config/vitest.config.mts test/unit/scripts/test/apple-signing.test.mts pnpm exec vitest run --config .config/vitest.terminal.config.mts + - name: Show failed scan setup screenshots + if: failure() && steps.terminal-helpers.outcome == 'failure' + env: + SOCKET_CLI_NATIVE_TEST_ARTIFACTS: *terminal_artifacts + shell: bash + run: | + python - <<'PYTHON' + import os + import pathlib + import sys + import xml.etree.ElementTree as ET + sys.stdout.reconfigure(encoding='utf-8') + for svg in (pathlib.Path(os.environ['SOCKET_CLI_NATIVE_TEST_ARTIFACTS']) / 'npm-scan-setup').glob('*.svg'): + if svg.name in ('menu.svg', 'canceled.svg'): + print(svg.name) + for row in ET.parse(svg).iter('{http://www.w3.org/2000/svg}text'): + print(''.join(row.itertext()).rstrip()) + PYTHON + - name: Verify .NET SDK shell: bash run: dotnet --list-sdks | awk -F. '$1 >= 8 { found=1 } END { exit !found }' diff --git a/package.json b/package.json index dccc9885e..f5f333a75 100644 --- a/package.json +++ b/package.json @@ -151,7 +151,6 @@ "@socketsecurity/config": "3.0.1", "@socketsecurity/registry": "1.1.17", "@socketsecurity/sdk": "4.0.3", - "@termless/vterm": "0.11.0", "@termless/core": "0.11.0", "@termless/xtermjs": "0.11.0", "@types/blessed": "0.1.25", @@ -309,6 +308,7 @@ "yargs-parser": "$yargs-parser" }, "patchedDependencies": { + "@termless/core@0.11.0": "patches/@termless__core@0.11.0.patch", "graceful-fs@4.2.11": "patches/graceful-fs@4.2.11.patch", "string_decoder@0.10.31": "patches/string_decoder@0.10.31.patch", "meow@13.2.0": "patches/meow@13.2.0.patch", diff --git a/patches/@termless__core@0.11.0.patch b/patches/@termless__core@0.11.0.patch new file mode 100644 index 000000000..b5cfb403b --- /dev/null +++ b/patches/@termless__core@0.11.0.patch @@ -0,0 +1,13 @@ +diff --git a/dist/backends-CRpWNI-T.mjs b/dist/backends-CRpWNI-T.mjs +index 81de773c4f73a2b4c53ecb5249d906c21b4ebdfe..7504a072f7b3d63a69318b1947d0d45d4d184a99 100644 +--- a/dist/backends-CRpWNI-T.mjs ++++ b/dist/backends-CRpWNI-T.mjs +@@ -113,7 +113,7 @@ function spawnNodePty(options) { + kill(signal) { + const sig = signal === 1 ? "SIGHUP" : signal === 9 ? "SIGKILL" : "SIGTERM"; + try { +- ptyProcess.kill(sig); ++ ptyProcess.kill(process.platform === "win32" ? undefined : sig); + } catch {} + }, + get exitCode() { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ffe1db99a..3c3787330 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -69,6 +69,9 @@ patchedDependencies: '@socketsecurity/sdk@4.0.3': hash: 4a12f35c50a3360c68a367609b2de41514cd790f12eda5197b3f8a778ac7e1e2 path: patches/@socketsecurity__sdk@4.0.3.patch + '@termless/core@0.11.0': + hash: 38ffbca72f99f8532af54a935ccafb88b75d9bcbc3058745f3c66cf4b5153400 + path: patches/@termless__core@0.11.0.patch ansi-term@0.0.2: hash: 06bb5127b7689d6ab2ea833f9617b2c3fbe9fe0048ce1c6b59b81f7e25ccbccb path: patches/ansi-term@0.0.2.patch @@ -233,13 +236,10 @@ importers: version: 4.0.3(patch_hash=4a12f35c50a3360c68a367609b2de41514cd790f12eda5197b3f8a778ac7e1e2) '@termless/core': specifier: 0.11.0 - version: 0.11.0(node-pty@1.2.0-beta.18) - '@termless/vterm': - specifier: 0.11.0 - version: 0.11.0(@termless/core@0.11.0(node-pty@1.2.0-beta.18)) + version: 0.11.0(patch_hash=38ffbca72f99f8532af54a935ccafb88b75d9bcbc3058745f3c66cf4b5153400)(node-pty@1.2.0-beta.18) '@termless/xtermjs': specifier: 0.11.0 - version: 0.11.0(@termless/core@0.11.0(node-pty@1.2.0-beta.18)) + version: 0.11.0(@termless/core@0.11.0(patch_hash=38ffbca72f99f8532af54a935ccafb88b75d9bcbc3058745f3c66cf4b5153400)(node-pty@1.2.0-beta.18)) '@types/blessed': specifier: 0.1.25 version: 0.1.25 @@ -2189,12 +2189,6 @@ packages: node-pty: optional: true - '@termless/vterm@0.11.0': - resolution: {integrity: sha512-+Mwoy7hRc5gloqGxojQbAuyBKcRslflI9D16oU/79jbukFg0RTDLPQXNXTjR39fY8JePSzNAu6qX8YChORp1aw==} - engines: {bun: '>=1.0.0', node: '>=23.6.0'} - peerDependencies: - '@termless/core': ^0.11.0 - '@termless/xtermjs@0.11.0': resolution: {integrity: sha512-0GL6F/65WIE11WKMBcw8nCb2fU+8yLfQJ1QE/0jH4NaFd7UROTbR8pdwzkaAZ2u9YVGXA1GFYAr+jBV/5EF7Uw==} engines: {bun: '>=1.0.0', node: '>=23.6.0'} @@ -5511,10 +5505,6 @@ packages: jsdom: optional: true - vterm.js@0.13.2: - resolution: {integrity: sha512-fhNiN1q1HZa2r4vY3WlVCCAg6VKvQvIa2/8f4qPfKiLZCUMzo1vOHzrk/140LdHK6pfsTm3OoMRtAw1lt9uZeA==} - engines: {node: '>=23.6.0'} - walk-up-path@4.0.0: resolution: {integrity: sha512-3hu+tD8YzSLGuFYtPRb48vdhKMi0KQV5sn+uWr8+7dMEq/2G/dtLrdDinkLjqq5TIbIBjYJ4Ax/n3YiaW7QM8A==} engines: {node: 20 || >=22} @@ -7474,7 +7464,7 @@ snapshots: '@stroncium/procfs@1.2.1': {} - '@termless/core@0.11.0(node-pty@1.2.0-beta.18)': + '@termless/core@0.11.0(patch_hash=38ffbca72f99f8532af54a935ccafb88b75d9bcbc3058745f3c66cf4b5153400)(node-pty@1.2.0-beta.18)': optionalDependencies: '@napi-rs/canvas': 1.0.11 '@resvg/resvg-js': 2.6.2 @@ -7484,14 +7474,9 @@ snapshots: playwright: 1.65.0 upng-js: 2.1.0 - '@termless/vterm@0.11.0(@termless/core@0.11.0(node-pty@1.2.0-beta.18))': + '@termless/xtermjs@0.11.0(@termless/core@0.11.0(patch_hash=38ffbca72f99f8532af54a935ccafb88b75d9bcbc3058745f3c66cf4b5153400)(node-pty@1.2.0-beta.18))': dependencies: - '@termless/core': 0.11.0(node-pty@1.2.0-beta.18) - vterm.js: 0.13.2 - - '@termless/xtermjs@0.11.0(@termless/core@0.11.0(node-pty@1.2.0-beta.18))': - dependencies: - '@termless/core': 0.11.0(node-pty@1.2.0-beta.18) + '@termless/core': 0.11.0(patch_hash=38ffbca72f99f8532af54a935ccafb88b75d9bcbc3058745f3c66cf4b5153400)(node-pty@1.2.0-beta.18) '@xterm/addon-unicode11': 0.9.0 '@xterm/headless': 6.0.0 @@ -11290,8 +11275,6 @@ snapshots: - tsx - yaml - vterm.js@0.13.2: {} - walk-up-path@4.0.0: {} webpack-virtual-modules@0.6.2: {} diff --git a/scripts/refresh/snapshots.mts b/scripts/refresh/snapshots.mts index 5e39c983d..64f8f15d0 100644 --- a/scripts/refresh/snapshots.mts +++ b/scripts/refresh/snapshots.mts @@ -1,18 +1,20 @@ -import type { SpawnSyncOptions } from 'node:child_process' import { spawnSync } from 'node:child_process' import { promises as fs } from 'node:fs' import path from 'node:path' import process from 'node:process' + import { isMainModule } from '../lib/is-main-module.mts' -import type { ScriptMeta } from '../lib/run-main.mts' import { runMain } from '../lib/run-main.mts' -import type { SnapshotDependencyName } from './snapshots/dependencies.mts' import { SNAPSHOT_DEPENDENCIES, assertSnapshotDependenciesCurrent, normalizeSnapshotDependencyName, } from './snapshots/dependencies.mts' +import type { ScriptMeta } from '../lib/run-main.mts' +import type { SnapshotDependencyName } from './snapshots/dependencies.mts' +import type { SpawnSyncOptions } from 'node:child_process' + const ROOT = path.resolve(import.meta.dirname, '../..') const ARTIFACTS_ROOT = path.join(ROOT, 'build/native-test-artifacts') const LOCK_DIR = path.join(ARTIFACTS_ROOT, '.snapshot-run-lock') diff --git a/scripts/test/native.mts b/scripts/test/native.mts index 238349790..e948ed33c 100644 --- a/scripts/test/native.mts +++ b/scripts/test/native.mts @@ -1,5 +1,3 @@ -import { SEA_VERSION } from '../../src/sea/version.mts' - import type { SpawnSyncOptions } from 'node:child_process' import { spawnSync } from 'node:child_process' import { createHash } from 'node:crypto' @@ -7,6 +5,7 @@ import { promises as fs } from 'node:fs' import os from 'node:os' import path from 'node:path' import process from 'node:process' +import { SEA_VERSION } from '../../src/sea/version.mts' import { isMainModule } from '../lib/is-main-module.mts' import type { ScriptMeta } from '../lib/run-main.mts' import { runMain } from '../lib/run-main.mts' diff --git a/src/commands/scan/cmd-scan-reach.test.mts b/src/commands/scan/cmd-scan-reach.test.mts index c4dc291cb..9eb0c170c 100644 --- a/src/commands/scan/cmd-scan-reach.test.mts +++ b/src/commands/scan/cmd-scan-reach.test.mts @@ -1,6 +1,8 @@ +import { once } from 'node:events' +import { createServer } from 'node:http' import path from 'node:path' -import { describe, expect, it } from 'vitest' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' import constants, { FLAG_CONFIG, @@ -655,6 +657,29 @@ describe('socket scan reach', async () => { ) describe('non dry-run tests', () => { + const api = createServer((_request, response) => { + response.writeHead(401, { 'content-type': 'application/json' }) + response.end(JSON.stringify({ message: 'Invalid test token' })) + }) + + beforeAll(async () => { + api.listen(0, '127.0.0.1') + await once(api, 'listening') + }) + afterAll(async () => { + await api[Symbol.asyncDispose]() + }) + + function runWithInvalidToken(cmd: string[]) { + const address = api.address() + if (!address || typeof address === 'string') { + throw new Error('Expected a local test API port') + } + return spawnSocketCli(binCliPath, cmd, { + env: { SOCKET_CLI_API_BASE_URL: `http://127.0.0.1:${address.port}` }, + }) + } + cmdit( [ 'scan', @@ -667,7 +692,7 @@ describe('socket scan reach', async () => { ], 'should handle reach analysis on test fixture', async cmd => { - const { code, stderr, stdout } = await spawnSocketCli(binCliPath, cmd) + const { code, stderr, stdout } = await runWithInvalidToken(cmd) // Should fail due to fake token/org, but validates command parsing. expect(code).toBeGreaterThan(0) const output = stdout + stderr @@ -689,7 +714,7 @@ describe('socket scan reach', async () => { ], 'should handle npm ecosystem specification', async cmd => { - const { code, stderr, stdout } = await spawnSocketCli(binCliPath, cmd) + const { code, stderr, stdout } = await runWithInvalidToken(cmd) expect(code).toBeGreaterThan(0) const output = stdout + stderr expect(output.length).toBeGreaterThan(0) @@ -710,7 +735,7 @@ describe('socket scan reach', async () => { ], 'should handle custom memory limit', async cmd => { - const { code, stderr, stdout } = await spawnSocketCli(binCliPath, cmd) + const { code, stderr, stdout } = await runWithInvalidToken(cmd) expect(code).toBeGreaterThan(0) const output = stdout + stderr expect(output.length).toBeGreaterThan(0) @@ -731,7 +756,7 @@ describe('socket scan reach', async () => { ], 'should handle custom timeout', async cmd => { - const { code, stderr, stdout } = await spawnSocketCli(binCliPath, cmd) + const { code, stderr, stdout } = await runWithInvalidToken(cmd) expect(code).toBeGreaterThan(0) const output = stdout + stderr expect(output.length).toBeGreaterThan(0) @@ -752,7 +777,7 @@ describe('socket scan reach', async () => { ], 'should handle path exclusions', async cmd => { - const { code, stderr, stdout } = await spawnSocketCli(binCliPath, cmd) + const { code, stderr, stdout } = await runWithInvalidToken(cmd) expect(code).toBeGreaterThan(0) const output = stdout + stderr expect(output.length).toBeGreaterThan(0) @@ -772,10 +797,10 @@ describe('socket scan reach', async () => { ], 'should handle analytics disabled', async cmd => { - const { code, stderr, stdout } = await spawnSocketCli(binCliPath, cmd) + const { code, stderr, stdout } = await runWithInvalidToken(cmd) expect(code).toBeGreaterThan(0) const output = stdout + stderr - expect(output.length).toBeGreaterThan(0) + expect(output).toContain('401') }, ) @@ -792,7 +817,7 @@ describe('socket scan reach', async () => { ], 'should handle cache skipping', async cmd => { - const { code, stderr, stdout } = await spawnSocketCli(binCliPath, cmd) + const { code, stderr, stdout } = await runWithInvalidToken(cmd) expect(code).toBeGreaterThan(0) const output = stdout + stderr expect(output.length).toBeGreaterThan(0) @@ -812,7 +837,7 @@ describe('socket scan reach', async () => { ], 'should handle JSON output format', async cmd => { - const { code, stderr, stdout } = await spawnSocketCli(binCliPath, cmd) + const { code, stderr, stdout } = await runWithInvalidToken(cmd) expect(code).toBeGreaterThan(0) // JSON output typically suppresses banner in stderr. const output = stdout + stderr @@ -833,7 +858,7 @@ describe('socket scan reach', async () => { ], 'should handle markdown output format', async cmd => { - const { code, stderr, stdout } = await spawnSocketCli(binCliPath, cmd) + const { code, stderr, stdout } = await runWithInvalidToken(cmd) expect(code).toBeGreaterThan(0) // Markdown output typically suppresses banner in stderr. const output = stdout + stderr @@ -860,7 +885,7 @@ describe('socket scan reach', async () => { ], 'should handle comprehensive flag combination', async cmd => { - const { code, stderr, stdout } = await spawnSocketCli(binCliPath, cmd) + const { code, stderr, stdout } = await runWithInvalidToken(cmd) expect(code).toBeGreaterThan(0) const output = stdout + stderr expect(output.length).toBeGreaterThan(0) diff --git a/test/e2e/termless.test.mts b/test/e2e/termless.test.mts index 0c4b57b65..7e43ed8bc 100644 --- a/test/e2e/termless.test.mts +++ b/test/e2e/termless.test.mts @@ -1,42 +1,65 @@ -import { join } from 'node:path' +import { mkdtemp, readFile, realpath, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' import { createTerminal } from '@termless/core' -import { createVtermBackend } from '@termless/vterm' -import { onTestFinished, test } from 'vitest' +import { createXtermBackend } from '@termless/xtermjs' +import { expect, onTestFinished, test } from 'vitest' +import { nativeFixturePathReplacements } from '../lib/native/cli-harness.mts' +import { normalizeBackendOutput } from '../lib/terminal/output.mts' import { captureCheckpoint, createRecording, expectTerminalAnimation, } from '../lib/termless/animation.mts' -test('captures the node -e fixture before and after Enter', async () => { - const terminal = createTerminal({ - backend: createVtermBackend(), - cols: 48, - rows: 8, +test('shows and cancels scan setup through the built socket CLI', async () => { + const cwd = await mkdtemp(join(tmpdir(), 'socket-cli-')) + const { version } = JSON.parse( + await readFile(resolve('package.json'), 'utf8'), + ) as { version: string } + const backend = createXtermBackend() + const normalizer = normalizeBackendOutput(backend, [ + ...nativeFixturePathReplacements(cwd, await realpath(cwd)), + { search: version, replacement: '' }, + ]) + const terminal = createTerminal({ backend, cols: 128, rows: 30 }) + onTestFinished(async () => { + await terminal.close() + await rm(cwd, { recursive: true, force: true }) }) - onTestFinished(() => terminal.close()) - const script = [ - "process.stdout.write('PTY fixture\\r\\n> ready')", - "process.stdin.once('data', () => { process.stdout.write('\\x1b[2J\\x1b[HEnter received\\r\\n'); process.exit(0) })", - ].join(';') - - await terminal.spawn([process.execPath, '-e', script]) - await terminal.waitFor('> ready', 5000) - const prompt = await captureCheckpoint(terminal, 'prompt') + await terminal.spawn( + [ + process.execPath, + resolve('bin/cli.js'), + 'scan', + 'setup', + '--config', + '{}', + ], + { + cwd, + env: { CI: '1', VITEST: '', NO_COLOR: '', NO_UPDATE_NOTIFIER: '1' }, + }, + ) + await terminal.waitFor('Which scan command do you want to configure?', 30_000) + await terminal.waitForStable(150, 10_000) + const menu = await captureCheckpoint(terminal, 'menu') + terminal.press('ArrowUp') + await terminal.waitForStable(150, 10_000) terminal.press('Enter') - await terminal.waitFor('Enter received', 5000) - const complete = await captureCheckpoint(terminal, 'after-enter') + await expect.poll(() => terminal.exitInfo, { timeout: 30_000 }).toBe('exit=0') + normalizer.flush() + const canceled = await captureCheckpoint(terminal, 'canceled') - await expectTerminalAnimation(createRecording([prompt, complete]), { - flow: 'node-e-fixture', - expectedSequence: ['prompt', 'after-enter'], + await expectTerminalAnimation(createRecording([menu, canceled]), { + flow: 'npm-scan-setup', + expectedSequence: ['menu', 'canceled'], snapshotsDir: join(process.cwd(), 'test/snapshots/termless'), - durations: [400, 400], artifactsDir: - process.env['SOCKET_CLI_NATIVE_TEST_ARTIFACTS'] ?? + process.env.SOCKET_CLI_NATIVE_TEST_ARTIFACTS ?? join(process.cwd(), 'build/native-test-artifacts'), }) -}) +}, 60_000) diff --git a/test/lib/termless/animation.mts b/test/lib/termless/animation.mts index 1d46c256a..4f0cf6863 100644 --- a/test/lib/termless/animation.mts +++ b/test/lib/termless/animation.mts @@ -22,7 +22,7 @@ import type { export interface Checkpoint { readonly name: string readonly svg: string - readonly captured?: CapturedCheckpoint + readonly captured: CapturedCheckpoint } export interface CapturedCheckpoint { @@ -70,6 +70,18 @@ export async function assertSamePixels( } } +export function assertSnapshotSvg( + expectedSvg: string, + actualSvg: string, + snapshotPath: string, +): void { + if (expectedSvg !== actualSvg) { + throw new Error( + `Terminal SVG snapshot is stale: ${snapshotPath}. Run pnpm run snapshots:termless:refresh and commit the updated snapshot.`, + ) + } +} + const safeName = /^[a-z0-9][a-z0-9-]*$/ const svgOptions = { fontFamily: "'JetBrains Mono', 'Noto Sans Symbols 2', monospace", @@ -232,7 +244,7 @@ export function createRecording( throw new Error('Recording needs a checkpoint') } const seen = new Set() - const frozen: Checkpoint[] = [] + const width = checkpoints[0]!.captured.cols for (const checkpoint of checkpoints) { if (!safeName.test(checkpoint.name)) { throw new Error(`Unsafe checkpoint name: ${checkpoint.name}`) @@ -241,38 +253,20 @@ export function createRecording( throw new Error(`Duplicate checkpoint: ${checkpoint.name}`) } seen.add(checkpoint.name) - if (typeof checkpoint.svg !== 'string') { - throw new Error('Invalid checkpoint data') - } - const captured = checkpoint.captured - if (captured) { - if ( - frozen.some( - item => item.captured && item.captured.cols !== captured.cols, - ) - ) { - throw new Error( - 'Captured checkpoints must have the same terminal width', - ) - } - frozen.push( - Object.freeze({ name: checkpoint.name, svg: checkpoint.svg, captured }), - ) - } else { - frozen.push(Object.freeze({ name: checkpoint.name, svg: checkpoint.svg })) + if (checkpoint.captured.cols !== width) { + throw new Error('Captured checkpoints must have the same terminal width') } } const sharedHeight = Math.max( - 0, - ...frozen.map(item => item.captured?.height ?? 0), + ...checkpoints.map(item => item.captured.height), ) - const normalized = frozen.map(checkpoint => - checkpoint.captured - ? Object.freeze({ + const normalized = checkpoints.map(checkpoint => + checkpoint.captured.height === sharedHeight + ? checkpoint + : Object.freeze({ ...checkpoint, svg: renderCaptured(checkpoint.captured, sharedHeight), - }) - : checkpoint, + }), ) return Object.freeze({ checkpoints: Object.freeze(normalized) }) } @@ -366,23 +360,46 @@ export async function expectTerminalAnimation( options.snapshotsDir, `${owner}.${options.flow}${checkpoints.length > 1 ? `.${checkpoint.name}` : ''}.svg`, ) + const actualSvg = await readFile( + path.join(flowDir, `${checkpoint.name}.svg`), + 'utf8', + ) if (baselineRasterizer) { - const expectedSvg = await readFile(svgPath, 'utf8') + let expectedSvg: string + try { + expectedSvg = await readFile(svgPath, 'utf8') + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') { + throw error + } + throw new Error( + `Terminal SVG snapshot is missing: ${svgPath}. Run pnpm run snapshots:termless:refresh and commit the updated snapshot.`, + ) + } try { await assertSamePixels( baselineRasterizer, expectedSvg, - checkpoint.svg, + actualSvg, ) } catch (error) { await writeFile( path.join(flowDir, `${checkpoint.name}.expected.png`), await baselineRasterizer.toPng(expectedSvg, 1), ) - throw error + const message = + error instanceof Error ? error.message : String(error) + throw new Error( + `${message}\nRun pnpm run snapshots:termless:refresh and commit the updated snapshot.`, + ) + } + // Termless serializes equivalent SVG differently on some operating + // systems; Linux is the canonical tracked SVG snapshot platform. + if (process.platform === 'linux') { + assertSnapshotSvg(expectedSvg, actualSvg, svgPath) } } else { - await expect(checkpoint.svg).toMatchFileSnapshot(svgPath) + await expect(actualSvg).toMatchFileSnapshot(svgPath) } }), ) diff --git a/test/lib/termless/build-cli.mts b/test/lib/termless/build-cli.mts new file mode 100644 index 000000000..b470eb473 --- /dev/null +++ b/test/lib/termless/build-cli.mts @@ -0,0 +1,8 @@ +import { execSync } from 'node:child_process' + +export function setup(): void { + execSync('pnpm run build:dist:src', { + env: { ...process.env, VITEST: '', NODE_ENV: 'production' }, + stdio: 'inherit', + }) +} diff --git a/test/snapshots/termless/termless.node-e-fixture.after-enter.svg b/test/snapshots/termless/termless.node-e-fixture.after-enter.svg deleted file mode 100644 index 827f69a95..000000000 --- a/test/snapshots/termless/termless.node-e-fixture.after-enter.svg +++ /dev/null @@ -1,9 +0,0 @@ - -Enter received - - - - - - - \ No newline at end of file diff --git a/test/snapshots/termless/termless.node-e-fixture.prompt.svg b/test/snapshots/termless/termless.node-e-fixture.prompt.svg deleted file mode 100644 index d80160dd5..000000000 --- a/test/snapshots/termless/termless.node-e-fixture.prompt.svg +++ /dev/null @@ -1,9 +0,0 @@ - -PTY fixture - -> ready - - - - - \ No newline at end of file diff --git a/test/snapshots/termless/termless.npm-scan-setup.canceled.svg b/test/snapshots/termless/termless.npm-scan-setup.canceled.svg new file mode 100644 index 000000000..cd40182c7 --- /dev/null +++ b/test/snapshots/termless/termless.npm-scan-setup.canceled.svg @@ -0,0 +1,58 @@ + +CLI: v<SOCKET_CLI_VERSION> | cmd: socket scan setup | org: (not set) | token: (not set) + + + +ℹ + No socket.json found at <NATIVE_FIXTURE>, will generate a new one + + + +Note: This tool will set up flag and argument defaults for certain + + CLI commands. You can still override them by explicitly + + setting the flag. It is meant to be a convenience tool. + + + +This command will generate a `socket.json` file in the target cwd. + +You can choose to add this file to your repo (handy for collab) + +or to add it to the ignored files, or neither. This file is only + +used in CLI workflows. + + + +Note: For details on a flag you can run `socket <cmd> --help` + + + +✔ + +Which scan command do you want to configure? + +(cancel) + + + + +ℹ + User canceled + + + + + +Finished + + + + + + + + + \ No newline at end of file diff --git a/test/snapshots/termless/termless.npm-scan-setup.menu.svg b/test/snapshots/termless/termless.npm-scan-setup.menu.svg new file mode 100644 index 000000000..680759f4a --- /dev/null +++ b/test/snapshots/termless/termless.npm-scan-setup.menu.svg @@ -0,0 +1,58 @@ + +CLI: v<SOCKET_CLI_VERSION> | cmd: socket scan setup | org: (not set) | token: (not set) + + + +ℹ + No socket.json found at <NATIVE_FIXTURE>, will generate a new one + + + +Note: This tool will set up flag and argument defaults for certain + + CLI commands. You can still override them by explicitly + + setting the flag. It is meant to be a convenience tool. + + + +This command will generate a `socket.json` file in the target cwd. + +You can choose to add this file to your repo (handy for collab) + +or to add it to the ignored files, or neither. This file is only + +used in CLI workflows. + + + +Note: For details on a flag you can run `socket <cmd> --help` + + + +? + +Which scan command do you want to configure? + +(Use arrow keys) + + +❯ socket scan create + + + socket scan github + + (cancel) + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/unit/lib/termless/animation.test.mts b/test/unit/lib/termless/animation.test.mts index 59a7e4084..b73aeace6 100644 --- a/test/unit/lib/termless/animation.test.mts +++ b/test/unit/lib/termless/animation.test.mts @@ -8,6 +8,7 @@ import { describe, expect, it, onTestFinished } from 'vitest' import { assertSamePixels, + assertSnapshotSvg, captureCheckpoint, createBlankCell, createRecording, @@ -128,17 +129,17 @@ describe('terminal animation recorder', () => { onTestFinished(async () => await terminal.close()) terminal.feed('top\r\n\r\nbottom') const checkpoint = await captureCheckpoint(terminal, 'trimmed') - expect(checkpoint.captured?.rows.length).toBe(5) + expect(checkpoint.captured.rows.length).toBe(5) expect( - checkpoint.captured?.rows[0]?.map(cell => cell.char).join(''), + checkpoint.captured.rows[0]?.map(cell => cell.char).join(''), ).toContain('top') expect( - checkpoint.captured?.rows[1]?.every( + checkpoint.captured.rows[1]?.every( cell => cell.char === '' || cell.char === ' ', ), ).toBe(true) expect( - checkpoint.captured?.rows[2]?.map(cell => cell.char).join(''), + checkpoint.captured.rows[2]?.map(cell => cell.char).join(''), ).toContain('bottom') expect(svgHeight(checkpoint.svg)).toBeLessThan( svgHeight(terminal.screenshotSvg({ fontSize: 14 })), @@ -156,20 +157,20 @@ describe('terminal animation recorder', () => { 'word\x1b[9;1H\x1b[44m \x1b[0m\x1b[11;1H😀\x1b[13;1H\x1b[?25h', ) const checkpoint = await captureCheckpoint(terminal, 'decorated') - expect(checkpoint.captured?.rows.length).toBe(14) - expect(checkpoint.captured?.rows[8]?.some(cell => cell.bg !== null)).toBe( + expect(checkpoint.captured.rows.length).toBe(14) + expect(checkpoint.captured.rows[8]?.some(cell => cell.bg !== null)).toBe( true, ) - const styledBlank = checkpoint.captured?.rows[8]?.find( + const styledBlank = checkpoint.captured.rows[8]?.find( cell => cell.bg !== null, ) expect(Object.isFrozen(styledBlank?.bg)).toBe(true) expect( - checkpoint.captured?.rows[10]?.some( + checkpoint.captured.rows[10]?.some( cell => cell.wide || cell.continuation, ), ).toBe(true) - expect(checkpoint.captured?.cursor.visible).toBe(true) + expect(checkpoint.captured.cursor.visible).toBe(true) expect(checkpoint.svg).not.toContain('text-decoration="underline"') }) @@ -182,8 +183,8 @@ describe('terminal animation recorder', () => { onTestFinished(async () => await terminal.close()) terminal.feed('\x1b[8;1H\x1b[?25h') const checkpoint = await captureCheckpoint(terminal, 'bottom-cursor') - expect(checkpoint.captured?.height).toBe(10) - expect(checkpoint.captured?.rows.length).toBe(8) + expect(checkpoint.captured.height).toBe(10) + expect(checkpoint.captured.rows.length).toBe(8) }) it('translates the visible cursor into absolute buffer coordinates after scrollback', async () => { @@ -196,7 +197,7 @@ describe('terminal animation recorder', () => { terminal.feed('one\r\ntwo\r\nthree\r\nfour\r\nfive') const checkpoint = await captureCheckpoint(terminal, 'scrolled-cursor') const scrollback = terminal.getScrollback() - expect(checkpoint.captured?.cursor.row).toBe( + expect(checkpoint.captured.cursor.row).toBe( scrollback.totalRows - scrollback.screenRows + terminal.getCursor().row, ) }) @@ -224,8 +225,8 @@ describe('terminal animation recorder', () => { ) expect(recording.checkpoints[0]!.svg).not.toContain('longer') expect(recording.checkpoints[0]!.svg).toContain('short') - expect(Object.isFrozen(first.captured?.rows[0])).toBe(true) - expect(Object.isFrozen(first.captured?.rows[0]?.[0])).toBe(true) + expect(Object.isFrozen(first.captured.rows[0])).toBe(true) + expect(Object.isFrozen(first.captured.rows[0]?.[0])).toBe(true) }) it('rejects reordered or deleted checkpoints against the declared sequence', async () => { @@ -235,16 +236,17 @@ describe('terminal animation recorder', () => { onTestFinished( async () => await rm(scratchDir, { recursive: true, force: true }), ) - const recording = createRecording([ - { - name: 'first', - svg: '', - }, - { - name: 'second', - svg: '', - }, - ]) + const terminal = createTerminal({ + backend: createXtermBackend(), + cols: 20, + rows: 8, + }) + onTestFinished(() => terminal.close()) + terminal.feed('first') + const first = await captureCheckpoint(terminal, 'first') + terminal.feed('\r\nsecond') + const second = await captureCheckpoint(terminal, 'second') + const recording = createRecording([first, second]) await expect( expectTerminalAnimation(recording, { @@ -265,20 +267,6 @@ describe('terminal animation recorder', () => { // The first resvg use may load the bundled font inventory on Windows. }, 30_000) - it('copies and freezes checkpoints when creating a recording', () => { - const source = { - name: 'first', - svg: '', - } - const recording = createRecording([source]) - source.svg = 'mutated' - expect(recording.checkpoints[0]?.svg).toBe( - '', - ) - expect(Object.isFrozen(recording.checkpoints[0])).toBe(true) - expect(Object.isFrozen(recording.checkpoints)).toBe(true) - }) - it('rejects a real raster pixel change', async () => { const rasterizer = await selectRasterizer('resvg') try { @@ -294,6 +282,22 @@ describe('terminal animation recorder', () => { await rasterizer.dispose?.() } }, 30_000) + + it('requires refreshing a snapshot when SVG source changes without pixel changes', async () => { + const svg = colorSvg('#ff0000') + const changedSvg = svg.replace(' + assertSnapshotSvg(svg, changedSvg, 'test/snapshots/termless/frame.svg'), + ).toThrow( + 'Terminal SVG snapshot is stale: test/snapshots/termless/frame.svg. Run pnpm run snapshots:termless:refresh and commit the updated snapshot.', + ) + } finally { + await rasterizer.dispose?.() + } + }, 30_000) }) function svgHeight(svg: string): number {