Zero the visited flag after an encoding error
[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
24     json_object_set_new(json, "foo", json_integer(5));
25     result = json_dumps(json, 0);
26     if(!result || strcmp(result, "{\"foo\": 5}"))
27       fail("json_dumps failed");
28
29     json_decref(json);
30
31     json = json_array();
32     result = json_dumps(json, 0);
33     if(!result || strcmp(result, "[]"))
34       fail("json_dumps failed");
35     free(result);
36
37     json_array_append_new(json, json_integer(5));
38     result = json_dumps(json, 0);
39     if(!result || strcmp(result, "[5]"))
40       fail("json_dumps failed");
41     free(result);
42
43     json_decref(json);
44
45     /* Construct a JSON object/array with a circular reference:
46
47        object: {"a": {"b": {"c": <circular reference to $.a>}}}
48        array: [[[<circular reference to the $[0] array>]]]
49
50        Encode it, remove the circular reference and encode again.
51     */
52     json = json_object();
53     json_object_set_new(json, "a", json_object());
54     json_object_set_new(json_object_get(json, "a"), "b", json_object());
55     json_object_set(json_object_get(json_object_get(json, "a"), "b"), "c",
56                     json_object_get(json, "a"));
57
58     if(json_dumps(json, 0))
59         fail("json_dumps encoded a circular reference!");
60
61     json_object_del(json_object_get(json_object_get(json, "a"), "b"), "c");
62
63     result = json_dumps(json, 0);
64     if(!result || strcmp(result, "{\"a\": {\"b\": {}}}"))
65         fail("json_dumps failed!");
66     free(result);
67
68     json_decref(json);
69
70     json = json_array();
71     json_array_append_new(json, json_array());
72     json_array_append_new(json_array_get(json, 0), json_array());
73     json_array_append(json_array_get(json_array_get(json, 0), 0),
74                       json_array_get(json, 0));
75
76     if(json_dumps(json, 0))
77         fail("json_dumps encoded a circular reference!");
78
79     json_array_remove(json_array_get(json_array_get(json, 0), 0), 0);
80
81     result = json_dumps(json, 0);
82     if(!result || strcmp(result, "[[[]]]"))
83         fail("json_dumps failed!");
84     free(result);
85
86     json_decref(json);
87
88     return 0;
89 }