3

我是 Python 新手,正在使用 pytest 进行测试

我正在从 python 脚本中执行 pytest。我在脚本中有一个全局变量,我根据测试结果进行了修改。执行测试后再次使用更新的全局变量。

import pytest
global test_suite_passed
test_suite_passed = True

def test_toggle():
   global test_suite_passed
   a = True
   b = True
   c = True if a == b else False
   test_suite_passed = c
   assert c

def test_switch():
   global test_suite_passed
   one = True
   two = False
   three = True if one == two else False
   if test_suite_passed:
      test_suite_passed = three
   assert three


if __name__ == '__main__':
   pytest.main()
   if not test_suite_passed:
      raise Exception("Test suite failed")
   print "Test suite passed"

我有两个问题:

1)上面的代码片段打印“测试套件通过”,而我希望在第二个测试用例失败时引发异常。

2)基本上,我想要一个pytest结果的句柄,通过它我可以知道通过和失败的测试用例的数量。这显示在测试摘要中。但是我正在寻找一个可以在执行测试后在脚本中进一步使用的对象

4

2 回答 2

1

这可以使用调用pytest.main()时的退出代码返回来解决, 不需要全局变量

import pytest

def test_toggle():
    a = True
    b = True
    c = True if a == b else False
    assert c

def test_switch():
    one = True
    two = False
    three = True if one == two else False
    assert three


if __name__ == '__main__':
    exit_code = pytest.main()
    if exit_code == 1:
        raise Exception("Test suite failed")
    print "Test suite passed"
于 2016-08-07T01:59:13.997 回答
1

pytest 旨在从命令行调用,而不是从测试脚本内部调用。您的全局变量不起作用,因为 pytest 将您的脚本作为模块导入,该模块具有自己的命名空间。

要自定义报告生成,请使用 post-process-hook: http ://doc.pytest.org/en/latest/example/simple.html#post-process-test-reports-failures

于 2016-08-06T08:56:20.140 回答