Test function behavior after changing current working directory using monkeypatch.chdir
Preconditions (2)
✅ Expected Result: The function returns the temporary directory path set by monkeypatch.chdir
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.
Now add data-driven testing with 3 different temporary directories and verify the function returns each correctly
monkeypatch.chdir in pytest tests?chdir methodmonkeypatch.chdir specifically changes the current working directory only for the duration of the test.monkeypatch.chdir(path).chdir = '/tmp' is incorrect; it must be called as a function. change_dir is the wrong method name. Adding permanent=True is unsupported.print(os.getcwd()) inside the test?import os
def test_change_dir(monkeypatch):
original_dir = os.getcwd()
monkeypatch.chdir('/tmp')
print(os.getcwd())
assert os.getcwd() != original_dirmonkeypatch.chdir('/tmp') is called, os.getcwd() will return '/tmp' inside the test.import os
def test_dir_change(monkeypatch):
monkeypatch.chdir('/nonexistent')
assert os.getcwd() == '/nonexistent'monkeypatch.chdir to test this function with a temporary test folder '/tmp/testfolder' containing 'data.txt' without affecting other tests?monkeypatch.chdir('/tmp/testfolder') changes the current directory only inside the test, isolating file access.Pass the test and this pattern moves unknown