- emit_warn 构造完整输出行一次,真实输出与测试记录器共享同一字符串(不再分叉) - 记录器改为线程局部并统计“实际发出的行数”⇒ 同 key 只发一次 / 洪水量 256 封顶在输出层被钉住 - 新增子进程用例:真 stderr 必须逐字出现两条 WARN 行(含前缀) - 新增源级守卫:emit_warn 里恰好一处真实标准错误输出,打印共享的那一行 - warn_once_variable 降为模块私有 ⇒ 兄弟模块无法用未净化值触发告警 - 补消息内容/标签顺序/前缀/净化上限 64 字节的精确断言;ends_with 换 assert_eq - 补正向 doctest,钉住 crate 路径可解析(compile_fail 不再因路径写错而假通过) Co-Authored-By: Claude Code <[email protected]>
1032 lines
41 KiB
Rust
1032 lines
41 KiB
Rust
//! 跨端协议版本闸门 —— 上游 `ssw.common.security.InternalTokenSupport` 的 Rust 等价物。
|
||
//!
|
||
//! 判定(逐字复刻):
|
||
//! declared 为空/空白 → 放行 + 一次性 WARN(兼容期)
|
||
//! major 相等且双方 minor 可解析 → 放行
|
||
//! 否则 → 拒绝(HTTP 401)
|
||
//!
|
||
//! ⚠️ 细节:**只比 major,但 minor 段解析失败会连累整体**
|
||
//! (`"1.x"` ⇒ 不可解析 ⇒ 不兼容;`"1.2.3"` ⇒ 段数超限 ⇒ 不兼容)。
|
||
//!
|
||
//! 一次性 WARN 的三条安全约束:
|
||
//! - **固定 key 与变量 key 分属两个集合**:固定 key(`protocol:missing`)永不受上限约束
|
||
//! ⇒ 对端没法用一堆伪造版本号把「老客户端还在线上」的信号永久静音。
|
||
//! - **变量 key 集合满了就抑制(不淘汰)** ⇒ 洪水量按每进程 256 条封顶;
|
||
//! 若改成淘汰,每来一个新版本串就会补一条 WARN,等于给对端一个「按对端节奏打日志」的放大器。
|
||
//! - **对端可控的值进日志前先净化**:去控制字符(含 ANSI ESC 序列、U+2028/U+2029)并按
|
||
//! 整字符截断,防日志伪造 / 终端转义注入。净化**只用于日志**,安全判定一律用原值。
|
||
//!
|
||
//! 🔴 净化的**调用点**同样有保护:打进日志的 key 与消息体只接受 `SafePeer`(已净化的
|
||
//! 对端声明值),而 `SafePeer` 只能经 `SafePeer::new` 构造 ⇒ 调用点在**类型上**没法把
|
||
//! 未净化的对端值送进日志。
|
||
//!
|
||
//! 🔴 净化的**出口**同样被封住:变量 key 的告警入口 `warn_once_variable` 是**模块私有**
|
||
//! ⇒ crate 内的兄弟模块既拿不到它,也没法用它把裸 `&str` 打进日志。
|
||
|
||
use std::collections::HashSet;
|
||
use std::sync::{Mutex, MutexGuard, OnceLock};
|
||
|
||
/// 本端协议版本。
|
||
pub const PROTOCOL_VERSION: &str = "1.0";
|
||
/// 协议版本声明头。
|
||
pub const PROTOCOL_VERSION_HEADER: &str = "X-Protocol-Version";
|
||
/// 内部令牌头。
|
||
pub const INTERNAL_TOKEN_HEADER: &str = "X-Internal-Token";
|
||
|
||
/// **变量** key(key 里含对端可控内容)的集合上限(对齐上游 `warnOnce` 的有界集合)。
|
||
/// 固定 key 不受此上限约束 —— 见 `warn_once`。
|
||
const WARN_ONCE_MAX_KEYS: usize = 256;
|
||
|
||
/// 写入日志前对声明值的净化上限(字节)。
|
||
const LOG_MAX_LEN: usize = 64;
|
||
|
||
/// 已净化的对端声明值(newtype)。
|
||
///
|
||
/// 放在**子模块**里是关键:字段私有 ⇒ 父模块(也就是真正拼 key / 消息的地方)
|
||
/// **无法**直接写 `SafePeer(raw)` 绕过净化 ⇒ 唯一构造路径是 [`SafePeer::new`],
|
||
/// 而净化就在 `new` 内部完成。
|
||
mod safe_peer {
|
||
use super::sanitize_for_log;
|
||
|
||
/// 已净化的对端声明值。
|
||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||
pub(super) struct SafePeer(String);
|
||
|
||
impl SafePeer {
|
||
/// 构造:**净化在��里发生**,外部无法绕过。
|
||
pub(super) fn new(raw: &str) -> Self {
|
||
Self(sanitize_for_log(raw))
|
||
}
|
||
|
||
/// 已净化后的文本。
|
||
pub(super) fn as_str(&self) -> &str {
|
||
&self.0
|
||
}
|
||
}
|
||
}
|
||
|
||
use safe_peer::SafePeer;
|
||
|
||
/// 固定 key 的已告警集合:与对端输入无关,**永不受上限约束**。
|
||
fn fixed_warned_keys() -> &'static Mutex<HashSet<String>> {
|
||
static KEYS: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
|
||
KEYS.get_or_init(|| Mutex::new(HashSet::new()))
|
||
}
|
||
|
||
/// 变量 key 的已告警集合:key 含对端可控内容,**有界**(见 `WARN_ONCE_MAX_KEYS`)。
|
||
fn variable_warned_keys() -> &'static Mutex<HashSet<String>> {
|
||
static KEYS: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
|
||
KEYS.get_or_init(|| Mutex::new(HashSet::new()))
|
||
}
|
||
|
||
/// 取集合锁;锁中毒时恢复(不让一次 panic 永久毒死告警通道)。
|
||
fn lock_set(set: &Mutex<HashSet<String>>) -> MutexGuard<'_, HashSet<String>> {
|
||
match set.lock() {
|
||
Ok(g) => g,
|
||
Err(poisoned) => poisoned.into_inner(),
|
||
}
|
||
}
|
||
|
||
/// 登记固定 key:首次登记返回 true。**永不受集合上限约束**。
|
||
fn claim_fixed_key(set: &Mutex<HashSet<String>>, key: &str) -> bool {
|
||
lock_set(set).insert(key.to_string())
|
||
}
|
||
|
||
/// 登记变量 key:首次登记返回 true。
|
||
///
|
||
/// 集合有界:**满了就抑制**(返回 false),**不淘汰**。淘汰会让「每来一个新版本串就补一条 WARN」
|
||
/// 变成按对端节奏的无界日志放大器,而且被淘汰的 key 之后会再次告警,破坏「同 key 只告警一次」。
|
||
fn claim_variable_key(set: &Mutex<HashSet<String>>, key: &str) -> bool {
|
||
let mut set = lock_set(set);
|
||
if set.len() >= WARN_ONCE_MAX_KEYS {
|
||
return false;
|
||
}
|
||
set.insert(key.to_string())
|
||
}
|
||
|
||
/// 实际打印告警。
|
||
///
|
||
/// ⚠️ **调用方必须已在 `claim_*` 返回之后调用本函数** —— 集合锁在 `claim_*` 内部即释放;
|
||
/// 本函数**绝不取集合锁**(不许持锁做 IO)。
|
||
///
|
||
/// 🔴 **完整输出行只构造一次**:真实输出与测试记录器共享**同一个**字符串 `line`
|
||
/// ⇒ 二者不可能分叉(不会一个记 A、一个打 B)。
|
||
/// ⚠️ stable 没有可用的**进程内** stderr 捕获手段(`std::io::set_output_capture` 是 `#[unstable]`)
|
||
/// ⇒ 「这一行真的落到了 fd 2」由**子进程**用例实测;本函数只保证「那一行还在、且内容是共享的那一行」。
|
||
fn emit_warn(message: &str) {
|
||
let line = format!("[tdc-connector] WARN {}", message);
|
||
eprintln!("{}", line);
|
||
#[cfg(test)]
|
||
warn_recorder::record(&line);
|
||
}
|
||
|
||
/// 测试用的告警记录器:**只存在于测试构建**。
|
||
///
|
||
/// 记录的是**真实输出行**(含 `[tdc-connector] WARN ` 前缀),与 `emit_warn` 共享同一个字符串。
|
||
///
|
||
/// 🔴 **线程局部**(`thread_local!`)⇒ libtest 每个用例一个线程 ⇒ 并行跑的用例之间
|
||
/// **互不污染** ⇒ 「实际发出了几行」这类计数断言不会被别的模块的告警干扰。
|
||
#[cfg(test)]
|
||
mod warn_recorder {
|
||
use std::cell::RefCell;
|
||
|
||
thread_local! {
|
||
static EMITTED: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
|
||
}
|
||
|
||
/// 记录一条**真实输出行**。
|
||
pub(super) fn record(line: &str) {
|
||
EMITTED.with(|v| v.borrow_mut().push(line.to_string()));
|
||
}
|
||
|
||
/// **实际发出的行数**(不是「登记了几个 key」—— 两者差别正是本模块的核心不变式)。
|
||
pub(super) fn emitted_count() -> usize {
|
||
EMITTED.with(|v| v.borrow().len())
|
||
}
|
||
|
||
/// 最近一条发出的行。
|
||
pub(super) fn last() -> Option<String> {
|
||
EMITTED.with(|v| v.borrow().last().cloned())
|
||
}
|
||
|
||
pub(super) fn clear() {
|
||
EMITTED.with(|v| v.borrow_mut().clear());
|
||
}
|
||
}
|
||
|
||
/// 解析 `major.minor`。**两段都必须可解析**,否则 `None`。
|
||
pub fn parse_version(v: &str) -> Option<(u64, u64)> {
|
||
let trimmed = v.trim();
|
||
if trimmed.is_empty() {
|
||
return None;
|
||
}
|
||
let parts: Vec<&str> = trimmed.split('.').collect();
|
||
if parts.len() > 2 {
|
||
return None;
|
||
}
|
||
let major = parts[0].parse::<u64>().ok()?;
|
||
let minor = if parts.len() == 2 {
|
||
parts[1].parse::<u64>().ok()?
|
||
} else {
|
||
0
|
||
};
|
||
Some((major, minor))
|
||
}
|
||
|
||
/// 只比 major。
|
||
pub fn is_protocol_compatible(declared: &str) -> bool {
|
||
let (mine, _) = match parse_version(PROTOCOL_VERSION) {
|
||
Some(v) => v,
|
||
None => return false,
|
||
};
|
||
match parse_version(declared) {
|
||
Some((theirs, _)) => theirs == mine,
|
||
None => false,
|
||
}
|
||
}
|
||
|
||
/// 未声明 ⇒ 放行(兼容期);声明了 ⇒ 必须兼容。
|
||
pub fn is_protocol_acceptable(declared: Option<&str>) -> bool {
|
||
let d = declared.unwrap_or("").trim();
|
||
if d.is_empty() {
|
||
return true;
|
||
}
|
||
is_protocol_compatible(d)
|
||
}
|
||
|
||
/// 同 key 只告警一次。返回 true = 本次真的告警了。
|
||
///
|
||
/// ⚠️ **key 必须是编译期常量**(与对端输入无关)—— 固定 key 永不受集合上限约束,
|
||
/// 任何时候都能告警。key 里含对端可控内容时**只能**用模块内部的
|
||
/// `warn_once_variable`(它收已净化的值,本模块外无出口)。
|
||
///
|
||
/// 对端派生的动态 key 走不通这条路(编译期拒绝):
|
||
///
|
||
/// ```compile_fail
|
||
/// use tdc_connector::protocol::warn_once;
|
||
/// let dynamic = String::from("protocol:incompatible:2.0");
|
||
/// warn_once(&dynamic, "x");
|
||
/// ```
|
||
///
|
||
/// 🔴 上面的 `compile_fail` 只保证「**动态 `String` 传不进来**」。
|
||
/// ⚠️ 它对「**路径写错**」也会判通过(未解析的 import 同样是编译不过)⇒
|
||
/// 必须有下面这条**正向** doctest 把 crate 路径钉死,否则 `compile_fail` 会假通过。
|
||
///
|
||
/// ```no_run
|
||
/// use tdc_connector::protocol::warn_once;
|
||
/// warn_once("protocol:missing", "x");
|
||
/// ```
|
||
///
|
||
/// ⚠️ **诚实限定**:`&'static str` 不是万无一失 —— `Box::leak` / `String::leak` 仍能造出
|
||
/// `&'static str`(Rust 类型系统的固有极限,doctest 也拦不住该形态)。
|
||
/// 真正的硬保证是**结构上的**:非测试代码里 `warn_once` 只有一处调用点
|
||
/// (`check_protocol_with_warn`),且传的是字面量 `"protocol:missing"`。
|
||
pub fn warn_once(key: &'static str, message: &str) -> bool {
|
||
if claim_fixed_key(fixed_warned_keys(), key) {
|
||
emit_warn(message);
|
||
true
|
||
} else {
|
||
false
|
||
}
|
||
}
|
||
|
||
/// 同 key 只告警一次,但 key 集合**有界**(上限 `WARN_ONCE_MAX_KEYS`,满了即抑制)。
|
||
/// 返回 true = 本次真的告警了。
|
||
///
|
||
/// 用于 key 含对端可控内容(如声明的协议版本)的场景:对端即使灌爆集合,
|
||
/// 也只是让**新的**变量告警不再产生,**不会**让固定 key 的告警失效。
|
||
///
|
||
/// 🔴 **模块私有**:变量 key 的告警是本模块的**内部实现细节**。
|
||
/// 它收**裸 `&str`**(key 与消息体),若留 crate 级可见性,**兄弟模块**就能用它把
|
||
/// **未净化**的对端字节直接打进日志 —— 那会绕过 `SafePeer` 这道 newtype 闸门。
|
||
/// 降为模块私有后,crate 内**没有任何**调用点能构造未净化的变量告警。
|
||
fn warn_once_variable(key: &str, message: &str) -> bool {
|
||
if claim_variable_key(variable_warned_keys(), key) {
|
||
emit_warn(message);
|
||
true
|
||
} else {
|
||
false
|
||
}
|
||
}
|
||
|
||
/// 需要从日志中剔除的字符:控制字符(C0/C1)、行/段分隔符与方向控制类格式字符。
|
||
fn is_log_unsafe(c: char) -> bool {
|
||
c.is_control()
|
||
|| matches!(
|
||
c,
|
||
'\u{200b}'..='\u{200f}' // 零宽字符
|
||
| '\u{2028}'..='\u{2029}' // LINE / PARAGRAPH SEPARATOR(部分查看器当换行处理)
|
||
| '\u{202a}'..='\u{202e}' // 双向覆写(RLO/LRO)
|
||
| '\u{2060}'..='\u{206f}' // 双向隔离 + 隐形字符
|
||
| '\u{feff}' // BOM / ZWNBSP
|
||
)
|
||
}
|
||
|
||
/// 净化对端可控的字符串,供**日志 / 告警**用途:去控制字符(含 ANSI ESC 序列)并按整字符截断。
|
||
///
|
||
/// ⚠️ **只用于日志**。安全判定(`is_protocol_compatible` / `is_protocol_acceptable`)
|
||
/// 必须使用原值 —— 净化会引入绕过风险(如 `"1.0\u{1b}[0m"` 净化后变 `"1.0"`,
|
||
/// 反而可能被误判为兼容)。
|
||
///
|
||
/// 截断**按整字符推进**(不用 `String::truncate`)⇒ 64 字节边界切在多字节字符中间也不会 panic。
|
||
pub(crate) fn sanitize_for_log(raw: &str) -> String {
|
||
let mut out = String::new();
|
||
let mut it = raw.chars().peekable();
|
||
while let Some(c) = it.next() {
|
||
if out.len() + c.len_utf8() > LOG_MAX_LEN {
|
||
break;
|
||
}
|
||
if c == '\u{1b}' {
|
||
// ANSI 转义序列:ESC [ … 消费到 final byte;ESC ] … 消费到 BEL/ST;其余按 2 字节序列
|
||
match it.peek() {
|
||
Some(&'[') => {
|
||
it.next();
|
||
for c2 in it.by_ref() {
|
||
if ('\u{40}'..='\u{7e}').contains(&c2) {
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
Some(&']') => {
|
||
it.next();
|
||
for c2 in it.by_ref() {
|
||
if c2 == '\u{7}' {
|
||
break;
|
||
}
|
||
if c2 == '\u{1b}' {
|
||
it.next();
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
_ => {
|
||
it.next();
|
||
}
|
||
}
|
||
continue;
|
||
}
|
||
if is_log_unsafe(c) {
|
||
continue;
|
||
}
|
||
out.push(c);
|
||
}
|
||
out
|
||
}
|
||
|
||
/// 变量 key:含**净化后**的声明值(防日志伪造 / 终端转义注入)。
|
||
/// 入参是 `SafePeer` ⇒ 调用点**没法**把未净化的原值塞进来。
|
||
fn incompatible_warn_key(peer: &SafePeer) -> String {
|
||
format!("protocol:incompatible:{}", peer.as_str())
|
||
}
|
||
|
||
/// 不兼容告警的消息体:只用**净化后**的声明值。
|
||
/// 入参是 `SafePeer` ⇒ 调用点**没法**把未净化的原值塞进来。
|
||
fn incompatible_message(peer: &SafePeer) -> String {
|
||
format!(
|
||
"跨端协议版本不兼容(对端 {},本端 {}),请升级对端",
|
||
peer.as_str(),
|
||
PROTOCOL_VERSION
|
||
)
|
||
}
|
||
|
||
/// 闸门判定 + 一次性告警。返回 `(是否放行, 本次是否真的告警了)`。
|
||
fn check_protocol_with_warn(declared: Option<&str>) -> (bool, bool) {
|
||
let d = declared.unwrap_or("").trim();
|
||
if d.is_empty() {
|
||
let warned = warn_once(
|
||
"protocol:missing",
|
||
&format!(
|
||
"跨端请求未声明 {},按兼容期放行(本端 {})",
|
||
PROTOCOL_VERSION_HEADER, PROTOCOL_VERSION
|
||
),
|
||
);
|
||
return (true, warned);
|
||
}
|
||
// 判定用原值 `d`;日志用净化值(净化恰好发生一次)。
|
||
if is_protocol_compatible(d) {
|
||
return (true, false);
|
||
}
|
||
let peer = SafePeer::new(d);
|
||
let warned = warn_once_variable(
|
||
&incompatible_warn_key(&peer),
|
||
&incompatible_message(&peer),
|
||
);
|
||
(false, warned)
|
||
}
|
||
|
||
/// 闸门判定 + 一次性告警。返回 true = 放行。
|
||
pub fn check_protocol(declared: Option<&str>) -> bool {
|
||
check_protocol_with_warn(declared).0
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
/// 串行化本模块用例:告警状态是进程级全局的,并发跑会互相干扰。
|
||
fn test_guard() -> MutexGuard<'static, ()> {
|
||
static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
|
||
match LOCK.get_or_init(|| Mutex::new(())).lock() {
|
||
Ok(g) => g,
|
||
Err(poisoned) => poisoned.into_inner(),
|
||
}
|
||
}
|
||
|
||
/// 清空全局告警状态(含告警记录器),让用例从干净状态开始(避免用例之间抢 key)。
|
||
fn reset_warn_state() {
|
||
lock_set(fixed_warned_keys()).clear();
|
||
lock_set(variable_warned_keys()).clear();
|
||
warn_recorder::clear();
|
||
}
|
||
|
||
/// 固定路径(未声明协议版本)的**期望整行**。
|
||
///
|
||
/// 🔴 期望值必须与被测代码**独立**(这里硬编码 header 名与文案模板,
|
||
/// 只用 `PROTOCOL_VERSION` 取本端版本)⇒ 否则「消息内容被改坏」这类变异会
|
||
/// 顺手把期望值一起改掉 ⇒ 假通过。
|
||
fn expected_missing_line() -> String {
|
||
format!(
|
||
"[tdc-connector] WARN 跨端请求未声明 X-Protocol-Version,按兼容期放行(本端 {})",
|
||
PROTOCOL_VERSION
|
||
)
|
||
}
|
||
|
||
/// 不兼容路径的**期望整行**(`peer` = 净化后的对端声明值)。
|
||
fn expected_incompatible_line(peer: &str) -> String {
|
||
format!(
|
||
"[tdc-connector] WARN 跨端协议版本不兼容(对端 {},本端 {}),请升级对端",
|
||
peer, PROTOCOL_VERSION
|
||
)
|
||
}
|
||
|
||
#[test]
|
||
fn parses_major_and_minor() {
|
||
assert_eq!(parse_version("1.0"), Some((1, 0)));
|
||
assert_eq!(parse_version("2"), Some((2, 0)));
|
||
assert_eq!(parse_version(" 1.7 "), Some((1, 7)));
|
||
}
|
||
|
||
#[test]
|
||
fn rejects_unparsable_minor_and_extra_parts() {
|
||
// 上游语义:两段都必须可解析,否则整体不可解析
|
||
assert_eq!(parse_version("1.x"), None);
|
||
assert_eq!(parse_version("1.2.3"), None);
|
||
assert_eq!(parse_version(""), None);
|
||
assert_eq!(parse_version("abc"), None);
|
||
}
|
||
|
||
#[test]
|
||
fn compares_major_only() {
|
||
assert!(is_protocol_compatible("1.0"));
|
||
assert!(is_protocol_compatible("1.9"));
|
||
assert!(!is_protocol_compatible("2.0"));
|
||
assert!(!is_protocol_compatible("0.9"));
|
||
assert!(!is_protocol_compatible("1.x"));
|
||
}
|
||
|
||
#[test]
|
||
fn missing_declaration_is_acceptable_compat_window() {
|
||
assert!(is_protocol_acceptable(None));
|
||
assert!(is_protocol_acceptable(Some("")));
|
||
assert!(is_protocol_acceptable(Some(" ")));
|
||
}
|
||
|
||
#[test]
|
||
fn incompatible_declaration_is_rejected() {
|
||
assert!(!is_protocol_acceptable(Some("9.0")));
|
||
assert!(!is_protocol_acceptable(Some("1.x")));
|
||
assert!(!is_protocol_acceptable(Some("1.2.3")));
|
||
}
|
||
|
||
#[test]
|
||
fn warn_once_fires_only_once_per_key() {
|
||
let _g = test_guard();
|
||
reset_warn_state();
|
||
let key = "test:warn-once:unique-1";
|
||
assert!(warn_once(key, "第一次"));
|
||
assert!(!warn_once(key, "第二次"));
|
||
}
|
||
|
||
// ---- 闸门本身:判定 + 告警 ----
|
||
|
||
#[test]
|
||
fn public_check_protocol_is_covered() {
|
||
// 公开 API 必须被直接断言(否则把 `.0` 写成 `.1` 也没人发现)
|
||
let _g = test_guard();
|
||
reset_warn_state();
|
||
assert!(check_protocol(None), "未声明 ⇒ 兼容期放行");
|
||
assert!(check_protocol(Some("1.4")), "同 major ⇒ 放行");
|
||
assert!(!check_protocol(Some("5.1")), "major 不同 ⇒ 拒绝");
|
||
}
|
||
|
||
#[test]
|
||
fn public_check_protocol_actually_emits_the_missing_warn() {
|
||
// 返回值对 ≠ 告警真的发出去了:brief 契约是「带一次性 WARN」
|
||
let _g = test_guard();
|
||
reset_warn_state();
|
||
assert!(check_protocol(None), "未声明 ⇒ 兼容期放行");
|
||
assert!(
|
||
lock_set(fixed_warned_keys()).contains("protocol:missing"),
|
||
"公开 check_protocol 必须真的走告警通道(brief 契约:带一次性 WARN)"
|
||
);
|
||
// 🔴 集合里有 key **不等于**告警发出去了 ⇒ 还要断言**真的打出了一行**
|
||
assert_eq!(
|
||
warn_recorder::emitted_count(),
|
||
1,
|
||
"固定路径必须真的打出一行 WARN(集合里有 key 不算数)"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn missing_declaration_stays_allowed_across_calls() {
|
||
// 第二次调用时 warn 标志变 false:若元组顺序写反,第二次就会变成 401
|
||
let _g = test_guard();
|
||
reset_warn_state();
|
||
assert!(check_protocol(None), "第一次未声明 ⇒ 放行");
|
||
assert!(check_protocol(None), "第二次未声明 ⇒ 仍应放行(兼容期)");
|
||
}
|
||
|
||
#[test]
|
||
fn check_protocol_allows_missing_and_compatible_and_rejects_incompatible() {
|
||
let _g = test_guard();
|
||
reset_warn_state();
|
||
|
||
let (allowed, warned) = check_protocol_with_warn(None);
|
||
assert!(allowed, "未声明协议版本 ⇒ 兼容期放行");
|
||
assert!(warned, "未声明协议版本 ⇒ 应告警一次");
|
||
|
||
let (allowed, warned) = check_protocol_with_warn(Some("1.0"));
|
||
assert!(allowed, "major 相同 ⇒ 放行");
|
||
assert!(!warned, "兼容的声明不该告警");
|
||
|
||
let (allowed, warned) = check_protocol_with_warn(Some("2.0"));
|
||
assert!(!allowed, "major 不同 ⇒ 拒绝");
|
||
assert!(warned, "不兼容的声明 ⇒ 应告警一次");
|
||
}
|
||
|
||
#[test]
|
||
fn check_protocol_warns_only_once_per_declared_version() {
|
||
let _g = test_guard();
|
||
reset_warn_state();
|
||
|
||
// 唯一版本串(其它用例不会用到)⇒ 独立的告警 key
|
||
let (allowed, warned) = check_protocol_with_warn(Some("3.7"));
|
||
assert!(!allowed, "major 不同 ⇒ 拒绝");
|
||
assert!(warned, "第一次不兼容 ⇒ 应告警");
|
||
|
||
let (allowed, warned) = check_protocol_with_warn(Some("3.7"));
|
||
assert!(!allowed);
|
||
assert!(!warned, "同一声明值只应告警一次");
|
||
}
|
||
|
||
// ---- 告警通道抗灌 ----
|
||
|
||
#[test]
|
||
fn variable_key_flood_cannot_silence_fixed_keys() {
|
||
let _g = test_guard();
|
||
reset_warn_state();
|
||
|
||
// 固定 key 先告警一次
|
||
assert!(warn_once("test:fixed:keep", "固定 key"));
|
||
|
||
// 对端用一堆不同的非法版本号灌爆变量 key 集合
|
||
for i in 0..(WARN_ONCE_MAX_KEYS + 16) {
|
||
let _ = warn_once_variable(&format!("test:flood:{}", i), "灌水");
|
||
}
|
||
// 变量 key 集合仍然有界
|
||
assert!(lock_set(variable_warned_keys()).len() <= WARN_ONCE_MAX_KEYS);
|
||
// 两个集合分开计数(包含性断言,不断言精确条数):
|
||
// 固定 key 记在固定集合,变量 key 不许进固定集合
|
||
assert!(
|
||
lock_set(fixed_warned_keys()).contains("test:fixed:keep"),
|
||
"固定 key 应记在固定集合"
|
||
);
|
||
assert!(
|
||
!lock_set(fixed_warned_keys()).contains("test:flood:0"),
|
||
"变量 key 不得记进固定集合"
|
||
);
|
||
assert!(
|
||
!lock_set(variable_warned_keys()).contains("test:fixed:keep"),
|
||
"固定 key 不得记进变量集合"
|
||
);
|
||
|
||
// 固定 key 仍被记住 ⇒ 不会被变量集合淘汰
|
||
assert!(
|
||
!warn_once("test:fixed:keep", "固定 key"),
|
||
"固定 key 不得被变量集合淘汰"
|
||
);
|
||
|
||
// 固定 key 仍然能告警:永不受变量 key 集合上限影响
|
||
let (allowed, warned) = check_protocol_with_warn(None);
|
||
assert!(allowed);
|
||
assert!(warned, "变量 key 灌爆后,固定 key 仍必须能告警");
|
||
|
||
// 变量 key 路径被上限封顶:新的声明值不再逐条告警(洪水量有界的代价)
|
||
let (allowed, warned) = check_protocol_with_warn(Some("4.2"));
|
||
assert!(!allowed, "major 不同 ⇒ 仍然拒绝");
|
||
assert!(!warned, "变量 key 集合已满 ⇒ 新声明值不再告警");
|
||
}
|
||
|
||
#[test]
|
||
fn variable_key_set_stays_bounded() {
|
||
let local = Mutex::new(HashSet::new());
|
||
for i in 0..WARN_ONCE_MAX_KEYS {
|
||
assert!(
|
||
claim_variable_key(&local, &format!("k:{}", i)),
|
||
"上限内的 key 应拿到位置"
|
||
);
|
||
}
|
||
// 超上限的 key 一律被抑制(不淘汰 ⇒ 不会把老 key 挤掉)
|
||
for i in WARN_ONCE_MAX_KEYS..(WARN_ONCE_MAX_KEYS + 32) {
|
||
assert!(
|
||
!claim_variable_key(&local, &format!("k:{}", i)),
|
||
"超上限的 key 应被抑制"
|
||
);
|
||
}
|
||
assert!(lock_set(&local).len() <= WARN_ONCE_MAX_KEYS);
|
||
}
|
||
|
||
#[test]
|
||
fn flood_cannot_amplify_log_volume() {
|
||
let _g = test_guard();
|
||
reset_warn_state();
|
||
|
||
// 洪水量必须被封顶:每进程至多 256 条变量告警(256 是 brief 明写的数字 ⇒ 用字面量钉住)
|
||
let mut warned = 0usize;
|
||
for i in 0..(WARN_ONCE_MAX_KEYS * 4) {
|
||
if warn_once_variable(&format!("test:volume:{}", i), "灌水") {
|
||
warned += 1;
|
||
}
|
||
}
|
||
assert!(warned <= 256, "洪水量必须封顶(brief 约定 256),实际 {} 条", warned);
|
||
assert_eq!(WARN_ONCE_MAX_KEYS, 256, "上限是 brief 约定的 256");
|
||
assert!(lock_set(variable_warned_keys()).len() <= WARN_ONCE_MAX_KEYS);
|
||
// 🔴 布尔计数对了**不等于**副作用没放大:还要断言**实际打出的行数**
|
||
assert!(
|
||
warn_recorder::emitted_count() <= 256,
|
||
"实际打出的行数必须封顶(brief 约定 256),实际 {} 行",
|
||
warn_recorder::emitted_count()
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn fixed_key_set_is_never_capped() {
|
||
let _g = test_guard();
|
||
reset_warn_state();
|
||
|
||
// 固定集合**无上限**:超过 256 个互异 key 也必须每一个都登记成功
|
||
for i in 0..(WARN_ONCE_MAX_KEYS * 2) {
|
||
assert!(
|
||
claim_fixed_key(fixed_warned_keys(), &format!("test:fixed-flood:{}", i)),
|
||
"固定 key 永不被抑制"
|
||
);
|
||
}
|
||
// 包含性断言:集合里确实有这些 key
|
||
assert!(lock_set(fixed_warned_keys()).contains("test:fixed-flood:0"));
|
||
assert!(lock_set(fixed_warned_keys()).len() >= WARN_ONCE_MAX_KEYS * 2);
|
||
}
|
||
|
||
// ---- 日志净化(只影响日志,不影响判定) ----
|
||
|
||
#[test]
|
||
fn sanitize_strips_control_chars_and_ansi_sequences() {
|
||
assert_eq!(sanitize_for_log("1.0"), "1.0");
|
||
assert_eq!(sanitize_for_log("1.0\n伪造日志行"), "1.0伪造日志行");
|
||
assert_eq!(sanitize_for_log("1.0\r\n"), "1.0");
|
||
assert_eq!(sanitize_for_log("1.0\t2.0"), "1.02.0");
|
||
assert_eq!(sanitize_for_log("1.0\u{1b}[31mRED\u{1b}[0m"), "1.0RED");
|
||
assert_eq!(sanitize_for_log("1.0\u{7}2.0"), "1.02.0");
|
||
assert_eq!(sanitize_for_log("1.0\u{202e}2.0"), "1.02.0");
|
||
// U+2028 / U+2029 是行/段分隔符,部分查看器当换行处理 ⇒ 必须剔除
|
||
assert_eq!(sanitize_for_log("1.0\u{2028}2.0"), "1.02.0");
|
||
assert_eq!(sanitize_for_log("1.0\u{2029}2.0"), "1.02.0");
|
||
}
|
||
|
||
#[test]
|
||
fn sanitized_log_value_has_no_control_chars() {
|
||
// 样本覆盖:C0(ESC/LF/BEL)、C1(NEL/CSI)、行段分隔符、零宽、双向覆写、双向隔离、BOM
|
||
let raw = "1.0\u{1b}[31m\u{2028}\u{2029}\n\u{7}\u{202e}\u{85}\u{9b}\u{200b}\u{200e}\u{2066}\u{feff}中";
|
||
let s = sanitize_for_log(raw);
|
||
assert!(
|
||
!s.chars().any(|c| c.is_control()),
|
||
"净化后不得残留控制字符:{:?}",
|
||
s
|
||
);
|
||
assert!(
|
||
!s.contains('\u{2028}') && !s.contains('\u{2029}'),
|
||
"净化后不得残留 U+2028/U+2029:{:?}",
|
||
s
|
||
);
|
||
for c in ['\u{85}', '\u{9b}', '\u{200b}', '\u{200e}', '\u{2066}', '\u{feff}'] {
|
||
assert!(!s.contains(c), "净化后不得残留 U+{:04X}:{:?}", c as u32, s);
|
||
}
|
||
assert!(s.len() <= LOG_MAX_LEN);
|
||
assert!(std::str::from_utf8(s.as_bytes()).is_ok(), "必须是合法 UTF-8");
|
||
}
|
||
|
||
#[test]
|
||
fn sanitize_truncates_long_values() {
|
||
// 🔴 净化上限是 brief 约定的 64 **字节**(用字面量钉住 ⇒ 上限被放大/缩小都变红)
|
||
assert_eq!(LOG_MAX_LEN, 64, "净化上限是 brief 约定的 64 字节");
|
||
let long = "9".repeat(200);
|
||
let s = sanitize_for_log(&long);
|
||
assert_eq!(s.len(), LOG_MAX_LEN);
|
||
}
|
||
|
||
#[test]
|
||
fn sanitize_truncates_on_char_boundary_for_cjk() {
|
||
// 64 字节边界会切在多字节字符中间 ⇒ 必须整字符推进,不得 panic
|
||
let cjk = "中".repeat(100);
|
||
let s = sanitize_for_log(&cjk);
|
||
assert!(s.len() <= LOG_MAX_LEN);
|
||
assert!(s.chars().all(|c| c == '中'));
|
||
assert_eq!(s.len(), 63, "21 个中文字 = 63 字节,第 22 个会越过 64");
|
||
assert!(std::str::from_utf8(s.as_bytes()).is_ok(), "必须是合法 UTF-8");
|
||
|
||
// ASCII 占到 63 字节后再跟一个多字节字符 ⇒ 不得越界、不得 panic
|
||
let mixed = format!("{}{}", "a".repeat(LOG_MAX_LEN - 1), "中");
|
||
let s2 = sanitize_for_log(&mixed);
|
||
assert!(s2.len() <= LOG_MAX_LEN);
|
||
assert_eq!(s2.len(), LOG_MAX_LEN - 1);
|
||
}
|
||
|
||
#[test]
|
||
fn judgment_uses_raw_value_not_sanitized() {
|
||
// 净化后是 "1.0"(major 相同 ⇒ 兼容),但判定必须用原值 ⇒ 原值不可解析 ⇒ 仍判不兼容
|
||
assert_eq!(sanitize_for_log("1.0\u{1b}[0m"), "1.0");
|
||
assert!(!is_protocol_compatible("1.0\u{1b}[0m"));
|
||
assert!(!is_protocol_acceptable(Some("1.0\u{1b}[0m")));
|
||
|
||
// 闸门本身也必须用原值判定 ⇒ 拒绝,不能被净化后的 "1.0" 骗过
|
||
let _g = test_guard();
|
||
reset_warn_state();
|
||
let (allowed, warned) = check_protocol_with_warn(Some("1.0\u{1b}[0m"));
|
||
assert!(!allowed, "含转义序列的声明必须按原值判定为不兼容");
|
||
assert!(warned, "不兼容 ⇒ 应告警一次");
|
||
}
|
||
|
||
#[test]
|
||
fn warn_key_uses_sanitized_value() {
|
||
let peer = SafePeer::new("2.0\u{1b}[0m");
|
||
assert_eq!(peer.as_str(), "2.0");
|
||
assert_eq!(incompatible_warn_key(&peer), "protocol:incompatible:2.0");
|
||
let key = incompatible_warn_key(&SafePeer::new("9.9\n伪造日志行"));
|
||
assert!(!key.contains('\n'), "告警 key 不得带换行");
|
||
assert!(!key.contains('\u{1b}'), "告警 key 不得带 ESC");
|
||
}
|
||
|
||
// ---- 打进日志的那两样东西本身(调用点级) ----
|
||
|
||
#[test]
|
||
fn incompatible_key_and_message_are_sanitized() {
|
||
let peer = SafePeer::new("2.0\u{1b}[31m\n伪造行\u{85}");
|
||
let msg = incompatible_message(&peer);
|
||
assert!(!msg.contains('\u{1b}'), "消息不得含 ESC:{:?}", msg);
|
||
assert!(!msg.contains('\n'), "消息不得含换行:{:?}", msg);
|
||
assert!(!msg.contains('\u{85}'), "消息不得含 NEL:{:?}", msg);
|
||
assert!(
|
||
!msg.chars().any(|c| c.is_control()),
|
||
"消息不得含控制字符:{:?}",
|
||
msg
|
||
);
|
||
|
||
let key = incompatible_warn_key(&peer);
|
||
assert!(
|
||
key.starts_with("protocol:incompatible:"),
|
||
"key 前缀身份:{}",
|
||
key
|
||
);
|
||
assert!(!key.contains('\u{1b}'), "key 不得含 ESC:{}", key);
|
||
assert!(!key.contains('\n'), "key 不得含换行:{}", key);
|
||
assert!(!key.contains('\u{85}'), "key 不得含 NEL:{}", key);
|
||
assert!(
|
||
!key.chars().any(|c| c.is_control()),
|
||
"key 不得含控制字符:{}",
|
||
key
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn incompatible_warning_key_is_sanitized_end_to_end() {
|
||
// 走 check_protocol_with_warn 的**调用点**,而不是直接调纯函数
|
||
let _g = test_guard();
|
||
reset_warn_state();
|
||
let (allowed, warned) = check_protocol_with_warn(Some("2.0\u{1b}[31m\n伪造行\u{85}"));
|
||
assert!(!allowed, "major 不同 ⇒ 拒绝");
|
||
assert!(warned, "不兼容 ⇒ 应告警一次");
|
||
|
||
let keys: Vec<String> = lock_set(variable_warned_keys()).iter().cloned().collect();
|
||
assert!(!keys.is_empty(), "应登记了变量告警 key");
|
||
let peer = SafePeer::new("2.0\u{1b}[31m\n伪造行\u{85}");
|
||
for key in &keys {
|
||
assert!(
|
||
key.starts_with("protocol:incompatible:"),
|
||
"变量 key 前缀身份:{}",
|
||
key
|
||
);
|
||
// 🔴 精确比对(不是 `ends_with`)——`ends_with` 在对端值为空时会退化成空断言
|
||
assert_eq!(
|
||
key,
|
||
&format!("protocol:incompatible:{}", peer.as_str()),
|
||
"变量 key 必须**精确**等于「前缀 + 净化后的对端值」:{}",
|
||
key
|
||
);
|
||
assert!(!key.contains('\u{1b}'), "key 不得含 ESC:{}", key);
|
||
assert!(!key.contains('\n'), "key 不得含换行:{}", key);
|
||
assert!(!key.contains('\u{85}'), "key 不得含 NEL:{}", key);
|
||
assert!(
|
||
!key.chars().any(|c| c.is_control()),
|
||
"key 不得含控制字符:{}",
|
||
key
|
||
);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn incompatible_warning_message_line_is_sanitized() {
|
||
// ⚠️ **不是端到端的 stderr 断言**:这里看的是**测试替身**(记录器)记下的那一行。
|
||
// 「这一行真的落到了 fd 2」由 `stderr_really_receives_the_exact_warn_lines`(子进程)负责。
|
||
let _g = test_guard();
|
||
reset_warn_state();
|
||
let _ = check_protocol_with_warn(Some("2.0\u{1b}[31m\n伪造行\u{85}"));
|
||
let line = warn_recorder::last().expect("应发出了一条 WARN");
|
||
assert!(!line.contains('\u{1b}'), "消息不得含 ESC:{:?}", line);
|
||
assert!(!line.contains('\n'), "消息不得含换行:{:?}", line);
|
||
assert!(!line.contains('\u{85}'), "消息不得含 NEL:{:?}", line);
|
||
assert!(
|
||
!line.chars().any(|c| c.is_control()),
|
||
"消息不得含控制字符:{:?}",
|
||
line
|
||
);
|
||
// 🔴 整行必须**逐字**等于期望值(含前缀、对端净化值、本端版本、标签顺序)
|
||
assert_eq!(
|
||
line,
|
||
expected_incompatible_line("2.0伪造行"),
|
||
"告警整行必须逐字匹配(净化后对端值 = \"2.0伪造行\")"
|
||
);
|
||
}
|
||
|
||
// ---- 告警副作用:发不发 / 发几次 / 发什么 ----
|
||
|
||
#[test]
|
||
fn same_declaration_emits_exactly_one_warn_line() {
|
||
// 🔴 「同 key 只告警一次」必须在**输出次数**层被断言:
|
||
// 只断言布尔返回值(`warned`)不够 —— 副作用多发 4 倍时布尔值依然是对的。
|
||
let _g = test_guard();
|
||
reset_warn_state();
|
||
for i in 0..5 {
|
||
let (allowed, warned) = check_protocol_with_warn(Some("8.8"));
|
||
assert!(!allowed, "major 不同 ⇒ 拒绝");
|
||
if i == 0 {
|
||
assert!(warned, "第一次不兼容 ⇒ 应告警");
|
||
} else {
|
||
assert!(!warned, "同一声明值只应告警一次(第 {} 次)", i + 1);
|
||
}
|
||
}
|
||
assert_eq!(
|
||
warn_recorder::emitted_count(),
|
||
1,
|
||
"同一声明值只应真的打出一行 WARN"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn missing_declaration_emits_exactly_one_warn_line() {
|
||
let _g = test_guard();
|
||
reset_warn_state();
|
||
for i in 0..5 {
|
||
let (allowed, warned) = check_protocol_with_warn(None);
|
||
assert!(allowed, "未声明 ⇒ 兼容期放行");
|
||
if i == 0 {
|
||
assert!(warned, "第一次未声明 ⇒ 应告警");
|
||
} else {
|
||
assert!(!warned, "同一声明值只应告警一次(第 {} 次)", i + 1);
|
||
}
|
||
}
|
||
assert_eq!(
|
||
warn_recorder::emitted_count(),
|
||
1,
|
||
"固定路径:同一声明值只应真的打出一行 WARN"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn distinct_warnings_emit_one_line_each() {
|
||
// 计数器必须**累加**(不是「置 1」)⇒ 两个不同的 key 必须打两行
|
||
let _g = test_guard();
|
||
reset_warn_state();
|
||
assert!(warn_once("test:distinct:a", "A"));
|
||
assert!(warn_once("test:distinct:b", "B"));
|
||
assert_eq!(warn_recorder::emitted_count(), 2, "两个不同的 key ⇒ 两行 WARN");
|
||
}
|
||
|
||
#[test]
|
||
fn compatible_declaration_emits_no_warn_line() {
|
||
// 副作用的**反向**:不该告警时就一行都不许打
|
||
let _g = test_guard();
|
||
reset_warn_state();
|
||
let (allowed, warned) = check_protocol_with_warn(Some("1.9"));
|
||
assert!(allowed, "同 major ⇒ 放行");
|
||
assert!(!warned, "兼容的声明不该告警");
|
||
assert_eq!(
|
||
warn_recorder::emitted_count(),
|
||
0,
|
||
"兼容的声明不得打任何 WARN"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn flood_emitted_line_count_is_capped_at_256() {
|
||
// 🔴 「洪水量封顶」必须在**实际输出行数**层被断言
|
||
// (不是布尔计数、不是集合长度 —— 那两个在副作用放大时依然是对的)
|
||
let _g = test_guard();
|
||
reset_warn_state();
|
||
for i in 0..1024 {
|
||
let _ = warn_once_variable(&format!("test:volume4:{}", i), "灌水");
|
||
}
|
||
assert!(
|
||
warn_recorder::emitted_count() <= 256,
|
||
"实际打出的行数必须封顶(brief 约定 256),实际 {} 行",
|
||
warn_recorder::emitted_count()
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn emitted_line_carries_the_warn_prefix() {
|
||
// 🔴 前缀是运维检索这条信号的方式(「老客户端还在线上」)⇒ 必须被钉住
|
||
let _g = test_guard();
|
||
reset_warn_state();
|
||
warn_once("test:prefix:x", "内容");
|
||
let line = warn_recorder::last().expect("应发出了一条 WARN");
|
||
assert!(
|
||
line.starts_with("[tdc-connector] WARN "),
|
||
"告警行必须带 [tdc-connector] WARN 前缀:{:?}",
|
||
line
|
||
);
|
||
assert_eq!(line, "[tdc-connector] WARN 内容", "整行内容必须逐字匹配");
|
||
}
|
||
|
||
#[test]
|
||
fn missing_declaration_message_states_header_and_version() {
|
||
// 🔴 消息**内容**必须被钉住:header 名、本端版本、二者顺序
|
||
let _g = test_guard();
|
||
reset_warn_state();
|
||
let _ = check_protocol_with_warn(None);
|
||
let line = warn_recorder::last().expect("应发出了一条 WARN");
|
||
assert_eq!(
|
||
line,
|
||
expected_missing_line(),
|
||
"固定路径告警行必须逐字匹配(含 header 名与本端版本)"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn incompatible_message_states_peer_and_local_version() {
|
||
// 🔴 「对端/本端」标签不可对调,且两个版本号都必须出现
|
||
let msg = incompatible_message(&SafePeer::new("2.0"));
|
||
assert_eq!(
|
||
msg,
|
||
format!(
|
||
"跨端协议版本不兼容(对端 2.0,本端 {}),请升级对端",
|
||
PROTOCOL_VERSION
|
||
),
|
||
"不兼容消息必须逐字匹配(对端 = 净化后的对端值,本端 = PROTOCOL_VERSION)"
|
||
);
|
||
}
|
||
|
||
// ---- 源级守卫 + 子进程真捕获:钉住「真实输出通道还在、且内容正确」 ----
|
||
|
||
/// 源级守卫:`emit_warn` 里必须**恰好一处**把共享的 `line` 打到标准错误。
|
||
///
|
||
/// 为什么需要它:记录器是**测试替身** ⇒ 真实输出整行被删掉时它照旧记录
|
||
/// ⇒ 只靠记录器断言抓不到「告警通道整个消失」。
|
||
///
|
||
/// ⚠️ 本守卫是**文本**守卫:它钉住「那一行还在、且打印的是共享的 `line`」,
|
||
/// 但**不能**证明「这条输出真的落到了 fd 2」—— 那由子进程用例负责。
|
||
#[test]
|
||
fn emit_warn_source_prints_the_shared_line_exactly_once() {
|
||
let src = include_str!("protocol.rs");
|
||
let start = src.find("fn emit_warn(").expect("emit_warn 必须存在");
|
||
let tail = &src[start..];
|
||
let end = tail.find("\n}").expect("emit_warn 必须有函数体");
|
||
let body = &tail[..end];
|
||
|
||
// 🔴 needle 在**运行时**拼接 ⇒ 本文件源码里不会出现连续的该词 ⇒ 不会自匹配
|
||
let needle = ["eprint", "ln!"].concat();
|
||
let hits: Vec<usize> = body.match_indices(needle.as_str()).map(|(i, _)| i).collect();
|
||
assert_eq!(
|
||
hits.len(),
|
||
1,
|
||
"emit_warn 里必须恰好一处真实标准错误输出:{:?}",
|
||
body
|
||
);
|
||
let at = hits[0];
|
||
let call_end = at + body[at..].find(';').expect("输出语句必须以分号结尾");
|
||
let p = ["eprint", "ln"].concat();
|
||
let accepted = [
|
||
format!("{}!(\"{}\", line)", p, "{}"),
|
||
format!("{}!({{line}})", p),
|
||
];
|
||
assert!(
|
||
accepted.iter().any(|a| a == &body[at..call_end]),
|
||
"真实输出必须打印共享的那一行 `line`,实际:{:?}",
|
||
&body[at..call_end]
|
||
);
|
||
}
|
||
|
||
/// 子进程探针:**只在子进程里跑**(父用例用 `--exact ... --ignored --nocapture` 启动它)。
|
||
///
|
||
/// ⚠️ libtest 的输出捕获是**线程局部**的 ⇒ 父进程里普通线程的输出仍会被 libtest 吞掉
|
||
/// ⇒ 必须靠**子进程**才能看到真实的 fd 2。
|
||
#[test]
|
||
#[ignore]
|
||
fn stderr_probe_helper() {
|
||
// 只负责在子进程里触发两条真实告警;断言全在父用例里做。
|
||
let _ = check_protocol_with_warn(None);
|
||
let _ = check_protocol_with_warn(Some("9.9"));
|
||
}
|
||
|
||
#[test]
|
||
fn stderr_really_receives_the_exact_warn_lines() {
|
||
let exe = std::env::current_exe().expect("应能拿到测试二进制路径");
|
||
let out = std::process::Command::new(&exe)
|
||
.args([
|
||
"--exact",
|
||
"protocol::tests::stderr_probe_helper",
|
||
"--ignored",
|
||
"--nocapture",
|
||
"--test-threads=1",
|
||
])
|
||
.output()
|
||
.expect("应能启动子进程");
|
||
let stdout = String::from_utf8_lossy(&out.stdout).to_string();
|
||
let stderr = String::from_utf8_lossy(&out.stderr).to_string();
|
||
assert!(
|
||
stdout.contains("1 passed"),
|
||
"子进程必须真的跑到那条 helper 用例:stdout={:?}",
|
||
stdout
|
||
);
|
||
|
||
let missing = expected_missing_line();
|
||
let incompatible = expected_incompatible_line("9.9");
|
||
for line in [&missing, &incompatible] {
|
||
assert_eq!(
|
||
stderr.lines().filter(|l| *l == line.as_str()).count(),
|
||
1,
|
||
"真实 stderr 里这一行必须恰好出现一次:{:?}\nstderr={:?}",
|
||
line,
|
||
stderr
|
||
);
|
||
}
|
||
assert_eq!(
|
||
stderr
|
||
.lines()
|
||
.filter(|l| l.starts_with("[tdc-connector] WARN "))
|
||
.count(),
|
||
2,
|
||
"真实 stderr 里恰好两条 WARN 行:stderr={:?}",
|
||
stderr
|
||
);
|
||
}
|
||
}
|