end2end_test.cc
Go to the documentation of this file.
1 /*
2  *
3  * Copyright 2015 gRPC authors.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18 
19 #include <mutex>
20 #include <thread>
21 
22 #include "absl/memory/memory.h"
23 #include "absl/strings/ascii.h"
24 #include "absl/strings/match.h"
25 #include "absl/strings/str_format.h"
26 
27 #include <grpc/grpc.h>
28 #include <grpc/support/alloc.h>
29 #include <grpc/support/log.h>
30 #include <grpc/support/time.h>
31 #include <grpcpp/channel.h>
32 #include <grpcpp/client_context.h>
33 #include <grpcpp/create_channel.h>
34 #include <grpcpp/resource_quota.h>
38 #include <grpcpp/server.h>
39 #include <grpcpp/server_builder.h>
40 #include <grpcpp/server_context.h>
43 
45 #include "src/core/lib/gpr/env.h"
48 #include "src/proto/grpc/testing/duplicate/echo_duplicate.grpc.pb.h"
49 #include "src/proto/grpc/testing/echo.grpc.pb.h"
50 #include "test/core/util/port.h"
56 
57 #ifdef GRPC_POSIX_SOCKET_EV
59 #endif // GRPC_POSIX_SOCKET_EV
60 
61 #include <gtest/gtest.h>
62 
63 using grpc::testing::EchoRequest;
64 using grpc::testing::EchoResponse;
66 using std::chrono::system_clock;
67 
68 namespace grpc {
69 namespace testing {
70 namespace {
71 
72 bool CheckIsLocalhost(const std::string& addr) {
73  const std::string kIpv6("ipv6:%5B::1%5D:");
74  const std::string kIpv4MappedIpv6("ipv6:%5B::ffff:127.0.0.1%5D:");
75  const std::string kIpv4("ipv4:127.0.0.1:");
76  return addr.substr(0, kIpv4.size()) == kIpv4 ||
77  addr.substr(0, kIpv4MappedIpv6.size()) == kIpv4MappedIpv6 ||
78  addr.substr(0, kIpv6.size()) == kIpv6;
79 }
80 
81 const int kClientChannelBackupPollIntervalMs = 200;
82 
83 const char kTestCredsPluginErrorMsg[] = "Could not find plugin metadata.";
84 
85 const char kFakeToken[] = "fake_token";
86 const char kFakeSelector[] = "fake_selector";
87 const char kExpectedFakeCredsDebugString[] =
88  "SecureCallCredentials{GoogleIAMCredentials{Token:present,"
89  "AuthoritySelector:fake_selector}}";
90 
91 const char kWrongToken[] = "wrong_token";
92 const char kWrongSelector[] = "wrong_selector";
93 const char kExpectedWrongCredsDebugString[] =
94  "SecureCallCredentials{GoogleIAMCredentials{Token:present,"
95  "AuthoritySelector:wrong_selector}}";
96 
97 const char kFakeToken1[] = "fake_token1";
98 const char kFakeSelector1[] = "fake_selector1";
99 const char kExpectedFakeCreds1DebugString[] =
100  "SecureCallCredentials{GoogleIAMCredentials{Token:present,"
101  "AuthoritySelector:fake_selector1}}";
102 
103 const char kFakeToken2[] = "fake_token2";
104 const char kFakeSelector2[] = "fake_selector2";
105 const char kExpectedFakeCreds2DebugString[] =
106  "SecureCallCredentials{GoogleIAMCredentials{Token:present,"
107  "AuthoritySelector:fake_selector2}}";
108 
109 const char kExpectedAuthMetadataPluginKeyFailureCredsDebugString[] =
110  "SecureCallCredentials{TestMetadataCredentials{key:TestPluginMetadata,"
111  "value:Does not matter, will fail the key is invalid.}}";
112 const char kExpectedAuthMetadataPluginValueFailureCredsDebugString[] =
113  "SecureCallCredentials{TestMetadataCredentials{key:test-plugin-metadata,"
114  "value:With illegal \n value.}}";
115 const char kExpectedAuthMetadataPluginWithDeadlineCredsDebugString[] =
116  "SecureCallCredentials{TestMetadataCredentials{key:meta_key,value:Does not "
117  "matter}}";
118 const char kExpectedNonBlockingAuthMetadataPluginFailureCredsDebugString[] =
119  "SecureCallCredentials{TestMetadataCredentials{key:test-plugin-metadata,"
120  "value:Does not matter, will fail anyway (see 3rd param)}}";
121 const char
122  kExpectedNonBlockingAuthMetadataPluginAndProcessorSuccessCredsDebugString
123  [] = "SecureCallCredentials{TestMetadataCredentials{key:test-plugin-"
124  "metadata,value:Dr Jekyll}}";
125 const char
126  kExpectedNonBlockingAuthMetadataPluginAndProcessorFailureCredsDebugString
127  [] = "SecureCallCredentials{TestMetadataCredentials{key:test-plugin-"
128  "metadata,value:Mr Hyde}}";
129 const char kExpectedBlockingAuthMetadataPluginFailureCredsDebugString[] =
130  "SecureCallCredentials{TestMetadataCredentials{key:test-plugin-metadata,"
131  "value:Does not matter, will fail anyway (see 3rd param)}}";
132 const char kExpectedCompositeCallCredsDebugString[] =
133  "SecureCallCredentials{CompositeCallCredentials{TestMetadataCredentials{"
134  "key:call-creds-key1,value:call-creds-val1},TestMetadataCredentials{key:"
135  "call-creds-key2,value:call-creds-val2}}}";
136 
137 class TestMetadataCredentialsPlugin : public MetadataCredentialsPlugin {
138  public:
139  static const char kGoodMetadataKey[];
140  static const char kBadMetadataKey[];
141 
142  TestMetadataCredentialsPlugin(const grpc::string_ref& metadata_key,
143  const grpc::string_ref& metadata_value,
144  bool is_blocking, bool is_successful,
145  int delay_ms)
146  : metadata_key_(metadata_key.data(), metadata_key.length()),
147  metadata_value_(metadata_value.data(), metadata_value.length()),
148  is_blocking_(is_blocking),
149  is_successful_(is_successful),
150  delay_ms_(delay_ms) {}
151 
152  bool IsBlocking() const override { return is_blocking_; }
153 
154  Status GetMetadata(
156  const grpc::AuthContext& channel_auth_context,
157  std::multimap<std::string, std::string>* metadata) override {
158  if (delay_ms_ != 0) {
162  }
163  EXPECT_GT(service_url.length(), 0UL);
164  EXPECT_GT(method_name.length(), 0UL);
165  EXPECT_TRUE(channel_auth_context.IsPeerAuthenticated());
166  EXPECT_TRUE(metadata != nullptr);
167  if (is_successful_) {
168  metadata->insert(std::make_pair(metadata_key_, metadata_value_));
169  return Status::OK;
170  } else {
171  return Status(StatusCode::NOT_FOUND, kTestCredsPluginErrorMsg);
172  }
173  }
174 
175  std::string DebugString() override {
176  return absl::StrFormat("TestMetadataCredentials{key:%s,value:%s}",
177  metadata_key_.c_str(), metadata_value_.c_str());
178  }
179 
180  private:
186 };
187 
189  "TestPluginMetadata";
191  "test-plugin-metadata";
192 
193 class TestAuthMetadataProcessor : public AuthMetadataProcessor {
194  public:
195  static const char kGoodGuy[];
196 
197  explicit TestAuthMetadataProcessor(bool is_blocking)
198  : is_blocking_(is_blocking) {}
199 
200  std::shared_ptr<CallCredentials> GetCompatibleClientCreds() {
202  std::unique_ptr<MetadataCredentialsPlugin>(
203  new TestMetadataCredentialsPlugin(
205  is_blocking_, true, 0)));
206  }
207 
208  std::shared_ptr<CallCredentials> GetIncompatibleClientCreds() {
210  std::unique_ptr<MetadataCredentialsPlugin>(
211  new TestMetadataCredentialsPlugin(
213  is_blocking_, true, 0)));
214  }
215 
216  // Interface implementation
217  bool IsBlocking() const override { return is_blocking_; }
218 
219  Status Process(const InputMetadata& auth_metadata, AuthContext* context,
220  OutputMetadata* consumed_auth_metadata,
221  OutputMetadata* response_metadata) override {
222  EXPECT_TRUE(consumed_auth_metadata != nullptr);
223  EXPECT_TRUE(context != nullptr);
224  EXPECT_TRUE(response_metadata != nullptr);
225  auto auth_md =
227  EXPECT_NE(auth_md, auth_metadata.end());
228  string_ref auth_md_value = auth_md->second;
229  if (auth_md_value == kGoodGuy) {
230  context->AddProperty(kIdentityPropName, kGoodGuy);
231  context->SetPeerIdentityPropertyName(kIdentityPropName);
232  consumed_auth_metadata->insert(std::make_pair(
233  string(auth_md->first.data(), auth_md->first.length()),
234  string(auth_md->second.data(), auth_md->second.length())));
235  return Status::OK;
236  } else {
238  string("Invalid principal: ") +
239  string(auth_md_value.data(), auth_md_value.length()));
240  }
241  }
242 
243  private:
244  static const char kIdentityPropName[];
245  bool is_blocking_;
246 };
247 
248 const char TestAuthMetadataProcessor::kGoodGuy[] = "Dr Jekyll";
249 const char TestAuthMetadataProcessor::kIdentityPropName[] = "novel identity";
250 
251 class Proxy : public grpc::testing::EchoTestService::Service {
252  public:
253  explicit Proxy(const std::shared_ptr<Channel>& channel)
254  : stub_(grpc::testing::EchoTestService::NewStub(channel)) {}
255 
256  Status Echo(ServerContext* server_context, const EchoRequest* request,
257  EchoResponse* response) override {
258  std::unique_ptr<ClientContext> client_context =
259  ClientContext::FromServerContext(*server_context);
260  return stub_->Echo(client_context.get(), *request, response);
261  }
262 
263  private:
264  std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
265 };
266 
267 class TestServiceImplDupPkg
268  : public grpc::testing::duplicate::EchoTestService::Service {
269  public:
270  Status Echo(ServerContext* /*context*/, const EchoRequest* /*request*/,
271  EchoResponse* response) override {
272  response->set_message("no package");
273  return Status::OK;
274  }
275 };
276 
277 class TestScenario {
278  public:
279  TestScenario(bool use_interceptors, bool use_proxy, bool inproc,
282  use_proxy_(use_proxy),
283  inproc_(inproc),
286 
287  bool use_interceptors() const { return use_interceptors_; }
288  bool use_proxy() const { return use_proxy_; }
289  bool inproc() const { return inproc_; }
290  const std::string& credentials_type() const { return credentials_type_; }
291  bool callback_server() const { return callback_server_; }
292 
293  std::string AsString() const;
294 
295  static std::string Name(const ::testing::TestParamInfo<TestScenario>& info) {
296  return info.param.AsString();
297  }
298 
299  private:
302  bool inproc_;
305 };
306 
307 std::string TestScenario::AsString() const {
308  std::string retval = use_interceptors_ ? "Interceptor" : "";
309  if (use_proxy_) retval += "Proxy";
310  if (inproc_) retval += "Inproc";
311  if (callback_server_) retval += "CallbackServer";
313  retval += "Insecure";
314  } else {
316  if (!creds_type.empty()) creds_type[0] = absl::ascii_toupper(creds_type[0]);
317  retval += creds_type;
318  }
319  return retval;
320 }
321 
322 class End2endTest : public ::testing::TestWithParam<TestScenario> {
323  protected:
324  static void SetUpTestCase() { grpc_init(); }
325  static void TearDownTestCase() { grpc_shutdown(); }
326  End2endTest()
328  kMaxMessageSize_(8192),
329  special_service_("special"),
330  first_picked_port_(0) {}
331 
332  void TearDown() override {
333  if (is_server_started_) {
334  server_->Shutdown();
335  if (proxy_server_) proxy_server_->Shutdown();
336  }
337  if (first_picked_port_ > 0) {
339  }
340  }
341 
342  void StartServer(const std::shared_ptr<AuthMetadataProcessor>& processor) {
345  server_address_ << "localhost:" << port;
346  // Setup server
347  BuildAndStartServer(processor);
348  }
349 
350  void RestartServer(const std::shared_ptr<AuthMetadataProcessor>& processor) {
351  if (is_server_started_) {
352  server_->Shutdown();
353  BuildAndStartServer(processor);
354  }
355  }
356 
357  void BuildAndStartServer(
358  const std::shared_ptr<AuthMetadataProcessor>& processor) {
359  ServerBuilder builder;
360  ConfigureServerBuilder(&builder);
361  auto server_creds = GetCredentialsProvider()->GetServerCredentials(
364  server_creds->SetAuthMetadataProcessor(processor);
365  }
366  if (GetParam().use_interceptors()) {
367  std::vector<
368  std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
369  creators;
370  // Add 20 phony server interceptors
371  creators.reserve(20);
372  for (auto i = 0; i < 20; i++) {
373  creators.push_back(absl::make_unique<PhonyInterceptorFactory>());
374  }
375  builder.experimental().SetInterceptorCreators(std::move(creators));
376  }
377  builder.AddListeningPort(server_address_.str(), server_creds);
378  if (!GetParam().callback_server()) {
379  builder.RegisterService(&service_);
380  } else {
381  builder.RegisterService(&callback_service_);
382  }
383  builder.RegisterService("foo.test.youtube.com", &special_service_);
384  builder.RegisterService(&dup_pkg_service_);
385 
386  builder.SetSyncServerOption(ServerBuilder::SyncServerOption::NUM_CQS, 4);
387  builder.SetSyncServerOption(
388  ServerBuilder::SyncServerOption::CQ_TIMEOUT_MSEC, 10);
389 
390  server_ = builder.BuildAndStart();
391  is_server_started_ = true;
392  }
393 
394  virtual void ConfigureServerBuilder(ServerBuilder* builder) {
395  builder->SetMaxMessageSize(
396  kMaxMessageSize_); // For testing max message size.
397  }
398 
399  void ResetChannel(
400  std::vector<
401  std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
402  interceptor_creators = {}) {
403  if (!is_server_started_) {
404  StartServer(std::shared_ptr<AuthMetadataProcessor>());
405  }
407  ChannelArguments args;
408  auto channel_creds = GetCredentialsProvider()->GetChannelCredentials(
410  if (!user_agent_prefix_.empty()) {
411  args.SetUserAgentPrefix(user_agent_prefix_);
412  }
413  args.SetString(GRPC_ARG_SECONDARY_USER_AGENT_STRING, "end2end_test");
414 
415  if (!GetParam().inproc()) {
416  if (!GetParam().use_interceptors()) {
418  channel_creds, args);
419  } else {
421  server_address_.str(), channel_creds, args,
422  interceptor_creators.empty() ? CreatePhonyClientInterceptors()
423  : std::move(interceptor_creators));
424  }
425  } else {
426  if (!GetParam().use_interceptors()) {
427  channel_ = server_->InProcessChannel(args);
428  } else {
429  channel_ = server_->experimental().InProcessChannelWithInterceptors(
430  args, interceptor_creators.empty()
432  : std::move(interceptor_creators));
433  }
434  }
435  }
436 
437  void ResetStub(
438  std::vector<
439  std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
440  interceptor_creators = {}) {
441  ResetChannel(std::move(interceptor_creators));
442  if (GetParam().use_proxy()) {
443  proxy_service_ = absl::make_unique<Proxy>(channel_);
445  std::ostringstream proxyaddr;
446  proxyaddr << "localhost:" << port;
447  ServerBuilder builder;
448  builder.AddListeningPort(proxyaddr.str(), InsecureServerCredentials());
449  builder.RegisterService(proxy_service_.get());
450 
451  builder.SetSyncServerOption(ServerBuilder::SyncServerOption::NUM_CQS, 4);
452  builder.SetSyncServerOption(
453  ServerBuilder::SyncServerOption::CQ_TIMEOUT_MSEC, 10);
454 
455  proxy_server_ = builder.BuildAndStart();
456 
457  channel_ =
459  }
460 
461  stub_ = grpc::testing::EchoTestService::NewStub(channel_);
463  }
464 
466  std::shared_ptr<Channel> channel_;
467  std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
468  std::unique_ptr<Server> server_;
469  std::unique_ptr<Server> proxy_server_;
470  std::unique_ptr<Proxy> proxy_service_;
471  std::ostringstream server_address_;
472  const int kMaxMessageSize_;
474  CallbackTestServiceImpl callback_service_;
476  TestServiceImplDupPkg dup_pkg_service_;
479 };
480 
481 void SendRpc(grpc::testing::EchoTestService::Stub* stub, int num_rpcs,
482  bool with_binary_metadata) {
483  EchoRequest request;
484  EchoResponse response;
485  request.set_message("Hello hello hello hello");
486 
487  for (int i = 0; i < num_rpcs; ++i) {
488  ClientContext context;
489  if (with_binary_metadata) {
490  char bytes[8] = {'\0', '\1', '\2', '\3',
491  '\4', '\5', '\6', static_cast<char>(i)};
492  context.AddMetadata("custom-bin", std::string(bytes, 8));
493  }
495  Status s = stub->Echo(&context, request, &response);
496  EXPECT_EQ(response.message(), request.message());
497  EXPECT_TRUE(s.ok());
498  }
499 }
500 
501 // This class is for testing scenarios where RPCs are cancelled on the server
502 // by calling ServerContext::TryCancel()
503 class End2endServerTryCancelTest : public End2endTest {
504  protected:
505  // Helper for testing client-streaming RPCs which are cancelled on the server.
506  // Depending on the value of server_try_cancel parameter, this will test one
507  // of the following three scenarios:
508  // CANCEL_BEFORE_PROCESSING: Rpc is cancelled by the server before reading
509  // any messages from the client
510  //
511  // CANCEL_DURING_PROCESSING: Rpc is cancelled by the server while reading
512  // messages from the client
513  //
514  // CANCEL_AFTER PROCESSING: Rpc is cancelled by server after reading all
515  // the messages from the client
516  //
517  // NOTE: Do not call this function with server_try_cancel == DO_NOT_CANCEL.
518  void TestRequestStreamServerCancel(
519  ServerTryCancelRequestPhase server_try_cancel, int num_msgs_to_send) {
520  RestartServer(std::shared_ptr<AuthMetadataProcessor>());
521  ResetStub();
522  EchoRequest request;
523  EchoResponse response;
524  ClientContext context;
525 
526  // Send server_try_cancel value in the client metadata
528  std::to_string(server_try_cancel));
529 
530  auto stream = stub_->RequestStream(&context, &response);
531 
532  int num_msgs_sent = 0;
533  while (num_msgs_sent < num_msgs_to_send) {
534  request.set_message("hello");
535  if (!stream->Write(request)) {
536  break;
537  }
538  num_msgs_sent++;
539  }
540  gpr_log(GPR_INFO, "Sent %d messages", num_msgs_sent);
541 
542  stream->WritesDone();
543  Status s = stream->Finish();
544 
545  // At this point, we know for sure that RPC was cancelled by the server
546  // since we passed server_try_cancel value in the metadata. Depending on the
547  // value of server_try_cancel, the RPC might have been cancelled by the
548  // server at different stages. The following validates our expectations of
549  // number of messages sent in various cancellation scenarios:
550 
551  switch (server_try_cancel) {
554  // If the RPC is cancelled by server before / during messages from the
555  // client, it means that the client most likely did not get a chance to
556  // send all the messages it wanted to send. i.e num_msgs_sent <=
557  // num_msgs_to_send
558  EXPECT_LE(num_msgs_sent, num_msgs_to_send);
559  break;
560 
562  // If the RPC was cancelled after all messages were read by the server,
563  // the client did get a chance to send all its messages
564  EXPECT_EQ(num_msgs_sent, num_msgs_to_send);
565  break;
566 
567  default:
568  gpr_log(GPR_ERROR, "Invalid server_try_cancel value: %d",
569  server_try_cancel);
570  EXPECT_TRUE(server_try_cancel > DO_NOT_CANCEL &&
571  server_try_cancel <= CANCEL_AFTER_PROCESSING);
572  break;
573  }
574 
575  EXPECT_FALSE(s.ok());
576  EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
577  // Make sure that the server interceptors were notified
578  if (GetParam().use_interceptors()) {
580  }
581  }
582 
583  // Helper for testing server-streaming RPCs which are cancelled on the server.
584  // Depending on the value of server_try_cancel parameter, this will test one
585  // of the following three scenarios:
586  // CANCEL_BEFORE_PROCESSING: Rpc is cancelled by the server before writing
587  // any messages to the client
588  //
589  // CANCEL_DURING_PROCESSING: Rpc is cancelled by the server while writing
590  // messages to the client
591  //
592  // CANCEL_AFTER PROCESSING: Rpc is cancelled by server after writing all
593  // the messages to the client
594  //
595  // NOTE: Do not call this function with server_try_cancel == DO_NOT_CANCEL.
596  void TestResponseStreamServerCancel(
597  ServerTryCancelRequestPhase server_try_cancel) {
598  RestartServer(std::shared_ptr<AuthMetadataProcessor>());
599  ResetStub();
600  EchoRequest request;
601  EchoResponse response;
602  ClientContext context;
603 
604  // Send server_try_cancel in the client metadata
606  std::to_string(server_try_cancel));
607 
608  request.set_message("hello");
609  auto stream = stub_->ResponseStream(&context, request);
610 
611  int num_msgs_read = 0;
612  while (num_msgs_read < kServerDefaultResponseStreamsToSend) {
613  if (!stream->Read(&response)) {
614  break;
615  }
616  EXPECT_EQ(response.message(),
617  request.message() + std::to_string(num_msgs_read));
618  num_msgs_read++;
619  }
620  gpr_log(GPR_INFO, "Read %d messages", num_msgs_read);
621 
622  Status s = stream->Finish();
623 
624  // Depending on the value of server_try_cancel, the RPC might have been
625  // cancelled by the server at different stages. The following validates our
626  // expectations of number of messages read in various cancellation
627  // scenarios:
628  switch (server_try_cancel) {
630  // Server cancelled before sending any messages. Which means the client
631  // wouldn't have read any
632  EXPECT_EQ(num_msgs_read, 0);
633  break;
634 
636  // Server cancelled while writing messages. Client must have read less
637  // than or equal to the expected number of messages
639  break;
640 
642  // Even though the Server cancelled after writing all messages, the RPC
643  // may be cancelled before the Client got a chance to read all the
644  // messages.
646  break;
647 
648  default: {
649  gpr_log(GPR_ERROR, "Invalid server_try_cancel value: %d",
650  server_try_cancel);
651  EXPECT_TRUE(server_try_cancel > DO_NOT_CANCEL &&
652  server_try_cancel <= CANCEL_AFTER_PROCESSING);
653  break;
654  }
655  }
656 
657  EXPECT_FALSE(s.ok());
658  // Make sure that the server interceptors were notified
659  if (GetParam().use_interceptors()) {
661  }
662  }
663 
664  // Helper for testing bidirectional-streaming RPCs which are cancelled on the
665  // server. Depending on the value of server_try_cancel parameter, this will
666  // test one of the following three scenarios:
667  // CANCEL_BEFORE_PROCESSING: Rpc is cancelled by the server before reading/
668  // writing any messages from/to the client
669  //
670  // CANCEL_DURING_PROCESSING: Rpc is cancelled by the server while reading/
671  // writing messages from/to the client
672  //
673  // CANCEL_AFTER PROCESSING: Rpc is cancelled by server after reading/writing
674  // all the messages from/to the client
675  //
676  // NOTE: Do not call this function with server_try_cancel == DO_NOT_CANCEL.
677  void TestBidiStreamServerCancel(ServerTryCancelRequestPhase server_try_cancel,
678  int num_messages) {
679  RestartServer(std::shared_ptr<AuthMetadataProcessor>());
680  ResetStub();
681  EchoRequest request;
682  EchoResponse response;
683  ClientContext context;
684 
685  // Send server_try_cancel in the client metadata
687  std::to_string(server_try_cancel));
688 
689  auto stream = stub_->BidiStream(&context);
690 
691  int num_msgs_read = 0;
692  int num_msgs_sent = 0;
693  while (num_msgs_sent < num_messages) {
694  request.set_message("hello " + std::to_string(num_msgs_sent));
695  if (!stream->Write(request)) {
696  break;
697  }
698  num_msgs_sent++;
699 
700  if (!stream->Read(&response)) {
701  break;
702  }
703  num_msgs_read++;
704 
705  EXPECT_EQ(response.message(), request.message());
706  }
707  gpr_log(GPR_INFO, "Sent %d messages", num_msgs_sent);
708  gpr_log(GPR_INFO, "Read %d messages", num_msgs_read);
709 
710  stream->WritesDone();
711  Status s = stream->Finish();
712 
713  // Depending on the value of server_try_cancel, the RPC might have been
714  // cancelled by the server at different stages. The following validates our
715  // expectations of number of messages read in various cancellation
716  // scenarios:
717  switch (server_try_cancel) {
719  EXPECT_EQ(num_msgs_read, 0);
720  break;
721 
723  EXPECT_LE(num_msgs_sent, num_messages);
724  EXPECT_LE(num_msgs_read, num_msgs_sent);
725  break;
726 
728  EXPECT_EQ(num_msgs_sent, num_messages);
729 
730  // The Server cancelled after reading the last message and after writing
731  // the message to the client. However, the RPC cancellation might have
732  // taken effect before the client actually read the response.
733  EXPECT_LE(num_msgs_read, num_msgs_sent);
734  break;
735 
736  default:
737  gpr_log(GPR_ERROR, "Invalid server_try_cancel value: %d",
738  server_try_cancel);
739  EXPECT_TRUE(server_try_cancel > DO_NOT_CANCEL &&
740  server_try_cancel <= CANCEL_AFTER_PROCESSING);
741  break;
742  }
743 
744  EXPECT_FALSE(s.ok());
745  EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
746  // Make sure that the server interceptors were notified
747  if (GetParam().use_interceptors()) {
749  }
750  }
751 };
752 
753 TEST_P(End2endServerTryCancelTest, RequestEchoServerCancel) {
754  ResetStub();
755  EchoRequest request;
756  EchoResponse response;
757  ClientContext context;
758 
761  Status s = stub_->Echo(&context, request, &response);
762  EXPECT_FALSE(s.ok());
763  EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
764 }
765 
766 // Server to cancel before doing reading the request
767 TEST_P(End2endServerTryCancelTest, RequestStreamServerCancelBeforeReads) {
768  TestRequestStreamServerCancel(CANCEL_BEFORE_PROCESSING, 1);
769 }
770 
771 // Server to cancel while reading a request from the stream in parallel
772 TEST_P(End2endServerTryCancelTest, RequestStreamServerCancelDuringRead) {
773  TestRequestStreamServerCancel(CANCEL_DURING_PROCESSING, 10);
774 }
775 
776 // Server to cancel after reading all the requests but before returning to the
777 // client
778 TEST_P(End2endServerTryCancelTest, RequestStreamServerCancelAfterReads) {
779  TestRequestStreamServerCancel(CANCEL_AFTER_PROCESSING, 4);
780 }
781 
782 // Server to cancel before sending any response messages
783 TEST_P(End2endServerTryCancelTest, ResponseStreamServerCancelBefore) {
784  TestResponseStreamServerCancel(CANCEL_BEFORE_PROCESSING);
785 }
786 
787 // Server to cancel while writing a response to the stream in parallel
788 TEST_P(End2endServerTryCancelTest, ResponseStreamServerCancelDuring) {
789  TestResponseStreamServerCancel(CANCEL_DURING_PROCESSING);
790 }
791 
792 // Server to cancel after writing all the respones to the stream but before
793 // returning to the client
794 TEST_P(End2endServerTryCancelTest, ResponseStreamServerCancelAfter) {
795  TestResponseStreamServerCancel(CANCEL_AFTER_PROCESSING);
796 }
797 
798 // Server to cancel before reading/writing any requests/responses on the stream
799 TEST_P(End2endServerTryCancelTest, BidiStreamServerCancelBefore) {
800  TestBidiStreamServerCancel(CANCEL_BEFORE_PROCESSING, 2);
801 }
802 
803 // Server to cancel while reading/writing requests/responses on the stream in
804 // parallel
805 TEST_P(End2endServerTryCancelTest, BidiStreamServerCancelDuring) {
806  TestBidiStreamServerCancel(CANCEL_DURING_PROCESSING, 10);
807 }
808 
809 // Server to cancel after reading/writing all requests/responses on the stream
810 // but before returning to the client
811 TEST_P(End2endServerTryCancelTest, BidiStreamServerCancelAfter) {
812  TestBidiStreamServerCancel(CANCEL_AFTER_PROCESSING, 5);
813 }
814 
815 TEST_P(End2endTest, SimpleRpcWithCustomUserAgentPrefix) {
816  // User-Agent is an HTTP header for HTTP transports only
817  if (GetParam().inproc()) {
818  return;
819  }
820  user_agent_prefix_ = "custom_prefix";
821  ResetStub();
822  EchoRequest request;
823  EchoResponse response;
824  request.set_message("Hello hello hello hello");
825  request.mutable_param()->set_echo_metadata(true);
826 
827  ClientContext context;
828  Status s = stub_->Echo(&context, request, &response);
829  EXPECT_EQ(response.message(), request.message());
830  EXPECT_TRUE(s.ok());
832  auto iter = trailing_metadata.find("user-agent");
834  std::string expected_prefix = user_agent_prefix_ + " grpc-c++/";
835  EXPECT_TRUE(iter->second.starts_with(expected_prefix)) << iter->second;
836 }
837 
838 TEST_P(End2endTest, MultipleRpcsWithVariedBinaryMetadataValue) {
839  ResetStub();
840  std::vector<std::thread> threads;
841  threads.reserve(10);
842  for (int i = 0; i < 10; ++i) {
843  threads.emplace_back(SendRpc, stub_.get(), 10, true);
844  }
845  for (int i = 0; i < 10; ++i) {
846  threads[i].join();
847  }
848 }
849 
850 TEST_P(End2endTest, MultipleRpcs) {
851  ResetStub();
852  std::vector<std::thread> threads;
853  threads.reserve(10);
854  for (int i = 0; i < 10; ++i) {
855  threads.emplace_back(SendRpc, stub_.get(), 10, false);
856  }
857  for (int i = 0; i < 10; ++i) {
858  threads[i].join();
859  }
860 }
861 
862 TEST_P(End2endTest, ManyStubs) {
863  ResetStub();
864  ChannelTestPeer peer(channel_.get());
865  int registered_calls_pre = peer.registered_calls();
866  int registration_attempts_pre = peer.registration_attempts();
867  for (int i = 0; i < 1000; ++i) {
868  grpc::testing::EchoTestService::NewStub(channel_);
869  }
870  EXPECT_EQ(peer.registered_calls(), registered_calls_pre);
871  EXPECT_GT(peer.registration_attempts(), registration_attempts_pre);
872 }
873 
874 TEST_P(End2endTest, EmptyBinaryMetadata) {
875  ResetStub();
876  EchoRequest request;
877  EchoResponse response;
878  request.set_message("Hello hello hello hello");
879  ClientContext context;
880  context.AddMetadata("custom-bin", "");
881  Status s = stub_->Echo(&context, request, &response);
882  EXPECT_EQ(response.message(), request.message());
883  EXPECT_TRUE(s.ok());
884 }
885 
886 TEST_P(End2endTest, AuthoritySeenOnServerSide) {
887  ResetStub();
888  EchoRequest request;
889  request.mutable_param()->set_echo_host_from_authority_header(true);
890  EchoResponse response;
891  request.set_message("Live long and prosper.");
892  ClientContext context;
893  Status s = stub_->Echo(&context, request, &response);
894  EXPECT_EQ(response.message(), request.message());
895  if (GetParam().credentials_type() == kTlsCredentialsType) {
896  // SSL creds overrides the authority.
897  EXPECT_EQ("foo.test.google.fr", response.param().host());
898  } else if (GetParam().inproc()) {
899  EXPECT_EQ("inproc", response.param().host());
900  } else {
901  EXPECT_EQ(server_address_.str(), response.param().host());
902  }
903  EXPECT_TRUE(s.ok());
904 }
905 
906 TEST_P(End2endTest, ReconnectChannel) {
907  if (GetParam().inproc()) {
908  return;
909  }
910  int poller_slowdown_factor = 1;
911  // It needs 2 pollset_works to reconnect the channel with polling engine
912  // "poll"
913 #ifdef GRPC_POSIX_SOCKET_EV
914  grpc_core::UniquePtr<char> poller = GPR_GLOBAL_CONFIG_GET(grpc_poll_strategy);
915  if (0 == strcmp(poller.get(), "poll")) {
916  poller_slowdown_factor = 2;
917  }
918 #endif // GRPC_POSIX_SOCKET_EV
919  ResetStub();
920  SendRpc(stub_.get(), 1, false);
921  RestartServer(std::shared_ptr<AuthMetadataProcessor>());
922  // It needs more than GRPC_CLIENT_CHANNEL_BACKUP_POLL_INTERVAL_MS time to
923  // reconnect the channel. Make it a factor of 5x
926  gpr_time_from_millis(kClientChannelBackupPollIntervalMs * 5 *
927  poller_slowdown_factor *
929  GPR_TIMESPAN)));
930  SendRpc(stub_.get(), 1, false);
931 }
932 
933 TEST_P(End2endTest, RequestStreamOneRequest) {
934  ResetStub();
935  EchoRequest request;
936  EchoResponse response;
937  ClientContext context;
938 
939  auto stream = stub_->RequestStream(&context, &response);
940  request.set_message("hello");
941  EXPECT_TRUE(stream->Write(request));
942  stream->WritesDone();
943  Status s = stream->Finish();
944  EXPECT_EQ(response.message(), request.message());
945  EXPECT_TRUE(s.ok());
947 }
948 
949 TEST_P(End2endTest, RequestStreamOneRequestWithCoalescingApi) {
950  ResetStub();
951  EchoRequest request;
952  EchoResponse response;
953  ClientContext context;
954 
956  auto stream = stub_->RequestStream(&context, &response);
957  request.set_message("hello");
958  stream->WriteLast(request, WriteOptions());
959  Status s = stream->Finish();
960  EXPECT_EQ(response.message(), request.message());
961  EXPECT_TRUE(s.ok());
962 }
963 
964 TEST_P(End2endTest, RequestStreamTwoRequests) {
965  ResetStub();
966  EchoRequest request;
967  EchoResponse response;
968  ClientContext context;
969 
970  auto stream = stub_->RequestStream(&context, &response);
971  request.set_message("hello");
972  EXPECT_TRUE(stream->Write(request));
973  EXPECT_TRUE(stream->Write(request));
974  stream->WritesDone();
975  Status s = stream->Finish();
976  EXPECT_EQ(response.message(), "hellohello");
977  EXPECT_TRUE(s.ok());
978 }
979 
980 TEST_P(End2endTest, RequestStreamTwoRequestsWithWriteThrough) {
981  ResetStub();
982  EchoRequest request;
983  EchoResponse response;
984  ClientContext context;
985 
986  auto stream = stub_->RequestStream(&context, &response);
987  request.set_message("hello");
988  EXPECT_TRUE(stream->Write(request, WriteOptions().set_write_through()));
989  EXPECT_TRUE(stream->Write(request, WriteOptions().set_write_through()));
990  stream->WritesDone();
991  Status s = stream->Finish();
992  EXPECT_EQ(response.message(), "hellohello");
993  EXPECT_TRUE(s.ok());
994 }
995 
996 TEST_P(End2endTest, RequestStreamTwoRequestsWithCoalescingApi) {
997  ResetStub();
998  EchoRequest request;
999  EchoResponse response;
1000  ClientContext context;
1001 
1003  auto stream = stub_->RequestStream(&context, &response);
1004  request.set_message("hello");
1005  EXPECT_TRUE(stream->Write(request));
1006  stream->WriteLast(request, WriteOptions());
1007  Status s = stream->Finish();
1008  EXPECT_EQ(response.message(), "hellohello");
1009  EXPECT_TRUE(s.ok());
1010 }
1011 
1012 TEST_P(End2endTest, ResponseStream) {
1013  ResetStub();
1014  EchoRequest request;
1015  EchoResponse response;
1016  ClientContext context;
1017  request.set_message("hello");
1018 
1019  auto stream = stub_->ResponseStream(&context, request);
1020  for (int i = 0; i < kServerDefaultResponseStreamsToSend; ++i) {
1021  EXPECT_TRUE(stream->Read(&response));
1022  EXPECT_EQ(response.message(), request.message() + std::to_string(i));
1023  }
1024  EXPECT_FALSE(stream->Read(&response));
1025 
1026  Status s = stream->Finish();
1027  EXPECT_TRUE(s.ok());
1028 }
1029 
1030 TEST_P(End2endTest, ResponseStreamWithCoalescingApi) {
1031  ResetStub();
1032  EchoRequest request;
1033  EchoResponse response;
1034  ClientContext context;
1035  request.set_message("hello");
1037 
1038  auto stream = stub_->ResponseStream(&context, request);
1039  for (int i = 0; i < kServerDefaultResponseStreamsToSend; ++i) {
1040  EXPECT_TRUE(stream->Read(&response));
1041  EXPECT_EQ(response.message(), request.message() + std::to_string(i));
1042  }
1043  EXPECT_FALSE(stream->Read(&response));
1044 
1045  Status s = stream->Finish();
1046  EXPECT_TRUE(s.ok());
1047 }
1048 
1049 // This was added to prevent regression from issue:
1050 // https://github.com/grpc/grpc/issues/11546
1051 TEST_P(End2endTest, ResponseStreamWithEverythingCoalesced) {
1052  ResetStub();
1053  EchoRequest request;
1054  EchoResponse response;
1055  ClientContext context;
1056  request.set_message("hello");
1058  // We will only send one message, forcing everything (init metadata, message,
1059  // trailing) to be coalesced together.
1061 
1062  auto stream = stub_->ResponseStream(&context, request);
1063  EXPECT_TRUE(stream->Read(&response));
1064  EXPECT_EQ(response.message(), request.message() + "0");
1065 
1066  EXPECT_FALSE(stream->Read(&response));
1067 
1068  Status s = stream->Finish();
1069  EXPECT_TRUE(s.ok());
1070 }
1071 
1072 TEST_P(End2endTest, BidiStream) {
1073  ResetStub();
1074  EchoRequest request;
1075  EchoResponse response;
1076  ClientContext context;
1077  std::string msg("hello");
1078 
1079  auto stream = stub_->BidiStream(&context);
1080 
1081  for (int i = 0; i < kServerDefaultResponseStreamsToSend; ++i) {
1082  request.set_message(msg + std::to_string(i));
1083  EXPECT_TRUE(stream->Write(request));
1084  EXPECT_TRUE(stream->Read(&response));
1085  EXPECT_EQ(response.message(), request.message());
1086  }
1087 
1088  stream->WritesDone();
1089  EXPECT_FALSE(stream->Read(&response));
1090  EXPECT_FALSE(stream->Read(&response));
1091 
1092  Status s = stream->Finish();
1093  EXPECT_TRUE(s.ok());
1094 }
1095 
1096 TEST_P(End2endTest, BidiStreamWithCoalescingApi) {
1097  ResetStub();
1098  EchoRequest request;
1099  EchoResponse response;
1100  ClientContext context;
1103  std::string msg("hello");
1104 
1105  auto stream = stub_->BidiStream(&context);
1106 
1107  request.set_message(msg + "0");
1108  EXPECT_TRUE(stream->Write(request));
1109  EXPECT_TRUE(stream->Read(&response));
1110  EXPECT_EQ(response.message(), request.message());
1111 
1112  request.set_message(msg + "1");
1113  EXPECT_TRUE(stream->Write(request));
1114  EXPECT_TRUE(stream->Read(&response));
1115  EXPECT_EQ(response.message(), request.message());
1116 
1117  request.set_message(msg + "2");
1118  stream->WriteLast(request, WriteOptions());
1119  EXPECT_TRUE(stream->Read(&response));
1120  EXPECT_EQ(response.message(), request.message());
1121 
1122  EXPECT_FALSE(stream->Read(&response));
1123  EXPECT_FALSE(stream->Read(&response));
1124 
1125  Status s = stream->Finish();
1126  EXPECT_TRUE(s.ok());
1127 }
1128 
1129 // This was added to prevent regression from issue:
1130 // https://github.com/grpc/grpc/issues/11546
1131 TEST_P(End2endTest, BidiStreamWithEverythingCoalesced) {
1132  ResetStub();
1133  EchoRequest request;
1134  EchoResponse response;
1135  ClientContext context;
1138  std::string msg("hello");
1139 
1140  auto stream = stub_->BidiStream(&context);
1141 
1142  request.set_message(msg + "0");
1143  stream->WriteLast(request, WriteOptions());
1144  EXPECT_TRUE(stream->Read(&response));
1145  EXPECT_EQ(response.message(), request.message());
1146 
1147  EXPECT_FALSE(stream->Read(&response));
1148  EXPECT_FALSE(stream->Read(&response));
1149 
1150  Status s = stream->Finish();
1151  EXPECT_TRUE(s.ok());
1152 }
1153 
1154 // Talk to the two services with the same name but different package names.
1155 // The two stubs are created on the same channel.
1156 TEST_P(End2endTest, DiffPackageServices) {
1157  ResetStub();
1158  EchoRequest request;
1159  EchoResponse response;
1160  request.set_message("Hello");
1161 
1162  ClientContext context;
1163  Status s = stub_->Echo(&context, request, &response);
1164  EXPECT_EQ(response.message(), request.message());
1165  EXPECT_TRUE(s.ok());
1166 
1167  std::unique_ptr<grpc::testing::duplicate::EchoTestService::Stub> dup_pkg_stub(
1168  grpc::testing::duplicate::EchoTestService::NewStub(channel_));
1169  ClientContext context2;
1170  s = dup_pkg_stub->Echo(&context2, request, &response);
1171  EXPECT_EQ("no package", response.message());
1172  EXPECT_TRUE(s.ok());
1173 }
1174 
1175 template <class ServiceType>
1176 void CancelRpc(ClientContext* context, int delay_us, ServiceType* service) {
1178  gpr_time_from_micros(delay_us, GPR_TIMESPAN)));
1179  while (!service->signal_client()) {
1180  }
1181  context->TryCancel();
1182 }
1183 
1184 TEST_P(End2endTest, CancelRpcBeforeStart) {
1185  ResetStub();
1186  EchoRequest request;
1187  EchoResponse response;
1188  ClientContext context;
1189  request.set_message("hello");
1190  context.TryCancel();
1191  Status s = stub_->Echo(&context, request, &response);
1192  EXPECT_EQ("", response.message());
1193  EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
1194  if (GetParam().use_interceptors()) {
1196  }
1197 }
1198 
1199 TEST_P(End2endTest, CancelRpcAfterStart) {
1200  ResetStub();
1201  EchoRequest request;
1202  EchoResponse response;
1203  ClientContext context;
1204  request.set_message("hello");
1205  request.mutable_param()->set_server_notify_client_when_started(true);
1206  request.mutable_param()->set_skip_cancelled_check(true);
1207  Status s;
1208  std::thread echo_thread([this, &s, &context, &request, &response] {
1209  s = stub_->Echo(&context, request, &response);
1210  EXPECT_EQ(StatusCode::CANCELLED, s.error_code());
1211  });
1212  if (!GetParam().callback_server()) {
1213  service_.ClientWaitUntilRpcStarted();
1214  } else {
1215  callback_service_.ClientWaitUntilRpcStarted();
1216  }
1217 
1218  context.TryCancel();
1219 
1220  if (!GetParam().callback_server()) {
1221  service_.SignalServerToContinue();
1222  } else {
1223  callback_service_.SignalServerToContinue();
1224  }
1225 
1226  echo_thread.join();
1227  EXPECT_EQ("", response.message());
1228  EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
1229  if (GetParam().use_interceptors()) {
1231  }
1232 }
1233 
1234 // Client cancels request stream after sending two messages
1235 TEST_P(End2endTest, ClientCancelsRequestStream) {
1236  ResetStub();
1237  EchoRequest request;
1238  EchoResponse response;
1239  ClientContext context;
1240  request.set_message("hello");
1241 
1242  auto stream = stub_->RequestStream(&context, &response);
1243  EXPECT_TRUE(stream->Write(request));
1244  EXPECT_TRUE(stream->Write(request));
1245 
1246  context.TryCancel();
1247 
1248  Status s = stream->Finish();
1249  EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
1250 
1251  EXPECT_EQ(response.message(), "");
1252  if (GetParam().use_interceptors()) {
1254  }
1255 }
1256 
1257 // Client cancels server stream after sending some messages
1258 TEST_P(End2endTest, ClientCancelsResponseStream) {
1259  ResetStub();
1260  EchoRequest request;
1261  EchoResponse response;
1262  ClientContext context;
1263  request.set_message("hello");
1264 
1265  auto stream = stub_->ResponseStream(&context, request);
1266 
1267  EXPECT_TRUE(stream->Read(&response));
1268  EXPECT_EQ(response.message(), request.message() + "0");
1269  EXPECT_TRUE(stream->Read(&response));
1270  EXPECT_EQ(response.message(), request.message() + "1");
1271 
1272  context.TryCancel();
1273 
1274  // The cancellation races with responses, so there might be zero or
1275  // one responses pending, read till failure
1276 
1277  if (stream->Read(&response)) {
1278  EXPECT_EQ(response.message(), request.message() + "2");
1279  // Since we have cancelled, we expect the next attempt to read to fail
1280  EXPECT_FALSE(stream->Read(&response));
1281  }
1282 
1283  Status s = stream->Finish();
1284  // The final status could be either of CANCELLED or OK depending on
1285  // who won the race.
1286  EXPECT_GE(grpc::StatusCode::CANCELLED, s.error_code());
1287  if (GetParam().use_interceptors()) {
1289  }
1290 }
1291 
1292 // Client cancels bidi stream after sending some messages
1293 TEST_P(End2endTest, ClientCancelsBidi) {
1294  ResetStub();
1295  EchoRequest request;
1296  EchoResponse response;
1297  ClientContext context;
1298  std::string msg("hello");
1299 
1300  // Send server_try_cancel value in the client metadata
1302 
1303  auto stream = stub_->BidiStream(&context);
1304 
1305  request.set_message(msg + "0");
1306  EXPECT_TRUE(stream->Write(request));
1307  EXPECT_TRUE(stream->Read(&response));
1308  EXPECT_EQ(response.message(), request.message());
1309 
1310  request.set_message(msg + "1");
1311  EXPECT_TRUE(stream->Write(request));
1312 
1313  context.TryCancel();
1314 
1315  // The cancellation races with responses, so there might be zero or
1316  // one responses pending, read till failure
1317 
1318  if (stream->Read(&response)) {
1319  EXPECT_EQ(response.message(), request.message());
1320  // Since we have cancelled, we expect the next attempt to read to fail
1321  EXPECT_FALSE(stream->Read(&response));
1322  }
1323 
1324  Status s = stream->Finish();
1325  EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
1326  if (GetParam().use_interceptors()) {
1328  }
1329 }
1330 
1331 TEST_P(End2endTest, RpcMaxMessageSize) {
1332  ResetStub();
1333  EchoRequest request;
1334  EchoResponse response;
1335  request.set_message(string(kMaxMessageSize_ * 2, 'a'));
1336  request.mutable_param()->set_server_die(true);
1337 
1338  ClientContext context;
1339  Status s = stub_->Echo(&context, request, &response);
1340  EXPECT_FALSE(s.ok());
1341 }
1342 
1343 void ReaderThreadFunc(ClientReaderWriter<EchoRequest, EchoResponse>* stream,
1344  gpr_event* ev) {
1345  EchoResponse resp;
1346  gpr_event_set(ev, reinterpret_cast<void*>(1));
1347  while (stream->Read(&resp)) {
1348  gpr_log(GPR_INFO, "Read message");
1349  }
1350 }
1351 
1352 // Run a Read and a WritesDone simultaneously.
1353 TEST_P(End2endTest, SimultaneousReadWritesDone) {
1354  ResetStub();
1355  ClientContext context;
1356  gpr_event ev;
1357  gpr_event_init(&ev);
1358  auto stream = stub_->BidiStream(&context);
1359  std::thread reader_thread(ReaderThreadFunc, stream.get(), &ev);
1361  stream->WritesDone();
1362  reader_thread.join();
1363  Status s = stream->Finish();
1364  EXPECT_TRUE(s.ok());
1365 }
1366 
1367 TEST_P(End2endTest, ChannelState) {
1368  if (GetParam().inproc()) {
1369  return;
1370  }
1371 
1372  ResetStub();
1373  // Start IDLE
1374  EXPECT_EQ(GRPC_CHANNEL_IDLE, channel_->GetState(false));
1375 
1376  // Did not ask to connect, no state change.
1377  CompletionQueue cq;
1379  std::chrono::system_clock::now() + std::chrono::milliseconds(10);
1380  channel_->NotifyOnStateChange(GRPC_CHANNEL_IDLE, deadline, &cq, nullptr);
1381  void* tag;
1382  bool ok = true;
1383  cq.Next(&tag, &ok);
1384  EXPECT_FALSE(ok);
1385 
1386  EXPECT_EQ(GRPC_CHANNEL_IDLE, channel_->GetState(true));
1387  EXPECT_TRUE(channel_->WaitForStateChange(GRPC_CHANNEL_IDLE,
1389  auto state = channel_->GetState(false);
1391 }
1392 
1393 // Takes 10s.
1394 TEST_P(End2endTest, ChannelStateTimeout) {
1395  if ((GetParam().credentials_type() != kInsecureCredentialsType) ||
1396  GetParam().inproc()) {
1397  return;
1398  }
1400  std::ostringstream server_address;
1401  server_address << "localhost:" << port;
1402  // Channel to non-existing server
1403  auto channel =
1405  // Start IDLE
1406  EXPECT_EQ(GRPC_CHANNEL_IDLE, channel->GetState(true));
1407 
1408  auto state = GRPC_CHANNEL_IDLE;
1409  for (int i = 0; i < 10; i++) {
1410  channel->WaitForStateChange(
1412  state = channel->GetState(false);
1413  }
1414 }
1415 
1416 TEST_P(End2endTest, ChannelStateOnLameChannel) {
1417  if ((GetParam().credentials_type() != kInsecureCredentialsType) ||
1418  GetParam().inproc()) {
1419  return;
1420  }
1421  // Channel using invalid target URI. This creates a lame channel.
1423  // Channel should immediately report TRANSIENT_FAILURE.
1425  // And state will never change.
1427  for (int i = 0; i < 10; ++i) {
1428  channel->WaitForStateChange(
1430  state = channel->GetState(false);
1431  }
1432 }
1433 
1434 // Talking to a non-existing service.
1435 TEST_P(End2endTest, NonExistingService) {
1436  ResetChannel();
1437  std::unique_ptr<grpc::testing::UnimplementedEchoService::Stub> stub;
1438  stub = grpc::testing::UnimplementedEchoService::NewStub(channel_);
1439 
1440  EchoRequest request;
1441  EchoResponse response;
1442  request.set_message("Hello");
1443 
1444  ClientContext context;
1445  Status s = stub->Unimplemented(&context, request, &response);
1446  EXPECT_EQ(StatusCode::UNIMPLEMENTED, s.error_code());
1447  EXPECT_EQ("", s.error_message());
1448 }
1449 
1450 // Ask the server to send back a serialized proto in trailer.
1451 // This is an example of setting error details.
1452 TEST_P(End2endTest, BinaryTrailerTest) {
1453  ResetStub();
1454  EchoRequest request;
1455  EchoResponse response;
1456  ClientContext context;
1457 
1458  request.mutable_param()->set_echo_metadata(true);
1459  DebugInfo* info = request.mutable_param()->mutable_debug_info();
1460  info->add_stack_entries("stack_entry_1");
1461  info->add_stack_entries("stack_entry_2");
1462  info->add_stack_entries("stack_entry_3");
1463  info->set_detail("detailed debug info");
1464  std::string expected_string = info->SerializeAsString();
1465  request.set_message("Hello");
1466 
1467  Status s = stub_->Echo(&context, request, &response);
1468  EXPECT_FALSE(s.ok());
1469  auto trailers = context.GetServerTrailingMetadata();
1470  EXPECT_EQ(1u, trailers.count(kDebugInfoTrailerKey));
1471  auto iter = trailers.find(kDebugInfoTrailerKey);
1472  EXPECT_EQ(expected_string, iter->second);
1473  // Parse the returned trailer into a DebugInfo proto.
1474  DebugInfo returned_info;
1475  EXPECT_TRUE(returned_info.ParseFromString(ToString(iter->second)));
1476 }
1477 
1478 TEST_P(End2endTest, ExpectErrorTest) {
1479  ResetStub();
1480 
1481  std::vector<ErrorStatus> expected_status;
1482  expected_status.emplace_back();
1483  expected_status.back().set_code(13); // INTERNAL
1484  // No Error message or details
1485 
1486  expected_status.emplace_back();
1487  expected_status.back().set_code(13); // INTERNAL
1488  expected_status.back().set_error_message("text error message");
1489  expected_status.back().set_binary_error_details("text error details");
1490 
1491  expected_status.emplace_back();
1492  expected_status.back().set_code(13); // INTERNAL
1493  expected_status.back().set_error_message("text error message");
1494  expected_status.back().set_binary_error_details(
1495  "\x0\x1\x2\x3\x4\x5\x6\x8\x9\xA\xB");
1496 
1497  for (auto iter = expected_status.begin(); iter != expected_status.end();
1498  ++iter) {
1499  EchoRequest request;
1500  EchoResponse response;
1501  ClientContext context;
1502  request.set_message("Hello");
1503  auto* error = request.mutable_param()->mutable_expected_error();
1504  error->set_code(iter->code());
1505  error->set_error_message(iter->error_message());
1506  error->set_binary_error_details(iter->binary_error_details());
1507 
1508  Status s = stub_->Echo(&context, request, &response);
1509  EXPECT_FALSE(s.ok());
1510  EXPECT_EQ(iter->code(), s.error_code());
1511  EXPECT_EQ(iter->error_message(), s.error_message());
1512  EXPECT_EQ(iter->binary_error_details(), s.error_details());
1514 #ifndef NDEBUG
1515  // GRPC_ERROR_INT_FILE_LINE is for debug only
1518 #endif
1521  }
1522 }
1523 
1525 // Test with and without a proxy.
1526 class ProxyEnd2endTest : public End2endTest {
1527  protected:
1528 };
1529 
1530 TEST_P(ProxyEnd2endTest, SimpleRpc) {
1531  ResetStub();
1532  SendRpc(stub_.get(), 1, false);
1533 }
1534 
1535 TEST_P(ProxyEnd2endTest, SimpleRpcWithEmptyMessages) {
1536  ResetStub();
1537  EchoRequest request;
1538  EchoResponse response;
1539 
1540  ClientContext context;
1541  Status s = stub_->Echo(&context, request, &response);
1542  EXPECT_TRUE(s.ok());
1543 }
1544 
1545 TEST_P(ProxyEnd2endTest, MultipleRpcs) {
1546  ResetStub();
1547  std::vector<std::thread> threads;
1548  threads.reserve(10);
1549  for (int i = 0; i < 10; ++i) {
1550  threads.emplace_back(SendRpc, stub_.get(), 10, false);
1551  }
1552  for (int i = 0; i < 10; ++i) {
1553  threads[i].join();
1554  }
1555 }
1556 
1557 // Set a 10us deadline and make sure proper error is returned.
1558 TEST_P(ProxyEnd2endTest, RpcDeadlineExpires) {
1559  ResetStub();
1560  EchoRequest request;
1561  EchoResponse response;
1562  request.set_message("Hello");
1563  request.mutable_param()->set_skip_cancelled_check(true);
1564  // Let server sleep for 40 ms first to guarantee expiry.
1565  // 40 ms might seem a bit extreme but the timer manager would have been just
1566  // initialized (when ResetStub() was called) and there are some warmup costs
1567  // i.e the timer thread many not have even started. There might also be other
1568  // delays in the timer manager thread (in acquiring locks, timer data
1569  // structure manipulations, starting backup timer threads) that add to the
1570  // delays. 40ms is still not enough in some cases but this significantly
1571  // reduces the test flakes
1572  request.mutable_param()->set_server_sleep_us(40 * 1000);
1573 
1574  ClientContext context;
1576  std::chrono::system_clock::now() + std::chrono::milliseconds(1);
1577  context.set_deadline(deadline);
1578  Status s = stub_->Echo(&context, request, &response);
1579  EXPECT_EQ(StatusCode::DEADLINE_EXCEEDED, s.error_code());
1580 }
1581 
1582 // Set a long but finite deadline.
1583 TEST_P(ProxyEnd2endTest, RpcLongDeadline) {
1584  ResetStub();
1585  EchoRequest request;
1586  EchoResponse response;
1587  request.set_message("Hello");
1588 
1589  ClientContext context;
1591  std::chrono::system_clock::now() + std::chrono::hours(1);
1592  context.set_deadline(deadline);
1593  Status s = stub_->Echo(&context, request, &response);
1594  EXPECT_EQ(response.message(), request.message());
1595  EXPECT_TRUE(s.ok());
1596 }
1597 
1598 // Ask server to echo back the deadline it sees.
1599 TEST_P(ProxyEnd2endTest, EchoDeadline) {
1600  ResetStub();
1601  EchoRequest request;
1602  EchoResponse response;
1603  request.set_message("Hello");
1604  request.mutable_param()->set_echo_deadline(true);
1605 
1606  ClientContext context;
1609  context.set_deadline(deadline);
1610  Status s = stub_->Echo(&context, request, &response);
1611  EXPECT_EQ(response.message(), request.message());
1612  EXPECT_TRUE(s.ok());
1613  gpr_timespec sent_deadline;
1614  Timepoint2Timespec(deadline, &sent_deadline);
1615  // We want to allow some reasonable error given:
1616  // - request_deadline() only has 1sec resolution so the best we can do is +-1
1617  // - if sent_deadline.tv_nsec is very close to the next second's boundary we
1618  // can end up being off by 2 in one direction.
1619  EXPECT_LE(response.param().request_deadline() - sent_deadline.tv_sec, 2);
1620  EXPECT_GE(response.param().request_deadline() - sent_deadline.tv_sec, -1);
1621 }
1622 
1623 // Ask server to echo back the deadline it sees. The rpc has no deadline.
1624 TEST_P(ProxyEnd2endTest, EchoDeadlineForNoDeadlineRpc) {
1625  ResetStub();
1626  EchoRequest request;
1627  EchoResponse response;
1628  request.set_message("Hello");
1629  request.mutable_param()->set_echo_deadline(true);
1630 
1631  ClientContext context;
1632  Status s = stub_->Echo(&context, request, &response);
1633  EXPECT_EQ(response.message(), request.message());
1634  EXPECT_TRUE(s.ok());
1635  EXPECT_EQ(response.param().request_deadline(),
1637 }
1638 
1639 TEST_P(ProxyEnd2endTest, UnimplementedRpc) {
1640  ResetStub();
1641  EchoRequest request;
1642  EchoResponse response;
1643  request.set_message("Hello");
1644 
1645  ClientContext context;
1646  Status s = stub_->Unimplemented(&context, request, &response);
1647  EXPECT_FALSE(s.ok());
1649  EXPECT_EQ(s.error_message(), "");
1650  EXPECT_EQ(response.message(), "");
1651 }
1652 
1653 // Client cancels rpc after 10ms
1654 TEST_P(ProxyEnd2endTest, ClientCancelsRpc) {
1655  ResetStub();
1656  EchoRequest request;
1657  EchoResponse response;
1658  request.set_message("Hello");
1659  const int kCancelDelayUs = 10 * 1000;
1660  request.mutable_param()->set_client_cancel_after_us(kCancelDelayUs);
1661 
1662  ClientContext context;
1663  std::thread cancel_thread;
1664  if (!GetParam().callback_server()) {
1665  cancel_thread = std::thread(
1666  [&context, this](int delay) { CancelRpc(&context, delay, &service_); },
1667  kCancelDelayUs);
1668  // Note: the unusual pattern above (and below) is caused by a conflict
1669  // between two sets of compiler expectations. clang allows const to be
1670  // captured without mention, so there is no need to capture kCancelDelayUs
1671  // (and indeed clang-tidy complains if you do so). OTOH, a Windows compiler
1672  // in our tests requires an explicit capture even for const. We square this
1673  // circle by passing the const value in as an argument to the lambda.
1674  } else {
1675  cancel_thread = std::thread(
1676  [&context, this](int delay) {
1677  CancelRpc(&context, delay, &callback_service_);
1678  },
1679  kCancelDelayUs);
1680  }
1681  Status s = stub_->Echo(&context, request, &response);
1682  cancel_thread.join();
1683  EXPECT_EQ(StatusCode::CANCELLED, s.error_code());
1684  EXPECT_EQ(s.error_message(), "CANCELLED");
1685 }
1686 
1687 // Server cancels rpc after 1ms
1688 TEST_P(ProxyEnd2endTest, ServerCancelsRpc) {
1689  ResetStub();
1690  EchoRequest request;
1691  EchoResponse response;
1692  request.set_message("Hello");
1693  request.mutable_param()->set_server_cancel_after_us(1000);
1694 
1695  ClientContext context;
1696  Status s = stub_->Echo(&context, request, &response);
1697  EXPECT_EQ(StatusCode::CANCELLED, s.error_code());
1698  EXPECT_TRUE(s.error_message().empty());
1699 }
1700 
1701 // Make the response larger than the flow control window.
1702 TEST_P(ProxyEnd2endTest, HugeResponse) {
1703  ResetStub();
1704  EchoRequest request;
1705  EchoResponse response;
1706  request.set_message("huge response");
1707  const size_t kResponseSize = 1024 * (1024 + 10);
1708  request.mutable_param()->set_response_message_length(kResponseSize);
1709 
1710  ClientContext context;
1713  context.set_deadline(deadline);
1714  Status s = stub_->Echo(&context, request, &response);
1715  EXPECT_EQ(kResponseSize, response.message().size());
1716  EXPECT_TRUE(s.ok());
1717 }
1718 
1719 TEST_P(ProxyEnd2endTest, Peer) {
1720  // Peer is not meaningful for inproc
1721  if (GetParam().inproc()) {
1722  return;
1723  }
1724  ResetStub();
1725  EchoRequest request;
1726  EchoResponse response;
1727  request.set_message("hello");
1728  request.mutable_param()->set_echo_peer(true);
1729 
1730  ClientContext context;
1731  Status s = stub_->Echo(&context, request, &response);
1732  EXPECT_EQ(response.message(), request.message());
1733  EXPECT_TRUE(s.ok());
1734  EXPECT_TRUE(CheckIsLocalhost(response.param().peer()));
1736 }
1737 
1739 class SecureEnd2endTest : public End2endTest {
1740  protected:
1741  SecureEnd2endTest() {
1742  GPR_ASSERT(!GetParam().use_proxy());
1744  }
1745 };
1746 
1747 TEST_P(SecureEnd2endTest, SimpleRpcWithHost) {
1748  ResetStub();
1749 
1750  EchoRequest request;
1751  EchoResponse response;
1752  request.set_message("Hello");
1753 
1754  ClientContext context;
1755  context.set_authority("foo.test.youtube.com");
1756  Status s = stub_->Echo(&context, request, &response);
1757  EXPECT_EQ(response.message(), request.message());
1758  EXPECT_TRUE(response.has_param());
1759  EXPECT_EQ("special", response.param().host());
1760  EXPECT_TRUE(s.ok());
1761 }
1762 
1763 bool MetadataContains(
1764  const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
1765  const std::string& key, const std::string& value) {
1766  int count = 0;
1767 
1768  for (std::multimap<grpc::string_ref, grpc::string_ref>::const_iterator iter =
1769  metadata.begin();
1770  iter != metadata.end(); ++iter) {
1771  if (ToString(iter->first) == key && ToString(iter->second) == value) {
1772  count++;
1773  }
1774  }
1775  return count == 1;
1776 }
1777 
1778 TEST_P(SecureEnd2endTest, BlockingAuthMetadataPluginAndProcessorSuccess) {
1779  auto* processor = new TestAuthMetadataProcessor(true);
1780  StartServer(std::shared_ptr<AuthMetadataProcessor>(processor));
1781  ResetStub();
1782  EchoRequest request;
1783  EchoResponse response;
1784  ClientContext context;
1785  context.set_credentials(processor->GetCompatibleClientCreds());
1786  request.set_message("Hello");
1787  request.mutable_param()->set_echo_metadata(true);
1788  request.mutable_param()->set_expected_client_identity(
1790  request.mutable_param()->set_expected_transport_security_type(
1791  GetParam().credentials_type());
1792 
1793  Status s = stub_->Echo(&context, request, &response);
1794  EXPECT_EQ(request.message(), response.message());
1795  EXPECT_TRUE(s.ok());
1796 
1797  // Metadata should have been consumed by the processor.
1798  EXPECT_FALSE(MetadataContains(
1801 }
1802 
1803 TEST_P(SecureEnd2endTest, BlockingAuthMetadataPluginAndProcessorFailure) {
1804  auto* processor = new TestAuthMetadataProcessor(true);
1805  StartServer(std::shared_ptr<AuthMetadataProcessor>(processor));
1806  ResetStub();
1807  EchoRequest request;
1808  EchoResponse response;
1809  ClientContext context;
1810  context.set_credentials(processor->GetIncompatibleClientCreds());
1811  request.set_message("Hello");
1812 
1813  Status s = stub_->Echo(&context, request, &response);
1814  EXPECT_FALSE(s.ok());
1815  EXPECT_EQ(s.error_code(), StatusCode::UNAUTHENTICATED);
1816 }
1817 
1818 TEST_P(SecureEnd2endTest, SetPerCallCredentials) {
1819  ResetStub();
1820  EchoRequest request;
1821  EchoResponse response;
1822  ClientContext context;
1823  std::shared_ptr<CallCredentials> creds =
1824  GoogleIAMCredentials(kFakeToken, kFakeSelector);
1825  context.set_credentials(creds);
1826  request.set_message("Hello");
1827  request.mutable_param()->set_echo_metadata(true);
1828 
1829  Status s = stub_->Echo(&context, request, &response);
1830  EXPECT_EQ(request.message(), response.message());
1831  EXPECT_TRUE(s.ok());
1832  EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
1834  kFakeToken));
1835  EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
1837  kFakeSelector));
1838  EXPECT_EQ(context.credentials()->DebugString(),
1839  kExpectedFakeCredsDebugString);
1840 }
1841 
1842 class CredentialsInterceptor : public experimental::Interceptor {
1843  public:
1844  explicit CredentialsInterceptor(experimental::ClientRpcInfo* info)
1845  : info_(info) {}
1846 
1847  void Intercept(experimental::InterceptorBatchMethods* methods) override {
1848  if (methods->QueryInterceptionHookPoint(
1850  std::shared_ptr<CallCredentials> creds =
1851  GoogleIAMCredentials(kFakeToken, kFakeSelector);
1852  info_->client_context()->set_credentials(creds);
1853  }
1854  methods->Proceed();
1855  }
1856 
1857  private:
1858  experimental::ClientRpcInfo* info_ = nullptr;
1859 };
1860 
1861 class CredentialsInterceptorFactory
1862  : public experimental::ClientInterceptorFactoryInterface {
1863  CredentialsInterceptor* CreateClientInterceptor(
1864  experimental::ClientRpcInfo* info) override {
1865  return new CredentialsInterceptor(info);
1866  }
1867 };
1868 
1869 TEST_P(SecureEnd2endTest, CallCredentialsInterception) {
1870  if (!GetParam().use_interceptors()) {
1871  return;
1872  }
1873  std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
1874  interceptor_creators;
1875  interceptor_creators.push_back(
1876  absl::make_unique<CredentialsInterceptorFactory>());
1877  ResetStub(std::move(interceptor_creators));
1878  EchoRequest request;
1879  EchoResponse response;
1880  ClientContext context;
1881 
1882  request.set_message("Hello");
1883  request.mutable_param()->set_echo_metadata(true);
1884 
1885  Status s = stub_->Echo(&context, request, &response);
1886  EXPECT_EQ(request.message(), response.message());
1887  EXPECT_TRUE(s.ok());
1888  EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
1890  kFakeToken));
1891  EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
1893  kFakeSelector));
1894  EXPECT_EQ(context.credentials()->DebugString(),
1895  kExpectedFakeCredsDebugString);
1896 }
1897 
1898 TEST_P(SecureEnd2endTest, CallCredentialsInterceptionWithSetCredentials) {
1899  if (!GetParam().use_interceptors()) {
1900  return;
1901  }
1902  std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
1903  interceptor_creators;
1904  interceptor_creators.push_back(
1905  absl::make_unique<CredentialsInterceptorFactory>());
1906  ResetStub(std::move(interceptor_creators));
1907  EchoRequest request;
1908  EchoResponse response;
1909  ClientContext context;
1910  std::shared_ptr<CallCredentials> creds1 =
1911  GoogleIAMCredentials(kWrongToken, kWrongSelector);
1912  context.set_credentials(creds1);
1913  EXPECT_EQ(context.credentials(), creds1);
1914  EXPECT_EQ(context.credentials()->DebugString(),
1915  kExpectedWrongCredsDebugString);
1916  request.set_message("Hello");
1917  request.mutable_param()->set_echo_metadata(true);
1918 
1919  Status s = stub_->Echo(&context, request, &response);
1920  EXPECT_EQ(request.message(), response.message());
1921  EXPECT_TRUE(s.ok());
1922  EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
1924  kFakeToken));
1925  EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
1927  kFakeSelector));
1928  EXPECT_EQ(context.credentials()->DebugString(),
1929  kExpectedFakeCredsDebugString);
1930 }
1931 
1932 TEST_P(SecureEnd2endTest, OverridePerCallCredentials) {
1933  ResetStub();
1934  EchoRequest request;
1935  EchoResponse response;
1936  ClientContext context;
1937  std::shared_ptr<CallCredentials> creds1 =
1938  GoogleIAMCredentials(kFakeToken1, kFakeSelector1);
1939  context.set_credentials(creds1);
1940  EXPECT_EQ(context.credentials(), creds1);
1941  EXPECT_EQ(context.credentials()->DebugString(),
1942  kExpectedFakeCreds1DebugString);
1943  std::shared_ptr<CallCredentials> creds2 =
1944  GoogleIAMCredentials(kFakeToken2, kFakeSelector2);
1945  context.set_credentials(creds2);
1946  EXPECT_EQ(context.credentials(), creds2);
1947  request.set_message("Hello");
1948  request.mutable_param()->set_echo_metadata(true);
1949 
1950  Status s = stub_->Echo(&context, request, &response);
1951  EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
1953  kFakeToken2));
1954  EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
1956  kFakeSelector2));
1957  EXPECT_FALSE(MetadataContains(context.GetServerTrailingMetadata(),
1959  kFakeToken1));
1960  EXPECT_FALSE(MetadataContains(context.GetServerTrailingMetadata(),
1962  kFakeSelector1));
1963  EXPECT_EQ(context.credentials()->DebugString(),
1964  kExpectedFakeCreds2DebugString);
1965  EXPECT_EQ(request.message(), response.message());
1966  EXPECT_TRUE(s.ok());
1967 }
1968 
1969 TEST_P(SecureEnd2endTest, AuthMetadataPluginKeyFailure) {
1970  ResetStub();
1971  EchoRequest request;
1972  EchoResponse response;
1973  ClientContext context;
1975  std::unique_ptr<MetadataCredentialsPlugin>(
1976  new TestMetadataCredentialsPlugin(
1978  "Does not matter, will fail the key is invalid.", false, true,
1979  0))));
1980  request.set_message("Hello");
1981 
1982  Status s = stub_->Echo(&context, request, &response);
1983  EXPECT_FALSE(s.ok());
1984  EXPECT_EQ(s.error_code(), StatusCode::UNAVAILABLE);
1985  EXPECT_EQ(context.credentials()->DebugString(),
1986  kExpectedAuthMetadataPluginKeyFailureCredsDebugString);
1987 }
1988 
1989 TEST_P(SecureEnd2endTest, AuthMetadataPluginValueFailure) {
1990  ResetStub();
1991  EchoRequest request;
1992  EchoResponse response;
1993  ClientContext context;
1995  std::unique_ptr<MetadataCredentialsPlugin>(
1996  new TestMetadataCredentialsPlugin(
1998  "With illegal \n value.", false, true, 0))));
1999  request.set_message("Hello");
2000 
2001  Status s = stub_->Echo(&context, request, &response);
2002  EXPECT_FALSE(s.ok());
2003  EXPECT_EQ(s.error_code(), StatusCode::UNAVAILABLE);
2004  EXPECT_EQ(context.credentials()->DebugString(),
2005  kExpectedAuthMetadataPluginValueFailureCredsDebugString);
2006 }
2007 
2008 TEST_P(SecureEnd2endTest, AuthMetadataPluginWithDeadline) {
2009  ResetStub();
2010  EchoRequest request;
2011  request.mutable_param()->set_skip_cancelled_check(true);
2012  EchoResponse response;
2013  ClientContext context;
2014  const int delay = 100;
2016  std::chrono::system_clock::now() + std::chrono::milliseconds(delay);
2017  context.set_deadline(deadline);
2019  std::unique_ptr<MetadataCredentialsPlugin>(
2020  new TestMetadataCredentialsPlugin("meta_key", "Does not matter", true,
2021  true, delay))));
2022  request.set_message("Hello");
2023 
2024  Status s = stub_->Echo(&context, request, &response);
2025  if (!s.ok()) {
2026  EXPECT_TRUE(s.error_code() == StatusCode::DEADLINE_EXCEEDED ||
2027  s.error_code() == StatusCode::UNAVAILABLE);
2028  }
2029  EXPECT_EQ(context.credentials()->DebugString(),
2030  kExpectedAuthMetadataPluginWithDeadlineCredsDebugString);
2031 }
2032 
2033 TEST_P(SecureEnd2endTest, AuthMetadataPluginWithCancel) {
2034  ResetStub();
2035  EchoRequest request;
2036  request.mutable_param()->set_skip_cancelled_check(true);
2037  EchoResponse response;
2038  ClientContext context;
2039  const int delay = 100;
2041  std::unique_ptr<MetadataCredentialsPlugin>(
2042  new TestMetadataCredentialsPlugin("meta_key", "Does not matter", true,
2043  true, delay))));
2044  request.set_message("Hello");
2045 
2046  std::thread cancel_thread([&] {
2049  context.TryCancel();
2050  });
2051  Status s = stub_->Echo(&context, request, &response);
2052  if (!s.ok()) {
2053  EXPECT_TRUE(s.error_code() == StatusCode::CANCELLED ||
2054  s.error_code() == StatusCode::UNAVAILABLE);
2055  }
2056  cancel_thread.join();
2057  EXPECT_EQ(context.credentials()->DebugString(),
2058  kExpectedAuthMetadataPluginWithDeadlineCredsDebugString);
2059 }
2060 
2061 TEST_P(SecureEnd2endTest, NonBlockingAuthMetadataPluginFailure) {
2062  ResetStub();
2063  EchoRequest request;
2064  EchoResponse response;
2065  ClientContext context;
2067  std::unique_ptr<MetadataCredentialsPlugin>(
2068  new TestMetadataCredentialsPlugin(
2070  "Does not matter, will fail anyway (see 3rd param)", false, false,
2071  0))));
2072  request.set_message("Hello");
2073 
2074  Status s = stub_->Echo(&context, request, &response);
2075  EXPECT_FALSE(s.ok());
2076  EXPECT_EQ(s.error_code(), StatusCode::UNAVAILABLE);
2077  EXPECT_EQ(s.error_message(),
2078  std::string("Getting metadata from plugin failed with error: ") +
2079  kTestCredsPluginErrorMsg);
2080  EXPECT_EQ(context.credentials()->DebugString(),
2081  kExpectedNonBlockingAuthMetadataPluginFailureCredsDebugString);
2082 }
2083 
2084 TEST_P(SecureEnd2endTest, NonBlockingAuthMetadataPluginAndProcessorSuccess) {
2085  auto* processor = new TestAuthMetadataProcessor(false);
2086  StartServer(std::shared_ptr<AuthMetadataProcessor>(processor));
2087  ResetStub();
2088  EchoRequest request;
2089  EchoResponse response;
2090  ClientContext context;
2091  context.set_credentials(processor->GetCompatibleClientCreds());
2092  request.set_message("Hello");
2093  request.mutable_param()->set_echo_metadata(true);
2094  request.mutable_param()->set_expected_client_identity(
2096  request.mutable_param()->set_expected_transport_security_type(
2097  GetParam().credentials_type());
2098 
2099  Status s = stub_->Echo(&context, request, &response);
2100  EXPECT_EQ(request.message(), response.message());
2101  EXPECT_TRUE(s.ok());
2102 
2103  // Metadata should have been consumed by the processor.
2104  EXPECT_FALSE(MetadataContains(
2107  EXPECT_EQ(
2108  context.credentials()->DebugString(),
2109  kExpectedNonBlockingAuthMetadataPluginAndProcessorSuccessCredsDebugString);
2110 }
2111 
2112 TEST_P(SecureEnd2endTest, NonBlockingAuthMetadataPluginAndProcessorFailure) {
2113  auto* processor = new TestAuthMetadataProcessor(false);
2114  StartServer(std::shared_ptr<AuthMetadataProcessor>(processor));
2115  ResetStub();
2116  EchoRequest request;
2117  EchoResponse response;
2118  ClientContext context;
2119  context.set_credentials(processor->GetIncompatibleClientCreds());
2120  request.set_message("Hello");
2121 
2122  Status s = stub_->Echo(&context, request, &response);
2123  EXPECT_FALSE(s.ok());
2124  EXPECT_EQ(s.error_code(), StatusCode::UNAUTHENTICATED);
2125  EXPECT_EQ(
2126  context.credentials()->DebugString(),
2127  kExpectedNonBlockingAuthMetadataPluginAndProcessorFailureCredsDebugString);
2128 }
2129 
2130 TEST_P(SecureEnd2endTest, BlockingAuthMetadataPluginFailure) {
2131  ResetStub();
2132  EchoRequest request;
2133  EchoResponse response;
2134  ClientContext context;
2136  std::unique_ptr<MetadataCredentialsPlugin>(
2137  new TestMetadataCredentialsPlugin(
2139  "Does not matter, will fail anyway (see 3rd param)", true, false,
2140  0))));
2141  request.set_message("Hello");
2142 
2143  Status s = stub_->Echo(&context, request, &response);
2144  EXPECT_FALSE(s.ok());
2145  EXPECT_EQ(s.error_code(), StatusCode::UNAVAILABLE);
2146  EXPECT_EQ(s.error_message(),
2147  std::string("Getting metadata from plugin failed with error: ") +
2148  kTestCredsPluginErrorMsg);
2149  EXPECT_EQ(context.credentials()->DebugString(),
2150  kExpectedBlockingAuthMetadataPluginFailureCredsDebugString);
2151 }
2152 
2153 TEST_P(SecureEnd2endTest, CompositeCallCreds) {
2154  ResetStub();
2155  EchoRequest request;
2156  EchoResponse response;
2157  ClientContext context;
2158  const char kMetadataKey1[] = "call-creds-key1";
2159  const char kMetadataKey2[] = "call-creds-key2";
2160  const char kMetadataVal1[] = "call-creds-val1";
2161  const char kMetadataVal2[] = "call-creds-val2";
2162 
2165  std::unique_ptr<MetadataCredentialsPlugin>(
2166  new TestMetadataCredentialsPlugin(kMetadataKey1, kMetadataVal1,
2167  true, true, 0))),
2169  std::unique_ptr<MetadataCredentialsPlugin>(
2170  new TestMetadataCredentialsPlugin(kMetadataKey2, kMetadataVal2,
2171  true, true, 0)))));
2172  request.set_message("Hello");
2173  request.mutable_param()->set_echo_metadata(true);
2174 
2175  Status s = stub_->Echo(&context, request, &response);
2176  EXPECT_TRUE(s.ok());
2177  EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
2178  kMetadataKey1, kMetadataVal1));
2179  EXPECT_TRUE(MetadataContains(context.GetServerTrailingMetadata(),
2180  kMetadataKey2, kMetadataVal2));
2181  EXPECT_EQ(context.credentials()->DebugString(),
2182  kExpectedCompositeCallCredsDebugString);
2183 }
2184 
2185 TEST_P(SecureEnd2endTest, ClientAuthContext) {
2186  ResetStub();
2187  EchoRequest request;
2188  EchoResponse response;
2189  request.set_message("Hello");
2190  request.mutable_param()->set_check_auth_context(
2191  GetParam().credentials_type() == kTlsCredentialsType);
2192  request.mutable_param()->set_expected_transport_security_type(
2193  GetParam().credentials_type());
2194  ClientContext context;
2195  Status s = stub_->Echo(&context, request, &response);
2196  EXPECT_EQ(response.message(), request.message());
2197  EXPECT_TRUE(s.ok());
2198 
2199  std::shared_ptr<const AuthContext> auth_ctx = context.auth_context();
2200  std::vector<grpc::string_ref> tst =
2201  auth_ctx->FindPropertyValues("transport_security_type");
2202  ASSERT_EQ(1u, tst.size());
2203  EXPECT_EQ(GetParam().credentials_type(), ToString(tst[0]));
2204  if (GetParam().credentials_type() == kTlsCredentialsType) {
2205  EXPECT_EQ("x509_subject_alternative_name",
2206  auth_ctx->GetPeerIdentityPropertyName());
2207  EXPECT_EQ(4u, auth_ctx->GetPeerIdentity().size());
2208  EXPECT_EQ("*.test.google.fr", ToString(auth_ctx->GetPeerIdentity()[0]));
2209  EXPECT_EQ("waterzooi.test.google.be",
2210  ToString(auth_ctx->GetPeerIdentity()[1]));
2211  EXPECT_EQ("*.test.youtube.com", ToString(auth_ctx->GetPeerIdentity()[2]));
2212  EXPECT_EQ("192.168.1.3", ToString(auth_ctx->GetPeerIdentity()[3]));
2213  }
2214 }
2215 
2216 class ResourceQuotaEnd2endTest : public End2endTest {
2217  public:
2218  ResourceQuotaEnd2endTest()
2219  : server_resource_quota_("server_resource_quota") {}
2220 
2221  void ConfigureServerBuilder(ServerBuilder* builder) override {
2222  builder->SetResourceQuota(server_resource_quota_);
2223  }
2224 
2225  private:
2226  ResourceQuota server_resource_quota_;
2227 };
2228 
2229 TEST_P(ResourceQuotaEnd2endTest, SimpleRequest) {
2230  ResetStub();
2231 
2232  EchoRequest request;
2233  EchoResponse response;
2234  request.set_message("Hello");
2235 
2236  ClientContext context;
2237  Status s = stub_->Echo(&context, request, &response);
2238  EXPECT_EQ(response.message(), request.message());
2239  EXPECT_TRUE(s.ok());
2240 }
2241 
2242 // TODO(vjpai): refactor arguments into a struct if it makes sense
2243 std::vector<TestScenario> CreateTestScenarios(bool use_proxy,
2244  bool test_insecure,
2245  bool test_secure,
2246  bool test_inproc,
2247  bool test_callback_server) {
2248  std::vector<TestScenario> scenarios;
2249  std::vector<std::string> credentials_types;
2250 
2251  GPR_GLOBAL_CONFIG_SET(grpc_client_channel_backup_poll_interval_ms,
2252  kClientChannelBackupPollIntervalMs);
2253 #if TARGET_OS_IPHONE
2254  // Workaround Apple CFStream bug
2255  gpr_setenv("grpc_cfstream", "0");
2256 #endif
2257 
2258  if (test_secure) {
2259  credentials_types =
2261  }
2262  auto insec_ok = [] {
2263  // Only allow insecure credentials type when it is registered with the
2264  // provider. User may create providers that do not have insecure.
2266  kInsecureCredentialsType, nullptr) != nullptr;
2267  };
2268  if (test_insecure && insec_ok()) {
2269  credentials_types.push_back(kInsecureCredentialsType);
2270  }
2271 
2272  // Test callback with inproc or if the event-engine allows it
2273  GPR_ASSERT(!credentials_types.empty());
2274  for (const auto& cred : credentials_types) {
2275  scenarios.emplace_back(false, false, false, cred, false);
2276  scenarios.emplace_back(true, false, false, cred, false);
2277  if (test_callback_server) {
2278  // Note that these scenarios will be dynamically disabled if the event
2279  // engine doesn't run in the background
2280  scenarios.emplace_back(false, false, false, cred, true);
2281  scenarios.emplace_back(true, false, false, cred, true);
2282  }
2283  if (use_proxy) {
2284  scenarios.emplace_back(false, true, false, cred, false);
2285  scenarios.emplace_back(true, true, false, cred, false);
2286  }
2287  }
2288  if (test_inproc && insec_ok()) {
2289  scenarios.emplace_back(false, false, true, kInsecureCredentialsType, false);
2290  scenarios.emplace_back(true, false, true, kInsecureCredentialsType, false);
2291  if (test_callback_server) {
2292  scenarios.emplace_back(false, false, true, kInsecureCredentialsType,
2293  true);
2294  scenarios.emplace_back(true, false, true, kInsecureCredentialsType, true);
2295  }
2296  }
2297  return scenarios;
2298 }
2299 
2301  End2end, End2endTest,
2302  ::testing::ValuesIn(CreateTestScenarios(false, true, true, true, true)),
2303  &TestScenario::Name);
2304 
2306  End2endServerTryCancel, End2endServerTryCancelTest,
2307  ::testing::ValuesIn(CreateTestScenarios(false, true, true, true, true)),
2308  &TestScenario::Name);
2309 
2311  ProxyEnd2end, ProxyEnd2endTest,
2312  ::testing::ValuesIn(CreateTestScenarios(true, true, true, true, true)),
2313  &TestScenario::Name);
2314 
2316  SecureEnd2end, SecureEnd2endTest,
2317  ::testing::ValuesIn(CreateTestScenarios(false, false, true, false, true)),
2318  &TestScenario::Name);
2319 
2321  ResourceQuotaEnd2end, ResourceQuotaEnd2endTest,
2322  ::testing::ValuesIn(CreateTestScenarios(false, true, true, true, true)),
2323  &TestScenario::Name);
2324 
2325 } // namespace
2326 } // namespace testing
2327 } // namespace grpc
2328 
2329 int main(int argc, char** argv) {
2330  grpc::testing::TestEnvironment env(&argc, argv);
2331  ::testing::InitGoogleTest(&argc, argv);
2332  int ret = RUN_ALL_TESTS();
2333  return ret;
2334 }
EXPECT_FALSE
#define EXPECT_FALSE(condition)
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest.h:1970
test_credentials_provider.h
use_proxy_
bool use_proxy_
Definition: end2end_test.cc:301
grpc::testing::kTlsCredentialsType
const char kTlsCredentialsType[]
Definition: test_credentials_provider.h:34
GPR_TIMESPAN
@ GPR_TIMESPAN
Definition: gpr_types.h:45
grpc::gpr_setenv
gpr_setenv("STS_CREDENTIALS", creds_file_name)
messages_pb2.SimpleRequest
SimpleRequest
Definition: messages_pb2.py:597
grpc::string_ref
Definition: grpcpp/impl/codegen/string_ref.h:43
absl::time_internal::cctz::seconds
std::chrono::duration< std::int_fast64_t > seconds
Definition: abseil-cpp/absl/time/internal/cctz/include/cctz/time_zone.h:40
grpc::ClientContext::peer
std::string peer() const
Definition: client_context.cc:174
gpr_timespec::tv_sec
int64_t tv_sec
Definition: gpr_types.h:51
GPR_INFO
#define GPR_INFO
Definition: include/grpc/impl/codegen/log.h:56
testing
Definition: aws_request_signer_test.cc:25
GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY
#define GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY
Definition: src/core/lib/security/credentials/credentials.h:58
iomgr.h
GRPC_CHANNEL_READY
@ GRPC_CHANNEL_READY
Definition: include/grpc/impl/codegen/connectivity_state.h:36
channel_
std::shared_ptr< Channel > channel_
Definition: end2end_test.cc:466
kMaxMessageSize_
const int kMaxMessageSize_
Definition: end2end_test.cc:472
now
static double now(void)
Definition: test/core/fling/client.cc:130
is_server_started_
bool is_server_started_
Definition: end2end_test.cc:465
log.h
grpc::testing::CredentialsProvider::GetChannelCredentials
virtual std::shared_ptr< ChannelCredentials > GetChannelCredentials(const std::string &type, ChannelArguments *args)=0
grpc::testing::PhonyInterceptor::Reset
static void Reset()
Definition: interceptors_util.h:51
port.h
info_
experimental::ClientRpcInfo * info_
Definition: end2end_test.cc:1858
generate.env
env
Definition: generate.py:37
metadata
Definition: cq_verifier.cc:48
absl::StrFormat
ABSL_MUST_USE_RESULT std::string StrFormat(const FormatSpec< Args... > &format, const Args &... args)
Definition: abseil-cpp/absl/strings/str_format.h:338
kBadMetadataKey
static const char kBadMetadataKey[]
Definition: end2end_test.cc:140
grpc::experimental::InterceptionHookPoints::PRE_SEND_INITIAL_METADATA
@ PRE_SEND_INITIAL_METADATA
The first three in this list are for clients and servers.
grpc
Definition: grpcpp/alarm.h:33
dup_pkg_service_
TestServiceImplDupPkg dup_pkg_service_
Definition: end2end_test.cc:476
kGoodGuy
static const char kGoodGuy[]
Definition: end2end_test.cc:195
grpc::testing::kClientTryCancelRequest
const char *const kClientTryCancelRequest
Definition: test_service_impl.h:45
GPR_GLOBAL_CONFIG_GET
#define GPR_GLOBAL_CONFIG_GET(name)
Definition: global_config_generic.h:24
false
#define false
Definition: setup_once.h:323
absl::time_internal::cctz::time_point
std::chrono::time_point< std::chrono::system_clock, D > time_point
Definition: abseil-cpp/absl/time/internal/cctz/include/cctz/time_zone.h:39
grpc::ClientContext::credentials
std::shared_ptr< grpc::CallCredentials > credentials()
Definition: grpcpp/impl/codegen/client_context.h:333
GRPC_ARG_SECONDARY_USER_AGENT_STRING
#define GRPC_ARG_SECONDARY_USER_AGENT_STRING
Definition: grpc_types.h:257
callback_server_
bool callback_server_
Definition: end2end_test.cc:304
framework.rpc.grpc_channelz.ChannelState
ChannelState
Definition: grpc_channelz.py:34
server_
std::unique_ptr< Server > server_
Definition: end2end_test.cc:468
grpc::ASSERT_EQ
ASSERT_EQ(sizeof(valid_json), fwrite(valid_json, 1, sizeof(valid_json), creds_file))
benchmark.request
request
Definition: benchmark.py:77
EXPECT_GT
#define EXPECT_GT(val1, val2)
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest.h:2036
gpr_event_set
GPRAPI void gpr_event_set(gpr_event *ev, void *value)
Definition: sync.cc:59
DebugString
std::string DebugString(const google::protobuf::Message &message)
Definition: bloaty/tests/test.h:60
grpc_recycle_unused_port
void grpc_recycle_unused_port(int port)
testing::internal::string
::std::string string
Definition: bloaty/third_party/protobuf/third_party/googletest/googletest/include/gtest/internal/gtest-port.h:881
error
grpc_error_handle error
Definition: retry_filter.cc:499
channel_test_peer.h
GRPC_CHANNEL_TRANSIENT_FAILURE
@ GRPC_CHANNEL_TRANSIENT_FAILURE
Definition: include/grpc/impl/codegen/connectivity_state.h:38
grpc::ClientContext::set_deadline
void set_deadline(const T &deadline)
Definition: grpcpp/impl/codegen/client_context.h:274
grpc::testing::CANCEL_AFTER_PROCESSING
@ CANCEL_AFTER_PROCESSING
Definition: test_service_impl.h:56
gpr_inf_future
GPRAPI gpr_timespec gpr_inf_future(gpr_clock_type type)
Definition: src/core/lib/gpr/time.cc:55
grpc::testing::DO_NOT_CANCEL
@ DO_NOT_CANCEL
Definition: test_service_impl.h:53
env.h
absl::FormatConversionChar::s
@ s
time.h
EXPECT_LE
#define EXPECT_LE(val1, val2)
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest.h:2030
async_greeter_client.stub
stub
Definition: hellostreamingworld/async_greeter_client.py:26
testing::Test::SetUpTestCase
static void SetUpTestCase()
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest.h:432
service_url
std::string service_url
Definition: call_creds_util.cc:39
grpc::ClientContext::AddMetadata
void AddMetadata(const std::string &meta_key, const std::string &meta_value)
Definition: client_context.cc:121
grpc::AuthContext::IsPeerAuthenticated
virtual bool IsPeerAuthenticated() const =0
Returns true if the peer is authenticated.
credentials.h
server_address
std::string server_address("0.0.0.0:10000")
absl::AsciiStrToLower
void AsciiStrToLower(std::string *s)
Definition: abseil-cpp/absl/strings/ascii.cc:158
threads
static uv_thread_t * threads
Definition: threadpool.c:38
test_service_impl.h
testing::TestWithParam
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest.h:1883
proxy_service_
std::unique_ptr< Proxy > proxy_service_
Definition: end2end_test.cc:470
grpc::testing::kInsecureCredentialsType
const char kInsecureCredentialsType[]
Definition: test_credentials_provider.h:31
metadata_value_
std::string metadata_value_
Definition: end2end_test.cc:182
absl::string_view::length
constexpr size_type length() const noexcept
Definition: abseil-cpp/absl/strings/string_view.h:282
grpc::ClientContext::set_initial_metadata_corked
void set_initial_metadata_corked(bool corked)
Definition: grpcpp/impl/codegen/client_context.h:357
grpc::ClientContext::set_authority
void set_authority(const std::string &authority)
Definition: grpcpp/impl/codegen/client_context.h:303
grpc::testing::PhonyInterceptor::GetNumTimesCancel
static int GetNumTimesCancel()
Definition: interceptors_util.h:62
grpc::testing::CredentialsProvider::GetServerCredentials
virtual std::shared_ptr< ServerCredentials > GetServerCredentials(const std::string &type)=0
user_agent_prefix_
std::string user_agent_prefix_
Definition: end2end_test.cc:477
proxy_server_
std::unique_ptr< Server > proxy_server_
Definition: end2end_test.cc:469
profile_analyzer.builder
builder
Definition: profile_analyzer.py:159
channel
wrapped_grpc_channel * channel
Definition: src/php/ext/grpc/call.h:33
grpc_status._async.trailing_metadata
trailing_metadata
Definition: grpcio_status/grpc_status/_async.py:36
asyncio_get_stats.args
args
Definition: asyncio_get_stats.py:40
grpc::testing::kServerDefaultResponseStreamsToSend
const int kServerDefaultResponseStreamsToSend
Definition: test_service_impl.h:42
absl::move
constexpr absl::remove_reference_t< T > && move(T &&t) noexcept
Definition: abseil-cpp/absl/utility/utility.h:221
GPR_ASSERT
#define GPR_ASSERT(x)
Definition: include/grpc/impl/codegen/log.h:94
ev_posix.h
EXPECT_NE
#define EXPECT_NE(val1, val2)
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest.h:2028
server_address_
std::ostringstream server_address_
Definition: end2end_test.cc:471
service_
TestServiceImpl service_
Definition: end2end_test.cc:473
gpr_log
GPRAPI void gpr_log(const char *file, int line, gpr_log_severity severity, const char *format,...) GPR_PRINT_FORMAT_CHECK(4
http2_server_health_check.resp
resp
Definition: http2_server_health_check.py:31
grpc.StatusCode.NOT_FOUND
tuple NOT_FOUND
Definition: src/python/grpcio/grpc/__init__.py:266
kIdentityPropName
static const char kIdentityPropName[]
Definition: end2end_test.cc:244
auth_metadata_processor.h
grpc::testing::kServerResponseStreamsToSend
const char *const kServerResponseStreamsToSend
Definition: test_service_impl.h:43
gpr_sleep_until
GPRAPI void gpr_sleep_until(gpr_timespec until)
grpc.h
GRPC_AUTHORIZATION_METADATA_KEY
#define GRPC_AUTHORIZATION_METADATA_KEY
Definition: src/core/lib/security/credentials/credentials.h:55
grpc_test_slowdown_factor
int64_t grpc_test_slowdown_factor()
Definition: test/core/util/test_config.cc:76
grpc::ClientContext::FromServerContext
static std::unique_ptr< ClientContext > FromServerContext(const grpc::ServerContextBase &server_context, PropagationOptions options=PropagationOptions())
Definition: client_context.cc:110
GRPC_CHANNEL_IDLE
@ GRPC_CHANNEL_IDLE
Definition: include/grpc/impl/codegen/connectivity_state.h:32
use_interceptors_
bool use_interceptors_
Definition: end2end_test.cc:300
channel.h
grpc::testing::ServerTryCancelRequestPhase
ServerTryCancelRequestPhase
Definition: test_service_impl.h:52
absl::StrContains
ABSL_NAMESPACE_BEGIN bool StrContains(absl::string_view haystack, absl::string_view needle) noexcept
Definition: third_party/abseil-cpp/absl/strings/match.h:46
grpc::testing::INSTANTIATE_TEST_SUITE_P
INSTANTIATE_TEST_SUITE_P(HistogramTestCases, HistogramTest, ::testing::Range< int >(0, GRPC_STATS_HISTOGRAM_COUNT))
backup_poller.h
grpc::ClientContext::auth_context
std::shared_ptr< const grpc::AuthContext > auth_context() const
Definition: grpcpp/impl/codegen/client_context.h:309
grpc::Status::OK
static const Status & OK
An OK pre-defined instance.
Definition: include/grpcpp/impl/codegen/status.h:113
scenarios
static const scenario scenarios[]
Definition: test/core/fling/client.cc:141
gpr_event_init
GPRAPI void gpr_event_init(gpr_event *ev)
Definition: sync.cc:54
data
char data[kBufferLength]
Definition: abseil-cpp/absl/strings/internal/str_format/float_conversion.cc:1006
grpc.StatusCode.UNAUTHENTICATED
tuple UNAUTHENTICATED
Definition: src/python/grpcio/grpc/__init__.py:280
grpc::CreateChannel
std::shared_ptr< Channel > CreateChannel(const grpc::string &target, const std::shared_ptr< ChannelCredentials > &creds)
RUN_ALL_TESTS
int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest.h:2471
GPR_ERROR
#define GPR_ERROR
Definition: include/grpc/impl/codegen/log.h:57
grpc_pick_unused_port_or_die
int grpc_pick_unused_port_or_die(void)
server_resource_quota_
ResourceQuota server_resource_quota_
Definition: end2end_test.cc:2226
gpr_now
GPRAPI gpr_timespec gpr_now(gpr_clock_type clock)
first_picked_port_
int first_picked_port_
Definition: end2end_test.cc:478
grpc_core::UniquePtr
std::unique_ptr< T, DefaultDeleteChar > UniquePtr
Definition: src/core/lib/gprpp/memory.h:43
GPR_GLOBAL_CONFIG_SET
#define GPR_GLOBAL_CONFIG_SET(name, value)
Definition: global_config_generic.h:26
grpc::CompositeCallCredentials
std::shared_ptr< CallCredentials > CompositeCallCredentials(const std::shared_ptr< CallCredentials > &creds1, const std::shared_ptr< CallCredentials > &creds2)
Combines two call credentials objects into a composite call credentials.
Definition: secure_credentials.cc:392
grpc.StatusCode.UNIMPLEMENTED
tuple UNIMPLEMENTED
Definition: src/python/grpcio/grpc/__init__.py:276
stub_
std::unique_ptr< grpc::testing::EchoTestService::Stub > stub_
Definition: end2end_test.cc:264
msg
std::string msg
Definition: client_interceptors_end2end_test.cc:372
gpr_event_wait
GPRAPI void * gpr_event_wait(gpr_event *ev, gpr_timespec abs_deadline)
Definition: sync.cc:73
grpc::testing::End2endTest::TearDown
void TearDown() override
Definition: streaming_throughput_test.cc:145
server_credentials.h
grpc::testing::tag
static void * tag(intptr_t t)
Definition: h2_ssl_cert_test.cc:263
GRPC_CHANNEL_CONNECTING
@ GRPC_CHANNEL_CONNECTING
Definition: include/grpc/impl/codegen/connectivity_state.h:34
grpc::testing::End2endTest::End2endTest
End2endTest()
Definition: thread_stress_test.cc:269
grpc::testing::End2endTest::ResetStub
void ResetStub()
Definition: streaming_throughput_test.cc:147
tests.unit._exit_scenarios.port
port
Definition: _exit_scenarios.py:179
test_config.h
value
const char * value
Definition: hpack_parser_table.cc:165
is_blocking_
bool is_blocking_
Definition: end2end_test.cc:183
grpc::ClientContext::GetServerTrailingMetadata
const std::multimap< grpc::string_ref, grpc::string_ref > & GetServerTrailingMetadata() const
Definition: grpcpp/impl/codegen/client_context.h:262
absl::ascii_toupper
char ascii_toupper(unsigned char c)
Definition: abseil-cpp/absl/strings/ascii.h:181
interceptors_util.h
grpc::testing::kServerTryCancelRequest
const char *const kServerTryCancelRequest
Definition: test_service_impl.h:44
gpr_event
Definition: impl/codegen/sync_generic.h:31
client_context.h
testing::InitGoogleTest
GTEST_API_ void InitGoogleTest(int *argc, char **argv)
Definition: bloaty/third_party/googletest/googletest/src/gtest.cc:6106
credentials.h
credentials_type_
const std::string credentials_type_
Definition: end2end_test.cc:303
key
const char * key
Definition: hpack_parser_table.cc:164
testing::Test::TearDownTestCase
static void TearDownTestCase()
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest.h:431
grpc::testing::CreatePhonyClientInterceptors
std::vector< std::unique_ptr< experimental::ClientInterceptorFactoryInterface > > CreatePhonyClientInterceptors()
Definition: interceptors_util.cc:205
callback_service_
CallbackTestServiceImpl callback_service_
Definition: end2end_test.cc:474
inproc
bool inproc
Definition: async_end2end_test.cc:235
bytes
uint8 bytes[10]
Definition: bloaty/third_party/protobuf/src/google/protobuf/io/coded_stream_unittest.cc:153
inproc_
bool inproc_
Definition: end2end_test.cc:302
kGoodMetadataKey
static const char kGoodMetadataKey[]
Definition: end2end_test.cc:139
gpr_time_add
GPRAPI gpr_timespec gpr_time_add(gpr_timespec a, gpr_timespec b)
Definition: src/core/lib/gpr/time.cc:135
grpc::testing::GetCredentialsProvider
CredentialsProvider * GetCredentialsProvider()
Definition: test_credentials_provider.cc:169
count
int * count
Definition: bloaty/third_party/googletest/googlemock/test/gmock_stress_test.cc:96
use_interceptors
bool use_interceptors
Definition: client_callback_end2end_test.cc:68
StartServer
void StartServer(JNIEnv *env, jobject obj, jmethodID is_cancelled_mid, int port)
Definition: grpc-helloworld.cc:48
ret
UniquePtr< SSL_SESSION > ret
Definition: ssl_x509.cc:1029
grpc::testing::ToString
std::string ToString(const grpc::string_ref &r)
Definition: string_ref_helper.cc:24
gpr_time_from_micros
GPRAPI gpr_timespec gpr_time_from_micros(int64_t us, gpr_clock_type clock_type)
Definition: src/core/lib/gpr/time.cc:115
alloc.h
grpc::ClientContext::TryCancel
void TryCancel()
Definition: client_context.cc:157
credentials_type
const std::string credentials_type
Definition: async_end2end_test.cc:237
server_context.h
grpc::experimental::CreateCustomChannelWithInterceptors
std::shared_ptr< Channel > CreateCustomChannelWithInterceptors(const grpc::string &target, const std::shared_ptr< ChannelCredentials > &creds, const ChannelArguments &args, std::vector< std::unique_ptr< experimental::ClientInterceptorFactoryInterface >> interceptor_creators)
asyncio_get_stats.response
response
Definition: asyncio_get_stats.py:28
grpc::testing::TestEnvironment
Definition: test/core/util/test_config.h:54
GRPC_COMPRESS_GZIP
@ GRPC_COMPRESS_GZIP
Definition: compression_types.h:63
grpc::CreateCustomChannel
std::shared_ptr< Channel > CreateCustomChannel(const grpc::string &target, const std::shared_ptr< ChannelCredentials > &creds, const ChannelArguments &args)
metadata_key_
std::string metadata_key_
Definition: end2end_test.cc:181
grpc::Timepoint2Timespec
void Timepoint2Timespec(const std::chrono::system_clock::time_point &from, gpr_timespec *to)
grpc::protobuf::util::Status
GRPC_CUSTOM_UTIL_STATUS Status
Definition: include/grpcpp/impl/codegen/config_protobuf.h:93
testing::WithParamInterface< TestScenario >::GetParam
static const ParamType & GetParam()
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest.h:1855
grpc::testing::kServerUseCoalescingApi
const char *const kServerUseCoalescingApi
Definition: test_service_impl.h:48
CreateTestScenarios
std::vector< std::string > CreateTestScenarios()
Definition: time_jump_test.cc:84
ok
bool ok
Definition: async_end2end_test.cc:197
state
Definition: bloaty/third_party/zlib/contrib/blast/blast.c:41
grpc::testing::EXPECT_EQ
EXPECT_EQ(options.token_exchange_service_uri, "https://foo/exchange")
CheckIsLocalhost
bool CheckIsLocalhost(const std::string &addr)
grpc::testing::CredentialsProvider::GetSecureCredentialsTypeList
virtual std::vector< std::string > GetSecureCredentialsTypeList()=0
EXPECT_GE
#define EXPECT_GE(val1, val2)
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest.h:2034
grpc.StatusCode.UNAVAILABLE
tuple UNAVAILABLE
Definition: src/python/grpcio/grpc/__init__.py:278
grpc::testing::CANCEL_DURING_PROCESSING
@ CANCEL_DURING_PROCESSING
Definition: test_service_impl.h:55
gpr_time_from_millis
GPRAPI gpr_timespec gpr_time_from_millis(int64_t ms, gpr_clock_type clock_type)
Definition: src/core/lib/gpr/time.cc:119
grpc::testing::kServerFinishAfterNReads
const char *const kServerFinishAfterNReads
Definition: test_service_impl.h:47
GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY
#define GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY
Definition: src/core/lib/security/credentials/credentials.h:56
resource_quota.h
grpc::InsecureServerCredentials
std::shared_ptr< ServerCredentials > InsecureServerCredentials()
Definition: insecure_server_credentials.cc:52
grpc.StatusCode.CANCELLED
tuple CANCELLED
Definition: src/python/grpcio/grpc/__init__.py:261
delay_ms_
int delay_ms_
Definition: end2end_test.cc:185
context
grpc::ClientContext context
Definition: istio_echo_server_lib.cc:61
iter
Definition: test_winkernel.cpp:47
grpc::testing::TEST_P
TEST_P(HistogramTest, IncHistogram)
Definition: stats_test.cc:87
grpc::testing::EXPECT_TRUE
EXPECT_TRUE(grpc::experimental::StsCredentialsOptionsFromJson(minimum_valid_json, &options) .ok())
grpc::testing::kDebugInfoTrailerKey
const char *const kDebugInfoTrailerKey
Definition: test_service_impl.h:46
testing::ValuesIn
internal::ParamGenerator< typename std::iterator_traits< ForwardIterator >::value_type > ValuesIn(ForwardIterator begin, ForwardIterator end)
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest-param-test.h:297
server.h
gpr_timespec
Definition: gpr_types.h:50
callback_server
bool callback_server
Definition: client_callback_end2end_test.cc:66
grpc::InsecureChannelCredentials
std::shared_ptr< ChannelCredentials > InsecureChannelCredentials()
Credentials for an unencrypted, unauthenticated channel.
Definition: cpp/client/insecure_credentials.cc:69
grpc_init
GRPCAPI void grpc_init(void)
Definition: init.cc:146
service
__attribute__((deprecated("Please use GRPCProtoMethod."))) @interface ProtoMethod NSString * service
Definition: ProtoMethod.h:25
grpc::ClientContext::set_credentials
void set_credentials(const std::shared_ptr< grpc::CallCredentials > &creds)
Definition: client_context.cc:86
grpc.StatusCode.DEADLINE_EXCEEDED
tuple DEADLINE_EXCEEDED
Definition: src/python/grpcio/grpc/__init__.py:264
length
std::size_t length
Definition: abseil-cpp/absl/time/internal/test_util.cc:57
grpc::ClientContext::debug_error_string
std::string debug_error_string() const
Definition: grpcpp/impl/codegen/client_context.h:414
GPR_CLOCK_REALTIME
@ GPR_CLOCK_REALTIME
Definition: gpr_types.h:39
is_successful_
bool is_successful_
Definition: end2end_test.cc:184
string_ref_helper.h
to_string
static bool to_string(zval *from)
Definition: protobuf/php/ext/google/protobuf/convert.c:333
TestServiceImpl
Definition: interop_server.cc:139
grpc::testing::SendRpc
static void SendRpc(grpc::testing::EchoTestService::Stub *stub, int num_rpcs, bool allow_exhaustion, gpr_atm *errors)
Definition: thread_stress_test.cc:277
grpc::MetadataCredentialsFromPlugin
std::shared_ptr< CallCredentials > MetadataCredentialsFromPlugin(std::unique_ptr< MetadataCredentialsPlugin > plugin)
Definition: secure_credentials.cc:404
method_name
absl::string_view method_name
Definition: call_creds_util.cc:40
grpc::ClientContext::set_compression_algorithm
void set_compression_algorithm(grpc_compression_algorithm algorithm)
Definition: client_context.cc:144
grpc::testing::CANCEL_BEFORE_PROCESSING
@ CANCEL_BEFORE_PROCESSING
Definition: test_service_impl.h:54
grpc::AuthContext
Definition: grpcpp/impl/codegen/security/auth_context.h:72
grpc_shutdown
GRPCAPI void grpc_shutdown(void)
Definition: init.cc:209
main
int main(int argc, char **argv)
Definition: end2end_test.cc:2329
addr
struct sockaddr_in addr
Definition: libuv/docs/code/tcp-echo-server/main.c:10
thread
static uv_thread_t thread
Definition: test-async-null-cb.c:29
server_builder.h
cq
static grpc_completion_queue * cq
Definition: test/core/fling/client.cc:37
special_service_
TestServiceImpl special_service_
Definition: end2end_test.cc:475
string_ref.h
i
uint64_t i
Definition: abseil-cpp/absl/container/btree_benchmark.cc:230
create_channel.h
grpc::GoogleIAMCredentials
std::shared_ptr< CallCredentials > GoogleIAMCredentials(const grpc::string &authorization_token, const grpc::string &authority_selector)
stream
voidpf stream
Definition: bloaty/third_party/zlib/contrib/minizip/ioapi.h:136


grpc
Author(s):
autogenerated on Fri May 16 2025 02:58:19