PythonInterpreterTest.cc 1.5 KB

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