pytest.raises(), 발생되는 예외 확인하기

최더디·2021년 12월 14일
0
post-thumbnail

📌 서론

pytest를 사용해 테스트를 하던 중 "에러가 발생되는 것이 정상인 메서드는 어떻게 테스트를 진행해야 할까?" 라는 궁금증이 생겼다. pytest에서는 pytest.raises()를 사용해 간단하게 에러가 발생하는지 테스트 할 수 있었다.

📌 테스트

📍에러 발생하는 함수 생성

def raise_exception():
	raise Exception("Error!")

📍pytest.raises() 사용

import pytest

def raise_exception():
    raise Exception("Error!")

def test_use_pytest_raises():
    # with문 안에서 Exception이 발생하는게 정상이라고 판단
    with pytest.raises(Exception):
        raise_exception()

pytest.raises() 의 with 문에서 에러가 발생하지 않는다면 어떻게 될까?

import pytest

def return_true():
    raise True

def test_use_pytest_raises():
    with pytest.raises(Exception):
        return_true()

위와 같이 에러가 발생되지 않는 코드를 작성하고 pytest를 실행하면 오류가 발생한다.
pytest.raises() 는 Exception 에러를 기대하고 있기 때문이다.

📍pytest.raises() 사용하지 않으면 어떻게 될까?

의도적으로 에러를 발생시키는 함수를 pytest.raises()를 사용하지 않고 테스트하면 어떻게 될까?

import pytest

def raise_exception():
    raise Exception("Error!!")

def test_not_use_pytest_raises():
    raise_exception()

당연한 얘기지만 에러가 발생한다. test_not_use_pytest_raises() 함수에서 raise_exception() 함수를 부르면 에러를 발생하기 때문이다.

📍여러 에러 메시지를 기대할 수 있음

Exception은 모든 에러를 처리하기 때문에, 조금 더 상세하게 에러를 확인해보자.

import pytest

def raise_assertion_error():
    assert 1==0

def test_use_pytest_raises():
    # AssertionError 를 기대함
    with pytest.raises(AssertionError):
        raise_assertion_error()

물론 Exception으로 에러를 체크한다 해도 테스트는 성공할 것이다. 하지만 내가 확인하고 싶은 에러가 AssertionError 라면 이와 같이 상세하게 적어주면 더 좋을 것 같다.

아래 코드는 ZeroDivisionError를 기대하는데, AssertionError가 발생했으니 당연히 오류가 발생한다.

import pytest

def raise_assertion_error():
    assert 1==0

def test_use_pytest_raises():
    with pytest.raises(ZeroDivisionError):
        raise_assertion_error()

ZeroDivisionError를 기대한다면 기대하는 에러를 발생시켜줘야 한다는 뜻이다.

import pytest

def test_use_pytest_raises():
    with pytest.raises(ZeroDivisionError):
        1/0

📍 에러 메시지 확인

test를 진행하다보면 예상치 못한 에러가 발생할 수 있다. 강제 발생시킨 에러인지 확인은 어떻게 할까?

나는 에러를 발생시킨 후, 내가 발생한 에러인지 확인하고 싶었다. 확인하는 방법은 내가 작성한 에러 메시지인지 확인하면 된다. 에러를 발생시킨 후, 에러 메시지 확인해 보는 방법은 아래와 같이 하면 된다.

import pytest

def raise_exception():
    raise Exception("Error Message: Test")

def test_use_pytest_raises():
    with pytest.raises(Exception) as error_info:
        raise_exception()
    print("공백")
    print(str(error_info.value))        # 방법1
    print(error_info.value.args[0])     # 방법2

assert를 사용해 내가 원한 에러 메시지인지 확인해보자.

import pytest

def raise_exception():
    raise Exception("Error Message: Test")

def test_use_pytest_raises():
    with pytest.raises(Exception) as error_info:
        raise_exception()
    assert str(error_info.value) == "Error Message: Test"
    assert error_info.value.args[0] == "Error Message: Test"
    print("Assert문 통과!")

내가 원한 에러 메시지가 아니라면 당연히 오류가 발생한다.

import pytest

def raise_exception():
    raise Exception("Error Message: Test")

def test_use_pytest_raises():
    with pytest.raises(Exception) as error_info:
        raise_exception()
    # 내가 발생시킨 에러 메시지가 아니면 오류 발생
    assert str(error_info.value) == "Not expect message"
    assert error_info.value.args[0] == "Error Message: Test"
    print("Assert문 통과!")

📌 참고

profile
focus on why

0개의 댓글