shithub: libds

ref: cfd7660a044c8bd3ad0c33a237155b05248c0b0b
dir: /tests/main.c/

View raw version
#include <u.h>
#include <libc.h>
#include "../ds.h"
#include "../list.h"

usize passed = 0;
usize failed = 0;

// Print whether a given test passes or fails. 
void
tfail(char *t, int tf, char *msg)
{
	if(tf){
		passed++;
		fprint(2, "pass: %s\n", t);
	}else{
		failed++;
		fprint(2, "fail: %s failed → %s\n", t, msg);
	}
	free(msg);
}

// End testing if a given test does not pass. 
void
tfatal(char *t, int tf, char *msg)
{
	if(tf){
		passed++;
		fprint(2, "pass: %s\n", t);
		free(msg);
	}else{
		failed++;
		sysfatal("fail: %s hard failed → %s", t, msg);
	}
}

// Test whether we can create a list. 
void
testmklist(void)
{
	char *t = "mklist";
	List *l = mklist();
	tfatal(t, l != nil, smprint("list allocation failed"));
	free(l);
}

void
testprependlist(void)
{
	char *t = "prependlist";
	List *l = mklist();
	int i;
	int n = 7;
	for(i = 0; i < n; i++){
		int v = i*i;
		listprepend(l, &v);
	}
	
	tfail(t, l->size == n, 
	smprint("size → expected %d, got %ld", n, l->size)
	);

	ListNode *ln;
	usize count = 0;
	for(ln = l->head; ln != nil; ln = ln->next)
		count++;

	tfail(t, l->size == n, 
	smprint("size → iteration %d, got %ld", n, l->size)
	);

	// TODO - delete/free contents

	free(l);
}

void
testappendlist(void)
{
	char *t = "appendlist";
	List *l = mklist();
	int i;
	int n = 7;
	for(i = 0; i < n; i++){
		int v = i*i;
		listappend(l, &v);
	}
	
	tfail(t, l->size == n, 
	smprint("size → expected %d, got %ld", n, l->size)
	);

	ListNode *ln;
	usize count = 0;
	for(ln = l->head; ln != nil; ln = ln->next)
		count++;

	tfail(t, l->size == n, 
	smprint("size → iteration %d, got %ld", n, l->size)
	);

	// TODO - delete/free contents

	free(l);
}

void
main(int, char*[])
{
	// Lists
	testmklist();
	testprependlist();
	testappendlist();

	// Final output
	double percent = (double)((double)passed/(double)(passed+failed))*100.0;
	print("%ld passed. %ld failed. %3.0f%% passing.\n", passed, failed, percent);

	exits(nil);
}