Basic
pytest 기본 사용법
# test1.py
import pytest
def func(x):
return x + 1
def test_add():
assert func(4) == 4
$ pytest test1.py
Fixture
Fixture란 Testing 을 하기 위해 공통적으로 필요한 자원을 사전에 준비해놓는 방법
(1) square_10이란 함수를 Fixture로 준비. (테스트 간 매반 호출됨)
# 함수를 fixture로
@pytest.fixture
def square_10():
return 10 * 10
def test_square(square_10):
assert square_10 == 100 # 121
(2) square_10이란 함수를 Fixture로 미리 준비 및 활용
@pytest.fixture(params=[1, -1]) # params : 변수 여러개 테스트 해보는 것
def make_double_value(request):
return (request.param, request.param ** 2)
def test_double_value(make_double_value):
assert make_double_value == (1, 1)
(3) scope를 활용해 테스트 간 최초 한번만 실행
@pytest.fixture(scope='session')
def setting_db():
db = create_engine('DB_URL', encoding = 'utf-8')
return db
mark
pytest.mark는 테스트 함수에 metadata 설정을 도와주는 역할로 pytest.ini 파일을 통해서 marker를 등록함. buildin-marker 사용하거나, marker 직접 제작도 가능
- skip - 테스트 건너뜀 (skipif => 특정 조건 충족시 건너뜀)
- filterwarnings - 경고 필터링 달기
- parametrize : 매개변수화하여 여러번 호출
- xfail : 특정 조건 충족시 실패에 대한 예상 결과 생성
mark.parametrize (multiple.test 목적)
파라미터 인자를 직접 테스트 코드에 전달하는 방법 (다수 케이스에 대한 테스트 가능)
import pytest
# 리스트로 다수의 파라미터 인자를 전달하여 다수 케이스에 대한 테스트
@pytest.mark.parametrize("test_input, expected", [("3+5", 8), ("2+4", 6), ("6*7", 42)])
def test_eval(test_input, expected):
assert eval(test_input) == expected
추후 Develop 할 내용
How to monkeypatch/mock modules and environments — pytest documentation
How to monkeypatch/mock modules and environments Sometimes tests need to invoke functionality which depends on global settings or which invokes code which cannot be easily tested such as network access. The monkeypatch fixture helps you to safely set/delet
docs.pytest.org
How-to guides — pytest documentation
docs.pytest.org
'Python > Advanced' 카테고리의 다른 글
[Python 비동기] (1) 코루틴, 비동기 관련 용어 이해 (0) | 2023.02.08 |
---|---|
[Pytest] 4. Pytest with Django (Feat. pytest-Django) (0) | 2022.11.06 |
[Pytest] 2. Pytest 명령어 옵션 (command) (0) | 2022.11.05 |
[Pytest] 1. Pytest란? (+ 프레임워크 별 사용) (0) | 2022.11.04 |
[Python 심화] Python의 GIL과 느린 이유 (0) | 2022.08.24 |