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