|
| 1 | +import pytest |
| 2 | + |
| 3 | +from pybind11_tests import type_caster_pyobject_ptr as m |
| 4 | + |
| 5 | + |
| 6 | +def test_cast_from_pyobject_ptr(): |
| 7 | + assert m.cast_from_pyobject_ptr() == 6758 |
| 8 | + |
| 9 | + |
| 10 | +def test_cast_to_pyobject_ptr(): |
| 11 | + assert m.cast_to_pyobject_ptr(()) |
| 12 | + assert not m.cast_to_pyobject_ptr({}) |
| 13 | + |
| 14 | + |
| 15 | +def test_return_pyobject_ptr(): |
| 16 | + assert m.return_pyobject_ptr() == 2314 |
| 17 | + |
| 18 | + |
| 19 | +def test_pass_pyobject_ptr(): |
| 20 | + assert m.pass_pyobject_ptr(()) |
| 21 | + assert not m.pass_pyobject_ptr({}) |
| 22 | + |
| 23 | + |
| 24 | +@pytest.mark.parametrize( |
| 25 | + "call_callback", |
| 26 | + [ |
| 27 | + m.call_callback_with_object_return, |
| 28 | + m.call_callback_with_handle_return, |
| 29 | + m.call_callback_with_pyobject_ptr_return, |
| 30 | + ], |
| 31 | +) |
| 32 | +def test_call_callback_with_object_return(call_callback): |
| 33 | + def cb(mode): |
| 34 | + if mode == 0: |
| 35 | + return 10 |
| 36 | + if mode == 1: |
| 37 | + return "One" |
| 38 | + raise NotImplementedError(f"Unknown mode: {mode}") |
| 39 | + |
| 40 | + assert call_callback(cb, 0) == 10 |
| 41 | + assert call_callback(cb, 1) == "One" |
| 42 | + with pytest.raises(NotImplementedError, match="Unknown mode: 2"): |
| 43 | + call_callback(cb, 2) |
| 44 | + |
| 45 | + |
| 46 | +def test_call_callback_with_pyobject_ptr_arg(): |
| 47 | + def cb(obj): |
| 48 | + return isinstance(obj, tuple) |
| 49 | + |
| 50 | + assert m.call_callback_with_pyobject_ptr_arg(cb, ()) |
| 51 | + assert not m.call_callback_with_pyobject_ptr_arg(cb, {}) |
| 52 | + |
| 53 | + |
| 54 | +@pytest.mark.parametrize("set_error", [True, False]) |
| 55 | +def test_cast_to_python_nullptr(set_error): |
| 56 | + expected = { |
| 57 | + True: r"^Reflective of healthy error handling\.$", |
| 58 | + False: ( |
| 59 | + r"^Internal error: pybind11::error_already_set called " |
| 60 | + r"while Python error indicator not set\.$" |
| 61 | + ), |
| 62 | + }[set_error] |
| 63 | + with pytest.raises(RuntimeError, match=expected): |
| 64 | + m.cast_to_pyobject_ptr_nullptr(set_error) |
| 65 | + |
| 66 | + |
| 67 | +def test_cast_to_python_non_nullptr_with_error_set(): |
| 68 | + with pytest.raises(SystemError) as excinfo: |
| 69 | + m.cast_to_pyobject_ptr_non_nullptr_with_error_set() |
| 70 | + assert str(excinfo.value) == "src != nullptr but PyErr_Occurred()" |
| 71 | + assert str(excinfo.value.__cause__) == "Reflective of unhealthy error handling." |
0 commit comments