aboutsummaryrefslogtreecommitdiff
path: root/minctest.c
blob: 2157bd17c99b22dac34cdc435a9ce6486ffb2ed5 (plain) (blame)
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
/**
 * MinCTest - Minimalistic C unit test framework
 * Copyright (C) 2015  Camil Staps

 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <stdio.h>
#include <stdlib.h>

#include "minctest.h"

// Colours for terminal output
#define KRED  "\x1B[31m"
#define KGRN  "\x1B[32m"
#define RESET "\x1B[0m"

struct tester *test_initialize() {
	struct tester *test = malloc(sizeof(struct tester));
	if (test == NULL)
		return NULL;
	test->passed = 0;
	test->failed = 0;
	test->show_pass = true;
	gettimeofday(&test->created, NULL);
	test_start_timer(test);
	return test;
}

void test_wrapup(struct tester* tester) {
	struct timeval end;
	gettimeofday(&end, NULL);
	float time = (end.tv_usec - tester->created.tv_usec) / 1000.0;
	float used = (tester->used) / 1000.0;

	if (tester->failed == 0) {
		printf(KGRN "\nAll tests passed (%d) [%.3fs / %.3fs]\n" RESET,
			tester->passed, used, time);
	} else {
		printf(KRED "\n%d test%s failed" RESET 
			" (%d passed) [%.3fs / %.3fs]\n",
			tester->failed, tester->failed > 1 ? "s" : "",
			tester->passed, used, time);
	}
}

void test_destroy(struct tester *tester) {
	free(tester);
}

void test_exit(struct tester *tester) {
	bool all_passed = tester->failed == 0;
	test_destroy(tester);
	exit(all_passed ? 0 : -1);
}

void test_start_timer(struct tester *tester) {
	gettimeofday(&tester->start_last_test, NULL);
}

void test_true(struct tester *tester, bool check, const char* text) {
	struct timeval end;
	gettimeofday(&end, NULL);
	tester->used += end.tv_usec - tester->start_last_test.tv_usec;
	float time = (end.tv_usec - tester->start_last_test.tv_usec) / 1000.0;

	if (!check || tester->show_pass) {
		puts(check ? KGRN : KRED);
		puts(check ? "Test passed" : "Test failed");
		if (text != NULL)
			printf(": %s", text);
		printf(" [%.3fs]", time);
		puts(RESET "\n");
	}

	*(check ? &tester->passed : &tester->failed) += 1;

	test_start_timer(tester);
}