From 125770dfbec15763b50ecfba69b320dce032b848 Mon Sep 17 00:00:00 2001 From: Stavan Somaiya Date: Mon, 23 Nov 2026 10:21:58 +0530 Subject: [PATCH] test(KnightTour): add mutation-resistant invariants for OpenKnightTour (R50-T010) Fixes: #10 --- Backtracking/KnightTour.js | 6 +- Backtracking/tests/KnightTour.test.js | 92 +++++++++ work/R50-T010/README.md | 72 +++++++ work/R50-T010/check.py | 267 ++++++++++++++++++++++++++ work/R50-T010/commands.log | 18 ++ work/R50-T010/evidence.mjs | 155 +++++++++++++++ work/R50-T010/results.json | 172 +++++++++++++++++ work/R50-T010/task.json | 22 +++ work/R50-T010/versions.txt | 5 + work/R50-T010/vitest-focused.json | 36 ++++ 10 files changed, 844 insertions(+), 1 deletion(-) create mode 100644 work/R50-T010/README.md create mode 100644 work/R50-T010/check.py create mode 100644 work/R50-T010/commands.log create mode 100644 work/R50-T010/evidence.mjs create mode 100644 work/R50-T010/results.json create mode 100644 work/R50-T010/task.json create mode 100644 work/R50-T010/versions.txt create mode 100644 work/R50-T010/vitest-focused.json diff --git a/Backtracking/KnightTour.js b/Backtracking/KnightTour.js index 5f81ca345a..c0ed87a97d 100644 --- a/Backtracking/KnightTour.js +++ b/Backtracking/KnightTour.js @@ -50,7 +50,11 @@ class OpenKnightTour { if (this.board[y][x] === 0) { this.board[y][x] = curr + 1 if (this.solveHelper([y, x], curr + 1)) return true - // Backtracking: If the solution is not found, reset the cell to 0 + // Backtracking: If the solution is not found, reset the cell to 0. + // Protected condition (see tests/KnightTour.test.js): every number + // written during a failed branch is undone, so a failed solve() + // leaves an all-zero board and a successful one uses each of + // 1..size*size exactly once. this.board[y][x] = 0 } } diff --git a/Backtracking/tests/KnightTour.test.js b/Backtracking/tests/KnightTour.test.js index f7dc511df9..50c1ca60d4 100644 --- a/Backtracking/tests/KnightTour.test.js +++ b/Backtracking/tests/KnightTour.test.js @@ -35,3 +35,95 @@ describe('OpenKnightTour', () => { ]) }) }) + +// Mutation-resistant regressions for OpenKnightTour (KnightTour.js line 3). +// They check properties of the result instead of only one exact board, so a +// one-line mistake in the bounds check or in the backtracking reset fails. + +// Independent check: the board holds each of 1..n*n exactly once and every +// step k -> k + 1 is a knight move. Does not call any OpenKnightTour method. +const tourProblems = (board) => { + const n = board.length + const where = new Map() + board.forEach((row, y) => + row.forEach((value, x) => { + if (where.has(value)) where.set(value, null) + else where.set(value, [y, x]) + }) + ) + const problems = [] + for (let k = 1; k <= n * n; k++) { + if (!where.get(k)) problems.push(`value ${k} missing or repeated`) + } + for (let k = 1; k < n * n; k++) { + const a = where.get(k) + const b = where.get(k + 1) + if (!a || !b) continue + const dy = Math.abs(a[0] - b[0]) + const dx = Math.abs(a[1] - b[1]) + if (!((dy === 1 && dx === 2) || (dy === 2 && dx === 1))) { + problems.push(`step ${k} -> ${k + 1} is not a knight move`) + } + } + return problems +} + +describe('OpenKnightTour invariants', () => { + // Smallest valid input. solve() starts each search with curr = 0 and never + // numbers the starting square (line 38), so a 1x1 board cannot be filled. + it('smallest board 1x1: no tour found, board untouched', () => { + const KT = new OpenKnightTour(1) + expect(KT.solve()).toBe(false) + expect(KT.board).toEqual([[0]]) + }) + + // Protected condition: backtracking undoes every placement (line 58). + it('failed search on 3x3 leaves the board all zeros', () => { + const KT = new OpenKnightTour(3) + expect(KT.solve()).toBe(false) + expect(KT.board).toEqual([ + [0, 0, 0], + [0, 0, 0], + [0, 0, 0] + ]) + }) + + it('5x5 solution is a valid open tour using 1..25 once each', () => { + const KT = new OpenKnightTour(5) + expect(KT.solve()).toBe(true) + expect(tourProblems(KT.board)).toEqual([]) + }) + + // Protected condition: the bounds filter keeps row 0 and column 0 (line 25). + it('getMoves keeps moves onto row 0 and column 0', () => { + // From [1, 2] on 3x3 only [2, 0] and [0, 0] are on the board, + // in the order they appear in the move list (lines 12-21). + expect(new OpenKnightTour(3).getMoves([1, 2])).toEqual([ + [2, 0], + [0, 0] + ]) + expect(new OpenKnightTour(5).getMoves([0, 0])).toEqual([ + [2, 1], + [1, 2] + ]) + }) + + it('fresh equivalent instances give identical results', () => { + // No external state is involved (printBoard is not called), so two fresh + // 5x5 instances must produce the same explicit board. + const expectedBoard = [ + [19, 4, 15, 10, 25], + [14, 9, 18, 5, 16], + [1, 20, 3, 24, 11], + [8, 13, 22, 17, 6], + [21, 2, 7, 12, 23] + ] + const first = new OpenKnightTour(5) + const second = new OpenKnightTour(5) + expect(first.solve()).toBe(true) + expect(second.solve()).toBe(true) + expect(first.board).toEqual(expectedBoard) + expect(second.board).toEqual(expectedBoard) + expect(first.board).not.toBe(second.board) + }) +}) diff --git a/work/R50-T010/README.md b/work/R50-T010/README.md new file mode 100644 index 0000000000..f209e435aa --- /dev/null +++ b/work/R50-T010/README.md @@ -0,0 +1,72 @@ +# R50-T010 — Mutation-resistant tests for `OpenKnightTour` + +Source: `Backtracking/KnightTour.js`, `OpenKnightTour` (line 3). + +## Recorded contract (before any change) + +| Aspect | Observation | +| --------------------- | ---------------------------------------------------------------------------------------------------------- | +| Input | `size` (constructor) — a primitive, so there is no caller-owned input to mutate. | +| Output | `solve()` → boolean; `board` → `size × size` array of numbers, `0` = unvisited. | +| Ordering | `getMoves` returns in-bounds moves in the order of the move list (lines 12-21). | +| Mutation | `solve()` writes into the instance's own `board` only. | +| External dependencies | none (`printBoard` takes an injectable `output`, not used here). | +| Quirk kept as-is | `solve()` starts with `curr = 0` and never numbers the start square (line 38), so `n = 1` returns `false`. | + +## Fixture (expected outputs established independently) + +| Input | Expected | +| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `n = 1` (smallest) | `solve() === false`, board `[[0]]` (see quirk) | +| `n = 3` | `solve() === false` (the centre square is unreachable), board **all zeros** after the failed search | +| `n = 5` (ordinary) | `solve() === true`, board uses each of 1..25 once and every step k → k+1 is a knight move (checked by an independent helper that calls no `OpenKnightTour` method) | +| `getMoves([1, 2])` on 3×3 | `[[2, 0], [0, 0]]` — hand-checked against the 8 candidate moves | +| two fresh `OpenKnightTour(5)` | both `solve() === true` and both boards equal the explicit board `[[19,4,15,10,25],[14,9,18,5,16],[1,20,3,24,11],[8,13,22,17,6],[21,2,7,12,23]]`; the two board arrays are separate objects | + +Baseline: all of these expected values were written down from the source's contract and checked by +hand before running. They matched the unmodified implementation, so the implementation was not +changed (only a comment was added). + +## Mutants (applied to temporary copies by `check.py`; the source never contains them) + +| One-line mistake | Smallest input where original and mutant differ | Named assertion that fails (and why) | +| ----------------------------------------------------------- | ----------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Backtracking reset `this.board[y][x] = 0` deleted (line 58) | `n = 3`: original board all zeros, mutant `[[2,5,8],[7,0,3],[4,1,6]]` | `failed search on 3x3 leaves the board all zeros` — numbers from abandoned branches are never undone. On `n = 5` the mutant even returns `true` with repeated numbers, failing `5x5 solution is a valid open tour…`. | +| Lower row bound `y >= 0` → `y > 0` (line 25) | `n = 3`, `getMoves([1, 2])`: original `[[2,0],[0,0]]`, mutant `[[2,0]]` | `getMoves keeps moves onto row 0 and column 0` — row 0 becomes unreachable, so no 5×5 tour exists either. | + +An **equivalent** mutant was also tried and rejected: `x < this.size` → `x <= this.size`. The extra +column is never chosen because `board[y][size]` is `undefined`, not `0`, so behaviour is unchanged. + +The protected condition is documented next to the reset in `KnightTour.js` (lines 53-58). The final +implementation has no mutation and no test-only branch; only a comment was added. + +## Follow-up (not changed here) + +The `n = 1` result is arguably a defect (a one-square board trivially has a tour). Fixing it means +numbering the start square, which would change every board the existing 5×5 test pins, so it is out +of scope for this task. + +## How to run + +From the repository root: + +```sh +python3 work/R50-T010/check.py +``` + +`check.py` installs dependencies from `package-lock.json`, runs the focused test file, evaluates the fixture with `evidence.mjs` (input, expected, actual and source line for every case), runs each deliberate mutant in a temporary copy, and finally runs the repository test script in non-watch mode (`npm test`, which is `vitest run`). It exits non-zero if any assertion or step fails, and records every command it ran in `commands.log`. + +### Recorded run (files in this folder) + +| Step | Command | Result | +| ------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | +| Install from lockfile | `npm ci --ignore-scripts --no-audit --no-fund` (exit 0) | ok | +| Focused tests | `node_modules/.bin/vitest run Backtracking/tests/KnightTour.test.js --reporter=json --outputFile=work/R50-T010/vitest-focused.raw.json` | 7/7 passed | +| Fixture evidence | `node work/R50-T010/evidence.mjs` | 7/7 rows match | +| Mutant: backtracking reset removed | temporary copy | killed by `failed search on 3x3 leaves the board all zeros` | +| Mutant: lower row bound off by one (y > 0) | temporary copy | killed by `getMoves keeps moves onto row 0 and column 0` | +| Repository test script | `npm test -- --reporter=json --outputFile=work/R50-T010/vitest-full.raw.json` | 11975/11975 passed | + +Tool versions (`versions.txt`): python 3.12.10; node v26.13.1; npm 11.20.0; platform macOS-27.2.1-arm64-arm-64bit; vitest vitest/1.2.1 darwin-arm64 node-v26.13.1. + +Files: `results.json` (all of the above, machine-readable), `vitest-focused.json` (each focused test and its status), `commands.log`, `versions.txt`. diff --git a/work/R50-T010/check.py b/work/R50-T010/check.py new file mode 100644 index 0000000000..0c4fa2268a --- /dev/null +++ b/work/R50-T010/check.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python3 +"""Focused check runner for R50-T010. + +Run from the repository root: + + python3 work/R50-T010/check.py + +Steps (everything is recorded under work/R50-T010/): + 1. Record tool versions -> versions.txt + 2. Install dependencies from the lockfile -> `npm ci --ignore-scripts` + (set SKIP_INSTALL=1 to reuse an existing node_modules) + 3. Run the focused Vitest file(s) for this task; require a non-zero test + count and zero failures -> vitest-focused.json + 4. Run evidence.mjs: literal fixture inputs against the real source, with + input / expected / actual / source line -> results.json ("fixture") + 5. Run each deliberate mutant in a temporary copy (never in the real + source); require the named regression test to pass on the original and + fail on the mutant -> results.json ("mutants") + 6. Run the repository test script in non-watch mode + (`npm test` = `vitest run`); require a non-zero test count and zero + failures -> results.json ("full_suite") + +Every command actually executed is written to commands.log. The exit status +is non-zero if any step or assertion fails (or a step times out). +""" + +import json +import os +import platform +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent.parent +CONFIG = json.loads((HERE / 'task.json').read_text()) +TASK = CONFIG['task'] +VITEST = str(ROOT / 'node_modules' / '.bin' / 'vitest') +TIMEOUT_SECONDS = 600 + +failures = [] +log = [] + + +def show(text): + """Hide machine-specific absolute paths in recorded evidence.""" + text = text.replace(str(ROOT) + os.sep, '').replace(str(ROOT), '.') + return text.replace(tempfile.gettempdir(), '$TMPDIR') + + +def run(cmd, cwd=ROOT, check=False): + """Run a command, log it exactly, and never wait forever.""" + shown = show(' '.join(cmd)) + log.append('$ ' + shown) + try: + proc = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, + timeout=TIMEOUT_SECONDS) + except subprocess.TimeoutExpired: + log.append(f' -> timed out after {TIMEOUT_SECONDS}s') + failures.append(f'timed out: {shown}') + return subprocess.CompletedProcess(cmd, 124, '', 'timeout') + log.append(f' -> exit {proc.returncode}') + if check and proc.returncode != 0: + print(proc.stdout[-4000:]) + print(proc.stderr[-4000:], file=sys.stderr) + return proc + + +def version(cmd): + try: + return run(cmd).stdout.strip().splitlines()[0] + except Exception as exc: # best effort only + return f'unavailable ({exc})' + + +def test_list(report): + return [ + {'name': t.get('fullName') or t.get('title'), 'status': t.get('status')} + for suite in report.get('testResults', []) + for t in suite.get('assertionResults', []) + ] + + +def read_report(proc, out): + if not out.exists(): + print(proc.stdout[-4000:]) + print(proc.stderr[-4000:], file=sys.stderr) + return None + report = json.loads(out.read_text()) + out.unlink() + return report + + +def summary(cmd, proc, report): + return { + 'command': show(' '.join(cmd)), + 'exit': proc.returncode, + 'total': report and report['numTotalTests'], + 'passed': report and report['numPassedTests'], + 'failed': report and report['numFailedTests'] + } + + +def require_green(label, info, report): + if info['exit'] != 0 or not report or report['numTotalTests'] == 0 or \ + report['numFailedTests'] != 0: + failures.append(f'{label} failed: {info}') + if report: + failures.extend(' failed: ' + t['name'] + for t in test_list(report) + if t['status'] == 'failed') + + +def main(): + results = {'task': TASK} + + # 1. Tool versions + versions = { + 'python': platform.python_version(), + 'node': version(['node', '--version']), + 'npm': version(['npm', '--version']), + 'platform': platform.platform() + } + + # 2. Install from the lockfile + if os.environ.get('SKIP_INSTALL') == '1': + results['install'] = 'skipped (SKIP_INSTALL=1)' + else: + cmd = ['npm', 'ci', '--ignore-scripts', '--no-audit', '--no-fund'] + proc = run(cmd, check=True) + results['install'] = {'command': ' '.join(cmd), + 'exit': proc.returncode} + if proc.returncode != 0: + failures.append('npm ci failed') + return finish(results, versions) + versions['vitest'] = version([VITEST, '--version']) + + # 3. Focused tests + out = HERE / 'vitest-focused.raw.json' + cmd = [VITEST, 'run', *CONFIG['focused_tests'], '--reporter=json', + f'--outputFile={out}'] + proc = run(cmd) + focused_report = read_report(proc, out) + results['focused_tests'] = summary(cmd, proc, focused_report) + require_green('focused tests', results['focused_tests'], focused_report) + if focused_report: + (HERE / 'vitest-focused.json').write_text(json.dumps({ + 'command': results['focused_tests']['command'], + 'numTotalTests': focused_report['numTotalTests'], + 'numPassedTests': focused_report['numPassedTests'], + 'numFailedTests': focused_report['numFailedTests'], + 'tests': test_list(focused_report) + }, indent=2) + '\n') + + # 4. Fixture evidence (input / expected / actual / source line) + proc = run(['node', str(HERE / 'evidence.mjs')]) + rows = [] + if proc.returncode != 0: + failures.append('evidence.mjs crashed: ' + show(proc.stderr[-2000:])) + else: + rows = json.loads(proc.stdout) + results['fixture'] = rows + for row in rows: + print(f"[{'PASS' if row['pass'] else 'FAIL'}] {row['name']}") + print(f" input: {json.dumps(row['input'])}") + print(f" expected: {json.dumps(row['expected'])}") + print(f" actual: {json.dumps(row['actual'])}") + if row.get('precondition'): + print(f" source: {row['precondition']}") + if not row['pass']: + failures.append(f"fixture mismatch: {row['name']}") + if not rows: + failures.append('no fixture rows were produced') + + # 5. Deliberate mutants, in temporary copies only + original_tests = test_list(focused_report) if focused_report else [] + mutants = [run_mutant(m, original_tests) for m in CONFIG.get('mutants', [])] + if mutants: + results['mutants'] = mutants + + # 6. Repository test script in non-watch mode: `npm test` (vitest run) + out = HERE / 'vitest-full.raw.json' + cmd = ['npm', 'test', '--', '--reporter=json', f'--outputFile={out}'] + proc = run(cmd) + full_report = read_report(proc, out) + results['full_suite'] = summary(cmd, proc, full_report) + require_green('repository test script', results['full_suite'], full_report) + + return finish(results, versions) + + +def run_mutant(mutant, original_tests): + """Copy the source and its tests into a temp dir, apply one edit there, + and require the named test to pass on the original and fail here.""" + original = (ROOT / mutant['file']).read_text() + named = [t for t in original_tests if mutant['must_fail'] in t['name']] + entry = { + 'name': mutant['name'], + 'file': mutant['file'], + 'edit': {'from': mutant['find'], 'to': mutant['replace']}, + 'named_test': mutant['must_fail'], + 'named_test_on_original': [t['status'] for t in named], + 'killed': False + } + if len(named) != 1 or named[0]['status'] != 'passed': + failures.append(f"mutant {mutant['name']}: named test must match " + f"exactly one passing test on the original") + return entry + if original.count(mutant['find']) != 1: + failures.append(f"mutant {mutant['name']}: edit must match once") + return entry + with tempfile.TemporaryDirectory(prefix=f'{TASK}-mutant-') as tmp: + tmp = Path(tmp) + for rel in [mutant['file'], *mutant['tests']]: + dest = tmp / rel + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copy(ROOT / rel, dest) + (tmp / mutant['file']).write_text( + original.replace(mutant['find'], mutant['replace'])) + out = tmp / 'mutant-report.json' + cmd = [VITEST, 'run', *mutant['tests'], '--root', str(tmp), + '--globals', '--reporter=json', f'--outputFile={out}'] + proc = run(cmd) + report = read_report(proc, out) + failed = [t['name'] for t in test_list(report) + if t['status'] == 'failed'] if report else [] + entry['exit'] = proc.returncode + entry['failed_tests_on_mutant'] = failed + entry['killed'] = proc.returncode != 0 and any( + mutant['must_fail'] in name for name in failed) + print(f"[{'KILLED' if entry['killed'] else 'SURVIVED'}] mutant " + f"{mutant['name']}: {mutant['find']!r} -> {mutant['replace']!r}") + for name in failed: + print(f' failed: {name}') + if not entry['killed']: + failures.append(f"mutant {mutant['name']} was not detected by " + f"'{mutant['must_fail']}'") + return entry + + +def finish(results, versions): + results['ok'] = not failures + results['failures'] = failures + (HERE / 'versions.txt').write_text( + ''.join(f'{k}: {v}\n' for k, v in versions.items())) + (HERE / 'results.json').write_text(json.dumps(results, indent=2) + '\n') + (HERE / 'commands.log').write_text('\n'.join(log) + '\n') + print() + for key, label in [('focused_tests', 'focused tests'), + ('full_suite', 'npm test')]: + if key in results: + info = results[key] + print(f"{label + ':':15}{info['passed']}/{info['total']} passed" + f" ({info['command']})") + if failures: + print('\nFAILED:') + for item in failures: + print(' - ' + item) + return 1 + print(f'\n{TASK}: all checks passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/work/R50-T010/commands.log b/work/R50-T010/commands.log new file mode 100644 index 0000000000..b69ed733e5 --- /dev/null +++ b/work/R50-T010/commands.log @@ -0,0 +1,18 @@ +$ node --version + -> exit 0 +$ npm --version + -> exit 0 +$ npm ci --ignore-scripts --no-audit --no-fund + -> exit 0 +$ node_modules/.bin/vitest --version + -> exit 0 +$ node_modules/.bin/vitest run Backtracking/tests/KnightTour.test.js --reporter=json --outputFile=work/R50-T010/vitest-focused.raw.json + -> exit 0 +$ node work/R50-T010/evidence.mjs + -> exit 0 +$ node_modules/.bin/vitest run Backtracking/tests/KnightTour.test.js --root $TMPDIR/R50-T010-mutant-uiksrn7f --globals --reporter=json --outputFile=$TMPDIR/R50-T010-mutant-uiksrn7f/mutant-report.json + -> exit 1 +$ node_modules/.bin/vitest run Backtracking/tests/KnightTour.test.js --root $TMPDIR/R50-T010-mutant-yl6skk01 --globals --reporter=json --outputFile=$TMPDIR/R50-T010-mutant-yl6skk01/mutant-report.json + -> exit 1 +$ npm test -- --reporter=json --outputFile=work/R50-T010/vitest-full.raw.json + -> exit 0 diff --git a/work/R50-T010/evidence.mjs b/work/R50-T010/evidence.mjs new file mode 100644 index 0000000000..1666ead49e --- /dev/null +++ b/work/R50-T010/evidence.mjs @@ -0,0 +1,155 @@ +// R50-T010 evidence: fixture results for OpenKnightTour on the real source and +// on two in-memory mutants (the file on disk is never changed). +import { readFileSync } from 'fs' +import { OpenKnightTour } from '../../Backtracking/KnightTour.js' + +const SRC = 'KnightTour.js' +const same = (a, b) => JSON.stringify(a) === JSON.stringify(b) + +const source = readFileSync( + new URL('../../Backtracking/KnightTour.js', import.meta.url), + 'utf8' +) +const loadVariant = async (find, replace) => { + if (!source.includes(find)) throw new Error(`pattern not found: ${find}`) + const code = source.replace(find, replace) + return (await import('data:text/javascript,' + encodeURIComponent(code))) + .OpenKnightTour +} +const NoReset = await loadVariant(' this.board[y][x] = 0\n', '') +const RowOff = await loadVariant( + 'y >= 0 && y < this.size', + 'y > 0 && y < this.size' +) + +// Same independent tour check as the Vitest file. +const tourProblems = (board) => { + const n = board.length + const where = new Map() + board.forEach((row, y) => + row.forEach((v, x) => where.set(v, where.has(v) ? null : [y, x])) + ) + let problems = 0 + for (let k = 1; k <= n * n; k++) if (!where.get(k)) problems++ + for (let k = 1; k < n * n; k++) { + const a = where.get(k) + const b = where.get(k + 1) + if (!a || !b) continue + const d = [Math.abs(a[0] - b[0]), Math.abs(a[1] - b[1])].sort().join() + if (d !== '1,2') problems++ + } + return problems +} + +const solveRun = (Cls, n) => { + const kt = new Cls(n) + const solved = kt.solve() + return { + solved, + board: kt.board, + tourProblems: solved ? tourProblems(kt.board) : null + } +} + +const rows = [] +const add = (name, input, expected, actual, precondition) => + rows.push({ + name, + input, + expected, + actual, + pass: same(expected, actual), + precondition + }) + +// Original implementation: must satisfy the expected outputs. +add( + 'original: smallest board n = 1', + 1, + { solved: false, board: [[0]], tourProblems: null }, + solveRun(OpenKnightTour, 1), + `${SRC}:38 start square is not numbered (curr = 0)` +) +add( + 'original: n = 3 failed search leaves zeros', + 3, + { + solved: false, + board: [ + [0, 0, 0], + [0, 0, 0], + [0, 0, 0] + ], + tourProblems: null + }, + solveRun(OpenKnightTour, 3), + `${SRC}:58 backtracking reset` +) +const five = solveRun(OpenKnightTour, 5) +add( + 'original: n = 5 is a valid tour', + 5, + { solved: true, tourProblems: 0 }, + { solved: five.solved, tourProblems: five.tourProblems }, + `${SRC}:24-26 in-bounds moves only; :58 reset` +) +add( + 'original: getMoves([1, 2]) on 3x3', + [3, [1, 2]], + [ + [2, 0], + [0, 0] + ], + new OpenKnightTour(3).getMoves([1, 2]), + `${SRC}:25 y >= 0 keeps row 0` +) + +// Mutants: these rows record how each mutant differs from the expected +// output. `pass` here means "the mutant was distinguished". +const mutantRow = ( + name, + input, + expectedForOriginal, + mutantActual, + precondition +) => + rows.push({ + name, + input, + expected: { differsFrom: expectedForOriginal }, + actual: mutantActual, + pass: !same(expectedForOriginal, mutantActual), + precondition + }) +const m3 = solveRun(NoReset, 3) +mutantRow( + 'mutant (no reset): n = 3 board', + 3, + [ + [0, 0, 0], + [0, 0, 0], + [0, 0, 0] + ], + m3.board, + `${SRC}:58 removed` +) +const m5 = solveRun(NoReset, 5) +mutantRow( + 'mutant (no reset): n = 5 tour problems', + 5, + 0, + m5.tourProblems, + `${SRC}:58 removed` +) +mutantRow( + 'mutant (y > 0): getMoves([1, 2]) on 3x3', + [3, [1, 2]], + [ + [2, 0], + [0, 0] + ], + new RowOff(3).getMoves([1, 2]), + `${SRC}:25 changed` +) + +console.log(JSON.stringify(rows)) diff --git a/work/R50-T010/results.json b/work/R50-T010/results.json new file mode 100644 index 0000000000..69eda694d7 --- /dev/null +++ b/work/R50-T010/results.json @@ -0,0 +1,172 @@ +{ + "task": "R50-T010", + "install": { + "command": "npm ci --ignore-scripts --no-audit --no-fund", + "exit": 0 + }, + "focused_tests": { + "command": "node_modules/.bin/vitest run Backtracking/tests/KnightTour.test.js --reporter=json --outputFile=work/R50-T010/vitest-focused.raw.json", + "exit": 0, + "total": 7, + "passed": 7, + "failed": 0 + }, + "fixture": [ + { + "name": "original: smallest board n = 1", + "input": 1, + "expected": { + "solved": false, + "board": [[0]], + "tourProblems": null + }, + "actual": { + "solved": false, + "board": [[0]], + "tourProblems": null + }, + "pass": true, + "precondition": "KnightTour.js:38 start square is not numbered (curr = 0)" + }, + { + "name": "original: n = 3 failed search leaves zeros", + "input": 3, + "expected": { + "solved": false, + "board": [ + [0, 0, 0], + [0, 0, 0], + [0, 0, 0] + ], + "tourProblems": null + }, + "actual": { + "solved": false, + "board": [ + [0, 0, 0], + [0, 0, 0], + [0, 0, 0] + ], + "tourProblems": null + }, + "pass": true, + "precondition": "KnightTour.js:58 backtracking reset" + }, + { + "name": "original: n = 5 is a valid tour", + "input": 5, + "expected": { + "solved": true, + "tourProblems": 0 + }, + "actual": { + "solved": true, + "tourProblems": 0 + }, + "pass": true, + "precondition": "KnightTour.js:24-26 in-bounds moves only; :58 reset" + }, + { + "name": "original: getMoves([1, 2]) on 3x3", + "input": [3, [1, 2]], + "expected": [ + [2, 0], + [0, 0] + ], + "actual": [ + [2, 0], + [0, 0] + ], + "pass": true, + "precondition": "KnightTour.js:25 y >= 0 keeps row 0" + }, + { + "name": "mutant (no reset): n = 3 board", + "input": 3, + "expected": { + "differsFrom": [ + [0, 0, 0], + [0, 0, 0], + [0, 0, 0] + ] + }, + "actual": [ + [2, 5, 8], + [7, 0, 3], + [4, 1, 6] + ], + "pass": true, + "precondition": "KnightTour.js:58 removed" + }, + { + "name": "mutant (no reset): n = 5 tour problems", + "input": 5, + "expected": { + "differsFrom": 0 + }, + "actual": 11, + "pass": true, + "precondition": "KnightTour.js:58 removed" + }, + { + "name": "mutant (y > 0): getMoves([1, 2]) on 3x3", + "input": [3, [1, 2]], + "expected": { + "differsFrom": [ + [2, 0], + [0, 0] + ] + }, + "actual": [[2, 0]], + "pass": true, + "precondition": "KnightTour.js:25 changed" + } + ], + "mutants": [ + { + "name": "backtracking reset removed", + "file": "Backtracking/KnightTour.js", + "edit": { + "from": " this.board[y][x] = 0\n", + "to": "" + }, + "named_test": "failed search on 3x3 leaves the board all zeros", + "named_test_on_original": ["passed"], + "killed": true, + "exit": 1, + "failed_tests_on_mutant": [ + " OpenKnightTour OpenKnightTour(5)", + " OpenKnightTour invariants failed search on 3x3 leaves the board all zeros", + " OpenKnightTour invariants 5x5 solution is a valid open tour using 1..25 once each", + " OpenKnightTour invariants fresh equivalent instances give identical results" + ] + }, + { + "name": "lower row bound off by one (y > 0)", + "file": "Backtracking/KnightTour.js", + "edit": { + "from": "([y, x]) => y >= 0 && y < this.size", + "to": "([y, x]) => y > 0 && y < this.size" + }, + "named_test": "getMoves keeps moves onto row 0 and column 0", + "named_test_on_original": ["passed"], + "killed": true, + "exit": 1, + "failed_tests_on_mutant": [ + " OpenKnightTour OpenKnightTour(5)", + " OpenKnightTour invariants 5x5 solution is a valid open tour using 1..25 once each", + " OpenKnightTour invariants getMoves keeps moves onto row 0 and column 0", + " OpenKnightTour invariants fresh equivalent instances give identical results" + ] + } + ], + "full_suite": { + "command": "npm test -- --reporter=json --outputFile=work/R50-T010/vitest-full.raw.json", + "exit": 0, + "total": 11975, + "passed": 11975, + "failed": 0 + }, + "ok": true, + "failures": [] +} diff --git a/work/R50-T010/task.json b/work/R50-T010/task.json new file mode 100644 index 0000000000..2133bf160e --- /dev/null +++ b/work/R50-T010/task.json @@ -0,0 +1,22 @@ +{ + "task": "R50-T010", + "focused_tests": ["Backtracking/tests/KnightTour.test.js"], + "mutants": [ + { + "name": "backtracking reset removed", + "file": "Backtracking/KnightTour.js", + "find": " this.board[y][x] = 0\n", + "replace": "", + "tests": ["Backtracking/tests/KnightTour.test.js"], + "must_fail": "failed search on 3x3 leaves the board all zeros" + }, + { + "name": "lower row bound off by one (y > 0)", + "file": "Backtracking/KnightTour.js", + "find": "([y, x]) => y >= 0 && y < this.size", + "replace": "([y, x]) => y > 0 && y < this.size", + "tests": ["Backtracking/tests/KnightTour.test.js"], + "must_fail": "getMoves keeps moves onto row 0 and column 0" + } + ] +} diff --git a/work/R50-T010/versions.txt b/work/R50-T010/versions.txt new file mode 100644 index 0000000000..b405ff9cb4 --- /dev/null +++ b/work/R50-T010/versions.txt @@ -0,0 +1,5 @@ +python: 3.12.10 +node: v26.13.1 +npm: 11.20.0 +platform: macOS-27.2.1-arm64-arm-64bit +vitest: vitest/1.2.1 darwin-arm64 node-v26.13.1 diff --git a/work/R50-T010/vitest-focused.json b/work/R50-T010/vitest-focused.json new file mode 100644 index 0000000000..234c4b929c --- /dev/null +++ b/work/R50-T010/vitest-focused.json @@ -0,0 +1,36 @@ +{ + "command": "node_modules/.bin/vitest run Backtracking/tests/KnightTour.test.js --reporter=json --outputFile=work/R50-T010/vitest-focused.raw.json", + "numTotalTests": 7, + "numPassedTests": 7, + "numFailedTests": 0, + "tests": [ + { + "name": " OpenKnightTour OpenKnightTour(5)", + "status": "passed" + }, + { + "name": " OpenKnightTour OpenKnightTour(2)", + "status": "passed" + }, + { + "name": " OpenKnightTour invariants smallest board 1x1: no tour found, board untouched", + "status": "passed" + }, + { + "name": " OpenKnightTour invariants failed search on 3x3 leaves the board all zeros", + "status": "passed" + }, + { + "name": " OpenKnightTour invariants 5x5 solution is a valid open tour using 1..25 once each", + "status": "passed" + }, + { + "name": " OpenKnightTour invariants getMoves keeps moves onto row 0 and column 0", + "status": "passed" + }, + { + "name": " OpenKnightTour invariants fresh equivalent instances give identical results", + "status": "passed" + } + ] +}