debug.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. """
  2. This plugin provides ``--pdb`` and ``--pdb-failures`` options. The ``--pdb``
  3. option will drop the test runner into pdb when it encounters an error. To
  4. drop into pdb on failure, use ``--pdb-failures``.
  5. """
  6. import pdb
  7. from nose.plugins.base import Plugin
  8. class Pdb(Plugin):
  9. """
  10. Provides --pdb and --pdb-failures options that cause the test runner to
  11. drop into pdb if it encounters an error or failure, respectively.
  12. """
  13. enabled_for_errors = False
  14. enabled_for_failures = False
  15. score = 5 # run last, among builtins
  16. def options(self, parser, env):
  17. """Register commandline options.
  18. """
  19. parser.add_option(
  20. "--pdb", action="store_true", dest="debugBoth",
  21. default=env.get('NOSE_PDB', False),
  22. help="Drop into debugger on failures or errors")
  23. parser.add_option(
  24. "--pdb-failures", action="store_true",
  25. dest="debugFailures",
  26. default=env.get('NOSE_PDB_FAILURES', False),
  27. help="Drop into debugger on failures")
  28. parser.add_option(
  29. "--pdb-errors", action="store_true",
  30. dest="debugErrors",
  31. default=env.get('NOSE_PDB_ERRORS', False),
  32. help="Drop into debugger on errors")
  33. def configure(self, options, conf):
  34. """Configure which kinds of exceptions trigger plugin.
  35. """
  36. self.conf = conf
  37. self.enabled_for_errors = options.debugErrors or options.debugBoth
  38. self.enabled_for_failures = options.debugFailures or options.debugBoth
  39. self.enabled = self.enabled_for_failures or self.enabled_for_errors
  40. def addError(self, test, err):
  41. """Enter pdb if configured to debug errors.
  42. """
  43. if not self.enabled_for_errors:
  44. return
  45. self.debug(err)
  46. def addFailure(self, test, err):
  47. """Enter pdb if configured to debug failures.
  48. """
  49. if not self.enabled_for_failures:
  50. return
  51. self.debug(err)
  52. def debug(self, err):
  53. import sys # FIXME why is this import here?
  54. ec, ev, tb = err
  55. stdout = sys.stdout
  56. sys.stdout = sys.__stdout__
  57. try:
  58. pdb.post_mortem(tb)
  59. finally:
  60. sys.stdout = stdout