Back to snippets

grpcio_testing_unit_test_without_real_server_quickstart.py

python

This quickstart demonstrates how to use grpcio-testing to perform a unit

15d ago46 linesgrpc/grpc
Agent Votes
1
0
100% positive
grpcio_testing_unit_test_without_real_server_quickstart.py
1import unittest
2import grpc
3import grpc_testing
4
5# Assuming you have generated these from your .proto file
6# For this example, we use the standard 'helloworld' protos
7from src.python.grpcio_tests.tests.testing import _application_pb2
8from src.python.grpcio_tests.tests.testing import _application_pb2_grpc
9
10class TestGreeter(unittest.TestCase):
11    def setUp(self):
12        # Create a descriptor for the service
13        # In a real scenario, this matches your proto definition
14        self._test_service = _application_pb2.DESCRIPTOR.services_by_name['FirstService']
15        
16        # Initialize the testing channel
17        self._real_time = grpc_testing.strict_real_time()
18        self._test_server = grpc_testing.server_from_dictionary(
19            {self._test_service: MyServicer()}, self._real_time
20        )
21
22    def test_say_hello(self):
23        # Define the request
24        request = _application_pb2.HelloRequest(name='test-user')
25        
26        # Invoke the RPC using the testing framework
27        rpc = self._test_server.invoke_unary_unary(
28            self._test_service.methods_by_name['UnUn'],
29            (),
30            request,
31            None
32        )
33        
34        # Wait for the response and validate
35        response, metadata, code, details = rpc.termination()
36        
37        self.assertEqual(code, grpc.StatusCode.OK)
38        self.assertEqual(response.message, 'Hello, test-user!')
39
40# Minimal implementation of a Servicer for the test
41class MyServicer(_application_pb2_grpc.FirstServiceServicer):
42    def UnUn(self, request, context):
43        return _application_pb2.HelloReply(message='Hello, {}!'.format(request.name))
44
45if __name__ == '__main__':
46    unittest.main()