Files with tmp_path
Code that reads and writes files needs a real folder to test against, and it should never be one you care about. Ask for the tmp_path fixture and each test gets a new, empty directory as a pathlib.Path. Nothing outside it changes, and tests cannot see each other's files.
import tempfile
from pathlib import Path
def save_lines(path, lines):
path.write_text("\n".join(lines) + "\n")
def test_save_lines(tmp_path):
target = tmp_path / "out.txt"
save_lines(target, ["a", "b"])
assert target.read_text() == "a\nb\n"
# pytest does roughly this for you:
with tempfile.TemporaryDirectory(
dir=".") as folder:
test_save_lines(Path(folder))
print("passed")Arrange with files
Write the input files in the arrange step, with write_text. Then test the cases where file code tends to break: a missing file, an empty one, odd lines.
A test that writes to a fixed path such as settings.txt passes on your machine, but it leaves a file behind, can overwrite a real one, and collides with any other test using the same name.
Your task
load_settings(path) is written for you. Write test_reads_pairs, test_skips_comments_and_blanks and test_missing_file_gives_empty_dict, each taking tmp_path and writing only inside it: two key = value lines (spaces around =) in the first, and a comment, a blank line and one setting in the second.
The explanation opens here once every check passes.