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