카테고리 없음

@pytest.mark

c29130811 2024. 7. 28. 14:37

Skip

테스트를 말 그대로 skip 할 경우 사용

import pytest

@pytest.fixture(scope="function")
def scope_fixture():
    return {"scope": "function"}

def test_scope(scope_fixture):
    assert scope_fixture["scope"] == "function"

def test_function_scope_2(scope_fixture):
    assert scope_fixture["scope"] == "function"

@pytest.mark.skip(reason="Skip Testing")
def test_skip():
    assert 1 == 1

 

다음

===================================================================================== test session starts ======================================================================================
platform darwin -- Python 3.12.4, pytest-8.2.2, pluggy-1.5.0
rootdir: /Users/june/Documents/Study/pytest
collected 3 items                                                                                                                                                                              

test_1.py ..s                                                                                                                                                                            [100%]

================================================================================= 2 passed, 1 skipped in 0.00s =================================================================================
(testing) june@juneui-MacBookPro pytest %

 

이렇게 1개가 skipped 되는데, 사실 이게 많이 쓰일지는 잘 모르겠다.

비슷하게 skipif에 첫번째 파라미터로 True 조건에 따라 일때만 건너뛰기도 가능.

import pytest

@pytest.mark.skipif(condition=True, reason="Condition이 True일때 Skip.")
def test_skipif():
    assert 1 == 1

 

parametrize

파라미터에 iterater 한 객체를 반복적으로 테스트하는 방법을 제공한다. 이때 @에 파라미터 명들은 함수에서 사용하는 것과 동일하지 않으면 에러가 난다.

1 넣어서 2랑 같은지 확인, 2를 넣으면 4랑 같은지 확인..

@pytest.mark.parametrize("input,expected", [(1, 2), (2, 4), (3, 6)])
def test_parametrize(input, expected):
    assert input * 2 == expected
input: 1
expected: 2
input: 2
expected: 4
input: 3
expected: 6

============================================================== 5 passed, 1 skipped in 0.00s ===============================================================

 

custom market

pytest.ini 파일에 markers로 생성할 custom들을 정의 

[pytest]
markers =
    plus: 덧셈
    minus: 뺄셈
    multi: 곱셈

 

그리고 test 코드에서 

import pytest

# 덧셈 테스트
@pytest.mark.plus
@pytest.mark.parametrize("p1, p2, expected", [(1, 2, 3), (3, 5, 8), (10, 20, 30)])
def test_plus(p1, p2, expected):
    assert p1 + p2 == expected

# 뺄셈 테스트
@pytest.mark.minus
@pytest.mark.parametrize("p1, p2, expected", [(5, 2, 3), (10, 5, 5), (20, 10, 10)])
def test_minus(p1, p2, expected):
    assert p1 - p2 == expected

# 곱셈 테스트
@pytest.mark.multi
@pytest.mark.parametrize("p1, p2, expected", [(1, 2, 2), (3, 5, 15), (10, 20, 200)])
def test_multi(p1, p2, expected):
    assert p1 * p2 == expected

를 작성한다.

 

그리고 custom marker 별로 테스트 하려면 -m 옵션을 준다.

// 덧셈 테스트 실행
pytest -m plus

// 뺄셈 테스트 실행
pytest -m minus

// 곱셈 테스트 실행
pytest -m multi

 

728x90