diff options
author | martin@ashbysoft.com <martin@ashbysoft.com> | 2022-06-11 21:59:03 +0000 |
---|---|---|
committer | martin@ashbysoft.com <martin@ashbysoft.com> | 2022-06-11 21:59:03 +0000 |
commit | bb40c4cbc74fe48a04069e6efb78c94bd0cc0451 (patch) | |
tree | 60580318d7c9cbb7df1aa95739e9171f76e824cf /ex1-9.c | |
parent | 83e0861e200999ed46a1a1a8afa0b5638e48e14b (diff) | |
download | learn-c-bb40c4cbc74fe48a04069e6efb78c94bd0cc0451.tar.gz learn-c-bb40c4cbc74fe48a04069e6efb78c94bd0cc0451.tar.bz2 learn-c-bb40c4cbc74fe48a04069e6efb78c94bd0cc0451.tar.xz learn-c-bb40c4cbc74fe48a04069e6efb78c94bd0cc0451.zip |
Add CuTest and test script.
Update ex1-9 with unit tests using CuTest.
Diffstat (limited to 'ex1-9.c')
-rw-r--r-- | ex1-9.c | 68 |
1 files changed, 61 insertions, 7 deletions
@@ -1,22 +1,76 @@ #include <stdio.h> #include <stdbool.h> +#include <string.h> + /* Copy stdin to stdout, replacing consecutive spaces with a single space Edge case: a leading space is retained if there are leading spaces. Edge case: an empty file just doesn't echo anything, but emits a warning on stderr */ -int main(void) { - int c = getchar(); +int remspace(FILE* fin, FILE* fout, FILE* ferr) { + int c = fgetc(fin); if (c == EOF) { - fprintf(stderr, "warning: no input\n"); + fprintf(ferr, "warning: no input\n"); goto exit; } - putchar(c); + fputc(c, fout); bool bl = (c == ' '); - while ((c = getchar()) != EOF) { + while ((c = fgetc(fin)) != EOF) { if ((!bl) || (c != ' ')) { - putchar(c); + fputc(c, fout); } bl = (c == ' '); } exit: + fflush(fout); + fflush(ferr); return 0; -}
\ No newline at end of file +} + +#ifndef test + +int main(void) { + return remspace(stdin, stdout, stderr); +} + +#else + +#include "CuTest.h" + +void do_test(CuTest* tc, char* input, const char* expected, const char* err_expected) { + char buf[100] = {0}; + char err_buf[100] = {0}; + FILE* tin = fmemopen(input, strlen(input), "r"); + FILE* tout = fmemopen(buf, 100, "w"); + FILE* terr = fmemopen(err_buf, 100, "w"); + int res = remspace(tin, tout, terr); + CuAssertIntEquals(tc, 0, res); + CuAssertStrEquals(tc, expected, buf); + CuAssertStrEquals(tc, err_expected, err_buf); +} +void test_remspace_empty(CuTest* tc) { + do_test(tc, "", "", "warning: no input\n"); +} +void test_remspace_oneword(CuTest* tc) { + do_test(tc, "foobar", "foobar", ""); +} +void test_remspace_leadtrailspace(CuTest* tc) { + do_test(tc, " foo bar ", " foo bar ", ""); +} +CuSuite* remspace_suite() { + CuSuite* suite = CuSuiteNew(); + SUITE_ADD_TEST(suite, test_remspace_empty); + SUITE_ADD_TEST(suite, test_remspace_oneword); + SUITE_ADD_TEST(suite, test_remspace_leadtrailspace); + return suite; +} +int main(void) { + CuString* output = CuStringNew(); + CuSuite* suite = CuSuiteNew(); + CuSuiteAddSuite(suite, remspace_suite()); + CuSuiteRun(suite); + CuSuiteSummary(suite, output); + CuSuiteDetails(suite, output); + printf("%s\n", output->buffer); + return 0; +} + +#endif |