如何使用unittest停止测试或setUp内的所有测试?

use*_*674 19 python testing automated-tests functional-testing python-unittest

我正在扩展python 2.7 unittest框架来进行一些功能测试.我想做的一件事就是阻止所有测试在测试内部和setUpClass()方法内部运行.有时如果测试失败,程序就会破坏,不再有任何用处继续测试,所以我想阻止测试运行.

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

有没有人有任何想法?有没有更好的办法?

hpk*_*k42 16

如果您感兴趣,这里有一个简单的例子,您可以自己决定如何使用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
Run Code Online (Sandbox Code Playgroud)

如果你运行这个你得到:

$ 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 =============
Run Code Online (Sandbox Code Playgroud)

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

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

Sidenote2:py.test对传统unittest.TestCase样式运行测试的支持有限.

  • 当前版本的Py.Test:import pytest然后你可以做pytest.exit("你的消息") (2认同)
  • 这也适用于 conftest.py 文件中声明的 pytest 固定装置,scope='session', autouse=True。这将在项目中的每个测试之前运行。从这里调用 pytest.exit 可以在任何测试运行之前中止整个测试运行。如果测试使用 prod 配置(实际上是任何非测试配置)运行,我会使用它来中止测试 (2认同)

use*_*674 5

这是我一段时间后想到的另一个答案:

首先,我添加了一个新的例外:

class StopTests(Exception):
"""
Raise this exception in a test to stop the test run.

"""
    pass
Run Code Online (Sandbox Code Playgroud)

然后我assert在我的孩子测试类中添加了一个新的:

def assertStopTestsIfFalse(self, statement, reason=''):
    try:
        assert statement            
    except AssertionError:
        result.addFailure(self, sys.exc_info())
Run Code Online (Sandbox Code Playgroud)

最后我覆盖了该run函数以将其包含在testMethod()调用的正下方:

except StopTests:
    result.addFailure(self, sys.exc_info())
    result.stop()
Run Code Online (Sandbox Code Playgroud)

我更喜欢这个,因为现在任何测试都可以停止所有测试,并且没有特定于 cpython 的代码。

  • StopTests 在哪里提出? (2认同)