From 3cb3ef0012e903ae381aa3886ebac4c78b893b96 Mon Sep 17 00:00:00 2001 From: Aniruddha Bongale Date: Sun, 22 Nov 2026 13:16:26 +0530 Subject: [PATCH] test(graphs): cover failure and empty-result behavior of FloydWarshall (R50-T048) --- Graphs/FloydWarshall.js | 76 ++++++---- Graphs/test/FloydWarshall.test.js | 92 ++++++++++++ work/R50-T048/check.py | 240 ++++++++++++++++++++++++++++++ work/R50-T048/results.json | 120 +++++++++++++++ 4 files changed, 499 insertions(+), 29 deletions(-) create mode 100644 Graphs/test/FloydWarshall.test.js create mode 100644 work/R50-T048/check.py create mode 100644 work/R50-T048/results.json diff --git a/Graphs/FloydWarshall.js b/Graphs/FloydWarshall.js index 4552d4c602..546678459a 100644 --- a/Graphs/FloydWarshall.js +++ b/Graphs/FloydWarshall.js @@ -1,11 +1,50 @@ -/* - Source: - https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm - - Complexity: - O(|V|^3) where V is the set of vertices -*/ - +/** + * Computes all-pairs shortest paths using the Floyd-Warshall algorithm. + * + * Source: + * https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm + * Complexity: + * O(|V|^3) where V is the set of vertices. + * + * Preconditions and Failure / Empty-Result Behavior: + * - Precondition at Line 24 (`const n = dist.length`): For an empty graph (`dist = []`), + * `n` is 0. The outer relaxation loop condition `k < n` (Line 25) evaluates to false, + * bypassing all relaxation loops and directly executing Line 35 (`return dist`), + * returning the valid empty result `[]` without error. + * - Absent-path sentinel (`Infinity`): Where no path exists between vertices `i` and `j`, + * the condition `dist[i][j] > dist[i][k] + dist[k][j]` at Line 28 is never satisfied + * for any intermediate vertex `k`. Thus, `dist[i][j]` preserves the `Infinity` sentinel, + * representing unreachable vertices / absent shortest paths. + * - In-place mutation: The function updates and returns the input `dist` matrix. Caller-owned + * matrices can be shallow/deep copied prior to invocation if caller persistence is required. + * + * @param {number[][]} dist - 2D square matrix where dist[i][j] represents edge weight b/w i and j. + * @returns {number[][]} Updated 2D matrix where dist[i][j] represents shortest distance b/w i and j. + * + * @example + * // Empty graph (empty-result path, Line 35) + * FloydWarshall([]) // returns [] + * + * @example + * // Smallest valid input (1x1 matrix, Line 24) + * FloydWarshall([[0]]) // returns [[0]] + * + * @example + * // Ordinary graph with shortest paths computed + * FloydWarshall([ + * [0, 1, 2, Infinity], + * [1, 0, Infinity, Infinity], + * [2, Infinity, 0, 1], + * [Infinity, Infinity, 1, 0] + * ]) + * // returns: + * // [ + * // [0, 1, 2, 3], + * // [1, 0, 3, 4], + * // [2, 3, 0, 1], + * // [3, 4, 1, 0] + * // ] + */ const FloydWarshall = (dist) => { // Input:- dist: 2D Array where dist[i][j] = edge weight b/w i and j // Output:- dist: 2D Array where dist[i][j] = shortest dist b/w i and j @@ -24,24 +63,3 @@ const FloydWarshall = (dist) => { } export { FloydWarshall } - -// For the following graph (edge weights are shown in brackets) -// 4 1 dist[1][2] = dist[2][1] = 1 -// \ (2)/ \ dist[1][3] = dist[3][1] = 2 -// \ / \(1) dist[1][4] = dist[4][1] = Infinity -// (1)\ / \ dist[3][4] = dist[4][3] = 1 -// 3 2 dist[2][4] = dist[4][2] = Infinity -// dist[2][3] = dist[3][2] = Infinity -// Output should be: -// [ [0, 1, 2, 3], -// [1, 0, 3, 4], -// [2, 3, 0, 1], -// [3, 4, 1, 0] ] - -// FloydWarshall( -// [[0, 1, 2, Infinity], -// [1, 0, Infinity, Infinity], -// [2, Infinity, 0, 1], -// [Infinity, Infinity, 1, 0] -// ] -// ) diff --git a/Graphs/test/FloydWarshall.test.js b/Graphs/test/FloydWarshall.test.js new file mode 100644 index 0000000000..b02a4c4225 --- /dev/null +++ b/Graphs/test/FloydWarshall.test.js @@ -0,0 +1,92 @@ +import { FloydWarshall } from '../FloydWarshall' + +describe('FloydWarshall', () => { + describe('Failure and Empty-Result Paths', () => { + test('handles empty input graph as valid empty-result path (Line 24, 25 -> Line 35)', () => { + // Precondition: dist.length === 0 at Line 24, loop at Line 25 bypassed + const emptyInput = [] + const result = FloydWarshall(emptyInput) + expect(result).toEqual([]) + }) + + test('preserves absent-path sentinel Infinity for disconnected components (Line 28 condition false)', () => { + // Disconnected 2-vertex graph: no edge between 0 and 1 + const disconnectedGraph = [ + [0, Infinity], + [Infinity, 0] + ] + const result = FloydWarshall(disconnectedGraph) + expect(result).toEqual([ + [0, Infinity], + [Infinity, 0] + ]) + }) + + test('caller-owned state remains valid and ordinary call succeeds immediately after empty/failure call', () => { + // 1. Call empty-result path + const emptyCall = FloydWarshall([]) + expect(emptyCall).toEqual([]) + + // 2. Subsequent ordinary call succeeds without corruption + const ordinaryInput = [ + [0, 1, 2, Infinity], + [1, 0, Infinity, Infinity], + [2, Infinity, 0, 1], + [Infinity, Infinity, 1, 0] + ] + const expectedOrdinary = [ + [0, 1, 2, 3], + [1, 0, 3, 4], + [2, 3, 0, 1], + [3, 4, 1, 0] + ] + const result = FloydWarshall(ordinaryInput) + expect(result).toEqual(expectedOrdinary) + }) + }) + + describe('Smallest Valid and Ordinary Inputs', () => { + test('smallest valid input: single vertex graph (Line 24: n=1)', () => { + const smallestInput = [[0]] + const expectedSmallest = [[0]] + const result = FloydWarshall(smallestInput) + expect(result).toEqual(expectedSmallest) + }) + + test('ordinary input: 4-vertex connected graph with indirect paths', () => { + const ordinaryInput = [ + [0, 1, 2, Infinity], + [1, 0, Infinity, Infinity], + [2, Infinity, 0, 1], + [Infinity, Infinity, 1, 0] + ] + const expectedOrdinary = [ + [0, 1, 2, 3], + [1, 0, 3, 4], + [2, 3, 0, 1], + [3, 4, 1, 0] + ] + const result = FloydWarshall(ordinaryInput) + expect(result).toEqual(expectedOrdinary) + }) + + test('ordinary directed graph with weighted edges', () => { + const directedGraph = [ + [0, 3, 8, Infinity, -4], + [Infinity, 0, Infinity, 1, 7], + [Infinity, 4, 0, Infinity, Infinity], + [2, Infinity, -5, 0, Infinity], + [Infinity, Infinity, Infinity, 6, 0] + ] + const expected = [ + [0, 1, -3, 2, -4], + [3, 0, -4, 1, -1], + [7, 4, 0, 5, 3], + [2, -1, -5, 0, -2], + [8, 5, 1, 6, 0] + ] + const result = FloydWarshall(directedGraph) + expect(result).toEqual(expected) + }) + }) +}) diff --git a/work/R50-T048/check.py b/work/R50-T048/check.py new file mode 100644 index 0000000000..11ba6c5c4f --- /dev/null +++ b/work/R50-T048/check.py @@ -0,0 +1,240 @@ +#!/usr/bin/env python3 +""" +Automated check runner for Task R50-T048: +Cover the failure behavior of FloydWarshall (Graphs/FloydWarshall.js). + +Executes repository native tests, verifies assertions on fixtures +(smallest valid input, ordinary input, empty-result/absent-path branches, +and caller-owned sequential call validity), and writes results to +work/R50-T048/results.json. +""" + +import json +import os +import re +import subprocess +import sys +from datetime import datetime, timezone + +WORKSPACE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +RESULTS_DIR = os.path.join(WORKSPACE_DIR, "work", "R50-T048") +RESULTS_PATH = os.path.join(RESULTS_DIR, "results.json") + +def get_tool_versions(): + versions = {} + # Python + versions["python"] = sys.version.split()[0] + + # Node + try: + out = subprocess.run(["node", "--version"], capture_output=True, text=True, check=True) + versions["node"] = out.stdout.strip() + except Exception as e: + versions["node"] = str(e) + + # npm + try: + out = subprocess.run(["npm", "--version"], capture_output=True, text=True, check=True) + versions["npm"] = out.stdout.strip() + except Exception as e: + versions["npm"] = str(e) + + # vitest + try: + out = subprocess.run(["npx", "vitest", "--version"], cwd=WORKSPACE_DIR, capture_output=True, text=True, check=True) + versions["vitest"] = out.stdout.strip() + except Exception as e: + versions["vitest"] = str(e) + + return versions + +def run_native_tests(): + cmd = ["npm", "test", "--", "Graphs/test/FloydWarshall.test.js"] + env = os.environ.copy() + env["PATH"] = f"/opt/homebrew/bin:{env.get('PATH', '')}" + result = subprocess.run(cmd, cwd=WORKSPACE_DIR, capture_output=True, text=True, env=env) + + output = result.stdout + "\n" + result.stderr + + # Parse test count: e.g. "Tests 6 passed (6)" + tests_passed = 0 + match = re.search(r"Tests\s+(\d+)\s+passed", output) + if match: + tests_passed = int(match.group(1)) + + return { + "command": " ".join(cmd), + "exit_code": result.returncode, + "tests_passed": tests_passed, + "output": output + } + +def run_node_eval(): + node_script = """ + import { FloydWarshall } from './Graphs/FloydWarshall.js'; + + const fixtures = [ + { + name: "smallest_valid_input_1x1", + precondition_source_line: "Line 24 (const n = dist.length = 1)", + input: [[0]], + expected: [[0]] + }, + { + name: "empty_result_path_0x0", + precondition_source_line: "Line 24 (n = 0) -> Line 25 (loop skipped) -> Line 35 (return dist)", + input: [], + expected: [] + }, + { + name: "absent_path_disconnected_sentinel", + precondition_source_line: "Line 28 (dist[i][j] > dist[i][k] + dist[k][j] evaluates false) -> preserves Infinity", + input: [[0, Infinity], [Infinity, 0]], + expected: [[0, Infinity], [Infinity, 0]] + }, + { + name: "ordinary_input_4x4", + precondition_source_line: "Line 24..35 (full iterative relaxation across 4 vertices)", + input: [ + [0, 1, 2, Infinity], + [1, 0, Infinity, Infinity], + [2, Infinity, 0, 1], + [Infinity, Infinity, 1, 0] + ], + expected: [ + [0, 1, 2, 3], + [1, 0, 3, 4], + [2, 3, 0, 1], + [3, 4, 1, 0] + ] + }, + { + name: "ordinary_directed_graph_5x5", + precondition_source_line: "Line 24..35 (relaxation with negative weights)", + input: [ + [0, 3, 8, Infinity, -4], + [Infinity, 0, Infinity, 1, 7], + [Infinity, 4, 0, Infinity, Infinity], + [2, Infinity, -5, 0, Infinity], + [Infinity, Infinity, Infinity, 6, 0] + ], + expected: [ + [0, 1, -3, 2, -4], + [3, 0, -4, 1, -1], + [7, 4, 0, 5, 3], + [2, -1, -5, 0, -2], + [8, 5, 1, 6, 0] + ] + } + ]; + + const cloneMatrix = (mat) => { + if (!Array.isArray(mat)) return mat; + return mat.map(row => Array.isArray(row) ? [...row] : row); + }; + + const results = fixtures.map(f => { + const inputCopy = cloneMatrix(f.input); + const actual = FloydWarshall(inputCopy); + const actualNormalized = Array.isArray(actual) + ? actual.map(row => Array.isArray(row) ? row.map(v => v === Infinity ? "Infinity" : v) : row) + : actual; + const expectedNormalized = Array.isArray(f.expected) + ? f.expected.map(row => Array.isArray(row) ? row.map(v => v === Infinity ? "Infinity" : v) : row) + : f.expected; + return { + name: f.name, + precondition_source_line: f.precondition_source_line, + input: f.input.map(row => Array.isArray(row) ? row.map(v => v === Infinity ? "Infinity" : v) : row), + expected: expectedNormalized, + actual: actualNormalized, + passed: JSON.stringify(actualNormalized) === JSON.stringify(expectedNormalized) + }; + }); + + // Test sequential validity: empty call followed by ordinary call + const emptyResult = FloydWarshall([]); + const ordResult = FloydWarshall([ + [0, 1, 2, Infinity], + [1, 0, Infinity, Infinity], + [2, Infinity, 0, 1], + [Infinity, Infinity, 1, 0] + ]); + const expectedOrd = [ + [0, 1, 2, 3], + [1, 0, 3, 4], + [2, 3, 0, 1], + [3, 4, 1, 0] + ]; + results.push({ + name: "sequential_call_after_failure_or_empty", + precondition_source_line: "Line 24..35 (valid execution after empty branch)", + input: "FloydWarshall([]) then FloydWarshall(ordinaryInput)", + expected: expectedOrd, + actual: ordResult, + passed: JSON.stringify(emptyResult) === "[]" && JSON.stringify(ordResult) === JSON.stringify(expectedOrd) + }); + + console.log(JSON.stringify(results)); + """ + env = os.environ.copy() + env["PATH"] = f"/opt/homebrew/bin:{env.get('PATH', '')}" + res = subprocess.run(["node", "--input-type=module", "-e", node_script], + cwd=WORKSPACE_DIR, capture_output=True, text=True, env=env) + if res.returncode != 0: + raise RuntimeError(f"Node execution failed: {res.stderr}") + return json.loads(res.stdout.strip()) + +def main(): + print(f"Running checks for Task R50-T048...") + tool_versions = get_tool_versions() + native_test_result = run_native_tests() + + if native_test_result["exit_code"] != 0: + print(f"Native tests failed with exit code {native_test_result['exit_code']}") + print(native_test_result["output"]) + sys.exit(1) + + print(f"Native tests passed: {native_test_result['tests_passed']} tests.") + + assertion_results = run_node_eval() + all_passed = True + for item in assertion_results: + if not item["passed"]: + print(f"Assertion failed for {item['name']}: expected {item['expected']}, got {item['actual']}") + all_passed = False + else: + print(f" ✓ {item['name']}: passed (Precondition: {item['precondition_source_line']})") + + if not all_passed: + print("Some assertions failed.") + sys.exit(1) + + os.makedirs(RESULTS_DIR, exist_ok=True) + summary = { + "task_id": "R50-T048", + "target": "Graphs/FloydWarshall.js", + "tested_function": "FloydWarshall", + "timestamp": datetime.now(timezone.utc).isoformat(), + "tool_versions": tool_versions, + "native_test": { + "command": native_test_result["command"], + "exit_code": native_test_result["exit_code"], + "tests_passed": native_test_result["tests_passed"] + }, + "assertions": assertion_results, + "status": "PASSED" + } + + with open(RESULTS_PATH, "w") as f: + json.dump(summary, f, indent=2) + print(f"Results written to {RESULTS_PATH}") + + # Format with prettier to satisfy pre-commit hook + env = os.environ.copy() + env["PATH"] = f"/opt/homebrew/bin:{env.get('PATH', '')}" + subprocess.run(["npx", "prettier", RESULTS_PATH, "--write"], cwd=WORKSPACE_DIR, env=env, check=False) + print(f"Prettier formatting applied to {RESULTS_PATH}") + +if __name__ == "__main__": + main() diff --git a/work/R50-T048/results.json b/work/R50-T048/results.json new file mode 100644 index 0000000000..c137bf8fcf --- /dev/null +++ b/work/R50-T048/results.json @@ -0,0 +1,120 @@ +{ + "task_id": "R50-T048", + "target": "Graphs/FloydWarshall.js", + "tested_function": "FloydWarshall", + "timestamp": "2026-11-22T07:44:05.983922+00:00", + "tool_versions": { + "python": "3.15.2", + "node": "v26.13.1", + "npm": "11.20.0", + "vitest": "vitest/1.2.1 darwin-arm64 node-v26.13.1" + }, + "native_test": { + "command": "npm test -- Graphs/test/FloydWarshall.test.js", + "exit_code": 0, + "tests_passed": 6 + }, + "assertions": [ + { + "name": "smallest_valid_input_1x1", + "precondition_source_line": "Line 24 (const n = dist.length = 1)", + "input": [[0]], + "expected": [[0]], + "actual": [[0]], + "passed": true + }, + { + "name": "empty_result_path_0x0", + "precondition_source_line": "Line 24 (n = 0) -> Line 25 (loop skipped) -> Line 35 (return dist)", + "input": [], + "expected": [], + "actual": [], + "passed": true + }, + { + "name": "absent_path_disconnected_sentinel", + "precondition_source_line": "Line 28 (dist[i][j] > dist[i][k] + dist[k][j] evaluates false) -> preserves Infinity", + "input": [ + [0, "Infinity"], + ["Infinity", 0] + ], + "expected": [ + [0, "Infinity"], + ["Infinity", 0] + ], + "actual": [ + [0, "Infinity"], + ["Infinity", 0] + ], + "passed": true + }, + { + "name": "ordinary_input_4x4", + "precondition_source_line": "Line 24..35 (full iterative relaxation across 4 vertices)", + "input": [ + [0, 1, 2, "Infinity"], + [1, 0, "Infinity", "Infinity"], + [2, "Infinity", 0, 1], + ["Infinity", "Infinity", 1, 0] + ], + "expected": [ + [0, 1, 2, 3], + [1, 0, 3, 4], + [2, 3, 0, 1], + [3, 4, 1, 0] + ], + "actual": [ + [0, 1, 2, 3], + [1, 0, 3, 4], + [2, 3, 0, 1], + [3, 4, 1, 0] + ], + "passed": true + }, + { + "name": "ordinary_directed_graph_5x5", + "precondition_source_line": "Line 24..35 (relaxation with negative weights)", + "input": [ + [0, 3, 8, "Infinity", -4], + ["Infinity", 0, "Infinity", 1, 7], + ["Infinity", 4, 0, "Infinity", "Infinity"], + [2, "Infinity", -5, 0, "Infinity"], + ["Infinity", "Infinity", "Infinity", 6, 0] + ], + "expected": [ + [0, 1, -3, 2, -4], + [3, 0, -4, 1, -1], + [7, 4, 0, 5, 3], + [2, -1, -5, 0, -2], + [8, 5, 1, 6, 0] + ], + "actual": [ + [0, 1, -3, 2, -4], + [3, 0, -4, 1, -1], + [7, 4, 0, 5, 3], + [2, -1, -5, 0, -2], + [8, 5, 1, 6, 0] + ], + "passed": true + }, + { + "name": "sequential_call_after_failure_or_empty", + "precondition_source_line": "Line 24..35 (valid execution after empty branch)", + "input": "FloydWarshall([]) then FloydWarshall(ordinaryInput)", + "expected": [ + [0, 1, 2, 3], + [1, 0, 3, 4], + [2, 3, 0, 1], + [3, 4, 1, 0] + ], + "actual": [ + [0, 1, 2, 3], + [1, 0, 3, 4], + [2, 3, 0, 1], + [3, 4, 1, 0] + ], + "passed": true + } + ], + "status": "PASSED" +}