//go:build !service // meitu_service_test.go — 「美图」工具纯函数单元测试。 package main import ( "strings" "testing" ) // TestMeituCategories 验证分类注册表:至少包含「女装」且字段完整。 func TestMeituCategories(t *testing.T) { svc := NewMeituService() cats := svc.Categories() if len(cats) == 0 { t.Fatal("Categories() 不应为空") } var found bool for _, c := range cats { if c.ID == "beauty" && c.Name == "女装" && c.PostID == "108629" { found = true if c.URL == "" { t.Error("女装分类缺少 URL") } } } if !found { t.Fatalf("未找到「女装」分类,当前: %+v", cats) } } // TestMeituFindCategory 验证按 ID 查找分类。 func TestMeituFindCategory(t *testing.T) { svc := NewMeituService() if c := svc.findCategory("beauty"); c == nil { t.Fatal("findCategory(beauty) 应命中") } if c := svc.findCategory("nonexistent"); c != nil { t.Fatalf("findCategory(unknown) 应为 nil,得到 %+v", c) } } // TestParseMeituImages 验证从 API 响应提取图片: // 提取 content 内 、跳过非 http 地址、去重、携带作者与时间。 func TestParseMeituImages(t *testing.T) { resp := &meituAPIResponse{ Code: 0, Data: struct { TotalPages int `json:"total_pages"` CurrentPage int `json:"current_page"` List []struct { ID int64 `json:"id"` Author string `json:"author"` DateGmt string `json:"date_gmt"` Content string `json:"content"` } `json:"list"` }{ List: []struct { ID int64 `json:"id"` Author string `json:"author"` DateGmt string `json:"date_gmt"` Content string `json:"content"` }{ { ID: 1, Author: "四月天", DateGmt: "2026-11-24", Content: ``, }, { ID: 2, Author: "路人", DateGmt: "2026-11-23", Content: `

正文

` + `` + // 非 http 跳过 ``, // 相对路径跳过 }, { ID: 3, Author: "路人", DateGmt: "2026-11-23", Content: ``, // 重复 → 去重 }, }, }, } imgs := parseMeituImages(resp) if len(imgs) != 2 { t.Fatalf("parseMeituImages() 应去重后得 2 张,得到 %d: %+v", len(imgs), imgs) } if imgs[0].URL != "https://img.wangmoyu.com/mw600/aaa.jpeg" { t.Errorf("首图 URL = %q", imgs[0].URL) } if imgs[0].Author != "四月天" || imgs[0].Date != "2026-11-24" { t.Errorf("首图作者/时间 = %q/%q", imgs[0].Author, imgs[0].Date) } if imgs[1].URL != "https://img.wangmoyu.com/mw600/bbb.jpeg.webp" { t.Errorf("二图 URL = %q", imgs[1].URL) } } // TestParseMeituImagesEmpty 验证空响应/无图片时返回空列表。 func TestParseMeituImagesEmpty(t *testing.T) { if got := parseMeituImages(nil); len(got) != 0 { t.Fatalf("parseMeituImages(nil) = %+v, want empty", got) } resp := &meituAPIResponse{Code: 0} if got := parseMeituImages(resp); len(got) != 0 { t.Fatalf("parseMeituImages(空) = %+v, want empty", got) } } // TestMeituImgRe 验证正则只抓 http(s) 图片且大小写不敏感。 func TestMeituImgRe(t *testing.T) { content := `` + `` + `` ms := meituImgRe.FindAllStringSubmatch(content, -1) if len(ms) != 3 { t.Fatalf("正则应匹配 3 个 img,得到 %d", len(ms)) } if !strings.Contains(ms[0][1], "xx.JPEG") { t.Errorf("大写 SRC 未匹配: %q", ms[0][1]) } }