简体   繁体   English

在Python中将单元测试用例强制为ERROR

[英]Force a unit test case to ERROR in Python

I went through the Unit Test Case module of python and found that there is way to force a test case to fail using the TestCase.fail() object. 我遍历了python的单元测试用例模块,发现使用TestCase.fail()对象可以强制测试用例失败。 However I did not find anything that would force a test case to error. 但是我没有发现任何会导致测试用例出错的东西。 Any ideas on how this could be done? 关于如何做到这一点的任何想法?

EDIT: 编辑:

More explaination 更多说明

There are few test scripts which were written long ago and which I'm using right now for testing a firmware. 很少有测试脚本,它们是很久以前编写的,而我现在正在使用它们来测试固件。 These test scripts use the UnitTest module of python. 这些测试脚本使用python的UnitTest模块。 The test scripts also import a bunch of other user-written modules. 测试脚本还导入了许多其他用户编写的模块。 All these user written modules throw few exceptions. 所有这些用户编写的模块都不会抛出异常。 So whenever a test case doesn't call methods from user-written modules with correct inputs exception are thrown. 因此,只要测试用例不调用带有正确输入异常的用户编写模块中的方法,就会抛出异常。 the UnitTest module rightly flags all such test cases as errors. UnitTest模块正确地将所有此类测试用例标记为错误。 But by looking at the output of UnitTest module, which is just a Traceback to the line where exception was generated, it is not immediately clear to me because of which input the exception was generated. 但是通过查看UnitTest模块的输出(这只是对生成异常的行的回溯),我无法立即弄清楚,因为生成了异常的输入。 So I used try-except construct in the test scripts to catch the exceptions and print out the input which was the reason for exception. 因此,我在测试脚本中使用了try-except构造来捕获异常并打印出输入,这就是产生异常的原因。 But since I handled the exceptions UnitTest was flagging these test cases as pass. 但是,由于我处理了异常,因此UnitTest将这些测试用例标记为通过。 Using the raise statement in the except block, as pointed out by @alecxe, solved this issue. @alecxe指出,在except块中使用raise语句可以解决此问题。

只需使用raise引发异常:

raise Exception('Manually raised exception')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM