0
0
PyTesttesting~15 mins

tmp_path and tmp_path_factory in PyTest - Build an Automation Script

Choose your learning style9 modes available
Create and verify temporary files using tmp_path and tmp_path_factory in pytest
Preconditions (2)
Step 1: Use the tmp_path fixture to create a temporary directory
Step 2: Inside this directory, create a file named 'testfile.txt' with content 'Hello pytest!'
Step 3: Verify that the file exists and contains the correct content
Step 4: Use the tmp_path_factory fixture to create a new temporary directory with a custom prefix 'myprefix'
Step 5: Inside this new directory, create a file named 'factoryfile.txt' with content 'Factory test content'
Step 6: Verify that this file exists and contains the correct content
✅ Expected Result: Both files are created successfully in their respective temporary directories with the correct content, and the directories are unique and cleaned up after tests
Automation Requirements - pytest
Assertions Needed:
Assert that 'testfile.txt' exists in tmp_path directory
Assert that the content of 'testfile.txt' is 'Hello pytest!'
Assert that 'factoryfile.txt' exists in the directory created by tmp_path_factory
Assert that the content of 'factoryfile.txt' is 'Factory test content'
Best Practices:
Use pytest fixtures tmp_path and tmp_path_factory for isolated temporary directories
Use pathlib.Path methods for file operations
Use assertions to verify file existence and content
Avoid hardcoding absolute paths
Let pytest handle cleanup of temporary directories
Automated Solution
PyTest
import pytest


def test_tmp_path_and_tmp_path_factory(tmp_path, tmp_path_factory):
    # Using tmp_path fixture
    test_file = tmp_path / "testfile.txt"
    test_file.write_text("Hello pytest!")
    
    # Assert file exists
    assert test_file.exists(), f"File {test_file} should exist"
    
    # Assert file content
    content = test_file.read_text()
    assert content == "Hello pytest!", f"File content should be 'Hello pytest!' but got '{content}'"

    # Using tmp_path_factory fixture
    custom_dir = tmp_path_factory.mktemp("myprefix")
    factory_file = custom_dir / "factoryfile.txt"
    factory_file.write_text("Factory test content")

    # Assert file exists
    assert factory_file.exists(), f"File {factory_file} should exist"

    # Assert file content
    factory_content = factory_file.read_text()
    assert factory_content == "Factory test content", f"File content should be 'Factory test content' but got '{factory_content}'"

This test function uses two pytest fixtures: tmp_path and tmp_path_factory.

First, tmp_path provides a temporary directory unique to this test. We create a file testfile.txt inside it and write text. We then check if the file exists and if its content matches what we wrote.

Next, tmp_path_factory is used to create another temporary directory with a custom prefix myprefix. Inside this directory, we create another file factoryfile.txt and write different content. We verify the file's existence and content similarly.

Using pathlib's Path methods makes file handling easy and readable. Assertions ensure the test fails if files are missing or contents are wrong. Pytest automatically cleans up these temporary directories after the test finishes, so no manual cleanup is needed.

Common Mistakes - 4 Pitfalls
Using string paths instead of pathlib.Path objects for file operations
Not asserting file existence before reading content
Hardcoding absolute paths or assuming fixed directory locations
{'mistake': 'Manually deleting temporary files or directories', 'why_bad': 'Pytest automatically cleans up temporary directories; manual deletion can cause errors or race conditions.', 'correct_approach': "Rely on pytest's automatic cleanup and avoid manual file or directory removal."}
Bonus Challenge

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

Show Hint