github.com/kaydxh/golang@v0.0.131/pkg/gocv/cgo/third_path/pybind11/tests/test_eval.cpp (about) 1 /* 2 tests/test_eval.cpp -- Usage of eval() and eval_file() 3 4 Copyright (c) 2016 Klemens D. Morgenstern 5 6 All rights reserved. Use of this source code is governed by a 7 BSD-style license that can be found in the LICENSE file. 8 */ 9 10 #include <pybind11/eval.h> 11 12 #include "pybind11_tests.h" 13 14 #include <utility> 15 16 TEST_SUBMODULE(eval_, m) { 17 // test_evals 18 19 auto global = py::dict(py::module_::import("__main__").attr("__dict__")); 20 21 m.def("test_eval_statements", [global]() { 22 auto local = py::dict(); 23 local["call_test"] = py::cpp_function([&]() -> int { return 42; }); 24 25 // Regular string literal 26 py::exec("message = 'Hello World!'\n" 27 "x = call_test()", 28 global, 29 local); 30 31 // Multi-line raw string literal 32 py::exec(R"( 33 if x == 42: 34 print(message) 35 else: 36 raise RuntimeError 37 )", 38 global, 39 local); 40 auto x = local["x"].cast<int>(); 41 42 return x == 42; 43 }); 44 45 m.def("test_eval", [global]() { 46 auto local = py::dict(); 47 local["x"] = py::int_(42); 48 auto x = py::eval("x", global, local); 49 return x.cast<int>() == 42; 50 }); 51 52 m.def("test_eval_single_statement", []() { 53 auto local = py::dict(); 54 local["call_test"] = py::cpp_function([&]() -> int { return 42; }); 55 56 auto result = py::eval<py::eval_single_statement>("x = call_test()", py::dict(), local); 57 auto x = local["x"].cast<int>(); 58 return result.is_none() && x == 42; 59 }); 60 61 m.def("test_eval_file", [global](py::str filename) { 62 auto local = py::dict(); 63 local["y"] = py::int_(43); 64 65 int val_out = 0; 66 local["call_test2"] = py::cpp_function([&](int value) { val_out = value; }); 67 68 auto result = py::eval_file(std::move(filename), global, local); 69 return val_out == 43 && result.is_none(); 70 }); 71 72 m.def("test_eval_failure", []() { 73 try { 74 py::eval("nonsense code ..."); 75 } catch (py::error_already_set &) { 76 return true; 77 } 78 return false; 79 }); 80 81 m.def("test_eval_file_failure", []() { 82 try { 83 py::eval_file("non-existing file"); 84 } catch (std::exception &) { 85 return true; 86 } 87 return false; 88 }); 89 90 // test_eval_empty_globals 91 m.def("eval_empty_globals", [](py::object global) { 92 if (global.is_none()) { 93 global = py::dict(); 94 } 95 auto int_class = py::eval("isinstance(42, int)", global); 96 return global; 97 }); 98 99 // test_eval_closure 100 m.def("test_eval_closure", []() { 101 py::dict global; 102 global["closure_value"] = 42; 103 py::dict local; 104 local["closure_value"] = 0; 105 py::exec(R"( 106 local_value = closure_value 107 108 def func_global(): 109 return closure_value 110 111 def func_local(): 112 return local_value 113 )", 114 global, 115 local); 116 return std::make_pair(global, local); 117 }); 118 }