garbageCollect.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // ArduinoJson - https://arduinojson.org
  2. // Copyright © 2014-2023, Benoit BLANCHON
  3. // MIT License
  4. #include <ArduinoJson.h>
  5. #include <stdlib.h> // malloc, free
  6. #include <catch.hpp>
  7. #include <utility>
  8. #include "Allocators.hpp"
  9. using ArduinoJson::detail::sizeofObject;
  10. using ArduinoJson::detail::sizeofString;
  11. TEST_CASE("JsonDocument::garbageCollect()") {
  12. ControllableAllocator controllableAllocator;
  13. SpyingAllocator spyingAllocator(&controllableAllocator);
  14. JsonDocument doc(4096, &spyingAllocator);
  15. SECTION("when allocation succeeds") {
  16. deserializeJson(doc, "{\"blanket\":1,\"dancing\":2}");
  17. REQUIRE(doc.memoryUsage() == sizeofObject(2) + 2 * sizeofString(7));
  18. doc.remove("blanket");
  19. bool result = doc.garbageCollect();
  20. REQUIRE(result == true);
  21. REQUIRE(doc.memoryUsage() == sizeofObject(1) + sizeofString(7));
  22. REQUIRE(doc.as<std::string>() == "{\"dancing\":2}");
  23. REQUIRE(spyingAllocator.log() == AllocatorLog()
  24. << AllocatorLog::Allocate(4096)
  25. << AllocatorLog::Allocate(4096)
  26. << AllocatorLog::Deallocate(4096));
  27. }
  28. SECTION("when allocation fails") {
  29. deserializeJson(doc, "{\"blanket\":1,\"dancing\":2}");
  30. REQUIRE(doc.memoryUsage() == sizeofObject(2) + 2 * sizeofString(7));
  31. doc.remove("blanket");
  32. controllableAllocator.disable();
  33. bool result = doc.garbageCollect();
  34. REQUIRE(result == false);
  35. REQUIRE(doc.memoryUsage() == sizeofObject(2) + 2 * sizeofString(7));
  36. REQUIRE(doc.as<std::string>() == "{\"dancing\":2}");
  37. REQUIRE(spyingAllocator.log() == AllocatorLog()
  38. << AllocatorLog::Allocate(4096)
  39. << AllocatorLog::AllocateFail(4096));
  40. }
  41. }