test_load_callback.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright (c) 2009-2011 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. #include <jansson.h>
  8. #include <string.h>
  9. #include <stdlib.h>
  10. #include "util.h"
  11. struct my_source {
  12. const char *buf;
  13. size_t off;
  14. size_t cap;
  15. };
  16. static const char my_str[] = "[\"A\", {\"B\": \"C\", \"e\": false}, 1, null, \"foo\"]";
  17. static size_t greedy_reader(void *buf, size_t buflen, void *arg)
  18. {
  19. struct my_source *s = arg;
  20. if (buflen > s->cap - s->off)
  21. buflen = s->cap - s->off;
  22. if (buflen > 0) {
  23. memcpy(buf, s->buf + s->off, buflen);
  24. s->off += buflen;
  25. return buflen;
  26. } else {
  27. return 0;
  28. }
  29. }
  30. static void run_tests()
  31. {
  32. struct my_source s;
  33. json_t *json;
  34. json_error_t error;
  35. s.off = 0;
  36. s.cap = strlen(my_str);
  37. s.buf = my_str;
  38. json = json_load_callback(greedy_reader, &s, 0, &error);
  39. if (!json)
  40. fail("json_load_callback failed on a valid callback");
  41. json_decref(json);
  42. s.off = 0;
  43. s.cap = strlen(my_str) - 1;
  44. s.buf = my_str;
  45. json = json_load_callback(greedy_reader, &s, 0, &error);
  46. if (json) {
  47. json_decref(json);
  48. fail("json_load_callback should have failed on an incomplete stream, but it didn't");
  49. }
  50. if (strcmp(error.source, "<callback>") != 0) {
  51. fail("json_load_callback returned an invalid error source");
  52. }
  53. if (strcmp(error.text, "']' expected near end of file") != 0) {
  54. fail("json_load_callback returned an invalid error message for an unclosed top-level array");
  55. }
  56. json = json_load_callback(NULL, NULL, 0, &error);
  57. if (json) {
  58. json_decref(json);
  59. fail("json_load_callback should have failed on NULL load callback, but it didn't");
  60. }
  61. if (strcmp(error.text, "wrong arguments") != 0) {
  62. fail("json_load_callback returned an invalid error message for a NULL load callback");
  63. }
  64. }