diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 8dc05b645..6d9767da8 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -69,6 +69,8 @@ add_boost_test(base base_dictionary/json base_fifo/construct base_fifo/io + base_json/encode + base_json/decode base_json/invalid1 base_object_packer/pack_null base_object_packer/pack_false diff --git a/test/base-json.cpp b/test/base-json.cpp index 7cb799af0..6e848a2cc 100644 --- a/test/base-json.cpp +++ b/test/base-json.cpp @@ -1,14 +1,98 @@ /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */ #include "base/dictionary.hpp" +#include "base/namespace.hpp" #include "base/objectlock.hpp" #include "base/json.hpp" +#include #include using namespace icinga; BOOST_AUTO_TEST_SUITE(base_json) +BOOST_AUTO_TEST_CASE(encode) +{ + Dictionary::Ptr input (new Dictionary({ + { "array", new Array({ new Namespace() }) }, + { "false", false }, + { "float", -1.25 }, + { "int", -42 }, + { "null", Value() }, + { "string", "LF\nTAB\tAUml\xC3\xA4Ill\xC3" }, + { "true", true }, + { "uint", 23u } + })); + + String output (R"EOF({ + "array": [ + {} + ], + "false": false, + "float": -1.25, + "int": -42.0, + "null": null, + "string": "LF\nTAB\tAUml\u00e4Ill\ufffd", + "true": true, + "uint": 23.0 +})EOF"); + + BOOST_CHECK(JsonEncode(input, true) == output); + + boost::algorithm::replace_all(output, " ", ""); + boost::algorithm::replace_all(output, "\n", ""); + + BOOST_CHECK(JsonEncode(input, false) == output); +} + +BOOST_AUTO_TEST_CASE(decode) +{ + String input (R"EOF({ + "array": [ + {} + ], + "false": false, + "float": -1.25, + "int": -42.0, + "null": null, + "string": "LF\nTAB\tAUmlIll", + "true": true, + "uint": 23.0 +})EOF"); + + boost::algorithm::replace_all(input, "AUml", "AUml\xC3\xA4"); + boost::algorithm::replace_all(input, "Ill", "Ill\xC3"); + + auto output ((Dictionary::Ptr)JsonDecode(input)); + BOOST_CHECK(output->GetKeys() == std::vector({"array", "false", "float", "int", "null", "string", "true", "uint"})); + + auto array ((Array::Ptr)output->Get("array")); + BOOST_CHECK(array->GetLength() == 1u); + + auto array0 ((Dictionary::Ptr)array->Get(0)); + BOOST_CHECK(array0->GetKeys() == std::vector()); + + auto fAlse (output->Get("false")); + BOOST_CHECK(fAlse.IsBoolean() && !fAlse.ToBool()); + + auto fLoat (output->Get("float")); + BOOST_CHECK(fLoat.IsNumber() && fLoat.Get() == -1.25); + + auto iNt (output->Get("int")); + BOOST_CHECK(iNt.IsNumber() && iNt.Get() == -42.0); + + BOOST_CHECK(output->Get("null").IsEmpty()); + + auto string (output->Get("string")); + BOOST_CHECK(string.IsString() && string.Get() == "LF\nTAB\tAUml\xC3\xA4Ill\xEF\xBF\xBD"); + + auto tRue (output->Get("true")); + BOOST_CHECK(tRue.IsBoolean() && tRue.ToBool()); + + auto uint (output->Get("uint")); + BOOST_CHECK(uint.IsNumber() && uint.Get() == 23.0); +} + BOOST_AUTO_TEST_CASE(invalid1) { BOOST_CHECK_THROW(JsonDecode("\"1.7"), std::exception);