]> git.scottworley.com Git - tl-append/blame - tl-append-test.c
test: Populate expectation
[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
eaaa0046
SW
7struct expectation {
8 const char *message;
9};
10
11const struct expectation END = {NULL};
12static struct expectation expectation(const char *message) {
13 struct expectation exp;
14 exp.message = message;
15 return exp;
16}
17
b3d5ed96
SW
18static void die(const char *message) {
19 fputs(message, stderr);
20 fputc('\n', stderr);
21 exit(1);
22}
23
24static void die_err(const char *message) {
25 perror(message);
26 exit(1);
27}
28
27dfbfeb
SW
29static void remove_logfile() {
30 if (remove("tl.log") != 0) {
31 if (errno != ENOENT) {
32 die_err("Error removing log file");
33 }
34 }
35}
36
eaaa0046 37static struct expectation write_to_tl_append(const char *content) {
b3d5ed96
SW
38 FILE *p = popen("./tl-append", "w");
39 if (p == NULL)
40 die_err("Couldn't run tl-append");
aacfb261 41 if (fputs(content, p) == EOF)
b3d5ed96
SW
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");
eaaa0046 48 return expectation(content);
aacfb261
SW
49}
50
51static void verify_log_contents(const char *contents) {
7a92d9bf
SW
52 size_t len = strlen(contents);
53 char *buf = (char *)malloc(len + 2);
b3d5ed96
SW
54
55 FILE *f = fopen("tl.log", "r");
56 if (f == NULL)
57 die_err("Error opening log file");
7a92d9bf 58 buf[fread(buf, 1, len + 1, f)] = '\0';
27dfbfeb 59 if (ferror(f))
b3d5ed96 60 die("Error reading log file");
7a92d9bf 61 if (strncmp(contents, buf, len + 1) != 0)
b3d5ed96
SW
62 die("Wrong contents in log file");
63 if (fclose(f) != 0)
64 die_err("Error closing log file");
7a92d9bf 65 free(buf);
b3d5ed96
SW
66}
67
aacfb261 68static void write_and_read_line() {
27dfbfeb 69 remove_logfile();
aacfb261
SW
70 write_to_tl_append("foo\n");
71 verify_log_contents("foo\n");
72}
73
27dfbfeb
SW
74static 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
81int main() {
82 write_and_read_line();
83 write_and_read_two_lines();
84}