| 1 |
# Copyright 2021 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 |
"""Test the time_remaining() method of async ServicerContext.""" |
| 15 |
|
| 16 |
import asyncio |
| 17 |
import datetime |
| 18 |
import logging |
| 19 |
import unittest |
| 20 |
|
| 21 |
import grpc |
| 22 |
from grpc import aio |
| 23 |
|
| 24 |
from tests_aio.unit._common import ADHOC_METHOD |
| 25 |
from tests_aio.unit._common import AdhocGenericHandler |
| 26 |
from tests_aio.unit._test_base import AioTestBase |
| 27 |
|
| 28 |
_REQUEST = b'\x09\x05' |
| 29 |
_REQUEST_TIMEOUT_S = datetime.timedelta(seconds=5).total_seconds() |
| 30 |
|
| 31 |
|
| 32 |
class TestServerTimeRemaining(AioTestBase): |
| 33 |
|
| 34 |
async def setUp(self): |
| 35 |
# Create async server |
| 36 |
self._server = aio.server(options=(('grpc.so_reuseport', 0),)) |
| 37 |
self._adhoc_handlers = AdhocGenericHandler() |
| 38 |
self._server.add_generic_rpc_handlers((self._adhoc_handlers,)) |
| 39 |
port = self._server.add_insecure_port('[::]:0') |
| 40 |
address = 'localhost:%d' % port |
| 41 |
await self._server.start() |
| 42 |
# Create async channel |
| 43 |
self._channel = aio.insecure_channel(address) |
| 44 |
|
| 45 |
async def tearDown(self): |
| 46 |
await self._channel.close() |
| 47 |
await self._server.stop(None) |
| 48 |
|
| 49 |
async def test_servicer_context_time_remaining(self): |
| 50 |
seen_time_remaining = [] |
| 51 |
|
| 52 |
@grpc.unary_unary_rpc_method_handler |
| 53 |
def log_time_remaining(request: bytes, |
| 54 |
context: grpc.ServicerContext) -> bytes: |
| 55 |
seen_time_remaining.append(context.time_remaining()) |
| 56 |
return b"" |
| 57 |
|
| 58 |
# Check if the deadline propagates properly |
| 59 |
self._adhoc_handlers.set_adhoc_handler(log_time_remaining) |
| 60 |
await self._channel.unary_unary(ADHOC_METHOD)( |
| 61 |
_REQUEST, timeout=_REQUEST_TIMEOUT_S) |
| 62 |
self.assertGreater(seen_time_remaining[0], _REQUEST_TIMEOUT_S / 2) |
| 63 |
# Check if there is no timeout, the time_remaining will be None |
| 64 |
self._adhoc_handlers.set_adhoc_handler(log_time_remaining) |
| 65 |
await self._channel.unary_unary(ADHOC_METHOD)(_REQUEST) |
| 66 |
self.assertIsNone(seen_time_remaining[1]) |
| 67 |
|
| 68 |
|
| 69 |
if __name__ == '__main__': |
| 70 |
logging.basicConfig(level=logging.DEBUG) |
| 71 |
unittest.main(verbosity=2) |