testReplaceExisting.c 2.0 KB

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