Backend/pytest

[pytest] 파이썬 테스팅을 위한 pytest 사용법

sangwonYoon 2023. 6. 9. 23:54

pytest 설치 방법

pip install pytest

 

pytest 실행 방법

1. 현재 디렉토리에서 테스트 

pytest

현재 디렉토리 내에 존재하는 test_*.py 또는 *_test.py 형식의 파일들을 모두 테스트한다.

 

2. 특정 파일만 테스트

# pytest <파일 이름>
pytest test_file.py

 

3. 특정 경로에서 테스트

# pytest <디렉토리 경로>
pytest testing/

이 때, 테스트해야 하는 파일의 이름은 test_*.py 또는 *_test.py 형식이어야 한다.

 

4. 특정 키워드를 갖는 요소만 테스트

# pytest -k <keyword expressions>
pytest -k 'MyClass and not method'

keyword expression에 부합하는 이름을 갖는 파일, 클래스, 함수를 테스트한다.

위 명령어를 입력할 경우, TestMyClass 클래스의 test_something이라는 메소드는 테스트가 진행되지만, TestMyClass의 test_method_simple은 테스트하지 않는다.

 

5. 테스트할 요소를 계층적으로 선택

# test_file.py 파일 내에 있는 test_func 함수 테스트
pytest test_file.py::test_func

# test_file.py 파일 내에 있는 TestClass 클래스의 test_method 메소드 테스트
pytest test_file.py::TestClass::test_method

:: 문자로 계층 요소를 구분한다.

 

테스트 탐색 규칙

pytest가 테스트할 요소를 탐색하는 방식은 아래와 같다.

  • 디렉토리를 발견하면 내부로 들어가 탐색한다.
  • 파일을 발견하면 해당 파일이 test_*.py 또는 *_test.py 형식인지 확인한다.
  • 위 조건을 만족하는 파일에서 아래 조건을 만족하는 테스트 요소를 수집한다
    • 클래스 밖에 존재하고 이름이 test로 시작하는 테스트 함수
    • 이름이 Test로 시작하는 테스트 클래스 내부에 존재하고 이름이 test로 시작하는 테스트 함수

 

테스트에서 제외할 경로 지정

--ignore 옵션을 사용해 테스트에서 제외할 경로를 지정할 수 있다.

tests/
|-- example
|   |-- test_example_01.py
|   |-- test_example_02.py
|   '-- test_example_03.py
|-- foobar
|   |-- test_foobar_01.py
|   |-- test_foobar_02.py
|   '-- test_foobar_03.py
'-- hello
    '-- world
        |-- test_world_01.py
        |-- test_world_02.py
        '-- test_world_03.py

위와 같은 디렉토리 구조에서 예시를 들어보면,

pytest --ignore=tests/foobar/test_foobar_03.py --ignore=tests/hello/

위 명령어를 CLI에서 실행할 경우, 테스트 결과는 아래와 같다.

=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
rootdir: $REGENDOC_TMPDIR, inifile:
collected 5 items

tests/example/test_example_01.py .                                   [ 20%]
tests/example/test_example_02.py .                                   [ 40%]
tests/example/test_example_03.py .                                   [ 60%]
tests/foobar/test_foobar_01.py .                                     [ 80%]
tests/foobar/test_foobar_02.py .                                     [100%]

========================= 5 passed in 0.02 seconds =========================

 

_01.py로 끝나는 파일을 테스트에서 제외하고 싶다면, --ignore-glob 옵션을 사용할 수 있다.

pytest --ignore-glob='*_01.py' # 해당 옵션의 값은 따옴표로 감싸줘야 한다!

 

테스트 실행 시간 출력

pytest --durations=10 --durations-min=1.0

1초 이상 걸리는 테스트 중 가장 느린 10개의 테스트를 출력하기 위해서는 위와 같이 입력한다.

-vv 옵션을 주지 않으면 0.005초 이내에 실행되는 테스트는 출력하지 않는다.