简体   繁体   English

如何编写 GRPC python unittest

[英]How to write a GRPC python unittest

We are using grpc as the RPC protocol for all our internal system.我们使用 grpc 作为我们所有内部系统的 RPC 协议。 Most of the system is written in Java.大部分系统是用Java编写的。

In Java, we can use InprocessServerBuilder for unittest.在 Java 中,我们可以使用 InprocessServerBuilder 进行单元测试。 However, I haven't find a similar class in Python.但是,我还没有在 Python 中找到类似的类。

Can any one provide a sample code for how to do GRPC unittest in python?任何人都可以提供有关如何在python中进行GRPC单元测试的示例代码吗?

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.因此,暂时的测试方法是使用完整的生产堆栈来连接您的客户端和服务器端代码(或违反 API 并模拟大量内部内容)但希望在几天到几周内会好得多将为您提供解决方案。

I find pytest-grpc is easy to follow and get it works in few minutes.我发现 pytest-grpc 很容易理解,并且在几分钟内就可以运行。

src: https://pypi.org/project/pytest-grpc/源代码: https : //pypi.org/project/pytest-grpc/

Some example code to get started:一些入门示例代码:

proto原型

syntax = "proto3";

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

message Request {
    string id = 1;
}

message Response {
    string status = 1;
}

python unit test python单元测试

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

import unittest

from grpc import StatusCode
from grpc_testing import server_from_dictionary, strict_real_time
from proto import rpc_pb2

class TestCase(unittest.TestCase):

    def __init__(self, methodName) -> None:
        super().__init__(methodName)

        servicers = {
            rpc_pb2.DESCRIPTOR.services_by_name['Library']: LibraryServicer()
        }
        self.test_server = server_from_dictionary(
            servicers, strict_real_time())

    def test_search(self):
        request = rpc_pb2.Request(
            id=2,
        )
        method = self.test_server.invoke_unary_unary(
            method_descriptor=(rpc_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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM