Spider2/tests/json_write.c

79 lines
2.7 KiB
C
Raw Normal View History

2024-09-01 16:12:11 +02:00
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include "json.h"
#include "unit.h"
#define CMP_STR "{\"string\":\"hello\",\"number\":69,\"boolean\":true,\"null\":" \
"null,\"null\":null,\"array\":[\"hello\",\"world\",\"it's\",\"max\"," \
"\"flow\",\"with\",\"ryhmes\",\"so-so\",0,-100,false,null],\"object\":{\"hello\":" \
"\"dipshit\"}}"
int tests_json_write(int argc, char **argv) {
jsonkv_dynarr_t map = dynarr_initi(jsonkv_dynarr_t);
jsonkv_t kv;
kv = (jsonkv_t){ .key = "string", .val = json_createstr("hello") };
dynarr_push(map, kv);
kv = (jsonkv_t){ .key = "number", .val = json_createint(69) };
dynarr_push(map, kv);
kv = (jsonkv_t){ .key = "boolean", .val = json_createbool(true) };
dynarr_push(map, kv);
kv = (jsonkv_t){ .key = "null", .val = json_createnull() };
dynarr_push(map, kv);
dynarr_push(map, kv);
jsonval_dynarr_t subarr = dynarr_initi(jsonval_dynarr_t);
dynarr_push(subarr, json_createstr("hello"));
dynarr_push(subarr, json_createstr("world"));
dynarr_push(subarr, json_createstr("it's"));
dynarr_push(subarr, json_createstr("max"));
dynarr_push(subarr, json_createstr("flow"));
dynarr_push(subarr, json_createstr("with"));
dynarr_push(subarr, json_createstr("ryhmes"));
dynarr_push(subarr, json_createstr("so-so"));
dynarr_push(subarr, json_createint(0));
dynarr_push(subarr, json_createint(-100));
dynarr_push(subarr, json_createbool(false));
dynarr_push(subarr, json_createnull());
jsonval_t j_subarr = json_createarr(subarr);
kv = (jsonkv_t){ .key = "array", .val = j_subarr };
dynarr_push(map, kv);
jsonkv_dynarr_t submap = dynarr_initi(jsonkv_dynarr_t);
kv = (jsonkv_t){ .key = "hello", .val = json_createstr("dipshit") };
dynarr_push(submap, kv);
kv = (jsonkv_t){ .key = "object", .val = json_createobj(submap) };
dynarr_push(map, kv);
jsonval_t j_map = json_createobj(map);
int fds[2] = { 11, 12 };
if (pipe(fds) < 0) {
fprintf(stderr, "pipe() failed: %s\n", strerror(errno));
return 1;
}
FILE *writer = fdopen(fds[1], "w");
if (writer == NULL) {
fprintf(stderr, "pipe() failed: %s\n", strerror(errno));
return 1;
}
json_write(writer, &j_map);
json_destroy(&j_map);
char buf[1000];
fflush(writer);
int cnt = read(fds[0], &buf, sizeof(buf));
if (cnt < 0) {
fprintf(stderr, "read() failed: %s\n", strerror(errno));
return 1;
}
buf[cnt] = '\0';
printf("cmp: %s\n", CMP_STR);
printf("buf: %s\n", buf);
chi_assert("test strings do not match", strcmp(buf, CMP_STR) == 0);
fclose(writer);
close(fds[0]);
return 0;
}