Add cJSON_AddObjectToArray() helper fn & unit tests

This commit is contained in:
Ondřej Hruška 2020-07-14 15:00:22 +02:00
parent cf97c6f066
commit e2be5e58b5
3 changed files with 51 additions and 0 deletions

13
cJSON.c
View File

@ -1995,6 +1995,19 @@ CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item)
return add_item_to_array(array, item);
}
/** Create object and add it to array */
CJSON_PUBLIC(cJSON*) cJSON_AddObjectToArray(cJSON * const array)
{
cJSON *object = cJSON_CreateObject();
if (cJSON_AddItemToArray(array, object))
{
return object;
}
cJSON_Delete(object);
return NULL;
}
#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
#pragma GCC diagnostic push
#endif

View File

@ -271,6 +271,10 @@ CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * con
CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name);
/* Helper function to create an object and add it to an existing array.
* It returns the added object or NULL on failure. */
CJSON_PUBLIC(cJSON*) cJSON_AddObjectToArray(cJSON * const array);
/* When assigning an integer value, it needs to be propagated to valuedouble too. */
#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number))
/* helper for the cJSON_SetNumberValue macro */

View File

@ -378,6 +378,36 @@ static void cjson_add_array_should_fail_on_allocation_failure(void)
cJSON_Delete(root);
}
static void cJSON_add_object_to_array_should_add_object(void)
{
cJSON *root = cJSON_CreateArray();
cJSON *object = NULL;
TEST_ASSERT_NOT_NULL(object = cJSON_AddObjectToArray(root));
TEST_ASSERT_EQUAL_INT(cJSON_GetArraySize(root), 1);
TEST_ASSERT_EQUAL_INT(cJSON_GetArrayItem(root, 0)->type, cJSON_Object);
cJSON_Delete(root);
}
static void cjson_add_object_to_array_should_fail_with_null_pointers(void)
{
TEST_ASSERT_NULL(cJSON_AddObjectToArray(NULL));
}
static void cjson_add_object_to_array_should_fail_on_allocation_failure(void)
{
cJSON *root = cJSON_CreateArray();
cJSON_InitHooks(&failing_hooks);
TEST_ASSERT_NULL(cJSON_AddObjectToArray(root));
cJSON_InitHooks(NULL);
cJSON_Delete(root);
}
int CJSON_CDECL main(void)
{
UNITY_BEGIN();
@ -418,5 +448,9 @@ int CJSON_CDECL main(void)
RUN_TEST(cjson_add_array_should_fail_with_null_pointers);
RUN_TEST(cjson_add_array_should_fail_on_allocation_failure);
RUN_TEST(cJSON_add_object_to_array_should_add_object);
RUN_TEST(cjson_add_object_to_array_should_fail_with_null_pointers);
RUN_TEST(cjson_add_object_to_array_should_fail_on_allocation_failure);
return UNITY_END();
}