Debian Codegraph @

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

raw
1 # Copyright 2019 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
15 import asyncio
16 import logging
17 import time
18 import unittest
19
20 import grpc
21 from grpc.experimental import aio
22
23 from tests.unit import resources
24 from tests.unit.framework.common import test_constants
25 from tests_aio.unit._test_base import AioTestBase
26
27 _SIMPLE_UNARY_UNARY = '/test/SimpleUnaryUnary'
28 _BLOCK_FOREVER = '/test/BlockForever'
29 _BLOCK_BRIEFLY = '/test/BlockBriefly'
30 _UNARY_STREAM_ASYNC_GEN = '/test/UnaryStreamAsyncGen'
31 _UNARY_STREAM_READER_WRITER = '/test/UnaryStreamReaderWriter'
32 _UNARY_STREAM_EVILLY_MIXED = '/test/UnaryStreamEvillyMixed'
33 _STREAM_UNARY_ASYNC_GEN = '/test/StreamUnaryAsyncGen'
34 _STREAM_UNARY_READER_WRITER = '/test/StreamUnaryReaderWriter'
35 _STREAM_UNARY_EVILLY_MIXED = '/test/StreamUnaryEvillyMixed'
36 _STREAM_STREAM_ASYNC_GEN = '/test/StreamStreamAsyncGen'
37 _STREAM_STREAM_READER_WRITER = '/test/StreamStreamReaderWriter'
38 _STREAM_STREAM_EVILLY_MIXED = '/test/StreamStreamEvillyMixed'
39 _UNIMPLEMENTED_METHOD = '/test/UnimplementedMethod'
40 _ERROR_IN_STREAM_STREAM = '/test/ErrorInStreamStream'
41 _ERROR_IN_STREAM_UNARY = '/test/ErrorInStreamUnary'
42 _ERROR_WITHOUT_RAISE_IN_UNARY_UNARY = '/test/ErrorWithoutRaiseInUnaryUnary'
43 _ERROR_WITHOUT_RAISE_IN_STREAM_STREAM = '/test/ErrorWithoutRaiseInStreamStream'
44 _INVALID_TRAILING_METADATA = '/test/InvalidTrailingMetadata'
45
46 _REQUEST = b'\x00\x00\x00'
47 _RESPONSE = b'\x01\x01\x01'
48 _NUM_STREAM_REQUESTS = 3
49 _NUM_STREAM_RESPONSES = 5
50 _MAXIMUM_CONCURRENT_RPCS = 5
51
52
53 class _GenericHandler(grpc.GenericRpcHandler):
54
55 def __init__(self):
56 self._called = asyncio.get_event_loop().create_future()
57 self._routing_table = {
58 _SIMPLE_UNARY_UNARY:
59 grpc.unary_unary_rpc_method_handler(self._unary_unary),
60 _BLOCK_FOREVER:
61 grpc.unary_unary_rpc_method_handler(self._block_forever),
62 _BLOCK_BRIEFLY:
63 grpc.unary_unary_rpc_method_handler(self._block_briefly),
64 _UNARY_STREAM_ASYNC_GEN:
65 grpc.unary_stream_rpc_method_handler(
66 self._unary_stream_async_gen),
67 _UNARY_STREAM_READER_WRITER:
68 grpc.unary_stream_rpc_method_handler(
69 self._unary_stream_reader_writer),
70 _UNARY_STREAM_EVILLY_MIXED:
71 grpc.unary_stream_rpc_method_handler(
72 self._unary_stream_evilly_mixed),
73 _STREAM_UNARY_ASYNC_GEN:
74 grpc.stream_unary_rpc_method_handler(
75 self._stream_unary_async_gen),
76 _STREAM_UNARY_READER_WRITER:
77 grpc.stream_unary_rpc_method_handler(
78 self._stream_unary_reader_writer),
79 _STREAM_UNARY_EVILLY_MIXED:
80 grpc.stream_unary_rpc_method_handler(
81 self._stream_unary_evilly_mixed),
82 _STREAM_STREAM_ASYNC_GEN:
83 grpc.stream_stream_rpc_method_handler(
84 self._stream_stream_async_gen),
85 _STREAM_STREAM_READER_WRITER:
86 grpc.stream_stream_rpc_method_handler(
87 self._stream_stream_reader_writer),
88 _STREAM_STREAM_EVILLY_MIXED:
89 grpc.stream_stream_rpc_method_handler(
90 self._stream_stream_evilly_mixed),
91 _ERROR_IN_STREAM_STREAM:
92 grpc.stream_stream_rpc_method_handler(
93 self._error_in_stream_stream),
94 _ERROR_IN_STREAM_UNARY:
95 grpc.stream_unary_rpc_method_handler(
96 self._value_error_in_stream_unary),
97 _ERROR_WITHOUT_RAISE_IN_UNARY_UNARY:
98 grpc.unary_unary_rpc_method_handler(
99 self._error_without_raise_in_unary_unary),
100 _ERROR_WITHOUT_RAISE_IN_STREAM_STREAM:
101 grpc.stream_stream_rpc_method_handler(
102 self._error_without_raise_in_stream_stream),
103 _INVALID_TRAILING_METADATA:
104 grpc.unary_unary_rpc_method_handler(
105 self._invalid_trailing_metadata),
106 }
107
108 @staticmethod
109 async def _unary_unary(unused_request, unused_context):
110 return _RESPONSE
111
112 async def _block_forever(self, unused_request, unused_context):
113 await asyncio.get_event_loop().create_future()
114
115 async def _block_briefly(self, unused_request, unused_context):
116 await asyncio.sleep(test_constants.SHORT_TIMEOUT / 2)
117 return _RESPONSE
118
119 async def _unary_stream_async_gen(self, unused_request, unused_context):
120 for _ in range(_NUM_STREAM_RESPONSES):
121 yield _RESPONSE
122
123 async def _unary_stream_reader_writer(self, unused_request, context):
124 for _ in range(_NUM_STREAM_RESPONSES):
125 await context.write(_RESPONSE)
126
127 async def _unary_stream_evilly_mixed(self, unused_request, context):
128 yield _RESPONSE
129 for _ in range(_NUM_STREAM_RESPONSES - 1):
130 await context.write(_RESPONSE)
131
132 async def _stream_unary_async_gen(self, request_iterator, unused_context):
133 request_count = 0
134 async for request in request_iterator:
135 assert _REQUEST == request
136 request_count += 1
137 assert _NUM_STREAM_REQUESTS == request_count
138 return _RESPONSE
139
140 async def _stream_unary_reader_writer(self, unused_request, context):
141 for _ in range(_NUM_STREAM_REQUESTS):
142 assert _REQUEST == await context.read()
143 return _RESPONSE
144
145 async def _stream_unary_evilly_mixed(self, request_iterator, context):
146 assert _REQUEST == await context.read()
147 request_count = 0
148 async for request in request_iterator:
149 assert _REQUEST == request
150 request_count += 1
151 assert _NUM_STREAM_REQUESTS - 1 == request_count
152 return _RESPONSE
153
154 async def _stream_stream_async_gen(self, request_iterator, unused_context):
155 request_count = 0
156 async for request in request_iterator:
157 assert _REQUEST == request
158 request_count += 1
159 assert _NUM_STREAM_REQUESTS == request_count
160
161 for _ in range(_NUM_STREAM_RESPONSES):
162 yield _RESPONSE
163
164 async def _stream_stream_reader_writer(self, unused_request, context):
165 for _ in range(_NUM_STREAM_REQUESTS):
166 assert _REQUEST == await context.read()
167 for _ in range(_NUM_STREAM_RESPONSES):
168 await context.write(_RESPONSE)
169
170 async def _stream_stream_evilly_mixed(self, request_iterator, context):
171 assert _REQUEST == await context.read()
172 request_count = 0
173 async for request in request_iterator:
174 assert _REQUEST == request
175 request_count += 1
176 assert _NUM_STREAM_REQUESTS - 1 == request_count
177
178 yield _RESPONSE
179 for _ in range(_NUM_STREAM_RESPONSES - 1):
180 await context.write(_RESPONSE)
181
182 async def _error_in_stream_stream(self, request_iterator, unused_context):
183 async for request in request_iterator:
184 assert _REQUEST == request
185 raise RuntimeError('A testing RuntimeError!')
186 yield _RESPONSE
187
188 async def _value_error_in_stream_unary(self, request_iterator, context):
189 request_count = 0
190 async for request in request_iterator:
191 assert _REQUEST == request
192 request_count += 1
193 if request_count >= 1:
194 raise ValueError('A testing RuntimeError!')
195
196 async def _error_without_raise_in_unary_unary(self, request, context):
197 assert _REQUEST == request
198 context.set_code(grpc.StatusCode.INTERNAL)
199
200 async def _error_without_raise_in_stream_stream(self, request_iterator,
201 context):
202 async for request in request_iterator:
203 assert _REQUEST == request
204 context.set_code(grpc.StatusCode.INTERNAL)
205
206 async def _invalid_trailing_metadata(self, request, context):
207 assert _REQUEST == request
208 for invalid_metadata in [
209 42, {}, {
210 'error': 'error'
211 }, [{
212 'error': "error"
213 }]
214 ]:
215 try:
216 context.set_trailing_metadata(invalid_metadata)
217 except TypeError:
218 pass
219 else:
220 raise ValueError(
221 f'No TypeError raised for invalid metadata: {invalid_metadata}'
222 )
223
224 await context.abort(grpc.StatusCode.DATA_LOSS,
225 details="invalid abort",
226 trailing_metadata=({
227 'error': ('error1', 'error2')
228 }))
229
230 def service(self, handler_details):
231 if not self._called.done():
232 self._called.set_result(None)
233 return self._routing_table.get(handler_details.method)
234
235 async def wait_for_call(self):
236 await self._called
237
238
239 async def _start_test_server():
240 server = aio.server()
241 port = server.add_insecure_port('[::]:0')
242 generic_handler = _GenericHandler()
243 server.add_generic_rpc_handlers((generic_handler,))
244 await server.start()
245 return 'localhost:%d' % port, server, generic_handler
246
247
248 class TestServer(AioTestBase):
249
250 async def setUp(self):
251 addr, self._server, self._generic_handler = await _start_test_server()
252 self._channel = aio.insecure_channel(addr)
253
254 async def tearDown(self):
255 await self._channel.close()
256 await self._server.stop(None)
257
258 async def test_unary_unary(self):
259 unary_unary_call = self._channel.unary_unary(_SIMPLE_UNARY_UNARY)
260 response = await unary_unary_call(_REQUEST)
261 self.assertEqual(response, _RESPONSE)
262
263 async def test_unary_stream_async_generator(self):
264 unary_stream_call = self._channel.unary_stream(_UNARY_STREAM_ASYNC_GEN)
265 call = unary_stream_call(_REQUEST)
266
267 response_cnt = 0
268 async for response in call:
269 response_cnt += 1
270 self.assertEqual(_RESPONSE, response)
271
272 self.assertEqual(_NUM_STREAM_RESPONSES, response_cnt)
273 self.assertEqual(await call.code(), grpc.StatusCode.OK)
274
275 async def test_unary_stream_reader_writer(self):
276 unary_stream_call = self._channel.unary_stream(
277 _UNARY_STREAM_READER_WRITER)
278 call = unary_stream_call(_REQUEST)
279
280 for _ in range(_NUM_STREAM_RESPONSES):
281 response = await call.read()
282 self.assertEqual(_RESPONSE, response)
283
284 self.assertEqual(await call.code(), grpc.StatusCode.OK)
285
286 async def test_unary_stream_evilly_mixed(self):
287 unary_stream_call = self._channel.unary_stream(
288 _UNARY_STREAM_EVILLY_MIXED)
289 call = unary_stream_call(_REQUEST)
290
291 # Uses reader API
292 self.assertEqual(_RESPONSE, await call.read())
293
294 # Uses async generator API, mixed!
295 with self.assertRaises(aio.UsageError):
296 async for response in call:
297 self.assertEqual(_RESPONSE, response)
298
299 async def test_stream_unary_async_generator(self):
300 stream_unary_call = self._channel.stream_unary(_STREAM_UNARY_ASYNC_GEN)
301 call = stream_unary_call()
302
303 for _ in range(_NUM_STREAM_REQUESTS):
304 await call.write(_REQUEST)
305 await call.done_writing()
306
307 response = await call
308 self.assertEqual(_RESPONSE, response)
309 self.assertEqual(await call.code(), grpc.StatusCode.OK)
310
311 async def test_stream_unary_async_generator_with_request_iter(self):
312 stream_unary_call = self._channel.stream_unary(_STREAM_UNARY_ASYNC_GEN)
313
314 finished = False
315
316 def request_gen():
317 for _ in range(_NUM_STREAM_REQUESTS):
318 yield _REQUEST
319 nonlocal finished
320 finished = True
321
322 call = stream_unary_call(request_gen())
323
324 response = await call
325 self.assertEqual(_RESPONSE, response)
326 self.assertEqual(await call.code(), grpc.StatusCode.OK)
327 self.assertEqual(finished, True)
328
329 async def test_stream_unary_reader_writer(self):
330 stream_unary_call = self._channel.stream_unary(
331 _STREAM_UNARY_READER_WRITER)
332 call = stream_unary_call()
333
334 for _ in range(_NUM_STREAM_REQUESTS):
335 await call.write(_REQUEST)
336 await call.done_writing()
337
338 response = await call
339 self.assertEqual(_RESPONSE, response)
340 self.assertEqual(await call.code(), grpc.StatusCode.OK)
341
342 async def test_stream_unary_evilly_mixed(self):
343 stream_unary_call = self._channel.stream_unary(
344 _STREAM_UNARY_EVILLY_MIXED)
345 call = stream_unary_call()
346
347 for _ in range(_NUM_STREAM_REQUESTS):
348 await call.write(_REQUEST)
349 await call.done_writing()
350
351 response = await call
352 self.assertEqual(_RESPONSE, response)
353 self.assertEqual(await call.code(), grpc.StatusCode.OK)
354
355 async def test_stream_stream_async_generator(self):
356 stream_stream_call = self._channel.stream_stream(
357 _STREAM_STREAM_ASYNC_GEN)
358 call = stream_stream_call()
359
360 for _ in range(_NUM_STREAM_REQUESTS):
361 await call.write(_REQUEST)
362 await call.done_writing()
363
364 for _ in range(_NUM_STREAM_RESPONSES):
365 response = await call.read()
366 self.assertEqual(_RESPONSE, response)
367
368 self.assertEqual(await call.code(), grpc.StatusCode.OK)
369
370 async def test_stream_stream_reader_writer(self):
371 stream_stream_call = self._channel.stream_stream(
372 _STREAM_STREAM_READER_WRITER)
373 call = stream_stream_call()
374
375 for _ in range(_NUM_STREAM_REQUESTS):
376 await call.write(_REQUEST)
377 await call.done_writing()
378
379 for _ in range(_NUM_STREAM_RESPONSES):
380 response = await call.read()
381 self.assertEqual(_RESPONSE, response)
382
383 self.assertEqual(await call.code(), grpc.StatusCode.OK)
384
385 async def test_stream_stream_evilly_mixed(self):
386 stream_stream_call = self._channel.stream_stream(
387 _STREAM_STREAM_EVILLY_MIXED)
388 call = stream_stream_call()
389
390 for _ in range(_NUM_STREAM_REQUESTS):
391 await call.write(_REQUEST)
392 await call.done_writing()
393
394 for _ in range(_NUM_STREAM_RESPONSES):
395 response = await call.read()
396 self.assertEqual(_RESPONSE, response)
397
398 self.assertEqual(await call.code(), grpc.StatusCode.OK)
399
400 async def test_shutdown(self):
401 await self._server.stop(None)
402 # Ensures no SIGSEGV triggered, and ends within timeout.
403
404 async def test_shutdown_after_call(self):
405 await self._channel.unary_unary(_SIMPLE_UNARY_UNARY)(_REQUEST)
406
407 await self._server.stop(None)
408
409 async def test_graceful_shutdown_success(self):
410 call = self._channel.unary_unary(_BLOCK_BRIEFLY)(_REQUEST)
411 await self._generic_handler.wait_for_call()
412
413 shutdown_start_time = time.time()
414 await self._server.stop(test_constants.SHORT_TIMEOUT)
415 grace_period_length = time.time() - shutdown_start_time
416 self.assertGreater(grace_period_length,
417 test_constants.SHORT_TIMEOUT / 3)
418
419 # Validates the states.
420 self.assertEqual(_RESPONSE, await call)
421 self.assertTrue(call.done())
422
423 async def test_graceful_shutdown_failed(self):
424 call = self._channel.unary_unary(_BLOCK_FOREVER)(_REQUEST)
425 await self._generic_handler.wait_for_call()
426
427 await self._server.stop(test_constants.SHORT_TIMEOUT)
428
429 with self.assertRaises(aio.AioRpcError) as exception_context:
430 await call
431 self.assertEqual(grpc.StatusCode.UNAVAILABLE,
432 exception_context.exception.code())
433
434 async def test_concurrent_graceful_shutdown(self):
435 call = self._channel.unary_unary(_BLOCK_BRIEFLY)(_REQUEST)
436 await self._generic_handler.wait_for_call()
437
438 # Expects the shortest grace period to be effective.
439 shutdown_start_time = time.time()
440 await asyncio.gather(
441 self._server.stop(test_constants.LONG_TIMEOUT),
442 self._server.stop(test_constants.SHORT_TIMEOUT),
443 self._server.stop(test_constants.LONG_TIMEOUT),
444 )
445 grace_period_length = time.time() - shutdown_start_time
446 self.assertGreater(grace_period_length,
447 test_constants.SHORT_TIMEOUT / 3)
448
449 self.assertEqual(_RESPONSE, await call)
450 self.assertTrue(call.done())
451
452 async def test_concurrent_graceful_shutdown_immediate(self):
453 call = self._channel.unary_unary(_BLOCK_FOREVER)(_REQUEST)
454 await self._generic_handler.wait_for_call()
455
456 # Expects no grace period, due to the "server.stop(None)".
457 await asyncio.gather(
458 self._server.stop(test_constants.LONG_TIMEOUT),
459 self._server.stop(None),
460 self._server.stop(test_constants.SHORT_TIMEOUT),
461 self._server.stop(test_constants.LONG_TIMEOUT),
462 )
463
464 with self.assertRaises(aio.AioRpcError) as exception_context:
465 await call
466 self.assertEqual(grpc.StatusCode.UNAVAILABLE,
467 exception_context.exception.code())
468
469 async def test_shutdown_before_call(self):
470 await self._server.stop(None)
471
472 # Ensures the server is cleaned up at this point.
473 # Some proper exception should be raised.
474 with self.assertRaises(aio.AioRpcError):
475 await self._channel.unary_unary(_SIMPLE_UNARY_UNARY)(_REQUEST)
476
477 async def test_unimplemented(self):
478 call = self._channel.unary_unary(_UNIMPLEMENTED_METHOD)
479 with self.assertRaises(aio.AioRpcError) as exception_context:
480 await call(_REQUEST)
481 rpc_error = exception_context.exception
482 self.assertEqual(grpc.StatusCode.UNIMPLEMENTED, rpc_error.code())
483
484 async def test_shutdown_during_stream_stream(self):
485 stream_stream_call = self._channel.stream_stream(
486 _STREAM_STREAM_ASYNC_GEN)
487 call = stream_stream_call()
488
489 # Don't half close the RPC yet, keep it alive.
490 await call.write(_REQUEST)
491 await self._server.stop(None)
492
493 self.assertEqual(grpc.StatusCode.UNAVAILABLE, await call.code())
494 # No segfault
495
496 async def test_error_in_stream_stream(self):
497 stream_stream_call = self._channel.stream_stream(
498 _ERROR_IN_STREAM_STREAM)
499 call = stream_stream_call()
500
501 # Don't half close the RPC yet, keep it alive.
502 await call.write(_REQUEST)
503
504 # Don't segfault here
505 self.assertEqual(grpc.StatusCode.UNKNOWN, await call.code())
506
507 async def test_error_without_raise_in_unary_unary(self):
508 call = self._channel.unary_unary(_ERROR_WITHOUT_RAISE_IN_UNARY_UNARY)(
509 _REQUEST)
510
511 with self.assertRaises(aio.AioRpcError) as exception_context:
512 await call
513
514 rpc_error = exception_context.exception
515 self.assertEqual(grpc.StatusCode.INTERNAL, rpc_error.code())
516
517 async def test_error_without_raise_in_stream_stream(self):
518 call = self._channel.stream_stream(
519 _ERROR_WITHOUT_RAISE_IN_STREAM_STREAM)()
520
521 for _ in range(_NUM_STREAM_REQUESTS):
522 await call.write(_REQUEST)
523 await call.done_writing()
524
525 self.assertEqual(grpc.StatusCode.INTERNAL, await call.code())
526
527 async def test_error_in_stream_unary(self):
528 stream_unary_call = self._channel.stream_unary(_ERROR_IN_STREAM_UNARY)
529
530 async def request_gen():
531 for _ in range(_NUM_STREAM_REQUESTS):
532 yield _REQUEST
533
534 call = stream_unary_call(request_gen())
535
536 with self.assertRaises(aio.AioRpcError) as exception_context:
537 await call
538 rpc_error = exception_context.exception
539 self.assertEqual(grpc.StatusCode.UNKNOWN, rpc_error.code())
540
541 async def test_port_binding_exception(self):
542 server = aio.server(options=(('grpc.so_reuseport', 0),))
543 port = server.add_insecure_port('localhost:0')
544 bind_address = "localhost:%d" % port
545
546 with self.assertRaises(RuntimeError):
547 server.add_insecure_port(bind_address)
548
549 server_credentials = grpc.ssl_server_credentials([
550 (resources.private_key(), resources.certificate_chain())
551 ])
552 with self.assertRaises(RuntimeError):
553 server.add_secure_port(bind_address, server_credentials)
554
555 async def test_maximum_concurrent_rpcs(self):
556 # Build the server with concurrent rpc argument
557 server = aio.server(maximum_concurrent_rpcs=_MAXIMUM_CONCURRENT_RPCS)
558 port = server.add_insecure_port('localhost:0')
559 bind_address = "localhost:%d" % port
560 server.add_generic_rpc_handlers((_GenericHandler(),))
561 await server.start()
562 # Build the channel
563 channel = aio.insecure_channel(bind_address)
564 # Deplete the concurrent quota with 3 times of max RPCs
565 rpcs = []
566 for _ in range(3 * _MAXIMUM_CONCURRENT_RPCS):
567 rpcs.append(channel.unary_unary(_BLOCK_BRIEFLY)(_REQUEST))
568 task = self.loop.create_task(
569 asyncio.wait(rpcs, return_when=asyncio.FIRST_EXCEPTION))
570 # Each batch took test_constants.SHORT_TIMEOUT /2
571 start_time = time.time()
572 await task
573 elapsed_time = time.time() - start_time
574 self.assertGreater(elapsed_time, test_constants.SHORT_TIMEOUT * 3 / 2)
575 # Clean-up
576 await channel.close()
577 await server.stop(0)
578
579 async def test_invalid_trailing_metadata(self):
580 call = self._channel.unary_unary(_INVALID_TRAILING_METADATA)(_REQUEST)
581
582 with self.assertRaises(aio.AioRpcError) as exception_context:
583 await call
584
585 rpc_error = exception_context.exception
586 self.assertEqual(grpc.StatusCode.UNKNOWN, rpc_error.code())
587 self.assertIn('trailing', rpc_error.details())
588
589
590 if __name__ == '__main__':
591 logging.basicConfig(level=logging.DEBUG)
592 unittest.main(verbosity=2)