blob: 69a71452c5d86aa3bd7d5709176e3347eb1f1be4 [file] [log] [blame]
Eric Haszlakiewicz6988f532012-07-24 23:27:41 -05001#include <stdio.h>
2#include <stdlib.h>
3#include <stddef.h>
4#include <string.h>
5
6#include "json.h"
7
8int main(int argc, char **argv)
9{
10 MC_SET_DEBUG(1);
11
12 /*
13 * Check that replacing an existing object keeps the key valid,
14 * and that it keeps the order the same.
15 */
16 json_object *my_object = json_object_new_object();
17 json_object_object_add(my_object, "foo1", json_object_new_string("bar1"));
18 json_object_object_add(my_object, "foo2", json_object_new_string("bar2"));
Eric Haszlakiewiczf6b27cb2012-10-20 20:26:37 -050019 json_object_object_add(my_object, "deleteme", json_object_new_string("bar2"));
Eric Haszlakiewicz6988f532012-07-24 23:27:41 -050020 json_object_object_add(my_object, "foo3", json_object_new_string("bar3"));
Eric Haszlakiewiczf6b27cb2012-10-20 20:26:37 -050021
22 printf("==== delete-in-loop test starting ====\n");
23
Eric Haszlakiewicz6988f532012-07-24 23:27:41 -050024 int orig_count = 0;
Eric Haszlakiewiczf6b27cb2012-10-20 20:26:37 -050025 json_object_object_foreach(my_object, key0, val0)
26 {
27 printf("Key at index %d is [%s]", orig_count, key0);
28 if (strcmp(key0, "deleteme") == 0)
29 {
30 json_object_object_del(my_object, key0);
31 printf(" (deleted)\n");
32 }
33 else
34 printf(" (kept)\n");
35 orig_count++;
36 }
37
38 printf("==== replace-value first loop starting ====\n");
39
40 const char *original_key = NULL;
41 orig_count = 0;
Eric Haszlakiewicz6988f532012-07-24 23:27:41 -050042 json_object_object_foreach(my_object, key, val)
43 {
44 printf("Key at index %d is [%s]\n", orig_count, key);
45 orig_count++;
46 if (strcmp(key, "foo2") != 0)
47 continue;
48 printf("replacing value for key [%s]\n", key);
49 original_key = key;
50 json_object_object_add(my_object, key, json_object_new_string("zzz"));
51 }
52
53 printf("==== second loop starting ====\n");
54
55 int new_count = 0;
56 int retval = 0;
57 json_object_object_foreach(my_object, key2, val2)
58 {
59 printf("Key at index %d is [%s]\n", new_count, key2);
60 new_count++;
61 if (strcmp(key2, "foo2") != 0)
62 continue;
63 printf("pointer for key [%s] does %smatch\n", key2,
64 (key2 == original_key) ? "" : "NOT ");
65 if (key2 != original_key)
66 retval = 1;
67 }
68 if (new_count != orig_count)
69 {
70 printf("mismatch between original count (%d) and new count (%d)\n",
71 orig_count, new_count);
72 retval = 1;
73 }
74
75 return 0;
76}