import errno import hashlib import json import os from pathlib import Path import tempfile import unittest from unittest.mock import Mock, patch from probe import BLOCK, SIZE, observe_case, query, read_exact, scan, write_exact class WalkerTests(unittest.TestCase): def test_empty_does_not_seek(self): seek = Mock() self.assertEqual(scan(7, 0, seek), []) seek.assert_not_called() def test_conservative_all_data_is_valid(self): seek = Mock(side_effect=[0, SIZE]) self.assertEqual(scan(7, SIZE, seek), [{"kind": "data", "start": 0, "end": SIZE}]) def test_leading_middle_and_trailing_holes(self): seek = Mock(side_effect=[4, 6, 8, 9, OSError(errno.ENXIO, "no data")]) self.assertEqual(scan(7, 12, seek), [ {"kind": "hole", "start": 0, "end": 4}, {"kind": "data", "start": 4, "end": 6}, {"kind": "hole", "start": 6, "end": 8}, {"kind": "data", "start": 8, "end": 9}, {"kind": "hole", "start": 9, "end": 12}, ]) def test_no_reported_data(self): self.assertEqual(scan(7, SIZE, Mock(side_effect=OSError(errno.ENXIO, "end"))), [{"kind": "hole", "start": 0, "end": SIZE}]) def test_other_errors_are_not_end_of_scan(self): for code in [errno.EINVAL, errno.EIO, errno.EBADF, errno.EOPNOTSUPP]: with self.subTest(code=code), self.assertRaises(OSError) as caught: scan(7, SIZE, Mock(side_effect=OSError(code, "error"))) self.assertEqual(caught.exception.errno, code) def test_hole_query_error_is_not_swallowed(self): with self.assertRaises(OSError): scan(7, SIZE, Mock(side_effect=[0, OSError(errno.ENXIO, "changed")])) def test_invalid_progress_and_bounds(self): for values in [[-1], [SIZE], [0, 0], [0, SIZE + 1], [4, 3]]: with self.subTest(values=values), self.assertRaises(ValueError): scan(7, SIZE, Mock(side_effect=values)) def test_invalid_size(self): for size in [-1, 1.5, True]: with self.subTest(size=size), self.assertRaises(ValueError): scan(7, size, Mock()) def test_short_reads_are_accumulated(self): read = Mock(side_effect=[b"ab", b"c", b"d"]) self.assertEqual(read_exact(7, 10, 4, read), b"abcd") self.assertEqual([c.args for c in read.call_args_list], [(7, 4, 10), (7, 2, 12), (7, 1, 13)]) def test_early_eof_fails(self): with self.assertRaises(RuntimeError): read_exact(7, 0, 2, Mock(side_effect=[b"a", b""])) class ReceiptTests(unittest.TestCase): def test_retained_observation(self): root = Path(__file__).parent receipt = json.loads((root / "observation.json").read_text()) self.assertEqual(receipt["probe_sha256"], hashlib.sha256((root / "probe.py").read_bytes()).hexdigest()) self.assertEqual([c["case"] for c in receipt["cases"]], ["empty", "unwritten-zeros", "written-zeros", "mixed"]) for case in receipt["cases"]: size = case["size_bytes"] for boundary in [size, size + 1]: for mode in ["data", "hole"]: self.assertEqual(case["endpoints"][str(boundary)][mode]["errno"], errno.ENXIO) self.assertTrue(case["reported_holes_read_zero"]) self.assertTrue(case["readback_matches_preparation"]) expected = bytes(size) if case["case"] != "mixed" else ( bytes(BLOCK) + b"X" * BLOCK + bytes(SIZE - 2 * BLOCK)) self.assertEqual(case["readback_sha256"], hashlib.sha256(expected).hexdigest()) cursor = 0 for item in case["ranges"]: self.assertEqual(item["start"], cursor) self.assertGreater(item["end"], cursor) self.assertLessEqual(item["end"], size) cursor = item["end"] self.assertEqual(cursor, size) cursor = receipt["cases"][-1]["cursor"] self.assertNotEqual(cursor["before_seek"], cursor["seek_hole_result"]) self.assertEqual(cursor["original_after_dup_seek"], cursor["seek_hole_result"]) self.assertEqual(cursor["original_after_pread"], cursor["seek_hole_result"]) self.assertEqual(cursor["separately_opened_cursor"], 0) self.assertTrue(cursor["pread_matches_pattern"]) class NativeTests(unittest.TestCase): def test_fresh_mixed_file(self): if not all(hasattr(os, x) for x in ["SEEK_DATA", "SEEK_HOLE"]): self.skipTest("runtime lacks seek classification") with tempfile.TemporaryDirectory() as folder: try: case = observe_case(folder, "mixed") except OSError as error: if error.errno in [errno.EINVAL, errno.EOPNOTSUPP]: self.skipTest("filesystem does not support this seek operation") raise self.assertTrue(case["readback_matches_preparation"]) for mode in ["data", "hole"]: self.assertEqual(case["endpoints"][str(SIZE)][mode]["errno"], errno.ENXIO) cursor = case["cursor"] self.assertEqual(cursor["original_after_dup_seek"], cursor["seek_hole_result"]) self.assertEqual(cursor["original_after_pread"], cursor["seek_hole_result"]) self.assertEqual(cursor["separately_opened_cursor"], 0) class FailurePathTests(unittest.TestCase): def test_scan_stops_at_eof_without_extra_seek(self): seek = Mock(side_effect=[0, SIZE]) scan(7, SIZE, seek) self.assertEqual([c.args for c in seek.call_args_list], [(7, 0, os.SEEK_DATA), (7, 0, os.SEEK_HOLE)]) def test_empty_read_does_not_issue_io(self): read = Mock() self.assertEqual(read_exact(7, 0, 0, read), b"") read.assert_not_called() def test_read_errors_propagate(self): with self.assertRaises(OSError) as caught: read_exact(7, 0, 4, Mock(side_effect=OSError(errno.EIO, "read failure"))) self.assertEqual(caught.exception.errno, errno.EIO) def test_short_writes_are_accumulated(self): with patch("probe.os.pwrite", side_effect=[2, 1, 1]) as write: write_exact(7, b"abcd", 10) self.assertEqual([c.args for c in write.call_args_list], [(7, b"abcd", 10), (7, b"cd", 12), (7, b"d", 13)]) def test_stalled_writes_fail(self): for result in [0, -1]: with self.subTest(result=result), patch("probe.os.pwrite", return_value=result): with self.assertRaises(RuntimeError): write_exact(7, b"x", 0) def test_write_errors_propagate(self): with patch("probe.os.pwrite", side_effect=OSError(errno.ENOSPC, "full")): with self.assertRaises(OSError) as caught: write_exact(7, b"x", 0) self.assertEqual(caught.exception.errno, errno.ENOSPC) def test_endpoint_query_retains_error_identity(self): for code in [errno.ENXIO, errno.EIO, errno.EINVAL]: with self.subTest(code=code): result = query(7, SIZE, os.SEEK_HOLE, Mock(side_effect=OSError(code, "failure"))) self.assertEqual(result, {"errno": code, "error": errno.errorcode[code]}) self.assertNotIn("offset", result) def test_failed_eof_seek_preserves_shared_cursor(self): if not all(hasattr(os, x) for x in ["SEEK_DATA", "SEEK_HOLE"]): self.skipTest("runtime lacks seek classification") with tempfile.TemporaryFile() as stream: fd = stream.fileno() os.ftruncate(fd, SIZE) alias = os.dup(fd) try: for mode in [os.SEEK_DATA, os.SEEK_HOLE]: os.lseek(fd, 17, os.SEEK_SET) with self.subTest(mode=mode), self.assertRaises(OSError) as caught: os.lseek(alias, SIZE, mode) if caught.exception.errno in [errno.EINVAL, errno.EOPNOTSUPP]: self.skipTest("filesystem does not support this seek operation") self.assertEqual(caught.exception.errno, errno.ENXIO) self.assertEqual(os.lseek(fd, 0, os.SEEK_CUR), 17) finally: os.close(alias) if __name__ == "__main__": unittest.main()