From 2edbea66125b0d6779d9b16fa1be7d1d8af40bbb Mon Sep 17 00:00:00 2001 From: Stavan Somaiya Date: Mon, 23 Nov 2026 10:12:15 +0530 Subject: [PATCH] test(OddEvenSort): add seeded invariant tests for swap (R50-T004) Fixes: #4 --- Sorts/OddEvenSort.js | 29 +++- Sorts/test/OddEvenSort.test.js | 127 +++++++++++++- work/R50-T004/README.md | 86 ++++++++++ work/R50-T004/check.py | 267 ++++++++++++++++++++++++++++++ work/R50-T004/commands.log | 18 ++ work/R50-T004/evidence.mjs | 84 ++++++++++ work/R50-T004/results.json | 182 ++++++++++++++++++++ work/R50-T004/task.json | 22 +++ work/R50-T004/versions.txt | 5 + work/R50-T004/vitest-focused.json | 76 +++++++++ 10 files changed, 893 insertions(+), 3 deletions(-) create mode 100644 work/R50-T004/README.md create mode 100644 work/R50-T004/check.py create mode 100644 work/R50-T004/commands.log create mode 100644 work/R50-T004/evidence.mjs create mode 100644 work/R50-T004/results.json create mode 100644 work/R50-T004/task.json create mode 100644 work/R50-T004/versions.txt create mode 100644 work/R50-T004/vitest-focused.json diff --git a/Sorts/OddEvenSort.js b/Sorts/OddEvenSort.js index f8eba7c474..792fd7cfe5 100644 --- a/Sorts/OddEvenSort.js +++ b/Sorts/OddEvenSort.js @@ -6,13 +6,38 @@ for more information : https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort */ -// Helper function to swap array items -function swap(arr, i, j) { +/** + * Helper function to swap array items in place. + * + * Invariant: a swap only exchanges two positions, so the multiset of values + * in `arr` (every value and how many times it occurs) never changes. + * This is what lets oddEvenSort return a permutation of its input. + * + * @param {Array} arr array to modify in place + * @param {number} i first index + * @param {number} j second index + * @returns {undefined} nothing; `arr` is mutated + * @example const a = [3, 1, 2]; swap(a, 0, 1) // a is now [1, 3, 2] + */ +export function swap(arr, i, j) { const tmp = arr[i] arr[i] = arr[j] arr[j] = tmp } +/** + * Sorts `arr` in ascending order, in place, and returns the same array. + * + * Invariants checked by the tests: + * - the result is ordered: result[k] <= result[k + 1] for every k; + * - the result has the same multiset of values as the input (only `swap` + * moves values); + * - the returned array is the input array (`oddEvenSort(a) === a`). + * + * @param {number[]} arr array of mutually comparable numbers + * @returns {number[]} the same array, now sorted ascending + * @example oddEvenSort([3, 1, 2]) // [1, 2, 3] + */ export function oddEvenSort(arr) { let sorted = false while (!sorted) { diff --git a/Sorts/test/OddEvenSort.test.js b/Sorts/test/OddEvenSort.test.js index 6d75851e5e..efc98f9b56 100644 --- a/Sorts/test/OddEvenSort.test.js +++ b/Sorts/test/OddEvenSort.test.js @@ -1,4 +1,4 @@ -import { oddEvenSort } from '../OddEvenSort' +import { oddEvenSort, swap } from '../OddEvenSort' test('The OddEvenSort of the array [5, 4, 3, 2, 1] is [1, 2, 3, 4, 5]', () => { const arr = [5, 4, 3, 2, 1] @@ -23,3 +23,128 @@ test('The OddEvenSort of the array [166, 169, 144] is [144, 166, 169]', () => { const res = oddEvenSort(arr) expect(res).toEqual([144, 166, 169]) }) + +// Invariant tests for swap (OddEvenSort.js line 22) and the sort built on it. +// Domain (JSDoc at lines 28-40, comparisons at lines 46 and 52): arrays of mutually +// comparable numbers. The generator only produces finite integers. + +// Small deterministic PRNG (mulberry32) so every run sees the same cases. +const mulberry32 = (seed) => () => { + seed = (seed + 0x6d2b79f5) | 0 + let t = Math.imul(seed ^ (seed >>> 15), 1 | seed) + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t + return ((t ^ (t >>> 14)) >>> 0) / 4294967296 +} + +const SEED = 20261123 +const generateCases = (count) => { + const random = mulberry32(SEED) + const cases = [] + for (let n = 0; n < count; n++) { + const length = Math.floor(random() * 13) // 0..12 items + const values = [] + for (let k = 0; k < length; k++) { + values.push(Math.floor(random() * 11) - 5) // -5..5, repeats likely + } + cases.push(values) + } + return cases +} + +const isOrdered = (arr) => arr.every((v, k) => k === 0 || arr[k - 1] <= v) +const counts = (arr) => { + const map = new Map() + for (const v of arr) map.set(v, (map.get(v) || 0) + 1) + return [...map.entries()].sort((a, b) => a[0] - b[0]) +} + +describe('swap invariant', () => { + test('swap exchanges two positions in place and returns undefined', () => { + const arr = [3, 1, 2] + expect(swap(arr, 0, 1)).toBeUndefined() + expect(arr).toEqual([1, 3, 2]) + }) + + test('swap preserves multiplicities', () => { + const arr = [2, 2, 1] + swap(arr, 1, 2) + expect(arr).toEqual([2, 1, 2]) + expect(counts(arr)).toEqual([ + [1, 1], + [2, 2] + ]) + }) +}) + +describe('oddEvenSort fixture (ascending, in place)', () => { + test.each([ + [ + [3, 1, 2], + [1, 2, 3] + ], + [ + [2, 2, 1], + [1, 2, 2] + ], + [ + [1, 2, 3], + [1, 2, 3] + ], + [ + [3, 2, 1], + [1, 2, 3] + ], + [[], []], + [[7], [7]] + ])('oddEvenSort(%j) is %j and returns the same array', (input, expected) => { + const arr = [...input] + const result = oddEvenSort(arr) + expect(result).toEqual(expected) + expect(result).toBe(arr) + }) +}) + +describe('oddEvenSort properties over 100 seeded cases', () => { + const cases = generateCases(100) + + // On failure, report the shortest failing input so it stays readable. + const smallestFailing = (fails) => + cases.filter(fails).sort((a, b) => a.length - b.length)[0] + + test('the generator is deterministic for a fixed seed', () => { + expect(cases.length).toBe(100) + // Pinned literal values for seed 20261123 (first case and two readable + // small cases, one with a repeated value). + expect(cases[0]).toEqual([4, 0, -1, -2, 0, -1, -5, 1, -4, 0, -3]) + expect(cases[10]).toEqual([-2, 5, 5]) + expect(cases[33]).toEqual([3, 5, -2]) + // The smallest supported collection (empty) is generated 4 times. + expect(cases.filter((c) => c.length === 0).length).toBe(4) + }) + + test('readable small generated cases sort as expected', () => { + expect(oddEvenSort([...cases[10]])).toEqual([-2, 5, 5]) + expect(oddEvenSort([...cases[33]])).toEqual([-2, 3, 5]) + }) + + test('output is ordered', () => { + const failing = smallestFailing((c) => !isOrdered(oddEvenSort([...c]))) + expect(failing).toBeUndefined() + }) + + test('output preserves input multiplicities', () => { + const failing = smallestFailing( + (c) => + JSON.stringify(counts(oddEvenSort([...c]))) !== + JSON.stringify(counts(c)) + ) + expect(failing).toBeUndefined() + }) + + test('output is the input array, mutated in place', () => { + for (const c of cases) { + const arr = [...c] + expect(oddEvenSort(arr)).toBe(arr) + } + }) +}) diff --git a/work/R50-T004/README.md b/work/R50-T004/README.md new file mode 100644 index 0000000000..c23081b68e --- /dev/null +++ b/work/R50-T004/README.md @@ -0,0 +1,86 @@ +# R50-T004 — Invariant tests for `swap` (Odd–Even Sort) + +Source: `Sorts/OddEvenSort.js`, `swap` (line 22 after this change; line 10 at pinned commit `5c39e87`). + +## Recorded contract (before any change) + +| Aspect | `swap(arr, i, j)` | `oddEvenSort(arr)` | +| --------------------- | ---------------------------------------- | -------------------------------------------------------- | +| Inputs | array, two indices | array of mutually comparable numbers (compared with `>`) | +| Result | `undefined` | the **same** array, sorted ascending (`return arr`) | +| Mutation | exchanges `arr[i]` and `arr[j]` in place | sorts `arr` in place | +| External dependencies | none | none | + +`swap` is now exported (with JSDoc) so the invariant can be tested directly. The sort keeps its +ascending interface; no descending mode exists in the source. + +## Invariant and why it holds + +`swap` only exchanges two positions, so the multiset of values (each value and its count) never +changes. `oddEvenSort` moves values **only** through `swap`, and stops only when a full odd pass and a +full even pass make no swap, i.e. no adjacent pair is out of order. Hence the output is: + +1. ordered: `out[k] <= out[k + 1]`; +2. a permutation of the input (same multiplicities); +3. the input array itself (`oddEvenSort(a) === a`). + +## Fixture (expected values written before running) + +| Input | Expected | +| --------------- | ----------- | +| `[3, 1, 2]` | `[1, 2, 3]` | +| `[2, 2, 1]` | `[1, 2, 2]` | +| `[1, 2, 3]` | `[1, 2, 3]` | +| `[3, 2, 1]` | `[1, 2, 3]` | +| `[]` (smallest) | `[]` | +| `[7]` | `[7]` | + +`swap([3, 1, 2], 0, 1)` → array becomes `[1, 3, 2]`, returns `undefined`. + +## Generator + +100 cases from a mulberry32 PRNG with fixed seed `20261123`; length 0..12, integers -5..5, so +repeated values are common (62 of the 100 cases contain a repeat) and the smallest supported +collection `[]` appears 4 times. Only finite integers are generated. `NaN`, mixed types and holes +are outside the comparable-number domain (`>` comparisons at lines 46 and 52), so the generator +never produces them. + +The test pins literal generated values so determinism is asserted against explicit expectations: +case 0 is `[4, 0, -1, -2, 0, -1, -5, 1, -4, 0, -3]`. Two readable small cases are retained with +explicit sorted outputs: case 10 `[-2, 5, 5]` → `[-2, 5, 5]` and case 33 `[3, 5, -2]` → +`[-2, 3, 5]`. If a property ever fails, the test reports the shortest failing input. + +## Deliberately broken copies (temporary directory only) + +| Mutant | Smallest readable failing case | Named assertion that fails | +| ------------------------------------------ | ------------------------------ | --------------------------------------- | +| `swap`: `arr[j] = tmp` → `arr[j] = arr[i]` | `[2, 1]` → `[1, 1]` | `output preserves input multiplicities` | +| even pass no longer sets `sorted = false` | `[3, 1, 2]` → `[1, 3, 2]` | `output is ordered` | + +Both mutants are applied by `check.py` to copies in a temp dir; the real source is never edited. +Baseline: all fixture values and both properties held on the unmodified implementation; no defect. + +## How to run + +From the repository root: + +```sh +python3 work/R50-T004/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 Sorts/test/OddEvenSort.test.js --reporter=json --outputFile=work/R50-T004/vitest-focused.raw.json` | 17/17 passed | +| Fixture evidence | `node work/R50-T004/evidence.mjs` | 8/8 rows match | +| Mutant: swap loses a value (arr[j] = arr[i]) | temporary copy | killed by `output preserves input multiplicities` | +| Mutant: even pass no longer clears the sorted flag | temporary copy | killed by `output is ordered` | +| Repository test script | `npm test -- --reporter=json --outputFile=work/R50-T004/vitest-full.raw.json` | 11983/11983 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-T004/check.py b/work/R50-T004/check.py new file mode 100644 index 0000000000..45d2640153 --- /dev/null +++ b/work/R50-T004/check.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python3 +"""Focused check runner for R50-T004. + +Run from the repository root: + + python3 work/R50-T004/check.py + +Steps (everything is recorded under work/R50-T004/): + 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-T004/commands.log b/work/R50-T004/commands.log new file mode 100644 index 0000000000..717e64b18a --- /dev/null +++ b/work/R50-T004/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 Sorts/test/OddEvenSort.test.js --reporter=json --outputFile=work/R50-T004/vitest-focused.raw.json + -> exit 0 +$ node work/R50-T004/evidence.mjs + -> exit 0 +$ node_modules/.bin/vitest run Sorts/test/OddEvenSort.test.js --root $TMPDIR/R50-T004-mutant-9udzchl_ --globals --reporter=json --outputFile=$TMPDIR/R50-T004-mutant-9udzchl_/mutant-report.json + -> exit 1 +$ node_modules/.bin/vitest run Sorts/test/OddEvenSort.test.js --root $TMPDIR/R50-T004-mutant-8tpryuo6 --globals --reporter=json --outputFile=$TMPDIR/R50-T004-mutant-8tpryuo6/mutant-report.json + -> exit 1 +$ npm test -- --reporter=json --outputFile=work/R50-T004/vitest-full.raw.json + -> exit 0 diff --git a/work/R50-T004/evidence.mjs b/work/R50-T004/evidence.mjs new file mode 100644 index 0000000000..8db635d90f --- /dev/null +++ b/work/R50-T004/evidence.mjs @@ -0,0 +1,84 @@ +// Evaluates the R50-T004 fixture and the seeded property run against the real +// source and prints JSON rows. Expected outputs were written before running. +import { oddEvenSort, swap } from '../../Sorts/OddEvenSort.js' + +const SRC = 'OddEvenSort.js' +const fixture = [ + [ + [3, 1, 2], + [1, 2, 3] + ], + [ + [2, 2, 1], + [1, 2, 2] + ], + [ + [1, 2, 3], + [1, 2, 3] + ], + [ + [3, 2, 1], + [1, 2, 3] + ], + [[], []], + [[7], [7]] +] + +const rows = fixture.map(([input, expected]) => { + const arr = [...input] + const result = oddEvenSort(arr) + const same = result === arr + return { + name: `oddEvenSort(${JSON.stringify(input)})`, + input, + expected: { result: expected, returnsSameArray: true }, + actual: { result, returnsSameArray: same }, + pass: JSON.stringify(result) === JSON.stringify(expected) && same, + precondition: `${SRC}:41 ascending, in place, returns arr (line 58)` + } +}) + +const a = [3, 1, 2] +const ret = swap(a, 0, 1) +rows.push({ + name: 'swap([3, 1, 2], 0, 1)', + input: [[3, 1, 2], 0, 1], + expected: { arr: [1, 3, 2], returned: 'undefined' }, + actual: { arr: a, returned: String(ret) }, + pass: JSON.stringify(a) === '[1,3,2]' && ret === undefined, + precondition: `${SRC}:22-26 swap mutates arr, returns nothing` +}) + +// Seeded property run (same generator as the Vitest file). +const mulberry32 = (seed) => () => { + seed = (seed + 0x6d2b79f5) | 0 + let t = Math.imul(seed ^ (seed >>> 15), 1 | seed) + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t + return ((t ^ (t >>> 14)) >>> 0) / 4294967296 +} +const random = mulberry32(20261123) +const counts = (arr) => { + const m = new Map() + for (const v of arr) m.set(v, (m.get(v) || 0) + 1) + return JSON.stringify([...m.entries()].sort((x, y) => x[0] - y[0])) +} +let ordered = 0 +let multiplicities = 0 +for (let n = 0; n < 100; n++) { + const length = Math.floor(random() * 13) + const values = [] + for (let k = 0; k < length; k++) values.push(Math.floor(random() * 11) - 5) + const sorted = oddEvenSort([...values]) + if (sorted.every((v, k) => k === 0 || sorted[k - 1] <= v)) ordered++ + if (counts(sorted) === counts(values)) multiplicities++ +} +rows.push({ + name: 'property run: 100 cases, seed 20261123, length 0..12, values -5..5', + input: { seed: 20261123, cases: 100 }, + expected: { ordered: 100, multiplicitiesPreserved: 100 }, + actual: { ordered, multiplicitiesPreserved: multiplicities }, + pass: ordered === 100 && multiplicities === 100, + precondition: `${SRC}:46,52 numbers compared with >` +}) + +console.log(JSON.stringify(rows)) diff --git a/work/R50-T004/results.json b/work/R50-T004/results.json new file mode 100644 index 0000000000..6db2b672f9 --- /dev/null +++ b/work/R50-T004/results.json @@ -0,0 +1,182 @@ +{ + "task": "R50-T004", + "install": { + "command": "npm ci --ignore-scripts --no-audit --no-fund", + "exit": 0 + }, + "focused_tests": { + "command": "node_modules/.bin/vitest run Sorts/test/OddEvenSort.test.js --reporter=json --outputFile=work/R50-T004/vitest-focused.raw.json", + "exit": 0, + "total": 17, + "passed": 17, + "failed": 0 + }, + "fixture": [ + { + "name": "oddEvenSort([3,1,2])", + "input": [3, 1, 2], + "expected": { + "result": [1, 2, 3], + "returnsSameArray": true + }, + "actual": { + "result": [1, 2, 3], + "returnsSameArray": true + }, + "pass": true, + "precondition": "OddEvenSort.js:41 ascending, in place, returns arr (line 58)" + }, + { + "name": "oddEvenSort([2,2,1])", + "input": [2, 2, 1], + "expected": { + "result": [1, 2, 2], + "returnsSameArray": true + }, + "actual": { + "result": [1, 2, 2], + "returnsSameArray": true + }, + "pass": true, + "precondition": "OddEvenSort.js:41 ascending, in place, returns arr (line 58)" + }, + { + "name": "oddEvenSort([1,2,3])", + "input": [1, 2, 3], + "expected": { + "result": [1, 2, 3], + "returnsSameArray": true + }, + "actual": { + "result": [1, 2, 3], + "returnsSameArray": true + }, + "pass": true, + "precondition": "OddEvenSort.js:41 ascending, in place, returns arr (line 58)" + }, + { + "name": "oddEvenSort([3,2,1])", + "input": [3, 2, 1], + "expected": { + "result": [1, 2, 3], + "returnsSameArray": true + }, + "actual": { + "result": [1, 2, 3], + "returnsSameArray": true + }, + "pass": true, + "precondition": "OddEvenSort.js:41 ascending, in place, returns arr (line 58)" + }, + { + "name": "oddEvenSort([])", + "input": [], + "expected": { + "result": [], + "returnsSameArray": true + }, + "actual": { + "result": [], + "returnsSameArray": true + }, + "pass": true, + "precondition": "OddEvenSort.js:41 ascending, in place, returns arr (line 58)" + }, + { + "name": "oddEvenSort([7])", + "input": [7], + "expected": { + "result": [7], + "returnsSameArray": true + }, + "actual": { + "result": [7], + "returnsSameArray": true + }, + "pass": true, + "precondition": "OddEvenSort.js:41 ascending, in place, returns arr (line 58)" + }, + { + "name": "swap([3, 1, 2], 0, 1)", + "input": [[3, 1, 2], 0, 1], + "expected": { + "arr": [1, 3, 2], + "returned": "undefined" + }, + "actual": { + "arr": [1, 3, 2], + "returned": "undefined" + }, + "pass": true, + "precondition": "OddEvenSort.js:22-26 swap mutates arr, returns nothing" + }, + { + "name": "property run: 100 cases, seed 20261123, length 0..12, values -5..5", + "input": { + "seed": 20261123, + "cases": 100 + }, + "expected": { + "ordered": 100, + "multiplicitiesPreserved": 100 + }, + "actual": { + "ordered": 100, + "multiplicitiesPreserved": 100 + }, + "pass": true, + "precondition": "OddEvenSort.js:46,52 numbers compared with >" + } + ], + "mutants": [ + { + "name": "swap loses a value (arr[j] = arr[i])", + "file": "Sorts/OddEvenSort.js", + "edit": { + "from": " arr[j] = tmp\n", + "to": " arr[j] = arr[i]\n" + }, + "named_test": "output preserves input multiplicities", + "named_test_on_original": ["passed"], + "killed": true, + "exit": 1, + "failed_tests_on_mutant": [ + " The OddEvenSort of the array [5, 4, 3, 2, 1] is [1, 2, 3, 4, 5]", + " The OddEvenSort of the array [10, 14, 12, 20] is [10, 12, 14, 20]", + " The OddEvenSort of the array [166, 169, 144] is [144, 166, 169]", + " swap invariant swap exchanges two positions in place and returns undefined", + " swap invariant swap preserves multiplicities", + " oddEvenSort fixture (ascending, in place) oddEvenSort([3,1,2]) is [1,2,3] and returns the same array", + " oddEvenSort fixture (ascending, in place) oddEvenSort([2,2,1]) is [1,2,2] and returns the same array", + " oddEvenSort fixture (ascending, in place) oddEvenSort([3,2,1]) is [1,2,3] and returns the same array", + " oddEvenSort properties over 100 seeded cases readable small generated cases sort as expected", + " oddEvenSort properties over 100 seeded cases output preserves input multiplicities" + ] + }, + { + "name": "even pass no longer clears the sorted flag", + "file": "Sorts/OddEvenSort.js", + "edit": { + "from": " for (let i = 0; i < arr.length - 1; i += 2) {\n if (arr[i] > arr[i + 1]) {\n swap(arr, i, i + 1)\n sorted = false\n", + "to": " for (let i = 0; i < arr.length - 1; i += 2) {\n if (arr[i] > arr[i + 1]) {\n swap(arr, i, i + 1)\n" + }, + "named_test": "output is ordered", + "named_test_on_original": ["passed"], + "killed": true, + "exit": 1, + "failed_tests_on_mutant": [ + " oddEvenSort fixture (ascending, in place) oddEvenSort([3,1,2]) is [1,2,3] and returns the same array", + " oddEvenSort properties over 100 seeded cases output is ordered" + ] + } + ], + "full_suite": { + "command": "npm test -- --reporter=json --outputFile=work/R50-T004/vitest-full.raw.json", + "exit": 0, + "total": 11983, + "passed": 11983, + "failed": 0 + }, + "ok": true, + "failures": [] +} diff --git a/work/R50-T004/task.json b/work/R50-T004/task.json new file mode 100644 index 0000000000..752044fbbc --- /dev/null +++ b/work/R50-T004/task.json @@ -0,0 +1,22 @@ +{ + "task": "R50-T004", + "focused_tests": ["Sorts/test/OddEvenSort.test.js"], + "mutants": [ + { + "name": "swap loses a value (arr[j] = arr[i])", + "file": "Sorts/OddEvenSort.js", + "find": " arr[j] = tmp\n", + "replace": " arr[j] = arr[i]\n", + "tests": ["Sorts/test/OddEvenSort.test.js"], + "must_fail": "output preserves input multiplicities" + }, + { + "name": "even pass no longer clears the sorted flag", + "file": "Sorts/OddEvenSort.js", + "find": " for (let i = 0; i < arr.length - 1; i += 2) {\n if (arr[i] > arr[i + 1]) {\n swap(arr, i, i + 1)\n sorted = false\n", + "replace": " for (let i = 0; i < arr.length - 1; i += 2) {\n if (arr[i] > arr[i + 1]) {\n swap(arr, i, i + 1)\n", + "tests": ["Sorts/test/OddEvenSort.test.js"], + "must_fail": "output is ordered" + } + ] +} diff --git a/work/R50-T004/versions.txt b/work/R50-T004/versions.txt new file mode 100644 index 0000000000..b405ff9cb4 --- /dev/null +++ b/work/R50-T004/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-T004/vitest-focused.json b/work/R50-T004/vitest-focused.json new file mode 100644 index 0000000000..45d497a33c --- /dev/null +++ b/work/R50-T004/vitest-focused.json @@ -0,0 +1,76 @@ +{ + "command": "node_modules/.bin/vitest run Sorts/test/OddEvenSort.test.js --reporter=json --outputFile=work/R50-T004/vitest-focused.raw.json", + "numTotalTests": 17, + "numPassedTests": 17, + "numFailedTests": 0, + "tests": [ + { + "name": " The OddEvenSort of the array [5, 4, 3, 2, 1] is [1, 2, 3, 4, 5]", + "status": "passed" + }, + { + "name": " The OddEvenSort of the array [] is []", + "status": "passed" + }, + { + "name": " The OddEvenSort of the array [10, 14, 12, 20] is [10, 12, 14, 20]", + "status": "passed" + }, + { + "name": " The OddEvenSort of the array [166, 169, 144] is [144, 166, 169]", + "status": "passed" + }, + { + "name": " swap invariant swap exchanges two positions in place and returns undefined", + "status": "passed" + }, + { + "name": " swap invariant swap preserves multiplicities", + "status": "passed" + }, + { + "name": " oddEvenSort fixture (ascending, in place) oddEvenSort([3,1,2]) is [1,2,3] and returns the same array", + "status": "passed" + }, + { + "name": " oddEvenSort fixture (ascending, in place) oddEvenSort([2,2,1]) is [1,2,2] and returns the same array", + "status": "passed" + }, + { + "name": " oddEvenSort fixture (ascending, in place) oddEvenSort([1,2,3]) is [1,2,3] and returns the same array", + "status": "passed" + }, + { + "name": " oddEvenSort fixture (ascending, in place) oddEvenSort([3,2,1]) is [1,2,3] and returns the same array", + "status": "passed" + }, + { + "name": " oddEvenSort fixture (ascending, in place) oddEvenSort([]) is [] and returns the same array", + "status": "passed" + }, + { + "name": " oddEvenSort fixture (ascending, in place) oddEvenSort([7]) is [7] and returns the same array", + "status": "passed" + }, + { + "name": " oddEvenSort properties over 100 seeded cases the generator is deterministic for a fixed seed", + "status": "passed" + }, + { + "name": " oddEvenSort properties over 100 seeded cases readable small generated cases sort as expected", + "status": "passed" + }, + { + "name": " oddEvenSort properties over 100 seeded cases output is ordered", + "status": "passed" + }, + { + "name": " oddEvenSort properties over 100 seeded cases output preserves input multiplicities", + "status": "passed" + }, + { + "name": " oddEvenSort properties over 100 seeded cases output is the input array, mutated in place", + "status": "passed" + } + ] +}