如何从python unittest发出测试错误(不是失败)的信号

时间:2013-10-01 08:49:05

标签: python unit-testing testing python-unittest

我有一个带帮助方法assertContains(super, sub)的测试用例。 sub参数是测试用例的硬编码部分。如果它们格式不正确,我希望我的测试用例中止错误。

我该怎么做?我试过了

def assertContains(super, sub):
    if isinstance(super, foo): ...
    elif isinstance(super, bar): ...
    else: assert False, repr(sub)

但是,这会将测试变为失败而非错误。

我可以引发一些其他异常(例如ValueError),但我想明确声明我声明测试用例是错误的。我可以做ErrorInTest = ValueError然后raise ErrorInTest(repr(sub))之类的事情,但感觉有点'icky'。我觉得应该有一个电池包含这样做的方式,但阅读友好的手册并没有对我提出任何建议。

1 个答案:

答案 0 :(得分:1)

assertRaises()中的方面有TestCase,您希望在其中确保待测试代码引发错误。

如果你想提出错误并在此时中止测试该单位(并继续进行下一次单元测试),只需提出一个未捕获的异常;单元测试模块将捕获它:

raise NotImplementedError("malformed sub: %r" % (sub,))

除了直接引发错误以表明单元测试用例导致错误之外,我认为还没有任何其他API方面可用。

class PassingTest(unittest.TestCase):
  def runTest(self):
    self.assertTrue(True)

class FailingTest(unittest.TestCase):
  def runTest(self):
    self.assertTrue(False)

class ErrorTest(unittest.TestCase):
  def runTest(self):
    raise NotImplementedError("error")

class PassingTest2(unittest.TestCase):
  def runTest(self):
    self.assertTrue(True)

结果:

EF..
======================================================================
ERROR: runTest (__main__.ErrorTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "./t.py", line 15, in runTest
    raise NotImplementedError("error")
NotImplementedError: error

======================================================================
FAIL: runTest (__main__.FailingTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "./t.py", line 11, in runTest
    self.assertTrue(False)
AssertionError: False is not true

----------------------------------------------------------------------
Ran 4 tests in 0.002s

FAILED (failures=1, errors=1)
相关问题