Being quite new to exception test handling I am wondering how to check if an assertion is raised.
a.py
class SomeError(Exception):
pass
class SomeClass(object):
def __init__(self):
...
raise SomeError
...
test_a.py
from a.a import SomeClass
def test_some_exception_raised():
?
What assertion should it be there to check if SomeError
is raised? I am using pytest.
In order to write assertions about raised exceptions, you can use pytest.raises
as a context manager like this:
a.py
class SomeError(Exception):
pass
class SomeClass(object):
def __init__(self):
...
raise SomeError("some error message")
...
test_a.py
from .a import SomeClass, SomeError
import pytest
def test_some_exception_raised():
with pytest.raises(SomeError) as excinfo:
obj = SomeClass()
assert 'some error message' in str(excinfo.value)
For more about exception assertions, see here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With