71 lines
1.5 KiB
C
71 lines
1.5 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <assert.h>
|
|
#include "stack.h"
|
|
|
|
// Helper: create int on heap
|
|
static int *make_int(int value) {
|
|
int *p = malloc(sizeof(int));
|
|
if (!p) {
|
|
fprintf(stderr, "Memory allocation failed\n");
|
|
exit(1);
|
|
}
|
|
*p = value;
|
|
return p;
|
|
}
|
|
|
|
int main(void) {
|
|
|
|
printf("Running stack unit tests...\n");
|
|
|
|
StackNode *stack = NULL;
|
|
|
|
// --- Test 1: push() on empty stack ---
|
|
int *a = make_int(10);
|
|
stack = push(stack, a);
|
|
assert(stack != NULL);
|
|
assert(top(stack) == a);
|
|
assert(*(int*)top(stack) == 10);
|
|
|
|
// --- Test 2: push() on non-empty stack ---
|
|
int *b = make_int(20);
|
|
stack = push(stack, b);
|
|
assert(top(stack) == b);
|
|
assert(*(int*)top(stack) == 20);
|
|
|
|
// --- Test 3: pop() returns previous element ---
|
|
stack = pop(stack); // removes 20
|
|
assert(top(stack) == a);
|
|
assert(*(int*)top(stack) == 10);
|
|
|
|
// --- Test 4: pop() on single element returns NULL ---
|
|
stack = pop(stack); // removes 10
|
|
assert(stack == NULL);
|
|
|
|
// --- Test 5: pop() on empty stack returns NULL ---
|
|
stack = pop(stack);
|
|
assert(stack == NULL);
|
|
|
|
// --- Test 6: clearStack() empties a multi-element stack ---
|
|
int *c = make_int(1);
|
|
int *d = make_int(2);
|
|
int *e = make_int(3);
|
|
stack = push(stack, c);
|
|
stack = push(stack, d);
|
|
stack = push(stack, e);
|
|
|
|
clearStack(stack);
|
|
stack = NULL;
|
|
|
|
// free allocated ints
|
|
free(a);
|
|
free(b);
|
|
free(c);
|
|
free(d);
|
|
free(e);
|
|
|
|
printf("All tests passed successfully.\n");
|
|
|
|
return 0;
|
|
}
|