pytest - добавить утверждения ко всем или отмеченным тестовым функциям - PullRequest
0 голосов
/ 11 сентября 2018

У меня есть общие утверждения, выполненные для прибора (названного здесь obj) в конце большинства тестовых функций, например:

assert obj.is_empty
assert obj.no_errors

Как добавить такие шаги к каждой тестовой функции или только к отмеченным, чтобы шаги:

  • будет работать с pytest.mark.parametrize,
  • сообщит Ошибка (не Ошибка ) при сбое общих утверждений?

1 Ответ

0 голосов
/ 11 сентября 2018

Хотя мне лично не нравится идея запуска скрытых утверждений в тестах ( явное лучше, чем неявное ), это, безусловно, выполнимо в pytest путем реализации собственного pytest_runtest_call крючок.Простой пример:

# conftest.py
import pytest


class Obj:

    def __init__(self):
        self.is_empty = True
        self.no_errors = True


@pytest.fixture
def obj():
    return Obj()


def pytest_runtest_call(item):
    item.runtest()
    try:
        obj = item.funcargs['obj']
        assert obj.is_empty
        assert obj.no_errors
    except KeyError:
        pass

Пример тестов:

import pytest


def test_spam(obj):
    assert True

def test_eggs(obj):
    obj.is_empty = False
    assert True

def test_bacon(obj):
    obj.no_errors = False
    assert True

@pytest.mark.parametrize('somearg', ['foo', 'bar', 'baz'])
def test_parametrized(obj, somearg):
    assert True

Запуск теста дает:

$ pytest -sv
================================== test session starts ==================================
platform darwin -- Python 3.6.4, pytest-3.7.3, py-1.5.4, pluggy-0.7.1 -- 
cachedir: .pytest_cache
rootdir: /Users/hoefling/projects/private/stackoverflow, inifile:
plugins: cov-2.5.1
collected 3 items

test_spam.py::test_spam PASSED
test_spam.py::test_eggs FAILED
test_spam.py::test_bacon FAILED
test_spam.py::test_parametrized[foo] PASSED
test_spam.py::test_parametrized[bar] PASSED
test_spam.py::test_parametrized[baz] PASSED

======================================== FAILURES =======================================
_______________________________________ test_eggs _______________________________________

item = <Function 'test_eggs'>

    def pytest_runtest_call(item):
        item.runtest()
        try:
        obj = item.funcargs['obj']
>           assert obj.is_empty
E           assert False
E            +  where False = <conftest.Obj object at 0x105854ba8>.is_empty

conftest.py:20: AssertionError
______________________________________ test_bacon _______________________________________

item = <Function 'test_bacon'>

    def pytest_runtest_call(item):
        item.runtest()
        try:
            obj = item.funcargs['obj']
            assert obj.is_empty
>           assert obj.no_errors
E           assert False
E            +  where False = <conftest.Obj object at 0x105868198>.no_errors

conftest.py:21: AssertionError
========================== 2 failed, 1 passed in 0.05 seconds ===========================
...