nose.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # -*- coding: utf-8 -*-
  2. """ run test suites written for nose. """
  3. from __future__ import absolute_import
  4. from __future__ import division
  5. from __future__ import print_function
  6. import sys
  7. import six
  8. import pytest
  9. from _pytest import python
  10. from _pytest import runner
  11. from _pytest import unittest
  12. from _pytest.config import hookimpl
  13. def get_skip_exceptions():
  14. skip_classes = set()
  15. for module_name in ("unittest", "unittest2", "nose"):
  16. mod = sys.modules.get(module_name)
  17. if hasattr(mod, "SkipTest"):
  18. skip_classes.add(mod.SkipTest)
  19. return tuple(skip_classes)
  20. def pytest_runtest_makereport(item, call):
  21. if call.excinfo and call.excinfo.errisinstance(get_skip_exceptions()):
  22. # let's substitute the excinfo with a pytest.skip one
  23. call2 = runner.CallInfo.from_call(
  24. lambda: pytest.skip(six.text_type(call.excinfo.value)), call.when
  25. )
  26. call.excinfo = call2.excinfo
  27. @hookimpl(trylast=True)
  28. def pytest_runtest_setup(item):
  29. if is_potential_nosetest(item):
  30. if not call_optional(item.obj, "setup"):
  31. # call module level setup if there is no object level one
  32. call_optional(item.parent.obj, "setup")
  33. # XXX this implies we only call teardown when setup worked
  34. item.session._setupstate.addfinalizer((lambda: teardown_nose(item)), item)
  35. def teardown_nose(item):
  36. if is_potential_nosetest(item):
  37. if not call_optional(item.obj, "teardown"):
  38. call_optional(item.parent.obj, "teardown")
  39. # if hasattr(item.parent, '_nosegensetup'):
  40. # #call_optional(item._nosegensetup, 'teardown')
  41. # del item.parent._nosegensetup
  42. def is_potential_nosetest(item):
  43. # extra check needed since we do not do nose style setup/teardown
  44. # on direct unittest style classes
  45. return isinstance(item, python.Function) and not isinstance(
  46. item, unittest.TestCaseFunction
  47. )
  48. def call_optional(obj, name):
  49. method = getattr(obj, name, None)
  50. isfixture = hasattr(method, "_pytestfixturefunction")
  51. if method is not None and not isfixture and callable(method):
  52. # If there's any problems allow the exception to raise rather than
  53. # silently ignoring them
  54. method()
  55. return True