diff options
author | robot-piglet <robot-piglet@yandex-team.com> | 2023-03-23 12:15:53 +0300 |
---|---|---|
committer | robot-piglet <robot-piglet@yandex-team.com> | 2023-03-23 12:15:53 +0300 |
commit | 8d5942b8f813c0e704a166c3c83902ccceefca07 (patch) | |
tree | d717bac5cbd96eaff6a15e1c3f7b664b3b5dfce8 /contrib/libs/grpc/src | |
parent | 091daa0ca1dd4df8f596b17239c6f9a72abf3aab (diff) | |
download | ydb-8d5942b8f813c0e704a166c3c83902ccceefca07.tar.gz |
Intermediate changes
Diffstat (limited to 'contrib/libs/grpc/src')
101 files changed, 6 insertions, 12727 deletions
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() |