2017-05-08 21 views
2

如何在IPython中運行單個Python unittest並使用%debug來調查斷言失敗的網站?如何使用%debug來調查Python unittest失敗?

具體而言,我想這個魔法......

$ ipython 
In [1]: def broken(): 
    ...:  DOESNOTEXIST 
    ...:  

In [2]: broken() 
--------------------------------------------------------------------------- 
NameError         Traceback (most recent call last) 
<ipython-input-2-38dbcef999e4> in <module>() 
----> 1 broken() 

<ipython-input-1-42074db4a06b> in broken() 
     1 def broken(): 
----> 2  DOESNOTEXIST 
     3 

NameError: name 'DOESNOTEXIST' is not defined 

In [3]: %debug 
> <ipython-input-1-42074db4a06b>(2)broken() 
     1 def broken(): 
----> 2  DOESNOTEXIST 
     3 

ipdb> # Rock on 

...可踢了單元測試時...

In [4]: %run -m unittest some/path/to/brokenness.py 

...其中,失敗,運行%debug將採取我到了raise那個測試用例失敗了。

似乎unittest模塊吞下異常(如人們所期望的)並且--failfast標誌不會使它們咳嗽。我知道我可以實例化測試對象,然後手動調用setUp()等。但是,這看起來溫和愚蠢和痛苦。我不想設置斷點。

+0

我會高興地還需要在哪裏可以得到的只有失敗投進IPython的解決方案。實際上更幸福的是 –

+0

。如果簡單地從CLI運行,並且在觸發斷言上獲得對IPython友好的調試器,將會很好。 –

+0

你可以用'nose'在ipython中運行測試。 – pylang

回答

1

使用的TestRunner

我建議你用pytest-IPDB插件安裝pytest。您應該能夠以類似的方式使用--ipdb標誌運行它,以便在測試中發生異常時進入ipdb調試器。

pip install git+git://github.com/mverteuil/pytest-ipdb.git 

然後

In [1]: %run -m pytest --ipdb some/path/to/brokenness.py 

,或者在命令行:

py.test --ipdb some/path/to/brokenness.py 

另外,如果你不喜歡pytest出於某種原因,相同的結果,可以用鼻子和存檔nose-ipdb插件。

1

看看跑步nose。這可以通過ipython或jupyter筆記本中的命令行單獨運行。

> pip install nose 

在包含測試文件包目錄,運行:

> nosetests --pdb 

這會自動尋找測試模塊在所有當前和子目錄前置test_。另外,您也可以在單獨的文件中運行它:

> nosetests test_filename.py --pdb 

有一個plugin使用ipdb爲好。

nose對於在ipython/jupyter會話中運行測試特別有用。因此,你必須不進行單獨的文件運行會話中的測試選項:

import nose.tools as nt 

def test(): 
    # Some test code 
    return 1 

nt.assert_equal(test(), 2) 

輸出

--------------------------------------------------------------------------- 
AssertionError       Traceback (most recent call last) 
<ipython-input-16-edbfc78f9c45> in <module>() 
     5  return 1 
     6 
----> 7 nt.assert_equal(test(), 2) 

C:\Anaconda3\envs\betalab\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\envs\betalab\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

從鼻子文件中可以看出:「過去幾年鼻子一直處於維護模式,如果沒有新人/團隊接管維護者,可能會停止。新項目應該考慮使用Nose2,py.test或者普通單元測試/ unittest2 「。 –

+0

它對單元測試很好。如果你願意,你可以試試nose2。 'pytest'會是最好的,但它還不支持會話測試。 – pylang