Files
ONE/backend/internal/admin/meta_test.go
T

63 lines
2.4 KiB
Go

package admin
import (
"strings"
"testing"
"oneblog/internal/model"
)
func TestSummarizeMarkdown(t *testing.T) {
md := "## 标题\n\n这是**正文**的第一段,含[链接](https://x.com)与图片:\n\n![封面](https://a.com/1.png)\n\n```go\ncode ignored\n```\n\n后续内容"
got := summarizeMarkdown(md, 110)
for _, bad := range []string{"#", "**", "![]", "```", "code ignored"} {
if strings.Contains(got, bad) {
t.Errorf("summary 含语法残留 %q: %q", bad, got)
}
}
if !strings.Contains(got, "链接") || !strings.HasPrefix(got, "这是") {
t.Errorf("summary 应以正文开头并保留链接文字: %q", got)
}
long := strings.Repeat("长", 200)
if got := summarizeMarkdown(long, 110); len([]rune(got)) != 111 || !strings.HasSuffix(got, "…") {
t.Errorf("超长应截到 110+省略号, got %d runes", len([]rune(got)))
}
}
func TestFirstImage(t *testing.T) {
md := "前言\n\n![封面](https://a.com/1.png)\n\n![第二张](https://a.com/2.png)"
if got := firstImage(md); got != "https://a.com/1.png" {
t.Errorf("firstImage = %q", got)
}
if got := firstImage("没有图片"); got != "" {
t.Errorf("无图应返回空, got %q", got)
}
}
func TestAutoMeta(t *testing.T) {
in := model.PostInput{Kind: model.KindLong, ContentMd: "# T\n\n正文内容 ![图](https://a.com/x.png)"}
autoMeta(&in, nil)
if in.Summary == "" || in.CoverURL != "https://a.com/x.png" {
t.Errorf("空字段应自动填充: summary=%q cover=%q", in.Summary, in.CoverURL)
}
// 站主已填的不能覆盖
in2 := model.PostInput{Kind: model.KindLong, ContentMd: "正文", Summary: "手写的", CoverURL: ""}
autoMeta(&in2, nil)
if in2.Summary != "手写的" {
t.Errorf("手写摘要不应被覆盖: %q", in2.Summary)
}
// 更新路径:新值与旧值都空才补——主动清空的保得住
cleared := model.PostInput{Kind: model.KindLong, ContentMd: "正文", Summary: "", CoverURL: ""}
cur := model.Post{Summary: "旧摘要", CoverURL: "旧封面"}
autoMeta(&cleared, &cur)
if cleared.Summary != "" || cleared.CoverURL != "" {
t.Errorf("主动清空不应复活: summary=%q cover=%q", cleared.Summary, cleared.CoverURL)
}
// 新旧都空 → 生成
never := model.PostInput{Kind: model.KindLong, ContentMd: "正文 ![图](/uploads/a.png)"}
autoMeta(&never, &model.Post{})
if never.CoverURL != "/uploads/a.png" {
t.Errorf("新旧都空应取首图: %q", never.CoverURL)
}
}