// ArduinoJson - https://arduinojson.org // Copyright © 2014-2024, Benoit BLANCHON // MIT License #include #include #include #include "Allocators.hpp" TEST_CASE("JsonVariant::add(T)") { JsonDocument doc; JsonVariant var = doc.to(); SECTION("add integer to new variant") { var.add(42); REQUIRE(var.as() == "[42]"); } SECTION("add const char* to new variant") { var.add("hello"); REQUIRE(var.as() == "[\"hello\"]"); } SECTION("add std::string to new variant") { var.add(std::string("hello")); REQUIRE(var.as() == "[\"hello\"]"); } SECTION("add integer to integer") { var.set(123); var.add(456); // no-op REQUIRE(var.as() == "123"); } SECTION("add integer to object") { var["val"] = 123; var.add(456); // no-op REQUIRE(var.as() == "{\"val\":123}"); } } TEST_CASE("JsonVariant::add()") { JsonDocument doc; JsonVariant var = doc.to(); SECTION("JsonArray") { JsonArray array = var.add(); array.add(1); array.add(2); REQUIRE(doc.as() == "[[1,2]]"); } SECTION("JsonVariant") { JsonVariant variant = var.add(); variant.set(42); REQUIRE(doc.as() == "[42]"); } } TEST_CASE("JsonObject::add(JsonObject) ") { JsonDocument doc1; doc1[std::string("hello")] = std::string("world"); TimebombAllocator allocator(10); SpyingAllocator spy(&allocator); JsonDocument doc2(&spy); JsonVariant variant = doc2.to(); SECTION("success") { bool result = variant.add(doc1.as()); REQUIRE(result == true); REQUIRE(doc2.as() == "[{\"hello\":\"world\"}]"); REQUIRE(spy.log() == AllocatorLog{ Allocate(sizeofPool()), Allocate(sizeofString("hello")), Allocate(sizeofString("world")), }); } SECTION("partial failure") { // issue #2081 allocator.setCountdown(2); bool result = variant.add(doc1.as()); REQUIRE(result == false); REQUIRE(doc2.as() == "[]"); REQUIRE(spy.log() == AllocatorLog{ Allocate(sizeofPool()), Allocate(sizeofString("hello")), AllocateFail(sizeofString("world")), Deallocate(sizeofString("hello")), }); } SECTION("complete failure") { allocator.setCountdown(0); bool result = variant.add(doc1.as()); REQUIRE(result == false); REQUIRE(doc2.as() == "[]"); REQUIRE(spy.log() == AllocatorLog{ AllocateFail(sizeofPool()), }); } }