Consider the following pytest test function that uses monkeypatch.chdir to change the current working directory.
What will be the printed output when this test runs?
import os import pytest def test_change_dir(monkeypatch): original_dir = os.getcwd() monkeypatch.chdir("/tmp") current_dir = os.getcwd() print(current_dir) print(original_dir == current_dir)
Think about what monkeypatch.chdir does to the current working directory during the test.
The monkeypatch.chdir("/tmp") changes the current working directory to /tmp inside the test. So os.getcwd() returns /tmp. The original directory is different, so the comparison is False.
You want to write a pytest test that confirms the current working directory changes to /var using monkeypatch.chdir. Which assertion is correct?
import os def test_dir_change(monkeypatch): monkeypatch.chdir("/var") # Which assertion below is correct?
Use == to compare strings, not is.
The correct way to check the current directory is to compare the string returned by os.getcwd() with the expected path using ==. Using is compares object identity, which is not reliable for strings.
Examine the test below. It is supposed to change the directory to /home/user and check it. However, it fails. What is the reason?
import os def test_fail_dir_change(monkeypatch): monkeypatch.chdir("/home/user") assert os.getcwd() == "/home/user" # The test fails with AssertionError.
Check if the directory exists in the environment where the test runs.
If the directory /home/user does not exist, monkeypatch.chdir cannot change to it, so os.getcwd() remains unchanged, causing the assertion to fail.
Which statement best describes the behavior of monkeypatch.chdir in pytest tests?
Think about test isolation and cleanup.
monkeypatch.chdir temporarily changes the current working directory during the test and automatically restores it after the test finishes, ensuring tests do not affect each other.
Why is it better to use monkeypatch.chdir instead of manually changing directories with os.chdir in pytest tests?
Consider test isolation and cleanup.
Using monkeypatch.chdir ensures the test environment is cleaned up by restoring the original directory after the test, avoiding interference with other tests. Manual os.chdir calls can cause side effects if not properly restored.