如何使用unittest从测试或设置内部停止所有测试? [英] How to stop all tests from inside a test or setUp using unittest?

查看:450
本文介绍了如何使用unittest从测试或设置内部停止所有测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在扩展python 2.7 unittest框架以进行一些功能测试.我想做的一件事是阻止所有测试在测试内部和setUpClass()方法内部运行.有时,如果测试失败,则程序会被破坏,以致无法继续进行测试,因此我想停止运行测试.

I'm extending the python 2.7 unittest framework to do some function testing. One of the things I would like to do is to stop all the tests from running inside of a test, and inside of a setUpClass() method. Sometimes if a test fails, the program is so broken it is no longer of any use to keep testing, so I want to stop the tests from running.

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

I noticed that a TestResult has a shouldStop attribute, and a stop() method, but I'm not sure how to get access to that inside of a test.

有人有什么想法吗?有更好的方法吗?

Does anyone have any ideas? Is there a better way?

推荐答案

一段时间后,我想到了另一个答案:

Here's another answer I came up with after a while:

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

First, I added a new exception:

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

"""
    pass

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

then I added a new assert to my child test class:

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

最后我覆盖了run函数,将其包括在testMethod()调用下面:

and last I overrode the run function to include this right below the testMethod() call:

except StopTests:
    result.addFailure(self, sys.exc_info())
    result.stop()

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

I like this better since any test now has the ability to stop all the tests, and there is no cpython-specific code.

这篇关于如何使用unittest从测试或设置内部停止所有测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆