Test that we can segment and parse a stream of json objects correctly. */
| 231 | |
| 232 | /* Test that we can segment and parse a stream of json objects correctly. */ |
| 233 | static void test_json_stream(void) |
| 234 | { |
| 235 | bool valid, complete; |
| 236 | char *input, *talstr; |
| 237 | jsmntok_t *toks; |
| 238 | jsmn_parser parser; |
| 239 | |
| 240 | /* Multiple full messages in a single buffer (happens when buffer |
| 241 | * boundary coincides with message boundary, or read returned after |
| 242 | * timeout. */ |
| 243 | input = "{\"x\":\"x\"}{\"y\":\"y\"}"; |
| 244 | talstr = tal_strndup(NULL, input, strlen(input)); |
| 245 | toks = toks_alloc(NULL); |
| 246 | jsmn_init(&parser); |
| 247 | valid = json_parse_input(&parser, &toks, talstr, strlen(talstr), &complete); |
| 248 | assert(tal_count(toks) == 4); |
| 249 | assert(toks[0].start == 0 && toks[0].end == 9); |
| 250 | assert(valid); |
| 251 | assert(complete); |
| 252 | tal_free(talstr); |
| 253 | |
| 254 | /* Multiple messages, and the last one is partial, far more likely than |
| 255 | * accidentally getting the boundaries to match. */ |
| 256 | input = "{\"x\":\"x\"}{\"y\":\"y\"}{\"z\":\"z"; |
| 257 | talstr = tal_strndup(NULL, input, strlen(input)); |
| 258 | toks_reset(toks); |
| 259 | jsmn_init(&parser); |
| 260 | valid = json_parse_input(&parser, &toks, talstr, strlen(talstr), &complete); |
| 261 | assert(toks); |
| 262 | assert(tal_count(toks) == 4); |
| 263 | assert(toks[0].start == 0 && toks[0].end == 9); |
| 264 | assert(valid); |
| 265 | assert(complete); |
| 266 | tal_free(talstr); |
| 267 | |
| 268 | /* We can do this incrementally, too. */ |
| 269 | toks_reset(toks); |
| 270 | input = "{\"x\":\"x\"}"; |
| 271 | jsmn_init(&parser); |
| 272 | for (size_t i = 0; i <= strlen(input); i++) { |
| 273 | valid = json_parse_input(&parser, &toks, input, i, &complete); |
| 274 | assert(valid); |
| 275 | if (i == strlen(input)) |
| 276 | assert(complete); |
| 277 | else |
| 278 | assert(!complete); |
| 279 | } |
| 280 | assert(tal_count(toks) == 4); |
| 281 | assert(toks[0].start == 0 && toks[0].end == 9); |
| 282 | tal_free(toks); |
| 283 | } |
| 284 | |
| 285 | int main(int argc, char *argv[]) |
| 286 | { |
no test coverage detected