0
0
PyTesttesting~8 mins

monkeypatch.setenv in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - monkeypatch.setenv
Folder Structure for pytest Framework
tests/
├── test_example.py       # Test files
├── conftest.py           # Shared fixtures and hooks
utils/
├── helpers.py            # Utility functions
configs/
├── config.yaml           # Environment and test configs
reports/
├── latest_report.html    # Test reports
Test Framework Layers
  • Test Layer: Contains test functions using pytest syntax, e.g., test_example.py.
  • Fixture Layer: conftest.py holds fixtures like monkeypatch for environment setup.
  • Utility Layer: Helper functions to support tests, e.g., reading configs or common actions.
  • Configuration Layer: YAML or JSON files to manage environment variables, URLs, credentials.
Configuration Patterns

Use monkeypatch.setenv in fixtures to temporarily set environment variables during tests.

Example fixture in conftest.py:

import pytest

@pytest.fixture
def set_test_env(monkeypatch):
    monkeypatch.setenv("API_KEY", "testkey123")
    monkeypatch.setenv("ENV", "test")
    yield
    # Environment variables reset automatically after test

Use config files (e.g., config.yaml) to store environment-specific values and load them in tests or fixtures.

Test Reporting and CI/CD Integration
  • Use pytest built-in options like --junitxml=reports/report.xml for XML reports.
  • Generate HTML reports with plugins like pytest-html to create reports/latest_report.html.
  • Integrate tests in CI/CD pipelines (GitHub Actions, Jenkins) to run tests and publish reports automatically.
  • Use environment variables set by CI tools or override them with monkeypatch.setenv during local tests.
Best Practices for Using monkeypatch.setenv in pytest Framework
  1. Isolate Environment Changes: Use monkeypatch.setenv in fixtures to avoid side effects on other tests.
  2. Keep Tests Independent: Each test should set its own environment variables to prevent hidden dependencies.
  3. Use conftest.py for Shared Fixtures: Centralize environment setup for reuse and clarity.
  4. Clean Up Automatically: monkeypatch resets environment after test, so no manual cleanup needed.
  5. Combine with Config Files: Load environment values from config files and apply them with monkeypatch for flexibility.
Self Check

Where in this pytest framework structure would you add a new fixture that sets an environment variable DATABASE_URL for tests?

Key Result
Use monkeypatch.setenv in pytest fixtures within conftest.py to safely manage environment variables during tests.