RpcServerTest.cc 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. #include <boost/bind.hpp>
  2. #include <boost/asio.hpp>
  3. #include <boost/function.hpp>
  4. #include <gtest/gtest.h>
  5. #include <gflags/gflags.h>
  6. #include <glog/logging.h>
  7. #include <google/protobuf/service.h>
  8. #include "Thread/CountBarrier.h"
  9. #include "Thread/ThreadPool.h"
  10. #include "Rpc/RpcChannel.h"
  11. #include "Rpc/RpcServer.h"
  12. #include "Rpc/RpcSession.h"
  13. #include "Rpc/RpcServerMock.h"
  14. #include "Rpc/Echo.pb.h"
  15. #include "Thread/ThreadPool.h"
  16. namespace Egametang {
  17. class MyEcho: public EchoService
  18. {
  19. public:
  20. virtual void Echo(
  21. google::protobuf::RpcController* controller,
  22. const EchoRequest* request,
  23. EchoResponse* response,
  24. google::protobuf::Closure* done)
  25. {
  26. int32 num = request->num();
  27. response->set_num(num);
  28. if (done)
  29. {
  30. done->Run();
  31. }
  32. }
  33. };
  34. static void IOServiceRun(boost::asio::io_service* io_service)
  35. {
  36. io_service->run();
  37. }
  38. class RpcServerTest: public testing::Test
  39. {
  40. protected:
  41. boost::asio::io_service io_server;
  42. boost::asio::io_service io_client;
  43. int port;
  44. public:
  45. RpcServerTest(): io_server(), io_client(), port(10003)
  46. {
  47. }
  48. virtual ~RpcServerTest()
  49. {
  50. }
  51. };
  52. TEST_F(RpcServerTest, ChannelAndServer)
  53. {
  54. ThreadPool thread_pool(2);
  55. RpcServicePtr echo_sevice(new MyEcho);
  56. RpcServer server(io_server, port);
  57. server.Register(echo_sevice);
  58. ASSERT_EQ(1U, server.methods.size());
  59. RpcChannel channel(io_client, "127.0.0.1", port);
  60. EchoService_Stub service(&channel);
  61. thread_pool.Schedule(boost::bind(&IOServiceRun, &io_server));
  62. thread_pool.Schedule(boost::bind(&IOServiceRun, &io_client));
  63. EchoRequest request;
  64. request.set_num(100);
  65. EchoResponse response;
  66. ASSERT_EQ(0U, response.num());
  67. CountBarrier barrier;
  68. service.Echo(NULL, &request, &response,
  69. google::protobuf::NewCallback(&barrier, &CountBarrier::Signal));
  70. barrier.Wait();
  71. VLOG(2) << "response: \n" << response.DebugString();
  72. channel.Stop();
  73. server.Stop();
  74. io_client.stop();
  75. io_server.stop();
  76. // rpc_channel是个无限循环的操作, 必须主动让channel和server stop才能wait线程
  77. thread_pool.Wait();
  78. ASSERT_EQ(100, response.num());
  79. }
  80. } // namespace Egametang
  81. int main(int argc, char* argv[])
  82. {
  83. testing::InitGoogleTest(&argc, argv);
  84. google::ParseCommandLineFlags(&argc, &argv, true);
  85. google::InitGoogleLogging(argv[0]);
  86. return RUN_ALL_TESTS();
  87. }