使用pytest在不同的函数中拆分测试

时间:2018-03-15 13:02:50

标签: python testing pytest

我使用pytest并运行多个测试来检查问题。

我想将所有测试分成不同的函数,如下所示:

# test_myTestSuite.py

@pytest.mark.issue(123)
class MyTestSuite():

    def test_part_1():
        result = do_something()
        assert result == True

    def test_part_2():
        result = do_an_other_something()
        assert result == 'ok'

当然,我在conftest.py

中实施了issue
# conftest.py

def pytest_addoption(parser):
    group = parser.getgroup('Issues')

    group.addoption('--issue', action='store',
                    dest='issue', default=0,
                    help='')

但我不知道在测试MyTestSuite后如何挂钩一次并检查MyTestSuite的所有测试是否正确通过。

有没有人有任何想法?

PS:这是我在StackOverflow上的第一篇文章。

1 个答案:

答案 0 :(得分:1)

尝试使用return函数作为最简单类型的正调试构造,如下所示。

@pytest.mark.issue(123)
class MyTestSuite():

    def test_part_1():
        result = do_something()
        assert result == True
        return 'tp1', True

    def test_part_2():
        result = do_an_other_something()
        assert result == 'ok'
        return 'tp2', True

..然后从以下位置开始测试:

x = MyTestSuite().test_part_1()
if x[1] == True:
    print 'Test %s completed correctly' % x[0] 

运行test1后的结果

  
      
  1. 测试tp1正确完成,或者......
  2.   
  3. 的AssertionError。
  4.   

收集断言错误:

collected_errors = []

def test_part_1():
    testname = 'tp1'
    try:
        result = do_something()
        assert result == True
        return testname, True
    except Exception as error:
        info = (testname, error)
        collected_errors.append(info)

您可以在SO上找到更多断言风格here