Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a GRPC python unittest

We are using grpc as the RPC protocol for all our internal system. Most of the system is written in Java.

In Java, we can use InprocessServerBuilder for unittest. However, I haven't find a similar class in Python.

Can any one provide a sample code for how to do GRPC unittest in python?

like image 663
Crazymooner Avatar asked Jun 23 '17 09:06

Crazymooner


2 Answers

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()
like image 62
rpstw Avatar answered Sep 17 '22 21:09

rpstw


I find pytest-grpc is easy to follow and get it works in few minutes.

src: https://pypi.org/project/pytest-grpc/

like image 34
echo Avatar answered Sep 18 '22 21:09

echo