aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/libs/grpc
diff options
context:
space:
mode:
authorrobot-piglet <robot-piglet@yandex-team.com>2023-03-23 12:15:53 +0300
committerrobot-piglet <robot-piglet@yandex-team.com>2023-03-23 12:15:53 +0300
commit8d5942b8f813c0e704a166c3c83902ccceefca07 (patch)
treed717bac5cbd96eaff6a15e1c3f7b664b3b5dfce8 /contrib/libs/grpc
parent091daa0ca1dd4df8f596b17239c6f9a72abf3aab (diff)
downloadydb-8d5942b8f813c0e704a166c3c83902ccceefca07.tar.gz
Intermediate changes
Diffstat (limited to 'contrib/libs/grpc')
-rw-r--r--contrib/libs/grpc/include/grpcpp/generic/generic_stub.h175
-rw-r--r--contrib/libs/grpc/include/grpcpp/support/client_callback.h24
-rw-r--r--contrib/libs/grpc/include/grpcpp/support/server_interceptor.h24
-rw-r--r--contrib/libs/grpc/src/proto/grpc/core/ya.make2
-rw-r--r--contrib/libs/grpc/src/proto/grpc/health/v1/ya.make2
-rw-r--r--contrib/libs/grpc/src/proto/grpc/status/ya.make2
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/benchmark_service.proto44
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/compiler_test.proto71
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/control.proto289
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/duplicate/echo_duplicate.proto27
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/duplicate/ya.make28
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/echo.proto70
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/echo_messages.proto70
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/empty.proto28
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/empty_service.proto23
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/messages.proto270
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/metrics.proto49
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/payloads.proto40
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/proxy-service.proto31
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/report_qps_scenario_service.proto26
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/simple_messages.proto26
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/stats.proto83
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/test.proto102
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/worker_service.proto45
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/xds/ads_for_test.proto51
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/xds/cds_for_test.proto186
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/xds/eds_for_test.proto517
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/xds/lds_rds_for_test.proto215
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/xds/lrs_for_test.proto189
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/xds/ya.make32
-rw-r--r--contrib/libs/grpc/src/proto/grpc/testing/ya.make43
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/__init__.py13
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_abort_test.py154
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_api_test.py121
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_auth_test.py82
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_args_test.py65
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_close_test.py220
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_connectivity_test.py156
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_ready_future_test.py98
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_contextvars_propagation_test.py163
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_credentials_test.py70
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/__init__.py13
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_cancel_many_calls_test.py222
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_channel_test.py70
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_common.py123
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_fork_test.py72
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_no_messages_server_completion_queue_per_call_test.py132
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_no_messages_single_server_completion_queue_test.py126
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_read_some_but_not_all_responses_test.py241
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_server_test.py49
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/cygrpc_test.py417
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/test_utilities.py52
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_dns_resolver_test.py68
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_dynamic_stubs_test.py147
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_empty_message_test.py124
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_error_message_encoding_test.py87
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_exit_scenarios.py236
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_exit_test.py262
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_from_grpc_import_star.py23
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_grpc_shutdown_test.py54
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_interceptor_test.py708
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_invalid_metadata_test.py140
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_invocation_defects_test.py266
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_local_credentials_test.py82
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_logging_test.py104
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_metadata_code_details_test.py723
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_metadata_flags_test.py260
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_metadata_test.py242
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_reconnect_test.py72
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_resource_exhausted_test.py259
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_rpc_part_1_test.py241
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_rpc_part_2_test.py435
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_rpc_test_helpers.py417
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_shutdown_scenarios.py97
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_shutdown_test.py95
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_test.py69
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_wait_for_termination_test.py92
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_signal_client.py119
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_signal_handling_test.py200
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_tcp_proxy.py141
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_version_test.py31
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_xds_credentials_test.py103
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/__init__.py13
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_beta_features_test.py355
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_connectivity_channel_test.py32
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_not_found_test.py60
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_utilities_test.py94
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/test_utilities.py40
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/README.md15
-rwxr-xr-xcontrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/ca.pem20
-rwxr-xr-xcontrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/server1.key28
-rwxr-xr-xcontrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/server1.pem22
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/__init__.py13
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/__init__.py102
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/test_constants.py45
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/test_control.py97
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/test_coverage.py101
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/foundation/__init__.py13
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/foundation/_logging_pool_test.py73
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/foundation/stream_testing.py57
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/resources.py113
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/test_common.py145
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/tests/unit/thread_pool.py34
-rw-r--r--contrib/libs/grpc/src/python/grpcio_tests/ya.make144
-rw-r--r--contrib/libs/grpc/test/core/util/build.cc77
-rw-r--r--contrib/libs/grpc/test/core/util/build.h33
-rw-r--r--contrib/libs/grpc/test/core/util/port.cc143
-rw-r--r--contrib/libs/grpc/test/core/util/port.h44
-rw-r--r--contrib/libs/grpc/test/core/util/port_server_client.cc238
-rw-r--r--contrib/libs/grpc/test/core/util/port_server_client.h30
-rw-r--r--contrib/libs/grpc/test/core/util/stack_tracer.cc109
-rw-r--r--contrib/libs/grpc/test/core/util/stack_tracer.h48
-rw-r--r--contrib/libs/grpc/test/core/util/test_config.cc156
-rw-r--r--contrib/libs/grpc/test/core/util/test_config.h72
-rw-r--r--contrib/libs/grpc/test/core/util/test_lb_policies.cc549
-rw-r--r--contrib/libs/grpc/test/core/util/test_lb_policies.h64
-rw-r--r--contrib/libs/grpc/test/core/util/ya.make53
-rw-r--r--contrib/libs/grpc/test/cpp/README-iOS.md52
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/health/ya.make28
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/health_service_end2end_test.cc374
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/interceptors_util.cc216
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/interceptors_util.h354
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/server_interceptors/ya.make27
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/server_interceptors_end2end_test.cc703
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/test_health_check_service_impl.cc98
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/test_health_check_service_impl.h58
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/test_service_impl.cc635
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/test_service_impl.h500
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/ya.make65
-rw-r--r--contrib/libs/grpc/test/cpp/util/byte_buffer_proto_helper.cc59
-rw-r--r--contrib/libs/grpc/test/cpp/util/byte_buffer_proto_helper.h42
-rw-r--r--contrib/libs/grpc/test/cpp/util/cli_call.cc225
-rw-r--r--contrib/libs/grpc/test/cpp/util/cli_call.h106
-rw-r--r--contrib/libs/grpc/test/cpp/util/cli_credentials.cc191
-rw-r--r--contrib/libs/grpc/test/cpp/util/cli_credentials.h55
-rw-r--r--contrib/libs/grpc/test/cpp/util/config_grpc_cli.h70
-rw-r--r--contrib/libs/grpc/test/cpp/util/grpc_tool.cc1010
-rw-r--r--contrib/libs/grpc/test/cpp/util/grpc_tool.h39
-rw-r--r--contrib/libs/grpc/test/cpp/util/proto_file_parser.cc331
-rw-r--r--contrib/libs/grpc/test/cpp/util/proto_file_parser.h135
-rw-r--r--contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.cc333
-rw-r--r--contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.h112
-rw-r--r--contrib/libs/grpc/test/cpp/util/service_describer.cc92
-rw-r--r--contrib/libs/grpc/test/cpp/util/service_describer.h43
-rw-r--r--contrib/libs/grpc/test/cpp/util/string_ref_helper.cc29
-rw-r--r--contrib/libs/grpc/test/cpp/util/string_ref_helper.h32
-rw-r--r--contrib/libs/grpc/test/cpp/util/test_config.h35
-rw-r--r--contrib/libs/grpc/test/cpp/util/test_config_cc.cc39
-rw-r--r--contrib/libs/grpc/test/cpp/util/ya.make38
-rw-r--r--contrib/libs/grpc/ya.make9
150 files changed, 6 insertions, 20701 deletions
diff --git a/contrib/libs/grpc/include/grpcpp/generic/generic_stub.h b/contrib/libs/grpc/include/grpcpp/generic/generic_stub.h
deleted file mode 100644
index 1f88438a2f8..00000000000
--- a/contrib/libs/grpc/include/grpcpp/generic/generic_stub.h
+++ /dev/null
@@ -1,175 +0,0 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPCPP_GENERIC_GENERIC_STUB_H
-#define GRPCPP_GENERIC_GENERIC_STUB_H
-
-#include <functional>
-
-#include <grpcpp/client_context.h>
-#include <grpcpp/impl/codegen/stub_options.h>
-#include <grpcpp/impl/rpc_method.h>
-#include <grpcpp/support/async_stream.h>
-#include <grpcpp/support/async_unary_call.h>
-#include <grpcpp/support/byte_buffer.h>
-#include <grpcpp/support/client_callback.h>
-#include <grpcpp/support/status.h>
-
-namespace grpc {
-
-class CompletionQueue;
-
-typedef ClientAsyncReaderWriter<ByteBuffer, ByteBuffer>
- GenericClientAsyncReaderWriter;
-typedef ClientAsyncResponseReader<ByteBuffer> GenericClientAsyncResponseReader;
-
-/// Generic stubs provide a type-unaware interface to call gRPC methods
-/// by name. In practice, the Request and Response types should be basic
-/// types like grpc::ByteBuffer or proto::MessageLite (the base protobuf).
-template <class RequestType, class ResponseType>
-class TemplatedGenericStub final {
- public:
- explicit TemplatedGenericStub(std::shared_ptr<grpc::ChannelInterface> channel)
- : channel_(channel) {}
-
- /// Setup a call to a named method \a method using \a context, but don't
- /// start it. Let it be started explicitly with StartCall and a tag.
- /// The return value only indicates whether or not registration of the call
- /// succeeded (i.e. the call won't proceed if the return value is nullptr).
- std::unique_ptr<ClientAsyncReaderWriter<RequestType, ResponseType>>
- PrepareCall(ClientContext* context, const TString& method,
- ::grpc::CompletionQueue* cq) {
- return CallInternal(channel_.get(), context, method, /*options=*/{}, cq,
- false, nullptr);
- }
-
- /// Setup a unary call to a named method \a method using \a context, and don't
- /// start it. Let it be started explicitly with StartCall.
- /// The return value only indicates whether or not registration of the call
- /// succeeded (i.e. the call won't proceed if the return value is nullptr).
- std::unique_ptr<ClientAsyncResponseReader<ResponseType>> PrepareUnaryCall(
- ClientContext* context, const TString& method,
- const RequestType& request, ::grpc::CompletionQueue* cq) {
- return std::unique_ptr<ClientAsyncResponseReader<ResponseType>>(
- internal::ClientAsyncResponseReaderHelper::Create<ResponseType>(
- channel_.get(), cq,
- grpc::internal::RpcMethod(method.c_str(),
- /*suffix_for_stats=*/nullptr,
- grpc::internal::RpcMethod::NORMAL_RPC),
- context, request));
- }
-
- /// DEPRECATED for multi-threaded use
- /// Begin a call to a named method \a method using \a context.
- /// A tag \a tag will be delivered to \a cq when the call has been started
- /// (i.e, initial metadata has been sent).
- /// The return value only indicates whether or not registration of the call
- /// succeeded (i.e. the call won't proceed if the return value is nullptr).
- std::unique_ptr<ClientAsyncReaderWriter<RequestType, ResponseType>> Call(
- ClientContext* context, const TString& method,
- ::grpc::CompletionQueue* cq, void* tag) {
- return CallInternal(channel_.get(), context, method, /*options=*/{}, cq,
- true, tag);
- }
-
- /// Setup and start a unary call to a named method \a method using
- /// \a context and specifying the \a request and \a response buffers.
- void UnaryCall(ClientContext* context, const TString& method,
- StubOptions options, const RequestType* request,
- ResponseType* response,
- std::function<void(grpc::Status)> on_completion) {
- UnaryCallInternal(context, method, options, request, response,
- std::move(on_completion));
- }
-
- /// Setup a unary call to a named method \a method using
- /// \a context and specifying the \a request and \a response buffers.
- /// Like any other reactor-based RPC, it will not be activated until
- /// StartCall is invoked on its reactor.
- void PrepareUnaryCall(ClientContext* context, const TString& method,
- StubOptions options, const RequestType* request,
- ResponseType* response, ClientUnaryReactor* reactor) {
- PrepareUnaryCallInternal(context, method, options, request, response,
- reactor);
- }
-
- /// Setup a call to a named method \a method using \a context and tied to
- /// \a reactor . Like any other bidi streaming RPC, it will not be activated
- /// until StartCall is invoked on its reactor.
- void PrepareBidiStreamingCall(
- ClientContext* context, const TString& method, StubOptions options,
- ClientBidiReactor<RequestType, ResponseType>* reactor) {
- PrepareBidiStreamingCallInternal(context, method, options, reactor);
- }
-
- private:
- std::shared_ptr<grpc::ChannelInterface> channel_;
-
- void UnaryCallInternal(ClientContext* context, const TString& method,
- StubOptions options, const RequestType* request,
- ResponseType* response,
- std::function<void(grpc::Status)> on_completion) {
- internal::CallbackUnaryCall(
- channel_.get(),
- grpc::internal::RpcMethod(method.c_str(), options.suffix_for_stats(),
- grpc::internal::RpcMethod::NORMAL_RPC),
- context, request, response, std::move(on_completion));
- }
-
- void PrepareUnaryCallInternal(ClientContext* context,
- const TString& method, StubOptions options,
- const RequestType* request,
- ResponseType* response,
- ClientUnaryReactor* reactor) {
- internal::ClientCallbackUnaryFactory::Create<RequestType, ResponseType>(
- channel_.get(),
- grpc::internal::RpcMethod(method.c_str(), options.suffix_for_stats(),
- grpc::internal::RpcMethod::NORMAL_RPC),
- context, request, response, reactor);
- }
-
- void PrepareBidiStreamingCallInternal(
- ClientContext* context, const TString& method, StubOptions options,
- ClientBidiReactor<RequestType, ResponseType>* reactor) {
- internal::ClientCallbackReaderWriterFactory<RequestType, ResponseType>::
- Create(channel_.get(),
- grpc::internal::RpcMethod(
- method.c_str(), options.suffix_for_stats(),
- grpc::internal::RpcMethod::BIDI_STREAMING),
- context, reactor);
- }
-
- std::unique_ptr<ClientAsyncReaderWriter<RequestType, ResponseType>>
- CallInternal(grpc::ChannelInterface* channel, ClientContext* context,
- const TString& method, StubOptions options,
- ::grpc::CompletionQueue* cq, bool start, void* tag) {
- return std::unique_ptr<ClientAsyncReaderWriter<RequestType, ResponseType>>(
- internal::ClientAsyncReaderWriterFactory<RequestType, ResponseType>::
- Create(channel, cq,
- grpc::internal::RpcMethod(
- method.c_str(), options.suffix_for_stats(),
- grpc::internal::RpcMethod::BIDI_STREAMING),
- context, start, tag));
- }
-};
-
-typedef TemplatedGenericStub<grpc::ByteBuffer, grpc::ByteBuffer> GenericStub;
-
-} // namespace grpc
-
-#endif // GRPCPP_GENERIC_GENERIC_STUB_H
diff --git a/contrib/libs/grpc/include/grpcpp/support/client_callback.h b/contrib/libs/grpc/include/grpcpp/support/client_callback.h
deleted file mode 100644
index c15bca0dbe8..00000000000
--- a/contrib/libs/grpc/include/grpcpp/support/client_callback.h
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- *
- * Copyright 2018 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPCPP_SUPPORT_CLIENT_CALLBACK_H
-#define GRPCPP_SUPPORT_CLIENT_CALLBACK_H
-
-#include <grpcpp/impl/codegen/client_callback.h> // IWYU pragma: export
-
-#endif // GRPCPP_SUPPORT_CLIENT_CALLBACK_H
diff --git a/contrib/libs/grpc/include/grpcpp/support/server_interceptor.h b/contrib/libs/grpc/include/grpcpp/support/server_interceptor.h
deleted file mode 100644
index ad9c7a18693..00000000000
--- a/contrib/libs/grpc/include/grpcpp/support/server_interceptor.h
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPCPP_SUPPORT_SERVER_INTERCEPTOR_H
-#define GRPCPP_SUPPORT_SERVER_INTERCEPTOR_H
-
-#include <grpcpp/impl/codegen/server_interceptor.h> // IWYU pragma: export
-
-#endif // GRPCPP_SUPPORT_SERVER_INTERCEPTOR_H
diff --git a/contrib/libs/grpc/src/proto/grpc/core/ya.make b/contrib/libs/grpc/src/proto/grpc/core/ya.make
index 29e70a5d56a..c6ebad89408 100644
--- a/contrib/libs/grpc/src/proto/grpc/core/ya.make
+++ b/contrib/libs/grpc/src/proto/grpc/core/ya.make
@@ -1,5 +1,7 @@
PROTO_LIBRARY()
+WITHOUT_LICENSE_TEXTS()
+
LICENSE(Apache-2.0)
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
diff --git a/contrib/libs/grpc/src/proto/grpc/health/v1/ya.make b/contrib/libs/grpc/src/proto/grpc/health/v1/ya.make
index aa5f57c5d1d..87e9e34c1dd 100644
--- a/contrib/libs/grpc/src/proto/grpc/health/v1/ya.make
+++ b/contrib/libs/grpc/src/proto/grpc/health/v1/ya.make
@@ -1,5 +1,7 @@
PROTO_LIBRARY()
+WITHOUT_LICENSE_TEXTS()
+
LICENSE(Apache-2.0)
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
diff --git a/contrib/libs/grpc/src/proto/grpc/status/ya.make b/contrib/libs/grpc/src/proto/grpc/status/ya.make
index 3b9e947b0bb..4641904cabf 100644
--- a/contrib/libs/grpc/src/proto/grpc/status/ya.make
+++ b/contrib/libs/grpc/src/proto/grpc/status/ya.make
@@ -1,5 +1,7 @@
PROTO_LIBRARY()
+WITHOUT_LICENSE_TEXTS()
+
LICENSE(Apache-2.0)
LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/benchmark_service.proto b/contrib/libs/grpc/src/proto/grpc/testing/benchmark_service.proto
deleted file mode 100644
index 63167a8cee6..00000000000
--- a/contrib/libs/grpc/src/proto/grpc/testing/benchmark_service.proto
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2015 gRPC authors.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// An integration test service that covers all the method signature permutations
-// of unary/streaming requests/responses.
-syntax = "proto3";
-
-import "src/proto/grpc/testing/messages.proto";
-
-package grpc.testing;
-
-service BenchmarkService {
- // One request followed by one response.
- // The server returns the client payload as-is.
- rpc UnaryCall(SimpleRequest) returns (SimpleResponse);
-
- // Repeated sequence of one request followed by one response.
- // Should be called streaming ping-pong
- // The server returns the client payload as-is on each response
- rpc StreamingCall(stream SimpleRequest) returns (stream SimpleResponse);
-
- // Single-sided unbounded streaming from client to server
- // The server returns the client payload as-is once the client does WritesDone
- rpc StreamingFromClient(stream SimpleRequest) returns (SimpleResponse);
-
- // Single-sided unbounded streaming from server to client
- // The server repeatedly returns the client payload as-is
- rpc StreamingFromServer(SimpleRequest) returns (stream SimpleResponse);
-
- // Two-sided unbounded streaming between server to client
- // Both sides send the content of their own choice to the other
- rpc StreamingBothWays(stream SimpleRequest) returns (stream SimpleResponse);
-}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/compiler_test.proto b/contrib/libs/grpc/src/proto/grpc/testing/compiler_test.proto
deleted file mode 100644
index 9fa5590a594..00000000000
--- a/contrib/libs/grpc/src/proto/grpc/testing/compiler_test.proto
+++ /dev/null
@@ -1,71 +0,0 @@
-// Copyright 2016 gRPC authors.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// File detached comment 1
-
-// File detached comment 2
-
-// File leading comment 1
-syntax = "proto3";
-
-// Ignored detached comment
-// The comments in this file are not meant for readability
-// but rather to test to make sure that the code generator
-// properly preserves comments on files, services, and RPCs
-
-// Ignored package leading comment
-package grpc.testing;
-
-message Request {
-}
-message Response {
-}
-
-// ServiceA detached comment 1
-
-// ServiceA detached comment 2
-
-// ServiceA leading comment 1
-service ServiceA {
- // MethodA1 leading comment 1
- rpc MethodA1(Request) returns (Response); // MethodA1 trailing comment 1
-
- // MethodA2 detached leading comment 1
-
- // Method A2 leading comment 1
- // Method A2 leading comment 2
- rpc MethodA2(stream Request) returns (Response);
- // MethodA2 trailing comment 1
-
- // Method A3 leading comment 1
- rpc MethodA3(Request) returns (stream Response);
- // Method A3 trailing comment 1
-
- // Method A4 leading comment 1
- rpc MethodA4(stream Request) returns (stream Response);
- // Method A4 trailing comment 1
-}
-// Ignored ServiceA trailing comment 1
-
-// ServiceB leading comment 1
-service ServiceB {
- // ServiceB trailing comment 1
-
- // MethodB1 leading comment 1
- rpc MethodB1(Request) returns (Response);
- // MethodB1 trailing comment 1
-}
-// Ignored ServiceB trailing comment 2
-
-// Ignored file trailing comment
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/control.proto b/contrib/libs/grpc/src/proto/grpc/testing/control.proto
deleted file mode 100644
index 742b21926e7..00000000000
--- a/contrib/libs/grpc/src/proto/grpc/testing/control.proto
+++ /dev/null
@@ -1,289 +0,0 @@
-// Copyright 2015 gRPC authors.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-syntax = "proto3";
-
-import "src/proto/grpc/testing/payloads.proto";
-import "src/proto/grpc/testing/stats.proto";
-
-package grpc.testing;
-
-enum ClientType {
- // Many languages support a basic distinction between using
- // sync or async client, and this allows the specification
- SYNC_CLIENT = 0;
- ASYNC_CLIENT = 1;
- OTHER_CLIENT = 2; // used for some language-specific variants
- CALLBACK_CLIENT = 3;
-}
-
-enum ServerType {
- SYNC_SERVER = 0;
- ASYNC_SERVER = 1;
- ASYNC_GENERIC_SERVER = 2;
- OTHER_SERVER = 3; // used for some language-specific variants
- CALLBACK_SERVER = 4;
-}
-
-enum RpcType {
- UNARY = 0;
- STREAMING = 1;
- STREAMING_FROM_CLIENT = 2;
- STREAMING_FROM_SERVER = 3;
- STREAMING_BOTH_WAYS = 4;
-}
-
-// Parameters of poisson process distribution, which is a good representation
-// of activity coming in from independent identical stationary sources.
-message PoissonParams {
- // The rate of arrivals (a.k.a. lambda parameter of the exp distribution).
- double offered_load = 1;
-}
-
-// Once an RPC finishes, immediately start a new one.
-// No configuration parameters needed.
-message ClosedLoopParams {}
-
-message LoadParams {
- oneof load {
- ClosedLoopParams closed_loop = 1;
- PoissonParams poisson = 2;
- };
-}
-
-// presence of SecurityParams implies use of TLS
-message SecurityParams {
- bool use_test_ca = 1;
- string server_host_override = 2;
- string cred_type = 3;
-}
-
-message ChannelArg {
- string name = 1;
- oneof value {
- string str_value = 2;
- int32 int_value = 3;
- }
-}
-
-message ClientConfig {
- // List of targets to connect to. At least one target needs to be specified.
- repeated string server_targets = 1;
- ClientType client_type = 2;
- SecurityParams security_params = 3;
- // How many concurrent RPCs to start for each channel.
- // For synchronous client, use a separate thread for each outstanding RPC.
- int32 outstanding_rpcs_per_channel = 4;
- // Number of independent client channels to create.
- // i-th channel will connect to server_target[i % server_targets.size()]
- int32 client_channels = 5;
- // Only for async client. Number of threads to use to start/manage RPCs.
- int32 async_client_threads = 7;
- RpcType rpc_type = 8;
- // The requested load for the entire client (aggregated over all the threads).
- LoadParams load_params = 10;
- PayloadConfig payload_config = 11;
- HistogramParams histogram_params = 12;
-
- // Specify the cores we should run the client on, if desired
- repeated int32 core_list = 13;
- int32 core_limit = 14;
-
- // If we use an OTHER_CLIENT client_type, this string gives more detail
- string other_client_api = 15;
-
- repeated ChannelArg channel_args = 16;
-
- // Number of threads that share each completion queue
- int32 threads_per_cq = 17;
-
- // Number of messages on a stream before it gets finished/restarted
- int32 messages_per_stream = 18;
-
- // Use coalescing API when possible.
- bool use_coalesce_api = 19;
-
- // If 0, disabled. Else, specifies the period between gathering latency
- // medians in milliseconds.
- int32 median_latency_collection_interval_millis = 20;
-
- // Number of client processes. 0 indicates no restriction.
- int32 client_processes = 21;
-}
-
-message ClientStatus { ClientStats stats = 1; }
-
-// Request current stats
-message Mark {
- // if true, the stats will be reset after taking their snapshot.
- bool reset = 1;
-}
-
-message ClientArgs {
- oneof argtype {
- ClientConfig setup = 1;
- Mark mark = 2;
- }
-}
-
-message ServerConfig {
- ServerType server_type = 1;
- SecurityParams security_params = 2;
- // Port on which to listen. Zero means pick unused port.
- int32 port = 4;
- // Only for async server. Number of threads used to serve the requests.
- int32 async_server_threads = 7;
- // Specify the number of cores to limit server to, if desired
- int32 core_limit = 8;
- // payload config, used in generic server.
- // Note this must NOT be used in proto (non-generic) servers. For proto servers,
- // 'response sizes' must be configured from the 'response_size' field of the
- // 'SimpleRequest' objects in RPC requests.
- PayloadConfig payload_config = 9;
-
- // Specify the cores we should run the server on, if desired
- repeated int32 core_list = 10;
-
- // If we use an OTHER_SERVER client_type, this string gives more detail
- string other_server_api = 11;
-
- // Number of threads that share each completion queue
- int32 threads_per_cq = 12;
-
- // c++-only options (for now) --------------------------------
-
- // Buffer pool size (no buffer pool specified if unset)
- int32 resource_quota_size = 1001;
- repeated ChannelArg channel_args = 1002;
-
- // Number of server processes. 0 indicates no restriction.
- int32 server_processes = 21;
-}
-
-message ServerArgs {
- oneof argtype {
- ServerConfig setup = 1;
- Mark mark = 2;
- }
-}
-
-message ServerStatus {
- ServerStats stats = 1;
- // the port bound by the server
- int32 port = 2;
- // Number of cores available to the server
- int32 cores = 3;
-}
-
-message CoreRequest {
-}
-
-message CoreResponse {
- // Number of cores available on the server
- int32 cores = 1;
-}
-
-message Void {
-}
-
-// A single performance scenario: input to qps_json_driver
-message Scenario {
- // Human readable name for this scenario
- string name = 1;
- // Client configuration
- ClientConfig client_config = 2;
- // Number of clients to start for the test
- int32 num_clients = 3;
- // Server configuration
- ServerConfig server_config = 4;
- // Number of servers to start for the test
- int32 num_servers = 5;
- // Warmup period, in seconds
- int32 warmup_seconds = 6;
- // Benchmark time, in seconds
- int32 benchmark_seconds = 7;
- // Number of workers to spawn locally (usually zero)
- int32 spawn_local_worker_count = 8;
-}
-
-// A set of scenarios to be run with qps_json_driver
-message Scenarios {
- repeated Scenario scenarios = 1;
-}
-
-// Basic summary that can be computed from ClientStats and ServerStats
-// once the scenario has finished.
-message ScenarioResultSummary
-{
- // Total number of operations per second over all clients. What is counted as 1 'operation' depends on the benchmark scenarios:
- // For unary benchmarks, an operation is processing of a single unary RPC.
- // For streaming benchmarks, an operation is processing of a single ping pong of request and response.
- double qps = 1;
- // QPS per server core.
- double qps_per_server_core = 2;
- // The total server cpu load based on system time across all server processes, expressed as percentage of a single cpu core.
- // For example, 85 implies 85% of a cpu core, 125 implies 125% of a cpu core. Since we are accumulating the cpu load across all the server
- // processes, the value could > 100 when there are multiple servers or a single server using multiple threads and cores.
- // Same explanation for the total client cpu load below.
- double server_system_time = 3;
- // The total server cpu load based on user time across all server processes, expressed as percentage of a single cpu core. (85 => 85%, 125 => 125%)
- double server_user_time = 4;
- // The total client cpu load based on system time across all client processes, expressed as percentage of a single cpu core. (85 => 85%, 125 => 125%)
- double client_system_time = 5;
- // The total client cpu load based on user time across all client processes, expressed as percentage of a single cpu core. (85 => 85%, 125 => 125%)
- double client_user_time = 6;
-
- // X% latency percentiles (in nanoseconds)
- double latency_50 = 7;
- double latency_90 = 8;
- double latency_95 = 9;
- double latency_99 = 10;
- double latency_999 = 11;
-
- // server cpu usage percentage
- double server_cpu_usage = 12;
-
- // Number of requests that succeeded/failed
- double successful_requests_per_second = 13;
- double failed_requests_per_second = 14;
-
- // Number of polls called inside completion queue per request
- double client_polls_per_request = 15;
- double server_polls_per_request = 16;
-
- // Queries per CPU-sec over all servers or clients
- double server_queries_per_cpu_sec = 17;
- double client_queries_per_cpu_sec = 18;
-}
-
-// Results of a single benchmark scenario.
-message ScenarioResult {
- // Inputs used to run the scenario.
- Scenario scenario = 1;
- // Histograms from all clients merged into one histogram.
- HistogramData latencies = 2;
- // Client stats for each client
- repeated ClientStats client_stats = 3;
- // Server stats for each server
- repeated ServerStats server_stats = 4;
- // Number of cores available to each server
- repeated int32 server_cores = 5;
- // An after-the-fact computed summary
- ScenarioResultSummary summary = 6;
- // Information on success or failure of each worker
- repeated bool client_success = 7;
- repeated bool server_success = 8;
- // Number of failed requests (one row per status code seen)
- repeated RequestResultCount request_results = 9;
-}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/duplicate/echo_duplicate.proto b/contrib/libs/grpc/src/proto/grpc/testing/duplicate/echo_duplicate.proto
deleted file mode 100644
index 24b7ee0a246..00000000000
--- a/contrib/libs/grpc/src/proto/grpc/testing/duplicate/echo_duplicate.proto
+++ /dev/null
@@ -1,27 +0,0 @@
-
-// Copyright 2015 gRPC authors.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// This is a partial copy of echo.proto with a different package name.
-
-syntax = "proto3";
-
-import "src/proto/grpc/testing/echo_messages.proto";
-
-package grpc.testing.duplicate;
-
-service EchoTestService {
- rpc Echo(grpc.testing.EchoRequest) returns (grpc.testing.EchoResponse);
- rpc ResponseStream(EchoRequest) returns (stream EchoResponse);
-}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/duplicate/ya.make b/contrib/libs/grpc/src/proto/grpc/testing/duplicate/ya.make
deleted file mode 100644
index 6b97d9e107e..00000000000
--- a/contrib/libs/grpc/src/proto/grpc/testing/duplicate/ya.make
+++ /dev/null
@@ -1,28 +0,0 @@
-PROTO_LIBRARY()
-
-LICENSE(Apache-2.0)
-
-LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-
-EXCLUDE_TAGS(
- GO_PROTO
- PY_PROTO
- PY3_PROTO
-)
-
-PROTO_NAMESPACE(
- GLOBAL
- contrib/libs/grpc
-)
-
-PEERDIR(
- contrib/libs/grpc/src/proto/grpc/testing
-)
-
-GRPC()
-
-SRCS(
- echo_duplicate.proto
-)
-
-END()
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/echo.proto b/contrib/libs/grpc/src/proto/grpc/testing/echo.proto
deleted file mode 100644
index ae38aeaf194..00000000000
--- a/contrib/libs/grpc/src/proto/grpc/testing/echo.proto
+++ /dev/null
@@ -1,70 +0,0 @@
-
-// Copyright 2015 gRPC authors.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-syntax = "proto3";
-
-package grpc.testing;
-
-import "src/proto/grpc/testing/echo_messages.proto";
-import "src/proto/grpc/testing/simple_messages.proto";
-
-service EchoTestService {
- rpc Echo(EchoRequest) returns (EchoResponse);
- rpc Echo1(EchoRequest) returns (EchoResponse);
- rpc Echo2(EchoRequest) returns (EchoResponse);
- rpc CheckDeadlineUpperBound(SimpleRequest42) returns (StringValue);
- rpc CheckDeadlineSet(SimpleRequest42) returns (StringValue);
- // A service which checks that the initial metadata sent over contains some
- // expected key value pair
- rpc CheckClientInitialMetadata(SimpleRequest42) returns (SimpleResponse42);
- rpc RequestStream(stream EchoRequest) returns (EchoResponse);
- rpc ResponseStream(EchoRequest) returns (stream EchoResponse);
- rpc BidiStream(stream EchoRequest) returns (stream EchoResponse);
- rpc Unimplemented(EchoRequest) returns (EchoResponse);
- rpc UnimplementedBidi(stream EchoRequest) returns (stream EchoResponse);
-}
-
-service EchoTest1Service {
- rpc Echo(EchoRequest) returns (EchoResponse);
- rpc Echo1(EchoRequest) returns (EchoResponse);
- rpc Echo2(EchoRequest) returns (EchoResponse);
- // A service which checks that the initial metadata sent over contains some
- // expected key value pair
- rpc CheckClientInitialMetadata(SimpleRequest42) returns (SimpleResponse42);
- rpc RequestStream(stream EchoRequest) returns (EchoResponse);
- rpc ResponseStream(EchoRequest) returns (stream EchoResponse);
- rpc BidiStream(stream EchoRequest) returns (stream EchoResponse);
- rpc Unimplemented(EchoRequest) returns (EchoResponse);
-}
-
-service EchoTest2Service {
- rpc Echo(EchoRequest) returns (EchoResponse);
- rpc Echo1(EchoRequest) returns (EchoResponse);
- rpc Echo2(EchoRequest) returns (EchoResponse);
- // A service which checks that the initial metadata sent over contains some
- // expected key value pair
- rpc CheckClientInitialMetadata(SimpleRequest42) returns (SimpleResponse42);
- rpc RequestStream(stream EchoRequest) returns (EchoResponse);
- rpc ResponseStream(EchoRequest) returns (stream EchoResponse);
- rpc BidiStream(stream EchoRequest) returns (stream EchoResponse);
- rpc Unimplemented(EchoRequest) returns (EchoResponse);
-}
-
-service UnimplementedEchoService {
- rpc Unimplemented(EchoRequest) returns (EchoResponse);
-}
-
-// A service without any rpc defined to test coverage.
-service NoRpcService {}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/echo_messages.proto b/contrib/libs/grpc/src/proto/grpc/testing/echo_messages.proto
deleted file mode 100644
index 6f1e5f34046..00000000000
--- a/contrib/libs/grpc/src/proto/grpc/testing/echo_messages.proto
+++ /dev/null
@@ -1,70 +0,0 @@
-
-// Copyright 2015 gRPC authors.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-syntax = "proto3";
-
-package grpc.testing;
-
-option cc_enable_arenas = true;
-
-// Message to be echoed back serialized in trailer.
-message DebugInfo {
- repeated string stack_entries = 1;
- string detail = 2;
-}
-
-// Error status client expects to see.
-message ErrorStatus {
- int32 code = 1;
- string error_message = 2;
- string binary_error_details = 3;
-}
-
-message RequestParams {
- bool echo_deadline = 1;
- int32 client_cancel_after_us = 2;
- int32 server_cancel_after_us = 3;
- bool echo_metadata = 4;
- bool check_auth_context = 5;
- int32 response_message_length = 6;
- bool echo_peer = 7;
- string expected_client_identity = 8; // will force check_auth_context.
- bool skip_cancelled_check = 9;
- string expected_transport_security_type = 10;
- DebugInfo debug_info = 11;
- bool server_die = 12; // Server should not see a request with this set.
- string binary_error_details = 13;
- ErrorStatus expected_error = 14;
- int32 server_sleep_us = 15; // sleep when invoking server for deadline tests
- int32 backend_channel_idx = 16; // which backend to send request to
- bool echo_metadata_initially = 17;
- bool server_notify_client_when_started = 18;
-}
-
-message EchoRequest {
- string message = 1;
- RequestParams param = 2;
-}
-
-message ResponseParams {
- int64 request_deadline = 1;
- string host = 2;
- string peer = 3;
-}
-
-message EchoResponse {
- string message = 1;
- ResponseParams param = 2;
-}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/empty.proto b/contrib/libs/grpc/src/proto/grpc/testing/empty.proto
deleted file mode 100644
index 6a0aa88dfde..00000000000
--- a/contrib/libs/grpc/src/proto/grpc/testing/empty.proto
+++ /dev/null
@@ -1,28 +0,0 @@
-
-// Copyright 2015 gRPC authors.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-syntax = "proto3";
-
-package grpc.testing;
-
-// An empty message that you can re-use to avoid defining duplicated empty
-// messages in your project. A typical example is to use it as argument or the
-// return value of a service API. For instance:
-//
-// service Foo {
-// rpc Bar (grpc.testing.Empty) returns (grpc.testing.Empty) { };
-// };
-//
-message Empty {}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/empty_service.proto b/contrib/libs/grpc/src/proto/grpc/testing/empty_service.proto
deleted file mode 100644
index 157629b7a45..00000000000
--- a/contrib/libs/grpc/src/proto/grpc/testing/empty_service.proto
+++ /dev/null
@@ -1,23 +0,0 @@
-
-// Copyright 2018 gRPC authors.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-syntax = "proto3";
-
-package grpc.testing;
-
-// A service that has zero methods.
-// See https://github.com/grpc/grpc/issues/15574
-service EmptyService {
-}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/messages.proto b/contrib/libs/grpc/src/proto/grpc/testing/messages.proto
deleted file mode 100644
index 559876ed7c0..00000000000
--- a/contrib/libs/grpc/src/proto/grpc/testing/messages.proto
+++ /dev/null
@@ -1,270 +0,0 @@
-
-// Copyright 2015-2016 gRPC authors.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// Message definitions to be used by integration test service definitions.
-
-syntax = "proto3";
-
-package grpc.testing;
-
-// TODO(dgq): Go back to using well-known types once
-// https://github.com/grpc/grpc/issues/6980 has been fixed.
-// import "google/protobuf/wrappers.proto";
-message BoolValue {
- // The bool value.
- bool value = 1;
-}
-
-// The type of payload that should be returned.
-enum PayloadType {
- // Compressable text format.
- COMPRESSABLE = 0;
-}
-
-// A block of data, to simply increase gRPC message size.
-message Payload {
- // The type of data in body.
- PayloadType type = 1;
- // Primary contents of payload.
- bytes body = 2;
-}
-
-// A protobuf representation for grpc status. This is used by test
-// clients to specify a status that the server should attempt to return.
-message EchoStatus {
- int32 code = 1;
- string message = 2;
-}
-
-// The type of route that a client took to reach a server w.r.t. gRPCLB.
-// The server must fill in "fallback" if it detects that the RPC reached
-// the server via the "gRPCLB fallback" path, and "backend" if it detects
-// that the RPC reached the server via "gRPCLB backend" path (i.e. if it got
-// the address of this server from the gRPCLB server BalanceLoad RPC). Exactly
-// how this detection is done is context and server dependent.
-enum GrpclbRouteType {
- // Server didn't detect the route that a client took to reach it.
- GRPCLB_ROUTE_TYPE_UNKNOWN = 0;
- // Indicates that a client reached a server via gRPCLB fallback.
- GRPCLB_ROUTE_TYPE_FALLBACK = 1;
- // Indicates that a client reached a server as a gRPCLB-given backend.
- GRPCLB_ROUTE_TYPE_BACKEND = 2;
-}
-
-// Unary request.
-message SimpleRequest {
- // Desired payload type in the response from the server.
- // If response_type is RANDOM, server randomly chooses one from other formats.
- PayloadType response_type = 1;
-
- // Desired payload size in the response from the server.
- int32 response_size = 2;
-
- // Optional input payload sent along with the request.
- Payload payload = 3;
-
- // Whether SimpleResponse should include username.
- bool fill_username = 4;
-
- // Whether SimpleResponse should include OAuth scope.
- bool fill_oauth_scope = 5;
-
- // Whether to request the server to compress the response. This field is
- // "nullable" in order to interoperate seamlessly with clients not able to
- // implement the full compression tests by introspecting the call to verify
- // the response's compression status.
- BoolValue response_compressed = 6;
-
- // Whether server should return a given status
- EchoStatus response_status = 7;
-
- // Whether the server should expect this request to be compressed.
- BoolValue expect_compressed = 8;
-
- // Whether SimpleResponse should include server_id.
- bool fill_server_id = 9;
-
- // Whether SimpleResponse should include grpclb_route_type.
- bool fill_grpclb_route_type = 10;
-}
-
-// Unary response, as configured by the request.
-message SimpleResponse {
- // Payload to increase message size.
- Payload payload = 1;
- // The user the request came from, for verifying authentication was
- // successful when the client expected it.
- string username = 2;
- // OAuth scope.
- string oauth_scope = 3;
-
- // Server ID. This must be unique among different server instances,
- // but the same across all RPC's made to a particular server instance.
- string server_id = 4;
- // gRPCLB Path.
- GrpclbRouteType grpclb_route_type = 5;
-
- // Server hostname.
- string hostname = 6;
-}
-
-// Client-streaming request.
-message StreamingInputCallRequest {
- // Optional input payload sent along with the request.
- Payload payload = 1;
-
- // Whether the server should expect this request to be compressed. This field
- // is "nullable" in order to interoperate seamlessly with servers not able to
- // implement the full compression tests by introspecting the call to verify
- // the request's compression status.
- BoolValue expect_compressed = 2;
-
- // Not expecting any payload from the response.
-}
-
-// Client-streaming response.
-message StreamingInputCallResponse {
- // Aggregated size of payloads received from the client.
- int32 aggregated_payload_size = 1;
-}
-
-// Configuration for a particular response.
-message ResponseParameters {
- // Desired payload sizes in responses from the server.
- int32 size = 1;
-
- // Desired interval between consecutive responses in the response stream in
- // microseconds.
- int32 interval_us = 2;
-
- // Whether to request the server to compress the response. This field is
- // "nullable" in order to interoperate seamlessly with clients not able to
- // implement the full compression tests by introspecting the call to verify
- // the response's compression status.
- BoolValue compressed = 3;
-}
-
-// Server-streaming request.
-message StreamingOutputCallRequest {
- // Desired payload type in the response from the server.
- // If response_type is RANDOM, the payload from each response in the stream
- // might be of different types. This is to simulate a mixed type of payload
- // stream.
- PayloadType response_type = 1;
-
- // Configuration for each expected response message.
- repeated ResponseParameters response_parameters = 2;
-
- // Optional input payload sent along with the request.
- Payload payload = 3;
-
- // Whether server should return a given status
- EchoStatus response_status = 7;
-}
-
-// Server-streaming response, as configured by the request and parameters.
-message StreamingOutputCallResponse {
- // Payload to increase response size.
- Payload payload = 1;
-}
-
-// For reconnect interop test only.
-// Client tells server what reconnection parameters it used.
-message ReconnectParams {
- int32 max_reconnect_backoff_ms = 1;
-}
-
-// For reconnect interop test only.
-// Server tells client whether its reconnects are following the spec and the
-// reconnect backoffs it saw.
-message ReconnectInfo {
- bool passed = 1;
- repeated int32 backoff_ms = 2;
-}
-
-message LoadBalancerStatsRequest {
- // Request stats for the next num_rpcs sent by client.
- int32 num_rpcs = 1;
- // If num_rpcs have not completed within timeout_sec, return partial results.
- int32 timeout_sec = 2;
-}
-
-message LoadBalancerStatsResponse {
- message RpcsByPeer {
- // The number of completed RPCs for each peer.
- map<string, int32> rpcs_by_peer = 1;
- }
- // The number of completed RPCs for each peer.
- map<string, int32> rpcs_by_peer = 1;
- // The number of RPCs that failed to record a remote peer.
- int32 num_failures = 2;
- map<string, RpcsByPeer> rpcs_by_method = 3;
-}
-
-// Request for retrieving a test client's accumulated stats.
-message LoadBalancerAccumulatedStatsRequest {}
-
-// Accumulated stats for RPCs sent by a test client.
-message LoadBalancerAccumulatedStatsResponse {
- // The total number of RPCs have ever issued for each type.
- // Deprecated: use stats_per_method.rpcs_started instead.
- map<string, int32> num_rpcs_started_by_method = 1 [deprecated = true];
- // The total number of RPCs have ever completed successfully for each type.
- // Deprecated: use stats_per_method.result instead.
- map<string, int32> num_rpcs_succeeded_by_method = 2 [deprecated = true];
- // The total number of RPCs have ever failed for each type.
- // Deprecated: use stats_per_method.result instead.
- map<string, int32> num_rpcs_failed_by_method = 3 [deprecated = true];
-
- message MethodStats {
- // The number of RPCs that were started for this method.
- int32 rpcs_started = 1;
-
- // The number of RPCs that completed with each status for this method. The
- // key is the integral value of a google.rpc.Code; the value is the count.
- map<int32, int32> result = 2;
- }
-
- // Per-method RPC statistics. The key is the RpcType in string form; e.g.
- // 'EMPTY_CALL' or 'UNARY_CALL'
- map<string, MethodStats> stats_per_method = 4;
-}
-
-// Configurations for a test client.
-message ClientConfigureRequest {
- // Type of RPCs to send.
- enum RpcType {
- EMPTY_CALL = 0;
- UNARY_CALL = 1;
- }
-
- // Metadata to be attached for the given type of RPCs.
- message Metadata {
- RpcType type = 1;
- string key = 2;
- string value = 3;
- }
-
- // The types of RPCs the client sends.
- repeated RpcType types = 1;
- // The collection of custom metadata to be attached to RPCs sent by the client.
- repeated Metadata metadata = 2;
- // The deadline to use, in seconds, for all RPCs. If unset or zero, the
- // client will use the default from the command-line.
- int32 timeout_sec = 3;
-}
-
-// Response for updating a test client's configuration.
-message ClientConfigureResponse {}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/metrics.proto b/contrib/libs/grpc/src/proto/grpc/testing/metrics.proto
deleted file mode 100644
index 69504006431..00000000000
--- a/contrib/libs/grpc/src/proto/grpc/testing/metrics.proto
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright 2015-2016 gRPC authors.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// Contains the definitions for a metrics service and the type of metrics
-// exposed by the service.
-//
-// Currently, 'Gauge' (i.e a metric that represents the measured value of
-// something at an instant of time) is the only metric type supported by the
-// service.
-syntax = "proto3";
-
-package grpc.testing;
-
-// Response message containing the gauge name and value
-message GaugeResponse {
- string name = 1;
- oneof value {
- int64 long_value = 2;
- double double_value = 3;
- string string_value = 4;
- }
-}
-
-// Request message containing the gauge name
-message GaugeRequest {
- string name = 1;
-}
-
-message EmptyMessage {}
-
-service MetricsService {
- // Returns the values of all the gauges that are currently being maintained by
- // the service
- rpc GetAllGauges(EmptyMessage) returns (stream GaugeResponse);
-
- // Returns the value of one gauge
- rpc GetGauge(GaugeRequest) returns (GaugeResponse);
-}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/payloads.proto b/contrib/libs/grpc/src/proto/grpc/testing/payloads.proto
deleted file mode 100644
index 4feab92eab6..00000000000
--- a/contrib/libs/grpc/src/proto/grpc/testing/payloads.proto
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright 2015 gRPC authors.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-syntax = "proto3";
-
-package grpc.testing;
-
-message ByteBufferParams {
- int32 req_size = 1;
- int32 resp_size = 2;
-}
-
-message SimpleProtoParams {
- int32 req_size = 1;
- int32 resp_size = 2;
-}
-
-message ComplexProtoParams {
- // TODO (vpai): Fill this in once the details of complex, representative
- // protos are decided
-}
-
-message PayloadConfig {
- oneof payload {
- ByteBufferParams bytebuf_params = 1;
- SimpleProtoParams simple_params = 2;
- ComplexProtoParams complex_params = 3;
- }
-}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/proxy-service.proto b/contrib/libs/grpc/src/proto/grpc/testing/proxy-service.proto
deleted file mode 100644
index deaabd13651..00000000000
--- a/contrib/libs/grpc/src/proto/grpc/testing/proxy-service.proto
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright 2017 gRPC authors.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-syntax = "proto3";
-
-import "src/proto/grpc/testing/control.proto";
-import "src/proto/grpc/testing/stats.proto";
-
-package grpc.testing;
-
-message ProxyStat {
- double latency = 1;
-}
-
-service ProxyClientService {
- rpc GetConfig(Void) returns (ClientConfig);
- rpc ReportTime(stream ProxyStat) returns (Void);
- rpc ReportHist(stream HistogramData) returns (Void);
-}
-
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/report_qps_scenario_service.proto b/contrib/libs/grpc/src/proto/grpc/testing/report_qps_scenario_service.proto
deleted file mode 100644
index f4e5c36254c..00000000000
--- a/contrib/libs/grpc/src/proto/grpc/testing/report_qps_scenario_service.proto
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright 2015 gRPC authors.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// An integration test service that covers all the method signature permutations
-// of unary/streaming requests/responses.
-syntax = "proto3";
-
-import "src/proto/grpc/testing/control.proto";
-
-package grpc.testing;
-
-service ReportQpsScenarioService {
- // Report results of a QPS test benchmark scenario.
- rpc ReportScenario(ScenarioResult) returns (Void);
-}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/simple_messages.proto b/contrib/libs/grpc/src/proto/grpc/testing/simple_messages.proto
deleted file mode 100644
index 6fbb395a448..00000000000
--- a/contrib/libs/grpc/src/proto/grpc/testing/simple_messages.proto
+++ /dev/null
@@ -1,26 +0,0 @@
-
-// Copyright 2018 gRPC authors.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-syntax = "proto3";
-
-package grpc.testing;
-
-message SimpleRequest42 {}
-
-message SimpleResponse42 {}
-
-message StringValue {
- string message = 1;
-}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/stats.proto b/contrib/libs/grpc/src/proto/grpc/testing/stats.proto
deleted file mode 100644
index a0f84ddbcee..00000000000
--- a/contrib/libs/grpc/src/proto/grpc/testing/stats.proto
+++ /dev/null
@@ -1,83 +0,0 @@
-// Copyright 2015 gRPC authors.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-syntax = "proto3";
-
-package grpc.testing;
-
-import "src/proto/grpc/core/stats.proto";
-
-message ServerStats {
- // wall clock time change in seconds since last reset
- double time_elapsed = 1;
-
- // change in user time (in seconds) used by the server since last reset
- double time_user = 2;
-
- // change in server time (in seconds) used by the server process and all
- // threads since last reset
- double time_system = 3;
-
- // change in total cpu time of the server (data from proc/stat)
- uint64 total_cpu_time = 4;
-
- // change in idle time of the server (data from proc/stat)
- uint64 idle_cpu_time = 5;
-
- // Number of polls called inside completion queue
- uint64 cq_poll_count = 6;
-
- // Core library stats
- grpc.core.Stats core_stats = 7;
-}
-
-// Histogram params based on grpc/support/histogram.c
-message HistogramParams {
- double resolution = 1; // first bucket is [0, 1 + resolution)
- double max_possible = 2; // use enough buckets to allow this value
-}
-
-// Histogram data based on grpc/support/histogram.c
-message HistogramData {
- repeated uint32 bucket = 1;
- double min_seen = 2;
- double max_seen = 3;
- double sum = 4;
- double sum_of_squares = 5;
- double count = 6;
-}
-
-message RequestResultCount {
- int32 status_code = 1;
- int64 count = 2;
-}
-
-message ClientStats {
- // Latency histogram. Data points are in nanoseconds.
- HistogramData latencies = 1;
-
- // See ServerStats for details.
- double time_elapsed = 2;
- double time_user = 3;
- double time_system = 4;
-
- // Number of failed requests (one row per status code seen)
- repeated RequestResultCount request_results = 5;
-
- // Number of polls called inside completion queue
- uint64 cq_poll_count = 6;
-
- // Core library stats
- grpc.core.Stats core_stats = 7;
-}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/test.proto b/contrib/libs/grpc/src/proto/grpc/testing/test.proto
deleted file mode 100644
index 5805a41da99..00000000000
--- a/contrib/libs/grpc/src/proto/grpc/testing/test.proto
+++ /dev/null
@@ -1,102 +0,0 @@
-
-// Copyright 2015-2016 gRPC authors.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// An integration test service that covers all the method signature permutations
-// of unary/streaming requests/responses.
-
-syntax = "proto3";
-
-import "src/proto/grpc/testing/empty.proto";
-import "src/proto/grpc/testing/messages.proto";
-
-package grpc.testing;
-
-// A simple service to test the various types of RPCs and experiment with
-// performance with various types of payload.
-service TestService {
- // One empty request followed by one empty response.
- rpc EmptyCall(grpc.testing.Empty) returns (grpc.testing.Empty);
-
- // One request followed by one response.
- rpc UnaryCall(SimpleRequest) returns (SimpleResponse);
-
- // One request followed by one response. Response has cache control
- // headers set such that a caching HTTP proxy (such as GFE) can
- // satisfy subsequent requests.
- rpc CacheableUnaryCall(SimpleRequest) returns (SimpleResponse);
-
- // One request followed by a sequence of responses (streamed download).
- // The server returns the payload with client desired type and sizes.
- rpc StreamingOutputCall(StreamingOutputCallRequest)
- returns (stream StreamingOutputCallResponse);
-
- // A sequence of requests followed by one response (streamed upload).
- // The server returns the aggregated size of client payload as the result.
- rpc StreamingInputCall(stream StreamingInputCallRequest)
- returns (StreamingInputCallResponse);
-
- // A sequence of requests with each request served by the server immediately.
- // As one request could lead to multiple responses, this interface
- // demonstrates the idea of full duplexing.
- rpc FullDuplexCall(stream StreamingOutputCallRequest)
- returns (stream StreamingOutputCallResponse);
-
- // A sequence of requests followed by a sequence of responses.
- // The server buffers all the client requests and then serves them in order. A
- // stream of responses are returned to the client when the server starts with
- // first request.
- rpc HalfDuplexCall(stream StreamingOutputCallRequest)
- returns (stream StreamingOutputCallResponse);
-
- // The test server will not implement this method. It will be used
- // to test the behavior when clients call unimplemented methods.
- rpc UnimplementedCall(grpc.testing.Empty) returns (grpc.testing.Empty);
-}
-
-// A simple service NOT implemented at servers so clients can test for
-// that case.
-service UnimplementedService {
- // A call that no server should implement
- rpc UnimplementedCall(grpc.testing.Empty) returns (grpc.testing.Empty);
-}
-
-// A service used to control reconnect server.
-service ReconnectService {
- rpc Start(grpc.testing.ReconnectParams) returns (grpc.testing.Empty);
- rpc Stop(grpc.testing.Empty) returns (grpc.testing.ReconnectInfo);
-}
-
-// A service used to obtain stats for verifying LB behavior.
-service LoadBalancerStatsService {
- // Gets the backend distribution for RPCs sent by a test client.
- rpc GetClientStats(LoadBalancerStatsRequest)
- returns (LoadBalancerStatsResponse) {}
-
- // Gets the accumulated stats for RPCs sent by a test client.
- rpc GetClientAccumulatedStats(LoadBalancerAccumulatedStatsRequest)
- returns (LoadBalancerAccumulatedStatsResponse) {}
-}
-
-// A service to remotely control health status of an xDS test server.
-service XdsUpdateHealthService {
- rpc SetServing(grpc.testing.Empty) returns (grpc.testing.Empty);
- rpc SetNotServing(grpc.testing.Empty) returns (grpc.testing.Empty);
-}
-
-// A service to dynamically update the configuration of an xDS test client.
-service XdsUpdateClientConfigureService {
- // Update the tes client's configuration.
- rpc Configure(ClientConfigureRequest) returns (ClientConfigureResponse);
-}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/worker_service.proto b/contrib/libs/grpc/src/proto/grpc/testing/worker_service.proto
deleted file mode 100644
index a4cde944b07..00000000000
--- a/contrib/libs/grpc/src/proto/grpc/testing/worker_service.proto
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright 2015 gRPC authors.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// An integration test service that covers all the method signature permutations
-// of unary/streaming requests/responses.
-syntax = "proto3";
-
-import "src/proto/grpc/testing/control.proto";
-
-package grpc.testing;
-
-service WorkerService {
- // Start server with specified workload.
- // First request sent specifies the ServerConfig followed by ServerStatus
- // response. After that, a "Mark" can be sent anytime to request the latest
- // stats. Closing the stream will initiate shutdown of the test server
- // and once the shutdown has finished, the OK status is sent to terminate
- // this RPC.
- rpc RunServer(stream ServerArgs) returns (stream ServerStatus);
-
- // Start client with specified workload.
- // First request sent specifies the ClientConfig followed by ClientStatus
- // response. After that, a "Mark" can be sent anytime to request the latest
- // stats. Closing the stream will initiate shutdown of the test client
- // and once the shutdown has finished, the OK status is sent to terminate
- // this RPC.
- rpc RunClient(stream ClientArgs) returns (stream ClientStatus);
-
- // Just return the core count - unary call
- rpc CoreCount(CoreRequest) returns (CoreResponse);
-
- // Quit this worker
- rpc QuitWorker(Void) returns (Void);
-}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/xds/ads_for_test.proto b/contrib/libs/grpc/src/proto/grpc/testing/xds/ads_for_test.proto
deleted file mode 100644
index 0d308fbbeac..00000000000
--- a/contrib/libs/grpc/src/proto/grpc/testing/xds/ads_for_test.proto
+++ /dev/null
@@ -1,51 +0,0 @@
-// Copyright 2019 The gRPC Authors
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// This file contains the eds protocol and its dependency.
-//
-// TODO(juanlishen): This file is a hack to avoid a problem we're
-// currently having where we can't depend on a proto file in an external
-// repo due to bazel limitations. Once that's fixed, this should be
-// removed. Until this, it should be used in the gRPC tests only, or else it
-// will cause a conflict due to the same proto messages being defined in
-// multiple files in the same binary.
-
-syntax = "proto3";
-
-package envoy.service.discovery.v2;
-
-import "src/proto/grpc/testing/xds/eds_for_test.proto";
-
-// [#not-implemented-hide:] Discovery services for endpoints, clusters, routes,
-// and listeners are retained in the package `envoy.api.v2` for backwards
-// compatibility with existing management servers. New development in discovery
-// services should proceed in the package `envoy.service.discovery.v2`.
-
-// See https://github.com/lyft/envoy-api#apis for a description of the role of
-// ADS and how it is intended to be used by a management server. ADS requests
-// have the same structure as their singleton xDS counterparts, but can
-// multiplex many resource types on a single stream. The type_url in the
-// DiscoveryRequest/DiscoveryResponse provides sufficient information to recover
-// the multiplexed singleton APIs at the Envoy instance and management server.
-service AggregatedDiscoveryService {
- // This is a gRPC-only API.
- rpc StreamAggregatedResources(stream envoy.api.v2.DiscoveryRequest)
- returns (stream envoy.api.v2.DiscoveryResponse) {
- }
-
- // Commented out so that we don't have to copy the request/response protos.
-// rpc DeltaAggregatedResources(stream api.v2.DeltaDiscoveryRequest)
-// returns (stream api.v2.DeltaDiscoveryResponse) {
-// }
-}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/xds/cds_for_test.proto b/contrib/libs/grpc/src/proto/grpc/testing/xds/cds_for_test.proto
deleted file mode 100644
index 3d3c1c164fb..00000000000
--- a/contrib/libs/grpc/src/proto/grpc/testing/xds/cds_for_test.proto
+++ /dev/null
@@ -1,186 +0,0 @@
-// Copyright 2019 The gRPC Authors
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// This file contains the xds protocol and its dependency. It can't be used by
-// the gRPC library; otherwise there can be duplicate definition problems if
-// users depend on both gRPC and Envoy. It can only be used by gRPC tests.
-//
-// TODO(juanlishen): This file is a hack to avoid a problem we're
-// currently having where we can't depend on a proto file in an external
-// repo due to bazel limitations. Once that's fixed, this should be
-// removed. Until this, it should be used in the gRPC tests only, or else it
-// will cause a conflict due to the same proto messages being defined in
-// multiple files in the same binary.
-
-syntax = "proto3";
-
-package envoy.api.v2;
-
-import "google/protobuf/wrappers.proto";
-
-// Aggregated Discovery Service (ADS) options. This is currently empty, but when
-// set in :ref:`ConfigSource <envoy_api_msg_core.ConfigSource>` can be used to
-// specify that ADS is to be used.
-message AggregatedConfigSource {
-}
-
-message SelfConfigSource {
-}
-
-message ConfigSource {
- oneof config_source_specifier {
- // When set, ADS will be used to fetch resources. The ADS API configuration
- // source in the bootstrap configuration is used.
- AggregatedConfigSource ads = 3;
-
- // [#not-implemented-hide:]
- // When set, the client will access the resources from the same server it got the
- // ConfigSource from, although not necessarily from the same stream. This is similar to the
- // :ref:`ads<envoy_api_field.ConfigSource.ads>` field, except that the client may use a
- // different stream to the same server. As a result, this field can be used for things
- // like LRS that cannot be sent on an ADS stream. It can also be used to link from (e.g.)
- // LDS to RDS on the same server without requiring the management server to know its name
- // or required credentials.
- // [#next-major-version: In xDS v3, consider replacing the ads field with this one, since
- // this field can implicitly mean to use the same stream in the case where the ConfigSource
- // is provided via ADS and the specified data can also be obtained via ADS.]
- SelfConfigSource self = 5;
- }
-}
-
-enum RoutingPriority {
- DEFAULT = 0;
- HIGH = 1;
-}
-
-message CircuitBreakers {
- message Thresholds {
- RoutingPriority priority = 1;
- google.protobuf.UInt32Value max_requests = 4;
- }
- repeated Thresholds thresholds = 1;
-}
-
-message ClusterConfig {
- repeated string clusters = 1;
-}
-
-message CustomClusterType {
- string name = 1;
- ClusterConfig typed_config = 2;
-}
-
-message Cluster {
- // Refer to :ref:`service discovery type <arch_overview_service_discovery_types>`
- // for an explanation on each type.
- enum DiscoveryType {
- // Refer to the :ref:`static discovery type<arch_overview_service_discovery_types_static>`
- // for an explanation.
- STATIC = 0;
-
- // Refer to the :ref:`strict DNS discovery
- // type<arch_overview_service_discovery_types_strict_dns>`
- // for an explanation.
- STRICT_DNS = 1;
-
- // Refer to the :ref:`logical DNS discovery
- // type<arch_overview_service_discovery_types_logical_dns>`
- // for an explanation.
- LOGICAL_DNS = 2;
-
- // Refer to the :ref:`service discovery type<arch_overview_service_discovery_types_eds>`
- // for an explanation.
- EDS = 3;
-
- // Refer to the :ref:`original destination discovery
- // type<arch_overview_service_discovery_types_original_destination>`
- // for an explanation.
- ORIGINAL_DST = 4;
- }
-
- string name = 1;
-
- oneof cluster_discovery_type {
- // The :ref:`service discovery type <arch_overview_service_discovery_types>`
- // to use for resolving the cluster.
- DiscoveryType type = 2;
-
- // The custom cluster type: aggregate cluster in this case.
- CustomClusterType cluster_type = 38;
- }
-
- // Only valid when discovery type is EDS.
- message EdsClusterConfig {
- // Configuration for the source of EDS updates for this Cluster.
- ConfigSource eds_config = 1;
-
- // Optional alternative to cluster name to present to EDS. This does not
- // have the same restrictions as cluster name, i.e. it may be arbitrary
- // length.
- string service_name = 2;
- }
-
- // Refer to :ref:`load balancer type <arch_overview_load_balancing_types>` architecture
- // overview section for information on each type.
- enum LbPolicy {
- // Refer to the :ref:`round robin load balancing
- // policy<arch_overview_load_balancing_types_round_robin>`
- // for an explanation.
- ROUND_ROBIN = 0;
-
- // Refer to the :ref:`least request load balancing
- // policy<arch_overview_load_balancing_types_least_request>`
- // for an explanation.
- LEAST_REQUEST = 1;
-
- // Refer to the :ref:`ring hash load balancing
- // policy<arch_overview_load_balancing_types_ring_hash>`
- // for an explanation.
- RING_HASH = 2;
-
- // Refer to the :ref:`random load balancing
- // policy<arch_overview_load_balancing_types_random>`
- // for an explanation.
- RANDOM = 3;
-
- // Refer to the :ref:`original destination load balancing
- // policy<arch_overview_load_balancing_types_original_destination>`
- // for an explanation.
- //
- // .. attention::
- //
- // **This load balancing policy is deprecated**. Use CLUSTER_PROVIDED instead.
- //
- ORIGINAL_DST_LB = 4;
-
- // Refer to the :ref:`Maglev load balancing policy<arch_overview_load_balancing_types_maglev>`
- // for an explanation.
- MAGLEV = 5;
-
- // This load balancer type must be specified if the configured cluster provides a cluster
- // specific load balancer. Consult the configured cluster's documentation for whether to set
- // this option or not.
- CLUSTER_PROVIDED = 6;
- }
- // The :ref:`load balancer type <arch_overview_load_balancing_types>` to use
- // when picking a host in the cluster.
- LbPolicy lb_policy = 6;
-
- // Configuration to use for EDS updates for the Cluster.
- EdsClusterConfig eds_cluster_config = 3;
-
- CircuitBreakers circuit_breakers = 10;
-
- ConfigSource lrs_server = 42;
-}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/xds/eds_for_test.proto b/contrib/libs/grpc/src/proto/grpc/testing/xds/eds_for_test.proto
deleted file mode 100644
index 3b8ce66f0e5..00000000000
--- a/contrib/libs/grpc/src/proto/grpc/testing/xds/eds_for_test.proto
+++ /dev/null
@@ -1,517 +0,0 @@
-// Copyright 2019 The gRPC Authors
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// This file contains the xds protocol and its dependency. It can't be used by
-// the gRPC library; otherwise there can be duplicate definition problems if
-// users depend on both gRPC and Envoy. It can only be used by gRPC tests.
-//
-// TODO(juanlishen): This file is a hack to avoid a problem we're
-// currently having where we can't depend on a proto file in an external
-// repo due to bazel limitations. Once that's fixed, this should be
-// removed. Until this, it should be used in the gRPC tests only, or else it
-// will cause a conflict due to the same proto messages being defined in
-// multiple files in the same binary.
-
-syntax = "proto3";
-
-package envoy.api.v2;
-
-import "google/protobuf/any.proto";
-import "google/protobuf/struct.proto";
-import "google/protobuf/wrappers.proto";
-
-message Status {
- // The status code, which should be an enum value of [google.rpc.Code][].
- int32 code = 1;
-
- // A developer-facing error message, which should be in English. Any
- // user-facing error message should be localized and sent in the
- // [google.rpc.Status.details][] field, or localized by the client.
- string message = 2;
-
- // A list of messages that carry the error details. There is a common set of
- // message types for APIs to use.
- repeated google.protobuf.Any details = 3;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-// Identifies location of where either Envoy runs or where upstream hosts run.
-message Locality {
- // Region this :ref:`zone <envoy_api_field_core.Locality.zone>` belongs to.
- string region = 1;
-
- // Defines the local service zone where Envoy is running. Though optional, it
- // should be set if discovery service routing is used and the discovery
- // service exposes :ref:`zone data <envoy_api_field_endpoint.LocalityLbEndpoints.locality>`,
- // either in this message or via :option:`--service-zone`. The meaning of zone
- // is context dependent, e.g. `Availability Zone (AZ)
- // <https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html>`_
- // on AWS, `Zone <https://cloud.google.com/compute/docs/regions-zones/>`_ on
- // GCP, etc.
- string zone = 2;
-
- // When used for locality of upstream hosts, this field further splits zone
- // into smaller chunks of sub-zones so they can be load balanced
- // independently.
- string sub_zone = 3;
-}
-
-// Identifies a specific Envoy instance. The node identifier is presented to the
-// management server, which may use this identifier to distinguish per Envoy
-// configuration for serving.
-message Node {
- // An opaque node identifier for the Envoy node. This also provides the local
- // service node name. It should be set if any of the following features are
- // used: :ref:`statsd <arch_overview_statistics>`, :ref:`CDS
- // <config_cluster_manager_cds>`, and :ref:`HTTP tracing
- // <arch_overview_tracing>`, either in this message or via
- // :option:`--service-node`.
- string id = 1;
-
- // Defines the local service cluster name where Envoy is running. Though
- // optional, it should be set if any of the following features are used:
- // :ref:`statsd <arch_overview_statistics>`, :ref:`health check cluster
- // verification <envoy_api_field_core.HealthCheck.HttpHealthCheck.service_name>`,
- // :ref:`runtime override directory <envoy_api_msg_config.bootstrap.v2.Runtime>`,
- // :ref:`user agent addition
- // <envoy_api_field_config.filter.network.http_connection_manager.v2.HttpConnectionManager.add_user_agent>`,
- // :ref:`HTTP global rate limiting <config_http_filters_rate_limit>`,
- // :ref:`CDS <config_cluster_manager_cds>`, and :ref:`HTTP tracing
- // <arch_overview_tracing>`, either in this message or via
- // :option:`--service-cluster`.
- string cluster = 2;
-
- // Opaque metadata extending the node identifier. Envoy will pass this
- // directly to the management server.
- google.protobuf.Struct metadata = 3;
-
- // Locality specifying where the Envoy instance is running.
- Locality locality = 4;
-
- // This is motivated by informing a management server during canary which
- // version of Envoy is being tested in a heterogeneous fleet. This will be set
- // by Envoy in management server RPCs.
- string build_version = 5 [deprecated = true];
-
- // Free-form string that identifies the entity requesting config.
- // E.g. "envoy" or "grpc"
- string user_agent_name = 6;
-
- oneof user_agent_version_type {
- // Free-form string that identifies the version of the entity requesting config.
- // E.g. "1.12.2" or "abcd1234", or "SpecialEnvoyBuild"
- string user_agent_version = 7;
- }
-
- // Client feature support list. These are well known features described
- // in the Envoy API repository for a given major version of an API. Client features
- // use reverse DNS naming scheme, for example `com.acme.feature`.
- // See :ref:`the list of features <client_features>` that xDS client may
- // support.
- repeated string client_features = 10;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-// A DiscoveryRequest requests a set of versioned resources of the same type for
-// a given Envoy node on some API.
-message DiscoveryRequest {
- // The version_info provided in the request messages will be the version_info
- // received with the most recent successfully processed response or empty on
- // the first request. It is expected that no new request is sent after a
- // response is received until the Envoy instance is ready to ACK/NACK the new
- // configuration. ACK/NACK takes place by returning the new API config version
- // as applied or the previous API config version respectively. Each type_url
- // (see below) has an independent version associated with it.
- string version_info = 1;
-
- // The node making the request.
- Node node = 2;
-
- // List of resources to subscribe to, e.g. list of cluster names or a route
- // configuration name. If this is empty, all resources for the API are
- // returned. LDS/CDS expect empty resource_names, since this is global
- // discovery for the Envoy instance. The LDS and CDS responses will then imply
- // a number of resources that need to be fetched via EDS/RDS, which will be
- // explicitly enumerated in resource_names.
- repeated string resource_names = 3;
-
- // Type of the resource that is being requested, e.g.
- // "type.googleapis.com/envoy.api.v2.ClusterLoadAssignment". This is implicit
- // in requests made via singleton xDS APIs such as CDS, LDS, etc. but is
- // required for ADS.
- string type_url = 4;
-
- // nonce corresponding to DiscoveryResponse being ACK/NACKed. See above
- // discussion on version_info and the DiscoveryResponse nonce comment. This
- // may be empty if no nonce is available, e.g. at startup or for non-stream
- // xDS implementations.
- string response_nonce = 5;
-
- // This is populated when the previous :ref:`DiscoveryResponse <envoy_api_msg_DiscoveryResponse>`
- // failed to update configuration. The *message* field in *error_details* provides the Envoy
- // internal exception related to the failure. It is only intended for consumption during manual
- // debugging, the string provided is not guaranteed to be stable across Envoy versions.
- Status error_detail = 6;
-}
-
-message DiscoveryResponse {
- // The version of the response data.
- string version_info = 1;
-
- // The response resources. These resources are typed and depend on the API being called.
- repeated google.protobuf.Any resources = 2;
-
- // [#not-implemented-hide:]
- // Canary is used to support two Envoy command line flags:
- //
- // * --terminate-on-canary-transition-failure. When set, Envoy is able to
- // terminate if it detects that configuration is stuck at canary. Consider
- // this example sequence of updates:
- // - Management server applies a canary config successfully.
- // - Management server rolls back to a production config.
- // - Envoy rejects the new production config.
- // Since there is no sensible way to continue receiving configuration
- // updates, Envoy will then terminate and apply production config from a
- // clean slate.
- // * --dry-run-canary. When set, a canary response will never be applied, only
- // validated via a dry run.
- bool canary = 3;
-
- // Type URL for resources. This must be consistent with the type_url in the
- // Any messages for resources if resources is non-empty. This effectively
- // identifies the xDS API when muxing over ADS.
- string type_url = 4;
-
- // For gRPC based subscriptions, the nonce provides a way to explicitly ack a
- // specific DiscoveryResponse in a following DiscoveryRequest. Additional
- // messages may have been sent by Envoy to the management server for the
- // previous version on the stream prior to this DiscoveryResponse, that were
- // unprocessed at response send time. The nonce allows the management server
- // to ignore any further DiscoveryRequests for the previous version until a
- // DiscoveryRequest bearing the nonce. The nonce is optional and is not
- // required for non-stream based xDS implementations.
- string nonce = 5;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-message Pipe {
- // Unix Domain Socket path. On Linux, paths starting with '@' will use the
- // abstract namespace. The starting '@' is replaced by a null byte by Envoy.
- // Paths starting with '@' will result in an error in environments other than
- // Linux.
- string path = 1;
-}
-
-message SocketAddress {
- enum Protocol {
- TCP = 0;
- // [#not-implemented-hide:]
- UDP = 1;
- }
- Protocol protocol = 1;
- // The address for this socket. :ref:`Listeners <config_listeners>` will bind
- // to the address. An empty address is not allowed. Specify ``0.0.0.0`` or ``::``
- // to bind to any address. [#comment:TODO(zuercher) reinstate when implemented:
- // It is possible to distinguish a Listener address via the prefix/suffix matching
- // in :ref:`FilterChainMatch <envoy_api_msg_listener.FilterChainMatch>`.] When used
- // within an upstream :ref:`BindConfig <envoy_api_msg_core.BindConfig>`, the address
- // controls the source address of outbound connections. For :ref:`clusters
- // <envoy_api_msg_Cluster>`, the cluster type determines whether the
- // address must be an IP (*STATIC* or *EDS* clusters) or a hostname resolved by DNS
- // (*STRICT_DNS* or *LOGICAL_DNS* clusters). Address resolution can be customized
- // via :ref:`resolver_name <envoy_api_field_core.SocketAddress.resolver_name>`.
- string address = 2;
- oneof port_specifier {
- uint32 port_value = 3;
- // This is only valid if :ref:`resolver_name
- // <envoy_api_field_core.SocketAddress.resolver_name>` is specified below and the
- // named resolver is capable of named port resolution.
- string named_port = 4;
- }
- // The name of the resolver. This must have been registered with Envoy. If this is
- // empty, a context dependent default applies. If address is a hostname this
- // should be set for resolution other than DNS. If the address is a concrete
- // IP address, no resolution will occur.
- string resolver_name = 5;
-
- // When binding to an IPv6 address above, this enables `IPv4 compatibity
- // <https://tools.ietf.org/html/rfc3493#page-11>`_. Binding to ``::`` will
- // allow both IPv4 and IPv6 connections, with peer IPv4 addresses mapped into
- // IPv6 space as ``::FFFF:<IPv4-address>``.
- bool ipv4_compat = 6;
-}
-
-// Addresses specify either a logical or physical address and port, which are
-// used to tell Envoy where to bind/listen, connect to upstream and find
-// management servers.
-message Address {
- oneof address {
-
- SocketAddress socket_address = 1;
- Pipe pipe = 2;
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-message Metadata {
- // Key is the reverse DNS filter name, e.g. com.acme.widget. The envoy.*
- // namespace is reserved for Envoy's built-in filters.
- map<string, google.protobuf.Struct> filter_metadata = 1;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-// Endpoint health status.
-enum HealthStatus {
- // The health status is not known. This is interpreted by Envoy as *HEALTHY*.
- UNKNOWN = 0;
-
- // Healthy.
- HEALTHY = 1;
-
- // Unhealthy.
- UNHEALTHY = 2;
-
- // Connection draining in progress. E.g.,
- // `<https://aws.amazon.com/blogs/aws/elb-connection-draining-remove-instances-from-service-with-care/>`_
- // or
- // `<https://cloud.google.com/compute/docs/load-balancing/enabling-connection-draining>`_.
- // This is interpreted by Envoy as *UNHEALTHY*.
- DRAINING = 3;
-
- // Health check timed out. This is part of HDS and is interpreted by Envoy as
- // *UNHEALTHY*.
- TIMEOUT = 4;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-// Upstream host identifier.
-message Endpoint {
- // The upstream host address.
- //
- // .. attention::
- //
- // The form of host address depends on the given cluster type. For STATIC or EDS,
- // it is expected to be a direct IP address (or something resolvable by the
- // specified :ref:`resolver <envoy_api_field_core.SocketAddress.resolver_name>`
- // in the Address). For LOGICAL or STRICT DNS, it is expected to be hostname,
- // and will be resolved via DNS.
- Address address = 1;
-
- // The optional health check configuration.
- message HealthCheckConfig {
- // Optional alternative health check port value.
- //
- // By default the health check address port of an upstream host is the same
- // as the host's serving address port. This provides an alternative health
- // check port. Setting this with a non-zero value allows an upstream host
- // to have different health check address port.
- uint32 port_value = 1;
- }
-
- // The optional health check configuration is used as configuration for the
- // health checker to contact the health checked host.
- //
- // .. attention::
- //
- // This takes into effect only for upstream clusters with
- // :ref:`active health checking <arch_overview_health_checking>` enabled.
- HealthCheckConfig health_check_config = 2;
-}
-
-// An Endpoint that Envoy can route traffic to.
-message LbEndpoint {
- // Upstream host identifier
- Endpoint endpoint = 1;
-
- // Optional health status when known and supplied by EDS server.
- HealthStatus health_status = 2;
-
- // The endpoint metadata specifies values that may be used by the load
- // balancer to select endpoints in a cluster for a given request. The filter
- // name should be specified as *envoy.lb*. An example boolean key-value pair
- // is *canary*, providing the optional canary status of the upstream host.
- // This may be matched against in a route's
- // :ref:`RouteAction <envoy_api_msg_route.RouteAction>` metadata_match field
- // to subset the endpoints considered in cluster load balancing.
- Metadata metadata = 3;
-
- // The optional load balancing weight of the upstream host, in the range 1 -
- // 128. Envoy uses the load balancing weight in some of the built in load
- // balancers. The load balancing weight for an endpoint is divided by the sum
- // of the weights of all endpoints in the endpoint's locality to produce a
- // percentage of traffic for the endpoint. This percentage is then further
- // weighted by the endpoint's locality's load balancing weight from
- // LocalityLbEndpoints. If unspecified, each host is presumed to have equal
- // weight in a locality.
- //
- // .. attention::
- //
- // The limit of 128 is somewhat arbitrary, but is applied due to performance
- // concerns with the current implementation and can be removed when
- // `this issue <https://github.com/envoyproxy/envoy/issues/1285>`_ is fixed.
- google.protobuf.UInt32Value load_balancing_weight = 4;
-}
-
-// A group of endpoints belonging to a Locality.
-// One can have multiple LocalityLbEndpoints for a locality, but this is
-// generally only done if the different groups need to have different load
-// balancing weights or different priorities.
-message LocalityLbEndpoints {
- // Identifies location of where the upstream hosts run.
- Locality locality = 1;
-
- // The group of endpoints belonging to the locality specified.
- repeated LbEndpoint lb_endpoints = 2;
-
- // Optional: Per priority/region/zone/sub_zone weight - range 1-128. The load
- // balancing weight for a locality is divided by the sum of the weights of all
- // localities at the same priority level to produce the effective percentage
- // of traffic for the locality.
- //
- // Locality weights are only considered when :ref:`locality weighted load
- // balancing <arch_overview_load_balancing_locality_weighted_lb>` is
- // configured. These weights are ignored otherwise. If no weights are
- // specificed when locality weighted load balancing is enabled, the cluster is
- // assumed to have a weight of 1.
- //
- // .. attention::
- //
- // The limit of 128 is somewhat arbitrary, but is applied due to performance
- // concerns with the current implementation and can be removed when
- // `this issue <https://github.com/envoyproxy/envoy/issues/1285>`_ is fixed.
- google.protobuf.UInt32Value load_balancing_weight = 3;
-
- // Optional: the priority for this LocalityLbEndpoints. If unspecified this will
- // default to the highest priority (0).
- //
- // Under usual circumstances, Envoy will only select endpoints for the highest
- // priority (0). In the event all endpoints for a particular priority are
- // unavailable/unhealthy, Envoy will fail over to selecting endpoints for the
- // next highest priority group.
- //
- // Priorities should range from 0 (highest) to N (lowest) without skipping.
- uint32 priority = 5;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-message FractionalPercent {
- // Specifies the numerator. Defaults to 0.
- uint32 numerator = 1;
-
- // Fraction percentages support several fixed denominator values.
- enum DenominatorType {
- // 100.
- //
- // **Example**: 1/100 = 1%.
- HUNDRED = 0;
-
- // 10,000.
- //
- // **Example**: 1/10000 = 0.01%.
- TEN_THOUSAND = 1;
-
- // 1,000,000.
- //
- // **Example**: 1/1000000 = 0.0001%.
- MILLION = 2;
- }
-
- // Specifies the denominator. If the denominator specified is less than the numerator, the final
- // fractional percentage is capped at 1 (100%).
- DenominatorType denominator = 2;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-// [#protodoc-title: EDS]
-// Endpoint discovery :ref:`architecture overview <arch_overview_service_discovery_types_eds>`
-service EndpointDiscoveryService {
- // The resource_names field in DiscoveryRequest specifies a list of clusters
- // to subscribe to updates for.
- rpc StreamEndpoints(stream DiscoveryRequest) returns (stream DiscoveryResponse) {
- }
-}
-
-// Each route from RDS will map to a single cluster or traffic split across
-// clusters using weights expressed in the RDS WeightedCluster.
-//
-// With EDS, each cluster is treated independently from a LB perspective, with
-// LB taking place between the Localities within a cluster and at a finer
-// granularity between the hosts within a locality. For a given cluster, the
-// effective weight of a host is its load_balancing_weight multiplied by the
-// load_balancing_weight of its Locality.
-message ClusterLoadAssignment {
- // Name of the cluster. This will be the :ref:`service_name
- // <envoy_api_field_Cluster.EdsClusterConfig.service_name>` value if specified
- // in the cluster :ref:`EdsClusterConfig
- // <envoy_api_msg_Cluster.EdsClusterConfig>`.
- string cluster_name = 1;
-
- // List of endpoints to load balance to.
- repeated LocalityLbEndpoints endpoints = 2;
-
- // Load balancing policy settings.
- message Policy {
- reserved 1;
-
- message DropOverload {
- // Identifier for the policy specifying the drop.
- string category = 1;
-
- // Percentage of traffic that should be dropped for the category.
- FractionalPercent drop_percentage = 2;
- }
- // Action to trim the overall incoming traffic to protect the upstream
- // hosts. This action allows protection in case the hosts are unable to
- // recover from an outage, or unable to autoscale or unable to handle
- // incoming traffic volume for any reason.
- //
- // At the client each category is applied one after the other to generate
- // the 'actual' drop percentage on all outgoing traffic. For example:
- //
- // .. code-block:: json
- //
- // { "drop_overloads": [
- // { "category": "throttle", "drop_percentage": 60 }
- // { "category": "lb", "drop_percentage": 50 }
- // ]}
- //
- // The actual drop percentages applied to the traffic at the clients will be
- // "throttle"_drop = 60%
- // "lb"_drop = 20% // 50% of the remaining 'actual' load, which is 40%.
- // actual_outgoing_load = 20% // remaining after applying all categories.
- repeated DropOverload drop_overloads = 2;
-
- // Priority levels and localities are considered overprovisioned with this
- // factor (in percentage). This means that we don't consider a priority
- // level or locality unhealthy until the percentage of healthy hosts
- // multiplied by the overprovisioning factor drops below 100.
- // With the default value 140(1.4), Envoy doesn't consider a priority level
- // or a locality unhealthy until their percentage of healthy hosts drops
- // below 72%.
- // Read more at :ref:`priority levels <arch_overview_load_balancing_priority_levels>` and
- // :ref:`localities <arch_overview_load_balancing_locality_weighted_lb>`.
- google.protobuf.UInt32Value overprovisioning_factor = 3;
- }
-
- // Load balancing policy settings.
- Policy policy = 4;
-}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/xds/lds_rds_for_test.proto b/contrib/libs/grpc/src/proto/grpc/testing/xds/lds_rds_for_test.proto
deleted file mode 100644
index d5ba5bd32bc..00000000000
--- a/contrib/libs/grpc/src/proto/grpc/testing/xds/lds_rds_for_test.proto
+++ /dev/null
@@ -1,215 +0,0 @@
-// Copyright 2019 The gRPC Authors
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// This file contains the eds protocol and its dependency.
-//
-// TODO(juanlishen): This file is a hack to avoid a problem we're
-// currently having where we can't depend on a proto file in an external
-// repo due to bazel limitations. Once that's fixed, this should be
-// removed. Until this, it should be used in the gRPC tests only, or else it
-// will cause a conflict due to the same proto messages being defined in
-// multiple files in the same binary.
-
-syntax = "proto3";
-
-package envoy.api.v2;
-
-import "google/protobuf/any.proto";
-import "google/protobuf/wrappers.proto";
-import "src/proto/grpc/testing/xds/cds_for_test.proto";
-import "src/proto/grpc/testing/xds/eds_for_test.proto";
-
-message RegexMatcher {
- message GoogleRE2 {
- google.protobuf.UInt32Value max_program_size = 1;
- }
- oneof engine_type {
- GoogleRE2 google_re2 = 1;
- }
- string regex = 2;
-}
-
-message Int64Range {
- // start of the range (inclusive)
- int64 start = 1;
-
- // end of the range (exclusive)
- int64 end = 2;
-}
-
-message BoolValue {
- // The bool value.
- bool value = 1;
-}
-
-message HeaderMatcher {
- string name = 1;
- oneof header_match_specifier {
- string exact_match = 4;
- RegexMatcher safe_regex_match = 11;
- Int64Range range_match = 6;
- bool present_match = 7;
- string prefix_match = 9;
- string suffix_match = 10;
- }
- bool invert_match = 8;
-}
-
-message QueryParameterMatcher {
- string name = 1;
-}
-
-message RuntimeFractionalPercent {
- FractionalPercent default_value = 1;
-}
-
-message RouteMatch {
- oneof path_specifier {
- // If specified, the route is a prefix rule meaning that the prefix must
- // match the beginning of the *:path* header.
- string prefix = 1;
- string path = 2;
- RegexMatcher safe_regex = 10;
- }
- BoolValue case_sensitive = 4;
- repeated QueryParameterMatcher query_parameters = 7;
- RuntimeFractionalPercent runtime_fraction = 9;
- repeated HeaderMatcher headers = 6;
-}
-
-message WeightedCluster {
- message ClusterWeight {
- string name = 1;
- google.protobuf.UInt32Value weight = 2;
- }
- repeated ClusterWeight clusters = 1;
- google.protobuf.UInt32Value total_weight = 3;
-}
-
-message RouteAction {
- oneof cluster_specifier {
- // Indicates the upstream cluster to which the request should be routed
- // to.
- string cluster = 1;
-
- // Envoy will determine the cluster to route to by reading the value of the
- // HTTP header named by cluster_header from the request headers. If the
- // header is not found or the referenced cluster does not exist, Envoy will
- // return a 404 response.
- //
- // .. attention::
- //
- // Internally, Envoy always uses the HTTP/2 *:authority* header to represent the HTTP/1
- // *Host* header. Thus, if attempting to match on *Host*, match on *:authority* instead.
- string cluster_header = 2;
- // Multiple upstream clusters can be specified for a given route. The
- // request is routed to one of the upstream clusters based on weights
- // assigned to each cluster. See
- // :ref:`traffic splitting <config_http_conn_man_route_table_traffic_splitting_split>`
- // for additional documentation.
- WeightedCluster weighted_clusters = 3;
- }
-}
-
-message RedirectAction {}
-
-message Route {
- RouteMatch match = 1;
-
- oneof action {
- // Route request to some upstream cluster.
- RouteAction route = 2;
-
- // Return a redirect.
- RedirectAction redirect = 3;
- }
-}
-
-message VirtualHost {
- repeated string domains = 2;
- repeated Route routes = 3;
-}
-
-message Rds {
- // Configuration source specifier for RDS.
- ConfigSource config_source = 1;
-
- // The name of the route configuration. This name will be passed to the RDS
- // API. This allows an Envoy configuration with multiple HTTP listeners (and
- // associated HTTP connection manager filters) to use different route
- // configurations.
- string route_config_name = 2;
-}
-
-message RouteConfiguration {
- // The name of the route configuration. For example, it might match
- // :ref:`route_config_name
- // <envoy_api_field_config.filter.network.http_connection_manager.v2.Rds.route_config_name>` in
- // :ref:`envoy_api_msg_config.filter.network.http_connection_manager.v2.Rds`.
- string name = 1;
-
- // An array of virtual hosts that make up the route table.
- repeated VirtualHost virtual_hosts = 2;
-}
-
-message ScopedRoutes {}
-
-message HttpConnectionManager {
- oneof route_specifier {
- // The connection manager’s route table will be dynamically loaded via the RDS API.
- Rds rds = 3;
-
- // The route table for the connection manager is static and is specified in this property.
- RouteConfiguration route_config = 4;
-
- // A route table will be dynamically assigned to each request based on request attributes
- // (e.g., the value of a header). The "routing scopes" (i.e., route tables) and "scope keys" are
- // specified in this message.
- ScopedRoutes scoped_routes = 31;
- }
-}
-
-message ApiListener {
- // The type in this field determines the type of API listener. At present, the following
- // types are supported:
- // envoy.config.filter.network.http_connection_manager.v2.HttpConnectionManager (HTTP)
- // [#next-major-version: In the v3 API, replace this Any field with a oneof containing the
- // specific config message for each type of API listener. We could not do this in v2 because
- // it would have caused circular dependencies for go protos: lds.proto depends on this file,
- // and http_connection_manager.proto depends on rds.proto, which is in the same directory as
- // lds.proto, so lds.proto cannot depend on this file.]
- google.protobuf.Any api_listener = 1;
-}
-
-message Listener {
- string name = 1;
-
- // Used to represent an API listener, which is used in non-proxy clients. The type of API
- // exposed to the non-proxy application depends on the type of API listener.
- // When this field is set, no other field except for :ref:`name<envoy_api_field_Listener.name>`
- // should be set.
- //
- // .. note::
- //
- // Currently only one ApiListener can be installed; and it can only be done via bootstrap config,
- // not LDS.
- //
- // [#next-major-version: In the v3 API, instead of this messy approach where the socket
- // listener fields are directly in the top-level Listener message and the API listener types
- // are in the ApiListener message, the socket listener messages should be in their own message,
- // and the top-level Listener should essentially be a oneof that selects between the
- // socket listener and the various types of API listener. That way, a given Listener message
- // can structurally only contain the fields of the relevant type.]
- ApiListener api_listener = 19;
-}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/xds/lrs_for_test.proto b/contrib/libs/grpc/src/proto/grpc/testing/xds/lrs_for_test.proto
deleted file mode 100644
index d46d5e2ccc5..00000000000
--- a/contrib/libs/grpc/src/proto/grpc/testing/xds/lrs_for_test.proto
+++ /dev/null
@@ -1,189 +0,0 @@
-// Copyright 2019 The gRPC Authors
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// This file contains the eds protocol and its dependency.
-//
-// TODO(juanlishen): This file is a hack to avoid a problem we're
-// currently having where we can't depend on a proto file in an external
-// repo due to bazel limitations. Once that's fixed, this should be
-// removed. Until this, it should be used in the gRPC tests only, or else it
-// will cause a conflict due to the same proto messages being defined in
-// multiple files in the same binary.
-
-syntax = "proto3";
-
-package envoy.service.load_stats.v2;
-
-import "google/protobuf/duration.proto";
-import "src/proto/grpc/testing/xds/eds_for_test.proto";
-
-// [#not-implemented-hide:] Not configuration. TBD how to doc proto APIs.
-message EndpointLoadMetricStats {
- // Name of the metric; may be empty.
- string metric_name = 1;
-
- // Number of calls that finished and included this metric.
- uint64 num_requests_finished_with_metric = 2;
-
- // Sum of metric values across all calls that finished with this metric for
- // load_reporting_interval.
- double total_metric_value = 3;
-}
-
-message UpstreamLocalityStats {
- // Name of zone, region and optionally endpoint group these metrics were
- // collected from. Zone and region names could be empty if unknown.
- envoy.api.v2.Locality locality = 1;
-
- // The total number of requests successfully completed by the endpoints in the
- // locality.
- uint64 total_successful_requests = 2;
-
- // The total number of unfinished requests
- uint64 total_requests_in_progress = 3;
-
- // The total number of requests that failed due to errors at the endpoint,
- // aggregated over all endpoints in the locality.
- uint64 total_error_requests = 4;
-
- // The total number of requests that were issued by this Envoy since
- // the last report. This information is aggregated over all the
- // upstream endpoints in the locality.
- uint64 total_issued_requests = 8;
-
- // Stats for multi-dimensional load balancing.
- repeated EndpointLoadMetricStats load_metric_stats = 5;
-
-// // Endpoint granularity stats information for this locality. This information
-// // is populated if the Server requests it by setting
-// // :ref:`LoadStatsResponse.report_endpoint_granularity<envoy_api_field_load_stats.LoadStatsResponse.report_endpoint_granularity>`.
-// repeated UpstreamEndpointStats upstream_endpoint_stats = 7;
-
- // [#not-implemented-hide:] The priority of the endpoint group these metrics
- // were collected from.
- uint32 priority = 6;
-}
-
-// Per cluster load stats. Envoy reports these stats a management server in a
-// :ref:`LoadStatsRequest<envoy_api_msg_load_stats.LoadStatsRequest>`
-// [#not-implemented-hide:] Not configuration. TBD how to doc proto APIs.
-// Next ID: 7
-message ClusterStats {
- // The name of the cluster.
- string cluster_name = 1;
-
- // The eds_cluster_config service_name of the cluster.
- // It's possible that two clusters send the same service_name to EDS,
- // in that case, the management server is supposed to do aggregation on the load reports.
- string cluster_service_name = 6;
-
- // Need at least one.
- repeated UpstreamLocalityStats upstream_locality_stats = 2;
-
- // Cluster-level stats such as total_successful_requests may be computed by
- // summing upstream_locality_stats. In addition, below there are additional
- // cluster-wide stats.
- //
- // The total number of dropped requests. This covers requests
- // deliberately dropped by the drop_overload policy and circuit breaking.
- uint64 total_dropped_requests = 3;
-
- message DroppedRequests {
- // Identifier for the policy specifying the drop.
- string category = 1;
- // Total number of deliberately dropped requests for the category.
- uint64 dropped_count = 2;
- }
- // Information about deliberately dropped requests for each category specified
- // in the DropOverload policy.
- repeated DroppedRequests dropped_requests = 5;
-
- // Period over which the actual load report occurred. This will be guaranteed to include every
- // request reported. Due to system load and delays between the *LoadStatsRequest* sent from Envoy
- // and the *LoadStatsResponse* message sent from the management server, this may be longer than
- // the requested load reporting interval in the *LoadStatsResponse*.
- google.protobuf.Duration load_report_interval = 4;
-}
-
-// [#protodoc-title: Load reporting service]
-
-service LoadReportingService {
- // Advanced API to allow for multi-dimensional load balancing by remote
- // server. For receiving LB assignments, the steps are:
- // 1, The management server is configured with per cluster/zone/load metric
- // capacity configuration. The capacity configuration definition is
- // outside of the scope of this document.
- // 2. Envoy issues a standard {Stream,Fetch}Endpoints request for the clusters
- // to balance.
- //
- // Independently, Envoy will initiate a StreamLoadStats bidi stream with a
- // management server:
- // 1. Once a connection establishes, the management server publishes a
- // LoadStatsResponse for all clusters it is interested in learning load
- // stats about.
- // 2. For each cluster, Envoy load balances incoming traffic to upstream hosts
- // based on per-zone weights and/or per-instance weights (if specified)
- // based on intra-zone LbPolicy. This information comes from the above
- // {Stream,Fetch}Endpoints.
- // 3. When upstream hosts reply, they optionally add header <define header
- // name> with ASCII representation of EndpointLoadMetricStats.
- // 4. Envoy aggregates load reports over the period of time given to it in
- // LoadStatsResponse.load_reporting_interval. This includes aggregation
- // stats Envoy maintains by itself (total_requests, rpc_errors etc.) as
- // well as load metrics from upstream hosts.
- // 5. When the timer of load_reporting_interval expires, Envoy sends new
- // LoadStatsRequest filled with load reports for each cluster.
- // 6. The management server uses the load reports from all reported Envoys
- // from around the world, computes global assignment and prepares traffic
- // assignment destined for each zone Envoys are located in. Goto 2.
- rpc StreamLoadStats(stream LoadStatsRequest) returns (stream LoadStatsResponse) {
- }
-}
-
-// A load report Envoy sends to the management server.
-// [#not-implemented-hide:] Not configuration. TBD how to doc proto APIs.
-message LoadStatsRequest {
- // Node identifier for Envoy instance.
- envoy.api.v2.Node node = 1;
-
- // A list of load stats to report.
- repeated ClusterStats cluster_stats = 2;
-}
-
-// The management server sends envoy a LoadStatsResponse with all clusters it
-// is interested in learning load stats about.
-// [#not-implemented-hide:] Not configuration. TBD how to doc proto APIs.
-message LoadStatsResponse {
- // Clusters to report stats for.
- // Not populated if *send_all_clusters* is true.
- repeated string clusters = 1;
-
- // If true, the client should send all clusters it knows about.
- // Only clients that advertise the "envoy.lrs.supports_send_all_clusters" capability in their
- // :ref:`client_features<envoy_api_field_core.Node.client_features>` field will honor this field.
- bool send_all_clusters = 4;
-
- // The minimum interval of time to collect stats over. This is only a minimum for two reasons:
- // 1. There may be some delay from when the timer fires until stats sampling occurs.
- // 2. For clusters that were already feature in the previous *LoadStatsResponse*, any traffic
- // that is observed in between the corresponding previous *LoadStatsRequest* and this
- // *LoadStatsResponse* will also be accumulated and billed to the cluster. This avoids a period
- // of inobservability that might otherwise exists between the messages. New clusters are not
- // subject to this consideration.
- google.protobuf.Duration load_reporting_interval = 2;
-
- // Set to *true* if the management server supports endpoint granularity
- // report.
- bool report_endpoint_granularity = 3;
-}
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/xds/ya.make b/contrib/libs/grpc/src/proto/grpc/testing/xds/ya.make
deleted file mode 100644
index 54f67904dbb..00000000000
--- a/contrib/libs/grpc/src/proto/grpc/testing/xds/ya.make
+++ /dev/null
@@ -1,32 +0,0 @@
-PROTO_LIBRARY()
-
-LICENSE(Apache-2.0)
-
-LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-
-EXCLUDE_TAGS(
- GO_PROTO
- PY_PROTO
- PY3_PROTO
-)
-
-PROTO_NAMESPACE(
- GLOBAL
- contrib/libs/grpc
-)
-
-PEERDIR(
- contrib/libs/grpc/src/proto/grpc/testing
-)
-
-GRPC()
-
-SRCS(
- ads_for_test.proto
- cds_for_test.proto
- eds_for_test.proto
- lds_rds_for_test.proto
- lrs_for_test.proto
-)
-
-END()
diff --git a/contrib/libs/grpc/src/proto/grpc/testing/ya.make b/contrib/libs/grpc/src/proto/grpc/testing/ya.make
deleted file mode 100644
index 4c140e6e263..00000000000
--- a/contrib/libs/grpc/src/proto/grpc/testing/ya.make
+++ /dev/null
@@ -1,43 +0,0 @@
-PROTO_LIBRARY()
-
-LICENSE(Apache-2.0)
-
-LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-
-EXCLUDE_TAGS(
- GO_PROTO
- PY_PROTO
- PY3_PROTO
-)
-
-PROTO_NAMESPACE(
- GLOBAL
- contrib/libs/grpc
-)
-
-PEERDIR(
- contrib/libs/grpc/src/proto/grpc/core
-)
-
-GRPC()
-
-SRCS(
- benchmark_service.proto
- compiler_test.proto
- control.proto
- echo.proto
- echo_messages.proto
- empty.proto
- empty_service.proto
- messages.proto
- metrics.proto
- payloads.proto
- proxy-service.proto
- report_qps_scenario_service.proto
- simple_messages.proto
- stats.proto
- test.proto
- worker_service.proto
-)
-
-END()
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/__init__.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/__init__.py
deleted file mode 100644
index 5fb4f3c3cfd..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/__init__.py
+++ /dev/null
@@ -1,13 +0,0 @@
-# Copyright 2015 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_abort_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_abort_test.py
deleted file mode 100644
index 84604726c99..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_abort_test.py
+++ /dev/null
@@ -1,154 +0,0 @@
-# Copyright 2018 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Tests server context abort mechanism"""
-
-import collections
-import gc
-import logging
-import unittest
-import weakref
-
-import grpc
-
-from tests.unit import test_common
-from tests.unit.framework.common import test_constants
-
-_ABORT = '/test/abort'
-_ABORT_WITH_STATUS = '/test/AbortWithStatus'
-_INVALID_CODE = '/test/InvalidCode'
-
-_REQUEST = b'\x00\x00\x00'
-_RESPONSE = b'\x00\x00\x00'
-
-_ABORT_DETAILS = 'Abandon ship!'
-_ABORT_METADATA = (('a-trailing-metadata', '42'),)
-
-
-class _Status(
- collections.namedtuple('_Status',
- ('code', 'details', 'trailing_metadata')),
- grpc.Status):
- pass
-
-
-class _Object(object):
- pass
-
-
-do_not_leak_me = _Object()
-
-
-def abort_unary_unary(request, servicer_context):
- this_should_not_be_leaked = do_not_leak_me
- servicer_context.abort(
- grpc.StatusCode.INTERNAL,
- _ABORT_DETAILS,
- )
- raise Exception('This line should not be executed!')
-
-
-def abort_with_status_unary_unary(request, servicer_context):
- servicer_context.abort_with_status(
- _Status(
- code=grpc.StatusCode.INTERNAL,
- details=_ABORT_DETAILS,
- trailing_metadata=_ABORT_METADATA,
- ))
- raise Exception('This line should not be executed!')
-
-
-def invalid_code_unary_unary(request, servicer_context):
- servicer_context.abort(
- 42,
- _ABORT_DETAILS,
- )
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def service(self, handler_call_details):
- if handler_call_details.method == _ABORT:
- return grpc.unary_unary_rpc_method_handler(abort_unary_unary)
- elif handler_call_details.method == _ABORT_WITH_STATUS:
- return grpc.unary_unary_rpc_method_handler(
- abort_with_status_unary_unary)
- elif handler_call_details.method == _INVALID_CODE:
- return grpc.stream_stream_rpc_method_handler(
- invalid_code_unary_unary)
- else:
- return None
-
-
-class AbortTest(unittest.TestCase):
-
- def setUp(self):
- self._server = test_common.test_server()
- port = self._server.add_insecure_port('[::]:0')
- self._server.add_generic_rpc_handlers((_GenericHandler(),))
- self._server.start()
-
- self._channel = grpc.insecure_channel('localhost:%d' % port)
-
- def tearDown(self):
- self._channel.close()
- self._server.stop(0)
-
- def test_abort(self):
- with self.assertRaises(grpc.RpcError) as exception_context:
- self._channel.unary_unary(_ABORT)(_REQUEST)
- rpc_error = exception_context.exception
-
- self.assertEqual(rpc_error.code(), grpc.StatusCode.INTERNAL)
- self.assertEqual(rpc_error.details(), _ABORT_DETAILS)
-
- # This test ensures that abort() does not store the raised exception, which
- # on Python 3 (via the `__traceback__` attribute) holds a reference to
- # all local vars. Storing the raised exception can prevent GC and stop the
- # grpc_call from being unref'ed, even after server shutdown.
- @unittest.skip("https://github.com/grpc/grpc/issues/17927")
- def test_abort_does_not_leak_local_vars(self):
- global do_not_leak_me # pylint: disable=global-statement
- weak_ref = weakref.ref(do_not_leak_me)
-
- # Servicer will abort() after creating a local ref to do_not_leak_me.
- with self.assertRaises(grpc.RpcError):
- self._channel.unary_unary(_ABORT)(_REQUEST)
-
- # Server may still have a stack frame reference to the exception even
- # after client sees error, so ensure server has shutdown.
- self._server.stop(None)
- do_not_leak_me = None
- self.assertIsNone(weak_ref())
-
- def test_abort_with_status(self):
- with self.assertRaises(grpc.RpcError) as exception_context:
- self._channel.unary_unary(_ABORT_WITH_STATUS)(_REQUEST)
- rpc_error = exception_context.exception
-
- self.assertEqual(rpc_error.code(), grpc.StatusCode.INTERNAL)
- self.assertEqual(rpc_error.details(), _ABORT_DETAILS)
- self.assertEqual(rpc_error.trailing_metadata(), _ABORT_METADATA)
-
- def test_invalid_code(self):
- with self.assertRaises(grpc.RpcError) as exception_context:
- self._channel.unary_unary(_INVALID_CODE)(_REQUEST)
- rpc_error = exception_context.exception
-
- self.assertEqual(rpc_error.code(), grpc.StatusCode.UNKNOWN)
- self.assertEqual(rpc_error.details(), _ABORT_DETAILS)
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_api_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_api_test.py
deleted file mode 100644
index c536328142d..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_api_test.py
+++ /dev/null
@@ -1,121 +0,0 @@
-# Copyright 2016 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Test of gRPC Python's application-layer API."""
-
-import logging
-import unittest
-
-import grpc
-import six
-
-from tests.unit import _from_grpc_import_star
-
-
-class AllTest(unittest.TestCase):
-
- def testAll(self):
- expected_grpc_code_elements = (
- 'FutureTimeoutError',
- 'FutureCancelledError',
- 'Future',
- 'ChannelConnectivity',
- 'Compression',
- 'StatusCode',
- 'Status',
- 'RpcError',
- 'RpcContext',
- 'Call',
- 'ChannelCredentials',
- 'CallCredentials',
- 'AuthMetadataContext',
- 'AuthMetadataPluginCallback',
- 'AuthMetadataPlugin',
- 'ServerCertificateConfiguration',
- 'ServerCredentials',
- 'UnaryUnaryMultiCallable',
- 'UnaryStreamMultiCallable',
- 'StreamUnaryMultiCallable',
- 'StreamStreamMultiCallable',
- 'UnaryUnaryClientInterceptor',
- 'UnaryStreamClientInterceptor',
- 'StreamUnaryClientInterceptor',
- 'StreamStreamClientInterceptor',
- 'Channel',
- 'ServicerContext',
- 'RpcMethodHandler',
- 'HandlerCallDetails',
- 'GenericRpcHandler',
- 'ServiceRpcHandler',
- 'Server',
- 'ServerInterceptor',
- 'LocalConnectionType',
- 'local_channel_credentials',
- 'local_server_credentials',
- 'alts_channel_credentials',
- 'alts_server_credentials',
- 'unary_unary_rpc_method_handler',
- 'unary_stream_rpc_method_handler',
- 'stream_unary_rpc_method_handler',
- 'ClientCallDetails',
- 'stream_stream_rpc_method_handler',
- 'method_handlers_generic_handler',
- 'ssl_channel_credentials',
- 'metadata_call_credentials',
- 'access_token_call_credentials',
- 'composite_call_credentials',
- 'composite_channel_credentials',
- 'compute_engine_channel_credentials',
- 'ssl_server_credentials',
- 'ssl_server_certificate_configuration',
- 'dynamic_ssl_server_credentials',
- 'channel_ready_future',
- 'insecure_channel',
- 'secure_channel',
- 'intercept_channel',
- 'server',
- 'protos',
- 'services',
- 'protos_and_services',
- 'xds_channel_credentials',
- 'xds_server_credentials',
- 'insecure_server_credentials',
- )
-
- six.assertCountEqual(self, expected_grpc_code_elements,
- _from_grpc_import_star.GRPC_ELEMENTS)
-
-
-class ChannelConnectivityTest(unittest.TestCase):
-
- def testChannelConnectivity(self):
- self.assertSequenceEqual((
- grpc.ChannelConnectivity.IDLE,
- grpc.ChannelConnectivity.CONNECTING,
- grpc.ChannelConnectivity.READY,
- grpc.ChannelConnectivity.TRANSIENT_FAILURE,
- grpc.ChannelConnectivity.SHUTDOWN,
- ), tuple(grpc.ChannelConnectivity))
-
-
-class ChannelTest(unittest.TestCase):
-
- def test_secure_channel(self):
- channel_credentials = grpc.ssl_channel_credentials()
- channel = grpc.secure_channel('google.com:443', channel_credentials)
- channel.close()
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_auth_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_auth_test.py
deleted file mode 100644
index 345239e0b87..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_auth_test.py
+++ /dev/null
@@ -1,82 +0,0 @@
-# Copyright 2016 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Tests of standard AuthMetadataPlugins."""
-
-import collections
-import logging
-import threading
-import unittest
-
-from grpc import _auth
-
-
-class MockGoogleCreds(object):
-
- def get_access_token(self):
- token = collections.namedtuple('MockAccessTokenInfo',
- ('access_token', 'expires_in'))
- token.access_token = 'token'
- return token
-
-
-class MockExceptionGoogleCreds(object):
-
- def get_access_token(self):
- raise Exception()
-
-
-class GoogleCallCredentialsTest(unittest.TestCase):
-
- def test_google_call_credentials_success(self):
- callback_event = threading.Event()
-
- def mock_callback(metadata, error):
- self.assertEqual(metadata, (('authorization', 'Bearer token'),))
- self.assertIsNone(error)
- callback_event.set()
-
- call_creds = _auth.GoogleCallCredentials(MockGoogleCreds())
- call_creds(None, mock_callback)
- self.assertTrue(callback_event.wait(1.0))
-
- def test_google_call_credentials_error(self):
- callback_event = threading.Event()
-
- def mock_callback(metadata, error):
- self.assertIsNotNone(error)
- callback_event.set()
-
- call_creds = _auth.GoogleCallCredentials(MockExceptionGoogleCreds())
- call_creds(None, mock_callback)
- self.assertTrue(callback_event.wait(1.0))
-
-
-class AccessTokenAuthMetadataPluginTest(unittest.TestCase):
-
- def test_google_call_credentials_success(self):
- callback_event = threading.Event()
-
- def mock_callback(metadata, error):
- self.assertEqual(metadata, (('authorization', 'Bearer token'),))
- self.assertIsNone(error)
- callback_event.set()
-
- metadata_plugin = _auth.AccessTokenAuthMetadataPlugin('token')
- metadata_plugin(None, mock_callback)
- self.assertTrue(callback_event.wait(1.0))
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_args_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_args_test.py
deleted file mode 100644
index d71906f6f41..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_args_test.py
+++ /dev/null
@@ -1,65 +0,0 @@
-# Copyright 2016 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Tests of channel arguments on client/server side."""
-
-from concurrent import futures
-import logging
-import unittest
-
-import grpc
-
-
-class TestPointerWrapper(object):
-
- def __int__(self):
- return 123456
-
-
-TEST_CHANNEL_ARGS = (
- ('arg1', b'bytes_val'),
- ('arg2', 'str_val'),
- ('arg3', 1),
- (b'arg4', 'str_val'),
- ('arg6', TestPointerWrapper()),
-)
-
-INVALID_TEST_CHANNEL_ARGS = [
- {
- 'foo': 'bar'
- },
- (('key',),),
- 'str',
-]
-
-
-class ChannelArgsTest(unittest.TestCase):
-
- def test_client(self):
- grpc.insecure_channel('localhost:8080', options=TEST_CHANNEL_ARGS)
-
- def test_server(self):
- grpc.server(futures.ThreadPoolExecutor(max_workers=1),
- options=TEST_CHANNEL_ARGS)
-
- def test_invalid_client_args(self):
- for invalid_arg in INVALID_TEST_CHANNEL_ARGS:
- self.assertRaises(ValueError,
- grpc.insecure_channel,
- 'localhost:8080',
- options=invalid_arg)
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_close_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_close_test.py
deleted file mode 100644
index 47f52b4890e..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_close_test.py
+++ /dev/null
@@ -1,220 +0,0 @@
-# Copyright 2018 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Tests server and client side compression."""
-
-import itertools
-import logging
-import threading
-import time
-import unittest
-
-import grpc
-
-from tests.unit import test_common
-from tests.unit.framework.common import test_constants
-
-_BEAT = 0.5
-_SOME_TIME = 5
-_MORE_TIME = 10
-
-_STREAM_URI = 'Meffod'
-_UNARY_URI = 'MeffodMan'
-
-
-class _StreamingMethodHandler(grpc.RpcMethodHandler):
-
- request_streaming = True
- response_streaming = True
- request_deserializer = None
- response_serializer = None
-
- def stream_stream(self, request_iterator, servicer_context):
- for request in request_iterator:
- yield request * 2
-
-
-class _UnaryMethodHandler(grpc.RpcMethodHandler):
-
- request_streaming = False
- response_streaming = False
- request_deserializer = None
- response_serializer = None
-
- def unary_unary(self, request, servicer_context):
- return request * 2
-
-
-_STREAMING_METHOD_HANDLER = _StreamingMethodHandler()
-_UNARY_METHOD_HANDLER = _UnaryMethodHandler()
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def service(self, handler_call_details):
- if handler_call_details.method == _STREAM_URI:
- return _STREAMING_METHOD_HANDLER
- else:
- return _UNARY_METHOD_HANDLER
-
-
-_GENERIC_HANDLER = _GenericHandler()
-
-
-class _Pipe(object):
-
- def __init__(self, values):
- self._condition = threading.Condition()
- self._values = list(values)
- self._open = True
-
- def __iter__(self):
- return self
-
- def _next(self):
- with self._condition:
- while not self._values and self._open:
- self._condition.wait()
- if self._values:
- return self._values.pop(0)
- else:
- raise StopIteration()
-
- def next(self):
- return self._next()
-
- def __next__(self):
- return self._next()
-
- def add(self, value):
- with self._condition:
- self._values.append(value)
- self._condition.notify()
-
- def close(self):
- with self._condition:
- self._open = False
- self._condition.notify()
-
- def __enter__(self):
- return self
-
- def __exit__(self, type, value, traceback):
- self.close()
-
-
-class ChannelCloseTest(unittest.TestCase):
-
- def setUp(self):
- self._server = test_common.test_server(
- max_workers=test_constants.THREAD_CONCURRENCY)
- self._server.add_generic_rpc_handlers((_GENERIC_HANDLER,))
- self._port = self._server.add_insecure_port('[::]:0')
- self._server.start()
-
- def tearDown(self):
- self._server.stop(None)
-
- def test_close_immediately_after_call_invocation(self):
- channel = grpc.insecure_channel('localhost:{}'.format(self._port))
- multi_callable = channel.stream_stream(_STREAM_URI)
- request_iterator = _Pipe(())
- response_iterator = multi_callable(request_iterator)
- channel.close()
- request_iterator.close()
-
- self.assertIs(response_iterator.code(), grpc.StatusCode.CANCELLED)
-
- def test_close_while_call_active(self):
- channel = grpc.insecure_channel('localhost:{}'.format(self._port))
- multi_callable = channel.stream_stream(_STREAM_URI)
- request_iterator = _Pipe((b'abc',))
- response_iterator = multi_callable(request_iterator)
- next(response_iterator)
- channel.close()
- request_iterator.close()
-
- self.assertIs(response_iterator.code(), grpc.StatusCode.CANCELLED)
-
- def test_context_manager_close_while_call_active(self):
- with grpc.insecure_channel('localhost:{}'.format(
- self._port)) as channel: # pylint: disable=bad-continuation
- multi_callable = channel.stream_stream(_STREAM_URI)
- request_iterator = _Pipe((b'abc',))
- response_iterator = multi_callable(request_iterator)
- next(response_iterator)
- request_iterator.close()
-
- self.assertIs(response_iterator.code(), grpc.StatusCode.CANCELLED)
-
- def test_context_manager_close_while_many_calls_active(self):
- with grpc.insecure_channel('localhost:{}'.format(
- self._port)) as channel: # pylint: disable=bad-continuation
- multi_callable = channel.stream_stream(_STREAM_URI)
- request_iterators = tuple(
- _Pipe((b'abc',))
- for _ in range(test_constants.THREAD_CONCURRENCY))
- response_iterators = []
- for request_iterator in request_iterators:
- response_iterator = multi_callable(request_iterator)
- next(response_iterator)
- response_iterators.append(response_iterator)
- for request_iterator in request_iterators:
- request_iterator.close()
-
- for response_iterator in response_iterators:
- self.assertIs(response_iterator.code(), grpc.StatusCode.CANCELLED)
-
- def test_many_concurrent_closes(self):
- channel = grpc.insecure_channel('localhost:{}'.format(self._port))
- multi_callable = channel.stream_stream(_STREAM_URI)
- request_iterator = _Pipe((b'abc',))
- response_iterator = multi_callable(request_iterator)
- next(response_iterator)
- start = time.time()
- end = start + _MORE_TIME
-
- def sleep_some_time_then_close():
- time.sleep(_SOME_TIME)
- channel.close()
-
- for _ in range(test_constants.THREAD_CONCURRENCY):
- close_thread = threading.Thread(target=sleep_some_time_then_close)
- close_thread.start()
- while True:
- request_iterator.add(b'def')
- time.sleep(_BEAT)
- if end < time.time():
- break
- request_iterator.close()
-
- self.assertIs(response_iterator.code(), grpc.StatusCode.CANCELLED)
-
- def test_exception_in_callback(self):
- with grpc.insecure_channel('localhost:{}'.format(
- self._port)) as channel:
- stream_multi_callable = channel.stream_stream(_STREAM_URI)
- endless_iterator = itertools.repeat(b'abc')
- stream_response_iterator = stream_multi_callable(endless_iterator)
- future = channel.unary_unary(_UNARY_URI).future(b'abc')
-
- def on_done_callback(future):
- raise Exception("This should not cause a deadlock.")
-
- future.add_done_callback(on_done_callback)
- future.result()
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_connectivity_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_connectivity_test.py
deleted file mode 100644
index 912d8290a4c..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_connectivity_test.py
+++ /dev/null
@@ -1,156 +0,0 @@
-# Copyright 2015 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Tests of grpc._channel.Channel connectivity."""
-
-import logging
-import threading
-import time
-import unittest
-
-import grpc
-
-from tests.unit import thread_pool
-from tests.unit.framework.common import test_constants
-
-
-def _ready_in_connectivities(connectivities):
- return grpc.ChannelConnectivity.READY in connectivities
-
-
-def _last_connectivity_is_not_ready(connectivities):
- return connectivities[-1] is not grpc.ChannelConnectivity.READY
-
-
-class _Callback(object):
-
- def __init__(self):
- self._condition = threading.Condition()
- self._connectivities = []
-
- def update(self, connectivity):
- with self._condition:
- self._connectivities.append(connectivity)
- self._condition.notify()
-
- def connectivities(self):
- with self._condition:
- return tuple(self._connectivities)
-
- def block_until_connectivities_satisfy(self, predicate):
- with self._condition:
- while True:
- connectivities = tuple(self._connectivities)
- if predicate(connectivities):
- return connectivities
- else:
- self._condition.wait()
-
-
-class ChannelConnectivityTest(unittest.TestCase):
-
- def test_lonely_channel_connectivity(self):
- callback = _Callback()
-
- channel = grpc.insecure_channel('localhost:12345')
- channel.subscribe(callback.update, try_to_connect=False)
- first_connectivities = callback.block_until_connectivities_satisfy(bool)
- channel.subscribe(callback.update, try_to_connect=True)
- second_connectivities = callback.block_until_connectivities_satisfy(
- lambda connectivities: 2 <= len(connectivities))
- # Wait for a connection that will never happen.
- time.sleep(test_constants.SHORT_TIMEOUT)
- third_connectivities = callback.connectivities()
- channel.unsubscribe(callback.update)
- fourth_connectivities = callback.connectivities()
- channel.unsubscribe(callback.update)
- fifth_connectivities = callback.connectivities()
-
- channel.close()
-
- self.assertSequenceEqual((grpc.ChannelConnectivity.IDLE,),
- first_connectivities)
- self.assertNotIn(grpc.ChannelConnectivity.READY, second_connectivities)
- self.assertNotIn(grpc.ChannelConnectivity.READY, third_connectivities)
- self.assertNotIn(grpc.ChannelConnectivity.READY, fourth_connectivities)
- self.assertNotIn(grpc.ChannelConnectivity.READY, fifth_connectivities)
-
- def test_immediately_connectable_channel_connectivity(self):
- recording_thread_pool = thread_pool.RecordingThreadPool(
- max_workers=None)
- server = grpc.server(recording_thread_pool,
- options=(('grpc.so_reuseport', 0),))
- port = server.add_insecure_port('[::]:0')
- server.start()
- first_callback = _Callback()
- second_callback = _Callback()
-
- channel = grpc.insecure_channel('localhost:{}'.format(port))
- channel.subscribe(first_callback.update, try_to_connect=False)
- first_connectivities = first_callback.block_until_connectivities_satisfy(
- bool)
- # Wait for a connection that will never happen because try_to_connect=True
- # has not yet been passed.
- time.sleep(test_constants.SHORT_TIMEOUT)
- second_connectivities = first_callback.connectivities()
- channel.subscribe(second_callback.update, try_to_connect=True)
- third_connectivities = first_callback.block_until_connectivities_satisfy(
- lambda connectivities: 2 <= len(connectivities))
- fourth_connectivities = second_callback.block_until_connectivities_satisfy(
- bool)
- # Wait for a connection that will happen (or may already have happened).
- first_callback.block_until_connectivities_satisfy(
- _ready_in_connectivities)
- second_callback.block_until_connectivities_satisfy(
- _ready_in_connectivities)
- channel.close()
- server.stop(None)
-
- self.assertSequenceEqual((grpc.ChannelConnectivity.IDLE,),
- first_connectivities)
- self.assertSequenceEqual((grpc.ChannelConnectivity.IDLE,),
- second_connectivities)
- self.assertNotIn(grpc.ChannelConnectivity.TRANSIENT_FAILURE,
- third_connectivities)
- self.assertNotIn(grpc.ChannelConnectivity.SHUTDOWN,
- third_connectivities)
- self.assertNotIn(grpc.ChannelConnectivity.TRANSIENT_FAILURE,
- fourth_connectivities)
- self.assertNotIn(grpc.ChannelConnectivity.SHUTDOWN,
- fourth_connectivities)
- self.assertFalse(recording_thread_pool.was_used())
-
- def test_reachable_then_unreachable_channel_connectivity(self):
- recording_thread_pool = thread_pool.RecordingThreadPool(
- max_workers=None)
- server = grpc.server(recording_thread_pool,
- options=(('grpc.so_reuseport', 0),))
- port = server.add_insecure_port('[::]:0')
- server.start()
- callback = _Callback()
-
- channel = grpc.insecure_channel('localhost:{}'.format(port))
- channel.subscribe(callback.update, try_to_connect=True)
- callback.block_until_connectivities_satisfy(_ready_in_connectivities)
- # Now take down the server and confirm that channel readiness is repudiated.
- server.stop(None)
- callback.block_until_connectivities_satisfy(
- _last_connectivity_is_not_ready)
- channel.unsubscribe(callback.update)
- channel.close()
- self.assertFalse(recording_thread_pool.was_used())
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_ready_future_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_ready_future_test.py
deleted file mode 100644
index 84a6f9196b3..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_channel_ready_future_test.py
+++ /dev/null
@@ -1,98 +0,0 @@
-# Copyright 2015 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Tests of grpc.channel_ready_future."""
-
-import logging
-import threading
-import unittest
-
-import grpc
-
-from tests.unit import thread_pool
-from tests.unit.framework.common import test_constants
-
-
-class _Callback(object):
-
- def __init__(self):
- self._condition = threading.Condition()
- self._value = None
-
- def accept_value(self, value):
- with self._condition:
- self._value = value
- self._condition.notify_all()
-
- def block_until_called(self):
- with self._condition:
- while self._value is None:
- self._condition.wait()
- return self._value
-
-
-class ChannelReadyFutureTest(unittest.TestCase):
-
- def test_lonely_channel_connectivity(self):
- channel = grpc.insecure_channel('localhost:12345')
- callback = _Callback()
-
- ready_future = grpc.channel_ready_future(channel)
- ready_future.add_done_callback(callback.accept_value)
- with self.assertRaises(grpc.FutureTimeoutError):
- ready_future.result(timeout=test_constants.SHORT_TIMEOUT)
- self.assertFalse(ready_future.cancelled())
- self.assertFalse(ready_future.done())
- self.assertTrue(ready_future.running())
- ready_future.cancel()
- value_passed_to_callback = callback.block_until_called()
- self.assertIs(ready_future, value_passed_to_callback)
- self.assertTrue(ready_future.cancelled())
- self.assertTrue(ready_future.done())
- self.assertFalse(ready_future.running())
-
- channel.close()
-
- def test_immediately_connectable_channel_connectivity(self):
- recording_thread_pool = thread_pool.RecordingThreadPool(
- max_workers=None)
- server = grpc.server(recording_thread_pool,
- options=(('grpc.so_reuseport', 0),))
- port = server.add_insecure_port('[::]:0')
- server.start()
- channel = grpc.insecure_channel('localhost:{}'.format(port))
- callback = _Callback()
-
- ready_future = grpc.channel_ready_future(channel)
- ready_future.add_done_callback(callback.accept_value)
- self.assertIsNone(
- ready_future.result(timeout=test_constants.LONG_TIMEOUT))
- value_passed_to_callback = callback.block_until_called()
- self.assertIs(ready_future, value_passed_to_callback)
- self.assertFalse(ready_future.cancelled())
- self.assertTrue(ready_future.done())
- self.assertFalse(ready_future.running())
- # Cancellation after maturity has no effect.
- ready_future.cancel()
- self.assertFalse(ready_future.cancelled())
- self.assertTrue(ready_future.done())
- self.assertFalse(ready_future.running())
- self.assertFalse(recording_thread_pool.was_used())
-
- channel.close()
- server.stop(None)
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_contextvars_propagation_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_contextvars_propagation_test.py
deleted file mode 100644
index 128ec514d06..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_contextvars_propagation_test.py
+++ /dev/null
@@ -1,163 +0,0 @@
-# Copyright 2020 The gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Test of propagation of contextvars to AuthMetadataPlugin threads.."""
-
-import contextlib
-import logging
-import os
-import sys
-import threading
-import unittest
-
-import grpc
-from six.moves import queue
-
-from tests.unit import test_common
-
-_UNARY_UNARY = "/test/UnaryUnary"
-_REQUEST = b"0000"
-
-
-def _unary_unary_handler(request, context):
- return request
-
-
-def contextvars_supported():
- try:
- import contextvars
- return True
- except ImportError:
- return False
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def service(self, handler_call_details):
- if handler_call_details.method == _UNARY_UNARY:
- return grpc.unary_unary_rpc_method_handler(_unary_unary_handler)
- else:
- raise NotImplementedError()
-
-
-@contextlib.contextmanager
-def _server():
- try:
- server = test_common.test_server()
- target = 'localhost:0'
- port = server.add_insecure_port(target)
- server.add_generic_rpc_handlers((_GenericHandler(),))
- server.start()
- yield port
- finally:
- server.stop(None)
-
-
-if contextvars_supported():
- import contextvars
-
- _EXPECTED_VALUE = 24601
- test_var = contextvars.ContextVar("test_var", default=None)
-
- def set_up_expected_context():
- test_var.set(_EXPECTED_VALUE)
-
- class TestCallCredentials(grpc.AuthMetadataPlugin):
-
- def __call__(self, context, callback):
- if test_var.get() != _EXPECTED_VALUE:
- raise AssertionError("{} != {}".format(test_var.get(),
- _EXPECTED_VALUE))
- callback((), None)
-
- def assert_called(self, test):
- test.assertTrue(self._invoked)
- test.assertEqual(_EXPECTED_VALUE, self._recorded_value)
-
-else:
-
- def set_up_expected_context():
- pass
-
- class TestCallCredentials(grpc.AuthMetadataPlugin):
-
- def __call__(self, context, callback):
- callback((), None)
-
-
-# TODO(https://github.com/grpc/grpc/issues/22257)
-@unittest.skipIf(os.name == "nt", "LocalCredentials not supported on Windows.")
-@unittest.skipIf(test_common.running_under_gevent(),
- "ThreadLocals do not work under gevent.")
-class ContextVarsPropagationTest(unittest.TestCase):
-
- def test_propagation_to_auth_plugin(self):
- set_up_expected_context()
- with _server() as port:
- target = "localhost:{}".format(port)
- local_credentials = grpc.local_channel_credentials()
- test_call_credentials = TestCallCredentials()
- call_credentials = grpc.metadata_call_credentials(
- test_call_credentials, "test call credentials")
- composite_credentials = grpc.composite_channel_credentials(
- local_credentials, call_credentials)
- with grpc.secure_channel(target, composite_credentials) as channel:
- stub = channel.unary_unary(_UNARY_UNARY)
- response = stub(_REQUEST, wait_for_ready=True)
- self.assertEqual(_REQUEST, response)
-
- def test_concurrent_propagation(self):
- _THREAD_COUNT = 32
- _RPC_COUNT = 32
-
- set_up_expected_context()
- with _server() as port:
- target = "localhost:{}".format(port)
- local_credentials = grpc.local_channel_credentials()
- test_call_credentials = TestCallCredentials()
- call_credentials = grpc.metadata_call_credentials(
- test_call_credentials, "test call credentials")
- composite_credentials = grpc.composite_channel_credentials(
- local_credentials, call_credentials)
- wait_group = test_common.WaitGroup(_THREAD_COUNT)
-
- def _run_on_thread(exception_queue):
- try:
- with grpc.secure_channel(target,
- composite_credentials) as channel:
- stub = channel.unary_unary(_UNARY_UNARY)
- wait_group.done()
- wait_group.wait()
- for i in range(_RPC_COUNT):
- response = stub(_REQUEST, wait_for_ready=True)
- self.assertEqual(_REQUEST, response)
- except Exception as e: # pylint: disable=broad-except
- exception_queue.put(e)
-
- threads = []
- for _ in range(_RPC_COUNT):
- q = queue.Queue()
- thread = threading.Thread(target=_run_on_thread, args=(q,))
- thread.setDaemon(True)
- thread.start()
- threads.append((thread, q))
-
- for thread, q in threads:
- thread.join()
- if not q.empty():
- raise q.get()
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_credentials_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_credentials_test.py
deleted file mode 100644
index 5b420eb73ae..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_credentials_test.py
+++ /dev/null
@@ -1,70 +0,0 @@
-# Copyright 2016 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Tests of credentials."""
-
-import logging
-import unittest
-
-import grpc
-import six
-
-
-class CredentialsTest(unittest.TestCase):
-
- def test_call_credentials_composition(self):
- first = grpc.access_token_call_credentials('abc')
- second = grpc.access_token_call_credentials('def')
- third = grpc.access_token_call_credentials('ghi')
-
- first_and_second = grpc.composite_call_credentials(first, second)
- first_second_and_third = grpc.composite_call_credentials(
- first, second, third)
-
- self.assertIsInstance(first_and_second, grpc.CallCredentials)
- self.assertIsInstance(first_second_and_third, grpc.CallCredentials)
-
- def test_channel_credentials_composition(self):
- first_call_credentials = grpc.access_token_call_credentials('abc')
- second_call_credentials = grpc.access_token_call_credentials('def')
- third_call_credentials = grpc.access_token_call_credentials('ghi')
- channel_credentials = grpc.ssl_channel_credentials()
-
- channel_and_first = grpc.composite_channel_credentials(
- channel_credentials, first_call_credentials)
- channel_first_and_second = grpc.composite_channel_credentials(
- channel_credentials, first_call_credentials,
- second_call_credentials)
- channel_first_second_and_third = grpc.composite_channel_credentials(
- channel_credentials, first_call_credentials,
- second_call_credentials, third_call_credentials)
-
- self.assertIsInstance(channel_and_first, grpc.ChannelCredentials)
- self.assertIsInstance(channel_first_and_second, grpc.ChannelCredentials)
- self.assertIsInstance(channel_first_second_and_third,
- grpc.ChannelCredentials)
-
- @unittest.skipIf(six.PY2, 'only invalid in Python3')
- def test_invalid_string_certificate(self):
- self.assertRaises(
- TypeError,
- grpc.ssl_channel_credentials,
- root_certificates='A Certificate',
- private_key=None,
- certificate_chain=None,
- )
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/__init__.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/__init__.py
deleted file mode 100644
index 5fb4f3c3cfd..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/__init__.py
+++ /dev/null
@@ -1,13 +0,0 @@
-# Copyright 2015 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_cancel_many_calls_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_cancel_many_calls_test.py
deleted file mode 100644
index 3ca0d686d61..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_cancel_many_calls_test.py
+++ /dev/null
@@ -1,222 +0,0 @@
-# Copyright 2016 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Test making many calls and immediately cancelling most of them."""
-
-import threading
-import unittest
-
-from grpc._cython import cygrpc
-from grpc.framework.foundation import logging_pool
-
-from tests.unit._cython import test_utilities
-from tests.unit.framework.common import test_constants
-
-_EMPTY_FLAGS = 0
-_EMPTY_METADATA = ()
-
-_SERVER_SHUTDOWN_TAG = 'server_shutdown'
-_REQUEST_CALL_TAG = 'request_call'
-_RECEIVE_CLOSE_ON_SERVER_TAG = 'receive_close_on_server'
-_RECEIVE_MESSAGE_TAG = 'receive_message'
-_SERVER_COMPLETE_CALL_TAG = 'server_complete_call'
-
-_SUCCESS_CALL_FRACTION = 1.0 / 8.0
-_SUCCESSFUL_CALLS = int(test_constants.RPC_CONCURRENCY * _SUCCESS_CALL_FRACTION)
-_UNSUCCESSFUL_CALLS = test_constants.RPC_CONCURRENCY - _SUCCESSFUL_CALLS
-
-
-class _State(object):
-
- def __init__(self):
- self.condition = threading.Condition()
- self.handlers_released = False
- self.parked_handlers = 0
- self.handled_rpcs = 0
-
-
-def _is_cancellation_event(event):
- return (event.tag is _RECEIVE_CLOSE_ON_SERVER_TAG and
- event.batch_operations[0].cancelled())
-
-
-class _Handler(object):
-
- def __init__(self, state, completion_queue, rpc_event):
- self._state = state
- self._lock = threading.Lock()
- self._completion_queue = completion_queue
- self._call = rpc_event.call
-
- def __call__(self):
- with self._state.condition:
- self._state.parked_handlers += 1
- if self._state.parked_handlers == test_constants.THREAD_CONCURRENCY:
- self._state.condition.notify_all()
- while not self._state.handlers_released:
- self._state.condition.wait()
-
- with self._lock:
- self._call.start_server_batch(
- (cygrpc.ReceiveCloseOnServerOperation(_EMPTY_FLAGS),),
- _RECEIVE_CLOSE_ON_SERVER_TAG)
- self._call.start_server_batch(
- (cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),),
- _RECEIVE_MESSAGE_TAG)
- first_event = self._completion_queue.poll()
- if _is_cancellation_event(first_event):
- self._completion_queue.poll()
- else:
- with self._lock:
- operations = (
- cygrpc.SendInitialMetadataOperation(_EMPTY_METADATA,
- _EMPTY_FLAGS),
- cygrpc.SendMessageOperation(b'\x79\x57', _EMPTY_FLAGS),
- cygrpc.SendStatusFromServerOperation(
- _EMPTY_METADATA, cygrpc.StatusCode.ok, b'test details!',
- _EMPTY_FLAGS),
- )
- self._call.start_server_batch(operations,
- _SERVER_COMPLETE_CALL_TAG)
- self._completion_queue.poll()
- self._completion_queue.poll()
-
-
-def _serve(state, server, server_completion_queue, thread_pool):
- for _ in range(test_constants.RPC_CONCURRENCY):
- call_completion_queue = cygrpc.CompletionQueue()
- server.request_call(call_completion_queue, server_completion_queue,
- _REQUEST_CALL_TAG)
- rpc_event = server_completion_queue.poll()
- thread_pool.submit(_Handler(state, call_completion_queue, rpc_event))
- with state.condition:
- state.handled_rpcs += 1
- if test_constants.RPC_CONCURRENCY <= state.handled_rpcs:
- state.condition.notify_all()
- server_completion_queue.poll()
-
-
-class _QueueDriver(object):
-
- def __init__(self, condition, completion_queue, due):
- self._condition = condition
- self._completion_queue = completion_queue
- self._due = due
- self._events = []
- self._returned = False
-
- def start(self):
-
- def in_thread():
- while True:
- event = self._completion_queue.poll()
- with self._condition:
- self._events.append(event)
- self._due.remove(event.tag)
- self._condition.notify_all()
- if not self._due:
- self._returned = True
- return
-
- thread = threading.Thread(target=in_thread)
- thread.start()
-
- def events(self, at_least):
- with self._condition:
- while len(self._events) < at_least:
- self._condition.wait()
- return tuple(self._events)
-
-
-class CancelManyCallsTest(unittest.TestCase):
-
- def testCancelManyCalls(self):
- server_thread_pool = logging_pool.pool(
- test_constants.THREAD_CONCURRENCY)
-
- server_completion_queue = cygrpc.CompletionQueue()
- server = cygrpc.Server([(
- b'grpc.so_reuseport',
- 0,
- )], False)
- server.register_completion_queue(server_completion_queue)
- port = server.add_http2_port(b'[::]:0')
- server.start()
- channel = cygrpc.Channel('localhost:{}'.format(port).encode(), None,
- None)
-
- state = _State()
-
- server_thread_args = (
- state,
- server,
- server_completion_queue,
- server_thread_pool,
- )
- server_thread = threading.Thread(target=_serve, args=server_thread_args)
- server_thread.start()
-
- client_condition = threading.Condition()
- client_due = set()
-
- with client_condition:
- client_calls = []
- for index in range(test_constants.RPC_CONCURRENCY):
- tag = 'client_complete_call_{0:04d}_tag'.format(index)
- client_call = channel.integrated_call(
- _EMPTY_FLAGS, b'/twinkies', None, None, _EMPTY_METADATA,
- None, ((
- (
- cygrpc.SendInitialMetadataOperation(
- _EMPTY_METADATA, _EMPTY_FLAGS),
- cygrpc.SendMessageOperation(b'\x45\x56',
- _EMPTY_FLAGS),
- cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS),
- cygrpc.ReceiveInitialMetadataOperation(
- _EMPTY_FLAGS),
- cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),
- cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),
- ),
- tag,
- ),))
- client_due.add(tag)
- client_calls.append(client_call)
-
- client_events_future = test_utilities.SimpleFuture(lambda: tuple(
- channel.next_call_event() for _ in range(_SUCCESSFUL_CALLS)))
-
- with state.condition:
- while True:
- if state.parked_handlers < test_constants.THREAD_CONCURRENCY:
- state.condition.wait()
- elif state.handled_rpcs < test_constants.RPC_CONCURRENCY:
- state.condition.wait()
- else:
- state.handlers_released = True
- state.condition.notify_all()
- break
-
- client_events_future.result()
- with client_condition:
- for client_call in client_calls:
- client_call.cancel(cygrpc.StatusCode.cancelled, 'Cancelled!')
- for _ in range(_UNSUCCESSFUL_CALLS):
- channel.next_call_event()
-
- channel.close(cygrpc.StatusCode.unknown, 'Cancelled on channel close!')
- with state.condition:
- server.shutdown(server_completion_queue, _SERVER_SHUTDOWN_TAG)
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_channel_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_channel_test.py
deleted file mode 100644
index 8f0b6fedc02..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_channel_test.py
+++ /dev/null
@@ -1,70 +0,0 @@
-# Copyright 2016 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import threading
-import time
-import unittest
-
-from grpc._cython import cygrpc
-
-from tests.unit.framework.common import test_constants
-
-
-def _channel():
- return cygrpc.Channel(b'localhost:54321', (), None)
-
-
-def _connectivity_loop(channel):
- for _ in range(100):
- connectivity = channel.check_connectivity_state(True)
- channel.watch_connectivity_state(connectivity, time.time() + 0.2)
-
-
-def _create_loop_destroy():
- channel = _channel()
- _connectivity_loop(channel)
- channel.close(cygrpc.StatusCode.ok, 'Channel close!')
-
-
-def _in_parallel(behavior, arguments):
- threads = tuple(
- threading.Thread(target=behavior, args=arguments)
- for _ in range(test_constants.THREAD_CONCURRENCY))
- for thread in threads:
- thread.start()
- for thread in threads:
- thread.join()
-
-
-class ChannelTest(unittest.TestCase):
-
- def test_single_channel_lonely_connectivity(self):
- channel = _channel()
- _connectivity_loop(channel)
- channel.close(cygrpc.StatusCode.ok, 'Channel close!')
-
- def test_multiple_channels_lonely_connectivity(self):
- _in_parallel(_create_loop_destroy, ())
-
- def test_negative_deadline_connectivity(self):
- channel = _channel()
- connectivity = channel.check_connectivity_state(True)
- channel.watch_connectivity_state(connectivity, -3.14)
- channel.close(cygrpc.StatusCode.ok, 'Channel close!')
- # NOTE(lidiz) The negative timeout should not trigger SIGABRT.
- # Bug report: https://github.com/grpc/grpc/issues/18244
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_common.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_common.py
deleted file mode 100644
index 42ec655feee..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_common.py
+++ /dev/null
@@ -1,123 +0,0 @@
-# Copyright 2017 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Common utilities for tests of the Cython layer of gRPC Python."""
-
-import collections
-import threading
-
-from grpc._cython import cygrpc
-
-RPC_COUNT = 4000
-
-EMPTY_FLAGS = 0
-
-INVOCATION_METADATA = (
- ('client-md-key', 'client-md-key'),
- ('client-md-key-bin', b'\x00\x01' * 3000),
-)
-
-INITIAL_METADATA = (
- ('server-initial-md-key', 'server-initial-md-value'),
- ('server-initial-md-key-bin', b'\x00\x02' * 3000),
-)
-
-TRAILING_METADATA = (
- ('server-trailing-md-key', 'server-trailing-md-value'),
- ('server-trailing-md-key-bin', b'\x00\x03' * 3000),
-)
-
-
-class QueueDriver(object):
-
- def __init__(self, condition, completion_queue):
- self._condition = condition
- self._completion_queue = completion_queue
- self._due = collections.defaultdict(int)
- self._events = collections.defaultdict(list)
-
- def add_due(self, tags):
- if not self._due:
-
- def in_thread():
- while True:
- event = self._completion_queue.poll()
- with self._condition:
- self._events[event.tag].append(event)
- self._due[event.tag] -= 1
- self._condition.notify_all()
- if self._due[event.tag] <= 0:
- self._due.pop(event.tag)
- if not self._due:
- return
-
- thread = threading.Thread(target=in_thread)
- thread.start()
- for tag in tags:
- self._due[tag] += 1
-
- def event_with_tag(self, tag):
- with self._condition:
- while True:
- if self._events[tag]:
- return self._events[tag].pop(0)
- else:
- self._condition.wait()
-
-
-def execute_many_times(behavior):
- return tuple(behavior() for _ in range(RPC_COUNT))
-
-
-class OperationResult(
- collections.namedtuple('OperationResult', (
- 'start_batch_result',
- 'completion_type',
- 'success',
- ))):
- pass
-
-
-SUCCESSFUL_OPERATION_RESULT = OperationResult(
- cygrpc.CallError.ok, cygrpc.CompletionType.operation_complete, True)
-
-
-class RpcTest(object):
-
- def setUp(self):
- self.server_completion_queue = cygrpc.CompletionQueue()
- self.server = cygrpc.Server([(b'grpc.so_reuseport', 0)], False)
- self.server.register_completion_queue(self.server_completion_queue)
- port = self.server.add_http2_port(b'[::]:0')
- self.server.start()
- self.channel = cygrpc.Channel('localhost:{}'.format(port).encode(), [],
- None)
-
- self._server_shutdown_tag = 'server_shutdown_tag'
- self.server_condition = threading.Condition()
- self.server_driver = QueueDriver(self.server_condition,
- self.server_completion_queue)
- with self.server_condition:
- self.server_driver.add_due({
- self._server_shutdown_tag,
- })
-
- self.client_condition = threading.Condition()
- self.client_completion_queue = cygrpc.CompletionQueue()
- self.client_driver = QueueDriver(self.client_condition,
- self.client_completion_queue)
-
- def tearDown(self):
- self.server.shutdown(self.server_completion_queue,
- self._server_shutdown_tag)
- self.server.cancel_all_calls()
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_fork_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_fork_test.py
deleted file mode 100644
index 5a5dedd5f26..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_fork_test.py
+++ /dev/null
@@ -1,72 +0,0 @@
-# Copyright 2018 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import os
-import threading
-import unittest
-
-from grpc._cython import cygrpc
-
-
-def _get_number_active_threads():
- return cygrpc._fork_state.active_thread_count._num_active_threads
-
-
-@unittest.skipIf(os.name == 'nt', 'Posix-specific tests')
-class ForkPosixTester(unittest.TestCase):
-
- def setUp(self):
- self._saved_fork_support_flag = cygrpc._GRPC_ENABLE_FORK_SUPPORT
- cygrpc._GRPC_ENABLE_FORK_SUPPORT = True
-
- def testForkManagedThread(self):
-
- def cb():
- self.assertEqual(1, _get_number_active_threads())
-
- thread = cygrpc.ForkManagedThread(cb)
- thread.start()
- thread.join()
- self.assertEqual(0, _get_number_active_threads())
-
- def testForkManagedThreadThrowsException(self):
-
- def cb():
- self.assertEqual(1, _get_number_active_threads())
- raise Exception("expected exception")
-
- thread = cygrpc.ForkManagedThread(cb)
- thread.start()
- thread.join()
- self.assertEqual(0, _get_number_active_threads())
-
- def tearDown(self):
- cygrpc._GRPC_ENABLE_FORK_SUPPORT = self._saved_fork_support_flag
-
-
-@unittest.skipUnless(os.name == 'nt', 'Windows-specific tests')
-class ForkWindowsTester(unittest.TestCase):
-
- def testForkManagedThreadIsNoOp(self):
-
- def cb():
- pass
-
- thread = cygrpc.ForkManagedThread(cb)
- thread.start()
- thread.join()
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_no_messages_server_completion_queue_per_call_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_no_messages_server_completion_queue_per_call_test.py
deleted file mode 100644
index 144a2fcae3f..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_no_messages_server_completion_queue_per_call_test.py
+++ /dev/null
@@ -1,132 +0,0 @@
-# Copyright 2017 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Test a corner-case at the level of the Cython API."""
-
-import threading
-import unittest
-
-from grpc._cython import cygrpc
-
-from tests.unit._cython import _common
-from tests.unit._cython import test_utilities
-
-
-class Test(_common.RpcTest, unittest.TestCase):
-
- def _do_rpcs(self):
- server_call_condition = threading.Condition()
- server_call_completion_queue = cygrpc.CompletionQueue()
- server_call_driver = _common.QueueDriver(server_call_condition,
- server_call_completion_queue)
-
- server_request_call_tag = 'server_request_call_tag'
- server_send_initial_metadata_tag = 'server_send_initial_metadata_tag'
- server_complete_rpc_tag = 'server_complete_rpc_tag'
-
- with self.server_condition:
- server_request_call_start_batch_result = self.server.request_call(
- server_call_completion_queue, self.server_completion_queue,
- server_request_call_tag)
- self.server_driver.add_due({
- server_request_call_tag,
- })
-
- client_receive_initial_metadata_tag = 'client_receive_initial_metadata_tag'
- client_complete_rpc_tag = 'client_complete_rpc_tag'
- client_call = self.channel.integrated_call(
- _common.EMPTY_FLAGS, b'/twinkies', None, None,
- _common.INVOCATION_METADATA, None, [(
- [
- cygrpc.ReceiveInitialMetadataOperation(_common.EMPTY_FLAGS),
- ],
- client_receive_initial_metadata_tag,
- )])
- client_call.operate([
- cygrpc.SendInitialMetadataOperation(_common.INVOCATION_METADATA,
- _common.EMPTY_FLAGS),
- cygrpc.SendCloseFromClientOperation(_common.EMPTY_FLAGS),
- cygrpc.ReceiveStatusOnClientOperation(_common.EMPTY_FLAGS),
- ], client_complete_rpc_tag)
-
- client_events_future = test_utilities.SimpleFuture(lambda: [
- self.channel.next_call_event(),
- self.channel.next_call_event(),
- ])
-
- server_request_call_event = self.server_driver.event_with_tag(
- server_request_call_tag)
-
- with server_call_condition:
- server_send_initial_metadata_start_batch_result = (
- server_request_call_event.call.start_server_batch([
- cygrpc.SendInitialMetadataOperation(
- _common.INITIAL_METADATA, _common.EMPTY_FLAGS),
- ], server_send_initial_metadata_tag))
- server_call_driver.add_due({
- server_send_initial_metadata_tag,
- })
- server_send_initial_metadata_event = server_call_driver.event_with_tag(
- server_send_initial_metadata_tag)
-
- with server_call_condition:
- server_complete_rpc_start_batch_result = (
- server_request_call_event.call.start_server_batch([
- cygrpc.ReceiveCloseOnServerOperation(_common.EMPTY_FLAGS),
- cygrpc.SendStatusFromServerOperation(
- _common.TRAILING_METADATA, cygrpc.StatusCode.ok,
- b'test details', _common.EMPTY_FLAGS),
- ], server_complete_rpc_tag))
- server_call_driver.add_due({
- server_complete_rpc_tag,
- })
- server_complete_rpc_event = server_call_driver.event_with_tag(
- server_complete_rpc_tag)
-
- client_events = client_events_future.result()
- if client_events[0].tag is client_receive_initial_metadata_tag:
- client_receive_initial_metadata_event = client_events[0]
- client_complete_rpc_event = client_events[1]
- else:
- client_complete_rpc_event = client_events[0]
- client_receive_initial_metadata_event = client_events[1]
-
- return (
- _common.OperationResult(server_request_call_start_batch_result,
- server_request_call_event.completion_type,
- server_request_call_event.success),
- _common.OperationResult(
- cygrpc.CallError.ok,
- client_receive_initial_metadata_event.completion_type,
- client_receive_initial_metadata_event.success),
- _common.OperationResult(cygrpc.CallError.ok,
- client_complete_rpc_event.completion_type,
- client_complete_rpc_event.success),
- _common.OperationResult(
- server_send_initial_metadata_start_batch_result,
- server_send_initial_metadata_event.completion_type,
- server_send_initial_metadata_event.success),
- _common.OperationResult(server_complete_rpc_start_batch_result,
- server_complete_rpc_event.completion_type,
- server_complete_rpc_event.success),
- )
-
- def test_rpcs(self):
- expecteds = [(_common.SUCCESSFUL_OPERATION_RESULT,) * 5
- ] * _common.RPC_COUNT
- actuallys = _common.execute_many_times(self._do_rpcs)
- self.assertSequenceEqual(expecteds, actuallys)
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_no_messages_single_server_completion_queue_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_no_messages_single_server_completion_queue_test.py
deleted file mode 100644
index 38964768db7..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_no_messages_single_server_completion_queue_test.py
+++ /dev/null
@@ -1,126 +0,0 @@
-# Copyright 2017 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Test a corner-case at the level of the Cython API."""
-
-import threading
-import unittest
-
-from grpc._cython import cygrpc
-
-from tests.unit._cython import _common
-from tests.unit._cython import test_utilities
-
-
-class Test(_common.RpcTest, unittest.TestCase):
-
- def _do_rpcs(self):
- server_request_call_tag = 'server_request_call_tag'
- server_send_initial_metadata_tag = 'server_send_initial_metadata_tag'
- server_complete_rpc_tag = 'server_complete_rpc_tag'
-
- with self.server_condition:
- server_request_call_start_batch_result = self.server.request_call(
- self.server_completion_queue, self.server_completion_queue,
- server_request_call_tag)
- self.server_driver.add_due({
- server_request_call_tag,
- })
-
- client_receive_initial_metadata_tag = 'client_receive_initial_metadata_tag'
- client_complete_rpc_tag = 'client_complete_rpc_tag'
- client_call = self.channel.integrated_call(
- _common.EMPTY_FLAGS, b'/twinkies', None, None,
- _common.INVOCATION_METADATA, None, [
- (
- [
- cygrpc.SendInitialMetadataOperation(
- _common.INVOCATION_METADATA, _common.EMPTY_FLAGS),
- cygrpc.SendCloseFromClientOperation(
- _common.EMPTY_FLAGS),
- cygrpc.ReceiveStatusOnClientOperation(
- _common.EMPTY_FLAGS),
- ],
- client_complete_rpc_tag,
- ),
- ])
- client_call.operate([
- cygrpc.ReceiveInitialMetadataOperation(_common.EMPTY_FLAGS),
- ], client_receive_initial_metadata_tag)
-
- client_events_future = test_utilities.SimpleFuture(lambda: [
- self.channel.next_call_event(),
- self.channel.next_call_event(),
- ])
- server_request_call_event = self.server_driver.event_with_tag(
- server_request_call_tag)
-
- with self.server_condition:
- server_send_initial_metadata_start_batch_result = (
- server_request_call_event.call.start_server_batch([
- cygrpc.SendInitialMetadataOperation(
- _common.INITIAL_METADATA, _common.EMPTY_FLAGS),
- ], server_send_initial_metadata_tag))
- self.server_driver.add_due({
- server_send_initial_metadata_tag,
- })
- server_send_initial_metadata_event = self.server_driver.event_with_tag(
- server_send_initial_metadata_tag)
-
- with self.server_condition:
- server_complete_rpc_start_batch_result = (
- server_request_call_event.call.start_server_batch([
- cygrpc.ReceiveCloseOnServerOperation(_common.EMPTY_FLAGS),
- cygrpc.SendStatusFromServerOperation(
- _common.TRAILING_METADATA, cygrpc.StatusCode.ok,
- 'test details', _common.EMPTY_FLAGS),
- ], server_complete_rpc_tag))
- self.server_driver.add_due({
- server_complete_rpc_tag,
- })
- server_complete_rpc_event = self.server_driver.event_with_tag(
- server_complete_rpc_tag)
-
- client_events = client_events_future.result()
- client_receive_initial_metadata_event = client_events[0]
- client_complete_rpc_event = client_events[1]
-
- return (
- _common.OperationResult(server_request_call_start_batch_result,
- server_request_call_event.completion_type,
- server_request_call_event.success),
- _common.OperationResult(
- cygrpc.CallError.ok,
- client_receive_initial_metadata_event.completion_type,
- client_receive_initial_metadata_event.success),
- _common.OperationResult(cygrpc.CallError.ok,
- client_complete_rpc_event.completion_type,
- client_complete_rpc_event.success),
- _common.OperationResult(
- server_send_initial_metadata_start_batch_result,
- server_send_initial_metadata_event.completion_type,
- server_send_initial_metadata_event.success),
- _common.OperationResult(server_complete_rpc_start_batch_result,
- server_complete_rpc_event.completion_type,
- server_complete_rpc_event.success),
- )
-
- def test_rpcs(self):
- expecteds = [(_common.SUCCESSFUL_OPERATION_RESULT,) * 5
- ] * _common.RPC_COUNT
- actuallys = _common.execute_many_times(self._do_rpcs)
- self.assertSequenceEqual(expecteds, actuallys)
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_read_some_but_not_all_responses_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_read_some_but_not_all_responses_test.py
deleted file mode 100644
index 701ebcee5c2..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_read_some_but_not_all_responses_test.py
+++ /dev/null
@@ -1,241 +0,0 @@
-# Copyright 2016 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Test a corner-case at the level of the Cython API."""
-
-import threading
-import unittest
-
-from grpc._cython import cygrpc
-
-from tests.unit._cython import test_utilities
-
-_EMPTY_FLAGS = 0
-_EMPTY_METADATA = ()
-
-
-class _ServerDriver(object):
-
- def __init__(self, completion_queue, shutdown_tag):
- self._condition = threading.Condition()
- self._completion_queue = completion_queue
- self._shutdown_tag = shutdown_tag
- self._events = []
- self._saw_shutdown_tag = False
-
- def start(self):
-
- def in_thread():
- while True:
- event = self._completion_queue.poll()
- with self._condition:
- self._events.append(event)
- self._condition.notify()
- if event.tag is self._shutdown_tag:
- self._saw_shutdown_tag = True
- break
-
- thread = threading.Thread(target=in_thread)
- thread.start()
-
- def done(self):
- with self._condition:
- return self._saw_shutdown_tag
-
- def first_event(self):
- with self._condition:
- while not self._events:
- self._condition.wait()
- return self._events[0]
-
- def events(self):
- with self._condition:
- while not self._saw_shutdown_tag:
- self._condition.wait()
- return tuple(self._events)
-
-
-class _QueueDriver(object):
-
- def __init__(self, condition, completion_queue, due):
- self._condition = condition
- self._completion_queue = completion_queue
- self._due = due
- self._events = []
- self._returned = False
-
- def start(self):
-
- def in_thread():
- while True:
- event = self._completion_queue.poll()
- with self._condition:
- self._events.append(event)
- self._due.remove(event.tag)
- self._condition.notify_all()
- if not self._due:
- self._returned = True
- return
-
- thread = threading.Thread(target=in_thread)
- thread.start()
-
- def done(self):
- with self._condition:
- return self._returned
-
- def event_with_tag(self, tag):
- with self._condition:
- while True:
- for event in self._events:
- if event.tag is tag:
- return event
- self._condition.wait()
-
- def events(self):
- with self._condition:
- while not self._returned:
- self._condition.wait()
- return tuple(self._events)
-
-
-class ReadSomeButNotAllResponsesTest(unittest.TestCase):
-
- def testReadSomeButNotAllResponses(self):
- server_completion_queue = cygrpc.CompletionQueue()
- server = cygrpc.Server([(
- b'grpc.so_reuseport',
- 0,
- )], False)
- server.register_completion_queue(server_completion_queue)
- port = server.add_http2_port(b'[::]:0')
- server.start()
- channel = cygrpc.Channel('localhost:{}'.format(port).encode(), set(),
- None)
-
- server_shutdown_tag = 'server_shutdown_tag'
- server_driver = _ServerDriver(server_completion_queue,
- server_shutdown_tag)
- server_driver.start()
-
- client_condition = threading.Condition()
- client_due = set()
-
- server_call_condition = threading.Condition()
- server_send_initial_metadata_tag = 'server_send_initial_metadata_tag'
- server_send_first_message_tag = 'server_send_first_message_tag'
- server_send_second_message_tag = 'server_send_second_message_tag'
- server_complete_rpc_tag = 'server_complete_rpc_tag'
- server_call_due = set((
- server_send_initial_metadata_tag,
- server_send_first_message_tag,
- server_send_second_message_tag,
- server_complete_rpc_tag,
- ))
- server_call_completion_queue = cygrpc.CompletionQueue()
- server_call_driver = _QueueDriver(server_call_condition,
- server_call_completion_queue,
- server_call_due)
- server_call_driver.start()
-
- server_rpc_tag = 'server_rpc_tag'
- request_call_result = server.request_call(server_call_completion_queue,
- server_completion_queue,
- server_rpc_tag)
-
- client_receive_initial_metadata_tag = 'client_receive_initial_metadata_tag'
- client_complete_rpc_tag = 'client_complete_rpc_tag'
- client_call = channel.segregated_call(
- _EMPTY_FLAGS, b'/twinkies', None, None, _EMPTY_METADATA, None, (
- (
- [
- cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),
- ],
- client_receive_initial_metadata_tag,
- ),
- (
- [
- cygrpc.SendInitialMetadataOperation(
- _EMPTY_METADATA, _EMPTY_FLAGS),
- cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS),
- cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),
- ],
- client_complete_rpc_tag,
- ),
- ))
- client_receive_initial_metadata_event_future = test_utilities.SimpleFuture(
- client_call.next_event)
-
- server_rpc_event = server_driver.first_event()
-
- with server_call_condition:
- server_send_initial_metadata_start_batch_result = (
- server_rpc_event.call.start_server_batch([
- cygrpc.SendInitialMetadataOperation(_EMPTY_METADATA,
- _EMPTY_FLAGS),
- ], server_send_initial_metadata_tag))
- server_send_first_message_start_batch_result = (
- server_rpc_event.call.start_server_batch([
- cygrpc.SendMessageOperation(b'\x07', _EMPTY_FLAGS),
- ], server_send_first_message_tag))
- server_send_initial_metadata_event = server_call_driver.event_with_tag(
- server_send_initial_metadata_tag)
- server_send_first_message_event = server_call_driver.event_with_tag(
- server_send_first_message_tag)
- with server_call_condition:
- server_send_second_message_start_batch_result = (
- server_rpc_event.call.start_server_batch([
- cygrpc.SendMessageOperation(b'\x07', _EMPTY_FLAGS),
- ], server_send_second_message_tag))
- server_complete_rpc_start_batch_result = (
- server_rpc_event.call.start_server_batch([
- cygrpc.ReceiveCloseOnServerOperation(_EMPTY_FLAGS),
- cygrpc.SendStatusFromServerOperation(
- (), cygrpc.StatusCode.ok, b'test details',
- _EMPTY_FLAGS),
- ], server_complete_rpc_tag))
- server_send_second_message_event = server_call_driver.event_with_tag(
- server_send_second_message_tag)
- server_complete_rpc_event = server_call_driver.event_with_tag(
- server_complete_rpc_tag)
- server_call_driver.events()
-
- client_recieve_initial_metadata_event = client_receive_initial_metadata_event_future.result(
- )
-
- client_receive_first_message_tag = 'client_receive_first_message_tag'
- client_call.operate([
- cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),
- ], client_receive_first_message_tag)
- client_receive_first_message_event = client_call.next_event()
-
- client_call_cancel_result = client_call.cancel(
- cygrpc.StatusCode.cancelled, 'Cancelled during test!')
- client_complete_rpc_event = client_call.next_event()
-
- channel.close(cygrpc.StatusCode.unknown, 'Channel closed!')
- server.shutdown(server_completion_queue, server_shutdown_tag)
- server.cancel_all_calls()
- server_driver.events()
-
- self.assertEqual(cygrpc.CallError.ok, request_call_result)
- self.assertEqual(cygrpc.CallError.ok,
- server_send_initial_metadata_start_batch_result)
- self.assertIs(server_rpc_tag, server_rpc_event.tag)
- self.assertEqual(cygrpc.CompletionType.operation_complete,
- server_rpc_event.completion_type)
- self.assertIsInstance(server_rpc_event.call, cygrpc.Call)
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_server_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_server_test.py
deleted file mode 100644
index 60b068243c0..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/_server_test.py
+++ /dev/null
@@ -1,49 +0,0 @@
-# Copyright 2017 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Test servers at the level of the Cython API."""
-
-import threading
-import time
-import unittest
-
-from grpc._cython import cygrpc
-
-
-class Test(unittest.TestCase):
-
- def test_lonely_server(self):
- server_call_completion_queue = cygrpc.CompletionQueue()
- server_shutdown_completion_queue = cygrpc.CompletionQueue()
- server = cygrpc.Server(None, False)
- server.register_completion_queue(server_call_completion_queue)
- server.register_completion_queue(server_shutdown_completion_queue)
- port = server.add_http2_port(b'[::]:0')
- server.start()
-
- server_request_call_tag = 'server_request_call_tag'
- server_request_call_start_batch_result = server.request_call(
- server_call_completion_queue, server_call_completion_queue,
- server_request_call_tag)
-
- time.sleep(4)
-
- server_shutdown_tag = 'server_shutdown_tag'
- server_shutdown_result = server.shutdown(
- server_shutdown_completion_queue, server_shutdown_tag)
- server_request_call_event = server_call_completion_queue.poll()
- server_shutdown_event = server_shutdown_completion_queue.poll()
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/cygrpc_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/cygrpc_test.py
deleted file mode 100644
index 9021dc08d1e..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/cygrpc_test.py
+++ /dev/null
@@ -1,417 +0,0 @@
-# Copyright 2015 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import platform
-import threading
-import time
-import unittest
-
-from grpc._cython import cygrpc
-
-from tests.unit import resources
-from tests.unit import test_common
-from tests.unit._cython import test_utilities
-
-_SSL_HOST_OVERRIDE = b'foo.test.google.fr'
-_CALL_CREDENTIALS_METADATA_KEY = 'call-creds-key'
-_CALL_CREDENTIALS_METADATA_VALUE = 'call-creds-value'
-_EMPTY_FLAGS = 0
-
-
-def _metadata_plugin(context, callback):
- callback(((
- _CALL_CREDENTIALS_METADATA_KEY,
- _CALL_CREDENTIALS_METADATA_VALUE,
- ),), cygrpc.StatusCode.ok, b'')
-
-
-class TypeSmokeTest(unittest.TestCase):
-
- def testCompletionQueueUpDown(self):
- completion_queue = cygrpc.CompletionQueue()
- del completion_queue
-
- def testServerUpDown(self):
- server = cygrpc.Server(set([(
- b'grpc.so_reuseport',
- 0,
- )]), False)
- del server
-
- def testChannelUpDown(self):
- channel = cygrpc.Channel(b'[::]:0', None, None)
- channel.close(cygrpc.StatusCode.cancelled, 'Test method anyway!')
-
- def test_metadata_plugin_call_credentials_up_down(self):
- cygrpc.MetadataPluginCallCredentials(_metadata_plugin,
- b'test plugin name!')
-
- def testServerStartNoExplicitShutdown(self):
- server = cygrpc.Server([(
- b'grpc.so_reuseport',
- 0,
- )], False)
- completion_queue = cygrpc.CompletionQueue()
- server.register_completion_queue(completion_queue)
- port = server.add_http2_port(b'[::]:0')
- self.assertIsInstance(port, int)
- server.start()
- del server
-
- def testServerStartShutdown(self):
- completion_queue = cygrpc.CompletionQueue()
- server = cygrpc.Server([
- (
- b'grpc.so_reuseport',
- 0,
- ),
- ], False)
- server.add_http2_port(b'[::]:0')
- server.register_completion_queue(completion_queue)
- server.start()
- shutdown_tag = object()
- server.shutdown(completion_queue, shutdown_tag)
- event = completion_queue.poll()
- self.assertEqual(cygrpc.CompletionType.operation_complete,
- event.completion_type)
- self.assertIs(shutdown_tag, event.tag)
- del server
- del completion_queue
-
-
-class ServerClientMixin(object):
-
- def setUpMixin(self, server_credentials, client_credentials, host_override):
- self.server_completion_queue = cygrpc.CompletionQueue()
- self.server = cygrpc.Server([(
- b'grpc.so_reuseport',
- 0,
- )], False)
- self.server.register_completion_queue(self.server_completion_queue)
- if server_credentials:
- self.port = self.server.add_http2_port(b'[::]:0',
- server_credentials)
- else:
- self.port = self.server.add_http2_port(b'[::]:0')
- self.server.start()
- self.client_completion_queue = cygrpc.CompletionQueue()
- if client_credentials:
- client_channel_arguments = ((
- cygrpc.ChannelArgKey.ssl_target_name_override,
- host_override,
- ),)
- self.client_channel = cygrpc.Channel(
- 'localhost:{}'.format(self.port).encode(),
- client_channel_arguments, client_credentials)
- else:
- self.client_channel = cygrpc.Channel(
- 'localhost:{}'.format(self.port).encode(), set(), None)
- if host_override:
- self.host_argument = None # default host
- self.expected_host = host_override
- else:
- # arbitrary host name necessitating no further identification
- self.host_argument = b'hostess'
- self.expected_host = self.host_argument
-
- def tearDownMixin(self):
- self.client_channel.close(cygrpc.StatusCode.ok, 'test being torn down!')
- del self.client_channel
- del self.server
- del self.client_completion_queue
- del self.server_completion_queue
-
- def _perform_queue_operations(self, operations, call, queue, deadline,
- description):
- """Perform the operations with given call, queue, and deadline.
-
- Invocation errors are reported with as an exception with `description`
- in the message. Performs the operations asynchronously, returning a
- future.
- """
-
- def performer():
- tag = object()
- try:
- call_result = call.start_client_batch(operations, tag)
- self.assertEqual(cygrpc.CallError.ok, call_result)
- event = queue.poll(deadline=deadline)
- self.assertEqual(cygrpc.CompletionType.operation_complete,
- event.completion_type)
- self.assertTrue(event.success)
- self.assertIs(tag, event.tag)
- except Exception as error:
- raise Exception("Error in '{}': {}".format(
- description, error.message))
- return event
-
- return test_utilities.SimpleFuture(performer)
-
- def test_echo(self):
- DEADLINE = time.time() + 5
- DEADLINE_TOLERANCE = 0.25
- CLIENT_METADATA_ASCII_KEY = 'key'
- CLIENT_METADATA_ASCII_VALUE = 'val'
- CLIENT_METADATA_BIN_KEY = 'key-bin'
- CLIENT_METADATA_BIN_VALUE = b'\0' * 1000
- SERVER_INITIAL_METADATA_KEY = 'init_me_me_me'
- SERVER_INITIAL_METADATA_VALUE = 'whodawha?'
- SERVER_TRAILING_METADATA_KEY = 'california_is_in_a_drought'
- SERVER_TRAILING_METADATA_VALUE = 'zomg it is'
- SERVER_STATUS_CODE = cygrpc.StatusCode.ok
- SERVER_STATUS_DETAILS = 'our work is never over'
- REQUEST = b'in death a member of project mayhem has a name'
- RESPONSE = b'his name is robert paulson'
- METHOD = b'twinkies'
-
- server_request_tag = object()
- request_call_result = self.server.request_call(
- self.server_completion_queue, self.server_completion_queue,
- server_request_tag)
-
- self.assertEqual(cygrpc.CallError.ok, request_call_result)
-
- client_call_tag = object()
- client_initial_metadata = (
- (
- CLIENT_METADATA_ASCII_KEY,
- CLIENT_METADATA_ASCII_VALUE,
- ),
- (
- CLIENT_METADATA_BIN_KEY,
- CLIENT_METADATA_BIN_VALUE,
- ),
- )
- client_call = self.client_channel.integrated_call(
- 0, METHOD, self.host_argument, DEADLINE, client_initial_metadata,
- None, [
- (
- [
- cygrpc.SendInitialMetadataOperation(
- client_initial_metadata, _EMPTY_FLAGS),
- cygrpc.SendMessageOperation(REQUEST, _EMPTY_FLAGS),
- cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS),
- cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),
- cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),
- cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),
- ],
- client_call_tag,
- ),
- ])
- client_event_future = test_utilities.SimpleFuture(
- self.client_channel.next_call_event)
-
- request_event = self.server_completion_queue.poll(deadline=DEADLINE)
- self.assertEqual(cygrpc.CompletionType.operation_complete,
- request_event.completion_type)
- self.assertIsInstance(request_event.call, cygrpc.Call)
- self.assertIs(server_request_tag, request_event.tag)
- self.assertTrue(
- test_common.metadata_transmitted(client_initial_metadata,
- request_event.invocation_metadata))
- self.assertEqual(METHOD, request_event.call_details.method)
- self.assertEqual(self.expected_host, request_event.call_details.host)
- self.assertLess(abs(DEADLINE - request_event.call_details.deadline),
- DEADLINE_TOLERANCE)
-
- server_call_tag = object()
- server_call = request_event.call
- server_initial_metadata = ((
- SERVER_INITIAL_METADATA_KEY,
- SERVER_INITIAL_METADATA_VALUE,
- ),)
- server_trailing_metadata = ((
- SERVER_TRAILING_METADATA_KEY,
- SERVER_TRAILING_METADATA_VALUE,
- ),)
- server_start_batch_result = server_call.start_server_batch([
- cygrpc.SendInitialMetadataOperation(server_initial_metadata,
- _EMPTY_FLAGS),
- cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),
- cygrpc.SendMessageOperation(RESPONSE, _EMPTY_FLAGS),
- cygrpc.ReceiveCloseOnServerOperation(_EMPTY_FLAGS),
- cygrpc.SendStatusFromServerOperation(
- server_trailing_metadata, SERVER_STATUS_CODE,
- SERVER_STATUS_DETAILS, _EMPTY_FLAGS)
- ], server_call_tag)
- self.assertEqual(cygrpc.CallError.ok, server_start_batch_result)
-
- server_event = self.server_completion_queue.poll(deadline=DEADLINE)
- client_event = client_event_future.result()
-
- self.assertEqual(6, len(client_event.batch_operations))
- found_client_op_types = set()
- for client_result in client_event.batch_operations:
- # we expect each op type to be unique
- self.assertNotIn(client_result.type(), found_client_op_types)
- found_client_op_types.add(client_result.type())
- if client_result.type(
- ) == cygrpc.OperationType.receive_initial_metadata:
- self.assertTrue(
- test_common.metadata_transmitted(
- server_initial_metadata,
- client_result.initial_metadata()))
- elif client_result.type() == cygrpc.OperationType.receive_message:
- self.assertEqual(RESPONSE, client_result.message())
- elif client_result.type(
- ) == cygrpc.OperationType.receive_status_on_client:
- self.assertTrue(
- test_common.metadata_transmitted(
- server_trailing_metadata,
- client_result.trailing_metadata()))
- self.assertEqual(SERVER_STATUS_DETAILS, client_result.details())
- self.assertEqual(SERVER_STATUS_CODE, client_result.code())
- self.assertEqual(
- set([
- cygrpc.OperationType.send_initial_metadata,
- cygrpc.OperationType.send_message,
- cygrpc.OperationType.send_close_from_client,
- cygrpc.OperationType.receive_initial_metadata,
- cygrpc.OperationType.receive_message,
- cygrpc.OperationType.receive_status_on_client
- ]), found_client_op_types)
-
- self.assertEqual(5, len(server_event.batch_operations))
- found_server_op_types = set()
- for server_result in server_event.batch_operations:
- self.assertNotIn(server_result.type(), found_server_op_types)
- found_server_op_types.add(server_result.type())
- if server_result.type() == cygrpc.OperationType.receive_message:
- self.assertEqual(REQUEST, server_result.message())
- elif server_result.type(
- ) == cygrpc.OperationType.receive_close_on_server:
- self.assertFalse(server_result.cancelled())
- self.assertEqual(
- set([
- cygrpc.OperationType.send_initial_metadata,
- cygrpc.OperationType.receive_message,
- cygrpc.OperationType.send_message,
- cygrpc.OperationType.receive_close_on_server,
- cygrpc.OperationType.send_status_from_server
- ]), found_server_op_types)
-
- del client_call
- del server_call
-
- def test_6522(self):
- DEADLINE = time.time() + 5
- DEADLINE_TOLERANCE = 0.25
- METHOD = b'twinkies'
-
- empty_metadata = ()
-
- # Prologue
- server_request_tag = object()
- self.server.request_call(self.server_completion_queue,
- self.server_completion_queue,
- server_request_tag)
- client_call = self.client_channel.segregated_call(
- 0, METHOD, self.host_argument, DEADLINE, None, None,
- ([(
- [
- cygrpc.SendInitialMetadataOperation(empty_metadata,
- _EMPTY_FLAGS),
- cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),
- ],
- object(),
- ),
- (
- [
- cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),
- ],
- object(),
- )]))
-
- client_initial_metadata_event_future = test_utilities.SimpleFuture(
- client_call.next_event)
-
- request_event = self.server_completion_queue.poll(deadline=DEADLINE)
- server_call = request_event.call
-
- def perform_server_operations(operations, description):
- return self._perform_queue_operations(operations, server_call,
- self.server_completion_queue,
- DEADLINE, description)
-
- server_event_future = perform_server_operations([
- cygrpc.SendInitialMetadataOperation(empty_metadata, _EMPTY_FLAGS),
- ], "Server prologue")
-
- client_initial_metadata_event_future.result() # force completion
- server_event_future.result()
-
- # Messaging
- for _ in range(10):
- client_call.operate([
- cygrpc.SendMessageOperation(b'', _EMPTY_FLAGS),
- cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),
- ], "Client message")
- client_message_event_future = test_utilities.SimpleFuture(
- client_call.next_event)
- server_event_future = perform_server_operations([
- cygrpc.SendMessageOperation(b'', _EMPTY_FLAGS),
- cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),
- ], "Server receive")
-
- client_message_event_future.result() # force completion
- server_event_future.result()
-
- # Epilogue
- client_call.operate([
- cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS),
- ], "Client epilogue")
- # One for ReceiveStatusOnClient, one for SendCloseFromClient.
- client_events_future = test_utilities.SimpleFuture(lambda: {
- client_call.next_event(),
- client_call.next_event(),
- })
-
- server_event_future = perform_server_operations([
- cygrpc.ReceiveCloseOnServerOperation(_EMPTY_FLAGS),
- cygrpc.SendStatusFromServerOperation(
- empty_metadata, cygrpc.StatusCode.ok, b'', _EMPTY_FLAGS)
- ], "Server epilogue")
-
- client_events_future.result() # force completion
- server_event_future.result()
-
-
-class InsecureServerInsecureClient(unittest.TestCase, ServerClientMixin):
-
- def setUp(self):
- self.setUpMixin(None, None, None)
-
- def tearDown(self):
- self.tearDownMixin()
-
-
-class SecureServerSecureClient(unittest.TestCase, ServerClientMixin):
-
- def setUp(self):
- server_credentials = cygrpc.server_credentials_ssl(
- None, [
- cygrpc.SslPemKeyCertPair(resources.private_key(),
- resources.certificate_chain())
- ], False)
- client_credentials = cygrpc.SSLChannelCredentials(
- resources.test_root_certificates(), None, None)
- self.setUpMixin(server_credentials, client_credentials,
- _SSL_HOST_OVERRIDE)
-
- def tearDown(self):
- self.tearDownMixin()
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/test_utilities.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/test_utilities.py
deleted file mode 100644
index 7d5eaaaa842..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_cython/test_utilities.py
+++ /dev/null
@@ -1,52 +0,0 @@
-# Copyright 2015 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import threading
-
-from grpc._cython import cygrpc
-
-
-class SimpleFuture(object):
- """A simple future mechanism."""
-
- def __init__(self, function, *args, **kwargs):
-
- def wrapped_function():
- try:
- self._result = function(*args, **kwargs)
- except Exception as error: # pylint: disable=broad-except
- self._error = error
-
- self._result = None
- self._error = None
- self._thread = threading.Thread(target=wrapped_function)
- self._thread.start()
-
- def result(self):
- """The resulting value of this future.
-
- Re-raises any exceptions.
- """
- self._thread.join()
- if self._error:
- # TODO(atash): re-raise exceptions in a way that preserves tracebacks
- raise self._error # pylint: disable=raising-bad-type
- return self._result
-
-
-class CompletionQueuePollFuture(SimpleFuture):
-
- def __init__(self, completion_queue, deadline):
- super(CompletionQueuePollFuture,
- self).__init__(lambda: completion_queue.poll(deadline=deadline))
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_dns_resolver_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_dns_resolver_test.py
deleted file mode 100644
index cc89dea1efa..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_dns_resolver_test.py
+++ /dev/null
@@ -1,68 +0,0 @@
-# Copyright 2019 The gRPC Authors
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Tests for an actual dns resolution."""
-
-import logging
-import unittest
-
-import grpc
-import six
-
-from tests.unit import test_common
-from tests.unit.framework.common import test_constants
-
-_METHOD = '/ANY/METHOD'
-_REQUEST = b'\x00\x00\x00'
-_RESPONSE = _REQUEST
-
-
-class GenericHandler(grpc.GenericRpcHandler):
-
- def service(self, unused_handler_details):
- return grpc.unary_unary_rpc_method_handler(
- lambda request, unused_context: request,
- )
-
-
-class DNSResolverTest(unittest.TestCase):
-
- def setUp(self):
- self._server = test_common.test_server()
- self._server.add_generic_rpc_handlers((GenericHandler(),))
- self._port = self._server.add_insecure_port('[::]:0')
- self._server.start()
-
- def tearDown(self):
- self._server.stop(None)
-
- def test_connect_loopback(self):
- # NOTE(https://github.com/grpc/grpc/issues/18422)
- # In short, Gevent + C-Ares = Segfault. The C-Ares driver is not
- # supported by custom io manager like "gevent"
- # NOTE(b/201064791): use loopback46.unittest.grpc.io since
- # it returns the expected responses even when DNS64 dns servers
- # are used on the test worker (and for purposes of this
- # test the use of loopback4 vs loopback46 makes no difference).
- with grpc.insecure_channel('loopback46.unittest.grpc.io:%d' %
- self._port) as channel:
- self.assertEqual(
- channel.unary_unary(_METHOD)(
- _REQUEST,
- timeout=test_constants.SHORT_TIMEOUT,
- ), _RESPONSE)
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_dynamic_stubs_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_dynamic_stubs_test.py
deleted file mode 100644
index e505c563d89..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_dynamic_stubs_test.py
+++ /dev/null
@@ -1,147 +0,0 @@
-# Copyright 2019 The gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Test of dynamic stub import API."""
-
-import contextlib
-import functools
-import logging
-import multiprocessing
-import os
-import sys
-import unittest
-
-from tests.unit import test_common
-
-_DATA_DIR = os.path.join("tests", "unit", "data")
-
-
-@contextlib.contextmanager
-def _grpc_tools_unimportable():
- original_sys_path = sys.path
- sys.path = [path for path in sys.path if "grpcio_tools" not in path]
- try:
- import grpc_tools
- except ImportError:
- pass
- else:
- del grpc_tools
- sys.path = original_sys_path
- raise unittest.SkipTest("Failed to make grpc_tools unimportable.")
- try:
- yield
- finally:
- sys.path = original_sys_path
-
-
-def _collect_errors(fn):
-
- @functools.wraps(fn)
- def _wrapped(error_queue):
- try:
- fn()
- except Exception as e:
- error_queue.put(e)
- raise
-
- return _wrapped
-
-
-def _python3_check(fn):
-
- @functools.wraps(fn)
- def _wrapped():
- if sys.version_info[0] == 3:
- fn()
- else:
- _assert_unimplemented("Python 3")
-
- return _wrapped
-
-
-def _run_in_subprocess(test_case):
- sys.path.insert(
- 0, os.path.join(os.path.realpath(os.path.dirname(__file__)), ".."))
- error_queue = multiprocessing.Queue()
- proc = multiprocessing.Process(target=test_case, args=(error_queue,))
- proc.start()
- proc.join()
- sys.path.pop(0)
- if not error_queue.empty():
- raise error_queue.get()
- assert proc.exitcode == 0, "Process exited with code {}".format(
- proc.exitcode)
-
-
-def _assert_unimplemented(msg_substr):
- import grpc
- try:
- protos, services = grpc.protos_and_services(
- "tests/unit/data/foo/bar.proto")
- except NotImplementedError as e:
- assert msg_substr in str(e), "{} was not in '{}'".format(
- msg_substr, str(e))
- else:
- assert False, "Did not raise NotImplementedError"
-
-
-@_collect_errors
-@_python3_check
-def _test_sunny_day():
- import grpc
- protos, services = grpc.protos_and_services(
- os.path.join(_DATA_DIR, "foo", "bar.proto"))
- assert protos.BarMessage is not None
- assert services.BarStub is not None
-
-
-@_collect_errors
-@_python3_check
-def _test_well_known_types():
- import grpc
- protos, services = grpc.protos_and_services(
- os.path.join(_DATA_DIR, "foo", "bar_with_wkt.proto"))
- assert protos.BarMessage is not None
- assert services.BarStub is not None
-
-
-@_collect_errors
-@_python3_check
-def _test_grpc_tools_unimportable():
- with _grpc_tools_unimportable():
- _assert_unimplemented("grpcio-tools")
-
-
-# NOTE(rbellevi): multiprocessing.Process fails to pickle function objects
-# when they do not come from the "__main__" module, so this test passes
-# if run directly on Windows, but not if started by the test runner.
-@unittest.skipIf(os.name == "nt", "Windows multiprocessing unsupported")
-@unittest.skipIf(test_common.running_under_gevent(),
- "Import paths do not work with gevent runner.")
-class DynamicStubTest(unittest.TestCase):
-
- @unittest.skip('grpcio-tools package required')
- def test_sunny_day(self):
- _run_in_subprocess(_test_sunny_day)
-
- @unittest.skip('grpcio-tools package required')
- def test_well_known_types(self):
- _run_in_subprocess(_test_well_known_types)
-
- def test_grpc_tools_unimportable(self):
- _run_in_subprocess(_test_grpc_tools_unimportable)
-
-
-if __name__ == "__main__":
- logging.basicConfig()
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_empty_message_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_empty_message_test.py
deleted file mode 100644
index 918dbe73d1a..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_empty_message_test.py
+++ /dev/null
@@ -1,124 +0,0 @@
-# Copyright 2016 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import logging
-import unittest
-
-import grpc
-
-from tests.unit import test_common
-from tests.unit.framework.common import test_constants
-
-_REQUEST = b''
-_RESPONSE = b''
-
-_UNARY_UNARY = '/test/UnaryUnary'
-_UNARY_STREAM = '/test/UnaryStream'
-_STREAM_UNARY = '/test/StreamUnary'
-_STREAM_STREAM = '/test/StreamStream'
-
-
-def handle_unary_unary(request, servicer_context):
- return _RESPONSE
-
-
-def handle_unary_stream(request, servicer_context):
- for _ in range(test_constants.STREAM_LENGTH):
- yield _RESPONSE
-
-
-def handle_stream_unary(request_iterator, servicer_context):
- for request in request_iterator:
- pass
- return _RESPONSE
-
-
-def handle_stream_stream(request_iterator, servicer_context):
- for request in request_iterator:
- yield _RESPONSE
-
-
-class _MethodHandler(grpc.RpcMethodHandler):
-
- def __init__(self, request_streaming, response_streaming):
- self.request_streaming = request_streaming
- self.response_streaming = response_streaming
- self.request_deserializer = None
- self.response_serializer = None
- self.unary_unary = None
- self.unary_stream = None
- self.stream_unary = None
- self.stream_stream = None
- if self.request_streaming and self.response_streaming:
- self.stream_stream = handle_stream_stream
- elif self.request_streaming:
- self.stream_unary = handle_stream_unary
- elif self.response_streaming:
- self.unary_stream = handle_unary_stream
- else:
- self.unary_unary = handle_unary_unary
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def service(self, handler_call_details):
- if handler_call_details.method == _UNARY_UNARY:
- return _MethodHandler(False, False)
- elif handler_call_details.method == _UNARY_STREAM:
- return _MethodHandler(False, True)
- elif handler_call_details.method == _STREAM_UNARY:
- return _MethodHandler(True, False)
- elif handler_call_details.method == _STREAM_STREAM:
- return _MethodHandler(True, True)
- else:
- return None
-
-
-class EmptyMessageTest(unittest.TestCase):
-
- def setUp(self):
- self._server = test_common.test_server()
- self._server.add_generic_rpc_handlers((_GenericHandler(),))
- port = self._server.add_insecure_port('[::]:0')
- self._server.start()
- self._channel = grpc.insecure_channel('localhost:%d' % port)
-
- def tearDown(self):
- self._server.stop(0)
- self._channel.close()
-
- def testUnaryUnary(self):
- response = self._channel.unary_unary(_UNARY_UNARY)(_REQUEST)
- self.assertEqual(_RESPONSE, response)
-
- def testUnaryStream(self):
- response_iterator = self._channel.unary_stream(_UNARY_STREAM)(_REQUEST)
- self.assertSequenceEqual([_RESPONSE] * test_constants.STREAM_LENGTH,
- list(response_iterator))
-
- def testStreamUnary(self):
- response = self._channel.stream_unary(_STREAM_UNARY)(iter(
- [_REQUEST] * test_constants.STREAM_LENGTH))
- self.assertEqual(_RESPONSE, response)
-
- def testStreamStream(self):
- response_iterator = self._channel.stream_stream(_STREAM_STREAM)(iter(
- [_REQUEST] * test_constants.STREAM_LENGTH))
- self.assertSequenceEqual([_RESPONSE] * test_constants.STREAM_LENGTH,
- list(response_iterator))
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_error_message_encoding_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_error_message_encoding_test.py
deleted file mode 100644
index e58007ad3ed..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_error_message_encoding_test.py
+++ /dev/null
@@ -1,87 +0,0 @@
-# Copyright 2018 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Tests 'utf-8' encoded error message."""
-
-import unittest
-import weakref
-
-import grpc
-
-from tests.unit import test_common
-from tests.unit.framework.common import test_constants
-
-_UNICODE_ERROR_MESSAGES = [
- b'\xe2\x80\x9d'.decode('utf-8'),
- b'abc\x80\xd0\xaf'.decode('latin-1'),
- b'\xc3\xa9'.decode('utf-8'),
-]
-
-_REQUEST = b'\x00\x00\x00'
-_RESPONSE = b'\x00\x00\x00'
-
-_UNARY_UNARY = '/test/UnaryUnary'
-
-
-class _MethodHandler(grpc.RpcMethodHandler):
-
- def __init__(self, request_streaming=None, response_streaming=None):
- self.request_streaming = request_streaming
- self.response_streaming = response_streaming
- self.request_deserializer = None
- self.response_serializer = None
- self.unary_stream = None
- self.stream_unary = None
- self.stream_stream = None
-
- def unary_unary(self, request, servicer_context):
- servicer_context.set_code(grpc.StatusCode.UNKNOWN)
- servicer_context.set_details(request.decode('utf-8'))
- return _RESPONSE
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def __init__(self, test):
- self._test = test
-
- def service(self, handler_call_details):
- return _MethodHandler()
-
-
-class ErrorMessageEncodingTest(unittest.TestCase):
-
- def setUp(self):
- self._server = test_common.test_server()
- self._server.add_generic_rpc_handlers(
- (_GenericHandler(weakref.proxy(self)),))
- port = self._server.add_insecure_port('[::]:0')
- self._server.start()
- self._channel = grpc.insecure_channel('localhost:%d' % port)
-
- def tearDown(self):
- self._server.stop(0)
- self._channel.close()
-
- def testMessageEncoding(self):
- for message in _UNICODE_ERROR_MESSAGES:
- multi_callable = self._channel.unary_unary(_UNARY_UNARY)
- with self.assertRaises(grpc.RpcError) as cm:
- multi_callable(message.encode('utf-8'))
-
- self.assertEqual(cm.exception.code(), grpc.StatusCode.UNKNOWN)
- self.assertEqual(cm.exception.details(), message)
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_exit_scenarios.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_exit_scenarios.py
deleted file mode 100644
index 301afb6c27c..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_exit_scenarios.py
+++ /dev/null
@@ -1,236 +0,0 @@
-# Copyright 2016 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Defines a number of module-scope gRPC scenarios to test clean exit."""
-
-import argparse
-import logging
-import threading
-import time
-
-import grpc
-
-from tests.unit.framework.common import test_constants
-
-WAIT_TIME = 1000
-
-REQUEST = b'request'
-
-UNSTARTED_SERVER = 'unstarted_server'
-RUNNING_SERVER = 'running_server'
-POLL_CONNECTIVITY_NO_SERVER = 'poll_connectivity_no_server'
-POLL_CONNECTIVITY = 'poll_connectivity'
-IN_FLIGHT_UNARY_UNARY_CALL = 'in_flight_unary_unary_call'
-IN_FLIGHT_UNARY_STREAM_CALL = 'in_flight_unary_stream_call'
-IN_FLIGHT_STREAM_UNARY_CALL = 'in_flight_stream_unary_call'
-IN_FLIGHT_STREAM_STREAM_CALL = 'in_flight_stream_stream_call'
-IN_FLIGHT_PARTIAL_UNARY_STREAM_CALL = 'in_flight_partial_unary_stream_call'
-IN_FLIGHT_PARTIAL_STREAM_UNARY_CALL = 'in_flight_partial_stream_unary_call'
-IN_FLIGHT_PARTIAL_STREAM_STREAM_CALL = 'in_flight_partial_stream_stream_call'
-
-UNARY_UNARY = b'/test/UnaryUnary'
-UNARY_STREAM = b'/test/UnaryStream'
-STREAM_UNARY = b'/test/StreamUnary'
-STREAM_STREAM = b'/test/StreamStream'
-PARTIAL_UNARY_STREAM = b'/test/PartialUnaryStream'
-PARTIAL_STREAM_UNARY = b'/test/PartialStreamUnary'
-PARTIAL_STREAM_STREAM = b'/test/PartialStreamStream'
-
-TEST_TO_METHOD = {
- IN_FLIGHT_UNARY_UNARY_CALL: UNARY_UNARY,
- IN_FLIGHT_UNARY_STREAM_CALL: UNARY_STREAM,
- IN_FLIGHT_STREAM_UNARY_CALL: STREAM_UNARY,
- IN_FLIGHT_STREAM_STREAM_CALL: STREAM_STREAM,
- IN_FLIGHT_PARTIAL_UNARY_STREAM_CALL: PARTIAL_UNARY_STREAM,
- IN_FLIGHT_PARTIAL_STREAM_UNARY_CALL: PARTIAL_STREAM_UNARY,
- IN_FLIGHT_PARTIAL_STREAM_STREAM_CALL: PARTIAL_STREAM_STREAM,
-}
-
-
-def hang_unary_unary(request, servicer_context):
- time.sleep(WAIT_TIME)
-
-
-def hang_unary_stream(request, servicer_context):
- time.sleep(WAIT_TIME)
-
-
-def hang_partial_unary_stream(request, servicer_context):
- for _ in range(test_constants.STREAM_LENGTH // 2):
- yield request
- time.sleep(WAIT_TIME)
-
-
-def hang_stream_unary(request_iterator, servicer_context):
- time.sleep(WAIT_TIME)
-
-
-def hang_partial_stream_unary(request_iterator, servicer_context):
- for _ in range(test_constants.STREAM_LENGTH // 2):
- next(request_iterator)
- time.sleep(WAIT_TIME)
-
-
-def hang_stream_stream(request_iterator, servicer_context):
- time.sleep(WAIT_TIME)
-
-
-def hang_partial_stream_stream(request_iterator, servicer_context):
- for _ in range(test_constants.STREAM_LENGTH // 2):
- yield next(request_iterator) #pylint: disable=stop-iteration-return
- time.sleep(WAIT_TIME)
-
-
-class MethodHandler(grpc.RpcMethodHandler):
-
- def __init__(self, request_streaming, response_streaming, partial_hang):
- self.request_streaming = request_streaming
- self.response_streaming = response_streaming
- self.request_deserializer = None
- self.response_serializer = None
- self.unary_unary = None
- self.unary_stream = None
- self.stream_unary = None
- self.stream_stream = None
- if self.request_streaming and self.response_streaming:
- if partial_hang:
- self.stream_stream = hang_partial_stream_stream
- else:
- self.stream_stream = hang_stream_stream
- elif self.request_streaming:
- if partial_hang:
- self.stream_unary = hang_partial_stream_unary
- else:
- self.stream_unary = hang_stream_unary
- elif self.response_streaming:
- if partial_hang:
- self.unary_stream = hang_partial_unary_stream
- else:
- self.unary_stream = hang_unary_stream
- else:
- self.unary_unary = hang_unary_unary
-
-
-class GenericHandler(grpc.GenericRpcHandler):
-
- def service(self, handler_call_details):
- if handler_call_details.method == UNARY_UNARY:
- return MethodHandler(False, False, False)
- elif handler_call_details.method == UNARY_STREAM:
- return MethodHandler(False, True, False)
- elif handler_call_details.method == STREAM_UNARY:
- return MethodHandler(True, False, False)
- elif handler_call_details.method == STREAM_STREAM:
- return MethodHandler(True, True, False)
- elif handler_call_details.method == PARTIAL_UNARY_STREAM:
- return MethodHandler(False, True, True)
- elif handler_call_details.method == PARTIAL_STREAM_UNARY:
- return MethodHandler(True, False, True)
- elif handler_call_details.method == PARTIAL_STREAM_STREAM:
- return MethodHandler(True, True, True)
- else:
- return None
-
-
-# Traditional executors will not exit until all their
-# current jobs complete. Because we submit jobs that will
-# never finish, we don't want to block exit on these jobs.
-class DaemonPool(object):
-
- def submit(self, fn, *args, **kwargs):
- thread = threading.Thread(target=fn, args=args, kwargs=kwargs)
- thread.daemon = True
- thread.start()
-
- def shutdown(self, wait=True):
- pass
-
-
-def infinite_request_iterator():
- while True:
- yield REQUEST
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- parser = argparse.ArgumentParser()
- parser.add_argument('scenario', type=str)
- parser.add_argument('--wait_for_interrupt',
- dest='wait_for_interrupt',
- action='store_true')
- args = parser.parse_args()
-
- if args.scenario == UNSTARTED_SERVER:
- server = grpc.server(DaemonPool(), options=(('grpc.so_reuseport', 0),))
- if args.wait_for_interrupt:
- time.sleep(WAIT_TIME)
- elif args.scenario == RUNNING_SERVER:
- server = grpc.server(DaemonPool(), options=(('grpc.so_reuseport', 0),))
- port = server.add_insecure_port('[::]:0')
- server.start()
- if args.wait_for_interrupt:
- time.sleep(WAIT_TIME)
- elif args.scenario == POLL_CONNECTIVITY_NO_SERVER:
- channel = grpc.insecure_channel('localhost:12345')
-
- def connectivity_callback(connectivity):
- pass
-
- channel.subscribe(connectivity_callback, try_to_connect=True)
- if args.wait_for_interrupt:
- time.sleep(WAIT_TIME)
- elif args.scenario == POLL_CONNECTIVITY:
- server = grpc.server(DaemonPool(), options=(('grpc.so_reuseport', 0),))
- port = server.add_insecure_port('[::]:0')
- server.start()
- channel = grpc.insecure_channel('localhost:%d' % port)
-
- def connectivity_callback(connectivity):
- pass
-
- channel.subscribe(connectivity_callback, try_to_connect=True)
- if args.wait_for_interrupt:
- time.sleep(WAIT_TIME)
-
- else:
- handler = GenericHandler()
- server = grpc.server(DaemonPool(), options=(('grpc.so_reuseport', 0),))
- port = server.add_insecure_port('[::]:0')
- server.add_generic_rpc_handlers((handler,))
- server.start()
- channel = grpc.insecure_channel('localhost:%d' % port)
-
- method = TEST_TO_METHOD[args.scenario]
-
- if args.scenario == IN_FLIGHT_UNARY_UNARY_CALL:
- multi_callable = channel.unary_unary(method)
- future = multi_callable.future(REQUEST)
- result, call = multi_callable.with_call(REQUEST)
- elif (args.scenario == IN_FLIGHT_UNARY_STREAM_CALL or
- args.scenario == IN_FLIGHT_PARTIAL_UNARY_STREAM_CALL):
- multi_callable = channel.unary_stream(method)
- response_iterator = multi_callable(REQUEST)
- for response in response_iterator:
- pass
- elif (args.scenario == IN_FLIGHT_STREAM_UNARY_CALL or
- args.scenario == IN_FLIGHT_PARTIAL_STREAM_UNARY_CALL):
- multi_callable = channel.stream_unary(method)
- future = multi_callable.future(infinite_request_iterator())
- result, call = multi_callable.with_call(
- iter([REQUEST] * test_constants.STREAM_LENGTH))
- elif (args.scenario == IN_FLIGHT_STREAM_STREAM_CALL or
- args.scenario == IN_FLIGHT_PARTIAL_STREAM_STREAM_CALL):
- multi_callable = channel.stream_stream(method)
- response_iterator = multi_callable(infinite_request_iterator())
- for response in response_iterator:
- pass
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_exit_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_exit_test.py
deleted file mode 100644
index eaf32278898..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_exit_test.py
+++ /dev/null
@@ -1,262 +0,0 @@
-# Copyright 2016 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Tests clean exit of server/client on Python Interpreter exit/sigint.
-
-The tests in this module spawn a subprocess for each test case, the
-test is considered successful if it doesn't freeze/timeout.
-"""
-
-import atexit
-import datetime
-import logging
-import os
-import signal
-import subprocess
-import sys
-import threading
-import time
-import unittest
-
-import six
-
-from tests.unit import _exit_scenarios
-
-# SCENARIO_FILE = os.path.abspath(
-# os.path.join(os.path.dirname(os.path.realpath(__file__)),
-# '_exit_scenarios.py'))
-INTERPRETER = sys.executable
-BASE_COMMAND = [INTERPRETER, '-m', 'tests.unit._exit_scenarios']
-BASE_SIGTERM_COMMAND = BASE_COMMAND + ['--wait_for_interrupt']
-
-INIT_TIME = datetime.timedelta(seconds=1)
-WAIT_CHECK_INTERVAL = datetime.timedelta(milliseconds=100)
-WAIT_CHECK_DEFAULT_TIMEOUT = datetime.timedelta(seconds=5)
-
-processes = []
-process_lock = threading.Lock()
-
-
-# Make sure we attempt to clean up any
-# processes we may have left running
-def cleanup_processes():
- with process_lock:
- for process in processes:
- try:
- process.kill()
- except Exception: # pylint: disable=broad-except
- pass
-
-
-atexit.register(cleanup_processes)
-
-
-def _process_wait_with_timeout(process, timeout=WAIT_CHECK_DEFAULT_TIMEOUT):
- """A funciton to mimic 3.3+ only timeout argument in process.wait."""
- deadline = datetime.datetime.now() + timeout
- while (process.poll() is None) and (datetime.datetime.now() < deadline):
- time.sleep(WAIT_CHECK_INTERVAL.total_seconds())
- if process.returncode is None:
- raise RuntimeError('Process failed to exit within %s' % timeout)
-
-
-def interrupt_and_wait(process):
- with process_lock:
- processes.append(process)
- time.sleep(INIT_TIME.total_seconds())
- os.kill(process.pid, signal.SIGINT)
- _process_wait_with_timeout(process)
-
-
-def wait(process):
- with process_lock:
- processes.append(process)
- _process_wait_with_timeout(process)
-
-
-# TODO(lidiz) enable exit tests once the root cause found.
-@unittest.skip('https://github.com/grpc/grpc/issues/23982')
-@unittest.skip('https://github.com/grpc/grpc/issues/23028')
-class ExitTest(unittest.TestCase):
-
- def test_unstarted_server(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(BASE_COMMAND +
- [_exit_scenarios.UNSTARTED_SERVER],
- stdout=sys.stdout,
- stderr=sys.stderr,
- env=env)
- wait(process)
-
- def test_unstarted_server_terminate(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(BASE_SIGTERM_COMMAND +
- [_exit_scenarios.UNSTARTED_SERVER],
- stdout=sys.stdout,
- env=env)
- interrupt_and_wait(process)
-
- def test_running_server(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(BASE_COMMAND +
- [_exit_scenarios.RUNNING_SERVER],
- stdout=sys.stdout,
- stderr=sys.stderr,
- env=env)
- wait(process)
-
- def test_running_server_terminate(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(BASE_SIGTERM_COMMAND +
- [_exit_scenarios.RUNNING_SERVER],
- stdout=sys.stdout,
- stderr=sys.stderr,
- env=env)
- interrupt_and_wait(process)
-
- def test_poll_connectivity_no_server(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(
- BASE_COMMAND + [_exit_scenarios.POLL_CONNECTIVITY_NO_SERVER],
- stdout=sys.stdout,
- stderr=sys.stderr,
- env=env)
- wait(process)
-
- def test_poll_connectivity_no_server_terminate(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(
- BASE_SIGTERM_COMMAND +
- [_exit_scenarios.POLL_CONNECTIVITY_NO_SERVER],
- stdout=sys.stdout,
- stderr=sys.stderr,
- env=env)
- interrupt_and_wait(process)
-
- def test_poll_connectivity(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(BASE_COMMAND +
- [_exit_scenarios.POLL_CONNECTIVITY],
- stdout=sys.stdout,
- stderr=sys.stderr,
- env=env)
- wait(process)
-
- def test_poll_connectivity_terminate(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(BASE_SIGTERM_COMMAND +
- [_exit_scenarios.POLL_CONNECTIVITY],
- stdout=sys.stdout,
- stderr=sys.stderr,
- env=env)
- interrupt_and_wait(process)
-
- @unittest.skipIf(os.name == 'nt',
- 'os.kill does not have required permission on Windows')
- def test_in_flight_unary_unary_call(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(BASE_COMMAND +
- [_exit_scenarios.IN_FLIGHT_UNARY_UNARY_CALL],
- stdout=sys.stdout,
- stderr=sys.stderr,
- env=env)
- interrupt_and_wait(process)
-
- @unittest.skipIf(os.name == 'nt',
- 'os.kill does not have required permission on Windows')
- def test_in_flight_unary_stream_call(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(
- BASE_COMMAND + [_exit_scenarios.IN_FLIGHT_UNARY_STREAM_CALL],
- stdout=sys.stdout,
- stderr=sys.stderr,
- env=env)
- interrupt_and_wait(process)
-
- @unittest.skipIf(os.name == 'nt',
- 'os.kill does not have required permission on Windows')
- def test_in_flight_stream_unary_call(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(
- BASE_COMMAND + [_exit_scenarios.IN_FLIGHT_STREAM_UNARY_CALL],
- stdout=sys.stdout,
- stderr=sys.stderr,
- env=env)
- interrupt_and_wait(process)
-
- @unittest.skipIf(os.name == 'nt',
- 'os.kill does not have required permission on Windows')
- def test_in_flight_stream_stream_call(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(
- BASE_COMMAND + [_exit_scenarios.IN_FLIGHT_STREAM_STREAM_CALL],
- stdout=sys.stdout,
- stderr=sys.stderr,
- env=env)
- interrupt_and_wait(process)
-
- @unittest.skipIf(os.name == 'nt',
- 'os.kill does not have required permission on Windows')
- def test_in_flight_partial_unary_stream_call(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(
- BASE_COMMAND +
- [_exit_scenarios.IN_FLIGHT_PARTIAL_UNARY_STREAM_CALL],
- stdout=sys.stdout,
- stderr=sys.stderr,
- env=env)
- interrupt_and_wait(process)
-
- @unittest.skipIf(os.name == 'nt',
- 'os.kill does not have required permission on Windows')
- def test_in_flight_partial_stream_unary_call(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(
- BASE_COMMAND +
- [_exit_scenarios.IN_FLIGHT_PARTIAL_STREAM_UNARY_CALL],
- stdout=sys.stdout,
- stderr=sys.stderr,
- env=env)
- interrupt_and_wait(process)
-
- @unittest.skipIf(os.name == 'nt',
- 'os.kill does not have required permission on Windows')
- def test_in_flight_partial_stream_stream_call(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(
- BASE_COMMAND +
- [_exit_scenarios.IN_FLIGHT_PARTIAL_STREAM_STREAM_CALL],
- stdout=sys.stdout,
- stderr=sys.stderr,
- env=env)
- interrupt_and_wait(process)
-
-
-if __name__ == '__main__':
- logging.basicConfig(level=logging.DEBUG)
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_from_grpc_import_star.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_from_grpc_import_star.py
deleted file mode 100644
index 1ada25382de..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_from_grpc_import_star.py
+++ /dev/null
@@ -1,23 +0,0 @@
-# Copyright 2016 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-_BEFORE_IMPORT = tuple(globals())
-
-from grpc import * # pylint: disable=wildcard-import,unused-wildcard-import
-
-_AFTER_IMPORT = tuple(globals())
-
-GRPC_ELEMENTS = tuple(
- element for element in _AFTER_IMPORT
- if element not in _BEFORE_IMPORT and element != '_BEFORE_IMPORT')
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_grpc_shutdown_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_grpc_shutdown_test.py
deleted file mode 100644
index b1f43e061b0..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_grpc_shutdown_test.py
+++ /dev/null
@@ -1,54 +0,0 @@
-# Copyright 2019 The gRPC Authors
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Tests the gRPC Core shutdown path."""
-
-import datetime
-import threading
-import time
-import unittest
-
-import grpc
-
-_TIMEOUT_FOR_SEGFAULT = datetime.timedelta(seconds=10)
-
-
-class GrpcShutdownTest(unittest.TestCase):
-
- def test_channel_close_with_connectivity_watcher(self):
- """Originated by https://github.com/grpc/grpc/issues/20299.
-
- The grpc_shutdown happens synchronously, but there might be Core object
- references left in Cython which might lead to ABORT or SIGSEGV.
- """
- connection_failed = threading.Event()
-
- def on_state_change(state):
- if state in (grpc.ChannelConnectivity.TRANSIENT_FAILURE,
- grpc.ChannelConnectivity.SHUTDOWN):
- connection_failed.set()
-
- # Connects to an void address, and subscribes state changes
- channel = grpc.insecure_channel("0.1.1.1:12345")
- channel.subscribe(on_state_change, True)
-
- deadline = datetime.datetime.now() + _TIMEOUT_FOR_SEGFAULT
-
- while datetime.datetime.now() < deadline:
- time.sleep(0.1)
- if connection_failed.is_set():
- channel.close()
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_interceptor_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_interceptor_test.py
deleted file mode 100644
index d8f3c90f415..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_interceptor_test.py
+++ /dev/null
@@ -1,708 +0,0 @@
-# Copyright 2017 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Test of gRPC Python interceptors."""
-
-import collections
-from concurrent import futures
-import itertools
-import logging
-import os
-import threading
-import unittest
-
-import grpc
-from grpc.framework.foundation import logging_pool
-
-from tests.unit import test_common
-from tests.unit.framework.common import test_constants
-from tests.unit.framework.common import test_control
-
-_SERIALIZE_REQUEST = lambda bytestring: bytestring * 2
-_DESERIALIZE_REQUEST = lambda bytestring: bytestring[len(bytestring) // 2:]
-_SERIALIZE_RESPONSE = lambda bytestring: bytestring * 3
-_DESERIALIZE_RESPONSE = lambda bytestring: bytestring[:len(bytestring) // 3]
-
-_EXCEPTION_REQUEST = b'\x09\x0a'
-
-_UNARY_UNARY = '/test/UnaryUnary'
-_UNARY_STREAM = '/test/UnaryStream'
-_STREAM_UNARY = '/test/StreamUnary'
-_STREAM_STREAM = '/test/StreamStream'
-
-
-class _ApplicationErrorStandin(Exception):
- pass
-
-
-class _Callback(object):
-
- def __init__(self):
- self._condition = threading.Condition()
- self._value = None
- self._called = False
-
- def __call__(self, value):
- with self._condition:
- self._value = value
- self._called = True
- self._condition.notify_all()
-
- def value(self):
- with self._condition:
- while not self._called:
- self._condition.wait()
- return self._value
-
-
-class _Handler(object):
-
- def __init__(self, control):
- self._control = control
-
- def handle_unary_unary(self, request, servicer_context):
- self._control.control()
- if servicer_context is not None:
- servicer_context.set_trailing_metadata(((
- 'testkey',
- 'testvalue',
- ),))
- if request == _EXCEPTION_REQUEST:
- raise _ApplicationErrorStandin()
- return request
-
- def handle_unary_stream(self, request, servicer_context):
- if request == _EXCEPTION_REQUEST:
- raise _ApplicationErrorStandin()
- for _ in range(test_constants.STREAM_LENGTH):
- self._control.control()
- yield request
- self._control.control()
- if servicer_context is not None:
- servicer_context.set_trailing_metadata(((
- 'testkey',
- 'testvalue',
- ),))
-
- def handle_stream_unary(self, request_iterator, servicer_context):
- if servicer_context is not None:
- servicer_context.invocation_metadata()
- self._control.control()
- response_elements = []
- for request in request_iterator:
- self._control.control()
- response_elements.append(request)
- self._control.control()
- if servicer_context is not None:
- servicer_context.set_trailing_metadata(((
- 'testkey',
- 'testvalue',
- ),))
- if _EXCEPTION_REQUEST in response_elements:
- raise _ApplicationErrorStandin()
- return b''.join(response_elements)
-
- def handle_stream_stream(self, request_iterator, servicer_context):
- self._control.control()
- if servicer_context is not None:
- servicer_context.set_trailing_metadata(((
- 'testkey',
- 'testvalue',
- ),))
- for request in request_iterator:
- if request == _EXCEPTION_REQUEST:
- raise _ApplicationErrorStandin()
- self._control.control()
- yield request
- self._control.control()
-
-
-class _MethodHandler(grpc.RpcMethodHandler):
-
- def __init__(self, request_streaming, response_streaming,
- request_deserializer, response_serializer, unary_unary,
- unary_stream, stream_unary, stream_stream):
- self.request_streaming = request_streaming
- self.response_streaming = response_streaming
- self.request_deserializer = request_deserializer
- self.response_serializer = response_serializer
- self.unary_unary = unary_unary
- self.unary_stream = unary_stream
- self.stream_unary = stream_unary
- self.stream_stream = stream_stream
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def __init__(self, handler):
- self._handler = handler
-
- def service(self, handler_call_details):
- if handler_call_details.method == _UNARY_UNARY:
- return _MethodHandler(False, False, None, None,
- self._handler.handle_unary_unary, None, None,
- None)
- elif handler_call_details.method == _UNARY_STREAM:
- return _MethodHandler(False, True, _DESERIALIZE_REQUEST,
- _SERIALIZE_RESPONSE, None,
- self._handler.handle_unary_stream, None, None)
- elif handler_call_details.method == _STREAM_UNARY:
- return _MethodHandler(True, False, _DESERIALIZE_REQUEST,
- _SERIALIZE_RESPONSE, None, None,
- self._handler.handle_stream_unary, None)
- elif handler_call_details.method == _STREAM_STREAM:
- return _MethodHandler(True, True, None, None, None, None, None,
- self._handler.handle_stream_stream)
- else:
- return None
-
-
-def _unary_unary_multi_callable(channel):
- return channel.unary_unary(_UNARY_UNARY)
-
-
-def _unary_stream_multi_callable(channel):
- return channel.unary_stream(_UNARY_STREAM,
- request_serializer=_SERIALIZE_REQUEST,
- response_deserializer=_DESERIALIZE_RESPONSE)
-
-
-def _stream_unary_multi_callable(channel):
- return channel.stream_unary(_STREAM_UNARY,
- request_serializer=_SERIALIZE_REQUEST,
- response_deserializer=_DESERIALIZE_RESPONSE)
-
-
-def _stream_stream_multi_callable(channel):
- return channel.stream_stream(_STREAM_STREAM)
-
-
-class _ClientCallDetails(
- collections.namedtuple(
- '_ClientCallDetails',
- ('method', 'timeout', 'metadata', 'credentials')),
- grpc.ClientCallDetails):
- pass
-
-
-class _GenericClientInterceptor(grpc.UnaryUnaryClientInterceptor,
- grpc.UnaryStreamClientInterceptor,
- grpc.StreamUnaryClientInterceptor,
- grpc.StreamStreamClientInterceptor):
-
- def __init__(self, interceptor_function):
- self._fn = interceptor_function
-
- def intercept_unary_unary(self, continuation, client_call_details, request):
- new_details, new_request_iterator, postprocess = self._fn(
- client_call_details, iter((request,)), False, False)
- response = continuation(new_details, next(new_request_iterator))
- return postprocess(response) if postprocess else response
-
- def intercept_unary_stream(self, continuation, client_call_details,
- request):
- new_details, new_request_iterator, postprocess = self._fn(
- client_call_details, iter((request,)), False, True)
- response_it = continuation(new_details, new_request_iterator)
- return postprocess(response_it) if postprocess else response_it
-
- def intercept_stream_unary(self, continuation, client_call_details,
- request_iterator):
- new_details, new_request_iterator, postprocess = self._fn(
- client_call_details, request_iterator, True, False)
- response = continuation(new_details, next(new_request_iterator))
- return postprocess(response) if postprocess else response
-
- def intercept_stream_stream(self, continuation, client_call_details,
- request_iterator):
- new_details, new_request_iterator, postprocess = self._fn(
- client_call_details, request_iterator, True, True)
- response_it = continuation(new_details, new_request_iterator)
- return postprocess(response_it) if postprocess else response_it
-
-
-class _LoggingInterceptor(grpc.ServerInterceptor,
- grpc.UnaryUnaryClientInterceptor,
- grpc.UnaryStreamClientInterceptor,
- grpc.StreamUnaryClientInterceptor,
- grpc.StreamStreamClientInterceptor):
-
- def __init__(self, tag, record):
- self.tag = tag
- self.record = record
-
- def intercept_service(self, continuation, handler_call_details):
- self.record.append(self.tag + ':intercept_service')
- return continuation(handler_call_details)
-
- def intercept_unary_unary(self, continuation, client_call_details, request):
- self.record.append(self.tag + ':intercept_unary_unary')
- result = continuation(client_call_details, request)
- assert isinstance(
- result,
- grpc.Call), '{} ({}) is not an instance of grpc.Call'.format(
- result, type(result))
- assert isinstance(
- result,
- grpc.Future), '{} ({}) is not an instance of grpc.Future'.format(
- result, type(result))
- return result
-
- def intercept_unary_stream(self, continuation, client_call_details,
- request):
- self.record.append(self.tag + ':intercept_unary_stream')
- return continuation(client_call_details, request)
-
- def intercept_stream_unary(self, continuation, client_call_details,
- request_iterator):
- self.record.append(self.tag + ':intercept_stream_unary')
- result = continuation(client_call_details, request_iterator)
- assert isinstance(
- result,
- grpc.Call), '{} is not an instance of grpc.Call'.format(result)
- assert isinstance(
- result,
- grpc.Future), '{} is not an instance of grpc.Future'.format(result)
- return result
-
- def intercept_stream_stream(self, continuation, client_call_details,
- request_iterator):
- self.record.append(self.tag + ':intercept_stream_stream')
- return continuation(client_call_details, request_iterator)
-
-
-class _DefectiveClientInterceptor(grpc.UnaryUnaryClientInterceptor):
-
- def intercept_unary_unary(self, ignored_continuation,
- ignored_client_call_details, ignored_request):
- raise test_control.Defect()
-
-
-def _wrap_request_iterator_stream_interceptor(wrapper):
-
- def intercept_call(client_call_details, request_iterator, request_streaming,
- ignored_response_streaming):
- if request_streaming:
- return client_call_details, wrapper(request_iterator), None
- else:
- return client_call_details, request_iterator, None
-
- return _GenericClientInterceptor(intercept_call)
-
-
-def _append_request_header_interceptor(header, value):
-
- def intercept_call(client_call_details, request_iterator,
- ignored_request_streaming, ignored_response_streaming):
- metadata = []
- if client_call_details.metadata:
- metadata = list(client_call_details.metadata)
- metadata.append((
- header,
- value,
- ))
- client_call_details = _ClientCallDetails(
- client_call_details.method, client_call_details.timeout, metadata,
- client_call_details.credentials)
- return client_call_details, request_iterator, None
-
- return _GenericClientInterceptor(intercept_call)
-
-
-class _GenericServerInterceptor(grpc.ServerInterceptor):
-
- def __init__(self, fn):
- self._fn = fn
-
- def intercept_service(self, continuation, handler_call_details):
- return self._fn(continuation, handler_call_details)
-
-
-def _filter_server_interceptor(condition, interceptor):
-
- def intercept_service(continuation, handler_call_details):
- if condition(handler_call_details):
- return interceptor.intercept_service(continuation,
- handler_call_details)
- return continuation(handler_call_details)
-
- return _GenericServerInterceptor(intercept_service)
-
-
-class InterceptorTest(unittest.TestCase):
-
- def setUp(self):
- self._control = test_control.PauseFailControl()
- self._handler = _Handler(self._control)
- self._server_pool = logging_pool.pool(test_constants.THREAD_CONCURRENCY)
-
- self._record = []
- conditional_interceptor = _filter_server_interceptor(
- lambda x: ('secret', '42') in x.invocation_metadata,
- _LoggingInterceptor('s3', self._record))
-
- self._server = grpc.server(self._server_pool,
- options=(('grpc.so_reuseport', 0),),
- interceptors=(
- _LoggingInterceptor('s1', self._record),
- conditional_interceptor,
- _LoggingInterceptor('s2', self._record),
- ))
- port = self._server.add_insecure_port('[::]:0')
- self._server.add_generic_rpc_handlers((_GenericHandler(self._handler),))
- self._server.start()
-
- self._channel = grpc.insecure_channel('localhost:%d' % port)
-
- def tearDown(self):
- self._server.stop(None)
- self._server_pool.shutdown(wait=True)
- self._channel.close()
-
- def testTripleRequestMessagesClientInterceptor(self):
-
- def triple(request_iterator):
- while True:
- try:
- item = next(request_iterator)
- yield item
- yield item
- yield item
- except StopIteration:
- break
-
- interceptor = _wrap_request_iterator_stream_interceptor(triple)
- channel = grpc.intercept_channel(self._channel, interceptor)
- requests = tuple(
- b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
-
- multi_callable = _stream_stream_multi_callable(channel)
- response_iterator = multi_callable(
- iter(requests),
- metadata=(
- ('test',
- 'InterceptedStreamRequestBlockingUnaryResponseWithCall'),))
-
- responses = tuple(response_iterator)
- self.assertEqual(len(responses), 3 * test_constants.STREAM_LENGTH)
-
- multi_callable = _stream_stream_multi_callable(self._channel)
- response_iterator = multi_callable(
- iter(requests),
- metadata=(
- ('test',
- 'InterceptedStreamRequestBlockingUnaryResponseWithCall'),))
-
- responses = tuple(response_iterator)
- self.assertEqual(len(responses), test_constants.STREAM_LENGTH)
-
- def testDefectiveClientInterceptor(self):
- interceptor = _DefectiveClientInterceptor()
- defective_channel = grpc.intercept_channel(self._channel, interceptor)
-
- request = b'\x07\x08'
-
- multi_callable = _unary_unary_multi_callable(defective_channel)
- call_future = multi_callable.future(
- request,
- metadata=(('test',
- 'InterceptedUnaryRequestBlockingUnaryResponse'),))
-
- self.assertIsNotNone(call_future.exception())
- self.assertEqual(call_future.code(), grpc.StatusCode.INTERNAL)
-
- def testInterceptedHeaderManipulationWithServerSideVerification(self):
- request = b'\x07\x08'
-
- channel = grpc.intercept_channel(
- self._channel, _append_request_header_interceptor('secret', '42'))
- channel = grpc.intercept_channel(
- channel, _LoggingInterceptor('c1', self._record),
- _LoggingInterceptor('c2', self._record))
-
- self._record[:] = []
-
- multi_callable = _unary_unary_multi_callable(channel)
- multi_callable.with_call(
- request,
- metadata=(
- ('test',
- 'InterceptedUnaryRequestBlockingUnaryResponseWithCall'),))
-
- self.assertSequenceEqual(self._record, [
- 'c1:intercept_unary_unary', 'c2:intercept_unary_unary',
- 's1:intercept_service', 's3:intercept_service',
- 's2:intercept_service'
- ])
-
- def testInterceptedUnaryRequestBlockingUnaryResponse(self):
- request = b'\x07\x08'
-
- self._record[:] = []
-
- channel = grpc.intercept_channel(
- self._channel, _LoggingInterceptor('c1', self._record),
- _LoggingInterceptor('c2', self._record))
-
- multi_callable = _unary_unary_multi_callable(channel)
- multi_callable(
- request,
- metadata=(('test',
- 'InterceptedUnaryRequestBlockingUnaryResponse'),))
-
- self.assertSequenceEqual(self._record, [
- 'c1:intercept_unary_unary', 'c2:intercept_unary_unary',
- 's1:intercept_service', 's2:intercept_service'
- ])
-
- def testInterceptedUnaryRequestBlockingUnaryResponseWithError(self):
- request = _EXCEPTION_REQUEST
-
- self._record[:] = []
-
- channel = grpc.intercept_channel(
- self._channel, _LoggingInterceptor('c1', self._record),
- _LoggingInterceptor('c2', self._record))
-
- multi_callable = _unary_unary_multi_callable(channel)
- with self.assertRaises(grpc.RpcError) as exception_context:
- multi_callable(
- request,
- metadata=(('test',
- 'InterceptedUnaryRequestBlockingUnaryResponse'),))
- exception = exception_context.exception
- self.assertFalse(exception.cancelled())
- self.assertFalse(exception.running())
- self.assertTrue(exception.done())
- with self.assertRaises(grpc.RpcError):
- exception.result()
- self.assertIsInstance(exception.exception(), grpc.RpcError)
-
- def testInterceptedUnaryRequestBlockingUnaryResponseWithCall(self):
- request = b'\x07\x08'
-
- channel = grpc.intercept_channel(
- self._channel, _LoggingInterceptor('c1', self._record),
- _LoggingInterceptor('c2', self._record))
-
- self._record[:] = []
-
- multi_callable = _unary_unary_multi_callable(channel)
- multi_callable.with_call(
- request,
- metadata=(
- ('test',
- 'InterceptedUnaryRequestBlockingUnaryResponseWithCall'),))
-
- self.assertSequenceEqual(self._record, [
- 'c1:intercept_unary_unary', 'c2:intercept_unary_unary',
- 's1:intercept_service', 's2:intercept_service'
- ])
-
- def testInterceptedUnaryRequestFutureUnaryResponse(self):
- request = b'\x07\x08'
-
- self._record[:] = []
- channel = grpc.intercept_channel(
- self._channel, _LoggingInterceptor('c1', self._record),
- _LoggingInterceptor('c2', self._record))
-
- multi_callable = _unary_unary_multi_callable(channel)
- response_future = multi_callable.future(
- request,
- metadata=(('test', 'InterceptedUnaryRequestFutureUnaryResponse'),))
- response_future.result()
-
- self.assertSequenceEqual(self._record, [
- 'c1:intercept_unary_unary', 'c2:intercept_unary_unary',
- 's1:intercept_service', 's2:intercept_service'
- ])
-
- def testInterceptedUnaryRequestStreamResponse(self):
- request = b'\x37\x58'
-
- self._record[:] = []
- channel = grpc.intercept_channel(
- self._channel, _LoggingInterceptor('c1', self._record),
- _LoggingInterceptor('c2', self._record))
-
- multi_callable = _unary_stream_multi_callable(channel)
- response_iterator = multi_callable(
- request,
- metadata=(('test', 'InterceptedUnaryRequestStreamResponse'),))
- tuple(response_iterator)
-
- self.assertSequenceEqual(self._record, [
- 'c1:intercept_unary_stream', 'c2:intercept_unary_stream',
- 's1:intercept_service', 's2:intercept_service'
- ])
-
- def testInterceptedUnaryRequestStreamResponseWithError(self):
- request = _EXCEPTION_REQUEST
-
- self._record[:] = []
- channel = grpc.intercept_channel(
- self._channel, _LoggingInterceptor('c1', self._record),
- _LoggingInterceptor('c2', self._record))
-
- multi_callable = _unary_stream_multi_callable(channel)
- response_iterator = multi_callable(
- request,
- metadata=(('test', 'InterceptedUnaryRequestStreamResponse'),))
- with self.assertRaises(grpc.RpcError) as exception_context:
- tuple(response_iterator)
- exception = exception_context.exception
- self.assertFalse(exception.cancelled())
- self.assertFalse(exception.running())
- self.assertTrue(exception.done())
- with self.assertRaises(grpc.RpcError):
- exception.result()
- self.assertIsInstance(exception.exception(), grpc.RpcError)
-
- def testInterceptedStreamRequestBlockingUnaryResponse(self):
- requests = tuple(
- b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
- request_iterator = iter(requests)
-
- self._record[:] = []
- channel = grpc.intercept_channel(
- self._channel, _LoggingInterceptor('c1', self._record),
- _LoggingInterceptor('c2', self._record))
-
- multi_callable = _stream_unary_multi_callable(channel)
- multi_callable(
- request_iterator,
- metadata=(('test',
- 'InterceptedStreamRequestBlockingUnaryResponse'),))
-
- self.assertSequenceEqual(self._record, [
- 'c1:intercept_stream_unary', 'c2:intercept_stream_unary',
- 's1:intercept_service', 's2:intercept_service'
- ])
-
- def testInterceptedStreamRequestBlockingUnaryResponseWithCall(self):
- requests = tuple(
- b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
- request_iterator = iter(requests)
-
- self._record[:] = []
- channel = grpc.intercept_channel(
- self._channel, _LoggingInterceptor('c1', self._record),
- _LoggingInterceptor('c2', self._record))
-
- multi_callable = _stream_unary_multi_callable(channel)
- multi_callable.with_call(
- request_iterator,
- metadata=(
- ('test',
- 'InterceptedStreamRequestBlockingUnaryResponseWithCall'),))
-
- self.assertSequenceEqual(self._record, [
- 'c1:intercept_stream_unary', 'c2:intercept_stream_unary',
- 's1:intercept_service', 's2:intercept_service'
- ])
-
- def testInterceptedStreamRequestFutureUnaryResponse(self):
- requests = tuple(
- b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
- request_iterator = iter(requests)
-
- self._record[:] = []
- channel = grpc.intercept_channel(
- self._channel, _LoggingInterceptor('c1', self._record),
- _LoggingInterceptor('c2', self._record))
-
- multi_callable = _stream_unary_multi_callable(channel)
- response_future = multi_callable.future(
- request_iterator,
- metadata=(('test', 'InterceptedStreamRequestFutureUnaryResponse'),))
- response_future.result()
-
- self.assertSequenceEqual(self._record, [
- 'c1:intercept_stream_unary', 'c2:intercept_stream_unary',
- 's1:intercept_service', 's2:intercept_service'
- ])
-
- def testInterceptedStreamRequestFutureUnaryResponseWithError(self):
- requests = tuple(
- _EXCEPTION_REQUEST for _ in range(test_constants.STREAM_LENGTH))
- request_iterator = iter(requests)
-
- self._record[:] = []
- channel = grpc.intercept_channel(
- self._channel, _LoggingInterceptor('c1', self._record),
- _LoggingInterceptor('c2', self._record))
-
- multi_callable = _stream_unary_multi_callable(channel)
- response_future = multi_callable.future(
- request_iterator,
- metadata=(('test', 'InterceptedStreamRequestFutureUnaryResponse'),))
- with self.assertRaises(grpc.RpcError) as exception_context:
- response_future.result()
- exception = exception_context.exception
- self.assertFalse(exception.cancelled())
- self.assertFalse(exception.running())
- self.assertTrue(exception.done())
- with self.assertRaises(grpc.RpcError):
- exception.result()
- self.assertIsInstance(exception.exception(), grpc.RpcError)
-
- def testInterceptedStreamRequestStreamResponse(self):
- requests = tuple(
- b'\x77\x58' for _ in range(test_constants.STREAM_LENGTH))
- request_iterator = iter(requests)
-
- self._record[:] = []
- channel = grpc.intercept_channel(
- self._channel, _LoggingInterceptor('c1', self._record),
- _LoggingInterceptor('c2', self._record))
-
- multi_callable = _stream_stream_multi_callable(channel)
- response_iterator = multi_callable(
- request_iterator,
- metadata=(('test', 'InterceptedStreamRequestStreamResponse'),))
- tuple(response_iterator)
-
- self.assertSequenceEqual(self._record, [
- 'c1:intercept_stream_stream', 'c2:intercept_stream_stream',
- 's1:intercept_service', 's2:intercept_service'
- ])
-
- def testInterceptedStreamRequestStreamResponseWithError(self):
- requests = tuple(
- _EXCEPTION_REQUEST for _ in range(test_constants.STREAM_LENGTH))
- request_iterator = iter(requests)
-
- self._record[:] = []
- channel = grpc.intercept_channel(
- self._channel, _LoggingInterceptor('c1', self._record),
- _LoggingInterceptor('c2', self._record))
-
- multi_callable = _stream_stream_multi_callable(channel)
- response_iterator = multi_callable(
- request_iterator,
- metadata=(('test', 'InterceptedStreamRequestStreamResponse'),))
- with self.assertRaises(grpc.RpcError) as exception_context:
- tuple(response_iterator)
- exception = exception_context.exception
- self.assertFalse(exception.cancelled())
- self.assertFalse(exception.running())
- self.assertTrue(exception.done())
- with self.assertRaises(grpc.RpcError):
- exception.result()
- self.assertIsInstance(exception.exception(), grpc.RpcError)
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_invalid_metadata_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_invalid_metadata_test.py
deleted file mode 100644
index c56b719c408..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_invalid_metadata_test.py
+++ /dev/null
@@ -1,140 +0,0 @@
-# Copyright 2016 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Test of RPCs made against gRPC Python's application-layer API."""
-
-import logging
-import unittest
-
-import grpc
-
-from tests.unit.framework.common import test_constants
-
-_SERIALIZE_REQUEST = lambda bytestring: bytestring * 2
-_DESERIALIZE_REQUEST = lambda bytestring: bytestring[len(bytestring) // 2:]
-_SERIALIZE_RESPONSE = lambda bytestring: bytestring * 3
-_DESERIALIZE_RESPONSE = lambda bytestring: bytestring[:len(bytestring) // 3]
-
-_UNARY_UNARY = '/test/UnaryUnary'
-_UNARY_STREAM = '/test/UnaryStream'
-_STREAM_UNARY = '/test/StreamUnary'
-_STREAM_STREAM = '/test/StreamStream'
-
-
-def _unary_unary_multi_callable(channel):
- return channel.unary_unary(_UNARY_UNARY)
-
-
-def _unary_stream_multi_callable(channel):
- return channel.unary_stream(_UNARY_STREAM,
- request_serializer=_SERIALIZE_REQUEST,
- response_deserializer=_DESERIALIZE_RESPONSE)
-
-
-def _stream_unary_multi_callable(channel):
- return channel.stream_unary(_STREAM_UNARY,
- request_serializer=_SERIALIZE_REQUEST,
- response_deserializer=_DESERIALIZE_RESPONSE)
-
-
-def _stream_stream_multi_callable(channel):
- return channel.stream_stream(_STREAM_STREAM)
-
-
-class InvalidMetadataTest(unittest.TestCase):
-
- def setUp(self):
- self._channel = grpc.insecure_channel('localhost:8080')
- self._unary_unary = _unary_unary_multi_callable(self._channel)
- self._unary_stream = _unary_stream_multi_callable(self._channel)
- self._stream_unary = _stream_unary_multi_callable(self._channel)
- self._stream_stream = _stream_stream_multi_callable(self._channel)
-
- def tearDown(self):
- self._channel.close()
-
- def testUnaryRequestBlockingUnaryResponse(self):
- request = b'\x07\x08'
- metadata = (('InVaLiD', 'UnaryRequestBlockingUnaryResponse'),)
- expected_error_details = "metadata was invalid: %s" % metadata
- with self.assertRaises(ValueError) as exception_context:
- self._unary_unary(request, metadata=metadata)
- self.assertIn(expected_error_details, str(exception_context.exception))
-
- def testUnaryRequestBlockingUnaryResponseWithCall(self):
- request = b'\x07\x08'
- metadata = (('InVaLiD', 'UnaryRequestBlockingUnaryResponseWithCall'),)
- expected_error_details = "metadata was invalid: %s" % metadata
- with self.assertRaises(ValueError) as exception_context:
- self._unary_unary.with_call(request, metadata=metadata)
- self.assertIn(expected_error_details, str(exception_context.exception))
-
- def testUnaryRequestFutureUnaryResponse(self):
- request = b'\x07\x08'
- metadata = (('InVaLiD', 'UnaryRequestFutureUnaryResponse'),)
- expected_error_details = "metadata was invalid: %s" % metadata
- with self.assertRaises(ValueError) as exception_context:
- self._unary_unary.future(request, metadata=metadata)
-
- def testUnaryRequestStreamResponse(self):
- request = b'\x37\x58'
- metadata = (('InVaLiD', 'UnaryRequestStreamResponse'),)
- expected_error_details = "metadata was invalid: %s" % metadata
- with self.assertRaises(ValueError) as exception_context:
- self._unary_stream(request, metadata=metadata)
- self.assertIn(expected_error_details, str(exception_context.exception))
-
- def testStreamRequestBlockingUnaryResponse(self):
- request_iterator = (
- b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
- metadata = (('InVaLiD', 'StreamRequestBlockingUnaryResponse'),)
- expected_error_details = "metadata was invalid: %s" % metadata
- with self.assertRaises(ValueError) as exception_context:
- self._stream_unary(request_iterator, metadata=metadata)
- self.assertIn(expected_error_details, str(exception_context.exception))
-
- def testStreamRequestBlockingUnaryResponseWithCall(self):
- request_iterator = (
- b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
- metadata = (('InVaLiD', 'StreamRequestBlockingUnaryResponseWithCall'),)
- expected_error_details = "metadata was invalid: %s" % metadata
- multi_callable = _stream_unary_multi_callable(self._channel)
- with self.assertRaises(ValueError) as exception_context:
- multi_callable.with_call(request_iterator, metadata=metadata)
- self.assertIn(expected_error_details, str(exception_context.exception))
-
- def testStreamRequestFutureUnaryResponse(self):
- request_iterator = (
- b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
- metadata = (('InVaLiD', 'StreamRequestFutureUnaryResponse'),)
- expected_error_details = "metadata was invalid: %s" % metadata
- with self.assertRaises(ValueError) as exception_context:
- self._stream_unary.future(request_iterator, metadata=metadata)
- self.assertIn(expected_error_details, str(exception_context.exception))
-
- def testStreamRequestStreamResponse(self):
- request_iterator = (
- b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
- metadata = (('InVaLiD', 'StreamRequestStreamResponse'),)
- expected_error_details = "metadata was invalid: %s" % metadata
- with self.assertRaises(ValueError) as exception_context:
- self._stream_stream(request_iterator, metadata=metadata)
- self.assertIn(expected_error_details, str(exception_context.exception))
-
- def testInvalidMetadata(self):
- self.assertRaises(TypeError, self._unary_unary, b'', metadata=42)
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_invocation_defects_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_invocation_defects_test.py
deleted file mode 100644
index cacb028c3b4..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_invocation_defects_test.py
+++ /dev/null
@@ -1,266 +0,0 @@
-# Copyright 2016 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import logging
-import unittest
-
-import grpc
-
-from tests.unit import test_common
-from tests.unit.framework.common import test_constants
-from tests.unit.framework.common import test_control
-
-_SERIALIZE_REQUEST = lambda bytestring: bytestring * 2
-_DESERIALIZE_REQUEST = lambda bytestring: bytestring[len(bytestring) // 2:]
-_SERIALIZE_RESPONSE = lambda bytestring: bytestring * 3
-_DESERIALIZE_RESPONSE = lambda bytestring: bytestring[:len(bytestring) // 3]
-
-_UNARY_UNARY = '/test/UnaryUnary'
-_UNARY_STREAM = '/test/UnaryStream'
-_STREAM_UNARY = '/test/StreamUnary'
-_STREAM_STREAM = '/test/StreamStream'
-_DEFECTIVE_GENERIC_RPC_HANDLER = '/test/DefectiveGenericRpcHandler'
-
-
-class _Handler(object):
-
- def __init__(self, control):
- self._control = control
-
- def handle_unary_unary(self, request, servicer_context):
- self._control.control()
- if servicer_context is not None:
- servicer_context.set_trailing_metadata(((
- 'testkey',
- 'testvalue',
- ),))
- return request
-
- def handle_unary_stream(self, request, servicer_context):
- for _ in range(test_constants.STREAM_LENGTH):
- self._control.control()
- yield request
- self._control.control()
- if servicer_context is not None:
- servicer_context.set_trailing_metadata(((
- 'testkey',
- 'testvalue',
- ),))
-
- def handle_stream_unary(self, request_iterator, servicer_context):
- if servicer_context is not None:
- servicer_context.invocation_metadata()
- self._control.control()
- response_elements = []
- for request in request_iterator:
- self._control.control()
- response_elements.append(request)
- self._control.control()
- if servicer_context is not None:
- servicer_context.set_trailing_metadata(((
- 'testkey',
- 'testvalue',
- ),))
- return b''.join(response_elements)
-
- def handle_stream_stream(self, request_iterator, servicer_context):
- self._control.control()
- if servicer_context is not None:
- servicer_context.set_trailing_metadata(((
- 'testkey',
- 'testvalue',
- ),))
- for request in request_iterator:
- self._control.control()
- yield request
- self._control.control()
-
- def defective_generic_rpc_handler(self):
- raise test_control.Defect()
-
-
-class _MethodHandler(grpc.RpcMethodHandler):
-
- def __init__(self, request_streaming, response_streaming,
- request_deserializer, response_serializer, unary_unary,
- unary_stream, stream_unary, stream_stream):
- self.request_streaming = request_streaming
- self.response_streaming = response_streaming
- self.request_deserializer = request_deserializer
- self.response_serializer = response_serializer
- self.unary_unary = unary_unary
- self.unary_stream = unary_stream
- self.stream_unary = stream_unary
- self.stream_stream = stream_stream
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def __init__(self, handler):
- self._handler = handler
-
- def service(self, handler_call_details):
- if handler_call_details.method == _UNARY_UNARY:
- return _MethodHandler(False, False, None, None,
- self._handler.handle_unary_unary, None, None,
- None)
- elif handler_call_details.method == _UNARY_STREAM:
- return _MethodHandler(False, True, _DESERIALIZE_REQUEST,
- _SERIALIZE_RESPONSE, None,
- self._handler.handle_unary_stream, None, None)
- elif handler_call_details.method == _STREAM_UNARY:
- return _MethodHandler(True, False, _DESERIALIZE_REQUEST,
- _SERIALIZE_RESPONSE, None, None,
- self._handler.handle_stream_unary, None)
- elif handler_call_details.method == _STREAM_STREAM:
- return _MethodHandler(True, True, None, None, None, None, None,
- self._handler.handle_stream_stream)
- elif handler_call_details.method == _DEFECTIVE_GENERIC_RPC_HANDLER:
- return self._handler.defective_generic_rpc_handler()
- else:
- return None
-
-
-class FailAfterFewIterationsCounter(object):
-
- def __init__(self, high, bytestring):
- self._current = 0
- self._high = high
- self._bytestring = bytestring
-
- def __iter__(self):
- return self
-
- def __next__(self):
- if self._current >= self._high:
- raise test_control.Defect()
- else:
- self._current += 1
- return self._bytestring
-
- next = __next__
-
-
-def _unary_unary_multi_callable(channel):
- return channel.unary_unary(_UNARY_UNARY)
-
-
-def _unary_stream_multi_callable(channel):
- return channel.unary_stream(_UNARY_STREAM,
- request_serializer=_SERIALIZE_REQUEST,
- response_deserializer=_DESERIALIZE_RESPONSE)
-
-
-def _stream_unary_multi_callable(channel):
- return channel.stream_unary(_STREAM_UNARY,
- request_serializer=_SERIALIZE_REQUEST,
- response_deserializer=_DESERIALIZE_RESPONSE)
-
-
-def _stream_stream_multi_callable(channel):
- return channel.stream_stream(_STREAM_STREAM)
-
-
-def _defective_handler_multi_callable(channel):
- return channel.unary_unary(_DEFECTIVE_GENERIC_RPC_HANDLER)
-
-
-class InvocationDefectsTest(unittest.TestCase):
- """Tests the handling of exception-raising user code on the client-side."""
-
- def setUp(self):
- self._control = test_control.PauseFailControl()
- self._handler = _Handler(self._control)
-
- self._server = test_common.test_server()
- port = self._server.add_insecure_port('[::]:0')
- self._server.add_generic_rpc_handlers((_GenericHandler(self._handler),))
- self._server.start()
-
- self._channel = grpc.insecure_channel('localhost:%d' % port)
-
- def tearDown(self):
- self._server.stop(0)
- self._channel.close()
-
- def testIterableStreamRequestBlockingUnaryResponse(self):
- requests = object()
- multi_callable = _stream_unary_multi_callable(self._channel)
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- multi_callable(
- requests,
- metadata=(('test',
- 'IterableStreamRequestBlockingUnaryResponse'),))
-
- self.assertIs(grpc.StatusCode.UNKNOWN,
- exception_context.exception.code())
-
- def testIterableStreamRequestFutureUnaryResponse(self):
- requests = object()
- multi_callable = _stream_unary_multi_callable(self._channel)
- response_future = multi_callable.future(
- requests,
- metadata=(('test', 'IterableStreamRequestFutureUnaryResponse'),))
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- response_future.result()
-
- self.assertIs(grpc.StatusCode.UNKNOWN,
- exception_context.exception.code())
-
- def testIterableStreamRequestStreamResponse(self):
- requests = object()
- multi_callable = _stream_stream_multi_callable(self._channel)
- response_iterator = multi_callable(
- requests,
- metadata=(('test', 'IterableStreamRequestStreamResponse'),))
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- next(response_iterator)
-
- self.assertIs(grpc.StatusCode.UNKNOWN,
- exception_context.exception.code())
-
- def testIteratorStreamRequestStreamResponse(self):
- requests_iterator = FailAfterFewIterationsCounter(
- test_constants.STREAM_LENGTH // 2, b'\x07\x08')
- multi_callable = _stream_stream_multi_callable(self._channel)
- response_iterator = multi_callable(
- requests_iterator,
- metadata=(('test', 'IteratorStreamRequestStreamResponse'),))
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- for _ in range(test_constants.STREAM_LENGTH // 2 + 1):
- next(response_iterator)
-
- self.assertIs(grpc.StatusCode.UNKNOWN,
- exception_context.exception.code())
-
- def testDefectiveGenericRpcHandlerUnaryResponse(self):
- request = b'\x07\x08'
- multi_callable = _defective_handler_multi_callable(self._channel)
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- multi_callable(request,
- metadata=(('test',
- 'DefectiveGenericRpcHandlerUnary'),))
-
- self.assertIs(grpc.StatusCode.UNKNOWN,
- exception_context.exception.code())
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_local_credentials_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_local_credentials_test.py
deleted file mode 100644
index 5351a2b4cc1..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_local_credentials_test.py
+++ /dev/null
@@ -1,82 +0,0 @@
-# Copyright 2019 The gRPC Authors
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Test of RPCs made using local credentials."""
-
-from concurrent.futures import ThreadPoolExecutor
-import os
-import unittest
-
-import grpc
-
-from tests.unit import test_common
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def service(self, handler_call_details):
- return grpc.unary_unary_rpc_method_handler(
- lambda request, unused_context: request)
-
-
-class LocalCredentialsTest(unittest.TestCase):
-
- def _create_server(self):
- server = grpc.server(ThreadPoolExecutor())
- server.add_generic_rpc_handlers((_GenericHandler(),))
- return server
-
- @unittest.skipIf(os.name == 'nt',
- 'TODO(https://github.com/grpc/grpc/issues/20078)')
- def test_local_tcp(self):
- server_addr = 'localhost:{}'
- channel_creds = grpc.local_channel_credentials(
- grpc.LocalConnectionType.LOCAL_TCP)
- server_creds = grpc.local_server_credentials(
- grpc.LocalConnectionType.LOCAL_TCP)
-
- server = self._create_server()
- port = server.add_secure_port(server_addr.format(0), server_creds)
- server.start()
- with grpc.secure_channel(server_addr.format(port),
- channel_creds) as channel:
- self.assertEqual(
- b'abc',
- channel.unary_unary('/test/method')(b'abc',
- wait_for_ready=True))
- server.stop(None)
-
- @unittest.skipIf(os.name == 'nt',
- 'Unix Domain Socket is not supported on Windows')
- @unittest.skipIf(test_common.running_under_gevent(),
- 'UDS not supported under gevent.')
- def test_uds(self):
- server_addr = 'unix:/tmp/grpc_fullstack_test'
- channel_creds = grpc.local_channel_credentials(
- grpc.LocalConnectionType.UDS)
- server_creds = grpc.local_server_credentials(
- grpc.LocalConnectionType.UDS)
-
- server = self._create_server()
- server.add_secure_port(server_addr, server_creds)
- server.start()
- with grpc.secure_channel(server_addr, channel_creds) as channel:
- self.assertEqual(
- b'abc',
- channel.unary_unary('/test/method')(b'abc',
- wait_for_ready=True))
- server.stop(None)
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_logging_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_logging_test.py
deleted file mode 100644
index 933d2e6212f..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_logging_test.py
+++ /dev/null
@@ -1,104 +0,0 @@
-# Copyright 2018 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Test of gRPC Python's interaction with the python logging module"""
-
-import logging
-import subprocess
-import sys
-import unittest
-
-import grpc
-import os
-
-INTERPRETER = sys.executable
-
-
-class LoggingTest(unittest.TestCase):
-
- def test_logger_not_occupied(self):
- script = """if True:
- import logging
-
- import grpc
-
- if len(logging.getLogger().handlers) != 0:
- raise Exception('expected 0 logging handlers')
-
- """
- self._verifyScriptSucceeds(script)
-
- def test_handler_found(self):
- script = """if True:
- import logging
-
- import grpc
- """
- out, err = self._verifyScriptSucceeds(script)
- self.assertEqual(0, len(err), 'unexpected output to stderr')
-
- def test_can_configure_logger(self):
- script = """if True:
- import logging
- import six
-
- import grpc
-
-
- intended_stream = six.StringIO()
- logging.basicConfig(stream=intended_stream)
-
- if len(logging.getLogger().handlers) != 1:
- raise Exception('expected 1 logging handler')
-
- if logging.getLogger().handlers[0].stream is not intended_stream:
- raise Exception('wrong handler stream')
-
- """
- self._verifyScriptSucceeds(script)
-
- def test_grpc_logger(self):
- script = """if True:
- import logging
-
- import grpc
-
- if "grpc" not in logging.Logger.manager.loggerDict:
- raise Exception('grpc logger not found')
-
- root_logger = logging.getLogger("grpc")
- if len(root_logger.handlers) != 1:
- raise Exception('expected 1 root logger handler')
- if not isinstance(root_logger.handlers[0], logging.NullHandler):
- raise Exception('expected logging.NullHandler')
-
- """
- self._verifyScriptSucceeds(script)
-
- def _verifyScriptSucceeds(self, script):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen([INTERPRETER, '-c', script],
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- env=env)
- out, err = process.communicate()
- self.assertEqual(
- 0, process.returncode,
- 'process failed with exit code %d (stdout: %s, stderr: %s)' %
- (process.returncode, out, err))
- return out, err
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_metadata_code_details_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_metadata_code_details_test.py
deleted file mode 100644
index 87441833c17..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_metadata_code_details_test.py
+++ /dev/null
@@ -1,723 +0,0 @@
-# Copyright 2016 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Tests application-provided metadata, status code, and details."""
-
-import logging
-import threading
-import unittest
-
-import grpc
-
-from tests.unit import test_common
-from tests.unit.framework.common import test_constants
-from tests.unit.framework.common import test_control
-
-_SERIALIZED_REQUEST = b'\x46\x47\x48'
-_SERIALIZED_RESPONSE = b'\x49\x50\x51'
-
-_REQUEST_SERIALIZER = lambda unused_request: _SERIALIZED_REQUEST
-_REQUEST_DESERIALIZER = lambda unused_serialized_request: object()
-_RESPONSE_SERIALIZER = lambda unused_response: _SERIALIZED_RESPONSE
-_RESPONSE_DESERIALIZER = lambda unused_serialized_response: object()
-
-_SERVICE = 'test.TestService'
-_UNARY_UNARY = 'UnaryUnary'
-_UNARY_STREAM = 'UnaryStream'
-_STREAM_UNARY = 'StreamUnary'
-_STREAM_STREAM = 'StreamStream'
-
-_CLIENT_METADATA = (('client-md-key', 'client-md-key'), ('client-md-key-bin',
- b'\x00\x01'))
-
-_SERVER_INITIAL_METADATA = (('server-initial-md-key',
- 'server-initial-md-value'),
- ('server-initial-md-key-bin', b'\x00\x02'))
-
-_SERVER_TRAILING_METADATA = (('server-trailing-md-key',
- 'server-trailing-md-value'),
- ('server-trailing-md-key-bin', b'\x00\x03'))
-
-_NON_OK_CODE = grpc.StatusCode.NOT_FOUND
-_DETAILS = 'Test details!'
-
-# calling abort should always fail an RPC, even for "invalid" codes
-_ABORT_CODES = (_NON_OK_CODE, 3, grpc.StatusCode.OK)
-_EXPECTED_CLIENT_CODES = (_NON_OK_CODE, grpc.StatusCode.UNKNOWN,
- grpc.StatusCode.UNKNOWN)
-_EXPECTED_DETAILS = (_DETAILS, _DETAILS, '')
-
-
-class _Servicer(object):
-
- def __init__(self):
- self._lock = threading.Lock()
- self._abort_call = False
- self._code = None
- self._details = None
- self._exception = False
- self._return_none = False
- self._received_client_metadata = None
-
- def unary_unary(self, request, context):
- with self._lock:
- self._received_client_metadata = context.invocation_metadata()
- context.send_initial_metadata(_SERVER_INITIAL_METADATA)
- context.set_trailing_metadata(_SERVER_TRAILING_METADATA)
- if self._abort_call:
- context.abort(self._code, self._details)
- else:
- if self._code is not None:
- context.set_code(self._code)
- if self._details is not None:
- context.set_details(self._details)
- if self._exception:
- raise test_control.Defect()
- else:
- return None if self._return_none else object()
-
- def unary_stream(self, request, context):
- with self._lock:
- self._received_client_metadata = context.invocation_metadata()
- context.send_initial_metadata(_SERVER_INITIAL_METADATA)
- context.set_trailing_metadata(_SERVER_TRAILING_METADATA)
- if self._abort_call:
- context.abort(self._code, self._details)
- else:
- if self._code is not None:
- context.set_code(self._code)
- if self._details is not None:
- context.set_details(self._details)
- for _ in range(test_constants.STREAM_LENGTH // 2):
- yield _SERIALIZED_RESPONSE
- if self._exception:
- raise test_control.Defect()
-
- def stream_unary(self, request_iterator, context):
- with self._lock:
- self._received_client_metadata = context.invocation_metadata()
- context.send_initial_metadata(_SERVER_INITIAL_METADATA)
- context.set_trailing_metadata(_SERVER_TRAILING_METADATA)
- # TODO(https://github.com/grpc/grpc/issues/6891): just ignore the
- # request iterator.
- list(request_iterator)
- if self._abort_call:
- context.abort(self._code, self._details)
- else:
- if self._code is not None:
- context.set_code(self._code)
- if self._details is not None:
- context.set_details(self._details)
- if self._exception:
- raise test_control.Defect()
- else:
- return None if self._return_none else _SERIALIZED_RESPONSE
-
- def stream_stream(self, request_iterator, context):
- with self._lock:
- self._received_client_metadata = context.invocation_metadata()
- context.send_initial_metadata(_SERVER_INITIAL_METADATA)
- context.set_trailing_metadata(_SERVER_TRAILING_METADATA)
- # TODO(https://github.com/grpc/grpc/issues/6891): just ignore the
- # request iterator.
- list(request_iterator)
- if self._abort_call:
- context.abort(self._code, self._details)
- else:
- if self._code is not None:
- context.set_code(self._code)
- if self._details is not None:
- context.set_details(self._details)
- for _ in range(test_constants.STREAM_LENGTH // 3):
- yield object()
- if self._exception:
- raise test_control.Defect()
-
- def set_abort_call(self):
- with self._lock:
- self._abort_call = True
-
- def set_code(self, code):
- with self._lock:
- self._code = code
-
- def set_details(self, details):
- with self._lock:
- self._details = details
-
- def set_exception(self):
- with self._lock:
- self._exception = True
-
- def set_return_none(self):
- with self._lock:
- self._return_none = True
-
- def received_client_metadata(self):
- with self._lock:
- return self._received_client_metadata
-
-
-def _generic_handler(servicer):
- method_handlers = {
- _UNARY_UNARY:
- grpc.unary_unary_rpc_method_handler(
- servicer.unary_unary,
- request_deserializer=_REQUEST_DESERIALIZER,
- response_serializer=_RESPONSE_SERIALIZER),
- _UNARY_STREAM:
- grpc.unary_stream_rpc_method_handler(servicer.unary_stream),
- _STREAM_UNARY:
- grpc.stream_unary_rpc_method_handler(servicer.stream_unary),
- _STREAM_STREAM:
- grpc.stream_stream_rpc_method_handler(
- servicer.stream_stream,
- request_deserializer=_REQUEST_DESERIALIZER,
- response_serializer=_RESPONSE_SERIALIZER),
- }
- return grpc.method_handlers_generic_handler(_SERVICE, method_handlers)
-
-
-@unittest.skipIf(test_common.running_under_gevent(),
- "Causes deadlock in gevent.")
-class MetadataCodeDetailsTest(unittest.TestCase):
-
- def setUp(self):
- self._servicer = _Servicer()
- self._server = test_common.test_server()
- self._server.add_generic_rpc_handlers(
- (_generic_handler(self._servicer),))
- port = self._server.add_insecure_port('[::]:0')
- self._server.start()
-
- self._channel = grpc.insecure_channel('localhost:{}'.format(port))
- self._unary_unary = self._channel.unary_unary(
- '/'.join((
- '',
- _SERVICE,
- _UNARY_UNARY,
- )),
- request_serializer=_REQUEST_SERIALIZER,
- response_deserializer=_RESPONSE_DESERIALIZER,
- )
- self._unary_stream = self._channel.unary_stream(
- '/'.join((
- '',
- _SERVICE,
- _UNARY_STREAM,
- )),)
- self._stream_unary = self._channel.stream_unary(
- '/'.join((
- '',
- _SERVICE,
- _STREAM_UNARY,
- )),)
- self._stream_stream = self._channel.stream_stream(
- '/'.join((
- '',
- _SERVICE,
- _STREAM_STREAM,
- )),
- request_serializer=_REQUEST_SERIALIZER,
- response_deserializer=_RESPONSE_DESERIALIZER,
- )
-
- def tearDown(self):
- self._server.stop(None)
- self._channel.close()
-
- def testSuccessfulUnaryUnary(self):
- self._servicer.set_details(_DETAILS)
-
- unused_response, call = self._unary_unary.with_call(
- object(), metadata=_CLIENT_METADATA)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA, self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
- call.initial_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(_SERVER_TRAILING_METADATA,
- call.trailing_metadata()))
- self.assertIs(grpc.StatusCode.OK, call.code())
-
- def testSuccessfulUnaryStream(self):
- self._servicer.set_details(_DETAILS)
-
- response_iterator_call = self._unary_stream(_SERIALIZED_REQUEST,
- metadata=_CLIENT_METADATA)
- received_initial_metadata = response_iterator_call.initial_metadata()
- list(response_iterator_call)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA, self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
- received_initial_metadata))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- response_iterator_call.trailing_metadata()))
- self.assertIs(grpc.StatusCode.OK, response_iterator_call.code())
-
- def testSuccessfulStreamUnary(self):
- self._servicer.set_details(_DETAILS)
-
- unused_response, call = self._stream_unary.with_call(
- iter([_SERIALIZED_REQUEST] * test_constants.STREAM_LENGTH),
- metadata=_CLIENT_METADATA)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA, self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
- call.initial_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(_SERVER_TRAILING_METADATA,
- call.trailing_metadata()))
- self.assertIs(grpc.StatusCode.OK, call.code())
-
- def testSuccessfulStreamStream(self):
- self._servicer.set_details(_DETAILS)
-
- response_iterator_call = self._stream_stream(iter(
- [object()] * test_constants.STREAM_LENGTH),
- metadata=_CLIENT_METADATA)
- received_initial_metadata = response_iterator_call.initial_metadata()
- list(response_iterator_call)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA, self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
- received_initial_metadata))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- response_iterator_call.trailing_metadata()))
- self.assertIs(grpc.StatusCode.OK, response_iterator_call.code())
-
- def testAbortedUnaryUnary(self):
- test_cases = zip(_ABORT_CODES, _EXPECTED_CLIENT_CODES,
- _EXPECTED_DETAILS)
- for abort_code, expected_code, expected_details in test_cases:
- self._servicer.set_code(abort_code)
- self._servicer.set_details(_DETAILS)
- self._servicer.set_abort_call()
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- self._unary_unary.with_call(object(), metadata=_CLIENT_METADATA)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA,
- self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_INITIAL_METADATA,
- exception_context.exception.initial_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- exception_context.exception.trailing_metadata()))
- self.assertIs(expected_code, exception_context.exception.code())
- self.assertEqual(expected_details,
- exception_context.exception.details())
-
- def testAbortedUnaryStream(self):
- test_cases = zip(_ABORT_CODES, _EXPECTED_CLIENT_CODES,
- _EXPECTED_DETAILS)
- for abort_code, expected_code, expected_details in test_cases:
- self._servicer.set_code(abort_code)
- self._servicer.set_details(_DETAILS)
- self._servicer.set_abort_call()
-
- response_iterator_call = self._unary_stream(
- _SERIALIZED_REQUEST, metadata=_CLIENT_METADATA)
- received_initial_metadata = \
- response_iterator_call.initial_metadata()
- with self.assertRaises(grpc.RpcError):
- self.assertEqual(len(list(response_iterator_call)), 0)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA,
- self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
- received_initial_metadata))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- response_iterator_call.trailing_metadata()))
- self.assertIs(expected_code, response_iterator_call.code())
- self.assertEqual(expected_details, response_iterator_call.details())
-
- def testAbortedStreamUnary(self):
- test_cases = zip(_ABORT_CODES, _EXPECTED_CLIENT_CODES,
- _EXPECTED_DETAILS)
- for abort_code, expected_code, expected_details in test_cases:
- self._servicer.set_code(abort_code)
- self._servicer.set_details(_DETAILS)
- self._servicer.set_abort_call()
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- self._stream_unary.with_call(iter([_SERIALIZED_REQUEST] *
- test_constants.STREAM_LENGTH),
- metadata=_CLIENT_METADATA)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA,
- self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_INITIAL_METADATA,
- exception_context.exception.initial_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- exception_context.exception.trailing_metadata()))
- self.assertIs(expected_code, exception_context.exception.code())
- self.assertEqual(expected_details,
- exception_context.exception.details())
-
- def testAbortedStreamStream(self):
- test_cases = zip(_ABORT_CODES, _EXPECTED_CLIENT_CODES,
- _EXPECTED_DETAILS)
- for abort_code, expected_code, expected_details in test_cases:
- self._servicer.set_code(abort_code)
- self._servicer.set_details(_DETAILS)
- self._servicer.set_abort_call()
-
- response_iterator_call = self._stream_stream(
- iter([object()] * test_constants.STREAM_LENGTH),
- metadata=_CLIENT_METADATA)
- received_initial_metadata = \
- response_iterator_call.initial_metadata()
- with self.assertRaises(grpc.RpcError):
- self.assertEqual(len(list(response_iterator_call)), 0)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA,
- self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
- received_initial_metadata))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- response_iterator_call.trailing_metadata()))
- self.assertIs(expected_code, response_iterator_call.code())
- self.assertEqual(expected_details, response_iterator_call.details())
-
- def testCustomCodeUnaryUnary(self):
- self._servicer.set_code(_NON_OK_CODE)
- self._servicer.set_details(_DETAILS)
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- self._unary_unary.with_call(object(), metadata=_CLIENT_METADATA)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA, self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_INITIAL_METADATA,
- exception_context.exception.initial_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- exception_context.exception.trailing_metadata()))
- self.assertIs(_NON_OK_CODE, exception_context.exception.code())
- self.assertEqual(_DETAILS, exception_context.exception.details())
-
- def testCustomCodeUnaryStream(self):
- self._servicer.set_code(_NON_OK_CODE)
- self._servicer.set_details(_DETAILS)
-
- response_iterator_call = self._unary_stream(_SERIALIZED_REQUEST,
- metadata=_CLIENT_METADATA)
- received_initial_metadata = response_iterator_call.initial_metadata()
- with self.assertRaises(grpc.RpcError):
- list(response_iterator_call)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA, self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
- received_initial_metadata))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- response_iterator_call.trailing_metadata()))
- self.assertIs(_NON_OK_CODE, response_iterator_call.code())
- self.assertEqual(_DETAILS, response_iterator_call.details())
-
- def testCustomCodeStreamUnary(self):
- self._servicer.set_code(_NON_OK_CODE)
- self._servicer.set_details(_DETAILS)
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- self._stream_unary.with_call(iter([_SERIALIZED_REQUEST] *
- test_constants.STREAM_LENGTH),
- metadata=_CLIENT_METADATA)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA, self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_INITIAL_METADATA,
- exception_context.exception.initial_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- exception_context.exception.trailing_metadata()))
- self.assertIs(_NON_OK_CODE, exception_context.exception.code())
- self.assertEqual(_DETAILS, exception_context.exception.details())
-
- def testCustomCodeStreamStream(self):
- self._servicer.set_code(_NON_OK_CODE)
- self._servicer.set_details(_DETAILS)
-
- response_iterator_call = self._stream_stream(iter(
- [object()] * test_constants.STREAM_LENGTH),
- metadata=_CLIENT_METADATA)
- received_initial_metadata = response_iterator_call.initial_metadata()
- with self.assertRaises(grpc.RpcError) as exception_context:
- list(response_iterator_call)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA, self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
- received_initial_metadata))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- exception_context.exception.trailing_metadata()))
- self.assertIs(_NON_OK_CODE, exception_context.exception.code())
- self.assertEqual(_DETAILS, exception_context.exception.details())
-
- def testCustomCodeExceptionUnaryUnary(self):
- self._servicer.set_code(_NON_OK_CODE)
- self._servicer.set_details(_DETAILS)
- self._servicer.set_exception()
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- self._unary_unary.with_call(object(), metadata=_CLIENT_METADATA)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA, self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_INITIAL_METADATA,
- exception_context.exception.initial_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- exception_context.exception.trailing_metadata()))
- self.assertIs(_NON_OK_CODE, exception_context.exception.code())
- self.assertEqual(_DETAILS, exception_context.exception.details())
-
- def testCustomCodeExceptionUnaryStream(self):
- self._servicer.set_code(_NON_OK_CODE)
- self._servicer.set_details(_DETAILS)
- self._servicer.set_exception()
-
- response_iterator_call = self._unary_stream(_SERIALIZED_REQUEST,
- metadata=_CLIENT_METADATA)
- received_initial_metadata = response_iterator_call.initial_metadata()
- with self.assertRaises(grpc.RpcError):
- list(response_iterator_call)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA, self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
- received_initial_metadata))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- response_iterator_call.trailing_metadata()))
- self.assertIs(_NON_OK_CODE, response_iterator_call.code())
- self.assertEqual(_DETAILS, response_iterator_call.details())
-
- def testCustomCodeExceptionStreamUnary(self):
- self._servicer.set_code(_NON_OK_CODE)
- self._servicer.set_details(_DETAILS)
- self._servicer.set_exception()
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- self._stream_unary.with_call(iter([_SERIALIZED_REQUEST] *
- test_constants.STREAM_LENGTH),
- metadata=_CLIENT_METADATA)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA, self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_INITIAL_METADATA,
- exception_context.exception.initial_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- exception_context.exception.trailing_metadata()))
- self.assertIs(_NON_OK_CODE, exception_context.exception.code())
- self.assertEqual(_DETAILS, exception_context.exception.details())
-
- def testCustomCodeExceptionStreamStream(self):
- self._servicer.set_code(_NON_OK_CODE)
- self._servicer.set_details(_DETAILS)
- self._servicer.set_exception()
-
- response_iterator_call = self._stream_stream(iter(
- [object()] * test_constants.STREAM_LENGTH),
- metadata=_CLIENT_METADATA)
- received_initial_metadata = response_iterator_call.initial_metadata()
- with self.assertRaises(grpc.RpcError):
- list(response_iterator_call)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA, self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(_SERVER_INITIAL_METADATA,
- received_initial_metadata))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- response_iterator_call.trailing_metadata()))
- self.assertIs(_NON_OK_CODE, response_iterator_call.code())
- self.assertEqual(_DETAILS, response_iterator_call.details())
-
- def testCustomCodeReturnNoneUnaryUnary(self):
- self._servicer.set_code(_NON_OK_CODE)
- self._servicer.set_details(_DETAILS)
- self._servicer.set_return_none()
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- self._unary_unary.with_call(object(), metadata=_CLIENT_METADATA)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA, self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_INITIAL_METADATA,
- exception_context.exception.initial_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- exception_context.exception.trailing_metadata()))
- self.assertIs(_NON_OK_CODE, exception_context.exception.code())
- self.assertEqual(_DETAILS, exception_context.exception.details())
-
- def testCustomCodeReturnNoneStreamUnary(self):
- self._servicer.set_code(_NON_OK_CODE)
- self._servicer.set_details(_DETAILS)
- self._servicer.set_return_none()
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- self._stream_unary.with_call(iter([_SERIALIZED_REQUEST] *
- test_constants.STREAM_LENGTH),
- metadata=_CLIENT_METADATA)
-
- self.assertTrue(
- test_common.metadata_transmitted(
- _CLIENT_METADATA, self._servicer.received_client_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_INITIAL_METADATA,
- exception_context.exception.initial_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(
- _SERVER_TRAILING_METADATA,
- exception_context.exception.trailing_metadata()))
- self.assertIs(_NON_OK_CODE, exception_context.exception.code())
- self.assertEqual(_DETAILS, exception_context.exception.details())
-
-
-class _InspectServicer(_Servicer):
-
- def __init__(self):
- super(_InspectServicer, self).__init__()
- self.actual_code = None
- self.actual_details = None
- self.actual_trailing_metadata = None
-
- def unary_unary(self, request, context):
- super(_InspectServicer, self).unary_unary(request, context)
-
- self.actual_code = context.code()
- self.actual_details = context.details()
- self.actual_trailing_metadata = context.trailing_metadata()
-
-
-class InspectContextTest(unittest.TestCase):
-
- def setUp(self):
- self._servicer = _InspectServicer()
- self._server = test_common.test_server()
- self._server.add_generic_rpc_handlers(
- (_generic_handler(self._servicer),))
- port = self._server.add_insecure_port('[::]:0')
- self._server.start()
-
- self._channel = grpc.insecure_channel('localhost:{}'.format(port))
- self._unary_unary = self._channel.unary_unary(
- '/'.join((
- '',
- _SERVICE,
- _UNARY_UNARY,
- )),
- request_serializer=_REQUEST_SERIALIZER,
- response_deserializer=_RESPONSE_DESERIALIZER,
- )
-
- def tearDown(self):
- self._server.stop(None)
- self._channel.close()
-
- def testCodeDetailsInContext(self):
- self._servicer.set_code(_NON_OK_CODE)
- self._servicer.set_details(_DETAILS)
-
- with self.assertRaises(grpc.RpcError) as exc_info:
- self._unary_unary.with_call(object(), metadata=_CLIENT_METADATA)
-
- err = exc_info.exception
- self.assertEqual(_NON_OK_CODE, err.code())
-
- self.assertEqual(self._servicer.actual_code, _NON_OK_CODE)
- self.assertEqual(self._servicer.actual_details.decode('utf-8'),
- _DETAILS)
- self.assertEqual(self._servicer.actual_trailing_metadata,
- _SERVER_TRAILING_METADATA)
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_metadata_flags_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_metadata_flags_test.py
deleted file mode 100644
index 982ec903334..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_metadata_flags_test.py
+++ /dev/null
@@ -1,260 +0,0 @@
-# Copyright 2018 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Tests metadata flags feature by testing wait-for-ready semantics"""
-
-import logging
-import socket
-import threading
-import time
-import unittest
-import weakref
-
-import grpc
-from six.moves import queue
-
-from tests.unit import test_common
-import tests.unit.framework.common
-from tests.unit.framework.common import get_socket
-from tests.unit.framework.common import test_constants
-
-_UNARY_UNARY = '/test/UnaryUnary'
-_UNARY_STREAM = '/test/UnaryStream'
-_STREAM_UNARY = '/test/StreamUnary'
-_STREAM_STREAM = '/test/StreamStream'
-
-_REQUEST = b'\x00\x00\x00'
-_RESPONSE = b'\x00\x00\x00'
-
-
-def handle_unary_unary(test, request, servicer_context):
- return _RESPONSE
-
-
-def handle_unary_stream(test, request, servicer_context):
- for _ in range(test_constants.STREAM_LENGTH):
- yield _RESPONSE
-
-
-def handle_stream_unary(test, request_iterator, servicer_context):
- for _ in request_iterator:
- pass
- return _RESPONSE
-
-
-def handle_stream_stream(test, request_iterator, servicer_context):
- for _ in request_iterator:
- yield _RESPONSE
-
-
-class _MethodHandler(grpc.RpcMethodHandler):
-
- def __init__(self, test, request_streaming, response_streaming):
- self.request_streaming = request_streaming
- self.response_streaming = response_streaming
- self.request_deserializer = None
- self.response_serializer = None
- self.unary_unary = None
- self.unary_stream = None
- self.stream_unary = None
- self.stream_stream = None
- if self.request_streaming and self.response_streaming:
- self.stream_stream = lambda req, ctx: handle_stream_stream(
- test, req, ctx)
- elif self.request_streaming:
- self.stream_unary = lambda req, ctx: handle_stream_unary(
- test, req, ctx)
- elif self.response_streaming:
- self.unary_stream = lambda req, ctx: handle_unary_stream(
- test, req, ctx)
- else:
- self.unary_unary = lambda req, ctx: handle_unary_unary(
- test, req, ctx)
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def __init__(self, test):
- self._test = test
-
- def service(self, handler_call_details):
- if handler_call_details.method == _UNARY_UNARY:
- return _MethodHandler(self._test, False, False)
- elif handler_call_details.method == _UNARY_STREAM:
- return _MethodHandler(self._test, False, True)
- elif handler_call_details.method == _STREAM_UNARY:
- return _MethodHandler(self._test, True, False)
- elif handler_call_details.method == _STREAM_STREAM:
- return _MethodHandler(self._test, True, True)
- else:
- return None
-
-
-def create_phony_channel():
- """Creating phony channels is a workaround for retries"""
- host, port, sock = get_socket(sock_options=(socket.SO_REUSEADDR,))
- sock.close()
- return grpc.insecure_channel('{}:{}'.format(host, port))
-
-
-def perform_unary_unary_call(channel, wait_for_ready=None):
- channel.unary_unary(_UNARY_UNARY).__call__(
- _REQUEST,
- timeout=test_constants.LONG_TIMEOUT,
- wait_for_ready=wait_for_ready)
-
-
-def perform_unary_unary_with_call(channel, wait_for_ready=None):
- channel.unary_unary(_UNARY_UNARY).with_call(
- _REQUEST,
- timeout=test_constants.LONG_TIMEOUT,
- wait_for_ready=wait_for_ready)
-
-
-def perform_unary_unary_future(channel, wait_for_ready=None):
- channel.unary_unary(_UNARY_UNARY).future(
- _REQUEST,
- timeout=test_constants.LONG_TIMEOUT,
- wait_for_ready=wait_for_ready).result(
- timeout=test_constants.LONG_TIMEOUT)
-
-
-def perform_unary_stream_call(channel, wait_for_ready=None):
- response_iterator = channel.unary_stream(_UNARY_STREAM).__call__(
- _REQUEST,
- timeout=test_constants.LONG_TIMEOUT,
- wait_for_ready=wait_for_ready)
- for _ in response_iterator:
- pass
-
-
-def perform_stream_unary_call(channel, wait_for_ready=None):
- channel.stream_unary(_STREAM_UNARY).__call__(
- iter([_REQUEST] * test_constants.STREAM_LENGTH),
- timeout=test_constants.LONG_TIMEOUT,
- wait_for_ready=wait_for_ready)
-
-
-def perform_stream_unary_with_call(channel, wait_for_ready=None):
- channel.stream_unary(_STREAM_UNARY).with_call(
- iter([_REQUEST] * test_constants.STREAM_LENGTH),
- timeout=test_constants.LONG_TIMEOUT,
- wait_for_ready=wait_for_ready)
-
-
-def perform_stream_unary_future(channel, wait_for_ready=None):
- channel.stream_unary(_STREAM_UNARY).future(
- iter([_REQUEST] * test_constants.STREAM_LENGTH),
- timeout=test_constants.LONG_TIMEOUT,
- wait_for_ready=wait_for_ready).result(
- timeout=test_constants.LONG_TIMEOUT)
-
-
-def perform_stream_stream_call(channel, wait_for_ready=None):
- response_iterator = channel.stream_stream(_STREAM_STREAM).__call__(
- iter([_REQUEST] * test_constants.STREAM_LENGTH),
- timeout=test_constants.LONG_TIMEOUT,
- wait_for_ready=wait_for_ready)
- for _ in response_iterator:
- pass
-
-
-_ALL_CALL_CASES = [
- perform_unary_unary_call, perform_unary_unary_with_call,
- perform_unary_unary_future, perform_unary_stream_call,
- perform_stream_unary_call, perform_stream_unary_with_call,
- perform_stream_unary_future, perform_stream_stream_call
-]
-
-
-class MetadataFlagsTest(unittest.TestCase):
-
- def check_connection_does_failfast(self, fn, channel, wait_for_ready=None):
- try:
- fn(channel, wait_for_ready)
- self.fail("The Call should fail")
- except BaseException as e: # pylint: disable=broad-except
- self.assertIs(grpc.StatusCode.UNAVAILABLE, e.code())
-
- def test_call_wait_for_ready_default(self):
- for perform_call in _ALL_CALL_CASES:
- with create_phony_channel() as channel:
- self.check_connection_does_failfast(perform_call, channel)
-
- def test_call_wait_for_ready_disabled(self):
- for perform_call in _ALL_CALL_CASES:
- with create_phony_channel() as channel:
- self.check_connection_does_failfast(perform_call,
- channel,
- wait_for_ready=False)
-
- def test_call_wait_for_ready_enabled(self):
- # To test the wait mechanism, Python thread is required to make
- # client set up first without handling them case by case.
- # Also, Python thread don't pass the unhandled exceptions to
- # main thread. So, it need another method to store the
- # exceptions and raise them again in main thread.
- unhandled_exceptions = queue.Queue()
-
- # We just need an unused TCP port
- host, port, sock = get_socket(sock_options=(socket.SO_REUSEADDR,))
- sock.close()
-
- addr = '{}:{}'.format(host, port)
- wg = test_common.WaitGroup(len(_ALL_CALL_CASES))
-
- def wait_for_transient_failure(channel_connectivity):
- if channel_connectivity == grpc.ChannelConnectivity.TRANSIENT_FAILURE:
- wg.done()
-
- def test_call(perform_call):
- with grpc.insecure_channel(addr) as channel:
- try:
- channel.subscribe(wait_for_transient_failure)
- perform_call(channel, wait_for_ready=True)
- except BaseException as e: # pylint: disable=broad-except
- # If the call failed, the thread would be destroyed. The
- # channel object can be collected before calling the
- # callback, which will result in a deadlock.
- wg.done()
- unhandled_exceptions.put(e, True)
-
- test_threads = []
- for perform_call in _ALL_CALL_CASES:
- test_thread = threading.Thread(target=test_call,
- args=(perform_call,))
- test_thread.daemon = True
- test_thread.exception = None
- test_thread.start()
- test_threads.append(test_thread)
-
- # Start the server after the connections are waiting
- wg.wait()
- server = test_common.test_server(reuse_port=True)
- server.add_generic_rpc_handlers((_GenericHandler(weakref.proxy(self)),))
- server.add_insecure_port(addr)
- server.start()
-
- for test_thread in test_threads:
- test_thread.join()
-
- # Stop the server to make test end properly
- server.stop(0)
-
- if not unhandled_exceptions.empty():
- raise unhandled_exceptions.get(True)
-
-
-if __name__ == '__main__':
- logging.basicConfig(level=logging.DEBUG)
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_metadata_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_metadata_test.py
deleted file mode 100644
index d975228d3b0..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_metadata_test.py
+++ /dev/null
@@ -1,242 +0,0 @@
-# Copyright 2016 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Tests server and client side metadata API."""
-
-import logging
-import unittest
-import weakref
-
-import grpc
-from grpc import _channel
-
-from tests.unit import test_common
-from tests.unit.framework.common import test_constants
-
-_CHANNEL_ARGS = (('grpc.primary_user_agent', 'primary-agent'),
- ('grpc.secondary_user_agent', 'secondary-agent'))
-
-_REQUEST = b'\x00\x00\x00'
-_RESPONSE = b'\x00\x00\x00'
-
-_UNARY_UNARY = '/test/UnaryUnary'
-_UNARY_STREAM = '/test/UnaryStream'
-_STREAM_UNARY = '/test/StreamUnary'
-_STREAM_STREAM = '/test/StreamStream'
-
-_INVOCATION_METADATA = (
- (
- b'invocation-md-key',
- u'invocation-md-value',
- ),
- (
- u'invocation-md-key-bin',
- b'\x00\x01',
- ),
-)
-_EXPECTED_INVOCATION_METADATA = (
- (
- 'invocation-md-key',
- 'invocation-md-value',
- ),
- (
- 'invocation-md-key-bin',
- b'\x00\x01',
- ),
-)
-
-_INITIAL_METADATA = ((b'initial-md-key', u'initial-md-value'),
- (u'initial-md-key-bin', b'\x00\x02'))
-_EXPECTED_INITIAL_METADATA = (
- (
- 'initial-md-key',
- 'initial-md-value',
- ),
- (
- 'initial-md-key-bin',
- b'\x00\x02',
- ),
-)
-
-_TRAILING_METADATA = (
- (
- 'server-trailing-md-key',
- 'server-trailing-md-value',
- ),
- (
- 'server-trailing-md-key-bin',
- b'\x00\x03',
- ),
-)
-_EXPECTED_TRAILING_METADATA = _TRAILING_METADATA
-
-
-def _user_agent(metadata):
- for key, val in metadata:
- if key == 'user-agent':
- return val
- raise KeyError('No user agent!')
-
-
-def validate_client_metadata(test, servicer_context):
- invocation_metadata = servicer_context.invocation_metadata()
- test.assertTrue(
- test_common.metadata_transmitted(_EXPECTED_INVOCATION_METADATA,
- invocation_metadata))
- user_agent = _user_agent(invocation_metadata)
- test.assertTrue(
- user_agent.startswith('primary-agent ' + _channel._USER_AGENT))
- test.assertTrue(user_agent.endswith('secondary-agent'))
-
-
-def handle_unary_unary(test, request, servicer_context):
- validate_client_metadata(test, servicer_context)
- servicer_context.send_initial_metadata(_INITIAL_METADATA)
- servicer_context.set_trailing_metadata(_TRAILING_METADATA)
- return _RESPONSE
-
-
-def handle_unary_stream(test, request, servicer_context):
- validate_client_metadata(test, servicer_context)
- servicer_context.send_initial_metadata(_INITIAL_METADATA)
- servicer_context.set_trailing_metadata(_TRAILING_METADATA)
- for _ in range(test_constants.STREAM_LENGTH):
- yield _RESPONSE
-
-
-def handle_stream_unary(test, request_iterator, servicer_context):
- validate_client_metadata(test, servicer_context)
- servicer_context.send_initial_metadata(_INITIAL_METADATA)
- servicer_context.set_trailing_metadata(_TRAILING_METADATA)
- # TODO(issue:#6891) We should be able to remove this loop
- for request in request_iterator:
- pass
- return _RESPONSE
-
-
-def handle_stream_stream(test, request_iterator, servicer_context):
- validate_client_metadata(test, servicer_context)
- servicer_context.send_initial_metadata(_INITIAL_METADATA)
- servicer_context.set_trailing_metadata(_TRAILING_METADATA)
- # TODO(issue:#6891) We should be able to remove this loop,
- # and replace with return; yield
- for request in request_iterator:
- yield _RESPONSE
-
-
-class _MethodHandler(grpc.RpcMethodHandler):
-
- def __init__(self, test, request_streaming, response_streaming):
- self.request_streaming = request_streaming
- self.response_streaming = response_streaming
- self.request_deserializer = None
- self.response_serializer = None
- self.unary_unary = None
- self.unary_stream = None
- self.stream_unary = None
- self.stream_stream = None
- if self.request_streaming and self.response_streaming:
- self.stream_stream = lambda x, y: handle_stream_stream(test, x, y)
- elif self.request_streaming:
- self.stream_unary = lambda x, y: handle_stream_unary(test, x, y)
- elif self.response_streaming:
- self.unary_stream = lambda x, y: handle_unary_stream(test, x, y)
- else:
- self.unary_unary = lambda x, y: handle_unary_unary(test, x, y)
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def __init__(self, test):
- self._test = test
-
- def service(self, handler_call_details):
- if handler_call_details.method == _UNARY_UNARY:
- return _MethodHandler(self._test, False, False)
- elif handler_call_details.method == _UNARY_STREAM:
- return _MethodHandler(self._test, False, True)
- elif handler_call_details.method == _STREAM_UNARY:
- return _MethodHandler(self._test, True, False)
- elif handler_call_details.method == _STREAM_STREAM:
- return _MethodHandler(self._test, True, True)
- else:
- return None
-
-
-class MetadataTest(unittest.TestCase):
-
- def setUp(self):
- self._server = test_common.test_server()
- self._server.add_generic_rpc_handlers(
- (_GenericHandler(weakref.proxy(self)),))
- port = self._server.add_insecure_port('[::]:0')
- self._server.start()
- self._channel = grpc.insecure_channel('localhost:%d' % port,
- options=_CHANNEL_ARGS)
-
- def tearDown(self):
- self._server.stop(0)
- self._channel.close()
-
- def testUnaryUnary(self):
- multi_callable = self._channel.unary_unary(_UNARY_UNARY)
- unused_response, call = multi_callable.with_call(
- _REQUEST, metadata=_INVOCATION_METADATA)
- self.assertTrue(
- test_common.metadata_transmitted(_EXPECTED_INITIAL_METADATA,
- call.initial_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(_EXPECTED_TRAILING_METADATA,
- call.trailing_metadata()))
-
- def testUnaryStream(self):
- multi_callable = self._channel.unary_stream(_UNARY_STREAM)
- call = multi_callable(_REQUEST, metadata=_INVOCATION_METADATA)
- self.assertTrue(
- test_common.metadata_transmitted(_EXPECTED_INITIAL_METADATA,
- call.initial_metadata()))
- for _ in call:
- pass
- self.assertTrue(
- test_common.metadata_transmitted(_EXPECTED_TRAILING_METADATA,
- call.trailing_metadata()))
-
- def testStreamUnary(self):
- multi_callable = self._channel.stream_unary(_STREAM_UNARY)
- unused_response, call = multi_callable.with_call(
- iter([_REQUEST] * test_constants.STREAM_LENGTH),
- metadata=_INVOCATION_METADATA)
- self.assertTrue(
- test_common.metadata_transmitted(_EXPECTED_INITIAL_METADATA,
- call.initial_metadata()))
- self.assertTrue(
- test_common.metadata_transmitted(_EXPECTED_TRAILING_METADATA,
- call.trailing_metadata()))
-
- def testStreamStream(self):
- multi_callable = self._channel.stream_stream(_STREAM_STREAM)
- call = multi_callable(iter([_REQUEST] * test_constants.STREAM_LENGTH),
- metadata=_INVOCATION_METADATA)
- self.assertTrue(
- test_common.metadata_transmitted(_EXPECTED_INITIAL_METADATA,
- call.initial_metadata()))
- for _ in call:
- pass
- self.assertTrue(
- test_common.metadata_transmitted(_EXPECTED_TRAILING_METADATA,
- call.trailing_metadata()))
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_reconnect_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_reconnect_test.py
deleted file mode 100644
index 62ab5a58fc6..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_reconnect_test.py
+++ /dev/null
@@ -1,72 +0,0 @@
-# Copyright 2017 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Tests that a channel will reconnect if a connection is dropped"""
-
-import logging
-import socket
-import time
-import unittest
-
-import grpc
-from grpc.framework.foundation import logging_pool
-
-from tests.unit import test_common
-from tests.unit.framework.common import bound_socket
-from tests.unit.framework.common import test_constants
-
-_REQUEST = b'\x00\x00\x00'
-_RESPONSE = b'\x00\x00\x01'
-
-_UNARY_UNARY = '/test/UnaryUnary'
-
-
-def _handle_unary_unary(unused_request, unused_servicer_context):
- return _RESPONSE
-
-
-@unittest.skipIf(test_common.running_under_gevent(),
- "Test is nondeterministic under gevent.")
-class ReconnectTest(unittest.TestCase):
-
- def test_reconnect(self):
- server_pool = logging_pool.pool(test_constants.THREAD_CONCURRENCY)
- handler = grpc.method_handlers_generic_handler('test', {
- 'UnaryUnary':
- grpc.unary_unary_rpc_method_handler(_handle_unary_unary)
- })
- options = (('grpc.so_reuseport', 1),)
- with bound_socket() as (host, port):
- addr = '{}:{}'.format(host, port)
- server = grpc.server(server_pool, (handler,), options=options)
- server.add_insecure_port(addr)
- server.start()
- channel = grpc.insecure_channel(addr)
- multi_callable = channel.unary_unary(_UNARY_UNARY)
- self.assertEqual(_RESPONSE, multi_callable(_REQUEST))
- server.stop(None)
- # By default, the channel connectivity is checked every 5s
- # GRPC_CLIENT_CHANNEL_BACKUP_POLL_INTERVAL_MS can be set to change
- # this.
- time.sleep(5.1)
- server = grpc.server(server_pool, (handler,), options=options)
- server.add_insecure_port(addr)
- server.start()
- self.assertEqual(_RESPONSE, multi_callable(_REQUEST))
- server.stop(None)
- channel.close()
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_resource_exhausted_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_resource_exhausted_test.py
deleted file mode 100644
index bd3272176ef..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_resource_exhausted_test.py
+++ /dev/null
@@ -1,259 +0,0 @@
-# Copyright 2017 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Tests server responding with RESOURCE_EXHAUSTED."""
-
-import logging
-import threading
-import unittest
-
-import grpc
-from grpc import _channel
-from grpc.framework.foundation import logging_pool
-
-from tests.unit import test_common
-from tests.unit.framework.common import test_constants
-
-_REQUEST = b'\x00\x00\x00'
-_RESPONSE = b'\x00\x00\x00'
-
-_UNARY_UNARY = '/test/UnaryUnary'
-_UNARY_STREAM = '/test/UnaryStream'
-_STREAM_UNARY = '/test/StreamUnary'
-_STREAM_STREAM = '/test/StreamStream'
-
-
-class _TestTrigger(object):
-
- def __init__(self, total_call_count):
- self._total_call_count = total_call_count
- self._pending_calls = 0
- self._triggered = False
- self._finish_condition = threading.Condition()
- self._start_condition = threading.Condition()
-
- # Wait for all calls be blocked in their handler
- def await_calls(self):
- with self._start_condition:
- while self._pending_calls < self._total_call_count:
- self._start_condition.wait()
-
- # Block in a response handler and wait for a trigger
- def await_trigger(self):
- with self._start_condition:
- self._pending_calls += 1
- self._start_condition.notify()
-
- with self._finish_condition:
- if not self._triggered:
- self._finish_condition.wait()
-
- # Finish all response handlers
- def trigger(self):
- with self._finish_condition:
- self._triggered = True
- self._finish_condition.notify_all()
-
-
-def handle_unary_unary(trigger, request, servicer_context):
- trigger.await_trigger()
- return _RESPONSE
-
-
-def handle_unary_stream(trigger, request, servicer_context):
- trigger.await_trigger()
- for _ in range(test_constants.STREAM_LENGTH):
- yield _RESPONSE
-
-
-def handle_stream_unary(trigger, request_iterator, servicer_context):
- trigger.await_trigger()
- # TODO(issue:#6891) We should be able to remove this loop
- for request in request_iterator:
- pass
- return _RESPONSE
-
-
-def handle_stream_stream(trigger, request_iterator, servicer_context):
- trigger.await_trigger()
- # TODO(issue:#6891) We should be able to remove this loop,
- # and replace with return; yield
- for request in request_iterator:
- yield _RESPONSE
-
-
-class _MethodHandler(grpc.RpcMethodHandler):
-
- def __init__(self, trigger, request_streaming, response_streaming):
- self.request_streaming = request_streaming
- self.response_streaming = response_streaming
- self.request_deserializer = None
- self.response_serializer = None
- self.unary_unary = None
- self.unary_stream = None
- self.stream_unary = None
- self.stream_stream = None
- if self.request_streaming and self.response_streaming:
- self.stream_stream = (
- lambda x, y: handle_stream_stream(trigger, x, y))
- elif self.request_streaming:
- self.stream_unary = lambda x, y: handle_stream_unary(trigger, x, y)
- elif self.response_streaming:
- self.unary_stream = lambda x, y: handle_unary_stream(trigger, x, y)
- else:
- self.unary_unary = lambda x, y: handle_unary_unary(trigger, x, y)
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def __init__(self, trigger):
- self._trigger = trigger
-
- def service(self, handler_call_details):
- if handler_call_details.method == _UNARY_UNARY:
- return _MethodHandler(self._trigger, False, False)
- elif handler_call_details.method == _UNARY_STREAM:
- return _MethodHandler(self._trigger, False, True)
- elif handler_call_details.method == _STREAM_UNARY:
- return _MethodHandler(self._trigger, True, False)
- elif handler_call_details.method == _STREAM_STREAM:
- return _MethodHandler(self._trigger, True, True)
- else:
- return None
-
-
-class ResourceExhaustedTest(unittest.TestCase):
-
- def setUp(self):
- self._server_pool = logging_pool.pool(test_constants.THREAD_CONCURRENCY)
- self._trigger = _TestTrigger(test_constants.THREAD_CONCURRENCY)
- self._server = grpc.server(
- self._server_pool,
- handlers=(_GenericHandler(self._trigger),),
- options=(('grpc.so_reuseport', 0),),
- maximum_concurrent_rpcs=test_constants.THREAD_CONCURRENCY)
- port = self._server.add_insecure_port('[::]:0')
- self._server.start()
- self._channel = grpc.insecure_channel('localhost:%d' % port)
-
- def tearDown(self):
- self._server.stop(0)
- self._channel.close()
-
- def testUnaryUnary(self):
- multi_callable = self._channel.unary_unary(_UNARY_UNARY)
- futures = []
- for _ in range(test_constants.THREAD_CONCURRENCY):
- futures.append(multi_callable.future(_REQUEST))
-
- self._trigger.await_calls()
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- multi_callable(_REQUEST)
-
- self.assertEqual(grpc.StatusCode.RESOURCE_EXHAUSTED,
- exception_context.exception.code())
-
- future_exception = multi_callable.future(_REQUEST)
- self.assertEqual(grpc.StatusCode.RESOURCE_EXHAUSTED,
- future_exception.exception().code())
-
- self._trigger.trigger()
- for future in futures:
- self.assertEqual(_RESPONSE, future.result())
-
- # Ensure a new request can be handled
- self.assertEqual(_RESPONSE, multi_callable(_REQUEST))
-
- def testUnaryStream(self):
- multi_callable = self._channel.unary_stream(_UNARY_STREAM)
- calls = []
- for _ in range(test_constants.THREAD_CONCURRENCY):
- calls.append(multi_callable(_REQUEST))
-
- self._trigger.await_calls()
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- next(multi_callable(_REQUEST))
-
- self.assertEqual(grpc.StatusCode.RESOURCE_EXHAUSTED,
- exception_context.exception.code())
-
- self._trigger.trigger()
-
- for call in calls:
- for response in call:
- self.assertEqual(_RESPONSE, response)
-
- # Ensure a new request can be handled
- new_call = multi_callable(_REQUEST)
- for response in new_call:
- self.assertEqual(_RESPONSE, response)
-
- def testStreamUnary(self):
- multi_callable = self._channel.stream_unary(_STREAM_UNARY)
- futures = []
- request = iter([_REQUEST] * test_constants.STREAM_LENGTH)
- for _ in range(test_constants.THREAD_CONCURRENCY):
- futures.append(multi_callable.future(request))
-
- self._trigger.await_calls()
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- multi_callable(request)
-
- self.assertEqual(grpc.StatusCode.RESOURCE_EXHAUSTED,
- exception_context.exception.code())
-
- future_exception = multi_callable.future(request)
- self.assertEqual(grpc.StatusCode.RESOURCE_EXHAUSTED,
- future_exception.exception().code())
-
- self._trigger.trigger()
-
- for future in futures:
- self.assertEqual(_RESPONSE, future.result())
-
- # Ensure a new request can be handled
- self.assertEqual(_RESPONSE, multi_callable(request))
-
- def testStreamStream(self):
- multi_callable = self._channel.stream_stream(_STREAM_STREAM)
- calls = []
- request = iter([_REQUEST] * test_constants.STREAM_LENGTH)
- for _ in range(test_constants.THREAD_CONCURRENCY):
- calls.append(multi_callable(request))
-
- self._trigger.await_calls()
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- next(multi_callable(request))
-
- self.assertEqual(grpc.StatusCode.RESOURCE_EXHAUSTED,
- exception_context.exception.code())
-
- self._trigger.trigger()
-
- for call in calls:
- for response in call:
- self.assertEqual(_RESPONSE, response)
-
- # Ensure a new request can be handled
- new_call = multi_callable(request)
- for response in new_call:
- self.assertEqual(_RESPONSE, response)
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_rpc_part_1_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_rpc_part_1_test.py
deleted file mode 100644
index 0ffa9eff94f..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_rpc_part_1_test.py
+++ /dev/null
@@ -1,241 +0,0 @@
-# Copyright 2016 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Test of RPCs made against gRPC Python's application-layer API."""
-
-from concurrent import futures
-import itertools
-import logging
-import threading
-import unittest
-
-import grpc
-from grpc.framework.foundation import logging_pool
-
-from tests.unit import test_common
-from tests.unit._rpc_test_helpers import BaseRPCTest
-from tests.unit._rpc_test_helpers import Callback
-from tests.unit._rpc_test_helpers import TIMEOUT_SHORT
-from tests.unit._rpc_test_helpers import \
- stream_stream_non_blocking_multi_callable
-from tests.unit._rpc_test_helpers import \
- unary_stream_non_blocking_multi_callable
-from tests.unit._rpc_test_helpers import stream_stream_multi_callable
-from tests.unit._rpc_test_helpers import stream_unary_multi_callable
-from tests.unit._rpc_test_helpers import unary_stream_multi_callable
-from tests.unit._rpc_test_helpers import unary_unary_multi_callable
-from tests.unit.framework.common import test_constants
-
-
-@unittest.skipIf(test_common.running_under_gevent(),
- "This test is nondeterministic under gevent.")
-class RPCPart1Test(BaseRPCTest, unittest.TestCase):
-
- def testExpiredStreamRequestBlockingUnaryResponse(self):
- requests = tuple(
- b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
- request_iterator = iter(requests)
-
- multi_callable = stream_unary_multi_callable(self._channel)
- with self._control.pause():
- with self.assertRaises(grpc.RpcError) as exception_context:
- multi_callable(
- request_iterator,
- timeout=TIMEOUT_SHORT,
- metadata=(('test',
- 'ExpiredStreamRequestBlockingUnaryResponse'),))
-
- self.assertIsInstance(exception_context.exception, grpc.RpcError)
- self.assertIsInstance(exception_context.exception, grpc.Call)
- self.assertIsNotNone(exception_context.exception.initial_metadata())
- self.assertIs(grpc.StatusCode.DEADLINE_EXCEEDED,
- exception_context.exception.code())
- self.assertIsNotNone(exception_context.exception.details())
- self.assertIsNotNone(exception_context.exception.trailing_metadata())
-
- def testExpiredStreamRequestFutureUnaryResponse(self):
- requests = tuple(
- b'\x07\x18' for _ in range(test_constants.STREAM_LENGTH))
- request_iterator = iter(requests)
- callback = Callback()
-
- multi_callable = stream_unary_multi_callable(self._channel)
- with self._control.pause():
- response_future = multi_callable.future(
- request_iterator,
- timeout=TIMEOUT_SHORT,
- metadata=(('test', 'ExpiredStreamRequestFutureUnaryResponse'),))
- with self.assertRaises(grpc.FutureTimeoutError):
- response_future.result(timeout=TIMEOUT_SHORT / 2.0)
- response_future.add_done_callback(callback)
- value_passed_to_callback = callback.value()
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- response_future.result()
- self.assertIs(grpc.StatusCode.DEADLINE_EXCEEDED, response_future.code())
- self.assertIs(grpc.StatusCode.DEADLINE_EXCEEDED,
- exception_context.exception.code())
- self.assertIsInstance(response_future.exception(), grpc.RpcError)
- self.assertIsNotNone(response_future.traceback())
- self.assertIs(response_future, value_passed_to_callback)
- self.assertIsNotNone(response_future.initial_metadata())
- self.assertIs(grpc.StatusCode.DEADLINE_EXCEEDED, response_future.code())
- self.assertIsNotNone(response_future.details())
- self.assertIsNotNone(response_future.trailing_metadata())
-
- def testExpiredStreamRequestStreamResponse(self):
- self._expired_stream_request_stream_response(
- stream_stream_multi_callable(self._channel))
-
- def testExpiredStreamRequestStreamResponseNonBlocking(self):
- self._expired_stream_request_stream_response(
- stream_stream_non_blocking_multi_callable(self._channel))
-
- def testFailedUnaryRequestBlockingUnaryResponse(self):
- request = b'\x37\x17'
-
- multi_callable = unary_unary_multi_callable(self._channel)
- with self._control.fail():
- with self.assertRaises(grpc.RpcError) as exception_context:
- multi_callable.with_call(
- request,
- metadata=(('test',
- 'FailedUnaryRequestBlockingUnaryResponse'),))
-
- self.assertIs(grpc.StatusCode.UNKNOWN,
- exception_context.exception.code())
- # sanity checks on to make sure returned string contains default members
- # of the error
- debug_error_string = exception_context.exception.debug_error_string()
- self.assertIn('created', debug_error_string)
- self.assertIn('description', debug_error_string)
- self.assertIn('file', debug_error_string)
- self.assertIn('file_line', debug_error_string)
-
- def testFailedUnaryRequestFutureUnaryResponse(self):
- request = b'\x37\x17'
- callback = Callback()
-
- multi_callable = unary_unary_multi_callable(self._channel)
- with self._control.fail():
- response_future = multi_callable.future(
- request,
- metadata=(('test', 'FailedUnaryRequestFutureUnaryResponse'),))
- response_future.add_done_callback(callback)
- value_passed_to_callback = callback.value()
-
- self.assertIsInstance(response_future, grpc.Future)
- self.assertIsInstance(response_future, grpc.Call)
- with self.assertRaises(grpc.RpcError) as exception_context:
- response_future.result()
- self.assertIs(grpc.StatusCode.UNKNOWN,
- exception_context.exception.code())
- self.assertIsInstance(response_future.exception(), grpc.RpcError)
- self.assertIsNotNone(response_future.traceback())
- self.assertIs(grpc.StatusCode.UNKNOWN,
- response_future.exception().code())
- self.assertIs(response_future, value_passed_to_callback)
-
- def testFailedUnaryRequestStreamResponse(self):
- self._failed_unary_request_stream_response(
- unary_stream_multi_callable(self._channel))
-
- def testFailedUnaryRequestStreamResponseNonBlocking(self):
- self._failed_unary_request_stream_response(
- unary_stream_non_blocking_multi_callable(self._channel))
-
- def testFailedStreamRequestBlockingUnaryResponse(self):
- requests = tuple(
- b'\x47\x58' for _ in range(test_constants.STREAM_LENGTH))
- request_iterator = iter(requests)
-
- multi_callable = stream_unary_multi_callable(self._channel)
- with self._control.fail():
- with self.assertRaises(grpc.RpcError) as exception_context:
- multi_callable(
- request_iterator,
- metadata=(('test',
- 'FailedStreamRequestBlockingUnaryResponse'),))
-
- self.assertIs(grpc.StatusCode.UNKNOWN,
- exception_context.exception.code())
-
- def testFailedStreamRequestFutureUnaryResponse(self):
- requests = tuple(
- b'\x07\x18' for _ in range(test_constants.STREAM_LENGTH))
- request_iterator = iter(requests)
- callback = Callback()
-
- multi_callable = stream_unary_multi_callable(self._channel)
- with self._control.fail():
- response_future = multi_callable.future(
- request_iterator,
- metadata=(('test', 'FailedStreamRequestFutureUnaryResponse'),))
- response_future.add_done_callback(callback)
- value_passed_to_callback = callback.value()
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- response_future.result()
- self.assertIs(grpc.StatusCode.UNKNOWN, response_future.code())
- self.assertIs(grpc.StatusCode.UNKNOWN,
- exception_context.exception.code())
- self.assertIsInstance(response_future.exception(), grpc.RpcError)
- self.assertIsNotNone(response_future.traceback())
- self.assertIs(response_future, value_passed_to_callback)
-
- def testFailedStreamRequestStreamResponse(self):
- self._failed_stream_request_stream_response(
- stream_stream_multi_callable(self._channel))
-
- def testFailedStreamRequestStreamResponseNonBlocking(self):
- self._failed_stream_request_stream_response(
- stream_stream_non_blocking_multi_callable(self._channel))
-
- def testIgnoredUnaryRequestFutureUnaryResponse(self):
- request = b'\x37\x17'
-
- multi_callable = unary_unary_multi_callable(self._channel)
- multi_callable.future(
- request,
- metadata=(('test', 'IgnoredUnaryRequestFutureUnaryResponse'),))
-
- def testIgnoredUnaryRequestStreamResponse(self):
- self._ignored_unary_stream_request_future_unary_response(
- unary_stream_multi_callable(self._channel))
-
- def testIgnoredUnaryRequestStreamResponseNonBlocking(self):
- self._ignored_unary_stream_request_future_unary_response(
- unary_stream_non_blocking_multi_callable(self._channel))
-
- def testIgnoredStreamRequestFutureUnaryResponse(self):
- requests = tuple(
- b'\x07\x18' for _ in range(test_constants.STREAM_LENGTH))
- request_iterator = iter(requests)
-
- multi_callable = stream_unary_multi_callable(self._channel)
- multi_callable.future(
- request_iterator,
- metadata=(('test', 'IgnoredStreamRequestFutureUnaryResponse'),))
-
- def testIgnoredStreamRequestStreamResponse(self):
- self._ignored_stream_request_stream_response(
- stream_stream_multi_callable(self._channel))
-
- def testIgnoredStreamRequestStreamResponseNonBlocking(self):
- self._ignored_stream_request_stream_response(
- stream_stream_non_blocking_multi_callable(self._channel))
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_rpc_part_2_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_rpc_part_2_test.py
deleted file mode 100644
index 6a82a9588f6..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_rpc_part_2_test.py
+++ /dev/null
@@ -1,435 +0,0 @@
-# Copyright 2016 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Test of RPCs made against gRPC Python's application-layer API."""
-
-from concurrent import futures
-import itertools
-import logging
-import threading
-import unittest
-
-import grpc
-from grpc.framework.foundation import logging_pool
-
-from tests.unit import test_common
-from tests.unit._rpc_test_helpers import BaseRPCTest
-from tests.unit._rpc_test_helpers import Callback
-from tests.unit._rpc_test_helpers import TIMEOUT_SHORT
-from tests.unit._rpc_test_helpers import \
- stream_stream_non_blocking_multi_callable
-from tests.unit._rpc_test_helpers import \
- unary_stream_non_blocking_multi_callable
-from tests.unit._rpc_test_helpers import stream_stream_multi_callable
-from tests.unit._rpc_test_helpers import stream_unary_multi_callable
-from tests.unit._rpc_test_helpers import unary_stream_multi_callable
-from tests.unit._rpc_test_helpers import unary_unary_multi_callable
-from tests.unit.framework.common import test_constants
-
-
-@unittest.skipIf(test_common.running_under_gevent(),
- "Causes deadlock under gevent.")
-class RPCPart2Test(BaseRPCTest, unittest.TestCase):
-
- def testDefaultThreadPoolIsUsed(self):
- self._consume_one_stream_response_unary_request(
- unary_stream_multi_callable(self._channel))
- self.assertFalse(self._thread_pool.was_used())
-
- def testExperimentalThreadPoolIsUsed(self):
- self._consume_one_stream_response_unary_request(
- unary_stream_non_blocking_multi_callable(self._channel))
- self.assertTrue(self._thread_pool.was_used())
-
- def testUnrecognizedMethod(self):
- request = b'abc'
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- self._channel.unary_unary('NoSuchMethod')(request)
-
- self.assertEqual(grpc.StatusCode.UNIMPLEMENTED,
- exception_context.exception.code())
-
- def testSuccessfulUnaryRequestBlockingUnaryResponse(self):
- request = b'\x07\x08'
- expected_response = self._handler.handle_unary_unary(request, None)
-
- multi_callable = unary_unary_multi_callable(self._channel)
- response = multi_callable(
- request,
- metadata=(('test', 'SuccessfulUnaryRequestBlockingUnaryResponse'),))
-
- self.assertEqual(expected_response, response)
-
- def testSuccessfulUnaryRequestBlockingUnaryResponseWithCall(self):
- request = b'\x07\x08'
- expected_response = self._handler.handle_unary_unary(request, None)
-
- multi_callable = unary_unary_multi_callable(self._channel)
- response, call = multi_callable.with_call(
- request,
- metadata=(('test',
- 'SuccessfulUnaryRequestBlockingUnaryResponseWithCall'),))
-
- self.assertEqual(expected_response, response)
- self.assertIs(grpc.StatusCode.OK, call.code())
- self.assertEqual('', call.debug_error_string())
-
- def testSuccessfulUnaryRequestFutureUnaryResponse(self):
- request = b'\x07\x08'
- expected_response = self._handler.handle_unary_unary(request, None)
-
- multi_callable = unary_unary_multi_callable(self._channel)
- response_future = multi_callable.future(
- request,
- metadata=(('test', 'SuccessfulUnaryRequestFutureUnaryResponse'),))
- response = response_future.result()
-
- self.assertIsInstance(response_future, grpc.Future)
- self.assertIsInstance(response_future, grpc.Call)
- self.assertEqual(expected_response, response)
- self.assertIsNone(response_future.exception())
- self.assertIsNone(response_future.traceback())
-
- def testSuccessfulUnaryRequestStreamResponse(self):
- request = b'\x37\x58'
- expected_responses = tuple(
- self._handler.handle_unary_stream(request, None))
-
- multi_callable = unary_stream_multi_callable(self._channel)
- response_iterator = multi_callable(
- request,
- metadata=(('test', 'SuccessfulUnaryRequestStreamResponse'),))
- responses = tuple(response_iterator)
-
- self.assertSequenceEqual(expected_responses, responses)
-
- def testSuccessfulStreamRequestBlockingUnaryResponse(self):
- requests = tuple(
- b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
- expected_response = self._handler.handle_stream_unary(
- iter(requests), None)
- request_iterator = iter(requests)
-
- multi_callable = stream_unary_multi_callable(self._channel)
- response = multi_callable(
- request_iterator,
- metadata=(('test',
- 'SuccessfulStreamRequestBlockingUnaryResponse'),))
-
- self.assertEqual(expected_response, response)
-
- def testSuccessfulStreamRequestBlockingUnaryResponseWithCall(self):
- requests = tuple(
- b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
- expected_response = self._handler.handle_stream_unary(
- iter(requests), None)
- request_iterator = iter(requests)
-
- multi_callable = stream_unary_multi_callable(self._channel)
- response, call = multi_callable.with_call(
- request_iterator,
- metadata=(
- ('test',
- 'SuccessfulStreamRequestBlockingUnaryResponseWithCall'),))
-
- self.assertEqual(expected_response, response)
- self.assertIs(grpc.StatusCode.OK, call.code())
-
- def testSuccessfulStreamRequestFutureUnaryResponse(self):
- requests = tuple(
- b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
- expected_response = self._handler.handle_stream_unary(
- iter(requests), None)
- request_iterator = iter(requests)
-
- multi_callable = stream_unary_multi_callable(self._channel)
- response_future = multi_callable.future(
- request_iterator,
- metadata=(('test', 'SuccessfulStreamRequestFutureUnaryResponse'),))
- response = response_future.result()
-
- self.assertEqual(expected_response, response)
- self.assertIsNone(response_future.exception())
- self.assertIsNone(response_future.traceback())
-
- def testSuccessfulStreamRequestStreamResponse(self):
- requests = tuple(
- b'\x77\x58' for _ in range(test_constants.STREAM_LENGTH))
-
- expected_responses = tuple(
- self._handler.handle_stream_stream(iter(requests), None))
- request_iterator = iter(requests)
-
- multi_callable = stream_stream_multi_callable(self._channel)
- response_iterator = multi_callable(
- request_iterator,
- metadata=(('test', 'SuccessfulStreamRequestStreamResponse'),))
- responses = tuple(response_iterator)
-
- self.assertSequenceEqual(expected_responses, responses)
-
- def testSequentialInvocations(self):
- first_request = b'\x07\x08'
- second_request = b'\x0809'
- expected_first_response = self._handler.handle_unary_unary(
- first_request, None)
- expected_second_response = self._handler.handle_unary_unary(
- second_request, None)
-
- multi_callable = unary_unary_multi_callable(self._channel)
- first_response = multi_callable(first_request,
- metadata=(('test',
- 'SequentialInvocations'),))
- second_response = multi_callable(second_request,
- metadata=(('test',
- 'SequentialInvocations'),))
-
- self.assertEqual(expected_first_response, first_response)
- self.assertEqual(expected_second_response, second_response)
-
- def testConcurrentBlockingInvocations(self):
- pool = logging_pool.pool(test_constants.THREAD_CONCURRENCY)
- requests = tuple(
- b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
- expected_response = self._handler.handle_stream_unary(
- iter(requests), None)
- expected_responses = [expected_response
- ] * test_constants.THREAD_CONCURRENCY
- response_futures = [None] * test_constants.THREAD_CONCURRENCY
-
- multi_callable = stream_unary_multi_callable(self._channel)
- for index in range(test_constants.THREAD_CONCURRENCY):
- request_iterator = iter(requests)
- response_future = pool.submit(
- multi_callable,
- request_iterator,
- metadata=(('test', 'ConcurrentBlockingInvocations'),))
- response_futures[index] = response_future
- responses = tuple(
- response_future.result() for response_future in response_futures)
-
- pool.shutdown(wait=True)
- self.assertSequenceEqual(expected_responses, responses)
-
- def testConcurrentFutureInvocations(self):
- requests = tuple(
- b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
- expected_response = self._handler.handle_stream_unary(
- iter(requests), None)
- expected_responses = [expected_response
- ] * test_constants.THREAD_CONCURRENCY
- response_futures = [None] * test_constants.THREAD_CONCURRENCY
-
- multi_callable = stream_unary_multi_callable(self._channel)
- for index in range(test_constants.THREAD_CONCURRENCY):
- request_iterator = iter(requests)
- response_future = multi_callable.future(
- request_iterator,
- metadata=(('test', 'ConcurrentFutureInvocations'),))
- response_futures[index] = response_future
- responses = tuple(
- response_future.result() for response_future in response_futures)
-
- self.assertSequenceEqual(expected_responses, responses)
-
- def testWaitingForSomeButNotAllConcurrentFutureInvocations(self):
- pool = logging_pool.pool(test_constants.THREAD_CONCURRENCY)
- request = b'\x67\x68'
- expected_response = self._handler.handle_unary_unary(request, None)
- response_futures = [None] * test_constants.THREAD_CONCURRENCY
- lock = threading.Lock()
- test_is_running_cell = [True]
-
- def wrap_future(future):
-
- def wrap():
- try:
- return future.result()
- except grpc.RpcError:
- with lock:
- if test_is_running_cell[0]:
- raise
- return None
-
- return wrap
-
- multi_callable = unary_unary_multi_callable(self._channel)
- for index in range(test_constants.THREAD_CONCURRENCY):
- inner_response_future = multi_callable.future(
- request,
- metadata=(
- ('test',
- 'WaitingForSomeButNotAllConcurrentFutureInvocations'),))
- outer_response_future = pool.submit(
- wrap_future(inner_response_future))
- response_futures[index] = outer_response_future
-
- some_completed_response_futures_iterator = itertools.islice(
- futures.as_completed(response_futures),
- test_constants.THREAD_CONCURRENCY // 2)
- for response_future in some_completed_response_futures_iterator:
- self.assertEqual(expected_response, response_future.result())
- with lock:
- test_is_running_cell[0] = False
-
- def testConsumingOneStreamResponseUnaryRequest(self):
- self._consume_one_stream_response_unary_request(
- unary_stream_multi_callable(self._channel))
-
- def testConsumingOneStreamResponseUnaryRequestNonBlocking(self):
- self._consume_one_stream_response_unary_request(
- unary_stream_non_blocking_multi_callable(self._channel))
-
- def testConsumingSomeButNotAllStreamResponsesUnaryRequest(self):
- self._consume_some_but_not_all_stream_responses_unary_request(
- unary_stream_multi_callable(self._channel))
-
- def testConsumingSomeButNotAllStreamResponsesUnaryRequestNonBlocking(self):
- self._consume_some_but_not_all_stream_responses_unary_request(
- unary_stream_non_blocking_multi_callable(self._channel))
-
- def testConsumingSomeButNotAllStreamResponsesStreamRequest(self):
- self._consume_some_but_not_all_stream_responses_stream_request(
- stream_stream_multi_callable(self._channel))
-
- def testConsumingSomeButNotAllStreamResponsesStreamRequestNonBlocking(self):
- self._consume_some_but_not_all_stream_responses_stream_request(
- stream_stream_non_blocking_multi_callable(self._channel))
-
- def testConsumingTooManyStreamResponsesStreamRequest(self):
- self._consume_too_many_stream_responses_stream_request(
- stream_stream_multi_callable(self._channel))
-
- def testConsumingTooManyStreamResponsesStreamRequestNonBlocking(self):
- self._consume_too_many_stream_responses_stream_request(
- stream_stream_non_blocking_multi_callable(self._channel))
-
- def testCancelledUnaryRequestUnaryResponse(self):
- request = b'\x07\x17'
-
- multi_callable = unary_unary_multi_callable(self._channel)
- with self._control.pause():
- response_future = multi_callable.future(
- request,
- metadata=(('test', 'CancelledUnaryRequestUnaryResponse'),))
- response_future.cancel()
-
- self.assertIs(grpc.StatusCode.CANCELLED, response_future.code())
- self.assertTrue(response_future.cancelled())
- with self.assertRaises(grpc.FutureCancelledError):
- response_future.result()
- with self.assertRaises(grpc.FutureCancelledError):
- response_future.exception()
- with self.assertRaises(grpc.FutureCancelledError):
- response_future.traceback()
-
- def testCancelledUnaryRequestStreamResponse(self):
- self._cancelled_unary_request_stream_response(
- unary_stream_multi_callable(self._channel))
-
- def testCancelledUnaryRequestStreamResponseNonBlocking(self):
- self._cancelled_unary_request_stream_response(
- unary_stream_non_blocking_multi_callable(self._channel))
-
- def testCancelledStreamRequestUnaryResponse(self):
- requests = tuple(
- b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
- request_iterator = iter(requests)
-
- multi_callable = stream_unary_multi_callable(self._channel)
- with self._control.pause():
- response_future = multi_callable.future(
- request_iterator,
- metadata=(('test', 'CancelledStreamRequestUnaryResponse'),))
- self._control.block_until_paused()
- response_future.cancel()
-
- self.assertIs(grpc.StatusCode.CANCELLED, response_future.code())
- self.assertTrue(response_future.cancelled())
- with self.assertRaises(grpc.FutureCancelledError):
- response_future.result()
- with self.assertRaises(grpc.FutureCancelledError):
- response_future.exception()
- with self.assertRaises(grpc.FutureCancelledError):
- response_future.traceback()
- self.assertIsNotNone(response_future.initial_metadata())
- self.assertIsNotNone(response_future.details())
- self.assertIsNotNone(response_future.trailing_metadata())
-
- def testCancelledStreamRequestStreamResponse(self):
- self._cancelled_stream_request_stream_response(
- stream_stream_multi_callable(self._channel))
-
- def testCancelledStreamRequestStreamResponseNonBlocking(self):
- self._cancelled_stream_request_stream_response(
- stream_stream_non_blocking_multi_callable(self._channel))
-
- def testExpiredUnaryRequestBlockingUnaryResponse(self):
- request = b'\x07\x17'
-
- multi_callable = unary_unary_multi_callable(self._channel)
- with self._control.pause():
- with self.assertRaises(grpc.RpcError) as exception_context:
- multi_callable.with_call(
- request,
- timeout=TIMEOUT_SHORT,
- metadata=(('test',
- 'ExpiredUnaryRequestBlockingUnaryResponse'),))
-
- self.assertIsInstance(exception_context.exception, grpc.Call)
- self.assertIsNotNone(exception_context.exception.initial_metadata())
- self.assertIs(grpc.StatusCode.DEADLINE_EXCEEDED,
- exception_context.exception.code())
- self.assertIsNotNone(exception_context.exception.details())
- self.assertIsNotNone(exception_context.exception.trailing_metadata())
-
- def testExpiredUnaryRequestFutureUnaryResponse(self):
- request = b'\x07\x17'
- callback = Callback()
-
- multi_callable = unary_unary_multi_callable(self._channel)
- with self._control.pause():
- response_future = multi_callable.future(
- request,
- timeout=TIMEOUT_SHORT,
- metadata=(('test', 'ExpiredUnaryRequestFutureUnaryResponse'),))
- response_future.add_done_callback(callback)
- value_passed_to_callback = callback.value()
-
- self.assertIs(response_future, value_passed_to_callback)
- self.assertIsNotNone(response_future.initial_metadata())
- self.assertIs(grpc.StatusCode.DEADLINE_EXCEEDED, response_future.code())
- self.assertIsNotNone(response_future.details())
- self.assertIsNotNone(response_future.trailing_metadata())
- with self.assertRaises(grpc.RpcError) as exception_context:
- response_future.result()
- self.assertIs(grpc.StatusCode.DEADLINE_EXCEEDED,
- exception_context.exception.code())
- self.assertIsInstance(response_future.exception(), grpc.RpcError)
- self.assertIsNotNone(response_future.traceback())
- self.assertIs(grpc.StatusCode.DEADLINE_EXCEEDED,
- response_future.exception().code())
-
- def testExpiredUnaryRequestStreamResponse(self):
- self._expired_unary_request_stream_response(
- unary_stream_multi_callable(self._channel))
-
- def testExpiredUnaryRequestStreamResponseNonBlocking(self):
- self._expired_unary_request_stream_response(
- unary_stream_non_blocking_multi_callable(self._channel))
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_rpc_test_helpers.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_rpc_test_helpers.py
deleted file mode 100644
index a3f18a9a490..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_rpc_test_helpers.py
+++ /dev/null
@@ -1,417 +0,0 @@
-# Copyright 2020 The gRPC Authors
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Test helpers for RPC invocation tests."""
-
-import datetime
-import threading
-
-import grpc
-from grpc.framework.foundation import logging_pool
-
-from tests.unit import test_common
-from tests.unit import thread_pool
-from tests.unit.framework.common import test_constants
-from tests.unit.framework.common import test_control
-
-_SERIALIZE_REQUEST = lambda bytestring: bytestring * 2
-_DESERIALIZE_REQUEST = lambda bytestring: bytestring[len(bytestring) // 2:]
-_SERIALIZE_RESPONSE = lambda bytestring: bytestring * 3
-_DESERIALIZE_RESPONSE = lambda bytestring: bytestring[:len(bytestring) // 3]
-
-_UNARY_UNARY = '/test/UnaryUnary'
-_UNARY_STREAM = '/test/UnaryStream'
-_UNARY_STREAM_NON_BLOCKING = '/test/UnaryStreamNonBlocking'
-_STREAM_UNARY = '/test/StreamUnary'
-_STREAM_STREAM = '/test/StreamStream'
-_STREAM_STREAM_NON_BLOCKING = '/test/StreamStreamNonBlocking'
-
-TIMEOUT_SHORT = datetime.timedelta(seconds=1).total_seconds()
-
-
-class Callback(object):
-
- def __init__(self):
- self._condition = threading.Condition()
- self._value = None
- self._called = False
-
- def __call__(self, value):
- with self._condition:
- self._value = value
- self._called = True
- self._condition.notify_all()
-
- def value(self):
- with self._condition:
- while not self._called:
- self._condition.wait()
- return self._value
-
-
-class _Handler(object):
-
- def __init__(self, control, thread_pool):
- self._control = control
- self._thread_pool = thread_pool
- non_blocking_functions = (self.handle_unary_stream_non_blocking,
- self.handle_stream_stream_non_blocking)
- for non_blocking_function in non_blocking_functions:
- non_blocking_function.__func__.experimental_non_blocking = True
- non_blocking_function.__func__.experimental_thread_pool = self._thread_pool
-
- def handle_unary_unary(self, request, servicer_context):
- self._control.control()
- if servicer_context is not None:
- servicer_context.set_trailing_metadata(((
- 'testkey',
- 'testvalue',
- ),))
- # TODO(https://github.com/grpc/grpc/issues/8483): test the values
- # returned by these methods rather than only "smoke" testing that
- # the return after having been called.
- servicer_context.is_active()
- servicer_context.time_remaining()
- return request
-
- def handle_unary_stream(self, request, servicer_context):
- for _ in range(test_constants.STREAM_LENGTH):
- self._control.control()
- yield request
- self._control.control()
- if servicer_context is not None:
- servicer_context.set_trailing_metadata(((
- 'testkey',
- 'testvalue',
- ),))
-
- def handle_unary_stream_non_blocking(self, request, servicer_context,
- on_next):
- for _ in range(test_constants.STREAM_LENGTH):
- self._control.control()
- on_next(request)
- self._control.control()
- if servicer_context is not None:
- servicer_context.set_trailing_metadata(((
- 'testkey',
- 'testvalue',
- ),))
- on_next(None)
-
- def handle_stream_unary(self, request_iterator, servicer_context):
- if servicer_context is not None:
- servicer_context.invocation_metadata()
- self._control.control()
- response_elements = []
- for request in request_iterator:
- self._control.control()
- response_elements.append(request)
- self._control.control()
- if servicer_context is not None:
- servicer_context.set_trailing_metadata(((
- 'testkey',
- 'testvalue',
- ),))
- return b''.join(response_elements)
-
- def handle_stream_stream(self, request_iterator, servicer_context):
- self._control.control()
- if servicer_context is not None:
- servicer_context.set_trailing_metadata(((
- 'testkey',
- 'testvalue',
- ),))
- for request in request_iterator:
- self._control.control()
- yield request
- self._control.control()
-
- def handle_stream_stream_non_blocking(self, request_iterator,
- servicer_context, on_next):
- self._control.control()
- if servicer_context is not None:
- servicer_context.set_trailing_metadata(((
- 'testkey',
- 'testvalue',
- ),))
- for request in request_iterator:
- self._control.control()
- on_next(request)
- self._control.control()
- on_next(None)
-
-
-class _MethodHandler(grpc.RpcMethodHandler):
-
- def __init__(self, request_streaming, response_streaming,
- request_deserializer, response_serializer, unary_unary,
- unary_stream, stream_unary, stream_stream):
- self.request_streaming = request_streaming
- self.response_streaming = response_streaming
- self.request_deserializer = request_deserializer
- self.response_serializer = response_serializer
- self.unary_unary = unary_unary
- self.unary_stream = unary_stream
- self.stream_unary = stream_unary
- self.stream_stream = stream_stream
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def __init__(self, handler):
- self._handler = handler
-
- def service(self, handler_call_details):
- if handler_call_details.method == _UNARY_UNARY:
- return _MethodHandler(False, False, None, None,
- self._handler.handle_unary_unary, None, None,
- None)
- elif handler_call_details.method == _UNARY_STREAM:
- return _MethodHandler(False, True, _DESERIALIZE_REQUEST,
- _SERIALIZE_RESPONSE, None,
- self._handler.handle_unary_stream, None, None)
- elif handler_call_details.method == _UNARY_STREAM_NON_BLOCKING:
- return _MethodHandler(
- False, True, _DESERIALIZE_REQUEST, _SERIALIZE_RESPONSE, None,
- self._handler.handle_unary_stream_non_blocking, None, None)
- elif handler_call_details.method == _STREAM_UNARY:
- return _MethodHandler(True, False, _DESERIALIZE_REQUEST,
- _SERIALIZE_RESPONSE, None, None,
- self._handler.handle_stream_unary, None)
- elif handler_call_details.method == _STREAM_STREAM:
- return _MethodHandler(True, True, None, None, None, None, None,
- self._handler.handle_stream_stream)
- elif handler_call_details.method == _STREAM_STREAM_NON_BLOCKING:
- return _MethodHandler(
- True, True, None, None, None, None, None,
- self._handler.handle_stream_stream_non_blocking)
- else:
- return None
-
-
-def unary_unary_multi_callable(channel):
- return channel.unary_unary(_UNARY_UNARY)
-
-
-def unary_stream_multi_callable(channel):
- return channel.unary_stream(_UNARY_STREAM,
- request_serializer=_SERIALIZE_REQUEST,
- response_deserializer=_DESERIALIZE_RESPONSE)
-
-
-def unary_stream_non_blocking_multi_callable(channel):
- return channel.unary_stream(_UNARY_STREAM_NON_BLOCKING,
- request_serializer=_SERIALIZE_REQUEST,
- response_deserializer=_DESERIALIZE_RESPONSE)
-
-
-def stream_unary_multi_callable(channel):
- return channel.stream_unary(_STREAM_UNARY,
- request_serializer=_SERIALIZE_REQUEST,
- response_deserializer=_DESERIALIZE_RESPONSE)
-
-
-def stream_stream_multi_callable(channel):
- return channel.stream_stream(_STREAM_STREAM)
-
-
-def stream_stream_non_blocking_multi_callable(channel):
- return channel.stream_stream(_STREAM_STREAM_NON_BLOCKING)
-
-
-class BaseRPCTest(object):
-
- def setUp(self):
- self._control = test_control.PauseFailControl()
- self._thread_pool = thread_pool.RecordingThreadPool(max_workers=None)
- self._handler = _Handler(self._control, self._thread_pool)
-
- self._server = test_common.test_server()
- port = self._server.add_insecure_port('[::]:0')
- self._server.add_generic_rpc_handlers((_GenericHandler(self._handler),))
- self._server.start()
-
- self._channel = grpc.insecure_channel('localhost:%d' % port)
-
- def tearDown(self):
- self._server.stop(None)
- self._channel.close()
-
- def _consume_one_stream_response_unary_request(self, multi_callable):
- request = b'\x57\x38'
-
- response_iterator = multi_callable(
- request,
- metadata=(('test', 'ConsumingOneStreamResponseUnaryRequest'),))
- next(response_iterator)
-
- def _consume_some_but_not_all_stream_responses_unary_request(
- self, multi_callable):
- request = b'\x57\x38'
-
- response_iterator = multi_callable(
- request,
- metadata=(('test',
- 'ConsumingSomeButNotAllStreamResponsesUnaryRequest'),))
- for _ in range(test_constants.STREAM_LENGTH // 2):
- next(response_iterator)
-
- def _consume_some_but_not_all_stream_responses_stream_request(
- self, multi_callable):
- requests = tuple(
- b'\x67\x88' for _ in range(test_constants.STREAM_LENGTH))
- request_iterator = iter(requests)
-
- response_iterator = multi_callable(
- request_iterator,
- metadata=(('test',
- 'ConsumingSomeButNotAllStreamResponsesStreamRequest'),))
- for _ in range(test_constants.STREAM_LENGTH // 2):
- next(response_iterator)
-
- def _consume_too_many_stream_responses_stream_request(self, multi_callable):
- requests = tuple(
- b'\x67\x88' for _ in range(test_constants.STREAM_LENGTH))
- request_iterator = iter(requests)
-
- response_iterator = multi_callable(
- request_iterator,
- metadata=(('test',
- 'ConsumingTooManyStreamResponsesStreamRequest'),))
- for _ in range(test_constants.STREAM_LENGTH):
- next(response_iterator)
- for _ in range(test_constants.STREAM_LENGTH):
- with self.assertRaises(StopIteration):
- next(response_iterator)
-
- self.assertIsNotNone(response_iterator.initial_metadata())
- self.assertIs(grpc.StatusCode.OK, response_iterator.code())
- self.assertIsNotNone(response_iterator.details())
- self.assertIsNotNone(response_iterator.trailing_metadata())
-
- def _cancelled_unary_request_stream_response(self, multi_callable):
- request = b'\x07\x19'
-
- with self._control.pause():
- response_iterator = multi_callable(
- request,
- metadata=(('test', 'CancelledUnaryRequestStreamResponse'),))
- self._control.block_until_paused()
- response_iterator.cancel()
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- next(response_iterator)
- self.assertIs(grpc.StatusCode.CANCELLED,
- exception_context.exception.code())
- self.assertIsNotNone(response_iterator.initial_metadata())
- self.assertIs(grpc.StatusCode.CANCELLED, response_iterator.code())
- self.assertIsNotNone(response_iterator.details())
- self.assertIsNotNone(response_iterator.trailing_metadata())
-
- def _cancelled_stream_request_stream_response(self, multi_callable):
- requests = tuple(
- b'\x07\x08' for _ in range(test_constants.STREAM_LENGTH))
- request_iterator = iter(requests)
-
- with self._control.pause():
- response_iterator = multi_callable(
- request_iterator,
- metadata=(('test', 'CancelledStreamRequestStreamResponse'),))
- response_iterator.cancel()
-
- with self.assertRaises(grpc.RpcError):
- next(response_iterator)
- self.assertIsNotNone(response_iterator.initial_metadata())
- self.assertIs(grpc.StatusCode.CANCELLED, response_iterator.code())
- self.assertIsNotNone(response_iterator.details())
- self.assertIsNotNone(response_iterator.trailing_metadata())
-
- def _expired_unary_request_stream_response(self, multi_callable):
- request = b'\x07\x19'
-
- with self._control.pause():
- with self.assertRaises(grpc.RpcError) as exception_context:
- response_iterator = multi_callable(
- request,
- timeout=test_constants.SHORT_TIMEOUT,
- metadata=(('test', 'ExpiredUnaryRequestStreamResponse'),))
- next(response_iterator)
-
- self.assertIs(grpc.StatusCode.DEADLINE_EXCEEDED,
- exception_context.exception.code())
- self.assertIs(grpc.StatusCode.DEADLINE_EXCEEDED,
- response_iterator.code())
-
- def _expired_stream_request_stream_response(self, multi_callable):
- requests = tuple(
- b'\x67\x18' for _ in range(test_constants.STREAM_LENGTH))
- request_iterator = iter(requests)
-
- with self._control.pause():
- with self.assertRaises(grpc.RpcError) as exception_context:
- response_iterator = multi_callable(
- request_iterator,
- timeout=test_constants.SHORT_TIMEOUT,
- metadata=(('test', 'ExpiredStreamRequestStreamResponse'),))
- next(response_iterator)
-
- self.assertIs(grpc.StatusCode.DEADLINE_EXCEEDED,
- exception_context.exception.code())
- self.assertIs(grpc.StatusCode.DEADLINE_EXCEEDED,
- response_iterator.code())
-
- def _failed_unary_request_stream_response(self, multi_callable):
- request = b'\x37\x17'
-
- with self.assertRaises(grpc.RpcError) as exception_context:
- with self._control.fail():
- response_iterator = multi_callable(
- request,
- metadata=(('test', 'FailedUnaryRequestStreamResponse'),))
- next(response_iterator)
-
- self.assertIs(grpc.StatusCode.UNKNOWN,
- exception_context.exception.code())
-
- def _failed_stream_request_stream_response(self, multi_callable):
- requests = tuple(
- b'\x67\x88' for _ in range(test_constants.STREAM_LENGTH))
- request_iterator = iter(requests)
-
- with self._control.fail():
- with self.assertRaises(grpc.RpcError) as exception_context:
- response_iterator = multi_callable(
- request_iterator,
- metadata=(('test', 'FailedStreamRequestStreamResponse'),))
- tuple(response_iterator)
-
- self.assertIs(grpc.StatusCode.UNKNOWN,
- exception_context.exception.code())
- self.assertIs(grpc.StatusCode.UNKNOWN, response_iterator.code())
-
- def _ignored_unary_stream_request_future_unary_response(
- self, multi_callable):
- request = b'\x37\x17'
-
- multi_callable(request,
- metadata=(('test',
- 'IgnoredUnaryRequestStreamResponse'),))
-
- def _ignored_stream_request_stream_response(self, multi_callable):
- requests = tuple(
- b'\x67\x88' for _ in range(test_constants.STREAM_LENGTH))
- request_iterator = iter(requests)
-
- multi_callable(request_iterator,
- metadata=(('test',
- 'IgnoredStreamRequestStreamResponse'),))
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_shutdown_scenarios.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_shutdown_scenarios.py
deleted file mode 100644
index 42f69ebe88b..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_shutdown_scenarios.py
+++ /dev/null
@@ -1,97 +0,0 @@
-# Copyright 2018 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Defines a number of module-scope gRPC scenarios to test server shutdown."""
-
-import argparse
-from concurrent import futures
-import logging
-import os
-import threading
-import time
-
-import grpc
-from six.moves import queue
-
-from tests.unit import test_common
-
-WAIT_TIME = 1000
-
-REQUEST = b'request'
-RESPONSE = b'response'
-
-SERVER_RAISES_EXCEPTION = 'server_raises_exception'
-SERVER_DEALLOCATED = 'server_deallocated'
-SERVER_FORK_CAN_EXIT = 'server_fork_can_exit'
-
-FORK_EXIT = '/test/ForkExit'
-
-
-def fork_and_exit(request, servicer_context):
- pid = os.fork()
- if pid == 0:
- os._exit(0)
- return RESPONSE
-
-
-class GenericHandler(grpc.GenericRpcHandler):
-
- def service(self, handler_call_details):
- if handler_call_details.method == FORK_EXIT:
- return grpc.unary_unary_rpc_method_handler(fork_and_exit)
- else:
- return None
-
-
-def run_server(port_queue):
- server = test_common.test_server()
- port = server.add_insecure_port('[::]:0')
- port_queue.put(port)
- server.add_generic_rpc_handlers((GenericHandler(),))
- server.start()
- # threading.Event.wait() does not exhibit the bug identified in
- # https://github.com/grpc/grpc/issues/17093, sleep instead
- time.sleep(WAIT_TIME)
-
-
-def run_test(args):
- if args.scenario == SERVER_RAISES_EXCEPTION:
- server = test_common.test_server()
- server.start()
- raise Exception()
- elif args.scenario == SERVER_DEALLOCATED:
- server = test_common.test_server()
- server.start()
- server.__del__()
- while server._state.stage != grpc._server._ServerStage.STOPPED:
- pass
- elif args.scenario == SERVER_FORK_CAN_EXIT:
- port_queue = queue.Queue()
- thread = threading.Thread(target=run_server, args=(port_queue,))
- thread.daemon = True
- thread.start()
- port = port_queue.get()
- channel = grpc.insecure_channel('localhost:%d' % port)
- multi_callable = channel.unary_unary(FORK_EXIT)
- result, call = multi_callable.with_call(REQUEST, wait_for_ready=True)
- os.wait()
- else:
- raise ValueError('unknown test scenario')
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- parser = argparse.ArgumentParser()
- parser.add_argument('scenario', type=str)
- args = parser.parse_args()
- run_test(args)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_shutdown_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_shutdown_test.py
deleted file mode 100644
index 31f45d6f3b2..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_shutdown_test.py
+++ /dev/null
@@ -1,95 +0,0 @@
-# Copyright 2018 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Tests clean shutdown of server on various interpreter exit conditions.
-
-The tests in this module spawn a subprocess for each test case, the
-test is considered successful if it doesn't freeze/timeout.
-"""
-
-import atexit
-import logging
-import os
-import subprocess
-import sys
-import threading
-import unittest
-
-from tests.unit import _server_shutdown_scenarios
-
-INTERPRETER = sys.executable
-BASE_COMMAND = [INTERPRETER, '-m', 'tests.unit._server_shutdown_scenarios']
-
-processes = []
-process_lock = threading.Lock()
-
-
-# Make sure we attempt to clean up any
-# processes we may have left running
-def cleanup_processes():
- with process_lock:
- for process in processes:
- try:
- process.kill()
- except Exception: # pylint: disable=broad-except
- pass
-
-
-atexit.register(cleanup_processes)
-
-
-def wait(process):
- with process_lock:
- processes.append(process)
- process.wait()
-
-
-class ServerShutdown(unittest.TestCase):
-
- # Currently we shut down a server (if possible) after the Python server
- # instance is garbage collected. This behavior may change in the future.
- def test_deallocated_server_stops(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(
- BASE_COMMAND + [_server_shutdown_scenarios.SERVER_DEALLOCATED],
- stdout=sys.stdout,
- stderr=sys.stderr,
- env=env)
- wait(process)
-
- def test_server_exception_exits(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(
- BASE_COMMAND + [_server_shutdown_scenarios.SERVER_RAISES_EXCEPTION],
- stdout=sys.stdout,
- stderr=sys.stderr,
- env=env)
- wait(process)
-
- @unittest.skipIf(os.name == 'nt', 'fork not supported on windows')
- def test_server_fork_can_exit(self):
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- process = subprocess.Popen(
- BASE_COMMAND + [_server_shutdown_scenarios.SERVER_FORK_CAN_EXIT],
- stdout=sys.stdout,
- stderr=sys.stderr,
- env=env)
- wait(process)
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_test.py
deleted file mode 100644
index 2cddaf4b81f..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_test.py
+++ /dev/null
@@ -1,69 +0,0 @@
-# Copyright 2018 The gRPC Authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-from concurrent import futures
-import logging
-import unittest
-
-import grpc
-
-from tests.unit import resources
-
-
-class _ActualGenericRpcHandler(grpc.GenericRpcHandler):
-
- def service(self, handler_call_details):
- return None
-
-
-class ServerTest(unittest.TestCase):
-
- def test_not_a_generic_rpc_handler_at_construction(self):
- with self.assertRaises(AttributeError) as exception_context:
- grpc.server(futures.ThreadPoolExecutor(max_workers=5),
- handlers=[
- _ActualGenericRpcHandler(),
- object(),
- ])
- self.assertIn('grpc.GenericRpcHandler',
- str(exception_context.exception))
-
- def test_not_a_generic_rpc_handler_after_construction(self):
- server = grpc.server(futures.ThreadPoolExecutor(max_workers=5))
- with self.assertRaises(AttributeError) as exception_context:
- server.add_generic_rpc_handlers([
- _ActualGenericRpcHandler(),
- object(),
- ])
- self.assertIn('grpc.GenericRpcHandler',
- str(exception_context.exception))
-
- def test_failed_port_binding_exception(self):
- server = grpc.server(None, options=(('grpc.so_reuseport', 0),))
- port = server.add_insecure_port('localhost:0')
- bind_address = "localhost:%d" % port
-
- with self.assertRaises(RuntimeError):
- server.add_insecure_port(bind_address)
-
- server_credentials = grpc.ssl_server_credentials([
- (resources.private_key(), resources.certificate_chain())
- ])
- with self.assertRaises(RuntimeError):
- server.add_secure_port(bind_address, server_credentials)
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_wait_for_termination_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_wait_for_termination_test.py
deleted file mode 100644
index 065285a83c2..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_server_wait_for_termination_test.py
+++ /dev/null
@@ -1,92 +0,0 @@
-# Copyright 2019 The gRPC Authors
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-from __future__ import division
-
-from concurrent import futures
-import datetime
-import threading
-import time
-import unittest
-
-import grpc
-import six
-
-from tests.unit.framework.common import test_constants
-
-_WAIT_FOR_BLOCKING = datetime.timedelta(seconds=1)
-
-
-def _block_on_waiting(server, termination_event, timeout=None):
- server.start()
- server.wait_for_termination(timeout=timeout)
- termination_event.set()
-
-
-class ServerWaitForTerminationTest(unittest.TestCase):
-
- def test_unblock_by_invoking_stop(self):
- termination_event = threading.Event()
- server = grpc.server(futures.ThreadPoolExecutor())
-
- wait_thread = threading.Thread(target=_block_on_waiting,
- args=(
- server,
- termination_event,
- ))
- wait_thread.daemon = True
- wait_thread.start()
- time.sleep(_WAIT_FOR_BLOCKING.total_seconds())
-
- server.stop(None)
- termination_event.wait(timeout=test_constants.SHORT_TIMEOUT)
- self.assertTrue(termination_event.is_set())
-
- def test_unblock_by_del(self):
- termination_event = threading.Event()
- server = grpc.server(futures.ThreadPoolExecutor())
-
- wait_thread = threading.Thread(target=_block_on_waiting,
- args=(
- server,
- termination_event,
- ))
- wait_thread.daemon = True
- wait_thread.start()
- time.sleep(_WAIT_FOR_BLOCKING.total_seconds())
-
- # Invoke manually here, in Python 2 it will be invoked by GC sometime.
- server.__del__()
- termination_event.wait(timeout=test_constants.SHORT_TIMEOUT)
- self.assertTrue(termination_event.is_set())
-
- def test_unblock_by_timeout(self):
- termination_event = threading.Event()
- server = grpc.server(futures.ThreadPoolExecutor())
-
- wait_thread = threading.Thread(target=_block_on_waiting,
- args=(
- server,
- termination_event,
- test_constants.SHORT_TIMEOUT / 2,
- ))
- wait_thread.daemon = True
- wait_thread.start()
-
- termination_event.wait(timeout=test_constants.SHORT_TIMEOUT)
- self.assertTrue(termination_event.is_set())
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_signal_client.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_signal_client.py
deleted file mode 100644
index 5cc68831f7e..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_signal_client.py
+++ /dev/null
@@ -1,119 +0,0 @@
-# Copyright 2019 the gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Client for testing responsiveness to signals."""
-
-from __future__ import print_function
-
-import argparse
-import functools
-import logging
-import signal
-import sys
-
-import grpc
-
-SIGTERM_MESSAGE = "Handling sigterm!"
-
-UNARY_UNARY = "/test/Unary"
-UNARY_STREAM = "/test/ServerStreaming"
-
-_MESSAGE = b'\x00\x00\x00'
-
-_ASSERTION_MESSAGE = "Control flow should never reach here."
-
-# NOTE(gnossen): We use a global variable here so that the signal handler can be
-# installed before the RPC begins. If we do not do this, then we may receive the
-# SIGINT before the signal handler is installed. I'm not happy with per-process
-# global state, but the per-process global state that is signal handlers
-# somewhat forces my hand.
-per_process_rpc_future = None
-
-
-def handle_sigint(unused_signum, unused_frame):
- print(SIGTERM_MESSAGE)
- if per_process_rpc_future is not None:
- per_process_rpc_future.cancel()
- sys.stderr.flush()
- # This sys.exit(0) avoids an exception caused by the cancelled RPC.
- sys.exit(0)
-
-
-def main_unary(server_target):
- """Initiate a unary RPC to be interrupted by a SIGINT."""
- global per_process_rpc_future # pylint: disable=global-statement
- with grpc.insecure_channel(server_target) as channel:
- multicallable = channel.unary_unary(UNARY_UNARY)
- signal.signal(signal.SIGINT, handle_sigint)
- per_process_rpc_future = multicallable.future(_MESSAGE,
- wait_for_ready=True)
- result = per_process_rpc_future.result()
- assert False, _ASSERTION_MESSAGE
-
-
-def main_streaming(server_target):
- """Initiate a streaming RPC to be interrupted by a SIGINT."""
- global per_process_rpc_future # pylint: disable=global-statement
- with grpc.insecure_channel(server_target) as channel:
- signal.signal(signal.SIGINT, handle_sigint)
- per_process_rpc_future = channel.unary_stream(UNARY_STREAM)(
- _MESSAGE, wait_for_ready=True)
- for result in per_process_rpc_future:
- pass
- assert False, _ASSERTION_MESSAGE
-
-
-def main_unary_with_exception(server_target):
- """Initiate a unary RPC with a signal handler that will raise."""
- channel = grpc.insecure_channel(server_target)
- try:
- channel.unary_unary(UNARY_UNARY)(_MESSAGE, wait_for_ready=True)
- except KeyboardInterrupt:
- sys.stderr.write("Running signal handler.\n")
- sys.stderr.flush()
-
- # This call should not freeze.
- channel.close()
-
-
-def main_streaming_with_exception(server_target):
- """Initiate a streaming RPC with a signal handler that will raise."""
- channel = grpc.insecure_channel(server_target)
- try:
- for _ in channel.unary_stream(UNARY_STREAM)(_MESSAGE,
- wait_for_ready=True):
- pass
- except KeyboardInterrupt:
- sys.stderr.write("Running signal handler.\n")
- sys.stderr.flush()
-
- # This call should not freeze.
- channel.close()
-
-
-if __name__ == '__main__':
- parser = argparse.ArgumentParser(description='Signal test client.')
- parser.add_argument('server', help='Server target')
- parser.add_argument('arity', help='Arity', choices=('unary', 'streaming'))
- parser.add_argument('--exception',
- help='Whether the signal throws an exception',
- action='store_true')
- args = parser.parse_args()
- if args.arity == 'unary' and not args.exception:
- main_unary(args.server)
- elif args.arity == 'streaming' and not args.exception:
- main_streaming(args.server)
- elif args.arity == 'unary' and args.exception:
- main_unary_with_exception(args.server)
- else:
- main_streaming_with_exception(args.server)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_signal_handling_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_signal_handling_test.py
deleted file mode 100644
index f45b049aa5c..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_signal_handling_test.py
+++ /dev/null
@@ -1,200 +0,0 @@
-# Copyright 2019 the gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Test of responsiveness to signals."""
-
-import logging
-import os
-import signal
-import subprocess
-import sys
-import tempfile
-import threading
-import unittest
-
-import grpc
-
-from tests.unit import _signal_client
-from tests.unit import test_common
-
-_CLIENT_PATH = None
-if sys.executable is not None:
- _CLIENT_PATH = 'tests.unit._signal_client'
-else:
- # NOTE(rbellevi): For compatibility with internal testing.
- if len(sys.argv) != 2:
- raise RuntimeError("Must supply path to executable client.")
- client_name = sys.argv[1].split("/")[-1]
- del sys.argv[1] # For compatibility with test runner.
- _CLIENT_PATH = os.path.realpath(
- os.path.join(os.path.dirname(os.path.abspath(__file__)), client_name))
-
-_HOST = 'localhost'
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def __init__(self):
- self._connected_clients_lock = threading.RLock()
- self._connected_clients_event = threading.Event()
- self._connected_clients = 0
-
- self._unary_unary_handler = grpc.unary_unary_rpc_method_handler(
- self._handle_unary_unary)
- self._unary_stream_handler = grpc.unary_stream_rpc_method_handler(
- self._handle_unary_stream)
-
- def _on_client_connect(self):
- with self._connected_clients_lock:
- self._connected_clients += 1
- self._connected_clients_event.set()
-
- def _on_client_disconnect(self):
- with self._connected_clients_lock:
- self._connected_clients -= 1
- if self._connected_clients == 0:
- self._connected_clients_event.clear()
-
- def await_connected_client(self):
- """Blocks until a client connects to the server."""
- self._connected_clients_event.wait()
-
- def _handle_unary_unary(self, request, servicer_context):
- """Handles a unary RPC.
-
- Blocks until the client disconnects and then echoes.
- """
- stop_event = threading.Event()
-
- def on_rpc_end():
- self._on_client_disconnect()
- stop_event.set()
-
- servicer_context.add_callback(on_rpc_end)
- self._on_client_connect()
- stop_event.wait()
- return request
-
- def _handle_unary_stream(self, request, servicer_context):
- """Handles a server streaming RPC.
-
- Blocks until the client disconnects and then echoes.
- """
- stop_event = threading.Event()
-
- def on_rpc_end():
- self._on_client_disconnect()
- stop_event.set()
-
- servicer_context.add_callback(on_rpc_end)
- self._on_client_connect()
- stop_event.wait()
- yield request
-
- def service(self, handler_call_details):
- if handler_call_details.method == _signal_client.UNARY_UNARY:
- return self._unary_unary_handler
- elif handler_call_details.method == _signal_client.UNARY_STREAM:
- return self._unary_stream_handler
- else:
- return None
-
-
-def _read_stream(stream):
- stream.seek(0)
- return stream.read()
-
-
-def _start_client(args, stdout, stderr):
- invocation = None
- if sys.executable is not None:
- invocation = (sys.executable, '-m', _CLIENT_PATH) + tuple(args)
- else:
- invocation = (_CLIENT_PATH,) + tuple(args)
- env = os.environ.copy()
- env['Y_PYTHON_ENTRY_POINT'] = ':main'
- return subprocess.Popen(invocation, stdout=stdout, stderr=stderr, env=env)
-
-
-class SignalHandlingTest(unittest.TestCase):
-
- def setUp(self):
- self._server = test_common.test_server()
- self._port = self._server.add_insecure_port('{}:0'.format(_HOST))
- self._handler = _GenericHandler()
- self._server.add_generic_rpc_handlers((self._handler,))
- self._server.start()
-
- def tearDown(self):
- self._server.stop(None)
-
- @unittest.skipIf(os.name == 'nt', 'SIGINT not supported on windows')
- def testUnary(self):
- """Tests that the server unary code path does not stall signal handlers."""
- server_target = '{}:{}'.format(_HOST, self._port)
- with tempfile.TemporaryFile(mode='r') as client_stdout:
- with tempfile.TemporaryFile(mode='r') as client_stderr:
- client = _start_client((server_target, 'unary'), client_stdout,
- client_stderr)
- self._handler.await_connected_client()
- client.send_signal(signal.SIGINT)
- self.assertFalse(client.wait(), msg=_read_stream(client_stderr))
- client_stdout.seek(0)
- self.assertIn(_signal_client.SIGTERM_MESSAGE,
- client_stdout.read())
-
- @unittest.skipIf(os.name == 'nt', 'SIGINT not supported on windows')
- def testStreaming(self):
- """Tests that the server streaming code path does not stall signal handlers."""
- server_target = '{}:{}'.format(_HOST, self._port)
- with tempfile.TemporaryFile(mode='r') as client_stdout:
- with tempfile.TemporaryFile(mode='r') as client_stderr:
- client = _start_client((server_target, 'streaming'),
- client_stdout, client_stderr)
- self._handler.await_connected_client()
- client.send_signal(signal.SIGINT)
- self.assertFalse(client.wait(), msg=_read_stream(client_stderr))
- client_stdout.seek(0)
- self.assertIn(_signal_client.SIGTERM_MESSAGE,
- client_stdout.read())
-
- @unittest.skipIf(os.name == 'nt', 'SIGINT not supported on windows')
- def testUnaryWithException(self):
- server_target = '{}:{}'.format(_HOST, self._port)
- with tempfile.TemporaryFile(mode='r') as client_stdout:
- with tempfile.TemporaryFile(mode='r') as client_stderr:
- client = _start_client(('--exception', server_target, 'unary'),
- client_stdout, client_stderr)
- self._handler.await_connected_client()
- client.send_signal(signal.SIGINT)
- client.wait()
- self.assertEqual(0, client.returncode)
-
- @unittest.skipIf(os.name == 'nt', 'SIGINT not supported on windows')
- def testStreamingHandlerWithException(self):
- server_target = '{}:{}'.format(_HOST, self._port)
- with tempfile.TemporaryFile(mode='r') as client_stdout:
- with tempfile.TemporaryFile(mode='r') as client_stderr:
- client = _start_client(
- ('--exception', server_target, 'streaming'), client_stdout,
- client_stderr)
- self._handler.await_connected_client()
- client.send_signal(signal.SIGINT)
- client.wait()
- print(_read_stream(client_stderr))
- self.assertEqual(0, client.returncode)
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_tcp_proxy.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_tcp_proxy.py
deleted file mode 100644
index 84dc0e2d6cf..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_tcp_proxy.py
+++ /dev/null
@@ -1,141 +0,0 @@
-# Copyright 2019 the gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-""" Proxies a TCP connection between a single client-server pair.
-
-This proxy is not suitable for production, but should work well for cases in
-which a test needs to spy on the bytes put on the wire between a server and
-a client.
-"""
-
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-import datetime
-import select
-import socket
-import threading
-
-from tests.unit.framework.common import get_socket
-
-_TCP_PROXY_BUFFER_SIZE = 1024
-_TCP_PROXY_TIMEOUT = datetime.timedelta(milliseconds=500)
-
-
-def _init_proxy_socket(gateway_address, gateway_port):
- proxy_socket = socket.create_connection((gateway_address, gateway_port))
- return proxy_socket
-
-
-class TcpProxy(object):
- """Proxies a TCP connection between one client and one server."""
-
- def __init__(self, bind_address, gateway_address, gateway_port):
- self._bind_address = bind_address
- self._gateway_address = gateway_address
- self._gateway_port = gateway_port
-
- self._byte_count_lock = threading.RLock()
- self._sent_byte_count = 0
- self._received_byte_count = 0
-
- self._stop_event = threading.Event()
-
- self._port = None
- self._listen_socket = None
- self._proxy_socket = None
-
- # The following three attributes are owned by the serving thread.
- self._northbound_data = b""
- self._southbound_data = b""
- self._client_sockets = []
-
- self._thread = threading.Thread(target=self._run_proxy)
-
- def start(self):
- _, self._port, self._listen_socket = get_socket(
- bind_address=self._bind_address)
- self._proxy_socket = _init_proxy_socket(self._gateway_address,
- self._gateway_port)
- self._thread.start()
-
- def get_port(self):
- return self._port
-
- def _handle_reads(self, sockets_to_read):
- for socket_to_read in sockets_to_read:
- if socket_to_read is self._listen_socket:
- client_socket, client_address = socket_to_read.accept()
- self._client_sockets.append(client_socket)
- elif socket_to_read is self._proxy_socket:
- data = socket_to_read.recv(_TCP_PROXY_BUFFER_SIZE)
- with self._byte_count_lock:
- self._received_byte_count += len(data)
- self._northbound_data += data
- elif socket_to_read in self._client_sockets:
- data = socket_to_read.recv(_TCP_PROXY_BUFFER_SIZE)
- if data:
- with self._byte_count_lock:
- self._sent_byte_count += len(data)
- self._southbound_data += data
- else:
- self._client_sockets.remove(socket_to_read)
- else:
- raise RuntimeError('Unidentified socket appeared in read set.')
-
- def _handle_writes(self, sockets_to_write):
- for socket_to_write in sockets_to_write:
- if socket_to_write is self._proxy_socket:
- if self._southbound_data:
- self._proxy_socket.sendall(self._southbound_data)
- self._southbound_data = b""
- elif socket_to_write in self._client_sockets:
- if self._northbound_data:
- socket_to_write.sendall(self._northbound_data)
- self._northbound_data = b""
-
- def _run_proxy(self):
- while not self._stop_event.is_set():
- expected_reads = (self._listen_socket, self._proxy_socket) + tuple(
- self._client_sockets)
- expected_writes = expected_reads
- sockets_to_read, sockets_to_write, _ = select.select(
- expected_reads, expected_writes, (),
- _TCP_PROXY_TIMEOUT.total_seconds())
- self._handle_reads(sockets_to_read)
- self._handle_writes(sockets_to_write)
- for client_socket in self._client_sockets:
- client_socket.close()
-
- def stop(self):
- self._stop_event.set()
- self._thread.join()
- self._listen_socket.close()
- self._proxy_socket.close()
-
- def get_byte_count(self):
- with self._byte_count_lock:
- return self._sent_byte_count, self._received_byte_count
-
- def reset_byte_count(self):
- with self._byte_count_lock:
- self._byte_count = 0
- self._received_byte_count = 0
-
- def __enter__(self):
- self.start()
- return self
-
- def __exit__(self, exc_type, exc_val, exc_tb):
- self.stop()
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_version_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_version_test.py
deleted file mode 100644
index a81e51e56c5..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_version_test.py
+++ /dev/null
@@ -1,31 +0,0 @@
-# Copyright 2018 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Test for grpc.__version__"""
-
-import logging
-import unittest
-
-import grpc
-from grpc import _grpcio_metadata
-
-
-class VersionTest(unittest.TestCase):
-
- def test_get_version(self):
- self.assertEqual(grpc.__version__, _grpcio_metadata.__version__)
-
-
-if __name__ == '__main__':
- logging.basicConfig()
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_xds_credentials_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_xds_credentials_test.py
deleted file mode 100644
index 64594061c01..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/_xds_credentials_test.py
+++ /dev/null
@@ -1,103 +0,0 @@
-# Copyright 2021 The gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Tests xDS server and channel credentials."""
-
-from concurrent import futures
-import contextlib
-import logging
-import unittest
-
-import grpc
-import grpc.experimental
-
-from tests.unit import resources
-from tests.unit import test_common
-
-
-class _GenericHandler(grpc.GenericRpcHandler):
-
- def service(self, handler_call_details):
- return grpc.unary_unary_rpc_method_handler(
- lambda request, unused_context: request)
-
-
-@contextlib.contextmanager
-def xds_channel_server_without_xds(server_fallback_creds):
- server = grpc.server(futures.ThreadPoolExecutor())
- server.add_generic_rpc_handlers((_GenericHandler(),))
- server_server_fallback_creds = grpc.ssl_server_credentials(
- ((resources.private_key(), resources.certificate_chain()),))
- server_creds = grpc.xds_server_credentials(server_fallback_creds)
- port = server.add_secure_port("localhost:0", server_creds)
- server.start()
- try:
- yield "localhost:{}".format(port)
- finally:
- server.stop(None)
-
-
-class XdsCredentialsTest(unittest.TestCase):
-
- def test_xds_creds_fallback_ssl(self):
- # Since there is no xDS server, the fallback credentials will be used.
- # In this case, SSL credentials.
- server_fallback_creds = grpc.ssl_server_credentials(
- ((resources.private_key(), resources.certificate_chain()),))
- with xds_channel_server_without_xds(
- server_fallback_creds) as server_address:
- override_options = (("grpc.ssl_target_name_override",
- "foo.test.google.fr"),)
- channel_fallback_creds = grpc.ssl_channel_credentials(
- root_certificates=resources.test_root_certificates(),
- private_key=resources.private_key(),
- certificate_chain=resources.certificate_chain())
- channel_creds = grpc.xds_channel_credentials(channel_fallback_creds)
- with grpc.secure_channel(server_address,
- channel_creds,
- options=override_options) as channel:
- request = b"abc"
- response = channel.unary_unary("/test/method")(
- request, wait_for_ready=True)
- self.assertEqual(response, request)
-
- def test_xds_creds_fallback_insecure(self):
- # Since there is no xDS server, the fallback credentials will be used.
- # In this case, insecure.
- server_fallback_creds = grpc.insecure_server_credentials()
- with xds_channel_server_without_xds(
- server_fallback_creds) as server_address:
- channel_fallback_creds = grpc.experimental.insecure_channel_credentials(
- )
- channel_creds = grpc.xds_channel_credentials(channel_fallback_creds)
- with grpc.secure_channel(server_address, channel_creds) as channel:
- request = b"abc"
- response = channel.unary_unary("/test/method")(
- request, wait_for_ready=True)
- self.assertEqual(response, request)
-
- def test_start_xds_server(self):
- server = grpc.server(futures.ThreadPoolExecutor(), xds=True)
- server.add_generic_rpc_handlers((_GenericHandler(),))
- server_fallback_creds = grpc.insecure_server_credentials()
- server_creds = grpc.xds_server_credentials(server_fallback_creds)
- port = server.add_secure_port("localhost:0", server_creds)
- server.start()
- server.stop(None)
- # No exceptions thrown. A more comprehensive suite of tests will be
- # provided by the interop tests.
-
-
-if __name__ == "__main__":
- logging.basicConfig()
- unittest.main()
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/__init__.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/__init__.py
deleted file mode 100644
index 5fb4f3c3cfd..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/__init__.py
+++ /dev/null
@@ -1,13 +0,0 @@
-# Copyright 2015 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_beta_features_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_beta_features_test.py
deleted file mode 100644
index 0ce3a127392..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_beta_features_test.py
+++ /dev/null
@@ -1,355 +0,0 @@
-# Copyright 2015 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Tests Face interface compliance of the gRPC Python Beta API."""
-
-import threading
-import unittest
-
-from grpc.beta import implementations
-from grpc.beta import interfaces
-from grpc.framework.common import cardinality
-from grpc.framework.interfaces.face import utilities
-
-from tests.unit import resources
-from tests.unit.beta import test_utilities
-from tests.unit.framework.common import test_constants
-
-_SERVER_HOST_OVERRIDE = 'foo.test.google.fr'
-
-_PER_RPC_CREDENTIALS_METADATA_KEY = b'my-call-credentials-metadata-key'
-_PER_RPC_CREDENTIALS_METADATA_VALUE = b'my-call-credentials-metadata-value'
-
-_GROUP = 'group'
-_UNARY_UNARY = 'unary-unary'
-_UNARY_STREAM = 'unary-stream'
-_STREAM_UNARY = 'stream-unary'
-_STREAM_STREAM = 'stream-stream'
-
-_REQUEST = b'abc'
-_RESPONSE = b'123'
-
-
-class _Servicer(object):
-
- def __init__(self):
- self._condition = threading.Condition()
- self._peer = None
- self._serviced = False
-
- def unary_unary(self, request, context):
- with self._condition:
- self._request = request
- self._peer = context.protocol_context().peer()
- self._invocation_metadata = context.invocation_metadata()
- context.protocol_context().disable_next_response_compression()
- self._serviced = True
- self._condition.notify_all()
- return _RESPONSE
-
- def unary_stream(self, request, context):
- with self._condition:
- self._request = request
- self._peer = context.protocol_context().peer()
- self._invocation_metadata = context.invocation_metadata()
- context.protocol_context().disable_next_response_compression()
- self._serviced = True
- self._condition.notify_all()
- return
- yield # pylint: disable=unreachable
-
- def stream_unary(self, request_iterator, context):
- for request in request_iterator:
- self._request = request
- with self._condition:
- self._peer = context.protocol_context().peer()
- self._invocation_metadata = context.invocation_metadata()
- context.protocol_context().disable_next_response_compression()
- self._serviced = True
- self._condition.notify_all()
- return _RESPONSE
-
- def stream_stream(self, request_iterator, context):
- for request in request_iterator:
- with self._condition:
- self._peer = context.protocol_context().peer()
- context.protocol_context().disable_next_response_compression()
- yield _RESPONSE
- with self._condition:
- self._invocation_metadata = context.invocation_metadata()
- self._serviced = True
- self._condition.notify_all()
-
- def peer(self):
- with self._condition:
- return self._peer
-
- def block_until_serviced(self):
- with self._condition:
- while not self._serviced:
- self._condition.wait()
-
-
-class _BlockingIterator(object):
-
- def __init__(self, upstream):
- self._condition = threading.Condition()
- self._upstream = upstream
- self._allowed = []
-
- def __iter__(self):
- return self
-
- def __next__(self):
- return self.next()
-
- def next(self):
- with self._condition:
- while True:
- if self._allowed is None:
- raise StopIteration()
- elif self._allowed:
- return self._allowed.pop(0)
- else:
- self._condition.wait()
-
- def allow(self):
- with self._condition:
- try:
- self._allowed.append(next(self._upstream))
- except StopIteration:
- self._allowed = None
- self._condition.notify_all()
-
-
-def _metadata_plugin(context, callback):
- callback([
- (_PER_RPC_CREDENTIALS_METADATA_KEY, _PER_RPC_CREDENTIALS_METADATA_VALUE)
- ], None)
-
-
-class BetaFeaturesTest(unittest.TestCase):
-
- def setUp(self):
- self._servicer = _Servicer()
- method_implementations = {
- (_GROUP, _UNARY_UNARY):
- utilities.unary_unary_inline(self._servicer.unary_unary),
- (_GROUP, _UNARY_STREAM):
- utilities.unary_stream_inline(self._servicer.unary_stream),
- (_GROUP, _STREAM_UNARY):
- utilities.stream_unary_inline(self._servicer.stream_unary),
- (_GROUP, _STREAM_STREAM):
- utilities.stream_stream_inline(self._servicer.stream_stream),
- }
-
- cardinalities = {
- _UNARY_UNARY: cardinality.Cardinality.UNARY_UNARY,
- _UNARY_STREAM: cardinality.Cardinality.UNARY_STREAM,
- _STREAM_UNARY: cardinality.Cardinality.STREAM_UNARY,
- _STREAM_STREAM: cardinality.Cardinality.STREAM_STREAM,
- }
-
- server_options = implementations.server_options(
- thread_pool_size=test_constants.POOL_SIZE)
- self._server = implementations.server(method_implementations,
- options=server_options)
- server_credentials = implementations.ssl_server_credentials([
- (
- resources.private_key(),
- resources.certificate_chain(),
- ),
- ])
- port = self._server.add_secure_port('[::]:0', server_credentials)
- self._server.start()
- self._channel_credentials = implementations.ssl_channel_credentials(
- resources.test_root_certificates())
- self._call_credentials = implementations.metadata_call_credentials(
- _metadata_plugin)
- channel = test_utilities.not_really_secure_channel(
- 'localhost', port, self._channel_credentials, _SERVER_HOST_OVERRIDE)
- stub_options = implementations.stub_options(
- thread_pool_size=test_constants.POOL_SIZE)
- self._dynamic_stub = implementations.dynamic_stub(channel,
- _GROUP,
- cardinalities,
- options=stub_options)
-
- def tearDown(self):
- self._dynamic_stub = None
- self._server.stop(test_constants.SHORT_TIMEOUT).wait()
-
- def test_unary_unary(self):
- call_options = interfaces.grpc_call_options(
- disable_compression=True, credentials=self._call_credentials)
- response = getattr(self._dynamic_stub,
- _UNARY_UNARY)(_REQUEST,
- test_constants.LONG_TIMEOUT,
- protocol_options=call_options)
- self.assertEqual(_RESPONSE, response)
- self.assertIsNotNone(self._servicer.peer())
- invocation_metadata = [
- (metadatum.key, metadatum.value)
- for metadatum in self._servicer._invocation_metadata
- ]
- self.assertIn((_PER_RPC_CREDENTIALS_METADATA_KEY,
- _PER_RPC_CREDENTIALS_METADATA_VALUE),
- invocation_metadata)
-
- def test_unary_stream(self):
- call_options = interfaces.grpc_call_options(
- disable_compression=True, credentials=self._call_credentials)
- response_iterator = getattr(self._dynamic_stub, _UNARY_STREAM)(
- _REQUEST,
- test_constants.LONG_TIMEOUT,
- protocol_options=call_options)
- self._servicer.block_until_serviced()
- self.assertIsNotNone(self._servicer.peer())
- invocation_metadata = [
- (metadatum.key, metadatum.value)
- for metadatum in self._servicer._invocation_metadata
- ]
- self.assertIn((_PER_RPC_CREDENTIALS_METADATA_KEY,
- _PER_RPC_CREDENTIALS_METADATA_VALUE),
- invocation_metadata)
-
- def test_stream_unary(self):
- call_options = interfaces.grpc_call_options(
- credentials=self._call_credentials)
- request_iterator = _BlockingIterator(iter((_REQUEST,)))
- response_future = getattr(self._dynamic_stub, _STREAM_UNARY).future(
- request_iterator,
- test_constants.LONG_TIMEOUT,
- protocol_options=call_options)
- response_future.protocol_context().disable_next_request_compression()
- request_iterator.allow()
- response_future.protocol_context().disable_next_request_compression()
- request_iterator.allow()
- self._servicer.block_until_serviced()
- self.assertIsNotNone(self._servicer.peer())
- self.assertEqual(_RESPONSE, response_future.result())
- invocation_metadata = [
- (metadatum.key, metadatum.value)
- for metadatum in self._servicer._invocation_metadata
- ]
- self.assertIn((_PER_RPC_CREDENTIALS_METADATA_KEY,
- _PER_RPC_CREDENTIALS_METADATA_VALUE),
- invocation_metadata)
-
- def test_stream_stream(self):
- call_options = interfaces.grpc_call_options(
- credentials=self._call_credentials)
- request_iterator = _BlockingIterator(iter((_REQUEST,)))
- response_iterator = getattr(self._dynamic_stub, _STREAM_STREAM)(
- request_iterator,
- test_constants.SHORT_TIMEOUT,
- protocol_options=call_options)
- response_iterator.protocol_context().disable_next_request_compression()
- request_iterator.allow()
- response = next(response_iterator)
- response_iterator.protocol_context().disable_next_request_compression()
- request_iterator.allow()
- self._servicer.block_until_serviced()
- self.assertIsNotNone(self._servicer.peer())
- self.assertEqual(_RESPONSE, response)
- invocation_metadata = [
- (metadatum.key, metadatum.value)
- for metadatum in self._servicer._invocation_metadata
- ]
- self.assertIn((_PER_RPC_CREDENTIALS_METADATA_KEY,
- _PER_RPC_CREDENTIALS_METADATA_VALUE),
- invocation_metadata)
-
-
-class ContextManagementAndLifecycleTest(unittest.TestCase):
-
- def setUp(self):
- self._servicer = _Servicer()
- self._method_implementations = {
- (_GROUP, _UNARY_UNARY):
- utilities.unary_unary_inline(self._servicer.unary_unary),
- (_GROUP, _UNARY_STREAM):
- utilities.unary_stream_inline(self._servicer.unary_stream),
- (_GROUP, _STREAM_UNARY):
- utilities.stream_unary_inline(self._servicer.stream_unary),
- (_GROUP, _STREAM_STREAM):
- utilities.stream_stream_inline(self._servicer.stream_stream),
- }
-
- self._cardinalities = {
- _UNARY_UNARY: cardinality.Cardinality.UNARY_UNARY,
- _UNARY_STREAM: cardinality.Cardinality.UNARY_STREAM,
- _STREAM_UNARY: cardinality.Cardinality.STREAM_UNARY,
- _STREAM_STREAM: cardinality.Cardinality.STREAM_STREAM,
- }
-
- self._server_options = implementations.server_options(
- thread_pool_size=test_constants.POOL_SIZE)
- self._server_credentials = implementations.ssl_server_credentials([
- (
- resources.private_key(),
- resources.certificate_chain(),
- ),
- ])
- self._channel_credentials = implementations.ssl_channel_credentials(
- resources.test_root_certificates())
- self._stub_options = implementations.stub_options(
- thread_pool_size=test_constants.POOL_SIZE)
-
- def test_stub_context(self):
- server = implementations.server(self._method_implementations,
- options=self._server_options)
- port = server.add_secure_port('[::]:0', self._server_credentials)
- server.start()
-
- channel = test_utilities.not_really_secure_channel(
- 'localhost', port, self._channel_credentials, _SERVER_HOST_OVERRIDE)
- dynamic_stub = implementations.dynamic_stub(channel,
- _GROUP,
- self._cardinalities,
- options=self._stub_options)
- for _ in range(100):
- with dynamic_stub:
- pass
- for _ in range(10):
- with dynamic_stub:
- call_options = interfaces.grpc_call_options(
- disable_compression=True)
- response = getattr(dynamic_stub,
- _UNARY_UNARY)(_REQUEST,
- test_constants.LONG_TIMEOUT,
- protocol_options=call_options)
- self.assertEqual(_RESPONSE, response)
- self.assertIsNotNone(self._servicer.peer())
-
- server.stop(test_constants.SHORT_TIMEOUT).wait()
-
- def test_server_lifecycle(self):
- for _ in range(100):
- server = implementations.server(self._method_implementations,
- options=self._server_options)
- port = server.add_secure_port('[::]:0', self._server_credentials)
- server.start()
- server.stop(test_constants.SHORT_TIMEOUT).wait()
- for _ in range(100):
- server = implementations.server(self._method_implementations,
- options=self._server_options)
- server.add_secure_port('[::]:0', self._server_credentials)
- server.add_insecure_port('[::]:0')
- with server:
- server.stop(test_constants.SHORT_TIMEOUT)
- server.stop(test_constants.SHORT_TIMEOUT)
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_connectivity_channel_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_connectivity_channel_test.py
deleted file mode 100644
index 1416902eab8..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_connectivity_channel_test.py
+++ /dev/null
@@ -1,32 +0,0 @@
-# Copyright 2015 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Tests of grpc.beta._connectivity_channel."""
-
-import unittest
-
-from grpc.beta import interfaces
-
-
-class ConnectivityStatesTest(unittest.TestCase):
-
- def testBetaConnectivityStates(self):
- self.assertIsNotNone(interfaces.ChannelConnectivity.IDLE)
- self.assertIsNotNone(interfaces.ChannelConnectivity.CONNECTING)
- self.assertIsNotNone(interfaces.ChannelConnectivity.READY)
- self.assertIsNotNone(interfaces.ChannelConnectivity.TRANSIENT_FAILURE)
- self.assertIsNotNone(interfaces.ChannelConnectivity.FATAL_FAILURE)
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_not_found_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_not_found_test.py
deleted file mode 100644
index 27fdecb8b7b..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_not_found_test.py
+++ /dev/null
@@ -1,60 +0,0 @@
-# Copyright 2015 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Tests of RPC-method-not-found behavior."""
-
-import unittest
-
-from grpc.beta import implementations
-from grpc.beta import interfaces
-from grpc.framework.interfaces.face import face
-
-from tests.unit.framework.common import test_constants
-
-
-class NotFoundTest(unittest.TestCase):
-
- def setUp(self):
- self._server = implementations.server({})
- port = self._server.add_insecure_port('[::]:0')
- channel = implementations.insecure_channel('localhost', port)
- self._generic_stub = implementations.generic_stub(channel)
- self._server.start()
-
- def tearDown(self):
- self._server.stop(0).wait()
- self._generic_stub = None
-
- def test_blocking_unary_unary_not_found(self):
- with self.assertRaises(face.LocalError) as exception_assertion_context:
- self._generic_stub.blocking_unary_unary('groop',
- 'meffod',
- b'abc',
- test_constants.LONG_TIMEOUT,
- with_call=True)
- self.assertIs(exception_assertion_context.exception.code,
- interfaces.StatusCode.UNIMPLEMENTED)
-
- def test_future_stream_unary_not_found(self):
- rpc_future = self._generic_stub.future_stream_unary(
- 'grupe', 'mevvod', iter([b'def']), test_constants.LONG_TIMEOUT)
- with self.assertRaises(face.LocalError) as exception_assertion_context:
- rpc_future.result()
- self.assertIs(exception_assertion_context.exception.code,
- interfaces.StatusCode.UNIMPLEMENTED)
- self.assertIs(rpc_future.exception().code,
- interfaces.StatusCode.UNIMPLEMENTED)
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_utilities_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_utilities_test.py
deleted file mode 100644
index 25773036f16..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/_utilities_test.py
+++ /dev/null
@@ -1,94 +0,0 @@
-# Copyright 2015 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Tests of grpc.beta.utilities."""
-
-import threading
-import time
-import unittest
-
-from grpc.beta import implementations
-from grpc.beta import utilities
-from grpc.framework.foundation import future
-
-from tests.unit.framework.common import test_constants
-
-
-class _Callback(object):
-
- def __init__(self):
- self._condition = threading.Condition()
- self._value = None
-
- def accept_value(self, value):
- with self._condition:
- self._value = value
- self._condition.notify_all()
-
- def block_until_called(self):
- with self._condition:
- while self._value is None:
- self._condition.wait()
- return self._value
-
-
-@unittest.skip('https://github.com/grpc/grpc/issues/16134')
-class ChannelConnectivityTest(unittest.TestCase):
-
- def test_lonely_channel_connectivity(self):
- channel = implementations.insecure_channel('localhost', 12345)
- callback = _Callback()
-
- ready_future = utilities.channel_ready_future(channel)
- ready_future.add_done_callback(callback.accept_value)
- with self.assertRaises(future.TimeoutError):
- ready_future.result(timeout=test_constants.SHORT_TIMEOUT)
- self.assertFalse(ready_future.cancelled())
- self.assertFalse(ready_future.done())
- self.assertTrue(ready_future.running())
- ready_future.cancel()
- value_passed_to_callback = callback.block_until_called()
- self.assertIs(ready_future, value_passed_to_callback)
- self.assertTrue(ready_future.cancelled())
- self.assertTrue(ready_future.done())
- self.assertFalse(ready_future.running())
-
- def test_immediately_connectable_channel_connectivity(self):
- server = implementations.server({})
- port = server.add_insecure_port('[::]:0')
- server.start()
- channel = implementations.insecure_channel('localhost', port)
- callback = _Callback()
-
- try:
- ready_future = utilities.channel_ready_future(channel)
- ready_future.add_done_callback(callback.accept_value)
- self.assertIsNone(
- ready_future.result(timeout=test_constants.LONG_TIMEOUT))
- value_passed_to_callback = callback.block_until_called()
- self.assertIs(ready_future, value_passed_to_callback)
- self.assertFalse(ready_future.cancelled())
- self.assertTrue(ready_future.done())
- self.assertFalse(ready_future.running())
- # Cancellation after maturity has no effect.
- ready_future.cancel()
- self.assertFalse(ready_future.cancelled())
- self.assertTrue(ready_future.done())
- self.assertFalse(ready_future.running())
- finally:
- ready_future.cancel()
- server.stop(0)
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/test_utilities.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/test_utilities.py
deleted file mode 100644
index c8d920d35e9..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/beta/test_utilities.py
+++ /dev/null
@@ -1,40 +0,0 @@
-# Copyright 2015 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Test-appropriate entry points into the gRPC Python Beta API."""
-
-import grpc
-from grpc.beta import implementations
-
-
-def not_really_secure_channel(host, port, channel_credentials,
- server_host_override):
- """Creates an insecure Channel to a remote host.
-
- Args:
- host: The name of the remote host to which to connect.
- port: The port of the remote host to which to connect.
- channel_credentials: The implementations.ChannelCredentials with which to
- connect.
- server_host_override: The target name used for SSL host name checking.
-
- Returns:
- An implementations.Channel to the remote host through which RPCs may be
- conducted.
- """
- target = '%s:%d' % (host, port)
- channel = grpc.secure_channel(target, channel_credentials, ((
- 'grpc.ssl_target_name_override',
- server_host_override,
- ),))
- return implementations.Channel(channel)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/README.md b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/README.md
deleted file mode 100644
index 100b43c1aaf..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/README.md
+++ /dev/null
@@ -1,15 +0,0 @@
-These are test keys *NOT* to be used in production.
-
-The `certificate_hierarchy_1` and `certificate_hierarchy_2` contain
-two disjoint but similarly organized certificate hierarchies. Each
-contains:
-
-* The respective root CA cert in `certs/ca.cert.pem`
-
-* The intermediate CA cert in
- `intermediate/certs/intermediate.cert.pem`, signed by the root CA
-
-* A client cert and a server cert--both signed by the intermediate
- CA--in `intermediate/certs/client.cert.pem` and
- `intermediate/certs/localhost-1.cert.pem`; the corresponding keys
- are in `intermediate/private`
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/ca.pem b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/ca.pem
deleted file mode 100755
index 49d39cd8ed5..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/ca.pem
+++ /dev/null
@@ -1,20 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIDWjCCAkKgAwIBAgIUWrP0VvHcy+LP6UuYNtiL9gBhD5owDQYJKoZIhvcNAQEL
-BQAwVjELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM
-GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDEPMA0GA1UEAwwGdGVzdGNhMB4XDTIw
-MDMxNzE4NTk1MVoXDTMwMDMxNTE4NTk1MVowVjELMAkGA1UEBhMCQVUxEzARBgNV
-BAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMgUHR5IEx0
-ZDEPMA0GA1UEAwwGdGVzdGNhMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC
-AQEAsGL0oXflF0LzoM+Bh+qUU9yhqzw2w8OOX5mu/iNCyUOBrqaHi7mGHx73GD01
-diNzCzvlcQqdNIH6NQSL7DTpBjca66jYT9u73vZe2MDrr1nVbuLvfu9850cdxiUO
-Inv5xf8+sTHG0C+a+VAvMhsLiRjsq+lXKRJyk5zkbbsETybqpxoJ+K7CoSy3yc/k
-QIY3TipwEtwkKP4hzyo6KiGd/DPexie4nBUInN3bS1BUeNZ5zeaIC2eg3bkeeW7c
-qT55b+Yen6CxY0TEkzBK6AKt/WUialKMgT0wbTxRZO7kUCH3Sq6e/wXeFdJ+HvdV
-LPlAg5TnMaNpRdQih/8nRFpsdwIDAQABoyAwHjAMBgNVHRMEBTADAQH/MA4GA1Ud
-DwEB/wQEAwICBDANBgkqhkiG9w0BAQsFAAOCAQEAkTrKZjBrJXHps/HrjNCFPb5a
-THuGPCSsepe1wkKdSp1h4HGRpLoCgcLysCJ5hZhRpHkRihhef+rFHEe60UePQO3S
-CVTtdJB4CYWpcNyXOdqefrbJW5QNljxgi6Fhvs7JJkBqdXIkWXtFk2eRgOIP2Eo9
-/OHQHlYnwZFrk6sp4wPyR+A95S0toZBcyDVz7u+hOW0pGK3wviOe9lvRgj/H3Pwt
-bewb0l+MhRig0/DVHamyVxrDRbqInU1/GTNCwcZkXKYFWSf92U+kIcTth24Q1gcw
-eZiLl5FfrWokUNytFElXob0V0a5/kbhiLc3yWmvWqHTpqCALbVyF+rKJo2f5Kw==
------END CERTIFICATE-----
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/server1.key b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/server1.key
deleted file mode 100755
index 086462992cf..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/server1.key
+++ /dev/null
@@ -1,28 +0,0 @@
------BEGIN PRIVATE KEY-----
-MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDnE443EknxvxBq
-6+hvn/t09hl8hx366EBYvZmVM/NC+7igXRAjiJiA/mIaCvL3MS0Iz5hBLxSGICU+
-WproA3GCIFITIwcf/ETyWj/5xpgZ4AKrLrjQmmX8mhwUajfF3UvwMJrCOVqPp67t
-PtP+2kBXaqrXdvnvXR41FsIB8V7zIAuIZB6bHQhiGVlc1sgZYsE2EGG9WMmHtS86
-qkAOTjG2XyjmPTGAwhGDpYkYrpzp99IiDh4/Veai81hn0ssQkbry0XRD/Ig3jcHh
-23WiriPNJ0JsbgXUSLKRPZObA9VgOLy2aXoN84IMaeK3yy+cwSYG/99w93fUZJte
-MXwz4oYZAgMBAAECggEBAIVn2Ncai+4xbH0OLWckabwgyJ4IM9rDc0LIU368O1kU
-koais8qP9dujAWgfoh3sGh/YGgKn96VnsZjKHlyMgF+r4TaDJn3k2rlAOWcurGlj
-1qaVlsV4HiEzp7pxiDmHhWvp4672Bb6iBG+bsjCUOEk/n9o9KhZzIBluRhtxCmw5
-nw4Do7z00PTvN81260uPWSc04IrytvZUiAIx/5qxD72bij2xJ8t/I9GI8g4FtoVB
-8pB6S/hJX1PZhh9VlU6Yk+TOfOVnbebG4W5138LkB835eqk3Zz0qsbc2euoi8Hxi
-y1VGwQEmMQ63jXz4c6g+X55ifvUK9Jpn5E8pq+pMd7ECgYEA93lYq+Cr54K4ey5t
-sWMa+ye5RqxjzgXj2Kqr55jb54VWG7wp2iGbg8FMlkQwzTJwebzDyCSatguEZLuB
-gRGroRnsUOy9vBvhKPOch9bfKIl6qOgzMJB267fBVWx5ybnRbWN/I7RvMQf3k+9y
-biCIVnxDLEEYyx7z85/5qxsXg/MCgYEA7wmWKtCTn032Hy9P8OL49T0X6Z8FlkDC
-Rk42ygrc/MUbugq9RGUxcCxoImOG9JXUpEtUe31YDm2j+/nbvrjl6/bP2qWs0V7l
-dTJl6dABP51pCw8+l4cWgBBX08Lkeen812AAFNrjmDCjX6rHjWHLJcpS18fnRRkP
-V1d/AHWX7MMCgYEA6Gsw2guhp0Zf2GCcaNK5DlQab8OL4Hwrpttzo4kuTlwtqNKp
-Q9H4al9qfF4Cr1TFya98+EVYf8yFRM3NLNjZpe3gwYf2EerlJj7VLcahw0KKzoN1
-QBENfwgPLRk5sDkx9VhSmcfl/diLroZdpAwtv3vo4nEoxeuGFbKTGx3Qkf0CgYEA
-xyR+dcb05Ygm3w4klHQTowQ10s1H80iaUcZBgQuR1ghEtDbUPZHsoR5t1xCB02ys
-DgAwLv1bChIvxvH/L6KM8ovZ2LekBX4AviWxoBxJnfz/EVau98B0b1auRN6eSC83
-FRuGldlSOW1z/nSh8ViizSYE5H5HX1qkXEippvFRE88CgYB3Bfu3YQY60ITWIShv
-nNkdcbTT9eoP9suaRJjw92Ln+7ZpALYlQMKUZmJ/5uBmLs4RFwUTQruLOPL4yLTH
-awADWUzs3IRr1fwn9E+zM8JVyKCnUEM3w4N5UZskGO2klashAd30hWO+knRv/y0r
-uGIYs9Ek7YXlXIRVrzMwcsrt1w==
------END PRIVATE KEY-----
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/server1.pem b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/server1.pem
deleted file mode 100755
index 88244f856c6..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/credentials/server1.pem
+++ /dev/null
@@ -1,22 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIDtDCCApygAwIBAgIUbJfTREJ6k6/+oInWhV1O1j3ZT0IwDQYJKoZIhvcNAQEL
-BQAwVjELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM
-GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDEPMA0GA1UEAwwGdGVzdGNhMB4XDTIw
-MDMxODAzMTA0MloXDTMwMDMxNjAzMTA0MlowZTELMAkGA1UEBhMCVVMxETAPBgNV
-BAgMCElsbGlub2lzMRAwDgYDVQQHDAdDaGljYWdvMRUwEwYDVQQKDAxFeGFtcGxl
-LCBDby4xGjAYBgNVBAMMESoudGVzdC5nb29nbGUuY29tMIIBIjANBgkqhkiG9w0B
-AQEFAAOCAQ8AMIIBCgKCAQEA5xOONxJJ8b8Qauvob5/7dPYZfIcd+uhAWL2ZlTPz
-Qvu4oF0QI4iYgP5iGgry9zEtCM+YQS8UhiAlPlqa6ANxgiBSEyMHH/xE8lo/+caY
-GeACqy640Jpl/JocFGo3xd1L8DCawjlaj6eu7T7T/tpAV2qq13b5710eNRbCAfFe
-8yALiGQemx0IYhlZXNbIGWLBNhBhvVjJh7UvOqpADk4xtl8o5j0xgMIRg6WJGK6c
-6ffSIg4eP1XmovNYZ9LLEJG68tF0Q/yIN43B4dt1oq4jzSdCbG4F1EiykT2TmwPV
-YDi8tml6DfOCDGnit8svnMEmBv/fcPd31GSbXjF8M+KGGQIDAQABo2swaTAJBgNV
-HRMEAjAAMAsGA1UdDwQEAwIF4DBPBgNVHREESDBGghAqLnRlc3QuZ29vZ2xlLmZy
-ghh3YXRlcnpvb2kudGVzdC5nb29nbGUuYmWCEioudGVzdC55b3V0dWJlLmNvbYcE
-wKgBAzANBgkqhkiG9w0BAQsFAAOCAQEAS8hDQA8PSgipgAml7Q3/djwQ644ghWQv
-C2Kb+r30RCY1EyKNhnQnIIh/OUbBZvh0M0iYsy6xqXgfDhCB93AA6j0i5cS8fkhH
-Jl4RK0tSkGQ3YNY4NzXwQP/vmUgfkw8VBAZ4Y4GKxppdATjffIW+srbAmdDruIRM
-wPeikgOoRrXf0LA1fi4TqxARzeRwenQpayNfGHTvVF9aJkl8HoaMunTAdG5pIVcr
-9GKi/gEMpXUJbbVv3U5frX1Wo4CFo+rZWJ/LyCMeb0jciNLxSdMwj/E/ZuExlyeZ
-gc9ctPjSMvgSyXEKv6Vwobleeg88V2ZgzenziORoWj4KszG/lbQZvg==
------END CERTIFICATE-----
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/__init__.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/__init__.py
deleted file mode 100644
index 5fb4f3c3cfd..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/__init__.py
+++ /dev/null
@@ -1,13 +0,0 @@
-# Copyright 2015 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/__init__.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/__init__.py
deleted file mode 100644
index 709f6175b2e..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/__init__.py
+++ /dev/null
@@ -1,102 +0,0 @@
-# Copyright 2019 The gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import contextlib
-import errno
-import os
-import socket
-
-_DEFAULT_SOCK_OPTIONS = (socket.SO_REUSEADDR,
- socket.SO_REUSEPORT) if os.name != 'nt' else (
- socket.SO_REUSEADDR,)
-_UNRECOVERABLE_ERRNOS = (errno.EADDRINUSE, errno.ENOSR)
-
-
-def get_socket(bind_address='localhost',
- port=0,
- listen=True,
- sock_options=_DEFAULT_SOCK_OPTIONS):
- """Opens a socket.
-
- Useful for reserving a port for a system-under-test.
-
- Args:
- bind_address: The host to which to bind.
- port: The port to which to bind.
- listen: A boolean value indicating whether or not to listen on the socket.
- sock_options: A sequence of socket options to apply to the socket.
-
- Returns:
- A tuple containing:
- - the address to which the socket is bound
- - the port to which the socket is bound
- - the socket object itself
- """
- _sock_options = sock_options if sock_options else []
- if socket.has_ipv6:
- address_families = (socket.AF_INET6, socket.AF_INET)
- else:
- address_families = (socket.AF_INET)
- for address_family in address_families:
- try:
- sock = socket.socket(address_family, socket.SOCK_STREAM)
- for sock_option in _sock_options:
- sock.setsockopt(socket.SOL_SOCKET, sock_option, 1)
- sock.bind((bind_address, port))
- if listen:
- sock.listen(1)
- return bind_address, sock.getsockname()[1], sock
- except OSError as os_error:
- sock.close()
- if os_error.errno in _UNRECOVERABLE_ERRNOS:
- raise
- else:
- continue
- # For PY2, socket.error is a child class of IOError; for PY3, it is
- # pointing to OSError. We need this catch to make it 2/3 agnostic.
- except socket.error: # pylint: disable=duplicate-except
- sock.close()
- continue
- raise RuntimeError("Failed to bind to {} with sock_options {}".format(
- bind_address, sock_options))
-
-
-@contextlib.contextmanager
-def bound_socket(bind_address='localhost',
- port=0,
- listen=True,
- sock_options=_DEFAULT_SOCK_OPTIONS):
- """Opens a socket bound to an arbitrary port.
-
- Useful for reserving a port for a system-under-test.
-
- Args:
- bind_address: The host to which to bind.
- port: The port to which to bind.
- listen: A boolean value indicating whether or not to listen on the socket.
- sock_options: A sequence of socket options to apply to the socket.
-
- Yields:
- A tuple containing:
- - the address to which the socket is bound
- - the port to which the socket is bound
- """
- host, port, sock = get_socket(bind_address=bind_address,
- port=port,
- listen=listen,
- sock_options=sock_options)
- try:
- yield host, port
- finally:
- sock.close()
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/test_constants.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/test_constants.py
deleted file mode 100644
index 2b9eb2e35bd..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/test_constants.py
+++ /dev/null
@@ -1,45 +0,0 @@
-# Copyright 2015 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Constants shared among tests throughout RPC Framework."""
-
-# Value for maximum duration in seconds that a test is allowed for its actual
-# behavioral logic, excluding all time spent deliberately waiting in the test.
-TIME_ALLOWANCE = 10
-# Value for maximum duration in seconds of RPCs that may time out as part of a
-# test.
-SHORT_TIMEOUT = 4
-# Absurdly large value for maximum duration in seconds for should-not-time-out
-# RPCs made during tests.
-LONG_TIMEOUT = 3000
-# Values to supply on construction of an object that will service RPCs; these
-# should not be used as the actual timeout values of any RPCs made during tests.
-DEFAULT_TIMEOUT = 300
-MAXIMUM_TIMEOUT = 3600
-
-# The number of payloads to transmit in streaming tests.
-STREAM_LENGTH = 200
-
-# The size of payloads to transmit in tests.
-PAYLOAD_SIZE = 256 * 1024 + 17
-
-# The concurrency to use in tests of concurrent RPCs that will not create as
-# many threads as RPCs.
-RPC_CONCURRENCY = 200
-
-# The concurrency to use in tests of concurrent RPCs that will create as many
-# threads as RPCs.
-THREAD_CONCURRENCY = 25
-
-# The size of thread pools to use in tests.
-POOL_SIZE = 10
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/test_control.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/test_control.py
deleted file mode 100644
index 999cb5f229d..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/test_control.py
+++ /dev/null
@@ -1,97 +0,0 @@
-# Copyright 2015 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Code for instructing systems under test to block or fail."""
-
-import abc
-import contextlib
-import threading
-
-import six
-
-
-class Defect(Exception):
- """Simulates a programming defect raised into in a system under test.
-
- Use of a standard exception type is too easily misconstrued as an actual
- defect in either the test infrastructure or the system under test.
- """
-
-
-class Control(six.with_metaclass(abc.ABCMeta)):
- """An object that accepts program control from a system under test.
-
- Systems under test passed a Control should call its control() method
- frequently during execution. The control() method may block, raise an
- exception, or do nothing, all according to the enclosing test's desire for
- the system under test to simulate freezing, failing, or functioning.
- """
-
- @abc.abstractmethod
- def control(self):
- """Potentially does anything."""
- raise NotImplementedError()
-
-
-class PauseFailControl(Control):
- """A Control that can be used to pause or fail code under control.
-
- This object is only safe for use from two threads: one of the system under
- test calling control and the other from the test system calling pause,
- block_until_paused, and fail.
- """
-
- def __init__(self):
- self._condition = threading.Condition()
- self._pause = False
- self._paused = False
- self._fail = False
-
- def control(self):
- with self._condition:
- if self._fail:
- raise Defect()
-
- while self._pause:
- self._paused = True
- self._condition.notify_all()
- self._condition.wait()
- self._paused = False
-
- @contextlib.contextmanager
- def pause(self):
- """Pauses code under control while controlling code is in context."""
- with self._condition:
- self._pause = True
- yield
- with self._condition:
- self._pause = False
- self._condition.notify_all()
-
- def block_until_paused(self):
- """Blocks controlling code until code under control is paused.
-
- May only be called within the context of a pause call.
- """
- with self._condition:
- while not self._paused:
- self._condition.wait()
-
- @contextlib.contextmanager
- def fail(self):
- """Fails code under control while controlling code is in context."""
- with self._condition:
- self._fail = True
- yield
- with self._condition:
- self._fail = False
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/test_coverage.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/test_coverage.py
deleted file mode 100644
index f90a11963fb..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/common/test_coverage.py
+++ /dev/null
@@ -1,101 +0,0 @@
-# Copyright 2015 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Governs coverage for tests of RPCs throughout RPC Framework."""
-
-import abc
-
-import six
-
-# This code is designed for use with the unittest module.
-# pylint: disable=invalid-name
-
-
-class Coverage(six.with_metaclass(abc.ABCMeta)):
- """Specification of test coverage."""
-
- @abc.abstractmethod
- def testSuccessfulUnaryRequestUnaryResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testSuccessfulUnaryRequestStreamResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testSuccessfulStreamRequestUnaryResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testSuccessfulStreamRequestStreamResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testSequentialInvocations(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testParallelInvocations(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testWaitingForSomeButNotAllParallelInvocations(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testCancelledUnaryRequestUnaryResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testCancelledUnaryRequestStreamResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testCancelledStreamRequestUnaryResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testCancelledStreamRequestStreamResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testExpiredUnaryRequestUnaryResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testExpiredUnaryRequestStreamResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testExpiredStreamRequestUnaryResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testExpiredStreamRequestStreamResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testFailedUnaryRequestUnaryResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testFailedUnaryRequestStreamResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testFailedStreamRequestUnaryResponse(self):
- raise NotImplementedError()
-
- @abc.abstractmethod
- def testFailedStreamRequestStreamResponse(self):
- raise NotImplementedError()
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/foundation/__init__.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/foundation/__init__.py
deleted file mode 100644
index 5fb4f3c3cfd..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/foundation/__init__.py
+++ /dev/null
@@ -1,13 +0,0 @@
-# Copyright 2015 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/foundation/_logging_pool_test.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/foundation/_logging_pool_test.py
deleted file mode 100644
index c4ea03177cc..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/foundation/_logging_pool_test.py
+++ /dev/null
@@ -1,73 +0,0 @@
-# Copyright 2015 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Tests for grpc.framework.foundation.logging_pool."""
-
-import threading
-import unittest
-
-from grpc.framework.foundation import logging_pool
-
-_POOL_SIZE = 16
-
-
-class _CallableObject(object):
-
- def __init__(self):
- self._lock = threading.Lock()
- self._passed_values = []
-
- def __call__(self, value):
- with self._lock:
- self._passed_values.append(value)
-
- def passed_values(self):
- with self._lock:
- return tuple(self._passed_values)
-
-
-class LoggingPoolTest(unittest.TestCase):
-
- def testUpAndDown(self):
- pool = logging_pool.pool(_POOL_SIZE)
- pool.shutdown(wait=True)
-
- with logging_pool.pool(_POOL_SIZE) as pool:
- self.assertIsNotNone(pool)
-
- def testTaskExecuted(self):
- test_list = []
-
- with logging_pool.pool(_POOL_SIZE) as pool:
- pool.submit(lambda: test_list.append(object())).result()
-
- self.assertTrue(test_list)
-
- def testException(self):
- with logging_pool.pool(_POOL_SIZE) as pool:
- raised_exception = pool.submit(lambda: 1 / 0).exception()
-
- self.assertIsNotNone(raised_exception)
-
- def testCallableObjectExecuted(self):
- callable_object = _CallableObject()
- passed_object = object()
- with logging_pool.pool(_POOL_SIZE) as pool:
- future = pool.submit(callable_object, passed_object)
- self.assertIsNone(future.result())
- self.assertSequenceEqual((passed_object,),
- callable_object.passed_values())
-
-
-if __name__ == '__main__':
- unittest.main(verbosity=2)
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/foundation/stream_testing.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/foundation/stream_testing.py
deleted file mode 100644
index dd5c5b3b031..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/framework/foundation/stream_testing.py
+++ /dev/null
@@ -1,57 +0,0 @@
-# Copyright 2015 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Utilities for testing stream-related code."""
-
-from grpc.framework.foundation import stream
-
-
-class TestConsumer(stream.Consumer):
- """A stream.Consumer instrumented for testing.
-
- Attributes:
- calls: A sequence of value-termination pairs describing the history of calls
- made on this object.
- """
-
- def __init__(self):
- self.calls = []
-
- def consume(self, value):
- """See stream.Consumer.consume for specification."""
- self.calls.append((value, False))
-
- def terminate(self):
- """See stream.Consumer.terminate for specification."""
- self.calls.append((None, True))
-
- def consume_and_terminate(self, value):
- """See stream.Consumer.consume_and_terminate for specification."""
- self.calls.append((value, True))
-
- def is_legal(self):
- """Reports whether or not a legal sequence of calls has been made."""
- terminated = False
- for value, terminal in self.calls:
- if terminated:
- return False
- elif terminal:
- terminated = True
- elif value is None:
- return False
- else: # pylint: disable=useless-else-on-loop
- return True
-
- def values(self):
- """Returns the sequence of values that have been passed to this Consumer."""
- return [value for value, _ in self.calls if value]
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/resources.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/resources.py
deleted file mode 100644
index 6efd870fc86..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/resources.py
+++ /dev/null
@@ -1,113 +0,0 @@
-# Copyright 2015 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Constants and functions for data used in testing."""
-
-import os
-import pkgutil
-
-_ROOT_CERTIFICATES_RESOURCE_PATH = 'credentials/ca.pem'
-_PRIVATE_KEY_RESOURCE_PATH = 'credentials/server1.key'
-_CERTIFICATE_CHAIN_RESOURCE_PATH = 'credentials/server1.pem'
-
-
-def test_root_certificates():
- return pkgutil.get_data(__name__, _ROOT_CERTIFICATES_RESOURCE_PATH)
-
-
-def private_key():
- return pkgutil.get_data(__name__, _PRIVATE_KEY_RESOURCE_PATH)
-
-
-def certificate_chain():
- return pkgutil.get_data(__name__, _CERTIFICATE_CHAIN_RESOURCE_PATH)
-
-
-def cert_hier_1_root_ca_cert():
- return pkgutil.get_data(
- __name__, 'credentials/certificate_hierarchy_1/certs/ca.cert.pem')
-
-
-def cert_hier_1_intermediate_ca_cert():
- return pkgutil.get_data(
- __name__,
- 'credentials/certificate_hierarchy_1/intermediate/certs/intermediate.cert.pem'
- )
-
-
-def cert_hier_1_client_1_key():
- return pkgutil.get_data(
- __name__,
- 'credentials/certificate_hierarchy_1/intermediate/private/client.key.pem'
- )
-
-
-def cert_hier_1_client_1_cert():
- return pkgutil.get_data(
- __name__,
- 'credentials/certificate_hierarchy_1/intermediate/certs/client.cert.pem'
- )
-
-
-def cert_hier_1_server_1_key():
- return pkgutil.get_data(
- __name__,
- 'credentials/certificate_hierarchy_1/intermediate/private/localhost-1.key.pem'
- )
-
-
-def cert_hier_1_server_1_cert():
- return pkgutil.get_data(
- __name__,
- 'credentials/certificate_hierarchy_1/intermediate/certs/localhost-1.cert.pem'
- )
-
-
-def cert_hier_2_root_ca_cert():
- return pkgutil.get_data(
- __name__, 'credentials/certificate_hierarchy_2/certs/ca.cert.pem')
-
-
-def cert_hier_2_intermediate_ca_cert():
- return pkgutil.get_data(
- __name__,
- 'credentials/certificate_hierarchy_2/intermediate/certs/intermediate.cert.pem'
- )
-
-
-def cert_hier_2_client_1_key():
- return pkgutil.get_data(
- __name__,
- 'credentials/certificate_hierarchy_2/intermediate/private/client.key.pem'
- )
-
-
-def cert_hier_2_client_1_cert():
- return pkgutil.get_data(
- __name__,
- 'credentials/certificate_hierarchy_2/intermediate/certs/client.cert.pem'
- )
-
-
-def cert_hier_2_server_1_key():
- return pkgutil.get_data(
- __name__,
- 'credentials/certificate_hierarchy_2/intermediate/private/localhost-1.key.pem'
- )
-
-
-def cert_hier_2_server_1_cert():
- return pkgutil.get_data(
- __name__,
- 'credentials/certificate_hierarchy_2/intermediate/certs/localhost-1.cert.pem'
- )
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/test_common.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/test_common.py
deleted file mode 100644
index dae69cbcebc..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/test_common.py
+++ /dev/null
@@ -1,145 +0,0 @@
-# Copyright 2015 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Common code used throughout tests of gRPC."""
-
-import collections
-from concurrent import futures
-import threading
-
-import grpc
-import six
-
-INVOCATION_INITIAL_METADATA = (
- ('0', 'abc'),
- ('1', 'def'),
- ('2', 'ghi'),
-)
-SERVICE_INITIAL_METADATA = (
- ('3', 'jkl'),
- ('4', 'mno'),
- ('5', 'pqr'),
-)
-SERVICE_TERMINAL_METADATA = (
- ('6', 'stu'),
- ('7', 'vwx'),
- ('8', 'yza'),
-)
-DETAILS = 'test details'
-
-
-def metadata_transmitted(original_metadata, transmitted_metadata):
- """Judges whether or not metadata was acceptably transmitted.
-
- gRPC is allowed to insert key-value pairs into the metadata values given by
- applications and to reorder key-value pairs with different keys but it is not
- allowed to alter existing key-value pairs or to reorder key-value pairs with
- the same key.
-
- Args:
- original_metadata: A metadata value used in a test of gRPC. An iterable over
- iterables of length 2.
- transmitted_metadata: A metadata value corresponding to original_metadata
- after having been transmitted via gRPC. An iterable over iterables of
- length 2.
-
- Returns:
- A boolean indicating whether transmitted_metadata accurately reflects
- original_metadata after having been transmitted via gRPC.
- """
- original = collections.defaultdict(list)
- for key, value in original_metadata:
- original[key].append(value)
- transmitted = collections.defaultdict(list)
- for key, value in transmitted_metadata:
- transmitted[key].append(value)
-
- for key, values in six.iteritems(original):
- transmitted_values = transmitted[key]
- transmitted_iterator = iter(transmitted_values)
- try:
- for value in values:
- while True:
- transmitted_value = next(transmitted_iterator)
- if value == transmitted_value:
- break
- except StopIteration:
- return False
- else:
- return True
-
-
-def test_secure_channel(target, channel_credentials, server_host_override):
- """Creates an insecure Channel to a remote host.
-
- Args:
- host: The name of the remote host to which to connect.
- port: The port of the remote host to which to connect.
- channel_credentials: The implementations.ChannelCredentials with which to
- connect.
- server_host_override: The target name used for SSL host name checking.
-
- Returns:
- An implementations.Channel to the remote host through which RPCs may be
- conducted.
- """
- channel = grpc.secure_channel(target, channel_credentials, ((
- 'grpc.ssl_target_name_override',
- server_host_override,
- ),))
- return channel
-
-
-def test_server(max_workers=10, reuse_port=False):
- """Creates an insecure grpc server.
-
- These servers have SO_REUSEPORT disabled to prevent cross-talk.
- """
- return grpc.server(futures.ThreadPoolExecutor(max_workers=max_workers),
- options=(('grpc.so_reuseport', int(reuse_port)),))
-
-
-class WaitGroup(object):
-
- def __init__(self, n=0):
- self.count = n
- self.cv = threading.Condition()
-
- def add(self, n):
- self.cv.acquire()
- self.count += n
- self.cv.release()
-
- def done(self):
- self.cv.acquire()
- self.count -= 1
- if self.count == 0:
- self.cv.notify_all()
- self.cv.release()
-
- def wait(self):
- self.cv.acquire()
- while self.count > 0:
- self.cv.wait()
- self.cv.release()
-
-
-def running_under_gevent():
- try:
- from gevent import monkey
- import gevent.socket
- except ImportError:
- return False
- else:
- import socket
- return socket.socket is gevent.socket.socket
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/thread_pool.py b/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/thread_pool.py
deleted file mode 100644
index 971806fd93f..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/tests/unit/thread_pool.py
+++ /dev/null
@@ -1,34 +0,0 @@
-# Copyright 2016 gRPC authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-from concurrent import futures
-import threading
-
-
-class RecordingThreadPool(futures.ThreadPoolExecutor):
- """A thread pool that records if used."""
-
- def __init__(self, max_workers):
- self._tp_executor = futures.ThreadPoolExecutor(max_workers=max_workers)
- self._lock = threading.Lock()
- self._was_used = False
-
- def submit(self, fn, *args, **kwargs): # pylint: disable=arguments-differ
- with self._lock:
- self._was_used = True
- self._tp_executor.submit(fn, *args, **kwargs)
-
- def was_used(self):
- with self._lock:
- return self._was_used
diff --git a/contrib/libs/grpc/src/python/grpcio_tests/ya.make b/contrib/libs/grpc/src/python/grpcio_tests/ya.make
deleted file mode 100644
index 11ac47ae693..00000000000
--- a/contrib/libs/grpc/src/python/grpcio_tests/ya.make
+++ /dev/null
@@ -1,144 +0,0 @@
-PY3TEST()
-
-LICENSE(Apache-2.0)
-
-LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-
-PEERDIR(
- contrib/python/grpcio
-)
-
-NO_LINT()
-
-PY_SRCS(
- TOP_LEVEL
- # tests/_sanity/__init__.py
- # tests/testing/proto/__init__.py
- # tests/testing/__init__.py
- # tests/testing/_application_common.py
- # tests/testing/_application_testing_common.py
- # tests/testing/_client_application.py
- # tests/testing/_client_test.py
- # tests/testing/_server_application.py
- # tests/testing/_server_test.py
- # tests/testing/_time_test.py
- tests/unit/__init__.py
- tests/unit/_cython/__init__.py
- tests/unit/_cython/_common.py
- tests/unit/_cython/test_utilities.py
- tests/unit/_exit_scenarios.py
- tests/unit/_from_grpc_import_star.py
- tests/unit/_rpc_test_helpers.py
- tests/unit/_server_shutdown_scenarios.py
- tests/unit/_signal_client.py
- tests/unit/_tcp_proxy.py
- tests/unit/beta/__init__.py
- tests/unit/beta/test_utilities.py
- tests/unit/framework/__init__.py
- tests/unit/framework/common/__init__.py
- tests/unit/framework/common/test_constants.py
- tests/unit/framework/common/test_control.py
- tests/unit/framework/common/test_coverage.py
- tests/unit/framework/foundation/__init__.py
- tests/unit/resources.py
- tests/unit/test_common.py
- tests/unit/thread_pool.py
- # protofiles
- # tests/interop/__init__.py
- # tests/interop/_intraop_test_case.py
- # tests/interop/client.py
- # tests/interop/methods.py
- # tests/interop/resources.py
- # tests/interop/server.py
- # tests/interop/service.py
- # protofiles
- # tests/fork/__init__.py
- # tests/fork/client.py
- # tests/fork/methods.py
- # protofiles
- # tests/__init__.py
- # tests/_loader.py
- # tests/_result.py
- # tests/_runner.py
-)
-
-TEST_SRCS(
- # coverage
- # tests/_sanity/_sanity_test.py
- tests/unit/_api_test.py
- tests/unit/_abort_test.py
- # CRASH
- # tests/unit/_auth_context_test.py
- tests/unit/_auth_test.py
- tests/unit/_channel_args_test.py
- tests/unit/_channel_close_test.py
- tests/unit/_channel_connectivity_test.py
- tests/unit/_channel_ready_future_test.py
- # FLAKY
- # tests/unit/_compression_test.py
- tests/unit/_contextvars_propagation_test.py
- tests/unit/_credentials_test.py
- tests/unit/_cython/_cancel_many_calls_test.py
- tests/unit/_cython/_channel_test.py
- tests/unit/_cython/_fork_test.py
- tests/unit/_cython/_no_messages_server_completion_queue_per_call_test.py
- tests/unit/_cython/_no_messages_single_server_completion_queue_test.py
- tests/unit/_cython/_read_some_but_not_all_responses_test.py
- tests/unit/_cython/_server_test.py
- tests/unit/_cython/cygrpc_test.py
- tests/unit/_dns_resolver_test.py
- tests/unit/_dynamic_stubs_test.py
- tests/unit/_empty_message_test.py
- tests/unit/_error_message_encoding_test.py
- tests/unit/_exit_test.py
- tests/unit/_grpc_shutdown_test.py
- tests/unit/_interceptor_test.py
- tests/unit/_invalid_metadata_test.py
- tests/unit/_invocation_defects_test.py
- tests/unit/_local_credentials_test.py
- tests/unit/_logging_test.py
- tests/unit/_metadata_code_details_test.py
- tests/unit/_metadata_flags_test.py
- tests/unit/_metadata_test.py
- tests/unit/_reconnect_test.py
- tests/unit/_resource_exhausted_test.py
- tests/unit/_rpc_part_1_test.py
- tests/unit/_rpc_part_2_test.py
- tests/unit/_server_shutdown_test.py
- tests/unit/_xds_credentials_test.py
- # tests.testing
- # tests/unit/_server_ssl_cert_config_test.py
- tests/unit/_server_test.py
- tests/unit/_server_wait_for_termination_test.py
- # CRASH
- # tests/unit/_session_cache_test.py
- tests/unit/_signal_handling_test.py
- tests/unit/_version_test.py
- tests/unit/beta/_beta_features_test.py
- tests/unit/beta/_connectivity_channel_test.py
- # oauth2client
- # tests/unit/beta/_implementations_test.py
- tests/unit/beta/_not_found_test.py
- tests/unit/beta/_utilities_test.py
- tests/unit/framework/foundation/_logging_pool_test.py
- tests/unit/framework/foundation/stream_testing.py
- # protofiles
- # tests/interop/_insecure_intraop_test.py
- # tests/interop/_secure_intraop_test.py
- # tests/fork/_fork_interop_test.py
-)
-
-SIZE(MEDIUM)
-
-RESOURCE_FILES(
- PREFIX contrib/libs/grpc/src/python/grpcio_tests/
- tests/unit/credentials/ca.pem
- tests/unit/credentials/server1.key
- tests/unit/credentials/server1.pem
-)
-
-EXPLICIT_DATA()
-
-REQUIREMENTS(network:full)
-
-END()
diff --git a/contrib/libs/grpc/test/core/util/build.cc b/contrib/libs/grpc/test/core/util/build.cc
deleted file mode 100644
index 04d39e9574d..00000000000
--- a/contrib/libs/grpc/test/core/util/build.cc
+++ /dev/null
@@ -1,77 +0,0 @@
-// Copyright 2021 gRPC authors.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-bool BuiltUnderValgrind() {
-#ifdef RUNNING_ON_VALGRIND
- return true;
-#else
- return false;
-#endif
-}
-
-bool BuiltUnderTsan() {
-#if defined(__has_feature)
-#if __has_feature(thread_sanitizer)
- return true;
-#else
- return false;
-#endif
-#else
-#ifdef THREAD_SANITIZER
- return true;
-#else
- return false;
-#endif
-#endif
-}
-
-bool BuiltUnderAsan() {
-#if defined(__has_feature)
-#if __has_feature(address_sanitizer)
- return true;
-#else
- return false;
-#endif
-#else
-#ifdef ADDRESS_SANITIZER
- return true;
-#else
- return false;
-#endif
-#endif
-}
-
-bool BuiltUnderMsan() {
-#if defined(__has_feature)
-#if __has_feature(memory_sanitizer)
- return true;
-#else
- return false;
-#endif
-#else
-#ifdef MEMORY_SANITIZER
- return true;
-#else
- return false;
-#endif
-#endif
-}
-
-bool BuiltUnderUbsan() {
-#ifdef GRPC_UBSAN
- return true;
-#else
- return false;
-#endif
-}
diff --git a/contrib/libs/grpc/test/core/util/build.h b/contrib/libs/grpc/test/core/util/build.h
deleted file mode 100644
index 9cdab0ced78..00000000000
--- a/contrib/libs/grpc/test/core/util/build.h
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright 2021 gRPC authors.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#ifndef GRPC_TEST_CORE_UTIL_BUILD_H
-#define GRPC_TEST_CORE_UTIL_BUILD_H
-
-// Returns whether this is built using our Valgrind config
-bool BuiltUnderValgrind();
-
-// Returns whether this is built under ThreadSanitizer
-bool BuiltUnderTsan();
-
-// Returns whether this is built under AddressSanitizer
-bool BuiltUnderAsan();
-
-// Returns whether this is built under MemorySanitizer
-bool BuiltUnderMsan();
-
-// Returns whether this is built under UndefinedBehaviorSanitizer
-bool BuiltUnderUbsan();
-
-#endif
diff --git a/contrib/libs/grpc/test/core/util/port.cc b/contrib/libs/grpc/test/core/util/port.cc
deleted file mode 100644
index 5a2e06266e5..00000000000
--- a/contrib/libs/grpc/test/core/util/port.cc
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include "src/core/lib/iomgr/port.h"
-
-#include "test/core/util/test_config.h"
-#if defined(GRPC_TEST_PICK_PORT)
-
-#include <stdbool.h>
-#include <stdio.h>
-#include <string.h>
-
-#include <grpc/grpc.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-
-#include "src/core/lib/address_utils/sockaddr_utils.h"
-#include "src/core/lib/http/httpcli.h"
-#include "src/core/lib/iomgr/resolve_address.h"
-#include "test/core/util/port.h"
-#include "test/core/util/port_server_client.h"
-
-static int* chosen_ports = nullptr;
-static size_t num_chosen_ports = 0;
-static grpc_core::Mutex* g_default_port_picker_mu;
-static gpr_once g_default_port_picker_init = GPR_ONCE_INIT;
-
-static void init_default_port_picker() {
- g_default_port_picker_mu = new grpc_core::Mutex();
-}
-
-static int free_chosen_port_locked(int port) {
- size_t i;
- int found = 0;
- size_t found_at = 0;
- /* Find the port and erase it from the list, then tell the server it can be
- freed. */
- for (i = 0; i < num_chosen_ports; i++) {
- if (chosen_ports[i] == port) {
- GPR_ASSERT(found == 0);
- found = 1;
- found_at = i;
- }
- }
- if (found) {
- chosen_ports[found_at] = chosen_ports[num_chosen_ports - 1];
- num_chosen_ports--;
- grpc_free_port_using_server(port);
- }
- return found;
-}
-
-static void free_chosen_ports(void) {
- grpc_core::MutexLock lock(g_default_port_picker_mu);
- size_t i;
- grpc_init();
- for (i = 0; i < num_chosen_ports; i++) {
- grpc_free_port_using_server(chosen_ports[i]);
- }
- grpc_shutdown();
- gpr_free(chosen_ports);
-}
-
-static void chose_port_locked(int port) {
- if (chosen_ports == nullptr) {
- atexit(free_chosen_ports);
- }
- num_chosen_ports++;
- chosen_ports = static_cast<int*>(
- gpr_realloc(chosen_ports, sizeof(int) * num_chosen_ports));
- chosen_ports[num_chosen_ports - 1] = port;
-}
-
-static int grpc_pick_unused_port_impl(void) {
- gpr_once_init(&g_default_port_picker_init, init_default_port_picker);
- grpc_core::MutexLock lock(g_default_port_picker_mu);
- int port = grpc_pick_port_using_server();
- if (port != 0) {
- chose_port_locked(port);
- }
-
- return port;
-}
-
-static int grpc_pick_unused_port_or_die_impl(void) {
- int port = grpc_pick_unused_port();
- if (port == 0) {
- fprintf(stderr,
- "gRPC tests require a helper port server to allocate ports used \n"
- "during the test.\n\n"
- "This server is not currently running.\n\n"
- "To start it, run tools/run_tests/start_port_server.py\n\n");
- exit(1);
- }
- return port;
-}
-
-static void grpc_recycle_unused_port_impl(int port) {
- gpr_once_init(&g_default_port_picker_init, init_default_port_picker);
- grpc_core::MutexLock lock(g_default_port_picker_mu);
- GPR_ASSERT(free_chosen_port_locked(port));
-}
-
-static grpc_pick_port_functions g_pick_port_functions = {
- grpc_pick_unused_port_impl, grpc_pick_unused_port_or_die_impl,
- grpc_recycle_unused_port_impl};
-
-int grpc_pick_unused_port(void) {
- return g_pick_port_functions.pick_unused_port_fn();
-}
-
-int grpc_pick_unused_port_or_die(void) {
- return g_pick_port_functions.pick_unused_port_or_die_fn();
-}
-
-void grpc_recycle_unused_port(int port) {
- g_pick_port_functions.recycle_unused_port_fn(port);
-}
-
-void grpc_set_pick_port_functions(grpc_pick_port_functions functions) {
- GPR_ASSERT(functions.pick_unused_port_fn != nullptr);
- GPR_ASSERT(functions.pick_unused_port_or_die_fn != nullptr);
- GPR_ASSERT(functions.recycle_unused_port_fn != nullptr);
- g_pick_port_functions = functions;
-}
-
-#endif /* GRPC_TEST_PICK_PORT */
diff --git a/contrib/libs/grpc/test/core/util/port.h b/contrib/libs/grpc/test/core/util/port.h
deleted file mode 100644
index 3a4cf4467a3..00000000000
--- a/contrib/libs/grpc/test/core/util/port.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CORE_UTIL_PORT_H
-#define GRPC_TEST_CORE_UTIL_PORT_H
-
-typedef struct grpc_pick_port_functions {
- int (*pick_unused_port_fn)(void);
- int (*pick_unused_port_or_die_fn)(void);
- void (*recycle_unused_port_fn)(int port);
-} grpc_pick_port_functions;
-
-/* pick a port number that is currently unused by either tcp or udp. return
- 0 on failure. */
-int grpc_pick_unused_port(void);
-/* pick a port number that is currently unused by either tcp or udp. abort
- on failure. */
-int grpc_pick_unused_port_or_die(void);
-
-/* Return a port which was previously returned by grpc_pick_unused_port().
- * Implementations of grpc_pick_unused_port() backed by a portserver may limit
- * the total number of ports available; this lets a binary return its allocated
- * ports back to the server if it is going to allocate a large number. */
-void grpc_recycle_unused_port(int port);
-
-/** Request the family of pick_port functions in \a functions be used. */
-void grpc_set_pick_port_functions(grpc_pick_port_functions functions);
-
-#endif /* GRPC_TEST_CORE_UTIL_PORT_H */
diff --git a/contrib/libs/grpc/test/core/util/port_server_client.cc b/contrib/libs/grpc/test/core/util/port_server_client.cc
deleted file mode 100644
index f5b5e28f953..00000000000
--- a/contrib/libs/grpc/test/core/util/port_server_client.cc
+++ /dev/null
@@ -1,238 +0,0 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "test/core/util/test_config.h"
-
-#ifdef GRPC_TEST_PICK_PORT
-#include <math.h>
-#include <string.h>
-
-#include <grpc/grpc.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-#include <grpc/support/string_util.h>
-#include <grpc/support/sync.h>
-#include <grpc/support/time.h>
-
-#include "src/core/lib/http/httpcli.h"
-#include "test/core/util/port_server_client.h"
-
-typedef struct freereq {
- gpr_mu* mu = nullptr;
- grpc_polling_entity pops = {};
- int done = 0;
-} freereq;
-
-static void destroy_pops_and_shutdown(void* p, grpc_error_handle /*error*/) {
- grpc_pollset* pollset =
- grpc_polling_entity_pollset(static_cast<grpc_polling_entity*>(p));
- grpc_pollset_destroy(pollset);
- gpr_free(pollset);
-}
-
-static void freed_port_from_server(void* arg, grpc_error_handle /*error*/) {
- freereq* pr = static_cast<freereq*>(arg);
- gpr_mu_lock(pr->mu);
- pr->done = 1;
- GRPC_LOG_IF_ERROR(
- "pollset_kick",
- grpc_pollset_kick(grpc_polling_entity_pollset(&pr->pops), nullptr));
- gpr_mu_unlock(pr->mu);
-}
-
-void grpc_free_port_using_server(int port) {
- grpc_httpcli_request req;
- grpc_httpcli_response rsp;
- freereq pr;
- char* path;
- grpc_closure* shutdown_closure;
-
- grpc_init();
- {
- grpc_core::ExecCtx exec_ctx;
-
- pr = {};
- memset(&req, 0, sizeof(req));
- rsp = {};
-
- grpc_pollset* pollset =
- static_cast<grpc_pollset*>(gpr_zalloc(grpc_pollset_size()));
- grpc_pollset_init(pollset, &pr.mu);
- pr.pops = grpc_polling_entity_create_from_pollset(pollset);
- shutdown_closure = GRPC_CLOSURE_CREATE(destroy_pops_and_shutdown, &pr.pops,
- grpc_schedule_on_exec_ctx);
-
- req.host = const_cast<char*>(GRPC_PORT_SERVER_ADDRESS);
- gpr_asprintf(&path, "/drop/%d", port);
- req.http.path = path;
-
- grpc_httpcli_get(&pr.pops, grpc_core::ResourceQuota::Default(), &req,
- grpc_core::ExecCtx::Get()->Now() + 30 * GPR_MS_PER_SEC,
- GRPC_CLOSURE_CREATE(freed_port_from_server, &pr,
- grpc_schedule_on_exec_ctx),
- &rsp);
- grpc_core::ExecCtx::Get()->Flush();
- gpr_mu_lock(pr.mu);
- while (!pr.done) {
- grpc_pollset_worker* worker = nullptr;
- if (!GRPC_LOG_IF_ERROR(
- "pollset_work",
- grpc_pollset_work(
- grpc_polling_entity_pollset(&pr.pops), &worker,
- grpc_core::ExecCtx::Get()->Now() + GPR_MS_PER_SEC))) {
- pr.done = 1;
- }
- }
- gpr_mu_unlock(pr.mu);
-
- grpc_pollset_shutdown(grpc_polling_entity_pollset(&pr.pops),
- shutdown_closure);
-
- gpr_free(path);
- grpc_http_response_destroy(&rsp);
- }
- grpc_shutdown();
-}
-
-typedef struct portreq {
- gpr_mu* mu = nullptr;
- grpc_polling_entity pops = {};
- int port = 0;
- int retries = 0;
- char* server = nullptr;
- grpc_httpcli_response response = {};
-} portreq;
-
-static void got_port_from_server(void* arg, grpc_error_handle error) {
- size_t i;
- int port = 0;
- portreq* pr = static_cast<portreq*>(arg);
- int failed = 0;
- grpc_httpcli_response* response = &pr->response;
-
- if (error != GRPC_ERROR_NONE) {
- failed = 1;
- gpr_log(GPR_DEBUG, "failed port pick from server: retrying [%s]",
- grpc_error_std_string(error).c_str());
- } else if (response->status != 200) {
- failed = 1;
- gpr_log(GPR_DEBUG, "failed port pick from server: status=%d",
- response->status);
- }
-
- if (failed) {
- grpc_httpcli_request req;
- memset(&req, 0, sizeof(req));
- if (pr->retries >= 5) {
- gpr_mu_lock(pr->mu);
- pr->port = 0;
- GRPC_LOG_IF_ERROR(
- "pollset_kick",
- grpc_pollset_kick(grpc_polling_entity_pollset(&pr->pops), nullptr));
- gpr_mu_unlock(pr->mu);
- return;
- }
- GPR_ASSERT(pr->retries < 10);
- gpr_sleep_until(gpr_time_add(
- gpr_now(GPR_CLOCK_REALTIME),
- gpr_time_from_millis(
- static_cast<int64_t>(
- 1000.0 * (1 + pow(1.3, pr->retries) * rand() / RAND_MAX)),
- GPR_TIMESPAN)));
- pr->retries++;
- req.host = pr->server;
- req.http.path = const_cast<char*>("/get");
- grpc_http_response_destroy(&pr->response);
- pr->response = {};
- grpc_httpcli_get(&pr->pops, grpc_core::ResourceQuota::Default(), &req,
- grpc_core::ExecCtx::Get()->Now() + 30 * GPR_MS_PER_SEC,
- GRPC_CLOSURE_CREATE(got_port_from_server, pr,
- grpc_schedule_on_exec_ctx),
- &pr->response);
- return;
- }
- GPR_ASSERT(response);
- GPR_ASSERT(response->status == 200);
- for (i = 0; i < response->body_length; i++) {
- GPR_ASSERT(response->body[i] >= '0' && response->body[i] <= '9');
- port = port * 10 + response->body[i] - '0';
- }
- GPR_ASSERT(port > 1024);
- gpr_mu_lock(pr->mu);
- pr->port = port;
- GRPC_LOG_IF_ERROR(
- "pollset_kick",
- grpc_pollset_kick(grpc_polling_entity_pollset(&pr->pops), nullptr));
- gpr_mu_unlock(pr->mu);
-}
-
-int grpc_pick_port_using_server(void) {
- grpc_httpcli_request req;
- portreq pr;
- grpc_closure* shutdown_closure;
-
- grpc_init();
- {
- grpc_core::ExecCtx exec_ctx;
- pr = {};
- memset(&req, 0, sizeof(req));
- grpc_pollset* pollset =
- static_cast<grpc_pollset*>(gpr_zalloc(grpc_pollset_size()));
- grpc_pollset_init(pollset, &pr.mu);
- pr.pops = grpc_polling_entity_create_from_pollset(pollset);
- shutdown_closure = GRPC_CLOSURE_CREATE(destroy_pops_and_shutdown, &pr.pops,
- grpc_schedule_on_exec_ctx);
- pr.port = -1;
- pr.server = const_cast<char*>(GRPC_PORT_SERVER_ADDRESS);
-
- req.host = const_cast<char*>(GRPC_PORT_SERVER_ADDRESS);
- req.http.path = const_cast<char*>("/get");
-
- grpc_httpcli_get(&pr.pops, grpc_core::ResourceQuota::Default(), &req,
- grpc_core::ExecCtx::Get()->Now() + 30 * GPR_MS_PER_SEC,
- GRPC_CLOSURE_CREATE(got_port_from_server, &pr,
- grpc_schedule_on_exec_ctx),
- &pr.response);
- grpc_core::ExecCtx::Get()->Flush();
- gpr_mu_lock(pr.mu);
- while (pr.port == -1) {
- grpc_pollset_worker* worker = nullptr;
- if (!GRPC_LOG_IF_ERROR(
- "pollset_work",
- grpc_pollset_work(
- grpc_polling_entity_pollset(&pr.pops), &worker,
- grpc_core::ExecCtx::Get()->Now() + GPR_MS_PER_SEC))) {
- pr.port = 0;
- }
- }
- gpr_mu_unlock(pr.mu);
-
- grpc_http_response_destroy(&pr.response);
- grpc_pollset_shutdown(grpc_polling_entity_pollset(&pr.pops),
- shutdown_closure);
-
- grpc_core::ExecCtx::Get()->Flush();
- }
- grpc_shutdown();
-
- return pr.port;
-}
-
-#endif // GRPC_TEST_PICK_PORT
diff --git a/contrib/libs/grpc/test/core/util/port_server_client.h b/contrib/libs/grpc/test/core/util/port_server_client.h
deleted file mode 100644
index 86dd7018ffd..00000000000
--- a/contrib/libs/grpc/test/core/util/port_server_client.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CORE_UTIL_PORT_SERVER_CLIENT_H
-#define GRPC_TEST_CORE_UTIL_PORT_SERVER_CLIENT_H
-
-// C interface to port_server.py
-
-// must be synchronized with tools/run_tests/python_utils/start_port_server.py
-#define GRPC_PORT_SERVER_ADDRESS "localhost:32766"
-
-int grpc_pick_port_using_server(void);
-void grpc_free_port_using_server(int port);
-
-#endif // GRPC_TEST_CORE_UTIL_PORT_SERVER_CLIENT_H
diff --git a/contrib/libs/grpc/test/core/util/stack_tracer.cc b/contrib/libs/grpc/test/core/util/stack_tracer.cc
deleted file mode 100644
index c91179a1658..00000000000
--- a/contrib/libs/grpc/test/core/util/stack_tracer.cc
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- *
- * Copyright 2020 the gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "test/core/util/stack_tracer.h"
-
-#include <cstdio>
-#include <util/generic/string.h>
-
-#include "y_absl/debugging/stacktrace.h"
-#include "y_absl/debugging/symbolize.h"
-
-#include "src/core/lib/gprpp/examine_stack.h"
-
-namespace {
-
-constexpr int kPrintfPointerFieldWidth = 2 + 2 * sizeof(void*);
-
-void DumpPCAndFrameSizeAndSymbol(void (*writerfn)(const char*, void*),
- void* writerfn_arg, void* pc,
- void* symbolize_pc, int framesize,
- const char* const prefix) {
- char tmp[1024];
- const char* symbol = "(unknown)";
- if (y_absl::Symbolize(symbolize_pc, tmp, sizeof(tmp))) {
- symbol = tmp;
- }
- char buf[1024];
- if (framesize <= 0) {
- snprintf(buf, sizeof(buf), "%s@ %*p (unknown) %s\n", prefix,
- kPrintfPointerFieldWidth, pc, symbol);
- } else {
- snprintf(buf, sizeof(buf), "%s@ %*p %9d %s\n", prefix,
- kPrintfPointerFieldWidth, pc, framesize, symbol);
- }
- writerfn(buf, writerfn_arg);
-}
-
-void DumpPCAndFrameSize(void (*writerfn)(const char*, void*),
- void* writerfn_arg, void* pc, int framesize,
- const char* const prefix) {
- char buf[100];
- if (framesize <= 0) {
- snprintf(buf, sizeof(buf), "%s@ %*p (unknown)\n", prefix,
- kPrintfPointerFieldWidth, pc);
- } else {
- snprintf(buf, sizeof(buf), "%s@ %*p %9d\n", prefix,
- kPrintfPointerFieldWidth, pc, framesize);
- }
- writerfn(buf, writerfn_arg);
-}
-
-void DumpStackTrace(void* const stack[], int frame_sizes[], int depth,
- bool symbolize_stacktrace,
- void (*writerfn)(const char*, void*), void* writerfn_arg) {
- for (int i = 0; i < depth; i++) {
- if (symbolize_stacktrace) {
- DumpPCAndFrameSizeAndSymbol(writerfn, writerfn_arg, stack[i],
- reinterpret_cast<char*>(stack[i]) - 1,
- frame_sizes[i], " ");
- } else {
- DumpPCAndFrameSize(writerfn, writerfn_arg, stack[i], frame_sizes[i],
- " ");
- }
- }
-}
-
-void DebugWriteToString(const char* data, void* str) {
- reinterpret_cast<TString*>(str)->append(data);
-}
-
-} // namespace
-
-namespace grpc_core {
-namespace testing {
-
-TString GetCurrentStackTrace() {
- TString result = "Stack trace:\n";
- constexpr int kNumStackFrames = 32;
- void* stack[kNumStackFrames];
- int frame_sizes[kNumStackFrames];
- int depth = y_absl::GetStackFrames(stack, frame_sizes, kNumStackFrames, 1);
- DumpStackTrace(stack, frame_sizes, depth, true, DebugWriteToString, &result);
- return result;
-}
-
-void InitializeStackTracer(const char* argv0) {
- y_absl::InitializeSymbolizer(argv0);
- SetCurrentStackTraceProvider(&GetCurrentStackTrace);
-}
-
-} // namespace testing
-} // namespace grpc_core
diff --git a/contrib/libs/grpc/test/core/util/stack_tracer.h b/contrib/libs/grpc/test/core/util/stack_tracer.h
deleted file mode 100644
index 16c2a433462..00000000000
--- a/contrib/libs/grpc/test/core/util/stack_tracer.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- *
- * Copyright 2020 the gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CORE_UTIL_EXAMINE_STACK_H
-#define GRPC_TEST_CORE_UTIL_EXAMINE_STACK_H
-
-#include <grpc/support/port_platform.h>
-
-#include <util/generic/string.h>
-
-namespace grpc_core {
-namespace testing {
-
-// Returns the current stack trace as a string. To have symbolized stack-traces,
-// InitializeStackTracer needs to be called beforehand.
-//
-// Example of stack-trace is
-// Stack trace:
-// @ 0x405b0f 192 StackTracerTest_Basic_Test::TestBody()
-// @ 0x7fbace6baf75 288 testing::internal::RunAllTests()
-// @ 0x7fbace6baa93 144 testing::UnitTest::Run()
-// @ 0x405d4d 64 main
-//
-TString GetCurrentStackTrace();
-
-// Initializes a stack tracer so that GetCurrentStackTrace can work.
-// This inits debug symbols and sets this as a gRPC stack-trace provider.
-void InitializeStackTracer(const char* argv0);
-
-} // namespace testing
-} // namespace grpc_core
-
-#endif /* GRPC_TEST_CORE_UTIL_EXAMINE_STACK_H */
diff --git a/contrib/libs/grpc/test/core/util/test_config.cc b/contrib/libs/grpc/test/core/util/test_config.cc
deleted file mode 100644
index 46c1455aaf1..00000000000
--- a/contrib/libs/grpc/test/core/util/test_config.cc
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include "test/core/util/test_config.h"
-
-#include <inttypes.h>
-#include <signal.h>
-#include <stdbool.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "y_absl/debugging/failure_signal_handler.h"
-#include "y_absl/debugging/symbolize.h"
-
-#include <grpc/grpc.h>
-#include <grpc/impl/codegen/gpr_types.h>
-#include <grpc/support/alloc.h>
-#include <grpc/support/log.h>
-
-#include "src/core/lib/gpr/string.h"
-#include "src/core/lib/gpr/useful.h"
-#include "src/core/lib/gprpp/examine_stack.h"
-#include "src/core/lib/surface/init.h"
-#include "test/core/util/build.h"
-#include "test/core/util/stack_tracer.h"
-
-int64_t g_fixture_slowdown_factor = 1;
-int64_t g_poller_slowdown_factor = 1;
-
-#if GPR_GETPID_IN_UNISTD_H
-#include <unistd.h>
-static unsigned seed(void) { return static_cast<unsigned>(getpid()); }
-#endif
-
-#if GPR_GETPID_IN_PROCESS_H
-#include <process.h>
-static unsigned seed(void) { return (unsigned)_getpid(); }
-#endif
-
-int64_t grpc_test_sanitizer_slowdown_factor() {
- int64_t sanitizer_multiplier = 1;
- if (BuiltUnderValgrind()) {
- sanitizer_multiplier = 20;
- } else if (BuiltUnderTsan()) {
- sanitizer_multiplier = 5;
- } else if (BuiltUnderAsan()) {
- sanitizer_multiplier = 3;
- } else if (BuiltUnderMsan()) {
- sanitizer_multiplier = 4;
- } else if (BuiltUnderUbsan()) {
- sanitizer_multiplier = 5;
- }
- return sanitizer_multiplier;
-}
-
-int64_t grpc_test_slowdown_factor() {
- return grpc_test_sanitizer_slowdown_factor() * g_fixture_slowdown_factor *
- g_poller_slowdown_factor;
-}
-
-gpr_timespec grpc_timeout_seconds_to_deadline(int64_t time_s) {
- return gpr_time_add(
- gpr_now(GPR_CLOCK_MONOTONIC),
- gpr_time_from_millis(
- grpc_test_slowdown_factor() * static_cast<int64_t>(1e3) * time_s,
- GPR_TIMESPAN));
-}
-
-gpr_timespec grpc_timeout_milliseconds_to_deadline(int64_t time_ms) {
- return gpr_time_add(
- gpr_now(GPR_CLOCK_MONOTONIC),
- gpr_time_from_micros(
- grpc_test_slowdown_factor() * static_cast<int64_t>(1e3) * time_ms,
- GPR_TIMESPAN));
-}
-
-void grpc_test_init(int /*argc*/, char** argv) {
- grpc_core::testing::InitializeStackTracer(argv[0]);
- y_absl::FailureSignalHandlerOptions options;
- y_absl::InstallFailureSignalHandler(options);
- gpr_log_verbosity_init();
- gpr_log(GPR_DEBUG,
- "test slowdown factor: sanitizer=%" PRId64 ", fixture=%" PRId64
- ", poller=%" PRId64 ", total=%" PRId64,
- grpc_test_sanitizer_slowdown_factor(), g_fixture_slowdown_factor,
- g_poller_slowdown_factor, grpc_test_slowdown_factor());
- /* seed rng with pid, so we don't end up with the same random numbers as a
- concurrently running test binary */
- srand(seed());
-}
-
-bool grpc_wait_until_shutdown(int64_t time_s) {
- gpr_timespec deadline = grpc_timeout_seconds_to_deadline(time_s);
- while (grpc_is_initialized()) {
- grpc_maybe_wait_for_async_shutdown();
- gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
- gpr_time_from_millis(1, GPR_TIMESPAN)));
- if (gpr_time_cmp(gpr_now(GPR_CLOCK_MONOTONIC), deadline) > 0) {
- return false;
- }
- }
- return true;
-}
-
-namespace grpc {
-namespace testing {
-
-TestEnvironment::TestEnvironment(int argc, char** argv) {
- grpc_test_init(argc, argv);
-}
-
-TestEnvironment::~TestEnvironment() {
- // This will wait until gRPC shutdown has actually happened to make sure
- // no gRPC resources (such as thread) are active. (timeout = 10s)
- if (!grpc_wait_until_shutdown(10)) {
- gpr_log(GPR_ERROR, "Timeout in waiting for gRPC shutdown");
- }
- if (BuiltUnderMsan()) {
- // This is a workaround for MSAN. MSAN doesn't like having shutdown thread
- // running. Although the code above waits until shutdown is done, chances
- // are that thread itself is still alive. To workaround this problem, this
- // is going to wait for 0.5 sec to give a chance to the shutdown thread to
- // exit. https://github.com/grpc/grpc/issues/23695
- gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
- gpr_time_from_millis(500, GPR_TIMESPAN)));
- }
- gpr_log(GPR_INFO, "TestEnvironment ends");
-}
-
-TestGrpcScope::TestGrpcScope() { grpc_init(); }
-
-TestGrpcScope::~TestGrpcScope() {
- grpc_shutdown();
- if (!grpc_wait_until_shutdown(10)) {
- gpr_log(GPR_ERROR, "Timeout in waiting for gRPC shutdown");
- }
-}
-
-} // namespace testing
-} // namespace grpc
diff --git a/contrib/libs/grpc/test/core/util/test_config.h b/contrib/libs/grpc/test/core/util/test_config.h
deleted file mode 100644
index 35da4d0f8e8..00000000000
--- a/contrib/libs/grpc/test/core/util/test_config.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CORE_UTIL_TEST_CONFIG_H
-#define GRPC_TEST_CORE_UTIL_TEST_CONFIG_H
-
-#include <grpc/support/time.h>
-
-#include "test/core/util/build.h"
-
-extern int64_t g_fixture_slowdown_factor;
-extern int64_t g_poller_slowdown_factor;
-
-/* Returns an appropriate scaling factor for timeouts. */
-int64_t grpc_test_slowdown_factor();
-
-/* Converts a given timeout (in seconds) to a deadline. */
-gpr_timespec grpc_timeout_seconds_to_deadline(int64_t time_s);
-
-/* Converts a given timeout (in milliseconds) to a deadline. */
-gpr_timespec grpc_timeout_milliseconds_to_deadline(int64_t time_ms);
-
-#if !defined(GRPC_TEST_CUSTOM_PICK_PORT) && !defined(GRPC_PORT_ISOLATED_RUNTIME)
-#define GRPC_TEST_PICK_PORT
-#endif
-
-// Prefer TestEnvironment below.
-void grpc_test_init(int argc, char** argv);
-
-// Wait until gRPC is fully shut down.
-// Returns if grpc is shutdown
-bool grpc_wait_until_shutdown(int64_t time_s);
-
-namespace grpc {
-namespace testing {
-
-// A TestEnvironment object should be alive in the main function of a test. It
-// provides test init and shutdown inside.
-class TestEnvironment {
- public:
- TestEnvironment(int argc, char** argv);
- ~TestEnvironment();
-};
-
-// A TestGrpcScope makes sure that
-// - when it's created, gRPC will be initialized
-// - when it's destroyed, gRPC will shutdown and it waits until shutdown
-class TestGrpcScope {
- public:
- TestGrpcScope();
- ~TestGrpcScope();
-};
-
-} // namespace testing
-} // namespace grpc
-
-#endif /* GRPC_TEST_CORE_UTIL_TEST_CONFIG_H */
diff --git a/contrib/libs/grpc/test/core/util/test_lb_policies.cc b/contrib/libs/grpc/test/core/util/test_lb_policies.cc
deleted file mode 100644
index 059869cfd2d..00000000000
--- a/contrib/libs/grpc/test/core/util/test_lb_policies.cc
+++ /dev/null
@@ -1,549 +0,0 @@
-//
-// Copyright 2018 gRPC authors.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include "test/core/util/test_lb_policies.h"
-
-#include <util/generic/string.h>
-
-#include <grpc/support/log.h>
-
-#include "src/core/ext/filters/client_channel/lb_policy.h"
-#include "src/core/ext/filters/client_channel/lb_policy_registry.h"
-#include "src/core/lib/address_utils/parse_address.h"
-#include "src/core/lib/channel/channel_args.h"
-#include "src/core/lib/channel/channelz.h"
-#include "src/core/lib/debug/trace.h"
-#include "src/core/lib/gprpp/memory.h"
-#include "src/core/lib/gprpp/orphanable.h"
-#include "src/core/lib/gprpp/ref_counted_ptr.h"
-#include "src/core/lib/iomgr/closure.h"
-#include "src/core/lib/iomgr/combiner.h"
-#include "src/core/lib/iomgr/error.h"
-#include "src/core/lib/iomgr/pollset_set.h"
-#include "src/core/lib/json/json.h"
-#include "src/core/lib/json/json_util.h"
-#include "src/core/lib/transport/connectivity_state.h"
-
-namespace grpc_core {
-
-namespace {
-
-//
-// ForwardingLoadBalancingPolicy
-//
-
-// A minimal forwarding class to avoid implementing a standalone test LB.
-class ForwardingLoadBalancingPolicy : public LoadBalancingPolicy {
- public:
- ForwardingLoadBalancingPolicy(
- std::unique_ptr<ChannelControlHelper> delegating_helper, Args args,
- const char* delegate_policy_name, intptr_t initial_refcount = 1)
- : LoadBalancingPolicy(std::move(args), initial_refcount) {
- Args delegate_args;
- delegate_args.work_serializer = work_serializer();
- delegate_args.channel_control_helper = std::move(delegating_helper);
- delegate_args.args = args.args;
- delegate_ = LoadBalancingPolicyRegistry::CreateLoadBalancingPolicy(
- delegate_policy_name, std::move(delegate_args));
- grpc_pollset_set_add_pollset_set(delegate_->interested_parties(),
- interested_parties());
- }
-
- ~ForwardingLoadBalancingPolicy() override = default;
-
- void UpdateLocked(UpdateArgs args) override {
- delegate_->UpdateLocked(std::move(args));
- }
-
- void ExitIdleLocked() override { delegate_->ExitIdleLocked(); }
-
- void ResetBackoffLocked() override { delegate_->ResetBackoffLocked(); }
-
- private:
- void ShutdownLocked() override { delegate_.reset(); }
-
- OrphanablePtr<LoadBalancingPolicy> delegate_;
-};
-
-//
-// TestPickArgsLb
-//
-
-constexpr char kTestPickArgsLbPolicyName[] = "test_pick_args_lb";
-
-class TestPickArgsLb : public ForwardingLoadBalancingPolicy {
- public:
- TestPickArgsLb(Args args, TestPickArgsCallback cb,
- const char* delegate_policy_name)
- : ForwardingLoadBalancingPolicy(
- y_absl::make_unique<Helper>(RefCountedPtr<TestPickArgsLb>(this), cb),
- std::move(args), delegate_policy_name,
- /*initial_refcount=*/2) {}
-
- ~TestPickArgsLb() override = default;
-
- const char* name() const override { return kTestPickArgsLbPolicyName; }
-
- private:
- class Picker : public SubchannelPicker {
- public:
- Picker(std::unique_ptr<SubchannelPicker> delegate_picker,
- TestPickArgsCallback cb)
- : delegate_picker_(std::move(delegate_picker)), cb_(std::move(cb)) {}
-
- PickResult Pick(PickArgs args) override {
- // Report args seen.
- PickArgsSeen args_seen;
- args_seen.path = TString(args.path);
- args_seen.metadata = args.initial_metadata->TestOnlyCopyToVector();
- cb_(args_seen);
- // Do pick.
- return delegate_picker_->Pick(args);
- }
-
- private:
- std::unique_ptr<SubchannelPicker> delegate_picker_;
- TestPickArgsCallback cb_;
- };
-
- class Helper : public ChannelControlHelper {
- public:
- Helper(RefCountedPtr<TestPickArgsLb> parent, TestPickArgsCallback cb)
- : parent_(std::move(parent)), cb_(std::move(cb)) {}
-
- RefCountedPtr<SubchannelInterface> CreateSubchannel(
- ServerAddress address, const grpc_channel_args& args) override {
- return parent_->channel_control_helper()->CreateSubchannel(
- std::move(address), args);
- }
-
- void UpdateState(grpc_connectivity_state state, const y_absl::Status& status,
- std::unique_ptr<SubchannelPicker> picker) override {
- parent_->channel_control_helper()->UpdateState(
- state, status, y_absl::make_unique<Picker>(std::move(picker), cb_));
- }
-
- void RequestReresolution() override {
- parent_->channel_control_helper()->RequestReresolution();
- }
-
- y_absl::string_view GetAuthority() override {
- return parent_->channel_control_helper()->GetAuthority();
- }
-
- void AddTraceEvent(TraceSeverity severity,
- y_absl::string_view message) override {
- parent_->channel_control_helper()->AddTraceEvent(severity, message);
- }
-
- private:
- RefCountedPtr<TestPickArgsLb> parent_;
- TestPickArgsCallback cb_;
- };
-};
-
-class TestPickArgsLbConfig : public LoadBalancingPolicy::Config {
- public:
- const char* name() const override { return kTestPickArgsLbPolicyName; }
-};
-
-class TestPickArgsLbFactory : public LoadBalancingPolicyFactory {
- public:
- explicit TestPickArgsLbFactory(TestPickArgsCallback cb,
- const char* delegate_policy_name)
- : cb_(std::move(cb)), delegate_policy_name_(delegate_policy_name) {}
-
- OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
- LoadBalancingPolicy::Args args) const override {
- return MakeOrphanable<TestPickArgsLb>(std::move(args), cb_,
- delegate_policy_name_);
- }
-
- const char* name() const override { return kTestPickArgsLbPolicyName; }
-
- RefCountedPtr<LoadBalancingPolicy::Config> ParseLoadBalancingConfig(
- const Json& /*json*/, grpc_error_handle* /*error*/) const override {
- return MakeRefCounted<TestPickArgsLbConfig>();
- }
-
- private:
- TestPickArgsCallback cb_;
- const char* delegate_policy_name_;
-};
-
-//
-// InterceptRecvTrailingMetadataLoadBalancingPolicy
-//
-
-constexpr char kInterceptRecvTrailingMetadataLbPolicyName[] =
- "intercept_trailing_metadata_lb";
-
-class InterceptRecvTrailingMetadataLoadBalancingPolicy
- : public ForwardingLoadBalancingPolicy {
- public:
- InterceptRecvTrailingMetadataLoadBalancingPolicy(
- Args args, InterceptRecvTrailingMetadataCallback cb)
- : ForwardingLoadBalancingPolicy(
- y_absl::make_unique<Helper>(
- RefCountedPtr<InterceptRecvTrailingMetadataLoadBalancingPolicy>(
- this),
- std::move(cb)),
- std::move(args),
- /*delegate_policy_name=*/"pick_first",
- /*initial_refcount=*/2) {}
-
- ~InterceptRecvTrailingMetadataLoadBalancingPolicy() override = default;
-
- const char* name() const override {
- return kInterceptRecvTrailingMetadataLbPolicyName;
- }
-
- private:
- class Picker : public SubchannelPicker {
- public:
- Picker(std::unique_ptr<SubchannelPicker> delegate_picker,
- InterceptRecvTrailingMetadataCallback cb)
- : delegate_picker_(std::move(delegate_picker)), cb_(std::move(cb)) {}
-
- PickResult Pick(PickArgs args) override {
- // Do pick.
- PickResult result = delegate_picker_->Pick(args);
- // Intercept trailing metadata.
- auto* complete_pick = y_absl::get_if<PickResult::Complete>(&result.result);
- if (complete_pick != nullptr) {
- complete_pick->subchannel_call_tracker =
- y_absl::make_unique<SubchannelCallTracker>(cb_);
- }
- return result;
- }
-
- private:
- std::unique_ptr<SubchannelPicker> delegate_picker_;
- InterceptRecvTrailingMetadataCallback cb_;
- };
-
- class Helper : public ChannelControlHelper {
- public:
- Helper(
- RefCountedPtr<InterceptRecvTrailingMetadataLoadBalancingPolicy> parent,
- InterceptRecvTrailingMetadataCallback cb)
- : parent_(std::move(parent)), cb_(std::move(cb)) {}
-
- RefCountedPtr<SubchannelInterface> CreateSubchannel(
- ServerAddress address, const grpc_channel_args& args) override {
- return parent_->channel_control_helper()->CreateSubchannel(
- std::move(address), args);
- }
-
- void UpdateState(grpc_connectivity_state state, const y_absl::Status& status,
- std::unique_ptr<SubchannelPicker> picker) override {
- parent_->channel_control_helper()->UpdateState(
- state, status, y_absl::make_unique<Picker>(std::move(picker), cb_));
- }
-
- void RequestReresolution() override {
- parent_->channel_control_helper()->RequestReresolution();
- }
-
- y_absl::string_view GetAuthority() override {
- return parent_->channel_control_helper()->GetAuthority();
- }
-
- void AddTraceEvent(TraceSeverity severity,
- y_absl::string_view message) override {
- parent_->channel_control_helper()->AddTraceEvent(severity, message);
- }
-
- private:
- RefCountedPtr<InterceptRecvTrailingMetadataLoadBalancingPolicy> parent_;
- InterceptRecvTrailingMetadataCallback cb_;
- };
-
- class SubchannelCallTracker : public SubchannelCallTrackerInterface {
- public:
- explicit SubchannelCallTracker(InterceptRecvTrailingMetadataCallback cb)
- : cb_(std::move(cb)) {}
-
- void Start() override {}
-
- void Finish(FinishArgs args) override {
- TrailingMetadataArgsSeen args_seen;
- args_seen.backend_metric_data =
- args.backend_metric_accessor->GetBackendMetricData();
- args_seen.metadata = args.trailing_metadata->TestOnlyCopyToVector();
- cb_(args_seen);
- }
-
- private:
- InterceptRecvTrailingMetadataCallback cb_;
- };
-};
-
-class InterceptTrailingConfig : public LoadBalancingPolicy::Config {
- public:
- const char* name() const override {
- return kInterceptRecvTrailingMetadataLbPolicyName;
- }
-};
-
-class InterceptTrailingFactory : public LoadBalancingPolicyFactory {
- public:
- explicit InterceptTrailingFactory(InterceptRecvTrailingMetadataCallback cb)
- : cb_(std::move(cb)) {}
-
- OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
- LoadBalancingPolicy::Args args) const override {
- return MakeOrphanable<InterceptRecvTrailingMetadataLoadBalancingPolicy>(
- std::move(args), cb_);
- }
-
- const char* name() const override {
- return kInterceptRecvTrailingMetadataLbPolicyName;
- }
-
- RefCountedPtr<LoadBalancingPolicy::Config> ParseLoadBalancingConfig(
- const Json& /*json*/, grpc_error_handle* /*error*/) const override {
- return MakeRefCounted<InterceptTrailingConfig>();
- }
-
- private:
- InterceptRecvTrailingMetadataCallback cb_;
-};
-
-//
-// AddressTestLoadBalancingPolicy
-//
-
-constexpr char kAddressTestLbPolicyName[] = "address_test_lb";
-
-class AddressTestLoadBalancingPolicy : public ForwardingLoadBalancingPolicy {
- public:
- AddressTestLoadBalancingPolicy(Args args, AddressTestCallback cb)
- : ForwardingLoadBalancingPolicy(
- y_absl::make_unique<Helper>(
- RefCountedPtr<AddressTestLoadBalancingPolicy>(this),
- std::move(cb)),
- std::move(args),
- /*delegate_policy_name=*/"pick_first",
- /*initial_refcount=*/2) {}
-
- ~AddressTestLoadBalancingPolicy() override = default;
-
- const char* name() const override { return kAddressTestLbPolicyName; }
-
- private:
- class Helper : public ChannelControlHelper {
- public:
- Helper(RefCountedPtr<AddressTestLoadBalancingPolicy> parent,
- AddressTestCallback cb)
- : parent_(std::move(parent)), cb_(std::move(cb)) {}
-
- RefCountedPtr<SubchannelInterface> CreateSubchannel(
- ServerAddress address, const grpc_channel_args& args) override {
- cb_(address);
- return parent_->channel_control_helper()->CreateSubchannel(
- std::move(address), args);
- }
-
- void UpdateState(grpc_connectivity_state state, const y_absl::Status& status,
- std::unique_ptr<SubchannelPicker> picker) override {
- parent_->channel_control_helper()->UpdateState(state, status,
- std::move(picker));
- }
-
- void RequestReresolution() override {
- parent_->channel_control_helper()->RequestReresolution();
- }
-
- y_absl::string_view GetAuthority() override {
- return parent_->channel_control_helper()->GetAuthority();
- }
-
- void AddTraceEvent(TraceSeverity severity,
- y_absl::string_view message) override {
- parent_->channel_control_helper()->AddTraceEvent(severity, message);
- }
-
- private:
- RefCountedPtr<AddressTestLoadBalancingPolicy> parent_;
- AddressTestCallback cb_;
- };
-};
-
-class AddressTestConfig : public LoadBalancingPolicy::Config {
- public:
- const char* name() const override { return kAddressTestLbPolicyName; }
-};
-
-class AddressTestFactory : public LoadBalancingPolicyFactory {
- public:
- explicit AddressTestFactory(AddressTestCallback cb) : cb_(std::move(cb)) {}
-
- OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
- LoadBalancingPolicy::Args args) const override {
- return MakeOrphanable<AddressTestLoadBalancingPolicy>(std::move(args), cb_);
- }
-
- const char* name() const override { return kAddressTestLbPolicyName; }
-
- RefCountedPtr<LoadBalancingPolicy::Config> ParseLoadBalancingConfig(
- const Json& /*json*/, grpc_error_handle* /*error*/) const override {
- return MakeRefCounted<AddressTestConfig>();
- }
-
- private:
- AddressTestCallback cb_;
-};
-
-//
-// FixedAddressLoadBalancingPolicy
-//
-
-constexpr char kFixedAddressLbPolicyName[] = "fixed_address_lb";
-
-class FixedAddressConfig : public LoadBalancingPolicy::Config {
- public:
- explicit FixedAddressConfig(TString address)
- : address_(std::move(address)) {}
-
- const char* name() const override { return kFixedAddressLbPolicyName; }
-
- const TString& address() const { return address_; }
-
- private:
- TString address_;
-};
-
-class FixedAddressLoadBalancingPolicy : public ForwardingLoadBalancingPolicy {
- public:
- explicit FixedAddressLoadBalancingPolicy(Args args)
- : ForwardingLoadBalancingPolicy(
- y_absl::make_unique<Helper>(
- RefCountedPtr<FixedAddressLoadBalancingPolicy>(this)),
- std::move(args),
- /*delegate_policy_name=*/"pick_first",
- /*initial_refcount=*/2) {}
-
- ~FixedAddressLoadBalancingPolicy() override = default;
-
- const char* name() const override { return kFixedAddressLbPolicyName; }
-
- void UpdateLocked(UpdateArgs args) override {
- auto* config = static_cast<FixedAddressConfig*>(args.config.get());
- gpr_log(GPR_INFO, "%s: update URI: %s", kFixedAddressLbPolicyName,
- config->address().c_str());
- auto uri = URI::Parse(config->address());
- args.config.reset();
- args.addresses = ServerAddressList();
- if (uri.ok()) {
- grpc_resolved_address address;
- GPR_ASSERT(grpc_parse_uri(*uri, &address));
- args.addresses->emplace_back(address, /*args=*/nullptr);
- } else {
- gpr_log(GPR_ERROR,
- "%s: could not parse URI (%s), using empty address list",
- kFixedAddressLbPolicyName, uri.status().ToString().c_str());
- }
- ForwardingLoadBalancingPolicy::UpdateLocked(std::move(args));
- }
-
- private:
- class Helper : public ChannelControlHelper {
- public:
- explicit Helper(RefCountedPtr<FixedAddressLoadBalancingPolicy> parent)
- : parent_(std::move(parent)) {}
-
- RefCountedPtr<SubchannelInterface> CreateSubchannel(
- ServerAddress address, const grpc_channel_args& args) override {
- return parent_->channel_control_helper()->CreateSubchannel(
- std::move(address), args);
- }
-
- void UpdateState(grpc_connectivity_state state, const y_absl::Status& status,
- std::unique_ptr<SubchannelPicker> picker) override {
- parent_->channel_control_helper()->UpdateState(state, status,
- std::move(picker));
- }
-
- void RequestReresolution() override {
- parent_->channel_control_helper()->RequestReresolution();
- }
-
- y_absl::string_view GetAuthority() override {
- return parent_->channel_control_helper()->GetAuthority();
- }
-
- void AddTraceEvent(TraceSeverity severity,
- y_absl::string_view message) override {
- parent_->channel_control_helper()->AddTraceEvent(severity, message);
- }
-
- private:
- RefCountedPtr<FixedAddressLoadBalancingPolicy> parent_;
- };
-};
-
-class FixedAddressFactory : public LoadBalancingPolicyFactory {
- public:
- FixedAddressFactory() = default;
-
- OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
- LoadBalancingPolicy::Args args) const override {
- return MakeOrphanable<FixedAddressLoadBalancingPolicy>(std::move(args));
- }
-
- const char* name() const override { return kFixedAddressLbPolicyName; }
-
- RefCountedPtr<LoadBalancingPolicy::Config> ParseLoadBalancingConfig(
- const Json& json, grpc_error_handle* error) const override {
- std::vector<grpc_error_handle> error_list;
- TString address;
- ParseJsonObjectField(json.object_value(), "address", &address, &error_list);
- if (!error_list.empty()) {
- *error = GRPC_ERROR_CREATE_FROM_VECTOR(
- "errors parsing fixed_address_lb config", &error_list);
- return nullptr;
- }
- return MakeRefCounted<FixedAddressConfig>(std::move(address));
- }
-};
-
-} // namespace
-
-void RegisterTestPickArgsLoadBalancingPolicy(TestPickArgsCallback cb,
- const char* delegate_policy_name) {
- LoadBalancingPolicyRegistry::Builder::RegisterLoadBalancingPolicyFactory(
- y_absl::make_unique<TestPickArgsLbFactory>(std::move(cb),
- delegate_policy_name));
-}
-
-void RegisterInterceptRecvTrailingMetadataLoadBalancingPolicy(
- InterceptRecvTrailingMetadataCallback cb) {
- LoadBalancingPolicyRegistry::Builder::RegisterLoadBalancingPolicyFactory(
- y_absl::make_unique<InterceptTrailingFactory>(std::move(cb)));
-}
-
-void RegisterAddressTestLoadBalancingPolicy(AddressTestCallback cb) {
- LoadBalancingPolicyRegistry::Builder::RegisterLoadBalancingPolicyFactory(
- y_absl::make_unique<AddressTestFactory>(std::move(cb)));
-}
-
-void RegisterFixedAddressLoadBalancingPolicy() {
- LoadBalancingPolicyRegistry::Builder::RegisterLoadBalancingPolicyFactory(
- y_absl::make_unique<FixedAddressFactory>());
-}
-
-} // namespace grpc_core
diff --git a/contrib/libs/grpc/test/core/util/test_lb_policies.h b/contrib/libs/grpc/test/core/util/test_lb_policies.h
deleted file mode 100644
index fc6b054ad35..00000000000
--- a/contrib/libs/grpc/test/core/util/test_lb_policies.h
+++ /dev/null
@@ -1,64 +0,0 @@
-//
-// Copyright 2018 gRPC authors.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef GRPC_TEST_CORE_UTIL_TEST_LB_POLICIES_H
-#define GRPC_TEST_CORE_UTIL_TEST_LB_POLICIES_H
-
-#include "src/core/ext/filters/client_channel/lb_policy.h"
-
-namespace grpc_core {
-
-using MetadataVector = std::vector<std::pair<TString, TString>>;
-
-struct PickArgsSeen {
- TString path;
- MetadataVector metadata;
-};
-
-using TestPickArgsCallback = std::function<void(const PickArgsSeen&)>;
-
-// Registers an LB policy called "test_pick_args_lb" that passes the args
-// passed to SubchannelPicker::Pick() to cb.
-void RegisterTestPickArgsLoadBalancingPolicy(
- TestPickArgsCallback cb, const char* delegate_policy_name = "pick_first");
-
-struct TrailingMetadataArgsSeen {
- const LoadBalancingPolicy::BackendMetricAccessor::BackendMetricData*
- backend_metric_data;
- MetadataVector metadata;
-};
-
-using InterceptRecvTrailingMetadataCallback =
- std::function<void(const TrailingMetadataArgsSeen&)>;
-
-// Registers an LB policy called "intercept_trailing_metadata_lb" that
-// invokes cb when trailing metadata is received for each call.
-void RegisterInterceptRecvTrailingMetadataLoadBalancingPolicy(
- InterceptRecvTrailingMetadataCallback cb);
-
-using AddressTestCallback = std::function<void(const ServerAddress&)>;
-
-// Registers an LB policy called "address_test_lb" that invokes cb for each
-// address used to create a subchannel.
-void RegisterAddressTestLoadBalancingPolicy(AddressTestCallback cb);
-
-// Registers an LB policy called "fixed_address_lb" that provides a
-// single subchannel whose address is in its configuration.
-void RegisterFixedAddressLoadBalancingPolicy();
-
-} // namespace grpc_core
-
-#endif // GRPC_TEST_CORE_UTIL_TEST_LB_POLICIES_H
diff --git a/contrib/libs/grpc/test/core/util/ya.make b/contrib/libs/grpc/test/core/util/ya.make
deleted file mode 100644
index 44b611ef677..00000000000
--- a/contrib/libs/grpc/test/core/util/ya.make
+++ /dev/null
@@ -1,53 +0,0 @@
-LIBRARY()
-
-LICENSE(Apache-2.0)
-
-LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-
-PEERDIR(
- contrib/libs/grpc
- contrib/restricted/abseil-cpp-tstring/y_absl/debugging
-)
-
-ADDINCL(
- ${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
- contrib/libs/grpc
-)
-
-NO_COMPILER_WARNINGS()
-
-SRCS(
- build.cc
- # cmdline.cc
- # cmdline_test.cc
- # debugger_macros.cc
- # fuzzer_corpus_test.cc
- # fuzzer_one_entry_runner.sh*
- # fuzzer_util.cc
- # grpc_fuzzer.bzl
- # grpc_profiler.cc
- # histogram.cc
- # histogram_test.cc
- # lsan_suppressions.txt
- # memory_counters.cc
- # mock_endpoint.cc
- # one_corpus_entry_fuzzer.cc
- # parse_hexstring.cc
- # passthru_endpoint.cc
- port.cc
- # port_isolated_runtime_environment.cc
- port_server_client.cc
- # reconnect_server.cc
- # run_with_poller.sh*
- # slice_splitter.cc
- # subprocess_posix.cc
- # subprocess_windows.cc
- stack_tracer.cc
- test_config.cc
- test_lb_policies.cc
- # test_tcp_server.cc
- # tracer_util.cc
- # trickle_endpoint.cc
-)
-
-END()
diff --git a/contrib/libs/grpc/test/cpp/README-iOS.md b/contrib/libs/grpc/test/cpp/README-iOS.md
deleted file mode 100644
index 898931085b3..00000000000
--- a/contrib/libs/grpc/test/cpp/README-iOS.md
+++ /dev/null
@@ -1,52 +0,0 @@
-## C++ tests on iOS
-
-[GTMGoogleTestRunner](https://github.com/google/google-toolbox-for-mac/blob/master/UnitTesting/GTMGoogleTestRunner.mm) is used to convert googletest cases to XCTest that can be run on iOS. GTMGoogleTestRunner doesn't execute the `main` function, so we can't have any test logic in `main`.
-However, it's ok to call `::testing::InitGoogleTest` in `main`, as `GTMGoogleTestRunner` [calls InitGoogleTest](https://github.com/google/google-toolbox-for-mac/blob/master/UnitTesting/GTMGoogleTestRunner.mm#L151).
-`grpc::testing::TestEnvironment` can also be called from `main`, as it does some test initialization (install crash handler, seed RNG) that's not strictly required to run testcases on iOS.
-
-
-## Porting exising C++ tests to run on iOS
-
-Please follow these guidelines when porting tests to run on iOS:
-
-- Tests need to use the googletest framework
-- Any setup/teardown code in `main` needs to be moved to `SetUpTestCase`/`TearDownTestCase`, and `TEST` needs to be changed to `TEST_F`.
-- [Death tests](https://github.com/google/googletest/blob/master/googletest/docs/advanced.md#death-tests) are not supported on iOS, so use the `*_IF_SUPPORTED()` macros to ensure that your code compiles on iOS.
-
-For example, the following test
-```c++
-TEST(MyTest, TestOne) {
- ASSERT_DEATH(ThisShouldDie(), "");
-}
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- grpc_init();
- return RUN_ALL_TESTS();
- grpc_shutdown();
-}
-```
-
-should be changed to
-```c++
-class MyTest : public ::testing::Test {
- protected:
- static void SetUpTestCase() { grpc_init(); }
- static void TearDownTestCase() { grpc_shutdown(); }
-};
-
-TEST_F(MyTest, TestOne) {
- ASSERT_DEATH_IF_SUPPORTED(ThisShouldDie(), "");
-}
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
-```
-
-## Limitations
-
-Due to a [limitation](https://github.com/google/google-toolbox-for-mac/blob/master/UnitTesting/GTMGoogleTestRunner.mm#L48-L56) in GTMGoogleTestRunner, `SetUpTestCase`/`TeardownTestCase` will be called before/after *every* individual test case, similar to `SetUp`/`TearDown`.
diff --git a/contrib/libs/grpc/test/cpp/end2end/health/ya.make b/contrib/libs/grpc/test/cpp/end2end/health/ya.make
deleted file mode 100644
index 85b03e58d0e..00000000000
--- a/contrib/libs/grpc/test/cpp/end2end/health/ya.make
+++ /dev/null
@@ -1,28 +0,0 @@
-GTEST_UGLY()
-
-ADDINCL(
- ${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
- ${ARCADIA_ROOT}/contrib/libs/grpc
-)
-
-PEERDIR(
- contrib/libs/grpc/src/proto/grpc/health/v1
- contrib/libs/grpc/src/proto/grpc/core
- contrib/libs/grpc/src/proto/grpc/testing
- contrib/libs/grpc/src/proto/grpc/testing/duplicate
- contrib/libs/grpc/test/core/util
- contrib/libs/grpc/test/cpp/end2end
- contrib/libs/grpc/test/cpp/util
-)
-
-NO_COMPILER_WARNINGS()
-
-SRCDIR(
- contrib/libs/grpc/test/cpp/end2end
-)
-
-SRCS(
- health_service_end2end_test.cc
-)
-
-END()
diff --git a/contrib/libs/grpc/test/cpp/end2end/health_service_end2end_test.cc b/contrib/libs/grpc/test/cpp/end2end/health_service_end2end_test.cc
deleted file mode 100644
index 7fad60ddedd..00000000000
--- a/contrib/libs/grpc/test/cpp/end2end/health_service_end2end_test.cc
+++ /dev/null
@@ -1,374 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <memory>
-#include <mutex>
-#include <thread>
-#include <vector>
-
-#include <gtest/gtest.h>
-
-#include <grpc/grpc.h>
-#include <grpc/support/log.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/ext/health_check_service_server_builder_option.h>
-#include <grpcpp/health_check_service_interface.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/server_context.h>
-
-#include "src/proto/grpc/health/v1/health.grpc.pb.h"
-#include "src/proto/grpc/testing/duplicate/echo_duplicate.grpc.pb.h"
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-#include "test/cpp/end2end/test_health_check_service_impl.h"
-#include "test/cpp/end2end/test_service_impl.h"
-
-using grpc::health::v1::Health;
-using grpc::health::v1::HealthCheckRequest;
-using grpc::health::v1::HealthCheckResponse;
-
-namespace grpc {
-namespace testing {
-namespace {
-
-// A custom implementation of the health checking service interface. This is
-// used to test that it prevents the server from creating a default service and
-// also serves as an example of how to override the default service.
-class CustomHealthCheckService : public HealthCheckServiceInterface {
- public:
- explicit CustomHealthCheckService(HealthCheckServiceImpl* impl)
- : impl_(impl) {
- impl_->SetStatus("", HealthCheckResponse::SERVING);
- }
- void SetServingStatus(const TString& service_name,
- bool serving) override {
- impl_->SetStatus(service_name, serving ? HealthCheckResponse::SERVING
- : HealthCheckResponse::NOT_SERVING);
- }
-
- void SetServingStatus(bool serving) override {
- impl_->SetAll(serving ? HealthCheckResponse::SERVING
- : HealthCheckResponse::NOT_SERVING);
- }
-
- void Shutdown() override { impl_->Shutdown(); }
-
- private:
- HealthCheckServiceImpl* impl_; // not owned
-};
-
-class HealthServiceEnd2endTest : public ::testing::Test {
- protected:
- HealthServiceEnd2endTest() {}
-
- void SetUpServer(bool register_sync_test_service, bool add_async_cq,
- bool explicit_health_service,
- std::unique_ptr<HealthCheckServiceInterface> service) {
- int port = 5001; // grpc_pick_unused_port_or_die();
- server_address_ << "localhost:" << port;
-
- bool register_sync_health_service_impl =
- explicit_health_service && service != nullptr;
-
- // Setup server
- ServerBuilder builder;
- if (explicit_health_service) {
- std::unique_ptr<ServerBuilderOption> option(
- new HealthCheckServiceServerBuilderOption(std::move(service)));
- builder.SetOption(std::move(option));
- }
- builder.AddListeningPort(server_address_.str(),
- grpc::InsecureServerCredentials());
- if (register_sync_test_service) {
- // Register a sync service.
- builder.RegisterService(&echo_test_service_);
- }
- if (register_sync_health_service_impl) {
- builder.RegisterService(&health_check_service_impl_);
- }
- if (add_async_cq) {
- cq_ = builder.AddCompletionQueue();
- }
- server_ = builder.BuildAndStart();
- }
-
- void TearDown() override {
- if (server_) {
- server_->Shutdown();
- if (cq_ != nullptr) {
- cq_->Shutdown();
- }
- if (cq_thread_.joinable()) {
- cq_thread_.join();
- }
- }
- }
-
- void ResetStubs() {
- std::shared_ptr<Channel> channel = grpc::CreateChannel(
- server_address_.str(), InsecureChannelCredentials());
- hc_stub_ = grpc::health::v1::Health::NewStub(channel);
- }
-
- // When the expected_status is NOT OK, we do not care about the response.
- void SendHealthCheckRpc(const TString& service_name,
- const Status& expected_status) {
- EXPECT_FALSE(expected_status.ok());
- SendHealthCheckRpc(service_name, expected_status,
- HealthCheckResponse::UNKNOWN);
- }
-
- void SendHealthCheckRpc(
- const TString& service_name, const Status& expected_status,
- HealthCheckResponse::ServingStatus expected_serving_status) {
- HealthCheckRequest request;
- request.set_service(service_name);
- HealthCheckResponse response;
- ClientContext context;
- Status s = hc_stub_->Check(&context, request, &response);
- EXPECT_EQ(expected_status.error_code(), s.error_code());
- if (s.ok()) {
- EXPECT_EQ(expected_serving_status, response.status());
- }
- }
-
- void VerifyHealthCheckService() {
- HealthCheckServiceInterface* service = server_->GetHealthCheckService();
- EXPECT_TRUE(service != nullptr);
- const TString kHealthyService("healthy_service");
- const TString kUnhealthyService("unhealthy_service");
- const TString kNotRegisteredService("not_registered");
- service->SetServingStatus(kHealthyService, true);
- service->SetServingStatus(kUnhealthyService, false);
-
- ResetStubs();
-
- SendHealthCheckRpc("", Status::OK, HealthCheckResponse::SERVING);
- SendHealthCheckRpc(kHealthyService, Status::OK,
- HealthCheckResponse::SERVING);
- SendHealthCheckRpc(kUnhealthyService, Status::OK,
- HealthCheckResponse::NOT_SERVING);
- SendHealthCheckRpc(kNotRegisteredService,
- Status(StatusCode::NOT_FOUND, ""));
-
- service->SetServingStatus(false);
- SendHealthCheckRpc("", Status::OK, HealthCheckResponse::NOT_SERVING);
- SendHealthCheckRpc(kHealthyService, Status::OK,
- HealthCheckResponse::NOT_SERVING);
- SendHealthCheckRpc(kUnhealthyService, Status::OK,
- HealthCheckResponse::NOT_SERVING);
- SendHealthCheckRpc(kNotRegisteredService,
- Status(StatusCode::NOT_FOUND, ""));
- }
-
- void VerifyHealthCheckServiceStreaming() {
- const TString kServiceName("service_name");
- HealthCheckServiceInterface* service = server_->GetHealthCheckService();
- // Start Watch for service.
- ClientContext context;
- HealthCheckRequest request;
- request.set_service(kServiceName);
- std::unique_ptr<::grpc::ClientReaderInterface<HealthCheckResponse>> reader =
- hc_stub_->Watch(&context, request);
- // Initial response will be SERVICE_UNKNOWN.
- HealthCheckResponse response;
- EXPECT_TRUE(reader->Read(&response));
- EXPECT_EQ(response.SERVICE_UNKNOWN, response.status());
- response.Clear();
- // Now set service to NOT_SERVING and make sure we get an update.
- service->SetServingStatus(kServiceName, false);
- EXPECT_TRUE(reader->Read(&response));
- EXPECT_EQ(response.NOT_SERVING, response.status());
- response.Clear();
- // Now set service to SERVING and make sure we get another update.
- service->SetServingStatus(kServiceName, true);
- EXPECT_TRUE(reader->Read(&response));
- EXPECT_EQ(response.SERVING, response.status());
- // Finish call.
- context.TryCancel();
- }
-
- // Verify that after HealthCheckServiceInterface::Shutdown is called
- // 1. unary client will see NOT_SERVING.
- // 2. unary client still sees NOT_SERVING after a SetServing(true) is called.
- // 3. streaming (Watch) client will see an update.
- // 4. setting a new service to serving after shutdown will add the service
- // name but return NOT_SERVING to client.
- // This has to be called last.
- void VerifyHealthCheckServiceShutdown() {
- HealthCheckServiceInterface* service = server_->GetHealthCheckService();
- EXPECT_TRUE(service != nullptr);
- const TString kHealthyService("healthy_service");
- const TString kUnhealthyService("unhealthy_service");
- const TString kNotRegisteredService("not_registered");
- const TString kNewService("add_after_shutdown");
- service->SetServingStatus(kHealthyService, true);
- service->SetServingStatus(kUnhealthyService, false);
-
- ResetStubs();
-
- // Start Watch for service.
- ClientContext context;
- HealthCheckRequest request;
- request.set_service(kHealthyService);
- std::unique_ptr<::grpc::ClientReaderInterface<HealthCheckResponse>> reader =
- hc_stub_->Watch(&context, request);
-
- HealthCheckResponse response;
- EXPECT_TRUE(reader->Read(&response));
- EXPECT_EQ(response.SERVING, response.status());
-
- SendHealthCheckRpc("", Status::OK, HealthCheckResponse::SERVING);
- SendHealthCheckRpc(kHealthyService, Status::OK,
- HealthCheckResponse::SERVING);
- SendHealthCheckRpc(kUnhealthyService, Status::OK,
- HealthCheckResponse::NOT_SERVING);
- SendHealthCheckRpc(kNotRegisteredService,
- Status(StatusCode::NOT_FOUND, ""));
- SendHealthCheckRpc(kNewService, Status(StatusCode::NOT_FOUND, ""));
-
- // Shutdown health check service.
- service->Shutdown();
-
- // Watch client gets another update.
- EXPECT_TRUE(reader->Read(&response));
- EXPECT_EQ(response.NOT_SERVING, response.status());
- // Finish Watch call.
- context.TryCancel();
-
- SendHealthCheckRpc("", Status::OK, HealthCheckResponse::NOT_SERVING);
- SendHealthCheckRpc(kHealthyService, Status::OK,
- HealthCheckResponse::NOT_SERVING);
- SendHealthCheckRpc(kUnhealthyService, Status::OK,
- HealthCheckResponse::NOT_SERVING);
- SendHealthCheckRpc(kNotRegisteredService,
- Status(StatusCode::NOT_FOUND, ""));
-
- // Setting status after Shutdown has no effect.
- service->SetServingStatus(kHealthyService, true);
- SendHealthCheckRpc(kHealthyService, Status::OK,
- HealthCheckResponse::NOT_SERVING);
-
- // Adding serving status for a new service after shutdown will return
- // NOT_SERVING.
- service->SetServingStatus(kNewService, true);
- SendHealthCheckRpc(kNewService, Status::OK,
- HealthCheckResponse::NOT_SERVING);
- }
-
- TestServiceImpl echo_test_service_;
- HealthCheckServiceImpl health_check_service_impl_;
- std::unique_ptr<Health::Stub> hc_stub_;
- std::unique_ptr<ServerCompletionQueue> cq_;
- std::unique_ptr<Server> server_;
- std::ostringstream server_address_;
- std::thread cq_thread_;
-};
-
-TEST_F(HealthServiceEnd2endTest, DefaultHealthServiceDisabled) {
- EnableDefaultHealthCheckService(false);
- EXPECT_FALSE(DefaultHealthCheckServiceEnabled());
- SetUpServer(true, false, false, nullptr);
- HealthCheckServiceInterface* default_service =
- server_->GetHealthCheckService();
- EXPECT_TRUE(default_service == nullptr);
-
- ResetStubs();
-
- SendHealthCheckRpc("", Status(StatusCode::UNIMPLEMENTED, ""));
-}
-
-TEST_F(HealthServiceEnd2endTest, DefaultHealthService) {
- EnableDefaultHealthCheckService(true);
- EXPECT_TRUE(DefaultHealthCheckServiceEnabled());
- SetUpServer(true, false, false, nullptr);
- VerifyHealthCheckService();
- VerifyHealthCheckServiceStreaming();
-
- // The default service has a size limit of the service name.
- const TString kTooLongServiceName(201, 'x');
- SendHealthCheckRpc(kTooLongServiceName,
- Status(StatusCode::INVALID_ARGUMENT, ""));
-}
-
-TEST_F(HealthServiceEnd2endTest, DefaultHealthServiceShutdown) {
- EnableDefaultHealthCheckService(true);
- EXPECT_TRUE(DefaultHealthCheckServiceEnabled());
- SetUpServer(true, false, false, nullptr);
- VerifyHealthCheckServiceShutdown();
-}
-
-// Provide an empty service to disable the default service.
-TEST_F(HealthServiceEnd2endTest, ExplicitlyDisableViaOverride) {
- EnableDefaultHealthCheckService(true);
- EXPECT_TRUE(DefaultHealthCheckServiceEnabled());
- std::unique_ptr<HealthCheckServiceInterface> empty_service;
- SetUpServer(true, false, true, std::move(empty_service));
- HealthCheckServiceInterface* service = server_->GetHealthCheckService();
- EXPECT_TRUE(service == nullptr);
-
- ResetStubs();
-
- SendHealthCheckRpc("", Status(StatusCode::UNIMPLEMENTED, ""));
-}
-
-// Provide an explicit override of health checking service interface.
-TEST_F(HealthServiceEnd2endTest, ExplicitlyOverride) {
- EnableDefaultHealthCheckService(true);
- EXPECT_TRUE(DefaultHealthCheckServiceEnabled());
- std::unique_ptr<HealthCheckServiceInterface> override_service(
- new CustomHealthCheckService(&health_check_service_impl_));
- HealthCheckServiceInterface* underlying_service = override_service.get();
- SetUpServer(false, false, true, std::move(override_service));
- HealthCheckServiceInterface* service = server_->GetHealthCheckService();
- EXPECT_TRUE(service == underlying_service);
-
- ResetStubs();
-
- VerifyHealthCheckService();
- VerifyHealthCheckServiceStreaming();
-}
-
-TEST_F(HealthServiceEnd2endTest, ExplicitlyHealthServiceShutdown) {
- EnableDefaultHealthCheckService(true);
- EXPECT_TRUE(DefaultHealthCheckServiceEnabled());
- std::unique_ptr<HealthCheckServiceInterface> override_service(
- new CustomHealthCheckService(&health_check_service_impl_));
- HealthCheckServiceInterface* underlying_service = override_service.get();
- SetUpServer(false, false, true, std::move(override_service));
- HealthCheckServiceInterface* service = server_->GetHealthCheckService();
- EXPECT_TRUE(service == underlying_service);
-
- ResetStubs();
-
- VerifyHealthCheckServiceShutdown();
-}
-
-} // namespace
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/contrib/libs/grpc/test/cpp/end2end/interceptors_util.cc b/contrib/libs/grpc/test/cpp/end2end/interceptors_util.cc
deleted file mode 100644
index b6369347507..00000000000
--- a/contrib/libs/grpc/test/cpp/end2end/interceptors_util.cc
+++ /dev/null
@@ -1,216 +0,0 @@
-/*
- *
- * Copyright 2018 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include "test/cpp/end2end/interceptors_util.h"
-
-#include "y_absl/memory/memory.h"
-
-#include <util/string/cast.h>
-
-namespace grpc {
-namespace testing {
-
-std::atomic<int> PhonyInterceptor::num_times_run_;
-std::atomic<int> PhonyInterceptor::num_times_run_reverse_;
-std::atomic<int> PhonyInterceptor::num_times_cancel_;
-
-void MakeCall(const std::shared_ptr<Channel>& channel,
- const StubOptions& options) {
- auto stub = grpc::testing::EchoTestService::NewStub(channel, options);
- ClientContext ctx;
- EchoRequest req;
- req.mutable_param()->set_echo_metadata(true);
- ctx.AddMetadata("testkey", "testvalue");
- req.set_message("Hello");
- EchoResponse resp;
- Status s = stub->Echo(&ctx, req, &resp);
- EXPECT_EQ(s.ok(), true);
- EXPECT_EQ(resp.message(), "Hello");
-}
-
-void MakeClientStreamingCall(const std::shared_ptr<Channel>& channel) {
- auto stub = grpc::testing::EchoTestService::NewStub(channel);
- ClientContext ctx;
- EchoRequest req;
- req.mutable_param()->set_echo_metadata(true);
- ctx.AddMetadata("testkey", "testvalue");
- req.set_message("Hello");
- EchoResponse resp;
- string expected_resp = "";
- auto writer = stub->RequestStream(&ctx, &resp);
- for (int i = 0; i < kNumStreamingMessages; i++) {
- writer->Write(req);
- expected_resp += "Hello";
- }
- writer->WritesDone();
- Status s = writer->Finish();
- EXPECT_EQ(s.ok(), true);
- EXPECT_EQ(resp.message(), expected_resp);
-}
-
-void MakeServerStreamingCall(const std::shared_ptr<Channel>& channel) {
- auto stub = grpc::testing::EchoTestService::NewStub(channel);
- ClientContext ctx;
- EchoRequest req;
- req.mutable_param()->set_echo_metadata(true);
- ctx.AddMetadata("testkey", "testvalue");
- req.set_message("Hello");
- EchoResponse resp;
- auto reader = stub->ResponseStream(&ctx, req);
- int count = 0;
- while (reader->Read(&resp)) {
- EXPECT_EQ(resp.message(), "Hello");
- count++;
- }
- ASSERT_EQ(count, kNumStreamingMessages);
- Status s = reader->Finish();
- EXPECT_EQ(s.ok(), true);
-}
-
-void MakeBidiStreamingCall(const std::shared_ptr<Channel>& channel) {
- auto stub = grpc::testing::EchoTestService::NewStub(channel);
- ClientContext ctx;
- EchoRequest req;
- EchoResponse resp;
- ctx.AddMetadata("testkey", "testvalue");
- req.mutable_param()->set_echo_metadata(true);
- auto stream = stub->BidiStream(&ctx);
- for (auto i = 0; i < kNumStreamingMessages; i++) {
- req.set_message(TString("Hello") + ::ToString(i));
- stream->Write(req);
- stream->Read(&resp);
- EXPECT_EQ(req.message(), resp.message());
- }
- ASSERT_TRUE(stream->WritesDone());
- Status s = stream->Finish();
- EXPECT_EQ(s.ok(), true);
-}
-
-void MakeAsyncCQCall(const std::shared_ptr<Channel>& channel) {
- auto stub = grpc::testing::EchoTestService::NewStub(channel);
- CompletionQueue cq;
- EchoRequest send_request;
- EchoResponse recv_response;
- Status recv_status;
- ClientContext cli_ctx;
-
- send_request.set_message("Hello");
- cli_ctx.AddMetadata("testkey", "testvalue");
- std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
- stub->AsyncEcho(&cli_ctx, send_request, &cq));
- response_reader->Finish(&recv_response, &recv_status, tag(1));
- Verifier().Expect(1, true).Verify(&cq);
- EXPECT_EQ(send_request.message(), recv_response.message());
- EXPECT_TRUE(recv_status.ok());
-}
-
-void MakeAsyncCQClientStreamingCall(
- const std::shared_ptr<Channel>& /*channel*/) {
- // TODO(yashykt) : Fill this out
-}
-
-void MakeAsyncCQServerStreamingCall(const std::shared_ptr<Channel>& channel) {
- auto stub = grpc::testing::EchoTestService::NewStub(channel);
- CompletionQueue cq;
- EchoRequest send_request;
- EchoResponse recv_response;
- Status recv_status;
- ClientContext cli_ctx;
-
- cli_ctx.AddMetadata("testkey", "testvalue");
- send_request.set_message("Hello");
- std::unique_ptr<ClientAsyncReader<EchoResponse>> cli_stream(
- stub->AsyncResponseStream(&cli_ctx, send_request, &cq, tag(1)));
- Verifier().Expect(1, true).Verify(&cq);
- // Read the expected number of messages
- for (int i = 0; i < kNumStreamingMessages; i++) {
- cli_stream->Read(&recv_response, tag(2));
- Verifier().Expect(2, true).Verify(&cq);
- ASSERT_EQ(recv_response.message(), send_request.message());
- }
- // The next read should fail
- cli_stream->Read(&recv_response, tag(3));
- Verifier().Expect(3, false).Verify(&cq);
- // Get the status
- cli_stream->Finish(&recv_status, tag(4));
- Verifier().Expect(4, true).Verify(&cq);
- EXPECT_TRUE(recv_status.ok());
-}
-
-void MakeAsyncCQBidiStreamingCall(const std::shared_ptr<Channel>& /*channel*/) {
- // TODO(yashykt) : Fill this out
-}
-
-void MakeCallbackCall(const std::shared_ptr<Channel>& channel) {
- auto stub = grpc::testing::EchoTestService::NewStub(channel);
- ClientContext ctx;
- EchoRequest req;
- std::mutex mu;
- std::condition_variable cv;
- bool done = false;
- req.mutable_param()->set_echo_metadata(true);
- ctx.AddMetadata("testkey", "testvalue");
- req.set_message("Hello");
- EchoResponse resp;
- stub->async()->Echo(&ctx, &req, &resp, [&resp, &mu, &done, &cv](Status s) {
- EXPECT_EQ(s.ok(), true);
- EXPECT_EQ(resp.message(), "Hello");
- std::lock_guard<std::mutex> l(mu);
- done = true;
- cv.notify_one();
- });
- std::unique_lock<std::mutex> l(mu);
- while (!done) {
- cv.wait(l);
- }
-}
-
-bool CheckMetadata(const std::multimap<grpc::string_ref, grpc::string_ref>& map,
- const string& key, const string& value) {
- for (const auto& pair : map) {
- if (pair.first.starts_with(key) && pair.second.starts_with(value)) {
- return true;
- }
- }
- return false;
-}
-
-bool CheckMetadata(const std::multimap<TString, TString>& map,
- const string& key, const string& value) {
- for (const auto& pair : map) {
- if (pair.first == key.c_str() && pair.second == value.c_str()) {
- return true;
- }
- }
- return false;
-}
-
-std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
-CreatePhonyClientInterceptors() {
- std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- creators;
- // Add 20 phony interceptors before hijacking interceptor
- creators.reserve(20);
- for (auto i = 0; i < 20; i++) {
- creators.push_back(y_absl::make_unique<PhonyInterceptorFactory>());
- }
- return creators;
-}
-
-} // namespace testing
-} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/end2end/interceptors_util.h b/contrib/libs/grpc/test/cpp/end2end/interceptors_util.h
deleted file mode 100644
index 3603fa2a14b..00000000000
--- a/contrib/libs/grpc/test/cpp/end2end/interceptors_util.h
+++ /dev/null
@@ -1,354 +0,0 @@
-/*
- *
- * Copyright 2018 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <condition_variable>
-
-#include <gtest/gtest.h>
-
-#include <grpcpp/channel.h>
-
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/cpp/util/string_ref_helper.h"
-
-namespace grpc {
-namespace testing {
-/* This interceptor does nothing. Just keeps a global count on the number of
- * times it was invoked. */
-class PhonyInterceptor : public experimental::Interceptor {
- public:
- PhonyInterceptor() {}
-
- void Intercept(experimental::InterceptorBatchMethods* methods) override {
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_INITIAL_METADATA)) {
- num_times_run_++;
- } else if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::
- POST_RECV_INITIAL_METADATA)) {
- num_times_run_reverse_++;
- } else if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_CANCEL)) {
- num_times_cancel_++;
- }
- methods->Proceed();
- }
-
- static void Reset() {
- num_times_run_.store(0);
- num_times_run_reverse_.store(0);
- num_times_cancel_.store(0);
- }
-
- static int GetNumTimesRun() {
- EXPECT_EQ(num_times_run_.load(), num_times_run_reverse_.load());
- return num_times_run_.load();
- }
-
- static int GetNumTimesCancel() { return num_times_cancel_.load(); }
-
- private:
- static std::atomic<int> num_times_run_;
- static std::atomic<int> num_times_run_reverse_;
- static std::atomic<int> num_times_cancel_;
-};
-
-class PhonyInterceptorFactory
- : public experimental::ClientInterceptorFactoryInterface,
- public experimental::ServerInterceptorFactoryInterface {
- public:
- experimental::Interceptor* CreateClientInterceptor(
- experimental::ClientRpcInfo* /*info*/) override {
- return new PhonyInterceptor();
- }
-
- experimental::Interceptor* CreateServerInterceptor(
- experimental::ServerRpcInfo* /*info*/) override {
- return new PhonyInterceptor();
- }
-};
-
-/* This interceptor can be used to test the interception mechanism. */
-class TestInterceptor : public experimental::Interceptor {
- public:
- TestInterceptor(const TString& method, const char* suffix_for_stats,
- experimental::ClientRpcInfo* info) {
- EXPECT_EQ(info->method(), method);
-
- if (suffix_for_stats == nullptr || info->suffix_for_stats() == nullptr) {
- EXPECT_EQ(info->suffix_for_stats(), suffix_for_stats);
- } else {
- EXPECT_EQ(strcmp(info->suffix_for_stats(), suffix_for_stats), 0);
- }
- }
-
- void Intercept(experimental::InterceptorBatchMethods* methods) override {
- methods->Proceed();
- }
-};
-
-class TestInterceptorFactory
- : public experimental::ClientInterceptorFactoryInterface {
- public:
- TestInterceptorFactory(const TString& method,
- const char* suffix_for_stats)
- : method_(method), suffix_for_stats_(suffix_for_stats) {}
-
- experimental::Interceptor* CreateClientInterceptor(
- experimental::ClientRpcInfo* info) override {
- return new TestInterceptor(method_, suffix_for_stats_, info);
- }
-
- private:
- TString method_;
- const char* suffix_for_stats_;
-};
-
-/* This interceptor factory returns nullptr on interceptor creation */
-class NullInterceptorFactory
- : public experimental::ClientInterceptorFactoryInterface,
- public experimental::ServerInterceptorFactoryInterface {
- public:
- experimental::Interceptor* CreateClientInterceptor(
- experimental::ClientRpcInfo* /*info*/) override {
- return nullptr;
- }
-
- experimental::Interceptor* CreateServerInterceptor(
- experimental::ServerRpcInfo* /*info*/) override {
- return nullptr;
- }
-};
-
-class EchoTestServiceStreamingImpl : public EchoTestService::Service {
- public:
- ~EchoTestServiceStreamingImpl() override {}
-
- Status Echo(ServerContext* context, const EchoRequest* request,
- EchoResponse* response) override {
- auto client_metadata = context->client_metadata();
- for (const auto& pair : client_metadata) {
- context->AddTrailingMetadata(ToString(pair.first), ToString(pair.second));
- }
- response->set_message(request->message());
- return Status::OK;
- }
-
- Status BidiStream(
- ServerContext* context,
- grpc::ServerReaderWriter<EchoResponse, EchoRequest>* stream) override {
- EchoRequest req;
- EchoResponse resp;
- auto client_metadata = context->client_metadata();
- for (const auto& pair : client_metadata) {
- context->AddTrailingMetadata(ToString(pair.first), ToString(pair.second));
- }
-
- while (stream->Read(&req)) {
- resp.set_message(req.message());
- EXPECT_TRUE(stream->Write(resp, grpc::WriteOptions()));
- }
- return Status::OK;
- }
-
- Status RequestStream(ServerContext* context,
- ServerReader<EchoRequest>* reader,
- EchoResponse* resp) override {
- auto client_metadata = context->client_metadata();
- for (const auto& pair : client_metadata) {
- context->AddTrailingMetadata(ToString(pair.first), ToString(pair.second));
- }
-
- EchoRequest req;
- string response_str = "";
- while (reader->Read(&req)) {
- response_str += req.message();
- }
- resp->set_message(response_str);
- return Status::OK;
- }
-
- Status ResponseStream(ServerContext* context, const EchoRequest* req,
- ServerWriter<EchoResponse>* writer) override {
- auto client_metadata = context->client_metadata();
- for (const auto& pair : client_metadata) {
- context->AddTrailingMetadata(ToString(pair.first), ToString(pair.second));
- }
-
- EchoResponse resp;
- resp.set_message(req->message());
- for (int i = 0; i < 10; i++) {
- EXPECT_TRUE(writer->Write(resp));
- }
- return Status::OK;
- }
-};
-
-constexpr int kNumStreamingMessages = 10;
-
-void MakeCall(const std::shared_ptr<Channel>& channel,
- const StubOptions& options = StubOptions());
-
-void MakeClientStreamingCall(const std::shared_ptr<Channel>& channel);
-
-void MakeServerStreamingCall(const std::shared_ptr<Channel>& channel);
-
-void MakeBidiStreamingCall(const std::shared_ptr<Channel>& channel);
-
-void MakeAsyncCQCall(const std::shared_ptr<Channel>& channel);
-
-void MakeAsyncCQClientStreamingCall(const std::shared_ptr<Channel>& channel);
-
-void MakeAsyncCQServerStreamingCall(const std::shared_ptr<Channel>& channel);
-
-void MakeAsyncCQBidiStreamingCall(const std::shared_ptr<Channel>& channel);
-
-void MakeCallbackCall(const std::shared_ptr<Channel>& channel);
-
-bool CheckMetadata(const std::multimap<grpc::string_ref, grpc::string_ref>& map,
- const string& key, const string& value);
-
-bool CheckMetadata(const std::multimap<TString, TString>& map,
- const string& key, const string& value);
-
-std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
-CreatePhonyClientInterceptors();
-
-inline void* tag(int i) { return reinterpret_cast<void*>(i); }
-inline int detag(void* p) {
- return static_cast<int>(reinterpret_cast<intptr_t>(p));
-}
-
-class Verifier {
- public:
- Verifier() : lambda_run_(false) {}
- // Expect sets the expected ok value for a specific tag
- Verifier& Expect(int i, bool expect_ok) {
- return ExpectUnless(i, expect_ok, false);
- }
- // ExpectUnless sets the expected ok value for a specific tag
- // unless the tag was already marked seen (as a result of ExpectMaybe)
- Verifier& ExpectUnless(int i, bool expect_ok, bool seen) {
- if (!seen) {
- expectations_[tag(i)] = expect_ok;
- }
- return *this;
- }
- // ExpectMaybe sets the expected ok value for a specific tag, but does not
- // require it to appear
- // If it does, sets *seen to true
- Verifier& ExpectMaybe(int i, bool expect_ok, bool* seen) {
- if (!*seen) {
- maybe_expectations_[tag(i)] = MaybeExpect{expect_ok, seen};
- }
- return *this;
- }
-
- // Next waits for 1 async tag to complete, checks its
- // expectations, and returns the tag
- int Next(CompletionQueue* cq, bool ignore_ok) {
- bool ok;
- void* got_tag;
- EXPECT_TRUE(cq->Next(&got_tag, &ok));
- GotTag(got_tag, ok, ignore_ok);
- return detag(got_tag);
- }
-
- template <typename T>
- CompletionQueue::NextStatus DoOnceThenAsyncNext(
- CompletionQueue* cq, void** got_tag, bool* ok, T deadline,
- std::function<void(void)> lambda) {
- if (lambda_run_) {
- return cq->AsyncNext(got_tag, ok, deadline);
- } else {
- lambda_run_ = true;
- return cq->DoThenAsyncNext(lambda, got_tag, ok, deadline);
- }
- }
-
- // Verify keeps calling Next until all currently set
- // expected tags are complete
- void Verify(CompletionQueue* cq) { Verify(cq, false); }
-
- // This version of Verify allows optionally ignoring the
- // outcome of the expectation
- void Verify(CompletionQueue* cq, bool ignore_ok) {
- GPR_ASSERT(!expectations_.empty() || !maybe_expectations_.empty());
- while (!expectations_.empty()) {
- Next(cq, ignore_ok);
- }
- }
-
- // This version of Verify stops after a certain deadline, and uses the
- // DoThenAsyncNext API
- // to call the lambda
- void Verify(CompletionQueue* cq,
- std::chrono::system_clock::time_point deadline,
- const std::function<void(void)>& lambda) {
- if (expectations_.empty()) {
- bool ok;
- void* got_tag;
- EXPECT_EQ(DoOnceThenAsyncNext(cq, &got_tag, &ok, deadline, lambda),
- CompletionQueue::TIMEOUT);
- } else {
- while (!expectations_.empty()) {
- bool ok;
- void* got_tag;
- EXPECT_EQ(DoOnceThenAsyncNext(cq, &got_tag, &ok, deadline, lambda),
- CompletionQueue::GOT_EVENT);
- GotTag(got_tag, ok, false);
- }
- }
- }
-
- private:
- void GotTag(void* got_tag, bool ok, bool ignore_ok) {
- auto it = expectations_.find(got_tag);
- if (it != expectations_.end()) {
- if (!ignore_ok) {
- EXPECT_EQ(it->second, ok);
- }
- expectations_.erase(it);
- } else {
- auto it2 = maybe_expectations_.find(got_tag);
- if (it2 != maybe_expectations_.end()) {
- if (it2->second.seen != nullptr) {
- EXPECT_FALSE(*it2->second.seen);
- *it2->second.seen = true;
- }
- if (!ignore_ok) {
- EXPECT_EQ(it2->second.ok, ok);
- }
- } else {
- gpr_log(GPR_ERROR, "Unexpected tag: %p", got_tag);
- abort();
- }
- }
- }
-
- struct MaybeExpect {
- bool ok;
- bool* seen;
- };
-
- std::map<void*, bool> expectations_;
- std::map<void*, MaybeExpect> maybe_expectations_;
- bool lambda_run_;
-};
-
-} // namespace testing
-} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/end2end/server_interceptors/ya.make b/contrib/libs/grpc/test/cpp/end2end/server_interceptors/ya.make
deleted file mode 100644
index 2bdf076b4a9..00000000000
--- a/contrib/libs/grpc/test/cpp/end2end/server_interceptors/ya.make
+++ /dev/null
@@ -1,27 +0,0 @@
-GTEST_UGLY()
-
-ADDINCL(
- ${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
- ${ARCADIA_ROOT}/contrib/libs/grpc
-)
-
-PEERDIR(
- contrib/libs/grpc/src/proto/grpc/core
- contrib/libs/grpc/src/proto/grpc/testing
- contrib/libs/grpc/src/proto/grpc/testing/duplicate
- contrib/libs/grpc/test/core/util
- contrib/libs/grpc/test/cpp/end2end
- contrib/libs/grpc/test/cpp/util
-)
-
-NO_COMPILER_WARNINGS()
-
-SRCDIR(
- contrib/libs/grpc/test/cpp/end2end
-)
-
-SRCS(
- server_interceptors_end2end_test.cc
-)
-
-END()
diff --git a/contrib/libs/grpc/test/cpp/end2end/server_interceptors_end2end_test.cc b/contrib/libs/grpc/test/cpp/end2end/server_interceptors_end2end_test.cc
deleted file mode 100644
index 5b631a1359e..00000000000
--- a/contrib/libs/grpc/test/cpp/end2end/server_interceptors_end2end_test.cc
+++ /dev/null
@@ -1,703 +0,0 @@
-/*
- *
- * Copyright 2018 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <memory>
-#include <vector>
-
-#include <gtest/gtest.h>
-
-#include "y_absl/memory/memory.h"
-#include "y_absl/strings/match.h"
-
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/generic/generic_stub.h>
-#include <grpcpp/impl/codegen/proto_utils.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/server_context.h>
-#include <grpcpp/support/server_interceptor.h>
-
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-#include "test/cpp/end2end/interceptors_util.h"
-#include "test/cpp/end2end/test_service_impl.h"
-#include "test/cpp/util/byte_buffer_proto_helper.h"
-
-namespace grpc {
-namespace testing {
-namespace {
-
-class LoggingInterceptor : public experimental::Interceptor {
- public:
- explicit LoggingInterceptor(experimental::ServerRpcInfo* info) {
- info_ = info;
-
- // Check the method name and compare to the type
- const char* method = info->method();
- experimental::ServerRpcInfo::Type type = info->type();
-
- // Check that we use one of our standard methods with expected type.
- // Also allow the health checking service.
- // We accept BIDI_STREAMING for Echo in case it's an AsyncGenericService
- // being tested (the GenericRpc test).
- // The empty method is for the Unimplemented requests that arise
- // when draining the CQ.
- EXPECT_TRUE(
- strstr(method, "/grpc.health") == method ||
- (strcmp(method, "/grpc.testing.EchoTestService/Echo") == 0 &&
- (type == experimental::ServerRpcInfo::Type::UNARY ||
- type == experimental::ServerRpcInfo::Type::BIDI_STREAMING)) ||
- (strcmp(method, "/grpc.testing.EchoTestService/RequestStream") == 0 &&
- type == experimental::ServerRpcInfo::Type::CLIENT_STREAMING) ||
- (strcmp(method, "/grpc.testing.EchoTestService/ResponseStream") == 0 &&
- type == experimental::ServerRpcInfo::Type::SERVER_STREAMING) ||
- (strcmp(method, "/grpc.testing.EchoTestService/BidiStream") == 0 &&
- type == experimental::ServerRpcInfo::Type::BIDI_STREAMING) ||
- strcmp(method, "/grpc.testing.EchoTestService/Unimplemented") == 0 ||
- (strcmp(method, "") == 0 &&
- type == experimental::ServerRpcInfo::Type::BIDI_STREAMING));
- }
-
- void Intercept(experimental::InterceptorBatchMethods* methods) override {
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_INITIAL_METADATA)) {
- auto* map = methods->GetSendInitialMetadata();
- // Got nothing better to do here for now
- EXPECT_EQ(map->size(), static_cast<unsigned>(0));
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_MESSAGE)) {
- EchoRequest req;
- auto* buffer = methods->GetSerializedSendMessage();
- auto copied_buffer = *buffer;
- EXPECT_TRUE(
- SerializationTraits<EchoRequest>::Deserialize(&copied_buffer, &req)
- .ok());
- EXPECT_TRUE(req.message().find("Hello") == 0);
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_STATUS)) {
- auto* map = methods->GetSendTrailingMetadata();
- bool found = false;
- // Check that we received the metadata as an echo
- for (const auto& pair : *map) {
- found = y_absl::StartsWith(pair.first, "testkey") &&
- y_absl::StartsWith(pair.second, "testvalue");
- if (found) break;
- }
- EXPECT_EQ(found, true);
- auto status = methods->GetSendStatus();
- EXPECT_EQ(status.ok(), true);
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::POST_RECV_INITIAL_METADATA)) {
- auto* map = methods->GetRecvInitialMetadata();
- bool found = false;
- // Check that we received the metadata as an echo
- for (const auto& pair : *map) {
- found = pair.first.find("testkey") == 0 &&
- pair.second.find("testvalue") == 0;
- if (found) break;
- }
- EXPECT_EQ(found, true);
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::POST_RECV_MESSAGE)) {
- EchoResponse* resp =
- static_cast<EchoResponse*>(methods->GetRecvMessage());
- if (resp != nullptr) {
- EXPECT_TRUE(resp->message().find("Hello") == 0);
- }
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::POST_RECV_CLOSE)) {
- // Got nothing interesting to do here
- }
- methods->Proceed();
- }
-
- private:
- experimental::ServerRpcInfo* info_;
-};
-
-class LoggingInterceptorFactory
- : public experimental::ServerInterceptorFactoryInterface {
- public:
- experimental::Interceptor* CreateServerInterceptor(
- experimental::ServerRpcInfo* info) override {
- return new LoggingInterceptor(info);
- }
-};
-
-// Test if SendMessage function family works as expected for sync/callback apis
-class SyncSendMessageTester : public experimental::Interceptor {
- public:
- explicit SyncSendMessageTester(experimental::ServerRpcInfo* /*info*/) {}
-
- void Intercept(experimental::InterceptorBatchMethods* methods) override {
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_MESSAGE)) {
- string old_msg =
- static_cast<const EchoRequest*>(methods->GetSendMessage())->message();
- EXPECT_EQ(old_msg.find("Hello"), 0u);
- new_msg_.set_message(TString("World" + old_msg).c_str());
- methods->ModifySendMessage(&new_msg_);
- }
- methods->Proceed();
- }
-
- private:
- EchoRequest new_msg_;
-};
-
-class SyncSendMessageTesterFactory
- : public experimental::ServerInterceptorFactoryInterface {
- public:
- experimental::Interceptor* CreateServerInterceptor(
- experimental::ServerRpcInfo* info) override {
- return new SyncSendMessageTester(info);
- }
-};
-
-// Test if SendMessage function family works as expected for sync/callback apis
-class SyncSendMessageVerifier : public experimental::Interceptor {
- public:
- explicit SyncSendMessageVerifier(experimental::ServerRpcInfo* /*info*/) {}
-
- void Intercept(experimental::InterceptorBatchMethods* methods) override {
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_MESSAGE)) {
- // Make sure that the changes made in SyncSendMessageTester persisted
- string old_msg =
- static_cast<const EchoRequest*>(methods->GetSendMessage())->message();
- EXPECT_EQ(old_msg.find("World"), 0u);
-
- // Remove the "World" part of the string that we added earlier
- new_msg_.set_message(old_msg.erase(0, 5));
- methods->ModifySendMessage(&new_msg_);
-
- // LoggingInterceptor verifies that changes got reverted
- }
- methods->Proceed();
- }
-
- private:
- EchoRequest new_msg_;
-};
-
-class SyncSendMessageVerifierFactory
- : public experimental::ServerInterceptorFactoryInterface {
- public:
- experimental::Interceptor* CreateServerInterceptor(
- experimental::ServerRpcInfo* info) override {
- return new SyncSendMessageVerifier(info);
- }
-};
-
-void MakeBidiStreamingCall(const std::shared_ptr<Channel>& channel) {
- auto stub = grpc::testing::EchoTestService::NewStub(channel);
- ClientContext ctx;
- EchoRequest req;
- EchoResponse resp;
- ctx.AddMetadata("testkey", "testvalue");
- auto stream = stub->BidiStream(&ctx);
- for (auto i = 0; i < 10; i++) {
- req.set_message("Hello" + ::ToString(i));
- stream->Write(req);
- stream->Read(&resp);
- EXPECT_EQ(req.message(), resp.message());
- }
- ASSERT_TRUE(stream->WritesDone());
- Status s = stream->Finish();
- EXPECT_EQ(s.ok(), true);
-}
-
-class ServerInterceptorsEnd2endSyncUnaryTest : public ::testing::Test {
- protected:
- ServerInterceptorsEnd2endSyncUnaryTest() {
- int port = 5004; // grpc_pick_unused_port_or_die();
-
- ServerBuilder builder;
- server_address_ = "localhost:" + ::ToString(port);
- builder.AddListeningPort(server_address_, InsecureServerCredentials());
- builder.RegisterService(&service_);
-
- std::vector<
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
- creators;
- creators.push_back(
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
- new SyncSendMessageTesterFactory()));
- creators.push_back(
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
- new SyncSendMessageVerifierFactory()));
- creators.push_back(
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
- new LoggingInterceptorFactory()));
- // Add 20 phony interceptor factories and null interceptor factories
- for (auto i = 0; i < 20; i++) {
- creators.push_back(y_absl::make_unique<PhonyInterceptorFactory>());
- creators.push_back(y_absl::make_unique<NullInterceptorFactory>());
- }
- builder.experimental().SetInterceptorCreators(std::move(creators));
- server_ = builder.BuildAndStart();
- }
- TString server_address_;
- TestServiceImpl service_;
- std::unique_ptr<Server> server_;
-};
-
-TEST_F(ServerInterceptorsEnd2endSyncUnaryTest, UnaryTest) {
- ChannelArguments args;
- PhonyInterceptor::Reset();
- auto channel =
- grpc::CreateChannel(server_address_, InsecureChannelCredentials());
- MakeCall(channel);
- // Make sure all 20 phony interceptors were run
- EXPECT_EQ(PhonyInterceptor::GetNumTimesRun(), 20);
-}
-
-class ServerInterceptorsEnd2endSyncStreamingTest : public ::testing::Test {
- protected:
- ServerInterceptorsEnd2endSyncStreamingTest() {
- int port = 5005; // grpc_pick_unused_port_or_die();
-
- ServerBuilder builder;
- server_address_ = "localhost:" + ::ToString(port);
- builder.AddListeningPort(server_address_, InsecureServerCredentials());
- builder.RegisterService(&service_);
-
- std::vector<
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
- creators;
- creators.push_back(
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
- new SyncSendMessageTesterFactory()));
- creators.push_back(
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
- new SyncSendMessageVerifierFactory()));
- creators.push_back(
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
- new LoggingInterceptorFactory()));
- for (auto i = 0; i < 20; i++) {
- creators.push_back(y_absl::make_unique<PhonyInterceptorFactory>());
- }
- builder.experimental().SetInterceptorCreators(std::move(creators));
- server_ = builder.BuildAndStart();
- }
- TString server_address_;
- EchoTestServiceStreamingImpl service_;
- std::unique_ptr<Server> server_;
-};
-
-TEST_F(ServerInterceptorsEnd2endSyncStreamingTest, ClientStreamingTest) {
- ChannelArguments args;
- PhonyInterceptor::Reset();
- auto channel =
- grpc::CreateChannel(server_address_, InsecureChannelCredentials());
- MakeClientStreamingCall(channel);
- // Make sure all 20 phony interceptors were run
- EXPECT_EQ(PhonyInterceptor::GetNumTimesRun(), 20);
-}
-
-TEST_F(ServerInterceptorsEnd2endSyncStreamingTest, ServerStreamingTest) {
- ChannelArguments args;
- PhonyInterceptor::Reset();
- auto channel =
- grpc::CreateChannel(server_address_, InsecureChannelCredentials());
- MakeServerStreamingCall(channel);
- // Make sure all 20 phony interceptors were run
- EXPECT_EQ(PhonyInterceptor::GetNumTimesRun(), 20);
-}
-
-TEST_F(ServerInterceptorsEnd2endSyncStreamingTest, BidiStreamingTest) {
- ChannelArguments args;
- PhonyInterceptor::Reset();
- auto channel =
- grpc::CreateChannel(server_address_, InsecureChannelCredentials());
- MakeBidiStreamingCall(channel);
- // Make sure all 20 phony interceptors were run
- EXPECT_EQ(PhonyInterceptor::GetNumTimesRun(), 20);
-}
-
-class ServerInterceptorsAsyncEnd2endTest : public ::testing::Test {};
-
-TEST_F(ServerInterceptorsAsyncEnd2endTest, UnaryTest) {
- PhonyInterceptor::Reset();
- int port = 5006; // grpc_pick_unused_port_or_die();
- string server_address = "localhost:" + ::ToString(port);
- ServerBuilder builder;
- EchoTestService::AsyncService service;
- builder.AddListeningPort(server_address, InsecureServerCredentials());
- builder.RegisterService(&service);
- std::vector<std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
- creators;
- creators.push_back(
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
- new LoggingInterceptorFactory()));
- for (auto i = 0; i < 20; i++) {
- creators.push_back(y_absl::make_unique<PhonyInterceptorFactory>());
- }
- builder.experimental().SetInterceptorCreators(std::move(creators));
- auto cq = builder.AddCompletionQueue();
- auto server = builder.BuildAndStart();
-
- ChannelArguments args;
- auto channel =
- grpc::CreateChannel(server_address, InsecureChannelCredentials());
- auto stub = grpc::testing::EchoTestService::NewStub(channel);
-
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
-
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx);
-
- send_request.set_message("Hello");
- cli_ctx.AddMetadata("testkey", "testvalue");
- std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
- stub->AsyncEcho(&cli_ctx, send_request, cq.get()));
-
- service.RequestEcho(&srv_ctx, &recv_request, &response_writer, cq.get(),
- cq.get(), tag(2));
-
- response_reader->Finish(&recv_response, &recv_status, tag(4));
-
- Verifier().Expect(2, true).Verify(cq.get());
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- EXPECT_TRUE(CheckMetadata(srv_ctx.client_metadata(), "testkey", "testvalue"));
- srv_ctx.AddTrailingMetadata("testkey", "testvalue");
-
- send_response.set_message(recv_request.message());
- response_writer.Finish(send_response, Status::OK, tag(3));
- Verifier().Expect(3, true).Expect(4, true).Verify(cq.get());
-
- EXPECT_EQ(send_response.message(), recv_response.message());
- EXPECT_TRUE(recv_status.ok());
- EXPECT_TRUE(CheckMetadata(cli_ctx.GetServerTrailingMetadata(), "testkey",
- "testvalue"));
-
- // Make sure all 20 phony interceptors were run
- EXPECT_EQ(PhonyInterceptor::GetNumTimesRun(), 20);
-
- server->Shutdown();
- cq->Shutdown();
- void* ignored_tag;
- bool ignored_ok;
- while (cq->Next(&ignored_tag, &ignored_ok)) {
- }
- // grpc_recycle_unused_port(port);
-}
-
-TEST_F(ServerInterceptorsAsyncEnd2endTest, BidiStreamingTest) {
- PhonyInterceptor::Reset();
- int port = 5007; // grpc_pick_unused_port_or_die();
- string server_address = "localhost:" + ::ToString(port);
- ServerBuilder builder;
- EchoTestService::AsyncService service;
- builder.AddListeningPort(server_address, InsecureServerCredentials());
- builder.RegisterService(&service);
- std::vector<std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
- creators;
- creators.push_back(
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
- new LoggingInterceptorFactory()));
- for (auto i = 0; i < 20; i++) {
- creators.push_back(y_absl::make_unique<PhonyInterceptorFactory>());
- }
- builder.experimental().SetInterceptorCreators(std::move(creators));
- auto cq = builder.AddCompletionQueue();
- auto server = builder.BuildAndStart();
-
- ChannelArguments args;
- auto channel =
- grpc::CreateChannel(server_address, InsecureChannelCredentials());
- auto stub = grpc::testing::EchoTestService::NewStub(channel);
-
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
-
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- grpc::ServerAsyncReaderWriter<EchoResponse, EchoRequest> srv_stream(&srv_ctx);
-
- send_request.set_message("Hello");
- cli_ctx.AddMetadata("testkey", "testvalue");
- std::unique_ptr<ClientAsyncReaderWriter<EchoRequest, EchoResponse>>
- cli_stream(stub->AsyncBidiStream(&cli_ctx, cq.get(), tag(1)));
-
- service.RequestBidiStream(&srv_ctx, &srv_stream, cq.get(), cq.get(), tag(2));
-
- Verifier().Expect(1, true).Expect(2, true).Verify(cq.get());
-
- EXPECT_TRUE(CheckMetadata(srv_ctx.client_metadata(), "testkey", "testvalue"));
- srv_ctx.AddTrailingMetadata("testkey", "testvalue");
-
- cli_stream->Write(send_request, tag(3));
- srv_stream.Read(&recv_request, tag(4));
- Verifier().Expect(3, true).Expect(4, true).Verify(cq.get());
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- send_response.set_message(recv_request.message());
- srv_stream.Write(send_response, tag(5));
- cli_stream->Read(&recv_response, tag(6));
- Verifier().Expect(5, true).Expect(6, true).Verify(cq.get());
- EXPECT_EQ(send_response.message(), recv_response.message());
-
- cli_stream->WritesDone(tag(7));
- srv_stream.Read(&recv_request, tag(8));
- Verifier().Expect(7, true).Expect(8, false).Verify(cq.get());
-
- srv_stream.Finish(Status::OK, tag(9));
- cli_stream->Finish(&recv_status, tag(10));
- Verifier().Expect(9, true).Expect(10, true).Verify(cq.get());
-
- EXPECT_TRUE(recv_status.ok());
- EXPECT_TRUE(CheckMetadata(cli_ctx.GetServerTrailingMetadata(), "testkey",
- "testvalue"));
-
- // Make sure all 20 phony interceptors were run
- EXPECT_EQ(PhonyInterceptor::GetNumTimesRun(), 20);
-
- server->Shutdown();
- cq->Shutdown();
- void* ignored_tag;
- bool ignored_ok;
- while (cq->Next(&ignored_tag, &ignored_ok)) {
- }
- // grpc_recycle_unused_port(port);
-}
-
-TEST_F(ServerInterceptorsAsyncEnd2endTest, GenericRPCTest) {
- PhonyInterceptor::Reset();
- int port = 5008; // grpc_pick_unused_port_or_die();
- string server_address = "localhost:" + ::ToString(port);
- ServerBuilder builder;
- AsyncGenericService service;
- builder.AddListeningPort(server_address, InsecureServerCredentials());
- builder.RegisterAsyncGenericService(&service);
- std::vector<std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
- creators;
- creators.reserve(20);
- for (auto i = 0; i < 20; i++) {
- creators.push_back(y_absl::make_unique<PhonyInterceptorFactory>());
- }
- builder.experimental().SetInterceptorCreators(std::move(creators));
- auto srv_cq = builder.AddCompletionQueue();
- CompletionQueue cli_cq;
- auto server = builder.BuildAndStart();
-
- ChannelArguments args;
- auto channel =
- grpc::CreateChannel(server_address, InsecureChannelCredentials());
- GenericStub generic_stub(channel);
-
- const TString kMethodName("/grpc.cpp.test.util.EchoTestService/Echo");
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
-
- ClientContext cli_ctx;
- GenericServerContext srv_ctx;
- GenericServerAsyncReaderWriter stream(&srv_ctx);
-
- // The string needs to be long enough to test heap-based slice.
- send_request.set_message("Hello");
- cli_ctx.AddMetadata("testkey", "testvalue");
-
- CompletionQueue* cq = srv_cq.get();
- std::thread request_call([cq]() { Verifier().Expect(4, true).Verify(cq); });
- std::unique_ptr<GenericClientAsyncReaderWriter> call =
- generic_stub.PrepareCall(&cli_ctx, kMethodName, &cli_cq);
- call->StartCall(tag(1));
- Verifier().Expect(1, true).Verify(&cli_cq);
- std::unique_ptr<ByteBuffer> send_buffer =
- SerializeToByteBuffer(&send_request);
- call->Write(*send_buffer, tag(2));
- // Send ByteBuffer can be destroyed after calling Write.
- send_buffer.reset();
- Verifier().Expect(2, true).Verify(&cli_cq);
- call->WritesDone(tag(3));
- Verifier().Expect(3, true).Verify(&cli_cq);
-
- service.RequestCall(&srv_ctx, &stream, srv_cq.get(), srv_cq.get(), tag(4));
-
- request_call.join();
- EXPECT_EQ(kMethodName, srv_ctx.method());
- EXPECT_TRUE(CheckMetadata(srv_ctx.client_metadata(), "testkey", "testvalue"));
- srv_ctx.AddTrailingMetadata("testkey", "testvalue");
-
- ByteBuffer recv_buffer;
- stream.Read(&recv_buffer, tag(5));
- Verifier().Expect(5, true).Verify(srv_cq.get());
- EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_request));
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- send_response.set_message(recv_request.message());
- send_buffer = SerializeToByteBuffer(&send_response);
- stream.Write(*send_buffer, tag(6));
- send_buffer.reset();
- Verifier().Expect(6, true).Verify(srv_cq.get());
-
- stream.Finish(Status::OK, tag(7));
- // Shutdown srv_cq before we try to get the tag back, to verify that the
- // interception API handles completion queue shutdowns that take place before
- // all the tags are returned
- srv_cq->Shutdown();
- Verifier().Expect(7, true).Verify(srv_cq.get());
-
- recv_buffer.Clear();
- call->Read(&recv_buffer, tag(8));
- Verifier().Expect(8, true).Verify(&cli_cq);
- EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_response));
-
- call->Finish(&recv_status, tag(9));
- cli_cq.Shutdown();
- Verifier().Expect(9, true).Verify(&cli_cq);
-
- EXPECT_EQ(send_response.message(), recv_response.message());
- EXPECT_TRUE(recv_status.ok());
- EXPECT_TRUE(CheckMetadata(cli_ctx.GetServerTrailingMetadata(), "testkey",
- "testvalue"));
-
- // Make sure all 20 phony interceptors were run
- EXPECT_EQ(PhonyInterceptor::GetNumTimesRun(), 20);
-
- server->Shutdown();
- void* ignored_tag;
- bool ignored_ok;
- while (cli_cq.Next(&ignored_tag, &ignored_ok)) {
- }
- while (srv_cq->Next(&ignored_tag, &ignored_ok)) {
- }
- // grpc_recycle_unused_port(port);
-}
-
-TEST_F(ServerInterceptorsAsyncEnd2endTest, UnimplementedRpcTest) {
- PhonyInterceptor::Reset();
- int port = 5009; // grpc_pick_unused_port_or_die();
- string server_address = "localhost:" + ::ToString(port);
- ServerBuilder builder;
- builder.AddListeningPort(server_address, InsecureServerCredentials());
- std::vector<std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
- creators;
- creators.reserve(20);
- for (auto i = 0; i < 20; i++) {
- creators.push_back(y_absl::make_unique<PhonyInterceptorFactory>());
- }
- builder.experimental().SetInterceptorCreators(std::move(creators));
- auto cq = builder.AddCompletionQueue();
- auto server = builder.BuildAndStart();
-
- ChannelArguments args;
- std::shared_ptr<Channel> channel =
- grpc::CreateChannel(server_address, InsecureChannelCredentials());
- std::unique_ptr<grpc::testing::UnimplementedEchoService::Stub> stub;
- stub = grpc::testing::UnimplementedEchoService::NewStub(channel);
- EchoRequest send_request;
- EchoResponse recv_response;
- Status recv_status;
-
- ClientContext cli_ctx;
- send_request.set_message("Hello");
- std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
- stub->AsyncUnimplemented(&cli_ctx, send_request, cq.get()));
-
- response_reader->Finish(&recv_response, &recv_status, tag(4));
- Verifier().Expect(4, true).Verify(cq.get());
-
- EXPECT_EQ(StatusCode::UNIMPLEMENTED, recv_status.error_code());
- EXPECT_EQ("", recv_status.error_message());
-
- // Make sure all 20 phony interceptors were run
- EXPECT_EQ(PhonyInterceptor::GetNumTimesRun(), 20);
-
- server->Shutdown();
- cq->Shutdown();
- void* ignored_tag;
- bool ignored_ok;
- while (cq->Next(&ignored_tag, &ignored_ok)) {
- }
- // grpc_recycle_unused_port(port);
-}
-
-class ServerInterceptorsSyncUnimplementedEnd2endTest : public ::testing::Test {
-};
-
-TEST_F(ServerInterceptorsSyncUnimplementedEnd2endTest, UnimplementedRpcTest) {
- PhonyInterceptor::Reset();
- int port = 5010; // grpc_pick_unused_port_or_die();
- string server_address = "localhost:" + ::ToString(port);
- ServerBuilder builder;
- TestServiceImpl service;
- builder.RegisterService(&service);
- builder.AddListeningPort(server_address, InsecureServerCredentials());
- std::vector<std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
- creators;
- creators.reserve(20);
- for (auto i = 0; i < 20; i++) {
- creators.push_back(y_absl::make_unique<PhonyInterceptorFactory>());
- }
- builder.experimental().SetInterceptorCreators(std::move(creators));
- auto server = builder.BuildAndStart();
-
- ChannelArguments args;
- std::shared_ptr<Channel> channel =
- grpc::CreateChannel(server_address, InsecureChannelCredentials());
- std::unique_ptr<grpc::testing::UnimplementedEchoService::Stub> stub;
- stub = grpc::testing::UnimplementedEchoService::NewStub(channel);
- EchoRequest send_request;
- EchoResponse recv_response;
-
- ClientContext cli_ctx;
- send_request.set_message("Hello");
- Status recv_status =
- stub->Unimplemented(&cli_ctx, send_request, &recv_response);
-
- EXPECT_EQ(StatusCode::UNIMPLEMENTED, recv_status.error_code());
- EXPECT_EQ("", recv_status.error_message());
-
- // Make sure all 20 phony interceptors were run
- EXPECT_EQ(PhonyInterceptor::GetNumTimesRun(), 20);
-
- server->Shutdown();
- // grpc_recycle_unused_port(port);
-}
-
-} // namespace
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/contrib/libs/grpc/test/cpp/end2end/test_health_check_service_impl.cc b/contrib/libs/grpc/test/cpp/end2end/test_health_check_service_impl.cc
deleted file mode 100644
index 5b212cba313..00000000000
--- a/contrib/libs/grpc/test/cpp/end2end/test_health_check_service_impl.cc
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- *
- * Copyright 2018 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include "test/cpp/end2end/test_health_check_service_impl.h"
-
-#include <grpc/grpc.h>
-
-using grpc::health::v1::HealthCheckRequest;
-using grpc::health::v1::HealthCheckResponse;
-
-namespace grpc {
-namespace testing {
-
-Status HealthCheckServiceImpl::Check(ServerContext* /*context*/,
- const HealthCheckRequest* request,
- HealthCheckResponse* response) {
- std::lock_guard<std::mutex> lock(mu_);
- auto iter = status_map_.find(request->service());
- if (iter == status_map_.end()) {
- return Status(StatusCode::NOT_FOUND, "");
- }
- response->set_status(iter->second);
- return Status::OK;
-}
-
-Status HealthCheckServiceImpl::Watch(
- ServerContext* context, const HealthCheckRequest* request,
- ::grpc::ServerWriter<HealthCheckResponse>* writer) {
- auto last_state = HealthCheckResponse::UNKNOWN;
- while (!context->IsCancelled()) {
- {
- std::lock_guard<std::mutex> lock(mu_);
- HealthCheckResponse response;
- auto iter = status_map_.find(request->service());
- if (iter == status_map_.end()) {
- response.set_status(response.SERVICE_UNKNOWN);
- } else {
- response.set_status(iter->second);
- }
- if (response.status() != last_state) {
- writer->Write(response, ::grpc::WriteOptions());
- last_state = response.status();
- }
- }
- gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
- gpr_time_from_millis(1000, GPR_TIMESPAN)));
- }
- return Status::OK;
-}
-
-void HealthCheckServiceImpl::SetStatus(
- const TString& service_name,
- HealthCheckResponse::ServingStatus status) {
- std::lock_guard<std::mutex> lock(mu_);
- if (shutdown_) {
- status = HealthCheckResponse::NOT_SERVING;
- }
- status_map_[service_name] = status;
-}
-
-void HealthCheckServiceImpl::SetAll(HealthCheckResponse::ServingStatus status) {
- std::lock_guard<std::mutex> lock(mu_);
- if (shutdown_) {
- return;
- }
- for (auto iter = status_map_.begin(); iter != status_map_.end(); ++iter) {
- iter->second = status;
- }
-}
-
-void HealthCheckServiceImpl::Shutdown() {
- std::lock_guard<std::mutex> lock(mu_);
- if (shutdown_) {
- return;
- }
- shutdown_ = true;
- for (auto iter = status_map_.begin(); iter != status_map_.end(); ++iter) {
- iter->second = HealthCheckResponse::NOT_SERVING;
- }
-}
-
-} // namespace testing
-} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/end2end/test_health_check_service_impl.h b/contrib/libs/grpc/test/cpp/end2end/test_health_check_service_impl.h
deleted file mode 100644
index d370e4693a5..00000000000
--- a/contrib/libs/grpc/test/cpp/end2end/test_health_check_service_impl.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- *
- * Copyright 2018 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-#ifndef GRPC_TEST_CPP_END2END_TEST_HEALTH_CHECK_SERVICE_IMPL_H
-#define GRPC_TEST_CPP_END2END_TEST_HEALTH_CHECK_SERVICE_IMPL_H
-
-#include <map>
-#include <mutex>
-
-#include <grpcpp/server_context.h>
-#include <grpcpp/support/status.h>
-
-#include "src/proto/grpc/health/v1/health.grpc.pb.h"
-
-namespace grpc {
-namespace testing {
-
-// A sample sync implementation of the health checking service. This does the
-// same thing as the default one.
-class HealthCheckServiceImpl : public health::v1::Health::Service {
- public:
- Status Check(ServerContext* context,
- const health::v1::HealthCheckRequest* request,
- health::v1::HealthCheckResponse* response) override;
- Status Watch(ServerContext* context,
- const health::v1::HealthCheckRequest* request,
- ServerWriter<health::v1::HealthCheckResponse>* writer) override;
- void SetStatus(const TString& service_name,
- health::v1::HealthCheckResponse::ServingStatus status);
- void SetAll(health::v1::HealthCheckResponse::ServingStatus status);
-
- void Shutdown();
-
- private:
- std::mutex mu_;
- bool shutdown_ = false;
- std::map<const TString, health::v1::HealthCheckResponse::ServingStatus>
- status_map_;
-};
-
-} // namespace testing
-} // namespace grpc
-
-#endif // GRPC_TEST_CPP_END2END_TEST_HEALTH_CHECK_SERVICE_IMPL_H
diff --git a/contrib/libs/grpc/test/cpp/end2end/test_service_impl.cc b/contrib/libs/grpc/test/cpp/end2end/test_service_impl.cc
deleted file mode 100644
index 7a5856806e5..00000000000
--- a/contrib/libs/grpc/test/cpp/end2end/test_service_impl.cc
+++ /dev/null
@@ -1,635 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include "test/cpp/end2end/test_service_impl.h"
-
-#include <util/generic/string.h>
-#include <thread>
-
-#include <gtest/gtest.h>
-
-#include <grpc/support/log.h>
-#include <grpcpp/alarm.h>
-#include <grpcpp/security/credentials.h>
-#include <grpcpp/server_context.h>
-
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/cpp/util/string_ref_helper.h"
-
-using std::chrono::system_clock;
-
-namespace grpc {
-namespace testing {
-namespace internal {
-
-// When echo_deadline is requested, deadline seen in the ServerContext is set in
-// the response in seconds.
-void MaybeEchoDeadline(ServerContextBase* context, const EchoRequest* request,
- EchoResponse* response) {
- if (request->has_param() && request->param().echo_deadline()) {
- gpr_timespec deadline = gpr_inf_future(GPR_CLOCK_REALTIME);
- if (context->deadline() != system_clock::time_point::max()) {
- Timepoint2Timespec(context->deadline(), &deadline);
- }
- response->mutable_param()->set_request_deadline(deadline.tv_sec);
- }
-}
-
-void CheckServerAuthContext(const ServerContextBase* context,
- const TString& expected_transport_security_type,
- const TString& expected_client_identity) {
- std::shared_ptr<const AuthContext> auth_ctx = context->auth_context();
- std::vector<grpc::string_ref> tst =
- auth_ctx->FindPropertyValues("transport_security_type");
- EXPECT_EQ(1u, tst.size());
- EXPECT_EQ(expected_transport_security_type.c_str(), ToString(tst[0]));
- if (expected_client_identity.empty()) {
- EXPECT_TRUE(auth_ctx->GetPeerIdentityPropertyName().empty());
- EXPECT_TRUE(auth_ctx->GetPeerIdentity().empty());
- EXPECT_FALSE(auth_ctx->IsPeerAuthenticated());
- } else {
- auto identity = auth_ctx->GetPeerIdentity();
- EXPECT_TRUE(auth_ctx->IsPeerAuthenticated());
- EXPECT_EQ(1u, identity.size());
- EXPECT_EQ(expected_client_identity.c_str(), ToString(identity[0]));
- }
-}
-
-// Returns the number of pairs in metadata that exactly match the given
-// key-value pair. Returns -1 if the pair wasn't found.
-int MetadataMatchCount(
- const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
- const TString& key, const TString& value) {
- int count = 0;
- for (const auto& metadatum : metadata) {
- if (ToString(metadatum.first) == key &&
- ToString(metadatum.second) == value) {
- count++;
- }
- }
- return count;
-}
-
-int GetIntValueFromMetadataHelper(
- const char* key,
- const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
- int default_value) {
- if (metadata.find(key) != metadata.end()) {
- std::istringstream iss(ToString(metadata.find(key)->second));
- iss >> default_value;
- gpr_log(GPR_INFO, "%s : %d", key, default_value);
- }
-
- return default_value;
-}
-
-int GetIntValueFromMetadata(
- const char* key,
- const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
- int default_value) {
- return GetIntValueFromMetadataHelper(key, metadata, default_value);
-}
-
-void ServerTryCancel(ServerContext* context) {
- EXPECT_FALSE(context->IsCancelled());
- context->TryCancel();
- gpr_log(GPR_INFO, "Server called TryCancel() to cancel the request");
- // Now wait until it's really canceled
- while (!context->IsCancelled()) {
- gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
- gpr_time_from_micros(1000, GPR_TIMESPAN)));
- }
-}
-
-void ServerTryCancelNonblocking(CallbackServerContext* context) {
- EXPECT_FALSE(context->IsCancelled());
- context->TryCancel();
- gpr_log(GPR_INFO,
- "Server called TryCancelNonblocking() to cancel the request");
-}
-
-} // namespace internal
-
-ServerUnaryReactor* CallbackTestServiceImpl::Echo(
- CallbackServerContext* context, const EchoRequest* request,
- EchoResponse* response) {
- class Reactor : public ::grpc::ServerUnaryReactor {
- public:
- Reactor(CallbackTestServiceImpl* service, CallbackServerContext* ctx,
- const EchoRequest* request, EchoResponse* response)
- : service_(service), ctx_(ctx), req_(request), resp_(response) {
- // It should be safe to call IsCancelled here, even though we don't know
- // the result. Call it asynchronously to see if we trigger any data races.
- // Join it in OnDone (technically that could be blocking but shouldn't be
- // for very long).
- async_cancel_check_ = std::thread([this] { (void)ctx_->IsCancelled(); });
-
- started_ = true;
-
- if (request->has_param() &&
- request->param().server_notify_client_when_started()) {
- service->signaller_.SignalClientThatRpcStarted();
- // Block on the "wait to continue" decision in a different thread since
- // we can't tie up an EM thread with blocking events. We can join it in
- // OnDone since it would definitely be done by then.
- rpc_wait_thread_ = std::thread([this] {
- service_->signaller_.ServerWaitToContinue();
- StartRpc();
- });
- } else {
- StartRpc();
- }
- }
-
- void StartRpc() {
- if (req_->has_param() && req_->param().server_sleep_us() > 0) {
- // Set an alarm for that much time
- alarm_.Set(
- gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
- gpr_time_from_micros(req_->param().server_sleep_us(),
- GPR_TIMESPAN)),
- [this](bool ok) { NonDelayed(ok); });
- return;
- }
- NonDelayed(true);
- }
- void OnSendInitialMetadataDone(bool ok) override {
- EXPECT_TRUE(ok);
- initial_metadata_sent_ = true;
- }
- void OnCancel() override {
- EXPECT_TRUE(started_);
- EXPECT_TRUE(ctx_->IsCancelled());
- on_cancel_invoked_ = true;
- std::lock_guard<std::mutex> l(cancel_mu_);
- cancel_cv_.notify_one();
- }
- void OnDone() override {
- if (req_->has_param() && req_->param().echo_metadata_initially()) {
- EXPECT_TRUE(initial_metadata_sent_);
- }
- EXPECT_EQ(ctx_->IsCancelled(), on_cancel_invoked_);
- // Validate that finishing with a non-OK status doesn't cause cancellation
- if (req_->has_param() && req_->param().has_expected_error()) {
- EXPECT_FALSE(on_cancel_invoked_);
- }
- async_cancel_check_.join();
- if (rpc_wait_thread_.joinable()) {
- rpc_wait_thread_.join();
- }
- if (finish_when_cancelled_.joinable()) {
- finish_when_cancelled_.join();
- }
- delete this;
- }
-
- private:
- void NonDelayed(bool ok) {
- if (!ok) {
- EXPECT_TRUE(ctx_->IsCancelled());
- Finish(Status::CANCELLED);
- return;
- }
- if (req_->has_param() && req_->param().server_die()) {
- gpr_log(GPR_ERROR, "The request should not reach application handler.");
- GPR_ASSERT(0);
- }
- if (req_->has_param() && req_->param().has_expected_error()) {
- const auto& error = req_->param().expected_error();
- Finish(Status(static_cast<StatusCode>(error.code()),
- error.error_message(), error.binary_error_details()));
- return;
- }
- int server_try_cancel = internal::GetIntValueFromMetadata(
- kServerTryCancelRequest, ctx_->client_metadata(), DO_NOT_CANCEL);
- if (server_try_cancel != DO_NOT_CANCEL) {
- // Since this is a unary RPC, by the time this server handler is called,
- // the 'request' message is already read from the client. So the
- // scenarios in server_try_cancel don't make much sense. Just cancel the
- // RPC as long as server_try_cancel is not DO_NOT_CANCEL
- EXPECT_FALSE(ctx_->IsCancelled());
- ctx_->TryCancel();
- gpr_log(GPR_INFO, "Server called TryCancel() to cancel the request");
- FinishWhenCancelledAsync();
- return;
- }
- resp_->set_message(req_->message());
- internal::MaybeEchoDeadline(ctx_, req_, resp_);
- if (service_->host_) {
- resp_->mutable_param()->set_host(*service_->host_);
- }
- if (req_->has_param() && req_->param().client_cancel_after_us()) {
- {
- std::unique_lock<std::mutex> lock(service_->mu_);
- service_->signal_client_ = true;
- }
- FinishWhenCancelledAsync();
- return;
- } else if (req_->has_param() && req_->param().server_cancel_after_us()) {
- alarm_.Set(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
- gpr_time_from_micros(
- req_->param().server_cancel_after_us(),
- GPR_TIMESPAN)),
- [this](bool) { Finish(Status::CANCELLED); });
- return;
- } else if (!req_->has_param() || !req_->param().skip_cancelled_check()) {
- EXPECT_FALSE(ctx_->IsCancelled());
- }
-
- if (req_->has_param() && req_->param().echo_metadata_initially()) {
- const std::multimap<grpc::string_ref, grpc::string_ref>&
- client_metadata = ctx_->client_metadata();
- for (const auto& metadatum : client_metadata) {
- ctx_->AddInitialMetadata(ToString(metadatum.first),
- ToString(metadatum.second));
- }
- StartSendInitialMetadata();
- }
-
- if (req_->has_param() && req_->param().echo_metadata()) {
- const std::multimap<grpc::string_ref, grpc::string_ref>&
- client_metadata = ctx_->client_metadata();
- for (const auto& metadatum : client_metadata) {
- ctx_->AddTrailingMetadata(ToString(metadatum.first),
- ToString(metadatum.second));
- }
- // Terminate rpc with error and debug info in trailer.
- if (req_->param().debug_info().stack_entries_size() ||
- !req_->param().debug_info().detail().empty()) {
- TString serialized_debug_info =
- req_->param().debug_info().SerializeAsString();
- ctx_->AddTrailingMetadata(kDebugInfoTrailerKey,
- serialized_debug_info);
- Finish(Status::CANCELLED);
- return;
- }
- }
- if (req_->has_param() &&
- (req_->param().expected_client_identity().length() > 0 ||
- req_->param().check_auth_context())) {
- internal::CheckServerAuthContext(
- ctx_, req_->param().expected_transport_security_type(),
- req_->param().expected_client_identity());
- }
- if (req_->has_param() && req_->param().response_message_length() > 0) {
- resp_->set_message(
- TString(req_->param().response_message_length(), '\0'));
- }
- if (req_->has_param() && req_->param().echo_peer()) {
- resp_->mutable_param()->set_peer(ctx_->peer().c_str());
- }
- Finish(Status::OK);
- }
- void FinishWhenCancelledAsync() {
- finish_when_cancelled_ = std::thread([this] {
- std::unique_lock<std::mutex> l(cancel_mu_);
- cancel_cv_.wait(l, [this] { return ctx_->IsCancelled(); });
- Finish(Status::CANCELLED);
- });
- }
-
- CallbackTestServiceImpl* const service_;
- CallbackServerContext* const ctx_;
- const EchoRequest* const req_;
- EchoResponse* const resp_;
- Alarm alarm_;
- std::mutex cancel_mu_;
- std::condition_variable cancel_cv_;
- bool initial_metadata_sent_ = false;
- bool started_ = false;
- bool on_cancel_invoked_ = false;
- std::thread async_cancel_check_;
- std::thread rpc_wait_thread_;
- std::thread finish_when_cancelled_;
- };
-
- return new Reactor(this, context, request, response);
-}
-
-ServerUnaryReactor* CallbackTestServiceImpl::CheckClientInitialMetadata(
- CallbackServerContext* context, const SimpleRequest42*, SimpleResponse42*) {
- class Reactor : public ::grpc::ServerUnaryReactor {
- public:
- explicit Reactor(CallbackServerContext* ctx) {
- EXPECT_EQ(internal::MetadataMatchCount(ctx->client_metadata(),
- kCheckClientInitialMetadataKey,
- kCheckClientInitialMetadataVal),
- 1);
- EXPECT_EQ(ctx->client_metadata().count(kCheckClientInitialMetadataKey),
- 1u);
- Finish(Status::OK);
- }
- void OnDone() override { delete this; }
- };
-
- return new Reactor(context);
-}
-
-ServerReadReactor<EchoRequest>* CallbackTestServiceImpl::RequestStream(
- CallbackServerContext* context, EchoResponse* response) {
- // If 'server_try_cancel' is set in the metadata, the RPC is cancelled by
- // the server by calling ServerContext::TryCancel() depending on the
- // value:
- // CANCEL_BEFORE_PROCESSING: The RPC is cancelled before the server
- // reads any message from the client CANCEL_DURING_PROCESSING: The RPC
- // is cancelled while the server is reading messages from the client
- // CANCEL_AFTER_PROCESSING: The RPC is cancelled after the server reads
- // all the messages from the client
- int server_try_cancel = internal::GetIntValueFromMetadata(
- kServerTryCancelRequest, context->client_metadata(), DO_NOT_CANCEL);
- if (server_try_cancel == CANCEL_BEFORE_PROCESSING) {
- internal::ServerTryCancelNonblocking(context);
- // Don't need to provide a reactor since the RPC is canceled
- return nullptr;
- }
-
- class Reactor : public ::grpc::ServerReadReactor<EchoRequest> {
- public:
- Reactor(CallbackServerContext* ctx, EchoResponse* response,
- int server_try_cancel)
- : ctx_(ctx),
- response_(response),
- server_try_cancel_(server_try_cancel) {
- EXPECT_NE(server_try_cancel, CANCEL_BEFORE_PROCESSING);
- response->set_message("");
-
- if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
- ctx->TryCancel();
- // Don't wait for it here
- }
- StartRead(&request_);
- setup_done_ = true;
- }
- void OnDone() override { delete this; }
- void OnCancel() override {
- EXPECT_TRUE(setup_done_);
- EXPECT_TRUE(ctx_->IsCancelled());
- FinishOnce(Status::CANCELLED);
- }
- void OnReadDone(bool ok) override {
- if (ok) {
- response_->mutable_message()->append(request_.message());
- num_msgs_read_++;
- StartRead(&request_);
- } else {
- gpr_log(GPR_INFO, "Read: %d messages", num_msgs_read_);
-
- if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
- // Let OnCancel recover this
- return;
- }
- if (server_try_cancel_ == CANCEL_AFTER_PROCESSING) {
- internal::ServerTryCancelNonblocking(ctx_);
- return;
- }
- FinishOnce(Status::OK);
- }
- }
-
- private:
- void FinishOnce(const Status& s) {
- std::lock_guard<std::mutex> l(finish_mu_);
- if (!finished_) {
- Finish(s);
- finished_ = true;
- }
- }
-
- CallbackServerContext* const ctx_;
- EchoResponse* const response_;
- EchoRequest request_;
- int num_msgs_read_{0};
- int server_try_cancel_;
- std::mutex finish_mu_;
- bool finished_{false};
- bool setup_done_{false};
- };
-
- return new Reactor(context, response, server_try_cancel);
-}
-
-// Return 'kNumResponseStreamMsgs' messages.
-// TODO(yangg) make it generic by adding a parameter into EchoRequest
-ServerWriteReactor<EchoResponse>* CallbackTestServiceImpl::ResponseStream(
- CallbackServerContext* context, const EchoRequest* request) {
- // If 'server_try_cancel' is set in the metadata, the RPC is cancelled by
- // the server by calling ServerContext::TryCancel() depending on the
- // value:
- // CANCEL_BEFORE_PROCESSING: The RPC is cancelled before the server
- // reads any message from the client CANCEL_DURING_PROCESSING: The RPC
- // is cancelled while the server is reading messages from the client
- // CANCEL_AFTER_PROCESSING: The RPC is cancelled after the server reads
- // all the messages from the client
- int server_try_cancel = internal::GetIntValueFromMetadata(
- kServerTryCancelRequest, context->client_metadata(), DO_NOT_CANCEL);
- if (server_try_cancel == CANCEL_BEFORE_PROCESSING) {
- internal::ServerTryCancelNonblocking(context);
- }
-
- class Reactor : public ::grpc::ServerWriteReactor<EchoResponse> {
- public:
- Reactor(CallbackServerContext* ctx, const EchoRequest* request,
- int server_try_cancel)
- : ctx_(ctx), request_(request), server_try_cancel_(server_try_cancel) {
- server_coalescing_api_ = internal::GetIntValueFromMetadata(
- kServerUseCoalescingApi, ctx->client_metadata(), 0);
- server_responses_to_send_ = internal::GetIntValueFromMetadata(
- kServerResponseStreamsToSend, ctx->client_metadata(),
- kServerDefaultResponseStreamsToSend);
- if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
- ctx->TryCancel();
- }
- if (server_try_cancel_ != CANCEL_BEFORE_PROCESSING) {
- if (num_msgs_sent_ < server_responses_to_send_) {
- NextWrite();
- }
- }
- setup_done_ = true;
- }
- void OnDone() override { delete this; }
- void OnCancel() override {
- EXPECT_TRUE(setup_done_);
- EXPECT_TRUE(ctx_->IsCancelled());
- FinishOnce(Status::CANCELLED);
- }
- void OnWriteDone(bool /*ok*/) override {
- if (num_msgs_sent_ < server_responses_to_send_) {
- NextWrite();
- } else if (server_coalescing_api_ != 0) {
- // We would have already done Finish just after the WriteLast
- } else if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
- // Let OnCancel recover this
- } else if (server_try_cancel_ == CANCEL_AFTER_PROCESSING) {
- internal::ServerTryCancelNonblocking(ctx_);
- } else {
- FinishOnce(Status::OK);
- }
- }
-
- private:
- void FinishOnce(const Status& s) {
- std::lock_guard<std::mutex> l(finish_mu_);
- if (!finished_) {
- Finish(s);
- finished_ = true;
- }
- }
-
- void NextWrite() {
- response_.set_message(request_->message() +
- ::ToString(num_msgs_sent_));
- if (num_msgs_sent_ == server_responses_to_send_ - 1 &&
- server_coalescing_api_ != 0) {
- {
- std::lock_guard<std::mutex> l(finish_mu_);
- if (!finished_) {
- num_msgs_sent_++;
- StartWriteLast(&response_, WriteOptions());
- }
- }
- // If we use WriteLast, we shouldn't wait before attempting Finish
- FinishOnce(Status::OK);
- } else {
- std::lock_guard<std::mutex> l(finish_mu_);
- if (!finished_) {
- num_msgs_sent_++;
- StartWrite(&response_);
- }
- }
- }
- CallbackServerContext* const ctx_;
- const EchoRequest* const request_;
- EchoResponse response_;
- int num_msgs_sent_{0};
- int server_try_cancel_;
- int server_coalescing_api_;
- int server_responses_to_send_;
- std::mutex finish_mu_;
- bool finished_{false};
- bool setup_done_{false};
- };
- return new Reactor(context, request, server_try_cancel);
-}
-
-ServerBidiReactor<EchoRequest, EchoResponse>*
-CallbackTestServiceImpl::BidiStream(CallbackServerContext* context) {
- class Reactor : public ::grpc::ServerBidiReactor<EchoRequest, EchoResponse> {
- public:
- explicit Reactor(CallbackServerContext* ctx) : ctx_(ctx) {
- // If 'server_try_cancel' is set in the metadata, the RPC is cancelled by
- // the server by calling ServerContext::TryCancel() depending on the
- // value:
- // CANCEL_BEFORE_PROCESSING: The RPC is cancelled before the server
- // reads any message from the client CANCEL_DURING_PROCESSING: The RPC
- // is cancelled while the server is reading messages from the client
- // CANCEL_AFTER_PROCESSING: The RPC is cancelled after the server reads
- // all the messages from the client
- server_try_cancel_ = internal::GetIntValueFromMetadata(
- kServerTryCancelRequest, ctx->client_metadata(), DO_NOT_CANCEL);
- server_write_last_ = internal::GetIntValueFromMetadata(
- kServerFinishAfterNReads, ctx->client_metadata(), 0);
- client_try_cancel_ = static_cast<bool>(internal::GetIntValueFromMetadata(
- kClientTryCancelRequest, ctx->client_metadata(), 0));
- if (server_try_cancel_ == CANCEL_BEFORE_PROCESSING) {
- internal::ServerTryCancelNonblocking(ctx);
- } else {
- if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
- ctx->TryCancel();
- }
- StartRead(&request_);
- }
- setup_done_ = true;
- }
- void OnDone() override {
- {
- // Use the same lock as finish to make sure that OnDone isn't inlined.
- std::lock_guard<std::mutex> l(finish_mu_);
- EXPECT_TRUE(finished_);
- finish_thread_.join();
- }
- delete this;
- }
- void OnCancel() override {
- EXPECT_TRUE(setup_done_);
- EXPECT_TRUE(ctx_->IsCancelled());
- FinishOnce(Status::CANCELLED);
- }
- void OnReadDone(bool ok) override {
- if (ok) {
- num_msgs_read_++;
- response_.set_message(request_.message());
- std::lock_guard<std::mutex> l(finish_mu_);
- if (!finished_) {
- if (num_msgs_read_ == server_write_last_) {
- StartWriteLast(&response_, WriteOptions());
- // If we use WriteLast, we shouldn't wait before attempting Finish
- } else {
- StartWrite(&response_);
- return;
- }
- }
- } else if (client_try_cancel_) {
- EXPECT_TRUE(ctx_->IsCancelled());
- }
-
- if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
- // Let OnCancel handle this
- } else if (server_try_cancel_ == CANCEL_AFTER_PROCESSING) {
- internal::ServerTryCancelNonblocking(ctx_);
- } else {
- FinishOnce(Status::OK);
- }
- }
- void OnWriteDone(bool /*ok*/) override {
- std::lock_guard<std::mutex> l(finish_mu_);
- if (!finished_) {
- StartRead(&request_);
- }
- }
-
- private:
- void FinishOnce(const Status& s) {
- std::lock_guard<std::mutex> l(finish_mu_);
- if (!finished_) {
- finished_ = true;
- // Finish asynchronously to make sure that there are no deadlocks.
- finish_thread_ = std::thread([this, s] {
- std::lock_guard<std::mutex> l(finish_mu_);
- Finish(s);
- });
- }
- }
-
- CallbackServerContext* const ctx_;
- EchoRequest request_;
- EchoResponse response_;
- int num_msgs_read_{0};
- int server_try_cancel_;
- int server_write_last_;
- std::mutex finish_mu_;
- bool finished_{false};
- bool setup_done_{false};
- std::thread finish_thread_;
- bool client_try_cancel_ = false;
- };
-
- return new Reactor(context);
-}
-
-} // namespace testing
-} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/end2end/test_service_impl.h b/contrib/libs/grpc/test/cpp/end2end/test_service_impl.h
deleted file mode 100644
index 9983b70ac41..00000000000
--- a/contrib/libs/grpc/test/cpp/end2end/test_service_impl.h
+++ /dev/null
@@ -1,500 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CPP_END2END_TEST_SERVICE_IMPL_H
-#define GRPC_TEST_CPP_END2END_TEST_SERVICE_IMPL_H
-
-#include <condition_variable>
-#include <memory>
-#include <mutex>
-#include <util/generic/string.h>
-#include <thread>
-
-#include <gtest/gtest.h>
-
-#include <grpc/grpc.h>
-#include <grpc/support/log.h>
-#include <grpcpp/alarm.h>
-#include <grpcpp/security/credentials.h>
-#include <grpcpp/server_context.h>
-
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/cpp/util/string_ref_helper.h"
-
-#include <util/string/cast.h>
-
-namespace grpc {
-namespace testing {
-
-const int kServerDefaultResponseStreamsToSend = 3;
-const char* const kServerResponseStreamsToSend = "server_responses_to_send";
-const char* const kServerTryCancelRequest = "server_try_cancel";
-const char* const kClientTryCancelRequest = "client_try_cancel";
-const char* const kDebugInfoTrailerKey = "debug-info-bin";
-const char* const kServerFinishAfterNReads = "server_finish_after_n_reads";
-const char* const kServerUseCoalescingApi = "server_use_coalescing_api";
-const char* const kCheckClientInitialMetadataKey = "custom_client_metadata";
-const char* const kCheckClientInitialMetadataVal = "Value for client metadata";
-
-typedef enum {
- DO_NOT_CANCEL = 0,
- CANCEL_BEFORE_PROCESSING,
- CANCEL_DURING_PROCESSING,
- CANCEL_AFTER_PROCESSING
-} ServerTryCancelRequestPhase;
-
-namespace internal {
-// When echo_deadline is requested, deadline seen in the ServerContext is set in
-// the response in seconds.
-void MaybeEchoDeadline(ServerContextBase* context, const EchoRequest* request,
- EchoResponse* response);
-
-void CheckServerAuthContext(const ServerContextBase* context,
- const TString& expected_transport_security_type,
- const TString& expected_client_identity);
-
-// Returns the number of pairs in metadata that exactly match the given
-// key-value pair. Returns -1 if the pair wasn't found.
-int MetadataMatchCount(
- const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
- const TString& key, const TString& value);
-
-int GetIntValueFromMetadataHelper(
- const char* key,
- const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
- int default_value);
-
-int GetIntValueFromMetadata(
- const char* key,
- const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
- int default_value);
-
-void ServerTryCancel(ServerContext* context);
-} // namespace internal
-
-class TestServiceSignaller {
- public:
- void ClientWaitUntilRpcStarted() {
- std::unique_lock<std::mutex> lock(mu_);
- cv_rpc_started_.wait(lock, [this] { return rpc_started_; });
- }
- void ServerWaitToContinue() {
- std::unique_lock<std::mutex> lock(mu_);
- cv_server_continue_.wait(lock, [this] { return server_should_continue_; });
- }
- void SignalClientThatRpcStarted() {
- std::unique_lock<std::mutex> lock(mu_);
- rpc_started_ = true;
- cv_rpc_started_.notify_one();
- }
- void SignalServerToContinue() {
- std::unique_lock<std::mutex> lock(mu_);
- server_should_continue_ = true;
- cv_server_continue_.notify_one();
- }
-
- private:
- std::mutex mu_;
- std::condition_variable cv_rpc_started_;
- bool rpc_started_ /* GUARDED_BY(mu_) */ = false;
- std::condition_variable cv_server_continue_;
- bool server_should_continue_ /* GUARDED_BY(mu_) */ = false;
-};
-
-template <typename RpcService>
-class TestMultipleServiceImpl : public RpcService {
- public:
- TestMultipleServiceImpl() : signal_client_(false), host_() {}
- explicit TestMultipleServiceImpl(const TString& host)
- : signal_client_(false), host_(new TString(host)) {}
-
- Status Echo(ServerContext* context, const EchoRequest* request,
- EchoResponse* response) {
- if (request->has_param() &&
- request->param().server_notify_client_when_started()) {
- signaller_.SignalClientThatRpcStarted();
- signaller_.ServerWaitToContinue();
- }
-
- // A bit of sleep to make sure that short deadline tests fail
- if (request->has_param() && request->param().server_sleep_us() > 0) {
- gpr_sleep_until(
- gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
- gpr_time_from_micros(request->param().server_sleep_us(),
- GPR_TIMESPAN)));
- }
-
- if (request->has_param() && request->param().server_die()) {
- gpr_log(GPR_ERROR, "The request should not reach application handler.");
- GPR_ASSERT(0);
- }
- if (request->has_param() && request->param().has_expected_error()) {
- const auto& error = request->param().expected_error();
- return Status(static_cast<StatusCode>(error.code()),
- error.error_message(), error.binary_error_details());
- }
- int server_try_cancel = internal::GetIntValueFromMetadata(
- kServerTryCancelRequest, context->client_metadata(), DO_NOT_CANCEL);
- if (server_try_cancel > DO_NOT_CANCEL) {
- // Since this is a unary RPC, by the time this server handler is called,
- // the 'request' message is already read from the client. So the scenarios
- // in server_try_cancel don't make much sense. Just cancel the RPC as long
- // as server_try_cancel is not DO_NOT_CANCEL
- internal::ServerTryCancel(context);
- return Status::CANCELLED;
- }
-
- response->set_message(request->message());
- internal::MaybeEchoDeadline(context, request, response);
- if (host_) {
- response->mutable_param()->set_host(*host_);
- }
- if (request->has_param() && request->param().client_cancel_after_us()) {
- {
- std::unique_lock<std::mutex> lock(mu_);
- signal_client_ = true;
- ++rpcs_waiting_for_client_cancel_;
- }
- while (!context->IsCancelled()) {
- gpr_sleep_until(gpr_time_add(
- gpr_now(GPR_CLOCK_REALTIME),
- gpr_time_from_micros(request->param().client_cancel_after_us(),
- GPR_TIMESPAN)));
- }
- {
- std::unique_lock<std::mutex> lock(mu_);
- --rpcs_waiting_for_client_cancel_;
- }
- return Status::CANCELLED;
- } else if (request->has_param() &&
- request->param().server_cancel_after_us()) {
- gpr_sleep_until(gpr_time_add(
- gpr_now(GPR_CLOCK_REALTIME),
- gpr_time_from_micros(request->param().server_cancel_after_us(),
- GPR_TIMESPAN)));
- return Status::CANCELLED;
- } else if (!request->has_param() ||
- !request->param().skip_cancelled_check()) {
- EXPECT_FALSE(context->IsCancelled());
- }
-
- if (request->has_param() && request->param().echo_metadata_initially()) {
- const std::multimap<grpc::string_ref, grpc::string_ref>& client_metadata =
- context->client_metadata();
- for (const auto& metadatum : client_metadata) {
- context->AddInitialMetadata(::ToString(metadatum.first),
- ::ToString(metadatum.second));
- }
- }
-
- if (request->has_param() && request->param().echo_metadata()) {
- const std::multimap<grpc::string_ref, grpc::string_ref>& client_metadata =
- context->client_metadata();
- for (const auto& metadatum : client_metadata) {
- context->AddTrailingMetadata(::ToString(metadatum.first),
- ::ToString(metadatum.second));
- }
- // Terminate rpc with error and debug info in trailer.
- if (request->param().debug_info().stack_entries_size() ||
- !request->param().debug_info().detail().empty()) {
- TString serialized_debug_info =
- request->param().debug_info().SerializeAsString();
- context->AddTrailingMetadata(kDebugInfoTrailerKey,
- serialized_debug_info);
- return Status::CANCELLED;
- }
- }
- if (request->has_param() &&
- (request->param().expected_client_identity().length() > 0 ||
- request->param().check_auth_context())) {
- internal::CheckServerAuthContext(
- context, request->param().expected_transport_security_type(),
- request->param().expected_client_identity());
- }
- if (request->has_param() &&
- request->param().response_message_length() > 0) {
- response->set_message(
- TString(request->param().response_message_length(), '\0'));
- }
- if (request->has_param() && request->param().echo_peer()) {
- response->mutable_param()->set_peer(context->peer());
- }
- return Status::OK;
- }
-
- Status Echo1(ServerContext* context, const EchoRequest* request,
- EchoResponse* response) {
- return Echo(context, request, response);
- }
-
- Status Echo2(ServerContext* context, const EchoRequest* request,
- EchoResponse* response) {
- return Echo(context, request, response);
- }
-
- Status CheckClientInitialMetadata(ServerContext* context,
- const SimpleRequest42* /*request*/,
- SimpleResponse42* /*response*/) {
- EXPECT_EQ(internal::MetadataMatchCount(context->client_metadata(),
- kCheckClientInitialMetadataKey,
- kCheckClientInitialMetadataVal),
- 1);
- EXPECT_EQ(1u,
- context->client_metadata().count(kCheckClientInitialMetadataKey));
- return Status::OK;
- }
-
- // Unimplemented is left unimplemented to test the returned error.
-
- Status RequestStream(ServerContext* context,
- ServerReader<EchoRequest>* reader,
- EchoResponse* response) {
- // If 'server_try_cancel' is set in the metadata, the RPC is cancelled by
- // the server by calling ServerContext::TryCancel() depending on the value:
- // CANCEL_BEFORE_PROCESSING: The RPC is cancelled before the server reads
- // any message from the client
- // CANCEL_DURING_PROCESSING: The RPC is cancelled while the server is
- // reading messages from the client
- // CANCEL_AFTER_PROCESSING: The RPC is cancelled after the server reads
- // all the messages from the client
- int server_try_cancel = internal::GetIntValueFromMetadata(
- kServerTryCancelRequest, context->client_metadata(), DO_NOT_CANCEL);
-
- EchoRequest request;
- response->set_message("");
-
- if (server_try_cancel == CANCEL_BEFORE_PROCESSING) {
- internal::ServerTryCancel(context);
- return Status::CANCELLED;
- }
-
- std::thread* server_try_cancel_thd = nullptr;
- if (server_try_cancel == CANCEL_DURING_PROCESSING) {
- server_try_cancel_thd =
- new std::thread([context] { internal::ServerTryCancel(context); });
- }
-
- int num_msgs_read = 0;
- while (reader->Read(&request)) {
- response->mutable_message()->append(request.message());
- }
- gpr_log(GPR_INFO, "Read: %d messages", num_msgs_read);
-
- if (server_try_cancel_thd != nullptr) {
- server_try_cancel_thd->join();
- delete server_try_cancel_thd;
- return Status::CANCELLED;
- }
-
- if (server_try_cancel == CANCEL_AFTER_PROCESSING) {
- internal::ServerTryCancel(context);
- return Status::CANCELLED;
- }
-
- return Status::OK;
- }
-
- // Return 'kNumResponseStreamMsgs' messages.
- // TODO(yangg) make it generic by adding a parameter into EchoRequest
- Status ResponseStream(ServerContext* context, const EchoRequest* request,
- ServerWriter<EchoResponse>* writer) {
- // If server_try_cancel is set in the metadata, the RPC is cancelled by the
- // server by calling ServerContext::TryCancel() depending on the value:
- // CANCEL_BEFORE_PROCESSING: The RPC is cancelled before the server writes
- // any messages to the client
- // CANCEL_DURING_PROCESSING: The RPC is cancelled while the server is
- // writing messages to the client
- // CANCEL_AFTER_PROCESSING: The RPC is cancelled after the server writes
- // all the messages to the client
- int server_try_cancel = internal::GetIntValueFromMetadata(
- kServerTryCancelRequest, context->client_metadata(), DO_NOT_CANCEL);
-
- int server_coalescing_api = internal::GetIntValueFromMetadata(
- kServerUseCoalescingApi, context->client_metadata(), 0);
-
- int server_responses_to_send = internal::GetIntValueFromMetadata(
- kServerResponseStreamsToSend, context->client_metadata(),
- kServerDefaultResponseStreamsToSend);
-
- if (server_try_cancel == CANCEL_BEFORE_PROCESSING) {
- internal::ServerTryCancel(context);
- return Status::CANCELLED;
- }
-
- EchoResponse response;
- std::thread* server_try_cancel_thd = nullptr;
- if (server_try_cancel == CANCEL_DURING_PROCESSING) {
- server_try_cancel_thd =
- new std::thread([context] { internal::ServerTryCancel(context); });
- }
-
- for (int i = 0; i < server_responses_to_send; i++) {
- response.set_message(request->message() + ::ToString(i));
- if (i == server_responses_to_send - 1 && server_coalescing_api != 0) {
- writer->WriteLast(response, WriteOptions());
- } else {
- writer->Write(response);
- }
- }
-
- if (server_try_cancel_thd != nullptr) {
- server_try_cancel_thd->join();
- delete server_try_cancel_thd;
- return Status::CANCELLED;
- }
-
- if (server_try_cancel == CANCEL_AFTER_PROCESSING) {
- internal::ServerTryCancel(context);
- return Status::CANCELLED;
- }
-
- return Status::OK;
- }
-
- Status BidiStream(ServerContext* context,
- ServerReaderWriter<EchoResponse, EchoRequest>* stream) {
- // If server_try_cancel is set in the metadata, the RPC is cancelled by the
- // server by calling ServerContext::TryCancel() depending on the value:
- // CANCEL_BEFORE_PROCESSING: The RPC is cancelled before the server reads/
- // writes any messages from/to the client
- // CANCEL_DURING_PROCESSING: The RPC is cancelled while the server is
- // reading/writing messages from/to the client
- // CANCEL_AFTER_PROCESSING: The RPC is cancelled after the server
- // reads/writes all messages from/to the client
- int server_try_cancel = internal::GetIntValueFromMetadata(
- kServerTryCancelRequest, context->client_metadata(), DO_NOT_CANCEL);
-
- int client_try_cancel = static_cast<bool>(internal::GetIntValueFromMetadata(
- kClientTryCancelRequest, context->client_metadata(), 0));
-
- EchoRequest request;
- EchoResponse response;
-
- if (server_try_cancel == CANCEL_BEFORE_PROCESSING) {
- internal::ServerTryCancel(context);
- return Status::CANCELLED;
- }
-
- std::thread* server_try_cancel_thd = nullptr;
- if (server_try_cancel == CANCEL_DURING_PROCESSING) {
- server_try_cancel_thd =
- new std::thread([context] { internal::ServerTryCancel(context); });
- }
-
- // kServerFinishAfterNReads suggests after how many reads, the server should
- // write the last message and send status (coalesced using WriteLast)
- int server_write_last = internal::GetIntValueFromMetadata(
- kServerFinishAfterNReads, context->client_metadata(), 0);
-
- int read_counts = 0;
- while (stream->Read(&request)) {
- read_counts++;
- gpr_log(GPR_INFO, "recv msg %s", request.message().c_str());
- response.set_message(request.message());
- if (read_counts == server_write_last) {
- stream->WriteLast(response, WriteOptions());
- break;
- } else {
- stream->Write(response);
- }
- }
-
- if (client_try_cancel) {
- EXPECT_TRUE(context->IsCancelled());
- }
-
- if (server_try_cancel_thd != nullptr) {
- server_try_cancel_thd->join();
- delete server_try_cancel_thd;
- return Status::CANCELLED;
- }
-
- if (server_try_cancel == CANCEL_AFTER_PROCESSING) {
- internal::ServerTryCancel(context);
- return Status::CANCELLED;
- }
-
- return Status::OK;
- }
-
- // Unimplemented is left unimplemented to test the returned error.
- bool signal_client() {
- std::unique_lock<std::mutex> lock(mu_);
- return signal_client_;
- }
- void ClientWaitUntilRpcStarted() { signaller_.ClientWaitUntilRpcStarted(); }
- void SignalServerToContinue() { signaller_.SignalServerToContinue(); }
- uint64_t RpcsWaitingForClientCancel() {
- std::unique_lock<std::mutex> lock(mu_);
- return rpcs_waiting_for_client_cancel_;
- }
-
- private:
- bool signal_client_;
- std::mutex mu_;
- TestServiceSignaller signaller_;
- std::unique_ptr<TString> host_;
- uint64_t rpcs_waiting_for_client_cancel_ = 0;
-};
-
-class CallbackTestServiceImpl
- : public ::grpc::testing::EchoTestService::CallbackService {
- public:
- CallbackTestServiceImpl() : signal_client_(false), host_() {}
- explicit CallbackTestServiceImpl(const TString& host)
- : signal_client_(false), host_(new TString(host)) {}
-
- ServerUnaryReactor* Echo(CallbackServerContext* context,
- const EchoRequest* request,
- EchoResponse* response) override;
-
- ServerUnaryReactor* CheckClientInitialMetadata(CallbackServerContext* context,
- const SimpleRequest42*,
- SimpleResponse42*) override;
-
- ServerReadReactor<EchoRequest>* RequestStream(
- CallbackServerContext* context, EchoResponse* response) override;
-
- ServerWriteReactor<EchoResponse>* ResponseStream(
- CallbackServerContext* context, const EchoRequest* request) override;
-
- ServerBidiReactor<EchoRequest, EchoResponse>* BidiStream(
- CallbackServerContext* context) override;
-
- // Unimplemented is left unimplemented to test the returned error.
- bool signal_client() {
- std::unique_lock<std::mutex> lock(mu_);
- return signal_client_;
- }
- void ClientWaitUntilRpcStarted() { signaller_.ClientWaitUntilRpcStarted(); }
- void SignalServerToContinue() { signaller_.SignalServerToContinue(); }
-
- private:
- bool signal_client_;
- std::mutex mu_;
- TestServiceSignaller signaller_;
- std::unique_ptr<TString> host_;
-};
-
-using TestServiceImpl =
- TestMultipleServiceImpl<::grpc::testing::EchoTestService::Service>;
-
-} // namespace testing
-} // namespace grpc
-
-#endif // GRPC_TEST_CPP_END2END_TEST_SERVICE_IMPL_H
diff --git a/contrib/libs/grpc/test/cpp/end2end/ya.make b/contrib/libs/grpc/test/cpp/end2end/ya.make
deleted file mode 100644
index 409a5fa720c..00000000000
--- a/contrib/libs/grpc/test/cpp/end2end/ya.make
+++ /dev/null
@@ -1,65 +0,0 @@
-LIBRARY()
-
-LICENSE(Apache-2.0)
-
-LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-
-PEERDIR(
- contrib/libs/grpc/src/proto/grpc/health/v1
- contrib/libs/grpc/src/proto/grpc/testing
- contrib/libs/grpc/src/proto/grpc/testing/duplicate
- contrib/libs/grpc/test/cpp/util
- contrib/libs/grpc
- contrib/restricted/googletest/googlemock
- contrib/restricted/googletest/googletest
-)
-
-ADDINCL(
- ${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
- contrib/libs/grpc
-)
-
-NO_COMPILER_WARNINGS()
-
-SRCS(
- # async_end2end_test.cc
- # channelz_service_test.cc
- # client_callback_end2end_test.cc
- # client_crash_test.cc
- # client_crash_test_server.cc
- # client_interceptors_end2end_test.cc
- # client_lb_end2end_test.cc lb needs opencensus, not enabled.
- # end2end_test.cc
- # exception_test.cc
- # filter_end2end_test.cc
- # generic_end2end_test.cc
- # grpclb_end2end_test.cc lb needs opencensus, not enabled.
- # health_service_end2end_test.cc
- # hybrid_end2end_test.cc
- interceptors_util.cc
- # mock_test.cc
- # nonblocking_test.cc
- # proto_server_reflection_test.cc
- # raw_end2end_test.cc
- # server_builder_plugin_test.cc
- # server_crash_test.cc
- # server_crash_test_client.cc
- # server_early_return_test.cc
- # server_interceptors_end2end_test.cc
- # server_load_reporting_end2end_test.cc
- # shutdown_test.cc
- # streaming_throughput_test.cc
- test_health_check_service_impl.cc
- test_service_impl.cc
- # thread_stress_test.cc
- # time_change_test.cc
-)
-
-END()
-
-RECURSE_FOR_TESTS(
- health
- server_interceptors
- # Needs new gtest
- # thread
-)
diff --git a/contrib/libs/grpc/test/cpp/util/byte_buffer_proto_helper.cc b/contrib/libs/grpc/test/cpp/util/byte_buffer_proto_helper.cc
deleted file mode 100644
index 4ddbf701ba6..00000000000
--- a/contrib/libs/grpc/test/cpp/util/byte_buffer_proto_helper.cc
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include "test/cpp/util/byte_buffer_proto_helper.h"
-
-#include "y_absl/memory/memory.h"
-
-namespace grpc {
-namespace testing {
-
-bool ParseFromByteBuffer(ByteBuffer* buffer, grpc::protobuf::Message* message) {
- std::vector<Slice> slices;
- (void)buffer->Dump(&slices);
- TString buf;
- buf.reserve(buffer->Length());
- for (auto s = slices.begin(); s != slices.end(); s++) {
- buf.append(reinterpret_cast<const char*>(s->begin()), s->size());
- }
- return message->ParseFromString(buf);
-}
-
-std::unique_ptr<ByteBuffer> SerializeToByteBuffer(
- grpc::protobuf::Message* message) {
- TString buf;
- message->SerializeToString(&buf);
- Slice slice(buf);
- return y_absl::make_unique<ByteBuffer>(&slice, 1);
-}
-
-bool SerializeToByteBufferInPlace(grpc::protobuf::Message* message,
- ByteBuffer* buffer) {
- TString buf;
- if (!message->SerializeToString(&buf)) {
- return false;
- }
- buffer->Clear();
- Slice slice(buf);
- ByteBuffer tmp(&slice, 1);
- buffer->Swap(&tmp);
- return true;
-}
-
-} // namespace testing
-} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/util/byte_buffer_proto_helper.h b/contrib/libs/grpc/test/cpp/util/byte_buffer_proto_helper.h
deleted file mode 100644
index 3d01fb24686..00000000000
--- a/contrib/libs/grpc/test/cpp/util/byte_buffer_proto_helper.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CPP_UTIL_BYTE_BUFFER_PROTO_HELPER_H
-#define GRPC_TEST_CPP_UTIL_BYTE_BUFFER_PROTO_HELPER_H
-
-#include <memory>
-
-#include <grpcpp/impl/codegen/config_protobuf.h>
-#include <grpcpp/support/byte_buffer.h>
-
-namespace grpc {
-namespace testing {
-
-bool ParseFromByteBuffer(ByteBuffer* buffer,
- ::grpc::protobuf::Message* message);
-
-std::unique_ptr<ByteBuffer> SerializeToByteBuffer(
- ::grpc::protobuf::Message* message);
-
-bool SerializeToByteBufferInPlace(::grpc::protobuf::Message* message,
- ByteBuffer* buffer);
-
-} // namespace testing
-} // namespace grpc
-
-#endif // GRPC_TEST_CPP_UTIL_BYTE_BUFFER_PROTO_HELPER_H
diff --git a/contrib/libs/grpc/test/cpp/util/cli_call.cc b/contrib/libs/grpc/test/cpp/util/cli_call.cc
deleted file mode 100644
index 575cc00c36f..00000000000
--- a/contrib/libs/grpc/test/cpp/util/cli_call.cc
+++ /dev/null
@@ -1,225 +0,0 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include "test/cpp/util/cli_call.h"
-
-#include <cmath>
-#include <iostream>
-#include <utility>
-
-#include <grpc/grpc.h>
-#include <grpc/slice.h>
-#include <grpc/support/log.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/support/byte_buffer.h>
-
-namespace grpc {
-namespace testing {
-namespace {
-void* tag(intptr_t t) { return reinterpret_cast<void*>(t); }
-} // namespace
-
-Status CliCall::Call(const TString& request, TString* response,
- IncomingMetadataContainer* server_initial_metadata,
- IncomingMetadataContainer* server_trailing_metadata) {
- Write(request);
- WritesDone();
- if (!Read(response, server_initial_metadata)) {
- fprintf(stderr, "Failed to read response.\n");
- }
- return Finish(server_trailing_metadata);
-}
-
-CliCall::CliCall(const std::shared_ptr<grpc::Channel>& channel,
- const TString& method,
- const OutgoingMetadataContainer& metadata, CliArgs args)
- : stub_(new grpc::GenericStub(channel)) {
- gpr_mu_init(&write_mu_);
- gpr_cv_init(&write_cv_);
- if (!metadata.empty()) {
- for (OutgoingMetadataContainer::const_iterator iter = metadata.begin();
- iter != metadata.end(); ++iter) {
- ctx_.AddMetadata(iter->first, iter->second);
- }
- }
-
- // Set deadline if timeout > 0 (default value -1 if no timeout specified)
- if (args.timeout > 0) {
- int64_t timeout_in_ns = ceil(args.timeout * 1e9);
-
- // Convert timeout (in nanoseconds) to a deadline
- auto deadline =
- gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
- gpr_time_from_nanos(timeout_in_ns, GPR_TIMESPAN));
- ctx_.set_deadline(deadline);
- } else if (args.timeout != -1) {
- fprintf(
- stderr,
- "WARNING: Non-positive timeout value, skipping setting deadline.\n");
- }
-
- call_ = stub_->PrepareCall(&ctx_, method, &cq_);
- call_->StartCall(tag(1));
- void* got_tag;
- bool ok;
- cq_.Next(&got_tag, &ok);
- GPR_ASSERT(ok);
-}
-
-CliCall::~CliCall() {
- gpr_cv_destroy(&write_cv_);
- gpr_mu_destroy(&write_mu_);
-}
-
-void CliCall::Write(const TString& request) {
- void* got_tag;
- bool ok;
-
- gpr_slice s = gpr_slice_from_copied_buffer(request.data(), request.size());
- grpc::Slice req_slice(s, grpc::Slice::STEAL_REF);
- grpc::ByteBuffer send_buffer(&req_slice, 1);
- call_->Write(send_buffer, tag(2));
- cq_.Next(&got_tag, &ok);
- GPR_ASSERT(ok);
-}
-
-bool CliCall::Read(TString* response,
- IncomingMetadataContainer* server_initial_metadata) {
- void* got_tag;
- bool ok;
-
- grpc::ByteBuffer recv_buffer;
- call_->Read(&recv_buffer, tag(3));
-
- if (!cq_.Next(&got_tag, &ok) || !ok) {
- return false;
- }
- std::vector<grpc::Slice> slices;
- GPR_ASSERT(recv_buffer.Dump(&slices).ok());
-
- response->clear();
- for (size_t i = 0; i < slices.size(); i++) {
- response->append(reinterpret_cast<const char*>(slices[i].begin()),
- slices[i].size());
- }
- if (server_initial_metadata) {
- *server_initial_metadata = ctx_.GetServerInitialMetadata();
- }
- return true;
-}
-
-void CliCall::WritesDone() {
- void* got_tag;
- bool ok;
-
- call_->WritesDone(tag(4));
- cq_.Next(&got_tag, &ok);
- GPR_ASSERT(ok);
-}
-
-void CliCall::WriteAndWait(const TString& request) {
- grpc::Slice req_slice(request);
- grpc::ByteBuffer send_buffer(&req_slice, 1);
-
- gpr_mu_lock(&write_mu_);
- call_->Write(send_buffer, tag(2));
- write_done_ = false;
- while (!write_done_) {
- gpr_cv_wait(&write_cv_, &write_mu_, gpr_inf_future(GPR_CLOCK_MONOTONIC));
- }
- gpr_mu_unlock(&write_mu_);
-}
-
-void CliCall::WritesDoneAndWait() {
- gpr_mu_lock(&write_mu_);
- call_->WritesDone(tag(4));
- write_done_ = false;
- while (!write_done_) {
- gpr_cv_wait(&write_cv_, &write_mu_, gpr_inf_future(GPR_CLOCK_MONOTONIC));
- }
- gpr_mu_unlock(&write_mu_);
-}
-
-bool CliCall::ReadAndMaybeNotifyWrite(
- TString* response, IncomingMetadataContainer* server_initial_metadata) {
- void* got_tag;
- bool ok;
- grpc::ByteBuffer recv_buffer;
-
- call_->Read(&recv_buffer, tag(3));
- bool cq_result = cq_.Next(&got_tag, &ok);
-
- while (got_tag != tag(3)) {
- gpr_mu_lock(&write_mu_);
- write_done_ = true;
- gpr_cv_signal(&write_cv_);
- gpr_mu_unlock(&write_mu_);
-
- cq_result = cq_.Next(&got_tag, &ok);
- if (got_tag == tag(2)) {
- GPR_ASSERT(ok);
- }
- }
-
- if (!cq_result || !ok) {
- // If the RPC is ended on the server side, we should still wait for the
- // pending write on the client side to be done.
- if (!ok) {
- gpr_mu_lock(&write_mu_);
- if (!write_done_) {
- cq_.Next(&got_tag, &ok);
- GPR_ASSERT(got_tag != tag(2));
- write_done_ = true;
- gpr_cv_signal(&write_cv_);
- }
- gpr_mu_unlock(&write_mu_);
- }
- return false;
- }
-
- std::vector<grpc::Slice> slices;
- GPR_ASSERT(recv_buffer.Dump(&slices).ok());
- response->clear();
- for (size_t i = 0; i < slices.size(); i++) {
- response->append(reinterpret_cast<const char*>(slices[i].begin()),
- slices[i].size());
- }
- if (server_initial_metadata) {
- *server_initial_metadata = ctx_.GetServerInitialMetadata();
- }
- return true;
-}
-
-Status CliCall::Finish(IncomingMetadataContainer* server_trailing_metadata) {
- void* got_tag;
- bool ok;
- grpc::Status status;
-
- call_->Finish(&status, tag(5));
- cq_.Next(&got_tag, &ok);
- GPR_ASSERT(ok);
- if (server_trailing_metadata) {
- *server_trailing_metadata = ctx_.GetServerTrailingMetadata();
- }
-
- return status;
-}
-
-} // namespace testing
-} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/util/cli_call.h b/contrib/libs/grpc/test/cpp/util/cli_call.h
deleted file mode 100644
index 330c752f430..00000000000
--- a/contrib/libs/grpc/test/cpp/util/cli_call.h
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CPP_UTIL_CLI_CALL_H
-#define GRPC_TEST_CPP_UTIL_CLI_CALL_H
-
-#include <map>
-
-#include <grpcpp/channel.h>
-#include <grpcpp/completion_queue.h>
-#include <grpcpp/generic/generic_stub.h>
-#include <grpcpp/support/status.h>
-#include <grpcpp/support/string_ref.h>
-
-namespace grpc {
-
-class ClientContext;
-
-struct CliArgs {
- double timeout = -1;
-};
-
-namespace testing {
-
-// CliCall handles the sending and receiving of generic messages given the name
-// of the remote method. This class is only used by GrpcTool. Its thread-safe
-// and thread-unsafe methods should not be used together.
-class CliCall final {
- public:
- typedef std::multimap<TString, TString> OutgoingMetadataContainer;
- typedef std::multimap<grpc::string_ref, grpc::string_ref>
- IncomingMetadataContainer;
-
- CliCall(const std::shared_ptr<grpc::Channel>& channel,
- const TString& method, const OutgoingMetadataContainer& metadata,
- CliArgs args);
- CliCall(const std::shared_ptr<grpc::Channel>& channel,
- const TString& method, const OutgoingMetadataContainer& metadata)
- : CliCall(channel, method, metadata, CliArgs{}) {}
-
- ~CliCall();
-
- // Perform an unary generic RPC.
- Status Call(const TString& request, TString* response,
- IncomingMetadataContainer* server_initial_metadata,
- IncomingMetadataContainer* server_trailing_metadata);
-
- // Send a generic request message in a synchronous manner. NOT thread-safe.
- void Write(const TString& request);
-
- // Send a generic request message in a synchronous manner. NOT thread-safe.
- void WritesDone();
-
- // Receive a generic response message in a synchronous manner.NOT thread-safe.
- bool Read(TString* response,
- IncomingMetadataContainer* server_initial_metadata);
-
- // Thread-safe write. Must be used with ReadAndMaybeNotifyWrite. Send out a
- // generic request message and wait for ReadAndMaybeNotifyWrite to finish it.
- void WriteAndWait(const TString& request);
-
- // Thread-safe WritesDone. Must be used with ReadAndMaybeNotifyWrite. Send out
- // WritesDone for gereneric request messages and wait for
- // ReadAndMaybeNotifyWrite to finish it.
- void WritesDoneAndWait();
-
- // Thread-safe Read. Blockingly receive a generic response message. Notify
- // writes if they are finished when this read is waiting for a resposne.
- bool ReadAndMaybeNotifyWrite(
- TString* response,
- IncomingMetadataContainer* server_initial_metadata);
-
- // Finish the RPC.
- Status Finish(IncomingMetadataContainer* server_trailing_metadata);
-
- TString peer() const { return ctx_.peer(); }
-
- private:
- std::unique_ptr<grpc::GenericStub> stub_;
- grpc::ClientContext ctx_;
- std::unique_ptr<grpc::GenericClientAsyncReaderWriter> call_;
- grpc::CompletionQueue cq_;
- gpr_mu write_mu_;
- gpr_cv write_cv_; // Protected by write_mu_;
- bool write_done_; // Portected by write_mu_;
-};
-
-} // namespace testing
-} // namespace grpc
-
-#endif // GRPC_TEST_CPP_UTIL_CLI_CALL_H
diff --git a/contrib/libs/grpc/test/cpp/util/cli_credentials.cc b/contrib/libs/grpc/test/cpp/util/cli_credentials.cc
deleted file mode 100644
index 0b28fe9d0ce..00000000000
--- a/contrib/libs/grpc/test/cpp/util/cli_credentials.cc
+++ /dev/null
@@ -1,191 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include "test/cpp/util/cli_credentials.h"
-
-#include "y_absl/flags/flag.h"
-
-#include <grpc/slice.h>
-#include <grpc/support/log.h>
-#include <grpcpp/impl/codegen/slice.h>
-
-#include "src/core/lib/iomgr/load_file.h"
-
-Y_ABSL_RETIRED_FLAG(bool, enable_ssl, false,
- "Replaced by --channel_creds_type=ssl.");
-Y_ABSL_RETIRED_FLAG(bool, use_auth, false,
- "Replaced by --channel_creds_type=gdc.");
-Y_ABSL_RETIRED_FLAG(TString, access_token, "",
- "Replaced by --call_creds=access_token=<token>.");
-Y_ABSL_FLAG(
- TString, ssl_target, "",
- "If not empty, treat the server host name as this for ssl/tls certificate "
- "validation.");
-Y_ABSL_FLAG(
- TString, ssl_client_cert, "",
- "If not empty, load this PEM formatted client certificate file. Requires "
- "use of --ssl_client_key.");
-Y_ABSL_FLAG(TString, ssl_client_key, "",
- "If not empty, load this PEM formatted private key. Requires use of "
- "--ssl_client_cert");
-Y_ABSL_FLAG(
- TString, local_connect_type, "local_tcp",
- "The type of local connections for which local channel credentials will "
- "be applied. Should be local_tcp or uds.");
-Y_ABSL_FLAG(
- TString, channel_creds_type, "",
- "The channel creds type: insecure, ssl, gdc (Google Default Credentials), "
- "alts, or local.");
-Y_ABSL_FLAG(
- TString, call_creds, "",
- "Call credentials to use: none (default), or access_token=<token>. If "
- "provided, the call creds are composited on top of channel creds.");
-
-namespace grpc {
-namespace testing {
-
-namespace {
-
-const char ACCESS_TOKEN_PREFIX[] = "access_token=";
-constexpr int ACCESS_TOKEN_PREFIX_LEN =
- sizeof(ACCESS_TOKEN_PREFIX) / sizeof(*ACCESS_TOKEN_PREFIX) - 1;
-
-bool IsAccessToken(const TString& auth) {
- return auth.length() > ACCESS_TOKEN_PREFIX_LEN &&
- auth.compare(0, ACCESS_TOKEN_PREFIX_LEN, ACCESS_TOKEN_PREFIX) == 0;
-}
-
-TString AccessToken(const TString& auth) {
- if (!IsAccessToken(auth)) {
- return "";
- }
- return TString(auth.c_str(), ACCESS_TOKEN_PREFIX_LEN);
-}
-
-} // namespace
-
-TString CliCredentials::GetDefaultChannelCredsType() const {
- return "insecure";
-}
-
-TString CliCredentials::GetDefaultCallCreds() const { return "none"; }
-
-std::shared_ptr<grpc::ChannelCredentials>
-CliCredentials::GetChannelCredentials() const {
- if (y_absl::GetFlag(FLAGS_channel_creds_type) == "insecure") {
- return grpc::InsecureChannelCredentials();
- } else if (y_absl::GetFlag(FLAGS_channel_creds_type) == "ssl") {
- grpc::SslCredentialsOptions ssl_creds_options;
- // TODO(@Capstan): This won't affect Google Default Credentials using SSL.
- if (!y_absl::GetFlag(FLAGS_ssl_client_cert).empty()) {
- grpc_slice cert_slice = grpc_empty_slice();
- GRPC_LOG_IF_ERROR(
- "load_file",
- grpc_load_file(y_absl::GetFlag(FLAGS_ssl_client_cert).c_str(), 1,
- &cert_slice));
- ssl_creds_options.pem_cert_chain =
- grpc::StringFromCopiedSlice(cert_slice);
- grpc_slice_unref(cert_slice);
- }
- if (!y_absl::GetFlag(FLAGS_ssl_client_key).empty()) {
- grpc_slice key_slice = grpc_empty_slice();
- GRPC_LOG_IF_ERROR(
- "load_file",
- grpc_load_file(y_absl::GetFlag(FLAGS_ssl_client_key).c_str(), 1,
- &key_slice));
- ssl_creds_options.pem_private_key =
- grpc::StringFromCopiedSlice(key_slice);
- grpc_slice_unref(key_slice);
- }
- return grpc::SslCredentials(ssl_creds_options);
- } else if (y_absl::GetFlag(FLAGS_channel_creds_type) == "gdc") {
- return grpc::GoogleDefaultCredentials();
- } else if (y_absl::GetFlag(FLAGS_channel_creds_type) == "alts") {
- return grpc::experimental::AltsCredentials(
- grpc::experimental::AltsCredentialsOptions());
- } else if (y_absl::GetFlag(FLAGS_channel_creds_type) == "local") {
- if (y_absl::GetFlag(FLAGS_local_connect_type) == "local_tcp") {
- return grpc::experimental::LocalCredentials(LOCAL_TCP);
- } else if (y_absl::GetFlag(FLAGS_local_connect_type) == "uds") {
- return grpc::experimental::LocalCredentials(UDS);
- } else {
- fprintf(stderr,
- "--local_connect_type=%s invalid; must be local_tcp or uds.\n",
- y_absl::GetFlag(FLAGS_local_connect_type).c_str());
- }
- }
- fprintf(stderr,
- "--channel_creds_type=%s invalid; must be insecure, ssl, gdc, "
- "alts, or local.\n",
- y_absl::GetFlag(FLAGS_channel_creds_type).c_str());
- return std::shared_ptr<grpc::ChannelCredentials>();
-}
-
-std::shared_ptr<grpc::CallCredentials> CliCredentials::GetCallCredentials()
- const {
- if (IsAccessToken(y_absl::GetFlag(FLAGS_call_creds))) {
- return grpc::AccessTokenCredentials(
- AccessToken(y_absl::GetFlag(FLAGS_call_creds)));
- }
- if (y_absl::GetFlag(FLAGS_call_creds) == "none") {
- // Nothing to do; creds, if any, are baked into the channel.
- return std::shared_ptr<grpc::CallCredentials>();
- }
- fprintf(stderr,
- "--call_creds=%s invalid; must be none "
- "or access_token=<token>.\n",
- y_absl::GetFlag(FLAGS_call_creds).c_str());
- return std::shared_ptr<grpc::CallCredentials>();
-}
-
-std::shared_ptr<grpc::ChannelCredentials> CliCredentials::GetCredentials()
- const {
- if (y_absl::GetFlag(FLAGS_call_creds).empty()) {
- y_absl::SetFlag(&FLAGS_call_creds, GetDefaultCallCreds());
- }
- if (y_absl::GetFlag(FLAGS_channel_creds_type).empty()) {
- y_absl::SetFlag(&FLAGS_channel_creds_type, GetDefaultChannelCredsType());
- }
- std::shared_ptr<grpc::ChannelCredentials> channel_creds =
- GetChannelCredentials();
- // Composite any call-type credentials on top of the base channel.
- std::shared_ptr<grpc::CallCredentials> call_creds = GetCallCredentials();
- return (channel_creds == nullptr || call_creds == nullptr)
- ? channel_creds
- : grpc::CompositeChannelCredentials(channel_creds, call_creds);
-}
-
-TString CliCredentials::GetCredentialUsage() const {
- return " --ssl_target ; Set server host for ssl validation\n"
- " --ssl_client_cert ; Client cert for ssl\n"
- " --ssl_client_key ; Client private key for ssl\n"
- " --local_connect_type ; Set to local_tcp or uds\n"
- " --channel_creds_type ; Set to insecure, ssl, gdc, alts, or "
- "local\n"
- " --call_creds ; Set to none, or"
- " access_token=<token>\n";
-}
-
-TString CliCredentials::GetSslTargetNameOverride() const {
- bool use_ssl = y_absl::GetFlag(FLAGS_channel_creds_type) == "ssl" ||
- y_absl::GetFlag(FLAGS_channel_creds_type) == "gdc";
- return use_ssl ? y_absl::GetFlag(FLAGS_ssl_target) : "";
-}
-
-} // namespace testing
-} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/util/cli_credentials.h b/contrib/libs/grpc/test/cpp/util/cli_credentials.h
deleted file mode 100644
index a60d5c2c10d..00000000000
--- a/contrib/libs/grpc/test/cpp/util/cli_credentials.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CPP_UTIL_CLI_CREDENTIALS_H
-#define GRPC_TEST_CPP_UTIL_CLI_CREDENTIALS_H
-
-#include <grpcpp/security/credentials.h>
-#include <grpcpp/support/config.h>
-
-namespace grpc {
-namespace testing {
-
-class CliCredentials {
- public:
- virtual ~CliCredentials() {}
- std::shared_ptr<grpc::ChannelCredentials> GetCredentials() const;
- virtual TString GetCredentialUsage() const;
- virtual TString GetSslTargetNameOverride() const;
-
- protected:
- // Returns the appropriate channel_creds_type value for the set of legacy
- // flag arguments.
- virtual TString GetDefaultChannelCredsType() const;
- // Returns the appropriate call_creds value for the set of legacy flag
- // arguments.
- virtual TString GetDefaultCallCreds() const;
- // Returns the base transport channel credentials. Child classes can override
- // to support additional channel_creds_types unknown to this base class.
- virtual std::shared_ptr<grpc::ChannelCredentials> GetChannelCredentials()
- const;
- // Returns call credentials to composite onto the base transport channel
- // credentials. Child classes can override to support additional
- // authentication flags unknown to this base class.
- virtual std::shared_ptr<grpc::CallCredentials> GetCallCredentials() const;
-};
-
-} // namespace testing
-} // namespace grpc
-
-#endif // GRPC_TEST_CPP_UTIL_CLI_CREDENTIALS_H
diff --git a/contrib/libs/grpc/test/cpp/util/config_grpc_cli.h b/contrib/libs/grpc/test/cpp/util/config_grpc_cli.h
deleted file mode 100644
index 358884196df..00000000000
--- a/contrib/libs/grpc/test/cpp/util/config_grpc_cli.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CPP_UTIL_CONFIG_GRPC_CLI_H
-#define GRPC_TEST_CPP_UTIL_CONFIG_GRPC_CLI_H
-
-#include <grpcpp/impl/codegen/config_protobuf.h>
-
-#ifndef GRPC_CUSTOM_DYNAMICMESSAGEFACTORY
-#include <google/protobuf/dynamic_message.h>
-#define GRPC_CUSTOM_DYNAMICMESSAGEFACTORY \
- ::google::protobuf::DynamicMessageFactory
-#endif
-
-#ifndef GRPC_CUSTOM_DESCRIPTORPOOLDATABASE
-#include <google/protobuf/descriptor.h>
-#define GRPC_CUSTOM_DESCRIPTORPOOLDATABASE \
- ::google::protobuf::DescriptorPoolDatabase
-#define GRPC_CUSTOM_MERGEDDESCRIPTORDATABASE \
- ::google::protobuf::MergedDescriptorDatabase
-#endif
-
-#ifndef GRPC_CUSTOM_TEXTFORMAT
-#include <google/protobuf/text_format.h>
-#define GRPC_CUSTOM_TEXTFORMAT ::google::protobuf::TextFormat
-#endif
-
-#ifndef GRPC_CUSTOM_DISKSOURCETREE
-#include <google/protobuf/compiler/importer.h>
-#define GRPC_CUSTOM_DISKSOURCETREE ::google::protobuf::compiler::DiskSourceTree
-#define GRPC_CUSTOM_IMPORTER ::google::protobuf::compiler::Importer
-#define GRPC_CUSTOM_MULTIFILEERRORCOLLECTOR \
- ::google::protobuf::compiler::MultiFileErrorCollector
-#endif
-
-namespace grpc {
-namespace protobuf {
-
-typedef GRPC_CUSTOM_DYNAMICMESSAGEFACTORY DynamicMessageFactory;
-
-typedef GRPC_CUSTOM_DESCRIPTORPOOLDATABASE DescriptorPoolDatabase;
-typedef GRPC_CUSTOM_MERGEDDESCRIPTORDATABASE MergedDescriptorDatabase;
-
-typedef GRPC_CUSTOM_TEXTFORMAT TextFormat;
-
-namespace compiler {
-typedef GRPC_CUSTOM_DISKSOURCETREE DiskSourceTree;
-typedef GRPC_CUSTOM_IMPORTER Importer;
-typedef GRPC_CUSTOM_MULTIFILEERRORCOLLECTOR MultiFileErrorCollector;
-} // namespace compiler
-
-} // namespace protobuf
-} // namespace grpc
-
-#endif // GRPC_TEST_CPP_UTIL_CONFIG_GRPC_CLI_H
diff --git a/contrib/libs/grpc/test/cpp/util/grpc_tool.cc b/contrib/libs/grpc/test/cpp/util/grpc_tool.cc
deleted file mode 100644
index 9ea30f32ede..00000000000
--- a/contrib/libs/grpc/test/cpp/util/grpc_tool.cc
+++ /dev/null
@@ -1,1010 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "test/cpp/util/grpc_tool.h"
-
-#include <cstdio>
-#include <fstream>
-#include <iostream>
-#include <memory>
-#include <sstream>
-#include <util/generic/string.h>
-#include <thread>
-
-#include "y_absl/flags/flag.h"
-#include "y_absl/memory/memory.h"
-
-#include <grpc/grpc.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/grpcpp.h>
-#include <grpcpp/security/credentials.h>
-#include <grpcpp/support/string_ref.h>
-
-#include "test/cpp/util/cli_call.h"
-#include "test/cpp/util/proto_file_parser.h"
-#include "test/cpp/util/proto_reflection_descriptor_database.h"
-#include "test/cpp/util/service_describer.h"
-
-#if GPR_WINDOWS
-#include <io.h>
-#else
-#include <unistd.h>
-#endif
-
-Y_ABSL_FLAG(bool, l, false, "Use a long listing format");
-Y_ABSL_FLAG(bool, remotedb, true,
- "Use server types to parse and format messages");
-Y_ABSL_FLAG(TString, metadata, "",
- "Metadata to send to server, in the form of key1:val1:key2:val2");
-Y_ABSL_FLAG(TString, proto_path, ".",
- "Path to look for the proto file. "
- "Multiple paths can be separated by " GRPC_CLI_PATH_SEPARATOR);
-Y_ABSL_FLAG(TString, protofiles, "", "Name of the proto file.");
-Y_ABSL_FLAG(bool, binary_input, false, "Input in binary format");
-Y_ABSL_FLAG(bool, binary_output, false, "Output in binary format");
-Y_ABSL_FLAG(TString, default_service_config, "",
- "Default service config to use on the channel, if non-empty. Note "
- "that this will be ignored if the name resolver returns a service "
- "config.");
-Y_ABSL_FLAG(bool, display_peer_address, false,
- "Log the peer socket address of the connection that each RPC is made "
- "on to stderr.");
-Y_ABSL_FLAG(bool, json_input, false, "Input in json format");
-Y_ABSL_FLAG(bool, json_output, false, "Output in json format");
-Y_ABSL_FLAG(TString, infile, "", "Input file (default is stdin)");
-Y_ABSL_FLAG(bool, batch, false,
- "Input contains multiple requests. Please do not use this to send "
- "more than a few RPCs. gRPC CLI has very different performance "
- "characteristics compared with normal RPC calls which make it "
- "unsuitable for loadtesting or significant production traffic.");
-// TODO(Capstan): Consider using y_absl::Duration
-Y_ABSL_FLAG(double, timeout, -1,
- "Specify timeout in seconds, used to set the deadline for all "
- "RPCs. The default value of -1 means no deadline has been set.");
-
-namespace grpc {
-namespace testing {
-namespace {
-
-class GrpcTool {
- public:
- explicit GrpcTool();
- virtual ~GrpcTool() {}
-
- bool Help(int argc, const char** argv, const CliCredentials& cred,
- const GrpcToolOutputCallback& callback);
- bool CallMethod(int argc, const char** argv, const CliCredentials& cred,
- const GrpcToolOutputCallback& callback);
- bool ListServices(int argc, const char** argv, const CliCredentials& cred,
- const GrpcToolOutputCallback& callback);
- bool PrintType(int argc, const char** argv, const CliCredentials& cred,
- const GrpcToolOutputCallback& callback);
- // TODO(zyc): implement the following methods
- // bool ListServices(int argc, const char** argv, GrpcToolOutputCallback
- // callback);
- // bool PrintTypeId(int argc, const char** argv, GrpcToolOutputCallback
- // callback);
- bool ParseMessage(int argc, const char** argv, const CliCredentials& cred,
- const GrpcToolOutputCallback& callback);
- bool ToText(int argc, const char** argv, const CliCredentials& cred,
- const GrpcToolOutputCallback& callback);
- bool ToJson(int argc, const char** argv, const CliCredentials& cred,
- const GrpcToolOutputCallback& callback);
- bool ToBinary(int argc, const char** argv, const CliCredentials& cred,
- const GrpcToolOutputCallback& callback);
-
- void SetPrintCommandMode(int exit_status) {
- print_command_usage_ = true;
- usage_exit_status_ = exit_status;
- }
-
- private:
- void CommandUsage(const TString& usage) const;
- bool print_command_usage_;
- int usage_exit_status_;
- const TString cred_usage_;
-};
-
-template <typename T>
-std::function<bool(GrpcTool*, int, const char**, const CliCredentials&,
- GrpcToolOutputCallback)>
-BindWith5Args(T&& func) {
- return std::bind(std::forward<T>(func), std::placeholders::_1,
- std::placeholders::_2, std::placeholders::_3,
- std::placeholders::_4, std::placeholders::_5);
-}
-
-template <typename T>
-size_t ArraySize(T& a) {
- return ((sizeof(a) / sizeof(*(a))) /
- static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))));
-}
-
-void ParseMetadataFlag(
- std::multimap<TString, TString>* client_metadata) {
- if (y_absl::GetFlag(FLAGS_metadata).empty()) {
- return;
- }
- std::vector<TString> fields;
- const char delim = ':';
- const char escape = '\\';
- size_t cur = -1;
- std::stringstream ss;
- while (++cur < y_absl::GetFlag(FLAGS_metadata).length()) {
- switch (y_absl::GetFlag(FLAGS_metadata).at(cur)) {
- case escape:
- if (cur < y_absl::GetFlag(FLAGS_metadata).length() - 1) {
- char c = y_absl::GetFlag(FLAGS_metadata).at(++cur);
- if (c == delim || c == escape) {
- ss << c;
- continue;
- }
- }
- fprintf(stderr, "Failed to parse metadata flag.\n");
- exit(1);
- case delim:
- fields.push_back(ss.str());
- ss.str("");
- ss.clear();
- break;
- default:
- ss << y_absl::GetFlag(FLAGS_metadata).at(cur);
- }
- }
- fields.push_back(ss.str());
- if (fields.size() % 2) {
- fprintf(stderr, "Failed to parse metadata flag.\n");
- exit(1);
- }
- for (size_t i = 0; i < fields.size(); i += 2) {
- client_metadata->insert(
- std::pair<TString, TString>(fields[i], fields[i + 1]));
- }
-}
-
-template <typename T>
-void PrintMetadata(const T& m, const TString& message) {
- if (m.empty()) {
- return;
- }
- fprintf(stderr, "%s\n", message.c_str());
- TString pair;
- for (typename T::const_iterator iter = m.begin(); iter != m.end(); ++iter) {
- pair.clear();
- pair.append(iter->first.data(), iter->first.size());
- pair.append(" : ");
- pair.append(iter->second.data(), iter->second.size());
- fprintf(stderr, "%s\n", pair.c_str());
- }
-}
-
-void ReadResponse(CliCall* call, const TString& method_name,
- const GrpcToolOutputCallback& callback,
- ProtoFileParser* parser, gpr_mu* parser_mu, bool print_mode) {
- TString serialized_response_proto;
- std::multimap<grpc::string_ref, grpc::string_ref> server_initial_metadata;
-
- for (bool receive_initial_metadata = true; call->ReadAndMaybeNotifyWrite(
- &serialized_response_proto,
- receive_initial_metadata ? &server_initial_metadata : nullptr);
- receive_initial_metadata = false) {
- fprintf(stderr, "got response.\n");
- if (!y_absl::GetFlag(FLAGS_binary_output)) {
- gpr_mu_lock(parser_mu);
- serialized_response_proto = parser->GetFormattedStringFromMethod(
- method_name, serialized_response_proto, false /* is_request */,
- y_absl::GetFlag(FLAGS_json_output));
- if (parser->HasError() && print_mode) {
- fprintf(stderr, "Failed to parse response.\n");
- }
- gpr_mu_unlock(parser_mu);
- }
- if (receive_initial_metadata) {
- PrintMetadata(server_initial_metadata,
- "Received initial metadata from server:");
- }
- if (!callback(serialized_response_proto) && print_mode) {
- fprintf(stderr, "Failed to output response.\n");
- }
- }
-}
-
-std::shared_ptr<grpc::Channel> CreateCliChannel(
- const TString& server_address, const CliCredentials& cred) {
- grpc::ChannelArguments args;
- if (!cred.GetSslTargetNameOverride().empty()) {
- args.SetSslTargetNameOverride(cred.GetSslTargetNameOverride());
- }
- if (!y_absl::GetFlag(FLAGS_default_service_config).empty()) {
- args.SetString(GRPC_ARG_SERVICE_CONFIG,
- y_absl::GetFlag(FLAGS_default_service_config).c_str());
- }
- // See |GRPC_ARG_MAX_METADATA_SIZE| in |grpc_types.h|.
- // Set to large enough size (10M) that should work for most use cases.
- args.SetInt(GRPC_ARG_MAX_METADATA_SIZE, 10 * 1024 * 1024);
- return ::grpc::CreateCustomChannel(server_address, cred.GetCredentials(),
- args);
-}
-
-struct Command {
- const char* command;
- std::function<bool(GrpcTool*, int, const char**, const CliCredentials&,
- GrpcToolOutputCallback)>
- function;
- int min_args;
- int max_args;
-};
-
-const Command ops[] = {
- {"help", BindWith5Args(&GrpcTool::Help), 0, INT_MAX},
- {"ls", BindWith5Args(&GrpcTool::ListServices), 1, 3},
- {"list", BindWith5Args(&GrpcTool::ListServices), 1, 3},
- {"call", BindWith5Args(&GrpcTool::CallMethod), 2, 3},
- {"type", BindWith5Args(&GrpcTool::PrintType), 2, 2},
- {"parse", BindWith5Args(&GrpcTool::ParseMessage), 2, 3},
- {"totext", BindWith5Args(&GrpcTool::ToText), 2, 3},
- {"tobinary", BindWith5Args(&GrpcTool::ToBinary), 2, 3},
- {"tojson", BindWith5Args(&GrpcTool::ToJson), 2, 3},
-};
-
-void Usage(const TString& msg) {
- fprintf(
- stderr,
- "%s\n"
- " grpc_cli ls ... ; List services\n"
- " grpc_cli call ... ; Call method\n"
- " grpc_cli type ... ; Print type\n"
- " grpc_cli parse ... ; Parse message\n"
- " grpc_cli totext ... ; Convert binary message to text\n"
- " grpc_cli tojson ... ; Convert binary message to json\n"
- " grpc_cli tobinary ... ; Convert text message to binary\n"
- " grpc_cli help ... ; Print this message, or per-command usage\n"
- "\n",
- msg.c_str());
-
- exit(1);
-}
-
-const Command* FindCommand(const TString& name) {
- for (int i = 0; i < static_cast<int>(ArraySize(ops)); i++) {
- if (name == ops[i].command) {
- return &ops[i];
- }
- }
- return nullptr;
-}
-} // namespace
-
-int GrpcToolMainLib(int argc, const char** argv, const CliCredentials& cred,
- const GrpcToolOutputCallback& callback) {
- if (argc < 2) {
- Usage("No command specified");
- }
-
- TString command = argv[1];
- argc -= 2;
- argv += 2;
-
- const Command* cmd = FindCommand(command);
- if (cmd != nullptr) {
- GrpcTool grpc_tool;
- if (argc < cmd->min_args || argc > cmd->max_args) {
- // Force the command to print its usage message
- fprintf(stderr, "\nWrong number of arguments for %s\n", command.c_str());
- grpc_tool.SetPrintCommandMode(1);
- return cmd->function(&grpc_tool, -1, nullptr, cred, callback);
- }
- const bool ok = cmd->function(&grpc_tool, argc, argv, cred, callback);
- return ok ? 0 : 1;
- } else {
- Usage("Invalid command '" + TString(command.c_str()) + "'");
- }
- return 1;
-}
-
-GrpcTool::GrpcTool() : print_command_usage_(false), usage_exit_status_(0) {}
-
-void GrpcTool::CommandUsage(const TString& usage) const {
- if (print_command_usage_) {
- fprintf(stderr, "\n%s%s\n", usage.c_str(),
- (usage.empty() || usage[usage.size() - 1] != '\n') ? "\n" : "");
- exit(usage_exit_status_);
- }
-}
-
-bool GrpcTool::Help(int argc, const char** argv, const CliCredentials& cred,
- const GrpcToolOutputCallback& callback) {
- CommandUsage(
- "Print help\n"
- " grpc_cli help [subcommand]\n");
-
- if (argc == 0) {
- Usage("");
- } else {
- const Command* cmd = FindCommand(argv[0]);
- if (cmd == nullptr) {
- Usage("Unknown command '" + TString(argv[0]) + "'");
- }
- SetPrintCommandMode(0);
- cmd->function(this, -1, nullptr, cred, callback);
- }
- return true;
-}
-
-bool GrpcTool::ListServices(int argc, const char** argv,
- const CliCredentials& cred,
- const GrpcToolOutputCallback& callback) {
- CommandUsage(
- "List services\n"
- " grpc_cli ls <address> [<service>[/<method>]]\n"
- " <address> ; host:port\n"
- " <service> ; Exported service name\n"
- " <method> ; Method name\n"
- " --l ; Use a long listing format\n"
- " --outfile ; Output filename (defaults to stdout)\n" +
- cred.GetCredentialUsage());
-
- TString server_address(argv[0]);
- std::shared_ptr<grpc::Channel> channel =
- CreateCliChannel(server_address, cred);
- grpc::ProtoReflectionDescriptorDatabase desc_db(channel);
- grpc::protobuf::DescriptorPool desc_pool(&desc_db);
-
- std::vector<TString> service_list;
- if (!desc_db.GetServices(&service_list)) {
- fprintf(stderr, "Received an error when querying services endpoint.\n");
- return false;
- }
-
- // If no service is specified, dump the list of services.
- TString output;
- if (argc < 2) {
- // List all services, if --l is passed, then include full description,
- // otherwise include a summarized list only.
- if (y_absl::GetFlag(FLAGS_l)) {
- output = DescribeServiceList(service_list, desc_pool);
- } else {
- for (auto it = service_list.begin(); it != service_list.end(); it++) {
- auto const& service = *it;
- output.append(service);
- output.append("\n");
- }
- }
- } else {
- std::string service_name;
- std::string method_name;
- std::stringstream ss(argv[1]);
-
- // Remove leading slashes.
- while (ss.peek() == '/') {
- ss.get();
- }
-
- // Parse service and method names. Support the following patterns:
- // Service
- // Service Method
- // Service.Method
- // Service/Method
- if (argc == 3) {
- std::getline(ss, service_name, '/');
- method_name = argv[2];
- } else {
- if (std::getline(ss, service_name, '/')) {
- std::getline(ss, method_name);
- }
- }
-
- const grpc::protobuf::ServiceDescriptor* service =
- desc_pool.FindServiceByName(google::protobuf::string(service_name));
- if (service != nullptr) {
- if (method_name.empty()) {
- output = y_absl::GetFlag(FLAGS_l) ? DescribeService(service)
- : SummarizeService(service);
- } else {
- method_name.insert(0, ".");
- method_name.insert(0, service_name);
- const grpc::protobuf::MethodDescriptor* method =
- desc_pool.FindMethodByName(google::protobuf::string(method_name));
- if (method != nullptr) {
- output = y_absl::GetFlag(FLAGS_l) ? DescribeMethod(method)
- : SummarizeMethod(method);
- } else {
- fprintf(stderr, "Method %s not found in service %s.\n",
- method_name.c_str(), service_name.c_str());
- return false;
- }
- }
- } else {
- if (!method_name.empty()) {
- fprintf(stderr, "Service %s not found.\n", service_name.c_str());
- return false;
- } else {
- const grpc::protobuf::MethodDescriptor* method =
- desc_pool.FindMethodByName(google::protobuf::string(service_name));
- if (method != nullptr) {
- output = y_absl::GetFlag(FLAGS_l) ? DescribeMethod(method)
- : SummarizeMethod(method);
- } else {
- fprintf(stderr, "Service or method %s not found.\n",
- service_name.c_str());
- return false;
- }
- }
- }
- }
- return callback(output);
-}
-
-bool GrpcTool::PrintType(int /*argc*/, const char** argv,
- const CliCredentials& cred,
- const GrpcToolOutputCallback& callback) {
- CommandUsage(
- "Print type\n"
- " grpc_cli type <address> <type>\n"
- " <address> ; host:port\n"
- " <type> ; Protocol buffer type name\n" +
- cred.GetCredentialUsage());
-
- TString server_address(argv[0]);
- std::shared_ptr<grpc::Channel> channel =
- CreateCliChannel(server_address, cred);
- grpc::ProtoReflectionDescriptorDatabase desc_db(channel);
- grpc::protobuf::DescriptorPool desc_pool(&desc_db);
-
- TString output;
- const grpc::protobuf::Descriptor* descriptor =
- desc_pool.FindMessageTypeByName(argv[1]);
- if (descriptor != nullptr) {
- output = descriptor->DebugString();
- } else {
- fprintf(stderr, "Type %s not found.\n", argv[1]);
- return false;
- }
- return callback(output);
-}
-
-bool GrpcTool::CallMethod(int argc, const char** argv,
- const CliCredentials& cred,
- const GrpcToolOutputCallback& callback) {
- CommandUsage(
- "Call method\n"
- " grpc_cli call <address> <service>[.<method>] <request>\n"
- " <address> ; host:port\n"
- " <service> ; Exported service name\n"
- " <method> ; Method name\n"
- " <request> ; Text protobuffer (overrides infile)\n"
- " --protofiles ; Comma separated proto files used as a"
- " fallback when parsing request/response\n"
- " --proto_path ; The search paths of proto files"
- " (" GRPC_CLI_PATH_SEPARATOR
- " separated), valid only when --protofiles is given\n"
- " --noremotedb ; Don't attempt to use reflection service"
- " at all\n"
- " --metadata ; The metadata to be sent to the server\n"
- " --infile ; Input filename (defaults to stdin)\n"
- " --outfile ; Output filename (defaults to stdout)\n"
- " --binary_input ; Input in binary format\n"
- " --binary_output ; Output in binary format\n"
- " --json_input ; Input in json format\n"
- " --json_output ; Output in json format\n"
- " --timeout ; Specify timeout (in seconds), used to "
- "set the deadline for RPCs. The default value of -1 means no "
- "deadline has been set.\n" +
- cred.GetCredentialUsage());
-
- std::stringstream output_ss;
- TString request_text;
- TString server_address(argv[0]);
- TString method_name(argv[1]);
- TString formatted_method_name;
- std::unique_ptr<ProtoFileParser> parser;
- TString serialized_request_proto;
- CliArgs cli_args;
- cli_args.timeout = y_absl::GetFlag(FLAGS_timeout);
- bool print_mode = false;
-
- std::shared_ptr<grpc::Channel> channel =
- CreateCliChannel(server_address, cred);
-
- if (!y_absl::GetFlag(FLAGS_binary_input) ||
- !y_absl::GetFlag(FLAGS_binary_output)) {
- parser = y_absl::make_unique<grpc::testing::ProtoFileParser>(
- y_absl::GetFlag(FLAGS_remotedb) ? channel : nullptr,
- y_absl::GetFlag(FLAGS_proto_path), y_absl::GetFlag(FLAGS_protofiles));
- if (parser->HasError()) {
- fprintf(
- stderr,
- "Failed to find remote reflection service and local proto files.\n");
- return false;
- }
- }
-
- if (y_absl::GetFlag(FLAGS_binary_input)) {
- formatted_method_name = method_name;
- } else {
- formatted_method_name = parser->GetFormattedMethodName(method_name);
- if (parser->HasError()) {
- fprintf(stderr, "Failed to find method %s in proto files.\n",
- method_name.c_str());
- }
- }
-
- if (argc == 3) {
- request_text = argv[2];
- }
-
- if (parser->IsStreaming(method_name, true /* is_request */)) {
- std::istream* input_stream;
- std::ifstream input_file;
-
- if (y_absl::GetFlag(FLAGS_batch)) {
- fprintf(stderr, "Batch mode for streaming RPC is not supported.\n");
- return false;
- }
-
- std::multimap<TString, TString> client_metadata;
- ParseMetadataFlag(&client_metadata);
- PrintMetadata(client_metadata, "Sending client initial metadata:");
-
- CliCall call(channel, formatted_method_name, client_metadata, cli_args);
- if (y_absl::GetFlag(FLAGS_display_peer_address)) {
- fprintf(stderr, "New call for method_name:%s has peer address:|%s|\n",
- formatted_method_name.c_str(), call.peer().c_str());
- }
-
- if (y_absl::GetFlag(FLAGS_infile).empty()) {
- if (isatty(fileno(stdin))) {
- print_mode = true;
- fprintf(stderr, "reading streaming request message from stdin...\n");
- }
- input_stream = &std::cin;
- } else {
- input_file.open(y_absl::GetFlag(FLAGS_infile),
- std::ios::in | std::ios::binary);
- input_stream = &input_file;
- }
-
- gpr_mu parser_mu;
- gpr_mu_init(&parser_mu);
- std::thread read_thread(ReadResponse, &call, method_name, callback,
- parser.get(), &parser_mu, print_mode);
-
- std::stringstream request_ss;
- std::string line;
- while (!request_text.empty() ||
- (!input_stream->eof() && getline(*input_stream, line))) {
- if (!request_text.empty()) {
- if (y_absl::GetFlag(FLAGS_binary_input)) {
- serialized_request_proto = request_text;
- request_text.clear();
- } else {
- gpr_mu_lock(&parser_mu);
- serialized_request_proto = parser->GetSerializedProtoFromMethod(
- method_name, request_text, true /* is_request */,
- y_absl::GetFlag(FLAGS_json_input));
- request_text.clear();
- if (parser->HasError()) {
- if (print_mode) {
- fprintf(stderr, "Failed to parse request.\n");
- }
- gpr_mu_unlock(&parser_mu);
- continue;
- }
- gpr_mu_unlock(&parser_mu);
- }
-
- call.WriteAndWait(serialized_request_proto);
- if (print_mode) {
- fprintf(stderr, "Request sent.\n");
- }
- } else {
- if (line.length() == 0) {
- request_text = request_ss.str();
- request_ss.str(TString());
- request_ss.clear();
- } else {
- request_ss << line << ' ';
- }
- }
- }
- if (input_file.is_open()) {
- input_file.close();
- }
-
- call.WritesDoneAndWait();
- read_thread.join();
- gpr_mu_destroy(&parser_mu);
-
- std::multimap<grpc::string_ref, grpc::string_ref> server_trailing_metadata;
- Status status = call.Finish(&server_trailing_metadata);
- PrintMetadata(server_trailing_metadata,
- "Received trailing metadata from server:");
-
- if (status.ok()) {
- fprintf(stderr, "Stream RPC succeeded with OK status\n");
- return true;
- } else {
- fprintf(stderr, "Rpc failed with status code %d, error message: %s\n",
- status.error_code(), status.error_message().c_str());
- return false;
- }
-
- } else { // parser->IsStreaming(method_name, true /* is_request */)
- if (y_absl::GetFlag(FLAGS_batch)) {
- if (parser->IsStreaming(method_name, false /* is_request */)) {
- fprintf(stderr, "Batch mode for streaming RPC is not supported.\n");
- return false;
- }
-
- std::istream* input_stream;
- std::ifstream input_file;
-
- if (y_absl::GetFlag(FLAGS_infile).empty()) {
- if (isatty(fileno(stdin))) {
- print_mode = true;
- fprintf(stderr, "reading request messages from stdin...\n");
- }
- input_stream = &std::cin;
- } else {
- input_file.open(y_absl::GetFlag(FLAGS_infile),
- std::ios::in | std::ios::binary);
- input_stream = &input_file;
- }
-
- std::multimap<TString, TString> client_metadata;
- ParseMetadataFlag(&client_metadata);
- if (print_mode) {
- PrintMetadata(client_metadata, "Sending client initial metadata:");
- }
-
- std::stringstream request_ss;
- std::string line;
- while (!request_text.empty() ||
- (!input_stream->eof() && getline(*input_stream, line))) {
- if (!request_text.empty()) {
- if (y_absl::GetFlag(FLAGS_binary_input)) {
- serialized_request_proto = request_text;
- request_text.clear();
- } else {
- serialized_request_proto = parser->GetSerializedProtoFromMethod(
- method_name, request_text, true /* is_request */,
- y_absl::GetFlag(FLAGS_json_input));
- request_text.clear();
- if (parser->HasError()) {
- if (print_mode) {
- fprintf(stderr, "Failed to parse request.\n");
- }
- continue;
- }
- }
-
- TString serialized_response_proto;
- std::multimap<grpc::string_ref, grpc::string_ref>
- server_initial_metadata, server_trailing_metadata;
- CliCall call(channel, formatted_method_name, client_metadata,
- cli_args);
- if (y_absl::GetFlag(FLAGS_display_peer_address)) {
- fprintf(stderr,
- "New call for method_name:%s has peer address:|%s|\n",
- formatted_method_name.c_str(), call.peer().c_str());
- }
- call.Write(serialized_request_proto);
- call.WritesDone();
- if (!call.Read(&serialized_response_proto,
- &server_initial_metadata)) {
- fprintf(stderr, "Failed to read response.\n");
- }
- Status status = call.Finish(&server_trailing_metadata);
-
- if (status.ok()) {
- if (print_mode) {
- fprintf(stderr, "Rpc succeeded with OK status.\n");
- PrintMetadata(server_initial_metadata,
- "Received initial metadata from server:");
- PrintMetadata(server_trailing_metadata,
- "Received trailing metadata from server:");
- }
-
- if (y_absl::GetFlag(FLAGS_binary_output)) {
- if (!callback(serialized_response_proto)) {
- break;
- }
- } else {
- TString response_text = parser->GetFormattedStringFromMethod(
- method_name, serialized_response_proto,
- false /* is_request */, y_absl::GetFlag(FLAGS_json_output));
-
- if (parser->HasError() && print_mode) {
- fprintf(stderr, "Failed to parse response.\n");
- } else {
- if (!callback(response_text)) {
- break;
- }
- }
- }
- } else {
- if (print_mode) {
- fprintf(stderr,
- "Rpc failed with status code %d, error message: %s\n",
- status.error_code(), status.error_message().c_str());
- }
- }
- } else {
- if (line.length() == 0) {
- request_text = request_ss.str();
- request_ss.str(TString());
- request_ss.clear();
- } else {
- request_ss << line << ' ';
- }
- }
- }
-
- if (input_file.is_open()) {
- input_file.close();
- }
-
- return true;
- }
-
- if (argc == 3) {
- if (!y_absl::GetFlag(FLAGS_infile).empty()) {
- fprintf(stderr, "warning: request given in argv, ignoring --infile\n");
- }
- } else {
- std::stringstream input_stream;
- if (y_absl::GetFlag(FLAGS_infile).empty()) {
- if (isatty(fileno(stdin))) {
- fprintf(stderr, "reading request message from stdin...\n");
- }
- input_stream << std::cin.rdbuf();
- } else {
- std::ifstream input_file(y_absl::GetFlag(FLAGS_infile),
- std::ios::in | std::ios::binary);
- input_stream << input_file.rdbuf();
- input_file.close();
- }
- request_text = input_stream.str();
- }
-
- if (y_absl::GetFlag(FLAGS_binary_input)) {
- serialized_request_proto = request_text;
- } else {
- serialized_request_proto = parser->GetSerializedProtoFromMethod(
- method_name, request_text, true /* is_request */,
- y_absl::GetFlag(FLAGS_json_input));
- if (parser->HasError()) {
- fprintf(stderr, "Failed to parse request.\n");
- return false;
- }
- }
- fprintf(stderr, "connecting to %s\n", server_address.c_str());
-
- TString serialized_response_proto;
- std::multimap<TString, TString> client_metadata;
- std::multimap<grpc::string_ref, grpc::string_ref> server_initial_metadata,
- server_trailing_metadata;
- ParseMetadataFlag(&client_metadata);
- PrintMetadata(client_metadata, "Sending client initial metadata:");
-
- CliCall call(channel, formatted_method_name, client_metadata, cli_args);
- if (y_absl::GetFlag(FLAGS_display_peer_address)) {
- fprintf(stderr, "New call for method_name:%s has peer address:|%s|\n",
- formatted_method_name.c_str(), call.peer().c_str());
- }
- call.Write(serialized_request_proto);
- call.WritesDone();
-
- for (bool receive_initial_metadata = true; call.Read(
- &serialized_response_proto,
- receive_initial_metadata ? &server_initial_metadata : nullptr);
- receive_initial_metadata = false) {
- if (!y_absl::GetFlag(FLAGS_binary_output)) {
- serialized_response_proto = parser->GetFormattedStringFromMethod(
- method_name, serialized_response_proto, false /* is_request */,
- y_absl::GetFlag(FLAGS_json_output));
- if (parser->HasError()) {
- fprintf(stderr, "Failed to parse response.\n");
- return false;
- }
- }
-
- if (receive_initial_metadata) {
- PrintMetadata(server_initial_metadata,
- "Received initial metadata from server:");
- }
- if (!callback(serialized_response_proto)) {
- return false;
- }
- }
- Status status = call.Finish(&server_trailing_metadata);
- PrintMetadata(server_trailing_metadata,
- "Received trailing metadata from server:");
- if (status.ok()) {
- fprintf(stderr, "Rpc succeeded with OK status\n");
- return true;
- } else {
- fprintf(stderr, "Rpc failed with status code %d, error message: %s\n",
- status.error_code(), status.error_message().c_str());
- return false;
- }
- }
- GPR_UNREACHABLE_CODE(return false);
-}
-
-bool GrpcTool::ParseMessage(int argc, const char** argv,
- const CliCredentials& cred,
- const GrpcToolOutputCallback& callback) {
- CommandUsage(
- "Parse message\n"
- " grpc_cli parse <address> <type> [<message>]\n"
- " <address> ; host:port\n"
- " <type> ; Protocol buffer type name\n"
- " <message> ; Text protobuffer (overrides --infile)\n"
- " --protofiles ; Comma separated proto files used as a"
- " fallback when parsing request/response\n"
- " --proto_path ; The search paths of proto files"
- " (" GRPC_CLI_PATH_SEPARATOR
- " separated), valid only when --protofiles is given\n"
- " --noremotedb ; Don't attempt to use reflection service"
- " at all\n"
- " --infile ; Input filename (defaults to stdin)\n"
- " --outfile ; Output filename (defaults to stdout)\n"
- " --binary_input ; Input in binary format\n"
- " --binary_output ; Output in binary format\n"
- " --json_input ; Input in json format\n"
- " --json_output ; Output in json format\n" +
- cred.GetCredentialUsage());
-
- std::stringstream output_ss;
- TString message_text;
- TString server_address(argv[0]);
- TString type_name(argv[1]);
- std::unique_ptr<grpc::testing::ProtoFileParser> parser;
- TString serialized_request_proto;
-
- if (argc == 3) {
- message_text = argv[2];
- if (!y_absl::GetFlag(FLAGS_infile).empty()) {
- fprintf(stderr, "warning: message given in argv, ignoring --infile.\n");
- }
- } else {
- std::stringstream input_stream;
- if (y_absl::GetFlag(FLAGS_infile).empty()) {
- if (isatty(fileno(stdin))) {
- fprintf(stderr, "reading request message from stdin...\n");
- }
- input_stream << std::cin.rdbuf();
- } else {
- std::ifstream input_file(y_absl::GetFlag(FLAGS_infile),
- std::ios::in | std::ios::binary);
- input_stream << input_file.rdbuf();
- input_file.close();
- }
- message_text = input_stream.str();
- }
-
- if (!y_absl::GetFlag(FLAGS_binary_input) ||
- !y_absl::GetFlag(FLAGS_binary_output)) {
- std::shared_ptr<grpc::Channel> channel =
- CreateCliChannel(server_address, cred);
- parser = y_absl::make_unique<grpc::testing::ProtoFileParser>(
- y_absl::GetFlag(FLAGS_remotedb) ? channel : nullptr,
- y_absl::GetFlag(FLAGS_proto_path), y_absl::GetFlag(FLAGS_protofiles));
- if (parser->HasError()) {
- fprintf(
- stderr,
- "Failed to find remote reflection service and local proto files.\n");
- return false;
- }
- }
-
- if (y_absl::GetFlag(FLAGS_binary_input)) {
- serialized_request_proto = message_text;
- } else {
- serialized_request_proto = parser->GetSerializedProtoFromMessageType(
- type_name, message_text, y_absl::GetFlag(FLAGS_json_input));
- if (parser->HasError()) {
- fprintf(stderr, "Failed to serialize the message.\n");
- return false;
- }
- }
-
- if (y_absl::GetFlag(FLAGS_binary_output)) {
- output_ss << serialized_request_proto;
- } else {
- TString output_text;
- output_text = parser->GetFormattedStringFromMessageType(
- type_name, serialized_request_proto, y_absl::GetFlag(FLAGS_json_output));
- if (parser->HasError()) {
- fprintf(stderr, "Failed to deserialize the message.\n");
- return false;
- }
-
- output_ss << output_text << std::endl;
- }
-
- return callback(output_ss.str());
-}
-
-bool GrpcTool::ToText(int argc, const char** argv, const CliCredentials& cred,
- const GrpcToolOutputCallback& callback) {
- CommandUsage(
- "Convert binary message to text\n"
- " grpc_cli totext <protofiles> <type>\n"
- " <protofiles> ; Comma separated list of proto files\n"
- " <type> ; Protocol buffer type name\n"
- " --proto_path ; The search paths of proto files"
- " (" GRPC_CLI_PATH_SEPARATOR
- " separated)\n"
- " --infile ; Input filename (defaults to stdin)\n"
- " --outfile ; Output filename (defaults to stdout)\n");
-
- y_absl::SetFlag(&FLAGS_protofiles, argv[0]);
- y_absl::SetFlag(&FLAGS_remotedb, false);
- y_absl::SetFlag(&FLAGS_binary_input, true);
- y_absl::SetFlag(&FLAGS_binary_output, false);
- return ParseMessage(argc, argv, cred, callback);
-}
-
-bool GrpcTool::ToJson(int argc, const char** argv, const CliCredentials& cred,
- const GrpcToolOutputCallback& callback) {
- CommandUsage(
- "Convert binary message to json\n"
- " grpc_cli tojson <protofiles> <type>\n"
- " <protofiles> ; Comma separated list of proto files\n"
- " <type> ; Protocol buffer type name\n"
- " --proto_path ; The search paths of proto files"
- " (" GRPC_CLI_PATH_SEPARATOR
- " separated)\n"
- " --infile ; Input filename (defaults to stdin)\n"
- " --outfile ; Output filename (defaults to stdout)\n");
-
- y_absl::SetFlag(&FLAGS_protofiles, argv[0]);
- y_absl::SetFlag(&FLAGS_remotedb, false);
- y_absl::SetFlag(&FLAGS_binary_input, true);
- y_absl::SetFlag(&FLAGS_binary_output, false);
- y_absl::SetFlag(&FLAGS_json_output, true);
- return ParseMessage(argc, argv, cred, callback);
-}
-
-bool GrpcTool::ToBinary(int argc, const char** argv, const CliCredentials& cred,
- const GrpcToolOutputCallback& callback) {
- CommandUsage(
- "Convert text message to binary\n"
- " grpc_cli tobinary <protofiles> <type> [<message>]\n"
- " <protofiles> ; Comma separated list of proto files\n"
- " <type> ; Protocol buffer type name\n"
- " --proto_path ; The search paths of proto files"
- " (" GRPC_CLI_PATH_SEPARATOR
- " separated)\n"
- " --infile ; Input filename (defaults to stdin)\n"
- " --outfile ; Output filename (defaults to stdout)\n");
-
- y_absl::SetFlag(&FLAGS_protofiles, argv[0]);
- y_absl::SetFlag(&FLAGS_remotedb, false);
- y_absl::SetFlag(&FLAGS_binary_input, false);
- y_absl::SetFlag(&FLAGS_binary_output, true);
- return ParseMessage(argc, argv, cred, callback);
-}
-
-} // namespace testing
-} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/util/grpc_tool.h b/contrib/libs/grpc/test/cpp/util/grpc_tool.h
deleted file mode 100644
index 7fbbe35c9ec..00000000000
--- a/contrib/libs/grpc/test/cpp/util/grpc_tool.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CPP_UTIL_GRPC_TOOL_H
-#define GRPC_TEST_CPP_UTIL_GRPC_TOOL_H
-
-#include <functional>
-
-#include <grpcpp/support/config.h>
-
-#include "test/cpp/util/cli_credentials.h"
-
-namespace grpc {
-namespace testing {
-
-typedef std::function<bool(const TString&)> GrpcToolOutputCallback;
-
-int GrpcToolMainLib(int argc, const char** argv, const CliCredentials& cred,
- const GrpcToolOutputCallback& callback);
-
-} // namespace testing
-} // namespace grpc
-
-#endif // GRPC_TEST_CPP_UTIL_GRPC_TOOL_H
diff --git a/contrib/libs/grpc/test/cpp/util/proto_file_parser.cc b/contrib/libs/grpc/test/cpp/util/proto_file_parser.cc
deleted file mode 100644
index c324a7688bd..00000000000
--- a/contrib/libs/grpc/test/cpp/util/proto_file_parser.cc
+++ /dev/null
@@ -1,331 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include "test/cpp/util/proto_file_parser.h"
-
-#include <algorithm>
-#include <iostream>
-#include <sstream>
-#include <unordered_set>
-
-#include "y_absl/memory/memory.h"
-#include "y_absl/strings/str_split.h"
-
-#include <grpcpp/support/config.h>
-
-namespace grpc {
-namespace testing {
-namespace {
-
-// Match the user input method string to the full_name from method descriptor.
-bool MethodNameMatch(const TString& full_name, const TString& input) {
- TString clean_input = input;
- std::replace(clean_input.begin(), clean_input.vend(), '/', '.');
- if (clean_input.size() > full_name.size()) {
- return false;
- }
- return full_name.compare(full_name.size() - clean_input.size(),
- clean_input.size(), clean_input) == 0;
-}
-} // namespace
-
-class ErrorPrinter : public protobuf::compiler::MultiFileErrorCollector {
- public:
- explicit ErrorPrinter(ProtoFileParser* parser) : parser_(parser) {}
-
- void AddError(const google::protobuf::string& filename, int line, int column,
- const google::protobuf::string& message) override {
- std::ostringstream oss;
- oss << "error " << filename << " " << line << " " << column << " "
- << message << "\n";
- parser_->LogError(oss.str());
- }
-
- void AddWarning(const google::protobuf::string& filename, int line, int column,
- const google::protobuf::string& message) override {
- std::cerr << "warning " << filename << " " << line << " " << column << " "
- << message << std::endl;
- }
-
- private:
- ProtoFileParser* parser_; // not owned
-};
-
-ProtoFileParser::ProtoFileParser(const std::shared_ptr<grpc::Channel>& channel,
- const TString& proto_path,
- const TString& protofiles)
- : has_error_(false),
- dynamic_factory_(new protobuf::DynamicMessageFactory()) {
- std::vector<TString> service_list;
- if (channel) {
- reflection_db_ =
- y_absl::make_unique<grpc::ProtoReflectionDescriptorDatabase>(channel);
- reflection_db_->GetServices(&service_list);
- }
-
- std::unordered_set<TString> known_services;
- if (!protofiles.empty()) {
- for (const y_absl::string_view single_path : y_absl::StrSplit(
- proto_path, GRPC_CLI_PATH_SEPARATOR, y_absl::AllowEmpty())) {
- source_tree_.MapPath("", google::protobuf::string(single_path));
- }
- error_printer_ = y_absl::make_unique<ErrorPrinter>(this);
- importer_ = y_absl::make_unique<protobuf::compiler::Importer>(
- &source_tree_, error_printer_.get());
-
- std::string file_name;
- std::stringstream ss(protofiles);
- while (std::getline(ss, file_name, ',')) {
- const auto* file_desc = importer_->Import(google::protobuf::string(file_name));
- if (file_desc) {
- for (int i = 0; i < file_desc->service_count(); i++) {
- service_desc_list_.push_back(file_desc->service(i));
- known_services.insert(file_desc->service(i)->full_name());
- }
- } else {
- std::cerr << file_name << " not found" << std::endl;
- }
- }
-
- file_db_ =
- y_absl::make_unique<protobuf::DescriptorPoolDatabase>(*importer_->pool());
- }
-
- if (!reflection_db_ && !file_db_) {
- LogError("No available proto database");
- return;
- }
-
- if (!reflection_db_) {
- desc_db_ = std::move(file_db_);
- } else if (!file_db_) {
- desc_db_ = std::move(reflection_db_);
- } else {
- desc_db_ = y_absl::make_unique<protobuf::MergedDescriptorDatabase>(
- reflection_db_.get(), file_db_.get());
- }
-
- desc_pool_ = y_absl::make_unique<protobuf::DescriptorPool>(desc_db_.get());
-
- for (auto it = service_list.begin(); it != service_list.end(); it++) {
- if (known_services.find(*it) == known_services.end()) {
- if (const protobuf::ServiceDescriptor* service_desc =
- desc_pool_->FindServiceByName(google::protobuf::string(*it))) {
- service_desc_list_.push_back(service_desc);
- known_services.insert(*it);
- }
- }
- }
-}
-
-ProtoFileParser::~ProtoFileParser() {}
-
-TString ProtoFileParser::GetFullMethodName(const TString& method) {
- has_error_ = false;
-
- if (known_methods_.find(method) != known_methods_.end()) {
- return known_methods_[method];
- }
-
- const protobuf::MethodDescriptor* method_descriptor = nullptr;
- for (auto it = service_desc_list_.begin(); it != service_desc_list_.end();
- it++) {
- const auto* service_desc = *it;
- for (int j = 0; j < service_desc->method_count(); j++) {
- const auto* method_desc = service_desc->method(j);
- if (MethodNameMatch(method_desc->full_name(), method)) {
- if (method_descriptor) {
- std::ostringstream error_stream;
- error_stream << "Ambiguous method names: ";
- error_stream << method_descriptor->full_name() << " ";
- error_stream << method_desc->full_name();
- LogError(error_stream.str());
- }
- method_descriptor = method_desc;
- }
- }
- }
- if (!method_descriptor) {
- LogError("Method name not found");
- }
- if (has_error_) {
- return "";
- }
-
- known_methods_[method] = method_descriptor->full_name();
-
- return method_descriptor->full_name();
-}
-
-TString ProtoFileParser::GetFormattedMethodName(const TString& method) {
- has_error_ = false;
- TString formatted_method_name = GetFullMethodName(method);
- if (has_error_) {
- return "";
- }
- size_t last_dot = formatted_method_name.find_last_of('.');
- if (last_dot != TString::npos) {
- formatted_method_name[last_dot] = '/';
- }
- formatted_method_name.insert(formatted_method_name.begin(), '/');
- return formatted_method_name;
-}
-
-TString ProtoFileParser::GetMessageTypeFromMethod(const TString& method,
- bool is_request) {
- has_error_ = false;
- TString full_method_name = GetFullMethodName(method);
- if (has_error_) {
- return "";
- }
- const protobuf::MethodDescriptor* method_desc =
- desc_pool_->FindMethodByName(google::protobuf::string(full_method_name));
- if (!method_desc) {
- LogError("Method not found");
- return "";
- }
-
- return is_request ? method_desc->input_type()->full_name()
- : method_desc->output_type()->full_name();
-}
-
-bool ProtoFileParser::IsStreaming(const TString& method, bool is_request) {
- has_error_ = false;
-
- TString full_method_name = GetFullMethodName(method);
- if (has_error_) {
- return false;
- }
-
- const protobuf::MethodDescriptor* method_desc =
- desc_pool_->FindMethodByName(google::protobuf::string(full_method_name));
- if (!method_desc) {
- LogError("Method not found");
- return false;
- }
-
- return is_request ? method_desc->client_streaming()
- : method_desc->server_streaming();
-}
-
-TString ProtoFileParser::GetSerializedProtoFromMethod(
- const TString& method, const TString& formatted_proto,
- bool is_request, bool is_json_format) {
- has_error_ = false;
- TString message_type_name = GetMessageTypeFromMethod(method, is_request);
- if (has_error_) {
- return "";
- }
- return GetSerializedProtoFromMessageType(message_type_name, formatted_proto,
- is_json_format);
-}
-
-TString ProtoFileParser::GetFormattedStringFromMethod(
- const TString& method, const TString& serialized_proto,
- bool is_request, bool is_json_format) {
- has_error_ = false;
- TString message_type_name = GetMessageTypeFromMethod(method, is_request);
- if (has_error_) {
- return "";
- }
- return GetFormattedStringFromMessageType(message_type_name, serialized_proto,
- is_json_format);
-}
-
-TString ProtoFileParser::GetSerializedProtoFromMessageType(
- const TString& message_type_name, const TString& formatted_proto,
- bool is_json_format) {
- has_error_ = false;
- google::protobuf::string serialized;
- const protobuf::Descriptor* desc =
- desc_pool_->FindMessageTypeByName(google::protobuf::string(message_type_name));
- if (!desc) {
- LogError("Message type not found");
- return "";
- }
- std::unique_ptr<grpc::protobuf::Message> msg(
- dynamic_factory_->GetPrototype(desc)->New());
- bool ok;
- if (is_json_format) {
- ok = grpc::protobuf::json::JsonStringToMessage(google::protobuf::string(formatted_proto), msg.get())
- .ok();
- if (!ok) {
- LogError("Failed to convert json format to proto.");
- return "";
- }
- } else {
- ok = protobuf::TextFormat::ParseFromString(google::protobuf::string(formatted_proto), msg.get());
- if (!ok) {
- LogError("Failed to convert text format to proto.");
- return "";
- }
- }
-
- ok = msg->SerializeToString(&serialized);
- if (!ok) {
- LogError("Failed to serialize proto.");
- return "";
- }
- return serialized;
-}
-
-TString ProtoFileParser::GetFormattedStringFromMessageType(
- const TString& message_type_name, const TString& serialized_proto,
- bool is_json_format) {
- has_error_ = false;
- const protobuf::Descriptor* desc =
- desc_pool_->FindMessageTypeByName(google::protobuf::string(message_type_name));
- if (!desc) {
- LogError("Message type not found");
- return "";
- }
- std::unique_ptr<grpc::protobuf::Message> msg(
- dynamic_factory_->GetPrototype(desc)->New());
- if (!msg->ParseFromString(google::protobuf::string(serialized_proto))) {
- LogError("Failed to deserialize proto.");
- return "";
- }
- google::protobuf::string formatted_string;
-
- if (is_json_format) {
- grpc::protobuf::json::JsonPrintOptions jsonPrintOptions;
- jsonPrintOptions.add_whitespace = true;
- if (!grpc::protobuf::json::MessageToJsonString(*msg, &formatted_string,
- jsonPrintOptions)
- .ok()) {
- LogError("Failed to print proto message to json format");
- return "";
- }
- } else {
- if (!protobuf::TextFormat::PrintToString(*msg, &formatted_string)) {
- LogError("Failed to print proto message to text format");
- return "";
- }
- }
- return formatted_string;
-}
-
-void ProtoFileParser::LogError(const TString& error_msg) {
- if (!error_msg.empty()) {
- std::cerr << error_msg << std::endl;
- }
- has_error_ = true;
-}
-
-} // namespace testing
-} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/util/proto_file_parser.h b/contrib/libs/grpc/test/cpp/util/proto_file_parser.h
deleted file mode 100644
index 9189b1ce0e8..00000000000
--- a/contrib/libs/grpc/test/cpp/util/proto_file_parser.h
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CPP_UTIL_PROTO_FILE_PARSER_H
-#define GRPC_TEST_CPP_UTIL_PROTO_FILE_PARSER_H
-
-#include <memory>
-
-#include <grpcpp/channel.h>
-
-#include "test/cpp/util/config_grpc_cli.h"
-#include "test/cpp/util/proto_reflection_descriptor_database.h"
-
-#if defined(_WIN32) && !defined(__CYGWIN__)
-#define GRPC_CLI_PATH_SEPARATOR ";"
-#else
-#define GRPC_CLI_PATH_SEPARATOR ":"
-#endif
-
-namespace grpc {
-namespace testing {
-class ErrorPrinter;
-
-// Find method and associated request/response types.
-class ProtoFileParser {
- public:
- // The parser will search proto files using the server reflection service
- // provided on the given channel. The given protofiles in a source tree rooted
- // from proto_path will also be searched.
- ProtoFileParser(const std::shared_ptr<grpc::Channel>& channel,
- const TString& proto_path, const TString& protofiles);
-
- ~ProtoFileParser();
-
- // The input method name in the following four functions could be a partial
- // string such as Service.Method or even just Method. It will log an error if
- // there is ambiguity.
- // Full method name is in the form of Service.Method, it's good to be used in
- // descriptor database queries.
- TString GetFullMethodName(const TString& method);
-
- // Formatted method name is in the form of /Service/Method, it's good to be
- // used as the argument of Stub::Call()
- TString GetFormattedMethodName(const TString& method);
-
- /// Converts a text or json string to its binary proto representation for the
- /// given method's input or return type.
- /// \param method the name of the method (does not need to be fully qualified
- /// name)
- /// \param formatted_proto the text- or json-formatted proto string
- /// \param is_request if \c true the resolved type is that of the input
- /// parameter of the method, otherwise it is the output type
- /// \param is_json_format if \c true the \c formatted_proto is treated as a
- /// json-formatted proto, otherwise it is treated as a text-formatted
- /// proto
- /// \return the serialised binary proto representation of \c formatted_proto
- TString GetSerializedProtoFromMethod(const TString& method,
- const TString& formatted_proto,
- bool is_request,
- bool is_json_format);
-
- /// Converts a text or json string to its proto representation for the given
- /// message type.
- /// \param formatted_proto the text- or json-formatted proto string
- /// \return the serialised binary proto representation of \c formatted_proto
- TString GetSerializedProtoFromMessageType(
- const TString& message_type_name, const TString& formatted_proto,
- bool is_json_format);
-
- /// Converts a binary proto string to its text or json string representation
- /// for the given method's input or return type.
- /// \param method the name of the method (does not need to be a fully
- /// qualified name)
- /// \param the serialised binary proto representation of type
- /// \c message_type_name
- /// \return the text- or json-formatted proto string of \c serialized_proto
- TString GetFormattedStringFromMethod(const TString& method,
- const TString& serialized_proto,
- bool is_request,
- bool is_json_format);
-
- /// Converts a binary proto string to its text or json string representation
- /// for the given message type.
- /// \param the serialised binary proto representation of type
- /// \c message_type_name
- /// \return the text- or json-formatted proto string of \c serialized_proto
- TString GetFormattedStringFromMessageType(
- const TString& message_type_name, const TString& serialized_proto,
- bool is_json_format);
-
- bool IsStreaming(const TString& method, bool is_request);
-
- bool HasError() const { return has_error_; }
-
- void LogError(const TString& error_msg);
-
- private:
- TString GetMessageTypeFromMethod(const TString& method,
- bool is_request);
-
- bool has_error_;
- TString request_text_;
- protobuf::compiler::DiskSourceTree source_tree_;
- std::unique_ptr<ErrorPrinter> error_printer_;
- std::unique_ptr<protobuf::compiler::Importer> importer_;
- std::unique_ptr<grpc::ProtoReflectionDescriptorDatabase> reflection_db_;
- std::unique_ptr<protobuf::DescriptorPoolDatabase> file_db_;
- std::unique_ptr<protobuf::DescriptorDatabase> desc_db_;
- std::unique_ptr<protobuf::DescriptorPool> desc_pool_;
- std::unique_ptr<protobuf::DynamicMessageFactory> dynamic_factory_;
- std::unique_ptr<grpc::protobuf::Message> request_prototype_;
- std::unique_ptr<grpc::protobuf::Message> response_prototype_;
- std::unordered_map<TString, TString> known_methods_;
- std::vector<const protobuf::ServiceDescriptor*> service_desc_list_;
-};
-
-} // namespace testing
-} // namespace grpc
-
-#endif // GRPC_TEST_CPP_UTIL_PROTO_FILE_PARSER_H
diff --git a/contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.cc b/contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.cc
deleted file mode 100644
index 5def4c1e770..00000000000
--- a/contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.cc
+++ /dev/null
@@ -1,333 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include "test/cpp/util/proto_reflection_descriptor_database.h"
-
-#include <vector>
-
-#include <grpc/support/log.h>
-
-using grpc::reflection::v1alpha::ErrorResponse;
-using grpc::reflection::v1alpha::ListServiceResponse;
-using grpc::reflection::v1alpha::ServerReflection;
-using grpc::reflection::v1alpha::ServerReflectionRequest;
-using grpc::reflection::v1alpha::ServerReflectionResponse;
-
-namespace grpc {
-
-ProtoReflectionDescriptorDatabase::ProtoReflectionDescriptorDatabase(
- std::unique_ptr<ServerReflection::Stub> stub)
- : stub_(std::move(stub)) {}
-
-ProtoReflectionDescriptorDatabase::ProtoReflectionDescriptorDatabase(
- const std::shared_ptr<grpc::Channel>& channel)
- : stub_(ServerReflection::NewStub(channel)) {}
-
-ProtoReflectionDescriptorDatabase::~ProtoReflectionDescriptorDatabase() {
- if (stream_) {
- stream_->WritesDone();
- Status status = stream_->Finish();
- if (!status.ok()) {
- if (status.error_code() == StatusCode::UNIMPLEMENTED) {
- fprintf(stderr,
- "Reflection request not implemented; "
- "is the ServerReflection service enabled?\n");
- } else {
- fprintf(stderr,
- "ServerReflectionInfo rpc failed. Error code: %d, message: %s, "
- "debug info: %s\n",
- static_cast<int>(status.error_code()),
- status.error_message().c_str(),
- ctx_.debug_error_string().c_str());
- }
- }
- }
-}
-
-bool ProtoReflectionDescriptorDatabase::FindFileByName(
- const google::protobuf::string& filename, protobuf::FileDescriptorProto* output) {
- if (cached_db_.FindFileByName(filename, output)) {
- return true;
- }
-
- if (known_files_.find(filename) != known_files_.end()) {
- return false;
- }
-
- ServerReflectionRequest request;
- request.set_file_by_filename(filename);
- ServerReflectionResponse response;
-
- if (!DoOneRequest(request, response)) {
- return false;
- }
-
- if (response.message_response_case() ==
- ServerReflectionResponse::MessageResponseCase::kFileDescriptorResponse) {
- AddFileFromResponse(response.file_descriptor_response());
- } else if (response.message_response_case() ==
- ServerReflectionResponse::MessageResponseCase::kErrorResponse) {
- const ErrorResponse& error = response.error_response();
- if (error.error_code() == StatusCode::NOT_FOUND) {
- gpr_log(GPR_INFO, "NOT_FOUND from server for FindFileByName(%s)",
- filename.c_str());
- } else {
- gpr_log(GPR_INFO,
- "Error on FindFileByName(%s)\n\tError code: %d\n"
- "\tError Message: %s",
- filename.c_str(), error.error_code(),
- error.error_message().c_str());
- }
- } else {
- gpr_log(
- GPR_INFO,
- "Error on FindFileByName(%s) response type\n"
- "\tExpecting: %d\n\tReceived: %d",
- filename.c_str(),
- ServerReflectionResponse::MessageResponseCase::kFileDescriptorResponse,
- response.message_response_case());
- }
-
- return cached_db_.FindFileByName(filename, output);
-}
-
-bool ProtoReflectionDescriptorDatabase::FindFileContainingSymbol(
- const google::protobuf::string& symbol_name, protobuf::FileDescriptorProto* output) {
- if (cached_db_.FindFileContainingSymbol(symbol_name, output)) {
- return true;
- }
-
- if (missing_symbols_.find(symbol_name) != missing_symbols_.end()) {
- return false;
- }
-
- ServerReflectionRequest request;
- request.set_file_containing_symbol(symbol_name);
- ServerReflectionResponse response;
-
- if (!DoOneRequest(request, response)) {
- return false;
- }
-
- if (response.message_response_case() ==
- ServerReflectionResponse::MessageResponseCase::kFileDescriptorResponse) {
- AddFileFromResponse(response.file_descriptor_response());
- } else if (response.message_response_case() ==
- ServerReflectionResponse::MessageResponseCase::kErrorResponse) {
- const ErrorResponse& error = response.error_response();
- if (error.error_code() == StatusCode::NOT_FOUND) {
- missing_symbols_.insert(symbol_name);
- gpr_log(GPR_INFO,
- "NOT_FOUND from server for FindFileContainingSymbol(%s)",
- symbol_name.c_str());
- } else {
- gpr_log(GPR_INFO,
- "Error on FindFileContainingSymbol(%s)\n"
- "\tError code: %d\n\tError Message: %s",
- symbol_name.c_str(), error.error_code(),
- error.error_message().c_str());
- }
- } else {
- gpr_log(
- GPR_INFO,
- "Error on FindFileContainingSymbol(%s) response type\n"
- "\tExpecting: %d\n\tReceived: %d",
- symbol_name.c_str(),
- ServerReflectionResponse::MessageResponseCase::kFileDescriptorResponse,
- response.message_response_case());
- }
- return cached_db_.FindFileContainingSymbol(symbol_name, output);
-}
-
-bool ProtoReflectionDescriptorDatabase::FindFileContainingExtension(
- const google::protobuf::string& containing_type, int field_number,
- protobuf::FileDescriptorProto* output) {
- if (cached_db_.FindFileContainingExtension(containing_type, field_number,
- output)) {
- return true;
- }
-
- if (missing_extensions_.find(containing_type) != missing_extensions_.end() &&
- missing_extensions_[containing_type].find(field_number) !=
- missing_extensions_[containing_type].end()) {
- gpr_log(GPR_INFO, "nested map.");
- return false;
- }
-
- ServerReflectionRequest request;
- request.mutable_file_containing_extension()->set_containing_type(
- containing_type);
- request.mutable_file_containing_extension()->set_extension_number(
- field_number);
- ServerReflectionResponse response;
-
- if (!DoOneRequest(request, response)) {
- return false;
- }
-
- if (response.message_response_case() ==
- ServerReflectionResponse::MessageResponseCase::kFileDescriptorResponse) {
- AddFileFromResponse(response.file_descriptor_response());
- } else if (response.message_response_case() ==
- ServerReflectionResponse::MessageResponseCase::kErrorResponse) {
- const ErrorResponse& error = response.error_response();
- if (error.error_code() == StatusCode::NOT_FOUND) {
- if (missing_extensions_.find(containing_type) ==
- missing_extensions_.end()) {
- missing_extensions_[containing_type] = {};
- }
- missing_extensions_[containing_type].insert(field_number);
- gpr_log(GPR_INFO,
- "NOT_FOUND from server for FindFileContainingExtension(%s, %d)",
- containing_type.c_str(), field_number);
- } else {
- gpr_log(GPR_INFO,
- "Error on FindFileContainingExtension(%s, %d)\n"
- "\tError code: %d\n\tError Message: %s",
- containing_type.c_str(), field_number, error.error_code(),
- error.error_message().c_str());
- }
- } else {
- gpr_log(
- GPR_INFO,
- "Error on FindFileContainingExtension(%s, %d) response type\n"
- "\tExpecting: %d\n\tReceived: %d",
- containing_type.c_str(), field_number,
- ServerReflectionResponse::MessageResponseCase::kFileDescriptorResponse,
- response.message_response_case());
- }
-
- return cached_db_.FindFileContainingExtension(containing_type, field_number,
- output);
-}
-
-bool ProtoReflectionDescriptorDatabase::FindAllExtensionNumbers(
- const google::protobuf::string& extendee_type, std::vector<int>* output) {
- if (cached_extension_numbers_.find(extendee_type) !=
- cached_extension_numbers_.end()) {
- *output = cached_extension_numbers_[extendee_type];
- return true;
- }
-
- ServerReflectionRequest request;
- request.set_all_extension_numbers_of_type(extendee_type);
- ServerReflectionResponse response;
-
- if (!DoOneRequest(request, response)) {
- return false;
- }
-
- if (response.message_response_case() ==
- ServerReflectionResponse::MessageResponseCase::
- kAllExtensionNumbersResponse) {
- auto number = response.all_extension_numbers_response().extension_number();
- *output = std::vector<int>(number.begin(), number.end());
- cached_extension_numbers_[extendee_type] = *output;
- return true;
- } else if (response.message_response_case() ==
- ServerReflectionResponse::MessageResponseCase::kErrorResponse) {
- const ErrorResponse& error = response.error_response();
- if (error.error_code() == StatusCode::NOT_FOUND) {
- gpr_log(GPR_INFO, "NOT_FOUND from server for FindAllExtensionNumbers(%s)",
- extendee_type.c_str());
- } else {
- gpr_log(GPR_INFO,
- "Error on FindAllExtensionNumbersExtension(%s)\n"
- "\tError code: %d\n\tError Message: %s",
- extendee_type.c_str(), error.error_code(),
- error.error_message().c_str());
- }
- }
- return false;
-}
-
-bool ProtoReflectionDescriptorDatabase::GetServices(
- std::vector<TString>* output) {
- ServerReflectionRequest request;
- request.set_list_services("");
- ServerReflectionResponse response;
-
- if (!DoOneRequest(request, response)) {
- return false;
- }
-
- if (response.message_response_case() ==
- ServerReflectionResponse::MessageResponseCase::kListServicesResponse) {
- const ListServiceResponse& ls_response = response.list_services_response();
- for (int i = 0; i < ls_response.service_size(); ++i) {
- (*output).push_back(ls_response.service(i).name());
- }
- return true;
- } else if (response.message_response_case() ==
- ServerReflectionResponse::MessageResponseCase::kErrorResponse) {
- const ErrorResponse& error = response.error_response();
- gpr_log(GPR_INFO,
- "Error on GetServices()\n\tError code: %d\n"
- "\tError Message: %s",
- error.error_code(), error.error_message().c_str());
- } else {
- gpr_log(
- GPR_INFO,
- "Error on GetServices() response type\n\tExpecting: %d\n\tReceived: %d",
- ServerReflectionResponse::MessageResponseCase::kListServicesResponse,
- response.message_response_case());
- }
- return false;
-}
-
-protobuf::FileDescriptorProto
-ProtoReflectionDescriptorDatabase::ParseFileDescriptorProtoResponse(
- const TString& byte_fd_proto) {
- protobuf::FileDescriptorProto file_desc_proto;
- file_desc_proto.ParseFromString(google::protobuf::string(byte_fd_proto));
- return file_desc_proto;
-}
-
-void ProtoReflectionDescriptorDatabase::AddFileFromResponse(
- const grpc::reflection::v1alpha::FileDescriptorResponse& response) {
- for (int i = 0; i < response.file_descriptor_proto_size(); ++i) {
- const protobuf::FileDescriptorProto file_proto =
- ParseFileDescriptorProtoResponse(response.file_descriptor_proto(i));
- if (known_files_.find(file_proto.name()) == known_files_.end()) {
- known_files_.insert(file_proto.name());
- cached_db_.Add(file_proto);
- }
- }
-}
-
-std::shared_ptr<ProtoReflectionDescriptorDatabase::ClientStream>
-ProtoReflectionDescriptorDatabase::GetStream() {
- if (!stream_) {
- stream_ = stub_->ServerReflectionInfo(&ctx_);
- }
- return stream_;
-}
-
-bool ProtoReflectionDescriptorDatabase::DoOneRequest(
- const ServerReflectionRequest& request,
- ServerReflectionResponse& response) {
- bool success = false;
- stream_mutex_.lock();
- if (GetStream()->Write(request) && GetStream()->Read(&response)) {
- success = true;
- }
- stream_mutex_.unlock();
- return success;
-}
-
-} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.h b/contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.h
deleted file mode 100644
index 6b6f51de8b1..00000000000
--- a/contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.h
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-#ifndef GRPC_TEST_CPP_PROTO_SERVER_REFLECTION_DATABSE_H
-#define GRPC_TEST_CPP_PROTO_SERVER_REFLECTION_DATABSE_H
-
-#include <mutex>
-#include <unordered_map>
-#include <unordered_set>
-#include <vector>
-
-#include <grpcpp/grpcpp.h>
-#include <grpcpp/impl/codegen/config_protobuf.h>
-
-#include "src/proto/grpc/reflection/v1alpha/reflection.grpc.pb.h"
-
-namespace grpc {
-
-// ProtoReflectionDescriptorDatabase takes a stub of ServerReflection and
-// provides the methods defined by DescriptorDatabase interfaces. It can be used
-// to feed a DescriptorPool instance.
-class ProtoReflectionDescriptorDatabase : public protobuf::DescriptorDatabase {
- public:
- explicit ProtoReflectionDescriptorDatabase(
- std::unique_ptr<reflection::v1alpha::ServerReflection::Stub> stub);
-
- explicit ProtoReflectionDescriptorDatabase(
- const std::shared_ptr<grpc::Channel>& channel);
-
- ~ProtoReflectionDescriptorDatabase() override;
-
- // The following four methods implement DescriptorDatabase interfaces.
- //
- // Find a file by file name. Fills in *output and returns true if found.
- // Otherwise, returns false, leaving the contents of *output undefined.
- bool FindFileByName(const google::protobuf::string& filename,
- protobuf::FileDescriptorProto* output) override;
-
- // Find the file that declares the given fully-qualified symbol name.
- // If found, fills in *output and returns true, otherwise returns false
- // and leaves *output undefined.
- bool FindFileContainingSymbol(const google::protobuf::string& symbol_name,
- protobuf::FileDescriptorProto* output) override;
-
- // Find the file which defines an extension extending the given message type
- // with the given field number. If found, fills in *output and returns true,
- // otherwise returns false and leaves *output undefined. containing_type
- // must be a fully-qualified type name.
- bool FindFileContainingExtension(
- const google::protobuf::string& containing_type, int field_number,
- protobuf::FileDescriptorProto* output) override;
-
- // Finds the tag numbers used by all known extensions of
- // extendee_type, and appends them to output in an undefined
- // order. This method is best-effort: it's not guaranteed that the
- // database will find all extensions, and it's not guaranteed that
- // FindFileContainingExtension will return true on all of the found
- // numbers. Returns true if the search was successful, otherwise
- // returns false and leaves output unchanged.
- bool FindAllExtensionNumbers(const google::protobuf::string& extendee_type,
- std::vector<int>* output) override;
-
- // Provide a list of full names of registered services
- bool GetServices(std::vector<TString>* output);
-
- private:
- typedef ClientReaderWriter<
- grpc::reflection::v1alpha::ServerReflectionRequest,
- grpc::reflection::v1alpha::ServerReflectionResponse>
- ClientStream;
-
- protobuf::FileDescriptorProto ParseFileDescriptorProtoResponse(
- const TString& byte_fd_proto);
-
- void AddFileFromResponse(
- const grpc::reflection::v1alpha::FileDescriptorResponse& response);
-
- std::shared_ptr<ClientStream> GetStream();
-
- bool DoOneRequest(
- const grpc::reflection::v1alpha::ServerReflectionRequest& request,
- grpc::reflection::v1alpha::ServerReflectionResponse& response);
-
- std::shared_ptr<ClientStream> stream_;
- grpc::ClientContext ctx_;
- std::unique_ptr<grpc::reflection::v1alpha::ServerReflection::Stub> stub_;
- std::unordered_set<string> known_files_;
- std::unordered_set<string> missing_symbols_;
- std::unordered_map<string, std::unordered_set<int>> missing_extensions_;
- std::unordered_map<string, std::vector<int>> cached_extension_numbers_;
- std::mutex stream_mutex_;
-
- protobuf::SimpleDescriptorDatabase cached_db_;
-};
-
-} // namespace grpc
-
-#endif // GRPC_TEST_CPP_METRICS_SERVER_H
diff --git a/contrib/libs/grpc/test/cpp/util/service_describer.cc b/contrib/libs/grpc/test/cpp/util/service_describer.cc
deleted file mode 100644
index 2af1104b979..00000000000
--- a/contrib/libs/grpc/test/cpp/util/service_describer.cc
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include "test/cpp/util/service_describer.h"
-
-#include <iostream>
-#include <sstream>
-#include <util/generic/string.h>
-#include <vector>
-
-namespace grpc {
-namespace testing {
-
-TString DescribeServiceList(std::vector<TString> service_list,
- grpc::protobuf::DescriptorPool& desc_pool) {
- std::stringstream result;
- for (auto it = service_list.begin(); it != service_list.end(); it++) {
- auto const& service = *it;
- const grpc::protobuf::ServiceDescriptor* service_desc =
- desc_pool.FindServiceByName(google::protobuf::string(service));
- if (service_desc != nullptr) {
- result << DescribeService(service_desc);
- }
- }
- return result.str();
-}
-
-TString DescribeService(const grpc::protobuf::ServiceDescriptor* service) {
- TString result;
- if (service->options().deprecated()) {
- result.append("DEPRECATED\n");
- }
- result.append("filename: " + service->file()->name() + "\n");
-
- TString package = service->full_name();
- size_t pos = package.rfind("." + service->name());
- if (pos != TString::npos) {
- package.erase(pos);
- result.append("package: " + package + ";\n");
- }
- result.append("service " + service->name() + " {\n");
- for (int i = 0; i < service->method_count(); ++i) {
- result.append(DescribeMethod(service->method(i)));
- }
- result.append("}\n\n");
- return result;
-}
-
-TString DescribeMethod(const grpc::protobuf::MethodDescriptor* method) {
- std::stringstream result;
- result << " rpc " << method->name()
- << (method->client_streaming() ? "(stream " : "(")
- << method->input_type()->full_name() << ") returns "
- << (method->server_streaming() ? "(stream " : "(")
- << method->output_type()->full_name() << ") {}\n";
- if (method->options().deprecated()) {
- result << " DEPRECATED";
- }
- return result.str();
-}
-
-TString SummarizeService(const grpc::protobuf::ServiceDescriptor* service) {
- TString result;
- for (int i = 0; i < service->method_count(); ++i) {
- result.append(SummarizeMethod(service->method(i)));
- }
- return result;
-}
-
-TString SummarizeMethod(const grpc::protobuf::MethodDescriptor* method) {
- TString result = method->name();
- result.append("\n");
- return result;
-}
-
-} // namespace testing
-} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/util/service_describer.h b/contrib/libs/grpc/test/cpp/util/service_describer.h
deleted file mode 100644
index a2b2a173203..00000000000
--- a/contrib/libs/grpc/test/cpp/util/service_describer.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CPP_UTIL_SERVICE_DESCRIBER_H
-#define GRPC_TEST_CPP_UTIL_SERVICE_DESCRIBER_H
-
-#include <grpcpp/support/config.h>
-
-#include "test/cpp/util/config_grpc_cli.h"
-
-namespace grpc {
-namespace testing {
-
-TString DescribeServiceList(std::vector<TString> service_list,
- grpc::protobuf::DescriptorPool& desc_pool);
-
-TString DescribeService(const grpc::protobuf::ServiceDescriptor* service);
-
-TString DescribeMethod(const grpc::protobuf::MethodDescriptor* method);
-
-TString SummarizeService(const grpc::protobuf::ServiceDescriptor* service);
-
-TString SummarizeMethod(const grpc::protobuf::MethodDescriptor* method);
-
-} // namespace testing
-} // namespace grpc
-
-#endif // GRPC_TEST_CPP_UTIL_SERVICE_DESCRIBER_H
diff --git a/contrib/libs/grpc/test/cpp/util/string_ref_helper.cc b/contrib/libs/grpc/test/cpp/util/string_ref_helper.cc
deleted file mode 100644
index e573f5d33ad..00000000000
--- a/contrib/libs/grpc/test/cpp/util/string_ref_helper.cc
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include "test/cpp/util/string_ref_helper.h"
-
-namespace grpc {
-namespace testing {
-
-TString ToString(const grpc::string_ref& r) {
- return TString(r.data(), r.size());
-}
-
-} // namespace testing
-} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/util/string_ref_helper.h b/contrib/libs/grpc/test/cpp/util/string_ref_helper.h
deleted file mode 100644
index e9e941f3192..00000000000
--- a/contrib/libs/grpc/test/cpp/util/string_ref_helper.h
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CPP_UTIL_STRING_REF_HELPER_H
-#define GRPC_TEST_CPP_UTIL_STRING_REF_HELPER_H
-
-#include <grpcpp/support/string_ref.h>
-
-namespace grpc {
-namespace testing {
-
-TString ToString(const grpc::string_ref& r);
-
-} // namespace testing
-} // namespace grpc
-
-#endif // GRPC_TEST_CPP_UTIL_STRING_REF_HELPER_H
diff --git a/contrib/libs/grpc/test/cpp/util/test_config.h b/contrib/libs/grpc/test/cpp/util/test_config.h
deleted file mode 100644
index fb2b257ddea..00000000000
--- a/contrib/libs/grpc/test/cpp/util/test_config.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CPP_UTIL_TEST_CONFIG_H
-#define GRPC_TEST_CPP_UTIL_TEST_CONFIG_H
-
-#ifndef GRPC_GTEST_FLAG_SET_DEATH_TEST_STYLE
-#define GRPC_GTEST_FLAG_SET_DEATH_TEST_STYLE(style) \
- ::testing::FLAGS_gtest_death_test_style = style
-#endif // GRPC_GTEST_FLAG_SET_DEATH_TEST_STYLE
-
-namespace grpc {
-namespace testing {
-
-void InitTest(int* argc, char*** argv, bool remove_flags);
-
-} // namespace testing
-} // namespace grpc
-
-#endif // GRPC_TEST_CPP_UTIL_TEST_CONFIG_H
diff --git a/contrib/libs/grpc/test/cpp/util/test_config_cc.cc b/contrib/libs/grpc/test/cpp/util/test_config_cc.cc
deleted file mode 100644
index 65b925751ec..00000000000
--- a/contrib/libs/grpc/test/cpp/util/test_config_cc.cc
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <vector>
-
-#include "y_absl/flags/parse.h"
-
-#include "test/cpp/util/test_config.h"
-
-namespace grpc {
-namespace testing {
-
-void InitTest(int* argc, char*** argv, bool remove_flags) {
- std::vector<char*> reduced_argv = y_absl::ParseCommandLine(*argc, *argv);
- if (remove_flags) {
- *argc = reduced_argv.size();
- for (int i = 0; i < *argc; i++) {
- (*argv)[i] = reduced_argv.at(i);
- }
- }
-}
-
-} // namespace testing
-} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/util/ya.make b/contrib/libs/grpc/test/cpp/util/ya.make
deleted file mode 100644
index f6879835dae..00000000000
--- a/contrib/libs/grpc/test/cpp/util/ya.make
+++ /dev/null
@@ -1,38 +0,0 @@
-LIBRARY()
-
-LICENSE(Apache-2.0)
-
-LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-
-PEERDIR(
- contrib/libs/gflags
- contrib/libs/protoc
- contrib/libs/grpc/src/proto/grpc/reflection/v1alpha
- contrib/restricted/googletest/googlemock
- contrib/restricted/googletest/googletest
- contrib/restricted/abseil-cpp-tstring/y_absl/flags
-)
-
-ADDINCL(
- ${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
- contrib/libs/grpc
-)
-
-NO_COMPILER_WARNINGS()
-
-SRCS(
- byte_buffer_proto_helper.cc
- # grpc_cli_libs:
- cli_call.cc
- cli_credentials.cc
- grpc_tool.cc
- proto_file_parser.cc
- service_describer.cc
- string_ref_helper.cc
- # grpc++_proto_reflection_desc_db:
- proto_reflection_descriptor_database.cc
- # grpc++_test_config:
- test_config_cc.cc
-)
-
-END()
diff --git a/contrib/libs/grpc/ya.make b/contrib/libs/grpc/ya.make
index 68902f71249..f6344b89dbe 100644
--- a/contrib/libs/grpc/ya.make
+++ b/contrib/libs/grpc/ya.make
@@ -798,16 +798,7 @@ RECURSE(
src/proto/grpc/health/v1
src/proto/grpc/reflection/v1alpha
src/proto/grpc/status
- src/proto/grpc/testing
- src/proto/grpc/testing/duplicate
- src/proto/grpc/testing/xds
src/python/grpcio
- src/python/grpcio_tests
- test/core/util
- test/cpp/end2end
- test/cpp/end2end/health
- test/cpp/end2end/server_interceptors
- test/cpp/util
third_party/address_sorting
third_party/upb
)