From ab8de582d8f946b36f2ced1efbf556c8ffd9765c Mon Sep 17 00:00:00 2001 From: hidaba Date: Sun, 14 May 2023 11:02:22 +0200 Subject: [PATCH] added library json --- PylontechMonitoring.ino | 12 +- libraries/ArduinoJson/ArduinoJson.h | 5 + libraries/ArduinoJson/CHANGELOG.md | 845 + libraries/ArduinoJson/CMakeLists.txt | 25 + libraries/ArduinoJson/CONTRIBUTING.md | 10 + libraries/ArduinoJson/LICENSE.txt | 10 + libraries/ArduinoJson/README.md | 161 + libraries/ArduinoJson/SUPPORT.md | 27 + libraries/ArduinoJson/appveyor.yml | 28 + libraries/ArduinoJson/component.mk | 1 + .../JsonConfigFile/JsonConfigFile.ino | 160 + .../JsonFilterExample/JsonFilterExample.ino | 63 + .../JsonGeneratorExample.ino | 77 + .../JsonHttpClient/JsonHttpClient.ino | 126 + .../JsonParserExample/JsonParserExample.ino | 80 + .../examples/JsonServer/JsonServer.ino | 117 + .../examples/JsonUdpBeacon/JsonUdpBeacon.ino | 106 + .../examples/MsgPackParser/MsgPackParser.ino | 75 + .../ProgmemExample/ProgmemExample.ino | 63 + .../examples/StringExample/StringExample.ino | 77 + .../extras/ArduinoJsonConfig.cmake.in | 4 + .../ArduinoJson/extras/CompileOptions.cmake | 95 + .../extras/ci/espidf/CMakeLists.txt | 8 + .../extras/ci/espidf/main/CMakeLists.txt | 8 + .../extras/ci/espidf/main/component.mk | 4 + .../extras/ci/espidf/main/main.cpp | 16 + libraries/ArduinoJson/extras/ci/particle.sh | 10 + .../ArduinoJson/extras/conf_test/avr.cpp | 18 + .../ArduinoJson/extras/conf_test/esp8266.cpp | 16 + .../ArduinoJson/extras/conf_test/x64.cpp | 15 + .../ArduinoJson/extras/conf_test/x86.cpp | 15 + .../ArduinoJson/extras/fuzzing/CMakeLists.txt | 58 + libraries/ArduinoJson/extras/fuzzing/Makefile | 22 + .../extras/fuzzing/json_fuzzer.cpp | 11 + .../fuzzing/json_seed_corpus/Comments.json | 10 + .../fuzzing/json_seed_corpus/EmptyArray.json | 1 + .../fuzzing/json_seed_corpus/EmptyObject.json | 1 + .../json_seed_corpus/ExcessiveNesting.json | 1 + .../json_seed_corpus/IntegerOverflow.json | 1 + .../fuzzing/json_seed_corpus/Numbers.json | 24 + .../json_seed_corpus/OpenWeatherMap.json | 53 + .../fuzzing/json_seed_corpus/Strings.json | 8 + .../json_seed_corpus/WeatherUnderground.json | 90 + .../extras/fuzzing/msgpack_fuzzer.cpp | 11 + .../fuzzing/msgpack_seed_corpus/array16 | Bin 0 -> 15 bytes .../fuzzing/msgpack_seed_corpus/array32 | Bin 0 -> 15 bytes .../extras/fuzzing/msgpack_seed_corpus/false | 1 + .../fuzzing/msgpack_seed_corpus/fixarray | 1 + .../msgpack_seed_corpus/fixint_negative | 1 + .../msgpack_seed_corpus/fixint_positive | 1 + .../extras/fuzzing/msgpack_seed_corpus/fixmap | 1 + .../extras/fuzzing/msgpack_seed_corpus/fixstr | 1 + .../fuzzing/msgpack_seed_corpus/float32 | 1 + .../fuzzing/msgpack_seed_corpus/float64 | 1 + .../extras/fuzzing/msgpack_seed_corpus/int16 | 1 + .../extras/fuzzing/msgpack_seed_corpus/int32 | 1 + .../extras/fuzzing/msgpack_seed_corpus/int64 | 1 + .../extras/fuzzing/msgpack_seed_corpus/int8 | 1 + .../extras/fuzzing/msgpack_seed_corpus/map16 | Bin 0 -> 19 bytes .../extras/fuzzing/msgpack_seed_corpus/map32 | Bin 0 -> 23 bytes .../extras/fuzzing/msgpack_seed_corpus/nil | 1 + .../extras/fuzzing/msgpack_seed_corpus/str16 | Bin 0 -> 8 bytes .../extras/fuzzing/msgpack_seed_corpus/str32 | Bin 0 -> 10 bytes .../extras/fuzzing/msgpack_seed_corpus/str8 | 1 + .../extras/fuzzing/msgpack_seed_corpus/true | 1 + .../extras/fuzzing/msgpack_seed_corpus/uint16 | 1 + .../extras/fuzzing/msgpack_seed_corpus/uint32 | 1 + .../extras/fuzzing/msgpack_seed_corpus/uint64 | 1 + .../extras/fuzzing/msgpack_seed_corpus/uint8 | 1 + .../ArduinoJson/extras/fuzzing/reproducer.cpp | 50 + .../extras/particle/project.properties | 1 + .../extras/particle/src/smocktest.ino | 5 + .../extras/scripts/build-arduino-package.sh | 23 + .../extras/scripts/build-single-header.sh | 65 + .../extras/scripts/get-release-body.sh | 14 + .../extras/scripts/get-release-page.sh | 18 + .../scripts/publish-particle-library.sh | 18 + .../ArduinoJson/extras/scripts/publish.sh | 78 + .../scripts/wandbox/JsonGeneratorExample.cpp | 60 + .../scripts/wandbox/JsonParserExample.cpp | 59 + .../scripts/wandbox/MsgPackParserExample.cpp | 68 + .../extras/scripts/wandbox/publish.sh | 29 + .../ArduinoJson/extras/tests/CMakeLists.txt | 29 + .../extras/tests/Cpp17/CMakeLists.txt | 29 + .../extras/tests/Cpp17/string_view.cpp | 100 + .../extras/tests/Cpp20/CMakeLists.txt | 29 + .../extras/tests/Cpp20/smoke_test.cpp | 15 + .../extras/tests/FailingBuilds/CMakeLists.txt | 42 + .../extras/tests/FailingBuilds/Issue1189.cpp | 13 + .../extras/tests/FailingBuilds/Issue978.cpp | 13 + .../tests/FailingBuilds/assign_char.cpp | 12 + .../FailingBuilds/delete_jsondocument.cpp | 12 + .../tests/FailingBuilds/read_long_long.cpp | 16 + .../tests/FailingBuilds/variant_as_char.cpp | 12 + .../tests/FailingBuilds/write_long_long.cpp | 15 + .../extras/tests/Helpers/Arduino.h | 13 + .../extras/tests/Helpers/CustomReader.hpp | 24 + .../extras/tests/Helpers/api/Print.h | 33 + .../extras/tests/Helpers/api/Stream.h | 14 + .../extras/tests/Helpers/api/String.h | 69 + .../extras/tests/Helpers/avr/pgmspace.h | 31 + .../tests/IntegrationTests/CMakeLists.txt | 24 + .../tests/IntegrationTests/gbathree.cpp | 210 + .../tests/IntegrationTests/issue772.cpp | 28 + .../tests/IntegrationTests/openweathermap.cpp | 68 + .../tests/IntegrationTests/round_trip.cpp | 82 + .../extras/tests/JsonArray/CMakeLists.txt | 28 + .../extras/tests/JsonArray/add.cpp | 138 + .../extras/tests/JsonArray/clear.cpp | 25 + .../extras/tests/JsonArray/compare.cpp | 512 + .../extras/tests/JsonArray/copyArray.cpp | 346 + .../extras/tests/JsonArray/createNested.cpp | 21 + .../extras/tests/JsonArray/equals.cpp | 69 + .../extras/tests/JsonArray/isNull.cpp | 58 + .../extras/tests/JsonArray/iterator.cpp | 52 + .../extras/tests/JsonArray/memoryUsage.cpp | 42 + .../extras/tests/JsonArray/nesting.cpp | 35 + .../extras/tests/JsonArray/remove.cpp | 89 + .../extras/tests/JsonArray/size.cpp | 31 + .../extras/tests/JsonArray/std_string.cpp | 32 + .../extras/tests/JsonArray/subscript.cpp | 174 + .../extras/tests/JsonArray/unbound.cpp | 35 + .../tests/JsonDeserializer/CMakeLists.txt | 28 + .../JsonDeserializer/DeserializationError.cpp | 122 + .../extras/tests/JsonDeserializer/array.cpp | 253 + .../tests/JsonDeserializer/array_static.cpp | 89 + .../extras/tests/JsonDeserializer/filter.cpp | 809 + .../JsonDeserializer/incomplete_input.cpp | 29 + .../tests/JsonDeserializer/input_types.cpp | 222 + .../tests/JsonDeserializer/invalid_input.cpp | 40 + .../extras/tests/JsonDeserializer/misc.cpp | 117 + .../tests/JsonDeserializer/nestingLimit.cpp | 103 + .../extras/tests/JsonDeserializer/number.cpp | 133 + .../extras/tests/JsonDeserializer/object.cpp | 315 + .../tests/JsonDeserializer/object_static.cpp | 64 + .../extras/tests/JsonDeserializer/string.cpp | 132 + .../tests/JsonDocument/BasicJsonDocument.cpp | 180 + .../extras/tests/JsonDocument/CMakeLists.txt | 32 + .../JsonDocument/DynamicJsonDocument.cpp | 230 + .../tests/JsonDocument/ElementProxy.cpp | 255 + .../extras/tests/JsonDocument/MemberProxy.cpp | 328 + .../tests/JsonDocument/StaticJsonDocument.cpp | 224 + .../extras/tests/JsonDocument/add.cpp | 22 + .../extras/tests/JsonDocument/cast.cpp | 18 + .../extras/tests/JsonDocument/compare.cpp | 103 + .../extras/tests/JsonDocument/containsKey.cpp | 44 + .../tests/JsonDocument/createNested.cpp | 66 + .../extras/tests/JsonDocument/isNull.cpp | 39 + .../extras/tests/JsonDocument/issue1120.cpp | 58 + .../extras/tests/JsonDocument/nesting.cpp | 30 + .../extras/tests/JsonDocument/overflowed.cpp | 85 + .../extras/tests/JsonDocument/remove.cpp | 52 + .../extras/tests/JsonDocument/shrinkToFit.cpp | 152 + .../extras/tests/JsonDocument/size.cpp | 28 + .../extras/tests/JsonDocument/subscript.cpp | 53 + .../extras/tests/JsonDocument/swap.cpp | 27 + .../extras/tests/JsonObject/CMakeLists.txt | 29 + .../extras/tests/JsonObject/clear.cpp | 25 + .../extras/tests/JsonObject/compare.cpp | 512 + .../extras/tests/JsonObject/containsKey.cpp | 39 + .../extras/tests/JsonObject/copy.cpp | 115 + .../tests/JsonObject/createNestedArray.cpp | 27 + .../tests/JsonObject/createNestedObject.cpp | 25 + .../extras/tests/JsonObject/equals.cpp | 67 + .../extras/tests/JsonObject/invalid.cpp | 35 + .../extras/tests/JsonObject/isNull.cpp | 58 + .../extras/tests/JsonObject/iterator.cpp | 73 + .../extras/tests/JsonObject/memoryUsage.cpp | 43 + .../extras/tests/JsonObject/nesting.cpp | 35 + .../extras/tests/JsonObject/remove.cpp | 82 + .../extras/tests/JsonObject/size.cpp | 39 + .../extras/tests/JsonObject/std_string.cpp | 110 + .../extras/tests/JsonObject/subscript.cpp | 233 + .../tests/JsonSerializer/CMakeLists.txt | 22 + .../tests/JsonSerializer/CustomWriter.cpp | 51 + .../extras/tests/JsonSerializer/JsonArray.cpp | 129 + .../tests/JsonSerializer/JsonArrayPretty.cpp | 75 + .../tests/JsonSerializer/JsonObject.cpp | 119 + .../tests/JsonSerializer/JsonObjectPretty.cpp | 77 + .../tests/JsonSerializer/JsonVariant.cpp | 121 + .../extras/tests/JsonSerializer/misc.cpp | 36 + .../tests/JsonSerializer/std_stream.cpp | 66 + .../tests/JsonSerializer/std_string.cpp | 57 + .../extras/tests/JsonVariant/CMakeLists.txt | 37 + .../extras/tests/JsonVariant/add.cpp | 46 + .../extras/tests/JsonVariant/as.cpp | 270 + .../extras/tests/JsonVariant/clear.cpp | 26 + .../extras/tests/JsonVariant/compare.cpp | 316 + .../extras/tests/JsonVariant/containsKey.cpp | 42 + .../extras/tests/JsonVariant/converters.cpp | 154 + .../extras/tests/JsonVariant/copy.cpp | 95 + .../extras/tests/JsonVariant/createNested.cpp | 58 + .../extras/tests/JsonVariant/is.cpp | 319 + .../extras/tests/JsonVariant/isnull.cpp | 93 + .../extras/tests/JsonVariant/memoryUsage.cpp | 41 + .../extras/tests/JsonVariant/misc.cpp | 55 + .../extras/tests/JsonVariant/nesting.cpp | 31 + .../extras/tests/JsonVariant/nullptr.cpp | 43 + .../extras/tests/JsonVariant/or.cpp | 159 + .../extras/tests/JsonVariant/overflow.cpp | 72 + .../extras/tests/JsonVariant/remove.cpp | 40 + .../extras/tests/JsonVariant/set.cpp | 172 + .../extras/tests/JsonVariant/shallowCopy.cpp | 87 + .../extras/tests/JsonVariant/size.cpp | 36 + .../tests/JsonVariant/stl_containers.cpp | 138 + .../extras/tests/JsonVariant/subscript.cpp | 204 + .../extras/tests/JsonVariant/types.cpp | 163 + .../extras/tests/JsonVariant/unbound.cpp | 66 + .../extras/tests/MemoryPool/CMakeLists.txt | 18 + .../extras/tests/MemoryPool/StringCopier.cpp | 93 + .../extras/tests/MemoryPool/allocVariant.cpp | 50 + .../extras/tests/MemoryPool/clear.cpp | 32 + .../extras/tests/MemoryPool/saveString.cpp | 106 + .../extras/tests/MemoryPool/size.cpp | 36 + .../extras/tests/Misc/CMakeLists.txt | 29 + .../extras/tests/Misc/FloatParts.cpp | 44 + .../extras/tests/Misc/JsonString.cpp | 103 + .../extras/tests/Misc/NoArduinoHeader.cpp | 20 + .../ArduinoJson/extras/tests/Misc/Readers.cpp | 227 + .../extras/tests/Misc/StringAdapters.cpp | 190 + .../extras/tests/Misc/StringWriter.cpp | 156 + .../extras/tests/Misc/TypeTraits.cpp | 216 + .../ArduinoJson/extras/tests/Misc/Utf16.cpp | 68 + .../ArduinoJson/extras/tests/Misc/Utf8.cpp | 60 + .../extras/tests/Misc/arithmeticCompare.cpp | 97 + .../extras/tests/Misc/conflicts.cpp | 59 + .../extras/tests/Misc/custom_string.hpp | 12 + .../extras/tests/Misc/printable.cpp | 144 + .../extras/tests/Misc/unsigned_char.cpp | 271 + .../ArduinoJson/extras/tests/Misc/version.cpp | 18 + .../extras/tests/Misc/weird_strcmp.hpp | 31 + .../tests/MixedConfiguration/CMakeLists.txt | 33 + .../MixedConfiguration/decode_unicode_0.cpp | 12 + .../MixedConfiguration/decode_unicode_1.cpp | 11 + .../MixedConfiguration/enable_alignment_0.cpp | 41 + .../MixedConfiguration/enable_alignment_1.cpp | 40 + .../MixedConfiguration/enable_comments_0.cpp | 54 + .../MixedConfiguration/enable_comments_1.cpp | 411 + .../MixedConfiguration/enable_infinity_0.cpp | 35 + .../MixedConfiguration/enable_infinity_1.cpp | 39 + .../tests/MixedConfiguration/enable_nan_0.cpp | 25 + .../tests/MixedConfiguration/enable_nan_1.cpp | 31 + .../MixedConfiguration/enable_progmem_1.cpp | 191 + .../enable_string_deduplication_0.cpp | 123 + .../enable_string_deduplication_1.cpp | 122 + .../tests/MixedConfiguration/issue1707.cpp | 17 + .../tests/MixedConfiguration/use_double_0.cpp | 17 + .../tests/MixedConfiguration/use_double_1.cpp | 17 + .../MixedConfiguration/use_long_long_0.cpp | 16 + .../MixedConfiguration/use_long_long_1.cpp | 17 + .../tests/MsgPackDeserializer/CMakeLists.txt | 24 + .../MsgPackDeserializer/deserializeArray.cpp | 83 + .../MsgPackDeserializer/deserializeObject.cpp | 130 + .../deserializeStaticVariant.cpp | 152 + .../deserializeVariant.cpp | 147 + .../MsgPackDeserializer/doubleToFloat.cpp | 25 + .../tests/MsgPackDeserializer/filter.cpp | 1135 + .../MsgPackDeserializer/incompleteInput.cpp | 158 + .../tests/MsgPackDeserializer/input_types.cpp | 95 + .../extras/tests/MsgPackDeserializer/misc.cpp | 26 + .../MsgPackDeserializer/nestingLimit.cpp | 87 + .../MsgPackDeserializer/notSupported.cpp | 82 + .../tests/MsgPackSerializer/CMakeLists.txt | 19 + .../MsgPackSerializer/destination_types.cpp | 59 + .../tests/MsgPackSerializer/measure.cpp | 14 + .../extras/tests/MsgPackSerializer/misc.cpp | 46 + .../MsgPackSerializer/serializeArray.cpp | 60 + .../MsgPackSerializer/serializeObject.cpp | 83 + .../MsgPackSerializer/serializeVariant.cpp | 162 + .../extras/tests/Numbers/CMakeLists.txt | 18 + .../extras/tests/Numbers/convertNumber.cpp | 131 + .../extras/tests/Numbers/parseDouble.cpp | 96 + .../extras/tests/Numbers/parseFloat.cpp | 101 + .../extras/tests/Numbers/parseInteger.cpp | 68 + .../extras/tests/Numbers/parseNumber.cpp | 53 + .../extras/tests/TextFormatter/CMakeLists.txt | 18 + .../extras/tests/TextFormatter/writeFloat.cpp | 119 + .../tests/TextFormatter/writeInteger.cpp | 55 + .../tests/TextFormatter/writeString.cpp | 57 + .../extras/tests/catch/CMakeLists.txt | 21 + .../ArduinoJson/extras/tests/catch/catch.cpp | 6 + .../ArduinoJson/extras/tests/catch/catch.hpp | 17976 ++++++++++++++++ libraries/ArduinoJson/idf_component.yml | 13 + libraries/ArduinoJson/keywords.txt | 40 + libraries/ArduinoJson/library.json | 25 + libraries/ArduinoJson/library.properties | 11 + libraries/ArduinoJson/src/ArduinoJson.h | 17 + libraries/ArduinoJson/src/ArduinoJson.hpp | 52 + .../src/ArduinoJson/Array/ElementProxy.hpp | 60 + .../src/ArduinoJson/Array/JsonArray.hpp | 211 + .../src/ArduinoJson/Array/JsonArrayConst.hpp | 135 + .../src/ArduinoJson/Array/JsonArrayImpl.hpp | 36 + .../ArduinoJson/Array/JsonArrayIterator.hpp | 121 + .../src/ArduinoJson/Array/Utilities.hpp | 114 + .../ArduinoJson/Collection/CollectionData.hpp | 95 + .../ArduinoJson/Collection/CollectionImpl.hpp | 197 + .../src/ArduinoJson/Configuration.hpp | 217 + .../Deserialization/DeserializationError.hpp | 106 + .../DeserializationOptions.hpp | 35 + .../ArduinoJson/Deserialization/Filter.hpp | 70 + .../Deserialization/NestingLimit.hpp | 32 + .../ArduinoJson/Deserialization/Reader.hpp | 73 + .../Readers/ArduinoStreamReader.hpp | 31 + .../Readers/ArduinoStringReader.hpp | 19 + .../Deserialization/Readers/FlashReader.hpp | 56 + .../Readers/IteratorReader.hpp | 45 + .../Deserialization/Readers/RamReader.hpp | 51 + .../Readers/StdStreamReader.hpp | 30 + .../Deserialization/Readers/VariantReader.hpp | 19 + .../Deserialization/deserialize.hpp | 66 + .../Document/BasicJsonDocument.hpp | 168 + .../Document/DynamicJsonDocument.hpp | 32 + .../src/ArduinoJson/Document/JsonDocument.hpp | 325 + .../Document/StaticJsonDocument.hpp | 61 + .../src/ArduinoJson/Json/EscapeSequence.hpp | 40 + .../src/ArduinoJson/Json/JsonDeserializer.hpp | 693 + .../src/ArduinoJson/Json/JsonSerializer.hpp | 155 + .../src/ArduinoJson/Json/Latch.hpp | 56 + .../ArduinoJson/Json/PrettyJsonSerializer.hpp | 101 + .../src/ArduinoJson/Json/TextFormatter.hpp | 173 + .../src/ArduinoJson/Json/Utf16.hpp | 67 + .../ArduinoJson/src/ArduinoJson/Json/Utf8.hpp | 46 + .../src/ArduinoJson/Memory/Alignment.hpp | 60 + .../src/ArduinoJson/Memory/MemoryPool.hpp | 253 + .../src/ArduinoJson/Misc/SerializedValue.hpp | 69 + .../MsgPack/MsgPackDeserializer.hpp | 585 + .../ArduinoJson/MsgPack/MsgPackSerializer.hpp | 227 + .../src/ArduinoJson/MsgPack/endianess.hpp | 46 + .../src/ArduinoJson/MsgPack/ieee754.hpp | 18 + .../ArduinoJson/src/ArduinoJson/Namespace.hpp | 43 + .../src/ArduinoJson/Numbers/FloatParts.hpp | 88 + .../src/ArduinoJson/Numbers/FloatTraits.hpp | 212 + .../src/ArduinoJson/Numbers/JsonFloat.hpp | 18 + .../src/ArduinoJson/Numbers/JsonInteger.hpp | 28 + .../ArduinoJson/Numbers/arithmeticCompare.hpp | 120 + .../src/ArduinoJson/Numbers/convertNumber.hpp | 135 + .../src/ArduinoJson/Numbers/parseNumber.hpp | 152 + .../src/ArduinoJson/Object/JsonObject.hpp | 251 + .../ArduinoJson/Object/JsonObjectConst.hpp | 156 + .../src/ArduinoJson/Object/JsonObjectImpl.hpp | 85 + .../ArduinoJson/Object/JsonObjectIterator.hpp | 123 + .../src/ArduinoJson/Object/JsonPair.hpp | 68 + .../src/ArduinoJson/Object/MemberProxy.hpp | 64 + .../src/ArduinoJson/Polyfills/alias_cast.hpp | 30 + .../src/ArduinoJson/Polyfills/assert.hpp | 14 + .../src/ArduinoJson/Polyfills/attributes.hpp | 32 + .../src/ArduinoJson/Polyfills/ctype.hpp | 21 + .../src/ArduinoJson/Polyfills/integer.hpp | 31 + .../src/ArduinoJson/Polyfills/limits.hpp | 45 + .../src/ArduinoJson/Polyfills/math.hpp | 27 + .../src/ArduinoJson/Polyfills/mpl/max.hpp | 27 + .../src/ArduinoJson/Polyfills/pgmspace.hpp | 144 + .../Polyfills/pgmspace_generic.hpp | 67 + .../ArduinoJson/Polyfills/preprocessor.hpp | 31 + .../src/ArduinoJson/Polyfills/type_traits.hpp | 25 + .../Polyfills/type_traits/conditional.hpp | 21 + .../Polyfills/type_traits/declval.hpp | 14 + .../Polyfills/type_traits/enable_if.hpp | 20 + .../type_traits/integral_constant.hpp | 19 + .../Polyfills/type_traits/is_array.hpp | 22 + .../Polyfills/type_traits/is_base_of.hpp | 27 + .../Polyfills/type_traits/is_class.hpp | 23 + .../Polyfills/type_traits/is_const.hpp | 18 + .../Polyfills/type_traits/is_convertible.hpp | 46 + .../Polyfills/type_traits/is_enum.hpp | 22 + .../type_traits/is_floating_point.hpp | 20 + .../Polyfills/type_traits/is_integral.hpp | 32 + .../Polyfills/type_traits/is_pointer.hpp | 17 + .../Polyfills/type_traits/is_same.hpp | 18 + .../Polyfills/type_traits/is_signed.hpp | 26 + .../Polyfills/type_traits/is_unsigned.hpp | 24 + .../Polyfills/type_traits/make_unsigned.hpp | 41 + .../Polyfills/type_traits/make_void.hpp | 14 + .../Polyfills/type_traits/remove_const.hpp | 21 + .../Polyfills/type_traits/remove_cv.hpp | 28 + .../type_traits/remove_reference.hpp | 21 + .../Polyfills/type_traits/type_identity.hpp | 16 + .../src/ArduinoJson/Polyfills/utility.hpp | 16 + .../Serialization/CountingDecorator.hpp | 33 + .../src/ArduinoJson/Serialization/Writer.hpp | 47 + .../Writers/ArduinoStringWriter.hpp | 53 + .../Serialization/Writers/DummyWriter.hpp | 22 + .../Serialization/Writers/PrintWriter.hpp | 30 + .../Writers/StaticStringWriter.hpp | 36 + .../Serialization/Writers/StdStreamWriter.hpp | 33 + .../Serialization/Writers/StdStringWriter.hpp | 43 + .../src/ArduinoJson/Serialization/measure.hpp | 19 + .../ArduinoJson/Serialization/serialize.hpp | 51 + .../StringStorage/StringCopier.hpp | 72 + .../ArduinoJson/StringStorage/StringMover.hpp | 48 + .../StringStorage/StringStorage.hpp | 24 + .../Strings/Adapters/FlashString.hpp | 89 + .../Strings/Adapters/JsonString.hpp | 36 + .../Strings/Adapters/RamString.hpp | 143 + .../Strings/Adapters/StringObject.hpp | 51 + .../src/ArduinoJson/Strings/IsString.hpp | 20 + .../src/ArduinoJson/Strings/JsonString.hpp | 84 + .../src/ArduinoJson/Strings/StoragePolicy.hpp | 18 + .../src/ArduinoJson/Strings/StringAdapter.hpp | 31 + .../ArduinoJson/Strings/StringAdapters.hpp | 77 + .../src/ArduinoJson/Strings/StringTraits.hpp | 79 + .../src/ArduinoJson/Variant/Converter.hpp | 26 + .../src/ArduinoJson/Variant/ConverterImpl.hpp | 324 + .../src/ArduinoJson/Variant/JsonVariant.hpp | 81 + .../ArduinoJson/Variant/JsonVariantConst.hpp | 144 + .../src/ArduinoJson/Variant/SlotFunctions.hpp | 45 + .../ArduinoJson/Variant/VariantAttorney.hpp | 48 + .../ArduinoJson/Variant/VariantCompare.hpp | 207 + .../ArduinoJson/Variant/VariantContent.hpp | 58 + .../src/ArduinoJson/Variant/VariantData.hpp | 322 + .../ArduinoJson/Variant/VariantFunctions.hpp | 113 + .../src/ArduinoJson/Variant/VariantImpl.hpp | 151 + .../ArduinoJson/Variant/VariantOperators.hpp | 195 + .../ArduinoJson/Variant/VariantRefBase.hpp | 298 + .../src/ArduinoJson/Variant/VariantSlot.hpp | 112 + .../src/ArduinoJson/Variant/VariantTag.hpp | 16 + .../src/ArduinoJson/Variant/VariantTo.hpp | 34 + .../src/ArduinoJson/Variant/Visitor.hpp | 54 + .../src/ArduinoJson/compatibility.hpp | 25 + .../ArduinoJson/src/ArduinoJson/version.hpp | 10 + libraries/ArduinoJson/src/CMakeLists.txt | 91 + 421 files changed, 51080 insertions(+), 6 deletions(-) create mode 100644 libraries/ArduinoJson/ArduinoJson.h create mode 100644 libraries/ArduinoJson/CHANGELOG.md create mode 100644 libraries/ArduinoJson/CMakeLists.txt create mode 100644 libraries/ArduinoJson/CONTRIBUTING.md create mode 100644 libraries/ArduinoJson/LICENSE.txt create mode 100644 libraries/ArduinoJson/README.md create mode 100644 libraries/ArduinoJson/SUPPORT.md create mode 100644 libraries/ArduinoJson/appveyor.yml create mode 100644 libraries/ArduinoJson/component.mk create mode 100644 libraries/ArduinoJson/examples/JsonConfigFile/JsonConfigFile.ino create mode 100644 libraries/ArduinoJson/examples/JsonFilterExample/JsonFilterExample.ino create mode 100644 libraries/ArduinoJson/examples/JsonGeneratorExample/JsonGeneratorExample.ino create mode 100644 libraries/ArduinoJson/examples/JsonHttpClient/JsonHttpClient.ino create mode 100644 libraries/ArduinoJson/examples/JsonParserExample/JsonParserExample.ino create mode 100644 libraries/ArduinoJson/examples/JsonServer/JsonServer.ino create mode 100644 libraries/ArduinoJson/examples/JsonUdpBeacon/JsonUdpBeacon.ino create mode 100644 libraries/ArduinoJson/examples/MsgPackParser/MsgPackParser.ino create mode 100644 libraries/ArduinoJson/examples/ProgmemExample/ProgmemExample.ino create mode 100644 libraries/ArduinoJson/examples/StringExample/StringExample.ino create mode 100644 libraries/ArduinoJson/extras/ArduinoJsonConfig.cmake.in create mode 100644 libraries/ArduinoJson/extras/CompileOptions.cmake create mode 100644 libraries/ArduinoJson/extras/ci/espidf/CMakeLists.txt create mode 100644 libraries/ArduinoJson/extras/ci/espidf/main/CMakeLists.txt create mode 100644 libraries/ArduinoJson/extras/ci/espidf/main/component.mk create mode 100644 libraries/ArduinoJson/extras/ci/espidf/main/main.cpp create mode 100644 libraries/ArduinoJson/extras/ci/particle.sh create mode 100644 libraries/ArduinoJson/extras/conf_test/avr.cpp create mode 100644 libraries/ArduinoJson/extras/conf_test/esp8266.cpp create mode 100644 libraries/ArduinoJson/extras/conf_test/x64.cpp create mode 100644 libraries/ArduinoJson/extras/conf_test/x86.cpp create mode 100644 libraries/ArduinoJson/extras/fuzzing/CMakeLists.txt create mode 100644 libraries/ArduinoJson/extras/fuzzing/Makefile create mode 100644 libraries/ArduinoJson/extras/fuzzing/json_fuzzer.cpp create mode 100644 libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/Comments.json create mode 100644 libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/EmptyArray.json create mode 100644 libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/EmptyObject.json create mode 100644 libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/ExcessiveNesting.json create mode 100644 libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/IntegerOverflow.json create mode 100644 libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/Numbers.json create mode 100644 libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/OpenWeatherMap.json create mode 100644 libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/Strings.json create mode 100644 libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/WeatherUnderground.json create mode 100644 libraries/ArduinoJson/extras/fuzzing/msgpack_fuzzer.cpp create mode 100644 libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/array16 create mode 100644 libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/array32 create mode 100644 libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/false create mode 100644 libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/fixarray create mode 100644 libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/fixint_negative create mode 100644 libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/fixint_positive create mode 100644 libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/fixmap create mode 100644 libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/fixstr create mode 100644 libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/float32 create mode 100644 libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/float64 create mode 100644 libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/int16 create mode 100644 libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/int32 create mode 100644 libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/int64 create mode 100644 libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/int8 create mode 100644 libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/map16 create mode 100644 libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/map32 create mode 100644 libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/nil create mode 100644 libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/str16 create mode 100644 libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/str32 create mode 100644 libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/str8 create mode 100644 libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/true create mode 100644 libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/uint16 create mode 100644 libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/uint32 create mode 100644 libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/uint64 create mode 100644 libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/uint8 create mode 100644 libraries/ArduinoJson/extras/fuzzing/reproducer.cpp create mode 100644 libraries/ArduinoJson/extras/particle/project.properties create mode 100644 libraries/ArduinoJson/extras/particle/src/smocktest.ino create mode 100644 libraries/ArduinoJson/extras/scripts/build-arduino-package.sh create mode 100644 libraries/ArduinoJson/extras/scripts/build-single-header.sh create mode 100644 libraries/ArduinoJson/extras/scripts/get-release-body.sh create mode 100644 libraries/ArduinoJson/extras/scripts/get-release-page.sh create mode 100644 libraries/ArduinoJson/extras/scripts/publish-particle-library.sh create mode 100644 libraries/ArduinoJson/extras/scripts/publish.sh create mode 100644 libraries/ArduinoJson/extras/scripts/wandbox/JsonGeneratorExample.cpp create mode 100644 libraries/ArduinoJson/extras/scripts/wandbox/JsonParserExample.cpp create mode 100644 libraries/ArduinoJson/extras/scripts/wandbox/MsgPackParserExample.cpp create mode 100644 libraries/ArduinoJson/extras/scripts/wandbox/publish.sh create mode 100644 libraries/ArduinoJson/extras/tests/CMakeLists.txt create mode 100644 libraries/ArduinoJson/extras/tests/Cpp17/CMakeLists.txt create mode 100644 libraries/ArduinoJson/extras/tests/Cpp17/string_view.cpp create mode 100644 libraries/ArduinoJson/extras/tests/Cpp20/CMakeLists.txt create mode 100644 libraries/ArduinoJson/extras/tests/Cpp20/smoke_test.cpp create mode 100644 libraries/ArduinoJson/extras/tests/FailingBuilds/CMakeLists.txt create mode 100644 libraries/ArduinoJson/extras/tests/FailingBuilds/Issue1189.cpp create mode 100644 libraries/ArduinoJson/extras/tests/FailingBuilds/Issue978.cpp create mode 100644 libraries/ArduinoJson/extras/tests/FailingBuilds/assign_char.cpp create mode 100644 libraries/ArduinoJson/extras/tests/FailingBuilds/delete_jsondocument.cpp create mode 100644 libraries/ArduinoJson/extras/tests/FailingBuilds/read_long_long.cpp create mode 100644 libraries/ArduinoJson/extras/tests/FailingBuilds/variant_as_char.cpp create mode 100644 libraries/ArduinoJson/extras/tests/FailingBuilds/write_long_long.cpp create mode 100644 libraries/ArduinoJson/extras/tests/Helpers/Arduino.h create mode 100644 libraries/ArduinoJson/extras/tests/Helpers/CustomReader.hpp create mode 100644 libraries/ArduinoJson/extras/tests/Helpers/api/Print.h create mode 100644 libraries/ArduinoJson/extras/tests/Helpers/api/Stream.h create mode 100644 libraries/ArduinoJson/extras/tests/Helpers/api/String.h create mode 100644 libraries/ArduinoJson/extras/tests/Helpers/avr/pgmspace.h create mode 100644 libraries/ArduinoJson/extras/tests/IntegrationTests/CMakeLists.txt create mode 100644 libraries/ArduinoJson/extras/tests/IntegrationTests/gbathree.cpp create mode 100644 libraries/ArduinoJson/extras/tests/IntegrationTests/issue772.cpp create mode 100644 libraries/ArduinoJson/extras/tests/IntegrationTests/openweathermap.cpp create mode 100644 libraries/ArduinoJson/extras/tests/IntegrationTests/round_trip.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonArray/CMakeLists.txt create mode 100644 libraries/ArduinoJson/extras/tests/JsonArray/add.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonArray/clear.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonArray/compare.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonArray/copyArray.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonArray/createNested.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonArray/equals.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonArray/isNull.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonArray/iterator.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonArray/memoryUsage.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonArray/nesting.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonArray/remove.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonArray/size.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonArray/std_string.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonArray/subscript.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonArray/unbound.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDeserializer/CMakeLists.txt create mode 100644 libraries/ArduinoJson/extras/tests/JsonDeserializer/DeserializationError.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDeserializer/array.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDeserializer/array_static.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDeserializer/filter.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDeserializer/incomplete_input.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDeserializer/input_types.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDeserializer/invalid_input.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDeserializer/misc.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDeserializer/nestingLimit.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDeserializer/number.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDeserializer/object.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDeserializer/object_static.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDeserializer/string.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDocument/BasicJsonDocument.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDocument/CMakeLists.txt create mode 100644 libraries/ArduinoJson/extras/tests/JsonDocument/DynamicJsonDocument.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDocument/ElementProxy.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDocument/MemberProxy.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDocument/StaticJsonDocument.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDocument/add.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDocument/cast.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDocument/compare.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDocument/containsKey.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDocument/createNested.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDocument/isNull.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDocument/issue1120.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDocument/nesting.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDocument/overflowed.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDocument/remove.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDocument/shrinkToFit.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDocument/size.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDocument/subscript.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonDocument/swap.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonObject/CMakeLists.txt create mode 100644 libraries/ArduinoJson/extras/tests/JsonObject/clear.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonObject/compare.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonObject/containsKey.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonObject/copy.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonObject/createNestedArray.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonObject/createNestedObject.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonObject/equals.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonObject/invalid.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonObject/isNull.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonObject/iterator.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonObject/memoryUsage.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonObject/nesting.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonObject/remove.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonObject/size.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonObject/std_string.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonObject/subscript.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonSerializer/CMakeLists.txt create mode 100644 libraries/ArduinoJson/extras/tests/JsonSerializer/CustomWriter.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonSerializer/JsonArray.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonSerializer/JsonArrayPretty.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonSerializer/JsonObject.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonSerializer/JsonObjectPretty.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonSerializer/JsonVariant.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonSerializer/misc.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonSerializer/std_stream.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonSerializer/std_string.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonVariant/CMakeLists.txt create mode 100644 libraries/ArduinoJson/extras/tests/JsonVariant/add.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonVariant/as.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonVariant/clear.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonVariant/compare.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonVariant/containsKey.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonVariant/converters.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonVariant/copy.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonVariant/createNested.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonVariant/is.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonVariant/isnull.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonVariant/memoryUsage.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonVariant/misc.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonVariant/nesting.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonVariant/nullptr.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonVariant/or.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonVariant/overflow.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonVariant/remove.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonVariant/set.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonVariant/shallowCopy.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonVariant/size.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonVariant/stl_containers.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonVariant/subscript.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonVariant/types.cpp create mode 100644 libraries/ArduinoJson/extras/tests/JsonVariant/unbound.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MemoryPool/CMakeLists.txt create mode 100644 libraries/ArduinoJson/extras/tests/MemoryPool/StringCopier.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MemoryPool/allocVariant.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MemoryPool/clear.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MemoryPool/saveString.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MemoryPool/size.cpp create mode 100644 libraries/ArduinoJson/extras/tests/Misc/CMakeLists.txt create mode 100644 libraries/ArduinoJson/extras/tests/Misc/FloatParts.cpp create mode 100644 libraries/ArduinoJson/extras/tests/Misc/JsonString.cpp create mode 100644 libraries/ArduinoJson/extras/tests/Misc/NoArduinoHeader.cpp create mode 100644 libraries/ArduinoJson/extras/tests/Misc/Readers.cpp create mode 100644 libraries/ArduinoJson/extras/tests/Misc/StringAdapters.cpp create mode 100644 libraries/ArduinoJson/extras/tests/Misc/StringWriter.cpp create mode 100644 libraries/ArduinoJson/extras/tests/Misc/TypeTraits.cpp create mode 100644 libraries/ArduinoJson/extras/tests/Misc/Utf16.cpp create mode 100644 libraries/ArduinoJson/extras/tests/Misc/Utf8.cpp create mode 100644 libraries/ArduinoJson/extras/tests/Misc/arithmeticCompare.cpp create mode 100644 libraries/ArduinoJson/extras/tests/Misc/conflicts.cpp create mode 100644 libraries/ArduinoJson/extras/tests/Misc/custom_string.hpp create mode 100644 libraries/ArduinoJson/extras/tests/Misc/printable.cpp create mode 100644 libraries/ArduinoJson/extras/tests/Misc/unsigned_char.cpp create mode 100644 libraries/ArduinoJson/extras/tests/Misc/version.cpp create mode 100644 libraries/ArduinoJson/extras/tests/Misc/weird_strcmp.hpp create mode 100644 libraries/ArduinoJson/extras/tests/MixedConfiguration/CMakeLists.txt create mode 100644 libraries/ArduinoJson/extras/tests/MixedConfiguration/decode_unicode_0.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MixedConfiguration/decode_unicode_1.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_alignment_0.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_alignment_1.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_comments_0.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_comments_1.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_infinity_0.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_infinity_1.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_nan_0.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_nan_1.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_progmem_1.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_string_deduplication_0.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_string_deduplication_1.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MixedConfiguration/issue1707.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MixedConfiguration/use_double_0.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MixedConfiguration/use_double_1.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MixedConfiguration/use_long_long_0.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MixedConfiguration/use_long_long_1.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MsgPackDeserializer/CMakeLists.txt create mode 100644 libraries/ArduinoJson/extras/tests/MsgPackDeserializer/deserializeArray.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MsgPackDeserializer/deserializeObject.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MsgPackDeserializer/deserializeStaticVariant.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MsgPackDeserializer/deserializeVariant.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MsgPackDeserializer/doubleToFloat.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MsgPackDeserializer/filter.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MsgPackDeserializer/incompleteInput.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MsgPackDeserializer/input_types.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MsgPackDeserializer/misc.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MsgPackDeserializer/nestingLimit.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MsgPackDeserializer/notSupported.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MsgPackSerializer/CMakeLists.txt create mode 100644 libraries/ArduinoJson/extras/tests/MsgPackSerializer/destination_types.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MsgPackSerializer/measure.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MsgPackSerializer/misc.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MsgPackSerializer/serializeArray.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MsgPackSerializer/serializeObject.cpp create mode 100644 libraries/ArduinoJson/extras/tests/MsgPackSerializer/serializeVariant.cpp create mode 100644 libraries/ArduinoJson/extras/tests/Numbers/CMakeLists.txt create mode 100644 libraries/ArduinoJson/extras/tests/Numbers/convertNumber.cpp create mode 100644 libraries/ArduinoJson/extras/tests/Numbers/parseDouble.cpp create mode 100644 libraries/ArduinoJson/extras/tests/Numbers/parseFloat.cpp create mode 100644 libraries/ArduinoJson/extras/tests/Numbers/parseInteger.cpp create mode 100644 libraries/ArduinoJson/extras/tests/Numbers/parseNumber.cpp create mode 100644 libraries/ArduinoJson/extras/tests/TextFormatter/CMakeLists.txt create mode 100644 libraries/ArduinoJson/extras/tests/TextFormatter/writeFloat.cpp create mode 100644 libraries/ArduinoJson/extras/tests/TextFormatter/writeInteger.cpp create mode 100644 libraries/ArduinoJson/extras/tests/TextFormatter/writeString.cpp create mode 100644 libraries/ArduinoJson/extras/tests/catch/CMakeLists.txt create mode 100644 libraries/ArduinoJson/extras/tests/catch/catch.cpp create mode 100644 libraries/ArduinoJson/extras/tests/catch/catch.hpp create mode 100644 libraries/ArduinoJson/idf_component.yml create mode 100644 libraries/ArduinoJson/keywords.txt create mode 100644 libraries/ArduinoJson/library.json create mode 100644 libraries/ArduinoJson/library.properties create mode 100644 libraries/ArduinoJson/src/ArduinoJson.h create mode 100644 libraries/ArduinoJson/src/ArduinoJson.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Array/ElementProxy.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Array/JsonArray.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Array/JsonArrayConst.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Array/JsonArrayImpl.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Array/JsonArrayIterator.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Array/Utilities.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Collection/CollectionData.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Collection/CollectionImpl.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Configuration.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Deserialization/DeserializationError.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Deserialization/DeserializationOptions.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Deserialization/Filter.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Deserialization/NestingLimit.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Deserialization/Reader.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Deserialization/Readers/ArduinoStreamReader.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Deserialization/Readers/ArduinoStringReader.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Deserialization/Readers/FlashReader.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Deserialization/Readers/IteratorReader.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Deserialization/Readers/RamReader.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Deserialization/Readers/StdStreamReader.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Deserialization/Readers/VariantReader.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Deserialization/deserialize.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Document/BasicJsonDocument.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Document/DynamicJsonDocument.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Document/JsonDocument.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Document/StaticJsonDocument.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Json/EscapeSequence.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Json/JsonDeserializer.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Json/JsonSerializer.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Json/Latch.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Json/PrettyJsonSerializer.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Json/TextFormatter.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Json/Utf16.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Json/Utf8.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Memory/Alignment.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Memory/MemoryPool.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Misc/SerializedValue.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/MsgPack/MsgPackDeserializer.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/MsgPack/MsgPackSerializer.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/MsgPack/endianess.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/MsgPack/ieee754.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Namespace.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Numbers/FloatParts.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Numbers/FloatTraits.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Numbers/JsonFloat.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Numbers/JsonInteger.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Numbers/arithmeticCompare.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Numbers/convertNumber.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Numbers/parseNumber.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Object/JsonObject.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Object/JsonObjectConst.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Object/JsonObjectImpl.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Object/JsonObjectIterator.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Object/JsonPair.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Object/MemberProxy.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/alias_cast.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/assert.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/attributes.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/ctype.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/integer.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/limits.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/math.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/mpl/max.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/pgmspace.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/pgmspace_generic.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/preprocessor.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/type_traits.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/type_traits/conditional.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/type_traits/declval.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/type_traits/enable_if.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/type_traits/integral_constant.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/type_traits/is_array.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/type_traits/is_base_of.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/type_traits/is_class.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/type_traits/is_const.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/type_traits/is_convertible.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/type_traits/is_enum.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/type_traits/is_floating_point.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/type_traits/is_integral.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/type_traits/is_pointer.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/type_traits/is_same.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/type_traits/is_signed.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/type_traits/is_unsigned.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/type_traits/make_unsigned.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/type_traits/make_void.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/type_traits/remove_const.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/type_traits/remove_cv.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/type_traits/remove_reference.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/type_traits/type_identity.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Polyfills/utility.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Serialization/CountingDecorator.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Serialization/Writer.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Serialization/Writers/ArduinoStringWriter.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Serialization/Writers/DummyWriter.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Serialization/Writers/PrintWriter.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Serialization/Writers/StaticStringWriter.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Serialization/Writers/StdStreamWriter.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Serialization/Writers/StdStringWriter.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Serialization/measure.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Serialization/serialize.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/StringStorage/StringCopier.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/StringStorage/StringMover.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/StringStorage/StringStorage.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Strings/Adapters/FlashString.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Strings/Adapters/JsonString.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Strings/Adapters/RamString.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Strings/Adapters/StringObject.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Strings/IsString.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Strings/JsonString.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Strings/StoragePolicy.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Strings/StringAdapter.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Strings/StringAdapters.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Strings/StringTraits.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Variant/Converter.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Variant/ConverterImpl.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Variant/JsonVariant.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Variant/JsonVariantConst.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Variant/SlotFunctions.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Variant/VariantAttorney.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Variant/VariantCompare.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Variant/VariantContent.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Variant/VariantData.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Variant/VariantFunctions.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Variant/VariantImpl.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Variant/VariantOperators.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Variant/VariantRefBase.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Variant/VariantSlot.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Variant/VariantTag.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Variant/VariantTo.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/Variant/Visitor.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/compatibility.hpp create mode 100644 libraries/ArduinoJson/src/ArduinoJson/version.hpp create mode 100644 libraries/ArduinoJson/src/CMakeLists.txt diff --git a/PylontechMonitoring.ino b/PylontechMonitoring.ino index 8494895..bb77b50 100644 --- a/PylontechMonitoring.ino +++ b/PylontechMonitoring.ino @@ -428,22 +428,22 @@ struct batteryStack } // power in Wh in charge - long powerIN() const + float powerIN() const { if (currentDC > 0) { - return (long)(((double)currentDC/1000.0)*((double)avgVoltage/1000.0)); + return (float)(((double)currentDC/1000.0)*((double)avgVoltage/1000.0)); } else { - return (long)(0); + return (float)(0); } } // power in Wh in discharge - long powerOUT() const + float powerOUT() const { if (currentDC < 0) { - return (long)(((double)currentDC/1000.0)*((double)avgVoltage/1000.0)*-1); + return (float)(((double)currentDC/1000.0)*((double)avgVoltage/1000.0)*-1); } else { - return (long)(0); + return (float)(0); } } diff --git a/libraries/ArduinoJson/ArduinoJson.h b/libraries/ArduinoJson/ArduinoJson.h new file mode 100644 index 0000000..15c218f --- /dev/null +++ b/libraries/ArduinoJson/ArduinoJson.h @@ -0,0 +1,5 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include "src/ArduinoJson.h" diff --git a/libraries/ArduinoJson/CHANGELOG.md b/libraries/ArduinoJson/CHANGELOG.md new file mode 100644 index 0000000..a477dd8 --- /dev/null +++ b/libraries/ArduinoJson/CHANGELOG.md @@ -0,0 +1,845 @@ +ArduinoJson: change log +======================= + +v6.21.2 (2023-04-12) +------- + +* Fix compatibility with the Zephyr Project (issue #1905) +* Allow using PROGMEM outside of Arduino (issue #1903) +* Set default for `ARDUINOJSON_ENABLE_PROGMEM` to `1` on AVR + +v6.21.1 (2023-03-27) +------- + +* Double speed of `DynamicJsonDocument::garbageCollect()` +* Fix compatibility with GCC 5.2 (issue #1897) + +v6.21.0 (2023-03-14) +------- + +* Drop support for C++98/C++03. Minimum required is C++11. +* Remove `ARDUINOJSON_NAMESPACE`; use `ArduinoJson` instead. +* Make string support generic (issue #1807) + +v6.20.1 (2023-02-08) +------- + +* Remove explicit exclusion of `as()` and `as()` (issue #1860) + If you try to call them, you'll now get the same error message as any unsupported type. + You could also add a custom converter for `char*` and `char`. + +v6.20.0 (2022-12-26) +------- + +* Add `JsonVariant::shallowCopy()` (issue #1343) +* Fix `9.22337e+18 is outside the range of representable values of type 'long'` +* Fix comparison operators for `JsonArray`, `JsonArrayConst`, `JsonObject`, and `JsonObjectConst` +* Fix lax parsing of `true`, `false`, and `null` (issue #1781) +* Remove undocumented `accept()` functions +* Rename `addElement()` to `add()` +* Remove `getElement()`, `getOrAddElement()`, `getMember()`, and `getOrAddMember()` +* Remove undocumented `JsonDocument::data()` and `JsonDocument::memoryPool()` +* Remove undocumented `JsonArrayIterator::internal()` and `JsonObjectIterator::internal()` +* Rename things in `ARDUINOJSON_NAMESPACE` to match the public names +* Add documentation to most public symbols +* Remove support for naked `char` (was deprecated since 6.18.0) + +> ### BREAKING CHANGES +> +> This release hides `JsonVariant`'s functions that were only intended for internal use. +> If you were using them in your programs, you must replace with `operator[]` and `to()`, like so: +> +> ```c++ +> // before +> JsonVariant a = variant.getElement(idx); +> JsonVariant b = variant.getOrAddElement(idx); +> JsonVariant c = variant.getMember(key); +> JsonVariant d = variant.getOrAddMember(key); +> +> // after +> JsonVariant a = variant[idx]; +> JsonVariant b = idx < variant.size() ? variant[idx] : variant[idx].to(); +> JsonVariant c = variant[key]; +> JsonVariant d = variant.containsKey(key) ? variant[key] : variant[key].to(); +> ``` + +v6.19.4 (2022-04-05) +------- + +* Add `ElementProxy::memoryUsage()` +* Add `MemberProxy::memoryUsage()` (issue #1730) +* Add implicit conversion from `JsonDocument` to `JsonVariant` +* Fix comparisons operators with `const JsonDocument&` + +v6.19.3 (2022-03-08) +------- + +* Fix `call of overloaded 'String(const char*, int)' is ambiguous` +* Fix `JsonString` operator `==` and `!=` for non-zero-terminated string +* Fix `-Wsign-conversion` on GCC 8 (issue #1715) +* MessagePack: serialize round floats as integers (issue #1718) + +v6.19.2 (2022-02-14) +------- + +* Fix `cannot convert 'pgm_p' to 'const void*'` (issue #1707) + +v6.19.1 (2022-01-14) +------- + +* Fix crash when adding an object member in a too small `JsonDocument` +* Fix filter not working in zero-copy mode (issue #1697) + +v6.19.0 (2022-01-08) +------- + +* Remove `ARDUINOJSON_EMBEDDED_MODE` and assume we run on an embedded platform. + Dependent settings (like `ARDUINOJSON_DEFAULT_NESTING_LIMIT`) must be set individually. +* Change the default of `ARDUINOJSON_USE_DOUBLE` to `1` +* Change the default of `ARDUINOJSON_USE_LONG_LONG` to `1` on 32-bit platforms +* Add `as()` and `is()` +* Add safe bool idiom in `JsonString` +* Add support for NUL in string values (issue #1646) +* Add support for arbitrary array rank in `copyArray()` +* Add support for `char[][]` in `copyArray()` +* Remove `DeserializationError == bool` and `DeserializationError != bool` +* Renamed undocumented function `isUndefined()` to `isUnbound()` +* Fix `JsonVariant::memoryUsage()` for raw strings +* Fix `call of overloaded 'swap(BasicJsonDocument&, BasicJsonDocument&)' is ambiguous` (issue #1678) +* Fix inconsistent pool capacity between `BasicJsonDocument`'s copy and move constructors +* Fix inconsistent pool capacity between `BasicJsonDocument`'s copy and move assignments +* Fix return type of `StaticJsonDocument::operator=` +* Avoid pool reallocation in `BasicJsonDocument`'s copy assignment if capacity is the same +* Avoid including `Arduino.h` when all its features are disabled (issue #1692, PR #1693 by @paulocsanz) +* Assume `PROGMEM` is available as soon as `ARDUINO` is defined (consequence of #1693) + +v6.18.5 (2021-09-28) +------- + +* Set `ARDUINOJSON_EMBEDDED_MODE` to `1` on Nios II (issue #1657) + +v6.18.4 (2021-09-06) +------- + +* Fixed error `'dummy' may be used uninitialized` on GCC 11 +* Fixed error `expected unqualified-id before 'const'` on GCC 11 (issue #1622) +* Filter: exact match takes precedence over wildcard (issue #1628) +* Fixed deserialization of `\u0000` (issue #1646) + +v6.18.3 (2021-07-27) +------- + +* Changed return type of `convertToJson()` and `Converter::toJson()` to `void` +* Added `as()` and `is()` + +v6.18.2 (2021-07-19) +------- + +* Removed a symlink because the Arduino Library Specification forbids it + +v6.18.1 (2021-07-03) +------- + +* Fixed support for `volatile float` and `volatile double` (issue #1557) +* Fixed error `[Pe070]: incomplete type is not allowed` on IAR (issue #1560) +* Fixed `serializeJson(doc, String)` when allocation fails (issue #1572) +* Fixed clang-tidy warnings (issue #1574, PR #1577 by @armandas) +* Added fake class `InvalidConversion` to easily identify invalid conversions (issue #1585) +* Added support for `std::string_view` (issue #1578, PR #1554 by @0xFEEDC0DE64) +* Fixed warning `definition of implicit copy constructor for 'MsgPackDeserializer' is deprecated because it has a user-declared copy assignment operator` +* Added `JsonArray::clear()` (issue #1597) +* Fixed `JsonVariant::as()` (issue #1601) +* Added support for ESP-IDF component build (PR #1562 by @qt1, PR #1599 by @andreaskuster) + +v6.18.0 (2021-05-05) +------- + +* Added support for custom converters (issue #687) +* Added support for `Printable` (issue #1444) +* Removed support for `char` values, see below (issue #1498) +* `deserializeJson()` leaves `\uXXXX` unchanged instead of returning `NotSupported` +* `deserializeMsgPack()` inserts `null` instead of returning `NotSupported` +* Removed `DeserializationError::NotSupported` +* Added `JsonVariant::is()` (issue #1412) +* Added `JsonVariant::is()` (issue #1412) +* Changed `JsonVariantConst::is()` to return `false` (issue #1412) +* Simplified `JsonVariant::as()` to always return `T` (see below) +* Updated folders list in `.mbedignore` (PR #1515 by @AGlass0fMilk) +* Fixed member-call-on-null-pointer in `getMember()` when array is empty +* `serializeMsgPack(doc, buffer, size)` doesn't add null-terminator anymore (issue #1545) +* `serializeJson(doc, buffer, size)` adds null-terminator only if there is enough room +* PlatformIO: set `build.libArchive` to `false` (PR #1550 by @askreet) + +> ### BREAKING CHANGES +> +> #### Support for `char` removed +> +> We cannot cast a `JsonVariant` to a `char` anymore, so the following will break: +> ```c++ +> char age = doc["age"]; // error: no matching function for call to 'variantAs(VariantData*&)' +> ``` +> Instead, you must use another integral type, such as `int8_t`: +> ```c++ +> int8_t age = doc["age"]; // OK +> ``` +> +> Similarly, we cannot assign from a `char` anymore, so the following will break: +> ```c++ +> char age; +> doc["age"] = age; // error: no matching function for call to 'VariantRef::set(const char&)' +> ``` +> Instead, you must use another integral type, such as `int8_t`: +> ```c++ +> int8_t age; +> doc["age"] = age; // OK +> ``` +> A deprecation warning with the message "Support for `char` is deprecated, use `int8_t` or `uint8_t` instead" was added to allow a smooth transition. +> +> #### `as()` always returns `T` +> +> Previously, `JsonVariant::as()` could return a type different from `T`. +> The most common example is `as()` that returned a `const char*`. +> While this feature simplified a few use cases, it was confusing and complicated the +> implementation of custom converters. +> +> Starting from this version, `as` doesn't try to auto-correct the return type and always return `T`, +> which means that you cannot write this anymore: +> +> ```c++ +> Serial.println(doc["sensor"].as()); // error: invalid conversion from 'const char*' to 'char*' [-fpermissive] +> ``` +> +> Instead, you must write: +> +> ```c++ +> Serial.println(doc["sensor"].as()); // OK +> ``` +> +> A deprecation warning with the message "Replace `as()` with `as()`" was added to allow a smooth transition. +> +> #### `DeserializationError::NotSupported` removed +> +> On a different topic, `DeserializationError::NotSupported` has been removed. +> Instead of returning this error: +> +> * `deserializeJson()` leaves `\uXXXX` unchanged (only when `ARDUINOJSON_DECODE_UNICODE` is `0`) +> * `deserializeMsgPack()` replaces unsupported values with `null`s +> +> #### Const-aware `is()` +> +> Lastly, a very minor change concerns `JsonVariantConst::is()`. +> It used to return `true` for `JsonArray` and `JsonOject`, but now it returns `false`. +> Instead, you must use `JsonArrayConst` and `JsonObjectConst`. + +v6.17.3 (2021-02-15) +------- + +* Made `JsonDocument`'s destructor protected (issue #1480) +* Added missing calls to `client.stop()` in `JsonHttpClient.ino` (issue #1485) +* Fixed error `expected ')' before 'char'` when `isdigit()` is a macro (issue #1487) +* Fixed error `definition of implicit copy constructor is deprecated` on Clang 10 +* PlatformIO: set framework compatibility to `*` (PR #1490 by @maxgerhardt) + +v6.17.2 (2020-11-14) +------- + +* Fixed invalid conversion error in `operator|(JsonVariant, char*)` (issue #1432) +* Changed the default value of `ARDUINOJSON_ENABLE_PROGMEM` (issue #1433). + It now checks that the `pgm_read_XXX` macros are defined before enabling `PROGMEM`. + +v6.17.1 (2020-11-07) +------- + +* Fixed error `ambiguous overload for 'operator|'` (issue #1411) +* Fixed `operator|(MemberProxy, JsonObject)` (issue #1415) +* Allowed more than 32767 values in non-embedded mode (issue #1414) + +v6.17.0 (2020-10-19) +------- + +* Added a build failure when nullptr is defined as a macro (issue #1355) +* Added `JsonDocument::overflowed()` which tells if the memory pool was too small (issue #1358) +* Added `DeserializationError::EmptyInput` which tells if the input was empty +* Added `DeserializationError::f_str()` which returns a `const __FlashStringHelper*` (issue #846) +* Added `operator|(JsonVariantConst, JsonVariantConst)` +* Added filtering for MessagePack (issue #1298, PR #1394 by Luca Passarella) +* Moved float convertion tables to PROGMEM +* Fixed `JsonVariant::set((char*)0)` which returned false instead of true (issue #1368) +* Fixed error `No such file or directory #include ` (issue #1381) + +v6.16.1 (2020-08-04) +------- + +* Fixed `deserializeJson()` that stopped reading after `{}` (issue #1335) + +v6.16.0 (2020-08-01) +------- + +* Added comparisons (`>`, `>=`, `==`, `!=`, `<`, and `<=`) between `JsonVariant`s +* Added string deduplication (issue #1303) +* Added `JsonString::operator!=` +* Added wildcard key (`*`) for filters (issue #1309) +* Set `ARDUINOJSON_DECODE_UNICODE` to `1` by default +* Fixed `copyArray()` not working with `String`, `ElementProxy`, and `MemberProxy` +* Fixed error `getOrAddElement is not a member of ElementProxy` (issue #1311) +* Fixed excessive stack usage when compiled with `-Og` (issues #1210 and #1314) +* Fixed `Warning[Pa093]: implicit conversion from floating point to integer` on IAR compiler (PR #1328 by @stawiski) + +v6.15.2 (2020-05-15) +------- + +* CMake: don't build tests when imported in another project +* CMake: made project arch-independent +* Visual Studio: fixed error C2766 with flag `/Zc:__cplusplus` (issue #1250) +* Added support for `JsonDocument` to `copyArray()` (issue #1255) +* Added support for `enum`s in `as()` and `is()` (issue #1256) +* Added `JsonVariant` as an input type for `deserializeXxx()` + For example, you can do: `deserializeJson(doc2, doc1["payload"])` +* Break the build if using 64-bit integers with ARDUINOJSON_USE_LONG_LONG==0 + +v6.15.1 (2020-04-08) +------- + +* Fixed "maybe-uninitialized" warning (issue #1217) +* Fixed "statement is unreachable" warning on IAR (issue #1233) +* Fixed "pointless integer comparison" warning on IAR (issue #1233) +* Added CMake "install" target (issue #1209) +* Disabled alignment on AVR (issue #1231) + +v6.15.0 (2020-03-22) +------- + +* Added `DeserializationOption::Filter` (issue #959) +* Added example `JsonFilterExample.ino` +* Changed the array subscript operator to automatically add missing elements +* Fixed "deprecated-copy" warning on GCC 9 (fixes #1184) +* Fixed `MemberProxy::set(char[])` not duplicating the string (issue #1191) +* Fixed enums serialized as booleans (issue #1197) +* Fixed incorrect string comparison on some platforms (issue #1198) +* Added move-constructor and move-assignment to `BasicJsonDocument` +* Added `BasicJsonDocument::garbageCollect()` (issue #1195) +* Added `StaticJsonDocument::garbageCollect()` +* Changed copy-constructor of `BasicJsonDocument` to preserve the capacity of the source. +* Removed copy-constructor of `JsonDocument` (issue #1189) + +> ### BREAKING CHANGES +> +> #### Copy-constructor of `BasicJsonDocument` +> +> In previous versions, the copy constructor of `BasicJsonDocument` looked at the source's `memoryUsage()` to choose its capacity. +> Now, the copy constructor of `BasicJsonDocument` uses the same capacity as the source. +> +> Example: +> +> ```c++ +> DynamicJsonDocument doc1(64); +> doc1.set(String("example")); +> +> DynamicJsonDocument doc2 = doc1; +> Serial.print(doc2.capacity()); // 8 with ArduinoJson 6.14 +> // 64 with ArduinoJson 6.15 +> ``` +> +> I made this change to get consistent results between copy-constructor and move-constructor, and whether RVO applies or not. +> +> If you use the copy-constructor to optimize your documents, you can use `garbageCollect()` or `shrinkToFit()` instead. +> +> #### Copy-constructor of `JsonDocument` +> +> In previous versions, it was possible to create a function that take a `JsonDocument` by value. +> +> ```c++ +> void myFunction(JsonDocument doc) {} +> ``` +> +> This function gives the wrong clues because it doesn't receive a copy of the `JsonDocument`, only a sliced version. +> It worked because the copy constructor copied the internal pointers, but it was an accident. +> +> From now, if you need to pass a `JsonDocument` to a function, you must use a reference: +> +> ```c++ +> void myFunction(JsonDocument& doc) {} +> ``` + +v6.14.1 (2020-01-27) +------- + +* Fixed regression in UTF16 decoding (issue #1173) +* Fixed `containsKey()` on `JsonVariantConst` +* Added `getElement()` and `getMember()` to `JsonVariantConst` + +v6.14.0 (2020-01-16) +------- + +* Added `BasicJsonDocument::shrinkToFit()` +* Added support of `uint8_t` for `serializeJson()`, `serializeJsonPretty()`, and `serializeMsgPack()` (issue #1142) +* Added `ARDUINOJSON_ENABLE_COMMENTS` to enable support for comments (defaults to 0) +* Auto enable support for `std::string` and `std::stream` on modern compilers (issue #1156) + (No need to define `ARDUINOJSON_ENABLE_STD_STRING` and `ARDUINOJSON_ENABLE_STD_STREAM` anymore) +* Improved decoding of UTF-16 surrogate pairs (PR #1157 by @kaysievers) + (ArduinoJson now produces standard UTF-8 instead of CESU-8) +* Added `measureJson`, `measureJsonPretty`, and `measureMsgPack` to `keywords.txt` + (This file is used for syntax highlighting in the Arduino IDE) +* Fixed `variant.is()` +* Fixed value returned by `serializeJson()`, `serializeJsonPretty()`, and `serializeMsgPack()` when writing to a `String` +* Improved speed of `serializeJson()`, `serializeJsonPretty()`, and `serializeMsgPack()` when writing to a `String` + +> ### BREAKING CHANGES +> +> #### Comments +> +> Support for comments in input is now optional and disabled by default. +> +> If you need support for comments, you must defined `ARDUINOJSON_ENABLE_COMMENTS` to `1`; otherwise, you'll receive `InvalidInput` errors. +> +> ```c++ +> #define ARDUINOJSON_ENABLE_COMMENTS 1 +> #include +> ``` + +v6.13.0 (2019-11-01) +------- + +* Added support for custom writer/reader classes (issue #1088) +* Added conversion from `JsonArray` and `JsonObject` to `bool`, to be consistent with `JsonVariant` +* Fixed `deserializeJson()` when input contains duplicate keys (issue #1095) +* Improved `deserializeMsgPack()` speed by reading several bytes at once +* Added detection of Atmel AVR8/GNU C Compiler (issue #1112) +* Fixed deserializer that stopped reading at the first `0xFF` (PR #1118 by @mikee47) +* Fixed dangling reference in copies of `MemberProxy` and `ElementProxy` (issue #1120) + +v6.12.0 (2019-09-05) +------- + +* Use absolute instead of relative includes (issue #1072) +* Changed `JsonVariant::as()` to return `true` for any non-null value (issue #1005) +* Moved ancillary files to `extras/` (issue #1011) + +v6.11.5 (2019-08-23) +------- + +* Added fallback implementations of `strlen_P()`, `strncmp_P()`, `strcmp_P()`, and `memcpy_P()` (issue #1073) + +v6.11.4 (2019-08-12) +------- + +* Added `measureJson()` to the `ArduinoJson` namespace (PR #1069 by @nomis) +* Added support for `basic_string` (issue #1045) +* Fixed example `JsonConfigFile.ino` for ESP8266 +* Include `Arduino.h` if `ARDUINO` is defined (PR #1071 by @nomis) + +v6.11.3 (2019-07-22) +------- + +* Added operators `==` and `!=` for `JsonDocument`, `ElementProxy`, and `MemberProxy` +* Fixed comparison of `JsonVariant` when one contains a linked string and the other contains an owned string (issue #1051) + +v6.11.2 (2019-07-08) +------- + +* Fixed assignment of `JsonDocument` to `JsonVariant` (issue #1023) +* Fix invalid conversion error on Particle Argon (issue #1035) + +v6.11.1 (2019-06-21) +------- + +* Fixed `serialized()` not working with Flash strings (issue #1030) + +v6.11.0 (2019-05-26) +------- + +* Fixed `deserializeJson()` silently accepting a `Stream*` (issue #978) +* Fixed invalid result from `operator|` (issue #981) +* Made `deserializeJson()` more picky about trailing characters (issue #980) +* Added `ARDUINOJSON_ENABLE_NAN` (default=0) to enable NaN in JSON (issue #973) +* Added `ARDUINOJSON_ENABLE_INFINITY` (default=0) to enable Infinity in JSON +* Removed implicit conversion in comparison operators (issue #998) +* Added lexicographical comparison for `JsonVariant` +* Added support for `nullptr` (issue #998) + +> ### BREAKING CHANGES +> +> #### NaN and Infinity +> +> The JSON specification allows neither NaN not Infinity, but previous +> versions of ArduinoJson supported it. Now, ArduinoJson behaves like most +> other libraries: a NaN or and Infinity in the `JsonDocument`, becomes +> a `null` in the output JSON. Also, `deserializeJson()` returns +> `InvalidInput` if the JSON document contains NaN or Infinity. +> +> This version still supports NaN and Infinity in JSON documents, but +> it's disabled by default to be compatible with other JSON parsers. +> If you need the old behavior back, define `ARDUINOJSON_ENABLE_NAN` and +> `ARDUINOJSON_ENABLE_INFINITY` to `1`;: +> +> ```c++ +> #define ARDUINOJSON_ENABLE_NAN 1 +> #define ARDUINOJSON_ENABLE_INFINITY 1 +> #include +> ``` +> +> #### The "or" operator +> +> This version slightly changes the behavior of the | operator when the +> variant contains a float and the user requests an integer. +> +> Older versions returned the floating point value truncated. +> Now, it returns the default value. +> +> ```c++ +> // suppose variant contains 1.2 +> int value = variant | 3; +> +> // old behavior: +> value == 1 +> +> // new behavior +> value == 3 +> ``` +> +> If you need the old behavior, you must add `if (variant.is())`. + +v6.10.1 (2019-04-23) +------- + +* Fixed error "attributes are not allowed on a function-definition" +* Fixed `deserializeJson()` not being picky enough (issue #969) +* Fixed error "no matching function for call to write(uint8_t)" (issue #972) + +v6.10.0 (2019-03-22) +------- + +* Fixed an integer overflow in the JSON deserializer +* Added overflow handling in `JsonVariant::as()` and `JsonVariant::is()`. + - `as()` returns `0` if the integer `T` overflows + - `is()` returns `false` if the integer `T` overflows +* Added `BasicJsonDocument` to support custom allocator (issue #876) +* Added `JsonDocument::containsKey()` (issue #938) +* Added `JsonVariant::containsKey()` + +v6.9.1 (2019-03-01) +------ + +* Fixed warning "unused variable" with GCC 4.4 (issue #912) +* Fixed warning "cast increases required alignment" (issue #914) +* Fixed warning "conversion may alter value" (issue #914) +* Fixed naming conflict with "CAPACITY" (issue #839) +* Muted warning "will change in GCC 7.1" (issue #914) +* Added a clear error message for `StaticJsonBuffer` and `DynamicJsonBuffer` +* Marked ArduinoJson.h as a "system header" + +v6.9.0 (2019-02-26) +------ + +* Decode escaped Unicode characters like \u00DE (issue #304, PR #791) + Many thanks to Daniel Schulte (aka @trilader) who implemented this feature. +* Added option ARDUINOJSON_DECODE_UNICODE to enable it +* Converted `JsonArray::copyFrom()/copyTo()` to free functions `copyArray()` +* Renamed `JsonArray::copyFrom()` and `JsonObject::copyFrom()` to `set()` +* Renamed `JsonArray::get()` to `getElement()` +* Renamed `JsonArray::add()` (without arg) to `addElement()` +* Renamed `JsonObject::get()` to `getMember()` +* Renamed `JsonObject::getOrCreate()` to `getOrAddMember()` +* Fixed `JsonVariant::isNull()` not returning `true` after `set((char*)0)` +* Fixed segfault after `variant.set(serialized((char*)0))` +* Detect `IncompleteInput` in `false`, `true`, and `null` +* Added `JsonDocument::size()` +* Added `JsonDocument::remove()` +* Added `JsonVariant::clear()` +* Added `JsonVariant::remove()` + +v6.8.0-beta (2019-01-30) +----------- + +* Import functions in the ArduinoJson namespace to get clearer errors +* Improved syntax highlighting in Arduino IDE +* Removed default capacity of `DynamicJsonDocument` +* `JsonArray::copyFrom()` accepts `JsonArrayConst` +* `JsonVariant::set()` accepts `JsonArrayConst` and `JsonObjectConst` +* `JsonDocument` was missing in the ArduinoJson namespace +* Added `memoryUsage()` to `JsonArray`, `JsonObject`, and `JsonVariant` +* Added `nesting()` to `JsonArray`, `JsonDocument`, `JsonObject`, and `JsonVariant` +* Replaced `JsonDocument::nestingLimit` with an additional parameter + to `deserializeJson()` and `deserializeMsgPack()` +* Fixed uninitialized variant in `JsonDocument` +* Fixed `StaticJsonDocument` copy constructor and copy assignment +* The copy constructor of `DynamicJsonDocument` chooses the capacity according to the memory usage of the source, not from the capacity of the source. +* Added the ability to create/assign a `StaticJsonDocument`/`DynamicJsonDocument` from a `JsonArray`/`JsonObject`/`JsonVariant` +* Added `JsonDocument::isNull()` +* Added `JsonDocument::operator[]` +* Added `ARDUINOJSON_TAB` to configure the indentation character +* Reduced the size of the pretty JSON serializer +* Added `add()`, `createNestedArray()` and `createNestedObject()` to `JsonVariant` +* `JsonVariant` automatically promotes to `JsonObject` or `JsonArray` on write. + Calling `JsonVariant::to()` is not required anymore. +* `JsonDocument` now support the same operations as `JsonVariant`. + Calling `JsonDocument::as()` is not required anymore. +* Fixed example `JsonHttpClient.ino` +* User can now use a `JsonString` as a key or a value + +> ### BREAKING CHANGES +> +> #### `DynamicJsonDocument`'s constructor +> +> The parameter to the constructor of `DynamicJsonDocument` is now mandatory +> +> Old code: +> +> ```c++ +> DynamicJsonDocument doc; +> ``` +> +> New code: +> +> ```c++ +> DynamicJsonDocument doc(1024); +> ``` +> +> #### Nesting limit +> +> `JsonDocument::nestingLimit` was replaced with a new parameter to `deserializeJson()` and `deserializeMsgPack()`. +> +> Old code: +> +> ```c++ +> doc.nestingLimit = 15; +> deserializeJson(doc, input); +> ``` +> +> New code: +> +> ```c++ +> deserializeJson(doc, input, DeserializationOption::NestingLimit(15)); +> ``` + +v6.7.0-beta (2018-12-07) +----------- + +* Removed the automatic expansion of `DynamicJsonDocument`, it now has a fixed capacity. +* Restored the monotonic allocator because the code was getting too big +* Reduced the memory usage +* Reduced the code size +* Renamed `JsonKey` to `JsonString` +* Removed spurious files in the Particle library + +v6.6.0-beta (2018-11-13) +----------- + +* Removed `JsonArray::is(i)` and `JsonArray::set(i,v)` +* Removed `JsonObject::is(k)` and `JsonObject::set(k,v)` +* Replaced `T JsonArray::get(i)` with `JsonVariant JsonArray::get(i)` +* Replaced `T JsonObject::get(k)` with `JsonVariant JsonObject::get(k)` +* Added `JSON_STRING_SIZE()` +* ~~Replacing or removing a value now releases the memory~~ +* Added `DeserializationError::code()` to be used in switch statements (issue #846) + +v6.5.0-beta (2018-10-13) +----------- + +* Added implicit conversion from `JsonArray` and `JsonObject` to `JsonVariant` +* Allow mixed configuration in compilation units (issue #809) +* Fixed object keys not being duplicated +* `JsonPair::key()` now returns a `JsonKey` +* Increased the default capacity of `DynamicJsonDocument` +* Fixed `JsonVariant::is()` (closes #763) +* Added `JsonArrayConst`, `JsonObjectConst`, and `JsonVariantConst` +* Added copy-constructor and copy-assignment-operator for `JsonDocument` (issue #827) + +v6.4.0-beta (2018-09-11) +----------- + +* Copy `JsonArray` and `JsonObject`, instead of storing pointers (issue #780) +* Added `JsonVariant::to()` and `JsonVariant::to()` + +v6.3.0-beta (2018-08-31) +----------- + +* Implemented reference semantics for `JsonVariant` +* Replaced `JsonPair`'s `key` and `value` with `key()` and `value()` +* Fixed `serializeJson(obj[key], dst)` (issue #794) + +> ### BREAKING CHANGES +> +> #### JsonVariant +> +> `JsonVariant` now has a semantic similar to `JsonObject` and `JsonArray`. +> It's a reference to a value stored in the `JsonDocument`. +> As a consequence, a `JsonVariant` cannot be used as a standalone variable anymore. +> +> Old code: +> +> ```c++ +> JsonVariant myValue = 42; +> ``` +> +> New code: +> +> ```c++ +> DynamicJsonDocument doc; +> JsonVariant myValue = doc.to(); +> myValue.set(42); +> ``` +> +> #### JsonPair +> +> Old code: +> +> ```c++ +> for(JsonPair p : myObject) { +> Serial.println(p.key); +> Serial.println(p.value.as()); +> } +> ``` +> +> New code: +> +> ```c++ +> for(JsonPair p : myObject) { +> Serial.println(p.key()); +> Serial.println(p.value().as()); +> } +> ``` +> +> CAUTION: the key is now read only! + +v6.2.3-beta (2018-07-19) +----------- + +* Fixed exception when using Flash strings as object keys (issue #784) + +v6.2.2-beta (2018-07-18) +----------- + +* Fixed `invalid application of 'sizeof' to incomplete type '__FlashStringHelper'` (issue #783) +* Fixed `char[]` not duplicated when passed to `JsonVariant::operator[]` + +v6.2.1-beta (2018-07-17) +----------- + +* Fixed `JsonObject` not inserting keys of type `String` (issue #782) + +v6.2.0-beta (2018-07-12) +----------- + +* Disabled lazy number deserialization (issue #772) +* Fixed `JsonVariant::is()` that returned true for empty strings +* Improved float serialization when `-fsingle-precision-constant` is used +* Renamed function `RawJson()` to `serialized()` +* `serializeMsgPack()` now supports values marked with `serialized()` + +> ### BREAKING CHANGES +> +> #### Non quoted strings +> +> Non quoted strings are now forbidden in values, but they are still allowed in keys. +> For example, `{key:"value"}` is accepted, but `{key:value}` is not. +> +> #### Preformatted values +> +> Old code: +> +> ```c++ +> object["values"] = RawJson("[1,2,3,4]"); +> ``` +> +> New code: +> +> ```c++ +> object["values"] = serialized("[1,2,3,4]"); +> ``` + +v6.1.0-beta (2018-07-02) +----------- + +* Return `JsonArray` and `JsonObject` by value instead of reference (issue #309) +* Replaced `success()` with `isNull()` + +> ### BREAKING CHANGES +> +> Old code: +> +> ```c++ +> JsonObject& obj = doc.to(); +> JsonArray& arr = obj.createNestedArray("key"); +> if (!arr.success()) { +> Serial.println("Not enough memory"); +> return; +> } +> ``` +> +> New code: +> +> ```c++ +> JsonObject obj = doc.to(); +> JsonArray arr = obj.createNestedArray("key"); +> if (arr.isNull()) { +> Serial.println("Not enough memory"); +> return; +> } +> ``` + +v6.0.1-beta (2018-06-11) +----------- + +* Fixed conflicts with `isnan()` and `isinf()` macros (issue #752) + +v6.0.0-beta (2018-06-07) +----------- + +* Added `DynamicJsonDocument` and `StaticJsonDocument` +* Added `deserializeJson()` +* Added `serializeJson()` and `serializeJsonPretty()` +* Added `measureJson()` and `measureJsonPretty()` +* Added `serializeMsgPack()`, `deserializeMsgPack()` and `measureMsgPack()` (issue #358) +* Added example `MsgPackParser.ino` (issue #358) +* Added support for non zero-terminated strings (issue #704) +* Removed `JsonBuffer::parseArray()`, `parseObject()` and `parse()` +* Removed `JsonBuffer::createArray()` and `createObject()` +* Removed `printTo()` and `prettyPrintTo()` +* Removed `measureLength()` and `measurePrettyLength()` +* Removed all deprecated features + +> ### BREAKING CHANGES +> +> #### Deserialization +> +> Old code: +> +> ```c++ +> DynamicJsonBuffer jb; +> JsonObject& obj = jb.parseObject(json); +> if (obj.success()) { +> +> } +> ``` +> +> New code: +> +> ```c++ +> DynamicJsonDocument doc; +> DeserializationError error = deserializeJson(doc, json); +> if (error) { +> +> } +> JsonObject& obj = doc.as(); +> ``` +> +> #### Serialization +> +> Old code: +> +> ```c++ +> DynamicJsonBuffer jb; +> JsonObject& obj = jb.createObject(); +> obj["key"] = "value"; +> obj.printTo(Serial); +> ``` +> +> New code: +> +> ```c++ +> DynamicJsonDocument obj; +> JsonObject& obj = doc.to(); +> obj["key"] = "value"; +> serializeJson(doc, Serial); +> ``` diff --git a/libraries/ArduinoJson/CMakeLists.txt b/libraries/ArduinoJson/CMakeLists.txt new file mode 100644 index 0000000..ca0c647 --- /dev/null +++ b/libraries/ArduinoJson/CMakeLists.txt @@ -0,0 +1,25 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2023, Benoit BLANCHON +# MIT License + +cmake_minimum_required(VERSION 3.15) + +if(ESP_PLATFORM) + # Build ArduinoJson as an ESP-IDF component + idf_component_register(INCLUDE_DIRS src) + return() +endif() + +project(ArduinoJson VERSION 6.21.2) + +if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME) + include(CTest) +endif() + +add_subdirectory(src) + +if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME AND BUILD_TESTING) + include(extras/CompileOptions.cmake) + add_subdirectory(extras/tests) + add_subdirectory(extras/fuzzing) +endif() diff --git a/libraries/ArduinoJson/CONTRIBUTING.md b/libraries/ArduinoJson/CONTRIBUTING.md new file mode 100644 index 0000000..d32a04f --- /dev/null +++ b/libraries/ArduinoJson/CONTRIBUTING.md @@ -0,0 +1,10 @@ +# Contribution to ArduinoJson + +First, thank you for taking the time to contribute to this project. + +You can submit changes via GitHub Pull Requests. + +Please: + +1. Update the test suite for any change of behavior +2. Use clang-format in "file" mode to format the code diff --git a/libraries/ArduinoJson/LICENSE.txt b/libraries/ArduinoJson/LICENSE.txt new file mode 100644 index 0000000..15f1b9f --- /dev/null +++ b/libraries/ArduinoJson/LICENSE.txt @@ -0,0 +1,10 @@ +The MIT License (MIT) +--------------------- + +Copyright © 2014-2023, Benoit BLANCHON + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/libraries/ArduinoJson/README.md b/libraries/ArduinoJson/README.md new file mode 100644 index 0000000..2b3d9eb --- /dev/null +++ b/libraries/ArduinoJson/README.md @@ -0,0 +1,161 @@ +

+ ArduinoJson +

+ +--- + +[![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/bblanchon/ArduinoJson/ci.yml?branch=6.x&logo=github)](https://github.com/bblanchon/ArduinoJson/actions?query=workflow%3A%22Continuous+Integration%22+branch%3A6.x) +[![Continuous Integration](https://ci.appveyor.com/api/projects/status/m7s53wav1l0abssg/branch/6.x?svg=true)](https://ci.appveyor.com/project/bblanchon/arduinojson/branch/6.x) +[![Fuzzing Status](https://oss-fuzz-build-logs.storage.googleapis.com/badges/arduinojson.svg)](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&can=1&q=proj:arduinojson) +[![Coveralls branch](https://img.shields.io/coveralls/github/bblanchon/ArduinoJson/6.x?logo=coveralls)](https://coveralls.io/github/bblanchon/ArduinoJson?branch=6.x) +[![Arduino Library Manager](https://img.shields.io/static/v1?label=Arduino&message=v6.21.2&logo=arduino&logoColor=white&color=blue)](https://www.ardu-badge.com/ArduinoJson/6.21.2) +[![PlatformIO Registry](https://badges.registry.platformio.org/packages/bblanchon/library/ArduinoJson.svg?version=6.21.2)](https://registry.platformio.org/packages/libraries/bblanchon/ArduinoJson?version=6.21.2) +[![ESP IDF](https://img.shields.io/static/v1?label=ESP+IDF&message=v6.21.2&logo=cpu&logoColor=white&color=blue)](https://components.espressif.com/components/bblanchon/arduinojson) +[![GitHub stars](https://img.shields.io/github/stars/bblanchon/ArduinoJson?style=flat&logo=github&color=orange)](https://github.com/bblanchon/ArduinoJson/stargazers) +[![GitHub Sponsors](https://img.shields.io/github/sponsors/bblanchon?logo=github&color=orange)](https://github.com/sponsors/bblanchon) + +ArduinoJson is a C++ JSON library for Arduino and IoT (Internet Of Things). + +## Features + +* [JSON deserialization](https://arduinojson.org/v6/api/json/deserializejson/) + * [Optionally decodes UTF-16 escape sequences to UTF-8](https://arduinojson.org/v6/api/config/decode_unicode/) + * [Optionally stores links to the input buffer (zero-copy)](https://arduinojson.org/v6/api/json/deserializejson/) + * [Optionally supports comments in the input](https://arduinojson.org/v6/api/config/enable_comments/) + * [Optionally filters the input to keep only desired values](https://arduinojson.org/v6/api/json/deserializejson/#filtering) + * Supports single quotes as a string delimiter + * Compatible with [NDJSON](http://ndjson.org/) and [JSON Lines](https://jsonlines.org/) +* [JSON serialization](https://arduinojson.org/v6/api/json/serializejson/) + * [Can write to a buffer or a stream](https://arduinojson.org/v6/api/json/serializejson/) + * [Optionally indents the document (prettified JSON)](https://arduinojson.org/v6/api/json/serializejsonpretty/) +* [MessagePack serialization](https://arduinojson.org/v6/api/msgpack/serializemsgpack/) +* [MessagePack deserialization](https://arduinojson.org/v6/api/msgpack/deserializemsgpack/) +* Efficient + * [Twice smaller than the "official" Arduino_JSON library](https://arduinojson.org/2019/11/19/arduinojson-vs-arduino_json/) + * [Almost 10% faster than the "official" Arduino_JSON library](https://arduinojson.org/2019/11/19/arduinojson-vs-arduino_json/) + * [Consumes roughly 10% less RAM than the "official" Arduino_JSON library](https://arduinojson.org/2019/11/19/arduinojson-vs-arduino_json/) + * [Fixed memory allocation, no heap fragmentation](https://arduinojson.org/v6/api/jsondocument/) + * [Optionally works without heap memory (zero malloc)](https://arduinojson.org/v6/api/staticjsondocument/) + * [Deduplicates strings](https://arduinojson.org/news/2020/08/01/version-6-16-0/) +* Versatile + * Supports [custom allocators (to use external RAM chip, for example)](https://arduinojson.org/v6/how-to/use-external-ram-on-esp32/) + * Supports [`String`](https://arduinojson.org/v6/api/config/enable_arduino_string/), [`std::string`](https://arduinojson.org/v6/api/config/enable_std_string/), and [`std::string_view`](https://arduinojson.org/v6/api/config/enable_string_view/) + * Supports [`Stream`](https://arduinojson.org/v6/api/config/enable_arduino_stream/) and [`std::istream`/`std::ostream`](https://arduinojson.org/v6/api/config/enable_std_stream/) + * Supports [Flash strings](https://arduinojson.org/v6/api/config/enable_progmem/) + * Supports [custom readers](https://arduinojson.org/v6/api/json/deserializejson/#custom-reader) and [custom writers](https://arduinojson.org/v6/api/json/serializejson/#custom-writer) + * Supports [custom converters](https://arduinojson.org/news/2021/05/04/version-6-18-0/) +* Portable + * Usable on any C++ project (not limited to Arduino) + * Compatible with C++11, C++14 and C++17 + * Support for C++98/C++03 available on [ArduinoJson 6.20.x](https://github.com/bblanchon/ArduinoJson/tree/6.20.x) + * Zero warnings with `-Wall -Wextra -pedantic` and `/W4` + * [Header-only library](https://en.wikipedia.org/wiki/Header-only) + * Works with virtually any board + * Arduino boards: [Uno](https://amzn.to/38aL2ik), [Due](https://amzn.to/36YkWi2), [Micro](https://amzn.to/35WkdwG), [Nano](https://amzn.to/2QTvwRX), [Mega](https://amzn.to/36XWhuf), [Yun](https://amzn.to/30odURc), [Leonardo](https://amzn.to/36XWjlR)... + * Espressif chips: [ESP8266](https://amzn.to/36YluV8), [ESP32](https://amzn.to/2G4pRCB) + * Lolin (WeMos) boards: [D1 mini](https://amzn.to/2QUpz7q), [D1 Mini Pro](https://amzn.to/36UsGSs)... + * Teensy boards: [4.0](https://amzn.to/30ljXGq), [3.2](https://amzn.to/2FT0EuC), [2.0](https://amzn.to/2QXUMXj) + * Particle boards: [Argon](https://amzn.to/2FQHa9X), [Boron](https://amzn.to/36WgLUd), [Electron](https://amzn.to/30vEc4k), [Photon](https://amzn.to/387F9Cd)... + * Texas Instruments boards: [MSP430](https://amzn.to/30nJWgg)... + * Soft cores: [Nios II](https://en.wikipedia.org/wiki/Nios_II)... + * Tested on all major development environments + * [Arduino IDE](https://www.arduino.cc/en/Main/Software) + * [Atmel Studio](http://www.atmel.com/microsite/atmel-studio/) + * [Atollic TrueSTUDIO](https://atollic.com/truestudio/) + * [Energia](http://energia.nu/) + * [IAR Embedded Workbench](https://www.iar.com/iar-embedded-workbench/) + * [Keil uVision](http://www.keil.com/) + * [MPLAB X IDE](http://www.microchip.com/mplab/mplab-x-ide) + * [Particle](https://www.particle.io/) + * [PlatformIO](http://platformio.org/) + * [Sloeber plugin for Eclipse](https://eclipse.baeyens.it/) + * [Visual Micro](http://www.visualmicro.com/) + * [Visual Studio](https://www.visualstudio.com/) + * [Even works with online compilers like wandbox.org](https://wandbox.org/permlink/RlZSKy17DjJ6HcdN) + * [CMake friendly](https://arduinojson.org/v6/how-to/use-arduinojson-with-cmake/) +* Well designed + * [Elegant API](http://arduinojson.org/v6/example/) + * [Thread-safe](https://en.wikipedia.org/wiki/Thread_safety) + * Self-contained (no external dependency) + * `const` friendly + * [`for` friendly](https://arduinojson.org/v6/api/jsonobject/begin_end/) + * [TMP friendly](https://en.wikipedia.org/wiki/Template_metaprogramming) + * Handles [integer overflows](https://arduinojson.org/v6/api/jsonvariant/as/#integer-overflows) +* Well tested + * [Unit test coverage close to 100%](https://coveralls.io/github/bblanchon/ArduinoJson?branch=6.x) + * Continuously tested on + * [Visual Studio 2017, 2019, 2022](https://ci.appveyor.com/project/bblanchon/arduinojson/branch/6.x) + * [GCC 5, 6, 7, 8, 9, 10, 11](https://github.com/bblanchon/ArduinoJson/actions?query=workflow%3A%22Continuous+Integration%22) + * [Clang 3.8, 3.9, 4.0, 5.0, 6.0, 7, 8, 9, 10](https://github.com/bblanchon/ArduinoJson/actions?query=workflow%3A%22Continuous+Integration%22) + * [Continuously fuzzed with Google OSS Fuzz](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&can=1&q=proj:arduinojson) + * Passes all default checks of [clang-tidy](https://releases.llvm.org/10.0.0/tools/clang/tools/extra/docs/clang-tidy/) +* Well documented + * [Tutorials](https://arduinojson.org/v6/doc/deserialization/) + * [Examples](https://arduinojson.org/v6/example/) + * [How-tos](https://arduinojson.org/v6/example/) + * [FAQ](https://arduinojson.org/v6/faq/) + * [Troubleshooter](https://arduinojson.org/v6/troubleshooter/) + * [Book](https://arduinojson.org/book/) + * [Changelog](CHANGELOG.md) +* Vibrant user community + * Most popular of all Arduino libraries on [GitHub](https://github.com/search?o=desc&q=arduino+library&s=stars&type=Repositories) + * [Used in hundreds of projects](https://www.hackster.io/search?i=projects&q=arduinojson) + * [Responsive support](https://github.com/bblanchon/ArduinoJson/issues?q=is%3Aissue+is%3Aclosed) + +## Quickstart + +### Deserialization + +Here is a program that parses a JSON document with ArduinoJson. + +```c++ +char json[] = "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}"; + +DynamicJsonDocument doc(1024); +deserializeJson(doc, json); + +const char* sensor = doc["sensor"]; +long time = doc["time"]; +double latitude = doc["data"][0]; +double longitude = doc["data"][1]; +``` + +See the [tutorial on arduinojson.org](https://arduinojson.org/v6/doc/deserialization/) + +### Serialization + +Here is a program that generates a JSON document with ArduinoJson: + +```c++ +DynamicJsonDocument doc(1024); + +doc["sensor"] = "gps"; +doc["time"] = 1351824120; +doc["data"][0] = 48.756080; +doc["data"][1] = 2.302038; + +serializeJson(doc, Serial); +// This prints: +// {"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]} +``` + +See the [tutorial on arduinojson.org](https://arduinojson.org/v6/doc/serialization/) + +## Sponsors + +ArduinoJson is thankful to its sponsors. Please give them a visit; they deserve it! + +

+ + Programming Electronics Academy + +

+

+ + 1technophile + +

+ +If you run a commercial project that embeds ArduinoJson, think about [sponsoring the library's development](https://github.com/sponsors/bblanchon): it ensures the code that your products rely on stays actively maintained. It can also give your project some exposure to the makers' community. + +If you are an individual user and want to support the development (or give a sign of appreciation), consider purchasing the book [Mastering ArduinoJson](https://arduinojson.org/book/) ❤, or simply [cast a star](https://github.com/bblanchon/ArduinoJson/stargazers) ⭐. diff --git a/libraries/ArduinoJson/SUPPORT.md b/libraries/ArduinoJson/SUPPORT.md new file mode 100644 index 0000000..c47e1b1 --- /dev/null +++ b/libraries/ArduinoJson/SUPPORT.md @@ -0,0 +1,27 @@ +# ArduinoJson Support + +First off, thank you very much for using ArduinoJson. + +We'll be very happy to help you, but first please read the following. + +## Before asking for help + +1. Read the [FAQ](https://arduinojson.org/faq/?utm_source=github&utm_medium=support) +2. Search in the [API Reference](https://arduinojson.org/api/?utm_source=github&utm_medium=support) + +If you did not find the answer, please create a [new issue on GitHub](https://github.com/bblanchon/ArduinoJson/issues/new). + +It is OK to add a comment to a currently opened issue, but please avoid adding comments to a closed issue. + +## Before hitting the Submit button + +Please provide all the relevant information: + +* Good title +* Short description of the problem +* Target platform +* Compiler model and version +* [MVCE](https://stackoverflow.com/help/mcve) +* Compiler output + +Good questions get fast answers! diff --git a/libraries/ArduinoJson/appveyor.yml b/libraries/ArduinoJson/appveyor.yml new file mode 100644 index 0000000..7948c64 --- /dev/null +++ b/libraries/ArduinoJson/appveyor.yml @@ -0,0 +1,28 @@ +version: 6.21.2.{build} +environment: + matrix: + - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2022 + CMAKE_GENERATOR: Visual Studio 17 2022 + - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 + CMAKE_GENERATOR: Visual Studio 16 2019 + - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 + CMAKE_GENERATOR: Visual Studio 15 2017 + - CMAKE_GENERATOR: Ninja + MINGW32: i686-6.3.0-posix-dwarf-rt_v5-rev1 # MinGW-w64 6.3.0 i686 + - CMAKE_GENERATOR: Ninja + MINGW64: x86_64-6.3.0-posix-seh-rt_v5-rev1 # MinGW-w64 6.3.0 x86_64 + - CMAKE_GENERATOR: Ninja + MINGW64: x86_64-7.3.0-posix-seh-rt_v5-rev0 # MinGW-w64 7.3.0 x86_64 + - CMAKE_GENERATOR: Ninja + MINGW64: x86_64-8.1.0-posix-seh-rt_v6-rev0 # MinGW-w64 8.1.0 x86_64 +configuration: Debug +before_build: + - set PATH=%PATH:C:\Program Files\Git\usr\bin;=% # Workaround for CMake not wanting sh.exe on PATH for MinGW + - if defined MINGW set PATH=C:\%MINGW%\bin;%PATH% + - if defined MINGW32 set PATH=C:\mingw-w64\%MINGW32%\mingw32\bin;%PATH% + - if defined MINGW64 set PATH=C:\mingw-w64\%MINGW64%\mingw64\bin;%PATH% + - cmake -DCMAKE_BUILD_TYPE=%CONFIGURATION% -G "%CMAKE_GENERATOR%" . +build_script: + - cmake --build . --config %CONFIGURATION% +test_script: + - ctest -C %CONFIGURATION% --output-on-failure . diff --git a/libraries/ArduinoJson/component.mk b/libraries/ArduinoJson/component.mk new file mode 100644 index 0000000..dc25d1c --- /dev/null +++ b/libraries/ArduinoJson/component.mk @@ -0,0 +1 @@ +COMPONENT_ADD_INCLUDEDIRS := src diff --git a/libraries/ArduinoJson/examples/JsonConfigFile/JsonConfigFile.ino b/libraries/ArduinoJson/examples/JsonConfigFile/JsonConfigFile.ino new file mode 100644 index 0000000..b2819d5 --- /dev/null +++ b/libraries/ArduinoJson/examples/JsonConfigFile/JsonConfigFile.ino @@ -0,0 +1,160 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License +// +// This example shows how to store your project configuration in a file. +// It uses the SD library but can be easily modified for any other file-system. +// +// The file contains a JSON document with the following content: +// { +// "hostname": "examples.com", +// "port": 2731 +// } +// +// To run this program, you need an SD card connected to the SPI bus as follows: +// * MOSI <-> pin 11 +// * MISO <-> pin 12 +// * CLK <-> pin 13 +// * CS <-> pin 4 +// +// https://arduinojson.org/v6/example/config/ + +#include +#include +#include + +// Our configuration structure. +// +// Never use a JsonDocument to store the configuration! +// A JsonDocument is *not* a permanent storage; it's only a temporary storage +// used during the serialization phase. See: +// https://arduinojson.org/v6/faq/why-must-i-create-a-separate-config-object/ +struct Config { + char hostname[64]; + int port; +}; + +const char *filename = "/config.txt"; // <- SD library uses 8.3 filenames +Config config; // <- global configuration object + +// Loads the configuration from a file +void loadConfiguration(const char *filename, Config &config) { + // Open file for reading + File file = SD.open(filename); + + // Allocate a temporary JsonDocument + // Don't forget to change the capacity to match your requirements. + // Use https://arduinojson.org/v6/assistant to compute the capacity. + StaticJsonDocument<512> doc; + + // Deserialize the JSON document + DeserializationError error = deserializeJson(doc, file); + if (error) + Serial.println(F("Failed to read file, using default configuration")); + + // Copy values from the JsonDocument to the Config + config.port = doc["port"] | 2731; + strlcpy(config.hostname, // <- destination + doc["hostname"] | "example.com", // <- source + sizeof(config.hostname)); // <- destination's capacity + + // Close the file (Curiously, File's destructor doesn't close the file) + file.close(); +} + +// Saves the configuration to a file +void saveConfiguration(const char *filename, const Config &config) { + // Delete existing file, otherwise the configuration is appended to the file + SD.remove(filename); + + // Open file for writing + File file = SD.open(filename, FILE_WRITE); + if (!file) { + Serial.println(F("Failed to create file")); + return; + } + + // Allocate a temporary JsonDocument + // Don't forget to change the capacity to match your requirements. + // Use https://arduinojson.org/assistant to compute the capacity. + StaticJsonDocument<256> doc; + + // Set the values in the document + doc["hostname"] = config.hostname; + doc["port"] = config.port; + + // Serialize JSON to file + if (serializeJson(doc, file) == 0) { + Serial.println(F("Failed to write to file")); + } + + // Close the file + file.close(); +} + +// Prints the content of a file to the Serial +void printFile(const char *filename) { + // Open file for reading + File file = SD.open(filename); + if (!file) { + Serial.println(F("Failed to read file")); + return; + } + + // Extract each characters by one by one + while (file.available()) { + Serial.print((char)file.read()); + } + Serial.println(); + + // Close the file + file.close(); +} + +void setup() { + // Initialize serial port + Serial.begin(9600); + while (!Serial) continue; + + // Initialize SD library + const int chipSelect = 4; + while (!SD.begin(chipSelect)) { + Serial.println(F("Failed to initialize SD library")); + delay(1000); + } + + // Should load default config if run for the first time + Serial.println(F("Loading configuration...")); + loadConfiguration(filename, config); + + // Create configuration file + Serial.println(F("Saving configuration...")); + saveConfiguration(filename, config); + + // Dump config file + Serial.println(F("Print config file...")); + printFile(filename); +} + +void loop() { + // not used in this example +} + +// Performance issue? +// ------------------ +// +// File is an unbuffered stream, which is not optimal for ArduinoJson. +// See: https://arduinojson.org/v6/how-to/improve-speed/ + +// See also +// -------- +// +// https://arduinojson.org/ contains the documentation for all the functions +// used above. It also includes an FAQ that will help you solve any +// serialization or deserialization problem. +// +// The book "Mastering ArduinoJson" contains a case study of a project that has +// a complex configuration with nested members. +// Contrary to this example, the project in the book uses the SPIFFS filesystem. +// Learn more at https://arduinojson.org/book/ +// Use the coupon code TWENTY for a 20% discount ❤❤❤❤❤ diff --git a/libraries/ArduinoJson/examples/JsonFilterExample/JsonFilterExample.ino b/libraries/ArduinoJson/examples/JsonFilterExample/JsonFilterExample.ino new file mode 100644 index 0000000..fc980aa --- /dev/null +++ b/libraries/ArduinoJson/examples/JsonFilterExample/JsonFilterExample.ino @@ -0,0 +1,63 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License +// +// This example shows how to use DeserializationOption::Filter +// +// https://arduinojson.org/v6/example/filter/ + +#include + +void setup() { + // Initialize serial port + Serial.begin(9600); + while (!Serial) continue; + + // The huge input: an extract from OpenWeatherMap response + const __FlashStringHelper* input_json = F( + "{\"cod\":\"200\",\"message\":0,\"list\":[{\"dt\":1581498000,\"main\":{" + "\"temp\":3.23,\"feels_like\":-3.63,\"temp_min\":3.23,\"temp_max\":4.62," + "\"pressure\":1014,\"sea_level\":1014,\"grnd_level\":1010,\"humidity\":" + "58,\"temp_kf\":-1.39},\"weather\":[{\"id\":800,\"main\":\"Clear\"," + "\"description\":\"clear " + "sky\",\"icon\":\"01d\"}],\"clouds\":{\"all\":0},\"wind\":{\"speed\":6." + "19,\"deg\":266},\"sys\":{\"pod\":\"d\"},\"dt_txt\":\"2020-02-12 " + "09:00:00\"},{\"dt\":1581508800,\"main\":{\"temp\":6.09,\"feels_like\":-" + "1.07,\"temp_min\":6.09,\"temp_max\":7.13,\"pressure\":1015,\"sea_" + "level\":1015,\"grnd_level\":1011,\"humidity\":48,\"temp_kf\":-1.04}," + "\"weather\":[{\"id\":800,\"main\":\"Clear\",\"description\":\"clear " + "sky\",\"icon\":\"01d\"}],\"clouds\":{\"all\":9},\"wind\":{\"speed\":6." + "64,\"deg\":268},\"sys\":{\"pod\":\"d\"},\"dt_txt\":\"2020-02-12 " + "12:00:00\"}],\"city\":{\"id\":2643743,\"name\":\"London\",\"coord\":{" + "\"lat\":51.5085,\"lon\":-0.1257},\"country\":\"GB\",\"population\":" + "1000000,\"timezone\":0,\"sunrise\":1581492085,\"sunset\":1581527294}}"); + + // The filter: it contains "true" for each value we want to keep + StaticJsonDocument<200> filter; + filter["list"][0]["dt"] = true; + filter["list"][0]["main"]["temp"] = true; + + // Deserialize the document + StaticJsonDocument<400> doc; + deserializeJson(doc, input_json, DeserializationOption::Filter(filter)); + + // Print the result + serializeJsonPretty(doc, Serial); +} + +void loop() { + // not used in this example +} + +// See also +// -------- +// +// https://arduinojson.org/ contains the documentation for all the functions +// used above. It also includes an FAQ that will help you solve any +// deserialization problem. +// +// The book "Mastering ArduinoJson" contains a tutorial on deserialization. +// It begins with a simple example, like the one above, and then adds more +// features like deserializing directly from a file or an HTTP request. +// Learn more at https://arduinojson.org/book/ +// Use the coupon code TWENTY for a 20% discount ❤❤❤❤❤ diff --git a/libraries/ArduinoJson/examples/JsonGeneratorExample/JsonGeneratorExample.ino b/libraries/ArduinoJson/examples/JsonGeneratorExample/JsonGeneratorExample.ino new file mode 100644 index 0000000..749e413 --- /dev/null +++ b/libraries/ArduinoJson/examples/JsonGeneratorExample/JsonGeneratorExample.ino @@ -0,0 +1,77 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License +// +// This example shows how to generate a JSON document with ArduinoJson. +// +// https://arduinojson.org/v6/example/generator/ + +#include + +void setup() { + // Initialize Serial port + Serial.begin(9600); + while (!Serial) continue; + + // Allocate the JSON document + // + // Inside the brackets, 200 is the RAM allocated to this document. + // Don't forget to change this value to match your requirement. + // Use https://arduinojson.org/v6/assistant to compute the capacity. + StaticJsonDocument<200> doc; + + // StaticJsonObject allocates memory on the stack, it can be + // replaced by DynamicJsonDocument which allocates in the heap. + // + // DynamicJsonDocument doc(200); + + // Add values in the document + // + doc["sensor"] = "gps"; + doc["time"] = 1351824120; + + // Add an array. + // + JsonArray data = doc.createNestedArray("data"); + data.add(48.756080); + data.add(2.302038); + + // Generate the minified JSON and send it to the Serial port. + // + serializeJson(doc, Serial); + // The above line prints: + // {"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]} + + // Start a new line + Serial.println(); + + // Generate the prettified JSON and send it to the Serial port. + // + serializeJsonPretty(doc, Serial); + // The above line prints: + // { + // "sensor": "gps", + // "time": 1351824120, + // "data": [ + // 48.756080, + // 2.302038 + // ] + // } +} + +void loop() { + // not used in this example +} + +// See also +// -------- +// +// https://arduinojson.org/ contains the documentation for all the functions +// used above. It also includes an FAQ that will help you solve any +// serialization problem. +// +// The book "Mastering ArduinoJson" contains a tutorial on serialization. +// It begins with a simple example, like the one above, and then adds more +// features like serializing directly to a file or an HTTP request. +// Learn more at https://arduinojson.org/book/ +// Use the coupon code TWENTY for a 20% discount ❤❤❤❤❤ diff --git a/libraries/ArduinoJson/examples/JsonHttpClient/JsonHttpClient.ino b/libraries/ArduinoJson/examples/JsonHttpClient/JsonHttpClient.ino new file mode 100644 index 0000000..72f311f --- /dev/null +++ b/libraries/ArduinoJson/examples/JsonHttpClient/JsonHttpClient.ino @@ -0,0 +1,126 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License +// +// This example shows how to parse a JSON document in an HTTP response. +// It uses the Ethernet library, but can be easily adapted for Wifi. +// +// It performs a GET resquest on https://arduinojson.org/example.json +// Here is the expected response: +// { +// "sensor": "gps", +// "time": 1351824120, +// "data": [ +// 48.756080, +// 2.302038 +// ] +// } +// +// https://arduinojson.org/v6/example/http-client/ + +#include +#include +#include + +void setup() { + // Initialize Serial port + Serial.begin(9600); + while (!Serial) continue; + + // Initialize Ethernet library + byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; + if (!Ethernet.begin(mac)) { + Serial.println(F("Failed to configure Ethernet")); + return; + } + delay(1000); + + Serial.println(F("Connecting...")); + + // Connect to HTTP server + EthernetClient client; + client.setTimeout(10000); + if (!client.connect("arduinojson.org", 80)) { + Serial.println(F("Connection failed")); + return; + } + + Serial.println(F("Connected!")); + + // Send HTTP request + client.println(F("GET /example.json HTTP/1.0")); + client.println(F("Host: arduinojson.org")); + client.println(F("Connection: close")); + if (client.println() == 0) { + Serial.println(F("Failed to send request")); + client.stop(); + return; + } + + // Check HTTP status + char status[32] = {0}; + client.readBytesUntil('\r', status, sizeof(status)); + // It should be "HTTP/1.0 200 OK" or "HTTP/1.1 200 OK" + if (strcmp(status + 9, "200 OK") != 0) { + Serial.print(F("Unexpected response: ")); + Serial.println(status); + client.stop(); + return; + } + + // Skip HTTP headers + char endOfHeaders[] = "\r\n\r\n"; + if (!client.find(endOfHeaders)) { + Serial.println(F("Invalid response")); + client.stop(); + return; + } + + // Allocate the JSON document + // Use https://arduinojson.org/v6/assistant to compute the capacity. + const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_ARRAY_SIZE(2) + 60; + DynamicJsonDocument doc(capacity); + + // Parse JSON object + DeserializationError error = deserializeJson(doc, client); + if (error) { + Serial.print(F("deserializeJson() failed: ")); + Serial.println(error.f_str()); + client.stop(); + return; + } + + // Extract values + Serial.println(F("Response:")); + Serial.println(doc["sensor"].as()); + Serial.println(doc["time"].as()); + Serial.println(doc["data"][0].as(), 6); + Serial.println(doc["data"][1].as(), 6); + + // Disconnect + client.stop(); +} + +void loop() { + // not used in this example +} + +// Performance issue? +// ------------------ +// +// EthernetClient is an unbuffered stream, which is not optimal for ArduinoJson. +// See: https://arduinojson.org/v6/how-to/improve-speed/ + +// See also +// -------- +// +// https://arduinojson.org/ contains the documentation for all the functions +// used above. It also includes an FAQ that will help you solve any +// serialization problem. +// +// The book "Mastering ArduinoJson" contains a tutorial on deserialization +// showing how to parse the response from GitHub's API. In the last chapter, +// it shows how to parse the huge documents from OpenWeatherMap +// and Reddit. +// Learn more at https://arduinojson.org/book/ +// Use the coupon code TWENTY for a 20% discount ❤❤❤❤❤ diff --git a/libraries/ArduinoJson/examples/JsonParserExample/JsonParserExample.ino b/libraries/ArduinoJson/examples/JsonParserExample/JsonParserExample.ino new file mode 100644 index 0000000..1d2bd16 --- /dev/null +++ b/libraries/ArduinoJson/examples/JsonParserExample/JsonParserExample.ino @@ -0,0 +1,80 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License +// +// This example shows how to deserialize a JSON document with ArduinoJson. +// +// https://arduinojson.org/v6/example/parser/ + +#include + +void setup() { + // Initialize serial port + Serial.begin(9600); + while (!Serial) continue; + + // Allocate the JSON document + // + // Inside the brackets, 200 is the capacity of the memory pool in bytes. + // Don't forget to change this value to match your JSON document. + // Use https://arduinojson.org/v6/assistant to compute the capacity. + StaticJsonDocument<200> doc; + + // StaticJsonDocument allocates memory on the stack, it can be + // replaced by DynamicJsonDocument which allocates in the heap. + // + // DynamicJsonDocument doc(200); + + // JSON input string. + // + // Using a char[], as shown here, enables the "zero-copy" mode. This mode uses + // the minimal amount of memory because the JsonDocument stores pointers to + // the input buffer. + // If you use another type of input, ArduinoJson must copy the strings from + // the input to the JsonDocument, so you need to increase the capacity of the + // JsonDocument. + char json[] = + "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}"; + + // Deserialize the JSON document + DeserializationError error = deserializeJson(doc, json); + + // Test if parsing succeeds. + if (error) { + Serial.print(F("deserializeJson() failed: ")); + Serial.println(error.f_str()); + return; + } + + // Fetch values. + // + // Most of the time, you can rely on the implicit casts. + // In other case, you can do doc["time"].as(); + const char* sensor = doc["sensor"]; + long time = doc["time"]; + double latitude = doc["data"][0]; + double longitude = doc["data"][1]; + + // Print values. + Serial.println(sensor); + Serial.println(time); + Serial.println(latitude, 6); + Serial.println(longitude, 6); +} + +void loop() { + // not used in this example +} + +// See also +// -------- +// +// https://arduinojson.org/ contains the documentation for all the functions +// used above. It also includes an FAQ that will help you solve any +// deserialization problem. +// +// The book "Mastering ArduinoJson" contains a tutorial on deserialization. +// It begins with a simple example, like the one above, and then adds more +// features like deserializing directly from a file or an HTTP request. +// Learn more at https://arduinojson.org/book/ +// Use the coupon code TWENTY for a 20% discount ❤❤❤❤❤ diff --git a/libraries/ArduinoJson/examples/JsonServer/JsonServer.ino b/libraries/ArduinoJson/examples/JsonServer/JsonServer.ino new file mode 100644 index 0000000..a897fce --- /dev/null +++ b/libraries/ArduinoJson/examples/JsonServer/JsonServer.ino @@ -0,0 +1,117 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License +// +// This example shows how to implement an HTTP server that sends a JSON document +// in the response. +// It uses the Ethernet library but can be easily adapted for Wifi. +// +// The JSON document contains the values of the analog and digital pins. +// It looks like that: +// { +// "analog": [0, 76, 123, 158, 192, 205], +// "digital": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0] +// } +// +// https://arduinojson.org/v6/example/http-server/ + +#include +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +EthernetServer server(80); + +void setup() { + // Initialize serial port + Serial.begin(9600); + while (!Serial) continue; + + // Initialize Ethernet libary + if (!Ethernet.begin(mac)) { + Serial.println(F("Failed to initialize Ethernet library")); + return; + } + + // Start to listen + server.begin(); + + Serial.println(F("Server is ready.")); + Serial.print(F("Please connect to http://")); + Serial.println(Ethernet.localIP()); +} + +void loop() { + // Wait for an incomming connection + EthernetClient client = server.available(); + + // Do we have a client? + if (!client) + return; + + Serial.println(F("New client")); + + // Read the request (we ignore the content in this example) + while (client.available()) client.read(); + + // Allocate a temporary JsonDocument + // Use https://arduinojson.org/v6/assistant to compute the capacity. + StaticJsonDocument<500> doc; + + // Create the "analog" array + JsonArray analogValues = doc.createNestedArray("analog"); + for (int pin = 0; pin < 6; pin++) { + // Read the analog input + int value = analogRead(pin); + + // Add the value at the end of the array + analogValues.add(value); + } + + // Create the "digital" array + JsonArray digitalValues = doc.createNestedArray("digital"); + for (int pin = 0; pin < 14; pin++) { + // Read the digital input + int value = digitalRead(pin); + + // Add the value at the end of the array + digitalValues.add(value); + } + + Serial.print(F("Sending: ")); + serializeJson(doc, Serial); + Serial.println(); + + // Write response headers + client.println(F("HTTP/1.0 200 OK")); + client.println(F("Content-Type: application/json")); + client.println(F("Connection: close")); + client.print(F("Content-Length: ")); + client.println(measureJsonPretty(doc)); + client.println(); + + // Write JSON document + serializeJsonPretty(doc, client); + + // Disconnect + client.stop(); +} + +// Performance issue? +// ------------------ +// +// EthernetClient is an unbuffered stream, which is not optimal for ArduinoJson. +// See: https://arduinojson.org/v6/how-to/improve-speed/ + +// See also +// -------- +// +// https://arduinojson.org/ contains the documentation for all the functions +// used above. It also includes an FAQ that will help you solve any +// serialization problem. +// +// The book "Mastering ArduinoJson" contains a tutorial on serialization. +// It begins with a simple example, then adds more features like serializing +// directly to a file or an HTTP client. +// Learn more at https://arduinojson.org/book/ +// Use the coupon code TWENTY for a 20% discount ❤❤❤❤❤ diff --git a/libraries/ArduinoJson/examples/JsonUdpBeacon/JsonUdpBeacon.ino b/libraries/ArduinoJson/examples/JsonUdpBeacon/JsonUdpBeacon.ino new file mode 100644 index 0000000..6c369fa --- /dev/null +++ b/libraries/ArduinoJson/examples/JsonUdpBeacon/JsonUdpBeacon.ino @@ -0,0 +1,106 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License +// +// This example shows how to send a JSON document to a UDP socket. +// At regular interval, it sends a UDP packet that contains the status of +// analog and digital pins. +// It looks like that: +// { +// "analog": [0, 76, 123, 158, 192, 205], +// "digital": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0] +// } +// +// If you want to test this program, you need to be able to receive the UDP +// packets. +// For example, you can run netcat on your computer +// $ ncat -ulp 8888 +// See https://nmap.org/ncat/ +// +// https://arduinojson.org/v6/example/udp-beacon/ + +#include +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress remoteIp(192, 168, 0, 108); // <- EDIT!!!! +unsigned short remotePort = 8888; +unsigned short localPort = 8888; +EthernetUDP udp; + +void setup() { + // Initialize serial port + Serial.begin(9600); + while (!Serial) continue; + + // Initialize Ethernet libary + if (!Ethernet.begin(mac)) { + Serial.println(F("Failed to initialize Ethernet library")); + return; + } + + // Enable UDP + udp.begin(localPort); +} + +void loop() { + // Allocate a temporary JsonDocument + // Use https://arduinojson.org/v6/assistant to compute the capacity. + StaticJsonDocument<500> doc; + + // Create the "analog" array + JsonArray analogValues = doc.createNestedArray("analog"); + for (int pin = 0; pin < 6; pin++) { + // Read the analog input + int value = analogRead(pin); + + // Add the value at the end of the array + analogValues.add(value); + } + + // Create the "digital" array + JsonArray digitalValues = doc.createNestedArray("digital"); + for (int pin = 0; pin < 14; pin++) { + // Read the digital input + int value = digitalRead(pin); + + // Add the value at the end of the array + digitalValues.add(value); + } + + // Log + Serial.print(F("Sending to ")); + Serial.print(remoteIp); + Serial.print(F(" on port ")); + Serial.println(remotePort); + serializeJson(doc, Serial); + + // Send UDP packet + udp.beginPacket(remoteIp, remotePort); + serializeJson(doc, udp); + udp.println(); + udp.endPacket(); + + // Wait + delay(10000); +} + +// Performance issue? +// ------------------ +// +// EthernetUDP is an unbuffered stream, which is not optimal for ArduinoJson. +// See: https://arduinojson.org/v6/how-to/improve-speed/ + +// See also +// -------- +// +// https://arduinojson.org/ contains the documentation for all the functions +// used above. It also includes an FAQ that will help you solve any +// serialization problem. +// +// The book "Mastering ArduinoJson" contains a tutorial on serialization. +// It begins with a simple example, then adds more features like serializing +// directly to a file or any stream. +// Learn more at https://arduinojson.org/book/ +// Use the coupon code TWENTY for a 20% discount ❤❤❤❤❤ diff --git a/libraries/ArduinoJson/examples/MsgPackParser/MsgPackParser.ino b/libraries/ArduinoJson/examples/MsgPackParser/MsgPackParser.ino new file mode 100644 index 0000000..1a54c3b --- /dev/null +++ b/libraries/ArduinoJson/examples/MsgPackParser/MsgPackParser.ino @@ -0,0 +1,75 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License +// +// This example shows how to deserialize a MessagePack document with +// ArduinoJson. +// +// https://arduinojson.org/v6/example/msgpack-parser/ + +#include + +void setup() { + // Initialize serial port + Serial.begin(9600); + while (!Serial) continue; + + // Allocate the JSON document + // + // Inside the brackets, 200 is the capacity of the memory pool in bytes. + // Don't forget to change this value to match your JSON document. + // Use https://arduinojson.org/v6/assistant to compute the capacity. + StaticJsonDocument<200> doc; + + // StaticJsonObject allocates memory on the stack, it can be + // replaced by DynamicJsonObject which allocates in the heap. + // + // DynamicJsonObject doc(200); + + // MessagePack input string. + // + // Using a char[], as shown here, enables the "zero-copy" mode. This mode uses + // the minimal amount of memory because the JsonDocument stores pointers to + // the input buffer. + // If you use another type of input, ArduinoJson must copy the strings from + // the input to the JsonDocument, so you need to increase the capacity of the + // JsonDocument. + uint8_t input[] = {131, 166, 115, 101, 110, 115, 111, 114, 163, 103, 112, 115, + 164, 116, 105, 109, 101, 206, 80, 147, 50, 248, 164, 100, + 97, 116, 97, 146, 203, 64, 72, 96, 199, 58, 188, 148, + 112, 203, 64, 2, 106, 146, 230, 33, 49, 169}; + // This MessagePack document contains: + // { + // "sensor": "gps", + // "time": 1351824120, + // "data": [48.75608, 2.302038] + // } + + DeserializationError error = deserializeMsgPack(doc, input); + + // Test if parsing succeeded. + if (error) { + Serial.print("deserializeMsgPack() failed: "); + Serial.println(error.f_str()); + return; + } + + // Fetch values. + // + // Most of the time, you can rely on the implicit casts. + // In other case, you can do doc["time"].as(); + const char* sensor = doc["sensor"]; + long time = doc["time"]; + double latitude = doc["data"][0]; + double longitude = doc["data"][1]; + + // Print values. + Serial.println(sensor); + Serial.println(time); + Serial.println(latitude, 6); + Serial.println(longitude, 6); +} + +void loop() { + // not used in this example +} diff --git a/libraries/ArduinoJson/examples/ProgmemExample/ProgmemExample.ino b/libraries/ArduinoJson/examples/ProgmemExample/ProgmemExample.ino new file mode 100644 index 0000000..68b8ec5 --- /dev/null +++ b/libraries/ArduinoJson/examples/ProgmemExample/ProgmemExample.ino @@ -0,0 +1,63 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License +// +// This example shows the different ways you can use Flash strings with +// ArduinoJson. +// +// Use Flash strings sparingly, because ArduinoJson duplicates them in the +// JsonDocument. Prefer plain old char*, as they are more efficient in term of +// code size, speed, and memory usage. +// +// https://arduinojson.org/v6/example/progmem/ + +#include + +void setup() { + DynamicJsonDocument doc(1024); + + // You can use a Flash String as your JSON input. + // WARNING: the strings in the input will be duplicated in the JsonDocument. + deserializeJson(doc, F("{\"sensor\":\"gps\",\"time\":1351824120," + "\"data\":[48.756080,2.302038]}")); + + // You can use a Flash String as a key to get a member from JsonDocument + // No duplication is done. + long time = doc[F("time")]; + + // You can use a Flash String as a key to set a member of a JsonDocument + // WARNING: the content of the Flash String will be duplicated in the + // JsonDocument. + doc[F("time")] = time; + + // You can set a Flash String as the content of a JsonVariant + // WARNING: the content of the Flash String will be duplicated in the + // JsonDocument. + doc["sensor"] = F("gps"); + + // It works with serialized() too: + doc["sensor"] = serialized(F("\"gps\"")); + doc["sensor"] = serialized(F("\xA3gps"), 3); + + // You can compare the content of a JsonVariant to a Flash String + if (doc["sensor"] == F("gps")) { + // ... + } +} + +void loop() { + // not used in this example +} + +// See also +// -------- +// +// https://arduinojson.org/ contains the documentation for all the functions +// used above. It also includes an FAQ that will help you solve any memory +// problem. +// +// The book "Mastering ArduinoJson" contains a quick C++ course that explains +// how your microcontroller stores strings in memory. It also tells why you +// should not abuse Flash strings with ArduinoJson. +// Learn more at https://arduinojson.org/book/ +// Use the coupon code TWENTY for a 20% discount ❤❤❤❤❤ diff --git a/libraries/ArduinoJson/examples/StringExample/StringExample.ino b/libraries/ArduinoJson/examples/StringExample/StringExample.ino new file mode 100644 index 0000000..3e51b91 --- /dev/null +++ b/libraries/ArduinoJson/examples/StringExample/StringExample.ino @@ -0,0 +1,77 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License +// +// This example shows the different ways you can use String with ArduinoJson. +// +// Use String objects sparingly, because ArduinoJson duplicates them in the +// JsonDocument. Prefer plain old char[], as they are more efficient in term of +// code size, speed, and memory usage. +// +// https://arduinojson.org/v6/example/string/ + +#include + +void setup() { + DynamicJsonDocument doc(1024); + + // You can use a String as your JSON input. + // WARNING: the string in the input will be duplicated in the JsonDocument. + String input = + "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}"; + deserializeJson(doc, input); + + // You can use a String as a key to get a member from JsonDocument + // No duplication is done. + long time = doc[String("time")]; + + // You can use a String as a key to set a member of a JsonDocument + // WARNING: the content of the String will be duplicated in the JsonDocument. + doc[String("time")] = time; + + // You can get the content of a JsonVariant as a String + // No duplication is done, at least not in the JsonDocument. + String sensor = doc["sensor"]; + + // Unfortunately, the following doesn't work (issue #118): + // sensor = doc["sensor"]; // <- error "ambiguous overload for 'operator='" + // As a workaround, you need to replace by: + sensor = doc["sensor"].as(); + + // You can set a String as the content of a JsonVariant + // WARNING: the content of the String will be duplicated in the JsonDocument. + doc["sensor"] = sensor; + + // It works with serialized() too: + doc["sensor"] = serialized(sensor); + + // You can also concatenate strings + // WARNING: the content of the String will be duplicated in the JsonDocument. + doc[String("sen") + "sor"] = String("gp") + "s"; + + // You can compare the content of a JsonObject with a String + if (doc["sensor"] == sensor) { + // ... + } + + // Lastly, you can print the resulting JSON to a String + // WARNING: it doesn't replace the content but appends to it + String output; + serializeJson(doc, output); +} + +void loop() { + // not used in this example +} + +// See also +// -------- +// +// https://arduinojson.org/ contains the documentation for all the functions +// used above. It also includes an FAQ that will help you solve any problem. +// +// The book "Mastering ArduinoJson" contains a quick C++ course that explains +// how your microcontroller stores strings in memory. On several occasions, it +// shows how you can avoid String in your program. +// Learn more at https://arduinojson.org/book/ +// Use the coupon code TWENTY for a 20% discount ❤❤❤❤❤ diff --git a/libraries/ArduinoJson/extras/ArduinoJsonConfig.cmake.in b/libraries/ArduinoJson/extras/ArduinoJsonConfig.cmake.in new file mode 100644 index 0000000..9c15f36 --- /dev/null +++ b/libraries/ArduinoJson/extras/ArduinoJsonConfig.cmake.in @@ -0,0 +1,4 @@ +@PACKAGE_INIT@ + +include("${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@Targets.cmake") +check_required_components("@PROJECT_NAME@") diff --git a/libraries/ArduinoJson/extras/CompileOptions.cmake b/libraries/ArduinoJson/extras/CompileOptions.cmake new file mode 100644 index 0000000..0cbd576 --- /dev/null +++ b/libraries/ArduinoJson/extras/CompileOptions.cmake @@ -0,0 +1,95 @@ +if(CMAKE_CXX_COMPILER_ID MATCHES "(GNU|Clang)") + add_compile_options( + -pedantic + -Wall + -Wcast-align + -Wcast-qual + -Wconversion + -Wctor-dtor-privacy + -Wdisabled-optimization + -Werror + -Wextra + -Wformat=2 + -Winit-self + -Wmissing-include-dirs + -Wnon-virtual-dtor + -Wold-style-cast + -Woverloaded-virtual + -Wparentheses + -Wredundant-decls + -Wshadow + -Wsign-conversion + -Wsign-promo + -Wstrict-aliasing + -Wundef + ) + + if(${COVERAGE}) + set(CMAKE_CXX_FLAGS "-fprofile-arcs -ftest-coverage") + endif() +endif() + +if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") + if((CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 4.8) AND(NOT ${COVERAGE})) + add_compile_options(-g -Og) + else() + add_compile_options(-g -O0) + endif() + + add_compile_options( + -Wstrict-null-sentinel + -Wno-vla # Allow VLA in tests + ) + add_definitions(-DHAS_VARIABLE_LENGTH_ARRAY) + + if(CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 4.5) + add_compile_options(-Wlogical-op) # the flag exists in 4.4 but is buggy + endif() + + if(CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 4.6) + add_compile_options(-Wnoexcept) + endif() +endif() + +if(CMAKE_CXX_COMPILER_ID MATCHES "Clang") + add_compile_options( + -Wc++11-compat + -Wdeprecated-register + -Wno-vla-extension # Allow VLA in tests + ) + add_definitions( + -DHAS_VARIABLE_LENGTH_ARRAY + -DSUBSCRIPT_CONFLICTS_WITH_BUILTIN_OPERATOR + ) +endif() + +if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") + if((CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 4.0) AND(NOT ${COVERAGE})) + add_compile_options(-g -Og) + else() + add_compile_options(-g -O0) + endif() +endif() + +if(CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang") + if((CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 9.0) AND(NOT ${COVERAGE})) + add_compile_options(-g -Og) + else() + add_compile_options(-g -O0) + endif() +endif() + +if(MSVC) + add_definitions(-D_CRT_SECURE_NO_WARNINGS) + add_compile_options( + /W4 # Set warning level + /WX # Treats all compiler warnings as errors. + /Zc:__cplusplus # Enable updated __cplusplus macro + ) +endif() + +if(MINGW) + # Static link on MinGW to avoid linking with the wrong DLLs when multiple + # versions are installed. + add_link_options(-static) +endif() diff --git a/libraries/ArduinoJson/extras/ci/espidf/CMakeLists.txt b/libraries/ArduinoJson/extras/ci/espidf/CMakeLists.txt new file mode 100644 index 0000000..3b87896 --- /dev/null +++ b/libraries/ArduinoJson/extras/ci/espidf/CMakeLists.txt @@ -0,0 +1,8 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2023, Benoit BLANCHON +# MIT License + +cmake_minimum_required(VERSION 3.5) + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +project(example) diff --git a/libraries/ArduinoJson/extras/ci/espidf/main/CMakeLists.txt b/libraries/ArduinoJson/extras/ci/espidf/main/CMakeLists.txt new file mode 100644 index 0000000..3e10ef8 --- /dev/null +++ b/libraries/ArduinoJson/extras/ci/espidf/main/CMakeLists.txt @@ -0,0 +1,8 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2023, Benoit BLANCHON +# MIT License + +idf_component_register( + SRCS "main.cpp" + INCLUDE_DIRS "" +) diff --git a/libraries/ArduinoJson/extras/ci/espidf/main/component.mk b/libraries/ArduinoJson/extras/ci/espidf/main/component.mk new file mode 100644 index 0000000..a98f634 --- /dev/null +++ b/libraries/ArduinoJson/extras/ci/espidf/main/component.mk @@ -0,0 +1,4 @@ +# +# "main" pseudo-component makefile. +# +# (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.) diff --git a/libraries/ArduinoJson/extras/ci/espidf/main/main.cpp b/libraries/ArduinoJson/extras/ci/espidf/main/main.cpp new file mode 100644 index 0000000..4818a67 --- /dev/null +++ b/libraries/ArduinoJson/extras/ci/espidf/main/main.cpp @@ -0,0 +1,16 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include + +extern "C" void app_main() { + char buffer[256]; + StaticJsonDocument<200> doc; + + doc["hello"] = "world"; + serializeJson(doc, buffer); + deserializeJson(doc, buffer); + serializeMsgPack(doc, buffer); + deserializeMsgPack(doc, buffer); +} diff --git a/libraries/ArduinoJson/extras/ci/particle.sh b/libraries/ArduinoJson/extras/ci/particle.sh new file mode 100644 index 0000000..5566353 --- /dev/null +++ b/libraries/ArduinoJson/extras/ci/particle.sh @@ -0,0 +1,10 @@ +#!/bin/sh -ex + +BOARD=$1 + +cd "$(dirname "$0")/../../" + +cp extras/particle/src/smocktest.ino src/ +cp extras/particle/project.properties ./ + +particle compile "$BOARD" diff --git a/libraries/ArduinoJson/extras/conf_test/avr.cpp b/libraries/ArduinoJson/extras/conf_test/avr.cpp new file mode 100644 index 0000000..b2b105e --- /dev/null +++ b/libraries/ArduinoJson/extras/conf_test/avr.cpp @@ -0,0 +1,18 @@ +#include + +static_assert(ARDUINOJSON_ENABLE_PROGMEM == 1, "ARDUINOJSON_ENABLE_PROGMEM"); + +static_assert(ARDUINOJSON_USE_LONG_LONG == 0, "ARDUINOJSON_USE_LONG_LONG"); + +static_assert(ARDUINOJSON_SLOT_OFFSET_SIZE == 1, + "ARDUINOJSON_SLOT_OFFSET_SIZE"); + +static_assert(ARDUINOJSON_LITTLE_ENDIAN == 1, "ARDUINOJSON_LITTLE_ENDIAN"); + +static_assert(ARDUINOJSON_USE_DOUBLE == 1, "ARDUINOJSON_USE_DOUBLE"); + +static_assert(sizeof(ArduinoJson::detail::VariantSlot) == 8, + "sizeof(VariantSlot)"); + +void setup() {} +void loop() {} diff --git a/libraries/ArduinoJson/extras/conf_test/esp8266.cpp b/libraries/ArduinoJson/extras/conf_test/esp8266.cpp new file mode 100644 index 0000000..caf70b2 --- /dev/null +++ b/libraries/ArduinoJson/extras/conf_test/esp8266.cpp @@ -0,0 +1,16 @@ +#include + +static_assert(ARDUINOJSON_USE_LONG_LONG == 1, "ARDUINOJSON_USE_LONG_LONG"); + +static_assert(ARDUINOJSON_SLOT_OFFSET_SIZE == 2, + "ARDUINOJSON_SLOT_OFFSET_SIZE"); + +static_assert(ARDUINOJSON_LITTLE_ENDIAN == 1, "ARDUINOJSON_LITTLE_ENDIAN"); + +static_assert(ARDUINOJSON_USE_DOUBLE == 1, "ARDUINOJSON_USE_DOUBLE"); + +static_assert(sizeof(ArduinoJson::detail::VariantSlot) == 16, + "sizeof(VariantSlot)"); + +void setup() {} +void loop() {} diff --git a/libraries/ArduinoJson/extras/conf_test/x64.cpp b/libraries/ArduinoJson/extras/conf_test/x64.cpp new file mode 100644 index 0000000..97838e3 --- /dev/null +++ b/libraries/ArduinoJson/extras/conf_test/x64.cpp @@ -0,0 +1,15 @@ +#include + +static_assert(ARDUINOJSON_USE_LONG_LONG == 1, "ARDUINOJSON_USE_LONG_LONG"); + +static_assert(ARDUINOJSON_SLOT_OFFSET_SIZE == 4, + "ARDUINOJSON_SLOT_OFFSET_SIZE"); + +static_assert(ARDUINOJSON_LITTLE_ENDIAN == 1, "ARDUINOJSON_LITTLE_ENDIAN"); + +static_assert(ARDUINOJSON_USE_DOUBLE == 1, "ARDUINOJSON_USE_DOUBLE"); + +static_assert(sizeof(ArduinoJson::detail::VariantSlot) == 32, + "sizeof(VariantSlot)"); + +int main() {} diff --git a/libraries/ArduinoJson/extras/conf_test/x86.cpp b/libraries/ArduinoJson/extras/conf_test/x86.cpp new file mode 100644 index 0000000..f3dab30 --- /dev/null +++ b/libraries/ArduinoJson/extras/conf_test/x86.cpp @@ -0,0 +1,15 @@ +#include + +static_assert(ARDUINOJSON_USE_LONG_LONG == 1, "ARDUINOJSON_USE_LONG_LONG"); + +static_assert(ARDUINOJSON_SLOT_OFFSET_SIZE == 2, + "ARDUINOJSON_SLOT_OFFSET_SIZE"); + +static_assert(ARDUINOJSON_LITTLE_ENDIAN == 1, "ARDUINOJSON_LITTLE_ENDIAN"); + +static_assert(ARDUINOJSON_USE_DOUBLE == 1, "ARDUINOJSON_USE_DOUBLE"); + +static_assert(sizeof(ArduinoJson::detail::VariantSlot) == 16, + "sizeof(VariantSlot)"); + +int main() {} diff --git a/libraries/ArduinoJson/extras/fuzzing/CMakeLists.txt b/libraries/ArduinoJson/extras/fuzzing/CMakeLists.txt new file mode 100644 index 0000000..1d439f4 --- /dev/null +++ b/libraries/ArduinoJson/extras/fuzzing/CMakeLists.txt @@ -0,0 +1,58 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2023, Benoit BLANCHON +# MIT License + +set(CMAKE_CXX_STANDARD 11) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +if(MSVC) + add_compile_options(-D_CRT_SECURE_NO_WARNINGS) +endif() + +add_executable(msgpack_reproducer + msgpack_fuzzer.cpp + reproducer.cpp +) +target_link_libraries(msgpack_reproducer + ArduinoJson +) + +add_executable(json_reproducer + json_fuzzer.cpp + reproducer.cpp +) +target_link_libraries(json_reproducer + ArduinoJson +) + +macro(add_fuzzer name) + set(FUZZER "${name}_fuzzer") + set(CORPUS_DIR "${CMAKE_CURRENT_SOURCE_DIR}/${name}_corpus") + set(SEED_CORPUS_DIR "${CMAKE_CURRENT_SOURCE_DIR}/${name}_seed_corpus") + add_executable("${FUZZER}" + "${name}_fuzzer.cpp" + ) + target_link_libraries("${FUZZER}" + ArduinoJson + ) + set_target_properties("${FUZZER}" + PROPERTIES + COMPILE_FLAGS "-fprofile-instr-generate -fcoverage-mapping -fsanitize=fuzzer -fno-sanitize-recover=all" + LINK_FLAGS "-fprofile-instr-generate -fcoverage-mapping -fsanitize=fuzzer -fno-sanitize-recover=all" + ) + + add_test( + NAME "${FUZZER}" + COMMAND "${FUZZER}" "${CORPUS_DIR}" "${SEED_CORPUS_DIR}" -max_total_time=5 -timeout=1 + ) + + set_tests_properties("${FUZZER}" + PROPERTIES + LABELS "Fuzzing" + ) +endmacro() + +if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang" AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 6) + add_fuzzer(json) + add_fuzzer(msgpack) +endif() diff --git a/libraries/ArduinoJson/extras/fuzzing/Makefile b/libraries/ArduinoJson/extras/fuzzing/Makefile new file mode 100644 index 0000000..81fc412 --- /dev/null +++ b/libraries/ArduinoJson/extras/fuzzing/Makefile @@ -0,0 +1,22 @@ +# CAUTION: this file is invoked by https://github.com/google/oss-fuzz + +CXXFLAGS += -I../../src -DARDUINOJSON_DEBUG=1 -std=c++11 + +all: \ + $(OUT)/json_fuzzer \ + $(OUT)/json_fuzzer_seed_corpus.zip \ + $(OUT)/json_fuzzer.options \ + $(OUT)/msgpack_fuzzer \ + $(OUT)/msgpack_fuzzer_seed_corpus.zip \ + $(OUT)/msgpack_fuzzer.options + +$(OUT)/%_fuzzer: %_fuzzer.cpp $(shell find ../../src -type f) + $(CXX) $(CXXFLAGS) $< -o$@ $(LIB_FUZZING_ENGINE) + +$(OUT)/%_fuzzer_seed_corpus.zip: %_seed_corpus/* + zip -j $@ $? + +$(OUT)/%_fuzzer.options: + @echo "[libfuzzer]" > $@ + @echo "max_len = 256" >> $@ + @echo "timeout = 10" >> $@ diff --git a/libraries/ArduinoJson/extras/fuzzing/json_fuzzer.cpp b/libraries/ArduinoJson/extras/fuzzing/json_fuzzer.cpp new file mode 100644 index 0000000..043cd42 --- /dev/null +++ b/libraries/ArduinoJson/extras/fuzzing/json_fuzzer.cpp @@ -0,0 +1,11 @@ +#include + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + DynamicJsonDocument doc(4096); + DeserializationError error = deserializeJson(doc, data, size); + if (!error) { + std::string json; + serializeJson(doc, json); + } + return 0; +} diff --git a/libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/Comments.json b/libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/Comments.json new file mode 100644 index 0000000..bcc4cec --- /dev/null +++ b/libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/Comments.json @@ -0,0 +1,10 @@ +//comment +/*comment*/ +[ //comment +/*comment*/"comment"/*comment*/,//comment +/*comment*/{//comment +/* comment*/"key"//comment +: //comment +"value"//comment +}/*comment*/ +]//comment \ No newline at end of file diff --git a/libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/EmptyArray.json b/libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/EmptyArray.json new file mode 100644 index 0000000..0637a08 --- /dev/null +++ b/libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/EmptyArray.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/EmptyObject.json b/libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/EmptyObject.json new file mode 100644 index 0000000..9e26dfe --- /dev/null +++ b/libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/EmptyObject.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/ExcessiveNesting.json b/libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/ExcessiveNesting.json new file mode 100644 index 0000000..9285019 --- /dev/null +++ b/libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/ExcessiveNesting.json @@ -0,0 +1 @@ +[1,[2,[3,[4,[5,[6,[7,[8,[9,[10,[11,[12,[13,[14,[15,[16,[17,[18,[19,[20,[21,[22,[23,[24,[25,[26,[27,[28,[29,[30,[31,[32,[33,[34,[35,[36,[37,[38,[39,[40,[41,[42,[43,[44,[45,[46,[47,[48,[49,[50,[51,[52,[53,[54,[55,[56,[57,[58,[59,[60,[61,[62,[63,[64,[65,[66,[67,[68,[69,[70,[71,[72,[73,[74,[75,[76,[77,[78,[79,[80,[81,[82,[83,[84,[85,[86,[87,[88,[89,[90,[91,[92,[93,[94,[95,[96,[97,[98,[99,[100,[101,[102,[103,[104,[105,[106,[107,[108,[109,[110,[111,[112,[113,[114,[115,[116,[117,[118,[119,[120]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]] \ No newline at end of file diff --git a/libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/IntegerOverflow.json b/libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/IntegerOverflow.json new file mode 100644 index 0000000..3a33cb8 --- /dev/null +++ b/libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/IntegerOverflow.json @@ -0,0 +1 @@ +9720730739393920739 diff --git a/libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/Numbers.json b/libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/Numbers.json new file mode 100644 index 0000000..f6b9419 --- /dev/null +++ b/libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/Numbers.json @@ -0,0 +1,24 @@ +[ + 123, + -123, + 123.456, + -123.456, + 12e34, + 12e-34, + 12e+34, + 12E34, + 12E-34, + 12E+34, + 12.34e56, + 12.34e-56, + 12.34e+56, + 12.34E56, + 12.34E-56, + 12.34E+56, + NaN, + -NaN, + +NaN, + Infinity, + +Infinity, + -Infinity +] \ No newline at end of file diff --git a/libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/OpenWeatherMap.json b/libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/OpenWeatherMap.json new file mode 100644 index 0000000..27d6baf --- /dev/null +++ b/libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/OpenWeatherMap.json @@ -0,0 +1,53 @@ +{ + "coord": { + "lon": -0.13, + "lat": 51.51 + }, + "weather": [ + { + "id": 301, + "main": "Drizzle", + "description": "drizzle", + "icon": "09n" + }, + { + "id": 701, + "main": "Mist", + "description": "mist", + "icon": "50n" + }, + { + "id": 741, + "main": "Fog", + "description": "fog", + "icon": "50n" + } + ], + "base": "stations", + "main": { + "temp": 281.87, + "pressure": 1032, + "humidity": 100, + "temp_min": 281.15, + "temp_max": 283.15 + }, + "visibility": 2900, + "wind": { + "speed": 1.5 + }, + "clouds": { + "all": 90 + }, + "dt": 1483820400, + "sys": { + "type": 1, + "id": 5091, + "message": 0.0226, + "country": "GB", + "sunrise": 1483776245, + "sunset": 1483805443 + }, + "id": 2643743, + "name": "London", + "cod": 200 +} diff --git a/libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/Strings.json b/libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/Strings.json new file mode 100644 index 0000000..3ffa235 --- /dev/null +++ b/libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/Strings.json @@ -0,0 +1,8 @@ +[ + "hello", + 'hello', + hello, + {"hello":"world"}, + {'hello':'world'}, + {hello:world} +] \ No newline at end of file diff --git a/libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/WeatherUnderground.json b/libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/WeatherUnderground.json new file mode 100644 index 0000000..d53ce00 --- /dev/null +++ b/libraries/ArduinoJson/extras/fuzzing/json_seed_corpus/WeatherUnderground.json @@ -0,0 +1,90 @@ +{ + "response": { + "version": "0.1", + "termsofService": "http://www.wunderground.com/weather/api/d/terms.html", + "features": { + "conditions": 1 + } + }, + "current_observation": { + "image": { + "url": "http://icons-ak.wxug.com/graphics/wu2/logo_130x80.png", + "title": "Weather Underground", + "link": "http://www.wunderground.com" + }, + "display_location": { + "full": "San Francisco, CA", + "city": "San Francisco", + "state": "CA", + "state_name": "California", + "country": "US", + "country_iso3166": "US", + "zip": "94101", + "latitude": "37.77500916", + "longitude": "-122.41825867", + "elevation": "47.00000000" + }, + "observation_location": { + "full": "SOMA - Near Van Ness, San Francisco, California", + "city": "SOMA - Near Van Ness, San Francisco", + "state": "California", + "country": "US", + "country_iso3166": "US", + "latitude": "37.773285", + "longitude": "-122.417725", + "elevation": "49 ft" + }, + "estimated": {}, + "station_id": "KCASANFR58", + "observation_time": "Last Updated on June 27, 5:27 PM PDT", + "observation_time_rfc822": "Wed, 27 Jun 2012 17:27:13 -0700", + "observation_epoch": "1340843233", + "local_time_rfc822": "Wed, 27 Jun 2012 17:27:14 -0700", + "local_epoch": "1340843234", + "local_tz_short": "PDT", + "local_tz_long": "America/Los_Angeles", + "local_tz_offset": "-0700", + "weather": "Partly Cloudy", + "temperature_string": "66.3 F (19.1 C)", + "temp_f": 66.3, + "temp_c": 19.1, + "relative_humidity": "65%", + "wind_string": "From the NNW at 22.0 MPH Gusting to 28.0 MPH", + "wind_dir": "NNW", + "wind_degrees": 346, + "wind_mph": 22, + "wind_gust_mph": "28.0", + "wind_kph": 35.4, + "wind_gust_kph": "45.1", + "pressure_mb": "1013", + "pressure_in": "29.93", + "pressure_trend": "+", + "dewpoint_string": "54 F (12 C)", + "dewpoint_f": 54, + "dewpoint_c": 12, + "heat_index_string": "NA", + "heat_index_f": "NA", + "heat_index_c": "NA", + "windchill_string": "NA", + "windchill_f": "NA", + "windchill_c": "NA", + "feelslike_string": "66.3 F (19.1 C)", + "feelslike_f": "66.3", + "feelslike_c": "19.1", + "visibility_mi": "10.0", + "visibility_km": "16.1", + "solarradiation": "", + "UV": "5", + "precip_1hr_string": "0.00 in ( 0 mm)", + "precip_1hr_in": "0.00", + "precip_1hr_metric": " 0", + "precip_today_string": "0.00 in (0 mm)", + "precip_today_in": "0.00", + "precip_today_metric": "0", + "icon": "partlycloudy", + "icon_url": "http://icons-ak.wxug.com/i/c/k/partlycloudy.gif", + "forecast_url": "http://www.wunderground.com/US/CA/San_Francisco.html", + "history_url": "http://www.wunderground.com/history/airport/KCASANFR58/2012/6/27/DailyHistory.html", + "ob_url": "http://www.wunderground.com/cgi-bin/findweather/getForecast?query=37.773285,-122.417725" + } +} diff --git a/libraries/ArduinoJson/extras/fuzzing/msgpack_fuzzer.cpp b/libraries/ArduinoJson/extras/fuzzing/msgpack_fuzzer.cpp new file mode 100644 index 0000000..b6ab141 --- /dev/null +++ b/libraries/ArduinoJson/extras/fuzzing/msgpack_fuzzer.cpp @@ -0,0 +1,11 @@ +#include + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + DynamicJsonDocument doc(4096); + DeserializationError error = deserializeMsgPack(doc, data, size); + if (!error) { + std::string json; + serializeMsgPack(doc, json); + } + return 0; +} diff --git a/libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/array16 b/libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/array16 new file mode 100644 index 0000000000000000000000000000000000000000..714ba99e70cbed2056b4e4b04c86bb1a2ff7311b GIT binary patch literal 15 Wcmcb^z_c_YH76&3X?cE8P6_}q=LTf} literal 0 HcmV?d00001 diff --git a/libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/array32 b/libraries/ArduinoJson/extras/fuzzing/msgpack_seed_corpus/array32 new file mode 100644 index 0000000000000000000000000000000000000000..6e3ed7b1b81742fbb90a4135004b55a9a45a5769 GIT binary patch literal 15 Vcmcc1z`($C3P>=Va`5 // size_t +#include // fopen et al. +#include // exit +#include +#include + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size); + +std::vector read(const char* path) { + FILE* f = fopen(path, "rb"); + if (!f) { + std::cerr << "Failed to open " << path << std::endl; + exit(1); + } + + fseek(f, 0, SEEK_END); + size_t size = static_cast(ftell(f)); + fseek(f, 0, SEEK_SET); + + std::vector buffer(size); + if (fread(buffer.data(), 1, size, f) != size) { + fclose(f); + std::cerr << "Failed to read " << path << std::endl; + exit(1); + } + + fclose(f); + return buffer; +} + +int main(int argc, const char* argv[]) { + if (argc < 2) { + std::cerr << "Usage: msgpack_fuzzer files" << std::endl; + return 1; + } + + for (int i = 1; i < argc; i++) { + std::cout << "Loading " << argv[i] << std::endl; + std::vector buffer = read(argv[i]); + LLVMFuzzerTestOneInput(buffer.data(), buffer.size()); + } + return 0; +} diff --git a/libraries/ArduinoJson/extras/particle/project.properties b/libraries/ArduinoJson/extras/particle/project.properties new file mode 100644 index 0000000..d39555a --- /dev/null +++ b/libraries/ArduinoJson/extras/particle/project.properties @@ -0,0 +1 @@ +name=ArduinoJsonCI diff --git a/libraries/ArduinoJson/extras/particle/src/smocktest.ino b/libraries/ArduinoJson/extras/particle/src/smocktest.ino new file mode 100644 index 0000000..ca17189 --- /dev/null +++ b/libraries/ArduinoJson/extras/particle/src/smocktest.ino @@ -0,0 +1,5 @@ +#include "ArduinoJson.h" + +void setup() {} + +void loop() {} diff --git a/libraries/ArduinoJson/extras/scripts/build-arduino-package.sh b/libraries/ArduinoJson/extras/scripts/build-arduino-package.sh new file mode 100644 index 0000000..09f6efb --- /dev/null +++ b/libraries/ArduinoJson/extras/scripts/build-arduino-package.sh @@ -0,0 +1,23 @@ +#!/bin/bash + +set -eu + +INPUT=$1 +OUTPUT=$2 + +cd "$INPUT" + +# remove existing file +rm -f "$OUTPUT" + +# create zip +7z a "$OUTPUT" \ + -xr!.vs \ + CHANGELOG.md \ + examples \ + src \ + keywords.txt \ + library.properties \ + LICENSE.txt \ + README.md \ + ArduinoJson.h diff --git a/libraries/ArduinoJson/extras/scripts/build-single-header.sh b/libraries/ArduinoJson/extras/scripts/build-single-header.sh new file mode 100644 index 0000000..00292e3 --- /dev/null +++ b/libraries/ArduinoJson/extras/scripts/build-single-header.sh @@ -0,0 +1,65 @@ +#!/bin/bash + +set -e + +RE_RELATIVE_INCLUDE='^#[[:space:]]*include[[:space:]]*"(.*)"' +RE_ABSOLUTE_INCLUDE='^#[[:space:]]*include[[:space:]]*<(ArduinoJson/.*)>' +RE_SYSTEM_INCLUDE='^#[[:space:]]*include[[:space:]]*<(.*)>' +RE_EMPTY='^(#[[:space:]]*pragma[[:space:]]+once)?[[:space:]]*(//.*)?$' +SRC_DIRECTORY="$(realpath "$(dirname $0)/../../src")" + + +declare -A INCLUDED + +process() +{ + local PARENT=$1 + local FOLDER=$(dirname $1) + local SHOW_COMMENT=$2 + while IFS= read -r LINE; do + if [[ $LINE =~ $RE_ABSOLUTE_INCLUDE ]]; then + local CHILD=${BASH_REMATCH[1]} + local CHILD_PATH + CHILD_PATH=$(realpath "$SRC_DIRECTORY/$CHILD") + echo "$PARENT -> $CHILD" >&2 + if [[ ! ${INCLUDED[$CHILD_PATH]} ]]; then + INCLUDED[$CHILD_PATH]=true + process "$CHILD" false + fi + elif [[ $LINE =~ $RE_RELATIVE_INCLUDE ]]; then + local CHILD=${BASH_REMATCH[1]} + pushd "$FOLDER" > /dev/null + local CHILD_PATH + CHILD_PATH=$(realpath "$CHILD") + echo "$PARENT -> $CHILD" >&2 + if [[ ! ${INCLUDED[$CHILD_PATH]} ]]; then + INCLUDED[$CHILD_PATH]=true + process "$CHILD" false + fi + popd > /dev/null + elif [[ $LINE =~ $RE_SYSTEM_INCLUDE ]]; then + local CHILD=${BASH_REMATCH[1]} + echo "$PARENT -> <$CHILD>" >&2 + if [[ ! ${INCLUDED[$CHILD]} ]]; then + echo "#include <$CHILD>" + INCLUDED[$CHILD]=true + fi + elif [[ "${SHOW_COMMENT}" = "true" ]] ; then + echo "$LINE" + elif [[ ! $LINE =~ $RE_EMPTY ]]; then + echo "$LINE" + fi + done < $PARENT +} + +simplify_namespaces() { + perl -p0i -e 's|ARDUINOJSON_END_PUBLIC_NAMESPACE\r?\nARDUINOJSON_BEGIN_PUBLIC_NAMESPACE\r?\n||igs' "$1" + perl -p0i -e 's|ARDUINOJSON_END_PRIVATE_NAMESPACE\r?\nARDUINOJSON_BEGIN_PRIVATE_NAMESPACE\r?\n||igs' "$1" + rm -f "$1.bak" +} + +INCLUDED=() +INPUT=$1 +OUTPUT=$2 +process "$INPUT" true > "$OUTPUT" +simplify_namespaces "$OUTPUT" diff --git a/libraries/ArduinoJson/extras/scripts/get-release-body.sh b/libraries/ArduinoJson/extras/scripts/get-release-body.sh new file mode 100644 index 0000000..7c842c2 --- /dev/null +++ b/libraries/ArduinoJson/extras/scripts/get-release-body.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +set -eu + +TAG="$1" +CHANGELOG="$2" + +cat << END +## Changes + +$(awk '/\* /{ FOUND=1 } /^[[:space:]]*$/ { if(FOUND) exit } { if(FOUND) print }' "$CHANGELOG") + +[View version history](https://github.com/bblanchon/ArduinoJson/blob/$TAG/CHANGELOG.md) +END diff --git a/libraries/ArduinoJson/extras/scripts/get-release-page.sh b/libraries/ArduinoJson/extras/scripts/get-release-page.sh new file mode 100644 index 0000000..2acb8d8 --- /dev/null +++ b/libraries/ArduinoJson/extras/scripts/get-release-page.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +set -eu + +VERSION="$1" +CHANGELOG="$2" +FRONTMATTER="$3" + +cat << END +--- +branch: v6 +version: $VERSION +date: '$(date +'%Y-%m-%d')' +$(cat "$FRONTMATTER") +--- + +$(awk '/\* /{ FOUND=1; print; next } { if (FOUND) exit}' "$CHANGELOG") +END diff --git a/libraries/ArduinoJson/extras/scripts/publish-particle-library.sh b/libraries/ArduinoJson/extras/scripts/publish-particle-library.sh new file mode 100644 index 0000000..3ee7f91 --- /dev/null +++ b/libraries/ArduinoJson/extras/scripts/publish-particle-library.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +set -eu + +SOURCE_DIR="$(dirname "$0")/../.." +WORK_DIR=$(mktemp -d) +trap 'rm -rf "$WORK_DIR"' EXIT + +cp "$SOURCE_DIR/README.md" "$WORK_DIR/README.md" +cp "$SOURCE_DIR/CHANGELOG.md" "$WORK_DIR/CHANGELOG.md" +cp "$SOURCE_DIR/library.properties" "$WORK_DIR/library.properties" +cp "$SOURCE_DIR/LICENSE.txt" "$WORK_DIR/LICENSE.txt" +cp -r "$SOURCE_DIR/src" "$WORK_DIR/" +cp -r "$SOURCE_DIR/examples" "$WORK_DIR/" + +cd "$WORK_DIR" +particle library upload -v +particle library publish -v diff --git a/libraries/ArduinoJson/extras/scripts/publish.sh b/libraries/ArduinoJson/extras/scripts/publish.sh new file mode 100644 index 0000000..a562a24 --- /dev/null +++ b/libraries/ArduinoJson/extras/scripts/publish.sh @@ -0,0 +1,78 @@ +#!/usr/bin/env bash + +set -eu + +which awk sed jq 7z curl perl >/dev/null + +cd "$(dirname "$0")/../.." + +if ! git diff --quiet --exit-code; then + echo "Repository contains uncommitted changes" + exit +fi + +VERSION="$1" +DATE=$(date +%F) +TAG="v$VERSION" +VERSION_REGEX='[0-9]+\.[0-9]+\.[0-9]+(-[a-z0-9]+)?' + +update_version_in_source () { + IFS=".-" read MAJOR MINOR REVISION EXTRA < <(echo "$VERSION") + UNDERLINE=$(printf -- '-%.0s' $(seq 1 ${#TAG})) + + sed -i~ -bE "1,20{s/$VERSION_REGEX/$VERSION/g}" README.md + rm README.md~ + + sed -i~ -bE "4s/HEAD/$TAG ($DATE)/; 5s/-+/$UNDERLINE/" CHANGELOG.md + rm CHANGELOG.md~ + + sed -i~ -bE "s/(project\\s*\\(ArduinoJson\\s+VERSION\\s+).*?\\)/\\1$MAJOR.$MINOR.$REVISION)/" CMakeLists.txt + rm CMakeLists.txt~ + + sed -i~ -bE "s/\"version\":.*$/\"version\": \"$VERSION\",/" library.json + rm library.json~ + + sed -i~ -bE "s/version=.*$/version=$VERSION/" library.properties + rm library.properties~ + + sed -i~ -bE "s/version: .*$/version: $VERSION.{build}/" appveyor.yml + rm appveyor.yml~ + + sed -i~ -bE "s/^version: .*$/version: \"$VERSION\"/" idf_component.yml + rm idf_component.yml~ + + sed -i~ -bE \ + -e "s/ARDUINOJSON_VERSION .*$/ARDUINOJSON_VERSION \"$VERSION\"/" \ + -e "s/ARDUINOJSON_VERSION_MAJOR .*$/ARDUINOJSON_VERSION_MAJOR $MAJOR/" \ + -e "s/ARDUINOJSON_VERSION_MINOR .*$/ARDUINOJSON_VERSION_MINOR $MINOR/" \ + -e "s/ARDUINOJSON_VERSION_REVISION .*$/ARDUINOJSON_VERSION_REVISION $REVISION/" \ + src/ArduinoJson/version.hpp + rm src/ArduinoJson/version.hpp*~ +} + +commit_new_version () { + git add src/ArduinoJson/version.hpp README.md CHANGELOG.md library.json library.properties appveyor.yml CMakeLists.txt idf_component.yml + git commit -m "Set version to $VERSION" +} + +add_tag () { + CHANGES=$(awk '/\* /{ FOUND=1; print; next } { if (FOUND) exit}' CHANGELOG.md) + git tag -m "ArduinoJson $VERSION"$'\n'"$CHANGES" "$TAG" +} + +push () { + git push --follow-tags +} + +update_version_in_source +commit_new_version +add_tag +push + +extras/scripts/build-arduino-package.sh . "../ArduinoJson-$TAG.zip" +extras/scripts/build-single-header.sh "src/ArduinoJson.h" "../ArduinoJson-$TAG.h" +extras/scripts/build-single-header.sh "src/ArduinoJson.hpp" "../ArduinoJson-$TAG.hpp" +extras/scripts/wandbox/publish.sh "../ArduinoJson-$TAG.h" > "../ArduinoJson-$TAG-wandbox.txt" || echo "Wandbox failed!" +extras/scripts/get-release-page.sh "$VERSION" "CHANGELOG.md" "../ArduinoJson-$TAG-wandbox.txt" > "../ArduinoJson-$TAG.md" + +echo "You can now copy ../ArduinoJson-$TAG.md into arduinojson.org/collections/_versions/$VERSION.md" diff --git a/libraries/ArduinoJson/extras/scripts/wandbox/JsonGeneratorExample.cpp b/libraries/ArduinoJson/extras/scripts/wandbox/JsonGeneratorExample.cpp new file mode 100644 index 0000000..b35d185 --- /dev/null +++ b/libraries/ArduinoJson/extras/scripts/wandbox/JsonGeneratorExample.cpp @@ -0,0 +1,60 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License +// +// This example shows how to generate a JSON document with ArduinoJson. + +#include +#include "ArduinoJson.h" + +int main() { + // Allocate the JSON document + // + // Inside the brackets, 200 is the RAM allocated to this document. + // Don't forget to change this value to match your requirement. + // Use https://arduinojson.org/v6/assistant to compute the capacity. + StaticJsonDocument<200> doc; + + // StaticJsonObject allocates memory on the stack, it can be + // replaced by DynamicJsonDocument which allocates in the heap. + // + // DynamicJsonDocument doc(200); + + // StaticJsonObject allocates memory on the stack, it can be + // replaced by DynamicJsonDocument which allocates in the heap. + // + // DynamicJsonDocument doc(200); + + // Add values in the document + // + doc["sensor"] = "gps"; + doc["time"] = 1351824120; + + // Add an array. + // + JsonArray data = doc.createNestedArray("data"); + data.add(48.756080); + data.add(2.302038); + + // Generate the minified JSON and send it to STDOUT + // + serializeJson(doc, std::cout); + // The above line prints: + // {"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]} + + // Start a new line + std::cout << std::endl; + + // Generate the prettified JSON and send it to STDOUT + // + serializeJsonPretty(doc, std::cout); + // The above line prints: + // { + // "sensor": "gps", + // "time": 1351824120, + // "data": [ + // 48.756080, + // 2.302038 + // ] + // } +} diff --git a/libraries/ArduinoJson/extras/scripts/wandbox/JsonParserExample.cpp b/libraries/ArduinoJson/extras/scripts/wandbox/JsonParserExample.cpp new file mode 100644 index 0000000..396f98c --- /dev/null +++ b/libraries/ArduinoJson/extras/scripts/wandbox/JsonParserExample.cpp @@ -0,0 +1,59 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License +// +// This example shows how to deserialize a JSON document with ArduinoJson. + +#include +#include "ArduinoJson.h" + +int main() { + // Allocate the JSON document + // + // Inside the brackets, 200 is the capacity of the memory pool in bytes. + // Don't forget to change this value to match your JSON document. + // Use https://arduinojson.org/v6/assistant to compute the capacity. + StaticJsonDocument<300> doc; + + // StaticJsonDocument allocates memory on the stack, it can be + // replaced by DynamicJsonDocument which allocates in the heap. + // + // DynamicJsonDocument doc(200); + + // JSON input string. + // + // Using a char[], as shown here, enables the "zero-copy" mode. This mode uses + // the minimal amount of memory because the JsonDocument stores pointers to + // the input buffer. + // If you use another type of input, ArduinoJson must copy the strings from + // the input to the JsonDocument, so you need to increase the capacity of the + // JsonDocument. + char json[] = + "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}"; + + // Deserialize the JSON document + DeserializationError error = deserializeJson(doc, json); + + // Test if parsing succeeds. + if (error) { + std::cerr << "deserializeJson() failed: " << error.c_str() << std::endl; + return 1; + } + + // Fetch values. + // + // Most of the time, you can rely on the implicit casts. + // In other case, you can do doc["time"].as(); + const char* sensor = doc["sensor"]; + long time = doc["time"]; + double latitude = doc["data"][0]; + double longitude = doc["data"][1]; + + // Print values. + std::cout << sensor << std::endl; + std::cout << time << std::endl; + std::cout << latitude << std::endl; + std::cout << longitude << std::endl; + + return 0; +} diff --git a/libraries/ArduinoJson/extras/scripts/wandbox/MsgPackParserExample.cpp b/libraries/ArduinoJson/extras/scripts/wandbox/MsgPackParserExample.cpp new file mode 100644 index 0000000..763de84 --- /dev/null +++ b/libraries/ArduinoJson/extras/scripts/wandbox/MsgPackParserExample.cpp @@ -0,0 +1,68 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License +// +// This example shows how to generate a JSON document with ArduinoJson. + +#include +#include "ArduinoJson.h" + +int main() { + // Allocate the JSON document + // + // Inside the brackets, 300 is the size of the memory pool in bytes. + // Don't forget to change this value to match your JSON document. + // Use https://arduinojson.org/assistant to compute the capacity. + StaticJsonDocument<300> doc; + + // StaticJsonObject allocates memory on the stack, it can be + // replaced by DynamicJsonObject which allocates in the heap. + // + // DynamicJsonObject doc(200); + + // MessagePack input string. + // + // It's better to use a char[] as shown here. + // If you use a const char* or a String, ArduinoJson will + // have to make a copy of the input in the JsonBuffer. + uint8_t input[] = {131, 166, 115, 101, 110, 115, 111, 114, 163, 103, 112, 115, + 164, 116, 105, 109, 101, 206, 80, 147, 50, 248, 164, 100, + 97, 116, 97, 146, 203, 64, 72, 96, 199, 58, 188, 148, + 112, 203, 64, 2, 106, 146, 230, 33, 49, 169}; + // This MessagePack document contains: + // { + // "sensor": "gps", + // "time": 1351824120, + // "data": [48.75608, 2.302038] + // } + + // doc of the object tree. + // + // It's a reference to the JsonObject, the actual bytes are inside the + // JsonBuffer with all the other nodes of the object tree. + // Memory is freed when jsonBuffer goes out of scope. + DeserializationError error = deserializeMsgPack(doc, input); + + // Test if parsing succeeds. + if (error) { + std::cerr << "deserializeMsgPack() failed: " << error.c_str() << std::endl; + return 1; + } + + // Fetch values. + // + // Most of the time, you can rely on the implicit casts. + // In other case, you can do doc["time"].as(); + const char* sensor = doc["sensor"]; + long time = doc["time"]; + double latitude = doc["data"][0]; + double longitude = doc["data"][1]; + + // Print values. + std::cout << sensor << std::endl; + std::cout << time << std::endl; + std::cout << latitude << std::endl; + std::cout << longitude << std::endl; + + return 0; +} diff --git a/libraries/ArduinoJson/extras/scripts/wandbox/publish.sh b/libraries/ArduinoJson/extras/scripts/wandbox/publish.sh new file mode 100644 index 0000000..0900cb0 --- /dev/null +++ b/libraries/ArduinoJson/extras/scripts/wandbox/publish.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash + +set -eu + +ARDUINOJSON_H="$1" + +read_string() { + jq --slurp --raw-input '.' "$1" +} + +compile() { + FILE_PATH="$(dirname $0)/$1.cpp" + cat >parameters.json < +#include + +#include + +#if !ARDUINOJSON_ENABLE_STRING_VIEW +# error ARDUINOJSON_ENABLE_STRING_VIEW must be set to 1 +#endif + +TEST_CASE("string_view") { + StaticJsonDocument<256> doc; + JsonVariant variant = doc.to(); + + SECTION("deserializeJson()") { + auto err = deserializeJson(doc, std::string_view("123", 2)); + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.as() == 12); + } + + SECTION("JsonDocument::set()") { + doc.set(std::string_view("123", 2)); + REQUIRE(doc.as() == "12"); + } + + SECTION("JsonDocument::operator[]() const") { + doc["ab"] = "Yes"; + doc["abc"] = "No"; + REQUIRE(doc[std::string_view("abc", 2)] == "Yes"); + } + + SECTION("JsonDocument::operator[]()") { + doc[std::string_view("abc", 2)] = "Yes"; + REQUIRE(doc["ab"] == "Yes"); + } + + SECTION("JsonVariant::operator==()") { + variant.set("A"); + REQUIRE(variant == std::string_view("AX", 1)); + REQUIRE_FALSE(variant == std::string_view("BX", 1)); + } + + SECTION("JsonVariant::operator>()") { + variant.set("B"); + REQUIRE(variant > std::string_view("AX", 1)); + REQUIRE_FALSE(variant > std::string_view("CX", 1)); + } + + SECTION("JsonVariant::operator<()") { + variant.set("B"); + REQUIRE(variant < std::string_view("CX", 1)); + REQUIRE_FALSE(variant < std::string_view("AX", 1)); + } + + SECTION("String deduplication") { + doc.add(std::string_view("example one", 7)); + REQUIRE(doc.memoryUsage() == JSON_ARRAY_SIZE(1) + 8); + + doc.add(std::string_view("example two", 7)); + REQUIRE(doc.memoryUsage() == JSON_ARRAY_SIZE(2) + 8); + + doc.add(std::string_view("example\0tree", 12)); + REQUIRE(doc.memoryUsage() == JSON_ARRAY_SIZE(3) + 21); + + doc.add(std::string_view("example\0tree and a half", 12)); + REQUIRE(doc.memoryUsage() == JSON_ARRAY_SIZE(4) + 21); + } + + SECTION("as()") { + doc["s"] = "Hello World"; + doc["i"] = 42; + REQUIRE(doc["s"].as() == std::string_view("Hello World")); + REQUIRE(doc["i"].as() == std::string_view()); + } + + SECTION("is()") { + doc["s"] = "Hello World"; + doc["i"] = 42; + REQUIRE(doc["s"].is() == true); + REQUIRE(doc["i"].is() == false); + } + + SECTION("String containing NUL") { + doc.set(std::string("hello\0world", 11)); + REQUIRE(doc.as().size() == 11); + REQUIRE(doc.as() == std::string_view("hello\0world", 11)); + } +} + +using ArduinoJson::detail::adaptString; + +TEST_CASE("StringViewAdapter") { + std::string_view str("bravoXXX", 5); + auto adapter = adaptString(str); + + CHECK(stringCompare(adapter, adaptString("alpha", 5)) > 0); + CHECK(stringCompare(adapter, adaptString("bravo", 5)) == 0); + CHECK(stringCompare(adapter, adaptString("charlie", 7)) < 0); + + CHECK(adapter.size() == 5); +} diff --git a/libraries/ArduinoJson/extras/tests/Cpp20/CMakeLists.txt b/libraries/ArduinoJson/extras/tests/Cpp20/CMakeLists.txt new file mode 100644 index 0000000..e993e97 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Cpp20/CMakeLists.txt @@ -0,0 +1,29 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2023, Benoit BLANCHON +# MIT License + +if(MSVC_VERSION LESS 1910) + return() +endif() + +if(CMAKE_CXX_COMPILER_ID MATCHES "Clang" AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS 10) + return() +endif() + +if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS 10) + return() +endif() + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +add_executable(Cpp20Tests + smoke_test.cpp +) + +add_test(Cpp20 Cpp20Tests) + +set_tests_properties(Cpp20 + PROPERTIES + LABELS "Catch" +) diff --git a/libraries/ArduinoJson/extras/tests/Cpp20/smoke_test.cpp b/libraries/ArduinoJson/extras/tests/Cpp20/smoke_test.cpp new file mode 100644 index 0000000..dc41e87 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Cpp20/smoke_test.cpp @@ -0,0 +1,15 @@ +#include + +#include +#include + +TEST_CASE("C++20 smoke test") { + StaticJsonDocument<128> doc; + + deserializeJson(doc, "{\"hello\":\"world\"}"); + REQUIRE(doc["hello"] == "world"); + + std::string json; + serializeJson(doc, json); + REQUIRE(json == "{\"hello\":\"world\"}"); +} diff --git a/libraries/ArduinoJson/extras/tests/FailingBuilds/CMakeLists.txt b/libraries/ArduinoJson/extras/tests/FailingBuilds/CMakeLists.txt new file mode 100644 index 0000000..0464908 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/FailingBuilds/CMakeLists.txt @@ -0,0 +1,42 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2023, Benoit BLANCHON +# MIT License + +macro(build_should_fail target) + set_target_properties(${target} + PROPERTIES + EXCLUDE_FROM_ALL TRUE + EXCLUDE_FROM_DEFAULT_BUILD TRUE + ) + add_test( + NAME ${target} + COMMAND ${CMAKE_COMMAND} --build . --target ${target} --config $ + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + ) + set_tests_properties(${target} + PROPERTIES + WILL_FAIL TRUE + LABELS "WillFail;Catch" + ) +endmacro() + +add_executable(Issue978 Issue978.cpp) +build_should_fail(Issue978) + +add_executable(Issue1189 Issue1189.cpp) +build_should_fail(Issue1189) + +add_executable(read_long_long read_long_long.cpp) +build_should_fail(read_long_long) + +add_executable(write_long_long write_long_long.cpp) +build_should_fail(write_long_long) + +add_executable(delete_jsondocument delete_jsondocument.cpp) +build_should_fail(delete_jsondocument) + +add_executable(variant_as_char variant_as_char.cpp) +build_should_fail(variant_as_char) + +add_executable(assign_char assign_char.cpp) +build_should_fail(assign_char) diff --git a/libraries/ArduinoJson/extras/tests/FailingBuilds/Issue1189.cpp b/libraries/ArduinoJson/extras/tests/FailingBuilds/Issue1189.cpp new file mode 100644 index 0000000..40cb59f --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/FailingBuilds/Issue1189.cpp @@ -0,0 +1,13 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include + +// a function should not be able to get a JsonDocument by value +void f(JsonDocument) {} + +int main() { + DynamicJsonDocument doc(1024); + f(doc); +} diff --git a/libraries/ArduinoJson/extras/tests/FailingBuilds/Issue978.cpp b/libraries/ArduinoJson/extras/tests/FailingBuilds/Issue978.cpp new file mode 100644 index 0000000..d85aaa0 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/FailingBuilds/Issue978.cpp @@ -0,0 +1,13 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include + +struct Stream {}; + +int main() { + Stream* stream = 0; + DynamicJsonDocument doc(1024); + deserializeJson(doc, stream); +} diff --git a/libraries/ArduinoJson/extras/tests/FailingBuilds/assign_char.cpp b/libraries/ArduinoJson/extras/tests/FailingBuilds/assign_char.cpp new file mode 100644 index 0000000..b9d897f --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/FailingBuilds/assign_char.cpp @@ -0,0 +1,12 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include + +// See issue #1498 + +int main() { + DynamicJsonDocument doc(1024); + doc["dummy"] = 'A'; +} diff --git a/libraries/ArduinoJson/extras/tests/FailingBuilds/delete_jsondocument.cpp b/libraries/ArduinoJson/extras/tests/FailingBuilds/delete_jsondocument.cpp new file mode 100644 index 0000000..174b80a --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/FailingBuilds/delete_jsondocument.cpp @@ -0,0 +1,12 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include + +struct Stream {}; + +int main() { + JsonDocument* doc = new DynamicJsonDocument(42); + delete doc; +} diff --git a/libraries/ArduinoJson/extras/tests/FailingBuilds/read_long_long.cpp b/libraries/ArduinoJson/extras/tests/FailingBuilds/read_long_long.cpp new file mode 100644 index 0000000..6fe5992 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/FailingBuilds/read_long_long.cpp @@ -0,0 +1,16 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#define ARDUINOJSON_USE_LONG_LONG 0 +#include + +#if defined(__SIZEOF_LONG__) && __SIZEOF_LONG__ >= 8 +# error This test requires sizeof(long) < 8 +#endif + +ARDUINOJSON_ASSERT_INTEGER_TYPE_IS_SUPPORTED(long long) +int main() { + DynamicJsonDocument doc(1024); + doc["dummy"].as(); +} diff --git a/libraries/ArduinoJson/extras/tests/FailingBuilds/variant_as_char.cpp b/libraries/ArduinoJson/extras/tests/FailingBuilds/variant_as_char.cpp new file mode 100644 index 0000000..1a9e834 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/FailingBuilds/variant_as_char.cpp @@ -0,0 +1,12 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include + +// See issue #1498 + +int main() { + DynamicJsonDocument doc(1024); + doc["dummy"].as(); +} diff --git a/libraries/ArduinoJson/extras/tests/FailingBuilds/write_long_long.cpp b/libraries/ArduinoJson/extras/tests/FailingBuilds/write_long_long.cpp new file mode 100644 index 0000000..6ff8356 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/FailingBuilds/write_long_long.cpp @@ -0,0 +1,15 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#define ARDUINOJSON_USE_LONG_LONG 0 +#include + +#if defined(__SIZEOF_LONG__) && __SIZEOF_LONG__ >= 8 +# error This test requires sizeof(long) < 8 +#endif + +int main() { + DynamicJsonDocument doc(1024); + doc["dummy"] = static_cast(42); +} diff --git a/libraries/ArduinoJson/extras/tests/Helpers/Arduino.h b/libraries/ArduinoJson/extras/tests/Helpers/Arduino.h new file mode 100644 index 0000000..ef3640d --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Helpers/Arduino.h @@ -0,0 +1,13 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#pragma once + +#include "api/Print.h" +#include "api/Stream.h" +#include "api/String.h" +#include "avr/pgmspace.h" + +#define ARDUINO +#define ARDUINO_H_INCLUDED 1 diff --git a/libraries/ArduinoJson/extras/tests/Helpers/CustomReader.hpp b/libraries/ArduinoJson/extras/tests/Helpers/CustomReader.hpp new file mode 100644 index 0000000..66525a2 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Helpers/CustomReader.hpp @@ -0,0 +1,24 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#pragma once + +#include + +class CustomReader { + std::stringstream stream_; + + public: + CustomReader(const char* input) : stream_(input) {} + CustomReader(const CustomReader&) = delete; + + int read() { + return stream_.get(); + } + + size_t readBytes(char* buffer, size_t length) { + stream_.read(buffer, static_cast(length)); + return static_cast(stream_.gcount()); + } +}; diff --git a/libraries/ArduinoJson/extras/tests/Helpers/api/Print.h b/libraries/ArduinoJson/extras/tests/Helpers/api/Print.h new file mode 100644 index 0000000..d3c27cc --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Helpers/api/Print.h @@ -0,0 +1,33 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#pragma once + +#include +#include +#include + +class Print { + public: + virtual ~Print() {} + + virtual size_t write(uint8_t) = 0; + virtual size_t write(const uint8_t *buffer, size_t size) = 0; + + size_t write(const char *str) { + if (!str) + return 0; + return write(reinterpret_cast(str), strlen(str)); + } + + size_t write(const char *buffer, size_t size) { + return write(reinterpret_cast(buffer), size); + } +}; + +class Printable { + public: + virtual ~Printable() {} + virtual size_t printTo(Print &p) const = 0; +}; diff --git a/libraries/ArduinoJson/extras/tests/Helpers/api/Stream.h b/libraries/ArduinoJson/extras/tests/Helpers/api/Stream.h new file mode 100644 index 0000000..387940b --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Helpers/api/Stream.h @@ -0,0 +1,14 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#pragma once + +// Reproduces Arduino's Stream class +class Stream // : public Print +{ + public: + virtual ~Stream() {} + virtual int read() = 0; + virtual size_t readBytes(char *buffer, size_t length) = 0; +}; diff --git a/libraries/ArduinoJson/extras/tests/Helpers/api/String.h b/libraries/ArduinoJson/extras/tests/Helpers/api/String.h new file mode 100644 index 0000000..64c763f --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Helpers/api/String.h @@ -0,0 +1,69 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#pragma once + +#include + +// Reproduces Arduino's String class +class String { + public: + String() : _maxCapacity(1024) {} + explicit String(const char* s) : _str(s), _maxCapacity(1024) {} + + void limitCapacityTo(size_t maxCapacity) { + _maxCapacity = maxCapacity; + } + + unsigned char concat(const char* s) { + return concat(s, strlen(s)); + } + + size_t length() const { + return _str.size(); + } + + const char* c_str() const { + return _str.c_str(); + } + + bool operator==(const char* s) const { + return _str == s; + } + + String& operator=(const char* s) { + _str.assign(s); + return *this; + } + + char operator[](unsigned int index) const { + if (index >= _str.size()) + return 0; + return _str[index]; + } + + friend std::ostream& operator<<(std::ostream& lhs, const ::String& rhs) { + lhs << rhs._str; + return lhs; + } + + protected: + // This function is protected in most Arduino cores + unsigned char concat(const char* s, size_t n) { + if (_str.size() + n > _maxCapacity) + return 0; + _str.append(s, n); + return 1; + } + + private: + std::string _str; + size_t _maxCapacity; +}; + +class StringSumHelper : public ::String {}; + +inline bool operator==(const std::string& lhs, const ::String& rhs) { + return lhs == rhs.c_str(); +} diff --git a/libraries/ArduinoJson/extras/tests/Helpers/avr/pgmspace.h b/libraries/ArduinoJson/extras/tests/Helpers/avr/pgmspace.h new file mode 100644 index 0000000..378065d --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Helpers/avr/pgmspace.h @@ -0,0 +1,31 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#pragma once + +#include // uint8_t + +#define PROGMEM + +class __FlashStringHelper; + +inline const void* convertPtrToFlash(const void* s) { + return reinterpret_cast(s) + 42; +} + +inline const void* convertFlashToPtr(const void* s) { + return reinterpret_cast(s) - 42; +} + +#define PSTR(X) reinterpret_cast(convertPtrToFlash(X)) +#define F(X) reinterpret_cast(PSTR(X)) + +inline uint8_t pgm_read_byte(const void* p) { + return *reinterpret_cast(convertFlashToPtr(p)); +} + +#define ARDUINOJSON_DEFINE_PROGMEM_ARRAY(type, name, ...) \ + static type const ARDUINOJSON_CONCAT2(name, _progmem)[] = __VA_ARGS__; \ + static type const* name = reinterpret_cast( \ + convertPtrToFlash(ARDUINOJSON_CONCAT2(name, _progmem))); diff --git a/libraries/ArduinoJson/extras/tests/IntegrationTests/CMakeLists.txt b/libraries/ArduinoJson/extras/tests/IntegrationTests/CMakeLists.txt new file mode 100644 index 0000000..9ee858d --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/IntegrationTests/CMakeLists.txt @@ -0,0 +1,24 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2023, Benoit BLANCHON +# MIT License + +add_executable(IntegrationTests + gbathree.cpp + issue772.cpp + round_trip.cpp + openweathermap.cpp +) + +if(CMAKE_CXX_COMPILER_ID MATCHES "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 6) + target_compile_options(IntegrationTests + PUBLIC + -fsingle-precision-constant # issue 544 + ) +endif() + +add_test(IntegrationTests IntegrationTests) + +set_tests_properties(IntegrationTests + PROPERTIES + LABELS "Catch" +) diff --git a/libraries/ArduinoJson/extras/tests/IntegrationTests/gbathree.cpp b/libraries/ArduinoJson/extras/tests/IntegrationTests/gbathree.cpp new file mode 100644 index 0000000..34c4d0d --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/IntegrationTests/gbathree.cpp @@ -0,0 +1,210 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("Gbathree") { + DynamicJsonDocument doc(4096); + + DeserializationError error = deserializeJson( + doc, + "{\"protocol_name\":\"fluorescence\",\"repeats\":1,\"wait\":0," + "\"averages\":1,\"measurements\":3,\"meas2_light\":15,\"meas1_" + "baseline\":0,\"act_light\":20,\"pulsesize\":25,\"pulsedistance\":" + "10000,\"actintensity1\":50,\"actintensity2\":255,\"measintensity\":" + "255,\"calintensity\":255,\"pulses\":[50,50,50],\"act\":[2,1,2,2]," + "\"red\":[2,2,2,2],\"detectors\":[[34,34,34,34],[34,34,34,34],[34," + "34,34,34],[34,34,34,34]],\"alta\":[2,2,2,2],\"altb\":[2,2,2,2]," + "\"measlights\":[[15,15,15,15],[15,15,15,15],[15,15,15,15],[15,15," + "15,15]],\"measlights2\":[[15,15,15,15],[15,15,15,15],[15,15,15,15]," + "[15,15,15,15]],\"altc\":[2,2,2,2],\"altd\":[2,2,2,2]}"); + JsonObject root = doc.as(); + + SECTION("Success") { + REQUIRE(error == DeserializationError::Ok); + } + + SECTION("ProtocolName") { + REQUIRE("fluorescence" == root["protocol_name"]); + } + + SECTION("Repeats") { + REQUIRE(1 == root["repeats"]); + } + + SECTION("Wait") { + REQUIRE(0 == root["wait"]); + } + + SECTION("Measurements") { + REQUIRE(3 == root["measurements"]); + } + + SECTION("Meas2_Light") { + REQUIRE(15 == root["meas2_light"]); + } + + SECTION("Meas1_Baseline") { + REQUIRE(0 == root["meas1_baseline"]); + } + + SECTION("Act_Light") { + REQUIRE(20 == root["act_light"]); + } + + SECTION("Pulsesize") { + REQUIRE(25 == root["pulsesize"]); + } + + SECTION("Pulsedistance") { + REQUIRE(10000 == root["pulsedistance"]); + } + + SECTION("Actintensity1") { + REQUIRE(50 == root["actintensity1"]); + } + + SECTION("Actintensity2") { + REQUIRE(255 == root["actintensity2"]); + } + + SECTION("Measintensity") { + REQUIRE(255 == root["measintensity"]); + } + + SECTION("Calintensity") { + REQUIRE(255 == root["calintensity"]); + } + + SECTION("Pulses") { + // "pulses":[50,50,50] + + JsonArray array = root["pulses"]; + REQUIRE(array.isNull() == false); + + REQUIRE(3 == array.size()); + + for (size_t i = 0; i < 3; i++) { + REQUIRE(50 == array[i]); + } + } + + SECTION("Act") { + // "act":[2,1,2,2] + + JsonArray array = root["act"]; + REQUIRE(array.isNull() == false); + + REQUIRE(4 == array.size()); + REQUIRE(2 == array[0]); + REQUIRE(1 == array[1]); + REQUIRE(2 == array[2]); + REQUIRE(2 == array[3]); + } + + SECTION("Detectors") { + // "detectors":[[34,34,34,34],[34,34,34,34],[34,34,34,34],[34,34,34,34]] + + JsonArray array = root["detectors"]; + REQUIRE(array.isNull() == false); + REQUIRE(4 == array.size()); + + for (size_t i = 0; i < 4; i++) { + JsonArray nestedArray = array[i]; + REQUIRE(4 == nestedArray.size()); + + for (size_t j = 0; j < 4; j++) { + REQUIRE(34 == nestedArray[j]); + } + } + } + + SECTION("Alta") { + // alta:[2,2,2,2] + + JsonArray array = root["alta"]; + REQUIRE(array.isNull() == false); + + REQUIRE(4 == array.size()); + + for (size_t i = 0; i < 4; i++) { + REQUIRE(2 == array[i]); + } + } + + SECTION("Altb") { + // altb:[2,2,2,2] + + JsonArray array = root["altb"]; + REQUIRE(array.isNull() == false); + + REQUIRE(4 == array.size()); + + for (size_t i = 0; i < 4; i++) { + REQUIRE(2 == array[i]); + } + } + + SECTION("Measlights") { + // "measlights":[[15,15,15,15],[15,15,15,15],[15,15,15,15],[15,15,15,15]] + + JsonArray array = root["measlights"]; + REQUIRE(array.isNull() == false); + REQUIRE(4 == array.size()); + + for (size_t i = 0; i < 4; i++) { + JsonArray nestedArray = array[i]; + + REQUIRE(4 == nestedArray.size()); + + for (size_t j = 0; j < 4; j++) { + REQUIRE(15 == nestedArray[j]); + } + } + } + + SECTION("Measlights2") { + // "measlights2":[[15,15,15,15],[15,15,15,15],[15,15,15,15],[15,15,15,15]] + + JsonArray array = root["measlights2"]; + REQUIRE(array.isNull() == false); + REQUIRE(4 == array.size()); + + for (size_t i = 0; i < 4; i++) { + JsonArray nestedArray = array[i]; + REQUIRE(4 == nestedArray.size()); + + for (size_t j = 0; j < 4; j++) { + REQUIRE(15 == nestedArray[j]); + } + } + } + + SECTION("Altc") { + // altc:[2,2,2,2] + + JsonArray array = root["altc"]; + REQUIRE(array.isNull() == false); + + REQUIRE(4 == array.size()); + + for (size_t i = 0; i < 4; i++) { + REQUIRE(2 == array[i]); + } + } + + SECTION("Altd") { + // altd:[2,2,2,2] + + JsonArray array = root["altd"]; + REQUIRE(array.isNull() == false); + + REQUIRE(4 == array.size()); + + for (size_t i = 0; i < 4; i++) { + REQUIRE(2 == array[i]); + } + } +} diff --git a/libraries/ArduinoJson/extras/tests/IntegrationTests/issue772.cpp b/libraries/ArduinoJson/extras/tests/IntegrationTests/issue772.cpp new file mode 100644 index 0000000..dd85a08 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/IntegrationTests/issue772.cpp @@ -0,0 +1,28 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +// https://github.com/bblanchon/ArduinoJson/issues/772 + +TEST_CASE("Issue772") { + DynamicJsonDocument doc1(4096); + DynamicJsonDocument doc2(4096); + DeserializationError err; + std::string data = + "{\"state\":{\"reported\":{\"timestamp\":\"2018-07-02T09:40:12Z\"," + "\"mac\":\"2C3AE84FC076\",\"firmwareVersion\":\"v0.2.7-5-gf4d4d78\"," + "\"visibleLight\":261,\"infraRed\":255,\"ultraViolet\":0.02," + "\"Temperature\":26.63,\"Pressure\":101145.7,\"Humidity\":54.79883," + "\"Vbat\":4.171261,\"soilMoisture\":0,\"ActB\":0}}}"; + err = deserializeJson(doc1, data); + REQUIRE(err == DeserializationError::Ok); + + data = ""; + serializeMsgPack(doc1, data); + err = deserializeMsgPack(doc2, data); + + REQUIRE(err == DeserializationError::Ok); +} diff --git a/libraries/ArduinoJson/extras/tests/IntegrationTests/openweathermap.cpp b/libraries/ArduinoJson/extras/tests/IntegrationTests/openweathermap.cpp new file mode 100644 index 0000000..e91ac0a --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/IntegrationTests/openweathermap.cpp @@ -0,0 +1,68 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("OpenWeatherMap") { + // clang-format off + const char* input_json = "{\"cod\":\"200\",\"message\":0,\"cnt\":40,\"list\":[{\"dt\":1581498000,\"main\":{\"temp\":3.23,\"feels_like\":-3.63,\"temp_min\":3.23,\"temp_max\":4.62,\"pressure\":1014,\"sea_level\":1014,\"grnd_level\":1010,\"humidity\":58,\"temp_kf\":-1.39},\"weather\":[{\"id\":800,\"main\":\"Clear\",\"description\":\"clear sky\",\"icon\":\"01d\"}],\"clouds\":{\"all\":0},\"wind\":{\"speed\":6.19,\"deg\":266},\"sys\":{\"pod\":\"d\"},\"dt_txt\":\"2020-02-12 09:00:00\"},{\"dt\":1581508800,\"main\":{\"temp\":6.09,\"feels_like\":-1.07,\"temp_min\":6.09,\"temp_max\":7.13,\"pressure\":1015,\"sea_level\":1015,\"grnd_level\":1011,\"humidity\":48,\"temp_kf\":-1.04},\"weather\":[{\"id\":800,\"main\":\"Clear\",\"description\":\"clear sky\",\"icon\":\"01d\"}],\"clouds\":{\"all\":9},\"wind\":{\"speed\":6.64,\"deg\":268},\"sys\":{\"pod\":\"d\"},\"dt_txt\":\"2020-02-12 12:00:00\"},{\"dt\":1581519600,\"main\":{\"temp\":6.82,\"feels_like\":0.47,\"temp_min\":6.82,\"temp_max\":7.52,\"pressure\":1015,\"sea_level\":1015,\"grnd_level\":1011,\"humidity\":47,\"temp_kf\":-0.7},\"weather\":[{\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04d\"}],\"clouds\":{\"all\":97},\"wind\":{\"speed\":5.55,\"deg\":267},\"sys\":{\"pod\":\"d\"},\"dt_txt\":\"2020-02-12 15:00:00\"},{\"dt\":1581530400,\"main\":{\"temp\":5.76,\"feels_like\":1.84,\"temp_min\":5.76,\"temp_max\":6.11,\"pressure\":1015,\"sea_level\":1015,\"grnd_level\":1010,\"humidity\":57,\"temp_kf\":-0.35},\"weather\":[{\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04n\"}],\"clouds\":{\"all\":99},\"wind\":{\"speed\":2.35,\"deg\":232},\"sys\":{\"pod\":\"n\"},\"dt_txt\":\"2020-02-12 18:00:00\"},{\"dt\":1581541200,\"main\":{\"temp\":5.7,\"feels_like\":1.34,\"temp_min\":5.7,\"temp_max\":5.7,\"pressure\":1012,\"sea_level\":1012,\"grnd_level\":1008,\"humidity\":71,\"temp_kf\":0},\"weather\":[{\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04n\"}],\"clouds\":{\"all\":100},\"wind\":{\"speed\":3.57,\"deg\":198},\"sys\":{\"pod\":\"n\"},\"dt_txt\":\"2020-02-12 21:00:00\"},{\"dt\":1581552000,\"main\":{\"temp\":5.82,\"feels_like\":1.39,\"temp_min\":5.82,\"temp_max\":5.82,\"pressure\":1009,\"sea_level\":1009,\"grnd_level\":1004,\"humidity\":86,\"temp_kf\":0},\"weather\":[{\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10n\"}],\"clouds\":{\"all\":100},\"wind\":{\"speed\":4.35,\"deg\":169},\"rain\":{\"3h\":0.5},\"sys\":{\"pod\":\"n\"},\"dt_txt\":\"2020-02-13 00:00:00\"},{\"dt\":1581562800,\"main\":{\"temp\":5.9,\"feels_like\":-0.85,\"temp_min\":5.9,\"temp_max\":5.9,\"pressure\":1000,\"sea_level\":1000,\"grnd_level\":997,\"humidity\":86,\"temp_kf\":0},\"weather\":[{\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10n\"}],\"clouds\":{\"all\":100},\"wind\":{\"speed\":7.69,\"deg\":178},\"rain\":{\"3h\":1.75},\"sys\":{\"pod\":\"n\"},\"dt_txt\":\"2020-02-13 03:00:00\"},{\"dt\":1581573600,\"main\":{\"temp\":7.52,\"feels_like\":1.74,\"temp_min\":7.52,\"temp_max\":7.52,\"pressure\":993,\"sea_level\":993,\"grnd_level\":988,\"humidity\":88,\"temp_kf\":0},\"weather\":[{\"id\":501,\"main\":\"Rain\",\"description\":\"moderate rain\",\"icon\":\"10n\"}],\"clouds\":{\"all\":100},\"wind\":{\"speed\":6.84,\"deg\":184},\"rain\":{\"3h\":7.06},\"sys\":{\"pod\":\"n\"},\"dt_txt\":\"2020-02-13 06:00:00\"},{\"dt\":1581584400,\"main\":{\"temp\":7.23,\"feels_like\":0.81,\"temp_min\":7.23,\"temp_max\":7.23,\"pressure\":992,\"sea_level\":992,\"grnd_level\":988,\"humidity\":69,\"temp_kf\":0},\"weather\":[{\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10d\"}],\"clouds\":{\"all\":49},\"wind\":{\"speed\":6.77,\"deg\":239},\"rain\":{\"3h\":0.25},\"sys\":{\"pod\":\"d\"},\"dt_txt\":\"2020-02-13 09:00:00\"},{\"dt\":1581595200,\"main\":{\"temp\":7.67,\"feels_like\":2.81,\"temp_min\":7.67,\"temp_max\":7.67,\"pressure\":991,\"sea_level\":991,\"grnd_level\":987,\"humidity\":75,\"temp_kf\":0},\"weather\":[{\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10d\"}],\"clouds\":{\"all\":73},\"wind\":{\"speed\":4.93,\"deg\":235},\"rain\":{\"3h\":0.75},\"sys\":{\"pod\":\"d\"},\"dt_txt\":\"2020-02-13 12:00:00\"},{\"dt\":1581606000,\"main\":{\"temp\":8.83,\"feels_like\":3.23,\"temp_min\":8.83,\"temp_max\":8.83,\"pressure\":993,\"sea_level\":993,\"grnd_level\":990,\"humidity\":64,\"temp_kf\":0},\"weather\":[{\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10d\"}],\"clouds\":{\"all\":83},\"wind\":{\"speed\":5.7,\"deg\":293},\"rain\":{\"3h\":0.38},\"sys\":{\"pod\":\"d\"},\"dt_txt\":\"2020-02-13 15:00:00\"},{\"dt\":1581616800,\"main\":{\"temp\":7.42,\"feels_like\":1.77,\"temp_min\":7.42,\"temp_max\":7.42,\"pressure\":1000,\"sea_level\":1000,\"grnd_level\":996,\"humidity\":71,\"temp_kf\":0},\"weather\":[{\"id\":803,\"main\":\"Clouds\",\"description\":\"broken clouds\",\"icon\":\"04n\"}],\"clouds\":{\"all\":54},\"wind\":{\"speed\":5.81,\"deg\":307},\"sys\":{\"pod\":\"n\"},\"dt_txt\":\"2020-02-13 18:00:00\"},{\"dt\":1581627600,\"main\":{\"temp\":5.82,\"feels_like\":0.89,\"temp_min\":5.82,\"temp_max\":5.82,\"pressure\":1007,\"sea_level\":1007,\"grnd_level\":1003,\"humidity\":79,\"temp_kf\":0},\"weather\":[{\"id\":800,\"main\":\"Clear\",\"description\":\"clear sky\",\"icon\":\"01n\"}],\"clouds\":{\"all\":6},\"wind\":{\"speed\":4.76,\"deg\":300},\"sys\":{\"pod\":\"n\"},\"dt_txt\":\"2020-02-13 21:00:00\"},{\"dt\":1581638400,\"main\":{\"temp\":5.58,\"feels_like\":2.09,\"temp_min\":5.58,\"temp_max\":5.58,\"pressure\":1011,\"sea_level\":1011,\"grnd_level\":1007,\"humidity\":81,\"temp_kf\":0},\"weather\":[{\"id\":802,\"main\":\"Clouds\",\"description\":\"scattered clouds\",\"icon\":\"03n\"}],\"clouds\":{\"all\":47},\"wind\":{\"speed\":2.73,\"deg\":326},\"sys\":{\"pod\":\"n\"},\"dt_txt\":\"2020-02-14 00:00:00\"},{\"dt\":1581649200,\"main\":{\"temp\":4.27,\"feels_like\":1.72,\"temp_min\":4.27,\"temp_max\":4.27,\"pressure\":1014,\"sea_level\":1014,\"grnd_level\":1010,\"humidity\":85,\"temp_kf\":0},\"weather\":[{\"id\":803,\"main\":\"Clouds\",\"description\":\"broken clouds\",\"icon\":\"04n\"}],\"clouds\":{\"all\":69},\"wind\":{\"speed\":1.24,\"deg\":295},\"sys\":{\"pod\":\"n\"},\"dt_txt\":\"2020-02-14 03:00:00\"},{\"dt\":1581660000,\"main\":{\"temp\":3.91,\"feels_like\":1.54,\"temp_min\":3.91,\"temp_max\":3.91,\"pressure\":1016,\"sea_level\":1016,\"grnd_level\":1012,\"humidity\":87,\"temp_kf\":0},\"weather\":[{\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04n\"}],\"clouds\":{\"all\":85},\"wind\":{\"speed\":0.98,\"deg\":211},\"sys\":{\"pod\":\"n\"},\"dt_txt\":\"2020-02-14 06:00:00\"},{\"dt\":1581670800,\"main\":{\"temp\":4.77,\"feels_like\":0.74,\"temp_min\":4.77,\"temp_max\":4.77,\"pressure\":1017,\"sea_level\":1017,\"grnd_level\":1013,\"humidity\":78,\"temp_kf\":0},\"weather\":[{\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04d\"}],\"clouds\":{\"all\":100},\"wind\":{\"speed\":3.19,\"deg\":184},\"sys\":{\"pod\":\"d\"},\"dt_txt\":\"2020-02-14 09:00:00\"},{\"dt\":1581681600,\"main\":{\"temp\":9.03,\"feels_like\":4,\"temp_min\":9.03,\"temp_max\":9.03,\"pressure\":1016,\"sea_level\":1016,\"grnd_level\":1012,\"humidity\":73,\"temp_kf\":0},\"weather\":[{\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04d\"}],\"clouds\":{\"all\":100},\"wind\":{\"speed\":5.43,\"deg\":206},\"sys\":{\"pod\":\"d\"},\"dt_txt\":\"2020-02-14 12:00:00\"},{\"dt\":1581692400,\"main\":{\"temp\":9.86,\"feels_like\":4.22,\"temp_min\":9.86,\"temp_max\":9.86,\"pressure\":1014,\"sea_level\":1014,\"grnd_level\":1010,\"humidity\":74,\"temp_kf\":0},\"weather\":[{\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04d\"}],\"clouds\":{\"all\":100},\"wind\":{\"speed\":6.58,\"deg\":209},\"sys\":{\"pod\":\"d\"},\"dt_txt\":\"2020-02-14 15:00:00\"},{\"dt\":1581703200,\"main\":{\"temp\":9.48,\"feels_like\":4.8,\"temp_min\":9.48,\"temp_max\":9.48,\"pressure\":1013,\"sea_level\":1013,\"grnd_level\":1009,\"humidity\":83,\"temp_kf\":0},\"weather\":[{\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04n\"}],\"clouds\":{\"all\":100},\"wind\":{\"speed\":5.6,\"deg\":206},\"sys\":{\"pod\":\"n\"},\"dt_txt\":\"2020-02-14 18:00:00\"},{\"dt\":1581714000,\"main\":{\"temp\":10.03,\"feels_like\":6.48,\"temp_min\":10.03,\"temp_max\":10.03,\"pressure\":1013,\"sea_level\":1013,\"grnd_level\":1009,\"humidity\":93,\"temp_kf\":0},\"weather\":[{\"id\":501,\"main\":\"Rain\",\"description\":\"moderate rain\",\"icon\":\"10n\"}],\"clouds\":{\"all\":100},\"wind\":{\"speed\":4.75,\"deg\":226},\"rain\":{\"3h\":3.13},\"sys\":{\"pod\":\"n\"},\"dt_txt\":\"2020-02-14 21:00:00\"},{\"dt\":1581724800,\"main\":{\"temp\":9.48,\"feels_like\":6.25,\"temp_min\":9.48,\"temp_max\":9.48,\"pressure\":1013,\"sea_level\":1013,\"grnd_level\":1009,\"humidity\":89,\"temp_kf\":0},\"weather\":[{\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10n\"}],\"clouds\":{\"all\":100},\"wind\":{\"speed\":3.87,\"deg\":214},\"rain\":{\"3h\":2.38},\"sys\":{\"pod\":\"n\"},\"dt_txt\":\"2020-02-15 00:00:00\"},{\"dt\":1581735600,\"main\":{\"temp\":9.12,\"feels_like\":7.08,\"temp_min\":9.12,\"temp_max\":9.12,\"pressure\":1011,\"sea_level\":1011,\"grnd_level\":1007,\"humidity\":96,\"temp_kf\":0},\"weather\":[{\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10n\"}],\"clouds\":{\"all\":100},\"wind\":{\"speed\":2.43,\"deg\":194},\"rain\":{\"3h\":1},\"sys\":{\"pod\":\"n\"},\"dt_txt\":\"2020-02-15 03:00:00\"},{\"dt\":1581746400,\"main\":{\"temp\":10.32,\"feels_like\":6.71,\"temp_min\":10.32,\"temp_max\":10.32,\"pressure\":1009,\"sea_level\":1009,\"grnd_level\":1004,\"humidity\":95,\"temp_kf\":0},\"weather\":[{\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10n\"}],\"clouds\":{\"all\":100},\"wind\":{\"speed\":5.05,\"deg\":196},\"rain\":{\"3h\":1.75},\"sys\":{\"pod\":\"n\"},\"dt_txt\":\"2020-02-15 06:00:00\"},{\"dt\":1581757200,\"main\":{\"temp\":11.57,\"feels_like\":5.85,\"temp_min\":11.57,\"temp_max\":11.57,\"pressure\":1006,\"sea_level\":1006,\"grnd_level\":1002,\"humidity\":85,\"temp_kf\":0},\"weather\":[{\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10d\"}],\"clouds\":{\"all\":100},\"wind\":{\"speed\":7.91,\"deg\":205},\"rain\":{\"3h\":1.44},\"sys\":{\"pod\":\"d\"},\"dt_txt\":\"2020-02-15 09:00:00\"},{\"dt\":1581768000,\"main\":{\"temp\":12.25,\"feels_like\":4.46,\"temp_min\":12.25,\"temp_max\":12.25,\"pressure\":1003,\"sea_level\":1003,\"grnd_level\":998,\"humidity\":78,\"temp_kf\":0},\"weather\":[{\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10d\"}],\"clouds\":{\"all\":100},\"wind\":{\"speed\":10.65,\"deg\":201},\"rain\":{\"3h\":1.81},\"sys\":{\"pod\":\"d\"},\"dt_txt\":\"2020-02-15 12:00:00\"},{\"dt\":1581778800,\"main\":{\"temp\":12.19,\"feels_like\":3.17,\"temp_min\":12.19,\"temp_max\":12.19,\"pressure\":998,\"sea_level\":998,\"grnd_level\":994,\"humidity\":80,\"temp_kf\":0},\"weather\":[{\"id\":501,\"main\":\"Rain\",\"description\":\"moderate rain\",\"icon\":\"10d\"}],\"clouds\":{\"all\":100},\"wind\":{\"speed\":12.52,\"deg\":204},\"rain\":{\"3h\":3.5},\"sys\":{\"pod\":\"d\"},\"dt_txt\":\"2020-02-15 15:00:00\"},{\"dt\":1581789600,\"main\":{\"temp\":12.25,\"feels_like\":4.15,\"temp_min\":12.25,\"temp_max\":12.25,\"pressure\":996,\"sea_level\":996,\"grnd_level\":992,\"humidity\":83,\"temp_kf\":0},\"weather\":[{\"id\":501,\"main\":\"Rain\",\"description\":\"moderate rain\",\"icon\":\"10n\"}],\"clouds\":{\"all\":100},\"wind\":{\"speed\":11.42,\"deg\":215},\"rain\":{\"3h\":4.88},\"sys\":{\"pod\":\"n\"},\"dt_txt\":\"2020-02-15 18:00:00\"},{\"dt\":1581800400,\"main\":{\"temp\":12.64,\"feels_like\":5.85,\"temp_min\":12.64,\"temp_max\":12.64,\"pressure\":994,\"sea_level\":994,\"grnd_level\":990,\"humidity\":76,\"temp_kf\":0},\"weather\":[{\"id\":501,\"main\":\"Rain\",\"description\":\"moderate rain\",\"icon\":\"10n\"}],\"clouds\":{\"all\":100},\"wind\":{\"speed\":9.22,\"deg\":217},\"rain\":{\"3h\":6.88},\"sys\":{\"pod\":\"n\"},\"dt_txt\":\"2020-02-15 21:00:00\"},{\"dt\":1581811200,\"main\":{\"temp\":12.96,\"feels_like\":4.03,\"temp_min\":12.96,\"temp_max\":12.96,\"pressure\":988,\"sea_level\":988,\"grnd_level\":984,\"humidity\":83,\"temp_kf\":0},\"weather\":[{\"id\":501,\"main\":\"Rain\",\"description\":\"moderate rain\",\"icon\":\"10n\"}],\"clouds\":{\"all\":100},\"wind\":{\"speed\":12.88,\"deg\":211},\"rain\":{\"3h\":5.63},\"sys\":{\"pod\":\"n\"},\"dt_txt\":\"2020-02-16 00:00:00\"},{\"dt\":1581822000,\"main\":{\"temp\":13.13,\"feels_like\":5.17,\"temp_min\":13.13,\"temp_max\":13.13,\"pressure\":987,\"sea_level\":987,\"grnd_level\":982,\"humidity\":82,\"temp_kf\":0},\"weather\":[{\"id\":501,\"main\":\"Rain\",\"description\":\"moderate rain\",\"icon\":\"10n\"}],\"clouds\":{\"all\":100},\"wind\":{\"speed\":11.49,\"deg\":246},\"rain\":{\"3h\":7.25},\"sys\":{\"pod\":\"n\"},\"dt_txt\":\"2020-02-16 03:00:00\"},{\"dt\":1581832800,\"main\":{\"temp\":9.07,\"feels_like\":0.79,\"temp_min\":9.07,\"temp_max\":9.07,\"pressure\":990,\"sea_level\":990,\"grnd_level\":986,\"humidity\":75,\"temp_kf\":0},\"weather\":[{\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10n\"}],\"clouds\":{\"all\":100},\"wind\":{\"speed\":10.18,\"deg\":255},\"rain\":{\"3h\":2},\"sys\":{\"pod\":\"n\"},\"dt_txt\":\"2020-02-16 06:00:00\"},{\"dt\":1581843600,\"main\":{\"temp\":8.05,\"feels_like\":-0.9,\"temp_min\":8.05,\"temp_max\":8.05,\"pressure\":994,\"sea_level\":994,\"grnd_level\":990,\"humidity\":51,\"temp_kf\":0},\"weather\":[{\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10d\"}],\"clouds\":{\"all\":100},\"wind\":{\"speed\":9.65,\"deg\":245},\"rain\":{\"3h\":1.19},\"sys\":{\"pod\":\"d\"},\"dt_txt\":\"2020-02-16 09:00:00\"},{\"dt\":1581854400,\"main\":{\"temp\":9.54,\"feels_like\":0.13,\"temp_min\":9.54,\"temp_max\":9.54,\"pressure\":996,\"sea_level\":996,\"grnd_level\":991,\"humidity\":41,\"temp_kf\":0},\"weather\":[{\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04d\"}],\"clouds\":{\"all\":94},\"wind\":{\"speed\":10.03,\"deg\":243},\"sys\":{\"pod\":\"d\"},\"dt_txt\":\"2020-02-16 12:00:00\"},{\"dt\":1581865200,\"main\":{\"temp\":9.08,\"feels_like\":-0.35,\"temp_min\":9.08,\"temp_max\":9.08,\"pressure\":996,\"sea_level\":996,\"grnd_level\":991,\"humidity\":44,\"temp_kf\":0},\"weather\":[{\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10d\"}],\"clouds\":{\"all\":89},\"wind\":{\"speed\":10.15,\"deg\":246},\"rain\":{\"3h\":0.25},\"sys\":{\"pod\":\"d\"},\"dt_txt\":\"2020-02-16 15:00:00\"},{\"dt\":1581876000,\"main\":{\"temp\":7.41,\"feels_like\":-1.34,\"temp_min\":7.41,\"temp_max\":7.41,\"pressure\":996,\"sea_level\":996,\"grnd_level\":992,\"humidity\":50,\"temp_kf\":0},\"weather\":[{\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04n\"}],\"clouds\":{\"all\":94},\"wind\":{\"speed\":9.21,\"deg\":240},\"sys\":{\"pod\":\"n\"},\"dt_txt\":\"2020-02-16 18:00:00\"},{\"dt\":1581886800,\"main\":{\"temp\":6.42,\"feels_like\":-1.7,\"temp_min\":6.42,\"temp_max\":6.42,\"pressure\":997,\"sea_level\":997,\"grnd_level\":993,\"humidity\":58,\"temp_kf\":0},\"weather\":[{\"id\":803,\"main\":\"Clouds\",\"description\":\"broken clouds\",\"icon\":\"04n\"}],\"clouds\":{\"all\":67},\"wind\":{\"speed\":8.52,\"deg\":236},\"sys\":{\"pod\":\"n\"},\"dt_txt\":\"2020-02-16 21:00:00\"},{\"dt\":1581897600,\"main\":{\"temp\":6.03,\"feels_like\":-2.65,\"temp_min\":6.03,\"temp_max\":6.03,\"pressure\":996,\"sea_level\":996,\"grnd_level\":993,\"humidity\":51,\"temp_kf\":0},\"weather\":[{\"id\":802,\"main\":\"Clouds\",\"description\":\"scattered clouds\",\"icon\":\"03n\"}],\"clouds\":{\"all\":38},\"wind\":{\"speed\":8.94,\"deg\":240},\"sys\":{\"pod\":\"n\"},\"dt_txt\":\"2020-02-17 00:00:00\"},{\"dt\":1581908400,\"main\":{\"temp\":5.62,\"feels_like\":-2.86,\"temp_min\":5.62,\"temp_max\":5.62,\"pressure\":995,\"sea_level\":995,\"grnd_level\":991,\"humidity\":53,\"temp_kf\":0},\"weather\":[{\"id\":800,\"main\":\"Clear\",\"description\":\"clear sky\",\"icon\":\"01n\"}],\"clouds\":{\"all\":0},\"wind\":{\"speed\":8.67,\"deg\":241},\"sys\":{\"pod\":\"n\"},\"dt_txt\":\"2020-02-17 03:00:00\"},{\"dt\":1581919200,\"main\":{\"temp\":5.51,\"feels_like\":-2.41,\"temp_min\":5.51,\"temp_max\":5.51,\"pressure\":995,\"sea_level\":995,\"grnd_level\":991,\"humidity\":61,\"temp_kf\":0},\"weather\":[{\"id\":802,\"main\":\"Clouds\",\"description\":\"scattered clouds\",\"icon\":\"03n\"}],\"clouds\":{\"all\":35},\"wind\":{\"speed\":8.2,\"deg\":244},\"sys\":{\"pod\":\"n\"},\"dt_txt\":\"2020-02-17 06:00:00\"}],\"city\":{\"id\":2643743,\"name\":\"London\",\"coord\":{\"lat\":51.5085,\"lon\":-0.1257},\"country\":\"GB\",\"population\":1000000,\"timezone\":0,\"sunrise\":1581492085,\"sunset\":1581527294}}"; + + const char* expected_json = "{\"list\":[" + "{\"dt\":1581498000,\"main\":{\"temp\":3.23},\"weather\":[{\"description\":\"clear sky\"}]}," + "{\"dt\":1581508800,\"main\":{\"temp\":6.09},\"weather\":[{\"description\":\"clear sky\"}]}," + "{\"dt\":1581519600,\"main\":{\"temp\":6.82},\"weather\":[{\"description\":\"overcast clouds\"}]}," + "{\"dt\":1581530400,\"main\":{\"temp\":5.76},\"weather\":[{\"description\":\"overcast clouds\"}]}," + "{\"dt\":1581541200,\"main\":{\"temp\":5.7},\"weather\":[{\"description\":\"overcast clouds\"}]}," + "{\"dt\":1581552000,\"main\":{\"temp\":5.82},\"weather\":[{\"description\":\"light rain\"}]}," + "{\"dt\":1581562800,\"main\":{\"temp\":5.9},\"weather\":[{\"description\":\"light rain\"}]}," + "{\"dt\":1581573600,\"main\":{\"temp\":7.52},\"weather\":[{\"description\":\"moderate rain\"}]}," + "{\"dt\":1581584400,\"main\":{\"temp\":7.23},\"weather\":[{\"description\":\"light rain\"}]}," + "{\"dt\":1581595200,\"main\":{\"temp\":7.67},\"weather\":[{\"description\":\"light rain\"}]}," + "{\"dt\":1581606000,\"main\":{\"temp\":8.83},\"weather\":[{\"description\":\"light rain\"}]}," + "{\"dt\":1581616800,\"main\":{\"temp\":7.42},\"weather\":[{\"description\":\"broken clouds\"}]}," + "{\"dt\":1581627600,\"main\":{\"temp\":5.82},\"weather\":[{\"description\":\"clear sky\"}]}," + "{\"dt\":1581638400,\"main\":{\"temp\":5.58},\"weather\":[{\"description\":\"scattered clouds\"}]}," + "{\"dt\":1581649200,\"main\":{\"temp\":4.27},\"weather\":[{\"description\":\"broken clouds\"}]}," + "{\"dt\":1581660000,\"main\":{\"temp\":3.91},\"weather\":[{\"description\":\"overcast clouds\"}]}," + "{\"dt\":1581670800,\"main\":{\"temp\":4.77},\"weather\":[{\"description\":\"overcast clouds\"}]}," + "{\"dt\":1581681600,\"main\":{\"temp\":9.03},\"weather\":[{\"description\":\"overcast clouds\"}]}," + "{\"dt\":1581692400,\"main\":{\"temp\":9.86},\"weather\":[{\"description\":\"overcast clouds\"}]}," + "{\"dt\":1581703200,\"main\":{\"temp\":9.48},\"weather\":[{\"description\":\"overcast clouds\"}]}," + "{\"dt\":1581714000,\"main\":{\"temp\":10.03},\"weather\":[{\"description\":\"moderate rain\"}]}," + "{\"dt\":1581724800,\"main\":{\"temp\":9.48},\"weather\":[{\"description\":\"light rain\"}]}," + "{\"dt\":1581735600,\"main\":{\"temp\":9.12},\"weather\":[{\"description\":\"light rain\"}]}," + "{\"dt\":1581746400,\"main\":{\"temp\":10.32},\"weather\":[{\"description\":\"light rain\"}]}," + "{\"dt\":1581757200,\"main\":{\"temp\":11.57},\"weather\":[{\"description\":\"light rain\"}]}," + "{\"dt\":1581768000,\"main\":{\"temp\":12.25},\"weather\":[{\"description\":\"light rain\"}]}," + "{\"dt\":1581778800,\"main\":{\"temp\":12.19},\"weather\":[{\"description\":\"moderate rain\"}]}," + "{\"dt\":1581789600,\"main\":{\"temp\":12.25},\"weather\":[{\"description\":\"moderate rain\"}]}," + "{\"dt\":1581800400,\"main\":{\"temp\":12.64},\"weather\":[{\"description\":\"moderate rain\"}]}," + "{\"dt\":1581811200,\"main\":{\"temp\":12.96},\"weather\":[{\"description\":\"moderate rain\"}]}," + "{\"dt\":1581822000,\"main\":{\"temp\":13.13},\"weather\":[{\"description\":\"moderate rain\"}]}," + "{\"dt\":1581832800,\"main\":{\"temp\":9.07},\"weather\":[{\"description\":\"light rain\"}]}," + "{\"dt\":1581843600,\"main\":{\"temp\":8.05},\"weather\":[{\"description\":\"light rain\"}]}," + "{\"dt\":1581854400,\"main\":{\"temp\":9.54},\"weather\":[{\"description\":\"overcast clouds\"}]}," + "{\"dt\":1581865200,\"main\":{\"temp\":9.08},\"weather\":[{\"description\":\"light rain\"}]}," + "{\"dt\":1581876000,\"main\":{\"temp\":7.41},\"weather\":[{\"description\":\"overcast clouds\"}]}," + "{\"dt\":1581886800,\"main\":{\"temp\":6.42},\"weather\":[{\"description\":\"broken clouds\"}]}," + "{\"dt\":1581897600,\"main\":{\"temp\":6.03},\"weather\":[{\"description\":\"scattered clouds\"}]}," + "{\"dt\":1581908400,\"main\":{\"temp\":5.62},\"weather\":[{\"description\":\"clear sky\"}]}," + "{\"dt\":1581919200,\"main\":{\"temp\":5.51},\"weather\":[{\"description\":\"scattered clouds\"}]}" + "]}"; + // clang-format on + + StaticJsonDocument<512> filter; + filter["list"][0]["dt"] = true; + filter["list"][0]["main"]["temp"] = true; + filter["list"][0]["weather"][0]["description"] = true; + + DynamicJsonDocument doc(16384); + + REQUIRE( + deserializeJson(doc, input_json, DeserializationOption::Filter(filter)) == + DeserializationError::Ok); + + REQUIRE(doc.as() == expected_json); +} diff --git a/libraries/ArduinoJson/extras/tests/IntegrationTests/round_trip.cpp b/libraries/ArduinoJson/extras/tests/IntegrationTests/round_trip.cpp new file mode 100644 index 0000000..ede311d --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/IntegrationTests/round_trip.cpp @@ -0,0 +1,82 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +void check(std::string originalJson) { + DynamicJsonDocument doc(16384); + + std::string prettyJson; + deserializeJson(doc, originalJson); + serializeJsonPretty(doc, prettyJson); + + std::string finalJson; + deserializeJson(doc, originalJson); + serializeJson(doc, finalJson); + + REQUIRE(originalJson == finalJson); +} + +TEST_CASE("Round Trip: parse -> prettyPrint -> parse -> print") { + SECTION("OpenWeatherMap") { + check( + "{\"coord\":{\"lon\":145.77,\"lat\":-16.92},\"sys\":{\"type\":1,\"id\":" + "8166,\"message\":0.1222,\"country\":\"AU\",\"sunrise\":1414784325," + "\"sunset\":1414830137},\"weather\":[{\"id\":801,\"main\":\"Clouds\"," + "\"description\":\"few clouds\",\"icon\":\"02n\"}],\"base\":\"cmc " + "stations\",\"main\":{\"temp\":296.15,\"pressure\":1014,\"humidity\":" + "83,\"temp_min\":296.15,\"temp_max\":296.15},\"wind\":{\"speed\":2.22," + "\"deg\":114.501},\"clouds\":{\"all\":20},\"dt\":1414846800,\"id\":" + "2172797,\"name\":\"Cairns\",\"cod\":200}"); + } + + SECTION("YahooQueryLanguage") { + check( + "{\"query\":{\"count\":40,\"created\":\"2014-11-01T14:16:49Z\"," + "\"lang\":\"fr-FR\",\"results\":{\"item\":[{\"title\":\"Burkina army " + "backs Zida as interim leader\"},{\"title\":\"British jets intercept " + "Russian bombers\"},{\"title\":\"Doubts chip away at nation's most " + "trusted agencies\"},{\"title\":\"Cruise ship stuck off Norway, no " + "damage\"},{\"title\":\"U.S. military launches 10 air strikes in " + "Syria, Iraq\"},{\"title\":\"Blackout hits Bangladesh as line from " + "India fails\"},{\"title\":\"Burkina Faso president in Ivory Coast " + "after ouster\"},{\"title\":\"Kurds in Turkey rally to back city " + "besieged by IS\"},{\"title\":\"A majority of Scots would vote for " + "independence now:poll\"},{\"title\":\"Tunisia elections possible " + "model for region\"},{\"title\":\"Islamic State kills 85 more members " + "of Iraqi tribe\"},{\"title\":\"Iraqi officials:IS extremists line " + "up, kill 50\"},{\"title\":\"Burkina Faso army backs presidential " + "guard official to lead transition\"},{\"title\":\"Kurdish peshmerga " + "arrive with weapons in Syria's Kobani\"},{\"title\":\"Driver sought " + "in crash that killed 3 on Halloween\"},{\"title\":\"Ex-Marine arrives " + "in US after release from Mexico jail\"},{\"title\":\"UN panel " + "scrambling to finish climate report\"},{\"title\":\"Investigators, " + "Branson go to spacecraft crash site\"},{\"title\":\"Soldiers vie for " + "power after Burkina Faso president quits\"},{\"title\":\"For a man " + "without a party, turnout is big test\"},{\"title\":\"'We just had a " + "hunch':US marshals nab Eric Frein\"},{\"title\":\"Boko Haram leader " + "threatens to kill German hostage\"},{\"title\":\"Nurse free to move " + "about as restrictions eased\"},{\"title\":\"Former Burkina president " + "Compaore arrives in Ivory Coast:sources\"},{\"title\":\"Libyan port " + "rebel leader refuses to hand over oil ports to rival " + "group\"},{\"title\":\"Iraqi peshmerga fighters prepare for Syria " + "battle\"},{\"title\":\"1 Dem Senate candidate welcoming Obama's " + "help\"},{\"title\":\"Bikers cancel party after police recover " + "bar\"},{\"title\":\"New question in Texas:Can Davis survive " + "defeat?\"},{\"title\":\"Ukraine rebels to hold election, despite " + "criticism\"},{\"title\":\"Iraqi officials say Islamic State group " + "lines up, kills 50 tribesmen, women in Anbar " + "province\"},{\"title\":\"James rebounds, leads Cavaliers past " + "Bulls\"},{\"title\":\"UK warns travelers they could be terror " + "targets\"},{\"title\":\"Hello Kitty celebrates 40th " + "birthday\"},{\"title\":\"A look at people killed during space " + "missions\"},{\"title\":\"Nigeria's purported Boko Haram leader says " + "has 'married off' girls:AFP\"},{\"title\":\"Mexico orders immediate " + "release of Marine veteran\"},{\"title\":\"As election closes in, " + "Obama on center stage\"},{\"title\":\"Body of Zambian president " + "arrives home\"},{\"title\":\"South Africa arrests 2 Vietnamese for " + "poaching\"}]}}}"); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonArray/CMakeLists.txt b/libraries/ArduinoJson/extras/tests/JsonArray/CMakeLists.txt new file mode 100644 index 0000000..d97a2b1 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonArray/CMakeLists.txt @@ -0,0 +1,28 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2023, Benoit BLANCHON +# MIT License + +add_executable(JsonArrayTests + add.cpp + clear.cpp + compare.cpp + copyArray.cpp + createNested.cpp + equals.cpp + isNull.cpp + iterator.cpp + memoryUsage.cpp + nesting.cpp + remove.cpp + size.cpp + std_string.cpp + subscript.cpp + unbound.cpp +) + +add_test(JsonArray JsonArrayTests) + +set_tests_properties(JsonArray + PROPERTIES + LABELS "Catch" +) diff --git a/libraries/ArduinoJson/extras/tests/JsonArray/add.cpp b/libraries/ArduinoJson/extras/tests/JsonArray/add.cpp new file mode 100644 index 0000000..2708c7d --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonArray/add.cpp @@ -0,0 +1,138 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonArray::add()") { + DynamicJsonDocument doc(4096); + JsonArray array = doc.to(); + + SECTION("int") { + array.add(123); + REQUIRE(123 == array[0].as()); + REQUIRE(array[0].is()); + REQUIRE(array[0].is()); + } + + SECTION("double") { + array.add(123.45); + REQUIRE(123.45 == array[0].as()); + REQUIRE(array[0].is()); + REQUIRE_FALSE(array[0].is()); + } + + SECTION("bool") { + array.add(true); + REQUIRE(true == array[0].as()); + REQUIRE(array[0].is()); + REQUIRE_FALSE(array[0].is()); + } + + SECTION("const char*") { + const char* str = "hello"; + array.add(str); + REQUIRE(str == array[0].as()); + REQUIRE(array[0].is()); + REQUIRE_FALSE(array[0].is()); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("vla") { + size_t i = 16; + char vla[i]; + strcpy(vla, "world"); + + array.add(vla); + + REQUIRE(std::string("world") == array[0]); + } +#endif + + SECTION("nested array") { + DynamicJsonDocument doc2(4096); + JsonArray arr = doc2.to(); + + array.add(arr); + + REQUIRE(arr == array[0].as()); + REQUIRE(array[0].is()); + REQUIRE_FALSE(array[0].is()); + } + + SECTION("nested object") { + DynamicJsonDocument doc2(4096); + JsonObject obj = doc2.to(); + + array.add(obj); + + REQUIRE(obj == array[0].as()); + REQUIRE(array[0].is()); + REQUIRE_FALSE(array[0].is()); + } + + SECTION("array subscript") { + const char* str = "hello"; + DynamicJsonDocument doc2(4096); + JsonArray arr = doc2.to(); + arr.add(str); + + array.add(arr[0]); + + REQUIRE(str == array[0]); + } + + SECTION("object subscript") { + const char* str = "hello"; + DynamicJsonDocument doc2(4096); + JsonObject obj = doc2.to(); + obj["x"] = str; + + array.add(obj["x"]); + + REQUIRE(str == array[0]); + } + + SECTION("should not duplicate const char*") { + array.add("world"); + const size_t expectedSize = JSON_ARRAY_SIZE(1); + REQUIRE(expectedSize == doc.memoryUsage()); + } + + SECTION("should duplicate char*") { + array.add(const_cast("world")); + const size_t expectedSize = JSON_ARRAY_SIZE(1) + JSON_STRING_SIZE(5); + REQUIRE(expectedSize == doc.memoryUsage()); + } + + SECTION("should duplicate std::string") { + array.add(std::string("world")); + const size_t expectedSize = JSON_ARRAY_SIZE(1) + JSON_STRING_SIZE(5); + REQUIRE(expectedSize == doc.memoryUsage()); + } + + SECTION("should not duplicate serialized(const char*)") { + array.add(serialized("{}")); + const size_t expectedSize = JSON_ARRAY_SIZE(1); + REQUIRE(expectedSize == doc.memoryUsage()); + } + + SECTION("should duplicate serialized(char*)") { + array.add(serialized(const_cast("{}"))); + const size_t expectedSize = JSON_ARRAY_SIZE(1) + JSON_STRING_SIZE(2); + REQUIRE(expectedSize == doc.memoryUsage()); + } + + SECTION("should duplicate serialized(std::string)") { + array.add(serialized(std::string("{}"))); + const size_t expectedSize = JSON_ARRAY_SIZE(1) + JSON_STRING_SIZE(2); + REQUIRE(expectedSize == doc.memoryUsage()); + } + + SECTION("should duplicate serialized(std::string)") { + array.add(serialized(std::string("\0XX", 3))); + const size_t expectedSize = JSON_ARRAY_SIZE(1) + JSON_STRING_SIZE(3); + REQUIRE(expectedSize == doc.memoryUsage()); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonArray/clear.cpp b/libraries/ArduinoJson/extras/tests/JsonArray/clear.cpp new file mode 100644 index 0000000..3a593c5 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonArray/clear.cpp @@ -0,0 +1,25 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonArray::clear()") { + SECTION("No-op on null JsonArray") { + JsonArray array; + array.clear(); + REQUIRE(array.isNull() == true); + REQUIRE(array.size() == 0); + } + + SECTION("Removes all elements") { + StaticJsonDocument<64> doc; + JsonArray array = doc.to(); + array.add(1); + array.add(2); + array.clear(); + REQUIRE(array.size() == 0); + REQUIRE(array.isNull() == false); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonArray/compare.cpp b/libraries/ArduinoJson/extras/tests/JsonArray/compare.cpp new file mode 100644 index 0000000..1e64e16 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonArray/compare.cpp @@ -0,0 +1,512 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("Compare JsonArray with JsonArray") { + StaticJsonDocument<256> doc; + + SECTION("Compare with unbound") { + JsonArray array = doc.to(); + array.add(1); + array.add("hello"); + JsonArray unbound; + + CHECK(array != unbound); + CHECK_FALSE(array == unbound); + CHECK_FALSE(array <= unbound); + CHECK_FALSE(array >= unbound); + CHECK_FALSE(array > unbound); + CHECK_FALSE(array < unbound); + + CHECK(unbound != array); + CHECK_FALSE(unbound == array); + CHECK_FALSE(unbound <= array); + CHECK_FALSE(unbound >= array); + CHECK_FALSE(unbound > array); + CHECK_FALSE(unbound < array); + } + + SECTION("Compare with self") { + JsonArray array = doc.to(); + array.add(1); + array.add("hello"); + + CHECK(array == array); + CHECK(array <= array); + CHECK(array >= array); + CHECK_FALSE(array != array); + CHECK_FALSE(array > array); + CHECK_FALSE(array < array); + } + + SECTION("Compare with identical array") { + JsonArray array1 = doc.createNestedArray(); + array1.add(1); + array1.add("hello"); + array1.createNestedObject(); + + JsonArray array2 = doc.createNestedArray(); + array2.add(1); + array2.add("hello"); + array2.createNestedObject(); + + CHECK(array1 == array2); + CHECK(array1 <= array2); + CHECK(array1 >= array2); + CHECK_FALSE(array1 != array2); + CHECK_FALSE(array1 > array2); + CHECK_FALSE(array1 < array2); + } + + SECTION("Compare with different array") { + JsonArray array1 = doc.createNestedArray(); + array1.add(1); + array1.add("hello1"); + array1.createNestedObject(); + + JsonArray array2 = doc.createNestedArray(); + array2.add(1); + array2.add("hello2"); + array2.createNestedObject(); + + CHECK(array1 != array2); + CHECK_FALSE(array1 == array2); + CHECK_FALSE(array1 > array2); + CHECK_FALSE(array1 < array2); + CHECK_FALSE(array1 <= array2); + CHECK_FALSE(array1 >= array2); + } +} + +TEST_CASE("Compare JsonArray with JsonVariant") { + StaticJsonDocument<256> doc; + + SECTION("Compare with self") { + JsonArray array = doc.to(); + array.add(1); + array.add("hello"); + + JsonVariant variant = array; + + CHECK(array == variant); + CHECK(array <= variant); + CHECK(array >= variant); + CHECK_FALSE(array != variant); + CHECK_FALSE(array > variant); + CHECK_FALSE(array < variant); + + CHECK(variant == array); + CHECK(variant <= array); + CHECK(variant >= array); + CHECK_FALSE(variant != array); + CHECK_FALSE(variant > array); + CHECK_FALSE(variant < array); + } + + SECTION("Compare with identical array") { + JsonArray array = doc.createNestedArray(); + array.add(1); + array.add("hello"); + array.createNestedObject(); + + JsonVariant variant = doc.createNestedArray(); + variant.add(1); + variant.add("hello"); + variant.createNestedObject(); + + CHECK(array == variant); + CHECK(array <= variant); + CHECK(array >= variant); + CHECK_FALSE(array != variant); + CHECK_FALSE(array > variant); + CHECK_FALSE(array < variant); + + CHECK(variant == array); + CHECK(variant <= array); + CHECK(variant >= array); + CHECK_FALSE(variant != array); + CHECK_FALSE(variant > array); + CHECK_FALSE(variant < array); + } + + SECTION("Compare with different array") { + JsonArray array = doc.createNestedArray(); + array.add(1); + array.add("hello1"); + array.createNestedObject(); + + JsonVariant variant = doc.createNestedArray(); + variant.add(1); + variant.add("hello2"); + variant.createNestedObject(); + + CHECK(array != variant); + CHECK_FALSE(array == variant); + CHECK_FALSE(array > variant); + CHECK_FALSE(array < variant); + CHECK_FALSE(array <= variant); + CHECK_FALSE(array >= variant); + } +} + +TEST_CASE("Compare JsonArray with JsonVariantConst") { + StaticJsonDocument<256> doc; + + SECTION("Compare with unbound") { + JsonArray array = doc.to(); + array.add(1); + array.add("hello"); + JsonVariantConst unbound; + + CHECK(array != unbound); + CHECK_FALSE(array == unbound); + CHECK_FALSE(array <= unbound); + CHECK_FALSE(array >= unbound); + CHECK_FALSE(array > unbound); + CHECK_FALSE(array < unbound); + + CHECK(unbound != array); + CHECK_FALSE(unbound == array); + CHECK_FALSE(unbound <= array); + CHECK_FALSE(unbound >= array); + CHECK_FALSE(unbound > array); + CHECK_FALSE(unbound < array); + } + + SECTION("Compare with self") { + JsonArray array = doc.to(); + array.add(1); + array.add("hello"); + + JsonVariantConst variant = array; + + CHECK(array == variant); + CHECK(array <= variant); + CHECK(array >= variant); + CHECK_FALSE(array != variant); + CHECK_FALSE(array > variant); + CHECK_FALSE(array < variant); + + CHECK(variant == array); + CHECK(variant <= array); + CHECK(variant >= array); + CHECK_FALSE(variant != array); + CHECK_FALSE(variant > array); + CHECK_FALSE(variant < array); + } + + SECTION("Compare with identical array") { + JsonArray array = doc.createNestedArray(); + array.add(1); + array.add("hello"); + array.createNestedObject(); + + JsonArray array2 = doc.createNestedArray(); + array2.add(1); + array2.add("hello"); + array2.createNestedObject(); + JsonVariantConst variant = array2; + + CHECK(array == variant); + CHECK(array <= variant); + CHECK(array >= variant); + CHECK_FALSE(array != variant); + CHECK_FALSE(array > variant); + CHECK_FALSE(array < variant); + + CHECK(variant == array); + CHECK(variant <= array); + CHECK(variant >= array); + CHECK_FALSE(variant != array); + CHECK_FALSE(variant > array); + CHECK_FALSE(variant < array); + } + + SECTION("Compare with different array") { + JsonArray array = doc.createNestedArray(); + array.add(1); + array.add("hello1"); + array.createNestedObject(); + + JsonArray array2 = doc.createNestedArray(); + array2.add(1); + array2.add("hello2"); + array2.createNestedObject(); + JsonVariantConst variant = array2; + + CHECK(array != variant); + CHECK_FALSE(array == variant); + CHECK_FALSE(array > variant); + CHECK_FALSE(array < variant); + CHECK_FALSE(array <= variant); + CHECK_FALSE(array >= variant); + } +} + +TEST_CASE("Compare JsonArray with JsonArrayConst") { + StaticJsonDocument<256> doc; + + SECTION("Compare with unbound") { + JsonArray array = doc.to(); + array.add(1); + array.add("hello"); + JsonArrayConst unbound; + + CHECK(array != unbound); + CHECK_FALSE(array == unbound); + CHECK_FALSE(array <= unbound); + CHECK_FALSE(array >= unbound); + CHECK_FALSE(array > unbound); + CHECK_FALSE(array < unbound); + + CHECK(unbound != array); + CHECK_FALSE(unbound == array); + CHECK_FALSE(unbound <= array); + CHECK_FALSE(unbound >= array); + CHECK_FALSE(unbound > array); + CHECK_FALSE(unbound < array); + } + + SECTION("Compare with self") { + JsonArray array = doc.to(); + array.add(1); + array.add("hello"); + JsonArrayConst carray = array; + + CHECK(array == carray); + CHECK(array <= carray); + CHECK(array >= carray); + CHECK_FALSE(array != carray); + CHECK_FALSE(array > carray); + CHECK_FALSE(array < carray); + + CHECK(carray == array); + CHECK(carray <= array); + CHECK(carray >= array); + CHECK_FALSE(carray != array); + CHECK_FALSE(carray > array); + CHECK_FALSE(carray < array); + } + + SECTION("Compare with identical array") { + JsonArray array1 = doc.createNestedArray(); + array1.add(1); + array1.add("hello"); + array1.createNestedObject(); + + JsonArray array2 = doc.createNestedArray(); + array2.add(1); + array2.add("hello"); + array2.createNestedObject(); + JsonArrayConst carray2 = array2; + + CHECK(array1 == carray2); + CHECK(array1 <= carray2); + CHECK(array1 >= carray2); + CHECK_FALSE(array1 != carray2); + CHECK_FALSE(array1 > carray2); + CHECK_FALSE(array1 < carray2); + + CHECK(carray2 == array1); + CHECK(carray2 <= array1); + CHECK(carray2 >= array1); + CHECK_FALSE(carray2 != array1); + CHECK_FALSE(carray2 > array1); + CHECK_FALSE(carray2 < array1); + } + + SECTION("Compare with different array") { + JsonArray array1 = doc.createNestedArray(); + array1.add(1); + array1.add("hello1"); + array1.createNestedObject(); + + JsonArray array2 = doc.createNestedArray(); + array2.add(1); + array2.add("hello2"); + array2.createNestedObject(); + JsonArrayConst carray2 = array2; + + CHECK(array1 != carray2); + CHECK_FALSE(array1 == carray2); + CHECK_FALSE(array1 > carray2); + CHECK_FALSE(array1 < carray2); + CHECK_FALSE(array1 <= carray2); + CHECK_FALSE(array1 >= carray2); + + CHECK(carray2 != array1); + CHECK_FALSE(carray2 == array1); + CHECK_FALSE(carray2 > array1); + CHECK_FALSE(carray2 < array1); + CHECK_FALSE(carray2 <= array1); + CHECK_FALSE(carray2 >= array1); + } +} + +TEST_CASE("Compare JsonArrayConst with JsonArrayConst") { + StaticJsonDocument<256> doc; + + SECTION("Compare with unbound") { + JsonArray array = doc.to(); + array.add(1); + array.add("hello"); + + JsonArrayConst carray = array; + JsonArrayConst unbound; + + CHECK(carray != unbound); + CHECK_FALSE(carray == unbound); + CHECK_FALSE(carray <= unbound); + CHECK_FALSE(carray >= unbound); + CHECK_FALSE(carray > unbound); + CHECK_FALSE(carray < unbound); + + CHECK(unbound != carray); + CHECK_FALSE(unbound == carray); + CHECK_FALSE(unbound <= carray); + CHECK_FALSE(unbound >= carray); + CHECK_FALSE(unbound > carray); + CHECK_FALSE(unbound < carray); + } + + SECTION("Compare with self") { + JsonArray array = doc.to(); + array.add(1); + array.add("hello"); + JsonArrayConst carray = array; + + CHECK(carray == carray); + CHECK(carray <= carray); + CHECK(carray >= carray); + CHECK_FALSE(carray != carray); + CHECK_FALSE(carray > carray); + CHECK_FALSE(carray < carray); + } + + SECTION("Compare with identical array") { + JsonArray array1 = doc.createNestedArray(); + array1.add(1); + array1.add("hello"); + array1.createNestedObject(); + JsonArrayConst carray1 = array1; + + JsonArray array2 = doc.createNestedArray(); + array2.add(1); + array2.add("hello"); + array2.createNestedObject(); + JsonArrayConst carray2 = array2; + + CHECK(carray1 == carray2); + CHECK(carray1 <= carray2); + CHECK(carray1 >= carray2); + CHECK_FALSE(carray1 != carray2); + CHECK_FALSE(carray1 > carray2); + CHECK_FALSE(carray1 < carray2); + } + + SECTION("Compare with different array") { + JsonArray array1 = doc.createNestedArray(); + array1.add(1); + array1.add("hello1"); + array1.createNestedObject(); + JsonArrayConst carray1 = array1; + + JsonArray array2 = doc.createNestedArray(); + array2.add(1); + array2.add("hello2"); + array2.createNestedObject(); + JsonArrayConst carray2 = array2; + + CHECK(carray1 != carray2); + CHECK_FALSE(carray1 == carray2); + CHECK_FALSE(carray1 > carray2); + CHECK_FALSE(carray1 < carray2); + CHECK_FALSE(carray1 <= carray2); + CHECK_FALSE(carray1 >= carray2); + } +} + +TEST_CASE("Compare JsonArrayConst with JsonVariant") { + StaticJsonDocument<256> doc; + + SECTION("Compare with self") { + JsonArray array = doc.to(); + array.add(1); + array.add("hello"); + JsonArrayConst carray = array; + JsonVariant variant = array; + + CHECK(carray == variant); + CHECK(carray <= variant); + CHECK(carray >= variant); + CHECK_FALSE(carray != variant); + CHECK_FALSE(carray > variant); + CHECK_FALSE(carray < variant); + + CHECK(variant == carray); + CHECK(variant <= carray); + CHECK(variant >= carray); + CHECK_FALSE(variant != carray); + CHECK_FALSE(variant > carray); + CHECK_FALSE(variant < carray); + } + + SECTION("Compare with identical array") { + JsonArray array1 = doc.createNestedArray(); + array1.add(1); + array1.add("hello"); + array1.createNestedObject(); + JsonArrayConst carray1 = array1; + + JsonArray array2 = doc.createNestedArray(); + array2.add(1); + array2.add("hello"); + array2.createNestedObject(); + JsonVariant variant2 = array2; + + CHECK(carray1 == variant2); + CHECK(carray1 <= variant2); + CHECK(carray1 >= variant2); + CHECK_FALSE(carray1 != variant2); + CHECK_FALSE(carray1 > variant2); + CHECK_FALSE(carray1 < variant2); + + CHECK(variant2 == carray1); + CHECK(variant2 <= carray1); + CHECK(variant2 >= carray1); + CHECK_FALSE(variant2 != carray1); + CHECK_FALSE(variant2 > carray1); + CHECK_FALSE(variant2 < carray1); + } + + SECTION("Compare with different array") { + JsonArray array1 = doc.createNestedArray(); + array1.add(1); + array1.add("hello1"); + array1.createNestedObject(); + JsonArrayConst carray1 = array1; + + JsonArray array2 = doc.createNestedArray(); + array2.add(1); + array2.add("hello2"); + array2.createNestedObject(); + JsonVariant variant2 = array2; + + CHECK(carray1 != variant2); + CHECK_FALSE(carray1 == variant2); + CHECK_FALSE(carray1 > variant2); + CHECK_FALSE(carray1 < variant2); + CHECK_FALSE(carray1 <= variant2); + CHECK_FALSE(carray1 >= variant2); + + CHECK(variant2 != carray1); + CHECK_FALSE(variant2 == carray1); + CHECK_FALSE(variant2 > carray1); + CHECK_FALSE(variant2 < carray1); + CHECK_FALSE(variant2 <= carray1); + CHECK_FALSE(variant2 >= carray1); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonArray/copyArray.cpp b/libraries/ArduinoJson/extras/tests/JsonArray/copyArray.cpp new file mode 100644 index 0000000..7973c37 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonArray/copyArray.cpp @@ -0,0 +1,346 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("copyArray()") { + SECTION("int[] -> JsonArray") { + DynamicJsonDocument doc(4096); + JsonArray array = doc.to(); + char json[32]; + int source[] = {1, 2, 3}; + + bool ok = copyArray(source, array); + CHECK(ok); + + serializeJson(array, json); + CHECK(std::string("[1,2,3]") == json); + } + + SECTION("std::string[] -> JsonArray") { + DynamicJsonDocument doc(4096); + JsonArray array = doc.to(); + char json[32]; + std::string source[] = {"a", "b", "c"}; + + bool ok = copyArray(source, array); + CHECK(ok); + + serializeJson(array, json); + CHECK(std::string("[\"a\",\"b\",\"c\"]") == json); + } + + SECTION("const char*[] -> JsonArray") { + DynamicJsonDocument doc(4096); + JsonArray array = doc.to(); + char json[32]; + const char* source[] = {"a", "b", "c"}; + + bool ok = copyArray(source, array); + CHECK(ok); + + serializeJson(array, json); + CHECK(std::string("[\"a\",\"b\",\"c\"]") == json); + } + + SECTION("const char[][] -> JsonArray") { + DynamicJsonDocument doc(4096); + JsonArray array = doc.to(); + char json[32]; + char source[][2] = {"a", "b", "c"}; + + bool ok = copyArray(source, array); + CHECK(ok); + + serializeJson(array, json); + CHECK(std::string("[\"a\",\"b\",\"c\"]") == json); + } + + SECTION("const char[][] -> JsonDocument") { + DynamicJsonDocument doc(4096); + char json[32]; + char source[][2] = {"a", "b", "c"}; + + bool ok = copyArray(source, doc); + CHECK(ok); + + serializeJson(doc, json); + CHECK(std::string("[\"a\",\"b\",\"c\"]") == json); + } + + SECTION("const char[][] -> MemberProxy") { + DynamicJsonDocument doc(4096); + char json[32]; + char source[][2] = {"a", "b", "c"}; + + bool ok = copyArray(source, doc["data"]); + CHECK(ok); + + serializeJson(doc, json); + CHECK(std::string("{\"data\":[\"a\",\"b\",\"c\"]}") == json); + } + + SECTION("int[] -> JsonDocument") { + DynamicJsonDocument doc(4096); + char json[32]; + int source[] = {1, 2, 3}; + + bool ok = copyArray(source, doc); + CHECK(ok); + + serializeJson(doc, json); + CHECK(std::string("[1,2,3]") == json); + } + + SECTION("int[] -> MemberProxy") { + DynamicJsonDocument doc(4096); + char json[32]; + int source[] = {1, 2, 3}; + + bool ok = copyArray(source, doc["data"]); + CHECK(ok); + + serializeJson(doc, json); + CHECK(std::string("{\"data\":[1,2,3]}") == json); + } + + SECTION("int[] -> JsonArray, but not enough memory") { + const size_t SIZE = JSON_ARRAY_SIZE(2); + StaticJsonDocument doc; + JsonArray array = doc.to(); + char json[32]; + int source[] = {1, 2, 3}; + + bool ok = copyArray(source, array); + REQUIRE_FALSE(ok); + + serializeJson(array, json); + CHECK(std::string("[1,2]") == json); + } + + SECTION("int[][] -> JsonArray") { + DynamicJsonDocument doc(4096); + JsonArray array = doc.to(); + char json[32]; + int source[][3] = {{1, 2, 3}, {4, 5, 6}}; + + bool ok = copyArray(source, array); + CHECK(ok); + + serializeJson(array, json); + CHECK(std::string("[[1,2,3],[4,5,6]]") == json); + } + + SECTION("int[][] -> MemberProxy") { + DynamicJsonDocument doc(4096); + char json[32]; + int source[][3] = {{1, 2, 3}, {4, 5, 6}}; + + bool ok = copyArray(source, doc["data"]); + CHECK(ok); + + serializeJson(doc, json); + CHECK(std::string("{\"data\":[[1,2,3],[4,5,6]]}") == json); + } + + SECTION("int[][] -> JsonDocument") { + DynamicJsonDocument doc(4096); + char json[32]; + int source[][3] = {{1, 2, 3}, {4, 5, 6}}; + + bool ok = copyArray(source, doc); + CHECK(ok); + + serializeJson(doc, json); + CHECK(std::string("[[1,2,3],[4,5,6]]") == json); + } + + SECTION("int[][] -> JsonArray, but not enough memory") { + const size_t SIZE = + JSON_ARRAY_SIZE(2) + JSON_ARRAY_SIZE(3) + JSON_ARRAY_SIZE(2); + StaticJsonDocument doc; + JsonArray array = doc.to(); + char json[32] = ""; + int source[][3] = {{1, 2, 3}, {4, 5, 6}}; + + CAPTURE(SIZE); + + bool ok = copyArray(source, array); + CAPTURE(doc.memoryUsage()); + CHECK_FALSE(ok); + + serializeJson(array, json); + CHECK(std::string("[[1,2,3],[4,5]]") == json); + } + + SECTION("JsonArray -> int[], with more space than needed") { + DynamicJsonDocument doc(4096); + char json[] = "[1,2,3]"; + DeserializationError err = deserializeJson(doc, json); + CHECK(err == DeserializationError::Ok); + JsonArray array = doc.as(); + + int destination[4] = {0}; + size_t result = copyArray(array, destination); + + CHECK(3 == result); + CHECK(1 == destination[0]); + CHECK(2 == destination[1]); + CHECK(3 == destination[2]); + CHECK(0 == destination[3]); + } + + SECTION("JsonArray -> int[], without enough space") { + DynamicJsonDocument doc(4096); + char json[] = "[1,2,3]"; + DeserializationError err = deserializeJson(doc, json); + CHECK(err == DeserializationError::Ok); + JsonArray array = doc.as(); + + int destination[2] = {0}; + size_t result = copyArray(array, destination); + + CHECK(2 == result); + CHECK(1 == destination[0]); + CHECK(2 == destination[1]); + } + + SECTION("JsonArray -> std::string[]") { + DynamicJsonDocument doc(4096); + char json[] = "[\"a\",\"b\",\"c\"]"; + DeserializationError err = deserializeJson(doc, json); + CHECK(err == DeserializationError::Ok); + JsonArray array = doc.as(); + + std::string destination[4]; + size_t result = copyArray(array, destination); + + CHECK(3 == result); + CHECK("a" == destination[0]); + CHECK("b" == destination[1]); + CHECK("c" == destination[2]); + CHECK("" == destination[3]); + } + + SECTION("JsonArray -> char[N][]") { + DynamicJsonDocument doc(4096); + char json[] = "[\"a12345\",\"b123456\",\"c1234567\"]"; + DeserializationError err = deserializeJson(doc, json); + CHECK(err == DeserializationError::Ok); + JsonArray array = doc.as(); + + char destination[4][8] = {{0}}; + size_t result = copyArray(array, destination); + + CHECK(3 == result); + CHECK(std::string("a12345") == destination[0]); + CHECK(std::string("b123456") == destination[1]); + CHECK(std::string("c123456") == destination[2]); // truncated + CHECK(std::string("") == destination[3]); + } + + SECTION("JsonDocument -> int[]") { + DynamicJsonDocument doc(4096); + char json[] = "[1,2,3]"; + DeserializationError err = deserializeJson(doc, json); + CHECK(err == DeserializationError::Ok); + + int destination[4] = {0}; + size_t result = copyArray(doc, destination); + + CHECK(3 == result); + CHECK(1 == destination[0]); + CHECK(2 == destination[1]); + CHECK(3 == destination[2]); + CHECK(0 == destination[3]); + } + + SECTION("MemberProxy -> int[]") { + DynamicJsonDocument doc(4096); + char json[] = "{\"data\":[1,2,3]}"; + DeserializationError err = deserializeJson(doc, json); + CHECK(err == DeserializationError::Ok); + + int destination[4] = {0}; + size_t result = copyArray(doc["data"], destination); + + CHECK(3 == result); + CHECK(1 == destination[0]); + CHECK(2 == destination[1]); + CHECK(3 == destination[2]); + CHECK(0 == destination[3]); + } + + SECTION("ElementProxy -> int[]") { + DynamicJsonDocument doc(4096); + char json[] = "[[1,2,3]]"; + DeserializationError err = deserializeJson(doc, json); + CHECK(err == DeserializationError::Ok); + + int destination[4] = {0}; + size_t result = copyArray(doc[0], destination); + + CHECK(3 == result); + CHECK(1 == destination[0]); + CHECK(2 == destination[1]); + CHECK(3 == destination[2]); + CHECK(0 == destination[3]); + } + + SECTION("JsonArray -> int[][]") { + DynamicJsonDocument doc(4096); + char json[] = "[[1,2],[3],[4]]"; + + DeserializationError err = deserializeJson(doc, json); + CHECK(err == DeserializationError::Ok); + JsonArray array = doc.as(); + + int destination[3][2] = {{0}}; + copyArray(array, destination); + + CHECK(1 == destination[0][0]); + CHECK(2 == destination[0][1]); + CHECK(3 == destination[1][0]); + CHECK(0 == destination[1][1]); + CHECK(4 == destination[2][0]); + CHECK(0 == destination[2][1]); + } + + SECTION("JsonDocument -> int[][]") { + DynamicJsonDocument doc(4096); + char json[] = "[[1,2],[3],[4]]"; + + DeserializationError err = deserializeJson(doc, json); + CHECK(err == DeserializationError::Ok); + + int destination[3][2] = {{0}}; + copyArray(doc, destination); + + CHECK(1 == destination[0][0]); + CHECK(2 == destination[0][1]); + CHECK(3 == destination[1][0]); + CHECK(0 == destination[1][1]); + CHECK(4 == destination[2][0]); + CHECK(0 == destination[2][1]); + } + + SECTION("MemberProxy -> int[][]") { + DynamicJsonDocument doc(4096); + char json[] = "{\"data\":[[1,2],[3],[4]]}"; + + DeserializationError err = deserializeJson(doc, json); + CHECK(err == DeserializationError::Ok); + + int destination[3][2] = {{0}}; + copyArray(doc["data"], destination); + + CHECK(1 == destination[0][0]); + CHECK(2 == destination[0][1]); + CHECK(3 == destination[1][0]); + CHECK(0 == destination[1][1]); + CHECK(4 == destination[2][0]); + CHECK(0 == destination[2][1]); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonArray/createNested.cpp b/libraries/ArduinoJson/extras/tests/JsonArray/createNested.cpp new file mode 100644 index 0000000..4801dbe --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonArray/createNested.cpp @@ -0,0 +1,21 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonArray basics") { + DynamicJsonDocument doc(4096); + JsonArray array = doc.to(); + + SECTION("CreateNestedArray") { + JsonArray arr = array.createNestedArray(); + REQUIRE(arr == array[0].as()); + } + + SECTION("CreateNestedObject") { + JsonObject obj = array.createNestedObject(); + REQUIRE(obj == array[0].as()); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonArray/equals.cpp b/libraries/ArduinoJson/extras/tests/JsonArray/equals.cpp new file mode 100644 index 0000000..4998d38 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonArray/equals.cpp @@ -0,0 +1,69 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonArray::operator==()") { + DynamicJsonDocument doc1(4096); + JsonArray array1 = doc1.to(); + JsonArrayConst array1c = array1; + + DynamicJsonDocument doc2(4096); + JsonArray array2 = doc2.to(); + JsonArrayConst array2c = array2; + + SECTION("should return false when arrays differ") { + array1.add("coucou"); + array2.add(1); + + REQUIRE_FALSE(array1 == array2); + REQUIRE_FALSE(array1c == array2c); + } + + SECTION("should return false when LHS has more elements") { + array1.add(1); + array1.add(2); + array2.add(1); + + REQUIRE_FALSE(array1 == array2); + REQUIRE_FALSE(array1c == array2c); + } + + SECTION("should return false when RHS has more elements") { + array1.add(1); + array2.add(1); + array2.add(2); + + REQUIRE_FALSE(array1 == array2); + REQUIRE_FALSE(array1c == array2c); + } + + SECTION("should return true when arrays equal") { + array1.add("coucou"); + array2.add("coucou"); + + REQUIRE(array1 == array2); + REQUIRE(array1c == array2c); + } + + SECTION("should return false when RHS is null") { + JsonArray null; + + REQUIRE_FALSE(array1 == null); + } + + SECTION("should return false when LHS is null") { + JsonArray null; + + REQUIRE_FALSE(null == array1); + } + + SECTION("should return true when both are null") { + JsonArray null1; + JsonArray null2; + + REQUIRE(null1 == null2); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonArray/isNull.cpp b/libraries/ArduinoJson/extras/tests/JsonArray/isNull.cpp new file mode 100644 index 0000000..0da13be --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonArray/isNull.cpp @@ -0,0 +1,58 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonArray::isNull()") { + SECTION("returns true") { + JsonArray arr; + REQUIRE(arr.isNull() == true); + } + + SECTION("returns false") { + DynamicJsonDocument doc(4096); + JsonArray arr = doc.to(); + REQUIRE(arr.isNull() == false); + } +} + +TEST_CASE("JsonArrayConst::isNull()") { + SECTION("returns true") { + JsonArrayConst arr; + REQUIRE(arr.isNull() == true); + } + + SECTION("returns false") { + DynamicJsonDocument doc(4096); + JsonArrayConst arr = doc.to(); + REQUIRE(arr.isNull() == false); + } +} + +TEST_CASE("JsonArray::operator bool()") { + SECTION("returns false") { + JsonArray arr; + REQUIRE(static_cast(arr) == false); + } + + SECTION("returns true") { + DynamicJsonDocument doc(4096); + JsonArray arr = doc.to(); + REQUIRE(static_cast(arr) == true); + } +} + +TEST_CASE("JsonArrayConst::operator bool()") { + SECTION("returns false") { + JsonArrayConst arr; + REQUIRE(static_cast(arr) == false); + } + + SECTION("returns true") { + DynamicJsonDocument doc(4096); + JsonArrayConst arr = doc.to(); + REQUIRE(static_cast(arr) == true); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonArray/iterator.cpp b/libraries/ArduinoJson/extras/tests/JsonArray/iterator.cpp new file mode 100644 index 0000000..50eb276 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonArray/iterator.cpp @@ -0,0 +1,52 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +template +static void run_iterator_test() { + StaticJsonDocument doc; + JsonArray tmp = doc.to(); + tmp.add(12); + tmp.add(34); + + TArray array = tmp; + typename TArray::iterator it = array.begin(); + typename TArray::iterator end = array.end(); + + REQUIRE(end != it); + REQUIRE(12 == it->template as()); + REQUIRE(12 == static_cast(*it)); + ++it; + REQUIRE(end != it); + REQUIRE(34 == it->template as()); + REQUIRE(34 == static_cast(*it)); + ++it; + REQUIRE(end == it); +} + +TEST_CASE("JsonArray::begin()/end()") { + SECTION("Non null JsonArray") { + run_iterator_test(); + } + + SECTION("Null JsonArray") { + JsonArray array; + + REQUIRE(array.begin() == array.end()); + } +} + +TEST_CASE("JsonArrayConst::begin()/end()") { + SECTION("Non null JsonArrayConst") { + run_iterator_test(); + } + + SECTION("Null JsonArrayConst") { + JsonArrayConst array; + + REQUIRE(array.begin() == array.end()); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonArray/memoryUsage.cpp b/libraries/ArduinoJson/extras/tests/JsonArray/memoryUsage.cpp new file mode 100644 index 0000000..9f4ea09 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonArray/memoryUsage.cpp @@ -0,0 +1,42 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonArray::memoryUsage()") { + DynamicJsonDocument doc(4096); + JsonArray arr = doc.to(); + + SECTION("return 0 if uninitialized") { + JsonArray unitialized; + REQUIRE(unitialized.memoryUsage() == 0); + } + + SECTION("JSON_ARRAY_SIZE(0) if empty") { + REQUIRE(arr.memoryUsage() == JSON_ARRAY_SIZE(0)); + } + + SECTION("JSON_ARRAY_SIZE(1) after add") { + arr.add("hello"); + REQUIRE(arr.memoryUsage() == JSON_ARRAY_SIZE(1)); + } + + SECTION("includes the size of the string") { + arr.add(std::string("hello")); + REQUIRE(arr.memoryUsage() == JSON_ARRAY_SIZE(1) + 6); + } + + SECTION("includes the size of the nested array") { + JsonArray nested = arr.createNestedArray(); + nested.add(42); + REQUIRE(arr.memoryUsage() == 2 * JSON_ARRAY_SIZE(1)); + } + + SECTION("includes the size of the nested arrect") { + JsonObject nested = arr.createNestedObject(); + nested["hello"] = "world"; + REQUIRE(arr.memoryUsage() == JSON_OBJECT_SIZE(1) + JSON_ARRAY_SIZE(1)); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonArray/nesting.cpp b/libraries/ArduinoJson/extras/tests/JsonArray/nesting.cpp new file mode 100644 index 0000000..fc1be8c --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonArray/nesting.cpp @@ -0,0 +1,35 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonArray::nesting()") { + DynamicJsonDocument doc(4096); + JsonArray arr = doc.to(); + + SECTION("return 0 if uninitialized") { + JsonArray unitialized; + REQUIRE(unitialized.nesting() == 0); + } + + SECTION("returns 1 for empty array") { + REQUIRE(arr.nesting() == 1); + } + + SECTION("returns 1 for flat array") { + arr.add("hello"); + REQUIRE(arr.nesting() == 1); + } + + SECTION("returns 2 with nested array") { + arr.createNestedArray(); + REQUIRE(arr.nesting() == 2); + } + + SECTION("returns 2 with nested object") { + arr.createNestedObject(); + REQUIRE(arr.nesting() == 2); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonArray/remove.cpp b/libraries/ArduinoJson/extras/tests/JsonArray/remove.cpp new file mode 100644 index 0000000..f75efda --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonArray/remove.cpp @@ -0,0 +1,89 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonArray::remove()") { + DynamicJsonDocument doc(4096); + JsonArray array = doc.to(); + array.add(1); + array.add(2); + array.add(3); + + SECTION("remove first by index") { + array.remove(0); + + REQUIRE(2 == array.size()); + REQUIRE(array[0] == 2); + REQUIRE(array[1] == 3); + } + + SECTION("remove middle by index") { + array.remove(1); + + REQUIRE(2 == array.size()); + REQUIRE(array[0] == 1); + REQUIRE(array[1] == 3); + } + + SECTION("remove last by index") { + array.remove(2); + + REQUIRE(2 == array.size()); + REQUIRE(array[0] == 1); + REQUIRE(array[1] == 2); + } + + SECTION("remove first by iterator") { + JsonArray::iterator it = array.begin(); + array.remove(it); + + REQUIRE(2 == array.size()); + REQUIRE(array[0] == 2); + REQUIRE(array[1] == 3); + } + + SECTION("remove middle by iterator") { + JsonArray::iterator it = array.begin(); + ++it; + array.remove(it); + + REQUIRE(2 == array.size()); + REQUIRE(array[0] == 1); + REQUIRE(array[1] == 3); + } + + SECTION("remove last bty iterator") { + JsonArray::iterator it = array.begin(); + ++it; + ++it; + array.remove(it); + + REQUIRE(2 == array.size()); + REQUIRE(array[0] == 1); + REQUIRE(array[1] == 2); + } + + SECTION("In a loop") { + for (JsonArray::iterator it = array.begin(); it != array.end(); ++it) { + if (*it == 2) + array.remove(it); + } + + REQUIRE(2 == array.size()); + REQUIRE(array[0] == 1); + REQUIRE(array[1] == 3); + } + + SECTION("remove by index on unbound reference") { + JsonArray unboundArray; + unboundArray.remove(20); + } + + SECTION("remove by iterator on unbound reference") { + JsonArray unboundArray; + unboundArray.remove(unboundArray.begin()); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonArray/size.cpp b/libraries/ArduinoJson/extras/tests/JsonArray/size.cpp new file mode 100644 index 0000000..6edd4db --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonArray/size.cpp @@ -0,0 +1,31 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonArray::size()") { + DynamicJsonDocument doc(4096); + JsonArray array = doc.to(); + + SECTION("returns 0 is empty") { + REQUIRE(0U == array.size()); + } + + SECTION("increases after add()") { + array.add("hello"); + REQUIRE(1U == array.size()); + + array.add("world"); + REQUIRE(2U == array.size()); + } + + SECTION("remains the same after replacing an element") { + array.add("hello"); + REQUIRE(1U == array.size()); + + array[0] = "hello"; + REQUIRE(1U == array.size()); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonArray/std_string.cpp b/libraries/ArduinoJson/extras/tests/JsonArray/std_string.cpp new file mode 100644 index 0000000..7d3ec9f --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonArray/std_string.cpp @@ -0,0 +1,32 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +static void eraseString(std::string& str) { + char* p = const_cast(str.c_str()); + while (*p) + *p++ = '*'; +} + +TEST_CASE("std::string") { + DynamicJsonDocument doc(4096); + JsonArray array = doc.to(); + + SECTION("add()") { + std::string value("hello"); + array.add(value); + eraseString(value); + REQUIRE(std::string("hello") == array[0]); + } + + SECTION("operator[]") { + std::string value("world"); + array.add("hello"); + array[0] = value; + eraseString(value); + REQUIRE(std::string("world") == array[0]); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonArray/subscript.cpp b/libraries/ArduinoJson/extras/tests/JsonArray/subscript.cpp new file mode 100644 index 0000000..3079d2f --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonArray/subscript.cpp @@ -0,0 +1,174 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include +#include + +TEST_CASE("JsonArray::operator[]") { + DynamicJsonDocument doc(4096); + JsonArray array = doc.to(); + + SECTION("Pad with null") { + array[2] = 2; + array[5] = 5; + REQUIRE(array.size() == 6); + REQUIRE(array[0].isNull() == true); + REQUIRE(array[1].isNull() == true); + REQUIRE(array[2].isNull() == false); + REQUIRE(array[3].isNull() == true); + REQUIRE(array[4].isNull() == true); + REQUIRE(array[5].isNull() == false); + REQUIRE(array[2] == 2); + REQUIRE(array[5] == 5); + } + + SECTION("int") { + array[0] = 123; + REQUIRE(123 == array[0].as()); + REQUIRE(true == array[0].is()); + REQUIRE(false == array[0].is()); + } + +#if ARDUINOJSON_USE_LONG_LONG + SECTION("long long") { + array[0] = 9223372036854775807; + REQUIRE(9223372036854775807 == array[0].as()); + REQUIRE(true == array[0].is()); + REQUIRE(false == array[0].is()); + REQUIRE(false == array[0].is()); + } +#endif + + SECTION("double") { + array[0] = 123.45; + REQUIRE(123.45 == array[0].as()); + REQUIRE(true == array[0].is()); + REQUIRE(false == array[0].is()); + } + + SECTION("bool") { + array[0] = true; + REQUIRE(true == array[0].as()); + REQUIRE(true == array[0].is()); + REQUIRE(false == array[0].is()); + } + + SECTION("const char*") { + const char* str = "hello"; + + array[0] = str; + REQUIRE(str == array[0].as()); + REQUIRE(true == array[0].is()); + REQUIRE(false == array[0].is()); + } + + SECTION("nested array") { + DynamicJsonDocument doc2(4096); + JsonArray arr2 = doc2.to(); + + array[0] = arr2; + + REQUIRE(arr2 == array[0].as()); + REQUIRE(true == array[0].is()); + REQUIRE(false == array[0].is()); + } + + SECTION("nested object") { + DynamicJsonDocument doc2(4096); + JsonObject obj = doc2.to(); + + array[0] = obj; + + REQUIRE(obj == array[0].as()); + REQUIRE(true == array[0].is()); + REQUIRE(false == array[0].is()); + } + + SECTION("array subscript") { + DynamicJsonDocument doc2(4096); + JsonArray arr2 = doc2.to(); + const char* str = "hello"; + + arr2.add(str); + + array[0] = arr2[0]; + + REQUIRE(str == array[0]); + } + + SECTION("object subscript") { + const char* str = "hello"; + DynamicJsonDocument doc2(4096); + JsonObject obj = doc2.to(); + + obj["x"] = str; + + array[0] = obj["x"]; + + REQUIRE(str == array[0]); + } + + SECTION("should not duplicate const char*") { + array[0] = "world"; + const size_t expectedSize = JSON_ARRAY_SIZE(1); + REQUIRE(expectedSize == doc.memoryUsage()); + } + + SECTION("should duplicate char*") { + array[0] = const_cast("world"); + const size_t expectedSize = JSON_ARRAY_SIZE(1) + JSON_STRING_SIZE(5); + REQUIRE(expectedSize == doc.memoryUsage()); + } + + SECTION("should duplicate std::string") { + array[0] = std::string("world"); + const size_t expectedSize = JSON_ARRAY_SIZE(1) + JSON_STRING_SIZE(5); + REQUIRE(expectedSize == doc.memoryUsage()); + } + + SECTION("array[0].to()") { + JsonObject obj = array[0].to(); + REQUIRE(obj.isNull() == false); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("set(VLA)") { + size_t i = 16; + char vla[i]; + strcpy(vla, "world"); + + array.add("hello"); + array[0].set(vla); + + REQUIRE(std::string("world") == array[0]); + } + + SECTION("operator=(VLA)") { + size_t i = 16; + char vla[i]; + strcpy(vla, "world"); + + array.add("hello"); + array[0] = vla; + + REQUIRE(std::string("world") == array[0]); + } +#endif +} + +TEST_CASE("JsonArrayConst::operator[]") { + DynamicJsonDocument doc(4096); + JsonArray array = doc.to(); + array.add(0); + + SECTION("int") { + array[0] = 123; + JsonArrayConst carr = array; + + REQUIRE(123 == carr[0].as()); + REQUIRE(true == carr[0].is()); + REQUIRE(false == carr[0].is()); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonArray/unbound.cpp b/libraries/ArduinoJson/extras/tests/JsonArray/unbound.cpp new file mode 100644 index 0000000..0e21310 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonArray/unbound.cpp @@ -0,0 +1,35 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +using namespace Catch::Matchers; + +TEST_CASE("Unbound JsonArray") { + JsonArray array; + + SECTION("SubscriptFails") { + REQUIRE(array[0].isNull()); + } + + SECTION("AddFails") { + array.add(1); + REQUIRE(0 == array.size()); + } + + SECTION("CreateNestedArrayFails") { + REQUIRE(array.createNestedArray().isNull()); + } + + SECTION("CreateNestedObjectFails") { + REQUIRE(array.createNestedObject().isNull()); + } + + SECTION("PrintToWritesBrackets") { + char buffer[32]; + serializeJson(array, buffer, sizeof(buffer)); + REQUIRE_THAT(buffer, Equals("null")); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDeserializer/CMakeLists.txt b/libraries/ArduinoJson/extras/tests/JsonDeserializer/CMakeLists.txt new file mode 100644 index 0000000..f60ad41 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDeserializer/CMakeLists.txt @@ -0,0 +1,28 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2023, Benoit BLANCHON +# MIT License + +add_executable(JsonDeserializerTests + array.cpp + array_static.cpp + DeserializationError.cpp + filter.cpp + incomplete_input.cpp + input_types.cpp + invalid_input.cpp + misc.cpp + nestingLimit.cpp + number.cpp + object.cpp + object_static.cpp + string.cpp +) + +set_target_properties(JsonDeserializerTests PROPERTIES UNITY_BUILD OFF) + +add_test(JsonDeserializer JsonDeserializerTests) + +set_tests_properties(JsonDeserializer + PROPERTIES + LABELS "Catch" +) diff --git a/libraries/ArduinoJson/extras/tests/JsonDeserializer/DeserializationError.cpp b/libraries/ArduinoJson/extras/tests/JsonDeserializer/DeserializationError.cpp new file mode 100644 index 0000000..fd1b188 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDeserializer/DeserializationError.cpp @@ -0,0 +1,122 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +#include + +void testStringification(DeserializationError error, std::string expected) { + REQUIRE(error.c_str() == expected); +} + +void testBoolification(DeserializationError error, bool expected) { + // DeserializationError on left-hand side + CHECK(bool(error) == expected); + CHECK(bool(error) != !expected); + CHECK(!bool(error) == !expected); + + // DeserializationError on right-hand side + CHECK(expected == bool(error)); + CHECK(!expected != bool(error)); + CHECK(!expected == !bool(error)); +} + +#define TEST_STRINGIFICATION(symbol) \ + testStringification(DeserializationError::symbol, #symbol) + +#define TEST_BOOLIFICATION(symbol, expected) \ + testBoolification(DeserializationError::symbol, expected) + +TEST_CASE("DeserializationError") { + SECTION("c_str()") { + TEST_STRINGIFICATION(Ok); + TEST_STRINGIFICATION(EmptyInput); + TEST_STRINGIFICATION(IncompleteInput); + TEST_STRINGIFICATION(InvalidInput); + TEST_STRINGIFICATION(NoMemory); + TEST_STRINGIFICATION(TooDeep); + } + + SECTION("as boolean") { + TEST_BOOLIFICATION(Ok, false); + TEST_BOOLIFICATION(EmptyInput, true); + TEST_BOOLIFICATION(IncompleteInput, true); + TEST_BOOLIFICATION(InvalidInput, true); + TEST_BOOLIFICATION(NoMemory, true); + TEST_BOOLIFICATION(TooDeep, true); + } + + SECTION("ostream DeserializationError") { + std::stringstream s; + s << DeserializationError(DeserializationError::InvalidInput); + REQUIRE(s.str() == "InvalidInput"); + } + + SECTION("ostream DeserializationError::Code") { + std::stringstream s; + s << DeserializationError::InvalidInput; + REQUIRE(s.str() == "InvalidInput"); + } + + SECTION("switch") { + DeserializationError err = DeserializationError::InvalidInput; + switch (err.code()) { + case DeserializationError::InvalidInput: + SUCCEED(); + break; + default: + FAIL(); + break; + } + } + + SECTION("Use in a condition") { + DeserializationError invalidInput(DeserializationError::InvalidInput); + DeserializationError ok(DeserializationError::Ok); + + SECTION("if (!err)") { + if (!invalidInput) + FAIL(); + } + + SECTION("if (err)") { + if (ok) + FAIL(); + } + } + + SECTION("Comparisons") { + DeserializationError invalidInput(DeserializationError::InvalidInput); + DeserializationError ok(DeserializationError::Ok); + + SECTION("DeserializationError == Code") { + REQUIRE(invalidInput == DeserializationError::InvalidInput); + REQUIRE(ok == DeserializationError::Ok); + } + + SECTION("Code == DeserializationError") { + REQUIRE(DeserializationError::InvalidInput == invalidInput); + REQUIRE(DeserializationError::Ok == ok); + } + + SECTION("DeserializationError != Code") { + REQUIRE(invalidInput != DeserializationError::Ok); + REQUIRE(ok != DeserializationError::InvalidInput); + } + + SECTION("Code != DeserializationError") { + REQUIRE(DeserializationError::Ok != invalidInput); + REQUIRE(DeserializationError::InvalidInput != ok); + } + + SECTION("DeserializationError == DeserializationError") { + REQUIRE_FALSE(invalidInput == ok); + } + + SECTION("DeserializationError != DeserializationError") { + REQUIRE(invalidInput != ok); + } + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDeserializer/array.cpp b/libraries/ArduinoJson/extras/tests/JsonDeserializer/array.cpp new file mode 100644 index 0000000..b30269c --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDeserializer/array.cpp @@ -0,0 +1,253 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("deserialize JSON array") { + DynamicJsonDocument doc(4096); + + SECTION("An empty array") { + DeserializationError err = deserializeJson(doc, "[]"); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(0 == arr.size()); + } + + SECTION("Spaces") { + SECTION("Before the opening bracket") { + DeserializationError err = deserializeJson(doc, " []"); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(0 == arr.size()); + } + + SECTION("Before first value") { + DeserializationError err = deserializeJson(doc, "[ \t\r\n42]"); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(1 == arr.size()); + REQUIRE(arr[0] == 42); + } + + SECTION("After first value") { + DeserializationError err = deserializeJson(doc, "[42 \t\r\n]"); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(1 == arr.size()); + REQUIRE(arr[0] == 42); + } + } + + SECTION("Values types") { + SECTION("On integer") { + DeserializationError err = deserializeJson(doc, "[42]"); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(1 == arr.size()); + REQUIRE(arr[0] == 42); + } + + SECTION("Two integers") { + DeserializationError err = deserializeJson(doc, "[42,84]"); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(2 == arr.size()); + REQUIRE(arr[0] == 42); + REQUIRE(arr[1] == 84); + } + + SECTION("Double") { + DeserializationError err = deserializeJson(doc, "[4.2,1e2]"); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(2 == arr.size()); + REQUIRE(arr[0] == 4.2); + REQUIRE(arr[1] == 1e2); + } + + SECTION("Unsigned long") { + DeserializationError err = deserializeJson(doc, "[4294967295]"); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(1 == arr.size()); + REQUIRE(arr[0] == 4294967295UL); + } + + SECTION("Boolean") { + DeserializationError err = deserializeJson(doc, "[true,false]"); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(2 == arr.size()); + REQUIRE(arr[0] == true); + REQUIRE(arr[1] == false); + } + + SECTION("Null") { + DeserializationError err = deserializeJson(doc, "[null,null]"); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(2 == arr.size()); + REQUIRE(arr[0].as() == 0); + REQUIRE(arr[1].as() == 0); + } + } + + SECTION("Quotes") { + SECTION("Double quotes") { + DeserializationError err = + deserializeJson(doc, "[ \"hello\" , \"world\" ]"); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(2 == arr.size()); + REQUIRE(arr[0] == "hello"); + REQUIRE(arr[1] == "world"); + } + + SECTION("Single quotes") { + DeserializationError err = deserializeJson(doc, "[ 'hello' , 'world' ]"); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(2 == arr.size()); + REQUIRE(arr[0] == "hello"); + REQUIRE(arr[1] == "world"); + } + + SECTION("No quotes") { + DeserializationError err = deserializeJson(doc, "[ hello , world ]"); + REQUIRE(err == DeserializationError::InvalidInput); + } + + SECTION("Double quotes (empty strings)") { + DeserializationError err = deserializeJson(doc, "[\"\",\"\"]"); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(2 == arr.size()); + REQUIRE(arr[0] == ""); + REQUIRE(arr[1] == ""); + } + + SECTION("Single quotes (empty strings)") { + DeserializationError err = deserializeJson(doc, "[\'\',\'\']"); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(2 == arr.size()); + REQUIRE(arr[0] == ""); + REQUIRE(arr[1] == ""); + } + + SECTION("No quotes (empty strings)") { + DeserializationError err = deserializeJson(doc, "[,]"); + + REQUIRE(err == DeserializationError::InvalidInput); + } + + SECTION("Closing single quotes missing") { + DeserializationError err = deserializeJson(doc, "[\"]"); + + REQUIRE(err == DeserializationError::IncompleteInput); + } + + SECTION("Closing double quotes missing") { + DeserializationError err = deserializeJson(doc, "[\']"); + + REQUIRE(err == DeserializationError::IncompleteInput); + } + } + + SECTION("Premature null-terminator") { + SECTION("After opening bracket") { + DeserializationError err = deserializeJson(doc, "["); + + REQUIRE(err == DeserializationError::IncompleteInput); + } + + SECTION("After value") { + DeserializationError err = deserializeJson(doc, "[1"); + + REQUIRE(err == DeserializationError::IncompleteInput); + } + + SECTION("After comma") { + DeserializationError err = deserializeJson(doc, "[1,"); + + REQUIRE(err == DeserializationError::IncompleteInput); + } + } + + SECTION("Premature end of input") { + const char* input = "[1,2]"; + + SECTION("After opening bracket") { + DeserializationError err = deserializeJson(doc, input, 1); + + REQUIRE(err == DeserializationError::IncompleteInput); + } + + SECTION("After value") { + DeserializationError err = deserializeJson(doc, input, 2); + + REQUIRE(err == DeserializationError::IncompleteInput); + } + + SECTION("After comma") { + DeserializationError err = deserializeJson(doc, input, 3); + + REQUIRE(err == DeserializationError::IncompleteInput); + } + } + + SECTION("Misc") { + SECTION("Nested objects") { + char jsonString[] = + " [ { \"a\" : 1 , \"b\" : 2 } , { \"c\" : 3 , \"d\" : 4 } ] "; + + DeserializationError err = deserializeJson(doc, jsonString); + JsonArray arr = doc.as(); + + JsonObject object1 = arr[0]; + const JsonObject object2 = arr[1]; + JsonObject object3 = arr[2]; + + REQUIRE(err == DeserializationError::Ok); + + REQUIRE(object1.isNull() == false); + REQUIRE(object2.isNull() == false); + REQUIRE(object3.isNull() == true); + + REQUIRE(2 == object1.size()); + REQUIRE(2 == object2.size()); + REQUIRE(0 == object3.size()); + + REQUIRE(1 == object1["a"].as()); + REQUIRE(2 == object1["b"].as()); + REQUIRE(3 == object2["c"].as()); + REQUIRE(4 == object2["d"].as()); + REQUIRE(0 == object3["e"].as()); + } + } + + SECTION("Should clear the JsonArray") { + deserializeJson(doc, "[1,2,3,4]"); + deserializeJson(doc, "[]"); + JsonArray arr = doc.as(); + + REQUIRE(arr.size() == 0); + REQUIRE(doc.memoryUsage() == JSON_ARRAY_SIZE(0)); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDeserializer/array_static.cpp b/libraries/ArduinoJson/extras/tests/JsonDeserializer/array_static.cpp new file mode 100644 index 0000000..2d1f538 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDeserializer/array_static.cpp @@ -0,0 +1,89 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("deserialize JSON array with a StaticJsonDocument") { + SECTION("BufferOfTheRightSizeForEmptyArray") { + StaticJsonDocument doc; + char input[] = "[]"; + + DeserializationError err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("TooSmallBufferForArrayWithOneValue") { + StaticJsonDocument doc; + char input[] = "[1]"; + + DeserializationError err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::NoMemory); + } + + SECTION("BufferOfTheRightSizeForArrayWithOneValue") { + StaticJsonDocument doc; + char input[] = "[1]"; + + DeserializationError err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("TooSmallBufferForArrayWithNestedObject") { + StaticJsonDocument doc; + char input[] = "[{}]"; + + DeserializationError err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::NoMemory); + } + + SECTION("BufferOfTheRightSizeForArrayWithNestedObject") { + StaticJsonDocument doc; + char input[] = "[{}]"; + + DeserializationError err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("CopyStringNotSpaces") { + StaticJsonDocument<100> doc; + + deserializeJson(doc, " [ \"1234567\" ] "); + + REQUIRE(JSON_ARRAY_SIZE(1) + JSON_STRING_SIZE(7) == doc.memoryUsage()); + // note: we use a string of 8 bytes to be sure that the StaticMemoryPool + // will not insert bytes to enforce alignement + } + + SECTION("Should clear the JsonArray") { + StaticJsonDocument doc; + char input[] = "[1,2,3,4]"; + + deserializeJson(doc, input); + deserializeJson(doc, "[]"); + + JsonArray arr = doc.as(); + REQUIRE(arr.size() == 0); + REQUIRE(doc.memoryUsage() == JSON_ARRAY_SIZE(0)); + } + + SECTION("Array") { + StaticJsonDocument doc; + char input[] = "[1,2]"; + + DeserializationError err = deserializeJson(doc, input); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(doc.memoryUsage() == JSON_ARRAY_SIZE(2)); + REQUIRE(arr[0] == 1); + REQUIRE(arr[1] == 2); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDeserializer/filter.cpp b/libraries/ArduinoJson/extras/tests/JsonDeserializer/filter.cpp new file mode 100644 index 0000000..f1c6e2e --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDeserializer/filter.cpp @@ -0,0 +1,809 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#define ARDUINOJSON_ENABLE_COMMENTS 1 +#include +#include + +#include +#include + +TEST_CASE("Filtering") { + struct TestCase { + const char* input; + const char* filter; + uint8_t nestingLimit; + DeserializationError error; + const char* output; + size_t memoryUsage; + }; + + // clang-format off + TestCase testCases[] = { + { + "{\"hello\":\"world\"}", // 1. input + "null", // 2. filter + 10, // 3. nestingLimit + DeserializationError::Ok, // 4. error + "null", // 5. output + 0 // 6. memoryUsage + }, + { + "{\"hello\":\"world\"}", + "false", + 10, + DeserializationError::Ok, + "null", + 0 + }, + { + "{\"abcdefg\":\"hijklmn\"}", + "true", + 10, + DeserializationError::Ok, + "{\"abcdefg\":\"hijklmn\"}", + JSON_OBJECT_SIZE(1) + 16 + }, + { + "{\"hello\":\"world\"}", + "{}", + 10, + DeserializationError::Ok, + "{}", + JSON_OBJECT_SIZE(0) + }, + { + // Input in an object, but filter wants an array + "{\"hello\":\"world\"}", + "[]", + 10, + DeserializationError::Ok, + "null", + 0 + }, + { + // Member is a string, but filter wants an array + "{\"example\":\"example\"}", + "{\"example\":[true]}", + 10, + DeserializationError::Ok, + "{\"example\":null}", + JSON_OBJECT_SIZE(1) + 8 + }, + { + // Member is a number, but filter wants an array + "{\"example\":42}", + "{\"example\":[true]}", + 10, + DeserializationError::Ok, + "{\"example\":null}", + JSON_OBJECT_SIZE(1) + 8 + }, + { + // Input is an array, but filter wants an object + "[\"hello\",\"world\"]", + "{}", + 10, + DeserializationError::Ok, + "null", + 0 + }, + { + // Input is a bool, but filter wants an object + "true", + "{}", + 10, + DeserializationError::Ok, + "null", + 0 + }, + { + // Input is a string, but filter wants an object + "\"hello\"", + "{}", + 10, + DeserializationError::Ok, + "null", + 0 + }, + { + // skip an integer + "{\"an_integer\":666,example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + JSON_OBJECT_SIZE(1) + 8 + }, + { + // skip a float + "{\"a_float\":12.34e-6,example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + JSON_OBJECT_SIZE(1) + 8 + }, + { + // skip false + "{\"a_bool\":false,example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + JSON_OBJECT_SIZE(1) + 8 + }, + { + // skip true + "{\"a_bool\":true,example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + JSON_OBJECT_SIZE(1) + 8 + }, + { + // skip null + "{\"a_bool\":null,example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + JSON_OBJECT_SIZE(1) + 8 + }, + { + // can skip a double-quoted string + "{\"a_double_quoted_string\":\"hello\",example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + JSON_OBJECT_SIZE(1) + 8 + }, + { + // can skip a single-quoted string + "{\"a_single_quoted_string\":'hello',example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + JSON_OBJECT_SIZE(1) + 8 + }, + { + // can skip an empty array + "{\"an_empty_array\":[],example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + JSON_OBJECT_SIZE(1) + 8 + }, + { + // can skip an empty array with spaces in it + "{\"an_empty_array\":[\t],example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + JSON_OBJECT_SIZE(1) + 8 + }, + { + // can skip an array + "{\"an_array\":[1,2,3],example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + JSON_OBJECT_SIZE(1) + 8 + }, + { + // can skip an array with spaces in it + "{\"an_array\": [ 1 , 2 , 3 ] ,example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + JSON_OBJECT_SIZE(1) + 8 + }, + { + // can skip an empty object + "{\"an_empty_object\":{},example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + JSON_OBJECT_SIZE(1) + 8 + }, + { + // can skip an empty object with spaces in it + "{\"an_empty_object\":{ },example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + JSON_OBJECT_SIZE(1) + 8 + }, + { + // can skip an object + "{\"an_object\":{a:1,'b':2,\"c\":3},example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + JSON_OBJECT_SIZE(1) + 8 + }, + { + // skip an object with spaces in it + "{\"an_object\" : { a : 1 , 'b' : 2 , \"c\" : 3 } ,example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + JSON_OBJECT_SIZE(1) + 8 + }, + { + "{\"an_integer\": 0,\"example\":{\"type\":\"int\",\"outcome\":42}}", + "{\"example\":{\"outcome\":true}}", + 10, + DeserializationError::Ok, + "{\"example\":{\"outcome\":42}}", + 2 * JSON_OBJECT_SIZE(1) + 16 + }, + { + // wildcard + "{\"example\":{\"type\":\"int\",\"outcome\":42}}", + "{\"*\":{\"outcome\":true}}", + 10, + DeserializationError::Ok, + "{\"example\":{\"outcome\":42}}", + 2 * JSON_OBJECT_SIZE(1) + 16 + }, + { + // exclusion filter (issue #1628) + "{\"example\":1,\"ignored\":2}", + "{\"*\":true,\"ignored\":false}", + 10, + DeserializationError::Ok, + "{\"example\":1}", + JSON_OBJECT_SIZE(1) + 8 + }, + { + // only the first element of array counts + "[1,2,3]", + "[true, false]", + 10, + DeserializationError::Ok, + "[1,2,3]", + JSON_ARRAY_SIZE(3) + }, + { + // only the first element of array counts + "[1,2,3]", + "[false, true]", + 10, + DeserializationError::Ok, + "[]", + JSON_ARRAY_SIZE(0) + }, + { + // filter members of object in array + "[{\"example\":1,\"ignore\":2},{\"example\":3,\"ignore\":4}]", + "[{\"example\":true}]", + 10, + DeserializationError::Ok, + "[{\"example\":1},{\"example\":3}]", + JSON_ARRAY_SIZE(2) + 2 * JSON_OBJECT_SIZE(1) + 8 + }, + { + "[',2,3]", + "[false,true]", + 10, + DeserializationError::IncompleteInput, + "[]", + JSON_ARRAY_SIZE(0) + }, + { + "[\",2,3]", + "[false,true]", + 10, + DeserializationError::IncompleteInput, + "[]", + JSON_ARRAY_SIZE(0) + }, + { + // detect errors in skipped value + "[!,2,\\]", + "[false]", + 10, + DeserializationError::InvalidInput, + "[]", + JSON_ARRAY_SIZE(0) + }, + { + // detect incomplete string event if it's skipped + "\"ABC", + "false", + 10, + DeserializationError::IncompleteInput, + "null", + 0 + }, + { + // detect incomplete string event if it's skipped + "'ABC", + "false", + 10, + DeserializationError::IncompleteInput, + "null", + 0 + }, + { + // handle escaped quotes + "'A\\'BC'", + "false", + 10, + DeserializationError::Ok, + "null", + 0 + }, + { + // handle escaped quotes + "\"A\\\"BC\"", + "false", + 10, + DeserializationError::Ok, + "null", + 0 + }, + { + // detect incomplete string in presence of escaped quotes + "'A\\'BC", + "false", + 10, + DeserializationError::IncompleteInput, + "null", + 0 + }, + { + // detect incomplete string in presence of escaped quotes + "\"A\\\"BC", + "false", + 10, + DeserializationError::IncompleteInput, + "null", + 0 + }, + { + // skip empty array + "[]", + "false", + 10, + DeserializationError::Ok, + "null", + 0 + }, + { + // skip empty array with spaces + " [ ] ", + "false", + 10, + DeserializationError::Ok, + "null", + 0 + }, + { + // bubble up element error even if array is skipped + "[1,'2,3]", + "false", + 10, + DeserializationError::IncompleteInput, + "null", + 0 + }, + { + // bubble up member error even if object is skipped + "{'hello':'worl}", + "false", + 10, + DeserializationError::IncompleteInput, + "null", + 0 + }, + { + // bubble up colon error even if object is skipped + "{'hello','world'}", + "false", + 10, + DeserializationError::InvalidInput, + "null", + 0 + }, + { + // bubble up key error even if object is skipped + "{'hello:1}", + "false", + 10, + DeserializationError::IncompleteInput, + "null", + 0 + }, + { + // detect invalid value in skipped object + "{'hello':!}", + "false", + 10, + DeserializationError::InvalidInput, + "null", + 0 + }, + { + // ignore invalid value in skipped object + "{'hello':\\}", + "false", + 10, + DeserializationError::InvalidInput, + "null", + 0 + }, + { + // check nesting limit even for ignored objects + "{}", + "false", + 0, + DeserializationError::TooDeep, + "null", + 0 + }, + { + // check nesting limit even for ignored objects + "{'hello':{}}", + "false", + 1, + DeserializationError::TooDeep, + "null", + 0 + }, + { + // check nesting limit even for ignored values in objects + "{'hello':{}}", + "{}", + 1, + DeserializationError::TooDeep, + "{}", + JSON_OBJECT_SIZE(0) + }, + { + // check nesting limit even for ignored arrays + "[]", + "false", + 0, + DeserializationError::TooDeep, + "null", + 0 + }, + { + // check nesting limit even for ignored arrays + "[[]]", + "false", + 1, + DeserializationError::TooDeep, + "null", + 0 + }, + { + // check nesting limit even for ignored values in arrays + "[[]]", + "[]", + 1, + DeserializationError::TooDeep, + "[]", + JSON_ARRAY_SIZE(0) + }, + { + // supports back-slash at the end of skipped string + "\"hell\\", + "false", + 1, + DeserializationError::IncompleteInput, + "null", + 0 + }, + { + // invalid comment at after an element in a skipped array + "[1/]", + "false", + 10, + DeserializationError::InvalidInput, + "null", + 0 + }, + { + // incomplete comment at after an element in a skipped array + "[1/*]", + "false", + 10, + DeserializationError::IncompleteInput, + "null", + 0 + }, + { + // missing comma in a skipped array + "[1 2]", + "false", + 10, + DeserializationError::InvalidInput, + "null", + 0 + }, + { + // invalid comment at the beginning of array + "[/1]", + "[false]", + 10, + DeserializationError::InvalidInput, + "[]", + JSON_ARRAY_SIZE(0) + }, + { + // incomplete comment at the begining of an array + "[/*]", + "[false]", + 10, + DeserializationError::IncompleteInput, + "[]", + JSON_ARRAY_SIZE(0) + }, + { + // invalid comment before key + "{/1:2}", + "{}", + 10, + DeserializationError::InvalidInput, + "{}", + JSON_OBJECT_SIZE(0) + }, + { + // incomplete comment before key + "{/*:2}", + "{}", + 10, + DeserializationError::IncompleteInput, + "{}", + JSON_OBJECT_SIZE(0) + }, + { + // invalid comment after key + "{\"example\"/1:2}", + "{}", + 10, + DeserializationError::InvalidInput, + "{}", + JSON_OBJECT_SIZE(0) + }, + { + // incomplete comment after key + "{\"example\"/*:2}", + "{}", + 10, + DeserializationError::IncompleteInput, + "{}", + JSON_OBJECT_SIZE(0) + }, + { + // invalid comment after colon + "{\"example\":/12}", + "{}", + 10, + DeserializationError::InvalidInput, + "{}", + JSON_OBJECT_SIZE(0) + }, + { + // incomplete comment after colon + "{\"example\":/*2}", + "{}", + 10, + DeserializationError::IncompleteInput, + "{}", + JSON_OBJECT_SIZE(0) + }, + { + // comment next to an integer + "{\"ignore\":1//,\"example\":2\n}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{}", + JSON_OBJECT_SIZE(0) + }, + { + // invalid comment after opening brace of a skipped object + "{/1:2}", + "false", + 10, + DeserializationError::InvalidInput, + "null", + 0 + }, + { + // incomplete after opening brace of a skipped object + "{/*:2}", + "false", + 10, + DeserializationError::IncompleteInput, + "null", + 0 + }, + { + // invalid comment after key of a skipped object + "{\"example\"/:2}", + "false", + 10, + DeserializationError::InvalidInput, + "null", + 0 + }, + { + // incomplete comment after key of a skipped object + "{\"example\"/*:2}", + "false", + 10, + DeserializationError::IncompleteInput, + "null", + 0 + }, + { + // invalid comment after value in a skipped object + "{\"example\":2/}", + "false", + 10, + DeserializationError::InvalidInput, + "null", + 0 + }, + { + // incomplete comment after value of a skipped object + "{\"example\":2/*}", + "false", + 10, + DeserializationError::IncompleteInput, + "null", + 0 + }, + { + // incomplete comment after comma in skipped object + "{\"example\":2,/*}", + "false", + 10, + DeserializationError::IncompleteInput, + "null", + 0 + }, + }; // clang-format on + + for (size_t i = 0; i < sizeof(testCases) / sizeof(testCases[0]); i++) { + CAPTURE(i); + + DynamicJsonDocument filter(256); + DynamicJsonDocument doc(256); + TestCase& tc = testCases[i]; + + CAPTURE(tc.filter); + REQUIRE(deserializeJson(filter, tc.filter) == DeserializationError::Ok); + + CAPTURE(tc.input); + CAPTURE(tc.nestingLimit); + CHECK(deserializeJson(doc, tc.input, DeserializationOption::Filter(filter), + DeserializationOption::NestingLimit( + tc.nestingLimit)) == tc.error); + + CHECK(doc.as() == tc.output); + CHECK(doc.memoryUsage() == tc.memoryUsage); + } +} + +TEST_CASE("Zero-copy mode") { // issue #1697 + char input[] = "{\"include\":42,\"exclude\":666}"; + + StaticJsonDocument<256> filter; + filter["include"] = true; + + StaticJsonDocument<256> doc; + DeserializationError err = + deserializeJson(doc, input, DeserializationOption::Filter(filter)); + + REQUIRE(err == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); +} + +TEST_CASE("Overloads") { + StaticJsonDocument<256> doc; + StaticJsonDocument<256> filter; + + using namespace DeserializationOption; + + // deserializeJson(..., Filter) + + SECTION("const char*, Filter") { + deserializeJson(doc, "{}", Filter(filter)); + } + + SECTION("const char*, size_t, Filter") { + deserializeJson(doc, "{}", 2, Filter(filter)); + } + + SECTION("const std::string&, Filter") { + deserializeJson(doc, std::string("{}"), Filter(filter)); + } + + SECTION("std::istream&, Filter") { + std::stringstream s("{}"); + deserializeJson(doc, s, Filter(filter)); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("char[n], Filter") { + size_t i = 4; + char vla[i]; + strcpy(vla, "{}"); + deserializeJson(doc, vla, Filter(filter)); + } +#endif + + // deserializeJson(..., Filter, NestingLimit) + + SECTION("const char*, Filter, NestingLimit") { + deserializeJson(doc, "{}", Filter(filter), NestingLimit(5)); + } + + SECTION("const char*, size_t, Filter, NestingLimit") { + deserializeJson(doc, "{}", 2, Filter(filter), NestingLimit(5)); + } + + SECTION("const std::string&, Filter, NestingLimit") { + deserializeJson(doc, std::string("{}"), Filter(filter), NestingLimit(5)); + } + + SECTION("std::istream&, Filter, NestingLimit") { + std::stringstream s("{}"); + deserializeJson(doc, s, Filter(filter), NestingLimit(5)); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("char[n], Filter, NestingLimit") { + size_t i = 4; + char vla[i]; + strcpy(vla, "{}"); + deserializeJson(doc, vla, Filter(filter), NestingLimit(5)); + } +#endif + + // deserializeJson(..., NestingLimit, Filter) + + SECTION("const char*, NestingLimit, Filter") { + deserializeJson(doc, "{}", NestingLimit(5), Filter(filter)); + } + + SECTION("const char*, size_t, NestingLimit, Filter") { + deserializeJson(doc, "{}", 2, NestingLimit(5), Filter(filter)); + } + + SECTION("const std::string&, NestingLimit, Filter") { + deserializeJson(doc, std::string("{}"), NestingLimit(5), Filter(filter)); + } + + SECTION("std::istream&, NestingLimit, Filter") { + std::stringstream s("{}"); + deserializeJson(doc, s, NestingLimit(5), Filter(filter)); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("char[n], NestingLimit, Filter") { + size_t i = 4; + char vla[i]; + strcpy(vla, "{}"); + deserializeJson(doc, vla, NestingLimit(5), Filter(filter)); + } +#endif +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDeserializer/incomplete_input.cpp b/libraries/ArduinoJson/extras/tests/JsonDeserializer/incomplete_input.cpp new file mode 100644 index 0000000..a34aede --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDeserializer/incomplete_input.cpp @@ -0,0 +1,29 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#define ARDUINOJSON_DECODE_UNICODE 1 +#include +#include + +TEST_CASE("Truncated JSON input") { + const char* testCases[] = {"\"hello", "\'hello", "'\\u", "'\\u00", "'\\u000", + // false + "f", "fa", "fal", "fals", + // true + "t", "tr", "tru", + // null + "n", "nu", "nul", + // object + "{", "{a", "{a:", "{a:1", "{a:1,", "{a:1,"}; + const size_t testCount = sizeof(testCases) / sizeof(testCases[0]); + + DynamicJsonDocument doc(4096); + + for (size_t i = 0; i < testCount; i++) { + const char* input = testCases[i]; + CAPTURE(input); + REQUIRE(deserializeJson(doc, input) == + DeserializationError::IncompleteInput); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDeserializer/input_types.cpp b/libraries/ArduinoJson/extras/tests/JsonDeserializer/input_types.cpp new file mode 100644 index 0000000..788319f --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDeserializer/input_types.cpp @@ -0,0 +1,222 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include + +#include +#include + +#include "CustomReader.hpp" + +TEST_CASE("deserializeJson(char*)") { + StaticJsonDocument<1024> doc; + + SECTION("should not duplicate strings") { + char input[] = "{\"hello\":\"world\"}"; + + DeserializationError err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::Ok); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1)); + CHECK(doc.as().memoryUsage() == + JSON_OBJECT_SIZE(1)); // issue #1318 + } +} + +TEST_CASE("deserializeJson(unsigned char*, unsigned int)") { // issue #1897 + StaticJsonDocument<1024> doc; + + unsigned char input[] = "{\"hello\":\"world\"}"; + unsigned char* input_ptr = input; + unsigned int size = sizeof(input); + + DeserializationError err = deserializeJson(doc, input_ptr, size); + + REQUIRE(err == DeserializationError::Ok); +} + +TEST_CASE("deserializeJson(uint8_t*, size_t)") { // issue #1898 + StaticJsonDocument<1024> doc; + + uint8_t input[] = "{\"hello\":\"world\"}"; + uint8_t* input_ptr = input; + size_t size = sizeof(input); + + DeserializationError err = deserializeJson(doc, input_ptr, size); + + REQUIRE(err == DeserializationError::Ok); +} + +TEST_CASE("deserializeJson(const std::string&)") { + DynamicJsonDocument doc(4096); + + SECTION("should accept const string") { + const std::string input("[42]"); + + DeserializationError err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("should accept temporary string") { + DeserializationError err = deserializeJson(doc, std::string("[42]")); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("should duplicate content") { + std::string input("[\"hello\"]"); + + DeserializationError err = deserializeJson(doc, input); + input[2] = 'X'; // alter the string tomake sure we made a copy + + JsonArray array = doc.as(); + REQUIRE(err == DeserializationError::Ok); + REQUIRE(std::string("hello") == array[0]); + } +} + +TEST_CASE("deserializeJson(std::istream&)") { + DynamicJsonDocument doc(4096); + + SECTION("array") { + std::istringstream json(" [ 42 ] "); + + DeserializationError err = deserializeJson(doc, json); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(1 == arr.size()); + REQUIRE(42 == arr[0]); + } + + SECTION("object") { + std::istringstream json(" { hello : 'world' }"); + + DeserializationError err = deserializeJson(doc, json); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(1 == obj.size()); + REQUIRE(std::string("world") == obj["hello"]); + } + + SECTION("Should not read after the closing brace of an empty object") { + std::istringstream json("{}123"); + + deserializeJson(doc, json); + + REQUIRE('1' == char(json.get())); + } + + SECTION("Should not read after the closing brace") { + std::istringstream json("{\"hello\":\"world\"}123"); + + deserializeJson(doc, json); + + REQUIRE('1' == char(json.get())); + } + + SECTION("Should not read after the closing bracket of an empty array") { + std::istringstream json("[]123"); + + deserializeJson(doc, json); + + REQUIRE('1' == char(json.get())); + } + + SECTION("Should not read after the closing bracket") { + std::istringstream json("[\"hello\",\"world\"]123"); + + deserializeJson(doc, json); + + REQUIRE('1' == char(json.get())); + } + + SECTION("Should not read after the closing quote") { + std::istringstream json("\"hello\"123"); + + deserializeJson(doc, json); + + REQUIRE('1' == char(json.get())); + } +} + +#ifdef HAS_VARIABLE_LENGTH_ARRAY +TEST_CASE("deserializeJson(VLA)") { + size_t i = 9; + char vla[i]; + strcpy(vla, "{\"a\":42}"); + + StaticJsonDocument doc; + DeserializationError err = deserializeJson(doc, vla); + + REQUIRE(err == DeserializationError::Ok); +} +#endif + +TEST_CASE("deserializeJson(CustomReader)") { + DynamicJsonDocument doc(4096); + CustomReader reader("[4,2]"); + DeserializationError err = deserializeJson(doc, reader); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.size() == 2); + REQUIRE(doc[0] == 4); + REQUIRE(doc[1] == 2); +} + +TEST_CASE("deserializeJson(JsonDocument&, MemberProxy)") { + DynamicJsonDocument doc1(4096); + doc1["payload"] = "[4,2]"; + + DynamicJsonDocument doc2(4096); + DeserializationError err = deserializeJson(doc2, doc1["payload"]); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc2.size() == 2); + REQUIRE(doc2[0] == 4); + REQUIRE(doc2[1] == 2); +} + +TEST_CASE("deserializeJson(JsonDocument&, JsonVariant)") { + DynamicJsonDocument doc1(4096); + doc1["payload"] = "[4,2]"; + + DynamicJsonDocument doc2(4096); + DeserializationError err = + deserializeJson(doc2, doc1["payload"].as()); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc2.size() == 2); + REQUIRE(doc2[0] == 4); + REQUIRE(doc2[1] == 2); +} + +TEST_CASE("deserializeJson(JsonDocument&, JsonVariantConst)") { + DynamicJsonDocument doc1(4096); + doc1["payload"] = "[4,2]"; + + DynamicJsonDocument doc2(4096); + DeserializationError err = + deserializeJson(doc2, doc1["payload"].as()); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc2.size() == 2); + REQUIRE(doc2[0] == 4); + REQUIRE(doc2[1] == 2); +} + +TEST_CASE("deserializeJson(JsonDocument&, ElementProxy)") { + DynamicJsonDocument doc1(4096); + doc1[0] = "[4,2]"; + + DynamicJsonDocument doc2(4096); + DeserializationError err = deserializeJson(doc2, doc1[0]); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc2.size() == 2); + REQUIRE(doc2[0] == 4); + REQUIRE(doc2[1] == 2); +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDeserializer/invalid_input.cpp b/libraries/ArduinoJson/extras/tests/JsonDeserializer/invalid_input.cpp new file mode 100644 index 0000000..52b5038 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDeserializer/invalid_input.cpp @@ -0,0 +1,40 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#define ARDUINOJSON_DECODE_UNICODE 1 +#include +#include + +TEST_CASE("Invalid JSON input") { + const char* testCases[] = {"'\\u'", "'\\u000g'", "'\\u000'", "'\\u000G'", + "'\\u000/'", "\\x1234", "6a9", "1,", + "nulL", "tru3", "fals3", "2]", + "3}"}; + const size_t testCount = sizeof(testCases) / sizeof(testCases[0]); + + DynamicJsonDocument doc(4096); + + for (size_t i = 0; i < testCount; i++) { + const char* input = testCases[i]; + CAPTURE(input); + REQUIRE(deserializeJson(doc, input) == DeserializationError::InvalidInput); + } +} + +TEST_CASE("Invalid JSON input that should pass") { + const char* testCases[] = { + "'\\ud83d'", // leading surrogate without a trailing surrogate + "'\\udda4'", // trailing surrogate without a leading surrogate + "'\\ud83d\\ud83d'", // two leading surrogates + }; + const size_t testCount = sizeof(testCases) / sizeof(testCases[0]); + + DynamicJsonDocument doc(4096); + + for (size_t i = 0; i < testCount; i++) { + const char* input = testCases[i]; + CAPTURE(input); + REQUIRE(deserializeJson(doc, input) == DeserializationError::Ok); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDeserializer/misc.cpp b/libraries/ArduinoJson/extras/tests/JsonDeserializer/misc.cpp new file mode 100644 index 0000000..4f22de1 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDeserializer/misc.cpp @@ -0,0 +1,117 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +using namespace Catch::Matchers; + +TEST_CASE("deserializeJson(DynamicJsonDocument&)") { + DynamicJsonDocument doc(4096); + + SECTION("Edge cases") { + SECTION("null char*") { + DeserializationError err = deserializeJson(doc, static_cast(0)); + + REQUIRE(err != DeserializationError::Ok); + } + + SECTION("null const char*") { + DeserializationError err = + deserializeJson(doc, static_cast(0)); + + REQUIRE(err != DeserializationError::Ok); + } + + SECTION("Empty input") { + DeserializationError err = deserializeJson(doc, ""); + + REQUIRE(err == DeserializationError::EmptyInput); + } + + SECTION("Only spaces") { + DeserializationError err = deserializeJson(doc, " \t\n\r"); + + REQUIRE(err == DeserializationError::EmptyInput); + } + + SECTION("issue #628") { + DeserializationError err = deserializeJson(doc, "null"); + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is() == false); + } + + SECTION("Garbage") { + DeserializationError err = deserializeJson(doc, "%*$£¤"); + + REQUIRE(err == DeserializationError::InvalidInput); + } + } + + SECTION("Booleans") { + SECTION("True") { + DeserializationError err = deserializeJson(doc, "true"); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(doc.as() == true); + } + + SECTION("False") { + DeserializationError err = deserializeJson(doc, "false"); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(doc.as() == false); + } + } + + SECTION("Premature null-terminator") { + SECTION("In escape sequence") { + DeserializationError err = deserializeJson(doc, "\"\\"); + + REQUIRE(err == DeserializationError::IncompleteInput); + } + + SECTION("In double quoted string") { + DeserializationError err = deserializeJson(doc, "\"hello"); + + REQUIRE(err == DeserializationError::IncompleteInput); + } + + SECTION("In single quoted string") { + DeserializationError err = deserializeJson(doc, "'hello"); + + REQUIRE(err == DeserializationError::IncompleteInput); + } + } + + SECTION("Premature end of input") { + SECTION("In escape sequence") { + DeserializationError err = deserializeJson(doc, "\"\\n\"", 2); + + REQUIRE(err == DeserializationError::IncompleteInput); + } + + SECTION("In double quoted string") { + DeserializationError err = deserializeJson(doc, "\"hello\"", 6); + + REQUIRE(err == DeserializationError::IncompleteInput); + } + + SECTION("In single quoted string") { + DeserializationError err = deserializeJson(doc, "'hello'", 6); + + REQUIRE(err == DeserializationError::IncompleteInput); + } + } + + SECTION("Should clear the JsonVariant") { + deserializeJson(doc, "[1,2,3]"); + deserializeJson(doc, "{}"); + + REQUIRE(doc.is()); + REQUIRE(doc.memoryUsage() == JSON_OBJECT_SIZE(0)); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDeserializer/nestingLimit.cpp b/libraries/ArduinoJson/extras/tests/JsonDeserializer/nestingLimit.cpp new file mode 100644 index 0000000..cf55dc8 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDeserializer/nestingLimit.cpp @@ -0,0 +1,103 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +#include + +#define SHOULD_WORK(expression) REQUIRE(DeserializationError::Ok == expression); +#define SHOULD_FAIL(expression) \ + REQUIRE(DeserializationError::TooDeep == expression); + +TEST_CASE("JsonDeserializer nesting") { + DynamicJsonDocument doc(4096); + + SECTION("Input = const char*") { + SECTION("limit = 0") { + DeserializationOption::NestingLimit nesting(0); + SHOULD_WORK(deserializeJson(doc, "\"toto\"", nesting)); + SHOULD_WORK(deserializeJson(doc, "123", nesting)); + SHOULD_WORK(deserializeJson(doc, "true", nesting)); + SHOULD_FAIL(deserializeJson(doc, "[]", nesting)); + SHOULD_FAIL(deserializeJson(doc, "{}", nesting)); + SHOULD_FAIL(deserializeJson(doc, "[\"toto\"]", nesting)); + SHOULD_FAIL(deserializeJson(doc, "{\"toto\":1}", nesting)); + } + + SECTION("limit = 1") { + DeserializationOption::NestingLimit nesting(1); + SHOULD_WORK(deserializeJson(doc, "[\"toto\"]", nesting)); + SHOULD_WORK(deserializeJson(doc, "{\"toto\":1}", nesting)); + SHOULD_FAIL(deserializeJson(doc, "{\"toto\":{}}", nesting)); + SHOULD_FAIL(deserializeJson(doc, "{\"toto\":[]}", nesting)); + SHOULD_FAIL(deserializeJson(doc, "[[\"toto\"]]", nesting)); + SHOULD_FAIL(deserializeJson(doc, "[{\"toto\":1}]", nesting)); + } + } + + SECTION("char* and size_t") { + SECTION("limit = 0") { + DeserializationOption::NestingLimit nesting(0); + SHOULD_WORK(deserializeJson(doc, "\"toto\"", 6, nesting)); + SHOULD_WORK(deserializeJson(doc, "123", 3, nesting)); + SHOULD_WORK(deserializeJson(doc, "true", 4, nesting)); + SHOULD_FAIL(deserializeJson(doc, "[]", 2, nesting)); + SHOULD_FAIL(deserializeJson(doc, "{}", 2, nesting)); + SHOULD_FAIL(deserializeJson(doc, "[\"toto\"]", 8, nesting)); + SHOULD_FAIL(deserializeJson(doc, "{\"toto\":1}", 10, nesting)); + } + + SECTION("limit = 1") { + DeserializationOption::NestingLimit nesting(1); + SHOULD_WORK(deserializeJson(doc, "[\"toto\"]", 8, nesting)); + SHOULD_WORK(deserializeJson(doc, "{\"toto\":1}", 10, nesting)); + SHOULD_FAIL(deserializeJson(doc, "{\"toto\":{}}", 11, nesting)); + SHOULD_FAIL(deserializeJson(doc, "{\"toto\":[]}", 11, nesting)); + SHOULD_FAIL(deserializeJson(doc, "[[\"toto\"]]", 10, nesting)); + SHOULD_FAIL(deserializeJson(doc, "[{\"toto\":1}]", 12, nesting)); + } + } + + SECTION("Input = std::string") { + SECTION("limit = 0") { + DeserializationOption::NestingLimit nesting(0); + SHOULD_WORK(deserializeJson(doc, std::string("\"toto\""), nesting)); + SHOULD_WORK(deserializeJson(doc, std::string("123"), nesting)); + SHOULD_WORK(deserializeJson(doc, std::string("true"), nesting)); + SHOULD_FAIL(deserializeJson(doc, std::string("[]"), nesting)); + SHOULD_FAIL(deserializeJson(doc, std::string("{}"), nesting)); + SHOULD_FAIL(deserializeJson(doc, std::string("[\"toto\"]"), nesting)); + SHOULD_FAIL(deserializeJson(doc, std::string("{\"toto\":1}"), nesting)); + } + + SECTION("limit = 1") { + DeserializationOption::NestingLimit nesting(1); + SHOULD_WORK(deserializeJson(doc, std::string("[\"toto\"]"), nesting)); + SHOULD_WORK(deserializeJson(doc, std::string("{\"toto\":1}"), nesting)); + SHOULD_FAIL(deserializeJson(doc, std::string("{\"toto\":{}}"), nesting)); + SHOULD_FAIL(deserializeJson(doc, std::string("{\"toto\":[]}"), nesting)); + SHOULD_FAIL(deserializeJson(doc, std::string("[[\"toto\"]]"), nesting)); + SHOULD_FAIL(deserializeJson(doc, std::string("[{\"toto\":1}]"), nesting)); + } + } + + SECTION("Input = std::istream") { + SECTION("limit = 0") { + DeserializationOption::NestingLimit nesting(0); + std::istringstream good("true"); + std::istringstream bad("[]"); + SHOULD_WORK(deserializeJson(doc, good, nesting)); + SHOULD_FAIL(deserializeJson(doc, bad, nesting)); + } + + SECTION("limit = 1") { + DeserializationOption::NestingLimit nesting(1); + std::istringstream good("[\"toto\"]"); + std::istringstream bad("{\"toto\":{}}"); + SHOULD_WORK(deserializeJson(doc, good, nesting)); + SHOULD_FAIL(deserializeJson(doc, bad, nesting)); + } + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDeserializer/number.cpp b/libraries/ArduinoJson/extras/tests/JsonDeserializer/number.cpp new file mode 100644 index 0000000..05cf89e --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDeserializer/number.cpp @@ -0,0 +1,133 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#define ARDUINOJSON_USE_LONG_LONG 0 +#define ARDUINOJSON_ENABLE_NAN 1 +#define ARDUINOJSON_ENABLE_INFINITY 1 + +#include +#include +#include + +namespace my { +using ArduinoJson::detail::isinf; +using ArduinoJson::detail::isnan; +} // namespace my + +TEST_CASE("deserialize an integer") { + DynamicJsonDocument doc(4096); + + SECTION("Integer") { + SECTION("0") { + DeserializationError err = deserializeJson(doc, "0"); + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is() == true); + REQUIRE(doc.as() == 0); + REQUIRE(doc.as() == "0"); // issue #808 + } + + SECTION("Negative") { + DeserializationError err = deserializeJson(doc, "-42"); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE_FALSE(doc.is()); + REQUIRE(doc.as() == -42); + } + +#if LONG_MAX == 2147483647 + SECTION("LONG_MAX") { + DeserializationError err = deserializeJson(doc, "2147483647"); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is() == true); + REQUIRE(doc.as() == LONG_MAX); + } + + SECTION("LONG_MAX + 1") { + DeserializationError err = deserializeJson(doc, "2147483648"); + + CAPTURE(LONG_MIN); + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is() == false); + REQUIRE(doc.is() == true); + } +#endif + +#if LONG_MIN == -2147483648 + SECTION("LONG_MIN") { + DeserializationError err = deserializeJson(doc, "-2147483648"); + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is() == true); + REQUIRE(doc.as() == LONG_MIN); + } + + SECTION("LONG_MIN - 1") { + DeserializationError err = deserializeJson(doc, "-2147483649"); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is() == false); + REQUIRE(doc.is() == true); + } +#endif + +#if ULONG_MAX == 4294967295 + SECTION("ULONG_MAX") { + DeserializationError err = deserializeJson(doc, "4294967295"); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is() == true); + REQUIRE(doc.as() == ULONG_MAX); + REQUIRE(doc.is() == false); + } + + SECTION("ULONG_MAX + 1") { + DeserializationError err = deserializeJson(doc, "4294967296"); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is() == false); + REQUIRE(doc.is() == true); + } +#endif + } + + SECTION("Floats") { + SECTION("Double") { + DeserializationError err = deserializeJson(doc, "-1.23e+4"); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE_FALSE(doc.is()); + REQUIRE(doc.is()); + REQUIRE(doc.as() == Approx(-1.23e+4)); + } + + SECTION("NaN") { + DeserializationError err = deserializeJson(doc, "NaN"); + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is() == true); + REQUIRE(my::isnan(doc.as())); + } + + SECTION("Infinity") { + DeserializationError err = deserializeJson(doc, "Infinity"); + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is() == true); + REQUIRE(my::isinf(doc.as())); + } + + SECTION("+Infinity") { + DeserializationError err = deserializeJson(doc, "+Infinity"); + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is() == true); + REQUIRE(my::isinf(doc.as())); + } + + SECTION("-Infinity") { + DeserializationError err = deserializeJson(doc, "-Infinity"); + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is() == true); + REQUIRE(my::isinf(doc.as())); + } + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDeserializer/object.cpp b/libraries/ArduinoJson/extras/tests/JsonDeserializer/object.cpp new file mode 100644 index 0000000..814258e --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDeserializer/object.cpp @@ -0,0 +1,315 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("deserialize JSON object") { + DynamicJsonDocument doc(4096); + + SECTION("An empty object") { + DeserializationError err = deserializeJson(doc, "{}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(obj.size() == 0); + } + + SECTION("Quotes") { + SECTION("Double quotes") { + DeserializationError err = deserializeJson(doc, "{\"key\":\"value\"}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(obj.size() == 1); + REQUIRE(obj["key"] == "value"); + } + + SECTION("Single quotes") { + DeserializationError err = deserializeJson(doc, "{'key':'value'}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(obj.size() == 1); + REQUIRE(obj["key"] == "value"); + } + + SECTION("No quotes") { + DeserializationError err = deserializeJson(doc, "{key:'value'}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(obj.size() == 1); + REQUIRE(obj["key"] == "value"); + } + + SECTION("No quotes, allow underscore in key") { + DeserializationError err = deserializeJson(doc, "{_k_e_y_:42}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(obj.size() == 1); + REQUIRE(obj["_k_e_y_"] == 42); + } + } + + SECTION("Spaces") { + SECTION("Before the key") { + DeserializationError err = deserializeJson(doc, "{ \"key\":\"value\"}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(obj.size() == 1); + REQUIRE(obj["key"] == "value"); + } + + SECTION("After the key") { + DeserializationError err = deserializeJson(doc, "{\"key\" :\"value\"}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(obj.size() == 1); + REQUIRE(obj["key"] == "value"); + } + + SECTION("Before the value") { + DeserializationError err = deserializeJson(doc, "{\"key\": \"value\"}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(obj.size() == 1); + REQUIRE(obj["key"] == "value"); + } + + SECTION("After the value") { + DeserializationError err = deserializeJson(doc, "{\"key\":\"value\" }"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(obj.size() == 1); + REQUIRE(obj["key"] == "value"); + } + + SECTION("Before the comma") { + DeserializationError err = + deserializeJson(doc, "{\"key1\":\"value1\" ,\"key2\":\"value2\"}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(obj.size() == 2); + REQUIRE(obj["key1"] == "value1"); + REQUIRE(obj["key2"] == "value2"); + } + + SECTION("After the comma") { + DeserializationError err = + deserializeJson(doc, "{\"key1\":\"value1\", \"key2\":\"value2\"}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(obj.size() == 2); + REQUIRE(obj["key1"] == "value1"); + REQUIRE(obj["key2"] == "value2"); + } + } + + SECTION("Values types") { + SECTION("String") { + DeserializationError err = + deserializeJson(doc, "{\"key1\":\"value1\",\"key2\":\"value2\"}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(obj.size() == 2); + REQUIRE(obj["key1"] == "value1"); + REQUIRE(obj["key2"] == "value2"); + } + + SECTION("Integer") { + DeserializationError err = + deserializeJson(doc, "{\"key1\":42,\"key2\":-42}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(obj.size() == 2); + REQUIRE(obj["key1"] == 42); + REQUIRE(obj["key2"] == -42); + } + + SECTION("Double") { + DeserializationError err = + deserializeJson(doc, "{\"key1\":12.345,\"key2\":-7E89}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(obj.size() == 2); + REQUIRE(obj["key1"] == 12.345); + REQUIRE(obj["key2"] == -7E89); + } + + SECTION("Booleans") { + DeserializationError err = + deserializeJson(doc, "{\"key1\":true,\"key2\":false}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(obj.size() == 2); + REQUIRE(obj["key1"] == true); + REQUIRE(obj["key2"] == false); + } + + SECTION("Null") { + DeserializationError err = + deserializeJson(doc, "{\"key1\":null,\"key2\":null}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(obj.size() == 2); + REQUIRE(obj["key1"].as() == 0); + REQUIRE(obj["key2"].as() == 0); + } + + SECTION("Array") { + char jsonString[] = " { \"ab\" : [ 1 , 2 ] , \"cd\" : [ 3 , 4 ] } "; + + DeserializationError err = deserializeJson(doc, jsonString); + JsonObject obj = doc.as(); + + JsonArray array1 = obj["ab"]; + const JsonArray array2 = obj["cd"]; + JsonArray array3 = obj["ef"]; + + REQUIRE(err == DeserializationError::Ok); + + REQUIRE(array1.isNull() == false); + REQUIRE(array2.isNull() == false); + REQUIRE(array3.isNull() == true); + + REQUIRE(2 == array1.size()); + REQUIRE(2 == array2.size()); + REQUIRE(0 == array3.size()); + + REQUIRE(1 == array1[0].as()); + REQUIRE(2 == array1[1].as()); + + REQUIRE(3 == array2[0].as()); + REQUIRE(4 == array2[1].as()); + + REQUIRE(0 == array3[0].as()); + } + } + + SECTION("Premature null terminator") { + SECTION("After opening brace") { + DeserializationError err = deserializeJson(doc, "{"); + + REQUIRE(err == DeserializationError::IncompleteInput); + } + + SECTION("After key") { + DeserializationError err = deserializeJson(doc, "{\"hello\""); + + REQUIRE(err == DeserializationError::IncompleteInput); + } + + SECTION("After colon") { + DeserializationError err = deserializeJson(doc, "{\"hello\":"); + + REQUIRE(err == DeserializationError::IncompleteInput); + } + + SECTION("After value") { + DeserializationError err = deserializeJson(doc, "{\"hello\":\"world\""); + + REQUIRE(err == DeserializationError::IncompleteInput); + } + + SECTION("After comma") { + DeserializationError err = deserializeJson(doc, "{\"hello\":\"world\","); + + REQUIRE(err == DeserializationError::IncompleteInput); + } + } + + SECTION("Misc") { + SECTION("A quoted key without value") { + DeserializationError err = deserializeJson(doc, "{\"key\"}"); + + REQUIRE(err == DeserializationError::InvalidInput); + } + + SECTION("A non-quoted key without value") { + DeserializationError err = deserializeJson(doc, "{key}"); + + REQUIRE(err == DeserializationError::InvalidInput); + } + + SECTION("A dangling comma") { + DeserializationError err = deserializeJson(doc, "{\"key1\":\"value1\",}"); + + REQUIRE(err == DeserializationError::InvalidInput); + } + + SECTION("null as a key") { + DeserializationError err = deserializeJson(doc, "{null:\"value\"}"); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("Repeated key") { + DeserializationError err = deserializeJson(doc, "{a:{b:{c:1}},a:2}"); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc["a"] == 2); + } + + SECTION("Repeated key with zero copy mode") { // issue #1697 + char input[] = "{a:{b:{c:1}},a:2}"; + DeserializationError err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc["a"] == 2); + } + + SECTION("NUL in keys") { // we don't support NULs in keys + DeserializationError err = + deserializeJson(doc, "{\"x\\u0000a\":1,\"x\\u0000b\":2}"); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.as() == "{\"x\":2}"); + } + } + + SECTION("Should clear the JsonObject") { + deserializeJson(doc, "{\"hello\":\"world\"}"); + deserializeJson(doc, "{}"); + JsonObject obj = doc.as(); + + REQUIRE(doc.is()); + REQUIRE(obj.size() == 0); + REQUIRE(doc.memoryUsage() == JSON_OBJECT_SIZE(0)); + } + + SECTION("Issue #1335") { + std::string json("{\"a\":{},\"b\":{}}"); + deserializeJson(doc, json); + CHECK(doc.as() == json); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDeserializer/object_static.cpp b/libraries/ArduinoJson/extras/tests/JsonDeserializer/object_static.cpp new file mode 100644 index 0000000..b198ea7 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDeserializer/object_static.cpp @@ -0,0 +1,64 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("deserialize JSON object with StaticJsonDocument") { + SECTION("BufferOfTheRightSizeForEmptyObject") { + StaticJsonDocument doc; + char input[] = "{}"; + + DeserializationError err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("TooSmallBufferForObjectWithOneValue") { + StaticJsonDocument doc; + char input[] = "{\"a\":1}"; + + DeserializationError err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::NoMemory); + } + + SECTION("BufferOfTheRightSizeForObjectWithOneValue") { + StaticJsonDocument doc; + char input[] = "{\"a\":1}"; + + DeserializationError err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("TooSmallBufferForObjectWithNestedObject") { + StaticJsonDocument doc; + char input[] = "{\"a\":[]}"; + + DeserializationError err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::NoMemory); + } + + SECTION("BufferOfTheRightSizeForObjectWithNestedObject") { + StaticJsonDocument doc; + char input[] = "{\"a\":[]}"; + + DeserializationError err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("Should clear the JsonObject") { + StaticJsonDocument doc; + char input[] = "{\"hello\":\"world\"}"; + + deserializeJson(doc, input); + deserializeJson(doc, "{}"); + + REQUIRE(doc.as().size() == 0); + REQUIRE(doc.memoryUsage() == JSON_OBJECT_SIZE(0)); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDeserializer/string.cpp b/libraries/ArduinoJson/extras/tests/JsonDeserializer/string.cpp new file mode 100644 index 0000000..2379d45 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDeserializer/string.cpp @@ -0,0 +1,132 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#define ARDUINOJSON_DECODE_UNICODE 1 +#include +#include + +TEST_CASE("Valid JSON strings value") { + struct TestCase { + const char* input; + const char* expectedOutput; + }; + + TestCase testCases[] = { + {"\"hello world\"", "hello world"}, + {"\'hello world\'", "hello world"}, + {"'\"'", "\""}, + {"'\\\\'", "\\"}, + {"'\\/'", "/"}, + {"'\\b'", "\b"}, + {"'\\f'", "\f"}, + {"'\\n'", "\n"}, + {"'\\r'", "\r"}, + {"'\\t'", "\t"}, + {"\"1\\\"2\\\\3\\/4\\b5\\f6\\n7\\r8\\t9\"", "1\"2\\3/4\b5\f6\n7\r8\t9"}, + {"'\\u0041'", "A"}, + {"'\\u00e4'", "\xc3\xa4"}, // ä + {"'\\u00E4'", "\xc3\xa4"}, // ä + {"'\\u3042'", "\xe3\x81\x82"}, // あ + {"'\\ud83d\\udda4'", "\xf0\x9f\x96\xa4"}, // 🖤 + {"'\\uF053'", "\xef\x81\x93"}, // issue #1173 + {"'\\uF015'", "\xef\x80\x95"}, // issue #1173 + {"'\\uF054'", "\xef\x81\x94"}, // issue #1173 + }; + const size_t testCount = sizeof(testCases) / sizeof(testCases[0]); + + DynamicJsonDocument doc(4096); + + for (size_t i = 0; i < testCount; i++) { + const TestCase& testCase = testCases[i]; + CAPTURE(testCase.input); + DeserializationError err = deserializeJson(doc, testCase.input); + CHECK(err == DeserializationError::Ok); + CHECK(doc.as() == testCase.expectedOutput); + } +} + +TEST_CASE("\\u0000") { + StaticJsonDocument<200> doc; + + DeserializationError err = deserializeJson(doc, "\"wx\\u0000yz\""); + REQUIRE(err == DeserializationError::Ok); + + const char* result = doc.as(); + CHECK(result[0] == 'w'); + CHECK(result[1] == 'x'); + CHECK(result[2] == 0); + CHECK(result[3] == 'y'); + CHECK(result[4] == 'z'); + CHECK(result[5] == 0); + + CHECK(doc.as().size() == 5); + CHECK(doc.as().size() == 5); +} + +TEST_CASE("Truncated JSON string") { + const char* testCases[] = {"\"hello", "\'hello", "'\\u", "'\\u00", "'\\u000"}; + const size_t testCount = sizeof(testCases) / sizeof(testCases[0]); + + DynamicJsonDocument doc(4096); + + for (size_t i = 0; i < testCount; i++) { + const char* input = testCases[i]; + CAPTURE(input); + REQUIRE(deserializeJson(doc, input) == + DeserializationError::IncompleteInput); + } +} + +TEST_CASE("Invalid JSON string") { + const char* testCases[] = {"'\\u'", "'\\u000g'", "'\\u000'", + "'\\u000G'", "'\\u000/'", "'\\x1234'"}; + const size_t testCount = sizeof(testCases) / sizeof(testCases[0]); + + DynamicJsonDocument doc(4096); + + for (size_t i = 0; i < testCount; i++) { + const char* input = testCases[i]; + CAPTURE(input); + REQUIRE(deserializeJson(doc, input) == DeserializationError::InvalidInput); + } +} + +TEST_CASE("Not enough room to save the key") { + DynamicJsonDocument doc(JSON_OBJECT_SIZE(1) + 8); + + SECTION("Quoted string") { + REQUIRE(deserializeJson(doc, "{\"example\":1}") == + DeserializationError::Ok); + REQUIRE(deserializeJson(doc, "{\"accuracy\":1}") == + DeserializationError::NoMemory); + REQUIRE(deserializeJson(doc, "{\"hello\":1,\"world\"}") == + DeserializationError::NoMemory); // fails in the second string + } + + SECTION("Non-quoted string") { + REQUIRE(deserializeJson(doc, "{example:1}") == DeserializationError::Ok); + REQUIRE(deserializeJson(doc, "{accuracy:1}") == + DeserializationError::NoMemory); + REQUIRE(deserializeJson(doc, "{hello:1,world}") == + DeserializationError::NoMemory); // fails in the second string + } +} + +TEST_CASE("Empty memory pool") { + // NOLINTNEXTLINE(clang-analyzer-optin.portability.UnixAPI) + DynamicJsonDocument doc(0); + + SECTION("Input is const char*") { + REQUIRE(deserializeJson(doc, "\"hello\"") == + DeserializationError::NoMemory); + REQUIRE(deserializeJson(doc, "\"\"") == DeserializationError::NoMemory); + } + + SECTION("Input is const char*") { + char hello[] = "\"hello\""; + REQUIRE(deserializeJson(doc, hello) == DeserializationError::Ok); + char empty[] = "\"hello\""; + REQUIRE(deserializeJson(doc, empty) == DeserializationError::Ok); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDocument/BasicJsonDocument.cpp b/libraries/ArduinoJson/extras/tests/JsonDocument/BasicJsonDocument.cpp new file mode 100644 index 0000000..348fd94 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDocument/BasicJsonDocument.cpp @@ -0,0 +1,180 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include // malloc, free +#include +#include +#include + +class SpyingAllocator { + public: + SpyingAllocator(const SpyingAllocator& src) : log_(src.log_) {} + SpyingAllocator(std::ostream& log) : log_(log) {} + SpyingAllocator& operator=(const SpyingAllocator& src) = delete; + + void* allocate(size_t n) { + log_ << "A" << n; + return malloc(n); + } + void deallocate(void* p) { + log_ << "F"; + free(p); + } + + private: + std::ostream& log_; +}; + +class ControllableAllocator { + public: + ControllableAllocator() : enabled_(true) {} + + void* allocate(size_t n) { + return enabled_ ? malloc(n) : 0; + } + + void deallocate(void* p) { + free(p); + } + + void disable() { + enabled_ = false; + } + + private: + bool enabled_; +}; + +TEST_CASE("BasicJsonDocument") { + std::stringstream log; + + SECTION("Construct/Destruct") { + { BasicJsonDocument doc(4096, log); } + REQUIRE(log.str() == "A4096F"); + } + + SECTION("Copy construct") { + { + BasicJsonDocument doc1(4096, log); + doc1.set(std::string("The size of this string is 32!!")); + + BasicJsonDocument doc2(doc1); + + REQUIRE(doc1.as() == "The size of this string is 32!!"); + REQUIRE(doc2.as() == "The size of this string is 32!!"); + REQUIRE(doc2.capacity() == 4096); + } + REQUIRE(log.str() == "A4096A4096FF"); + } + + SECTION("Move construct") { + { + BasicJsonDocument doc1(4096, log); + doc1.set(std::string("The size of this string is 32!!")); + + BasicJsonDocument doc2(std::move(doc1)); + + REQUIRE(doc2.as() == "The size of this string is 32!!"); + REQUIRE(doc1.as() == "null"); + REQUIRE(doc1.capacity() == 0); + REQUIRE(doc2.capacity() == 4096); + } + REQUIRE(log.str() == "A4096F"); + } + + SECTION("Copy assign larger") { + { + BasicJsonDocument doc1(4096, log); + doc1.set(std::string("The size of this string is 32!!")); + BasicJsonDocument doc2(8, log); + + doc2 = doc1; + + REQUIRE(doc1.as() == "The size of this string is 32!!"); + REQUIRE(doc2.as() == "The size of this string is 32!!"); + REQUIRE(doc2.capacity() == 4096); + } + REQUIRE(log.str() == "A4096A8FA4096FF"); + } + + SECTION("Copy assign smaller") { + { + BasicJsonDocument doc1(1024, log); + doc1.set(std::string("The size of this string is 32!!")); + BasicJsonDocument doc2(4096, log); + + doc2 = doc1; + + REQUIRE(doc1.as() == "The size of this string is 32!!"); + REQUIRE(doc2.as() == "The size of this string is 32!!"); + REQUIRE(doc2.capacity() == 1024); + } + REQUIRE(log.str() == "A1024A4096FA1024FF"); + } + + SECTION("Copy assign same size") { + { + BasicJsonDocument doc1(1024, log); + doc1.set(std::string("The size of this string is 32!!")); + BasicJsonDocument doc2(1024, log); + + doc2 = doc1; + + REQUIRE(doc1.as() == "The size of this string is 32!!"); + REQUIRE(doc2.as() == "The size of this string is 32!!"); + REQUIRE(doc2.capacity() == 1024); + } + REQUIRE(log.str() == "A1024A1024FF"); + } + + SECTION("Move assign") { + { + BasicJsonDocument doc1(4096, log); + doc1.set(std::string("The size of this string is 32!!")); + BasicJsonDocument doc2(8, log); + + doc2 = std::move(doc1); + + REQUIRE(doc2.as() == "The size of this string is 32!!"); + REQUIRE(doc1.as() == "null"); + REQUIRE(doc1.capacity() == 0); + REQUIRE(doc2.capacity() == 4096); + } + REQUIRE(log.str() == "A4096A8FF"); + } + + SECTION("garbageCollect()") { + BasicJsonDocument doc(4096); + + SECTION("when allocation succeeds") { + deserializeJson(doc, "{\"blanket\":1,\"dancing\":2}"); + REQUIRE(doc.capacity() == 4096); + REQUIRE(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + doc.remove("blanket"); + + bool result = doc.garbageCollect(); + + REQUIRE(result == true); + REQUIRE(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + REQUIRE(doc.capacity() == 4096); + REQUIRE(doc.as() == "{\"dancing\":2}"); + } + + SECTION("when allocation fails") { + deserializeJson(doc, "{\"blanket\":1,\"dancing\":2}"); + REQUIRE(doc.capacity() == 4096); + REQUIRE(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + doc.remove("blanket"); + doc.allocator().disable(); + + bool result = doc.garbageCollect(); + + REQUIRE(result == false); + REQUIRE(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + REQUIRE(doc.capacity() == 4096); + REQUIRE(doc.as() == "{\"dancing\":2}"); + } + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDocument/CMakeLists.txt b/libraries/ArduinoJson/extras/tests/JsonDocument/CMakeLists.txt new file mode 100644 index 0000000..3e9b468 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDocument/CMakeLists.txt @@ -0,0 +1,32 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2023, Benoit BLANCHON +# MIT License + +add_executable(JsonDocumentTests + add.cpp + BasicJsonDocument.cpp + cast.cpp + compare.cpp + containsKey.cpp + createNested.cpp + DynamicJsonDocument.cpp + ElementProxy.cpp + isNull.cpp + issue1120.cpp + MemberProxy.cpp + nesting.cpp + overflowed.cpp + remove.cpp + shrinkToFit.cpp + size.cpp + StaticJsonDocument.cpp + subscript.cpp + swap.cpp +) + +add_test(JsonDocument JsonDocumentTests) + +set_tests_properties(JsonDocument + PROPERTIES + LABELS "Catch" +) diff --git a/libraries/ArduinoJson/extras/tests/JsonDocument/DynamicJsonDocument.cpp b/libraries/ArduinoJson/extras/tests/JsonDocument/DynamicJsonDocument.cpp new file mode 100644 index 0000000..397f8c5 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDocument/DynamicJsonDocument.cpp @@ -0,0 +1,230 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +using ArduinoJson::detail::addPadding; + +static void REQUIRE_JSON(JsonDocument& doc, const std::string& expected) { + std::string json; + serializeJson(doc, json); + REQUIRE(json == expected); +} + +TEST_CASE("DynamicJsonDocument") { + DynamicJsonDocument doc(4096); + + SECTION("serializeJson()") { + JsonObject obj = doc.to(); + obj["hello"] = "world"; + + std::string json; + serializeJson(doc, json); + + REQUIRE(json == "{\"hello\":\"world\"}"); + } + + SECTION("memoryUsage()") { + SECTION("starts at zero") { + REQUIRE(doc.memoryUsage() == 0); + } + + SECTION("JSON_ARRAY_SIZE(0)") { + doc.to(); + REQUIRE(doc.memoryUsage() == JSON_ARRAY_SIZE(0)); + } + + SECTION("JSON_ARRAY_SIZE(1)") { + doc.to().add(42); + REQUIRE(doc.memoryUsage() == JSON_ARRAY_SIZE(1)); + } + + SECTION("JSON_ARRAY_SIZE(1) + JSON_ARRAY_SIZE(0)") { + doc.to().createNestedArray(); + REQUIRE(doc.memoryUsage() == JSON_ARRAY_SIZE(1) + JSON_ARRAY_SIZE(0)); + } + } + + SECTION("capacity()") { + SECTION("matches constructor argument") { + DynamicJsonDocument doc2(256); + REQUIRE(doc2.capacity() == 256); + } + + SECTION("rounds up constructor argument") { + DynamicJsonDocument doc2(253); + REQUIRE(doc2.capacity() == 256); + } + } + + SECTION("memoryUsage()") { + SECTION("Increases after adding value to array") { + JsonArray arr = doc.to(); + + REQUIRE(doc.memoryUsage() == JSON_ARRAY_SIZE(0)); + arr.add(42); + REQUIRE(doc.memoryUsage() == JSON_ARRAY_SIZE(1)); + arr.add(43); + REQUIRE(doc.memoryUsage() == JSON_ARRAY_SIZE(2)); + } + + SECTION("Increases after adding value to object") { + JsonObject obj = doc.to(); + + REQUIRE(doc.memoryUsage() == JSON_OBJECT_SIZE(0)); + obj["a"] = 1; + REQUIRE(doc.memoryUsage() == JSON_OBJECT_SIZE(1)); + obj["b"] = 2; + REQUIRE(doc.memoryUsage() == JSON_OBJECT_SIZE(2)); + } + } +} + +TEST_CASE("DynamicJsonDocument constructor") { + SECTION("Copy constructor") { + DynamicJsonDocument doc1(1234); + deserializeJson(doc1, "{\"hello\":\"world\"}"); + + DynamicJsonDocument doc2 = doc1; + + REQUIRE_JSON(doc2, "{\"hello\":\"world\"}"); + + REQUIRE(doc2.capacity() == doc1.capacity()); + } + + SECTION("Construct from StaticJsonDocument") { + StaticJsonDocument<200> doc1; + deserializeJson(doc1, "{\"hello\":\"world\"}"); + + DynamicJsonDocument doc2 = doc1; + + REQUIRE_JSON(doc2, "{\"hello\":\"world\"}"); + REQUIRE(doc2.capacity() == doc1.capacity()); + } + + SECTION("Construct from JsonObject") { + StaticJsonDocument<200> doc1; + JsonObject obj = doc1.to(); + obj["hello"] = "world"; + + DynamicJsonDocument doc2 = obj; + + REQUIRE_JSON(doc2, "{\"hello\":\"world\"}"); + REQUIRE(doc2.capacity() == addPadding(doc1.memoryUsage())); + } + + SECTION("Construct from JsonArray") { + StaticJsonDocument<200> doc1; + JsonArray arr = doc1.to(); + arr.add("hello"); + + DynamicJsonDocument doc2 = arr; + + REQUIRE_JSON(doc2, "[\"hello\"]"); + REQUIRE(doc2.capacity() == addPadding(doc1.memoryUsage())); + } + + SECTION("Construct from JsonVariant") { + StaticJsonDocument<200> doc1; + deserializeJson(doc1, "42"); + + DynamicJsonDocument doc2 = doc1.as(); + + REQUIRE_JSON(doc2, "42"); + REQUIRE(doc2.capacity() == addPadding(doc1.memoryUsage())); + } +} + +TEST_CASE("DynamicJsonDocument assignment") { + SECTION("Copy assignment reallocates when capacity is smaller") { + DynamicJsonDocument doc1(1234); + deserializeJson(doc1, "{\"hello\":\"world\"}"); + DynamicJsonDocument doc2(8); + + doc2 = doc1; + + REQUIRE_JSON(doc2, "{\"hello\":\"world\"}"); + REQUIRE(doc2.capacity() == doc1.capacity()); + } + + SECTION("Copy assignment reallocates when capacity is larger") { + DynamicJsonDocument doc1(100); + deserializeJson(doc1, "{\"hello\":\"world\"}"); + DynamicJsonDocument doc2(1234); + + doc2 = doc1; + + REQUIRE_JSON(doc2, "{\"hello\":\"world\"}"); + REQUIRE(doc2.capacity() == doc1.capacity()); + } + + SECTION("Assign from StaticJsonDocument") { + StaticJsonDocument<200> doc1; + deserializeJson(doc1, "{\"hello\":\"world\"}"); + DynamicJsonDocument doc2(4096); + doc2.to().set(666); + + doc2 = doc1; + + REQUIRE_JSON(doc2, "{\"hello\":\"world\"}"); + } + + SECTION("Assign from JsonObject") { + StaticJsonDocument<200> doc1; + JsonObject obj = doc1.to(); + obj["hello"] = "world"; + + DynamicJsonDocument doc2(4096); + doc2 = obj; + + REQUIRE_JSON(doc2, "{\"hello\":\"world\"}"); + REQUIRE(doc2.capacity() == 4096); + } + + SECTION("Assign from JsonArray") { + StaticJsonDocument<200> doc1; + JsonArray arr = doc1.to(); + arr.add("hello"); + + DynamicJsonDocument doc2(4096); + doc2 = arr; + + REQUIRE_JSON(doc2, "[\"hello\"]"); + REQUIRE(doc2.capacity() == 4096); + } + + SECTION("Assign from JsonVariant") { + StaticJsonDocument<200> doc1; + deserializeJson(doc1, "42"); + + DynamicJsonDocument doc2(4096); + doc2 = doc1.as(); + + REQUIRE_JSON(doc2, "42"); + REQUIRE(doc2.capacity() == 4096); + } + + SECTION("Assign from MemberProxy") { + StaticJsonDocument<200> doc1; + doc1["value"] = 42; + + DynamicJsonDocument doc2(4096); + doc2 = doc1["value"]; + + REQUIRE_JSON(doc2, "42"); + REQUIRE(doc2.capacity() == 4096); + } + + SECTION("Assign from ElementProxy") { + StaticJsonDocument<200> doc1; + doc1[0] = 42; + + DynamicJsonDocument doc2(4096); + doc2 = doc1[0]; + + REQUIRE_JSON(doc2, "42"); + REQUIRE(doc2.capacity() == 4096); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDocument/ElementProxy.cpp b/libraries/ArduinoJson/extras/tests/JsonDocument/ElementProxy.cpp new file mode 100644 index 0000000..00fcdda --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDocument/ElementProxy.cpp @@ -0,0 +1,255 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +typedef ArduinoJson::detail::ElementProxy ElementProxy; + +TEST_CASE("ElementProxy::add()") { + DynamicJsonDocument doc(4096); + doc.add(); + ElementProxy ep = doc[0]; + + SECTION("add(int)") { + ep.add(42); + + REQUIRE(doc.as() == "[[42]]"); + } + + SECTION("add(const char*)") { + ep.add("world"); + + REQUIRE(doc.as() == "[[\"world\"]]"); + } + + SECTION("set(char[])") { + char s[] = "world"; + ep.add(s); + strcpy(s, "!!!!!"); + + REQUIRE(doc.as() == "[[\"world\"]]"); + } +} + +TEST_CASE("ElementProxy::clear()") { + DynamicJsonDocument doc(4096); + doc.add(); + ElementProxy ep = doc[0]; + + SECTION("size goes back to zero") { + ep.add(42); + ep.clear(); + + REQUIRE(ep.size() == 0); + } + + SECTION("isNull() return true") { + ep.add("hello"); + ep.clear(); + + REQUIRE(ep.isNull() == true); + } +} + +TEST_CASE("ElementProxy::operator==()") { + DynamicJsonDocument doc(4096); + + SECTION("1 vs 1") { + doc.add(1); + doc.add(1); + + REQUIRE(doc[0] <= doc[1]); + REQUIRE(doc[0] == doc[1]); + REQUIRE(doc[0] >= doc[1]); + REQUIRE_FALSE(doc[0] != doc[1]); + REQUIRE_FALSE(doc[0] < doc[1]); + REQUIRE_FALSE(doc[0] > doc[1]); + } + + SECTION("1 vs 2") { + doc.add(1); + doc.add(2); + + REQUIRE(doc[0] != doc[1]); + REQUIRE(doc[0] < doc[1]); + REQUIRE(doc[0] <= doc[1]); + REQUIRE_FALSE(doc[0] == doc[1]); + REQUIRE_FALSE(doc[0] > doc[1]); + REQUIRE_FALSE(doc[0] >= doc[1]); + } + + SECTION("'abc' vs 'bcd'") { + doc.add("abc"); + doc.add("bcd"); + + REQUIRE(doc[0] != doc[1]); + REQUIRE(doc[0] < doc[1]); + REQUIRE(doc[0] <= doc[1]); + REQUIRE_FALSE(doc[0] == doc[1]); + REQUIRE_FALSE(doc[0] > doc[1]); + REQUIRE_FALSE(doc[0] >= doc[1]); + } +} + +TEST_CASE("ElementProxy::remove()") { + DynamicJsonDocument doc(4096); + doc.add(); + ElementProxy ep = doc[0]; + + SECTION("remove(int)") { + ep.add(1); + ep.add(2); + ep.add(3); + + ep.remove(1); + + REQUIRE(ep.as() == "[1,3]"); + } + + SECTION("remove(const char *)") { + ep["a"] = 1; + ep["b"] = 2; + + ep.remove("a"); + + REQUIRE(ep.as() == "{\"b\":2}"); + } + + SECTION("remove(std::string)") { + ep["a"] = 1; + ep["b"] = 2; + + ep.remove(std::string("b")); + + REQUIRE(ep.as() == "{\"a\":1}"); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("remove(vla)") { + ep["a"] = 1; + ep["b"] = 2; + + size_t i = 4; + char vla[i]; + strcpy(vla, "b"); + ep.remove(vla); + + REQUIRE(ep.as() == "{\"a\":1}"); + } +#endif +} + +TEST_CASE("ElementProxy::set()") { + DynamicJsonDocument doc(4096); + ElementProxy ep = doc[0]; + + SECTION("set(int)") { + ep.set(42); + + REQUIRE(doc.as() == "[42]"); + } + + SECTION("set(const char*)") { + ep.set("world"); + + REQUIRE(doc.as() == "[\"world\"]"); + } + + SECTION("set(char[])") { + char s[] = "world"; + ep.set(s); + strcpy(s, "!!!!!"); + + REQUIRE(doc.as() == "[\"world\"]"); + } +} + +TEST_CASE("ElementProxy::size()") { + DynamicJsonDocument doc(4096); + doc.add(); + ElementProxy ep = doc[0]; + + SECTION("returns 0") { + REQUIRE(ep.size() == 0); + } + + SECTION("as an array, returns 2") { + ep.add(1); + ep.add(2); + REQUIRE(ep.size() == 2); + } + + SECTION("as an object, returns 2") { + ep["a"] = 1; + ep["b"] = 2; + REQUIRE(ep.size() == 2); + } +} + +TEST_CASE("ElementProxy::memoryUsage()") { + DynamicJsonDocument doc(4096); + doc.add(); + ElementProxy ep = doc[0]; + + SECTION("returns 0 for null") { + REQUIRE(ep.memoryUsage() == 0); + } + + SECTION("returns size for string") { + ep.set(std::string("hello")); + REQUIRE(ep.memoryUsage() == 6); + } +} + +TEST_CASE("ElementProxy::operator[]") { + DynamicJsonDocument doc(4096); + ElementProxy ep = doc[1]; + + SECTION("set member") { + ep["world"] = 42; + + REQUIRE(doc.as() == "[null,{\"world\":42}]"); + } + + SECTION("set element") { + ep[2] = 42; + + REQUIRE(doc.as() == "[null,[null,null,42]]"); + } +} + +TEST_CASE("ElementProxy cast to JsonVariantConst") { + DynamicJsonDocument doc(4096); + doc[0] = "world"; + + const ElementProxy ep = doc[0]; + + JsonVariantConst var = ep; + + CHECK(var.as() == "world"); +} + +TEST_CASE("ElementProxy cast to JsonVariant") { + DynamicJsonDocument doc(4096); + doc[0] = "world"; + + ElementProxy ep = doc[0]; + + JsonVariant var = ep; + + CHECK(var.as() == "world"); + + var.set("toto"); + + CHECK(doc.as() == "[\"toto\"]"); +} + +TEST_CASE("ElementProxy::shallowCopy()") { + StaticJsonDocument<1024> doc1, doc2; + doc2["hello"] = "world"; + doc1[0].shallowCopy(doc2); + + CHECK(doc1.as() == "[{\"hello\":\"world\"}]"); +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDocument/MemberProxy.cpp b/libraries/ArduinoJson/extras/tests/JsonDocument/MemberProxy.cpp new file mode 100644 index 0000000..a3707b0 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDocument/MemberProxy.cpp @@ -0,0 +1,328 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +typedef ArduinoJson::detail::MemberProxy + MemberProxy; + +TEST_CASE("MemberProxy::add()") { + DynamicJsonDocument doc(4096); + MemberProxy mp = doc["hello"]; + + SECTION("add(int)") { + mp.add(42); + + REQUIRE(doc.as() == "{\"hello\":[42]}"); + } + + SECTION("add(const char*)") { + mp.add("world"); + + REQUIRE(doc.as() == "{\"hello\":[\"world\"]}"); + } +} + +TEST_CASE("MemberProxy::clear()") { + DynamicJsonDocument doc(4096); + MemberProxy mp = doc["hello"]; + + SECTION("size goes back to zero") { + mp.add(42); + mp.clear(); + + REQUIRE(mp.size() == 0); + } + + SECTION("isNull() return true") { + mp.add("hello"); + mp.clear(); + + REQUIRE(mp.isNull() == true); + } +} + +TEST_CASE("MemberProxy::operator==()") { + DynamicJsonDocument doc(4096); + + SECTION("1 vs 1") { + doc["a"] = 1; + doc["b"] = 1; + + REQUIRE(doc["a"] <= doc["b"]); + REQUIRE(doc["a"] == doc["b"]); + REQUIRE(doc["a"] >= doc["b"]); + REQUIRE_FALSE(doc["a"] != doc["b"]); + REQUIRE_FALSE(doc["a"] < doc["b"]); + REQUIRE_FALSE(doc["a"] > doc["b"]); + } + + SECTION("1 vs 2") { + doc["a"] = 1; + doc["b"] = 2; + + REQUIRE(doc["a"] != doc["b"]); + REQUIRE(doc["a"] < doc["b"]); + REQUIRE(doc["a"] <= doc["b"]); + REQUIRE_FALSE(doc["a"] == doc["b"]); + REQUIRE_FALSE(doc["a"] > doc["b"]); + REQUIRE_FALSE(doc["a"] >= doc["b"]); + } + + SECTION("'abc' vs 'bcd'") { + doc["a"] = "abc"; + doc["b"] = "bcd"; + + REQUIRE(doc["a"] != doc["b"]); + REQUIRE(doc["a"] < doc["b"]); + REQUIRE(doc["a"] <= doc["b"]); + REQUIRE_FALSE(doc["a"] == doc["b"]); + REQUIRE_FALSE(doc["a"] > doc["b"]); + REQUIRE_FALSE(doc["a"] >= doc["b"]); + } +} + +TEST_CASE("MemberProxy::containsKey()") { + DynamicJsonDocument doc(4096); + MemberProxy mp = doc["hello"]; + + SECTION("containsKey(const char*)") { + mp["key"] = "value"; + + REQUIRE(mp.containsKey("key") == true); + REQUIRE(mp.containsKey("key") == true); + } + + SECTION("containsKey(std::string)") { + mp["key"] = "value"; + + REQUIRE(mp.containsKey(std::string("key")) == true); + REQUIRE(mp.containsKey(std::string("key")) == true); + } +} + +TEST_CASE("MemberProxy::operator|()") { + DynamicJsonDocument doc(4096); + + SECTION("const char*") { + doc["a"] = "hello"; + + REQUIRE((doc["a"] | "world") == std::string("hello")); + REQUIRE((doc["b"] | "world") == std::string("world")); + } + + SECTION("Issue #1411") { + doc["sensor"] = "gps"; + + const char* test = "test"; // <- the literal must be captured in a variable + // to trigger the bug + const char* sensor = doc["sensor"] | test; // "gps" + + REQUIRE(sensor == std::string("gps")); + } + + SECTION("Issue #1415") { + JsonObject object = doc.to(); + object["hello"] = "world"; + + StaticJsonDocument<0> emptyDoc; + JsonObject anotherObject = object["hello"] | emptyDoc.to(); + + REQUIRE(anotherObject.isNull() == false); + REQUIRE(anotherObject.size() == 0); + } +} + +TEST_CASE("MemberProxy::remove()") { + DynamicJsonDocument doc(4096); + MemberProxy mp = doc["hello"]; + + SECTION("remove(int)") { + mp.add(1); + mp.add(2); + mp.add(3); + + mp.remove(1); + + REQUIRE(mp.as() == "[1,3]"); + } + + SECTION("remove(const char *)") { + mp["a"] = 1; + mp["b"] = 2; + + mp.remove("a"); + + REQUIRE(mp.as() == "{\"b\":2}"); + } + + SECTION("remove(std::string)") { + mp["a"] = 1; + mp["b"] = 2; + + mp.remove(std::string("b")); + + REQUIRE(mp.as() == "{\"a\":1}"); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("remove(vla)") { + mp["a"] = 1; + mp["b"] = 2; + + size_t i = 4; + char vla[i]; + strcpy(vla, "b"); + mp.remove(vla); + + REQUIRE(mp.as() == "{\"a\":1}"); + } +#endif +} + +TEST_CASE("MemberProxy::set()") { + DynamicJsonDocument doc(4096); + MemberProxy mp = doc["hello"]; + + SECTION("set(int)") { + mp.set(42); + + REQUIRE(doc.as() == "{\"hello\":42}"); + } + + SECTION("set(const char*)") { + mp.set("world"); + + REQUIRE(doc.as() == "{\"hello\":\"world\"}"); + } + + SECTION("set(char[])") { // issue #1191 + char s[] = "world"; + mp.set(s); + strcpy(s, "!!!!!"); + + REQUIRE(doc.as() == "{\"hello\":\"world\"}"); + } +} + +TEST_CASE("MemberProxy::size()") { + DynamicJsonDocument doc(4096); + MemberProxy mp = doc["hello"]; + + SECTION("returns 0") { + REQUIRE(mp.size() == 0); + } + + SECTION("as an array, return 2") { + mp.add(1); + mp.add(2); + + REQUIRE(mp.size() == 2); + } + + SECTION("as an object, return 2") { + mp["a"] = 1; + mp["b"] = 2; + + REQUIRE(mp.size() == 2); + } +} + +TEST_CASE("MemberProxy::memoryUsage()") { + DynamicJsonDocument doc(4096); + MemberProxy mp = doc["hello"]; + + SECTION("returns 0 when null") { + REQUIRE(mp.memoryUsage() == 0); + } + + SECTION("return the size for a string") { + mp.set(std::string("hello")); + REQUIRE(mp.memoryUsage() == 6); + } +} + +TEST_CASE("MemberProxy::operator[]") { + DynamicJsonDocument doc(4096); + MemberProxy mp = doc["hello"]; + + SECTION("set member") { + mp["world"] = 42; + + REQUIRE(doc.as() == "{\"hello\":{\"world\":42}}"); + } + + SECTION("set element") { + mp[2] = 42; + + REQUIRE(doc.as() == "{\"hello\":[null,null,42]}"); + } +} + +TEST_CASE("MemberProxy cast to JsonVariantConst") { + DynamicJsonDocument doc(4096); + doc["hello"] = "world"; + + const MemberProxy mp = doc["hello"]; + + JsonVariantConst var = mp; + + CHECK(var.as() == "world"); +} + +TEST_CASE("MemberProxy cast to JsonVariant") { + DynamicJsonDocument doc(4096); + doc["hello"] = "world"; + + MemberProxy mp = doc["hello"]; + + JsonVariant var = mp; + + CHECK(var.as() == "world"); + + var.set("toto"); + + CHECK(doc.as() == "{\"hello\":\"toto\"}"); +} + +TEST_CASE("MemberProxy::createNestedArray()") { + StaticJsonDocument<1024> doc; + JsonArray arr = doc["items"].createNestedArray(); + arr.add(42); + + CHECK(doc["items"][0][0] == 42); +} + +TEST_CASE("MemberProxy::createNestedArray(key)") { + StaticJsonDocument<1024> doc; + JsonArray arr = doc["weather"].createNestedArray("temp"); + arr.add(42); + + CHECK(doc["weather"]["temp"][0] == 42); +} + +TEST_CASE("MemberProxy::createNestedObject()") { + StaticJsonDocument<1024> doc; + JsonObject obj = doc["items"].createNestedObject(); + obj["value"] = 42; + + CHECK(doc["items"][0]["value"] == 42); +} + +TEST_CASE("MemberProxy::createNestedObject(key)") { + StaticJsonDocument<1024> doc; + JsonObject obj = doc["status"].createNestedObject("weather"); + obj["temp"] = 42; + + CHECK(doc["status"]["weather"]["temp"] == 42); +} + +TEST_CASE("MemberProxy::shallowCopy()") { + StaticJsonDocument<1024> doc1, doc2; + doc2["hello"] = "world"; + doc1["obj"].shallowCopy(doc2); + + CHECK(doc1.as() == "{\"obj\":{\"hello\":\"world\"}}"); +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDocument/StaticJsonDocument.cpp b/libraries/ArduinoJson/extras/tests/JsonDocument/StaticJsonDocument.cpp new file mode 100644 index 0000000..0d4089b --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDocument/StaticJsonDocument.cpp @@ -0,0 +1,224 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +static void REQUIRE_JSON(JsonDocument& doc, const std::string& expected) { + std::string json; + serializeJson(doc, json); + REQUIRE(json == expected); +} + +TEST_CASE("StaticJsonDocument") { + SECTION("capacity()") { + SECTION("matches template argument") { + StaticJsonDocument<256> doc; + REQUIRE(doc.capacity() == 256); + } + + SECTION("rounds up template argument") { + StaticJsonDocument<253> doc; + REQUIRE(doc.capacity() == 256); + } + } + + SECTION("serializeJson()") { + StaticJsonDocument<200> doc; + JsonObject obj = doc.to(); + obj["hello"] = "world"; + + std::string json; + serializeJson(doc, json); + + REQUIRE(json == "{\"hello\":\"world\"}"); + } + + SECTION("Copy assignment") { + StaticJsonDocument<200> doc1, doc2; + doc1.to().set(666); + deserializeJson(doc2, "{\"hello\":\"world\"}"); + + doc1 = doc2; + + REQUIRE_JSON(doc2, "{\"hello\":\"world\"}"); + } + + SECTION("Contructor") { + SECTION("Copy constructor") { + StaticJsonDocument<200> doc1; + deserializeJson(doc1, "{\"hello\":\"world\"}"); + + StaticJsonDocument<200> doc2 = doc1; + + deserializeJson(doc1, "{\"HELLO\":\"WORLD\"}"); + REQUIRE_JSON(doc2, "{\"hello\":\"world\"}"); + } + + SECTION("Construct from StaticJsonDocument of different size") { + StaticJsonDocument<300> doc1; + deserializeJson(doc1, "{\"hello\":\"world\"}"); + + StaticJsonDocument<200> doc2 = doc1; + + REQUIRE_JSON(doc2, "{\"hello\":\"world\"}"); + } + + SECTION("Construct from DynamicJsonDocument") { + DynamicJsonDocument doc1(4096); + deserializeJson(doc1, "{\"hello\":\"world\"}"); + + StaticJsonDocument<200> doc2 = doc1; + + REQUIRE_JSON(doc2, "{\"hello\":\"world\"}"); + } + + SECTION("Construct from JsonObject") { + DynamicJsonDocument doc1(4096); + deserializeJson(doc1, "{\"hello\":\"world\"}"); + + StaticJsonDocument<200> doc2 = doc1.as(); + + deserializeJson(doc1, "{\"HELLO\":\"WORLD\"}"); + REQUIRE_JSON(doc2, "{\"hello\":\"world\"}"); + } + + SECTION("Construct from JsonArray") { + DynamicJsonDocument doc1(4096); + deserializeJson(doc1, "[\"hello\",\"world\"]"); + + StaticJsonDocument<200> doc2 = doc1.as(); + + deserializeJson(doc1, "[\"HELLO\",\"WORLD\"]"); + REQUIRE_JSON(doc2, "[\"hello\",\"world\"]"); + } + + SECTION("Construct from JsonVariant") { + DynamicJsonDocument doc1(4096); + deserializeJson(doc1, "42"); + + StaticJsonDocument<200> doc2 = doc1.as(); + + REQUIRE_JSON(doc2, "42"); + } + } + + SECTION("Assignment") { + SECTION("Copy assignment") { + StaticJsonDocument<200> doc1, doc2; + doc1.to().set(666); + deserializeJson(doc1, "{\"hello\":\"world\"}"); + + doc2 = doc1; + + deserializeJson(doc1, "{\"HELLO\":\"WORLD\"}"); + REQUIRE_JSON(doc2, "{\"hello\":\"world\"}"); + } + + SECTION("Assign from StaticJsonDocument of different capacity") { + StaticJsonDocument<200> doc1; + StaticJsonDocument<300> doc2; + doc1.to().set(666); + deserializeJson(doc1, "{\"hello\":\"world\"}"); + + doc2 = doc1; + + REQUIRE_JSON(doc2, "{\"hello\":\"world\"}"); + } + + SECTION("Assign from DynamicJsonDocument") { + StaticJsonDocument<200> doc1; + DynamicJsonDocument doc2(4096); + doc1.to().set(666); + deserializeJson(doc1, "{\"hello\":\"world\"}"); + + doc2 = doc1; + + deserializeJson(doc1, "{\"HELLO\":\"WORLD\"}"); + REQUIRE_JSON(doc2, "{\"hello\":\"world\"}"); + } + + SECTION("Assign from JsonArray") { + StaticJsonDocument<200> doc1; + DynamicJsonDocument doc2(4096); + doc1.to().set(666); + deserializeJson(doc1, "[\"hello\",\"world\"]"); + + doc2 = doc1.as(); + + deserializeJson(doc1, "[\"HELLO\",\"WORLD\"]"); + REQUIRE_JSON(doc2, "[\"hello\",\"world\"]"); + } + + SECTION("Assign from JsonArrayConst") { + StaticJsonDocument<200> doc1; + DynamicJsonDocument doc2(4096); + doc1.to().set(666); + deserializeJson(doc1, "[\"hello\",\"world\"]"); + + doc2 = doc1.as(); + + deserializeJson(doc1, "[\"HELLO\",\"WORLD\"]"); + REQUIRE_JSON(doc2, "[\"hello\",\"world\"]"); + } + + SECTION("Assign from JsonObject") { + StaticJsonDocument<200> doc1; + DynamicJsonDocument doc2(4096); + doc1.to().set(666); + deserializeJson(doc1, "{\"hello\":\"world\"}"); + + doc2 = doc1.as(); + + deserializeJson(doc1, "{\"HELLO\":\"WORLD\"}"); + REQUIRE_JSON(doc2, "{\"hello\":\"world\"}"); + } + + SECTION("Assign from JsonObjectConst") { + StaticJsonDocument<200> doc1; + DynamicJsonDocument doc2(4096); + doc1.to().set(666); + deserializeJson(doc1, "{\"hello\":\"world\"}"); + + doc2 = doc1.as(); + + deserializeJson(doc1, "{\"HELLO\":\"WORLD\"}"); + REQUIRE_JSON(doc2, "{\"hello\":\"world\"}"); + } + + SECTION("Assign from JsonVariant") { + DynamicJsonDocument doc1(4096); + doc1.to().set(666); + deserializeJson(doc1, "42"); + + StaticJsonDocument<200> doc2; + doc2 = doc1.as(); + + REQUIRE_JSON(doc2, "42"); + } + + SECTION("Assign from JsonVariantConst") { + DynamicJsonDocument doc1(4096); + doc1.to().set(666); + deserializeJson(doc1, "42"); + + StaticJsonDocument<200> doc2; + doc2 = doc1.as(); + + REQUIRE_JSON(doc2, "42"); + } + } + + SECTION("garbageCollect()") { + StaticJsonDocument<256> doc; + doc[std::string("example")] = std::string("jukebox"); + doc.remove("example"); + REQUIRE(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 16); + + doc.garbageCollect(); + + REQUIRE(doc.memoryUsage() == JSON_OBJECT_SIZE(0)); + REQUIRE_JSON(doc, "{}"); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDocument/add.cpp b/libraries/ArduinoJson/extras/tests/JsonDocument/add.cpp new file mode 100644 index 0000000..5843ac9 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDocument/add.cpp @@ -0,0 +1,22 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonDocument::add()") { + DynamicJsonDocument doc(4096); + + SECTION("integer") { + doc.add(42); + + REQUIRE(doc.as() == "[42]"); + } + + SECTION("const char*") { + doc.add("hello"); + + REQUIRE(doc.as() == "[\"hello\"]"); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDocument/cast.cpp b/libraries/ArduinoJson/extras/tests/JsonDocument/cast.cpp new file mode 100644 index 0000000..253e1fc --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDocument/cast.cpp @@ -0,0 +1,18 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +#include + +TEST_CASE("Implicit cast to JsonVariant") { + StaticJsonDocument<128> doc; + + doc["hello"] = "world"; + + JsonVariant var = doc; + + CHECK(var.as() == "{\"hello\":\"world\"}"); +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDocument/compare.cpp b/libraries/ArduinoJson/extras/tests/JsonDocument/compare.cpp new file mode 100644 index 0000000..d834b22 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDocument/compare.cpp @@ -0,0 +1,103 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("DynamicJsonDocument::operator==(const DynamicJsonDocument&)") { + DynamicJsonDocument doc1(4096); + DynamicJsonDocument doc2(4096); + + SECTION("Empty") { + REQUIRE(doc1 == doc2); + REQUIRE_FALSE(doc1 != doc2); + } + + SECTION("With same object") { + doc1["hello"] = "world"; + doc2["hello"] = "world"; + REQUIRE(doc1 == doc2); + REQUIRE_FALSE(doc1 != doc2); + } + SECTION("With different object") { + doc1["hello"] = "world"; + doc2["world"] = "hello"; + REQUIRE_FALSE(doc1 == doc2); + REQUIRE(doc1 != doc2); + } +} + +TEST_CASE("DynamicJsonDocument::operator==(const StaticJsonDocument&)") { + DynamicJsonDocument doc1(4096); + StaticJsonDocument<256> doc2; + + SECTION("Empty") { + REQUIRE(doc1 == doc2); + REQUIRE_FALSE(doc1 != doc2); + } + + SECTION("With same object") { + doc1["hello"] = "world"; + doc2["hello"] = "world"; + REQUIRE(doc1 == doc2); + REQUIRE_FALSE(doc1 != doc2); + } + + SECTION("With different object") { + doc1["hello"] = "world"; + doc2["world"] = "hello"; + REQUIRE_FALSE(doc1 == doc2); + REQUIRE(doc1 != doc2); + } +} + +TEST_CASE("StaticJsonDocument::operator==(const DynamicJsonDocument&)") { + StaticJsonDocument<256> doc1; + DynamicJsonDocument doc2(4096); + + SECTION("Empty") { + REQUIRE(doc1 == doc2); + REQUIRE_FALSE(doc1 != doc2); + } + + SECTION("With same object") { + doc1["hello"] = "world"; + doc2["hello"] = "world"; + REQUIRE(doc1 == doc2); + REQUIRE_FALSE(doc1 != doc2); + } + + SECTION("With different object") { + doc1["hello"] = "world"; + doc2["world"] = "hello"; + REQUIRE_FALSE(doc1 == doc2); + REQUIRE(doc1 != doc2); + } +} + +TEST_CASE("JsonDocument::operator==(const JsonDocument&)") { + StaticJsonDocument<256> doc1; + StaticJsonDocument<256> doc2; + const JsonDocument& ref1 = doc1; + const JsonDocument& ref2 = doc2; + + SECTION("Empty") { + REQUIRE(ref1 == ref2); + REQUIRE_FALSE(ref1 != ref2); + } + + SECTION("With same object") { + doc1["hello"] = "world"; + doc2["hello"] = "world"; + REQUIRE(ref1 == ref2); + REQUIRE_FALSE(ref1 != ref2); + } + + SECTION("With different object") { + doc1["hello"] = "world"; + doc2["world"] = "hello"; + REQUIRE_FALSE(ref1 == ref2); + REQUIRE(ref1 != ref2); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDocument/containsKey.cpp b/libraries/ArduinoJson/extras/tests/JsonDocument/containsKey.cpp new file mode 100644 index 0000000..8274fc7 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDocument/containsKey.cpp @@ -0,0 +1,44 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonDocument::containsKey()") { + DynamicJsonDocument doc(4096); + + SECTION("returns true on object") { + doc["hello"] = "world"; + + REQUIRE(doc.containsKey("hello") == true); + } + + SECTION("returns true when value is null") { + doc["hello"] = static_cast(0); + + REQUIRE(doc.containsKey("hello") == true); + } + + SECTION("returns true when key is a std::string") { + doc["hello"] = "world"; + + REQUIRE(doc.containsKey(std::string("hello")) == true); + } + + SECTION("returns false on object") { + doc["world"] = "hello"; + + REQUIRE(doc.containsKey("hello") == false); + } + + SECTION("returns false on array") { + doc.add("hello"); + + REQUIRE(doc.containsKey("hello") == false); + } + + SECTION("returns false on null") { + REQUIRE(doc.containsKey("hello") == false); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDocument/createNested.cpp b/libraries/ArduinoJson/extras/tests/JsonDocument/createNested.cpp new file mode 100644 index 0000000..0c94357 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDocument/createNested.cpp @@ -0,0 +1,66 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonDocument::createNestedArray()") { + DynamicJsonDocument doc(4096); + + SECTION("promotes to array") { + doc.createNestedArray(); + + REQUIRE(doc.is()); + } +} + +TEST_CASE("JsonDocument::createNestedArray(key)") { + DynamicJsonDocument doc(4096); + + SECTION("key is const char*") { + SECTION("promotes to object") { + doc.createNestedArray("hello"); + + REQUIRE(doc.is()); + } + } + + SECTION("key is std::string") { + SECTION("promotes to object") { + doc.createNestedArray(std::string("hello")); + + REQUIRE(doc.is()); + } + } +} + +TEST_CASE("JsonDocument::createNestedObject()") { + DynamicJsonDocument doc(4096); + + SECTION("promotes to array") { + doc.createNestedObject(); + + REQUIRE(doc.is()); + } +} + +TEST_CASE("JsonDocument::createNestedObject(key)") { + DynamicJsonDocument doc(4096); + + SECTION("key is const char*") { + SECTION("promotes to object") { + doc.createNestedObject("hello"); + + REQUIRE(doc.is()); + } + } + + SECTION("key is std::string") { + SECTION("promotes to object") { + doc.createNestedObject(std::string("hello")); + + REQUIRE(doc.is()); + } + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDocument/isNull.cpp b/libraries/ArduinoJson/extras/tests/JsonDocument/isNull.cpp new file mode 100644 index 0000000..d5aaae0 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDocument/isNull.cpp @@ -0,0 +1,39 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonDocument::isNull()") { + DynamicJsonDocument doc(4096); + + SECTION("returns true if uninitialized") { + REQUIRE(doc.isNull() == true); + } + + SECTION("returns false after to()") { + doc.to(); + REQUIRE(doc.isNull() == false); + } + + SECTION("returns false after to()") { + doc.to(); + REQUIRE(doc.isNull() == false); + } + + SECTION("returns true after to()") { + REQUIRE(doc.isNull() == true); + } + + SECTION("returns false after set()") { + doc.to().set(42); + REQUIRE(doc.isNull() == false); + } + + SECTION("returns true after clear()") { + doc.to(); + doc.clear(); + REQUIRE(doc.isNull() == true); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDocument/issue1120.cpp b/libraries/ArduinoJson/extras/tests/JsonDocument/issue1120.cpp new file mode 100644 index 0000000..fbee477 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDocument/issue1120.cpp @@ -0,0 +1,58 @@ +#include + +#include + +TEST_CASE("Issue #1120") { + StaticJsonDocument<500> doc; + constexpr char str[] = + "{\"contents\":[{\"module\":\"Packet\"},{\"module\":\"Analog\"}]}"; + deserializeJson(doc, str); + + SECTION("MemberProxy::isNull()") { + SECTION("returns false") { + auto value = doc[std::string("contents")]; + CHECK(value.isNull() == false); + } + + SECTION("returns true") { + auto value = doc[std::string("zontents")]; + CHECK(value.isNull() == true); + } + } + + SECTION("ElementProxy >::isNull()") { + SECTION("returns false") { // Issue #1120 + auto value = doc["contents"][1]; + CHECK(value.isNull() == false); + } + + SECTION("returns true") { + auto value = doc["contents"][2]; + CHECK(value.isNull() == true); + } + } + + SECTION("MemberProxy, const char*>::isNull()") { + SECTION("returns false") { + auto value = doc["contents"][1]["module"]; + CHECK(value.isNull() == false); + } + + SECTION("returns true") { + auto value = doc["contents"][1]["zodule"]; + CHECK(value.isNull() == true); + } + } + + SECTION("MemberProxy, std::string>::isNull()") { + SECTION("returns false") { + auto value = doc["contents"][1][std::string("module")]; + CHECK(value.isNull() == false); + } + + SECTION("returns true") { + auto value = doc["contents"][1][std::string("zodule")]; + CHECK(value.isNull() == true); + } + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDocument/nesting.cpp b/libraries/ArduinoJson/extras/tests/JsonDocument/nesting.cpp new file mode 100644 index 0000000..7ac7e76 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDocument/nesting.cpp @@ -0,0 +1,30 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonDocument::nesting()") { + DynamicJsonDocument doc(4096); + + SECTION("return 0 if uninitialized") { + REQUIRE(doc.nesting() == 0); + } + + SECTION("returns 0 for string") { + JsonVariant var = doc.to(); + var.set("hello"); + REQUIRE(doc.nesting() == 0); + } + + SECTION("returns 1 for empty object") { + doc.to(); + REQUIRE(doc.nesting() == 1); + } + + SECTION("returns 1 for empty array") { + doc.to(); + REQUIRE(doc.nesting() == 1); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDocument/overflowed.cpp b/libraries/ArduinoJson/extras/tests/JsonDocument/overflowed.cpp new file mode 100644 index 0000000..e46d21b --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDocument/overflowed.cpp @@ -0,0 +1,85 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonDocument::overflowed()") { + SECTION("returns false on a fresh object") { + StaticJsonDocument<0> doc; + CHECK(doc.overflowed() == false); + } + + SECTION("returns true after a failed insertion") { + StaticJsonDocument<0> doc; + doc.add(0); + CHECK(doc.overflowed() == true); + } + + SECTION("returns false after successful insertion") { + StaticJsonDocument doc; + doc.add(0); + CHECK(doc.overflowed() == false); + } + + SECTION("returns true after a failed string copy") { + StaticJsonDocument doc; + doc.add(std::string("example")); + CHECK(doc.overflowed() == true); + } + + SECTION("returns false after a successful string copy") { + StaticJsonDocument doc; + doc.add(std::string("example")); + CHECK(doc.overflowed() == false); + } + + SECTION("returns true after a failed member add") { + StaticJsonDocument<1> doc; + doc["example"] = true; + CHECK(doc.overflowed() == true); + } + + SECTION("returns true after a failed deserialization") { + StaticJsonDocument doc; + deserializeJson(doc, "[\"example\"]"); + CHECK(doc.overflowed() == true); + } + + SECTION("returns false after a successful deserialization") { + StaticJsonDocument doc; + deserializeJson(doc, "[\"example\"]"); + CHECK(doc.overflowed() == false); + } + + SECTION("returns false after clear()") { + StaticJsonDocument<0> doc; + doc.add(0); + doc.clear(); + CHECK(doc.overflowed() == false); + } + + SECTION("remains false after shrinkToFit()") { + DynamicJsonDocument doc(JSON_ARRAY_SIZE(1)); + doc.add(0); + doc.shrinkToFit(); + CHECK(doc.overflowed() == false); + } + + SECTION("remains true after shrinkToFit()") { + DynamicJsonDocument doc(JSON_ARRAY_SIZE(1)); + doc.add(0); + doc.add(0); + doc.shrinkToFit(); + CHECK(doc.overflowed() == true); + } + + SECTION("return false after garbageCollect()") { + DynamicJsonDocument doc(JSON_ARRAY_SIZE(1)); + doc.add(0); + doc.add(0); + doc.garbageCollect(); + CHECK(doc.overflowed() == false); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDocument/remove.cpp b/libraries/ArduinoJson/extras/tests/JsonDocument/remove.cpp new file mode 100644 index 0000000..724b324 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDocument/remove.cpp @@ -0,0 +1,52 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonDocument::remove()") { + DynamicJsonDocument doc(4096); + + SECTION("remove(int)") { + doc.add(1); + doc.add(2); + doc.add(3); + + doc.remove(1); + + REQUIRE(doc.as() == "[1,3]"); + } + + SECTION("remove(const char *)") { + doc["a"] = 1; + doc["b"] = 2; + + doc.remove("a"); + + REQUIRE(doc.as() == "{\"b\":2}"); + } + + SECTION("remove(std::string)") { + doc["a"] = 1; + doc["b"] = 2; + + doc.remove(std::string("b")); + + REQUIRE(doc.as() == "{\"a\":1}"); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("remove(vla)") { + doc["a"] = 1; + doc["b"] = 2; + + size_t i = 4; + char vla[i]; + strcpy(vla, "b"); + doc.remove(vla); + + REQUIRE(doc.as() == "{\"a\":1}"); + } +#endif +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDocument/shrinkToFit.cpp b/libraries/ArduinoJson/extras/tests/JsonDocument/shrinkToFit.cpp new file mode 100644 index 0000000..a442334 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDocument/shrinkToFit.cpp @@ -0,0 +1,152 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +#include // malloc, free +#include + +class ArmoredAllocator { + public: + ArmoredAllocator() : ptr_(0), size_(0) {} + + void* allocate(size_t size) { + ptr_ = malloc(size); + size_ = size; + return ptr_; + } + + void deallocate(void* ptr) { + REQUIRE(ptr == ptr_); + free(ptr); + ptr_ = 0; + size_ = 0; + } + + void* reallocate(void* ptr, size_t new_size) { + REQUIRE(ptr == ptr_); + // don't call realloc, instead alloc a new buffer and erase the old one + // this way we make sure we support relocation + void* new_ptr = malloc(new_size); + memcpy(new_ptr, ptr_, std::min(new_size, size_)); + memset(ptr_, '#', size_); // erase + free(ptr_); + ptr_ = new_ptr; + return new_ptr; + } + + private: + void* ptr_; + size_t size_; +}; + +typedef BasicJsonDocument ShrinkToFitTestDocument; + +void testShrinkToFit(ShrinkToFitTestDocument& doc, std::string expected_json, + size_t expected_size) { + // test twice: shrinkToFit() should be idempotent + for (int i = 0; i < 2; i++) { + doc.shrinkToFit(); + + REQUIRE(doc.capacity() == expected_size); + REQUIRE(doc.memoryUsage() == expected_size); + + std::string json; + serializeJson(doc, json); + REQUIRE(json == expected_json); + } +} + +TEST_CASE("BasicJsonDocument::shrinkToFit()") { + ShrinkToFitTestDocument doc(4096); + + SECTION("null") { + testShrinkToFit(doc, "null", 0); + } + + SECTION("empty object") { + deserializeJson(doc, "{}"); + testShrinkToFit(doc, "{}", JSON_OBJECT_SIZE(0)); + } + + SECTION("empty array") { + deserializeJson(doc, "[]"); + testShrinkToFit(doc, "[]", JSON_ARRAY_SIZE(0)); + } + + SECTION("linked string") { + doc.set("hello"); + testShrinkToFit(doc, "\"hello\"", 0); + } + + SECTION("owned string") { + doc.set(std::string("abcdefg")); + testShrinkToFit(doc, "\"abcdefg\"", 8); + } + + SECTION("linked raw") { + doc.set(serialized("[{},123]")); + testShrinkToFit(doc, "[{},123]", 0); + } + + SECTION("owned raw") { + doc.set(serialized(std::string("[{},12]"))); + testShrinkToFit(doc, "[{},12]", 8); + } + + SECTION("linked key") { + doc["key"] = 42; + testShrinkToFit(doc, "{\"key\":42}", JSON_OBJECT_SIZE(1)); + } + + SECTION("owned key") { + doc[std::string("abcdefg")] = 42; + testShrinkToFit(doc, "{\"abcdefg\":42}", JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("linked string in array") { + doc.add("hello"); + testShrinkToFit(doc, "[\"hello\"]", JSON_ARRAY_SIZE(1)); + } + + SECTION("owned string in array") { + doc.add(std::string("abcdefg")); + testShrinkToFit(doc, "[\"abcdefg\"]", JSON_ARRAY_SIZE(1) + 8); + } + + SECTION("linked string in object") { + doc["key"] = "hello"; + testShrinkToFit(doc, "{\"key\":\"hello\"}", JSON_OBJECT_SIZE(1)); + } + + SECTION("owned string in object") { + doc["key"] = std::string("abcdefg"); + testShrinkToFit(doc, "{\"key\":\"abcdefg\"}", JSON_ARRAY_SIZE(1) + 8); + } + + SECTION("unaligned") { + doc.add(std::string("?")); // two bytes in the string pool + REQUIRE(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 2); + + doc.shrinkToFit(); + + // the new capacity should be padded to align the pointers + REQUIRE(doc.capacity() == JSON_OBJECT_SIZE(1) + sizeof(void*)); + REQUIRE(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 2); + REQUIRE(doc[0] == "?"); + } +} + +TEST_CASE("DynamicJsonDocument::shrinkToFit()") { + DynamicJsonDocument doc(4096); + + deserializeJson(doc, "{\"hello\":[\"world\"]"); + + doc.shrinkToFit(); + + std::string json; + serializeJson(doc, json); + REQUIRE(json == "{\"hello\":[\"world\"]}"); +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDocument/size.cpp b/libraries/ArduinoJson/extras/tests/JsonDocument/size.cpp new file mode 100644 index 0000000..b3205a1 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDocument/size.cpp @@ -0,0 +1,28 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonDocument::size()") { + DynamicJsonDocument doc(4096); + + SECTION("returns 0") { + REQUIRE(doc.size() == 0); + } + + SECTION("as an array, return 2") { + doc.add(1); + doc.add(2); + + REQUIRE(doc.size() == 2); + } + + SECTION("as an object, return 2") { + doc["a"] = 1; + doc["b"] = 2; + + REQUIRE(doc.size() == 2); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDocument/subscript.cpp b/libraries/ArduinoJson/extras/tests/JsonDocument/subscript.cpp new file mode 100644 index 0000000..f4186f8 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDocument/subscript.cpp @@ -0,0 +1,53 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonDocument::operator[]") { + DynamicJsonDocument doc(4096); + const JsonDocument& cdoc = doc; + + SECTION("object") { + deserializeJson(doc, "{\"hello\":\"world\"}"); + + SECTION("const char*") { + REQUIRE(doc["hello"] == "world"); + REQUIRE(cdoc["hello"] == "world"); + } + + SECTION("std::string") { + REQUIRE(doc[std::string("hello")] == "world"); + REQUIRE(cdoc[std::string("hello")] == "world"); + } + + SECTION("supports operator|") { + REQUIRE((doc["hello"] | "nope") == std::string("world")); + REQUIRE((doc["world"] | "nope") == std::string("nope")); + } + } + + SECTION("array") { + deserializeJson(doc, "[\"hello\",\"world\"]"); + + REQUIRE(doc[1] == "world"); + REQUIRE(cdoc[1] == "world"); + } +} + +TEST_CASE("JsonDocument automatically promotes to object") { + DynamicJsonDocument doc(4096); + + doc["one"]["two"]["three"] = 4; + + REQUIRE(doc["one"]["two"]["three"] == 4); +} + +TEST_CASE("JsonDocument automatically promotes to array") { + DynamicJsonDocument doc(4096); + + doc[2] = 2; + + REQUIRE(doc.as() == "[null,null,2]"); +} diff --git a/libraries/ArduinoJson/extras/tests/JsonDocument/swap.cpp b/libraries/ArduinoJson/extras/tests/JsonDocument/swap.cpp new file mode 100644 index 0000000..60d672f --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonDocument/swap.cpp @@ -0,0 +1,27 @@ +#include + +#include +#include +#include + +using namespace std; + +TEST_CASE("std::swap") { + SECTION("DynamicJsonDocument*") { + DynamicJsonDocument *p1, *p2; + swap(p1, p2); // issue #1678 + } + + SECTION("DynamicJsonDocument") { + DynamicJsonDocument doc1(0x10), doc2(0x20); + doc1.set("hello"); + doc2.set("world"); + + swap(doc1, doc2); + + CHECK(doc1.capacity() == 0x20); + CHECK(doc1.as() == "world"); + CHECK(doc2.capacity() == 0x10); + CHECK(doc2.as() == "hello"); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonObject/CMakeLists.txt b/libraries/ArduinoJson/extras/tests/JsonObject/CMakeLists.txt new file mode 100644 index 0000000..8676811 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonObject/CMakeLists.txt @@ -0,0 +1,29 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2023, Benoit BLANCHON +# MIT License + +add_executable(JsonObjectTests + clear.cpp + compare.cpp + containsKey.cpp + copy.cpp + createNestedArray.cpp + createNestedObject.cpp + equals.cpp + invalid.cpp + isNull.cpp + iterator.cpp + memoryUsage.cpp + nesting.cpp + remove.cpp + size.cpp + std_string.cpp + subscript.cpp +) + +add_test(JsonObject JsonObjectTests) + +set_tests_properties(JsonObject + PROPERTIES + LABELS "Catch" +) diff --git a/libraries/ArduinoJson/extras/tests/JsonObject/clear.cpp b/libraries/ArduinoJson/extras/tests/JsonObject/clear.cpp new file mode 100644 index 0000000..e112a8d --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonObject/clear.cpp @@ -0,0 +1,25 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonObject::clear()") { + SECTION("No-op on null JsonObject") { + JsonObject obj; + obj.clear(); + REQUIRE(obj.isNull() == true); + REQUIRE(obj.size() == 0); + } + + SECTION("Removes all elements") { + StaticJsonDocument<64> doc; + JsonObject obj = doc.to(); + obj["hello"] = 1; + obj["world"] = 2; + obj.clear(); + REQUIRE(obj.size() == 0); + REQUIRE(obj.isNull() == false); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonObject/compare.cpp b/libraries/ArduinoJson/extras/tests/JsonObject/compare.cpp new file mode 100644 index 0000000..9b747e3 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonObject/compare.cpp @@ -0,0 +1,512 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("Compare JsonObject with JsonObject") { + StaticJsonDocument<512> doc; + + SECTION("Compare with unbound") { + JsonObject object = doc.to(); + object["a"] = 1; + object["b"] = "hello"; + JsonObject unbound; + + CHECK(object != unbound); + CHECK_FALSE(object == unbound); + CHECK_FALSE(object <= unbound); + CHECK_FALSE(object >= unbound); + CHECK_FALSE(object > unbound); + CHECK_FALSE(object < unbound); + + CHECK(unbound != object); + CHECK_FALSE(unbound == object); + CHECK_FALSE(unbound <= object); + CHECK_FALSE(unbound >= object); + CHECK_FALSE(unbound > object); + CHECK_FALSE(unbound < object); + } + + SECTION("Compare with self") { + JsonObject object = doc.to(); + object["a"] = 1; + object["b"] = "hello"; + + CHECK(object == object); + CHECK(object <= object); + CHECK(object >= object); + CHECK_FALSE(object != object); + CHECK_FALSE(object > object); + CHECK_FALSE(object < object); + } + + SECTION("Compare with identical object") { + JsonObject object1 = doc.createNestedObject(); + object1["a"] = 1; + object1["b"] = "hello"; + object1["c"][0] = false; + + JsonObject object2 = doc.createNestedObject(); + object2["a"] = 1; + object2["b"] = "hello"; + object2["c"][0] = false; + + CHECK(object1 == object2); + CHECK(object1 <= object2); + CHECK(object1 >= object2); + CHECK_FALSE(object1 != object2); + CHECK_FALSE(object1 > object2); + CHECK_FALSE(object1 < object2); + } + + SECTION("Compare with different object") { + JsonObject object1 = doc.createNestedObject(); + object1["a"] = 1; + object1["b"] = "hello1"; + object1["c"][0] = false; + + JsonObject object2 = doc.createNestedObject(); + object2["a"] = 1; + object2["b"] = "hello2"; + object2["c"][0] = false; + + CHECK(object1 != object2); + CHECK_FALSE(object1 == object2); + CHECK_FALSE(object1 > object2); + CHECK_FALSE(object1 < object2); + CHECK_FALSE(object1 <= object2); + CHECK_FALSE(object1 >= object2); + } +} + +TEST_CASE("Compare JsonObject with JsonVariant") { + StaticJsonDocument<512> doc; + + SECTION("Compare with self") { + JsonObject object = doc.to(); + object["a"] = 1; + object["b"] = "hello"; + + JsonVariant variant = object; + + CHECK(object == variant); + CHECK(object <= variant); + CHECK(object >= variant); + CHECK_FALSE(object != variant); + CHECK_FALSE(object > variant); + CHECK_FALSE(object < variant); + + CHECK(variant == object); + CHECK(variant <= object); + CHECK(variant >= object); + CHECK_FALSE(variant != object); + CHECK_FALSE(variant > object); + CHECK_FALSE(variant < object); + } + + SECTION("Compare with identical object") { + JsonObject object = doc.createNestedObject(); + object["a"] = 1; + object["b"] = "hello"; + object["c"][0] = false; + + JsonVariant variant = doc.createNestedObject(); + variant["a"] = 1; + variant["b"] = "hello"; + variant["c"][0] = false; + + CHECK(object == variant); + CHECK(object <= variant); + CHECK(object >= variant); + CHECK_FALSE(object != variant); + CHECK_FALSE(object > variant); + CHECK_FALSE(object < variant); + + CHECK(variant == object); + CHECK(variant <= object); + CHECK(variant >= object); + CHECK_FALSE(variant != object); + CHECK_FALSE(variant > object); + CHECK_FALSE(variant < object); + } + + SECTION("Compare with different object") { + JsonObject object = doc.createNestedObject(); + object["a"] = 1; + object["b"] = "hello1"; + object["c"][0] = false; + + JsonVariant variant = doc.createNestedObject(); + variant["a"] = 1; + variant["b"] = "hello2"; + variant["c"][0] = false; + + CHECK(object != variant); + CHECK_FALSE(object == variant); + CHECK_FALSE(object > variant); + CHECK_FALSE(object < variant); + CHECK_FALSE(object <= variant); + CHECK_FALSE(object >= variant); + } +} + +TEST_CASE("Compare JsonObject with JsonVariantConst") { + StaticJsonDocument<512> doc; + + SECTION("Compare with unbound") { + JsonObject object = doc.to(); + object["a"] = 1; + object["b"] = "hello"; + JsonVariantConst unbound; + + CHECK(object != unbound); + CHECK_FALSE(object == unbound); + CHECK_FALSE(object <= unbound); + CHECK_FALSE(object >= unbound); + CHECK_FALSE(object > unbound); + CHECK_FALSE(object < unbound); + + CHECK(unbound != object); + CHECK_FALSE(unbound == object); + CHECK_FALSE(unbound <= object); + CHECK_FALSE(unbound >= object); + CHECK_FALSE(unbound > object); + CHECK_FALSE(unbound < object); + } + + SECTION("Compare with self") { + JsonObject object = doc.to(); + object["a"] = 1; + object["b"] = "hello"; + + JsonVariantConst variant = object; + + CHECK(object == variant); + CHECK(object <= variant); + CHECK(object >= variant); + CHECK_FALSE(object != variant); + CHECK_FALSE(object > variant); + CHECK_FALSE(object < variant); + + CHECK(variant == object); + CHECK(variant <= object); + CHECK(variant >= object); + CHECK_FALSE(variant != object); + CHECK_FALSE(variant > object); + CHECK_FALSE(variant < object); + } + + SECTION("Compare with identical object") { + JsonObject object = doc.createNestedObject(); + object["a"] = 1; + object["b"] = "hello"; + object["c"][0] = false; + + JsonObject object2 = doc.createNestedObject(); + object2["a"] = 1; + object2["b"] = "hello"; + object2["c"][0] = false; + JsonVariantConst variant = object2; + + CHECK(object == variant); + CHECK(object <= variant); + CHECK(object >= variant); + CHECK_FALSE(object != variant); + CHECK_FALSE(object > variant); + CHECK_FALSE(object < variant); + + CHECK(variant == object); + CHECK(variant <= object); + CHECK(variant >= object); + CHECK_FALSE(variant != object); + CHECK_FALSE(variant > object); + CHECK_FALSE(variant < object); + } + + SECTION("Compare with different object") { + JsonObject object = doc.createNestedObject(); + object["a"] = 1; + object["b"] = "hello1"; + object["c"][0] = false; + + JsonObject object2 = doc.createNestedObject(); + object2["a"] = 1; + object2["b"] = "hello2"; + object2["c"][0] = false; + JsonVariantConst variant = object2; + + CHECK(object != variant); + CHECK_FALSE(object == variant); + CHECK_FALSE(object > variant); + CHECK_FALSE(object < variant); + CHECK_FALSE(object <= variant); + CHECK_FALSE(object >= variant); + } +} + +TEST_CASE("Compare JsonObject with JsonObjectConst") { + StaticJsonDocument<512> doc; + + SECTION("Compare with unbound") { + JsonObject object = doc.to(); + object["a"] = 1; + object["b"] = "hello"; + JsonObjectConst unbound; + + CHECK(object != unbound); + CHECK_FALSE(object == unbound); + CHECK_FALSE(object <= unbound); + CHECK_FALSE(object >= unbound); + CHECK_FALSE(object > unbound); + CHECK_FALSE(object < unbound); + + CHECK(unbound != object); + CHECK_FALSE(unbound == object); + CHECK_FALSE(unbound <= object); + CHECK_FALSE(unbound >= object); + CHECK_FALSE(unbound > object); + CHECK_FALSE(unbound < object); + } + + SECTION("Compare with self") { + JsonObject object = doc.to(); + object["a"] = 1; + object["b"] = "hello"; + JsonObjectConst cobject = object; + + CHECK(object == cobject); + CHECK(object <= cobject); + CHECK(object >= cobject); + CHECK_FALSE(object != cobject); + CHECK_FALSE(object > cobject); + CHECK_FALSE(object < cobject); + + CHECK(cobject == object); + CHECK(cobject <= object); + CHECK(cobject >= object); + CHECK_FALSE(cobject != object); + CHECK_FALSE(cobject > object); + CHECK_FALSE(cobject < object); + } + + SECTION("Compare with identical object") { + JsonObject object1 = doc.createNestedObject(); + object1["a"] = 1; + object1["b"] = "hello"; + object1["c"][0] = false; + + JsonObject object2 = doc.createNestedObject(); + object2["a"] = 1; + object2["b"] = "hello"; + object2["c"][0] = false; + JsonObjectConst carray2 = object2; + + CHECK(object1 == carray2); + CHECK(object1 <= carray2); + CHECK(object1 >= carray2); + CHECK_FALSE(object1 != carray2); + CHECK_FALSE(object1 > carray2); + CHECK_FALSE(object1 < carray2); + + CHECK(carray2 == object1); + CHECK(carray2 <= object1); + CHECK(carray2 >= object1); + CHECK_FALSE(carray2 != object1); + CHECK_FALSE(carray2 > object1); + CHECK_FALSE(carray2 < object1); + } + + SECTION("Compare with different object") { + JsonObject object1 = doc.createNestedObject(); + object1["a"] = 1; + object1["b"] = "hello1"; + object1["c"][0] = false; + + JsonObject object2 = doc.createNestedObject(); + object2["a"] = 1; + object2["b"] = "hello2"; + object2["c"][0] = false; + JsonObjectConst carray2 = object2; + + CHECK(object1 != carray2); + CHECK_FALSE(object1 == carray2); + CHECK_FALSE(object1 > carray2); + CHECK_FALSE(object1 < carray2); + CHECK_FALSE(object1 <= carray2); + CHECK_FALSE(object1 >= carray2); + + CHECK(carray2 != object1); + CHECK_FALSE(carray2 == object1); + CHECK_FALSE(carray2 > object1); + CHECK_FALSE(carray2 < object1); + CHECK_FALSE(carray2 <= object1); + CHECK_FALSE(carray2 >= object1); + } +} + +TEST_CASE("Compare JsonObjectConst with JsonObjectConst") { + StaticJsonDocument<512> doc; + + SECTION("Compare with unbound") { + JsonObject object = doc.to(); + object["a"] = 1; + object["b"] = "hello"; + + JsonObjectConst cobject = object; + JsonObjectConst unbound; + + CHECK(cobject != unbound); + CHECK_FALSE(cobject == unbound); + CHECK_FALSE(cobject <= unbound); + CHECK_FALSE(cobject >= unbound); + CHECK_FALSE(cobject > unbound); + CHECK_FALSE(cobject < unbound); + + CHECK(unbound != cobject); + CHECK_FALSE(unbound == cobject); + CHECK_FALSE(unbound <= cobject); + CHECK_FALSE(unbound >= cobject); + CHECK_FALSE(unbound > cobject); + CHECK_FALSE(unbound < cobject); + } + + SECTION("Compare with self") { + JsonObject object = doc.to(); + object["a"] = 1; + object["b"] = "hello"; + JsonObjectConst cobject = object; + + CHECK(cobject == cobject); + CHECK(cobject <= cobject); + CHECK(cobject >= cobject); + CHECK_FALSE(cobject != cobject); + CHECK_FALSE(cobject > cobject); + CHECK_FALSE(cobject < cobject); + } + + SECTION("Compare with identical object") { + JsonObject object1 = doc.createNestedObject(); + object1["a"] = 1; + object1["b"] = "hello"; + object1["c"][0] = false; + JsonObjectConst carray1 = object1; + + JsonObject object2 = doc.createNestedObject(); + object2["a"] = 1; + object2["b"] = "hello"; + object2["c"][0] = false; + JsonObjectConst carray2 = object2; + + CHECK(carray1 == carray2); + CHECK(carray1 <= carray2); + CHECK(carray1 >= carray2); + CHECK_FALSE(carray1 != carray2); + CHECK_FALSE(carray1 > carray2); + CHECK_FALSE(carray1 < carray2); + } + + SECTION("Compare with different object") { + JsonObject object1 = doc.createNestedObject(); + object1["a"] = 1; + object1["b"] = "hello1"; + object1["c"][0] = false; + JsonObjectConst carray1 = object1; + + JsonObject object2 = doc.createNestedObject(); + object2["a"] = 1; + object2["b"] = "hello2"; + object2["c"][0] = false; + JsonObjectConst carray2 = object2; + + CHECK(carray1 != carray2); + CHECK_FALSE(carray1 == carray2); + CHECK_FALSE(carray1 > carray2); + CHECK_FALSE(carray1 < carray2); + CHECK_FALSE(carray1 <= carray2); + CHECK_FALSE(carray1 >= carray2); + } +} + +TEST_CASE("Compare JsonObjectConst with JsonVariant") { + StaticJsonDocument<512> doc; + + SECTION("Compare with self") { + JsonObject object = doc.to(); + object["a"] = 1; + object["b"] = "hello"; + JsonObjectConst cobject = object; + JsonVariant variant = object; + + CHECK(cobject == variant); + CHECK(cobject <= variant); + CHECK(cobject >= variant); + CHECK_FALSE(cobject != variant); + CHECK_FALSE(cobject > variant); + CHECK_FALSE(cobject < variant); + + CHECK(variant == cobject); + CHECK(variant <= cobject); + CHECK(variant >= cobject); + CHECK_FALSE(variant != cobject); + CHECK_FALSE(variant > cobject); + CHECK_FALSE(variant < cobject); + } + + SECTION("Compare with identical object") { + JsonObject object1 = doc.createNestedObject(); + object1["a"] = 1; + object1["b"] = "hello"; + object1["c"][0] = false; + JsonObjectConst carray1 = object1; + + JsonObject object2 = doc.createNestedObject(); + object2["a"] = 1; + object2["b"] = "hello"; + object2["c"][0] = false; + JsonVariant variant2 = object2; + + CHECK(carray1 == variant2); + CHECK(carray1 <= variant2); + CHECK(carray1 >= variant2); + CHECK_FALSE(carray1 != variant2); + CHECK_FALSE(carray1 > variant2); + CHECK_FALSE(carray1 < variant2); + + CHECK(variant2 == carray1); + CHECK(variant2 <= carray1); + CHECK(variant2 >= carray1); + CHECK_FALSE(variant2 != carray1); + CHECK_FALSE(variant2 > carray1); + CHECK_FALSE(variant2 < carray1); + } + + SECTION("Compare with different object") { + JsonObject object1 = doc.createNestedObject(); + object1["a"] = 1; + object1["b"] = "hello1"; + object1["c"][0] = false; + JsonObjectConst carray1 = object1; + + JsonObject object2 = doc.createNestedObject(); + object2["a"] = 1; + object2["b"] = "hello2"; + object2["c"][0] = false; + JsonVariant variant2 = object2; + + CHECK(carray1 != variant2); + CHECK_FALSE(carray1 == variant2); + CHECK_FALSE(carray1 > variant2); + CHECK_FALSE(carray1 < variant2); + CHECK_FALSE(carray1 <= variant2); + CHECK_FALSE(carray1 >= variant2); + + CHECK(variant2 != carray1); + CHECK_FALSE(variant2 == carray1); + CHECK_FALSE(variant2 > carray1); + CHECK_FALSE(variant2 < carray1); + CHECK_FALSE(variant2 <= carray1); + CHECK_FALSE(variant2 >= carray1); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonObject/containsKey.cpp b/libraries/ArduinoJson/extras/tests/JsonObject/containsKey.cpp new file mode 100644 index 0000000..85335a8 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonObject/containsKey.cpp @@ -0,0 +1,39 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonObject::containsKey()") { + DynamicJsonDocument doc(4096); + JsonObject obj = doc.to(); + obj["hello"] = 42; + + SECTION("returns true only if key is present") { + REQUIRE(false == obj.containsKey("world")); + REQUIRE(true == obj.containsKey("hello")); + } + + SECTION("works with JsonObjectConst") { + JsonObjectConst cobj = obj; + REQUIRE(false == cobj.containsKey("world")); + REQUIRE(true == cobj.containsKey("hello")); + } + + SECTION("returns false after remove()") { + obj.remove("hello"); + + REQUIRE(false == obj.containsKey("hello")); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("key is a VLA") { + size_t i = 16; + char vla[i]; + strcpy(vla, "hello"); + + REQUIRE(true == obj.containsKey(vla)); + } +#endif +} diff --git a/libraries/ArduinoJson/extras/tests/JsonObject/copy.cpp b/libraries/ArduinoJson/extras/tests/JsonObject/copy.cpp new file mode 100644 index 0000000..a4d5b5f --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonObject/copy.cpp @@ -0,0 +1,115 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonObject::set()") { + DynamicJsonDocument doc1(4096); + DynamicJsonDocument doc2(4096); + + JsonObject obj1 = doc1.to(); + JsonObject obj2 = doc2.to(); + + SECTION("doesn't copy static string in key or value") { + obj1["hello"] = "world"; + + bool success = obj2.set(obj1); + + REQUIRE(success == true); + REQUIRE(doc1.memoryUsage() == doc2.memoryUsage()); + REQUIRE(obj2["hello"] == std::string("world")); + } + + SECTION("copy local string value") { + obj1["hello"] = std::string("world"); + + bool success = obj2.set(obj1); + + REQUIRE(success == true); + REQUIRE(doc1.memoryUsage() == doc2.memoryUsage()); + REQUIRE(obj2["hello"] == std::string("world")); + } + + SECTION("copy local key") { + obj1[std::string("hello")] = "world"; + + bool success = obj2.set(obj1); + + REQUIRE(success == true); + REQUIRE(doc1.memoryUsage() == doc2.memoryUsage()); + REQUIRE(obj2["hello"] == std::string("world")); + } + + SECTION("copy string from deserializeJson()") { + deserializeJson(doc1, "{'hello':'world'}"); + + bool success = obj2.set(obj1); + + REQUIRE(success == true); + REQUIRE(doc1.memoryUsage() == doc2.memoryUsage()); + REQUIRE(obj2["hello"] == std::string("world")); + } + + SECTION("copy string from deserializeMsgPack()") { + deserializeMsgPack(doc1, "\x81\xA5hello\xA5world"); + + bool success = obj2.set(obj1); + + REQUIRE(success == true); + REQUIRE(doc1.memoryUsage() == doc2.memoryUsage()); + REQUIRE(obj2["hello"] == std::string("world")); + } + + SECTION("should work with JsonObjectConst") { + obj1["hello"] = "world"; + + obj2.set(static_cast(obj1)); + + REQUIRE(doc1.memoryUsage() == doc2.memoryUsage()); + REQUIRE(obj2["hello"] == std::string("world")); + } + + SECTION("destination too small to store the key") { + StaticJsonDocument doc3; + JsonObject obj3 = doc3.to(); + + obj1[std::string("hello")] = "world"; + + bool success = obj3.set(obj1); + + REQUIRE(success == false); + REQUIRE(doc3.as() == "{}"); + } + + SECTION("destination too small to store the value") { + StaticJsonDocument doc3; + JsonObject obj3 = doc3.to(); + + obj1["hello"] = std::string("world"); + + bool success = obj3.set(obj1); + + REQUIRE(success == false); + REQUIRE(doc3.as() == "{\"hello\":null}"); + } + + SECTION("destination is null") { + JsonObject null; + obj1["hello"] = "world"; + + bool success = null.set(obj1); + + REQUIRE(success == false); + } + + SECTION("source is null") { + JsonObject null; + obj1["hello"] = "world"; + + bool success = obj1.set(null); + + REQUIRE(success == false); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonObject/createNestedArray.cpp b/libraries/ArduinoJson/extras/tests/JsonObject/createNestedArray.cpp new file mode 100644 index 0000000..26c1a86 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonObject/createNestedArray.cpp @@ -0,0 +1,27 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonObject::createNestedArray()") { + DynamicJsonDocument doc(4096); + JsonObject obj = doc.to(); + + SECTION("key is a const char*") { + JsonArray arr = obj.createNestedArray("hello"); + REQUIRE(arr.isNull() == false); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("key is a VLA") { + size_t i = 16; + char vla[i]; + strcpy(vla, "hello"); + + JsonArray arr = obj.createNestedArray(vla); + REQUIRE(arr.isNull() == false); + } +#endif +} diff --git a/libraries/ArduinoJson/extras/tests/JsonObject/createNestedObject.cpp b/libraries/ArduinoJson/extras/tests/JsonObject/createNestedObject.cpp new file mode 100644 index 0000000..9ea067a --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonObject/createNestedObject.cpp @@ -0,0 +1,25 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonObject::createNestedObject()") { + DynamicJsonDocument doc(4096); + JsonObject obj = doc.to(); + + SECTION("key is a const char*") { + obj.createNestedObject("hello"); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("key is a VLA") { + size_t i = 16; + char vla[i]; + strcpy(vla, "hello"); + + obj.createNestedObject(vla); + } +#endif +} diff --git a/libraries/ArduinoJson/extras/tests/JsonObject/equals.cpp b/libraries/ArduinoJson/extras/tests/JsonObject/equals.cpp new file mode 100644 index 0000000..02d451f --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonObject/equals.cpp @@ -0,0 +1,67 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonObject::operator==()") { + DynamicJsonDocument doc1(4096); + JsonObject obj1 = doc1.to(); + JsonObjectConst obj1c = obj1; + + DynamicJsonDocument doc2(4096); + JsonObject obj2 = doc2.to(); + JsonObjectConst obj2c = obj2; + + SECTION("should return false when objs differ") { + obj1["hello"] = "coucou"; + obj2["world"] = 1; + + REQUIRE_FALSE(obj1 == obj2); + REQUIRE_FALSE(obj1c == obj2c); + } + + SECTION("should return false when LHS has more elements") { + obj1["hello"] = "coucou"; + obj1["world"] = 666; + obj2["hello"] = "coucou"; + + REQUIRE_FALSE(obj1 == obj2); + REQUIRE_FALSE(obj1c == obj2c); + } + + SECTION("should return false when RKS has more elements") { + obj1["hello"] = "coucou"; + obj2["hello"] = "coucou"; + obj2["world"] = 666; + + REQUIRE_FALSE(obj1 == obj2); + REQUIRE_FALSE(obj1c == obj2c); + } + + SECTION("should return true when objs equal") { + obj1["hello"] = "world"; + obj1["anwser"] = 42; + // insert in different order + obj2["anwser"] = 42; + obj2["hello"] = "world"; + + REQUIRE(obj1 == obj2); + REQUIRE(obj1c == obj2c); + } + + SECTION("should return false when RHS is null") { + JsonObject null; + + REQUIRE_FALSE(obj1 == null); + REQUIRE_FALSE(obj1c == null); + } + + SECTION("should return false when LHS is null") { + JsonObject null; + + REQUIRE_FALSE(null == obj2); + REQUIRE_FALSE(null == obj2c); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonObject/invalid.cpp b/libraries/ArduinoJson/extras/tests/JsonObject/invalid.cpp new file mode 100644 index 0000000..0695b48 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonObject/invalid.cpp @@ -0,0 +1,35 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +using namespace Catch::Matchers; + +TEST_CASE("JsonObject::invalid()") { + JsonObject obj; + + SECTION("SubscriptFails") { + REQUIRE(obj["key"].isNull()); + } + + SECTION("AddFails") { + obj["hello"] = "world"; + REQUIRE(0 == obj.size()); + } + + SECTION("CreateNestedArrayFails") { + REQUIRE(obj.createNestedArray("hello").isNull()); + } + + SECTION("CreateNestedObjectFails") { + REQUIRE(obj.createNestedObject("world").isNull()); + } + + SECTION("serialize to 'null'") { + char buffer[32]; + serializeJson(obj, buffer, sizeof(buffer)); + REQUIRE_THAT(buffer, Equals("null")); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonObject/isNull.cpp b/libraries/ArduinoJson/extras/tests/JsonObject/isNull.cpp new file mode 100644 index 0000000..9fdff95 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonObject/isNull.cpp @@ -0,0 +1,58 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonObject::isNull()") { + SECTION("returns true") { + JsonObject obj; + REQUIRE(obj.isNull() == true); + } + + SECTION("returns false") { + DynamicJsonDocument doc(4096); + JsonObject obj = doc.to(); + REQUIRE(obj.isNull() == false); + } +} + +TEST_CASE("JsonObjectConst::isNull()") { + SECTION("returns true") { + JsonObjectConst obj; + REQUIRE(obj.isNull() == true); + } + + SECTION("returns false") { + DynamicJsonDocument doc(4096); + JsonObjectConst obj = doc.to(); + REQUIRE(obj.isNull() == false); + } +} + +TEST_CASE("JsonObject::operator bool()") { + SECTION("returns false") { + JsonObject obj; + REQUIRE(static_cast(obj) == false); + } + + SECTION("returns true") { + DynamicJsonDocument doc(4096); + JsonObject obj = doc.to(); + REQUIRE(static_cast(obj) == true); + } +} + +TEST_CASE("JsonObjectConst::operator bool()") { + SECTION("returns false") { + JsonObjectConst obj; + REQUIRE(static_cast(obj) == false); + } + + SECTION("returns true") { + DynamicJsonDocument doc(4096); + JsonObjectConst obj = doc.to(); + REQUIRE(static_cast(obj) == true); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonObject/iterator.cpp b/libraries/ArduinoJson/extras/tests/JsonObject/iterator.cpp new file mode 100644 index 0000000..c48de5f --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonObject/iterator.cpp @@ -0,0 +1,73 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +using namespace Catch::Matchers; + +TEST_CASE("JsonObject::begin()/end()") { + StaticJsonDocument doc; + JsonObject obj = doc.to(); + obj["ab"] = 12; + obj["cd"] = 34; + + SECTION("NonConstIterator") { + JsonObject::iterator it = obj.begin(); + REQUIRE(obj.end() != it); + REQUIRE(it->key() == "ab"); + REQUIRE(12 == it->value()); + ++it; + REQUIRE(obj.end() != it); + REQUIRE(it->key() == "cd"); + REQUIRE(34 == it->value()); + ++it; + REQUIRE(obj.end() == it); + } + + SECTION("Dereferencing end() is safe") { + REQUIRE(obj.end()->key().isNull()); + REQUIRE(obj.end()->value().isNull()); + } + + SECTION("null JsonObject") { + JsonObject null; + REQUIRE(null.begin() == null.end()); + } +} + +TEST_CASE("JsonObjectConst::begin()/end()") { + StaticJsonDocument doc; + JsonObject obj = doc.to(); + obj["ab"] = 12; + obj["cd"] = 34; + + JsonObjectConst cobj = obj; + + SECTION("Iteration") { + JsonObjectConst::iterator it = cobj.begin(); + REQUIRE(cobj.end() != it); + REQUIRE(it->key() == "ab"); + REQUIRE(12 == it->value()); + + ++it; + REQUIRE(cobj.end() != it); + JsonPairConst pair = *it; + REQUIRE(pair.key() == "cd"); + REQUIRE(34 == pair.value()); + + ++it; + REQUIRE(cobj.end() == it); + } + + SECTION("Dereferencing end() is safe") { + REQUIRE(cobj.end()->key().isNull()); + REQUIRE(cobj.end()->value().isNull()); + } + + SECTION("null JsonObjectConst") { + JsonObjectConst null; + REQUIRE(null.begin() == null.end()); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonObject/memoryUsage.cpp b/libraries/ArduinoJson/extras/tests/JsonObject/memoryUsage.cpp new file mode 100644 index 0000000..406bcda --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonObject/memoryUsage.cpp @@ -0,0 +1,43 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include +#include + +TEST_CASE("JsonObject::memoryUsage()") { + DynamicJsonDocument doc(4096); + JsonObject obj = doc.to(); + + SECTION("return 0 if uninitialized") { + JsonObject unitialized; + REQUIRE(unitialized.memoryUsage() == 0); + } + + SECTION("JSON_OBJECT_SIZE(0) for empty object") { + REQUIRE(obj.memoryUsage() == JSON_OBJECT_SIZE(0)); + } + + SECTION("JSON_OBJECT_SIZE(1) after add") { + obj["hello"] = 42; + REQUIRE(obj.memoryUsage() == JSON_OBJECT_SIZE(1)); + } + + SECTION("includes the size of the key") { + obj[std::string("hello")] = 42; + REQUIRE(obj.memoryUsage() == JSON_OBJECT_SIZE(1) + 6); + } + + SECTION("includes the size of the nested array") { + JsonArray nested = obj.createNestedArray("nested"); + nested.add(42); + REQUIRE(obj.memoryUsage() == JSON_OBJECT_SIZE(1) + JSON_ARRAY_SIZE(1)); + } + + SECTION("includes the size of the nested object") { + JsonObject nested = obj.createNestedObject("nested"); + nested["hello"] = "world"; + REQUIRE(obj.memoryUsage() == 2 * JSON_OBJECT_SIZE(1)); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonObject/nesting.cpp b/libraries/ArduinoJson/extras/tests/JsonObject/nesting.cpp new file mode 100644 index 0000000..2ba98ad --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonObject/nesting.cpp @@ -0,0 +1,35 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonObject::nesting()") { + DynamicJsonDocument doc(4096); + JsonObject obj = doc.to(); + + SECTION("return 0 if uninitialized") { + JsonObject unitialized; + REQUIRE(unitialized.nesting() == 0); + } + + SECTION("returns 1 for empty object") { + REQUIRE(obj.nesting() == 1); + } + + SECTION("returns 1 for flat object") { + obj["hello"] = "world"; + REQUIRE(obj.nesting() == 1); + } + + SECTION("returns 2 with nested array") { + obj.createNestedArray("nested"); + REQUIRE(obj.nesting() == 2); + } + + SECTION("returns 2 with nested object") { + obj.createNestedObject("nested"); + REQUIRE(obj.nesting() == 2); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonObject/remove.cpp b/libraries/ArduinoJson/extras/tests/JsonObject/remove.cpp new file mode 100644 index 0000000..1dbd4bd --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonObject/remove.cpp @@ -0,0 +1,82 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include +#include + +TEST_CASE("JsonObject::remove()") { + DynamicJsonDocument doc(4096); + JsonObject obj = doc.to(); + obj["a"] = 0; + obj["b"] = 1; + obj["c"] = 2; + std::string result; + + SECTION("remove(key)") { + SECTION("Remove first") { + obj.remove("a"); + serializeJson(obj, result); + REQUIRE("{\"b\":1,\"c\":2}" == result); + } + + SECTION("Remove middle") { + obj.remove("b"); + serializeJson(obj, result); + REQUIRE("{\"a\":0,\"c\":2}" == result); + } + + SECTION("Remove last") { + obj.remove("c"); + serializeJson(obj, result); + REQUIRE("{\"a\":0,\"b\":1}" == result); + } + } + + SECTION("remove(iterator)") { + JsonObject::iterator it = obj.begin(); + + SECTION("Remove first") { + obj.remove(it); + serializeJson(obj, result); + REQUIRE("{\"b\":1,\"c\":2}" == result); + } + + SECTION("Remove middle") { + ++it; + obj.remove(it); + serializeJson(obj, result); + REQUIRE("{\"a\":0,\"c\":2}" == result); + } + + SECTION("Remove last") { + it += 2; + obj.remove(it); + serializeJson(obj, result); + REQUIRE("{\"a\":0,\"b\":1}" == result); + } + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("key is a vla") { + size_t i = 16; + char vla[i]; + strcpy(vla, "b"); + obj.remove(vla); + + serializeJson(obj, result); + REQUIRE("{\"a\":0,\"c\":2}" == result); + } +#endif + + SECTION("remove by key on unbound reference") { + JsonObject unboundObject; + unboundObject.remove("key"); + } + + SECTION("remove by iterator on unbound reference") { + JsonObject unboundObject; + unboundObject.remove(unboundObject.begin()); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonObject/size.cpp b/libraries/ArduinoJson/extras/tests/JsonObject/size.cpp new file mode 100644 index 0000000..d9c7bb7 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonObject/size.cpp @@ -0,0 +1,39 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include +#include + +TEST_CASE("JsonObject::size()") { + DynamicJsonDocument doc(4096); + JsonObject obj = doc.to(); + + SECTION("initial size is zero") { + REQUIRE(0 == obj.size()); + } + + SECTION("increases when values are added") { + obj["hello"] = 42; + REQUIRE(1 == obj.size()); + } + + SECTION("decreases when values are removed") { + obj["hello"] = 42; + obj.remove("hello"); + REQUIRE(0 == obj.size()); + } + + SECTION("doesn't increase when the same key is added twice") { + obj["hello"] = 1; + obj["hello"] = 2; + REQUIRE(1 == obj.size()); + } + + SECTION("doesn't decrease when another key is removed") { + obj["hello"] = 1; + obj.remove("world"); + REQUIRE(1 == obj.size()); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonObject/std_string.cpp b/libraries/ArduinoJson/extras/tests/JsonObject/std_string.cpp new file mode 100644 index 0000000..8a93d3f --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonObject/std_string.cpp @@ -0,0 +1,110 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +static void eraseString(std::string& str) { + char* p = const_cast(str.c_str()); + while (*p) + *p++ = '*'; +} + +TEST_CASE("std::string") { + DynamicJsonDocument doc(4096); + + SECTION("operator[]") { + char json[] = "{\"key\":\"value\"}"; + + deserializeJson(doc, json); + JsonObject obj = doc.as(); + + REQUIRE(std::string("value") == obj[std::string("key")]); + } + + SECTION("operator[] const") { + char json[] = "{\"key\":\"value\"}"; + + deserializeJson(doc, json); + JsonObject obj = doc.as(); + + REQUIRE(std::string("value") == obj[std::string("key")]); + } + + SECTION("createNestedObject()") { + JsonObject obj = doc.to(); + std::string key = "key"; + char json[64]; + obj.createNestedObject(key); + eraseString(key); + serializeJson(doc, json, sizeof(json)); + REQUIRE(std::string("{\"key\":{}}") == json); + } + + SECTION("createNestedArray()") { + JsonObject obj = doc.to(); + std::string key = "key"; + char json[64]; + obj.createNestedArray(key); + eraseString(key); + serializeJson(doc, json, sizeof(json)); + REQUIRE(std::string("{\"key\":[]}") == json); + } + + SECTION("containsKey()") { + char json[] = "{\"key\":\"value\"}"; + deserializeJson(doc, json); + JsonObject obj = doc.as(); + REQUIRE(true == obj.containsKey(std::string("key"))); + } + + SECTION("remove()") { + JsonObject obj = doc.to(); + obj["key"] = "value"; + + obj.remove(std::string("key")); + + REQUIRE(0 == obj.size()); + } + + SECTION("operator[], set key") { + std::string key("hello"); + JsonObject obj = doc.to(); + obj[key] = "world"; + eraseString(key); + REQUIRE(std::string("world") == obj["hello"]); + } + + SECTION("operator[], set value") { + std::string value("world"); + JsonObject obj = doc.to(); + obj["hello"] = value; + eraseString(value); + REQUIRE(std::string("world") == obj["hello"]); + } + + SECTION("memoryUsage() increases when adding a new key") { + std::string key1("hello"), key2("world"); + JsonObject obj = doc.to(); + + obj[key1] = 1; + size_t sizeBefore = doc.memoryUsage(); + obj[key2] = 2; + size_t sizeAfter = doc.memoryUsage(); + + REQUIRE(sizeAfter - sizeBefore >= key2.size()); + } + + SECTION("memoryUsage() remains when adding the same key") { + std::string key("hello"); + JsonObject obj = doc.to(); + + obj[key] = 1; + size_t sizeBefore = doc.memoryUsage(); + obj[key] = 2; + size_t sizeAfter = doc.memoryUsage(); + + REQUIRE(sizeBefore == sizeAfter); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonObject/subscript.cpp b/libraries/ArduinoJson/extras/tests/JsonObject/subscript.cpp new file mode 100644 index 0000000..afc567a --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonObject/subscript.cpp @@ -0,0 +1,233 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonObject::operator[]") { + DynamicJsonDocument doc(4096); + JsonObject obj = doc.to(); + + SECTION("int") { + obj["hello"] = 123; + + REQUIRE(123 == obj["hello"].as()); + REQUIRE(true == obj["hello"].is()); + REQUIRE(false == obj["hello"].is()); + } + + SECTION("volatile int") { // issue #415 + volatile int i = 123; + obj["hello"] = i; + + REQUIRE(123 == obj["hello"].as()); + REQUIRE(true == obj["hello"].is()); + REQUIRE(false == obj["hello"].is()); + } + + SECTION("double") { + obj["hello"] = 123.45; + + REQUIRE(true == obj["hello"].is()); + REQUIRE(false == obj["hello"].is()); + REQUIRE(123.45 == obj["hello"].as()); + } + + SECTION("bool") { + obj["hello"] = true; + + REQUIRE(true == obj["hello"].is()); + REQUIRE(false == obj["hello"].is()); + REQUIRE(true == obj["hello"].as()); + } + + SECTION("const char*") { + obj["hello"] = "h3110"; + + REQUIRE(true == obj["hello"].is()); + REQUIRE(false == obj["hello"].is()); + REQUIRE(std::string("h3110") == obj["hello"].as()); + } + + SECTION("array") { + DynamicJsonDocument doc2(4096); + JsonArray arr = doc2.to(); + + obj["hello"] = arr; + + REQUIRE(arr == obj["hello"].as()); + REQUIRE(true == obj["hello"].is()); + REQUIRE(false == obj["hello"].is()); + } + + SECTION("object") { + DynamicJsonDocument doc2(4096); + JsonObject obj2 = doc2.to(); + + obj["hello"] = obj2; + + REQUIRE(obj2 == obj["hello"].as()); + REQUIRE(true == obj["hello"].is()); + REQUIRE(false == obj["hello"].is()); + } + + SECTION("array subscript") { + DynamicJsonDocument doc2(4096); + JsonArray arr = doc2.to(); + arr.add(42); + + obj["a"] = arr[0]; + + REQUIRE(42 == obj["a"]); + } + + SECTION("object subscript") { + DynamicJsonDocument doc2(4096); + JsonObject obj2 = doc2.to(); + obj2["x"] = 42; + + obj["a"] = obj2["x"]; + + REQUIRE(42 == obj["a"]); + } + + SECTION("char key[]") { // issue #423 + char key[] = "hello"; + obj[key] = 42; + REQUIRE(42 == obj[key]); + } + + SECTION("should not duplicate const char*") { + obj["hello"] = "world"; + const size_t expectedSize = JSON_OBJECT_SIZE(1); + REQUIRE(expectedSize == doc.memoryUsage()); + } + + SECTION("should duplicate char* value") { + obj["hello"] = const_cast("world"); + const size_t expectedSize = JSON_OBJECT_SIZE(1) + JSON_STRING_SIZE(5); + REQUIRE(expectedSize == doc.memoryUsage()); + } + + SECTION("should duplicate char* key") { + obj[const_cast("hello")] = "world"; + const size_t expectedSize = JSON_OBJECT_SIZE(1) + JSON_STRING_SIZE(5); + REQUIRE(expectedSize == doc.memoryUsage()); + } + + SECTION("should duplicate char* key&value") { + obj[const_cast("hello")] = const_cast("world"); + const size_t expectedSize = JSON_OBJECT_SIZE(1) + 2 * JSON_STRING_SIZE(5); + REQUIRE(expectedSize <= doc.memoryUsage()); + } + + SECTION("should duplicate std::string value") { + obj["hello"] = std::string("world"); + const size_t expectedSize = JSON_OBJECT_SIZE(1) + JSON_STRING_SIZE(5); + REQUIRE(expectedSize == doc.memoryUsage()); + } + + SECTION("should duplicate std::string key") { + obj[std::string("hello")] = "world"; + const size_t expectedSize = JSON_OBJECT_SIZE(1) + JSON_STRING_SIZE(5); + REQUIRE(expectedSize == doc.memoryUsage()); + } + + SECTION("should duplicate std::string key&value") { + obj[std::string("hello")] = std::string("world"); + const size_t expectedSize = JSON_OBJECT_SIZE(1) + 2 * JSON_STRING_SIZE(5); + REQUIRE(expectedSize <= doc.memoryUsage()); + } + + SECTION("should duplicate a non-static JsonString key") { + obj[JsonString("hello", JsonString::Copied)] = "world"; + const size_t expectedSize = JSON_OBJECT_SIZE(1) + JSON_STRING_SIZE(5); + REQUIRE(expectedSize == doc.memoryUsage()); + } + + SECTION("should not duplicate a static JsonString key") { + obj[JsonString("hello", JsonString::Linked)] = "world"; + const size_t expectedSize = JSON_OBJECT_SIZE(1); + REQUIRE(expectedSize == doc.memoryUsage()); + } + + SECTION("should ignore null key") { + // object must have a value to make a call to strcmp() + obj["dummy"] = 42; + + const char* null = 0; + obj[null] = 666; + + REQUIRE(obj.size() == 1); + REQUIRE(obj[null] == null); + } + + SECTION("obj[key].to()") { + JsonArray arr = obj["hello"].to(); + + REQUIRE(arr.isNull() == false); + } + +#if defined(HAS_VARIABLE_LENGTH_ARRAY) && \ + !defined(SUBSCRIPT_CONFLICTS_WITH_BUILTIN_OPERATOR) + SECTION("obj[VLA] = str") { + size_t i = 16; + char vla[i]; + strcpy(vla, "hello"); + + obj[vla] = "world"; + + REQUIRE(std::string("world") == obj["hello"]); + } + + SECTION("obj[str] = VLA") { // issue #416 + size_t i = 32; + char vla[i]; + strcpy(vla, "world"); + + obj["hello"] = vla; + + REQUIRE(std::string("world") == obj["hello"].as()); + } + + SECTION("obj.set(VLA, str)") { + size_t i = 16; + char vla[i]; + strcpy(vla, "hello"); + + obj[vla] = "world"; + + REQUIRE(std::string("world") == obj["hello"]); + } + + SECTION("obj.set(str, VLA)") { + size_t i = 32; + char vla[i]; + strcpy(vla, "world"); + + obj["hello"].set(vla); + + REQUIRE(std::string("world") == obj["hello"].as()); + } + + SECTION("obj[VLA]") { + size_t i = 16; + char vla[i]; + strcpy(vla, "hello"); + + deserializeJson(doc, "{\"hello\":\"world\"}"); + + obj = doc.as(); + REQUIRE(std::string("world") == obj[vla]); + } +#endif + + SECTION("chain") { + obj.createNestedObject("hello")["world"] = 123; + + REQUIRE(123 == obj["hello"]["world"].as()); + REQUIRE(true == obj["hello"]["world"].is()); + REQUIRE(false == obj["hello"]["world"].is()); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonSerializer/CMakeLists.txt b/libraries/ArduinoJson/extras/tests/JsonSerializer/CMakeLists.txt new file mode 100644 index 0000000..0ec4937 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonSerializer/CMakeLists.txt @@ -0,0 +1,22 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2023, Benoit BLANCHON +# MIT License + +add_executable(JsonSerializerTests + CustomWriter.cpp + JsonArray.cpp + JsonArrayPretty.cpp + JsonObject.cpp + JsonObjectPretty.cpp + JsonVariant.cpp + misc.cpp + std_stream.cpp + std_string.cpp +) + +add_test(JsonSerializer JsonSerializerTests) + +set_tests_properties(JsonSerializer + PROPERTIES + LABELS "Catch" +) diff --git a/libraries/ArduinoJson/extras/tests/JsonSerializer/CustomWriter.cpp b/libraries/ArduinoJson/extras/tests/JsonSerializer/CustomWriter.cpp new file mode 100644 index 0000000..a84657a --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonSerializer/CustomWriter.cpp @@ -0,0 +1,51 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +class CustomWriter { + public: + CustomWriter() {} + CustomWriter(const CustomWriter&) = delete; + CustomWriter& operator=(const CustomWriter&) = delete; + + size_t write(uint8_t c) { + str_.append(1, static_cast(c)); + return 1; + } + + size_t write(const uint8_t* s, size_t n) { + str_.append(reinterpret_cast(s), n); + return n; + } + + const std::string& str() const { + return str_; + } + + private: + std::string str_; +}; + +TEST_CASE("CustomWriter") { + DynamicJsonDocument doc(4096); + JsonArray array = doc.to(); + array.add(4); + array.add(2); + + SECTION("serializeJson()") { + CustomWriter writer; + serializeJson(array, writer); + + REQUIRE("[4,2]" == writer.str()); + } + + SECTION("serializeJsonPretty") { + CustomWriter writer; + serializeJsonPretty(array, writer); + + REQUIRE("[\r\n 4,\r\n 2\r\n]" == writer.str()); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonSerializer/JsonArray.cpp b/libraries/ArduinoJson/extras/tests/JsonSerializer/JsonArray.cpp new file mode 100644 index 0000000..1fad69d --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonSerializer/JsonArray.cpp @@ -0,0 +1,129 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +static void check(JsonArray array, std::string expected) { + std::string actual; + size_t actualLen = serializeJson(array, actual); + REQUIRE(expected == actual); + REQUIRE(actualLen == expected.size()); + size_t measuredLen = measureJson(array); + REQUIRE(measuredLen == expected.size()); +} + +TEST_CASE("serializeJson(JsonArray)") { + StaticJsonDocument doc; + JsonArray array = doc.to(); + + SECTION("Empty") { + check(array, "[]"); + } + + SECTION("Null") { + array.add(static_cast(0)); + + check(array, "[null]"); + } + + SECTION("OneString") { + array.add("hello"); + + check(array, "[\"hello\"]"); + } + + SECTION("TwoStrings") { + array.add("hello"); + array.add("world"); + + check(array, "[\"hello\",\"world\"]"); + } + + SECTION("OneStringOverCapacity") { + array.add("hello"); + array.add("world"); + array.add("lost"); + + check(array, "[\"hello\",\"world\"]"); + } + + SECTION("One double") { + array.add(3.1415927); + check(array, "[3.1415927]"); + } + + SECTION("OneInteger") { + array.add(1); + + check(array, "[1]"); + } + + SECTION("TwoIntegers") { + array.add(1); + array.add(2); + + check(array, "[1,2]"); + } + + SECTION("serialized(const char*)") { + array.add(serialized("{\"key\":\"value\"}")); + + check(array, "[{\"key\":\"value\"}]"); + } + + SECTION("serialized(char*)") { + char tmp[] = "{\"key\":\"value\"}"; + array.add(serialized(tmp)); + + check(array, "[{\"key\":\"value\"}]"); + } + + SECTION("OneIntegerOverCapacity") { + array.add(1); + array.add(2); + array.add(3); + + check(array, "[1,2]"); + } + + SECTION("OneTrue") { + array.add(true); + + check(array, "[true]"); + } + + SECTION("OneFalse") { + array.add(false); + + check(array, "[false]"); + } + + SECTION("TwoBooleans") { + array.add(false); + array.add(true); + + check(array, "[false,true]"); + } + + SECTION("OneBooleanOverCapacity") { + array.add(false); + array.add(true); + array.add(false); + + check(array, "[false,true]"); + } + + SECTION("OneEmptyNestedArray") { + array.createNestedArray(); + + check(array, "[[]]"); + } + + SECTION("OneEmptyNestedHash") { + array.createNestedObject(); + + check(array, "[{}]"); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonSerializer/JsonArrayPretty.cpp b/libraries/ArduinoJson/extras/tests/JsonSerializer/JsonArrayPretty.cpp new file mode 100644 index 0000000..9abeb01 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonSerializer/JsonArrayPretty.cpp @@ -0,0 +1,75 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +static void checkArray(JsonArray array, std::string expected) { + std::string actual; + size_t actualLen = serializeJsonPretty(array, actual); + size_t measuredLen = measureJsonPretty(array); + CHECK(actualLen == expected.size()); + CHECK(measuredLen == expected.size()); + REQUIRE(expected == actual); +} + +TEST_CASE("serializeJsonPretty(JsonArray)") { + DynamicJsonDocument doc(4096); + JsonArray array = doc.to(); + + SECTION("Empty") { + checkArray(array, "[]"); + } + + SECTION("OneElement") { + array.add(1); + + checkArray(array, + "[\r\n" + " 1\r\n" + "]"); + } + + SECTION("TwoElements") { + array.add(1); + array.add(2); + + checkArray(array, + "[\r\n" + " 1,\r\n" + " 2\r\n" + "]"); + } + + SECTION("EmptyNestedArrays") { + array.createNestedArray(); + array.createNestedArray(); + + checkArray(array, + "[\r\n" + " [],\r\n" + " []\r\n" + "]"); + } + + SECTION("NestedArrays") { + JsonArray nested1 = array.createNestedArray(); + nested1.add(1); + nested1.add(2); + + JsonObject nested2 = array.createNestedObject(); + nested2["key"] = 3; + + checkArray(array, + "[\r\n" + " [\r\n" + " 1,\r\n" + " 2\r\n" + " ],\r\n" + " {\r\n" + " \"key\": 3\r\n" + " }\r\n" + "]"); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonSerializer/JsonObject.cpp b/libraries/ArduinoJson/extras/tests/JsonSerializer/JsonObject.cpp new file mode 100644 index 0000000..9ba2114 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonSerializer/JsonObject.cpp @@ -0,0 +1,119 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include +#include + +static void checkObject(const JsonObject obj, const std::string& expected) { + char actual[256]; + memset(actual, '!', sizeof(actual)); + + size_t actualLen = serializeJson(obj, actual); + size_t measuredLen = measureJson(obj); + + REQUIRE(expected.size() == measuredLen); + REQUIRE(expected.size() == actualLen); + REQUIRE(actual[actualLen] == 0); // serializeJson() adds a null terminator + REQUIRE(expected == actual); +} + +TEST_CASE("serializeJson(JsonObject)") { + DynamicJsonDocument doc(4096); + JsonObject obj = doc.to(); + + SECTION("EmptyObject") { + checkObject(obj, "{}"); + } + + SECTION("TwoStrings") { + obj["key1"] = "value1"; + obj["key2"] = "value2"; + + checkObject(obj, "{\"key1\":\"value1\",\"key2\":\"value2\"}"); + } + + SECTION("RemoveFirst") { + obj["key1"] = "value1"; + obj["key2"] = "value2"; + obj.remove("key1"); + + checkObject(obj, "{\"key2\":\"value2\"}"); + } + + SECTION("RemoveLast") { + obj["key1"] = "value1"; + obj["key2"] = "value2"; + obj.remove("key2"); + + checkObject(obj, "{\"key1\":\"value1\"}"); + } + + SECTION("RemoveUnexistingKey") { + obj["key1"] = "value1"; + obj["key2"] = "value2"; + obj.remove("key3"); + + checkObject(obj, "{\"key1\":\"value1\",\"key2\":\"value2\"}"); + } + + SECTION("ReplaceExistingKey") { + obj["key"] = "value1"; + obj["key"] = "value2"; + + checkObject(obj, "{\"key\":\"value2\"}"); + } + + SECTION("TwoIntegers") { + obj["a"] = 1; + obj["b"] = 2; + checkObject(obj, "{\"a\":1,\"b\":2}"); + } + + SECTION("serialized(const char*)") { + obj["a"] = serialized("[1,2]"); + obj["b"] = serialized("[4,5]"); + checkObject(obj, "{\"a\":[1,2],\"b\":[4,5]}"); + } + + SECTION("Two doubles") { + obj["a"] = 12.34; + obj["b"] = 56.78; + checkObject(obj, "{\"a\":12.34,\"b\":56.78}"); + } + + SECTION("TwoNull") { + obj["a"] = static_cast(0); + obj["b"] = static_cast(0); + checkObject(obj, "{\"a\":null,\"b\":null}"); + } + + SECTION("TwoBooleans") { + obj["a"] = true; + obj["b"] = false; + checkObject(obj, "{\"a\":true,\"b\":false}"); + } + + SECTION("ThreeNestedArrays") { + DynamicJsonDocument b(4096); + DynamicJsonDocument c(4096); + + obj.createNestedArray("a"); + obj["b"] = b.to(); + obj["c"] = c.to(); + + checkObject(obj, "{\"a\":[],\"b\":[],\"c\":[]}"); + } + + SECTION("ThreeNestedObjects") { + DynamicJsonDocument b(4096); + DynamicJsonDocument c(4096); + + obj.createNestedObject("a"); + obj["b"] = b.to(); + obj["c"] = c.to(); + + checkObject(obj, "{\"a\":{},\"b\":{},\"c\":{}}"); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonSerializer/JsonObjectPretty.cpp b/libraries/ArduinoJson/extras/tests/JsonSerializer/JsonObjectPretty.cpp new file mode 100644 index 0000000..4e8d113 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonSerializer/JsonObjectPretty.cpp @@ -0,0 +1,77 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include +#include + +static void checkObjectPretty(const JsonObject obj, + const std::string expected) { + char json[256]; + + size_t actualLen = serializeJsonPretty(obj, json); + size_t measuredLen = measureJsonPretty(obj); + + REQUIRE(json == expected); + REQUIRE(expected.size() == actualLen); + REQUIRE(expected.size() == measuredLen); +} + +TEST_CASE("serializeJsonPretty(JsonObject)") { + DynamicJsonDocument doc(4096); + JsonObject obj = doc.to(); + + SECTION("EmptyObject") { + checkObjectPretty(obj, "{}"); + } + + SECTION("OneMember") { + obj["key"] = "value"; + + checkObjectPretty(obj, + "{\r\n" + " \"key\": \"value\"\r\n" + "}"); + } + + SECTION("TwoMembers") { + obj["key1"] = "value1"; + obj["key2"] = "value2"; + + checkObjectPretty(obj, + "{\r\n" + " \"key1\": \"value1\",\r\n" + " \"key2\": \"value2\"\r\n" + "}"); + } + + SECTION("EmptyNestedContainers") { + obj.createNestedObject("key1"); + obj.createNestedArray("key2"); + + checkObjectPretty(obj, + "{\r\n" + " \"key1\": {},\r\n" + " \"key2\": []\r\n" + "}"); + } + + SECTION("NestedContainers") { + JsonObject nested1 = obj.createNestedObject("key1"); + nested1["a"] = 1; + + JsonArray nested2 = obj.createNestedArray("key2"); + nested2.add(2); + + checkObjectPretty(obj, + "{\r\n" + " \"key1\": {\r\n" + " \"a\": 1\r\n" + " },\r\n" + " \"key2\": [\r\n" + " 2\r\n" + " ]\r\n" + "}"); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonSerializer/JsonVariant.cpp b/libraries/ArduinoJson/extras/tests/JsonSerializer/JsonVariant.cpp new file mode 100644 index 0000000..81553d3 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonSerializer/JsonVariant.cpp @@ -0,0 +1,121 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include +#include + +template +void check(T value, const std::string& expected) { + DynamicJsonDocument doc(4096); + doc.to().set(value); + char buffer[256] = ""; + size_t returnValue = serializeJson(doc, buffer, sizeof(buffer)); + REQUIRE(expected == buffer); + REQUIRE(expected.size() == returnValue); +} + +TEST_CASE("serializeJson(JsonVariant)") { + SECTION("Undefined") { + check(JsonVariant(), "null"); + } + + SECTION("Null string") { + check(static_cast(0), "null"); + } + + SECTION("const char*") { + check("hello", "\"hello\""); + } + + SECTION("string") { + check(std::string("hello"), "\"hello\""); + + SECTION("Escape quotation mark") { + check(std::string("hello \"world\""), "\"hello \\\"world\\\"\""); + } + + SECTION("Escape reverse solidus") { + check(std::string("hello\\world"), "\"hello\\\\world\""); + } + + SECTION("Don't escape solidus") { + check(std::string("fifty/fifty"), "\"fifty/fifty\""); + } + + SECTION("Escape backspace") { + check(std::string("hello\bworld"), "\"hello\\bworld\""); + } + + SECTION("Escape formfeed") { + check(std::string("hello\fworld"), "\"hello\\fworld\""); + } + + SECTION("Escape linefeed") { + check(std::string("hello\nworld"), "\"hello\\nworld\""); + } + + SECTION("Escape carriage return") { + check(std::string("hello\rworld"), "\"hello\\rworld\""); + } + + SECTION("Escape tab") { + check(std::string("hello\tworld"), "\"hello\\tworld\""); + } + + SECTION("NUL char") { + check(std::string("hello\0world", 11), "\"hello\\u0000world\""); + } + } + + SECTION("SerializedValue") { + check(serialized("[1,2]"), "[1,2]"); + } + + SECTION("SerializedValue") { + check(serialized(std::string("[1,2]")), "[1,2]"); + } + + SECTION("Double") { + check(3.1415927, "3.1415927"); + } + + SECTION("Zero") { + check(0, "0"); + } + + SECTION("Integer") { + check(42, "42"); + } + + SECTION("NegativeLong") { + check(-42, "-42"); + } + + SECTION("UnsignedLong") { + check(4294967295UL, "4294967295"); + } + + SECTION("True") { + check(true, "true"); + } + + SECTION("OneFalse") { + check(false, "false"); + } + +#if ARDUINOJSON_USE_LONG_LONG + SECTION("NegativeInt64") { + check(-9223372036854775807 - 1, "-9223372036854775808"); + } + + SECTION("PositiveInt64") { + check(9223372036854775807, "9223372036854775807"); + } + + SECTION("UInt64") { + check(18446744073709551615U, "18446744073709551615"); + } +#endif +} diff --git a/libraries/ArduinoJson/extras/tests/JsonSerializer/misc.cpp b/libraries/ArduinoJson/extras/tests/JsonSerializer/misc.cpp new file mode 100644 index 0000000..59c09eb --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonSerializer/misc.cpp @@ -0,0 +1,36 @@ +#include +#include +#include + +TEST_CASE("serializeJson(MemberProxy)") { + DynamicJsonDocument doc(4096); + deserializeJson(doc, "{\"hello\":42}"); + JsonObject obj = doc.as(); + std::string result; + + serializeJson(obj["hello"], result); + + REQUIRE(result == "42"); +} + +TEST_CASE("serializeJson(ElementProxy)") { + DynamicJsonDocument doc(4096); + deserializeJson(doc, "[42]"); + JsonArray arr = doc.as(); + std::string result; + + serializeJson(arr[0], result); + + REQUIRE(result == "42"); +} + +TEST_CASE("serializeJson(JsonVariantSubscript)") { + DynamicJsonDocument doc(4096); + deserializeJson(doc, "[42]"); + JsonVariant var = doc.as(); + std::string result; + + serializeJson(var[0], result); + + REQUIRE(result == "42"); +} diff --git a/libraries/ArduinoJson/extras/tests/JsonSerializer/std_stream.cpp b/libraries/ArduinoJson/extras/tests/JsonSerializer/std_stream.cpp new file mode 100644 index 0000000..411f479 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonSerializer/std_stream.cpp @@ -0,0 +1,66 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include +#include + +TEST_CASE("operator<<(std::ostream)") { + DynamicJsonDocument doc(4096); + std::ostringstream os; + + SECTION("JsonVariant containing false") { + JsonVariant variant = doc.to(); + + variant.set(false); + os << variant; + + REQUIRE("false" == os.str()); + } + + SECTION("JsonVariant containing string") { + JsonVariant variant = doc.to(); + + variant.set("coucou"); + os << variant; + + REQUIRE("\"coucou\"" == os.str()); + } + + SECTION("JsonObject") { + JsonObject object = doc.to(); + object["key"] = "value"; + + os << object; + + REQUIRE("{\"key\":\"value\"}" == os.str()); + } + + SECTION("MemberProxy") { + JsonObject object = doc.to(); + object["key"] = "value"; + + os << object["key"]; + + REQUIRE("\"value\"" == os.str()); + } + + SECTION("JsonArray") { + JsonArray array = doc.to(); + array.add("value"); + + os << array; + + REQUIRE("[\"value\"]" == os.str()); + } + + SECTION("ElementProxy") { + JsonArray array = doc.to(); + array.add("value"); + + os << array[0]; + + REQUIRE("\"value\"" == os.str()); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonSerializer/std_string.cpp b/libraries/ArduinoJson/extras/tests/JsonSerializer/std_string.cpp new file mode 100644 index 0000000..af0d809 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonSerializer/std_string.cpp @@ -0,0 +1,57 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("serialize JsonArray to std::string") { + DynamicJsonDocument doc(4096); + JsonArray array = doc.to(); + array.add(4); + array.add(2); + + SECTION("serializeJson()") { + std::string json; + serializeJson(array, json); + + REQUIRE("[4,2]" == json); + } + + SECTION("serializeJsonPretty") { + std::string json; + serializeJsonPretty(array, json); + + REQUIRE("[\r\n 4,\r\n 2\r\n]" == json); + } +} + +TEST_CASE("serialize JsonObject to std::string") { + DynamicJsonDocument doc(4096); + JsonObject obj = doc.to(); + obj["key"] = "value"; + + SECTION("object") { + std::string json; + serializeJson(doc, json); + + REQUIRE("{\"key\":\"value\"}" == json); + } + + SECTION("serializeJsonPretty") { + std::string json; + serializeJsonPretty(doc, json); + + REQUIRE("{\r\n \"key\": \"value\"\r\n}" == json); + } +} + +TEST_CASE("serialize an std::string containing a NUL") { + StaticJsonDocument<256> doc; + doc.set(std::string("hello\0world", 11)); + CHECK(doc.memoryUsage() == 12); + + std::string json; + serializeJson(doc, json); + CHECK("\"hello\\u0000world\"" == json); +} diff --git a/libraries/ArduinoJson/extras/tests/JsonVariant/CMakeLists.txt b/libraries/ArduinoJson/extras/tests/JsonVariant/CMakeLists.txt new file mode 100644 index 0000000..d43a971 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonVariant/CMakeLists.txt @@ -0,0 +1,37 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2023, Benoit BLANCHON +# MIT License + +add_executable(JsonVariantTests + add.cpp + as.cpp + clear.cpp + compare.cpp + containsKey.cpp + converters.cpp + copy.cpp + createNested.cpp + is.cpp + isnull.cpp + memoryUsage.cpp + misc.cpp + nesting.cpp + nullptr.cpp + or.cpp + overflow.cpp + remove.cpp + set.cpp + shallowCopy.cpp + size.cpp + stl_containers.cpp + subscript.cpp + types.cpp + unbound.cpp +) + +add_test(JsonVariant JsonVariantTests) + +set_tests_properties(JsonVariant + PROPERTIES + LABELS "Catch" +) diff --git a/libraries/ArduinoJson/extras/tests/JsonVariant/add.cpp b/libraries/ArduinoJson/extras/tests/JsonVariant/add.cpp new file mode 100644 index 0000000..6907ae3 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonVariant/add.cpp @@ -0,0 +1,46 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include +#include + +TEST_CASE("JsonVariant::add()") { + DynamicJsonDocument doc(4096); + 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}"); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonVariant/as.cpp b/libraries/ArduinoJson/extras/tests/JsonVariant/as.cpp new file mode 100644 index 0000000..01e263e --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonVariant/as.cpp @@ -0,0 +1,270 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include +#include + +namespace my { +using ArduinoJson::detail::isinf; +} // namespace my + +enum MY_ENUM { ONE = 1, TWO = 2 }; + +TEST_CASE("JsonVariant::as()") { + static const char* null = 0; + + DynamicJsonDocument doc(4096); + JsonVariant variant = doc.to(); + + SECTION("not set") { + REQUIRE(false == variant.as()); + REQUIRE(0 == variant.as()); + REQUIRE(0.0f == variant.as()); + REQUIRE(0 == variant.as()); + REQUIRE("null" == variant.as()); + REQUIRE(variant.as().isNull()); + } + + SECTION("set(4.2)") { + variant.set(4.2); + + REQUIRE(variant.as()); + REQUIRE(0 == variant.as()); + REQUIRE(variant.as() == "4.2"); + REQUIRE(variant.as() == 4L); + REQUIRE(variant.as() == 4U); + REQUIRE(variant.as().isNull()); + } + + SECTION("set(0.0)") { + variant.set(0.0); + + REQUIRE(variant.as() == false); + REQUIRE(variant.as() == 0L); + REQUIRE(variant.as().isNull()); + } + + SECTION("set(false)") { + variant.set(false); + + REQUIRE(false == variant.as()); + REQUIRE(variant.as() == 0.0); + REQUIRE(variant.as() == 0L); + REQUIRE(variant.as() == "false"); + REQUIRE(variant.as().isNull()); + } + + SECTION("set(true)") { + variant.set(true); + + REQUIRE(variant.as()); + REQUIRE(variant.as() == 1.0); + REQUIRE(variant.as() == 1L); + REQUIRE(variant.as() == "true"); + REQUIRE(variant.as().isNull()); + } + + SECTION("set(42)") { + variant.set(42); + + REQUIRE(variant.as() == true); + REQUIRE(variant.as() == 42.0); + REQUIRE(variant.as() == 42); + REQUIRE(variant.as() == 42U); // issue #1601 + REQUIRE(variant.as() == "42"); + REQUIRE(variant.as().isNull()); + } + + SECTION("set(42L)") { + variant.set(42L); + + REQUIRE(variant.as() == true); + REQUIRE(variant.as() == 42.0); + REQUIRE(variant.as() == "42"); + REQUIRE(variant.as().isNull()); + } + + SECTION("set(-42L)") { + variant.set(-42L); + + REQUIRE(variant.as() == -42.0); + REQUIRE(variant.as() == "-42"); + REQUIRE(variant.as().isNull()); + } + + SECTION("set(42UL)") { + variant.set(42UL); + + REQUIRE(variant.as() == true); + REQUIRE(variant.as() == 42.0); + REQUIRE(variant.as() == "42"); + REQUIRE(variant.as().isNull()); + } + + SECTION("set(0L)") { + variant.set(0L); + + REQUIRE(variant.as() == false); + REQUIRE(variant.as() == 0.0); + REQUIRE(variant.as() == "0"); + REQUIRE(variant.as().isNull()); + } + + SECTION("set(0UL)") { + variant.set(0UL); + + REQUIRE(variant.as() == false); + REQUIRE(variant.as() == 0.0); + REQUIRE(variant.as() == "0"); + REQUIRE(variant.as().isNull()); + } + + SECTION("set(null)") { + variant.set(null); + + REQUIRE(variant.as() == false); + REQUIRE(variant.as() == 0.0); + REQUIRE(variant.as() == 0L); + REQUIRE(variant.as() == "null"); + REQUIRE(variant.as().isNull()); + } + + SECTION("set(\"42\")") { + variant.set("42"); + + REQUIRE(variant.as() == 42L); + REQUIRE(variant.as() == "42"); + REQUIRE(variant.as().isLinked() == true); + } + + SECTION("set(\"hello\")") { + variant.set("hello"); + + REQUIRE(variant.as() == true); + REQUIRE(variant.as() == 0L); + REQUIRE(variant.as() == std::string("hello")); + REQUIRE(variant.as() == std::string("hello")); + REQUIRE(variant.as() == std::string("hello")); + REQUIRE(variant.as() == "hello"); + } + + SECTION("set(std::string(\"4.2\"))") { + variant.set(std::string("4.2")); + + REQUIRE(variant.as() == true); + REQUIRE(variant.as() == 4L); + REQUIRE(variant.as() == 4.2); + REQUIRE(variant.as() == std::string("4.2")); + REQUIRE(variant.as() == std::string("4.2")); + REQUIRE(variant.as() == "4.2"); + REQUIRE(variant.as().isLinked() == false); + } + + SECTION("set(\"true\")") { + variant.set("true"); + + REQUIRE(variant.as() == true); + REQUIRE(variant.as() == 0); + REQUIRE(variant.as() == "true"); + } + + SECTION("set(-1e300)") { + variant.set(-1e300); + + REQUIRE(variant.as() == true); + REQUIRE(variant.as() == -1e300); + REQUIRE(variant.as() < 0); + REQUIRE(my::isinf(variant.as())); + REQUIRE(variant.as().isNull()); + } + + SECTION("set(1e300)") { + variant.set(1e300); + + REQUIRE(variant.as() == true); + REQUIRE(variant.as() == 1e300); + REQUIRE(variant.as() > 0); + REQUIRE(my::isinf(variant.as())); + REQUIRE(variant.as().isNull()); + } + + SECTION("set(1e-300)") { + variant.set(1e-300); + + REQUIRE(variant.as() == true); + REQUIRE(variant.as() == 1e-300); + REQUIRE(variant.as() == 0); + REQUIRE(variant.as().isNull()); + } + + SECTION("to()") { + JsonObject obj = variant.to(); + obj["key"] = "value"; + + SECTION("as()") { + REQUIRE(variant.as() == true); + } + + SECTION("as()") { + REQUIRE(variant.as() == std::string("{\"key\":\"value\"}")); + } + + SECTION("ObjectAsJsonObject") { + JsonObject o = variant.as(); + REQUIRE(o.size() == 1); + REQUIRE(o["key"] == std::string("value")); + } + } + + SECTION("to()") { + JsonArray arr = variant.to(); + arr.add(4); + arr.add(2); + + SECTION("as()") { + REQUIRE(variant.as() == true); + } + + SECTION("as()") { + REQUIRE(variant.as() == std::string("[4,2]")); + } + + SECTION("as()") { + JsonArray a = variant.as(); + REQUIRE(a.size() == 2); + REQUIRE(a[0] == 4); + REQUIRE(a[1] == 2); + } + } + +#if ARDUINOJSON_USE_LONG_LONG + SECTION("Smallest int64 negative") { + variant.set("-9223372036854775808"); + REQUIRE(variant.as() == -9223372036854775807 - 1); + } + + SECTION("Biggerst int64 positive") { + variant.set("9223372036854775807"); + REQUIRE(variant.as() == 9223372036854775807); + } +#endif + + SECTION("should work on JsonVariantConst") { + variant.set("hello"); + + JsonVariantConst cvar = variant; + + REQUIRE(cvar.as() == true); + REQUIRE(cvar.as() == 0L); + REQUIRE(cvar.as() == std::string("hello")); + REQUIRE(cvar.as() == std::string("hello")); + } + + SECTION("as()") { + variant.set(1); + + REQUIRE(variant.as() == ONE); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonVariant/clear.cpp b/libraries/ArduinoJson/extras/tests/JsonVariant/clear.cpp new file mode 100644 index 0000000..d516ca6 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonVariant/clear.cpp @@ -0,0 +1,26 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include +#include + +TEST_CASE("JsonVariant::clear()") { + DynamicJsonDocument doc(4096); + JsonVariant var = doc.to(); + + SECTION("size goes back to zero") { + var.add(42); + var.clear(); + + REQUIRE(var.size() == 0); + } + + SECTION("isNull() return true") { + var.add("hello"); + var.clear(); + + REQUIRE(var.isNull() == true); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonVariant/compare.cpp b/libraries/ArduinoJson/extras/tests/JsonVariant/compare.cpp new file mode 100644 index 0000000..1922df0 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonVariant/compare.cpp @@ -0,0 +1,316 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +// Most code is already covered by arithmeticCompare.cpp. +// Here, we're just filling the holes + +TEST_CASE("Compare JsonVariant with value") { + StaticJsonDocument<256> doc; + JsonVariant a = doc.add(); + + SECTION("null vs (char*)0") { + char* b = 0; + + CHECK(a == b); + CHECK(a <= b); + CHECK(a >= b); + CHECK_FALSE(a != b); + CHECK_FALSE(a < b); + CHECK_FALSE(a > b); + } + + SECTION("42 vs 42") { + a.set(42); + int b = 42; + + CHECK(a == b); + CHECK(a <= b); + CHECK(a >= b); + CHECK_FALSE(a != b); + CHECK_FALSE(a < b); + CHECK_FALSE(a > b); + } +} + +TEST_CASE("Compare JsonVariant with JsonVariant") { + StaticJsonDocument<256> doc; + JsonVariant a = doc.add(); + JsonVariant b = doc.add(); + + SECTION("'abc' vs 'abc'") { + a.set("abc"); + b.set("abc"); + + CHECK(a == b); + CHECK(a <= b); + CHECK(a >= b); + CHECK_FALSE(a != b); + CHECK_FALSE(a < b); + CHECK_FALSE(a > b); + } + + SECTION("'abc' vs 'bcd'") { + a.set("abc"); + b.set("bcd"); + + CHECK(a != b); + CHECK(a < b); + CHECK(a <= b); + CHECK_FALSE(a == b); + CHECK_FALSE(a > b); + CHECK_FALSE(a >= b); + } + + SECTION("'bcd' vs 'abc'") { + a.set("bcd"); + b.set("abc"); + + CHECK(a != b); + CHECK(a > b); + CHECK(a >= b); + CHECK_FALSE(a < b); + CHECK_FALSE(a <= b); + CHECK_FALSE(a == b); + } + + SECTION("serialized('abc') vs serialized('abc')") { + a.set(serialized("abc")); + b.set(serialized("abc")); + + CHECK(a == b); + CHECK(a <= b); + CHECK(a >= b); + CHECK_FALSE(a != b); + CHECK_FALSE(a < b); + CHECK_FALSE(a > b); + } + + SECTION("serialized('abc') vs serialized('bcd')") { + a.set(serialized("abc")); + b.set(serialized("bcd")); + + CHECK(a != b); + CHECK(a < b); + CHECK(a <= b); + CHECK_FALSE(a == b); + CHECK_FALSE(a > b); + CHECK_FALSE(a >= b); + } + + SECTION("serialized('bcd') vs serialized('abc')") { + a.set(serialized("bcd")); + b.set(serialized("abc")); + + CHECK(a != b); + CHECK(a > b); + CHECK(a >= b); + CHECK_FALSE(a < b); + CHECK_FALSE(a <= b); + CHECK_FALSE(a == b); + } + + SECTION("false vs true") { + a.set(false); + b.set(true); + + CHECK(a != b); + CHECK(a < b); + CHECK(a <= b); + CHECK_FALSE(a == b); + CHECK_FALSE(a > b); + CHECK_FALSE(a >= b); + } + + SECTION("false vs -1") { + a.set(false); + b.set(-1); + + CHECK(a != b); + CHECK(a > b); + CHECK(a >= b); + CHECK_FALSE(a < b); + CHECK_FALSE(a <= b); + CHECK_FALSE(a == b); + } + + SECTION("null vs null") { + CHECK(a == b); + CHECK(a <= b); + CHECK(a >= b); + CHECK_FALSE(a != b); + CHECK_FALSE(a < b); + CHECK_FALSE(a > b); + } + + SECTION("42 vs 42") { + a.set(42); + b.set(42); + + CHECK(a == b); + CHECK(a <= b); + CHECK(a >= b); + CHECK_FALSE(a != b); + CHECK_FALSE(a < b); + CHECK_FALSE(a > b); + } + + SECTION("42 vs 42U") { + a.set(42); + b.set(42U); + + CHECK(a == b); + CHECK(a <= b); + CHECK(a >= b); + CHECK_FALSE(a != b); + CHECK_FALSE(a < b); + CHECK_FALSE(a > b); + } + + SECTION("42 vs 42.0") { + a.set(42); + b.set(42.0); + + CHECK(a == b); + CHECK(a <= b); + CHECK(a >= b); + CHECK_FALSE(a != b); + CHECK_FALSE(a < b); + CHECK_FALSE(a > b); + } + + SECTION("42.0 vs 42") { + a.set(42.0); + b.set(42); + + CHECK(a == b); + CHECK(a <= b); + CHECK(a >= b); + CHECK_FALSE(a != b); + CHECK_FALSE(a < b); + CHECK_FALSE(a > b); + } + + SECTION("-42 vs -42") { + a.set(-42); + b.set(-42); + + CHECK(a == b); + CHECK(a <= b); + CHECK(a >= b); + CHECK_FALSE(a != b); + CHECK_FALSE(a < b); + CHECK_FALSE(a > b); + } + + SECTION("-42 vs 42") { + a.set(-42); + b.set(42); + + CHECK(a != b); + CHECK(a < b); + CHECK(a <= b); + CHECK_FALSE(a == b); + CHECK_FALSE(a > b); + CHECK_FALSE(a >= b); + } + + SECTION("42 vs -42") { + a.set(42); + b.set(-42); + + CHECK(a != b); + CHECK(a > b); + CHECK(a >= b); + CHECK_FALSE(a < b); + CHECK_FALSE(a <= b); + CHECK_FALSE(a == b); + } + + SECTION("42.0 vs -42") { + a.set(42.0); + b.set(-42); + + CHECK(a != b); + CHECK(a > b); + CHECK(a >= b); + CHECK_FALSE(a < b); + CHECK_FALSE(a <= b); + CHECK_FALSE(a == b); + } + + SECTION("42U vs 42U") { + a.set(42U); + b.set(42U); + + CHECK(a == b); + CHECK(a <= b); + CHECK(a >= b); + CHECK_FALSE(a != b); + CHECK_FALSE(a < b); + CHECK_FALSE(a > b); + } + + SECTION("42U vs 42") { + a.set(42U); + b.set(42); + + CHECK(a == b); + CHECK(a <= b); + CHECK(a >= b); + CHECK_FALSE(a != b); + CHECK_FALSE(a < b); + CHECK_FALSE(a > b); + } + + SECTION("[1] vs [1]") { + a.add(1); + b.add(1); + + CHECK(a <= b); + CHECK(a == b); + CHECK(a >= b); + CHECK_FALSE(a != b); + CHECK_FALSE(a < b); + CHECK_FALSE(a > b); + } + + SECTION("[1] vs [2]") { + a.add(1); + b.add(2); + + CHECK(a != b); + CHECK_FALSE(a < b); + CHECK_FALSE(a <= b); + CHECK_FALSE(a == b); + CHECK_FALSE(a > b); + CHECK_FALSE(a >= b); + } + + SECTION("{x:1} vs {x:1}") { + a["x"] = 1; + b["x"] = 1; + + CHECK(a <= b); + CHECK(a == b); + CHECK(a >= b); + CHECK_FALSE(a != b); + CHECK_FALSE(a < b); + CHECK_FALSE(a > b); + } + + SECTION("{x:1} vs {x:2}") { + a["x"] = 1; + b["x"] = 2; + + CHECK(a != b); + CHECK_FALSE(a < b); + CHECK_FALSE(a <= b); + CHECK_FALSE(a == b); + CHECK_FALSE(a > b); + CHECK_FALSE(a >= b); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonVariant/containsKey.cpp b/libraries/ArduinoJson/extras/tests/JsonVariant/containsKey.cpp new file mode 100644 index 0000000..d003d11 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonVariant/containsKey.cpp @@ -0,0 +1,42 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include +#include + +TEST_CASE("JsonVariant::containsKey()") { + DynamicJsonDocument doc(4096); + JsonVariant var = doc.to(); + + SECTION("containsKey(const char*)") { + var["hello"] = "world"; + + REQUIRE(var.containsKey("hello") == true); + REQUIRE(var.containsKey("world") == false); + } + + SECTION("containsKey(std::string)") { + var["hello"] = "world"; + + REQUIRE(var.containsKey(std::string("hello")) == true); + REQUIRE(var.containsKey(std::string("world")) == false); + } +} + +TEST_CASE("JsonVariantConst::containsKey()") { + DynamicJsonDocument doc(4096); + doc["hello"] = "world"; + JsonVariantConst cvar = doc.as(); + + SECTION("containsKey(const char*) returns true") { + REQUIRE(cvar.containsKey("hello") == true); + REQUIRE(cvar.containsKey("world") == false); + } + + SECTION("containsKey(std::string) returns true") { + REQUIRE(cvar.containsKey(std::string("hello")) == true); + REQUIRE(cvar.containsKey(std::string("world")) == false); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonVariant/converters.cpp b/libraries/ArduinoJson/extras/tests/JsonVariant/converters.cpp new file mode 100644 index 0000000..89b34de --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonVariant/converters.cpp @@ -0,0 +1,154 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include +#include + +namespace { +struct Date { + int day; + int month; + int year; +}; + +void convertToJson(const Date& src, JsonVariant dst) { + dst["day"] = src.day; + dst["month"] = src.month; + dst["year"] = src.year; +} + +void convertFromJson(JsonVariantConst src, Date& dst) { + dst.day = src["day"]; + dst.month = src["month"]; + dst.year = src["year"]; +} + +bool canConvertFromJson(JsonVariantConst src, const Date&) { + return src["day"].is() && src["month"].is() && + src["year"].is(); +} +} // namespace + +TEST_CASE("Custom converter with overloading") { + DynamicJsonDocument doc(4096); + + SECTION("convert JSON to Date") { + doc["date"]["day"] = 2; + doc["date"]["month"] = 3; + doc["date"]["year"] = 2021; + + Date date = doc["date"]; + + REQUIRE(date.day == 2); + REQUIRE(date.month == 3); + REQUIRE(date.year == 2021); + } + + SECTION("is() returns true") { + doc["date"]["day"] = 2; + doc["date"]["month"] = 3; + doc["date"]["year"] = 2021; + + REQUIRE(doc["date"].is()); + } + + SECTION("is() returns false") { + doc["date"]["day"] = 2; + doc["date"]["month"] = 3; + doc["date"]["year"] = "2021"; + + REQUIRE(doc["date"].is() == false); + } + + SECTION("convert Date to JSON") { + Date date = {19, 3, 2021}; + doc["date"] = date; + + REQUIRE(doc["date"]["day"] == 19); + REQUIRE(doc["date"]["month"] == 3); + REQUIRE(doc["date"]["year"] == 2021); + } +} + +class Complex { + public: + explicit Complex(double r, double i) : real_(r), imag_(i) {} + + double real() const { + return real_; + } + + double imag() const { + return imag_; + } + + private: + double real_, imag_; +}; + +namespace ArduinoJson { +template <> +struct Converter { + static void toJson(const Complex& src, JsonVariant dst) { + dst["real"] = src.real(); + dst["imag"] = src.imag(); + } + + static Complex fromJson(JsonVariantConst src) { + return Complex(src["real"], src["imag"]); + } + + static bool checkJson(JsonVariantConst src) { + return src["real"].is() && src["imag"].is(); + } +}; +} // namespace ArduinoJson + +TEST_CASE("Custom converter with specialization") { + DynamicJsonDocument doc(4096); + + SECTION("convert JSON to Complex") { + doc["value"]["real"] = 2; + doc["value"]["imag"] = 3; + + Complex value = doc["value"]; + + REQUIRE(value.real() == 2); + REQUIRE(value.imag() == 3); + } + + SECTION("is() returns true") { + doc["value"]["real"] = 2; + doc["value"]["imag"] = 3; + + REQUIRE(doc["value"].is()); + } + + SECTION("is() returns false") { + doc["value"]["real"] = 2; + doc["value"]["imag"] = "3"; + + REQUIRE(doc["value"].is() == false); + } + + SECTION("convert value to JSON") { + doc["value"] = Complex(19, 3); + + REQUIRE(doc["value"]["real"] == 19); + REQUIRE(doc["value"]["imag"] == 3); + } +} + +TEST_CASE("ConverterNeedsWriteableRef") { + using namespace ArduinoJson::detail; + CHECK(ConverterNeedsWriteableRef::value == false); + CHECK(ConverterNeedsWriteableRef::value == false); + CHECK(ConverterNeedsWriteableRef::value == true); + CHECK(ConverterNeedsWriteableRef::value == false); + CHECK(ConverterNeedsWriteableRef::value == true); + CHECK(ConverterNeedsWriteableRef::value == false); + CHECK(ConverterNeedsWriteableRef::value == true); + CHECK(ConverterNeedsWriteableRef::value == false); +} diff --git a/libraries/ArduinoJson/extras/tests/JsonVariant/copy.cpp b/libraries/ArduinoJson/extras/tests/JsonVariant/copy.cpp new file mode 100644 index 0000000..0d96bf9 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonVariant/copy.cpp @@ -0,0 +1,95 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonVariant::set(JsonVariant)") { + DynamicJsonDocument doc1(4096); + DynamicJsonDocument doc2(4096); + JsonVariant var1 = doc1.to(); + JsonVariant var2 = doc2.to(); + + SECTION("stores JsonArray by copy") { + JsonArray arr = doc2.to(); + JsonObject obj = arr.createNestedObject(); + obj["hello"] = "world"; + + var1.set(arr); + + arr[0] = 666; + REQUIRE(var1.as() == "[{\"hello\":\"world\"}]"); + } + + SECTION("stores JsonObject by copy") { + JsonObject obj = doc2.to(); + JsonArray arr = obj.createNestedArray("value"); + arr.add(42); + + var1.set(obj); + + obj["value"] = 666; + REQUIRE(var1.as() == "{\"value\":[42]}"); + } + + SECTION("stores const char* by reference") { + var1.set("hello!!"); + var2.set(var1); + + REQUIRE(doc1.memoryUsage() == 0); + REQUIRE(doc2.memoryUsage() == 0); + } + + SECTION("stores char* by copy") { + char str[] = "hello!!"; + + var1.set(str); + var2.set(var1); + + REQUIRE(doc1.memoryUsage() == JSON_STRING_SIZE(7)); + REQUIRE(doc2.memoryUsage() == JSON_STRING_SIZE(7)); + } + + SECTION("stores std::string by copy") { + var1.set(std::string("hello!!")); + var2.set(var1); + + REQUIRE(doc1.memoryUsage() == JSON_STRING_SIZE(7)); + REQUIRE(doc2.memoryUsage() == JSON_STRING_SIZE(7)); + } + + SECTION("stores Serialized by reference") { + var1.set(serialized("hello!!", 8)); + var2.set(var1); + + REQUIRE(doc1.memoryUsage() == 0); + REQUIRE(doc2.memoryUsage() == 0); + } + + SECTION("stores Serialized by copy") { + char str[] = "hello!!"; + var1.set(serialized(str, 7)); + var2.set(var1); + + REQUIRE(doc1.memoryUsage() == JSON_STRING_SIZE(7)); + REQUIRE(doc2.memoryUsage() == JSON_STRING_SIZE(7)); + } + + SECTION("stores Serialized by copy") { + var1.set(serialized(std::string("hello!!"))); + var2.set(var1); + + REQUIRE(doc1.memoryUsage() == JSON_STRING_SIZE(7)); + REQUIRE(doc2.memoryUsage() == JSON_STRING_SIZE(7)); + } + + SECTION("destination is unbound") { + JsonVariant unboundVariant; + + unboundVariant.set(var1); + + REQUIRE(unboundVariant.isUnbound()); + REQUIRE(unboundVariant.isNull()); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonVariant/createNested.cpp b/libraries/ArduinoJson/extras/tests/JsonVariant/createNested.cpp new file mode 100644 index 0000000..e395823 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonVariant/createNested.cpp @@ -0,0 +1,58 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include +#include + +TEST_CASE("JsonVariant::createNestedObject()") { + DynamicJsonDocument doc(4096); + JsonVariant variant = doc.to(); + + SECTION("promotes to array") { + JsonObject obj = variant.createNestedObject(); + obj["value"] = 42; + + REQUIRE(variant.is() == true); + REQUIRE(variant[0]["value"] == 42); + REQUIRE(obj.isNull() == false); + } +} + +TEST_CASE("JsonVariant::createNestedArray()") { + DynamicJsonDocument doc(4096); + JsonVariant variant = doc.to(); + + SECTION("promotes to array") { + JsonArray arr = variant.createNestedArray(); + + REQUIRE(variant.is() == true); + REQUIRE(arr.isNull() == false); + } +} + +TEST_CASE("JsonVariant::createNestedObject(key)") { + DynamicJsonDocument doc(4096); + JsonVariant variant = doc.to(); + + SECTION("promotes to object") { + JsonObject obj = variant.createNestedObject("weather"); + obj["temp"] = 42; + + REQUIRE(variant.is() == true); + REQUIRE(variant["weather"]["temp"] == 42); + } +} + +TEST_CASE("JsonVariant::createNestedArray(key)") { + DynamicJsonDocument doc(4096); + JsonVariant variant = doc.to(); + + SECTION("promotes to object") { + JsonArray arr = variant.createNestedArray("items"); + + REQUIRE(variant.is() == true); + REQUIRE(arr.isNull() == false); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonVariant/is.cpp b/libraries/ArduinoJson/extras/tests/JsonVariant/is.cpp new file mode 100644 index 0000000..6a414a4 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonVariant/is.cpp @@ -0,0 +1,319 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +enum MYENUM2 { ONE = 1, TWO = 2 }; + +TEST_CASE("JsonVariant::is()") { + DynamicJsonDocument doc(4096); + JsonVariant variant = doc.to(); + + SECTION("unbound") { + variant = JsonVariant(); + + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + } + + SECTION("null") { + CHECK(variant.is() == true); + CHECK(variant.is() == true); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + } + + SECTION("true") { + variant.set(true); + + CHECK(variant.is() == true); + CHECK(variant.is() == true); + CHECK(variant.is() == true); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + } + + SECTION("false") { + variant.set(false); + + CHECK(variant.is() == true); + CHECK(variant.is() == true); + CHECK(variant.is() == true); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + } + + SECTION("int") { + variant.set(42); + + CHECK(variant.is() == true); + CHECK(variant.is() == true); + CHECK(variant.is() == true); + CHECK(variant.is() == true); + CHECK(variant.is() == true); + CHECK(variant.is() == true); + CHECK(variant.is() == true); + CHECK(variant.is() == true); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + } + + SECTION("double") { + variant.set(4.2); + + CHECK(variant.is() == true); + CHECK(variant.is() == true); + CHECK(variant.is() == true); + CHECK(variant.is() == true); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + } + + SECTION("const char*") { + variant.set("4.2"); + + CHECK(variant.is() == true); + CHECK(variant.is() == true); + CHECK(variant.is() == true); + CHECK(variant.is() == true); + CHECK(variant.is() == true); + CHECK(variant.is() == true); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + } + + SECTION("JsonArray") { + variant.to(); + + CHECK(variant.is() == true); + CHECK(variant.is() == true); + CHECK(variant.is() == true); + CHECK(variant.is() == true); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + } + + SECTION("JsonObject") { + variant.to(); + + CHECK(variant.is() == true); + CHECK(variant.is() == true); + CHECK(variant.is() == true); + CHECK(variant.is() == true); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == false); + CHECK(variant.is() == true); + CHECK(variant.is() == true); + } +} + +TEST_CASE("JsonVariantConst::is()") { + DynamicJsonDocument doc(4096); + JsonVariant variant = doc.to(); + JsonVariantConst cvariant = variant; + + SECTION("unbound") { + cvariant = JsonVariantConst(); + + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + } + + SECTION("null") { + CHECK(cvariant.is() == true); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + } + + SECTION("true") { + variant.set(true); + + CHECK(cvariant.is() == true); + CHECK(cvariant.is() == true); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + } + + SECTION("false") { + variant.set(false); + + CHECK(cvariant.is() == true); + CHECK(cvariant.is() == true); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + } + + SECTION("int") { + variant.set(42); + + CHECK(cvariant.is() == true); + CHECK(cvariant.is() == true); + CHECK(cvariant.is() == true); + CHECK(cvariant.is() == true); + CHECK(cvariant.is() == true); + CHECK(cvariant.is() == true); + CHECK(cvariant.is() == true); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + } + + SECTION("double") { + variant.set(4.2); + + CHECK(cvariant.is() == true); + CHECK(cvariant.is() == true); + CHECK(cvariant.is() == true); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + } + + SECTION("const char*") { + variant.set("4.2"); + + CHECK(cvariant.is() == true); + CHECK(cvariant.is() == true); + CHECK(cvariant.is() == true); + CHECK(cvariant.is() == true); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + } + + SECTION("JsonArray") { + variant.to(); + + CHECK(cvariant.is() == true); + CHECK(cvariant.is() == true); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + } + + SECTION("JsonObject") { + variant.to(); + + CHECK(cvariant.is() == true); + CHECK(cvariant.is() == true); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + CHECK(cvariant.is() == false); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonVariant/isnull.cpp b/libraries/ArduinoJson/extras/tests/JsonVariant/isnull.cpp new file mode 100644 index 0000000..bb9de71 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonVariant/isnull.cpp @@ -0,0 +1,93 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonVariant::isNull()") { + DynamicJsonDocument doc(4096); + JsonVariant variant = doc.to(); + + SECTION("returns true when Undefined") { + REQUIRE(variant.isNull() == true); + } + + SECTION("returns false when Integer") { + variant.set(42); + + REQUIRE(variant.isNull() == false); + } + + SECTION("returns false when EmptyArray") { + DynamicJsonDocument doc2(4096); + JsonArray array = doc2.to(); + + variant.set(array); + REQUIRE(variant.isNull() == false); + } + + SECTION("returns false when EmptyObject") { + DynamicJsonDocument doc2(4096); + JsonObject obj = doc2.to(); + + variant.set(obj); + REQUIRE(variant.isNull() == false); + } + + SECTION("returns true after set(JsonArray())") { + variant.set(JsonArray()); + REQUIRE(variant.isNull() == true); + } + + SECTION("returns true after set(JsonObject())") { + variant.set(JsonObject()); + REQUIRE(variant.isNull() == true); + } + + SECTION("returns false after set('hello')") { + variant.set("hello"); + REQUIRE(variant.isNull() == false); + } + + SECTION("returns true after set((char*)0)") { + variant.set(static_cast(0)); + REQUIRE(variant.isNull() == true); + } + + SECTION("returns true after set((const char*)0)") { + variant.set(static_cast(0)); + REQUIRE(variant.isNull() == true); + } + + SECTION("returns true after set(serialized((char*)0))") { + variant.set(serialized(static_cast(0))); + REQUIRE(variant.isNull() == true); + } + + SECTION("returns true after set(serialized((const char*)0))") { + variant.set(serialized(static_cast(0))); + REQUIRE(variant.isNull() == true); + } + + SECTION("returns true for a shallow null copy") { + StaticJsonDocument<128> doc2; + variant.shallowCopy(doc2); + CHECK(variant.isNull() == true); + } + + SECTION("returns false for a shallow array copy") { + StaticJsonDocument<128> doc2; + doc2[0] = 42; + variant.shallowCopy(doc2); + CHECK(variant.isNull() == false); + } + + SECTION("works with JsonVariantConst") { + variant.set(42); + + JsonVariantConst cvar = variant; + + REQUIRE(cvar.isNull() == false); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonVariant/memoryUsage.cpp b/libraries/ArduinoJson/extras/tests/JsonVariant/memoryUsage.cpp new file mode 100644 index 0000000..808acb3 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonVariant/memoryUsage.cpp @@ -0,0 +1,41 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include +#include + +TEST_CASE("JsonVariant::memoryUsage()") { + DynamicJsonDocument doc(4096); + JsonVariant var = doc.to(); + + SECTION("returns 0 if uninitialized") { + JsonVariant unitialized; + REQUIRE(unitialized.memoryUsage() == 0); + } + + SECTION("returns size of object") { + JsonObject obj = var.to(); + obj["hello"] = 42; + REQUIRE(var.memoryUsage() == JSON_OBJECT_SIZE(1)); + } + + SECTION("returns size of array") { + JsonArray arr = var.to(); + arr.add(42); + REQUIRE(var.memoryUsage() == JSON_ARRAY_SIZE(1)); + } + + SECTION("returns size of owned string") { + var.set(std::string("hello")); + REQUIRE(var.memoryUsage() == 6); + REQUIRE(var.memoryUsage() == doc.memoryUsage()); + } + + SECTION("returns size of owned raw") { + var.set(serialized(std::string("hello"))); + REQUIRE(var.memoryUsage() == 6); + REQUIRE(var.memoryUsage() == doc.memoryUsage()); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonVariant/misc.cpp b/libraries/ArduinoJson/extras/tests/JsonVariant/misc.cpp new file mode 100644 index 0000000..7089f64 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonVariant/misc.cpp @@ -0,0 +1,55 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("VariantData") { + REQUIRE(std::is_standard_layout::value == + true); +} + +TEST_CASE("JsonVariant from JsonArray") { + SECTION("JsonArray is null") { + JsonArray arr; + JsonVariant v = arr; + REQUIRE(v.isNull() == true); + } + + SECTION("JsonArray is not null") { + DynamicJsonDocument doc(4096); + JsonArray arr = doc.to(); + arr.add(12); + arr.add(34); + + JsonVariant v = arr; + + REQUIRE(v.is() == true); + REQUIRE(v.size() == 2); + REQUIRE(v[0] == 12); + REQUIRE(v[1] == 34); + } +} + +TEST_CASE("JsonVariant from JsonObject") { + SECTION("JsonObject is null") { + JsonObject obj; + JsonVariant v = obj; + REQUIRE(v.isNull() == true); + } + + SECTION("JsonObject is not null") { + DynamicJsonDocument doc(4096); + JsonObject obj = doc.to(); + obj["a"] = 12; + obj["b"] = 34; + + JsonVariant v = obj; + + REQUIRE(v.is() == true); + REQUIRE(v.size() == 2); + REQUIRE(v["a"] == 12); + REQUIRE(v["b"] == 34); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonVariant/nesting.cpp b/libraries/ArduinoJson/extras/tests/JsonVariant/nesting.cpp new file mode 100644 index 0000000..1028a28 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonVariant/nesting.cpp @@ -0,0 +1,31 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonVariant::nesting()") { + DynamicJsonDocument doc(4096); + JsonVariant var = doc.to(); + + SECTION("return 0 if uninitialized") { + JsonVariant unitialized; + REQUIRE(unitialized.nesting() == 0); + } + + SECTION("returns 0 for string") { + var.set("hello"); + REQUIRE(var.nesting() == 0); + } + + SECTION("returns 1 for empty object") { + var.to(); + REQUIRE(var.nesting() == 1); + } + + SECTION("returns 1 for empty array") { + var.to(); + REQUIRE(var.nesting() == 1); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonVariant/nullptr.cpp b/libraries/ArduinoJson/extras/tests/JsonVariant/nullptr.cpp new file mode 100644 index 0000000..e26d930 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonVariant/nullptr.cpp @@ -0,0 +1,43 @@ +#include + +#include + +TEST_CASE("nullptr") { + DynamicJsonDocument doc(4096); + JsonVariant variant = doc.to(); + + SECTION("JsonVariant == nullptr") { + REQUIRE(variant == nullptr); + REQUIRE_FALSE(variant != nullptr); + } + + SECTION("JsonVariant != nullptr") { + variant.set(42); + + REQUIRE_FALSE(variant == nullptr); + REQUIRE(variant != nullptr); + } + + SECTION("JsonVariant.set(nullptr)") { + variant.set(42); + variant.set(nullptr); + + REQUIRE(variant.isNull()); + } + + SECTION("JsonVariant.set(nullptr) with unbound reference") { + JsonVariant unboundReference; + + unboundReference.set(nullptr); + + REQUIRE(variant.isNull()); + } + + SECTION("JsonVariant.is()") { + variant.set(42); + REQUIRE(variant.is() == false); + + variant.clear(); + REQUIRE(variant.is() == true); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonVariant/or.cpp b/libraries/ArduinoJson/extras/tests/JsonVariant/or.cpp new file mode 100644 index 0000000..01ec470 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonVariant/or.cpp @@ -0,0 +1,159 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonVariant::operator|()") { + DynamicJsonDocument doc(4096); + JsonVariant variant = doc["value"].to(); + + SECTION("null") { + SECTION("null | const char*") { + std::string result = variant | "default"; + REQUIRE(result == "default"); + } + + SECTION("null | int") { + int result = variant | 42; + REQUIRE(result == 42); + } + + SECTION("null | bool") { + bool result = variant | true; + REQUIRE(result == true); + } + + SECTION("null | ElementProxy") { + doc["array"][0] = 42; + + JsonVariantConst result = variant | doc["array"][0]; + REQUIRE(result == 42); + } + + SECTION("null | MemberProxy") { + doc["other"] = 42; + + JsonVariantConst result = variant | doc["other"]; + REQUIRE(result == 42); + } + + SECTION("ElementProxy | ElementProxy") { + doc["array"][0] = 42; + + JsonVariantConst result = doc["array"][1] | doc["array"][0]; + REQUIRE(result == 42); + } + } + + SECTION("null") { + variant.set(static_cast(0)); + + SECTION("null | const char*") { + std::string result = variant | "default"; + REQUIRE(result == "default"); + } + + SECTION("null | int") { + int result = variant | 42; + REQUIRE(result == 42); + } + + SECTION("null | bool") { + bool result = variant | true; + REQUIRE(result == true); + } + + SECTION("null | ElementProxy") { + doc["array"][0] = 42; + + JsonVariantConst result = variant | doc["array"][0]; + REQUIRE(result == 42); + } + + SECTION("null | MemberProxy") { + doc["other"] = 42; + + JsonVariantConst result = variant | doc["other"]; + REQUIRE(result == 42); + } + } + + SECTION("int | const char*") { + variant.set(42); + std::string result = variant | "default"; + REQUIRE(result == "default"); + } + + SECTION("int | uint8_t (out of range)") { + variant.set(666); + uint8_t result = variant | static_cast(42); + REQUIRE(result == 42); + } + + SECTION("int | ElementProxy") { + variant.set(42); + doc["array"][0] = 666; + JsonVariantConst result = variant | doc["array"][0]; + REQUIRE(result == 42); + } + + SECTION("int | MemberProxy") { + variant.set(42); + doc["other"] = 666; + JsonVariantConst result = variant | doc["other"]; + REQUIRE(result == 42); + } + + SECTION("int | int") { + variant.set(0); + int result = variant | 666; + REQUIRE(result == 0); + } + + SECTION("double | int") { + // NOTE: changed the behavior to fix #981 + variant.set(666.0); + int result = variant | 42; + REQUIRE(result == 42); + } + + SECTION("bool | bool") { + variant.set(false); + bool result = variant | true; + REQUIRE(result == false); + } + + SECTION("int | bool") { + variant.set(0); + bool result = variant | true; + REQUIRE(result == true); + } + + SECTION("const char* | const char*") { + variant.set("not default"); + std::string result = variant | "default"; + REQUIRE(result == "not default"); + } + + SECTION("const char* | char*") { + char dflt[] = "default"; + variant.set("not default"); + std::string result = variant | dflt; + REQUIRE(result == "not default"); + } + + SECTION("int | char*") { + char dflt[] = "default"; + variant.set(42); + std::string result = variant | dflt; + REQUIRE(result == "default"); + } + + SECTION("const char* | int") { + variant.set("not default"); + int result = variant | 42; + REQUIRE(result == 42); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonVariant/overflow.cpp b/libraries/ArduinoJson/extras/tests/JsonVariant/overflow.cpp new file mode 100644 index 0000000..1123e98 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonVariant/overflow.cpp @@ -0,0 +1,72 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +template +void shouldBeOk(TIn value) { + StaticJsonDocument<1> doc; + JsonVariant var = doc.to(); + var.set(value); + REQUIRE(var.as() == TOut(value)); +} + +template +void shouldOverflow(TIn value) { + StaticJsonDocument<1> doc; + JsonVariant var = doc.to(); + var.set(value); + REQUIRE(var.as() == 0); + REQUIRE(var.is() == false); +} + +TEST_CASE("Handle integer overflow in stored integer") { + SECTION("int8_t") { + // ok + shouldBeOk(-128); + shouldBeOk(42.0); + shouldBeOk(127); + + // too low + shouldOverflow(-128.1); + shouldOverflow(-129); + + // too high + shouldOverflow(128); + shouldOverflow(127.1); + } + + SECTION("int16_t") { + // ok + shouldBeOk(-32768); + shouldBeOk(-32767.9); + shouldBeOk(32766.9); + shouldBeOk(32767); + + // too low + shouldOverflow(-32768.1); + shouldOverflow(-32769); + + // too high + shouldOverflow(32767.1); + shouldOverflow(32768); + } + + SECTION("uint8_t") { + // ok + shouldBeOk(1); + shouldBeOk(42.0); + shouldBeOk(255); + + // too low + shouldOverflow(-1); + shouldOverflow(-0.1); + + // to high + shouldOverflow(255.1); + shouldOverflow(256); + shouldOverflow(257); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonVariant/remove.cpp b/libraries/ArduinoJson/extras/tests/JsonVariant/remove.cpp new file mode 100644 index 0000000..0835bf0 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonVariant/remove.cpp @@ -0,0 +1,40 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include +#include + +TEST_CASE("JsonVariant::remove()") { + DynamicJsonDocument doc(4096); + JsonVariant var = doc.to(); + + SECTION("remove(int)") { + var.add(1); + var.add(2); + var.add(3); + + var.remove(1); + + REQUIRE(var.as() == "[1,3]"); + } + + SECTION("remove(const char *)") { + var["a"] = 1; + var["b"] = 2; + + var.remove("a"); + + REQUIRE(var.as() == "{\"b\":2}"); + } + + SECTION("remove(std::string)") { + var["a"] = 1; + var["b"] = 2; + + var.remove(std::string("b")); + + REQUIRE(var.as() == "{\"a\":1}"); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonVariant/set.cpp b/libraries/ArduinoJson/extras/tests/JsonVariant/set.cpp new file mode 100644 index 0000000..4743afb --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonVariant/set.cpp @@ -0,0 +1,172 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +enum ErrorCode { ERROR_01 = 1, ERROR_10 = 10 }; + +TEST_CASE("JsonVariant::set() when there is enough memory") { + DynamicJsonDocument doc(4096); + JsonVariant variant = doc.to(); + + SECTION("const char*") { + char str[16]; + + strcpy(str, "hello"); + bool result = variant.set(static_cast(str)); + strcpy(str, "world"); + + REQUIRE(result == true); + REQUIRE(variant == "world"); // stores by pointer + } + + SECTION("(const char*)0") { + bool result = variant.set(static_cast(0)); + + REQUIRE(result == true); + REQUIRE(variant.isNull()); + } + + SECTION("char*") { + char str[16]; + + strcpy(str, "hello"); + bool result = variant.set(str); + strcpy(str, "world"); + + REQUIRE(result == true); + REQUIRE(variant == "hello"); // stores by copy + } + + SECTION("(char*)0") { + bool result = variant.set(static_cast(0)); + + REQUIRE(result == true); + REQUIRE(variant.isNull()); + } + + SECTION("unsigned char*") { + char str[16]; + + strcpy(str, "hello"); + bool result = variant.set(reinterpret_cast(str)); + strcpy(str, "world"); + + REQUIRE(result == true); + REQUIRE(variant == "hello"); // stores by copy + } + + SECTION("signed char*") { + char str[16]; + + strcpy(str, "hello"); + bool result = variant.set(reinterpret_cast(str)); + strcpy(str, "world"); + + REQUIRE(result == true); + REQUIRE(variant == "hello"); // stores by copy + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("VLA") { + size_t n = 16; + char str[n]; + + strcpy(str, "hello"); + bool result = variant.set(str); + strcpy(str, "world"); + + REQUIRE(result == true); + REQUIRE(variant == "hello"); // stores by copy + } +#endif + + SECTION("std::string") { + std::string str; + + str = "hello"; + bool result = variant.set(str); + str.replace(0, 5, "world"); + + REQUIRE(result == true); + REQUIRE(variant == "hello"); // stores by copy + } + + SECTION("static JsonString") { + char str[16]; + + strcpy(str, "hello"); + bool result = variant.set(JsonString(str, JsonString::Linked)); + strcpy(str, "world"); + + REQUIRE(result == true); + REQUIRE(variant == "world"); // stores by pointer + } + + SECTION("non-static JsonString") { + char str[16]; + + strcpy(str, "hello"); + bool result = variant.set(JsonString(str, JsonString::Copied)); + strcpy(str, "world"); + + REQUIRE(result == true); + REQUIRE(variant == "hello"); // stores by copy + } + + SECTION("enum") { + ErrorCode code = ERROR_10; + + bool result = variant.set(code); + + REQUIRE(result == true); + REQUIRE(variant.is() == true); + REQUIRE(variant.as() == 10); + } +} + +TEST_CASE("JsonVariant::set() with not enough memory") { + StaticJsonDocument<1> doc; + + JsonVariant v = doc.to(); + + SECTION("std::string") { + bool result = v.set(std::string("hello world!!")); + + REQUIRE(result == false); + REQUIRE(v.isNull()); + } + + SECTION("Serialized") { + bool result = v.set(serialized(std::string("hello world!!"))); + + REQUIRE(result == false); + REQUIRE(v.isNull()); + } + + SECTION("char*") { + char s[] = "hello world!!"; + bool result = v.set(s); + + REQUIRE(result == false); + REQUIRE(v.isNull()); + } +} + +TEST_CASE("JsonVariant::set(DynamicJsonDocument)") { + DynamicJsonDocument doc1(1024); + doc1["hello"] = "world"; + + DynamicJsonDocument doc2(1024); + JsonVariant v = doc2.to(); + + // Should copy the doc + v.set(doc1); + doc1.clear(); + + std::string json; + serializeJson(doc2, json); + REQUIRE(json == "{\"hello\":\"world\"}"); +} diff --git a/libraries/ArduinoJson/extras/tests/JsonVariant/shallowCopy.cpp b/libraries/ArduinoJson/extras/tests/JsonVariant/shallowCopy.cpp new file mode 100644 index 0000000..28aa38c --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonVariant/shallowCopy.cpp @@ -0,0 +1,87 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonVariant::shallowCopy()") { + StaticJsonDocument<1024> doc1, doc2; + JsonVariant variant = doc1.to(); + + SECTION("JsonVariant::shallowCopy(JsonDocument&)") { + doc2["hello"] = "world"; + + variant.shallowCopy(doc2); + + CHECK(variant.as() == "{\"hello\":\"world\"}"); + + // altering the linked document should change the result + doc2["hello"] = "WORLD!"; + + CHECK(variant.as() == "{\"hello\":\"WORLD!\"}"); + } + + SECTION("JsonVariant::shallowCopy(MemberProxy)") { + doc2["obj"]["hello"] = "world"; + + variant.shallowCopy(doc2["obj"]); + + CHECK(variant.as() == "{\"hello\":\"world\"}"); + + // altering the linked document should change the result + doc2["obj"]["hello"] = "WORLD!"; + + CHECK(variant.as() == "{\"hello\":\"WORLD!\"}"); + } + + SECTION("JsonVariant::shallowCopy(ElementProxy)") { + doc2[0]["hello"] = "world"; + + variant.shallowCopy(doc2[0]); + + CHECK(variant.as() == "{\"hello\":\"world\"}"); + + // altering the linked document should change the result + doc2[0]["hello"] = "WORLD!"; + + CHECK(variant.as() == "{\"hello\":\"WORLD!\"}"); + } + + SECTION("target is unbound") { + JsonVariant unbound; + variant["hello"] = "world"; + + variant.shallowCopy(unbound); + + CHECK(variant.isUnbound() == false); + CHECK(variant.isNull() == true); + CHECK(variant.memoryUsage() == 0); + CHECK(variant.size() == 0); + } + + SECTION("variant is unbound") { + JsonVariant unbound; + doc2["hello"] = "world"; + + unbound.shallowCopy(doc2); + + CHECK(unbound.isUnbound() == true); + CHECK(unbound.isNull() == true); + CHECK(unbound.memoryUsage() == 0); + CHECK(unbound.size() == 0); + } + + SECTION("preserves owned key bit") { + doc2.set(42); + + doc1["a"].shallowCopy(doc2); + doc1[std::string("b")].shallowCopy(doc2); + + JsonObject::iterator it = doc1.as().begin(); + + CHECK(it->key().isLinked() == true); + ++it; + CHECK(it->key().isLinked() == false); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonVariant/size.cpp b/libraries/ArduinoJson/extras/tests/JsonVariant/size.cpp new file mode 100644 index 0000000..3a4ec46 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonVariant/size.cpp @@ -0,0 +1,36 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonVariant::size()") { + DynamicJsonDocument doc(4096); + JsonVariant variant = doc.to(); + + SECTION("unbound reference") { + JsonVariant unbound; + + CHECK(unbound.size() == 0); + } + + SECTION("int") { + variant.set(42); + + CHECK(variant.size() == 0); + } + + SECTION("string") { + variant.set("hello"); + + CHECK(variant.size() == 0); + } + + SECTION("object") { + variant["a"] = 1; + variant["b"] = 2; + + CHECK(variant.size() == 2); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonVariant/stl_containers.cpp b/libraries/ArduinoJson/extras/tests/JsonVariant/stl_containers.cpp new file mode 100644 index 0000000..d6b9b60 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonVariant/stl_containers.cpp @@ -0,0 +1,138 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include +#include + +#include +#include +#include + +namespace ArduinoJson { +template +struct Converter> { + static void toJson(const std::vector& src, JsonVariant dst) { + JsonArray array = dst.to(); + for (T item : src) + array.add(item); + } + + static std::vector fromJson(JsonVariantConst src) { + std::vector dst; + for (T item : src.as()) + dst.push_back(item); + return dst; + } + + static bool checkJson(JsonVariantConst src) { + JsonArrayConst array = src; + bool result = array; + for (JsonVariantConst item : array) + result &= item.is(); + return result; + } +}; + +template +struct Converter> { + static void toJson(const std::array& src, JsonVariant dst) { + JsonArray array = dst.to(); + for (T item : src) + array.add(item); + } + + static std::array fromJson(JsonVariantConst src) { + std::array dst; + dst.fill(0); + size_t idx = 0; + for (T item : src.as()) + dst[idx++] = item; + return dst; + } + + static bool checkJson(JsonVariantConst src) { + JsonArrayConst array = src; + bool result = array; + size_t size = 0; + for (JsonVariantConst item : array) { + result &= item.is(); + size++; + } + return result && size == N; + } +}; +} // namespace ArduinoJson + +TEST_CASE("vector") { + SECTION("toJson") { + std::vector v = {1, 2}; + + StaticJsonDocument<128> doc; + doc.set(v); + REQUIRE(doc.as() == "[1,2]"); + } + + SECTION("fromJson") { + StaticJsonDocument<128> doc; + doc.add(1); + doc.add(2); + + auto v = doc.as>(); + REQUIRE(v.size() == 2); + CHECK(v[0] == 1); + CHECK(v[1] == 2); + } + + SECTION("checkJson") { + StaticJsonDocument<128> doc; + CHECK(doc.is>() == false); + + doc.add(1); + doc.add(2); + CHECK(doc.is>() == true); + + doc.add("foo"); + CHECK(doc.is>() == false); + } +} + +TEST_CASE("array") { + typedef std::array array_type; + + SECTION("toJson") { + array_type v; + v[0] = 1; + v[1] = 2; + + StaticJsonDocument<128> doc; + doc.set(v); + REQUIRE(doc.as() == "[1,2]"); + } + + SECTION("fromJson") { + StaticJsonDocument<128> doc; + doc.add(1); + doc.add(2); + + auto v = doc.as(); + REQUIRE(v.size() == 2); + CHECK(v[0] == 1); + CHECK(v[1] == 2); + } + + SECTION("checkJson") { + StaticJsonDocument<128> doc; + CHECK(doc.is() == false); + + doc.add(1); + CHECK(doc.is() == false); + + doc.add(2); + CHECK(doc.is() == true); + + doc[0] = "foo"; + CHECK(doc.is() == false); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonVariant/subscript.cpp b/libraries/ArduinoJson/extras/tests/JsonVariant/subscript.cpp new file mode 100644 index 0000000..93f759b --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonVariant/subscript.cpp @@ -0,0 +1,204 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonVariant::operator[]") { + DynamicJsonDocument doc(4096); + JsonVariant var = doc.to(); + + SECTION("The JsonVariant is null") { + REQUIRE(0 == var.size()); + REQUIRE(var["0"].isNull()); + REQUIRE(var[0].isNull()); + } + + SECTION("The JsonVariant is a string") { + var.set("hello world"); + REQUIRE(0 == var.size()); + REQUIRE(var["0"].isNull()); + REQUIRE(var[0].isNull()); + } + + SECTION("The JsonVariant is a JsonArray") { + JsonArray array = var.to(); + + SECTION("get value") { + array.add("element at index 0"); + array.add("element at index 1"); + + REQUIRE(2 == var.size()); + var[0].as(); + // REQUIRE(std::string("element at index 0") == ); + REQUIRE(std::string("element at index 1") == var[1]); + REQUIRE(std::string("element at index 0") == + var[static_cast(0)]); // issue #381 + REQUIRE(var[666].isNull()); + REQUIRE(var[3].isNull()); + REQUIRE(var["0"].isNull()); + } + + SECTION("set value") { + array.add("hello"); + + var[1] = "world"; + + REQUIRE(var.size() == 2); + REQUIRE(std::string("world") == var[1]); + } + + SECTION("set value in a nested object") { + array.createNestedObject(); + + var[0]["hello"] = "world"; + + REQUIRE(1 == var.size()); + REQUIRE(1 == var[0].size()); + REQUIRE(std::string("world") == var[0]["hello"]); + } + + SECTION("variant[0] when variant contains an integer") { + var.set(123); + + var[0] = 345; // no-op + + REQUIRE(var.is()); + REQUIRE(var.as() == 123); + } + } + + SECTION("The JsonVariant is a JsonObject") { + JsonObject object = var.to(); + + SECTION("get value") { + object["a"] = "element at key \"a\""; + object["b"] = "element at key \"b\""; + + REQUIRE(2 == var.size()); + REQUIRE(std::string("element at key \"a\"") == var["a"]); + REQUIRE(std::string("element at key \"b\"") == var["b"]); + REQUIRE(var["c"].isNull()); + REQUIRE(var[0].isNull()); + } + + SECTION("set value, key is a const char*") { + var["hello"] = "world"; + + REQUIRE(1 == var.size()); + REQUIRE(std::string("world") == var["hello"]); + } + + SECTION("set value, key is a char[]") { + char key[] = "hello"; + var[key] = "world"; + key[0] = '!'; // make sure the key is duplicated + + REQUIRE(1 == var.size()); + REQUIRE(std::string("world") == var["hello"]); + } + + SECTION("var[key].to()") { + JsonArray arr = var["hello"].to(); + REQUIRE(arr.isNull() == false); + } + } + +#if defined(HAS_VARIABLE_LENGTH_ARRAY) && \ + !defined(SUBSCRIPT_CONFLICTS_WITH_BUILTIN_OPERATOR) + SECTION("key is a VLA") { + size_t i = 16; + char vla[i]; + strcpy(vla, "hello"); + + deserializeJson(doc, "{\"hello\":\"world\"}"); + JsonVariant variant = doc.as(); + + REQUIRE(std::string("world") == variant[vla]); + } + + SECTION("key is a VLA, const JsonVariant") { + size_t i = 16; + char vla[i]; + strcpy(vla, "hello"); + + deserializeJson(doc, "{\"hello\":\"world\"}"); + const JsonVariant variant = doc.as(); + + REQUIRE(std::string("world") == variant[vla]); + } +#endif +} + +TEST_CASE("JsonVariantConst::operator[]") { + DynamicJsonDocument doc(4096); + JsonVariant var = doc.to(); + JsonVariantConst cvar = var; + + SECTION("The JsonVariant is null") { + REQUIRE(0 == cvar.size()); + REQUIRE(cvar["0"].isNull()); + REQUIRE(cvar[0].isNull()); + } + + SECTION("The JsonVariant is a string") { + var.set("hello world"); + REQUIRE(0 == cvar.size()); + REQUIRE(cvar["0"].isNull()); + REQUIRE(cvar[0].isNull()); + } + + SECTION("The JsonVariant is a JsonArray") { + JsonArray array = var.to(); + + SECTION("get value") { + array.add("element at index 0"); + array.add("element at index 1"); + + REQUIRE(2 == cvar.size()); + REQUIRE(std::string("element at index 0") == cvar[0]); + REQUIRE(std::string("element at index 1") == cvar[1]); + REQUIRE(std::string("element at index 0") == + var[static_cast(0)]); // issue #381 + REQUIRE(cvar[666].isNull()); + REQUIRE(cvar[3].isNull()); + REQUIRE(cvar["0"].isNull()); + } + } + + SECTION("The JsonVariant is a JsonObject") { + JsonObject object = var.to(); + + SECTION("get value") { + object["a"] = "element at key \"a\""; + object["b"] = "element at key \"b\""; + + REQUIRE(2 == cvar.size()); + REQUIRE(std::string("element at key \"a\"") == cvar["a"]); + REQUIRE(std::string("element at key \"b\"") == cvar["b"]); + REQUIRE(cvar["c"].isNull()); + REQUIRE(cvar[0].isNull()); + } + } + + SECTION("Auto promote null JsonVariant to JsonObject") { + var["hello"] = "world"; + + REQUIRE(var.is() == true); + } + + SECTION("Don't auto promote non-null JsonVariant to JsonObject") { + var.set(42); + var["hello"] = "world"; + + REQUIRE(var.is() == false); + } + + SECTION("Don't auto promote null JsonVariant to JsonObject when reading") { + const char* value = var["hello"]; + + REQUIRE(var.is() == false); + REQUIRE(value == 0); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonVariant/types.cpp b/libraries/ArduinoJson/extras/tests/JsonVariant/types.cpp new file mode 100644 index 0000000..4224299 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonVariant/types.cpp @@ -0,0 +1,163 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include +#include +#include + +template +void checkValue(T expected) { + DynamicJsonDocument doc(4096); + JsonVariant variant = doc.to(); + + variant.set(expected); + REQUIRE(expected == variant.as()); +} + +template +void checkReference(T& expected) { + JsonVariant variant = expected; + REQUIRE(expected == variant.as()); +} + +template +void checkNumericType() { + DynamicJsonDocument docMin(4096), docMax(4096); + JsonVariant variantMin = docMin.to(); + JsonVariant variantMax = docMax.to(); + + T min = std::numeric_limits::min(); + T max = std::numeric_limits::max(); + + variantMin.set(min); + variantMax.set(max); + + REQUIRE(min == variantMin.as()); + REQUIRE(max == variantMax.as()); +} + +TEST_CASE("JsonVariant set()/get()") { +#if ARDUINOJSON_USE_LONG_LONG + SECTION("SizeOfJsonInteger") { + REQUIRE(8 == sizeof(JsonInteger)); + } +#endif + + SECTION("Null") { + checkValue(NULL); + } + SECTION("const char*") { + checkValue("hello"); + } + SECTION("std::string") { + checkValue("hello"); + } + + SECTION("False") { + checkValue(false); + } + SECTION("True") { + checkValue(true); + } + + SECTION("Double") { + checkNumericType(); + } + SECTION("Float") { + checkNumericType(); + } + SECTION("SChar") { + checkNumericType(); + } + SECTION("SInt") { + checkNumericType(); + } + SECTION("SLong") { + checkNumericType(); + } + SECTION("SShort") { + checkNumericType(); + } + SECTION("UChar") { + checkNumericType(); + } + SECTION("UInt") { + checkNumericType(); + } + SECTION("ULong") { + checkNumericType(); + } + SECTION("UShort") { + checkNumericType(); + } +#if ARDUINOJSON_USE_LONG_LONG + SECTION("LongLong") { + checkNumericType(); + } + SECTION("ULongLong") { + checkNumericType(); + } +#endif + + SECTION("Int8") { + checkNumericType(); + } + SECTION("Uint8") { + checkNumericType(); + } + SECTION("Int16") { + checkNumericType(); + } + SECTION("Uint16") { + checkNumericType(); + } + SECTION("Int32") { + checkNumericType(); + } + SECTION("Uint32") { + checkNumericType(); + } +#if ARDUINOJSON_USE_LONG_LONG + SECTION("Int64") { + checkNumericType(); + } + SECTION("Uint64") { + checkNumericType(); + } +#endif + + SECTION("CanStoreObject") { + DynamicJsonDocument doc(4096); + JsonObject object = doc.to(); + + checkValue(object); + } +} + +TEST_CASE("volatile") { + DynamicJsonDocument doc(4096); + JsonVariant variant = doc.to(); + + SECTION("volatile int") { + volatile int f = 42; + variant.set(f); + CHECK(variant.is() == true); + CHECK(variant.as() == 42); + } + + SECTION("volatile float") { // issue #1557 + volatile float f = 3.14f; + variant.set(f); + CHECK(variant.is() == true); + CHECK(variant.as() == 3.14f); + } + + SECTION("volatile double") { + volatile double f = 3.14; + variant.set(f); + CHECK(variant.is() == true); + CHECK(variant.as() == 3.14); + } +} diff --git a/libraries/ArduinoJson/extras/tests/JsonVariant/unbound.cpp b/libraries/ArduinoJson/extras/tests/JsonVariant/unbound.cpp new file mode 100644 index 0000000..9020323 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/JsonVariant/unbound.cpp @@ -0,0 +1,66 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("Unbound JsonVariant") { + JsonVariant variant; + + SECTION("as()") { + CHECK(variant.as() == false); + CHECK(variant.as() == 0); + CHECK(variant.as() == 0.0f); + CHECK(variant.as() == 0); + CHECK(variant.as() == "null"); + CHECK(variant.as().isNull()); + CHECK(variant.as().isNull()); + CHECK(variant.as().isNull()); + CHECK(variant.as().isNull()); + CHECK(variant.as().isNull()); + CHECK(variant.as().isNull()); + CHECK(variant.as().isNull()); + } + + SECTION("is()") { + CHECK_FALSE(variant.is()); + CHECK_FALSE(variant.is()); + CHECK_FALSE(variant.is()); + CHECK_FALSE(variant.is()); + CHECK_FALSE(variant.is()); + CHECK_FALSE(variant.is()); + CHECK_FALSE(variant.is()); + CHECK_FALSE(variant.is()); + CHECK_FALSE(variant.is()); + CHECK_FALSE(variant.is()); + CHECK_FALSE(variant.is()); + CHECK_FALSE(variant.is()); + } + + SECTION("set()") { + CHECK_FALSE(variant.set("42")); + CHECK_FALSE(variant.set(42.0)); + CHECK_FALSE(variant.set(42L)); + CHECK_FALSE(variant.set(42U)); + CHECK_FALSE(variant.set(serialized("42"))); + CHECK_FALSE(variant.set(true)); + } + + SECTION("add()") { + CHECK_FALSE(variant.add("42")); + CHECK_FALSE(variant.add(42.0)); + CHECK_FALSE(variant.add(42L)); + CHECK_FALSE(variant.add(42U)); + CHECK_FALSE(variant.add(serialized("42"))); + CHECK_FALSE(variant.add(true)); + } + + SECTION("operator[]") { + CHECK(variant[0].isNull()); + CHECK(variant["key"].isNull()); + CHECK_FALSE(variant[0].set(1)); + CHECK_FALSE(variant["key"].set(1)); + CHECK_FALSE(variant[std::string("key")].set(1)); + } +} diff --git a/libraries/ArduinoJson/extras/tests/MemoryPool/CMakeLists.txt b/libraries/ArduinoJson/extras/tests/MemoryPool/CMakeLists.txt new file mode 100644 index 0000000..2f809cc --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MemoryPool/CMakeLists.txt @@ -0,0 +1,18 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2023, Benoit BLANCHON +# MIT License + +add_executable(MemoryPoolTests + allocVariant.cpp + clear.cpp + saveString.cpp + size.cpp + StringCopier.cpp +) + +add_test(MemoryPool MemoryPoolTests) + +set_tests_properties(MemoryPool + PROPERTIES + LABELS "Catch" +) diff --git a/libraries/ArduinoJson/extras/tests/MemoryPool/StringCopier.cpp b/libraries/ArduinoJson/extras/tests/MemoryPool/StringCopier.cpp new file mode 100644 index 0000000..0342bc4 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MemoryPool/StringCopier.cpp @@ -0,0 +1,93 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +using namespace ArduinoJson::detail; + +TEST_CASE("StringCopier") { + char buffer[4096]; + + SECTION("Works when buffer is big enough") { + MemoryPool pool(buffer, addPadding(JSON_STRING_SIZE(5))); + StringCopier str(&pool); + + str.startString(); + str.append("hello"); + + REQUIRE(str.isValid() == true); + REQUIRE(str.str() == "hello"); + REQUIRE(pool.overflowed() == false); + } + + SECTION("Returns null when too small") { + MemoryPool pool(buffer, sizeof(void*)); + StringCopier str(&pool); + + str.startString(); + str.append("hello world!"); + + REQUIRE(str.isValid() == false); + REQUIRE(pool.overflowed() == true); + } + + SECTION("Increases size of memory pool") { + MemoryPool pool(buffer, addPadding(JSON_STRING_SIZE(6))); + StringCopier str(&pool); + + str.startString(); + str.save(); + + REQUIRE(1 == pool.size()); + REQUIRE(pool.overflowed() == false); + } + + SECTION("Works when memory pool is 0 bytes") { + MemoryPool pool(buffer, 0); + StringCopier str(&pool); + + str.startString(); + REQUIRE(str.isValid() == false); + REQUIRE(pool.overflowed() == true); + } +} + +static const char* addStringToPool(MemoryPool& pool, const char* s) { + StringCopier str(&pool); + str.startString(); + str.append(s); + return str.save().c_str(); +} + +TEST_CASE("StringCopier::save() deduplicates strings") { + char buffer[4096]; + MemoryPool pool(buffer, 4096); + + SECTION("Basic") { + const char* s1 = addStringToPool(pool, "hello"); + const char* s2 = addStringToPool(pool, "world"); + const char* s3 = addStringToPool(pool, "hello"); + + REQUIRE(s1 == s3); + REQUIRE(s2 != s3); + REQUIRE(pool.size() == 12); + } + + SECTION("Requires terminator") { + const char* s1 = addStringToPool(pool, "hello world"); + const char* s2 = addStringToPool(pool, "hello"); + + REQUIRE(s2 != s1); + REQUIRE(pool.size() == 12 + 6); + } + + SECTION("Don't overrun") { + const char* s1 = addStringToPool(pool, "hello world"); + const char* s2 = addStringToPool(pool, "wor"); + + REQUIRE(s2 != s1); + REQUIRE(pool.size() == 12 + 4); + } +} diff --git a/libraries/ArduinoJson/extras/tests/MemoryPool/allocVariant.cpp b/libraries/ArduinoJson/extras/tests/MemoryPool/allocVariant.cpp new file mode 100644 index 0000000..5123a4e --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MemoryPool/allocVariant.cpp @@ -0,0 +1,50 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +using namespace ArduinoJson::detail; + +TEST_CASE("MemoryPool::allocVariant()") { + char buffer[4096]; + + SECTION("Returns different pointer") { + MemoryPool pool(buffer, sizeof(buffer)); + + VariantSlot* s1 = pool.allocVariant(); + REQUIRE(s1 != 0); + VariantSlot* s2 = pool.allocVariant(); + REQUIRE(s2 != 0); + + REQUIRE(s1 != s2); + } + + SECTION("Returns aligned pointers") { + MemoryPool pool(buffer, sizeof(buffer)); + + REQUIRE(isAligned(pool.allocVariant())); + REQUIRE(isAligned(pool.allocVariant())); + } + + SECTION("Returns zero if capacity is 0") { + MemoryPool pool(buffer, 0); + + REQUIRE(pool.allocVariant() == 0); + } + + SECTION("Returns zero if buffer is null") { + MemoryPool pool(0, sizeof(buffer)); + + REQUIRE(pool.allocVariant() == 0); + } + + SECTION("Returns zero if capacity is insufficient") { + MemoryPool pool(buffer, sizeof(VariantSlot)); + + pool.allocVariant(); + + REQUIRE(pool.allocVariant() == 0); + } +} diff --git a/libraries/ArduinoJson/extras/tests/MemoryPool/clear.cpp b/libraries/ArduinoJson/extras/tests/MemoryPool/clear.cpp new file mode 100644 index 0000000..9e33b47 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MemoryPool/clear.cpp @@ -0,0 +1,32 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include +#include + +using namespace ArduinoJson::detail; + +static const size_t poolCapacity = 512; + +TEST_CASE("MemoryPool::clear()") { + char buffer[poolCapacity]; + MemoryPool pool(buffer, sizeof(buffer)); + + SECTION("Discards allocated variants") { + pool.allocVariant(); + + pool.clear(); + REQUIRE(pool.size() == 0); + } + + SECTION("Discards allocated strings") { + pool.saveString(adaptString(const_cast("123456789"))); + REQUIRE(pool.size() == 10); + + pool.clear(); + + REQUIRE(pool.size() == 0); + } +} diff --git a/libraries/ArduinoJson/extras/tests/MemoryPool/saveString.cpp b/libraries/ArduinoJson/extras/tests/MemoryPool/saveString.cpp new file mode 100644 index 0000000..ba8d5b9 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MemoryPool/saveString.cpp @@ -0,0 +1,106 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include +#include + +using namespace ArduinoJson::detail; + +static const char* saveString(MemoryPool& pool, const char* s) { + return pool.saveString(adaptString(const_cast(s))); +} + +static const char* saveString(MemoryPool& pool, const char* s, size_t n) { + return pool.saveString(adaptString(s, n)); +} + +TEST_CASE("MemoryPool::saveString()") { + char buffer[32]; + MemoryPool pool(buffer, 32); + + SECTION("Duplicates different strings") { + const char* a = saveString(pool, "hello"); + const char* b = saveString(pool, "world"); + REQUIRE(a != b); + REQUIRE(pool.size() == 6 + 6); + } + + SECTION("Deduplicates identical strings") { + const char* a = saveString(pool, "hello"); + const char* b = saveString(pool, "hello"); + REQUIRE(a == b); + REQUIRE(pool.size() == 6); + } + + SECTION("Deduplicates identical strings that contain NUL") { + const char* a = saveString(pool, "hello\0world", 11); + const char* b = saveString(pool, "hello\0world", 11); + REQUIRE(a == b); + REQUIRE(pool.size() == 12); + } + + SECTION("Reuse part of a string if it ends with NUL") { + const char* a = saveString(pool, "hello\0world", 11); + const char* b = saveString(pool, "hello"); + REQUIRE(a == b); + REQUIRE(pool.size() == 12); + } + + SECTION("Don't stop on first NUL") { + const char* a = saveString(pool, "hello"); + const char* b = saveString(pool, "hello\0world", 11); + REQUIRE(a != b); + REQUIRE(pool.size() == 18); + } + + SECTION("Returns NULL when full") { + REQUIRE(pool.capacity() == 32); + + const void* p1 = saveString(pool, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); + REQUIRE(p1 != 0); + REQUIRE(pool.size() == 32); + + const void* p2 = saveString(pool, "b"); + REQUIRE(p2 == 0); + } + + SECTION("Returns NULL when pool is too small") { + const void* p = saveString(pool, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); + REQUIRE(0 == p); + } + + SECTION("Returns NULL when buffer is NULL") { + MemoryPool pool2(0, 32); + REQUIRE(0 == saveString(pool2, "a")); + } + + SECTION("Returns NULL when capacity is 0") { + MemoryPool pool2(buffer, 0); + REQUIRE(0 == saveString(pool2, "a")); + } + + SECTION("Returns same address after clear()") { + const void* a = saveString(pool, "hello"); + pool.clear(); + const void* b = saveString(pool, "world"); + + REQUIRE(a == b); + } + + SECTION("Can use full capacity when fresh") { + const void* a = saveString(pool, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); + + REQUIRE(a != 0); + } + + SECTION("Can use full capacity after clear") { + saveString(pool, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); + pool.clear(); + + const void* a = saveString(pool, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); + + REQUIRE(a != 0); + } +} diff --git a/libraries/ArduinoJson/extras/tests/MemoryPool/size.cpp b/libraries/ArduinoJson/extras/tests/MemoryPool/size.cpp new file mode 100644 index 0000000..057f4ab --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MemoryPool/size.cpp @@ -0,0 +1,36 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +using namespace ArduinoJson::detail; + +TEST_CASE("MemoryPool::capacity()") { + char buffer[4096]; + const size_t capacity = 64; + MemoryPool pool(buffer, capacity); + REQUIRE(capacity == pool.capacity()); +} + +TEST_CASE("MemoryPool::size()") { + char buffer[4096]; + MemoryPool pool(buffer, sizeof(buffer)); + + SECTION("Initial size is 0") { + REQUIRE(0 == pool.size()); + } + + SECTION("Doesn't grow when memory pool is full") { + const size_t variantCount = sizeof(buffer) / sizeof(VariantSlot); + + for (size_t i = 0; i < variantCount; i++) + pool.allocVariant(); + size_t size = pool.size(); + + pool.allocVariant(); + + REQUIRE(size == pool.size()); + } +} diff --git a/libraries/ArduinoJson/extras/tests/Misc/CMakeLists.txt b/libraries/ArduinoJson/extras/tests/Misc/CMakeLists.txt new file mode 100644 index 0000000..5655a08 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Misc/CMakeLists.txt @@ -0,0 +1,29 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2023, Benoit BLANCHON +# MIT License + +add_executable(MiscTests + arithmeticCompare.cpp + conflicts.cpp + FloatParts.cpp + JsonString.cpp + NoArduinoHeader.cpp + printable.cpp + Readers.cpp + StringAdapters.cpp + StringWriter.cpp + TypeTraits.cpp + unsigned_char.cpp + Utf16.cpp + Utf8.cpp + version.cpp +) + +set_target_properties(MiscTests PROPERTIES UNITY_BUILD OFF) + +add_test(Misc MiscTests) + +set_tests_properties(Misc + PROPERTIES + LABELS "Catch" +) diff --git a/libraries/ArduinoJson/extras/tests/Misc/FloatParts.cpp b/libraries/ArduinoJson/extras/tests/Misc/FloatParts.cpp new file mode 100644 index 0000000..8e3d82e --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Misc/FloatParts.cpp @@ -0,0 +1,44 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +using namespace ArduinoJson::detail; + +TEST_CASE("FloatParts") { + SECTION("1.7976931348623157E+308") { + FloatParts parts(1.7976931348623157E+308); + REQUIRE(parts.integral == 1); + REQUIRE(parts.decimal == 797693135); + REQUIRE(parts.decimalPlaces == 9); + REQUIRE(parts.exponent == 308); + } + + SECTION("4.94065645841247e-324") { + FloatParts parts(4.94065645841247e-324); + REQUIRE(parts.integral == 4); + REQUIRE(parts.decimal == 940656458); + REQUIRE(parts.decimalPlaces == 9); + REQUIRE(parts.exponent == -324); + } +} + +TEST_CASE("FloatParts") { + SECTION("3.4E+38") { + FloatParts parts(3.4E+38f); + REQUIRE(parts.integral == 3); + REQUIRE(parts.decimal == 4); + REQUIRE(parts.decimalPlaces == 1); + REQUIRE(parts.exponent == 38); + } + + SECTION("1.17549435e−38") { + FloatParts parts(1.17549435e-38f); + REQUIRE(parts.integral == 1); + REQUIRE(parts.decimal == 175494); + REQUIRE(parts.decimalPlaces == 6); + REQUIRE(parts.exponent == -38); + } +} diff --git a/libraries/ArduinoJson/extras/tests/Misc/JsonString.cpp b/libraries/ArduinoJson/extras/tests/Misc/JsonString.cpp new file mode 100644 index 0000000..c3dca17 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Misc/JsonString.cpp @@ -0,0 +1,103 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +#include + +TEST_CASE("JsonString") { + SECTION("Default constructor creates a null JsonString") { + JsonString s; + + CHECK(s.isNull() == true); + CHECK(s.c_str() == 0); + CHECK(s.isLinked() == true); + CHECK(s == JsonString()); + CHECK(s != ""); + } + + SECTION("Null converts to false") { + JsonString s; + + CHECK(bool(s) == false); + } + + SECTION("Empty string converts to true") { + JsonString s(""); + + CHECK(bool(s) == true); + } + + SECTION("Non-empty string converts to true") { + JsonString s(""); + + CHECK(bool(s) == true); + } + + SECTION("Null strings equals each others") { + JsonString a, b; + + CHECK(a == b); + CHECK_FALSE(a != b); + } + + SECTION("Null and empty strings differ") { + JsonString a, b(""); + + CHECK_FALSE(a == b); + CHECK(a != b); + + CHECK_FALSE(b == a); + CHECK(b != a); + } + + SECTION("Null and non-empty strings differ") { + JsonString a, b("hello"); + + CHECK_FALSE(a == b); + CHECK(a != b); + + CHECK_FALSE(b == a); + CHECK(b != a); + } + + SECTION("Compare different strings") { + JsonString a("hello"), b("world"); + + CHECK_FALSE(a == b); + CHECK(a != b); + } + + SECTION("Compare identical by pointer") { + JsonString a("hello"), b("hello"); + + CHECK(a == b); + CHECK_FALSE(a != b); + } + + SECTION("Compare identical by value") { + char s1[] = "hello"; + char s2[] = "hello"; + JsonString a(s1), b(s2); + + CHECK(a == b); + CHECK_FALSE(a != b); + } + + SECTION("std::stream") { + std::stringstream ss; + ss << JsonString("hello world!"); + CHECK(ss.str() == "hello world!"); + } + + SECTION("Construct with a size") { + JsonString s("hello world", 5); + + CHECK(s.size() == 5); + CHECK(s.isLinked() == true); + CHECK(s == "hello"); + CHECK(s != "hello world"); + } +} diff --git a/libraries/ArduinoJson/extras/tests/Misc/NoArduinoHeader.cpp b/libraries/ArduinoJson/extras/tests/Misc/NoArduinoHeader.cpp new file mode 100644 index 0000000..4b0218b --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Misc/NoArduinoHeader.cpp @@ -0,0 +1,20 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#define ARDUINO 1 +#define ARDUINOJSON_ENABLE_PROGMEM 0 +#define ARDUINOJSON_ENABLE_ARDUINO_STRING 0 +#define ARDUINOJSON_ENABLE_ARDUINO_STREAM 0 +#define ARDUINOJSON_ENABLE_ARDUINO_PRINT 0 +#include + +#include + +TEST_CASE("Arduino.h") { +#ifdef ARDUINO_H_INCLUDED + FAIL("Arduino.h should not be included"); +#else + INFO("Arduino.h not included"); +#endif +} diff --git a/libraries/ArduinoJson/extras/tests/Misc/Readers.cpp b/libraries/ArduinoJson/extras/tests/Misc/Readers.cpp new file mode 100644 index 0000000..0b8f4d5 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Misc/Readers.cpp @@ -0,0 +1,227 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include +#include + +#include + +using namespace ArduinoJson::detail; + +TEST_CASE("Reader") { + SECTION("read()") { + std::istringstream src("\x01\xFF"); + Reader reader(src); + + REQUIRE(reader.read() == 0x01); + REQUIRE(reader.read() == 0xFF); + REQUIRE(reader.read() == -1); + } + + SECTION("readBytes() all at once") { + std::istringstream src("ABC"); + Reader reader(src); + + char buffer[8] = "abcd"; + REQUIRE(reader.readBytes(buffer, 4) == 3); + + REQUIRE(buffer[0] == 'A'); + REQUIRE(buffer[1] == 'B'); + REQUIRE(buffer[2] == 'C'); + REQUIRE(buffer[3] == 'd'); + } + + SECTION("readBytes() in two parts") { + std::istringstream src("ABCDEF"); + Reader reader(src); + + char buffer[12] = "abcdefg"; + REQUIRE(reader.readBytes(buffer, 4) == 4); + REQUIRE(reader.readBytes(buffer + 4, 4) == 2); + + REQUIRE(buffer[0] == 'A'); + REQUIRE(buffer[1] == 'B'); + REQUIRE(buffer[2] == 'C'); + REQUIRE(buffer[3] == 'D'); + REQUIRE(buffer[4] == 'E'); + REQUIRE(buffer[5] == 'F'); + REQUIRE(buffer[6] == 'g'); + } +} + +TEST_CASE("BoundedReader") { + SECTION("read") { + BoundedReader reader("\x01\xFF", 2); + REQUIRE(reader.read() == 0x01); + REQUIRE(reader.read() == 0xFF); + REQUIRE(reader.read() == -1); + REQUIRE(reader.read() == -1); + } + + SECTION("readBytes() all at once") { + BoundedReader reader("ABCD", 3); + + char buffer[8] = "abcd"; + REQUIRE(reader.readBytes(buffer, 4) == 3); + + REQUIRE(buffer[0] == 'A'); + REQUIRE(buffer[1] == 'B'); + REQUIRE(buffer[2] == 'C'); + REQUIRE(buffer[3] == 'd'); + } + + SECTION("readBytes() in two parts") { + BoundedReader reader("ABCDEF", 6); + + char buffer[8] = "abcdefg"; + REQUIRE(reader.readBytes(buffer, 4) == 4); + REQUIRE(reader.readBytes(buffer + 4, 4) == 2); + + REQUIRE(buffer[0] == 'A'); + REQUIRE(buffer[1] == 'B'); + REQUIRE(buffer[2] == 'C'); + REQUIRE(buffer[3] == 'D'); + REQUIRE(buffer[4] == 'E'); + REQUIRE(buffer[5] == 'F'); + REQUIRE(buffer[6] == 'g'); + } +} + +TEST_CASE("Reader") { + SECTION("read()") { + Reader reader("\x01\xFF\x00\x12"); + REQUIRE(reader.read() == 0x01); + REQUIRE(reader.read() == 0xFF); + REQUIRE(reader.read() == 0); + REQUIRE(reader.read() == 0x12); + } + + SECTION("readBytes() all at once") { + Reader reader("ABCD"); + + char buffer[8] = "abcd"; + REQUIRE(reader.readBytes(buffer, 3) == 3); + + REQUIRE(buffer[0] == 'A'); + REQUIRE(buffer[1] == 'B'); + REQUIRE(buffer[2] == 'C'); + REQUIRE(buffer[3] == 'd'); + } + + SECTION("readBytes() in two parts") { + Reader reader("ABCDEF"); + + char buffer[8] = "abcdefg"; + REQUIRE(reader.readBytes(buffer, 4) == 4); + REQUIRE(reader.readBytes(buffer + 4, 2) == 2); + + REQUIRE(buffer[0] == 'A'); + REQUIRE(buffer[1] == 'B'); + REQUIRE(buffer[2] == 'C'); + REQUIRE(buffer[3] == 'D'); + REQUIRE(buffer[4] == 'E'); + REQUIRE(buffer[5] == 'F'); + REQUIRE(buffer[6] == 'g'); + } +} + +TEST_CASE("IteratorReader") { + SECTION("read()") { + std::string src("\x01\xFF"); + IteratorReader reader(src.begin(), src.end()); + + REQUIRE(reader.read() == 0x01); + REQUIRE(reader.read() == 0xFF); + REQUIRE(reader.read() == -1); + } + + SECTION("readBytes() all at once") { + std::string src("ABC"); + IteratorReader reader(src.begin(), src.end()); + + char buffer[8] = "abcd"; + REQUIRE(reader.readBytes(buffer, 4) == 3); + + REQUIRE(buffer[0] == 'A'); + REQUIRE(buffer[1] == 'B'); + REQUIRE(buffer[2] == 'C'); + REQUIRE(buffer[3] == 'd'); + } + + SECTION("readBytes() in two parts") { + std::string src("ABCDEF"); + IteratorReader reader(src.begin(), src.end()); + + char buffer[12] = "abcdefg"; + REQUIRE(reader.readBytes(buffer, 4) == 4); + REQUIRE(reader.readBytes(buffer + 4, 4) == 2); + + REQUIRE(buffer[0] == 'A'); + REQUIRE(buffer[1] == 'B'); + REQUIRE(buffer[2] == 'C'); + REQUIRE(buffer[3] == 'D'); + REQUIRE(buffer[4] == 'E'); + REQUIRE(buffer[5] == 'F'); + REQUIRE(buffer[6] == 'g'); + } +} + +class StreamStub : public Stream { + public: + StreamStub(const char* s) : stream_(s) {} + + int read() { + return stream_.get(); + } + + size_t readBytes(char* buffer, size_t length) { + stream_.read(buffer, static_cast(length)); + return static_cast(stream_.gcount()); + } + + private: + std::istringstream stream_; +}; + +TEST_CASE("Reader") { + SECTION("read()") { + StreamStub src("\x01\xFF"); + Reader reader(src); + + REQUIRE(reader.read() == 0x01); + REQUIRE(reader.read() == 0xFF); + REQUIRE(reader.read() == -1); + } + + SECTION("readBytes() all at once") { + StreamStub src("ABC"); + Reader reader(src); + + char buffer[8] = "abcd"; + REQUIRE(reader.readBytes(buffer, 4) == 3); + + REQUIRE(buffer[0] == 'A'); + REQUIRE(buffer[1] == 'B'); + REQUIRE(buffer[2] == 'C'); + REQUIRE(buffer[3] == 'd'); + } + + SECTION("readBytes() in two parts") { + StreamStub src("ABCDEF"); + Reader reader(src); + + char buffer[12] = "abcdefg"; + REQUIRE(reader.readBytes(buffer, 4) == 4); + REQUIRE(reader.readBytes(buffer + 4, 4) == 2); + + REQUIRE(buffer[0] == 'A'); + REQUIRE(buffer[1] == 'B'); + REQUIRE(buffer[2] == 'C'); + REQUIRE(buffer[3] == 'D'); + REQUIRE(buffer[4] == 'E'); + REQUIRE(buffer[5] == 'F'); + REQUIRE(buffer[6] == 'g'); + } +} diff --git a/libraries/ArduinoJson/extras/tests/Misc/StringAdapters.cpp b/libraries/ArduinoJson/extras/tests/Misc/StringAdapters.cpp new file mode 100644 index 0000000..1c77e08 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Misc/StringAdapters.cpp @@ -0,0 +1,190 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include + +#include +#include + +#include + +#include "custom_string.hpp" +#include "weird_strcmp.hpp" + +using namespace ArduinoJson::detail; + +TEST_CASE("ZeroTerminatedRamString") { + SECTION("null") { + ZeroTerminatedRamString s = adaptString(static_cast(0)); + + CHECK(s.isNull() == true); + CHECK(s.size() == 0); + } + + SECTION("non-null") { + ZeroTerminatedRamString s = adaptString("bravo"); + + CHECK(s.isNull() == false); + CHECK(s.size() == 5); + } +} + +TEST_CASE("SizedRamString") { + SECTION("null") { + SizedRamString s = adaptString(static_cast(0), 10); + + CHECK(s.isNull() == true); + } + + SECTION("non-null") { + SizedRamString s = adaptString("bravo", 5); + + CHECK(s.isNull() == false); + CHECK(s.size() == 5); + } +} + +TEST_CASE("FlashString") { + SECTION("null") { + FlashString s = adaptString(static_cast(0)); + + CHECK(s.isNull() == true); + CHECK(s.size() == 0); + } + + SECTION("non-null") { + FlashString s = adaptString(F("bravo")); + + CHECK(s.isNull() == false); + CHECK(s.size() == 5); + } +} + +TEST_CASE("std::string") { + std::string orig("bravo"); + SizedRamString s = adaptString(orig); + + CHECK(s.isNull() == false); + CHECK(s.size() == 5); +} + +TEST_CASE("Arduino String") { + ::String orig("bravo"); + SizedRamString s = adaptString(orig); + + CHECK(s.isNull() == false); + CHECK(s.size() == 5); +} + +TEST_CASE("custom_string") { + custom_string orig("bravo"); + SizedRamString s = adaptString(orig); + + CHECK(s.isNull() == false); + CHECK(s.size() == 5); +} + +struct EmptyStruct {}; + +TEST_CASE("IsString") { + CHECK(IsString::value == true); + CHECK(IsString>::value == false); + CHECK(IsString::value == true); + CHECK(IsString::value == true); + CHECK(IsString::value == true); + CHECK(IsString::value == true); + CHECK(IsString<::String>::value == true); + CHECK(IsString<::StringSumHelper>::value == true); + CHECK(IsString::value == false); +} + +TEST_CASE("stringCompare") { + SECTION("ZeroTerminatedRamString vs ZeroTerminatedRamString") { + CHECK(stringCompare(adaptString("bravo"), adaptString("alpha")) > 0); + CHECK(stringCompare(adaptString("bravo"), adaptString("bravo")) == 0); + CHECK(stringCompare(adaptString("bravo"), adaptString("charlie")) < 0); + } + + SECTION("ZeroTerminatedRamString vs SizedRamString") { + CHECK(stringCompare(adaptString("bravo"), adaptString("alpha?", 5)) > 0); + CHECK(stringCompare(adaptString("bravo"), adaptString("bravo?", 4)) > 0); + CHECK(stringCompare(adaptString("bravo"), adaptString("bravo?", 5)) == 0); + CHECK(stringCompare(adaptString("bravo"), adaptString("bravo?", 6)) < 0); + CHECK(stringCompare(adaptString("bravo"), adaptString("charlie?", 7)) < 0); + } + + SECTION("SizedRamString vs SizedRamString") { + // clang-format off + CHECK(stringCompare(adaptString("bravo!", 5), adaptString("alpha?", 5)) > 0); + CHECK(stringCompare(adaptString("bravo!", 5), adaptString("bravo?", 5)) == 0); + CHECK(stringCompare(adaptString("bravo!", 5), adaptString("charlie?", 7)) < 0); + + CHECK(stringCompare(adaptString("bravo!", 5), adaptString("bravo!", 4)) > 0); + CHECK(stringCompare(adaptString("bravo!", 5), adaptString("bravo!", 5)) == 0); + CHECK(stringCompare(adaptString("bravo!", 5), adaptString("bravo!", 6)) < 0); + // clang-format on + } + + SECTION("FlashString vs FlashString") { + // clang-format off + CHECK(stringCompare(adaptString(F("bravo")), adaptString(F("alpha"))) > 0); + CHECK(stringCompare(adaptString(F("bravo")), adaptString(F("bravo"))) == 0); + CHECK(stringCompare(adaptString(F("bravo")), adaptString(F("charlie"))) < 0); + // clang-format on + } + + SECTION("FlashString vs SizedRamString") { + // clang-format off + CHECK(stringCompare(adaptString(F("bravo")), adaptString("alpha?", 5)) > 0); + CHECK(stringCompare(adaptString(F("bravo")), adaptString("bravo?", 5)) == 0); + CHECK(stringCompare(adaptString(F("bravo")), adaptString("charlie?", 7)) < 0); + + CHECK(stringCompare(adaptString(F("bravo")), adaptString("bravo!", 4)) > 0); + CHECK(stringCompare(adaptString(F("bravo")), adaptString("bravo!", 5)) == 0); + CHECK(stringCompare(adaptString(F("bravo")), adaptString("bravo!", 6)) < 0); + // clang-format on + } + + SECTION("ZeroTerminatedRamString vs FlashString") { + // clang-format off + CHECK(stringCompare(adaptString("bravo"), adaptString(F("alpha?"), 5)) > 0); + CHECK(stringCompare(adaptString("bravo"), adaptString(F("bravo?"), 4)) > 0); + CHECK(stringCompare(adaptString("bravo"), adaptString(F("bravo?"), 5)) == 0); + CHECK(stringCompare(adaptString("bravo"), adaptString(F("bravo?"), 6)) < 0); + CHECK(stringCompare(adaptString("bravo"), adaptString(F("charlie?"), 7)) < 0); + // clang-format on + } +} + +TEST_CASE("stringEquals()") { + SECTION("ZeroTerminatedRamString vs ZeroTerminatedRamString") { + CHECK(stringEquals(adaptString("bravo"), adaptString("brav")) == false); + CHECK(stringEquals(adaptString("bravo"), adaptString("bravo")) == true); + CHECK(stringEquals(adaptString("bravo"), adaptString("bravo!")) == false); + } + + SECTION("ZeroTerminatedRamString vs SizedRamString") { + // clang-format off + CHECK(stringEquals(adaptString("bravo"), adaptString("bravo!", 4)) == false); + CHECK(stringEquals(adaptString("bravo"), adaptString("bravo!", 5)) == true); + CHECK(stringEquals(adaptString("bravo"), adaptString("bravo!", 6)) == false); + // clang-format on + } + + SECTION("FlashString vs SizedRamString") { + // clang-format off + CHECK(stringEquals(adaptString(F("bravo")), adaptString("bravo!", 4)) == false); + CHECK(stringEquals(adaptString(F("bravo")), adaptString("bravo!", 5)) == true); + CHECK(stringEquals(adaptString(F("bravo")), adaptString("bravo!", 6)) == false); + // clang-format on + } + + SECTION("SizedRamString vs SizedRamString") { + // clang-format off + CHECK(stringEquals(adaptString("bravo?", 5), adaptString("bravo!", 4)) == false); + CHECK(stringEquals(adaptString("bravo?", 5), adaptString("bravo!", 5)) == true); + CHECK(stringEquals(adaptString("bravo?", 5), adaptString("bravo!", 6)) == false); + // clang-format on + } +} diff --git a/libraries/ArduinoJson/extras/tests/Misc/StringWriter.cpp b/libraries/ArduinoJson/extras/tests/Misc/StringWriter.cpp new file mode 100644 index 0000000..81cb88e --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Misc/StringWriter.cpp @@ -0,0 +1,156 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include + +#define ARDUINOJSON_STRING_BUFFER_SIZE 5 +#include + +#include + +#include "custom_string.hpp" + +using namespace ArduinoJson::detail; + +template +static size_t print(StringWriter& writer, const char* s) { + return writer.write(reinterpret_cast(s), strlen(s)); +} + +template +static size_t print(StringWriter& writer, char c) { + return writer.write(static_cast(c)); +} + +template +void common_tests(StringWriter& writer, const String& output) { + SECTION("InitialState") { + REQUIRE(std::string("") == output); + } + + SECTION("EmptyString") { + REQUIRE(0 == print(writer, "")); + REQUIRE(std::string("") == output); + } + + SECTION("OneString") { + REQUIRE(4 == print(writer, "ABCD")); + REQUIRE(std::string("ABCD") == output); + } + + SECTION("TwoStrings") { + REQUIRE(4 == print(writer, "ABCD")); + REQUIRE(4 == print(writer, "EFGH")); + REQUIRE(std::string("ABCDEFGH") == output); + } +} + +TEST_CASE("StaticStringWriter") { + char output[20] = {0}; + StaticStringWriter writer(output, sizeof(output)); + + common_tests(writer, static_cast(output)); + + SECTION("OverCapacity") { + REQUIRE(20 == print(writer, "ABCDEFGHIJKLMNOPQRSTUVWXYZ")); + REQUIRE(0 == print(writer, "ABC")); + REQUIRE(0 == print(writer, 'D')); + REQUIRE("ABCDEFGHIJKLMNOPQRST" == std::string(output, 20)); + } +} + +TEST_CASE("Writer") { + std::string output; + Writer writer(output); + common_tests(writer, output); +} + +TEST_CASE("Writer") { + ::String output; + Writer<::String> writer(output); + + SECTION("write(char)") { + SECTION("writes to temporary buffer") { + // accumulate in buffer + writer.write('a'); + writer.write('b'); + writer.write('c'); + writer.write('d'); + REQUIRE(output == ""); + + // flush when full + writer.write('e'); + REQUIRE(output == "abcd"); + + // flush on destruction + writer.write('f'); + writer.~Writer(); + REQUIRE(output == "abcdef"); + } + + SECTION("returns 1 on success") { + for (int i = 0; i < ARDUINOJSON_STRING_BUFFER_SIZE; i++) { + REQUIRE(writer.write('x') == 1); + } + } + + SECTION("returns 0 on error") { + output.limitCapacityTo(1); + + REQUIRE(writer.write('a') == 1); + REQUIRE(writer.write('b') == 1); + REQUIRE(writer.write('c') == 1); + REQUIRE(writer.write('d') == 1); + REQUIRE(writer.write('e') == 0); + REQUIRE(writer.write('f') == 0); + } + } + + SECTION("write(char*, size_t)") { + SECTION("empty string") { + REQUIRE(0 == print(writer, "")); + writer.flush(); + REQUIRE(output == ""); + } + + SECTION("writes to temporary buffer") { + // accumulate in buffer + print(writer, "abc"); + REQUIRE(output == ""); + + // flush when full, and continue to accumulate + print(writer, "de"); + REQUIRE(output == "abcd"); + + // flush on destruction + writer.~Writer(); + REQUIRE(output == "abcde"); + } + } +} + +TEST_CASE("Writer") { + custom_string output; + Writer writer(output); + + REQUIRE(4 == print(writer, "ABCD")); + REQUIRE("ABCD" == output); +} + +TEST_CASE("serializeJson(doc, String)") { + StaticJsonDocument<1024> doc; + doc["hello"] = "world"; + ::String output; + + SECTION("sufficient capacity") { + serializeJson(doc, output); + REQUIRE(output == "{\"hello\":\"world\"}"); + } + + SECTION("unsufficient capacity") { // issue #1561 + output.limitCapacityTo(10); + serializeJson(doc, output); + REQUIRE(output == "{\"hello\""); + } +} diff --git a/libraries/ArduinoJson/extras/tests/Misc/TypeTraits.cpp b/libraries/ArduinoJson/extras/tests/Misc/TypeTraits.cpp new file mode 100644 index 0000000..10b6168 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Misc/TypeTraits.cpp @@ -0,0 +1,216 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +#include + +using namespace ArduinoJson::detail; + +class EmptyClass {}; +enum EmptyEnum {}; + +TEST_CASE("Polyfills/type_traits") { + SECTION("is_base_of") { + REQUIRE_FALSE( + static_cast(is_base_of::value)); + REQUIRE( + static_cast(is_base_of::value)); + } + + SECTION("is_array") { + REQUIRE_FALSE(is_array::value); + REQUIRE(is_array::value); + REQUIRE(is_array::value); + } + + SECTION("is_const") { + CHECK(is_const::value == false); + CHECK(is_const::value == true); + } + + SECTION("is_integral") { + CHECK(is_integral::value == false); + CHECK(is_integral::value == false); + CHECK(is_integral::value == false); + CHECK(is_integral::value == false); + CHECK(is_integral::value == false); + CHECK(is_integral::value == false); + CHECK(is_integral::value == false); + CHECK(is_integral::value == false); + + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + CHECK(is_integral::value == true); + + CHECK(is_integral::value == true); + } + + SECTION("is_signed") { + CHECK(is_signed::value == true); + CHECK(is_signed::value == true); + CHECK(is_signed::value == true); + CHECK(is_signed::value == true); + CHECK(is_signed::value == true); + CHECK(is_signed::value == true); + CHECK(is_signed::value == true); + CHECK(is_signed::value == false); + + CHECK(is_signed::value == true); + CHECK(is_signed::value == true); + CHECK(is_signed::value == true); + CHECK(is_signed::value == true); + CHECK(is_signed::value == true); + CHECK(is_signed::value == true); + CHECK(is_signed::value == true); + CHECK(is_signed::value == false); + + CHECK(is_signed::value == true); + CHECK(is_signed::value == true); + CHECK(is_signed::value == true); + CHECK(is_signed::value == true); + CHECK(is_signed::value == true); + CHECK(is_signed::value == true); + CHECK(is_signed::value == true); + CHECK(is_signed::value == false); + + CHECK(is_signed::value == true); + CHECK(is_signed::value == true); + CHECK(is_signed::value == true); + CHECK(is_signed::value == true); + CHECK(is_signed::value == true); + CHECK(is_signed::value == true); + CHECK(is_signed::value == true); + CHECK(is_signed::value == false); + } + + SECTION("is_unsigned") { + CHECK(is_unsigned::value == true); + CHECK(is_unsigned::value == true); + CHECK(is_unsigned::value == true); + CHECK(is_unsigned::value == true); + CHECK(is_unsigned::value == true); + CHECK(is_unsigned::value == false); + CHECK(is_unsigned::value == false); + CHECK(is_unsigned::value == false); + + CHECK(is_unsigned::value == true); + CHECK(is_unsigned::value == true); + CHECK(is_unsigned::value == true); + CHECK(is_unsigned::value == true); + CHECK(is_unsigned::value == true); + CHECK(is_unsigned::value == false); + CHECK(is_unsigned::value == false); + CHECK(is_unsigned::value == false); + + CHECK(is_unsigned::value == true); + CHECK(is_unsigned::value == true); + CHECK(is_unsigned::value == true); + CHECK(is_unsigned::value == true); + CHECK(is_unsigned::value == true); + CHECK(is_unsigned::value == false); + CHECK(is_unsigned::value == false); + CHECK(is_unsigned::value == false); + + CHECK(is_unsigned::value == true); + CHECK(is_unsigned::value == true); + CHECK(is_unsigned::value == true); + CHECK(is_unsigned::value == true); + CHECK(is_unsigned::value == true); + CHECK(is_unsigned::value == false); + CHECK(is_unsigned::value == false); + CHECK(is_unsigned::value == false); + } + + SECTION("is_floating_point") { + CHECK(is_floating_point::value == false); + CHECK(is_floating_point::value == true); + CHECK(is_floating_point::value == true); + CHECK(is_floating_point::value == true); + CHECK(is_floating_point::value == true); + CHECK(is_floating_point::value == true); + CHECK(is_floating_point::value == true); + CHECK(is_floating_point::value == true); + CHECK(is_floating_point::value == true); + } + + SECTION("is_convertible") { + CHECK(is_convertible::value == true); + CHECK(is_convertible::value == true); + CHECK(is_convertible::value == true); + CHECK(is_convertible::value == false); + CHECK(is_convertible::value == false); + + CHECK(is_convertible::value == + false); + CHECK(is_convertible::value == false); + CHECK(is_convertible::value == true); + CHECK(is_convertible::value == true); + CHECK(is_convertible::value == true); + CHECK(is_convertible, JsonVariantConst>::value == + true); + CHECK(is_convertible::value == true); + CHECK(is_convertible::value == true); + CHECK(is_convertible, + JsonVariantConst>::value == true); + CHECK(is_convertible::value == true); + CHECK(is_convertible::value == true); + CHECK(is_convertible, JsonVariantConst>::value == + true); + } + + SECTION("is_class") { + CHECK(is_class::value == false); + CHECK(is_class::value == false); + CHECK(is_class::value == false); + CHECK(is_class::value == true); + } + + SECTION("is_enum") { + CHECK(is_enum::value == false); + CHECK(is_enum::value == true); + CHECK(is_enum::value == false); + CHECK(is_enum::value == false); + CHECK(is_enum::value == false); + CHECK(is_enum::value == false); + } +} diff --git a/libraries/ArduinoJson/extras/tests/Misc/Utf16.cpp b/libraries/ArduinoJson/extras/tests/Misc/Utf16.cpp new file mode 100644 index 0000000..3a59591 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Misc/Utf16.cpp @@ -0,0 +1,68 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +using namespace ArduinoJson::detail; + +static void testUtf16Codepoint(uint16_t codeunit, uint32_t expectedCodepoint) { + Utf16::Codepoint cp; + REQUIRE(cp.append(codeunit) == true); + REQUIRE(cp.value() == expectedCodepoint); +} + +static void testUtf16Codepoint(uint16_t codeunit1, uint16_t codeunit2, + uint32_t expectedCodepoint) { + Utf16::Codepoint cp; + REQUIRE(cp.append(codeunit1) == false); + REQUIRE(cp.append(codeunit2) == true); + REQUIRE(cp.value() == expectedCodepoint); +} + +TEST_CASE("Utf16::Codepoint()") { + SECTION("U+0000") { + testUtf16Codepoint(0x0000, 0x000000); + } + + SECTION("U+0001") { + testUtf16Codepoint(0x0001, 0x000001); + } + + SECTION("U+D7FF") { + testUtf16Codepoint(0xD7FF, 0x00D7FF); + } + + SECTION("U+E000") { + testUtf16Codepoint(0xE000, 0x00E000); + } + + SECTION("U+FFFF") { + testUtf16Codepoint(0xFFFF, 0x00FFFF); + } + + SECTION("U+010000") { + testUtf16Codepoint(0xD800, 0xDC00, 0x010000); + } + + SECTION("U+010001") { + testUtf16Codepoint(0xD800, 0xDC01, 0x010001); + } + + SECTION("U+0103FF") { + testUtf16Codepoint(0xD800, 0xDFFF, 0x0103FF); + } + + SECTION("U+010400") { + testUtf16Codepoint(0xD801, 0xDC00, 0x010400); + } + + SECTION("U+010400") { + testUtf16Codepoint(0xDBFF, 0xDC00, 0x10FC00); + } + + SECTION("U+10FFFF") { + testUtf16Codepoint(0xDBFF, 0xDFFF, 0x10FFFF); + } +} diff --git a/libraries/ArduinoJson/extras/tests/Misc/Utf8.cpp b/libraries/ArduinoJson/extras/tests/Misc/Utf8.cpp new file mode 100644 index 0000000..0c62033 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Misc/Utf8.cpp @@ -0,0 +1,60 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +#include + +using namespace ArduinoJson::detail; + +static void testCodepoint(uint32_t codepoint, std::string expected) { + char buffer[4096]; + MemoryPool pool(buffer, 4096); + StringCopier str(&pool); + str.startString(); + + CAPTURE(codepoint); + Utf8::encodeCodepoint(codepoint, str); + + REQUIRE(str.str().c_str() == expected); +} + +TEST_CASE("Utf8::encodeCodepoint()") { + SECTION("U+0000") { + testCodepoint(0x0000, ""); + } + + SECTION("U+0001") { + testCodepoint(0x0001, "\x01"); + } + + SECTION("U+007F") { + testCodepoint(0x007F, "\x7f"); + } + + SECTION("U+0080") { + testCodepoint(0x0080, "\xc2\x80"); + } + + SECTION("U+07FF") { + testCodepoint(0x07FF, "\xdf\xbf"); + } + + SECTION("U+0800") { + testCodepoint(0x0800, "\xe0\xa0\x80"); + } + + SECTION("U+FFFF") { + testCodepoint(0xFFFF, "\xef\xbf\xbf"); + } + + SECTION("U+10000") { + testCodepoint(0x10000, "\xf0\x90\x80\x80"); + } + + SECTION("U+10FFFF") { + testCodepoint(0x10FFFF, "\xf4\x8f\xbf\xbf"); + } +} diff --git a/libraries/ArduinoJson/extras/tests/Misc/arithmeticCompare.cpp b/libraries/ArduinoJson/extras/tests/Misc/arithmeticCompare.cpp new file mode 100644 index 0000000..2d51754 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Misc/arithmeticCompare.cpp @@ -0,0 +1,97 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +using namespace ArduinoJson::detail; + +TEST_CASE("arithmeticCompare()") { + SECTION("int vs uint8_t") { + CHECK(arithmeticCompare(256, 1) == COMPARE_RESULT_GREATER); + CHECK(arithmeticCompare(41, 42) == COMPARE_RESULT_LESS); + CHECK(arithmeticCompare(42, 42) == COMPARE_RESULT_EQUAL); + CHECK(arithmeticCompare(43, 42) == COMPARE_RESULT_GREATER); + } + + SECTION("unsigned vs int") { + CHECK(arithmeticCompare(0, -1) == COMPARE_RESULT_GREATER); + CHECK(arithmeticCompare(42, 41) == COMPARE_RESULT_GREATER); + CHECK(arithmeticCompare(42, 42) == COMPARE_RESULT_EQUAL); + CHECK(arithmeticCompare(42, 43) == COMPARE_RESULT_LESS); + } + + SECTION("float vs int") { + CHECK(arithmeticCompare(42, 41) == COMPARE_RESULT_GREATER); + CHECK(arithmeticCompare(42, 42) == COMPARE_RESULT_EQUAL); + CHECK(arithmeticCompare(42, 43) == COMPARE_RESULT_LESS); + } + + SECTION("int vs unsigned") { + CHECK(arithmeticCompare(-1, 0) == COMPARE_RESULT_LESS); + CHECK(arithmeticCompare(0, 0) == COMPARE_RESULT_EQUAL); + CHECK(arithmeticCompare(1, 0) == COMPARE_RESULT_GREATER); + CHECK(arithmeticCompare(42, 41) == COMPARE_RESULT_GREATER); + CHECK(arithmeticCompare(42, 42) == COMPARE_RESULT_EQUAL); + CHECK(arithmeticCompare(42, 43) == COMPARE_RESULT_LESS); + } + + SECTION("unsigned vs unsigned") { + CHECK(arithmeticCompare(42, 41) == + COMPARE_RESULT_GREATER); + CHECK(arithmeticCompare(42, 42) == + COMPARE_RESULT_EQUAL); + CHECK(arithmeticCompare(42, 43) == COMPARE_RESULT_LESS); + } + + SECTION("bool vs bool") { + CHECK(arithmeticCompare(false, false) == COMPARE_RESULT_EQUAL); + CHECK(arithmeticCompare(true, true) == COMPARE_RESULT_EQUAL); + CHECK(arithmeticCompare(false, true) == COMPARE_RESULT_LESS); + CHECK(arithmeticCompare(true, false) == COMPARE_RESULT_GREATER); + } + + SECTION("bool vs int") { + CHECK(arithmeticCompare(false, -1) == COMPARE_RESULT_GREATER); + CHECK(arithmeticCompare(false, 0) == COMPARE_RESULT_EQUAL); + CHECK(arithmeticCompare(false, 1) == COMPARE_RESULT_LESS); + CHECK(arithmeticCompare(true, 0) == COMPARE_RESULT_GREATER); + CHECK(arithmeticCompare(true, 1) == COMPARE_RESULT_EQUAL); + CHECK(arithmeticCompare(true, 2) == COMPARE_RESULT_LESS); + } + + SECTION("bool vs int") { + CHECK(arithmeticCompare(0, false) == COMPARE_RESULT_EQUAL); + CHECK(arithmeticCompare(1, true) == COMPARE_RESULT_EQUAL); + CHECK(arithmeticCompare(1, false) == COMPARE_RESULT_GREATER); + CHECK(arithmeticCompare(0, true) == COMPARE_RESULT_LESS); + } +} + +TEST_CASE("arithmeticCompareNegateLeft()") { + SECTION("unsigned vs int") { + CHECK(arithmeticCompareNegateLeft(0, 1) == COMPARE_RESULT_LESS); + CHECK(arithmeticCompareNegateLeft(42, -41) == COMPARE_RESULT_LESS); + CHECK(arithmeticCompareNegateLeft(42, -42) == COMPARE_RESULT_EQUAL); + CHECK(arithmeticCompareNegateLeft(42, -43) == COMPARE_RESULT_GREATER); + } + + SECTION("unsigned vs unsigned") { + CHECK(arithmeticCompareNegateLeft(42, 42) == COMPARE_RESULT_LESS); + } +} + +TEST_CASE("arithmeticCompareNegateRight()") { + SECTION("int vs unsigned") { + CHECK(arithmeticCompareNegateRight(1, 0) == COMPARE_RESULT_GREATER); + CHECK(arithmeticCompareNegateRight(-41, 42) == COMPARE_RESULT_GREATER); + CHECK(arithmeticCompareNegateRight(-42, 42) == COMPARE_RESULT_EQUAL); + CHECK(arithmeticCompareNegateRight(-43, 42) == COMPARE_RESULT_LESS); + } + + SECTION("unsigned vs unsigned") { + CHECK(arithmeticCompareNegateRight(42, 42) == + COMPARE_RESULT_GREATER); + } +} diff --git a/libraries/ArduinoJson/extras/tests/Misc/conflicts.cpp b/libraries/ArduinoJson/extras/tests/Misc/conflicts.cpp new file mode 100644 index 0000000..2e33ea1 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Misc/conflicts.cpp @@ -0,0 +1,59 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +// Include any header that might use the conflicting macros +#include +#include +#include + +// All cores +#define bit() +#define constrain() +#define DEFAULT +#define DISABLED +#define HIGH +#define INPUT +#define LOW +#define max() +#define min() +#define OUTPUT +#define round() +#define sq() +#define word() +#define bitRead() +#define bitSet() +#define bitClear() +#define bitWrite() +#define interrupts() +#define lowByte() +#define highByte() +#define DEC +#define HEX +#define OCT +#define BIN +#define cbi() +#define sbi() + +// ESP8266 +#define _max() +#define _min() + +// Realtek Ameba +#define isdigit(c) (((c) >= '0') && ((c) <= '9')) +#define isprint(c) +#define isxdigit(c) +#define isspace(c) +#define isupper(c) +#define islower(c) +#define isalpha(c) + +// issue #839 +#define BLOCKSIZE +#define CAPACITY + +// issue #1905 +#define _current + +// catch.hpp mutes several warnings, this file also allows to detect them +#include "ArduinoJson.h" diff --git a/libraries/ArduinoJson/extras/tests/Misc/custom_string.hpp b/libraries/ArduinoJson/extras/tests/Misc/custom_string.hpp new file mode 100644 index 0000000..4a6a5a7 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Misc/custom_string.hpp @@ -0,0 +1,12 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#pragma once + +#include + +struct custom_char_traits : std::char_traits {}; +struct custom_allocator : std::allocator {}; +typedef std::basic_string + custom_string; diff --git a/libraries/ArduinoJson/extras/tests/Misc/printable.cpp b/libraries/ArduinoJson/extras/tests/Misc/printable.cpp new file mode 100644 index 0000000..09c23ad --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Misc/printable.cpp @@ -0,0 +1,144 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +#define ARDUINOJSON_ENABLE_ARDUINO_STREAM 1 +#include + +struct PrintOneCharacterAtATime { + static size_t printStringTo(const std::string& s, Print& p) { + size_t result = 0; + for (std::string::const_iterator it = s.begin(); it != s.end(); ++it) { + size_t n = p.write(uint8_t(*it)); + if (n == 0) + break; + result += n; + } + return result; + } +}; + +struct PrintAllAtOnce { + static size_t printStringTo(const std::string& s, Print& p) { + return p.write(s.data(), s.size()); + } +}; + +template +struct PrintableString : public Printable { + PrintableString(const char* s) : str_(s), total_(0) {} + + virtual size_t printTo(Print& p) const { + size_t result = PrintPolicy::printStringTo(str_, p); + total_ += result; + return result; + } + + size_t totalBytesWritten() const { + return total_; + } + + private: + std::string str_; + mutable size_t total_; +}; + +TEST_CASE("Printable") { + SECTION("Doesn't overflow") { + StaticJsonDocument<8> doc; + const char* value = "example"; // == 7 chars + + doc.set(666); // to make sure we override the value + + SECTION("Via Print::write(char)") { + PrintableString printable(value); + CHECK(doc.set(printable) == true); + CHECK(doc.as() == value); + CHECK(printable.totalBytesWritten() == 7); + CHECK(doc.overflowed() == false); + CHECK(doc.memoryUsage() == 8); + CHECK(doc.as().memoryUsage() == 8); + } + + SECTION("Via Print::write(const char* size_t)") { + PrintableString printable(value); + CHECK(doc.set(printable) == true); + CHECK(doc.as() == value); + CHECK(printable.totalBytesWritten() == 7); + CHECK(doc.overflowed() == false); + CHECK(doc.memoryUsage() == 8); + CHECK(doc.as().memoryUsage() == 8); + } + } + + SECTION("Overflows early") { + StaticJsonDocument<8> doc; + const char* value = "hello world"; // > 8 chars + + doc.set(666); // to make sure we override the value + + SECTION("Via Print::write(char)") { + PrintableString printable(value); + CHECK(doc.set(printable) == false); + CHECK(doc.isNull()); + CHECK(printable.totalBytesWritten() == 8); + CHECK(doc.overflowed() == true); + CHECK(doc.memoryUsage() == 0); + } + + SECTION("Via Print::write(const char*, size_t)") { + PrintableString printable(value); + CHECK(doc.set(printable) == false); + CHECK(doc.isNull()); + CHECK(printable.totalBytesWritten() == 0); + CHECK(doc.overflowed() == true); + CHECK(doc.memoryUsage() == 0); + } + } + + SECTION("Overflows adding terminator") { + StaticJsonDocument<8> doc; + const char* value = "overflow"; // == 8 chars + + doc.set(666); // to make sure we override the value + + SECTION("Via Print::write(char)") { + PrintableString printable(value); + CHECK(doc.set(printable) == false); + CHECK(doc.isNull()); + CHECK(printable.totalBytesWritten() == 8); + CHECK(doc.overflowed() == true); + CHECK(doc.memoryUsage() == 0); + } + + SECTION("Via Print::write(const char*, size_t)") { + PrintableString printable(value); + CHECK(doc.set(printable) == false); + CHECK(doc.isNull()); + CHECK(printable.totalBytesWritten() == 0); + CHECK(doc.overflowed() == true); + CHECK(doc.memoryUsage() == 0); + } + } + + SECTION("Null variant") { + JsonVariant var; + PrintableString printable = "Hello World!"; + CHECK(var.set(printable) == false); + CHECK(var.isNull()); + CHECK(printable.totalBytesWritten() == 0); + } + + SECTION("String deduplication") { + StaticJsonDocument<128> doc; + doc.add(PrintableString("Hello World!")); + doc.add(PrintableString("Hello World!")); + REQUIRE(doc.size() == 2); + CHECK(doc[0] == "Hello World!"); + CHECK(doc[1] == "Hello World!"); + CHECK(doc.memoryUsage() == JSON_ARRAY_SIZE(2) + 13); + } +} diff --git a/libraries/ArduinoJson/extras/tests/Misc/unsigned_char.cpp b/libraries/ArduinoJson/extras/tests/Misc/unsigned_char.cpp new file mode 100644 index 0000000..d3ee492 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Misc/unsigned_char.cpp @@ -0,0 +1,271 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +#if defined(__clang__) +# define CONFLICTS_WITH_BUILTIN_OPERATOR +#endif + +TEST_CASE("unsigned char[]") { + SECTION("deserializeJson()") { + unsigned char input[] = "{\"a\":42}"; + + StaticJsonDocument doc; + DeserializationError err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("deserializeMsgPack()") { + unsigned char input[] = "\xDE\x00\x01\xA5Hello\xA5world"; + + StaticJsonDocument doc; + DeserializationError err = deserializeMsgPack(doc, input); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("serializeMsgPack(unsigned char[])") { + unsigned char buffer[32]; + StaticJsonDocument doc; + doc["hello"] = "world"; + + size_t n = serializeMsgPack(doc, buffer); + + REQUIRE(n == 13); + REQUIRE(memcmp(buffer, "\x81\xA5hello\xA5world", 13) == 0); + } + + SECTION("serializeMsgPack(unsigned char*)") { + unsigned char buffer[32]; + StaticJsonDocument doc; + doc["hello"] = "world"; + + size_t n = serializeMsgPack(doc, buffer, sizeof(buffer)); + + REQUIRE(n == 13); + REQUIRE(memcmp(buffer, "\x81\xA5hello\xA5world", 13) == 0); + } + + SECTION("serializeJson(unsigned char[])") { + unsigned char buffer[32]; + StaticJsonDocument doc; + doc["hello"] = "world"; + + size_t n = serializeJson(doc, buffer); + + REQUIRE(n == 17); + REQUIRE(memcmp(buffer, "{\"hello\":\"world\"}", n) == 0); + } + + SECTION("serializeJson(unsigned char*)") { + unsigned char buffer[32]; + StaticJsonDocument doc; + doc["hello"] = "world"; + + size_t n = serializeJson(doc, buffer, sizeof(buffer)); + + REQUIRE(n == 17); + REQUIRE(memcmp(buffer, "{\"hello\":\"world\"}", n) == 0); + } + + SECTION("serializeJsonPretty(unsigned char[])") { + unsigned char buffer[32]; + StaticJsonDocument doc; + doc["hello"] = "world"; + + size_t n = serializeJsonPretty(doc, buffer); + + REQUIRE(n == 24); + } + + SECTION("serializeJsonPretty(unsigned char*)") { + unsigned char buffer[32]; + StaticJsonDocument doc; + doc["hello"] = "world"; + + size_t n = serializeJsonPretty(doc, buffer, sizeof(buffer)); + + REQUIRE(n == 24); + } + + SECTION("JsonVariant") { + DynamicJsonDocument doc(4096); + + SECTION("set") { + unsigned char value[] = "42"; + + JsonVariant variant = doc.to(); + variant.set(value); + + REQUIRE(42 == variant.as()); + } + +#ifndef CONFLICTS_WITH_BUILTIN_OPERATOR + SECTION("operator[]") { + unsigned char key[] = "hello"; + + deserializeJson(doc, "{\"hello\":\"world\"}"); + JsonVariant variant = doc.as(); + + REQUIRE(std::string("world") == variant[key]); + } +#endif + +#ifndef CONFLICTS_WITH_BUILTIN_OPERATOR + SECTION("operator[] const") { + unsigned char key[] = "hello"; + + deserializeJson(doc, "{\"hello\":\"world\"}"); + const JsonVariant variant = doc.as(); + + REQUIRE(std::string("world") == variant[key]); + } +#endif + + SECTION("operator==") { + unsigned char comparand[] = "hello"; + + JsonVariant variant = doc.to(); + variant.set("hello"); + + REQUIRE(comparand == variant); + REQUIRE(variant == comparand); + REQUIRE_FALSE(comparand != variant); + REQUIRE_FALSE(variant != comparand); + } + + SECTION("operator!=") { + unsigned char comparand[] = "hello"; + + JsonVariant variant = doc.to(); + variant.set("world"); + + REQUIRE(comparand != variant); + REQUIRE(variant != comparand); + REQUIRE_FALSE(comparand == variant); + REQUIRE_FALSE(variant == comparand); + } + } + + SECTION("JsonObject") { +#ifndef CONFLICTS_WITH_BUILTIN_OPERATOR + SECTION("operator[]") { + unsigned char key[] = "hello"; + + DynamicJsonDocument doc(4096); + JsonObject obj = doc.to(); + obj[key] = "world"; + + REQUIRE(std::string("world") == obj["hello"]); + } + + SECTION("JsonObject::operator[] const") { + unsigned char key[] = "hello"; + + DynamicJsonDocument doc(4096); + deserializeJson(doc, "{\"hello\":\"world\"}"); + + JsonObject obj = doc.as(); + REQUIRE(std::string("world") == obj[key]); + } +#endif + + SECTION("containsKey()") { + unsigned char key[] = "hello"; + + DynamicJsonDocument doc(4096); + deserializeJson(doc, "{\"hello\":\"world\"}"); + JsonObject obj = doc.as(); + REQUIRE(true == obj.containsKey(key)); + } + + SECTION("remove()") { + unsigned char key[] = "hello"; + + DynamicJsonDocument doc(4096); + deserializeJson(doc, "{\"hello\":\"world\"}"); + JsonObject obj = doc.as(); + obj.remove(key); + + REQUIRE(0 == obj.size()); + } + + SECTION("createNestedArray()") { + unsigned char key[] = "hello"; + + DynamicJsonDocument doc(4096); + JsonObject obj = doc.to(); + obj.createNestedArray(key); + } + + SECTION("createNestedObject()") { + unsigned char key[] = "hello"; + + DynamicJsonDocument doc(4096); + JsonObject obj = doc.to(); + obj.createNestedObject(key); + } + } + + SECTION("MemberProxy") { + SECTION("operator=") { // issue #416 + unsigned char value[] = "world"; + + DynamicJsonDocument doc(4096); + JsonObject obj = doc.to(); + obj["hello"] = value; + + REQUIRE(std::string("world") == obj["hello"]); + } + + SECTION("set()") { + unsigned char value[] = "world"; + + DynamicJsonDocument doc(4096); + JsonObject obj = doc.to(); + obj["hello"].set(value); + + REQUIRE(std::string("world") == obj["hello"]); + } + } + + SECTION("JsonArray") { + SECTION("add()") { + unsigned char value[] = "world"; + + DynamicJsonDocument doc(4096); + JsonArray arr = doc.to(); + arr.add(value); + + REQUIRE(std::string("world") == arr[0]); + } + } + + SECTION("ElementProxy") { + SECTION("set()") { + unsigned char value[] = "world"; + + DynamicJsonDocument doc(4096); + JsonArray arr = doc.to(); + arr.add("hello"); + arr[0].set(value); + + REQUIRE(std::string("world") == arr[0]); + } + + SECTION("operator=") { + unsigned char value[] = "world"; + + DynamicJsonDocument doc(4096); + JsonArray arr = doc.to(); + arr.add("hello"); + arr[0] = value; + + REQUIRE(std::string("world") == arr[0]); + } + } +} diff --git a/libraries/ArduinoJson/extras/tests/Misc/version.cpp b/libraries/ArduinoJson/extras/tests/Misc/version.cpp new file mode 100644 index 0000000..a91f159 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Misc/version.cpp @@ -0,0 +1,18 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include +#include + +using Catch::Matchers::StartsWith; + +TEST_CASE("ARDUINOJSON_VERSION") { + std::stringstream version; + + version << ARDUINOJSON_VERSION_MAJOR << "." << ARDUINOJSON_VERSION_MINOR + << "." << ARDUINOJSON_VERSION_REVISION; + + REQUIRE_THAT(ARDUINOJSON_VERSION, StartsWith(version.str())); +} diff --git a/libraries/ArduinoJson/extras/tests/Misc/weird_strcmp.hpp b/libraries/ArduinoJson/extras/tests/Misc/weird_strcmp.hpp new file mode 100644 index 0000000..5463d7e --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Misc/weird_strcmp.hpp @@ -0,0 +1,31 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include + +#include // strcmp, strncmp + +// Issue #1198: strcmp() implementation that returns a value larger than 8-bit + +ARDUINOJSON_BEGIN_PRIVATE_NAMESPACE + +int strcmp(const char* a, const char* b) { + int result = ::strcmp(a, b); + if (result > 0) + return 2147483647; + if (result < 0) + return -214748364; + return 0; +} + +int strncmp(const char* a, const char* b, size_t n) { + int result = ::strncmp(a, b, n); + if (result > 0) + return 2147483647; + if (result < 0) + return -214748364; + return 0; +} + +ARDUINOJSON_END_PRIVATE_NAMESPACE diff --git a/libraries/ArduinoJson/extras/tests/MixedConfiguration/CMakeLists.txt b/libraries/ArduinoJson/extras/tests/MixedConfiguration/CMakeLists.txt new file mode 100644 index 0000000..c2c9dc5 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MixedConfiguration/CMakeLists.txt @@ -0,0 +1,33 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2023, Benoit BLANCHON +# MIT License + +add_executable(MixedConfigurationTests + decode_unicode_0.cpp + decode_unicode_1.cpp + enable_alignment_0.cpp + enable_alignment_1.cpp + enable_comments_0.cpp + enable_comments_1.cpp + enable_infinity_0.cpp + enable_infinity_1.cpp + enable_nan_0.cpp + enable_nan_1.cpp + enable_progmem_1.cpp + enable_string_deduplication_0.cpp + enable_string_deduplication_1.cpp + issue1707.cpp + use_double_0.cpp + use_double_1.cpp + use_long_long_0.cpp + use_long_long_1.cpp +) + +set_target_properties(MixedConfigurationTests PROPERTIES UNITY_BUILD OFF) + +add_test(MixedConfiguration MixedConfigurationTests) + +set_tests_properties(MixedConfiguration + PROPERTIES + LABELS "Catch" +) diff --git a/libraries/ArduinoJson/extras/tests/MixedConfiguration/decode_unicode_0.cpp b/libraries/ArduinoJson/extras/tests/MixedConfiguration/decode_unicode_0.cpp new file mode 100644 index 0000000..b5dc1f1 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MixedConfiguration/decode_unicode_0.cpp @@ -0,0 +1,12 @@ +#define ARDUINOJSON_DECODE_UNICODE 0 +#include + +#include + +TEST_CASE("ARDUINOJSON_DECODE_UNICODE == 0") { + DynamicJsonDocument doc(2048); + DeserializationError err = deserializeJson(doc, "\"\\uD834\\uDD1E\""); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.as() == "\\uD834\\uDD1E"); +} diff --git a/libraries/ArduinoJson/extras/tests/MixedConfiguration/decode_unicode_1.cpp b/libraries/ArduinoJson/extras/tests/MixedConfiguration/decode_unicode_1.cpp new file mode 100644 index 0000000..2b5b652 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MixedConfiguration/decode_unicode_1.cpp @@ -0,0 +1,11 @@ +#define ARDUINOJSON_DECODE_UNICODE 1 +#include + +#include + +TEST_CASE("ARDUINOJSON_DECODE_UNICODE == 1") { + DynamicJsonDocument doc(2048); + DeserializationError err = deserializeJson(doc, "\"\\uD834\\uDD1E\""); + + REQUIRE(err == DeserializationError::Ok); +} diff --git a/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_alignment_0.cpp b/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_alignment_0.cpp new file mode 100644 index 0000000..569f84a --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_alignment_0.cpp @@ -0,0 +1,41 @@ +#define ARDUINOJSON_VERSION_NAMESPACE NoAlignment +#define ARDUINOJSON_ENABLE_ALIGNMENT 0 +#include + +#include + +TEST_CASE("ARDUINOJSON_ENABLE_ALIGNMENT == 0") { + using namespace ArduinoJson::detail; + + const size_t N = sizeof(void*); + + SECTION("isAligned()") { + CHECK(isAligned(0) == true); + CHECK(isAligned(1) == true); + CHECK(isAligned(N) == true); + CHECK(isAligned(N + 1) == true); + CHECK(isAligned(2 * N) == true); + CHECK(isAligned(2 * N + 1) == true); + } + + SECTION("addPadding()") { + CHECK(addPadding(0) == 0); + CHECK(addPadding(1) == 1); + CHECK(addPadding(N) == N); + CHECK(addPadding(N + 1) == N + 1); + } + + SECTION("AddPadding<>") { + const size_t a = AddPadding<0>::value; + CHECK(a == 0); + + const size_t b = AddPadding<1>::value; + CHECK(b == 1); + + const size_t c = AddPadding::value; + CHECK(c == N); + + const size_t d = AddPadding::value; + CHECK(d == N + 1); + } +} diff --git a/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_alignment_1.cpp b/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_alignment_1.cpp new file mode 100644 index 0000000..56d4816 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_alignment_1.cpp @@ -0,0 +1,40 @@ +#define ARDUINOJSON_ENABLE_ALIGNMENT 1 +#include + +#include + +TEST_CASE("ARDUINOJSON_ENABLE_ALIGNMENT == 1") { + using namespace ArduinoJson::detail; + + const size_t N = sizeof(void*); + + SECTION("isAligned()") { + CHECK(isAligned(0) == true); + CHECK(isAligned(1) == false); + CHECK(isAligned(N) == true); + CHECK(isAligned(N + 1) == false); + CHECK(isAligned(2 * N) == true); + CHECK(isAligned(2 * N + 1) == false); + } + + SECTION("addPadding()") { + CHECK(addPadding(0) == 0); + CHECK(addPadding(1) == N); + CHECK(addPadding(N) == N); + CHECK(addPadding(N + 1) == 2 * N); + } + + SECTION("AddPadding<>") { + const size_t a = AddPadding<0>::value; + CHECK(a == 0); + + const size_t b = AddPadding<1>::value; + CHECK(b == N); + + const size_t c = AddPadding::value; + CHECK(c == N); + + const size_t d = AddPadding::value; + CHECK(d == 2 * N); + } +} diff --git a/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_comments_0.cpp b/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_comments_0.cpp new file mode 100644 index 0000000..a3ada5e --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_comments_0.cpp @@ -0,0 +1,54 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#define ARDUINOJSON_ENABLE_COMMENTS 0 +#include + +#include + +TEST_CASE("Comments should produce InvalidInput") { + DynamicJsonDocument doc(2048); + + const char* testCases[] = { + "/*COMMENT*/ [\"hello\"]", + "[/*COMMENT*/ \"hello\"]", + "[\"hello\"/*COMMENT*/]", + "[\"hello\"/*COMMENT*/,\"world\"]", + "[\"hello\",/*COMMENT*/ \"world\"]", + "[/*/\n]", + "[/*COMMENT]", + "[/*COMMENT*]", + "//COMMENT\n\t[\"hello\"]", + "[//COMMENT\n\"hello\"]", + "[\"hello\"//COMMENT\r\n]", + "[\"hello\"//COMMENT\n,\"world\"]", + "[\"hello\",//COMMENT\n\"world\"]", + "[/COMMENT\n]", + "[//COMMENT", + "/*COMMENT*/ {\"hello\":\"world\"}", + "{/*COMMENT*/\"hello\":\"world\"}", + "{\"hello\"/*COMMENT*/:\"world\"}", + "{\"hello\":/*COMMENT*/\"world\"}", + "{\"hello\":\"world\"/*COMMENT*/}", + "//COMMENT\n {\"hello\":\"world\"}", + "{//COMMENT\n\"hello\":\"world\"}", + "{\"hello\"//COMMENT\n:\"world\"}", + "{\"hello\"://COMMENT\n\"world\"}", + "{\"hello\":\"world\"//COMMENT\n}", + "/{\"hello\":\"world\"}", + "{/\"hello\":\"world\"}", + "{\"hello\"/:\"world\"}", + "{\"hello\":/\"world\"}", + "{\"hello\":\"world\"/}", + "{\"hello\":\"world\"/,\"answer\":42}", + "{\"hello\":\"world\",/\"answer\":42}", + }; + const size_t testCount = sizeof(testCases) / sizeof(testCases[0]); + + for (size_t i = 0; i < testCount; i++) { + const char* input = testCases[i]; + CAPTURE(input); + REQUIRE(deserializeJson(doc, input) == DeserializationError::InvalidInput); + } +} diff --git a/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_comments_1.cpp b/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_comments_1.cpp new file mode 100644 index 0000000..5e0831c --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_comments_1.cpp @@ -0,0 +1,411 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#define ARDUINOJSON_ENABLE_COMMENTS 1 +#include + +#include + +TEST_CASE("Comments in arrays") { + DynamicJsonDocument doc(2048); + + SECTION("Block comments") { + SECTION("Before opening bracket") { + DeserializationError err = + deserializeJson(doc, "/*COMMENT*/ [\"hello\"]"); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(1 == arr.size()); + REQUIRE(arr[0] == "hello"); + } + + SECTION("After opening bracket") { + DeserializationError err = + deserializeJson(doc, "[/*COMMENT*/ \"hello\"]"); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(1 == arr.size()); + REQUIRE(arr[0] == "hello"); + } + + SECTION("Before closing bracket") { + DeserializationError err = deserializeJson(doc, "[\"hello\"/*COMMENT*/]"); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(1 == arr.size()); + REQUIRE(arr[0] == "hello"); + } + + SECTION("After closing bracket") { + DeserializationError err = deserializeJson(doc, "[\"hello\"]/*COMMENT*/"); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(1 == arr.size()); + REQUIRE(arr[0] == "hello"); + } + + SECTION("Before comma") { + DeserializationError err = + deserializeJson(doc, "[\"hello\"/*COMMENT*/,\"world\"]"); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(2 == arr.size()); + REQUIRE(arr[0] == "hello"); + REQUIRE(arr[1] == "world"); + } + + SECTION("After comma") { + DeserializationError err = + deserializeJson(doc, "[\"hello\",/*COMMENT*/ \"world\"]"); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(2 == arr.size()); + REQUIRE(arr[0] == "hello"); + REQUIRE(arr[1] == "world"); + } + + SECTION("/*/") { + DeserializationError err = deserializeJson(doc, "[/*/\n]"); + REQUIRE(err == DeserializationError::IncompleteInput); + } + + SECTION("Unfinished comment") { + DeserializationError err = deserializeJson(doc, "[/*COMMENT]"); + REQUIRE(err == DeserializationError::IncompleteInput); + } + + SECTION("Final slash missing") { + DeserializationError err = deserializeJson(doc, "[/*COMMENT*]"); + REQUIRE(err == DeserializationError::IncompleteInput); + } + } + + SECTION("Trailing comments") { + SECTION("Before opening bracket") { + DeserializationError err = + deserializeJson(doc, "//COMMENT\n\t[\"hello\"]"); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(1 == arr.size()); + REQUIRE(arr[0] == "hello"); + } + + SECTION("After opening bracket") { + DeserializationError err = deserializeJson(doc, "[//COMMENT\n\"hello\"]"); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(1 == arr.size()); + REQUIRE(arr[0] == "hello"); + } + + SECTION("Before closing bracket") { + DeserializationError err = + deserializeJson(doc, "[\"hello\"//COMMENT\r\n]"); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(1 == arr.size()); + REQUIRE(arr[0] == "hello"); + } + + SECTION("After closing bracket") { + DeserializationError err = deserializeJson(doc, "[\"hello\"]//COMMENT\n"); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(1 == arr.size()); + REQUIRE(arr[0] == "hello"); + } + + SECTION("Before comma") { + DeserializationError err = + deserializeJson(doc, "[\"hello\"//COMMENT\n,\"world\"]"); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(2 == arr.size()); + REQUIRE(arr[0] == "hello"); + REQUIRE(arr[1] == "world"); + } + + SECTION("After comma") { + DeserializationError err = + deserializeJson(doc, "[\"hello\",//COMMENT\n\"world\"]"); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(2 == arr.size()); + REQUIRE(arr[0] == "hello"); + REQUIRE(arr[1] == "world"); + } + + SECTION("Invalid comment") { + DeserializationError err = deserializeJson(doc, "[/COMMENT\n]"); + REQUIRE(err == DeserializationError::InvalidInput); + } + + SECTION("End document with comment") { + DeserializationError err = deserializeJson(doc, "[//COMMENT"); + REQUIRE(err == DeserializationError::IncompleteInput); + } + } +} + +TEST_CASE("Comments in objects") { + DynamicJsonDocument doc(2048); + + SECTION("Block comments") { + SECTION("Before opening brace") { + DeserializationError err = + deserializeJson(doc, "/*COMMENT*/ {\"hello\":\"world\"}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(obj["hello"] == "world"); + } + + SECTION("After opening brace") { + DeserializationError err = + deserializeJson(doc, "{/*COMMENT*/\"hello\":\"world\"}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(obj["hello"] == "world"); + } + + SECTION("Before colon") { + DeserializationError err = + deserializeJson(doc, "{\"hello\"/*COMMENT*/:\"world\"}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(obj["hello"] == "world"); + } + + SECTION("After colon") { + DeserializationError err = + deserializeJson(doc, "{\"hello\":/*COMMENT*/\"world\"}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(obj["hello"] == "world"); + } + + SECTION("Before closing brace") { + DeserializationError err = + deserializeJson(doc, "{\"hello\":\"world\"/*COMMENT*/}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(obj["hello"] == "world"); + } + + SECTION("After closing brace") { + DeserializationError err = + deserializeJson(doc, "{\"hello\":\"world\"}/*COMMENT*/"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(obj["hello"] == "world"); + } + + SECTION("Before comma") { + DeserializationError err = deserializeJson( + doc, "{\"hello\":\"world\"/*COMMENT*/,\"answer\":42}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(obj["hello"] == "world"); + REQUIRE(obj["answer"] == 42); + } + + SECTION("After comma") { + DeserializationError err = deserializeJson( + doc, "{\"hello\":\"world\",/*COMMENT*/\"answer\":42}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(obj["hello"] == "world"); + REQUIRE(obj["answer"] == 42); + } + } + + SECTION("Trailing comments") { + SECTION("Before opening brace") { + DeserializationError err = + deserializeJson(doc, "//COMMENT\n {\"hello\":\"world\"}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(obj["hello"] == "world"); + } + + SECTION("After opening brace") { + DeserializationError err = + deserializeJson(doc, "{//COMMENT\n\"hello\":\"world\"}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(obj["hello"] == "world"); + } + + SECTION("Before colon") { + DeserializationError err = + deserializeJson(doc, "{\"hello\"//COMMENT\n:\"world\"}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(obj["hello"] == "world"); + } + + SECTION("After colon") { + DeserializationError err = + deserializeJson(doc, "{\"hello\"://COMMENT\n\"world\"}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(obj["hello"] == "world"); + } + + SECTION("Before closing brace") { + DeserializationError err = + deserializeJson(doc, "{\"hello\":\"world\"//COMMENT\n}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(obj["hello"] == "world"); + } + + SECTION("After closing brace") { + DeserializationError err = + deserializeJson(doc, "{\"hello\":\"world\"}//COMMENT\n"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(obj["hello"] == "world"); + } + + SECTION("Before comma") { + DeserializationError err = deserializeJson( + doc, "{\"hello\":\"world\"//COMMENT\n,\"answer\":42}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(obj["hello"] == "world"); + REQUIRE(obj["answer"] == 42); + } + + SECTION("After comma") { + DeserializationError err = deserializeJson( + doc, "{\"hello\":\"world\",//COMMENT\n\"answer\":42}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(obj["hello"] == "world"); + REQUIRE(obj["answer"] == 42); + } + } + + SECTION("Dangling slash") { + SECTION("Before opening brace") { + DeserializationError err = deserializeJson(doc, "/{\"hello\":\"world\"}"); + + REQUIRE(err == DeserializationError::InvalidInput); + } + + SECTION("After opening brace") { + DeserializationError err = deserializeJson(doc, "{/\"hello\":\"world\"}"); + + REQUIRE(err == DeserializationError::InvalidInput); + } + + SECTION("Before colon") { + DeserializationError err = deserializeJson(doc, "{\"hello\"/:\"world\"}"); + + REQUIRE(err == DeserializationError::InvalidInput); + } + + SECTION("After colon") { + DeserializationError err = deserializeJson(doc, "{\"hello\":/\"world\"}"); + + REQUIRE(err == DeserializationError::InvalidInput); + } + + SECTION("Before closing brace") { + DeserializationError err = deserializeJson(doc, "{\"hello\":\"world\"/}"); + + REQUIRE(err == DeserializationError::InvalidInput); + } + + SECTION("After closing brace") { + DeserializationError err = deserializeJson(doc, "{\"hello\":\"world\"}/"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(obj["hello"] == "world"); + } + + SECTION("Before comma") { + DeserializationError err = + deserializeJson(doc, "{\"hello\":\"world\"/,\"answer\":42}"); + + REQUIRE(err == DeserializationError::InvalidInput); + } + + SECTION("After comma") { + DeserializationError err = + deserializeJson(doc, "{\"hello\":\"world\",/\"answer\":42}"); + + REQUIRE(err == DeserializationError::InvalidInput); + } + } +} + +TEST_CASE("Comments alone") { + DynamicJsonDocument doc(2048); + + SECTION("Just a trailing comment with no line break") { + DeserializationError err = deserializeJson(doc, "// comment"); + + REQUIRE(err == DeserializationError::IncompleteInput); + } + + SECTION("Just a trailing comment with no a break") { + DeserializationError err = deserializeJson(doc, "// comment\n"); + + REQUIRE(err == DeserializationError::EmptyInput); + } + + SECTION("Just a block comment") { + DeserializationError err = deserializeJson(doc, "/*comment*/"); + + REQUIRE(err == DeserializationError::EmptyInput); + } + + SECTION("Just a slash") { + DeserializationError err = deserializeJson(doc, "/"); + + REQUIRE(err == DeserializationError::InvalidInput); + } + + SECTION("Premature terminator") { + DeserializationError err = deserializeJson(doc, "/* comment"); + + REQUIRE(err == DeserializationError::IncompleteInput); + } + + SECTION("Premature end on sized input") { + DeserializationError err = deserializeJson(doc, "/* comment */", 10); + + REQUIRE(err == DeserializationError::IncompleteInput); + } +} diff --git a/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_infinity_0.cpp b/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_infinity_0.cpp new file mode 100644 index 0000000..521fb84 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_infinity_0.cpp @@ -0,0 +1,35 @@ +#define ARDUINOJSON_ENABLE_INFINITY 0 +#include + +#include +#include + +static void assertParseFails(const char* json) { + DynamicJsonDocument doc(4096); + DeserializationError err = deserializeJson(doc, json); + + REQUIRE(err == DeserializationError::InvalidInput); +} + +static void assertJsonEquals(const JsonDocument& doc, + std::string expectedJson) { + std::string actualJson; + serializeJson(doc, actualJson); + REQUIRE(actualJson == expectedJson); +} + +TEST_CASE("ARDUINOJSON_ENABLE_INFINITY == 0") { + SECTION("serializeJson()") { + DynamicJsonDocument doc(4096); + doc.add(std::numeric_limits::infinity()); + doc.add(-std::numeric_limits::infinity()); + + assertJsonEquals(doc, "[null,null]"); + } + + SECTION("deserializeJson()") { + assertParseFails("{\"X\":Infinity}"); + assertParseFails("{\"X\":-Infinity}"); + assertParseFails("{\"X\":+Infinity}"); + } +} diff --git a/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_infinity_1.cpp b/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_infinity_1.cpp new file mode 100644 index 0000000..28a3461 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_infinity_1.cpp @@ -0,0 +1,39 @@ +#define ARDUINOJSON_ENABLE_INFINITY 1 +#include + +#include +#include + +namespace my { +using ArduinoJson::detail::isinf; +} // namespace my + +TEST_CASE("ARDUINOJSON_ENABLE_INFINITY == 1") { + DynamicJsonDocument doc(4096); + + SECTION("serializeJson()") { + doc.add(std::numeric_limits::infinity()); + doc.add(-std::numeric_limits::infinity()); + + std::string json; + serializeJson(doc, json); + + REQUIRE(json == "[Infinity,-Infinity]"); + } + + SECTION("deserializeJson()") { + DeserializationError err = + deserializeJson(doc, "[Infinity,-Infinity,+Infinity]"); + float a = doc[0]; + float b = doc[1]; + float c = doc[2]; + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(my::isinf(a)); + REQUIRE(a > 0); + REQUIRE(my::isinf(b)); + REQUIRE(b < 0); + REQUIRE(my::isinf(c)); + REQUIRE(c > 0); + } +} diff --git a/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_nan_0.cpp b/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_nan_0.cpp new file mode 100644 index 0000000..e015a0d --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_nan_0.cpp @@ -0,0 +1,25 @@ +#define ARDUINOJSON_ENABLE_NAN 0 +#include + +#include +#include + +TEST_CASE("ARDUINOJSON_ENABLE_NAN == 0") { + DynamicJsonDocument doc(4096); + JsonObject root = doc.to(); + + SECTION("serializeJson()") { + root["X"] = std::numeric_limits::signaling_NaN(); + + std::string json; + serializeJson(doc, json); + + REQUIRE(json == "{\"X\":null}"); + } + + SECTION("deserializeJson()") { + DeserializationError err = deserializeJson(doc, "{\"X\":NaN}"); + + REQUIRE(err == DeserializationError::InvalidInput); + } +} diff --git a/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_nan_1.cpp b/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_nan_1.cpp new file mode 100644 index 0000000..f9ae04a --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_nan_1.cpp @@ -0,0 +1,31 @@ +#define ARDUINOJSON_ENABLE_NAN 1 +#include + +#include +#include + +namespace my { +using ArduinoJson::detail::isnan; +} // namespace my + +TEST_CASE("ARDUINOJSON_ENABLE_NAN == 1") { + DynamicJsonDocument doc(4096); + JsonObject root = doc.to(); + + SECTION("serializeJson()") { + root["X"] = std::numeric_limits::signaling_NaN(); + + std::string json; + serializeJson(doc, json); + + REQUIRE(json == "{\"X\":NaN}"); + } + + SECTION("deserializeJson()") { + DeserializationError err = deserializeJson(doc, "{\"X\":NaN}"); + float x = doc["X"]; + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(my::isnan(x)); + } +} diff --git a/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_progmem_1.cpp b/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_progmem_1.cpp new file mode 100644 index 0000000..2cc683d --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_progmem_1.cpp @@ -0,0 +1,191 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#define ARDUINOJSON_ENABLE_PROGMEM 1 +#include + +#include + +TEST_CASE("Flash strings") { + DynamicJsonDocument doc(2048); + + SECTION("deserializeJson()") { + DeserializationError err = deserializeJson(doc, F("{'hello':'world'}")); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc["hello"] == "world"); + } + + SECTION("JsonDocument::operator[]") { + doc[F("hello")] = F("world"); + + REQUIRE(doc["hello"] == "world"); + } + + SECTION("JsonDocument::add()") { + doc.add(F("world")); + + REQUIRE(doc[0] == "world"); + } + + SECTION("JsonVariant::set()") { + JsonVariant var = doc.to(); + + var.set(F("world")); + + REQUIRE(var == "world"); + } + + SECTION("MemberProxy::operator==") { + doc["hello"] = "world"; + + REQUIRE(doc["hello"] == F("world")); + } + + SECTION("ElementProxy::operator==") { + doc.add("world"); + + REQUIRE(doc[0] == F("world")); + } +} + +TEST_CASE("parseNumber()") { // tables are in Flash + using ArduinoJson::detail::parseNumber; + + CHECK(parseNumber("1") == 1.f); + CHECK(parseNumber("1.23") == 1.23f); + CHECK(parseNumber("-1.23e34") == -1.23e34f); +} + +TEST_CASE("strlen_P") { + CHECK(strlen_P(PSTR("")) == 0); + CHECK(strlen_P(PSTR("a")) == 1); + CHECK(strlen_P(PSTR("ac")) == 2); +} + +TEST_CASE("strncmp_P") { + CHECK(strncmp_P("a", PSTR("b"), 0) == 0); + CHECK(strncmp_P("a", PSTR("b"), 1) == -1); + CHECK(strncmp_P("b", PSTR("a"), 1) == 1); + CHECK(strncmp_P("a", PSTR("a"), 0) == 0); + CHECK(strncmp_P("a", PSTR("b"), 2) == -1); + CHECK(strncmp_P("b", PSTR("a"), 2) == 1); + CHECK(strncmp_P("a", PSTR("a"), 2) == 0); +} + +TEST_CASE("strcmp_P") { + CHECK(strcmp_P("a", PSTR("b")) == -1); + CHECK(strcmp_P("b", PSTR("a")) == 1); + CHECK(strcmp_P("a", PSTR("a")) == 0); + CHECK(strcmp_P("aa", PSTR("ab")) == -1); + CHECK(strcmp_P("ab", PSTR("aa")) == 1); + CHECK(strcmp_P("aa", PSTR("aa")) == 0); +} + +TEST_CASE("memcpy_P") { + char dst[4]; + CHECK(memcpy_P(dst, PSTR("ABC"), 4) == dst); + CHECK(dst[0] == 'A'); + CHECK(dst[1] == 'B'); + CHECK(dst[2] == 'C'); + CHECK(dst[3] == 0); +} + +TEST_CASE("BoundedReader") { + using namespace ArduinoJson::detail; + + SECTION("read") { + BoundedReader reader(F("\x01\xFF"), 2); + REQUIRE(reader.read() == 0x01); + REQUIRE(reader.read() == 0xFF); + REQUIRE(reader.read() == -1); + REQUIRE(reader.read() == -1); + } + + SECTION("readBytes() all at once") { + BoundedReader reader(F("ABCD"), 3); + + char buffer[8] = "abcd"; + REQUIRE(reader.readBytes(buffer, 4) == 3); + + REQUIRE(buffer[0] == 'A'); + REQUIRE(buffer[1] == 'B'); + REQUIRE(buffer[2] == 'C'); + REQUIRE(buffer[3] == 'd'); + } + + SECTION("readBytes() in two parts") { + BoundedReader reader(F("ABCDEF"), 6); + + char buffer[8] = "abcdefg"; + REQUIRE(reader.readBytes(buffer, 4) == 4); + REQUIRE(reader.readBytes(buffer + 4, 4) == 2); + + REQUIRE(buffer[0] == 'A'); + REQUIRE(buffer[1] == 'B'); + REQUIRE(buffer[2] == 'C'); + REQUIRE(buffer[3] == 'D'); + REQUIRE(buffer[4] == 'E'); + REQUIRE(buffer[5] == 'F'); + REQUIRE(buffer[6] == 'g'); + } +} + +TEST_CASE("Reader") { + using namespace ArduinoJson::detail; + + SECTION("read()") { + Reader reader(F("\x01\xFF\x00\x12")); + REQUIRE(reader.read() == 0x01); + REQUIRE(reader.read() == 0xFF); + REQUIRE(reader.read() == 0); + REQUIRE(reader.read() == 0x12); + } + + SECTION("readBytes() all at once") { + Reader reader(F("ABCD")); + + char buffer[8] = "abcd"; + REQUIRE(reader.readBytes(buffer, 3) == 3); + + REQUIRE(buffer[0] == 'A'); + REQUIRE(buffer[1] == 'B'); + REQUIRE(buffer[2] == 'C'); + REQUIRE(buffer[3] == 'd'); + } + + SECTION("readBytes() in two parts") { + Reader reader(F("ABCDEF")); + + char buffer[8] = "abcdefg"; + REQUIRE(reader.readBytes(buffer, 4) == 4); + REQUIRE(reader.readBytes(buffer + 4, 2) == 2); + + REQUIRE(buffer[0] == 'A'); + REQUIRE(buffer[1] == 'B'); + REQUIRE(buffer[2] == 'C'); + REQUIRE(buffer[3] == 'D'); + REQUIRE(buffer[4] == 'E'); + REQUIRE(buffer[5] == 'F'); + REQUIRE(buffer[6] == 'g'); + } +} + +static void testStringification(DeserializationError error, + std::string expected) { + const __FlashStringHelper* s = error.f_str(); + CHECK(reinterpret_cast(convertFlashToPtr(s)) == expected); +} + +#define TEST_STRINGIFICATION(symbol) \ + testStringification(DeserializationError::symbol, #symbol) + +TEST_CASE("DeserializationError::f_str()") { + TEST_STRINGIFICATION(Ok); + TEST_STRINGIFICATION(EmptyInput); + TEST_STRINGIFICATION(IncompleteInput); + TEST_STRINGIFICATION(InvalidInput); + TEST_STRINGIFICATION(NoMemory); + TEST_STRINGIFICATION(TooDeep); +} diff --git a/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_string_deduplication_0.cpp b/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_string_deduplication_0.cpp new file mode 100644 index 0000000..7277af9 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_string_deduplication_0.cpp @@ -0,0 +1,123 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#define ARDUINOJSON_ENABLE_ARDUINO_STRING 1 +#define ARDUINOJSON_ENABLE_PROGMEM 1 +#define ARDUINOJSON_ENABLE_STRING_DEDUPLICATION 0 +#include + +#include + +TEST_CASE("ARDUINOJSON_ENABLE_STRING_DEDUPLICATION = 0") { + StaticJsonDocument<1024> doc; + + SECTION("deserializeJson()") { + SECTION("Deduplicate values") { + deserializeJson(doc, "[\"example\",\"example\"]"); + + CHECK(doc.memoryUsage() == JSON_ARRAY_SIZE(2) + 16); + CHECK(doc[0].as() != doc[1].as()); + } + + SECTION("Deduplicate keys") { + deserializeJson(doc, "[{\"example\":1},{\"example\":2}]"); + + CHECK(doc.memoryUsage() == + 2 * JSON_OBJECT_SIZE(1) + JSON_ARRAY_SIZE(2) + 16); + + const char* key1 = doc[0].as().begin()->key().c_str(); + const char* key2 = doc[1].as().begin()->key().c_str(); + + CHECK(key1 != key2); + } + } + + SECTION("JsonDocument") { + SECTION("values") { + SECTION("std::string") { + doc.add(std::string("example")); + doc.add(std::string("example")); + + CHECK(doc.memoryUsage() == JSON_ARRAY_SIZE(2) + 16); + CHECK(doc[0].as() != doc[1].as()); + } + + SECTION("char*") { + char value[] = "example"; + doc.add(value); + doc.add(value); + + CHECK(doc.memoryUsage() == JSON_ARRAY_SIZE(2) + 16); + CHECK(doc[0].as() != doc[1].as()); + } + + SECTION("Arduino String") { + doc.add(String("example")); + doc.add(String("example")); + + CHECK(doc.memoryUsage() == JSON_ARRAY_SIZE(2) + 16); + CHECK(doc[0].as() != doc[1].as()); + } + + SECTION("Flash string") { + doc.add(F("example")); + doc.add(F("example")); + + CHECK(doc.memoryUsage() == JSON_ARRAY_SIZE(2) + 16); + CHECK(doc[0].as() != doc[1].as()); + } + } + + SECTION("keys") { + SECTION("std::string") { + doc[0][std::string("example")] = 1; + doc[1][std::string("example")] = 2; + + CHECK(doc.memoryUsage() == + JSON_ARRAY_SIZE(2) + 2 * JSON_OBJECT_SIZE(1) + 16); + + const char* key1 = doc[0].as().begin()->key().c_str(); + const char* key2 = doc[1].as().begin()->key().c_str(); + CHECK(key1 != key2); + } + + SECTION("char*") { + char key[] = "example"; + doc[0][key] = 1; + doc[1][key] = 2; + + CHECK(doc.memoryUsage() == + JSON_ARRAY_SIZE(2) + 2 * JSON_OBJECT_SIZE(1) + 16); + + const char* key1 = doc[0].as().begin()->key().c_str(); + const char* key2 = doc[1].as().begin()->key().c_str(); + CHECK(key1 != key2); + } + + SECTION("Arduino String") { + doc[0][String("example")] = 1; + doc[1][String("example")] = 2; + + CHECK(doc.memoryUsage() == + JSON_ARRAY_SIZE(2) + 2 * JSON_OBJECT_SIZE(1) + 16); + + const char* key1 = doc[0].as().begin()->key().c_str(); + const char* key2 = doc[1].as().begin()->key().c_str(); + CHECK(key1 != key2); + } + + SECTION("Flash string") { + doc[0][F("example")] = 1; + doc[1][F("example")] = 2; + + CHECK(doc.memoryUsage() == + JSON_ARRAY_SIZE(2) + 2 * JSON_OBJECT_SIZE(1) + 16); + + const char* key1 = doc[0].as().begin()->key().c_str(); + const char* key2 = doc[1].as().begin()->key().c_str(); + CHECK(key1 != key2); + } + } + } +} diff --git a/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_string_deduplication_1.cpp b/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_string_deduplication_1.cpp new file mode 100644 index 0000000..d3b2285 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MixedConfiguration/enable_string_deduplication_1.cpp @@ -0,0 +1,122 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#define ARDUINOJSON_ENABLE_ARDUINO_STRING 1 +#define ARDUINOJSON_ENABLE_PROGMEM 1 +#define ARDUINOJSON_ENABLE_STRING_DEDUPLICATION 1 +#include + +#include + +TEST_CASE("ARDUINOJSON_ENABLE_STRING_DEDUPLICATION = 1") { + StaticJsonDocument<1024> doc; + + SECTION("deserializeJson()") { + SECTION("Deduplicate values") { + deserializeJson(doc, "[\"example\",\"example\"]"); + + CHECK(doc.memoryUsage() == JSON_ARRAY_SIZE(2) + 8); + CHECK(doc[0].as() == doc[1].as()); + } + + SECTION("Deduplicate keys") { + deserializeJson(doc, "[{\"example\":1},{\"example\":2}]"); + + CHECK(doc.memoryUsage() == + 2 * JSON_OBJECT_SIZE(1) + JSON_ARRAY_SIZE(2) + 8); + + const char* key1 = doc[0].as().begin()->key().c_str(); + const char* key2 = doc[1].as().begin()->key().c_str(); + CHECK(key1 == key2); + } + } + + SECTION("JsonDocument") { + SECTION("values") { + SECTION("std::string") { + doc.add(std::string("example")); + doc.add(std::string("example")); + + CHECK(doc.memoryUsage() == JSON_ARRAY_SIZE(2) + 8); + CHECK(doc[0].as() == doc[1].as()); + } + + SECTION("char*") { + char value[] = "example"; + doc.add(value); + doc.add(value); + + CHECK(doc.memoryUsage() == JSON_ARRAY_SIZE(2) + 8); + CHECK(doc[0].as() == doc[1].as()); + } + + SECTION("Arduino String") { + doc.add(String("example")); + doc.add(String("example")); + + CHECK(doc.memoryUsage() == JSON_ARRAY_SIZE(2) + 8); + CHECK(doc[0].as() == doc[1].as()); + } + + SECTION("Flash string") { + doc.add(F("example")); + doc.add(F("example")); + + CHECK(doc.memoryUsage() == JSON_ARRAY_SIZE(2) + 8); + CHECK(doc[0].as() == doc[1].as()); + } + } + + SECTION("keys") { + SECTION("std::string") { + doc[0][std::string("example")] = 1; + doc[1][std::string("example")] = 2; + + CHECK(doc.memoryUsage() == + JSON_ARRAY_SIZE(2) + 2 * JSON_OBJECT_SIZE(1) + 8); + + const char* key1 = doc[0].as().begin()->key().c_str(); + const char* key2 = doc[1].as().begin()->key().c_str(); + CHECK(key1 == key2); + } + + SECTION("char*") { + char key[] = "example"; + doc[0][key] = 1; + doc[1][key] = 2; + + CHECK(doc.memoryUsage() == + JSON_ARRAY_SIZE(2) + 2 * JSON_OBJECT_SIZE(1) + 8); + + const char* key1 = doc[0].as().begin()->key().c_str(); + const char* key2 = doc[1].as().begin()->key().c_str(); + CHECK(key1 == key2); + } + + SECTION("Arduino String") { + doc[0][String("example")] = 1; + doc[1][String("example")] = 2; + + CHECK(doc.memoryUsage() == + JSON_ARRAY_SIZE(2) + 2 * JSON_OBJECT_SIZE(1) + 8); + + const char* key1 = doc[0].as().begin()->key().c_str(); + const char* key2 = doc[1].as().begin()->key().c_str(); + CHECK(key1 == key2); + } + + SECTION("Flash string") { + doc[0][F("example")] = 1; + doc[1][F("example")] = 2; + + CHECK(doc.memoryUsage() == + JSON_ARRAY_SIZE(2) + 2 * JSON_OBJECT_SIZE(1) + 8); + + const char* key1 = doc[0].as().begin()->key().c_str(); + const char* key2 = doc[1].as().begin()->key().c_str(); + CHECK(key1 == key2); + } + } + } +} diff --git a/libraries/ArduinoJson/extras/tests/MixedConfiguration/issue1707.cpp b/libraries/ArduinoJson/extras/tests/MixedConfiguration/issue1707.cpp new file mode 100644 index 0000000..f8ca566 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MixedConfiguration/issue1707.cpp @@ -0,0 +1,17 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#define ARDUINO +#define memcpy_P(dest, src, n) memcpy((dest), (src), (n)) + +#include + +#include + +TEST_CASE("Issue1707") { + StaticJsonDocument<128> doc; + + DeserializationError err = deserializeJson(doc, F("{\"hello\":12}")); + REQUIRE(err == DeserializationError::Ok); +} diff --git a/libraries/ArduinoJson/extras/tests/MixedConfiguration/use_double_0.cpp b/libraries/ArduinoJson/extras/tests/MixedConfiguration/use_double_0.cpp new file mode 100644 index 0000000..f38ee1f --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MixedConfiguration/use_double_0.cpp @@ -0,0 +1,17 @@ +#define ARDUINOJSON_USE_DOUBLE 0 +#include + +#include + +TEST_CASE("ARDUINOJSON_USE_DOUBLE == 0") { + DynamicJsonDocument doc(4096); + JsonObject root = doc.to(); + + root["pi"] = 3.14; + root["e"] = 2.72; + + std::string json; + serializeJson(doc, json); + + REQUIRE(json == "{\"pi\":3.14,\"e\":2.72}"); +} diff --git a/libraries/ArduinoJson/extras/tests/MixedConfiguration/use_double_1.cpp b/libraries/ArduinoJson/extras/tests/MixedConfiguration/use_double_1.cpp new file mode 100644 index 0000000..ff4a0e3 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MixedConfiguration/use_double_1.cpp @@ -0,0 +1,17 @@ +#define ARDUINOJSON_USE_DOUBLE 1 +#include + +#include + +TEST_CASE("ARDUINOJSON_USE_DOUBLE == 1") { + DynamicJsonDocument doc(4096); + JsonObject root = doc.to(); + + root["pi"] = 3.14; + root["e"] = 2.72; + + std::string json; + serializeJson(doc, json); + + REQUIRE(json == "{\"pi\":3.14,\"e\":2.72}"); +} diff --git a/libraries/ArduinoJson/extras/tests/MixedConfiguration/use_long_long_0.cpp b/libraries/ArduinoJson/extras/tests/MixedConfiguration/use_long_long_0.cpp new file mode 100644 index 0000000..f467aab --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MixedConfiguration/use_long_long_0.cpp @@ -0,0 +1,16 @@ +#define ARDUINOJSON_USE_LONG_LONG 0 +#include + +#include + +TEST_CASE("ARDUINOJSON_USE_LONG_LONG == 0") { + DynamicJsonDocument doc(4096); + + doc["A"] = 42; + doc["B"] = 84; + + std::string json; + serializeJson(doc, json); + + REQUIRE(json == "{\"A\":42,\"B\":84}"); +} diff --git a/libraries/ArduinoJson/extras/tests/MixedConfiguration/use_long_long_1.cpp b/libraries/ArduinoJson/extras/tests/MixedConfiguration/use_long_long_1.cpp new file mode 100644 index 0000000..5127a55 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MixedConfiguration/use_long_long_1.cpp @@ -0,0 +1,17 @@ +#define ARDUINOJSON_USE_LONG_LONG 1 +#include + +#include + +TEST_CASE("ARDUINOJSON_USE_LONG_LONG == 1") { + DynamicJsonDocument doc(4096); + JsonObject root = doc.to(); + + root["A"] = 123456789123456789; + root["B"] = 987654321987654321; + + std::string json; + serializeJson(doc, json); + + REQUIRE(json == "{\"A\":123456789123456789,\"B\":987654321987654321}"); +} diff --git a/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/CMakeLists.txt b/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/CMakeLists.txt new file mode 100644 index 0000000..a544207 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/CMakeLists.txt @@ -0,0 +1,24 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2023, Benoit BLANCHON +# MIT License + +add_executable(MsgPackDeserializerTests + deserializeArray.cpp + deserializeObject.cpp + deserializeStaticVariant.cpp + deserializeVariant.cpp + doubleToFloat.cpp + filter.cpp + incompleteInput.cpp + input_types.cpp + misc.cpp + nestingLimit.cpp + notSupported.cpp +) + +add_test(MsgPackDeserializer MsgPackDeserializerTests) + +set_tests_properties(MsgPackDeserializer + PROPERTIES + LABELS "Catch" +) diff --git a/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/deserializeArray.cpp b/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/deserializeArray.cpp new file mode 100644 index 0000000..356a9fe --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/deserializeArray.cpp @@ -0,0 +1,83 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("deserialize MsgPack array") { + DynamicJsonDocument doc(4096); + + SECTION("fixarray") { + SECTION("empty") { + const char* input = "\x90"; + + DeserializationError error = deserializeMsgPack(doc, input); + JsonArray array = doc.as(); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(array.size() == 0); + } + + SECTION("two integers") { + const char* input = "\x92\x01\x02"; + + DeserializationError error = deserializeMsgPack(doc, input); + JsonArray array = doc.as(); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(array.size() == 2); + REQUIRE(array[0] == 1); + REQUIRE(array[1] == 2); + } + } + + SECTION("array 16") { + SECTION("empty") { + const char* input = "\xDC\x00\x00"; + + DeserializationError error = deserializeMsgPack(doc, input); + JsonArray array = doc.as(); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(array.size() == 0); + } + + SECTION("two strings") { + const char* input = "\xDC\x00\x02\xA5hello\xA5world"; + + DeserializationError error = deserializeMsgPack(doc, input); + JsonArray array = doc.as(); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(array.size() == 2); + REQUIRE(array[0] == "hello"); + REQUIRE(array[1] == "world"); + } + } + + SECTION("array 32") { + SECTION("empty") { + const char* input = "\xDD\x00\x00\x00\x00"; + + DeserializationError error = deserializeMsgPack(doc, input); + JsonArray array = doc.as(); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(array.size() == 0); + } + + SECTION("two floats") { + const char* input = + "\xDD\x00\x00\x00\x02\xCA\x00\x00\x00\x00\xCA\x40\x48\xF5\xC3"; + + DeserializationError error = deserializeMsgPack(doc, input); + JsonArray array = doc.as(); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(array.size() == 2); + REQUIRE(array[0] == 0.0f); + REQUIRE(array[1] == 3.14f); + } + } +} diff --git a/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/deserializeObject.cpp b/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/deserializeObject.cpp new file mode 100644 index 0000000..4aeb553 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/deserializeObject.cpp @@ -0,0 +1,130 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("deserialize MsgPack object") { + DynamicJsonDocument doc(4096); + + SECTION("fixmap") { + SECTION("empty") { + const char* input = "\x80"; + + DeserializationError error = deserializeMsgPack(doc, input); + JsonObject obj = doc.as(); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(obj.size() == 0); + } + + SECTION("two integers") { + const char* input = "\x82\xA3one\x01\xA3two\x02"; + + DeserializationError error = deserializeMsgPack(doc, input); + JsonObject obj = doc.as(); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(obj.size() == 2); + REQUIRE(obj["one"] == 1); + REQUIRE(obj["two"] == 2); + } + + SECTION("key is str 8") { + const char* input = "\x82\xd9\x03one\x01\xd9\x03two\x02"; + + DeserializationError error = deserializeMsgPack(doc, input); + JsonObject obj = doc.as(); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(obj.size() == 2); + REQUIRE(obj["one"] == 1); + REQUIRE(obj["two"] == 2); + } + + SECTION("key is str 16") { + const char* input = "\x82\xda\x00\x03one\x01\xda\x00\x03two\x02"; + + DeserializationError error = deserializeMsgPack(doc, input); + JsonObject obj = doc.as(); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(obj.size() == 2); + REQUIRE(obj["one"] == 1); + REQUIRE(obj["two"] == 2); + } + + SECTION("key is str 32") { + const char* input = + "\x82\xdb\x00\x00\x00\x03one\x01\xdb\x00\x00\x00\x03two\x02"; + + DeserializationError error = deserializeMsgPack(doc, input); + JsonObject obj = doc.as(); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(obj.size() == 2); + REQUIRE(obj["one"] == 1); + REQUIRE(obj["two"] == 2); + } + } + + SECTION("map 16") { + SECTION("empty") { + const char* input = "\xDE\x00\x00"; + + DeserializationError error = deserializeMsgPack(doc, input); + JsonObject obj = doc.as(); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(obj.size() == 0); + } + + SECTION("two strings") { + const char* input = "\xDE\x00\x02\xA1H\xA5hello\xA1W\xA5world"; + + DeserializationError error = deserializeMsgPack(doc, input); + JsonObject obj = doc.as(); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(obj.size() == 2); + REQUIRE(obj["H"] == "hello"); + REQUIRE(obj["W"] == "world"); + } + } + + SECTION("map 32") { + SECTION("empty") { + const char* input = "\xDF\x00\x00\x00\x00"; + + DeserializationError error = deserializeMsgPack(doc, input); + JsonObject obj = doc.as(); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(obj.size() == 0); + } + + SECTION("two floats") { + const char* input = + "\xDF\x00\x00\x00\x02\xA4zero\xCA\x00\x00\x00\x00\xA2pi\xCA\x40\x48" + "\xF5\xC3"; + + DeserializationError error = deserializeMsgPack(doc, input); + JsonObject obj = doc.as(); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(obj.size() == 2); + REQUIRE(obj["zero"] == 0.0f); + REQUIRE(obj["pi"] == 3.14f); + } + } +} diff --git a/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/deserializeStaticVariant.cpp b/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/deserializeStaticVariant.cpp new file mode 100644 index 0000000..0e126ff --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/deserializeStaticVariant.cpp @@ -0,0 +1,152 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +template +static void check(const char* input, DeserializationError expected) { + StaticJsonDocument doc; + + DeserializationError error = deserializeMsgPack(doc, input); + + CAPTURE(input); + REQUIRE(error == expected); +} + +template +static void checkString(const char* input, DeserializationError expected) { + check(input, expected); +} + +TEST_CASE("deserializeMsgPack(StaticJsonDocument&)") { + SECTION("single values always fit") { + check<0>("\xc0", DeserializationError::Ok); // nil + check<0>("\xc2", DeserializationError::Ok); // false + check<0>("\xc3", DeserializationError::Ok); // true + check<0>("\xcc\x00", DeserializationError::Ok); // uint 8 + check<0>("\xcd\x30\x39", DeserializationError::Ok); // uint 16 + check<0>("\xCE\x12\x34\x56\x78", DeserializationError::Ok); // uint 32 + } + + SECTION("fixstr") { + checkString<8>("\xA0", DeserializationError::Ok); + checkString<8>("\xA7ZZZZZZZ", DeserializationError::Ok); + checkString<8>("\xA8ZZZZZZZZ", DeserializationError::NoMemory); + checkString<16>("\xAFZZZZZZZZZZZZZZZ", DeserializationError::Ok); + checkString<16>("\xB0ZZZZZZZZZZZZZZZZ", DeserializationError::NoMemory); + } + + SECTION("str 8") { + checkString<8>("\xD9\x00", DeserializationError::Ok); + checkString<8>("\xD9\x07ZZZZZZZ", DeserializationError::Ok); + checkString<8>("\xD9\x08ZZZZZZZZ", DeserializationError::NoMemory); + checkString<16>("\xD9\x0FZZZZZZZZZZZZZZZ", DeserializationError::Ok); + checkString<16>("\xD9\x10ZZZZZZZZZZZZZZZZ", DeserializationError::NoMemory); + } + + SECTION("str 16") { + checkString<8>("\xDA\x00\x00", DeserializationError::Ok); + checkString<8>("\xDA\x00\x07ZZZZZZZ", DeserializationError::Ok); + checkString<8>("\xDA\x00\x08ZZZZZZZZ", DeserializationError::NoMemory); + checkString<16>("\xDA\x00\x0FZZZZZZZZZZZZZZZ", DeserializationError::Ok); + checkString<16>("\xDA\x00\x10ZZZZZZZZZZZZZZZZ", + DeserializationError::NoMemory); + } + + SECTION("str 32") { + checkString<8>("\xDB\x00\x00\x00\x00", DeserializationError::Ok); + checkString<8>("\xDB\x00\x00\x00\x07ZZZZZZZ", DeserializationError::Ok); + checkString<8>("\xDB\x00\x00\x00\x08ZZZZZZZZ", + DeserializationError::NoMemory); + checkString<16>("\xDB\x00\x00\x00\x0FZZZZZZZZZZZZZZZ", + DeserializationError::Ok); + checkString<16>("\xDB\x00\x00\x00\x10ZZZZZZZZZZZZZZZZ", + DeserializationError::NoMemory); + } + + SECTION("fixarray") { + check("\x90", DeserializationError::Ok); // [] + check("\x91\x01", + DeserializationError::NoMemory); // [1] + check("\x91\x01", DeserializationError::Ok); // [1] + check("\x92\x01\x02", + DeserializationError::NoMemory); // [1,2] + } + + SECTION("array 16") { + check("\xDC\x00\x00", DeserializationError::Ok); + check("\xDC\x00\x01\x01", + DeserializationError::NoMemory); + check("\xDC\x00\x01\x01", DeserializationError::Ok); + check("\xDC\x00\x02\x01\x02", + DeserializationError::NoMemory); + } + + SECTION("array 32") { + check("\xDD\x00\x00\x00\x00", DeserializationError::Ok); + check("\xDD\x00\x00\x00\x01\x01", + DeserializationError::NoMemory); + check("\xDD\x00\x00\x00\x01\x01", + DeserializationError::Ok); + check("\xDD\x00\x00\x00\x02\x01\x02", + DeserializationError::NoMemory); + } + + SECTION("fixmap") { + SECTION("{}") { + check("\x80", DeserializationError::Ok); + } + SECTION("{H:1}") { + check("\x81\xA1H\x01", + DeserializationError::NoMemory); + check( + "\x81\xA1H\x01", DeserializationError::Ok); + } + SECTION("{H:1,W:2}") { + check( + "\x82\xA1H\x01\xA1W\x02", DeserializationError::NoMemory); + check( + "\x82\xA1H\x01\xA1W\x02", DeserializationError::Ok); + } + } + + SECTION("map 16") { + SECTION("{}") { + check("\xDE\x00\x00", DeserializationError::Ok); + } + SECTION("{H:1}") { + check("\xDE\x00\x01\xA1H\x01", + DeserializationError::NoMemory); + check( + "\xDE\x00\x01\xA1H\x01", DeserializationError::Ok); + } + SECTION("{H:1,W:2}") { + check( + "\xDE\x00\x02\xA1H\x01\xA1W\x02", DeserializationError::NoMemory); + check( + "\xDE\x00\x02\xA1H\x01\xA1W\x02", DeserializationError::Ok); + } + } + + SECTION("map 32") { + SECTION("{}") { + check("\xDF\x00\x00\x00\x00", + DeserializationError::Ok); + } + SECTION("{H:1}") { + check("\xDF\x00\x00\x00\x01\xA1H\x01", + DeserializationError::NoMemory); + check( + "\xDF\x00\x00\x00\x01\xA1H\x01", DeserializationError::Ok); + } + SECTION("{H:1,W:2}") { + check( + "\xDF\x00\x00\x00\x02\xA1H\x01\xA1W\x02", + DeserializationError::NoMemory); + check( + "\xDF\x00\x00\x00\x02\xA1H\x01\xA1W\x02", DeserializationError::Ok); + } + } +} diff --git a/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/deserializeVariant.cpp b/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/deserializeVariant.cpp new file mode 100644 index 0000000..87f38d6 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/deserializeVariant.cpp @@ -0,0 +1,147 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +template +static void check(const char* input, U expected) { + DynamicJsonDocument doc(4096); + + DeserializationError error = deserializeMsgPack(doc, input); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(doc.as() == expected); +} + +#if ARDUINOJSON_USE_LONG_LONG == 0 +static void checkNotSupported(const char* input) { + DynamicJsonDocument doc(4096); + DeserializationError error = deserializeMsgPack(doc, input); + REQUIRE(error == DeserializationError::Ok); + REQUIRE(doc.isNull()); +} +#endif + +static void checkIsNull(const char* input) { + DynamicJsonDocument doc(4096); + + DeserializationError error = deserializeMsgPack(doc, input); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(doc.as().isNull()); +} + +TEST_CASE("deserialize MsgPack value") { + SECTION("nil") { + checkIsNull("\xc0"); + } + + SECTION("bool") { + check("\xc2", false); + check("\xc3", true); + } + + SECTION("positive fixint") { + check("\x00", 0); + check("\x7F", 127); + } + + SECTION("negative fixint") { + check("\xe0", -32); + check("\xff", -1); + } + + SECTION("uint 8") { + check("\xcc\x00", 0); + check("\xcc\xff", 255); + } + + SECTION("uint 16") { + check("\xcd\x00\x00", 0); + check("\xcd\xFF\xFF", 65535); + check("\xcd\x30\x39", 12345); + } + + SECTION("uint 32") { + check("\xCE\x00\x00\x00\x00", 0x00000000U); + check("\xCE\xFF\xFF\xFF\xFF", 0xFFFFFFFFU); + check("\xCE\x12\x34\x56\x78", 0x12345678U); + } + + SECTION("uint 64") { +#if ARDUINOJSON_USE_LONG_LONG + check("\xCF\x00\x00\x00\x00\x00\x00\x00\x00", 0U); + check("\xCF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", + 0xFFFFFFFFFFFFFFFFU); + check("\xCF\x12\x34\x56\x78\x9A\xBC\xDE\xF0", + 0x123456789ABCDEF0U); +#else + checkNotSupported("\xCF\x00\x00\x00\x00\x00\x00\x00\x00"); + checkNotSupported("\xCF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"); + checkNotSupported("\xCF\x12\x34\x56\x78\x9A\xBC\xDE\xF0"); +#endif + } + + SECTION("int 8") { + check("\xd0\x00", 0); + check("\xd0\xff", -1); + } + + SECTION("int 16") { + check("\xD1\x00\x00", 0); + check("\xD1\xFF\xFF", -1); + check("\xD1\xCF\xC7", -12345); + } + + SECTION("int 32") { + check("\xD2\x00\x00\x00\x00", 0); + check("\xD2\xFF\xFF\xFF\xFF", -1); + check("\xD2\xB6\x69\xFD\x2E", -1234567890); + } + + SECTION("int 64") { +#if ARDUINOJSON_USE_LONG_LONG + check("\xD3\x00\x00\x00\x00\x00\x00\x00\x00", int64_t(0U)); + check("\xD3\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", + int64_t(0xFFFFFFFFFFFFFFFFU)); + check("\xD3\x12\x34\x56\x78\x9A\xBC\xDE\xF0", + int64_t(0x123456789ABCDEF0)); +#else + checkNotSupported("\xD3\x00\x00\x00\x00\x00\x00\x00\x00"); + checkNotSupported("\xD3\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"); + checkNotSupported("\xD3\x12\x34\x56\x78\x9A\xBC\xDE\xF0"); +#endif + } + + SECTION("float 32") { + check("\xCA\x00\x00\x00\x00", 0.0f); + check("\xCA\x40\x48\xF5\xC3", 3.14f); + } + + SECTION("float 64") { + check("\xCB\x00\x00\x00\x00\x00\x00\x00\x00", 0.0); + check("\xCB\x40\x09\x21\xCA\xC0\x83\x12\x6F", 3.1415); + } + + SECTION("fixstr") { + check("\xA0", std::string("")); + check("\xABhello world", std::string("hello world")); + check("\xBFhello world hello world hello !", + std::string("hello world hello world hello !")); + } + + SECTION("str 8") { + check("\xd9\x05hello", std::string("hello")); + } + + SECTION("str 16") { + check("\xda\x00\x05hello", std::string("hello")); + } + + SECTION("str 32") { + check("\xdb\x00\x00\x00\x05hello", std::string("hello")); + } +} diff --git a/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/doubleToFloat.cpp b/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/doubleToFloat.cpp new file mode 100644 index 0000000..fb2c25d --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/doubleToFloat.cpp @@ -0,0 +1,25 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +using namespace ArduinoJson::detail; + +template +static void check(const char* input, T expected) { + T actual; + uint8_t* f = reinterpret_cast(&actual); + const uint8_t* d = reinterpret_cast(input); + doubleToFloat(d, f); + fixEndianess(actual); + CHECK(actual == expected); +} + +TEST_CASE("doubleToFloat()") { + check("\x40\x09\x21\xCA\xC0\x83\x12\x6F", 3.1415f); + check("\x00\x00\x00\x00\x00\x00\x00\x00", 0.0f); + check("\x80\x00\x00\x00\x00\x00\x00\x00", -0.0f); + check("\xC0\x5E\xDC\xCC\xCC\xCC\xCC\xCD", -123.45f); +} diff --git a/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/filter.cpp b/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/filter.cpp new file mode 100644 index 0000000..78700db --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/filter.cpp @@ -0,0 +1,1135 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +#include + +using namespace ArduinoJson::detail; + +TEST_CASE("deserializeMsgPack() filter") { + StaticJsonDocument<4096> doc; + DeserializationError error; + + StaticJsonDocument<200> filter; + DeserializationOption::Filter filterOpt(filter); + + SECTION("root is fixmap") { + SECTION("filter = {include:true,ignore:false)") { + filter["include"] = true; + filter["ignore"] = false; + + SECTION("input truncated after ignored key") { + error = deserializeMsgPack(doc, "\x82\xA6ignore", 8, filterOpt); + + CHECK(error == DeserializationError::IncompleteInput); + CHECK(doc.as() == "{}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(0)); + } + + SECTION("input truncated after inside skipped uint 8") { + error = deserializeMsgPack(doc, "\x82\xA6ignore\xCC\x2A\xA7include\x2A", + 9, filterOpt); + + CHECK(error == DeserializationError::IncompleteInput); + CHECK(doc.as() == "{}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(0)); + } + + SECTION("input truncated after before skipped string size") { + error = deserializeMsgPack(doc, "\x82\xA6ignore\xd9", 9, filterOpt); + + CHECK(error == DeserializationError::IncompleteInput); + CHECK(doc.as() == "{}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(0)); + } + + SECTION("input truncated after before skipped ext size") { + error = deserializeMsgPack(doc, "\x82\xA6ignore\xC7", 9, filterOpt); + + CHECK(error == DeserializationError::IncompleteInput); + CHECK(doc.as() == "{}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(0)); + } + + SECTION("skip nil") { + error = deserializeMsgPack(doc, "\x82\xA6ignore\xC0\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("reject 0xc1") { + error = deserializeMsgPack(doc, "\x82\xA6ignore\xC1\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::InvalidInput); + } + + SECTION("skip false") { + error = deserializeMsgPack(doc, "\x82\xA6ignore\xC2\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip true") { + error = deserializeMsgPack(doc, "\x82\xA6ignore\xC3\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip positive fixint") { + error = deserializeMsgPack(doc, "\x82\xA6ignore\x2A\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip negative fixint") { + error = deserializeMsgPack(doc, "\x82\xA6ignore\xFF\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip uint 8") { + error = deserializeMsgPack(doc, "\x82\xA6ignore\xCC\x2A\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip int 8") { + error = deserializeMsgPack(doc, "\x82\xA6ignore\xD0\x2A\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip uint 16") { + error = deserializeMsgPack( + doc, "\x82\xA6ignore\xcd\x30\x39\xA7include\x2A", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip int 16") { + error = deserializeMsgPack( + doc, "\x82\xA6ignore\xD1\xCF\xC7\xA7include\x2A", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip uint 32") { + error = deserializeMsgPack( + doc, "\x82\xA6ignore\xCE\x12\x34\x56\x78\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip int 32") { + error = deserializeMsgPack( + doc, "\x82\xA6ignore\xD2\xB6\x69\xFD\x2E\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip uint 64") { + error = deserializeMsgPack( + doc, + "\x82\xA6ignore\xCF\x12\x34\x56\x78\x9A\xBC\xDE\xF0\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip int 64") { + error = deserializeMsgPack( + doc, + "\x82\xA6ignore\xD3\x12\x34\x56\x78\x9A\xBC\xDE\xF0\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip float 32") { + error = deserializeMsgPack( + doc, "\x82\xA6ignore\xCA\x40\x48\xF5\xC3\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip float 64") { + error = deserializeMsgPack( + doc, + "\x82\xA6ignore\xCB\x40\x09\x21\xCA\xC0\x83\x12\x6F\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip fixstr") { + error = deserializeMsgPack( + doc, "\x82\xA6ignore\xABhello world\xA7include\x2A", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip str 8") { + error = deserializeMsgPack( + doc, "\x82\xA6ignore\xd9\x05hello\xA7include\x2A", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip str 16") { + error = deserializeMsgPack( + doc, "\x82\xA6ignore\xda\x00\x05hello\xA7include\x2A", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip str 32") { + error = deserializeMsgPack( + doc, "\x82\xA6ignore\xdb\x00\x00\x00\x05hello\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip bin 8") { + error = deserializeMsgPack( + doc, "\x82\xA6ignore\xC4\x05hello\xA7include\x2A", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip bin 16") { + error = deserializeMsgPack( + doc, "\x82\xA6ignore\xC5\x00\x05hello\xA7include\x2A", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip bin 32") { + error = deserializeMsgPack( + doc, "\x82\xA6ignore\xC6\x00\x00\x00\x05hello\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip fixarray") { + error = deserializeMsgPack( + doc, "\x82\xA6ignore\x92\x01\x02\xA7include\x2A", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip array 16") { + error = deserializeMsgPack( + doc, "\x82\xA6ignore\xDC\x00\x02\xA5hello\xA5world\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip array 32") { + error = deserializeMsgPack( + doc, + "\x82\xA6ignore" + "\xDD\x00\x00\x00\x02\xCA\x00\x00\x00\x00\xCA\x40\x48\xF5\xC3" + "\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip fixmap") { + error = deserializeMsgPack( + doc, "\x82\xA6ignore\x82\xA3one\x01\xA3two\x02\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip map 16") { + error = deserializeMsgPack(doc, + "\x82\xA6ignore" + "\xDE\x00\x02\xA1H\xA5hello\xA1W\xA5world" + "\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip map 32") { + error = deserializeMsgPack(doc, + "\x82\xA6ignore" + "\xDF\x00\x00\x00\x02" + "\xA4zero\xCA\x00\x00\x00\x00" + "\xA2pi\xCA\x40\x48\xF5\xC3" + "\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip fixext 1") { + error = deserializeMsgPack(doc, + "\x82\xA6ignore" + "\xd4\x01\x02" + "\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip fixext 2") { + error = deserializeMsgPack(doc, + "\x82\xA6ignore" + "\xd5\x01\x02\x03" + "\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip fixext 4") { + error = deserializeMsgPack(doc, + "\x82\xA6ignore" + "\xd6\x01\x02\x03\x04\x05" + "\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip fixext 8") { + error = deserializeMsgPack(doc, + "\x82\xA6ignore" + "\xd7\x01\x02\x03\x04\x05\x06\x07\x08\x09" + "\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip fixext 16") { + error = + deserializeMsgPack(doc, + "\x82\xA6ignore" + "\xd8\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A" + "\x0B\x0C\x0D\x0E\x0F\x10\x11" + "\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip ext 8") { + error = deserializeMsgPack(doc, + "\x82\xA6ignore" + "\xc7\x02\x00\x01\x02" + "\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip ext 16") { + error = deserializeMsgPack(doc, + "\x82\xA6ignore" + "\xc8\x00\x02\x00\x01\x02" + "\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + + SECTION("skip ext 32") { + error = deserializeMsgPack(doc, + "\x82\xA6ignore" + "\xc9\x00\x00\x00\x02\x00\x01\x02" + "\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(1) + 8); + } + } + + SECTION("Filter = {arronly:[{measure:true}],include:true}") { + filter["onlyarr"][0]["measure"] = true; + filter["include"] = true; + + CAPTURE(filter.as()); + + SECTION("include fixarray") { + error = deserializeMsgPack(doc, + "\x82\xA7onlyarr\x92" + "\x82\xA8location\x01\xA7measure\x02" + "\x82\xA8location\x02\xA7measure\x04" + "\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == + "{\"onlyarr\":[{\"measure\":2},{\"measure\":4}],\"include\":42}"); + CHECK(doc.memoryUsage() == + JSON_ARRAY_SIZE(2) + 2 * JSON_OBJECT_SIZE(2) + 24); + } + + SECTION("include array 16") { + error = deserializeMsgPack(doc, + "\x82\xA7onlyarr" + "\xDC\x00\x02" + "\x82\xA8location\x01\xA7measure\x02" + "\x82\xA8location\x02\xA7measure\x04" + "\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == + "{\"onlyarr\":[{\"measure\":2},{\"measure\":4}],\"include\":42}"); + CHECK(doc.memoryUsage() == + JSON_ARRAY_SIZE(2) + 2 * JSON_OBJECT_SIZE(2) + 24); + } + + SECTION("include array 32") { + error = deserializeMsgPack(doc, + "\x82\xA7onlyarr" + "\xDD\x00\x00\x00\x02" + "\x82\xA8location\x01\xA7measure\x02" + "\x82\xA8location\x02\xA7measure\x04" + "\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == + "{\"onlyarr\":[{\"measure\":2},{\"measure\":4}],\"include\":42}"); + CHECK(doc.memoryUsage() == + JSON_ARRAY_SIZE(2) + 2 * JSON_OBJECT_SIZE(2) + 24); + } + + SECTION("skip null") { + error = deserializeMsgPack(doc, "\x82\xA7onlyarr\xC0\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyarr\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip false") { + error = deserializeMsgPack(doc, "\x82\xA7onlyarr\xC2\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyarr\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip true") { + error = deserializeMsgPack(doc, "\x82\xA7onlyarr\xC3\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyarr\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip positive fixint") { + error = deserializeMsgPack(doc, "\x82\xA7onlyarr\x2A\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyarr\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip negative fixint") { + error = deserializeMsgPack(doc, "\x82\xA7onlyarr\xFF\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyarr\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip uint 8") { + error = deserializeMsgPack( + doc, "\x82\xA7onlyarr\xCC\x2A\xA7include\x2A", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyarr\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip uint 16") { + error = deserializeMsgPack( + doc, "\x82\xA7onlyarr\xcd\x30\x39\xA7include\x2A", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyarr\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip uint 32") { + error = deserializeMsgPack( + doc, "\x82\xA7onlyarr\xCE\x12\x34\x56\x78\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyarr\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip uint 64") { + error = deserializeMsgPack(doc, + "\x82\xA7onlyarr\xCF\x12\x34\x56\x78\x9A\xBC" + "\xDE\xF0\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyarr\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip int 8") { + error = deserializeMsgPack( + doc, "\x82\xA7onlyarr\xD0\x2A\xA7include\x2A", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyarr\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip int 16") { + error = deserializeMsgPack( + doc, "\x82\xA7onlyarr\xD1\xCF\xC7\xA7include\x2A", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyarr\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip int 32") { + error = deserializeMsgPack( + doc, "\x82\xA7onlyarr\xD2\xB6\x69\xFD\x2E\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyarr\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip int 64") { + error = deserializeMsgPack(doc, + "\x82\xA7onlyarr\xD3\x12\x34\x56\x78\x9A\xBC" + "\xDE\xF0\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyarr\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip float 32") { + error = deserializeMsgPack( + doc, "\x82\xA7onlyarr\xCA\x40\x48\xF5\xC3\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyarr\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip float 64") { + error = deserializeMsgPack(doc, + "\x82\xA7onlyarr\xCB\x40\x09\x21\xCA\xC0\x83" + "\x12\x6F\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyarr\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip fixstr") { + error = deserializeMsgPack( + doc, "\x82\xA7onlyarr\xABhello world\xA7include\x2A", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyarr\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip str 8") { + error = deserializeMsgPack( + doc, "\x82\xA7onlyarr\xd9\x05hello\xA7include\x2A", filterOpt); + + CHECK(error == DeserializationError::Ok); + } + + SECTION("skip str 16") { + error = deserializeMsgPack( + doc, "\x82\xA7onlyarr\xda\x00\x05hello\xA7include\x2A", filterOpt); + + CHECK(doc.as() == "{\"onlyarr\":null,\"include\":42}"); + } + + SECTION("skip str 32") { + error = deserializeMsgPack( + doc, "\x82\xA7onlyarr\xdb\x00\x00\x00\x05hello\xA7include\x2A", + filterOpt); + + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip fixmap") { + error = deserializeMsgPack( + doc, "\x82\xA7onlyarr\x82\xA3one\x01\xA3two\x02\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyarr\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip map 16") { + error = deserializeMsgPack(doc, + "\x82\xA7onlyarr" + "\xDE\x00\x02\xA1H\xA5hello\xA1W\xA5world" + "\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyarr\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip map 32") { + error = deserializeMsgPack(doc, + "\x82\xA7onlyarr" + "\xDF\x00\x00\x00\x02" + "\xA4zero\xCA\x00\x00\x00\x00" + "\xA2pi\xCA\x40\x48\xF5\xC3" + "\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyarr\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + } + } + + SECTION("root is fixarray") { + SECTION("filter = [false, true]") { + filter[0] = false; // only the first elment of the filter matters + filter[1] = true; // so this one is ignored + + SECTION("input = [1,2,3]") { + error = deserializeMsgPack(doc, "\x93\x01\x02\x03", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "[]"); + CHECK(doc.memoryUsage() == JSON_ARRAY_SIZE(0)); + } + } + + SECTION("filter = [true, false]") { + filter[0] = true; // only the first elment of the filter matters + filter[1] = false; // so this one is ignored + + SECTION("input = [1,2,3]") { + error = deserializeMsgPack(doc, "\x93\x01\x02\x03", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "[1,2,3]"); + CHECK(doc.memoryUsage() == JSON_ARRAY_SIZE(3)); + } + } + } + + SECTION("Filter = {onlyobj:{measure:true},include:true}") { + filter["onlyobj"]["measure"] = true; + filter["include"] = true; + + CAPTURE(filter.as()); + + SECTION("include fixmap") { + error = deserializeMsgPack(doc, + "\x82\xA7onlyobj" + "\x82\xA8location\x01\xA7measure\x02" + "\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == + "{\"onlyobj\":{\"measure\":2},\"include\":42}"); + CHECK(doc.memoryUsage() == + JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(1) + 24); + } + + SECTION("include map 16") { + error = deserializeMsgPack(doc, + "\x82\xA7onlyobj" + "\xDE\x00\x02\xA8location\x01\xA7measure\x02" + "\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == + "{\"onlyobj\":{\"measure\":2},\"include\":42}"); + CHECK(doc.memoryUsage() == + JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(1) + 24); + } + + SECTION("include map 32") { + error = deserializeMsgPack(doc, + "\x82\xA7onlyobj" + "\xDF\x00\x00\x00\x02" + "\xA8location\x01\xA7measure\x02" + "\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == + "{\"onlyobj\":{\"measure\":2},\"include\":42}"); + CHECK(doc.memoryUsage() == + JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(1) + 24); + } + + SECTION("skip null") { + error = deserializeMsgPack(doc, "\x82\xA7onlyobj\xC0\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyobj\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip false") { + error = deserializeMsgPack(doc, "\x82\xA7onlyobj\xC2\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyobj\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip true") { + error = deserializeMsgPack(doc, "\x82\xA7onlyobj\xC3\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyobj\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip positive fixint") { + error = deserializeMsgPack(doc, "\x82\xA7onlyobj\x2A\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyobj\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip negative fixint") { + error = deserializeMsgPack(doc, "\x82\xA7onlyobj\xFF\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyobj\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip uint 8") { + error = deserializeMsgPack(doc, "\x82\xA7onlyobj\xCC\x2A\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyobj\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip uint 16") { + error = deserializeMsgPack( + doc, "\x82\xA7onlyobj\xcd\x30\x39\xA7include\x2A", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyobj\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip uint 32") { + error = deserializeMsgPack( + doc, "\x82\xA7onlyobj\xCE\x12\x34\x56\x78\xA7include\x2A", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyobj\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip uint 64") { + error = deserializeMsgPack(doc, + "\x82\xA7onlyobj\xCF\x12\x34\x56\x78\x9A\xBC" + "\xDE\xF0\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyobj\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip int 8") { + error = deserializeMsgPack(doc, "\x82\xA7onlyobj\xD0\x2A\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyobj\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip int 16") { + error = deserializeMsgPack( + doc, "\x82\xA7onlyobj\xD1\xCF\xC7\xA7include\x2A", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyobj\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip int 32") { + error = deserializeMsgPack( + doc, "\x82\xA7onlyobj\xD2\xB6\x69\xFD\x2E\xA7include\x2A", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyobj\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip int 64") { + error = deserializeMsgPack(doc, + "\x82\xA7onlyobj\xD3\x12\x34\x56\x78\x9A\xBC" + "\xDE\xF0\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyobj\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip float 32") { + error = deserializeMsgPack( + doc, "\x82\xA7onlyobj\xCA\x40\x48\xF5\xC3\xA7include\x2A", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyobj\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip float 64") { + error = deserializeMsgPack(doc, + "\x82\xA7onlyobj\xCB\x40\x09\x21\xCA\xC0\x83" + "\x12\x6F\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyobj\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip fixstr") { + error = deserializeMsgPack( + doc, "\x82\xA7onlyobj\xABhello world\xA7include\x2A", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyobj\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip str 8") { + error = deserializeMsgPack( + doc, "\x82\xA7onlyobj\xd9\x05hello\xA7include\x2A", filterOpt); + + CHECK(error == DeserializationError::Ok); + } + + SECTION("skip str 16") { + error = deserializeMsgPack( + doc, "\x82\xA7onlyobj\xda\x00\x05hello\xA7include\x2A", filterOpt); + + CHECK(doc.as() == "{\"onlyobj\":null,\"include\":42}"); + } + + SECTION("skip str 32") { + error = deserializeMsgPack( + doc, "\x82\xA7onlyobj\xdb\x00\x00\x00\x05hello\xA7include\x2A", + filterOpt); + + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip fixarray") { + error = deserializeMsgPack( + doc, "\x82\xA7onlyobj\x92\x01\x02\xA7include\x2A", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyobj\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip array 16") { + error = deserializeMsgPack(doc, + "\x82\xA7onlyobj\xDC\x00\x01\xA7" + "example\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyobj\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + + SECTION("skip array 32") { + error = deserializeMsgPack(doc, + "\x82\xA7onlyobj" + "\xDD\x00\x00\x00\x02\x01\x02" + "\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyobj\":null,\"include\":42}"); + CHECK(doc.memoryUsage() == JSON_OBJECT_SIZE(2) + 16); + } + } + + SECTION("filter = true") { + filter.set(true); + + error = deserializeMsgPack(doc, "\x90", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.is() == true); + CHECK(doc.size() == 0); + } + + SECTION("filter = false") { + filter.set(false); + + SECTION("input = fixarray") { + error = deserializeMsgPack(doc, "\x92\x01\x02", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.isNull() == true); + } + + SECTION("input = array 16") { + error = deserializeMsgPack(doc, "\xDC\x00\x02\x01\x02", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.isNull() == true); + } + + SECTION("array too deep") { + error = deserializeMsgPack(doc, "\x91\x91\x91\x91\x91", 5, filterOpt, + DeserializationOption::NestingLimit(4)); + + CHECK(error == DeserializationError::TooDeep); + } + + SECTION("object too deep") { + error = deserializeMsgPack( + doc, "\x81\xA1z\x81\xA1z\x81\xA1z\x81\xA1z\x81\xA1z", 15, filterOpt, + DeserializationOption::NestingLimit(4)); + + CHECK(error == DeserializationError::TooDeep); + } + } +} + +TEST_CASE("Zero-copy mode") { // issue #1697 + char input[] = "\x82\xA7include\x01\xA6ignore\x02"; + + StaticJsonDocument<256> filter; + filter["include"] = true; + + StaticJsonDocument<256> doc; + DeserializationError err = + deserializeMsgPack(doc, input, 18, DeserializationOption::Filter(filter)); + + CHECK(err == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":1}"); +} + +TEST_CASE("Overloads") { + StaticJsonDocument<256> doc; + StaticJsonDocument<256> filter; + + using namespace DeserializationOption; + + // deserializeMsgPack(..., Filter) + + SECTION("const char*, Filter") { + deserializeMsgPack(doc, "{}", Filter(filter)); + } + + SECTION("const char*, size_t, Filter") { + deserializeMsgPack(doc, "{}", 2, Filter(filter)); + } + + SECTION("const std::string&, Filter") { + deserializeMsgPack(doc, std::string("{}"), Filter(filter)); + } + + SECTION("std::istream&, Filter") { + std::stringstream s("{}"); + deserializeMsgPack(doc, s, Filter(filter)); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("char[n], Filter") { + size_t i = 4; + char vla[i]; + strcpy(vla, "{}"); + deserializeMsgPack(doc, vla, Filter(filter)); + } +#endif + + // deserializeMsgPack(..., Filter, NestingLimit) + + SECTION("const char*, Filter, NestingLimit") { + deserializeMsgPack(doc, "{}", Filter(filter), NestingLimit(5)); + } + + SECTION("const char*, size_t, Filter, NestingLimit") { + deserializeMsgPack(doc, "{}", 2, Filter(filter), NestingLimit(5)); + } + + SECTION("const std::string&, Filter, NestingLimit") { + deserializeMsgPack(doc, std::string("{}"), Filter(filter), NestingLimit(5)); + } + + SECTION("std::istream&, Filter, NestingLimit") { + std::stringstream s("{}"); + deserializeMsgPack(doc, s, Filter(filter), NestingLimit(5)); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("char[n], Filter, NestingLimit") { + size_t i = 4; + char vla[i]; + strcpy(vla, "{}"); + deserializeMsgPack(doc, vla, Filter(filter), NestingLimit(5)); + } +#endif + + // deserializeMsgPack(..., NestingLimit, Filter) + + SECTION("const char*, NestingLimit, Filter") { + deserializeMsgPack(doc, "{}", NestingLimit(5), Filter(filter)); + } + + SECTION("const char*, size_t, NestingLimit, Filter") { + deserializeMsgPack(doc, "{}", 2, NestingLimit(5), Filter(filter)); + } + + SECTION("const std::string&, NestingLimit, Filter") { + deserializeMsgPack(doc, std::string("{}"), NestingLimit(5), Filter(filter)); + } + + SECTION("std::istream&, NestingLimit, Filter") { + std::stringstream s("{}"); + deserializeMsgPack(doc, s, NestingLimit(5), Filter(filter)); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("char[n], NestingLimit, Filter") { + size_t i = 4; + char vla[i]; + strcpy(vla, "{}"); + deserializeMsgPack(doc, vla, NestingLimit(5), Filter(filter)); + } +#endif +} diff --git a/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/incompleteInput.cpp b/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/incompleteInput.cpp new file mode 100644 index 0000000..6a56388 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/incompleteInput.cpp @@ -0,0 +1,158 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +DeserializationError deserialize(const char* input, size_t len) { + DynamicJsonDocument doc(4096); + + return deserializeMsgPack(doc, input, len); +} + +void checkAllSizes(const char* input, size_t len) { + REQUIRE(deserialize(input, len) == DeserializationError::Ok); + + while (--len) { + REQUIRE(deserialize(input, len) == DeserializationError::IncompleteInput); + } +} + +TEST_CASE("deserializeMsgPack() returns IncompleteInput") { + SECTION("empty input") { + checkAllSizes("\x00", 1); + } + + SECTION("fixarray") { + checkAllSizes("\x91\x01", 2); + } + + SECTION("array 16") { + checkAllSizes("\xDC\x00\x01\x01", 4); + } + + SECTION("array 32") { + checkAllSizes("\xDD\x00\x00\x00\x01\x01", 6); + } + + SECTION("fixmap") { + checkAllSizes("\x81\xA3one\x01", 6); + } + + SECTION("map 16") { + checkAllSizes("\xDE\x00\x01\xA3one\x01", 8); + } + + SECTION("map 32") { + checkAllSizes("\xDF\x00\x00\x00\x01\xA3one\x01", 10); + checkAllSizes("\xDF\x00\x00\x00\x01\xd9\x03one\x01", 11); + } + + SECTION("uint 8") { + checkAllSizes("\xcc\x01", 2); + } + + SECTION("uint 16") { + checkAllSizes("\xcd\x00\x01", 3); + } + + SECTION("uint 32") { + checkAllSizes("\xCE\x00\x00\x00\x01", 5); + } + +#if ARDUINOJSON_USE_LONG_LONG + SECTION("uint 64") { + checkAllSizes("\xCF\x00\x00\x00\x00\x00\x00\x00\x00", 9); + } +#endif + + SECTION("int 8") { + checkAllSizes("\xD0\x01", 2); + } + + SECTION("int 16") { + checkAllSizes("\xD1\x00\x01", 3); + } + + SECTION("int 32") { + checkAllSizes("\xD2\x00\x00\x00\x01", 5); + } + +#if ARDUINOJSON_USE_LONG_LONG + SECTION("int 64") { + checkAllSizes("\xD3\x00\x00\x00\x00\x00\x00\x00\x00", 9); + } +#endif + + SECTION("float 32") { + checkAllSizes("\xCA\x40\x48\xF5\xC3", 5); + } + + SECTION("float 64") { + checkAllSizes("\xCB\x40\x09\x21\xCA\xC0\x83\x12\x6F", 9); + } + + SECTION("fixstr") { + checkAllSizes("\xABhello world", 12); + } + + SECTION("str 8") { + checkAllSizes("\xd9\x05hello", 7); + } + + SECTION("str 16") { + checkAllSizes("\xda\x00\x05hello", 8); + } + + SECTION("str 32") { + checkAllSizes("\xdb\x00\x00\x00\x05hello", 10); + } + + SECTION("bin 8") { + checkAllSizes("\xc4\x01X", 3); + } + + SECTION("bin 16") { + checkAllSizes("\xc5\x00\x01X", 4); + } + + SECTION("bin 32") { + checkAllSizes("\xc6\x00\x00\x00\x01X", 6); + } + + SECTION("ext 8") { + checkAllSizes("\xc7\x01\x01\x01", 4); + } + + SECTION("ext 16") { + checkAllSizes("\xc8\x00\x01\x01\x01", 5); + } + + SECTION("ext 32") { + checkAllSizes("\xc9\x00\x00\x00\x01\x01\x01", 7); + } + + SECTION("fixext 1") { + checkAllSizes("\xd4\x01\x01", 3); + } + + SECTION("fixext 2") { + checkAllSizes("\xd5\x01\x01\x02", 4); + } + + SECTION("fixext 4") { + checkAllSizes("\xd6\x01\x01\x02\x03\x04", 6); + } + + SECTION("fixext 8") { + checkAllSizes("\xd7\x01\x01\x02\x03\x04\x05\x06\x07\x08", 10); + } + + SECTION("fixext 16") { + checkAllSizes( + "\xd8\x01\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E" + "\x0F\x10", + 18); + } +} diff --git a/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/input_types.cpp b/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/input_types.cpp new file mode 100644 index 0000000..783aaa2 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/input_types.cpp @@ -0,0 +1,95 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +#include "CustomReader.hpp" + +TEST_CASE("deserializeMsgPack(const std::string&)") { + DynamicJsonDocument doc(4096); + + SECTION("should accept const string") { + const std::string input("\x92\x01\x02"); + + DeserializationError err = deserializeMsgPack(doc, input); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("should accept temporary string") { + DeserializationError err = + deserializeMsgPack(doc, std::string("\x92\x01\x02")); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("should duplicate content") { + std::string input("\x91\xA5hello"); + + DeserializationError err = deserializeMsgPack(doc, input); + input[2] = 'X'; // alter the string tomake sure we made a copy + + JsonArray array = doc.as(); + REQUIRE(err == DeserializationError::Ok); + REQUIRE(std::string("hello") == array[0]); + } + + SECTION("should accept a zero in input") { + DeserializationError err = + deserializeMsgPack(doc, std::string("\x92\x00\x02", 3)); + + REQUIRE(err == DeserializationError::Ok); + JsonArray arr = doc.as(); + REQUIRE(arr[0] == 0); + REQUIRE(arr[1] == 2); + } +} + +TEST_CASE("deserializeMsgPack(std::istream&)") { + DynamicJsonDocument doc(4096); + + SECTION("should accept a zero in input") { + std::istringstream input(std::string("\x92\x00\x02", 3)); + + DeserializationError err = deserializeMsgPack(doc, input); + + REQUIRE(err == DeserializationError::Ok); + JsonArray arr = doc.as(); + REQUIRE(arr[0] == 0); + REQUIRE(arr[1] == 2); + } + + SECTION("should detect incomplete input") { + std::istringstream input("\x92\x00\x02"); + + DeserializationError err = deserializeMsgPack(doc, input); + + REQUIRE(err == DeserializationError::IncompleteInput); + } +} + +#ifdef HAS_VARIABLE_LENGTH_ARRAY +TEST_CASE("deserializeMsgPack(VLA)") { + size_t i = 16; + char vla[i]; + memcpy(vla, "\xDE\x00\x01\xA5Hello\xA5world", 15); + + StaticJsonDocument doc; + DeserializationError err = deserializeMsgPack(doc, vla); + + REQUIRE(err == DeserializationError::Ok); +} +#endif + +TEST_CASE("deserializeMsgPack(CustomReader)") { + DynamicJsonDocument doc(4096); + CustomReader reader("\x92\xA5Hello\xA5world"); + DeserializationError err = deserializeMsgPack(doc, reader); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.size() == 2); + REQUIRE(doc[0] == "Hello"); + REQUIRE(doc[1] == "world"); +} diff --git a/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/misc.cpp b/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/misc.cpp new file mode 100644 index 0000000..25137b3 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/misc.cpp @@ -0,0 +1,26 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +#include + +TEST_CASE("deserializeMsgPack() returns EmptyInput") { + StaticJsonDocument<100> doc; + + SECTION("from sized buffer") { + DeserializationError err = deserializeMsgPack(doc, "", 0); + + REQUIRE(err == DeserializationError::EmptyInput); + } + + SECTION("from stream") { + std::istringstream input(""); + + DeserializationError err = deserializeMsgPack(doc, input); + + REQUIRE(err == DeserializationError::EmptyInput); + } +} diff --git a/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/nestingLimit.cpp b/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/nestingLimit.cpp new file mode 100644 index 0000000..2936415 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/nestingLimit.cpp @@ -0,0 +1,87 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +#include + +#define SHOULD_WORK(expression) REQUIRE(DeserializationError::Ok == expression); +#define SHOULD_FAIL(expression) \ + REQUIRE(DeserializationError::TooDeep == expression); + +TEST_CASE("JsonDeserializer nesting") { + DynamicJsonDocument doc(4096); + + SECTION("Input = const char*") { + SECTION("limit = 0") { + DeserializationOption::NestingLimit nesting(0); + SHOULD_WORK(deserializeMsgPack(doc, "\xA1H", nesting)); // "H" + SHOULD_FAIL(deserializeMsgPack(doc, "\x90", nesting)); // [] + SHOULD_FAIL(deserializeMsgPack(doc, "\x80", nesting)); // {} + } + + SECTION("limit = 1") { + DeserializationOption::NestingLimit nesting(1); + SHOULD_WORK(deserializeMsgPack(doc, "\x90", nesting)); // {} + SHOULD_WORK(deserializeMsgPack(doc, "\x80", nesting)); // [] + SHOULD_FAIL(deserializeMsgPack(doc, "\x81\xA1H\x80", nesting)); // {H:{}} + SHOULD_FAIL(deserializeMsgPack(doc, "\x91\x90", nesting)); // [[]] + } + } + + SECTION("char* and size_t") { + SECTION("limit = 0") { + DeserializationOption::NestingLimit nesting(0); + SHOULD_WORK(deserializeMsgPack(doc, "\xA1H", 2, nesting)); + SHOULD_FAIL(deserializeMsgPack(doc, "\x90", 1, nesting)); + SHOULD_FAIL(deserializeMsgPack(doc, "\x80", 1, nesting)); + } + + SECTION("limit = 1") { + DeserializationOption::NestingLimit nesting(1); + SHOULD_WORK(deserializeMsgPack(doc, "\x90", 1, nesting)); + SHOULD_WORK(deserializeMsgPack(doc, "\x80", 1, nesting)); + SHOULD_FAIL(deserializeMsgPack(doc, "\x81\xA1H\x80", 4, nesting)); + SHOULD_FAIL(deserializeMsgPack(doc, "\x91\x90", 2, nesting)); + } + } + + SECTION("Input = std::string") { + using std::string; + + SECTION("limit = 0") { + DeserializationOption::NestingLimit nesting(0); + SHOULD_WORK(deserializeMsgPack(doc, string("\xA1H"), nesting)); + SHOULD_FAIL(deserializeMsgPack(doc, string("\x90"), nesting)); + SHOULD_FAIL(deserializeMsgPack(doc, string("\x80"), nesting)); + } + + SECTION("limit = 1") { + DeserializationOption::NestingLimit nesting(1); + SHOULD_WORK(deserializeMsgPack(doc, string("\x90"), nesting)); + SHOULD_WORK(deserializeMsgPack(doc, string("\x80"), nesting)); + SHOULD_FAIL(deserializeMsgPack(doc, string("\x81\xA1H\x80"), nesting)); + SHOULD_FAIL(deserializeMsgPack(doc, string("\x91\x90"), nesting)); + } + } + + SECTION("Input = std::istream") { + SECTION("limit = 0") { + DeserializationOption::NestingLimit nesting(0); + std::istringstream good("\xA1H"); // "H" + std::istringstream bad("\x90"); // [] + SHOULD_WORK(deserializeMsgPack(doc, good, nesting)); + SHOULD_FAIL(deserializeMsgPack(doc, bad, nesting)); + } + + SECTION("limit = 1") { + DeserializationOption::NestingLimit nesting(1); + std::istringstream good("\x90"); // [] + std::istringstream bad("\x91\x90"); // [[]] + SHOULD_WORK(deserializeMsgPack(doc, good, nesting)); + SHOULD_FAIL(deserializeMsgPack(doc, bad, nesting)); + } + } +} diff --git a/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/notSupported.cpp b/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/notSupported.cpp new file mode 100644 index 0000000..2be0f1e --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MsgPackDeserializer/notSupported.cpp @@ -0,0 +1,82 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +static void checkMsgPackDocument(const char* input, size_t inputSize, + const char* expectedJson) { + DynamicJsonDocument doc(4096); + + DeserializationError error = deserializeMsgPack(doc, input, inputSize); + + REQUIRE(error == DeserializationError::Ok); + std::string actualJson; + serializeJson(doc, actualJson); + REQUIRE(actualJson == expectedJson); +} + +static void checkMsgPackError(const char* input, size_t inputSize, + DeserializationError expectedError) { + DynamicJsonDocument doc(4096); + + DeserializationError error = deserializeMsgPack(doc, input, inputSize); + + REQUIRE(error == expectedError); +} + +TEST_CASE("deserializeMsgPack() return NotSupported") { + SECTION("bin 8") { + checkMsgPackDocument("\x92\xc4\x01X\x2A", 5, "[null,42]"); + } + + SECTION("bin 16") { + checkMsgPackDocument("\x92\xc5\x00\x01X\x2A", 6, "[null,42]"); + } + + SECTION("bin 32") { + checkMsgPackDocument("\x92\xc6\x00\x00\x00\x01X\x2A", 8, "[null,42]"); + } + + SECTION("ext 8") { + checkMsgPackDocument("\x92\xc7\x01\x01\x01\x2A", 6, "[null,42]"); + } + + SECTION("ext 16") { + checkMsgPackDocument("\x92\xc8\x00\x01\x01\x01\x2A", 7, "[null,42]"); + } + + SECTION("ext 32") { + checkMsgPackDocument("\x92\xc9\x00\x00\x00\x01\x01\x01\x2A", 9, + "[null,42]"); + } + + SECTION("fixext 1") { + checkMsgPackDocument("\x92\xd4\x01\x01\x2A", 5, "[null,42]"); + } + + SECTION("fixext 2") { + checkMsgPackDocument("\x92\xd5\x01\x01\x02\x2A", 6, "[null,42]"); + } + + SECTION("fixext 4") { + checkMsgPackDocument("\x92\xd6\x01\x01\x02\x03\x04\x2A", 8, "[null,42]"); + } + + SECTION("fixext 8") { + checkMsgPackDocument("\x92\xd7\x01\x01\x02\x03\x04\x05\x06\x07\x08\x2A", 12, + "[null,42]"); + } + + SECTION("fixext 16") { + checkMsgPackDocument( + "\x92\xd8\x01\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E" + "\x0F\x10\x2A", + 20, "[null,42]"); + } + + SECTION("integer as key") { + checkMsgPackError("\x81\x01\xA1H", 3, DeserializationError::InvalidInput); + } +} diff --git a/libraries/ArduinoJson/extras/tests/MsgPackSerializer/CMakeLists.txt b/libraries/ArduinoJson/extras/tests/MsgPackSerializer/CMakeLists.txt new file mode 100644 index 0000000..2f3d8cc --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MsgPackSerializer/CMakeLists.txt @@ -0,0 +1,19 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2023, Benoit BLANCHON +# MIT License + +add_executable(MsgPackSerializerTests + destination_types.cpp + measure.cpp + misc.cpp + serializeArray.cpp + serializeObject.cpp + serializeVariant.cpp +) + +add_test(MsgPackSerializer MsgPackSerializerTests) + +set_tests_properties(MsgPackSerializer + PROPERTIES + LABELS "Catch" +) diff --git a/libraries/ArduinoJson/extras/tests/MsgPackSerializer/destination_types.cpp b/libraries/ArduinoJson/extras/tests/MsgPackSerializer/destination_types.cpp new file mode 100644 index 0000000..8b0dffa --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MsgPackSerializer/destination_types.cpp @@ -0,0 +1,59 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("serialize MsgPack to various destination types") { + DynamicJsonDocument doc(4096); + JsonObject object = doc.to(); + object["hello"] = "world"; + const char* expected_result = "\x81\xA5hello\xA5world"; + const size_t expected_length = 13; + + SECTION("std::string") { + std::string result; + size_t len = serializeMsgPack(object, result); + + REQUIRE(expected_result == result); + REQUIRE(expected_length == len); + } + + /* SECTION("std::vector") { + std::vector result; + size_t len = serializeMsgPack(object, result); + + REQUIRE(std::vector(expected_result, expected_result + 13) == + result); + REQUIRE(expected_length == len); + } */ + + SECTION("char[] larger than needed") { + char result[64]; + memset(result, 42, sizeof(result)); + size_t len = serializeMsgPack(object, result); + + REQUIRE(expected_length == len); + REQUIRE(std::string(expected_result, len) == std::string(result, len)); + REQUIRE(result[len] == 42); + } + + SECTION("char[] of the right size") { // #1545 + char result[13]; + size_t len = serializeMsgPack(object, result); + + REQUIRE(expected_length == len); + REQUIRE(std::string(expected_result, len) == std::string(result, len)); + } + + SECTION("char*") { + char result[64]; + memset(result, 42, sizeof(result)); + size_t len = serializeMsgPack(object, result, 64); + + REQUIRE(expected_length == len); + REQUIRE(std::string(expected_result, len) == std::string(result, len)); + REQUIRE(result[len] == 42); + } +} diff --git a/libraries/ArduinoJson/extras/tests/MsgPackSerializer/measure.cpp b/libraries/ArduinoJson/extras/tests/MsgPackSerializer/measure.cpp new file mode 100644 index 0000000..a6a4fc9 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MsgPackSerializer/measure.cpp @@ -0,0 +1,14 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("measureMsgPack()") { + DynamicJsonDocument doc(4096); + JsonObject object = doc.to(); + object["hello"] = "world"; + + REQUIRE(measureMsgPack(doc) == 13); +} diff --git a/libraries/ArduinoJson/extras/tests/MsgPackSerializer/misc.cpp b/libraries/ArduinoJson/extras/tests/MsgPackSerializer/misc.cpp new file mode 100644 index 0000000..4753dbf --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MsgPackSerializer/misc.cpp @@ -0,0 +1,46 @@ +#include +#include +#include + +template +void check(T value, const std::string& expected) { + DynamicJsonDocument doc(4096); + doc.to().set(value); + char buffer[256] = ""; + size_t returnValue = serializeMsgPack(doc, buffer, sizeof(buffer)); + REQUIRE(expected == buffer); + REQUIRE(expected.size() == returnValue); +} + +TEST_CASE("serializeMsgPack(MemberProxy)") { + DynamicJsonDocument doc(4096); + deserializeJson(doc, "{\"hello\":42}"); + JsonObject obj = doc.as(); + std::string result; + + serializeMsgPack(obj["hello"], result); + + REQUIRE(result == "*"); +} + +TEST_CASE("serializeMsgPack(ElementProxy)") { + DynamicJsonDocument doc(4096); + deserializeJson(doc, "[42]"); + JsonArray arr = doc.as(); + std::string result; + + serializeMsgPack(arr[0], result); + + REQUIRE(result == "*"); +} + +TEST_CASE("serializeMsgPack(JsonVariantSubscript)") { + DynamicJsonDocument doc(4096); + deserializeJson(doc, "[42]"); + JsonVariant var = doc.as(); + std::string result; + + serializeMsgPack(var[0], result); + + REQUIRE(result == "*"); +} diff --git a/libraries/ArduinoJson/extras/tests/MsgPackSerializer/serializeArray.cpp b/libraries/ArduinoJson/extras/tests/MsgPackSerializer/serializeArray.cpp new file mode 100644 index 0000000..a8ec639 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MsgPackSerializer/serializeArray.cpp @@ -0,0 +1,60 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +static void check(const JsonArray array, const char* expected_data, + size_t expected_len) { + std::string expected(expected_data, expected_data + expected_len); + std::string actual; + size_t len = serializeMsgPack(array, actual); + CAPTURE(array); + REQUIRE(len == expected_len); + REQUIRE(actual == expected); +} + +template +static void check(const JsonArray array, const char (&expected_data)[N]) { + const size_t expected_len = N - 1; + check(array, expected_data, expected_len); +} + +static void check(const JsonArray array, const std::string& expected) { + check(array, expected.data(), expected.length()); +} + +TEST_CASE("serialize MsgPack array") { + DynamicJsonDocument doc(JSON_ARRAY_SIZE(65536)); + JsonArray array = doc.to(); + + SECTION("empty") { + check(array, "\x90"); + } + + SECTION("fixarray") { + array.add("hello"); + array.add("world"); + + check(array, "\x92\xA5hello\xA5world"); + } + + SECTION("array 16") { + for (int i = 0; i < 16; i++) + array.add(i); + + check(array, + "\xDC\x00\x10\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D" + "\x0E\x0F"); + } + + SECTION("array 32") { + const char* nil = 0; + for (int i = 0; i < 65536; i++) + array.add(nil); + + check(array, + std::string("\xDD\x00\x01\x00\x00", 5) + std::string(65536, '\xc0')); + } +} diff --git a/libraries/ArduinoJson/extras/tests/MsgPackSerializer/serializeObject.cpp b/libraries/ArduinoJson/extras/tests/MsgPackSerializer/serializeObject.cpp new file mode 100644 index 0000000..8817307 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MsgPackSerializer/serializeObject.cpp @@ -0,0 +1,83 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include +#include + +static void check(const JsonObject object, const char* expected_data, + size_t expected_len) { + std::string expected(expected_data, expected_data + expected_len); + std::string actual; + size_t len = serializeMsgPack(object, actual); + CAPTURE(object); + REQUIRE(len == expected_len); + REQUIRE(actual == expected); +} + +template +static void check(const JsonObject object, const char (&expected_data)[N]) { + const size_t expected_len = N - 1; + check(object, expected_data, expected_len); +} + +// TODO: used by the commented test +// static void check(const JsonObject object, const std::string& expected) { +// check(object, expected.data(), expected.length()); +//} + +TEST_CASE("serialize MsgPack object") { + DynamicJsonDocument doc(4096); + JsonObject object = doc.to(); + + SECTION("empty") { + check(object, "\x80"); + } + + SECTION("fixmap") { + object["hello"] = "world"; + + check(object, "\x81\xA5hello\xA5world"); + } + + SECTION("map 16") { + for (int i = 0; i < 16; ++i) { + char key[16]; + sprintf(key, "i%X", i); + object[key] = i; + } + + check(object, + "\xDE\x00\x10\xA2i0\x00\xA2i1\x01\xA2i2\x02\xA2i3\x03\xA2i4\x04\xA2i5" + "\x05\xA2i6\x06\xA2i7\x07\xA2i8\x08\xA2i9\x09\xA2iA\x0A\xA2iB\x0B\xA2" + "iC\x0C\xA2iD\x0D\xA2iE\x0E\xA2iF\x0F"); + } + + // TODO: improve performance and uncomment + // SECTION("map 32") { + // std::string expected("\xDF\x00\x01\x00\x00", 5); + // + // for (int i = 0; i < 65536; ++i) { + // char kv[16]; + // sprintf(kv, "%04x", i); + // object[kv] = kv; + // expected += '\xA4'; + // expected += kv; + // expected += '\xA4'; + // expected += kv; + // } + // + // check(object, expected); + // } + + SECTION("serialized(const char*)") { + object["hello"] = serialized("\xDB\x00\x01\x00\x00", 5); + check(object, "\x81\xA5hello\xDB\x00\x01\x00\x00"); + } + + SECTION("serialized(std::string)") { + object["hello"] = serialized(std::string("\xDB\x00\x01\x00\x00", 5)); + check(object, "\x81\xA5hello\xDB\x00\x01\x00\x00"); + } +} diff --git a/libraries/ArduinoJson/extras/tests/MsgPackSerializer/serializeVariant.cpp b/libraries/ArduinoJson/extras/tests/MsgPackSerializer/serializeVariant.cpp new file mode 100644 index 0000000..b8a021f --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/MsgPackSerializer/serializeVariant.cpp @@ -0,0 +1,162 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +template +static void checkVariant(T value, const char* expected_data, + size_t expected_len) { + DynamicJsonDocument doc(4096); + JsonVariant variant = doc.to(); + variant.set(value); + std::string expected(expected_data, expected_data + expected_len); + std::string actual; + size_t len = serializeMsgPack(variant, actual); + CAPTURE(variant); + REQUIRE(len == expected_len); + REQUIRE(actual == expected); +} + +template +static void checkVariant(T value, const char (&expected_data)[N]) { + const size_t expected_len = N - 1; + checkVariant(value, expected_data, expected_len); +} + +template +static void checkVariant(T value, const std::string& expected) { + checkVariant(value, expected.data(), expected.length()); +} + +TEST_CASE("serialize MsgPack value") { + SECTION("unbound") { + checkVariant(JsonVariant(), "\xC0"); // we represent undefined as nil + } + + SECTION("nil") { + const char* nil = 0; // ArduinoJson uses a string for null + checkVariant(nil, "\xC0"); + } + + SECTION("bool") { + checkVariant(false, "\xC2"); + checkVariant(true, "\xC3"); + } + + SECTION("positive fixint") { + SECTION("signed") { + checkVariant(0, "\x00"); + checkVariant(127, "\x7F"); + } + SECTION("unsigned") { + checkVariant(0U, "\x00"); + checkVariant(127U, "\x7F"); + } + } + + SECTION("uint 8") { + checkVariant(128, "\xCC\x80"); + checkVariant(255, "\xCC\xFF"); + } + + SECTION("uint 16") { + checkVariant(256, "\xCD\x01\x00"); + checkVariant(0xFFFF, "\xCD\xFF\xFF"); + } + + SECTION("uint 32") { + checkVariant(0x00010000U, "\xCE\x00\x01\x00\x00"); + checkVariant(0x12345678U, "\xCE\x12\x34\x56\x78"); + checkVariant(0xFFFFFFFFU, "\xCE\xFF\xFF\xFF\xFF"); + } + +#if ARDUINOJSON_USE_LONG_LONG + SECTION("uint 64") { + checkVariant(0x0001000000000000U, "\xCF\x00\x01\x00\x00\x00\x00\x00\x00"); + checkVariant(0x123456789ABCDEF0U, "\xCF\x12\x34\x56\x78\x9A\xBC\xDE\xF0"); + checkVariant(0xFFFFFFFFFFFFFFFFU, "\xCF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"); + } +#endif + + SECTION("negative fixint") { + checkVariant(-1, "\xFF"); + checkVariant(-32, "\xE0"); + } + + SECTION("int 8") { + checkVariant(-33, "\xD0\xDF"); + checkVariant(-128, "\xD0\x80"); + } + + SECTION("int 16") { + checkVariant(-129, "\xD1\xFF\x7F"); + checkVariant(-32768, "\xD1\x80\x00"); + } + + SECTION("int 32") { + checkVariant(-32769, "\xD2\xFF\xFF\x7F\xFF"); + checkVariant(-2147483647 - 1, "\xD2\x80\x00\x00\x00"); + } + +#if ARDUINOJSON_USE_LONG_LONG + SECTION("int 64") { + checkVariant(int64_t(0xFEDCBA9876543210), + "\xD3\xFE\xDC\xBA\x98\x76\x54\x32\x10"); + } +#endif + + SECTION("float 32") { + checkVariant(1.25, "\xCA\x3F\xA0\x00\x00"); + checkVariant(9.22337204e+18f, "\xca\x5f\x00\x00\x00"); + } + + SECTION("float 64") { + checkVariant(3.1415, "\xCB\x40\x09\x21\xCA\xC0\x83\x12\x6F"); + } + + SECTION("fixstr") { + checkVariant("", "\xA0"); + checkVariant("hello world hello world hello !", + "\xBFhello world hello world hello !"); + } + + SECTION("str 8") { + checkVariant("hello world hello world hello !!", + "\xD9\x20hello world hello world hello !!"); + } + + SECTION("str 16") { + std::string shortest(256, '?'); + checkVariant(shortest.c_str(), std::string("\xDA\x01\x00", 3) + shortest); + + std::string longest(65535, '?'); + checkVariant(longest.c_str(), std::string("\xDA\xFF\xFF", 3) + longest); + } + + SECTION("str 32") { + std::string shortest(65536, '?'); + checkVariant(shortest.c_str(), + std::string("\xDB\x00\x01\x00\x00", 5) + shortest); + } + + SECTION("serialized(const char*)") { + checkVariant(serialized("\xDA\xFF\xFF"), "\xDA\xFF\xFF"); + checkVariant(serialized("\xDB\x00\x01\x00\x00", 5), "\xDB\x00\x01\x00\x00"); + } + + SECTION("serialize round double as integer") { // Issue #1718 + checkVariant(-32768.0, "\xD1\x80\x00"); + checkVariant(-129.0, "\xD1\xFF\x7F"); + checkVariant(-128.0, "\xD0\x80"); + checkVariant(-33.0, "\xD0\xDF"); + checkVariant(-32.0, "\xE0"); + checkVariant(-1.0, "\xFF"); + checkVariant(0.0, "\x00"); + checkVariant(127.0, "\x7F"); + checkVariant(128.0, "\xCC\x80"); + checkVariant(255.0, "\xCC\xFF"); + checkVariant(256.0, "\xCD\x01\x00"); + } +} diff --git a/libraries/ArduinoJson/extras/tests/Numbers/CMakeLists.txt b/libraries/ArduinoJson/extras/tests/Numbers/CMakeLists.txt new file mode 100644 index 0000000..48cf8c0 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Numbers/CMakeLists.txt @@ -0,0 +1,18 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2023, Benoit BLANCHON +# MIT License + +add_executable(NumbersTests + convertNumber.cpp + parseFloat.cpp + parseDouble.cpp + parseInteger.cpp + parseNumber.cpp +) + +add_test(Numbers NumbersTests) + +set_tests_properties(Numbers + PROPERTIES + LABELS "Catch" +) diff --git a/libraries/ArduinoJson/extras/tests/Numbers/convertNumber.cpp b/libraries/ArduinoJson/extras/tests/Numbers/convertNumber.cpp new file mode 100644 index 0000000..ca0cc5e --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Numbers/convertNumber.cpp @@ -0,0 +1,131 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include +#include + +using namespace ArduinoJson::detail; + +TEST_CASE("canConvertNumber()") { + SECTION("int8_t -> int8_t") { + CHECK(canConvertNumber(0) == true); + CHECK(canConvertNumber(127) == true); + CHECK(canConvertNumber(-128) == true); + } + + SECTION("int8_t -> int16_t") { + CHECK(canConvertNumber(0) == true); + CHECK(canConvertNumber(127) == true); + CHECK(canConvertNumber(-128) == true); + } + + SECTION("int8_t -> uint8_t") { + CHECK(canConvertNumber(0) == true); + CHECK(canConvertNumber(127) == true); + CHECK(canConvertNumber(-128) == false); + } + + SECTION("int8_t -> uint16_t") { + CHECK(canConvertNumber(0) == true); + CHECK(canConvertNumber(127) == true); + CHECK(canConvertNumber(-128) == false); + } + + SECTION("int16_t -> int8_t") { + CHECK(canConvertNumber(0) == true); + CHECK(canConvertNumber(127) == true); + CHECK(canConvertNumber(128) == false); + CHECK(canConvertNumber(-128) == true); + CHECK(canConvertNumber(-129) == false); + } + + SECTION("int16_t -> uint8_t") { + CHECK(canConvertNumber(0) == true); + CHECK(canConvertNumber(255) == true); + CHECK(canConvertNumber(256) == false); + CHECK(canConvertNumber(-1) == false); + } + + SECTION("uint8_t -> int8_t") { + CHECK(canConvertNumber(0) == true); + CHECK(canConvertNumber(127) == true); + CHECK(canConvertNumber(128) == false); + CHECK(canConvertNumber(255) == false); + } + + SECTION("uint8_t -> int16_t") { + CHECK(canConvertNumber(0) == true); + CHECK(canConvertNumber(127) == true); + CHECK(canConvertNumber(128) == true); + CHECK(canConvertNumber(255) == true); + } + + SECTION("uint8_t -> uint8_t") { + CHECK(canConvertNumber(0) == true); + CHECK(canConvertNumber(127) == true); + CHECK(canConvertNumber(128) == true); + CHECK(canConvertNumber(255) == true); + } + + SECTION("uint8_t -> uint16_t") { + CHECK(canConvertNumber(0) == true); + CHECK(canConvertNumber(127) == true); + CHECK(canConvertNumber(128) == true); + CHECK(canConvertNumber(255) == true); + } + + SECTION("float -> int32_t") { + CHECK(canConvertNumber(0) == true); + CHECK(canConvertNumber(-2.147483904e9f) == false); + CHECK(canConvertNumber(-2.147483648e+9f) == true); + CHECK(canConvertNumber(2.14748352e+9f) == true); + CHECK(canConvertNumber(2.14748365e+9f) == false); + } + + SECTION("double -> int32_t") { + CHECK(canConvertNumber(0) == true); + CHECK(canConvertNumber(-2.147483649e+9) == false); + CHECK(canConvertNumber(-2.147483648e+9) == true); + CHECK(canConvertNumber(2.147483647e+9) == true); + CHECK(canConvertNumber(2.147483648e+9) == false); + } + + SECTION("float -> uint32_t") { + CHECK(canConvertNumber(0) == true); + CHECK(canConvertNumber(-1.401298e-45f) == false); + CHECK(canConvertNumber(4.29496704e+9f) == true); + CHECK(canConvertNumber(4.294967296e+9f) == false); + } + + SECTION("float -> int64_t") { + CHECK(canConvertNumber(0) == true); + CHECK(canConvertNumber(-9.22337204e+18f) == true); + CHECK(canConvertNumber(9.22337149e+18f) == true); + CHECK(canConvertNumber(9.22337204e+18f) == false); + } + + SECTION("double -> int64_t") { + CHECK(canConvertNumber(0) == true); + CHECK(canConvertNumber(-9.2233720368547758e+18) == true); + CHECK(canConvertNumber(9.2233720368547748e+18) == true); + CHECK(canConvertNumber(9.2233720368547758e+18) == false); + } + + SECTION("float -> uint64_t") { + CHECK(canConvertNumber(0) == true); + CHECK(canConvertNumber(-1.401298e-45f) == false); + CHECK(canConvertNumber(1.84467429741979238e+19f) == true); + CHECK(canConvertNumber(1.844674407370955161e+19f) == + false); + } + + SECTION("double -> uint64_t") { + CHECK(canConvertNumber(0) == true); + CHECK(canConvertNumber(-4.9406564584124e-324) == false); + CHECK(canConvertNumber(1.844674407370954958e+19) == true); + CHECK(canConvertNumber(1.844674407370955166e+19) == + false); + } +} diff --git a/libraries/ArduinoJson/extras/tests/Numbers/parseDouble.cpp b/libraries/ArduinoJson/extras/tests/Numbers/parseDouble.cpp new file mode 100644 index 0000000..301aa0c --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Numbers/parseDouble.cpp @@ -0,0 +1,96 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#define ARDUINOJSON_USE_DOUBLE 1 +#define ARDUINOJSON_ENABLE_NAN 1 +#define ARDUINOJSON_ENABLE_INFINITY 1 + +#include +#include + +using namespace ArduinoJson::detail; + +void checkDouble(const char* input, double expected) { + CAPTURE(input); + REQUIRE(parseNumber(input) == Approx(expected)); +} + +void checkDoubleNaN(const char* input) { + CAPTURE(input); + double result = parseNumber(input); + REQUIRE(result != result); +} + +void checkDoubleInf(const char* input, bool negative) { + CAPTURE(input); + double x = parseNumber(input); + if (negative) + REQUIRE(x < 0); + else + REQUIRE(x > 0); + REQUIRE(x == x); // not a NaN + REQUIRE(x * 2 == x); // a property of infinity +} + +TEST_CASE("parseNumber()") { + SECTION("Short_NoExponent") { + checkDouble("3.14", 3.14); + checkDouble("-3.14", -3.14); + checkDouble("+3.14", +3.14); + } + + SECTION("Short_NoDot") { + checkDouble("1E+308", 1E+308); + checkDouble("-1E+308", -1E+308); + checkDouble("+1E-308", +1E-308); + checkDouble("+1e+308", +1e+308); + checkDouble("-1e-308", -1e-308); + } + + SECTION("Max") { + checkDouble(".017976931348623147e+310", 1.7976931348623147e+308); + checkDouble(".17976931348623147e+309", 1.7976931348623147e+308); + checkDouble("1.7976931348623147e+308", 1.7976931348623147e+308); + checkDouble("17.976931348623147e+307", 1.7976931348623147e+308); + checkDouble("179.76931348623147e+306", 1.7976931348623147e+308); + } + + SECTION("Min") { + checkDouble(".022250738585072014e-306", 2.2250738585072014e-308); + checkDouble(".22250738585072014e-307", 2.2250738585072014e-308); + checkDouble("2.2250738585072014e-308", 2.2250738585072014e-308); + checkDouble("22.250738585072014e-309", 2.2250738585072014e-308); + checkDouble("222.50738585072014e-310", 2.2250738585072014e-308); + } + + SECTION("VeryLong") { + checkDouble("0.00000000000000000000000000000001", 1e-32); + checkDouble("100000000000000000000000000000000.0", 1e+32); + checkDouble( + "100000000000000000000000000000000.00000000000000000000000000000", + 1e+32); + } + + SECTION("MantissaTooLongToFit") { + checkDouble("0.179769313486231571111111111111", 0.17976931348623157); + checkDouble("17976931348623157.11111111111111", 17976931348623157.0); + checkDouble("1797693.134862315711111111111111", 1797693.1348623157); + + checkDouble("-0.179769313486231571111111111111", -0.17976931348623157); + checkDouble("-17976931348623157.11111111111111", -17976931348623157.0); + checkDouble("-1797693.134862315711111111111111", -1797693.1348623157); + } + + SECTION("ExponentTooBig") { + checkDoubleInf("1e309", false); + checkDoubleInf("-1e309", true); + checkDoubleInf("1e65535", false); + checkDouble("1e-65535", 0.0); + } + + SECTION("NaN") { + checkDoubleNaN("NaN"); + checkDoubleNaN("nan"); + } +} diff --git a/libraries/ArduinoJson/extras/tests/Numbers/parseFloat.cpp b/libraries/ArduinoJson/extras/tests/Numbers/parseFloat.cpp new file mode 100644 index 0000000..4e9c1d4 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Numbers/parseFloat.cpp @@ -0,0 +1,101 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#define ARDUINOJSON_USE_DOUBLE 0 +#define ARDUINOJSON_ENABLE_NAN 1 +#define ARDUINOJSON_ENABLE_INFINITY 1 + +#include +#include + +using namespace ArduinoJson::detail; + +void checkFloat(const char* input, float expected) { + CAPTURE(input); + REQUIRE(parseNumber(input) == Approx(expected)); +} + +void checkFloatNaN(const char* input) { + CAPTURE(input); + float result = parseNumber(input); + REQUIRE(result != result); +} + +void checkFloatInf(const char* input, bool negative) { + CAPTURE(input); + float x = parseNumber(input); + if (negative) + REQUIRE(x < 0); + else + REQUIRE(x > 0); + REQUIRE(x == x); // not a NaN + REQUIRE(x * 2 == x); // a property of infinity +} + +TEST_CASE("parseNumber()") { + SECTION("Float_Short_NoExponent") { + checkFloat("3.14", 3.14f); + checkFloat("-3.14", -3.14f); + checkFloat("+3.14", +3.14f); + } + + SECTION("Short_NoDot") { + checkFloat("1E+38", 1E+38f); + checkFloat("-1E+38", -1E+38f); + checkFloat("+1E-38", +1E-38f); + checkFloat("+1e+38", +1e+38f); + checkFloat("-1e-38", -1e-38f); + } + + SECTION("Max") { + checkFloat("340.2823e+36", 3.402823e+38f); + checkFloat("34.02823e+37", 3.402823e+38f); + checkFloat("3.402823e+38", 3.402823e+38f); + checkFloat("0.3402823e+39", 3.402823e+38f); + checkFloat("0.03402823e+40", 3.402823e+38f); + checkFloat("0.003402823e+41", 3.402823e+38f); + } + + SECTION("VeryLong") { + checkFloat("0.00000000000000000000000000000001", 1e-32f); + checkFloat("100000000000000000000000000000000.0", 1e+32f); + checkFloat( + "100000000000000000000000000000000.00000000000000000000000000000", + 1e+32f); + } + + SECTION("MantissaTooLongToFit") { + checkFloat("0.340282346638528861111111111111", 0.34028234663852886f); + checkFloat("34028234663852886.11111111111111", 34028234663852886.0f); + checkFloat("34028234.66385288611111111111111", 34028234.663852886f); + + checkFloat("-0.340282346638528861111111111111", -0.34028234663852886f); + checkFloat("-34028234663852886.11111111111111", -34028234663852886.0f); + checkFloat("-34028234.66385288611111111111111", -34028234.663852886f); + } + + SECTION("ExponentTooBig") { + checkFloatInf("1e39", false); + checkFloatInf("-1e39", true); + checkFloatInf("1e255", false); + checkFloat("1e-255", 0.0f); + } + + SECTION("NaN") { + checkFloatNaN("NaN"); + checkFloatNaN("nan"); + } + + SECTION("Infinity") { + checkFloatInf("Infinity", false); + checkFloatInf("+Infinity", false); + checkFloatInf("-Infinity", true); + checkFloatInf("inf", false); + checkFloatInf("+inf", false); + checkFloatInf("-inf", true); + + checkFloatInf("1e300", false); + checkFloatInf("-1e300", true); + } +} diff --git a/libraries/ArduinoJson/extras/tests/Numbers/parseInteger.cpp b/libraries/ArduinoJson/extras/tests/Numbers/parseInteger.cpp new file mode 100644 index 0000000..880da76 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Numbers/parseInteger.cpp @@ -0,0 +1,68 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include +#include + +using namespace ArduinoJson::detail; + +template +void checkInteger(const char* input, T expected) { + CAPTURE(input); + T actual = parseNumber(input); + REQUIRE(expected == actual); +} + +TEST_CASE("parseNumber()") { + checkInteger("-128", -128); + checkInteger("127", 127); + checkInteger("+127", 127); + checkInteger("3.14", 3); + checkInteger("x42", 0); + checkInteger("128", 0); // overflow + checkInteger("-129", 0); // overflow +} + +TEST_CASE("parseNumber()") { + checkInteger("-32768", -32768); + checkInteger("32767", 32767); + checkInteger("+32767", 32767); + checkInteger("3.14", 3); + checkInteger("x42", 0); + checkInteger("-32769", 0); // overflow + checkInteger("32768", 0); // overflow +} + +TEST_CASE("parseNumber()") { + checkInteger("-2147483648", (-2147483647 - 1)); + checkInteger("2147483647", 2147483647); + checkInteger("+2147483647", 2147483647); + checkInteger("3.14", 3); + checkInteger("x42", 0); + checkInteger("-2147483649", 0); // overflow + checkInteger("2147483648", 0); // overflow +} + +TEST_CASE("parseNumber()") { + checkInteger("0", 0); + checkInteger("-0", 0); + checkInteger("255", 255); + checkInteger("+255", 255); + checkInteger("3.14", 3); + checkInteger("x42", 0); + checkInteger("-1", 0); + checkInteger("256", 0); +} + +TEST_CASE("parseNumber()") { + checkInteger("0", 0); + checkInteger("65535", 65535); + checkInteger("+65535", 65535); + checkInteger("3.14", 3); + // checkInteger(" 42", 0); + checkInteger("x42", 0); + checkInteger("-1", 0); + checkInteger("65536", 0); +} diff --git a/libraries/ArduinoJson/extras/tests/Numbers/parseNumber.cpp b/libraries/ArduinoJson/extras/tests/Numbers/parseNumber.cpp new file mode 100644 index 0000000..48163c1 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/Numbers/parseNumber.cpp @@ -0,0 +1,53 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include + +using namespace ArduinoJson; +using namespace ArduinoJson::detail; + +TEST_CASE("Test unsigned integer overflow") { + VariantData first, second; + + // Avoids MSVC warning C4127 (conditional expression is constant) + size_t integerSize = sizeof(JsonInteger); + + if (integerSize == 8) { + parseNumber("18446744073709551615", first); + parseNumber("18446744073709551616", second); + } else { + parseNumber("4294967295", first); + parseNumber("4294967296", second); + } + + REQUIRE(first.type() == uint8_t(VALUE_IS_UNSIGNED_INTEGER)); + REQUIRE(second.type() == uint8_t(VALUE_IS_FLOAT)); +} + +TEST_CASE("Test signed integer overflow") { + VariantData first, second; + + // Avoids MSVC warning C4127 (conditional expression is constant) + size_t integerSize = sizeof(JsonInteger); + + if (integerSize == 8) { + parseNumber("-9223372036854775808", first); + parseNumber("-9223372036854775809", second); + } else { + parseNumber("-2147483648", first); + parseNumber("-2147483649", second); + } + + REQUIRE(first.type() == uint8_t(VALUE_IS_SIGNED_INTEGER)); + REQUIRE(second.type() == uint8_t(VALUE_IS_FLOAT)); +} + +TEST_CASE("Invalid value") { + VariantData result; + + parseNumber("6a3", result); + + REQUIRE(result.type() == uint8_t(VALUE_IS_NULL)); +} diff --git a/libraries/ArduinoJson/extras/tests/TextFormatter/CMakeLists.txt b/libraries/ArduinoJson/extras/tests/TextFormatter/CMakeLists.txt new file mode 100644 index 0000000..2bc4a89 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/TextFormatter/CMakeLists.txt @@ -0,0 +1,18 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2023, Benoit BLANCHON +# MIT License + +add_executable(TextFormatterTests + writeFloat.cpp + writeInteger.cpp + writeString.cpp +) + +set_target_properties(TextFormatterTests PROPERTIES UNITY_BUILD OFF) + +add_test(TextFormatter TextFormatterTests) + +set_tests_properties(TextFormatter + PROPERTIES + LABELS "Catch" +) diff --git a/libraries/ArduinoJson/extras/tests/TextFormatter/writeFloat.cpp b/libraries/ArduinoJson/extras/tests/TextFormatter/writeFloat.cpp new file mode 100644 index 0000000..8e4bd7e --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/TextFormatter/writeFloat.cpp @@ -0,0 +1,119 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include +#include + +#define ARDUINOJSON_ENABLE_NAN 1 +#define ARDUINOJSON_ENABLE_INFINITY 1 +#include +#include + +using namespace ArduinoJson::detail; + +template +void check(TFloat input, const std::string& expected) { + std::string output; + Writer sb(output); + TextFormatter> writer(sb); + writer.writeFloat(input); + REQUIRE(writer.bytesWritten() == output.size()); + CHECK(expected == output); +} + +TEST_CASE("TextFormatter::writeFloat(double)") { + SECTION("Pi") { + check(3.14159265359, "3.141592654"); + } + + SECTION("Signaling NaN") { + double nan = std::numeric_limits::signaling_NaN(); + check(nan, "NaN"); + } + + SECTION("Quiet NaN") { + double nan = std::numeric_limits::quiet_NaN(); + check(nan, "NaN"); + } + + SECTION("Infinity") { + double inf = std::numeric_limits::infinity(); + check(inf, "Infinity"); + check(-inf, "-Infinity"); + } + + SECTION("Zero") { + check(0.0, "0"); + check(-0.0, "0"); + } + + SECTION("Espilon") { + check(2.2250738585072014E-308, "2.225073859e-308"); + check(-2.2250738585072014E-308, "-2.225073859e-308"); + } + + SECTION("Max double") { + check(1.7976931348623157E+308, "1.797693135e308"); + check(-1.7976931348623157E+308, "-1.797693135e308"); + } + + SECTION("Big exponent") { + // this test increases coverage of normalize() + check(1e255, "1e255"); + check(1e-255, "1e-255"); + } + + SECTION("Exponentation when <= 1e-5") { + check(1e-4, "0.0001"); + check(1e-5, "1e-5"); + + check(-1e-4, "-0.0001"); + check(-1e-5, "-1e-5"); + } + + SECTION("Exponentation when >= 1e7") { + check(9999999.999, "9999999.999"); + check(10000000.0, "1e7"); + + check(-9999999.999, "-9999999.999"); + check(-10000000.0, "-1e7"); + } + + SECTION("Rounding when too many decimals") { + check(0.000099999999999, "0.0001"); + check(0.0000099999999999, "1e-5"); + check(0.9999999996, "1"); + } + + SECTION("9 decimal places") { + check(0.100000001, "0.100000001"); + check(0.999999999, "0.999999999"); + + check(9.000000001, "9.000000001"); + check(9.999999999, "9.999999999"); + } + + SECTION("10 decimal places") { + check(0.1000000001, "0.1"); + check(0.9999999999, "1"); + + check(9.0000000001, "9"); + check(9.9999999999, "10"); + } +} + +TEST_CASE("TextFormatter::writeFloat(float)") { + SECTION("Pi") { + check(3.14159265359f, "3.141593"); + } + + SECTION("999.9") { // issue #543 + check(999.9f, "999.9"); + } + + SECTION("24.3") { // # issue #588 + check(24.3f, "24.3"); + } +} diff --git a/libraries/ArduinoJson/extras/tests/TextFormatter/writeInteger.cpp b/libraries/ArduinoJson/extras/tests/TextFormatter/writeInteger.cpp new file mode 100644 index 0000000..20cbd29 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/TextFormatter/writeInteger.cpp @@ -0,0 +1,55 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include +#include +#include + +#include +#include + +using namespace ArduinoJson::detail; + +template +void checkWriteInteger(T value, std::string expected) { + char output[64] = {0}; + StaticStringWriter sb(output, sizeof(output)); + TextFormatter writer(sb); + writer.writeInteger(value); + REQUIRE(expected == output); + REQUIRE(writer.bytesWritten() == expected.size()); +} + +TEST_CASE("int8_t") { + checkWriteInteger(0, "0"); + checkWriteInteger(-128, "-128"); + checkWriteInteger(127, "127"); +} + +TEST_CASE("uint8_t") { + checkWriteInteger(0, "0"); + checkWriteInteger(255, "255"); +} + +TEST_CASE("int16_t") { + checkWriteInteger(0, "0"); + checkWriteInteger(-32768, "-32768"); + checkWriteInteger(32767, "32767"); +} + +TEST_CASE("uint16_t") { + checkWriteInteger(0, "0"); + checkWriteInteger(65535, "65535"); +} + +TEST_CASE("int32_t") { + checkWriteInteger(0, "0"); + checkWriteInteger(-2147483647 - 1, "-2147483648"); + checkWriteInteger(2147483647, "2147483647"); +} + +TEST_CASE("uint32_t") { + checkWriteInteger(0, "0"); + checkWriteInteger(4294967295U, "4294967295"); +} diff --git a/libraries/ArduinoJson/extras/tests/TextFormatter/writeString.cpp b/libraries/ArduinoJson/extras/tests/TextFormatter/writeString.cpp new file mode 100644 index 0000000..2be9191 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/TextFormatter/writeString.cpp @@ -0,0 +1,57 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2023, Benoit BLANCHON +// MIT License + +#include + +#include +#include + +using namespace ArduinoJson::detail; + +void check(const char* input, std::string expected) { + char output[64] = {0}; + StaticStringWriter sb(output, sizeof(output)); + TextFormatter writer(sb); + writer.writeString(input); + REQUIRE(expected == output); + REQUIRE(writer.bytesWritten() == expected.size()); +} + +TEST_CASE("TextFormatter::writeString()") { + SECTION("EmptyString") { + check("", "\"\""); + } + + SECTION("QuotationMark") { + check("\"", "\"\\\"\""); + } + + SECTION("ReverseSolidus") { + check("\\", "\"\\\\\""); + } + + SECTION("Solidus") { + check("/", "\"/\""); // but the JSON format allows \/ + } + + SECTION("Backspace") { + check("\b", "\"\\b\""); + } + + SECTION("Formfeed") { + check("\f", "\"\\f\""); + } + + SECTION("Newline") { + check("\n", "\"\\n\""); + } + + SECTION("CarriageReturn") { + check("\r", "\"\\r\""); + } + + SECTION("HorizontalTab") { + check("\t", "\"\\t\""); + } +} diff --git a/libraries/ArduinoJson/extras/tests/catch/CMakeLists.txt b/libraries/ArduinoJson/extras/tests/catch/CMakeLists.txt new file mode 100644 index 0000000..c5fb5fb --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/catch/CMakeLists.txt @@ -0,0 +1,21 @@ +# ArduinoJson - https://arduinojson.org +# Copyright Benoit Blanchon 2014-2021 +# MIT License + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED OFF) + +add_library(catch + catch.hpp + catch.cpp +) + +target_include_directories(catch + PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR} +) + +if(MINGW) + # prevent "too many sections (32837)" with MinGW + target_compile_options(catch PRIVATE -Wa,-mbig-obj) +endif() diff --git a/libraries/ArduinoJson/extras/tests/catch/catch.cpp b/libraries/ArduinoJson/extras/tests/catch/catch.cpp new file mode 100644 index 0000000..e6c8548 --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/catch/catch.cpp @@ -0,0 +1,6 @@ +// ArduinoJson - https://arduinojson.org +// Copyright Benoit Blanchon 2014-2021 +// MIT License + +#define CATCH_CONFIG_MAIN +#include "catch.hpp" diff --git a/libraries/ArduinoJson/extras/tests/catch/catch.hpp b/libraries/ArduinoJson/extras/tests/catch/catch.hpp new file mode 100644 index 0000000..9b309bd --- /dev/null +++ b/libraries/ArduinoJson/extras/tests/catch/catch.hpp @@ -0,0 +1,17976 @@ +/* + * Catch v2.13.10 + * Generated: 2022-10-16 11:01:23.452308 + * ---------------------------------------------------------- + * This file has been merged from multiple headers. Please don't edit it directly + * Copyright (c) 2022 Two Blue Cubes Ltd. All rights reserved. + * + * Distributed under the Boost Software License, Version 1.0. (See accompanying + * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + */ +#ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED +#define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED +// start catch.hpp + + +#define CATCH_VERSION_MAJOR 2 +#define CATCH_VERSION_MINOR 13 +#define CATCH_VERSION_PATCH 10 + +#ifdef __clang__ +# pragma clang system_header +#elif defined __GNUC__ +# pragma GCC system_header +#endif + +// start catch_suppress_warnings.h + +#ifdef __clang__ +# ifdef __ICC // icpc defines the __clang__ macro +# pragma warning(push) +# pragma warning(disable: 161 1682) +# else // __ICC +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wpadded" +# pragma clang diagnostic ignored "-Wswitch-enum" +# pragma clang diagnostic ignored "-Wcovered-switch-default" +# endif +#elif defined __GNUC__ + // Because REQUIREs trigger GCC's -Wparentheses, and because still + // supported version of g++ have only buggy support for _Pragmas, + // Wparentheses have to be suppressed globally. +# pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details + +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wunused-variable" +# pragma GCC diagnostic ignored "-Wpadded" +#endif +// end catch_suppress_warnings.h +#if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER) +# define CATCH_IMPL +# define CATCH_CONFIG_ALL_PARTS +#endif + +// In the impl file, we want to have access to all parts of the headers +// Can also be used to sanely support PCHs +#if defined(CATCH_CONFIG_ALL_PARTS) +# define CATCH_CONFIG_EXTERNAL_INTERFACES +# if defined(CATCH_CONFIG_DISABLE_MATCHERS) +# undef CATCH_CONFIG_DISABLE_MATCHERS +# endif +# if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER) +# define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER +# endif +#endif + +#if !defined(CATCH_CONFIG_IMPL_ONLY) +// start catch_platform.h + +// See e.g.: +// https://opensource.apple.com/source/CarbonHeaders/CarbonHeaders-18.1/TargetConditionals.h.auto.html +#ifdef __APPLE__ +# include +# if (defined(TARGET_OS_OSX) && TARGET_OS_OSX == 1) || \ + (defined(TARGET_OS_MAC) && TARGET_OS_MAC == 1) +# define CATCH_PLATFORM_MAC +# elif (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1) +# define CATCH_PLATFORM_IPHONE +# endif + +#elif defined(linux) || defined(__linux) || defined(__linux__) +# define CATCH_PLATFORM_LINUX + +#elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__) +# define CATCH_PLATFORM_WINDOWS +#endif + +// end catch_platform.h + +#ifdef CATCH_IMPL +# ifndef CLARA_CONFIG_MAIN +# define CLARA_CONFIG_MAIN_NOT_DEFINED +# define CLARA_CONFIG_MAIN +# endif +#endif + +// start catch_user_interfaces.h + +namespace Catch { + unsigned int rngSeed(); +} + +// end catch_user_interfaces.h +// start catch_tag_alias_autoregistrar.h + +// start catch_common.h + +// start catch_compiler_capabilities.h + +// Detect a number of compiler features - by compiler +// The following features are defined: +// +// CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported? +// CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported? +// CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported? +// CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled? +// **************** +// Note to maintainers: if new toggles are added please document them +// in configuration.md, too +// **************** + +// In general each macro has a _NO_ form +// (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature. +// Many features, at point of detection, define an _INTERNAL_ macro, so they +// can be combined, en-mass, with the _NO_ forms later. + +#ifdef __cplusplus + +# if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L) +# define CATCH_CPP14_OR_GREATER +# endif + +# if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) +# define CATCH_CPP17_OR_GREATER +# endif + +#endif + +// Only GCC compiler should be used in this block, so other compilers trying to +// mask themselves as GCC should be ignored. +#if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && !defined(__CUDACC__) && !defined(__LCC__) +# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic push" ) +# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic pop" ) + +# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) + +#endif + +#if defined(__clang__) + +# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic push" ) +# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic pop" ) + +// As of this writing, IBM XL's implementation of __builtin_constant_p has a bug +// which results in calls to destructors being emitted for each temporary, +// without a matching initialization. In practice, this can result in something +// like `std::string::~string` being called on an uninitialized value. +// +// For example, this code will likely segfault under IBM XL: +// ``` +// REQUIRE(std::string("12") + "34" == "1234") +// ``` +// +// Therefore, `CATCH_INTERNAL_IGNORE_BUT_WARN` is not implemented. +# if !defined(__ibmxl__) && !defined(__CUDACC__) +# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) /* NOLINT(cppcoreguidelines-pro-type-vararg, hicpp-vararg) */ +# endif + +# define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \ + _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"") + +# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ + _Pragma( "clang diagnostic ignored \"-Wparentheses\"" ) + +# define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ + _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" ) + +# define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ + _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" ) + +# define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ + _Pragma( "clang diagnostic ignored \"-Wunused-template\"" ) + +#endif // __clang__ + +//////////////////////////////////////////////////////////////////////////////// +// Assume that non-Windows platforms support posix signals by default +#if !defined(CATCH_PLATFORM_WINDOWS) + #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS +#endif + +//////////////////////////////////////////////////////////////////////////////// +// We know some environments not to support full POSIX signals +#if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__) + #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS +#endif + +#ifdef __OS400__ +# define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS +# define CATCH_CONFIG_COLOUR_NONE +#endif + +//////////////////////////////////////////////////////////////////////////////// +// Android somehow still does not support std::to_string +#if defined(__ANDROID__) +# define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING +# define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE +#endif + +//////////////////////////////////////////////////////////////////////////////// +// Not all Windows environments support SEH properly +#if defined(__MINGW32__) +# define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH +#endif + +//////////////////////////////////////////////////////////////////////////////// +// PS4 +#if defined(__ORBIS__) +# define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE +#endif + +//////////////////////////////////////////////////////////////////////////////// +// Cygwin +#ifdef __CYGWIN__ + +// Required for some versions of Cygwin to declare gettimeofday +// see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin +# define _BSD_SOURCE +// some versions of cygwin (most) do not support std::to_string. Use the libstd check. +// https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813 +# if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \ + && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF)) + +# define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING + +# endif +#endif // __CYGWIN__ + +//////////////////////////////////////////////////////////////////////////////// +// Visual C++ +#if defined(_MSC_VER) + +// Universal Windows platform does not support SEH +// Or console colours (or console at all...) +# if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) +# define CATCH_CONFIG_COLOUR_NONE +# else +# define CATCH_INTERNAL_CONFIG_WINDOWS_SEH +# endif + +# if !defined(__clang__) // Handle Clang masquerading for msvc + +// MSVC traditional preprocessor needs some workaround for __VA_ARGS__ +// _MSVC_TRADITIONAL == 0 means new conformant preprocessor +// _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor +# if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL) +# define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +# endif // MSVC_TRADITIONAL + +// Only do this if we're not using clang on Windows, which uses `diagnostic push` & `diagnostic pop` +# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) ) +# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma( warning(pop) ) +# endif // __clang__ + +#endif // _MSC_VER + +#if defined(_REENTRANT) || defined(_MSC_VER) +// Enable async processing, as -pthread is specified or no additional linking is required +# define CATCH_INTERNAL_CONFIG_USE_ASYNC +#endif // _MSC_VER + +//////////////////////////////////////////////////////////////////////////////// +// Check if we are compiled with -fno-exceptions or equivalent +#if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND) +# define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED +#endif + +//////////////////////////////////////////////////////////////////////////////// +// DJGPP +#ifdef __DJGPP__ +# define CATCH_INTERNAL_CONFIG_NO_WCHAR +#endif // __DJGPP__ + +//////////////////////////////////////////////////////////////////////////////// +// Embarcadero C++Build +#if defined(__BORLANDC__) + #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN +#endif + +//////////////////////////////////////////////////////////////////////////////// + +// Use of __COUNTER__ is suppressed during code analysis in +// CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly +// handled by it. +// Otherwise all supported compilers support COUNTER macro, +// but user still might want to turn it off +#if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L ) + #define CATCH_INTERNAL_CONFIG_COUNTER +#endif + +//////////////////////////////////////////////////////////////////////////////// + +// RTX is a special version of Windows that is real time. +// This means that it is detected as Windows, but does not provide +// the same set of capabilities as real Windows does. +#if defined(UNDER_RTSS) || defined(RTX64_BUILD) + #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH + #define CATCH_INTERNAL_CONFIG_NO_ASYNC + #define CATCH_CONFIG_COLOUR_NONE +#endif + +#if !defined(_GLIBCXX_USE_C99_MATH_TR1) +#define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER +#endif + +// Various stdlib support checks that require __has_include +#if defined(__has_include) + // Check if string_view is available and usable + #if __has_include() && defined(CATCH_CPP17_OR_GREATER) + # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW + #endif + + // Check if optional is available and usable + # if __has_include() && defined(CATCH_CPP17_OR_GREATER) + # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL + # endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) + + // Check if byte is available and usable + # if __has_include() && defined(CATCH_CPP17_OR_GREATER) + # include + # if defined(__cpp_lib_byte) && (__cpp_lib_byte > 0) + # define CATCH_INTERNAL_CONFIG_CPP17_BYTE + # endif + # endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) + + // Check if variant is available and usable + # if __has_include() && defined(CATCH_CPP17_OR_GREATER) + # if defined(__clang__) && (__clang_major__ < 8) + // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852 + // fix should be in clang 8, workaround in libstdc++ 8.2 + # include + # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) + # define CATCH_CONFIG_NO_CPP17_VARIANT + # else + # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT + # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) + # else + # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT + # endif // defined(__clang__) && (__clang_major__ < 8) + # endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) +#endif // defined(__has_include) + +#if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) +# define CATCH_CONFIG_COUNTER +#endif +#if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH) +# define CATCH_CONFIG_WINDOWS_SEH +#endif +// This is set by default, because we assume that unix compilers are posix-signal-compatible by default. +#if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS) +# define CATCH_CONFIG_POSIX_SIGNALS +#endif +// This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions. +#if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR) +# define CATCH_CONFIG_WCHAR +#endif + +#if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING) +# define CATCH_CONFIG_CPP11_TO_STRING +#endif + +#if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL) +# define CATCH_CONFIG_CPP17_OPTIONAL +#endif + +#if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW) +# define CATCH_CONFIG_CPP17_STRING_VIEW +#endif + +#if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT) +# define CATCH_CONFIG_CPP17_VARIANT +#endif + +#if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE) +# define CATCH_CONFIG_CPP17_BYTE +#endif + +#if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT) +# define CATCH_INTERNAL_CONFIG_NEW_CAPTURE +#endif + +#if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE) +# define CATCH_CONFIG_NEW_CAPTURE +#endif + +#if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) +# define CATCH_CONFIG_DISABLE_EXCEPTIONS +#endif + +#if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN) +# define CATCH_CONFIG_POLYFILL_ISNAN +#endif + +#if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC) +# define CATCH_CONFIG_USE_ASYNC +#endif + +#if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE) +# define CATCH_CONFIG_ANDROID_LOGWRITE +#endif + +#if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER) +# define CATCH_CONFIG_GLOBAL_NEXTAFTER +#endif + +// Even if we do not think the compiler has that warning, we still have +// to provide a macro that can be used by the code. +#if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION) +# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION +#endif +#if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION) +# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION +#endif +#if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) +# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS +#endif +#if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS) +# define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS +#endif +#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS) +# define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS +#endif +#if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS) +# define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS +#endif + +// The goal of this macro is to avoid evaluation of the arguments, but +// still have the compiler warn on problems inside... +#if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN) +# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) +#endif + +#if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10) +# undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS +#elif defined(__clang__) && (__clang_major__ < 5) +# undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS +#endif + +#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS) +# define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS +#endif + +#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) +#define CATCH_TRY if ((true)) +#define CATCH_CATCH_ALL if ((false)) +#define CATCH_CATCH_ANON(type) if ((false)) +#else +#define CATCH_TRY try +#define CATCH_CATCH_ALL catch (...) +#define CATCH_CATCH_ANON(type) catch (type) +#endif + +#if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) +#define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#endif + +// end catch_compiler_capabilities.h +#define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line +#define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) +#ifdef CATCH_CONFIG_COUNTER +# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ ) +#else +# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ ) +#endif + +#include +#include +#include + +// We need a dummy global operator<< so we can bring it into Catch namespace later +struct Catch_global_namespace_dummy {}; +std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy); + +namespace Catch { + + struct CaseSensitive { enum Choice { + Yes, + No + }; }; + + class NonCopyable { + NonCopyable( NonCopyable const& ) = delete; + NonCopyable( NonCopyable && ) = delete; + NonCopyable& operator = ( NonCopyable const& ) = delete; + NonCopyable& operator = ( NonCopyable && ) = delete; + + protected: + NonCopyable(); + virtual ~NonCopyable(); + }; + + struct SourceLineInfo { + + SourceLineInfo() = delete; + SourceLineInfo( char const* _file, std::size_t _line ) noexcept + : file( _file ), + line( _line ) + {} + + SourceLineInfo( SourceLineInfo const& other ) = default; + SourceLineInfo& operator = ( SourceLineInfo const& ) = default; + SourceLineInfo( SourceLineInfo&& ) noexcept = default; + SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default; + + bool empty() const noexcept { return file[0] == '\0'; } + bool operator == ( SourceLineInfo const& other ) const noexcept; + bool operator < ( SourceLineInfo const& other ) const noexcept; + + char const* file; + std::size_t line; + }; + + std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ); + + // Bring in operator<< from global namespace into Catch namespace + // This is necessary because the overload of operator<< above makes + // lookup stop at namespace Catch + using ::operator<<; + + // Use this in variadic streaming macros to allow + // >> +StreamEndStop + // as well as + // >> stuff +StreamEndStop + struct StreamEndStop { + std::string operator+() const; + }; + template + T const& operator + ( T const& value, StreamEndStop ) { + return value; + } +} + +#define CATCH_INTERNAL_LINEINFO \ + ::Catch::SourceLineInfo( __FILE__, static_cast( __LINE__ ) ) + +// end catch_common.h +namespace Catch { + + struct RegistrarForTagAliases { + RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ); + }; + +} // end namespace Catch + +#define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \ + CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \ + CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION + +// end catch_tag_alias_autoregistrar.h +// start catch_test_registry.h + +// start catch_interfaces_testcase.h + +#include + +namespace Catch { + + class TestSpec; + + struct ITestInvoker { + virtual void invoke () const = 0; + virtual ~ITestInvoker(); + }; + + class TestCase; + struct IConfig; + + struct ITestCaseRegistry { + virtual ~ITestCaseRegistry(); + virtual std::vector const& getAllTests() const = 0; + virtual std::vector const& getAllTestsSorted( IConfig const& config ) const = 0; + }; + + bool isThrowSafe( TestCase const& testCase, IConfig const& config ); + bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ); + std::vector filterTests( std::vector const& testCases, TestSpec const& testSpec, IConfig const& config ); + std::vector const& getAllTestCasesSorted( IConfig const& config ); + +} + +// end catch_interfaces_testcase.h +// start catch_stringref.h + +#include +#include +#include +#include + +namespace Catch { + + /// A non-owning string class (similar to the forthcoming std::string_view) + /// Note that, because a StringRef may be a substring of another string, + /// it may not be null terminated. + class StringRef { + public: + using size_type = std::size_t; + using const_iterator = const char*; + + private: + static constexpr char const* const s_empty = ""; + + char const* m_start = s_empty; + size_type m_size = 0; + + public: // construction + constexpr StringRef() noexcept = default; + + StringRef( char const* rawChars ) noexcept; + + constexpr StringRef( char const* rawChars, size_type size ) noexcept + : m_start( rawChars ), + m_size( size ) + {} + + StringRef( std::string const& stdString ) noexcept + : m_start( stdString.c_str() ), + m_size( stdString.size() ) + {} + + explicit operator std::string() const { + return std::string(m_start, m_size); + } + + public: // operators + auto operator == ( StringRef const& other ) const noexcept -> bool; + auto operator != (StringRef const& other) const noexcept -> bool { + return !(*this == other); + } + + auto operator[] ( size_type index ) const noexcept -> char { + assert(index < m_size); + return m_start[index]; + } + + public: // named queries + constexpr auto empty() const noexcept -> bool { + return m_size == 0; + } + constexpr auto size() const noexcept -> size_type { + return m_size; + } + + // Returns the current start pointer. If the StringRef is not + // null-terminated, throws std::domain_exception + auto c_str() const -> char const*; + + public: // substrings and searches + // Returns a substring of [start, start + length). + // If start + length > size(), then the substring is [start, size()). + // If start > size(), then the substring is empty. + auto substr( size_type start, size_type length ) const noexcept -> StringRef; + + // Returns the current start pointer. May not be null-terminated. + auto data() const noexcept -> char const*; + + constexpr auto isNullTerminated() const noexcept -> bool { + return m_start[m_size] == '\0'; + } + + public: // iterators + constexpr const_iterator begin() const { return m_start; } + constexpr const_iterator end() const { return m_start + m_size; } + }; + + auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&; + auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&; + + constexpr auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef { + return StringRef( rawChars, size ); + } +} // namespace Catch + +constexpr auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef { + return Catch::StringRef( rawChars, size ); +} + +// end catch_stringref.h +// start catch_preprocessor.hpp + + +#define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__ +#define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__))) +#define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__))) +#define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__))) +#define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__))) +#define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__))) + +#ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__ +// MSVC needs more evaluations +#define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__))) +#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__)) +#else +#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__) +#endif + +#define CATCH_REC_END(...) +#define CATCH_REC_OUT + +#define CATCH_EMPTY() +#define CATCH_DEFER(id) id CATCH_EMPTY() + +#define CATCH_REC_GET_END2() 0, CATCH_REC_END +#define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2 +#define CATCH_REC_GET_END(...) CATCH_REC_GET_END1 +#define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT +#define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0) +#define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next) + +#define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ ) +#define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ ) +#define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ ) + +#define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ ) +#define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD) ) ( f, userdata, peek, __VA_ARGS__ ) +#define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ ) + +// Applies the function macro `f` to each of the remaining parameters, inserts commas between the results, +// and passes userdata as the first parameter to each invocation, +// e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c) +#define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) + +#define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) + +#define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param) +#define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__ +#define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__ +#define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF +#define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__) +#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__ +#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) +#else +// MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF +#define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__) +#define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__ +#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1) +#endif + +#define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__ +#define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name) + +#define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__) + +#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper()) +#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)) +#else +#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper())) +#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))) +#endif + +#define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\ + CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__) + +#define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0) +#define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1) +#define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2) +#define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3) +#define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4) +#define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5) +#define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _3, _4, _5, _6) +#define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7) +#define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8) +#define INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9) +#define INTERNAL_CATCH_REMOVE_PARENS_11_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10) + +#define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N + +#define INTERNAL_CATCH_TYPE_GEN\ + template struct TypeList {};\ + template\ + constexpr auto get_wrapper() noexcept -> TypeList { return {}; }\ + template class...> struct TemplateTypeList{};\ + template class...Cs>\ + constexpr auto get_wrapper() noexcept -> TemplateTypeList { return {}; }\ + template\ + struct append;\ + template\ + struct rewrap;\ + template class, typename...>\ + struct create;\ + template class, typename>\ + struct convert;\ + \ + template \ + struct append { using type = T; };\ + template< template class L1, typename...E1, template class L2, typename...E2, typename...Rest>\ + struct append, L2, Rest...> { using type = typename append, Rest...>::type; };\ + template< template class L1, typename...E1, typename...Rest>\ + struct append, TypeList, Rest...> { using type = L1; };\ + \ + template< template class Container, template class List, typename...elems>\ + struct rewrap, List> { using type = TypeList>; };\ + template< template class Container, template class List, class...Elems, typename...Elements>\ + struct rewrap, List, Elements...> { using type = typename append>, typename rewrap, Elements...>::type>::type; };\ + \ + template