0
0
PyTesttesting~5 mins

Temporary directory management in PyTest - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Atmp_path
Btmpdir
Ctempfile
Dtemp_dir
What happens to the temporary directory created by pytest after the test finishes?
AIt remains on disk until manually deleted
BIt is deleted automatically
CIt is moved to a backup folder
DIt is archived as a zip file
Why should tests use temporary directories instead of real folders?
ATo permanently save test data
BTo speed up test execution
CTo share files between tests
DTo avoid affecting real files and keep tests isolated
Which of these is NOT a pytest fixture for temporary directories?
Atmp_path
Btempfile
Ctmp_file
Dtmpdir
In pytest, how do you write text to a file inside a temporary directory using tmp_path?
Afile = tmp_path / 'file.txt'; file.write_text('data')
Bfile = tmp_path.join('file.txt'); file.write('data')
Cfile = tmp_path.create_file('file.txt'); file.write('data')
Dfile = tmp_path.open('file.txt'); file.write('data')
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.