brpc_proto_unittest.cpp 2.27 KB
Newer Older
gejun's avatar
gejun committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
// Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved

// Author: The baidu-rpc authors (pbrpc@baidu.com)
// Date: 2015/03/31 14:50:20


#include <gtest/gtest.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/dynamic_message.h>
#include "brpc/policy/baidu_rpc_meta.pb.h"
#include "test/echo.pb.h"

namespace {
using namespace google::protobuf;
using namespace brpc;

void BuildDependency(const FileDescriptor *file_desc, DescriptorPool *pool) {
    for (int i = 0; i < file_desc->dependency_count(); ++i) {
        const FileDescriptor *fd = file_desc->dependency(i);
        BuildDependency(fd, pool);
        FileDescriptorProto proto;
        fd->CopyTo(&proto);
        ASSERT_TRUE(pool->BuildFile(proto) != NULL);
    }
    FileDescriptorProto proto;
    file_desc->CopyTo(&proto);
    ASSERT_TRUE(pool->BuildFile(proto) != NULL);
}

TEST(ProtoTest, proto) {
    policy::RpcMeta meta;
    const Descriptor *desc = meta.GetDescriptor();
    const FileDescriptor *file_desc = desc->file();
    DescriptorPool pool;
    DynamicMessageFactory factory(&pool);
    BuildDependency(file_desc, &pool);
    FileDescriptorProto file_desc_proto;
    file_desc->CopyTo(&file_desc_proto);
    const FileDescriptor *new_file_desc = pool.BuildFile(file_desc_proto);
    ASSERT_TRUE(new_file_desc != NULL);
    const Descriptor *new_desc = new_file_desc->FindMessageTypeByName(desc->name());
    ASSERT_TRUE(new_desc != NULL);
    meta.set_correlation_id(123);
    std::string data;
    ASSERT_TRUE(meta.SerializeToString(&data));
    Message *msg = factory.GetPrototype(new_desc)->New();
    ASSERT_TRUE(msg != NULL);
    ASSERT_TRUE(msg->ParseFromString(data));
    ASSERT_TRUE(msg->SerializeToString(&data));
    policy::RpcMeta new_meta;
    ASSERT_TRUE(new_meta.ParseFromString(data));
    ASSERT_EQ(123, new_meta.correlation_id());
}

TEST(ProtoTest, required_enum) {
    test::Message1 msg1;
    msg1.set_stat(test::STATE0_NUM_1);
    std::string buf;
    ASSERT_TRUE(msg1.SerializeToString(&buf));
    test::Message2 msg2;
    ASSERT_TRUE(msg2.ParseFromString(buf));
    ASSERT_EQ((int)msg1.stat(), (int)msg2.stat());
    msg1.set_stat(test::STATE0_NUM_2);
    ASSERT_TRUE(msg1.SerializeToString(&buf));
    ASSERT_FALSE(msg2.ParseFromString(buf));
}
} //namespace