Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions include/rfl/parsing/FieldVariantReader.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ class FieldVariantReader {
*/
void read(const std::string_view& _disc_value,
const InputVarType& _var) const noexcept {
if (*field_variant_) {
*field_variant_ = error(
"Could not parse rfl::Variant: Expected the object to have "
"exactly one field, but found more than one.");
return;
}
try_matching_fields(
_disc_value, _var,
std::make_integer_sequence<int, sizeof...(FieldTypes)>());
Expand Down
42 changes: 42 additions & 0 deletions tests/json/test_field_variant_multiple_fields.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#include <gtest/gtest.h>

#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>

namespace test_field_variant_multiple_fields {

struct Circle {
double radius;
};

struct Rectangle {
double height;
double width;
};

using Shapes =
rfl::Variant<rfl::Field<"circle", Circle>, rfl::Field<"rectangle", Rectangle>>;

TEST(json, test_field_variant_multiple_fields) {
const std::string faulty_string =
R"({"circle":{"radius":2.0},"rectangle":{"height":10.0,"width":5.0}})";

const auto result = rfl::json::read<Shapes>(faulty_string);

EXPECT_TRUE(!result.has_value() && true);
EXPECT_EQ(result.error().what(),
"Could not parse rfl::Variant: Expected the object to have "
"exactly one field, but found more than one.");
}

TEST(json, test_field_variant_unknown_then_known_field) {
const std::string faulty_string =
R"({"triangle":{"base":3.0},"circle":{"radius":2.0}})";

const auto result = rfl::json::read<Shapes>(faulty_string);

EXPECT_TRUE(!result.has_value() && true);
}

} // namespace test_field_variant_multiple_fields