Coming from this thread, it seems that is not possible with pytest to check if a specific exception is raised: if you mention the parent exception, the test passes as well.
I made this little example to illustrate, all three tests passed just fine. I expect only one to pass.
Could you confirm ? Should I check the excinfo ?
(Why is this a problem? The function I was testing can, in some cases, return a true
TypeError exception, and I’d like my tests to detect precisely when one or the other is raised)
import pytest class CustomExc(TypeError): pass def a_random_function(): raise CustomExc def test_random_function1(): with pytest.raises(TypeError): a_random_function() def test_random_function2(): with pytest.raises(CustomExc): a_random_function() def test_random_function3(): with pytest.raises(BaseException): a_random_function()
Source: Python Questions