constructor.cpp 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // ArduinoJson - https://arduinojson.org
  2. // Copyright © 2014-2023, Benoit BLANCHON
  3. // MIT License
  4. #include <ArduinoJson.h>
  5. #include <catch.hpp>
  6. #include "Allocators.hpp"
  7. using ArduinoJson::detail::addPadding;
  8. TEST_CASE("JsonDocument constructor") {
  9. SpyingAllocator spyingAllocator;
  10. SECTION("JsonDocument(size_t)") {
  11. { JsonDocument doc(4096, &spyingAllocator); }
  12. REQUIRE(spyingAllocator.log() == AllocatorLog()
  13. << AllocatorLog::Allocate(4096)
  14. << AllocatorLog::Deallocate(4096));
  15. }
  16. SECTION("JsonDocument(const JsonDocument&)") {
  17. {
  18. JsonDocument doc1(4096, &spyingAllocator);
  19. doc1.set(std::string("The size of this string is 32!!"));
  20. JsonDocument doc2(doc1);
  21. REQUIRE(doc1.as<std::string>() == "The size of this string is 32!!");
  22. REQUIRE(doc2.as<std::string>() == "The size of this string is 32!!");
  23. REQUIRE(doc2.capacity() == 4096);
  24. }
  25. REQUIRE(spyingAllocator.log() == AllocatorLog()
  26. << AllocatorLog::Allocate(4096)
  27. << AllocatorLog::Allocate(4096)
  28. << AllocatorLog::Deallocate(4096)
  29. << AllocatorLog::Deallocate(4096));
  30. }
  31. SECTION("JsonDocument(JsonDocument&&)") {
  32. {
  33. JsonDocument doc1(4096, &spyingAllocator);
  34. doc1.set(std::string("The size of this string is 32!!"));
  35. JsonDocument doc2(std::move(doc1));
  36. REQUIRE(doc2.as<std::string>() == "The size of this string is 32!!");
  37. REQUIRE(doc1.as<std::string>() == "null");
  38. REQUIRE(doc1.capacity() == 0);
  39. REQUIRE(doc2.capacity() == 4096);
  40. }
  41. REQUIRE(spyingAllocator.log() == AllocatorLog()
  42. << AllocatorLog::Allocate(4096)
  43. << AllocatorLog::Deallocate(4096));
  44. }
  45. SECTION("JsonDocument(JsonObject)") {
  46. JsonDocument doc1(200);
  47. JsonObject obj = doc1.to<JsonObject>();
  48. obj["hello"] = "world";
  49. JsonDocument doc2 = obj;
  50. REQUIRE(doc2.as<std::string>() == "{\"hello\":\"world\"}");
  51. REQUIRE(doc2.capacity() == addPadding(doc1.memoryUsage()));
  52. }
  53. SECTION("Construct from JsonArray") {
  54. JsonDocument doc1(200);
  55. JsonArray arr = doc1.to<JsonArray>();
  56. arr.add("hello");
  57. JsonDocument doc2 = arr;
  58. REQUIRE(doc2.as<std::string>() == "[\"hello\"]");
  59. REQUIRE(doc2.capacity() == addPadding(doc1.memoryUsage()));
  60. }
  61. SECTION("Construct from JsonVariant") {
  62. JsonDocument doc1(200);
  63. deserializeJson(doc1, "42");
  64. JsonDocument doc2 = doc1.as<JsonVariant>();
  65. REQUIRE(doc2.as<std::string>() == "42");
  66. REQUIRE(doc2.capacity() == addPadding(doc1.memoryUsage()));
  67. }
  68. }