Test Overview
This test uses monkeypatch.setenv to temporarily change an environment variable. It verifies that the code reads the updated environment variable correctly during the test.
This test uses monkeypatch.setenv to temporarily change an environment variable. It verifies that the code reads the updated environment variable correctly during the test.
import os import pytest def get_api_key(): return os.getenv('API_KEY', 'default_key') def test_get_api_key_with_monkeypatch(monkeypatch): monkeypatch.setenv('API_KEY', 'test_key_123') result = get_api_key() assert result == 'test_key_123'
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and pytest initializes the test environment | No environment variable 'API_KEY' is set or it has a default value | - | PASS |
| 2 | monkeypatch.setenv sets 'API_KEY' environment variable to 'test_key_123' | Environment variable 'API_KEY' is temporarily set to 'test_key_123' for this test | - | PASS |
| 3 | Call get_api_key() which reads the 'API_KEY' environment variable | Function reads environment variable 'API_KEY' which is 'test_key_123' | Check if returned value equals 'test_key_123' | PASS |
| 4 | Assert that the returned API key is 'test_key_123' | Returned value is 'test_key_123' | assert result == 'test_key_123' | PASS |
| 5 | Test ends and pytest restores original environment variables | Environment variable 'API_KEY' is restored to original state | - | PASS |