PythonInterpreterTest.cc 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #include <boost/python.hpp>
  2. #include <boost/make_shared.hpp>
  3. #include <gtest/gtest.h>
  4. #include <glog/logging.h>
  5. #include <gflags/gflags.h>
  6. #include "Python/PythonInterpreter.h"
  7. namespace Egametang {
  8. class PythonInterpreterTest: public testing::Test
  9. {
  10. protected:
  11. PythonInterpreter interpreter;
  12. public:
  13. PythonInterpreterTest(): interpreter()
  14. {
  15. }
  16. virtual ~PythonInterpreterTest()
  17. {
  18. }
  19. };
  20. class PersonTest
  21. {
  22. private:
  23. int guid;
  24. std::string name;
  25. public:
  26. PersonTest(): guid(0)
  27. {
  28. }
  29. void SetGuid(int guid)
  30. {
  31. this->guid = guid;
  32. }
  33. int Guid() const
  34. {
  35. return guid;
  36. }
  37. void SetName(const std::string& name)
  38. {
  39. this->name = name;
  40. }
  41. std::string Name() const
  42. {
  43. return name;
  44. }
  45. };
  46. typedef boost::shared_ptr<PersonTest> PersonTestPtr;
  47. BOOST_PYTHON_MODULE(PersonTest)
  48. {
  49. boost::python::class_<PersonTest>("Person")
  50. .def("SetGuid", &PersonTest::SetGuid)
  51. .def("Guid", &PersonTest::Guid)
  52. .def("SetName", &PersonTest::SetName)
  53. .def("Name", &PersonTest::Name)
  54. ;
  55. boost::python::register_ptr_to_python<PersonTestPtr>();
  56. }
  57. TEST_F(PythonInterpreterTest, EnterPythonScript)
  58. {
  59. initPersonTest();
  60. interpreter.ImportPath("../../../Cpp/Platform/Python/");
  61. interpreter.ImportModule("PythonInterpreterTest");
  62. auto person = boost::make_shared<PersonTestPtr>();
  63. interpreter.RegisterObjectPtr("person", person);
  64. ASSERT_EQ(0, person->Guid());
  65. // 进到python脚本层设置person的值为2
  66. interpreter.Execute("PythonInterpreterTest.fun(person)");
  67. ASSERT_EQ(2, person->Guid());
  68. ASSERT_EQ(std::string("tanghai"), person->Name());
  69. }
  70. } // namespace Egametang
  71. int main(int argc, char* argv[])
  72. {
  73. testing::InitGoogleTest(&argc, argv);
  74. google::InitGoogleLogging(argv[0]);
  75. google::ParseCommandLineFlags(&argc, &argv, true);
  76. return RUN_ALL_TESTS();
  77. }