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