Fix a few memory leaks in tests
[jansson.git] / test / suites / api / test_dump.c
1 /*
2  * Copyright (c) 2009, 2010 Petri Lehtinen <petri@digip.org>
3  *
4  * Jansson is free software; you can redistribute it and/or modify
5  * it under the terms of the MIT license. See LICENSE for details.
6  */
7
8 #include <jansson.h>
9 #include <string.h>
10 #include "util.h"
11
12 int main()
13 {
14     json_t *json;
15     char *result;
16
17     /* Encode an empty object/array, add an item, encode again */
18
19     json = json_object();
20     result = json_dumps(json, 0);
21     if(!result || strcmp(result, "{}"))
22       fail("json_dumps failed");
23     free(result);
24
25     json_object_set_new(json, "foo", json_integer(5));
26     result = json_dumps(json, 0);
27     if(!result || strcmp(result, "{\"foo\": 5}"))
28       fail("json_dumps failed");
29     free(result);
30
31     json_decref(json);
32
33     json = json_array();
34     result = json_dumps(json, 0);
35     if(!result || strcmp(result, "[]"))
36       fail("json_dumps failed");
37     free(result);
38
39     json_array_append_new(json, json_integer(5));
40     result = json_dumps(json, 0);
41     if(!result || strcmp(result, "[5]"))
42       fail("json_dumps failed");
43     free(result);
44
45     json_decref(json);
46
47     /* Construct a JSON object/array with a circular reference:
48
49        object: {"a": {"b": {"c": <circular reference to $.a>}}}
50        array: [[[<circular reference to the $[0] array>]]]
51
52        Encode it, remove the circular reference and encode again.
53     */
54     json = json_object();
55     json_object_set_new(json, "a", json_object());
56     json_object_set_new(json_object_get(json, "a"), "b", json_object());
57     json_object_set(json_object_get(json_object_get(json, "a"), "b"), "c",
58                     json_object_get(json, "a"));
59
60     if(json_dumps(json, 0))
61         fail("json_dumps encoded a circular reference!");
62
63     json_object_del(json_object_get(json_object_get(json, "a"), "b"), "c");
64
65     result = json_dumps(json, 0);
66     if(!result || strcmp(result, "{\"a\": {\"b\": {}}}"))
67         fail("json_dumps failed!");
68     free(result);
69
70     json_decref(json);
71
72     json = json_array();
73     json_array_append_new(json, json_array());
74     json_array_append_new(json_array_get(json, 0), json_array());
75     json_array_append(json_array_get(json_array_get(json, 0), 0),
76                       json_array_get(json, 0));
77
78     if(json_dumps(json, 0))
79         fail("json_dumps encoded a circular reference!");
80
81     json_array_remove(json_array_get(json_array_get(json, 0), 0), 0);
82
83     result = json_dumps(json, 0);
84     if(!result || strcmp(result, "[[[]]]"))
85         fail("json_dumps failed!");
86     free(result);
87
88     json_decref(json);
89
90     return 0;
91 }