garbageCollect.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. spyingAllocator.clearLog();
  20. bool result = doc.garbageCollect();
  21. REQUIRE(result == true);
  22. REQUIRE(doc.memoryUsage() == sizeofObject(1) + sizeofString(7));
  23. REQUIRE(doc.as<std::string>() == "{\"dancing\":2}");
  24. REQUIRE(spyingAllocator.log() ==
  25. AllocatorLog() << AllocatorLog::Allocate(4096)
  26. << AllocatorLog::Allocate(sizeofString(7))
  27. << AllocatorLog::Deallocate(sizeofString(7))
  28. << AllocatorLog::Deallocate(sizeofString(7))
  29. << AllocatorLog::Deallocate(4096));
  30. }
  31. SECTION("when allocation fails") {
  32. deserializeJson(doc, "{\"blanket\":1,\"dancing\":2}");
  33. REQUIRE(doc.memoryUsage() == sizeofObject(2) + 2 * sizeofString(7));
  34. doc.remove("blanket");
  35. controllableAllocator.disable();
  36. spyingAllocator.clearLog();
  37. bool result = doc.garbageCollect();
  38. REQUIRE(result == false);
  39. REQUIRE(doc.memoryUsage() == sizeofObject(2) + 2 * sizeofString(7));
  40. REQUIRE(doc.as<std::string>() == "{\"dancing\":2}");
  41. REQUIRE(spyingAllocator.log() == AllocatorLog()
  42. << AllocatorLog::AllocateFail(4096));
  43. }
  44. }