compat.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import sys
  2. class WarningMessage(object):
  3. """Holds the result of a single showwarning() call."""
  4. _WARNING_DETAILS = ("message", "category", "filename", "lineno", "file",
  5. "line")
  6. def __init__(self, message, category, filename, lineno, file=None,
  7. line=None):
  8. local_values = locals()
  9. for attr in self._WARNING_DETAILS:
  10. setattr(self, attr, local_values[attr])
  11. self._category_name = category and category.__name__ or None
  12. def __str__(self):
  13. return ("{message : %r, category : %r, filename : %r, lineno : %s, "
  14. "line : %r}" % (self.message, self._category_name,
  15. self.filename, self.lineno, self.line))
  16. class catch_warnings(object):
  17. """A context manager that copies and restores the warnings filter upon
  18. exiting the context.
  19. The 'record' argument specifies whether warnings should be captured by a
  20. custom implementation of warnings.showwarning() and be appended to a list
  21. returned by the context manager. Otherwise None is returned by the context
  22. manager. The objects appended to the list are arguments whose attributes
  23. mirror the arguments to showwarning().
  24. The 'module' argument is to specify an alternative module to the module
  25. named 'warnings' and imported under that name. This argument is only
  26. useful when testing the warnings module itself.
  27. """
  28. def __init__(self, record=False, module=None):
  29. """Specify whether to record warnings and if an alternative module
  30. should be used other than sys.modules['warnings'].
  31. For compatibility with Python 3.0, please consider all arguments to be
  32. keyword-only.
  33. """
  34. self._record = record
  35. self._module = module is None and sys.modules["warnings"] or module
  36. self._entered = False
  37. def __repr__(self):
  38. args = []
  39. if self._record:
  40. args.append("record=True")
  41. if self._module is not sys.modules['warnings']:
  42. args.append("module=%r" % self._module)
  43. name = type(self).__name__
  44. return "%s(%s)" % (name, ", ".join(args))
  45. def __enter__(self):
  46. if self._entered:
  47. raise RuntimeError("Cannot enter %r twice" % self)
  48. self._entered = True
  49. self._filters = self._module.filters
  50. self._module.filters = self._filters[:]
  51. self._showwarning = self._module.showwarning
  52. if self._record:
  53. log = []
  54. def showwarning(*args, **kwargs):
  55. log.append(WarningMessage(*args, **kwargs))
  56. self._module.showwarning = showwarning
  57. return log
  58. else:
  59. return None
  60. def __exit__(self, *exc_info):
  61. if not self._entered:
  62. raise RuntimeError("Cannot exit %r without entering first" % self)
  63. self._module.filters = self._filters
  64. self._module.showwarning = self._showwarning