Programming/Python
Python pytest 살펴보기, 예제 코드
쿠마쿠마34
2023. 1. 3. 16:41
반응형
안녕하세요, 오늘은 Python에서 제공하는 test library 모듈인 pytest에 대해 알아보려고 합니다.
이 글은 공식 문서인 , 아래 링크를 참조하여 정리한 글 입니다.
📍Pytest 설치하기
pip install -U pytest
//pytest 버전 확인
pytest 7.2.0
📍Sample test Code 작성해보기
test_sample.py
def func(x):
return x + 1
def test_answer():
assert func(3) == 5
- assert로 검증하고자 하는 함수와 결과 값이 일치하는지 확인한다.
📍여러개의 test 실행하기
- pytest는 실행한 디렉토리와 그 디렉토리 하위의 파일들 중 test_*.py , *_test.py 형식의 파일을 모두 실행한다.
📍Exception과 관련된 Assert
- 에러가 발생하는 것이 정상인 테스트 케이스들에 대해 테스트
✔️Raises 사용 방법
pytest.raises를 사용하게 되면 catch하고자 하는 Exception이 발생하는지를 확인한다.
import pytest
def raise_exception():
raise Exception("Error!")
def test_use_pytest_raise():
with pytest.raises(Exception):
raise_exception()
→ with문 안에서 Exception이 호출되었는지를 확인한다.
with 문 안에서 확인하고자 하는 에러가 나오지 않으면 Test_fail이 나온다
import pytest
def return_no_exception():
return 1
def test_use_pytest_raises_error():
with pytest.raises(Exception):
return_no_exception()
Raises를 사용하지 않은 상태에서 error가 발생하면 테스트가 돌지 않고 에러가 발생하여 종료된다.
def raise_exception():
raise Exception("Error!")
def test_without_raise():
raise_exception()
✔️Error Type에 대한 test
Exception Type을 더 정확하게 기입해서 상세한 테스트가 가능하다
def test_check_exception_type():
# Assertion Error가 나야 함
with pytest.raises(ZeroDivisionError):
raise_assertion_error()
def test_check_exception_type():
# Assertion Error가 나야 함
with pytest.raises(ZeroDivisionError):
raise_assertion_error()
→ ZeroDivisionError를 잡아야 하는데 AssertionError가 나오면 test가 fail된다.
✔️Error Message에 대한 Test
- Error에서 던져진 메시지에 대한 검증을 통해 예상치 못한 에러인지, 정상적인 에러인지 판단할 수 있다.
def test_err_message():
with pytest.raises(Exception) as error_info:
raise_exception()
assert str(error_info.value) == "Error!"
assert error_info.value.args[0] == "Error!"
print("Assert문 통과!")
📍여러 Test를 Class에서 테스트하기
- Prefix “Test_”로 시작하는 class에서만 적용이 된다.
- Class 안에 있는 test함수들에 대해 실행이 된다.
# content of test_class.py
class TestClass:
def test_one(self):
x = "this"
assert "A" in x
def test_two(self):
x = "hello"
assert hasattr(x, "check")
오늘 정리한 모든 코드는 아래 깃허브에 올려두었습니다 :)
https://github.com/kumakuma34/pytest_study
반응형