如何编写 GRPC python 单元测试

How to write a GRPC python unittest

我们正在使用 grpc 作为我们所有内部系统的 RPC 协议。大部分系统都是用Java写的。

在Java中,我们可以使用InprocessServerBuilder进行单元测试。但是,我在Python.

中没有找到类似的class

任何人都可以提供有关如何在 python 中进行 GRPC 单元测试的示例代码吗?

你今天问这个问题真是太巧了; 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(或违反 API 并模拟大量内部内容)但希望在几天到几周内,您会得到更好的解决方案。

我发现 pytest-grpc 很容易理解,几分钟后就可以使用。

来源:https://pypi.org/project/pytest-grpc/

一些入门示例代码:

原型

syntax = "proto3";

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

message Request {
    string id = 1;
}

message Response {
    string status = 1;
}

python单元测试

#!/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()