Batu Lab NotesPractical developer guides

Use bytes assertions to prove a read-only input stayed unchanged

By Batu ยท English technical notes

Also published in our Blogger archive.

Quick answer

Path.read_bytes returns the exact file contents as bytes, which is the correct representation for a preservation assertion.

Example

The script captures bytes before reading text, then captures bytes afterward and compares them. The text read establishes that a consumer can decode the fixture, while byte equality proves this particular operation did not rewrite CRLF or leading zeroes.

from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as d:
    p = Path(d) / 'input.csv'
    p.write_bytes(b'id\r\n001\r\n')
    before = p.read_bytes()
    rows = p.read_text(encoding='utf-8')
    after = p.read_bytes()
    assert before == after and '001' in rows
    print(f'unchanged={before == after}')

Expected stdout:

unchanged=True

Reading the result

Equal bytes do not prove another function is safe or that a concurrent process did not race the check. Keep the before-and-after reads close to the operation under test.

Use a byte-level fixture containing newline and leading-zero cases because they reveal accidental text rewriting. A simple ASCII word alone would not expose the preservation property being tested.

The byte fixture uses CRLF and 001 because these representations are easy to damage with eager text processing. The second byte read is the essential regression observation.

Sources

- Python pathlib documentation

Prepared with AI assistance. The example uses synthetic data; its stated limits apply.