-
Notifications
You must be signed in to change notification settings - Fork 16
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add
lightning_utilities.test.warning.no_warning_call
(#55)
- Loading branch information
Showing
3 changed files
with
39 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |