helloworld.py 2.5 KB

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