0
0
PyTesttesting~8 mins

Asserting exceptions (pytest.raises) - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Asserting exceptions (pytest.raises)
Folder Structure
test_project/
├── tests/
│   ├── test_example.py       # Test files using pytest
│   └── test_exceptions.py    # Tests specifically for exception handling
├── src/
│   └── example_module.py     # Application code
├── conftest.py               # Shared fixtures and hooks
├── pytest.ini                # Pytest configuration file
└── requirements.txt          # Dependencies
Test Framework Layers
  • Application Code (src/): Contains the main Python code to be tested.
  • Tests (tests/): Contains test scripts. Tests for exceptions use pytest.raises to check errors.
  • Fixtures and Hooks (conftest.py): Setup reusable test data or environment before tests run.
  • Configuration (pytest.ini): Controls pytest behavior like markers, test paths, and warnings.
  • Utilities (optional): Helper functions or classes to support tests.
Configuration Patterns
  • pytest.ini: Define test markers and addini options for environment or browser if needed.
  • Environment Variables: Use os.environ or pytest fixtures to pass credentials or config securely.
  • Command Line Options: Add custom options in conftest.py to select test environments or toggle debug mode.
  • Exception Testing: No special config needed; pytest.raises is used directly in test code.
Test Reporting and CI/CD Integration
  • Pytest Output: Shows passed/failed tests with clear messages when exceptions are expected or not.
  • Verbose Mode: Use pytest -v for detailed test names and results.
  • JUnit XML Reports: Generate XML reports with pytest --junitxml=report.xml for CI tools.
  • CI/CD Integration: Run tests in pipelines (GitHub Actions, Jenkins) and fail builds if exception tests fail.
  • Test Logs: Capture logs or error messages for debugging failed exception tests.
Best Practices
  • Use pytest.raises as a context manager: It clearly shows which code should raise the exception.
  • Check exception type and message: Assert the exact exception and optionally check the error message for clarity.
  • Keep tests simple and focused: Test one exception scenario per test function for easy debugging.
  • Use fixtures for setup: Prepare test data or environment to isolate exception tests from unrelated failures.
  • Write negative tests: Confirm that invalid inputs or actions raise the expected exceptions to improve code robustness.
Self Check

Where in this folder structure would you add a new test file to verify that a function raises a ValueError when given bad input?

Key Result
Organize pytest tests in a clear folder structure using pytest.raises to assert exceptions with focused, readable tests.