Files
lix/tests/unit/libutil/json-utils.cc
T
eldritch horrors 19d7c8352e treewide: add nix::JSON
this will become a proper specialization of `nlohmann::basic_json` soon.
specialing basic_json will let us get rid of our `adl_serializer` hacks,
and it'll open the door to better enum serializing behavior without also
forcing all those who use lix as a library to set certain defines (which
may not even be possible depending on how those users use json already).

Change-Id: I5228d2b9df581a189552c993363207cfbd20f445
2025-03-23 20:42:39 +00:00

59 lines
1.5 KiB
C++

#include <vector>
#include <optional>
#include <gtest/gtest.h>
#include "lix/libutil/json-utils.hh"
namespace nix {
/* Test `to_json` and `from_json` with `std::optional` types.
* We are specifically interested in whether we can _nest_ optionals in STL
* containers so we that we can leverage existing adl_serializer templates. */
TEST(to_json, optionalInt) {
std::optional<int> val = std::make_optional(420);
ASSERT_EQ(JSON(val), JSON(420));
val = std::nullopt;
ASSERT_EQ(JSON(val), JSON(nullptr));
}
TEST(to_json, vectorOfOptionalInts) {
std::vector<std::optional<int>> vals = {
std::make_optional(420),
std::nullopt,
};
ASSERT_EQ(JSON(vals), JSON::parse("[420,null]"));
}
TEST(to_json, optionalVectorOfInts) {
std::optional<std::vector<int>> val = std::make_optional(std::vector<int> {
-420,
420,
});
ASSERT_EQ(JSON(val), JSON::parse("[-420,420]"));
val = std::nullopt;
ASSERT_EQ(JSON(val), JSON(nullptr));
}
TEST(from_json, optionalInt) {
JSON json = 420;
std::optional<int> val = json;
ASSERT_TRUE(val.has_value());
ASSERT_EQ(*val, 420);
json = nullptr;
json.get_to(val);
ASSERT_FALSE(val.has_value());
}
TEST(from_json, vectorOfOptionalInts) {
JSON json = { 420, nullptr };
std::vector<std::optional<int>> vals = json;
ASSERT_EQ(vals.size(), 2);
ASSERT_TRUE(vals.at(0).has_value());
ASSERT_EQ(*vals.at(0), 420);
ASSERT_FALSE(vals.at(1).has_value());
}
} /* namespace nix */