2010-03-16 50 views
9

在IDLE中有沒有辦法直接運行PyUnit(unittest module)單元測試?使用IDLE運行Python PyUnit單元測試

我問,因爲我有一個簡短的測試模塊,當我從Cygwin shell中運行python mymodule.py時,所有測試都通過了,但是當我使用Run-> Run Module from IDLE時,測試通過,得到一個異常(SystemExit:False)。

例如,這裏是一個樣品的測試模塊來重現此:

#!/usr/bin/python 

import unittest 

class fooTests(unittest.TestCase): 

    def setUp(self): 
     self.foo = "bar" 

    def testDummyTest(self): 
     self.assertTrue(True) 

    def testDummyTestTwo(self): 
     self.assertEquals("foo", "foo") 


    def tearDown(self): 
     self.foo = None 

if __name__ == '__main__': 
    unittest.main() 

當運行此從Cygwin的外殼,蟒fooTests.py它產生:

$ python fooTests.py 
.. 
---------------------------------------------------------------------- 
Ran 2 tests in 0.000s 

OK 

但是,當我在IDLE中編輯fooTests.py並且我運行 - >運行模塊,由IDLE產生的新的Python Shell生成:

>>> ================================ RESTART ================================ 
>>> 
.. 
---------------------------------------------------------------------- 
Ran 2 tests in 0.031s 

OK 

Traceback (most recent call last): 
    File "C:\Some\path\info\I\shortened\fooTests.py", line 20, in <module> 
    unittest.main() 
    File "C:\Python26\lib\unittest.py", line 817, in __init__ 
    self.runTests() 
    File "C:\Python26\lib\unittest.py", line 865, in runTests 
    sys.exit(not result.wasSuccessful()) 
SystemExit: False 
>>> 

我在做什麼錯誤,產生這個回溯,尤其是如何修復它,以便我可以在IDLE內運行 - >運行模塊(或F5)來快速運行單元測試?

(這想必一定是一個簡單的問題,但我很快試圖弄清楚已被證明無果而終。)

回答

7

沒有人回答。(我發現,如果沒有在最初幾分鐘任何答案,答案的可能性顯着下降:),所以我一直在研究這個問題。

不知道這是最好的解決方法還是不行,但改變:

if __name__ == '__main__': 
    unittest.main() 

if __name__ == '__main__': 
    try: unittest.main() 
    except SystemExit: pass 

似乎這樣的伎倆。

我想問題是(根據http://coding.derkeiler.com/Archive/Python/comp.lang.python/2003-11/0239.html),unittest模塊通過調用sys.exit完成,這對於IDLE來說顯然是有問題的,因爲它希望保持Python shell運行,而從運行它時不是問題該命令行預計會將您轉儲回已經運行的命令行。

我不知道這個解決方案捕獲SystemExit事件並忽略它,根本就是有問題的,但它似乎適用於我檢查的所有測試通過和一些測試失敗的情況。

另請參見此StackOverFlow Post:What code can I use to check if Python is running in IDLE?,它提供了一個測試,以查看程序是否在IDLE內運行。

+0

try/except可能會使用返回碼,因此如果代碼在CI環境中進行測試,可能會造成麻煩。但是,這些信息非常方便:unitest模塊調用sys.exit,當交互式shell要保持打開狀態時(例如IDle,Emacs python shell等),將顯示此異常。 – 2011-05-24 15:20:20

1

像這樣的事情也應該工作:

suite = unittest.TestLoader().loadTestsFromTestCase(fooTests) 
unittest.TextTestRunner(verbosity=2).run(suite) 

我發現here,以及它爲我工作。

9

您還可以,如果你使用的是Python> = 2做

if __name__ == '__main__': 
    unittest.main(exit=False) 

。7