Programming/Pytest

Assertion

c29130811 2024. 7. 13. 14:32

https://docs.pytest.org/en/stable/how-to/assert.html

 

pytest 를 사용하면 표준 Python assert에 따라 값을 검증 할 수 있다고 한다.

# content of test_assert1.py
def f():
    return 3


def test_function():
    assert f() == 4

 

기본적인 assert 문은 조건이 참인지 확인하는데, 조건이 거짓이면 실패 메시지를 생성하고 테스트를 실패로 처리함.

또한 아래 처럼 , 를 통해 사용자 메시지를 지정할 수도 있음

def test_custom_message():
    assert 1 + 1 == 3, "Expected 3"  # 실패 시 사용자 메세지 출력

 

리스트에 2가 있는지 확인

def test_collection():
    my_list = [1, 2, 3]
    assert 2 in my_list

 

with Context Manager를 활용한 에러 발생 

def test_raises_type_error():
    with pytest.raises(TypeError):
        1 + "2"  # TypeError가 발생해야 테스트 통과

 

 

with 에 대한 구문이 좀 어려웠는데, 리소스를 알아서 할당하고 제공한다고하니, 알아서 동작하겠지 하니 맘이 편해짐...

 

728x90

'Programming > Pytest' 카테고리의 다른 글

pytest pytest.ini, conftest.py  (0) 2024.10.27
Requests API 테스트  (0) 2024.08.15
@pytest.fixture  (1) 2024.07.14
Pytest  (1) 2024.07.12