-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtests.c
95 lines (74 loc) · 2.39 KB
/
tests.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#define TESTING
#include <stdlib.h>
#include <stdio.h>
#include "hash.h"
#define ASSERT(condition, error_msg) if(!(condition)) { printf("Error: %s\n", error_msg); return false; }
#define TEST(test_name) ASSERT(test_name(), #test_name " failed.")
void assert(bool condition, const char* error_msg) {
if(!condition) {
printf("Error: %s\n", error_msg);
}
}
bool test_hash_distribution() {
int bucket_count = 16;
int * buckets = calloc(bucket_count, sizeof(int));
char key [4];
key[3] = 0;
int total=0;
unsigned int i;
for(i = 0; i <= 4096 ; i ++) {
key[0]=rand()%95+32;
key[1]=rand()%95+32;
key[2]=rand()%95+32;
buckets[hash(key)%bucket_count]++;
}
for(i = 0 ; i < bucket_count ; i++) {
double error = buckets[i]-256;
error = error * 12 / (bucket_count * bucket_count - 1 );
error = error < 0? -error: error;
printf("%2i: %4i (deviation: %10f)\n", i, buckets[i], error);
ASSERT(error < 2, "error above acceptable threshold (standard deviation >= 2)")
}
return true;
}
bool test_duplicate_insert_overrides() {
Table * t = makeTable();
hset(t, "Key", "A");
hset(t, "Key", "B");
char* returned = hget(t, "Key");
ASSERT(returned != 0, "Table returned null on duplicate insert");
ASSERT(returned[0] != 'A', "Table returned old value on duplicate insert");
ASSERT(returned[0] == 'B', "Table returned wrong value on duplicate insert");
freeTable(t);
return true;
}
bool test_remove() {
Table * t = makeTable();
hset(t, "Key", "A");
char *returned = hget(t, "Key");
ASSERT(returned != 0, "Table returned null after setting");
hdel(t, "Key");
returned = hget(t, "Key");
//missing key returns empty string?
ASSERT(returned[0] == 0, "Table returned non-null");
return true;
}
bool test_segfault_during_delete() {
Table * t = makeTable();
char * key1 = "0";
char * key2 = "8";
ASSERT( (hash(key1) % t->size) == (hash(key2) % t->size), "Keys will not collide. Update keys for this test.")
hset(t, key1, "asdf");
hset(t, key2, "asdf");
hdel(t, key2);
hdel(t, key1); // This segfaults
freeTable(t);
return true;
}
int main(int argc, char **argv) {
test_hash_distribution();
TEST(test_duplicate_insert_overrides);
TEST(test_remove);
TEST(test_segfault_during_delete);
printf("All tests passed!\n");
}