Typorithm · medium

Test files in an owned temporary directory

pythonpytesttestingindependent-practice
Saved on this device
Full lesson · 4 learning steps Open any exercise for focused practice
1

Step 1 of 4 · intro card

Test files in an owned temporary directory

0%

Concept and contract

Verify bytes and Unicode using a path supplied for this test.

A file test should own its path and contents. tmp_path supplies a pathlib.Path to a unique temporary directory for the test invocation. This prevents collisions with another test’s files and removes the need for a hard-coded Downloads folder or production document path.

Temporary does not mean imaginary: the write and read are real filesystem operations. In the browser they occur in Pyodide’s virtual filesystem; on a local Python installation they occur in pytest’s temporary directory. Neither example should write to a user’s existing documents.

Mechanism and worked example

The complete function writes UTF-8 text and reads it back with the same explicit encoding.

The complete function writes UTF-8 text and reads it back with the same explicit encoding. The test constructs a filename beneath tmp_path and compares the returned string. Paths are assembled with pathlib rather than manual slash concatenation.

Reading back is a useful integration check for a small helper, but it cannot establish durability across a power loss or correct behavior on every filesystem. Keep the claimed contract narrow: correct contents in an owned location with the stated encoding.

Complete worked example

python

def round_trip(path, text):
    path.write_text(text, encoding="utf-8")
    return path.read_text(encoding="utf-8")


def test_ascii_round_trip(tmp_path):
    path = tmp_path / "note.txt"
    assert round_trip(path, "hello") == "hello"
Reasoning
The complete function writes UTF-8 text and reads it back with the same explicit encoding. The test constructs a filename beneath tmp_path and compares the returned string. Paths are assembled with pathlib rather than manual slash concatenation. Reading back is a useful integration check for a small helper, but it cannot establish durability across a power loss or correct behavior on every filesystem. Keep the claimed contract narrow: correct contents in an owned location with the stated encoding.
Open in local Python playground ↗

Focused test decision: context is in the complete example

python

path = tmp_path / "note.txt"
assert round_trip(path, "hello") == "hello"
Focused test decision
Type this short test decision after understanding the complete runnable module. Desktop typing records practice; Run tests in the local playground executes real pytest.

Counterexamples and common mistakes

The controlled function returns stale text instead of the file’s actual contents.

The controlled function returns stale text instead of the file’s actual contents. The assertion catches it. Other mistakes include using a shared fixed filename, omitting the encoding, asserting only that a path exists, or accepting a file left by an earlier run as proof that this run wrote it.

Avoid using the current directory as a hidden parameter. Pass the path explicitly where possible. If a legacy function reads cwd, use monkeypatch.chdir(tmp_path) in that test and ensure the path does not escape the owned directory.

Controlled bug: the tests must report failure

python

def round_trip(path, text):
    path.write_text(text, encoding="utf-8")
    return "stale"


def test_ascii_round_trip(tmp_path):
    path = tmp_path / "note.txt"
    assert round_trip(path, "hello") == "hello"
Reasoning
The controlled function returns stale text instead of the file’s actual contents. The assertion catches it. Other mistakes include using a shared fixed filename, omitting the encoding, asserting only that a path exists, or accepting a file left by an earlier run as proof that this run wrote it. Avoid using the current directory as a hidden parameter. Pass the path explicitly where possible. If a legacy function reads cwd, use monkeypatch.chdir(tmp_path) in that test and ensure the path does not escape the owned directory.
Open in local Python playground ↗

Independent practice

Add a non-ASCII round-trip using a synthetic Ukrainian word and an emoji.

Add a non-ASCII round-trip using a synthetic Ukrainian word and an emoji. This tests the explicit encoding boundary with a known expected string. Retain the ASCII case; do not replace it with a broad assertion that the result is merely a string.

Start with the added assertion and run it. Then temporarily force the implementation to encode through ASCII with ignored errors. Predict that the old ASCII test will remain green while the new case loses characters.

Step 1: Add an exact UTF-8 round-trip for a non-ASCII string. Step 2: Keep the existing passing cases. Add the smallest new assertion first; predict the failure before running pytest.

Practice starter: solve before reading the solution

python

def round_trip(path, text):
    path.write_text(text, encoding="utf-8")
    return path.read_text(encoding="utf-8")


def test_ascii_round_trip(tmp_path):
    path = tmp_path / "note.txt"
    assert round_trip(path, "hello") == "hello"

# Task: Add an exact UTF-8 round-trip for a non-ASCII string.
Reasoning
Add an exact UTF-8 round-trip for a non-ASCII string.
Open in local Python playground ↗
  • Hint 1: Use tmp_path / "unicode.txt".
  • Hint 2: Compare the complete original string, including the emoji.

Solution, tests and trade-offs

The solution asserts exact Unicode preservation.

The solution asserts exact Unicode preservation. The probe strips characters through an ASCII encode/decode operation before writing. Only the newly added case detects that loss, showing why a representative encoding boundary is useful.

tmp_path directories may be retained according to pytest’s configured retention policy. Do not assume that test cleanup can delete arbitrary siblings or guarantee secure erasure. Our downloadable lab writes only its own fixtures, and the browser creates a fresh virtual project on every run.

Practice solution and acceptance checks

python

def round_trip(path, text):
    path.write_text(text, encoding="utf-8")
    return path.read_text(encoding="utf-8")


def test_ascii_round_trip(tmp_path):
    path = tmp_path / "note.txt"
    assert round_trip(path, "hello") == "hello"

def test_unicode_round_trip(tmp_path):
    assert round_trip(tmp_path / "unicode.txt", "Київ 🐍") == "Київ 🐍"
Reasoning
The solution asserts exact Unicode preservation. The probe strips characters through an ASCII encode/decode operation before writing. Only the newly added case detects that loss, showing why a representative encoding boundary is useful. tmp_path directories may be retained according to pytest’s configured retention policy. Do not assume that test cleanup can delete arbitrary siblings or guarantee secure erasure. Our downloadable lab writes only its own fixtures, and the browser creates a fresh virtual project on every run.
Open in local Python playground ↗

Interview reasoning and next step

Explain which part of this is a unit boundary and which part integrates with a real filesystem.

Explain which part of this is a unit boundary and which part integrates with a real filesystem. State why explicit encoding and owned paths improve reproducibility. If the application requires atomic replacement, permissions or crash safety, propose separate tests in an environment that can exercise those properties.

Next assert terminal output with capsys. A function that returns the right value can still emit the wrong report, so output may be another explicit observable contract.

Optional stretch — after the core task works: Introduce one deliberate implementation mistake and explain which assertion catches it. A green run alone is not evidence that every possible bug is covered.

Computer lab: https://applydjinn.com/typorithm/pytest-lab-20261106.zip. Run verify.py in an isolated environment. Worked examples and solutions pass, controlled counterexamples fail, and the new practice assertions reject a mutation missed by the baseline. Run --practice pyq-tmp-path after changing the supplied exercise. Python executes on your computer or in the browser, without submitting code to a server. Native question progress is a separate learning record.

Verify bytes and Unicode using a path supplied for this test.