From 3a9a575bf5bf9aac76a673459fd79e2e8ea4a1a6 Mon Sep 17 00:00:00 2001 From: Lars Wirzenius Date: Mon, 25 Oct 2010 10:46:28 +0100 Subject: Refactor unittest to combine identical code for write and fwrite tests. --- unittests.c | 59 ++++++++++++++++++++++++++++------------------------------- 1 file changed, 28 insertions(+), 31 deletions(-) diff --git a/unittests.c b/unittests.c index cb145d1..f888f94 100644 --- a/unittests.c +++ b/unittests.c @@ -962,9 +962,8 @@ static int test_cmp_returns_positive_if_second_string_comes_first(void) } -static int test_fwrite_writes_string(void) +static int write_test(long (*callback)(char *filename, Dynstr *dynstr)) { - FILE *f; char tempname[] = "unittest.XXXXXX"; int fd; size_t num_bytes; @@ -979,9 +978,7 @@ static int test_fwrite_writes_string(void) if (fd == -1) abort(); - f = fopen(tempname, "w"); - num_bytes = dynstr_fwrite(f, dynstr); - fclose(f); + num_bytes = callback(tempname, dynstr); FAIL_UNLESS_EQUAL(num_bytes, dynstr_len(dynstr)); @@ -998,39 +995,39 @@ static int test_fwrite_writes_string(void) } -static int test_write_writes_string(void) +static long fwrite_callback(char *filename, Dynstr *dynstr) { - char tempname[] = "unittest.XXXXXX"; - int fd; - int fd2; - size_t num_bytes; - Dynstr *dynstr; - Dynstr *dynstr2; - char buf[1024]; - int read_bytes; - - dynstr = new_from_cstring("life is too short for str* and mem* in apps"); + FILE *f; + long num_bytes; - fd = mkstemp(tempname); - if (fd == -1) - abort(); + f = fopen(filename, "w"); + num_bytes = dynstr_fwrite(f, dynstr); + fclose(f); + return num_bytes; +} - fd2 = open(tempname, O_WRONLY, 0); - num_bytes = dynstr_write(fd2, dynstr); - close(fd2); - FAIL_UNLESS_EQUAL(num_bytes, dynstr_len(dynstr)); +static int test_fwrite_writes_string(void) +{ + return write_test(fwrite_callback); +} + + +static long write_callback(char *filename, Dynstr *dynstr) +{ + int fd; + long num_bytes; - read_bytes = read(fd, buf, sizeof(buf)); - if (read_bytes == -1) - abort(); + fd = open(filename, O_WRONLY, 0); + num_bytes = dynstr_write(fd, dynstr); close(fd); - dynstr2 = dynstr_new_from_memory(buf, read_bytes); - FAIL_UNLESS_EQUAL(read_bytes, dynstr_len(dynstr)); - FAIL_UNLESS_EQUAL(dynstr_cmp(dynstr, dynstr2), 0); - dynstr_free(dynstr2); + return num_bytes; +} - return true; + +static int test_write_writes_string(void) +{ + return write_test(write_callback); } -- cgit v1.2.1