Changed unit testing framework from Google Test to Catch

This commit is contained in:
Benoit Blanchon
2017-04-18 18:22:24 +02:00
parent f2ef338cb8
commit df541a2a22
266 changed files with 15955 additions and 146149 deletions

View File

@ -5,11 +5,8 @@
# https://bblanchon.github.io/ArduinoJson/
# If you like this project, please add a star!
include(gtest.cmake)
if(CMAKE_CXX_COMPILER_ID MATCHES "(GNU|Clang)")
add_compile_options(
-fno-exceptions
-pedantic
-Wall
-Wcast-align

View File

@ -6,12 +6,13 @@
# If you like this project, please add a star!
add_executable(DynamicJsonBufferTests
array.cpp
basics.cpp
noMemory.cpp
object.cpp
string.cpp
alloc.cpp
createArray.cpp
no_memory.cpp
createObject.cpp
strdup.cpp
startString.cpp
)
target_link_libraries(DynamicJsonBufferTests gtest)
target_link_libraries(DynamicJsonBufferTests catch)
add_test(DynamicJsonBuffer DynamicJsonBufferTests)

View File

@ -0,0 +1,45 @@
// Copyright Benoit Blanchon 2014-2017
// MIT License
//
// Arduino JSON library
// https://bblanchon.github.io/ArduinoJson/
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <catch.hpp>
static bool isAligned(void* ptr) {
const size_t mask = sizeof(void*) - 1;
size_t addr = reinterpret_cast<size_t>(ptr);
return (addr & mask) == 0;
}
TEST_CASE("DynamicJsonBuffer::alloc()") {
DynamicJsonBuffer buffer;
SECTION("InitialSizeIsZero") {
REQUIRE(0 == buffer.size());
}
SECTION("SizeIncreasesAfterAlloc") {
buffer.alloc(1);
REQUIRE(1U <= buffer.size());
buffer.alloc(1);
REQUIRE(2U <= buffer.size());
}
SECTION("ReturnDifferentPointer") {
void* p1 = buffer.alloc(1);
void* p2 = buffer.alloc(2);
REQUIRE(p1 != p2);
}
SECTION("Alignment") {
// make room for two but not three
buffer = DynamicJsonBuffer(2 * sizeof(void*) + 1);
REQUIRE(isAligned(buffer.alloc(1))); // this on is aligned by design
REQUIRE(isAligned(buffer.alloc(1))); // this one fits in the first block
REQUIRE(isAligned(buffer.alloc(1))); // this one requires a new block
}
}

View File

@ -1,33 +0,0 @@
// Copyright Benoit Blanchon 2014-2017
// MIT License
//
// Arduino JSON library
// https://bblanchon.github.io/ArduinoJson/
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
TEST(DynamicJsonBuffer_Array_Tests, GrowsWithArray) {
DynamicJsonBuffer jsonBuffer;
JsonArray &array = jsonBuffer.createArray();
ASSERT_EQ(JSON_ARRAY_SIZE(0), jsonBuffer.size());
array.add("hello");
ASSERT_EQ(JSON_ARRAY_SIZE(1), jsonBuffer.size());
array.add("world");
ASSERT_EQ(JSON_ARRAY_SIZE(2), jsonBuffer.size());
}
TEST(DynamicJsonBuffer_Array_Tests, CanAdd1000Values) {
DynamicJsonBuffer jsonBuffer;
JsonArray &array = jsonBuffer.createArray();
for (int i = 1; i <= 1000; i++) {
array.add("hello");
ASSERT_EQ(array.size(), i);
}
}

View File

@ -1,59 +0,0 @@
// Copyright Benoit Blanchon 2014-2017
// MIT License
//
// Arduino JSON library
// https://bblanchon.github.io/ArduinoJson/
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
class DynamicJsonBuffer_Basic_Tests : public testing::Test {
protected:
DynamicJsonBuffer buffer;
};
TEST_F(DynamicJsonBuffer_Basic_Tests, InitialSizeIsZero) {
ASSERT_EQ(0, buffer.size());
}
TEST_F(DynamicJsonBuffer_Basic_Tests, SizeIncreasesAfterAlloc) {
buffer.alloc(1);
ASSERT_LE(1U, buffer.size());
buffer.alloc(1);
ASSERT_LE(2U, buffer.size());
}
TEST_F(DynamicJsonBuffer_Basic_Tests, ReturnDifferentPointer) {
void* p1 = buffer.alloc(1);
void* p2 = buffer.alloc(2);
ASSERT_NE(p1, p2);
}
static bool isAligned(void* ptr) {
const size_t mask = sizeof(void*) - 1;
size_t addr = reinterpret_cast<size_t>(ptr);
return (addr & mask) == 0;
}
TEST_F(DynamicJsonBuffer_Basic_Tests, Alignment) {
// make room for tow but not three
buffer = DynamicJsonBuffer(2 * sizeof(void*) + 1);
ASSERT_TRUE(isAligned(buffer.alloc(1))); // this on is aligned by design
ASSERT_TRUE(isAligned(buffer.alloc(1))); // this one fits in the first block
ASSERT_TRUE(isAligned(buffer.alloc(1))); // this one requires a new block
}
TEST_F(DynamicJsonBuffer_Basic_Tests, strdup) {
char original[] = "hello";
char* copy = buffer.strdup(original);
strcpy(original, "world");
ASSERT_STREQ("hello", copy);
}
TEST_F(DynamicJsonBuffer_Basic_Tests, strdup_givenNull) {
const char* original = NULL;
char* copy = buffer.strdup(original);
ASSERT_EQ(NULL, copy);
}

View File

@ -0,0 +1,31 @@
// Copyright Benoit Blanchon 2014-2017
// MIT License
//
// Arduino JSON library
// https://bblanchon.github.io/ArduinoJson/
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <catch.hpp>
TEST_CASE("DynamicJsonBuffer::createArray()") {
DynamicJsonBuffer jsonBuffer;
JsonArray &array = jsonBuffer.createArray();
SECTION("GrowsWithArray") {
REQUIRE(JSON_ARRAY_SIZE(0) == jsonBuffer.size());
array.add("hello");
REQUIRE(JSON_ARRAY_SIZE(1) == jsonBuffer.size());
array.add("world");
REQUIRE(JSON_ARRAY_SIZE(2) == jsonBuffer.size());
}
SECTION("CanAdd1000Values") {
for (size_t i = 1; i <= 1000; i++) {
array.add("hello");
REQUIRE(array.size() == i);
}
}
}

View File

@ -6,20 +6,20 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
TEST(DynamicJsonBuffer_Object_Tests, GrowsWithObject) {
TEST_CASE("DynamicJsonBuffer::createObject()") {
DynamicJsonBuffer json;
JsonObject &obj = json.createObject();
ASSERT_EQ(JSON_OBJECT_SIZE(0), json.size());
REQUIRE(JSON_OBJECT_SIZE(0) == json.size());
obj["hello"] = 1;
ASSERT_EQ(JSON_OBJECT_SIZE(1), json.size());
REQUIRE(JSON_OBJECT_SIZE(1) == json.size());
obj["world"] = 2;
ASSERT_EQ(JSON_OBJECT_SIZE(2), json.size());
REQUIRE(JSON_OBJECT_SIZE(2) == json.size());
obj["world"] = 3; // <- same key, should not grow
ASSERT_EQ(JSON_OBJECT_SIZE(2), json.size());
REQUIRE(JSON_OBJECT_SIZE(2) == json.size());
}

View File

@ -1,52 +0,0 @@
// Copyright Benoit Blanchon 2014-2017
// MIT License
//
// Arduino JSON library
// https://bblanchon.github.io/ArduinoJson/
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
class NoMemoryAllocator {
public:
void* allocate(size_t) {
return NULL;
}
void deallocate(void*) {}
};
class DynamicJsonBuffer_NoMemory_Tests : public ::testing::Test {
protected:
DynamicJsonBufferBase<NoMemoryAllocator> _jsonBuffer;
};
TEST_F(DynamicJsonBuffer_NoMemory_Tests, FixCodeCoverage) {
// call this function to fix code coverage
NoMemoryAllocator().deallocate(NULL);
}
TEST_F(DynamicJsonBuffer_NoMemory_Tests, CreateArray) {
ASSERT_FALSE(_jsonBuffer.createArray().success());
}
TEST_F(DynamicJsonBuffer_NoMemory_Tests, CreateObject) {
ASSERT_FALSE(_jsonBuffer.createObject().success());
}
TEST_F(DynamicJsonBuffer_NoMemory_Tests, ParseArray) {
char json[] = "[]";
ASSERT_FALSE(_jsonBuffer.parseArray(json).success());
}
TEST_F(DynamicJsonBuffer_NoMemory_Tests, ParseObject) {
char json[] = "{}";
ASSERT_FALSE(_jsonBuffer.parseObject(json).success());
}
TEST_F(DynamicJsonBuffer_NoMemory_Tests, String) {
DynamicJsonBufferBase<NoMemoryAllocator>::String str =
_jsonBuffer.startString();
str.append('!');
ASSERT_EQ(NULL, str.c_str());
}

View File

@ -0,0 +1,50 @@
// Copyright Benoit Blanchon 2014-2017
// MIT License
//
// Arduino JSON library
// https://bblanchon.github.io/ArduinoJson/
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <catch.hpp>
struct NoMemoryAllocator {
void* allocate(size_t) {
return NULL;
}
void deallocate(void*) {}
};
TEST_CASE("DynamicJsonBuffer no memory") {
DynamicJsonBufferBase<NoMemoryAllocator> _jsonBuffer;
SECTION("FixCodeCoverage") {
// call this function to fix code coverage
NoMemoryAllocator().deallocate(NULL);
}
SECTION("createArray()") {
REQUIRE_FALSE(_jsonBuffer.createArray().success());
}
SECTION("createObject()") {
REQUIRE_FALSE(_jsonBuffer.createObject().success());
}
SECTION("parseArray()") {
char json[] = "[]";
REQUIRE_FALSE(_jsonBuffer.parseArray(json).success());
}
SECTION("parseObject()") {
char json[] = "{}";
REQUIRE_FALSE(_jsonBuffer.parseObject(json).success());
}
SECTION("startString()") {
DynamicJsonBufferBase<NoMemoryAllocator>::String str =
_jsonBuffer.startString();
str.append('!');
REQUIRE(0 == str.c_str());
}
}

View File

@ -0,0 +1,50 @@
// Copyright Benoit Blanchon 2014-2017
// MIT License
//
// Arduino JSON library
// https://bblanchon.github.io/ArduinoJson/
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <catch.hpp>
TEST_CASE("DynamicJsonBuffer::startString()") {
SECTION("WorksWhenBufferIsBigEnough") {
DynamicJsonBuffer jsonBuffer(6);
DynamicJsonBuffer::String str = jsonBuffer.startString();
str.append('h');
str.append('e');
str.append('l');
str.append('l');
str.append('o');
REQUIRE(std::string("hello") == str.c_str());
}
SECTION("GrowsWhenBufferIsTooSmall") {
DynamicJsonBuffer jsonBuffer(5);
DynamicJsonBuffer::String str = jsonBuffer.startString();
str.append('h');
str.append('e');
str.append('l');
str.append('l');
str.append('o');
REQUIRE(std::string("hello") == str.c_str());
}
SECTION("SizeIncreases") {
DynamicJsonBuffer jsonBuffer(5);
DynamicJsonBuffer::String str = jsonBuffer.startString();
REQUIRE(0 == jsonBuffer.size());
str.append('h');
REQUIRE(1 == jsonBuffer.size());
str.c_str();
REQUIRE(2 == jsonBuffer.size());
}
}

View File

@ -0,0 +1,26 @@
// Copyright Benoit Blanchon 2014-2017
// MIT License
//
// Arduino JSON library
// https://bblanchon.github.io/ArduinoJson/
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <catch.hpp>
TEST_CASE("DynamicJsonBuffer::strdup()") {
DynamicJsonBuffer buffer;
SECTION("Should return a copy") {
char original[] = "hello";
char* copy = buffer.strdup(original);
strcpy(original, "world");
REQUIRE(std::string("hello") == copy);
}
SECTION("Given NULL, return NULL") {
const char* original = NULL;
char* copy = buffer.strdup(original);
REQUIRE(0 == copy);
}
}

View File

@ -1,48 +0,0 @@
// Copyright Benoit Blanchon 2014-2017
// MIT License
//
// Arduino JSON library
// https://bblanchon.github.io/ArduinoJson/
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
TEST(DynamicJsonBuffer_String_Tests, WorksWhenBufferIsBigEnough) {
DynamicJsonBuffer jsonBuffer(6);
DynamicJsonBuffer::String str = jsonBuffer.startString();
str.append('h');
str.append('e');
str.append('l');
str.append('l');
str.append('o');
ASSERT_STREQ("hello", str.c_str());
}
TEST(DynamicJsonBuffer_String_Tests, GrowsWhenBufferIsTooSmall) {
DynamicJsonBuffer jsonBuffer(5);
DynamicJsonBuffer::String str = jsonBuffer.startString();
str.append('h');
str.append('e');
str.append('l');
str.append('l');
str.append('o');
ASSERT_STREQ("hello", str.c_str());
}
TEST(DynamicJsonBuffer_String_Tests, SizeIncreases) {
DynamicJsonBuffer jsonBuffer(5);
DynamicJsonBuffer::String str = jsonBuffer.startString();
ASSERT_EQ(0, jsonBuffer.size());
str.append('h');
ASSERT_EQ(1, jsonBuffer.size());
str.c_str();
ASSERT_EQ(2, jsonBuffer.size());
}

View File

@ -7,8 +7,8 @@
add_executable(IntegrationTests
gbathree.cpp
parse_print.cpp
round_trip.cpp
)
target_link_libraries(IntegrationTests gtest)
target_link_libraries(IntegrationTests catch)
add_test(IntegrationTests IntegrationTests)

View File

@ -6,210 +6,206 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
class GbathreeBug : public testing::Test {
public:
GbathreeBug() : _object(_buffer.parseObject(getJson())) {}
protected:
char _json[1024];
TEST_CASE("Gbathree") {
DynamicJsonBuffer _buffer;
const JsonObject& _object;
private:
char* getJson() {
strcpy(_json,
"{\"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]}");
return _json;
const JsonObject& _object = _buffer.parseObject(
"{\"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]}");
SECTION("Success") {
REQUIRE(_object.success());
}
};
TEST_F(GbathreeBug, Success) {
EXPECT_TRUE(_object.success());
}
SECTION("ProtocolName") {
REQUIRE("fluorescence" == _object["protocol_name"]);
}
TEST_F(GbathreeBug, ProtocolName) {
EXPECT_STREQ("fluorescence", _object["protocol_name"]);
}
SECTION("Repeats") {
REQUIRE(1 == _object["repeats"]);
}
TEST_F(GbathreeBug, Repeats) {
EXPECT_EQ(1, _object["repeats"]);
}
SECTION("Wait") {
REQUIRE(0 == _object["wait"]);
}
TEST_F(GbathreeBug, Wait) {
EXPECT_EQ(0, _object["wait"]);
}
SECTION("Measurements") {
REQUIRE(3 == _object["measurements"]);
}
TEST_F(GbathreeBug, Measurements) {
EXPECT_EQ(3, _object["measurements"]);
}
SECTION("Meas2_Light") {
REQUIRE(15 == _object["meas2_light"]);
}
TEST_F(GbathreeBug, Meas2_Light) {
EXPECT_EQ(15, _object["meas2_light"]);
}
SECTION("Meas1_Baseline") {
REQUIRE(0 == _object["meas1_baseline"]);
}
TEST_F(GbathreeBug, Meas1_Baseline) {
EXPECT_EQ(0, _object["meas1_baseline"]);
}
SECTION("Act_Light") {
REQUIRE(20 == _object["act_light"]);
}
TEST_F(GbathreeBug, Act_Light) {
EXPECT_EQ(20, _object["act_light"]);
}
SECTION("Pulsesize") {
REQUIRE(25 == _object["pulsesize"]);
}
TEST_F(GbathreeBug, Pulsesize) {
EXPECT_EQ(25, _object["pulsesize"]);
}
SECTION("Pulsedistance") {
REQUIRE(10000 == _object["pulsedistance"]);
}
TEST_F(GbathreeBug, Pulsedistance) {
EXPECT_EQ(10000, _object["pulsedistance"]);
}
SECTION("Actintensity1") {
REQUIRE(50 == _object["actintensity1"]);
}
TEST_F(GbathreeBug, Actintensity1) {
EXPECT_EQ(50, _object["actintensity1"]);
}
SECTION("Actintensity2") {
REQUIRE(255 == _object["actintensity2"]);
}
TEST_F(GbathreeBug, Actintensity2) {
EXPECT_EQ(255, _object["actintensity2"]);
}
SECTION("Measintensity") {
REQUIRE(255 == _object["measintensity"]);
}
TEST_F(GbathreeBug, Measintensity) {
EXPECT_EQ(255, _object["measintensity"]);
}
SECTION("Calintensity") {
REQUIRE(255 == _object["calintensity"]);
}
TEST_F(GbathreeBug, Calintensity) {
EXPECT_EQ(255, _object["calintensity"]);
}
SECTION("Pulses") {
// "pulses":[50,50,50]
TEST_F(GbathreeBug, Pulses) {
// "pulses":[50,50,50]
JsonArray& array = _object["pulses"];
REQUIRE(array.success());
JsonArray& array = _object["pulses"];
EXPECT_TRUE(array.success());
REQUIRE(3 == array.size());
EXPECT_EQ(3, array.size());
for (int i = 0; i < 3; i++) {
REQUIRE(50 == array[i]);
}
}
for (int i = 0; i < 3; i++) {
EXPECT_EQ(50, array[i]);
}
}
TEST_F(GbathreeBug, Act) {
// "act":[2,1,2,2]
JsonArray& array = _object["act"];
EXPECT_TRUE(array.success());
EXPECT_EQ(4, array.size());
EXPECT_EQ(2, array[0]);
EXPECT_EQ(1, array[1]);
EXPECT_EQ(2, array[2]);
EXPECT_EQ(2, array[3]);
}
TEST_F(GbathreeBug, Detectors) {
// "detectors":[[34,34,34,34],[34,34,34,34],[34,34,34,34],[34,34,34,34]]
JsonArray& array = _object["detectors"];
EXPECT_TRUE(array.success());
EXPECT_EQ(4, array.size());
for (int i = 0; i < 4; i++) {
JsonArray& nestedArray = array[i];
EXPECT_EQ(4, nestedArray.size());
for (int j = 0; j < 4; j++) EXPECT_EQ(34, nestedArray[j]);
}
}
TEST_F(GbathreeBug, Alta) {
// alta:[2,2,2,2]
JsonArray& array = _object["alta"];
EXPECT_TRUE(array.success());
EXPECT_EQ(4, array.size());
for (int i = 0; i < 4; i++) {
EXPECT_EQ(2, array[i]);
}
}
TEST_F(GbathreeBug, Altb) {
// altb:[2,2,2,2]
JsonArray& array = _object["altb"];
EXPECT_TRUE(array.success());
EXPECT_EQ(4, array.size());
for (int i = 0; i < 4; i++) {
EXPECT_EQ(2, array[i]);
}
}
TEST_F(GbathreeBug, Measlights) {
// "measlights":[[15,15,15,15],[15,15,15,15],[15,15,15,15],[15,15,15,15]]
JsonArray& array = _object["measlights"];
EXPECT_TRUE(array.success());
EXPECT_EQ(4, array.size());
for (int i = 0; i < 4; i++) {
JsonArray& nestedArray = array[i];
EXPECT_EQ(4, nestedArray.size());
for (int j = 0; j < 4; j++) EXPECT_EQ(15, nestedArray[j]);
}
}
TEST_F(GbathreeBug, Measlights2) {
// "measlights2":[[15,15,15,15],[15,15,15,15],[15,15,15,15],[15,15,15,15]]
JsonArray& array = _object["measlights2"];
EXPECT_TRUE(array.success());
EXPECT_EQ(4, array.size());
for (int i = 0; i < 4; i++) {
JsonArray& nestedArray = array[i];
EXPECT_EQ(4, nestedArray.size());
for (int j = 0; j < 4; j++) EXPECT_EQ(15, nestedArray[j]);
}
}
TEST_F(GbathreeBug, Altc) {
// altc:[2,2,2,2]
JsonArray& array = _object["altc"];
EXPECT_TRUE(array.success());
EXPECT_EQ(4, array.size());
for (int i = 0; i < 4; i++) {
EXPECT_EQ(2, array[i]);
}
}
TEST_F(GbathreeBug, Altd) {
// altd:[2,2,2,2]
JsonArray& array = _object["altd"];
EXPECT_TRUE(array.success());
EXPECT_EQ(4, array.size());
for (int i = 0; i < 4; i++) {
EXPECT_EQ(2, array[i]);
SECTION("Act") {
// "act":[2,1,2,2]
JsonArray& array = _object["act"];
REQUIRE(array.success());
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 = _object["detectors"];
REQUIRE(array.success());
REQUIRE(4 == array.size());
for (int i = 0; i < 4; i++) {
JsonArray& nestedArray = array[i];
REQUIRE(4 == nestedArray.size());
for (int j = 0; j < 4; j++) {
REQUIRE(34 == nestedArray[j]);
}
}
}
SECTION("Alta") {
// alta:[2,2,2,2]
JsonArray& array = _object["alta"];
REQUIRE(array.success());
REQUIRE(4 == array.size());
for (int i = 0; i < 4; i++) {
REQUIRE(2 == array[i]);
}
}
SECTION("Altb") {
// altb:[2,2,2,2]
JsonArray& array = _object["altb"];
REQUIRE(array.success());
REQUIRE(4 == array.size());
for (int 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 = _object["measlights"];
REQUIRE(array.success());
REQUIRE(4 == array.size());
for (int i = 0; i < 4; i++) {
JsonArray& nestedArray = array[i];
REQUIRE(4 == nestedArray.size());
for (int 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 = _object["measlights2"];
REQUIRE(array.success());
REQUIRE(4 == array.size());
for (int i = 0; i < 4; i++) {
JsonArray& nestedArray = array[i];
REQUIRE(4 == nestedArray.size());
for (int j = 0; j < 4; j++) {
REQUIRE(15 == nestedArray[j]);
}
}
}
SECTION("Altc") {
// altc:[2,2,2,2]
JsonArray& array = _object["altc"];
REQUIRE(array.success());
REQUIRE(4 == array.size());
for (int i = 0; i < 4; i++) {
REQUIRE(2 == array[i]);
}
}
SECTION("Altd") {
// altd:[2,2,2,2]
JsonArray& array = _object["altd"];
REQUIRE(array.success());
REQUIRE(4 == array.size());
for (int i = 0; i < 4; i++) {
REQUIRE(2 == array[i]);
}
}
}

View File

@ -6,47 +6,23 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
class IntegrationTests : public testing::TestWithParam<const char*> {
static const size_t MAX_JSON_SIZE = 10000;
void check(std::string originalJson) {
DynamicJsonBuffer jb;
protected:
virtual void SetUp() {
_input = GetParam();
strcpy(_inputBuffer, _input);
}
std::string prettyJson;
jb.parseObject(originalJson).prettyPrintTo(prettyJson);
void parseThenPrint(char* input, char* output) {
DynamicJsonBuffer buffer;
buffer.parseObject(input).printTo(output, MAX_JSON_SIZE);
}
std::string finalJson;
jb.parseObject(prettyJson).printTo(finalJson);
void parseThenPrettyPrint(char* input, char* output) {
DynamicJsonBuffer buffer;
buffer.parseObject(input).prettyPrintTo(output, MAX_JSON_SIZE);
}
const char* _input;
char _inputBuffer[MAX_JSON_SIZE];
char _outputBuffer[MAX_JSON_SIZE];
char _intermediateBuffer[MAX_JSON_SIZE];
};
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 +30,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 +78,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\"}]}}}");
}
}

View File

@ -19,5 +19,5 @@ add_executable(JsonArrayTests
subscript.cpp
)
target_link_libraries(JsonArrayTests gtest)
target_link_libraries(JsonArrayTests catch)
add_test(JsonArray JsonArrayTests)

View File

@ -6,85 +6,83 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
class JsonArray_Add_Tests : public ::testing::Test {
protected:
JsonArray_Add_Tests() : _array(_jsonBuffer.createArray()) {}
#include <catch.hpp>
TEST_CASE("JsonArray::add()") {
DynamicJsonBuffer _jsonBuffer;
JsonArray& _array;
};
JsonArray& _array = _jsonBuffer.createArray();
#define TEST_(name) TEST_F(JsonArray_Add_Tests, name)
SECTION("SizeIncreased_WhenValuesAreAdded") {
_array.add("hello");
REQUIRE(1U == _array.size());
}
TEST_(SizeIncreased_WhenValuesAreAdded) {
_array.add("hello");
EXPECT_EQ(1U, _array.size());
}
TEST_(StoreInteger) {
_array.add(123);
EXPECT_EQ(123, _array[0].as<int>());
EXPECT_TRUE(_array[0].is<int>());
EXPECT_FALSE(_array[0].is<double>());
}
TEST_(StoreDouble) {
_array.add(123.45);
EXPECT_EQ(123.45, _array[0].as<double>());
EXPECT_TRUE(_array[0].is<double>());
EXPECT_FALSE(_array[0].is<int>());
}
TEST_(StoreBoolean) {
_array.add(true);
EXPECT_EQ(true, _array[0].as<bool>());
EXPECT_TRUE(_array[0].is<bool>());
EXPECT_FALSE(_array[0].is<int>());
}
TEST_(StoreString) {
_array.add("hello");
EXPECT_STREQ("hello", _array[0].as<const char*>());
EXPECT_TRUE(_array[0].is<const char*>());
EXPECT_FALSE(_array[0].is<int>());
}
TEST_(StoreNestedArray) {
JsonArray& arr = _jsonBuffer.createArray();
_array.add(arr);
EXPECT_EQ(&arr, &_array[0].as<JsonArray&>());
EXPECT_TRUE(_array[0].is<JsonArray&>());
EXPECT_FALSE(_array[0].is<int>());
}
TEST_(StoreNestedObject) {
JsonObject& obj = _jsonBuffer.createObject();
_array.add(obj);
EXPECT_EQ(&obj, &_array[0].as<JsonObject&>());
EXPECT_TRUE(_array[0].is<JsonObject&>());
EXPECT_FALSE(_array[0].is<int>());
}
TEST_(StoreArraySubscript) {
JsonArray& arr = _jsonBuffer.createArray();
arr.add("hello");
_array.add(arr[0]);
EXPECT_STREQ("hello", _array[0]);
}
TEST_(StoreObjectSubscript) {
JsonObject& obj = _jsonBuffer.createObject();
obj["x"] = "hello";
_array.add(obj["x"]);
EXPECT_STREQ("hello", _array[0]);
SECTION("StoreInteger") {
_array.add(123);
REQUIRE(123 == _array[0].as<int>());
REQUIRE(_array[0].is<int>());
REQUIRE_FALSE(_array[0].is<double>());
}
SECTION("StoreDouble") {
_array.add(123.45);
REQUIRE(123.45 == _array[0].as<double>());
REQUIRE(_array[0].is<double>());
REQUIRE_FALSE(_array[0].is<int>());
}
SECTION("StoreBoolean") {
_array.add(true);
REQUIRE(true == _array[0].as<bool>());
REQUIRE(_array[0].is<bool>());
REQUIRE_FALSE(_array[0].is<int>());
}
SECTION("StoreString") {
const char* str = "hello";
_array.add(str);
REQUIRE(str == _array[0].as<const char*>());
REQUIRE(_array[0].is<const char*>());
REQUIRE_FALSE(_array[0].is<int>());
}
SECTION("StoreNestedArray") {
JsonArray& arr = _jsonBuffer.createArray();
_array.add(arr);
REQUIRE(&arr == &_array[0].as<JsonArray&>());
REQUIRE(_array[0].is<JsonArray&>());
REQUIRE_FALSE(_array[0].is<int>());
}
SECTION("StoreNestedObject") {
JsonObject& obj = _jsonBuffer.createObject();
_array.add(obj);
REQUIRE(&obj == &_array[0].as<JsonObject&>());
REQUIRE(_array[0].is<JsonObject&>());
REQUIRE_FALSE(_array[0].is<int>());
}
SECTION("StoreArraySubscript") {
const char* str = "hello";
JsonArray& arr = _jsonBuffer.createArray();
arr.add(str);
_array.add(arr[0]);
REQUIRE(str == _array[0]);
}
SECTION("StoreObjectSubscript") {
const char* str = "hello";
JsonObject& obj = _jsonBuffer.createObject();
obj["x"] = str;
_array.add(obj["x"]);
REQUIRE(str == _array[0]);
}
}

View File

@ -6,36 +6,27 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
#define TEST_(name) TEST(JsonArray_Basic_Tests, name)
TEST_CASE("JsonArray basics") {
DynamicJsonBuffer jb;
JsonArray& array = jb.createArray();
TEST_(SuccessIsTrue) {
DynamicJsonBuffer _jsonBuffer;
JsonArray& array = _jsonBuffer.createArray();
SECTION("SuccessIsTrue") {
REQUIRE(array.success());
}
EXPECT_TRUE(array.success());
}
TEST_(InitialSizeIsZero) {
DynamicJsonBuffer _jsonBuffer;
JsonArray& array = _jsonBuffer.createArray();
EXPECT_EQ(0U, array.size());
}
TEST_(CreateNestedArray) {
DynamicJsonBuffer _jsonBuffer;
JsonArray& array = _jsonBuffer.createArray();
JsonArray& arr = array.createNestedArray();
EXPECT_EQ(&arr, &array[0].as<JsonArray&>());
}
TEST_(CreateNestedObject) {
DynamicJsonBuffer _jsonBuffer;
JsonArray& array = _jsonBuffer.createArray();
JsonObject& obj = array.createNestedObject();
EXPECT_EQ(&obj, &array[0].as<JsonObject&>());
SECTION("InitialSizeIsZero") {
REQUIRE(0U == array.size());
}
SECTION("CreateNestedArray") {
JsonArray& arr = array.createNestedArray();
REQUIRE(&arr == &array[0].as<JsonArray&>());
}
SECTION("CreateNestedObject") {
JsonObject& obj = array.createNestedObject();
REQUIRE(&obj == &array[0].as<JsonObject&>());
}
}

View File

@ -6,59 +6,61 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
TEST(JsonArray_CopyFrom_Tests, OneDimension) {
DynamicJsonBuffer jsonBuffer;
JsonArray& array = jsonBuffer.createArray();
char json[32];
int source[] = {1, 2, 3};
TEST_CASE("JsonArray::copyFrom()") {
SECTION("OneDimension") {
DynamicJsonBuffer jsonBuffer;
JsonArray& array = jsonBuffer.createArray();
char json[32];
int source[] = {1, 2, 3};
bool ok = array.copyFrom(source);
ASSERT_TRUE(ok);
bool ok = array.copyFrom(source);
REQUIRE(ok);
array.printTo(json, sizeof(json));
ASSERT_STREQ("[1,2,3]", json);
}
TEST(JsonArray_CopyFrom_Tests, OneDimension_JsonBufferTooSmall) {
const size_t SIZE = JSON_ARRAY_SIZE(2);
StaticJsonBuffer<SIZE> jsonBuffer;
JsonArray& array = jsonBuffer.createArray();
char json[32];
int source[] = {1, 2, 3};
bool ok = array.copyFrom(source);
ASSERT_FALSE(ok);
array.printTo(json, sizeof(json));
ASSERT_STREQ("[1,2]", json);
}
TEST(JsonArray_CopyFrom_Tests, TwoDimensions) {
DynamicJsonBuffer jsonBuffer;
JsonArray& array = jsonBuffer.createArray();
char json[32];
int source[][3] = {{1, 2, 3}, {4, 5, 6}};
bool ok = array.copyFrom(source);
ASSERT_TRUE(ok);
array.printTo(json, sizeof(json));
ASSERT_STREQ("[[1,2,3],[4,5,6]]", json);
}
TEST(JsonArray_CopyFrom_Tests, TwoDimensions_JsonBufferTooSmall) {
const size_t SIZE =
JSON_ARRAY_SIZE(2) + JSON_ARRAY_SIZE(3) + JSON_ARRAY_SIZE(2);
StaticJsonBuffer<SIZE> jsonBuffer;
JsonArray& array = jsonBuffer.createArray();
char json[32];
int source[][3] = {{1, 2, 3}, {4, 5, 6}};
bool ok = array.copyFrom(source);
ASSERT_FALSE(ok);
array.printTo(json, sizeof(json));
ASSERT_STREQ("[[1,2,3],[4,5]]", json);
array.printTo(json, sizeof(json));
REQUIRE(std::string("[1,2,3]") == json);
}
SECTION("OneDimension_JsonBufferTooSmall") {
const size_t SIZE = JSON_ARRAY_SIZE(2);
StaticJsonBuffer<SIZE> jsonBuffer;
JsonArray& array = jsonBuffer.createArray();
char json[32];
int source[] = {1, 2, 3};
bool ok = array.copyFrom(source);
REQUIRE_FALSE(ok);
array.printTo(json, sizeof(json));
REQUIRE(std::string("[1,2]") == json);
}
SECTION("TwoDimensions") {
DynamicJsonBuffer jsonBuffer;
JsonArray& array = jsonBuffer.createArray();
char json[32];
int source[][3] = {{1, 2, 3}, {4, 5, 6}};
bool ok = array.copyFrom(source);
REQUIRE(ok);
array.printTo(json, sizeof(json));
REQUIRE(std::string("[[1,2,3],[4,5,6]]") == json);
}
SECTION("TwoDimensions_JsonBufferTooSmall") {
const size_t SIZE =
JSON_ARRAY_SIZE(2) + JSON_ARRAY_SIZE(3) + JSON_ARRAY_SIZE(2);
StaticJsonBuffer<SIZE> jsonBuffer;
JsonArray& array = jsonBuffer.createArray();
char json[32];
int source[][3] = {{1, 2, 3}, {4, 5, 6}};
bool ok = array.copyFrom(source);
REQUIRE_FALSE(ok);
array.printTo(json, sizeof(json));
REQUIRE(std::string("[[1,2,3],[4,5]]") == json);
}
}

View File

@ -6,51 +6,50 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
TEST(JsonArray_CopyTo_Tests, BiggerOneDimensionIntegerArray) {
char json[] = "[1,2,3]";
#include <catch.hpp>
TEST_CASE("JsonArray::copyTo()") {
DynamicJsonBuffer jsonBuffer;
JsonArray& array = jsonBuffer.parseArray(json);
int destination[4] = {0};
size_t result = array.copyTo(destination);
SECTION("BiggerOneDimensionIntegerArray") {
char json[] = "[1,2,3]";
JsonArray& array = jsonBuffer.parseArray(json);
ASSERT_EQ(3, result);
ASSERT_EQ(1, destination[0]);
ASSERT_EQ(2, destination[1]);
ASSERT_EQ(3, destination[2]);
ASSERT_EQ(0, destination[3]);
}
TEST(JsonArray_CopyTo_Tests, SmallerOneDimensionIntegerArray) {
char json[] = "[1,2,3]";
DynamicJsonBuffer jsonBuffer;
JsonArray& array = jsonBuffer.parseArray(json);
int destination[2] = {0};
size_t result = array.copyTo(destination);
ASSERT_EQ(2, result);
ASSERT_EQ(1, destination[0]);
ASSERT_EQ(2, destination[1]);
}
TEST(JsonArray_CopyTo_Tests, TwoOneDimensionIntegerArray) {
char json[] = "[[1,2],[3],[4]]";
DynamicJsonBuffer jsonBuffer;
JsonArray& array = jsonBuffer.parseArray(json);
int destination[3][2] = {{0}};
array.copyTo(destination);
ASSERT_EQ(1, destination[0][0]);
ASSERT_EQ(2, destination[0][1]);
ASSERT_EQ(3, destination[1][0]);
ASSERT_EQ(0, destination[1][1]);
ASSERT_EQ(4, destination[2][0]);
ASSERT_EQ(0, destination[2][1]);
int destination[4] = {0};
size_t result = array.copyTo(destination);
REQUIRE(3 == result);
REQUIRE(1 == destination[0]);
REQUIRE(2 == destination[1]);
REQUIRE(3 == destination[2]);
REQUIRE(0 == destination[3]);
}
SECTION("SmallerOneDimensionIntegerArray") {
char json[] = "[1,2,3]";
JsonArray& array = jsonBuffer.parseArray(json);
int destination[2] = {0};
size_t result = array.copyTo(destination);
REQUIRE(2 == result);
REQUIRE(1 == destination[0]);
REQUIRE(2 == destination[1]);
}
SECTION("TwoOneDimensionIntegerArray") {
char json[] = "[[1,2],[3],[4]]";
JsonArray& array = jsonBuffer.parseArray(json);
int destination[3][2] = {{0}};
array.copyTo(destination);
REQUIRE(1 == destination[0][0]);
REQUIRE(2 == destination[0][1]);
REQUIRE(3 == destination[1][0]);
REQUIRE(0 == destination[1][1]);
REQUIRE(4 == destination[2][0]);
REQUIRE(0 == destination[2][1]);
}
}

View File

@ -6,28 +6,32 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
TEST(JsonArray_Invalid_Tests, SubscriptFails) {
ASSERT_FALSE(JsonArray::invalid()[0].success());
}
using namespace Catch::Matchers;
TEST(JsonArray_Invalid_Tests, AddFails) {
JsonArray& array = JsonArray::invalid();
array.add(1);
ASSERT_EQ(0, array.size());
}
TEST_CASE("JsonArray::invalid()") {
SECTION("SubscriptFails") {
REQUIRE_FALSE(JsonArray::invalid()[0].success());
}
TEST(JsonArray_Invalid_Tests, CreateNestedArrayFails) {
ASSERT_FALSE(JsonArray::invalid().createNestedArray().success());
}
SECTION("AddFails") {
JsonArray& array = JsonArray::invalid();
array.add(1);
REQUIRE(0 == array.size());
}
TEST(JsonArray_Invalid_Tests, CreateNestedObjectFails) {
ASSERT_FALSE(JsonArray::invalid().createNestedObject().success());
}
SECTION("CreateNestedArrayFails") {
REQUIRE_FALSE(JsonArray::invalid().createNestedArray().success());
}
TEST(JsonArray_Invalid_Tests, PrintToWritesBrackets) {
char buffer[32];
JsonArray::invalid().printTo(buffer, sizeof(buffer));
ASSERT_STREQ("[]", buffer);
SECTION("CreateNestedObjectFails") {
REQUIRE_FALSE(JsonArray::invalid().createNestedObject().success());
}
SECTION("PrintToWritesBrackets") {
char buffer[32];
JsonArray::invalid().printTo(buffer, sizeof(buffer));
REQUIRE_THAT(buffer, Equals("[]"));
}
}

View File

@ -6,7 +6,7 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
template <typename TIterator>
static void run_iterator_test() {
@ -19,21 +19,23 @@ static void run_iterator_test() {
TIterator it = array.begin();
TIterator end = array.end();
EXPECT_NE(end, it);
EXPECT_EQ(12, it->template as<int>());
EXPECT_EQ(12, static_cast<int>(*it));
REQUIRE(end != it);
REQUIRE(12 == it->template as<int>());
REQUIRE(12 == static_cast<int>(*it));
++it;
EXPECT_NE(end, it);
EXPECT_EQ(34, it->template as<int>());
EXPECT_EQ(34, static_cast<int>(*it));
REQUIRE(end != it);
REQUIRE(34 == it->template as<int>());
REQUIRE(34 == static_cast<int>(*it));
++it;
EXPECT_EQ(end, it);
REQUIRE(end == it);
}
TEST(JsonArray_Iterator_Test, RunItertorToEnd) {
run_iterator_test<JsonArray::iterator>();
}
TEST_CASE("JsonArray::begin()/end()") {
SECTION("Mutable") {
run_iterator_test<JsonArray::iterator>();
}
TEST(JsonArray_Iterator_Test, RunConstItertorToEnd) {
run_iterator_test<JsonArray::const_iterator>();
SECTION("Const") {
run_iterator_test<JsonArray::const_iterator>();
}
}

View File

@ -6,79 +6,73 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
class JsonArray_PrettyPrintTo_Tests : public testing::Test {
public:
JsonArray_PrettyPrintTo_Tests() : array(jsonBuffer.createArray()) {}
static void check(JsonArray& array, std::string expected) {
std::string actual;
size_t actualLen = array.prettyPrintTo(actual);
size_t measuredLen = array.measurePrettyLength();
CHECK(actualLen == expected.size());
CHECK(measuredLen == expected.size());
REQUIRE(expected == actual);
}
protected:
DynamicJsonBuffer jsonBuffer;
JsonArray& array;
TEST_CASE("JsonArray::prettyPrintTo()") {
DynamicJsonBuffer jb;
JsonArray& array = jb.createArray();
void outputMustBe(const char* expected) {
char actual[256];
size_t actualLen = array.prettyPrintTo(actual);
size_t measuredLen = array.measurePrettyLength();
EXPECT_STREQ(expected, actual);
EXPECT_EQ(strlen(expected), actualLen);
EXPECT_EQ(strlen(expected), measuredLen);
SECTION("Empty") {
check(array, "[]");
}
};
TEST_F(JsonArray_PrettyPrintTo_Tests, Empty) {
outputMustBe("[]");
}
TEST_F(JsonArray_PrettyPrintTo_Tests, OneElement) {
array.add(1);
outputMustBe(
"[\r\n"
" 1\r\n"
"]");
}
TEST_F(JsonArray_PrettyPrintTo_Tests, TwoElements) {
array.add(1);
array.add(2);
outputMustBe(
"[\r\n"
" 1,\r\n"
" 2\r\n"
"]");
}
TEST_F(JsonArray_PrettyPrintTo_Tests, EmptyNestedArrays) {
array.createNestedArray();
array.createNestedArray();
outputMustBe(
"[\r\n"
" [],\r\n"
" []\r\n"
"]");
}
TEST_F(JsonArray_PrettyPrintTo_Tests, NestedArrays) {
JsonArray& nested1 = array.createNestedArray();
nested1.add(1);
nested1.add(2);
JsonObject& nested2 = array.createNestedObject();
nested2["key"] = 3;
outputMustBe(
"[\r\n"
" [\r\n"
" 1,\r\n"
" 2\r\n"
" ],\r\n"
" {\r\n"
" \"key\": 3\r\n"
" }\r\n"
"]");
SECTION("OneElement") {
array.add(1);
check(array,
"[\r\n"
" 1\r\n"
"]");
}
SECTION("TwoElements") {
array.add(1);
array.add(2);
check(array,
"[\r\n"
" 1,\r\n"
" 2\r\n"
"]");
}
SECTION("EmptyNestedArrays") {
array.createNestedArray();
array.createNestedArray();
check(array,
"[\r\n"
" [],\r\n"
" []\r\n"
"]");
}
SECTION("NestedArrays") {
JsonArray& nested1 = array.createNestedArray();
nested1.add(1);
nested1.add(2);
JsonObject& nested2 = array.createNestedObject();
nested2["key"] = 3;
check(array,
"[\r\n"
" [\r\n"
" 1,\r\n"
" 2\r\n"
" ],\r\n"
" {\r\n"
" \"key\": 3\r\n"
" }\r\n"
"]");
}
}

View File

@ -6,147 +6,140 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
class JsonArray_PrintTo_Tests : public testing::Test {
public:
JsonArray_PrintTo_Tests() : array(json.createArray()) {}
static void check(JsonArray &array, std::string expected) {
std::string actual;
size_t actualLen = array.printTo(actual);
size_t measuredLen = array.measureLength();
CHECK(actualLen == expected.size());
CHECK(measuredLen == expected.size());
REQUIRE(expected == actual);
}
protected:
StaticJsonBuffer<JSON_ARRAY_SIZE(2)> json;
JsonArray &array;
TEST_CASE("JsonArray::printTo()") {
StaticJsonBuffer<JSON_ARRAY_SIZE(2)> jb;
JsonArray &array = jb.createArray();
void outputMustBe(const char *expected) {
size_t actualLen = array.printTo(buffer);
size_t measuredLen = array.measureLength();
EXPECT_STREQ(expected, buffer);
EXPECT_EQ(strlen(expected), actualLen);
EXPECT_EQ(strlen(expected), measuredLen);
SECTION("Empty") {
check(array, "[]");
}
private:
char buffer[256];
};
SECTION("Null") {
array.add(static_cast<char *>(0));
TEST_F(JsonArray_PrintTo_Tests, Empty) {
outputMustBe("[]");
}
TEST_F(JsonArray_PrintTo_Tests, Null) {
array.add(static_cast<char *>(0));
outputMustBe("[null]");
}
TEST_F(JsonArray_PrintTo_Tests, OneString) {
array.add("hello");
outputMustBe("[\"hello\"]");
}
TEST_F(JsonArray_PrintTo_Tests, TwoStrings) {
array.add("hello");
array.add("world");
outputMustBe("[\"hello\",\"world\"]");
}
TEST_F(JsonArray_PrintTo_Tests, OneStringOverCapacity) {
array.add("hello");
array.add("world");
array.add("lost");
outputMustBe("[\"hello\",\"world\"]");
}
TEST_F(JsonArray_PrintTo_Tests, OneDoubleDefaultDigits) {
array.add(3.14159265358979323846);
outputMustBe("[3.14]");
}
TEST_F(JsonArray_PrintTo_Tests, OneDoubleFourDigits) {
array.add(3.14159265358979323846, 4);
outputMustBe("[3.1416]");
}
TEST_F(JsonArray_PrintTo_Tests, OneDoubleFourDigits_AlternativeSyntax) {
array.add(double_with_n_digits(3.14159265358979323846, 4));
outputMustBe("[3.1416]");
}
TEST_F(JsonArray_PrintTo_Tests, OneFloatDefaultDigits) {
array.add(3.14159f);
outputMustBe("[3.14]");
}
TEST_F(JsonArray_PrintTo_Tests, OneFloatFourDigits) {
array.add(3.14159f, 4);
outputMustBe("[3.1416]");
}
TEST_F(JsonArray_PrintTo_Tests, OneInteger) {
array.add(1);
outputMustBe("[1]");
}
TEST_F(JsonArray_PrintTo_Tests, TwoIntegers) {
array.add(1);
array.add(2);
outputMustBe("[1,2]");
}
TEST_F(JsonArray_PrintTo_Tests, RawJson) {
array.add(RawJson("{\"key\":\"value\"}"));
outputMustBe("[{\"key\":\"value\"}]");
}
TEST_F(JsonArray_PrintTo_Tests, OneIntegerOverCapacity) {
array.add(1);
array.add(2);
array.add(3);
outputMustBe("[1,2]");
}
TEST_F(JsonArray_PrintTo_Tests, OneTrue) {
array.add(true);
outputMustBe("[true]");
}
TEST_F(JsonArray_PrintTo_Tests, OneFalse) {
array.add(false);
outputMustBe("[false]");
}
TEST_F(JsonArray_PrintTo_Tests, TwoBooleans) {
array.add(false);
array.add(true);
outputMustBe("[false,true]");
}
TEST_F(JsonArray_PrintTo_Tests, OneBooleanOverCapacity) {
array.add(false);
array.add(true);
array.add(false);
outputMustBe("[false,true]");
}
TEST_F(JsonArray_PrintTo_Tests, OneEmptyNestedArray) {
array.createNestedArray();
outputMustBe("[[]]");
}
TEST_F(JsonArray_PrintTo_Tests, OneEmptyNestedHash) {
array.createNestedObject();
outputMustBe("[{}]");
check(array, "[null]");
}
SECTION("OneString") {
array.add("hello");
check(array, "[\"hello\"]");
}
SECTION("TwoStrings") {
array.add("hello");
array.add("world");
check(array, "[\"hello\",\"world\"]");
}
SECTION("OneStringOverCapacity") {
array.add("hello");
array.add("world");
array.add("lost");
check(array, "[\"hello\",\"world\"]");
}
SECTION("OneDoubleDefaultDigits") {
array.add(3.14159265358979323846);
check(array, "[3.14]");
}
SECTION("OneDoubleFourDigits") {
array.add(3.14159265358979323846, 4);
check(array, "[3.1416]");
}
SECTION("OneDoubleFourDigits_AlternativeSyntax") {
array.add(double_with_n_digits(3.14159265358979323846, 4));
check(array, "[3.1416]");
}
SECTION("OneFloatDefaultDigits") {
array.add(3.14159f);
check(array, "[3.14]");
}
SECTION("OneFloatFourDigits") {
array.add(3.14159f, 4);
check(array, "[3.1416]");
}
SECTION("OneInteger") {
array.add(1);
check(array, "[1]");
}
SECTION("TwoIntegers") {
array.add(1);
array.add(2);
check(array, "[1,2]");
}
SECTION("RawJson") {
array.add(RawJson("{\"key\":\"value\"}"));
check(array, "[{\"key\":\"value\"}]");
}
SECTION("OneIntegerOverCapacity") {
array.add(1);
array.add(2);
array.add(3);
check(array, "[1,2]");
}
SECTION("OneTrue") {
array.add(true);
check(array, "[true]");
}
SECTION("OneFalse") {
array.add(false);
check(array, "[false]");
}
SECTION("TwoBooleans") {
array.add(false);
array.add(true);
check(array, "[false,true]");
}
SECTION("OneBooleanOverCapacity") {
array.add(false);
array.add(true);
array.add(false);
check(array, "[false,true]");
}
SECTION("OneEmptyNestedArray") {
array.createNestedArray();
check(array, "[[]]");
}
SECTION("OneEmptyNestedHash") {
array.createNestedObject();
check(array, "[{}]");
}
}

View File

@ -6,72 +6,66 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
class JsonArray_Remove_Tests : public ::testing::Test {
protected:
JsonArray_Remove_Tests() : _array(_jsonBuffer.createArray()) {
_array.add("one");
_array.add("two");
_array.add("three");
TEST_CASE("JsonArray::remove()") {
DynamicJsonBuffer _jsonBuffer;
JsonArray& _array = _jsonBuffer.createArray();
_array.add(1);
_array.add(2);
_array.add(3);
SECTION("RemoveFirstByIndex") {
_array.remove(0);
REQUIRE(2 == _array.size());
REQUIRE(_array[0] == 2);
REQUIRE(_array[1] == 3);
}
DynamicJsonBuffer _jsonBuffer;
JsonArray& _array;
};
SECTION("RemoveMiddleByIndex") {
_array.remove(1);
#define TEST_(name) TEST_F(JsonArray_Remove_Tests, name)
REQUIRE(2 == _array.size());
REQUIRE(_array[0] == 1);
REQUIRE(_array[1] == 3);
}
TEST_(RemoveFirstByIndex) {
_array.remove(0);
SECTION("RemoveLastByIndex") {
_array.remove(2);
EXPECT_EQ(2, _array.size());
EXPECT_STREQ("two", _array[0]);
EXPECT_STREQ("three", _array[1]);
}
TEST_(RemoveMiddleByIndex) {
_array.remove(1);
EXPECT_EQ(2, _array.size());
EXPECT_STREQ("one", _array[0]);
EXPECT_STREQ("three", _array[1]);
}
TEST_(RemoveLastByIndex) {
_array.remove(2);
EXPECT_EQ(2, _array.size());
EXPECT_STREQ("one", _array[0]);
EXPECT_STREQ("two", _array[1]);
}
TEST_(RemoveFirstByIterator) {
JsonArray::iterator it = _array.begin();
_array.remove(it);
EXPECT_EQ(2, _array.size());
EXPECT_STREQ("two", _array[0]);
EXPECT_STREQ("three", _array[1]);
}
TEST_(RemoveMiddleByIterator) {
JsonArray::iterator it = _array.begin();
++it;
_array.remove(it);
EXPECT_EQ(2, _array.size());
EXPECT_STREQ("one", _array[0]);
EXPECT_STREQ("three", _array[1]);
}
TEST_(RemoveLastByIterator) {
JsonArray::iterator it = _array.begin();
++it;
++it;
_array.remove(it);
EXPECT_EQ(2, _array.size());
EXPECT_STREQ("one", _array[0]);
EXPECT_STREQ("two", _array[1]);
REQUIRE(2 == _array.size());
REQUIRE(_array[0] == 1);
REQUIRE(_array[1] == 2);
}
SECTION("RemoveFirstByIterator") {
JsonArray::iterator it = _array.begin();
_array.remove(it);
REQUIRE(2 == _array.size());
REQUIRE(_array[0] == 2);
REQUIRE(_array[1] == 3);
}
SECTION("RemoveMiddleByIterator") {
JsonArray::iterator it = _array.begin();
++it;
_array.remove(it);
REQUIRE(2 == _array.size());
REQUIRE(_array[0] == 1);
REQUIRE(_array[1] == 3);
}
SECTION("RemoveLastByIterator") {
JsonArray::iterator it = _array.begin();
++it;
++it;
_array.remove(it);
REQUIRE(2 == _array.size());
REQUIRE(_array[0] == 1);
REQUIRE(_array[1] == 2);
}
}

View File

@ -6,87 +6,83 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
class JsonArray_Set_Tests : public ::testing::Test {
protected:
JsonArray_Set_Tests() : _array(_jsonBuffer.createArray()) {
_array.add(0);
using namespace Catch::Matchers;
TEST_CASE("JsonArray::set()") {
DynamicJsonBuffer _jsonBuffer;
JsonArray& _array = _jsonBuffer.createArray();
_array.add(0);
SECTION("SizeIsUnchanged") {
_array.set(0, "hello");
REQUIRE(1U == _array.size());
}
DynamicJsonBuffer _jsonBuffer;
JsonArray& _array;
};
SECTION("StoreInteger") {
_array.set(0, 123);
REQUIRE(123 == _array[0].as<int>());
REQUIRE(_array[0].is<int>());
REQUIRE_FALSE(_array[0].is<double>());
}
#define TEST_(name) TEST_F(JsonArray_Set_Tests, name)
SECTION("StoreDouble") {
_array.set(0, 123.45);
REQUIRE(123.45 == _array[0].as<double>());
REQUIRE(_array[0].is<double>());
REQUIRE_FALSE(_array[0].is<int>());
}
TEST_(SizeIsUnchanged) {
_array.set(0, "hello");
EXPECT_EQ(1U, _array.size());
}
TEST_(StoreInteger) {
_array.set(0, 123);
EXPECT_EQ(123, _array[0].as<int>());
EXPECT_TRUE(_array[0].is<int>());
EXPECT_FALSE(_array[0].is<double>());
}
TEST_(StoreDouble) {
_array.set(0, 123.45);
EXPECT_EQ(123.45, _array[0].as<double>());
EXPECT_TRUE(_array[0].is<double>());
EXPECT_FALSE(_array[0].is<int>());
}
TEST_(StoreBoolean) {
_array.set(0, true);
EXPECT_EQ(true, _array[0].as<bool>());
EXPECT_TRUE(_array[0].is<bool>());
EXPECT_FALSE(_array[0].is<int>());
}
TEST_(StoreString) {
_array.set(0, "hello");
EXPECT_STREQ("hello", _array[0].as<const char*>());
EXPECT_TRUE(_array[0].is<const char*>());
EXPECT_FALSE(_array[0].is<int>());
}
TEST_(StoreNestedArray) {
JsonArray& arr = _jsonBuffer.createArray();
_array.set(0, arr);
EXPECT_EQ(&arr, &_array[0].as<JsonArray&>());
EXPECT_TRUE(_array[0].is<JsonArray&>());
EXPECT_FALSE(_array[0].is<int>());
}
TEST_(StoreNestedObject) {
JsonObject& obj = _jsonBuffer.createObject();
_array.set(0, obj);
EXPECT_EQ(&obj, &_array[0].as<JsonObject&>());
EXPECT_TRUE(_array[0].is<JsonObject&>());
EXPECT_FALSE(_array[0].is<int>());
}
TEST_(StoreArraySubscript) {
JsonArray& arr = _jsonBuffer.createArray();
arr.add("hello");
_array.set(0, arr[0]);
EXPECT_STREQ("hello", _array[0]);
}
TEST_(StoreObjectSubscript) {
JsonObject& obj = _jsonBuffer.createObject();
obj["x"] = "hello";
_array.set(0, obj["x"]);
EXPECT_STREQ("hello", _array[0]);
SECTION("StoreBoolean") {
_array.set(0, true);
REQUIRE(true == _array[0].as<bool>());
REQUIRE(_array[0].is<bool>());
REQUIRE_FALSE(_array[0].is<int>());
}
SECTION("StoreString") {
_array.set(0, "hello");
REQUIRE_THAT(_array[0].as<const char*>(), Equals("hello"));
REQUIRE(_array[0].is<const char*>());
REQUIRE_FALSE(_array[0].is<int>());
}
SECTION("StoreNestedArray") {
JsonArray& arr = _jsonBuffer.createArray();
_array.set(0, arr);
REQUIRE(&arr == &_array[0].as<JsonArray&>());
REQUIRE(_array[0].is<JsonArray&>());
REQUIRE_FALSE(_array[0].is<int>());
}
SECTION("StoreNestedObject") {
JsonObject& obj = _jsonBuffer.createObject();
_array.set(0, obj);
REQUIRE(&obj == &_array[0].as<JsonObject&>());
REQUIRE(_array[0].is<JsonObject&>());
REQUIRE_FALSE(_array[0].is<int>());
}
SECTION("StoreArraySubscript") {
JsonArray& arr = _jsonBuffer.createArray();
arr.add("hello");
_array.set(0, arr[0]);
REQUIRE_THAT(_array[0].as<char*>(), Equals("hello"));
}
SECTION("StoreObjectSubscript") {
JsonObject& obj = _jsonBuffer.createObject();
obj["x"] = "hello";
_array.set(0, obj["x"]);
REQUIRE_THAT(_array[0].as<char*>(), Equals("hello"));
}
}

View File

@ -6,111 +6,111 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <stdint.h>
#include <catch.hpp>
class JsonArray_Subscript_Tests : public ::testing::Test {
protected:
JsonArray_Subscript_Tests() : _array(_jsonBuffer.createArray()) {
_array.add(0);
TEST_CASE("JsonArray::operator[]") {
DynamicJsonBuffer _jsonBuffer;
JsonArray& _array = _jsonBuffer.createArray();
_array.add(0);
SECTION("SizeIsUnchanged") {
_array[0] = "hello";
REQUIRE(1U == _array.size());
}
DynamicJsonBuffer _jsonBuffer;
JsonArray& _array;
};
#define TEST_(name) TEST_F(JsonArray_Subscript_Tests, name)
TEST_(SizeIsUnchanged) {
_array[0] = "hello";
EXPECT_EQ(1U, _array.size());
}
TEST_(StoreInteger) {
_array[0] = 123;
EXPECT_EQ(123, _array[0].as<int>());
EXPECT_TRUE(_array[0].is<int>());
EXPECT_FALSE(_array[0].is<double>());
}
SECTION("StoreInteger") {
_array[0] = 123;
REQUIRE(123 == _array[0].as<int>());
REQUIRE(true == _array[0].is<int>());
REQUIRE(false == _array[0].is<double>());
}
#if ARDUINOJSON_USE_LONG_LONG || ARDUINOJSON_USE_INT64
TEST_(StoreLongLong) {
_array[0] = 9223372036854775807;
EXPECT_EQ(9223372036854775807, _array[0].as<long long>());
EXPECT_TRUE(_array[0].is<int>());
EXPECT_FALSE(_array[0].is<double>());
}
SECTION("StoreLongLong") {
_array[0] = 9223372036854775807;
REQUIRE(9223372036854775807 == _array[0].as<long long>());
REQUIRE(true == _array[0].is<int>());
REQUIRE(false == _array[0].is<double>());
}
#endif
TEST_(StoreDouble) {
_array[0] = 123.45;
EXPECT_EQ(123.45, _array[0].as<double>());
EXPECT_TRUE(_array[0].is<double>());
EXPECT_FALSE(_array[0].is<int>());
}
TEST_(StoreDoubleWithDecimals) {
_array[0].set(123.45, 2);
EXPECT_EQ(123.45, _array[0].as<double>());
EXPECT_TRUE(_array[0].is<double>());
EXPECT_FALSE(_array[0].is<int>());
}
TEST_(StoreBoolean) {
_array[0] = true;
EXPECT_EQ(true, _array[0].as<bool>());
EXPECT_TRUE(_array[0].is<bool>());
EXPECT_FALSE(_array[0].is<int>());
}
TEST_(StoreString) {
_array[0] = "hello";
EXPECT_STREQ("hello", _array[0].as<const char*>());
EXPECT_STREQ("hello", _array[0].as<char*>()); // <- short hand
EXPECT_TRUE(_array[0].is<const char*>());
EXPECT_FALSE(_array[0].is<int>());
}
TEST_(StoreNestedArray) {
JsonArray& arr = _jsonBuffer.createArray();
_array[0] = arr;
EXPECT_EQ(&arr, &_array[0].as<JsonArray&>());
EXPECT_EQ(&arr, &_array[0].as<JsonArray>()); // <- short hand
EXPECT_EQ(&arr, &_array[0].as<const JsonArray&>());
EXPECT_EQ(&arr, &_array[0].as<const JsonArray>()); // <- short hand
EXPECT_TRUE(_array[0].is<JsonArray&>());
EXPECT_FALSE(_array[0].is<int>());
}
TEST_(StoreNestedObject) {
JsonObject& obj = _jsonBuffer.createObject();
_array[0] = obj;
EXPECT_EQ(&obj, &_array[0].as<JsonObject&>());
EXPECT_EQ(&obj, &_array[0].as<JsonObject>()); // <- short hand
EXPECT_EQ(&obj, &_array[0].as<const JsonObject&>());
EXPECT_EQ(&obj, &_array[0].as<const JsonObject>()); // <- short hand
EXPECT_TRUE(_array[0].is<JsonObject&>());
EXPECT_FALSE(_array[0].is<int>());
}
TEST_(StoreArraySubscript) {
JsonArray& arr = _jsonBuffer.createArray();
arr.add("hello");
_array[0] = arr[0];
EXPECT_STREQ("hello", _array[0]);
}
TEST_(StoreObjectSubscript) {
JsonObject& obj = _jsonBuffer.createObject();
obj["x"] = "hello";
_array[0] = obj["x"];
EXPECT_STREQ("hello", _array[0]);
SECTION("StoreDouble") {
_array[0] = 123.45;
REQUIRE(123.45 == _array[0].as<double>());
REQUIRE(true == _array[0].is<double>());
REQUIRE(false == _array[0].is<int>());
}
SECTION("StoreDoubleWithDecimals") {
_array[0].set(123.45, 2);
REQUIRE(123.45 == _array[0].as<double>());
REQUIRE(true == _array[0].is<double>());
REQUIRE(false == _array[0].is<int>());
}
SECTION("StoreBoolean") {
_array[0] = true;
REQUIRE(true == _array[0].as<bool>());
REQUIRE(true == _array[0].is<bool>());
REQUIRE(false == _array[0].is<int>());
}
SECTION("StoreString") {
const char* str = "hello";
_array[0] = str;
REQUIRE(str == _array[0].as<const char*>());
REQUIRE(str == _array[0].as<char*>()); // <- short hand
REQUIRE(true == _array[0].is<const char*>());
REQUIRE(false == _array[0].is<int>());
}
SECTION("StoreNestedArray") {
JsonArray& arr = _jsonBuffer.createArray();
_array[0] = arr;
REQUIRE(&arr == &_array[0].as<JsonArray&>());
REQUIRE(&arr == &_array[0].as<JsonArray>()); // <- short hand
REQUIRE(&arr == &_array[0].as<const JsonArray&>());
REQUIRE(&arr == &_array[0].as<const JsonArray>()); // <- short hand
REQUIRE(true == _array[0].is<JsonArray&>());
REQUIRE(false == _array[0].is<int>());
}
SECTION("StoreNestedObject") {
JsonObject& obj = _jsonBuffer.createObject();
_array[0] = obj;
REQUIRE(&obj == &_array[0].as<JsonObject&>());
REQUIRE(&obj == &_array[0].as<JsonObject>()); // <- short hand
REQUIRE(&obj == &_array[0].as<const JsonObject&>());
REQUIRE(&obj == &_array[0].as<const JsonObject>()); // <- short hand
REQUIRE(true == _array[0].is<JsonObject&>());
REQUIRE(false == _array[0].is<int>());
}
SECTION("StoreArraySubscript") {
JsonArray& arr = _jsonBuffer.createArray();
const char* str = "hello";
arr.add(str);
_array[0] = arr[0];
REQUIRE(str == _array[0]);
}
SECTION("StoreObjectSubscript") {
JsonObject& obj = _jsonBuffer.createObject();
const char* str = "hello";
obj["x"] = str;
_array[0] = obj["x"];
REQUIRE(str == _array[0]);
}
}

View File

@ -13,5 +13,5 @@ add_executable(JsonBufferTests
parseObject.cpp
)
target_link_libraries(JsonBufferTests gtest)
target_link_libraries(JsonBufferTests catch)
add_test(JsonBuffer JsonBufferTests)

View File

@ -6,59 +6,61 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
TEST(JsonParser_Nested_Tests, ArrayNestedInObject) {
DynamicJsonBuffer jsonBuffer;
char jsonString[] = " { \"ab\" : [ 1 , 2 ] , \"cd\" : [ 3 , 4 ] } ";
TEST_CASE("JsonBuffer nested objects") {
SECTION("ArrayNestedInObject") {
DynamicJsonBuffer jsonBuffer;
char jsonString[] = " { \"ab\" : [ 1 , 2 ] , \"cd\" : [ 3 , 4 ] } ";
JsonObject &object = jsonBuffer.parseObject(jsonString);
JsonArray &array1 = object["ab"];
const JsonArray &array2 = object["cd"];
JsonArray &array3 = object["ef"];
JsonObject &object = jsonBuffer.parseObject(jsonString);
JsonArray &array1 = object["ab"];
const JsonArray &array2 = object["cd"];
JsonArray &array3 = object["ef"];
ASSERT_TRUE(object.success());
REQUIRE(true == object.success());
ASSERT_TRUE(array1.success());
ASSERT_TRUE(array2.success());
ASSERT_FALSE(array3.success());
REQUIRE(true == array1.success());
REQUIRE(true == array2.success());
REQUIRE(false == array3.success());
ASSERT_EQ(2, array1.size());
ASSERT_EQ(2, array2.size());
ASSERT_EQ(0, array3.size());
REQUIRE(2 == array1.size());
REQUIRE(2 == array2.size());
REQUIRE(0 == array3.size());
EXPECT_EQ(1, array1[0].as<int>());
EXPECT_EQ(2, array1[1].as<int>());
REQUIRE(1 == array1[0].as<int>());
REQUIRE(2 == array1[1].as<int>());
EXPECT_EQ(3, array2[0].as<int>());
EXPECT_EQ(4, array2[1].as<int>());
REQUIRE(3 == array2[0].as<int>());
REQUIRE(4 == array2[1].as<int>());
EXPECT_EQ(0, array3[0].as<int>());
}
TEST(JsonParser_Nested_Tests, ObjectNestedInArray) {
DynamicJsonBuffer jsonBuffer;
char jsonString[] =
" [ { \"a\" : 1 , \"b\" : 2 } , { \"c\" : 3 , \"d\" : 4 } ] ";
JsonArray &array = jsonBuffer.parseArray(jsonString);
JsonObject &object1 = array[0];
const JsonObject &object2 = array[1];
JsonObject &object3 = array[2];
ASSERT_TRUE(array.success());
ASSERT_TRUE(object1.success());
ASSERT_TRUE(object2.success());
ASSERT_FALSE(object3.success());
ASSERT_EQ(2, object1.size());
ASSERT_EQ(2, object2.size());
ASSERT_EQ(0, object3.size());
EXPECT_EQ(1, object1["a"].as<int>());
EXPECT_EQ(2, object1["b"].as<int>());
EXPECT_EQ(3, object2["c"].as<int>());
EXPECT_EQ(4, object2["d"].as<int>());
EXPECT_EQ(0, object3["e"].as<int>());
REQUIRE(0 == array3[0].as<int>());
}
SECTION("ObjectNestedInArray") {
DynamicJsonBuffer jsonBuffer;
char jsonString[] =
" [ { \"a\" : 1 , \"b\" : 2 } , { \"c\" : 3 , \"d\" : 4 } ] ";
JsonArray &array = jsonBuffer.parseArray(jsonString);
JsonObject &object1 = array[0];
const JsonObject &object2 = array[1];
JsonObject &object3 = array[2];
REQUIRE(true == array.success());
REQUIRE(true == object1.success());
REQUIRE(true == object2.success());
REQUIRE(false == object3.success());
REQUIRE(2 == object1.size());
REQUIRE(2 == object2.size());
REQUIRE(0 == object3.size());
REQUIRE(1 == object1["a"].as<int>());
REQUIRE(2 == object1["b"].as<int>());
REQUIRE(3 == object2["c"].as<int>());
REQUIRE(4 == object2["d"].as<int>());
REQUIRE(0 == object3["e"].as<int>());
}
}

View File

@ -6,80 +6,46 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
class JsonParser_NestingLimit_Tests : public testing::Test {
protected:
void whenNestingLimitIs(uint8_t nestingLimit) {
_nestingLimit = nestingLimit;
}
void parseArrayMustFail(const char *json) {
ASSERT_FALSE(tryParseArray(json));
}
void parseArrayMustSucceed(const char *json) {
ASSERT_TRUE(tryParseArray(json));
}
void parseObjectMustFail(const char *json) {
ASSERT_FALSE(tryParseObject(json));
}
void parseObjectMustSucceed(const char *json) {
ASSERT_TRUE(tryParseObject(json));
}
private:
bool tryParseArray(const char *json) {
DynamicJsonBuffer buffer;
char s[256];
strcpy(s, json);
return buffer.parseArray(s, _nestingLimit).success();
}
bool tryParseObject(const char *json) {
DynamicJsonBuffer buffer;
char s[256];
strcpy(s, json);
return buffer.parseObject(s, _nestingLimit).success();
}
uint8_t _nestingLimit;
};
TEST_F(JsonParser_NestingLimit_Tests, ParseArrayWithNestingLimit0) {
whenNestingLimitIs(0);
parseArrayMustSucceed("[]");
parseArrayMustFail("[[]]");
bool tryParseArray(const char *json, uint8_t nestingLimit) {
DynamicJsonBuffer buffer;
return buffer.parseArray(json, nestingLimit).success();
}
TEST_F(JsonParser_NestingLimit_Tests, ParseArrayWithNestingLimit1) {
whenNestingLimitIs(1);
parseArrayMustSucceed("[[]]");
parseArrayMustFail("[[[]]]");
bool tryParseObject(const char *json, uint8_t nestingLimit) {
DynamicJsonBuffer buffer;
return buffer.parseObject(json, nestingLimit).success();
}
TEST_F(JsonParser_NestingLimit_Tests, ParseArrayWithNestingLimit2) {
whenNestingLimitIs(2);
parseArrayMustSucceed("[[[]]]");
parseArrayMustFail("[[[[]]]]");
}
TEST_CASE("JsonParser nestingLimit") {
SECTION("ParseArrayWithNestingLimit0") {
REQUIRE(true == tryParseArray("[]", 0));
REQUIRE(false == tryParseArray("[[]]", 0));
}
TEST_F(JsonParser_NestingLimit_Tests, ParseObjectWithNestingLimit0) {
whenNestingLimitIs(0);
parseObjectMustSucceed("{}");
parseObjectMustFail("{\"key\":{}}");
}
SECTION("ParseArrayWithNestingLimit1") {
REQUIRE(true == tryParseArray("[[]]", 1));
REQUIRE(false == tryParseArray("[[[]]]", 1));
}
TEST_F(JsonParser_NestingLimit_Tests, ParseObjectWithNestingLimit1) {
whenNestingLimitIs(1);
parseObjectMustSucceed("{\"key\":{}}");
parseObjectMustFail("{\"key\":{\"key\":{}}}");
}
SECTION("ParseArrayWithNestingLimit2") {
REQUIRE(true == tryParseArray("[[[]]]", 2));
REQUIRE(false == tryParseArray("[[[[]]]]", 2));
}
TEST_F(JsonParser_NestingLimit_Tests, ParseObjectWithNestingLimit2) {
whenNestingLimitIs(2);
parseObjectMustSucceed("{\"key\":{\"key\":{}}}");
parseObjectMustFail("{\"key\":{\"key\":{\"key\":{}}}}");
SECTION("ParseObjectWithNestingLimit0") {
REQUIRE(true == tryParseObject("{}", 0));
REQUIRE(false == tryParseObject("{\"key\":{}}", 0));
}
SECTION("ParseObjectWithNestingLimit1") {
REQUIRE(true == tryParseObject("{\"key\":{}}", 1));
REQUIRE(false == tryParseObject("{\"key\":{\"key\":{}}}", 1));
}
SECTION("ParseObjectWithNestingLimit2") {
REQUIRE(true == tryParseObject("{\"key\":{\"key\":{}}}", 2));
REQUIRE(false == tryParseObject("{\"key\":{\"key\":{\"key\":{}}}}", 2));
}
}

View File

@ -6,100 +6,78 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
class JsonParser_Variant_Test : public testing::Test {
protected:
void whenInputIs(const char* jsonString) {
strcpy(_jsonString, jsonString);
_result = _jsonBuffer.parse(_jsonString);
using namespace Catch::Matchers;
TEST_CASE("JsonBuffer::parse()") {
DynamicJsonBuffer jb;
SECTION("EmptyObject") {
JsonVariant variant = jb.parse("{}");
REQUIRE(variant.success());
REQUIRE(variant.is<JsonObject>());
}
template <typename T>
void resultMustEqual(T expected) {
EXPECT_EQ(expected, _result.as<T>());
SECTION("EmptyArray") {
JsonVariant variant = jb.parse("[]");
REQUIRE(variant.success());
REQUIRE(variant.is<JsonArray>());
}
void resultMustEqual(const char* expected) {
EXPECT_STREQ(expected, _result.as<char*>());
SECTION("Integer") {
JsonVariant variant = jb.parse("-42");
REQUIRE(variant.success());
REQUIRE(variant.is<int>());
REQUIRE_FALSE(variant.is<double>());
REQUIRE(variant == -42);
}
void resultMustEqual(double expected) {
EXPECT_DOUBLE_EQ(expected, _result.as<double>());
SECTION("Double") {
JsonVariant variant = jb.parse("-1.23e+4");
REQUIRE(variant.success());
REQUIRE_FALSE(variant.is<int>());
REQUIRE(variant.is<double>());
REQUIRE(variant.as<double>() == Approx(-1.23e+4));
}
template <typename T>
void resultTypeMustBe() {
EXPECT_TRUE(_result.is<T>());
SECTION("Double quoted string") {
JsonVariant variant = jb.parse("\"hello world\"");
REQUIRE(variant.success());
REQUIRE(variant.is<char*>());
REQUIRE_THAT(variant.as<char*>(), Equals("hello world"));
}
void resultMustBeInvalid() {
EXPECT_FALSE(_result.success());
}
void resultMustBeValid() {
EXPECT_TRUE(_result.success());
SECTION("Single quoted string") {
JsonVariant variant = jb.parse("\'hello world\'");
REQUIRE(variant.success());
REQUIRE(variant.is<char*>());
REQUIRE_THAT(variant.as<char*>(), Equals("hello world"));
}
template <typename T>
void verify(const char* input, T expected) {
whenInputIs(input);
resultMustBeValid();
resultTypeMustBe<T>();
resultMustEqual(expected);
SECTION("True") {
JsonVariant variant = jb.parse("true");
REQUIRE(variant.success());
REQUIRE(variant.is<bool>());
REQUIRE(variant == true);
}
private:
DynamicJsonBuffer _jsonBuffer;
JsonVariant _result;
char _jsonString[256];
};
SECTION("False") {
JsonVariant variant = jb.parse("false");
REQUIRE(variant.success());
REQUIRE(variant.is<bool>());
REQUIRE(variant == false);
}
TEST_F(JsonParser_Variant_Test, EmptyObject) {
whenInputIs("{}");
resultMustBeValid();
resultTypeMustBe<JsonObject>();
}
SECTION("OpenBrace") {
JsonVariant variant = jb.parse("{");
REQUIRE_FALSE(variant.success());
}
TEST_F(JsonParser_Variant_Test, EmptyArray) {
whenInputIs("[]");
resultMustBeValid();
resultTypeMustBe<JsonArray>();
}
TEST_F(JsonParser_Variant_Test, Integer) {
verify("42", 42);
verify("-42", -42);
}
TEST_F(JsonParser_Variant_Test, Double) {
verify("3.14", 3.14);
verify("3.14", 3.14);
verify("1E+10", 1E+10);
verify("-1E+10", -1E+10);
verify("1.234E+10", 1.234E+10);
verify("1.79769e+308", 1.79769e+308);
verify("-1.79769e+308", -1.79769e+308);
verify("1.7976931348623157e+308", 1.7976931348623157e+308);
verify("0.017976931348623157e+310", 0.017976931348623157e+310);
}
TEST_F(JsonParser_Variant_Test, String) {
verify("\"hello world\"", "hello world");
}
TEST_F(JsonParser_Variant_Test, True) {
verify("true", true);
verify("false", false);
}
TEST_F(JsonParser_Variant_Test, OpenBrace) {
whenInputIs("{");
resultMustBeInvalid();
}
TEST_F(JsonParser_Variant_Test, IncompleteStrings) {
verify("\"", "");
verify("\"hello", "hello");
verify("\'", "");
verify("\'world", "world");
SECTION("Incomplete string") {
JsonVariant variant = jb.parse("\"hello");
REQUIRE(variant.success());
REQUIRE(variant.is<char*>());
REQUIRE_THAT(variant.as<char*>(), Equals("hello"));
}
}

View File

@ -6,362 +6,316 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
class JsonParser_Array_Tests : public testing::Test {
protected:
void whenInputIs(const char *json) {
strcpy(_jsonString, json);
TEST_CASE("JsonBuffer::parseArray()") {
DynamicJsonBuffer jb;
SECTION("EmptyArray") {
JsonArray& arr = jb.parseArray("[]");
REQUIRE(arr.success());
REQUIRE(0 == arr.size());
}
void whenInputIs(const char *json, size_t len) {
memcpy(_jsonString, json, len);
SECTION("MissingOpeningBracket") {
JsonArray& arr = jb.parseArray("]");
REQUIRE_FALSE(arr.success());
}
void parseMustSucceed() {
_array = &_jsonBuffer.parseArray(_jsonString);
EXPECT_TRUE(_array->success());
SECTION("ArrayWithNoEnd") {
JsonArray& arr = jb.parseArray("[");
REQUIRE_FALSE(arr.success());
}
void parseMustFail() {
_array = &_jsonBuffer.parseArray(_jsonString);
EXPECT_FALSE(_array->success());
EXPECT_EQ(0, _array->size());
SECTION("EmptyArrayWithLeadingSpaces") {
JsonArray& arr = jb.parseArray(" []");
REQUIRE(arr.success());
REQUIRE(0 == arr.size());
}
void sizeMustBe(int expected) {
ASSERT_EQ(expected, _array->size());
SECTION("Garbage") {
JsonArray& arr = jb.parseArray("%*$£¤");
REQUIRE_FALSE(arr.success());
}
template <typename T>
void firstElementMustBe(T expected) {
elementAtIndexMustBe(0, expected);
SECTION("OneInteger") {
JsonArray& arr = jb.parseArray("[42]");
REQUIRE(arr.success());
REQUIRE(1 == arr.size());
REQUIRE(arr[0] == 42);
}
template <typename T>
void secondElementMustBe(T expected) {
elementAtIndexMustBe(1, expected);
SECTION("OneIntegerWithSpacesBefore") {
JsonArray& arr = jb.parseArray("[ \t\r\n42]");
REQUIRE(arr.success());
REQUIRE(1 == arr.size());
REQUIRE(arr[0] == 42);
}
template <typename T>
void elementAtIndexMustBe(int index, T expected) {
EXPECT_EQ(expected, (*_array)[index].as<T>());
SECTION("OneIntegerWithSpaceAfter") {
JsonArray& arr = jb.parseArray("[42 \t\r\n]");
REQUIRE(arr.success());
REQUIRE(1 == arr.size());
REQUIRE(arr[0] == 42);
}
void elementAtIndexMustBe(int index, const char *expected) {
EXPECT_STREQ(expected, (*_array)[index].as<const char *>());
SECTION("TwoIntegers") {
JsonArray& arr = jb.parseArray("[42,84]");
REQUIRE(arr.success());
REQUIRE(2 == arr.size());
REQUIRE(arr[0] == 42);
REQUIRE(arr[1] == 84);
}
DynamicJsonBuffer _jsonBuffer;
JsonArray *_array;
char _jsonString[256];
};
SECTION("TwoDoubles") {
JsonArray& arr = jb.parseArray("[4.2,1e2]");
TEST_F(JsonParser_Array_Tests, EmptyArray) {
whenInputIs("[]");
REQUIRE(arr.success());
REQUIRE(2 == arr.size());
REQUIRE(arr[0] == 4.2);
REQUIRE(arr[1] == 1e2);
}
parseMustSucceed();
sizeMustBe(0);
}
TEST_F(JsonParser_Array_Tests, MissingOpeningBracket) {
whenInputIs("]");
parseMustFail();
}
TEST_F(JsonParser_Array_Tests, ArrayWithNoEnd) {
whenInputIs("[");
parseMustFail();
}
TEST_F(JsonParser_Array_Tests, EmptyArrayWithLeadingSpaces) {
whenInputIs(" []");
parseMustSucceed();
sizeMustBe(0);
}
TEST_F(JsonParser_Array_Tests, Garbage) {
whenInputIs("%*$£¤");
parseMustFail();
}
TEST_F(JsonParser_Array_Tests, OneInteger) {
whenInputIs("[42]");
parseMustSucceed();
sizeMustBe(1);
firstElementMustBe(42);
}
TEST_F(JsonParser_Array_Tests, OneIntegerWithSpacesBefore) {
whenInputIs("[ \t\r\n42]");
parseMustSucceed();
sizeMustBe(1);
firstElementMustBe(42);
}
TEST_F(JsonParser_Array_Tests, OneIntegerWithSpaceAfter) {
whenInputIs("[42 \t\r\n]");
parseMustSucceed();
sizeMustBe(1);
firstElementMustBe(42);
}
TEST_F(JsonParser_Array_Tests, TwoIntegers) {
whenInputIs("[42,84]");
parseMustSucceed();
sizeMustBe(2);
firstElementMustBe(42);
secondElementMustBe(84);
}
TEST_F(JsonParser_Array_Tests, TwoDoubles) {
whenInputIs("[4.2,1e2]");
parseMustSucceed();
sizeMustBe(2);
firstElementMustBe(4.2);
secondElementMustBe(1e2);
}
TEST_F(JsonParser_Array_Tests, UnsignedLong) {
whenInputIs("[4294967295]");
parseMustSucceed();
sizeMustBe(1);
firstElementMustBe(4294967295UL);
}
TEST_F(JsonParser_Array_Tests, TwoBooleans) {
whenInputIs("[true,false]");
parseMustSucceed();
sizeMustBe(2);
firstElementMustBe(true);
secondElementMustBe(false);
}
TEST_F(JsonParser_Array_Tests, TwoNulls) {
const char *const nullCharPtr = 0;
whenInputIs("[null,null]");
parseMustSucceed();
sizeMustBe(2);
firstElementMustBe(nullCharPtr);
secondElementMustBe(nullCharPtr);
}
TEST_F(JsonParser_Array_Tests, TwoStringsDoubleQuotes) {
whenInputIs("[ \"hello\" , \"world\" ]");
parseMustSucceed();
sizeMustBe(2);
firstElementMustBe("hello");
secondElementMustBe("world");
}
TEST_F(JsonParser_Array_Tests, TwoStringsSingleQuotes) {
whenInputIs("[ 'hello' , 'world' ]");
parseMustSucceed();
sizeMustBe(2);
firstElementMustBe("hello");
secondElementMustBe("world");
}
TEST_F(JsonParser_Array_Tests, TwoStringsNoQuotes) {
whenInputIs("[ hello , world ]");
parseMustSucceed();
sizeMustBe(2);
firstElementMustBe("hello");
secondElementMustBe("world");
}
TEST_F(JsonParser_Array_Tests, EmptyStringsDoubleQuotes) {
whenInputIs("[\"\",\"\"]");
parseMustSucceed();
sizeMustBe(2);
firstElementMustBe("");
secondElementMustBe("");
}
TEST_F(JsonParser_Array_Tests, EmptyStringSingleQuotes) {
whenInputIs("[\'\',\'\']");
parseMustSucceed();
sizeMustBe(2);
firstElementMustBe("");
secondElementMustBe("");
}
TEST_F(JsonParser_Array_Tests, EmptyStringNoQuotes) {
whenInputIs("[,]");
parseMustSucceed();
sizeMustBe(2);
firstElementMustBe("");
secondElementMustBe("");
}
TEST_F(JsonParser_Array_Tests, ClosingDoubleQuoteMissing) {
whenInputIs("[\"]");
parseMustFail();
}
TEST_F(JsonParser_Array_Tests, ClosingSignleQuoteMissing) {
whenInputIs("[\']");
parseMustFail();
}
TEST_F(JsonParser_Array_Tests, StringWithEscapedChars) {
whenInputIs("[\"1\\\"2\\\\3\\/4\\b5\\f6\\n7\\r8\\t9\"]");
parseMustSucceed();
sizeMustBe(1);
firstElementMustBe("1\"2\\3/4\b5\f6\n7\r8\t9");
}
TEST_F(JsonParser_Array_Tests, StringWithUnterminatedEscapeSequence) {
whenInputIs("\"\\\0\"", 4);
parseMustFail();
}
TEST_F(JsonParser_Array_Tests, CCommentBeforeOpeningBracket) {
whenInputIs("/*COMMENT*/ [\"hello\"]");
parseMustSucceed();
sizeMustBe(1);
firstElementMustBe("hello");
}
TEST_F(JsonParser_Array_Tests, CCommentAfterOpeningBracket) {
whenInputIs("[/*COMMENT*/ \"hello\"]");
parseMustSucceed();
sizeMustBe(1);
firstElementMustBe("hello");
}
TEST_F(JsonParser_Array_Tests, CCommentBeforeClosingBracket) {
whenInputIs("[\"hello\"/*COMMENT*/]");
parseMustSucceed();
sizeMustBe(1);
firstElementMustBe("hello");
}
TEST_F(JsonParser_Array_Tests, CCommentAfterClosingBracket) {
whenInputIs("[\"hello\"]/*COMMENT*/");
parseMustSucceed();
sizeMustBe(1);
firstElementMustBe("hello");
}
TEST_F(JsonParser_Array_Tests, CCommentBeforeComma) {
whenInputIs("[\"hello\"/*COMMENT*/,\"world\"]");
parseMustSucceed();
sizeMustBe(2);
firstElementMustBe("hello");
secondElementMustBe("world");
}
TEST_F(JsonParser_Array_Tests, CCommentAfterComma) {
whenInputIs("[\"hello\",/*COMMENT*/ \"world\"]");
parseMustSucceed();
sizeMustBe(2);
firstElementMustBe("hello");
secondElementMustBe("world");
}
TEST_F(JsonParser_Array_Tests, CppCommentBeforeOpeningBracket) {
whenInputIs("//COMMENT\n\t[\"hello\"]");
parseMustSucceed();
sizeMustBe(1);
firstElementMustBe("hello");
}
TEST_F(JsonParser_Array_Tests, CppCommentAfterOpeningBracket) {
whenInputIs("[//COMMENT\n\"hello\"]");
parseMustSucceed();
sizeMustBe(1);
firstElementMustBe("hello");
}
TEST_F(JsonParser_Array_Tests, CppCommentBeforeClosingBracket) {
whenInputIs("[\"hello\"//COMMENT\r\n]");
parseMustSucceed();
sizeMustBe(1);
firstElementMustBe("hello");
}
TEST_F(JsonParser_Array_Tests, CppCommentAfterClosingBracket) {
whenInputIs("[\"hello\"]//COMMENT\n");
parseMustSucceed();
sizeMustBe(1);
firstElementMustBe("hello");
}
TEST_F(JsonParser_Array_Tests, CppCommentBeforeComma) {
whenInputIs("[\"hello\"//COMMENT\n,\"world\"]");
parseMustSucceed();
sizeMustBe(2);
firstElementMustBe("hello");
secondElementMustBe("world");
}
TEST_F(JsonParser_Array_Tests, CppCommentAfterComma) {
whenInputIs("[\"hello\",//COMMENT\n\"world\"]");
parseMustSucceed();
sizeMustBe(2);
firstElementMustBe("hello");
secondElementMustBe("world");
}
TEST_F(JsonParser_Array_Tests, InvalidCppComment) {
whenInputIs("[/COMMENT\n]");
parseMustFail();
}
TEST_F(JsonParser_Array_Tests, InvalidComment) {
whenInputIs("[/*/\n]");
parseMustFail();
}
TEST_F(JsonParser_Array_Tests, UnfinishedCComment) {
whenInputIs("[/*COMMENT]");
parseMustFail();
}
TEST_F(JsonParser_Array_Tests, EndsInCppComment) {
whenInputIs("[//COMMENT");
parseMustFail();
}
TEST_F(JsonParser_Array_Tests, AfterClosingStar) {
whenInputIs("[/*COMMENT*");
parseMustFail();
}
TEST_F(JsonParser_Array_Tests, DeeplyNested) {
whenInputIs("[[[[[[[[[[[[[[[[[[[\"Not too deep\"]]]]]]]]]]]]]]]]]]]");
parseMustSucceed();
SECTION("UnsignedLong") {
JsonArray& arr = jb.parseArray("[4294967295]");
REQUIRE(arr.success());
REQUIRE(1 == arr.size());
REQUIRE(arr[0] == 4294967295UL);
}
SECTION("TwoBooleans") {
JsonArray& arr = jb.parseArray("[true,false]");
REQUIRE(arr.success());
REQUIRE(2 == arr.size());
REQUIRE(arr[0] == true);
REQUIRE(arr[1] == false);
}
SECTION("TwoNulls") {
JsonArray& arr = jb.parseArray("[null,null]");
REQUIRE(arr.success());
REQUIRE(2 == arr.size());
REQUIRE(arr[0].as<char*>() == 0);
REQUIRE(arr[1].as<char*>() == 0);
}
SECTION("TwoStringsDoubleQuotes") {
JsonArray& arr = jb.parseArray("[ \"hello\" , \"world\" ]");
REQUIRE(arr.success());
REQUIRE(2 == arr.size());
REQUIRE(arr[0] == "hello");
REQUIRE(arr[1] == "world");
}
SECTION("TwoStringsSingleQuotes") {
JsonArray& arr = jb.parseArray("[ 'hello' , 'world' ]");
REQUIRE(arr.success());
REQUIRE(2 == arr.size());
REQUIRE(arr[0] == "hello");
REQUIRE(arr[1] == "world");
}
SECTION("TwoStringsNoQuotes") {
JsonArray& arr = jb.parseArray("[ hello , world ]");
REQUIRE(arr.success());
REQUIRE(2 == arr.size());
REQUIRE(arr[0] == "hello");
REQUIRE(arr[1] == "world");
}
SECTION("EmptyStringsDoubleQuotes") {
JsonArray& arr = jb.parseArray("[\"\",\"\"]");
REQUIRE(arr.success());
REQUIRE(2 == arr.size());
REQUIRE(arr[0] == "");
REQUIRE(arr[1] == "");
}
SECTION("EmptyStringSingleQuotes") {
JsonArray& arr = jb.parseArray("[\'\',\'\']");
REQUIRE(arr.success());
REQUIRE(2 == arr.size());
REQUIRE(arr[0] == "");
REQUIRE(arr[1] == "");
}
SECTION("EmptyStringNoQuotes") {
JsonArray& arr = jb.parseArray("[,]");
REQUIRE(arr.success());
REQUIRE(2 == arr.size());
REQUIRE(arr[0] == "");
REQUIRE(arr[1] == "");
}
SECTION("ClosingDoubleQuoteMissing") {
JsonArray& arr = jb.parseArray("[\"]");
REQUIRE_FALSE(arr.success());
}
SECTION("ClosingSignleQuoteMissing") {
JsonArray& arr = jb.parseArray("[\']");
REQUIRE_FALSE(arr.success());
}
SECTION("StringWithEscapedChars") {
JsonArray& arr = jb.parseArray("[\"1\\\"2\\\\3\\/4\\b5\\f6\\n7\\r8\\t9\"]");
REQUIRE(arr.success());
REQUIRE(1 == arr.size());
REQUIRE(arr[0] == "1\"2\\3/4\b5\f6\n7\r8\t9");
}
SECTION("StringWithUnterminatedEscapeSequence") {
JsonArray& arr = jb.parseArray("\"\\\0\"", 4);
REQUIRE_FALSE(arr.success());
}
SECTION("CCommentBeforeOpeningBracket") {
JsonArray& arr = jb.parseArray("/*COMMENT*/ [\"hello\"]");
REQUIRE(arr.success());
REQUIRE(1 == arr.size());
REQUIRE(arr[0] == "hello");
}
SECTION("CCommentAfterOpeningBracket") {
JsonArray& arr = jb.parseArray("[/*COMMENT*/ \"hello\"]");
REQUIRE(arr.success());
REQUIRE(1 == arr.size());
REQUIRE(arr[0] == "hello");
}
SECTION("CCommentBeforeClosingBracket") {
JsonArray& arr = jb.parseArray("[\"hello\"/*COMMENT*/]");
REQUIRE(arr.success());
REQUIRE(1 == arr.size());
REQUIRE(arr[0] == "hello");
}
SECTION("CCommentAfterClosingBracket") {
JsonArray& arr = jb.parseArray("[\"hello\"]/*COMMENT*/");
REQUIRE(arr.success());
REQUIRE(1 == arr.size());
REQUIRE(arr[0] == "hello");
}
SECTION("CCommentBeforeComma") {
JsonArray& arr = jb.parseArray("[\"hello\"/*COMMENT*/,\"world\"]");
REQUIRE(arr.success());
REQUIRE(2 == arr.size());
REQUIRE(arr[0] == "hello");
REQUIRE(arr[1] == "world");
}
SECTION("CCommentAfterComma") {
JsonArray& arr = jb.parseArray("[\"hello\",/*COMMENT*/ \"world\"]");
REQUIRE(arr.success());
REQUIRE(2 == arr.size());
REQUIRE(arr[0] == "hello");
REQUIRE(arr[1] == "world");
}
SECTION("CppCommentBeforeOpeningBracket") {
JsonArray& arr = jb.parseArray("//COMMENT\n\t[\"hello\"]");
REQUIRE(arr.success());
REQUIRE(1 == arr.size());
REQUIRE(arr[0] == "hello");
}
SECTION("CppCommentAfterOpeningBracket") {
JsonArray& arr = jb.parseArray("[//COMMENT\n\"hello\"]");
REQUIRE(arr.success());
REQUIRE(1 == arr.size());
REQUIRE(arr[0] == "hello");
}
SECTION("CppCommentBeforeClosingBracket") {
JsonArray& arr = jb.parseArray("[\"hello\"//COMMENT\r\n]");
REQUIRE(arr.success());
REQUIRE(1 == arr.size());
REQUIRE(arr[0] == "hello");
}
SECTION("CppCommentAfterClosingBracket") {
JsonArray& arr = jb.parseArray("[\"hello\"]//COMMENT\n");
REQUIRE(arr.success());
REQUIRE(1 == arr.size());
REQUIRE(arr[0] == "hello");
}
SECTION("CppCommentBeforeComma") {
JsonArray& arr = jb.parseArray("[\"hello\"//COMMENT\n,\"world\"]");
REQUIRE(arr.success());
REQUIRE(2 == arr.size());
REQUIRE(arr[0] == "hello");
REQUIRE(arr[1] == "world");
}
SECTION("CppCommentAfterComma") {
JsonArray& arr = jb.parseArray("[\"hello\",//COMMENT\n\"world\"]");
REQUIRE(arr.success());
REQUIRE(2 == arr.size());
REQUIRE(arr[0] == "hello");
REQUIRE(arr[1] == "world");
}
SECTION("InvalidCppComment") {
JsonArray& arr = jb.parseArray("[/COMMENT\n]");
REQUIRE_FALSE(arr.success());
}
SECTION("InvalidComment") {
JsonArray& arr = jb.parseArray("[/*/\n]");
REQUIRE_FALSE(arr.success());
}
SECTION("UnfinishedCComment") {
JsonArray& arr = jb.parseArray("[/*COMMENT]");
REQUIRE_FALSE(arr.success());
}
SECTION("EndsInCppComment") {
JsonArray& arr = jb.parseArray("[//COMMENT");
REQUIRE_FALSE(arr.success());
}
SECTION("AfterClosingStar") {
JsonArray& arr = jb.parseArray("[/*COMMENT*");
REQUIRE_FALSE(arr.success());
}
SECTION("DeeplyNested") {
JsonArray& arr =
jb.parseArray("[[[[[[[[[[[[[[[[[[[\"Not too deep\"]]]]]]]]]]]]]]]]]]]");
REQUIRE(arr.success());
}
}

View File

@ -6,182 +6,153 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
class JsonParser_Object_Test : public testing::Test {
protected:
void whenInputIs(const char *jsonString) {
strcpy(_jsonString, jsonString);
_object = &_jsonBuffer.parseObject(_jsonString);
TEST_CASE("JsonBuffer::parseObject()") {
DynamicJsonBuffer jb;
SECTION("EmptyObject") {
JsonObject& obj = jb.parseObject("{}");
REQUIRE(obj.success());
REQUIRE(obj.size() == 0);
}
void parseMustSucceed() {
EXPECT_TRUE(_object->success());
SECTION("MissingOpeningBrace") {
JsonObject& obj = jb.parseObject("}");
REQUIRE_FALSE(obj.success());
}
void parseMustFail() {
EXPECT_FALSE(_object->success());
SECTION("MissingClosingBrace") {
JsonObject& obj = jb.parseObject("{");
REQUIRE_FALSE(obj.success());
}
void sizeMustBe(int expected) {
EXPECT_EQ(expected, _object->size());
SECTION("MissingColonAndValue") {
JsonObject& obj = jb.parseObject("{\"key\"}");
REQUIRE_FALSE(obj.success());
}
void keyMustHaveValue(const char *key, const char *expected) {
EXPECT_STREQ(expected, (*_object)[key]);
SECTION("MissingQuotesAndColonAndValue") {
JsonObject& obj = jb.parseObject("{key}");
REQUIRE_FALSE(obj.success());
}
template <typename T>
void keyMustHaveValue(const char *key, T expected) {
EXPECT_EQ(expected, (*_object)[key].as<T>());
SECTION("OneString") {
JsonObject& obj = jb.parseObject("{\"key\":\"value\"}");
REQUIRE(obj.success());
REQUIRE(obj.size() == 1);
REQUIRE(obj["key"] == "value");
}
private:
DynamicJsonBuffer _jsonBuffer;
JsonObject *_object;
char _jsonString[256];
};
SECTION("OneStringSingleQuotes") {
JsonObject& obj = jb.parseObject("{'key':'value'}");
REQUIRE(obj.success());
REQUIRE(obj.size() == 1);
REQUIRE(obj["key"] == "value");
}
TEST_F(JsonParser_Object_Test, EmptyObject) {
whenInputIs("{}");
parseMustSucceed();
sizeMustBe(0);
}
TEST_F(JsonParser_Object_Test, MissingOpeningBrace) {
whenInputIs("}");
parseMustFail();
}
TEST_F(JsonParser_Object_Test, MissingClosingBrace) {
whenInputIs("{");
parseMustFail();
}
TEST_F(JsonParser_Object_Test, MissingColonAndValue) {
whenInputIs("{\"key\"}");
parseMustFail();
}
TEST_F(JsonParser_Object_Test, MissingQuotesAndColonAndValue) {
whenInputIs("{key}");
parseMustFail();
}
TEST_F(JsonParser_Object_Test, OneString) {
whenInputIs("{\"key\":\"value\"}");
parseMustSucceed();
sizeMustBe(1);
keyMustHaveValue("key", "value");
}
TEST_F(JsonParser_Object_Test, OneStringSingleQuotes) {
whenInputIs("{'key':'value'}");
parseMustSucceed();
sizeMustBe(1);
keyMustHaveValue("key", "value");
}
TEST_F(JsonParser_Object_Test, OneStringNoQuotes) {
whenInputIs("{key:value}");
parseMustSucceed();
sizeMustBe(1);
keyMustHaveValue("key", "value");
}
TEST_F(JsonParser_Object_Test, OneStringSpaceBeforeKey) {
whenInputIs("{ \"key\":\"value\"}");
parseMustSucceed();
sizeMustBe(1);
keyMustHaveValue("key", "value");
}
TEST_F(JsonParser_Object_Test, OneStringSpaceAfterKey) {
whenInputIs("{\"key\" :\"value\"}");
parseMustSucceed();
sizeMustBe(1);
keyMustHaveValue("key", "value");
}
TEST_F(JsonParser_Object_Test, OneStringSpaceBeforeValue) {
whenInputIs("{\"key\": \"value\"}");
parseMustSucceed();
sizeMustBe(1);
keyMustHaveValue("key", "value");
}
TEST_F(JsonParser_Object_Test, OneStringSpaceAfterValue) {
whenInputIs("{\"key\":\"value\" }");
parseMustSucceed();
sizeMustBe(1);
keyMustHaveValue("key", "value");
}
TEST_F(JsonParser_Object_Test, TwoStrings) {
whenInputIs("{\"key1\":\"value1\",\"key2\":\"value2\"}");
parseMustSucceed();
sizeMustBe(2);
keyMustHaveValue("key1", "value1");
keyMustHaveValue("key2", "value2");
}
TEST_F(JsonParser_Object_Test, TwoStringsSpaceBeforeComma) {
whenInputIs("{\"key1\":\"value1\" ,\"key2\":\"value2\"}");
parseMustSucceed();
sizeMustBe(2);
keyMustHaveValue("key1", "value1");
keyMustHaveValue("key2", "value2");
}
TEST_F(JsonParser_Object_Test, TwoStringsSpaceAfterComma) {
whenInputIs("{\"key1\":\"value1\" ,\"key2\":\"value2\"}");
parseMustSucceed();
sizeMustBe(2);
keyMustHaveValue("key1", "value1");
keyMustHaveValue("key2", "value2");
}
TEST_F(JsonParser_Object_Test, EndingWithAComma) {
whenInputIs("{\"key1\":\"value1\",}");
parseMustFail();
sizeMustBe(0);
}
TEST_F(JsonParser_Object_Test, TwoIntergers) {
whenInputIs("{\"key1\":42,\"key2\":-42}");
parseMustSucceed();
sizeMustBe(2);
keyMustHaveValue("key1", 42);
keyMustHaveValue("key2", -42);
}
TEST_F(JsonParser_Object_Test, TwoDoubles) {
whenInputIs("{\"key1\":12.345,\"key2\":-7E89}");
parseMustSucceed();
sizeMustBe(2);
keyMustHaveValue("key1", 12.345);
keyMustHaveValue("key2", -7E89);
}
TEST_F(JsonParser_Object_Test, TwoBooleans) {
whenInputIs("{\"key1\":true,\"key2\":false}");
parseMustSucceed();
sizeMustBe(2);
keyMustHaveValue("key1", true);
keyMustHaveValue("key2", false);
}
TEST_F(JsonParser_Object_Test, TwoNulls) {
const char *const nullstr = 0;
whenInputIs("{\"key1\":null,\"key2\":null}");
parseMustSucceed();
sizeMustBe(2);
keyMustHaveValue("key1", nullstr);
keyMustHaveValue("key2", nullstr);
}
TEST_F(JsonParser_Object_Test, NullForKey) {
whenInputIs("null:\"value\"}");
parseMustFail();
SECTION("OneStringNoQuotes") {
JsonObject& obj = jb.parseObject("{key:value}");
REQUIRE(obj.success());
REQUIRE(obj.size() == 1);
REQUIRE(obj["key"] == "value");
}
SECTION("OneStringSpaceBeforeKey") {
JsonObject& obj = jb.parseObject("{ \"key\":\"value\"}");
REQUIRE(obj.success());
REQUIRE(obj.size() == 1);
REQUIRE(obj["key"] == "value");
}
SECTION("OneStringSpaceAfterKey") {
JsonObject& obj = jb.parseObject("{\"key\" :\"value\"}");
REQUIRE(obj.success());
REQUIRE(obj.size() == 1);
REQUIRE(obj["key"] == "value");
}
SECTION("OneStringSpaceBeforeValue") {
JsonObject& obj = jb.parseObject("{\"key\": \"value\"}");
REQUIRE(obj.success());
REQUIRE(obj.size() == 1);
REQUIRE(obj["key"] == "value");
}
SECTION("OneStringSpaceAfterValue") {
JsonObject& obj = jb.parseObject("{\"key\":\"value\" }");
REQUIRE(obj.success());
REQUIRE(obj.size() == 1);
REQUIRE(obj["key"] == "value");
}
SECTION("TwoStrings") {
JsonObject& obj =
jb.parseObject("{\"key1\":\"value1\",\"key2\":\"value2\"}");
REQUIRE(obj.success());
REQUIRE(obj.size() == 2);
REQUIRE(obj["key1"] == "value1");
REQUIRE(obj["key2"] == "value2");
}
SECTION("TwoStringsSpaceBeforeComma") {
JsonObject& obj =
jb.parseObject("{\"key1\":\"value1\" ,\"key2\":\"value2\"}");
REQUIRE(obj.success());
REQUIRE(obj.size() == 2);
REQUIRE(obj["key1"] == "value1");
REQUIRE(obj["key2"] == "value2");
}
SECTION("TwoStringsSpaceAfterComma") {
JsonObject& obj =
jb.parseObject("{\"key1\":\"value1\" ,\"key2\":\"value2\"}");
REQUIRE(obj.success());
REQUIRE(obj.size() == 2);
REQUIRE(obj["key1"] == "value1");
REQUIRE(obj["key2"] == "value2");
}
SECTION("EndingWithAComma") {
JsonObject& obj = jb.parseObject("{\"key1\":\"value1\",}");
REQUIRE_FALSE(obj.success());
REQUIRE(obj.size() == 0);
}
SECTION("TwoIntergers") {
JsonObject& obj = jb.parseObject("{\"key1\":42,\"key2\":-42}");
REQUIRE(obj.success());
REQUIRE(obj.size() == 2);
REQUIRE(obj["key1"] == 42);
REQUIRE(obj["key2"] == -42);
}
SECTION("TwoDoubles") {
JsonObject& obj = jb.parseObject("{\"key1\":12.345,\"key2\":-7E89}");
REQUIRE(obj.success());
REQUIRE(obj.size() == 2);
REQUIRE(obj["key1"] == 12.345);
REQUIRE(obj["key2"] == -7E89);
}
SECTION("TwoBooleans") {
JsonObject& obj = jb.parseObject("{\"key1\":true,\"key2\":false}");
REQUIRE(obj.success());
REQUIRE(obj.size() == 2);
REQUIRE(obj["key1"] == true);
REQUIRE(obj["key2"] == false);
}
SECTION("TwoNulls") {
JsonObject& obj = jb.parseObject("{\"key1\":null,\"key2\":null}");
REQUIRE(obj.success());
REQUIRE(obj.size() == 2);
REQUIRE(obj["key1"].as<char*>() == 0);
REQUIRE(obj["key2"].as<char*>() == 0);
}
SECTION("NullForKey") {
JsonObject& obj = jb.parseObject("null:\"value\"}");
REQUIRE_FALSE(obj.success());
}
}

View File

@ -18,5 +18,5 @@ add_executable(JsonObjectTests
subscript.cpp
)
target_link_libraries(JsonObjectTests gtest)
target_link_libraries(JsonObjectTests catch)
add_test(JsonObject JsonObjectTests)

View File

@ -6,20 +6,17 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
#define TEST_(name) TEST(JsonObject_Basic_Tests, name)
TEST_(InitialSizeIsZero) {
TEST_CASE("JsonObject basics") {
DynamicJsonBuffer _jsonBuffer;
JsonObject& _object = _jsonBuffer.createObject();
EXPECT_EQ(0, _object.size());
}
SECTION("InitialSizeIsZero") {
REQUIRE(0 == _object.size());
}
TEST_(SuccessIsTrue) {
DynamicJsonBuffer _jsonBuffer;
JsonObject& _object = _jsonBuffer.createObject();
EXPECT_TRUE(_object.success());
SECTION("SuccessIsTrue") {
REQUIRE(_object.success());
}
}

View File

@ -6,34 +6,28 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
#define TEST_(name) TEST(JsonObject_Basic_Tests, name)
TEST_(ContainsKeyReturnsFalseForNonExistingKey) {
TEST_CASE("JsonObject::containsKey()") {
DynamicJsonBuffer _jsonBuffer;
JsonObject& _object = _jsonBuffer.createObject();
_object.set("hello", 42);
SECTION("ContainsKeyReturnsFalseForNonExistingKey") {
_object.set("hello", 42);
EXPECT_FALSE(_object.containsKey("world"));
}
TEST_(ContainsKeyReturnsTrueForDefinedValue) {
DynamicJsonBuffer _jsonBuffer;
JsonObject& _object = _jsonBuffer.createObject();
_object.set("hello", 42);
EXPECT_TRUE(_object.containsKey("hello"));
}
TEST_(ContainsKeyReturnsFalseAfterRemove) {
DynamicJsonBuffer _jsonBuffer;
JsonObject& _object = _jsonBuffer.createObject();
_object.set("hello", 42);
_object.remove("hello");
EXPECT_FALSE(_object.containsKey("hello"));
REQUIRE(false == _object.containsKey("world"));
}
SECTION("ContainsKeyReturnsTrueForDefinedValue") {
_object.set("hello", 42);
REQUIRE(true == _object.containsKey("hello"));
}
SECTION("ContainsKeyReturnsFalseAfterRemove") {
_object.set("hello", 42);
_object.remove("hello");
REQUIRE(false == _object.containsKey("hello"));
}
}

View File

@ -6,21 +6,17 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
class JsonObject_Get_Tests : public ::testing::Test {
public:
JsonObject_Get_Tests() : _object(_jsonBuffer.createObject()) {}
using namespace Catch::Matchers;
protected:
DynamicJsonBuffer _jsonBuffer;
JsonObject& _object;
};
TEST_CASE("JsonObject::get()") {
DynamicJsonBuffer jb;
JsonObject& obj = jb.createObject();
#define TEST_(name) TEST_F(JsonObject_Get_Tests, name)
TEST_(GetConstCharPointer_GivenStringLiteral) {
_object.set("hello", "world");
const char* value = _object.get<const char*>("hello");
EXPECT_STREQ("world", value);
SECTION("GetConstCharPointer_GivenStringLiteral") {
obj.set("hello", "world");
const char* value = obj.get<const char*>("hello");
REQUIRE_THAT(value, Equals("world"));
}
}

View File

@ -6,28 +6,33 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
TEST(JsonObject_Invalid_Tests, SubscriptFails) {
ASSERT_FALSE(JsonObject::invalid()["key"].success());
}
using namespace Catch::Matchers;
TEST(JsonObject_Invalid_Tests, AddFails) {
JsonObject& object = JsonObject::invalid();
object.set("hello", "world");
ASSERT_EQ(0, object.size());
}
TEST_CASE("JsonObject::invalid()") {
JsonObject& obj = JsonObject::invalid();
TEST(JsonObject_Invalid_Tests, CreateNestedArrayFails) {
ASSERT_FALSE(JsonObject::invalid().createNestedArray("hello").success());
}
SECTION("SubscriptFails") {
REQUIRE_FALSE(obj["key"].success());
}
TEST(JsonObject_Invalid_Tests, CreateNestedObjectFails) {
ASSERT_FALSE(JsonObject::invalid().createNestedObject("world").success());
}
SECTION("AddFails") {
obj.set("hello", "world");
REQUIRE(0 == obj.size());
}
TEST(JsonObject_Invalid_Tests, PrintToWritesBraces) {
char buffer[32];
JsonObject::invalid().printTo(buffer, sizeof(buffer));
ASSERT_STREQ("{}", buffer);
SECTION("CreateNestedArrayFails") {
REQUIRE_FALSE(obj.createNestedArray("hello").success());
}
SECTION("CreateNestedObjectFails") {
REQUIRE_FALSE(obj.createNestedObject("world").success());
}
SECTION("PrintToWritesBraces") {
char buffer[32];
obj.printTo(buffer, sizeof(buffer));
REQUIRE_THAT(buffer, Equals("{}"));
}
}

View File

@ -6,52 +6,49 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
class JsonObject_Iterator_Test : public testing::Test {
public:
JsonObject_Iterator_Test() : _object(_buffer.createObject()) {
_object["ab"] = 12;
_object["cd"] = 34;
using namespace Catch::Matchers;
TEST_CASE("JsonObject::begin()/end()") {
StaticJsonBuffer<JSON_OBJECT_SIZE(2)> jb;
JsonObject& obj = jb.createObject();
obj["ab"] = 12;
obj["cd"] = 34;
SECTION("NonConstIterator") {
JsonObject::iterator it = obj.begin();
REQUIRE(obj.end() != it);
REQUIRE_THAT(it->key, Equals("ab"));
REQUIRE(12 == it->value);
it->key = "a.b";
it->value = 1.2;
++it;
REQUIRE(obj.end() != it);
REQUIRE_THAT(it->key, Equals("cd"));
REQUIRE(34 == it->value);
it->key = "c.d";
it->value = 3.4;
++it;
REQUIRE(obj.end() == it);
REQUIRE(2 == obj.size());
REQUIRE(1.2 == obj["a.b"]);
REQUIRE(3.4 == obj["c.d"]);
}
protected:
StaticJsonBuffer<JSON_OBJECT_SIZE(2)> _buffer;
JsonObject& _object;
};
SECTION("ConstIterator") {
const JsonObject& const_object = obj;
JsonObject::const_iterator it = const_object.begin();
TEST_F(JsonObject_Iterator_Test, NonConstIterator) {
JsonObject::iterator it = _object.begin();
ASSERT_NE(_object.end(), it);
EXPECT_STREQ("ab", it->key);
EXPECT_EQ(12, it->value);
it->key = "a.b";
it->value = 1.2;
++it;
ASSERT_NE(_object.end(), it);
EXPECT_STREQ("cd", it->key);
EXPECT_EQ(34, it->value);
it->key = "c.d";
it->value = 3.4;
++it;
ASSERT_EQ(_object.end(), it);
ASSERT_EQ(2, _object.size());
EXPECT_EQ(1.2, _object["a.b"]);
EXPECT_EQ(3.4, _object["c.d"]);
}
TEST_F(JsonObject_Iterator_Test, ConstIterator) {
const JsonObject& const_object = _object;
JsonObject::const_iterator it = const_object.begin();
ASSERT_NE(const_object.end(), it);
EXPECT_STREQ("ab", it->key);
EXPECT_EQ(12, it->value);
++it;
ASSERT_NE(const_object.end(), it);
EXPECT_STREQ("cd", it->key);
EXPECT_EQ(34, it->value);
++it;
ASSERT_EQ(const_object.end(), it);
REQUIRE(const_object.end() != it);
REQUIRE_THAT(it->key, Equals("ab"));
REQUIRE(12 == it->value);
++it;
REQUIRE(const_object.end() != it);
REQUIRE_THAT(it->key, Equals("cd"));
REQUIRE(34 == it->value);
++it;
REQUIRE(const_object.end() == it);
}
}

View File

@ -6,77 +6,74 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
#include <string>
class JsonObject_PrettyPrintTo_Tests : public testing::Test {
public:
JsonObject_PrettyPrintTo_Tests() : _object(_jsonBuffer.createObject()) {}
void check(const JsonObject &obj, const std::string expected) {
char json[256];
protected:
DynamicJsonBuffer _jsonBuffer;
JsonObject &_object;
size_t actualLen = obj.prettyPrintTo(json);
size_t measuredLen = obj.measurePrettyLength();
void outputMustBe(const char *expected) {
char buffer[256];
REQUIRE(json == expected);
REQUIRE(expected.size() == actualLen);
REQUIRE(expected.size() == measuredLen);
}
size_t actualLen = _object.prettyPrintTo(buffer);
size_t measuredLen = _object.measurePrettyLength();
TEST_CASE("JsonObject::prettyPrintTo()") {
DynamicJsonBuffer jb;
JsonObject &obj = jb.createObject();
EXPECT_STREQ(expected, buffer);
EXPECT_EQ(strlen(expected), actualLen);
EXPECT_EQ(strlen(expected), measuredLen);
SECTION("EmptyObject") {
check(obj, "{}");
}
};
TEST_F(JsonObject_PrettyPrintTo_Tests, EmptyObject) {
outputMustBe("{}");
}
TEST_F(JsonObject_PrettyPrintTo_Tests, OneMember) {
_object["key"] = "value";
outputMustBe(
"{\r\n"
" \"key\": \"value\"\r\n"
"}");
}
TEST_F(JsonObject_PrettyPrintTo_Tests, TwoMembers) {
_object["key1"] = "value1";
_object["key2"] = "value2";
outputMustBe(
"{\r\n"
" \"key1\": \"value1\",\r\n"
" \"key2\": \"value2\"\r\n"
"}");
}
TEST_F(JsonObject_PrettyPrintTo_Tests, EmptyNestedContainers) {
_object.createNestedObject("key1");
_object.createNestedArray("key2");
outputMustBe(
"{\r\n"
" \"key1\": {},\r\n"
" \"key2\": []\r\n"
"}");
}
TEST_F(JsonObject_PrettyPrintTo_Tests, NestedContainers) {
JsonObject &nested1 = _object.createNestedObject("key1");
nested1["a"] = 1;
JsonArray &nested2 = _object.createNestedArray("key2");
nested2.add(2);
outputMustBe(
"{\r\n"
" \"key1\": {\r\n"
" \"a\": 1\r\n"
" },\r\n"
" \"key2\": [\r\n"
" 2\r\n"
" ]\r\n"
"}");
SECTION("OneMember") {
obj["key"] = "value";
check(obj,
"{\r\n"
" \"key\": \"value\"\r\n"
"}");
}
SECTION("TwoMembers") {
obj["key1"] = "value1";
obj["key2"] = "value2";
check(obj,
"{\r\n"
" \"key1\": \"value1\",\r\n"
" \"key2\": \"value2\"\r\n"
"}");
}
SECTION("EmptyNestedContainers") {
obj.createNestedObject("key1");
obj.createNestedArray("key2");
check(obj,
"{\r\n"
" \"key1\": {},\r\n"
" \"key2\": []\r\n"
"}");
}
SECTION("NestedContainers") {
JsonObject &nested1 = obj.createNestedObject("key1");
nested1["a"] = 1;
JsonArray &nested2 = obj.createNestedArray("key2");
nested2.add(2);
check(obj,
"{\r\n"
" \"key1\": {\r\n"
" \"a\": 1\r\n"
" },\r\n"
" \"key2\": [\r\n"
" 2\r\n"
" ]\r\n"
"}");
}
}

View File

@ -6,118 +6,114 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
#include <string>
class JsonObject_PrintTo_Tests : public testing::Test {
public:
JsonObject_PrintTo_Tests() : _object(_jsonBuffer.createObject()) {}
void check(const JsonObject &obj, const std::string &expected) {
char actual[256];
size_t actualLen = obj.printTo(actual);
size_t measuredLen = obj.measureLength();
protected:
void outputMustBe(const char *expected) {
char actual[256];
size_t actualLen = _object.printTo(actual);
size_t measuredLen = _object.measureLength();
REQUIRE(expected == actual);
REQUIRE(expected.size() == actualLen);
REQUIRE(expected.size() == measuredLen);
}
TEST_CASE("JsonObject::printTo()") {
DynamicJsonBuffer _jsonBuffer;
JsonObject &obj = _jsonBuffer.createObject();
EXPECT_STREQ(expected, actual);
EXPECT_EQ(strlen(expected), actualLen);
EXPECT_EQ(strlen(expected), measuredLen);
SECTION("EmptyObject") {
check(obj, "{}");
}
DynamicJsonBuffer _jsonBuffer;
JsonObject &_object;
};
SECTION("TwoStrings") {
obj["key1"] = "value1";
obj.set("key2", "value2");
TEST_F(JsonObject_PrintTo_Tests, EmptyObject) {
outputMustBe("{}");
}
TEST_F(JsonObject_PrintTo_Tests, TwoStrings) {
_object["key1"] = "value1";
_object.set("key2", "value2");
outputMustBe("{\"key1\":\"value1\",\"key2\":\"value2\"}");
}
TEST_F(JsonObject_PrintTo_Tests, RemoveFirst) {
_object["key1"] = "value1";
_object["key2"] = "value2";
_object.remove("key1");
outputMustBe("{\"key2\":\"value2\"}");
}
TEST_F(JsonObject_PrintTo_Tests, RemoveLast) {
_object["key1"] = "value1";
_object["key2"] = "value2";
_object.remove("key2");
outputMustBe("{\"key1\":\"value1\"}");
}
TEST_F(JsonObject_PrintTo_Tests, RemoveUnexistingKey) {
_object["key1"] = "value1";
_object["key2"] = "value2";
_object.remove("key3");
outputMustBe("{\"key1\":\"value1\",\"key2\":\"value2\"}");
}
TEST_F(JsonObject_PrintTo_Tests, ReplaceExistingKey) {
_object["key"] = "value1";
_object["key"] = "value2";
outputMustBe("{\"key\":\"value2\"}");
}
TEST_F(JsonObject_PrintTo_Tests, TwoIntegers) {
_object["a"] = 1;
_object.set("b", 2);
outputMustBe("{\"a\":1,\"b\":2}");
}
TEST_F(JsonObject_PrintTo_Tests, RawJson) {
_object["a"] = RawJson("[1,2]");
_object.set("b", RawJson("[4,5]"));
outputMustBe("{\"a\":[1,2],\"b\":[4,5]}");
}
TEST_F(JsonObject_PrintTo_Tests, TwoDoublesFourDigits) {
_object["a"] = double_with_n_digits(3.14159265358979323846, 4);
_object.set("b", 2.71828182845904523536, 4);
_object.set("c", double_with_n_digits(3.14159265358979323846, 3));
outputMustBe("{\"a\":3.1416,\"b\":2.7183,\"c\":3.142}");
}
TEST_F(JsonObject_PrintTo_Tests, TwoDoubleDefaultDigits) {
_object["a"] = 3.14159265358979323846;
_object.set("b", 2.71828182845904523536);
outputMustBe("{\"a\":3.14,\"b\":2.72}");
}
TEST_F(JsonObject_PrintTo_Tests, TwoNull) {
_object["a"] = static_cast<char *>(0);
_object.set("b", static_cast<char *>(0));
outputMustBe("{\"a\":null,\"b\":null}");
}
TEST_F(JsonObject_PrintTo_Tests, TwoBooleans) {
_object["a"] = true;
_object.set("b", false);
outputMustBe("{\"a\":true,\"b\":false}");
}
TEST_F(JsonObject_PrintTo_Tests, ThreeNestedArrays) {
_object.createNestedArray("a");
_object["b"] = _jsonBuffer.createArray();
_object.set("c", _jsonBuffer.createArray());
outputMustBe("{\"a\":[],\"b\":[],\"c\":[]}");
}
TEST_F(JsonObject_PrintTo_Tests, ThreeNestedObjects) {
_object.createNestedObject("a");
_object["b"] = _jsonBuffer.createObject();
_object.set("c", _jsonBuffer.createObject());
outputMustBe("{\"a\":{},\"b\":{},\"c\":{}}");
check(obj, "{\"key1\":\"value1\",\"key2\":\"value2\"}");
}
SECTION("RemoveFirst") {
obj["key1"] = "value1";
obj["key2"] = "value2";
obj.remove("key1");
check(obj, "{\"key2\":\"value2\"}");
}
SECTION("RemoveLast") {
obj["key1"] = "value1";
obj["key2"] = "value2";
obj.remove("key2");
check(obj, "{\"key1\":\"value1\"}");
}
SECTION("RemoveUnexistingKey") {
obj["key1"] = "value1";
obj["key2"] = "value2";
obj.remove("key3");
check(obj, "{\"key1\":\"value1\",\"key2\":\"value2\"}");
}
SECTION("ReplaceExistingKey") {
obj["key"] = "value1";
obj["key"] = "value2";
check(obj, "{\"key\":\"value2\"}");
}
SECTION("TwoIntegers") {
obj["a"] = 1;
obj.set("b", 2);
check(obj, "{\"a\":1,\"b\":2}");
}
SECTION("RawJson") {
obj["a"] = RawJson("[1,2]");
obj.set("b", RawJson("[4,5]"));
check(obj, "{\"a\":[1,2],\"b\":[4,5]}");
}
SECTION("TwoDoublesFourDigits") {
obj["a"] = double_with_n_digits(3.14159265358979323846, 4);
obj.set("b", 2.71828182845904523536, 4);
obj.set("c", double_with_n_digits(3.14159265358979323846, 3));
check(obj, "{\"a\":3.1416,\"b\":2.7183,\"c\":3.142}");
}
SECTION("TwoDoubleDefaultDigits") {
obj["a"] = 3.14159265358979323846;
obj.set("b", 2.71828182845904523536);
check(obj, "{\"a\":3.14,\"b\":2.72}");
}
SECTION("TwoNull") {
obj["a"] = static_cast<char *>(0);
obj.set("b", static_cast<char *>(0));
check(obj, "{\"a\":null,\"b\":null}");
}
SECTION("TwoBooleans") {
obj["a"] = true;
obj.set("b", false);
check(obj, "{\"a\":true,\"b\":false}");
}
SECTION("ThreeNestedArrays") {
obj.createNestedArray("a");
obj["b"] = _jsonBuffer.createArray();
obj.set("c", _jsonBuffer.createArray());
check(obj, "{\"a\":[],\"b\":[],\"c\":[]}");
}
SECTION("ThreeNestedObjects") {
obj.createNestedObject("a");
obj["b"] = _jsonBuffer.createObject();
obj.set("c", _jsonBuffer.createObject());
check(obj, "{\"a\":{},\"b\":{},\"c\":{}}");
}
}

View File

@ -6,39 +6,39 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
#include <string>
#define TEST_(name) TEST(JsonObject_Remove_Tests, name)
TEST_CASE("JsonObject::remove()") {
DynamicJsonBuffer jb;
TEST_(SizeDecreased_WhenValuesAreRemoved) {
DynamicJsonBuffer _jsonBuffer;
JsonObject& _object = _jsonBuffer.createObject();
_object["hello"] = 1;
SECTION("SizeDecreased_WhenValuesAreRemoved") {
JsonObject& obj = jb.createObject();
obj["hello"] = 1;
_object.remove("hello");
obj.remove("hello");
EXPECT_EQ(0, _object.size());
}
TEST_(SizeUntouched_WhenRemoveIsCalledWithAWrongKey) {
DynamicJsonBuffer _jsonBuffer;
JsonObject& _object = _jsonBuffer.createObject();
_object["hello"] = 1;
_object.remove("world");
EXPECT_EQ(1, _object.size());
}
TEST_(RemoveByIterator) {
DynamicJsonBuffer _jsonBuffer;
JsonObject& _object = _jsonBuffer.parseObject("{\"a\":0,\"b\":1,\"c\":2}");
for (JsonObject::iterator it = _object.begin(); it != _object.end(); ++it) {
if (it->value == 1) _object.remove(it);
REQUIRE(0 == obj.size());
}
char result[64];
_object.printTo(result);
EXPECT_STREQ("{\"a\":0,\"c\":2}", result);
SECTION("SizeUntouched_WhenRemoveIsCalledWithAWrongKey") {
JsonObject& obj = jb.createObject();
obj["hello"] = 1;
obj.remove("world");
REQUIRE(1 == obj.size());
}
SECTION("RemoveByIterator") {
JsonObject& obj = jb.parseObject("{\"a\":0,\"b\":1,\"c\":2}");
for (JsonObject::iterator it = obj.begin(); it != obj.end(); ++it) {
if (it->value == 1) obj.remove(it);
}
std::string result;
obj.printTo(result);
REQUIRE("{\"a\":0,\"c\":2}" == result);
}
}

View File

@ -6,122 +6,113 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
#include <string>
class JsonObject_Set_Tests : public ::testing::Test {
public:
JsonObject_Set_Tests() : _object(_jsonBuffer.createObject()) {}
TEST_CASE("JsonObject::set()") {
DynamicJsonBuffer jb;
JsonObject& _object = jb.createObject();
protected:
DynamicJsonBuffer _jsonBuffer;
JsonObject& _object;
};
SECTION("SizeIncreased_WhenValuesAreAdded") {
_object.set("hello", 42);
REQUIRE(1 == _object.size());
}
#define TEST_(name) TEST_F(JsonObject_Set_Tests, name)
SECTION("SizeUntouched_WhenSameValueIsAdded") {
_object["hello"] = 1;
_object["hello"] = 2;
REQUIRE(1 == _object.size());
}
TEST_(SizeIncreased_WhenValuesAreAdded) {
_object.set("hello", 42);
EXPECT_EQ(1, _object.size());
}
TEST_(SizeUntouched_WhenSameValueIsAdded) {
_object["hello"] = 1;
_object["hello"] = 2;
EXPECT_EQ(1, _object.size());
}
TEST_(StoreInteger) {
_object.set("hello", 123);
EXPECT_EQ(123, _object["hello"].as<int>());
EXPECT_TRUE(_object["hello"].is<int>());
EXPECT_FALSE(_object["hello"].is<double>());
}
TEST_(StoreDouble) {
_object.set("hello", 123.45);
EXPECT_EQ(123.45, _object["hello"].as<double>());
EXPECT_TRUE(_object["hello"].is<double>());
EXPECT_FALSE(_object["hello"].is<long>());
}
TEST_(StoreDoubleWithDigits) {
_object.set("hello", 123.45, 2);
EXPECT_EQ(123.45, _object["hello"].as<double>());
EXPECT_TRUE(_object["hello"].is<double>());
EXPECT_FALSE(_object["hello"].is<long>());
}
TEST_(StoreBoolean) {
_object.set("hello", true);
EXPECT_TRUE(_object["hello"].as<bool>());
EXPECT_TRUE(_object["hello"].is<bool>());
EXPECT_FALSE(_object["hello"].is<long>());
}
TEST_(StoreString) {
_object.set("hello", "h3110");
EXPECT_STREQ("h3110", _object["hello"].as<const char*>());
EXPECT_TRUE(_object["hello"].is<const char*>());
EXPECT_FALSE(_object["hello"].is<long>());
}
TEST_(StoreArray) {
JsonArray& arr = _jsonBuffer.createArray();
_object.set("hello", arr);
EXPECT_EQ(&arr, &_object["hello"].as<JsonArray>());
EXPECT_TRUE(_object["hello"].is<JsonArray&>());
EXPECT_FALSE(_object["hello"].is<JsonObject&>());
}
TEST_(StoreObject) {
JsonObject& obj = _jsonBuffer.createObject();
_object.set("hello", obj);
EXPECT_EQ(&obj, &_object["hello"].as<JsonObject>());
EXPECT_TRUE(_object["hello"].is<JsonObject&>());
EXPECT_FALSE(_object["hello"].is<JsonArray&>());
}
TEST_(StoreArraySubscript) {
JsonArray& arr = _jsonBuffer.createArray();
arr.add(42);
_object.set("a", arr[0]);
EXPECT_EQ(42, _object["a"]);
}
TEST_(StoreObjectSubscript) {
JsonObject& obj = _jsonBuffer.createObject();
obj.set("x", 42);
_object.set("a", obj["x"]);
EXPECT_EQ(42, _object["a"]);
}
TEST_(ShouldReturnTrue_WhenAllocationSucceeds) {
StaticJsonBuffer<JSON_OBJECT_SIZE(1) + 15> jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
bool result = obj.set(std::string("hello"), std::string("world"));
ASSERT_TRUE(result);
}
TEST_(ShouldReturnFalse_WhenAllocationFails) {
StaticJsonBuffer<JSON_OBJECT_SIZE(1) + 10> jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
bool result = obj.set(std::string("hello"), std::string("world"));
ASSERT_FALSE(result);
SECTION("StoreInteger") {
_object.set("hello", 123);
REQUIRE(123 == _object["hello"].as<int>());
REQUIRE(_object["hello"].is<int>());
REQUIRE_FALSE(_object["hello"].is<double>());
}
SECTION("StoreDouble") {
_object.set("hello", 123.45);
REQUIRE(123.45 == _object["hello"].as<double>());
REQUIRE(_object["hello"].is<double>());
REQUIRE_FALSE(_object["hello"].is<long>());
}
SECTION("StoreDoubleWithDigits") {
_object.set("hello", 123.45, 2);
REQUIRE(123.45 == _object["hello"].as<double>());
REQUIRE(_object["hello"].is<double>());
REQUIRE_FALSE(_object["hello"].is<long>());
}
SECTION("StoreBoolean") {
_object.set("hello", true);
REQUIRE(_object["hello"].as<bool>());
REQUIRE(_object["hello"].is<bool>());
REQUIRE_FALSE(_object["hello"].is<long>());
}
SECTION("StoreString") {
_object.set("hello", "h3110");
REQUIRE(std::string("h3110") == _object["hello"].as<const char*>());
REQUIRE(_object["hello"].is<const char*>());
REQUIRE_FALSE(_object["hello"].is<long>());
}
SECTION("StoreArray") {
JsonArray& arr = jb.createArray();
_object.set("hello", arr);
REQUIRE(&arr == &_object["hello"].as<JsonArray>());
REQUIRE(_object["hello"].is<JsonArray&>());
REQUIRE_FALSE(_object["hello"].is<JsonObject&>());
}
SECTION("StoreObject") {
JsonObject& obj = jb.createObject();
_object.set("hello", obj);
REQUIRE(&obj == &_object["hello"].as<JsonObject>());
REQUIRE(_object["hello"].is<JsonObject&>());
REQUIRE_FALSE(_object["hello"].is<JsonArray&>());
}
SECTION("StoreArraySubscript") {
JsonArray& arr = jb.createArray();
arr.add(42);
_object.set("a", arr[0]);
REQUIRE(42 == _object["a"]);
}
SECTION("StoreObjectSubscript") {
JsonObject& obj = jb.createObject();
obj.set("x", 42);
_object.set("a", obj["x"]);
REQUIRE(42 == _object["a"]);
}
SECTION("ShouldReturnTrue_WhenAllocationSucceeds") {
StaticJsonBuffer<JSON_OBJECT_SIZE(1) + 15> jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
REQUIRE(true == obj.set(std::string("hello"), std::string("world")));
}
SECTION("ShouldReturnFalse_WhenAllocationFails") {
StaticJsonBuffer<JSON_OBJECT_SIZE(1) + 10> jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
REQUIRE(false == obj.set(std::string("hello"), std::string("world")));
}
}

View File

@ -6,132 +6,127 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
class JsonObject_Subscript_Tests : public ::testing::Test {
public:
JsonObject_Subscript_Tests() : _object(_jsonBuffer.createObject()) {}
protected:
TEST_CASE("JsonObject::operator[]") {
DynamicJsonBuffer _jsonBuffer;
JsonObject& _object;
};
JsonObject& _object = _jsonBuffer.createObject();
#define TEST_(name) TEST_F(JsonObject_Subscript_Tests, name)
SECTION("SizeIncreased_WhenValuesAreAdded") {
_object["hello"] = 1;
REQUIRE(1 == _object.size());
}
TEST_(SizeIncreased_WhenValuesAreAdded) {
_object["hello"] = 1;
EXPECT_EQ(1, _object.size());
}
TEST_(SizeUntouched_WhenSameValueIsAdded) {
_object["hello"] = 1;
_object["hello"] = 2;
EXPECT_EQ(1, _object.size());
}
TEST_(StoreInteger) {
_object["hello"] = 123;
EXPECT_EQ(123, _object["hello"].as<int>());
EXPECT_TRUE(_object["hello"].is<int>());
EXPECT_FALSE(_object["hello"].is<double>());
}
TEST_(StoreVolatileInteger) { // issue #415
volatile int i = 123;
_object["hello"] = i;
EXPECT_EQ(123, _object["hello"].as<int>());
EXPECT_TRUE(_object["hello"].is<int>());
EXPECT_FALSE(_object["hello"].is<double>());
}
TEST_(StoreDouble) {
_object["hello"] = 123.45;
EXPECT_TRUE(_object["hello"].is<double>());
EXPECT_FALSE(_object["hello"].is<long>());
EXPECT_EQ(123.45, _object["hello"].as<double>());
}
TEST_(StoreDoubleWithDigits) {
_object["hello"].set(123.45, 2);
EXPECT_TRUE(_object["hello"].is<double>());
EXPECT_FALSE(_object["hello"].is<long>());
EXPECT_EQ(123.45, _object["hello"].as<double>());
}
TEST_(StoreBoolean) {
_object["hello"] = true;
EXPECT_TRUE(_object["hello"].is<bool>());
EXPECT_FALSE(_object["hello"].is<long>());
EXPECT_TRUE(_object["hello"].as<bool>());
}
TEST_(StoreString) {
_object["hello"] = "h3110";
EXPECT_TRUE(_object["hello"].is<const char*>());
EXPECT_FALSE(_object["hello"].is<long>());
EXPECT_STREQ("h3110", _object["hello"].as<const char*>());
EXPECT_STREQ("h3110", _object["hello"].as<char*>()); // <- short hand
}
TEST_(StoreArray) {
JsonArray& arr = _jsonBuffer.createArray();
_object["hello"] = arr;
EXPECT_EQ(&arr, &_object["hello"].as<JsonArray&>());
EXPECT_EQ(&arr, &_object["hello"].as<JsonArray>()); // <- short hand
EXPECT_EQ(&arr, &_object["hello"].as<const JsonArray&>());
EXPECT_EQ(&arr, &_object["hello"].as<const JsonArray>()); // <- short hand
EXPECT_TRUE(_object["hello"].is<JsonArray&>());
EXPECT_TRUE(_object["hello"].is<JsonArray>());
EXPECT_TRUE(_object["hello"].is<const JsonArray&>());
EXPECT_TRUE(_object["hello"].is<const JsonArray>());
EXPECT_FALSE(_object["hello"].is<JsonObject&>());
}
TEST_(StoreObject) {
JsonObject& obj = _jsonBuffer.createObject();
_object["hello"] = obj;
EXPECT_EQ(&obj, &_object["hello"].as<JsonObject&>());
EXPECT_EQ(&obj, &_object["hello"].as<JsonObject>()); // <- short hand
EXPECT_EQ(&obj, &_object["hello"].as<const JsonObject&>());
EXPECT_EQ(&obj, &_object["hello"].as<const JsonObject>()); // <- short hand
EXPECT_TRUE(_object["hello"].is<JsonObject&>());
EXPECT_TRUE(_object["hello"].is<JsonObject>());
EXPECT_TRUE(_object["hello"].is<const JsonObject&>());
EXPECT_TRUE(_object["hello"].is<const JsonObject>());
EXPECT_FALSE(_object["hello"].is<JsonArray&>());
}
TEST_(StoreArraySubscript) {
JsonArray& arr = _jsonBuffer.createArray();
arr.add(42);
_object["a"] = arr[0];
EXPECT_EQ(42, _object["a"]);
}
TEST_(StoreObjectSubscript) {
JsonObject& obj = _jsonBuffer.createObject();
obj.set("x", 42);
_object["a"] = obj["x"];
EXPECT_EQ(42, _object["a"]);
}
TEST_(KeyAsCharArray) { // issue #423
char key[] = "hello";
_object[key] = 42;
EXPECT_EQ(42, _object[key]);
SECTION("SizeUntouched_WhenSameValueIsAdded") {
_object["hello"] = 1;
_object["hello"] = 2;
REQUIRE(1 == _object.size());
}
SECTION("StoreInteger") {
_object["hello"] = 123;
REQUIRE(123 == _object["hello"].as<int>());
REQUIRE(true == _object["hello"].is<int>());
REQUIRE(false == _object["hello"].is<double>());
}
SECTION("StoreVolatileInteger") { // issue #415
volatile int i = 123;
_object["hello"] = i;
REQUIRE(123 == _object["hello"].as<int>());
REQUIRE(true == _object["hello"].is<int>());
REQUIRE(false == _object["hello"].is<double>());
}
SECTION("StoreDouble") {
_object["hello"] = 123.45;
REQUIRE(true == _object["hello"].is<double>());
REQUIRE(false == _object["hello"].is<long>());
REQUIRE(123.45 == _object["hello"].as<double>());
}
SECTION("StoreDoubleWithDigits") {
_object["hello"].set(123.45, 2);
REQUIRE(true == _object["hello"].is<double>());
REQUIRE(false == _object["hello"].is<long>());
REQUIRE(123.45 == _object["hello"].as<double>());
}
SECTION("StoreBoolean") {
_object["hello"] = true;
REQUIRE(true == _object["hello"].is<bool>());
REQUIRE(false == _object["hello"].is<long>());
REQUIRE(true == _object["hello"].as<bool>());
}
SECTION("StoreString") {
_object["hello"] = "h3110";
REQUIRE(true == _object["hello"].is<const char*>());
REQUIRE(false == _object["hello"].is<long>());
REQUIRE(std::string("h3110") == _object["hello"].as<const char*>());
REQUIRE(std::string("h3110") ==
_object["hello"].as<char*>()); // <- short hand
}
SECTION("StoreArray") {
JsonArray& arr = _jsonBuffer.createArray();
_object["hello"] = arr;
REQUIRE(&arr == &_object["hello"].as<JsonArray&>());
REQUIRE(&arr == &_object["hello"].as<JsonArray>()); // <- short hand
REQUIRE(&arr == &_object["hello"].as<const JsonArray&>());
REQUIRE(&arr == &_object["hello"].as<const JsonArray>()); // <- short hand
REQUIRE(true == _object["hello"].is<JsonArray&>());
REQUIRE(true == _object["hello"].is<JsonArray>());
REQUIRE(true == _object["hello"].is<const JsonArray&>());
REQUIRE(true == _object["hello"].is<const JsonArray>());
REQUIRE(false == _object["hello"].is<JsonObject&>());
}
SECTION("StoreObject") {
JsonObject& obj = _jsonBuffer.createObject();
_object["hello"] = obj;
REQUIRE(&obj == &_object["hello"].as<JsonObject&>());
REQUIRE(&obj == &_object["hello"].as<JsonObject>()); // <- short hand
REQUIRE(&obj == &_object["hello"].as<const JsonObject&>());
REQUIRE(&obj == &_object["hello"].as<const JsonObject>()); // <- short hand
REQUIRE(true == _object["hello"].is<JsonObject&>());
REQUIRE(true == _object["hello"].is<JsonObject>());
REQUIRE(true == _object["hello"].is<const JsonObject&>());
REQUIRE(true == _object["hello"].is<const JsonObject>());
REQUIRE(false == _object["hello"].is<JsonArray&>());
}
SECTION("StoreArraySubscript") {
JsonArray& arr = _jsonBuffer.createArray();
arr.add(42);
_object["a"] = arr[0];
REQUIRE(42 == _object["a"]);
}
SECTION("StoreObjectSubscript") {
JsonObject& obj = _jsonBuffer.createObject();
obj.set("x", 42);
_object["a"] = obj["x"];
REQUIRE(42 == _object["a"]);
}
SECTION("KeyAsCharArray") { // issue #423
char key[] = "hello";
_object[key] = 42;
REQUIRE(42 == _object[key]);
}
}

View File

@ -17,5 +17,5 @@ add_executable(JsonVariantTests
undefined.cpp
)
target_link_libraries(JsonVariantTests gtest)
target_link_libraries(JsonVariantTests catch)
add_test(JsonVariant JsonVariantTests)

View File

@ -6,229 +6,230 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <stdint.h>
#include <catch.hpp>
static const char* null = 0;
TEST(JsonVariant_As_Tests, DoubleAsBool) {
JsonVariant variant = 4.2;
ASSERT_TRUE(variant.as<bool>());
}
TEST_CASE("JsonVariant::as()") {
SECTION("DoubleAsBool") {
JsonVariant variant = 4.2;
REQUIRE(variant.as<bool>());
}
TEST(JsonVariant_As_Tests, DoubleAsCstr) {
JsonVariant variant = 4.2;
ASSERT_FALSE(variant.as<const char*>());
}
SECTION("DoubleAsCstr") {
JsonVariant variant = 4.2;
REQUIRE_FALSE(variant.as<const char*>());
}
TEST(JsonVariant_As_Tests, DoubleAsString) {
JsonVariant variant = 4.2;
ASSERT_EQ(std::string("4.20"), variant.as<std::string>());
}
SECTION("DoubleAsString") {
JsonVariant variant = 4.2;
REQUIRE(std::string("4.20") == variant.as<std::string>());
}
TEST(JsonVariant_As_Tests, DoubleAsLong) {
JsonVariant variant = 4.2;
ASSERT_EQ(4L, variant.as<long>());
}
SECTION("DoubleAsLong") {
JsonVariant variant = 4.2;
REQUIRE(4L == variant.as<long>());
}
TEST(JsonVariant_As_Tests, DoubleAsUnsigned) {
JsonVariant variant = 4.2;
ASSERT_EQ(4U, variant.as<unsigned>());
}
SECTION("DoubleAsUnsigned") {
JsonVariant variant = 4.2;
REQUIRE(4U == variant.as<unsigned>());
}
TEST(JsonVariant_As_Tests, DoubleZeroAsBool) {
JsonVariant variant = 0.0;
ASSERT_FALSE(variant.as<bool>());
}
SECTION("DoubleZeroAsBool") {
JsonVariant variant = 0.0;
REQUIRE_FALSE(variant.as<bool>());
}
TEST(JsonVariant_As_Tests, DoubleZeroAsLong) {
JsonVariant variant = 0.0;
ASSERT_EQ(0L, variant.as<long>());
}
SECTION("DoubleZeroAsLong") {
JsonVariant variant = 0.0;
REQUIRE(0L == variant.as<long>());
}
TEST(JsonVariant_As_Tests, FalseAsBool) {
JsonVariant variant = false;
ASSERT_FALSE(variant.as<bool>());
}
SECTION("FalseAsBool") {
JsonVariant variant = false;
REQUIRE_FALSE(variant.as<bool>());
}
TEST(JsonVariant_As_Tests, FalseAsDouble) {
JsonVariant variant = false;
ASSERT_EQ(0.0, variant.as<double>());
}
SECTION("FalseAsDouble") {
JsonVariant variant = false;
REQUIRE(0.0 == variant.as<double>());
}
TEST(JsonVariant_As_Tests, FalseAsLong) {
JsonVariant variant = false;
ASSERT_EQ(0L, variant.as<long>());
}
SECTION("FalseAsLong") {
JsonVariant variant = false;
REQUIRE(0L == variant.as<long>());
}
TEST(JsonVariant_As_Tests, FalseAsString) {
JsonVariant variant = false;
ASSERT_EQ(std::string("false"), variant.as<std::string>());
}
SECTION("FalseAsString") {
JsonVariant variant = false;
REQUIRE(std::string("false") == variant.as<std::string>());
}
TEST(JsonVariant_As_Tests, TrueAsBool) {
JsonVariant variant = true;
ASSERT_TRUE(variant.as<bool>());
}
SECTION("TrueAsBool") {
JsonVariant variant = true;
REQUIRE(variant.as<bool>());
}
TEST(JsonVariant_As_Tests, TrueAsDouble) {
JsonVariant variant = true;
ASSERT_EQ(1.0, variant.as<double>());
}
SECTION("TrueAsDouble") {
JsonVariant variant = true;
REQUIRE(1.0 == variant.as<double>());
}
TEST(JsonVariant_As_Tests, TrueAsLong) {
JsonVariant variant = true;
ASSERT_EQ(1L, variant.as<long>());
}
SECTION("TrueAsLong") {
JsonVariant variant = true;
REQUIRE(1L == variant.as<long>());
}
TEST(JsonVariant_As_Tests, TrueAsString) {
JsonVariant variant = true;
ASSERT_EQ(std::string("true"), variant.as<std::string>());
}
SECTION("TrueAsString") {
JsonVariant variant = true;
REQUIRE(std::string("true") == variant.as<std::string>());
}
TEST(JsonVariant_As_Tests, LongAsBool) {
JsonVariant variant = 42L;
ASSERT_TRUE(variant.as<bool>());
}
SECTION("LongAsBool") {
JsonVariant variant = 42L;
REQUIRE(variant.as<bool>());
}
TEST(JsonVariant_As_Tests, LongZeroAsBool) {
JsonVariant variant = 0L;
ASSERT_FALSE(variant.as<bool>());
}
SECTION("LongZeroAsBool") {
JsonVariant variant = 0L;
REQUIRE_FALSE(variant.as<bool>());
}
TEST(JsonVariant_As_Tests, PositiveLongAsDouble) {
JsonVariant variant = 42L;
ASSERT_EQ(42.0, variant.as<double>());
}
SECTION("PositiveLongAsDouble") {
JsonVariant variant = 42L;
REQUIRE(42.0 == variant.as<double>());
}
TEST(JsonVariant_As_Tests, NegativeLongAsDouble) {
JsonVariant variant = -42L;
ASSERT_EQ(-42.0, variant.as<double>());
}
SECTION("NegativeLongAsDouble") {
JsonVariant variant = -42L;
REQUIRE(-42.0 == variant.as<double>());
}
TEST(JsonVariant_As_Tests, LongAsString) {
JsonVariant variant = 42L;
ASSERT_EQ(std::string("42"), variant.as<std::string>());
}
SECTION("LongAsString") {
JsonVariant variant = 42L;
REQUIRE(std::string("42") == variant.as<std::string>());
}
TEST(JsonVariant_As_Tests, LongZeroAsDouble) {
JsonVariant variant = 0L;
ASSERT_EQ(0.0, variant.as<double>());
}
SECTION("LongZeroAsDouble") {
JsonVariant variant = 0L;
REQUIRE(0.0 == variant.as<double>());
}
TEST(JsonVariant_As_Tests, NullAsBool) {
JsonVariant variant = null;
ASSERT_FALSE(variant.as<bool>());
}
SECTION("NullAsBool") {
JsonVariant variant = null;
REQUIRE_FALSE(variant.as<bool>());
}
TEST(JsonVariant_As_Tests, NullAsDouble) {
JsonVariant variant = null;
ASSERT_EQ(0.0, variant.as<double>());
}
SECTION("NullAsDouble") {
JsonVariant variant = null;
REQUIRE(0.0 == variant.as<double>());
}
TEST(JsonVariant_As_Tests, NullAsLong) {
JsonVariant variant = null;
ASSERT_EQ(0L, variant.as<long>());
}
SECTION("NullAsLong") {
JsonVariant variant = null;
REQUIRE(0L == variant.as<long>());
}
TEST(JsonVariant_As_Tests, NullAsString) {
JsonVariant variant = null;
ASSERT_EQ(std::string("null"), variant.as<std::string>());
}
SECTION("NullAsString") {
JsonVariant variant = null;
REQUIRE(std::string("null") == variant.as<std::string>());
}
TEST(JsonVariant_As_Tests, NumberStringAsBool) {
JsonVariant variant = "42";
ASSERT_TRUE(variant.as<bool>());
}
SECTION("NumberStringAsBool") {
JsonVariant variant = "42";
REQUIRE(variant.as<bool>());
}
TEST(JsonVariant_As_Tests, NumberStringAsLong) {
JsonVariant variant = "42";
ASSERT_EQ(42L, variant.as<long>());
}
SECTION("NumberStringAsLong") {
JsonVariant variant = "42";
REQUIRE(42L == variant.as<long>());
}
#if ARDUINOJSON_USE_LONG_LONG || ARDUINOJSON_USE_INT64
TEST(JsonVariant_As_Tests, NumberStringAsInt64Negative) {
JsonVariant variant = "-9223372036854775808";
ASSERT_EQ(-9223372036854775807 - 1, variant.as<long long>());
}
SECTION("NumberStringAsInt64Negative") {
JsonVariant variant = "-9223372036854775808";
REQUIRE(-9223372036854775807 - 1 == variant.as<long long>());
}
TEST(JsonVariant_As_Tests, NumberStringAsInt64Positive) {
JsonVariant variant = "9223372036854775807";
ASSERT_EQ(9223372036854775807, variant.as<long long>());
}
SECTION("NumberStringAsInt64Positive") {
JsonVariant variant = "9223372036854775807";
REQUIRE(9223372036854775807 == variant.as<long long>());
}
#endif
TEST(JsonVariant_As_Tests, RandomStringAsBool) {
JsonVariant variant = "hello";
ASSERT_FALSE(variant.as<bool>());
}
TEST(JsonVariant_As_Tests, RandomStringAsLong) {
JsonVariant variant = "hello";
ASSERT_EQ(0L, variant.as<long>());
}
TEST(JsonVariant_As_Tests, RandomStringAsConstCharPtr) {
JsonVariant variant = "hello";
ASSERT_STREQ("hello", variant.as<const char*>());
}
TEST(JsonVariant_As_Tests, RandomStringAsCharPtr) {
JsonVariant variant = "hello";
ASSERT_STREQ("hello", variant.as<char*>());
}
TEST(JsonVariant_As_Tests, RandomStringAsString) {
JsonVariant variant = "hello";
ASSERT_EQ(std::string("hello"), variant.as<std::string>());
}
TEST(JsonVariant_As_Tests, TrueStringAsBool) {
JsonVariant variant = "true";
ASSERT_TRUE(variant.as<bool>());
}
TEST(JsonVariant_As_Tests, TrueStringAsLong) {
JsonVariant variant = "true";
ASSERT_EQ(1L, variant.as<long>());
}
TEST(JsonVariant_As_Tests, ObjectAsString) {
DynamicJsonBuffer buffer;
JsonObject& obj = buffer.createObject();
obj["key"] = "value";
JsonVariant variant = obj;
ASSERT_EQ(std::string("{\"key\":\"value\"}"), variant.as<std::string>());
}
TEST(JsonVariant_As_Tests, ArrayAsString) {
DynamicJsonBuffer buffer;
JsonArray& arr = buffer.createArray();
arr.add(4);
arr.add(2);
JsonVariant variant = arr;
ASSERT_EQ(std::string("[4,2]"), variant.as<std::string>());
}
TEST(JsonVariant_As_Tests, ArrayAsJsonArray) {
DynamicJsonBuffer buffer;
JsonArray& arr = buffer.createArray();
JsonVariant variant = arr;
ASSERT_EQ(&arr, &variant.as<JsonArray&>());
ASSERT_EQ(&arr, &variant.as<JsonArray>()); // <- shorthand
}
TEST(JsonVariant_As_Tests, ObjectAsJsonObject) {
DynamicJsonBuffer buffer;
JsonObject& arr = buffer.createObject();
JsonVariant variant = arr;
ASSERT_EQ(&arr, &variant.as<JsonObject&>());
ASSERT_EQ(&arr, &variant.as<JsonObject>()); // <- shorthand
SECTION("RandomStringAsBool") {
JsonVariant variant = "hello";
REQUIRE_FALSE(variant.as<bool>());
}
SECTION("RandomStringAsLong") {
JsonVariant variant = "hello";
REQUIRE(0L == variant.as<long>());
}
SECTION("RandomStringAsConstCharPtr") {
JsonVariant variant = "hello";
REQUIRE(std::string("hello") == variant.as<const char*>());
}
SECTION("RandomStringAsCharPtr") {
JsonVariant variant = "hello";
REQUIRE(std::string("hello") == variant.as<char*>());
}
SECTION("RandomStringAsString") {
JsonVariant variant = "hello";
REQUIRE(std::string("hello") == variant.as<std::string>());
}
SECTION("TrueStringAsBool") {
JsonVariant variant = "true";
REQUIRE(variant.as<bool>());
}
SECTION("TrueStringAsLong") {
JsonVariant variant = "true";
REQUIRE(1L == variant.as<long>());
}
SECTION("ObjectAsString") {
DynamicJsonBuffer buffer;
JsonObject& obj = buffer.createObject();
obj["key"] = "value";
JsonVariant variant = obj;
REQUIRE(std::string("{\"key\":\"value\"}") == variant.as<std::string>());
}
SECTION("ArrayAsString") {
DynamicJsonBuffer buffer;
JsonArray& arr = buffer.createArray();
arr.add(4);
arr.add(2);
JsonVariant variant = arr;
REQUIRE(std::string("[4,2]") == variant.as<std::string>());
}
SECTION("ArrayAsJsonArray") {
DynamicJsonBuffer buffer;
JsonArray& arr = buffer.createArray();
JsonVariant variant = arr;
REQUIRE(&arr == &variant.as<JsonArray&>());
REQUIRE(&arr == &variant.as<JsonArray>()); // <- shorthand
}
SECTION("ObjectAsJsonObject") {
DynamicJsonBuffer buffer;
JsonObject& arr = buffer.createObject();
JsonVariant variant = arr;
REQUIRE(&arr == &variant.as<JsonObject&>());
REQUIRE(&arr == &variant.as<JsonObject>()); // <- shorthand
}
}

View File

@ -6,223 +6,230 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
class JsonVariant_Comparison_Tests : public ::testing::Test {
protected:
template <typename T>
void testValue(T low, T mid, T high) {
setValueTo(mid);
mustBeEqualTo(mid);
mustBeGreaterThan(low);
mustBeLessThan(high);
template <typename T>
void checkEquals(JsonVariant a, T b) {
REQUIRE(b == a);
REQUIRE(a == b);
REQUIRE(b <= a);
REQUIRE(a <= b);
REQUIRE(b >= a);
REQUIRE(a >= b);
REQUIRE_FALSE(b != a);
REQUIRE_FALSE(a != b);
REQUIRE_FALSE(b > a);
REQUIRE_FALSE(a > b);
REQUIRE_FALSE(b < a);
REQUIRE_FALSE(a < b);
}
template <typename T>
void checkGreater(JsonVariant a, T b) {
REQUIRE(a > b);
REQUIRE(b < a);
REQUIRE(a != b);
REQUIRE(b != a);
REQUIRE_FALSE(a < b);
REQUIRE_FALSE(b > a);
REQUIRE_FALSE(a == b);
REQUIRE_FALSE(b == a);
}
template <typename T>
void checkLower(JsonVariant a, T b) {
REQUIRE(a < b);
REQUIRE(b > a);
REQUIRE(a != b);
REQUIRE(b != a);
REQUIRE_FALSE(a > b);
REQUIRE_FALSE(b < a);
REQUIRE_FALSE(a == b);
REQUIRE_FALSE(b == a);
}
template <typename T>
void checkComparisons(T low, T mid, T high) {
checkEquals(mid, mid);
checkGreater(mid, low);
checkLower(mid, high);
}
TEST_CASE("JsonVariant comparisons") {
SECTION("Double") {
checkComparisons<double>(123.44, 123.45, 123.46);
}
private:
template <typename T>
void setValueTo(T expected) {
actual = expected;
SECTION("Float") {
checkComparisons<float>(123.44f, 123.45f, 123.46f);
}
template <typename T>
void mustBeEqualTo(T expected) {
EXPECT_EQ(expected, actual); // operator==
EXPECT_EQ(actual, expected); // operator==
EXPECT_LE(expected, actual); // operator<=
EXPECT_LE(actual, expected); // operator<=
EXPECT_GE(expected, actual); // operator>=
EXPECT_GE(actual, expected); // operator>=
SECTION("SChar") {
checkComparisons<signed char>(122, 123, 124);
}
template <typename T>
void mustBeGreaterThan(T expected) {
EXPECT_GT(actual, expected); // operator>
EXPECT_LT(expected, actual); // operator<
EXPECT_NE(actual, expected); // operator!=
EXPECT_NE(expected, actual); // operator!=
SECTION("SInt") {
checkComparisons<signed int>(122, 123, 124);
}
template <typename T>
void mustBeLessThan(T expected) {
EXPECT_LT(actual, expected); // operator<
EXPECT_GT(expected, actual); // operator<
EXPECT_NE(actual, expected); // operator!=
EXPECT_NE(expected, actual); // operator!=
SECTION("SLong") {
checkComparisons<signed long>(122L, 123L, 124L);
}
JsonVariant actual;
};
SECTION("SShort") {
checkComparisons<signed short>(122, 123, 124);
}
TEST_F(JsonVariant_Comparison_Tests, Double) {
testValue<double>(123.44, 123.45, 123.46);
}
SECTION("UChar") {
checkComparisons<unsigned char>(122, 123, 124);
}
TEST_F(JsonVariant_Comparison_Tests, Float) {
testValue<float>(123.44f, 123.45f, 123.46f);
}
SECTION("UInt") {
checkComparisons<unsigned int>(122, 123, 124);
}
TEST_F(JsonVariant_Comparison_Tests, SChar) {
testValue<signed char>(122, 123, 124);
}
SECTION("ULong") {
checkComparisons<unsigned long>(122L, 123L, 124L);
}
TEST_F(JsonVariant_Comparison_Tests, SInt) {
testValue<signed int>(122, 123, 124);
}
SECTION("UShort") {
checkComparisons<unsigned short>(122, 123, 124);
}
TEST_F(JsonVariant_Comparison_Tests, SLong) {
testValue<signed long>(122L, 123L, 124L);
}
SECTION("StringLiteral") {
DynamicJsonBuffer jsonBuffer;
JsonVariant variant = jsonBuffer.parse("\"hello\"");
TEST_F(JsonVariant_Comparison_Tests, SShort) {
testValue<signed short>(122, 123, 124);
}
REQUIRE(variant == "hello");
REQUIRE_FALSE(variant != "hello");
TEST_F(JsonVariant_Comparison_Tests, UChar) {
testValue<unsigned char>(122, 123, 124);
}
REQUIRE(variant != "world");
REQUIRE_FALSE(variant == "world");
TEST_F(JsonVariant_Comparison_Tests, UInt) {
testValue<unsigned int>(122, 123, 124);
}
REQUIRE("hello" == variant);
REQUIRE_FALSE("hello" != variant);
TEST_F(JsonVariant_Comparison_Tests, ULong) {
testValue<unsigned long>(122L, 123L, 124L);
}
REQUIRE("world" != variant);
REQUIRE_FALSE("world" == variant);
}
TEST_F(JsonVariant_Comparison_Tests, UShort) {
testValue<unsigned short>(122, 123, 124);
}
SECTION("String") {
DynamicJsonBuffer jsonBuffer;
JsonVariant variant = jsonBuffer.parse("\"hello\"");
TEST_F(JsonVariant_Comparison_Tests, StringLiteral) {
DynamicJsonBuffer jsonBuffer;
JsonVariant variant = jsonBuffer.parse("\"hello\"");
REQUIRE(variant == std::string("hello"));
REQUIRE_FALSE(variant != std::string("hello"));
ASSERT_TRUE(variant == "hello");
ASSERT_FALSE(variant != "hello");
REQUIRE(variant != std::string("world"));
REQUIRE_FALSE(variant == std::string("world"));
ASSERT_TRUE(variant != "world");
ASSERT_FALSE(variant == "world");
REQUIRE(std::string("hello") == variant);
REQUIRE_FALSE(std::string("hello") != variant);
ASSERT_TRUE("hello" == variant);
ASSERT_FALSE("hello" != variant);
REQUIRE(std::string("world") != variant);
REQUIRE_FALSE(std::string("world") == variant);
}
ASSERT_TRUE("world" != variant);
ASSERT_FALSE("world" == variant);
}
SECTION("IntegerInVariant") {
JsonVariant variant1 = 42;
JsonVariant variant2 = 42;
JsonVariant variant3 = 666;
TEST_F(JsonVariant_Comparison_Tests, String) {
DynamicJsonBuffer jsonBuffer;
JsonVariant variant = jsonBuffer.parse("\"hello\"");
REQUIRE(variant1 == variant2);
REQUIRE_FALSE(variant1 != variant2);
ASSERT_TRUE(variant == std::string("hello"));
ASSERT_FALSE(variant != std::string("hello"));
REQUIRE(variant1 != variant3);
REQUIRE_FALSE(variant1 == variant3);
}
ASSERT_TRUE(variant != std::string("world"));
ASSERT_FALSE(variant == std::string("world"));
SECTION("StringInVariant") {
JsonVariant variant1 = "0hello" + 1; // make sure they have
JsonVariant variant2 = "1hello" + 1; // different addresses
JsonVariant variant3 = "world";
ASSERT_TRUE(std::string("hello") == variant);
ASSERT_FALSE(std::string("hello") != variant);
REQUIRE(variant1 == variant2);
REQUIRE_FALSE(variant1 != variant2);
ASSERT_TRUE(std::string("world") != variant);
ASSERT_FALSE(std::string("world") == variant);
}
REQUIRE(variant1 != variant3);
REQUIRE_FALSE(variant1 == variant3);
}
TEST_F(JsonVariant_Comparison_Tests, IntegerInVariant) {
JsonVariant variant1 = 42;
JsonVariant variant2 = 42;
JsonVariant variant3 = 666;
SECTION("DoubleInVariant") {
JsonVariant variant1 = 42.0;
JsonVariant variant2 = 42.0;
JsonVariant variant3 = 666.0;
ASSERT_TRUE(variant1 == variant2);
ASSERT_FALSE(variant1 != variant2);
REQUIRE(variant1 == variant2);
REQUIRE_FALSE(variant1 != variant2);
ASSERT_TRUE(variant1 != variant3);
ASSERT_FALSE(variant1 == variant3);
}
REQUIRE(variant1 != variant3);
REQUIRE_FALSE(variant1 == variant3);
}
TEST_F(JsonVariant_Comparison_Tests, StringInVariant) {
JsonVariant variant1 = "0hello" + 1; // make sure they have
JsonVariant variant2 = "1hello" + 1; // different addresses
JsonVariant variant3 = "world";
SECTION("BoolInVariant") {
JsonVariant variant1 = true;
JsonVariant variant2 = true;
JsonVariant variant3 = false;
ASSERT_TRUE(variant1 == variant2);
ASSERT_FALSE(variant1 != variant2);
REQUIRE(variant1 == variant2);
REQUIRE_FALSE(variant1 != variant2);
ASSERT_TRUE(variant1 != variant3);
ASSERT_FALSE(variant1 == variant3);
}
REQUIRE(variant1 != variant3);
REQUIRE_FALSE(variant1 == variant3);
}
TEST_F(JsonVariant_Comparison_Tests, DoubleInVariant) {
JsonVariant variant1 = 42.0;
JsonVariant variant2 = 42.0;
JsonVariant variant3 = 666.0;
SECTION("ArrayInVariant") {
DynamicJsonBuffer jsonBuffer;
JsonArray& array1 = jsonBuffer.createArray();
JsonArray& array2 = jsonBuffer.createArray();
ASSERT_TRUE(variant1 == variant2);
ASSERT_FALSE(variant1 != variant2);
JsonVariant variant1 = array1;
JsonVariant variant2 = array1;
JsonVariant variant3 = array2;
ASSERT_TRUE(variant1 != variant3);
ASSERT_FALSE(variant1 == variant3);
}
REQUIRE(variant1 == variant2);
REQUIRE_FALSE(variant1 != variant2);
TEST_F(JsonVariant_Comparison_Tests, BoolInVariant) {
JsonVariant variant1 = true;
JsonVariant variant2 = true;
JsonVariant variant3 = false;
REQUIRE(variant1 != variant3);
REQUIRE_FALSE(variant1 == variant3);
}
ASSERT_TRUE(variant1 == variant2);
ASSERT_FALSE(variant1 != variant2);
SECTION("ObjectInVariant") {
DynamicJsonBuffer jsonBuffer;
JsonObject& obj1 = jsonBuffer.createObject();
JsonObject& obj2 = jsonBuffer.createObject();
ASSERT_TRUE(variant1 != variant3);
ASSERT_FALSE(variant1 == variant3);
}
JsonVariant variant1 = obj1;
JsonVariant variant2 = obj1;
JsonVariant variant3 = obj2;
TEST_F(JsonVariant_Comparison_Tests, ArrayInVariant) {
DynamicJsonBuffer jsonBuffer;
JsonArray& array1 = jsonBuffer.createArray();
JsonArray& array2 = jsonBuffer.createArray();
REQUIRE(variant1 == variant2);
REQUIRE_FALSE(variant1 != variant2);
JsonVariant variant1 = array1;
JsonVariant variant2 = array1;
JsonVariant variant3 = array2;
REQUIRE(variant1 != variant3);
REQUIRE_FALSE(variant1 == variant3);
}
ASSERT_TRUE(variant1 == variant2);
ASSERT_FALSE(variant1 != variant2);
SECTION("VariantsOfDifferentTypes") {
DynamicJsonBuffer jsonBuffer;
JsonVariant variants[] = {
true,
42,
666.667,
"hello",
jsonBuffer.createArray(),
jsonBuffer.createObject(),
};
size_t n = sizeof(variants) / sizeof(variants[0]);
ASSERT_TRUE(variant1 != variant3);
ASSERT_FALSE(variant1 == variant3);
}
TEST_F(JsonVariant_Comparison_Tests, ObjectInVariant) {
DynamicJsonBuffer jsonBuffer;
JsonObject& obj1 = jsonBuffer.createObject();
JsonObject& obj2 = jsonBuffer.createObject();
JsonVariant variant1 = obj1;
JsonVariant variant2 = obj1;
JsonVariant variant3 = obj2;
ASSERT_TRUE(variant1 == variant2);
ASSERT_FALSE(variant1 != variant2);
ASSERT_TRUE(variant1 != variant3);
ASSERT_FALSE(variant1 == variant3);
}
TEST_F(JsonVariant_Comparison_Tests, VariantsOfDifferentTypes) {
DynamicJsonBuffer jsonBuffer;
JsonVariant variants[] = {
true,
42,
666.667,
"hello",
jsonBuffer.createArray(),
jsonBuffer.createObject(),
};
size_t n = sizeof(variants) / sizeof(variants[0]);
for (size_t i = 0; i < n; i++) {
for (size_t j = i + 1; j < n; j++) {
ASSERT_TRUE(variants[i] != variants[j]);
ASSERT_FALSE(variants[i] == variants[j]);
for (size_t i = 0; i < n; i++) {
for (size_t j = i + 1; j < n; j++) {
REQUIRE(variants[i] != variants[j]);
REQUIRE_FALSE(variants[i] == variants[j]);
}
}
}
}

View File

@ -6,63 +6,62 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
class JsonVariant_Copy_Tests : public ::testing::Test {
protected:
TEST_CASE("JsonVariant copy") {
DynamicJsonBuffer _jsonBuffer;
JsonVariant _variant1;
JsonVariant _variant2;
};
TEST_F(JsonVariant_Copy_Tests, IntegersAreCopiedByValue) {
_variant1 = 123;
_variant2 = _variant1;
_variant1 = 456;
SECTION("IntegersAreCopiedByValue") {
_variant1 = 123;
_variant2 = _variant1;
_variant1 = 456;
EXPECT_EQ(123, _variant2.as<int>());
}
TEST_F(JsonVariant_Copy_Tests, DoublesAreCopiedByValue) {
_variant1 = 123.45;
_variant2 = _variant1;
_variant1 = 456.78;
EXPECT_EQ(123.45, _variant2.as<double>());
}
TEST_F(JsonVariant_Copy_Tests, BooleansAreCopiedByValue) {
_variant1 = true;
_variant2 = _variant1;
_variant1 = false;
EXPECT_TRUE(_variant2.as<bool>());
}
TEST_F(JsonVariant_Copy_Tests, StringsAreCopiedByValue) {
_variant1 = "hello";
_variant2 = _variant1;
_variant1 = "world";
EXPECT_STREQ("hello", _variant2.as<const char *>());
}
TEST_F(JsonVariant_Copy_Tests, ObjectsAreCopiedByReference) {
JsonObject &object = _jsonBuffer.createObject();
_variant1 = object;
object["hello"] = "world";
EXPECT_EQ(1, _variant1.as<JsonObject>().size());
}
TEST_F(JsonVariant_Copy_Tests, ArraysAreCopiedByReference) {
JsonArray &array = _jsonBuffer.createArray();
_variant1 = array;
array.add("world");
EXPECT_EQ(1, _variant1.as<JsonArray>().size());
REQUIRE(123 == _variant2.as<int>());
}
SECTION("DoublesAreCopiedByValue") {
_variant1 = 123.45;
_variant2 = _variant1;
_variant1 = 456.78;
REQUIRE(123.45 == _variant2.as<double>());
}
SECTION("BooleansAreCopiedByValue") {
_variant1 = true;
_variant2 = _variant1;
_variant1 = false;
REQUIRE(_variant2.as<bool>());
}
SECTION("StringsAreCopiedByValue") {
_variant1 = "hello";
_variant2 = _variant1;
_variant1 = "world";
REQUIRE(std::string("hello") == _variant2.as<const char *>());
}
SECTION("ObjectsAreCopiedByReference") {
JsonObject &object = _jsonBuffer.createObject();
_variant1 = object;
object["hello"] = "world";
REQUIRE(1 == _variant1.as<JsonObject>().size());
}
SECTION("ArraysAreCopiedByReference") {
JsonArray &array = _jsonBuffer.createArray();
_variant1 = array;
array.add("world");
REQUIRE(1 == _variant1.as<JsonArray>().size());
}
}

View File

@ -6,257 +6,113 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
#define SUITE JsonVariant_Is_Tests
void checkIsArray(JsonVariant var) {
REQUIRE(var.is<JsonArray>());
REQUIRE(var.is<JsonArray&>());
REQUIRE(var.is<const JsonArray>());
REQUIRE(var.is<const JsonArray&>());
template <typename TTo, typename TFrom>
void assertIsNot(TFrom value) {
JsonVariant variant = value;
ASSERT_FALSE(variant.is<TTo>());
REQUIRE_FALSE(var.is<bool>());
REQUIRE_FALSE(var.is<double>());
REQUIRE_FALSE(var.is<float>());
REQUIRE_FALSE(var.is<int>());
REQUIRE_FALSE(var.is<long>());
REQUIRE_FALSE(var.is<const char*>());
REQUIRE_FALSE(var.is<JsonObject>());
}
template <typename TTo>
void assertIsNot(JsonArray& value) {
JsonVariant variant = value;
ASSERT_FALSE(variant.is<TTo>());
void checkIsBool(JsonVariant var) {
REQUIRE(var.is<bool>());
REQUIRE_FALSE(var.is<double>());
REQUIRE_FALSE(var.is<float>());
REQUIRE_FALSE(var.is<int>());
REQUIRE_FALSE(var.is<long>());
REQUIRE_FALSE(var.is<const char*>());
REQUIRE_FALSE(var.is<JsonArray>());
REQUIRE_FALSE(var.is<JsonObject>());
}
template <typename TTo, typename TFrom>
void assertIs(TFrom value) {
JsonVariant variant = value;
ASSERT_TRUE(variant.is<TTo>());
void checkIsFloat(JsonVariant var) {
REQUIRE(var.is<double>());
REQUIRE(var.is<float>());
REQUIRE_FALSE(var.is<bool>());
REQUIRE_FALSE(var.is<int>());
REQUIRE_FALSE(var.is<long>());
REQUIRE_FALSE(var.is<const char*>());
REQUIRE_FALSE(var.is<JsonArray>());
REQUIRE_FALSE(var.is<JsonObject>());
}
template <typename TTo>
void assertIs(JsonArray& value) {
JsonVariant variant = value;
ASSERT_TRUE(variant.is<TTo>());
void checkIsInteger(JsonVariant var) {
REQUIRE(var.is<long>());
REQUIRE(var.is<int>());
REQUIRE_FALSE(var.is<bool>());
REQUIRE_FALSE(var.is<double>());
REQUIRE_FALSE(var.is<float>());
REQUIRE_FALSE(var.is<const char*>());
REQUIRE_FALSE(var.is<JsonArray>());
REQUIRE_FALSE(var.is<JsonObject>());
}
TEST(SUITE, ArrayIsArray) {
void checkIsString(JsonVariant var) {
REQUIRE(var.is<const char*>());
REQUIRE_FALSE(var.is<bool>());
REQUIRE_FALSE(var.is<int>());
REQUIRE_FALSE(var.is<double>());
REQUIRE_FALSE(var.is<float>());
REQUIRE_FALSE(var.is<long>());
REQUIRE_FALSE(var.is<JsonArray>());
REQUIRE_FALSE(var.is<JsonObject>());
}
TEST_CASE("JsonVariant::is()") {
DynamicJsonBuffer jsonBuffer;
assertIs<JsonArray&>(jsonBuffer.createArray());
}
TEST(SUITE, ArrayIsNotBool) {
DynamicJsonBuffer jsonBuffer;
assertIsNot<bool>(jsonBuffer.createArray());
}
TEST(SUITE, ArrayIsNotDouble) {
DynamicJsonBuffer jsonBuffer;
assertIsNot<double>(jsonBuffer.createArray());
}
TEST(SUITE, ArrayIsNotFloat) {
DynamicJsonBuffer jsonBuffer;
assertIsNot<float>(jsonBuffer.createArray());
}
TEST(SUITE, ArrayIsNotInt) {
DynamicJsonBuffer jsonBuffer;
assertIsNot<int>(jsonBuffer.createArray());
}
TEST(SUITE, ArrayIsNotLong) {
DynamicJsonBuffer jsonBuffer;
assertIsNot<long>(jsonBuffer.createArray());
}
TEST(SUITE, ArrayIsNotString) {
DynamicJsonBuffer jsonBuffer;
assertIsNot<const char*>(jsonBuffer.createArray());
}
TEST(SUITE, BoolIsArray) {
assertIsNot<JsonArray&>(true);
}
TEST(SUITE, BoolIsBool) {
assertIs<bool>(true);
}
TEST(SUITE, BoolIsDouble) {
assertIsNot<double>(true);
}
TEST(SUITE, BoolIsFloat) {
assertIsNot<float>(true);
}
TEST(SUITE, BoolIsInt) {
assertIsNot<int>(true);
}
TEST(SUITE, BoolIsLong) {
assertIsNot<long>(true);
}
TEST(SUITE, BoolIsString) {
assertIsNot<const char*>(true);
}
SECTION("JsonArray") {
checkIsArray(jsonBuffer.createArray());
}
TEST(SUITE, DoubleIsArray) {
assertIsNot<JsonArray&>(4.2);
}
TEST(SUITE, DoubleIsBool) {
assertIsNot<bool>(4.2);
}
TEST(SUITE, DoubleIsDouble) {
assertIs<double>(4.2);
}
TEST(SUITE, DoubleIsFloat) {
assertIs<float>(4.2);
}
TEST(SUITE, DoubleIsInt) {
assertIsNot<int>(4.2);
}
TEST(SUITE, DoubleIsLong) {
assertIsNot<long>(4.2);
}
TEST(SUITE, DoubleIsString) {
assertIsNot<const char*>(4.2);
}
SECTION("bool") {
checkIsBool(true);
checkIsBool(false);
}
TEST(SUITE, LongIsArray) {
assertIsNot<JsonArray&>(42L);
}
TEST(SUITE, LongIsBool) {
assertIsNot<bool>(42L);
}
TEST(SUITE, LongIsDouble) {
assertIsNot<double>(42L);
}
TEST(SUITE, LongIsFloat) {
assertIsNot<float>(42L);
}
TEST(SUITE, LongIsInt) {
assertIs<int>(42L);
}
TEST(SUITE, LongIsLong) {
assertIs<long>(42L);
}
TEST(SUITE, LongIsString) {
assertIsNot<const char*>(42L);
}
SECTION("double") {
checkIsFloat(4.2);
}
TEST(SUITE, StringIsArray) {
assertIsNot<JsonArray&>("42");
}
TEST(SUITE, StringIsBool) {
assertIsNot<bool>("42");
}
TEST(SUITE, StringIsDouble) {
assertIsNot<double>("42");
}
TEST(SUITE, StringIsFloat) {
assertIsNot<float>("42");
}
TEST(SUITE, StringIsInt) {
assertIsNot<int>("42");
}
TEST(SUITE, StringIsLong) {
assertIsNot<long>("42");
}
TEST(SUITE, StringIsString) {
assertIs<const char*>("42");
}
SECTION("int") {
checkIsInteger(42);
}
TEST(SUITE, UnparsedTrueIsArray) {
assertIsNot<JsonArray&>(RawJson("true"));
}
TEST(SUITE, UnparsedTrueIsBool) {
assertIs<bool>(RawJson("true"));
}
TEST(SUITE, UnparsedTrueIsDouble) {
assertIsNot<double>(RawJson("true"));
}
TEST(SUITE, UnparsedTrueIsFloat) {
assertIsNot<float>(RawJson("true"));
}
TEST(SUITE, UnparsedTrueIsInt) {
assertIsNot<int>(RawJson("true"));
}
TEST(SUITE, UnparsedTrueIsLong) {
assertIsNot<long>(RawJson("true"));
}
TEST(SUITE, UnparsedTrueIsString) {
assertIsNot<const char*>(RawJson("true"));
}
SECTION("long") {
checkIsInteger(42L);
}
TEST(SUITE, UnparsedFalseIsArray) {
assertIsNot<JsonArray&>(RawJson("false"));
}
TEST(SUITE, UnparsedFalseIsBool) {
assertIs<bool>(RawJson("false"));
}
TEST(SUITE, UnparsedFalseIsDouble) {
assertIsNot<double>(RawJson("false"));
}
TEST(SUITE, UnparsedFalseIsFloat) {
assertIsNot<float>(RawJson("false"));
}
TEST(SUITE, UnparsedFalseIsInt) {
assertIsNot<int>(RawJson("false"));
}
TEST(SUITE, UnparsedFalseIsLong) {
assertIsNot<long>(RawJson("false"));
}
TEST(SUITE, UnparsedFalseIsString) {
assertIsNot<const char*>(RawJson("false"));
}
SECTION("string") {
checkIsString("42");
}
TEST(SUITE, UnparsedIntIsArray) {
assertIsNot<JsonArray&>(RawJson("42"));
}
TEST(SUITE, UnparsedIntIsBool) {
assertIsNot<bool>(RawJson("42"));
}
TEST(SUITE, UnparsedIntIsDouble) {
assertIsNot<double>(RawJson("42"));
}
TEST(SUITE, UnparsedIntIsFloat) {
assertIsNot<float>(RawJson("42"));
}
TEST(SUITE, UnparsedIntIsInt) {
assertIs<int>(RawJson("42"));
}
TEST(SUITE, UnparsedIntIsLong) {
assertIs<long>(RawJson("42"));
}
TEST(SUITE, UnparsedIntIsString) {
assertIsNot<const char*>(RawJson("42"));
}
SECTION("unparsed bool") {
checkIsBool(RawJson("true"));
checkIsBool(RawJson("false"));
}
TEST(SUITE, UnparsedFloatIsBool) {
assertIsNot<bool>(RawJson("4.2e-10"));
}
TEST(SUITE, UnparsedFloatIsDouble) {
assertIs<double>(RawJson("4.2e-10"));
}
TEST(SUITE, UnparsedFloatIsFloat) {
assertIs<float>(RawJson("4.2e-10"));
}
TEST(SUITE, UnparsedFloatIsInt) {
assertIsNot<int>(RawJson("4.2e-10"));
}
TEST(SUITE, UnparsedFloatIsLong) {
assertIsNot<long>(RawJson("4.2e-10"));
}
TEST(SUITE, UnparsedFloatIsStr) {
assertIsNot<const char*>(RawJson("4.2"));
}
SECTION("unparsed int") {
checkIsInteger(RawJson("42"));
}
TEST(SUITE, UnparsedNullIsArray) {
assertIsNot<JsonArray&>(RawJson("null"));
}
TEST(SUITE, UnparsedNullIsBool) {
assertIsNot<bool>(RawJson("null"));
}
TEST(SUITE, UnparsedNullIsDouble) {
assertIsNot<double>(RawJson("null"));
}
TEST(SUITE, UnparsedNullIsFloat) {
assertIsNot<float>(RawJson("null"));
}
TEST(SUITE, UnparsedNullIsInt) {
assertIsNot<int>(RawJson("null"));
}
TEST(SUITE, UnparsedNullIsLong) {
assertIsNot<long>(RawJson("null"));
}
TEST(SUITE, UnparsedNullIsConstCharPtr) {
assertIs<const char*>(RawJson("null"));
}
TEST(SUITE, UnparsedNullIsCharPtr) {
assertIs<char*>(RawJson("null"));
SECTION("unparsed float") {
checkIsFloat(RawJson("4.2e-10"));
}
SECTION("unparsed null") {
checkIsString(RawJson("null"));
}
}

View File

@ -6,128 +6,104 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
#include <limits>
class JsonVariant_PrintTo_Tests : public testing::Test {
protected:
JsonVariant variant;
void check(JsonVariant variant, const std::string &expected) {
char buffer[256] = "";
size_t returnValue = variant.printTo(buffer, sizeof(buffer));
REQUIRE(expected == buffer);
REQUIRE(expected.size() == returnValue);
}
void outputMustBe(const char *expected) {
char buffer[256] = "";
size_t n = variant.printTo(buffer, sizeof(buffer));
ASSERT_STREQ(expected, buffer);
ASSERT_EQ(strlen(expected), n);
TEST_CASE("JsonVariant::printTo()") {
SECTION("Empty") {
check(JsonVariant(), "");
}
};
TEST_F(JsonVariant_PrintTo_Tests, Empty) {
outputMustBe("");
}
SECTION("Null") {
check(static_cast<char *>(0), "null");
}
TEST_F(JsonVariant_PrintTo_Tests, Null) {
variant = static_cast<char *>(0);
outputMustBe("null");
}
SECTION("String") {
check("hello", "\"hello\"");
}
TEST_F(JsonVariant_PrintTo_Tests, String) {
variant = "hello";
outputMustBe("\"hello\"");
}
SECTION("DoubleZero") {
check(0.0, "0.00");
}
TEST_F(JsonVariant_PrintTo_Tests, DoubleZero) {
variant = 0.0;
outputMustBe("0.00");
}
SECTION("DoubleDefaultDigits") {
check(3.14159265358979323846, "3.14");
}
TEST_F(JsonVariant_PrintTo_Tests, DoubleDefaultDigits) {
variant = 3.14159265358979323846;
outputMustBe("3.14");
}
SECTION("DoubleFourDigits") {
check(JsonVariant(3.14159265358979323846, 4), "3.1416");
}
TEST_F(JsonVariant_PrintTo_Tests, DoubleFourDigits) {
variant = JsonVariant(3.14159265358979323846, 4);
outputMustBe("3.1416");
}
SECTION("Infinity") {
check(std::numeric_limits<double>::infinity(), "Infinity");
}
TEST_F(JsonVariant_PrintTo_Tests, Infinity) {
variant = std::numeric_limits<double>::infinity();
outputMustBe("Infinity");
}
SECTION("MinusInfinity") {
check(-std::numeric_limits<double>::infinity(), "-Infinity");
}
TEST_F(JsonVariant_PrintTo_Tests, MinusInfinity) {
variant = -std::numeric_limits<double>::infinity();
outputMustBe("-Infinity");
}
SECTION("SignalingNaN") {
check(std::numeric_limits<double>::signaling_NaN(), "NaN");
}
TEST_F(JsonVariant_PrintTo_Tests, SignalingNaN) {
variant = std::numeric_limits<double>::signaling_NaN();
outputMustBe("NaN");
}
SECTION("QuietNaN") {
check(std::numeric_limits<double>::quiet_NaN(), "NaN");
}
TEST_F(JsonVariant_PrintTo_Tests, QuietNaN) {
variant = std::numeric_limits<double>::quiet_NaN();
outputMustBe("NaN");
}
SECTION("VeryBigPositiveDouble") {
check(JsonVariant(3.14159265358979323846e42, 4), "3.1416e42");
}
TEST_F(JsonVariant_PrintTo_Tests, VeryBigPositiveDouble) {
variant = JsonVariant(3.14159265358979323846e42, 4);
outputMustBe("3.1416e42");
}
SECTION("VeryBigNegativeDouble") {
check(JsonVariant(-3.14159265358979323846e42, 4), "-3.1416e42");
}
TEST_F(JsonVariant_PrintTo_Tests, VeryBigNegativeDouble) {
variant = JsonVariant(-3.14159265358979323846e42, 4);
outputMustBe("-3.1416e42");
}
SECTION("VerySmallPositiveDouble") {
check(JsonVariant(3.14159265358979323846e-42, 4), "3.1416e-42");
}
TEST_F(JsonVariant_PrintTo_Tests, VerySmallPositiveDouble) {
variant = JsonVariant(3.14159265358979323846e-42, 4);
outputMustBe("3.1416e-42");
}
SECTION("VerySmallNegativeDouble") {
check(JsonVariant(-3.14159265358979323846e-42, 4), "-3.1416e-42");
}
TEST_F(JsonVariant_PrintTo_Tests, VerySmallNegativeDouble) {
variant = JsonVariant(-3.14159265358979323846e-42, 4);
outputMustBe("-3.1416e-42");
}
SECTION("Integer") {
check(42, "42");
}
TEST_F(JsonVariant_PrintTo_Tests, Integer) {
variant = 42;
outputMustBe("42");
}
SECTION("NegativeLong") {
check(-42, "-42");
}
TEST_F(JsonVariant_PrintTo_Tests, NegativeLong) {
variant = -42;
outputMustBe("-42");
}
SECTION("UnsignedLong") {
check(4294967295UL, "4294967295");
}
TEST_F(JsonVariant_PrintTo_Tests, UnsignedLong) {
variant = 4294967295UL;
outputMustBe("4294967295");
}
SECTION("True") {
check(true, "true");
}
TEST_F(JsonVariant_PrintTo_Tests, True) {
variant = true;
outputMustBe("true");
}
TEST_F(JsonVariant_PrintTo_Tests, OneFalse) {
variant = false;
outputMustBe("false");
}
SECTION("OneFalse") {
check(false, "false");
}
#if ARDUINOJSON_USE_LONG_LONG || ARDUINOJSON_USE_INT64
TEST_F(JsonVariant_PrintTo_Tests, NegativeInt64) {
variant = -9223372036854775807 - 1;
outputMustBe("-9223372036854775808");
}
SECTION("NegativeInt64") {
check(-9223372036854775807 - 1, "-9223372036854775808");
}
TEST_F(JsonVariant_PrintTo_Tests, PositiveInt64) {
variant = 9223372036854775807;
outputMustBe("9223372036854775807");
}
SECTION("PositiveInt64") {
check(9223372036854775807, "9223372036854775807");
}
TEST_F(JsonVariant_PrintTo_Tests, UInt64) {
variant = 18446744073709551615;
outputMustBe("18446744073709551615");
}
SECTION("UInt64") {
check(18446744073709551615, "18446744073709551615");
}
#endif
}

View File

@ -6,129 +6,128 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <stdint.h>
#include <catch.hpp>
#include <limits>
class JsonVariant_Storage_Tests : public ::testing::Test {
protected:
template <typename T>
void testValue(T expected) {
JsonVariant variant = expected;
EXPECT_EQ(expected, variant.as<T>());
}
template <typename T>
void testReference(T &expected) {
JsonVariant variant = expected;
EXPECT_EQ(expected, variant.as<T &>());
}
template <typename T>
void testNumericType() {
T min = std::numeric_limits<T>::min();
T max = std::numeric_limits<T>::max();
JsonVariant variantMin(min);
JsonVariant variantMax(max);
EXPECT_EQ(min, variantMin.as<T>());
EXPECT_EQ(max, variantMax.as<T>());
}
};
#if ARDUINOJSON_USE_LONG_LONG || ARDUINOJSON_USE_INT64
TEST_F(JsonVariant_Storage_Tests, SizeOfJsonInteger) {
ASSERT_EQ(8, sizeof(Internals::JsonInteger));
template <typename T>
void checkValue(T expected) {
JsonVariant variant = expected;
REQUIRE(expected == variant.as<T>());
}
template <typename T>
void checkReference(T &expected) {
JsonVariant variant = expected;
REQUIRE(expected == variant.as<T &>());
}
template <typename T>
void checkNumericType() {
T min = std::numeric_limits<T>::min();
T max = std::numeric_limits<T>::max();
JsonVariant variantMin(min);
JsonVariant variantMax(max);
REQUIRE(min == variantMin.as<T>());
REQUIRE(max == variantMax.as<T>());
}
TEST_CASE("JsonVariant set()/get()") {
#if ARDUINOJSON_USE_LONG_LONG || ARDUINOJSON_USE_INT64
SECTION("SizeOfJsonInteger") {
REQUIRE(8 == sizeof(Internals::JsonInteger));
}
#endif
TEST_F(JsonVariant_Storage_Tests, Null) {
testValue<const char *>(NULL);
}
TEST_F(JsonVariant_Storage_Tests, String) {
testValue<const char *>("hello");
}
SECTION("Null") {
checkValue<const char *>(NULL);
}
SECTION("String") {
checkValue<const char *>("hello");
}
TEST_F(JsonVariant_Storage_Tests, False) {
testValue<bool>(false);
}
TEST_F(JsonVariant_Storage_Tests, True) {
testValue<bool>(true);
}
SECTION("False") {
checkValue<bool>(false);
}
SECTION("True") {
checkValue<bool>(true);
}
TEST_F(JsonVariant_Storage_Tests, Double) {
testNumericType<double>();
}
TEST_F(JsonVariant_Storage_Tests, Float) {
testNumericType<float>();
}
TEST_F(JsonVariant_Storage_Tests, Char) {
testNumericType<char>();
}
TEST_F(JsonVariant_Storage_Tests, SChar) {
testNumericType<signed char>();
}
TEST_F(JsonVariant_Storage_Tests, SInt) {
testNumericType<signed int>();
}
TEST_F(JsonVariant_Storage_Tests, SLong) {
testNumericType<signed long>();
}
TEST_F(JsonVariant_Storage_Tests, SShort) {
testNumericType<signed short>();
}
TEST_F(JsonVariant_Storage_Tests, UChar) {
testNumericType<unsigned char>();
}
TEST_F(JsonVariant_Storage_Tests, UInt) {
testNumericType<unsigned int>();
}
TEST_F(JsonVariant_Storage_Tests, ULong) {
testNumericType<unsigned long>();
}
TEST_F(JsonVariant_Storage_Tests, UShort) {
testNumericType<unsigned short>();
}
SECTION("Double") {
checkNumericType<double>();
}
SECTION("Float") {
checkNumericType<float>();
}
SECTION("Char") {
checkNumericType<char>();
}
SECTION("SChar") {
checkNumericType<signed char>();
}
SECTION("SInt") {
checkNumericType<signed int>();
}
SECTION("SLong") {
checkNumericType<signed long>();
}
SECTION("SShort") {
checkNumericType<signed short>();
}
SECTION("UChar") {
checkNumericType<unsigned char>();
}
SECTION("UInt") {
checkNumericType<unsigned int>();
}
SECTION("ULong") {
checkNumericType<unsigned long>();
}
SECTION("UShort") {
checkNumericType<unsigned short>();
}
#if ARDUINOJSON_USE_LONG_LONG || ARDUINOJSON_USE_INT64
TEST_F(JsonVariant_Storage_Tests, LongLong) {
testNumericType<unsigned long long>();
}
TEST_F(JsonVariant_Storage_Tests, ULongLong) {
testNumericType<unsigned long long>();
}
SECTION("LongLong") {
checkNumericType<unsigned long long>();
}
SECTION("ULongLong") {
checkNumericType<unsigned long long>();
}
#endif
TEST_F(JsonVariant_Storage_Tests, Int8) {
testNumericType<int8_t>();
}
TEST_F(JsonVariant_Storage_Tests, Uint8) {
testNumericType<uint8_t>();
}
TEST_F(JsonVariant_Storage_Tests, Int16) {
testNumericType<int16_t>();
}
TEST_F(JsonVariant_Storage_Tests, Uint16) {
testNumericType<uint16_t>();
}
TEST_F(JsonVariant_Storage_Tests, Int32) {
testNumericType<int32_t>();
}
TEST_F(JsonVariant_Storage_Tests, Uint32) {
testNumericType<uint32_t>();
}
SECTION("Int8") {
checkNumericType<int8_t>();
}
SECTION("Uint8") {
checkNumericType<uint8_t>();
}
SECTION("Int16") {
checkNumericType<int16_t>();
}
SECTION("Uint16") {
checkNumericType<uint16_t>();
}
SECTION("Int32") {
checkNumericType<int32_t>();
}
SECTION("Uint32") {
checkNumericType<uint32_t>();
}
#if ARDUINOJSON_USE_LONG_LONG || ARDUINOJSON_USE_INT64
TEST_F(JsonVariant_Storage_Tests, Int64) {
testNumericType<int64_t>();
}
TEST_F(JsonVariant_Storage_Tests, Uint64) {
testNumericType<uint64_t>();
}
SECTION("Int64") {
checkNumericType<int64_t>();
}
SECTION("Uint64") {
checkNumericType<uint64_t>();
}
#endif
TEST_F(JsonVariant_Storage_Tests, CanStoreObject) {
DynamicJsonBuffer jsonBuffer;
JsonObject &object = jsonBuffer.createObject();
SECTION("CanStoreObject") {
DynamicJsonBuffer jsonBuffer;
JsonObject &object = jsonBuffer.createObject();
testReference(object);
checkReference(object);
}
}

View File

@ -6,77 +6,75 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
class JsonVariant_Subscript_Tests : public ::testing::Test {
protected:
TEST_CASE("JsonVariant::operator[]") {
DynamicJsonBuffer _jsonBuffer;
JsonVariant _variant;
};
TEST_F(JsonVariant_Subscript_Tests, Array) {
JsonArray &array = _jsonBuffer.createArray();
array.add("element at index 0");
array.add("element at index 1");
SECTION("Array") {
JsonArray &array = _jsonBuffer.createArray();
array.add("element at index 0");
array.add("element at index 1");
_variant = array;
JsonVariant var = array;
EXPECT_EQ(2, _variant.size());
EXPECT_STREQ("element at index 0", _variant[0]);
EXPECT_STREQ("element at index 1", _variant[1]);
EXPECT_STREQ("element at index 0",
_variant[static_cast<unsigned char>(0)]); // issue #381
EXPECT_FALSE(_variant[-1].success());
EXPECT_FALSE(_variant[3].success());
EXPECT_FALSE(_variant["0"].success());
}
TEST_F(JsonVariant_Subscript_Tests, Object) {
JsonObject &object = _jsonBuffer.createObject();
object["a"] = "element at key \"a\"";
object["b"] = "element at key \"b\"";
_variant = object;
EXPECT_EQ(2, _variant.size());
EXPECT_STREQ("element at key \"a\"", _variant["a"]);
EXPECT_STREQ("element at key \"b\"", _variant["b"]);
EXPECT_FALSE(_variant["c"].success());
EXPECT_FALSE(_variant[0].success());
}
TEST_F(JsonVariant_Subscript_Tests, Undefined) {
_variant = JsonVariant();
EXPECT_EQ(0, _variant.size());
EXPECT_FALSE(_variant["0"].success());
EXPECT_FALSE(_variant[0].success());
}
TEST_F(JsonVariant_Subscript_Tests, String) {
_variant = "hello world";
EXPECT_EQ(0, _variant.size());
EXPECT_FALSE(_variant["0"].success());
EXPECT_FALSE(_variant[0].success());
}
TEST_F(JsonVariant_Subscript_Tests, ObjectSetValue) {
_variant = _jsonBuffer.createObject();
_variant["hello"] = "world";
EXPECT_EQ(1, _variant.size());
EXPECT_STREQ("world", _variant["hello"]);
}
TEST_F(JsonVariant_Subscript_Tests, ArraySetValue) {
_variant = _jsonBuffer.parseArray("[\"hello\"]");
_variant[0] = "world";
EXPECT_EQ(1, _variant.size());
EXPECT_STREQ("world", _variant[0]);
}
TEST_F(JsonVariant_Subscript_Tests, NestedObjectSetValue) {
_variant = _jsonBuffer.parseArray("[{}]");
_variant[0]["hello"] = "world";
EXPECT_EQ(1, _variant.size());
EXPECT_EQ(1, _variant[0].size());
EXPECT_STREQ("world", _variant[0]["hello"]);
REQUIRE(2 == var.size());
REQUIRE(std::string("element at index 0") == var[0]);
REQUIRE(std::string("element at index 1") == var[1]);
REQUIRE(std::string("element at index 0") ==
var[static_cast<unsigned char>(0)]); // issue #381
REQUIRE_FALSE(var[-1].success());
REQUIRE_FALSE(var[3].success());
REQUIRE_FALSE(var["0"].success());
}
SECTION("Object") {
JsonObject &object = _jsonBuffer.createObject();
object["a"] = "element at key \"a\"";
object["b"] = "element at key \"b\"";
JsonVariant var = object;
REQUIRE(2 == var.size());
REQUIRE(std::string("element at key \"a\"") == var["a"]);
REQUIRE(std::string("element at key \"b\"") == var["b"]);
REQUIRE_FALSE(var["c"].success());
REQUIRE_FALSE(var[0].success());
}
SECTION("Undefined") {
JsonVariant var = JsonVariant();
REQUIRE(0 == var.size());
REQUIRE_FALSE(var["0"].success());
REQUIRE_FALSE(var[0].success());
}
SECTION("String") {
JsonVariant var = "hello world";
REQUIRE(0 == var.size());
REQUIRE_FALSE(var["0"].success());
REQUIRE_FALSE(var[0].success());
}
SECTION("ObjectSetValue") {
JsonVariant var = _jsonBuffer.createObject();
var["hello"] = "world";
REQUIRE(1 == var.size());
REQUIRE(std::string("world") == var["hello"]);
}
SECTION("ArraySetValue") {
JsonVariant var = _jsonBuffer.parseArray("[\"hello\"]");
var[0] = "world";
REQUIRE(1 == var.size());
REQUIRE(std::string("world") == var[0]);
}
SECTION("NestedObjectSetValue") {
JsonVariant var = _jsonBuffer.parseArray("[{}]");
var[0]["hello"] = "world";
REQUIRE(1 == var.size());
REQUIRE(1 == var[0].size());
REQUIRE(std::string("world") == var[0]["hello"]);
}
}

View File

@ -6,38 +6,40 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
TEST(JsonVariant_Success_Tests, ReturnsFalse_WhenUndefined) {
JsonVariant variant;
EXPECT_FALSE(variant.success());
}
TEST(JsonVariant_Success_Tests, ReturnsTrue_WhenInteger) {
JsonVariant variant = 0;
EXPECT_TRUE(variant.success());
}
TEST(JsonVariant_Success_Tests, ReturnsTrue_WhenEmptyArray) {
DynamicJsonBuffer jsonBuffer;
JsonVariant variant = jsonBuffer.createArray();
EXPECT_TRUE(variant.success());
}
TEST(JsonVariant_Success_Tests, ReturnsTrue_WhenEmptyObject) {
DynamicJsonBuffer jsonBuffer;
JsonVariant variant = jsonBuffer.createObject();
EXPECT_TRUE(variant.success());
}
TEST(JsonVariant_Success_Tests, ReturnsFalse_WhenInvalidArray) {
JsonVariant variant = JsonArray::invalid();
EXPECT_FALSE(variant.success());
}
TEST(JsonVariant_Success_Tests, ReturnsFalse_WhenInvalidObject) {
JsonVariant variant = JsonObject::invalid();
EXPECT_FALSE(variant.success());
TEST_CASE("JsonVariant::success()") {
SECTION("ReturnsFalse_WhenUndefined") {
JsonVariant variant;
REQUIRE(false == variant.success());
}
SECTION("ReturnsTrue_WhenInteger") {
JsonVariant variant = 0;
REQUIRE(true == variant.success());
}
SECTION("ReturnsTrue_WhenEmptyArray") {
DynamicJsonBuffer jsonBuffer;
JsonVariant variant = jsonBuffer.createArray();
REQUIRE(true == variant.success());
}
SECTION("ReturnsTrue_WhenEmptyObject") {
DynamicJsonBuffer jsonBuffer;
JsonVariant variant = jsonBuffer.createObject();
REQUIRE(true == variant.success());
}
SECTION("ReturnsFalse_WhenInvalidArray") {
JsonVariant variant = JsonArray::invalid();
REQUIRE(false == variant.success());
}
SECTION("ReturnsFalse_WhenInvalidObject") {
JsonVariant variant = JsonObject::invalid();
REQUIRE(false == variant.success());
}
}

View File

@ -6,53 +6,52 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
class JsonVariant_Undefined_Tests : public ::testing::Test {
protected:
TEST_CASE("JsonVariant undefined") {
JsonVariant variant;
};
TEST_F(JsonVariant_Undefined_Tests, AsLongReturns0) {
EXPECT_EQ(0, variant.as<long>());
}
SECTION("AsLongReturns0") {
REQUIRE(0 == variant.as<long>());
}
TEST_F(JsonVariant_Undefined_Tests, AsUnsignedReturns0) {
EXPECT_EQ(0, variant.as<unsigned>());
}
SECTION("AsUnsignedReturns0") {
REQUIRE(0 == variant.as<unsigned>());
}
TEST_F(JsonVariant_Undefined_Tests, AsStringReturnsNull) {
EXPECT_EQ(0, variant.as<char*>());
}
SECTION("AsStringReturnsNull") {
REQUIRE(0 == variant.as<char*>());
}
TEST_F(JsonVariant_Undefined_Tests, AsDoubleReturns0) {
EXPECT_EQ(0, variant.as<double>());
}
SECTION("AsDoubleReturns0") {
REQUIRE(0 == variant.as<double>());
}
TEST_F(JsonVariant_Undefined_Tests, AsBoolReturnsFalse) {
EXPECT_FALSE(variant.as<bool>());
}
SECTION("AsBoolReturnsFalse") {
REQUIRE(false == variant.as<bool>());
}
TEST_F(JsonVariant_Undefined_Tests, AsArrayReturnInvalid) {
EXPECT_EQ(JsonArray::invalid(), variant.as<JsonArray&>());
}
SECTION("AsArrayReturnInvalid") {
REQUIRE(JsonArray::invalid() == variant.as<JsonArray&>());
}
TEST_F(JsonVariant_Undefined_Tests, AsConstArrayReturnInvalid) {
EXPECT_EQ(JsonArray::invalid(), variant.as<const JsonArray&>());
}
SECTION("AsConstArrayReturnInvalid") {
REQUIRE(JsonArray::invalid() == variant.as<const JsonArray&>());
}
TEST_F(JsonVariant_Undefined_Tests, AsObjectReturnInvalid) {
EXPECT_EQ(JsonObject::invalid(), variant.as<JsonObject&>());
}
SECTION("AsObjectReturnInvalid") {
REQUIRE(JsonObject::invalid() == variant.as<JsonObject&>());
}
TEST_F(JsonVariant_Undefined_Tests, AsConstObjectReturnInvalid) {
EXPECT_EQ(JsonObject::invalid(), variant.as<const JsonObject&>());
}
SECTION("AsConstObjectReturnInvalid") {
REQUIRE(JsonObject::invalid() == variant.as<const JsonObject&>());
}
TEST_F(JsonVariant_Undefined_Tests, AsArrayWrapperReturnInvalid) {
EXPECT_EQ(JsonArray::invalid(), variant.as<JsonArray>());
}
SECTION("AsArrayWrapperReturnInvalid") {
REQUIRE(JsonArray::invalid() == variant.as<JsonArray>());
}
TEST_F(JsonVariant_Undefined_Tests, AsObjectWrapperReturnInvalid) {
EXPECT_EQ(JsonObject::invalid(), variant.as<JsonObject>());
SECTION("AsObjectWrapperReturnInvalid") {
REQUIRE(JsonObject::invalid() == variant.as<JsonObject>());
}
}

View File

@ -10,5 +10,5 @@ add_executable(JsonWriterTests
writeString.cpp
)
target_link_libraries(JsonWriterTests gtest)
target_link_libraries(JsonWriterTests catch)
add_test(JsonWriter JsonWriterTests)

View File

@ -5,109 +5,86 @@
// https://bblanchon.github.io/ArduinoJson/
// If you like this project, please add a star!
#include <gtest/gtest.h>
#include <catch.hpp>
#include <limits>
#include <string>
#include <ArduinoJson/Serialization/JsonWriter.hpp>
#include <ArduinoJson/Serialization/StaticStringBuilder.hpp>
using namespace ArduinoJson::Internals;
class JsonWriter_WriteFloat_Tests : public testing::Test {
protected:
void whenInputIs(double input, uint8_t digits = 2) {
StaticStringBuilder sb(buffer, sizeof(buffer));
JsonWriter writer(sb);
writer.writeFloat(input, digits);
returnValue = writer.bytesWritten();
void check(const std::string& expected, double input, uint8_t digits = 2) {
char output[1024];
StaticStringBuilder sb(output, sizeof(output));
JsonWriter writer(sb);
writer.writeFloat(input, digits);
REQUIRE(output == expected);
REQUIRE(writer.bytesWritten() == expected.size());
}
TEST_CASE("JsonWriter::writeFloat()") {
SECTION("NaN") {
check("NaN", std::numeric_limits<double>::signaling_NaN());
}
void outputMustBe(const char *expected) {
EXPECT_STREQ(expected, buffer);
EXPECT_EQ(strlen(expected), returnValue);
SECTION("PositiveInfinity") {
check("Infinity", std::numeric_limits<double>::infinity());
}
private:
char buffer[1024];
size_t returnValue;
};
SECTION("NegativeInfinity") {
check("-Infinity", -std::numeric_limits<double>::infinity());
}
TEST_F(JsonWriter_WriteFloat_Tests, NaN) {
whenInputIs(std::numeric_limits<double>::signaling_NaN());
outputMustBe("NaN");
}
SECTION("Zero") {
check("0.00", 0);
}
TEST_F(JsonWriter_WriteFloat_Tests, PositiveInfinity) {
whenInputIs(std::numeric_limits<double>::infinity());
outputMustBe("Infinity");
}
SECTION("ZeroDigits_Rounding") {
check("10", 9.5, 0);
}
TEST_F(JsonWriter_WriteFloat_Tests, NegativeInfinity) {
whenInputIs(-std::numeric_limits<double>::infinity());
outputMustBe("-Infinity");
}
SECTION("ZeroDigits_NoRounding") {
check("9", 9.4, 0);
}
TEST_F(JsonWriter_WriteFloat_Tests, Zero) {
whenInputIs(0);
outputMustBe("0.00");
}
SECTION("OneDigit_Rounding") {
check("10.0", 9.95, 1);
}
TEST_F(JsonWriter_WriteFloat_Tests, ZeroDigits_Rounding) {
whenInputIs(9.5, 0);
outputMustBe("10");
}
SECTION("OneDigit_NoRounding") {
check("9.9", 9.94, 1);
}
TEST_F(JsonWriter_WriteFloat_Tests, ZeroDigits_NoRounding) {
whenInputIs(9.4, 0);
outputMustBe("9");
}
SECTION("TwoDigits_Rounding") {
check("10.00", 9.995, 2);
}
TEST_F(JsonWriter_WriteFloat_Tests, OneDigit_Rounding) {
whenInputIs(9.95, 1);
outputMustBe("10.0");
}
SECTION("TwoDigits_NoRounding") {
check("9.99", 9.994, 2);
}
TEST_F(JsonWriter_WriteFloat_Tests, OneDigit_NoRounding) {
whenInputIs(9.94, 1);
outputMustBe("9.9");
}
SECTION("ThreeDigits_Rounding") {
check("10.000", 9.9995, 3);
}
TEST_F(JsonWriter_WriteFloat_Tests, TwoDigits_Rounding) {
whenInputIs(9.995, 2);
outputMustBe("10.00");
}
SECTION("ThreeDigits_NoRounding") {
check("9.999", 9.9994, 3);
}
TEST_F(JsonWriter_WriteFloat_Tests, TwoDigits_NoRounding) {
whenInputIs(9.994, 2);
outputMustBe("9.99");
}
SECTION("FourDigits_Rounding") {
check("10.0000", 9.99995, 4);
}
TEST_F(JsonWriter_WriteFloat_Tests, ThreeDigits_Rounding) {
whenInputIs(9.9995, 3);
outputMustBe("10.000");
}
SECTION("FourDigits_NoRounding") {
check("9.9999", 9.99994, 4);
}
TEST_F(JsonWriter_WriteFloat_Tests, ThreeDigits_NoRounding) {
whenInputIs(9.9994, 3);
outputMustBe("9.999");
}
SECTION("FiveDigits_Rounding") {
check("10.00000", 9.999995, 5);
}
TEST_F(JsonWriter_WriteFloat_Tests, FourDigits_Rounding) {
whenInputIs(9.99995, 4);
outputMustBe("10.0000");
}
TEST_F(JsonWriter_WriteFloat_Tests, FourDigits_NoRounding) {
whenInputIs(9.99994, 4);
outputMustBe("9.9999");
}
TEST_F(JsonWriter_WriteFloat_Tests, FiveDigits_Rounding) {
whenInputIs(9.999995, 5);
outputMustBe("10.00000");
}
TEST_F(JsonWriter_WriteFloat_Tests, FiveDigits_NoRounding) {
whenInputIs(9.999994, 5);
outputMustBe("9.99999");
SECTION("FiveDigits_NoRounding") {
check("9.99999", 9.999994, 5);
}
}

View File

@ -5,78 +5,60 @@
// https://bblanchon.github.io/ArduinoJson/
// If you like this project, please add a star!
#include <gtest/gtest.h>
#include <catch.hpp>
#include <ArduinoJson/Serialization/JsonWriter.hpp>
#include <ArduinoJson/Serialization/StaticStringBuilder.hpp>
using namespace ArduinoJson::Internals;
class JsonWriter_WriteString_Tests : public testing::Test {
protected:
void whenInputIs(const char *input) {
StaticStringBuilder sb(buffer, sizeof(buffer));
JsonWriter writer(sb);
writer.writeString(input);
returnValue = writer.bytesWritten();
void check(const char* input, std::string expected) {
char output[1024];
StaticStringBuilder sb(output, sizeof(output));
JsonWriter writer(sb);
writer.writeString(input);
REQUIRE(expected == output);
REQUIRE(writer.bytesWritten() == expected.size());
}
TEST_CASE("JsonWriter::writeString()") {
SECTION("Null") {
check(0, "null");
}
void outputMustBe(const char *expected) {
EXPECT_STREQ(expected, buffer);
EXPECT_EQ(strlen(expected), returnValue);
SECTION("EmptyString") {
check("", "\"\"");
}
private:
char buffer[1024];
size_t returnValue;
};
SECTION("QuotationMark") {
check("\"", "\"\\\"\"");
}
TEST_F(JsonWriter_WriteString_Tests, Null) {
whenInputIs(0);
outputMustBe("null");
}
SECTION("ReverseSolidus") {
check("\\", "\"\\\\\"");
}
TEST_F(JsonWriter_WriteString_Tests, EmptyString) {
whenInputIs("");
outputMustBe("\"\"");
}
SECTION("Solidus") {
check("/", "\"/\""); // but the JSON format allows \/
}
TEST_F(JsonWriter_WriteString_Tests, QuotationMark) {
whenInputIs("\"");
outputMustBe("\"\\\"\"");
}
SECTION("Backspace") {
check("\b", "\"\\b\"");
}
TEST_F(JsonWriter_WriteString_Tests, ReverseSolidus) {
whenInputIs("\\");
outputMustBe("\"\\\\\"");
}
SECTION("Formfeed") {
check("\f", "\"\\f\"");
}
TEST_F(JsonWriter_WriteString_Tests, Solidus) {
whenInputIs("/");
outputMustBe("\"/\""); // but the JSON format allows \/
}
SECTION("Newline") {
check("\n", "\"\\n\"");
}
TEST_F(JsonWriter_WriteString_Tests, Backspace) {
whenInputIs("\b");
outputMustBe("\"\\b\"");
}
SECTION("CarriageReturn") {
check("\r", "\"\\r\"");
}
TEST_F(JsonWriter_WriteString_Tests, Formfeed) {
whenInputIs("\f");
outputMustBe("\"\\f\"");
}
TEST_F(JsonWriter_WriteString_Tests, Newline) {
whenInputIs("\n");
outputMustBe("\"\\n\"");
}
TEST_F(JsonWriter_WriteString_Tests, CarriageReturn) {
whenInputIs("\r");
outputMustBe("\"\\r\"");
}
TEST_F(JsonWriter_WriteString_Tests, HorizontalTab) {
whenInputIs("\t");
outputMustBe("\"\\t\"");
SECTION("HorizontalTab") {
check("\t", "\"\\t\"");
}
}

View File

@ -15,5 +15,5 @@ add_executable(MiscTests
vla.cpp
)
target_link_libraries(MiscTests gtest)
target_link_libraries(MiscTests catch)
add_test(Misc MiscTests)

View File

@ -6,70 +6,37 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
using namespace ArduinoJson::Internals;
class StringBuilderTests : public testing::Test {
protected:
virtual void SetUp() {
_stringBuilder = new StaticStringBuilder(_buffer, sizeof(_buffer));
TEST_CASE("StringBuilder") {
char output[20];
StaticStringBuilder sb(output, sizeof(output));
SECTION("InitialState") {
REQUIRE(std::string("") == output);
}
virtual void TearDown() {
delete _stringBuilder;
SECTION("OverCapacity") {
REQUIRE(19 == sb.print("ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
REQUIRE(0 == sb.print("ABC"));
REQUIRE(std::string("ABCDEFGHIJKLMNOPQRS") == output);
}
void print(const char *value) {
_returnValue = _stringBuilder->print(value);
SECTION("EmptyString") {
REQUIRE(0 == sb.print(""));
REQUIRE(std::string("") == output);
}
void outputMustBe(const char *expected) {
EXPECT_STREQ(expected, _buffer);
SECTION("OneString") {
REQUIRE(4 == sb.print("ABCD"));
REQUIRE(std::string("ABCD") == output);
}
void resultMustBe(size_t expected) {
EXPECT_EQ(expected, _returnValue);
SECTION("TwoStrings") {
REQUIRE(4 == sb.print("ABCD"));
REQUIRE(4 == sb.print("EFGH"));
REQUIRE(std::string("ABCDEFGH") == output);
}
private:
char _buffer[20];
Print *_stringBuilder;
size_t _returnValue;
};
TEST_F(StringBuilderTests, InitialState) {
outputMustBe("");
}
TEST_F(StringBuilderTests, OverCapacity) {
print("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
resultMustBe(19);
print("ABC");
resultMustBe(0);
outputMustBe("ABCDEFGHIJKLMNOPQRS");
}
TEST_F(StringBuilderTests, EmptyString) {
print("");
resultMustBe(0);
outputMustBe("");
}
TEST_F(StringBuilderTests, OneString) {
print("ABCD");
resultMustBe(4);
outputMustBe("ABCD");
}
TEST_F(StringBuilderTests, TwoStrings) {
print("ABCD");
resultMustBe(4);
print("EFGH");
resultMustBe(4);
outputMustBe("ABCDEFGH");
}

View File

@ -6,31 +6,37 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
#include <sstream>
using namespace ArduinoJson::TypeTraits;
TEST(TypeTraits, IsBaseOf) {
ASSERT_FALSE((IsBaseOf<std::istream, std::ostringstream>::value));
ASSERT_TRUE((IsBaseOf<std::istream, std::istringstream>::value));
ASSERT_TRUE((IsBaseOf<JsonVariantBase<JsonObjectSubscript<const char*> >,
JsonObjectSubscript<const char*> >::value));
}
TEST_CASE("TypeTraits") {
SECTION("IsBaseOf") {
REQUIRE_FALSE(
static_cast<bool>(IsBaseOf<std::istream, std::ostringstream>::value));
REQUIRE(
static_cast<bool>(IsBaseOf<std::istream, std::istringstream>::value));
REQUIRE(static_cast<bool>(
IsBaseOf<JsonVariantBase<JsonObjectSubscript<const char*> >,
JsonObjectSubscript<const char*> >::value));
}
TEST(TypeTraits, IsArray) {
ASSERT_FALSE((IsArray<const char*>::value));
ASSERT_TRUE((IsArray<const char[]>::value));
ASSERT_TRUE((IsArray<const char[10]>::value));
}
SECTION("IsArray") {
REQUIRE_FALSE((IsArray<const char*>::value));
REQUIRE((IsArray<const char[]>::value));
REQUIRE((IsArray<const char[10]>::value));
}
TEST(TypeTraits, IsVariant) {
ASSERT_TRUE((IsVariant<JsonObjectSubscript<const char*> >::value));
ASSERT_TRUE((IsVariant<JsonVariant>::value));
}
SECTION("IsVariant") {
REQUIRE(
static_cast<bool>(IsVariant<JsonObjectSubscript<const char*> >::value));
REQUIRE(static_cast<bool>(IsVariant<JsonVariant>::value));
}
TEST(TypeTraits, IsString) {
ASSERT_TRUE((IsString<const char*>::value));
ASSERT_TRUE((IsString<std::string>::value));
ASSERT_FALSE((IsString<double>::value));
SECTION("IsString") {
REQUIRE((IsString<const char*>::value));
REQUIRE((IsString<std::string>::value));
REQUIRE_FALSE((IsString<double>::value));
}
}

View File

@ -8,7 +8,7 @@
#define ARDUINOJSON_ENABLE_DEPRECATED 1
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
#if defined(__clang__)
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
@ -18,25 +18,27 @@
#pragma warning(disable : 4996)
#endif
TEST(Deprecated, asArray) {
DynamicJsonBuffer jsonBuffer;
JsonVariant variant = jsonBuffer.createArray();
ASSERT_TRUE(variant.asArray().success());
}
TEST_CASE("Deprecated functions") {
SECTION("JsonVariant::asArray()") {
DynamicJsonBuffer jsonBuffer;
JsonVariant variant = jsonBuffer.createArray();
REQUIRE(variant.asArray().success());
}
TEST(Deprecated, asObject) {
DynamicJsonBuffer jsonBuffer;
JsonVariant variant = jsonBuffer.createObject();
ASSERT_TRUE(variant.asObject().success());
}
SECTION("JsonVariant::asObject()") {
DynamicJsonBuffer jsonBuffer;
JsonVariant variant = jsonBuffer.createObject();
REQUIRE(variant.asObject().success());
}
TEST(Deprecated, asString) {
JsonVariant variant = "hello";
ASSERT_STREQ("hello", variant.asString());
}
SECTION("JsonVariant::asString()") {
JsonVariant variant = "hello";
REQUIRE(std::string("hello") == variant.asString());
}
TEST(Deprecated, removeAt) {
DynamicJsonBuffer jsonBuffer;
JsonArray& arr = jsonBuffer.createArray();
arr.removeAt(0);
SECTION("JsonArray::removeAt()") {
DynamicJsonBuffer jsonBuffer;
JsonArray& arr = jsonBuffer.createArray();
arr.removeAt(0);
}
}

View File

@ -6,80 +6,82 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
#include <sstream>
TEST(StdStream_Tests, JsonVariantFalse) {
std::ostringstream os;
JsonVariant variant = false;
os << variant;
ASSERT_EQ("false", os.str());
}
TEST_CASE("std::stream") {
SECTION("JsonVariantFalse") {
std::ostringstream os;
JsonVariant variant = false;
os << variant;
REQUIRE("false" == os.str());
}
TEST(StdStream_Tests, JsonVariantString) {
std::ostringstream os;
JsonVariant variant = "coucou";
os << variant;
ASSERT_EQ("\"coucou\"", os.str());
}
SECTION("JsonVariantString") {
std::ostringstream os;
JsonVariant variant = "coucou";
os << variant;
REQUIRE("\"coucou\"" == os.str());
}
TEST(StdStream_Tests, JsonObject) {
std::ostringstream os;
DynamicJsonBuffer jsonBuffer;
JsonObject& object = jsonBuffer.createObject();
object["key"] = "value";
os << object;
ASSERT_EQ("{\"key\":\"value\"}", os.str());
}
SECTION("JsonObject") {
std::ostringstream os;
DynamicJsonBuffer jsonBuffer;
JsonObject& object = jsonBuffer.createObject();
object["key"] = "value";
os << object;
REQUIRE("{\"key\":\"value\"}" == os.str());
}
TEST(StdStream_Tests, JsonObjectSubscript) {
std::ostringstream os;
DynamicJsonBuffer jsonBuffer;
JsonObject& object = jsonBuffer.createObject();
object["key"] = "value";
os << object["key"];
ASSERT_EQ("\"value\"", os.str());
}
SECTION("JsonObjectSubscript") {
std::ostringstream os;
DynamicJsonBuffer jsonBuffer;
JsonObject& object = jsonBuffer.createObject();
object["key"] = "value";
os << object["key"];
REQUIRE("\"value\"" == os.str());
}
TEST(StdStream_Tests, JsonArray) {
std::ostringstream os;
DynamicJsonBuffer jsonBuffer;
JsonArray& array = jsonBuffer.createArray();
array.add("value");
os << array;
ASSERT_EQ("[\"value\"]", os.str());
}
SECTION("JsonArray") {
std::ostringstream os;
DynamicJsonBuffer jsonBuffer;
JsonArray& array = jsonBuffer.createArray();
array.add("value");
os << array;
REQUIRE("[\"value\"]" == os.str());
}
TEST(StdStream_Tests, JsonArraySubscript) {
std::ostringstream os;
DynamicJsonBuffer jsonBuffer;
JsonArray& array = jsonBuffer.createArray();
array.add("value");
os << array[0];
ASSERT_EQ("\"value\"", os.str());
}
SECTION("JsonArraySubscript") {
std::ostringstream os;
DynamicJsonBuffer jsonBuffer;
JsonArray& array = jsonBuffer.createArray();
array.add("value");
os << array[0];
REQUIRE("\"value\"" == os.str());
}
TEST(StdStream_Tests, ParseArray) {
std::istringstream json(" [ 42 /* comment */ ] ");
DynamicJsonBuffer jsonBuffer;
JsonArray& arr = jsonBuffer.parseArray(json);
ASSERT_TRUE(arr.success());
ASSERT_EQ(1, arr.size());
ASSERT_EQ(42, arr[0]);
}
SECTION("ParseArray") {
std::istringstream json(" [ 42 /* comment */ ] ");
DynamicJsonBuffer jsonBuffer;
JsonArray& arr = jsonBuffer.parseArray(json);
REQUIRE(true == arr.success());
REQUIRE(1 == arr.size());
REQUIRE(42 == arr[0]);
}
TEST(StdStream_Tests, ParseObject) {
std::istringstream json(" { hello : world // comment\n }");
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.parseObject(json);
ASSERT_TRUE(obj.success());
ASSERT_EQ(1, obj.size());
ASSERT_STREQ("world", obj["hello"]);
}
SECTION("ParseObject") {
std::istringstream json(" { hello : world // comment\n }");
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.parseObject(json);
REQUIRE(true == obj.success());
REQUIRE(1 == obj.size());
REQUIRE(std::string("world") == obj["hello"]);
}
TEST(StdStream_Tests, ShouldNotReadPastTheEnd) {
std::istringstream json("{}123");
DynamicJsonBuffer jsonBuffer;
jsonBuffer.parseObject(json);
ASSERT_EQ('1', json.get());
SECTION("ShouldNotReadPastTheEnd") {
std::istringstream json("{}123");
DynamicJsonBuffer jsonBuffer;
jsonBuffer.parseObject(json);
REQUIRE('1' == json.get());
}
}

View File

@ -6,247 +6,248 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
class StringTests : public ::testing::Test {
protected:
static void eraseString(std::string &str) {
char *p = const_cast<char *>(str.c_str());
while (*p) *p++ = '*';
static void eraseString(std::string &str) {
char *p = const_cast<char *>(str.c_str());
while (*p) *p++ = '*';
}
TEST_CASE("std::string") {
DynamicJsonBuffer jb;
SECTION("JsonBuffer_ParseArray") {
std::string json("[\"hello\"]");
JsonArray &array = jb.parseArray(json);
eraseString(json);
REQUIRE(true == array.success());
REQUIRE(std::string("hello") == array[0]);
}
DynamicJsonBuffer _jsonBuffer;
};
SECTION("JsonBuffer_ParseObject") {
std::string json("{\"hello\":\"world\"}");
JsonObject &object = jb.parseObject(json);
eraseString(json);
REQUIRE(true == object.success());
REQUIRE(std::string("world") == object["hello"]);
}
TEST_F(StringTests, JsonBuffer_ParseArray) {
std::string json("[\"hello\"]");
JsonArray &array = _jsonBuffer.parseArray(json);
eraseString(json);
ASSERT_TRUE(array.success());
ASSERT_STREQ("hello", array[0]);
}
TEST_F(StringTests, JsonBuffer_ParseObject) {
std::string json("{\"hello\":\"world\"}");
JsonObject &object = _jsonBuffer.parseObject(json);
eraseString(json);
ASSERT_TRUE(object.success());
ASSERT_STREQ("world", object["hello"]);
}
TEST_F(StringTests, JsonObject_Subscript) {
char json[] = "{\"key\":\"value\"}";
JsonObject &object = _jsonBuffer.parseObject(json);
ASSERT_STREQ("value", object[std::string("key")]);
}
TEST_F(StringTests, JsonObject_ConstSubscript) {
char json[] = "{\"key\":\"value\"}";
const JsonObject &object = _jsonBuffer.parseObject(json);
ASSERT_STREQ("value", object[std::string("key")]);
}
TEST_F(StringTests, JsonObject_SetKey) {
JsonObject &object = _jsonBuffer.createObject();
std::string key("hello");
object.set(key, "world");
eraseString(key);
ASSERT_STREQ("world", object["hello"]);
}
TEST_F(StringTests, JsonObject_SetValue) {
JsonObject &object = _jsonBuffer.createObject();
std::string value("world");
object.set("hello", value);
eraseString(value);
ASSERT_STREQ("world", object["hello"]);
}
TEST_F(StringTests, JsonObject_SetKeyValue) {
JsonObject &object = _jsonBuffer.createObject();
std::string key("hello");
std::string value("world");
object.set(key, value);
eraseString(key);
eraseString(value);
ASSERT_STREQ("world", object["hello"]);
}
TEST_F(StringTests, JsonObject_SetToArraySubscript) {
JsonArray &arr = _jsonBuffer.createArray();
arr.add("world");
JsonObject &object = _jsonBuffer.createObject();
object.set(std::string("hello"), arr[0]);
ASSERT_STREQ("world", object["hello"]);
}
TEST_F(StringTests, JsonObject_SetToObjectSubscript) {
JsonObject &arr = _jsonBuffer.createObject();
arr.set("x", "world");
JsonObject &object = _jsonBuffer.createObject();
object.set(std::string("hello"), arr["x"]);
ASSERT_STREQ("world", object["hello"]);
}
TEST_F(StringTests, JsonObject_Get) {
char json[] = "{\"key\":\"value\"}";
const JsonObject &object = _jsonBuffer.parseObject(json);
ASSERT_STREQ("value", object.get<const char *>(std::string("key")));
}
TEST_F(StringTests, JsonObject_GetT) {
char json[] = "{\"key\":\"value\"}";
const JsonObject &object = _jsonBuffer.parseObject(json);
ASSERT_STREQ("value", object.get<const char *>(std::string("key")));
}
TEST_F(StringTests, JsonObject_IsT) {
char json[] = "{\"key\":\"value\"}";
const JsonObject &object = _jsonBuffer.parseObject(json);
ASSERT_TRUE(object.is<const char *>(std::string("key")));
}
TEST_F(StringTests, JsonObject_CreateNestedObject) {
std::string key = "key";
char json[64];
JsonObject &object = _jsonBuffer.createObject();
object.createNestedObject(key);
eraseString(key);
object.printTo(json, sizeof(json));
ASSERT_STREQ("{\"key\":{}}", json);
}
TEST_F(StringTests, JsonObject_CreateNestedArray) {
std::string key = "key";
char json[64];
JsonObject &object = _jsonBuffer.createObject();
object.createNestedArray(key);
eraseString(key);
object.printTo(json, sizeof(json));
ASSERT_STREQ("{\"key\":[]}", json);
}
TEST_F(StringTests, JsonObject_ContainsKey) {
char json[] = "{\"key\":\"value\"}";
const JsonObject &object = _jsonBuffer.parseObject(json);
ASSERT_TRUE(object.containsKey(std::string("key")));
}
TEST_F(StringTests, JsonObject_Remove) {
char json[] = "{\"key\":\"value\"}";
JsonObject &object = _jsonBuffer.parseObject(json);
ASSERT_EQ(1, object.size());
object.remove(std::string("key"));
ASSERT_EQ(0, object.size());
}
TEST_F(StringTests, JsonObjectSubscript_SetKey) {
JsonObject &object = _jsonBuffer.createObject();
std::string key("hello");
object[key] = "world";
eraseString(key);
ASSERT_STREQ("world", object["hello"]);
}
TEST_F(StringTests, JsonObjectSubscript_SetValue) {
JsonObject &object = _jsonBuffer.createObject();
std::string value("world");
object["hello"] = value;
eraseString(value);
ASSERT_STREQ("world", object["hello"]);
}
TEST_F(StringTests, JsonArray_Add) {
JsonArray &array = _jsonBuffer.createArray();
std::string value("hello");
array.add(value);
eraseString(value);
ASSERT_STREQ("hello", array[0]);
}
TEST_F(StringTests, JsonArray_Set) {
JsonArray &array = _jsonBuffer.createArray();
std::string value("world");
array.add("hello");
array.set(0, value);
eraseString(value);
ASSERT_STREQ("world", array[0]);
}
TEST_F(StringTests, JsonArraySubscript) {
JsonArray &array = _jsonBuffer.createArray();
std::string value("world");
array.add("hello");
array[0] = value;
eraseString(value);
ASSERT_STREQ("world", array[0]);
}
TEST_F(StringTests, JsonArray_PrintTo) {
JsonArray &array = _jsonBuffer.createArray();
array.add(4);
array.add(2);
std::string json;
array.printTo(json);
ASSERT_EQ(std::string("[4,2]"), json);
}
TEST_F(StringTests, JsonArray_PrettyPrintTo) {
JsonArray &array = _jsonBuffer.createArray();
array.add(4);
array.add(2);
std::string json;
array.prettyPrintTo(json);
ASSERT_EQ(std::string("[\r\n 4,\r\n 2\r\n]"), json);
}
TEST_F(StringTests, JsonObject_PrintTo) {
JsonObject &object = _jsonBuffer.createObject();
object["key"] = "value";
std::string json;
object.printTo(json);
ASSERT_EQ(std::string("{\"key\":\"value\"}"), json);
}
TEST_F(StringTests, JsonObject_PrettyPrintTo) {
JsonObject &object = _jsonBuffer.createObject();
object["key"] = "value";
std::string json;
object.prettyPrintTo(json);
ASSERT_EQ(std::string("{\r\n \"key\": \"value\"\r\n}"), json);
}
TEST_F(StringTests, JsonBuffer_GrowWhenAddingNewKey) {
JsonObject &object = _jsonBuffer.createObject();
std::string key1("hello"), key2("world");
object[key1] = 1;
size_t sizeBefore = _jsonBuffer.size();
object[key2] = 2;
size_t sizeAfter = _jsonBuffer.size();
ASSERT_GT(sizeAfter - sizeBefore, key2.size());
}
TEST_F(StringTests, JsonBuffer_DontGrowWhenReusingKey) {
JsonObject &object = _jsonBuffer.createObject();
std::string key("hello");
object[key] = 1;
size_t sizeBefore = _jsonBuffer.size();
object[key] = 2;
size_t sizeAfter = _jsonBuffer.size();
ASSERT_EQ(sizeBefore, sizeAfter);
}
TEST_F(StringTests, JsonBuffer_strdup) {
std::string original("hello");
char *copy = _jsonBuffer.strdup(original);
original[0] = 'w';
ASSERT_STREQ("hello", copy);
SECTION("JsonObject_Subscript") {
char json[] = "{\"key\":\"value\"}";
JsonObject &object = jb.parseObject(json);
REQUIRE(std::string("value") == object[std::string("key")]);
}
SECTION("JsonObject_ConstSubscript") {
char json[] = "{\"key\":\"value\"}";
const JsonObject &object = jb.parseObject(json);
REQUIRE(std::string("value") == object[std::string("key")]);
}
SECTION("JsonObject_SetKey") {
JsonObject &object = jb.createObject();
std::string key("hello");
object.set(key, "world");
eraseString(key);
REQUIRE(std::string("world") == object["hello"]);
}
SECTION("JsonObject_SetValue") {
JsonObject &object = jb.createObject();
std::string value("world");
object.set("hello", value);
eraseString(value);
REQUIRE(std::string("world") == object["hello"]);
}
SECTION("JsonObject_SetKeyValue") {
JsonObject &object = jb.createObject();
std::string key("hello");
std::string value("world");
object.set(key, value);
eraseString(key);
eraseString(value);
REQUIRE(std::string("world") == object["hello"]);
}
SECTION("JsonObject_SetToArraySubscript") {
JsonArray &arr = jb.createArray();
arr.add("world");
JsonObject &object = jb.createObject();
object.set(std::string("hello"), arr[0]);
REQUIRE(std::string("world") == object["hello"]);
}
SECTION("JsonObject_SetToObjectSubscript") {
JsonObject &arr = jb.createObject();
arr.set("x", "world");
JsonObject &object = jb.createObject();
object.set(std::string("hello"), arr["x"]);
REQUIRE(std::string("world") == object["hello"]);
}
SECTION("JsonObject_Get") {
char json[] = "{\"key\":\"value\"}";
const JsonObject &object = jb.parseObject(json);
REQUIRE(std::string("value") ==
object.get<const char *>(std::string("key")));
}
SECTION("JsonObject_GetT") {
char json[] = "{\"key\":\"value\"}";
const JsonObject &object = jb.parseObject(json);
REQUIRE(std::string("value") ==
object.get<const char *>(std::string("key")));
}
SECTION("JsonObject_IsT") {
char json[] = "{\"key\":\"value\"}";
const JsonObject &object = jb.parseObject(json);
REQUIRE(true == object.is<const char *>(std::string("key")));
}
SECTION("JsonObject_CreateNestedObject") {
std::string key = "key";
char json[64];
JsonObject &object = jb.createObject();
object.createNestedObject(key);
eraseString(key);
object.printTo(json, sizeof(json));
REQUIRE(std::string("{\"key\":{}}") == json);
}
SECTION("JsonObject_CreateNestedArray") {
std::string key = "key";
char json[64];
JsonObject &object = jb.createObject();
object.createNestedArray(key);
eraseString(key);
object.printTo(json, sizeof(json));
REQUIRE(std::string("{\"key\":[]}") == json);
}
SECTION("JsonObject_ContainsKey") {
char json[] = "{\"key\":\"value\"}";
const JsonObject &object = jb.parseObject(json);
REQUIRE(true == object.containsKey(std::string("key")));
}
SECTION("JsonObject_Remove") {
char json[] = "{\"key\":\"value\"}";
JsonObject &object = jb.parseObject(json);
REQUIRE(1 == object.size());
object.remove(std::string("key"));
REQUIRE(0 == object.size());
}
SECTION("JsonObjectSubscript_SetKey") {
JsonObject &object = jb.createObject();
std::string key("hello");
object[key] = "world";
eraseString(key);
REQUIRE(std::string("world") == object["hello"]);
}
SECTION("JsonObjectSubscript_SetValue") {
JsonObject &object = jb.createObject();
std::string value("world");
object["hello"] = value;
eraseString(value);
REQUIRE(std::string("world") == object["hello"]);
}
SECTION("JsonArray_Add") {
JsonArray &array = jb.createArray();
std::string value("hello");
array.add(value);
eraseString(value);
REQUIRE(std::string("hello") == array[0]);
}
SECTION("JsonArray_Set") {
JsonArray &array = jb.createArray();
std::string value("world");
array.add("hello");
array.set(0, value);
eraseString(value);
REQUIRE(std::string("world") == array[0]);
}
SECTION("JsonArraySubscript") {
JsonArray &array = jb.createArray();
std::string value("world");
array.add("hello");
array[0] = value;
eraseString(value);
REQUIRE(std::string("world") == array[0]);
}
SECTION("JsonArray_PrintTo") {
JsonArray &array = jb.createArray();
array.add(4);
array.add(2);
std::string json;
array.printTo(json);
REQUIRE(std::string("[4,2]") == json);
}
SECTION("JsonArray_PrettyPrintTo") {
JsonArray &array = jb.createArray();
array.add(4);
array.add(2);
std::string json;
array.prettyPrintTo(json);
REQUIRE(std::string("[\r\n 4,\r\n 2\r\n]") == json);
}
SECTION("JsonObject_PrintTo") {
JsonObject &object = jb.createObject();
object["key"] = "value";
std::string json;
object.printTo(json);
REQUIRE(std::string("{\"key\":\"value\"}") == json);
}
SECTION("JsonObject_PrettyPrintTo") {
JsonObject &object = jb.createObject();
object["key"] = "value";
std::string json;
object.prettyPrintTo(json);
REQUIRE(std::string("{\r\n \"key\": \"value\"\r\n}") == json);
}
SECTION("JsonBuffer_GrowWhenAddingNewKey") {
JsonObject &object = jb.createObject();
std::string key1("hello"), key2("world");
object[key1] = 1;
size_t sizeBefore = jb.size();
object[key2] = 2;
size_t sizeAfter = jb.size();
REQUIRE(sizeAfter - sizeBefore >= key2.size());
}
SECTION("JsonBuffer_DontGrowWhenReusingKey") {
JsonObject &object = jb.createObject();
std::string key("hello");
object[key] = 1;
size_t sizeBefore = jb.size();
object[key] = 2;
size_t sizeAfter = jb.size();
REQUIRE(sizeBefore == sizeAfter);
}
SECTION("JsonBuffer_strdup") {
std::string original("hello");
char *copy = jb.strdup(original);
original[0] = 'w';
REQUIRE(std::string("hello") == copy);
}
}

View File

@ -6,278 +6,280 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
#if defined(__clang__)
#define CONFLICTS_WITH_BUILTIN_OPERATOR
#endif
TEST(UnsignedCharArray, ParseArray) {
unsigned char json[] = "[42]";
TEST_CASE("unsigned char string") {
SECTION("JsonBuffer::parseArray") {
unsigned char json[] = "[42]";
StaticJsonBuffer<JSON_ARRAY_SIZE(1)> jsonBuffer;
JsonArray& arr = jsonBuffer.parseArray(json);
StaticJsonBuffer<JSON_ARRAY_SIZE(1)> jsonBuffer;
JsonArray& arr = jsonBuffer.parseArray(json);
EXPECT_TRUE(arr.success());
}
REQUIRE(true == arr.success());
}
TEST(UnsignedCharArray, ParseObject) {
unsigned char json[] = "{\"a\":42}";
SECTION("JsonBuffer::parseObject") {
unsigned char json[] = "{\"a\":42}";
StaticJsonBuffer<JSON_OBJECT_SIZE(1)> jsonBuffer;
JsonObject& obj = jsonBuffer.parseObject(json);
StaticJsonBuffer<JSON_OBJECT_SIZE(1)> jsonBuffer;
JsonObject& obj = jsonBuffer.parseObject(json);
EXPECT_TRUE(obj.success());
}
REQUIRE(true == obj.success());
}
TEST(UnsignedCharArray, JsonVariant_Constructor) {
unsigned char value[] = "42";
SECTION("JsonVariant constructor") {
unsigned char value[] = "42";
JsonVariant variant(value);
JsonVariant variant(value);
EXPECT_EQ(42, variant.as<int>());
}
REQUIRE(42 == variant.as<int>());
}
TEST(UnsignedCharArray, JsonVariant_Assign) {
unsigned char value[] = "42";
SECTION("JsonVariant assignment operator") {
unsigned char value[] = "42";
JsonVariant variant(666);
variant = value;
JsonVariant variant(666);
variant = value;
EXPECT_EQ(42, variant.as<int>());
}
REQUIRE(42 == variant.as<int>());
}
#ifndef CONFLICTS_WITH_BUILTIN_OPERATOR
TEST(UnsignedCharArray, JsonVariant_Subscript) {
unsigned char key[] = "hello";
SECTION("JsonVariant::operator[]") {
unsigned char key[] = "hello";
DynamicJsonBuffer jsonBuffer;
JsonVariant variant = jsonBuffer.parseObject("{\"hello\":\"world\"}");
DynamicJsonBuffer jsonBuffer;
JsonVariant variant = jsonBuffer.parseObject("{\"hello\":\"world\"}");
EXPECT_STREQ("world", variant[key]);
}
REQUIRE(std::string("world") == variant[key]);
}
#endif
#ifndef CONFLICTS_WITH_BUILTIN_OPERATOR
TEST(UnsignedCharArray, JsonVariant_Subscript_Const) {
unsigned char key[] = "hello";
SECTION("JsonVariant::operator[] const") {
unsigned char key[] = "hello";
DynamicJsonBuffer jsonBuffer;
const JsonVariant variant = jsonBuffer.parseObject("{\"hello\":\"world\"}");
DynamicJsonBuffer jsonBuffer;
const JsonVariant variant = jsonBuffer.parseObject("{\"hello\":\"world\"}");
EXPECT_STREQ("world", variant[key]);
}
REQUIRE(std::string("world") == variant[key]);
}
#endif
TEST(UnsignedCharArray, JsonVariant_Equals) {
unsigned char comparand[] = "hello";
SECTION("JsonVariant::operator==") {
unsigned char comparand[] = "hello";
DynamicJsonBuffer jsonBuffer;
const JsonVariant variant = "hello";
DynamicJsonBuffer jsonBuffer;
const JsonVariant variant = "hello";
EXPECT_TRUE(comparand == variant);
EXPECT_TRUE(variant == comparand);
EXPECT_FALSE(comparand != variant);
EXPECT_FALSE(variant != comparand);
}
REQUIRE(comparand == variant);
REQUIRE(variant == comparand);
REQUIRE_FALSE(comparand != variant);
REQUIRE_FALSE(variant != comparand);
}
TEST(UnsignedCharArray, JsonVariant_Differs) {
unsigned char comparand[] = "hello";
SECTION("JsonVariant::operator!=") {
unsigned char comparand[] = "hello";
DynamicJsonBuffer jsonBuffer;
const JsonVariant variant = "world";
DynamicJsonBuffer jsonBuffer;
const JsonVariant variant = "world";
EXPECT_TRUE(comparand != variant);
EXPECT_TRUE(variant != comparand);
EXPECT_FALSE(comparand == variant);
EXPECT_FALSE(variant == comparand);
}
REQUIRE(comparand != variant);
REQUIRE(variant != comparand);
REQUIRE_FALSE(comparand == variant);
REQUIRE_FALSE(variant == comparand);
}
#ifndef CONFLICTS_WITH_BUILTIN_OPERATOR
TEST(UnsignedCharArray, JsonObject_Subscript) {
unsigned char key[] = "hello";
SECTION("JsonObject::operator[]") {
unsigned char key[] = "hello";
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj[key] = "world";
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj[key] = "world";
EXPECT_STREQ("world", obj["hello"]);
}
REQUIRE(std::string("world") == obj["hello"]);
}
#endif
TEST(UnsignedCharArray, JsonObject_Subscript_Assign) { // issue #416
unsigned char value[] = "world";
SECTION("JsonObjectSubscript::operator=") { // issue #416
unsigned char value[] = "world";
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj["hello"] = value;
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj["hello"] = value;
EXPECT_STREQ("world", obj["hello"]);
}
REQUIRE(std::string("world") == obj["hello"]);
}
TEST(UnsignedCharArray, JsonObject_Subscript_Set) {
unsigned char value[] = "world";
SECTION("JsonObjectSubscript::set()") {
unsigned char value[] = "world";
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj["hello"].set(value);
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj["hello"].set(value);
EXPECT_STREQ("world", obj["hello"]);
}
REQUIRE(std::string("world") == obj["hello"]);
}
#ifndef CONFLICTS_WITH_BUILTIN_OPERATOR
TEST(UnsignedCharArray, JsonObject_Subscript_Const) {
unsigned char key[] = "hello";
SECTION("JsonObject::operator[] const") {
unsigned char key[] = "hello";
DynamicJsonBuffer jsonBuffer;
const JsonObject& obj = jsonBuffer.parseObject("{\"hello\":\"world\"}");
DynamicJsonBuffer jsonBuffer;
const JsonObject& obj = jsonBuffer.parseObject("{\"hello\":\"world\"}");
EXPECT_STREQ("world", obj[key]);
}
REQUIRE(std::string("world") == obj[key]);
}
#endif
TEST(UnsignedCharArray, JsonObject_Get) {
unsigned char key[] = "hello";
SECTION("JsonObject::get()") {
unsigned char key[] = "hello";
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.parseObject("{\"hello\":\"world\"}");
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.parseObject("{\"hello\":\"world\"}");
EXPECT_STREQ("world", obj.get<char*>(key));
}
TEST(UnsignedCharArray, JsonObject_Set_Key) {
unsigned char key[] = "hello";
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj.set(key, "world");
EXPECT_STREQ("world", obj["hello"]);
}
TEST(UnsignedCharArray, JsonObject_Set_Value) {
unsigned char value[] = "world";
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj.set("hello", value);
EXPECT_STREQ("world", obj["hello"]);
}
TEST(UnsignedCharArray, JsonObject_Set_Key_WithDecimals) {
unsigned char key[] = "hello";
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj.set(key, 3.14, 2);
EXPECT_EQ(3.14, obj["hello"]);
}
TEST(UnsignedCharArray, JsonObject_Set_KeyAndValue) {
unsigned char key[] = "world";
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj.set(key, key);
EXPECT_STREQ("world", obj["world"]);
}
TEST(UnsignedCharArray, JsonObject_ContainsKey) {
unsigned char key[] = "hello";
DynamicJsonBuffer jsonBuffer;
const JsonObject& obj = jsonBuffer.parseObject("{\"hello\":\"world\"}");
EXPECT_TRUE(obj.containsKey(key));
}
TEST(UnsignedCharArray, JsonObject_Remove) {
unsigned char key[] = "hello";
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.parseObject("{\"hello\":\"world\"}");
obj.remove(key);
EXPECT_EQ(0, obj.size());
}
TEST(UnsignedCharArray, JsonObject_Is) {
unsigned char key[] = "hello";
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.parseObject("{\"hello\":42}");
EXPECT_TRUE(obj.is<int>(key));
}
TEST(UnsignedCharArray, JsonObject_CreateNestedArray) {
unsigned char key[] = "hello";
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj.createNestedArray(key);
}
TEST(UnsignedCharArray, JsonObject_CreateNestedObject) {
unsigned char key[] = "hello";
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj.createNestedObject(key);
}
TEST(UnsignedCharArray, JsonArray_Add) {
unsigned char value[] = "world";
DynamicJsonBuffer jsonBuffer;
JsonArray& arr = jsonBuffer.createArray();
arr.add(value);
EXPECT_STREQ("world", arr[0]);
}
TEST(UnsignedCharArray, JsonArray_Set) {
unsigned char value[] = "world";
DynamicJsonBuffer jsonBuffer;
JsonArray& arr = jsonBuffer.createArray();
arr.add("hello");
arr.set(0, value);
EXPECT_STREQ("world", arr[0]);
}
TEST(UnsignedCharArray, JsonArraySubscript_Set) {
unsigned char value[] = "world";
DynamicJsonBuffer jsonBuffer;
JsonArray& arr = jsonBuffer.createArray();
arr.add("hello");
arr[0].set(value);
EXPECT_STREQ("world", arr[0]);
}
TEST(UnsignedCharArray, JsonArraySubscript_Assign) {
unsigned char value[] = "world";
DynamicJsonBuffer jsonBuffer;
JsonArray& arr = jsonBuffer.createArray();
arr.add("hello");
arr[0] = value;
EXPECT_STREQ("world", arr[0]);
}
TEST(UnsignedCharArray, JsonBuffer_strdup) {
unsigned char value[] = "world";
DynamicJsonBuffer jsonBuffer;
const char* dup = jsonBuffer.strdup(value);
EXPECT_NE(static_cast<const void*>(value), static_cast<const void*>(dup));
EXPECT_STREQ("world", dup);
REQUIRE(std::string("world") == obj.get<char*>(key));
}
SECTION("JsonObject::set() key") {
unsigned char key[] = "hello";
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj.set(key, "world");
REQUIRE(std::string("world") == obj["hello"]);
}
SECTION("JsonObject::set() value") {
unsigned char value[] = "world";
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj.set("hello", value);
REQUIRE(std::string("world") == obj["hello"]);
}
SECTION("JsonObject::set() key with decimals") {
unsigned char key[] = "hello";
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj.set(key, 3.14, 2);
REQUIRE(3.14 == obj["hello"]);
}
SECTION("JsonObject::set key&value") {
unsigned char key[] = "world";
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj.set(key, key);
REQUIRE(std::string("world") == obj["world"]);
}
SECTION("JsonObject::containsKey()") {
unsigned char key[] = "hello";
DynamicJsonBuffer jsonBuffer;
const JsonObject& obj = jsonBuffer.parseObject("{\"hello\":\"world\"}");
REQUIRE(true == obj.containsKey(key));
}
SECTION("JsonObject::remove()") {
unsigned char key[] = "hello";
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.parseObject("{\"hello\":\"world\"}");
obj.remove(key);
REQUIRE(0 == obj.size());
}
SECTION("JsonObject::is()") {
unsigned char key[] = "hello";
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.parseObject("{\"hello\":42}");
REQUIRE(true == obj.is<int>(key));
}
SECTION("JsonObject::createNestedArray()") {
unsigned char key[] = "hello";
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj.createNestedArray(key);
}
SECTION("JsonObject::createNestedObject()") {
unsigned char key[] = "hello";
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj.createNestedObject(key);
}
SECTION("JsonArray::add()") {
unsigned char value[] = "world";
DynamicJsonBuffer jsonBuffer;
JsonArray& arr = jsonBuffer.createArray();
arr.add(value);
REQUIRE(std::string("world") == arr[0]);
}
SECTION("JsonArray::set()") {
unsigned char value[] = "world";
DynamicJsonBuffer jsonBuffer;
JsonArray& arr = jsonBuffer.createArray();
arr.add("hello");
arr.set(0, value);
REQUIRE(std::string("world") == arr[0]);
}
SECTION("JsonArraySubscript::set()") {
unsigned char value[] = "world";
DynamicJsonBuffer jsonBuffer;
JsonArray& arr = jsonBuffer.createArray();
arr.add("hello");
arr[0].set(value);
REQUIRE(std::string("world") == arr[0]);
}
SECTION("JsonArraySubscript::operator=") {
unsigned char value[] = "world";
DynamicJsonBuffer jsonBuffer;
JsonArray& arr = jsonBuffer.createArray();
arr.add("hello");
arr[0] = value;
REQUIRE(std::string("world") == arr[0]);
}
SECTION("JsonBuffer::strdup()") {
unsigned char value[] = "world";
DynamicJsonBuffer jsonBuffer;
const char* dup = jsonBuffer.strdup(value);
REQUIRE(static_cast<const void*>(value) != static_cast<const void*>(dup));
REQUIRE(std::string("world") == dup);
}
}

View File

@ -6,7 +6,7 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
#if defined(__clang__)
#pragma clang diagnostic ignored "-Wvla-extension"
@ -19,339 +19,340 @@
#ifndef VLA_NOT_SUPPORTED
TEST(VariableLengthArray, ParseArray) {
int i = 8;
char vla[i];
strcpy(vla, "[42]");
TEST_CASE("Variable Length Array") {
SECTION("ParseArray") {
int i = 8;
char vla[i];
strcpy(vla, "[42]");
StaticJsonBuffer<JSON_ARRAY_SIZE(1)> jsonBuffer;
JsonArray& arr = jsonBuffer.parseArray(vla);
StaticJsonBuffer<JSON_ARRAY_SIZE(1)> jsonBuffer;
JsonArray& arr = jsonBuffer.parseArray(vla);
EXPECT_TRUE(arr.success());
}
REQUIRE(true == arr.success());
}
TEST(VariableLengthArray, ParseObject) {
int i = 16;
char vla[i];
strcpy(vla, "{\"a\":42}");
SECTION("ParseObject") {
int i = 16;
char vla[i];
strcpy(vla, "{\"a\":42}");
StaticJsonBuffer<JSON_OBJECT_SIZE(1)> jsonBuffer;
JsonObject& obj = jsonBuffer.parseObject(vla);
StaticJsonBuffer<JSON_OBJECT_SIZE(1)> jsonBuffer;
JsonObject& obj = jsonBuffer.parseObject(vla);
EXPECT_TRUE(obj.success());
}
REQUIRE(true == obj.success());
}
TEST(VariableLengthArray, Parse) {
int i = 16;
char vla[i];
strcpy(vla, "42");
SECTION("Parse") {
int i = 16;
char vla[i];
strcpy(vla, "42");
StaticJsonBuffer<1> jsonBuffer;
JsonVariant variant = jsonBuffer.parse(vla);
StaticJsonBuffer<1> jsonBuffer;
JsonVariant variant = jsonBuffer.parse(vla);
EXPECT_EQ(42, variant.as<int>());
}
REQUIRE(42 == variant.as<int>());
}
TEST(VariableLengthArray, JsonVariant_Constructor) {
int i = 16;
char vla[i];
strcpy(vla, "42");
SECTION("JsonVariant_Constructor") {
int i = 16;
char vla[i];
strcpy(vla, "42");
JsonVariant variant(vla);
JsonVariant variant(vla);
EXPECT_EQ(42, variant.as<int>());
}
REQUIRE(42 == variant.as<int>());
}
TEST(VariableLengthArray, JsonVariant_Assign) {
int i = 16;
char vla[i];
strcpy(vla, "42");
SECTION("JsonVariant_Assign") {
int i = 16;
char vla[i];
strcpy(vla, "42");
JsonVariant variant(666);
variant = vla;
JsonVariant variant(666);
variant = vla;
EXPECT_EQ(42, variant.as<int>());
}
REQUIRE(42 == variant.as<int>());
}
#ifndef CONFLICTS_WITH_BUILTIN_OPERATOR
TEST(VariableLengthArray, JsonVariant_Subscript) {
int i = 16;
char vla[i];
strcpy(vla, "hello");
SECTION("JsonVariant_Subscript") {
int i = 16;
char vla[i];
strcpy(vla, "hello");
DynamicJsonBuffer jsonBuffer;
JsonVariant variant = jsonBuffer.parseObject("{\"hello\":\"world\"}");
DynamicJsonBuffer jsonBuffer;
JsonVariant variant = jsonBuffer.parseObject("{\"hello\":\"world\"}");
EXPECT_STREQ("world", variant[vla]);
}
REQUIRE(std::string("world") == variant[vla]);
}
#endif
#ifndef CONFLICTS_WITH_BUILTIN_OPERATOR
TEST(VariableLengthArray, JsonVariant_Subscript_Const) {
int i = 16;
char vla[i];
strcpy(vla, "hello");
SECTION("JsonVariant_Subscript_Const") {
int i = 16;
char vla[i];
strcpy(vla, "hello");
DynamicJsonBuffer jsonBuffer;
const JsonVariant variant = jsonBuffer.parseObject("{\"hello\":\"world\"}");
DynamicJsonBuffer jsonBuffer;
const JsonVariant variant = jsonBuffer.parseObject("{\"hello\":\"world\"}");
EXPECT_STREQ("world", variant[vla]);
}
REQUIRE(std::string("world") == variant[vla]);
}
#endif
TEST(VariableLengthArray, JsonVariant_Equals) {
int i = 16;
char vla[i];
strcpy(vla, "hello");
SECTION("JsonVariant_Equals") {
int i = 16;
char vla[i];
strcpy(vla, "hello");
DynamicJsonBuffer jsonBuffer;
const JsonVariant variant = "hello";
DynamicJsonBuffer jsonBuffer;
const JsonVariant variant = "hello";
EXPECT_TRUE(vla == variant);
EXPECT_TRUE(variant == vla);
EXPECT_FALSE(vla != variant);
EXPECT_FALSE(variant != vla);
}
REQUIRE((vla == variant));
REQUIRE((variant == vla));
REQUIRE_FALSE((vla != variant));
REQUIRE_FALSE((variant != vla));
}
TEST(VariableLengthArray, JsonVariant_Differs) {
int i = 16;
char vla[i];
strcpy(vla, "hello");
SECTION("JsonVariant_Differs") {
int i = 16;
char vla[i];
strcpy(vla, "hello");
DynamicJsonBuffer jsonBuffer;
const JsonVariant variant = "world";
DynamicJsonBuffer jsonBuffer;
const JsonVariant variant = "world";
EXPECT_TRUE(vla != variant);
EXPECT_TRUE(variant != vla);
EXPECT_FALSE(vla == variant);
EXPECT_FALSE(variant == vla);
}
REQUIRE((vla != variant));
REQUIRE((variant != vla));
REQUIRE_FALSE((vla == variant));
REQUIRE_FALSE((variant == vla));
}
#ifndef CONFLICTS_WITH_BUILTIN_OPERATOR
TEST(VariableLengthArray, JsonObject_Subscript) {
int i = 16;
char vla[i];
strcpy(vla, "hello");
SECTION("JsonObject_Subscript") {
int i = 16;
char vla[i];
strcpy(vla, "hello");
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj[vla] = "world";
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj[vla] = "world";
EXPECT_STREQ("world", obj["hello"]);
}
REQUIRE(std::string("world") == obj["hello"]);
}
#endif
TEST(VariableLengthArray, JsonObject_Subscript_Assign) { // issue #416
int i = 32;
char vla[i];
strcpy(vla, "world");
SECTION("JsonObject_Subscript_Assign") { // issue #416
int i = 32;
char vla[i];
strcpy(vla, "world");
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj["hello"] = vla;
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj["hello"] = vla;
EXPECT_STREQ("world", obj["hello"].as<char*>());
}
REQUIRE(std::string("world") == obj["hello"].as<char*>());
}
TEST(VariableLengthArray, JsonObject_Subscript_Set) {
int i = 32;
char vla[i];
strcpy(vla, "world");
SECTION("JsonObject_Subscript_Set") {
int i = 32;
char vla[i];
strcpy(vla, "world");
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj["hello"].set(vla);
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj["hello"].set(vla);
EXPECT_STREQ("world", obj["hello"].as<char*>());
}
REQUIRE(std::string("world") == obj["hello"].as<char*>());
}
#ifndef CONFLICTS_WITH_BUILTIN_OPERATOR
TEST(VariableLengthArray, JsonObject_Subscript_Const) {
int i = 16;
char vla[i];
strcpy(vla, "hello");
SECTION("JsonObject_Subscript_Const") {
int i = 16;
char vla[i];
strcpy(vla, "hello");
DynamicJsonBuffer jsonBuffer;
const JsonObject& obj = jsonBuffer.parseObject("{\"hello\":\"world\"}");
DynamicJsonBuffer jsonBuffer;
const JsonObject& obj = jsonBuffer.parseObject("{\"hello\":\"world\"}");
EXPECT_STREQ("world", obj[vla]);
}
REQUIRE(std::string("world") == obj[vla]);
}
#endif
TEST(VariableLengthArray, JsonObject_Get) {
int i = 16;
char vla[i];
strcpy(vla, "hello");
SECTION("JsonObject_Get") {
int i = 16;
char vla[i];
strcpy(vla, "hello");
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.parseObject("{\"hello\":\"world\"}");
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.parseObject("{\"hello\":\"world\"}");
EXPECT_STREQ("world", obj.get<char*>(vla));
REQUIRE(std::string("world") == obj.get<char*>(vla));
}
SECTION("JsonObject_Set_Key") {
int i = 16;
char vla[i];
strcpy(vla, "hello");
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj.set(vla, "world");
REQUIRE(std::string("world") == obj["hello"]);
}
SECTION("JsonObject_Set_Value") {
int i = 16;
char vla[i];
strcpy(vla, "world");
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj.set("hello", vla);
REQUIRE(std::string("world") == obj["hello"]);
}
SECTION("JsonObject_Set_Key_WithDecimals") {
int i = 16;
char vla[i];
strcpy(vla, "hello");
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj.set(vla, 3.14, 2);
REQUIRE(3.14 == obj["hello"]);
}
SECTION("JsonObject_Set_KeyAndValue") {
int i = 16;
char vla[i];
strcpy(vla, "world");
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj.set(vla, vla);
REQUIRE(std::string("world") == obj["world"]);
}
SECTION("JsonObject_ContainsKey") {
int i = 16;
char vla[i];
strcpy(vla, "hello");
DynamicJsonBuffer jsonBuffer;
const JsonObject& obj = jsonBuffer.parseObject("{\"hello\":\"world\"}");
REQUIRE(true == obj.containsKey(vla));
}
SECTION("JsonObject_Remove") {
int i = 16;
char vla[i];
strcpy(vla, "hello");
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.parseObject("{\"hello\":\"world\"}");
obj.remove(vla);
REQUIRE(0 == obj.size());
}
SECTION("JsonObject_Is") {
int i = 16;
char vla[i];
strcpy(vla, "hello");
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.parseObject("{\"hello\":42}");
REQUIRE(true == obj.is<int>(vla));
}
SECTION("JsonObject_CreateNestedArray") {
int i = 16;
char vla[i];
strcpy(vla, "hello");
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj.createNestedArray(vla);
}
SECTION("JsonObject_CreateNestedObject") {
int i = 16;
char vla[i];
strcpy(vla, "hello");
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj.createNestedObject(vla);
}
SECTION("JsonArray_Add") {
int i = 16;
char vla[i];
strcpy(vla, "world");
DynamicJsonBuffer jsonBuffer;
JsonArray& arr = jsonBuffer.createArray();
arr.add(vla);
REQUIRE(std::string("world") == arr[0]);
}
SECTION("JsonArray_Set") {
int i = 16;
char vla[i];
strcpy(vla, "world");
DynamicJsonBuffer jsonBuffer;
JsonArray& arr = jsonBuffer.createArray();
arr.add("hello");
arr.set(0, vla);
REQUIRE(std::string("world") == arr[0]);
}
SECTION("JsonArraySubscript_Set") {
int i = 16;
char vla[i];
strcpy(vla, "world");
DynamicJsonBuffer jsonBuffer;
JsonArray& arr = jsonBuffer.createArray();
arr.add("hello");
arr[0].set(vla);
REQUIRE(std::string("world") == arr[0]);
}
SECTION("JsonArraySubscript_Assign") {
int i = 16;
char vla[i];
strcpy(vla, "world");
DynamicJsonBuffer jsonBuffer;
JsonArray& arr = jsonBuffer.createArray();
arr.add("hello");
arr[0] = vla;
REQUIRE(std::string("world") == arr[0]);
}
SECTION("JsonBuffer_strdup") {
int i = 16;
char vla[i];
strcpy(vla, "world");
DynamicJsonBuffer jsonBuffer;
const char* dup = jsonBuffer.strdup(vla);
REQUIRE(static_cast<const void*>(vla) != static_cast<const void*>(dup));
REQUIRE(std::string("world") == dup);
}
}
TEST(VariableLengthArray, JsonObject_Set_Key) {
int i = 16;
char vla[i];
strcpy(vla, "hello");
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj.set(vla, "world");
EXPECT_STREQ("world", obj["hello"]);
}
TEST(VariableLengthArray, JsonObject_Set_Value) {
int i = 16;
char vla[i];
strcpy(vla, "world");
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj.set("hello", vla);
EXPECT_STREQ("world", obj["hello"]);
}
TEST(VariableLengthArray, JsonObject_Set_Key_WithDecimals) {
int i = 16;
char vla[i];
strcpy(vla, "hello");
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj.set(vla, 3.14, 2);
EXPECT_EQ(3.14, obj["hello"]);
}
TEST(VariableLengthArray, JsonObject_Set_KeyAndValue) {
int i = 16;
char vla[i];
strcpy(vla, "world");
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj.set(vla, vla);
EXPECT_STREQ("world", obj["world"]);
}
TEST(VariableLengthArray, JsonObject_ContainsKey) {
int i = 16;
char vla[i];
strcpy(vla, "hello");
DynamicJsonBuffer jsonBuffer;
const JsonObject& obj = jsonBuffer.parseObject("{\"hello\":\"world\"}");
EXPECT_TRUE(obj.containsKey(vla));
}
TEST(VariableLengthArray, JsonObject_Remove) {
int i = 16;
char vla[i];
strcpy(vla, "hello");
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.parseObject("{\"hello\":\"world\"}");
obj.remove(vla);
EXPECT_EQ(0, obj.size());
}
TEST(VariableLengthArray, JsonObject_Is) {
int i = 16;
char vla[i];
strcpy(vla, "hello");
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.parseObject("{\"hello\":42}");
EXPECT_TRUE(obj.is<int>(vla));
}
TEST(VariableLengthArray, JsonObject_CreateNestedArray) {
int i = 16;
char vla[i];
strcpy(vla, "hello");
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj.createNestedArray(vla);
}
TEST(VariableLengthArray, JsonObject_CreateNestedObject) {
int i = 16;
char vla[i];
strcpy(vla, "hello");
DynamicJsonBuffer jsonBuffer;
JsonObject& obj = jsonBuffer.createObject();
obj.createNestedObject(vla);
}
TEST(VariableLengthArray, JsonArray_Add) {
int i = 16;
char vla[i];
strcpy(vla, "world");
DynamicJsonBuffer jsonBuffer;
JsonArray& arr = jsonBuffer.createArray();
arr.add(vla);
EXPECT_STREQ("world", arr[0]);
}
TEST(VariableLengthArray, JsonArray_Set) {
int i = 16;
char vla[i];
strcpy(vla, "world");
DynamicJsonBuffer jsonBuffer;
JsonArray& arr = jsonBuffer.createArray();
arr.add("hello");
arr.set(0, vla);
EXPECT_STREQ("world", arr[0]);
}
TEST(VariableLengthArray, JsonArraySubscript_Set) {
int i = 16;
char vla[i];
strcpy(vla, "world");
DynamicJsonBuffer jsonBuffer;
JsonArray& arr = jsonBuffer.createArray();
arr.add("hello");
arr[0].set(vla);
EXPECT_STREQ("world", arr[0]);
}
TEST(VariableLengthArray, JsonArraySubscript_Assign) {
int i = 16;
char vla[i];
strcpy(vla, "world");
DynamicJsonBuffer jsonBuffer;
JsonArray& arr = jsonBuffer.createArray();
arr.add("hello");
arr[0] = vla;
EXPECT_STREQ("world", arr[0]);
}
TEST(VariableLengthArray, JsonBuffer_strdup) {
int i = 16;
char vla[i];
strcpy(vla, "world");
DynamicJsonBuffer jsonBuffer;
const char* dup = jsonBuffer.strdup(vla);
EXPECT_NE(static_cast<const void*>(vla), static_cast<const void*>(dup));
EXPECT_STREQ("world", dup);
}
#endif

View File

@ -12,5 +12,5 @@ add_executable(PolyfillsTests
parseInteger.cpp
)
target_link_libraries(PolyfillsTests gtest)
target_link_libraries(PolyfillsTests catch)
add_test(Polyfills PolyfillsTests)

View File

@ -5,81 +5,75 @@
// https://bblanchon.github.io/ArduinoJson/
// If you like this project, please add a star!
#include <gtest/gtest.h>
#include <ArduinoJson/Polyfills/isFloat.hpp>
#include <catch.hpp>
using namespace ArduinoJson::Polyfills;
struct Polyfills_IsFloat_Tests : testing::Test {
void check(bool expected, const char* input) {
bool actual = isFloat(input);
EXPECT_EQ(expected, actual) << input;
TEST_CASE("isFloat()") {
SECTION("Input is NULL") {
REQUIRE(isFloat(NULL) == false);
}
};
#define TEST_(X) TEST_F(Polyfills_IsFloat_Tests, X)
TEST_(Null) {
check(false, NULL);
}
SECTION("NoExponent") {
REQUIRE(isFloat("3.14"));
REQUIRE(isFloat("-3.14"));
REQUIRE(isFloat("+3.14"));
}
TEST_(NoExponent) {
check(true, "3.14");
check(true, "-3.14");
check(true, "+3.14");
}
SECTION("IntegralPartMissing") {
REQUIRE(isFloat(".14"));
REQUIRE(isFloat("-.14"));
REQUIRE(isFloat("+.14"));
}
TEST_(IntegralPartMissing) {
check(true, ".14");
check(true, "-.14");
check(true, "+.14");
}
SECTION("FractionalPartMissing") {
REQUIRE(isFloat("3."));
REQUIRE(isFloat("-3.e14"));
REQUIRE(isFloat("+3.e-14"));
}
TEST_(FractionalPartMissing) {
check(true, "3.");
check(true, "-3.e14");
check(true, "+3.e-14");
}
SECTION("NoDot") {
REQUIRE(isFloat("3e14"));
REQUIRE(isFloat("3e-14"));
REQUIRE(isFloat("3e+14"));
}
TEST_(NoDot) {
check(true, "3e14");
check(true, "3e-14");
check(true, "3e+14");
}
SECTION("Integer") {
REQUIRE_FALSE(isFloat("14"));
REQUIRE_FALSE(isFloat("-14"));
REQUIRE_FALSE(isFloat("+14"));
}
TEST_(Integer) {
check(false, "14");
check(false, "-14");
check(false, "+14");
}
SECTION("ExponentMissing") {
REQUIRE_FALSE(isFloat("3.14e"));
REQUIRE_FALSE(isFloat("3.14e-"));
REQUIRE_FALSE(isFloat("3.14e+"));
}
TEST_(ExponentMissing) {
check(false, "3.14e");
check(false, "3.14e-");
check(false, "3.14e+");
}
SECTION("JustASign") {
REQUIRE_FALSE(isFloat("-"));
REQUIRE_FALSE(isFloat("+"));
}
TEST_(JustASign) {
check(false, "-");
check(false, "+");
}
SECTION("Empty") {
REQUIRE_FALSE(isFloat(""));
}
TEST_(Empty) {
check(false, "");
}
SECTION("NaN") {
REQUIRE(isFloat("NaN"));
REQUIRE_FALSE(isFloat("n"));
REQUIRE_FALSE(isFloat("N"));
REQUIRE_FALSE(isFloat("nan"));
REQUIRE_FALSE(isFloat("-NaN"));
REQUIRE_FALSE(isFloat("+NaN"));
}
TEST_(NaN) {
check(true, "NaN");
check(false, "n");
check(false, "N");
check(false, "nan");
check(false, "-NaN");
check(false, "+NaN");
}
TEST_(Infinity) {
check(true, "Infinity");
check(true, "+Infinity");
check(true, "-Infinity");
check(false, "infinity");
check(false, "Inf");
SECTION("Infinity") {
REQUIRE(isFloat("Infinity"));
REQUIRE(isFloat("+Infinity"));
REQUIRE(isFloat("-Infinity"));
REQUIRE_FALSE(isFloat("infinity"));
REQUIRE_FALSE(isFloat("Inf"));
}
}

View File

@ -5,41 +5,35 @@
// https://bblanchon.github.io/ArduinoJson/
// If you like this project, please add a star!
#include <gtest/gtest.h>
#include <ArduinoJson/Polyfills/isInteger.hpp>
#include <catch.hpp>
using namespace ArduinoJson::Polyfills;
struct Polyfills_IsInteger_Tests : testing::Test {
void check(bool expected, const char* input) {
bool actual = isInteger(input);
EXPECT_EQ(expected, actual) << input;
TEST_CASE("isInteger()") {
SECTION("Null") {
REQUIRE_FALSE(isInteger(NULL));
}
};
#define TEST_(X) TEST_F(Polyfills_IsInteger_Tests, X)
TEST_(Null) {
check(false, NULL);
}
SECTION("FloatNotInteger") {
REQUIRE_FALSE(isInteger("3.14"));
REQUIRE_FALSE(isInteger("-3.14"));
REQUIRE_FALSE(isInteger("+3.14"));
}
TEST_(FloatNotInteger) {
check(false, "3.14");
check(false, "-3.14");
check(false, "+3.14");
}
SECTION("Spaces") {
REQUIRE_FALSE(isInteger("42 "));
REQUIRE_FALSE(isInteger(" 42"));
}
TEST_(Spaces) {
check(false, "42 ");
check(false, " 42");
}
SECTION("Valid") {
REQUIRE(isInteger("42"));
REQUIRE(isInteger("-42"));
REQUIRE(isInteger("+42"));
}
TEST_(Valid) {
check(true, "42");
check(true, "-42");
check(true, "+42");
}
TEST_(ExtraSign) {
check(false, "--42");
check(false, "++42");
SECTION("ExtraSign") {
REQUIRE_FALSE(isInteger("--42"));
REQUIRE_FALSE(isInteger("++42"));
}
}

View File

@ -5,179 +5,166 @@
// https://bblanchon.github.io/ArduinoJson/
// If you like this project, please add a star!
#include <gtest/gtest.h>
#include <ArduinoJson/Polyfills/parseFloat.hpp>
#include <catch.hpp>
using namespace ArduinoJson::Polyfills;
struct Polyfills_ParseFloat_Float_Tests : testing::Test {
void check(const char* input, float expected) {
float actual = parseFloat<float>(input);
EXPECT_FLOAT_EQ(expected, actual) << input;
template <typename T>
void check(const char* input, T expected) {
CAPTURE(input);
REQUIRE(parseFloat<T>(input) == Approx(expected));
}
template <typename T>
void checkNaN(const char* input) {
CAPTURE(input);
T result = parseFloat<T>(input);
REQUIRE(result != result);
}
template <typename T>
void checkInf(const char* input, bool negative) {
CAPTURE(input);
T x = parseFloat<T>(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("parseFloat<float>()") {
SECTION("Null") {
check<float>(NULL, 0);
}
void checkNaN(const char* input) {
float result = parseFloat<float>(input);
EXPECT_TRUE(result != result) << input;
SECTION("Float_Short_NoExponent") {
check<float>("3.14", 3.14f);
check<float>("-3.14", -3.14f);
check<float>("+3.14", +3.14f);
}
void checkInf(const char* input, bool negative) {
float x = parseFloat<float>(input);
if (negative)
EXPECT_TRUE(x < 0) << input;
else
EXPECT_TRUE(x > 0) << input;
EXPECT_TRUE(x == x && x * 2 == x) << input;
}
};
#define TEST_FLOAT(X) TEST_F(Polyfills_ParseFloat_Float_Tests, X)
struct Polyfills_ParseFloat_Double_Tests : testing::Test {
void check(const char* input, double expected) {
double actual = parseFloat<double>(input);
EXPECT_DOUBLE_EQ(expected, actual) << input;
SECTION("Short_NoDot") {
check<float>("1E+38", 1E+38f);
check<float>("-1E+38", -1E+38f);
check<float>("+1E-38", +1E-38f);
check<float>("+1e+38", +1e+38f);
check<float>("-1e-38", -1e-38f);
}
void checkNaN(const char* input) {
double result = parseFloat<double>(input);
EXPECT_TRUE(result != result) << input;
SECTION("Max") {
check<float>("340.2823e+36", 3.402823e+38f);
check<float>("34.02823e+37", 3.402823e+38f);
check<float>("3.402823e+38", 3.402823e+38f);
check<float>("0.3402823e+39", 3.402823e+38f);
check<float>("0.03402823e+40", 3.402823e+38f);
check<float>("0.003402823e+41", 3.402823e+38f);
}
void checkInf(const char* input, bool negative) {
double x = parseFloat<double>(input);
if (negative)
EXPECT_TRUE(x < 0) << input;
else
EXPECT_TRUE(x > 0) << input;
EXPECT_TRUE(x == x && x * 2 == x) << input;
}
};
#define TEST_DOUBLE(X) TEST_F(Polyfills_ParseFloat_Double_Tests, X)
TEST_DOUBLE(Null) {
check(NULL, 0);
}
TEST_FLOAT(Null) {
check(NULL, 0);
}
TEST_DOUBLE(Short_NoExponent) {
check("3.14", 3.14);
check("-3.14", -3.14);
check("+3.14", +3.14);
}
TEST_FLOAT(Float_Short_NoExponent) {
check("3.14", 3.14f);
check("-3.14", -3.14f);
check("+3.14", +3.14f);
}
TEST_DOUBLE(Short_NoDot) {
check("1E+308", 1E+308);
check("-1E+308", -1E+308);
check("+1E-308", +1E-308);
check("+1e+308", +1e+308);
check("-1e-308", -1e-308);
}
TEST_FLOAT(Short_NoDot) {
check("1E+38", 1E+38f);
check("-1E+38", -1E+38f);
check("+1E-38", +1E-38f);
check("+1e+38", +1e+38f);
check("-1e-38", -1e-38f);
}
TEST_FLOAT(Max) {
check("340.2823e+36", 3.402823e+38f);
check("34.02823e+37", 3.402823e+38f);
check("3.402823e+38", 3.402823e+38f);
check("0.3402823e+39", 3.402823e+38f);
check("00.3402823e+40", 3.402823e+38f);
check("000.3402823e+41", 3.402823e+38f);
}
TEST_DOUBLE(Max) {
check(".017976931348623147e+310", 1.7976931348623147e+308);
check(".17976931348623147e+309", 1.7976931348623147e+308);
check("1.7976931348623147e+308", 1.7976931348623147e+308);
check("17.976931348623147e+307", 1.7976931348623147e+308);
check("179.76931348623147e+306", 1.7976931348623147e+308);
}
TEST_DOUBLE(Min) {
check(".022250738585072014e-306", 2.2250738585072014e-308);
check(".22250738585072014e-307", 2.2250738585072014e-308);
check("2.2250738585072014e-308", 2.2250738585072014e-308);
check("22.250738585072014e-309", 2.2250738585072014e-308);
check("222.50738585072014e-310", 2.2250738585072014e-308);
}
TEST_DOUBLE(VeryLong) {
check("0.00000000000000000000000000000001", 1e-32);
check("100000000000000000000000000000000.0", 1e+32);
check("100000000000000000000000000000000.00000000000000000000000000000",
1e+32);
}
TEST_FLOAT(VeryLong) {
check("0.00000000000000000000000000000001", 1e-32f);
check("100000000000000000000000000000000.0", 1e+32f);
check("100000000000000000000000000000000.00000000000000000000000000000",
SECTION("VeryLong") {
check<float>("0.00000000000000000000000000000001", 1e-32f);
check<float>("100000000000000000000000000000000.0", 1e+32f);
check<float>(
"100000000000000000000000000000000.00000000000000000000000000000",
1e+32f);
}
SECTION("MantissaTooLongToFit") {
check<float>("0.340282346638528861111111111111", 0.34028234663852886f);
check<float>("34028234663852886.11111111111111", 34028234663852886.0f);
check<float>("34028234.66385288611111111111111", 34028234.663852886f);
check<float>("-0.340282346638528861111111111111", -0.34028234663852886f);
check<float>("-34028234663852886.11111111111111", -34028234663852886.0f);
check<float>("-34028234.66385288611111111111111", -34028234.663852886f);
}
SECTION("ExponentTooBig") {
checkInf<float>("1e39", false);
checkInf<float>("-1e39", true);
checkInf<float>("1e255", false);
check<float>("1e-255", 0.0f);
}
SECTION("NaN") {
checkNaN<float>("NaN");
checkNaN<float>("nan");
}
SECTION("Infinity") {
checkInf<float>("Infinity", false);
checkInf<float>("+Infinity", false);
checkInf<float>("-Infinity", true);
checkInf<float>("inf", false);
checkInf<float>("+inf", false);
checkInf<float>("-inf", true);
}
}
TEST_DOUBLE(MantissaTooLongToFit) {
check("0.179769313486231571111111111111", 0.17976931348623157);
check("17976931348623157.11111111111111", 17976931348623157.0);
check("1797693.134862315711111111111111", 1797693.1348623157);
TEST_CASE("parseFloat<double>()") {
SECTION("Null") {
check<double>(NULL, 0);
}
check("-0.179769313486231571111111111111", -0.17976931348623157);
check("-17976931348623157.11111111111111", -17976931348623157.0);
check("-1797693.134862315711111111111111", -1797693.1348623157);
}
TEST_FLOAT(MantissaTooLongToFit) {
check("0.340282346638528861111111111111", 0.34028234663852886f);
check("34028234663852886.11111111111111", 34028234663852886.0f);
check("34028234.66385288611111111111111", 34028234.663852886f);
check("-0.340282346638528861111111111111", -0.34028234663852886f);
check("-34028234663852886.11111111111111", -34028234663852886.0f);
check("-34028234.66385288611111111111111", -34028234.663852886f);
}
TEST_DOUBLE(ExponentTooBig) {
checkInf("1e309", false);
checkInf("-1e309", true);
checkInf("1e65535", false);
check("1e-65535", 0.0);
}
TEST_FLOAT(ExponentTooBig) {
checkInf("1e39", false);
checkInf("-1e39", true);
checkInf("1e255", false);
check("1e-255", 0.0f);
}
TEST_DOUBLE(NaN) {
checkNaN("NaN");
checkNaN("nan");
}
TEST_FLOAT(NaN) {
checkNaN("NaN");
checkNaN("nan");
}
TEST_FLOAT(Infinity) {
checkInf("Infinity", false);
checkInf("+Infinity", false);
checkInf("-Infinity", true);
checkInf("inf", false);
checkInf("+inf", false);
checkInf("-inf", true);
SECTION("Short_NoExponent") {
check<double>("3.14", 3.14);
check<double>("-3.14", -3.14);
check<double>("+3.14", +3.14);
}
SECTION("Short_NoDot") {
check<double>("1E+308", 1E+308);
check<double>("-1E+308", -1E+308);
check<double>("+1E-308", +1E-308);
check<double>("+1e+308", +1e+308);
check<double>("-1e-308", -1e-308);
}
SECTION("Max") {
check<double>(".017976931348623147e+310", 1.7976931348623147e+308);
check<double>(".17976931348623147e+309", 1.7976931348623147e+308);
check<double>("1.7976931348623147e+308", 1.7976931348623147e+308);
check<double>("17.976931348623147e+307", 1.7976931348623147e+308);
check<double>("179.76931348623147e+306", 1.7976931348623147e+308);
}
SECTION("Min") {
check<double>(".022250738585072014e-306", 2.2250738585072014e-308);
check<double>(".22250738585072014e-307", 2.2250738585072014e-308);
check<double>("2.2250738585072014e-308", 2.2250738585072014e-308);
check<double>("22.250738585072014e-309", 2.2250738585072014e-308);
check<double>("222.50738585072014e-310", 2.2250738585072014e-308);
}
SECTION("VeryLong") {
check<double>("0.00000000000000000000000000000001", 1e-32);
check<double>("100000000000000000000000000000000.0", 1e+32);
check<double>(
"100000000000000000000000000000000.00000000000000000000000000000",
1e+32);
}
SECTION("MantissaTooLongToFit") {
check<double>("0.179769313486231571111111111111", 0.17976931348623157);
check<double>("17976931348623157.11111111111111", 17976931348623157.0);
check<double>("1797693.134862315711111111111111", 1797693.1348623157);
check<double>("-0.179769313486231571111111111111", -0.17976931348623157);
check<double>("-17976931348623157.11111111111111", -17976931348623157.0);
check<double>("-1797693.134862315711111111111111", -1797693.1348623157);
}
SECTION("ExponentTooBig") {
checkInf<double>("1e309", false);
checkInf<double>("-1e309", true);
checkInf<double>("1e65535", false);
check<double>("1e-65535", 0.0);
}
SECTION("NaN") {
checkNaN<double>("NaN");
checkNaN<double>("nan");
}
}

View File

@ -5,23 +5,20 @@
// https://bblanchon.github.io/ArduinoJson/
// If you like this project, please add a star!
#include <gtest/gtest.h>
#include <stdint.h>
#include <ArduinoJson/Polyfills/parseInteger.hpp>
#include <catch.hpp>
using namespace ArduinoJson::Polyfills;
struct Polyfills_ParseInteger_Tests : testing::Test {
template <typename T>
void check(const char* input, T expected) {
T actual = parseInteger<T>(input);
EXPECT_EQ(expected, actual) << input;
}
};
template <typename T>
void check(const char* input, T expected) {
CAPTURE(input);
T actual = parseInteger<T>(input);
REQUIRE(expected == actual);
}
#define TEST_(X) TEST_F(Polyfills_ParseInteger_Tests, X)
TEST_(int8_t) {
TEST_CASE("parseInteger<int8_t>()") {
check<int8_t>("-128", -128);
check<int8_t>("127", 127);
check<int8_t>("+127", 127);
@ -33,7 +30,7 @@ TEST_(int8_t) {
check<int8_t>(NULL, 0);
}
TEST_(int16_t) {
TEST_CASE("parseInteger<int16_t>()") {
check<int16_t>("-32768", -32768);
check<int16_t>("32767", 32767);
check<int16_t>("+32767", 32767);
@ -45,7 +42,7 @@ TEST_(int16_t) {
check<int16_t>(NULL, 0);
}
TEST_(int32_t) {
TEST_CASE("parseInteger<int32_t>()") {
check<int32_t>("-2147483648", (-2147483647 - 1));
check<int32_t>("2147483647", 2147483647);
check<int32_t>("+2147483647", 2147483647);
@ -56,7 +53,7 @@ TEST_(int32_t) {
check<int32_t>("2147483648", (-2147483647 - 1));
}
TEST_(uint8_t) {
TEST_CASE("parseInteger<uint8_t>()") {
check<uint8_t>("0", 0);
check<uint8_t>("255", 255);
check<uint8_t>("+255", 255);
@ -67,7 +64,7 @@ TEST_(uint8_t) {
check<uint8_t>("256", 0);
}
TEST_(uint16_t) {
TEST_CASE("parseInteger<uint16_t>()") {
check<uint16_t>("0", 0);
check<uint16_t>("65535", 65535);
check<uint16_t>("+65535", 65535);

View File

@ -6,13 +6,13 @@
# If you like this project, please add a star!
add_executable(StaticJsonBufferTests
basics.cpp
alloc.cpp
createArray.cpp
createObject.cpp
parseArray.cpp
parseObject.cpp
string.cpp
startString.cpp
)
target_link_libraries(StaticJsonBufferTests gtest)
target_link_libraries(StaticJsonBufferTests catch)
add_test(StaticJsonBuffer StaticJsonBufferTests)

View File

@ -0,0 +1,68 @@
// Copyright Benoit Blanchon 2014-2017
// MIT License
//
// Arduino JSON library
// https://bblanchon.github.io/ArduinoJson/
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <catch.hpp>
static bool isAligned(void *ptr) {
const size_t mask = sizeof(void *) - 1;
size_t addr = reinterpret_cast<size_t>(ptr);
return (addr & mask) == 0;
}
TEST_CASE("StaticJsonBuffer::alloc()") {
StaticJsonBuffer<64> buffer;
SECTION("CapacityMatchTemplateParameter") {
REQUIRE(64 == buffer.capacity());
}
SECTION("InitialSizeIsZero") {
REQUIRE(0 == buffer.size());
}
SECTION("GrowsAfterAlloc") {
buffer.alloc(1);
REQUIRE(1U <= buffer.size());
buffer.alloc(1);
REQUIRE(2U <= buffer.size());
}
SECTION("DoesntGrowWhenFull") {
buffer.alloc(64);
buffer.alloc(1);
REQUIRE(64 == buffer.size());
}
SECTION("DoesntGrowWhenTooSmall") {
buffer.alloc(65);
REQUIRE(0 == buffer.size());
}
SECTION("ReturnsNonNull") {
void *p = buffer.alloc(64);
REQUIRE(0 != p);
}
SECTION("ReturnsNullWhenFull") {
buffer.alloc(64);
void *p = buffer.alloc(1);
REQUIRE(0 == p);
}
SECTION("ReturnsNullWhenTooSmall") {
void *p = buffer.alloc(65);
REQUIRE(0 == p);
}
SECTION("Alignment") {
for (size_t size = 1; size <= sizeof(void *); size++) {
void *p = buffer.alloc(1);
REQUIRE(isAligned(p));
}
}
}

View File

@ -1,65 +0,0 @@
// Copyright Benoit Blanchon 2014-2017
// MIT License
//
// Arduino JSON library
// https://bblanchon.github.io/ArduinoJson/
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
class StaticJsonBuffer_Basic_Tests : public testing::Test {
protected:
StaticJsonBuffer<64> buffer;
};
TEST_F(StaticJsonBuffer_Basic_Tests, CapacityMatchTemplateParameter) {
ASSERT_EQ(64, buffer.capacity());
}
TEST_F(StaticJsonBuffer_Basic_Tests, InitialSizeIsZero) {
ASSERT_EQ(0, buffer.size());
}
TEST_F(StaticJsonBuffer_Basic_Tests, GrowsAfterAlloc) {
buffer.alloc(1);
ASSERT_LE(1U, buffer.size());
buffer.alloc(1);
ASSERT_LE(2U, buffer.size());
}
TEST_F(StaticJsonBuffer_Basic_Tests, DoesntGrowWhenFull) {
buffer.alloc(64);
buffer.alloc(1);
ASSERT_EQ(64, buffer.size());
}
TEST_F(StaticJsonBuffer_Basic_Tests, DoesntGrowWhenTooSmall) {
buffer.alloc(65);
ASSERT_EQ(0, buffer.size());
}
TEST_F(StaticJsonBuffer_Basic_Tests, ReturnsNonNull) {
void *p = buffer.alloc(64);
ASSERT_NE(static_cast<void *>(0), p);
}
TEST_F(StaticJsonBuffer_Basic_Tests, ReturnsNullWhenFull) {
buffer.alloc(64);
void *p = buffer.alloc(1);
ASSERT_EQ(NULL, p);
}
TEST_F(StaticJsonBuffer_Basic_Tests, ReturnsNullWhenTooSmall) {
void *p = buffer.alloc(65);
ASSERT_EQ(NULL, p);
}
TEST_F(StaticJsonBuffer_Basic_Tests, Alignment) {
size_t mask = sizeof(void *) - 1;
for (size_t size = 1; size <= sizeof(void *); size++) {
size_t addr = reinterpret_cast<size_t>(buffer.alloc(1));
ASSERT_EQ(0, addr & mask);
}
}

View File

@ -6,41 +6,43 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
TEST(StaticJsonBuffer_CreateArray_Tests, GrowsWithArray) {
StaticJsonBuffer<JSON_ARRAY_SIZE(2)> json;
TEST_CASE("StaticJsonBuffer::createArray()") {
SECTION("GrowsWithArray") {
StaticJsonBuffer<JSON_ARRAY_SIZE(2)> json;
JsonArray &array = json.createArray();
ASSERT_EQ(JSON_ARRAY_SIZE(0), json.size());
JsonArray &array = json.createArray();
REQUIRE(JSON_ARRAY_SIZE(0) == json.size());
array.add("hello");
ASSERT_EQ(JSON_ARRAY_SIZE(1), json.size());
array.add("hello");
REQUIRE(JSON_ARRAY_SIZE(1) == json.size());
array.add("world");
ASSERT_EQ(JSON_ARRAY_SIZE(2), json.size());
}
TEST(StaticJsonBuffer_CreateArray_Tests, SucceedWhenBigEnough) {
StaticJsonBuffer<JSON_ARRAY_SIZE(0)> json;
JsonArray &array = json.createArray();
ASSERT_TRUE(array.success());
}
TEST(StaticJsonBuffer_CreateArray_Tests, FailsWhenTooSmall) {
StaticJsonBuffer<JSON_ARRAY_SIZE(0) - 1> json;
JsonArray &array = json.createArray();
ASSERT_FALSE(array.success());
}
TEST(StaticJsonBuffer_CreateArray_Tests, ArrayDoesntGrowWhenFull) {
StaticJsonBuffer<JSON_ARRAY_SIZE(1)> json;
JsonArray &array = json.createArray();
array.add("hello");
array.add("world");
EXPECT_EQ(1, array.size());
array.add("world");
REQUIRE(JSON_ARRAY_SIZE(2) == json.size());
}
SECTION("SucceedWhenBigEnough") {
StaticJsonBuffer<JSON_ARRAY_SIZE(0)> json;
JsonArray &array = json.createArray();
REQUIRE(array.success());
}
SECTION("FailsWhenTooSmall") {
StaticJsonBuffer<JSON_ARRAY_SIZE(0) - 1> json;
JsonArray &array = json.createArray();
REQUIRE_FALSE(array.success());
}
SECTION("ArrayDoesntGrowWhenFull") {
StaticJsonBuffer<JSON_ARRAY_SIZE(1)> json;
JsonArray &array = json.createArray();
array.add("hello");
array.add("world");
REQUIRE(1 == array.size());
}
}

View File

@ -6,52 +6,54 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
TEST(StaticJsonBuffer_CreateObject_Tests, GrowsWithObject) {
StaticJsonBuffer<JSON_OBJECT_SIZE(3)> buffer;
TEST_CASE("StaticJsonBuffer::createObject()") {
SECTION("GrowsWithObject") {
StaticJsonBuffer<JSON_OBJECT_SIZE(3)> buffer;
JsonObject &obj = buffer.createObject();
ASSERT_EQ(JSON_OBJECT_SIZE(0), buffer.size());
JsonObject &obj = buffer.createObject();
REQUIRE(JSON_OBJECT_SIZE(0) == buffer.size());
obj["hello"];
ASSERT_EQ(JSON_OBJECT_SIZE(0), buffer.size());
obj["hello"];
REQUIRE(JSON_OBJECT_SIZE(0) == buffer.size());
obj["hello"] = 1;
ASSERT_EQ(JSON_OBJECT_SIZE(1), buffer.size());
obj["hello"] = 1;
REQUIRE(JSON_OBJECT_SIZE(1) == buffer.size());
obj["world"] = 2;
ASSERT_EQ(JSON_OBJECT_SIZE(2), buffer.size());
obj["world"] = 2;
REQUIRE(JSON_OBJECT_SIZE(2) == buffer.size());
obj["world"] = 3; // <- same key, should not grow
ASSERT_EQ(JSON_OBJECT_SIZE(2), buffer.size());
}
TEST(StaticJsonBuffer_CreateObject_Tests, SucceedWhenBigEnough) {
StaticJsonBuffer<JSON_OBJECT_SIZE(0)> buffer;
JsonObject &object = buffer.createObject();
ASSERT_TRUE(object.success());
}
TEST(StaticJsonBuffer_CreateObject_Tests, FailsWhenTooSmall) {
StaticJsonBuffer<JSON_OBJECT_SIZE(0) - 1> buffer;
JsonObject &object = buffer.createObject();
ASSERT_FALSE(object.success());
}
TEST(StaticJsonBuffer_CreateObject_Tests, ObjectDoesntGrowWhenFull) {
StaticJsonBuffer<JSON_OBJECT_SIZE(1)> buffer;
JsonObject &obj = buffer.createObject();
obj["hello"] = 1;
obj["world"] = 2;
ASSERT_EQ(JSON_OBJECT_SIZE(1), buffer.size());
ASSERT_EQ(1, obj.size());
char json[64];
obj.printTo(json, sizeof(json));
ASSERT_STREQ("{\"hello\":1}", json);
obj["world"] = 3; // <- same key, should not grow
REQUIRE(JSON_OBJECT_SIZE(2) == buffer.size());
}
SECTION("SucceedWhenBigEnough") {
StaticJsonBuffer<JSON_OBJECT_SIZE(0)> buffer;
JsonObject &object = buffer.createObject();
REQUIRE(object.success());
}
SECTION("FailsWhenTooSmall") {
StaticJsonBuffer<JSON_OBJECT_SIZE(0) - 1> buffer;
JsonObject &object = buffer.createObject();
REQUIRE_FALSE(object.success());
}
SECTION("ObjectDoesntGrowWhenFull") {
StaticJsonBuffer<JSON_OBJECT_SIZE(1)> buffer;
JsonObject &obj = buffer.createObject();
obj["hello"] = 1;
obj["world"] = 2;
REQUIRE(JSON_OBJECT_SIZE(1) == buffer.size());
REQUIRE(1 == obj.size());
char json[64];
obj.printTo(json, sizeof(json));
REQUIRE(std::string("{\"hello\":1}") == json);
}
}

View File

@ -6,91 +6,69 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
#include <catch.hpp>
class StaticJsonBuffer_ParseArray_Tests : public testing::Test {
protected:
void with(StaticJsonBufferBase& jsonBuffer) {
_jsonBuffer = &jsonBuffer;
TEST_CASE("StaticJsonBuffer::parseArray()") {
SECTION("TooSmallBufferForEmptyArray") {
StaticJsonBuffer<JSON_ARRAY_SIZE(0) - 1> bufferTooSmall;
char input[] = "[]";
JsonArray& arr = bufferTooSmall.parseArray(input);
REQUIRE_FALSE(arr.success());
}
void whenInputIs(const char* json) {
strcpy(_jsonString, json);
SECTION("BufferOfTheRightSizeForEmptyArray") {
StaticJsonBuffer<JSON_ARRAY_SIZE(0)> bufferOfRightSize;
char input[] = "[]";
JsonArray& arr = bufferOfRightSize.parseArray(input);
REQUIRE(arr.success());
}
void parseMustSucceed() {
EXPECT_TRUE(_jsonBuffer->parseArray(_jsonString).success());
SECTION("TooSmallBufferForArrayWithOneValue") {
StaticJsonBuffer<JSON_ARRAY_SIZE(1) - 1> bufferTooSmall;
char input[] = "[1]";
JsonArray& arr = bufferTooSmall.parseArray(input);
REQUIRE_FALSE(arr.success());
}
void parseMustFail() {
EXPECT_FALSE(_jsonBuffer->parseArray(_jsonString).success());
SECTION("BufferOfTheRightSizeForArrayWithOneValue") {
StaticJsonBuffer<JSON_ARRAY_SIZE(1)> bufferOfRightSize;
char input[] = "[1]";
JsonArray& arr = bufferOfRightSize.parseArray(input);
REQUIRE(arr.success());
}
private:
StaticJsonBufferBase* _jsonBuffer;
char _jsonString[256];
};
SECTION("TooSmallBufferForArrayWithNestedObject") {
StaticJsonBuffer<JSON_ARRAY_SIZE(1) + JSON_OBJECT_SIZE(0) - 1>
bufferTooSmall;
char input[] = "[{}]";
JsonArray& arr = bufferTooSmall.parseArray(input);
REQUIRE_FALSE(arr.success());
}
TEST_F(StaticJsonBuffer_ParseArray_Tests, TooSmallBufferForEmptyArray) {
StaticJsonBuffer<JSON_ARRAY_SIZE(0) - 1> bufferTooSmall;
with(bufferTooSmall);
whenInputIs("[]");
parseMustFail();
}
SECTION("BufferOfTheRightSizeForArrayWithNestedObject") {
StaticJsonBuffer<JSON_ARRAY_SIZE(1) + JSON_OBJECT_SIZE(0)>
bufferOfRightSize;
char input[] = "[{}]";
JsonArray& arr = bufferOfRightSize.parseArray(input);
REQUIRE(arr.success());
}
TEST_F(StaticJsonBuffer_ParseArray_Tests, BufferOfTheRightSizeForEmptyArray) {
StaticJsonBuffer<JSON_ARRAY_SIZE(0)> bufferOfRightSize;
with(bufferOfRightSize);
whenInputIs("[]");
parseMustSucceed();
}
SECTION("CharPtrNull") {
REQUIRE_FALSE(
StaticJsonBuffer<100>().parseArray(static_cast<char*>(0)).success());
}
TEST_F(StaticJsonBuffer_ParseArray_Tests, TooSmallBufferForArrayWithOneValue) {
StaticJsonBuffer<JSON_ARRAY_SIZE(1) - 1> bufferTooSmall;
with(bufferTooSmall);
whenInputIs("[1]");
parseMustFail();
}
SECTION("ConstCharPtrNull") {
REQUIRE_FALSE(StaticJsonBuffer<100>()
.parseArray(static_cast<const char*>(0))
.success());
}
TEST_F(StaticJsonBuffer_ParseArray_Tests,
BufferOfTheRightSizeForArrayWithOneValue) {
StaticJsonBuffer<JSON_ARRAY_SIZE(1)> bufferOfRightSize;
with(bufferOfRightSize);
whenInputIs("[1]");
parseMustSucceed();
}
TEST_F(StaticJsonBuffer_ParseArray_Tests,
TooSmallBufferForArrayWithNestedObject) {
StaticJsonBuffer<JSON_ARRAY_SIZE(1) + JSON_OBJECT_SIZE(0) - 1> bufferTooSmall;
with(bufferTooSmall);
whenInputIs("[{}]");
parseMustFail();
}
TEST_F(StaticJsonBuffer_ParseArray_Tests,
BufferOfTheRightSizeForArrayWithNestedObject) {
StaticJsonBuffer<JSON_ARRAY_SIZE(1) + JSON_OBJECT_SIZE(0)> bufferOfRightSize;
with(bufferOfRightSize);
whenInputIs("[{}]");
parseMustSucceed();
}
TEST_F(StaticJsonBuffer_ParseArray_Tests, CharPtrNull) {
ASSERT_FALSE(
StaticJsonBuffer<100>().parseArray(static_cast<char*>(0)).success());
}
TEST_F(StaticJsonBuffer_ParseArray_Tests, ConstCharPtrNull) {
ASSERT_FALSE(StaticJsonBuffer<100>()
.parseArray(static_cast<const char*>(0))
.success());
}
TEST_F(StaticJsonBuffer_ParseArray_Tests, CopyStringNotSpaces) {
StaticJsonBuffer<100> jsonBuffer;
jsonBuffer.parseArray(" [ \"1234567\" ] ");
ASSERT_EQ(JSON_ARRAY_SIZE(1) + sizeof("1234567"), jsonBuffer.size());
// note we use a string of 8 bytes to be sure that the StaticJsonBuffer
// will not insert bytes to enforce alignement
SECTION("CopyStringNotSpaces") {
StaticJsonBuffer<100> jsonBuffer;
jsonBuffer.parseArray(" [ \"1234567\" ] ");
REQUIRE(JSON_ARRAY_SIZE(1) + sizeof("1234567") == jsonBuffer.size());
// note we use a string of 8 bytes to be sure that the StaticJsonBuffer
// will not insert bytes to enforce alignement
}
}

View File

@ -6,84 +6,60 @@
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
class StaticJsonBuffer_ParseObject_Tests : public testing::Test {
protected:
void with(StaticJsonBufferBase& jsonBuffer) {
_jsonBuffer = &jsonBuffer;
#include <catch.hpp>
TEST_CASE("StaticJsonBuffer::parseObject()") {
SECTION("TooSmallBufferForEmptyObject") {
StaticJsonBuffer<JSON_OBJECT_SIZE(0) - 1> bufferTooSmall;
char input[] = "{}";
JsonObject& obj = bufferTooSmall.parseObject(input);
REQUIRE_FALSE(obj.success());
}
void whenInputIs(const char* json) {
strcpy(_jsonString, json);
SECTION("BufferOfTheRightSizeForEmptyObject") {
StaticJsonBuffer<JSON_OBJECT_SIZE(0)> bufferOfRightSize;
char input[] = "{}";
JsonObject& obj = bufferOfRightSize.parseObject(input);
REQUIRE(obj.success());
}
void parseMustSucceed() {
EXPECT_TRUE(_jsonBuffer->parseObject(_jsonString).success());
SECTION("TooSmallBufferForObjectWithOneValue") {
StaticJsonBuffer<JSON_OBJECT_SIZE(1) - 1> bufferTooSmall;
char input[] = "{\"a\":1}";
JsonObject& obj = bufferTooSmall.parseObject(input);
REQUIRE_FALSE(obj.success());
}
void parseMustFail() {
EXPECT_FALSE(_jsonBuffer->parseObject(_jsonString).success());
SECTION("BufferOfTheRightSizeForObjectWithOneValue") {
StaticJsonBuffer<JSON_OBJECT_SIZE(1)> bufferOfRightSize;
char input[] = "{\"a\":1}";
JsonObject& obj = bufferOfRightSize.parseObject(input);
REQUIRE(obj.success());
}
private:
StaticJsonBufferBase* _jsonBuffer;
char _jsonString[256];
};
SECTION("TooSmallBufferForObjectWithNestedObject") {
StaticJsonBuffer<JSON_OBJECT_SIZE(1) + JSON_ARRAY_SIZE(0) - 1>
bufferTooSmall;
char input[] = "{\"a\":[]}";
JsonObject& obj = bufferTooSmall.parseObject(input);
REQUIRE_FALSE(obj.success());
}
TEST_F(StaticJsonBuffer_ParseObject_Tests, TooSmallBufferForEmptyObject) {
StaticJsonBuffer<JSON_OBJECT_SIZE(0) - 1> bufferTooSmall;
with(bufferTooSmall);
whenInputIs("{}");
parseMustFail();
}
SECTION("BufferOfTheRightSizeForObjectWithNestedObject") {
StaticJsonBuffer<JSON_OBJECT_SIZE(1) + JSON_ARRAY_SIZE(0)>
bufferOfRightSize;
char input[] = "{\"a\":[]}";
JsonObject& obj = bufferOfRightSize.parseObject(input);
REQUIRE(obj.success());
}
TEST_F(StaticJsonBuffer_ParseObject_Tests, BufferOfTheRightSizeForEmptyObject) {
StaticJsonBuffer<JSON_OBJECT_SIZE(0)> bufferOfRightSize;
with(bufferOfRightSize);
whenInputIs("{}");
parseMustSucceed();
}
SECTION("CharPtrNull") {
REQUIRE_FALSE(
StaticJsonBuffer<100>().parseObject(static_cast<char*>(0)).success());
}
TEST_F(StaticJsonBuffer_ParseObject_Tests,
TooSmallBufferForObjectWithOneValue) {
StaticJsonBuffer<JSON_OBJECT_SIZE(1) - 1> bufferTooSmall;
with(bufferTooSmall);
whenInputIs("{\"a\":1}");
parseMustFail();
}
TEST_F(StaticJsonBuffer_ParseObject_Tests,
BufferOfTheRightSizeForObjectWithOneValue) {
StaticJsonBuffer<JSON_OBJECT_SIZE(1)> bufferOfRightSize;
with(bufferOfRightSize);
whenInputIs("{\"a\":1}");
parseMustSucceed();
}
TEST_F(StaticJsonBuffer_ParseObject_Tests,
TooSmallBufferForObjectWithNestedObject) {
StaticJsonBuffer<JSON_OBJECT_SIZE(1) + JSON_ARRAY_SIZE(0) - 1> bufferTooSmall;
with(bufferTooSmall);
whenInputIs("{\"a\":[]}");
parseMustFail();
}
TEST_F(StaticJsonBuffer_ParseObject_Tests,
BufferOfTheRightSizeForObjectWithNestedObject) {
StaticJsonBuffer<JSON_OBJECT_SIZE(1) + JSON_ARRAY_SIZE(0)> bufferOfRightSize;
with(bufferOfRightSize);
whenInputIs("{\"a\":[]}");
parseMustSucceed();
}
TEST_F(StaticJsonBuffer_ParseObject_Tests, CharPtrNull) {
ASSERT_FALSE(
StaticJsonBuffer<100>().parseObject(static_cast<char*>(0)).success());
}
TEST_F(StaticJsonBuffer_ParseObject_Tests, ConstCharPtrNull) {
ASSERT_FALSE(StaticJsonBuffer<100>()
.parseObject(static_cast<const char*>(0))
.success());
SECTION("ConstCharPtrNull") {
REQUIRE_FALSE(StaticJsonBuffer<100>()
.parseObject(static_cast<const char*>(0))
.success());
}
}

View File

@ -0,0 +1,50 @@
// Copyright Benoit Blanchon 2014-2017
// MIT License
//
// Arduino JSON library
// https://bblanchon.github.io/ArduinoJson/
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <catch.hpp>
TEST_CASE("StaticJsonBuffer::startString()") {
SECTION("WorksWhenBufferIsBigEnough") {
StaticJsonBuffer<6> jsonBuffer;
StaticJsonBufferBase::String str = jsonBuffer.startString();
str.append('h');
str.append('e');
str.append('l');
str.append('l');
str.append('o');
REQUIRE(std::string("hello") == str.c_str());
}
SECTION("ReturnsNullWhenTooSmall") {
StaticJsonBuffer<5> jsonBuffer;
StaticJsonBufferBase::String str = jsonBuffer.startString();
str.append('h');
str.append('e');
str.append('l');
str.append('l');
str.append('o');
REQUIRE(0 == str.c_str());
}
SECTION("SizeIncreases") {
StaticJsonBuffer<5> jsonBuffer;
StaticJsonBufferBase::String str = jsonBuffer.startString();
REQUIRE(0 == jsonBuffer.size());
str.append('h');
REQUIRE(1 == jsonBuffer.size());
str.c_str();
REQUIRE(2 == jsonBuffer.size());
}
}

View File

@ -1,48 +0,0 @@
// Copyright Benoit Blanchon 2014-2017
// MIT License
//
// Arduino JSON library
// https://bblanchon.github.io/ArduinoJson/
// If you like this project, please add a star!
#include <ArduinoJson.h>
#include <gtest/gtest.h>
TEST(StaticJsonBuffer_String_Tests, WorksWhenBufferIsBigEnough) {
StaticJsonBuffer<6> jsonBuffer;
StaticJsonBufferBase::String str = jsonBuffer.startString();
str.append('h');
str.append('e');
str.append('l');
str.append('l');
str.append('o');
ASSERT_STREQ("hello", str.c_str());
}
TEST(StaticJsonBuffer_String_Tests, ReturnsNullWhenTooSmall) {
StaticJsonBuffer<5> jsonBuffer;
StaticJsonBufferBase::String str = jsonBuffer.startString();
str.append('h');
str.append('e');
str.append('l');
str.append('l');
str.append('o');
ASSERT_EQ(NULL, str.c_str());
}
TEST(StaticJsonBuffer_String_Tests, SizeIncreases) {
StaticJsonBuffer<5> jsonBuffer;
StaticJsonBufferBase::String str = jsonBuffer.startString();
ASSERT_EQ(0, jsonBuffer.size());
str.append('h');
ASSERT_EQ(1, jsonBuffer.size());
str.c_str();
ASSERT_EQ(2, jsonBuffer.size());
}

View File

@ -1,24 +0,0 @@
set(GTEST_DIR ../third-party/gtest-1.7.0)
add_library(gtest
${GTEST_DIR}/src/gtest-all.cc
${GTEST_DIR}/src/gtest_main.cc
)
target_include_directories(gtest
PUBLIC
${GTEST_DIR}
${GTEST_DIR}/include
)
target_compile_definitions(gtest PUBLIC -DGTEST_HAS_PTHREAD=0)
if (MSVC)
if (MSVC_VERSION EQUAL 1700)
# Workaround for Visual Studio 2012
target_compile_definitions(gtest PUBLIC -D_VARIADIC_MAX=10)
endif()
target_compile_definitions(gtest PUBLIC -D_CRT_SECURE_NO_WARNINGS)
endif()