Test Overview
This test demonstrates how to use tmp_path and tmp_path_factory in pytest to create temporary directories and files. It verifies that files created in these temporary paths exist and contain the expected content.
This test demonstrates how to use tmp_path and tmp_path_factory in pytest to create temporary directories and files. It verifies that files created in these temporary paths exist and contain the expected content.
import pytest # Test using tmp_path fixture def test_tmp_path_creates_file(tmp_path): file = tmp_path / "testfile.txt" file.write_text("hello world") assert file.exists() assert file.read_text() == "hello world" # Test using tmp_path_factory fixture @pytest.fixture def custom_tmp_dir(tmp_path_factory): return tmp_path_factory.mktemp("custom") def test_tmp_path_factory_creates_file(custom_tmp_dir): file = custom_tmp_dir / "data.txt" file.write_text("pytest tmp_path_factory") assert file.exists() assert file.read_text() == "pytest tmp_path_factory"
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | pytest test runner initialized | - | PASS |
| 2 | pytest injects tmp_path fixture into test_tmp_path_creates_file | Temporary directory created for this test | - | PASS |
| 3 | Create file 'testfile.txt' in tmp_path and write 'hello world' | File 'testfile.txt' exists in temporary directory with content 'hello world' | Check file exists | PASS |
| 4 | Read file content and assert it equals 'hello world' | File content is 'hello world' | Assert file.read_text() == 'hello world' | PASS |
| 5 | pytest injects tmp_path_factory fixture into custom_tmp_dir fixture | Temporary directory 'custom' created by tmp_path_factory | - | PASS |
| 6 | custom_tmp_dir fixture returns the 'custom' temporary directory | Test receives custom temporary directory path | - | PASS |
| 7 | Create file 'data.txt' in custom_tmp_dir and write 'pytest tmp_path_factory' | File 'data.txt' exists in 'custom' directory with content 'pytest tmp_path_factory' | Check file exists | PASS |
| 8 | Read file content and assert it equals 'pytest tmp_path_factory' | File content is 'pytest tmp_path_factory' | Assert file.read_text() == 'pytest tmp_path_factory' | PASS |
| 9 | Test ends | All assertions passed, temporary files cleaned up after test | - | PASS |