aboutsummaryrefslogtreecommitdiff
path: root/test/main.c
blob: 8c2fffe54768e02d2e5e474139dab2a14ba399c4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <stdio.h>
#include <stdlib.h>
#include <stdatomic.h>
#include <time.h>
#include "test_framework.h"
#include "test_declarations.h"

#define STR_(x) #x
#define STR(x) STR_(x)


// Referred to via extern in 'test_framework.c'
atomic_flag test_framework_assertion_failed = ATOMIC_FLAG_INIT;


static void report(const char *clr, const char *label, const char *name, clock_t taken) {
	printf("\x1B[%sm[%s] %s (%lfs)\x1B[0m\n",
			clr, label, name, (double)taken / CLOCKS_PER_SEC);
}

static void report_success(const char *name, clock_t taken) {
	report("32", "  OK  ", name, taken);
}

static void report_failure(const char *name, clock_t taken) {
	report("31", "FAILED", name, taken);
}

#define RUN_TEST(name) do { \
		atomic_flag_clear(&test_framework_assertion_failed); \
		const clock_t start_ = clock(); \
		const int ret_ = TEST(name)(); \
		const clock_t diff_ = clock() - start_; \
		if (ret_ == 0 && !atomic_flag_test_and_set(&test_framework_assertion_failed)) { \
			report_success(STR(name), diff_); \
		} else { \
			report_failure(STR(name), diff_); \
			return 1; \
		} \
	} while (0)

static int run_tests(void) {
	RUN_TEST(hashtable_unit1);
	RUN_TEST(hashtable);
	RUN_TEST(utf8_unit1);
	RUN_TEST(utf8_random);
	RUN_TEST(utf8_random_valid);
	RUN_TEST(utf8_exhaustive_1);
	return 0;
}

static unsigned int random_seed_from_device(void) {
	FILE *f = fopen("/dev/urandom", "r");
	if (!f) {
		fprintf(stderr, "Cannot open /dev/urandom\n");
		exit(1);
	}
	unsigned int seed;
	int nread = fread(&seed, 1, sizeof seed, f);
	if (nread < (int)sizeof seed) {
		fprintf(stderr, "Cannot read from /dev/urandom\n");
		exit(1);
	}
	fclose(f);
	return seed;
}

int main(void) {
	unsigned int seed;
	const char *seed_env_var = getenv("SEED");
	if (seed_env_var && seed_env_var[0]) {
		seed = strtol(seed_env_var, NULL, 10);
	} else {
		seed = random_seed_from_device();
	}
	fprintf(stderr, "seed = %u\n", seed);
	srandom(seed);

	return run_tests();
}