chibipub

experimental activitypub node in C
git clone git://jb55.com/chibipub
Log | Files | Refs | README | LICENSE

test_json.c (2070B)


      1 
      2 #include "json.h"
      3 #include "ubjson.h"
      4 #include "cursor.h"
      5 #include "io.h"
      6 
      7 #include <assert.h>
      8 #include <stdio.h>
      9 #include <string.h>
     10 #include <sys/mman.h>
     11 #include <sys/stat.h>
     12 #include <sys/types.h>
     13 #include <fcntl.h>
     14 #include <unistd.h>
     15 #include <stdlib.h>
     16 
     17 static void write_data(unsigned char *data, int data_size)
     18 {
     19 	FILE *file;
     20 
     21 	file = fopen("test_out.ubjson", "wb");
     22 	fwrite(data, data_size, 1, file) ;
     23 	fclose(file);
     24 }
     25 
     26 static void test_ubjson_handler(unsigned char *out, size_t outlen)
     27 {
     28 	unsigned char *p;
     29 	struct ubjson ubjson;
     30 	struct json val;
     31 	size_t flen;
     32 
     33 	init_ubjson(&ubjson, out, outlen);
     34 
     35 	unsigned char empty[] = "{}";
     36 	assert(parse_ubjson(empty, sizeof(empty), &ubjson));
     37 	ubjson.cur.p = ubjson.cur.start;
     38 
     39 	unsigned char kv[] = "{ \"key\" : {\"obj\":123} , \"hmm\":null,\"otherkey\": \"stringy\"}";
     40 	assert(parse_ubjson(kv, sizeof(kv), &ubjson));
     41 
     42 	const char *path[] = {"key", "obj"};
     43 	assert(ubjson_lookup(&ubjson, path, 2, &val));
     44 	assert(val.number_int == 123);
     45 	ubjson.cur.p = ubjson.cur.start;
     46 
     47 	assert(map_file("corpus/math.json", &p, &flen));
     48 	assert(ubjson.errs.record);
     49 	assert(parse_ubjson(p, flen, &ubjson));
     50 
     51 	write_data(ubjson.cur.start, ubjson.data_end - ubjson.cur.start);
     52 
     53 	const char *path2[] = {"meta", "view", "oid"};
     54 	assert(ubjson_lookup(&ubjson, path2, 3, &val));
     55 	assert(val.number_int == 26867540);
     56 }
     57 
     58 static void test_compact_handler(unsigned char *out, size_t outlen)
     59 {
     60 	struct json_parser p;
     61 	struct json_handlers h;
     62 	struct json_pusher pusher;
     63 
     64 	init_json_pusher(&pusher, out, outlen);
     65 	make_compact_handlers(&h, &pusher);
     66 
     67 	unsigned char kv[] = "\n{ \"key\" : {\"obj\":\"123\"} , \"otherkey\": \"stringy\"}\n";
     68 	assert(parse_json(kv, sizeof(kv), &p, &h));
     69 	const char *expected = "{\"key\":{\"obj\":\"123\"},\"otherkey\":\"stringy\"}";
     70 	assert(!memcmp(expected, pusher.cur.start, strlen(expected)));
     71 }
     72 
     73 int main(int argc, char *argv[])
     74 {
     75 	unsigned char *out;
     76 	size_t outlen;
     77 
     78 	outlen = 1024 * 1024 * 80;
     79 	out = malloc(outlen);
     80 
     81 	test_ubjson_handler(out, outlen);
     82 	test_compact_handler(out, outlen);
     83 
     84 	free(out);
     85 }