test(host): HostFn id/name/params 一致性测试;refactor: 转义函数去重

一、先暴露问题:写 4 个一致性测试后发现——
- id 空间是**稀疏**的(10 个退役 id),不是连续的;测试按"每个已分配 id 都能还原"重写
- Access 变体只有隐式判别值,补 `= 212` 使之显式(避免重排时静默错位)
- 四个测试现在锁定:id→as_u16 往返、name→from_name 往返、名称唯一、
  required/optional 不重叠且无重复参数。审计提到的 from_name/name 漂移由此可被捕获。

二、转义去重
- urlencoding_encode 与 urlencoding_path 逐字相同 → 合并为 urlencoding_path(pub(crate))
- escape_js_string 两份:debug_page 的副本漏了 U+2028/2029 转义(真实缺陷)
  → 保留 html 的完整版并 pub(crate),debug_page 改为引用

cargo build 零警告;cargo test --release 609 passed / 0 failed(605 + 4 个新测试)。
This commit is contained in:
cflmy committed 2026-10-22 15:42:42 +08:00
1 parent a14a6e221d
commit 932403237a
3 files changed
+85 -31

No files matched your search

+78 -1
View File
@@ -219,7 +219,7 @@ pub enum HostFn {
ForeignSessionList = 210,
ForeignSessionInterrupt = 211,
/// `<TAB>` M7: `access(集合, 键)` — polymorphic collection access (legacy index).
Access,
Access = 212,
}
@@ -1973,3 +1973,80 @@ fn require<'a>(bound: &'a HashMap<String, Value>, key: &str) -> Result<&'a Value
.get(key)
.ok_or_else(|| format!("host call missing `{key}`"))
}
#[cfg(test)]
mod tests {
use super::HostFn;
/// Every host id must round-trip through `from_u16` / `as_u16`, and every
/// canonical name through `from_name` / `name`. This pins the drift the
/// audit found (`from_name` accepted `http_get` while `name()` emitted
/// `host_http_get`) without rewriting the five tables.
#[test]
fn every_assigned_id_round_trips() {
// The id space is intentionally sparse: retired ids are never reused
// (bytecode from an older build must not silently change meaning).
let mut seen = 0;
for id in 1..=400u16 {
let Some(f) = HostFn::from_u16(id) else {
continue; // retired id
};
seen += 1;
assert_eq!(f.as_u16(), id, "id {id} → {f:?} → {}", f.as_u16());
}
assert!(seen >= 200, "expected ~200 live host ids, got {seen}");
}
#[test]
fn every_id_has_a_name_that_round_trips() {
for id in 1..=300u16 {
let Some(f) = HostFn::from_u16(id) else {
continue;
};
let name = f.name();
assert!(!name.is_empty(), "id {id} has an empty name");
assert_eq!(
HostFn::from_name(name),
Some(f),
"id {id}: name `{name}` does not round-trip"
);
}
}
#[test]
fn names_are_unique() {
let mut seen = std::collections::HashMap::new();
for id in 1..=300u16 {
let Some(f) = HostFn::from_u16(id) else {
continue;
};
let name = f.name();
if let Some(prev) = seen.insert(name.to_string(), id) {
panic!("duplicate host name `{name}` at ids {prev} and {id}");
}
}
}
#[test]
fn required_and_optional_params_are_disjoint() {
for id in 1..=300u16 {
let Some(f) = HostFn::from_u16(id) else {
continue;
};
let req = f.required_params();
let opt = f.optional_params();
for r in req {
assert!(
!opt.contains(r),
"{:?} lists `{r}` as both required and optional",
f
);
}
let all = f.all_params();
let mut uniq = all.clone();
uniq.sort_unstable();
uniq.dedup();
assert_eq!(uniq.len(), all.len(), "{f:?} has duplicate params");
}
}
}
+1 -15
View File
@@ -3,6 +3,7 @@
//! Toolbar · Structure (breakpoints) · Variables / Breakpoints / Frame · Console
use std::path::{Path, PathBuf};
use super::html::escape_js_string;
use crate::view::html::{escape, nav_html, LinkMode};
use crate::view::render::{render_function_outline, render_module_structure_mode, StructureMode};
@@ -144,21 +145,6 @@ window.MARQDO_FILE_PATH = {path_js};
layout_debug(rel, &body)
}
fn escape_js_string(s: &str) -> String {
let mut out = String::from('"');
for c in s.chars() {
match c {
'\\' => out.push_str("\\\\"),
'"' => out.push_str("\\\""),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
c if c.is_control() => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
out
}
fn layout_debug(title: &str, main: &str) -> String {
format!(
+6 -15
View File
@@ -2805,7 +2805,7 @@ fn open_nav_group(out: &mut String, folder: &str, active: Option<&str>) {
fn href_file(links: &LinkMode, target_rel: &str) -> String {
match links {
LinkMode::Live => format!("/file?path={}", urlencoding_encode(target_rel)),
LinkMode::Live => format!("/file?path={}", urlencoding_path(target_rel)),
LinkMode::Static { from: None } => format!("pages/{}.html", target_rel),
LinkMode::Static {
from: Some(from_rel),
@@ -2843,18 +2843,6 @@ fn relative_page_href(from_rel: &str, to_rel: &str) -> String {
format!("{}{}", "../".repeat(ups), to_path.to_string_lossy().replace('\\', "/"))
}
fn urlencoding_encode(s: &str) -> String {
let mut out = String::new();
for b in s.bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => {
out.push(b as char);
}
_ => out.push_str(&format!("%{b:02X}")),
}
}
out
}
pub fn page_index(files: &[PathBuf], only: Option<&Path>, links: &LinkMode) -> String {
let nav = nav_html(files, None, links);
@@ -4374,7 +4362,8 @@ fn plan_process_list(events: Option<&Vec<serde_json::Value>>) -> String {
format!(r#"<ul class="plan-process">{}</ul>"#, items.join(""))
}
fn urlencoding_path(s: &str) -> String {
/// Percent-encode a path for `?path=` (shared by every link builder).
pub(crate) fn urlencoding_path(s: &str) -> String {
let mut out = String::new();
for b in s.as_bytes() {
match *b {
@@ -4387,7 +4376,9 @@ fn urlencoding_path(s: &str) -> String {
out
}
fn escape_js_string(s: &str) -> String {
/// Escape a Rust string as a JS string literal (keeps U+2028/2029 escaped,
/// which the debug-page copy used to miss).
pub(crate) fn escape_js_string(s: &str) -> String {
let mut out = String::from('"');
for c in s.chars() {
match c {