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