Sometimes, tests need temporary files or directories. You can do this in Python’s unittest with the standard library tempfile module. Let’s look at some recipes to do so within individual tests and setUp().
This. We kinda stumbled on this pattern, and use it to great effect. Simplified code:
@pytest.fixture
def tmpfiles():
with NamedTemporaryFile(suffix=".html") as f:
yield f
# or for paths, which are more suitable for certain tests
# touch them so they exist
@pytest.fixture
def othertmppaths() -> list[Path]:
f1 = Path("...")
f1.touch()
f2 = Path("...")
f2.touch()
yield [f1, f2]
# you could delete them here if needed
f1.unlink()
def test_foo(othertmppaths list[Path]):
result = upload_resource(othertmppaths[0])
assert result.status == 200
The context manager one will properly clean up all files.
People still use unitest instead of pytest fixtures? https://docs.pytest.org/en/6.2.x/tmpdir.html
This. We kinda stumbled on this pattern, and use it to great effect. Simplified code:
@pytest.fixture def tmpfiles(): with NamedTemporaryFile(suffix=".html") as f: yield f # or for paths, which are more suitable for certain tests # touch them so they exist @pytest.fixture def othertmppaths() -> list[Path]: f1 = Path("...") f1.touch() f2 = Path("...") f2.touch() yield [f1, f2] # you could delete them here if needed f1.unlink() def test_foo(othertmppaths list[Path]): result = upload_resource(othertmppaths[0]) assert result.status == 200
The context manager one will properly clean up all files.
E: Pretty website btw
Often using pytest to debug code. When using a tmp_path, would prefer not to delete the file tree in the end.
When the test fails, can run the code against the folder tree
cd
into the tmp folder