pytest

pytest 8+

pytest CLI 빠른 참조 — 테스트 디스커버리, 선택, 픽스처, 마커, 병렬 처리, parametrize — 자주 쓰는 옵션과 실전 예시까지 함께 정리했습니다.

명령어 34개

도움말

pytest --version

pytest 버전과 발견한 import 라이브러리 경로를 출력합니다.

pytest --version
pytest --help

모든 pytest CLI 플래그를 한 줄 설명과 함께 표시합니다.

-h

pytest --help | less

디스커버리

pytest

현재 디렉터리와 하위 디렉터리에서 기본 디스커버리 규칙(`test_*.py` / `*_test.py`, `test_*` 함수, `Test*` 클래스)을 따라 모든 테스트를 실행합니다.

-x; --maxfail=1; --co; --collect-only; -q; -v; -k <expr>; -m <marker>; --no-header

pytest
pytest <path>

지정한 파일 또는 디렉터리 아래의 테스트만 실행합니다. 글로브가 지원됩니다.

<path>; tests/; tests/test_x.py; tests/test_x.py::test_y

pytest tests/unit
pytest tests/test_user.py::TestUser::test_create

전체 노드 경로 — 모듈 / 클래스 / 함수 — 로 단일 테스트를 실행합니다.

pytest tests/test_user.py::test_create_user

선택

pytest -k <expr>

이름이 부분 문자열 / Python 표현식과 일치하는 테스트를 실행합니다(`-k 'user and not slow'`).

-k 'pattern'; -k 'ClassName and method'

pytest -k 'create or update'
pytest -m <marker>

주어진 마커가 있는 테스트만 실행합니다(경고를 억제하려면 마커를 `pyproject.toml` 또는 pytest.ini에 등록해야 합니다).

-m slow; -m 'not slow'

pytest -m 'not integration'
pytest --co

수집 전용 모드 — pytest이 실행할 테스트를 실행하지 않고 나열합니다. CI 미리보기에 좋습니다.

--collect-only; -q

pytest --co -q

중단 / 리포트

pytest -x

첫 번째 실패에서 중단합니다. 사용자 정의 임계값은 `--maxfail=N`을 사용하세요.

--maxfail=1; --maxfail=3; --exitfirst; -x

pytest -x --maxfail=2
pytest --tb=short

트레이스백 스타일을 선택합니다: `long`(기본), `short`, `line`, `native`, `no`(억제).

long; short; line; native; no

pytest --tb=short
pytest -v

자세한 모드 — 각 테스트 함수의 전체 노드 ID를 표시합니다. `-vv`로 더 자세한 정보도 함께 봅니다.

-v; -vv; --no-header; --no-summary; -q; -rA

pytest -v --no-header
pytest -s

stdout/stderr 캡처를 비활성화합니다 — `print()` 문이 터미널로 직접 흐르게 합니다(드묾; 대신 테스트 내부에서 `capfd` 픽스처 사용).

--capture=no; -s; --capture=fd

pytest -s tests/test_print.py
pytest --durations=10

최종 리포트에서 가장 느린 10개 테스트를 표시합니다(전체를 보려면 `--durations=0`).

--durations=10; --durations=min=0.5

pytest --durations=10
pytest -rA

추가 테스트 결과 요약을 출력합니다: `E` 오류, `F` 실패, `s` 스킵, `x` xfail, `A` 모두.

-rA; -rfE; -rs; -rxX

pytest -rA

재실행

pytest --lf

마지막 실패 — 이전 실행에서 실패한 테스트만 다시 실행합니다. 실패한 테스트를 먼저 정렬하려면 `--ff`와 함께 사용하세요.

--lf; --last-failed; --ff; --failed-first; --cache-clear

pytest --lf
pytest --sw

단계별 모드 — 첫 번째 실패에서 멈추고 다음 호출에서 거기서 재개합니다.

--stepwise; --stepwise-skip; --stepwise-skip-some

pytest --sw

Parametrize / 픽스처

pytest --fixtures

현재 테스트 범위에서 보이는 모든 픽스처를 나열합니다(리포지터리 루트에서 실행하면 프로젝트 전체).

--fixtures; --fixtures-per-test

pytest --fixtures -q
pytest --markers

정의된 모든 마커를 나열합니다(pytest.ini / pyproject.toml에 등록됨).

--markers

pytest --markers

병렬 처리

pytest -n <N>

`<N>` 워커 프로세스에서 테스트를 병렬로 실행합니다(pytest-xdist 플러그인). CPU 수만큼 워커를 쓰려면 `auto`를 사용하세요.

-n auto; -n 4; --dist loadscope; --dist loadfile; -p no:cacheprovider

pytest -n auto
pytest --dist loadgroup

`@pytest.mark.group_*` 마커로 테스트를 그룹화(xdist)해 단일 그룹이 단일 워커에서 실행되도록 합니다 — 리소스 충돌 테스트에 유용합니다.

--dist loadgroup; --dist loadscope

pytest -n 4 --dist loadgroup

출력

pytest --junitxml=<file>

JUnit 스타일 XML 리포트를 출력합니다(GitHub Actions, GitLab, Jenkins, CircleCI가 소비).

--junitxml=report.xml; --junit-xml=report.xml

pytest --junitxml=pytest-report.xml
pytest --html=<file>

자체 완결적인 HTML 테스트 리포트를 생성합니다(pytest-html 플러그인).

--html=report.html; --self-contained-html

pytest --html=report.html --self-contained-html
pytest --cov=<pkg>

coverage 측정 하에 테스트를 실행합니다(pytest-cov 플러그인). `--cov-report=`로 출력 형식을 선택하세요.

--cov=src; --cov-report=term; --cov-report=xml; --cov-report=html; --cov-fail-under=80

pytest --cov=src --cov-report=term-missing --cov-fail-under=80

감시 / 자동 재실행

pytest --looponfail

통과할 때까지 매 저장마다 실패한 테스트를 다시 실행합니다(pytest 7+에서 deprecated; pytest-watch / pytest-xdist --loop-onfail 사용).

--looponfail

pytest --looponfail
ptw

pytest을 감시 모드로 실행합니다 — 모든 파일 변경 시 스위트를 다시 실행합니다(pytest-watch, pip로 설치).

--clear; --runner 'pytest -x'; --now

ptw -- -x

설정

pytest -c <file>

pytest 설정 파일을 재정의합니다(기본 `pytest.ini` / `pyproject.toml [tool.pytest.ini_options]` / `tox.ini` / `setup.cfg`).

-c pytest.ini; -c tests/pytest-cfg.ini

pytest -c tests/pytest-cfg.ini
pytest -p <plugin>

CLI에서 플러그인을 로드합니다(예: `pytest -p no:cacheprovider`는 캐싱을 비활성화).

-p django; -p asyncio; -p no:warnings; -p no:cacheprovider

pytest -p no:cacheprovider

디버그

pytest --trace

첫 번째 테스트 시작 시 `pdb.set_trace()`에 진입합니다(비-CLI 충돌에는 `--trace-cli` 사용).

--trace; --trace-cli

pytest --trace tests/test_user.py::test_login
pytest --pdb

모든 테스트 실패 또는 오류 시 자동으로 pdb를 시작합니다.

--pdb; --pdbcls=IPython.terminal.debugger.TerminalPdb

pytest --pdb -x
pytest --setup-show

실행 중 픽스처의 setup / teardown 트레이스를 표시합니다(실행 없이 트레이스만 보려면 `--setup-plan` 사용).

--setup-show; --setup-plan

pytest --setup-show tests/test_db.py

경고

pytest -W <filter>

pytest이 발생시킨 것처럼 Python 경고를 전달합니다. 필터는 `-W` 액션 모듈 사양을 따릅니다.

-W error; -W ignore::DeprecationWarning; -W default

pytest -W error::DeprecationWarning
pytest --strict-markers

등록되지 않은 마커를 오류로 처리합니다 — `@pytest.mark.slow` 등의 오타를 잡습니다.

--strict-markers; --strict-config; --strict

pytest --strict-markers

비동기

pytest -p asyncio

`async def test_*` 함수를 지원하도록 pytest-asyncio 플러그인을 등록합니다.

-p asyncio; --asyncio-mode=auto

pytest --asyncio-mode=auto

기타

pytest --rootdir=<dir>

pytest이 설정 디스커버리에 사용하는 프로젝트 루트를 재정의합니다.

--rootdir=.; --import-mode=importlib

pytest --rootdir=. tests/

관련 명령어 치트시트

pytest 소개

pytest는 사실상 표준 Python 테스팅 프레임워크입니다. Holger Krekel이 만들고 2008년에 출시되었으며(원래 더 오래된 `py` 라이브러리의 후속), Python 표준 라이브러리 `unittest`의 보일러플레이트를 단순화합니다 — 테스트는 평범한 `def test_*():` 함수이며, 클래스 보일러플레이트가 필요 없고 — 강력한 픽스처 시스템, parametrize, 마커, 풍부한 플러그인 생태계(pytest-cov, pytest-xdist, pytest-mock, pytest-django, pytest-asyncio, hypothesis 등)를 제공합니다. 현재 안정 라인은 pytest 8+(8.3+)입니다. pytest는 기본 명명 규칙(`test_*.py` / `*_test.py`)으로 테스트를 자동 디스커버리하고, 결정적 순서로 실행하며, 단언 실패 시 풍부한 diff를 생성합니다. pytest는 unittest / nose 스타일 테스트도 실행할 수 있습니다. 흔히 함께 쓰는 동반 CLI는 `coverage`(`coverage run -m pytest` 후 `coverage report`)입니다. pytest는 코드를 업로드하지 않으며, 모든 테스트 실행은 로컬입니다.

치트시트 버전 1.0.0