From 3900a39205d989a7dab60de8660874add5542f21 Mon Sep 17 00:00:00 2001 From: jlamothe Date: Tue, 7 Nov 2023 04:33:22 +0000 Subject: [PATCH] implemented append_log() and some internal maintenance stuff --- 9unit.c | 87 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 9unit.h | 7 +++++ 2 files changed, 93 insertions(+), 1 deletion(-) diff --git a/9unit.c b/9unit.c index ff7b8b5..3471e70 100644 --- a/9unit.c +++ b/9unit.c @@ -26,7 +26,10 @@ // Internal Prototypes -static void init_TestState(TestState *s); +static void init_TestState(TestState *); +static void print_log(TestState *); +static void clear_log(TestState *); +static void reindex(TestState *); // Public Functions @@ -62,6 +65,38 @@ run_tests(void (*tests)(TestState *)) printf("Tests passed: %d\n", s.passed); printf("Tests failed: %d\n", s.failed); printf("Tests postponed: %d\n", s.postponed); + print_log(&s); + clear_log(&s); +} + +void +append_log(TestState *s, const char *msg) +{ + if (!(s && msg)) return; + + // build a new entry: + TestLogEntry *entry = malloc(sizeof(TestLogEntry)); + entry->text = malloc(strlen(msg) + 1); + strcpy(entry->text, msg); + entry->next = 0; + + // add it to the list: + if (!s->last_log) + { + if (s->first_log) // no last entry but we have a first? + { + reindex(s); + s->last_log->next = entry; + } + else s->first_log = entry; + } + else // there's already a last entry + { + if (!s->first_log) // no first entry but we have a last? + reindex(s); // do our best to fix that + s->last_log->next = entry; + } + s->last_log = entry; } // Internal Functions @@ -78,4 +113,54 @@ init_TestState(TestState *s) s->last_log = 0; } +static void +print_log(TestState *s) +{ + if (!s) return; + TestLogEntry *e = s->first_log; + while(e) + { + if(e->text) printf("%s\n", e->text); + else print("(empty message)\n"); + e = e->next; + } +} + +static void +clear_log(TestState *s) +{ + if (!s) return; + if(s->last_log && !s->first_log) reindex(s); // fix if broken + TestLogEntry *e = s->first_log, *next; + s->first_log = 0; + s->last_log = 0; + while (e) + { + next = e->next; + free(e->text); + free(e); + e = next; + } +} + +static void +reindex(TestState *s) +{ + if (!s) return; + if (s->first_log) + { + TestLogEntry *e = s->first_log; + while (e) + { + s->last_log = e; + e = e->next; + } + } + else if (s->last_log) // we have a last log but no first? + { + s->first_log = s->last_log; + fprint(2, "potential memory leak in test log\n"); + } +} + //jl diff --git a/9unit.h b/9unit.h index 4bf31f7..814bb5f 100644 --- a/9unit.h +++ b/9unit.h @@ -63,4 +63,11 @@ extern void run_tests( void (*)(TestState *) ); +// Adds an entry to the log that is displayed after the tests have +// completed +extern void append_log( + TestState *, // the current state + const char * // the message to append +); + //jl