copy.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // ArduinoJson - arduinojson.org
  2. // Copyright Benoit Blanchon 2014-2020
  3. // MIT License
  4. #include <ArduinoJson.h>
  5. #include <catch.hpp>
  6. TEST_CASE("JsonObject::set()") {
  7. DynamicJsonDocument doc1(4096);
  8. DynamicJsonDocument doc2(4096);
  9. JsonObject obj1 = doc1.to<JsonObject>();
  10. JsonObject obj2 = doc2.to<JsonObject>();
  11. SECTION("doesn't copy static string in key or value") {
  12. obj1["hello"] = "world";
  13. bool success = obj2.set(obj1);
  14. REQUIRE(success == true);
  15. REQUIRE(doc1.memoryUsage() == doc2.memoryUsage());
  16. REQUIRE(obj2["hello"] == std::string("world"));
  17. }
  18. SECTION("copy local string value") {
  19. obj1["hello"] = std::string("world");
  20. bool success = obj2.set(obj1);
  21. REQUIRE(success == true);
  22. REQUIRE(doc1.memoryUsage() == doc2.memoryUsage());
  23. REQUIRE(obj2["hello"] == std::string("world"));
  24. }
  25. SECTION("copy local key") {
  26. obj1[std::string("hello")] = "world";
  27. bool success = obj2.set(obj1);
  28. REQUIRE(success == true);
  29. REQUIRE(doc1.memoryUsage() == doc2.memoryUsage());
  30. REQUIRE(obj2["hello"] == std::string("world"));
  31. }
  32. SECTION("copy string from deserializeJson()") {
  33. deserializeJson(doc1, "{'hello':'world'}");
  34. bool success = obj2.set(obj1);
  35. REQUIRE(success == true);
  36. REQUIRE(doc1.memoryUsage() == doc2.memoryUsage());
  37. REQUIRE(obj2["hello"] == std::string("world"));
  38. }
  39. SECTION("copy string from deserializeMsgPack()") {
  40. deserializeMsgPack(doc1, "\x81\xA5hello\xA5world");
  41. bool success = obj2.set(obj1);
  42. REQUIRE(success == true);
  43. REQUIRE(doc1.memoryUsage() == doc2.memoryUsage());
  44. REQUIRE(obj2["hello"] == std::string("world"));
  45. }
  46. SECTION("should work with JsonObjectConst") {
  47. obj1["hello"] = "world";
  48. obj2.set(static_cast<JsonObjectConst>(obj1));
  49. REQUIRE(doc1.memoryUsage() == doc2.memoryUsage());
  50. REQUIRE(obj2["hello"] == std::string("world"));
  51. }
  52. SECTION("destination too small to store the key") {
  53. StaticJsonDocument<JSON_OBJECT_SIZE(1)> doc3;
  54. JsonObject obj3 = doc3.to<JsonObject>();
  55. obj1[std::string("hello")] = "world";
  56. bool success = obj3.set(obj1);
  57. REQUIRE(success == false);
  58. REQUIRE(doc3.as<std::string>() == "{}");
  59. }
  60. SECTION("destination too small to store the value") {
  61. StaticJsonDocument<JSON_OBJECT_SIZE(1)> doc3;
  62. JsonObject obj3 = doc3.to<JsonObject>();
  63. obj1["hello"] = std::string("world");
  64. bool success = obj3.set(obj1);
  65. REQUIRE(success == false);
  66. REQUIRE(doc3.as<std::string>() == "{\"hello\":null}");
  67. }
  68. }