Skip to content

Commit a525811

Browse files
committed
test: cover AddNumberWithPrecision output
Add public API regressions for cJSON_AddNumberWithPrecisionToObject formatting through cJSON_PrintUnformatted. The new cases assert fixed-width decimal output with preserved trailing zeroes, printf-style rounding, negative number formatting, and the accepted max precision boundary. Also cover invalid precision bounds by checking that 0 and 15 are rejected and leave the destination object empty. Tested:\n- make -C build\n- make -C build test
1 parent 1221b22 commit a525811

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

tests/cjson_add.c

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,43 @@ static void cjson_add_number_should_add_number(void)
255255
cJSON_Delete(root);
256256
}
257257

258+
static void assert_add_number_with_precision_prints(const char *expected, double number, int decimal_places)
259+
{
260+
cJSON *root = cJSON_CreateObject();
261+
char *printed = NULL;
262+
263+
TEST_ASSERT_NOT_NULL(cJSON_AddNumberWithPrecisionToObject(root, "number", number, decimal_places));
264+
265+
printed = cJSON_PrintUnformatted(root);
266+
TEST_ASSERT_EQUAL_STRING(expected, printed);
267+
268+
cJSON_free(printed);
269+
cJSON_Delete(root);
270+
}
271+
272+
static void cjson_add_number_with_precision_should_format_output(void)
273+
{
274+
assert_add_number_with_precision_prints("{\"number\":1.20}", 1.2, 2);
275+
assert_add_number_with_precision_prints("{\"number\":1.24}", 1.236, 2);
276+
assert_add_number_with_precision_prints("{\"number\":-1.200}", -1.2, 3);
277+
assert_add_number_with_precision_prints("{\"number\":0.12345678901234}", 0.12345678901234, 14);
278+
}
279+
280+
static void cjson_add_number_with_precision_should_reject_invalid_precision(void)
281+
{
282+
cJSON *root = cJSON_CreateObject();
283+
char *printed = NULL;
284+
285+
TEST_ASSERT_NULL(cJSON_AddNumberWithPrecisionToObject(root, "number", 1.2, 0));
286+
TEST_ASSERT_NULL(cJSON_AddNumberWithPrecisionToObject(root, "number", 1.2, 15));
287+
288+
printed = cJSON_PrintUnformatted(root);
289+
TEST_ASSERT_EQUAL_STRING("{}", printed);
290+
291+
cJSON_free(printed);
292+
cJSON_Delete(root);
293+
}
294+
258295
static void cjson_add_number_should_fail_with_null_pointers(void)
259296
{
260297
cJSON *root = cJSON_CreateObject();
@@ -448,6 +485,8 @@ int CJSON_CDECL main(void)
448485
RUN_TEST(cjson_add_bool_should_fail_on_allocation_failure);
449486

450487
RUN_TEST(cjson_add_number_should_add_number);
488+
RUN_TEST(cjson_add_number_with_precision_should_format_output);
489+
RUN_TEST(cjson_add_number_with_precision_should_reject_invalid_precision);
451490
RUN_TEST(cjson_add_number_should_fail_with_null_pointers);
452491
RUN_TEST(cjson_add_number_should_fail_on_allocation_failure);
453492

0 commit comments

Comments
 (0)