]> git.scottworley.com Git - overonion/blob - reverse_test.c
fe35bcc303a04330c55e7bbd890f5fde8b590efb
[overonion] / reverse_test.c
1 #include "reverse_lib.h"
2
3 #include <err.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <sysexits.h>
8 #include <unistd.h>
9
10 static const char test_file[] = "reverse.c";
11
12 char* reverse_to_temp_file(const char* input_file) {
13 char* temp_filename = strdup("/tmp/reverse_test.XXXXXX");
14 int fd = mkstemp(temp_filename);
15 if (fd == -1) err(EX_IOERR, "Couldn't make a temporary file");
16 reverse_file(input_file, fd);
17 if (close(fd) == -1) err(EX_IOERR, "Couldn't close temporary file");
18 return temp_filename;
19 }
20
21 void test_reverse_twice_is_the_same() {
22 char* intermediate = reverse_to_temp_file(test_file);
23 char* back_to_normal = reverse_to_temp_file(intermediate);
24
25 FILE* f1 = fopen(test_file, "r");
26 if (f1 == NULL) err(EX_IOERR, "Couldn't open test file");
27 FILE* f2 = fopen(back_to_normal, "r");
28 if (f2 == NULL) err(EX_IOERR, "Couldn't open twice-reversed temp file");
29
30 for (int pos = 0; ; pos++) {
31 int c1 = fgetc(f1);
32 int c2 = fgetc(f2);
33 if (c1 == EOF && ferror(f1)) err(EX_IOERR, "Error reading test file");
34 if (c2 == EOF && ferror(f2)) err(EX_IOERR, "Error reading twice-reversed temp file");
35 if (c1 != c2) {
36 errx(EX_SOFTWARE, "Unexpected difference found at offset %d after reversing twice. "
37 "Expected %d but found %d", pos, c1, c2);
38 }
39 if (c1 == EOF) break;
40 }
41
42 if (fclose(f1) != 0) err(EX_IOERR, "Couldn't close test file");
43 if (fclose(f2) != 0) err(EX_IOERR, "Couldn't close twice-reversed temp file");
44 if (unlink(intermediate) == -1) err(EX_IOERR, "Couldn't remove intermediate temp file");
45 if (unlink(back_to_normal) == -1) err(EX_IOERR, "Couldn't remove twice-reversed temp file");
46 free(intermediate);
47 free(back_to_normal);
48 }
49
50 int main() {
51 test_reverse_twice_is_the_same();
52 puts("PASS");
53 return 0;
54 }