Post

테스트 실습3[Elice]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import pytest

def apply_coupon(price, coupon_rate):

    # 0에서 100까지만 입력해야함
    if not (0 <= coupon_rate <= 100):
        raise ValueError("할인율은 0~100% 사이여야 합니다.")

    # 문자는 입력할 수 없음
    if not isinstance(price,(int,float)):
        raise TypeError("가격은 숫자여야 한다.")

    # 가격은 0 이상이여야 함
    if price < 0:
        raise ValueError("올바른 가격을 입력해 주세요")

    # 할인율은 숫자여야함
    if not isinstance(coupon_rate,(int,float)):
        raise TypeError("할인율은 숫자여야 한다")

    # 할인 적용된 금액 표시
    return price * (1 - coupon_rate/100)

# 'raise' 직접 예외를 발생시키는 키워드
# 'pytest.raises()' with 문을 사용해 특정 코드가 예외를 발생 시키는지 검사함
#  ㄴ 예외처리 한게 정상으로 되는지 확인하는 용도
# 'isinstance()' 변수의 데이터 타입을 확인하는 함수
#  ㄴ print(isinstance(10,int)) 10은 정수형인가? =>  True
#  ㄴ print(isinstance(10,(int,float))) 10은 정수이며 실수 이다 => True

# 테스트 코드
def test_apply_valid_coupon():
    assert apply_coupon(10000,0) == 10000 # 할인율 0% 일 때, 할인 금액 비교
    assert apply_coupon(10000,50) == 5000 # 할인율 50% 일 때, 할인 금액 비교
    assert apply_coupon(10000,100) == 0 # 할인율 100% 일 때, 할인 금액 비교

def test_not_apply_coupon():
    with pytest.raises(ValueError): # 오류로서 예외처리
        apply_coupon(10000,120) # 할인율 100을 초과할 경우
    with pytest.raises(ValueError): # 할인율과 가격이 음수일 경우는 값이 에러이기에
        apply_coupon(-10000, 10)
        apply_coupon(10000,-10)
        apply_coupon(-10000,-10)
        apply_coupon(0,10)
        apply_coupon(0,-10)
    with pytest.raises(TypeError): # 각 값들에 문자가 들어갈 경우 타입이 잘못 되었기에
        apply_coupon("10000",10)
        apply_coupon(10000,"10")

테스트 결과

1
2
3
4
5
6
7
8
pytest test_07.py
Pytest
plugins: Faker-37.0.0
collected 2 items

test_07.py ..                                                 [100%]

======================== 2 passed in 0.31s =========================
This post is licensed under CC BY 4.0 by the author.