Files
tamabox/internal/template/announcement_test.go
T
2026-10-22 15:08:24 +08:00

64 lines
2.1 KiB
Go

// Copyright 2026 tamakyi. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package template
import "testing"
func TestAnnouncementHTML(t *testing.T) {
cases := []struct {
name string
in string
want string
}{
{"纯文本原样输出", "机房维护通知", "机房维护通知"},
{"真实换行转 br", "第一行\n第二行", "第一行<br>第二行"},
{"字面量 \\n 也转 br", `第一行\n第二行`, "第一行<br>第二行"},
{"crlf 不产生多余 br", "第一行\r\n第二行", "第一行<br>第二行"},
{
"标签按字面转义",
`<script>alert(1)</script>`,
`&lt;script&gt;alert(1)&lt;/script&gt;`,
},
{
"地址自动变链接",
"详见 https://status.example.com/incident 谢谢",
`详见 <a href="https://status.example.com/incident" target="_blank" rel="noopener noreferrer nofollow">https://status.example.com/incident</a> 谢谢`,
},
{
"查询串的 & 被转义",
"https://example.com/a?b=1&c=2",
`<a href="https://example.com/a?b=1&amp;c=2" target="_blank" rel="noopener noreferrer nofollow">https://example.com/a?b=1&amp;c=2</a>`,
},
{
"句末中文标点不进链接",
"见 https://example.com/x。",
`见 <a href="https://example.com/x" target="_blank" rel="noopener noreferrer nofollow">https://example.com/x</a>。`,
},
{
"句末英文标点不进链接",
"https://example.com/x, thanks",
`<a href="https://example.com/x" target="_blank" rel="noopener noreferrer nofollow">https://example.com/x</a>, thanks`,
},
{
"裸 scheme 不当链接",
"https:// 后面没写地址",
"https:// 后面没写地址",
},
{
"引号无法逃逸属性",
`https://example.com/"><img src=x onerror=alert(1)>`,
`<a href="https://example.com/" target="_blank" rel="noopener noreferrer nofollow">https://example.com/</a>&#34;&gt;&lt;img src=x onerror=alert(1)&gt;`,
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got := string(AnnouncementHTML(c.in))
if got != c.want {
t.Fatalf("AnnouncementHTML(%q)\n got %q\n want %q", c.in, got, c.want)
}
})
}
}