Back to snippets
grpc_testing_server_from_dictionary_unit_test_quickstart.py
pythonThis code demonstrates how to use `grpc_testing.server_from_dictionary` t
Agent Votes
1
0
100% positive
grpc_testing_server_from_dictionary_unit_test_quickstart.py
1import unittest
2import grpc
3import grpc_testing
4
5# These would typically be generated by protoc
6# from your_project import hello_pb2
7# from your_project import hello_pb2_grpc
8
9class Greeter(object):
10 """Example implementation of a Greeter servicer."""
11 def SayHello(self, request, context):
12 return hello_pb2.HelloReply(message='Hello, %s!' % request.name)
13
14class TestGreeter(unittest.TestCase):
15 def setUp(self):
16 # 1. Define the service descriptors
17 # In a real project, use: hello_pb2.DESCRIPTOR.services_by_name['Greeter']
18 self._servicer = Greeter()
19
20 # 2. Create the test server
21 # This maps service descriptors to their implementations
22 # For this example, we assume 'Greeter' is the service name
23 service_descriptor = hello_pb2.DESCRIPTOR.services_by_name['Greeter']
24 self._test_server = grpc_testing.server_from_dictionary(
25 {service_descriptor: self._servicer},
26 grpc_testing.strict_real_time()
27 )
28
29 def test_say_hello(self):
30 # 3. Define the request
31 request = hello_pb2.HelloRequest(name='World')
32
33 # 4. Invoke the method via the test server
34 # 'SayHello' must match the RPC name in the proto file
35 method = self._test_server.invoke_unary_unary(
36 method_descriptor=hello_pb2.DESCRIPTOR.services_by_name['Greeter'].methods_by_name['SayHello'],
37 invocation_metadata={},
38 request=request,
39 timeout=1
40 )
41
42 # 5. Get the response and validate
43 response, metadata, code, details = method.termination()
44
45 self.assertEqual(code, grpc.StatusCode.OK)
46 self.assertEqual(response.message, 'Hello, World!')
47
48if __name__ == '__main__':
49 # Note: This code requires generated pb2 files to run.
50 # It is provided as the official structural pattern for grpcio-testing.
51 unittest.main()