0
0
PyTesttesting~15 mins

monkeypatch fixture in PyTest - Build an Automation Script

Choose your learning style9 modes available
Test function behavior with monkeypatched environment variable
Preconditions (2)
Step 1: Use the monkeypatch fixture to set the environment variable 'API_KEY' to 'test123'
Step 2: Call the function that reads 'API_KEY'
Step 3: Verify the function returns 'test123'
✅ Expected Result: The function returns the monkeypatched environment variable value 'test123'
Automation Requirements - pytest
Assertions Needed:
Assert the function returns the monkeypatched environment variable value
Best Practices:
Use the monkeypatch fixture parameter in the test function
Patch environment variables using monkeypatch.setenv
Keep tests isolated and independent
Automated Solution
PyTest
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.

Common Mistakes - 3 Pitfalls
{'mistake': 'Not using the monkeypatch fixture parameter in the test function', 'why_bad': 'Without the fixture parameter, monkeypatch methods cannot be used, causing errors.', 'correct_approach': "Always include 'monkeypatch' as a parameter in the test function to access the fixture."}
Setting environment variables globally instead of using monkeypatch
Not asserting the expected value after monkeypatching
Bonus Challenge

Now add data-driven testing with 3 different environment variable values

Show Hint