typestar

Built-in fixtures in Python

tmp_path, monkeypatch and capsys cover most of what a test needs.

import os
from pathlib import Path


def count_lines(path):
    return len(Path(path).read_text().splitlines())


def report(name):
    print(f"theme is {os.environ.get('TYPESTAR_THEME', 'default')}")
    return name


def test_counts_lines(tmp_path):
    target = tmp_path / "runs.txt"
    target.write_text("one\ntwo\nthree\n")
    assert count_lines(target) == 3


def test_reads_the_environment(monkeypatch, capsys):
    monkeypatch.setenv("TYPESTAR_THEME", "monokai")
    report("x")
    assert "monokai" in capsys.readouterr().out

How it works

  1. tmp_path is a fresh directory per test.
  2. monkeypatch undoes its changes when the test ends.
  3. capsys captures what the code printed.

Keywords and builtins used here

The run, in numbers

Lines
23
Characters to type
500
Tokens
130
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 74 seconds.

Type this snippet

Step 2 of 2 in Fixtures, step 5 of 9 in Testing with pytest.

← Previous Next →