We use monkeypatch.chdir to temporarily change the current folder during a test. This helps test code that works with files or folders without changing your real working folder.
0
0
monkeypatch.chdir in PyTest
Introduction
Testing a function that reads files from a specific folder.
Checking how your code behaves when run in different directories.
Avoiding side effects by not changing the real current folder during tests.
Running tests that create or delete files in a temporary folder.
Simulating running your program from another folder.
Syntax
PyTest
monkeypatch.chdir(path)
path can be a string or a pathlib.Path object representing the folder to switch to.
This change lasts only during the test function where you use it.
Examples
Change current folder to
/tmp and check it.PyTest
import os def test_change_dir(monkeypatch): monkeypatch.chdir('/tmp') assert os.getcwd() == '/tmp'
Use
pathlib.Path to change directory.PyTest
from pathlib import Path def test_with_pathlib(monkeypatch): monkeypatch.chdir(Path('/var')) assert Path.cwd() == Path('/var')
Sample Program
This test changes the current folder to /tmp temporarily. It prints the current folder and checks it is /tmp.
PyTest
import os from pathlib import Path def test_temp_dir(monkeypatch): temp_dir = Path('/tmp') monkeypatch.chdir(temp_dir) current = Path.cwd() print(f'Current directory is: {current}') assert current == temp_dir
OutputSuccess
Important Notes
Always use monkeypatch.chdir inside test functions with the monkeypatch fixture.
It does not change the folder outside the test, so your real environment stays safe.
If the folder does not exist, the test will fail, so ensure the path is valid.
Summary
monkeypatch.chdir temporarily changes the current working directory during a test.
It helps test code that depends on the current folder without side effects.
Use it with the monkeypatch fixture inside pytest test functions.