개요
pytest는 성숙하고 완전한 기능을 갖춘 Python 테스트 도구로, fixture 매개변수화, 풍부한 플러그인 아키텍처 및 자동 테스트 검색을 지원합니다. 상세한 어설션 실패 정보를 제공하여 디버깅을 용이하게 합니다.
README 미리보기
.. image:: https://github.com/pytest-dev/pytest/raw/main/doc/en/img/pytest_logo_curves.svg\n :target: https://docs.pytest.org/en/stable/\n :align: center\n :height: 200\n :alt: pytest\n\n\n------\n\n.. image:: https://img.shields.io/pypi/v/pytest.svg\n :target: https://pypi.org/project/pytest/\n\n.. image:: https://img.shields.io/conda/vn/conda-forge/pytest.svg\n :target: https://anaconda.org/conda-forge/pytest\n\n.. image:: https://img.shields.io/pypi/pyversions/pytest.svg\n :target: https://pypi.org/project/pytest/\n\n.. image:: https://codecov.io/gh/pytest-dev/pytest/branch/main/graph/badge.svg\n :target: https://codecov.io/gh/pytest-dev/pytest\n :alt: Code coverage Status\n\n.. image:: https://github.com/pytest-dev/pytest/actions/workflows/test.yml/badge.svg\n :target: https://github.com/pytest-dev/pytest/actions?query=workflow%3Atest\n\n.. image:: https://results.pre-commit.ci/badge/github/pytest-dev/pytest/main.svg\n :target: https://results.pre-commit.ci/latest/github/pytest-dev/pytest/main\n :alt: pre-commit.ci status\n\n.. image:: https://www.codetriage.com/pytest-dev/pytest/badges/users.svg\n :target: https://www.codetriage.com/pytest-dev/pytest\n\n.. image:: https://readthedocs.org/projects/pytest/badge/?version=latest\n :target: https://pytest.readthedocs.io/en/latest/?badge=latest\n :alt: Documentation Status\n\n.. image:: https://img.shields.io/badge/Discord-pytest--dev-blue\n :target: https://discord.com/invite/pytest-dev\n :alt: Discord\n\n.. image:: https://img.shields.io/badge/Libera%20chat-%23pytest-orange\n :target: https://web.libera.chat/#pytest\n :alt: Libera chat\n\n\nThe ``pytest`` framework makes it easy to write small tests, yet\nscales to support complex functional testing for applications and libraries.\n\nAn example of a simple test:\n\n.. code-block:: python\n\n # content of test_sample.py\n def inc(x):\n return x + 1\n\n\n def test_answer():\n assert inc(3) == 5
FAQ (5)
문제 해결"py:class reference target not found: pluggy._compat.DistFacade" 경고로 인해 Sphinx 문서 빌드가 실패하는 문제를 해결하는 방법은?
이 오류는 Pluggy 1.7.0으로 문서를 빌드할 때(예: pytest의 경우 tox -e docs) 발생합니다. PluginManager.list_plugin_distinfo의 docstring이 문서화되지 않은 비공개 클래스 pluggy._compat.DistFacade를 참조하고, -W가 이 경고를 실패로 전환하기 때문입니다. 해결 방법: Sphinx conf.py의 nitpick_ignore에 해당 비공개 클래스를 추가하세요:
nitpick_ignore = [
# ... 기존 항목 ...
("py:class", "pluggy._compat.DistFacade"),
]
이렇게 하면 Pluggy를 핀 고정하거나 다운그레이드하지 않으면서 다른 모든 대상에 대한 엄격한 참조 검사를 유지할 수 있습니다. 참고: Pluggy 1.6.0으로 다운그레이드하는 것은 다른 비공개 Pluggy 타입 참조 경고를 유발하므로 유효한 해결 방법이 아닙니다.
문제 해결중첩된 시퀀스를 비교할 때 발생하는 pytest.approx() AttributeError: 'tuple' object has no attribute 'expected' 오류를 수정하는 방법
pytest.approx()는 튜플 리스트와 같은 중첩 데이터 구조(예: pytest.approx([(2.0, 2.0)]))를 지원하지 않습니다. pytest <= 9.1.1에서는 어설션 보고 과정에서 혼란스러운 AttributeError: 'tuple' object has no attribute 'expected' 오류가 발생합니다.
해결 방법:
1. 비교하기 전에 구조를 평탄화합니다: assert [x for t in sut() for x in t] == pytest.approx([2.0, 2.0])
2. 요소를 개별적으로 비교합니다: result = sut(); assert result[0] == pytest.approx((2.0, 2.0)) (숫자로 이루어진 단일 평면 튜플/리스트는 지원됩니다)
3. 숫자 2D 데이터의 경우 approx가 처리할 수 있는 numpy 배열을 사용합니다.
pytest 9.2+로 업그레이드(PR #14934의 수정 사항)해도 중첩 구조가 작동하지는 않지만, 알기 어려운 AttributeError가 명확한 오류 TypeError: pytest.approx() does not support nested data structures로 대체됩니다. 여전히 위에 나온 것처럼 비교 방식을 재구성해야 합니다.
문제 해결pytest exconly(tryshort=True)가 'AssertionError: '를 제거하지 않는 문제를 해결하는 방법?
이것은 pytest 8.0.2 및 관련 버전의 버그입니다: ExceptionInfo.for_later()는 예외가 캡처되기 전에 ExceptionInfo를 생성하며 assertion striptext를 절대 채우지 않으므로, exconly(tryshort=True)가 AssertionError: 접두사를 그대로 유지합니다.
예외 값을 직접 사용하세요:
with pytest.raises(AssertionError) as exc_info:
raise AssertionError("message")
message = str(exc_info.value)
assert message == "message"
exconly() 동작을 유지해야 하는 경우, 캡처된 예외로부터 ExceptionInfo를 다시 구성하세요:
from pytest import ExceptionInfo
message = ExceptionInfo.from_exception(
exc_info.value
).exconly(tryshort=True)
Python 3.9+에서 사용할 수 있는 문자열 우회 방법은 다음과 같습니다:
message = str(exc_info.value).removeprefix("AssertionError: ")문제 해결pytest가 ABCMeta 추상 메서드를 상속한 테스트 클래스를 수집하면서도 테스트가 없다고 보고하는 이유는 무엇인가요?
pytest 8.3+에서는 수집 단계에서 추상 테스트 클래스가 건너뛰어집니다. TestFoo 클래스는 상속된 test_foo 메서드를 구현하지 않아 추상 클래스로 남아 있으므로, pytest는 아무 경고 없이 이 클래스에서 아무것도 수집하지 않습니다.
구현되지 않은 추상 메서드를 확인하세요:
python -c "import your_test_module; print(your_test_module.TestFoo.__abstractmethods__)"
이 명령은 {'test_foo'}를 출력해야 합니다. 구상 테스트 클래스에서 모든 추상 메서드를 구현하여 문제를 해결하세요:
class TestFoo(AbstractTestFoo):
def test_foo(self):
assert True
그런 다음 pytest를 다시 실행하세요. 클래스가 의도적으로 추상 클래스이거나 수집되지 않아야 하는 경우에는 Test로 시작하지 않도록 이름을 변경하거나 __test__ = False를 설정하세요. 자동으로 건너뛰어지는 추상 클래스에 대한 pytest 경고는 issue #13546 및 draft PR #15082에서 추적되고 있었습니다.
문제 해결테스트 클래스가 추상 메서드를 상속할 때 pytest에서 'collected 0 items'라고 보고하는 이유는 무엇인가요?
TestFoo는 test_foo를 구현하지 않은 채 상속하므로 여전히 추상 클래스입니다. Pytest는 수집 과정에서 추상 클래스를 건너뛰기 때문에 테스트 인스턴스나 테스트 메서드가 수집되지 않습니다. 구체적인 하위 클래스에서 추상 메서드를 구현하세요:
class TestFoo(AbstractTestFoo):
def test_foo(self):
assert True # 여기에 테스트 작성
다음 명령으로 수집 결과를 확인하세요:
pytest --collect-only
이제 TestFoo::test_foo가 목록에 표시되어야 합니다. pytest 9.1.1에서는 이 상태가 아무 알림 없이 조용히 건너뛰어지며, 수집 중 실패하거나 경고를 표시하는 것은 제안된 변경 사항에 불과했습니다.