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
tmp_pathis a fresh directory per test.monkeypatchundoes its changes when the test ends.capsyscaptures what the code printed.
Keywords and builtins used here
assertcount_linesdeflenprintreportreturntest_counts_linestest_reads_the_environment
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.
Step 2 of 2 in Fixtures, step 5 of 9 in Testing with pytest.