簡體   English   中英

如何從python unittest發出測試錯誤(不是失敗)的信號

[英]How do I signal test error (not failure) from 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)) ,但是感覺有點“棘手”。 我覺得應該有一個包括電池在內的方法,但是閱讀友好的手冊對我沒有任何建議。

TestCase類中的各個方面都有一個assertRaises() ,您想在其中確保要測試的代碼引發錯誤。

如果要引發錯誤並在此時放棄對該單元的測試(並繼續進行下一個單元測試),則只需引發未捕獲的異常即可; 單元測試模塊將捕獲它:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM