calculator/tests/charness.c

56 lines
1.2 KiB
C
Raw Normal View History

2025-03-09 10:15:33 +00:00
#include "../calc.h"
#define BUF_SIZE 80
2025-03-09 11:01:58 +00:00
#define make_str(s) { sizeof(s) - 1, (const u8 *)s }
2025-03-09 10:15:33 +00:00
#define make_test(name) { make_str(#name), name }
extern bool streq(const u8 *, uint, const u8 *, uint);
extern int read(u8 *, uint); // read from stdin
2025-03-09 11:01:58 +00:00
extern void exit(int);
2025-03-09 10:15:33 +00:00
// Tests
extern void count_digits(void);
extern void fmt_decimal(void);
typedef struct {
u8 len;
const u8 *data;
2025-03-09 11:01:58 +00:00
} Str;
2025-03-09 10:15:33 +00:00
2025-03-09 11:01:58 +00:00
typedef void (*Testfn)(void);
2025-03-09 10:15:33 +00:00
typedef struct {
2025-03-09 11:01:58 +00:00
Str name;
Testfn fn;
} Test;
2025-03-09 10:15:33 +00:00
2025-03-09 11:01:58 +00:00
static Test tests[3] = {
make_test(count_digits),
make_test(fmt_decimal),
{ { 0, NULL }, NULL }
};
2025-03-09 10:15:33 +00:00
void _start(void) {
u8 buf[BUF_SIZE];
int nread0 = read(buf, BUF_SIZE);
if (nread0 < 0) {
for(;;); // TODO: add abort function
}
uint nread = (uint)nread0;
2025-03-09 11:01:58 +00:00
if (nread > 0 && buf[nread - 1] == '\n') {
nread--; // ignore trailing newline
}
2025-03-09 10:15:33 +00:00
2025-03-09 11:01:58 +00:00
Test t;
uint i;
for(i = 0, t = tests[i]; t.name.data != NULL; i++, t = tests[i]) {
if (streq(buf, nread, t.name.data, t.name.len)) {
t.fn();
exit(0);
2025-03-09 10:15:33 +00:00
}
}
2025-03-09 11:01:58 +00:00
exit(2);
2025-03-09 10:15:33 +00:00
}