2 * Copyright 2008 Google Inc.
3 * Copyright 2014-2015 Andreas Schneider <asn@cryptomilk.org>
4 * Copyright 2015 Jakub Hrozek <jakub.hrozek@posteo.se>
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
26 #ifdef HAVE_INTTYPES_H
44 * This allows to add a platform specific header file. Some embedded platforms
45 * sometimes miss certain types and definitions.
49 * typedef unsigned long int uintptr_t
50 * #define _UINTPTR_T 1
51 * #define _UINTPTR_T_DEFINED 1
53 #ifdef CMOCKA_PLATFORM_INCLUDE
54 # include "cmocka_platform.h"
55 #endif /* CMOCKA_PLATFORM_INCLUDE */
58 #include <cmocka_private.h>
60 /* Size of guard bytes around dynamically allocated blocks. */
61 #define MALLOC_GUARD_SIZE 16
62 /* Pattern used to initialize guard blocks. */
63 #define MALLOC_GUARD_PATTERN 0xEF
64 /* Pattern used to initialize memory allocated with test_malloc(). */
65 #define MALLOC_ALLOC_PATTERN 0xBA
66 #define MALLOC_FREE_PATTERN 0xCD
67 /* Alignment of allocated blocks. NOTE: This must be base2. */
68 #define MALLOC_ALIGNMENT sizeof(size_t)
70 /* Printf formatting for source code locations. */
71 #define SOURCE_LOCATION_FORMAT "%s:%u"
73 #if defined(HAVE_GCC_THREAD_LOCAL_STORAGE)
74 # define CMOCKA_THREAD __thread
75 #elif defined(HAVE_MSVC_THREAD_LOCAL_STORAGE)
76 # define CMOCKA_THREAD __declspec(thread)
78 # define CMOCKA_THREAD
81 #ifdef HAVE_CLOCK_GETTIME_REALTIME
82 #define CMOCKA_CLOCK_GETTIME(clock_id, ts) clock_gettime((clock_id), (ts))
84 #define CMOCKA_CLOCK_GETTIME(clock_id, ts)
88 * Declare and initialize the pointer member of ValuePointer variable name
91 #define declare_initialize_value_pointer_pointer(name, ptr) \
94 name.x.pointer = (void*)(ptr)
97 * Declare and initialize the value member of ValuePointer variable name
100 #define declare_initialize_value_pointer_value(name, val) \
101 ValuePointer name ; \
104 /* Cast a LargestIntegralType to pointer_type via a ValuePointer. */
105 #define cast_largest_integral_type_to_pointer( \
106 pointer_type, largest_integral_type) \
107 ((pointer_type)((ValuePointer*)&(largest_integral_type))->x.pointer)
109 /* Used to cast LargetIntegralType to void* and vice versa. */
110 typedef union ValuePointer {
111 LargestIntegralType value;
113 #if defined(WORDS_BIGENDIAN) && (WORDS_SIZEOF_VOID_P == 4)
114 unsigned int padding;
120 /* Doubly linked list node. */
121 typedef struct ListNode {
124 struct ListNode *next;
125 struct ListNode *prev;
128 /* Debug information for malloc(). */
129 typedef struct MallocBlockInfo {
130 void* block; /* Address of the block returned by malloc(). */
131 size_t allocated_size; /* Total size of the allocated block. */
132 size_t size; /* Request block size. */
133 SourceLocation location; /* Where the block was allocated. */
134 ListNode node; /* Node within list of all allocated blocks. */
137 /* State of each test. */
138 typedef struct TestState {
139 const ListNode *check_point; /* Check point of the test if there's a */
140 /* setup function. */
141 void *state; /* State associated with the test. */
144 /* Determines whether two values are the same. */
145 typedef int (*EqualityFunction)(const void *left, const void *right);
147 /* Value of a symbol and the place it was declared. */
148 typedef struct SymbolValue {
149 SourceLocation location;
150 LargestIntegralType value;
154 * Contains a list of values for a symbol.
155 * NOTE: Each structure referenced by symbol_values_list_head must have a
156 * SourceLocation as its' first member.
158 typedef struct SymbolMapValue {
159 const char *symbol_name;
160 ListNode symbol_values_list_head;
163 /* Used by list_free() to deallocate values referenced by list nodes. */
164 typedef void (*CleanupListValue)(const void *value, void *cleanup_value_data);
166 /* Structure used to check the range of integer types.a */
167 typedef struct CheckIntegerRange {
168 CheckParameterEvent event;
169 LargestIntegralType minimum;
170 LargestIntegralType maximum;
173 /* Structure used to check whether an integer value is in a set. */
174 typedef struct CheckIntegerSet {
175 CheckParameterEvent event;
176 const LargestIntegralType *set;
180 /* Used to check whether a parameter matches the area of memory referenced by
182 typedef struct CheckMemoryData {
183 CheckParameterEvent event;
188 static ListNode* list_initialize(ListNode * const node);
189 static ListNode* list_add(ListNode * const head, ListNode *new_node);
190 static ListNode* list_add_value(ListNode * const head, const void *value,
192 static ListNode* list_remove(
193 ListNode * const node, const CleanupListValue cleanup_value,
194 void * const cleanup_value_data);
195 static void list_remove_free(
196 ListNode * const node, const CleanupListValue cleanup_value,
197 void * const cleanup_value_data);
198 static int list_empty(const ListNode * const head);
199 static int list_find(
200 ListNode * const head, const void *value,
201 const EqualityFunction equal_func, ListNode **output);
202 static int list_first(ListNode * const head, ListNode **output);
203 static ListNode* list_free(
204 ListNode * const head, const CleanupListValue cleanup_value,
205 void * const cleanup_value_data);
207 static void add_symbol_value(
208 ListNode * const symbol_map_head, const char * const symbol_names[],
209 const size_t number_of_symbol_names, const void* value, const int count);
210 static int get_symbol_value(
211 ListNode * const symbol_map_head, const char * const symbol_names[],
212 const size_t number_of_symbol_names, void **output);
213 static void free_value(const void *value, void *cleanup_value_data);
214 static void free_symbol_map_value(
215 const void *value, void *cleanup_value_data);
216 static void remove_always_return_values(ListNode * const map_head,
217 const size_t number_of_symbol_names);
218 static int check_for_leftover_values(
219 const ListNode * const map_head, const char * const error_message,
220 const size_t number_of_symbol_names);
222 * This must be called at the beginning of a test to initialize some data
225 static void initialize_testing(const char *test_name);
227 /* This must be called at the end of a test to free() allocated structures. */
228 static void teardown_testing(const char *test_name);
230 static int cm_error_message_enabled = 1;
231 static CMOCKA_THREAD char *cm_error_message;
233 void cm_print_error(const char * const format, ...) CMOCKA_PRINTF_ATTRIBUTE(1, 2);
236 * Keeps track of the calling context returned by setenv() so that the fail()
237 * method can jump out of a test.
239 static CMOCKA_THREAD jmp_buf global_run_test_env;
240 static CMOCKA_THREAD int global_running_test = 0;
242 /* Keeps track of the calling context returned by setenv() so that */
243 /* mock_assert() can optionally jump back to expect_assert_failure(). */
244 jmp_buf global_expect_assert_env;
245 int global_expecting_assert = 0;
246 const char *global_last_failed_assert = NULL;
247 static int global_skip_test;
249 /* Keeps a map of the values that functions will have to return to provide */
250 /* mocked interfaces. */
251 static CMOCKA_THREAD ListNode global_function_result_map_head;
252 /* Location of the last mock value returned was declared. */
253 static CMOCKA_THREAD SourceLocation global_last_mock_value_location;
255 /* Keeps a map of the values that functions expect as parameters to their
256 * mocked interfaces. */
257 static CMOCKA_THREAD ListNode global_function_parameter_map_head;
258 /* Location of last parameter value checked was declared. */
259 static CMOCKA_THREAD SourceLocation global_last_parameter_location;
261 /* List of all currently allocated blocks. */
262 static CMOCKA_THREAD ListNode global_allocated_blocks;
264 static enum cm_message_output global_msg_output = CM_OUTPUT_STDOUT;
267 /* Signals caught by exception_handler(). */
268 static const int exception_signals[] = {
280 /* Default signal functions that should be restored after a test is complete. */
281 typedef void (*SignalFunction)(int signal);
282 static SignalFunction default_signal_functions[
283 ARRAY_SIZE(exception_signals)];
287 /* The default exception filter. */
288 static LPTOP_LEVEL_EXCEPTION_FILTER previous_exception_filter;
290 /* Fatal exceptions. */
291 typedef struct ExceptionCodeInfo {
293 const char* description;
296 #define EXCEPTION_CODE_INFO(exception_code) {exception_code, #exception_code}
298 static const ExceptionCodeInfo exception_codes[] = {
299 EXCEPTION_CODE_INFO(EXCEPTION_ACCESS_VIOLATION),
300 EXCEPTION_CODE_INFO(EXCEPTION_ARRAY_BOUNDS_EXCEEDED),
301 EXCEPTION_CODE_INFO(EXCEPTION_DATATYPE_MISALIGNMENT),
302 EXCEPTION_CODE_INFO(EXCEPTION_FLT_DENORMAL_OPERAND),
303 EXCEPTION_CODE_INFO(EXCEPTION_FLT_DIVIDE_BY_ZERO),
304 EXCEPTION_CODE_INFO(EXCEPTION_FLT_INEXACT_RESULT),
305 EXCEPTION_CODE_INFO(EXCEPTION_FLT_INVALID_OPERATION),
306 EXCEPTION_CODE_INFO(EXCEPTION_FLT_OVERFLOW),
307 EXCEPTION_CODE_INFO(EXCEPTION_FLT_STACK_CHECK),
308 EXCEPTION_CODE_INFO(EXCEPTION_FLT_UNDERFLOW),
309 EXCEPTION_CODE_INFO(EXCEPTION_GUARD_PAGE),
310 EXCEPTION_CODE_INFO(EXCEPTION_ILLEGAL_INSTRUCTION),
311 EXCEPTION_CODE_INFO(EXCEPTION_INT_DIVIDE_BY_ZERO),
312 EXCEPTION_CODE_INFO(EXCEPTION_INT_OVERFLOW),
313 EXCEPTION_CODE_INFO(EXCEPTION_INVALID_DISPOSITION),
314 EXCEPTION_CODE_INFO(EXCEPTION_INVALID_HANDLE),
315 EXCEPTION_CODE_INFO(EXCEPTION_IN_PAGE_ERROR),
316 EXCEPTION_CODE_INFO(EXCEPTION_NONCONTINUABLE_EXCEPTION),
317 EXCEPTION_CODE_INFO(EXCEPTION_PRIV_INSTRUCTION),
318 EXCEPTION_CODE_INFO(EXCEPTION_STACK_OVERFLOW),
322 enum CMUnitTestStatus {
330 struct CMUnitTestState {
331 const ListNode *check_point; /* Check point of the test if there's a setup function. */
332 const struct CMUnitTest *test; /* Point to array element in the tests we get passed */
333 void *state; /* State associated with the test */
334 const char *error_message; /* The error messages by the test */
335 enum CMUnitTestStatus status; /* PASSED, FAILED, ABORT ... */
336 double runtime; /* Time calculations */
339 /* Exit the currently executing test. */
340 static void exit_test(const int quit_application)
342 const char *abort_test = getenv("CMOCKA_TEST_ABORT");
344 if (abort_test != NULL && abort_test[0] == '1') {
345 print_error("%s", cm_error_message);
347 } else if (global_running_test) {
348 longjmp(global_run_test_env, 1);
349 } else if (quit_application) {
354 void _skip(const char * const file, const int line)
356 cm_print_error(SOURCE_LOCATION_FORMAT ": Skipped!\n", file, line);
357 global_skip_test = 1;
361 /* Initialize a SourceLocation structure. */
362 static void initialize_source_location(SourceLocation * const location) {
363 assert_non_null(location);
364 location->file = NULL;
369 /* Determine whether a source location is currently set. */
370 static int source_location_is_set(const SourceLocation * const location) {
371 assert_non_null(location);
372 return location->file && location->line;
376 /* Set a source location. */
377 static void set_source_location(
378 SourceLocation * const location, const char * const file,
380 assert_non_null(location);
381 location->file = file;
382 location->line = line;
386 /* Create function results and expected parameter lists. */
387 void initialize_testing(const char *test_name) {
389 list_initialize(&global_function_result_map_head);
390 initialize_source_location(&global_last_mock_value_location);
391 list_initialize(&global_function_parameter_map_head);
392 initialize_source_location(&global_last_parameter_location);
396 static void fail_if_leftover_values(const char *test_name) {
397 int error_occurred = 0;
399 remove_always_return_values(&global_function_result_map_head, 1);
400 if (check_for_leftover_values(
401 &global_function_result_map_head,
402 "%s() has remaining non-returned values.\n", 1)) {
406 remove_always_return_values(&global_function_parameter_map_head, 2);
407 if (check_for_leftover_values(
408 &global_function_parameter_map_head,
409 "%s parameter still has values that haven't been checked.\n", 2)) {
412 if (error_occurred) {
418 static void teardown_testing(const char *test_name) {
420 list_free(&global_function_result_map_head, free_symbol_map_value,
422 initialize_source_location(&global_last_mock_value_location);
423 list_free(&global_function_parameter_map_head, free_symbol_map_value,
425 initialize_source_location(&global_last_parameter_location);
428 /* Initialize a list node. */
429 static ListNode* list_initialize(ListNode * const node) {
439 * Adds a value at the tail of a given list.
440 * The node referencing the value is allocated from the heap.
442 static ListNode* list_add_value(ListNode * const head, const void *value,
443 const int refcount) {
444 ListNode * const new_node = (ListNode*)malloc(sizeof(ListNode));
445 assert_non_null(head);
446 assert_non_null(value);
447 new_node->value = value;
448 new_node->refcount = refcount;
449 return list_add(head, new_node);
453 /* Add new_node to the end of the list. */
454 static ListNode* list_add(ListNode * const head, ListNode *new_node) {
455 assert_non_null(head);
456 assert_non_null(new_node);
457 new_node->next = head;
458 new_node->prev = head->prev;
459 head->prev->next = new_node;
460 head->prev = new_node;
465 /* Remove a node from a list. */
466 static ListNode* list_remove(
467 ListNode * const node, const CleanupListValue cleanup_value,
468 void * const cleanup_value_data) {
469 assert_non_null(node);
470 node->prev->next = node->next;
471 node->next->prev = node->prev;
473 cleanup_value(node->value, cleanup_value_data);
479 /* Remove a list node from a list and free the node. */
480 static void list_remove_free(
481 ListNode * const node, const CleanupListValue cleanup_value,
482 void * const cleanup_value_data) {
483 assert_non_null(node);
484 free(list_remove(node, cleanup_value, cleanup_value_data));
489 * Frees memory kept by a linked list The cleanup_value function is called for
490 * every "value" field of nodes in the list, except for the head. In addition
491 * to each list value, cleanup_value_data is passed to each call to
492 * cleanup_value. The head of the list is not deallocated.
494 static ListNode* list_free(
495 ListNode * const head, const CleanupListValue cleanup_value,
496 void * const cleanup_value_data) {
497 assert_non_null(head);
498 while (!list_empty(head)) {
499 list_remove_free(head->next, cleanup_value, cleanup_value_data);
505 /* Determine whether a list is empty. */
506 static int list_empty(const ListNode * const head) {
507 assert_non_null(head);
508 return head->next == head;
513 * Find a value in the list using the equal_func to compare each node with the
516 static int list_find(ListNode * const head, const void *value,
517 const EqualityFunction equal_func, ListNode **output) {
519 assert_non_null(head);
520 for (current = head->next; current != head; current = current->next) {
521 if (equal_func(current->value, value)) {
529 /* Returns the first node of a list */
530 static int list_first(ListNode * const head, ListNode **output) {
531 ListNode *target_node;
532 assert_non_null(head);
533 if (list_empty(head)) {
536 target_node = head->next;
537 *output = target_node;
542 /* Deallocate a value referenced by a list. */
543 static void free_value(const void *value, void *cleanup_value_data) {
544 (void)cleanup_value_data;
545 assert_non_null(value);
550 /* Releases memory associated to a symbol_map_value. */
551 static void free_symbol_map_value(const void *value,
552 void *cleanup_value_data) {
553 SymbolMapValue * const map_value = (SymbolMapValue*)value;
554 const LargestIntegralType children = cast_ptr_to_largest_integral_type(cleanup_value_data);
555 assert_non_null(value);
556 list_free(&map_value->symbol_values_list_head,
557 children ? free_symbol_map_value : free_value,
558 (void *) ((uintptr_t)children - 1));
564 * Determine whether a symbol name referenced by a symbol_map_value matches the
565 * specified function name.
567 static int symbol_names_match(const void *map_value, const void *symbol) {
568 return !strcmp(((SymbolMapValue*)map_value)->symbol_name,
569 (const char*)symbol);
574 * Adds a value to the queue of values associated with the given hierarchy of
575 * symbols. It's assumed value is allocated from the heap.
577 static void add_symbol_value(ListNode * const symbol_map_head,
578 const char * const symbol_names[],
579 const size_t number_of_symbol_names,
580 const void* value, const int refcount) {
581 const char* symbol_name;
582 ListNode *target_node;
583 SymbolMapValue *target_map_value;
584 assert_non_null(symbol_map_head);
585 assert_non_null(symbol_names);
586 assert_true(number_of_symbol_names);
587 symbol_name = symbol_names[0];
589 if (!list_find(symbol_map_head, symbol_name, symbol_names_match,
591 SymbolMapValue * const new_symbol_map_value =
592 (SymbolMapValue*)malloc(sizeof(*new_symbol_map_value));
593 new_symbol_map_value->symbol_name = symbol_name;
594 list_initialize(&new_symbol_map_value->symbol_values_list_head);
595 target_node = list_add_value(symbol_map_head, new_symbol_map_value,
599 target_map_value = (SymbolMapValue*)target_node->value;
600 if (number_of_symbol_names == 1) {
601 list_add_value(&target_map_value->symbol_values_list_head,
604 add_symbol_value(&target_map_value->symbol_values_list_head,
605 &symbol_names[1], number_of_symbol_names - 1, value,
612 * Gets the next value associated with the given hierarchy of symbols.
613 * The value is returned as an output parameter with the function returning the
614 * node's old refcount value if a value is found, 0 otherwise. This means that
615 * a return value of 1 indicates the node was just removed from the list.
617 static int get_symbol_value(
618 ListNode * const head, const char * const symbol_names[],
619 const size_t number_of_symbol_names, void **output) {
620 const char* symbol_name;
621 ListNode *target_node;
622 assert_non_null(head);
623 assert_non_null(symbol_names);
624 assert_true(number_of_symbol_names);
625 assert_non_null(output);
626 symbol_name = symbol_names[0];
628 if (list_find(head, symbol_name, symbol_names_match, &target_node)) {
629 SymbolMapValue *map_value;
630 ListNode *child_list;
631 int return_value = 0;
632 assert_non_null(target_node);
633 assert_non_null(target_node->value);
635 map_value = (SymbolMapValue*)target_node->value;
636 child_list = &map_value->symbol_values_list_head;
638 if (number_of_symbol_names == 1) {
639 ListNode *value_node = NULL;
640 return_value = list_first(child_list, &value_node);
641 assert_true(return_value);
642 *output = (void*) value_node->value;
643 return_value = value_node->refcount;
644 if (--value_node->refcount == 0) {
645 list_remove_free(value_node, NULL, NULL);
648 return_value = get_symbol_value(
649 child_list, &symbol_names[1], number_of_symbol_names - 1,
652 if (list_empty(child_list)) {
653 list_remove_free(target_node, free_symbol_map_value, (void*)0);
657 cm_print_error("No entries for symbol %s.\n", symbol_name);
664 * Traverse down a tree of symbol values and remove the first symbol value
665 * in each branch that has a refcount < -1 (i.e should always be returned
666 * and has been returned at least once).
668 static void remove_always_return_values(ListNode * const map_head,
669 const size_t number_of_symbol_names) {
671 assert_non_null(map_head);
672 assert_true(number_of_symbol_names);
673 current = map_head->next;
674 while (current != map_head) {
675 SymbolMapValue * const value = (SymbolMapValue*)current->value;
676 ListNode * const next = current->next;
677 ListNode *child_list;
678 assert_non_null(value);
679 child_list = &value->symbol_values_list_head;
681 if (!list_empty(child_list)) {
682 if (number_of_symbol_names == 1) {
683 ListNode * const child_node = child_list->next;
684 /* If this item has been returned more than once, free it. */
685 if (child_node->refcount < -1) {
686 list_remove_free(child_node, free_value, NULL);
689 remove_always_return_values(child_list,
690 number_of_symbol_names - 1);
694 if (list_empty(child_list)) {
695 list_remove_free(current, free_value, NULL);
702 * Checks if there are any leftover values set up by the test that were never
703 * retrieved through execution, and fail the test if that is the case.
705 static int check_for_leftover_values(
706 const ListNode * const map_head, const char * const error_message,
707 const size_t number_of_symbol_names) {
708 const ListNode *current;
709 int symbols_with_leftover_values = 0;
710 assert_non_null(map_head);
711 assert_true(number_of_symbol_names);
713 for (current = map_head->next; current != map_head;
714 current = current->next) {
715 const SymbolMapValue * const value =
716 (SymbolMapValue*)current->value;
717 const ListNode *child_list;
718 assert_non_null(value);
719 child_list = &value->symbol_values_list_head;
721 if (!list_empty(child_list)) {
722 if (number_of_symbol_names == 1) {
723 const ListNode *child_node;
724 cm_print_error(error_message, value->symbol_name);
726 for (child_node = child_list->next; child_node != child_list;
727 child_node = child_node->next) {
728 const SourceLocation * const location =
729 (const SourceLocation*)child_node->value;
730 cm_print_error(SOURCE_LOCATION_FORMAT
731 ": note: remaining item was declared here\n",
732 location->file, location->line);
735 cm_print_error("%s.", value->symbol_name);
736 check_for_leftover_values(child_list, error_message,
737 number_of_symbol_names - 1);
739 symbols_with_leftover_values ++;
742 return symbols_with_leftover_values;
746 /* Get the next return value for the specified mock function. */
747 LargestIntegralType _mock(const char * const function, const char* const file,
750 const int rc = get_symbol_value(&global_function_result_map_head,
751 &function, 1, &result);
753 SymbolValue * const symbol = (SymbolValue*)result;
754 const LargestIntegralType value = symbol->value;
755 global_last_mock_value_location = symbol->location;
761 cm_print_error(SOURCE_LOCATION_FORMAT ": error: Could not get value "
762 "to mock function %s\n", file, line, function);
763 if (source_location_is_set(&global_last_mock_value_location)) {
764 cm_print_error(SOURCE_LOCATION_FORMAT
765 ": note: Previously returned mock value was declared here\n",
766 global_last_mock_value_location.file,
767 global_last_mock_value_location.line);
769 cm_print_error("There were no previously returned mock values for "
778 /* Add a return value for the specified mock function name. */
779 void _will_return(const char * const function_name, const char * const file,
780 const int line, const LargestIntegralType value,
782 SymbolValue * const return_value =
783 (SymbolValue*)malloc(sizeof(*return_value));
784 assert_true(count > 0 || count == -1);
785 return_value->value = value;
786 set_source_location(&return_value->location, file, line);
787 add_symbol_value(&global_function_result_map_head, &function_name, 1,
788 return_value, count);
793 * Add a custom parameter checking function. If the event parameter is NULL
794 * the event structure is allocated internally by this function. If event
795 * parameter is provided it must be allocated on the heap and doesn't need to
796 * be deallocated by the caller.
799 const char* const function, const char* const parameter,
800 const char* const file, const int line,
801 const CheckParameterValue check_function,
802 const LargestIntegralType check_data,
803 CheckParameterEvent * const event, const int count) {
804 CheckParameterEvent * const check =
805 event ? event : (CheckParameterEvent*)malloc(sizeof(*check));
806 const char* symbols[] = {function, parameter};
807 check->parameter_name = parameter;
808 check->check_value = check_function;
809 check->check_value_data = check_data;
810 set_source_location(&check->location, file, line);
811 add_symbol_value(&global_function_parameter_map_head, symbols, 2, check,
816 /* Returns 1 if the specified values are equal. If the values are not equal
817 * an error is displayed and 0 is returned. */
818 static int values_equal_display_error(const LargestIntegralType left,
819 const LargestIntegralType right) {
820 const int equal = left == right;
822 cm_print_error(LargestIntegralTypePrintfFormat " != "
823 LargestIntegralTypePrintfFormat "\n", left, right);
829 * Returns 1 if the specified values are not equal. If the values are equal
830 * an error is displayed and 0 is returned. */
831 static int values_not_equal_display_error(const LargestIntegralType left,
832 const LargestIntegralType right) {
833 const int not_equal = left != right;
835 cm_print_error(LargestIntegralTypePrintfFormat " == "
836 LargestIntegralTypePrintfFormat "\n", left, right);
843 * Determine whether value is contained within check_integer_set.
844 * If invert is 0 and the value is in the set 1 is returned, otherwise 0 is
845 * returned and an error is displayed. If invert is 1 and the value is not
846 * in the set 1 is returned, otherwise 0 is returned and an error is
849 static int value_in_set_display_error(
850 const LargestIntegralType value,
851 const CheckIntegerSet * const check_integer_set, const int invert) {
852 int succeeded = invert;
853 assert_non_null(check_integer_set);
855 const LargestIntegralType * const set = check_integer_set->set;
856 const size_t size_of_set = check_integer_set->size_of_set;
858 for (i = 0; i < size_of_set; i++) {
859 if (set[i] == value) {
860 /* If invert = 0 and item is found, succeeded = 1. */
861 /* If invert = 1 and item is found, succeeded = 0. */
862 succeeded = !succeeded;
869 cm_print_error("%" PRIu64 " is %sin the set (", value,
870 invert ? "" : "not ");
871 for (i = 0; i < size_of_set; i++) {
872 cm_print_error("%" PRIu64 ", ", set[i]);
874 cm_print_error(")\n");
881 * Determine whether a value is within the specified range. If the value is
882 * within the specified range 1 is returned. If the value isn't within the
883 * specified range an error is displayed and 0 is returned.
885 static int integer_in_range_display_error(
886 const LargestIntegralType value, const LargestIntegralType range_min,
887 const LargestIntegralType range_max) {
888 if (value >= range_min && value <= range_max) {
891 cm_print_error("%" PRIu64 " is not within the range %" PRIu64 "-%" PRIu64 "\n",
892 value, range_min, range_max);
898 * Determine whether a value is within the specified range. If the value
899 * is not within the range 1 is returned. If the value is within the
900 * specified range an error is displayed and zero is returned.
902 static int integer_not_in_range_display_error(
903 const LargestIntegralType value, const LargestIntegralType range_min,
904 const LargestIntegralType range_max) {
905 if (value < range_min || value > range_max) {
908 cm_print_error("%" PRIu64 " is within the range %" PRIu64 "-%" PRIu64 "\n",
909 value, range_min, range_max);
915 * Determine whether the specified strings are equal. If the strings are equal
916 * 1 is returned. If they're not equal an error is displayed and 0 is
919 static int string_equal_display_error(
920 const char * const left, const char * const right) {
921 if (strcmp(left, right) == 0) {
924 cm_print_error("\"%s\" != \"%s\"\n", left, right);
930 * Determine whether the specified strings are equal. If the strings are not
931 * equal 1 is returned. If they're not equal an error is displayed and 0 is
934 static int string_not_equal_display_error(
935 const char * const left, const char * const right) {
936 if (strcmp(left, right) != 0) {
939 cm_print_error("\"%s\" == \"%s\"\n", left, right);
945 * Determine whether the specified areas of memory are equal. If they're equal
946 * 1 is returned otherwise an error is displayed and 0 is returned.
948 static int memory_equal_display_error(const char* const a, const char* const b,
952 for (i = 0; i < size; i++) {
956 cm_print_error("difference at offset %" PRIdS " 0x%02x 0x%02x\n",
962 cm_print_error("%d bytes of %p and %p differ\n", differences,
971 * Determine whether the specified areas of memory are not equal. If they're
972 * not equal 1 is returned otherwise an error is displayed and 0 is
975 static int memory_not_equal_display_error(
976 const char* const a, const char* const b, const size_t size) {
979 for (i = 0; i < size; i++) {
987 cm_print_error("%"PRIdS "bytes of %p and %p the same\n", same,
995 /* CheckParameterValue callback to check whether a value is within a set. */
996 static int check_in_set(const LargestIntegralType value,
997 const LargestIntegralType check_value_data) {
998 return value_in_set_display_error(value,
999 cast_largest_integral_type_to_pointer(CheckIntegerSet*,
1000 check_value_data), 0);
1004 /* CheckParameterValue callback to check whether a value isn't within a set. */
1005 static int check_not_in_set(const LargestIntegralType value,
1006 const LargestIntegralType check_value_data) {
1007 return value_in_set_display_error(value,
1008 cast_largest_integral_type_to_pointer(CheckIntegerSet*,
1009 check_value_data), 1);
1013 /* Create the callback data for check_in_set() or check_not_in_set() and
1014 * register a check event. */
1015 static void expect_set(
1016 const char* const function, const char* const parameter,
1017 const char* const file, const int line,
1018 const LargestIntegralType values[], const size_t number_of_values,
1019 const CheckParameterValue check_function, const int count) {
1020 CheckIntegerSet * const check_integer_set =
1021 (CheckIntegerSet*)malloc(sizeof(*check_integer_set) +
1022 (sizeof(values[0]) * number_of_values));
1023 LargestIntegralType * const set = (LargestIntegralType*)(
1024 check_integer_set + 1);
1025 declare_initialize_value_pointer_pointer(check_data, check_integer_set);
1026 assert_non_null(values);
1027 assert_true(number_of_values);
1028 memcpy(set, values, number_of_values * sizeof(values[0]));
1029 check_integer_set->set = set;
1030 check_integer_set->size_of_set = number_of_values;
1032 function, parameter, file, line, check_function,
1033 check_data.value, &check_integer_set->event, count);
1037 /* Add an event to check whether a value is in a set. */
1038 void _expect_in_set(
1039 const char* const function, const char* const parameter,
1040 const char* const file, const int line,
1041 const LargestIntegralType values[], const size_t number_of_values,
1043 expect_set(function, parameter, file, line, values, number_of_values,
1044 check_in_set, count);
1048 /* Add an event to check whether a value isn't in a set. */
1049 void _expect_not_in_set(
1050 const char* const function, const char* const parameter,
1051 const char* const file, const int line,
1052 const LargestIntegralType values[], const size_t number_of_values,
1054 expect_set(function, parameter, file, line, values, number_of_values,
1055 check_not_in_set, count);
1059 /* CheckParameterValue callback to check whether a value is within a range. */
1060 static int check_in_range(const LargestIntegralType value,
1061 const LargestIntegralType check_value_data) {
1062 CheckIntegerRange * const check_integer_range =
1063 cast_largest_integral_type_to_pointer(CheckIntegerRange*,
1065 assert_non_null(check_integer_range);
1066 return integer_in_range_display_error(value, check_integer_range->minimum,
1067 check_integer_range->maximum);
1071 /* CheckParameterValue callback to check whether a value is not within a range. */
1072 static int check_not_in_range(const LargestIntegralType value,
1073 const LargestIntegralType check_value_data) {
1074 CheckIntegerRange * const check_integer_range =
1075 cast_largest_integral_type_to_pointer(CheckIntegerRange*,
1077 assert_non_null(check_integer_range);
1078 return integer_not_in_range_display_error(
1079 value, check_integer_range->minimum, check_integer_range->maximum);
1083 /* Create the callback data for check_in_range() or check_not_in_range() and
1084 * register a check event. */
1085 static void expect_range(
1086 const char* const function, const char* const parameter,
1087 const char* const file, const int line,
1088 const LargestIntegralType minimum, const LargestIntegralType maximum,
1089 const CheckParameterValue check_function, const int count) {
1090 CheckIntegerRange * const check_integer_range =
1091 (CheckIntegerRange*)malloc(sizeof(*check_integer_range));
1092 declare_initialize_value_pointer_pointer(check_data, check_integer_range);
1093 check_integer_range->minimum = minimum;
1094 check_integer_range->maximum = maximum;
1095 _expect_check(function, parameter, file, line, check_function,
1096 check_data.value, &check_integer_range->event, count);
1100 /* Add an event to determine whether a parameter is within a range. */
1101 void _expect_in_range(
1102 const char* const function, const char* const parameter,
1103 const char* const file, const int line,
1104 const LargestIntegralType minimum, const LargestIntegralType maximum,
1106 expect_range(function, parameter, file, line, minimum, maximum,
1107 check_in_range, count);
1111 /* Add an event to determine whether a parameter is not within a range. */
1112 void _expect_not_in_range(
1113 const char* const function, const char* const parameter,
1114 const char* const file, const int line,
1115 const LargestIntegralType minimum, const LargestIntegralType maximum,
1117 expect_range(function, parameter, file, line, minimum, maximum,
1118 check_not_in_range, count);
1122 /* CheckParameterValue callback to check whether a value is equal to an
1123 * expected value. */
1124 static int check_value(const LargestIntegralType value,
1125 const LargestIntegralType check_value_data) {
1126 return values_equal_display_error(value, check_value_data);
1130 /* Add an event to check a parameter equals an expected value. */
1132 const char* const function, const char* const parameter,
1133 const char* const file, const int line,
1134 const LargestIntegralType value, const int count) {
1135 _expect_check(function, parameter, file, line, check_value, value, NULL,
1140 /* CheckParameterValue callback to check whether a value is not equal to an
1141 * expected value. */
1142 static int check_not_value(const LargestIntegralType value,
1143 const LargestIntegralType check_value_data) {
1144 return values_not_equal_display_error(value, check_value_data);
1148 /* Add an event to check a parameter is not equal to an expected value. */
1149 void _expect_not_value(
1150 const char* const function, const char* const parameter,
1151 const char* const file, const int line,
1152 const LargestIntegralType value, const int count) {
1153 _expect_check(function, parameter, file, line, check_not_value, value,
1158 /* CheckParameterValue callback to check whether a parameter equals a string. */
1159 static int check_string(const LargestIntegralType value,
1160 const LargestIntegralType check_value_data) {
1161 return string_equal_display_error(
1162 cast_largest_integral_type_to_pointer(char*, value),
1163 cast_largest_integral_type_to_pointer(char*, check_value_data));
1167 /* Add an event to check whether a parameter is equal to a string. */
1168 void _expect_string(
1169 const char* const function, const char* const parameter,
1170 const char* const file, const int line, const char* string,
1172 declare_initialize_value_pointer_pointer(string_pointer,
1173 discard_const(string));
1174 _expect_check(function, parameter, file, line, check_string,
1175 string_pointer.value, NULL, count);
1179 /* CheckParameterValue callback to check whether a parameter is not equals to
1181 static int check_not_string(const LargestIntegralType value,
1182 const LargestIntegralType check_value_data) {
1183 return string_not_equal_display_error(
1184 cast_largest_integral_type_to_pointer(char*, value),
1185 cast_largest_integral_type_to_pointer(char*, check_value_data));
1189 /* Add an event to check whether a parameter is not equal to a string. */
1190 void _expect_not_string(
1191 const char* const function, const char* const parameter,
1192 const char* const file, const int line, const char* string,
1194 declare_initialize_value_pointer_pointer(string_pointer,
1195 discard_const(string));
1196 _expect_check(function, parameter, file, line, check_not_string,
1197 string_pointer.value, NULL, count);
1200 /* CheckParameterValue callback to check whether a parameter equals an area of
1202 static int check_memory(const LargestIntegralType value,
1203 const LargestIntegralType check_value_data) {
1204 CheckMemoryData * const check = cast_largest_integral_type_to_pointer(
1205 CheckMemoryData*, check_value_data);
1206 assert_non_null(check);
1207 return memory_equal_display_error(
1208 cast_largest_integral_type_to_pointer(const char*, value),
1209 (const char*)check->memory, check->size);
1213 /* Create the callback data for check_memory() or check_not_memory() and
1214 * register a check event. */
1215 static void expect_memory_setup(
1216 const char* const function, const char* const parameter,
1217 const char* const file, const int line,
1218 const void * const memory, const size_t size,
1219 const CheckParameterValue check_function, const int count) {
1220 CheckMemoryData * const check_data =
1221 (CheckMemoryData*)malloc(sizeof(*check_data) + size);
1222 void * const mem = (void*)(check_data + 1);
1223 declare_initialize_value_pointer_pointer(check_data_pointer, check_data);
1224 assert_non_null(memory);
1226 memcpy(mem, memory, size);
1227 check_data->memory = mem;
1228 check_data->size = size;
1229 _expect_check(function, parameter, file, line, check_function,
1230 check_data_pointer.value, &check_data->event, count);
1234 /* Add an event to check whether a parameter matches an area of memory. */
1235 void _expect_memory(
1236 const char* const function, const char* const parameter,
1237 const char* const file, const int line, const void* const memory,
1238 const size_t size, const int count) {
1239 expect_memory_setup(function, parameter, file, line, memory, size,
1240 check_memory, count);
1244 /* CheckParameterValue callback to check whether a parameter is not equal to
1245 * an area of memory. */
1246 static int check_not_memory(const LargestIntegralType value,
1247 const LargestIntegralType check_value_data) {
1248 CheckMemoryData * const check = cast_largest_integral_type_to_pointer(
1249 CheckMemoryData*, check_value_data);
1250 assert_non_null(check);
1251 return memory_not_equal_display_error(
1252 cast_largest_integral_type_to_pointer(const char*, value),
1253 (const char*)check->memory,
1258 /* Add an event to check whether a parameter doesn't match an area of memory. */
1259 void _expect_not_memory(
1260 const char* const function, const char* const parameter,
1261 const char* const file, const int line, const void* const memory,
1262 const size_t size, const int count) {
1263 expect_memory_setup(function, parameter, file, line, memory, size,
1264 check_not_memory, count);
1268 /* CheckParameterValue callback that always returns 1. */
1269 static int check_any(const LargestIntegralType value,
1270 const LargestIntegralType check_value_data) {
1272 (void)check_value_data;
1277 /* Add an event to allow any value for a parameter. */
1279 const char* const function, const char* const parameter,
1280 const char* const file, const int line, const int count) {
1281 _expect_check(function, parameter, file, line, check_any, 0, NULL,
1286 void _check_expected(
1287 const char * const function_name, const char * const parameter_name,
1288 const char* file, const int line, const LargestIntegralType value) {
1290 const char* symbols[] = {function_name, parameter_name};
1291 const int rc = get_symbol_value(&global_function_parameter_map_head,
1292 symbols, 2, &result);
1294 CheckParameterEvent * const check = (CheckParameterEvent*)result;
1295 int check_succeeded;
1296 global_last_parameter_location = check->location;
1297 check_succeeded = check->check_value(value, check->check_value_data);
1301 if (!check_succeeded) {
1302 cm_print_error(SOURCE_LOCATION_FORMAT
1303 ": error: Check of parameter %s, function %s failed\n"
1304 SOURCE_LOCATION_FORMAT
1305 ": note: Expected parameter declared here\n",
1307 parameter_name, function_name,
1308 global_last_parameter_location.file,
1309 global_last_parameter_location.line);
1313 cm_print_error(SOURCE_LOCATION_FORMAT ": error: Could not get value "
1314 "to check parameter %s of function %s\n", file, line,
1315 parameter_name, function_name);
1316 if (source_location_is_set(&global_last_parameter_location)) {
1317 cm_print_error(SOURCE_LOCATION_FORMAT
1318 ": note: Previously declared parameter value was declared here\n",
1319 global_last_parameter_location.file,
1320 global_last_parameter_location.line);
1322 cm_print_error("There were no previously declared parameter values "
1323 "for this test.\n");
1330 /* Replacement for assert. */
1331 void mock_assert(const int result, const char* const expression,
1332 const char* const file, const int line) {
1334 if (global_expecting_assert) {
1335 global_last_failed_assert = expression;
1336 longjmp(global_expect_assert_env, result);
1338 cm_print_error("ASSERT: %s\n", expression);
1345 void _assert_true(const LargestIntegralType result,
1346 const char * const expression,
1347 const char * const file, const int line) {
1349 cm_print_error("%s\n", expression);
1354 void _assert_return_code(const LargestIntegralType result,
1356 const LargestIntegralType error,
1357 const char * const expression,
1358 const char * const file,
1361 LargestIntegralType valmax;
1372 valmax = 2147483647;
1376 if (rlen > sizeof(valmax)) {
1377 valmax = 2147483647;
1379 valmax = 9223372036854775807L;
1384 if (result > valmax - 1) {
1386 cm_print_error("%s < 0, errno(%" PRIu64 "): %s\n",
1387 expression, error, strerror((int)error));
1389 cm_print_error("%s < 0\n", expression);
1395 void _assert_int_equal(
1396 const LargestIntegralType a, const LargestIntegralType b,
1397 const char * const file, const int line) {
1398 if (!values_equal_display_error(a, b)) {
1404 void _assert_int_not_equal(
1405 const LargestIntegralType a, const LargestIntegralType b,
1406 const char * const file, const int line) {
1407 if (!values_not_equal_display_error(a, b)) {
1413 void _assert_string_equal(const char * const a, const char * const b,
1414 const char * const file, const int line) {
1415 if (!string_equal_display_error(a, b)) {
1421 void _assert_string_not_equal(const char * const a, const char * const b,
1422 const char *file, const int line) {
1423 if (!string_not_equal_display_error(a, b)) {
1429 void _assert_memory_equal(const void * const a, const void * const b,
1430 const size_t size, const char* const file,
1432 if (!memory_equal_display_error((const char*)a, (const char*)b, size)) {
1438 void _assert_memory_not_equal(const void * const a, const void * const b,
1439 const size_t size, const char* const file,
1441 if (!memory_not_equal_display_error((const char*)a, (const char*)b,
1448 void _assert_in_range(
1449 const LargestIntegralType value, const LargestIntegralType minimum,
1450 const LargestIntegralType maximum, const char* const file,
1452 if (!integer_in_range_display_error(value, minimum, maximum)) {
1457 void _assert_not_in_range(
1458 const LargestIntegralType value, const LargestIntegralType minimum,
1459 const LargestIntegralType maximum, const char* const file,
1461 if (!integer_not_in_range_display_error(value, minimum, maximum)) {
1466 void _assert_in_set(const LargestIntegralType value,
1467 const LargestIntegralType values[],
1468 const size_t number_of_values, const char* const file,
1470 CheckIntegerSet check_integer_set;
1471 check_integer_set.set = values;
1472 check_integer_set.size_of_set = number_of_values;
1473 if (!value_in_set_display_error(value, &check_integer_set, 0)) {
1478 void _assert_not_in_set(const LargestIntegralType value,
1479 const LargestIntegralType values[],
1480 const size_t number_of_values, const char* const file,
1482 CheckIntegerSet check_integer_set;
1483 check_integer_set.set = values;
1484 check_integer_set.size_of_set = number_of_values;
1485 if (!value_in_set_display_error(value, &check_integer_set, 1)) {
1491 /* Get the list of allocated blocks. */
1492 static ListNode* get_allocated_blocks_list() {
1493 /* If it initialized, initialize the list of allocated blocks. */
1494 if (!global_allocated_blocks.value) {
1495 list_initialize(&global_allocated_blocks);
1496 global_allocated_blocks.value = (void*)1;
1498 return &global_allocated_blocks;
1501 static void *libc_malloc(size_t size)
1504 return malloc(size);
1505 #define malloc test_malloc
1508 static void libc_free(void *ptr)
1512 #define free test_free
1515 static void *libc_realloc(void *ptr, size_t size)
1518 return realloc(ptr, size);
1519 #define realloc test_realloc
1522 static void vcm_print_error(const char* const format,
1523 va_list args) CMOCKA_PRINTF_ATTRIBUTE(1, 0);
1525 /* It's important to use the libc malloc and free here otherwise
1526 * the automatic free of leaked blocks can reap the error messages
1528 static void vcm_print_error(const char* const format, va_list args)
1535 len = vsnprintf(buffer, sizeof(buffer), format, args);
1541 if (cm_error_message == NULL) {
1542 /* CREATE MESSAGE */
1544 cm_error_message = libc_malloc(len + 1);
1545 if (cm_error_message == NULL) {
1550 /* APPEND MESSAGE */
1553 msg_len = strlen(cm_error_message);
1554 tmp = libc_realloc(cm_error_message, msg_len + len + 1);
1558 cm_error_message = tmp;
1561 if (((size_t)len) < sizeof(buffer)) {
1562 /* Use len + 1 to also copy '\0' */
1563 memcpy(cm_error_message + msg_len, buffer, len + 1);
1566 vsnprintf(cm_error_message + msg_len, len, format, ap);
1571 static void vcm_free_error(char *err_msg)
1576 /* Use the real malloc in this function. */
1578 void* _test_malloc(const size_t size, const char* file, const int line) {
1580 MallocBlockInfo *block_info;
1581 ListNode * const block_list = get_allocated_blocks_list();
1582 const size_t allocate_size = size + (MALLOC_GUARD_SIZE * 2) +
1583 sizeof(*block_info) + MALLOC_ALIGNMENT;
1584 char* const block = (char*)malloc(allocate_size);
1585 assert_non_null(block);
1587 /* Calculate the returned address. */
1588 ptr = (char*)(((size_t)block + MALLOC_GUARD_SIZE + sizeof(*block_info) +
1589 MALLOC_ALIGNMENT) & ~(MALLOC_ALIGNMENT - 1));
1591 /* Initialize the guard blocks. */
1592 memset(ptr - MALLOC_GUARD_SIZE, MALLOC_GUARD_PATTERN, MALLOC_GUARD_SIZE);
1593 memset(ptr + size, MALLOC_GUARD_PATTERN, MALLOC_GUARD_SIZE);
1594 memset(ptr, MALLOC_ALLOC_PATTERN, size);
1596 block_info = (MallocBlockInfo*)(ptr - (MALLOC_GUARD_SIZE +
1597 sizeof(*block_info)));
1598 set_source_location(&block_info->location, file, line);
1599 block_info->allocated_size = allocate_size;
1600 block_info->size = size;
1601 block_info->block = block;
1602 block_info->node.value = block_info;
1603 list_add(block_list, &block_info->node);
1606 #define malloc test_malloc
1609 void* _test_calloc(const size_t number_of_elements, const size_t size,
1610 const char* file, const int line) {
1611 void* const ptr = _test_malloc(number_of_elements * size, file, line);
1613 memset(ptr, 0, number_of_elements * size);
1619 /* Use the real free in this function. */
1621 void _test_free(void* const ptr, const char* file, const int line) {
1623 char *block = discard_const_p(char, ptr);
1624 MallocBlockInfo *block_info;
1630 _assert_true(cast_ptr_to_largest_integral_type(ptr), "ptr", file, line);
1631 block_info = (MallocBlockInfo*)(block - (MALLOC_GUARD_SIZE +
1632 sizeof(*block_info)));
1633 /* Check the guard blocks. */
1635 char *guards[2] = {block - MALLOC_GUARD_SIZE,
1636 block + block_info->size};
1637 for (i = 0; i < ARRAY_SIZE(guards); i++) {
1639 char * const guard = guards[i];
1640 for (j = 0; j < MALLOC_GUARD_SIZE; j++) {
1641 const char diff = guard[j] - MALLOC_GUARD_PATTERN;
1643 cm_print_error(SOURCE_LOCATION_FORMAT
1644 ": error: Guard block of %p size=%lu is corrupt\n"
1645 SOURCE_LOCATION_FORMAT ": note: allocated here at %p\n",
1647 ptr, (unsigned long)block_info->size,
1648 block_info->location.file, block_info->location.line,
1655 list_remove(&block_info->node, NULL, NULL);
1657 block = discard_const_p(char, block_info->block);
1658 memset(block, MALLOC_FREE_PATTERN, block_info->allocated_size);
1661 #define free test_free
1664 void *_test_realloc(void *ptr,
1669 MallocBlockInfo *block_info;
1671 size_t block_size = size;
1675 return _test_malloc(size, file, line);
1679 _test_free(ptr, file, line);
1683 block_info = (MallocBlockInfo*)(block - (MALLOC_GUARD_SIZE +
1684 sizeof(*block_info)));
1686 new = _test_malloc(size, file, line);
1691 if (block_info->size < size) {
1692 block_size = block_info->size;
1695 memcpy(new, ptr, block_size);
1697 /* Free previous memory */
1698 _test_free(ptr, file, line);
1702 #define realloc test_realloc
1704 /* Crudely checkpoint the current heap state. */
1705 static const ListNode* check_point_allocated_blocks() {
1706 return get_allocated_blocks_list()->prev;
1710 /* Display the blocks allocated after the specified check point. This
1711 * function returns the number of blocks displayed. */
1712 static int display_allocated_blocks(const ListNode * const check_point) {
1713 const ListNode * const head = get_allocated_blocks_list();
1714 const ListNode *node;
1715 int allocated_blocks = 0;
1716 assert_non_null(check_point);
1717 assert_non_null(check_point->next);
1719 for (node = check_point->next; node != head; node = node->next) {
1720 const MallocBlockInfo * const block_info =
1721 (const MallocBlockInfo*)node->value;
1722 assert_non_null(block_info);
1724 if (!allocated_blocks) {
1725 cm_print_error("Blocks allocated...\n");
1727 cm_print_error(SOURCE_LOCATION_FORMAT ": note: block %p allocated here\n",
1728 block_info->location.file,
1729 block_info->location.line,
1731 allocated_blocks ++;
1733 return allocated_blocks;
1737 /* Free all blocks allocated after the specified check point. */
1738 static void free_allocated_blocks(const ListNode * const check_point) {
1739 const ListNode * const head = get_allocated_blocks_list();
1740 const ListNode *node;
1741 assert_non_null(check_point);
1743 node = check_point->next;
1744 assert_non_null(node);
1746 while (node != head) {
1747 MallocBlockInfo * const block_info = (MallocBlockInfo*)node->value;
1749 free(discard_const_p(char, block_info) + sizeof(*block_info) + MALLOC_GUARD_SIZE);
1754 /* Fail if any any blocks are allocated after the specified check point. */
1755 static void fail_if_blocks_allocated(const ListNode * const check_point,
1756 const char * const test_name) {
1757 const int allocated_blocks = display_allocated_blocks(check_point);
1758 if (allocated_blocks) {
1759 free_allocated_blocks(check_point);
1760 cm_print_error("ERROR: %s leaked %d block(s)\n", test_name,
1767 void _fail(const char * const file, const int line) {
1768 cm_print_error(SOURCE_LOCATION_FORMAT ": error: Failure!\n", file, line);
1774 static void exception_handler(int sig) {
1775 #ifdef HAVE_STRSIGNAL
1776 cm_print_error("Test failed with exception: %s\n", strsignal(sig));
1778 cm_print_error("Test failed with exception: %d\n", sig);
1785 static LONG WINAPI exception_filter(EXCEPTION_POINTERS *exception_pointers) {
1786 EXCEPTION_RECORD * const exception_record =
1787 exception_pointers->ExceptionRecord;
1788 const DWORD code = exception_record->ExceptionCode;
1790 for (i = 0; i < ARRAY_SIZE(exception_codes); i++) {
1791 const ExceptionCodeInfo * const code_info = &exception_codes[i];
1792 if (code == code_info->code) {
1793 static int shown_debug_message = 0;
1795 cm_print_error("%s occurred at %p.\n", code_info->description,
1796 exception_record->ExceptionAddress);
1797 if (!shown_debug_message) {
1800 "To debug in Visual Studio...\n"
1801 "1. Select menu item File->Open Project\n"
1802 "2. Change 'Files of type' to 'Executable Files'\n"
1803 "3. Open this executable.\n"
1804 "4. Select menu item Debug->Start\n"
1806 "Alternatively, set the environment variable \n"
1807 "UNIT_TESTING_DEBUG to 1 and rebuild this executable, \n"
1808 "then click 'Debug' in the popup dialog box.\n"
1810 shown_debug_message = 1;
1813 return EXCEPTION_EXECUTE_HANDLER;
1816 return EXCEPTION_CONTINUE_SEARCH;
1818 #endif /* !_WIN32 */
1820 void cm_print_error(const char * const format, ...)
1823 va_start(args, format);
1824 if (cm_error_message_enabled) {
1825 vcm_print_error(format, args);
1827 vprint_error(format, args);
1832 /* Standard output and error print methods. */
1833 void vprint_message(const char* const format, va_list args) {
1835 vsnprintf(buffer, sizeof(buffer), format, args);
1836 printf("%s", buffer);
1839 OutputDebugString(buffer);
1844 void vprint_error(const char* const format, va_list args) {
1846 vsnprintf(buffer, sizeof(buffer), format, args);
1847 fprintf(stderr, "%s", buffer);
1850 OutputDebugString(buffer);
1855 void print_message(const char* const format, ...) {
1857 va_start(args, format);
1858 vprint_message(format, args);
1863 void print_error(const char* const format, ...) {
1865 va_start(args, format);
1866 vprint_error(format, args);
1871 static enum cm_message_output cm_get_output(void)
1873 enum cm_message_output output = global_msg_output;
1876 env = getenv("CMOCKA_MESSAGE_OUTPUT");
1878 if (strcasecmp(env, "STDOUT") == 0) {
1879 output = CM_OUTPUT_STDOUT;
1880 } else if (strcasecmp(env, "SUBUNIT") == 0) {
1881 output = CM_OUTPUT_SUBUNIT;
1882 } else if (strcasecmp(env, "TAP") == 0) {
1883 output = CM_OUTPUT_TAP;
1884 } else if (strcasecmp(env, "XML") == 0) {
1885 output = CM_OUTPUT_XML;
1892 enum cm_printf_type {
1894 PRINTF_TEST_SUCCESS,
1895 PRINTF_TEST_FAILURE,
1897 PRINTF_TEST_SKIPPED,
1900 static void cmprintf_group_finish_xml(const char *group_name,
1901 size_t total_executed,
1902 size_t total_failed,
1903 size_t total_errors,
1904 size_t total_skipped,
1905 double total_runtime,
1906 struct CMUnitTestState *cm_tests)
1909 int file_opened = 0;
1913 env = getenv("CMOCKA_XML_FILE");
1916 snprintf(buf, sizeof(buf), "%s", env);
1918 fp = fopen(buf, "r");
1920 fp = fopen(buf, "w");
1932 fprintf(fp, "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
1933 fprintf(fp, "<testsuites>\n");
1934 fprintf(fp, " <testsuite name=\"%s\" time=\"%.3f\" "
1935 "tests=\"%u\" failures=\"%u\" errors=\"%u\" skipped=\"%u\" >\n",
1937 total_runtime * 1000, /* miliseconds */
1938 (unsigned)total_executed,
1939 (unsigned)total_failed,
1940 (unsigned)total_errors,
1941 (unsigned)total_skipped);
1943 for (i = 0; i < total_executed; i++) {
1944 struct CMUnitTestState *cmtest = &cm_tests[i];
1946 fprintf(fp, " <testcase name=\"%s\" time=\"%.3f\" >\n",
1947 cmtest->test->name, cmtest->runtime * 1000);
1949 switch (cmtest->status) {
1951 case CM_TEST_FAILED:
1952 if (cmtest->error_message != NULL) {
1953 fprintf(fp, " <failure><![CDATA[%s]]></failure>\n",
1954 cmtest->error_message);
1956 fprintf(fp, " <failure message=\"Unknown error\" />\n");
1959 case CM_TEST_SKIPPED:
1960 fprintf(fp, " <skipped/>\n");
1963 case CM_TEST_PASSED:
1964 case CM_TEST_NOT_STARTED:
1968 fprintf(fp, " </testcase>\n");
1971 fprintf(fp, " </testsuite>\n");
1972 fprintf(fp, "</testsuites>\n");
1979 static void cmprintf_group_start_standard(const size_t num_tests)
1981 print_message("[==========] Running %u test(s).\n",
1982 (unsigned)num_tests);
1985 static void cmprintf_group_finish_standard(size_t total_executed,
1986 size_t total_passed,
1987 size_t total_failed,
1988 size_t total_errors,
1989 size_t total_skipped,
1990 struct CMUnitTestState *cm_tests)
1994 print_message("[==========] %u test(s) run.\n", (unsigned)total_executed);
1995 print_error("[ PASSED ] %u test(s).\n",
1996 (unsigned)(total_passed));
1998 if (total_skipped) {
1999 print_error("[ SKIPPED ] %"PRIdS " test(s), listed below:\n", total_skipped);
2000 for (i = 0; i < total_executed; i++) {
2001 struct CMUnitTestState *cmtest = &cm_tests[i];
2003 if (cmtest->status == CM_TEST_SKIPPED) {
2004 print_error("[ SKIPPED ] %s\n", cmtest->test->name);
2007 print_error("\n %u SKIPPED TEST(S)\n", (unsigned)(total_skipped));
2011 print_error("[ FAILED ] %"PRIdS " test(s), listed below:\n", total_failed);
2012 for (i = 0; i < total_executed; i++) {
2013 struct CMUnitTestState *cmtest = &cm_tests[i];
2015 if (cmtest->status == CM_TEST_FAILED) {
2016 print_error("[ FAILED ] %s\n", cmtest->test->name);
2019 print_error("\n %u FAILED TEST(S)\n",
2020 (unsigned)(total_failed + total_errors));
2024 static void cmprintf_standard(enum cm_printf_type type,
2025 const char *test_name,
2026 const char *error_message)
2029 case PRINTF_TEST_START:
2030 print_message("[ RUN ] %s\n", test_name);
2032 case PRINTF_TEST_SUCCESS:
2033 print_message("[ OK ] %s\n", test_name);
2035 case PRINTF_TEST_FAILURE:
2036 if (error_message != NULL) {
2037 print_error("%s\n", error_message);
2039 print_message("[ FAILED ] %s\n", test_name);
2041 case PRINTF_TEST_SKIPPED:
2042 print_message("[ SKIPPED ] %s\n", test_name);
2044 case PRINTF_TEST_ERROR:
2045 if (error_message != NULL) {
2046 print_error("%s\n", error_message);
2048 print_error("[ ERROR ] %s\n", test_name);
2053 static void cmprintf_group_start_tap(const size_t num_tests)
2055 print_message("\t1..%u\n", (unsigned)num_tests);
2058 static void cmprintf_group_finish_tap(const char *group_name,
2059 size_t total_executed,
2060 size_t total_passed,
2061 size_t total_skipped)
2063 const char *status = "not ok";
2064 if (total_passed + total_skipped == total_executed) {
2067 print_message("%s - %s\n", status, group_name);
2070 static void cmprintf_tap(enum cm_printf_type type,
2071 uint32_t test_number,
2072 const char *test_name,
2073 const char *error_message)
2076 case PRINTF_TEST_START:
2078 case PRINTF_TEST_SUCCESS:
2079 print_message("\tok %u - %s\n", (unsigned)test_number, test_name);
2081 case PRINTF_TEST_FAILURE:
2082 print_message("\tnot ok %u - %s\n", (unsigned)test_number, test_name);
2083 if (error_message != NULL) {
2087 msg = strdup(error_message);
2093 while (p[0] != '\0') {
2096 p = strchr(q, '\n');
2101 print_message("\t# %s\n", q);
2111 case PRINTF_TEST_SKIPPED:
2112 print_message("\tnot ok %u # SKIP %s\n", (unsigned)test_number, test_name);
2114 case PRINTF_TEST_ERROR:
2115 print_message("\tnot ok %u - %s %s\n",
2116 (unsigned)test_number, test_name, error_message);
2121 static void cmprintf_subunit(enum cm_printf_type type,
2122 const char *test_name,
2123 const char *error_message)
2126 case PRINTF_TEST_START:
2127 print_message("test: %s\n", test_name);
2129 case PRINTF_TEST_SUCCESS:
2130 print_message("success: %s\n", test_name);
2132 case PRINTF_TEST_FAILURE:
2133 print_message("failure: %s", test_name);
2134 if (error_message != NULL) {
2135 print_message(" [\n%s]\n", error_message);
2138 case PRINTF_TEST_SKIPPED:
2139 print_message("skip: %s\n", test_name);
2141 case PRINTF_TEST_ERROR:
2142 print_message("error: %s [ %s ]\n", test_name, error_message);
2147 static void cmprintf_group_start(const size_t num_tests)
2149 enum cm_message_output output;
2151 output = cm_get_output();
2154 case CM_OUTPUT_STDOUT:
2155 cmprintf_group_start_standard(num_tests);
2157 case CM_OUTPUT_SUBUNIT:
2160 cmprintf_group_start_tap(num_tests);
2167 static void cmprintf_group_finish(const char *group_name,
2168 size_t total_executed,
2169 size_t total_passed,
2170 size_t total_failed,
2171 size_t total_errors,
2172 size_t total_skipped,
2173 double total_runtime,
2174 struct CMUnitTestState *cm_tests)
2176 enum cm_message_output output;
2178 output = cm_get_output();
2181 case CM_OUTPUT_STDOUT:
2182 cmprintf_group_finish_standard(total_executed,
2189 case CM_OUTPUT_SUBUNIT:
2192 cmprintf_group_finish_tap(group_name, total_executed, total_passed, total_skipped);
2195 cmprintf_group_finish_xml(group_name,
2206 static void cmprintf(enum cm_printf_type type,
2208 const char *test_name,
2209 const char *error_message)
2211 enum cm_message_output output;
2213 output = cm_get_output();
2216 case CM_OUTPUT_STDOUT:
2217 cmprintf_standard(type, test_name, error_message);
2219 case CM_OUTPUT_SUBUNIT:
2220 cmprintf_subunit(type, test_name, error_message);
2223 cmprintf_tap(type, test_number, test_name, error_message);
2230 void cmocka_set_message_output(enum cm_message_output output)
2232 global_msg_output = output;
2235 /****************************************************************************
2237 ****************************************************************************/
2239 #ifdef HAVE_STRUCT_TIMESPEC
2240 static struct timespec cm_tspecdiff(struct timespec time1,
2241 struct timespec time0)
2243 struct timespec ret;
2247 if (time0.tv_nsec > time1.tv_nsec) {
2248 xsec = (int) ((time0.tv_nsec - time1.tv_nsec) / (1E9 + 1));
2249 time0.tv_nsec -= (long int) (1E9 * xsec);
2250 time0.tv_sec += xsec;
2253 if ((time1.tv_nsec - time0.tv_nsec) > 1E9) {
2254 xsec = (int) ((time1.tv_nsec - time0.tv_nsec) / 1E9);
2255 time0.tv_nsec += (long int) (1E9 * xsec);
2256 time0.tv_sec -= xsec;
2259 ret.tv_sec = time1.tv_sec - time0.tv_sec;
2260 ret.tv_nsec = time1.tv_nsec - time0.tv_nsec;
2262 if (time1.tv_sec < time0.tv_sec) {
2266 ret.tv_sec = ret.tv_sec * sign;
2271 static double cm_secdiff(struct timespec clock1, struct timespec clock0)
2274 struct timespec diff;
2276 diff = cm_tspecdiff(clock1, clock0);
2279 ret += (double) diff.tv_nsec / (double) 1E9;
2283 #endif /* HAVE_STRUCT_TIMESPEC */
2285 /****************************************************************************
2286 * CMOCKA TEST RUNNER
2287 ****************************************************************************/
2288 static int cmocka_run_one_test_or_fixture(const char *function_name,
2289 CMUnitTestFunction test_func,
2290 CMFixtureFunction setup_func,
2291 CMFixtureFunction teardown_func,
2292 void ** const volatile state,
2293 const void *const heap_check_point)
2295 const ListNode * const volatile check_point = (const ListNode*)
2296 (heap_check_point != NULL ?
2297 heap_check_point : check_point_allocated_blocks());
2298 int handle_exceptions = 1;
2299 void *current_state = NULL;
2302 /* FIXME check only one test or fixture is set */
2304 /* Detect if we should handle exceptions */
2306 handle_exceptions = !IsDebuggerPresent();
2308 #ifdef UNIT_TESTING_DEBUG
2309 handle_exceptions = 0;
2310 #endif /* UNIT_TESTING_DEBUG */
2313 if (handle_exceptions) {
2316 for (i = 0; i < ARRAY_SIZE(exception_signals); i++) {
2317 default_signal_functions[i] = signal(
2318 exception_signals[i], exception_handler);
2321 previous_exception_filter = SetUnhandledExceptionFilter(
2323 #endif /* !_WIN32 */
2326 /* Init the test structure */
2327 initialize_testing(function_name);
2329 global_running_test = 1;
2331 if (setjmp(global_run_test_env) == 0) {
2332 if (test_func != NULL) {
2333 test_func(state != NULL ? state : ¤t_state);
2335 fail_if_blocks_allocated(check_point, function_name);
2337 } else if (setup_func != NULL) {
2338 rc = setup_func(state != NULL ? state : ¤t_state);
2341 * For setup we can ignore any allocated blocks. We just need to
2342 * ensure they're deallocated on tear down.
2344 } else if (teardown_func != NULL) {
2345 rc = teardown_func(state != NULL ? state : ¤t_state);
2347 fail_if_blocks_allocated(check_point, function_name);
2351 fail_if_leftover_values(function_name);
2352 global_running_test = 0;
2355 global_running_test = 0;
2358 teardown_testing(function_name);
2360 if (handle_exceptions) {
2363 for (i = 0; i < ARRAY_SIZE(exception_signals); i++) {
2364 signal(exception_signals[i], default_signal_functions[i]);
2367 if (previous_exception_filter) {
2368 SetUnhandledExceptionFilter(previous_exception_filter);
2369 previous_exception_filter = NULL;
2371 #endif /* !_WIN32 */
2377 static int cmocka_run_group_fixture(const char *function_name,
2378 CMFixtureFunction setup_func,
2379 CMFixtureFunction teardown_func,
2381 const void *const heap_check_point)
2385 if (setup_func != NULL) {
2386 rc = cmocka_run_one_test_or_fixture(function_name,
2393 rc = cmocka_run_one_test_or_fixture(function_name,
2404 static int cmocka_run_one_tests(struct CMUnitTestState *test_state)
2406 #ifdef HAVE_STRUCT_TIMESPEC
2407 struct timespec start = {
2411 struct timespec finish = {
2419 if (test_state->test->setup_func != NULL) {
2420 /* Setup the memory check point, it will be evaluated on teardown */
2421 test_state->check_point = check_point_allocated_blocks();
2423 rc = cmocka_run_one_test_or_fixture(test_state->test->name,
2425 test_state->test->setup_func,
2428 test_state->check_point);
2430 test_state->status = CM_TEST_ERROR;
2431 cm_print_error("Test setup failed");
2436 #ifdef HAVE_STRUCT_TIMESPEC
2437 CMOCKA_CLOCK_GETTIME(CLOCK_REALTIME, &start);
2441 rc = cmocka_run_one_test_or_fixture(test_state->test->name,
2442 test_state->test->test_func,
2448 test_state->status = CM_TEST_PASSED;
2450 if (global_skip_test) {
2451 test_state->status = CM_TEST_SKIPPED;
2452 global_skip_test = 0; /* Do not skip the next test */
2454 test_state->status = CM_TEST_FAILED;
2460 test_state->runtime = 0.0;
2462 #ifdef HAVE_STRUCT_TIMESPEC
2463 CMOCKA_CLOCK_GETTIME(CLOCK_REALTIME, &finish);
2464 test_state->runtime = cm_secdiff(finish, start);
2468 if (rc == 0 && test_state->test->teardown_func != NULL) {
2469 rc = cmocka_run_one_test_or_fixture(test_state->test->name,
2472 test_state->test->teardown_func,
2474 test_state->check_point);
2476 test_state->status = CM_TEST_ERROR;
2477 cm_print_error("Test teardown failed");
2481 test_state->error_message = cm_error_message;
2482 cm_error_message = NULL;
2487 int _cmocka_run_group_tests(const char *group_name,
2488 const struct CMUnitTest * const tests,
2489 const size_t num_tests,
2490 CMFixtureFunction group_setup,
2491 CMFixtureFunction group_teardown)
2493 struct CMUnitTestState *cm_tests;
2494 const ListNode *group_check_point = check_point_allocated_blocks();
2495 void *group_state = NULL;
2496 size_t total_failed = 0;
2497 size_t total_passed = 0;
2498 size_t total_executed = 0;
2499 size_t total_errors = 0;
2500 size_t total_skipped = 0;
2501 double total_runtime = 0;
2505 /* Make sure LargestIntegralType is at least the size of a pointer. */
2506 assert_true(sizeof(LargestIntegralType) >= sizeof(void*));
2508 cm_tests = (struct CMUnitTestState *)libc_malloc(sizeof(struct CMUnitTestState) * num_tests);
2509 if (cm_tests == NULL) {
2513 cmprintf_group_start(num_tests);
2515 /* Setup cmocka test array */
2516 for (i = 0; i < num_tests; i++) {
2517 cm_tests[i] = (struct CMUnitTestState) {
2519 .status = CM_TEST_NOT_STARTED,
2526 /* Run group setup */
2527 if (group_setup != NULL) {
2528 rc = cmocka_run_group_fixture("cmocka_group_setup",
2537 for (i = 0; i < num_tests; i++) {
2538 struct CMUnitTestState *cmtest = &cm_tests[i];
2539 size_t test_number = i + 1;
2541 cmprintf(PRINTF_TEST_START, test_number, cmtest->test->name, NULL);
2543 if (group_state != NULL) {
2544 cm_tests[i].state = group_state;
2546 rc = cmocka_run_one_tests(cmtest);
2548 total_runtime += cmtest->runtime;
2550 switch (cmtest->status) {
2551 case CM_TEST_PASSED:
2552 cmprintf(PRINTF_TEST_SUCCESS,
2555 cmtest->error_message);
2558 case CM_TEST_SKIPPED:
2559 cmprintf(PRINTF_TEST_SKIPPED,
2562 cmtest->error_message);
2565 case CM_TEST_FAILED:
2566 cmprintf(PRINTF_TEST_FAILURE,
2569 cmtest->error_message);
2573 cmprintf(PRINTF_TEST_ERROR,
2576 "Internal cmocka error");
2581 cmprintf(PRINTF_TEST_ERROR,
2584 "Could not run the test - check test fixtures");
2589 cmprintf(PRINTF_TEST_ERROR, 0,
2590 group_name, "Group setup failed");
2594 /* Run group teardown */
2595 if (group_teardown != NULL) {
2596 rc = cmocka_run_group_fixture("cmocka_group_teardown",
2603 cmprintf_group_finish(group_name,
2612 for (i = 0; i < num_tests; i++) {
2613 vcm_free_error(discard_const_p(char, cm_tests[i].error_message));
2615 libc_free(cm_tests);
2616 fail_if_blocks_allocated(group_check_point, "cmocka_group_tests");
2618 return total_failed + total_errors;
2621 /****************************************************************************
2622 * DEPRECATED TEST RUNNER
2623 ****************************************************************************/
2626 const char * const function_name, const UnitTestFunction Function,
2627 void ** const volatile state, const UnitTestFunctionType function_type,
2628 const void* const heap_check_point) {
2629 const ListNode * const volatile check_point = (const ListNode*)
2631 heap_check_point : check_point_allocated_blocks());
2632 void *current_state = NULL;
2633 volatile int rc = 1;
2634 int handle_exceptions = 1;
2636 handle_exceptions = !IsDebuggerPresent();
2638 #ifdef UNIT_TESTING_DEBUG
2639 handle_exceptions = 0;
2640 #endif /* UNIT_TESTING_DEBUG */
2642 cm_error_message_enabled = 0;
2644 if (handle_exceptions) {
2647 for (i = 0; i < ARRAY_SIZE(exception_signals); i++) {
2648 default_signal_functions[i] = signal(
2649 exception_signals[i], exception_handler);
2652 previous_exception_filter = SetUnhandledExceptionFilter(
2654 #endif /* !_WIN32 */
2657 if (function_type == UNIT_TEST_FUNCTION_TYPE_TEST) {
2658 print_message("[ RUN ] %s\n", function_name);
2660 initialize_testing(function_name);
2661 global_running_test = 1;
2662 if (setjmp(global_run_test_env) == 0) {
2663 Function(state ? state : ¤t_state);
2664 fail_if_leftover_values(function_name);
2666 /* If this is a setup function then ignore any allocated blocks
2667 * only ensure they're deallocated on tear down. */
2668 if (function_type != UNIT_TEST_FUNCTION_TYPE_SETUP) {
2669 fail_if_blocks_allocated(check_point, function_name);
2672 global_running_test = 0;
2674 if (function_type == UNIT_TEST_FUNCTION_TYPE_TEST) {
2675 print_message("[ OK ] %s\n", function_name);
2679 global_running_test = 0;
2680 print_message("[ FAILED ] %s\n", function_name);
2682 teardown_testing(function_name);
2684 if (handle_exceptions) {
2687 for (i = 0; i < ARRAY_SIZE(exception_signals); i++) {
2688 signal(exception_signals[i], default_signal_functions[i]);
2691 if (previous_exception_filter) {
2692 SetUnhandledExceptionFilter(previous_exception_filter);
2693 previous_exception_filter = NULL;
2695 #endif /* !_WIN32 */
2702 int _run_tests(const UnitTest * const tests, const size_t number_of_tests) {
2703 /* Whether to execute the next test. */
2704 int run_next_test = 1;
2705 /* Whether the previous test failed. */
2706 int previous_test_failed = 0;
2707 /* Whether the previous setup failed. */
2708 int previous_setup_failed = 0;
2709 /* Check point of the heap state. */
2710 const ListNode * const check_point = check_point_allocated_blocks();
2711 /* Current test being executed. */
2712 size_t current_test = 0;
2713 /* Number of tests executed. */
2714 size_t tests_executed = 0;
2715 /* Number of failed tests. */
2716 size_t total_failed = 0;
2717 /* Number of setup functions. */
2719 /* Number of teardown functions. */
2720 size_t teardowns = 0;
2723 * A stack of test states. A state is pushed on the stack
2724 * when a test setup occurs and popped on tear down.
2726 TestState* test_states =
2727 (TestState*)malloc(number_of_tests * sizeof(*test_states));
2728 /* The number of test states which should be 0 at the end */
2729 long number_of_test_states = 0;
2730 /* Names of the tests that failed. */
2731 const char** failed_names = (const char**)malloc(number_of_tests *
2732 sizeof(*failed_names));
2733 void **current_state = NULL;
2735 /* Count setup and teardown functions */
2736 for (i = 0; i < number_of_tests; i++) {
2737 const UnitTest * const test = &tests[i];
2739 if (test->function_type == UNIT_TEST_FUNCTION_TYPE_SETUP) {
2743 if (test->function_type == UNIT_TEST_FUNCTION_TYPE_TEARDOWN) {
2748 print_message("[==========] Running %"PRIdS " test(s).\n",
2749 number_of_tests - setups - teardowns);
2751 /* Make sure LargestIntegralType is at least the size of a pointer. */
2752 assert_true(sizeof(LargestIntegralType) >= sizeof(void*));
2754 while (current_test < number_of_tests) {
2755 const ListNode *test_check_point = NULL;
2756 TestState *current_TestState;
2757 const UnitTest * const test = &tests[current_test++];
2758 if (!test->function) {
2762 switch (test->function_type) {
2763 case UNIT_TEST_FUNCTION_TYPE_TEST:
2764 if (! previous_setup_failed) {
2768 case UNIT_TEST_FUNCTION_TYPE_SETUP: {
2769 /* Checkpoint the heap before the setup. */
2770 current_TestState = &test_states[number_of_test_states++];
2771 current_TestState->check_point = check_point_allocated_blocks();
2772 test_check_point = current_TestState->check_point;
2773 current_state = ¤t_TestState->state;
2774 *current_state = NULL;
2778 case UNIT_TEST_FUNCTION_TYPE_TEARDOWN:
2779 /* Check the heap based on the last setup checkpoint. */
2780 assert_true(number_of_test_states);
2781 current_TestState = &test_states[--number_of_test_states];
2782 test_check_point = current_TestState->check_point;
2783 current_state = ¤t_TestState->state;
2786 print_error("Invalid unit test function type %d\n",
2787 test->function_type);
2792 if (run_next_test) {
2793 int failed = _run_test(test->name, test->function, current_state,
2794 test->function_type, test_check_point);
2796 failed_names[total_failed] = test->name;
2799 switch (test->function_type) {
2800 case UNIT_TEST_FUNCTION_TYPE_TEST:
2801 previous_test_failed = failed;
2802 total_failed += failed;
2806 case UNIT_TEST_FUNCTION_TYPE_SETUP:
2810 /* Skip forward until the next test or setup function. */
2812 previous_setup_failed = 1;
2814 previous_test_failed = 0;
2817 case UNIT_TEST_FUNCTION_TYPE_TEARDOWN:
2818 /* If this test failed. */
2819 if (failed && !previous_test_failed) {
2825 assert_null("BUG: shouldn't be here!");
2832 print_message("[==========] %"PRIdS " test(s) run.\n", tests_executed);
2833 print_error("[ PASSED ] %"PRIdS " test(s).\n", tests_executed - total_failed);
2835 if (total_failed > 0) {
2836 print_error("[ FAILED ] %"PRIdS " test(s), listed below:\n", total_failed);
2837 for (i = 0; i < total_failed; i++) {
2838 print_error("[ FAILED ] %s\n", failed_names[i]);
2841 print_error("\n %"PRIdS " FAILED TEST(S)\n", total_failed);
2844 if (number_of_test_states != 0) {
2845 print_error("[ ERROR ] Mismatched number of setup %"PRIdS " and "
2846 "teardown %"PRIdS " functions\n", setups, teardowns);
2847 total_failed = (size_t)-1;
2851 free((void*)failed_names);
2853 fail_if_blocks_allocated(check_point, "run_tests");
2854 return (int)total_failed;
2857 int _run_group_tests(const UnitTest * const tests, const size_t number_of_tests)
2859 UnitTestFunction setup = NULL;
2860 const char *setup_name;
2861 size_t num_setups = 0;
2862 UnitTestFunction teardown = NULL;
2863 const char *teardown_name;
2864 size_t num_teardowns = 0;
2865 size_t current_test = 0;
2868 /* Number of tests executed. */
2869 size_t tests_executed = 0;
2870 /* Number of failed tests. */
2871 size_t total_failed = 0;
2872 /* Check point of the heap state. */
2873 const ListNode * const check_point = check_point_allocated_blocks();
2874 const char** failed_names = (const char**)malloc(number_of_tests *
2875 sizeof(*failed_names));
2876 void **current_state = NULL;
2877 TestState group_state;
2879 /* Find setup and teardown function */
2880 for (i = 0; i < number_of_tests; i++) {
2881 const UnitTest * const test = &tests[i];
2883 if (test->function_type == UNIT_TEST_FUNCTION_TYPE_GROUP_SETUP) {
2884 if (setup == NULL) {
2885 setup = test->function;
2886 setup_name = test->name;
2889 print_error("[ ERROR ] More than one group setup function detected\n");
2894 if (test->function_type == UNIT_TEST_FUNCTION_TYPE_GROUP_TEARDOWN) {
2895 if (teardown == NULL) {
2896 teardown = test->function;
2897 teardown_name = test->name;
2900 print_error("[ ERROR ] More than one group teardown function detected\n");
2906 print_message("[==========] Running %"PRIdS " test(s).\n",
2907 number_of_tests - num_setups - num_teardowns);
2909 if (setup != NULL) {
2912 group_state.check_point = check_point_allocated_blocks();
2913 current_state = &group_state.state;
2914 *current_state = NULL;
2915 failed = _run_test(setup_name,
2918 UNIT_TEST_FUNCTION_TYPE_SETUP,
2919 group_state.check_point);
2921 failed_names[total_failed] = setup_name;
2924 total_failed += failed;
2928 while (current_test < number_of_tests) {
2930 const UnitTest * const test = &tests[current_test++];
2931 if (test->function == NULL) {
2935 switch (test->function_type) {
2936 case UNIT_TEST_FUNCTION_TYPE_TEST:
2939 case UNIT_TEST_FUNCTION_TYPE_SETUP:
2940 case UNIT_TEST_FUNCTION_TYPE_TEARDOWN:
2941 case UNIT_TEST_FUNCTION_TYPE_GROUP_SETUP:
2942 case UNIT_TEST_FUNCTION_TYPE_GROUP_TEARDOWN:
2945 print_error("Invalid unit test function type %d\n",
2946 test->function_type);
2953 failed = _run_test(test->name,
2956 test->function_type,
2959 failed_names[total_failed] = test->name;
2962 total_failed += failed;
2967 if (teardown != NULL) {
2970 failed = _run_test(teardown_name,
2973 UNIT_TEST_FUNCTION_TYPE_GROUP_TEARDOWN,
2974 group_state.check_point);
2976 failed_names[total_failed] = teardown_name;
2979 total_failed += failed;
2983 print_message("[==========] %"PRIdS " test(s) run.\n", tests_executed);
2984 print_error("[ PASSED ] %"PRIdS " test(s).\n", tests_executed - total_failed);
2987 print_error("[ FAILED ] %"PRIdS " test(s), listed below:\n", total_failed);
2988 for (i = 0; i < total_failed; i++) {
2989 print_error("[ FAILED ] %s\n", failed_names[i]);
2992 print_error("\n %"PRIdS " FAILED TEST(S)\n", total_failed);
2995 free((void*)failed_names);
2996 fail_if_blocks_allocated(check_point, "run_group_tests");
2998 return (int)total_failed;