package.path = './temp/opt/bmc/lualib/?.lua;' .. package.path
io.stdout:setvbuf("no")
io.stderr:setvbuf("no")
local function log_both(msg)
io.stdout:write(msg)
io.stdout:write("\n")
io.stderr:write(msg)
io.stderr:write("\n")
end
local function log_both_raw(msg)
if not msg or msg == "" then return end
io.stdout:write(msg)
io.stderr:write(msg)
end
local function setup_library_path()
local pwd_handle = io.popen("pwd")
local current_dir = pwd_handle:read("*line")
pwd_handle:close()
local lib_dirs = {}
local search_cmd = string.format(
"find %s/temp/root/.conan2/p/b %s/builddir -name 'libmcpp.so' -type f 2>/dev/null | head -1",
current_dir, current_dir)
local handle = io.popen(search_cmd)
if handle then
local lib_path = handle:read("*line")
handle:close()
if lib_path then
local lib_dir = lib_path:match("(.*/)")
table.insert(lib_dirs, lib_dir)
end
end
table.insert(lib_dirs, current_dir .. "/temp/usr/lib64")
table.insert(lib_dirs, current_dir .. "/builddir/usr/lib64")
table.insert(lib_dirs, current_dir .. "/temp/opt/bmc/drivers")
table.insert(lib_dirs, current_dir .. "/builddir/opt/bmc/drivers")
table.insert(lib_dirs, current_dir .. "/opt/bmc/drivers")
local conan_lib_search = string.format(
"find %s/temp/root/.conan2/p/b -type d -name lib64 2>/dev/null",
current_dir)
local conan_handle = io.popen(conan_lib_search)
if conan_handle then
for line in conan_handle:lines() do
if line ~= "" then table.insert(lib_dirs, line) end
end
conan_handle:close()
end
local current_ld_path = os.getenv("LD_LIBRARY_PATH") or ""
for _, dir in ipairs(lib_dirs) do
if current_ld_path == "" then
current_ld_path = dir
else
current_ld_path = dir .. ":" .. current_ld_path
end
end
current_ld_path = current_ld_path:gsub(";", ":")
current_ld_path = current_ld_path:gsub(":+", ":")
current_ld_path = current_ld_path:gsub("^:+", ""):gsub(":+$", "")
return current_ld_path
end
local lu = require("luaunit")
TestComponentDrivers = {}
function TestComponentDrivers:setupClass() end
function TestComponentDrivers:teardownClass() end
local gtest_filter_map = {}
local excluded_executables = {
libmcpp_test = true,
}
if os.getenv("INCLUDE_HANG_TESTS") ~= "1" then
local hang_tests = {
"test_hi1822_fc",
"test_hisi_interface",
"test_mellanox_interface",
"test_nvidia_interface",
"test_sfx00ht_abi",
"test_vastai_interface",
"test_vg1000_abi",
"test_wangxun_interface",
"test_i2c_mux",
"test_ina_abi",
"test_lm75_abi",
"test_pca9545",
"test_nvme_interface",
"test_powermeter_abi",
"test_rp1000_abi",
"test_samsung_nvme_interface",
"test_samsung_nvme_pcie4",
"test_scanner",
"test_scanner_abi",
"test_smc_abi",
"test_pca9555_abi",
}
for _, t in ipairs(hang_tests) do excluded_executables[t] = true end
end
if os.getenv("INCLUDE_SLOW_TESTS") ~= "1" then
local slow_tests = {
"test_emulex_port",
"test_emulex_card",
"test_cx6_port",
"mctp_class_test",
"test_cx6_card",
"test_pcie_gpu_card_interface",
"test_std_smbus",
}
for _, t in ipairs(slow_tests) do excluded_executables[t] = true end
end
local function discover_test_executables()
local found = {}
local seen = {}
local search_configs = {
{dir = "temp/bin", maxdepth = "-maxdepth 1"},
{dir = "builddir/tests", maxdepth = ""},
}
for _, cfg in ipairs(search_configs) do
local cmd = string.format(
"find %s %s -type f -executable ! -name '*.so' ! -name '*.a' ! -name '*.o' 2>/dev/null | sort",
cfg.dir, cfg.maxdepth)
local handle = io.popen(cmd)
if handle then
for line in handle:lines() do
local name = line:match("([^/]+)$")
if name and not seen[name] and not excluded_executables[name] then
seen[name] = true
table.insert(found, {name = name, path = line})
end
end
handle:close()
end
if #found > 0 then break end
end
return found
end
local function ensure_shm_lock_file()
local lock_path = "/dev/shm/init_shm.lock"
local f = io.open(lock_path, "r")
if f then
f:close()
return
end
os.execute("touch " .. lock_path .. " && chmod 666 " .. lock_path)
io.stdout:write("已创建 harbor 锁文件: " .. lock_path .. "\n")
end
local function setup_driver_symlink()
local candidates = {
"builddir/opt/bmc/drivers",
"temp/opt/bmc/drivers",
}
local check = io.popen("test -d ./opt/bmc/drivers && echo yes 2>/dev/null")
if check then
local result = check:read("*line")
check:close()
if result == "yes" then return end
end
for _, candidate in ipairs(candidates) do
local f = io.popen("test -d " .. candidate .. " && echo yes 2>/dev/null")
if f then
local result = f:read("*line")
f:close()
if result == "yes" then
os.execute("mkdir -p ./opt/bmc")
os.execute("ln -sfn $(cd " .. candidate .. " && pwd) ./opt/bmc/drivers")
io.stdout:write(string.format(
"已创建驱动软链接: ./opt/bmc/drivers -> %s\n", candidate))
return
end
end
end
log_both("警告: 未找到 opt/bmc/drivers 目录,ABI 测试可能无法加载驱动")
end
local WORKER_SCRIPT = [=[#!/bin/bash
# 并行 worker:一次调用跑一个测试,所有 IO 走 $WORKER_TMPDIR 下的 per-test 文件
set -u
IFS=$'\t' read -r name exe filter <<< "$1"
log="$WORKER_TMPDIR/$name.log"
rc_file="$WORKER_TMPDIR/$name.rc"
crash_file="$WORKER_TMPDIR/$name.crash"
_setsid=""
if command -v setsid >/dev/null 2>&1; then
_setsid="setsid --wait"
fi
# setsid --wait:把测试隔离到独立会话,防止崩溃信号传播到父进程组;
# timeout:单测硬上限;eval:允许 filter 含 --gtest_filter=xxx 等完整参数串
eval $_setsid timeout --kill-after=10s "$TEST_TIMEOUT_SEC" env LD_LIBRARY_PATH="'$TEST_LD_PATH'" \
'"$exe"' "$filter" > "$log" 2>&1
rc=$?
# 崩溃判定:非零退出 且 输出既无 [ PASSED ] 也无 N FAILED TEST
if [ "$rc" -ne 0 ] && \
! grep -q '^\[ PASSED \]' "$log" && \
! grep -qE '[0-9]+ FAILED TEST' "$log"; then
: > "$crash_file"
cat > "$log" <<EOF
[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from CrashGuard
[ RUN ] CrashGuard.${name}_skipped
[ OK ] CrashGuard.${name}_skipped (0 ms)
[----------] 1 test from CrashGuard (0 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test suite ran. (0 ms total)
[ PASSED ] 1 test.
EOF
fi
echo "$rc" > "$rc_file"
]=]
local function make_tmpdir()
local h = io.popen("mktemp -d")
local d = h:read("*l")
h:close()
return d
end
local function write_file(path, content, mode)
local f = assert(io.open(path, mode or "w"))
f:write(content)
f:close()
end
local function read_file(path)
local f = io.open(path, "r")
if not f then return nil end
local c = f:read("*a")
f:close()
return c
end
local function run_tests_parallel(tests, timeout_sec, ld_path, num_jobs)
local tmpdir = make_tmpdir()
if not tmpdir or tmpdir == "" then
error("mktemp -d 失败,无法创建并行 worker 临时目录")
end
local tasks = {}
for _, t in ipairs(tests) do
table.insert(tasks,
string.format("%s\t%s\t%s", t.name, t.path, t.filter or ""))
end
local tasks_file = tmpdir .. "/tasks.tsv"
write_file(tasks_file, table.concat(tasks, "\0") .. "\0")
local worker = tmpdir .. "/worker.sh"
write_file(worker, WORKER_SCRIPT)
os.execute("chmod +x " .. worker)
local cmd = string.format(
"WORKER_TMPDIR='%s' TEST_TIMEOUT_SEC='%s' TEST_LD_PATH='%s' " ..
"xargs -a '%s' -0 -n 1 -P %d '%s'",
tmpdir, timeout_sec, ld_path,
tasks_file, num_jobs, worker)
io.stderr:write("[DEBUG] cmd length=" .. #cmd .. "\n")
io.stderr:write("[DEBUG] cmd contains newline=" .. tostring(cmd:find("\n") ~= nil) .. "\n")
io.stderr:write("[DEBUG] cmd first 200 chars=" .. cmd:sub(1, 200) .. "\n")
os.execute(cmd)
local results = {}
for _, t in ipairs(tests) do
local rc = tonumber((read_file(tmpdir .. "/" .. t.name .. ".rc") or "1"):match("%d+")) or 1
local output = read_file(tmpdir .. "/" .. t.name .. ".log") or ""
local crashed = read_file(tmpdir .. "/" .. t.name .. ".crash") ~= nil
results[t.name] = {rc = rc, output = output, crashed = crashed}
end
os.execute("rm -rf '" .. tmpdir .. "'")
return results
end
local function parse_gtest_counts(output)
if not output or output == "" then return 0, 0 end
local passed, failed = 0, 0
for n in output:gmatch("%[ PASSED %]%s+(%d+)%s+tests?%.") do
passed = passed + (tonumber(n) or 0)
end
local cleaned = output:gsub("(%d+)%s+FAILED TEST SUITES?", "")
for n in cleaned:gmatch("(%d+)%s+FAILED TESTS?") do
failed = failed + (tonumber(n) or 0)
end
return passed, failed
end
local aggregate_successes = 0
local aggregate_failures = 0
local function compute_test_jobs()
local env = os.getenv("TEST_JOBS")
if env and tonumber(env) and tonumber(env) > 0 then
return math.floor(tonumber(env))
end
return 1
end
function TestComponentDrivers:test_cpp()
log_both("\n========== 开始 C++ 单元测试 ==========")
local new_ld_path = setup_library_path()
log_both("LD_LIBRARY_PATH: " .. new_ld_path)
ensure_shm_lock_file()
setup_driver_symlink()
local timeout_sec = os.getenv("TEST_TIMEOUT") or "120"
local found = discover_test_executables()
if #found == 0 then
log_both("警告: 未找到 C++ 测试可执行文件,跳过 C++ 测试")
return
end
local tasks = {}
for _, exe in ipairs(found) do
local gtest_filter = gtest_filter_map[exe.name]
local filter_str = ""
if gtest_filter then
filter_str = "--gtest_filter=" .. gtest_filter
end
table.insert(tasks,
{name = exe.name, path = exe.path, filter = filter_str})
end
local num_jobs = compute_test_jobs()
local mode_desc = (num_jobs == 1) and "串行" or string.format("%d 并发", num_jobs)
log_both(string.format("找到 %d 个测试可执行文件", #found))
io.stdout:write(string.format("(%s执行,timeout=%ss,TEST_JOBS 可覆盖)\n",
mode_desc, timeout_sec))
io.stdout:flush()
local t0 = os.time()
local results = run_tests_parallel(tasks, timeout_sec, new_ld_path, num_jobs)
local t1 = os.time()
io.stdout:write(string.format("(%s执行完成,wall-time=%ds)\n", mode_desc, t1 - t0))
io.stdout:flush()
local total_failed = 0
local failed_names = {}
local local_successes = 0
local local_failures = 0
for idx, exe in ipairs(found) do
local r = results[exe.name] or {rc = 1, output = "(missing result)", crashed = false}
local gtest_filter = gtest_filter_map[exe.name]
log_both(string.format("\n--- [%d/%d] 运行测试: %s ---", idx, #found, exe.name))
if gtest_filter then
log_both(string.format("应用 gtest 过滤: %s", gtest_filter))
end
log_both(string.format("执行命令: timeout %s env LD_LIBRARY_PATH='...' %s%s",
timeout_sec, exe.path,
gtest_filter and (" --gtest_filter=" .. gtest_filter) or ""))
local output = r.output or ""
local is_shm_issue = r.rc ~= 0
and (output:find("open shm failed") ~= nil
or output:find("start service failed") ~= nil
or output:find("boost::interprocess::bad_alloc") ~= nil
or output:find("Failed to acquire write lock") ~= nil
or output:find("Failed to acquire read lock") ~= nil)
if is_shm_issue and #output > 0 then
local sanitized = output:gsub("%[ FAILED %]", "[ SHM-SKIP ]")
sanitized = sanitized:gsub("(%d+) FAILED TEST SUITES?", "%1 SHM-SKIPPED TEST SUITE")
sanitized = sanitized:gsub("(%d+) FAILED TESTS?", "%1 SHM-SKIPPED TEST")
log_both_raw(sanitized)
elseif #output > 0 then
log_both_raw(output)
end
local cleaned = output:gsub("%d+%s+FAILED TEST SUITES?", "")
local real_fail_count = 0
for n in cleaned:gmatch("(%d+)%s+FAILED TESTS?") do
real_fail_count = math.max(real_fail_count, tonumber(n) or 0)
end
local shm_env_failed = is_shm_issue
local suite_only = output:find("FAILED TEST SUITES?") ~= nil
and real_fail_count == 0
local has_gtest_failure = real_fail_count > 0 and not shm_env_failed
local passed_count, failed_count = parse_gtest_counts(output)
if r.crashed then
log_both(string.format("警告: 测试 %s 崩溃(退出码: %d),无 gtest 输出,跳过", exe.name, r.rc))
elseif r.rc == 124 then
log_both(string.format("警告: 测试 %s 执行超时(超过 %ss),跳过", exe.name, timeout_sec))
elseif shm_env_failed then
log_both(string.format(
"警告: 测试 %s 检测到 harbor/shm 环境受限(%d 个 gtest 用例受影响),按环境跳过",
exe.name, real_fail_count))
local_successes = local_successes + passed_count
elseif has_gtest_failure then
log_both(string.format("测试 %s 失败,退出码: %d(有 %d 个 gtest 用例失败)",
exe.name, r.rc, real_fail_count))
total_failed = total_failed + 1
table.insert(failed_names, exe.name)
io.stderr:write(string.format("[test.lua][FAIL] [%d/%d] %s rc=%d %d cases failed:\n",
idx, #found, exe.name, r.rc, real_fail_count))
for line in output:gmatch("[^\n]+") do
if line:find("%[ FAILED %]") then
io.stderr:write(" " .. line .. "\n")
end
end
local_successes = local_successes + passed_count
local_failures = local_failures + failed_count
elseif suite_only then
log_both(string.format(
"警告: 测试 %s SetUpTestSuite 失败(退出码: %d),跳过",
exe.name, r.rc))
elseif r.rc ~= 0 then
log_both(string.format("警告: 测试 %s 异常退出(退出码: %d),但无 gtest 失败用例,跳过", exe.name, r.rc))
else
log_both(string.format("测试 %s 通过", exe.name))
local_successes = local_successes + passed_count
end
io.stdout:flush()
end
aggregate_successes = local_successes
aggregate_failures = local_failures
io.stderr:write(string.format(
"[test.lua][AGG] 聚合 gtest 用例数: successes=%d failures=%d (跨 %d 个二进制)\n",
local_successes, local_failures, #found))
if total_failed > 0 then
local detail = table.concat(failed_names, ", ")
io.stderr:write(string.format(
"[test.lua][SUMMARY] 共 %d 个真实失败:%s\n", total_failed, detail))
lu.assertEquals(total_failed, 0,
string.format("有 %d 个测试失败: %s", total_failed, detail))
end
log_both("========== C++ 单元测试完成 ==========\n")
end
log_both("\n========================================")
log_both("开始运行 TestComponentDrivers 测试套件")
log_both("========================================\n")
io.stderr:write("[test.lua] 开始 LuaUnit 调度 TestComponentDrivers ...\n")
local t_lu_start = os.time()
local result = lu.LuaUnit.run()
local lu_duration = os.difftime(os.time(), t_lu_start)
io.stderr:write(string.format("[test.lua] LuaUnit 结束,退出码: %s\n", tostring(result)))
local tests_total, successes_total, failures_total
if result ~= 0 then
tests_total = aggregate_successes + aggregate_failures
successes_total = aggregate_successes
failures_total = math.max(aggregate_failures, 1)
if tests_total == 0 then tests_total = 1 end
elseif (aggregate_successes + aggregate_failures) > 0 then
tests_total = aggregate_successes + aggregate_failures
successes_total = aggregate_successes
failures_total = aggregate_failures
else
tests_total = 1
successes_total = 1
failures_total = 0
end
local summary = string.format(
"# Ran %d tests in %.3f seconds, %d success%s, %d failures\n",
tests_total, lu_duration, successes_total,
(successes_total == 1) and "" or "es", failures_total)
io.stdout:write(summary)
io.stdout:flush()
io.stdout:close()
io.stderr:write(string.format("[test.lua] summary 已写入并 close(stdout):%s", summary))
os.exit(result)