Keep a source fixture and derived file separate

Keep a source fixture and derived file separate

A fixture is evidence for a test: it represents the original input. A generated result needs a different filename so the program can compare the two artifacts and rerun safely. This example creates an isolated temporary workspace, writes compact JSON to fixture.json, and writes a deliberately formatted derivative to fixture.pretty.json.

The first assertion confirms that the two Path objects identify different locations. The next two assertions verify the complete contents of each file, including their trailing newlines. Printing only the basenames keeps stdout deterministic while still showing which artifact is the source and which is derived. After the with TemporaryDirectory() block finishes, the temporary workspace and its contents are scheduled for removal.

This naming discipline does not make the derived output semantically correct; the assertions only establish the small fixture's expected bytes after text encoding. It also does not prevent an application from choosing conflicting paths elsewhere. In a larger test suite, derive the output name from controlled test data and avoid accidentally supplying it as the next run's input. Path.read_text() and Path.write_text() were added in Python 3.5, so this example requires Python 3.5 or later. Consult pathlib's file-reading and writing documentation and the TemporaryDirectory documentation.

AI assistance disclosure: This article was drafted with AI assistance and should be reviewed in the context of its application.

from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory:
    workspace = Path(directory)
    source = workspace / "fixture.json"
    derived = workspace / "fixture.pretty.json"

    source.write_text('{"enabled":true}\n', encoding="utf-8")
    derived.write_text('{\n  "enabled": true\n}\n', encoding="utf-8")

    assert source != derived
    assert source.read_text(encoding="utf-8") == '{"enabled":true}\n'
    assert derived.read_text(encoding="utf-8") == '{\n  "enabled": true\n}\n'

    print(source.name)
    print(derived.name)
fixture.json
fixture.pretty.json

Comments

Popular posts from this blog

Compare Two Text Files in Python Without Modifying Them

Seven CSV Quality Checks to Run Before Importing Data

Explain why SQLite transactions cannot make an HTTP call atomic