|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import warnings |
| 4 | + |
| 5 | +import pytest |
| 6 | + |
| 7 | +import pybind11_tests # noqa: F401 |
| 8 | +from pybind11_tests import warnings_ as m |
| 9 | + |
| 10 | + |
| 11 | +@pytest.mark.parametrize( |
| 12 | + ("expected_category", "expected_message", "expected_value", "module_function"), |
| 13 | + [ |
| 14 | + (Warning, "This is simple warning", 21, m.warn_and_return_value), |
| 15 | + (RuntimeWarning, "This is RuntimeWarning", None, m.warn_with_default_category), |
| 16 | + (FutureWarning, "This is FutureWarning", None, m.warn_with_different_category), |
| 17 | + ], |
| 18 | +) |
| 19 | +def test_warning_simple( |
| 20 | + expected_category, expected_message, expected_value, module_function |
| 21 | +): |
| 22 | + with pytest.warns(Warning) as excinfo: |
| 23 | + value = module_function() |
| 24 | + |
| 25 | + assert issubclass(excinfo[0].category, expected_category) |
| 26 | + assert str(excinfo[0].message) == expected_message |
| 27 | + assert value == expected_value |
| 28 | + |
| 29 | + |
| 30 | +def test_warning_wrong_subclass_fail(): |
| 31 | + with pytest.raises(Exception) as excinfo: |
| 32 | + m.warn_with_invalid_category() |
| 33 | + |
| 34 | + assert issubclass(excinfo.type, RuntimeError) |
| 35 | + assert ( |
| 36 | + str(excinfo.value) |
| 37 | + == "pybind11::warnings::warn(): cannot raise warning, category must be a subclass of PyExc_Warning!" |
| 38 | + ) |
| 39 | + |
| 40 | + |
| 41 | +def test_warning_double_register_fail(): |
| 42 | + with pytest.raises(Exception) as excinfo: |
| 43 | + m.register_duplicate_warning() |
| 44 | + |
| 45 | + assert issubclass(excinfo.type, RuntimeError) |
| 46 | + assert ( |
| 47 | + str(excinfo.value) |
| 48 | + == 'pybind11::warnings::new_warning_type(): an attribute with name "CustomWarning" exists already.' |
| 49 | + ) |
| 50 | + |
| 51 | + |
| 52 | +def test_warning_register(): |
| 53 | + assert m.CustomWarning is not None |
| 54 | + |
| 55 | + with pytest.warns(m.CustomWarning) as excinfo: |
| 56 | + warnings.warn("This is warning from Python!", m.CustomWarning, stacklevel=1) |
| 57 | + |
| 58 | + assert issubclass(excinfo[0].category, DeprecationWarning) |
| 59 | + assert str(excinfo[0].message) == "This is warning from Python!" |
| 60 | + |
| 61 | + |
| 62 | +def test_warning_custom(): |
| 63 | + with pytest.warns(m.CustomWarning) as excinfo: |
| 64 | + value = m.warn_with_custom_type() |
| 65 | + |
| 66 | + assert issubclass(excinfo[0].category, DeprecationWarning) |
| 67 | + assert str(excinfo[0].message) == "This is CustomWarning" |
| 68 | + assert value == 37 |
0 commit comments