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.
B. Missing assertion statement causes test failure
C. Using + operator to join paths causes a TypeError
D. tmp_path fixture is not passed as argument
Solution
Step 1: Check path joining method
tmp_path is a Path object; using + with string causes TypeError.
Step 2: Correct path joining
Use tmp_path / 'file.txt' to join paths properly.
Final Answer:
Using + operator to join paths causes a TypeError -> Option C
Quick Check:
Path + string = error; use / operator [OK]
Hint: Join paths with / operator, not + [OK]
Common Mistakes:
Using + to join Path and string
Forgetting to pass tmp_path as parameter
Assuming write_text is invalid method
5. You want to create a nested directory structure inside tmp_path and write a file in the deepest folder. Which code snippet correctly does this in pytest?