【问题标题】:Using `@unittest.skipIf` with older versions of Python在旧版本的 Python 中使用 `@unittest.skipIf`
【发布时间】:2012-06-15 00:18:38
【问题描述】:

使用unittest 模块,我喜欢feature to skip tests,但它仅在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()

如果我尝试使用早期版本的 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 装饰器并跳过测试?

【问题讨论】:

    标签: python unit-testing decorator backport


    【解决方案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)
    

    【讨论】:

    • unittestnose 集成的解决方案将提醒用户跳过测试。例如,Ran 14 tests in 1.325s. OK (SKIP=1)。 print 语句可能无法满足很多情况。例如,当使用nosetests 时,您必须使用-s 标志才能看到打印语句。
    【解决方案2】:

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

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

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

    这适用于 Python 2.3+

    鼻子还有很多功能:

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

    【讨论】:

      【解决方案3】:

      unittest2 是 Python 2.7 中添加到 unittest 测试框架的新功能的反向移植。经测试可在 Python 2.4 - 2.7 上运行。

      要使用 unittest2 而不是 unittest 只需替换 导入单元测试 和 导入单元测试2

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

      【讨论】:

      • unittest2 对我来说并不令人满意,虽然它有效,但它会发出一个弃用警告,例如:DeprecationWarning: Use of a TestResult without an addSkip method is deprecated self._addSkip(result, skip_why) 我无法让它迅速消失。
      猜你喜欢
      • 2022-11-17
      • 2021-09-25
      • 2019-09-02
      • 1970-01-01
      • 2014-08-11
      • 2023-03-05
      • 2017-01-28
      • 2013-07-13
      • 1970-01-01
      相关资源
      最近更新 更多