Bird
Raised Fist0
PyTesttesting~20 mins

monkeypatch.chdir in PyTest - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Monkeypatch Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output after using monkeypatch.chdir?

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?

PyTest
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)
A
Original directory path
True
B
/tmp
True
C
Original directory path
False
D
/tmp
False
Attempts:
2 left
💡 Hint

Think about what monkeypatch.chdir does to the current working directory during the test.

❓ assertion
intermediate
1:30remaining
Which assertion correctly verifies directory change with monkeypatch.chdir?

You want to write a pytest test that confirms the current working directory changes to /var using monkeypatch.chdir. Which assertion is correct?

PyTest
import os
def test_dir_change(monkeypatch):
    monkeypatch.chdir("/var")
    # Which assertion below is correct?
Aassert os.getcwd() == "/tmp"
Bassert os.getcwd() != "/var"
Cassert os.getcwd() == "/var"
Dassert os.getcwd() is "/var"
Attempts:
2 left
💡 Hint

Use == to compare strings, not is.

🔧 Debug
advanced
2:00remaining
Why does this test fail when using monkeypatch.chdir?

Examine the test below. It is supposed to change the directory to /home/user and check it. However, it fails. What is the reason?

PyTest
import os
def test_fail_dir_change(monkeypatch):
    monkeypatch.chdir("/home/user")
    assert os.getcwd() == "/home/user"

# The test fails with AssertionError.
AThe directory /home/user does not exist in the test environment.
Bmonkeypatch.chdir does not actually change the directory.
CThe assertion syntax is incorrect.
Dos.getcwd() returns a relative path, not absolute.
Attempts:
2 left
💡 Hint

Check if the directory exists in the environment where the test runs.

❓ framework
advanced
1:30remaining
How does monkeypatch.chdir affect tests in pytest?

Which statement best describes the behavior of monkeypatch.chdir in pytest tests?

AIt permanently changes the working directory for all tests in the session.
BIt changes the current working directory only for the duration of the test function and restores it afterward.
CIt changes the directory globally and does not restore it after the test.
DIt only simulates directory change without affecting os.getcwd().
Attempts:
2 left
💡 Hint

Think about test isolation and cleanup.

🧠 Conceptual
expert
2:30remaining
What is the main benefit of using monkeypatch.chdir in tests?

Why is it better to use monkeypatch.chdir instead of manually changing directories with os.chdir in pytest tests?

Amonkeypatch.chdir automatically restores the original directory after the test, preventing side effects.
Bmonkeypatch.chdir changes directories faster than os.chdir.
Cmonkeypatch.chdir changes the directory globally for all running processes.
Dmonkeypatch.chdir works outside of pytest tests as well.
Attempts:
2 left
💡 Hint

Consider test isolation and cleanup.

Practice

(1/5)
1. What is the main purpose of using monkeypatch.chdir in pytest tests?
easy
A. To temporarily change the current working directory during a test
B. To permanently change the system's default directory
C. To mock HTTP requests in tests
D. To patch environment variables permanently

Solution

  1. Step 1: Understand the role of monkeypatch in pytest

    Monkeypatch is used to temporarily modify or replace parts of the system during tests without permanent changes.
  2. Step 2: Focus on the chdir method

    monkeypatch.chdir specifically changes the current working directory only for the duration of the test.
  3. Final Answer:

    To temporarily change the current working directory during a test -> Option A
  4. Quick Check:

    monkeypatch.chdir = temporary directory change [OK]
Hint: Remember monkeypatch changes things only during tests [OK]
Common Mistakes:
  • Thinking it changes directories permanently
  • Confusing with mocking HTTP requests
  • Using it to patch environment variables permanently
2. Which of the following is the correct syntax to change the current directory to '/tmp' using monkeypatch in a pytest test function?
easy
A. monkeypatch.chdir('/tmp')
B. monkeypatch.chdir = '/tmp'
C. monkeypatch.change_dir('/tmp')
D. monkeypatch.chdir('/tmp', permanent=True)

Solution

  1. Step 1: Recall the method name and usage

    The correct method to change directory temporarily is monkeypatch.chdir(path).
  2. Step 2: Check each option for syntax correctness

    Assignment like chdir = '/tmp' is incorrect; it must be called as a function. change_dir is the wrong method name. Adding permanent=True is unsupported.
  3. Final Answer:

    monkeypatch.chdir('/tmp') -> Option A
  4. Quick Check:

    Correct method call = monkeypatch.chdir(path) [OK]
Hint: Use monkeypatch.chdir(path) exactly as a function call [OK]
Common Mistakes:
  • Assigning instead of calling the method
  • Using wrong method names like change_dir
  • Adding unsupported arguments
3. Given the following pytest test code, what will be the output of 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_dir
medium
A. original_dir value
B. /tmp
C. Raises FileNotFoundError
D. Empty string

Solution

  1. Step 1: Understand what monkeypatch.chdir does

    It temporarily changes the current working directory to the given path during the test.
  2. Step 2: Analyze the print statement after monkeypatch.chdir

    Since monkeypatch.chdir('/tmp') is called, os.getcwd() will return '/tmp' inside the test.
  3. Final Answer:

    /tmp -> Option B
  4. Quick Check:

    os.getcwd() after monkeypatch.chdir('/tmp') = '/tmp' [OK]
Hint: After monkeypatch.chdir(path), os.getcwd() returns path [OK]
Common Mistakes:
  • Expecting original directory instead of changed one
  • Thinking it raises an error if directory exists
  • Assuming it returns empty string
4. Identify the error in this pytest test using monkeypatch.chdir:
import os

def test_dir_change(monkeypatch):
    monkeypatch.chdir('/nonexistent')
    assert os.getcwd() == '/nonexistent'
medium
A. assert statement syntax is incorrect
B. monkeypatch.chdir should be called without arguments
C. The directory '/nonexistent' may not exist, causing an error
D. os.getcwd() cannot be used inside tests

Solution

  1. Step 1: Check the directory path used in monkeypatch.chdir

    The path '/nonexistent' likely does not exist on the system, which causes an error when changing directory.
  2. Step 2: Understand monkeypatch.chdir behavior with invalid paths

    It tries to change directory and will raise FileNotFoundError if the path is invalid.
  3. Final Answer:

    The directory '/nonexistent' may not exist, causing an error -> Option C
  4. Quick Check:

    Invalid path in monkeypatch.chdir causes error [OK]
Hint: Ensure directory exists before monkeypatch.chdir call [OK]
Common Mistakes:
  • Thinking monkeypatch.chdir works without a valid path
  • Believing os.getcwd() is invalid in tests
  • Misreading assert syntax
5. You want to test a function that reads a file named 'data.txt' in the current directory. How can you use monkeypatch.chdir to test this function with a temporary test folder '/tmp/testfolder' containing 'data.txt' without affecting other tests?
hard
A. Copy 'data.txt' to the original directory and run the test there
B. Change directory globally before running all tests
C. Use monkeypatch.chdir('/tmp/testfolder') and set permanent=True
D. Use monkeypatch.chdir('/tmp/testfolder') inside the test to change directory temporarily

Solution

  1. Step 1: Understand the need for isolation in tests

    Tests should not affect global state or other tests, so changing directory temporarily is best.
  2. Step 2: Use monkeypatch.chdir to change directory only during the test

    Calling monkeypatch.chdir('/tmp/testfolder') changes the current directory only inside the test, isolating file access.
  3. Final Answer:

    Use monkeypatch.chdir('/tmp/testfolder') inside the test to change directory temporarily -> Option D
  4. Quick Check:

    Temporary directory change isolates test file access [OK]
Hint: Use monkeypatch.chdir(path) to isolate file-based tests [OK]
Common Mistakes:
  • Changing directory globally affecting other tests
  • Copying files unnecessarily
  • Using unsupported permanent argument
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard