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"""The Python implementation of the GRPC helloworld.Greeter client.""" 15 16from concurrent import futures 17import contextlib 18import datetime 19import logging 20import unittest 21 22# TODO(https://github.com/grpc/grpc/issues/29284) 23# isort: off 24import grpc 25from google.protobuf import duration_pb2 26from google.protobuf import timestamp_pb2 27from google.cloud import helloworld_pb2 28from google.cloud import helloworld_pb2_grpc 29 30# isort: on 31 32_HOST = "localhost" 33_SERVER_ADDRESS = "{}:0".format(_HOST) 34 35 36class Greeter(helloworld_pb2_grpc.GreeterServicer): 37 def SayHello(self, request, context): 38 request_in_flight = ( 39 datetime.datetime.now() - request.request_initiation.ToDatetime() 40 ) 41 request_duration = duration_pb2.Duration() 42 request_duration.FromTimedelta(request_in_flight) 43 return helloworld_pb2.HelloReply( 44 message="Hello, %s!" % request.name, 45 request_duration=request_duration, 46 ) 47 48 49@contextlib.contextmanager 50def _listening_server(): 51 server = grpc.server(futures.ThreadPoolExecutor()) 52 helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server) 53 port = server.add_insecure_port(_SERVER_ADDRESS) 54 server.start() 55 try: 56 yield port 57 finally: 58 server.stop(0) 59 60 61class ImportTest(unittest.TestCase): 62 def test_import(self): 63 with _listening_server() as port: 64 with grpc.insecure_channel("{}:{}".format(_HOST, port)) as channel: 65 stub = helloworld_pb2_grpc.GreeterStub(channel) 66 request_timestamp = timestamp_pb2.Timestamp() 67 request_timestamp.GetCurrentTime() 68 response = stub.SayHello( 69 helloworld_pb2.HelloRequest( 70 name="you", 71 request_initiation=request_timestamp, 72 ), 73 wait_for_ready=True, 74 ) 75 self.assertEqual(response.message, "Hello, you!") 76 self.assertGreater(response.request_duration.nanos, 0) 77 78 79if __name__ == "__main__": 80 logging.basicConfig() 81 unittest.main() 82