test_eval.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. tests/test_eval.cpp -- Usage of eval() and eval_file()
  3. Copyright (c) 2016 Klemens D. Morgenstern
  4. All rights reserved. Use of this source code is governed by a
  5. BSD-style license that can be found in the LICENSE file.
  6. */
  7. #include <pybind11/eval.h>
  8. #include "pybind11_tests.h"
  9. TEST_SUBMODULE(eval_, m) {
  10. // test_evals
  11. auto global = py::dict(py::module::import("__main__").attr("__dict__"));
  12. m.def("test_eval_statements", [global]() {
  13. auto local = py::dict();
  14. local["call_test"] = py::cpp_function([&]() -> int {
  15. return 42;
  16. });
  17. // Regular string literal
  18. py::exec(
  19. "message = 'Hello World!'\n"
  20. "x = call_test()",
  21. global, local
  22. );
  23. // Multi-line raw string literal
  24. py::exec(R"(
  25. if x == 42:
  26. print(message)
  27. else:
  28. raise RuntimeError
  29. )", global, local
  30. );
  31. auto x = local["x"].cast<int>();
  32. return x == 42;
  33. });
  34. m.def("test_eval", [global]() {
  35. auto local = py::dict();
  36. local["x"] = py::int_(42);
  37. auto x = py::eval("x", global, local);
  38. return x.cast<int>() == 42;
  39. });
  40. m.def("test_eval_single_statement", []() {
  41. auto local = py::dict();
  42. local["call_test"] = py::cpp_function([&]() -> int {
  43. return 42;
  44. });
  45. auto result = py::eval<py::eval_single_statement>("x = call_test()", py::dict(), local);
  46. auto x = local["x"].cast<int>();
  47. return result.is_none() && x == 42;
  48. });
  49. m.def("test_eval_file", [global](py::str filename) {
  50. auto local = py::dict();
  51. local["y"] = py::int_(43);
  52. int val_out;
  53. local["call_test2"] = py::cpp_function([&](int value) { val_out = value; });
  54. auto result = py::eval_file(filename, global, local);
  55. return val_out == 43 && result.is_none();
  56. });
  57. m.def("test_eval_failure", []() {
  58. try {
  59. py::eval("nonsense code ...");
  60. } catch (py::error_already_set &) {
  61. return true;
  62. }
  63. return false;
  64. });
  65. m.def("test_eval_file_failure", []() {
  66. try {
  67. py::eval_file("non-existing file");
  68. } catch (std::exception &) {
  69. return true;
  70. }
  71. return false;
  72. });
  73. }