add.cpp 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. // ArduinoJson - https://arduinojson.org
  2. // Copyright © 2014-2024, Benoit BLANCHON
  3. // MIT License
  4. #define ARDUINOJSON_ENABLE_ARDUINO_STRING 1
  5. #define ARDUINOJSON_ENABLE_PROGMEM 1
  6. #include <ArduinoJson.h>
  7. #include <catch.hpp>
  8. #include "Allocators.hpp"
  9. using ArduinoJson::detail::sizeofArray;
  10. TEST_CASE("JsonDocument::add(T)") {
  11. SpyingAllocator spy;
  12. JsonDocument doc(&spy);
  13. SECTION("integer") {
  14. doc.add(42);
  15. REQUIRE(doc.as<std::string>() == "[42]");
  16. REQUIRE(spy.log() == AllocatorLog{
  17. Allocate(sizeofPool()),
  18. });
  19. }
  20. SECTION("const char*") {
  21. doc.add("hello");
  22. REQUIRE(doc.as<std::string>() == "[\"hello\"]");
  23. REQUIRE(spy.log() == AllocatorLog{
  24. Allocate(sizeofPool()),
  25. });
  26. }
  27. SECTION("std::string") {
  28. doc.add(std::string("example"));
  29. doc.add(std::string("example"));
  30. CHECK(doc[0].as<const char*>() == doc[1].as<const char*>());
  31. REQUIRE(spy.log() == AllocatorLog{
  32. Allocate(sizeofPool()),
  33. Allocate(sizeofString("example")),
  34. });
  35. }
  36. SECTION("char*") {
  37. char value[] = "example";
  38. doc.add(value);
  39. doc.add(value);
  40. CHECK(doc[0].as<const char*>() == doc[1].as<const char*>());
  41. REQUIRE(spy.log() == AllocatorLog{
  42. Allocate(sizeofPool()),
  43. Allocate(sizeofString("example")),
  44. });
  45. }
  46. SECTION("Arduino String") {
  47. doc.add(String("example"));
  48. doc.add(String("example"));
  49. CHECK(doc[0].as<const char*>() == doc[1].as<const char*>());
  50. REQUIRE(spy.log() == AllocatorLog{
  51. Allocate(sizeofPool()),
  52. Allocate(sizeofString("example")),
  53. });
  54. }
  55. SECTION("Flash string") {
  56. doc.add(F("example"));
  57. doc.add(F("example"));
  58. CHECK(doc[0].as<const char*>() == doc[1].as<const char*>());
  59. REQUIRE(spy.log() == AllocatorLog{
  60. Allocate(sizeofPool()),
  61. Allocate(sizeofString("example")),
  62. });
  63. }
  64. }
  65. TEST_CASE("JsonDocument::add<T>()") {
  66. JsonDocument doc;
  67. SECTION("JsonArray") {
  68. JsonArray array = doc.add<JsonArray>();
  69. array.add(1);
  70. array.add(2);
  71. REQUIRE(doc.as<std::string>() == "[[1,2]]");
  72. }
  73. SECTION("JsonObject") {
  74. JsonObject object = doc.add<JsonObject>();
  75. object["hello"] = "world";
  76. REQUIRE(doc.as<std::string>() == "[{\"hello\":\"world\"}]");
  77. }
  78. SECTION("JsonVariant") {
  79. JsonVariant variant = doc.add<JsonVariant>();
  80. variant.set(42);
  81. REQUIRE(doc.as<std::string>() == "[42]");
  82. }
  83. }