File indexing completed on 2025-01-18 10:17:53
0001
0002
0003
0004
0005
0006
0007
0008
0009
0010 #include <pybind11/eval.h>
0011
0012 #include "pybind11_tests.h"
0013
0014 #include <utility>
0015
0016 TEST_SUBMODULE(eval_, m) {
0017
0018
0019 auto global = py::dict(py::module_::import("__main__").attr("__dict__"));
0020
0021 m.def("test_eval_statements", [global]() {
0022 auto local = py::dict();
0023 local["call_test"] = py::cpp_function([&]() -> int { return 42; });
0024
0025
0026 py::exec("message = 'Hello World!'\n"
0027 "x = call_test()",
0028 global,
0029 local);
0030
0031
0032 py::exec(R"(
0033 if x == 42:
0034 print(message)
0035 else:
0036 raise RuntimeError
0037 )",
0038 global,
0039 local);
0040 auto x = local["x"].cast<int>();
0041
0042 return x == 42;
0043 });
0044
0045 m.def("test_eval", [global]() {
0046 auto local = py::dict();
0047 local["x"] = py::int_(42);
0048 auto x = py::eval("x", global, local);
0049 return x.cast<int>() == 42;
0050 });
0051
0052 m.def("test_eval_single_statement", []() {
0053 auto local = py::dict();
0054 local["call_test"] = py::cpp_function([&]() -> int { return 42; });
0055
0056 auto result = py::eval<py::eval_single_statement>("x = call_test()", py::dict(), local);
0057 auto x = local["x"].cast<int>();
0058 return result.is_none() && x == 42;
0059 });
0060
0061 m.def("test_eval_file", [global](py::str filename) {
0062 auto local = py::dict();
0063 local["y"] = py::int_(43);
0064
0065 int val_out = 0;
0066 local["call_test2"] = py::cpp_function([&](int value) { val_out = value; });
0067
0068 auto result = py::eval_file(std::move(filename), global, local);
0069 return val_out == 43 && result.is_none();
0070 });
0071
0072 m.def("test_eval_failure", []() {
0073 try {
0074 py::eval("nonsense code ...");
0075 } catch (py::error_already_set &) {
0076 return true;
0077 }
0078 return false;
0079 });
0080
0081 m.def("test_eval_file_failure", []() {
0082 try {
0083 py::eval_file("non-existing file");
0084 } catch (std::exception &) {
0085 return true;
0086 }
0087 return false;
0088 });
0089
0090
0091 m.def("eval_empty_globals", [](py::object global) {
0092 if (global.is_none()) {
0093 global = py::dict();
0094 }
0095 auto int_class = py::eval("isinstance(42, int)", global);
0096 return global;
0097 });
0098
0099
0100 m.def("test_eval_closure", []() {
0101 py::dict global;
0102 global["closure_value"] = 42;
0103 py::dict local;
0104 local["closure_value"] = 0;
0105 py::exec(R"(
0106 local_value = closure_value
0107
0108 def func_global():
0109 return closure_value
0110
0111 def func_local():
0112 return local_value
0113 )",
0114 global,
0115 local);
0116 return std::make_pair(global, local);
0117 });
0118 }