2016-11-04 61 views
0

使用Python的unittest模塊,斷言我如何才能只顯示自定義錯誤消息Python的unittest模塊

self.assertTrue(a > b - 0.5 && a < b + 0.5, "The two values did not agree") 

輸出失敗如下:

AssertionError: False is not true : The two values did not agree 

我不想False is not true被打印。理想情況下,AssertionError也不應該打印。應該只打印The two values did not agree

我可以這樣做嗎?

回答

1

你可以禁止該False is true部分,但是,有一點要記住這裏,你是提高一個例外,你看到的是標準輸出斷言的Python中被提出。你想看到這個。此外,這是直接的斷言方法調用,你可以從下面的assertTrue看到:

def assertTrue(self, expr, msg=None): 
    """Check that the expression is true.""" 
    if not expr: 
     msg = self._formatMessage(msg, "%s is not true" % safe_repr(expr)) 
     raise self.failureException(msg) 

要剿了「假爲真」的一部分,改變longMessage類屬性設置爲false:

class TestCompare(unittest.TestCase): 

    longMessage = False 

    def test_thing(self): 
     self.assertTrue(5 == 6, "The two values did not agree") 

輸出:

Failure 
Traceback (most recent call last): 
    File "/Users/XXX/dev/rough/test_this.py", line 21, in test_things 
    self.assertTrue(5 == 6, "The two values did not agree") 
AssertionError: The two values did not agree 
+1

它的工作原理,感謝 – Tyler

+0

@Tyler沒問題。祝你好運。 – idjaw

相關問題