0
0
PyTesttesting~8 mins

capsys for stdout/stderr in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - capsys for stdout/stderr
Folder Structure
project-root/
├── tests/
│   ├── test_example.py
│   ├── test_utils.py
│   └── conftest.py
├── src/
│   └── app_code.py
├── pytest.ini
└── requirements.txt
    

This structure keeps test files inside tests/ and application code inside src/. The conftest.py file holds shared fixtures and setup.

Test Framework Layers
  • Test Cases: Individual test functions in tests/ using capsys to capture output.
  • Fixtures: Shared setup in conftest.py, can provide reusable capsys usage if needed.
  • Application Code: Code under test in src/.
  • Utilities: Helper functions or classes to support tests.
  • Configuration: pytest.ini for pytest settings.
Configuration Patterns

Use pytest.ini to configure pytest options like verbosity or markers.

Example pytest.ini:

[pytest]
addopts = -v
markers =
    slow: marks tests as slow
    smoke: marks smoke tests
    

Environment variables can be used to control test behavior if needed.

Test Reporting and CI/CD Integration

pytest outputs test results to the console by default, showing which tests passed or failed.

Use plugins like pytest-html to generate HTML reports for better visualization.

Integrate pytest runs into CI/CD pipelines (GitHub Actions, Jenkins, GitLab CI) by running pytest commands and collecting reports.

Best Practices
  • Use capsys fixture to capture and assert output from stdout and stderr without modifying application code.
  • Keep tests isolated; do not rely on output order or side effects outside the test scope.
  • Use clear and descriptive assertion messages when checking captured output.
  • Use capsys.readouterr() only once per test to avoid missing output.
  • Combine capsys with parameterized tests to check multiple output scenarios efficiently.
Self Check

Where in this framework structure would you add a new test that verifies the output printed by a function?

Key Result
Use pytest's capsys fixture in test functions to capture and assert stdout and stderr output cleanly.