将`@ unittest.skipIf`与旧版本的Python一起使用

Mik*_*e T 12 python unit-testing backport decorator

使用该unittest模块,我喜欢跳过测试功能,但它仅适用于Python 2.7+.

例如,考虑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()
Run Code Online (Sandbox Code Playgroud)

如果我尝试使用早期版本的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'
Run Code Online (Sandbox Code Playgroud)

有没有办法"欺骗"旧版本的Python来忽略unittest装饰器,并跳过测试?

小智 6

unittest2是Python 2.7中添加到unittest测试框架的新功能的后端.它经过测试可以在Python 2.4 - 2.7上运行.

要使用unittest2而不是unittest,只需使用import unittest2替换import unittest

参考:http://pypi.python.org/pypi/unittest2


sch*_*mar 5

一般来说,我建议不要使用,unittest因为它没有真正的 Pythonic API。

在 Python 中进行测试的一个很好的框架是nose. 您可以通过引发SkipTest异常来跳过测试,例如:

if (sys.version_info < (2, 6, 0)):
    from nose.plugins.skip import SkipTest
    raise SkipTest
Run Code Online (Sandbox Code Playgroud)

这适用于 Python 2.3+

鼻子还有很多特点:

  • 你不需要课程。一个函数也可以是一个测试。
  • 固定装置的装饰器(设置、拆卸功能)。
  • 模块级夹具。
  • 期待异常的装饰器。
  • ...