Spec-Zone.ru › pytest

Основные шаблоны и примеры

Как изменить значения параметров командной строки по умолчанию

Каждый раз вводить одну и ту же последовательность параметров командной строки при использовании pytest может быть утомительно. Например, если вы всегда хотите видеть подробную информацию о пропущенных тестах и тестах с ожидаемым сбоем, а также получать более компактный вывод хода выполнения в виде точек, вы можете записать это в файл конфигурации:

# content of pytest.toml
[pytest]
addopts = ["-ra", "-q"]

Также можно задать переменную среды PYTEST_ADDOPTS, чтобы добавлять параметры командной строки на время использования этой среды:

export PYTEST_ADDOPTS="-v"

Вот как формируется командная строка при наличии addopts или переменной среды:

<configuration file addopts> $PYTEST_ADDOPTS <extra command-line arguments>

Итак, если пользователь выполнит в командной строке:

pytest -m slow

Фактически будет выполнена следующая командная строка:

pytest -ra -q -v -m slow

Обратите внимание: как и в других приложениях командной строки, при конфликтующих параметрах действует последний из них, поэтому в примере выше будет показан подробный вывод, так как -v переопределяет -q.

Передача тестовой функции разных значений в зависимости от параметров командной строки

Предположим, мы хотим написать тест, поведение которого зависит от параметра командной строки. Вот базовый шаблон, который позволяет это сделать:

# content of test_sample.py
def test_answer(cmdopt):
    if cmdopt == "type1":
        print("first")
    elif cmdopt == "type2":
        print("second")
    assert 0  # to see what was printed

Для этого нужно добавить параметр командной строки и предоставить cmdopt с помощью функции-фикстуры:

# content of conftest.py
import pytest


def pytest_addoption(parser):
    parser.addoption(
        "--cmdopt", action="store", default="type1", help="my option: type1 or type2"
    )


@pytest.fixture
def cmdopt(request):
    return request.config.getoption("--cmdopt")

Запустим тест без нового параметра:

$ pytest -q test_sample.py
F                                                                    [100%]
================================= FAILURES =================================
_______________________________ test_answer ________________________________

cmdopt = 'type1'

    def test_answer(cmdopt):
        if cmdopt == "type1":
            print("first")
        elif cmdopt == "type2":
            print("second")
>       assert 0  # to see what was printed
        ^^^^^^^^
E       assert 0

test_sample.py:6: AssertionError
--------------------------- Captured stdout call ---------------------------
first
========================= short test summary info ==========================
FAILED test_sample.py::test_answer - assert 0
1 failed in 0.12s

А теперь укажем параметр командной строки:

$ pytest -q --cmdopt=type2
F                                                                    [100%]
================================= FAILURES =================================
_______________________________ test_answer ________________________________

cmdopt = 'type2'

    def test_answer(cmdopt):
        if cmdopt == "type1":
            print("first")
        elif cmdopt == "type2":
            print("second")
>       assert 0  # to see what was printed
        ^^^^^^^^
E       assert 0

test_sample.py:6: AssertionError
--------------------------- Captured stdout call ---------------------------
second
========================= short test summary info ==========================
FAILED test_sample.py::test_answer - assert 0
1 failed in 0.12s

Как видите, параметр командной строки был передан нашему тесту.

Можно добавить простую проверку ввода, перечислив допустимые значения:

# content of conftest.py
import pytest


def pytest_addoption(parser):
    parser.addoption(
        "--cmdopt",
        action="store",
        default="type1",
        help="my option: type1 or type2",
        choices=("type1", "type2"),
    )

Теперь при неверном аргументе мы получим сообщение об ошибке:

$ pytest -q --cmdopt=type3
ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...]
pytest: error: argument --cmdopt: invalid choice: 'type3' (choose from 'type1', 'type2')
  inifile: None
  rootdir: /home/sweet/project

Если вам нужны более подробные сообщения об ошибках, можно использовать параметр type и вызвать исключение pytest.UsageError:

# content of conftest.py
import pytest


def type_checker(value):
    msg = "cmdopt must specify a numeric type as typeNNN"
    if not value.startswith("type"):
        raise pytest.UsageError(msg)
    try:
        int(value[4:])
    except ValueError:
        raise pytest.UsageError(msg)

    return value


def pytest_addoption(parser):
    parser.addoption(
        "--cmdopt",
        action="store",
        default="type1",
        help="my option: type1 or type2",
        type=type_checker,
    )

На этом базовый шаблон завершён. Однако часто бывает удобнее обрабатывать параметры командной строки вне теста, а затем передавать разные или более сложные объекты.

Динамическое добавление параметров командной строки

С помощью addopts можно статически добавить параметры командной строки для проекта. Также можно динамически изменить аргументы командной строки до их обработки:

# installable external plugin
import sys


def pytest_load_initial_conftests(args):
    if "xdist" in sys.modules:  # pytest-xdist plugin
        import multiprocessing

        num = max(multiprocessing.cpu_count() / 2, 1)
        args[:] = ["-n", str(num)] + args

Если у вас установлен плагин xdist, то теперь тесты всегда будут запускаться с числом подпроцессов, близким к числу процессоров вашего компьютера. Запустим pytest в пустом каталоге с приведённым выше файлом conftest.py:

$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 0 items

========================== no tests ran in 0.12s ===========================

Управление пропуском тестов с помощью параметра командной строки

Вот файл conftest.py, добавляющий параметр командной строки --runslow для управления пропуском тестов, помеченных маркером pytest.mark.slow:

# content of conftest.py

import pytest


def pytest_addoption(parser):
    parser.addoption(
        "--runslow", action="store_true", default=False, help="run slow tests"
    )


def pytest_configure(config):
    config.addinivalue_line("markers", "slow: mark test as slow to run")


def pytest_collection_modifyitems(config, items):
    if config.getoption("--runslow"):
        # --runslow given in cli: do not skip slow tests
        return
    skip_slow = pytest.mark.skip(reason="need --runslow option to run")
    for item in items:
        if "slow" in item.keywords:
            item.add_marker(skip_slow)

Теперь можно написать такой тестовый модуль:

# content of test_module.py
import pytest


def test_func_fast():
    pass


@pytest.mark.slow
def test_func_slow():
    pass

и при запуске увидим, что тест “slow” пропущен:

$ pytest -rs    # "-rs" means report details on the little 's'
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 2 items

test_module.py .s                                                    [100%]

========================= short test summary info ==========================
SKIPPED [1] test_module.py:8: need --runslow option to run
======================= 1 passed, 1 skipped in 0.12s =======================

Или запустить его, включив тест с маркером slow:

$ pytest --runslow
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 2 items

test_module.py ..                                                    [100%]

============================ 2 passed in 0.12s =============================

Создание хорошо интегрированных вспомогательных функций для проверок

Если тест вызывает вспомогательную функцию, можно использовать маркер pytest.fail, чтобы завершить тест с определённым сообщением. Если задать параметр __tracebackhide__ в теле вспомогательной функции, она не будет отображаться в трассировке. Например:

# content of test_checkconfig.py
import pytest


def checkconfig(x):
    __tracebackhide__ = True
    if not hasattr(x, "config"):
        pytest.fail(f"not configured: {x}")


def test_something():
    checkconfig(42)

Настройка __tracebackhide__ влияет на отображение трассировок в pytest: функция checkconfig не будет показана, если не указан параметр командной строки --full-trace. Запустим нашу небольшую функцию:

$ pytest -q test_checkconfig.py
F                                                                    [100%]
================================= FAILURES =================================
______________________________ test_something ______________________________

    def test_something():
>       checkconfig(42)
E       Failed: not configured: 42

test_checkconfig.py:11: Failed
========================= short test summary info ==========================
FAILED test_checkconfig.py::test_something - Failed: not configured: 42
1 failed in 0.12s

Если нужно скрывать только определённые исключения, можно присвоить __tracebackhide__ вызываемый объект, которому передаётся объект ExceptionInfo. Например, так можно убедиться, что неожиданные типы исключений не скрываются:

import operator

import pytest


class ConfigException(Exception):
    pass


def checkconfig(x):
    __tracebackhide__ = operator.methodcaller("errisinstance", ConfigException)
    if not hasattr(x, "config"):
        raise ConfigException(f"not configured: {x}")


def test_something():
    checkconfig(42)

Это позволит не скрывать трассировку исключения для посторонних исключений (то есть ошибок во вспомогательных функциях проверок).

Определение запуска из процесса pytest

Обычно не стоит менять поведение кода приложения в зависимости от того, был ли он вызван из теста. Но если вам непременно нужно определить, выполняется ли код приложения из теста, это можно сделать так:

import os


if os.environ.get("PYTEST_VERSION") is not None:
    # Things you want to do if your code is called by pytest.
    ...
else:
    # Things you want to do if your code is not called by pytest.
    ...

Добавление информации в заголовок отчёта о тестировании

Добавить дополнительную информацию в запуск pytest несложно:

# content of conftest.py


def pytest_report_header(config):
    return "project deps: mylib-1.1"

В результате эта строка будет добавлена в заголовок теста:

$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
project deps: mylib-1.1
rootdir: /home/sweet/project
collected 0 items

========================== no tests ran in 0.12s ===========================

Также можно вернуть список строк, которые будут отображены как несколько строк информации. Чтобы показывать дополнительную информацию, если это применимо, можно использовать config.getoption('verbose'):

# content of conftest.py


def pytest_report_header(config):
    if config.get_verbosity() > 0:
        return ["info1: did you know that ...", "did you?"]

В этом случае информация будет добавляться только при запуске с параметром “–v”:

$ pytest -v
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python
cachedir: .pytest_cache
info1: did you know that ...
did you?
rootdir: /home/sweet/project
collecting ... collected 0 items

========================== no tests ran in 0.12s ===========================

а при обычном запуске её не будет:

$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 0 items

========================== no tests ran in 0.12s ===========================

Профилирование длительности тестов

Если ваш большой набор тестов выполняется медленно, может быть полезно выяснить, какие тесты самые медленные. Создадим искусственный набор тестов:

# content of test_some_are_slow.py
import time


def test_funcfast():
    time.sleep(0.1)


def test_funcslow1():
    time.sleep(0.2)


def test_funcslow2():
    time.sleep(0.3)

Теперь можно определить, какие тестовые функции выполняются медленнее всего:

$ pytest --durations=3
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 3 items

test_some_are_slow.py ...                                            [100%]

=========================== slowest 3 durations ============================
0.30s call     test_some_are_slow.py::test_funcslow2
0.20s call     test_some_are_slow.py::test_funcslow1
0.10s call     test_some_are_slow.py::test_funcfast
============================ 3 passed in 0.12s =============================

Инкрементальное тестирование — шаги теста

Иногда тестирование состоит из последовательности шагов. Если один шаг завершается с ошибкой, дальнейшие шаги выполнять бессмысленно: ожидается, что они тоже завершатся с ошибкой, а их трассировки не дадут дополнительной информации. Вот простой файл conftest.py, в котором определяется маркер incremental для использования с классами:

# content of conftest.py

import pytest

# store history of failures per test class name and per index in parametrize (if parametrize used)
_test_failed_incremental: dict[str, dict[tuple[int, ...], str]] = {}


def pytest_runtest_makereport(item, call):
    if "incremental" in item.keywords:
        # incremental marker is used
        if call.excinfo is not None:
            # the test has failed
            # retrieve the class name of the test
            cls_name = str(item.cls)
            # retrieve the index of the test (if parametrize is used in combination with incremental)
            parametrize_index = (
                tuple(item.callspec.indices.values())
                if hasattr(item, "callspec")
                else ()
            )
            # retrieve the name of the test function
            test_name = item.originalname or item.name
            # store in _test_failed_incremental the original name of the failed test
            _test_failed_incremental.setdefault(cls_name, {}).setdefault(
                parametrize_index, test_name
            )


def pytest_runtest_setup(item):
    if "incremental" in item.keywords:
        # retrieve the class name of the test
        cls_name = str(item.cls)
        # check if a previous test has failed for this class
        if cls_name in _test_failed_incremental:
            # retrieve the index of the test (if parametrize is used in combination with incremental)
            parametrize_index = (
                tuple(item.callspec.indices.values())
                if hasattr(item, "callspec")
                else ()
            )
            # retrieve the name of the first test function to fail for this class name and index
            test_name = _test_failed_incremental[cls_name].get(parametrize_index, None)
            # if name found, test has failed for the combination of class name & test name
            if test_name is not None:
                pytest.xfail(f"previous test failed ({test_name})")

Эти две реализации хуков совместно прерывают тесты в классе, помеченные как инкрементальные. Вот пример тестового модуля:

# content of test_step.py

import pytest


@pytest.mark.incremental
class TestUserHandling:
    def test_login(self):
        pass

    def test_modification(self):
        assert 0

    def test_deletion(self):
        pass


def test_normal():
    pass

Если запустить его:

$ pytest -rx
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 4 items

test_step.py .Fx.                                                    [100%]

================================= FAILURES =================================
____________________ TestUserHandling.test_modification ____________________

self = <test_step.TestUserHandling object at 0xdeadbeef0001>

    def test_modification(self):
>       assert 0
E       assert 0

test_step.py:11: AssertionError
========================= short test summary info ==========================
XFAIL test_step.py::TestUserHandling::test_deletion - previous test failed (test_modification)
================== 1 failed, 2 passed, 1 xfailed in 0.12s ==================

Мы увидим, что test_deletion не был выполнен, потому что test_modification завершился с ошибкой. Он отмечен как «ожидаемо завершившийся с ошибкой».

Фикстуры на уровне пакета/каталога (настройка)

Если у вас есть вложенные каталоги с тестами, можно задать область видимости фикстур для каждого каталога, разместив функции-фикстуры в файле conftest.py этого каталога. Можно использовать все типы фикстур, в том числе автоматически используемые фикстуры, соответствующие концепции настройки/очистки из xUnit. Однако рекомендуется явно указывать фикстуры в тестах или тестовых классах, а не полагаться на неявное выполнение функций настройки/очистки, особенно если они находятся далеко от самих тестов.

Вот пример создания фикстуры db, доступной в каталоге:

# content of a/conftest.py
import pytest


class DB:
    pass


@pytest.fixture(scope="package")
def db():
    return DB()

а затем тестового модуля в этом каталоге:

# content of a/test_db.py
def test_a1(db):
    assert 0, db  # to show value

ещё одного тестового модуля:

# content of a/test_db2.py
def test_a2(db):
    assert 0, db  # to show value

и модуля в соседнем каталоге, которому фикстура db будет недоступна:

# content of b/test_error.py
def test_root(db):  # no db here, will error out
    pass

Запустим тесты:

$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 7 items

a/test_db.py F                                                       [ 14%]
a/test_db2.py F                                                      [ 28%]
b/test_error.py E                                                    [ 42%]
test_step.py .Fx.                                                    [100%]

================================== ERRORS ==================================
_______________________ ERROR at setup of test_root ________________________
file /home/sweet/project/b/test_error.py, line 1
  def test_root(db):  # no db here, will error out
E       fixture 'db' not found
>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, capteesys, doctest_namespace, monkeypatch, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, subtests, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory
>       use 'pytest --fixtures [testpath]' for help on them.

/home/sweet/project/b/test_error.py:1
================================= FAILURES =================================
_________________________________ test_a1 __________________________________

db = <conftest.DB object at 0xdeadbeef0002>

    def test_a1(db):
>       assert 0, db  # to show value
        ^^^^^^^^^^^^
E       AssertionError: <conftest.DB object at 0xdeadbeef0002>
E       assert 0

a/test_db.py:2: AssertionError
_________________________________ test_a2 __________________________________

db = <conftest.DB object at 0xdeadbeef0002>

    def test_a2(db):
>       assert 0, db  # to show value
        ^^^^^^^^^^^^
E       AssertionError: <conftest.DB object at 0xdeadbeef0002>
E       assert 0

a/test_db2.py:2: AssertionError
____________________ TestUserHandling.test_modification ____________________

self = <test_step.TestUserHandling object at 0xdeadbeef0003>

    def test_modification(self):
>       assert 0
E       assert 0

test_step.py:11: AssertionError
========================= short test summary info ==========================
FAILED a/test_db.py::test_a1 - AssertionError: <conftest.DB object at 0x7...
FAILED a/test_db2.py::test_a2 - AssertionError: <conftest.DB object at 0x...
FAILED test_step.py::TestUserHandling::test_modification - assert 0
ERROR b/test_error.py::test_root
============= 3 failed, 2 passed, 1 xfailed, 1 error in 0.12s ==============

Два тестовых модуля в каталоге a используют один и тот же экземпляр фикстуры db, а единственный тест в соседнем каталоге b её не видит. Разумеется, в файле conftest.py этого соседнего каталога можно также определить фикстуру db. Обратите внимание: каждая фикстура создаётся, только если она действительно нужна тесту (если только вы не используете фикстуры с автоматическим запуском, которые выполняются перед первым тестом).

Постобработка отчётов о тестировании и ошибках

Если вы хотите выполнять постобработку отчётов о тестировании и вам нужен доступ к среде выполнения, можно реализовать хук, вызываемый перед созданием объекта «отчёта» о тесте. В этом примере мы записываем информацию обо всех вызовах тестов, завершившихся с ошибкой, а также получаем доступ к фикстуре (если тест её использовал), чтобы при необходимости просмотреть её во время постобработки. В нашем случае мы просто записываем некоторую информацию в файл failures:

# content of conftest.py

import os.path

import pytest


@pytest.hookimpl(wrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
    # execute all other hooks to obtain the report object
    rep = yield

    # we only look at actual failing test calls, not setup/teardown
    if rep.when == "call" and rep.failed:
        mode = "a" if os.path.exists("failures") else "w"
        with open("failures", mode, encoding="utf-8") as f:
            # let's also access a fixture for the fun of it
            if "tmp_path" in item.fixturenames:
                extra = " ({})".format(item.funcargs["tmp_path"])
            else:
                extra = ""

            f.write(rep.nodeid + extra + "\n")

    return rep

если затем у вас есть тесты, завершающиеся с ошибкой:

# content of test_module.py
def test_fail1(tmp_path):
    assert 0


def test_fail2():
    assert 0

и вы запустите их:

$ pytest test_module.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 2 items

test_module.py FF                                                    [100%]

================================= FAILURES =================================
________________________________ test_fail1 ________________________________

tmp_path = PosixPath('PYTEST_TMPDIR/test_fail10')

    def test_fail1(tmp_path):
>       assert 0
E       assert 0

test_module.py:2: AssertionError
________________________________ test_fail2 ________________________________

    def test_fail2():
>       assert 0
E       assert 0

test_module.py:6: AssertionError
========================= short test summary info ==========================
FAILED test_module.py::test_fail1 - assert 0
FAILED test_module.py::test_fail2 - assert 0
============================ 2 failed in 0.12s =============================

у вас появится файл “failures” со списком идентификаторов тестов, завершившихся с ошибкой:

$ cat failures
test_module.py::test_fail1 (PYTEST_TMPDIR/test_fail10)
test_module.py::test_fail2

Предоставление информации о результатах тестирования в фикстурах

Если вы хотите сделать отчёты о результатах тестирования доступными в завершающих функциях фикстур, вот небольшой пример с локальным плагином:

# content of conftest.py
import pytest
from pytest import StashKey, CollectReport

phase_report_key = StashKey[dict[str, CollectReport]]()


@pytest.hookimpl(wrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
    # execute all other hooks to obtain the report object
    rep = yield

    # store test results for each phase of a call, which can
    # be "setup", "call", "teardown"
    item.stash.setdefault(phase_report_key, {})[rep.when] = rep

    return rep


@pytest.fixture
def something(request):
    yield
    # request.node is an "item" because we use the default
    # "function" scope
    report = request.node.stash[phase_report_key]
    if report["setup"].failed:
        print("setting up a test failed", request.node.nodeid)
    elif report["setup"].skipped:
        print("setting up a test skipped", request.node.nodeid)
    elif ("call" not in report) or report["call"].failed:
        print("executing test failed or skipped", request.node.nodeid)

если затем у вас есть тесты, завершающиеся с ошибкой:

# content of test_module.py

import pytest


@pytest.fixture
def other():
    assert 0


def test_setup_fails(something, other):
    pass


def test_call_fails(something):
    assert 0


def test_fail2():
    assert 0

и вы запустите их:

$ pytest -s test_module.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 3 items

test_module.py Esetting up a test failed test_module.py::test_setup_fails
Fexecuting test failed or skipped test_module.py::test_call_fails
F

================================== ERRORS ==================================
____________________ ERROR at setup of test_setup_fails ____________________

    @pytest.fixture
    def other():
>       assert 0
E       assert 0

test_module.py:7: AssertionError
================================= FAILURES =================================
_____________________________ test_call_fails ______________________________

something = None

    def test_call_fails(something):
>       assert 0
E       assert 0

test_module.py:15: AssertionError
________________________________ test_fail2 ________________________________

    def test_fail2():
>       assert 0
E       assert 0

test_module.py:19: AssertionError
========================= short test summary info ==========================
FAILED test_module.py::test_call_fails - assert 0
FAILED test_module.py::test_fail2 - assert 0
ERROR test_module.py::test_setup_fails - assert 0
======================== 2 failed, 1 error in 0.12s ========================

Вы увидите, что завершающие функции фикстур могут использовать точную информацию из отчёта.

Переменная среды PYTEST_CURRENT_TEST

Иногда сеанс тестирования может зависнуть, и бывает сложно определить, какой именно тест завис, например, если pytest был запущен в тихом режиме (-q) или у вас нет доступа к выводу консоли. Это особенно проблематично, если проблема возникает лишь время от времени — классический случай «нестабильных» тестов.

При запуске тестов pytest задаёт переменную среды PYTEST_CURRENT_TEST. С помощью утилит мониторинга процессов или библиотек вроде psutil можно проверить её значение и при необходимости выяснить, какой тест завис:

import psutil

for pid in psutil.pids():
    environ = psutil.Process(pid).environ()
    if "PYTEST_CURRENT_TEST" in environ:
        print(f'pytest process {pid} running: {environ["PYTEST_CURRENT_TEST"]}')

Во время сеанса тестирования pytest устанавливает PYTEST_CURRENT_TEST в значение текущего nodeid теста и текущего этапа, которым может быть setup, call или teardown.

Например, при запуске одной тестовой функции с именем test_foo из foo_module.py значение PYTEST_CURRENT_TEST будет следующим:

  1. foo_module.py::test_foo (setup)
  2. foo_module.py::test_foo (call)
  3. foo_module.py::test_foo (teardown)

именно в таком порядке.

Примечание

Содержимое PYTEST_CURRENT_TEST предназначено для чтения человеком, а его формат может меняться между выпусками (даже в исправлениях ошибок), поэтому не следует полагаться на него в сценариях или автоматизации.

Заморозка pytest

Если вы замораживаете приложение с помощью такого инструмента, как PyInstaller, чтобы распространять его среди конечных пользователей, имеет смысл включить в пакет и средство запуска тестов, а затем запускать тесты с помощью замороженного приложения. Так можно заранее обнаружить ошибки упаковки — например, отсутствие зависимостей в исполняемом файле, — а также передать пользователям файлы тестов, чтобы они могли запустить их на своих компьютерах. Это может помочь собрать дополнительную информацию о трудно воспроизводимой ошибке.

К счастью, в последних выпусках PyInstaller уже есть специальный хук для pytest. Но если вы используете другой инструмент для заморозки исполняемых файлов, например cx_freeze или py2exe, можно использовать pytest.freeze_includes(), чтобы получить полный список внутренних модулей pytest. Однако способы настройки инструментов для поиска внутренних модулей различаются.

Вместо того чтобы замораживать средство запуска pytest в отдельный исполняемый файл, можно заставить замороженную программу выполнять его функции, предусмотрев обработку аргументов при запуске программы. Так можно получить один исполняемый файл, что обычно удобнее. Обратите внимание: используемый pytest механизм обнаружения плагинов (точки входа) не работает с замороженными исполняемыми файлами, поэтому pytest не может автоматически находить сторонние плагины. Чтобы включить сторонние плагины, например pytest-timeout, их нужно явно импортировать и передать в pytest.main.

# contents of app_main.py
import sys

import pytest_timeout  # Third party plugin

if len(sys.argv) > 1 and sys.argv[1] == "--pytest":
    import pytest

    sys.exit(pytest.main(sys.argv[2:], plugins=[pytest_timeout]))
else:
    # normal application execution: at this point argv can be parsed
    # by your argument-parsing library of choice as usual
    ...

Это позволяет запускать тесты с помощью замороженного приложения, используя стандартные параметры командной строки pytest:

./app_main --pytest --verbose --tb=long --junit=xml=results.xml test-suite/

© 2015–2026 Holger Krekel and pytest-dev team
Licensed under the MIT License.
https://docs.pytest.org/en/stable/example/simple.html

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API