]> git.scottworley.com Git - tl-append/blob - tl-append-test.c
3eef960f33a7c14d2357bf32b9f7b0f8fd2c5168
[tl-append] / tl-append-test.c
1 #define _POSIX_C_SOURCE 2
2 #include <errno.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
6
7 struct expectation {
8 const char *message;
9 };
10
11 const struct expectation END = {NULL};
12 static struct expectation expectation(const char *message) {
13 struct expectation exp;
14 exp.message = message;
15 return exp;
16 }
17
18 static void die(const char *message) {
19 fputs(message, stderr);
20 fputc('\n', stderr);
21 exit(1);
22 }
23
24 static void die_err(const char *message) {
25 perror(message);
26 exit(1);
27 }
28
29 static void remove_logfile() {
30 if (remove("tl.log") != 0) {
31 if (errno != ENOENT) {
32 die_err("Error removing log file");
33 }
34 }
35 }
36
37 static struct expectation write_to_tl_append(const char *content) {
38 FILE *p = popen("./tl-append", "w");
39 if (p == NULL)
40 die_err("Couldn't run tl-append");
41 if (fputs(content, p) == EOF)
42 die("Couldn't write to pipe");
43 int status = pclose(p);
44 if (status < 0)
45 die_err("Error closing pipe");
46 if (status != 0)
47 die("tl-append exited abnormally");
48 return expectation(content);
49 }
50
51 static void verify_log_contents(const char *contents) {
52 size_t len = strlen(contents);
53 char *buf = (char *)malloc(len + 2);
54
55 FILE *f = fopen("tl.log", "r");
56 if (f == NULL)
57 die_err("Error opening log file");
58 buf[fread(buf, 1, len + 1, f)] = '\0';
59 if (ferror(f))
60 die("Error reading log file");
61 if (strncmp(contents, buf, len + 1) != 0)
62 die("Wrong contents in log file");
63 if (fclose(f) != 0)
64 die_err("Error closing log file");
65 free(buf);
66 }
67
68 static void write_and_read_line() {
69 remove_logfile();
70 write_to_tl_append("foo\n");
71 verify_log_contents("foo\n");
72 }
73
74 static void write_and_read_two_lines() {
75 remove_logfile();
76 write_to_tl_append("foo\n");
77 write_to_tl_append("bar\n");
78 verify_log_contents("foo\nbar\n");
79 }
80
81 int main() {
82 write_and_read_line();
83 write_and_read_two_lines();
84 }