summaryrefslogtreecommitdiff
path: root/tests/testing.c
blob: 21e026456fcf86d04440c147aeac38b965e777aa (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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include "../src/testing.c"

#include <assert.h>
#include <string.h>

#include "../src/logerr.h"
#include "slurp.h"



static const char
FNAME[] = __FILE__ ".txt";



int
main(void) {
	int rc = EXIT_FAILURE;

	test_start("testing.c");
	testing("output varying on $NO_COLOUR value");

	FILE *file = NULL;
	char *str  = NULL;

	file = fopen(FNAME, "w");
	if (file == NULL) {
		logerr("fopen(FNAME, \"w\")");
		goto out;
	}
	test_set_stream(file);

	test_start("testing.c");
	const bool should_overwrite = true;

	const char *const orig = getenv(ENVVAR_NAME);

	if (unsetenv(ENVVAR_NAME)) {
		logerr("unsetenv(\"NO_COLOUR\")");
		goto out;
	}
	{
		assert(show_colour() == true);
		testing("unset NO_COLOUR");
		test_ok();
	}

	if (setenv(ENVVAR_NAME, "", should_overwrite)) {
		logerr("setenv(\"NO_COLOUR\", \"\", 1)");
		goto out;
	}
	{
		assert(show_colour() == true);
		testing("empty NO_COLOUR");
		test_ok();
	}

	if (setenv(ENVVAR_NAME, "something", should_overwrite)) {
		logerr("setenv(\"NO_COLOUR\", \"something\", 1)");
		goto out;
	}
	{
		assert(show_colour() == false);
		testing("defined NO_COLOUR");
		test_ok();
	}

	test_set_stream(NULL);
	const int ret = fclose(file);
	file = NULL;
	if (ret) {
		logerr("fclose(file)");
		goto out;
	}

	if (orig == NULL) {
		if (unsetenv(ENVVAR_NAME)) {
			logerr("unsetenv(\"NO_COLOUR\")");
			goto out;
		}
	} else {
		if (setenv(ENVVAR_NAME, orig, true)) {
			logerr("setenv(\"NO_COLOUR\", orig, true)");
			goto out;
		}
	}

	if (slurp_for_tests(FNAME, &str)) {
		logerr("slurp_for_tests()");
		goto out;
	}

	const char expected[] =
		"testing.c:\n"
		"\033[0;33mtesting\033[0m: unset NO_COLOUR... "
		"\033[0;32mOK\033[0m.\n"
		"\033[0;33mtesting\033[0m: empty NO_COLOUR... "
		"\033[0;32mOK\033[0m.\n"
		"testing: defined NO_COLOUR... OK.\n"
		;

	assert(strcmp(expected, str) == 0);

	free(str);
	str = NULL;

	test_ok();

	rc = EXIT_SUCCESS;
out:
	if (str != NULL) {
		free(str);
		str = NULL;
	}
	if (file != NULL) {
		if (fclose(file)) {
			logerr("flose()");
			rc = EXIT_FAILURE;
		}
	}
	return rc;
}