Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if expection is raised with pytest [duplicate]

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.

like image 366
Mihai Avatar asked Feb 05 '23 19:02

Mihai


1 Answers

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

like image 84
Akshay Pratap Singh Avatar answered Feb 07 '23 07:02

Akshay Pratap Singh