test_interpreter.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. #include <pybind11/embed.h>
  2. #ifdef _MSC_VER
  3. // Silence MSVC C++17 deprecation warning from Catch regarding std::uncaught_exceptions (up to catch
  4. // 2.0.1; this should be fixed in the next catch release after 2.0.1).
  5. # pragma warning(disable: 4996)
  6. #endif
  7. #include <catch.hpp>
  8. #include <thread>
  9. #include <fstream>
  10. #include <functional>
  11. namespace py = pybind11;
  12. using namespace py::literals;
  13. class Widget {
  14. public:
  15. Widget(std::string message) : message(message) { }
  16. virtual ~Widget() = default;
  17. std::string the_message() const { return message; }
  18. virtual int the_answer() const = 0;
  19. private:
  20. std::string message;
  21. };
  22. class PyWidget final : public Widget {
  23. using Widget::Widget;
  24. int the_answer() const override { PYBIND11_OVERLOAD_PURE(int, Widget, the_answer); }
  25. };
  26. PYBIND11_EMBEDDED_MODULE(widget_module, m) {
  27. py::class_<Widget, PyWidget>(m, "Widget")
  28. .def(py::init<std::string>())
  29. .def_property_readonly("the_message", &Widget::the_message);
  30. m.def("add", [](int i, int j) { return i + j; });
  31. }
  32. PYBIND11_EMBEDDED_MODULE(throw_exception, ) {
  33. throw std::runtime_error("C++ Error");
  34. }
  35. PYBIND11_EMBEDDED_MODULE(throw_error_already_set, ) {
  36. auto d = py::dict();
  37. d["missing"].cast<py::object>();
  38. }
  39. TEST_CASE("Pass classes and data between modules defined in C++ and Python") {
  40. auto module = py::module::import("test_interpreter");
  41. REQUIRE(py::hasattr(module, "DerivedWidget"));
  42. auto locals = py::dict("hello"_a="Hello, World!", "x"_a=5, **module.attr("__dict__"));
  43. py::exec(R"(
  44. widget = DerivedWidget("{} - {}".format(hello, x))
  45. message = widget.the_message
  46. )", py::globals(), locals);
  47. REQUIRE(locals["message"].cast<std::string>() == "Hello, World! - 5");
  48. auto py_widget = module.attr("DerivedWidget")("The question");
  49. auto message = py_widget.attr("the_message");
  50. REQUIRE(message.cast<std::string>() == "The question");
  51. const auto &cpp_widget = py_widget.cast<const Widget &>();
  52. REQUIRE(cpp_widget.the_answer() == 42);
  53. }
  54. TEST_CASE("Import error handling") {
  55. REQUIRE_NOTHROW(py::module::import("widget_module"));
  56. REQUIRE_THROWS_WITH(py::module::import("throw_exception"),
  57. "ImportError: C++ Error");
  58. REQUIRE_THROWS_WITH(py::module::import("throw_error_already_set"),
  59. Catch::Contains("ImportError: KeyError"));
  60. }
  61. TEST_CASE("There can be only one interpreter") {
  62. static_assert(std::is_move_constructible<py::scoped_interpreter>::value, "");
  63. static_assert(!std::is_move_assignable<py::scoped_interpreter>::value, "");
  64. static_assert(!std::is_copy_constructible<py::scoped_interpreter>::value, "");
  65. static_assert(!std::is_copy_assignable<py::scoped_interpreter>::value, "");
  66. REQUIRE_THROWS_WITH(py::initialize_interpreter(), "The interpreter is already running");
  67. REQUIRE_THROWS_WITH(py::scoped_interpreter(), "The interpreter is already running");
  68. py::finalize_interpreter();
  69. REQUIRE_NOTHROW(py::scoped_interpreter());
  70. {
  71. auto pyi1 = py::scoped_interpreter();
  72. auto pyi2 = std::move(pyi1);
  73. }
  74. py::initialize_interpreter();
  75. }
  76. bool has_pybind11_internals_builtin() {
  77. auto builtins = py::handle(PyEval_GetBuiltins());
  78. return builtins.contains(PYBIND11_INTERNALS_ID);
  79. };
  80. bool has_pybind11_internals_static() {
  81. auto **&ipp = py::detail::get_internals_pp();
  82. return ipp && *ipp;
  83. }
  84. TEST_CASE("Restart the interpreter") {
  85. // Verify pre-restart state.
  86. REQUIRE(py::module::import("widget_module").attr("add")(1, 2).cast<int>() == 3);
  87. REQUIRE(has_pybind11_internals_builtin());
  88. REQUIRE(has_pybind11_internals_static());
  89. REQUIRE(py::module::import("external_module").attr("A")(123).attr("value").cast<int>() == 123);
  90. // local and foreign module internals should point to the same internals:
  91. REQUIRE(reinterpret_cast<uintptr_t>(*py::detail::get_internals_pp()) ==
  92. py::module::import("external_module").attr("internals_at")().cast<uintptr_t>());
  93. // Restart the interpreter.
  94. py::finalize_interpreter();
  95. REQUIRE(Py_IsInitialized() == 0);
  96. py::initialize_interpreter();
  97. REQUIRE(Py_IsInitialized() == 1);
  98. // Internals are deleted after a restart.
  99. REQUIRE_FALSE(has_pybind11_internals_builtin());
  100. REQUIRE_FALSE(has_pybind11_internals_static());
  101. pybind11::detail::get_internals();
  102. REQUIRE(has_pybind11_internals_builtin());
  103. REQUIRE(has_pybind11_internals_static());
  104. REQUIRE(reinterpret_cast<uintptr_t>(*py::detail::get_internals_pp()) ==
  105. py::module::import("external_module").attr("internals_at")().cast<uintptr_t>());
  106. // Make sure that an interpreter with no get_internals() created until finalize still gets the
  107. // internals destroyed
  108. py::finalize_interpreter();
  109. py::initialize_interpreter();
  110. bool ran = false;
  111. py::module::import("__main__").attr("internals_destroy_test") =
  112. py::capsule(&ran, [](void *ran) { py::detail::get_internals(); *static_cast<bool *>(ran) = true; });
  113. REQUIRE_FALSE(has_pybind11_internals_builtin());
  114. REQUIRE_FALSE(has_pybind11_internals_static());
  115. REQUIRE_FALSE(ran);
  116. py::finalize_interpreter();
  117. REQUIRE(ran);
  118. py::initialize_interpreter();
  119. REQUIRE_FALSE(has_pybind11_internals_builtin());
  120. REQUIRE_FALSE(has_pybind11_internals_static());
  121. // C++ modules can be reloaded.
  122. auto cpp_module = py::module::import("widget_module");
  123. REQUIRE(cpp_module.attr("add")(1, 2).cast<int>() == 3);
  124. // C++ type information is reloaded and can be used in python modules.
  125. auto py_module = py::module::import("test_interpreter");
  126. auto py_widget = py_module.attr("DerivedWidget")("Hello after restart");
  127. REQUIRE(py_widget.attr("the_message").cast<std::string>() == "Hello after restart");
  128. }
  129. TEST_CASE("Subinterpreter") {
  130. // Add tags to the modules in the main interpreter and test the basics.
  131. py::module::import("__main__").attr("main_tag") = "main interpreter";
  132. {
  133. auto m = py::module::import("widget_module");
  134. m.attr("extension_module_tag") = "added to module in main interpreter";
  135. REQUIRE(m.attr("add")(1, 2).cast<int>() == 3);
  136. }
  137. REQUIRE(has_pybind11_internals_builtin());
  138. REQUIRE(has_pybind11_internals_static());
  139. /// Create and switch to a subinterpreter.
  140. auto main_tstate = PyThreadState_Get();
  141. auto sub_tstate = Py_NewInterpreter();
  142. // Subinterpreters get their own copy of builtins. detail::get_internals() still
  143. // works by returning from the static variable, i.e. all interpreters share a single
  144. // global pybind11::internals;
  145. REQUIRE_FALSE(has_pybind11_internals_builtin());
  146. REQUIRE(has_pybind11_internals_static());
  147. // Modules tags should be gone.
  148. REQUIRE_FALSE(py::hasattr(py::module::import("__main__"), "tag"));
  149. {
  150. auto m = py::module::import("widget_module");
  151. REQUIRE_FALSE(py::hasattr(m, "extension_module_tag"));
  152. // Function bindings should still work.
  153. REQUIRE(m.attr("add")(1, 2).cast<int>() == 3);
  154. }
  155. // Restore main interpreter.
  156. Py_EndInterpreter(sub_tstate);
  157. PyThreadState_Swap(main_tstate);
  158. REQUIRE(py::hasattr(py::module::import("__main__"), "main_tag"));
  159. REQUIRE(py::hasattr(py::module::import("widget_module"), "extension_module_tag"));
  160. }
  161. TEST_CASE("Execution frame") {
  162. // When the interpreter is embedded, there is no execution frame, but `py::exec`
  163. // should still function by using reasonable globals: `__main__.__dict__`.
  164. py::exec("var = dict(number=42)");
  165. REQUIRE(py::globals()["var"]["number"].cast<int>() == 42);
  166. }
  167. TEST_CASE("Threads") {
  168. // Restart interpreter to ensure threads are not initialized
  169. py::finalize_interpreter();
  170. py::initialize_interpreter();
  171. REQUIRE_FALSE(has_pybind11_internals_static());
  172. constexpr auto num_threads = 10;
  173. auto locals = py::dict("count"_a=0);
  174. {
  175. py::gil_scoped_release gil_release{};
  176. REQUIRE(has_pybind11_internals_static());
  177. auto threads = std::vector<std::thread>();
  178. for (auto i = 0; i < num_threads; ++i) {
  179. threads.emplace_back([&]() {
  180. py::gil_scoped_acquire gil{};
  181. locals["count"] = locals["count"].cast<int>() + 1;
  182. });
  183. }
  184. for (auto &thread : threads) {
  185. thread.join();
  186. }
  187. }
  188. REQUIRE(locals["count"].cast<int>() == num_threads);
  189. }
  190. // Scope exit utility https://stackoverflow.com/a/36644501/7255855
  191. struct scope_exit {
  192. std::function<void()> f_;
  193. explicit scope_exit(std::function<void()> f) noexcept : f_(std::move(f)) {}
  194. ~scope_exit() { if (f_) f_(); }
  195. };
  196. TEST_CASE("Reload module from file") {
  197. // Disable generation of cached bytecode (.pyc files) for this test, otherwise
  198. // Python might pick up an old version from the cache instead of the new versions
  199. // of the .py files generated below
  200. auto sys = py::module::import("sys");
  201. bool dont_write_bytecode = sys.attr("dont_write_bytecode").cast<bool>();
  202. sys.attr("dont_write_bytecode") = true;
  203. // Reset the value at scope exit
  204. scope_exit reset_dont_write_bytecode([&]() {
  205. sys.attr("dont_write_bytecode") = dont_write_bytecode;
  206. });
  207. std::string module_name = "test_module_reload";
  208. std::string module_file = module_name + ".py";
  209. // Create the module .py file
  210. std::ofstream test_module(module_file);
  211. test_module << "def test():\n";
  212. test_module << " return 1\n";
  213. test_module.close();
  214. // Delete the file at scope exit
  215. scope_exit delete_module_file([&]() {
  216. std::remove(module_file.c_str());
  217. });
  218. // Import the module from file
  219. auto module = py::module::import(module_name.c_str());
  220. int result = module.attr("test")().cast<int>();
  221. REQUIRE(result == 1);
  222. // Update the module .py file with a small change
  223. test_module.open(module_file);
  224. test_module << "def test():\n";
  225. test_module << " return 2\n";
  226. test_module.close();
  227. // Reload the module
  228. module.reload();
  229. result = module.attr("test")().cast<int>();
  230. REQUIRE(result == 2);
  231. }