Files
ArduinoJson/extras/tests/JsonArray/remove.cpp

112 lines
2.4 KiB
C++
Raw Normal View History

// ArduinoJson - https://arduinojson.org
2023-02-16 11:45:01 +01:00
// Copyright © 2014-2023, Benoit BLANCHON
// MIT License
#include <ArduinoJson.h>
#include <catch.hpp>
2023-07-20 17:54:38 +02:00
#include "Allocators.hpp"
TEST_CASE("JsonArray::remove()") {
JsonDocument doc;
2021-09-10 08:40:02 +02:00
JsonArray array = doc.to<JsonArray>();
array.add(1);
array.add(2);
array.add(3);
2021-09-10 08:40:02 +02:00
SECTION("remove first by index") {
array.remove(0);
2021-09-10 08:40:02 +02:00
REQUIRE(2 == array.size());
REQUIRE(array[0] == 2);
REQUIRE(array[1] == 3);
}
2021-09-10 08:40:02 +02:00
SECTION("remove middle by index") {
array.remove(1);
2021-09-10 08:40:02 +02:00
REQUIRE(2 == array.size());
REQUIRE(array[0] == 1);
REQUIRE(array[1] == 3);
}
2021-09-10 08:40:02 +02:00
SECTION("remove last by index") {
array.remove(2);
2021-09-10 08:40:02 +02:00
REQUIRE(2 == array.size());
REQUIRE(array[0] == 1);
REQUIRE(array[1] == 2);
}
2021-09-10 08:40:02 +02:00
SECTION("remove first by iterator") {
JsonArray::iterator it = array.begin();
array.remove(it);
2021-09-10 08:40:02 +02:00
REQUIRE(2 == array.size());
REQUIRE(array[0] == 2);
REQUIRE(array[1] == 3);
}
2021-09-10 08:40:02 +02:00
SECTION("remove middle by iterator") {
JsonArray::iterator it = array.begin();
++it;
2021-09-10 08:40:02 +02:00
array.remove(it);
2021-09-10 08:40:02 +02:00
REQUIRE(2 == array.size());
REQUIRE(array[0] == 1);
REQUIRE(array[1] == 3);
}
2021-09-10 08:40:02 +02:00
SECTION("remove last bty iterator") {
JsonArray::iterator it = array.begin();
++it;
++it;
2021-09-10 08:40:02 +02:00
array.remove(it);
2021-09-10 08:40:02 +02:00
REQUIRE(2 == array.size());
REQUIRE(array[0] == 1);
REQUIRE(array[1] == 2);
}
SECTION("In a loop") {
2021-09-10 08:40:02 +02:00
for (JsonArray::iterator it = array.begin(); it != array.end(); ++it) {
if (*it == 2)
2021-09-10 08:40:02 +02:00
array.remove(it);
}
2021-09-10 08:40:02 +02:00
REQUIRE(2 == array.size());
REQUIRE(array[0] == 1);
REQUIRE(array[1] == 3);
}
SECTION("remove by index on unbound reference") {
JsonArray unboundArray;
unboundArray.remove(20);
}
SECTION("remove by iterator on unbound reference") {
JsonArray unboundArray;
unboundArray.remove(unboundArray.begin());
}
}
2023-07-20 17:54:38 +02:00
TEST_CASE("Removed elements are recycled") {
SpyingAllocator allocator;
JsonDocument doc(&allocator);
JsonArray array = doc.to<JsonArray>();
// fill the pool entirely
for (int i = 0; i < ARDUINOJSON_POOL_CAPACITY; i++)
array.add(i);
// free one slot in the pool
array.remove(0);
// add one element; it should use the free slot
array.add(42);
2023-07-21 10:38:35 +02:00
REQUIRE(allocator.log() == AllocatorLog() << AllocatorLog::Allocate(
sizeofPool()) // only one pool
2023-07-20 17:54:38 +02:00
);
}