JsonObjectPretty.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // ArduinoJson - https://arduinojson.org
  2. // Copyright © 2014-2022, Benoit BLANCHON
  3. // MIT License
  4. #include <ArduinoJson.h>
  5. #include <catch.hpp>
  6. #include <string>
  7. static void checkObjectPretty(const JsonObject obj,
  8. const std::string expected) {
  9. char json[256];
  10. size_t actualLen = serializeJsonPretty(obj, json);
  11. size_t measuredLen = measureJsonPretty(obj);
  12. REQUIRE(json == expected);
  13. REQUIRE(expected.size() == actualLen);
  14. REQUIRE(expected.size() == measuredLen);
  15. }
  16. TEST_CASE("serializeJsonPretty(JsonObject)") {
  17. DynamicJsonDocument doc(4096);
  18. JsonObject obj = doc.to<JsonObject>();
  19. SECTION("EmptyObject") {
  20. checkObjectPretty(obj, "{}");
  21. }
  22. SECTION("OneMember") {
  23. obj["key"] = "value";
  24. checkObjectPretty(obj,
  25. "{\r\n"
  26. " \"key\": \"value\"\r\n"
  27. "}");
  28. }
  29. SECTION("TwoMembers") {
  30. obj["key1"] = "value1";
  31. obj["key2"] = "value2";
  32. checkObjectPretty(obj,
  33. "{\r\n"
  34. " \"key1\": \"value1\",\r\n"
  35. " \"key2\": \"value2\"\r\n"
  36. "}");
  37. }
  38. SECTION("EmptyNestedContainers") {
  39. obj.createNestedObject("key1");
  40. obj.createNestedArray("key2");
  41. checkObjectPretty(obj,
  42. "{\r\n"
  43. " \"key1\": {},\r\n"
  44. " \"key2\": []\r\n"
  45. "}");
  46. }
  47. SECTION("NestedContainers") {
  48. JsonObject nested1 = obj.createNestedObject("key1");
  49. nested1["a"] = 1;
  50. JsonArray nested2 = obj.createNestedArray("key2");
  51. nested2.add(2);
  52. checkObjectPretty(obj,
  53. "{\r\n"
  54. " \"key1\": {\r\n"
  55. " \"a\": 1\r\n"
  56. " },\r\n"
  57. " \"key2\": [\r\n"
  58. " 2\r\n"
  59. " ]\r\n"
  60. "}");
  61. }
  62. }