]> git.scottworley.com Git - tl-append/blame_incremental - tl-append-test.c
test: Use expectations for verifying output
[tl-append] / tl-append-test.c
... / ...
CommitLineData
1#define _POSIX_C_SOURCE 2
2#include <errno.h>
3#include <stdio.h>
4#include <stdlib.h>
5#include <string.h>
6
7typedef struct expectation {
8 const char *message;
9} ex_t;
10
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;
15 exp.message = message;
16 return exp;
17}
18
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
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
38static ex_t write_to_tl_append(const char *content) {
39 FILE *p = popen("./tl-append", "w");
40 if (p == NULL)
41 die_err("Couldn't run tl-append");
42 if (fputs(content, p) == EOF)
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");
49 return expectation(content);
50}
51
52static void verify_log_contents(ex_t exps[]) {
53
54 FILE *f = fopen("tl.log", "r");
55 if (f == NULL)
56 die_err("Error opening log file");
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 }
68 if (fclose(f) != 0)
69 die_err("Error closing log file");
70}
71
72static void write_and_read_line() {
73 remove_logfile();
74 ex_t e = write_to_tl_append("foo\n");
75 verify_log_contents((ex_t[]){e, END});
76}
77
78static void write_and_read_two_lines() {
79 remove_logfile();
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});
83}
84
85int main() {
86 write_and_read_line();
87 write_and_read_two_lines();
88}