From 4e89412cde7facd5a0e9cb4f9dd673b7061e40a5 Mon Sep 17 00:00:00 2001 From: xfy Date: Mon, 15 Jun 2026 10:57:51 +0800 Subject: [PATCH] =?UTF-8?q?test(theme):=20=E6=89=A9=E5=85=85=E4=B8=BB?= =?UTF-8?q?=E9=A2=98=E6=A8=A1=E5=9D=97=E6=B5=8B=E8=AF=95=E8=A6=86=E7=9B=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 原仅 2 个 toggle 测试,补充后覆盖: - toggle 的对合性(连续切换两次回到原值) - Theme 的 PartialEq / Copy trait 行为 - 首屏预加载脚本的关键行为契约:读取 localStorage、 回退 prefers-color-scheme、添加 dark class、 包裹 try/catch 防止禁用 localStorage 时抛错 共 9 个测试,全部通过。 --- src/theme.rs | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/src/theme.rs b/src/theme.rs index b1654a2..c34e40b 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -210,4 +210,55 @@ mod tests { fn toggle_switches_dark_to_light() { assert_eq!(Theme::Dark.toggle(), Theme::Light); } + + #[test] + fn toggle_is_an_involution() { + // 连续切换两次应当回到原始主题。 + assert_eq!(Theme::Light.toggle().toggle(), Theme::Light); + assert_eq!(Theme::Dark.toggle().toggle(), Theme::Dark); + } + + #[test] + fn theme_derives_equality() { + // Theme 派生了 PartialEq,相同变体必须相等。 + assert_eq!(Theme::Light, Theme::Light); + assert_eq!(Theme::Dark, Theme::Dark); + assert_ne!(Theme::Light, Theme::Dark); + } + + #[test] + fn theme_is_copy() { + // 确认 Theme 实现了 Copy,赋值后原值仍可用。 + let a = Theme::Light; + let b = a; + assert_eq!(a, b); + // 再次使用 a,若未实现 Copy 则编译失败。 + let _ = a.toggle(); + } + + #[test] + fn theme_preload_script_adds_dark_class() { + // 预加载脚本必须包含给 documentElement 添加 dark class 的逻辑。 + assert!(THEME_PRELOAD_SCRIPT.contains("classList.add('dark')")); + } + + #[test] + fn theme_preload_script_reads_local_storage() { + // 预加载脚本必须读取 yggdrasil-theme 键,与 THEME_KEY 保持一致。 + assert!(THEME_PRELOAD_SCRIPT.contains("localStorage.getItem('yggdrasil-theme')")); + assert_eq!(THEME_KEY, "yggdrasil-theme"); + } + + #[test] + fn theme_preload_script_falls_back_to_prefers_color_scheme() { + // 当 localStorage 中无主题时,脚本应回退到系统颜色偏好。 + assert!(THEME_PRELOAD_SCRIPT.contains("prefers-color-scheme: dark")); + } + + #[test] + fn theme_preload_script_swallows_errors() { + // 预加载脚本必须包裹在 try/catch 中,避免禁用 localStorage 时抛错。 + assert!(THEME_PRELOAD_SCRIPT.contains("try")); + assert!(THEME_PRELOAD_SCRIPT.contains("catch")); + } }