set.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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. }
  31. SECTION("const char*") {
  32. const char* value = "example";
  33. doc.set(value);
  34. REQUIRE(doc.as<const char*>() == "example"_s);
  35. REQUIRE(spy.log() == AllocatorLog{
  36. Allocate(sizeofString("example")),
  37. });
  38. }
  39. SECTION("std::string") {
  40. doc.set("example"_s);
  41. REQUIRE(doc.as<const char*>() == "example"_s);
  42. REQUIRE(spy.log() == AllocatorLog{
  43. Allocate(sizeofString("example")),
  44. });
  45. }
  46. SECTION("char*") {
  47. char value[] = "example";
  48. doc.set(value);
  49. REQUIRE(doc.as<const char*>() == "example"_s);
  50. REQUIRE(spy.log() == AllocatorLog{
  51. Allocate(sizeofString("example")),
  52. });
  53. }
  54. SECTION("Arduino String") {
  55. doc.set(String("example"));
  56. REQUIRE(doc.as<const char*>() == "example"_s);
  57. REQUIRE(spy.log() == AllocatorLog{
  58. Allocate(sizeofString("example")),
  59. });
  60. }
  61. SECTION("Flash string") {
  62. doc.set(F("example"));
  63. REQUIRE(doc.as<const char*>() == "example"_s);
  64. REQUIRE(spy.log() == AllocatorLog{
  65. Allocate(sizeofString("example")),
  66. });
  67. }
  68. SECTION("Flash tiny string") { // issue #2170
  69. doc.set(F("abc"));
  70. REQUIRE(doc.as<const char*>() == "abc"_s);
  71. REQUIRE(spy.log() == AllocatorLog{});
  72. }
  73. #ifdef HAS_VARIABLE_LENGTH_ARRAY
  74. SECTION("VLA") {
  75. size_t i = 16;
  76. char vla[i];
  77. strcpy(vla, "example");
  78. doc.set(vla);
  79. REQUIRE(doc.as<const char*>() == "example"_s);
  80. REQUIRE(spy.log() == AllocatorLog{
  81. Allocate(sizeofString("example")),
  82. });
  83. }
  84. #endif
  85. }