summaryrefslogtreecommitdiff
path: root/test.c
blob: 51ce05f8cdb915ed55d6187679438887f5d97f5c (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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <stdio.h>
#include <stdarg.h>

static int passed;
static int failed;

typedef enum {
	DEFAULT = 39,
	RED = 31,
	GREEN = 32,
	YELLOW = 33,
	BLUE = 34,
	MAGENTA = 35
} Color;

static void set_output_color(Color c)
{
	printf("\033[%dm", c);
}

static void print_result(int success, const char *format, ...)
{
	va_list ap;
	Color color = GREEN;
	char indicator = '+';

	if (success) {
		set_output_color(GREEN);
		printf("+ ");
		passed++;
	} else {
		set_output_color(RED);
		printf("- ");
		failed++;
	}

	set_output_color(color);
	printf("%c ", indicator);

	va_start(ap, format);
	vprintf(format, ap);
	va_end(ap);

	printf("%c", success ? '\n' : '\n');
	set_output_color(DEFAULT);
}

void testing_header(const char *header)
{
	printf("Testing header ");
	set_output_color(MAGENTA);
	printf("<%s>", header);
	set_output_color(DEFAULT);
	printf("\n");
}

void testing_end(void)
{
	printf("%d tests passed, %d tests failed\n", passed, failed);

	passed = 0;
	failed = 0;
}

void testing_comment(const char *comment)
{
	printf("- %s\n", comment);
}

void test_int_equals_imp(const char *expression, int result, int expected)
{
	print_result(result == expected, "%s == %d", expression, expected);
}

void test_void_imp(const char *expression)
{
	printf("? %s\n", expression);
}

void test_bool_imp(const char *expression, int result, int expected)
{
	int success = (result && expected) || (!result && !expected);
	print_result(success, "%s%s", expected ? "" : "!", expression);
}

void test_string_imp(const char *expression, const char *totest, const char *tocompare)
{
	int success = 1;
	int i;
	for (i = 0; totest[i] != '\0'; i++) {
		if (totest[i] != tocompare[i]) {
			success = 0;
		}
	}
	if (tocompare[i] != '\0') {
		success = 0;
	}
	print_result(success, "%s == \"%s\"", expression, tocompare);
}

void test_distinct_imp(const char *arrayname, int *array, size_t nelements)
{
	int success = 1;
	size_t i, j;
	for (i = 0; i < nelements; i++) {
		for (j = i + 1; j < nelements; j++) {
			if (array[i] == array[j]) {
				success = 0;
			}
		}
	}
	print_result(success, "Elements in %s are%s distinct", arrayname, success ? "" : " not");
}