BasicJsonDocument.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // ArduinoJson - https://arduinojson.org
  2. // Copyright © 2014-2025, Benoit BLANCHON
  3. // MIT License
  4. #include <ArduinoJson.h>
  5. #include <catch.hpp>
  6. #include <string>
  7. using ArduinoJson::detail::is_base_of;
  8. static std::string allocatorLog;
  9. struct CustomAllocator {
  10. CustomAllocator() {
  11. allocatorLog = "";
  12. }
  13. void* allocate(size_t n) {
  14. allocatorLog += "A";
  15. return malloc(n);
  16. }
  17. void deallocate(void* p) {
  18. free(p);
  19. allocatorLog += "D";
  20. }
  21. void* reallocate(void* p, size_t n) {
  22. allocatorLog += "R";
  23. return realloc(p, n);
  24. }
  25. };
  26. TEST_CASE("BasicJsonDocument") {
  27. allocatorLog.clear();
  28. SECTION("is a JsonDocument") {
  29. REQUIRE(
  30. is_base_of<JsonDocument, BasicJsonDocument<CustomAllocator>>::value ==
  31. true);
  32. }
  33. SECTION("deserialize / serialize") {
  34. BasicJsonDocument<CustomAllocator> doc(256);
  35. deserializeJson(doc, "{\"hello\":\"world\"}");
  36. REQUIRE(doc.as<std::string>() == "{\"hello\":\"world\"}");
  37. doc.clear();
  38. REQUIRE(allocatorLog == "AARARDDD");
  39. }
  40. SECTION("copy") {
  41. BasicJsonDocument<CustomAllocator> doc(256);
  42. doc["hello"] = "world";
  43. auto copy = doc;
  44. REQUIRE(copy.as<std::string>() == "{\"hello\":\"world\"}");
  45. REQUIRE(allocatorLog == "AAAA");
  46. }
  47. SECTION("capacity") {
  48. BasicJsonDocument<CustomAllocator> doc(256);
  49. REQUIRE(doc.capacity() == 256);
  50. }
  51. SECTION("garbageCollect()") {
  52. BasicJsonDocument<CustomAllocator> doc(256);
  53. doc.garbageCollect();
  54. }
  55. }