|
| 1 | +#include <gtest/gtest.h> |
| 2 | + |
| 3 | +#include <iostream> |
| 4 | +#include <rfl.hpp> |
| 5 | +#include <rfl/ubjson.hpp> |
| 6 | +#include <rfl/json.hpp> |
| 7 | +#include <string> |
| 8 | +#include <vector> |
| 9 | + |
| 10 | +namespace test_error_messages { |
| 11 | + |
| 12 | +struct Person { |
| 13 | + rfl::Rename<"firstName", std::string> first_name; |
| 14 | + rfl::Rename<"lastName", std::string> last_name; |
| 15 | + rfl::Timestamp<"%Y-%m-%d"> birthday; |
| 16 | + std::vector<Person> children; |
| 17 | +}; |
| 18 | + |
| 19 | +TEST(ubjson, test_field_error_messages) { |
| 20 | + const std::string faulty_string = |
| 21 | + R"({"firstName":"Homer","lastName":12345,"birthday":"04/19/1987"})"; |
| 22 | + const auto faulty_generic = rfl::json::read<rfl::Generic>(faulty_string); |
| 23 | + const auto faulty_ubjson = rfl::ubjson::write(faulty_generic); |
| 24 | + const auto result = rfl::ubjson::read<Person>(faulty_ubjson); |
| 25 | + |
| 26 | + // Order of errors is different than input JSON because rfl::Generic doesn't preserve order |
| 27 | + const std::string expected = R"(Found 3 errors: |
| 28 | +1) Failed to parse field 'birthday': String '04/19/1987' did not match format '%Y-%m-%d'. |
| 29 | +2) Failed to parse field 'lastName': Could not cast to string. |
| 30 | +3) Field named 'children' not found.)"; |
| 31 | + |
| 32 | + EXPECT_TRUE(!result.has_value() && true); |
| 33 | + |
| 34 | + EXPECT_EQ(result.error().what(), expected); |
| 35 | +} |
| 36 | + |
| 37 | +TEST(ubjson, test_decode_error_without_exception) { |
| 38 | + const std::string good_string = |
| 39 | + R"({"firstName":"Homer","lastName":"Simpson","birthday":"1987-04-19"})"; |
| 40 | + const auto good_generic = rfl::json::read<rfl::Generic>(good_string); |
| 41 | + auto faulty_ubjson = rfl::ubjson::write(good_generic); |
| 42 | + faulty_ubjson[0] = '\xff'; // Corrupt structure of ubjson encoding |
| 43 | + |
| 44 | + rfl::Result<Person> result = rfl::error("result didn't get set"); |
| 45 | + EXPECT_NO_THROW({ |
| 46 | + result = rfl::ubjson::read<Person>(faulty_ubjson); |
| 47 | + }); |
| 48 | + |
| 49 | + // A proposal: A generic prefix, followed by the underlying library's error output |
| 50 | + const std::string expected = R"(Could not parse UBJSON: Unknown type at position 1)"; |
| 51 | + EXPECT_EQ(result.error().what(), expected); |
| 52 | + |
| 53 | + EXPECT_TRUE(!result.has_value() && true); |
| 54 | +} |
| 55 | + |
| 56 | +} // namespace test_error_messages |
0 commit comments