// input_truncation_test.go -- 输入过大截断防御点的单元测试(任务 7.6 防御点 d). // // 由于截断逻辑内嵌在 runLoop 中(需要 ch 推送 WarningEvent), // 这里通过复现相同逻辑的白盒测试来验证行为, // 以及对 maxInputChars 常量做边界检验. package engine import ( "strings" "testing" ) // TestMaxInputChars_Const 验证 maxInputChars 常量值正确. func TestMaxInputChars_Const(t *testing.T) { if maxInputChars != 100_000 { t.Errorf("maxInputChars 应为 100000,实际: %d", maxInputChars) } } // TestInputTruncation_Logic 白盒测试:验证截断逻辑正确. // 复现 runLoop 中的截断逻辑: // // if len(userPrompt) > maxInputChars { // userPrompt = userPrompt[:maxInputChars] // // push WarningEvent // } func TestInputTruncation_Logic(t *testing.T) { // 构造恰好超过 maxInputChars 的输入(ASCII) oversized := strings.Repeat("A", maxInputChars+100) var truncated string var warned bool if len(oversized) > maxInputChars { truncated = oversized[:maxInputChars] warned = true } else { truncated = oversized } if !warned { t.Fatal("超大输入应触发截断警告") } if len(truncated) != maxInputChars { t.Errorf("截断后长度应为 %d,实际: %d", maxInputChars, len(truncated)) } // 截断部分应全是 'A' for i, ch := range truncated { if ch != 'A' { t.Errorf("第 %d 字符不是 'A'", i) break } } } // TestInputTruncation_ExactLimit 测试刚好等于限制时不截断. func TestInputTruncation_ExactLimit(t *testing.T) { exact := strings.Repeat("B", maxInputChars) var truncated string var warned bool if len(exact) > maxInputChars { truncated = exact[:maxInputChars] warned = true } else { truncated = exact } if warned { t.Error("刚好等于限制时不应截断") } if len(truncated) != maxInputChars { t.Errorf("等于限制时长度应保持 %d,实际: %d", maxInputChars, len(truncated)) } } // TestInputTruncation_BelowLimit 测试小于限制时不截断. func TestInputTruncation_BelowLimit(t *testing.T) { small := "hello world" var truncated string var warned bool if len(small) > maxInputChars { truncated = small[:maxInputChars] warned = true } else { truncated = small } if warned { t.Error("小于限制时不应截断") } if truncated != small { t.Errorf("小于限制时内容应保持不变,期望 %q,实际: %q", small, truncated) } } // TestInputTruncation_Empty 测试空字符串不截断. func TestInputTruncation_Empty(t *testing.T) { empty := "" var warned bool if len(empty) > maxInputChars { warned = true } if warned { t.Error("空字符串不应截断") } } // TestInputTruncation_WarningEventCode 验证 WarningEvent 的 Code 字段符合规范. // 防止日后有人随意改 Code 导致消费层监控告警漏报. func TestInputTruncation_WarningEventCode(t *testing.T) { // 预期的警告码 expectedCode := "input_truncated" // 构造截断触发时的 WarningEvent event := &WarningEvent{ Code: expectedCode, Message: "input truncated to 100K characters", } if event.Code != "input_truncated" { t.Errorf("WarningEvent.Code 应为 'input_truncated',实际: %q", event.Code) } if !strings.Contains(event.Message, "100K") { t.Errorf("WarningEvent.Message 应包含 '100K',实际: %q", event.Message) } }