summaryrefslogtreecommitdiff
path: root/tests/util.c
blob: a720123730a328245bb99ee92a2e41ce634ba13d (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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include "../src/util.c"

#include <assert.h>

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


static void
test_EXIT_USAGE(void) {
	test_start("EXIT_USAGE");

	{
		testing("it is different that EXIT_SUCCESS and EXIT_FAILURE");
		assert(EXIT_USAGE != EXIT_SUCCESS);
		assert(EXIT_USAGE != EXIT_FAILURE);
		test_ok();
	}
}

static int
test_freeit(void) {
	int rc = -1;

	test_start("freeit()");

	const char *ptr = NULL;

	{
		testing("ptr is NULL afterwards");

		ptr = malloc(1234U);
		if (ptr == NULL) {
			logerr("malloc(): %s", strerror(errno));
			goto out;
		}

		assert(ptr != NULL);
		freeit((void *)&ptr);
		assert(ptr == NULL);

		test_ok();
	}
	{
		testing("tolerate be given a NULL pointer");

		void *p = NULL;
		freeit(NULL);
		freeit(p);
		freeit((void *)&p);

		test_ok();
	}

	rc = 0;
out:
	if (ptr != NULL) {
		freeit((void *)&ptr);
	}
	return rc;
}

static int
test_slurp(void) {
	int rc = -1;

	char *given    = NULL;
	char *expected = NULL;

	{
		testing("non-existent file");

		const char *const filename = __FILE__ ".non-existant";
		const int ret_given    = slurp(filename, &given);
		const int ret_expected = slurp_for_tests(filename, &expected);

		assert(given    == NULL);
		assert(expected == NULL);
		assert(!!ret_given == !!ret_expected);

		test_ok();
	}
	{
		testing("slurp() == slurp_for_tests()");

		if (slurp(__FILE__, &given)) {
			logerr("slurp()");
			goto out;
		}

		if (slurp_for_tests(__FILE__, &expected)) {
			logerr("slurp_for_tests()");
			goto out;
		}

		assert(given    != NULL);
		assert(expected != NULL);
		assert(strcmp(given, expected) == 0);

		freeit((void *)&given);
		freeit((void *)&expected);

		test_ok();
	}

	rc = 0;
out:
	if (expected != NULL) {
		freeit((void *)expected);
	}
	if (given != NULL) {
		freeit((void *)&given);
	}
	return rc;
}


int
main(void) {
	int rc = EXIT_FAILURE;

	test_EXIT_USAGE();

	if (test_slurp()) {
		logerr("test_slurp()");
		goto out;
	}

	if (test_freeit()) {
		logerr("test_freeit()");
		goto out;
	}

	rc = EXIT_SUCCESS;
out:
	return rc;
}