2016-11-18 28 views
1

我正在研究如何在Python中執行斷言自省,方法與that py.test does相同。例如...如何在Python中執行斷言自省

>>> a = 1 
>>> b = 2 
>>> assert a == b 
Traceback (most recent call last): 
File "<stdin>", line 1, in <module> 
AssertionError # <--- I want more information here, eg 'AssertionError: 1 != 2' 

我看到py.codehas some functionality around this和我也看到this answer指出,sys.excepthook讓你在想什麼異常行爲,堵塞,但它不是我清楚如何把它放在一起。

+0

爲什麼不'pytest'本身使用? – pylang

+0

@pylang我沒有問題重新使用py.test的部分允許這種情況發生,但我不能只使用py.test本身。爲了我的問題,我說你應該假設例如。我並沒有真正在這種情況下運行測試。 –

回答

1

,如果你想顯示詳細的錯誤信息

def assertion(a,b): 
    try: 
     assert a==b 
    except AssertionError as e: 
     e.args += ('some other', 'information',) 
     raise 

a=1 
b=2 
assertion(a,b) 

這個代碼將會給這個輸出可以做這樣的事情:

Traceback (most recent call last): 
    File "tp.py", line 11, in <module> 
    assertion(a,b) 
    File "tp.py", line 4, in assertion 
    assert a==b 
AssertionError: ('some other', 'information') 
+1

@Tom。這有幫助嗎? –

+0

不是特別的,不,但總是感激。這個答案在其他附加信息中增加了例外情況,但我感興趣的是比較本身的狀態。在這種情況下,這意味着包括a和b的值,並確定問題是他們不相等。 (但是通用方法還可以與其他運營商的價值) –

1

unittest斷言提供額外信息(可能不止你需要)。靈感來自Raymond Hettinger的talk。 這是一個部分答案,只給出了ab(輸出的最後一行)的值,而不是您在pytest中唯一尋找的額外內省。

import unittest 

class EqualTest(unittest.TestCase): 

    def testEqual(self, a, b): 
     self.assertEqual(a, b) 


a, b = 1, 2 
assert_ = EqualTest().testEqual 
assert_(a, b) 

輸出

--------------------------------------------------------------------------- 
AssertionError       Traceback (most recent call last) 
<ipython-input-4-851ce0f1f668> in <module>() 
     9 a, b = 1, 2 
    10 assert_ = EqualTest().testEqual 
---> 11 assert_(a, b) 

<ipython-input-4-851ce0f1f668> in testEqual(self, a, b) 
     4 
     5  def testEqual(self, a, b): 
----> 6   self.assertEqual(a, b) 
     7 
     8 

C:\Anaconda3\lib\unittest\case.py in assertEqual(self, first, second, msg) 
    818   """ 
    819   assertion_func = self._getAssertEqualityFunc(first, second) 
--> 820   assertion_func(first, second, msg=msg) 
    821 
    822  def assertNotEqual(self, first, second, msg=None): 

C:\Anaconda3\lib\unittest\case.py in _baseAssertEqual(self, first, second, msg) 
    811    standardMsg = '%s != %s' % _common_shorten_repr(first, second) 
    812    msg = self._formatMessage(msg, standardMsg) 
--> 813    raise self.failureException(msg) 
    814 
    815  def assertEqual(self, first, second, msg=None): 

AssertionError: 1 != 2 
+0

謝謝,壽在這種情況下,我特別是在自省'assert'語句本身感興趣。 –