add testStack.c and test_number.c

This commit is contained in:
fonkou 2025-12-02 15:53:19 +01:00
parent 9f0191845d
commit 941374cbc2
2 changed files with 74 additions and 7 deletions

View File

@ -55,12 +55,9 @@ int main(void) {
stack = push(stack, e);
clearStack(stack);
// stack pointer still points to old top; we must reset manually
stack = NULL;
// no crash = success
// free remaining data
// free allocated ints
free(a);
free(b);
free(c);

View File

@ -1,3 +1,73 @@
//
// Created by kamtewil on 02.12.2025.
//
#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 pointer still points to old top; we must reset manually
stack = NULL;
// no crash = success
// free remaining data
free(a);
free(b);
free(c);
free(d);
free(e);
printf("All tests passed successfully.\n");
return 0;
}