0
0
PyTesttesting~15 mins

monkeypatch.chdir in PyTest - Build an Automation Script

Choose your learning style9 modes available
Test function behavior after changing current working directory using monkeypatch.chdir
Preconditions (2)
Step 1: Use monkeypatch.chdir to change the current working directory to a temporary directory
Step 2: Call the function that returns the current working directory
Step 3: Verify that the returned directory path matches the temporary directory path
✅ Expected Result: The function returns the temporary directory path set by monkeypatch.chdir
Automation Requirements - pytest
Assertions Needed:
Assert that the function returns the temporary directory path after monkeypatch.chdir
Best Practices:
Use pytest's monkeypatch fixture to change directories
Use tmp_path fixture to create a temporary directory
Keep tests isolated and clean up automatically
Automated Solution
PyTest
import os
import pytest

def get_current_directory():
    return os.getcwd()


def test_monkeypatch_chdir(monkeypatch, tmp_path):
    # Change current directory to tmp_path
    monkeypatch.chdir(tmp_path)
    # Call the function that returns current directory
    current_dir = get_current_directory()
    # Assert it matches tmp_path
    assert current_dir == str(tmp_path), f"Expected {tmp_path}, got {current_dir}"

This test uses pytest's monkeypatch.chdir to temporarily change the current working directory to a tmp_path provided by pytest.

The get_current_directory function returns the current directory using os.getcwd().

After changing the directory, the test asserts that the returned directory matches the temporary directory path.

This ensures the function behaves correctly when the working directory changes.

Common Mistakes - 3 Pitfalls
Not using monkeypatch.chdir and instead using os.chdir directly
{'mistake': 'Not using tmp_path fixture and hardcoding directory paths', 'why_bad': 'Hardcoded paths may not exist on all machines and can cause tests to fail or be non-portable.', 'correct_approach': "Use pytest's tmp_path fixture to create a reliable temporary directory for testing."}
Not asserting the directory path as a string
Bonus Challenge

Now add data-driven testing with 3 different temporary directories and verify the function returns each correctly

Show Hint