|
| 1 | +import pytest |
| 2 | +import warnings |
| 3 | + |
| 4 | +from devito.warnings import warn, DevitoWarning |
| 5 | + |
| 6 | + |
| 7 | +class NewWarning(UserWarning): |
| 8 | + """ |
| 9 | + A custom warning class |
| 10 | + """ |
| 11 | + pass |
| 12 | + |
| 13 | + |
| 14 | +@pytest.fixture |
| 15 | +def custom_warning(): |
| 16 | + # Instance of custom warning class |
| 17 | + return NewWarning('** NEW ** A fun new kind of warning') |
| 18 | + |
| 19 | + |
| 20 | +class TestDevitoWarnings: |
| 21 | + """ |
| 22 | + In all cases check that the `DevitoWarning` type of Warning is raised |
| 23 | + __in all cases__, even if a custom type is provided |
| 24 | + """ |
| 25 | + def test_raise(self): |
| 26 | + with pytest.warns(DevitoWarning) as w: |
| 27 | + warn('Let this be a warning to you') |
| 28 | + |
| 29 | + assert len(w) == 1 |
| 30 | + assert 'DevitoWarning' in repr(w[0].message) |
| 31 | + assert w[0].filename == __file__ |
| 32 | + |
| 33 | + def test_raise_from_user(self): |
| 34 | + with pytest.warns(DevitoWarning) as w: |
| 35 | + warn('Let this be another warning to you', UserWarning) |
| 36 | + |
| 37 | + assert len(w) == 1 |
| 38 | + assert 'UserWarning:' in str(w[0].message) |
| 39 | + assert w[0].filename == __file__ |
| 40 | + |
| 41 | + def test_raise_from_user_kw(self): |
| 42 | + with pytest.warns(DevitoWarning) as w: |
| 43 | + warn('Let this be another warning to you', category=UserWarning) |
| 44 | + |
| 45 | + assert len(w) == 1 |
| 46 | + assert 'UserWarning:' in str(w[0].message) |
| 47 | + assert w[0].filename == __file__ |
| 48 | + |
| 49 | + def test_raise_from_custom(self, custom_warning): |
| 50 | + with pytest.warns(DevitoWarning) as w: |
| 51 | + warn(custom_warning) |
| 52 | + |
| 53 | + assert len(w) == 1 |
| 54 | + assert 'NewWarning:' in str(w[0].message) |
| 55 | + assert w[0].filename == __file__ |
| 56 | + |
| 57 | + |
| 58 | +class TestWarning: |
| 59 | + """ |
| 60 | + Check that the custom DevitoWarning does not interfere with Python warnings |
| 61 | + """ |
| 62 | + def test_raise(self): |
| 63 | + with pytest.warns(UserWarning): |
| 64 | + warnings.warn('Let this be a warning to you') |
| 65 | + |
| 66 | + def test_raise_devito(self): |
| 67 | + with pytest.warns(DevitoWarning): |
| 68 | + warnings.warn('Let this be another warning to you', DevitoWarning) |
| 69 | + |
| 70 | + def test_raise_devito_kw(self): |
| 71 | + with pytest.warns(DevitoWarning): |
| 72 | + warn('Let this be another warning to you', category=DevitoWarning) |
| 73 | + |
| 74 | + def test_raise_from_custom(self, custom_warning): |
| 75 | + with pytest.warns(NewWarning): |
| 76 | + warnings.warn(custom_warning) |
0 commit comments