2017-03-29 22:20:42 +00:00
|
|
|
#include <pybind11/embed.h>
|
2017-12-15 14:15:25 +00:00
|
|
|
|
|
|
|
#ifdef _MSC_VER
|
|
|
|
// Silence MSVC C++17 deprecation warning from Catch regarding std::uncaught_exceptions (up to catch
|
|
|
|
// 2.0.1; this should be fixed in the next catch release after 2.0.1).
|
|
|
|
# pragma warning(disable: 4996)
|
|
|
|
#endif
|
|
|
|
|
2017-03-23 16:27:32 +00:00
|
|
|
#include <catch.hpp>
|
|
|
|
|
2021-10-04 00:15:37 +00:00
|
|
|
#include <cstdlib>
|
2017-09-12 06:05:05 +00:00
|
|
|
#include <fstream>
|
|
|
|
#include <functional>
|
2021-06-22 16:11:54 +00:00
|
|
|
#include <thread>
|
|
|
|
#include <utility>
|
2017-06-20 21:50:51 +00:00
|
|
|
|
2017-03-23 16:27:32 +00:00
|
|
|
namespace py = pybind11;
|
|
|
|
using namespace py::literals;
|
|
|
|
|
|
|
|
class Widget {
|
|
|
|
public:
|
CodeHealth: Enabling clang-tidy google-explicit-constructor (#3250)
* Adding google-explicit-constructor to .clang-tidy
* clang-tidy explicit attr.h (all automatic)
* clang-tidy explicit cast.h (all automatic)
* clang-tidy detail/init.h (1 NOLINT)
* clang-tidy detail/type_caster_base.h (2 NOLINT)
* clang-tidy pybind11.h (7 NOLINT)
* clang-tidy detail/common.h (3 NOLINT)
* clang-tidy detail/descr.h (2 NOLINT)
* clang-tidy pytypes.h (23 NOLINT, only 1 explicit)
* clang-tidy eigen.h (7 NOLINT, 0 explicit)
* Adding 2 explicit in functional.h
* Adding 4 explicit in iostream.h
* clang-tidy numpy.h (1 NOLINT, 1 explicit)
* clang-tidy embed.h (0 NOLINT, 1 explicit)
* clang-tidy tests/local_bindings.h (0 NOLINT, 4 explicit)
* clang-tidy tests/pybind11_cross_module_tests.cpp (0 NOLINT, 1 explicit)
* clang-tidy tests/pybind11_tests.h (0 NOLINT, 2 explicit)
* clang-tidy tests/test_buffers.cpp (0 NOLINT, 2 explicit)
* clang-tidy tests/test_builtin_casters.cpp (0 NOLINT, 4 explicit)
* clang-tidy tests/test_class.cpp (0 NOLINT, 6 explicit)
* clang-tidy tests/test_copy_move.cpp (0 NOLINT, 7 explicit)
* clang-tidy tests/test_embed/external_module.cpp (0 NOLINT, 1 explicit)
* clang-tidy tests/test_embed/test_interpreter.cpp (0 NOLINT, 1 explicit)
* clang-tidy tests/object.h (0 NOLINT, 2 explicit)
* clang-tidy batch of fully automatic fixes.
* Workaround for MSVC 19.16.27045.0 C++17 Python 2 C++ syntax error.
2021-09-09 01:53:38 +00:00
|
|
|
explicit Widget(std::string message) : message(std::move(message)) {}
|
2017-03-23 16:27:32 +00:00
|
|
|
virtual ~Widget() = default;
|
|
|
|
|
|
|
|
std::string the_message() const { return message; }
|
|
|
|
virtual int the_answer() const = 0;
|
2021-08-26 21:12:54 +00:00
|
|
|
virtual std::string argv0() const = 0;
|
2017-03-23 16:27:32 +00:00
|
|
|
|
|
|
|
private:
|
|
|
|
std::string message;
|
|
|
|
};
|
|
|
|
|
|
|
|
class PyWidget final : public Widget {
|
|
|
|
using Widget::Widget;
|
|
|
|
|
2020-09-15 12:56:20 +00:00
|
|
|
int the_answer() const override { PYBIND11_OVERRIDE_PURE(int, Widget, the_answer); }
|
2021-08-26 21:12:54 +00:00
|
|
|
std::string argv0() const override { PYBIND11_OVERRIDE_PURE(std::string, Widget, argv0); }
|
2017-03-23 16:27:32 +00:00
|
|
|
};
|
|
|
|
|
2017-03-29 22:20:42 +00:00
|
|
|
PYBIND11_EMBEDDED_MODULE(widget_module, m) {
|
2017-03-23 16:27:32 +00:00
|
|
|
py::class_<Widget, PyWidget>(m, "Widget")
|
|
|
|
.def(py::init<std::string>())
|
|
|
|
.def_property_readonly("the_message", &Widget::the_message);
|
2017-04-20 21:40:56 +00:00
|
|
|
|
|
|
|
m.def("add", [](int i, int j) { return i + j; });
|
2017-03-29 22:20:42 +00:00
|
|
|
}
|
2017-03-23 16:27:32 +00:00
|
|
|
|
2017-03-29 22:20:42 +00:00
|
|
|
PYBIND11_EMBEDDED_MODULE(throw_exception, ) {
|
|
|
|
throw std::runtime_error("C++ Error");
|
2017-03-23 16:27:32 +00:00
|
|
|
}
|
|
|
|
|
2017-03-29 22:20:42 +00:00
|
|
|
PYBIND11_EMBEDDED_MODULE(throw_error_already_set, ) {
|
|
|
|
auto d = py::dict();
|
|
|
|
d["missing"].cast<py::object>();
|
2017-03-23 16:27:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
TEST_CASE("Pass classes and data between modules defined in C++ and Python") {
|
2020-10-03 17:38:03 +00:00
|
|
|
auto module_ = py::module_::import("test_interpreter");
|
|
|
|
REQUIRE(py::hasattr(module_, "DerivedWidget"));
|
2017-03-29 22:20:42 +00:00
|
|
|
|
2020-10-03 17:38:03 +00:00
|
|
|
auto locals = py::dict("hello"_a="Hello, World!", "x"_a=5, **module_.attr("__dict__"));
|
2017-03-29 22:20:42 +00:00
|
|
|
py::exec(R"(
|
|
|
|
widget = DerivedWidget("{} - {}".format(hello, x))
|
|
|
|
message = widget.the_message
|
|
|
|
)", py::globals(), locals);
|
|
|
|
REQUIRE(locals["message"].cast<std::string>() == "Hello, World! - 5");
|
|
|
|
|
2020-10-03 17:38:03 +00:00
|
|
|
auto py_widget = module_.attr("DerivedWidget")("The question");
|
2017-03-29 22:20:42 +00:00
|
|
|
auto message = py_widget.attr("the_message");
|
|
|
|
REQUIRE(message.cast<std::string>() == "The question");
|
2017-03-23 16:27:32 +00:00
|
|
|
|
2017-03-29 22:20:42 +00:00
|
|
|
const auto &cpp_widget = py_widget.cast<const Widget &>();
|
|
|
|
REQUIRE(cpp_widget.the_answer() == 42);
|
|
|
|
}
|
|
|
|
|
|
|
|
TEST_CASE("Import error handling") {
|
2020-10-03 17:38:03 +00:00
|
|
|
REQUIRE_NOTHROW(py::module_::import("widget_module"));
|
|
|
|
REQUIRE_THROWS_WITH(py::module_::import("throw_exception"),
|
2017-03-29 22:20:42 +00:00
|
|
|
"ImportError: C++ Error");
|
2021-08-24 00:30:01 +00:00
|
|
|
#if PY_VERSION_HEX >= 0x03030000
|
|
|
|
REQUIRE_THROWS_WITH(py::module_::import("throw_error_already_set"),
|
|
|
|
Catch::Contains("ImportError: initialization failed"));
|
|
|
|
|
|
|
|
auto locals = py::dict("is_keyerror"_a=false, "message"_a="not set");
|
|
|
|
py::exec(R"(
|
|
|
|
try:
|
|
|
|
import throw_error_already_set
|
|
|
|
except ImportError as e:
|
|
|
|
is_keyerror = type(e.__cause__) == KeyError
|
|
|
|
message = str(e.__cause__)
|
|
|
|
)", py::globals(), locals);
|
|
|
|
REQUIRE(locals["is_keyerror"].cast<bool>() == true);
|
|
|
|
REQUIRE(locals["message"].cast<std::string>() == "'missing'");
|
|
|
|
#else
|
2020-10-03 17:38:03 +00:00
|
|
|
REQUIRE_THROWS_WITH(py::module_::import("throw_error_already_set"),
|
2017-03-29 22:20:42 +00:00
|
|
|
Catch::Contains("ImportError: KeyError"));
|
2021-08-24 00:30:01 +00:00
|
|
|
#endif
|
2017-03-29 22:20:42 +00:00
|
|
|
}
|
2017-03-23 16:27:32 +00:00
|
|
|
|
2017-03-29 22:20:42 +00:00
|
|
|
TEST_CASE("There can be only one interpreter") {
|
|
|
|
static_assert(std::is_move_constructible<py::scoped_interpreter>::value, "");
|
|
|
|
static_assert(!std::is_move_assignable<py::scoped_interpreter>::value, "");
|
|
|
|
static_assert(!std::is_copy_constructible<py::scoped_interpreter>::value, "");
|
|
|
|
static_assert(!std::is_copy_assignable<py::scoped_interpreter>::value, "");
|
|
|
|
|
|
|
|
REQUIRE_THROWS_WITH(py::initialize_interpreter(), "The interpreter is already running");
|
|
|
|
REQUIRE_THROWS_WITH(py::scoped_interpreter(), "The interpreter is already running");
|
|
|
|
|
|
|
|
py::finalize_interpreter();
|
|
|
|
REQUIRE_NOTHROW(py::scoped_interpreter());
|
|
|
|
{
|
|
|
|
auto pyi1 = py::scoped_interpreter();
|
|
|
|
auto pyi2 = std::move(pyi1);
|
2017-03-23 16:27:32 +00:00
|
|
|
}
|
2017-03-29 22:20:42 +00:00
|
|
|
py::initialize_interpreter();
|
2017-03-23 16:27:32 +00:00
|
|
|
}
|
2017-04-20 21:40:56 +00:00
|
|
|
|
2017-06-07 15:35:39 +00:00
|
|
|
bool has_pybind11_internals_builtin() {
|
2017-04-20 21:40:56 +00:00
|
|
|
auto builtins = py::handle(PyEval_GetBuiltins());
|
|
|
|
return builtins.contains(PYBIND11_INTERNALS_ID);
|
|
|
|
};
|
|
|
|
|
2017-06-07 15:35:39 +00:00
|
|
|
bool has_pybind11_internals_static() {
|
2018-01-11 23:46:10 +00:00
|
|
|
auto **&ipp = py::detail::get_internals_pp();
|
2021-07-27 22:32:26 +00:00
|
|
|
return (ipp != nullptr) && (*ipp != nullptr);
|
2017-06-07 15:35:39 +00:00
|
|
|
}
|
|
|
|
|
2017-04-20 21:40:56 +00:00
|
|
|
TEST_CASE("Restart the interpreter") {
|
|
|
|
// Verify pre-restart state.
|
2020-10-03 17:38:03 +00:00
|
|
|
REQUIRE(py::module_::import("widget_module").attr("add")(1, 2).cast<int>() == 3);
|
2017-06-07 15:35:39 +00:00
|
|
|
REQUIRE(has_pybind11_internals_builtin());
|
|
|
|
REQUIRE(has_pybind11_internals_static());
|
2020-10-03 17:38:03 +00:00
|
|
|
REQUIRE(py::module_::import("external_module").attr("A")(123).attr("value").cast<int>() == 123);
|
2018-01-11 23:46:10 +00:00
|
|
|
|
|
|
|
// local and foreign module internals should point to the same internals:
|
|
|
|
REQUIRE(reinterpret_cast<uintptr_t>(*py::detail::get_internals_pp()) ==
|
2020-10-03 17:38:03 +00:00
|
|
|
py::module_::import("external_module").attr("internals_at")().cast<uintptr_t>());
|
2017-04-20 21:40:56 +00:00
|
|
|
|
|
|
|
// Restart the interpreter.
|
|
|
|
py::finalize_interpreter();
|
|
|
|
REQUIRE(Py_IsInitialized() == 0);
|
|
|
|
|
|
|
|
py::initialize_interpreter();
|
|
|
|
REQUIRE(Py_IsInitialized() == 1);
|
|
|
|
|
|
|
|
// Internals are deleted after a restart.
|
2017-06-07 15:35:39 +00:00
|
|
|
REQUIRE_FALSE(has_pybind11_internals_builtin());
|
|
|
|
REQUIRE_FALSE(has_pybind11_internals_static());
|
2017-04-20 21:40:56 +00:00
|
|
|
pybind11::detail::get_internals();
|
2017-06-07 15:35:39 +00:00
|
|
|
REQUIRE(has_pybind11_internals_builtin());
|
|
|
|
REQUIRE(has_pybind11_internals_static());
|
2018-01-11 23:46:10 +00:00
|
|
|
REQUIRE(reinterpret_cast<uintptr_t>(*py::detail::get_internals_pp()) ==
|
2020-10-03 17:38:03 +00:00
|
|
|
py::module_::import("external_module").attr("internals_at")().cast<uintptr_t>());
|
2017-06-07 15:35:39 +00:00
|
|
|
|
|
|
|
// Make sure that an interpreter with no get_internals() created until finalize still gets the
|
|
|
|
// internals destroyed
|
|
|
|
py::finalize_interpreter();
|
|
|
|
py::initialize_interpreter();
|
|
|
|
bool ran = false;
|
2020-10-03 17:38:03 +00:00
|
|
|
py::module_::import("__main__").attr("internals_destroy_test") =
|
2017-06-07 15:35:39 +00:00
|
|
|
py::capsule(&ran, [](void *ran) { py::detail::get_internals(); *static_cast<bool *>(ran) = true; });
|
|
|
|
REQUIRE_FALSE(has_pybind11_internals_builtin());
|
|
|
|
REQUIRE_FALSE(has_pybind11_internals_static());
|
|
|
|
REQUIRE_FALSE(ran);
|
|
|
|
py::finalize_interpreter();
|
|
|
|
REQUIRE(ran);
|
|
|
|
py::initialize_interpreter();
|
|
|
|
REQUIRE_FALSE(has_pybind11_internals_builtin());
|
|
|
|
REQUIRE_FALSE(has_pybind11_internals_static());
|
2017-04-20 21:40:56 +00:00
|
|
|
|
|
|
|
// C++ modules can be reloaded.
|
2020-10-03 17:38:03 +00:00
|
|
|
auto cpp_module = py::module_::import("widget_module");
|
2017-04-20 21:40:56 +00:00
|
|
|
REQUIRE(cpp_module.attr("add")(1, 2).cast<int>() == 3);
|
|
|
|
|
|
|
|
// C++ type information is reloaded and can be used in python modules.
|
2020-10-03 17:38:03 +00:00
|
|
|
auto py_module = py::module_::import("test_interpreter");
|
2017-04-20 21:40:56 +00:00
|
|
|
auto py_widget = py_module.attr("DerivedWidget")("Hello after restart");
|
|
|
|
REQUIRE(py_widget.attr("the_message").cast<std::string>() == "Hello after restart");
|
|
|
|
}
|
|
|
|
|
|
|
|
TEST_CASE("Subinterpreter") {
|
|
|
|
// Add tags to the modules in the main interpreter and test the basics.
|
2020-10-03 17:38:03 +00:00
|
|
|
py::module_::import("__main__").attr("main_tag") = "main interpreter";
|
2017-04-20 21:40:56 +00:00
|
|
|
{
|
2020-10-03 17:38:03 +00:00
|
|
|
auto m = py::module_::import("widget_module");
|
2017-04-20 21:40:56 +00:00
|
|
|
m.attr("extension_module_tag") = "added to module in main interpreter";
|
|
|
|
|
|
|
|
REQUIRE(m.attr("add")(1, 2).cast<int>() == 3);
|
|
|
|
}
|
2017-06-07 15:35:39 +00:00
|
|
|
REQUIRE(has_pybind11_internals_builtin());
|
|
|
|
REQUIRE(has_pybind11_internals_static());
|
2017-04-20 21:40:56 +00:00
|
|
|
|
|
|
|
/// Create and switch to a subinterpreter.
|
|
|
|
auto main_tstate = PyThreadState_Get();
|
|
|
|
auto sub_tstate = Py_NewInterpreter();
|
|
|
|
|
|
|
|
// Subinterpreters get their own copy of builtins. detail::get_internals() still
|
|
|
|
// works by returning from the static variable, i.e. all interpreters share a single
|
|
|
|
// global pybind11::internals;
|
2017-06-07 15:35:39 +00:00
|
|
|
REQUIRE_FALSE(has_pybind11_internals_builtin());
|
|
|
|
REQUIRE(has_pybind11_internals_static());
|
2017-04-20 21:40:56 +00:00
|
|
|
|
|
|
|
// Modules tags should be gone.
|
2020-10-03 17:38:03 +00:00
|
|
|
REQUIRE_FALSE(py::hasattr(py::module_::import("__main__"), "tag"));
|
2017-04-20 21:40:56 +00:00
|
|
|
{
|
2020-10-03 17:38:03 +00:00
|
|
|
auto m = py::module_::import("widget_module");
|
2017-04-20 21:40:56 +00:00
|
|
|
REQUIRE_FALSE(py::hasattr(m, "extension_module_tag"));
|
|
|
|
|
|
|
|
// Function bindings should still work.
|
|
|
|
REQUIRE(m.attr("add")(1, 2).cast<int>() == 3);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Restore main interpreter.
|
|
|
|
Py_EndInterpreter(sub_tstate);
|
|
|
|
PyThreadState_Swap(main_tstate);
|
|
|
|
|
2020-10-03 17:38:03 +00:00
|
|
|
REQUIRE(py::hasattr(py::module_::import("__main__"), "main_tag"));
|
|
|
|
REQUIRE(py::hasattr(py::module_::import("widget_module"), "extension_module_tag"));
|
2017-04-20 21:40:56 +00:00
|
|
|
}
|
2017-06-06 15:05:19 +00:00
|
|
|
|
|
|
|
TEST_CASE("Execution frame") {
|
|
|
|
// When the interpreter is embedded, there is no execution frame, but `py::exec`
|
|
|
|
// should still function by using reasonable globals: `__main__.__dict__`.
|
|
|
|
py::exec("var = dict(number=42)");
|
|
|
|
REQUIRE(py::globals()["var"]["number"].cast<int>() == 42);
|
|
|
|
}
|
2017-06-20 21:50:51 +00:00
|
|
|
|
|
|
|
TEST_CASE("Threads") {
|
|
|
|
// Restart interpreter to ensure threads are not initialized
|
|
|
|
py::finalize_interpreter();
|
|
|
|
py::initialize_interpreter();
|
|
|
|
REQUIRE_FALSE(has_pybind11_internals_static());
|
|
|
|
|
|
|
|
constexpr auto num_threads = 10;
|
|
|
|
auto locals = py::dict("count"_a=0);
|
|
|
|
|
|
|
|
{
|
|
|
|
py::gil_scoped_release gil_release{};
|
|
|
|
REQUIRE(has_pybind11_internals_static());
|
|
|
|
|
|
|
|
auto threads = std::vector<std::thread>();
|
|
|
|
for (auto i = 0; i < num_threads; ++i) {
|
|
|
|
threads.emplace_back([&]() {
|
|
|
|
py::gil_scoped_acquire gil{};
|
2017-06-24 19:00:18 +00:00
|
|
|
locals["count"] = locals["count"].cast<int>() + 1;
|
2017-06-20 21:50:51 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
for (auto &thread : threads) {
|
|
|
|
thread.join();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
REQUIRE(locals["count"].cast<int>() == num_threads);
|
|
|
|
}
|
2017-09-12 06:05:05 +00:00
|
|
|
|
|
|
|
// Scope exit utility https://stackoverflow.com/a/36644501/7255855
|
|
|
|
struct scope_exit {
|
|
|
|
std::function<void()> f_;
|
|
|
|
explicit scope_exit(std::function<void()> f) noexcept : f_(std::move(f)) {}
|
|
|
|
~scope_exit() { if (f_) f_(); }
|
|
|
|
};
|
|
|
|
|
|
|
|
TEST_CASE("Reload module from file") {
|
|
|
|
// Disable generation of cached bytecode (.pyc files) for this test, otherwise
|
|
|
|
// Python might pick up an old version from the cache instead of the new versions
|
|
|
|
// of the .py files generated below
|
2020-10-03 17:38:03 +00:00
|
|
|
auto sys = py::module_::import("sys");
|
2017-09-12 06:05:05 +00:00
|
|
|
bool dont_write_bytecode = sys.attr("dont_write_bytecode").cast<bool>();
|
|
|
|
sys.attr("dont_write_bytecode") = true;
|
|
|
|
// Reset the value at scope exit
|
|
|
|
scope_exit reset_dont_write_bytecode([&]() {
|
|
|
|
sys.attr("dont_write_bytecode") = dont_write_bytecode;
|
|
|
|
});
|
|
|
|
|
|
|
|
std::string module_name = "test_module_reload";
|
|
|
|
std::string module_file = module_name + ".py";
|
|
|
|
|
|
|
|
// Create the module .py file
|
|
|
|
std::ofstream test_module(module_file);
|
|
|
|
test_module << "def test():\n";
|
|
|
|
test_module << " return 1\n";
|
|
|
|
test_module.close();
|
|
|
|
// Delete the file at scope exit
|
|
|
|
scope_exit delete_module_file([&]() {
|
|
|
|
std::remove(module_file.c_str());
|
|
|
|
});
|
|
|
|
|
|
|
|
// Import the module from file
|
2020-10-03 17:38:03 +00:00
|
|
|
auto module_ = py::module_::import(module_name.c_str());
|
|
|
|
int result = module_.attr("test")().cast<int>();
|
2017-09-12 06:05:05 +00:00
|
|
|
REQUIRE(result == 1);
|
|
|
|
|
|
|
|
// Update the module .py file with a small change
|
|
|
|
test_module.open(module_file);
|
|
|
|
test_module << "def test():\n";
|
|
|
|
test_module << " return 2\n";
|
|
|
|
test_module.close();
|
|
|
|
|
|
|
|
// Reload the module
|
2020-10-03 17:38:03 +00:00
|
|
|
module_.reload();
|
|
|
|
result = module_.attr("test")().cast<int>();
|
2017-09-12 06:05:05 +00:00
|
|
|
REQUIRE(result == 2);
|
|
|
|
}
|
2021-08-26 21:12:54 +00:00
|
|
|
|
|
|
|
TEST_CASE("sys.argv gets initialized properly") {
|
|
|
|
py::finalize_interpreter();
|
|
|
|
{
|
|
|
|
py::scoped_interpreter default_scope;
|
|
|
|
auto module = py::module::import("test_interpreter");
|
|
|
|
auto py_widget = module.attr("DerivedWidget")("The question");
|
|
|
|
const auto &cpp_widget = py_widget.cast<const Widget &>();
|
|
|
|
REQUIRE(cpp_widget.argv0().empty());
|
|
|
|
}
|
|
|
|
|
|
|
|
{
|
|
|
|
char *argv[] = {strdup("a.out")};
|
|
|
|
py::scoped_interpreter argv_scope(true, 1, argv);
|
2021-10-04 00:15:37 +00:00
|
|
|
std::free(argv[0]);
|
2021-08-26 21:12:54 +00:00
|
|
|
auto module = py::module::import("test_interpreter");
|
|
|
|
auto py_widget = module.attr("DerivedWidget")("The question");
|
|
|
|
const auto &cpp_widget = py_widget.cast<const Widget &>();
|
|
|
|
REQUIRE(cpp_widget.argv0() == "a.out");
|
|
|
|
}
|
|
|
|
py::initialize_interpreter();
|
|
|
|
}
|