如何在pytest中的teardown_module()中获得模块的所有测试的结果(通过/失败)

时间:2017-07-19 07:15:55

标签: python pytest

这是我的情景。 我有一个test_1.py文件,就像这样

import pytest
def setup_module():
    print 'setup module'
def teardown_module():
    print 'teardown module'

class Test_ABC:
    def setup_class(cls):
        print 'setup class'
    def teardown_class(cls):
        print 'teardown class'
    def test_1(self):
        print 'test_1'
    def test_2(self):
        print 'test_2'

所以在这里我想知道是否有可能获得test_1test_2测试的结果(通过/失败)。 可以说,如果测试套件中的任何测试失败,我需要发送电子邮件。 我在teardown模块中调用电子邮件模块。

1 个答案:

答案 0 :(得分:0)

在测试包中的conftest.py中,例如:

from _pytest.runner import runtestprotocol


def pytest_runtest_protocol(item, nextitem):

    reports = runtestprotocol(item, nextitem=nextitem)
    for report in reports:
        if report.when == 'call':
            print('\n%s --- %s' % (item.name, report.outcome))

                if report.outcome is 'passed':
                    print('cool too')
                elif report.outcome is 'failed':
                    print('cool')
    return True

另一种选择是:

    @pytest.fixture
    def after_test_report_pass_fail(request):
        yield
... your code goes here

然后你可以报告每个项目(测试)

相关问题