Recall & Review
beginner
What is the purpose of using a temporary directory in pytest tests?
A temporary directory provides a safe, isolated space to create files or folders during tests without affecting the real file system. It is automatically cleaned up after the test finishes.
Click to reveal answer
beginner
How do you access a temporary directory in a pytest test function?
You use the built-in pytest fixture called
tmp_path or tmpdir. Just add it as a parameter to your test function, and pytest provides a fresh temporary directory path.Click to reveal answer
intermediate
What is the difference between
tmp_path and tmpdir fixtures in pytest?tmp_path returns a pathlib.Path object, which is modern and recommended. tmpdir returns a py.path.local object, which is older. Both create temporary directories.Click to reveal answer
beginner
Why is it important that pytest cleans up the temporary directory after the test?
Cleaning up prevents leftover files from filling disk space or interfering with other tests. It keeps tests independent and the environment clean.
Click to reveal answer
beginner
Show a simple pytest test function that writes a file in a temporary directory using
tmp_path.import pytest
def test_write_file(tmp_path):
file = tmp_path / "test.txt"
file.write_text("hello")
assert file.read_text() == "hello"Click to reveal answer
Which pytest fixture provides a temporary directory as a pathlib.Path object?
✗ Incorrect
tmp_path returns a pathlib.Path object for temporary directories. tmpdir returns a py.path.local object.
What happens to the temporary directory created by pytest after the test finishes?
✗ Incorrect
pytest automatically cleans up temporary directories after tests to keep the environment clean.
Why should tests use temporary directories instead of real folders?
✗ Incorrect
Temporary directories isolate test data and prevent side effects on real files.
Which of these is NOT a pytest fixture for temporary directories?
✗ Incorrect
tmp_file is not a pytest fixture. tmp_path and tmpdir are valid fixtures.
In pytest, how do you write text to a file inside a temporary directory using
tmp_path?✗ Incorrect
tmp_path uses pathlib.Path syntax: use / to join paths and write_text() to write text.
Explain how pytest's temporary directory fixtures help keep tests independent and clean.
Think about why tests should not share or keep files after running.
You got /4 concepts.
Describe the difference between pytest's tmp_path and tmpdir fixtures and when to prefer one over the other.
Consider the Python standard library's pathlib module.
You got /4 concepts.