Skip to content

Commit

Permalink
Add lightning_utilities.test.warning.no_warning_call (#55)
Browse files Browse the repository at this point in the history
  • Loading branch information
carmocca authored Sep 23, 2022
1 parent 86e9e48 commit 88bd877
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 3 deletions.
3 changes: 0 additions & 3 deletions .github/workflows/check-package.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,6 @@ jobs:

- name: Check local package
run: |
pip install -q -U check-manifest
# check MANIFEST.in
check-manifest
# check package
python setup.py check --metadata --strict
Expand Down
14 changes: 14 additions & 0 deletions src/lightning_utilities/test/warning.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import re
import warnings
from contextlib import contextmanager
from typing import Generator, Optional, Type


@contextmanager
def no_warning_call(expected_warning: Type[Warning] = Warning, match: Optional[str] = None) -> Generator:
with warnings.catch_warnings(record=True) as record:
yield

for w in record:
if issubclass(w.category, expected_warning) and (match is None or re.compile(match).search(str(w.message))):
raise AssertionError(f"`{expected_warning.__name__}` was raised: {w.message!r}")
25 changes: 25 additions & 0 deletions tests/unittests/test/test_warnings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import warnings
from re import escape

import pytest

from lightning_utilities.test.warning import no_warning_call


def test_no_warning_call():
with no_warning_call():
...

with pytest.raises(AssertionError, match=escape("`Warning` was raised: UserWarning('foo')")):
with no_warning_call():
warnings.warn("foo")

with no_warning_call(DeprecationWarning):
warnings.warn("foo")

class MyDeprecationWarning(DeprecationWarning):
...

with pytest.raises(AssertionError, match=escape("`DeprecationWarning` was raised: MyDeprecationWarning('bar')")):
with pytest.warns(DeprecationWarning), no_warning_call(DeprecationWarning):
warnings.warn("bar", category=MyDeprecationWarning)

0 comments on commit 88bd877

Please sign in to comment.