0
0
PyTesttesting~10 mins

monkeypatch.chdir in PyTest - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test uses monkeypatch.chdir to change the current working directory temporarily. It verifies that the directory changes inside the test and reverts after the test ends.

Test Code - pytest
PyTest
import os
import pytest

def test_change_directory(monkeypatch):
    original_dir = os.getcwd()
    new_dir = "/tmp"
    
    monkeypatch.chdir(new_dir)
    current_dir = os.getcwd()
    
    assert current_dir == new_dir
    
    # After test, directory should revert automatically
Execution Trace - 4 Steps
StepActionSystem StateAssertionResult
1Test startsTest environment ready, current directory is original_dir-PASS
2monkeypatch.chdir("/tmp") is called to change directoryCurrent working directory is changed to /tmp temporarily-PASS
3os.getcwd() is called to get current directoryCurrent directory is /tmpassert current_dir == new_dirPASS
4Test ends, monkeypatch reverts directory to original_dirCurrent directory restored to original_dir-PASS
Failure Scenario
Failing Condition: If monkeypatch.chdir does not change directory or directory is not /tmp
Execution Trace Quiz - 3 Questions
Test your understanding
What does monkeypatch.chdir do in this test?
APermanently changes the current working directory
BTemporarily changes the current working directory
CDeletes the current working directory
DCreates a new directory
Key Result
Using monkeypatch.chdir allows tests to safely change the working directory without affecting other tests or the environment, ensuring isolation and cleanup.