우리는 왜 pytest를 사용해야하는가?
Intuitive Syntex : pytest offers readable, expressive way to write tests.
Powerful Fixtures : Easily set up and tear down test environments with fixtures
Rich Plugin Ecosystem : Extend pytest's capabilities with a wide range of plugins
사용법
설치 : pip install pytest
테스트 파일 명명 : *_test.py or test_*.py (*은 문구)
테스트 함수 명명 : test_* 라는 이름으로 명명 (*은 문구)
클래스 이름 명명 : Test* 라는 이름으로 명명 (*은 문구)
메소드 명명 : test_* 라는 이름으로 명명 (*은 문구)
Assertion : built-in assert statement를 사용
pytest Fixtures
Reusable Setup and Teardown : 함수 테스트 전 후에 정의함.
Scoping : Fixture의 사용방식을 설정한다.
Parameterization : 다른 Input data를 집어 넣어 체크 가능하다.
pytest 간단 예시
calcuate.py
def add(x, y):
return x + y
def subtract(x, y):
return x - y
test_calcualtor_fixture.py
assert 명령문을 통해 값이 올바른 지 확인할 수 있고, fixture를 통해 해당 함수 작동 전에 환경을 셋팅할 수 있다.
import pytest
from calculate import add, subtract
@pytest.fixture
def calculator_setup():
print("Setting up environment for calculator")
return {}
def test_add(calculator_setup):
assert add(3,4) == 7
def test_subtract(calculator_setup):
assert subtract(4, 3) == 1
테스트 결과

calculator_setup이 각 함수 이전에 먼저 작동 되고 해당 작동 이후에 결과가 맞는 지 안맞는 지 도출되는 것을 알 수 있다.
'인공지능 > Python' 카테고리의 다른 글
Python 프로그래밍 시 필요한 개념 (4) | 2024.10.09 |
---|