Test that we can segment and parse a stream of json objects correctly. */
| 207 | |
| 208 | /* Test that we can segment and parse a stream of json objects correctly. */ |
| 209 | static void test_json_stream(void) |
| 210 | { |
| 211 | bool valid, complete; |
| 212 | char *input, *talstr; |
| 213 | jsmntok_t *toks; |
| 214 | jsmn_parser parser; |
| 215 | |
| 216 | /* Multiple full messages in a single buffer (happens when buffer |
| 217 | * boundary coincides with message boundary, or read returned after |
| 218 | * timeout. */ |
| 219 | input = "{\"x\":\"x\"}{\"y\":\"y\"}"; |
| 220 | talstr = tal_strndup(NULL, input, strlen(input)); |
| 221 | toks = toks_alloc(NULL); |
| 222 | jsmn_init(&parser); |
| 223 | valid = json_parse_input(&parser, &toks, talstr, strlen(talstr), &complete); |
| 224 | assert(tal_count(toks) == 4); |
| 225 | assert(toks[0].start == 0 && toks[0].end == 9); |
| 226 | assert(valid); |
| 227 | assert(complete); |
| 228 | tal_free(talstr); |
| 229 | |
| 230 | /* Multiple messages, and the last one is partial, far more likely than |
| 231 | * accidentally getting the boundaries to match. */ |
| 232 | input = "{\"x\":\"x\"}{\"y\":\"y\"}{\"z\":\"z"; |
| 233 | talstr = tal_strndup(NULL, input, strlen(input)); |
| 234 | toks_reset(toks); |
| 235 | jsmn_init(&parser); |
| 236 | valid = json_parse_input(&parser, &toks, talstr, strlen(talstr), &complete); |
| 237 | assert(toks); |
| 238 | assert(tal_count(toks) == 4); |
| 239 | assert(toks[0].start == 0 && toks[0].end == 9); |
| 240 | assert(valid); |
| 241 | assert(complete); |
| 242 | tal_free(talstr); |
| 243 | |
| 244 | /* We can do this incrementally, too. */ |
| 245 | toks_reset(toks); |
| 246 | input = "{\"x\":\"x\"}"; |
| 247 | jsmn_init(&parser); |
| 248 | for (size_t i = 0; i <= strlen(input); i++) { |
| 249 | valid = json_parse_input(&parser, &toks, input, i, &complete); |
| 250 | assert(valid); |
| 251 | if (i == strlen(input)) |
| 252 | assert(complete); |
| 253 | else |
| 254 | assert(!complete); |
| 255 | } |
| 256 | assert(tal_count(toks) == 4); |
| 257 | assert(toks[0].start == 0 && toks[0].end == 9); |
| 258 | tal_free(toks); |
| 259 | } |
| 260 | |
| 261 | int main(int argc, char *argv[]) |
| 262 | { |
no test coverage detected