utils.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. # -*- coding: utf-8 -*-
  2. from unittest import TestCase
  3. from functools import wraps
  4. from nose.plugins.skip import SkipTest
  5. from nltk.util import py26
  6. def skip(reason):
  7. """
  8. Unconditionally skip a test.
  9. """
  10. def decorator(test_item):
  11. is_test_class = isinstance(test_item, type) and issubclass(test_item, TestCase)
  12. if is_test_class and py26():
  13. # Patch all test_ methods to raise SkipText exception.
  14. # This is necessary for Python 2.6 because its unittest
  15. # doesn't understand __unittest_skip__.
  16. for meth_name in (m for m in dir(test_item) if m.startswith('test_')):
  17. patched_method = skip(reason)(getattr(test_item, meth_name))
  18. setattr(test_item, meth_name, patched_method)
  19. if not is_test_class:
  20. @wraps(test_item)
  21. def skip_wrapper(*args, **kwargs):
  22. raise SkipTest(reason)
  23. skip_wrapper.__name__ = test_item.__name__
  24. test_item = skip_wrapper
  25. test_item.__unittest_skip__ = True
  26. test_item.__unittest_skip_why__ = reason
  27. return test_item
  28. return decorator
  29. def skipIf(condition, reason):
  30. """
  31. Skip a test if the condition is true.
  32. """
  33. if condition:
  34. return skip(reason)
  35. return lambda obj: obj