0
0
PyTesttesting~8 mins

caplog for log messages in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - caplog for log messages
Folder Structure
project-root/
├── tests/
│   ├── test_example.py
│   ├── conftest.py
│   └── utils.py
├── src/
│   └── app_code.py
├── pytest.ini
└── requirements.txt
    

This is a simple Pytest project structure. Test files go under tests/. The conftest.py holds fixtures and shared setup. Application code is in src/.

Test Framework Layers
  • Test Layer: Test functions in tests/ using Pytest syntax.
  • Logging Capture Layer: Use Pytest's caplog fixture to capture log messages during tests.
  • Utilities Layer: Helper functions in tests/utils.py for common test tasks.
  • Fixtures Layer: Shared setup in conftest.py, including configuring loggers if needed.
  • Application Layer: Code under test in src/.
Configuration Patterns

Configure logging and test settings in pytest.ini or conftest.py. Example:

# pytest.ini
[pytest]
log_cli = true
log_cli_level = INFO
    

This enables live logging during tests. You can also configure loggers in conftest.py to set levels or formats.

Test Reporting and CI/CD Integration

Pytest outputs test results with pass/fail status. When using caplog, you can assert on log messages to verify behavior.

Integrate with CI/CD pipelines by running pytest commands. Use plugins like pytest-html for HTML reports or pytest-junitxml for XML reports.

Example CI command:

pytest --junitxml=reports/results.xml
    
Best Practices
  • Use caplog fixture to capture logs instead of manual logger patching.
  • Assert on specific log messages and levels to verify expected logging behavior.
  • Keep log messages clear and consistent in the application code for easier testing.
  • Configure logging levels in pytest.ini to control verbosity during tests.
  • Use fixtures in conftest.py to set up logger configurations shared across tests.
Self Check

Where would you add a new test that verifies a warning log message is generated when invalid input is given?

Key Result
Use Pytest's caplog fixture to capture and assert log messages during tests for clear verification of logging behavior.