How to write a GRPC python unittest

How serendipitous that you have asked this question today; our unit test framework just entered code review. So for the time being the way to test is to use the full production stack to connect your client-side and server-side code (or to violate the API and mock a lot of internal stuff) but hopefully in days to weeks the much better solution will be available to you.


Some example code to get started:

proto

syntax = "proto3";

service MyLibrary {
    rpc Search (Request) returns (Response);
}

message Request {
    string id = 1;
}

message Response {
    string status = 1;
}

python unit test

#!/usr/bin/env python
# coding=utf-8

import unittest

from grpc import StatusCode
from grpc_testing import server_from_dictionary, strict_real_time
import mylibrary_pb2

class TestCase(unittest.TestCase):

    def __init__(self, methodName) -> None:
        super().__init__(methodName)
        
        myServicer = MyLibraryServicer()
        servicers = {
            mylibrary_pb2.DESCRIPTOR.services_by_name['MyLibrary']: myServicer
        }
        self.test_server = server_from_dictionary(
            servicers, strict_real_time())

    def test_search(self):
        request = mylibrary_pb2.Request(
            id=2,
        )
        method = self.test_server.invoke_unary_unary(
            method_descriptor=(mylibrary_pb2.DESCRIPTOR
                .services_by_name['Library']
                .methods_by_name['Search']),
            invocation_metadata={},
            request=request, timeout=1)

        response, metadata, code, details = method.termination()
        self.assertTrue(bool(response.status))
        self.assertEqual(code, StatusCode.OK)

if __name__ == '__main__':
    unittest.main()