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