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
一般来说,我建议不要使用,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+
鼻子还有很多特点:
| 归档时间: |
|
| 查看次数: |
4287 次 |
| 最近记录: |