68 lines
2.4 KiB
C
68 lines
2.4 KiB
C
/*
|
|
* tests/test_json.c — unit tests for util/json.c
|
|
* Build: make test
|
|
* Run: ./test_runner
|
|
*/
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <assert.h>
|
|
#include "json.h"
|
|
|
|
static int passed = 0, failed = 0;
|
|
|
|
#define CHECK(expr, desc) do { \
|
|
if (expr) { printf(" PASS: %s\n", desc); passed++; } \
|
|
else { printf(" FAIL: %s\n", desc); failed++; } \
|
|
} while(0)
|
|
|
|
static void test_json_str(void) {
|
|
printf("json_str:\n");
|
|
const char *j = "{\"name\":\"test show\",\"id\":\"42\",\"flag\":true}";
|
|
char *v;
|
|
|
|
v = json_str(j, "name"); CHECK(v && strcmp(v,"test show")==0, "string value"); free(v);
|
|
v = json_str(j, "id"); CHECK(v && strcmp(v,"42")==0, "numeric string"); free(v);
|
|
v = json_str(j, "flag"); CHECK(v && strcmp(v,"true")==0, "bare value"); free(v);
|
|
v = json_str(j, "missing"); CHECK(v == NULL, "missing key"); free(v);
|
|
}
|
|
|
|
static void test_json_array(void) {
|
|
printf("json_array:\n");
|
|
const char *j = "[{\"id\":\"1\"},{\"id\":\"2\"},{\"id\":\"3\"}]";
|
|
int n; char **arr = json_array(j, &n);
|
|
CHECK(n == 3, "count == 3");
|
|
if (arr) {
|
|
char *v = json_str(arr[0], "id"); CHECK(v && strcmp(v,"1")==0, "arr[0].id==1"); free(v);
|
|
v = json_str(arr[2], "id"); CHECK(v && strcmp(v,"3")==0, "arr[2].id==3"); free(v);
|
|
for (int i = 0; i < n; i++) free(arr[i]);
|
|
free(arr);
|
|
}
|
|
/* empty array */
|
|
arr = json_array("[]", &n); CHECK(n == 0, "empty array n==0"); free(arr);
|
|
}
|
|
|
|
static void test_urldecode(void) {
|
|
printf("urldecode:\n");
|
|
char s1[] = "hello%20world"; urldecode(s1); CHECK(strcmp(s1,"hello world")==0, "%%20 → space");
|
|
char s2[] = "a+b+c"; urldecode(s2); CHECK(strcmp(s2,"a b c")==0, "+ → space");
|
|
char s3[] = "no%20change%21"; urldecode(s3); CHECK(strcmp(s3,"no change!")==0, "mixed");
|
|
}
|
|
|
|
static void test_str_icontains(void) {
|
|
printf("str_icontains:\n");
|
|
CHECK(str_icontains("Walking Dead", "walking"), "case-insensitive match");
|
|
CHECK(str_icontains("Walking Dead", "DEAD"), "uppercase needle");
|
|
CHECK(!str_icontains("Walking Dead", "sopranos"),"no match");
|
|
CHECK(str_icontains("anything", ""), "empty needle → true");
|
|
}
|
|
|
|
int main(void) {
|
|
test_json_str();
|
|
test_json_array();
|
|
test_urldecode();
|
|
test_str_icontains();
|
|
printf("\n%d passed, %d failed\n", passed, failed);
|
|
return failed ? 1 : 0;
|
|
}
|