Pytest:在测试中更新全局变量

时间:2016-08-06 06:24:46

标签: python python-2.7 pytest pytest-django

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

2 个答案:

答案 0 :(得分: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"

答案 1 :(得分:0)

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

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

相关问题