Skip to content

Commit 75ae715

Browse files
TheoTheo
Theo
authored and
Theo
committed
add a few tests
1 parent f1345d9 commit 75ae715

File tree

2 files changed

+41
-2
lines changed

2 files changed

+41
-2
lines changed

Diff for: src/json.hpp

+4-1
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,8 @@ struct is_compatible_basic_json_type
274274
T>::value;
275275
};
276276

277+
278+
// This trait checks if JSONSerializer<T>::from_json exists
277279
template <template <typename, typename> class JSONSerializer, typename Json,
278280
typename T>
279281
struct has_from_json
@@ -290,6 +292,7 @@ struct has_from_json
290292
detect(std::declval<JSONSerializer<T, void>>()))>::value;
291293
};
292294

295+
// This trait checks if JSONSerializer<T>::to_json exists
293296
template <template <typename, typename> class JSONSerializer, typename Json,
294297
typename T>
295298
struct has_to_json
@@ -307,7 +310,7 @@ struct has_to_json
307310
};
308311

309312
// those declarations are needed to workaround a MSVC bug related to ADL
310-
// (idea taken from MSVC-Ranges implementation
313+
// (taken from MSVC-Ranges implementation)
311314
void to_json();
312315
void from_json();
313316

Diff for: test/src/unit-udt.cpp

+37-1
Original file line numberDiff line numberDiff line change
@@ -397,6 +397,29 @@ struct my_serializer
397397
}
398398
};
399399

400+
// partial specialization on optional_type
401+
template <typename T>
402+
struct my_serializer<udt::optional_type<T>>
403+
{
404+
template <typename Json>
405+
static void from_json(Json const& j, udt::optional_type<T>& opt)
406+
{
407+
if (j.is_null())
408+
opt = nullptr;
409+
else
410+
opt = j.get<T>();
411+
}
412+
413+
template <typename Json>
414+
static void to_json(Json& j, udt::optional_type<T> const& opt)
415+
{
416+
if (opt)
417+
j = *opt;
418+
else
419+
j = nullptr;
420+
}
421+
};
422+
400423
using my_json = nlohmann::basic_json<std::map, std::vector, std::string, bool,
401424
std::int64_t, std::uint64_t, double,
402425
std::allocator, my_serializer>;
@@ -414,7 +437,7 @@ namespace udt
414437
}
415438
}
416439

417-
TEST_CASE("custom serializer")
440+
TEST_CASE("custom serializer", "[udt]")
418441
{
419442
SECTION("default use works like default serializer")
420443
{
@@ -429,4 +452,17 @@ TEST_CASE("custom serializer")
429452
CHECK(pod2 == pod3);
430453
CHECK(pod2 == pod);
431454
}
455+
456+
SECTION("serializer specialization")
457+
{
458+
udt::optional_type<int> opt;
459+
460+
json j{opt};
461+
CHECK(j.is_null());
462+
463+
opt = 42;
464+
j = json{opt};
465+
CHECK(j.get<udt::optional_type<int>>() == opt);
466+
CHECK(42 == j.get<int>());
467+
}
432468
}

0 commit comments

Comments
 (0)