Skip to content

Commit b2ecbf0

Browse files
committed
POC test for #2847
1 parent f61855b commit b2ecbf0

File tree

4 files changed

+23
-0
lines changed

4 files changed

+23
-0
lines changed

tests/pybind11_cross_module_tests.cpp

+8
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
#include "pybind11_tests.h"
1111
#include "local_bindings.h"
12+
#include "test_exceptions.h"
1213
#include <pybind11/stl_bind.h>
1314
#include <numeric>
1415

@@ -30,6 +31,13 @@ PYBIND11_MODULE(pybind11_cross_module_tests, m) {
3031
m.def("throw_pybind_value_error", []() { throw py::value_error("pybind11 value error"); });
3132
m.def("throw_pybind_type_error", []() { throw py::type_error("pybind11 type error"); });
3233
m.def("throw_stop_iteration", []() { throw py::stop_iteration(); });
34+
py::register_exception_translator([](std::exception_ptr p) {
35+
try {
36+
if (p) std::rethrow_exception(p);
37+
} catch (const tmp_e &_) {
38+
PyErr_SetString(PyExc_KeyError, "");
39+
}
40+
});
3341

3442
// test_local_bindings.py
3543
// Local to both:

tests/test_exceptions.cpp

+2
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
BSD-style license that can be found in the LICENSE file.
88
*/
99

10+
#include "test_exceptions.h"
1011
#include "pybind11_tests.h"
1112

1213
// A type that should be raised as an exception in Python
@@ -228,4 +229,5 @@ TEST_SUBMODULE(exceptions, m) {
228229
// Test repr that cannot be displayed
229230
m.def("simple_bool_passthrough", [](bool x) {return x;});
230231

232+
m.def("throw_", []() { throw tmp_e(); });
231233
}

tests/test_exceptions.h

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
#pragma once
2+
#include "pybind11_tests.h"
3+
#include <stdexcept>
4+
5+
// shared exceptions for cross_module_tests
6+
7+
class tmp_e : public std::runtime_error {
8+
public:
9+
explicit tmp_e() : std::runtime_error("") {}
10+
};

tests/test_exceptions.py

+3
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,9 @@ def test_cross_module_exceptions():
4343
with pytest.raises(StopIteration) as excinfo:
4444
cm.throw_stop_iteration()
4545

46+
with pytest.raises(KeyError) as excinfo:
47+
m.throw_()
48+
4649

4750
def test_python_call_in_catch():
4851
d = {}

0 commit comments

Comments
 (0)