重构代码的架构设计,增加测试单元,提高代码可靠性

This commit is contained in:
2026-03-23 20:40:04 +08:00
parent c2ce221691
commit a4bf0962b2
31 changed files with 2084 additions and 703 deletions

66
tests/test_common.h Normal file
View File

@@ -0,0 +1,66 @@
/* 统一测试辅助头:
* - 提供轻量断言宏,失败时打印上下文并返回 1 终止当前测试程序
* - 所有测试文件可直接 include 本头,减少重复样板代码
*/
#ifndef DTU_TEST_COMMON_H
#define DTU_TEST_COMMON_H
/* 标准库依赖:
* - stdio.h : fprintf
* - stdlib.h : 通用工具(当前宏未直接使用,预留)
* - string.h : strcmp
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* 断言:表达式为真
* 失败输出:失败表达式 + 文件 + 行号
* 失败返回1约定 main 返回非 0 表示测试失败)
*/
#define ASSERT_TRUE(expr) \
do { \
if (!(expr)) { \
fprintf(stderr, "ASSERT_TRUE failed: %s (%s:%d)\n", #expr, __FILE__,\
__LINE__); \
return 1; \
} \
} while (0)
/* 断言:两个整数值相等(按 int 比较) */
#define ASSERT_EQ_INT(expected, actual) \
do { \
int _exp = (int)(expected); \
int _act = (int)(actual); \
if (_exp != _act) { \
fprintf(stderr, \
"ASSERT_EQ_INT failed: expected=%d actual=%d (%s:%d)\n", \
_exp, _act, __FILE__, __LINE__); \
return 1; \
} \
} while (0)
/* 断言:两个无符号 32 位值相等(按 unsigned int 比较) */
#define ASSERT_EQ_U32(expected, actual) \
do { \
unsigned int _exp = (unsigned int)(expected); \
unsigned int _act = (unsigned int)(actual); \
if (_exp != _act) { \
fprintf(stderr, \
"ASSERT_EQ_U32 failed: expected=%u actual=%u (%s:%d)\n", \
_exp, _act, __FILE__, __LINE__); \
return 1; \
} \
} while (0)
/* 断言:两个 C 字符串内容相等(区分大小写) */
#define ASSERT_STREQ(expected, actual) \
do { \
if (strcmp((expected), (actual)) != 0) { \
fprintf(stderr, "ASSERT_STREQ failed: expected=\"%s\" actual=\"%s\" (%s:%d)\n", \
(expected), (actual), __FILE__, __LINE__); \
return 1; \
} \
} while (0)
#endif