garbageCollect.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. TEST_CASE("JsonDocument::garbageCollect()") {
  11. SpyingAllocator spyingAllocator;
  12. ControllableAllocator controllableAllocator;
  13. JsonDocument doc(4096, &controllableAllocator);
  14. SECTION("when allocation succeeds") {
  15. deserializeJson(doc, "{\"blanket\":1,\"dancing\":2}");
  16. REQUIRE(doc.capacity() == 4096);
  17. REQUIRE(doc.memoryUsage() == sizeofObject(2) + 16);
  18. doc.remove("blanket");
  19. bool result = doc.garbageCollect();
  20. REQUIRE(result == true);
  21. REQUIRE(doc.memoryUsage() == sizeofObject(1) + 8);
  22. REQUIRE(doc.capacity() == 4096);
  23. REQUIRE(doc.as<std::string>() == "{\"dancing\":2}");
  24. }
  25. SECTION("when allocation fails") {
  26. deserializeJson(doc, "{\"blanket\":1,\"dancing\":2}");
  27. REQUIRE(doc.capacity() == 4096);
  28. REQUIRE(doc.memoryUsage() == sizeofObject(2) + 16);
  29. doc.remove("blanket");
  30. controllableAllocator.disable();
  31. bool result = doc.garbageCollect();
  32. REQUIRE(result == false);
  33. REQUIRE(doc.memoryUsage() == sizeofObject(2) + 16);
  34. REQUIRE(doc.capacity() == 4096);
  35. REQUIRE(doc.as<std::string>() == "{\"dancing\":2}");
  36. }
  37. }