提交 2d6a2e01 编写于 作者: M Max Bruckner

Merge branch 'develop' prepare v1.5.0

......@@ -103,7 +103,7 @@ if (NOT WIN32)
target_link_libraries("${CJSON_LIB}" m)
endif()
configure_file("${CMAKE_CURRENT_SOURCE_DIR}/libcjson.pc.in"
configure_file("${CMAKE_CURRENT_SOURCE_DIR}/library_config/libcjson.pc.in"
"${CMAKE_CURRENT_BINARY_DIR}/libcjson.pc" @ONLY)
install(FILES cJSON.h DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/cjson")
......@@ -130,7 +130,7 @@ if(ENABLE_CJSON_UTILS)
add_library("${CJSON_UTILS_LIB}" "${HEADERS_UTILS}" "${SOURCES_UTILS}")
target_link_libraries("${CJSON_UTILS_LIB}" "${CJSON_LIB}")
configure_file("${CMAKE_CURRENT_SOURCE_DIR}/libcjson_utils.pc.in"
configure_file("${CMAKE_CURRENT_SOURCE_DIR}/library_config/libcjson_utils.pc.in"
"${CMAKE_CURRENT_BINARY_DIR}/libcjson_utils.pc" @ONLY)
install(TARGETS "${CJSON_UTILS_LIB}" DESTINATION "${CMAKE_INSTALL_LIBDIR}" EXPORT "${CJSON_UTILS_LIB}")
......@@ -149,10 +149,10 @@ endif()
# create the other package config files
configure_file(
cJSONConfig.cmake.in
"${CMAKE_CURRENT_SOURCE_DIR}/library_config/cJSONConfig.cmake.in"
${PROJECT_BINARY_DIR}/cJSONConfig.cmake @ONLY)
configure_file(
cJSONConfigVersion.cmake.in
"${CMAKE_CURRENT_SOURCE_DIR}/library_config/cJSONConfigVersion.cmake.in"
${PROJECT_BINARY_DIR}/cJSONConfigVersion.cmake @ONLY)
# Install package config files
......@@ -179,18 +179,10 @@ if(ENABLE_CJSON_TEST)
endif()
endif()
if(ENABLE_CJSON_UTILS)
set(TEST_CJSON_UTILS cJSON_test_utils)
add_executable("${TEST_CJSON_UTILS}" test_utils.c)
target_link_libraries("${TEST_CJSON_UTILS}" "${CJSON_UTILS_LIB}")
add_test(NAME ${TEST_CJSON_UTILS} COMMAND "${CMAKE_CURRENT_BINARY_DIR}/${TEST_CJSON_UTILS}")
endif()
#"check" target that automatically builds everything and runs the tests
add_custom_target(check
COMMAND ${CMAKE_CTEST_COMMAND} --output-on-failure
DEPENDS ${TEST_CJSON} ${TEST_CJSON_UTILS})
DEPENDS ${TEST_CJSON})
endif()
add_subdirectory(tests)
......
......@@ -6,6 +6,7 @@ Contributors
* [Anton Sergeev](https://github.com/anton-sergeev)
* [Christian Schulze](https://github.com/ChristianSch)
* [Dave Gamble](https://github.com/DaveGamble)
* [Debora Grosse](https://github.com/DeboraG)
* [dieyushi](https://github.com/dieyushi)
* [Dongwen Huang (黄东文)](https://github.com/DongwenHuang)
* Eswar Yaganti
......@@ -22,7 +23,9 @@ Contributors
* [Max Bruckner](https://github.com/FSMaxB)
* Mike Pontillo
* [Mike Jerris](https://github.com/mjerris)
* [Mike Robinson](https://github.com/mhrobinson)
* Paulo Antonio Alvarez
* [Pawel Winogrodzki](https://github.com/PawelWMS)
* [Rafael Leal Dias](https://github.com/rafaeldias)
* [Rod Vagg](https://github.com/rvagg)
* [Roland Meertens](https://github.com/rmeertens)
......
Copyright (c) 2009 Dave Gamble
Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
......
......@@ -3,10 +3,8 @@ UTILS_OBJ = cJSON_Utils.o
CJSON_LIBNAME = libcjson
UTILS_LIBNAME = libcjson_utils
CJSON_TEST = cJSON_test
UTILS_TEST = cJSON_test_utils
CJSON_TEST_SRC = cJSON.c test.c
UTILS_TEST_SRC = cJSON.c cJSON_Utils.c test_utils.c
LDLIBS = -lm
......@@ -71,9 +69,6 @@ test: tests
#cJSON
$(CJSON_TEST): $(CJSON_TEST_SRC) cJSON.h
$(CC) $(R_CFLAGS) $(CJSON_TEST_SRC) -o $@ $(LDLIBS) -I.
#cJSON_Utils
$(UTILS_TEST): $(UTILS_TEST_SRC) cJSON.h cJSON_Utils.h
$(CC) $(R_CFLAGS) $(UTILS_TEST_SRC) -o $@ $(LDLIBS) -I.
#static libraries
#cJSON
......
......@@ -14,7 +14,9 @@ Ultralightweight JSON parser in ANSI C.
## License
> Copyright (c) 2009-2016 Dave Gamble
MIT License
> Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
>
> Permission is hereby granted, free of charge, to any person obtaining a copy
> of this software and associated documentation files (the "Software"), to deal
......@@ -136,8 +138,8 @@ This is an object. We're in C. We don't have objects. But we do have structs.
What's the framerate?
```c
cJSON *format = cJSON_GetObjectItem(root, "format");
cJSON *framerate_item = cJSON_GetObjectItem(format, "frame rate");
cJSON *format = cJSON_GetObjectItemCaseSensitive(root, "format");
cJSON *framerate_item = cJSON_GetObjectItemCaseSensitive(format, "frame rate");
double framerate = 0;
if (cJSON_IsNumber(framerate_item))
{
......@@ -148,7 +150,7 @@ if (cJSON_IsNumber(framerate_item))
Want to change the framerate?
```c
cJSON *framerate_item = cJSON_GetObjectItem(format, "frame rate");
cJSON *framerate_item = cJSON_GetObjectItemCaseSensitive(format, "frame rate");
cJSON_SetNumberValue(framerate_item, 25);
```
......@@ -395,6 +397,10 @@ cJSON does not officially support any `double` implementations other than IEE754
The maximum length of a floating point literal that cJSON supports is currently 63 characters.
#### Deep Nesting Of Arrays And Objects
cJSON doesn't support arrays and objects that are nested too deeply because this would result in a stack overflow. To prevent this cJSON limits the depth to `CJSON_NESTING_LIMIT` which is 1000 by default but can be changed at compile time.
#### Thread Safety
In general cJSON is **not thread safe**.
......@@ -404,6 +410,10 @@ However it is thread safe under the following conditions:
* `cJSON_InitHooks` is only ever called before using cJSON in any threads.
* `setlocale` is never called before all calls to cJSON functions have returned.
#### Case Sensitivity
When cJSON was originally created, it didn't follow the JSON standard and didn't make a distinction between uppercase and lowercase letters. If you want the correct, standard compliant, behavior, you need to use the `CaseSensitive` functions where available.
# Enjoy cJSON!
- Dave Gamble, Aug 2009
此差异已折叠。
/*
Copyright (c) 2009 Dave Gamble
Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
......@@ -123,18 +123,24 @@ then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJ
#endif
#endif
/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them.
* This is to prevent stack overflows. */
#ifndef CJSON_NESTING_LIMIT
#define CJSON_NESTING_LIMIT 1000
#endif
/* returns the version of cJSON as a string */
CJSON_PUBLIC(const char*) cJSON_Version(void);
/* Supply malloc, realloc and free functions to cJSON */
CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks);
/* Supply a block of JSON, and this returns a cJSON object you can interrogate. Call cJSON_Delete when finished. */
/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */
/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */
CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value);
/* Render a cJSON entity to text for transfer/storage. Free the char* when finished. */
/* Render a cJSON entity to text for transfer/storage. */
CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item);
/* Render a cJSON entity to text for transfer/storage without any formatting. Free the char* when finished. */
/* Render a cJSON entity to text for transfer/storage without any formatting. */
CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item);
/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */
CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt);
......@@ -147,10 +153,10 @@ CJSON_PUBLIC(void) cJSON_Delete(cJSON *c);
/* Returns the number of items in an array (or object). */
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array);
/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */
CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int item);
CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index);
/* Get item "string" from object. Case insensitive. */
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string);
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON *object, const char *string);
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string);
CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string);
/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void);
......@@ -197,21 +203,30 @@ CJSON_PUBLIC(void) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
CJSON_PUBLIC(void) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item);
/* Remove/Detatch items from Arrays/Objects. */
CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which);
CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string);
CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string);
CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string);
/* Update array items. */
CJSON_PUBLIC(void) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement);
CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem);
CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
CJSON_PUBLIC(void) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem);
/* Duplicate a cJSON item */
CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse);
/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will
need to be released. With recurse!=0, it will duplicate any children connected to the item.
The item->next and ->prev pointers are always zero on return from Duplicate. */
/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal.
* case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */
CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive);
/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */
/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error. If not, then cJSON_GetErrorPtr() does the job. */
......@@ -237,6 +252,10 @@ CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number);
/* Macro for iterating over an array */
#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next)
/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */
CJSON_PUBLIC(void *) cJSON_malloc(size_t size);
CJSON_PUBLIC(void) cJSON_free(void *object);
#ifdef __cplusplus
}
#endif
......
此差异已折叠。
/*
Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "cJSON.h"
/* Implement RFC6901 (https://tools.ietf.org/html/rfc6901) JSON Pointer spec. */
CJSON_PUBLIC(cJSON *) cJSONUtils_GetPointer(cJSON *object, const char *pointer);
CJSON_PUBLIC(cJSON *) cJSONUtils_GetPointer(cJSON * const object, const char *pointer);
CJSON_PUBLIC(cJSON *) cJSONUtils_GetPointerCaseSensitive(cJSON * const object, const char *pointer);
/* Implement RFC6902 (https://tools.ietf.org/html/rfc6902) JSON Patch spec. */
CJSON_PUBLIC(cJSON *) cJSONUtils_GeneratePatches(cJSON *from, cJSON *to);
/* NOTE: This modifies objects in 'from' and 'to' by sorting the elements by their key */
CJSON_PUBLIC(cJSON *) cJSONUtils_GeneratePatches(cJSON * const from, cJSON * const to);
CJSON_PUBLIC(cJSON *) cJSONUtils_GeneratePatchesCaseSensitive(cJSON * const from, cJSON * const to);
/* Utility for generating patch array entries. */
CJSON_PUBLIC(void) cJSONUtils_AddPatchToArray(cJSON *array, const char *op, const char *path, cJSON *val);
CJSON_PUBLIC(void) cJSONUtils_AddPatchToArray(cJSON * const array, const char * const operation, const char * const path, const cJSON * const value);
/* Returns 0 for success. */
CJSON_PUBLIC(int) cJSONUtils_ApplyPatches(cJSON *object, cJSON *patches);
CJSON_PUBLIC(int) cJSONUtils_ApplyPatches(cJSON * const object, const cJSON * const patches);
CJSON_PUBLIC(int) cJSONUtils_ApplyPatchesCaseSensitive(cJSON * const object, const cJSON * const patches);
/*
// Note that ApplyPatches is NOT atomic on failure. To implement an atomic ApplyPatches, use:
......@@ -33,12 +59,16 @@ CJSON_PUBLIC(int) cJSONUtils_ApplyPatches(cJSON *object, cJSON *patches);
/* Implement RFC7386 (https://tools.ietf.org/html/rfc7396) JSON Merge Patch spec. */
/* target will be modified by patch. return value is new ptr for target. */
CJSON_PUBLIC(cJSON *) cJSONUtils_MergePatch(cJSON *target, cJSON *patch);
CJSON_PUBLIC(cJSON *) cJSONUtils_MergePatch(cJSON *target, const cJSON * const patch);
CJSON_PUBLIC(cJSON *) cJSONUtils_MergePatchCaseSensitive(cJSON *target, const cJSON * const patch);
/* generates a patch to move from -> to */
CJSON_PUBLIC(cJSON *) cJSONUtils_GenerateMergePatch(cJSON *from, cJSON *to);
/* NOTE: This modifies objects in 'from' and 'to' by sorting the elements by their key */
CJSON_PUBLIC(cJSON *) cJSONUtils_GenerateMergePatch(cJSON * const from, cJSON * const to);
CJSON_PUBLIC(cJSON *) cJSONUtils_GenerateMergePatchCaseSensitive(cJSON * const from, cJSON * const to);
/* Given a root object and a target object, construct a pointer from one to the other. */
CJSON_PUBLIC(char *) cJSONUtils_FindPointerFromObjectTo(cJSON *object, cJSON *target);
CJSON_PUBLIC(char *) cJSONUtils_FindPointerFromObjectTo(const cJSON * const object, const cJSON * const target);
/* Sorts the members of the object into alphabetical order. */
CJSON_PUBLIC(void) cJSONUtils_SortObject(cJSON *object);
CJSON_PUBLIC(void) cJSONUtils_SortObject(cJSON * const object);
CJSON_PUBLIC(void) cJSONUtils_SortObjectCaseSensitive(cJSON * const object);
/*
Copyright (c) 2009 Dave Gamble
Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
......
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "cJSON_Utils.h"
int main(void)
{
/* Some variables */
char *temp = NULL;
char *patchtext = NULL;
char *patchedtext = NULL;
int i = 0;
/* JSON Pointer tests: */
cJSON *root = NULL;
const char *json=
"{"
"\"foo\": [\"bar\", \"baz\"],"
"\"\": 0,"
"\"a/b\": 1,"
"\"c%d\": 2,"
"\"e^f\": 3,"
"\"g|h\": 4,"
"\"i\\\\j\": 5,"
"\"k\\\"l\": 6,"
"\" \": 7,"
"\"m~n\": 8"
"}";
const char *tests[12] = {"","/foo","/foo/0","/","/a~1b","/c%d","/e^f","/g|h","/i\\j","/k\"l","/ ","/m~0n"};
/* JSON Apply Patch tests: */
const char *patches[15][3] =
{
{"{ \"foo\": \"bar\"}", "[{ \"op\": \"add\", \"path\": \"/baz\", \"value\": \"qux\" }]","{\"baz\": \"qux\",\"foo\": \"bar\"}"},
{"{ \"foo\": [ \"bar\", \"baz\" ] }", "[{ \"op\": \"add\", \"path\": \"/foo/1\", \"value\": \"qux\" }]","{\"foo\": [ \"bar\", \"qux\", \"baz\" ] }"},
{"{\"baz\": \"qux\",\"foo\": \"bar\"}"," [{ \"op\": \"remove\", \"path\": \"/baz\" }]","{\"foo\": \"bar\" }"},
{"{ \"foo\": [ \"bar\", \"qux\", \"baz\" ] }","[{ \"op\": \"remove\", \"path\": \"/foo/1\" }]","{\"foo\": [ \"bar\", \"baz\" ] }"},
{"{ \"baz\": \"qux\",\"foo\": \"bar\"}","[{ \"op\": \"replace\", \"path\": \"/baz\", \"value\": \"boo\" }]","{\"baz\": \"boo\",\"foo\": \"bar\"}"},
{"{\"foo\": {\"bar\": \"baz\",\"waldo\": \"fred\"},\"qux\": {\"corge\": \"grault\"}}","[{ \"op\": \"move\", \"from\": \"/foo/waldo\", \"path\": \"/qux/thud\" }]","{\"foo\": {\"bar\": \"baz\"},\"qux\": {\"corge\": \"grault\",\"thud\": \"fred\"}}"},
{"{ \"foo\": [ \"all\", \"grass\", \"cows\", \"eat\" ] }","[ { \"op\": \"move\", \"from\": \"/foo/1\", \"path\": \"/foo/3\" }]","{ \"foo\": [ \"all\", \"cows\", \"eat\", \"grass\" ] }"},
{"{\"baz\": \"qux\",\"foo\": [ \"a\", 2, \"c\" ]}","[{ \"op\": \"test\", \"path\": \"/baz\", \"value\": \"qux\" },{ \"op\": \"test\", \"path\": \"/foo/1\", \"value\": 2 }]",""},
{"{ \"baz\": \"qux\" }","[ { \"op\": \"test\", \"path\": \"/baz\", \"value\": \"bar\" }]",""},
{"{ \"foo\": \"bar\" }","[{ \"op\": \"add\", \"path\": \"/child\", \"value\": { \"grandchild\": { } } }]","{\"foo\": \"bar\",\"child\": {\"grandchild\": {}}}"},
{"{ \"foo\": \"bar\" }","[{ \"op\": \"add\", \"path\": \"/baz\", \"value\": \"qux\", \"xyz\": 123 }]","{\"foo\": \"bar\",\"baz\": \"qux\"}"},
{"{ \"foo\": \"bar\" }","[{ \"op\": \"add\", \"path\": \"/baz/bat\", \"value\": \"qux\" }]",""},
{"{\"/\": 9,\"~1\": 10}","[{\"op\": \"test\", \"path\": \"/~01\", \"value\": 10}]",""},
{"{\"/\": 9,\"~1\": 10}","[{\"op\": \"test\", \"path\": \"/~01\", \"value\": \"10\"}]",""},
{"{ \"foo\": [\"bar\"] }","[ { \"op\": \"add\", \"path\": \"/foo/-\", \"value\": [\"abc\", \"def\"] }]","{\"foo\": [\"bar\", [\"abc\", \"def\"]] }"}
};
/* JSON Apply Merge tests: */
const char *merges[15][3] =
{
{"{\"a\":\"b\"}", "{\"a\":\"c\"}", "{\"a\":\"c\"}"},
{"{\"a\":\"b\"}", "{\"b\":\"c\"}", "{\"a\":\"b\",\"b\":\"c\"}"},
{"{\"a\":\"b\"}", "{\"a\":null}", "{}"},
{"{\"a\":\"b\",\"b\":\"c\"}", "{\"a\":null}", "{\"b\":\"c\"}"},
{"{\"a\":[\"b\"]}", "{\"a\":\"c\"}", "{\"a\":\"c\"}"},
{"{\"a\":\"c\"}", "{\"a\":[\"b\"]}", "{\"a\":[\"b\"]}"},
{"{\"a\":{\"b\":\"c\"}}", "{\"a\":{\"b\":\"d\",\"c\":null}}", "{\"a\":{\"b\":\"d\"}}"},
{"{\"a\":[{\"b\":\"c\"}]}", "{\"a\":[1]}", "{\"a\":[1]}"},
{"[\"a\",\"b\"]", "[\"c\",\"d\"]", "[\"c\",\"d\"]"},
{"{\"a\":\"b\"}", "[\"c\"]", "[\"c\"]"},
{"{\"a\":\"foo\"}", "null", "null"},
{"{\"a\":\"foo\"}", "\"bar\"", "\"bar\""},
{"{\"e\":null}", "{\"a\":1}", "{\"e\":null,\"a\":1}"},
{"[1,2]", "{\"a\":\"b\",\"c\":null}", "{\"a\":\"b\"}"},
{"{}","{\"a\":{\"bb\":{\"ccc\":null}}}", "{\"a\":{\"bb\":{}}}"}
};
/* Misc tests */
int numbers[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
const char *random = "QWERTYUIOPASDFGHJKLZXCVBNM";
char buf[2] = {0,0};
char *before = NULL;
char *after = NULL;
cJSON *object = NULL;
cJSON *nums = NULL;
cJSON *num6 = NULL;
cJSON *sortme = NULL;
printf("JSON Pointer Tests\n");
root = cJSON_Parse(json);
for (i = 0; i < 12; i++)
{
char *output = cJSON_Print(cJSONUtils_GetPointer(root, tests[i]));
printf("Test %d:\n%s\n\n", i + 1, output);
free(output);
}
cJSON_Delete(root);
printf("JSON Apply Patch Tests\n");
for (i = 0; i < 15; i++)
{
cJSON *object_to_be_patched = cJSON_Parse(patches[i][0]);
cJSON *patch = cJSON_Parse(patches[i][1]);
int err = cJSONUtils_ApplyPatches(object_to_be_patched, patch);
char *output = cJSON_Print(object_to_be_patched);
printf("Test %d (err %d):\n%s\n\n", i + 1, err, output);
free(output);
cJSON_Delete(object_to_be_patched);
cJSON_Delete(patch);
}
/* JSON Generate Patch tests: */
printf("JSON Generate Patch Tests\n");
for (i = 0; i < 15; i++)
{
cJSON *from;
cJSON *to;
cJSON *patch;
char *out;
if (!strlen(patches[i][2]))
{
continue;
}
from = cJSON_Parse(patches[i][0]);
to = cJSON_Parse(patches[i][2]);
patch = cJSONUtils_GeneratePatches(from, to);
out = cJSON_Print(patch);
printf("Test %d: (patch: %s):\n%s\n\n", i + 1, patches[i][1], out);
free(out);
cJSON_Delete(from);
cJSON_Delete(to);
cJSON_Delete(patch);
}
/* Misc tests: */
printf("JSON Pointer construct\n");
object = cJSON_CreateObject();
nums = cJSON_CreateIntArray(numbers, 10);
num6 = cJSON_GetArrayItem(nums, 6);
cJSON_AddItemToObject(object, "numbers", nums);
temp = cJSONUtils_FindPointerFromObjectTo(object, num6);
printf("Pointer: [%s]\n", temp);
free(temp);
temp = cJSONUtils_FindPointerFromObjectTo(object, nums);
printf("Pointer: [%s]\n", temp);
free(temp);
temp = cJSONUtils_FindPointerFromObjectTo(object, object);
printf("Pointer: [%s]\n", temp);
free(temp);
cJSON_Delete(object);
/* JSON Sort test: */
sortme = cJSON_CreateObject();
for (i = 0; i < 26; i++)
{
buf[0] = random[i];
cJSON_AddItemToObject(sortme, buf, cJSON_CreateNumber(1));
}
before = cJSON_PrintUnformatted(sortme);
cJSONUtils_SortObject(sortme);
after = cJSON_PrintUnformatted(sortme);
printf("Before: [%s]\nAfter: [%s]\n\n", before, after);
free(before);
free(after);
cJSON_Delete(sortme);
/* Merge tests: */
printf("JSON Merge Patch tests\n");
for (i = 0; i < 15; i++)
{
cJSON *object_to_be_merged = cJSON_Parse(merges[i][0]);
cJSON *patch = cJSON_Parse(merges[i][1]);
char *before_merge = cJSON_PrintUnformatted(object_to_be_merged);
patchtext = cJSON_PrintUnformatted(patch);
printf("Before: [%s] -> [%s] = ", before_merge, patchtext);
object_to_be_merged = cJSONUtils_MergePatch(object_to_be_merged, patch);
after = cJSON_PrintUnformatted(object_to_be_merged);
printf("[%s] vs [%s] (%s)\n", after, merges[i][2], strcmp(after, merges[i][2]) ? "FAIL" : "OK");
free(before_merge);
free(patchtext);
free(after);
cJSON_Delete(object_to_be_merged);
cJSON_Delete(patch);
}
/* Generate Merge tests: */
for (i = 0; i < 15; i++)
{
cJSON *from = cJSON_Parse(merges[i][0]);
cJSON *to = cJSON_Parse(merges[i][2]);
cJSON *patch = cJSONUtils_GenerateMergePatch(from,to);
from = cJSONUtils_MergePatch(from,patch);
patchtext = cJSON_PrintUnformatted(patch);
patchedtext = cJSON_PrintUnformatted(from);
printf("Patch [%s] vs [%s] = [%s] vs [%s] (%s)\n", patchtext, merges[i][1], patchedtext, merges[i][2], strcmp(patchedtext, merges[i][2]) ? "FAIL" : "OK");
cJSON_Delete(from);
cJSON_Delete(to);
cJSON_Delete(patch);
free(patchtext);
free(patchedtext);
}
return 0;
}
......@@ -45,6 +45,8 @@ if(ENABLE_CJSON_TEST)
print_object
print_value
misc_tests
parse_with_opts
compare_tests
)
add_library(test-common common.c)
......@@ -73,4 +75,29 @@ if(ENABLE_CJSON_TEST)
endforeach()
add_dependencies(check ${unity_tests})
if (ENABLE_CJSON_UTILS)
#copy test files
file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/json-patch-tests")
file(GLOB test_files "json-patch-tests/*")
file(COPY ${test_files} DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/json-patch-tests/")
set (cjson_utils_tests
json_patch_tests
old_utils_tests)
foreach (cjson_utils_test ${cjson_utils_tests})
add_executable("${cjson_utils_test}" "${cjson_utils_test}.c")
target_link_libraries("${cjson_utils_test}" "${CJSON_LIB}" "${CJSON_UTILS_LIB}" unity test-common)
if(MEMORYCHECK_COMMAND)
add_test(NAME "${cjson_utils_test}"
COMMAND "${MEMORYCHECK_COMMAND}" ${MEMORYCHECK_COMMAND_OPTIONS} "${CMAKE_CURRENT_BINARY_DIR}/${cjson_utils_test}")
else()
add_test(NAME "${cjson_utils_test}"
COMMAND "./${cjson_utils_test}")
endif()
endforeach()
add_dependencies(check ${cjson_utils_tests})
endif()
endif()
/*
Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "unity/examples/unity_config.h"
#include "unity/src/unity.h"
#include "common.h"
static cJSON_bool compare_from_string(const char * const a, const char * const b, const cJSON_bool case_sensitive)
{
cJSON *a_json = NULL;
cJSON *b_json = NULL;
cJSON_bool result = false;
a_json = cJSON_Parse(a);
TEST_ASSERT_NOT_NULL_MESSAGE(a_json, "Failed to parse a.");
b_json = cJSON_Parse(b);
TEST_ASSERT_NOT_NULL_MESSAGE(b_json, "Failed to parse b.");
result = cJSON_Compare(a_json, b_json, case_sensitive);
cJSON_Delete(a_json);
cJSON_Delete(b_json);
return result;
}
static void cjson_compare_should_compare_null_pointer_as_not_equal(void)
{
TEST_ASSERT_FALSE(cJSON_Compare(NULL, NULL, true));
TEST_ASSERT_FALSE(cJSON_Compare(NULL, NULL, false));
}
static void cjson_compare_should_compare_invalid_as_not_equal(void)
{
cJSON invalid[1];
memset(invalid, '\0', sizeof(invalid));
TEST_ASSERT_FALSE(cJSON_Compare(invalid, invalid, false));
TEST_ASSERT_FALSE(cJSON_Compare(invalid, invalid, true));
}
static void cjson_compare_should_compare_numbers(void)
{
TEST_ASSERT_TRUE(compare_from_string("1", "1", true));
TEST_ASSERT_TRUE(compare_from_string("1", "1", false));
TEST_ASSERT_TRUE(compare_from_string("0.0001", "0.0001", true));
TEST_ASSERT_TRUE(compare_from_string("0.0001", "0.0001", false));
TEST_ASSERT_FALSE(compare_from_string("1", "2", true));
TEST_ASSERT_FALSE(compare_from_string("1", "2", false));
}
static void cjson_compare_should_compare_booleans(void)
{
/* true */
TEST_ASSERT_TRUE(compare_from_string("true", "true", true));
TEST_ASSERT_TRUE(compare_from_string("true", "true", false));
/* false */
TEST_ASSERT_TRUE(compare_from_string("false", "false", true));
TEST_ASSERT_TRUE(compare_from_string("false", "false", false));
/* mixed */
TEST_ASSERT_FALSE(compare_from_string("true", "false", true));
TEST_ASSERT_FALSE(compare_from_string("true", "false", false));
TEST_ASSERT_FALSE(compare_from_string("false", "true", true));
TEST_ASSERT_FALSE(compare_from_string("false", "true", false));
}
static void cjson_compare_should_compare_null(void)
{
TEST_ASSERT_TRUE(compare_from_string("null", "null", true));
TEST_ASSERT_TRUE(compare_from_string("null", "null", false));
TEST_ASSERT_FALSE(compare_from_string("null", "true", true));
TEST_ASSERT_FALSE(compare_from_string("null", "true", false));
}
static void cjson_compare_should_not_accept_invalid_types(void)
{
cJSON invalid[1];
memset(invalid, '\0', sizeof(invalid));
invalid->type = cJSON_Number | cJSON_String;
TEST_ASSERT_FALSE(cJSON_Compare(invalid, invalid, true));
TEST_ASSERT_FALSE(cJSON_Compare(invalid, invalid, false));
}
static void cjson_compare_should_compare_strings(void)
{
TEST_ASSERT_TRUE(compare_from_string("\"abcdefg\"", "\"abcdefg\"", true));
TEST_ASSERT_TRUE(compare_from_string("\"abcdefg\"", "\"abcdefg\"", false));
TEST_ASSERT_FALSE(compare_from_string("\"ABCDEFG\"", "\"abcdefg\"", true));
TEST_ASSERT_FALSE(compare_from_string("\"ABCDEFG\"", "\"abcdefg\"", false));
}
static void cjson_compare_should_compare_raw(void)
{
cJSON *raw1 = NULL;
cJSON *raw2 = NULL;
raw1 = cJSON_Parse("\"[true, false]\"");
TEST_ASSERT_NOT_NULL(raw1);
raw2 = cJSON_Parse("\"[true, false]\"");
TEST_ASSERT_NOT_NULL(raw2);
raw1->type = cJSON_Raw;
raw2->type = cJSON_Raw;
TEST_ASSERT_TRUE(cJSON_Compare(raw1, raw2, true));
TEST_ASSERT_TRUE(cJSON_Compare(raw1, raw2, false));
cJSON_Delete(raw1);
cJSON_Delete(raw2);
}
static void cjson_compare_should_compare_arrays(void)
{
TEST_ASSERT_TRUE(compare_from_string("[]", "[]", true));
TEST_ASSERT_TRUE(compare_from_string("[]", "[]", false));
TEST_ASSERT_TRUE(compare_from_string("[false,true,null,42,\"string\",[],{}]", "[false, true, null, 42, \"string\", [], {}]", true));
TEST_ASSERT_TRUE(compare_from_string("[false,true,null,42,\"string\",[],{}]", "[false, true, null, 42, \"string\", [], {}]", false));
TEST_ASSERT_TRUE(compare_from_string("[[[1], 2]]", "[[[1], 2]]", true));
TEST_ASSERT_TRUE(compare_from_string("[[[1], 2]]", "[[[1], 2]]", false));
TEST_ASSERT_FALSE(compare_from_string("[true,null,42,\"string\",[],{}]", "[false, true, null, 42, \"string\", [], {}]", true));
TEST_ASSERT_FALSE(compare_from_string("[true,null,42,\"string\",[],{}]", "[false, true, null, 42, \"string\", [], {}]", false));
}
static void cjson_compare_should_compare_objects(void)
{
TEST_ASSERT_TRUE(compare_from_string("{}", "{}", true));
TEST_ASSERT_TRUE(compare_from_string("{}", "{}", false));
TEST_ASSERT_TRUE(compare_from_string(
"{\"false\": false, \"true\": true, \"null\": null, \"number\": 42, \"string\": \"string\", \"array\": [], \"object\": {}}",
"{\"true\": true, \"false\": false, \"null\": null, \"number\": 42, \"string\": \"string\", \"array\": [], \"object\": {}}",
true));
TEST_ASSERT_FALSE(compare_from_string(
"{\"False\": false, \"true\": true, \"null\": null, \"number\": 42, \"string\": \"string\", \"array\": [], \"object\": {}}",
"{\"true\": true, \"false\": false, \"null\": null, \"number\": 42, \"string\": \"string\", \"array\": [], \"object\": {}}",
true));
TEST_ASSERT_TRUE(compare_from_string(
"{\"False\": false, \"true\": true, \"null\": null, \"number\": 42, \"string\": \"string\", \"array\": [], \"object\": {}}",
"{\"true\": true, \"false\": false, \"null\": null, \"number\": 42, \"string\": \"string\", \"array\": [], \"object\": {}}",
false));
TEST_ASSERT_FALSE(compare_from_string(
"{\"Flse\": false, \"true\": true, \"null\": null, \"number\": 42, \"string\": \"string\", \"array\": [], \"object\": {}}",
"{\"true\": true, \"false\": false, \"null\": null, \"number\": 42, \"string\": \"string\", \"array\": [], \"object\": {}}",
false));
}
int main(void)
{
UNITY_BEGIN();
RUN_TEST(cjson_compare_should_compare_null_pointer_as_not_equal);
RUN_TEST(cjson_compare_should_compare_invalid_as_not_equal);
RUN_TEST(cjson_compare_should_compare_numbers);
RUN_TEST(cjson_compare_should_compare_booleans);
RUN_TEST(cjson_compare_should_compare_null);
RUN_TEST(cjson_compare_should_not_accept_invalid_types);
RUN_TEST(cjson_compare_should_compare_strings);
RUN_TEST(cjson_compare_should_compare_raw);
RUN_TEST(cjson_compare_should_compare_arrays);
RUN_TEST(cjson_compare_should_compare_objects);
return UNITY_END();
}
# EditorConfig is awesome: http://EditorConfig.org
root = true
[*]
end_of_line = lf
insert_final_newline = true
charset = utf-8
trim_trailing_whitespace = true
indent_style = space
*~
\#*
!.editorconfig
!.gitignore
JSON Patch Tests
================
These are test cases for implementations of [IETF JSON Patch (RFC6902)](http://tools.ietf.org/html/rfc6902).
Some implementations can be found at [jsonpatch.com](http://jsonpatch.com).
Test Format
-----------
Each test file is a JSON document that contains an array of test records. A
test record is an object with the following members:
- doc: The JSON document to test against
- patch: The patch(es) to apply
- expected: The expected resulting document, OR
- error: A string describing an expected error
- comment: A string describing the test
- disabled: True if the test should be skipped
All fields except 'doc' and 'patch' are optional. Test records consisting only
of a comment are also OK.
Files
-----
- tests.json: the main test file
- spec_tests.json: tests from the RFC6902 spec
Writing Tests
-------------
All tests should have a descriptive comment. Tests should be as
simple as possible - just what's required to test a specific piece of
behavior. If you want to test interacting behaviors, create tests for
each behavior as well as the interaction.
If an 'error' member is specified, the error text should describe the
error the implementation should raise - *not* what's being tested.
Implementation error strings will vary, but the suggested error should
be easily matched to the implementation error string. Try to avoid
creating error tests that might pass because an incorrect error was
reported.
Please feel free to contribute!
Credits
-------
The seed test set was adapted from Byron Ruth's
[jsonpatch-js](https://github.com/bruth/jsonpatch-js/blob/master/test.js) and
extended by [Mike McCabe](https://github.com/mikemccabe).
License
-------
Copyright 2014 The Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
[
{
"comment": "1",
"doc": { "foo": "bar"},
"patch": [{ "op": "add", "path": "/baz", "value": "qux" }],
"expected": {"baz": "qux", "foo": "bar"}
},
{
"comment": "2",
"doc": { "foo": [ "bar", "baz" ] },
"patch": [{ "op": "add", "path": "/foo/1", "value": "qux" }],
"expected": {"foo": [ "bar", "qux", "baz" ] }
},
{
"comment": "3",
"doc": {"baz": "qux","foo": "bar"},
"patch": [{ "op": "remove", "path": "/baz" }],
"expected": {"foo": "bar" }
},
{
"comment": "4",
"doc": { "foo": [ "bar", "qux", "baz" ] },
"patch": [{ "op": "remove", "path": "/foo/1" }],
"expected": {"foo": [ "bar", "baz" ] }
},
{
"comment": "5",
"doc": { "baz": "qux","foo": "bar"},
"patch": [{ "op": "replace", "path": "/baz", "value": "boo" }],
"expected": {"baz": "boo","foo": "bar"}
},
{
"comment": "6",
"doc": {"foo": {"bar": "baz","waldo": "fred"},"qux": {"corge": "grault"}},
"patch": [{ "op": "move", "from": "/foo/waldo", "path": "/qux/thud" }],
"expected": {"foo": {"bar": "baz"},"qux": {"corge": "grault","thud": "fred"}}
},
{
"comment": "7",
"doc": { "foo": [ "all", "grass", "cows", "eat" ] },
"patch": [ { "op": "move", "from": "/foo/1", "path": "/foo/3" }],
"expected": { "foo": [ "all", "cows", "eat", "grass" ] }
},
{
"comment": "8",
"doc": {"baz": "qux","foo": [ "a", 2, "c" ]},
"patch": [{ "op": "test", "path": "/baz", "value": "qux" },{ "op": "test", "path": "/foo/1", "value": 2 }]
},
{
"comment": "9",
"doc": { "baz": "qux" },
"patch": [ { "op": "test", "path": "/baz", "value": "bar" }],
"error": "\"bar\" doesn't exist"
},
{
"comment": "10",
"doc": { "foo": "bar" },
"patch": [{ "op": "add", "path": "/child", "value": { "grandchild": { } } }],
"expected": {"foo": "bar","child": {"grandchild": {}}}
},
{
"comment": "11",
"doc": { "foo": "bar" },
"patch": [{ "op": "add", "path": "/baz", "value": "qux", "xyz": 123 }],
"expected": {"foo": "bar","baz": "qux"}
},
{
"comment": "12",
"doc": { "foo": "bar" },
"patch": [{ "op": "add", "path": "/baz/bat", "value": "qux" }],
"error": "Can't add to nonexistent object"
},
{
"comment": "13",
"doc": {"/": 9,"~1": 10},
"patch": [{"op": "test", "path": "/~01", "value": 10}]
},
{
"comment": "14",
"doc": { "foo": ["bar"] },
"patch": [ { "op": "add", "path": "/foo/-", "value": ["abc", "def"] }],
"expected": {"foo": ["bar", ["abc", "def"]] }
}
]
{
"name": "json-patch-test-suite",
"version": "1.1.0",
"description": "JSON Patch RFC 6902 test suite",
"repository": "github:json-patch/json-patch-tests",
"homepage": "https://github.com/json-patch/json-patch-tests",
"bugs": "https://github.com/json-patch/json-patch-tests/issues",
"keywords": [
"JSON",
"Patch",
"test",
"suite"
],
"license": "Apache-2.0"
}
[
{
"comment": "4.1. add with missing object",
"doc": { "q": { "bar": 2 } },
"patch": [ {"op": "add", "path": "/a/b", "value": 1} ],
"error":
"path /a does not exist -- missing objects are not created recursively"
},
{
"comment": "A.1. Adding an Object Member",
"doc": {
"foo": "bar"
},
"patch": [
{ "op": "add", "path": "/baz", "value": "qux" }
],
"expected": {
"baz": "qux",
"foo": "bar"
}
},
{
"comment": "A.2. Adding an Array Element",
"doc": {
"foo": [ "bar", "baz" ]
},
"patch": [
{ "op": "add", "path": "/foo/1", "value": "qux" }
],
"expected": {
"foo": [ "bar", "qux", "baz" ]
}
},
{
"comment": "A.3. Removing an Object Member",
"doc": {
"baz": "qux",
"foo": "bar"
},
"patch": [
{ "op": "remove", "path": "/baz" }
],
"expected": {
"foo": "bar"
}
},
{
"comment": "A.4. Removing an Array Element",
"doc": {
"foo": [ "bar", "qux", "baz" ]
},
"patch": [
{ "op": "remove", "path": "/foo/1" }
],
"expected": {
"foo": [ "bar", "baz" ]
}
},
{
"comment": "A.5. Replacing a Value",
"doc": {
"baz": "qux",
"foo": "bar"
},
"patch": [
{ "op": "replace", "path": "/baz", "value": "boo" }
],
"expected": {
"baz": "boo",
"foo": "bar"
}
},
{
"comment": "A.6. Moving a Value",
"doc": {
"foo": {
"bar": "baz",
"waldo": "fred"
},
"qux": {
"corge": "grault"
}
},
"patch": [
{ "op": "move", "from": "/foo/waldo", "path": "/qux/thud" }
],
"expected": {
"foo": {
"bar": "baz"
},
"qux": {
"corge": "grault",
"thud": "fred"
}
}
},
{
"comment": "A.7. Moving an Array Element",
"doc": {
"foo": [ "all", "grass", "cows", "eat" ]
},
"patch": [
{ "op": "move", "from": "/foo/1", "path": "/foo/3" }
],
"expected": {
"foo": [ "all", "cows", "eat", "grass" ]
}
},
{
"comment": "A.8. Testing a Value: Success",
"doc": {
"baz": "qux",
"foo": [ "a", 2, "c" ]
},
"patch": [
{ "op": "test", "path": "/baz", "value": "qux" },
{ "op": "test", "path": "/foo/1", "value": 2 }
],
"expected": {
"baz": "qux",
"foo": [ "a", 2, "c" ]
}
},
{
"comment": "A.9. Testing a Value: Error",
"doc": {
"baz": "qux"
},
"patch": [
{ "op": "test", "path": "/baz", "value": "bar" }
],
"error": "string not equivalent"
},
{
"comment": "A.10. Adding a nested Member Object",
"doc": {
"foo": "bar"
},
"patch": [
{ "op": "add", "path": "/child", "value": { "grandchild": { } } }
],
"expected": {
"foo": "bar",
"child": {
"grandchild": {
}
}
}
},
{
"comment": "A.11. Ignoring Unrecognized Elements",
"doc": {
"foo":"bar"
},
"patch": [
{ "op": "add", "path": "/baz", "value": "qux", "xyz": 123 }
],
"expected": {
"foo":"bar",
"baz":"qux"
}
},
{
"comment": "A.12. Adding to a Non-existent Target",
"doc": {
"foo": "bar"
},
"patch": [
{ "op": "add", "path": "/baz/bat", "value": "qux" }
],
"error": "add to a non-existent target"
},
{
"comment": "A.13 Invalid JSON Patch Document",
"doc": {
"foo": "bar"
},
"patch": [
{ "op": "add", "path": "/baz", "value": "qux", "op": "remove" }
],
"error": "operation has two 'op' members",
"disabled": true
},
{
"comment": "A.14. ~ Escape Ordering",
"doc": {
"/": 9,
"~1": 10
},
"patch": [{"op": "test", "path": "/~01", "value": 10}],
"expected": {
"/": 9,
"~1": 10
}
},
{
"comment": "A.15. Comparing Strings and Numbers",
"doc": {
"/": 9,
"~1": 10
},
"patch": [{"op": "test", "path": "/~01", "value": "10"}],
"error": "number is not equal to string"
},
{
"comment": "A.16. Adding an Array Value",
"doc": {
"foo": ["bar"]
},
"patch": [{ "op": "add", "path": "/foo/-", "value": ["abc", "def"] }],
"expected": {
"foo": ["bar", ["abc", "def"]]
}
}
]
此差异已折叠。
/*
Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "unity/examples/unity_config.h"
#include "unity/src/unity.h"
#include "common.h"
#include "../cJSON_Utils.h"
static cJSON *parse_test_file(const char * const filename)
{
char *file = NULL;
cJSON *json = NULL;
file = read_file(filename);
TEST_ASSERT_NOT_NULL_MESSAGE(file, "Failed to read file.");
json = cJSON_Parse(file);
TEST_ASSERT_NOT_NULL_MESSAGE(json, "Failed to parse test json.");
TEST_ASSERT_TRUE_MESSAGE(cJSON_IsArray(json), "Json is not an array.");
free(file);
return json;
}
static cJSON_bool test_apply_patch(const cJSON * const test)
{
cJSON *doc = NULL;
cJSON *patch = NULL;
cJSON *expected = NULL;
cJSON *error_element = NULL;
cJSON *comment = NULL;
cJSON *disabled = NULL;
cJSON *object = NULL;
cJSON_bool successful = false;
/* extract all the data out of the test */
comment = cJSON_GetObjectItemCaseSensitive(test, "comment");
if (cJSON_IsString(comment))
{
printf("Testing \"%s\"\n", comment->valuestring);
}
else
{
printf("Testing unkown\n");
}
disabled = cJSON_GetObjectItemCaseSensitive(test, "disabled");
if (cJSON_IsTrue(disabled))
{
printf("SKIPPED\n");
return true;
}
doc = cJSON_GetObjectItemCaseSensitive(test, "doc");
TEST_ASSERT_NOT_NULL_MESSAGE(doc, "No \"doc\" in the test.");
patch = cJSON_GetObjectItemCaseSensitive(test, "patch");
TEST_ASSERT_NOT_NULL_MESSAGE(patch, "No \"patch\"in the test.");
/* Make a working copy of 'doc' */
object = cJSON_Duplicate(doc, true);
TEST_ASSERT_NOT_NULL(object);
expected = cJSON_GetObjectItemCaseSensitive(test, "expected");
error_element = cJSON_GetObjectItemCaseSensitive(test, "error");
if (error_element != NULL)
{
/* excepting an error */
TEST_ASSERT_TRUE_MESSAGE(0 != cJSONUtils_ApplyPatchesCaseSensitive(object, patch), "Test didn't fail as it's supposed to.");
successful = true;
}
else
{
/* apply the patch */
TEST_ASSERT_EQUAL_INT_MESSAGE(0, cJSONUtils_ApplyPatchesCaseSensitive(object, patch), "Failed to apply patches.");
successful = true;
if (expected != NULL)
{
successful = cJSON_Compare(object, expected, true);
}
}
cJSON_Delete(object);
if (successful)
{
printf("OK\n");
}
else
{
printf("FAILED\n");
}
return successful;
}
static cJSON_bool test_generate_test(cJSON *test __attribute__((unused)))
{
cJSON *doc = NULL;
cJSON *patch = NULL;
cJSON *expected = NULL;
cJSON *disabled = NULL;
cJSON *object = NULL;
cJSON_bool successful = false;
char *printed_patch = NULL;
disabled = cJSON_GetObjectItemCaseSensitive(test, "disabled");
if (cJSON_IsTrue(disabled))
{
printf("SKIPPED\n");
return true;
}
doc = cJSON_GetObjectItemCaseSensitive(test, "doc");
TEST_ASSERT_NOT_NULL_MESSAGE(doc, "No \"doc\" in the test.");
/* Make a working copy of 'doc' */
object = cJSON_Duplicate(doc, true);
TEST_ASSERT_NOT_NULL(object);
expected = cJSON_GetObjectItemCaseSensitive(test, "expected");
if (expected == NULL)
{
cJSON_Delete(object);
/* if there is no expected output, this test doesn't make sense */
return true;
}
patch = cJSONUtils_GeneratePatchesCaseSensitive(doc, expected);
TEST_ASSERT_NOT_NULL_MESSAGE(patch, "Failed to generate patches.");
printed_patch = cJSON_Print(patch);
printf("%s\n", printed_patch);
free(printed_patch);
/* apply the generated patch */
TEST_ASSERT_EQUAL_INT_MESSAGE(0, cJSONUtils_ApplyPatchesCaseSensitive(object, patch), "Failed to apply generated patch.");
successful = cJSON_Compare(object, expected, true);
cJSON_Delete(patch);
cJSON_Delete(object);
if (successful)
{
printf("generated patch: OK\n");
}
else
{
printf("generated patch: FAILED\n");
}
return successful;
}
static void cjson_utils_should_pass_json_patch_test_tests(void)
{
cJSON *tests = parse_test_file("json-patch-tests/tests.json");
cJSON *test = NULL;
cJSON_bool failed = false;
cJSON_ArrayForEach(test, tests)
{
failed |= !test_apply_patch(test);
failed |= !test_generate_test(test);
}
cJSON_Delete(tests);
TEST_ASSERT_FALSE_MESSAGE(failed, "Some tests failed.");
}
static void cjson_utils_should_pass_json_patch_test_spec_tests(void)
{
cJSON *tests = parse_test_file("json-patch-tests/spec_tests.json");
cJSON *test = NULL;
cJSON_bool failed = false;
cJSON_ArrayForEach(test, tests)
{
failed |= !test_apply_patch(test);
failed |= !test_generate_test(test);
}
cJSON_Delete(tests);
TEST_ASSERT_FALSE_MESSAGE(failed, "Some tests failed.");
}
static void cjson_utils_should_pass_json_patch_test_cjson_utils_tests(void)
{
cJSON *tests = parse_test_file("json-patch-tests/cjson-utils-tests.json");
cJSON *test = NULL;
cJSON_bool failed = false;
cJSON_ArrayForEach(test, tests)
{
failed |= !test_apply_patch(test);
failed |= !test_generate_test(test);
}
cJSON_Delete(tests);
TEST_ASSERT_FALSE_MESSAGE(failed, "Some tests failed.");
}
int main(void)
{
UNITY_BEGIN();
RUN_TEST(cjson_utils_should_pass_json_patch_test_tests);
RUN_TEST(cjson_utils_should_pass_json_patch_test_spec_tests);
RUN_TEST(cjson_utils_should_pass_json_patch_test_cjson_utils_tests);
return UNITY_END();
}
此差异已折叠。
此差异已折叠。
......@@ -30,8 +30,6 @@
static cJSON item[1];
static const unsigned char *error_pointer = NULL;
static void assert_is_array(cJSON *array_item)
{
TEST_ASSERT_NOT_NULL_MESSAGE(array_item, "Item is NULL.");
......@@ -46,13 +44,23 @@ static void assert_is_array(cJSON *array_item)
static void assert_not_array(const char *json)
{
TEST_ASSERT_NULL(parse_array(item, (const unsigned char*)json, &error_pointer, &global_hooks));
parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } };
buffer.content = (const unsigned char*)json;
buffer.length = strlen(json) + sizeof("");
buffer.hooks = global_hooks;
TEST_ASSERT_FALSE(parse_array(item, &buffer));
assert_is_invalid(item);
}
static void assert_parse_array(const char *json)
{
TEST_ASSERT_NOT_NULL(parse_array(item, (const unsigned char*)json, &error_pointer, &global_hooks));
parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } };
buffer.content = (const unsigned char*)json;
buffer.length = strlen(json) + sizeof("");
buffer.hooks = global_hooks;
TEST_ASSERT_TRUE(parse_array(item, &buffer));
assert_is_array(item);
}
......
......@@ -45,7 +45,11 @@ static void assert_is_number(cJSON *number_item)
static void assert_parse_number(const char *string, int integer, double real)
{
TEST_ASSERT_NOT_NULL(parse_number(item, (const unsigned char*)string));
parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } };
buffer.content = (const unsigned char*)string;
buffer.length = strlen(string) + sizeof("");
TEST_ASSERT_TRUE(parse_number(item, &buffer));
assert_is_number(item);
TEST_ASSERT_EQUAL_INT(integer, item->valueint);
TEST_ASSERT_EQUAL_DOUBLE(real, item->valuedouble);
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
......@@ -27,13 +27,14 @@
static void assert_print_string(const char *expected, const char *input)
{
unsigned char printed[1024];
printbuffer buffer;
printbuffer buffer = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } };
buffer.buffer = printed;
buffer.length = sizeof(printed);
buffer.offset = 0;
buffer.noalloc = true;
buffer.hooks = global_hooks;
TEST_ASSERT_TRUE_MESSAGE(print_string_ptr((const unsigned char*)input, &buffer, &global_hooks), "Failed to print string.");
TEST_ASSERT_TRUE_MESSAGE(print_string_ptr((const unsigned char*)input, &buffer), "Failed to print string.");
TEST_ASSERT_EQUAL_STRING_MESSAGE(expected, printed, "The printed string isn't as expected.");
}
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册