diff --git a/.clang-format b/.clang-format index 368093632..0853a7826 100644 --- a/.clang-format +++ b/.clang-format @@ -1,5 +1,12 @@ # http://clang.llvm.org/docs/ClangFormatStyleOptions.html BasedOnStyle: Google -Standard: Cpp03 +Standard: c++11 AllowShortFunctionsOnASingleLine: Empty +IncludeBlocks: Preserve +IndentPPDirectives: AfterHash +DerivePointerAlignment: false + +# Always break after if to get accurate coverage +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false diff --git a/.devcontainer/clang10/devcontainer.json b/.devcontainer/clang10/devcontainer.json new file mode 100644 index 000000000..7fa61307a --- /dev/null +++ b/.devcontainer/clang10/devcontainer.json @@ -0,0 +1,18 @@ +{ + "name": "Clang 10", + "image": "conanio/clang10", + "runArgs": [ + "--name=ArduinoJson-clang10" + ], + "customizations": { + "vscode": { + "extensions": [ + "ms-vscode.cmake-tools" + ], + "settings": { + "cmake.generator": "Unix Makefiles", + "cmake.buildDirectory": "/tmp/build" + } + } + } +} diff --git a/.devcontainer/clang11/devcontainer.json b/.devcontainer/clang11/devcontainer.json new file mode 100644 index 000000000..572533eec --- /dev/null +++ b/.devcontainer/clang11/devcontainer.json @@ -0,0 +1,18 @@ +{ + "name": "Clang 11", + "image": "conanio/clang11", + "runArgs": [ + "--name=ArduinoJson-clang11" + ], + "customizations": { + "vscode": { + "extensions": [ + "ms-vscode.cmake-tools" + ], + "settings": { + "cmake.generator": "Unix Makefiles", + "cmake.buildDirectory": "/tmp/build" + } + } + } +} diff --git a/.devcontainer/clang13/Dockerfile b/.devcontainer/clang13/Dockerfile new file mode 100644 index 000000000..74f4c5f23 --- /dev/null +++ b/.devcontainer/clang13/Dockerfile @@ -0,0 +1,5 @@ +FROM ubuntu:22.04 + +RUN apt-get update +RUN apt-get install -y cmake git clang-13 libc++-13-dev libc++abi-13-dev +ENV CC=clang-13 CXX=clang++-13 diff --git a/.devcontainer/clang13/devcontainer.json b/.devcontainer/clang13/devcontainer.json new file mode 100644 index 000000000..fc747d5c1 --- /dev/null +++ b/.devcontainer/clang13/devcontainer.json @@ -0,0 +1,20 @@ +{ + "name": "Clang 13", + "build": { + "dockerfile": "Dockerfile" + }, + "runArgs": [ + "--name=ArduinoJson-clang13" + ], + "customizations": { + "vscode": { + "extensions": [ + "ms-vscode.cmake-tools" + ], + "settings": { + "cmake.generator": "Unix Makefiles", + "cmake.buildDirectory": "/tmp/build" + } + } + } +} diff --git a/.devcontainer/clang14/Dockerfile b/.devcontainer/clang14/Dockerfile new file mode 100644 index 000000000..0e7d67fa5 --- /dev/null +++ b/.devcontainer/clang14/Dockerfile @@ -0,0 +1,5 @@ +FROM ubuntu:22.04 + +RUN apt-get update +RUN apt-get install -y cmake git clang-14 libc++-14-dev libc++abi-14-dev +ENV CC=clang-14 CXX=clang++-14 diff --git a/.devcontainer/clang14/devcontainer.json b/.devcontainer/clang14/devcontainer.json new file mode 100644 index 000000000..716e824fb --- /dev/null +++ b/.devcontainer/clang14/devcontainer.json @@ -0,0 +1,20 @@ +{ + "name": "Clang 14", + "build": { + "dockerfile": "Dockerfile" + }, + "runArgs": [ + "--name=ArduinoJson-clang14" + ], + "customizations": { + "vscode": { + "extensions": [ + "ms-vscode.cmake-tools" + ], + "settings": { + "cmake.generator": "Unix Makefiles", + "cmake.buildDirectory": "/tmp/build" + } + } + } +} diff --git a/.devcontainer/clang15/Dockerfile b/.devcontainer/clang15/Dockerfile new file mode 100644 index 000000000..21abe15f8 --- /dev/null +++ b/.devcontainer/clang15/Dockerfile @@ -0,0 +1,5 @@ +FROM ubuntu:22.04 + +RUN apt-get update +RUN apt-get install -y cmake git clang-15 libc++-15-dev libc++abi-15-dev +ENV CC=clang-15 CXX=clang++-15 diff --git a/.devcontainer/clang15/devcontainer.json b/.devcontainer/clang15/devcontainer.json new file mode 100644 index 000000000..b802f2f13 --- /dev/null +++ b/.devcontainer/clang15/devcontainer.json @@ -0,0 +1,20 @@ +{ + "name": "Clang 15", + "build": { + "dockerfile": "Dockerfile" + }, + "runArgs": [ + "--name=ArduinoJson-clang15" + ], + "customizations": { + "vscode": { + "extensions": [ + "ms-vscode.cmake-tools" + ], + "settings": { + "cmake.generator": "Unix Makefiles", + "cmake.buildDirectory": "/tmp/build" + } + } + } +} diff --git a/.devcontainer/clang16/Dockerfile b/.devcontainer/clang16/Dockerfile new file mode 100644 index 000000000..206efc16b --- /dev/null +++ b/.devcontainer/clang16/Dockerfile @@ -0,0 +1,5 @@ +FROM ubuntu:22.04 + +RUN apt-get update +RUN apt-get install -y cmake git clang-16 libc++-16-dev libc++abi-16-dev +ENV CC=clang-16 CXX=clang++-16 diff --git a/.devcontainer/clang16/devcontainer.json b/.devcontainer/clang16/devcontainer.json new file mode 100644 index 000000000..650cf7988 --- /dev/null +++ b/.devcontainer/clang16/devcontainer.json @@ -0,0 +1,20 @@ +{ + "name": "Clang 16", + "build": { + "dockerfile": "Dockerfile" + }, + "runArgs": [ + "--name=ArduinoJson-clang16" + ], + "customizations": { + "vscode": { + "extensions": [ + "ms-vscode.cmake-tools" + ], + "settings": { + "cmake.generator": "Unix Makefiles", + "cmake.buildDirectory": "/tmp/build" + } + } + } +} diff --git a/.devcontainer/clang17/Dockerfile b/.devcontainer/clang17/Dockerfile new file mode 100644 index 000000000..1b4501a40 --- /dev/null +++ b/.devcontainer/clang17/Dockerfile @@ -0,0 +1,5 @@ +FROM ubuntu:24.04 + +RUN apt-get update +RUN apt-get install -y cmake git clang-17 libc++-17-dev libc++abi-17-dev +ENV CC=clang-17 CXX=clang++-17 diff --git a/.devcontainer/clang17/devcontainer.json b/.devcontainer/clang17/devcontainer.json new file mode 100644 index 000000000..6980f1c07 --- /dev/null +++ b/.devcontainer/clang17/devcontainer.json @@ -0,0 +1,20 @@ +{ + "name": "Clang 17", + "build": { + "dockerfile": "Dockerfile" + }, + "runArgs": [ + "--name=ArduinoJson-clang17" + ], + "customizations": { + "vscode": { + "extensions": [ + "ms-vscode.cmake-tools" + ], + "settings": { + "cmake.generator": "Unix Makefiles", + "cmake.buildDirectory": "/tmp/build" + } + } + } +} diff --git a/.devcontainer/clang5/devcontainer.json b/.devcontainer/clang5/devcontainer.json new file mode 100644 index 000000000..8844d1391 --- /dev/null +++ b/.devcontainer/clang5/devcontainer.json @@ -0,0 +1,18 @@ +{ + "name": "Clang 5", + "image": "conanio/clang50", + "runArgs": [ + "--name=ArduinoJson-clang5" + ], + "customizations": { + "vscode": { + "extensions": [ + "ms-vscode.cmake-tools" + ], + "settings": { + "cmake.generator": "Unix Makefiles", + "cmake.buildDirectory": "/tmp/build" + } + } + } +} diff --git a/.devcontainer/clang6/devcontainer.json b/.devcontainer/clang6/devcontainer.json new file mode 100644 index 000000000..e4a35f4f3 --- /dev/null +++ b/.devcontainer/clang6/devcontainer.json @@ -0,0 +1,18 @@ +{ + "name": "Clang 6", + "image": "conanio/clang60", + "runArgs": [ + "--name=ArduinoJson-clang6" + ], + "customizations": { + "vscode": { + "extensions": [ + "ms-vscode.cmake-tools" + ], + "settings": { + "cmake.generator": "Unix Makefiles", + "cmake.buildDirectory": "/tmp/build" + } + } + } +} diff --git a/.devcontainer/clang7/devcontainer.json b/.devcontainer/clang7/devcontainer.json new file mode 100644 index 000000000..1a8b55803 --- /dev/null +++ b/.devcontainer/clang7/devcontainer.json @@ -0,0 +1,18 @@ +{ + "name": "Clang 7", + "image": "conanio/clang7", + "runArgs": [ + "--name=ArduinoJson-clang7" + ], + "customizations": { + "vscode": { + "extensions": [ + "ms-vscode.cmake-tools" + ], + "settings": { + "cmake.generator": "Unix Makefiles", + "cmake.buildDirectory": "/tmp/build" + } + } + } +} diff --git a/.devcontainer/clang8/devcontainer.json b/.devcontainer/clang8/devcontainer.json new file mode 100644 index 000000000..7be768088 --- /dev/null +++ b/.devcontainer/clang8/devcontainer.json @@ -0,0 +1,18 @@ +{ + "name": "Clang 8", + "image": "conanio/clang8", + "runArgs": [ + "--name=ArduinoJson-clang8" + ], + "customizations": { + "vscode": { + "extensions": [ + "ms-vscode.cmake-tools" + ], + "settings": { + "cmake.generator": "Unix Makefiles", + "cmake.buildDirectory": "/tmp/build" + } + } + } +} diff --git a/.devcontainer/clang9/devcontainer.json b/.devcontainer/clang9/devcontainer.json new file mode 100644 index 000000000..46f07fc39 --- /dev/null +++ b/.devcontainer/clang9/devcontainer.json @@ -0,0 +1,18 @@ +{ + "name": "Clang 9", + "image": "conanio/clang9", + "runArgs": [ + "--name=ArduinoJson-clang9" + ], + "customizations": { + "vscode": { + "extensions": [ + "ms-vscode.cmake-tools" + ], + "settings": { + "cmake.generator": "Unix Makefiles", + "cmake.buildDirectory": "/tmp/build" + } + } + } +} diff --git a/.devcontainer/gcc10/devcontainer.json b/.devcontainer/gcc10/devcontainer.json new file mode 100644 index 000000000..d6dfba059 --- /dev/null +++ b/.devcontainer/gcc10/devcontainer.json @@ -0,0 +1,18 @@ +{ + "name": "GCC 10", + "image": "conanio/gcc10", + "runArgs": [ + "--name=ArduinoJson-gcc10" + ], + "customizations": { + "vscode": { + "extensions": [ + "ms-vscode.cmake-tools" + ], + "settings": { + "cmake.generator": "Unix Makefiles", + "cmake.buildDirectory": "/tmp/build" + } + } + } +} diff --git a/.devcontainer/gcc11/devcontainer.json b/.devcontainer/gcc11/devcontainer.json new file mode 100644 index 000000000..1edc308f7 --- /dev/null +++ b/.devcontainer/gcc11/devcontainer.json @@ -0,0 +1,18 @@ +{ + "name": "GCC 11", + "image": "conanio/gcc11", + "runArgs": [ + "--name=ArduinoJson-gcc11" + ], + "customizations": { + "vscode": { + "extensions": [ + "ms-vscode.cmake-tools" + ], + "settings": { + "cmake.generator": "Unix Makefiles", + "cmake.buildDirectory": "/tmp/build" + } + } + } +} diff --git a/.devcontainer/gcc12/Dockerfile b/.devcontainer/gcc12/Dockerfile new file mode 100644 index 000000000..a6275d437 --- /dev/null +++ b/.devcontainer/gcc12/Dockerfile @@ -0,0 +1,4 @@ +FROM ubuntu:22.04 + +RUN apt-get update +RUN apt-get install -y cmake git g++-12 diff --git a/.devcontainer/gcc12/devcontainer.json b/.devcontainer/gcc12/devcontainer.json new file mode 100644 index 000000000..8c744c899 --- /dev/null +++ b/.devcontainer/gcc12/devcontainer.json @@ -0,0 +1,20 @@ +{ + "name": "GCC 12", + "build": { + "dockerfile": "Dockerfile", + }, + "runArgs": [ + "--name=ArduinoJson-gcc12" + ], + "customizations": { + "vscode": { + "extensions": [ + "ms-vscode.cmake-tools" + ], + "settings": { + "cmake.generator": "Unix Makefiles", + "cmake.buildDirectory": "/tmp/build" + } + } + } +} diff --git a/.devcontainer/gcc48/devcontainer.json b/.devcontainer/gcc48/devcontainer.json new file mode 100644 index 000000000..660eac45d --- /dev/null +++ b/.devcontainer/gcc48/devcontainer.json @@ -0,0 +1,20 @@ +{ + "name": "GCC 4.8", + "image": "conanio/gcc48", + "runArgs": [ + "--name=ArduinoJson-gcc48" + ], + "customizations": { + "vscode": { + "extensions": [ + "ms-vscode.cmake-tools", + "josetr.cmake-language-support-vscode", + "ms-vscode.cpptools" + ], + "settings": { + "cmake.generator": "Unix Makefiles", + "cmake.buildDirectory": "/tmp/build" + } + } + } +} diff --git a/.devcontainer/gcc5/devcontainer.json b/.devcontainer/gcc5/devcontainer.json new file mode 100644 index 000000000..20ce7c11d --- /dev/null +++ b/.devcontainer/gcc5/devcontainer.json @@ -0,0 +1,18 @@ +{ + "name": "GCC 5", + "image": "conanio/gcc5", + "runArgs": [ + "--name=ArduinoJson-gcc5" + ], + "customizations": { + "vscode": { + "extensions": [ + "ms-vscode.cmake-tools" + ], + "settings": { + "cmake.generator": "Unix Makefiles", + "cmake.buildDirectory": "/tmp/build" + } + } + } +} diff --git a/.devcontainer/gcc6/devcontainer.json b/.devcontainer/gcc6/devcontainer.json new file mode 100644 index 000000000..35fb5fa25 --- /dev/null +++ b/.devcontainer/gcc6/devcontainer.json @@ -0,0 +1,18 @@ +{ + "name": "GCC 6", + "image": "conanio/gcc6", + "runArgs": [ + "--name=ArduinoJson-gcc6" + ], + "customizations": { + "vscode": { + "extensions": [ + "ms-vscode.cmake-tools" + ], + "settings": { + "cmake.generator": "Unix Makefiles", + "cmake.buildDirectory": "/tmp/build" + } + } + } +} diff --git a/.devcontainer/gcc7/devcontainer.json b/.devcontainer/gcc7/devcontainer.json new file mode 100644 index 000000000..28bab2082 --- /dev/null +++ b/.devcontainer/gcc7/devcontainer.json @@ -0,0 +1,18 @@ +{ + "name": "GCC 7", + "image": "conanio/gcc7", + "runArgs": [ + "--name=ArduinoJson-gcc7" + ], + "customizations": { + "vscode": { + "extensions": [ + "ms-vscode.cmake-tools" + ], + "settings": { + "cmake.generator": "Unix Makefiles", + "cmake.buildDirectory": "/tmp/build" + } + } + } +} diff --git a/.devcontainer/gcc8/devcontainer.json b/.devcontainer/gcc8/devcontainer.json new file mode 100644 index 000000000..622d47219 --- /dev/null +++ b/.devcontainer/gcc8/devcontainer.json @@ -0,0 +1,18 @@ +{ + "name": "GCC 8", + "image": "conanio/gcc8", + "runArgs": [ + "--name=ArduinoJson-gcc8" + ], + "customizations": { + "vscode": { + "extensions": [ + "ms-vscode.cmake-tools" + ], + "settings": { + "cmake.generator": "Unix Makefiles", + "cmake.buildDirectory": "/tmp/build" + } + } + } +} diff --git a/.devcontainer/gcc9/devcontainer.json b/.devcontainer/gcc9/devcontainer.json new file mode 100644 index 000000000..f946d9fb8 --- /dev/null +++ b/.devcontainer/gcc9/devcontainer.json @@ -0,0 +1,18 @@ +{ + "name": "GCC 9", + "image": "conanio/gcc9", + "runArgs": [ + "--name=ArduinoJson-gcc9" + ], + "customizations": { + "vscode": { + "extensions": [ + "ms-vscode.cmake-tools" + ], + "settings": { + "cmake.generator": "Unix Makefiles", + "cmake.buildDirectory": "/tmp/build" + } + } + } +} diff --git a/.gitattributes b/.gitattributes index 526c8a38d..efdba8764 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,2 @@ -*.sh text eol=lf \ No newline at end of file +* text=auto +*.sh text eol=lf diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 000000000..0ec57d0ac --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,4 @@ +github: bblanchon +custom: + - https://arduinojson.org/book/ + - https://donate.benoitblanchon.fr/ diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index a803d5cc7..000000000 --- a/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,11 +0,0 @@ - diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 000000000..57ee85179 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,54 @@ +--- +name: 🐛 Bug report +about: Report a bug in ArduinoJson +title: '' +labels: 'bug' +assignees: '' +--- + + + +**Describe the bug** +A clear and concise description of what the bug is. + +**Troubleshooter report** +Here is the report generated by the [ArduinoJson Troubleshooter](https://arduinojson.org/v7/troubleshooter/): +[Paste the report here] + +**Environment** +Here is the environment that I used: +* Microcontroller: [e.g. ESP8266] +* Core/runtime: [e.g. ESP8266 core for Arduino v3.0.2] +* IDE: [e.g. Arduino IDE 1.8.16] + +**Reproduction** +Here is a small snippet that reproduces the issue. + +```c++ +JsonDocument doc; + +DeserializationError error = deserializeJson(doc, "{\"hello\":\"world\"}"); + +[insert repro code here] +``` + +**Compiler output** +If relevant, include the complete compiler output (i.e. not just the line that contains the error.) + + +**Program output** +If relevant, include the repro program output. + +Expected output: + +``` +[insert expected output here] +``` + +Actual output: + +``` +[insert actual output here] +``` diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 000000000..5f69e8e98 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,8 @@ +blank_issues_enabled: true +contact_links: + - name: 👨‍🏫 ArduinoJson Assistant + url: https://arduinojson.org/v7/assistant/ + about: An online tool that computes memory requirements and generates scaffolding code for your project. + - name: 👨‍⚕️ ArduinoJson Troubleshooter + url: https://arduinojson.org/v7/troubleshooter/ + about: An online tool that helps you diagnose the most common issues with ArduinoJson. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 000000000..889baaf22 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,19 @@ +--- +name: 💡 Feature request +about: Suggest an idea for ArduinoJson +title: '' +labels: enhancement +assignees: '' +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/ISSUE_TEMPLATE/help.md b/.github/ISSUE_TEMPLATE/help.md new file mode 100644 index 000000000..4440b866a --- /dev/null +++ b/.github/ISSUE_TEMPLATE/help.md @@ -0,0 +1,51 @@ +--- +name: 😭 Help! +about: Ask for help +title: '' +labels: 'question' +assignees: '' +--- + + + +**Describe the issue** +A clear and concise description of what you're trying to do. +You don't need to explain every aspect of your project: focus on the problem you're having. + +**Troubleshooter report** +Here is the report generated by the [ArduinoJson Troubleshooter](https://arduinojson.org/v7/troubleshooter/): +[Paste the report here] + +**Environment** +Here is the environment that I'm using': +* Microconroller: [e.g. ESP8266] +* Core/runtime: [e.g. ESP8266 core for Arduino v3.0.2] +* IDE: [e.g. Arduino IDE 1.8.16] + +**Reproduction** +Here is a small snippet that demonstrate the problem. + +```c++ +JsonDocument doc; + +DeserializationError error = deserializeJson(doc, "{\"hello\":\"world\"}"); + +// insert code here +``` + +**Program output** +If relevant, include the program output. + +Expected output: + +``` +[insert expected output here] +``` + +Actual output: + +``` +[insert actual output here] +``` diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000..214bb6988 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,601 @@ +name: Continuous Integration + +on: [push, pull_request] + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + lint: + name: Lint + runs-on: ubuntu-22.04 + steps: + - name: Install + run: sudo apt-get install -y clang-format + - name: Checkout + uses: actions/checkout@v4 + - name: Symlinks + run: find * -type l -printf "::error::%p is a symlink. This is forbidden by the Arduino Library Specification." -exec false {} + + - name: Clang-format + run: | + find src/ extras/ -name '*.[ch]pp' | xargs clang-format -i --verbose --style=file + git diff --exit-code + - name: Check URLs + run: | + grep -hREo "(http|https)://[a-zA-Z0-9./?=_%:-]*" src/ | sort -u | while read -r URL + do + STATUS=$(curl -s -o /dev/null -I -w "%{http_code}" "$URL") + [ "$STATUS" -ge 400 ] && echo "::warning title=HTTP $STATUS::$URL returned $STATUS" + done || true + + gcc: + name: GCC + needs: lint + runs-on: ubuntu-22.04 + strategy: + fail-fast: false + matrix: + include: + - gcc: "4.8" + - gcc: "5" + - gcc: "6" + - gcc: "7" + cxxflags: -fsanitize=leak -fno-sanitize-recover=all + - gcc: "8" + cxxflags: -fsanitize=undefined -fno-sanitize-recover=all + - gcc: "9" + cxxflags: -fsanitize=address -fno-sanitize-recover=all + - gcc: "10" + cxxflags: -funsigned-char # Issue #1715 + - gcc: "11" + - gcc: "12" + steps: + - name: Workaround for actions/runner-images#9491 + run: sudo sysctl vm.mmap_rnd_bits=28 + + - name: Install + run: | + sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 40976EAF437D05B5 3B4FE6ACC0B21F32 + sudo add-apt-repository -yn 'deb http://archive.ubuntu.com/ubuntu/ xenial main universe' + sudo add-apt-repository -yn 'deb http://archive.ubuntu.com/ubuntu/ bionic main universe' + sudo add-apt-repository -yn 'deb http://archive.ubuntu.com/ubuntu/ focal main universe' + sudo apt-get update + sudo apt-get install -y gcc-${{ matrix.gcc }} g++-${{ matrix.gcc }} + timeout-minutes: 5 + + - name: Checkout + uses: actions/checkout@v4 + timeout-minutes: 1 + + - name: Configure + run: cmake -DCMAKE_BUILD_TYPE=Debug . + env: + CC: gcc-${{ matrix.gcc }} + CXX: g++-${{ matrix.gcc }} + CXXFLAGS: ${{ matrix.cxxflags }} + timeout-minutes: 1 + + - name: Build + run: cmake --build . + timeout-minutes: 10 + + - name: Test + run: ctest --output-on-failure -C Debug . + env: + UBSAN_OPTIONS: print_stacktrace=1 + timeout-minutes: 2 + + clang: + name: Clang + needs: lint + strategy: + fail-fast: false + matrix: + include: + - clang: "7" + runner: ubuntu-22.04 + archive: focal + - clang: "8" + cxxflags: -fsanitize=leak -fno-sanitize-recover=all + runner: ubuntu-22.04 + archive: focal + - clang: "9" + cxxflags: -fsanitize=undefined -fno-sanitize-recover=all + runner: ubuntu-22.04 + archive: focal + - clang: "10" + cxxflags: -fsanitize=address -fno-sanitize-recover=all + runner: ubuntu-22.04 + archive: focal + - clang: "11" + runner: ubuntu-22.04 + - clang: "12" + runner: ubuntu-22.04 + - clang: "13" + runner: ubuntu-22.04 + - clang: 14 + - clang: 15 + - clang: 16 + - clang: 17 + - clang: 18 + - clang: 19 + runs-on: ${{ matrix.runner || 'ubuntu-latest' }} + steps: + - name: Add archive repositories + if: matrix.archive + run: | + sudo gpg --keyserver keyserver.ubuntu.com --recv-keys 3B4FE6ACC0B21F32 + sudo gpg --export 3B4FE6ACC0B21F32 | sudo tee /etc/apt/trusted.gpg.d/ubuntu-keyring.gpg > /dev/null + sudo add-apt-repository -yn 'deb http://archive.ubuntu.com/ubuntu/ ${{ matrix.archive }} main' + sudo add-apt-repository -yn 'deb http://archive.ubuntu.com/ubuntu/ ${{ matrix.archive }} universe' + - name: Install Clang ${{ matrix.clang }} + run: | + sudo apt-get update + sudo apt-get install -y clang-${{ matrix.clang }} + - name: Install libc++ ${{ matrix.clang }} + run: sudo apt-get install -y libc++-${{ matrix.clang }}-dev libc++abi-${{ matrix.clang }}-dev + - name: Install libunwind ${{ matrix.clang }} + if: matrix.clang == 12 # dependency is missing in Ubuntu 22.04 + run: sudo apt-get install -y libunwind-${{ matrix.clang }}-dev + - name: Checkout + uses: actions/checkout@v4 + - name: Configure + run: cmake -DCMAKE_BUILD_TYPE=Debug . + env: + CC: clang-${{ matrix.clang }} + CXX: clang++-${{ matrix.clang }} + CXXFLAGS: >- + ${{ matrix.cxxflags }} + ${{ matrix.clang < 11 && '-I/usr/lib/llvm-10/include/c++/v1/' || '' }} + - name: Build + run: cmake --build . + - name: Test + run: ctest --output-on-failure -C Debug . + env: + UBSAN_OPTIONS: print_stacktrace=1 + + conf_test: + name: Test configuration on Linux + needs: [gcc, clang] + runs-on: ubuntu-22.04 + steps: + - name: Install + run: | + sudo apt-get update + sudo apt-get install -y g++-multilib gcc-avr avr-libc + - name: Checkout + uses: actions/checkout@v4 + - name: AVR + run: avr-g++ -std=c++11 -Isrc extras/conf_test/avr.cpp + - name: GCC 32-bit + run: g++ -std=c++11 -m32 -Isrc extras/conf_test/x86.cpp + - name: GCC 64-bit + run: g++ -std=c++11 -m64 -Isrc extras/conf_test/x64.cpp + - name: Clang 32-bit + run: clang++ -std=c++11 -m32 -Isrc extras/conf_test/x86.cpp + - name: Clang 64-bit + run: clang++ -std=c++11 -m64 -Isrc extras/conf_test/x64.cpp + + conf_test_windows: + name: Test configuration on Windows + runs-on: windows-2019 + needs: [gcc, clang] + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: 32-bit + run: | + call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\Build\vcvars32.bat" + cl /Isrc extras/conf_test/x86.cpp + shell: cmd + - name: 64-bit + run: | + call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\Build\vcvars64.bat" + cl /Isrc extras/conf_test/x64.cpp + shell: cmd + + xcode: + name: XCode + needs: clang + runs-on: macos-13 + strategy: + fail-fast: false + matrix: + include: + - xcode: "14.1" + - xcode: "14.2" + - xcode: "14.3.1" + - xcode: "15.0.1" + - xcode: "15.1" + - xcode: "15.2" + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Select XCode version + run: sudo xcode-select --switch /Applications/Xcode_${{ matrix.xcode }}.app + - name: Configure + run: cmake -DCMAKE_BUILD_TYPE=Debug . + - name: Build + run: cmake --build . + - name: Test + run: ctest --output-on-failure -C Debug . + + # DISABLED: Running on AppVeyor instead because it supports older versions of the compiler + # msvc: + # name: Visual Studio + # strategy: + # fail-fast: false + # matrix: + # include: + # - os: windows-2016 + # - os: windows-2019 + # runs-on: ${{ matrix.os }} + # steps: + # - name: Checkout + # uses: actions/checkout@v4 + # - name: Configure + # run: cmake -DCMAKE_BUILD_TYPE=Debug . + # - name: Build + # run: cmake --build . + # - name: Test + # run: ctest --output-on-failure -C Debug . + + arduino: + name: Arduino + needs: gcc + strategy: + fail-fast: false + matrix: + include: + - core: arduino:avr + board: arduino:avr:uno + - core: arduino:samd + board: arduino:samd:mkr1000 + runs-on: ubuntu-22.04 + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Install arduino-cli + run: curl -fsSL https://raw.githubusercontent.com/arduino/arduino-cli/master/install.sh | BINDIR=/usr/local/bin sh + - name: Install core + run: arduino-cli core install ${{ matrix.core }} + - name: Install libraries + run: arduino-cli lib install SD Ethernet + - name: Build JsonConfigFile + run: arduino-cli compile --library . --warnings all -b ${{ matrix.board }} "examples/JsonConfigFile/JsonConfigFile.ino" + - name: Build JsonFilterExample + run: arduino-cli compile --library . --warnings all -b ${{ matrix.board }} "examples/JsonFilterExample/JsonFilterExample.ino" + - name: Build JsonGeneratorExample + run: arduino-cli compile --library . --warnings all -b ${{ matrix.board }} "examples/JsonGeneratorExample/JsonGeneratorExample.ino" + - name: Build JsonHttpClient + run: arduino-cli compile --library . --warnings all -b ${{ matrix.board }} "examples/JsonHttpClient/JsonHttpClient.ino" + - name: Build JsonParserExample + run: arduino-cli compile --library . --warnings all -b ${{ matrix.board }} "examples/JsonParserExample/JsonParserExample.ino" + - name: Build JsonServer + run: arduino-cli compile --library . --warnings all -b ${{ matrix.board }} "examples/JsonServer/JsonServer.ino" + - name: Build JsonUdpBeacon + run: arduino-cli compile --library . --warnings all -b ${{ matrix.board }} "examples/JsonUdpBeacon/JsonUdpBeacon.ino" + - name: Build MsgPackParser + run: arduino-cli compile --library . --warnings all -b ${{ matrix.board }} "examples/MsgPackParser/MsgPackParser.ino" + - name: Build ProgmemExample + run: arduino-cli compile --library . --warnings all -b ${{ matrix.board }} "examples/ProgmemExample/ProgmemExample.ino" + - name: Build StringExample + run: arduino-cli compile --library . --warnings all -b ${{ matrix.board }} "examples/StringExample/StringExample.ino" + + platformio: + name: PlatformIO + needs: gcc + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + - platform: atmelavr + board: leonardo + libraries: + - SD + - Ethernet + conf_test: avr + - platform: espressif8266 + board: huzzah + conf_test: esp8266 + - platform: espressif32 + board: esp32dev + libraries: + - Ethernet + conf_test: esp8266 + - platform: atmelsam + board: mkr1000USB + libraries: + - SD + - Ethernet + conf_test: esp8266 + - platform: teensy + board: teensy31 + conf_test: esp8266 + - platform: ststm32 + board: adafruit_feather_f405 + libraries: + - SD + - Ethernet + conf_test: esp8266 + - platform: nordicnrf52 + board: adafruit_feather_nrf52840 + libraries: + - SD + - Ethernet + conf_test: esp8266 + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Set up cache for pip + uses: actions/cache@v4 + with: + path: ~/.cache/pip + key: ${{ runner.os }}-pip + - name: Set up Python 3.x + uses: actions/setup-python@v5 + with: + python-version: "3.x" + - name: Install PlatformIO + run: pip install platformio + - name: Install adafruit-nrfutil + if: ${{ matrix.platform == 'nordicnrf52' }} + run: pip install adafruit-nrfutil + - name: Include Adafruit_TinyUSB.h # https://github.com/adafruit/Adafruit_nRF52_Arduino/issues/653 + if: ${{ matrix.platform == 'nordicnrf52' }} + run: find examples/ -name '*.ino' -exec sed -i 's/\(#include \)/\1\n#include /' {} + + - name: Set up cache for platformio + uses: actions/cache@v4 + with: + path: ~/.platformio + key: ${{ runner.os }}-platformio-${{ matrix.platform }} + - name: Install platform "${{ matrix.platform }}" + run: platformio platform install ${{ matrix.platform }} + - name: Install libraries + if: ${{ matrix.libraries }} + run: platformio lib install arduino-libraries/${{ join(matrix.libraries, ' arduino-libraries/') }} + - name: Test configuration + run: platformio ci "extras/conf_test/${{ matrix.conf_test }}.cpp" -l '.' -b ${{ matrix.board }} + if: ${{ matrix.conf_test }} + - name: Build JsonConfigFile + run: platformio ci "examples/JsonConfigFile/JsonConfigFile.ino" -l '.' -b ${{ matrix.board }} + - name: Build JsonFilterExample + run: platformio ci "examples/JsonFilterExample/JsonFilterExample.ino" -l '.' -b ${{ matrix.board }} + - name: Build JsonGeneratorExample + run: platformio ci "examples/JsonGeneratorExample/JsonGeneratorExample.ino" -l '.' -b ${{ matrix.board }} + - name: Build JsonHttpClient + run: platformio ci "examples/JsonHttpClient/JsonHttpClient.ino" -l '.' -b ${{ matrix.board }} + - name: Build JsonParserExample + run: platformio ci "examples/JsonParserExample/JsonParserExample.ino" -l '.' -b ${{ matrix.board }} + - name: Build JsonServer + if: ${{ matrix.platform != 'espressif32' }} + run: platformio ci "examples/JsonServer/JsonServer.ino" -l '.' -b ${{ matrix.board }} + - name: Build JsonUdpBeacon + run: platformio ci "examples/JsonUdpBeacon/JsonUdpBeacon.ino" -l '.' -b ${{ matrix.board }} + - name: Build MsgPackParser + run: platformio ci "examples/MsgPackParser/MsgPackParser.ino" -l '.' -b ${{ matrix.board }} + - name: Build ProgmemExample + run: platformio ci "examples/ProgmemExample/ProgmemExample.ino" -l '.' -b ${{ matrix.board }} + - name: Build StringExample + run: platformio ci "examples/StringExample/StringExample.ino" -l '.' -b ${{ matrix.board }} + - name: PlatformIO prune + if: ${{ always() }} + run: platformio system prune -f + + particle: + name: Particle + needs: gcc + runs-on: ubuntu-latest + if: github.event_name == 'push' + strategy: + fail-fast: false + matrix: + include: + - board: argon + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Install Particle CLI + run: sudo npm install -g particle-cli + - name: Login to Particle + run: particle login -t "${{ secrets.PARTICLE_TOKEN }}" + - name: Compile + run: extras/ci/particle.sh ${{ matrix.board }} + + arm: + name: GCC for ARM processor + needs: gcc + runs-on: ubuntu-22.04 + steps: + - name: Install + run: | + sudo apt-get update + sudo apt-get install -y g++-arm-linux-gnueabihf + - name: Checkout + uses: actions/checkout@v4 + - name: Configure + run: cmake . + env: + CC: arm-linux-gnueabihf-gcc + CXX: arm-linux-gnueabihf-g++ + - name: Build + run: cmake --build . + + coverage: + needs: gcc + name: Coverage + runs-on: ubuntu-22.04 + steps: + - name: Install + run: sudo apt-get install -y lcov ninja-build + - name: Checkout + uses: actions/checkout@v4 + - name: Configure + run: cmake -G Ninja -DCOVERAGE=true . + - name: Build + run: ninja + - name: Test + run: ctest --output-on-failure -LE 'WillFail|Fuzzing' -T test + - name: lcov --capture + run: lcov --capture --no-external --directory . --output-file coverage.info + - name: lcov --remove + run: lcov --remove coverage.info "$(pwd)/extras/*" --output-file coverage_filtered.info + - name: genhtml + run: mkdir coverage && genhtml coverage_filtered.info -o coverage -t ArduinoJson + - name: Upload HTML report + uses: actions/upload-artifact@v4 + with: + name: Coverage report + path: coverage + - name: Upload to Coveralls + uses: coverallsapp/github-action@v2 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + path-to-lcov: coverage_filtered.info + + valgrind: + needs: gcc + name: Valgrind + runs-on: ubuntu-22.04 + steps: + - name: Install + run: | + sudo apt-get update + sudo apt-get install -y valgrind ninja-build + - name: Checkout + uses: actions/checkout@v4 + - name: Configure + run: cmake -G Ninja -D MEMORYCHECK_COMMAND_OPTIONS="--error-exitcode=1 --leak-check=full" . + - name: Build + run: ninja + - name: Memcheck + run: ctest --output-on-failure -LE WillFail -T memcheck + id: memcheck + - name: MemoryChecker.*.log + run: cat Testing/Temporary/MemoryChecker.*.log > $GITHUB_STEP_SUMMARY + if: failure() + + clang-tidy: + needs: clang + name: Clang-Tidy + runs-on: ubuntu-latest + steps: + - name: Install + run: sudo apt-get install -y clang-tidy libc++-dev libc++abi-dev + - name: Checkout + uses: actions/checkout@v4 + - name: Configure + run: cmake -G Ninja -DCMAKE_CXX_CLANG_TIDY="clang-tidy;--warnings-as-errors=*" -DCMAKE_BUILD_TYPE=Debug . + env: + CC: clang + CXX: clang++ + - name: Check + run: cmake --build . -- -k 0 + + amalgamate: + needs: gcc + name: Amalgamate ArduinoJson.h + runs-on: ubuntu-22.04 + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Setup + run: | + if [[ $GITHUB_REF == refs/tags/* ]]; then + VERSION=${GITHUB_REF#refs/tags/} + else + VERSION=${GITHUB_SHA::7} + fi + echo "ARDUINOJSON_H=ArduinoJson-$VERSION.h" >> $GITHUB_ENV + echo "ARDUINOJSON_HPP=ArduinoJson-$VERSION.hpp" >> $GITHUB_ENV + - name: Amalgamate ArduinoJson.h + run: extras/scripts/build-single-header.sh "src/ArduinoJson.h" "$ARDUINOJSON_H" + - name: Amalgamate ArduinoJson.hpp + run: extras/scripts/build-single-header.sh "src/ArduinoJson.hpp" "$ARDUINOJSON_HPP" + - name: Upload artifact + uses: actions/upload-artifact@v4 + with: + name: Single headers + path: | + ${{ env.ARDUINOJSON_H }} + ${{ env.ARDUINOJSON_HPP }} + - name: Smoke test ArduinoJson.h + run: | + g++ -x c++ - <> $GITHUB_OUTPUT + echo "version=${GITHUB_REF#refs/tags/v}" >> $GITHUB_OUTPUT + - name: Checkout + uses: actions/checkout@v4 + - name: Write release body + id: body + run: | + FILENAME=RELEASE.md + tee $FILENAME <> $GITHUB_OUTPUT + - name: Amalgamate ArduinoJson.h + id: amalgamate_h + run: | + FILENAME=ArduinoJson-${{ steps.init.outputs.tag }}.h + extras/scripts/build-single-header.sh src/ArduinoJson.h "$FILENAME" + echo "filename=$FILENAME" >> $GITHUB_OUTPUT + - name: Amalgamate ArduinoJson.hpp + id: amalgamate_hpp + run: | + FILENAME=ArduinoJson-${{ steps.init.outputs.tag }}.hpp + extras/scripts/build-single-header.sh src/ArduinoJson.hpp "$FILENAME" + echo "filename=$FILENAME" >> $GITHUB_OUTPUT + - name: Create release + uses: ncipollo/release-action@v1 + with: + bodyFile: ${{ steps.body.outputs.filename }} + name: ArduinoJson ${{ steps.init.outputs.version }} + artifacts: ${{ steps.amalgamate_h.outputs.filename }},${{ steps.amalgamate_hpp.outputs.filename }} + token: ${{ secrets.GITHUB_TOKEN }} + + idf: + name: IDF Component Registry + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Upload component to the component registry + uses: espressif/upload-components-ci-action@v1 + with: + name: ArduinoJson + namespace: bblanchon + api_token: ${{ secrets.IDF_COMPONENT_API_TOKEN }} + + particle: + name: Particle + runs-on: ubuntu-latest + steps: + - name: Install + run: npm install -g particle-cli + - name: Checkout + uses: actions/checkout@v4 + - name: Login + run: particle login --token ${{ secrets.PARTICLE_TOKEN }} + - name: Publish + run: bash -eux extras/scripts/publish-particle-library.sh + + platformio: + name: PlatformIO + runs-on: ubuntu-latest + steps: + - name: Set up Python 3.x + uses: actions/setup-python@v5 + with: + python-version: "3.x" + - name: Install PlatformIO + run: pip install platformio + - name: Checkout + uses: actions/checkout@v4 + - name: Publish + run: pio pkg publish --no-interactive --no-notify + env: + PLATFORMIO_AUTH_TOKEN: ${{ secrets.PLATFORMIO_AUTH_TOKEN }} diff --git a/.gitignore b/.gitignore index 567dc13be..b2b9c95c0 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,15 @@ /sftp-config.json .tags .tags_sorted_by_file -/fuzzing/*_fuzzer -/fuzzing/*_fuzzer.options -/fuzzing/*_fuzzer_seed_corpus.zip +/extras/fuzzing/*_fuzzer +/extras/fuzzing/*_fuzzer.options +/extras/fuzzing/*_fuzzer_seed_corpus.zip +.vs/ +/out/ + +# Used by CI for Particle +/src/*.ino +/project.properties + +# Used by IDF +/dist/ diff --git a/.mbedignore b/.mbedignore index b52329d15..c5da30d91 100644 --- a/.mbedignore +++ b/.mbedignore @@ -1,6 +1,4 @@ +.devcontainer/ .github/ examples/ -fuzzing/ -scripts/ -test/ -third-party/ +extras/ diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 000000000..dd449725e --- /dev/null +++ b/.prettierignore @@ -0,0 +1 @@ +*.md diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 21f5f9bc0..000000000 --- a/.travis.yml +++ /dev/null @@ -1,104 +0,0 @@ -sudo: false -language: cpp -matrix: - include: - - compiler: gcc - addons: - apt: - sources: ['ubuntu-toolchain-r-test'] - packages: ['g++-4.4'] - env: SCRIPT=cmake GCC=4.4 - - compiler: gcc - addons: - apt: - sources: ['ubuntu-toolchain-r-test'] - packages: ['g++-4.5'] - env: SCRIPT=cmake GCC=4.5 - - compiler: gcc - addons: - apt: - sources: ['ubuntu-toolchain-r-test'] - packages: ['g++-4.6'] - env: SCRIPT=cmake GCC=4.6 - - compiler: gcc - addons: - apt: - sources: ['ubuntu-toolchain-r-test'] - packages: ['g++-4.7'] - env: SCRIPT=cmake GCC=4.7 - - compiler: gcc - addons: - apt: - sources: ['ubuntu-toolchain-r-test'] - packages: ['g++-4.8'] - env: SCRIPT=cmake GCC=4.8 SANITIZE=address - - compiler: gcc - addons: - apt: - sources: ['ubuntu-toolchain-r-test'] - packages: ['g++-4.9'] - env: SCRIPT=cmake GCC=4.9 SANITIZE=leak - - compiler: gcc - addons: - apt: - sources: ['ubuntu-toolchain-r-test'] - packages: ['g++-5'] - env: SCRIPT=cmake GCC=5 SANITIZE=undefined - - compiler: clang - env: SCRIPT=cmake - - compiler: clang - addons: - apt: - sources: ['ubuntu-toolchain-r-test','llvm-toolchain-precise-3.5'] - packages: ['clang-3.5'] - env: SCRIPT=cmake CLANG=3.5 SANITIZE=address - - compiler: clang - addons: - apt: - sources: ['ubuntu-toolchain-r-test','llvm-toolchain-precise-3.6'] - packages: ['clang-3.6'] - env: SCRIPT=cmake CLANG=3.6 SANITIZE=leak - - compiler: clang - addons: - apt: - sources: ['ubuntu-toolchain-r-test','llvm-toolchain-precise-3.7'] - packages: ['clang-3.7'] - env: SCRIPT=cmake CLANG=3.7 - - compiler: clang - addons: - apt: - sources: ['ubuntu-toolchain-r-test','llvm-toolchain-precise-3.8'] - packages: ['clang-3.8'] - env: SCRIPT=cmake CLANG=3.8 SANITIZE=undefined - - compiler: gcc - env: SCRIPT=coverage - - os: osx - osx_image: xcode6.4 - compiler: clang - env: SCRIPT=cmake - - os: osx - osx_image: xcode7 - compiler: clang - env: SCRIPT=cmake - - os: osx - osx_image: xcode7.1 - compiler: clang - env: SCRIPT=cmake - - os: osx - osx_image: xcode7.2 - compiler: clang - env: SCRIPT=cmake - - os: osx - osx_image: xcode7.3 - compiler: clang - env: SCRIPT=cmake SANITIZE=address - - env: SCRIPT=arduino VERSION=1.6.7 BOARD=arduino:avr:uno - - env: SCRIPT=arduino VERSION=1.6.12 BOARD=arduino:avr:uno - - env: SCRIPT=platformio BOARD=uno - - env: SCRIPT=platformio BOARD=due - - env: SCRIPT=platformio BOARD=esp01 - - env: SCRIPT=platformio BOARD=teensy31 -cache: - directories: - - "~/.platformio" -script: scripts/travis/$SCRIPT.sh diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 000000000..350c40014 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,17 @@ +{ + "C_Cpp.default.configurationProvider": "ms-vscode.cmake-tools", + "git.inputValidationLength": 80, + "git.inputValidationSubjectLength": 72, + "files.insertFinalNewline": true, + "files.trimFinalNewlines": true, + "search.exclude": { + "/extras/tests/catch/*": true + }, + "C_Cpp.default.includePath": [ + "/src" + ], + "[cmake]": { + "editor.detectIndentation": false, + "editor.insertSpaces": false, + } +} diff --git a/ArduinoJson.h b/ArduinoJson.h index ffea66013..a0caed799 100644 --- a/ArduinoJson.h +++ b/ArduinoJson.h @@ -1,8 +1,5 @@ -// Copyright Benoit Blanchon 2014-2017 +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON // MIT License -// -// Arduino JSON library -// https://github.com/bblanchon/ArduinoJson -// If you like this project, please add a star! -#include "include/ArduinoJson.h" +#include "src/ArduinoJson.h" diff --git a/CHANGELOG.md b/CHANGELOG.md index d07a57ce3..a0a7a6f6a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,427 +1,255 @@ ArduinoJson: change log ======================= -v5.8.3 ------- - -* Fixed an access violation in `DynamicJsonBuffer` when memory allocation fails (issue #433) -* Added operators `==` and `!=` for two `JsonVariant`s (issue #436) -* Fixed `JsonVariant::operator[const FlashStringHelper*]` (issue #441) - -v5.8.2 ------- - -* Fixed parsing of comments (issue #421) -* Fixed ignored `Stream` timeout (issue #422) -* Made sure we don't read more that necessary (issue #422) -* Fixed error when the key of a `JsonObject` is a `char[]` (issue #423) -* Reduced code size when using `const` references -* Fixed error with string of type `unsigned char*` (issue #428) -* Added `deprecated` attribute on `asArray()`, `asObject()` and `asString()` (issue #420) - -v5.8.1 ------- - -* Fixed error when assigning a `volatile int` to a `JsonVariant` (issue #415) -* Fixed errors with Variable Length Arrays (issue #416) -* Fixed error when both `ARDUINOJSON_ENABLE_STD_STREAM` and `ARDUINOJSON_ENABLE_ARDUINO_STREAM` are set to `1` -* Fixed error "Stream does not name a type" (issue #412) - -v5.8.0 ------- - -* Added operator `==` to compare `JsonVariant` and strings (issue #402) -* Added support for `Stream` (issue #300) -* Reduced memory consumption by not duplicating spaces and comments - -**BREAKING CHANGES**: - -`JsonBuffer::parseObject()` and `JsonBuffer::parseArray()` have been pulled down to the derived classes `DynamicJsonBuffer` and `StaticJsonBufferBase`. - -This means that if you have code like: - -```c++ -void myFunction(JsonBuffer& jsonBuffer); -``` - -you need to replace it with one of the following: - -```c++ -void myFunction(DynamicJsonBuffer& jsonBuffer); -void myFunction(StaticJsonBufferBase& jsonBuffer); -template void myFunction(TJsonBuffer& jsonBuffer); -``` - -v5.7.3 ------- - -* Added an `printTo(char[N])` and `prettyPrintTo(char[N])` (issue #292) -* Added ability to set a nested value like this: `root["A"]["B"] = "C"` (issue #352) -* Renamed `*.ipp` to `*Impl.hpp` because they were ignored by Arduino IDE (issue #396) - -v5.7.2 ------- - -* Made PROGMEM available on more platforms (issue #381) -* Fixed PROGMEM causing an exception on ESP8266 (issue #383) - -v5.7.1 ------- - -* Added support for PROGMEM (issue #76) -* Fixed compilation error when index is not an `int` (issue #381) - -v5.7.0 ------- - -* Templatized all functions using `String` or `std::string` -* Removed `ArduinoJson::String` -* Removed `JsonVariant::defaultValue()` -* Removed non-template `JsonObject::get()` and `JsonArray.get()` -* Fixed support for `StringSumHelper` (issue #184) -* Replaced `ARDUINOJSON_USE_ARDUINO_STRING` by `ARDUINOJSON_ENABLE_STD_STRING` and `ARDUINOJSON_ENABLE_ARDUINO_STRING` (issue #378) -* Added example `StringExample.ino` to show where `String` can be used -* Increased default nesting limit to 50 when compiled for a computer (issue #349) - -**BREAKING CHANGES**: - -The non-template functions `JsonObject::get()` and `JsonArray.get()` have been removed. This means that you need to explicitely tell the type you expect in return. - -Old code: - -```c++ -#define ARDUINOJSON_USE_ARDUINO_STRING 0 -JsonVariant value1 = myObject.get("myKey"); -JsonVariant value2 = myArray.get(0); -``` - -New code: - -```c++ -#define ARDUINOJSON_ENABLE_ARDUINO_STRING 0 -#define ARDUINOJSON_ENABLE_STD_STRING 1 -JsonVariant value1 = myObject.get("myKey"); -JsonVariant value2 = myArray.get(0); -``` - - -v5.6.7 ------- - -* Fixed `array[idx].as()` and `object[key].as()` -* Fixed return value of `JsonObject::set()` (issue #350) -* Fixed undefined behavior in `Prettyfier` and `Print` (issue #354) -* Fixed parser that incorrectly rejected floats containing a `+` (issue #349) - -v5.6.6 ------- - -* Fixed `-Wparentheses` warning introduced in v5.6.5 (PR #335 by @nuket) -* Added `.mbedignore` for ARM mbdeb (PR #334 by @nuket) -* Fixed `JsonVariant::success()` which didn't propagate `JsonArray::success()` nor `JsonObject::success()` (issue #342). - -v5.6.5 ------- - -* `as()` now returns `true` when input is `null` (issue #330) - -v5.6.4 ------- - -* Fixed error in float serialization (issue #324) - -v5.6.3 ------- - -* Improved speed of float serialization (about twice faster) -* Added `as()` as a synonym for `as()`... (issue #291) -* Fixed `call of overloaded isinf(double&) is ambiguous` (issue #284) - -v5.6.2 ------- - -* Fixed build when another lib does `#undef isnan` (issue #284) - -v5.6.1 ------- - -* Added missing `#pragma once` (issue #310) - -v5.6.0 ------- - -* ArduinoJson is now a header-only library (issue #199) - -v5.5.1 ------- - -* Fixed compilation error with Intel Galileo (issue #299) - -v5.5.0 ------- - -* Added `JsonVariant::success()` (issue #279) -* Renamed `JsonVariant::invalid()` to `JsonVariant::defaultValue()` - -v5.4.0 ------- - -* Changed `::String` to `ArduinoJson::String` (issue #275) -* Changed `::Print` to `ArduinoJson::Print` too - -v5.3.0 ------- - -* Added custom implementation of `ftoa` (issues #266, #267, #269 and #270) -* Added `JsonVariant JsonBuffer::parse()` (issue #265) -* Fixed `unsigned long` printed as `signed long` (issue #170) - -v5.2.0 ------- - -* Added `JsonVariant::as()` as a synonym for `JsonVariant::as()` (issue #257) -* Added example `JsonHttpClient` (issue #256) -* Added `JsonArray::copyTo()` and `JsonArray::copyFrom()` (issue #254) -* Added `RawJson()` to insert pregenerated JSON portions (issue #259) - -v5.1.1 ------- - -* Removed `String` duplication when one replaces a value in a `JsonObject` (PR #232 by @ulion) - -v5.1.0 ------- - -* Added support of `long long` (issue #171) -* Moved all build settings to `ArduinoJson/Configuration.hpp` +v7.4.2 (2025-06-20) +------ + +* Fix truncated strings on Arduino Due (issue #2181) + +v7.4.1 (2025-04-11) +------ + +* Fix crash with tiny Flash strings (issue #2170) + +v7.4.0 (2025-04-09) +------ + +* Optimize storage of tiny strings (up to 3 characters) +* Fix support for `const char[]` (issue #2166) + +v7.3.1 (2025-02-27) +------ + +* Fix conversion from static string to number +* Slightly reduce code size + +v7.3.0 (2024-12-29) +------ + +* Fix support for NUL characters in `deserializeJson()` +* Make `ElementProxy` and `MemberProxy` non-copyable +* Change string copy policy: only string literal are stored by pointer +* `JsonString` is now stored by copy, unless specified otherwise +* Replace undocumented `JsonString::Ownership` with `bool` +* Rename undocumented `JsonString::isLinked()` to `isStatic()` +* Move public facing SFINAEs to template declarations -**BREAKING CHANGE**: -If you defined `ARDUINOJSON_ENABLE_STD_STREAM`, you now need to define it to `1`. +> ### BREAKING CHANGES +> +> In previous versions, `MemberProxy` (the class returned by `operator[]`) could lead to dangling pointers when used with a temporary string. +> To prevent this issue, `MemberProxy` and `ElementProxy` are now non-copyable. +> +> Your code is likely to be affected if you use `auto` to store the result of `operator[]`. For example, the following line won't compile anymore: +> +> ```cpp +> auto value = doc["key"]; +> ``` +> +> To fix the issue, you must append either `.as()` or `.to()`, depending on the situation. +> +> For example, if you are extracting values from a JSON document, you should update like this: +> +> ```diff +> - auto config = doc["config"]; +> + auto config = doc["config"].as(); +> const char* name = config["name"]; +> ``` +> +> However, if you are building a JSON document, you should update like this: +> +> ```diff +> - auto config = doc["config"]; +> + auto config = doc["config"].to(); +> config["name"] = "ArduinoJson"; +> ``` -v5.0.8 +v7.2.1 (2024-11-15) ------ -* Made the library compatible with [PlatformIO](http://platformio.org/) (issue #181) -* Fixed `JsonVariant::is()` that was incorrectly returning false (issue #214) - -v5.0.7 ------- - -* Made library easier to use from a CMake project: simply `add_subdirectory(ArduinoJson/src)` -* Changed `String` to be a `typedef` of `std::string` (issues #142 and #161) - -**BREAKING CHANGES**: -- `JsonVariant(true).as()` now returns `"true"` instead of `"1"` -- `JsonVariant(false).as()` now returns `"false"` instead of `"0"` - -v5.0.6 ------- - -* Added parameter to `DynamicJsonBuffer` constructor to set initial size (issue #152) -* Fixed warning about library category in Arduino 1.6.6 (issue #147) -* Examples: Added a loop to wait for serial port to be ready (issue #156) - -v5.0.5 ------- - -* Added overload `JsonObjectSuscript::set(value, decimals)` (issue #143) -* Use `float` instead of `double` to reduce the size of `JsonVariant` (issue #134) - -v5.0.4 ------- - -* Fixed ambiguous overload with `JsonArraySubscript` and `JsonObjectSubscript` (issue #122) - -v5.0.3 ------- - -* Fixed `printTo(String)` which wrote numbers instead of strings (issue #120) -* Fixed return type of `JsonArray::is()` and some others (issue #121) - -v5.0.2 ------- - -* Fixed segmentation fault in `parseObject(String)` and `parseArray(String)`, when the - `StaticJsonBuffer` is too small to hold a copy of the string -* Fixed Clang warning "register specifier is deprecated" (issue #102) -* Fixed GCC warning "declaration shadows a member" (issue #103) -* Fixed memory alignment, which made ESP8266 crash (issue #104) -* Fixed compilation on Visual Studio 2010 and 2012 (issue #107) - -v5.0.1 ------- - -* Fixed compilation with Arduino 1.0.6 (issue #99) - -v5.0.0 ------- - -* Added support of `String` class (issues #55, #56, #70, #77) -* Added `JsonBuffer::strdup()` to make a copy of a string (issues #10, #57) -* Implicitly call `strdup()` for `String` but not for `char*` (issues #84, #87) -* Added support of non standard JSON input (issue #44) -* Added support of comments in JSON input (issue #88) -* Added implicit cast between numerical types (issues #64, #69, #93) -* Added ability to read number values as string (issue #90) -* Redesigned `JsonVariant` to leverage converting constructors instead of assignment operators (issue #66) -* Switched to new the library layout (requires Arduino 1.0.6 or above) - -**BREAKING CHANGES**: -- `JsonObject::add()` was renamed to `set()` -- `JsonArray::at()` and `JsonObject::at()` were renamed to `get()` -- Number of digits of floating point value are now set with `double_with_n_digits()` - -**Personal note about the `String` class**: -Support of the `String` class has been added to the library because many people use it in their programs. -However, you should not see this as an invitation to use the `String` class. -The `String` class is **bad** because it uses dynamic memory allocation. -Compared to static allocation, it compiles to a bigger, slower program, and is less predictable. -You certainly don't want that in an embedded environment! - -v4.6 ----- - -* Fixed segmentation fault in `DynamicJsonBuffer` when memory allocation fails (issue #92) - -v4.5 ----- - -* Fixed buffer overflow when input contains a backslash followed by a terminator (issue #81) - -**Upgrading is recommended** since previous versions contain a potential security risk. - -Special thanks to [Giancarlo Canales Barreto](https://github.com/gcanalesb) for finding this nasty bug. - -v4.4 ----- - -* Added `JsonArray::measureLength()` and `JsonObject::measureLength()` (issue #75) - -v4.3 ----- - -* Added `JsonArray::removeAt()` to remove an element of an array (issue #58) -* Fixed stack-overflow in `DynamicJsonBuffer` when parsing huge JSON files (issue #65) -* Fixed wrong return value of `parseArray()` and `parseObject()` when allocation fails (issue #68) - -v4.2 ----- - -* Switched back to old library layout (issues #39, #43 and #45) -* Removed global new operator overload (issue #40, #45 and #46) -* Added an example with EthernetServer - -v4.1 ----- - -* Added DynamicJsonBuffer (issue #19) - -v4.0 ----- - -* Unified parser and generator API (issue #23) -* Updated library layout, now requires Arduino 1.0.6 or newer - -**BREAKING CHANGE**: API changed significantly, see [Migrating code to the new API](https://github.com/bblanchon/ArduinoJson/wiki/Migrating-code-to-the-new-API). - - -v3.4 ----- - -* Fixed escaped char parsing (issue #16) - - -v3.3 ----- - -* Added indented output for the JSON generator (issue #11), see example bellow. -* Added `IndentedPrint`, a decorator for `Print` to allow indented output - -Example: - - JsonOject<2> json; - json["key"] = "value"; - json.prettyPrintTo(Serial); - -v3.2 ----- - -* Fixed a bug when adding nested object in `JsonArray` (bug introduced in v3.1). - -v3.1 ----- - -* Calling `Generator::JsonObject::add()` twice with the same `key` now replaces the `value` -* Added `Generator::JsonObject::operator[]`, see bellow the new API -* Added `Generator::JsonObject::remove()` (issue #9) - -Old generator API: - - JsonObject<3> root; - root.add("sensor", "gps"); - root.add("time", 1351824120); - root.add("data", array); - -New generator API: - - JsonObject<3> root; - root["sensor"] = "gps"; - root["time"] = 1351824120; - root["data"] = array; - -v3.0 ----- - -* New parser API, see bellow -* Renamed `JsonHashTable` into `JsonObject` -* Added iterators for `JsonArray` and `JsonObject` (issue #4) - -Old parser API: - - JsonHashTable root = parser.parseHashTable(json); - - char* sensor = root.getString("sensor"); - long time = root.getLong("time"); - double latitude = root.getArray("data").getDouble(0); - double longitude = root.getArray("data").getDouble(1); - -New parser API: - - JsonObject root = parser.parse(json); - - char* sensor = root["sensor"]; - long time = root["time"]; - double latitude = root["data"][0]; - double longitude = root["data"][1]; - -v2.1 ----- - -* Fixed case `#include "jsmn.cpp"` which caused an error in Linux (issue #6) -* Fixed a buffer overrun in JSON Parser (issue #5) - -v2.0 ----- - -* Added JSON encoding (issue #2) -* Renamed the library `ArduinoJsonParser` becomes `ArduinoJson` - -**Breaking change**: you need to add the following line at the top of your program. - - using namespace ArduinoJson::Parser; - -v1.2 ----- - -* Fixed error in JSON parser example (issue #1) - -v1.1 ----- - -* Example: changed `char* json` into `char[] json` so that the bytes are not write protected -* Fixed parsing bug when the JSON contains multi-dimensional arrays - -v1.0 ----- - -Initial release +* Forbid `deserializeJson(JsonArray|JsonObject, ...)` (issue #2135) +* Fix VLA support in `JsonDocument::set()` +* Fix `operator[](variant)` ignoring NUL characters + +v7.2.0 (2024-09-18) +------ + +* Store object members with two slots: one for the key and one for the value +* Store 64-bit numbers (`double` and `long long`) in an additional slot +* Reduce the slot size (see table below) +* Improve message when user forgets third arg of `serializeJson()` et al. +* Set `ARDUINOJSON_USE_DOUBLE` to `0` by default on 8-bit architectures +* Deprecate `containsKey()` in favor of `doc["key"].is()` +* Add support for escape sequence `\'` (issue #2124) + +| Architecture | before | after | +|--------------|----------|----------| +| 8-bit | 8 bytes | 6 bytes | +| 32-bit | 16 bytes | 8 bytes | +| 64-bit | 24 bytes | 16 bytes | + +> ### BREAKING CHANGES +> +> After being on the death row for years, the `containsKey()` method has finally been deprecated. +> You should replace `doc.containsKey("key")` with `doc["key"].is()`, which not only checks that the key exists but also that the value is of the expected type. +> +> ```cpp +> // Before +> if (doc.containsKey("value")) { +> int value = doc["value"]; +> // ... +> } +> +> // After +> if (doc["value"].is()) { +> int value = doc["value"]; +> // ... +> } +> ``` + +v7.1.0 (2024-06-27) +------ + +* Add `ARDUINOJSON_STRING_LENGTH_SIZE` to the namespace name +* Add support for MsgPack binary (PR #2078 by @Sanae6) +* Add support for MsgPack extension +* Make string support even more generic (PR #2084 by @d-a-v) +* Optimize `deserializeMsgPack()` +* Allow using a `JsonVariant` as a key or index (issue #2080) + Note: works only for reading, not for writing +* Support `ElementProxy` and `MemberProxy` in `JsonDocument`'s constructor +* Don't add partial objects when allocation fails (issue #2081) +* Read MsgPack's 64-bit integers even if `ARDUINOJSON_USE_LONG_LONG` is `0` + (they are set to `null` if they don't fit in a `long`) + +v7.0.4 (2024-03-12) +------ + +* Make `JSON_STRING_SIZE(N)` return `N+1` to fix third-party code (issue #2054) + +v7.0.3 (2024-02-05) +------ + +* Improve error messages when using `char` or `char*` (issue #2043) +* Reduce stack consumption (issue #2046) +* Fix compatibility with GCC 4.8 (issue #2045) + +v7.0.2 (2024-01-19) +------ + +* Fix assertion `poolIndex < count_` after `JsonDocument::clear()` (issue #2034) + +v7.0.1 (2024-01-10) +------ + +* Fix "no matching function" with `JsonObjectConst::operator[]` (issue #2019) +* Remove unused files in the PlatformIO package +* Fix `volatile bool` serialized as `1` or `0` instead of `true` or `false` (issue #2029) + +v7.0.0 (2024-01-03) +------ + +* Remove `BasicJsonDocument` +* Remove `StaticJsonDocument` +* Add abstract `Allocator` class +* Merge `DynamicJsonDocument` with `JsonDocument` +* Remove `JSON_ARRAY_SIZE()`, `JSON_OBJECT_SIZE()`, and `JSON_STRING_SIZE()` +* Remove `ARDUINOJSON_ENABLE_STRING_DEDUPLICATION` (string deduplication cannot be disabled anymore) +* Remove `JsonDocument::capacity()` +* Store the strings in the heap +* Reference-count shared strings +* Always store `serialized("string")` by copy (#1915) +* Remove the zero-copy mode of `deserializeJson()` and `deserializeMsgPack()` +* Fix double lookup in `to()` +* Fix double call to `size()` in `serializeMsgPack()` +* Include `ARDUINOJSON_SLOT_OFFSET_SIZE` in the namespace name +* Remove `JsonVariant::shallowCopy()` +* `JsonDocument`'s capacity grows as needed, no need to pass it to the constructor anymore +* `JsonDocument`'s allocator is not monotonic anymore, removed values get recycled +* Show a link to the documentation when user passes an unsupported input type +* Remove `JsonDocument::memoryUsage()` +* Remove `JsonDocument::garbageCollect()` +* Add `deserializeJson(JsonVariant, ...)` and `deserializeMsgPack(JsonVariant, ...)` (#1226) +* Call `shrinkToFit()` in `deserializeJson()` and `deserializeMsgPack()` +* `serializeJson()` and `serializeMsgPack()` replace the content of `std::string` and `String` instead of appending to it +* Replace `add()` with `add()` (`add(T)` is still supported) +* Remove `createNestedArray()` and `createNestedObject()` (use `to()` and `to()` instead) + +> ### BREAKING CHANGES +> +> As every major release, ArduinoJson 7 introduces several breaking changes. +> I added some stubs so that most existing programs should compile, but I highty recommend you upgrade your code. +> +> #### `JsonDocument` +> +> In ArduinoJson 6, you could allocate the memory pool on the stack (with `StaticJsonDocument`) or in the heap (with `DynamicJsonDocument`). +> In ArduinoJson 7, the memory pool is always allocated in the heap, so `StaticJsonDocument` and `DynamicJsonDocument` have been merged into `JsonDocument`. +> +> In ArduinoJson 6, `JsonDocument` had a fixed capacity; in ArduinoJson 7, it has an elastic capacity that grows as needed. +> Therefore, you don't need to specify the capacity anymore, so the macros `JSON_ARRAY_SIZE()`, `JSON_OBJECT_SIZE()`, and `JSON_STRING_SIZE()` have been removed. +> +> ```c++ +> // ArduinoJson 6 +> StaticJsonDocument<256> doc; +> // or +> DynamicJsonDocument doc(256); +> +> // ArduinoJson 7 +> JsonDocument doc; +> ``` +> +> In ArduinoJson 7, `JsonDocument` reuses released memory, so `garbageCollect()` has been removed. +> `shrinkToFit()` is still available and releases the over-allocated memory. +> +> Due to a change in the implementation, it's not possible to store a pointer to a variant from another `JsonDocument`, so `shallowCopy()` has been removed. +> +> In ArduinoJson 6, the meaning of `memoryUsage()` was clear: it returned the number of bytes used in the memory pool. +> In ArduinoJson 7, the meaning of `memoryUsage()` would be ambiguous, so it has been removed. +> +> #### Custom allocators +> +> In ArduinoJson 6, you could specify a custom allocator class as a template parameter of `BasicJsonDocument`. +> In ArduinoJson 7, you must inherit from `ArduinoJson::Allocator` and pass a pointer to an instance of your class to the constructor of `JsonDocument`. +> +> ```c++ +> // ArduinoJson 6 +> class MyAllocator { +> // ... +> }; +> BasicJsonDocument doc(256); +> +> // ArduinoJson 7 +> class MyAllocator : public ArduinoJson::Allocator { +> // ... +> }; +> MyAllocator myAllocator; +> JsonDocument doc(&myAllocator); +> ``` +> +> #### `createNestedArray()` and `createNestedObject()` +> +> In ArduinoJson 6, you could create a nested array or object with `createNestedArray()` and `createNestedObject()`. +> In ArduinoJson 7, you must use `add()` or `to()` instead. +> +> For example, to create `[[],{}]`, you would write: +> +> ```c++ +> // ArduinoJson 6 +> arr.createNestedArray(); +> arr.createNestedObject(); +> +> // ArduinoJson 7 +> arr.add(); +> arr.add(); +> ``` +> +> And to create `{"array":[],"object":{}}`, you would write: +> +> ```c++ +> // ArduinoJson 6 +> obj.createNestedArray("array"); +> obj.createNestedObject("object"); +> +> // ArduinoJson 7 +> obj["array"].to(); +> obj["object"].to(); +> ``` diff --git a/CMakeLists.txt b/CMakeLists.txt index 05994f4ec..cc96a4d7c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,21 +1,25 @@ -# Copyright Benoit Blanchon 2014-2017 +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2025, Benoit BLANCHON # MIT License -# -# Arduino JSON library -# https://github.com/bblanchon/ArduinoJson -# If you like this project, please add a star! -cmake_minimum_required(VERSION 3.0) -project(ArduinoJson) +cmake_minimum_required(VERSION 3.15) -enable_testing() +if(ESP_PLATFORM) + # Build ArduinoJson as an ESP-IDF component + idf_component_register(INCLUDE_DIRS src) + return() +endif() -set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/lib) -set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/lib) -set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/bin) +project(ArduinoJson VERSION 7.4.2) -if(${COVERAGE}) - set(CMAKE_CXX_FLAGS "-g -O0 -fprofile-arcs -ftest-coverage") +if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME) + include(CTest) endif() -add_subdirectory(test) +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/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..d32a04ff1 --- /dev/null +++ b/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/LICENSE.md b/LICENSE.txt similarity index 95% rename from LICENSE.md rename to LICENSE.txt index 627b1767d..782b05d8e 100644 --- a/LICENSE.md +++ b/LICENSE.txt @@ -1,10 +1,10 @@ -The MIT License (MIT) ---------------------- - -Copyright © 2014-2017 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. +The MIT License (MIT) +--------------------- + +Copyright © 2014-2025, 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/README.md b/README.md index 39fb30488..7c5517160 100644 --- a/README.md +++ b/README.md @@ -1,145 +1,153 @@ -ArduinoJson - C++ JSON library for IoT -==================== +

+ ArduinoJson +

-[![Build status](https://ci.appveyor.com/api/projects/status/m7s53wav1l0abssg/branch/master?svg=true)](https://ci.appveyor.com/project/bblanchon/arduinojson/branch/master) [![Build Status](https://travis-ci.org/bblanchon/ArduinoJson.svg?branch=master)](https://travis-ci.org/bblanchon/ArduinoJson) [![Coverage Status](https://img.shields.io/coveralls/bblanchon/ArduinoJson.svg)](https://coveralls.io/r/bblanchon/ArduinoJson?branch=master) [![Star this project](http://githubbadges.com/star.svg?user=bblanchon&repo=ArduinoJson&style=flat&color=fff&background=007ec6)](https://github.com/bblanchon/ArduinoJson) - -*An elegant and efficient JSON library for embedded systems.* - -It's designed to have the most intuitive API, the smallest footprint and is able to work without any allocation on the heap (no malloc). - -It has been written with Arduino in mind, but it isn't linked to Arduino libraries so you can use this library in any other C++ project. -For instance, it supports Aduino's `String` and `Stream`, but also `std::string`, `std::istream` and `std::ostream`. - -Features --------- - -* JSON decoding (comments are supported) -* JSON encoding (with optional indentation) -* Elegant API, very easy to use -* Fixed memory allocation (zero malloc) -* No data duplication (zero copy) -* Portable (written in C++98) -* Self-contained (no external dependency) -* Small footprint -* Header-only library -* MIT License - -Works on --------- - -* All Arduino boards (Uno, Due, Mini, Micro, Yun...) -* ESP8266 -* Teensy -* Intel Edison and Galileo -* PlatformIO -* Energia -* RedBearLab boards (BLE Nano...) -* Computers (Windows, Linux, OSX...) - -See [FAQ: Compatibility issues](https://bblanchon.github.io/ArduinoJson/faq/compilation-fails-device-crashes-nothing-on-serial-console) - -Quick start ------------ +--- -#### Decoding / Parsing +[![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/bblanchon/ArduinoJson/ci.yml?branch=7.x&logo=github)](https://github.com/bblanchon/ArduinoJson/actions?query=workflow%3A%22Continuous+Integration%22+branch%3A7.x) +[![Continuous Integration](https://ci.appveyor.com/api/projects/status/m7s53wav1l0abssg/branch/7.x?svg=true)](https://ci.appveyor.com/project/bblanchon/arduinojson/branch/7.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/7.x?logo=coveralls)](https://coveralls.io/github/bblanchon/ArduinoJson?branch=7.x) +[![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/v7/api/json/deserializejson/) + * [Optionally decodes UTF-16 escape sequences to UTF-8](https://arduinojson.org/v7/api/config/decode_unicode/) + * [Optionally supports comments in the input](https://arduinojson.org/v7/api/config/enable_comments/) + * [Optionally filters the input to keep only desired values](https://arduinojson.org/v7/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/v7/api/json/serializejson/) + * [Can write to a buffer or a stream](https://arduinojson.org/v7/api/json/serializejson/) + * [Optionally indents the document (prettified JSON)](https://arduinojson.org/v7/api/json/serializejsonpretty/) +* [MessagePack serialization](https://arduinojson.org/v7/api/msgpack/serializemsgpack/) +* [MessagePack deserialization](https://arduinojson.org/v7/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/) + * [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/v7/how-to/use-external-ram-on-esp32/) + * Supports [`String`](https://arduinojson.org/v7/api/config/enable_arduino_string/), [`std::string`](https://arduinojson.org/v7/api/config/enable_std_string/), and [`std::string_view`](https://arduinojson.org/v7/api/config/enable_string_view/) + * Supports [`Stream`](https://arduinojson.org/v7/api/config/enable_arduino_stream/) and [`std::istream`/`std::ostream`](https://arduinojson.org/v7/api/config/enable_std_stream/) + * Supports [Flash strings](https://arduinojson.org/v7/api/config/enable_progmem/) + * Supports [custom readers](https://arduinojson.org/v7/api/json/deserializejson/#custom-reader) and [custom writers](https://arduinojson.org/v7/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/v7/how-to/use-arduinojson-with-cmake/) +* Well designed + * [Elegant API](http://arduinojson.org/v7/example/) + * [Thread-safe](https://en.wikipedia.org/wiki/Thread_safety) + * Self-contained (no external dependency) + * `const` friendly + * [`for` friendly](https://arduinojson.org/v7/api/jsonobject/begin_end/) + * [TMP friendly](https://en.wikipedia.org/wiki/Template_metaprogramming) + * Handles [integer overflows](https://arduinojson.org/v7/api/jsonvariant/as/#integer-overflows) +* Well tested + * [Unit test coverage close to 100%](https://coveralls.io/github/bblanchon/ArduinoJson?branch=7.x) + * Continuously tested on + * [Visual Studio 2017, 2019, 2022](https://ci.appveyor.com/project/bblanchon/arduinojson/branch/7.x) + * [GCC 4.8, 5, 6, 7, 8, 9, 10, 11, 12](https://github.com/bblanchon/ArduinoJson/actions?query=workflow%3A%22Continuous+Integration%22) + * [Clang 7 to 19](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/v7/doc/deserialization/) + * [Examples](https://arduinojson.org/v7/example/) + * [How-tos](https://arduinojson.org/v7/example/) + * [FAQ](https://arduinojson.org/v7/faq/) + * [Troubleshooter](https://arduinojson.org/v7/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]}"; - -StaticJsonBuffer<200> jsonBuffer; +const char* json = "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}"; -JsonObject& root = jsonBuffer.parseObject(json); +JsonDocument doc; +deserializeJson(doc, json); -const char* sensor = root["sensor"]; -long time = root["time"]; -double latitude = root["data"][0]; -double longitude = root["data"][1]; +const char* sensor = doc["sensor"]; +long time = doc["time"]; +double latitude = doc["data"][0]; +double longitude = doc["data"][1]; ``` -[See JsonParserExample.ino](examples/JsonParserExample/JsonParserExample.ino) +See the [tutorial on arduinojson.org](https://arduinojson.org/v7/doc/deserialization/) -#### Encoding / Generating +### Serialization -```c++ -StaticJsonBuffer<200> jsonBuffer; +Here is a program that generates a JSON document with ArduinoJson: -JsonObject& root = jsonBuffer.createObject(); -root["sensor"] = "gps"; -root["time"] = 1351824120; +```c++ +JsonDocument doc; -JsonArray& data = root.createNestedArray("data"); -data.add(48.756080, 6); // 6 is the number of decimals to print -data.add(2.302038, 6); // if not specified, 2 digits are printed +doc["sensor"] = "gps"; +doc["time"] = 1351824120; +doc["data"][0] = 48.756080; +doc["data"][1] = 2.302038; -root.printTo(Serial); +serializeJson(doc, Serial); // This prints: // {"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]} ``` -[See JsonGeneratorExample.ino](examples/JsonGeneratorExample/JsonGeneratorExample.ino) - +See the [tutorial on arduinojson.org](https://arduinojson.org/v7/doc/serialization/) -Documentation -------------- +## Sponsors -The documentation is available online in the [ArduinoJson wiki](https://github.com/bblanchon/ArduinoJson/wiki). +ArduinoJson is thankful to its sponsors. Please give them a visit; they deserve it! -The [ArduinoJson Assistant](https://bblanchon.github.io/ArduinoJson/assistant/) helps you get started with the library. +

+ + 1technophile + + + LArkema + +

+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. -Testimonials ------------- - -From Arduino's Forum user `jflaplante`: -> I tried aJson json-arduino before trying your library. I always ran into memory problem after a while. -> I have no such problem so far with your library. It is working perfectly with my web services. - -From StackOverflow user `thegreendroid`: -> It has a really elegant, simple API and it works like a charm on embedded and Windows/Linux platforms. We recently started using this on an embedded project and I can vouch for its quality. - -From GitHub user `zacsketches`: -> Thanks for a great library!!! -> I've been watching you consistently develop this library over the past six months, and I used it today for a publish and subscribe architecture designed to help hobbyists move into more advanced robotics. Your library allowed me to implement remote subscription in order to facilitate multi-processor robots. -> ArduinoJson saved me a week's worth of time!! - -[From Reddit user `erm_what_`](https://www.reddit.com/r/arduino/comments/3jj6ep/announcing_arduinojson_50/cusjk8c): -> This is a great library and I wouldn't be able to do the project I'm doing without it. I completely recommend it. - -[From Reddit user `makerhacks`](https://www.reddit.com/r/arduino/comments/3jj6ep/announcing_arduinojson_50/cusqg7b): -> I am just starting an ESP8266 clock project and now I can output JSON from my server script and interpret it painlessly. - -[From Twitter user `@hemalchevli`](https://twitter.com/hemalchevli/status/715788439397011456): -> ArduinoJson library should be used as a benchmark/reference for making libraries. Truly elegant. - -[From GitHub user `sticilface`](https://github.com/bblanchon/ArduinoJson/issues/381#issuecomment-260203594): -> its a great lib:) and i use it in everything! - -Donators --------- - -Special thanks to the following persons and companies who made generous donations to the library author: - -* Robert Murphy USA -* Surge Communications USA -* Alex Scott United Kingdom -* Firepick Services LLC USA -* A B Doodkorte Netherlands -* Scott Smith USA -* Johann Stieger Austria -* Gustavo Donizeti Gini Brazil -* Charles-Henri Hallard France -* Martijn van den Burg Netherlands -* Nick Koumaris Greece -* Jon Williams USA -* Kestutis Liaugminas Lithuania -* Darlington Adibe Nigeria -* Yoeri Kroon Netherlands -* Andrew Melvin United Kingdom -* Doanh Luong Vietnam -* Christoph Schmidt Germany -* OpenEVSE LLC USA -* Prokhoryatov Alexey Russia - ---- - -Found this library useful? Please star this project or [help me back with a donation!](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=donate%40benoitblanchon%2efr&lc=GB&item_name=Benoit%20Blanchon&item_number=Arduino%20JSON¤cy_code=EUR&bn=PP%2dDonationsBF%3abtn_donate_LG%2egif%3aNonHosted) :smile: +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/SUPPORT.md b/SUPPORT.md new file mode 100644 index 000000000..c47e1b1ba --- /dev/null +++ b/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/appveyor.yml b/appveyor.yml index ed98fb0ec..8709b12bd 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,18 +1,28 @@ -version: 5.8.3.{build} +version: 7.4.2.{build} environment: matrix: - - CMAKE_GENERATOR: Visual Studio 14 2015 - - CMAKE_GENERATOR: Visual Studio 12 2013 - - CMAKE_GENERATOR: Visual Studio 11 2012 - - CMAKE_GENERATOR: Visual Studio 10 2010 -# - CMAKE_GENERATOR: MinGW Makefiles -# Note: Disabled because of unexplicated error -1073741511 -# This used to work fine with GCC 4.8.2 then failed after they upgraded to GCC 4.9.3 + - 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=C:\MinGW\bin;%PATH:C:\Program Files\Git\usr\bin;=% # Workaround for CMake not wanting sh.exe on PATH for MinGW -- cmake -DCMAKE_BUILD_TYPE=%CONFIGURATION% -G "%CMAKE_GENERATOR%" . + - 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% + - cmake --build . --config %CONFIGURATION% test_script: -- ctest -V . + - ctest -C %CONFIGURATION% --output-on-failure . diff --git a/component.mk b/component.mk new file mode 100644 index 000000000..dc25d1c0e --- /dev/null +++ b/component.mk @@ -0,0 +1 @@ +COMPONENT_ADD_INCLUDEDIRS := src diff --git a/examples/IndentedPrintExample/IndentedPrintExample.ino b/examples/IndentedPrintExample/IndentedPrintExample.ino deleted file mode 100644 index f70fa7b29..000000000 --- a/examples/IndentedPrintExample/IndentedPrintExample.ino +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright Benoit Blanchon 2014-2017 -// MIT License -// -// Arduino JSON library -// https://github.com/bblanchon/ArduinoJson -// If you like this project, please add a star! - -#include - -using namespace ArduinoJson::Internals; - -void setup() { - Serial.begin(9600); - while (!Serial) { - // wait serial port initialization - } - - IndentedPrint serial(Serial); - serial.setTabSize(4); - - serial.println("This is at indentation 0"); - serial.indent(); - serial.println("This is at indentation 1"); - serial.println("This is also at indentation 1"); - serial.indent(); - serial.println("This is at indentation 2"); - - serial.unindent(); - serial.unindent(); - serial.println("This is back at indentation 0"); -} - -void loop() { - // not used in this example -} diff --git a/examples/JsonConfigFile/JsonConfigFile.ino b/examples/JsonConfigFile/JsonConfigFile.ino new file mode 100644 index 000000000..32ad3a5b4 --- /dev/null +++ b/examples/JsonConfigFile/JsonConfigFile.ino @@ -0,0 +1,152 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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/v7/example/config/ + +#include +#include +#include + +// Our configuration structure. +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 + JsonDocument 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 + JsonDocument 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/v7/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/examples/JsonFilterExample/JsonFilterExample.ino b/examples/JsonFilterExample/JsonFilterExample.ino new file mode 100644 index 000000000..16e49ddb1 --- /dev/null +++ b/examples/JsonFilterExample/JsonFilterExample.ino @@ -0,0 +1,64 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License +// +// This example shows how to use DeserializationOption::Filter +// +// https://arduinojson.org/v7/example/filter/ + +#include + +void setup() { + // Initialize serial port + Serial.begin(9600); + while (!Serial) + continue; + + // The huge input: an extract from OpenWeatherMap response + auto 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 + JsonDocument filter; + filter["list"][0]["dt"] = true; + filter["list"][0]["main"]["temp"] = true; + + // Deserialize the document + JsonDocument 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/examples/JsonGeneratorExample/JsonGeneratorExample.ino b/examples/JsonGeneratorExample/JsonGeneratorExample.ino index c18d012d6..ffbc9a1cd 100644 --- a/examples/JsonGeneratorExample/JsonGeneratorExample.ino +++ b/examples/JsonGeneratorExample/JsonGeneratorExample.ino @@ -1,60 +1,42 @@ -// Copyright Benoit Blanchon 2014-2017 +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON // MIT License // -// Arduino JSON library -// https://github.com/bblanchon/ArduinoJson -// If you like this project, please add a star! +// This example shows how to generate a JSON document with ArduinoJson. +// +// https://arduinojson.org/v7/example/generator/ #include void setup() { + // Initialize Serial port Serial.begin(9600); - while (!Serial) { - // wait serial port initialization - } - - // Memory pool for JSON object tree. - // - // Inside the brackets, 200 is the size of the pool in bytes. - // If the JSON object is more complex, you need to increase that value. - StaticJsonBuffer<200> jsonBuffer; - - // StaticJsonBuffer allocates memory on the stack, it can be - // replaced by DynamicJsonBuffer which allocates in the heap. - // It's simpler but less efficient. - // - // DynamicJsonBuffer jsonBuffer; + while (!Serial) + continue; - // Create the root 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. - JsonObject& root = jsonBuffer.createObject(); + // Allocate the JSON document + JsonDocument doc; - // Add values in the object - // - // Most of the time, you can rely on the implicit casts. - // In other case, you can do root.set("time", 1351824120); - root["sensor"] = "gps"; - root["time"] = 1351824120; + // Add values in the document + doc["sensor"] = "gps"; + doc["time"] = 1351824120; - // Add a nested array. - // - // It's also possible to create the array separately and add it to the - // JsonObject but it's less efficient. - JsonArray& data = root.createNestedArray("data"); - data.add(double_with_n_digits(48.756080, 6)); - data.add(double_with_n_digits(2.302038, 6)); + // Add an array + JsonArray data = doc["data"].to(); + data.add(48.756080); + data.add(2.302038); - root.printTo(Serial); - // This prints: + // 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(); - root.prettyPrintTo(Serial); - // This prints: + // Generate the prettified JSON and send it to the Serial port + serializeJsonPretty(doc, Serial); + // The above line prints: // { // "sensor": "gps", // "time": 1351824120, @@ -68,3 +50,16 @@ void setup() { 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/examples/JsonHttpClient/JsonHttpClient.ino b/examples/JsonHttpClient/JsonHttpClient.ino index 35954fb6e..c2d38468f 100644 --- a/examples/JsonHttpClient/JsonHttpClient.ino +++ b/examples/JsonHttpClient/JsonHttpClient.ino @@ -1,184 +1,125 @@ -// Sample Arduino Json Web Client -// Downloads and parse http://jsonplaceholder.typicode.com/users/1 -// -// Copyright Benoit Blanchon 2014-2017 +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON // MIT License // -// Arduino JSON library -// https://github.com/bblanchon/ArduinoJson -// If you like this project, please add a star! +// 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/v7/example/http-client/ #include #include #include -EthernetClient client; - -const char* server = "jsonplaceholder.typicode.com"; // server's address -const char* resource = "/users/1"; // http resource -const unsigned long BAUD_RATE = 9600; // serial connection speed -const unsigned long HTTP_TIMEOUT = 10000; // max respone time from server -const size_t MAX_CONTENT_SIZE = 512; // max size of the HTTP response - -// The type of data that we want to extract from the page -struct UserData { - char name[32]; - char company[32]; -}; - -// ARDUINO entry point #1: runs once when you press reset or power the board void setup() { - initSerial(); - initEthernet(); -} + // Initialize Serial port + Serial.begin(9600); + while (!Serial) + continue; -// ARDUINO entry point #2: runs over and over again forever -void loop() { - if (connect(server)) { - if (sendRequest(server, resource) && skipResponseHeaders()) { - UserData userData; - if (readReponseContent(&userData)) { - printUserData(&userData); - } - } - } - disconnect(); - wait(); -} - -// Initialize Serial port -void initSerial() { - Serial.begin(BAUD_RATE); - while (!Serial) { - ; // wait for serial port to initialize - } - Serial.println("Serial ready"); -} - -// Initialize Ethernet library -void initEthernet() { + // Initialize Ethernet library byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; if (!Ethernet.begin(mac)) { - Serial.println("Failed to configure Ethernet"); + Serial.println(F("Failed to configure Ethernet")); return; } - Serial.println("Ethernet ready"); delay(1000); -} - -// Open connection to the HTTP server -bool connect(const char* hostName) { - Serial.print("Connect to "); - Serial.println(hostName); - bool ok = client.connect(hostName, 80); + Serial.println(F("Connecting...")); - Serial.println(ok ? "Connected" : "Connection Failed!"); - return ok; -} + // Connect to HTTP server + EthernetClient client; + client.setTimeout(10000); + if (!client.connect("arduinojson.org", 80)) { + Serial.println(F("Connection failed")); + return; + } -// Send the HTTP GET request to the server -bool sendRequest(const char* host, const char* resource) { - Serial.print("GET "); - Serial.println(resource); + Serial.println(F("Connected!")); - client.print("GET "); - client.print(resource); - client.println(" HTTP/1.0"); - client.print("Host: "); - client.println(host); - client.println("Connection: close"); - client.println(); + // 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; + } - return true; -} + // 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 so that we are at the beginning of the response's body -bool skipResponseHeaders() { - // HTTP headers end with an empty line + // Skip HTTP headers char endOfHeaders[] = "\r\n\r\n"; - - client.setTimeout(HTTP_TIMEOUT); - bool ok = client.find(endOfHeaders); - - if (!ok) { - Serial.println("No response or invalid response!"); + if (!client.find(endOfHeaders)) { + Serial.println(F("Invalid response")); + client.stop(); + return; } - return ok; -} + // Allocate the JSON document + JsonDocument doc; -// Parse the JSON from the input string and extract the interesting values -// Here is the JSON we need to parse -// { -// "id": 1, -// "name": "Leanne Graham", -// "username": "Bret", -// "email": "Sincere@april.biz", -// "address": { -// "street": "Kulas Light", -// "suite": "Apt. 556", -// "city": "Gwenborough", -// "zipcode": "92998-3874", -// "geo": { -// "lat": "-37.3159", -// "lng": "81.1496" -// } -// }, -// "phone": "1-770-736-8031 x56442", -// "website": "hildegard.org", -// "company": { -// "name": "Romaguera-Crona", -// "catchPhrase": "Multi-layered client-server neural-net", -// "bs": "harness real-time e-markets" -// } -// } -bool readReponseContent(struct UserData* userData) { - // Compute optimal size of the JSON buffer according to what we need to parse. - // This is only required if you use StaticJsonBuffer. - const size_t BUFFER_SIZE = - JSON_OBJECT_SIZE(8) // the root object has 8 elements - + JSON_OBJECT_SIZE(5) // the "address" object has 5 elements - + JSON_OBJECT_SIZE(2) // the "geo" object has 2 elements - + JSON_OBJECT_SIZE(3) // the "company" object has 3 elements - + MAX_CONTENT_SIZE; // additional space for strings - - // Allocate a temporary memory pool - DynamicJsonBuffer jsonBuffer(BUFFER_SIZE); - - JsonObject& root = jsonBuffer.parseObject(client); - - if (!root.success()) { - Serial.println("JSON parsing failed!"); - return false; + // Parse JSON object + DeserializationError error = deserializeJson(doc, client); + if (error) { + Serial.print(F("deserializeJson() failed: ")); + Serial.println(error.f_str()); + client.stop(); + return; } - // Here were copy the strings we're interested in - strcpy(userData->name, root["name"]); - strcpy(userData->company, root["company"]["name"]); - // It's not mandatory to make a copy, you could just use the pointers - // Since, they are pointing inside the "content" buffer, so you need to make - // sure it's still in memory when you read the string + // 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); - return true; + // Disconnect + client.stop(); } -// Print the data extracted from the JSON -void printUserData(const struct UserData* userData) { - Serial.print("Name = "); - Serial.println(userData->name); - Serial.print("Company = "); - Serial.println(userData->company); +void loop() { + // not used in this example } -// Close the connection with the HTTP server -void disconnect() { - Serial.println("Disconnect"); - client.stop(); -} +// Performance issue? +// ------------------ +// +// EthernetClient is an unbuffered stream, which is not optimal for ArduinoJson. +// See: https://arduinojson.org/v7/how-to/improve-speed/ -// Pause for a 1 minute -void wait() { - Serial.println("Wait 60 seconds"); - delay(60000); -} +// 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/examples/JsonParserExample/JsonParserExample.ino b/examples/JsonParserExample/JsonParserExample.ino index 293894f21..7b3261604 100644 --- a/examples/JsonParserExample/JsonParserExample.ino +++ b/examples/JsonParserExample/JsonParserExample.ino @@ -1,61 +1,46 @@ -// Copyright Benoit Blanchon 2014-2017 +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON // MIT License // -// Arduino JSON library -// https://github.com/bblanchon/ArduinoJson -// If you like this project, please add a star! +// This example shows how to deserialize a JSON document with ArduinoJson. +// +// https://arduinojson.org/v7/example/parser/ #include void setup() { + // Initialize serial port Serial.begin(9600); - while (!Serial) { - // wait serial port initialization - } + while (!Serial) + continue; - // Memory pool for JSON object tree. - // - // Inside the brackets, 200 is the size of the pool in bytes, - // If the JSON object is more complex, you need to increase that value. - StaticJsonBuffer<200> jsonBuffer; - - // StaticJsonBuffer allocates memory on the stack, it can be - // replaced by DynamicJsonBuffer which allocates in the heap. - // It's simpler but less efficient. - // - // DynamicJsonBuffer jsonBuffer; + // Allocate the JSON document + JsonDocument doc; // JSON 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. - char json[] = + const char* json = "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}"; - // Root 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. - JsonObject& root = jsonBuffer.parseObject(json); + // Deserialize the JSON document + DeserializationError error = deserializeJson(doc, json); - // Test if parsing succeeds. - if (!root.success()) { - Serial.println("parseObject() failed"); + // Test if parsing succeeds + if (error) { + Serial.print(F("deserializeJson() failed: ")); + Serial.println(error.f_str()); return; } - // Fetch values. + // Fetch the values // // Most of the time, you can rely on the implicit casts. - // In other case, you can do root["time"].as(); - const char* sensor = root["sensor"]; - long time = root["time"]; - double latitude = root["data"][0]; - double longitude = root["data"][1]; + // 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. + // Print the values Serial.println(sensor); Serial.println(time); Serial.println(latitude, 6); @@ -65,3 +50,16 @@ void setup() { 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/examples/JsonServer/JsonServer.ino b/examples/JsonServer/JsonServer.ino index d3fec3ece..51fdf3c26 100644 --- a/examples/JsonServer/JsonServer.ino +++ b/examples/JsonServer/JsonServer.ino @@ -1,74 +1,118 @@ -// Sample Arduino Json Web Server -// Created by Benoit Blanchon. -// Heavily inspired by "Web Server" from David A. Mellis and Tom Igoe +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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/v7/example/http-server/ -#include -#include #include +#include +#include byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; -IPAddress ip(192, 168, 0, 177); EthernetServer server(80); -bool readRequest(EthernetClient& client) { - bool currentLineIsBlank = true; - while (client.connected()) { - if (client.available()) { - char c = client.read(); - if (c == '\n' && currentLineIsBlank) { - return true; - } else if (c == '\n') { - currentLineIsBlank = true; - } else if (c != '\r') { - currentLineIsBlank = false; - } - } +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; } - return false; + + // Start to listen + server.begin(); + + Serial.println(F("Server is ready.")); + Serial.print(F("Please connect to http://")); + Serial.println(Ethernet.localIP()); } -JsonObject& prepareResponse(JsonBuffer& jsonBuffer) { - JsonObject& root = jsonBuffer.createObject(); +void loop() { + // Wait for an incomming connection + EthernetClient client = server.available(); + + // Do we have a client? + if (!client) + return; + + Serial.println(F("New client")); - JsonArray& analogValues = root.createNestedArray("analog"); + // Read the request (we ignore the content in this example) + while (client.available()) + client.read(); + + // Allocate a temporary JsonDocument + JsonDocument doc; + + // Create the "analog" array + JsonArray analogValues = doc["analog"].to(); 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); } - JsonArray& digitalValues = root.createNestedArray("digital"); + // Create the "digital" array + JsonArray digitalValues = doc["digital"].to(); 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); } - return root; -} + Serial.print(F("Sending: ")); + serializeJson(doc, Serial); + Serial.println(); -void writeResponse(EthernetClient& client, JsonObject& json) { - client.println("HTTP/1.1 200 OK"); - client.println("Content-Type: application/json"); - client.println("Connection: close"); + // 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(); - json.prettyPrintTo(client); -} + // Write JSON document + serializeJsonPretty(doc, client); -void setup() { - Ethernet.begin(mac, ip); - server.begin(); + // Disconnect + client.stop(); } -void loop() { - EthernetClient client = server.available(); - if (client) { - bool success = readRequest(client); - if (success) { - StaticJsonBuffer<500> jsonBuffer; - JsonObject& json = prepareResponse(jsonBuffer); - writeResponse(client, json); - } - delay(1); - client.stop(); - } -} +// Performance issue? +// ------------------ +// +// EthernetClient is an unbuffered stream, which is not optimal for ArduinoJson. +// See: https://arduinojson.org/v7/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/examples/JsonUdpBeacon/JsonUdpBeacon.ino b/examples/JsonUdpBeacon/JsonUdpBeacon.ino index 2975fad4c..d6ecb5511 100644 --- a/examples/JsonUdpBeacon/JsonUdpBeacon.ino +++ b/examples/JsonUdpBeacon/JsonUdpBeacon.ino @@ -1,55 +1,106 @@ -// Send a JSON object on UDP at regular interval +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License // -// You can easily test this program with netcat: -// $ nc -ulp 8888 +// 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] +// } // -// by Benoit Blanchon, MIT License 2015-2017 +// 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/v7/example/udp-beacon/ #include #include #include byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; -IPAddress localIp(192, 168, 0, 177); -IPAddress remoteIp(192, 168, 0, 109); -unsigned int remotePort = 8888; -unsigned localPort = 8888; +IPAddress remoteIp(192, 168, 0, 108); // <- EDIT!!!! +unsigned short remotePort = 8888; +unsigned short localPort = 8888; EthernetUDP udp; -JsonObject& buildJson(JsonBuffer& jsonBuffer) { - JsonObject& root = jsonBuffer.createObject(); +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); +} - JsonArray& analogValues = root.createNestedArray("analog"); +void loop() { + // Allocate a temporary JsonDocument + JsonDocument doc; + + // Create the "analog" array + JsonArray analogValues = doc["analog"].to(); 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); } - JsonArray& digitalValues = root.createNestedArray("digital"); + // Create the "digital" array + JsonArray digitalValues = doc["digital"].to(); 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); } - return root; -} + // Log + Serial.print(F("Sending to ")); + Serial.print(remoteIp); + Serial.print(F(" on port ")); + Serial.println(remotePort); + serializeJson(doc, Serial); -void sendJson(JsonObject& json) { + // Send UDP packet udp.beginPacket(remoteIp, remotePort); - json.printTo(udp); + serializeJson(doc, udp); udp.println(); udp.endPacket(); -} -void setup() { - Ethernet.begin(mac, localIp); - udp.begin(localPort); + // Wait + delay(10000); } -void loop() { - delay(1000); +// Performance issue? +// ------------------ +// +// EthernetUDP is an unbuffered stream, which is not optimal for ArduinoJson. +// See: https://arduinojson.org/v7/how-to/improve-speed/ - StaticJsonBuffer<300> jsonBuffer; - JsonObject& json = buildJson(jsonBuffer); - sendJson(json); -} +// 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/examples/MsgPackParser/MsgPackParser.ino b/examples/MsgPackParser/MsgPackParser.ino new file mode 100644 index 000000000..364908109 --- /dev/null +++ b/examples/MsgPackParser/MsgPackParser.ino @@ -0,0 +1,61 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License +// +// This example shows how to deserialize a MessagePack document with +// ArduinoJson. +// +// https://arduinojson.org/v7/example/msgpack-parser/ + +#include + +void setup() { + // Initialize serial port + Serial.begin(9600); + while (!Serial) + continue; + + // Allocate the JSON document + JsonDocument doc; + + // The MessagePack input string + 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] + // } + + // Parse the input + DeserializationError error = deserializeMsgPack(doc, input); + + // Test if parsing succeeded + if (error) { + Serial.print("deserializeMsgPack() failed: "); + Serial.println(error.f_str()); + return; + } + + // Fetch the 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 the 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/examples/ProgmemExample/ProgmemExample.ino b/examples/ProgmemExample/ProgmemExample.ino index dc8dd4bc0..729cb8bf5 100644 --- a/examples/ProgmemExample/ProgmemExample.ino +++ b/examples/ProgmemExample/ProgmemExample.ino @@ -1,56 +1,63 @@ -// Copyright Benoit Blanchon 2014-2017 +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON // MIT License // -// Arduino JSON library -// https://github.com/bblanchon/ArduinoJson -// If you like this project, please add a star! +// 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/v7/example/progmem/ #include -// About -// ----- -// This example shows the different ways you can use PROGMEM with ArduinoJson. -// Please don't see this as an invitation to use PROGMEM. -// On the contrary, you should always use char[] when possible, it's much more -// efficient in term of code size, speed and memory usage. - void setup() { -#ifdef PROGMEM - DynamicJsonBuffer jsonBuffer; + JsonDocument doc; // You can use a Flash String as your JSON input. - // WARNING: the content of the Flash String will be duplicated in the - // JsonBuffer. - JsonObject& root = - jsonBuffer.parseObject(F("{\"sensor\":\"gps\",\"time\":1351824120," - "\"data\":[48.756080,2.302038]}")); + // 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 to get an element of a JsonObject + // You can use a Flash String as a key to get a member from JsonDocument // No duplication is done. - long time = root[F("time")]; + long time = doc[F("time")]; - // You can use a Flash String to set an element of a JsonObject + // 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 - // JsonBuffer. - root[F("time")] = time; + // JsonDocument. + doc[F("time")] = time; - // You can set a Flash String to a JsonObject or JsonArray: + // You can set a Flash String as the content of a JsonVariant // WARNING: the content of the Flash String will be duplicated in the - // JsonBuffer. - root["sensor"] = F("gps"); + // 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 (root["sensor"] == F("gps")) { + if (doc["sensor"] == F("gps")) { // ... } - -#else - -#warning PROGMEM is not supported on this platform - -#endif } 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/examples/StringExample/StringExample.ino b/examples/StringExample/StringExample.ino index f76f9dbe2..845df9df7 100644 --- a/examples/StringExample/StringExample.ino +++ b/examples/StringExample/StringExample.ino @@ -1,63 +1,76 @@ -// Copyright Benoit Blanchon 2014-2017 +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON // MIT License // -// Arduino JSON library -// https://github.com/bblanchon/ArduinoJson -// If you like this project, please add a star! +// 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/v7/example/string/ #include -// About -// ----- -// This example shows the different ways you can use String with ArduinoJson. -// Please don't see this as an invitation to use String. -// On the contrary, you should always use char[] when possible, it's much more -// efficient in term of code size, speed and memory usage. - void setup() { - DynamicJsonBuffer jsonBuffer; + JsonDocument doc; // You can use a String as your JSON input. - // WARNING: the content of the String will be duplicated in the JsonBuffer. + // WARNING: the string in the input will be duplicated in the JsonDocument. String input = "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}"; - JsonObject& root = jsonBuffer.parseObject(input); + deserializeJson(doc, input); - // You can use a String to get an element of a JsonObject + // You can use a String as a key to get a member from JsonDocument // No duplication is done. - long time = root[String("time")]; + long time = doc[String("time")]; - // You can use a String to set an element of a JsonObject - // WARNING: the content of the String will be duplicated in the JsonBuffer. - root[String("time")] = 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 a String from a JsonObject or JsonArray: - // No duplication is done, at least not in the JsonBuffer. - String sensor = root["sensor"]; + // 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 = root["sensor"]; // <- error "ambiguous overload for 'operator='" + // sensor = doc["sensor"]; // <- error "ambiguous overload for 'operator='" // As a workaround, you need to replace by: - sensor = root["sensor"].as(); + sensor = doc["sensor"].as(); - // You can set a String to a JsonObject or JsonArray: - // WARNING: the content of the String will be duplicated in the JsonBuffer. - root["sensor"] = sensor; + // 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 JsonBuffer. - root[String("sen") + "sor"] = String("gp") + "s"; + // 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 (root["sensor"] == sensor) { + if (doc["sensor"] == sensor) { // ... } // Lastly, you can print the resulting JSON to a String String output; - root.printTo(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/extras/ArduinoJsonConfig.cmake.in b/extras/ArduinoJsonConfig.cmake.in new file mode 100644 index 000000000..9c15f36a2 --- /dev/null +++ b/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/extras/CompileOptions.cmake b/extras/CompileOptions.cmake new file mode 100644 index 000000000..5d9f8046a --- /dev/null +++ b/extras/CompileOptions.cmake @@ -0,0 +1,112 @@ +if(NOT DEFINED COVERAGE) + set(COVERAGE OFF) +endif() + +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.9) AND(NOT ${COVERAGE})) + add_compile_options(-g -Og) + else() # GCC 4.8 + add_compile_options( + -g + -O0 # GCC 4.8 doesn't support -Og + -Wno-shadow # allow the same name for a function parameter and a member functions + -Wp,-w # Disable preprocessing warnings (see below) + ) + # GCC 4.8 doesn't support __has_include, so we need to help him + add_definitions( + -DARDUINOJSON_ENABLE_STD_STRING=1 + -DARDUINOJSON_ENABLE_STD_STREAM=1 + ) + 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") + add_compile_options(-stdlib=libc++) + link_libraries(c++ m) + + 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/extras/ci/espidf/CMakeLists.txt b/extras/ci/espidf/CMakeLists.txt new file mode 100644 index 000000000..613570132 --- /dev/null +++ b/extras/ci/espidf/CMakeLists.txt @@ -0,0 +1,8 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2025, Benoit BLANCHON +# MIT License + +cmake_minimum_required(VERSION 3.5) + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +project(example) diff --git a/extras/ci/espidf/main/CMakeLists.txt b/extras/ci/espidf/main/CMakeLists.txt new file mode 100644 index 000000000..bf22507a3 --- /dev/null +++ b/extras/ci/espidf/main/CMakeLists.txt @@ -0,0 +1,8 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2025, Benoit BLANCHON +# MIT License + +idf_component_register( + SRCS "main.cpp" + INCLUDE_DIRS "" +) diff --git a/extras/ci/espidf/main/component.mk b/extras/ci/espidf/main/component.mk new file mode 100644 index 000000000..a98f634ea --- /dev/null +++ b/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/extras/ci/espidf/main/main.cpp b/extras/ci/espidf/main/main.cpp new file mode 100644 index 000000000..436eb4032 --- /dev/null +++ b/extras/ci/espidf/main/main.cpp @@ -0,0 +1,16 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include + +extern "C" void app_main() { + char buffer[256]; + JsonDocument doc; + + doc["hello"] = "world"; + serializeJson(doc, buffer); + deserializeJson(doc, buffer); + serializeMsgPack(doc, buffer); + deserializeMsgPack(doc, buffer); +} diff --git a/extras/ci/particle.sh b/extras/ci/particle.sh new file mode 100755 index 000000000..556635305 --- /dev/null +++ b/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/extras/conf_test/avr.cpp b/extras/conf_test/avr.cpp new file mode 100644 index 000000000..769317a81 --- /dev/null +++ b/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_ID_SIZE == 1, "ARDUINOJSON_SLOT_ID_SIZE"); + +static_assert(ARDUINOJSON_POOL_CAPACITY == 16, "ARDUINOJSON_POOL_CAPACITY"); + +static_assert(ARDUINOJSON_LITTLE_ENDIAN == 1, "ARDUINOJSON_LITTLE_ENDIAN"); + +static_assert(ARDUINOJSON_USE_DOUBLE == 0, "ARDUINOJSON_USE_DOUBLE"); + +static_assert(ArduinoJson::detail::ResourceManager::slotSize == 6, "slot size"); + +void setup() {} +void loop() {} diff --git a/extras/conf_test/esp8266.cpp b/extras/conf_test/esp8266.cpp new file mode 100644 index 000000000..b37bfd67a --- /dev/null +++ b/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_ID_SIZE == 2, "ARDUINOJSON_SLOT_ID_SIZE"); + +static_assert(ARDUINOJSON_POOL_CAPACITY == 128, "ARDUINOJSON_POOL_CAPACITY"); + +static_assert(ARDUINOJSON_LITTLE_ENDIAN == 1, "ARDUINOJSON_LITTLE_ENDIAN"); + +static_assert(ARDUINOJSON_USE_DOUBLE == 1, "ARDUINOJSON_USE_DOUBLE"); + +static_assert(ArduinoJson::detail::ResourceManager::slotSize == 8, "slot size"); + +void setup() {} +void loop() {} diff --git a/extras/conf_test/x64.cpp b/extras/conf_test/x64.cpp new file mode 100644 index 000000000..df6b044bf --- /dev/null +++ b/extras/conf_test/x64.cpp @@ -0,0 +1,16 @@ +#include + +static_assert(ARDUINOJSON_USE_LONG_LONG == 1, "ARDUINOJSON_USE_LONG_LONG"); + +static_assert(ARDUINOJSON_SLOT_ID_SIZE == 4, "ARDUINOJSON_SLOT_ID_SIZE"); + +static_assert(ARDUINOJSON_POOL_CAPACITY == 256, "ARDUINOJSON_POOL_CAPACITY"); + +static_assert(ARDUINOJSON_LITTLE_ENDIAN == 1, "ARDUINOJSON_LITTLE_ENDIAN"); + +static_assert(ARDUINOJSON_USE_DOUBLE == 1, "ARDUINOJSON_USE_DOUBLE"); + +static_assert(ArduinoJson::detail::ResourceManager::slotSize == 16, + "slot size"); + +int main() {} diff --git a/extras/conf_test/x86.cpp b/extras/conf_test/x86.cpp new file mode 100644 index 000000000..9dff8f17b --- /dev/null +++ b/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_ID_SIZE == 2, "ARDUINOJSON_SLOT_ID_SIZE"); + +static_assert(ARDUINOJSON_POOL_CAPACITY == 128, "ARDUINOJSON_POOL_CAPACITY"); + +static_assert(ARDUINOJSON_LITTLE_ENDIAN == 1, "ARDUINOJSON_LITTLE_ENDIAN"); + +static_assert(ARDUINOJSON_USE_DOUBLE == 1, "ARDUINOJSON_USE_DOUBLE"); + +static_assert(ArduinoJson::detail::ResourceManager::slotSize == 8, "slot size"); + +int main() {} diff --git a/extras/fuzzing/CMakeLists.txt b/extras/fuzzing/CMakeLists.txt new file mode 100644 index 000000000..42c9260ec --- /dev/null +++ b/extras/fuzzing/CMakeLists.txt @@ -0,0 +1,67 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2025, 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() + +# Needs Clang 6+ to compile +if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang" AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 6) + if(DEFINED ENV{GITHUB_ACTIONS} AND CMAKE_CXX_COMPILER_VERSION MATCHES "^11\\.") + # Clang 11 fails on GitHub Actions with the following error: + # > ERROR: UndefinedBehaviorSanitizer failed to allocate 0x0 (0) bytes of SetAlternateSignalStack (error code: 22) + # > Sanitizer CHECK failed: /build/llvm-toolchain-11-mnvtwk/llvm-toolchain-11-11.1.0/compiler-rt/lib/sanitizer_common/sanitizer_common.cpp:54 ((0 && "unable to mmap")) != (0) (0, 0) + message(WARNING "Fuzzing is disabled on GitHub Actions to workaround a bug in Clang 11") + return() + endif() + + add_fuzzer(json) + add_fuzzer(msgpack) +endif() diff --git a/extras/fuzzing/Makefile b/extras/fuzzing/Makefile new file mode 100644 index 000000000..81fc41257 --- /dev/null +++ b/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/fuzzing/my_corpus/.gitignore b/extras/fuzzing/json_corpus/.gitignore similarity index 100% rename from fuzzing/my_corpus/.gitignore rename to extras/fuzzing/json_corpus/.gitignore diff --git a/extras/fuzzing/json_fuzzer.cpp b/extras/fuzzing/json_fuzzer.cpp new file mode 100644 index 000000000..8d78aa345 --- /dev/null +++ b/extras/fuzzing/json_fuzzer.cpp @@ -0,0 +1,11 @@ +#include + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + JsonDocument doc; + DeserializationError error = deserializeJson(doc, data, size); + if (!error) { + std::string json; + serializeJson(doc, json); + } + return 0; +} diff --git a/fuzzing/seed_corpus/Comments.json b/extras/fuzzing/json_seed_corpus/Comments.json similarity index 100% rename from fuzzing/seed_corpus/Comments.json rename to extras/fuzzing/json_seed_corpus/Comments.json diff --git a/fuzzing/seed_corpus/EmptyArray.json b/extras/fuzzing/json_seed_corpus/EmptyArray.json similarity index 100% rename from fuzzing/seed_corpus/EmptyArray.json rename to extras/fuzzing/json_seed_corpus/EmptyArray.json diff --git a/fuzzing/seed_corpus/EmptyObject.json b/extras/fuzzing/json_seed_corpus/EmptyObject.json similarity index 100% rename from fuzzing/seed_corpus/EmptyObject.json rename to extras/fuzzing/json_seed_corpus/EmptyObject.json diff --git a/fuzzing/seed_corpus/ExcessiveNesting.json b/extras/fuzzing/json_seed_corpus/ExcessiveNesting.json similarity index 100% rename from fuzzing/seed_corpus/ExcessiveNesting.json rename to extras/fuzzing/json_seed_corpus/ExcessiveNesting.json diff --git a/extras/fuzzing/json_seed_corpus/IntegerOverflow.json b/extras/fuzzing/json_seed_corpus/IntegerOverflow.json new file mode 100644 index 000000000..3a33cb89d --- /dev/null +++ b/extras/fuzzing/json_seed_corpus/IntegerOverflow.json @@ -0,0 +1 @@ +9720730739393920739 diff --git a/fuzzing/seed_corpus/Numbers.json b/extras/fuzzing/json_seed_corpus/Numbers.json similarity index 68% rename from fuzzing/seed_corpus/Numbers.json rename to extras/fuzzing/json_seed_corpus/Numbers.json index 7ce8ef623..f6b941942 100644 --- a/fuzzing/seed_corpus/Numbers.json +++ b/extras/fuzzing/json_seed_corpus/Numbers.json @@ -14,5 +14,11 @@ 12.34e+56, 12.34E56, 12.34E-56, - 12.34E+56 + 12.34E+56, + NaN, + -NaN, + +NaN, + Infinity, + +Infinity, + -Infinity ] \ No newline at end of file diff --git a/fuzzing/seed_corpus/OpenWeatherMap.json b/extras/fuzzing/json_seed_corpus/OpenWeatherMap.json similarity index 100% rename from fuzzing/seed_corpus/OpenWeatherMap.json rename to extras/fuzzing/json_seed_corpus/OpenWeatherMap.json diff --git a/fuzzing/seed_corpus/Strings.json b/extras/fuzzing/json_seed_corpus/Strings.json similarity index 100% rename from fuzzing/seed_corpus/Strings.json rename to extras/fuzzing/json_seed_corpus/Strings.json diff --git a/fuzzing/seed_corpus/WeatherUnderground.json b/extras/fuzzing/json_seed_corpus/WeatherUnderground.json similarity index 100% rename from fuzzing/seed_corpus/WeatherUnderground.json rename to extras/fuzzing/json_seed_corpus/WeatherUnderground.json diff --git a/extras/fuzzing/msgpack_corpus/.gitignore b/extras/fuzzing/msgpack_corpus/.gitignore new file mode 100644 index 000000000..d6b7ef32c --- /dev/null +++ b/extras/fuzzing/msgpack_corpus/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/extras/fuzzing/msgpack_fuzzer.cpp b/extras/fuzzing/msgpack_fuzzer.cpp new file mode 100644 index 000000000..3011501b7 --- /dev/null +++ b/extras/fuzzing/msgpack_fuzzer.cpp @@ -0,0 +1,11 @@ +#include + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + JsonDocument doc; + DeserializationError error = deserializeMsgPack(doc, data, size); + if (!error) { + std::string json; + serializeMsgPack(doc, json); + } + return 0; +} diff --git a/extras/fuzzing/msgpack_seed_corpus/array16 b/extras/fuzzing/msgpack_seed_corpus/array16 new file mode 100644 index 000000000..714ba99e7 Binary files /dev/null and b/extras/fuzzing/msgpack_seed_corpus/array16 differ diff --git a/extras/fuzzing/msgpack_seed_corpus/array32 b/extras/fuzzing/msgpack_seed_corpus/array32 new file mode 100644 index 000000000..6e3ed7b1b Binary files /dev/null and b/extras/fuzzing/msgpack_seed_corpus/array32 differ diff --git a/extras/fuzzing/msgpack_seed_corpus/false b/extras/fuzzing/msgpack_seed_corpus/false new file mode 100644 index 000000000..527718838 --- /dev/null +++ b/extras/fuzzing/msgpack_seed_corpus/false @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/extras/fuzzing/msgpack_seed_corpus/fixarray b/extras/fuzzing/msgpack_seed_corpus/fixarray new file mode 100644 index 000000000..95d54b199 --- /dev/null +++ b/extras/fuzzing/msgpack_seed_corpus/fixarray @@ -0,0 +1 @@ +helloworld \ No newline at end of file diff --git a/extras/fuzzing/msgpack_seed_corpus/fixint_negative b/extras/fuzzing/msgpack_seed_corpus/fixint_negative new file mode 100644 index 000000000..eda5949cb --- /dev/null +++ b/extras/fuzzing/msgpack_seed_corpus/fixint_negative @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/extras/fuzzing/msgpack_seed_corpus/fixint_positive b/extras/fuzzing/msgpack_seed_corpus/fixint_positive new file mode 100644 index 000000000..16e0e90df --- /dev/null +++ b/extras/fuzzing/msgpack_seed_corpus/fixint_positive @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/extras/fuzzing/msgpack_seed_corpus/fixmap b/extras/fuzzing/msgpack_seed_corpus/fixmap new file mode 100644 index 000000000..df26118e4 --- /dev/null +++ b/extras/fuzzing/msgpack_seed_corpus/fixmap @@ -0,0 +1 @@ +onetwo \ No newline at end of file diff --git a/extras/fuzzing/msgpack_seed_corpus/fixstr b/extras/fuzzing/msgpack_seed_corpus/fixstr new file mode 100644 index 000000000..2ff7b3f3e --- /dev/null +++ b/extras/fuzzing/msgpack_seed_corpus/fixstr @@ -0,0 +1 @@ +hello world \ No newline at end of file diff --git a/extras/fuzzing/msgpack_seed_corpus/float32 b/extras/fuzzing/msgpack_seed_corpus/float32 new file mode 100644 index 000000000..a574220c5 --- /dev/null +++ b/extras/fuzzing/msgpack_seed_corpus/float32 @@ -0,0 +1 @@ +@H \ No newline at end of file diff --git a/extras/fuzzing/msgpack_seed_corpus/float64 b/extras/fuzzing/msgpack_seed_corpus/float64 new file mode 100644 index 000000000..36088bcdc --- /dev/null +++ b/extras/fuzzing/msgpack_seed_corpus/float64 @@ -0,0 +1 @@ +@ !o \ No newline at end of file diff --git a/extras/fuzzing/msgpack_seed_corpus/int16 b/extras/fuzzing/msgpack_seed_corpus/int16 new file mode 100644 index 000000000..9ffc705e4 --- /dev/null +++ b/extras/fuzzing/msgpack_seed_corpus/int16 @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/extras/fuzzing/msgpack_seed_corpus/int32 b/extras/fuzzing/msgpack_seed_corpus/int32 new file mode 100644 index 000000000..d735e2175 --- /dev/null +++ b/extras/fuzzing/msgpack_seed_corpus/int32 @@ -0,0 +1 @@ +Ҷi. \ No newline at end of file diff --git a/extras/fuzzing/msgpack_seed_corpus/int64 b/extras/fuzzing/msgpack_seed_corpus/int64 new file mode 100644 index 000000000..9d2cd3b99 --- /dev/null +++ b/extras/fuzzing/msgpack_seed_corpus/int64 @@ -0,0 +1 @@ +4Vx \ No newline at end of file diff --git a/extras/fuzzing/msgpack_seed_corpus/int8 b/extras/fuzzing/msgpack_seed_corpus/int8 new file mode 100644 index 000000000..ae2ca9cc1 --- /dev/null +++ b/extras/fuzzing/msgpack_seed_corpus/int8 @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/extras/fuzzing/msgpack_seed_corpus/map16 b/extras/fuzzing/msgpack_seed_corpus/map16 new file mode 100644 index 000000000..836a71874 Binary files /dev/null and b/extras/fuzzing/msgpack_seed_corpus/map16 differ diff --git a/extras/fuzzing/msgpack_seed_corpus/map32 b/extras/fuzzing/msgpack_seed_corpus/map32 new file mode 100644 index 000000000..97ab162eb Binary files /dev/null and b/extras/fuzzing/msgpack_seed_corpus/map32 differ diff --git a/extras/fuzzing/msgpack_seed_corpus/nil b/extras/fuzzing/msgpack_seed_corpus/nil new file mode 100644 index 000000000..e7754cae5 --- /dev/null +++ b/extras/fuzzing/msgpack_seed_corpus/nil @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/extras/fuzzing/msgpack_seed_corpus/str16 b/extras/fuzzing/msgpack_seed_corpus/str16 new file mode 100644 index 000000000..91c1396de Binary files /dev/null and b/extras/fuzzing/msgpack_seed_corpus/str16 differ diff --git a/extras/fuzzing/msgpack_seed_corpus/str32 b/extras/fuzzing/msgpack_seed_corpus/str32 new file mode 100644 index 000000000..50cac52ad Binary files /dev/null and b/extras/fuzzing/msgpack_seed_corpus/str32 differ diff --git a/extras/fuzzing/msgpack_seed_corpus/str8 b/extras/fuzzing/msgpack_seed_corpus/str8 new file mode 100644 index 000000000..ff5a2c0ee --- /dev/null +++ b/extras/fuzzing/msgpack_seed_corpus/str8 @@ -0,0 +1 @@ +hello \ No newline at end of file diff --git a/extras/fuzzing/msgpack_seed_corpus/true b/extras/fuzzing/msgpack_seed_corpus/true new file mode 100644 index 000000000..6b10f9584 --- /dev/null +++ b/extras/fuzzing/msgpack_seed_corpus/true @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/extras/fuzzing/msgpack_seed_corpus/uint16 b/extras/fuzzing/msgpack_seed_corpus/uint16 new file mode 100644 index 000000000..7f4c2e826 --- /dev/null +++ b/extras/fuzzing/msgpack_seed_corpus/uint16 @@ -0,0 +1 @@ +09 \ No newline at end of file diff --git a/extras/fuzzing/msgpack_seed_corpus/uint32 b/extras/fuzzing/msgpack_seed_corpus/uint32 new file mode 100644 index 000000000..864826fbc --- /dev/null +++ b/extras/fuzzing/msgpack_seed_corpus/uint32 @@ -0,0 +1 @@ +4Vx \ No newline at end of file diff --git a/extras/fuzzing/msgpack_seed_corpus/uint64 b/extras/fuzzing/msgpack_seed_corpus/uint64 new file mode 100644 index 000000000..20ede759d --- /dev/null +++ b/extras/fuzzing/msgpack_seed_corpus/uint64 @@ -0,0 +1 @@ +4Vx \ No newline at end of file diff --git a/extras/fuzzing/msgpack_seed_corpus/uint8 b/extras/fuzzing/msgpack_seed_corpus/uint8 new file mode 100644 index 000000000..6a9612072 --- /dev/null +++ b/extras/fuzzing/msgpack_seed_corpus/uint8 @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/extras/fuzzing/reproducer.cpp b/extras/fuzzing/reproducer.cpp new file mode 100644 index 000000000..beeb2dfea --- /dev/null +++ b/extras/fuzzing/reproducer.cpp @@ -0,0 +1,50 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +// This file is NOT use by Google's OSS fuzz +// I only use it to reproduce the bugs found + +#include // 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/extras/particle/project.properties b/extras/particle/project.properties new file mode 100644 index 000000000..d39555ad5 --- /dev/null +++ b/extras/particle/project.properties @@ -0,0 +1 @@ +name=ArduinoJsonCI diff --git a/extras/particle/src/smocktest.ino b/extras/particle/src/smocktest.ino new file mode 100644 index 000000000..ca17189ea --- /dev/null +++ b/extras/particle/src/smocktest.ino @@ -0,0 +1,5 @@ +#include "ArduinoJson.h" + +void setup() {} + +void loop() {} diff --git a/extras/scripts/build-single-header.sh b/extras/scripts/build-single-header.sh new file mode 100755 index 000000000..00292e307 --- /dev/null +++ b/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/extras/scripts/extract_changes.awk b/extras/scripts/extract_changes.awk new file mode 100755 index 000000000..d96d459de --- /dev/null +++ b/extras/scripts/extract_changes.awk @@ -0,0 +1,29 @@ +#!/usr/bin/awk -f + +# Start echoing after the first list item +/\* / { + STARTED=1 + EMPTY_LINE=0 +} + +# Remember if we have seen an empty line +/^[[:space:]]*$/ { + EMPTY_LINE=1 +} + +# Exit when seeing a new version number +/^v[[:digit:]]/ { + if (STARTED) exit +} + +# Print if the line is not empty +# and restore the empty line we have skipped +!/^[[:space:]]*$/ { + if (STARTED) { + if (EMPTY_LINE) { + print "" + EMPTY_LINE=0 + } + print + } +} diff --git a/extras/scripts/get-release-page.sh b/extras/scripts/get-release-page.sh new file mode 100755 index 000000000..10fa08775 --- /dev/null +++ b/extras/scripts/get-release-page.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +set -eu + +VERSION="$1" +CHANGELOG="$2" +ARDUINOJSON_H="$3" + +cat << END +--- +branch: v7 +version: $VERSION +date: '$(date +'%Y-%m-%d')' +$(extras/scripts/wandbox/publish.sh "$ARDUINOJSON_H") +--- + +$(extras/scripts/extract_changes.awk "$CHANGELOG") +END diff --git a/extras/scripts/publish-particle-library.sh b/extras/scripts/publish-particle-library.sh new file mode 100755 index 000000000..d410c470a --- /dev/null +++ b/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 +particle library publish diff --git a/extras/scripts/publish.sh b/extras/scripts/publish.sh new file mode 100755 index 000000000..60af5fc46 --- /dev/null +++ b/extras/scripts/publish.sh @@ -0,0 +1,87 @@ +#!/usr/bin/env bash + +set -eu + +which awk sed jq 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]+)?' +STARS=$(curl -s https://api.github.com/repos/bblanchon/ArduinoJson | jq '.stargazers_count') + +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 \ + -e "s/\"version\":.*$/\"version\": \"$VERSION\",/" \ + -e "s/[0-9]+ stars/$STARS stars/" \ + library.json + rm library.json~ + + sed -i~ -bE \ + -e "s/version=.*$/version=$VERSION/" \ + -e "s/[0-9]+ stars/$STARS stars/" \ + library.properties + rm library.properties~ + + sed -i~ -bE "s/version: .*$/version: $VERSION.{build}/" appveyor.yml + rm appveyor.yml~ + + sed -i~ -bE \ + -e "s/^version: .*$/version: \"$VERSION\"/" \ + -e "s/[0-9]+ stars/$STARS stars/" \ + 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/" \ + -e "s/ARDUINOJSON_VERSION_MACRO .*$/ARDUINOJSON_VERSION_MACRO V$MAJOR$MINOR$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-single-header.sh "src/ArduinoJson.h" "../ArduinoJson-$TAG.h" +extras/scripts/build-single-header.sh "src/ArduinoJson.hpp" "../ArduinoJson-$TAG.hpp" +extras/scripts/get-release-page.sh "$VERSION" "CHANGELOG.md" "../ArduinoJson-$TAG.h" > "../ArduinoJson-$TAG.md" + +echo "You can now copy ../ArduinoJson-$TAG.md into arduinojson.org/collections/_versions/$VERSION.md" diff --git a/extras/scripts/wandbox/JsonGeneratorExample.cpp b/extras/scripts/wandbox/JsonGeneratorExample.cpp new file mode 100644 index 000000000..2e08b4ca5 --- /dev/null +++ b/extras/scripts/wandbox/JsonGeneratorExample.cpp @@ -0,0 +1,42 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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 + JsonDocument doc; + + // Add values in the document. + doc["sensor"] = "gps"; + doc["time"] = 1351824120; + + // Add an array + JsonArray data = doc["data"].to(); + 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/extras/scripts/wandbox/JsonParserExample.cpp b/extras/scripts/wandbox/JsonParserExample.cpp new file mode 100644 index 000000000..1969cf269 --- /dev/null +++ b/extras/scripts/wandbox/JsonParserExample.cpp @@ -0,0 +1,43 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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 + JsonDocument doc; + + // JSON input string + const 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 the 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 the 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/extras/scripts/wandbox/MsgPackParserExample.cpp b/extras/scripts/wandbox/MsgPackParserExample.cpp new file mode 100644 index 000000000..81e68221a --- /dev/null +++ b/extras/scripts/wandbox/MsgPackParserExample.cpp @@ -0,0 +1,51 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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 + JsonDocument doc; + + // The MessagePack input string + 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] + // } + + // Parse the input + DeserializationError error = deserializeMsgPack(doc, input); + + // Test if parsing succeeds + if (error) { + std::cerr << "deserializeMsgPack() failed: " << error.c_str() << std::endl; + return 1; + } + + // Fetch the 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 the 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/extras/scripts/wandbox/publish.sh b/extras/scripts/wandbox/publish.sh new file mode 100755 index 000000000..611572f86 --- /dev/null +++ b/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 < +// but we don't want it to included accidentally +#undef ARDUINO +#define ARDUINOJSON_ENABLE_STD_STREAM 0 +#define ARDUINOJSON_ENABLE_STD_STRING 0 + +#include +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +#if !ARDUINOJSON_ENABLE_STRING_VIEW +# error ARDUINOJSON_ENABLE_STRING_VIEW must be set to 1 +#endif + +using ArduinoJson::detail::sizeofArray; + +TEST_CASE("string_view") { + SpyingAllocator spy; + JsonDocument doc(&spy); + 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)); + doc.add(std::string_view("example two", 7)); + doc.add(std::string_view("example\0tree", 12)); + doc.add(std::string_view("example\0tree and a half", 12)); + + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("example")), + Allocate(sizeofString("example tree")), + }); + } + + 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("hello\0world"_s); + 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/extras/tests/Cpp20/CMakeLists.txt b/extras/tests/Cpp20/CMakeLists.txt new file mode 100644 index 000000000..6346d4d2e --- /dev/null +++ b/extras/tests/Cpp20/CMakeLists.txt @@ -0,0 +1,29 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2025, 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/extras/tests/Cpp20/smoke_test.cpp b/extras/tests/Cpp20/smoke_test.cpp new file mode 100644 index 000000000..72dd50f32 --- /dev/null +++ b/extras/tests/Cpp20/smoke_test.cpp @@ -0,0 +1,15 @@ +#include + +#include +#include + +TEST_CASE("C++20 smoke test") { + JsonDocument doc; + + deserializeJson(doc, "{\"hello\":\"world\"}"); + REQUIRE(doc["hello"] == "world"); + + std::string json; + serializeJson(doc, json); + REQUIRE(json == "{\"hello\":\"world\"}"); +} diff --git a/extras/tests/Deprecated/BasicJsonDocument.cpp b/extras/tests/Deprecated/BasicJsonDocument.cpp new file mode 100644 index 000000000..a35097792 --- /dev/null +++ b/extras/tests/Deprecated/BasicJsonDocument.cpp @@ -0,0 +1,69 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include + +using ArduinoJson::detail::is_base_of; + +static std::string allocatorLog; + +struct CustomAllocator { + CustomAllocator() { + allocatorLog = ""; + } + + void* allocate(size_t n) { + allocatorLog += "A"; + return malloc(n); + } + + void deallocate(void* p) { + free(p); + allocatorLog += "D"; + } + + void* reallocate(void* p, size_t n) { + allocatorLog += "R"; + return realloc(p, n); + } +}; + +TEST_CASE("BasicJsonDocument") { + allocatorLog.clear(); + + SECTION("is a JsonDocument") { + REQUIRE( + is_base_of>::value == + true); + } + + SECTION("deserialize / serialize") { + BasicJsonDocument doc(256); + deserializeJson(doc, "{\"hello\":\"world\"}"); + REQUIRE(doc.as() == "{\"hello\":\"world\"}"); + doc.clear(); + REQUIRE(allocatorLog == "AARARDDD"); + } + + SECTION("copy") { + BasicJsonDocument doc(256); + doc["hello"] = "world"; + auto copy = doc; + REQUIRE(copy.as() == "{\"hello\":\"world\"}"); + REQUIRE(allocatorLog == "AA"); + } + + SECTION("capacity") { + BasicJsonDocument doc(256); + REQUIRE(doc.capacity() == 256); + } + + SECTION("garbageCollect()") { + BasicJsonDocument doc(256); + doc.garbageCollect(); + } +} diff --git a/extras/tests/Deprecated/CMakeLists.txt b/extras/tests/Deprecated/CMakeLists.txt new file mode 100644 index 000000000..bcf33e11b --- /dev/null +++ b/extras/tests/Deprecated/CMakeLists.txt @@ -0,0 +1,35 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2025, Benoit BLANCHON +# MIT License + +if(CMAKE_CXX_COMPILER_ID MATCHES "(GNU|Clang)") + add_compile_options( + -w + ) +endif() + +if(MSVC) + add_compile_options( + /wd4996 + ) +endif() + +add_executable(DeprecatedTests + add.cpp + BasicJsonDocument.cpp + containsKey.cpp + createNestedArray.cpp + createNestedObject.cpp + DynamicJsonDocument.cpp + macros.cpp + memoryUsage.cpp + shallowCopy.cpp + StaticJsonDocument.cpp +) + +add_test(Deprecated DeprecatedTests) + +set_tests_properties(Deprecated + PROPERTIES + LABELS "Catch" +) diff --git a/extras/tests/Deprecated/DynamicJsonDocument.cpp b/extras/tests/Deprecated/DynamicJsonDocument.cpp new file mode 100644 index 000000000..7c6d44b88 --- /dev/null +++ b/extras/tests/Deprecated/DynamicJsonDocument.cpp @@ -0,0 +1,37 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +using ArduinoJson::detail::is_base_of; + +TEST_CASE("DynamicJsonDocument") { + SECTION("is a JsonDocument") { + REQUIRE(is_base_of::value == true); + } + + SECTION("deserialize / serialize") { + DynamicJsonDocument doc(256); + deserializeJson(doc, "{\"hello\":\"world\"}"); + REQUIRE(doc.as() == "{\"hello\":\"world\"}"); + } + + SECTION("copy") { + DynamicJsonDocument doc(256); + doc["hello"] = "world"; + auto copy = doc; + REQUIRE(copy.as() == "{\"hello\":\"world\"}"); + } + + SECTION("capacity") { + DynamicJsonDocument doc(256); + REQUIRE(doc.capacity() == 256); + } + + SECTION("garbageCollect()") { + DynamicJsonDocument doc(256); + doc.garbageCollect(); + } +} diff --git a/extras/tests/Deprecated/StaticJsonDocument.cpp b/extras/tests/Deprecated/StaticJsonDocument.cpp new file mode 100644 index 000000000..39a363be8 --- /dev/null +++ b/extras/tests/Deprecated/StaticJsonDocument.cpp @@ -0,0 +1,32 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +using ArduinoJson::detail::is_base_of; + +TEST_CASE("StaticJsonDocument") { + SECTION("is a JsonDocument") { + REQUIRE(is_base_of>::value == true); + } + + SECTION("deserialize / serialize") { + StaticJsonDocument<256> doc; + deserializeJson(doc, "{\"hello\":\"world\"}"); + REQUIRE(doc.as() == "{\"hello\":\"world\"}"); + } + + SECTION("copy") { + StaticJsonDocument<256> doc; + doc["hello"] = "world"; + auto copy = doc; + REQUIRE(copy.as() == "{\"hello\":\"world\"}"); + } + + SECTION("capacity") { + StaticJsonDocument<256> doc; + REQUIRE(doc.capacity() == 256); + } +} diff --git a/extras/tests/Deprecated/add.cpp b/extras/tests/Deprecated/add.cpp new file mode 100644 index 000000000..586e22b80 --- /dev/null +++ b/extras/tests/Deprecated/add.cpp @@ -0,0 +1,38 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonArray::add()") { + JsonDocument doc; + JsonArray array = doc.to(); + array.add().set(42); + REQUIRE(doc.as() == "[42]"); +} + +TEST_CASE("JsonDocument::add()") { + JsonDocument doc; + doc.add().set(42); + REQUIRE(doc.as() == "[42]"); +} + +TEST_CASE("ElementProxy::add()") { + JsonDocument doc; + doc[0].add().set(42); + REQUIRE(doc.as() == "[[42]]"); +} + +TEST_CASE("MemberProxy::add()") { + JsonDocument doc; + doc["x"].add().set(42); + REQUIRE(doc.as() == "{\"x\":[42]}"); +} + +TEST_CASE("JsonVariant::add()") { + JsonDocument doc; + JsonVariant v = doc.add(); + v.add().set(42); + REQUIRE(doc.as() == "[[42]]"); +} diff --git a/extras/tests/Deprecated/containsKey.cpp b/extras/tests/Deprecated/containsKey.cpp new file mode 100644 index 000000000..d001d4068 --- /dev/null +++ b/extras/tests/Deprecated/containsKey.cpp @@ -0,0 +1,246 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Literals.hpp" + +TEST_CASE("JsonDocument::containsKey()") { + JsonDocument doc; + + 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("hello"_s) == 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); + } + + SECTION("supports JsonVariant") { + doc["hello"] = "world"; + doc["key"] = "hello"; + + REQUIRE(doc.containsKey(doc["key"]) == true); + REQUIRE(doc.containsKey(doc["foo"]) == false); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("supports VLAs") { + size_t i = 16; + char vla[i]; + strcpy(vla, "hello"); + + doc["hello"] = "world"; + + REQUIRE(doc.containsKey(vla) == true); + } +#endif +} + +TEST_CASE("MemberProxy::containsKey()") { + JsonDocument doc; + const auto& 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("key"_s) == true); + REQUIRE(mp.containsKey("key"_s) == true); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("supports VLAs") { + size_t i = 16; + char vla[i]; + strcpy(vla, "hello"); + + mp["hello"] = "world"; + + REQUIRE(mp.containsKey(vla) == true); + } +#endif +} + +TEST_CASE("JsonObject::containsKey()") { + JsonDocument doc; + 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("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 + + SECTION("key is a JsonVariant") { + doc["key"] = "hello"; + REQUIRE(true == obj.containsKey(obj["key"])); + REQUIRE(false == obj.containsKey(obj["hello"])); + } + + SECTION("std::string") { + REQUIRE(true == obj.containsKey("hello"_s)); + } + + SECTION("unsigned char[]") { + unsigned char key[] = "hello"; + REQUIRE(true == obj.containsKey(key)); + } +} + +TEST_CASE("JsonObjectConst::containsKey()") { + JsonDocument doc; + doc["hello"] = 42; + auto obj = doc.as(); + + SECTION("supports const char*") { + REQUIRE(false == obj.containsKey("world")); + REQUIRE(true == obj.containsKey("hello")); + } + + SECTION("supports std::string") { + REQUIRE(false == obj.containsKey("world"_s)); + REQUIRE(true == obj.containsKey("hello"_s)); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("supports VLA") { + size_t i = 16; + char vla[i]; + strcpy(vla, "hello"); + + REQUIRE(true == obj.containsKey(vla)); + } +#endif + + SECTION("supports JsonVariant") { + doc["key"] = "hello"; + REQUIRE(true == obj.containsKey(obj["key"])); + REQUIRE(false == obj.containsKey(obj["hello"])); + } +} + +TEST_CASE("JsonVariant::containsKey()") { + JsonDocument doc; + JsonVariant var = doc.to(); + + SECTION("returns false is unbound") { + CHECK_FALSE(JsonVariant().containsKey("hello")); + } + + 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("hello"_s) == true); + REQUIRE(var.containsKey("world"_s) == false); + } + + SECTION("containsKey(JsonVariant)") { + var["hello"] = "world"; + var["key"] = "hello"; + + REQUIRE(var.containsKey(doc["key"]) == true); + REQUIRE(var.containsKey(doc["foo"]) == false); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("supports VLAs") { + size_t i = 16; + char vla[i]; + strcpy(vla, "hello"); + + var["hello"] = "world"; + + REQUIRE(var.containsKey(vla) == true); + } +#endif +} + +TEST_CASE("JsonVariantConst::containsKey()") { + JsonDocument doc; + doc["hello"] = "world"; + JsonVariantConst var = doc.as(); + + SECTION("support const char*") { + REQUIRE(var.containsKey("hello") == true); + REQUIRE(var.containsKey("world") == false); + } + + SECTION("support std::string") { + REQUIRE(var.containsKey("hello"_s) == true); + REQUIRE(var.containsKey("world"_s) == false); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("supports VLA") { + size_t i = 16; + char vla[i]; + strcpy(vla, "hello"); + + REQUIRE(true == var.containsKey(vla)); + } +#endif + + SECTION("support JsonVariant") { + doc["key"] = "hello"; + REQUIRE(var.containsKey(var["key"]) == true); + REQUIRE(var.containsKey(var["foo"]) == false); + } +} diff --git a/extras/tests/Deprecated/createNestedArray.cpp b/extras/tests/Deprecated/createNestedArray.cpp new file mode 100644 index 000000000..858c022d1 --- /dev/null +++ b/extras/tests/Deprecated/createNestedArray.cpp @@ -0,0 +1,113 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include + +#include "Literals.hpp" + +TEST_CASE("JsonDocument::createNestedArray()") { + JsonDocument doc; + + SECTION("createNestedArray()") { + JsonArray array = doc.createNestedArray(); + array.add(42); + REQUIRE(doc.as() == "[[42]]"); + } + + SECTION("createNestedArray(const char*)") { + JsonArray array = doc.createNestedArray("key"); + array.add(42); + REQUIRE(doc.as() == "{\"key\":[42]}"); + } + + SECTION("createNestedArray(std::string)") { + JsonArray array = doc.createNestedArray("key"_s); + array.add(42); + REQUIRE(doc.as() == "{\"key\":[42]}"); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("createNestedArray(VLA)") { + size_t i = 16; + char vla[i]; + strcpy(vla, "key"); + JsonArray array = doc.createNestedArray(vla); + array.add(42); + REQUIRE(doc.as() == "{\"key\":[42]}"); + } +#endif +} + +TEST_CASE("JsonArray::createNestedArray()") { + JsonDocument doc; + JsonArray array = doc.to(); + JsonArray nestedArray = array.createNestedArray(); + nestedArray.add(42); + REQUIRE(doc.as() == "[[42]]"); +} + +TEST_CASE("JsonObject::createNestedArray()") { + JsonDocument doc; + JsonObject object = doc.to(); + + SECTION("createNestedArray(const char*)") { + JsonArray array = object.createNestedArray("key"); + array.add(42); + REQUIRE(doc.as() == "{\"key\":[42]}"); + } + + SECTION("createNestedArray(std::string)") { + JsonArray array = object.createNestedArray("key"_s); + array.add(42); + REQUIRE(doc.as() == "{\"key\":[42]}"); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("createNestedArray(VLA)") { + size_t i = 16; + char vla[i]; + strcpy(vla, "key"); + JsonArray array = object.createNestedArray(vla); + array.add(42); + REQUIRE(doc.as() == "{\"key\":[42]}"); + } +#endif +} + +TEST_CASE("JsonVariant::createNestedArray()") { + JsonDocument doc; + JsonVariant variant = doc.to(); + + SECTION("createNestedArray()") { + JsonArray array = variant.createNestedArray(); + array.add(42); + REQUIRE(doc.as() == "[[42]]"); + } + + SECTION("createNestedArray(const char*)") { + JsonArray array = variant.createNestedArray("key"); + array.add(42); + REQUIRE(doc.as() == "{\"key\":[42]}"); + } + + SECTION("createNestedArray(std::string)") { + JsonArray array = variant.createNestedArray("key"_s); + array.add(42); + REQUIRE(doc.as() == "{\"key\":[42]}"); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("createNestedArray(VLA)") { + size_t i = 16; + char vla[i]; + strcpy(vla, "key"); + JsonArray array = variant.createNestedArray(vla); + array.add(42); + REQUIRE(doc.as() == "{\"key\":[42]}"); + } +#endif +} diff --git a/extras/tests/Deprecated/createNestedObject.cpp b/extras/tests/Deprecated/createNestedObject.cpp new file mode 100644 index 000000000..c035eb8fc --- /dev/null +++ b/extras/tests/Deprecated/createNestedObject.cpp @@ -0,0 +1,113 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include + +#include "Literals.hpp" + +TEST_CASE("JsonDocument::createNestedObject()") { + JsonDocument doc; + + SECTION("createNestedObject()") { + JsonObject object = doc.createNestedObject(); + object["hello"] = "world"; + REQUIRE(doc.as() == "[{\"hello\":\"world\"}]"); + } + + SECTION("createNestedObject(const char*)") { + JsonObject object = doc.createNestedObject("key"); + object["hello"] = "world"; + REQUIRE(doc.as() == "{\"key\":{\"hello\":\"world\"}}"); + } + + SECTION("createNestedObject(std::string)") { + JsonObject object = doc.createNestedObject("key"_s); + object["hello"] = "world"; + REQUIRE(doc.as() == "{\"key\":{\"hello\":\"world\"}}"); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("createNestedObject(VLA)") { + size_t i = 16; + char vla[i]; + strcpy(vla, "key"); + JsonObject object = doc.createNestedObject(vla); + object["hello"] = "world"; + REQUIRE(doc.as() == "{\"key\":{\"hello\":\"world\"}}"); + } +#endif +} + +TEST_CASE("JsonArray::createNestedObject()") { + JsonDocument doc; + JsonArray array = doc.to(); + JsonObject object = array.createNestedObject(); + object["hello"] = "world"; + REQUIRE(doc.as() == "[{\"hello\":\"world\"}]"); +} + +TEST_CASE("JsonObject::createNestedObject()") { + JsonDocument doc; + JsonObject object = doc.to(); + + SECTION("createNestedObject(const char*)") { + JsonObject nestedObject = object.createNestedObject("key"); + nestedObject["hello"] = "world"; + REQUIRE(doc.as() == "{\"key\":{\"hello\":\"world\"}}"); + } + + SECTION("createNestedObject(std::string)") { + JsonObject nestedObject = object.createNestedObject("key"_s); + nestedObject["hello"] = "world"; + REQUIRE(doc.as() == "{\"key\":{\"hello\":\"world\"}}"); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("createNestedObject(VLA)") { + size_t i = 16; + char vla[i]; + strcpy(vla, "key"); + JsonObject nestedObject = object.createNestedObject(vla); + nestedObject["hello"] = "world"; + REQUIRE(doc.as() == "{\"key\":{\"hello\":\"world\"}}"); + } +#endif +} + +TEST_CASE("JsonVariant::createNestedObject()") { + JsonDocument doc; + JsonVariant variant = doc.to(); + + SECTION("createNestedObject()") { + JsonObject object = variant.createNestedObject(); + object["hello"] = "world"; + REQUIRE(doc.as() == "[{\"hello\":\"world\"}]"); + } + + SECTION("createNestedObject(const char*)") { + JsonObject object = variant.createNestedObject("key"); + object["hello"] = "world"; + REQUIRE(doc.as() == "{\"key\":{\"hello\":\"world\"}}"); + } + + SECTION("createNestedObject(std::string)") { + JsonObject object = variant.createNestedObject("key"_s); + object["hello"] = "world"; + REQUIRE(doc.as() == "{\"key\":{\"hello\":\"world\"}}"); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("createNestedObject(VLA)") { + size_t i = 16; + char vla[i]; + strcpy(vla, "key"); + JsonObject object = variant.createNestedObject(vla); + object["hello"] = "world"; + REQUIRE(doc.as() == "{\"key\":{\"hello\":\"world\"}}"); + } +#endif +} diff --git a/extras/tests/Deprecated/macros.cpp b/extras/tests/Deprecated/macros.cpp new file mode 100644 index 000000000..2e73d5b3c --- /dev/null +++ b/extras/tests/Deprecated/macros.cpp @@ -0,0 +1,18 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JSON_ARRAY_SIZE") { + REQUIRE(JSON_ARRAY_SIZE(10) == ArduinoJson::detail::sizeofArray(10)); +} + +TEST_CASE("JSON_OBJECT_SIZE") { + REQUIRE(JSON_OBJECT_SIZE(10) == ArduinoJson::detail::sizeofObject(10)); +} + +TEST_CASE("JSON_STRING_SIZE") { + REQUIRE(JSON_STRING_SIZE(10) == 11); // issue #2054 +} diff --git a/extras/tests/Deprecated/memoryUsage.cpp b/extras/tests/Deprecated/memoryUsage.cpp new file mode 100644 index 000000000..89258f08f --- /dev/null +++ b/extras/tests/Deprecated/memoryUsage.cpp @@ -0,0 +1,51 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonArray::memoryUsage()") { + JsonArray array; + REQUIRE(array.memoryUsage() == 0); +} + +TEST_CASE("JsonArrayConst::memoryUsage()") { + JsonArrayConst array; + REQUIRE(array.memoryUsage() == 0); +} + +TEST_CASE("JsonDocument::memoryUsage()") { + JsonDocument doc; + REQUIRE(doc.memoryUsage() == 0); +} + +TEST_CASE("JsonObject::memoryUsage()") { + JsonObject array; + REQUIRE(array.memoryUsage() == 0); +} + +TEST_CASE("JsonObjectConst::memoryUsage()") { + JsonObjectConst array; + REQUIRE(array.memoryUsage() == 0); +} + +TEST_CASE("JsonVariant::memoryUsage()") { + JsonVariant doc; + REQUIRE(doc.memoryUsage() == 0); +} + +TEST_CASE("JsonVariantConst::memoryUsage()") { + JsonVariantConst doc; + REQUIRE(doc.memoryUsage() == 0); +} + +TEST_CASE("ElementProxy::memoryUsage()") { + JsonDocument doc; + REQUIRE(doc[0].memoryUsage() == 0); +} + +TEST_CASE("MemberProxy::memoryUsage()") { + JsonDocument doc; + REQUIRE(doc["hello"].memoryUsage() == 0); +} diff --git a/extras/tests/Deprecated/shallowCopy.cpp b/extras/tests/Deprecated/shallowCopy.cpp new file mode 100644 index 000000000..1f0d12e3b --- /dev/null +++ b/extras/tests/Deprecated/shallowCopy.cpp @@ -0,0 +1,14 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("shallowCopy()") { + JsonDocument doc1, doc2; + doc1["b"] = "c"; + doc2["a"].shallowCopy(doc1); + + REQUIRE(doc2.as() == "{\"a\":{\"b\":\"c\"}}"); +} diff --git a/extras/tests/FailingBuilds/CMakeLists.txt b/extras/tests/FailingBuilds/CMakeLists.txt new file mode 100644 index 000000000..08dbe529c --- /dev/null +++ b/extras/tests/FailingBuilds/CMakeLists.txt @@ -0,0 +1,32 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2025, Benoit BLANCHON +# MIT License + +macro(add_failing_build source_file) + get_filename_component(target ${source_file} NAME_WE) + + add_executable(${target} ${source_file}) + + 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" + ) +endmacro() + +add_failing_build(Issue978.cpp) +add_failing_build(read_long_long.cpp) +add_failing_build(write_long_long.cpp) +add_failing_build(variant_as_char.cpp) +add_failing_build(assign_char.cpp) +add_failing_build(deserialize_object.cpp) diff --git a/extras/tests/FailingBuilds/Issue978.cpp b/extras/tests/FailingBuilds/Issue978.cpp new file mode 100644 index 000000000..3b9ec9581 --- /dev/null +++ b/extras/tests/FailingBuilds/Issue978.cpp @@ -0,0 +1,13 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include + +struct Stream {}; + +int main() { + Stream* stream = 0; + JsonDocument doc; + deserializeJson(doc, stream); +} diff --git a/extras/tests/FailingBuilds/assign_char.cpp b/extras/tests/FailingBuilds/assign_char.cpp new file mode 100644 index 000000000..888d23c91 --- /dev/null +++ b/extras/tests/FailingBuilds/assign_char.cpp @@ -0,0 +1,12 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include + +// See issue #1498 + +int main() { + JsonDocument doc; + doc["dummy"] = 'A'; +} diff --git a/extras/tests/FailingBuilds/deserialize_object.cpp b/extras/tests/FailingBuilds/deserialize_object.cpp new file mode 100644 index 000000000..b9313ed40 --- /dev/null +++ b/extras/tests/FailingBuilds/deserialize_object.cpp @@ -0,0 +1,12 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include + +// See issue #2135 + +int main() { + JsonObject obj; + deserializeJson(obj, ""); +} diff --git a/extras/tests/FailingBuilds/read_long_long.cpp b/extras/tests/FailingBuilds/read_long_long.cpp new file mode 100644 index 000000000..daf1f40de --- /dev/null +++ b/extras/tests/FailingBuilds/read_long_long.cpp @@ -0,0 +1,16 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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() { + JsonDocument doc; + doc["dummy"].as(); +} diff --git a/extras/tests/FailingBuilds/variant_as_char.cpp b/extras/tests/FailingBuilds/variant_as_char.cpp new file mode 100644 index 000000000..b1e86ee60 --- /dev/null +++ b/extras/tests/FailingBuilds/variant_as_char.cpp @@ -0,0 +1,12 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include + +// See issue #1498 + +int main() { + JsonDocument doc; + doc["dummy"].as(); +} diff --git a/extras/tests/FailingBuilds/write_long_long.cpp b/extras/tests/FailingBuilds/write_long_long.cpp new file mode 100644 index 000000000..4aee6565e --- /dev/null +++ b/extras/tests/FailingBuilds/write_long_long.cpp @@ -0,0 +1,15 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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() { + JsonDocument doc; + doc["dummy"] = static_cast(42); +} diff --git a/extras/tests/Helpers/Allocators.hpp b/extras/tests/Helpers/Allocators.hpp new file mode 100644 index 000000000..17e05cab2 --- /dev/null +++ b/extras/tests/Helpers/Allocators.hpp @@ -0,0 +1,288 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#pragma once + +#include +#include +#include + +#include + +namespace { + +struct FailingAllocator : ArduinoJson::Allocator { + static FailingAllocator* instance() { + static FailingAllocator allocator; + return &allocator; + } + + private: + FailingAllocator() = default; + ~FailingAllocator() = default; + + void* allocate(size_t) override { + return nullptr; + } + + void deallocate(void*) override {} + + void* reallocate(void*, size_t) override { + return nullptr; + } +}; + +class AllocatorLogEntry { + public: + AllocatorLogEntry(std::string s, size_t n = 1) : str_(s), count_(n) {} + + const std::string& str() const { + return str_; + } + + size_t count() const { + return count_; + } + + AllocatorLogEntry operator*(size_t n) const { + return AllocatorLogEntry(str_, n); + } + + private: + std::string str_; + size_t count_; +}; + +inline AllocatorLogEntry Allocate(size_t s) { + char buffer[32]; + snprintf(buffer, sizeof(buffer), "allocate(%zu)", s); + return AllocatorLogEntry(buffer); +} + +inline AllocatorLogEntry AllocateFail(size_t s) { + char buffer[32]; + snprintf(buffer, sizeof(buffer), "allocate(%zu) -> nullptr", s); + return AllocatorLogEntry(buffer); +} + +inline AllocatorLogEntry Reallocate(size_t s1, size_t s2) { + char buffer[32]; + snprintf(buffer, sizeof(buffer), "reallocate(%zu, %zu)", s1, s2); + return AllocatorLogEntry(buffer); +} + +inline AllocatorLogEntry ReallocateFail(size_t s1, size_t s2) { + char buffer[32]; + snprintf(buffer, sizeof(buffer), "reallocate(%zu, %zu) -> nullptr", s1, s2); + return AllocatorLogEntry(buffer); +} + +inline AllocatorLogEntry Deallocate(size_t s) { + char buffer[32]; + snprintf(buffer, sizeof(buffer), "deallocate(%zu)", s); + return AllocatorLogEntry(buffer); +} + +class AllocatorLog { + public: + AllocatorLog() = default; + AllocatorLog(std::initializer_list list) { + for (auto& entry : list) + append(entry); + } + + void clear() { + log_.str(""); + } + + void append(const AllocatorLogEntry& entry) { + for (size_t i = 0; i < entry.count(); i++) + log_ << entry.str() << "\n"; + } + + std::string str() const { + auto s = log_.str(); + if (s.empty()) + return "(empty)"; + s.pop_back(); // remove the trailing '\n' + return s; + } + + bool operator==(const AllocatorLog& other) const { + return str() == other.str(); + } + + friend std::ostream& operator<<(std::ostream& os, const AllocatorLog& log) { + os << log.str(); + return os; + } + + private: + std::ostringstream log_; +}; + +class SpyingAllocator : public ArduinoJson::Allocator { + public: + SpyingAllocator( + Allocator* upstream = ArduinoJson::detail::DefaultAllocator::instance()) + : upstream_(upstream) {} + virtual ~SpyingAllocator() {} + + size_t allocatedBytes() const { + return allocatedBytes_; + } + + void* allocate(size_t n) override { + auto block = reinterpret_cast( + upstream_->allocate(sizeof(AllocatedBlock) + n - 1)); + if (block) { + log_.append(Allocate(n)); + allocatedBytes_ += n; + block->size = n; + return block->payload; + } else { + log_.append(AllocateFail(n)); + return nullptr; + } + } + + void deallocate(void* p) override { + auto block = AllocatedBlock::fromPayload(p); + allocatedBytes_ -= block->size; + log_.append(Deallocate(block ? block->size : 0)); + upstream_->deallocate(block); + } + + void* reallocate(void* p, size_t n) override { + auto block = AllocatedBlock::fromPayload(p); + auto oldSize = block ? block->size : 0; + block = reinterpret_cast( + upstream_->reallocate(block, sizeof(AllocatedBlock) + n - 1)); + if (block) { + log_.append(Reallocate(oldSize, n)); + block->size = n; + allocatedBytes_ += n - oldSize; + return block->payload; + } else { + log_.append(ReallocateFail(oldSize, n)); + return nullptr; + } + } + + void clearLog() { + log_.clear(); + } + + const AllocatorLog& log() const { + return log_; + } + + private: + struct AllocatedBlock { + size_t size; + char payload[1]; + + static AllocatedBlock* fromPayload(void* p) { + if (!p) + return nullptr; + return reinterpret_cast( + // Cast to void* to silence "cast increases required alignment of + // target type [-Werror=cast-align]" + reinterpret_cast(reinterpret_cast(p) - + offsetof(AllocatedBlock, payload))); + } + }; + + AllocatorLog log_; + Allocator* upstream_; + size_t allocatedBytes_ = 0; +}; + +class KillswitchAllocator : public ArduinoJson::Allocator { + public: + KillswitchAllocator( + Allocator* upstream = ArduinoJson::detail::DefaultAllocator::instance()) + : working_(true), upstream_(upstream) {} + virtual ~KillswitchAllocator() {} + + void* allocate(size_t n) override { + return working_ ? upstream_->allocate(n) : 0; + } + + void deallocate(void* p) override { + upstream_->deallocate(p); + } + + void* reallocate(void* ptr, size_t n) override { + return working_ ? upstream_->reallocate(ptr, n) : 0; + } + + // Turn the killswitch on, so all allocation fail + void on() { + working_ = false; + } + + private: + bool working_; + Allocator* upstream_; +}; + +class TimebombAllocator : public ArduinoJson::Allocator { + public: + TimebombAllocator( + size_t initialCountdown, + Allocator* upstream = ArduinoJson::detail::DefaultAllocator::instance()) + : countdown_(initialCountdown), upstream_(upstream) {} + virtual ~TimebombAllocator() {} + + void* allocate(size_t n) override { + if (!countdown_) + return nullptr; + countdown_--; + return upstream_->allocate(n); + } + + void deallocate(void* p) override { + upstream_->deallocate(p); + } + + void* reallocate(void* ptr, size_t n) override { + if (!countdown_) + return nullptr; + countdown_--; + return upstream_->reallocate(ptr, n); + } + + void setCountdown(size_t value) { + countdown_ = value; + } + + private: + size_t countdown_ = 0; + Allocator* upstream_; +}; +} // namespace + +inline size_t sizeofPoolList(size_t n = ARDUINOJSON_INITIAL_POOL_COUNT) { + using namespace ArduinoJson::detail; + return sizeof(MemoryPool) * n; +} + +inline size_t sizeofPool( + ArduinoJson::detail::SlotCount n = ARDUINOJSON_POOL_CAPACITY) { + using namespace ArduinoJson::detail; + return MemoryPool::slotsToBytes(n); +} + +inline size_t sizeofStringBuffer(size_t iteration = 1) { + // returns 31, 63, 127, 255, etc. + auto capacity = ArduinoJson::detail::StringBuilder::initialCapacity; + for (size_t i = 1; i < iteration; i++) + capacity = capacity * 2 + 1; + return ArduinoJson::detail::sizeofString(capacity); +} + +inline size_t sizeofString(const char* s) { + return ArduinoJson::detail::sizeofString(strlen(s)); +} diff --git a/extras/tests/Helpers/Arduino.h b/extras/tests/Helpers/Arduino.h new file mode 100644 index 000000000..d12f872a9 --- /dev/null +++ b/extras/tests/Helpers/Arduino.h @@ -0,0 +1,13 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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/extras/tests/Helpers/CustomReader.hpp b/extras/tests/Helpers/CustomReader.hpp new file mode 100644 index 000000000..76a513833 --- /dev/null +++ b/extras/tests/Helpers/CustomReader.hpp @@ -0,0 +1,24 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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/extras/tests/Helpers/Literals.hpp b/extras/tests/Helpers/Literals.hpp new file mode 100644 index 000000000..07c079dc8 --- /dev/null +++ b/extras/tests/Helpers/Literals.hpp @@ -0,0 +1,12 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#pragma once + +#include + +// the space before _s is required by GCC 4.8 +inline std::string operator"" _s(const char* str, size_t len) { + return std::string(str, len); +} diff --git a/extras/tests/Helpers/api/Print.h b/extras/tests/Helpers/api/Print.h new file mode 100644 index 000000000..cdf05bbfc --- /dev/null +++ b/extras/tests/Helpers/api/Print.h @@ -0,0 +1,33 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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/extras/tests/Helpers/api/Stream.h b/extras/tests/Helpers/api/Stream.h new file mode 100644 index 000000000..64b9eaf99 --- /dev/null +++ b/extras/tests/Helpers/api/Stream.h @@ -0,0 +1,14 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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/extras/tests/Helpers/api/String.h b/extras/tests/Helpers/api/String.h new file mode 100644 index 000000000..1841610c5 --- /dev/null +++ b/extras/tests/Helpers/api/String.h @@ -0,0 +1,75 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#pragma once + +#include + +// Reproduces Arduino's String class +class String { + public: + String() = default; + String(const char* s) { + if (s) + str_.assign(s); + } + + 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) { + if (s) + str_.assign(s); + else + str_.clear(); + 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_ = 1024; +}; + +class StringSumHelper : public ::String {}; + +inline bool operator==(const std::string& lhs, const ::String& rhs) { + return lhs == rhs.c_str(); +} diff --git a/extras/tests/Helpers/avr/pgmspace.h b/extras/tests/Helpers/avr/pgmspace.h new file mode 100644 index 000000000..8cbf44e09 --- /dev/null +++ b/extras/tests/Helpers/avr/pgmspace.h @@ -0,0 +1,31 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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/extras/tests/IntegrationTests/CMakeLists.txt b/extras/tests/IntegrationTests/CMakeLists.txt new file mode 100644 index 000000000..d3e400485 --- /dev/null +++ b/extras/tests/IntegrationTests/CMakeLists.txt @@ -0,0 +1,24 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2025, 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/extras/tests/IntegrationTests/gbathree.cpp b/extras/tests/IntegrationTests/gbathree.cpp new file mode 100644 index 000000000..fead9ff08 --- /dev/null +++ b/extras/tests/IntegrationTests/gbathree.cpp @@ -0,0 +1,210 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("Gbathree") { + JsonDocument doc; + + 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/extras/tests/IntegrationTests/issue772.cpp b/extras/tests/IntegrationTests/issue772.cpp new file mode 100644 index 000000000..e81cf40cc --- /dev/null +++ b/extras/tests/IntegrationTests/issue772.cpp @@ -0,0 +1,28 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +// https://github.com/bblanchon/ArduinoJson/issues/772 + +TEST_CASE("Issue772") { + JsonDocument doc1; + JsonDocument doc2; + 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/extras/tests/IntegrationTests/openweathermap.cpp b/extras/tests/IntegrationTests/openweathermap.cpp new file mode 100644 index 000000000..34dbba25f --- /dev/null +++ b/extras/tests/IntegrationTests/openweathermap.cpp @@ -0,0 +1,68 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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 + + JsonDocument filter; + filter["list"][0]["dt"] = true; + filter["list"][0]["main"]["temp"] = true; + filter["list"][0]["weather"][0]["description"] = true; + + JsonDocument doc; + + REQUIRE( + deserializeJson(doc, input_json, DeserializationOption::Filter(filter)) == + DeserializationError::Ok); + + REQUIRE(doc.as() == expected_json); +} diff --git a/test/IntegrationTests.cpp b/extras/tests/IntegrationTests/round_trip.cpp similarity index 72% rename from test/IntegrationTests.cpp rename to extras/tests/IntegrationTests/round_trip.cpp index 4957a882b..54bd6f4a7 100644 --- a/test/IntegrationTests.cpp +++ b/extras/tests/IntegrationTests/round_trip.cpp @@ -1,52 +1,27 @@ -// Copyright Benoit Blanchon 2014-2017 +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON // MIT License -// -// Arduino JSON library -// https://github.com/bblanchon/ArduinoJson -// If you like this project, please add a star! #include -#include +#include -class IntegrationTests : public testing::TestWithParam { - static const size_t MAX_JSON_SIZE = 10000; +void check(std::string originalJson) { + JsonDocument doc; - protected: - virtual void SetUp() { - _input = GetParam(); - strcpy(_inputBuffer, _input); - } - - void parseThenPrint(char* input, char* output) { - DynamicJsonBuffer buffer; - buffer.parseObject(input).printTo(output, MAX_JSON_SIZE); - } - - void parseThenPrettyPrint(char* input, char* output) { - DynamicJsonBuffer buffer; - buffer.parseObject(input).prettyPrintTo(output, MAX_JSON_SIZE); - } + std::string prettyJson; + deserializeJson(doc, originalJson); + serializeJsonPretty(doc, prettyJson); - const char* _input; - char _inputBuffer[MAX_JSON_SIZE]; - char _outputBuffer[MAX_JSON_SIZE]; - char _intermediateBuffer[MAX_JSON_SIZE]; -}; + std::string finalJson; + deserializeJson(doc, originalJson); + serializeJson(doc, finalJson); -TEST_P(IntegrationTests, ParseThenPrint) { - parseThenPrint(_inputBuffer, _outputBuffer); - ASSERT_STREQ(_input, _outputBuffer); + REQUIRE(originalJson == finalJson); } -TEST_P(IntegrationTests, ParseThenPrettyPrintThenParseThenPrint) { - parseThenPrettyPrint(_inputBuffer, _intermediateBuffer); - parseThenPrint(_intermediateBuffer, _outputBuffer); - ASSERT_STREQ(_input, _outputBuffer); -} - -INSTANTIATE_TEST_CASE_P( - OpenWeatherMap, IntegrationTests, - testing::Values( +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\"," @@ -54,11 +29,11 @@ INSTANTIATE_TEST_CASE_P( "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}")); + "2172797,\"name\":\"Cairns\",\"cod\":200}"); + } -INSTANTIATE_TEST_CASE_P( - YahooQueryLanguage, IntegrationTests, - testing::Values( + 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 " @@ -102,4 +77,6 @@ INSTANTIATE_TEST_CASE_P( "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\"}]}}}")); + "poaching\"}]}}}"); + } +} diff --git a/extras/tests/JsonArray/CMakeLists.txt b/extras/tests/JsonArray/CMakeLists.txt new file mode 100644 index 000000000..0b8a56239 --- /dev/null +++ b/extras/tests/JsonArray/CMakeLists.txt @@ -0,0 +1,25 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2025, Benoit BLANCHON +# MIT License + +add_executable(JsonArrayTests + add.cpp + clear.cpp + compare.cpp + copyArray.cpp + equals.cpp + isNull.cpp + iterator.cpp + nesting.cpp + remove.cpp + size.cpp + subscript.cpp + unbound.cpp +) + +add_test(JsonArray JsonArrayTests) + +set_tests_properties(JsonArray + PROPERTIES + LABELS "Catch" +) diff --git a/extras/tests/JsonArray/add.cpp b/extras/tests/JsonArray/add.cpp new file mode 100644 index 000000000..0983e3bde --- /dev/null +++ b/extras/tests/JsonArray/add.cpp @@ -0,0 +1,262 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +using ArduinoJson::detail::sizeofArray; + +TEST_CASE("JsonArray::add(T)") { + SpyingAllocator spy; + JsonDocument doc(&spy); + JsonArray array = doc.to(); + + SECTION("int") { + array.add(123); + + REQUIRE(123 == array[0].as()); + REQUIRE(array[0].is()); + REQUIRE(array[0].is()); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + }); + } + + SECTION("double") { + array.add(123.45); + + REQUIRE(123.45 == array[0].as()); + REQUIRE(array[0].is()); + REQUIRE_FALSE(array[0].is()); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + }); + } + + SECTION("bool") { + array.add(true); + + REQUIRE(array[0].as() == true); + REQUIRE(array[0].is()); + REQUIRE_FALSE(array[0].is()); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + }); + } + + SECTION("string literal") { + array.add("hello"); + + REQUIRE(array[0].as() == "hello"); + REQUIRE(array[0].is()); + REQUIRE(array[0].is() == false); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + }); + } + + SECTION("std::string") { + array.add("hello"_s); + + REQUIRE(array[0].as() == "hello"); + REQUIRE(array[0].is() == true); + REQUIRE(array[0].is() == false); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("hello")), + }); + } + + SECTION("const char*") { + const char* str = "hello"; + array.add(str); + + REQUIRE(array[0].as() == "hello"); + REQUIRE(array[0].as() != str); + REQUIRE(array[0].is() == true); + REQUIRE(array[0].is() == false); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("hello")), + }); + } + + SECTION("serialized(const char*)") { + array.add(serialized("{}")); + + REQUIRE(doc.as() == "[{}]"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("{}")), + }); + } + + SECTION("serialized(char*)") { + array.add(serialized(const_cast("{}"))); + + REQUIRE(doc.as() == "[{}]"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("{}")), + }); + } + + SECTION("serialized(std::string)") { + array.add(serialized("{}"_s)); + + REQUIRE(doc.as() == "[{}]"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("{}")), + }); + } + + SECTION("serialized(std::string)") { + array.add(serialized("\0XX"_s)); + + REQUIRE(doc.as() == "[\0XX]"_s); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString(" XX")), + }); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("vla") { + size_t i = 16; + char vla[i]; + strcpy(vla, "world"); + + array.add(vla); + + strcpy(vla, "hello"); + REQUIRE(array[0] == "world"_s); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("hello")), + }); + } +#endif + + SECTION("nested array") { + JsonDocument doc2; + JsonArray arr = doc2.to(); + + array.add(arr); + + REQUIRE(arr == array[0].as()); + REQUIRE(array[0].is()); + REQUIRE_FALSE(array[0].is()); + } + + SECTION("nested object") { + JsonDocument doc2; + 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"; + JsonDocument doc2; + JsonArray arr = doc2.to(); + arr.add(str); + + array.add(arr[0]); + + REQUIRE(str == array[0]); + } + + SECTION("object subscript") { + const char* str = "hello"; + JsonDocument doc2; + JsonObject obj = doc2.to(); + obj["x"] = str; + + array.add(obj["x"]); + + REQUIRE(str == array[0]); + } +} + +TEST_CASE("JsonArray::add()") { + JsonDocument doc; + JsonArray array = doc.to(); + + SECTION("add()") { + JsonArray nestedArray = array.add(); + nestedArray.add(1); + nestedArray.add(2); + REQUIRE(doc.as() == "[[1,2]]"); + } + + SECTION("add()") { + JsonObject nestedObject = array.add(); + nestedObject["a"] = 1; + nestedObject["b"] = 2; + REQUIRE(doc.as() == "[{\"a\":1,\"b\":2}]"); + } + + SECTION("add()") { + JsonVariant nestedVariant = array.add(); + nestedVariant.set(42); + REQUIRE(doc.as() == "[42]"); + } +} + +TEST_CASE("JsonObject::add(JsonObject) ") { + JsonDocument doc1; + doc1["key1"_s] = "value1"_s; + + TimebombAllocator allocator(10); + SpyingAllocator spy(&allocator); + JsonDocument doc2(&spy); + JsonArray array = doc2.to(); + + SECTION("success") { + bool result = array.add(doc1.as()); + + REQUIRE(result == true); + REQUIRE(doc2.as() == "[{\"key1\":\"value1\"}]"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("key1")), + Allocate(sizeofString("value1")), + }); + } + + SECTION("partial failure") { // issue #2081 + allocator.setCountdown(2); + + bool result = array.add(doc1.as()); + + REQUIRE(result == false); + REQUIRE(doc2.as() == "[]"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("key1")), + AllocateFail(sizeofString("value1")), + Deallocate(sizeofString("key1")), + }); + } + + SECTION("complete failure") { + allocator.setCountdown(0); + + bool result = array.add(doc1.as()); + + REQUIRE(result == false); + REQUIRE(doc2.as() == "[]"); + REQUIRE(spy.log() == AllocatorLog{ + AllocateFail(sizeofPool()), + }); + } +} diff --git a/extras/tests/JsonArray/clear.cpp b/extras/tests/JsonArray/clear.cpp new file mode 100644 index 000000000..069376de5 --- /dev/null +++ b/extras/tests/JsonArray/clear.cpp @@ -0,0 +1,46 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Allocators.hpp" + +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") { + JsonDocument doc; + JsonArray array = doc.to(); + array.add(1); + array.add(2); + array.clear(); + REQUIRE(array.size() == 0); + REQUIRE(array.isNull() == false); + } + + SECTION("Removed elements are recycled") { + SpyingAllocator spy; + JsonDocument doc(&spy); + JsonArray array = doc.to(); + + // fill the pool entirely + for (int i = 0; i < ARDUINOJSON_POOL_CAPACITY; i++) + array.add(i); + + // clear and fill again + array.clear(); + for (int i = 0; i < ARDUINOJSON_POOL_CAPACITY; i++) + array.add(i); + + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + }); + } +} diff --git a/extras/tests/JsonArray/compare.cpp b/extras/tests/JsonArray/compare.cpp new file mode 100644 index 000000000..23f2ea9dc --- /dev/null +++ b/extras/tests/JsonArray/compare.cpp @@ -0,0 +1,512 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("Compare JsonArray with JsonArray") { + JsonDocument 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.add(); + array1.add(1); + array1.add("hello"); + array1.add(); + + JsonArray array2 = doc.add(); + array2.add(1); + array2.add("hello"); + array2.add(); + + 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.add(); + array1.add(1); + array1.add("hello1"); + array1.add(); + + JsonArray array2 = doc.add(); + array2.add(1); + array2.add("hello2"); + array2.add(); + + 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") { + JsonDocument 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.add(); + array.add(1); + array.add("hello"); + array.add(); + + JsonVariant variant = doc.add(); + variant.add(1); + variant.add("hello"); + variant.add(); + + 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.add(); + array.add(1); + array.add("hello1"); + array.add(); + + JsonVariant variant = doc.add(); + variant.add(1); + variant.add("hello2"); + variant.add(); + + 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") { + JsonDocument 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.add(); + array.add(1); + array.add("hello"); + array.add(); + + JsonArray array2 = doc.add(); + array2.add(1); + array2.add("hello"); + array2.add(); + 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.add(); + array.add(1); + array.add("hello1"); + array.add(); + + JsonArray array2 = doc.add(); + array2.add(1); + array2.add("hello2"); + array2.add(); + 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") { + JsonDocument 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.add(); + array1.add(1); + array1.add("hello"); + array1.add(); + + JsonArray array2 = doc.add(); + array2.add(1); + array2.add("hello"); + array2.add(); + 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.add(); + array1.add(1); + array1.add("hello1"); + array1.add(); + + JsonArray array2 = doc.add(); + array2.add(1); + array2.add("hello2"); + array2.add(); + 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") { + JsonDocument 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.add(); + array1.add(1); + array1.add("hello"); + array1.add(); + JsonArrayConst carray1 = array1; + + JsonArray array2 = doc.add(); + array2.add(1); + array2.add("hello"); + array2.add(); + 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.add(); + array1.add(1); + array1.add("hello1"); + array1.add(); + JsonArrayConst carray1 = array1; + + JsonArray array2 = doc.add(); + array2.add(1); + array2.add("hello2"); + array2.add(); + 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") { + JsonDocument 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.add(); + array1.add(1); + array1.add("hello"); + array1.add(); + JsonArrayConst carray1 = array1; + + JsonArray array2 = doc.add(); + array2.add(1); + array2.add("hello"); + array2.add(); + 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.add(); + array1.add(1); + array1.add("hello1"); + array1.add(); + JsonArrayConst carray1 = array1; + + JsonArray array2 = doc.add(); + array2.add(1); + array2.add("hello2"); + array2.add(); + 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/extras/tests/JsonArray/copyArray.cpp b/extras/tests/JsonArray/copyArray.cpp new file mode 100644 index 000000000..dd31cf646 --- /dev/null +++ b/extras/tests/JsonArray/copyArray.cpp @@ -0,0 +1,335 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +TEST_CASE("copyArray()") { + SECTION("int[] -> JsonArray") { + JsonDocument doc; + JsonArray array = doc.to(); + char json[32]; + int source[] = {1, 2, 3}; + + bool ok = copyArray(source, array); + CHECK(ok); + + serializeJson(array, json); + CHECK("[1,2,3]"_s == json); + } + + SECTION("std::string[] -> JsonArray") { + JsonDocument doc; + JsonArray array = doc.to(); + char json[32]; + std::string source[] = {"a", "b", "c"}; + + bool ok = copyArray(source, array); + CHECK(ok); + + serializeJson(array, json); + CHECK("[\"a\",\"b\",\"c\"]"_s == json); + } + + SECTION("const char*[] -> JsonArray") { + JsonDocument doc; + JsonArray array = doc.to(); + char json[32]; + const char* source[] = {"a", "b", "c"}; + + bool ok = copyArray(source, array); + CHECK(ok); + + serializeJson(array, json); + CHECK("[\"a\",\"b\",\"c\"]"_s == json); + } + + SECTION("const char[][] -> JsonArray") { + JsonDocument doc; + JsonArray array = doc.to(); + char json[32]; + char source[][2] = {"a", "b", "c"}; + + bool ok = copyArray(source, array); + CHECK(ok); + + serializeJson(array, json); + CHECK("[\"a\",\"b\",\"c\"]"_s == json); + } + + SECTION("const char[][] -> JsonDocument") { + JsonDocument doc; + char json[32]; + char source[][2] = {"a", "b", "c"}; + + bool ok = copyArray(source, doc); + CHECK(ok); + + serializeJson(doc, json); + CHECK("[\"a\",\"b\",\"c\"]"_s == json); + } + + SECTION("const char[][] -> MemberProxy") { + JsonDocument doc; + char json[32]; + char source[][2] = {"a", "b", "c"}; + + bool ok = copyArray(source, doc["data"]); + CHECK(ok); + + serializeJson(doc, json); + CHECK("{\"data\":[\"a\",\"b\",\"c\"]}"_s == json); + } + + SECTION("int[] -> JsonDocument") { + JsonDocument doc; + char json[32]; + int source[] = {1, 2, 3}; + + bool ok = copyArray(source, doc); + CHECK(ok); + + serializeJson(doc, json); + CHECK("[1,2,3]"_s == json); + } + + SECTION("int[] -> MemberProxy") { + JsonDocument doc; + char json[32]; + int source[] = {1, 2, 3}; + + bool ok = copyArray(source, doc["data"]); + CHECK(ok); + + serializeJson(doc, json); + CHECK("{\"data\":[1,2,3]}"_s == json); + } + + SECTION("int[] -> JsonArray, but not enough memory") { + JsonDocument doc(FailingAllocator::instance()); + JsonArray array = doc.to(); + int source[] = {1, 2, 3}; + + bool ok = copyArray(source, array); + REQUIRE_FALSE(ok); + } + + SECTION("int[][] -> JsonArray") { + JsonDocument doc; + 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("[[1,2,3],[4,5,6]]"_s == json); + } + + SECTION("int[][] -> MemberProxy") { + JsonDocument doc; + char json[32]; + int source[][3] = {{1, 2, 3}, {4, 5, 6}}; + + bool ok = copyArray(source, doc["data"]); + CHECK(ok); + + serializeJson(doc, json); + CHECK("{\"data\":[[1,2,3],[4,5,6]]}"_s == json); + } + + SECTION("int[][] -> JsonDocument") { + JsonDocument doc; + char json[32]; + int source[][3] = {{1, 2, 3}, {4, 5, 6}}; + + bool ok = copyArray(source, doc); + CHECK(ok); + + serializeJson(doc, json); + CHECK("[[1,2,3],[4,5,6]]"_s == json); + } + + SECTION("int[][] -> JsonArray, but not enough memory") { + JsonDocument doc(FailingAllocator::instance()); + JsonArray array = doc.to(); + int source[][3] = {{1, 2, 3}, {4, 5, 6}}; + + bool ok = copyArray(source, array); + REQUIRE(ok == false); + } + + SECTION("JsonArray -> int[], with more space than needed") { + JsonDocument doc; + 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") { + JsonDocument doc; + 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[]") { + JsonDocument doc; + 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][]") { + JsonDocument doc; + 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("a12345"_s == destination[0]); + CHECK("b123456"_s == destination[1]); + CHECK("c123456"_s == destination[2]); // truncated + CHECK(std::string("") == destination[3]); + } + + SECTION("JsonDocument -> int[]") { + JsonDocument doc; + 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[]") { + JsonDocument doc; + 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[]") { + JsonDocument doc; + 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[][]") { + JsonDocument doc; + 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[][]") { + JsonDocument doc; + 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[][]") { + JsonDocument doc; + 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/extras/tests/JsonArray/equals.cpp b/extras/tests/JsonArray/equals.cpp new file mode 100644 index 000000000..241aa7194 --- /dev/null +++ b/extras/tests/JsonArray/equals.cpp @@ -0,0 +1,63 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonArray::operator==()") { + JsonDocument doc1; + JsonArray array1 = doc1.to(); + + JsonDocument doc2; + JsonArray array2 = doc2.to(); + + SECTION("should return false when arrays differ") { + array1.add("coucou"); + array2.add(1); + + REQUIRE_FALSE(array1 == array2); + } + + SECTION("should return false when LHS has more elements") { + array1.add(1); + array1.add(2); + array2.add(1); + + REQUIRE_FALSE(array1 == array2); + } + + SECTION("should return false when RHS has more elements") { + array1.add(1); + array2.add(1); + array2.add(2); + + REQUIRE_FALSE(array1 == array2); + } + + SECTION("should return true when arrays equal") { + array1.add("coucou"); + array2.add("coucou"); + + REQUIRE(array1 == array2); + } + + 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/extras/tests/JsonArray/isNull.cpp b/extras/tests/JsonArray/isNull.cpp new file mode 100644 index 000000000..77f15125f --- /dev/null +++ b/extras/tests/JsonArray/isNull.cpp @@ -0,0 +1,32 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonArray::isNull()") { + SECTION("returns true") { + JsonArray arr; + REQUIRE(arr.isNull() == true); + } + + SECTION("returns false") { + JsonDocument doc; + JsonArray 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") { + JsonDocument doc; + JsonArray arr = doc.to(); + REQUIRE(static_cast(arr) == true); + } +} diff --git a/extras/tests/JsonArray/iterator.cpp b/extras/tests/JsonArray/iterator.cpp new file mode 100644 index 000000000..f6bb3ef99 --- /dev/null +++ b/extras/tests/JsonArray/iterator.cpp @@ -0,0 +1,34 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonArray::begin()/end()") { + SECTION("Non null JsonArray") { + JsonDocument doc; + JsonArray array = doc.to(); + array.add(12); + array.add(34); + + auto it = array.begin(); + auto end = array.end(); + + REQUIRE(end != it); + REQUIRE(12 == it->as()); + REQUIRE(12 == static_cast(*it)); + ++it; + REQUIRE(end != it); + REQUIRE(34 == it->as()); + REQUIRE(34 == static_cast(*it)); + ++it; + REQUIRE(end == it); + } + + SECTION("Null JsonArray") { + JsonArray array; + + REQUIRE(array.begin() == array.end()); + } +} diff --git a/extras/tests/JsonArray/nesting.cpp b/extras/tests/JsonArray/nesting.cpp new file mode 100644 index 000000000..434c41851 --- /dev/null +++ b/extras/tests/JsonArray/nesting.cpp @@ -0,0 +1,35 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonArray::nesting()") { + JsonDocument doc; + 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.add(); + REQUIRE(arr.nesting() == 2); + } + + SECTION("returns 2 with nested object") { + arr.add(); + REQUIRE(arr.nesting() == 2); + } +} diff --git a/extras/tests/JsonArray/remove.cpp b/extras/tests/JsonArray/remove.cpp new file mode 100644 index 000000000..86911719f --- /dev/null +++ b/extras/tests/JsonArray/remove.cpp @@ -0,0 +1,126 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Allocators.hpp" + +TEST_CASE("JsonArray::remove()") { + JsonDocument doc; + 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("remove end()") { + array.remove(array.end()); + + REQUIRE(3 == array.size()); + } + + 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()); + } + + SECTION("use JsonVariant as index") { + array.remove(array[3]); // no effect with null variant + array.remove(array[0]); // remove element at index 1 + + REQUIRE(2 == array.size()); + REQUIRE(array[0] == 1); + REQUIRE(array[1] == 3); + } +} + +TEST_CASE("Removed elements are recycled") { + SpyingAllocator spy; + JsonDocument doc(&spy); + JsonArray array = doc.to(); + + // fill the pool entirely + for (int i = 0; i < ARDUINOJSON_POOL_CAPACITY; i++) + array.add(i); + + // free one slot in the pool + array.remove(0); + + // add one element; it should use the free slot + array.add(42); + + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), // only one pool + }); +} diff --git a/extras/tests/JsonArray/size.cpp b/extras/tests/JsonArray/size.cpp new file mode 100644 index 000000000..63bf55dd8 --- /dev/null +++ b/extras/tests/JsonArray/size.cpp @@ -0,0 +1,31 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonArray::size()") { + JsonDocument doc; + 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/extras/tests/JsonArray/subscript.cpp b/extras/tests/JsonArray/subscript.cpp new file mode 100644 index 000000000..fa0400cec --- /dev/null +++ b/extras/tests/JsonArray/subscript.cpp @@ -0,0 +1,171 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +TEST_CASE("JsonArray::operator[]") { + SpyingAllocator spy; + JsonDocument doc(&spy); + 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("string literal") { + array[0] = "hello"; + + REQUIRE(array[0].as() == "hello"); + REQUIRE(true == array[0].is()); + REQUIRE(false == array[0].is()); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("world")), + }); + } + + SECTION("const char*") { + const char* str = "hello"; + array[0] = str; + + REQUIRE(array[0].as() == "hello"); + REQUIRE(true == array[0].is()); + REQUIRE(false == array[0].is()); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("world")), + }); + } + + SECTION("std::string") { + array[0] = "hello"_s; + + REQUIRE(array[0].as() == "hello"); + REQUIRE(true == array[0].is()); + REQUIRE(false == array[0].is()); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("world")), + }); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("VLA") { + size_t i = 16; + char vla[i]; + strcpy(vla, "world"); + + array.add("hello"); + array[0] = vla; + + REQUIRE(array[0] == "world"_s); + } +#endif + + SECTION("nested array") { + JsonDocument doc2; + 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") { + JsonDocument doc2; + 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") { + JsonDocument doc2; + 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"; + JsonDocument doc2; + JsonObject obj = doc2.to(); + + obj["x"] = str; + + array[0] = obj["x"]; + + REQUIRE(str == array[0]); + } + + SECTION("array[0].to()") { + JsonObject obj = array[0].to(); + REQUIRE(obj.isNull() == false); + } + + SECTION("Use a JsonVariant as index") { + array[0] = 1; + array[1] = 2; + array[2] = 3; + + REQUIRE(array[array[1]] == 3); + REQUIRE(array[array[3]] == nullptr); + } +} diff --git a/extras/tests/JsonArray/unbound.cpp b/extras/tests/JsonArray/unbound.cpp new file mode 100644 index 000000000..ba800189e --- /dev/null +++ b/extras/tests/JsonArray/unbound.cpp @@ -0,0 +1,27 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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("PrintToWritesBrackets") { + char buffer[32]; + serializeJson(array, buffer, sizeof(buffer)); + REQUIRE_THAT(buffer, Equals("null")); + } +} diff --git a/extras/tests/JsonArrayConst/CMakeLists.txt b/extras/tests/JsonArrayConst/CMakeLists.txt new file mode 100644 index 000000000..4d69c716c --- /dev/null +++ b/extras/tests/JsonArrayConst/CMakeLists.txt @@ -0,0 +1,19 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2025, Benoit BLANCHON +# MIT License + +add_executable(JsonArrayConstTests + equals.cpp + isNull.cpp + iterator.cpp + nesting.cpp + size.cpp + subscript.cpp +) + +add_test(JsonArrayConst JsonArrayConstTests) + +set_tests_properties(JsonArrayConst + PROPERTIES + LABELS "Catch" +) diff --git a/extras/tests/JsonArrayConst/equals.cpp b/extras/tests/JsonArrayConst/equals.cpp new file mode 100644 index 000000000..de939cc09 --- /dev/null +++ b/extras/tests/JsonArrayConst/equals.cpp @@ -0,0 +1,63 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonArrayConst::operator==()") { + JsonDocument doc1; + JsonArrayConst array1 = doc1.to(); + + JsonDocument doc2; + JsonArrayConst array2 = doc2.to(); + + SECTION("should return false when arrays differ") { + doc1.add("coucou"); + doc2.add(1); + + REQUIRE_FALSE(array1 == array2); + } + + SECTION("should return false when LHS has more elements") { + doc1.add(1); + doc1.add(2); + doc2.add(1); + + REQUIRE_FALSE(array1 == array2); + } + + SECTION("should return false when RHS has more elements") { + doc1.add(1); + doc2.add(1); + doc2.add(2); + + REQUIRE_FALSE(array1 == array2); + } + + SECTION("should return true when arrays equal") { + doc1.add("coucou"); + doc2.add("coucou"); + + REQUIRE(array1 == array2); + } + + SECTION("should return false when RHS is null") { + JsonArrayConst null; + + REQUIRE_FALSE(array1 == null); + } + + SECTION("should return false when LHS is null") { + JsonArrayConst null; + + REQUIRE_FALSE(null == array1); + } + + SECTION("should return true when both are null") { + JsonArrayConst null1; + JsonArrayConst null2; + + REQUIRE(null1 == null2); + } +} diff --git a/extras/tests/JsonArrayConst/isNull.cpp b/extras/tests/JsonArrayConst/isNull.cpp new file mode 100644 index 000000000..d443a73ec --- /dev/null +++ b/extras/tests/JsonArrayConst/isNull.cpp @@ -0,0 +1,32 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonArrayConst::isNull()") { + SECTION("returns true") { + JsonArrayConst arr; + REQUIRE(arr.isNull() == true); + } + + SECTION("returns false") { + JsonDocument doc; + JsonArrayConst arr = doc.to(); + REQUIRE(arr.isNull() == false); + } +} + +TEST_CASE("JsonArrayConst::operator bool()") { + SECTION("returns false") { + JsonArrayConst arr; + REQUIRE(static_cast(arr) == false); + } + + SECTION("returns true") { + JsonDocument doc; + JsonArrayConst arr = doc.to(); + REQUIRE(static_cast(arr) == true); + } +} diff --git a/extras/tests/JsonArrayConst/iterator.cpp b/extras/tests/JsonArrayConst/iterator.cpp new file mode 100644 index 000000000..0907af7e2 --- /dev/null +++ b/extras/tests/JsonArrayConst/iterator.cpp @@ -0,0 +1,34 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonArrayConst::begin()/end()") { + SECTION("Non null JsonArrayConst") { + JsonDocument doc; + JsonArrayConst array = doc.to(); + doc.add(12); + doc.add(34); + + auto it = array.begin(); + auto end = array.end(); + + REQUIRE(end != it); + REQUIRE(12 == it->as()); + REQUIRE(12 == static_cast(*it)); + ++it; + REQUIRE(end != it); + REQUIRE(34 == it->as()); + REQUIRE(34 == static_cast(*it)); + ++it; + REQUIRE(end == it); + } + + SECTION("Null JsonArrayConst") { + JsonArrayConst array; + + REQUIRE(array.begin() == array.end()); + } +} diff --git a/extras/tests/JsonArrayConst/nesting.cpp b/extras/tests/JsonArrayConst/nesting.cpp new file mode 100644 index 000000000..547d5d4b8 --- /dev/null +++ b/extras/tests/JsonArrayConst/nesting.cpp @@ -0,0 +1,35 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonArrayConst::nesting()") { + JsonDocument doc; + JsonArrayConst arr = doc.to(); + + SECTION("return 0 if unbound") { + JsonArrayConst unbound; + REQUIRE(unbound.nesting() == 0); + } + + SECTION("returns 1 for empty array") { + REQUIRE(arr.nesting() == 1); + } + + SECTION("returns 1 for flat array") { + doc.add("hello"); + REQUIRE(arr.nesting() == 1); + } + + SECTION("returns 2 with nested array") { + doc.add(); + REQUIRE(arr.nesting() == 2); + } + + SECTION("returns 2 with nested object") { + doc.add(); + REQUIRE(arr.nesting() == 2); + } +} diff --git a/extras/tests/JsonArrayConst/size.cpp b/extras/tests/JsonArrayConst/size.cpp new file mode 100644 index 000000000..4bf000ffb --- /dev/null +++ b/extras/tests/JsonArrayConst/size.cpp @@ -0,0 +1,27 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonArrayConst::size()") { + JsonDocument doc; + JsonArrayConst array = doc.to(); + + SECTION("returns 0 if unbound") { + JsonArrayConst unbound; + REQUIRE(0U == unbound.size()); + } + + SECTION("returns 0 is empty") { + REQUIRE(0U == array.size()); + } + + SECTION("return number of elements") { + doc.add("hello"); + doc.add("world"); + + REQUIRE(2U == array.size()); + } +} diff --git a/extras/tests/JsonArrayConst/subscript.cpp b/extras/tests/JsonArrayConst/subscript.cpp new file mode 100644 index 000000000..907cf319a --- /dev/null +++ b/extras/tests/JsonArrayConst/subscript.cpp @@ -0,0 +1,27 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include +#include + +TEST_CASE("JsonArrayConst::operator[]") { + JsonDocument doc; + JsonArrayConst arr = doc.to(); + doc.add(1); + doc.add(2); + doc.add(3); + + SECTION("int") { + REQUIRE(1 == arr[0].as()); + REQUIRE(2 == arr[1].as()); + REQUIRE(3 == arr[2].as()); + REQUIRE(0 == arr[3].as()); + } + + SECTION("JsonVariant") { + REQUIRE(2 == arr[arr[0]].as()); + REQUIRE(0 == arr[arr[3]].as()); + } +} diff --git a/extras/tests/JsonDeserializer/CMakeLists.txt b/extras/tests/JsonDeserializer/CMakeLists.txt new file mode 100644 index 000000000..6faaaa867 --- /dev/null +++ b/extras/tests/JsonDeserializer/CMakeLists.txt @@ -0,0 +1,26 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2025, Benoit BLANCHON +# MIT License + +add_executable(JsonDeserializerTests + array.cpp + DeserializationError.cpp + destination_types.cpp + errors.cpp + filter.cpp + input_types.cpp + misc.cpp + nestingLimit.cpp + number.cpp + object.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/extras/tests/JsonDeserializer/DeserializationError.cpp b/extras/tests/JsonDeserializer/DeserializationError.cpp new file mode 100644 index 000000000..edfcd3a8b --- /dev/null +++ b/extras/tests/JsonDeserializer/DeserializationError.cpp @@ -0,0 +1,122 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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/extras/tests/JsonDeserializer/array.cpp b/extras/tests/JsonDeserializer/array.cpp new file mode 100644 index 000000000..e6fb18d51 --- /dev/null +++ b/extras/tests/JsonDeserializer/array.cpp @@ -0,0 +1,337 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Allocators.hpp" + +using ArduinoJson::detail::sizeofArray; + +TEST_CASE("deserialize JSON array") { + SpyingAllocator spy; + JsonDocument doc(&spy); + + 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("Float") { + DeserializationError err = deserializeJson(doc, "[4.2,1e2]"); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(2 == arr.size()); + REQUIRE(arr[0].as() == Approx(4.2f)); + REQUIRE(arr[1] == 1e2f); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofPool(2)), + }); + } + + SECTION("Double") { + DeserializationError err = deserializeJson(doc, "[4.2123456,-7E89]"); + JsonArray arr = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(2 == arr.size()); + REQUIRE(arr[0].as() == Approx(4.2123456)); + REQUIRE(arr[1] == -7E89); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofPool(4)), + }); + } + + 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]"); + spy.clearLog(); + + deserializeJson(doc, "[]"); + + JsonArray arr = doc.as(); + REQUIRE(arr.size() == 0); + REQUIRE(spy.log() == AllocatorLog{ + Deallocate(sizeofArray(4)), + }); + } +} + +TEST_CASE("deserialize JSON array under memory constraints") { + TimebombAllocator timebomb(100); + SpyingAllocator spy(&timebomb); + JsonDocument doc(&spy); + + SECTION("empty array requires no allocation") { + timebomb.setCountdown(0); + char input[] = "[]"; + + DeserializationError err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("allocation of pool list fails") { + timebomb.setCountdown(0); + char input[] = "[1]"; + + DeserializationError err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::NoMemory); + REQUIRE(doc.as() == "[]"); + } + + SECTION("allocation of pool fails") { + timebomb.setCountdown(0); + char input[] = "[1]"; + + DeserializationError err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::NoMemory); + REQUIRE(doc.as() == "[]"); + } + + SECTION("allocation of string fails in array") { + timebomb.setCountdown(1); + char input[] = "[0,\"hi!\"]"; + + DeserializationError err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::NoMemory); + REQUIRE(doc.as() == "[0,null]"); + } + + SECTION("don't store space characters") { + deserializeJson(doc, " [ \"1234567\" ] "); + + REQUIRE(spy.log() == + AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofStringBuffer()), + Reallocate(sizeofStringBuffer(), sizeofString("1234567")), + Reallocate(sizeofPool(), sizeofArray(1)), + }); + } +} diff --git a/extras/tests/JsonDeserializer/destination_types.cpp b/extras/tests/JsonDeserializer/destination_types.cpp new file mode 100644 index 000000000..0f96b23ef --- /dev/null +++ b/extras/tests/JsonDeserializer/destination_types.cpp @@ -0,0 +1,109 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include + +#include +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +using ArduinoJson::detail::sizeofArray; +using ArduinoJson::detail::sizeofObject; + +TEST_CASE("deserializeJson(JsonDocument&)") { + SpyingAllocator spy; + JsonDocument doc(&spy); + doc.add("hello"_s); + spy.clearLog(); + + auto err = deserializeJson(doc, "[42]"); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.as() == "[42]"); + REQUIRE(spy.log() == AllocatorLog{ + Deallocate(sizeofPool()), + Deallocate(sizeofString("hello")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofArray(1)), + }); +} + +TEST_CASE("deserializeJson(JsonVariant)") { + SECTION("variant is bound") { + SpyingAllocator spy; + JsonDocument doc(&spy); + doc.add("hello"_s); + spy.clearLog(); + + JsonVariant variant = doc[0]; + + auto err = deserializeJson(variant, "[42]"); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.as() == "[[42]]"); + REQUIRE(spy.log() == AllocatorLog{ + Deallocate(sizeofString("hello")), + }); + } + + SECTION("variant is unbound") { + JsonVariant variant; + + auto err = deserializeJson(variant, "[42]"); + + REQUIRE(err == DeserializationError::NoMemory); + } +} + +TEST_CASE("deserializeJson(ElementProxy)") { + SpyingAllocator spy; + JsonDocument doc(&spy); + doc.add("hello"_s); + spy.clearLog(); + + SECTION("element already exists") { + auto err = deserializeJson(doc[0], "[42]"); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.as() == "[[42]]"); + REQUIRE(spy.log() == AllocatorLog{ + Deallocate(sizeofString("hello")), + }); + } + + SECTION("element must be created") { + auto err = deserializeJson(doc[1], "[42]"); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.as() == "[\"hello\",[42]]"); + REQUIRE(spy.log() == AllocatorLog{}); + } +} + +TEST_CASE("deserializeJson(MemberProxy)") { + SpyingAllocator spy; + JsonDocument doc(&spy); + doc["hello"_s] = "world"_s; + spy.clearLog(); + + SECTION("member already exists") { + auto err = deserializeJson(doc["hello"], "[42]"); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.as() == "{\"hello\":[42]}"); + REQUIRE(spy.log() == AllocatorLog{ + Deallocate(sizeofString("world")), + }); + } + + SECTION("member must be created exists") { + auto err = deserializeJson(doc["value"], "[42]"); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.as() == "{\"hello\":\"world\",\"value\":[42]}"); + REQUIRE(spy.log() == AllocatorLog{}); + } +} diff --git a/extras/tests/JsonDeserializer/errors.cpp b/extras/tests/JsonDeserializer/errors.cpp new file mode 100644 index 000000000..35d3ca399 --- /dev/null +++ b/extras/tests/JsonDeserializer/errors.cpp @@ -0,0 +1,162 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#define ARDUINOJSON_DECODE_UNICODE 1 +#include +#include + +#include "Allocators.hpp" + +TEST_CASE("deserializeJson() returns IncompleteInput") { + const char* testCases[] = { + // strings + "\"\\", + "\"hello", + "\'hello", + // unicode + "'\\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,b", + "{a:1,b:", + }; + + for (auto input : testCases) { + SECTION(input) { + JsonDocument doc; + REQUIRE(deserializeJson(doc, input) == + DeserializationError::IncompleteInput); + } + } +} + +TEST_CASE("deserializeJson() returns InvalidInput") { + const char* testCases[] = { + // unicode + "'\\u'", "'\\u000g'", "'\\u000'", "'\\u000G'", "'\\u000/'", "\\x1234", + // numbers + "6a9", "1,", "2]", "3}", + // constants + "nulL", "tru3", "fals3", + // garbage + "%*$£¤"}; + + for (auto input : testCases) { + SECTION(input) { + JsonDocument doc; + REQUIRE(deserializeJson(doc, input) == + DeserializationError::InvalidInput); + } + } +} + +TEST_CASE("deserializeJson() oversees some edge cases") { + const char* testCases[] = { + "'\\ud83d'", // leading surrogate without a trailing surrogate + "'\\udda4'", // trailing surrogate without a leading surrogate + "'\\ud83d\\ud83d'", // two leading surrogates + }; + + for (auto input : testCases) { + SECTION(input) { + JsonDocument doc; + REQUIRE(deserializeJson(doc, input) == DeserializationError::Ok); + } + } +} + +TEST_CASE("deserializeJson() returns EmptyInput") { + JsonDocument doc; + + SECTION("null") { + auto err = deserializeJson(doc, static_cast(0)); + REQUIRE(err == DeserializationError::EmptyInput); + } + + SECTION("Empty string") { + auto err = deserializeJson(doc, ""); + REQUIRE(err == DeserializationError::EmptyInput); + } + + SECTION("Only spaces") { + auto err = deserializeJson(doc, " \t\n\r"); + REQUIRE(err == DeserializationError::EmptyInput); + } +} + +TEST_CASE("deserializeJson() returns NoMemory if string length overflows") { + JsonDocument doc; + auto maxLength = ArduinoJson::detail::StringNode::maxLength; + + SECTION("max length should succeed") { + auto err = deserializeJson(doc, "\"" + std::string(maxLength, 'a') + "\""); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("one above max length should fail") { + auto err = + deserializeJson(doc, "\"" + std::string(maxLength + 1, 'a') + "\""); + REQUIRE(err == DeserializationError::NoMemory); + } +} + +TEST_CASE("deserializeJson() returns NoMemory if extension allocation fails") { + JsonDocument doc(FailingAllocator::instance()); + + SECTION("uint32_t should pass") { + auto err = deserializeJson(doc, "4294967295"); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("uint64_t should fail") { + auto err = deserializeJson(doc, "18446744073709551615"); + + REQUIRE(err == DeserializationError::NoMemory); + } + + SECTION("int32_t should pass") { + auto err = deserializeJson(doc, "-2147483648"); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("int64_t should fail") { + auto err = deserializeJson(doc, "-9223372036854775808"); + + REQUIRE(err == DeserializationError::NoMemory); + } + + SECTION("float should pass") { + auto err = deserializeJson(doc, "3.402823e38"); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("double should fail") { + auto err = deserializeJson(doc, "1.7976931348623157e308"); + + REQUIRE(err == DeserializationError::NoMemory); + } +} diff --git a/extras/tests/JsonDeserializer/filter.cpp b/extras/tests/JsonDeserializer/filter.cpp new file mode 100644 index 000000000..4f9d9b9bf --- /dev/null +++ b/extras/tests/JsonDeserializer/filter.cpp @@ -0,0 +1,831 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#define ARDUINOJSON_ENABLE_COMMENTS 1 +#include +#include + +#include +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +using ArduinoJson::detail::sizeofArray; +using ArduinoJson::detail::sizeofObject; + +TEST_CASE("Filtering") { + struct TestCase { + const char* description; + const char* input; + const char* filter; + uint8_t nestingLimit; + DeserializationError error; + const char* output; + size_t memoryUsage; + }; + + TestCase testCases[] = { + { + "Input is object, filter is null", // description + "{\"hello\":\"world\"}", // input + "null", // filter + 10, // nestingLimit + DeserializationError::Ok, // error + "null", // output + 0, // memoryUsage + }, + { + "Input is object, filter is false", + "{\"hello\":\"world\"}", + "false", + 10, + DeserializationError::Ok, + "null", + 0, + }, + { + "Input is object, filter is true", + "{\"abcdefg\":\"hijklmn\"}", + "true", + 10, + DeserializationError::Ok, + "{\"abcdefg\":\"hijklmn\"}", + sizeofObject(1) + sizeofString("abcdefg") + sizeofString("hijklmn"), + }, + { + "Input is object, filter is empty object", + "{\"hello\":\"world\"}", + "{}", + 10, + DeserializationError::Ok, + "{}", + sizeofObject(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}", + sizeofObject(1) + sizeofString("example"), + }, + { + "Member is a number, but filter wants an array", + "{\"example\":42}", + "{\"example\":[true]}", + 10, + DeserializationError::Ok, + "{\"example\":null}", + sizeofObject(1) + sizeofString("example"), + }, + { + "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}", + sizeofObject(1) + sizeofString("example"), + }, + { + "Skip a float", + "{\"a_float\":12.34e-6,example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + sizeofObject(1) + sizeofString("example"), + }, + { + "Skip false", + "{\"a_bool\":false,example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + sizeofObject(1) + sizeofString("example"), + }, + { + "Skip true", + "{\"a_bool\":true,example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + sizeofObject(1) + sizeofString("example"), + }, + { + "Skip null", + "{\"a_bool\":null,example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + sizeofObject(1) + sizeofString("example"), + }, + { + "Skip a double-quoted string", + "{\"a_double_quoted_string\":\"hello\",example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + sizeofObject(1) + sizeofString("example"), + }, + { + "Skip a single-quoted string", + "{\"a_single_quoted_string\":'hello',example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + sizeofObject(1) + sizeofString("example"), + }, + { + "Skip an empty array", + "{\"an_empty_array\":[],example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + sizeofObject(1) + sizeofString("example"), + }, + { + "Skip an empty array with spaces in it", + "{\"an_empty_array\":[\t],example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + sizeofObject(1) + sizeofString("example"), + }, + { + "Skip an array", + "{\"an_array\":[1,2,3],example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + sizeofObject(1) + sizeofString("example"), + }, + { + "Skip an array with spaces in it", + "{\"an_array\": [ 1 , 2 , 3 ] ,example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + sizeofObject(1) + sizeofString("example"), + }, + { + "Skip an empty nested object", + "{\"an_empty_object\":{},example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + sizeofObject(1) + sizeofString("example"), + }, + { + "Skip an empty nested object with spaces in it", + "{\"an_empty_object\":{ },example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + sizeofObject(1) + sizeofString("example"), + }, + { + "Skip a nested object", + "{\"an_object\":{a:1,'b':2,\"c\":3},example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + sizeofObject(1) + sizeofString("example"), + }, + { + "Skip an object with spaces in it", + "{\"an_object\" : { a : 1 , 'b' : 2 , \"c\" : 3 } ,example:42}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{\"example\":42}", + sizeofObject(1) + sizeofString("example"), + }, + { + "Skip a string in a nested object", + "{\"an_integer\": 0,\"example\":{\"type\":\"int\",\"outcome\":42}}", + "{\"example\":{\"outcome\":true}}", + 10, + DeserializationError::Ok, + "{\"example\":{\"outcome\":42}}", + 2 * sizeofObject(1) + 2 * sizeofString("example"), + }, + { + "wildcard", + "{\"example\":{\"type\":\"int\",\"outcome\":42}}", + "{\"*\":{\"outcome\":true}}", + 10, + DeserializationError::Ok, + "{\"example\":{\"outcome\":42}}", + 2 * sizeofObject(1) + 2 * sizeofString("example"), + }, + { + "exclusion filter (issue #1628)", + "{\"example\":1,\"ignored\":2}", + "{\"*\":true,\"ignored\":false}", + 10, + DeserializationError::Ok, + "{\"example\":1}", + sizeofObject(1) + sizeofString("example"), + }, + { + "only the first element of array counts", + "[1,2,3]", + "[true, false]", + 10, + DeserializationError::Ok, + "[1,2,3]", + sizeofArray(3), + }, + { + "only the first element of array counts", + "[1,2,3]", + "[false, true]", + 10, + DeserializationError::Ok, + "[]", + sizeofArray(0), + }, + { + "filter members of object in array", + "[{\"example\":1,\"ignore\":2},{\"example\":3,\"ignore\":4}]", + "[{\"example\":true}]", + 10, + DeserializationError::Ok, + "[{\"example\":1},{\"example\":3}]", + sizeofArray(2) + 2 * sizeofObject(1) + sizeofString("example"), + }, + { + "Unclosed single quote in skipped element", + "[',2,3]", + "[false,true]", + 10, + DeserializationError::IncompleteInput, + "[]", + sizeofArray(0), + }, + { + "Unclosed double quote in skipped element", + "[\",2,3]", + "[false,true]", + 10, + DeserializationError::IncompleteInput, + "[]", + sizeofArray(0), + }, + { + "Detect errors in skipped value", + "[!,2,\\]", + "[false]", + 10, + DeserializationError::InvalidInput, + "[]", + sizeofArray(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, + "{}", + sizeofObject(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, + "[]", + sizeofArray(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, + "[]", + sizeofArray(0), + }, + { + "Incomplete comment at the begining of an array", + "[/*]", + "[false]", + 10, + DeserializationError::IncompleteInput, + "[]", + sizeofArray(0), + }, + { + "Invalid comment before key", + "{/1:2}", + "{}", + 10, + DeserializationError::InvalidInput, + "{}", + sizeofObject(0), + }, + { + "Incomplete comment before key", + "{/*:2}", + "{}", + 10, + DeserializationError::IncompleteInput, + "{}", + sizeofObject(0), + }, + { + "Invalid comment after key", + "{\"example\"/1:2}", + "{}", + 10, + DeserializationError::InvalidInput, + "{}", + sizeofObject(0), + }, + { + "Incomplete comment after key", + "{\"example\"/*:2}", + "{}", + 10, + DeserializationError::IncompleteInput, + "{}", + sizeofObject(0), + }, + { + "Invalid comment after colon", + "{\"example\":/12}", + "{}", + 10, + DeserializationError::InvalidInput, + "{}", + sizeofObject(0), + }, + { + "Incomplete comment after colon", + "{\"example\":/*2}", + "{}", + 10, + DeserializationError::IncompleteInput, + "{}", + sizeofObject(0), + }, + { + "Comment next to an integer", + "{\"ignore\":1//,\"example\":2\n}", + "{\"example\":true}", + 10, + DeserializationError::Ok, + "{}", + sizeofObject(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, + }, + { + "NUL character in key", + "{\"x\":0,\"x\\u0000a\":1,\"x\\u0000b\":2}", + "{\"x\\u0000a\":true}", + 10, + DeserializationError::Ok, + "{\"x\\u0000a\":1}", + sizeofObject(1) + sizeofString("x?a"), + }, + }; + + for (auto& tc : testCases) { + SECTION(tc.description) { + SpyingAllocator spy; + JsonDocument filter; + JsonDocument doc(&spy); + + REQUIRE(deserializeJson(filter, tc.filter) == DeserializationError::Ok); + + CHECK(deserializeJson( + doc, tc.input, DeserializationOption::Filter(filter), + DeserializationOption::NestingLimit(tc.nestingLimit)) == + tc.error); + + CHECK(doc.as() == tc.output); + + doc.shrinkToFit(); + CHECK(spy.allocatedBytes() == tc.memoryUsage); + } + } +} + +TEST_CASE("Overloads") { + JsonDocument doc; + JsonDocument 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, "{}"_s, 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, "{}"_s, 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, "{}"_s, 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 +} + +TEST_CASE("shrink filter") { + JsonDocument doc; + SpyingAllocator spy; + JsonDocument filter(&spy); + filter["a"] = true; + spy.clearLog(); + + deserializeJson(doc, "{}", DeserializationOption::Filter(filter)); + + REQUIRE(spy.log() == AllocatorLog{ + Reallocate(sizeofPool(), sizeofObject(1)), + }); +} diff --git a/extras/tests/JsonDeserializer/input_types.cpp b/extras/tests/JsonDeserializer/input_types.cpp new file mode 100644 index 000000000..e750fd6a6 --- /dev/null +++ b/extras/tests/JsonDeserializer/input_types.cpp @@ -0,0 +1,232 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include + +#include +#include + +#include "Allocators.hpp" +#include "CustomReader.hpp" +#include "Literals.hpp" + +using ArduinoJson::detail::sizeofObject; + +TEST_CASE("deserializeJson(char*)") { + SpyingAllocator spy; + JsonDocument doc(&spy); + + char input[] = "{\"hello\":\"world\"}"; + + DeserializationError err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::Ok); + + REQUIRE(spy.log() == + AllocatorLog{ + Allocate(sizeofStringBuffer()), + Allocate(sizeofPool()), + Reallocate(sizeofStringBuffer(), sizeofString("hello")), + Allocate(sizeofStringBuffer()), + Reallocate(sizeofStringBuffer(), sizeofString("world")), + Reallocate(sizeofPool(), sizeofObject(1)), + }); +} + +TEST_CASE("deserializeJson(unsigned char*, unsigned int)") { // issue #1897 + JsonDocument 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 + JsonDocument 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&)") { + JsonDocument doc; + + 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, "[42]"_s); + + 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("hello"_s == array[0]); + } +} + +TEST_CASE("deserializeJson(std::istream&)") { + JsonDocument doc; + + 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("world"_s == 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}"); + + JsonDocument doc; + DeserializationError err = deserializeJson(doc, vla); + + REQUIRE(err == DeserializationError::Ok); +} +#endif + +TEST_CASE("deserializeJson(CustomReader)") { + JsonDocument doc; + 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)") { + JsonDocument doc1; + doc1["payload"] = "[4,2]"; + + JsonDocument doc2; + 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)") { + JsonDocument doc1; + doc1["payload"] = "[4,2]"; + + JsonDocument doc2; + 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)") { + JsonDocument doc1; + doc1["payload"] = "[4,2]"; + + JsonDocument doc2; + 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)") { + JsonDocument doc1; + doc1[0] = "[4,2]"; + + JsonDocument doc2; + 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/extras/tests/JsonDeserializer/misc.cpp b/extras/tests/JsonDeserializer/misc.cpp new file mode 100644 index 000000000..c13956b54 --- /dev/null +++ b/extras/tests/JsonDeserializer/misc.cpp @@ -0,0 +1,49 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Allocators.hpp" + +using ArduinoJson::detail::sizeofArray; + +TEST_CASE("deserializeJson() misc cases") { + SpyingAllocator spy; + JsonDocument doc(&spy); + + SECTION("null") { + DeserializationError err = deserializeJson(doc, "null"); + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is() == false); + } + + 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("Should clear the JsonVariant") { + deserializeJson(doc, "[1,2,3]"); + spy.clearLog(); + + deserializeJson(doc, "{}"); + + REQUIRE(doc.is()); + REQUIRE(spy.log() == AllocatorLog{ + Deallocate(sizeofArray(3)), + }); + } +} diff --git a/extras/tests/JsonDeserializer/nestingLimit.cpp b/extras/tests/JsonDeserializer/nestingLimit.cpp new file mode 100644 index 000000000..07f8f1953 --- /dev/null +++ b/extras/tests/JsonDeserializer/nestingLimit.cpp @@ -0,0 +1,105 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include + +#include "Literals.hpp" + +#define SHOULD_WORK(expression) REQUIRE(DeserializationError::Ok == expression); +#define SHOULD_FAIL(expression) \ + REQUIRE(DeserializationError::TooDeep == expression); + +TEST_CASE("JsonDeserializer nesting") { + JsonDocument doc; + + 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, "\"toto\""_s, nesting)); + SHOULD_WORK(deserializeJson(doc, "123"_s, nesting)); + SHOULD_WORK(deserializeJson(doc, "true"_s, nesting)); + SHOULD_FAIL(deserializeJson(doc, "[]"_s, nesting)); + SHOULD_FAIL(deserializeJson(doc, "{}"_s, nesting)); + SHOULD_FAIL(deserializeJson(doc, "[\"toto\"]"_s, nesting)); + SHOULD_FAIL(deserializeJson(doc, "{\"toto\":1}"_s, nesting)); + } + + SECTION("limit = 1") { + DeserializationOption::NestingLimit nesting(1); + SHOULD_WORK(deserializeJson(doc, "[\"toto\"]"_s, nesting)); + SHOULD_WORK(deserializeJson(doc, "{\"toto\":1}"_s, nesting)); + SHOULD_FAIL(deserializeJson(doc, "{\"toto\":{}}"_s, nesting)); + SHOULD_FAIL(deserializeJson(doc, "{\"toto\":[]}"_s, nesting)); + SHOULD_FAIL(deserializeJson(doc, "[[\"toto\"]]"_s, nesting)); + SHOULD_FAIL(deserializeJson(doc, "[{\"toto\":1}]"_s, 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/extras/tests/JsonDeserializer/number.cpp b/extras/tests/JsonDeserializer/number.cpp new file mode 100644 index 000000000..a74e50bcc --- /dev/null +++ b/extras/tests/JsonDeserializer/number.cpp @@ -0,0 +1,133 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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") { + JsonDocument doc; + + 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/extras/tests/JsonDeserializer/object.cpp b/extras/tests/JsonDeserializer/object.cpp new file mode 100644 index 000000000..34b357ab5 --- /dev/null +++ b/extras/tests/JsonDeserializer/object.cpp @@ -0,0 +1,400 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +using ArduinoJson::detail::sizeofObject; + +TEST_CASE("deserialize JSON object") { + SpyingAllocator spy; + JsonDocument doc(&spy); + + 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("Float") { + DeserializationError err = + deserializeJson(doc, "{\"key1\":12.345,\"key2\":-7E3}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(obj.size() == 2); + REQUIRE(obj["key1"].as() == Approx(12.345f)); + REQUIRE(obj["key2"] == -7E3f); + } + + SECTION("Double") { + DeserializationError err = + deserializeJson(doc, "{\"key1\":12.3456789,\"key2\":-7E89}"); + JsonObject obj = doc.as(); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(obj.size() == 2); + REQUIRE(obj["key1"].as() == Approx(12.3456789)); + 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, "{alfa:{bravo:{charlie:1}},alfa:2}"); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.as() == "{\"alfa\":2}"); + REQUIRE(spy.log() == + AllocatorLog{ + Allocate(sizeofStringBuffer()), + Allocate(sizeofPool()), + Reallocate(sizeofStringBuffer(), sizeofString("alfa")), + Allocate(sizeofStringBuffer()), + Reallocate(sizeofStringBuffer(), sizeofString("bravo")), + Allocate(sizeofStringBuffer()), + Reallocate(sizeofStringBuffer(), sizeofString("charlie")), + Allocate(sizeofStringBuffer()), + Deallocate(sizeofString("bravo")), + Deallocate(sizeofString("charlie")), + Deallocate(sizeofStringBuffer()), + Reallocate(sizeofPool(), sizeofObject(2) + sizeofObject(1)), + }); + } + + 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") { + DeserializationError err = + deserializeJson(doc, "{\"x\":0,\"x\\u0000a\":1,\"x\\u0000b\":2}"); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.as() == + "{\"x\":0,\"x\\u0000a\":1,\"x\\u0000b\":2}"); + } + } + + SECTION("Should clear the JsonObject") { + deserializeJson(doc, "{\"hello\":\"world\"}"); + spy.clearLog(); + + deserializeJson(doc, "{}"); + + REQUIRE(doc.is()); + REQUIRE(doc.size() == 0); + REQUIRE(spy.log() == AllocatorLog{ + Deallocate(sizeofObject(1)), + Deallocate(sizeofString("hello")), + Deallocate(sizeofString("world")), + }); + } + + SECTION("Issue #1335") { + std::string json("{\"a\":{},\"b\":{}}"); + deserializeJson(doc, json); + CHECK(doc.as() == json); + } +} + +TEST_CASE("deserialize JSON object under memory constraints") { + TimebombAllocator timebomb(1024); + JsonDocument doc(&timebomb); + + SECTION("empty object requires no allocation") { + timebomb.setCountdown(0); + char input[] = "{}"; + + DeserializationError err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.as() == "{}"); + } + + SECTION("key allocation fails") { + timebomb.setCountdown(0); + char input[] = "{\"a\":1}"; + + DeserializationError err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::NoMemory); + REQUIRE(doc.as() == "{}"); + } + + SECTION("pool allocation fails") { + timebomb.setCountdown(1); + char input[] = "{\"a\":1}"; + + DeserializationError err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::NoMemory); + REQUIRE(doc.as() == "{}"); + } + + SECTION("string allocation fails") { + timebomb.setCountdown(3); + char input[] = "{\"alfa\":\"bravo\"}"; + + DeserializationError err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::NoMemory); + REQUIRE(doc.as() == "{\"alfa\":null}"); + } +} diff --git a/extras/tests/JsonDeserializer/string.cpp b/extras/tests/JsonDeserializer/string.cpp new file mode 100644 index 000000000..5ad867862 --- /dev/null +++ b/extras/tests/JsonDeserializer/string.cpp @@ -0,0 +1,214 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#define ARDUINOJSON_DECODE_UNICODE 1 +#include +#include + +#include "Allocators.hpp" + +using ArduinoJson::detail::sizeofArray; +using ArduinoJson::detail::sizeofObject; + +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]); + + JsonDocument doc; + + 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") { + JsonDocument 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]); + + JsonDocument doc; + + for (size_t i = 0; i < testCount; i++) { + const char* input = testCases[i]; + CAPTURE(input); + REQUIRE(deserializeJson(doc, input) == + DeserializationError::IncompleteInput); + } +} + +TEST_CASE("Escape single quote in single quoted string") { + JsonDocument doc; + + DeserializationError err = deserializeJson(doc, "'ab\\\'cd'"); + REQUIRE(err == DeserializationError::Ok); + CHECK(doc.as() == "ab\'cd"); +} + +TEST_CASE("Escape double quote in double quoted string") { + JsonDocument doc; + + DeserializationError err = deserializeJson(doc, "'ab\\\"cd'"); + REQUIRE(err == DeserializationError::Ok); + CHECK(doc.as() == "ab\"cd"); +} + +TEST_CASE("Invalid JSON string") { + const char* testCases[] = {"'\\u'", "'\\u000g'", "'\\u000'", + "'\\u000G'", "'\\u000/'", "'\\x1234'"}; + const size_t testCount = sizeof(testCases) / sizeof(testCases[0]); + + JsonDocument doc; + + for (size_t i = 0; i < testCount; i++) { + const char* input = testCases[i]; + CAPTURE(input); + REQUIRE(deserializeJson(doc, input) == DeserializationError::InvalidInput); + } +} + +TEST_CASE("Allocation of the key fails") { + TimebombAllocator timebomb(0); + SpyingAllocator spy(&timebomb); + JsonDocument doc(&spy); + + SECTION("Quoted string, first member") { + REQUIRE(deserializeJson(doc, "{\"example\":1}") == + DeserializationError::NoMemory); + REQUIRE(spy.log() == AllocatorLog{ + AllocateFail(sizeofStringBuffer()), + }); + } + + SECTION("Quoted string, second member") { + timebomb.setCountdown(3); + REQUIRE(deserializeJson(doc, "{\"hello\":1,\"world\"}") == + DeserializationError::NoMemory); + REQUIRE(spy.log() == + AllocatorLog{ + Allocate(sizeofStringBuffer()), + Allocate(sizeofPool()), + Reallocate(sizeofStringBuffer(), sizeofString("hello")), + AllocateFail(sizeofStringBuffer()), + ReallocateFail(sizeofPool(), sizeofObject(1)), + }); + } + + SECTION("Non-Quoted string, first member") { + REQUIRE(deserializeJson(doc, "{example:1}") == + DeserializationError::NoMemory); + REQUIRE(spy.log() == AllocatorLog{ + AllocateFail(sizeofStringBuffer()), + }); + } + + SECTION("Non-Quoted string, second member") { + timebomb.setCountdown(3); + REQUIRE(deserializeJson(doc, "{hello:1,world}") == + DeserializationError::NoMemory); + REQUIRE(spy.log() == + AllocatorLog{ + Allocate(sizeofStringBuffer()), + Allocate(sizeofPool()), + Reallocate(sizeofStringBuffer(), sizeofString("hello")), + AllocateFail(sizeofStringBuffer()), + ReallocateFail(sizeofPool(), sizeofObject(1)), + }); + } +} + +TEST_CASE("String allocation fails") { + SpyingAllocator spy(FailingAllocator::instance()); + JsonDocument doc(&spy); + + SECTION("Input is const char*") { + REQUIRE(deserializeJson(doc, "\"hello\"") == + DeserializationError::NoMemory); + REQUIRE(spy.log() == AllocatorLog{ + AllocateFail(sizeofStringBuffer()), + }); + } +} + +TEST_CASE("Deduplicate values") { + SpyingAllocator spy; + JsonDocument doc(&spy); + deserializeJson(doc, "[\"example\",\"example\"]"); + + CHECK(doc[0].as() == doc[1].as()); + REQUIRE(spy.log() == + AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofStringBuffer()), + Reallocate(sizeofStringBuffer(), sizeofString("example")), + Allocate(sizeofStringBuffer()), + Deallocate(sizeofStringBuffer()), + Reallocate(sizeofPool(), sizeofArray(2)), + }); +} + +TEST_CASE("Deduplicate keys") { + SpyingAllocator spy; + JsonDocument doc(&spy); + deserializeJson(doc, "[{\"example\":1},{\"example\":2}]"); + + const char* key1 = doc[0].as().begin()->key().c_str(); + const char* key2 = doc[1].as().begin()->key().c_str(); + CHECK(key1 == key2); + + REQUIRE(spy.log() == + AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofStringBuffer()), + Reallocate(sizeofStringBuffer(), sizeofString("example")), + Allocate(sizeofStringBuffer()), + Deallocate(sizeofStringBuffer()), + Reallocate(sizeofPool(), sizeofArray(2) + 2 * sizeofObject(1)), + }); +} diff --git a/extras/tests/JsonDocument/CMakeLists.txt b/extras/tests/JsonDocument/CMakeLists.txt new file mode 100644 index 000000000..dc8036af3 --- /dev/null +++ b/extras/tests/JsonDocument/CMakeLists.txt @@ -0,0 +1,31 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2025, Benoit BLANCHON +# MIT License + +add_executable(JsonDocumentTests + add.cpp + assignment.cpp + cast.cpp + clear.cpp + compare.cpp + constructor.cpp + ElementProxy.cpp + isNull.cpp + issue1120.cpp + MemberProxy.cpp + nesting.cpp + overflowed.cpp + remove.cpp + set.cpp + shrinkToFit.cpp + size.cpp + subscript.cpp + swap.cpp +) + +add_test(JsonDocument JsonDocumentTests) + +set_tests_properties(JsonDocument + PROPERTIES + LABELS "Catch" +) diff --git a/extras/tests/JsonDocument/ElementProxy.cpp b/extras/tests/JsonDocument/ElementProxy.cpp new file mode 100644 index 000000000..9cf885514 --- /dev/null +++ b/extras/tests/JsonDocument/ElementProxy.cpp @@ -0,0 +1,297 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +using ElementProxy = ArduinoJson::detail::ElementProxy; + +TEST_CASE("ElementProxy::add()") { + SpyingAllocator spy; + JsonDocument doc(&spy); + doc.add(); + const ElementProxy& ep = doc[0]; + + SECTION("integer") { + ep.add(42); + + REQUIRE(doc.as() == "[[42]]"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + }); + } + + SECTION("string literal") { + ep.add("world"); + + REQUIRE(doc.as() == "[[\"world\"]]"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + }); + } + + SECTION("const char*") { + const char* s = "world"; + ep.add(s); + + REQUIRE(doc.as() == "[[\"world\"]]"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("world")), + }); + } + + SECTION("char[]") { + char s[] = "world"; + ep.add(s); + strcpy(s, "!!!!!"); + + REQUIRE(doc.as() == "[[\"world\"]]"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("world")), + }); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("VLA") { + size_t i = 8; + char vla[i]; + strcpy(vla, "world"); + + ep.add(vla); + + REQUIRE(doc.as() == "[[\"world\"]]"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("world")), + }); + } +#endif +} + +TEST_CASE("ElementProxy::clear()") { + JsonDocument doc; + doc.add(); + const 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==()") { + JsonDocument doc; + + 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()") { + JsonDocument doc; + doc.add(); + const 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("b"_s); + + 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()") { + JsonDocument doc; + const 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\"]"); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("set(VLA)") { + size_t i = 8; + char vla[i]; + strcpy(vla, "world"); + + ep.set(vla); + + REQUIRE(doc.as() == "[\"world\"]"); + } +#endif +} + +TEST_CASE("ElementProxy::size()") { + JsonDocument doc; + doc.add(); + const 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::operator[]") { + JsonDocument doc; + const 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]]"); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("set VLA") { + size_t i = 8; + char vla[i]; + strcpy(vla, "world"); + + ep[0] = vla; + + REQUIRE(doc.as() == "[null,[\"world\"]]"); + } +#endif +} + +TEST_CASE("ElementProxy cast to JsonVariantConst") { + JsonDocument doc; + doc[0] = "world"; + + const ElementProxy& ep = doc[0]; + + JsonVariantConst var = ep; + + CHECK(var.as() == "world"); +} + +TEST_CASE("ElementProxy cast to JsonVariant") { + JsonDocument doc; + doc[0] = "world"; + + const ElementProxy& ep = doc[0]; + + JsonVariant var = ep; + + CHECK(var.as() == "world"); + + var.set("toto"); + + CHECK(doc.as() == "[\"toto\"]"); +} diff --git a/extras/tests/JsonDocument/MemberProxy.cpp b/extras/tests/JsonDocument/MemberProxy.cpp new file mode 100644 index 000000000..c42edcc10 --- /dev/null +++ b/extras/tests/JsonDocument/MemberProxy.cpp @@ -0,0 +1,432 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#define ARDUINOJSON_ENABLE_ARDUINO_STRING 1 +#define ARDUINOJSON_ENABLE_PROGMEM 1 +#include + +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +using ArduinoJson::detail::sizeofArray; +using ArduinoJson::detail::sizeofObject; + +TEST_CASE("MemberProxy::add()") { + SpyingAllocator spy; + JsonDocument doc(&spy); + const auto& mp = doc["hello"]; + + SECTION("integer") { + mp.add(42); + + REQUIRE(doc.as() == "{\"hello\":[42]}"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + }); + } + + SECTION("string literal") { + mp.add("world"); + + REQUIRE(doc.as() == "{\"hello\":[\"world\"]}"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + }); + } + + SECTION("const char*") { + const char* temp = "world"; + mp.add(temp); + + REQUIRE(doc.as() == "{\"hello\":[\"world\"]}"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("world")), + }); + } + + SECTION("char[]") { + char temp[] = "world"; + mp.add(temp); + + REQUIRE(doc.as() == "{\"hello\":[\"world\"]}"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("world")), + + }); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("VLA") { + size_t i = 16; + char vla[i]; + strcpy(vla, "world"); + + mp.add(vla); + + REQUIRE(doc.as() == "{\"hello\":[\"world\"]}"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("world")), + }); + } +#endif +} + +TEST_CASE("MemberProxy::clear()") { + JsonDocument doc; + const auto& 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==()") { + JsonDocument doc; + + 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::operator|()") { + JsonDocument doc; + + SECTION("const char*") { + doc["a"] = "hello"; + + REQUIRE((doc["a"] | "world") == "hello"_s); + REQUIRE((doc["b"] | "world") == "world"_s); + } + + 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 == "gps"_s); + } + + SECTION("Issue #1415") { + JsonObject object = doc.to(); + object["hello"] = "world"; + + JsonDocument emptyDoc; + JsonObject anotherObject = object["hello"] | emptyDoc.to(); + + REQUIRE(anotherObject.isNull() == false); + REQUIRE(anotherObject.size() == 0); + } +} + +TEST_CASE("MemberProxy::remove()") { + JsonDocument doc; + const auto& 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("b"_s); + + 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()") { + JsonDocument doc; + const auto& 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\"}"); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("set(vla)") { + size_t i = 8; + char vla[i]; + strcpy(vla, "world"); + + mp.set(vla); + + REQUIRE(doc.as() == "{\"hello\":\"world\"}"); + } +#endif +} + +TEST_CASE("MemberProxy::size()") { + JsonDocument doc; + const auto& 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::operator[]") { + JsonDocument doc; + const auto& 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") { + JsonDocument doc; + doc["hello"] = "world"; + + const auto& mp = doc["hello"]; + + JsonVariantConst var = mp; + + CHECK(var.as() == "world"); +} + +TEST_CASE("MemberProxy cast to JsonVariant") { + JsonDocument doc; + doc["hello"] = "world"; + + const auto& mp = doc["hello"]; + + JsonVariant var = mp; + + CHECK(var.as() == "world"); + + var.set("toto"); + + CHECK(doc.as() == "{\"hello\":\"toto\"}"); +} + +TEST_CASE("Deduplicate keys") { + SpyingAllocator spy; + JsonDocument doc(&spy); + + SECTION("std::string") { + doc[0]["example"_s] = 1; + doc[1]["example"_s] = 2; + + const char* key1 = doc[0].as().begin()->key().c_str(); + const char* key2 = doc[1].as().begin()->key().c_str(); + CHECK(key1 == key2); + + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("example")), + }); + } + + SECTION("char*") { + char key[] = "example"; + doc[0][key] = 1; + doc[1][key] = 2; + + const char* key1 = doc[0].as().begin()->key().c_str(); + const char* key2 = doc[1].as().begin()->key().c_str(); + CHECK(key1 == key2); + + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("example")), + }); + } + + SECTION("Arduino String") { + doc[0][String("example")] = 1; + doc[1][String("example")] = 2; + + const char* key1 = doc[0].as().begin()->key().c_str(); + const char* key2 = doc[1].as().begin()->key().c_str(); + CHECK(key1 == key2); + + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("example")), + }); + } + + SECTION("Flash string") { + doc[0][F("example")] = 1; + doc[1][F("example")] = 2; + + const char* key1 = doc[0].as().begin()->key().c_str(); + const char* key2 = doc[1].as().begin()->key().c_str(); + CHECK(key1 == key2); + + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("example")), + }); + } +} + +TEST_CASE("MemberProxy under memory constraints") { + TimebombAllocator timebomb(1); + SpyingAllocator spy(&timebomb); + JsonDocument doc(&spy); + + SECTION("key slot allocation fails") { + timebomb.setCountdown(0); + + doc["hello"_s] = "world"; + + REQUIRE(doc.is()); + REQUIRE(doc.size() == 0); + REQUIRE(doc.overflowed() == true); + REQUIRE(spy.log() == AllocatorLog{ + AllocateFail(sizeofPool()), + }); + } + + SECTION("value slot allocation fails") { + timebomb.setCountdown(1); + + // fill the pool entirely, but leave one slot for the key + doc["foo"][ARDUINOJSON_POOL_CAPACITY - 4] = 1; + REQUIRE(doc.overflowed() == false); + + doc["hello"_s] = "world"; + + REQUIRE(doc.is()); + REQUIRE(doc.size() == 1); + REQUIRE(doc.overflowed() == true); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + AllocateFail(sizeofPool()), + }); + } + + SECTION("key string allocation fails") { + timebomb.setCountdown(1); + + doc["hello"_s] = "world"; + + REQUIRE(doc.is()); + REQUIRE(doc.size() == 0); + REQUIRE(doc.overflowed() == true); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + AllocateFail(sizeofString("hello")), + }); + } +} diff --git a/extras/tests/JsonDocument/add.cpp b/extras/tests/JsonDocument/add.cpp new file mode 100644 index 000000000..da898e661 --- /dev/null +++ b/extras/tests/JsonDocument/add.cpp @@ -0,0 +1,176 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#define ARDUINOJSON_ENABLE_ARDUINO_STRING 1 +#define ARDUINOJSON_ENABLE_PROGMEM 1 +#include + +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +using ArduinoJson::detail::sizeofArray; + +TEST_CASE("JsonDocument::add(T)") { + SpyingAllocator spy; + JsonDocument doc(&spy); + + SECTION("integer") { + doc.add(42); + + REQUIRE(doc.as() == "[42]"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + }); + } + + SECTION("string literal") { + doc.add("hello"); + + REQUIRE(doc.as() == "[\"hello\"]"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + }); + } + + SECTION("const char*") { + const char* value = "hello"; + doc.add(value); + + REQUIRE(doc.as() == "[\"hello\"]"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("hello")), + }); + } + + SECTION("std::string") { + doc.add("example"_s); + doc.add("example"_s); + + CHECK(doc[0].as() == doc[1].as()); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("example")), + }); + } + + SECTION("char*") { + char value[] = "example"; + doc.add(value); + doc.add(value); + + CHECK(doc[0].as() == doc[1].as()); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("example")), + }); + } + + SECTION("Arduino String") { + doc.add(String("example")); + doc.add(String("example")); + + CHECK(doc[0].as() == doc[1].as()); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("example")), + }); + } + + SECTION("Flash string") { + doc.add(F("example")); + doc.add(F("example")); + + CHECK(doc[0].as() == doc[1].as()); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("example")), + }); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("VLA") { + size_t i = 16; + char vla[i]; + strcpy(vla, "example"); + + doc.add(vla); + doc.add(vla); + + CHECK(doc[0].as() == doc[1].as()); + REQUIRE("example"_s == doc[0]); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("example")), + }); + } +#endif +} + +TEST_CASE("JsonDocument::add()") { + JsonDocument doc; + + SECTION("JsonArray") { + JsonArray array = doc.add(); + array.add(1); + array.add(2); + REQUIRE(doc.as() == "[[1,2]]"); + } + + SECTION("JsonVariant") { + JsonVariant variant = doc.add(); + variant.set(42); + REQUIRE(doc.as() == "[42]"); + } +} + +TEST_CASE("JsonObject::add(JsonObject) ") { + JsonDocument doc1; + doc1["hello"_s] = "world"_s; + + TimebombAllocator allocator(10); + SpyingAllocator spy(&allocator); + JsonDocument doc2(&spy); + + SECTION("success") { + bool result = doc2.add(doc1.as()); + + REQUIRE(result == true); + REQUIRE(doc2.as() == "[{\"hello\":\"world\"}]"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("hello")), + Allocate(sizeofString("world")), + }); + } + + SECTION("partial failure") { // issue #2081 + allocator.setCountdown(2); + + bool result = doc2.add(doc1.as()); + + REQUIRE(result == false); + REQUIRE(doc2.as() == "[]"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("hello")), + AllocateFail(sizeofString("world")), + Deallocate(sizeofString("hello")), + }); + } + + SECTION("complete failure") { + allocator.setCountdown(0); + + bool result = doc2.add(doc1.as()); + + REQUIRE(result == false); + REQUIRE(doc2.as() == "[]"); + REQUIRE(spy.log() == AllocatorLog{ + AllocateFail(sizeofPool()), + }); + } +} diff --git a/extras/tests/JsonDocument/assignment.cpp b/extras/tests/JsonDocument/assignment.cpp new file mode 100644 index 000000000..64d7dd020 --- /dev/null +++ b/extras/tests/JsonDocument/assignment.cpp @@ -0,0 +1,137 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +TEST_CASE("JsonDocument assignment") { + SpyingAllocator spyingAllocator; + + SECTION("Copy assignment same capacity") { + JsonDocument doc1(&spyingAllocator); + deserializeJson(doc1, "{\"hello\":\"world\"}"); + JsonDocument doc2(&spyingAllocator); + spyingAllocator.clearLog(); + + doc2 = doc1; + + REQUIRE(doc2.as() == "{\"hello\":\"world\"}"); + + REQUIRE(spyingAllocator.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("hello")), + Allocate(sizeofString("world")), + }); + } + + SECTION("Copy assignment reallocates when capacity is smaller") { + JsonDocument doc1(&spyingAllocator); + deserializeJson(doc1, "[{\"hello\":\"world\"}]"); + JsonDocument doc2(&spyingAllocator); + spyingAllocator.clearLog(); + + doc2 = doc1; + + REQUIRE(doc2.as() == "[{\"hello\":\"world\"}]"); + REQUIRE(spyingAllocator.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("hello")), + Allocate(sizeofString("world")), + }); + } + + SECTION("Copy assignment reallocates when capacity is larger") { + JsonDocument doc1(&spyingAllocator); + deserializeJson(doc1, "{\"hello\":\"world\"}"); + JsonDocument doc2(&spyingAllocator); + spyingAllocator.clearLog(); + + doc2 = doc1; + + REQUIRE(doc2.as() == "{\"hello\":\"world\"}"); + REQUIRE(spyingAllocator.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("hello")), + Allocate(sizeofString("world")), + }); + } + + SECTION("Move assign") { + { + JsonDocument doc1(&spyingAllocator); + doc1["hello"_s] = "world"_s; + JsonDocument doc2(&spyingAllocator); + + doc2 = std::move(doc1); + + REQUIRE(doc2.as() == "{\"hello\":\"world\"}"); + + // NOLINTNEXTLINE(clang-analyzer-cplusplus.Move) + REQUIRE(doc1.as() == "null"); + } + REQUIRE(spyingAllocator.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("hello")), + Allocate(sizeofString("world")), + Deallocate(sizeofString("hello")), + Deallocate(sizeofString("world")), + Deallocate(sizeofPool()), + }); + } + + SECTION("Assign from JsonObject") { + JsonDocument doc1; + JsonObject obj = doc1.to(); + obj["hello"] = "world"; + + JsonDocument doc2; + doc2 = obj; + + REQUIRE(doc2.as() == "{\"hello\":\"world\"}"); + } + + SECTION("Assign from JsonArray") { + JsonDocument doc1; + JsonArray arr = doc1.to(); + arr.add("hello"); + + JsonDocument doc2; + doc2 = arr; + + REQUIRE(doc2.as() == "[\"hello\"]"); + } + + SECTION("Assign from JsonVariant") { + JsonDocument doc1; + deserializeJson(doc1, "42"); + + JsonDocument doc2; + doc2 = doc1.as(); + + REQUIRE(doc2.as() == "42"); + } + + SECTION("Assign from MemberProxy") { + JsonDocument doc1; + doc1["value"] = 42; + + JsonDocument doc2; + doc2 = doc1["value"]; + + REQUIRE(doc2.as() == "42"); + } + + SECTION("Assign from ElementProxy") { + JsonDocument doc1; + doc1[0] = 42; + + JsonDocument doc2; + doc2 = doc1[0]; + + REQUIRE(doc2.as() == "42"); + } +} diff --git a/extras/tests/JsonDocument/cast.cpp b/extras/tests/JsonDocument/cast.cpp new file mode 100644 index 000000000..0bb9caaa5 --- /dev/null +++ b/extras/tests/JsonDocument/cast.cpp @@ -0,0 +1,18 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include + +TEST_CASE("Implicit cast to JsonVariant") { + JsonDocument doc; + + doc["hello"] = "world"; + + JsonVariant var = doc; + + CHECK(var.as() == "{\"hello\":\"world\"}"); +} diff --git a/extras/tests/JsonDocument/clear.cpp b/extras/tests/JsonDocument/clear.cpp new file mode 100644 index 000000000..98d24998f --- /dev/null +++ b/extras/tests/JsonDocument/clear.cpp @@ -0,0 +1,48 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include // malloc, free +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +TEST_CASE("JsonDocument::clear()") { + SpyingAllocator spy; + JsonDocument doc(&spy); + + SECTION("null") { + doc.clear(); + + REQUIRE(doc.isNull()); + REQUIRE(spy.log() == AllocatorLog{}); + } + + SECTION("releases resources") { + doc["hello"_s] = "world"_s; + spy.clearLog(); + + doc.clear(); + + REQUIRE(doc.isNull()); + REQUIRE(spy.log() == AllocatorLog{ + Deallocate(sizeofPool()), + Deallocate(sizeofString("hello")), + Deallocate(sizeofString("world")), + }); + } + + SECTION("clear free list") { // issue #2034 + JsonObject obj = doc.to(); + obj["a"] = 1; + obj.clear(); // puts the slot in the free list + + doc.clear(); + + doc["b"] = 2; // will it pick from the free list? + } +} diff --git a/extras/tests/JsonDocument/compare.cpp b/extras/tests/JsonDocument/compare.cpp new file mode 100644 index 000000000..da7af58fc --- /dev/null +++ b/extras/tests/JsonDocument/compare.cpp @@ -0,0 +1,29 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonDocument::operator==(const JsonDocument&)") { + JsonDocument doc1; + JsonDocument 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); + } +} diff --git a/extras/tests/JsonDocument/constructor.cpp b/extras/tests/JsonDocument/constructor.cpp new file mode 100644 index 000000000..371a2561f --- /dev/null +++ b/extras/tests/JsonDocument/constructor.cpp @@ -0,0 +1,150 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +using ArduinoJson::detail::addPadding; + +TEST_CASE("JsonDocument constructor") { + SpyingAllocator spyingAllocator; + + SECTION("JsonDocument(size_t)") { + { JsonDocument doc(&spyingAllocator); } + REQUIRE(spyingAllocator.log() == AllocatorLog{}); + } + + SECTION("JsonDocument(const JsonDocument&)") { + { + JsonDocument doc1(&spyingAllocator); + doc1.set("The size of this string is 32!!"_s); + + JsonDocument doc2(doc1); + + REQUIRE(doc1.as() == "The size of this string is 32!!"); + REQUIRE(doc2.as() == "The size of this string is 32!!"); + } + REQUIRE(spyingAllocator.log() == AllocatorLog{ + Allocate(sizeofStringBuffer()), + Allocate(sizeofStringBuffer()), + Deallocate(sizeofStringBuffer()), + Deallocate(sizeofStringBuffer()), + }); + } + + SECTION("JsonDocument(JsonDocument&&)") { + { + JsonDocument doc1(&spyingAllocator); + doc1.set("The size of this string is 32!!"_s); + + JsonDocument doc2(std::move(doc1)); + + REQUIRE(doc2.as() == "The size of this string is 32!!"); + + // NOLINTNEXTLINE(clang-analyzer-cplusplus.Move) + REQUIRE(doc1.as() == "null"); + } + REQUIRE(spyingAllocator.log() == AllocatorLog{ + Allocate(sizeofStringBuffer()), + Deallocate(sizeofStringBuffer()), + }); + } + + SECTION("JsonDocument(JsonObject, Allocator*)") { + JsonDocument doc1; + JsonObject obj = doc1.to(); + obj["hello"] = "world"; + + JsonDocument doc2(obj, &spyingAllocator); + + REQUIRE(doc2.as() == "{\"hello\":\"world\"}"); + REQUIRE(spyingAllocator.log() == AllocatorLog{ + Allocate(sizeofPool()), + }); + } + + SECTION("JsonDocument(JsonObject)") { + JsonDocument doc1; + JsonObject obj = doc1.to(); + obj["hello"] = "world"; + + JsonDocument doc2(obj); + + REQUIRE(doc2.as() == "{\"hello\":\"world\"}"); + } + + SECTION("JsonDocument(JsonArray, Allocator*)") { + JsonDocument doc1; + JsonArray arr = doc1.to(); + arr.add("hello"); + + JsonDocument doc2(arr, &spyingAllocator); + + REQUIRE(doc2.as() == "[\"hello\"]"); + REQUIRE(spyingAllocator.log() == AllocatorLog{ + Allocate(sizeofPool()), + }); + } + + SECTION("JsonDocument(JsonArray)") { + JsonDocument doc1; + JsonArray arr = doc1.to(); + arr.add("hello"); + + JsonDocument doc2(arr); + + REQUIRE(doc2.as() == "[\"hello\"]"); + } + + SECTION("JsonDocument(JsonVariant, Allocator*)") { + JsonDocument doc1; + deserializeJson(doc1, "\"hello\""); + + JsonDocument doc2(doc1.as(), &spyingAllocator); + + REQUIRE(doc2.as() == "hello"); + REQUIRE(spyingAllocator.log() == AllocatorLog{ + Allocate(sizeofString("hello")), + }); + } + + SECTION("JsonDocument(JsonVariant)") { + JsonDocument doc1; + deserializeJson(doc1, "\"hello\""); + + JsonDocument doc2(doc1.as()); + + REQUIRE(doc2.as() == "hello"); + } + + SECTION("JsonDocument(JsonVariantConst)") { + JsonDocument doc1; + deserializeJson(doc1, "\"hello\""); + + JsonDocument doc2(doc1.as()); + + REQUIRE(doc2.as() == "hello"); + } + + SECTION("JsonDocument(ElementProxy)") { + JsonDocument doc1; + deserializeJson(doc1, "[\"hello\",\"world\"]"); + + JsonDocument doc2(doc1[1]); + + REQUIRE(doc2.as() == "world"); + } + + SECTION("JsonDocument(MemberProxy)") { + JsonDocument doc1; + deserializeJson(doc1, "{\"hello\":\"world\"}"); + + JsonDocument doc2(doc1["hello"]); + + REQUIRE(doc2.as() == "world"); + } +} diff --git a/extras/tests/JsonDocument/isNull.cpp b/extras/tests/JsonDocument/isNull.cpp new file mode 100644 index 000000000..d030842cf --- /dev/null +++ b/extras/tests/JsonDocument/isNull.cpp @@ -0,0 +1,39 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonDocument::isNull()") { + JsonDocument doc; + + 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/extras/tests/JsonDocument/issue1120.cpp b/extras/tests/JsonDocument/issue1120.cpp new file mode 100644 index 000000000..aa3132f53 --- /dev/null +++ b/extras/tests/JsonDocument/issue1120.cpp @@ -0,0 +1,52 @@ +#include + +#include + +#include "Literals.hpp" + +TEST_CASE("Issue #1120") { + JsonDocument doc; + constexpr char str[] = + "{\"contents\":[{\"module\":\"Packet\"},{\"module\":\"Analog\"}]}"; + deserializeJson(doc, str); + + SECTION("MemberProxy::isNull()") { + SECTION("returns false") { + CHECK(doc["contents"_s].isNull() == false); + } + + SECTION("returns true") { + CHECK(doc["zontents"_s].isNull() == true); + } + } + + SECTION("ElementProxy >::isNull()") { + SECTION("returns false") { // Issue #1120 + CHECK(doc["contents"][1].isNull() == false); + } + + SECTION("returns true") { + CHECK(doc["contents"][2].isNull() == true); + } + } + + SECTION("MemberProxy, const char*>::isNull()") { + SECTION("returns false") { + CHECK(doc["contents"][1]["module"].isNull() == false); + } + + SECTION("returns true") { + CHECK(doc["contents"][1]["zodule"].isNull() == true); + } + } + + SECTION("MemberProxy, std::string>::isNull()") { + SECTION("returns false") { + CHECK(doc["contents"][1]["module"_s].isNull() == false); + } + + SECTION("returns true") { + CHECK(doc["contents"][1]["zodule"_s].isNull() == true); + } + } +} diff --git a/extras/tests/JsonDocument/nesting.cpp b/extras/tests/JsonDocument/nesting.cpp new file mode 100644 index 000000000..2fb86e1ae --- /dev/null +++ b/extras/tests/JsonDocument/nesting.cpp @@ -0,0 +1,30 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonDocument::nesting()") { + JsonDocument doc; + + 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/extras/tests/JsonDocument/overflowed.cpp b/extras/tests/JsonDocument/overflowed.cpp new file mode 100644 index 000000000..44003ebc0 --- /dev/null +++ b/extras/tests/JsonDocument/overflowed.cpp @@ -0,0 +1,96 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +TEST_CASE("JsonDocument::overflowed()") { + TimebombAllocator timebomb(10); + JsonDocument doc(&timebomb); + + SECTION("returns false on a fresh object") { + timebomb.setCountdown(0); + CHECK(doc.overflowed() == false); + } + + SECTION("returns true after a failed insertion") { + timebomb.setCountdown(0); + doc.add(0); + CHECK(doc.overflowed() == true); + } + + SECTION("returns false after successful insertion") { + timebomb.setCountdown(2); + doc.add(0); + CHECK(doc.overflowed() == false); + } + + SECTION("returns true after a failed string copy") { + timebomb.setCountdown(0); + doc.add("example"_s); + CHECK(doc.overflowed() == true); + } + + SECTION("returns false after a successful string copy") { + timebomb.setCountdown(3); + doc.add("example"_s); + CHECK(doc.overflowed() == false); + } + + SECTION("returns true after a failed member add") { + timebomb.setCountdown(0); + doc["example"] = true; + CHECK(doc.overflowed() == true); + } + + SECTION("returns true after a failed deserialization") { + timebomb.setCountdown(0); + deserializeJson(doc, "[1, 2]"); + CHECK(doc.overflowed() == true); + } + + SECTION("returns false after a successful deserialization") { + timebomb.setCountdown(3); + deserializeJson(doc, "[\"example\"]"); + CHECK(doc.overflowed() == false); + } + + SECTION("returns false after clear()") { + timebomb.setCountdown(0); + doc.add(0); + doc.clear(); + CHECK(doc.overflowed() == false); + } + + SECTION("remains false after shrinkToFit()") { + timebomb.setCountdown(2); + doc.add(0); + timebomb.setCountdown(2); + doc.shrinkToFit(); + CHECK(doc.overflowed() == false); + } + + SECTION("remains true after shrinkToFit()") { + timebomb.setCountdown(0); + doc.add(0); + timebomb.setCountdown(2); + doc.shrinkToFit(); + CHECK(doc.overflowed() == true); + } + + SECTION("returns false when string length doesn't overflow") { + auto maxLength = ArduinoJson::detail::StringNode::maxLength; + CHECK(doc.set(std::string(maxLength, 'a')) == true); + CHECK(doc.overflowed() == false); + } + + SECTION("returns true when string length overflows") { + auto maxLength = ArduinoJson::detail::StringNode::maxLength; + CHECK(doc.set(std::string(maxLength + 1, 'a')) == false); + CHECK(doc.overflowed() == true); + } +} diff --git a/extras/tests/JsonDocument/remove.cpp b/extras/tests/JsonDocument/remove.cpp new file mode 100644 index 000000000..f017bb9ae --- /dev/null +++ b/extras/tests/JsonDocument/remove.cpp @@ -0,0 +1,85 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Literals.hpp" + +TEST_CASE("JsonDocument::remove()") { + JsonDocument doc; + + SECTION("remove(int)") { + doc.add(1); + doc.add(2); + doc.add(3); + + doc.remove(1); + + REQUIRE(doc.as() == "[1,3]"); + } + + SECTION("string literal") { + doc["a"] = 1; + doc["a\0b"_s] = 2; + doc["b"] = 3; + + doc.remove("a\0b"); + + REQUIRE(doc.as() == "{\"a\":1,\"b\":3}"); + } + + SECTION("remove(const char *)") { + doc["a"] = 1; + doc["b"] = 2; + + doc.remove(static_cast("a")); + + REQUIRE(doc.as() == "{\"b\":2}"); + } + + SECTION("remove(std::string)") { + doc["a"] = 1; + doc["b"] = 2; + + doc.remove("b"_s); + + 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 + + SECTION("remove(JsonVariant) from object") { + doc["a"] = 1; + doc["b"] = 2; + doc["c"] = "b"; + + doc.remove(doc["c"]); + + REQUIRE(doc.as() == "{\"a\":1,\"c\":\"b\"}"); + } + + SECTION("remove(JsonVariant) from array") { + doc[0] = 3; + doc[1] = 2; + doc[2] = 1; + + doc.remove(doc[2]); + doc.remove(doc[3]); // noop + + REQUIRE(doc.as() == "[3,1]"); + } +} diff --git a/extras/tests/JsonDocument/set.cpp b/extras/tests/JsonDocument/set.cpp new file mode 100644 index 000000000..88c33bbc9 --- /dev/null +++ b/extras/tests/JsonDocument/set.cpp @@ -0,0 +1,111 @@ +#define ARDUINOJSON_ENABLE_ARDUINO_STRING 1 +#define ARDUINOJSON_ENABLE_PROGMEM 1 +#include + +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +TEST_CASE("JsonDocument::set()") { + SpyingAllocator spy; + JsonDocument doc(&spy); + + SECTION("nullptr") { + doc.set(nullptr); + + REQUIRE(doc.isNull()); + REQUIRE(spy.log() == AllocatorLog{}); + } + + SECTION("integer&") { + int toto = 42; + doc.set(toto); + + REQUIRE(doc.as() == "42"); + REQUIRE(spy.log() == AllocatorLog{}); + } + + SECTION("integer") { + doc.set(42); + + REQUIRE(doc.as() == "42"); + REQUIRE(spy.log() == AllocatorLog{}); + } + + SECTION("string literal") { + doc.set("example"); + + REQUIRE(doc.as() == "example"_s); + REQUIRE(spy.log() == AllocatorLog{}); + } + + SECTION("const char*") { + const char* value = "example"; + doc.set(value); + + REQUIRE(doc.as() == "example"_s); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofString("example")), + }); + } + + SECTION("std::string") { + doc.set("example"_s); + + REQUIRE(doc.as() == "example"_s); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofString("example")), + }); + } + + SECTION("char*") { + char value[] = "example"; + doc.set(value); + + REQUIRE(doc.as() == "example"_s); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofString("example")), + }); + } + + SECTION("Arduino String") { + doc.set(String("example")); + + REQUIRE(doc.as() == "example"_s); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofString("example")), + }); + } + + SECTION("Flash string") { + doc.set(F("example")); + + REQUIRE(doc.as() == "example"_s); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofString("example")), + }); + } + + SECTION("Flash tiny string") { // issue #2170 + doc.set(F("abc")); + + REQUIRE(doc.as() == "abc"_s); + REQUIRE(spy.log() == AllocatorLog{}); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("VLA") { + size_t i = 16; + char vla[i]; + strcpy(vla, "example"); + + doc.set(vla); + + REQUIRE(doc.as() == "example"_s); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofString("example")), + }); + } +#endif +} diff --git a/extras/tests/JsonDocument/shrinkToFit.cpp b/extras/tests/JsonDocument/shrinkToFit.cpp new file mode 100644 index 000000000..148b552d6 --- /dev/null +++ b/extras/tests/JsonDocument/shrinkToFit.cpp @@ -0,0 +1,184 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include // malloc, free +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +using ArduinoJson::detail::sizeofArray; +using ArduinoJson::detail::sizeofObject; + +class ArmoredAllocator : public Allocator { + public: + virtual ~ArmoredAllocator() {} + + void* allocate(size_t size) override { + return malloc(size); + } + + void deallocate(void* ptr) override { + free(ptr); + } + + void* reallocate(void* ptr, size_t new_size) override { + // 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); + memset(new_ptr, '#', new_size); // erase + if (ptr) { + memcpy(new_ptr, ptr, std::min(new_size, new_size)); + free(ptr); + } + return new_ptr; + } +}; + +TEST_CASE("JsonDocument::shrinkToFit()") { + ArmoredAllocator armoredAllocator; + SpyingAllocator spyingAllocator(&armoredAllocator); + JsonDocument doc(&spyingAllocator); + + SECTION("null") { + doc.shrinkToFit(); + + REQUIRE(doc.as() == "null"); + REQUIRE(spyingAllocator.log() == AllocatorLog{}); + } + + SECTION("empty object") { + deserializeJson(doc, "{}"); + + doc.shrinkToFit(); + + REQUIRE(doc.as() == "{}"); + REQUIRE(spyingAllocator.log() == AllocatorLog{}); + } + + SECTION("empty array") { + deserializeJson(doc, "[]"); + + doc.shrinkToFit(); + + REQUIRE(doc.as() == "[]"); + REQUIRE(spyingAllocator.log() == AllocatorLog{}); + } + + SECTION("linked string") { + doc.set("hello"); + + doc.shrinkToFit(); + + REQUIRE(doc.as() == "hello"); + REQUIRE(spyingAllocator.log() == AllocatorLog{}); + } + + SECTION("owned string") { + doc.set("abcdefg"_s); + REQUIRE(doc.as() == "abcdefg"); + + doc.shrinkToFit(); + + REQUIRE(doc.as() == "abcdefg"); + REQUIRE(spyingAllocator.log() == AllocatorLog{ + Allocate(sizeofString("abcdefg")), + }); + } + + SECTION("raw string") { + doc.set(serialized("[{},12]")); + + doc.shrinkToFit(); + + REQUIRE(doc.as() == "[{},12]"); + REQUIRE(spyingAllocator.log() == AllocatorLog{ + Allocate(sizeofString("[{},12]")), + }); + } + + SECTION("linked key") { + doc["key"] = 42; + + doc.shrinkToFit(); + + REQUIRE(doc.as() == "{\"key\":42}"); + REQUIRE(spyingAllocator.log() == + AllocatorLog{ + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + SECTION("owned key") { + doc["abcdefg"_s] = 42; + + doc.shrinkToFit(); + + REQUIRE(doc.as() == "{\"abcdefg\":42}"); + REQUIRE(spyingAllocator.log() == + AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("abcdefg")), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + SECTION("linked string in array") { + doc.add("hello"); + + doc.shrinkToFit(); + + REQUIRE(doc.as() == "[\"hello\"]"); + REQUIRE(spyingAllocator.log() == + AllocatorLog{ + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofArray(1)), + }); + } + + SECTION("owned string in array") { + doc.add("abcdefg"_s); + + doc.shrinkToFit(); + + REQUIRE(doc.as() == "[\"abcdefg\"]"); + REQUIRE(spyingAllocator.log() == + AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("abcdefg")), + Reallocate(sizeofPool(), sizeofArray(1)), + }); + } + + SECTION("linked string in object") { + doc["key"] = "hello"; + + doc.shrinkToFit(); + + REQUIRE(doc.as() == "{\"key\":\"hello\"}"); + REQUIRE(spyingAllocator.log() == + AllocatorLog{ + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + SECTION("owned string in object") { + doc["key"] = "abcdefg"_s; + + doc.shrinkToFit(); + + REQUIRE(doc.as() == "{\"key\":\"abcdefg\"}"); + REQUIRE(spyingAllocator.log() == + AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("abcdefg")), + Reallocate(sizeofPool(), sizeofPool(2)), + }); + } +} diff --git a/extras/tests/JsonDocument/size.cpp b/extras/tests/JsonDocument/size.cpp new file mode 100644 index 000000000..fad658430 --- /dev/null +++ b/extras/tests/JsonDocument/size.cpp @@ -0,0 +1,28 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonDocument::size()") { + JsonDocument doc; + + 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/extras/tests/JsonDocument/subscript.cpp b/extras/tests/JsonDocument/subscript.cpp new file mode 100644 index 000000000..17bdcc2ec --- /dev/null +++ b/extras/tests/JsonDocument/subscript.cpp @@ -0,0 +1,167 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +TEST_CASE("JsonDocument::operator[]") { + JsonDocument doc; + const JsonDocument& cdoc = doc; + + SECTION("object") { + doc["abc"_s] = "ABC"; + doc["abc\0d"_s] = "ABCD"; + + SECTION("const char*") { + const char* key = "abc"; + REQUIRE(doc[key] == "ABC"); + REQUIRE(cdoc[key] == "ABC"); + } + + SECTION("string literal") { + REQUIRE(doc["abc"] == "ABC"); + REQUIRE(cdoc["abc"] == "ABC"); + REQUIRE(doc["abc\0d"] == "ABCD"); + REQUIRE(cdoc["abc\0d"] == "ABCD"); + } + + SECTION("std::string") { + REQUIRE(doc["abc"_s] == "ABC"); + REQUIRE(cdoc["abc"_s] == "ABC"); + REQUIRE(doc["abc\0d"_s] == "ABCD"); + REQUIRE(cdoc["abc\0d"_s] == "ABCD"); + } + + SECTION("JsonVariant") { + doc["key1"] = "abc"; + doc["key2"] = "abc\0d"_s; + doc["key3"] = "foo"; + + CHECK(doc[doc["key1"]] == "ABC"); + CHECK(doc[doc["key2"]] == "ABCD"); + CHECK(doc[doc["key3"]] == nullptr); + CHECK(doc[doc["key4"]] == nullptr); + + CHECK(cdoc[cdoc["key1"]] == "ABC"); + CHECK(cdoc[cdoc["key2"]] == "ABCD"); + CHECK(cdoc[cdoc["key3"]] == nullptr); + CHECK(cdoc[cdoc["key4"]] == nullptr); + } + + SECTION("supports operator|") { + REQUIRE((doc["abc"] | "nope") == "ABC"_s); + REQUIRE((doc["def"] | "nope") == "nope"_s); + } + +#if defined(HAS_VARIABLE_LENGTH_ARRAY) && \ + !defined(SUBSCRIPT_CONFLICTS_WITH_BUILTIN_OPERATOR) + SECTION("supports VLAs") { + size_t i = 16; + char vla[i]; + strcpy(vla, "hello"); + + doc[vla] = "world"; + + REQUIRE(doc[vla] == "world"); + REQUIRE(cdoc[vla] == "world"); + } +#endif + } + + SECTION("array") { + deserializeJson(doc, "[\"hello\",\"world\"]"); + + SECTION("int") { + REQUIRE(doc[1] == "world"); + REQUIRE(cdoc[1] == "world"); + } + + SECTION("JsonVariant") { + doc[2] = 1; + REQUIRE(doc[doc[2]] == "world"); + REQUIRE(cdoc[doc[2]] == "world"); + } + } +} + +TEST_CASE("JsonDocument automatically promotes to object") { + JsonDocument doc; + + doc["one"]["two"]["three"] = 4; + + REQUIRE(doc["one"]["two"]["three"] == 4); +} + +TEST_CASE("JsonDocument automatically promotes to array") { + JsonDocument doc; + + doc[2] = 2; + + REQUIRE(doc.as() == "[null,null,2]"); +} + +TEST_CASE("JsonDocument::operator[] key storage") { + SpyingAllocator spy; + JsonDocument doc(&spy); + + SECTION("string literal") { + doc["hello"] = 0; + + REQUIRE(doc.as() == "{\"hello\":0}"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + }); + } + + SECTION("const char*") { + const char* key = "hello"; + doc[key] = 0; + + REQUIRE(doc.as() == "{\"hello\":0}"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("hello")), + }); + } + + SECTION("char[]") { + char key[] = "hello"; + doc[key] = 0; + + REQUIRE(doc.as() == "{\"hello\":0}"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("hello")), + }); + } + + SECTION("std::string") { + doc["hello"_s] = 0; + + REQUIRE(doc.as() == "{\"hello\":0}"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("hello")), + }); + } +#if defined(HAS_VARIABLE_LENGTH_ARRAY) && \ + !defined(SUBSCRIPT_CONFLICTS_WITH_BUILTIN_OPERATOR) + SECTION("VLA") { + size_t i = 16; + char vla[i]; + strcpy(vla, "hello"); + + doc[vla] = 0; + + REQUIRE(doc.as() == "{\"hello\":0}"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("hello")), + }); + } +#endif +} diff --git a/extras/tests/JsonDocument/swap.cpp b/extras/tests/JsonDocument/swap.cpp new file mode 100644 index 000000000..353830896 --- /dev/null +++ b/extras/tests/JsonDocument/swap.cpp @@ -0,0 +1,25 @@ +#include + +#include +#include +#include + +using namespace std; + +TEST_CASE("std::swap") { + SECTION("JsonDocument*") { + JsonDocument *p1, *p2; + swap(p1, p2); // issue #1678 + } + + SECTION("JsonDocument") { + JsonDocument doc1, doc2; + doc1.set("hello"); + doc2.set("world"); + + swap(doc1, doc2); + + CHECK(doc1.as() == "world"); + CHECK(doc2.as() == "hello"); + } +} diff --git a/extras/tests/JsonObject/CMakeLists.txt b/extras/tests/JsonObject/CMakeLists.txt new file mode 100644 index 000000000..3f44d9860 --- /dev/null +++ b/extras/tests/JsonObject/CMakeLists.txt @@ -0,0 +1,25 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2025, Benoit BLANCHON +# MIT License + +add_executable(JsonObjectTests + clear.cpp + compare.cpp + equals.cpp + isNull.cpp + iterator.cpp + nesting.cpp + remove.cpp + set.cpp + size.cpp + std_string.cpp + subscript.cpp + unbound.cpp +) + +add_test(JsonObject JsonObjectTests) + +set_tests_properties(JsonObject + PROPERTIES + LABELS "Catch" +) diff --git a/extras/tests/JsonObject/clear.cpp b/extras/tests/JsonObject/clear.cpp new file mode 100644 index 000000000..f6f8a2213 --- /dev/null +++ b/extras/tests/JsonObject/clear.cpp @@ -0,0 +1,25 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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") { + JsonDocument doc; + JsonObject obj = doc.to(); + obj["hello"] = 1; + obj["world"] = 2; + obj.clear(); + REQUIRE(obj.size() == 0); + REQUIRE(obj.isNull() == false); + } +} diff --git a/extras/tests/JsonObject/compare.cpp b/extras/tests/JsonObject/compare.cpp new file mode 100644 index 000000000..faa0cbd0a --- /dev/null +++ b/extras/tests/JsonObject/compare.cpp @@ -0,0 +1,512 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("Compare JsonObject with JsonObject") { + JsonDocument 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.add(); + object1["a"] = 1; + object1["b"] = "hello"; + object1["c"][0] = false; + + JsonObject object2 = doc.add(); + 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.add(); + object1["a"] = 1; + object1["b"] = "hello1"; + object1["c"][0] = false; + + JsonObject object2 = doc.add(); + 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") { + JsonDocument 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.add(); + object["a"] = 1; + object["b"] = "hello"; + object["c"][0] = false; + + JsonVariant variant = doc.add(); + 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.add(); + object["a"] = 1; + object["b"] = "hello1"; + object["c"][0] = false; + + JsonVariant variant = doc.add(); + 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") { + JsonDocument 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.add(); + object["a"] = 1; + object["b"] = "hello"; + object["c"][0] = false; + + JsonObject object2 = doc.add(); + 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.add(); + object["a"] = 1; + object["b"] = "hello1"; + object["c"][0] = false; + + JsonObject object2 = doc.add(); + 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") { + JsonDocument 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.add(); + object1["a"] = 1; + object1["b"] = "hello"; + object1["c"][0] = false; + + JsonObject object2 = doc.add(); + 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.add(); + object1["a"] = 1; + object1["b"] = "hello1"; + object1["c"][0] = false; + + JsonObject object2 = doc.add(); + 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") { + JsonDocument 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.add(); + object1["a"] = 1; + object1["b"] = "hello"; + object1["c"][0] = false; + JsonObjectConst carray1 = object1; + + JsonObject object2 = doc.add(); + 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.add(); + object1["a"] = 1; + object1["b"] = "hello1"; + object1["c"][0] = false; + JsonObjectConst carray1 = object1; + + JsonObject object2 = doc.add(); + 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") { + JsonDocument 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.add(); + object1["a"] = 1; + object1["b"] = "hello"; + object1["c"][0] = false; + JsonObjectConst carray1 = object1; + + JsonObject object2 = doc.add(); + 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.add(); + object1["a"] = 1; + object1["b"] = "hello1"; + object1["c"][0] = false; + JsonObjectConst carray1 = object1; + + JsonObject object2 = doc.add(); + 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/extras/tests/JsonObject/equals.cpp b/extras/tests/JsonObject/equals.cpp new file mode 100644 index 000000000..4a594a78f --- /dev/null +++ b/extras/tests/JsonObject/equals.cpp @@ -0,0 +1,59 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonObject::operator==()") { + JsonDocument doc1; + JsonObject obj1 = doc1.to(); + + JsonDocument doc2; + JsonObject obj2 = doc2.to(); + + SECTION("should return false when objs differ") { + obj1["hello"] = "coucou"; + obj2["world"] = 1; + + REQUIRE_FALSE(obj1 == obj2); + } + + SECTION("should return false when LHS has more elements") { + obj1["hello"] = "coucou"; + obj1["world"] = 666; + obj2["hello"] = "coucou"; + + REQUIRE_FALSE(obj1 == obj2); + } + + SECTION("should return false when RKS has more elements") { + obj1["hello"] = "coucou"; + obj2["hello"] = "coucou"; + obj2["world"] = 666; + + REQUIRE_FALSE(obj1 == obj2); + } + + 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); + } + + SECTION("should return false when RHS is null") { + JsonObject null; + + REQUIRE_FALSE(obj1 == null); + } + + SECTION("should return false when LHS is null") { + JsonObject null; + + REQUIRE_FALSE(null == obj2); + } +} diff --git a/extras/tests/JsonObject/isNull.cpp b/extras/tests/JsonObject/isNull.cpp new file mode 100644 index 000000000..8ddb51c70 --- /dev/null +++ b/extras/tests/JsonObject/isNull.cpp @@ -0,0 +1,32 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonObject::isNull()") { + SECTION("returns true") { + JsonObject obj; + REQUIRE(obj.isNull() == true); + } + + SECTION("returns false") { + JsonDocument doc; + JsonObject 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") { + JsonDocument doc; + JsonObject obj = doc.to(); + REQUIRE(static_cast(obj) == true); + } +} diff --git a/extras/tests/JsonObject/iterator.cpp b/extras/tests/JsonObject/iterator.cpp new file mode 100644 index 000000000..e22d72ad7 --- /dev/null +++ b/extras/tests/JsonObject/iterator.cpp @@ -0,0 +1,36 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonObject::begin()/end()") { + JsonDocument 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()); + } +} diff --git a/extras/tests/JsonObject/nesting.cpp b/extras/tests/JsonObject/nesting.cpp new file mode 100644 index 000000000..a3fdaea19 --- /dev/null +++ b/extras/tests/JsonObject/nesting.cpp @@ -0,0 +1,35 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonObject::nesting()") { + JsonDocument doc; + 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["nested"].to(); + REQUIRE(obj.nesting() == 2); + } + + SECTION("returns 2 with nested object") { + obj["nested"].to(); + REQUIRE(obj.nesting() == 2); + } +} diff --git a/extras/tests/JsonObject/remove.cpp b/extras/tests/JsonObject/remove.cpp new file mode 100644 index 000000000..052433dfe --- /dev/null +++ b/extras/tests/JsonObject/remove.cpp @@ -0,0 +1,89 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include +#include + +TEST_CASE("JsonObject::remove()") { + JsonDocument doc; + 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; + ++it; + 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()); + } + + SECTION("remove(JsonVariant)") { + obj["key"] = "b"; + obj.remove(obj["key"]); + REQUIRE("{\"a\":0,\"c\":2,\"key\":\"b\"}" == doc.as()); + } +} diff --git a/extras/tests/JsonObject/set.cpp b/extras/tests/JsonObject/set.cpp new file mode 100644 index 000000000..e5c3044d8 --- /dev/null +++ b/extras/tests/JsonObject/set.cpp @@ -0,0 +1,142 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +TEST_CASE("JsonObject::set()") { + SpyingAllocator spy; + JsonDocument doc1(&spy); + JsonDocument doc2(&spy); + + JsonObject obj1 = doc1.to(); + JsonObject obj2 = doc2.to(); + + SECTION("doesn't copy static string in key or value") { + obj1["hello"] = "world"; + spy.clearLog(); + + bool success = obj2.set(obj1); + + REQUIRE(success == true); + REQUIRE(obj2["hello"] == "world"_s); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + }); + } + + SECTION("copy local string value") { + obj1["hello"] = "world"_s; + spy.clearLog(); + + bool success = obj2.set(obj1); + + REQUIRE(success == true); + REQUIRE(obj2["hello"] == "world"_s); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("world")), + }); + } + + SECTION("copy local key") { + obj1["hello"_s] = "world"; + spy.clearLog(); + + bool success = obj2.set(obj1); + + REQUIRE(success == true); + REQUIRE(obj2["hello"] == "world"_s); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("hello")), + }); + } + + SECTION("copy string from deserializeJson()") { + deserializeJson(doc1, "{'hello':'world'}"); + spy.clearLog(); + + bool success = obj2.set(obj1); + + REQUIRE(success == true); + REQUIRE(obj2["hello"] == "world"_s); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("hello")), + Allocate(sizeofString("world")), + }); + } + + SECTION("copy string from deserializeMsgPack()") { + deserializeMsgPack(doc1, "\x81\xA5hello\xA5world"); + spy.clearLog(); + + bool success = obj2.set(obj1); + + REQUIRE(success == true); + REQUIRE(obj2["hello"] == "world"_s); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("hello")), + Allocate(sizeofString("world")), + }); + } + + SECTION("should work with JsonObjectConst") { + obj1["hello"] = "world"; + + obj2.set(static_cast(obj1)); + + REQUIRE(obj2["hello"] == "world"_s); + } + + SECTION("copy fails in the middle of an object") { + TimebombAllocator timebomb(2); + JsonDocument doc3(&timebomb); + JsonObject obj3 = doc3.to(); + + obj1["alpha"_s] = 1; + obj1["beta"_s] = 2; + + bool success = obj3.set(obj1); + + REQUIRE(success == false); + REQUIRE(doc3.as() == "{\"alpha\":1}"); + } + + SECTION("copy fails in the middle of an array") { + TimebombAllocator timebomb(1); + JsonDocument doc3(&timebomb); + JsonObject obj3 = doc3.to(); + + obj1["hello"][0] = "world"_s; + + bool success = obj3.set(obj1); + + REQUIRE(success == false); + REQUIRE(doc3.as() == "{\"hello\":[]}"); + } + + 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/extras/tests/JsonObject/size.cpp b/extras/tests/JsonObject/size.cpp new file mode 100644 index 000000000..5c5258e77 --- /dev/null +++ b/extras/tests/JsonObject/size.cpp @@ -0,0 +1,39 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include +#include + +TEST_CASE("JsonObject::size()") { + JsonDocument doc; + 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/extras/tests/JsonObject/std_string.cpp b/extras/tests/JsonObject/std_string.cpp new file mode 100644 index 000000000..82b87b980 --- /dev/null +++ b/extras/tests/JsonObject/std_string.cpp @@ -0,0 +1,61 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Literals.hpp" + +static void eraseString(std::string& str) { + char* p = const_cast(str.c_str()); + while (*p) + *p++ = '*'; +} + +TEST_CASE("std::string") { + JsonDocument doc; + + SECTION("operator[]") { + char json[] = "{\"key\":\"value\"}"; + + deserializeJson(doc, json); + JsonObject obj = doc.as(); + + REQUIRE("value"_s == obj["key"_s]); + } + + SECTION("operator[] const") { + char json[] = "{\"key\":\"value\"}"; + + deserializeJson(doc, json); + JsonObject obj = doc.as(); + + REQUIRE("value"_s == obj["key"_s]); + } + + SECTION("remove()") { + JsonObject obj = doc.to(); + obj["key"] = "value"; + + obj.remove("key"_s); + + REQUIRE(0 == obj.size()); + } + + SECTION("operator[], set key") { + std::string key("hello"); + JsonObject obj = doc.to(); + obj[key] = "world"; + eraseString(key); + REQUIRE("world"_s == obj["hello"]); + } + + SECTION("operator[], set value") { + std::string value("world"); + JsonObject obj = doc.to(); + obj["hello"] = value; + eraseString(value); + REQUIRE("world"_s == obj["hello"]); + } +} diff --git a/extras/tests/JsonObject/subscript.cpp b/extras/tests/JsonObject/subscript.cpp new file mode 100644 index 000000000..bdf900f95 --- /dev/null +++ b/extras/tests/JsonObject/subscript.cpp @@ -0,0 +1,267 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +TEST_CASE("JsonObject::operator[]") { + SpyingAllocator spy; + JsonDocument doc(&spy); + 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("h3110"_s == obj["hello"].as()); + } + + SECTION("array") { + JsonDocument doc2; + JsonArray arr = doc2.to(); + + obj["hello"] = arr; + + REQUIRE(arr == obj["hello"].as()); + REQUIRE(true == obj["hello"].is()); + REQUIRE(false == obj["hello"].is()); + } + + SECTION("object") { + JsonDocument doc2; + 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") { + JsonDocument doc2; + JsonArray arr = doc2.to(); + arr.add(42); + + obj["a"] = arr[0]; + + REQUIRE(42 == obj["a"]); + } + + SECTION("object subscript") { + JsonDocument doc2; + 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"; + REQUIRE(spy.log() == AllocatorLog{Allocate(sizeofPool())}); + } + + SECTION("should duplicate char* value") { + obj["hello"] = const_cast("world"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("world")), + }); + } + + SECTION("should duplicate char* key") { + obj[const_cast("hello")] = "world"; + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("hello")), + }); + } + + SECTION("should duplicate char* key&value") { + obj[const_cast("hello")] = const_cast("world"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("hello")), + Allocate(sizeofString("world")), + }); + } + + SECTION("should duplicate std::string value") { + obj["hello"] = "world"_s; + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("world")), + }); + } + + SECTION("should duplicate std::string key") { + obj["hello"_s] = "world"; + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("hello")), + }); + } + + SECTION("should duplicate std::string key&value") { + obj["hello"_s] = "world"_s; + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("hello")), + Allocate(sizeofString("world")), + }); + } + + SECTION("should duplicate a non-static JsonString key") { + obj[JsonString("hello", false)] = "world"; + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("hello")), + }); + } + + SECTION("should not duplicate a static JsonString key") { + obj[JsonString("hello", true)] = "world"; + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + }); + } + + 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("world"_s == obj["hello"]); + } + + SECTION("obj[str] = VLA") { // issue #416 + size_t i = 32; + char vla[i]; + strcpy(vla, "world"); + + obj["hello"] = vla; + + REQUIRE("world"_s == obj["hello"].as()); + } + + SECTION("obj.set(VLA, str)") { + size_t i = 16; + char vla[i]; + strcpy(vla, "hello"); + + obj[vla] = "world"; + + REQUIRE("world"_s == obj["hello"]); + } + + SECTION("obj.set(str, VLA)") { + size_t i = 32; + char vla[i]; + strcpy(vla, "world"); + + obj["hello"].set(vla); + + REQUIRE("world"_s == obj["hello"].as()); + } + + SECTION("obj[VLA]") { + size_t i = 16; + char vla[i]; + strcpy(vla, "hello"); + + deserializeJson(doc, "{\"hello\":\"world\"}"); + + obj = doc.as(); + REQUIRE("world"_s == obj[vla]); + } +#endif + + SECTION("chain") { + obj["hello"]["world"] = 123; + + REQUIRE(123 == obj["hello"]["world"].as()); + REQUIRE(true == obj["hello"]["world"].is()); + REQUIRE(false == obj["hello"]["world"].is()); + } + + SECTION("JsonVariant") { + obj["hello"] = "world"; + obj["a\0b"_s] = "ABC"; + + doc["key1"] = "hello"; + doc["key2"] = "a\0b"_s; + doc["key3"] = "foo"; + + REQUIRE(obj[obj["key1"]] == "world"); + REQUIRE(obj[obj["key2"]] == "ABC"); + REQUIRE(obj[obj["key3"]] == nullptr); + REQUIRE(obj[obj["key4"]] == nullptr); + } +} diff --git a/extras/tests/JsonObject/unbound.cpp b/extras/tests/JsonObject/unbound.cpp new file mode 100644 index 000000000..030050214 --- /dev/null +++ b/extras/tests/JsonObject/unbound.cpp @@ -0,0 +1,27 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +using namespace Catch::Matchers; + +TEST_CASE("Unbound JsonObject") { + JsonObject obj; + + SECTION("retrieve member") { + REQUIRE(obj["key"].isNull()); + } + + SECTION("add member") { + obj["hello"] = "world"; + REQUIRE(0 == obj.size()); + } + + SECTION("serialize") { + char buffer[32]; + serializeJson(obj, buffer, sizeof(buffer)); + REQUIRE_THAT(buffer, Equals("null")); + } +} diff --git a/extras/tests/JsonObjectConst/CMakeLists.txt b/extras/tests/JsonObjectConst/CMakeLists.txt new file mode 100644 index 000000000..9eb114426 --- /dev/null +++ b/extras/tests/JsonObjectConst/CMakeLists.txt @@ -0,0 +1,19 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2025, Benoit BLANCHON +# MIT License + +add_executable(JsonObjectConstTests + equals.cpp + isNull.cpp + iterator.cpp + nesting.cpp + size.cpp + subscript.cpp +) + +add_test(JsonObjectConst JsonObjectConstTests) + +set_tests_properties(JsonObjectConst + PROPERTIES + LABELS "Catch" +) diff --git a/extras/tests/JsonObjectConst/equals.cpp b/extras/tests/JsonObjectConst/equals.cpp new file mode 100644 index 000000000..c1ad6ff34 --- /dev/null +++ b/extras/tests/JsonObjectConst/equals.cpp @@ -0,0 +1,65 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonObjectConst::operator==()") { + JsonDocument doc1; + JsonObjectConst obj1 = doc1.to(); + + JsonDocument doc2; + JsonObjectConst obj2 = doc2.to(); + + SECTION("should return false when objs differ") { + doc1["hello"] = "coucou"; + doc2["world"] = 1; + + REQUIRE_FALSE(obj1 == obj2); + } + + SECTION("should return false when LHS has more elements") { + doc1["hello"] = "coucou"; + doc1["world"] = 666; + doc2["hello"] = "coucou"; + + REQUIRE_FALSE(obj1 == obj2); + } + + SECTION("should return false when RKS has more elements") { + doc1["hello"] = "coucou"; + doc2["hello"] = "coucou"; + doc2["world"] = 666; + + REQUIRE_FALSE(obj1 == obj2); + } + + SECTION("should return true when objs equal") { + doc1["hello"] = "world"; + doc1["anwser"] = 42; + // insert in different order + doc2["anwser"] = 42; + doc2["hello"] = "world"; + + REQUIRE(obj1 == obj2); + } + + SECTION("should return false when RHS is null") { + JsonObjectConst null; + + REQUIRE_FALSE(obj1 == null); + } + + SECTION("should return false when LHS is null") { + JsonObjectConst null; + + REQUIRE_FALSE(null == obj2); + } + + SECTION("should return true when both are null") { + JsonObjectConst null1, null2; + + REQUIRE(null1 == null2); + } +} diff --git a/extras/tests/JsonObjectConst/isNull.cpp b/extras/tests/JsonObjectConst/isNull.cpp new file mode 100644 index 000000000..c88b9d735 --- /dev/null +++ b/extras/tests/JsonObjectConst/isNull.cpp @@ -0,0 +1,32 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonObjectConst::isNull()") { + SECTION("returns true") { + JsonObjectConst obj; + REQUIRE(obj.isNull() == true); + } + + SECTION("returns false") { + JsonDocument doc; + JsonObjectConst obj = doc.to(); + REQUIRE(obj.isNull() == false); + } +} + +TEST_CASE("JsonObjectConst::operator bool()") { + SECTION("returns false") { + JsonObjectConst obj; + REQUIRE(static_cast(obj) == false); + } + + SECTION("returns true") { + JsonDocument doc; + JsonObjectConst obj = doc.to(); + REQUIRE(static_cast(obj) == true); + } +} diff --git a/extras/tests/JsonObjectConst/iterator.cpp b/extras/tests/JsonObjectConst/iterator.cpp new file mode 100644 index 000000000..3b474f4f7 --- /dev/null +++ b/extras/tests/JsonObjectConst/iterator.cpp @@ -0,0 +1,39 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonObjectConst::begin()/end()") { + JsonDocument doc; + JsonObjectConst obj = doc.to(); + doc["ab"] = 12; + doc["cd"] = 34; + + SECTION("Iteration") { + JsonObjectConst::iterator it = obj.begin(); + REQUIRE(obj.end() != it); + REQUIRE(it->key() == "ab"); + REQUIRE(12 == it->value()); + + ++it; + REQUIRE(obj.end() != it); + JsonPairConst pair = *it; + REQUIRE(pair.key() == "cd"); + REQUIRE(34 == pair.value()); + + ++it; + REQUIRE(obj.end() == it); + } + + SECTION("Dereferencing end() is safe") { + REQUIRE(obj.end()->key().isNull()); + REQUIRE(obj.end()->value().isNull()); + } + + SECTION("null JsonObjectConst") { + JsonObjectConst null; + REQUIRE(null.begin() == null.end()); + } +} diff --git a/extras/tests/JsonObjectConst/nesting.cpp b/extras/tests/JsonObjectConst/nesting.cpp new file mode 100644 index 000000000..6d72cdfb0 --- /dev/null +++ b/extras/tests/JsonObjectConst/nesting.cpp @@ -0,0 +1,35 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonObjectConst::nesting()") { + JsonDocument doc; + JsonObjectConst obj = doc.to(); + + SECTION("return 0 if unbound") { + JsonObjectConst unbound; + REQUIRE(unbound.nesting() == 0); + } + + SECTION("returns 1 for empty object") { + REQUIRE(obj.nesting() == 1); + } + + SECTION("returns 1 for flat object") { + doc["hello"] = "world"; + REQUIRE(obj.nesting() == 1); + } + + SECTION("returns 2 with nested array") { + doc["nested"].to(); + REQUIRE(obj.nesting() == 2); + } + + SECTION("returns 2 with nested object") { + doc["nested"].to(); + REQUIRE(obj.nesting() == 2); + } +} diff --git a/extras/tests/JsonObjectConst/size.cpp b/extras/tests/JsonObjectConst/size.cpp new file mode 100644 index 000000000..10e1e13cc --- /dev/null +++ b/extras/tests/JsonObjectConst/size.cpp @@ -0,0 +1,22 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include +#include + +TEST_CASE("JsonObjectConst::size()") { + JsonDocument doc; + JsonObjectConst obj = doc.to(); + + SECTION("returns 0 when empty") { + REQUIRE(0 == obj.size()); + } + + SECTION("returns the number of members") { + doc["hello"] = 1; + doc["world"] = 2; + REQUIRE(2 == obj.size()); + } +} diff --git a/extras/tests/JsonObjectConst/subscript.cpp b/extras/tests/JsonObjectConst/subscript.cpp new file mode 100644 index 000000000..d611b3c2e --- /dev/null +++ b/extras/tests/JsonObjectConst/subscript.cpp @@ -0,0 +1,46 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +TEST_CASE("JsonObjectConst::operator[]") { + JsonDocument doc; + doc["hello"] = "world"; + doc["a\0b"_s] = "ABC"; + JsonObjectConst obj = doc.as(); + + SECTION("supports const char*") { + REQUIRE(obj["hello"] == "world"); // issue #2019 + } + + SECTION("supports std::string") { + REQUIRE(obj["hello"_s] == "world"); // issue #2019 + REQUIRE(obj["a\0b"_s] == "ABC"); + } + +#if defined(HAS_VARIABLE_LENGTH_ARRAY) && \ + !defined(SUBSCRIPT_CONFLICTS_WITH_BUILTIN_OPERATOR) + SECTION("supports VLA") { + size_t i = 16; + char vla[i]; + strcpy(vla, "hello"); + + REQUIRE(obj[vla] == "world"_s); + } +#endif + + SECTION("supports JsonVariant") { + doc["key1"] = "hello"; + doc["key2"] = "a\0b"_s; + doc["key3"] = "foo"; + REQUIRE(obj[obj["key1"]] == "world"); + REQUIRE(obj[obj["key2"]] == "ABC"); + REQUIRE(obj[obj["key3"]] == nullptr); + REQUIRE(obj[obj["key4"]] == nullptr); + } +} diff --git a/extras/tests/JsonSerializer/CMakeLists.txt b/extras/tests/JsonSerializer/CMakeLists.txt new file mode 100644 index 000000000..28ba51e22 --- /dev/null +++ b/extras/tests/JsonSerializer/CMakeLists.txt @@ -0,0 +1,22 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2025, 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/extras/tests/JsonSerializer/CustomWriter.cpp b/extras/tests/JsonSerializer/CustomWriter.cpp new file mode 100644 index 000000000..8e7f1de67 --- /dev/null +++ b/extras/tests/JsonSerializer/CustomWriter.cpp @@ -0,0 +1,51 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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") { + JsonDocument doc; + 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/extras/tests/JsonSerializer/JsonArray.cpp b/extras/tests/JsonSerializer/JsonArray.cpp new file mode 100644 index 000000000..f33c15230 --- /dev/null +++ b/extras/tests/JsonSerializer/JsonArray.cpp @@ -0,0 +1,105 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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)") { + JsonDocument 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("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("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("OneEmptyNestedArray") { + array.add(); + + check(array, "[[]]"); + } + + SECTION("OneEmptyNestedHash") { + array.add(); + + check(array, "[{}]"); + } +} diff --git a/extras/tests/JsonSerializer/JsonArrayPretty.cpp b/extras/tests/JsonSerializer/JsonArrayPretty.cpp new file mode 100644 index 000000000..7939bd99f --- /dev/null +++ b/extras/tests/JsonSerializer/JsonArrayPretty.cpp @@ -0,0 +1,75 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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)") { + JsonDocument doc; + 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.add(); + array.add(); + + checkArray(array, + "[\r\n" + " [],\r\n" + " []\r\n" + "]"); + } + + SECTION("NestedArrays") { + JsonArray nested1 = array.add(); + nested1.add(1); + nested1.add(2); + + JsonObject nested2 = array.add(); + 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/extras/tests/JsonSerializer/JsonObject.cpp b/extras/tests/JsonSerializer/JsonObject.cpp new file mode 100644 index 000000000..c21d16d1e --- /dev/null +++ b/extras/tests/JsonSerializer/JsonObject.cpp @@ -0,0 +1,119 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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)") { + JsonDocument doc; + 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") { + JsonDocument b; + JsonDocument c; + + obj["a"].to(); + obj["b"] = b.to(); + obj["c"] = c.to(); + + checkObject(obj, "{\"a\":[],\"b\":[],\"c\":[]}"); + } + + SECTION("ThreeNestedObjects") { + JsonDocument b; + JsonDocument c; + + obj["a"].to(); + obj["b"] = b.to(); + obj["c"] = c.to(); + + checkObject(obj, "{\"a\":{},\"b\":{},\"c\":{}}"); + } +} diff --git a/extras/tests/JsonSerializer/JsonObjectPretty.cpp b/extras/tests/JsonSerializer/JsonObjectPretty.cpp new file mode 100644 index 000000000..24e32fbd8 --- /dev/null +++ b/extras/tests/JsonSerializer/JsonObjectPretty.cpp @@ -0,0 +1,77 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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)") { + JsonDocument doc; + 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["key1"].to(); + obj["key2"].to(); + + checkObjectPretty(obj, + "{\r\n" + " \"key1\": {},\r\n" + " \"key2\": []\r\n" + "}"); + } + + SECTION("NestedContainers") { + JsonObject nested1 = obj["key1"].to(); + nested1["a"] = 1; + + JsonArray nested2 = obj["key2"].to(); + 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/extras/tests/JsonSerializer/JsonVariant.cpp b/extras/tests/JsonSerializer/JsonVariant.cpp new file mode 100644 index 000000000..dcb8aeea5 --- /dev/null +++ b/extras/tests/JsonSerializer/JsonVariant.cpp @@ -0,0 +1,132 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include +#include + +#include "Literals.hpp" + +template +void check(T value, const std::string& expected) { + JsonDocument doc; + 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("hello"_s, "\"hello\""); + + SECTION("Escape quotation mark") { + check("hello \"world\""_s, "\"hello \\\"world\\\"\""); + } + + SECTION("Escape reverse solidus") { + check("hello\\world"_s, "\"hello\\\\world\""); + } + + SECTION("Don't escape solidus") { + check("fifty/fifty"_s, "\"fifty/fifty\""); + } + + SECTION("Don't escape single quote") { + check("hello'world"_s, "\"hello'world\""); + } + + SECTION("Escape backspace") { + check("hello\bworld"_s, "\"hello\\bworld\""); + } + + SECTION("Escape formfeed") { + check("hello\fworld"_s, "\"hello\\fworld\""); + } + + SECTION("Escape linefeed") { + check("hello\nworld"_s, "\"hello\\nworld\""); + } + + SECTION("Escape carriage return") { + check("hello\rworld"_s, "\"hello\\rworld\""); + } + + SECTION("Escape tab") { + check("hello\tworld"_s, "\"hello\\tworld\""); + } + + SECTION("NUL char") { + check("hello\0world"_s, "\"hello\\u0000world\""); + } + } + + SECTION("SerializedValue") { + check(serialized("[1,2]"), "[1,2]"); + } + + SECTION("SerializedValue") { + check(serialized("[1,2]"_s), "[1,2]"); + } + + SECTION("Double") { + check(3.1415927, "3.1415927"); + } + + SECTION("Float") { + REQUIRE(sizeof(float) == 4); + check(3.1415927f, "3.141593"); + } + + 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/extras/tests/JsonSerializer/misc.cpp b/extras/tests/JsonSerializer/misc.cpp new file mode 100644 index 000000000..46d7da5a5 --- /dev/null +++ b/extras/tests/JsonSerializer/misc.cpp @@ -0,0 +1,36 @@ +#include +#include +#include + +TEST_CASE("serializeJson(MemberProxy)") { + JsonDocument doc; + deserializeJson(doc, "{\"hello\":42}"); + JsonObject obj = doc.as(); + std::string result; + + serializeJson(obj["hello"], result); + + REQUIRE(result == "42"); +} + +TEST_CASE("serializeJson(ElementProxy)") { + JsonDocument doc; + deserializeJson(doc, "[42]"); + JsonArray arr = doc.as(); + std::string result; + + serializeJson(arr[0], result); + + REQUIRE(result == "42"); +} + +TEST_CASE("serializeJson(JsonVariantSubscript)") { + JsonDocument doc; + deserializeJson(doc, "[42]"); + JsonVariant var = doc.as(); + std::string result; + + serializeJson(var[0], result); + + REQUIRE(result == "42"); +} diff --git a/extras/tests/JsonSerializer/std_stream.cpp b/extras/tests/JsonSerializer/std_stream.cpp new file mode 100644 index 000000000..28fd6f7f4 --- /dev/null +++ b/extras/tests/JsonSerializer/std_stream.cpp @@ -0,0 +1,66 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include +#include + +TEST_CASE("operator<<(std::ostream)") { + JsonDocument doc; + 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/extras/tests/JsonSerializer/std_string.cpp b/extras/tests/JsonSerializer/std_string.cpp new file mode 100644 index 000000000..0d2342905 --- /dev/null +++ b/extras/tests/JsonSerializer/std_string.cpp @@ -0,0 +1,58 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Literals.hpp" + +TEST_CASE("serialize JsonArray to std::string") { + JsonDocument doc; + JsonArray array = doc.to(); + array.add(4); + array.add(2); + + SECTION("serializeJson()") { + std::string json = "erase me"; + serializeJson(array, json); + + REQUIRE("[4,2]" == json); + } + + SECTION("serializeJsonPretty") { + std::string json = "erase me"; + serializeJsonPretty(array, json); + + REQUIRE("[\r\n 4,\r\n 2\r\n]" == json); + } +} + +TEST_CASE("serialize JsonObject to std::string") { + JsonDocument doc; + JsonObject obj = doc.to(); + obj["key"] = "value"; + + SECTION("object") { + std::string json = "erase me"; + serializeJson(doc, json); + + REQUIRE("{\"key\":\"value\"}" == json); + } + + SECTION("serializeJsonPretty") { + std::string json = "erase me"; + serializeJsonPretty(doc, json); + + REQUIRE("{\r\n \"key\": \"value\"\r\n}" == json); + } +} + +TEST_CASE("serialize an std::string containing a NUL") { + JsonDocument doc; + doc.set("hello\0world"_s); + + std::string json = "erase me"; + serializeJson(doc, json); + CHECK("\"hello\\u0000world\"" == json); +} diff --git a/extras/tests/JsonVariant/CMakeLists.txt b/extras/tests/JsonVariant/CMakeLists.txt new file mode 100644 index 000000000..6aec75fc6 --- /dev/null +++ b/extras/tests/JsonVariant/CMakeLists.txt @@ -0,0 +1,33 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2025, Benoit BLANCHON +# MIT License + +add_executable(JsonVariantTests + add.cpp + as.cpp + clear.cpp + compare.cpp + converters.cpp + copy.cpp + is.cpp + isnull.cpp + misc.cpp + nesting.cpp + nullptr.cpp + or.cpp + overflow.cpp + remove.cpp + set.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/extras/tests/JsonVariant/add.cpp b/extras/tests/JsonVariant/add.cpp new file mode 100644 index 000000000..3aaa72443 --- /dev/null +++ b/extras/tests/JsonVariant/add.cpp @@ -0,0 +1,128 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +TEST_CASE("JsonVariant::add(T)") { + JsonDocument doc; + JsonVariant var = doc.to(); + + SECTION("add integer to new variant") { + var.add(42); + + REQUIRE(var.as() == "[42]"); + } + + SECTION("add const char* to new variant") { + var.add("hello"); + + REQUIRE(var.as() == "[\"hello\"]"); + } + + SECTION("add std::string to new variant") { + var.add("hello"_s); + + 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}"); + } + +#ifdef HAS_VARIABLE_LENGTH_ARRAY + SECTION("supports VLAs") { + size_t i = 16; + char vla[i]; + strcpy(vla, "hello"); + + var.add(vla); + + REQUIRE(var.as() == "[\"hello\"]"); + } +#endif +} + +TEST_CASE("JsonVariant::add()") { + JsonDocument doc; + JsonVariant var = doc.to(); + + SECTION("JsonArray") { + JsonArray array = var.add(); + array.add(1); + array.add(2); + REQUIRE(doc.as() == "[[1,2]]"); + } + + SECTION("JsonVariant") { + JsonVariant variant = var.add(); + variant.set(42); + REQUIRE(doc.as() == "[42]"); + } +} + +TEST_CASE("JsonObject::add(JsonObject) ") { + JsonDocument doc1; + doc1["hello"_s] = "world"_s; + + TimebombAllocator allocator(10); + SpyingAllocator spy(&allocator); + JsonDocument doc2(&spy); + JsonVariant variant = doc2.to(); + + SECTION("success") { + bool result = variant.add(doc1.as()); + + REQUIRE(result == true); + REQUIRE(doc2.as() == "[{\"hello\":\"world\"}]"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("hello")), + Allocate(sizeofString("world")), + }); + } + + SECTION("partial failure") { // issue #2081 + allocator.setCountdown(2); + + bool result = variant.add(doc1.as()); + + REQUIRE(result == false); + REQUIRE(doc2.as() == "[]"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("hello")), + AllocateFail(sizeofString("world")), + Deallocate(sizeofString("hello")), + }); + } + + SECTION("complete failure") { + allocator.setCountdown(0); + + bool result = variant.add(doc1.as()); + + REQUIRE(result == false); + REQUIRE(doc2.as() == "[]"); + REQUIRE(spy.log() == AllocatorLog{ + AllocateFail(sizeofPool()), + }); + } +} diff --git a/extras/tests/JsonVariant/as.cpp b/extras/tests/JsonVariant/as.cpp new file mode 100644 index 000000000..b1235725f --- /dev/null +++ b/extras/tests/JsonVariant/as.cpp @@ -0,0 +1,327 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include +#include + +#include "Literals.hpp" + +namespace my { +using ArduinoJson::detail::isinf; +} // namespace my + +enum MY_ENUM { ONE = 1, TWO = 2 }; + +TEST_CASE("JsonVariant::as()") { + static const char* null = 0; + + JsonDocument doc; + 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()); + REQUIRE(variant.as().data() == nullptr); + REQUIRE(variant.as().data() == nullptr); + } + + SECTION("set(float)") { + variant.set(4.2f); + + REQUIRE(variant.as()); + REQUIRE(0 == variant.as()); + REQUIRE(variant.as() == "4.2"); + REQUIRE(variant.as() == 4L); + REQUIRE(variant.as() == 4.2f); + REQUIRE(variant.as() == 4U); + REQUIRE(variant.as().isNull()); + REQUIRE(variant.as().data() == nullptr); + REQUIRE(variant.as().data() == nullptr); + } + + SECTION("set(double)") { + variant.set(4.2); + + REQUIRE(variant.as()); + REQUIRE(0 == variant.as()); + REQUIRE(variant.as() == "4.2"); + REQUIRE(variant.as() == 4L); + REQUIRE(variant.as() == 4.2); + REQUIRE(variant.as() == 4U); + REQUIRE(variant.as().isNull()); + REQUIRE(variant.as().data() == nullptr); + REQUIRE(variant.as().data() == nullptr); + } + + SECTION("set(0.0)") { + variant.set(0.0); + + REQUIRE(variant.as() == false); + REQUIRE(variant.as() == 0L); + REQUIRE(variant.as().isNull()); + REQUIRE(variant.as().data() == nullptr); + REQUIRE(variant.as().data() == nullptr); + } + + 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()); + REQUIRE(variant.as().data() == nullptr); + REQUIRE(variant.as().data() == nullptr); + } + + 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()); + REQUIRE(variant.as().data() == nullptr); + REQUIRE(variant.as().data() == nullptr); + } + + SECTION("set(uint32_t)") { + variant.set(4294967295U); + + REQUIRE(variant.as() == true); + REQUIRE(variant.as() == 4294967295.0); + REQUIRE(variant.as() == 0); + REQUIRE(variant.as() == 4294967295U); + REQUIRE(variant.as() == 4294967295U); + REQUIRE(variant.as() == "4294967295"); + REQUIRE(variant.as().isNull()); + REQUIRE(variant.as().data() == nullptr); + REQUIRE(variant.as().data() == nullptr); + } + + SECTION("set(int32_t)") { + variant.set(-2147483648LL); + + REQUIRE(variant.as() == true); + REQUIRE(variant.as() == -2147483648LL); + REQUIRE(variant.as() == -2147483648LL); + REQUIRE(variant.as() == -2147483648LL); + REQUIRE(variant.as() == 0); + REQUIRE(variant.as() == 0); + REQUIRE(variant.as() == "-2147483648"); + REQUIRE(variant.as().isNull()); + REQUIRE(variant.as().data() == nullptr); + REQUIRE(variant.as().data() == nullptr); + } + + SECTION("set(uint64_t)") { + variant.set(4294967296U); + + REQUIRE(variant.as() == true); + REQUIRE(variant.as() == 4294967296.0); + REQUIRE(variant.as() == 0); + REQUIRE(variant.as() == 0); + REQUIRE(variant.as() == 4294967296U); + REQUIRE(variant.as() == "4294967296"); + REQUIRE(variant.as().isNull()); + REQUIRE(variant.as().data() == nullptr); + REQUIRE(variant.as().data() == nullptr); + } + + SECTION("set(int64_t)") { + variant.set(-2147483649LL); + + REQUIRE(variant.as() == true); + REQUIRE(variant.as() == -2147483649LL); + REQUIRE(variant.as() == 0); + REQUIRE(variant.as() == -2147483649LL); + REQUIRE(variant.as() == 0); + REQUIRE(variant.as() == 0); + REQUIRE(variant.as() == "-2147483649"); + REQUIRE(variant.as().isNull()); + REQUIRE(variant.as().data() == nullptr); + REQUIRE(variant.as().data() == nullptr); + } + + 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() == "42"); + REQUIRE(variant.as().isStatic() == true); + } + + SECTION("set(\"hello\")") { + variant.set("hello"); + + REQUIRE(variant.as() == true); + REQUIRE(variant.as() == 0L); + REQUIRE(variant.as() == "hello"_s); + REQUIRE(variant.as() == "hello"_s); + REQUIRE(variant.as() == "hello"_s); + REQUIRE(variant.as() == "hello"); + } + + SECTION("set(std::string(\"4.2\")) (tiny string optimization)") { + variant.set("4.2"_s); + + REQUIRE(variant.as() == true); + REQUIRE(variant.as() == 4L); + REQUIRE(variant.as() == Approx(4.2)); + REQUIRE(variant.as() == "4.2"_s); + REQUIRE(variant.as() == "4.2"_s); + REQUIRE(variant.as() == "4.2"); + REQUIRE(variant.as().isStatic() == false); + } + + SECTION("set(std::string(\"123.45\"))") { + variant.set("123.45"_s); + + REQUIRE(variant.as() == true); + REQUIRE(variant.as() == 123L); + REQUIRE(variant.as() == Approx(123.45)); + REQUIRE(variant.as() == "123.45"_s); + REQUIRE(variant.as() == "123.45"_s); + REQUIRE(variant.as() == "123.45"); + REQUIRE(variant.as().isStatic() == 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("set(serialized(\"hello\"))") { + variant.set(serialized("hello")); + + REQUIRE(variant.as().data() == nullptr); + REQUIRE(variant.as().data() == nullptr); + } + + SECTION("to()") { + JsonObject obj = variant.to(); + obj["key"] = "value"; + + SECTION("as()") { + REQUIRE(variant.as() == true); + } + + SECTION("as()") { + REQUIRE(variant.as() == "{\"key\":\"value\"}"_s); + } + + SECTION("ObjectAsJsonObject") { + JsonObject o = variant.as(); + REQUIRE(o.size() == 1); + REQUIRE(o["key"] == "value"_s); + } + } + + SECTION("to()") { + JsonArray arr = variant.to(); + arr.add(4); + arr.add(2); + + SECTION("as()") { + REQUIRE(variant.as() == true); + } + + SECTION("as()") { + REQUIRE(variant.as() == "[4,2]"_s); + } + + 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("Biggest int64 positive") { + variant.set("9223372036854775807"); + REQUIRE(variant.as() == 9223372036854775807); + } +#endif + + SECTION("as()") { + variant.set(1); + + REQUIRE(variant.as() == ONE); + } +} diff --git a/extras/tests/JsonVariant/clear.cpp b/extras/tests/JsonVariant/clear.cpp new file mode 100644 index 000000000..6078d6b38 --- /dev/null +++ b/extras/tests/JsonVariant/clear.cpp @@ -0,0 +1,40 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +TEST_CASE("JsonVariant::clear()") { + SpyingAllocator spy; + JsonDocument doc(&spy); + 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); + } + + SECTION("releases owned string") { + var.set("hello"_s); + var.clear(); + + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofString("hello")), + Deallocate(sizeofString("hello")), + }); + } +} diff --git a/extras/tests/JsonVariant/compare.cpp b/extras/tests/JsonVariant/compare.cpp new file mode 100644 index 000000000..719566ed9 --- /dev/null +++ b/extras/tests/JsonVariant/compare.cpp @@ -0,0 +1,352 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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") { + JsonDocument 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") { + JsonDocument 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("MsgPackBinary('abc') vs MsgPackBinary('abc')") { + a.set(MsgPackBinary("abc", 4)); + b.set(MsgPackBinary("abc", 4)); + + CHECK(a == b); + CHECK(a <= b); + CHECK(a >= b); + CHECK_FALSE(a != b); + CHECK_FALSE(a < b); + CHECK_FALSE(a > b); + } + + SECTION("MsgPackBinary('abc') vs MsgPackBinary('bcd')") { + a.set(MsgPackBinary("abc", 4)); + b.set(MsgPackBinary("bcd", 4)); + + CHECK(a != b); + CHECK(a < b); + CHECK(a <= b); + CHECK_FALSE(a == b); + CHECK_FALSE(a > b); + CHECK_FALSE(a >= b); + } + + SECTION("MsgPackBinary('bcd') vs MsgPackBinary('abc')") { + a.set(MsgPackBinary("bcd", 4)); + b.set(MsgPackBinary("abc", 4)); + + 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/extras/tests/JsonVariant/converters.cpp b/extras/tests/JsonVariant/converters.cpp new file mode 100644 index 000000000..10d738542 --- /dev/null +++ b/extras/tests/JsonVariant/converters.cpp @@ -0,0 +1,142 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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") { + JsonDocument doc; + + 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") { + JsonDocument doc; + + 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); + } +} diff --git a/extras/tests/JsonVariant/copy.cpp b/extras/tests/JsonVariant/copy.cpp new file mode 100644 index 000000000..b5da71f57 --- /dev/null +++ b/extras/tests/JsonVariant/copy.cpp @@ -0,0 +1,142 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include +#include "Allocators.hpp" + +#include "Literals.hpp" + +TEST_CASE("JsonVariant::set(JsonVariant)") { + KillswitchAllocator killswitch; + SpyingAllocator spyingAllocator(&killswitch); + JsonDocument doc1(&spyingAllocator); + JsonDocument doc2(&spyingAllocator); + JsonVariant var1 = doc1.to(); + JsonVariant var2 = doc2.to(); + + SECTION("stores JsonArray by copy") { + JsonArray arr = doc2.to(); + JsonObject obj = arr.add(); + 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["value"].to(); + arr.add(42); + + var1.set(obj); + + obj["value"] = 666; + REQUIRE(var1.as() == "{\"value\":[42]}"); + } + + SECTION("stores const char* by reference") { + var1.set("hello!!"); + spyingAllocator.clearLog(); + + var2.set(var1); + + REQUIRE(spyingAllocator.log() == AllocatorLog{}); + } + + SECTION("stores char* by copy") { + char str[] = "hello!!"; + var1.set(str); + spyingAllocator.clearLog(); + + var2.set(var1); + + REQUIRE(spyingAllocator.log() == AllocatorLog{ + Allocate(sizeofString("hello!!")), + }); + } + + SECTION("fails gracefully if string allocation fails") { + char str[] = "hello!!"; + var1.set(str); + killswitch.on(); + spyingAllocator.clearLog(); + + var2.set(var1); + + REQUIRE(doc2.overflowed() == true); + REQUIRE(spyingAllocator.log() == AllocatorLog{ + AllocateFail(sizeofString("hello!!")), + }); + } + + SECTION("stores std::string by copy") { + var1.set("hello!!"_s); + spyingAllocator.clearLog(); + + var2.set(var1); + + REQUIRE(spyingAllocator.log() == AllocatorLog{ + Allocate(sizeofString("hello!!")), + }); + } + + SECTION("stores Serialized by copy") { + var1.set(serialized("hello!!", 7)); + spyingAllocator.clearLog(); + + var2.set(var1); + + REQUIRE(spyingAllocator.log() == AllocatorLog{ + Allocate(sizeofString("hello!!")), + }); + } + + SECTION("stores Serialized by copy") { + char str[] = "hello!!"; + var1.set(serialized(str, 7)); + spyingAllocator.clearLog(); + + var2.set(var1); + + REQUIRE(spyingAllocator.log() == AllocatorLog{ + Allocate(sizeofString("hello!!")), + }); + } + + SECTION("stores Serialized by copy") { + var1.set(serialized("hello!!"_s)); + spyingAllocator.clearLog(); + + var2.set(var1); + + REQUIRE(spyingAllocator.log() == AllocatorLog{ + Allocate(sizeofString("hello!!")), + }); + } + + SECTION("fails gracefully if raw string allocation fails") { + var1.set(serialized("hello!!"_s)); + killswitch.on(); + spyingAllocator.clearLog(); + + var2.set(var1); + + REQUIRE(doc2.overflowed() == true); + REQUIRE(spyingAllocator.log() == AllocatorLog{ + AllocateFail(sizeofString("hello!!")), + }); + } + + SECTION("destination is unbound") { + JsonVariant unboundVariant; + + unboundVariant.set(var1); + + REQUIRE(unboundVariant.isUnbound()); + REQUIRE(unboundVariant.isNull()); + } +} diff --git a/extras/tests/JsonVariant/is.cpp b/extras/tests/JsonVariant/is.cpp new file mode 100644 index 000000000..9e38b7bee --- /dev/null +++ b/extras/tests/JsonVariant/is.cpp @@ -0,0 +1,164 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +enum MYENUM2 { ONE = 1, TWO = 2 }; + +TEST_CASE("JsonVariant::is()") { + JsonDocument doc; + 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); + } +} diff --git a/extras/tests/JsonVariant/isnull.cpp b/extras/tests/JsonVariant/isnull.cpp new file mode 100644 index 000000000..7683eb8ff --- /dev/null +++ b/extras/tests/JsonVariant/isnull.cpp @@ -0,0 +1,72 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonVariant::isNull()") { + JsonDocument doc; + 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") { + JsonDocument doc2; + JsonArray array = doc2.to(); + + variant.set(array); + REQUIRE(variant.isNull() == false); + } + + SECTION("returns false when EmptyObject") { + JsonDocument doc2; + 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); + } +} diff --git a/extras/tests/JsonVariant/misc.cpp b/extras/tests/JsonVariant/misc.cpp new file mode 100644 index 000000000..629834423 --- /dev/null +++ b/extras/tests/JsonVariant/misc.cpp @@ -0,0 +1,60 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("VariantData") { + REQUIRE(std::is_standard_layout::value == + true); +} + +TEST_CASE("StringNode") { + 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") { + JsonDocument doc; + 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") { + JsonDocument doc; + 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/extras/tests/JsonVariant/nesting.cpp b/extras/tests/JsonVariant/nesting.cpp new file mode 100644 index 000000000..cb4e35166 --- /dev/null +++ b/extras/tests/JsonVariant/nesting.cpp @@ -0,0 +1,31 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonVariant::nesting()") { + JsonDocument doc; + 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/extras/tests/JsonVariant/nullptr.cpp b/extras/tests/JsonVariant/nullptr.cpp new file mode 100644 index 000000000..434ba5c86 --- /dev/null +++ b/extras/tests/JsonVariant/nullptr.cpp @@ -0,0 +1,43 @@ +#include + +#include + +TEST_CASE("nullptr") { + JsonDocument doc; + 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/extras/tests/JsonVariant/or.cpp b/extras/tests/JsonVariant/or.cpp new file mode 100644 index 000000000..588689938 --- /dev/null +++ b/extras/tests/JsonVariant/or.cpp @@ -0,0 +1,159 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonVariant::operator|()") { + JsonDocument doc; + 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/extras/tests/JsonVariant/overflow.cpp b/extras/tests/JsonVariant/overflow.cpp new file mode 100644 index 000000000..00dbed708 --- /dev/null +++ b/extras/tests/JsonVariant/overflow.cpp @@ -0,0 +1,72 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +template +void shouldBeOk(TIn value) { + JsonDocument doc; + JsonVariant var = doc.to(); + var.set(value); + REQUIRE(var.as() == TOut(value)); +} + +template +void shouldOverflow(TIn value) { + JsonDocument 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/extras/tests/JsonVariant/remove.cpp b/extras/tests/JsonVariant/remove.cpp new file mode 100644 index 000000000..2926cfef7 --- /dev/null +++ b/extras/tests/JsonVariant/remove.cpp @@ -0,0 +1,128 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +using ArduinoJson::detail::sizeofArray; + +TEST_CASE("JsonVariant::remove(int)") { + SpyingAllocator spy; + JsonDocument doc(&spy); + + SECTION("release top level strings") { + doc.add("hello"_s); + doc.add("hello"_s); + doc.add("world"_s); + + JsonVariant var = doc.as(); + REQUIRE(var.as() == "[\"hello\",\"hello\",\"world\"]"); + + spy.clearLog(); + var.remove(1); + REQUIRE(var.as() == "[\"hello\",\"world\"]"); + REQUIRE(spy.log() == AllocatorLog{}); + + spy.clearLog(); + var.remove(1); + REQUIRE(var.as() == "[\"hello\"]"); + REQUIRE(spy.log() == AllocatorLog{ + Deallocate(sizeofString("world")), + }); + + spy.clearLog(); + var.remove(0); + REQUIRE(var.as() == "[]"); + REQUIRE(spy.log() == AllocatorLog{ + Deallocate(sizeofString("hello")), + }); + } + + SECTION("release strings in nested array") { + doc[0][0] = "hello"_s; + + JsonVariant var = doc.as(); + REQUIRE(var.as() == "[[\"hello\"]]"); + + spy.clearLog(); + var.remove(0); + + REQUIRE(var.as() == "[]"); + REQUIRE(spy.log() == AllocatorLog{ + Deallocate(sizeofString("hello")), + }); + } +} + +TEST_CASE("JsonVariant::remove(const char *)") { + JsonDocument doc; + JsonVariant var = doc.to(); + + var["a"] = 1; + var["b"] = 2; + + var.remove("a"); + + REQUIRE(var.as() == "{\"b\":2}"); +} + +TEST_CASE("JsonVariant::remove(std::string)") { + JsonDocument doc; + JsonVariant var = doc.to(); + + var["a"] = 1; + var["b"] = 2; + + var.remove("b"_s); + + REQUIRE(var.as() == "{\"a\":1}"); +} + +#ifdef HAS_VARIABLE_LENGTH_ARRAY +TEST_CASE("JsonVariant::remove(VLA)") { + JsonDocument doc; + JsonVariant var = doc.to(); + + var["a"] = 1; + var["b"] = 2; + size_t i = 16; + char vla[i]; + strcpy(vla, "b"); + + var.remove("b"_s); + + REQUIRE(var.as() == "{\"a\":1}"); +} +#endif + +TEST_CASE("JsonVariant::remove(JsonVariant) from object") { + JsonDocument doc; + JsonVariant var = doc.to(); + + var["a"] = "a"; + var["b"] = 2; + var["c"] = "b"; + + var.remove(var["c"]); + + REQUIRE(var.as() == "{\"a\":\"a\",\"c\":\"b\"}"); +} + +TEST_CASE("JsonVariant::remove(JsonVariant) from array") { + JsonDocument doc; + JsonVariant var = doc.to(); + + var[0] = 3; + var[1] = 2; + var[2] = 1; + + var.remove(var[2]); + var.remove(var[3]); // noop + + REQUIRE(var.as() == "[3,1]"); +} diff --git a/extras/tests/JsonVariant/set.cpp b/extras/tests/JsonVariant/set.cpp new file mode 100644 index 000000000..7d56818b0 --- /dev/null +++ b/extras/tests/JsonVariant/set.cpp @@ -0,0 +1,407 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +using ArduinoJson::detail::sizeofObject; + +enum ErrorCode { ERROR_01 = 1, ERROR_10 = 10 }; + +TEST_CASE("JsonVariant::set() when there is enough memory") { + SpyingAllocator spy; + JsonDocument doc(&spy); + JsonVariant variant = doc.to(); + + SECTION("string literal") { + bool result = variant.set("hello\0world"); + + REQUIRE(result == true); + CHECK(variant == + "hello"_s); // linked string cannot contain '\0' at the moment + CHECK(spy.log() == AllocatorLog{}); + } + + SECTION("const char*") { + char str[16]; + + strcpy(str, "hello"); + bool result = variant.set(static_cast(str)); + strcpy(str, "world"); + + REQUIRE(result == true); + REQUIRE(variant == "hello"); // stores by copy + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofString("hello")), + }); + } + + SECTION("(const char*)0") { + bool result = variant.set(static_cast(0)); + + REQUIRE(result == true); + REQUIRE(variant.isNull()); + REQUIRE(variant.as() == nullptr); + REQUIRE(spy.log() == AllocatorLog{}); + } + + 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 + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofString("hello")), + }); + } + + SECTION("char* (tiny string optimization)") { + char str[16]; + + strcpy(str, "abc"); + bool result = variant.set(str); + strcpy(str, "def"); + + REQUIRE(result == true); + REQUIRE(variant == "abc"); // stores by copy + REQUIRE(spy.log() == AllocatorLog{}); + } + + SECTION("(char*)0") { + bool result = variant.set(static_cast(0)); + + REQUIRE(result == true); + REQUIRE(variant.isNull()); + REQUIRE(spy.log() == AllocatorLog{}); + } + + 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 + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofString("hello")), + }); + } + + 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 + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofString("hello")), + }); + } + +#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 + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofString("hello")), + }); + } +#endif + + SECTION("std::string") { + std::string str = "hello\0world"_s; + bool result = variant.set(str); + str.replace(0, 5, "world"); + + REQUIRE(result == true); + REQUIRE(variant == "hello\0world"_s); // stores by copy + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofString("hello?world")), + }); + } + + SECTION("static JsonString") { + char str[16]; + + strcpy(str, "hello"); + bool result = variant.set(JsonString(str, true)); + strcpy(str, "world"); + + REQUIRE(result == true); + REQUIRE(variant == "world"); // stores by pointer + REQUIRE(spy.log() == AllocatorLog{}); + } + + SECTION("non-static JsonString") { + char str[16]; + + strcpy(str, "hello"); + bool result = variant.set(JsonString(str)); + strcpy(str, "world"); + + REQUIRE(result == true); + REQUIRE(variant == "hello"); // stores by copy + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofString("hello")), + }); + } + + SECTION("enum") { + ErrorCode code = ERROR_10; + + bool result = variant.set(code); + + REQUIRE(result == true); + REQUIRE(variant.is() == true); + REQUIRE(variant.as() == 10); + REQUIRE(spy.log() == AllocatorLog{}); + } + + SECTION("float") { + bool result = variant.set(1.2f); + + REQUIRE(result == true); + REQUIRE(variant.is() == true); + REQUIRE(variant.as() == 1.2f); + REQUIRE(spy.log() == AllocatorLog{}); + } + + SECTION("double") { + bool result = variant.set(1.2); + doc.shrinkToFit(); + + REQUIRE(result == true); + REQUIRE(variant.is() == true); + REQUIRE(variant.as() == 1.2); + REQUIRE(spy.log() == + AllocatorLog{ + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofPool(1)), // one extension slot + }); + } + + SECTION("int32_t") { + bool result = variant.set(int32_t(42)); + + REQUIRE(result == true); + REQUIRE(variant.is() == true); + REQUIRE(variant.as() == 42); + REQUIRE(spy.log() == AllocatorLog{}); + } + + SECTION("int64_t") { + bool result = variant.set(int64_t(-2147483649LL)); + doc.shrinkToFit(); + + REQUIRE(result == true); + REQUIRE(variant.is() == true); + REQUIRE(variant.as() == -2147483649LL); + REQUIRE(spy.log() == + AllocatorLog{ + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofPool(1)), // one extension slot + }); + } + + SECTION("uint32_t") { + bool result = variant.set(uint32_t(42)); + + REQUIRE(result == true); + REQUIRE(variant.is() == true); + REQUIRE(variant.as() == 42); + REQUIRE(spy.log() == AllocatorLog{}); + } + + SECTION("uint64_t") { + bool result = variant.set(uint64_t(4294967296)); + doc.shrinkToFit(); + + REQUIRE(result == true); + REQUIRE(variant.is() == true); + REQUIRE(variant.as() == 4294967296); + REQUIRE(spy.log() == + AllocatorLog{ + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofPool(1)), // one extension slot + }); + } + + SECTION("JsonDocument") { + JsonDocument doc1; + doc1["hello"] = "world"; + + // Should copy the doc + variant.set(doc1); + doc1.clear(); + + std::string json; + serializeJson(doc, json); + REQUIRE(json == "{\"hello\":\"world\"}"); + } +} + +TEST_CASE("JsonVariant::set() with not enough memory") { + JsonDocument doc(FailingAllocator::instance()); + + JsonVariant v = doc.to(); + + SECTION("std::string") { + bool result = v.set("hello world!!"_s); + + REQUIRE(result == false); + REQUIRE(v.isNull()); + } + + SECTION("Serialized") { + bool result = v.set(serialized("hello world!!"_s)); + + REQUIRE(result == false); + REQUIRE(v.isNull()); + } + + SECTION("char*") { + char s[] = "hello world!!"; + bool result = v.set(s); + + REQUIRE(result == false); + REQUIRE(v.isNull()); + } + + SECTION("float") { + bool result = v.set(1.2f); + + REQUIRE(result == true); + REQUIRE(v.is()); + } + + SECTION("double") { + bool result = v.set(1.2); + + REQUIRE(result == false); + REQUIRE(v.isNull()); + } + + SECTION("int32_t") { + bool result = v.set(-42); + + REQUIRE(result == true); + REQUIRE(v.is()); + } + + SECTION("int64_t") { + bool result = v.set(-2147483649LL); + + REQUIRE(result == false); + REQUIRE(v.isNull()); + } + + SECTION("uint32_t") { + bool result = v.set(42); + + REQUIRE(result == true); + REQUIRE(v.is()); + } + + SECTION("uint64_t") { + bool result = v.set(4294967296U); + + REQUIRE(result == false); + REQUIRE(v.isNull()); + } +} + +TEST_CASE("JsonVariant::set() releases the previous value") { + SpyingAllocator spy; + JsonDocument doc(&spy); + doc["hello"] = "world"_s; + spy.clearLog(); + + JsonVariant v = doc["hello"]; + + SECTION("int") { + v.set(42); + REQUIRE(spy.log() == AllocatorLog{ + Deallocate(sizeofString("world")), + }); + } + + SECTION("bool") { + v.set(false); + REQUIRE(spy.log() == AllocatorLog{ + Deallocate(sizeofString("world")), + }); + } + + SECTION("const char*") { + v.set("hello"); + REQUIRE(spy.log() == AllocatorLog{ + Deallocate(sizeofString("world")), + }); + } + + SECTION("float") { + v.set(1.2); + REQUIRE(spy.log() == AllocatorLog{ + Deallocate(sizeofString("world")), + }); + } + + SECTION("Serialized") { + v.set(serialized("[]")); + REQUIRE(spy.log() == AllocatorLog{ + Deallocate(sizeofString("world")), + Allocate(sizeofString("[]")), + }); + } +} + +TEST_CASE("JsonVariant::set() reuses extension slot") { + SpyingAllocator spy; + JsonDocument doc(&spy); + JsonVariant variant = doc.to(); + + variant.set(1.2); + doc.shrinkToFit(); + spy.clearLog(); + + SECTION("double") { + bool result = variant.set(3.4); + + REQUIRE(result == true); + REQUIRE(spy.log() == AllocatorLog{}); + } + + SECTION("int64_t") { + bool result = variant.set(-2147483649LL); + + REQUIRE(result == true); + REQUIRE(spy.log() == AllocatorLog{}); + } + + SECTION("uint64_t") { + bool result = variant.set(4294967296U); + + REQUIRE(result == true); + REQUIRE(spy.log() == AllocatorLog{}); + } +} diff --git a/extras/tests/JsonVariant/size.cpp b/extras/tests/JsonVariant/size.cpp new file mode 100644 index 000000000..e0c5bb42b --- /dev/null +++ b/extras/tests/JsonVariant/size.cpp @@ -0,0 +1,36 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonVariant::size()") { + JsonDocument doc; + 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/extras/tests/JsonVariant/stl_containers.cpp b/extras/tests/JsonVariant/stl_containers.cpp new file mode 100644 index 000000000..53a23fdcb --- /dev/null +++ b/extras/tests/JsonVariant/stl_containers.cpp @@ -0,0 +1,138 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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}; + + JsonDocument doc; + doc.set(v); + REQUIRE(doc.as() == "[1,2]"); + } + + SECTION("fromJson") { + JsonDocument 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") { + JsonDocument 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") { + using array_type = std::array; + + SECTION("toJson") { + array_type v; + v[0] = 1; + v[1] = 2; + + JsonDocument doc; + doc.set(v); + REQUIRE(doc.as() == "[1,2]"); + } + + SECTION("fromJson") { + JsonDocument 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") { + JsonDocument 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/extras/tests/JsonVariant/subscript.cpp b/extras/tests/JsonVariant/subscript.cpp new file mode 100644 index 000000000..0f9509c9a --- /dev/null +++ b/extras/tests/JsonVariant/subscript.cpp @@ -0,0 +1,159 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Literals.hpp" + +TEST_CASE("JsonVariant::operator[]") { + JsonDocument doc; + 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("element at index 0"_s == ); + REQUIRE("element at index 1"_s == var[1]); + REQUIRE("element at index 0"_s == + 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("world"_s == var[1]); + } + + SECTION("set value in a nested object") { + array.add(); + + var[0]["hello"] = "world"; + + REQUIRE(1 == var.size()); + REQUIRE(1 == var[0].size()); + REQUIRE("world"_s == 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("use JsonVariant as index") { + array.add("A"); + array.add("B"); + array.add(1); + + REQUIRE(var[var[2]] == "B"); + REQUIRE(var[var[3]].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 == var.size()); + REQUIRE("element at key \"a\""_s == var["a"]); + REQUIRE("element at key \"b\""_s == 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("world"_s == 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("world"_s == var["hello"]); + } + + SECTION("var[key].to()") { + JsonArray arr = var["hello"].to(); + REQUIRE(arr.isNull() == false); + } + + SECTION("use JsonVariant as key") { + object["a"] = "A"; + object["ab"] = "AB"; + object["ab\0c"_s] = "ABC"; + object["key1"] = "a"; + object["key2"] = "ab"; + object["key3"] = "ab\0c"_s; + object["key4"] = "foo"; + + REQUIRE(var[var["key1"]] == "A"); + REQUIRE(var[var["key2"]] == "AB"); + REQUIRE(var[var["key3"]] == "ABC"); + REQUIRE(var[var["key4"]].isNull()); + REQUIRE(var[var["key5"]].isNull()); + } + } + +#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("world"_s == 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("world"_s == variant[vla]); + } +#endif +} diff --git a/extras/tests/JsonVariant/types.cpp b/extras/tests/JsonVariant/types.cpp new file mode 100644 index 000000000..26a6265ef --- /dev/null +++ b/extras/tests/JsonVariant/types.cpp @@ -0,0 +1,168 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include +#include +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +template +void checkReference(T& expected) { + JsonVariant variant = expected; + REQUIRE(expected == variant.as()); +} + +template +void checkNumericType() { + JsonDocument docMin, docMax; + 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()") { + SpyingAllocator spy; + JsonDocument doc(&spy); + JsonVariant variant = doc.to(); + +#if ARDUINOJSON_USE_LONG_LONG + SECTION("SizeOfJsonInteger") { + REQUIRE(8 == sizeof(JsonInteger)); + } +#endif + + // /!\ Most test were moved to `JsonVariant/set.cpp` + // TODO: move the remaining tests too + + SECTION("False") { + variant.set(false); + REQUIRE(variant.as() == false); + REQUIRE(spy.log() == AllocatorLog{}); + } + + SECTION("True") { + variant.set(true); + REQUIRE(variant.as() == true); + REQUIRE(spy.log() == AllocatorLog{}); + } + + 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") { + JsonDocument doc2; + JsonObject object = doc2.to(); + + variant.set(object); + REQUIRE(variant.is()); + REQUIRE(variant.as() == object); + } +} + +TEST_CASE("volatile") { + JsonDocument doc; + JsonVariant variant = doc.to(); + + SECTION("volatile bool") { // issue #2029 + volatile bool f = true; + variant.set(f); + CHECK(variant.is() == true); + CHECK(variant.as() == true); + } + + 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/extras/tests/JsonVariant/unbound.cpp b/extras/tests/JsonVariant/unbound.cpp new file mode 100644 index 000000000..a19a8c418 --- /dev/null +++ b/extras/tests/JsonVariant/unbound.cpp @@ -0,0 +1,80 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Literals.hpp" + +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()); + CHECK(variant.as().data() == nullptr); + CHECK(variant.as().size() == 0); + CHECK(variant.as().data() == nullptr); + CHECK(variant.as().size() == 0); + } + + 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(serialized("42"_s))); + CHECK_FALSE(variant.set(true)); + CHECK_FALSE(variant.set(MsgPackBinary("hello", 5))); + CHECK_FALSE(variant.set(MsgPackExtension(1, "hello", 5))); + } + + 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["key"_s].set(1)); + } + + SECTION("remove()") { + variant.remove(0); + variant.remove("hello"); + } +} diff --git a/extras/tests/JsonVariantConst/CMakeLists.txt b/extras/tests/JsonVariantConst/CMakeLists.txt new file mode 100644 index 000000000..1cff558ce --- /dev/null +++ b/extras/tests/JsonVariantConst/CMakeLists.txt @@ -0,0 +1,19 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2025, Benoit BLANCHON +# MIT License + +add_executable(JsonVariantConstTests + as.cpp + is.cpp + isnull.cpp + nesting.cpp + size.cpp + subscript.cpp +) + +add_test(JsonVariantConst JsonVariantConstTests) + +set_tests_properties(JsonVariantConst + PROPERTIES + LABELS "Catch" +) diff --git a/extras/tests/JsonVariantConst/as.cpp b/extras/tests/JsonVariantConst/as.cpp new file mode 100644 index 000000000..8584ff5fd --- /dev/null +++ b/extras/tests/JsonVariantConst/as.cpp @@ -0,0 +1,42 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include +#include + +#include "Literals.hpp" + +TEST_CASE("JsonVariantConst::as()") { + JsonDocument doc; + JsonVariantConst var = doc.to(); + + doc.set("hello"); + + REQUIRE(var.as() == true); + REQUIRE(var.as() == 0L); + REQUIRE(var.as() == "hello"_s); + REQUIRE(var.as() == "hello"_s); +} + +TEST_CASE("Invalid conversions") { + using namespace ArduinoJson::detail; + + JsonVariantConst variant; + + CHECK(is_same()), int>::value); + CHECK(is_same()), float>::value); + CHECK(is_same()), + JsonVariantConst>::value); + CHECK( + is_same()), JsonObjectConst>::value); + CHECK(is_same()), JsonArrayConst>::value); + + CHECK(is_same()), + InvalidConversion>::value); + CHECK(is_same()), + InvalidConversion>::value); + CHECK(is_same()), + InvalidConversion>::value); +} diff --git a/extras/tests/JsonVariantConst/is.cpp b/extras/tests/JsonVariantConst/is.cpp new file mode 100644 index 000000000..32c16ac51 --- /dev/null +++ b/extras/tests/JsonVariantConst/is.cpp @@ -0,0 +1,162 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +enum MYENUM2 { ONE = 1, TWO = 2 }; + +TEST_CASE("JsonVariantConst::is()") { + JsonDocument doc; + JsonVariantConst var = doc.to(); + + SECTION("unbound") { + var = JsonVariantConst(); + + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + } + + SECTION("null") { + CHECK(var.is() == true); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + } + + SECTION("true") { + doc.set(true); + + CHECK(var.is() == true); + CHECK(var.is() == true); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + } + + SECTION("false") { + doc.set(false); + + CHECK(var.is() == true); + CHECK(var.is() == true); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + } + + SECTION("int") { + doc.set(42); + + CHECK(var.is() == true); + CHECK(var.is() == true); + CHECK(var.is() == true); + CHECK(var.is() == true); + CHECK(var.is() == true); + CHECK(var.is() == true); + CHECK(var.is() == true); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + } + + SECTION("double") { + doc.set(4.2); + + CHECK(var.is() == true); + CHECK(var.is() == true); + CHECK(var.is() == true); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + } + + SECTION("const char*") { + doc.set("4.2"); + + CHECK(var.is() == true); + CHECK(var.is() == true); + CHECK(var.is() == true); + CHECK(var.is() == true); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + } + + SECTION("JsonArray") { + doc.to(); + + CHECK(var.is() == true); + CHECK(var.is() == true); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + } + + SECTION("JsonObject") { + doc.to(); + + CHECK(var.is() == true); + CHECK(var.is() == true); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + CHECK(var.is() == false); + } +} diff --git a/extras/tests/JsonVariantConst/isnull.cpp b/extras/tests/JsonVariantConst/isnull.cpp new file mode 100644 index 000000000..30996db13 --- /dev/null +++ b/extras/tests/JsonVariantConst/isnull.cpp @@ -0,0 +1,21 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonVariantConst::isNull()") { + JsonDocument doc; + JsonVariantConst variant = doc.to(); + + SECTION("returns true when undefined") { + REQUIRE(variant.isNull() == true); + } + + SECTION("returns false if value is integer") { + doc.set(42); + + REQUIRE(variant.isNull() == false); + } +} diff --git a/extras/tests/JsonVariantConst/nesting.cpp b/extras/tests/JsonVariantConst/nesting.cpp new file mode 100644 index 000000000..4f035db15 --- /dev/null +++ b/extras/tests/JsonVariantConst/nesting.cpp @@ -0,0 +1,31 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonVariantConst::nesting()") { + JsonDocument doc; + JsonVariantConst var = doc.to(); + + SECTION("return 0 if unbound") { + JsonVariantConst unbound; + REQUIRE(unbound.nesting() == 0); + } + + SECTION("returns 0 for string") { + doc.set("hello"); + REQUIRE(var.nesting() == 0); + } + + SECTION("returns 1 for empty object") { + doc.to(); + REQUIRE(var.nesting() == 1); + } + + SECTION("returns 1 for empty array") { + doc.to(); + REQUIRE(var.nesting() == 1); + } +} diff --git a/extras/tests/JsonVariantConst/size.cpp b/extras/tests/JsonVariantConst/size.cpp new file mode 100644 index 000000000..9a6943e3c --- /dev/null +++ b/extras/tests/JsonVariantConst/size.cpp @@ -0,0 +1,36 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("JsonVariantConst::size()") { + JsonDocument doc; + JsonVariantConst variant = doc.to(); + + SECTION("unbound reference") { + JsonVariantConst unbound; + + CHECK(unbound.size() == 0); + } + + SECTION("int") { + doc.set(42); + + CHECK(variant.size() == 0); + } + + SECTION("string") { + doc.set("hello"); + + CHECK(variant.size() == 0); + } + + SECTION("object") { + doc["a"] = 1; + doc["b"] = 2; + + CHECK(variant.size() == 2); + } +} diff --git a/extras/tests/JsonVariantConst/subscript.cpp b/extras/tests/JsonVariantConst/subscript.cpp new file mode 100644 index 000000000..281e3d956 --- /dev/null +++ b/extras/tests/JsonVariantConst/subscript.cpp @@ -0,0 +1,104 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Literals.hpp" + +TEST_CASE("JsonVariantConst::operator[]") { + JsonDocument doc; + JsonVariantConst var = doc.to(); + + SECTION("null") { + REQUIRE(0 == var.size()); + REQUIRE(var["0"].isNull()); + REQUIRE(var[0].isNull()); + } + + SECTION("string") { + doc.set("hello world"); + REQUIRE(0 == var.size()); + REQUIRE(var["0"].isNull()); + REQUIRE(var[0].isNull()); + } + + SECTION("array") { + JsonArray array = doc.to(); + array.add("A"); + array.add("B"); + + SECTION("int") { + REQUIRE("A"_s == var[0]); + REQUIRE("B"_s == var[1]); + REQUIRE("A"_s == var[static_cast(0)]); // issue #381 + REQUIRE(var[666].isNull()); + REQUIRE(var[3].isNull()); + } + + SECTION("const char*") { + REQUIRE(var["0"].isNull()); + } + + SECTION("JsonVariant") { + array.add(1); + REQUIRE(var[var[2]] == "B"_s); + REQUIRE(var[var[3]].isNull()); + } + } + + SECTION("object") { + JsonObject object = doc.to(); + object["ab"_s] = "AB"; + object["abc"_s] = "ABC"; + object["abc\0d"_s] = "ABCD"; + + SECTION("string literal") { + REQUIRE(var["ab"] == "AB"_s); + REQUIRE(var["abc"] == "ABC"_s); + REQUIRE(var["abc\0d"] == "ABCD"_s); + REQUIRE(var["def"].isNull()); + REQUIRE(var[0].isNull()); + } + + SECTION("const char*") { + REQUIRE(var[static_cast("ab")] == "AB"_s); + REQUIRE(var[static_cast("abc")] == "ABC"_s); + REQUIRE(var[static_cast("abc\0d")] == "ABC"_s); + REQUIRE(var[static_cast("def")].isNull()); + REQUIRE(var[static_cast(0)].isNull()); + } + + SECTION("supports std::string") { + REQUIRE(var["ab"_s] == "AB"_s); + REQUIRE(var["abc"_s] == "ABC"_s); + REQUIRE(var["abc\0d"_s] == "ABCD"_s); + REQUIRE(var["def"_s].isNull()); + } + +#if defined(HAS_VARIABLE_LENGTH_ARRAY) && \ + !defined(SUBSCRIPT_CONFLICTS_WITH_BUILTIN_OPERATOR) + SECTION("supports VLA") { + size_t i = 16; + char vla[i]; + strcpy(vla, "abc"); + + REQUIRE(var[vla] == "ABC"_s); + } +#endif + + SECTION("supports JsonVariant") { + object["key1"] = "ab"; + object["key2"] = "abc"; + object["key3"] = "abc\0d"_s; + object["key4"] = "foo"; + + REQUIRE(var[var["key1"]] == "AB"_s); + REQUIRE(var[var["key2"]] == "ABC"_s); + REQUIRE(var[var["key3"]] == "ABCD"_s); + REQUIRE(var[var["key4"]].isNull()); + REQUIRE(var[var["key5"]].isNull()); + } + } +} diff --git a/extras/tests/Misc/CMakeLists.txt b/extras/tests/Misc/CMakeLists.txt new file mode 100644 index 000000000..66afc4f78 --- /dev/null +++ b/extras/tests/Misc/CMakeLists.txt @@ -0,0 +1,51 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2025, Benoit BLANCHON +# MIT License + +add_executable(MiscTests + arithmeticCompare.cpp + conflicts.cpp + issue1967.cpp + issue2129.cpp + issue2166.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" +) + +add_executable(Issue2181 + issue2181.cpp # Cannot be linked with other tests +) + +set_target_properties(Issue2181 PROPERTIES UNITY_BUILD OFF) + +add_test(Issue2181 Issue2181) + +set_tests_properties(Issue2181 + PROPERTIES + LABELS "Catch" +) + +if(CMAKE_CXX_COMPILER_ID MATCHES "Clang") + target_compile_options(Issue2181 + PRIVATE + -Wno-keyword-macro # keyword is hidden by macro definition + ) +endif() diff --git a/extras/tests/Misc/JsonString.cpp b/extras/tests/Misc/JsonString.cpp new file mode 100644 index 000000000..a66f77100 --- /dev/null +++ b/extras/tests/Misc/JsonString.cpp @@ -0,0 +1,103 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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.isStatic() == 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.isStatic() == false); + CHECK(s == "hello"); + CHECK(s != "hello world"); + } +} diff --git a/extras/tests/Misc/NoArduinoHeader.cpp b/extras/tests/Misc/NoArduinoHeader.cpp new file mode 100644 index 000000000..efcd8e451 --- /dev/null +++ b/extras/tests/Misc/NoArduinoHeader.cpp @@ -0,0 +1,20 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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/extras/tests/Misc/Readers.cpp b/extras/tests/Misc/Readers.cpp new file mode 100644 index 000000000..40772430c --- /dev/null +++ b/extras/tests/Misc/Readers.cpp @@ -0,0 +1,227 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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/extras/tests/Misc/StringAdapters.cpp b/extras/tests/Misc/StringAdapters.cpp new file mode 100644 index 000000000..991789752 --- /dev/null +++ b/extras/tests/Misc/StringAdapters.cpp @@ -0,0 +1,226 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include + +#include +#include +#include + +#include + +#include "custom_string.hpp" +#include "weird_strcmp.hpp" + +using ArduinoJson::JsonString; +using namespace ArduinoJson::detail; + +TEST_CASE("adaptString()") { + SECTION("string literal") { + auto s = adaptString("bravo\0alpha"); + + CHECK(s.isNull() == false); + CHECK(s.size() == 11); + CHECK(s.isStatic() == true); + } + + SECTION("null const char*") { + auto s = adaptString(static_cast(0)); + + CHECK(s.isNull() == true); + CHECK(s.size() == 0); + } + + SECTION("non-null const char*") { + const char* p = "bravo"; + auto s = adaptString(p); + + CHECK(s.isNull() == false); + CHECK(s.size() == 5); + CHECK(s.isStatic() == false); + CHECK(s.data() == p); + } + + SECTION("null const char* + size") { + auto s = adaptString(static_cast(0), 10); + + CHECK(s.isNull() == true); + CHECK(s.isStatic() == false); + } + + SECTION("non-null const char* + size") { + auto s = adaptString("bravo", 5); + + CHECK(s.isNull() == false); + CHECK(s.size() == 5); + CHECK(s.isStatic() == false); + } + + SECTION("null Flash string") { + auto s = adaptString(static_cast(0)); + + CHECK(s.isNull() == true); + CHECK(s.size() == 0); + CHECK(s.isStatic() == false); + } + + SECTION("non-null Flash string") { + auto s = adaptString(F("bravo")); + + CHECK(s.isNull() == false); + CHECK(s.size() == 5); + CHECK(s.isStatic() == false); + } + + SECTION("std::string") { + std::string orig("bravo"); + auto s = adaptString(orig); + + CHECK(s.isNull() == false); + CHECK(s.size() == 5); + CHECK(s.isStatic() == false); + } + + SECTION("Arduino String") { + ::String orig("bravo"); + auto s = adaptString(orig); + + CHECK(s.isNull() == false); + CHECK(s.size() == 5); + CHECK(s.isStatic() == false); + } + + SECTION("custom_string") { + custom_string orig("bravo"); + auto s = adaptString(orig); + + CHECK(s.isNull() == false); + CHECK(s.size() == 5); + CHECK(s.isStatic() == false); + } + + SECTION("JsonString linked") { + JsonString orig("hello", true); + auto s = adaptString(orig); + + CHECK(s.isNull() == false); + CHECK(s.size() == 5); + CHECK(s.isStatic() == true); + } + + SECTION("JsonString copied") { + JsonString orig("hello", false); + auto s = adaptString(orig); + + CHECK(s.isNull() == false); + CHECK(s.size() == 5); + CHECK(s.isStatic() == false); + } +} + +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::value == true); + CHECK(IsString<::String>::value == true); + CHECK(IsString<::StringSumHelper>::value == true); + CHECK(IsString::value == false); + CHECK(IsString::value == true); +} + +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/extras/tests/Misc/StringWriter.cpp b/extras/tests/Misc/StringWriter.cpp new file mode 100644 index 000000000..6c22720b4 --- /dev/null +++ b/extras/tests/Misc/StringWriter.cpp @@ -0,0 +1,157 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include + +#define ARDUINOJSON_STRING_BUFFER_SIZE 5 +#include + +#include + +#include "Literals.hpp" +#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("ABCD"_s == output); + } + + SECTION("TwoStrings") { + REQUIRE(4 == print(writer, "ABCD")); + REQUIRE(4 == print(writer, "EFGH")); + REQUIRE("ABCDEFGH"_s == 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)") { + JsonDocument doc; + doc["hello"] = "world"; + ::String output = "erase me"; + + 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/extras/tests/Misc/TypeTraits.cpp b/extras/tests/Misc/TypeTraits.cpp new file mode 100644 index 000000000..4fad79922 --- /dev/null +++ b/extras/tests/Misc/TypeTraits.cpp @@ -0,0 +1,236 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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); + } + + 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); + } + + SECTION("remove_cv") { + CHECK(is_same, int>::value); + CHECK(is_same, int>::value); + CHECK(is_same, int>::value); + CHECK(is_same, int>::value); + CHECK(is_same, decltype("toto")>::value); + } + + SECTION("decay") { + CHECK(is_same, int>::value); + CHECK(is_same, int>::value); + CHECK(is_same, int>::value); + CHECK(is_same, int*>::value); + CHECK(is_same, int*>::value); + CHECK(is_same, const char*>::value); + } +} + +TEST_CASE("is_std_string") { + REQUIRE(is_std_string::value == true); + REQUIRE(is_std_string::value == false); +} diff --git a/extras/tests/Misc/Utf16.cpp b/extras/tests/Misc/Utf16.cpp new file mode 100644 index 000000000..39fbe3c9c --- /dev/null +++ b/extras/tests/Misc/Utf16.cpp @@ -0,0 +1,68 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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/extras/tests/Misc/Utf8.cpp b/extras/tests/Misc/Utf8.cpp new file mode 100644 index 000000000..740046d0d --- /dev/null +++ b/extras/tests/Misc/Utf8.cpp @@ -0,0 +1,59 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include + +using namespace ArduinoJson::detail; + +static void testCodepoint(uint32_t codepoint, std::string expected) { + ResourceManager resources; + StringBuilder str(&resources); + 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/extras/tests/Misc/arithmeticCompare.cpp b/extras/tests/Misc/arithmeticCompare.cpp new file mode 100644 index 000000000..e955194d8 --- /dev/null +++ b/extras/tests/Misc/arithmeticCompare.cpp @@ -0,0 +1,97 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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/extras/tests/Misc/conflicts.cpp b/extras/tests/Misc/conflicts.cpp new file mode 100644 index 000000000..a00d0196c --- /dev/null +++ b/extras/tests/Misc/conflicts.cpp @@ -0,0 +1,67 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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 + +// issue #1914 +#define V7 7 + +// STM32, Mbed, Particle +#define A0 16 +#define A1 17 +#define A2 18 + +// catch.hpp mutes several warnings, this file also allows to detect them +#include "ArduinoJson.h" diff --git a/extras/tests/Misc/custom_string.hpp b/extras/tests/Misc/custom_string.hpp new file mode 100644 index 000000000..9982040fb --- /dev/null +++ b/extras/tests/Misc/custom_string.hpp @@ -0,0 +1,11 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#pragma once + +#include + +struct custom_char_traits : std::char_traits {}; + +using custom_string = std::basic_string; diff --git a/extras/tests/Misc/issue1967.cpp b/extras/tests/Misc/issue1967.cpp new file mode 100644 index 000000000..bb067f057 --- /dev/null +++ b/extras/tests/Misc/issue1967.cpp @@ -0,0 +1,13 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +// we expect ArduinoJson.h to include +#define ARDUINOJSON_ENABLE_STD_STRING 1 + +// but we don't want it to included accidentally +#undef ARDUINO +#define ARDUINOJSON_ENABLE_STD_STREAM 0 +#define ARDUINOJSON_ENABLE_STRING_VIEW 0 + +#include diff --git a/extras/tests/Misc/issue2129.cpp b/extras/tests/Misc/issue2129.cpp new file mode 100644 index 000000000..022e23260 --- /dev/null +++ b/extras/tests/Misc/issue2129.cpp @@ -0,0 +1,55 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +template +class Nullable { + public: + Nullable() : value_{} {} + Nullable(T value) : value_{value} {} + + operator T() const { + return value_; + } + + operator T&() { + return value_; + } + + bool is_valid() const { + return value_ != invalid_value_; + } + + T value() const { + return value_; + } + + private: + T value_; + static T invalid_value_; +}; + +template <> +float Nullable::invalid_value_ = std::numeric_limits::lowest(); + +template +void convertToJson(const Nullable& src, JsonVariant dst) { + if (src.is_valid()) { + dst.set(src.value()); + } else { + dst.clear(); + } +} + +TEST_CASE("Issue #2129") { + Nullable nullable_value = Nullable{123.4f}; + + JsonDocument doc; + + doc["value"] = nullable_value; + + REQUIRE(doc["value"].as() == Approx(123.4f)); +} diff --git a/extras/tests/Misc/issue2166.cpp b/extras/tests/Misc/issue2166.cpp new file mode 100644 index 000000000..f068bd628 --- /dev/null +++ b/extras/tests/Misc/issue2166.cpp @@ -0,0 +1,22 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +struct CCLASS { + static const char mszKey[]; +}; + +TEST_CASE("Issue #2166") { + JsonDocument doc; + doc[CCLASS::mszKey] = 12; + REQUIRE(doc.as() == "{\"test3\":12}"); + + JsonObject obj = doc.to(); + obj[CCLASS::mszKey] = 12; + REQUIRE(doc.as() == "{\"test3\":12}"); +} + +const char CCLASS::mszKey[] = "test3"; diff --git a/extras/tests/Misc/issue2181.cpp b/extras/tests/Misc/issue2181.cpp new file mode 100644 index 000000000..73929137f --- /dev/null +++ b/extras/tests/Misc/issue2181.cpp @@ -0,0 +1,15 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#define true 0x1 +#define false 0x0 + +#include +#include + +TEST_CASE("Issue #2181") { + JsonDocument doc; + doc["hello"] = "world"; + REQUIRE(doc.as() == "{\"hello\":\"world\"}"); +} diff --git a/extras/tests/Misc/printable.cpp b/extras/tests/Misc/printable.cpp new file mode 100644 index 000000000..3e20a5ba9 --- /dev/null +++ b/extras/tests/Misc/printable.cpp @@ -0,0 +1,192 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#define ARDUINOJSON_ENABLE_ARDUINO_STREAM 1 +#include + +#include "Allocators.hpp" + +using ArduinoJson::detail::sizeofArray; + +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") { + SpyingAllocator spy; + JsonDocument doc(&spy); + const char* value = "example"; + + 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(spy.log() == + AllocatorLog{ + Allocate(sizeofStringBuffer()), + Reallocate(sizeofStringBuffer(), sizeofString("example")), + }); + } + + 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(spy.log() == + AllocatorLog{ + Allocate(sizeofStringBuffer()), + Reallocate(sizeofStringBuffer(), sizeofString("example")), + }); + } + } + + SECTION("First allocation fails") { + SpyingAllocator spy(FailingAllocator::instance()); + JsonDocument doc(&spy); + const char* value = "hello world"; + + doc.set(666); // to make sure we override the value + + SECTION("Via Print::write(char)") { + PrintableString printable(value); + + bool success = doc.set(printable); + + CHECK(success == false); + CHECK(doc.isNull()); + CHECK(printable.totalBytesWritten() == 0); + CHECK(doc.overflowed() == true); + CHECK(spy.log() == AllocatorLog{ + AllocateFail(sizeofStringBuffer()), + }); + } + + SECTION("Via Print::write(const char*, size_t)") { + PrintableString printable(value); + + bool success = doc.set(printable); + + CHECK(success == false); + CHECK(doc.isNull()); + CHECK(printable.totalBytesWritten() == 0); + CHECK(doc.overflowed() == true); + CHECK(spy.log() == AllocatorLog{ + AllocateFail(sizeofStringBuffer()), + }); + } + } + + SECTION("Reallocation fails") { + TimebombAllocator timebomb(1); + SpyingAllocator spy(&timebomb); + JsonDocument doc(&spy); + const char* value = "Lorem ipsum dolor sit amet, cons"; // > 31 chars + + doc.set(666); // to make sure we override the value + + SECTION("Via Print::write(char)") { + PrintableString printable(value); + + bool success = doc.set(printable); + + CHECK(success == false); + CHECK(doc.isNull()); + CHECK(printable.totalBytesWritten() == 31); + CHECK(doc.overflowed() == true); + CHECK(spy.log() == + AllocatorLog{ + Allocate(sizeofStringBuffer()), + ReallocateFail(sizeofStringBuffer(), sizeofStringBuffer(2)), + Deallocate(sizeofStringBuffer()), + }); + } + + SECTION("Via Print::write(const char*, size_t)") { + PrintableString printable(value); + + bool success = doc.set(printable); + + CHECK(success == false); + CHECK(doc.isNull()); + CHECK(printable.totalBytesWritten() == 31); + CHECK(doc.overflowed() == true); + CHECK(spy.log() == + AllocatorLog{ + Allocate(sizeofStringBuffer()), + ReallocateFail(sizeofStringBuffer(), sizeofStringBuffer(2)), + Deallocate(sizeofStringBuffer()), + }); + } + } + + SECTION("Null variant") { + JsonVariant var; + PrintableString printable = "Hello World!"; + CHECK(var.set(printable) == false); + CHECK(var.isNull()); + CHECK(printable.totalBytesWritten() == 0); + } + + SECTION("String deduplication") { + SpyingAllocator spy; + JsonDocument doc(&spy); + 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(spy.log() == + AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofStringBuffer()), + Reallocate(sizeofStringBuffer(), sizeofString("Hello World!")), + Allocate(sizeofStringBuffer()), + Deallocate(sizeofStringBuffer()), + }); + } +} diff --git a/extras/tests/Misc/unsigned_char.cpp b/extras/tests/Misc/unsigned_char.cpp new file mode 100644 index 000000000..3e9502746 --- /dev/null +++ b/extras/tests/Misc/unsigned_char.cpp @@ -0,0 +1,248 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Literals.hpp" + +#if defined(__clang__) +# define CONFLICTS_WITH_BUILTIN_OPERATOR +#endif + +TEST_CASE("unsigned char[]") { + SECTION("deserializeJson()") { + unsigned char input[] = "{\"a\":42}"; + + JsonDocument doc; + DeserializationError err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("deserializeMsgPack()") { + unsigned char input[] = "\xDE\x00\x01\xA5Hello\xA5world"; + + JsonDocument doc; + DeserializationError err = deserializeMsgPack(doc, input); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("serializeMsgPack(unsigned char[])") { + unsigned char buffer[32]; + JsonDocument 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]; + JsonDocument 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]; + JsonDocument 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]; + JsonDocument 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]; + JsonDocument doc; + doc["hello"] = "world"; + + size_t n = serializeJsonPretty(doc, buffer); + + REQUIRE(n == 24); + } + + SECTION("serializeJsonPretty(unsigned char*)") { + unsigned char buffer[32]; + JsonDocument doc; + doc["hello"] = "world"; + + size_t n = serializeJsonPretty(doc, buffer, sizeof(buffer)); + + REQUIRE(n == 24); + } + + SECTION("JsonVariant") { + JsonDocument doc; + + 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("world"_s == 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("world"_s == 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"; + + JsonDocument doc; + JsonObject obj = doc.to(); + obj[key] = "world"; + + REQUIRE("world"_s == obj["hello"]); + } + + SECTION("JsonObject::operator[] const") { + unsigned char key[] = "hello"; + + JsonDocument doc; + deserializeJson(doc, "{\"hello\":\"world\"}"); + + JsonObject obj = doc.as(); + REQUIRE("world"_s == obj[key]); + } +#endif + + SECTION("remove()") { + unsigned char key[] = "hello"; + + JsonDocument doc; + deserializeJson(doc, "{\"hello\":\"world\"}"); + JsonObject obj = doc.as(); + obj.remove(key); + + REQUIRE(0 == obj.size()); + } + } + + SECTION("MemberProxy") { + SECTION("operator=") { // issue #416 + unsigned char value[] = "world"; + + JsonDocument doc; + JsonObject obj = doc.to(); + obj["hello"] = value; + + REQUIRE("world"_s == obj["hello"]); + } + + SECTION("set()") { + unsigned char value[] = "world"; + + JsonDocument doc; + JsonObject obj = doc.to(); + obj["hello"].set(value); + + REQUIRE("world"_s == obj["hello"]); + } + } + + SECTION("JsonArray") { + SECTION("add()") { + unsigned char value[] = "world"; + + JsonDocument doc; + JsonArray arr = doc.to(); + arr.add(value); + + REQUIRE("world"_s == arr[0]); + } + } + + SECTION("ElementProxy") { + SECTION("set()") { + unsigned char value[] = "world"; + + JsonDocument doc; + JsonArray arr = doc.to(); + arr.add("hello"); + arr[0].set(value); + + REQUIRE("world"_s == arr[0]); + } + + SECTION("operator=") { + unsigned char value[] = "world"; + + JsonDocument doc; + JsonArray arr = doc.to(); + arr.add("hello"); + arr[0] = value; + + REQUIRE("world"_s == arr[0]); + } + } +} diff --git a/extras/tests/Misc/version.cpp b/extras/tests/Misc/version.cpp new file mode 100644 index 000000000..136dbf3a3 --- /dev/null +++ b/extras/tests/Misc/version.cpp @@ -0,0 +1,18 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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/extras/tests/Misc/weird_strcmp.hpp b/extras/tests/Misc/weird_strcmp.hpp new file mode 100644 index 000000000..dbe122f6f --- /dev/null +++ b/extras/tests/Misc/weird_strcmp.hpp @@ -0,0 +1,31 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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/extras/tests/MixedConfiguration/CMakeLists.txt b/extras/tests/MixedConfiguration/CMakeLists.txt new file mode 100644 index 000000000..08d888835 --- /dev/null +++ b/extras/tests/MixedConfiguration/CMakeLists.txt @@ -0,0 +1,34 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2025, 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 + issue1707.cpp + string_length_size_1.cpp + string_length_size_2.cpp + string_length_size_4.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/extras/tests/MixedConfiguration/decode_unicode_0.cpp b/extras/tests/MixedConfiguration/decode_unicode_0.cpp new file mode 100644 index 000000000..91b03bb87 --- /dev/null +++ b/extras/tests/MixedConfiguration/decode_unicode_0.cpp @@ -0,0 +1,12 @@ +#define ARDUINOJSON_DECODE_UNICODE 0 +#include + +#include + +TEST_CASE("ARDUINOJSON_DECODE_UNICODE == 0") { + JsonDocument doc; + DeserializationError err = deserializeJson(doc, "\"\\uD834\\uDD1E\""); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.as() == "\\uD834\\uDD1E"); +} diff --git a/extras/tests/MixedConfiguration/decode_unicode_1.cpp b/extras/tests/MixedConfiguration/decode_unicode_1.cpp new file mode 100644 index 000000000..0568ab53f --- /dev/null +++ b/extras/tests/MixedConfiguration/decode_unicode_1.cpp @@ -0,0 +1,11 @@ +#define ARDUINOJSON_DECODE_UNICODE 1 +#include + +#include + +TEST_CASE("ARDUINOJSON_DECODE_UNICODE == 1") { + JsonDocument doc; + DeserializationError err = deserializeJson(doc, "\"\\uD834\\uDD1E\""); + + REQUIRE(err == DeserializationError::Ok); +} diff --git a/extras/tests/MixedConfiguration/enable_alignment_0.cpp b/extras/tests/MixedConfiguration/enable_alignment_0.cpp new file mode 100644 index 000000000..569f84aa5 --- /dev/null +++ b/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/extras/tests/MixedConfiguration/enable_alignment_1.cpp b/extras/tests/MixedConfiguration/enable_alignment_1.cpp new file mode 100644 index 000000000..56d48169a --- /dev/null +++ b/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/extras/tests/MixedConfiguration/enable_comments_0.cpp b/extras/tests/MixedConfiguration/enable_comments_0.cpp new file mode 100644 index 000000000..f0904c585 --- /dev/null +++ b/extras/tests/MixedConfiguration/enable_comments_0.cpp @@ -0,0 +1,54 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#define ARDUINOJSON_ENABLE_COMMENTS 0 +#include + +#include + +TEST_CASE("Comments should produce InvalidInput") { + JsonDocument doc; + + 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/extras/tests/MixedConfiguration/enable_comments_1.cpp b/extras/tests/MixedConfiguration/enable_comments_1.cpp new file mode 100644 index 000000000..7e135dfa8 --- /dev/null +++ b/extras/tests/MixedConfiguration/enable_comments_1.cpp @@ -0,0 +1,411 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#define ARDUINOJSON_ENABLE_COMMENTS 1 +#include + +#include + +TEST_CASE("Comments in arrays") { + JsonDocument doc; + + 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") { + JsonDocument doc; + + 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") { + JsonDocument doc; + + 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/extras/tests/MixedConfiguration/enable_infinity_0.cpp b/extras/tests/MixedConfiguration/enable_infinity_0.cpp new file mode 100644 index 000000000..41566e247 --- /dev/null +++ b/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) { + JsonDocument doc; + 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()") { + JsonDocument doc; + 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/extras/tests/MixedConfiguration/enable_infinity_1.cpp b/extras/tests/MixedConfiguration/enable_infinity_1.cpp new file mode 100644 index 000000000..99ab3fe71 --- /dev/null +++ b/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") { + JsonDocument doc; + + 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/extras/tests/MixedConfiguration/enable_nan_0.cpp b/extras/tests/MixedConfiguration/enable_nan_0.cpp new file mode 100644 index 000000000..7491e4a3d --- /dev/null +++ b/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") { + JsonDocument doc; + 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/extras/tests/MixedConfiguration/enable_nan_1.cpp b/extras/tests/MixedConfiguration/enable_nan_1.cpp new file mode 100644 index 000000000..20d0874ec --- /dev/null +++ b/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") { + JsonDocument doc; + 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/extras/tests/MixedConfiguration/enable_progmem_1.cpp b/extras/tests/MixedConfiguration/enable_progmem_1.cpp new file mode 100644 index 000000000..312a87ffe --- /dev/null +++ b/extras/tests/MixedConfiguration/enable_progmem_1.cpp @@ -0,0 +1,191 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#define ARDUINOJSON_ENABLE_PROGMEM 1 +#include + +#include + +TEST_CASE("Flash strings") { + JsonDocument doc; + + 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/extras/tests/MixedConfiguration/issue1707.cpp b/extras/tests/MixedConfiguration/issue1707.cpp new file mode 100644 index 000000000..ff8d2bac4 --- /dev/null +++ b/extras/tests/MixedConfiguration/issue1707.cpp @@ -0,0 +1,17 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#define ARDUINO +#define memcpy_P(dest, src, n) memcpy((dest), (src), (n)) + +#include + +#include + +TEST_CASE("Issue1707") { + JsonDocument doc; + + DeserializationError err = deserializeJson(doc, F("{\"hello\":12}")); + REQUIRE(err == DeserializationError::Ok); +} diff --git a/extras/tests/MixedConfiguration/string_length_size_1.cpp b/extras/tests/MixedConfiguration/string_length_size_1.cpp new file mode 100644 index 000000000..32636867e --- /dev/null +++ b/extras/tests/MixedConfiguration/string_length_size_1.cpp @@ -0,0 +1,131 @@ +#define ARDUINOJSON_STRING_LENGTH_SIZE 1 +#include + +#include +#include + +#include "Literals.hpp" + +TEST_CASE("ARDUINOJSON_STRING_LENGTH_SIZE == 1") { + JsonDocument doc; + + SECTION("set(std::string)") { + SECTION("returns true if len <= 255") { + auto result = doc.set(std::string(255, '?')); + + REQUIRE(result == true); + REQUIRE(doc.overflowed() == false); + } + + SECTION("returns false if len >= 256") { + auto result = doc.set(std::string(256, '?')); + + REQUIRE(result == false); + REQUIRE(doc.overflowed() == true); + } + } + + SECTION("set(MsgPackBinary)") { + SECTION("returns true if size <= 253") { + auto str = std::string(253, '?'); + auto result = doc.set(MsgPackBinary(str.data(), str.size())); + + REQUIRE(result == true); + REQUIRE(doc.overflowed() == false); + } + + SECTION("returns false if size >= 254") { + auto str = std::string(254, '?'); + auto result = doc.set(MsgPackBinary(str.data(), str.size())); + + REQUIRE(result == false); + REQUIRE(doc.overflowed() == true); + } + } + + SECTION("set(MsgPackExtension)") { + SECTION("returns true if size <= 252") { + auto str = std::string(252, '?'); + auto result = doc.set(MsgPackExtension(1, str.data(), str.size())); + + REQUIRE(result == true); + REQUIRE(doc.overflowed() == false); + } + + SECTION("returns false if size >= 253") { + auto str = std::string(253, '?'); + auto result = doc.set(MsgPackExtension(1, str.data(), str.size())); + + REQUIRE(result == false); + REQUIRE(doc.overflowed() == true); + } + } + + SECTION("deserializeJson()") { + SECTION("returns Ok if string length <= 255") { + auto input = "\"" + std::string(255, '?') + "\""; + + auto err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("returns NoMemory if string length >= 256") { + auto input = "\"" + std::string(256, '?') + "\""; + + auto err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::NoMemory); + } + } + + SECTION("deserializeMsgPack()") { + SECTION("returns Ok if string length <= 255") { + auto input = "\xd9\xff" + std::string(255, '?'); + + auto err = deserializeMsgPack(doc, input); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("returns NoMemory if string length >= 256") { + auto input = "\xda\x01\x00"_s + std::string(256, '?'); + + auto err = deserializeMsgPack(doc, input); + + REQUIRE(err == DeserializationError::NoMemory); + } + + SECTION("returns Ok if binary size <= 253") { + auto input = "\xc4\xfd" + std::string(253, '?'); + + auto err = deserializeMsgPack(doc, input); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("returns NoMemory if binary size >= 254") { + auto input = "\xc4\xfe" + std::string(254, '?'); + + auto err = deserializeMsgPack(doc, input); + + REQUIRE(err == DeserializationError::NoMemory); + } + + SECTION("returns Ok if extension size <= 252") { + auto input = "\xc7\xfc\x01" + std::string(252, '?'); + + auto err = deserializeMsgPack(doc, input); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("returns NoMemory if binary size >= 253") { + auto input = "\xc7\xfd\x01" + std::string(253, '?'); + + auto err = deserializeMsgPack(doc, input); + + REQUIRE(err == DeserializationError::NoMemory); + } + } +} diff --git a/extras/tests/MixedConfiguration/string_length_size_2.cpp b/extras/tests/MixedConfiguration/string_length_size_2.cpp new file mode 100644 index 000000000..2c1315b08 --- /dev/null +++ b/extras/tests/MixedConfiguration/string_length_size_2.cpp @@ -0,0 +1,140 @@ +#define ARDUINOJSON_STRING_LENGTH_SIZE 2 +#include + +#include +#include + +#include "Literals.hpp" + +TEST_CASE("ARDUINOJSON_STRING_LENGTH_SIZE == 2") { + JsonDocument doc; + + SECTION("set(std::string)") { + SECTION("returns true if len <= 65535") { + auto result = doc.set(std::string(65535, '?')); + + REQUIRE(result == true); + REQUIRE(doc.overflowed() == false); + } + + SECTION("returns false if len >= 65536") { + auto result = doc.set(std::string(65536, '?')); + + REQUIRE(result == false); + REQUIRE(doc.overflowed() == true); + } + } + + SECTION("set(MsgPackBinary)") { + SECTION("returns true if size <= 65532") { + auto str = std::string(65532, '?'); + auto result = doc.set(MsgPackBinary(str.data(), str.size())); + + REQUIRE(result == true); + REQUIRE(doc.overflowed() == false); + } + + SECTION("returns false if size >= 65533") { + auto str = std::string(65533, '?'); + auto result = doc.set(MsgPackBinary(str.data(), str.size())); + + REQUIRE(result == false); + REQUIRE(doc.overflowed() == true); + } + } + + SECTION("set(MsgPackExtension)") { + SECTION("returns true if size <= 65531") { + auto str = std::string(65531, '?'); + auto result = doc.set(MsgPackExtension(1, str.data(), str.size())); + + REQUIRE(result == true); + REQUIRE(doc.overflowed() == false); + } + + SECTION("returns false if size >= 65532") { + auto str = std::string(65532, '?'); + auto result = doc.set(MsgPackExtension(1, str.data(), str.size())); + + REQUIRE(result == false); + REQUIRE(doc.overflowed() == true); + } + } + + SECTION("deserializeJson()") { + SECTION("returns Ok if string length <= 65535") { + auto input = "\"" + std::string(65535, '?') + "\""; + + auto err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("returns NoMemory if string length >= 65536") { + auto input = "\"" + std::string(65536, '?') + "\""; + + auto err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::NoMemory); + } + } + + SECTION("deserializeMsgPack()") { + SECTION("returns Ok if string length <= 65535") { + auto input = "\xda\xff\xff" + std::string(65535, '?'); + + auto err = deserializeMsgPack(doc, input); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("returns NoMemory if string length >= 65536") { + auto input = "\xdb\x00\x01\x00\x00"_s + std::string(65536, '?'); + + auto err = deserializeMsgPack(doc, input); + + REQUIRE(err == DeserializationError::NoMemory); + } + + SECTION("returns Ok if binary size <= 65532") { + auto input = "\xc5\xff\xfc" + std::string(65532, '?'); + + auto err = deserializeMsgPack(doc, input); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("returns NoMemory if binary size >= 65534") { + auto input = "\xc5\xff\xfd" + std::string(65534, '?'); + + auto err = deserializeMsgPack(doc, input); + + REQUIRE(err == DeserializationError::NoMemory); + } + + // https://oss-fuzz.com/testcase?key=5354792971993088 + SECTION("doesn't overflow if binary size == 0xFFFF") { + auto input = "\xc5\xff\xff"_s; + + auto err = deserializeMsgPack(doc, input); + + REQUIRE(err == DeserializationError::NoMemory); + } + + SECTION("returns Ok if extension size <= 65531") { + auto input = "\xc8\xff\xfb\x01" + std::string(65531, '?'); + + auto err = deserializeMsgPack(doc, input); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("returns NoMemory if extension size >= 65532") { + auto input = "\xc8\xff\xfc\x01" + std::string(65532, '?'); + + auto err = deserializeMsgPack(doc, input); + + REQUIRE(err == DeserializationError::NoMemory); + } + } +} diff --git a/extras/tests/MixedConfiguration/string_length_size_4.cpp b/extras/tests/MixedConfiguration/string_length_size_4.cpp new file mode 100644 index 000000000..4059c3d48 --- /dev/null +++ b/extras/tests/MixedConfiguration/string_length_size_4.cpp @@ -0,0 +1,146 @@ +#define ARDUINOJSON_STRING_LENGTH_SIZE 4 +#include + +#include +#include + +#include "Literals.hpp" + +TEST_CASE("ARDUINOJSON_STRING_LENGTH_SIZE == 4") { + JsonDocument doc; + + SECTION("set(std::string)") { + SECTION("returns true if string length >= 65536") { + auto result = doc.set(std::string(65536, '?')); + + REQUIRE(result == true); + REQUIRE(doc.overflowed() == false); + } + } + + SECTION("set(MsgPackBinary)") { + SECTION("returns true if size >= 65536") { + auto str = std::string(65536, '?'); + auto result = doc.set(MsgPackBinary(str.data(), str.size())); + + REQUIRE(result == true); + REQUIRE(doc.overflowed() == false); + } + } + + SECTION("set(MsgPackExtension)") { + SECTION("returns true if size >= 65532") { + auto str = std::string(65532, '?'); + auto result = doc.set(MsgPackExtension(1, str.data(), str.size())); + + REQUIRE(result == true); + REQUIRE(doc.overflowed() == false); + } + } + + SECTION("deserializeJson()") { + SECTION("returns Ok if string length >= 65536") { + auto input = "\"" + std::string(65536, '?') + "\""; + + auto err = deserializeJson(doc, input); + + REQUIRE(err == DeserializationError::Ok); + } + } + + SECTION("deserializeMsgPack()") { + SECTION("returns Ok if string size >= 65536") { + auto input = "\xda\xff\xff" + std::string(65536, '?'); + + auto err = deserializeMsgPack(doc, input); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("returns Ok if binary size >= 65536") { + auto input = "\xc5\xff\xff" + std::string(65536, '?'); + + auto err = deserializeMsgPack(doc, input); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("returns Ok if extension size >= 65532") { + auto input = "\xc8\xff\xfb\x01" + std::string(65532, '?'); + + auto err = deserializeMsgPack(doc, input); + + REQUIRE(err == DeserializationError::Ok); + } + + // https://oss-fuzz.com/testcase?key=5354792971993088 + SECTION("doesn't overflow if binary size == 0xFFFFFFFF") { + auto input = "\xc6\xff\xff\xff\xff"_s; + + auto err = deserializeMsgPack(doc, input); + + REQUIRE(err == DeserializationError::NoMemory); + } + + SECTION("doesn't overflow if string size == 0xFFFFFFFF") { + auto input = "\xdb\xff\xff\xff\xff???????????????????"_s; + + auto err = deserializeMsgPack(doc, input); + + REQUIRE(err != DeserializationError::Ok); + } + } + + SECTION("bin 32 deserialization") { + auto str = std::string(65536, '?'); + auto input = "\xc6\x00\x01\x00\x00"_s + str; + + auto err = deserializeMsgPack(doc, input); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is()); + auto binary = doc.as(); + REQUIRE(binary.size() == 65536); + REQUIRE(binary.data() != nullptr); + REQUIRE(std::string(reinterpret_cast(binary.data()), + binary.size()) == str); + } + + SECTION("bin 32 serialization") { + auto str = std::string(65536, '?'); + doc.set(MsgPackBinary(str.data(), str.size())); + + std::string output; + auto result = serializeMsgPack(doc, output); + + REQUIRE(result == 5 + str.size()); + REQUIRE(output == "\xc6\x00\x01\x00\x00"_s + str); + } + + SECTION("ext 32 deserialization") { + auto str = std::string(65536, '?'); + auto input = "\xc9\x00\x01\x00\x00\x2a"_s + str; + + auto err = deserializeMsgPack(doc, input); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.is()); + auto value = doc.as(); + REQUIRE(value.type() == 42); + REQUIRE(value.size() == 65536); + REQUIRE(value.data() != nullptr); + REQUIRE(std::string(reinterpret_cast(value.data()), + value.size()) == str); + } + + SECTION("ext 32 serialization") { + auto str = std::string(65536, '?'); + doc.set(MsgPackExtension(42, str.data(), str.size())); + + std::string output; + auto result = serializeMsgPack(doc, output); + + REQUIRE(result == 6 + str.size()); + REQUIRE(output == "\xc9\x00\x01\x00\x00\x2a"_s + str); + } +} diff --git a/extras/tests/MixedConfiguration/use_double_0.cpp b/extras/tests/MixedConfiguration/use_double_0.cpp new file mode 100644 index 000000000..6958bc060 --- /dev/null +++ b/extras/tests/MixedConfiguration/use_double_0.cpp @@ -0,0 +1,67 @@ +#define ARDUINOJSON_USE_DOUBLE 0 +#include + +#include + +namespace my { +using ArduinoJson::detail::isinf; +} // namespace my + +void checkFloat(const char* input, float expected) { + using ArduinoJson::detail::NumberType; + using ArduinoJson::detail::parseNumber; + CAPTURE(input); + auto result = parseNumber(input); + REQUIRE(result.type() == NumberType::Float); + REQUIRE(result.asFloat() == Approx(expected)); +} + +TEST_CASE("ARDUINOJSON_USE_DOUBLE == 0") { + SECTION("serializeJson()") { + JsonDocument doc; + 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}"); + } + + SECTION("parseNumber()") { + using ArduinoJson::detail::NumberType; + using ArduinoJson::detail::parseNumber; + + SECTION("Large positive number") { + auto result = parseNumber("1e300"); + REQUIRE(result.type() == NumberType::Float); + REQUIRE(result.asFloat() > 0); + REQUIRE(my::isinf(result.asFloat())); + } + + SECTION("Large negative number") { + auto result = parseNumber("-1e300"); + REQUIRE(result.type() == NumberType::Float); + REQUIRE(result.asFloat() < 0); + REQUIRE(my::isinf(result.asFloat())); + } + + SECTION("Too small to be represented") { + auto result = parseNumber("1e-300"); + REQUIRE(result.type() == NumberType::Float); + REQUIRE(result.asFloat() == 0); + } + + 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); + } + } +} diff --git a/extras/tests/MixedConfiguration/use_double_1.cpp b/extras/tests/MixedConfiguration/use_double_1.cpp new file mode 100644 index 000000000..15c4849c8 --- /dev/null +++ b/extras/tests/MixedConfiguration/use_double_1.cpp @@ -0,0 +1,17 @@ +#define ARDUINOJSON_USE_DOUBLE 1 +#include + +#include + +TEST_CASE("ARDUINOJSON_USE_DOUBLE == 1") { + JsonDocument doc; + 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/extras/tests/MixedConfiguration/use_long_long_0.cpp b/extras/tests/MixedConfiguration/use_long_long_0.cpp new file mode 100644 index 000000000..16c07db16 --- /dev/null +++ b/extras/tests/MixedConfiguration/use_long_long_0.cpp @@ -0,0 +1,38 @@ +#define ARDUINOJSON_USE_LONG_LONG 0 +#include + +#include + +#include "Literals.hpp" + +TEST_CASE("ARDUINOJSON_USE_LONG_LONG == 0") { + JsonDocument doc; + + SECTION("smoke test") { + doc["A"] = 42; + doc["B"] = 84; + + std::string json; + serializeJson(doc, json); + + REQUIRE(json == "{\"A\":42,\"B\":84}"); + } + + SECTION("deserializeMsgPack()") { + SECTION("cf 00 00 00 00 ff ff ff ff") { + auto err = + deserializeMsgPack(doc, "\xcf\x00\x00\x00\x00\xff\xff\xff\xff"_s); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.as() == 0xFFFFFFFF); + } + + SECTION("cf 00 00 00 01 00 00 00 00") { + auto err = + deserializeMsgPack(doc, "\xcf\x00\x00\x00\x01\x00\x00\x00\x00"_s); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.isNull()); + } + } +} diff --git a/extras/tests/MixedConfiguration/use_long_long_1.cpp b/extras/tests/MixedConfiguration/use_long_long_1.cpp new file mode 100644 index 000000000..a2c4fd8e2 --- /dev/null +++ b/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") { + JsonDocument doc; + 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/extras/tests/MsgPackDeserializer/CMakeLists.txt b/extras/tests/MsgPackDeserializer/CMakeLists.txt new file mode 100644 index 000000000..96b4584c0 --- /dev/null +++ b/extras/tests/MsgPackDeserializer/CMakeLists.txt @@ -0,0 +1,22 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2025, Benoit BLANCHON +# MIT License + +add_executable(MsgPackDeserializerTests + deserializeArray.cpp + deserializeObject.cpp + deserializeVariant.cpp + destination_types.cpp + doubleToFloat.cpp + errors.cpp + filter.cpp + input_types.cpp + nestingLimit.cpp +) + +add_test(MsgPackDeserializer MsgPackDeserializerTests) + +set_tests_properties(MsgPackDeserializer + PROPERTIES + LABELS "Catch" +) diff --git a/extras/tests/MsgPackDeserializer/deserializeArray.cpp b/extras/tests/MsgPackDeserializer/deserializeArray.cpp new file mode 100644 index 000000000..03409a979 --- /dev/null +++ b/extras/tests/MsgPackDeserializer/deserializeArray.cpp @@ -0,0 +1,104 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Allocators.hpp" + +TEST_CASE("deserialize MsgPack array") { + SpyingAllocator spy; + JsonDocument doc(&spy); + + 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("tiny strings") { + DeserializationError error = + deserializeMsgPack(doc, "\x92\xA3xxx\xA3yyy"); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(doc.size() == 2); + REQUIRE(doc[0] == "xxx"); + REQUIRE(doc[1] == "yyy"); + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Allocate(sizeofString("xxx")), + // Buffer is reused for the next string + Deallocate(sizeofString("xxx")), + Reallocate(sizeofPool(), sizeofPool(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/extras/tests/MsgPackDeserializer/deserializeObject.cpp b/extras/tests/MsgPackDeserializer/deserializeObject.cpp new file mode 100644 index 000000000..75266f29d --- /dev/null +++ b/extras/tests/MsgPackDeserializer/deserializeObject.cpp @@ -0,0 +1,130 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("deserialize MsgPack object") { + JsonDocument doc; + + 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/extras/tests/MsgPackDeserializer/deserializeVariant.cpp b/extras/tests/MsgPackDeserializer/deserializeVariant.cpp new file mode 100644 index 000000000..bbe88ed1f --- /dev/null +++ b/extras/tests/MsgPackDeserializer/deserializeVariant.cpp @@ -0,0 +1,395 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +template +static void checkValue(const char* input, T expected) { + JsonDocument doc; + + DeserializationError error = deserializeMsgPack(doc, input); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(doc.is()); + REQUIRE(doc.as() == expected); +} + +static void checkError(size_t timebombCountDown, const char* input, + DeserializationError expected) { + TimebombAllocator timebomb(timebombCountDown); + JsonDocument doc(&timebomb); + + DeserializationError error = deserializeMsgPack(doc, input); + + CAPTURE(input); + REQUIRE(error == expected); +} + +TEST_CASE("deserialize MsgPack value") { + SECTION("nil") { + checkValue("\xc0", nullptr); + } + + SECTION("bool") { + checkValue("\xc2", false); + checkValue("\xc3", true); + } + + SECTION("positive fixint") { + checkValue("\x00", 0); + checkValue("\x7F", 127); + } + + SECTION("negative fixint") { + checkValue("\xe0", -32); + checkValue("\xff", -1); + } + + SECTION("uint 8") { + checkValue("\xcc\x00", 0); + checkValue("\xcc\xff", 255); + } + + SECTION("uint 16") { + checkValue("\xcd\x00\x00", 0); + checkValue("\xcd\xFF\xFF", 65535); + checkValue("\xcd\x30\x39", 12345); + } + + SECTION("uint 32") { + checkValue("\xCE\x00\x00\x00\x00", 0x00000000U); + checkValue("\xCE\xFF\xFF\xFF\xFF", 0xFFFFFFFFU); + checkValue("\xCE\x12\x34\x56\x78", 0x12345678U); + } + + SECTION("uint 64") { +#if ARDUINOJSON_USE_LONG_LONG + checkValue("\xCF\x00\x00\x00\x00\x00\x00\x00\x00", 0U); + checkValue("\xCF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", + 0xFFFFFFFFFFFFFFFFU); + checkValue("\xCF\x12\x34\x56\x78\x9A\xBC\xDE\xF0", + 0x123456789ABCDEF0U); +#else + checkValue("\xCF\x00\x00\x00\x00\x00\x00\x00\x00", nullptr); + checkValue("\xCF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", nullptr); + checkValue("\xCF\x12\x34\x56\x78\x9A\xBC\xDE\xF0", nullptr); +#endif + } + + SECTION("int 8") { + checkValue("\xd0\x00", 0); + checkValue("\xd0\xff", -1); + } + + SECTION("int 16") { + checkValue("\xD1\x00\x00", 0); + checkValue("\xD1\xFF\xFF", -1); + checkValue("\xD1\xCF\xC7", -12345); + } + + SECTION("int 32") { + checkValue("\xD2\x00\x00\x00\x00", 0); + checkValue("\xD2\xFF\xFF\xFF\xFF", -1); + checkValue("\xD2\xB6\x69\xFD\x2E", -1234567890); + } + + SECTION("int 64") { +#if ARDUINOJSON_USE_LONG_LONG + checkValue("\xD3\x00\x00\x00\x00\x00\x00\x00\x00", int64_t(0U)); + checkValue("\xD3\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", + int64_t(0xFFFFFFFFFFFFFFFFU)); + checkValue("\xD3\x12\x34\x56\x78\x9A\xBC\xDE\xF0", + int64_t(0x123456789ABCDEF0)); +#else + checkValue("\xD3\x00\x00\x00\x00\x00\x00\x00\x00", nullptr); + checkValue("\xD3\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", nullptr); + checkValue("\xD3\x12\x34\x56\x78\x9A\xBC\xDE\xF0", nullptr); +#endif + } + + SECTION("float 32") { + checkValue("\xCA\x00\x00\x00\x00", 0.0f); + checkValue("\xCA\x40\x48\xF5\xC3", 3.14f); + } + + SECTION("float 64") { + checkValue("\xCB\x00\x00\x00\x00\x00\x00\x00\x00", 0.0); + checkValue("\xCB\x40\x09\x21\xCA\xC0\x83\x12\x6F", 3.1415); + } + + SECTION("fixstr") { + checkValue("\xA0", std::string("")); + checkValue("\xABhello world", "hello world"_s); + checkValue("\xBFhello world hello world hello !", + "hello world hello world hello !"_s); + } + + SECTION("str 8") { + checkValue("\xd9\x05hello", "hello"_s); + } + + SECTION("str 16") { + checkValue("\xda\x00\x05hello", "hello"_s); + } + + SECTION("str 32") { + checkValue("\xdb\x00\x00\x00\x05hello", "hello"_s); + } + + SECTION("bin 8") { + JsonDocument doc; + + DeserializationError error = deserializeMsgPack(doc, "\xc4\x01?"); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(doc.is()); + auto binary = doc.as(); + REQUIRE(binary.size() == 1); + REQUIRE(binary.data() != nullptr); + REQUIRE(reinterpret_cast(binary.data())[0] == '?'); + } + + SECTION("bin 16") { + JsonDocument doc; + auto str = std::string(256, '?'); + auto input = "\xc5\x01\x00"_s + str; + + DeserializationError error = deserializeMsgPack(doc, input); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(doc.is()); + auto binary = doc.as(); + REQUIRE(binary.size() == 0x100); + REQUIRE(binary.data() != nullptr); + REQUIRE(std::string(reinterpret_cast(binary.data()), + binary.size()) == str); + } + + SECTION("fixext 1") { + JsonDocument doc; + + auto error = deserializeMsgPack(doc, "\xd4\x01\x02"); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(doc.is()); + auto ext = doc.as(); + REQUIRE(ext.type() == 1); + REQUIRE(ext.size() == 1); + auto data = reinterpret_cast(ext.data()); + REQUIRE(data[0] == 2); + } + + SECTION("fixext 2") { + JsonDocument doc; + + auto error = deserializeMsgPack(doc, "\xd5\x01\x02\x03"); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(doc.is()); + auto ext = doc.as(); + REQUIRE(ext.type() == 1); + REQUIRE(ext.size() == 2); + auto data = reinterpret_cast(ext.data()); + REQUIRE(data[0] == 2); + REQUIRE(data[1] == 3); + } + + SECTION("fixext 4") { + JsonDocument doc; + + auto error = deserializeMsgPack(doc, "\xd6\x01\x02\x03\x04\x05"); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(doc.is()); + auto ext = doc.as(); + REQUIRE(ext.type() == 1); + REQUIRE(ext.size() == 4); + auto data = reinterpret_cast(ext.data()); + REQUIRE(data[0] == 2); + REQUIRE(data[1] == 3); + REQUIRE(data[2] == 4); + REQUIRE(data[3] == 5); + } + + SECTION("fixext 8") { + JsonDocument doc; + + auto error = deserializeMsgPack(doc, "\xd7\x01????????"); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(doc.is()); + auto ext = doc.as(); + REQUIRE(ext.type() == 1); + REQUIRE(ext.size() == 8); + auto data = reinterpret_cast(ext.data()); + REQUIRE(data[0] == '?'); + REQUIRE(data[7] == '?'); + } + + SECTION("fixext 16") { + JsonDocument doc; + + auto error = deserializeMsgPack(doc, "\xd8\x01?????????????????"); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(doc.is()); + auto ext = doc.as(); + REQUIRE(ext.type() == 1); + REQUIRE(ext.size() == 16); + auto data = reinterpret_cast(ext.data()); + REQUIRE(data[0] == '?'); + REQUIRE(data[15] == '?'); + } + + SECTION("ext 8") { + JsonDocument doc; + + auto error = deserializeMsgPack(doc, "\xc7\x02\x01\x03\x04"); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(doc.is()); + auto ext = doc.as(); + REQUIRE(ext.type() == 1); + REQUIRE(ext.size() == 2); + auto data = reinterpret_cast(ext.data()); + REQUIRE(data[0] == 3); + REQUIRE(data[1] == 4); + } + + SECTION("ext 16") { + JsonDocument doc; + + auto error = deserializeMsgPack(doc, "\xc8\x00\x02\x01\x03\x04"); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(doc.is()); + auto ext = doc.as(); + REQUIRE(ext.type() == 1); + REQUIRE(ext.size() == 2); + auto data = reinterpret_cast(ext.data()); + REQUIRE(data[0] == 3); + REQUIRE(data[1] == 4); + } + + SECTION("ext 32") { + JsonDocument doc; + + auto error = deserializeMsgPack(doc, "\xc9\x00\x00\x00\x02\x01\x03\x04"); + + REQUIRE(error == DeserializationError::Ok); + REQUIRE(doc.is()); + auto ext = doc.as(); + REQUIRE(ext.type() == 1); + REQUIRE(ext.size() == 2); + auto data = reinterpret_cast(ext.data()); + REQUIRE(data[0] == 3); + REQUIRE(data[1] == 4); + } +} + +TEST_CASE("deserializeMsgPack() under memory constaints") { + SECTION("single values always fit") { + checkError(0, "\xc0", DeserializationError::Ok); // nil + checkError(0, "\xc2", DeserializationError::Ok); // false + checkError(0, "\xc3", DeserializationError::Ok); // true + checkError(0, "\xcc\x00", DeserializationError::Ok); // uint 8 + checkError(0, "\xcd\x30\x39", DeserializationError::Ok); // uint 16 + checkError(0, "\xCE\x12\x34\x56\x78", + DeserializationError::Ok); // uint 32 + } + + SECTION("fixstr") { + checkError(2, "\xA7ZZZZZZZ", DeserializationError::Ok); + checkError(0, "\xA7ZZZZZZZ", DeserializationError::NoMemory); + } + + SECTION("str 8") { + checkError(2, "\xD9\x07ZZZZZZZ", DeserializationError::Ok); + checkError(0, "\xD9\x07ZZZZZZZ", DeserializationError::NoMemory); + } + + SECTION("str 16") { + checkError(2, "\xDA\x00\x07ZZZZZZZ", DeserializationError::Ok); + checkError(0, "\xDA\x00\x07ZZZZZZZ", DeserializationError::NoMemory); + } + + SECTION("str 32") { + checkError(2, "\xDB\x00\x00\x00\x07ZZZZZZZ", DeserializationError::Ok); + checkError(0, "\xDB\x00\x00\x00\x07ZZZZZZZ", + DeserializationError::NoMemory); + } + + SECTION("fixarray") { + checkError(0, "\x90", DeserializationError::Ok); // [] + checkError(0, "\x91\x01", + DeserializationError::NoMemory); // [1] + checkError(1, "\x91\x01", + DeserializationError::Ok); // [1] + } + + SECTION("array 16") { + checkError(0, "\xDC\x00\x00", DeserializationError::Ok); + checkError(0, "\xDC\x00\x01\x01", DeserializationError::NoMemory); + checkError(1, "\xDC\x00\x01\x01", DeserializationError::Ok); + } + + SECTION("array 32") { + checkError(0, "\xDD\x00\x00\x00\x00", DeserializationError::Ok); + checkError(0, "\xDD\x00\x00\x00\x01\x01", DeserializationError::NoMemory); + checkError(1, "\xDD\x00\x00\x00\x01\x01", DeserializationError::Ok); + } + + SECTION("fixmap") { + SECTION("{}") { + checkError(0, "\x80", DeserializationError::Ok); + } + SECTION("{Hello:1}") { + checkError(1, "\x81\xA5Hello\x01", DeserializationError::NoMemory); + checkError(2, "\x81\xA5Hello\x01", DeserializationError::Ok); + } + SECTION("{Hello:1,World:2}") { + checkError(2, "\x82\xA5Hello\x01\xA5World\x02", + DeserializationError::NoMemory); + checkError(3, "\x82\xA5Hello\x01\xA5World\x02", DeserializationError::Ok); + } + } + + SECTION("map 16") { + SECTION("{}") { + checkError(0, "\xDE\x00\x00", DeserializationError::Ok); + } + SECTION("{Hello:1}") { + checkError(1, "\xDE\x00\x01\xA5Hello\x01", + DeserializationError::NoMemory); + checkError(2, "\xDE\x00\x01\xA5Hello\x01", DeserializationError::Ok); + } + SECTION("{Hello:1,World:2}") { + checkError(2, "\xDE\x00\x02\xA5Hello\x01\xA5World\x02", + DeserializationError::NoMemory); + checkError(3, "\xDE\x00\x02\xA5Hello\x01\xA5World\x02", + DeserializationError::Ok); + } + } + + SECTION("map 32") { + SECTION("{}") { + checkError(0, "\xDF\x00\x00\x00\x00", DeserializationError::Ok); + } + SECTION("{H:1}") { + checkError(1, "\xDF\x00\x00\x00\x01\xA1H\x01", + DeserializationError::NoMemory); + checkError(2, "\xDF\x00\x00\x00\x01\xA1H\x01", DeserializationError::Ok); + } + SECTION("{Hello:1,World:2}") { + checkError(2, "\xDF\x00\x00\x00\x02\xA5Hello\x01\xA5World\x02", + DeserializationError::NoMemory); + checkError(3, "\xDF\x00\x00\x00\x02\xA1H\x01\xA1W\x02", + DeserializationError::Ok); + } + } +} diff --git a/extras/tests/MsgPackDeserializer/destination_types.cpp b/extras/tests/MsgPackDeserializer/destination_types.cpp new file mode 100644 index 000000000..6b437ec71 --- /dev/null +++ b/extras/tests/MsgPackDeserializer/destination_types.cpp @@ -0,0 +1,109 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include + +#include +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +using ArduinoJson::detail::sizeofArray; +using ArduinoJson::detail::sizeofObject; + +TEST_CASE("deserializeMsgPack(JsonDocument&)") { + SpyingAllocator spy; + JsonDocument doc(&spy); + doc.add("hello"_s); + spy.clearLog(); + + auto err = deserializeMsgPack(doc, "\x91\x2A"); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.as() == "[42]"); + REQUIRE(spy.log() == AllocatorLog{ + Deallocate(sizeofPool()), + Deallocate(sizeofString("hello")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofArray(1)), + }); +} + +TEST_CASE("deserializeMsgPack(JsonVariant)") { + SECTION("variant is bound") { + SpyingAllocator spy; + JsonDocument doc(&spy); + doc.add("hello"_s); + spy.clearLog(); + + JsonVariant variant = doc[0]; + + auto err = deserializeMsgPack(variant, "\x91\x2A"); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.as() == "[[42]]"); + REQUIRE(spy.log() == AllocatorLog{ + Deallocate(sizeofString("hello")), + }); + } + + SECTION("variant is unbound") { + JsonVariant variant; + + auto err = deserializeMsgPack(variant, "\x91\x2A"); + + REQUIRE(err == DeserializationError::NoMemory); + } +} + +TEST_CASE("deserializeMsgPack(ElementProxy)") { + SpyingAllocator spy; + JsonDocument doc(&spy); + doc.add("hello"_s); + spy.clearLog(); + + SECTION("element already exists") { + auto err = deserializeMsgPack(doc[0], "\x91\x2A"); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.as() == "[[42]]"); + REQUIRE(spy.log() == AllocatorLog{ + Deallocate(sizeofString("hello")), + }); + } + + SECTION("element must be created exists") { + auto err = deserializeMsgPack(doc[1], "\x91\x2A"); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.as() == "[\"hello\",[42]]"); + REQUIRE(spy.log() == AllocatorLog{}); + } +} + +TEST_CASE("deserializeMsgPack(MemberProxy)") { + SpyingAllocator spy; + JsonDocument doc(&spy); + doc["hello"_s] = "world"_s; + spy.clearLog(); + + SECTION("member already exists") { + auto err = deserializeMsgPack(doc["hello"], "\x91\x2A"); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.as() == "{\"hello\":[42]}"); + REQUIRE(spy.log() == AllocatorLog{ + Deallocate(sizeofString("world")), + }); + } + + SECTION("member must be created") { + auto err = deserializeMsgPack(doc["value"], "\x91\x2A"); + + REQUIRE(err == DeserializationError::Ok); + REQUIRE(doc.as() == "{\"hello\":\"world\",\"value\":[42]}"); + REQUIRE(spy.log() == AllocatorLog{}); + } +} diff --git a/extras/tests/MsgPackDeserializer/doubleToFloat.cpp b/extras/tests/MsgPackDeserializer/doubleToFloat.cpp new file mode 100644 index 000000000..6eadd0ee1 --- /dev/null +++ b/extras/tests/MsgPackDeserializer/doubleToFloat.cpp @@ -0,0 +1,25 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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); + fixEndianness(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/extras/tests/MsgPackDeserializer/errors.cpp b/extras/tests/MsgPackDeserializer/errors.cpp new file mode 100644 index 000000000..9a8119e23 --- /dev/null +++ b/extras/tests/MsgPackDeserializer/errors.cpp @@ -0,0 +1,242 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include + +#include "Allocators.hpp" + +TEST_CASE("deserializeMsgPack() returns InvalidInput") { + JsonDocument doc; + + SECTION("integer as key") { + auto err = deserializeMsgPack(doc, "\x81\x01\xA1H", 3); + REQUIRE(err == DeserializationError::InvalidInput); + } +} + +TEST_CASE("deserializeMsgPack() returns EmptyInput") { + JsonDocument doc; + + SECTION("from sized buffer") { + auto err = deserializeMsgPack(doc, "", 0); + + REQUIRE(err == DeserializationError::EmptyInput); + } + + SECTION("from stream") { + std::istringstream input(""); + + auto err = deserializeMsgPack(doc, input); + + REQUIRE(err == DeserializationError::EmptyInput); + } +} + +static void testIncompleteInput(const char* input, size_t len) { + JsonDocument doc; + REQUIRE(deserializeMsgPack(doc, input, len) == DeserializationError::Ok); + + while (--len) { + REQUIRE(deserializeMsgPack(doc, input, len) == + DeserializationError::IncompleteInput); + } +} + +TEST_CASE("deserializeMsgPack() returns IncompleteInput") { + SECTION("empty input") { + testIncompleteInput("\x00", 1); + } + + SECTION("fixarray") { + testIncompleteInput("\x91\x01", 2); + } + + SECTION("array 16") { + testIncompleteInput("\xDC\x00\x01\x01", 4); + } + + SECTION("array 32") { + testIncompleteInput("\xDD\x00\x00\x00\x01\x01", 6); + } + + SECTION("fixmap") { + testIncompleteInput("\x81\xA3one\x01", 6); + } + + SECTION("map 16") { + testIncompleteInput("\xDE\x00\x01\xA3one\x01", 8); + } + + SECTION("map 32") { + testIncompleteInput("\xDF\x00\x00\x00\x01\xA3one\x01", 10); + testIncompleteInput("\xDF\x00\x00\x00\x01\xd9\x03one\x01", 11); + } + + SECTION("uint 8") { + testIncompleteInput("\xcc\x01", 2); + } + + SECTION("uint 16") { + testIncompleteInput("\xcd\x00\x01", 3); + } + + SECTION("uint 32") { + testIncompleteInput("\xCE\x00\x00\x00\x01", 5); + } + +#if ARDUINOJSON_USE_LONG_LONG + SECTION("uint 64") { + testIncompleteInput("\xCF\x00\x00\x00\x00\x00\x00\x00\x00", 9); + } +#endif + + SECTION("int 8") { + testIncompleteInput("\xD0\x01", 2); + } + + SECTION("int 16") { + testIncompleteInput("\xD1\x00\x01", 3); + } + + SECTION("int 32") { + testIncompleteInput("\xD2\x00\x00\x00\x01", 5); + } + +#if ARDUINOJSON_USE_LONG_LONG + SECTION("int 64") { + testIncompleteInput("\xD3\x00\x00\x00\x00\x00\x00\x00\x00", 9); + } +#endif + + SECTION("float 32") { + testIncompleteInput("\xCA\x40\x48\xF5\xC3", 5); + } + + SECTION("float 64") { + testIncompleteInput("\xCB\x40\x09\x21\xCA\xC0\x83\x12\x6F", 9); + } + + SECTION("fixstr") { + testIncompleteInput("\xABhello world", 12); + } + + SECTION("str 8") { + testIncompleteInput("\xd9\x05hello", 7); + } + + SECTION("str 16") { + testIncompleteInput("\xda\x00\x05hello", 8); + } + + SECTION("str 32") { + testIncompleteInput("\xdb\x00\x00\x00\x05hello", 10); + } + + SECTION("bin 8") { + testIncompleteInput("\xc4\x01X", 3); + } + + SECTION("bin 16") { + testIncompleteInput("\xc5\x00\x01X", 4); + } + + SECTION("bin 32") { + testIncompleteInput("\xc6\x00\x00\x00\x01X", 6); + } + + SECTION("ext 8") { + testIncompleteInput("\xc7\x01\x01\x01", 4); + } + + SECTION("ext 16") { + testIncompleteInput("\xc8\x00\x01\x01\x01", 5); + } + + SECTION("ext 32") { + testIncompleteInput("\xc9\x00\x00\x00\x01\x01\x01", 7); + } + + SECTION("fixext 1") { + testIncompleteInput("\xd4\x01\x01", 3); + } + + SECTION("fixext 2") { + testIncompleteInput("\xd5\x01\x01\x02", 4); + } + + SECTION("fixext 4") { + testIncompleteInput("\xd6\x01\x01\x02\x03\x04", 6); + } + + SECTION("fixext 8") { + testIncompleteInput("\xd7\x01\x01\x02\x03\x04\x05\x06\x07\x08", 10); + } + + SECTION("fixext 16") { + testIncompleteInput( + "\xd8\x01\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E" + "\x0F\x10", + 18); + } +} + +TEST_CASE( + "deserializeMsgPack() returns NoMemory when string allocation fails") { + TimebombAllocator allocator(0); + JsonDocument doc(&allocator); + + SECTION("fixstr") { + DeserializationError err = deserializeMsgPack(doc, "\xA5hello", 9); + REQUIRE(err == DeserializationError::NoMemory); + } + + SECTION("bin 8") { + DeserializationError err = deserializeMsgPack(doc, "\xC4\x01X", 3); + REQUIRE(err == DeserializationError::NoMemory); + } +} + +TEST_CASE( + "deserializeMsgPack() returns NoMemory if extension allocation fails") { + JsonDocument doc(FailingAllocator::instance()); + + SECTION("uint32_t should pass") { + auto err = deserializeMsgPack(doc, "\xceXXXX"); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("uint64_t should fail") { + auto err = deserializeMsgPack(doc, "\xcfXXXXXXXX"); + + REQUIRE(err == DeserializationError::NoMemory); + } + + SECTION("int32_t should pass") { + auto err = deserializeMsgPack(doc, "\xd2XXXX"); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("int64_t should fail") { + auto err = deserializeMsgPack(doc, "\xd3XXXXXXXX"); + + REQUIRE(err == DeserializationError::NoMemory); + } + + SECTION("float should pass") { + auto err = deserializeMsgPack(doc, "\xcaXXXX"); + + REQUIRE(err == DeserializationError::Ok); + } + + SECTION("double should fail") { + auto err = deserializeMsgPack(doc, "\xcbXXXXXXXX"); + + REQUIRE(err == DeserializationError::NoMemory); + } +} diff --git a/extras/tests/MsgPackDeserializer/filter.cpp b/extras/tests/MsgPackDeserializer/filter.cpp new file mode 100644 index 000000000..6bcd7b1cd --- /dev/null +++ b/extras/tests/MsgPackDeserializer/filter.cpp @@ -0,0 +1,1628 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +using namespace ArduinoJson::detail; + +TEST_CASE("deserializeMsgPack() filter") { + SpyingAllocator spy; + JsonDocument doc(&spy); + DeserializationError error; + + JsonDocument 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + }); + } + + SECTION("input truncated after before skipped string size") { + error = deserializeMsgPack(doc, "\x82\xA6ignore\xd9", 9, filterOpt); + + CHECK(error == DeserializationError::IncompleteInput); + CHECK(doc.as() == "{}"); + CHECK(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + }); + } + + SECTION("input truncated after before skipped ext size") { + error = deserializeMsgPack(doc, "\x82\xA6ignore\xC7", 9, filterOpt); + + CHECK(error == DeserializationError::IncompleteInput); + CHECK(doc.as() == "{}"); + CHECK(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + }); + } + + SECTION("skip nil") { + error = deserializeMsgPack(doc, "\x82\xA6ignore\xC0\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + SECTION("reject 0xc1") { + error = deserializeMsgPack(doc, "\x82\xA6ignore\xC1\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::InvalidInput); + CHECK(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + }); + } + + SECTION("skip false") { + error = deserializeMsgPack(doc, "\x82\xA6ignore\xC2\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + SECTION("skip true") { + error = deserializeMsgPack(doc, "\x82\xA6ignore\xC3\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + SECTION("skip positive fixint") { + error = deserializeMsgPack(doc, "\x82\xA6ignore\x2A\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + SECTION("skip negative fixint") { + error = deserializeMsgPack(doc, "\x82\xA6ignore\xFF\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + SECTION("skip uint 8") { + error = deserializeMsgPack(doc, "\x82\xA6ignore\xCC\x2A\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + SECTION("skip int 8") { + error = deserializeMsgPack(doc, "\x82\xA6ignore\xD0\x2A\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + SECTION("skip fixstr") { + error = deserializeMsgPack( + doc, "\x82\xA6ignore\xABhello world\xA7include\x2A", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + SECTION("skip str 8") { + error = deserializeMsgPack( + doc, "\x82\xA6ignore\xd9\x05hello\xA7include\x2A", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + SECTION("skip bin 8") { + error = deserializeMsgPack( + doc, "\x82\xA6ignore\xC4\x05hello\xA7include\x2A", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + SECTION("skip fixarray") { + error = deserializeMsgPack( + doc, "\x82\xA6ignore\x92\x01\x02\xA7include\x2A", filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":42}"); + CHECK(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("ignore")), + Deallocate(sizeofString("ignore")), + Allocate(sizeofString("include")), + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofObject(1)), + }); + } + } + + 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(spy.log() == + AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("location")), + Reallocate(sizeofString("location"), sizeofString("measure")), + Allocate(sizeofString("location")), + Reallocate(sizeofString("location"), sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2) + sizeofArray(2) + + 2 * sizeofObject(1)), + }); + } + + 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(spy.log() == + AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("location")), + Reallocate(sizeofString("location"), sizeofString("measure")), + Allocate(sizeofString("location")), + Reallocate(sizeofString("location"), sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2) + sizeofArray(2) + + 2 * sizeofObject(1)), + }); + } + + 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(spy.log() == + AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("location")), + Reallocate(sizeofString("location"), sizeofString("measure")), + Allocate(sizeofString("location")), + Reallocate(sizeofString("location"), sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2) + sizeofArray(2) + + 2 * sizeofObject(1)), + }); + } + + SECTION("skip null") { + error = deserializeMsgPack(doc, "\x82\xA7onlyarr\xC0\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyarr\":null,\"include\":42}"); + CHECK(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + SECTION("skip false") { + error = deserializeMsgPack(doc, "\x82\xA7onlyarr\xC2\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyarr\":null,\"include\":42}"); + CHECK(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + SECTION("skip true") { + error = deserializeMsgPack(doc, "\x82\xA7onlyarr\xC3\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyarr\":null,\"include\":42}"); + CHECK(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("one")), + Deallocate(sizeofString("one")), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("H")), + Deallocate(sizeofString("H")), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("zero")), + Deallocate(sizeofString("zero")), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + } + } + + 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(spy.log() == AllocatorLog()); + } + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofArray(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(spy.log() == + AllocatorLog{ + Allocate(sizeofString("onlyobj")), + Allocate(sizeofPool()), + Allocate(sizeofString("location")), + Reallocate(sizeofString("location"), sizeofString("measure")), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2) + sizeofObject(1)), + }); + } + + 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(spy.log() == + AllocatorLog{ + Allocate(sizeofString("onlyobj")), + Allocate(sizeofPool()), + Allocate(sizeofString("location")), + Reallocate(sizeofString("location"), sizeofString("measure")), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2) + sizeofObject(1)), + }); + } + + 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(spy.log() == + AllocatorLog{ + Allocate(sizeofString("onlyobj")), + Allocate(sizeofPool()), + Allocate(sizeofString("location")), + Reallocate(sizeofString("location"), sizeofString("measure")), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2) + sizeofObject(1)), + }); + } + + SECTION("skip null") { + error = deserializeMsgPack(doc, "\x82\xA7onlyobj\xC0\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyobj\":null,\"include\":42}"); + CHECK(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + SECTION("skip false") { + error = deserializeMsgPack(doc, "\x82\xA7onlyobj\xC2\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyobj\":null,\"include\":42}"); + CHECK(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + SECTION("skip true") { + error = deserializeMsgPack(doc, "\x82\xA7onlyobj\xC3\xA7include\x2A", + filterOpt); + + CHECK(error == DeserializationError::Ok); + CHECK(doc.as() == "{\"onlyobj\":null,\"include\":42}"); + CHECK(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + + 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(spy.log() == AllocatorLog{ + Allocate(sizeofString("onlyarr")), + Allocate(sizeofPool()), + Allocate(sizeofString("include")), + Reallocate(sizeofPool(), sizeofObject(2)), + }); + } + } + + 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"; + + JsonDocument filter; + filter["include"] = true; + + JsonDocument doc; + DeserializationError err = + deserializeMsgPack(doc, input, 18, DeserializationOption::Filter(filter)); + + CHECK(err == DeserializationError::Ok); + CHECK(doc.as() == "{\"include\":1}"); +} + +TEST_CASE("Overloads") { + JsonDocument doc; + JsonDocument 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, "{}"_s, 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, "{}"_s, 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, "{}"_s, 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/extras/tests/MsgPackDeserializer/input_types.cpp b/extras/tests/MsgPackDeserializer/input_types.cpp new file mode 100644 index 000000000..42f613780 --- /dev/null +++ b/extras/tests/MsgPackDeserializer/input_types.cpp @@ -0,0 +1,96 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "CustomReader.hpp" +#include "Literals.hpp" + +using ArduinoJson::detail::sizeofObject; + +TEST_CASE("deserializeMsgPack(const std::string&)") { + JsonDocument doc; + + 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, "\x92\x01\x02"_s); + + 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("hello"_s == array[0]); + } + + SECTION("should accept a zero in input") { + DeserializationError err = deserializeMsgPack(doc, "\x92\x00\x02"_s); + + REQUIRE(err == DeserializationError::Ok); + JsonArray arr = doc.as(); + REQUIRE(arr[0] == 0); + REQUIRE(arr[1] == 2); + } +} + +TEST_CASE("deserializeMsgPack(std::istream&)") { + JsonDocument doc; + + SECTION("should accept a zero in input") { + std::istringstream input("\x92\x00\x02"_s); + + 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); + + JsonDocument doc; + DeserializationError err = deserializeMsgPack(doc, vla); + + REQUIRE(err == DeserializationError::Ok); +} +#endif + +TEST_CASE("deserializeMsgPack(CustomReader)") { + JsonDocument doc; + 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/extras/tests/MsgPackDeserializer/nestingLimit.cpp b/extras/tests/MsgPackDeserializer/nestingLimit.cpp new file mode 100644 index 000000000..a41ea0a4f --- /dev/null +++ b/extras/tests/MsgPackDeserializer/nestingLimit.cpp @@ -0,0 +1,87 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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") { + JsonDocument doc; + + 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/extras/tests/MsgPackSerializer/CMakeLists.txt b/extras/tests/MsgPackSerializer/CMakeLists.txt new file mode 100644 index 000000000..8f484bbec --- /dev/null +++ b/extras/tests/MsgPackSerializer/CMakeLists.txt @@ -0,0 +1,19 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2025, 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/extras/tests/MsgPackSerializer/destination_types.cpp b/extras/tests/MsgPackSerializer/destination_types.cpp new file mode 100644 index 000000000..160ca8a57 --- /dev/null +++ b/extras/tests/MsgPackSerializer/destination_types.cpp @@ -0,0 +1,59 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("serialize MsgPack to various destination types") { + JsonDocument doc; + 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/extras/tests/MsgPackSerializer/measure.cpp b/extras/tests/MsgPackSerializer/measure.cpp new file mode 100644 index 000000000..882069bcf --- /dev/null +++ b/extras/tests/MsgPackSerializer/measure.cpp @@ -0,0 +1,14 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +TEST_CASE("measureMsgPack()") { + JsonDocument doc; + JsonObject object = doc.to(); + object["hello"] = "world"; + + REQUIRE(measureMsgPack(doc) == 13); +} diff --git a/extras/tests/MsgPackSerializer/misc.cpp b/extras/tests/MsgPackSerializer/misc.cpp new file mode 100644 index 000000000..bea9b242a --- /dev/null +++ b/extras/tests/MsgPackSerializer/misc.cpp @@ -0,0 +1,46 @@ +#include +#include +#include + +template +void check(T value, const std::string& expected) { + JsonDocument doc; + 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)") { + JsonDocument doc; + deserializeJson(doc, "{\"hello\":42}"); + JsonObject obj = doc.as(); + std::string result; + + serializeMsgPack(obj["hello"], result); + + REQUIRE(result == "*"); +} + +TEST_CASE("serializeMsgPack(ElementProxy)") { + JsonDocument doc; + deserializeJson(doc, "[42]"); + JsonArray arr = doc.as(); + std::string result; + + serializeMsgPack(arr[0], result); + + REQUIRE(result == "*"); +} + +TEST_CASE("serializeMsgPack(JsonVariantSubscript)") { + JsonDocument doc; + deserializeJson(doc, "[42]"); + JsonVariant var = doc.as(); + std::string result; + + serializeMsgPack(var[0], result); + + REQUIRE(result == "*"); +} diff --git a/extras/tests/MsgPackSerializer/serializeArray.cpp b/extras/tests/MsgPackSerializer/serializeArray.cpp new file mode 100644 index 000000000..953904198 --- /dev/null +++ b/extras/tests/MsgPackSerializer/serializeArray.cpp @@ -0,0 +1,64 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#define ARDUINOJSON_SLOT_ID_SIZE 4 // required to reach 65536 elements + +#include +#include + +#include "Literals.hpp" + +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") { + JsonDocument doc; + 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); + REQUIRE(array.size() == 65536); + + check(array, "\xDD\x00\x01\x00\x00"_s + std::string(65536, '\xc0')); + } +} diff --git a/extras/tests/MsgPackSerializer/serializeObject.cpp b/extras/tests/MsgPackSerializer/serializeObject.cpp new file mode 100644 index 000000000..7dc1526c3 --- /dev/null +++ b/extras/tests/MsgPackSerializer/serializeObject.cpp @@ -0,0 +1,85 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include +#include + +#include "Literals.hpp" + +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") { + JsonDocument doc; + 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]; + snprintf(key, sizeof(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]; + // snprintf(kv, sizeof(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("\xDB\x00\x01\x00\x00"_s); + check(object, "\x81\xA5hello\xDB\x00\x01\x00\x00"); + } +} diff --git a/extras/tests/MsgPackSerializer/serializeVariant.cpp b/extras/tests/MsgPackSerializer/serializeVariant.cpp new file mode 100644 index 000000000..56faccd4d --- /dev/null +++ b/extras/tests/MsgPackSerializer/serializeVariant.cpp @@ -0,0 +1,214 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Literals.hpp" + +template +static void checkVariant(T value, const char* expected_data, + size_t expected_len) { + JsonDocument doc; + 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(), "\xDA\x01\x00"_s + shortest); + + std::string longest(65535, '?'); + checkVariant(longest.c_str(), "\xDA\xFF\xFF"_s + longest); + } + + SECTION("str 32") { + std::string shortest(65536, '?'); + checkVariant(JsonString(shortest.c_str(), true), // force store by pointer + "\xDB\x00\x01\x00\x00"_s + 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("bin 8") { + checkVariant(MsgPackBinary("?", 1), "\xC4\x01?"); + } + + SECTION("bin 16") { + auto str = std::string(256, '?'); + checkVariant(MsgPackBinary(str.data(), str.size()), "\xC5\x01\x00"_s + str); + } + + // bin 32 is tested in string_length_size_4.cpp + + SECTION("fixext 1") { + checkVariant(MsgPackExtension(1, "\x02", 1), "\xD4\x01\x02"); + } + + SECTION("fixext 2") { + checkVariant(MsgPackExtension(1, "\x03\x04", 2), "\xD5\x01\x03\x04"); + } + + SECTION("fixext 4") { + checkVariant(MsgPackExtension(1, "\x05\x06\x07\x08", 4), + "\xD6\x01\x05\x06\x07\x08"); + } + + SECTION("fixext 8") { + checkVariant(MsgPackExtension(1, "????????", 8), "\xD7\x01????????"); + } + + SECTION("fixext 16") { + checkVariant(MsgPackExtension(1, "????????????????", 16), + "\xD8\x01????????????????"); + } + + SECTION("ext 8") { + checkVariant(MsgPackExtension(2, "???", 3), "\xC7\x03\x02???"); + checkVariant(MsgPackExtension(2, "?????", 5), "\xC7\x05\x02?????"); + checkVariant(MsgPackExtension(2, "???????", 7), "\xC7\x07\x02???????"); + checkVariant(MsgPackExtension(2, "?????????", 9), "\xC7\x09\x02?????????"); + checkVariant(MsgPackExtension(2, "???????????????", 15), + "\xC7\x0F\x02???????????????"); + checkVariant(MsgPackExtension(2, "?????????????????", 17), + "\xC7\x11\x02?????????????????"); + } + + SECTION("ext 16") { + auto str = std::string(256, '?'); + checkVariant(MsgPackExtension(2, str.data(), str.size()), + "\xC8\x01\x00\x02"_s + str); + } + + 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/extras/tests/Numbers/CMakeLists.txt b/extras/tests/Numbers/CMakeLists.txt new file mode 100644 index 000000000..6505ce756 --- /dev/null +++ b/extras/tests/Numbers/CMakeLists.txt @@ -0,0 +1,19 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2025, Benoit BLANCHON +# MIT License + +add_executable(NumbersTests + convertNumber.cpp + decomposeFloat.cpp + parseDouble.cpp + parseFloat.cpp + parseInteger.cpp + parseNumber.cpp +) + +add_test(Numbers NumbersTests) + +set_tests_properties(Numbers + PROPERTIES + LABELS "Catch" +) diff --git a/extras/tests/Numbers/convertNumber.cpp b/extras/tests/Numbers/convertNumber.cpp new file mode 100644 index 000000000..98cd6763a --- /dev/null +++ b/extras/tests/Numbers/convertNumber.cpp @@ -0,0 +1,131 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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/extras/tests/Numbers/decomposeFloat.cpp b/extras/tests/Numbers/decomposeFloat.cpp new file mode 100644 index 000000000..e0578f6ca --- /dev/null +++ b/extras/tests/Numbers/decomposeFloat.cpp @@ -0,0 +1,42 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +using namespace ArduinoJson::detail; + +TEST_CASE("decomposeFloat()") { + SECTION("1.7976931348623157E+308") { + auto parts = decomposeFloat(1.7976931348623157E+308, 9); + REQUIRE(parts.integral == 1); + REQUIRE(parts.decimal == 797693135); + REQUIRE(parts.decimalPlaces == 9); + REQUIRE(parts.exponent == 308); + } + + SECTION("4.94065645841247e-324") { + auto parts = decomposeFloat(4.94065645841247e-324, 9); + REQUIRE(parts.integral == 4); + REQUIRE(parts.decimal == 940656458); + REQUIRE(parts.decimalPlaces == 9); + REQUIRE(parts.exponent == -324); + } + + SECTION("3.4E+38") { + auto parts = decomposeFloat(3.4E+38f, 6); + REQUIRE(parts.integral == 3); + REQUIRE(parts.decimal == 4); + REQUIRE(parts.decimalPlaces == 1); + REQUIRE(parts.exponent == 38); + } + + SECTION("1.17549435e−38") { + auto parts = decomposeFloat(1.17549435e-38f, 6); + REQUIRE(parts.integral == 1); + REQUIRE(parts.decimal == 175494); + REQUIRE(parts.decimalPlaces == 6); + REQUIRE(parts.exponent == -38); + } +} diff --git a/extras/tests/Numbers/parseDouble.cpp b/extras/tests/Numbers/parseDouble.cpp new file mode 100644 index 000000000..a45927902 --- /dev/null +++ b/extras/tests/Numbers/parseDouble.cpp @@ -0,0 +1,96 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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/extras/tests/Numbers/parseFloat.cpp b/extras/tests/Numbers/parseFloat.cpp new file mode 100644 index 000000000..62c0917ce --- /dev/null +++ b/extras/tests/Numbers/parseFloat.cpp @@ -0,0 +1,87 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#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); + auto result = parseNumber(input); + REQUIRE(result.type() == NumberType::Float); + REQUIRE(result.asFloat() == 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); + + // The following don't work because they have many digits so parseNumber() + // treats them as double. But it's not an issue because JsonVariant will use + // a float to store them. + // + // checkFloat("100000000000000000000000000000000.0", 1e+32f); + // checkFloat( + // "100000000000000000000000000000000.00000000000000000000000000000", + // 1e+32f); + } + + 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); + } +} diff --git a/extras/tests/Numbers/parseInteger.cpp b/extras/tests/Numbers/parseInteger.cpp new file mode 100644 index 000000000..aff235852 --- /dev/null +++ b/extras/tests/Numbers/parseInteger.cpp @@ -0,0 +1,68 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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/extras/tests/Numbers/parseNumber.cpp b/extras/tests/Numbers/parseNumber.cpp new file mode 100644 index 000000000..37b12bb7c --- /dev/null +++ b/extras/tests/Numbers/parseNumber.cpp @@ -0,0 +1,63 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +using namespace ArduinoJson; +using namespace ArduinoJson::detail; + +TEST_CASE("Test unsigned integer overflow") { + Number first, second; + + // Avoids MSVC warning C4127 (conditional expression is constant) + size_t integerSize = sizeof(JsonInteger); + + if (integerSize == 8) { + first = parseNumber("18446744073709551615"); + second = parseNumber("18446744073709551616"); + } else { + first = parseNumber("4294967295"); + second = parseNumber("4294967296"); + } + + REQUIRE(first.type() == NumberType::UnsignedInteger); + REQUIRE(second.type() == NumberType::Double); +} + +TEST_CASE("Test signed integer overflow") { + Number first, second; + + // Avoids MSVC warning C4127 (conditional expression is constant) + size_t integerSize = sizeof(JsonInteger); + + if (integerSize == 8) { + first = parseNumber("-9223372036854775808"); + second = parseNumber("-9223372036854775809"); + } else { + first = parseNumber("-2147483648"); + second = parseNumber("-2147483649"); + } + + REQUIRE(first.type() == NumberType::SignedInteger); + REQUIRE(second.type() == NumberType::Double); +} + +TEST_CASE("Invalid value") { + auto result = parseNumber("6a3"); + + REQUIRE(result.type() == NumberType::Invalid); +} + +TEST_CASE("float") { + auto result = parseNumber("3.402823e38"); + + REQUIRE(result.type() == NumberType::Float); +} + +TEST_CASE("double") { + auto result = parseNumber("1.7976931348623157e308"); + + REQUIRE(result.type() == NumberType::Double); +} diff --git a/extras/tests/ResourceManager/CMakeLists.txt b/extras/tests/ResourceManager/CMakeLists.txt new file mode 100644 index 000000000..3a0908af5 --- /dev/null +++ b/extras/tests/ResourceManager/CMakeLists.txt @@ -0,0 +1,26 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2025, Benoit BLANCHON +# MIT License + +add_executable(ResourceManagerTests + allocVariant.cpp + clear.cpp + saveString.cpp + shrinkToFit.cpp + size.cpp + StringBuffer.cpp + StringBuilder.cpp + swap.cpp +) + +add_compile_definitions(ResourceManagerTests + ARDUINOJSON_SLOT_ID_SIZE=1 # require less RAM for overflow tests + ARDUINOJSON_POOL_CAPACITY=16 +) + +add_test(ResourceManager ResourceManagerTests) + +set_tests_properties(ResourceManager + PROPERTIES + LABELS "Catch" +) diff --git a/extras/tests/ResourceManager/StringBuffer.cpp b/extras/tests/ResourceManager/StringBuffer.cpp new file mode 100644 index 000000000..1fb2b01b2 --- /dev/null +++ b/extras/tests/ResourceManager/StringBuffer.cpp @@ -0,0 +1,50 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Allocators.hpp" +#include "Literals.hpp" + +using namespace ArduinoJson::detail; + +TEST_CASE("StringBuffer") { + SpyingAllocator spy; + ResourceManager resources(&spy); + StringBuffer sb(&resources); + VariantData variant; + + SECTION("Tiny string") { + auto ptr = sb.reserve(3); + strcpy(ptr, "hi!"); + sb.save(&variant); + + REQUIRE(variant.type() == VariantType::TinyString); + REQUIRE(variant.asString() == "hi!"); + } + + SECTION("Tiny string can't contain NUL") { + auto ptr = sb.reserve(3); + memcpy(ptr, "a\0b", 3); + sb.save(&variant); + + REQUIRE(variant.type() == VariantType::OwnedString); + + auto str = variant.asString(); + REQUIRE(str.size() == 3); + REQUIRE(str.c_str()[0] == 'a'); + REQUIRE(str.c_str()[1] == 0); + REQUIRE(str.c_str()[2] == 'b'); + } + + SECTION("Tiny string can't have 4 characters") { + auto ptr = sb.reserve(4); + strcpy(ptr, "alfa"); + sb.save(&variant); + + REQUIRE(variant.type() == VariantType::OwnedString); + REQUIRE(variant.asString() == "alfa"); + } +} diff --git a/extras/tests/ResourceManager/StringBuilder.cpp b/extras/tests/ResourceManager/StringBuilder.cpp new file mode 100644 index 000000000..5c6dd2208 --- /dev/null +++ b/extras/tests/ResourceManager/StringBuilder.cpp @@ -0,0 +1,186 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Allocators.hpp" + +using namespace ArduinoJson; +using namespace ArduinoJson::detail; + +TEST_CASE("StringBuilder") { + KillswitchAllocator killswitch; + SpyingAllocator spyingAllocator(&killswitch); + ResourceManager resources(&spyingAllocator); + + SECTION("Empty string") { + StringBuilder str(&resources); + VariantData data; + + str.startString(); + str.save(&data); + + REQUIRE(resources.overflowed() == false); + REQUIRE(spyingAllocator.log() == AllocatorLog{ + Allocate(sizeofStringBuffer()), + }); + REQUIRE(data.type() == VariantType::TinyString); + } + + SECTION("Tiny string") { + StringBuilder str(&resources); + + str.startString(); + str.append("url"); + + REQUIRE(str.isValid() == true); + REQUIRE(str.str() == "url"); + REQUIRE(spyingAllocator.log() == AllocatorLog{ + Allocate(sizeofStringBuffer()), + }); + + VariantData data; + str.save(&data); + + REQUIRE(resources.overflowed() == false); + REQUIRE(data.type() == VariantType::TinyString); + REQUIRE(data.asString() == "url"); + } + + SECTION("Short string fits in first allocation") { + StringBuilder str(&resources); + + str.startString(); + str.append("hello"); + + REQUIRE(str.isValid() == true); + REQUIRE(str.str() == "hello"); + REQUIRE(resources.overflowed() == false); + REQUIRE(spyingAllocator.log() == AllocatorLog{ + Allocate(sizeofStringBuffer()), + }); + } + + SECTION("Long string needs reallocation") { + StringBuilder str(&resources); + const char* lorem = + "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do " + "eiusmod tempor incididunt ut labore et dolore magna aliqua."; + + str.startString(); + str.append(lorem); + + REQUIRE(str.isValid() == true); + REQUIRE(str.str() == lorem); + REQUIRE(resources.overflowed() == false); + REQUIRE(spyingAllocator.log() == + AllocatorLog{ + Allocate(sizeofStringBuffer(1)), + Reallocate(sizeofStringBuffer(1), sizeofStringBuffer(2)), + Reallocate(sizeofStringBuffer(2), sizeofStringBuffer(3)), + }); + } + + SECTION("Realloc fails") { + StringBuilder str(&resources); + + str.startString(); + killswitch.on(); + str.append( + "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do " + "eiusmod tempor incididunt ut labore et dolore magna aliqua."); + + REQUIRE(spyingAllocator.log() == + AllocatorLog{ + Allocate(sizeofStringBuffer()), + ReallocateFail(sizeofStringBuffer(), sizeofStringBuffer(2)), + Deallocate(sizeofStringBuffer()), + }); + REQUIRE(str.isValid() == false); + REQUIRE(resources.overflowed() == true); + } + + SECTION("Initial allocation fails") { + StringBuilder str(&resources); + + killswitch.on(); + str.startString(); + + REQUIRE(str.isValid() == false); + REQUIRE(resources.overflowed() == true); + REQUIRE(spyingAllocator.log() == AllocatorLog{ + AllocateFail(sizeofStringBuffer()), + }); + } +} + +static VariantData saveString(StringBuilder& builder, const char* s) { + VariantData data; + builder.startString(); + builder.append(s); + builder.save(&data); + return data; +} + +TEST_CASE("StringBuilder::save() deduplicates strings") { + SpyingAllocator spy; + ResourceManager resources(&spy); + StringBuilder builder(&resources); + + SECTION("Basic") { + auto s1 = saveString(builder, "hello"); + auto s2 = saveString(builder, "world"); + auto s3 = saveString(builder, "hello"); + + REQUIRE(s1.asString() == "hello"); + REQUIRE(s2.asString() == "world"); + REQUIRE(+s1.asString().c_str() == +s3.asString().c_str()); // same address + + REQUIRE(spy.log() == + AllocatorLog{ + Allocate(sizeofStringBuffer()), + Reallocate(sizeofStringBuffer(), sizeofString("hello")), + Allocate(sizeofStringBuffer()), + Reallocate(sizeofStringBuffer(), sizeofString("world")), + Allocate(sizeofStringBuffer()), + }); + } + + SECTION("Requires terminator") { + auto s1 = saveString(builder, "hello world"); + auto s2 = saveString(builder, "hello"); + + REQUIRE(s1.asString() == "hello world"); + REQUIRE(s2.asString() == "hello"); + REQUIRE(+s2.asString().c_str() != + +s1.asString().c_str()); // different address + + REQUIRE(spy.log() == + AllocatorLog{ + Allocate(sizeofStringBuffer()), + Reallocate(sizeofStringBuffer(), sizeofString("hello world")), + Allocate(sizeofStringBuffer()), + Reallocate(sizeofStringBuffer(), sizeofString("hello")), + }); + } + + SECTION("Don't overrun") { + auto s1 = saveString(builder, "hello world"); + auto s2 = saveString(builder, "worl"); + + REQUIRE(s1.asString() == "hello world"); + REQUIRE(s2.asString() == "worl"); + REQUIRE(s2.asString().c_str() != + s1.asString().c_str()); // different address + + REQUIRE(spy.log() == + AllocatorLog{ + Allocate(sizeofStringBuffer()), + Reallocate(sizeofStringBuffer(), sizeofString("hello world")), + Allocate(sizeofStringBuffer()), + Reallocate(sizeofStringBuffer(), sizeofString("worl")), + }); + } +} diff --git a/extras/tests/ResourceManager/allocVariant.cpp b/extras/tests/ResourceManager/allocVariant.cpp new file mode 100644 index 000000000..05687917d --- /dev/null +++ b/extras/tests/ResourceManager/allocVariant.cpp @@ -0,0 +1,92 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +#include "Allocators.hpp" + +using namespace ArduinoJson::detail; + +TEST_CASE("ResourceManager::allocVariant()") { + SECTION("Returns different pointer") { + ResourceManager resources; + + auto s1 = resources.allocVariant(); + REQUIRE(s1.ptr() != nullptr); + auto s2 = resources.allocVariant(); + REQUIRE(s2.ptr() != nullptr); + + REQUIRE(s1.ptr() != s2.ptr()); + } + + SECTION("Returns the same slot after calling freeVariant()") { + ResourceManager resources; + + auto s1 = resources.allocVariant(); + auto s2 = resources.allocVariant(); + resources.freeVariant(s1); + resources.freeVariant(s2); + auto s3 = resources.allocVariant(); + auto s4 = resources.allocVariant(); + auto s5 = resources.allocVariant(); + + REQUIRE(s2.id() != s1.id()); + REQUIRE(s3.id() == s2.id()); + REQUIRE(s4.id() == s1.id()); + REQUIRE(s5.id() != s1.id()); + REQUIRE(s5.id() != s2.id()); + } + + SECTION("Returns aligned pointers") { + ResourceManager resources; + + REQUIRE(isAligned(resources.allocVariant().ptr())); + REQUIRE(isAligned(resources.allocVariant().ptr())); + } + + SECTION("Returns null if pool list allocation fails") { + ResourceManager resources(FailingAllocator::instance()); + + auto variant = resources.allocVariant(); + REQUIRE(variant.id() == NULL_SLOT); + REQUIRE(variant.ptr() == nullptr); + } + + SECTION("Returns null if pool allocation fails") { + ResourceManager resources(FailingAllocator::instance()); + + resources.allocVariant(); + + auto variant = resources.allocVariant(); + REQUIRE(variant.id() == NULL_SLOT); + REQUIRE(variant.ptr() == nullptr); + } + + SECTION("Try overflow pool counter") { + ResourceManager resources; + + // this test assumes SlotId is 8-bit; otherwise it consumes a lot of memory + // tyhe GitHub Workflow gets killed + REQUIRE(NULL_SLOT == 255); + + // fill all the pools + for (SlotId i = 0; i < NULL_SLOT; i++) { + auto slot = resources.allocVariant(); + REQUIRE(slot.id() == i); // or != NULL_SLOT + REQUIRE(slot.ptr() != nullptr); + } + + REQUIRE(resources.overflowed() == false); + + // now all allocations should fail + for (int i = 0; i < 10; i++) { + auto slot = resources.allocVariant(); + REQUIRE(slot.id() == NULL_SLOT); + REQUIRE(slot.ptr() == nullptr); + } + + REQUIRE(resources.overflowed() == true); + } +} diff --git a/extras/tests/ResourceManager/clear.cpp b/extras/tests/ResourceManager/clear.cpp new file mode 100644 index 000000000..e77077634 --- /dev/null +++ b/extras/tests/ResourceManager/clear.cpp @@ -0,0 +1,30 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include +#include +#include + +using namespace ArduinoJson::detail; + +TEST_CASE("ResourceManager::clear()") { + ResourceManager resources; + + SECTION("Discards allocated variants") { + resources.allocVariant(); + + resources.clear(); + REQUIRE(resources.size() == 0); + } + + SECTION("Discards allocated strings") { + resources.saveString(adaptString("123456789")); + REQUIRE(resources.size() == sizeofString(9)); + + resources.clear(); + + REQUIRE(resources.size() == 0); + } +} diff --git a/extras/tests/ResourceManager/saveString.cpp b/extras/tests/ResourceManager/saveString.cpp new file mode 100644 index 000000000..3c7a228b7 --- /dev/null +++ b/extras/tests/ResourceManager/saveString.cpp @@ -0,0 +1,70 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include +#include + +#include "Allocators.hpp" + +using namespace ArduinoJson::detail; + +static StringNode* saveString(ResourceManager& resources, const char* s) { + return resources.saveString(adaptString(s)); +} + +static StringNode* saveString(ResourceManager& resources, const char* s, + size_t n) { + return resources.saveString(adaptString(s, n)); +} + +TEST_CASE("ResourceManager::saveString()") { + ResourceManager resources; + + SECTION("Duplicates different strings") { + auto a = saveString(resources, "hello"); + auto b = saveString(resources, "world"); + REQUIRE(+a->data != +b->data); + REQUIRE(a->length == 5); + REQUIRE(b->length == 5); + REQUIRE(a->references == 1); + REQUIRE(b->references == 1); + REQUIRE(resources.size() == sizeofString("hello") + sizeofString("world")); + } + + SECTION("Deduplicates identical strings") { + auto a = saveString(resources, "hello"); + auto b = saveString(resources, "hello"); + REQUIRE(a == b); + REQUIRE(a->length == 5); + REQUIRE(a->references == 2); + REQUIRE(resources.size() == sizeofString("hello")); + } + + SECTION("Deduplicates identical strings that contain NUL") { + auto a = saveString(resources, "hello\0world", 11); + auto b = saveString(resources, "hello\0world", 11); + REQUIRE(a == b); + REQUIRE(a->length == 11); + REQUIRE(a->references == 2); + REQUIRE(resources.size() == sizeofString("hello world")); + } + + SECTION("Don't stop on first NUL") { + auto a = saveString(resources, "hello"); + auto b = saveString(resources, "hello\0world", 11); + REQUIRE(a != b); + REQUIRE(a->length == 5); + REQUIRE(b->length == 11); + REQUIRE(a->references == 1); + REQUIRE(b->references == 1); + REQUIRE(resources.size() == + sizeofString("hello") + sizeofString("hello world")); + } + + SECTION("Returns NULL when allocation fails") { + ResourceManager pool2(FailingAllocator::instance()); + REQUIRE(saveString(pool2, "a") == nullptr); + } +} diff --git a/extras/tests/ResourceManager/shrinkToFit.cpp b/extras/tests/ResourceManager/shrinkToFit.cpp new file mode 100644 index 000000000..4f1eb5de8 --- /dev/null +++ b/extras/tests/ResourceManager/shrinkToFit.cpp @@ -0,0 +1,57 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include +#include + +#include "Allocators.hpp" + +using namespace ArduinoJson::detail; + +TEST_CASE("ResourceManager::shrinkToFit()") { + SpyingAllocator spyingAllocator; + ResourceManager resources(&spyingAllocator); + + SECTION("empty") { + resources.shrinkToFit(); + + REQUIRE(spyingAllocator.log() == AllocatorLog{}); + } + + SECTION("only one pool") { + resources.allocVariant(); + + resources.shrinkToFit(); + + REQUIRE(spyingAllocator.log() == + AllocatorLog{ + Allocate(sizeofPool()), + Reallocate(sizeofPool(), sizeofPool(1)), + }); + } + + SECTION("more pools than initial count") { + for (size_t i = 0; + i < ARDUINOJSON_POOL_CAPACITY * ARDUINOJSON_INITIAL_POOL_COUNT + 1; + i++) + resources.allocVariant(); + REQUIRE(spyingAllocator.log() == + AllocatorLog{ + Allocate(sizeofPool()) * ARDUINOJSON_INITIAL_POOL_COUNT, + Allocate(sizeofPoolList(ARDUINOJSON_INITIAL_POOL_COUNT * 2)), + Allocate(sizeofPool()), + }); + + spyingAllocator.clearLog(); + resources.shrinkToFit(); + + REQUIRE(spyingAllocator.log() == + AllocatorLog{ + Reallocate(sizeofPool(), sizeofPool(1)), + Reallocate(sizeofPoolList(ARDUINOJSON_INITIAL_POOL_COUNT * 2), + sizeofPoolList(ARDUINOJSON_INITIAL_POOL_COUNT + 1)), + }); + } +} diff --git a/extras/tests/ResourceManager/size.cpp b/extras/tests/ResourceManager/size.cpp new file mode 100644 index 000000000..17f3f42e8 --- /dev/null +++ b/extras/tests/ResourceManager/size.cpp @@ -0,0 +1,31 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include +#include + +#include "Allocators.hpp" + +using namespace ArduinoJson::detail; + +TEST_CASE("ResourceManager::size()") { + TimebombAllocator timebomb(0); + ResourceManager resources(&timebomb); + + SECTION("Initial size is 0") { + REQUIRE(0 == resources.size()); + } + + SECTION("Doesn't grow when allocation of second pool fails") { + timebomb.setCountdown(1); + for (size_t i = 0; i < ARDUINOJSON_POOL_CAPACITY; i++) + resources.allocVariant(); + size_t size = resources.size(); + + resources.allocVariant(); + + REQUIRE(size == resources.size()); + } +} diff --git a/extras/tests/ResourceManager/swap.cpp b/extras/tests/ResourceManager/swap.cpp new file mode 100644 index 000000000..f5d8feece --- /dev/null +++ b/extras/tests/ResourceManager/swap.cpp @@ -0,0 +1,96 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include +#include +#include + +#include "Allocators.hpp" + +using namespace ArduinoJson::detail; + +static void fullPreallocatedPools(ResourceManager& resources) { + for (int i = 0; + i < ARDUINOJSON_INITIAL_POOL_COUNT * ARDUINOJSON_POOL_CAPACITY; i++) + resources.allocVariant(); +} + +TEST_CASE("ResourceManager::swap()") { + SECTION("Both using preallocated pool list") { + SpyingAllocator spy; + ResourceManager a(&spy); + ResourceManager b(&spy); + + auto a1 = a.allocVariant(); + auto b1 = b.allocVariant(); + + swap(a, b); + + REQUIRE(a1.ptr() == b.getVariant(a1.id())); + REQUIRE(b1.ptr() == a.getVariant(b1.id())); + + REQUIRE(spy.log() == AllocatorLog{ + Allocate(sizeofPool()) * 2, + }); + } + + SECTION("Only left using preallocated pool list") { + SpyingAllocator spy; + ResourceManager a(&spy); + ResourceManager b(&spy); + fullPreallocatedPools(b); + + auto a1 = a.allocVariant(); + auto b1 = b.allocVariant(); + swap(a, b); + + REQUIRE(a1.ptr() == b.getVariant(a1.id())); + REQUIRE(b1.ptr() == a.getVariant(b1.id())); + + REQUIRE(spy.log() == + AllocatorLog{ + Allocate(sizeofPool()) * (ARDUINOJSON_INITIAL_POOL_COUNT + 1), + Allocate(sizeofPoolList(ARDUINOJSON_INITIAL_POOL_COUNT * 2)), + Allocate(sizeofPool()), + }); + } + + SECTION("Only right using preallocated pool list") { + SpyingAllocator spy; + ResourceManager a(&spy); + fullPreallocatedPools(a); + ResourceManager b(&spy); + + auto a1 = a.allocVariant(); + auto b1 = b.allocVariant(); + swap(a, b); + + REQUIRE(a1.ptr() == b.getVariant(a1.id())); + REQUIRE(b1.ptr() == a.getVariant(b1.id())); + + REQUIRE(spy.log() == + AllocatorLog{ + Allocate(sizeofPool()) * ARDUINOJSON_INITIAL_POOL_COUNT, + Allocate(sizeofPoolList(ARDUINOJSON_INITIAL_POOL_COUNT * 2)), + Allocate(sizeofPool()) * 2, + }); + } + + SECTION("None is using preallocated pool list") { + SpyingAllocator spy; + ResourceManager a(&spy); + fullPreallocatedPools(a); + ResourceManager b(&spy); + fullPreallocatedPools(b); + + auto a1 = a.allocVariant(); + auto b1 = b.allocVariant(); + + swap(a, b); + + REQUIRE(a1.ptr() == b.getVariant(a1.id())); + REQUIRE(b1.ptr() == a.getVariant(b1.id())); + } +} diff --git a/extras/tests/TextFormatter/CMakeLists.txt b/extras/tests/TextFormatter/CMakeLists.txt new file mode 100644 index 000000000..79618c784 --- /dev/null +++ b/extras/tests/TextFormatter/CMakeLists.txt @@ -0,0 +1,18 @@ +# ArduinoJson - https://arduinojson.org +# Copyright © 2014-2025, 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/extras/tests/TextFormatter/writeFloat.cpp b/extras/tests/TextFormatter/writeFloat.cpp new file mode 100644 index 000000000..1afcaec55 --- /dev/null +++ b/extras/tests/TextFormatter/writeFloat.cpp @@ -0,0 +1,119 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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/extras/tests/TextFormatter/writeInteger.cpp b/extras/tests/TextFormatter/writeInteger.cpp new file mode 100644 index 000000000..47a864c32 --- /dev/null +++ b/extras/tests/TextFormatter/writeInteger.cpp @@ -0,0 +1,55 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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/extras/tests/TextFormatter/writeString.cpp b/extras/tests/TextFormatter/writeString.cpp new file mode 100644 index 000000000..35ae29778 --- /dev/null +++ b/extras/tests/TextFormatter/writeString.cpp @@ -0,0 +1,57 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, 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/extras/tests/catch/.clang-format b/extras/tests/catch/.clang-format new file mode 100644 index 000000000..9d159247d --- /dev/null +++ b/extras/tests/catch/.clang-format @@ -0,0 +1,2 @@ +DisableFormat: true +SortIncludes: false diff --git a/extras/tests/catch/CMakeLists.txt b/extras/tests/catch/CMakeLists.txt new file mode 100644 index 000000000..c5fb5fb83 --- /dev/null +++ b/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/extras/tests/catch/catch.cpp b/extras/tests/catch/catch.cpp new file mode 100644 index 000000000..e6c8548a9 --- /dev/null +++ b/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/extras/tests/catch/catch.hpp b/extras/tests/catch/catch.hpp new file mode 100644 index 000000000..9b309bddc --- /dev/null +++ b/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