1
0

module.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #include "test.h"
  2. #include <gtest/gtest.h>
  3. PYBIND11_EMBEDDED_MODULE(example, m) {
  4. m.def("add", [](int a, int b) {
  5. return a + b;
  6. });
  7. auto math = m.def_submodule("math");
  8. math.def("sub", [](int a, int b) {
  9. return a - b;
  10. });
  11. }
  12. namespace {
  13. TEST_F(PYBIND11_TEST, module) {
  14. py::exec("import example");
  15. EXPECT_EVAL_EQ("example.add(1, 2)", 3);
  16. py::exec("from example import math");
  17. EXPECT_EVAL_EQ("math.sub(1, 2)", -1);
  18. py::exec("from example.math import sub");
  19. EXPECT_EVAL_EQ("sub(1, 2)", -1);
  20. auto math = py::module::import("example.math");
  21. EXPECT_EQ(math.attr("sub")(4, 3).cast<int>(), 1);
  22. }
  23. TEST_F(PYBIND11_TEST, raw_module) {
  24. auto m = py::module::create("example2");
  25. m.def("add", [](int a, int b) {
  26. return a + b;
  27. });
  28. auto math = m.def_submodule("math");
  29. math.def("sub", [](int a, int b) {
  30. return a - b;
  31. });
  32. py::exec("import example2");
  33. EXPECT_EVAL_EQ("example2.add(1, 2)", 3);
  34. py::exec("from example2 import math");
  35. EXPECT_EVAL_EQ("math.sub(1, 2)", -1);
  36. py::exec("from example2.math import sub");
  37. EXPECT_EVAL_EQ("sub(1, 2)", -1);
  38. auto math2 = py::module::import("example2.math");
  39. EXPECT_EQ(math2.attr("sub")(4, 3).cast<int>(), 1);
  40. }
  41. } // namespace