0
0
PyTesttesting~10 mins

tmp_path and tmp_path_factory in PyTest - Test Execution Trace

Choose your learning style9 modes available
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.

Test Code - pytest
PyTest
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"
Execution Trace - 9 Steps
StepActionSystem StateAssertionResult
1Test startspytest test runner initialized-PASS
2pytest injects tmp_path fixture into test_tmp_path_creates_fileTemporary directory created for this test-PASS
3Create file 'testfile.txt' in tmp_path and write 'hello world'File 'testfile.txt' exists in temporary directory with content 'hello world'Check file existsPASS
4Read file content and assert it equals 'hello world'File content is 'hello world'Assert file.read_text() == 'hello world'PASS
5pytest injects tmp_path_factory fixture into custom_tmp_dir fixtureTemporary directory 'custom' created by tmp_path_factory-PASS
6custom_tmp_dir fixture returns the 'custom' temporary directoryTest receives custom temporary directory path-PASS
7Create 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 existsPASS
8Read 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
9Test endsAll assertions passed, temporary files cleaned up after test-PASS
Failure Scenario
Failing Condition: File is not created or content does not match expected string
Execution Trace Quiz - 3 Questions
Test your understanding
What does the tmp_path fixture provide in pytest?
AA permanent directory shared across tests
BA temporary directory unique to the test function
CA temporary file only
DA database connection
Key Result
Using tmp_path and tmp_path_factory fixtures in pytest helps create isolated temporary directories for tests, ensuring no leftover files affect other tests and making tests reliable and clean.