1#include <gtest/gtest.h>
3#include <google/protobuf/util/json_util.h>
5#include <userver/formats/json/serialize.hpp>
6#include <userver/protobuf/json/convert.hpp>
7#include <userver/utest/assert_macros.hpp>
11USERVER_NAMESPACE_BEGIN
15using ProtobufStringType =
16 decltype(std::declval<::google::protobuf::Reflection>()
17 .GetString(std::declval<
const ::google::protobuf::Message&>(),
nullptr));
19TEST(ComplexToJsonSuccessTest, Test) {
20 proto_json::messages::ComplexMessage message;
21 proto_json::messages::ComplexMessage::Bottom bottom_message;
23 for (
int i = 1; i <= 2; ++i) {
24 auto inter = message.add_inters();
25 auto bottoms = inter->mutable_bottoms();
26 (*bottoms)[
"aaa"].set_field1(i * 10);
27 (*bottoms)[
"aaa"].mutable_field2()->set_seconds(i * 1);
28 (*bottoms)[
"aaa"].mutable_field2()->set_nanos(i * 2);
29 (*bottoms)[
"bbb"].set_field1(i * 20);
30 (*bottoms)[
"bbb"].mutable_field2()->set_seconds(i * 3);
31 (*bottoms)[
"bbb"].mutable_field2()->set_nanos(i * 4);
34 formats::json::ValueBuilder builder;
37 formats::json::Value json, expected_json, sample_json;
38 json = builder.ExtractValue();
40 expected_json = formats::json::FromString(
42 "inters": [
43 {
44 "bottoms": {
45 "aaa": {"field1":10, "field2":"1.000000002s"},
46 "bbb": {"field1":20, "field2":"3.000000004s"}
47 }
48 },
49 {
50 "bottoms": {
51 "aaa": {"field1":20, "field2":"2.000000004s"},
52 "bbb": {"field1":40, "field2":"6.000000008s"}
53 }
54 }
55 ]
56 })"
60 ProtobufStringType sample_json_str;
61 ASSERT_TRUE(::google::protobuf::util::MessageToJsonString(message, &sample_json_str).ok());
62 UASSERT_NO_THROW((sample_json = formats::json::FromString(sample_json_str)));
64 EXPECT_EQ(json, expected_json);
65 EXPECT_EQ(expected_json, sample_json);
68 (bottom_message = json[
"inters"][1][
"bottoms"][
"aaa"].As<proto_json::messages::ComplexMessage::Bottom>())
70 EXPECT_EQ(bottom_message.field1(), std::uint32_t{20});
71 EXPECT_EQ(bottom_message.field2().seconds(), 2);
72 EXPECT_EQ(bottom_message.field2().nanos(), 4);
75TEST(ComplexToJsonFailureTest, Test) {
76 proto_json::messages::ComplexMessage message;
77 proto_json::messages::ComplexMessage::Bottom bottom_message;
79 auto inter = message.add_inters();
80 auto bottoms = inter->mutable_bottoms();
81 (*bottoms)[
"aaa"].set_field1(10);
82 (*bottoms)[
"aaa"].mutable_field2()->set_seconds(1);
83 (*bottoms)[
"aaa"].mutable_field2()->set_nanos(-1);
85 formats::json::ValueBuilder builder;
86 EXPECT_WRITE_ERROR((builder = message), WriteErrorCode::kInvalidValue,
"inters[0].bottoms['aaa'].field2");