개발/Python

[Python] 파이썬 pytest를 활용해서 테스트 해보자

growing-dev 2023. 2. 28. 22:08
반응형

파이썬에서 유닛테스트를 구현하기 위해 pytest를 이해하고 활용해서 테스트를 구현해 본다.

 

파이썬 pytest를 활용해서 테스트해 보자

지난번 파이썬 테스트를 위해서 내장된 unittest 모듈을 활용해 보았다. 이번에는 pytest를 활용해서 파이썬을 테스트해 보도록 하겠다. 이번에는 Pycharm 보다 VS Code이 편해서 VS Code를 사용해서 진행해 본다. 

 

https://docs.pytest.org/en/stable/

 

pytest: helps you write better programs — pytest documentation

pytest: helps you write better programs The pytest framework makes it easy to write small, readable tests, and can scale to support complex functional testing for applications and libraries. pytest requires: Python 3.7+ or PyPy3. PyPI package name: pytest

docs.pytest.org

 

 

 

VS Code에서 pytest 설정하기

우선 VS Code에서 Ctrl+Shift+P 를 통해 Python Configure을 검색하여 Congigure Tests를 선택한다.

파이썬 테스트 구성

 

그러면 아래와 같이 2가지 unittest와 pytest가 뜨는데, 우리는 pytest를 해볼 것이니 pytest를 선택하면 된다.

pytest 선택하기

 

이후 테스트를 포함할 디렉터리를 선택한다. 나는 디렉터리도 따로 없고 간단히 테스트만 해볼 것이라서 Root directory를 선택했다. 실제 프로젝트의 디렉터리가 복잡하거나 테스트가 모인 디렉토리가 있다면 그곳을 지정해 주면 편할 것이다. 물론 추후에 수정도 가능하다.

디렉토리 선택

 

 

이렇게 모두 설정이 완료되면 setting.json 파일에 아래와 같이 설정되는 것을 확인할 수 있다. 대충 보아도 *_test.py라는 파일을 테스트할 것이고, pytest는 enable, unittest는 disable 했다고 확인할 수 있다. 손쉽게 pytest를 해볼 수 있도록 설정 방법을 제공하는 정도라고 이해하면 된다.

    "python.testing.unittestArgs": [
        "-v",
        "-s",
        ".",
        "-p",
        "*_test.py"
    ],
    "python.testing.pytestEnabled": true,
    "python.testing.unittestEnabled": false,
    "python.testing.pytestArgs": [
        "."
    ]

 

 

VS Code에서 pytest 만들어 보기

우선 나는 기존에 unittest 때에도 사용했던 factorial.py를 활용할 것이고 이를 테스트하는 test_factorial.py 파일을 만들었다.

 

파일 구조

factorial.py는 다음과 같다.

def factorial(n):
    if n < 0:
        n = -n
    val = 1

    while n > 0:
        val *= n
        n -= 1

    return val

 

test_factorial.py는 공식 문서를 참고해서 만들었고 우선 일부러 fail이 되도록 만들어보았다.

 

test_factorial.py

from factorial import *

def test_factorial_zero():
    assert factorial(0) == 0

 

실행하려면 지정했던 디렉터리에서 pytest를 입력하기만 하면 된다. 아래와 같이 factorial_test.py 가 발견되고 실행되었으며 실패했다는 것을 확인할 수 있다.

 

실행 결과

 

코드를 아래와 같이 정상적으로 수정하였다. factorial(0)의 결과는 1이 되는 것이 현재 구현사항이므로 이렇게 수정하면 아래와 같이 pass 되는 것을 확인할 수 있다. 직관적으로 빨간색으로 실패를, 초록색으로 성공을 표시해 주어서 쉽게 확인할 수 있다.

from factorial import *

def test_factorial_zero():
    assert factorial(0) == 1

성공

 

 

아래와 같이 2가지 테스트 케이스를 좀 더 추가해 보았다. VS Code에서 제공하는 테스트 탐색기를 활용하면 쉽게 실행하거나 디버깅해 볼 수 있다.

from factorial import *
import math

def test_factorial_zero():
    assert factorial(0) == 1

def test_factorial_10():
    assert factorial(10) == math.factorial(10)

def test_factorial_1000():
    assert factorial(1000) == math.factorial(1000)

테스트 탐색기

 

 

결론

pytest를 공부해보다 보니 상대적으로 unittest에 비해서 test fixture와 assert 활용법 같은 추가적인 기능이 많은 것 같다. 일단 기본 사용법을 익혔으니 조금 더 실제와 비슷한 예제를 바탕으로 pytest를 잘 활용하는 방법을 공부해 나가 볼 생각이다.

반응형