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

82 lines
2.0 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 <stdint.h>
#include <catch.hpp>
2023-07-24 17:21:25 +02:00
#include "Allocators.hpp"
2023-04-17 09:46:41 +02:00
using ArduinoJson::detail::sizeofArray;
using ArduinoJson::detail::sizeofString;
TEST_CASE("JsonVariant::remove(int)") {
2023-07-24 17:21:25 +02:00
SpyingAllocator allocator;
JsonDocument doc(&allocator);
2023-04-17 09:46:41 +02:00
SECTION("release top level strings") {
doc.add(std::string("hello"));
doc.add(std::string("hello"));
doc.add(std::string("world"));
JsonVariant var = doc.as<JsonVariant>();
REQUIRE(var.as<std::string>() == "[\"hello\",\"hello\",\"world\"]");
2023-07-24 17:21:25 +02:00
allocator.clearLog();
2023-04-17 09:46:41 +02:00
var.remove(1);
REQUIRE(var.as<std::string>() == "[\"hello\",\"world\"]");
2023-07-24 17:21:25 +02:00
REQUIRE(allocator.log() == AllocatorLog());
2023-07-24 17:21:25 +02:00
allocator.clearLog();
var.remove(1);
2023-04-17 09:46:41 +02:00
REQUIRE(var.as<std::string>() == "[\"hello\"]");
2023-07-24 17:21:25 +02:00
REQUIRE(allocator.log() ==
AllocatorLog() << AllocatorLog::Deallocate(sizeofString(5)));
2023-07-24 17:21:25 +02:00
allocator.clearLog();
2023-04-17 09:46:41 +02:00
var.remove(0);
REQUIRE(var.as<std::string>() == "[]");
2023-07-24 17:21:25 +02:00
REQUIRE(allocator.log() ==
AllocatorLog() << AllocatorLog::Deallocate(sizeofString(5)));
}
2023-04-17 09:46:41 +02:00
SECTION("release strings in nested array") {
doc[0][0] = std::string("hello");
2023-04-17 09:46:41 +02:00
JsonVariant var = doc.as<JsonVariant>();
REQUIRE(var.as<std::string>() == "[[\"hello\"]]");
2023-07-24 17:21:25 +02:00
allocator.clearLog();
2023-04-17 09:46:41 +02:00
var.remove(0);
2023-07-24 17:21:25 +02:00
2023-04-17 09:46:41 +02:00
REQUIRE(var.as<std::string>() == "[]");
2023-07-24 17:21:25 +02:00
REQUIRE(allocator.log() ==
AllocatorLog() << AllocatorLog::Deallocate(sizeofString(5)));
}
2023-04-17 09:46:41 +02:00
}
2023-04-17 09:46:41 +02:00
TEST_CASE("JsonVariant::remove(const char *)") {
JsonDocument doc;
2023-04-17 09:46:41 +02:00
JsonVariant var = doc.to<JsonVariant>();
2023-04-17 09:46:41 +02:00
var["a"] = 1;
var["b"] = 2;
2023-04-17 09:46:41 +02:00
var.remove("a");
REQUIRE(var.as<std::string>() == "{\"b\":2}");
}
TEST_CASE("JsonVariant::remove(std::string)") {
JsonDocument doc;
2023-04-17 09:46:41 +02:00
JsonVariant var = doc.to<JsonVariant>();
var["a"] = 1;
var["b"] = 2;
var.remove(std::string("b"));
REQUIRE(var.as<std::string>() == "{\"a\":1}");
}