test_*.py or *_test.py | 테스트 파일 이름 |
def test_function(): | 테스트 함수 이름 |
class TestClass: | 테스트 클래스 이름 |
def test_method(self): | 클래스 내 테스트 메서드 |
assert x == y | 기본 단언문 |
assert x != y | 같지 않음 |
assert x in collection | 포함 여부 |
assert x is None | None인지 |
assert x is not None | None이 아닌지 |
assert isinstance(x, Type) | 타입 확인 |
assert 0.1 + 0.2 == pytest.approx(0.3) | 부동소수점 비교 |
pytest | 모든 테스트 실행 |
pytest test_file.py | 특정 파일 실행 |
pytest test_file.py::test_func | 특정 테스트 실행 |
pytest test_file.py::TestClass | 테스트 클래스 실행 |
pytest -k "keyword" | 키워드로 실행 |
pytest -k "not slow" | 키워드 제외 |
pytest -m marker | 마커로 실행 |
pytest -v | 상세 출력 |
pytest -vv | 더 상세 출력 |
pytest -q | 조용한 출력 |
pytest -s | print 문 표시 |
pytest --tb=short | 짧은 트레이스백 |
pytest --tb=long | 긴 트레이스백 |
pytest --tb=no | 트레이스백 없음 |
pytest -l | 트레이스백에 로컬 변수 표시 |
pytest -x | 첫 실패 시 중지 |
pytest --maxfail=3 | N번 실패 후 중지 |
pytest --lf | 마지막 실패 재실행 |
pytest --ff | 실패 먼저, 나머지 후 |
pytest -n auto | 병렬 (pytest-xdist) |
pytest --durations=10 | 가장 느린 10개 표시 |
@pytest.fixture | 픽스처 정의 |
def test_func(fixture_name): | 픽스처 사용 |
@pytest.fixture(scope="function") | 함수 스코프 (기본) |
@pytest.fixture(scope="class") | 클래스 스코프 |
@pytest.fixture(scope="module") | 모듈 스코프 |
@pytest.fixture(scope="session") | 세션 스코프 |
@pytest.fixture(autouse=True) | 자동 사용 픽스처 |
yield value | 설정/해제 픽스처 |
@pytest.fixture(params=[1, 2, 3]) | 매개변수화된 픽스처 |
request.param | 픽스처 매개변수 접근 |
conftest.py | 공유 픽스처 파일 |
@pytest.fixture(name="custom_name") | 커스텀 픽스처 이름 |
tmp_path | 임시 디렉토리 (Path) |
tmp_path_factory | 임시 디렉토리 팩토리 |
capsys | stdout/stderr 캡처 |
capfd | 파일 디스크립터 캡처 |
monkeypatch | 객체 수정 |
request | 테스트 요청 정보 |
@pytest.mark.skip | 테스트 건너뛰기 |
@pytest.mark.skip(reason="msg") | 이유와 함께 건너뛰기 |
@pytest.mark.skipif(condition, reason="") | 조건부 건너뛰기 |
@pytest.mark.xfail | 예상 실패 |
@pytest.mark.xfail(raises=Exception) | 예상 예외 |
@pytest.mark.usefixtures("fix1", "fix2") | 픽스처 사용 |
@pytest.mark.slow | 커스텀 마커 |
@pytest.mark.integration | 통합 테스트 마커 |
pytest.ini: markers = slow: desc | 마커 등록 |
pytest -m "slow" | 마커된 테스트 실행 |
pytest -m "not slow" | 마커된 테스트 제외 |
@pytest.mark.parametrize("arg", [1, 2, 3]) | 단일 매개변수 |
@pytest.mark.parametrize("a,b", [(1,2), (3,4)]) | 다중 매개변수 |
@pytest.mark.parametrize("a", [1, pytest.param(2, marks=pytest.mark.skip)]) | 마커가 있는 매개변수 |
@pytest.mark.parametrize("a", [1, 2], ids=["one", "two"]) | 커스텀 ID |
with pytest.raises(ValueError): | 예외 예상 |
with pytest.raises(ValueError, match="pattern"): | 메시지 매칭 |
exc_info = pytest.raises(ValueError)\nexc_info.value | 예외 접근 |
@pytest.mark.xfail(raises=ValueError) | 발생 예상 |
with pytest.warns(UserWarning): | 경고 예상 |
with pytest.warns(UserWarning, match="msg"): | 경고 매칭 |
pytest -W error::UserWarning | 경고를 에러로 취급 |
@pytest.mark.filterwarnings("ignore::Warning") | 경고 무시 |
monkeypatch.setattr(obj, "attr", value) | 속성 설정 |
monkeypatch.setattr("module.func", mock_func) | 함수 모킹 |
monkeypatch.delattr(obj, "attr") | 속성 삭제 |
monkeypatch.setenv("VAR", "value") | 환경 변수 설정 |
monkeypatch.delenv("VAR") | 환경 변수 삭제 |
monkeypatch.chdir(path) | 디렉토리 변경 |
from unittest.mock import Mock, patch | mock 가져오기 |
mock = Mock(return_value=42) | mock 생성 |
mock.assert_called_once() | 한 번 호출 확인 |
@patch("module.function") | patch 데코레이터 |
with patch("module.function") as mock: | patch 컨텍스트 매니저 |