nose.py 2.5 KB

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