首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在旧版本的`@unittest.skipIf`中使用Python

在旧版本的`@unittest.skipIf`中使用Python
EN

Stack Overflow用户
提问于 2012-06-12 13:54:55
回答 3查看 4.7K关注 0票数 13

有了Python模块,我喜欢feature to skip tests,但它只在unittest 2.7+中可用。

例如,考虑test.py

代码语言:javascript
复制
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运行测试,则会得到一个错误:

代码语言:javascript
复制
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装饰器,并跳过测试?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 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

票数 6
EN

Stack Overflow用户

发布于 2012-06-12 16:02:44

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

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

代码语言:javascript
复制
if (sys.version_info < (2, 6, 0)):
    from nose.plugins.skip import SkipTest
    raise SkipTest

这适用于Python 2.3+

nose中有更多的特性:

  • 你不需要类。函数也可以是一个测试。用于灯具的
  • 装饰器(用于预期Exception.
  • ...

的setup,teardown functions).

  • Module level fixtures.

  • Decorator
票数 5
EN

Stack Overflow用户

发布于 2012-06-12 14:02:33

使用if语句怎么样?

代码语言:javascript
复制
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)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10991198

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档