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