The source code and dockerfile for the GSW2024 AI Lab.
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.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

89 lines
2.3 KiB

4 weeks ago
  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. // Regular string literal
  17. py::exec(
  18. "message = 'Hello World!'\n"
  19. "x = call_test()",
  20. global, local
  21. );
  22. // Multi-line raw string literal
  23. py::exec(R"(
  24. if x == 42:
  25. print(message)
  26. else:
  27. raise RuntimeError
  28. )", global, local
  29. );
  30. auto x = local["x"].cast<int>();
  31. return x == 42;
  32. });
  33. m.def("test_eval", [global]() {
  34. auto local = py::dict();
  35. local["x"] = py::int_(42);
  36. auto x = py::eval("x", global, local);
  37. return x.cast<int>() == 42;
  38. });
  39. m.def("test_eval_single_statement", []() {
  40. auto local = py::dict();
  41. local["call_test"] = py::cpp_function([&]() -> int {
  42. return 42;
  43. });
  44. auto result = py::eval<py::eval_single_statement>("x = call_test()", py::dict(), local);
  45. auto x = local["x"].cast<int>();
  46. return result.is_none() && x == 42;
  47. });
  48. m.def("test_eval_file", [global](py::str filename) {
  49. auto local = py::dict();
  50. local["y"] = py::int_(43);
  51. int val_out;
  52. local["call_test2"] = py::cpp_function([&](int value) { val_out = value; });
  53. auto result = py::eval_file(filename, global, local);
  54. return val_out == 43 && result.is_none();
  55. });
  56. m.def("test_eval_failure", []() {
  57. try {
  58. py::eval("nonsense code ...");
  59. } catch (py::error_already_set &) {
  60. return true;
  61. }
  62. return false;
  63. });
  64. m.def("test_eval_file_failure", []() {
  65. try {
  66. py::eval_file("non-existing file");
  67. } catch (std::exception &) {
  68. return true;
  69. }
  70. return false;
  71. });
  72. });