-
Notifications
You must be signed in to change notification settings - Fork 0
/
ncunit.c
115 lines (95 loc) · 2.37 KB
/
ncunit.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include "ncunit.h"
#include <setjmp.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
static jmp_buf env;
static void sigsegv(int sig) {
longjmp(env, 1);
}
#ifdef NC_HEADERS
static void print_header(const char * test) {
fprintf(stderr, "[nunit] >> Test: %s", test);
fprintf(stderr, "\n");
}
#endif
static void print_error(const char * test, const char * msg) {
fprintf(stderr, "[nunit] XX %s: ERROR: ", test);
fprintf(stderr, msg);
fprintf(stderr, "\n");
}
static void print_ok(const char * test) {
fprintf(stderr, "[nunit] $$ %s: OK\n", test);
}
void execute_test(const char * (*test)(), void (*before)(), void (*after)(), const char * name) {
if(before != NULL) (*before)();
const char * result = (*test)();
#ifdef NC_HEADERS
print_header(name);
#endif
if (result == NULL) {
print_ok(name);
} else {
print_error(name, result);
}
if(after != NULL) (*after)();
}
int equals_float(float actual, float expected, float epsilon){
if(epsilon < 0) epsilon = -epsilon;
return actual <= expected + epsilon && actual >= expected - epsilon;
}
int equals_double(double actual, double expected, double epsilon){
if(epsilon < 0) epsilon = -epsilon;
return actual <= expected + epsilon && actual >= expected - epsilon;
}
int equals_ptr(void * actual, void * expected, size_t n_bytes) {
int i;
uint8_t * c_actual = (uint8_t *) actual;
uint8_t * c_expect = (uint8_t *) expected;
for(i = 0; i < n_bytes; i++){
if(c_actual[i] != c_expect[i]){
return 0;
}
}
return 1;
}
int mem_access(void * ptr, size_t n){
struct sigaction act;
struct sigaction oact;
act.sa_handler = sigsegv;
act.sa_flags = 0;
sigaction(SIGSEGV, &act, &oact);
uint8_t * u = malloc(n);
int segv;
if(!(segv = setjmp(env)))
memcpy(u, ptr, n);
free(u);
sigaction(SIGSEGV, &oact, NULL);
if(segv) {
return 0;
}else{
return 1;
}
}
int not_equals_float(float actual, float expected, float epsilon){
if(equals_float(actual, expected, epsilon))
return 0;
else return 1;
}
int not_equals_double(double actual, double expected, double epsilon){
if(equals_double(actual, expected, epsilon))
return 0;
else return 1;
}
int not_equals_ptr(void * actual, void * expected, size_t n_bytes){
if(equals_ptr(actual, expected, n_bytes))
return 0;
else return 1;
}
int not_mem_access(void * ptr, size_t n){
if(mem_access(ptr, n))
return 0;
else return 1;
}