python/응용

pytest - basic

wefree 2022. 5. 23. 14:41

cal.py

class Cal(object):
    def add(self, x, y):
        if type(x) is not int or type(y) is not int:
            raise ValueError('Invalid Int')
        return x + y

 

test_cal.py

import pytest

import cal


# scope 영역마다 1 번씩만 수행됨
@pytest.fixture(scope="function")
def calculator():
    c = cal.Cal()
    print("Before")
    yield c
    print("After")


def test_cal(calculator):
    assert calculator.add(1, 2) == 3
    
    
@pytest.mark.parametrize(["x", "y", "result"], [
    (1, 2, 3),
    (4, 5, 9),
    (6, 7, 13)
])
def test_with_params(calculator, x, y, result):
    assert calculator.add(x, y) == result    
    

@pytest.mark.skip(reason='my skip')
def test_skip():
    pass

 

test_exception

def test_exception():
    c = Cal()
    with pytest.raises(ValueError) as e:
        c.add('a', 2)
        
    # 위에서 충분히 exception 여부는 테스트 되어 아래 부분은 필요에 따라 생락해 사용
    # exception 의 message 까지 이렇게 확인하는 것도 가능
    assert(str(e.value) == 'Invalid Int')

 

test_float_compare.py

import pytest


def test_good_float_compare():
    x = 0.1 + 0.2
    assert x == pytest.approx(0.3)