New macro TEST_ASSERT_ERRNO

Show errno if a test assertion fails.

Signed-off-by: Gilles Peskine <[email protected]>
This commit is contained in:
Gilles Peskine
2026-02-17 17:21:20 +01:00
parent 8ed11c99fe
commit f41a9f6056
3 changed files with 54 additions and 0 deletions
+13
View File
@@ -240,6 +240,19 @@ void mbedtls_test_platform_teardown(void);
*/
void mbedtls_test_fail(const char *test, int line_no, const char *filename);
/**
* \brief Record the current test case as a failure
* and show the value of errno.
*
* This function is usually called via #TEST_ASSERT_ERRNO.
*
* \param test Description of the failure or assertion that failed. This
* MUST be a string literal.
* \param line_no Line number where the failure originated.
* \param filename Filename where the failure originated.
*/
void mbedtls_test_fail_errno(const char *test, int line_no, const char *filename);
/**
* \brief Record the current test case as skipped.
*
+15
View File
@@ -54,6 +54,21 @@
} \
} while (0)
/** \brief Evaluate an integer expression. If the value is 0 (i.e. false),
* mark the test case as failed and display errno.
*
* This is intended for functions that follow the Unix API convention of
* returning a particular value (often -1) and setting errno on failure,
* e.g. `TEST_ASSERT_ERRNO(open(...) != -1)`.
*/
#define TEST_ASSERT_ERRNO(expr) \
do { \
if (!(expr)) { \
mbedtls_test_fail_errno(#expr, __LINE__, __FILE__); \
goto exit; \
} \
} while (0)
/** This macro asserts fails the test with given output message.
*
* \param MESSAGE The message to be outputed on assertion
+26
View File
@@ -6,6 +6,7 @@
#include <test/constant_flow.h>
#include <test/helpers.h>
#include <test/macros.h>
#include <errno.h>
#include <string.h>
#if defined(MBEDTLS_PSA_INJECT_ENTROPY)
@@ -571,6 +572,31 @@ int mbedtls_test_le_s(const char *test, int line_no, const char *filename,
return 0;
}
void mbedtls_test_fail_errno(const char *test,
int line_no, const char *filename)
{
#ifdef MBEDTLS_THREADING_C
mbedtls_mutex_lock(&mbedtls_test_info_mutex);
#endif /* MBEDTLS_THREADING_C */
/* Don't use accessor, we already hold mutex. */
if (mbedtls_test_info.result != MBEDTLS_TEST_RESULT_FAILED) {
/* If we've already recorded the test as having failed then don't
* overwrite any previous information about the failure. */
char buf[MBEDTLS_TEST_LINE_LENGTH];
mbedtls_test_fail_internal(test, line_no, filename);
(void) mbedtls_snprintf(buf, sizeof(buf),
"errno = %d (%s)",
errno, strerror(errno));
mbedtls_test_set_line1_internal(buf);
}
#ifdef MBEDTLS_THREADING_C
mbedtls_mutex_unlock(&mbedtls_test_info_mutex);
#endif /* MBEDTLS_THREADING_C */
}
int mbedtls_test_unhexify(unsigned char *obuf,
size_t obufmax,
const char *ibuf,