json/test/src/unit-udt.cpp

644 lines
16 KiB
C++
Raw Normal View History

/*
__ _____ _____ _____
__| | __| | | | JSON for Modern C++ (test suite)
2016-11-17 03:49:24 +08:00
| | |__ | | | | | | version 2.0.7
|_____|_____|_____|_|___| https://github.com/nlohmann/json
Licensed under the MIT License <http://opensource.org/licenses/MIT>.
Copyright (c) 2013-2016 Niels Lohmann <http://nlohmann.me>.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <array>
#include <map>
#include <string>
#include <memory>
#include "catch.hpp"
#include "json.hpp"
2016-12-15 07:06:37 +08:00
using nlohmann::json;
namespace udt
{
enum class country
{
2016-12-14 07:03:55 +08:00
china,
france,
russia
};
2016-12-14 07:03:55 +08:00
struct age
{
2016-12-01 06:16:54 +08:00
int m_val;
};
2016-10-18 05:41:53 +08:00
struct name
{
2016-12-01 06:16:54 +08:00
std::string m_val;
};
struct address
{
2016-12-01 06:16:54 +08:00
std::string m_val;
};
struct person
{
2016-12-01 06:16:54 +08:00
age m_age;
name m_name;
2016-12-14 07:03:55 +08:00
country m_country;
};
struct contact
{
2016-12-01 06:16:54 +08:00
person m_person;
address m_address;
};
struct contact_book
{
2016-12-01 06:16:54 +08:00
name m_book_name;
std::vector<contact> m_contacts;
};
}
2016-10-18 05:41:53 +08:00
2016-12-14 07:03:55 +08:00
// to_json methods
namespace udt
2016-10-18 05:41:53 +08:00
{
// templates because of the custom_json tests (see below)
template <typename Json>
void to_json(Json& j, age a)
{
2016-12-01 06:16:54 +08:00
j = a.m_val;
}
2016-10-18 05:41:53 +08:00
template <typename Json>
void to_json(Json& j, name const& n)
{
2016-12-01 06:16:54 +08:00
j = n.m_val;
}
2016-10-18 05:41:53 +08:00
template <typename Json>
void to_json(Json& j, country c)
{
2016-12-14 07:03:55 +08:00
switch (c)
{
case country::china:
j = u8"中华人民共和国";
return;
case country::france:
j = "France";
return;
case country::russia:
j = u8"Российская Федерация";
return;
2016-12-14 07:03:55 +08:00
}
}
2016-12-14 07:03:55 +08:00
template <typename Json>
void to_json(Json& j, person const& p)
{
2016-12-15 07:06:37 +08:00
j = Json{{"age", p.m_age}, {"name", p.m_name}, {"country", p.m_country}};
}
2016-10-18 05:41:53 +08:00
void to_json(nlohmann::json& j, address const& a)
{
2016-12-01 06:16:54 +08:00
j = a.m_val;
}
2016-10-18 05:41:53 +08:00
void to_json(nlohmann::json& j, contact const& c)
{
j = json{{"person", c.m_person}, {"address", c.m_address}};
}
2016-10-18 05:41:53 +08:00
void to_json(nlohmann::json& j, contact_book const& cb)
{
j = json{{"name", cb.m_book_name}, {"contacts", cb.m_contacts}};
}
2016-12-01 06:16:54 +08:00
// operators
bool operator==(age lhs, age rhs)
{
2016-12-01 06:16:54 +08:00
return lhs.m_val == rhs.m_val;
}
2016-12-01 06:16:54 +08:00
bool operator==(address const& lhs, address const& rhs)
{
2016-12-01 06:16:54 +08:00
return lhs.m_val == rhs.m_val;
}
2016-12-01 06:16:54 +08:00
bool operator==(name const& lhs, name const& rhs)
{
2016-12-01 06:16:54 +08:00
return lhs.m_val == rhs.m_val;
}
2016-12-01 06:16:54 +08:00
bool operator==(person const& lhs, person const& rhs)
{
2016-12-01 06:16:54 +08:00
return std::tie(lhs.m_name, lhs.m_age) == std::tie(rhs.m_name, rhs.m_age);
}
2016-12-01 06:16:54 +08:00
bool operator==(contact const& lhs, contact const& rhs)
{
2016-12-01 06:16:54 +08:00
return std::tie(lhs.m_person, lhs.m_address) ==
std::tie(rhs.m_person, rhs.m_address);
}
2016-12-01 06:16:54 +08:00
bool operator==(contact_book const& lhs, contact_book const& rhs)
{
2016-12-01 06:16:54 +08:00
return std::tie(lhs.m_book_name, lhs.m_contacts) ==
std::tie(rhs.m_book_name, rhs.m_contacts);
}
2016-12-01 06:16:54 +08:00
}
2016-12-14 07:03:55 +08:00
// from_json methods
2016-12-01 06:16:54 +08:00
namespace udt
{
template <typename Json>
void from_json(Json const& j, age& a)
{
a.m_val = j.template get<int>();
}
2016-12-01 06:16:54 +08:00
template <typename Json>
void from_json(Json const& j, name& n)
{
n.m_val = j.template get<std::string>();
}
2016-12-01 06:16:54 +08:00
template <typename Json>
void from_json(Json const& j, country& c)
{
const auto str = j.template get<std::string>();
static const std::map<std::string, country> m =
{
2016-12-14 07:03:55 +08:00
{u8"中华人民共和国", country::china},
{"France", country::france},
{"Российская Федерация", country::russia}
};
2016-12-14 07:03:55 +08:00
const auto it = m.find(str);
// TODO test exceptions
c = it->second;
}
2016-12-14 07:03:55 +08:00
template <typename Json>
void from_json(Json const& j, person& p)
{
p.m_age = j["age"].template get<age>();
p.m_name = j["name"].template get<name>();
p.m_country = j["country"].template get<country>();
}
2016-12-01 06:16:54 +08:00
void from_json(nlohmann::json const& j, address& a)
{
2016-12-01 06:16:54 +08:00
a.m_val = j.get<std::string>();
}
2016-12-01 06:16:54 +08:00
void from_json(nlohmann::json const& j, contact& c)
{
2016-12-01 06:16:54 +08:00
c.m_person = j["person"].get<person>();
c.m_address = j["address"].get<address>();
}
2016-12-01 06:16:54 +08:00
void from_json(nlohmann::json const& j, contact_book& cb)
{
2016-12-01 06:16:54 +08:00
cb.m_book_name = j["name"].get<name>();
cb.m_contacts = j["contacts"].get<std::vector<contact>>();
}
2016-10-18 05:41:53 +08:00
}
2016-11-15 21:22:12 +08:00
TEST_CASE("basic usage", "[udt]")
2016-11-15 21:22:12 +08:00
{
// a bit narcissic maybe :) ?
const udt::age a
{
23
};
const udt::name n{"theo"};
const udt::country c{udt::country::france};
const udt::person sfinae_addict{a, n, c};
const udt::person senior_programmer{{42}, {u8"王芳"}, udt::country::china};
const udt::address addr{"Paris"};
const udt::contact cpp_programmer{sfinae_addict, addr};
const udt::contact_book book{{"C++"}, {cpp_programmer, {senior_programmer, addr}}};
SECTION("conversion to json via free-functions")
{
CHECK(json(a) == json(23));
CHECK(json(n) == json("theo"));
CHECK(json(c) == json("France"));
CHECK(json(sfinae_addict) == R"({"name":"theo", "age":23, "country":"France"})"_json);
CHECK(json("Paris") == json(addr));
CHECK(json(cpp_programmer) ==
R"({"person" : {"age":23, "name":"theo", "country":"France"}, "address":"Paris"})"_json);
CHECK(
json(book) ==
u8R"({"name":"C++", "contacts" : [{"person" : {"age":23, "name":"theo", "country":"France"}, "address":"Paris"}, {"person" : {"age":42, "country":"", "name":""}, "address":"Paris"}]})"_json);
}
SECTION("conversion from json via free-functions")
{
const auto big_json =
u8R"({"name":"C++", "contacts" : [{"person" : {"age":23, "name":"theo", "country":"France"}, "address":"Paris"}, {"person" : {"age":42, "country":"", "name":""}, "address":"Paris"}]})"_json;
const auto parsed_book = big_json.get<udt::contact_book>();
const auto book_name = big_json["name"].get<udt::name>();
const auto contacts = big_json["contacts"].get<std::vector<udt::contact>>();
const auto contact_json = big_json["contacts"].at(0);
const auto contact = contact_json.get<udt::contact>();
const auto person = contact_json["person"].get<udt::person>();
const auto address = contact_json["address"].get<udt::address>();
const auto age = contact_json["person"]["age"].get<udt::age>();
const auto country = contact_json["person"]["country"].get<udt::country>();
const auto name = contact_json["person"]["name"].get<udt::name>();
CHECK(age == a);
CHECK(name == n);
CHECK(country == c);
CHECK(address == addr);
CHECK(person == sfinae_addict);
CHECK(contact == cpp_programmer);
CHECK(contacts == book.m_contacts);
CHECK(book_name == udt::name{"C++"});
CHECK(book == parsed_book);
}
2016-12-01 06:16:54 +08:00
}
2016-12-14 05:01:38 +08:00
namespace udt
{
struct legacy_type
{
std::string number;
2016-12-14 05:01:38 +08:00
};
}
namespace nlohmann
{
template <typename T>
2016-12-15 07:06:37 +08:00
struct adl_serializer<std::shared_ptr<T>>
2016-12-14 05:01:38 +08:00
{
static void to_json(json& j, std::shared_ptr<T> const& opt)
{
if (opt)
{
j = *opt;
}
else
{
j = nullptr;
}
}
static void from_json(json const& j, std::shared_ptr<T>& opt)
{
if (j.is_null())
{
opt = nullptr;
}
else
{
opt.reset(new T(j.get<T>()));
}
}
2016-12-14 05:01:38 +08:00
};
template <>
struct adl_serializer<udt::legacy_type>
{
static void to_json(json& j, udt::legacy_type const& l)
{
j = std::stoi(l.number);
}
2016-12-14 05:01:38 +08:00
static void from_json(json const& j, udt::legacy_type& l)
{
l.number = std::to_string(j.get<int>());
}
2016-12-14 05:01:38 +08:00
};
}
TEST_CASE("adl_serializer specialization", "[udt]")
{
SECTION("partial specialization")
2016-12-14 05:01:38 +08:00
{
SECTION("to_json")
{
std::shared_ptr<udt::person> optPerson;
2016-12-14 05:01:38 +08:00
json j = optPerson;
CHECK(j.is_null());
2016-12-14 05:01:38 +08:00
optPerson.reset(new udt::person{{42}, {"John Doe"}});
j = optPerson;
CHECK_FALSE(j.is_null());
2016-12-14 05:01:38 +08:00
CHECK(j.get<udt::person>() == *optPerson);
}
2016-12-14 05:01:38 +08:00
SECTION("from_json")
{
auto person = udt::person{{42}, {"John Doe"}};
json j = person;
2016-12-14 05:01:38 +08:00
auto optPerson = j.get<std::shared_ptr<udt::person>>();
REQUIRE(optPerson);
CHECK(*optPerson == person);
2016-12-14 05:01:38 +08:00
j = nullptr;
optPerson = j.get<std::shared_ptr<udt::person>>();
CHECK(!optPerson);
}
2016-12-14 05:01:38 +08:00
}
SECTION("total specialization")
2016-12-14 05:01:38 +08:00
{
SECTION("to_json")
{
udt::legacy_type lt{"4242"};
json j = lt;
CHECK(j.get<int>() == 4242);
}
SECTION("from_json")
{
json j = 4242;
auto lt = j.get<udt::legacy_type>();
CHECK(lt.number == "4242");
}
2016-12-14 05:01:38 +08:00
}
}
2016-12-15 07:06:37 +08:00
namespace nlohmann
{
2017-01-09 07:29:00 +08:00
template <>
struct adl_serializer<std::vector<float>>
{
static void to_json(json& j, std::vector<float> const&)
{
j = "hijacked!";
}
static void from_json(json const&, std::vector<float>& opt)
{
opt = {42.0, 42.0, 42.0};
}
};
2016-12-15 07:06:37 +08:00
}
2017-01-09 07:29:00 +08:00
TEST_CASE("even supported types can be specialized", "[udt]")
2016-12-15 07:06:37 +08:00
{
2017-01-09 07:29:00 +08:00
json j = std::vector<float> {1.0, 2.0, 3.0};
CHECK(j.dump() == R"("hijacked!")");
auto f = j.get<std::vector<float>>();
CHECK((f == std::vector<float>{42.0, 42.0, 42.0}));
2016-12-15 07:06:37 +08:00
}
namespace nlohmann
{
template <typename T>
struct adl_serializer<std::unique_ptr<T>>
{
static void to_json(json& j, std::unique_ptr<T> const& opt)
{
if (opt)
{
j = *opt;
}
else
{
j = nullptr;
}
}
// this is the overload needed for non-copyable types,
static std::unique_ptr<T> from_json(json const& j)
{
if (j.is_null())
{
return nullptr;
}
else
{
return std::unique_ptr<T>(new T(j.get<T>()));
}
}
2016-12-15 07:06:37 +08:00
};
}
TEST_CASE("Non-copyable types", "[udt]")
{
SECTION("to_json")
{
std::unique_ptr<udt::person> optPerson;
2016-12-15 07:06:37 +08:00
json j = optPerson;
CHECK(j.is_null());
2016-12-15 07:06:37 +08:00
2017-01-09 07:29:00 +08:00
optPerson.reset(new udt::person{{42}, {"John Doe"}, udt::country::russia});
j = optPerson;
CHECK_FALSE(j.is_null());
2016-12-15 07:06:37 +08:00
CHECK(j.get<udt::person>() == *optPerson);
}
2016-12-15 07:06:37 +08:00
SECTION("from_json")
{
2017-01-09 07:29:00 +08:00
auto person = udt::person{{42}, {"John Doe"}, udt::country::russia};
json j = person;
2016-12-15 07:06:37 +08:00
auto optPerson = j.get<std::unique_ptr<udt::person>>();
REQUIRE(optPerson);
CHECK(*optPerson == person);
2016-12-15 07:06:37 +08:00
j = nullptr;
optPerson = j.get<std::unique_ptr<udt::person>>();
CHECK(!optPerson);
}
2016-12-15 07:06:37 +08:00
}
2017-01-09 07:29:00 +08:00
// custom serializer - advanced usage
// pack structs that are pod-types (but not scalar types)
// relies on adl for any other type
template <typename T, typename = void>
2016-12-15 07:06:37 +08:00
struct pod_serializer
{
2017-01-09 07:29:00 +08:00
// use adl for non-pods, or scalar types
template <
typename Json, typename U = T,
typename std::enable_if<
not(std::is_pod<U>::value and std::is_class<U>::value), int>::type = 0>
static void from_json(Json const &j, U &t)
{
using nlohmann::from_json;
from_json(j, t);
}
// special behaviour for pods
template <typename Json, typename U = T,
typename std::enable_if<
std::is_pod<U>::value and std::is_class<U>::value, int>::type = 0>
static void from_json(Json const &j, U &t)
{
std::uint64_t value;
// TODO The following block is no longer relevant in this serializer, make another one that shows the issue
// the problem arises only when one from_json method is defined without any constraint
//
// Why cannot we simply use: j.get<std::uint64_t>() ?
// Well, with the current experiment, the get method looks for a from_json
// function, which we are currently defining!
// This would end up in a stack overflow. Calling nlohmann::from_json is a
// workaround (is it?).
// I shall find a good way to avoid this once all constructors are converted
// to free methods
//
// In short, constructing a json by constructor calls to_json
// calling get calls from_json, for now, we cannot do this in custom
// serializers
nlohmann::from_json(j, value);
auto bytes = static_cast<char *>(static_cast<void *>(&value));
std::memcpy(&t, bytes, sizeof(value));
}
template <
typename Json, typename U = T,
typename std::enable_if<
not(std::is_pod<U>::value and std::is_class<U>::value), int>::type = 0>
static void to_json(Json &j, T const &t)
{
using nlohmann::to_json;
to_json(j, t);
}
template <typename Json, typename U = T,
typename std::enable_if<
std::is_pod<U>::value and std::is_class<U>::value, int>::type = 0>
static void to_json(Json &j, T const &t) noexcept
{
auto bytes = static_cast<unsigned char const *>(static_cast<void const *>(&t));
std::uint64_t value = bytes[0];
for (auto i = 1; i < 8; ++i)
value |= std::uint64_t{bytes[i]} << 8 * i;
nlohmann::to_json(j, value);
}
2016-12-15 07:06:37 +08:00
};
namespace udt
{
struct small_pod
{
int begin;
char middle;
short end;
2016-12-15 07:06:37 +08:00
};
2017-01-09 07:29:00 +08:00
struct non_pod
{
std::string s;
};
template <typename Json>
void to_json(Json& j, non_pod const& np)
{
j = np.s;
}
template <typename Json>
void from_json(Json const& j, non_pod& np)
{
np.s = j.template get<std::string>();
}
bool operator==(small_pod lhs, small_pod rhs) noexcept
2016-12-15 07:06:37 +08:00
{
return std::tie(lhs.begin, lhs.middle, lhs.end) ==
2017-01-09 07:29:00 +08:00
std::tie(rhs.begin, rhs.middle, rhs.end);
}
bool operator==(non_pod const &lhs, non_pod const &rhs) noexcept
{
return lhs.s == rhs.s;
}
std::ostream& operator<<(std::ostream& os, small_pod l)
{
return os << "begin: " << l.begin << ", middle: " << l.middle << ", end: " << l.end;
2016-12-15 07:06:37 +08:00
}
}
TEST_CASE("custom serializer for pods", "[udt]")
{
2017-01-09 07:29:00 +08:00
using custom_json =
nlohmann::basic_json<std::map, std::vector, std::string, bool,
std::int64_t, std::uint64_t, double, std::allocator,
pod_serializer>;
auto p = udt::small_pod{42, '/', 42};
custom_json j = p;
2016-12-15 07:06:37 +08:00
2017-01-09 07:29:00 +08:00
auto p2 = j.get<udt::small_pod>();
2016-12-15 07:06:37 +08:00
2017-01-09 07:29:00 +08:00
CHECK(p == p2);
2016-12-15 07:06:37 +08:00
2017-01-09 07:29:00 +08:00
auto np = udt::non_pod{{"non-pod"}};
custom_json j2 = np;
auto np2 = j2.get<udt::non_pod>();
CHECK(np == np2);
2016-12-15 07:06:37 +08:00
}
template <typename T, typename>
struct another_adl_serializer;
using custom_json = nlohmann::basic_json<std::map, std::vector, std::string, bool, std::int64_t, std::uint64_t, double, std::allocator, another_adl_serializer>;
2016-12-15 07:06:37 +08:00
template <typename T, typename>
struct another_adl_serializer
{
static void from_json(custom_json const& j , T& t)
{
using nlohmann::from_json;
from_json(j, t);
}
static void to_json(custom_json& j , T const& t)
{
using nlohmann::to_json;
to_json(j, t);
}
2016-12-15 07:06:37 +08:00
};
TEST_CASE("custom serializer that does adl by default", "[udt]")
{
using json = nlohmann::json;
2016-12-15 07:06:37 +08:00
auto me = udt::person{23, "theo", udt::country::france};
2016-12-15 07:06:37 +08:00
json j = me;
custom_json cj = me;
2016-12-15 07:06:37 +08:00
CHECK(j.dump() == cj.dump());
2016-12-15 07:06:37 +08:00
CHECK(me == j.get<udt::person>());
CHECK(me == cj.get<udt::person>());
2016-12-15 07:06:37 +08:00
}