[Python]pytest(3) 부가 기능들(parametrize, xfail, param, id)

변도진·2024년 6월 4일
0

Python

목록 보기
5/13
post-thumbnail

parametrize()

test에 필요한 매개변수를 배열에 있는 요소 대로 대입하여 반복한다.

예시

코드

import pytest

def f(a): return a + 1

@pytest.mark.parametrize(
    "a, result", # 파라미터를 입력한다.
    [(2, 3), # case를 입력한다.
     (3, 4),
     (4, 5)]
)
def test_f(a, result):
    assert f(a) == result

결과

========================= test session starts ========================== 
platform win32 -- Python 3.12.2, pytest-8.2.1, pluggy-1.5.0
rootdir: C:\workspace\pytest-study
collected 3 items                                                        

test.py ...                                                       [100%] 

========================== 3 passed in 0.01s =========================== 

xfail()

실패가 예상되는 함수에 지정한다.

예시

코드

import pytest

def f(a): return a + 1

@pytest.mark.xfail(reason="wrong result") # 실패 예상 이유 작성
@pytest.mark.parametrize(
    "a, result",
    [(2, 4),
     (3, 5),
     (4, 6)]
)
def test_f(a, result):
    assert f(a) == result

결과

========================= test session starts ==========================
platform win32 -- Python 3.12.2, pytest-8.2.1, pluggy-1.5.0
rootdir: C:\workspace\pytest-study
collected 3 items

test.py xxx                                                       [100%]

========================== 3 xfailed in 0.03s ========================== 

param()

case에 mark를 적용 할 수 있다.

예시

코드

import pytest

def f(a): return a + 1

@pytest.mark.parametrize(
    "a, result",
    [(1, 2),
     pytest.param(1, 3, marks=pytest.mark.xfail)]
)
def test_f(a, result):
    assert f(a) == result

결과

========================= test session starts ==========================
platform win32 -- Python 3.12.2, pytest-8.2.1, pluggy-1.5.0
rootdir: C:\workspace\pytest-study
collected 2 items

test.py .x                                                        [100%]

===================== 1 passed, 1 xfailed in 0.03s =====================

id()

case의 의미를 작성 할 수 있다.

예시

코드

import pytest

def f(a): return a + 1

@pytest.mark.parametrize(
    "a, result",
    [pytest.param(1, 2, id="success case"),
     pytest.param(1, 3, marks=pytest.mark.xfail, id="fail case")]
)
def test_f(a, result):
    assert f(a) == result

결과

========================= test session starts ==========================
platform win32 -- Python 3.12.2, pytest-8.2.1, pluggy-1.5.0
rootdir: C:\workspace\pytest-study
collected 2 items

test.py .x                                                        [100%]

===================== 1 passed, 1 xfailed in 0.05s ===================== 

정리

pytest의 편리한 부가 기능들을 알아보았다.
test를 위해 만들어져서 반복적인 코드와 코드 별 명시가 중요하니
잘 사용하여 좋은 test 코드를 만들자

참조

https://sangjuncha-dev.github.io/posts/programming/python/2022-02-08-python-pytest-guide/

profile
낚시하고 싶다.

0개의 댓글