4

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.

Mihai
  • 189
  • 2
  • 10

1 Answers1

8

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

Akshay Pratap Singh
  • 3,197
  • 1
  • 24
  • 33