PythonInterpreterTest.cc 1.7 KB

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