有了Python模块,我喜欢feature to skip tests,但它只在unittest 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()如果我尝试使用早期版本的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装饰器,并跳过测试?
发布于 2012-06-12 14:09:28
unittest2是Python2.7中添加到单元测试框架中的新功能的后端。它在Python2.4- 2.7上进行了测试。
要使用unittest2而不是unittest,只需用import unittest2替换import unittest
参考:http://pypi.python.org/pypi/unittest2
发布于 2012-06-12 16:02:44
一般来说,我建议不要使用unittest,因为它并没有真正的pythonic。
在Python语言中测试的一个很好的框架是nose。您可以通过引发SkipTest异常来跳过测试,例如:
if (sys.version_info < (2, 6, 0)):
from nose.plugins.skip import SkipTest
raise SkipTest这适用于Python 2.3+
nose中有更多的特性:
的setup,teardown functions).
发布于 2012-06-12 14:02:33
使用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)https://stackoverflow.com/questions/10991198
复制相似问题