PythonInterpreterTest.cc 1.6 KB

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