constructor.cpp 3.0 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. }
  24. REQUIRE(spyingAllocator.log() == AllocatorLog()
  25. << AllocatorLog::Allocate(4096)
  26. << AllocatorLog::Allocate(4096)
  27. << AllocatorLog::Deallocate(4096)
  28. << AllocatorLog::Deallocate(4096));
  29. }
  30. SECTION("JsonDocument(JsonDocument&&)") {
  31. {
  32. JsonDocument doc1(4096, &spyingAllocator);
  33. doc1.set(std::string("The size of this string is 32!!"));
  34. JsonDocument doc2(std::move(doc1));
  35. REQUIRE(doc2.as<std::string>() == "The size of this string is 32!!");
  36. REQUIRE(doc1.as<std::string>() == "null");
  37. }
  38. REQUIRE(spyingAllocator.log() == AllocatorLog()
  39. << AllocatorLog::Allocate(4096)
  40. << AllocatorLog::Deallocate(4096));
  41. }
  42. SECTION("JsonDocument(JsonObject)") {
  43. JsonDocument doc1(200);
  44. JsonObject obj = doc1.to<JsonObject>();
  45. obj["hello"] = "world";
  46. JsonDocument doc2(obj, &spyingAllocator);
  47. REQUIRE(doc2.as<std::string>() == "{\"hello\":\"world\"}");
  48. REQUIRE(spyingAllocator.log() == AllocatorLog() << AllocatorLog::Allocate(
  49. addPadding(doc1.memoryUsage())));
  50. }
  51. SECTION("Construct from JsonArray") {
  52. JsonDocument doc1(200);
  53. JsonArray arr = doc1.to<JsonArray>();
  54. arr.add("hello");
  55. JsonDocument doc2(arr, &spyingAllocator);
  56. REQUIRE(doc2.as<std::string>() == "[\"hello\"]");
  57. REQUIRE(spyingAllocator.log() == AllocatorLog() << AllocatorLog::Allocate(
  58. addPadding(doc1.memoryUsage())));
  59. }
  60. SECTION("Construct from JsonVariant") {
  61. JsonDocument doc1(200);
  62. deserializeJson(doc1, "\"hello\"");
  63. JsonDocument doc2(doc1.as<JsonVariant>(), &spyingAllocator);
  64. REQUIRE(doc2.as<std::string>() == "hello");
  65. REQUIRE(spyingAllocator.log() == AllocatorLog() << AllocatorLog::Allocate(
  66. addPadding(doc1.memoryUsage())));
  67. }
  68. }