Create a temporary file fixture in pytest

We can use tmp_path fixture which is a pathlib.Path object.[1] This file will be stored in a random location under /tmp location.

def test_create_file(tmp_path: Path):
	d = tmp_path / 'sub'
	d.mkdir()
	p = d / 'hello.txt'
	p.write_text("hello!")
	assert p.read_text() == 'hello!'
	assert len(list(tmp_path.iterdir())) == 1

  1. https://docs.pytest.org/en/7.1.x/how-to/tmp_path.html ↩︎