]> git.scottworley.com Git - tl-append/blobdiff - tl-append-test.c
test: Use expectations for verifying output
[tl-append] / tl-append-test.c
index 0867280d26afc5a843c21c7e5eeaf576cd5f85f9..2a5d233d6b6ebaeb22bc358ea6fc30611a1a8f93 100644 (file)
@@ -1,8 +1,21 @@
 #define _POSIX_C_SOURCE 2
+#include <errno.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 
+typedef struct expectation {
+  const char *message;
+} ex_t;
+
+const ex_t END = {NULL};
+static int is_end(ex_t exp) { return exp.message == END.message; }
+static ex_t expectation(const char *message) {
+  ex_t exp;
+  exp.message = message;
+  return exp;
+}
+
 static void die(const char *message) {
   fputs(message, stderr);
   fputc('\n', stderr);
@@ -14,7 +27,15 @@ static void die_err(const char *message) {
   exit(1);
 }
 
-static void write_to_tl_append(const char *content) {
+static void remove_logfile() {
+  if (remove("tl.log") != 0) {
+    if (errno != ENOENT) {
+      die_err("Error removing log file");
+    }
+  }
+}
+
+static ex_t write_to_tl_append(const char *content) {
   FILE *p = popen("./tl-append", "w");
   if (p == NULL)
     die_err("Couldn't run tl-append");
@@ -25,25 +46,43 @@ static void write_to_tl_append(const char *content) {
     die_err("Error closing pipe");
   if (status != 0)
     die("tl-append exited abnormally");
+  return expectation(content);
 }
 
-static void verify_log_contents(const char *contents) {
-  char buf[10];
+static void verify_log_contents(ex_t exps[]) {
 
   FILE *f = fopen("tl.log", "r");
   if (f == NULL)
     die_err("Error opening log file");
-  if (fgets(buf, sizeof(buf), f) == NULL)
-    die("Error reading log file");
-  if (strncmp(contents, buf, sizeof(buf)) != 0)
-    die("Wrong contents in log file");
+  for (size_t i = 0; !is_end(exps[i]); i++) {
+    size_t len = strlen(exps[i].message);
+    char *buf = (char *)malloc(len + 2);
+    if (fgets(buf, len + 1, f) == NULL)
+      die("Error reading log file");
+    if (ferror(f))
+      die("Error reading log file");
+    if (strncmp(exps[i].message, buf, len + 1) != 0)
+      die("Wrong contents in log file");
+    free(buf);
+  }
   if (fclose(f) != 0)
     die_err("Error closing log file");
 }
 
 static void write_and_read_line() {
-  write_to_tl_append("foo\n");
-  verify_log_contents("foo\n");
+  remove_logfile();
+  ex_t e = write_to_tl_append("foo\n");
+  verify_log_contents((ex_t[]){e, END});
+}
+
+static void write_and_read_two_lines() {
+  remove_logfile();
+  ex_t e1 = write_to_tl_append("foo\n");
+  ex_t e2 = write_to_tl_append("bar\n");
+  verify_log_contents((ex_t[]){e1, e2, END});
 }
 
-int main() { write_and_read_line(); }
+int main() {
+  write_and_read_line();
+  write_and_read_two_lines();
+}