Skip to content

Reading JSON into a struct with a DefaultVal field and a size validator field always raises a size validation error #700

Description

@wbernoudy

For example, using rfl::json::read with the struct

struct Person {
  rfl::DefaultVal<std::string> name = "Homer Simpson";
  rfl::Validator<std::vector<std::string>, rfl::Size<rfl::Minimum<1>>> favorite_foods;
};

seems to always fail with the exception Size validation failed: Value expected to be greater than or equal to 1, but got 0., even when given a list of favorite_foods with one or more items.

A short test case to see the behavior:

namespace test_default_val_alongside_size_validator {

struct Person {
  rfl::DefaultVal<std::string> name = "Homer Simpson";
  rfl::Validator<std::vector<std::string>, rfl::Size<rfl::Minimum<1>>> favorite_foods;
};

TEST(json, test_default_val_alongside_size_validator) {
  static_assert(rfl::internal::has_default_val_v<Person>,
                "Should have default val");

  const auto should_fail = rfl::json::read<Person>(R"({})");

  EXPECT_EQ(should_fail && true, false)
      << "Should have failed due to missing required field";

  const auto homer =
      rfl::json::read<Person>(R"({"favorite_foods": ["donuts", "pizza"]})").value();

  EXPECT_EQ(homer.name.value(), "Homer Simpson");
  EXPECT_EQ(homer.favorite_foods.value().size(), 2);
  EXPECT_EQ(homer.favorite_foods.value()[0], "donuts");
  EXPECT_EQ(homer.favorite_foods.value()[1], "pizza");
}
}  // namespace test_default_val_alongside_size_validator

However, if you set a default value for the field that satisfies the validator, everything seems to work. For example, you can change the favorite_foods definition in the above test to

  rfl::Validator<std::vector<std::string>, rfl::Size<rfl::Minimum<1>>> favorite_foods = {{std::string{"beer"}}};

and it should pass.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions