From 5f45bd2baba17c092f76cb9878e439ff93c7d8f6 Mon Sep 17 00:00:00 2001 From: Gilles Peskine Date: Mon, 31 May 2021 15:40:31 +0200 Subject: [PATCH] New macros TEST_EQUAL, ASSERT_ALLOC, ASSERT_ALLOC_WEAK Backports some test helper macros added after 2.16. This will facilitate backporting new test code. Signed-off-by: Gilles Peskine --- tests/suites/helpers.function | 60 +++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/tests/suites/helpers.function b/tests/suites/helpers.function index ceac6703ff..ae207fd042 100644 --- a/tests/suites/helpers.function +++ b/tests/suites/helpers.function @@ -160,6 +160,66 @@ typedef enum } \ } while( 0 ) +/** Evaluate two expressions and fail the test case if they have different + * values. + * + * \param expr1 An expression to evaluate. + * \param expr2 The expected value of \p expr1. This can be any + * expression, but it is typically a constant. + */ +#define TEST_EQUAL( expr1, expr2 ) \ + TEST_ASSERT( ( expr1 ) == ( expr2 ) ) + +/** Allocate memory dynamically and fail the test case if this fails. + * The allocated memory will be filled with zeros. + * + * You must set \p pointer to \c NULL before calling this macro and + * put `mbedtls_free( pointer )` in the test's cleanup code. + * + * If \p length is zero, the resulting \p pointer will be \c NULL. + * This is usually what we want in tests since API functions are + * supposed to accept null pointers when a buffer size is zero. + * + * This macro expands to an instruction, not an expression. + * It may jump to the \c exit label. + * + * \param pointer An lvalue where the address of the allocated buffer + * will be stored. + * This expression may be evaluated multiple times. + * \param length Number of elements to allocate. + * This expression may be evaluated multiple times. + * + */ +#define ASSERT_ALLOC( pointer, length ) \ + do \ + { \ + TEST_ASSERT( ( pointer ) == NULL ); \ + if( ( length ) != 0 ) \ + { \ + ( pointer ) = mbedtls_calloc( sizeof( *( pointer ) ), \ + ( length ) ); \ + TEST_ASSERT( ( pointer ) != NULL ); \ + } \ + } \ + while( 0 ) + +/** Allocate memory dynamically. If the allocation fails, skip the test case. + * + * This macro behaves like #ASSERT_ALLOC, except that if the allocation + * fails, it marks the test as skipped rather than failed. + */ +#define ASSERT_ALLOC_WEAK( pointer, length ) \ + do \ + { \ + TEST_ASSERT( ( pointer ) == NULL ); \ + if( ( length ) != 0 ) \ + { \ + ( pointer ) = mbedtls_calloc( sizeof( *( pointer ) ), \ + ( length ) ); \ + TEST_ASSUME( ( pointer ) != NULL ); \ + } \ + } \ + while( 0 ) /** Compare two buffers and fail the test case if they differ. * * This macro expands to an instruction, not an expression.