2012-06-12 45 views
11

對於unittest模塊,我喜歡feature to skip tests,但它只適用於Python 2.7+。在舊版本的Python中使用`@ unittest.skipIf`

例如,考慮test.py

import unittest 
try: 
    import proprietary_module 
except ImportError: 
    proprietary_module = None 

class TestProprietary(unittest.TestCase): 
    @unittest.skipIf(proprietary_module is None, "requries proprietary module") 
    def test_something_proprietary(self): 
     self.assertTrue(proprietary_module is not None) 

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

如果我試圖與Python的早期版本運行測試,我得到一個錯誤:

Traceback (most recent call last): 
    File "test.py", line 7, in <module> 
    class TestProprietary(unittest.TestCase): 
    File "test.py", line 8, in TestProprietary 
    @unittest.skipIf(proprietary_module is None, "requries proprietary module") 
AttributeError: 'module' object has no attribute 'skipIf' 

是有辦法「帽子戲法「舊版本的Python忽略unittest裝飾器,並跳過測試?

回答

6

unittest2是在Python 2.7中添加到unittest測試框架中的新功能的回溯。它經過測試可以在Python 2.4 - 2.7上運行。

要使用unittest2,而不是簡單的單元測試與 進口替代進口 單元測試 unittest2

編號:http://pypi.python.org/pypi/unittest2

+0

unittest2在我的結尾並不令人滿意,雖然它工作正常,但它吐出了一個棄用警告,如: 'DeprecationWarning:不使用addSkip方法的TestResult的使用已被棄用 self._addSkip(result,skip_why)' 我無法讓它迅速消失。 –

1

如何使用if聲明?

if proprietary_module is None: 
    print "Skipping test since it requires proprietary module" 
else: 
    def test_something_proprietary(self): 
     self.assertTrue(proprietary_module is not None) 
+0

集成有'unittest'或'nose'的解決方案將提醒用戶測試已被跳過。例如,在1.325s內運行14次測試。 OK(SKIP = 1)'。打印聲明可能無法滿足許多情況。例如,使用'nosetests'時,你必須使用'-s'標誌來查看print語句。 – Aman

4

一般來說,我會建議不使用unittest因爲它不是一個真正的Python的API。

一個很好的Python測試框架是nose。您可以通過提高SkipTest例外跳過測試,例如:

if (sys.version_info < (2, 6, 0)): 
    from nose.plugins.skip import SkipTest 
    raise SkipTest 

這適用於Python 2.3+

有很多更多的功能在鼻子:

  • 你不需要類。功能也可以是測試。
  • 裝修裝修(安裝,拆卸功能)。
  • 模塊級別的燈具。
  • 期待異常的裝飾器。
  • ...