There are two ways to handle such cases in pytest:
Using pytest.raises :
def whatever(): return 9/0 def test_whatever(): with pytest.raises(ZeroDivisionError): whatever()
Using pytest.mark.xfail :
@pytest.mark.xfail(raises=ZeroDivisionError) def test_whatever(): whatever()
The output of pytest.raises :
============================= test session starts ============================ platform linux2 -- Python 2.7.10, pytest-3.2.3, py-1.4.34, pluggy-0.4.0 -- /usr/local/python_2.7_10/bin/python cachedir: .cache rootdir: /home/user, inifile: collected 1 item test_fun.py::test_whatever PASSED ======================== 1 passed in 0.01 seconds =============================
pytest.xfail marker pytest.xfail :
============================= test session starts ============================ platform linux2 -- Python 2.7.10, pytest-3.2.3, py-1.4.34, pluggy-0.4.0 -- /usr/local/python_2.7_10/bin/python cachedir: .cache rootdir: /home/user, inifile: collected 1 item test_fun.py::test_whatever xfail ======================== 1 xfailed in 0.03 seconds=============================
As the documentation says:
Using pytest.raises is likely to be better when you test the exceptions that your own code intentionally raises, while using @pytest.mark.xfail with a validation function is probably better for something like documenting unfixed errors ( where the test describes what “should” happen) or errors in dependencies.
veri_pudcha_coder Nov 15 '17 at 13:20 2017-11-15 13:20
source share