You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
2.1 KiB

  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_initializer eval([](py::module &m) {
  10. auto global = py::dict(py::module::import("__main__").attr("__dict__"));
  11. m.def("test_eval_statements", [global]() {
  12. auto local = py::dict();
  13. local["call_test"] = py::cpp_function([&]() -> int {
  14. return 42;
  15. });
  16. auto result = py::eval<py::eval_statements>(
  17. "print('Hello World!');\n"
  18. "x = call_test();",
  19. global, local
  20. );
  21. auto x = local["x"].cast<int>();
  22. return result == py::none() && x == 42;
  23. });
  24. m.def("test_eval", [global]() {
  25. auto local = py::dict();
  26. local["x"] = py::int_(42);
  27. auto x = py::eval("x", global, local);
  28. return x.cast<int>() == 42;
  29. });
  30. m.def("test_eval_single_statement", []() {
  31. auto local = py::dict();
  32. local["call_test"] = py::cpp_function([&]() -> int {
  33. return 42;
  34. });
  35. auto result = py::eval<py::eval_single_statement>("x = call_test()", py::dict(), local);
  36. auto x = local["x"].cast<int>();
  37. return result == py::none() && x == 42;
  38. });
  39. m.def("test_eval_file", [global](py::str filename) {
  40. auto local = py::dict();
  41. local["y"] = py::int_(43);
  42. int val_out;
  43. local["call_test2"] = py::cpp_function([&](int value) { val_out = value; });
  44. auto result = py::eval_file(filename, global, local);
  45. return val_out == 43 && result == py::none();
  46. });
  47. m.def("test_eval_failure", []() {
  48. try {
  49. py::eval("nonsense code ...");
  50. } catch (py::error_already_set &) {
  51. return true;
  52. }
  53. return false;
  54. });
  55. m.def("test_eval_file_failure", []() {
  56. try {
  57. py::eval_file("non-existing file");
  58. } catch (std::exception &) {
  59. return true;
  60. }
  61. return false;
  62. });
  63. });