2023-04-01 19:10:35 +02:00
|
|
|
// ArduinoJson - https://arduinojson.org
|
|
|
|
// Copyright © 2014-2023, Benoit BLANCHON
|
|
|
|
// MIT License
|
|
|
|
|
|
|
|
#include <ArduinoJson.h>
|
|
|
|
#include <stdlib.h> // malloc, free
|
|
|
|
#include <catch.hpp>
|
|
|
|
#include <utility>
|
|
|
|
|
|
|
|
#include "Allocators.hpp"
|
|
|
|
|
|
|
|
using ArduinoJson::detail::sizeofObject;
|
2023-04-07 14:43:16 +02:00
|
|
|
using ArduinoJson::detail::sizeofString;
|
2023-04-01 19:10:35 +02:00
|
|
|
|
|
|
|
TEST_CASE("JsonDocument::garbageCollect()") {
|
|
|
|
ControllableAllocator controllableAllocator;
|
2023-04-02 16:47:37 +02:00
|
|
|
SpyingAllocator spyingAllocator(&controllableAllocator);
|
2023-07-17 18:15:13 +02:00
|
|
|
JsonDocument doc(&spyingAllocator);
|
2023-04-01 19:10:35 +02:00
|
|
|
|
|
|
|
SECTION("when allocation succeeds") {
|
|
|
|
deserializeJson(doc, "{\"blanket\":1,\"dancing\":2}");
|
2023-04-07 14:43:16 +02:00
|
|
|
REQUIRE(doc.memoryUsage() == sizeofObject(2) + 2 * sizeofString(7));
|
2023-04-01 19:10:35 +02:00
|
|
|
doc.remove("blanket");
|
2023-04-11 10:03:47 +02:00
|
|
|
spyingAllocator.clearLog();
|
2023-04-01 19:10:35 +02:00
|
|
|
|
|
|
|
bool result = doc.garbageCollect();
|
|
|
|
|
|
|
|
REQUIRE(result == true);
|
2023-04-07 14:43:16 +02:00
|
|
|
REQUIRE(doc.memoryUsage() == sizeofObject(1) + sizeofString(7));
|
2023-04-01 19:10:35 +02:00
|
|
|
REQUIRE(doc.as<std::string>() == "{\"dancing\":2}");
|
2023-04-11 10:03:47 +02:00
|
|
|
REQUIRE(spyingAllocator.log() ==
|
2023-07-17 14:39:57 +02:00
|
|
|
AllocatorLog() << AllocatorLog::Allocate(sizeofString(7))
|
|
|
|
<< AllocatorLog::Allocate(sizeofPool())
|
2023-04-11 10:03:47 +02:00
|
|
|
<< AllocatorLog::Deallocate(sizeofString(7))
|
2023-07-21 10:38:35 +02:00
|
|
|
<< AllocatorLog::Deallocate(sizeofPool()));
|
2023-04-01 19:10:35 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
SECTION("when allocation fails") {
|
|
|
|
deserializeJson(doc, "{\"blanket\":1,\"dancing\":2}");
|
2023-04-07 14:43:16 +02:00
|
|
|
REQUIRE(doc.memoryUsage() == sizeofObject(2) + 2 * sizeofString(7));
|
2023-04-01 19:10:35 +02:00
|
|
|
doc.remove("blanket");
|
|
|
|
controllableAllocator.disable();
|
2023-04-11 10:03:47 +02:00
|
|
|
spyingAllocator.clearLog();
|
2023-04-01 19:10:35 +02:00
|
|
|
|
|
|
|
bool result = doc.garbageCollect();
|
|
|
|
|
|
|
|
REQUIRE(result == false);
|
2023-04-17 09:46:41 +02:00
|
|
|
REQUIRE(doc.memoryUsage() == sizeofObject(2) + sizeofString(7));
|
2023-04-01 19:10:35 +02:00
|
|
|
REQUIRE(doc.as<std::string>() == "{\"dancing\":2}");
|
2023-04-02 16:47:37 +02:00
|
|
|
|
2023-07-03 11:53:56 +02:00
|
|
|
REQUIRE(spyingAllocator.log() ==
|
2023-07-17 14:39:57 +02:00
|
|
|
AllocatorLog() << AllocatorLog::AllocateFail(sizeofString(7)));
|
2023-04-01 19:10:35 +02:00
|
|
|
}
|
|
|
|
}
|