# shellcheck shell=bash # ============================================================================ # 轻量断言库(tests/run.sh 在每个用例文件的子 shell 中 source) # 所有断言失败时打印诊断并返回非 0;测试函数应直接调用并以其返回值作为结果。 # ============================================================================ # 断言两值相等。用法:assert_eq <期望值> <实际值> [描述] assert_eq() { local expected="$1" actual="$2" msg="${3:-}" if [[ "$expected" == "$actual" ]]; then return 0 fi echo " ✗ assert_eq${msg:+($msg)}" >&2 echo " 期望: [$expected]" >&2 echo " 实际: [$actual]" >&2 return 1 } # 断言字符串包含子串。用法:assert_contains <字符串> <子串> [描述] assert_contains() { local haystack="$1" needle="$2" msg="${3:-}" if [[ "$haystack" == *"$needle"* ]]; then return 0 fi echo " ✗ assert_contains${msg:+($msg)}" >&2 echo " 字符串: [$haystack]" >&2 echo " 子串: [$needle]" >&2 return 1 } # 断言字符串为空。用法:assert_empty <字符串> [描述] assert_empty() { local val="$1" msg="${2:-}" if [[ -z "$val" ]]; then return 0 fi echo " ✗ assert_empty${msg:+($msg)}:实际为 [$val]" >&2 return 1 } # 断言字符串非空。用法:assert_not_empty <字符串> [描述] assert_not_empty() { local val="$1" msg="${2:-}" if [[ -n "$val" ]]; then return 0 fi echo " ✗ assert_not_empty${msg:+($msg)}:实际为空" >&2 return 1 } # 断言命令成功。用法:assert_success <命令...> assert_success() { if "$@"; then return 0 fi echo " ✗ assert_success:命令失败:$*" >&2 return 1 } # 断言命令失败(返回非 0)。用法:assert_failure <命令...> assert_failure() { if "$@"; then echo " ✗ assert_failure:命令意外成功:$*" >&2 return 1 fi return 0 } # 断言文件存在。用法:assert_file_exists <路径> [描述] assert_file_exists() { local path="$1" msg="${2:-}" if [[ -f "$path" ]]; then return 0 fi echo " ✗ assert_file_exists${msg:+($msg)}:$path 不存在" >&2 return 1 } # 断言文件不存在。用法:assert_file_absent <路径> [描述] assert_file_absent() { local path="$1" msg="${2:-}" if [[ ! -e "$path" ]]; then return 0 fi echo " ✗ assert_file_absent${msg:+($msg)}:$path 意外存在" >&2 return 1 }