garbageCollect.cpp 1.8 KB

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