Debian Codegraph @

src/python/grpcio_tests/tests_aio/unit/outside_init_test.py

raw
1 # Copyright 2020 The gRPC Authors
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 """Tests behavior around the metadata mechanism."""
15
16 import asyncio
17 import logging
18 import unittest
19
20 import grpc
21 from grpc.experimental import aio
22
23 from src.proto.grpc.testing import messages_pb2
24 from src.proto.grpc.testing import test_pb2_grpc
25 from tests_aio.unit._test_server import start_test_server
26
27 _NUM_OF_LOOPS = 50
28
29
30 class TestOutsideInit(unittest.TestCase):
31
32 def test_behavior_outside_asyncio(self):
33 # Ensures non-AsyncIO object can be initiated
34 channel_creds = grpc.ssl_channel_credentials()
35
36 # Ensures AsyncIO API not raising outside of AsyncIO.
37 # NOTE(lidiz) This behavior is bound with GAPIC generator, and required
38 # by test frameworks like pytest. In test frameworks, objects shared
39 # across cases need to be created outside of AsyncIO coroutines.
40 aio.insecure_channel('')
41 aio.secure_channel('', channel_creds)
42 aio.server()
43 aio.init_grpc_aio()
44 aio.shutdown_grpc_aio()
45
46 def test_multi_ephemeral_loops(self):
47 # Initializes AIO module outside. It's part of the test. We especially
48 # want to ensure the closing of the default loop won't cause deadlocks.
49 aio.init_grpc_aio()
50
51 async def ping_pong():
52 address, server = await start_test_server()
53 channel = aio.insecure_channel(address)
54 stub = test_pb2_grpc.TestServiceStub(channel)
55
56 await stub.UnaryCall(messages_pb2.SimpleRequest())
57
58 await channel.close()
59 await server.stop(None)
60
61 for i in range(_NUM_OF_LOOPS):
62 old_loop = asyncio.get_event_loop()
63 old_loop.close()
64
65 loop = asyncio.new_event_loop()
66 loop.set_debug(True)
67 asyncio.set_event_loop(loop)
68
69 loop.run_until_complete(ping_pong())
70
71 aio.shutdown_grpc_aio()
72
73
74 if __name__ == "__main__":
75 logging.basicConfig(level=logging.DEBUG)
76 unittest.main(verbosity=2)