implemented append_log() and some internal maintenance stuff

This commit is contained in:
jlamothe 2023-11-07 04:33:22 +00:00
parent 870f1b619b
commit 3900a39205
2 changed files with 93 additions and 1 deletions

87
9unit.c
View File

@ -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

View File

@ -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