Skip to main content
 首页 » 编程设计

python之Pytest:更新测试中的全局变量

2025年04月02日14hnrainll

我是 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 结果的句柄,通过它我可以了解通过和失败的测试用例的数量。这显示在测试摘要中。但是我正在寻找一个对象,我可以在执行测试后在脚本中进一步使用它

请您参考如下方法:

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

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