Files
Library/tests/standalone/Data/ReflectAnnotations.cpp
T

63 lines
1.9 KiB
C++

// @requires-reflection
#include <Void/Data/Reflect.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <string>
namespace J = Void::Json;
namespace
{
struct Address {
std::string city = "?";
int zip = 0;
};
struct User {
[[= J::Rename{"user_id"}]] int id = 0;
[[= J::Skip{}]] int cache = 99;
[[= J::Required{}]] std::string name = "";
[[= J::Flatten{}]] Address addr{};
};
} // namespace
// @tag reflection
Void::Testing::Test json_annotations_to_json()
{
User u{7, 99, "neo", Address{"zion", 100}};
const auto j = J::to_json(u);
Void::Testing::expect(j.find("user_id") != nullptr); // Rename
Void::Testing::expect_eq(j.find("user_id")->as_int(), std::int64_t{7});
Void::Testing::expect(j.find("cache") == nullptr); // Skip
Void::Testing::expect(j.find("name") != nullptr);
// Flatten: Address keys appear at top level, "addr" does not.
Void::Testing::expect(j.find("city") != nullptr);
Void::Testing::expect_eq(j.find("city")->as_string(), std::string{"zion"});
Void::Testing::expect(j.find("zip") != nullptr);
Void::Testing::expect(j.find("addr") == nullptr);
}
// @tag reflection
Void::Testing::Test json_annotations_round_trip()
{
User u{7, 99, "neo", Address{"zion", 100}};
const auto j = J::to_json(u);
const auto back = J::from_json<User>(j);
Void::Testing::expect(back.has_value());
Void::Testing::expect_eq(back->id, 7);
Void::Testing::expect_eq(back->name, std::string{"neo"});
Void::Testing::expect_eq(back->addr.city, std::string{"zion"});
Void::Testing::expect_eq(back->addr.zip, 100);
Void::Testing::expect_eq(back->cache, 99); // Skip keeps default
}
// @tag reflection
Void::Testing::Test json_required_missing_is_error()
{
const auto j = J::parse(R"({"user_id":1,"city":"x","zip":2})");
Void::Testing::expect(j.has_value());
const auto r = J::from_json<User>(*j);
Void::Testing::expect(!r.has_value());
Void::Testing::expect_eq(r.error().field, std::string{"name"});
}