If you need even more control—say, you want to log the traceback separately while still failing the test—you can manually capture it using Python’s traceback module. This is useful when debugging or integrating with logging systems.
import pytest
import traceback
def whatever():
return 9 / 0
def test_whatever():
try:
whatever()
except ZeroDivisionError as exc:
print(traceback.format_exc()) # Prints full traceback
pytest.fail(f"Exception raised: {exc}", pytrace=True)
Here, traceback.format_exc() prints the traceback exactly as it appears in an unhandled exception, which can be useful for debugging while still failing the test with pytest.fail.