Using `@unittest.skipIf` with older versions of Python
Asked Answered
D

3

13

With the unittest module, I like the feature to skip tests, but it is only available in Python 2.7+.

For example, consider 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()

If I try to run a test with an earlier version of Python, I get an error:

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'

Is there a way to "trick" older versions of Python to ignore the unittest decorator, and to skip the test?

Daryl answered 12/6, 2012 at 5:54 Comment(0)
A
6

unittest2 is a backport of the new features added to the unittest testing framework in Python 2.7. It is tested to run on Python 2.4 - 2.7.

To use unittest2 instead of unittest simply replace import unittest with import unittest2

Ref: http://pypi.python.org/pypi/unittest2

Ageratum answered 12/6, 2012 at 6:9 Comment(1)
unittest2 wasn't satisfactory on my end, although it worked, it spits out a deprecation warning like: DeprecationWarning: Use of a TestResult without an addSkip method is deprecated self._addSkip(result, skip_why) I was unable to get it to disappear quickly.Findley
B
5

In general I would recommend not using unittest because it has not really a pythonic API.

A good framework for testing in Python is nose. You can skip tests by raising a SkipTest exception, for example:

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

This works for Python 2.3+

There are a lot more features in nose:

  • You do not need classes. A function could be a test, too.
  • Decorator for fixtures (setup, teardown functions).
  • Module level fixtures.
  • Decorator for expecting an Exception.
  • ...
Basilius answered 12/6, 2012 at 8:2 Comment(0)
A
2

How about using if statement?

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)
Amble answered 12/6, 2012 at 6:2 Comment(1)
Solutions integrated with unittest or nose will alert the user that a test was skipped. E.g., Ran 14 tests in 1.325s. OK (SKIP=1). The print statement may not satisfy many situations. For example, when using nosetests, you'd have to use the -s flag to see the print statement.Jazmin

© 2022 - 2024 — McMap. All rights reserved.