gpt4 book ai didi

python - 如何使用 unittest 从测试或设置中停止所有测试?

转载 作者:IT老高 更新时间:2023-10-28 21:02:21 25 4
gpt4 key购买 nike

我正在扩展 python 2.7 unittest 框架来做一些功能测试。我想做的一件事是阻止所有测试在测试内部和 setUpClass() 方法内部运行。有时如果一个测试失败了,程序就这么坏了,不再继续测试了,所以我想停止运行测试。

我注意到 TestResult 有一个 shouldStop 属性和一个 stop() 方法,但我不确定如何在测试中访问它.

有人有什么想法吗?有没有更好的办法?

最佳答案

如果您有兴趣,这里有一个简单的示例,您可以如何自己决定是否使用 py.test 干净地退出测试套件:

# content of test_module.py
import pytest
counter = 0
def setup_function(func):
global counter
counter += 1
if counter >=3:
pytest.exit("decided to stop the test run")

def test_one():
pass
def test_two():
pass
def test_three():
pass

如果你运行它,你会得到:

$ pytest test_module.py 
============== test session starts =================
platform linux2 -- Python 2.6.5 -- pytest-1.4.0a1
test path 1: test_module.py

test_module.py ..

!!!! Exit: decided to stop the test run !!!!!!!!!!!!
============= 2 passed in 0.08 seconds =============

您还可以将 py.test.exit() 调用放入测试或项目特定插件中。

旁注:py.test原生支持py.test --maxfail=NUM实现NUM失败后停止。

旁注 2:py.test 仅对以传统 unittest.TestCase 样式运行测试提供有限支持。

关于python - 如何使用 unittest 从测试或设置中停止所有测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3806695/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com