test_json.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. /**************************************************************************/
  2. /* test_json.h */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #pragma once
  31. #include "core/io/json.h"
  32. #include "thirdparty/doctest/doctest.h"
  33. namespace TestJSON {
  34. TEST_CASE("[JSON] Stringify single data types") {
  35. CHECK(JSON::stringify(Variant()) == "null");
  36. CHECK(JSON::stringify(false) == "false");
  37. CHECK(JSON::stringify(true) == "true");
  38. CHECK(JSON::stringify(0) == "0");
  39. CHECK(JSON::stringify(12345) == "12345");
  40. CHECK(JSON::stringify(0.75) == "0.75");
  41. CHECK(JSON::stringify("test") == "\"test\"");
  42. CHECK(JSON::stringify("\\\b\f\n\r\t\v\"") == "\"\\\\\\b\\f\\n\\r\\t\\v\\\"\"");
  43. }
  44. TEST_CASE("[JSON] Stringify arrays") {
  45. CHECK(JSON::stringify(Array()) == "[]");
  46. Array int_array;
  47. for (int i = 0; i < 10; i++) {
  48. int_array.push_back(i);
  49. }
  50. CHECK(JSON::stringify(int_array) == "[0,1,2,3,4,5,6,7,8,9]");
  51. Array str_array;
  52. str_array.push_back("Hello");
  53. str_array.push_back("World");
  54. str_array.push_back("!");
  55. CHECK(JSON::stringify(str_array) == "[\"Hello\",\"World\",\"!\"]");
  56. Array indented_array;
  57. Array nested_array;
  58. for (int i = 0; i < 5; i++) {
  59. indented_array.push_back(i);
  60. nested_array.push_back(i);
  61. }
  62. indented_array.push_back(nested_array);
  63. CHECK(JSON::stringify(indented_array, "\t") == "[\n\t0,\n\t1,\n\t2,\n\t3,\n\t4,\n\t[\n\t\t0,\n\t\t1,\n\t\t2,\n\t\t3,\n\t\t4\n\t]\n]");
  64. Array full_precision_array;
  65. full_precision_array.push_back(0.123456789012345677);
  66. CHECK(JSON::stringify(full_precision_array, "", true, true) == "[0.123456789012345677]");
  67. ERR_PRINT_OFF
  68. Array self_array;
  69. self_array.push_back(self_array);
  70. CHECK(JSON::stringify(self_array) == "[\"[...]\"]");
  71. self_array.clear();
  72. Array max_recursion_array;
  73. for (int i = 0; i < Variant::MAX_RECURSION_DEPTH + 1; i++) {
  74. Array next;
  75. next.push_back(max_recursion_array);
  76. max_recursion_array = next;
  77. }
  78. CHECK(JSON::stringify(max_recursion_array).contains("[...]"));
  79. ERR_PRINT_ON
  80. }
  81. TEST_CASE("[JSON] Stringify dictionaries") {
  82. CHECK(JSON::stringify(Dictionary()) == "{}");
  83. Dictionary single_entry;
  84. single_entry["key"] = "value";
  85. CHECK(JSON::stringify(single_entry) == "{\"key\":\"value\"}");
  86. Dictionary indented;
  87. indented["key1"] = "value1";
  88. indented["key2"] = 2;
  89. CHECK(JSON::stringify(indented, "\t") == "{\n\t\"key1\": \"value1\",\n\t\"key2\": 2\n}");
  90. Dictionary outer;
  91. Dictionary inner;
  92. inner["key"] = "value";
  93. outer["inner"] = inner;
  94. CHECK(JSON::stringify(outer) == "{\"inner\":{\"key\":\"value\"}}");
  95. Dictionary full_precision_dictionary;
  96. full_precision_dictionary["key"] = 0.123456789012345677;
  97. CHECK(JSON::stringify(full_precision_dictionary, "", true, true) == "{\"key\":0.123456789012345677}");
  98. ERR_PRINT_OFF
  99. Dictionary self_dictionary;
  100. self_dictionary["key"] = self_dictionary;
  101. CHECK(JSON::stringify(self_dictionary) == "{\"key\":\"{...}\"}");
  102. self_dictionary.clear();
  103. Dictionary max_recursion_dictionary;
  104. for (int i = 0; i < Variant::MAX_RECURSION_DEPTH + 1; i++) {
  105. Dictionary next;
  106. next["key"] = max_recursion_dictionary;
  107. max_recursion_dictionary = next;
  108. }
  109. CHECK(JSON::stringify(max_recursion_dictionary).contains("{...:...}"));
  110. ERR_PRINT_ON
  111. }
  112. // NOTE: The current JSON parser accepts many non-conformant strings such as
  113. // single-quoted strings, duplicate commas and trailing commas.
  114. // This is intentionally not tested as users shouldn't rely on this behavior.
  115. TEST_CASE("[JSON] Parsing single data types") {
  116. // Parsing a single data type as JSON is valid per the JSON specification.
  117. JSON json;
  118. json.parse("null");
  119. CHECK_MESSAGE(
  120. json.get_error_line() == 0,
  121. "Parsing `null` as JSON should parse successfully.");
  122. CHECK_MESSAGE(
  123. json.get_data() == Variant(),
  124. "Parsing a double quoted string as JSON should return the expected value.");
  125. json.parse("true");
  126. CHECK_MESSAGE(
  127. json.get_error_line() == 0,
  128. "Parsing boolean `true` as JSON should parse successfully.");
  129. CHECK_MESSAGE(
  130. json.get_data(),
  131. "Parsing boolean `true` as JSON should return the expected value.");
  132. json.parse("false");
  133. CHECK_MESSAGE(
  134. json.get_error_line() == 0,
  135. "Parsing boolean `false` as JSON should parse successfully.");
  136. CHECK_MESSAGE(
  137. !json.get_data(),
  138. "Parsing boolean `false` as JSON should return the expected value.");
  139. json.parse("123456");
  140. CHECK_MESSAGE(
  141. json.get_error_line() == 0,
  142. "Parsing an integer number as JSON should parse successfully.");
  143. CHECK_MESSAGE(
  144. (int)(json.get_data()) == 123456,
  145. "Parsing an integer number as JSON should return the expected value.");
  146. json.parse("0.123456");
  147. CHECK_MESSAGE(
  148. json.get_error_line() == 0,
  149. "Parsing a floating-point number as JSON should parse successfully.");
  150. CHECK_MESSAGE(
  151. double(json.get_data()) == doctest::Approx(0.123456),
  152. "Parsing a floating-point number as JSON should return the expected value.");
  153. json.parse("\"hello\"");
  154. CHECK_MESSAGE(
  155. json.get_error_line() == 0,
  156. "Parsing a double quoted string as JSON should parse successfully.");
  157. CHECK_MESSAGE(
  158. json.get_data() == "hello",
  159. "Parsing a double quoted string as JSON should return the expected value.");
  160. }
  161. TEST_CASE("[JSON] Parsing arrays") {
  162. JSON json;
  163. // JSON parsing fails if it's split over several lines (even if leading indentation is removed).
  164. json.parse(R"(["Hello", "world.", "This is",["a","json","array.",[]], "Empty arrays ahoy:", [[["Gotcha!"]]]])");
  165. const Array array = json.get_data();
  166. CHECK_MESSAGE(
  167. json.get_error_line() == 0,
  168. "Parsing a JSON array should parse successfully.");
  169. CHECK_MESSAGE(
  170. array[0] == "Hello",
  171. "The parsed JSON should contain the expected values.");
  172. const Array sub_array = array[3];
  173. CHECK_MESSAGE(
  174. sub_array.size() == 4,
  175. "The parsed JSON should contain the expected values.");
  176. CHECK_MESSAGE(
  177. sub_array[1] == "json",
  178. "The parsed JSON should contain the expected values.");
  179. CHECK_MESSAGE(
  180. sub_array[3].hash() == Array().hash(),
  181. "The parsed JSON should contain the expected values.");
  182. const Array deep_array = Array(Array(array[5])[0])[0];
  183. CHECK_MESSAGE(
  184. deep_array[0] == "Gotcha!",
  185. "The parsed JSON should contain the expected values.");
  186. }
  187. TEST_CASE("[JSON] Parsing objects (dictionaries)") {
  188. JSON json;
  189. json.parse(R"({"name": "Godot Engine", "is_free": true, "bugs": null, "apples": {"red": 500, "green": 0, "blue": -20}, "empty_object": {}})");
  190. const Dictionary dictionary = json.get_data();
  191. CHECK_MESSAGE(
  192. dictionary["name"] == "Godot Engine",
  193. "The parsed JSON should contain the expected values.");
  194. CHECK_MESSAGE(
  195. dictionary["is_free"],
  196. "The parsed JSON should contain the expected values.");
  197. CHECK_MESSAGE(
  198. dictionary["bugs"] == Variant(),
  199. "The parsed JSON should contain the expected values.");
  200. CHECK_MESSAGE(
  201. (int)Dictionary(dictionary["apples"])["blue"] == -20,
  202. "The parsed JSON should contain the expected values.");
  203. CHECK_MESSAGE(
  204. dictionary["empty_object"].hash() == Dictionary().hash(),
  205. "The parsed JSON should contain the expected values.");
  206. }
  207. TEST_CASE("[JSON] Parsing escape sequences") {
  208. // Only certain escape sequences are valid according to the JSON specification.
  209. // Others must result in a parsing error instead.
  210. JSON json;
  211. TypedArray<String> valid_escapes = { "\";\"", "\\;\\", "/;/", "b;\b", "f;\f", "n;\n", "r;\r", "t;\t" };
  212. SUBCASE("Basic valid escape sequences") {
  213. for (int i = 0; i < valid_escapes.size(); i++) {
  214. String valid_escape = valid_escapes[i];
  215. String valid_escape_string = valid_escape.get_slicec(';', 0);
  216. String valid_escape_value = valid_escape.get_slicec(';', 1);
  217. String json_string = "\"\\";
  218. json_string += valid_escape_string;
  219. json_string += "\"";
  220. json.parse(json_string);
  221. CHECK_MESSAGE(
  222. json.get_error_line() == 0,
  223. vformat("Parsing valid escape sequence `%s` as JSON should parse successfully.", valid_escape_string));
  224. String json_value = json.get_data();
  225. CHECK_MESSAGE(
  226. json_value == valid_escape_value,
  227. vformat("Parsing valid escape sequence `%s` as JSON should return the expected value.", valid_escape_string));
  228. }
  229. }
  230. SUBCASE("Valid unicode escape sequences") {
  231. String json_string = "\"\\u0020\"";
  232. json.parse(json_string);
  233. CHECK_MESSAGE(
  234. json.get_error_line() == 0,
  235. vformat("Parsing valid unicode escape sequence with value `0020` as JSON should parse successfully."));
  236. String json_value = json.get_data();
  237. CHECK_MESSAGE(
  238. json_value == " ",
  239. vformat("Parsing valid unicode escape sequence with value `0020` as JSON should return the expected value."));
  240. }
  241. SUBCASE("Invalid escape sequences") {
  242. ERR_PRINT_OFF
  243. for (char32_t i = 0; i < 128; i++) {
  244. bool skip = false;
  245. for (int j = 0; j < valid_escapes.size(); j++) {
  246. String valid_escape = valid_escapes[j];
  247. String valid_escape_string = valid_escape.get_slicec(';', 0);
  248. if (valid_escape_string[0] == i) {
  249. skip = true;
  250. break;
  251. }
  252. }
  253. if (skip) {
  254. continue;
  255. }
  256. String json_string = "\"\\";
  257. json_string += i;
  258. json_string += "\"";
  259. Error err = json.parse(json_string);
  260. // TODO: Line number is currently kept on 0, despite an error occurring. This should be fixed in the JSON parser.
  261. // CHECK_MESSAGE(
  262. // json.get_error_line() != 0,
  263. // vformat("Parsing invalid escape sequence with ASCII value `%d` as JSON should fail to parse.", i));
  264. CHECK_MESSAGE(
  265. err == ERR_PARSE_ERROR,
  266. vformat("Parsing invalid escape sequence with ASCII value `%d` as JSON should fail to parse with ERR_PARSE_ERROR.", i));
  267. }
  268. ERR_PRINT_ON
  269. }
  270. }
  271. TEST_CASE("[JSON] Serialization") {
  272. JSON json;
  273. struct FpTestCase {
  274. double number;
  275. String json;
  276. };
  277. struct IntTestCase {
  278. int64_t number;
  279. String json;
  280. };
  281. struct UIntTestCase {
  282. uint64_t number;
  283. String json;
  284. };
  285. static FpTestCase fp_tests_default_precision[] = {
  286. { 0.0, "0.0" },
  287. { 1000.1234567890123456789, "1000.12345678901" },
  288. { -1000.1234567890123456789, "-1000.12345678901" },
  289. { DBL_MAX, "179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.0" },
  290. { DBL_MAX - 1, "179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.0" },
  291. { std::pow(2, 53), "9007199254740992.0" },
  292. { -std::pow(2, 53), "-9007199254740992.0" },
  293. { 0.00000000000000011, "0.00000000000000011" },
  294. { -0.00000000000000011, "-0.00000000000000011" },
  295. { 1.0 / 3.0, "0.333333333333333" },
  296. { 0.9999999999999999, "1.0" },
  297. { 1.0000000000000001, "1.0" },
  298. };
  299. static FpTestCase fp_tests_full_precision[] = {
  300. { 0.0, "0.0" },
  301. { 1000.1234567890123456789, "1000.12345678901238" },
  302. { -1000.1234567890123456789, "-1000.12345678901238" },
  303. { DBL_MAX, "179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.0" },
  304. { DBL_MAX - 1, "179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.0" },
  305. { std::pow(2, 53), "9007199254740992.0" },
  306. { -std::pow(2, 53), "-9007199254740992.0" },
  307. { 0.00000000000000011, "0.00000000000000011" },
  308. { -0.00000000000000011, "-0.00000000000000011" },
  309. { 1.0 / 3.0, "0.333333333333333315" },
  310. { 0.9999999999999999, "0.999999999999999889" },
  311. { 1.0000000000000001, "1.0" },
  312. };
  313. static IntTestCase int_tests[] = {
  314. { 0, "0" },
  315. { INT64_MAX, "9223372036854775807" },
  316. { INT64_MIN, "-9223372036854775808" },
  317. };
  318. SUBCASE("Floating point default precision") {
  319. for (FpTestCase &test : fp_tests_default_precision) {
  320. String json_value = json.stringify(test.number, "", true, false);
  321. CHECK_MESSAGE(
  322. json_value == test.json,
  323. vformat("Serializing `%.20d` to JSON should return the expected value.", test.number));
  324. }
  325. }
  326. SUBCASE("Floating point full precision") {
  327. for (FpTestCase &test : fp_tests_full_precision) {
  328. String json_value = json.stringify(test.number, "", true, true);
  329. CHECK_MESSAGE(
  330. json_value == test.json,
  331. vformat("Serializing `%20f` to JSON should return the expected value.", test.number));
  332. }
  333. }
  334. SUBCASE("Signed integer") {
  335. for (IntTestCase &test : int_tests) {
  336. String json_value = json.stringify(test.number, "", true, true);
  337. CHECK_MESSAGE(
  338. json_value == test.json,
  339. vformat("Serializing `%d` to JSON should return the expected value.", test.number));
  340. }
  341. }
  342. }
  343. } // namespace TestJSON