AI 自动生成测试用例
This commit is contained in:
parent
fa2a0dee39
commit
5bd31d606d
|
|
@ -0,0 +1,81 @@
|
||||||
|
#include "gtest/gtest.h"
|
||||||
|
#include "src/errors.cpp"
|
||||||
|
#include <iostream>
|
||||||
|
#include <csignal>
|
||||||
|
#include <csetjmp>
|
||||||
|
|
||||||
|
// 用于捕获信号(如SIGSEGV)的跳转点
|
||||||
|
static jmp_buf jump_buffer;
|
||||||
|
|
||||||
|
// 信号处理函数
|
||||||
|
void signal_handler(int sig) {
|
||||||
|
(void)sig; // 抑制未使用参数的警告
|
||||||
|
longjmp(jump_buffer, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 测试空指针解引用
|
||||||
|
TEST(ErrorsTest, TestNullPointer) {
|
||||||
|
// 安装信号处理程序以捕获段错误
|
||||||
|
struct sigaction sa;
|
||||||
|
struct sigaction old_sa;
|
||||||
|
sa.sa_handler = signal_handler;
|
||||||
|
sigemptyset(&sa.sa_mask);
|
||||||
|
sa.sa_flags = 0;
|
||||||
|
sigaction(SIGSEGV, &sa, &old_sa);
|
||||||
|
|
||||||
|
// 设置跳转点,如果发生段错误,将跳转回此处
|
||||||
|
if (setjmp(jump_buffer) == 0) {
|
||||||
|
// 尝试调用会解引用空指针的函数
|
||||||
|
test_null_pointer();
|
||||||
|
// 如果执行到这里,说明没有触发段错误,测试失败
|
||||||
|
FAIL() << "Expected segmentation fault from null pointer dereference, but none occurred.";
|
||||||
|
} else {
|
||||||
|
// 成功捕获到段错误,测试通过
|
||||||
|
SUCCEED();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 恢复原来的信号处理程序
|
||||||
|
sigaction(SIGSEGV, &old_sa, nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 测试数组越界访问
|
||||||
|
TEST(ErrorsTest, TestArrayOutOfBounds) {
|
||||||
|
// 安装信号处理程序以捕获段错误
|
||||||
|
struct sigaction sa;
|
||||||
|
struct sigaction old_sa;
|
||||||
|
sa.sa_handler = signal_handler;
|
||||||
|
sigemptyset(&sa.sa_mask);
|
||||||
|
sa.sa_flags = 0;
|
||||||
|
sigaction(SIGSEGV, &sa, &old_sa);
|
||||||
|
|
||||||
|
// 设置跳转点,如果发生段错误,将跳转回此处
|
||||||
|
if (setjmp(jump_buffer) == 0) {
|
||||||
|
// 尝试调用会进行数组越界访问的函数
|
||||||
|
test_array_out_of_bounds();
|
||||||
|
// 如果执行到这里,说明没有触发段错误,测试失败
|
||||||
|
FAIL() << "Expected segmentation fault from array out-of-bounds access, but none occurred.";
|
||||||
|
} else {
|
||||||
|
// 成功捕获到段错误,测试通过
|
||||||
|
SUCCEED();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 恢复原来的信号处理程序
|
||||||
|
sigaction(SIGSEGV, &old_sa, nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 测试使用未初始化变量
|
||||||
|
// 注意:未初始化变量的行为是未定义的,可能不会导致崩溃。
|
||||||
|
// 此测试旨在验证函数可以无崩溃地执行(尽管逻辑错误)。
|
||||||
|
TEST(ErrorsTest, TestUninitializedVar) {
|
||||||
|
// 由于使用未初始化变量的行为是未定义的,
|
||||||
|
// 我们主要测试函数调用不会导致程序崩溃。
|
||||||
|
// 它可能打印垃圾值或什么都不做。
|
||||||
|
EXPECT_NO_FATAL_FAILURE(test_uninitialized_var());
|
||||||
|
// 注意:我们无法可靠地预测或测试其输出,因为 `val` 的值是未定义的。
|
||||||
|
}
|
||||||
|
|
||||||
|
// 主函数(如果单独编译测试文件则需要)
|
||||||
|
int main(int argc, char **argv) {
|
||||||
|
::testing::InitGoogleTest(&argc, argv);
|
||||||
|
return RUN_ALL_TESTS();
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue