Blame external/pybind11/tests/test_exceptions.cpp

Packit 534379
/*
Packit 534379
    tests/test_custom-exceptions.cpp -- exception translation
Packit 534379
Packit 534379
    Copyright (c) 2016 Pim Schellart <P.Schellart@princeton.edu>
Packit 534379
Packit 534379
    All rights reserved. Use of this source code is governed by a
Packit 534379
    BSD-style license that can be found in the LICENSE file.
Packit 534379
*/
Packit 534379
Packit 534379
#include "pybind11_tests.h"
Packit 534379
Packit 534379
// A type that should be raised as an exception in Python
Packit 534379
class MyException : public std::exception {
Packit 534379
public:
Packit 534379
    explicit MyException(const char * m) : message{m} {}
Packit 534379
    virtual const char * what() const noexcept override {return message.c_str();}
Packit 534379
private:
Packit 534379
    std::string message = "";
Packit 534379
};
Packit 534379
Packit 534379
// A type that should be translated to a standard Python exception
Packit 534379
class MyException2 : public std::exception {
Packit 534379
public:
Packit 534379
    explicit MyException2(const char * m) : message{m} {}
Packit 534379
    virtual const char * what() const noexcept override {return message.c_str();}
Packit 534379
private:
Packit 534379
    std::string message = "";
Packit 534379
};
Packit 534379
Packit 534379
// A type that is not derived from std::exception (and is thus unknown)
Packit 534379
class MyException3 {
Packit 534379
public:
Packit 534379
    explicit MyException3(const char * m) : message{m} {}
Packit 534379
    virtual const char * what() const noexcept {return message.c_str();}
Packit 534379
private:
Packit 534379
    std::string message = "";
Packit 534379
};
Packit 534379
Packit 534379
// A type that should be translated to MyException
Packit 534379
// and delegated to its exception translator
Packit 534379
class MyException4 : public std::exception {
Packit 534379
public:
Packit 534379
    explicit MyException4(const char * m) : message{m} {}
Packit 534379
    virtual const char * what() const noexcept override {return message.c_str();}
Packit 534379
private:
Packit 534379
    std::string message = "";
Packit 534379
};
Packit 534379
Packit 534379
Packit 534379
// Like the above, but declared via the helper function
Packit 534379
class MyException5 : public std::logic_error {
Packit 534379
public:
Packit 534379
    explicit MyException5(const std::string &what) : std::logic_error(what) {}
Packit 534379
};
Packit 534379
Packit 534379
// Inherits from MyException5
Packit 534379
class MyException5_1 : public MyException5 {
Packit 534379
    using MyException5::MyException5;
Packit 534379
};
Packit 534379
Packit 534379
struct PythonCallInDestructor {
Packit 534379
    PythonCallInDestructor(const py::dict &d) : d(d) {}
Packit 534379
    ~PythonCallInDestructor() { d["good"] = true; }
Packit 534379
Packit 534379
    py::dict d;
Packit 534379
};
Packit 534379
Packit 534379
TEST_SUBMODULE(exceptions, m) {
Packit 534379
    m.def("throw_std_exception", []() {
Packit 534379
        throw std::runtime_error("This exception was intentionally thrown.");
Packit 534379
    });
Packit 534379
Packit 534379
    // make a new custom exception and use it as a translation target
Packit 534379
    static py::exception<MyException> ex(m, "MyException");
Packit 534379
    py::register_exception_translator([](std::exception_ptr p) {
Packit 534379
        try {
Packit 534379
            if (p) std::rethrow_exception(p);
Packit 534379
        } catch (const MyException &e) {
Packit 534379
            // Set MyException as the active python error
Packit 534379
            ex(e.what());
Packit 534379
        }
Packit 534379
    });
Packit 534379
Packit 534379
    // register new translator for MyException2
Packit 534379
    // no need to store anything here because this type will
Packit 534379
    // never by visible from Python
Packit 534379
    py::register_exception_translator([](std::exception_ptr p) {
Packit 534379
        try {
Packit 534379
            if (p) std::rethrow_exception(p);
Packit 534379
        } catch (const MyException2 &e) {
Packit 534379
            // Translate this exception to a standard RuntimeError
Packit 534379
            PyErr_SetString(PyExc_RuntimeError, e.what());
Packit 534379
        }
Packit 534379
    });
Packit 534379
Packit 534379
    // register new translator for MyException4
Packit 534379
    // which will catch it and delegate to the previously registered
Packit 534379
    // translator for MyException by throwing a new exception
Packit 534379
    py::register_exception_translator([](std::exception_ptr p) {
Packit 534379
        try {
Packit 534379
            if (p) std::rethrow_exception(p);
Packit 534379
        } catch (const MyException4 &e) {
Packit 534379
            throw MyException(e.what());
Packit 534379
        }
Packit 534379
    });
Packit 534379
Packit 534379
    // A simple exception translation:
Packit 534379
    auto ex5 = py::register_exception<MyException5>(m, "MyException5");
Packit 534379
    // A slightly more complicated one that declares MyException5_1 as a subclass of MyException5
Packit 534379
    py::register_exception<MyException5_1>(m, "MyException5_1", ex5.ptr());
Packit 534379
Packit 534379
    m.def("throws1", []() { throw MyException("this error should go to a custom type"); });
Packit 534379
    m.def("throws2", []() { throw MyException2("this error should go to a standard Python exception"); });
Packit 534379
    m.def("throws3", []() { throw MyException3("this error cannot be translated"); });
Packit 534379
    m.def("throws4", []() { throw MyException4("this error is rethrown"); });
Packit 534379
    m.def("throws5", []() { throw MyException5("this is a helper-defined translated exception"); });
Packit 534379
    m.def("throws5_1", []() { throw MyException5_1("MyException5 subclass"); });
Packit 534379
    m.def("throws_logic_error", []() { throw std::logic_error("this error should fall through to the standard handler"); });
Packit 534379
    m.def("exception_matches", []() {
Packit 534379
        py::dict foo;
Packit 534379
        try {
Packit 534379
            // Assign to a py::object to force read access of nonexistent dict entry
Packit 534379
            py::object o = foo["bar"];
Packit 534379
        }
Packit 534379
        catch (py::error_already_set& ex) {
Packit 534379
            if (!ex.matches(PyExc_KeyError)) throw;
Packit 534379
            return true;
Packit 534379
        }
Packit 534379
        return false;
Packit 534379
    });
Packit 534379
    m.def("exception_matches_base", []() {
Packit 534379
        py::dict foo;
Packit 534379
        try {
Packit 534379
            // Assign to a py::object to force read access of nonexistent dict entry
Packit 534379
            py::object o = foo["bar"];
Packit 534379
        }
Packit 534379
        catch (py::error_already_set &ex) {
Packit 534379
            if (!ex.matches(PyExc_Exception)) throw;
Packit 534379
            return true;
Packit 534379
        }
Packit 534379
        return false;
Packit 534379
    });
Packit 534379
    m.def("modulenotfound_exception_matches_base", []() {
Packit 534379
        try {
Packit 534379
            // On Python >= 3.6, this raises a ModuleNotFoundError, a subclass of ImportError
Packit 534379
            py::module::import("nonexistent");
Packit 534379
        }
Packit 534379
        catch (py::error_already_set &ex) {
Packit 534379
            if (!ex.matches(PyExc_ImportError)) throw;
Packit 534379
            return true;
Packit 534379
        }
Packit 534379
        return false;
Packit 534379
    });
Packit 534379
Packit 534379
    m.def("throw_already_set", [](bool err) {
Packit 534379
        if (err)
Packit 534379
            PyErr_SetString(PyExc_ValueError, "foo");
Packit 534379
        try {
Packit 534379
            throw py::error_already_set();
Packit 534379
        } catch (const std::runtime_error& e) {
Packit 534379
            if ((err && e.what() != std::string("ValueError: foo")) ||
Packit 534379
                (!err && e.what() != std::string("Unknown internal error occurred")))
Packit 534379
            {
Packit 534379
                PyErr_Clear();
Packit 534379
                throw std::runtime_error("error message mismatch");
Packit 534379
            }
Packit 534379
        }
Packit 534379
        PyErr_Clear();
Packit 534379
        if (err)
Packit 534379
            PyErr_SetString(PyExc_ValueError, "foo");
Packit 534379
        throw py::error_already_set();
Packit 534379
    });
Packit 534379
Packit 534379
    m.def("python_call_in_destructor", [](py::dict d) {
Packit 534379
        try {
Packit 534379
            PythonCallInDestructor set_dict_in_destructor(d);
Packit 534379
            PyErr_SetString(PyExc_ValueError, "foo");
Packit 534379
            throw py::error_already_set();
Packit 534379
        } catch (const py::error_already_set&) {
Packit 534379
            return true;
Packit 534379
        }
Packit 534379
        return false;
Packit 534379
    });
Packit 534379
Packit 534379
    // test_nested_throws
Packit 534379
    m.def("try_catch", [m](py::object exc_type, py::function f, py::args args) {
Packit 534379
        try { f(*args); }
Packit 534379
        catch (py::error_already_set &ex) {
Packit 534379
            if (ex.matches(exc_type))
Packit 534379
                py::print(ex.what());
Packit 534379
            else
Packit 534379
                throw;
Packit 534379
        }
Packit 534379
    });
Packit 534379
Packit 534379
}