blob: 7ec983dab62b9c524f14fb804708e75ed21e0dda [file] [log] [blame]
rjw1f884582022-01-06 17:20:42 +08001/*
2 * Copyright (c) 2013, Google, Inc. All rights reserved
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files
6 * (the "Software"), to deal in the Software without restriction,
7 * including without limitation the rights to use, copy, modify, merge,
8 * publish, distribute, sublicense, and/or sell copies of the Software,
9 * and to permit persons to whom the Software is furnished to do so,
10 * subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
18 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
19 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
20 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
21 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 */
23/*
24 * Functions for unit tests. See lib/unittest/include/unittest.h for usage.
25 */
26#include <unittest.h>
27#include <debug.h>
28#include <stdbool.h>
29#include <string.h>
30#include <stdio.h>
31#include <stddef.h>
32#include <stdint.h>
33
34/**
35 * \brief Default function to dump unit test results
36 *
37 * \param[in] line is the buffer to dump
38 * \param[in] len is the length of the buffer to dump
39 * \param[in] arg can be any kind of arguments needed to dump the values
40 */
41static void default_printf (const char *line, int len, void *arg)
42{
43 printf (line);
44}
45
46// Default output function is the printf
47static test_output_func out_func = default_printf;
48// Buffer the argument to be sent to the output function
49static void *out_func_arg = NULL;
50
51/**
52 * \brief Function called to dump results
53 *
54 * This function will call the out_func callback
55 */
56void unittest_printf (const char *format, ...)
57{
58 static char print_buffer[PRINT_BUFFER_SIZE];
59
60 va_list argp;
61 va_start (argp, format);
62
63 if (out_func != NULL) {
64 // Format the string
65 vsnprintf(print_buffer, PRINT_BUFFER_SIZE, format, argp);
66 out_func (print_buffer, PRINT_BUFFER_SIZE, out_func_arg);
67 }
68
69 va_end (argp);
70}
71
72bool expect_bytes_eq(const uint8_t *expected, const uint8_t *actual, size_t len,
73 const char *msg)
74{
75 if (memcmp(expected, actual, len)) {
76 printf("%s. expected\n", msg);
77 hexdump8(expected, len);
78 printf("actual\n");
79 hexdump8(actual, len);
80 return false;
81 }
82 return true;
83}
84
85void unittest_set_output_function (test_output_func fun, void *arg)
86{
87 out_func = fun;
88 out_func_arg = arg;
89}