Challenge - 5 Problems
tmp_path Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of tmp_path usage in pytest
What is the output of this pytest test function when run?
PyTest
def test_tmp_path_usage(tmp_path): file = tmp_path / "testfile.txt" file.write_text("hello") content = file.read_text() assert content == "hello" print(len(list(tmp_path.iterdir())))
Attempts:
2 left
💡 Hint
tmp_path is a temporary directory unique to the test function.
✗ Incorrect
The test creates one file inside tmp_path, so iterating tmp_path yields one item. The printed length is 1.
❓ assertion
intermediate1:30remaining
Correct assertion for tmp_path_factory usage
Which assertion correctly verifies that a directory created by tmp_path_factory exists?
PyTest
def test_tmp_path_factory(tmp_path_factory): new_dir = tmp_path_factory.mktemp("mydir")
Attempts:
2 left
💡 Hint
mktemp creates a new temporary directory.
✗ Incorrect
mktemp returns a Path object for a new directory. It must exist and be a directory.
🔧 Debug
advanced2:00remaining
Identify the error in tmp_path usage
What error will this pytest test raise?
PyTest
def test_write_file(tmp_path): file = tmp_path / 123 file.write_text("data")
Attempts:
2 left
💡 Hint
Path objects expect string or Path-like objects for joining.
✗ Incorrect
Using an integer to join a path raises TypeError because the / operator expects a string or Path.
🧠 Conceptual
advanced2:30remaining
Difference between tmp_path and tmp_path_factory
Which statement correctly describes the difference between tmp_path and tmp_path_factory in pytest?
Attempts:
2 left
💡 Hint
Think about scope and number of directories created.
✗ Incorrect
tmp_path is a per-test temporary directory. tmp_path_factory can create multiple directories and can be shared across tests.
❓ framework
expert3:00remaining
Using tmp_path_factory for shared test resources
You want to create a temporary directory shared by multiple test functions in the same module using pytest fixtures. Which fixture setup correctly uses tmp_path_factory to achieve this?
PyTest
import pytest @pytest.fixture(scope="module") def shared_tmp_dir(tmp_path_factory): dir = tmp_path_factory.mktemp("shared") return dir def test_one(shared_tmp_dir): file = shared_tmp_dir / "file1.txt" file.write_text("one") assert file.read_text() == "one" def test_two(shared_tmp_dir): file = shared_tmp_dir / "file2.txt" file.write_text("two") assert file.read_text() == "two"
Attempts:
2 left
💡 Hint
Consider fixture scope and tmp_path_factory capabilities.
✗ Incorrect
Using tmp_path_factory.mktemp inside a module-scoped fixture creates a shared temp directory for all tests in the module.