RpcServerTest.cc 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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_client;
  42. boost::asio::io_service io_server;
  43. int port;
  44. public:
  45. RpcServerTest(): io_client(), io_server(), 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. RpcServerPtr server(new RpcServer(io_server, port));
  57. // 注册service
  58. server->Register(echo_sevice);
  59. ASSERT_EQ(1U, server->methods.size());
  60. RpcChannelPtr channel(new RpcChannel(io_client, "127.0.0.1", port));
  61. EchoService_Stub service(channel.get());
  62. // 定义消息
  63. EchoRequest request;
  64. request.set_num(100);
  65. EchoResponse response;
  66. ASSERT_EQ(0U, response.num());
  67. // server和client分别在两个不同的线程
  68. thread_pool.Schedule(boost::bind(&IOServiceRun, &io_server));
  69. thread_pool.Schedule(boost::bind(&IOServiceRun, &io_client));
  70. CountBarrier barrier;
  71. service.Echo(NULL, &request, &response,
  72. google::protobuf::NewCallback(&barrier, &CountBarrier::Signal));
  73. barrier.Wait();
  74. channel->Stop();
  75. server->Stop();
  76. io_client.stop();
  77. io_server.stop();
  78. // rpc_channel是个无限循环的操作, 必须主动让channel和server stop才能wait线程
  79. thread_pool.Wait();
  80. ASSERT_EQ(100, response.num());
  81. }
  82. } // namespace Egametang
  83. int main(int argc, char* argv[])
  84. {
  85. testing::InitGoogleTest(&argc, argv);
  86. google::ParseCommandLineFlags(&argc, &argv, true);
  87. google::InitGoogleLogging(argv[0]);
  88. return RUN_ALL_TESTS();
  89. }