]>
git.scottworley.com Git - overonion/blob - reverse_test.c
1 #include "reverse_lib.h"
11 static const char test_file
[] = "reverse.c";
13 /* Reverse input_file. Dump the result in a temporary file. Return the temp
14 * file's name. The caller must free the filename. */
15 char* reverse_to_temp_file(const char* input_file
) {
18 make_temporary_file(&temp_filename
, &f
);
19 reverse_file(input_file
, f
);
20 if (fclose(f
) == EOF
) err(EX_IOERR
, "Couldn't close temporary file");
24 /* Compare the contents of two files. Terminate with a diagnostic if they
26 void compare(const char* filename1
, const char* filename2
) {
27 FILE* f1
= fopen(filename1
, "r");
28 if (f1
== NULL
) err(EX_IOERR
, "Couldn't open file %s", filename1
);
29 FILE* f2
= fopen(filename2
, "r");
30 if (f2
== NULL
) err(EX_IOERR
, "Couldn't open file %s", filename2
);
32 for (int pos
= 0; ; pos
++) {
35 if (c1
== EOF
&& ferror(f1
)) err(EX_IOERR
, "Error reading file %s", filename1
);
36 if (c2
== EOF
&& ferror(f2
)) err(EX_IOERR
, "Error reading file %s", filename2
);
38 errx(EX_SOFTWARE
, "Unexpected difference found at offset %d after reversing twice. "
39 "Expected %d but found %d", pos
, c1
, c2
);
44 if (fclose(f1
) != 0) err(EX_IOERR
, "Couldn't close file %s", filename1
);
45 if (fclose(f2
) != 0) err(EX_IOERR
, "Couldn't close file %s", filename2
);
48 void test_reverse_twice_from_files_is_the_same() {
49 char* intermediate
= reverse_to_temp_file(test_file
);
50 char* back_to_normal
= reverse_to_temp_file(intermediate
);
52 compare(test_file
, back_to_normal
);
54 if (unlink(intermediate
) == -1) err(EX_IOERR
, "Couldn't remove intermediate temp file");
55 if (unlink(back_to_normal
) == -1) err(EX_IOERR
, "Couldn't remove twice-reversed temp file");
60 void test_reverse_from_file_then_from_stream_is_the_same() {
62 if (pipe(pipefd
) == -1) err(EX_OSERR
, "Couldn't create pipe");
65 if (pid
== -1) err(EX_OSERR
, "Couldn't fork");
67 if (close(pipefd
[0]) == -1) err(EX_OSERR
, "Couldn't close unneeded pipe descriptor");
68 FILE* to_second
= fdopen(pipefd
[1], "w");
69 if (to_second
== NULL
) err(EX_IOERR
, "Couldn't open pipe for writing");
70 reverse_file(test_file
, to_second
);
73 if (close(pipefd
[1]) == -1) err(EX_OSERR
, "Couldn't close unneeded pipe descriptor");
74 FILE* from_first
= fdopen(pipefd
[0], "r");
75 if (from_first
== NULL
) err(EX_IOERR
, "Couldn't open pipe for reading");
76 char* out_temp_filename
;
78 make_temporary_file(&out_temp_filename
, &out_file
);
79 reverse_stream(from_first
, out_file
);
80 if (fclose(out_file
) == EOF
) err(EX_IOERR
, "Couldn't close temporary file");
82 compare(test_file
, out_temp_filename
);
84 if (unlink(out_temp_filename
) == -1) err(EX_IOERR
, "Couldn't remove temp output file");
85 free(out_temp_filename
);
89 test_reverse_twice_from_files_is_the_same();
90 test_reverse_from_file_then_from_stream_is_the_same();