-
Notifications
You must be signed in to change notification settings - Fork 5
/
acutest.h
1770 lines (1519 loc) · 56.7 KB
/
acutest.h
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Acutest -- Another C/C++ Unit Test facility
* <https://github.com/mity/acutest>
*
* Copyright 2013-2020 Martin Mitas
* Copyright 2019 Garrett D'Amore
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#ifndef ACUTEST_H
#define ACUTEST_H
/************************
*** Public interface ***
************************/
/* By default, "acutest.h" provides the main program entry point (function
* main()). However, if the test suite is composed of multiple source files
* which include "acutest.h", then this causes a problem of multiple main()
* definitions. To avoid this problem, #define macro TEST_NO_MAIN in all
* compilation units but one.
*/
/* Macro to specify list of unit tests in the suite.
* The unit test implementation MUST provide list of unit tests it implements
* with this macro:
*
* TEST_LIST = {
* { "test1_name", test1_func_ptr },
* { "test2_name", test2_func_ptr },
* ...
* { 0 }
* };
*
* The list specifies names of each test (must be unique) and pointer to
* a function implementing it. The function does not take any arguments
* and has no return values, i.e. every test function has to be compatible
* with this prototype:
*
* void test_func(void);
*/
#define TEST_LIST const struct test_ test_list_[]
/* Macros for testing whether an unit test succeeds or fails. These macros
* can be used arbitrarily in functions implementing the unit tests.
*
* If any condition fails throughout execution of a test, the test fails.
*
* TEST_CHECK takes only one argument (the condition), TEST_CHECK_ allows
* also to specify an error message to print out if the condition fails.
* (It expects printf-like format string and its parameters). The macros
* return non-zero (condition passes) or 0 (condition fails).
*
* That can be useful when more conditions should be checked only if some
* preceding condition passes, as illustrated in this code snippet:
*
* SomeStruct* ptr = allocate_some_struct();
* if(TEST_CHECK(ptr != NULL)) {
* TEST_CHECK(ptr->member1 < 100);
* TEST_CHECK(ptr->member2 > 200);
* }
*/
#define TEST_CHECK_(cond,...) test_check_((cond), __FILE__, __LINE__, __VA_ARGS__)
#define TEST_CHECK(cond) test_check_((cond), __FILE__, __LINE__, "%s", #cond)
/* These macros are the same as TEST_CHECK_ and TEST_CHECK except that if the
* condition fails, the currently executed unit test is immediately aborted.
*
* That is done either by calling abort() if the unit test is executed as a
* child process; or via longjmp() if the unit test is executed within the
* main Acutest process.
*
* As a side effect of such abortion, your unit tests may cause memory leaks,
* unflushed file descriptors, and other phenomena caused by the abortion.
*
* Therefore you should not use these as a general replacement for TEST_CHECK.
* Use it with some caution, especially if your test causes some other side
* effects to the outside world (e.g. communicating with some server, inserting
* into a database etc.).
*/
#define TEST_ASSERT_(cond,...) \
do { \
if(!test_check_((cond), __FILE__, __LINE__, __VA_ARGS__)) \
test_abort_(); \
} while(0)
#define TEST_ASSERT(cond) \
do { \
if(!test_check_((cond), __FILE__, __LINE__, "%s", #cond)) \
test_abort_(); \
} while(0)
#ifdef __cplusplus
/* Macros to verify that the code (the 1st argument) throws exception of given
* type (the 2nd argument). (Note these macros are only available in C++.)
*
* TEST_EXCEPTION_ is like TEST_EXCEPTION but accepts custom printf-like
* message.
*
* For example:
*
* TEST_EXCEPTION(function_that_throw(), ExpectedExceptionType);
*
* If the function_that_throw() throws ExpectedExceptionType, the check passes.
* If the function throws anything incompatible with ExpectedExceptionType
* (or if it does not thrown an exception at all), the check fails.
*/
#define TEST_EXCEPTION(code, exctype) \
do { \
bool exc_ok_ = false; \
const char *msg_ = NULL; \
try { \
code; \
msg_ = "No exception thrown."; \
} catch(exctype const&) { \
exc_ok_= true; \
} catch(...) { \
msg_ = "Unexpected exception thrown."; \
} \
test_check_(exc_ok_, __FILE__, __LINE__, #code " throws " #exctype); \
if(msg_ != NULL) \
test_message_("%s", msg_); \
} while(0)
#define TEST_EXCEPTION_(code, exctype, ...) \
do { \
bool exc_ok_ = false; \
const char *msg_ = NULL; \
try { \
code; \
msg_ = "No exception thrown."; \
} catch(exctype const&) { \
exc_ok_= true; \
} catch(...) { \
msg_ = "Unexpected exception thrown."; \
} \
test_check_(exc_ok_, __FILE__, __LINE__, __VA_ARGS__); \
if(msg_ != NULL) \
test_message_("%s", msg_); \
} while(0)
#endif /* #ifdef __cplusplus */
/* Sometimes it is useful to split execution of more complex unit tests to some
* smaller parts and associate those parts with some names.
*
* This is especially handy if the given unit test is implemented as a loop
* over some vector of multiple testing inputs. Using these macros allow to use
* sort of subtitle for each iteration of the loop (e.g. outputting the input
* itself or a name associated to it), so that if any TEST_CHECK condition
* fails in the loop, it can be easily seen which iteration triggers the
* failure, without the need to manually output the iteration-specific data in
* every single TEST_CHECK inside the loop body.
*
* TEST_CASE allows to specify only single string as the name of the case,
* TEST_CASE_ provides all the power of printf-like string formatting.
*
* Note that the test cases cannot be nested. Starting a new test case ends
* implicitly the previous one. To end the test case explicitly (e.g. to end
* the last test case after exiting the loop), you may use TEST_CASE(NULL).
*/
#define TEST_CASE_(...) test_case_(__VA_ARGS__)
#define TEST_CASE(name) test_case_("%s", name)
/* Maximal output per TEST_CASE call. Longer messages are cut.
* You may define another limit prior including "acutest.h"
*/
#ifndef TEST_CASE_MAXSIZE
#define TEST_CASE_MAXSIZE 64
#endif
/* printf-like macro for outputting an extra information about a failure.
*
* Intended use is to output some computed output versus the expected value,
* e.g. like this:
*
* if(!TEST_CHECK(produced == expected)) {
* TEST_MSG("Expected: %d", expected);
* TEST_MSG("Produced: %d", produced);
* }
*
* Note the message is only written down if the most recent use of any checking
* macro (like e.g. TEST_CHECK or TEST_EXCEPTION) in the current test failed.
* This means the above is equivalent to just this:
*
* TEST_CHECK(produced == expected);
* TEST_MSG("Expected: %d", expected);
* TEST_MSG("Produced: %d", produced);
*
* The macro can deal with multi-line output fairly well. It also automatically
* adds a final new-line if there is none present.
*/
#define TEST_MSG(...) test_message_(__VA_ARGS__)
/* Maximal output per TEST_MSG call. Longer messages are cut.
* You may define another limit prior including "acutest.h"
*/
#ifndef TEST_MSG_MAXSIZE
#define TEST_MSG_MAXSIZE 1024
#endif
/* Macro for dumping a block of memory.
*
* Its intended use is very similar to what TEST_MSG is for, but instead of
* generating any printf-like message, this is for dumping raw block of a
* memory in a hexadecimal form:
*
* TEST_CHECK(size_produced == size_expected &&
* memcmp(addr_produced, addr_expected, size_produced) == 0);
* TEST_DUMP("Expected:", addr_expected, size_expected);
* TEST_DUMP("Produced:", addr_produced, size_produced);
*/
#define TEST_DUMP(title, addr, size) test_dump_(title, addr, size)
/* Maximal output per TEST_DUMP call (in bytes to dump). Longer blocks are cut.
* You may define another limit prior including "acutest.h"
*/
#ifndef TEST_DUMP_MAXSIZE
#define TEST_DUMP_MAXSIZE 1024
#endif
/* Common test initialiation/clean-up
*
* In some test suites, it may be needed to perform some sort of the same
* initialization and/or clean-up in all the tests.
*
* Such test suites may use macros TEST_INIT and/or TEST_FINI prior including
* this header. The expansion of the macro is then used as a body of helper
* function called just before executing every single (TEST_INIT) or just after
* it ends (TEST_FINI).
*
* Examples of various ways how to use the macro TEST_INIT:
*
* #define TEST_INIT my_init_func();
* #define TEST_INIT my_init_func() // Works even without the semicolon
* #define TEST_INIT setlocale(LC_ALL, NULL);
* #define TEST_INIT { setlocale(LC_ALL, NULL); my_init_func(); }
*
* TEST_FINI is to be used in the same way.
*/
/**********************
*** Implementation ***
**********************/
/* The unit test files should not rely on anything below. */
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <setjmp.h>
#if defined(unix) || defined(__unix__) || defined(__unix) || defined(__APPLE__)
#define ACUTEST_UNIX_ 1
#include <errno.h>
#include <libgen.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <time.h>
#if defined CLOCK_PROCESS_CPUTIME_ID && defined CLOCK_MONOTONIC
#define ACUTEST_HAS_POSIX_TIMER_ 1
#endif
#endif
#if defined(_gnu_linux_)
#define ACUTEST_LINUX_ 1
#include <fcntl.h>
#include <sys/stat.h>
#endif
#if defined(_WIN32) || defined(__WIN32__) || defined(__WINDOWS__)
#define ACUTEST_WIN_ 1
#include <windows.h>
#include <io.h>
#endif
#ifdef __cplusplus
#include <exception>
#endif
/* Load valgrind.h, if available. This allows to detect valgrind's presence via RUNNING_ON_VALGRIND. */
#ifdef __has_include
#if __has_include(<valgrind.h>)
#include <valgrind.h>
#endif
#endif
/* Enable the use of the non-standard keyword __attribute__ to silence warnings under some compilers */
#if defined(__GNUC__) || defined(__clang__)
#define TEST_ATTRIBUTE_(attr) __attribute__((attr))
#else
#define TEST_ATTRIBUTE_(attr)
#endif
/* Note our global private identifiers end with '_' to mitigate risk of clash
* with the unit tests implementation. */
#ifdef __cplusplus
extern "C" {
#endif
#ifdef _MSC_VER
/* In the multi-platform code like ours, we cannot use the non-standard
* "safe" functions from Microsoft C lib like e.g. sprintf_s() instead of
* standard sprintf(). Hence, lets disable the warning C4996. */
#pragma warning(push)
#pragma warning(disable: 4996)
#endif
struct test_ {
const char* name;
void (*func)(void);
};
struct test_detail_ {
unsigned char flags;
double duration;
};
enum {
TEST_FLAG_RUN_ = 1 << 0,
TEST_FLAG_SUCCESS_ = 1 << 1,
TEST_FLAG_FAILURE_ = 1 << 2,
};
extern const struct test_ test_list_[];
int test_check_(int cond, const char* file, int line, const char* fmt, ...);
void test_case_(const char* fmt, ...);
void test_message_(const char* fmt, ...);
void test_dump_(const char* title, const void* addr, size_t size);
void test_abort_(void) TEST_ATTRIBUTE_(noreturn);
#ifndef TEST_NO_MAIN
static char* test_argv0_ = NULL;
static size_t test_list_size_ = 0;
static struct test_detail_ *test_details_ = NULL;
static size_t test_count_ = 0;
static int test_no_exec_ = -1;
static int test_no_summary_ = 0;
static int test_tap_ = 0;
static int test_skip_mode_ = 0;
static int test_worker_ = 0;
static int test_worker_index_ = 0;
static int test_cond_failed_ = 0;
static int test_was_aborted_ = 0;
static FILE *test_xml_output_ = NULL;
static int test_stat_failed_units_ = 0;
static int test_stat_run_units_ = 0;
static const struct test_* test_current_unit_ = NULL;
static int test_current_index_ = 0;
static char test_case_name_[TEST_CASE_MAXSIZE] = "";
static int test_current_already_logged_ = 0;
static int test_case_current_already_logged_ = 0;
static int test_verbose_level_ = 2;
static int test_current_failures_ = 0;
static int test_colorize_ = 0;
static int test_timer_ = 0;
static int test_abort_has_jmp_buf_ = 0;
static jmp_buf test_abort_jmp_buf_;
#if defined ACUTEST_WIN_
typedef LARGE_INTEGER test_timer_type_;
static LARGE_INTEGER test_timer_freq_;
static test_timer_type_ test_timer_start_;
static test_timer_type_ test_timer_end_;
static void
test_timer_init_(void)
{
QueryPerformanceFrequency(&test_timer_freq_);
}
static void
test_timer_get_time_(LARGE_INTEGER* ts)
{
QueryPerformanceCounter(ts);
}
static double
test_timer_diff_(LARGE_INTEGER start, LARGE_INTEGER end)
{
double duration = (double)(end.QuadPart - start.QuadPart);
duration /= (double)test_timer_freq_.QuadPart;
return duration;
}
static void
test_timer_print_diff_(void)
{
printf("%.6lf secs", test_timer_diff_(test_timer_start_, test_timer_end_));
}
#elif defined ACUTEST_HAS_POSIX_TIMER_
static clockid_t test_timer_id_;
typedef struct timespec test_timer_type_;
static test_timer_type_ test_timer_start_;
static test_timer_type_ test_timer_end_;
static void
test_timer_init_(void)
{
if(test_timer_ == 1)
test_timer_id_ = CLOCK_MONOTONIC;
else if(test_timer_ == 2)
test_timer_id_ = CLOCK_PROCESS_CPUTIME_ID;
}
static void
test_timer_get_time_(struct timespec* ts)
{
clock_gettime(test_timer_id_, ts);
}
static double
test_timer_diff_(struct timespec start, struct timespec end)
{
double endns;
double startns;
endns = end.tv_sec;
endns *= 1e9;
endns += end.tv_nsec;
startns = start.tv_sec;
startns *= 1e9;
startns += start.tv_nsec;
return ((endns - startns)/ 1e9);
}
static void
test_timer_print_diff_(void)
{
printf("%.6lf secs",
test_timer_diff_(test_timer_start_, test_timer_end_));
}
#else
typedef int test_timer_type_;
static test_timer_type_ test_timer_start_;
static test_timer_type_ test_timer_end_;
void
test_timer_init_(void)
{}
static void
test_timer_get_time_(int* ts)
{
(void) ts;
}
static double
test_timer_diff_(int start, int end)
{
(void) start;
(void) end;
return 0.0;
}
static void
test_timer_print_diff_(void)
{}
#endif
#define TEST_COLOR_DEFAULT_ 0
#define TEST_COLOR_GREEN_ 1
#define TEST_COLOR_RED_ 2
#define TEST_COLOR_DEFAULT_INTENSIVE_ 3
#define TEST_COLOR_GREEN_INTENSIVE_ 4
#define TEST_COLOR_RED_INTENSIVE_ 5
static int TEST_ATTRIBUTE_(format (printf, 2, 3))
test_print_in_color_(int color, const char* fmt, ...)
{
va_list args;
char buffer[256];
int n;
va_start(args, fmt);
vsnprintf(buffer, sizeof(buffer), fmt, args);
va_end(args);
buffer[sizeof(buffer)-1] = '\0';
if(!test_colorize_) {
return printf("%s", buffer);
}
#if defined ACUTEST_UNIX_
{
const char* col_str;
switch(color) {
case TEST_COLOR_GREEN_: col_str = "\033[0;32m"; break;
case TEST_COLOR_RED_: col_str = "\033[0;31m"; break;
case TEST_COLOR_GREEN_INTENSIVE_: col_str = "\033[1;32m"; break;
case TEST_COLOR_RED_INTENSIVE_: col_str = "\033[1;31m"; break;
case TEST_COLOR_DEFAULT_INTENSIVE_: col_str = "\033[1m"; break;
default: col_str = "\033[0m"; break;
}
printf("%s", col_str);
n = printf("%s", buffer);
printf("\033[0m");
return n;
}
#elif defined ACUTEST_WIN_
{
HANDLE h;
CONSOLE_SCREEN_BUFFER_INFO info;
WORD attr;
h = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(h, &info);
switch(color) {
case TEST_COLOR_GREEN_: attr = FOREGROUND_GREEN; break;
case TEST_COLOR_RED_: attr = FOREGROUND_RED; break;
case TEST_COLOR_GREEN_INTENSIVE_: attr = FOREGROUND_GREEN | FOREGROUND_INTENSITY; break;
case TEST_COLOR_RED_INTENSIVE_: attr = FOREGROUND_RED | FOREGROUND_INTENSITY; break;
case TEST_COLOR_DEFAULT_INTENSIVE_: attr = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY; break;
default: attr = 0; break;
}
if(attr != 0)
SetConsoleTextAttribute(h, attr);
n = printf("%s", buffer);
SetConsoleTextAttribute(h, info.wAttributes);
return n;
}
#else
n = printf("%s", buffer);
return n;
#endif
}
static void
test_begin_test_line_(const struct test_* test)
{
if(!test_tap_) {
if(test_verbose_level_ >= 3) {
test_print_in_color_(TEST_COLOR_DEFAULT_INTENSIVE_, "Test %s:\n", test->name);
test_current_already_logged_++;
} else if(test_verbose_level_ >= 1) {
int n;
char spaces[48];
n = test_print_in_color_(TEST_COLOR_DEFAULT_INTENSIVE_, "Test %s... ", test->name);
memset(spaces, ' ', sizeof(spaces));
if(n < (int) sizeof(spaces))
printf("%.*s", (int) sizeof(spaces) - n, spaces);
} else {
test_current_already_logged_ = 1;
}
}
}
static void
test_finish_test_line_(int result)
{
if(test_tap_) {
const char* str = (result == 0) ? "ok" : "not ok";
printf("%s %d - %s\n", str, test_current_index_ + 1, test_current_unit_->name);
if(result == 0 && test_timer_) {
printf("# Duration: ");
test_timer_print_diff_();
printf("\n");
}
} else {
int color = (result == 0) ? TEST_COLOR_GREEN_INTENSIVE_ : TEST_COLOR_RED_INTENSIVE_;
const char* str = (result == 0) ? "OK" : "FAILED";
printf("[ ");
test_print_in_color_(color, "%s", str);
printf(" ]");
if(result == 0 && test_timer_) {
printf(" ");
test_timer_print_diff_();
}
printf("\n");
}
}
static void
test_line_indent_(int level)
{
static const char spaces[] = " ";
int n = level * 2;
if(test_tap_ && n > 0) {
n--;
printf("#");
}
while(n > 16) {
printf("%s", spaces);
n -= 16;
}
printf("%.*s", n, spaces);
}
int TEST_ATTRIBUTE_(format (printf, 4, 5))
test_check_(int cond, const char* file, int line, const char* fmt, ...)
{
const char *result_str;
int result_color;
int verbose_level;
if(cond) {
result_str = "ok";
result_color = TEST_COLOR_GREEN_;
verbose_level = 3;
} else {
if(!test_current_already_logged_ && test_current_unit_ != NULL)
test_finish_test_line_(-1);
result_str = "failed";
result_color = TEST_COLOR_RED_;
verbose_level = 2;
test_current_failures_++;
test_current_already_logged_++;
}
if(test_verbose_level_ >= verbose_level) {
va_list args;
if(!test_case_current_already_logged_ && test_case_name_[0]) {
test_line_indent_(1);
test_print_in_color_(TEST_COLOR_DEFAULT_INTENSIVE_, "Case %s:\n", test_case_name_);
test_current_already_logged_++;
test_case_current_already_logged_++;
}
test_line_indent_(test_case_name_[0] ? 2 : 1);
if(file != NULL) {
#ifdef ACUTEST_WIN_
const char* lastsep1 = strrchr(file, '\\');
const char* lastsep2 = strrchr(file, '/');
if(lastsep1 == NULL)
lastsep1 = file-1;
if(lastsep2 == NULL)
lastsep2 = file-1;
file = (lastsep1 > lastsep2 ? lastsep1 : lastsep2) + 1;
#else
const char* lastsep = strrchr(file, '/');
if(lastsep != NULL)
file = lastsep+1;
#endif
printf("%s:%d: Check ", file, line);
}
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
printf("... ");
test_print_in_color_(result_color, "%s", result_str);
printf("\n");
test_current_already_logged_++;
}
test_cond_failed_ = (cond == 0);
return !test_cond_failed_;
}
void TEST_ATTRIBUTE_(format (printf, 1, 2))
test_case_(const char* fmt, ...)
{
va_list args;
if(test_verbose_level_ < 2)
return;
if(test_case_name_[0]) {
test_case_current_already_logged_ = 0;
test_case_name_[0] = '\0';
}
if(fmt == NULL)
return;
va_start(args, fmt);
vsnprintf(test_case_name_, sizeof(test_case_name_) - 1, fmt, args);
va_end(args);
test_case_name_[sizeof(test_case_name_) - 1] = '\0';
if(test_verbose_level_ >= 3) {
test_line_indent_(1);
test_print_in_color_(TEST_COLOR_DEFAULT_INTENSIVE_, "Case %s:\n", test_case_name_);
test_current_already_logged_++;
test_case_current_already_logged_++;
}
}
void TEST_ATTRIBUTE_(format (printf, 1, 2))
test_message_(const char* fmt, ...)
{
char buffer[TEST_MSG_MAXSIZE];
char* line_beg;
char* line_end;
va_list args;
if(test_verbose_level_ < 2)
return;
/* We allow extra message only when something is already wrong in the
* current test. */
if(test_current_unit_ == NULL || !test_cond_failed_)
return;
va_start(args, fmt);
vsnprintf(buffer, TEST_MSG_MAXSIZE, fmt, args);
va_end(args);
buffer[TEST_MSG_MAXSIZE-1] = '\0';
line_beg = buffer;
while(1) {
line_end = strchr(line_beg, '\n');
if(line_end == NULL)
break;
test_line_indent_(test_case_name_[0] ? 3 : 2);
printf("%.*s\n", (int)(line_end - line_beg), line_beg);
line_beg = line_end + 1;
}
if(line_beg[0] != '\0') {
test_line_indent_(test_case_name_[0] ? 3 : 2);
printf("%s\n", line_beg);
}
}
void
test_dump_(const char* title, const void* addr, size_t size)
{
static const size_t BYTES_PER_LINE = 16;
size_t line_beg;
size_t truncate = 0;
if(test_verbose_level_ < 2)
return;
/* We allow extra message only when something is already wrong in the
* current test. */
if(test_current_unit_ == NULL || !test_cond_failed_)
return;
if(size > TEST_DUMP_MAXSIZE) {
truncate = size - TEST_DUMP_MAXSIZE;
size = TEST_DUMP_MAXSIZE;
}
test_line_indent_(test_case_name_[0] ? 3 : 2);
printf((title[strlen(title)-1] == ':') ? "%s\n" : "%s:\n", title);
for(line_beg = 0; line_beg < size; line_beg += BYTES_PER_LINE) {
size_t line_end = line_beg + BYTES_PER_LINE;
size_t off;
test_line_indent_(test_case_name_[0] ? 4 : 3);
printf("%08lx: ", (unsigned long)line_beg);
for(off = line_beg; off < line_end; off++) {
if(off < size)
printf(" %02x", ((const unsigned char*)addr)[off]);
else
printf(" ");
}
printf(" ");
for(off = line_beg; off < line_end; off++) {
unsigned char byte = ((const unsigned char*)addr)[off];
if(off < size)
printf("%c", (iscntrl(byte) ? '.' : byte));
else
break;
}
printf("\n");
}
if(truncate > 0) {
test_line_indent_(test_case_name_[0] ? 4 : 3);
printf(" ... (and more %u bytes)\n", (unsigned) truncate);
}
}
void
test_abort_(void)
{
if(test_abort_has_jmp_buf_)
longjmp(test_abort_jmp_buf_, 1);
else
abort();
}
static void
test_list_names_(void)
{
const struct test_* test;
printf("Unit tests:\n");
for(test = &test_list_[0]; test->func != NULL; test++)
printf(" %s\n", test->name);
}
static void
test_remember_(int i)
{
if(test_details_[i].flags & TEST_FLAG_RUN_)
return;
test_details_[i].flags |= TEST_FLAG_RUN_;
test_count_++;
}
static void
test_set_success_(int i, int success)
{
test_details_[i].flags |= success ? TEST_FLAG_SUCCESS_ : TEST_FLAG_FAILURE_;
}
static void
test_set_duration_(int i, double duration)
{
test_details_[i].duration = duration;
}
static int
test_name_contains_word_(const char* name, const char* pattern)
{
static const char word_delim[] = " \t-_/.,:;";
const char* substr;
size_t pattern_len;
pattern_len = strlen(pattern);
substr = strstr(name, pattern);
while(substr != NULL) {
int starts_on_word_boundary = (substr == name || strchr(word_delim, substr[-1]) != NULL);
int ends_on_word_boundary = (substr[pattern_len] == '\0' || strchr(word_delim, substr[pattern_len]) != NULL);
if(starts_on_word_boundary && ends_on_word_boundary)
return 1;
substr = strstr(substr+1, pattern);
}
return 0;
}
static int
test_lookup_(const char* pattern)
{
int i;
int n = 0;
/* Try exact match. */
for(i = 0; i < (int) test_list_size_; i++) {
if(strcmp(test_list_[i].name, pattern) == 0) {
test_remember_(i);
n++;
break;
}
}
if(n > 0)
return n;
/* Try word match. */
for(i = 0; i < (int) test_list_size_; i++) {
if(test_name_contains_word_(test_list_[i].name, pattern)) {
test_remember_(i);
n++;
}
}
if(n > 0)
return n;
/* Try relaxed match. */
for(i = 0; i < (int) test_list_size_; i++) {
if(strstr(test_list_[i].name, pattern) != NULL) {
test_remember_(i);
n++;
}
}
return n;
}
/* Called if anything goes bad in Acutest, or if the unit test ends in other
* way then by normal returning from its function (e.g. exception or some
* abnormal child process termination). */
static void TEST_ATTRIBUTE_(format (printf, 1, 2))
test_error_(const char* fmt, ...)
{
if(test_verbose_level_ == 0)
return;
if(test_verbose_level_ >= 2) {
va_list args;
test_line_indent_(1);
if(test_verbose_level_ >= 3)
test_print_in_color_(TEST_COLOR_RED_INTENSIVE_, "ERROR: ");
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
printf("\n");
}
if(test_verbose_level_ >= 3) {
printf("\n");
}
}
/* This is called just before each test */
static void
test_init_(const char *test_name)
{
#ifdef TEST_INIT
TEST_INIT
; /* Allow for a single unterminated function call */
#endif
/* Suppress any warnings about unused variable. */
(void) test_name;
}
/* This is called after each test */
static void
test_fini_(const char *test_name)
{
#ifdef TEST_FINI
TEST_FINI
; /* Allow for a single unterminated function call */
#endif
/* Suppress any warnings about unused variable. */
(void) test_name;
}
/* Call directly the given test unit function. */
static int
test_do_run_(const struct test_* test, int index)
{
int status = -1;
test_was_aborted_ = 0;
test_current_unit_ = test;
test_current_index_ = index;
test_current_failures_ = 0;
test_current_already_logged_ = 0;
test_cond_failed_ = 0;
#ifdef __cplusplus
try {
#endif
test_init_(test->name);
test_begin_test_line_(test);
/* This is good to do in case the test unit crashes. */
fflush(stdout);
fflush(stderr);
if(!test_worker_) {
test_abort_has_jmp_buf_ = 1;
if(setjmp(test_abort_jmp_buf_) != 0) {