set.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. #define ARDUINOJSON_ENABLE_ARDUINO_STRING 1
  2. #define ARDUINOJSON_ENABLE_PROGMEM 1
  3. #include <ArduinoJson.h>
  4. #include <catch.hpp>
  5. #include "Allocators.hpp"
  6. #include "Literals.hpp"
  7. TEST_CASE("JsonDocument::set()") {
  8. SpyingAllocator spy;
  9. JsonDocument doc(&spy);
  10. SECTION("nullptr") {
  11. doc.set(nullptr);
  12. REQUIRE(doc.isNull());
  13. REQUIRE(spy.log() == AllocatorLog{});
  14. }
  15. SECTION("integer&") {
  16. int toto = 42;
  17. doc.set(toto);
  18. REQUIRE(doc.as<std::string>() == "42");
  19. REQUIRE(spy.log() == AllocatorLog{});
  20. }
  21. SECTION("integer") {
  22. doc.set(42);
  23. REQUIRE(doc.as<std::string>() == "42");
  24. REQUIRE(spy.log() == AllocatorLog{});
  25. }
  26. SECTION("string literal") {
  27. doc.set("example");
  28. REQUIRE(doc.as<const char*>() == "example"_s);
  29. REQUIRE(spy.log() == AllocatorLog{
  30. Allocate(sizeofStaticStringPool()),
  31. });
  32. }
  33. SECTION("const char*") {
  34. const char* value = "example";
  35. doc.set(value);
  36. REQUIRE(doc.as<const char*>() == "example"_s);
  37. REQUIRE(spy.log() == AllocatorLog{
  38. Allocate(sizeofString("example")),
  39. });
  40. }
  41. SECTION("std::string") {
  42. doc.set("example"_s);
  43. REQUIRE(doc.as<const char*>() == "example"_s);
  44. REQUIRE(spy.log() == AllocatorLog{
  45. Allocate(sizeofString("example")),
  46. });
  47. }
  48. SECTION("char*") {
  49. char value[] = "example";
  50. doc.set(value);
  51. REQUIRE(doc.as<const char*>() == "example"_s);
  52. REQUIRE(spy.log() == AllocatorLog{
  53. Allocate(sizeofString("example")),
  54. });
  55. }
  56. SECTION("Arduino String") {
  57. doc.set(String("example"));
  58. REQUIRE(doc.as<const char*>() == "example"_s);
  59. REQUIRE(spy.log() == AllocatorLog{
  60. Allocate(sizeofString("example")),
  61. });
  62. }
  63. SECTION("Flash string") {
  64. doc.set(F("example"));
  65. REQUIRE(doc.as<const char*>() == "example"_s);
  66. REQUIRE(spy.log() == AllocatorLog{
  67. Allocate(sizeofString("example")),
  68. });
  69. }
  70. SECTION("Flash tiny string") { // issue #2170
  71. doc.set(F("abc"));
  72. REQUIRE(doc.as<const char*>() == "abc"_s);
  73. REQUIRE(spy.log() == AllocatorLog{});
  74. }
  75. #ifdef HAS_VARIABLE_LENGTH_ARRAY
  76. SECTION("VLA") {
  77. size_t i = 16;
  78. char vla[i];
  79. strcpy(vla, "example");
  80. doc.set(vla);
  81. REQUIRE(doc.as<const char*>() == "example"_s);
  82. REQUIRE(spy.log() == AllocatorLog{
  83. Allocate(sizeofString("example")),
  84. });
  85. }
  86. #endif
  87. }