Skip to main content
 首页 » 编程设计

python之使用 pytest 拆分不同函数的测试

2024年09月07日9www_RR

我正在使用 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 后 Hook 一次并检查 MyTestSuite 的所有测试是否正确通过。

有没有人有什么想法?

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

请您参考如下方法:

尝试使用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]  

运行测试 1 后的结果:

  1. Test tp1 completed correctly, or...
  2. AssertionError.

收集断言错误:

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) 

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