0
0
PyTesttesting~15 mins

Temporary directory management in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify temporary directory creation and cleanup using pytest tmp_path fixture
Preconditions (2)
Step 1: Use pytest tmp_path fixture to create a temporary directory
Step 2: Inside the test, create a new file named 'testfile.txt' in the temporary directory
Step 3: Write the text 'Hello, pytest!' into the file
Step 4: Read the file content and verify it matches 'Hello, pytest!'
Step 5: After the test finishes, verify that the temporary directory and its contents are deleted automatically
✅ Expected Result: The file 'testfile.txt' is created with correct content during the test, and the temporary directory is removed after test completion
Automation Requirements - pytest
Assertions Needed:
Assert that the file 'testfile.txt' exists in the temporary directory
Assert that the file content equals 'Hello, pytest!'
Best Practices:
Use pytest tmp_path fixture for temporary directory management
Avoid hardcoding paths; use pathlib.Path methods
Do not manually delete temporary files or directories; rely on pytest cleanup
Keep tests isolated and independent
Automated Solution
PyTest
import pytest


def test_temporary_directory(tmp_path):
    # Create a file path in the temporary directory
    file_path = tmp_path / "testfile.txt"
    # Write text to the file
    file_path.write_text("Hello, pytest!")
    # Read the text back
    content = file_path.read_text()
    # Assert the file exists
    assert file_path.exists(), f"File {file_path} should exist"
    # Assert the content is correct
    assert content == "Hello, pytest!", f"File content should be 'Hello, pytest!' but was '{content}'"

# Note: pytest automatically cleans up tmp_path after test execution

This test uses the tmp_path fixture provided by pytest to create a temporary directory unique to the test run.

We create a file testfile.txt inside this directory and write the string 'Hello, pytest!' to it.

Then, we read the file content and assert that the file exists and the content matches what we wrote.

We rely on pytest to automatically delete the temporary directory and its contents after the test finishes, so no manual cleanup is needed.

This approach keeps tests isolated and avoids side effects on the real file system.

Common Mistakes - 3 Pitfalls
Hardcoding file paths instead of using tmp_path fixture
Manually deleting temporary files or directories in the test
Not asserting file existence before reading content
Bonus Challenge

Now add data-driven testing to create multiple files with different names and contents using pytest parametrize

Show Hint