end2end_test.cc 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. /*
  2. *
  3. * Copyright 2015, Google Inc.
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are
  8. * met:
  9. *
  10. * * Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * * Redistributions in binary form must reproduce the above
  13. * copyright notice, this list of conditions and the following disclaimer
  14. * in the documentation and/or other materials provided with the
  15. * distribution.
  16. * * Neither the name of Google Inc. nor the names of its
  17. * contributors may be used to endorse or promote products derived from
  18. * this software without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. *
  32. */
  33. #include <mutex>
  34. #include <thread>
  35. #include "src/core/security/credentials.h"
  36. #include "test/core/end2end/data/ssl_test_data.h"
  37. #include "test/core/util/port.h"
  38. #include "test/core/util/test_config.h"
  39. #include "test/cpp/util/echo_duplicate.grpc.pb.h"
  40. #include "test/cpp/util/echo.grpc.pb.h"
  41. #include <grpc++/channel_arguments.h>
  42. #include <grpc++/channel_interface.h>
  43. #include <grpc++/client_context.h>
  44. #include <grpc++/create_channel.h>
  45. #include <grpc++/credentials.h>
  46. #include <grpc++/dynamic_thread_pool.h>
  47. #include <grpc++/server.h>
  48. #include <grpc++/server_builder.h>
  49. #include <grpc++/server_context.h>
  50. #include <grpc++/server_credentials.h>
  51. #include <grpc++/status.h>
  52. #include <grpc++/stream.h>
  53. #include <grpc++/time.h>
  54. #include <gtest/gtest.h>
  55. #include <grpc/grpc.h>
  56. #include <grpc/support/thd.h>
  57. #include <grpc/support/time.h>
  58. using grpc::cpp::test::util::EchoRequest;
  59. using grpc::cpp::test::util::EchoResponse;
  60. using std::chrono::system_clock;
  61. namespace grpc {
  62. namespace testing {
  63. namespace {
  64. const char* kServerCancelAfterReads = "cancel_after_reads";
  65. // When echo_deadline is requested, deadline seen in the ServerContext is set in
  66. // the response in seconds.
  67. void MaybeEchoDeadline(ServerContext* context, const EchoRequest* request,
  68. EchoResponse* response) {
  69. if (request->has_param() && request->param().echo_deadline()) {
  70. gpr_timespec deadline = gpr_inf_future(GPR_CLOCK_REALTIME);
  71. if (context->deadline() != system_clock::time_point::max()) {
  72. Timepoint2Timespec(context->deadline(), &deadline);
  73. }
  74. response->mutable_param()->set_request_deadline(deadline.tv_sec);
  75. }
  76. }
  77. void CheckServerAuthContext(const ServerContext* context) {
  78. std::shared_ptr<const AuthContext> auth_ctx = context->auth_context();
  79. std::vector<grpc::string> ssl =
  80. auth_ctx->FindPropertyValues("transport_security_type");
  81. EXPECT_EQ(1u, ssl.size());
  82. EXPECT_EQ("ssl", ssl[0]);
  83. EXPECT_TRUE(auth_ctx->GetPeerIdentityPropertyName().empty());
  84. EXPECT_TRUE(auth_ctx->GetPeerIdentity().empty());
  85. }
  86. } // namespace
  87. class TestServiceImpl : public ::grpc::cpp::test::util::TestService::Service {
  88. public:
  89. TestServiceImpl() : signal_client_(false), host_() {}
  90. explicit TestServiceImpl(const grpc::string& host)
  91. : signal_client_(false), host_(new grpc::string(host)) {}
  92. Status Echo(ServerContext* context, const EchoRequest* request,
  93. EchoResponse* response) GRPC_OVERRIDE {
  94. response->set_message(request->message());
  95. MaybeEchoDeadline(context, request, response);
  96. if (host_) {
  97. response->mutable_param()->set_host(*host_);
  98. }
  99. if (request->has_param() && request->param().client_cancel_after_us()) {
  100. {
  101. std::unique_lock<std::mutex> lock(mu_);
  102. signal_client_ = true;
  103. }
  104. while (!context->IsCancelled()) {
  105. gpr_sleep_until(gpr_time_add(
  106. gpr_now(GPR_CLOCK_REALTIME),
  107. gpr_time_from_micros(request->param().client_cancel_after_us(),
  108. GPR_TIMESPAN)));
  109. }
  110. return Status::CANCELLED;
  111. } else if (request->has_param() &&
  112. request->param().server_cancel_after_us()) {
  113. gpr_sleep_until(gpr_time_add(
  114. gpr_now(GPR_CLOCK_REALTIME),
  115. gpr_time_from_micros(request->param().server_cancel_after_us(),
  116. GPR_TIMESPAN)));
  117. return Status::CANCELLED;
  118. } else {
  119. EXPECT_FALSE(context->IsCancelled());
  120. }
  121. if (request->has_param() && request->param().echo_metadata()) {
  122. const std::multimap<grpc::string, grpc::string>& client_metadata =
  123. context->client_metadata();
  124. for (std::multimap<grpc::string, grpc::string>::const_iterator iter =
  125. client_metadata.begin();
  126. iter != client_metadata.end(); ++iter) {
  127. context->AddTrailingMetadata((*iter).first, (*iter).second);
  128. }
  129. }
  130. if (request->has_param() && request->param().check_auth_context()) {
  131. CheckServerAuthContext(context);
  132. }
  133. if (request->has_param() &&
  134. request->param().response_message_length() > 0) {
  135. response->set_message(
  136. grpc::string(request->param().response_message_length(), '\0'));
  137. }
  138. return Status::OK;
  139. }
  140. // Unimplemented is left unimplemented to test the returned error.
  141. Status RequestStream(ServerContext* context,
  142. ServerReader<EchoRequest>* reader,
  143. EchoResponse* response) GRPC_OVERRIDE {
  144. EchoRequest request;
  145. response->set_message("");
  146. int cancel_after_reads = 0;
  147. const std::multimap<grpc::string, grpc::string> client_initial_metadata =
  148. context->client_metadata();
  149. if (client_initial_metadata.find(kServerCancelAfterReads) !=
  150. client_initial_metadata.end()) {
  151. std::istringstream iss(
  152. client_initial_metadata.find(kServerCancelAfterReads)->second);
  153. iss >> cancel_after_reads;
  154. gpr_log(GPR_INFO, "cancel_after_reads %d", cancel_after_reads);
  155. }
  156. while (reader->Read(&request)) {
  157. if (cancel_after_reads == 1) {
  158. gpr_log(GPR_INFO, "return cancel status");
  159. return Status::CANCELLED;
  160. } else if (cancel_after_reads > 0) {
  161. cancel_after_reads--;
  162. }
  163. response->mutable_message()->append(request.message());
  164. }
  165. return Status::OK;
  166. }
  167. // Return 3 messages.
  168. // TODO(yangg) make it generic by adding a parameter into EchoRequest
  169. Status ResponseStream(ServerContext* context, const EchoRequest* request,
  170. ServerWriter<EchoResponse>* writer) GRPC_OVERRIDE {
  171. EchoResponse response;
  172. response.set_message(request->message() + "0");
  173. writer->Write(response);
  174. response.set_message(request->message() + "1");
  175. writer->Write(response);
  176. response.set_message(request->message() + "2");
  177. writer->Write(response);
  178. return Status::OK;
  179. }
  180. Status BidiStream(ServerContext* context,
  181. ServerReaderWriter<EchoResponse, EchoRequest>* stream)
  182. GRPC_OVERRIDE {
  183. EchoRequest request;
  184. EchoResponse response;
  185. while (stream->Read(&request)) {
  186. gpr_log(GPR_INFO, "recv msg %s", request.message().c_str());
  187. response.set_message(request.message());
  188. stream->Write(response);
  189. }
  190. return Status::OK;
  191. }
  192. bool signal_client() {
  193. std::unique_lock<std::mutex> lock(mu_);
  194. return signal_client_;
  195. }
  196. private:
  197. bool signal_client_;
  198. std::mutex mu_;
  199. std::unique_ptr<grpc::string> host_;
  200. };
  201. class TestServiceImplDupPkg
  202. : public ::grpc::cpp::test::util::duplicate::TestService::Service {
  203. public:
  204. Status Echo(ServerContext* context, const EchoRequest* request,
  205. EchoResponse* response) GRPC_OVERRIDE {
  206. response->set_message("no package");
  207. return Status::OK;
  208. }
  209. };
  210. class End2endTest : public ::testing::Test {
  211. protected:
  212. End2endTest()
  213. : kMaxMessageSize_(8192), special_service_("special"), thread_pool_(2) {}
  214. void SetUp() GRPC_OVERRIDE {
  215. int port = grpc_pick_unused_port_or_die();
  216. server_address_ << "localhost:" << port;
  217. // Setup server
  218. ServerBuilder builder;
  219. SslServerCredentialsOptions::PemKeyCertPair pkcp = {test_server1_key,
  220. test_server1_cert};
  221. SslServerCredentialsOptions ssl_opts;
  222. ssl_opts.pem_root_certs = "";
  223. ssl_opts.pem_key_cert_pairs.push_back(pkcp);
  224. builder.AddListeningPort(server_address_.str(),
  225. SslServerCredentials(ssl_opts));
  226. builder.RegisterService(&service_);
  227. builder.RegisterService("foo.test.youtube.com", &special_service_);
  228. builder.SetMaxMessageSize(
  229. kMaxMessageSize_); // For testing max message size.
  230. builder.RegisterService(&dup_pkg_service_);
  231. builder.SetThreadPool(&thread_pool_);
  232. server_ = builder.BuildAndStart();
  233. }
  234. void TearDown() GRPC_OVERRIDE { server_->Shutdown(); }
  235. void ResetStub() {
  236. SslCredentialsOptions ssl_opts = {test_root_cert, "", ""};
  237. ChannelArguments args;
  238. args.SetSslTargetNameOverride("foo.test.google.fr");
  239. args.SetString(GRPC_ARG_SECONDARY_USER_AGENT_STRING, "end2end_test");
  240. channel_ = CreateChannel(server_address_.str(), SslCredentials(ssl_opts),
  241. args);
  242. stub_ = std::move(grpc::cpp::test::util::TestService::NewStub(channel_));
  243. }
  244. std::shared_ptr<ChannelInterface> channel_;
  245. std::unique_ptr<grpc::cpp::test::util::TestService::Stub> stub_;
  246. std::unique_ptr<Server> server_;
  247. std::ostringstream server_address_;
  248. const int kMaxMessageSize_;
  249. TestServiceImpl service_;
  250. TestServiceImpl special_service_;
  251. TestServiceImplDupPkg dup_pkg_service_;
  252. DynamicThreadPool thread_pool_;
  253. };
  254. #if 0
  255. static void SendRpc(grpc::cpp::test::util::TestService::Stub* stub,
  256. int num_rpcs) {
  257. EchoRequest request;
  258. EchoResponse response;
  259. request.set_message("Hello hello hello hello");
  260. for (int i = 0; i < num_rpcs; ++i) {
  261. ClientContext context;
  262. context.set_compression_algorithm(GRPC_COMPRESS_GZIP);
  263. Status s = stub->Echo(&context, request, &response);
  264. EXPECT_EQ(response.message(), request.message());
  265. EXPECT_TRUE(s.ok());
  266. }
  267. }
  268. TEST_F(End2endTest, SimpleRpcWithHost) {
  269. ResetStub();
  270. EchoRequest request;
  271. EchoResponse response;
  272. request.set_message("Hello");
  273. ClientContext context;
  274. context.set_authority("foo.test.youtube.com");
  275. Status s = stub_->Echo(&context, request, &response);
  276. EXPECT_EQ(response.message(), request.message());
  277. EXPECT_TRUE(response.has_param());
  278. EXPECT_EQ("special", response.param().host());
  279. EXPECT_TRUE(s.ok());
  280. }
  281. TEST_F(End2endTest, SimpleRpc) {
  282. ResetStub();
  283. SendRpc(stub_.get(), 1);
  284. }
  285. TEST_F(End2endTest, MultipleRpcs) {
  286. ResetStub();
  287. std::vector<std::thread*> threads;
  288. for (int i = 0; i < 10; ++i) {
  289. threads.push_back(new std::thread(SendRpc, stub_.get(), 10));
  290. }
  291. for (int i = 0; i < 10; ++i) {
  292. threads[i]->join();
  293. delete threads[i];
  294. }
  295. }
  296. // Set a 10us deadline and make sure proper error is returned.
  297. TEST_F(End2endTest, RpcDeadlineExpires) {
  298. ResetStub();
  299. EchoRequest request;
  300. EchoResponse response;
  301. request.set_message("Hello");
  302. ClientContext context;
  303. std::chrono::system_clock::time_point deadline =
  304. std::chrono::system_clock::now() + std::chrono::microseconds(10);
  305. context.set_deadline(deadline);
  306. Status s = stub_->Echo(&context, request, &response);
  307. EXPECT_EQ(StatusCode::DEADLINE_EXCEEDED, s.error_code());
  308. }
  309. // Set a long but finite deadline.
  310. TEST_F(End2endTest, RpcLongDeadline) {
  311. ResetStub();
  312. EchoRequest request;
  313. EchoResponse response;
  314. request.set_message("Hello");
  315. ClientContext context;
  316. std::chrono::system_clock::time_point deadline =
  317. std::chrono::system_clock::now() + std::chrono::hours(1);
  318. context.set_deadline(deadline);
  319. Status s = stub_->Echo(&context, request, &response);
  320. EXPECT_EQ(response.message(), request.message());
  321. EXPECT_TRUE(s.ok());
  322. }
  323. // Ask server to echo back the deadline it sees.
  324. TEST_F(End2endTest, EchoDeadline) {
  325. ResetStub();
  326. EchoRequest request;
  327. EchoResponse response;
  328. request.set_message("Hello");
  329. request.mutable_param()->set_echo_deadline(true);
  330. ClientContext context;
  331. std::chrono::system_clock::time_point deadline =
  332. std::chrono::system_clock::now() + std::chrono::seconds(100);
  333. context.set_deadline(deadline);
  334. Status s = stub_->Echo(&context, request, &response);
  335. EXPECT_EQ(response.message(), request.message());
  336. EXPECT_TRUE(s.ok());
  337. gpr_timespec sent_deadline;
  338. Timepoint2Timespec(deadline, &sent_deadline);
  339. // Allow 1 second error.
  340. EXPECT_LE(response.param().request_deadline() - sent_deadline.tv_sec, 1);
  341. EXPECT_GE(response.param().request_deadline() - sent_deadline.tv_sec, -1);
  342. }
  343. // Ask server to echo back the deadline it sees. The rpc has no deadline.
  344. TEST_F(End2endTest, EchoDeadlineForNoDeadlineRpc) {
  345. ResetStub();
  346. EchoRequest request;
  347. EchoResponse response;
  348. request.set_message("Hello");
  349. request.mutable_param()->set_echo_deadline(true);
  350. ClientContext context;
  351. Status s = stub_->Echo(&context, request, &response);
  352. EXPECT_EQ(response.message(), request.message());
  353. EXPECT_TRUE(s.ok());
  354. EXPECT_EQ(response.param().request_deadline(),
  355. gpr_inf_future(GPR_CLOCK_REALTIME).tv_sec);
  356. }
  357. TEST_F(End2endTest, UnimplementedRpc) {
  358. ResetStub();
  359. EchoRequest request;
  360. EchoResponse response;
  361. request.set_message("Hello");
  362. ClientContext context;
  363. Status s = stub_->Unimplemented(&context, request, &response);
  364. EXPECT_FALSE(s.ok());
  365. EXPECT_EQ(s.error_code(), grpc::StatusCode::UNIMPLEMENTED);
  366. EXPECT_EQ(s.error_message(), "");
  367. EXPECT_EQ(response.message(), "");
  368. }
  369. TEST_F(End2endTest, RequestStreamOneRequest) {
  370. ResetStub();
  371. EchoRequest request;
  372. EchoResponse response;
  373. ClientContext context;
  374. auto stream = stub_->RequestStream(&context, &response);
  375. request.set_message("hello");
  376. EXPECT_TRUE(stream->Write(request));
  377. stream->WritesDone();
  378. Status s = stream->Finish();
  379. EXPECT_EQ(response.message(), request.message());
  380. EXPECT_TRUE(s.ok());
  381. }
  382. TEST_F(End2endTest, RequestStreamTwoRequests) {
  383. ResetStub();
  384. EchoRequest request;
  385. EchoResponse response;
  386. ClientContext context;
  387. auto stream = stub_->RequestStream(&context, &response);
  388. request.set_message("hello");
  389. EXPECT_TRUE(stream->Write(request));
  390. EXPECT_TRUE(stream->Write(request));
  391. stream->WritesDone();
  392. Status s = stream->Finish();
  393. EXPECT_EQ(response.message(), "hellohello");
  394. EXPECT_TRUE(s.ok());
  395. }
  396. TEST_F(End2endTest, ResponseStream) {
  397. ResetStub();
  398. EchoRequest request;
  399. EchoResponse response;
  400. ClientContext context;
  401. request.set_message("hello");
  402. auto stream = stub_->ResponseStream(&context, request);
  403. EXPECT_TRUE(stream->Read(&response));
  404. EXPECT_EQ(response.message(), request.message() + "0");
  405. EXPECT_TRUE(stream->Read(&response));
  406. EXPECT_EQ(response.message(), request.message() + "1");
  407. EXPECT_TRUE(stream->Read(&response));
  408. EXPECT_EQ(response.message(), request.message() + "2");
  409. EXPECT_FALSE(stream->Read(&response));
  410. Status s = stream->Finish();
  411. EXPECT_TRUE(s.ok());
  412. }
  413. TEST_F(End2endTest, BidiStream) {
  414. ResetStub();
  415. EchoRequest request;
  416. EchoResponse response;
  417. ClientContext context;
  418. grpc::string msg("hello");
  419. auto stream = stub_->BidiStream(&context);
  420. request.set_message(msg + "0");
  421. EXPECT_TRUE(stream->Write(request));
  422. EXPECT_TRUE(stream->Read(&response));
  423. EXPECT_EQ(response.message(), request.message());
  424. request.set_message(msg + "1");
  425. EXPECT_TRUE(stream->Write(request));
  426. EXPECT_TRUE(stream->Read(&response));
  427. EXPECT_EQ(response.message(), request.message());
  428. request.set_message(msg + "2");
  429. EXPECT_TRUE(stream->Write(request));
  430. EXPECT_TRUE(stream->Read(&response));
  431. EXPECT_EQ(response.message(), request.message());
  432. stream->WritesDone();
  433. EXPECT_FALSE(stream->Read(&response));
  434. Status s = stream->Finish();
  435. EXPECT_TRUE(s.ok());
  436. }
  437. // Talk to the two services with the same name but different package names.
  438. // The two stubs are created on the same channel.
  439. TEST_F(End2endTest, DiffPackageServices) {
  440. ResetStub();
  441. EchoRequest request;
  442. EchoResponse response;
  443. request.set_message("Hello");
  444. ClientContext context;
  445. Status s = stub_->Echo(&context, request, &response);
  446. EXPECT_EQ(response.message(), request.message());
  447. EXPECT_TRUE(s.ok());
  448. std::unique_ptr<grpc::cpp::test::util::duplicate::TestService::Stub>
  449. dup_pkg_stub(
  450. grpc::cpp::test::util::duplicate::TestService::NewStub(channel_));
  451. ClientContext context2;
  452. s = dup_pkg_stub->Echo(&context2, request, &response);
  453. EXPECT_EQ("no package", response.message());
  454. EXPECT_TRUE(s.ok());
  455. }
  456. // rpc and stream should fail on bad credentials.
  457. TEST_F(End2endTest, BadCredentials) {
  458. std::shared_ptr<Credentials> bad_creds = ServiceAccountCredentials("", "", 1);
  459. EXPECT_EQ(static_cast<Credentials*>(nullptr), bad_creds.get());
  460. std::shared_ptr<ChannelInterface> channel =
  461. CreateChannel(server_address_.str(), bad_creds, ChannelArguments());
  462. std::unique_ptr<grpc::cpp::test::util::TestService::Stub> stub(
  463. grpc::cpp::test::util::TestService::NewStub(channel));
  464. EchoRequest request;
  465. EchoResponse response;
  466. ClientContext context;
  467. request.set_message("Hello");
  468. Status s = stub->Echo(&context, request, &response);
  469. EXPECT_EQ("", response.message());
  470. EXPECT_FALSE(s.ok());
  471. EXPECT_EQ(StatusCode::UNKNOWN, s.error_code());
  472. EXPECT_EQ("Rpc sent on a lame channel.", s.error_message());
  473. ClientContext context2;
  474. auto stream = stub->BidiStream(&context2);
  475. s = stream->Finish();
  476. EXPECT_FALSE(s.ok());
  477. EXPECT_EQ(StatusCode::UNKNOWN, s.error_code());
  478. EXPECT_EQ("Rpc sent on a lame channel.", s.error_message());
  479. }
  480. void CancelRpc(ClientContext* context, int delay_us, TestServiceImpl* service) {
  481. gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
  482. gpr_time_from_micros(delay_us, GPR_TIMESPAN)));
  483. while (!service->signal_client()) {
  484. }
  485. context->TryCancel();
  486. }
  487. // Client cancels rpc after 10ms
  488. TEST_F(End2endTest, ClientCancelsRpc) {
  489. ResetStub();
  490. EchoRequest request;
  491. EchoResponse response;
  492. request.set_message("Hello");
  493. const int kCancelDelayUs = 10 * 1000;
  494. request.mutable_param()->set_client_cancel_after_us(kCancelDelayUs);
  495. ClientContext context;
  496. std::thread cancel_thread(CancelRpc, &context, kCancelDelayUs, &service_);
  497. Status s = stub_->Echo(&context, request, &response);
  498. cancel_thread.join();
  499. EXPECT_EQ(StatusCode::CANCELLED, s.error_code());
  500. EXPECT_EQ(s.error_message(), "Cancelled");
  501. }
  502. // Server cancels rpc after 1ms
  503. TEST_F(End2endTest, ServerCancelsRpc) {
  504. ResetStub();
  505. EchoRequest request;
  506. EchoResponse response;
  507. request.set_message("Hello");
  508. request.mutable_param()->set_server_cancel_after_us(1000);
  509. ClientContext context;
  510. Status s = stub_->Echo(&context, request, &response);
  511. EXPECT_EQ(StatusCode::CANCELLED, s.error_code());
  512. EXPECT_TRUE(s.error_message().empty());
  513. }
  514. // Client cancels request stream after sending two messages
  515. TEST_F(End2endTest, ClientCancelsRequestStream) {
  516. ResetStub();
  517. EchoRequest request;
  518. EchoResponse response;
  519. ClientContext context;
  520. request.set_message("hello");
  521. auto stream = stub_->RequestStream(&context, &response);
  522. EXPECT_TRUE(stream->Write(request));
  523. EXPECT_TRUE(stream->Write(request));
  524. context.TryCancel();
  525. Status s = stream->Finish();
  526. EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
  527. EXPECT_EQ(response.message(), "");
  528. }
  529. // Client cancels server stream after sending some messages
  530. TEST_F(End2endTest, ClientCancelsResponseStream) {
  531. ResetStub();
  532. EchoRequest request;
  533. EchoResponse response;
  534. ClientContext context;
  535. request.set_message("hello");
  536. auto stream = stub_->ResponseStream(&context, request);
  537. EXPECT_TRUE(stream->Read(&response));
  538. EXPECT_EQ(response.message(), request.message() + "0");
  539. EXPECT_TRUE(stream->Read(&response));
  540. EXPECT_EQ(response.message(), request.message() + "1");
  541. context.TryCancel();
  542. // The cancellation races with responses, so there might be zero or
  543. // one responses pending, read till failure
  544. if (stream->Read(&response)) {
  545. EXPECT_EQ(response.message(), request.message() + "2");
  546. // Since we have cancelled, we expect the next attempt to read to fail
  547. EXPECT_FALSE(stream->Read(&response));
  548. }
  549. Status s = stream->Finish();
  550. // The final status could be either of CANCELLED or OK depending on
  551. // who won the race.
  552. EXPECT_GE(grpc::StatusCode::CANCELLED, s.error_code());
  553. }
  554. // Client cancels bidi stream after sending some messages
  555. TEST_F(End2endTest, ClientCancelsBidi) {
  556. ResetStub();
  557. EchoRequest request;
  558. EchoResponse response;
  559. ClientContext context;
  560. grpc::string msg("hello");
  561. auto stream = stub_->BidiStream(&context);
  562. request.set_message(msg + "0");
  563. EXPECT_TRUE(stream->Write(request));
  564. EXPECT_TRUE(stream->Read(&response));
  565. EXPECT_EQ(response.message(), request.message());
  566. request.set_message(msg + "1");
  567. EXPECT_TRUE(stream->Write(request));
  568. context.TryCancel();
  569. // The cancellation races with responses, so there might be zero or
  570. // one responses pending, read till failure
  571. if (stream->Read(&response)) {
  572. EXPECT_EQ(response.message(), request.message());
  573. // Since we have cancelled, we expect the next attempt to read to fail
  574. EXPECT_FALSE(stream->Read(&response));
  575. }
  576. Status s = stream->Finish();
  577. EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
  578. }
  579. TEST_F(End2endTest, RpcMaxMessageSize) {
  580. ResetStub();
  581. EchoRequest request;
  582. EchoResponse response;
  583. request.set_message(string(kMaxMessageSize_ * 2, 'a'));
  584. ClientContext context;
  585. Status s = stub_->Echo(&context, request, &response);
  586. EXPECT_FALSE(s.ok());
  587. }
  588. bool MetadataContains(const std::multimap<grpc::string, grpc::string>& metadata,
  589. const grpc::string& key, const grpc::string& value) {
  590. int count = 0;
  591. for (std::multimap<grpc::string, grpc::string>::const_iterator iter =
  592. metadata.begin();
  593. iter != metadata.end(); ++iter) {
  594. if ((*iter).first == key && (*iter).second == value) {
  595. count++;
  596. }
  597. }
  598. return count == 1;
  599. }
  600. TEST_F(End2endTest, SetPerCallCredentials) {
  601. ResetStub();
  602. EchoRequest request;
  603. EchoResponse response;
  604. ClientContext context;
  605. std::shared_ptr<Credentials> creds =
  606. IAMCredentials("fake_token", "fake_selector");
  607. context.set_credentials(creds);
  608. request.set_message("Hello");
  609. request.mutable_param()->set_echo_metadata(true);
  610. Status s = stub_->Echo(&context, request, &response);
  611. EXPECT_EQ(request.message(), response.message());
  612. EXPECT_TRUE(s.ok());
  613. EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
  614. GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY,
  615. "fake_token"));
  616. EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
  617. GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY,
  618. "fake_selector"));
  619. }
  620. TEST_F(End2endTest, InsecurePerCallCredentials) {
  621. ResetStub();
  622. EchoRequest request;
  623. EchoResponse response;
  624. ClientContext context;
  625. std::shared_ptr<Credentials> creds = InsecureCredentials();
  626. context.set_credentials(creds);
  627. request.set_message("Hello");
  628. request.mutable_param()->set_echo_metadata(true);
  629. Status s = stub_->Echo(&context, request, &response);
  630. EXPECT_EQ(StatusCode::CANCELLED, s.error_code());
  631. EXPECT_EQ("Failed to set credentials to rpc.", s.error_message());
  632. }
  633. TEST_F(End2endTest, OverridePerCallCredentials) {
  634. ResetStub();
  635. EchoRequest request;
  636. EchoResponse response;
  637. ClientContext context;
  638. std::shared_ptr<Credentials> creds1 =
  639. IAMCredentials("fake_token1", "fake_selector1");
  640. context.set_credentials(creds1);
  641. std::shared_ptr<Credentials> creds2 =
  642. IAMCredentials("fake_token2", "fake_selector2");
  643. context.set_credentials(creds2);
  644. request.set_message("Hello");
  645. request.mutable_param()->set_echo_metadata(true);
  646. Status s = stub_->Echo(&context, request, &response);
  647. EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
  648. GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY,
  649. "fake_token2"));
  650. EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
  651. GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY,
  652. "fake_selector2"));
  653. EXPECT_FALSE(MetadataContains(context.GetServerTrailingMetadata(),
  654. GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY,
  655. "fake_token1"));
  656. EXPECT_FALSE(MetadataContains(context.GetServerTrailingMetadata(),
  657. GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY,
  658. "fake_selector1"));
  659. EXPECT_EQ(request.message(), response.message());
  660. EXPECT_TRUE(s.ok());
  661. }
  662. // Client sends 20 requests and the server returns CANCELLED status after
  663. // reading 10 requests.
  664. TEST_F(End2endTest, RequestStreamServerEarlyCancelTest) {
  665. ResetStub();
  666. EchoRequest request;
  667. EchoResponse response;
  668. ClientContext context;
  669. context.AddMetadata(kServerCancelAfterReads, "10");
  670. auto stream = stub_->RequestStream(&context, &response);
  671. request.set_message("hello");
  672. int send_messages = 20;
  673. while (send_messages > 0) {
  674. EXPECT_TRUE(stream->Write(request));
  675. send_messages--;
  676. }
  677. stream->WritesDone();
  678. Status s = stream->Finish();
  679. EXPECT_EQ(s.error_code(), StatusCode::CANCELLED);
  680. }
  681. TEST_F(End2endTest, ClientAuthContext) {
  682. ResetStub();
  683. EchoRequest request;
  684. EchoResponse response;
  685. request.set_message("Hello");
  686. request.mutable_param()->set_check_auth_context(true);
  687. ClientContext context;
  688. Status s = stub_->Echo(&context, request, &response);
  689. EXPECT_EQ(response.message(), request.message());
  690. EXPECT_TRUE(s.ok());
  691. std::shared_ptr<const AuthContext> auth_ctx = context.auth_context();
  692. std::vector<grpc::string> ssl =
  693. auth_ctx->FindPropertyValues("transport_security_type");
  694. EXPECT_EQ(1u, ssl.size());
  695. EXPECT_EQ("ssl", ssl[0]);
  696. EXPECT_EQ("x509_subject_alternative_name",
  697. auth_ctx->GetPeerIdentityPropertyName());
  698. EXPECT_EQ(3u, auth_ctx->GetPeerIdentity().size());
  699. EXPECT_EQ("*.test.google.fr", auth_ctx->GetPeerIdentity()[0]);
  700. EXPECT_EQ("waterzooi.test.google.be", auth_ctx->GetPeerIdentity()[1]);
  701. EXPECT_EQ("*.test.youtube.com", auth_ctx->GetPeerIdentity()[2]);
  702. }
  703. // Make the response larger than the flow control window.
  704. TEST_F(End2endTest, HugeResponse) {
  705. ResetStub();
  706. EchoRequest request;
  707. EchoResponse response;
  708. request.set_message("huge response");
  709. const size_t kResponseSize = 1024 * (1024 + 10);
  710. request.mutable_param()->set_response_message_length(kResponseSize);
  711. ClientContext context;
  712. Status s = stub_->Echo(&context, request, &response);
  713. EXPECT_EQ(kResponseSize, response.message().size());
  714. EXPECT_TRUE(s.ok());
  715. }
  716. #endif
  717. namespace {
  718. void ReaderThreadFunc(ClientReaderWriter<EchoRequest, EchoResponse>* stream, gpr_event *ev) {
  719. EchoResponse resp;
  720. gpr_event_set(ev, (void*)1);
  721. while (stream->Read(&resp)) {
  722. gpr_log(GPR_INFO, "Read message");
  723. }
  724. }
  725. } // namespace
  726. // Run a Read and a WritesDone simultaneously.
  727. TEST_F(End2endTest, SimuReadWritesDone) {
  728. ResetStub();
  729. ClientContext context;
  730. gpr_event ev;
  731. gpr_event_init(&ev);
  732. auto stream = stub_->BidiStream(&context);
  733. std::thread reader_thread(ReaderThreadFunc, stream.get(), &ev);
  734. gpr_event_wait(&ev, gpr_inf_future(GPR_CLOCK_REALTIME));
  735. stream->WritesDone();
  736. Status s = stream->Finish();
  737. EXPECT_TRUE(s.ok());
  738. reader_thread.join();
  739. }
  740. } // namespace testing
  741. } // namespace grpc
  742. int main(int argc, char** argv) {
  743. grpc_test_init(argc, argv);
  744. ::testing::InitGoogleTest(&argc, argv);
  745. return RUN_ALL_TESTS();
  746. }