Skip to main content

Test a file-processing script with temporary directories

2026-11-11 15:57:31.669765+00:00
Test a file-processing script with temporary directories

A file-processing test should own its input directory. Pointing a test at a developer's Downloads folder makes its result depend on unrelated files and can turn a mistaken cleanup into data loss.

Temporary directory tree beside a compact test-result matrix.

Build the directory inside the test

Pytest's tmp_path fixture supplies a Path for an isolated test directory. This example tests a tiny line-normalization function; save both definitions in a test module.

def normalize(source, destination):
    count = 0
    with source.open(encoding="utf-8") as incoming:
        with destination.open("w", encoding="utf-8") as outgoing:
            for line in incoming:
                text = line.strip()
                if text:
                    outgoing.write(text + "\n")
                    count += 1
    return count

def test_unicode_and_blank_lines(tmp_path):
    source = tmp_path / "résumé input.txt"
    output = tmp_path / "result.txt"
    source.write_text("  alpha  \n\n beta", encoding="utf-8")

    assert normalize(source, output) == 2
    assert output.read_text(encoding="utf-8") == "alpha\nbeta\n"

def test_empty_input(tmp_path):
    source = tmp_path / "empty.txt"
    output = tmp_path / "result.txt"
    source.write_text("", encoding="utf-8")

    assert normalize(source, output) == 0
    assert output.read_text(encoding="utf-8") == ""

Run the module with "python -m pytest". The assertions cover the actual output and the return value. Checking only that the function did not raise would miss whitespace changes, missing final newlines and accidental blank records.

Use filenames containing spaces and non-ASCII characters because shell quoting and encoding mistakes often hide behind short ASCII fixtures. Keep fixtures small enough that a failed assertion remains readable.

Simulate failures intentionally

A chmod-based permission test is not equally reliable on every operating system or when tests run with elevated privileges. For a narrow unit test, inject a writer that raises PermissionError and assert the function propagates the failure. Keep a separate platform-specific test if real permission behavior is part of the product requirement.

Do not mock Path indiscriminately. A test that replaces every filesystem operation can pass while the real code opens the wrong file. Temporary directories let ordinary path and encoding behavior run while limiting the test's scope.

If the script overwrites an existing output, add a fixture containing an old result and test the failure policy. Atomic export code should preserve that old result when an exception occurs before replacement.

The automation context in Postzyo is related. Pytest documents fixtures, including how test resources are constructed and cleaned up.