Code:
# coding=utf-8
import pytest
def whatever():
return 9/0
def test_whatever():
try:
whatever()
except ZeroDivisionError as exc:
pytest.fail(exc, pytrace=True)
Output:
================================ test session starts =================================
platform linux2 -- Python 2.7.3 -- py-1.4.20 -- pytest-2.5.2
plugins: django, cov
collected 1 items
pytest_test.py F
====================================== FAILURES ======================================
___________________________________ test_whatever ____________________________________
def test_whatever():
try:
whatever()
except ZeroDivisionError as exc:
> pytest.fail(exc, pytrace=True)
E Failed: integer division or modulo by zero
pytest_test.py:12: Failed
============================== 1 failed in 1.16 seconds ==============================
How to make pytest print traceback, so I would see where in the whatever
function an exception was raised?
you can try
Have you tried to remove "pytrace=True" ?
Have you tried to run with '--fulltrace' ?
This solution is what we are using:
Please refer to pytest, https://docs.pytest.org/en/latest/reference.html#pytest-raises
pytest.raises(Exception)
is what you need.Code
Output
Note that
e_info
saves the exception object so you can extract details from it. For example, if you want to check the exception call stack or another nested exception inside.Right way is using
pytest.raises
but I found interesting alternative way in comments here and want to save it for future readers of this question:pytest constantly evolves and with one of the nice changes in the recent past it is now possible to simultaneously test for
Two examples from the documentation:
I have been using that approach in a number of projects and like it very much.