Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

POC test for #2847 #3016

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions tests/pybind11_cross_module_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

#include "pybind11_tests.h"
#include "local_bindings.h"
#include "test_exceptions.h"
#include <pybind11/stl_bind.h>
#include <numeric>

Expand All @@ -30,6 +31,13 @@ PYBIND11_MODULE(pybind11_cross_module_tests, m) {
m.def("throw_pybind_value_error", []() { throw py::value_error("pybind11 value error"); });
m.def("throw_pybind_type_error", []() { throw py::type_error("pybind11 type error"); });
m.def("throw_stop_iteration", []() { throw py::stop_iteration(); });
py::register_exception_translator([](std::exception_ptr p) {
try {
if (p) std::rethrow_exception(p);
} catch (const tmp_e &e) {
PyErr_SetString(PyExc_KeyError, e.what());
}
});

// test_local_bindings.py
// Local to both:
Expand Down
2 changes: 2 additions & 0 deletions tests/test_exceptions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
BSD-style license that can be found in the LICENSE file.
*/

#include "test_exceptions.h"
#include "pybind11_tests.h"

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

m.def("throw_", []() { throw tmp_e(); });
}
12 changes: 12 additions & 0 deletions tests/test_exceptions.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#pragma once
#include "pybind11_tests.h"
#include <stdexcept>

// shared exceptions for cross_module_tests

class PYBIND11_EXPORT tmp_e : public pybind11::builtin_exception {
public:
using builtin_exception::builtin_exception;
explicit tmp_e() : tmp_e("") {}
void set_error() const override { PyErr_SetString(PyExc_RuntimeError, what()); }
};
3 changes: 3 additions & 0 deletions tests/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ def test_cross_module_exceptions():
with pytest.raises(StopIteration) as excinfo:
cm.throw_stop_iteration()

with pytest.raises(KeyError) as excinfo:
m.throw_()


def test_python_call_in_catch():
d = {}
Expand Down