pytest-rich
pytest-rich is a pytest plugin that integrates the rich library to provide enhanced, colorful, and highly readable output for test sessions. It improves the default pytest terminal output with features like better traceback formatting, progress bars, and syntax highlighting. As of version 0.2.0, it is actively maintained with a relatively stable release cadence, primarily focusing on bug fixes and compatibility updates.
Common errors
-
ModuleNotFoundError: No module named 'rich' (or 'pytest_rich')
cause `rich` or `pytest-rich` is not installed in the Python environment currently being used by `pytest`.fixInstall both libraries: `pip install pytest-rich rich`. -
Error: unknown option: --rich
cause `pytest-rich` is not being loaded by `pytest`. This usually happens if `pytest` is running from a different virtual environment than where `pytest-rich` was installed, or the plugin isn't properly discovered.fixEnsure `pytest-rich` is installed in the active virtual environment. Try running `python -m pytest` instead of just `pytest` to ensure you're using the `pytest` executable associated with your current Python environment. -
Visual glitches or unformatted output when --rich is enabled
cause This can be caused by terminal emulator incompatibilities, conflicting `pytest` plugins, or an outdated `rich` library version.fixUpdate `rich` (`pip install --upgrade rich`), try a different terminal emulator, or temporarily disable other `pytest` plugins (`pytest -p no:xdist --rich`) to identify conflicts. Check the `pytest-rich` documentation for known terminal or plugin incompatibilities.
Warnings
- gotcha pytest-rich extensively modifies `sys.stdout` and `sys.stderr`. If other pytest plugins or custom test code also heavily manipulate terminal output, conflicts can occur, leading to malformed or incomplete rich output.
- gotcha While `pytest-rich` specifies a minimum `rich` version, using significantly older or very bleeding-edge `rich` versions not fully tested with `pytest-rich` might lead to unexpected rendering issues or visual glitches.
Install
-
pip install pytest-rich
Quickstart
import pytest
import os
# Create a dummy test file
with open("test_example.py", "w") as f:
f.write(
"""import pytest
def test_success():
assert True
def test_failure():
assert False
def test_error_division_by_zero():
1 / 0
@pytest.mark.skip(reason="demonstrate skip")
def test_skipped():
pass
def test_warning():
pytest.warn("This is a test warning.")
"""
)
# Create a pyproject.toml to enable rich output
with open("pyproject.toml", "w") as f:
f.write(
"""[tool.pytest.ini_options]
addopts = [
"--rich",
"--rich-tracebacks",
"--rich-help",
"--strict-markers",
]
"""
)
print("Created test_example.py and pyproject.toml")
print("To run, navigate to this directory in your terminal and execute: pytest")