0
0
PyTesttesting~15 mins

File system testing with tmp_path in PyTest - Build an Automation Script

Choose your learning style9 modes available
Create and verify a file using tmp_path fixture in pytest
Preconditions (2)
Step 1: Use the tmp_path fixture to get a temporary directory
Step 2: Create a new file named 'testfile.txt' inside the tmp_path directory
Step 3: Write the text 'Hello, pytest!' into the file
Step 4: Read the content of the file
Step 5: Verify that the content matches 'Hello, pytest!'
✅ Expected Result: The file 'testfile.txt' is created in the temporary directory with the exact content 'Hello, pytest!'
Automation Requirements - pytest
Assertions Needed:
Assert the file 'testfile.txt' exists in the tmp_path directory
Assert the file content equals 'Hello, pytest!'
Best Practices:
Use the tmp_path fixture for isolated temporary file system testing
Use context managers for file operations
Keep tests independent and clean up automatically
Automated Solution
PyTest
import pytest

def test_create_and_read_file(tmp_path):
    # Create a file path object for 'testfile.txt'
    file = tmp_path / "testfile.txt"
    # Write text to the file using context manager
    with file.open('w', encoding='utf-8') as f:
        f.write('Hello, pytest!')
    # Read the content back
    with file.open('r', encoding='utf-8') as f:
        content = f.read()
    # Assert the file exists
    assert file.exists(), f"File {file} should exist"
    # Assert the content is correct
    assert content == 'Hello, pytest!', f"File content should be 'Hello, pytest!' but was '{content}'"

This test uses the tmp_path fixture provided by pytest to get a temporary directory unique to this test run. It creates a file named testfile.txt inside this directory.

Using a context manager (with statement) ensures the file is properly opened and closed when writing and reading.

Assertions check that the file exists and that its content matches the expected string. This ensures the file system operations are working as intended in an isolated environment.

Using tmp_path keeps tests clean and avoids side effects on the real file system.

Common Mistakes - 3 Pitfalls
Not using tmp_path and writing files to a fixed directory
Not closing files properly after writing or reading
Not asserting file existence before reading content
Bonus Challenge

Now add data-driven testing to create and verify files with three different contents

Show Hint