0
0
PyTesttesting~15 mins

monkeypatch.setenv in PyTest - Build an Automation Script

Choose your learning style9 modes available
Test function behavior with modified environment variable using monkeypatch.setenv
Preconditions (2)
Step 1: Use monkeypatch.setenv to set 'APP_MODE' to 'test'
Step 2: Call the function that reads 'APP_MODE'
Step 3: Verify the function returns 'test'
Step 4: Use monkeypatch.setenv to set 'APP_MODE' to 'production'
Step 5: Call the function again
Step 6: Verify the function returns 'production'
✅ Expected Result: The function returns the environment variable value as set by monkeypatch.setenv in each case
Automation Requirements - pytest
Assertions Needed:
Assert the function returns 'test' after monkeypatch.setenv('APP_MODE', 'test')
Assert the function returns 'production' after monkeypatch.setenv('APP_MODE', 'production')
Best Practices:
Use the pytest monkeypatch fixture parameter in the test function
Use monkeypatch.setenv to temporarily set environment variables
Keep tests isolated and independent
Use clear and descriptive assertion messages
Automated Solution
PyTest
import os
import pytest

def get_app_mode():
    return os.getenv('APP_MODE', 'default')


def test_get_app_mode(monkeypatch):
    # Set APP_MODE to 'test' and verify
    monkeypatch.setenv('APP_MODE', 'test')
    assert get_app_mode() == 'test', "Expected APP_MODE to be 'test'"

    # Set APP_MODE to 'production' and verify
    monkeypatch.setenv('APP_MODE', 'production')
    assert get_app_mode() == 'production', "Expected APP_MODE to be 'production'"

This test uses the monkeypatch fixture provided by pytest to temporarily set environment variables.

First, it sets APP_MODE to 'test' and calls get_app_mode(). The assertion checks that the function returns 'test'.

Then, it sets APP_MODE to 'production' and asserts the function returns 'production'.

Using monkeypatch.setenv ensures the environment variable changes only affect this test and are cleaned up automatically.

Common Mistakes - 3 Pitfalls
Not using the monkeypatch fixture and setting environment variables globally
Forgetting to import os and using os.getenv in the function
Not asserting the function output after setting environment variables
Bonus Challenge

Now add data-driven testing with 3 different APP_MODE values: 'test', 'production', and 'development'

Show Hint