1 // Copyright 2019 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "util/json/json_serialization.h"
6 
7 #include <array>
8 #include <string>
9 
10 #include "gtest/gtest.h"
11 #include "platform/base/error.h"
12 
13 namespace openscreen {
14 namespace {
15 template <typename Value>
AssertError(ErrorOr<Value> error_or,Error::Code code)16 void AssertError(ErrorOr<Value> error_or, Error::Code code) {
17   EXPECT_EQ(error_or.error().code(), code);
18 }
19 }  // namespace
20 
TEST(JsonSerializationTest,MalformedDocumentReturnsParseError)21 TEST(JsonSerializationTest, MalformedDocumentReturnsParseError) {
22   const std::array<std::string, 4> kMalformedDocuments{
23       {"", "{", "{ foo: bar }", R"({"foo": "bar", "foo": baz})"}};
24 
25   for (auto& document : kMalformedDocuments) {
26     AssertError(json::Parse(document), Error::Code::kJsonParseError);
27   }
28 }
29 
TEST(JsonSerializationTest,ValidEmptyDocumentParsedCorrectly)30 TEST(JsonSerializationTest, ValidEmptyDocumentParsedCorrectly) {
31   const auto actual = json::Parse("{}");
32 
33   EXPECT_TRUE(actual.is_value());
34   EXPECT_EQ(actual.value().getMemberNames().size(), 0u);
35 }
36 
37 // Jsoncpp has its own suite of tests ensure that things are parsed correctly,
38 // so we only do some rudimentary checks here to make sure we didn't mangle
39 // the value.
TEST(JsonSerializationTest,ValidDocumentParsedCorrectly)40 TEST(JsonSerializationTest, ValidDocumentParsedCorrectly) {
41   const auto actual = json::Parse(R"({"foo": "bar", "baz": 1337})");
42 
43   EXPECT_TRUE(actual.is_value());
44   EXPECT_EQ(actual.value().getMemberNames().size(), 2u);
45 }
46 
TEST(JsonSerializationTest,NullValueReturnsError)47 TEST(JsonSerializationTest, NullValueReturnsError) {
48   const auto null_value = Json::Value();
49   const auto actual = json::Stringify(null_value);
50 
51   EXPECT_TRUE(actual.is_error());
52   EXPECT_EQ(actual.error().code(), Error::Code::kJsonWriteError);
53 }
54 
TEST(JsonSerializationTest,ValidValueReturnsString)55 TEST(JsonSerializationTest, ValidValueReturnsString) {
56   const Json::Int64 value = 31337;
57   const auto actual = json::Stringify(value);
58 
59   EXPECT_TRUE(actual.is_value());
60   EXPECT_EQ(actual.value(), "31337");
61 }
62 }  // namespace openscreen
63