remove.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // ArduinoJson - https://arduinojson.org
  2. // Copyright © 2014-2024, Benoit BLANCHON
  3. // MIT License
  4. #include <ArduinoJson.h>
  5. #include <stdint.h>
  6. #include <catch.hpp>
  7. #include "Allocators.hpp"
  8. using ArduinoJson::detail::sizeofArray;
  9. TEST_CASE("JsonVariant::remove(int)") {
  10. SpyingAllocator spy;
  11. JsonDocument doc(&spy);
  12. SECTION("release top level strings") {
  13. doc.add(std::string("hello"));
  14. doc.add(std::string("hello"));
  15. doc.add(std::string("world"));
  16. JsonVariant var = doc.as<JsonVariant>();
  17. REQUIRE(var.as<std::string>() == "[\"hello\",\"hello\",\"world\"]");
  18. spy.clearLog();
  19. var.remove(1);
  20. REQUIRE(var.as<std::string>() == "[\"hello\",\"world\"]");
  21. REQUIRE(spy.log() == AllocatorLog{});
  22. spy.clearLog();
  23. var.remove(1);
  24. REQUIRE(var.as<std::string>() == "[\"hello\"]");
  25. REQUIRE(spy.log() == AllocatorLog{
  26. Deallocate(sizeofString("world")),
  27. });
  28. spy.clearLog();
  29. var.remove(0);
  30. REQUIRE(var.as<std::string>() == "[]");
  31. REQUIRE(spy.log() == AllocatorLog{
  32. Deallocate(sizeofString("hello")),
  33. });
  34. }
  35. SECTION("release strings in nested array") {
  36. doc[0][0] = std::string("hello");
  37. JsonVariant var = doc.as<JsonVariant>();
  38. REQUIRE(var.as<std::string>() == "[[\"hello\"]]");
  39. spy.clearLog();
  40. var.remove(0);
  41. REQUIRE(var.as<std::string>() == "[]");
  42. REQUIRE(spy.log() == AllocatorLog{
  43. Deallocate(sizeofString("hello")),
  44. });
  45. }
  46. }
  47. TEST_CASE("JsonVariant::remove(const char *)") {
  48. JsonDocument doc;
  49. JsonVariant var = doc.to<JsonVariant>();
  50. var["a"] = 1;
  51. var["b"] = 2;
  52. var.remove("a");
  53. REQUIRE(var.as<std::string>() == "{\"b\":2}");
  54. }
  55. TEST_CASE("JsonVariant::remove(std::string)") {
  56. JsonDocument doc;
  57. JsonVariant var = doc.to<JsonVariant>();
  58. var["a"] = 1;
  59. var["b"] = 2;
  60. var.remove(std::string("b"));
  61. REQUIRE(var.as<std::string>() == "{\"a\":1}");
  62. }