ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • pytest - basic
    python/응용 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)

    'python > 응용' 카테고리의 다른 글

    json 읽기 / 쓰기  (0) 2022.05.31
    pytest - fixture  (0) 2022.05.23
    Thread - queue & PoisonPill  (0) 2022.05.23
    logging  (0) 2022.05.22
    optparse  (0) 2022.05.22

    댓글

Designed by Tistory.