Test function behavior with monkeypatched environment variable
Preconditions (2)
✅ Expected Result: The function returns the monkeypatched environment variable value 'test123'
import os import pytest def get_api_key(): return os.getenv('API_KEY') def test_get_api_key(monkeypatch): # Use monkeypatch to set environment variable monkeypatch.setenv('API_KEY', 'test123') # Call the function that reads the environment variable result = get_api_key() # Assert the returned value matches the monkeypatched value assert result == 'test123'
This test uses pytest's monkeypatch fixture to temporarily set the environment variable API_KEY to test123. The function get_api_key reads this environment variable using os.getenv. The test then asserts that the function returns the monkeypatched value.
Using monkeypatch.setenv ensures the environment variable is only changed during this test and restored afterward, keeping tests isolated and reliable.
Now add data-driven testing with 3 different environment variable values
monkeypatch fixture in pytest?monkeypatch to replace a function get_data in a module my_module?monkeypatch.setattr(target, value) where target is a string path.def get_value():
return 10
def test_value(monkeypatch):
monkeypatch.setattr('__main__.get_value', lambda: 5)
assert get_value() == ?get_value in the __main__ module with a lambda returning 5.get_value() now returns 5, so assert get_value() == 5 passes.def test_env(monkeypatch):
monkeypatch.setenv('API_KEY')
assert os.getenv('API_KEY') is Nonesetenv method requires both a key and a value to set an environment variable.open. How can you use monkeypatch to avoid reading a real file and instead provide fake content?open with a function returning a StringIO object simulates file reading without disk access.builtins.open with a lambda or function returning StringIO containing fake content.Pass the test and this pattern moves unknown