_warnings.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. # From scikit-image: https://github.com/scikit-image/scikit-image/blob/c2f8c4ab123ebe5f7b827bc495625a32bb225c10/skimage/_shared/_warnings.py
  2. # Licensed under modified BSD license
  3. __all__ = ["all_warnings", "expected_warnings"]
  4. import inspect
  5. import os
  6. import re
  7. import sys
  8. import warnings
  9. from contextlib import contextmanager
  10. from unittest import mock
  11. @contextmanager
  12. def all_warnings():
  13. """
  14. Context for use in testing to ensure that all warnings are raised.
  15. Examples
  16. --------
  17. >>> import warnings
  18. >>> def foo():
  19. ... warnings.warn(RuntimeWarning("bar"))
  20. We raise the warning once, while the warning filter is set to "once".
  21. Hereafter, the warning is invisible, even with custom filters:
  22. >>> with warnings.catch_warnings():
  23. ... warnings.simplefilter('once')
  24. ... foo()
  25. We can now run ``foo()`` without a warning being raised:
  26. >>> from numpy.testing import assert_warns # doctest: +SKIP
  27. >>> foo() # doctest: +SKIP
  28. To catch the warning, we call in the help of ``all_warnings``:
  29. >>> with all_warnings(): # doctest: +SKIP
  30. ... assert_warns(RuntimeWarning, foo)
  31. """
  32. # Whenever a warning is triggered, Python adds a __warningregistry__
  33. # member to the *calling* module. The exercise here is to find
  34. # and eradicate all those breadcrumbs that were left lying around.
  35. #
  36. # We proceed by first searching all parent calling frames and explicitly
  37. # clearing their warning registries (necessary for the doctests above to
  38. # pass). Then, we search for all submodules of skimage and clear theirs
  39. # as well (necessary for the skimage test suite to pass).
  40. frame = inspect.currentframe()
  41. if frame:
  42. for f in inspect.getouterframes(frame):
  43. f[0].f_locals["__warningregistry__"] = {}
  44. del frame
  45. for _, mod in list(sys.modules.items()):
  46. try:
  47. mod.__warningregistry__.clear()
  48. except AttributeError:
  49. pass
  50. with warnings.catch_warnings(record=True) as w, mock.patch.dict(
  51. os.environ, {"TRAITLETS_ALL_DEPRECATIONS": "1"}
  52. ):
  53. warnings.simplefilter("always")
  54. yield w
  55. @contextmanager
  56. def expected_warnings(matching):
  57. r"""Context for use in testing to catch known warnings matching regexes
  58. Parameters
  59. ----------
  60. matching : list of strings or compiled regexes
  61. Regexes for the desired warning to catch
  62. Examples
  63. --------
  64. >>> from skimage import data, img_as_ubyte, img_as_float # doctest: +SKIP
  65. >>> with expected_warnings(["precision loss"]): # doctest: +SKIP
  66. ... d = img_as_ubyte(img_as_float(data.coins())) # doctest: +SKIP
  67. Notes
  68. -----
  69. Uses `all_warnings` to ensure all warnings are raised.
  70. Upon exiting, it checks the recorded warnings for the desired matching
  71. pattern(s).
  72. Raises a ValueError if any match was not found or an unexpected
  73. warning was raised.
  74. Allows for three types of behaviors: "and", "or", and "optional" matches.
  75. This is done to accommodate different build environments or loop conditions
  76. that may produce different warnings. The behaviors can be combined.
  77. If you pass multiple patterns, you get an orderless "and", where all of the
  78. warnings must be raised.
  79. If you use the "|" operator in a pattern, you can catch one of several warnings.
  80. Finally, you can use "|\A\Z" in a pattern to signify it as optional.
  81. """
  82. with all_warnings() as w:
  83. # enter context
  84. yield w
  85. # exited user context, check the recorded warnings
  86. remaining = [m for m in matching if r"\A\Z" not in m.split("|")]
  87. for warn in w:
  88. found = False
  89. for match in matching:
  90. if re.search(match, str(warn.message)) is not None:
  91. found = True
  92. if match in remaining:
  93. remaining.remove(match)
  94. if not found:
  95. raise ValueError("Unexpected warning: %s" % str(warn.message))
  96. if len(remaining) > 0:
  97. msg = "No warning raised matching:\n%s" % "\n".join(remaining)
  98. raise ValueError(msg)