Bird
Raised Fist0
PyTesttesting~20 mins

monkeypatch.setenv 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 monkeypatch.setenv changes the environment variable?
Consider this pytest test function that uses monkeypatch.setenv to change an environment variable. What will be printed when the test runs?
PyTest
import os

def test_env(monkeypatch):
    monkeypatch.setenv('MY_VAR', '123')
    print(os.getenv('MY_VAR'))
ANone
B123
CMY_VAR
D'' (empty string)
Attempts:
2 left
💡 Hint
Remember that monkeypatch.setenv temporarily sets environment variables during the test.
❓ assertion
intermediate
2:00remaining
Which assertion correctly verifies the environment variable set by monkeypatch.setenv?
You want to check that the environment variable 'API_KEY' is set to 'secret' inside a pytest test using monkeypatch. Which assertion is correct?
Aassert os.getenv('API_KEY') is not None
Bassert os.environ['API_KEY'] == 'secret'
Cassert os.getenv('API_KEY') == 'secret'
Dassert monkeypatch.getenv('API_KEY') == 'secret'
Attempts:
2 left
💡 Hint
Use the standard way to get environment variables in Python.
🔧 Debug
advanced
2:00remaining
Why does this test fail to see the environment variable set by monkeypatch.setenv?
This pytest test tries to set 'CONFIG' environment variable but fails to see it inside the tested function. Why?
import os

config_cache = os.getenv('CONFIG')

def get_config():
    return config_cache

def test_config(monkeypatch):
    monkeypatch.setenv('CONFIG', 'value')
    assert get_config() == 'value'
AThe get_config function caches the environment variable before the test
BThe environment variable is not set globally, so get_config cannot see it
CThe test is missing monkeypatch.delenv('CONFIG') before setting it
DThe get_config function is called before monkeypatch.setenv runs
Attempts:
2 left
💡 Hint
Think about when environment variables are read and if caching can affect the test.
❓ framework
advanced
2:00remaining
How does monkeypatch.setenv affect environment variables during pytest test execution?
Which statement best describes the behavior of monkeypatch.setenv in pytest?
AIt temporarily sets the environment variable only during the test and restores it after
BIt sets the environment variable only for subprocesses spawned by the test
CIt sets the environment variable only if it does not already exist
DIt permanently changes the environment variable for the whole system
Attempts:
2 left
💡 Hint
Think about test isolation and cleanup.
🧠 Conceptual
expert
2:00remaining
What is the correct way to test code that reads environment variables using monkeypatch.setenv and pytest?
You have a function that reads an environment variable 'MODE'. You want to test it with different values using pytest and monkeypatch. Which approach is best?
APass the environment variable as a function argument instead of reading it inside the function
BSet the environment variable globally before running pytest and do not use monkeypatch
CModify os.environ directly without monkeypatch to set 'MODE' before each test
DUse monkeypatch.setenv('MODE', value) inside each test to set the variable, then call the function
Attempts:
2 left
💡 Hint
Consider test isolation and avoiding side effects.

Practice

(1/5)
1.

What is the main purpose of monkeypatch.setenv in pytest?

easy
A. Create new environment variables outside tests
B. Permanently change environment variables on the system
C. Temporarily change environment variables during a test
D. Delete 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 environment during tests without permanent effects.
  2. Step 2: Focus on setenv method

    The setenv method specifically changes environment variables only for the duration of the test.
  3. Final Answer:

    Temporarily change environment variables during a test -> Option C
  4. Quick Check:

    monkeypatch.setenv = temporary env change [OK]
Hint: Remember: monkeypatch.setenv only affects test-time env variables [OK]
Common Mistakes:
  • Thinking setenv changes env variables permanently
  • Confusing setenv with creating new system variables
  • Assuming changes persist after test ends
2.

Which of the following is the correct syntax to set an environment variable API_KEY to 12345 using monkeypatch.setenv in a pytest test function?

def test_api_key(monkeypatch):
    # Your code here
    assert ...
easy
A. monkeypatch.setenv('API_KEY', '12345')
B. monkeypatch.setenv('API_KEY', 12345)
C. monkeypatch.setenv(API_KEY='12345')
D. monkeypatch.setenv('API_KEY') = '12345'

Solution

  1. Step 1: Check method signature of setenv

    setenv takes two string arguments: the variable name and its value.
  2. Step 2: Identify correct string usage

    The value must be a string, so '12345' is correct, not integer 12345.
  3. Final Answer:

    monkeypatch.setenv('API_KEY', '12345') -> Option A
  4. Quick Check:

    setenv('VAR', 'value') syntax [OK]
Hint: Always pass env var values as strings in setenv [OK]
Common Mistakes:
  • Passing integer instead of string as value
  • Using keyword arguments instead of positional
  • Trying to assign value with '=' outside method call
3.

What will be the output of the following pytest test?

import os

def test_env(monkeypatch):
    monkeypatch.setenv('MODE', 'test')
    mode = os.getenv('MODE')
    assert mode == 'test'
    print(mode)
medium
A. AssertionError
B. None
C. MODE
D. test

Solution

  1. Step 1: Understand monkeypatch.setenv effect

    It sets environment variable 'MODE' to 'test' temporarily during the test.
  2. Step 2: Check os.getenv call and assertion

    os.getenv('MODE') returns 'test', so assertion passes and print outputs 'test'.
  3. Final Answer:

    test -> Option D
  4. Quick Check:

    setenv sets env var, getenv reads it [OK]
Hint: setenv changes env var for test, getenv reads it [OK]
Common Mistakes:
  • Expecting None because env var not set globally
  • Thinking assertion fails
  • Confusing variable name with value
4.

Identify the error in this pytest test using monkeypatch.setenv:

def test_path(monkeypatch):
    monkeypatch.setenv(PATH)
    assert os.getenv('PATH') == '/usr/bin'
medium
A. Missing import of os module
B. setenv missing value argument
C. Incorrect assertion syntax
D. Using monkeypatch outside test function

Solution

  1. Step 1: Check setenv method call

    setenv requires two arguments: variable name and value. Here only one argument is given.
  2. Step 2: Verify assertion and imports

    Assertion syntax is correct and os module import is assumed; error is in setenv call.
  3. Final Answer:

    setenv missing value argument -> Option B
  4. Quick Check:

    setenv needs two args: name and value [OK]
Hint: setenv always needs two strings: var name and value [OK]
Common Mistakes:
  • Calling setenv with only one argument
  • Forgetting to import os module
  • Miswriting assertion statement
5.

You want to test a function that behaves differently based on the environment variable FEATURE_FLAG. Which pytest test code correctly uses monkeypatch.setenv to test the function with FEATURE_FLAG set to enabled and ensures the environment is restored after the test?

def test_feature(monkeypatch):
    # Your code here
    result = feature_function()
    assert result == 'Feature Enabled'
hard
A. monkeypatch.setenv('FEATURE_FLAG', 'enabled')
B. os.environ['FEATURE_FLAG'] = 'enabled'
C. monkeypatch.setenv(FEATURE_FLAG='enabled')
D. monkeypatch.setenv('FEATURE_FLAG') = 'enabled'

Solution

  1. Step 1: Identify correct usage of monkeypatch.setenv

    setenv requires two string arguments: variable name and value, passed positionally.
  2. Step 2: Understand environment restoration

    Using monkeypatch.setenv ensures the env var is set only during the test and restored after, unlike direct os.environ assignment.
  3. Final Answer:

    monkeypatch.setenv('FEATURE_FLAG', 'enabled') -> Option A
  4. Quick Check:

    Use monkeypatch.setenv for temporary env changes [OK]
Hint: Use monkeypatch.setenv for temp env vars, not os.environ [OK]
Common Mistakes:
  • Directly modifying os.environ without monkeypatch
  • Using keyword arguments in setenv
  • Trying to assign value outside setenv call
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