warning.py 1.0 KB

12345678910111213141516171819202122232425262728
  1. # Licensed under the Apache License, Version 2.0 (the "License");
  2. # http://www.apache.org/licenses/LICENSE-2.0
  3. #
  4. import re
  5. import warnings
  6. from collections.abc import Generator
  7. from contextlib import contextmanager
  8. from typing import Optional
  9. @contextmanager
  10. def no_warning_call(expected_warning: type[Warning] = Warning, match: Optional[str] = None) -> Generator:
  11. """Assert that no matching warning is emitted within the context.
  12. Args:
  13. expected_warning: The warning class (or subclass) to check for.
  14. match: Optional regular expression to match against the warning message.
  15. Raises:
  16. AssertionError: If a warning of the given type (and matching the regex, if provided) is captured.
  17. """
  18. with warnings.catch_warnings(record=True) as record:
  19. yield
  20. for w in record:
  21. if issubclass(w.category, expected_warning) and (match is None or re.compile(match).search(str(w.message))):
  22. raise AssertionError(f"`{expected_warning.__name__}` was raised: {w.message!r}")