【发布时间】:2022-11-11 04:06:42
【问题描述】:
我正在尝试为一些通过 gRPC 通信的 C++ 应用程序创建一些测试驱动程序。这些测试驱动程序中的大多数只是简单地使用 grpcurl 向被测应用程序发出一些消息并验证响应。
但是,我们的一些应用程序连接到流式 RPC。编写一个为我们需要的所有流提供服务的测试驱动程序应用程序将是微不足道的;但是我希望做一些更通用的东西。我的想法是编写一个应用程序,它可以接收描述符集、要服务的流式传输方法的名称,以及定义在应用程序连接到流式 RPC 时提供的消息的 JSON 文件。
解析描述符集(通过 protoc 的 --descriptor_set_out 参数生成)、获取流方法的服务和方法描述符以及加载消息以从 JSON 文件返回都非常容易。我挂断的地方实际上是从描述符创建服务。
这是我作为快速概念验证拼凑起来的代码 - 注意没有错误检查/硬编码路径,我只是想快速看看这是否可行:
#include "google/protobuf/descriptor.pb.h"
#include "google/protobuf/dynamic_message.h"
#include "google/protobuf/util/json_util.h"
#include <fstream>
#include <sstream>
int main(int argc, char** argv)
{
google::protobuf::FileDescriptorSet desc;
std::stringstream sst;
{
std::ifstream i("/tmp/test.protoset");
sst << i.rdbuf();
}
desc.ParseFromString(sst.str());
google::protobuf::DescriptorPool desc_pool;
for (const auto& fdesc : desc.file())
{
desc_pool.BuildFile(fdesc);
}
auto sdesc = desc_pool.FindServiceByName("TestService");
auto mdesc = sdesc->FindMethodByName("connect");
auto resp_type = mdesc->output_type();
google::protobuf::DynamicMessageFactory dmf(&desc_pool);
sst.str("");
sst.clear();
auto out_message = std::shared_ptr<google::protobuf::Message>(dmf.GetPrototype(resp_type)->New());
{
std::ifstream i("/tmp/test_message.json");
sst << i.rdbuf();
}
auto stat = google::protobuf::util::JsonStringToMessage(sst.str(), out_message.get());
std::cout << "READ " << stat << " " << out_message->DebugString() << std::endl;
}
现在是否可以以任何方式实际创建“TestService/connect”流式 rpc,等待连接,并返回内置于 out_message 的消息?
【问题讨论】:
标签: c++ protocol-buffers grpc