Files
tamabox/route/question/share_layout_test.go
T
tamakyi d51629ef2f fix(share): 字体缺失不再永久失败;二维码按模块整数倍绘制
测试环境部署后分享卡整站 500「字体文件未配置或无法加载」。根因不是代码
回退,而是字体从来就不在仓库里:static/fonts/ 既没有入库(git 历史为空),
也没有 embed,凡是按仓库新建的环境都缺这个文件,只有手工补过字体的老环境
才正常。

- getFont 不再用 sync.Once 永久缓存失败:补上字体文件即生效,无需重启;
  失败时错误信息带上「已尝试的路径」,排障不用再猜是配置还是文件
- 候选路径:font_path → static/fonts/*.{otf,ttf,ttc} → 常见系统 CJK 字体,
  换过字体文件名也能用
- app.sample.ini 注明字体必须自备、缺失的后果

顺带做 P1 的第一项:generateQR 改为按模块整数倍出图(41 模块 @165px →
每模块 4px、符号 164px 居中)。原先是 256px 生成后最近邻缩到 165px,
每模块 4.02px,模块宽窄相差 1px,小尺寸二次压缩后更容易扫不动。
内嵌头像改为按目标尺寸等比(size*48/256)+ 2px 白边,静默区不受影响。

守门测试新增两条:TestGenerateQRIsModuleAligned(扫描线游程必须是模块
宽度的整数倍,变异成等比缩放后立刻 FAIL)、TestGenerateQRWithLogo
(中心是头像、四角静默区纯白)。
2026-10-22 22:33:22 +08:00

282 lines
8.7 KiB
Go

package question
import (
"image"
"image/color"
"image/draw"
"image/png"
"os"
"path/filepath"
"testing"
"github.com/golang/freetype"
"github.com/golang/freetype/truetype"
qrcode "github.com/skip2/go-qrcode"
"github.com/tamakyi/TamaBox/internal/conf"
)
// 分享卡测试需要一份真实字体;中文站点部署时 conf.App.FontPath 必然存在,
// 本机开发/CI 缺失时跳过,避免把「没有字体」当成排版错误。
func TestMain(m *testing.M) {
if _, err := os.Stat(conf.App.FontPath); err != nil {
for _, candidate := range []string{
"C:/Windows/Fonts/NotoSansSC-VF.ttf",
"C:/Windows/Fonts/msyh.ttc",
"/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
} {
if _, err := os.Stat(candidate); err == nil {
conf.App.FontPath = candidate
break
}
}
}
os.Exit(m.Run())
}
func requireFont(t *testing.T) *truetype.Font {
t.Helper()
ft, err := getFont()
if err != nil {
t.Skipf("no usable font (%v), skip share card layout tests", err)
}
return ft
}
// measureTextWidth 必须与 freetype 实际笔位推进一致,否则居中会重新出现偏移。
func TestMeasureTextWidthMatchesAdvance(t *testing.T) {
requireFont(t)
cases := []struct {
text string
size float64
}{
{"https://box.shiroko.one/_/tamakyi", FontSizeLink},
{"box.shiroko.one/_/tamakyi", 13},
{"ask.some-quite-long-domain-name.example.com", LinkMinSize},
{"Powered by 狼的提问箱", FontSizeFooter},
{"扫码向我匿名提问", FontSizeQRHint},
}
for _, c := range cases {
dst := image.NewRGBA(image.Rect(0, 0, 1400, 80))
fctx := freetype.NewContext()
fctx.SetFont(requireFont(t))
fctx.SetDPI(72)
fctx.SetFontSize(c.size)
fctx.SetSrc(image.NewUniform(color.Black))
fctx.SetDst(dst)
pen, err := fctx.DrawString(c.text, freetype.Pt(0, 60))
if err != nil {
t.Fatalf("draw %q: %v", c.text, err)
}
want := float64(pen.X) / 64.0
if got := measureTextWidth(c.text, c.size); got != want {
t.Errorf("%q @%.1f: measure=%.2f, advance=%.2f", c.text, c.size, got, want)
}
}
}
// 任意长度的链接都必须收进卡片,且不得缩到不可读。
func TestLayoutLinkFitsCard(t *testing.T) {
requireFont(t)
urls := []string{
"box.shiroko.one/_/tamakyi",
"box-dev-api.337845818.best/_/tamakyi",
"ask.some-quite-long-domain-name.example.com/_/tamakyi",
"questions.tamabox-community.example.org/anon/box/_/a-rather-long-handle-name",
"averyveryveryverylongdomainnamethatkeepsgoingandonandonforever.example/_/x",
}
for _, u := range urls {
lines, size := layoutLink(u)
if size < LinkMinSize {
t.Errorf("%q: font size %.2f below floor %.2f", u, size, LinkMinSize)
}
if len(lines) > 2 {
t.Errorf("%q: got %d lines, want <=2", u, len(lines))
}
for _, line := range lines {
if w := measureTextWidth(line, size); w > float64(LinkMaxWidth) {
t.Errorf("%q: line %q is %.1fpx, card allows %dpx", u, line, w, LinkMaxWidth)
}
}
}
}
// 居中必须落在二维码卡片中线上(按真实着墨边界判断,允许左右侧边距带来的 3px 内偏差)。
func TestDrawTextCenteredIsCentered(t *testing.T) {
requireFont(t)
cx := QRCardX + QRCardW/2
for _, text := range []string{
"box.shiroko.one/_/tamakyi",
"box-dev-api.337845818.best/_/tamakyi",
"Powered by 狼的提问箱",
} {
canvas := image.NewRGBA(image.Rect(0, 0, CardWidth, CardHeight))
draw.Draw(canvas, canvas.Bounds(), &image.Uniform{ColorWhite}, image.Point{}, draw.Src)
fctx := freetype.NewContext()
fctx.SetFont(requireFont(t))
fctx.SetDPI(72)
drawTextCentered(canvas, text, cx, 300, FontSizeLink, ColorDarkText, fctx)
minX, maxX := -1, -1
for x := 0; x < CardWidth; x++ {
for y := 250; y < 320; y++ {
if r, _, _, a := canvas.At(x, y).RGBA(); a > 40 && r < 0x8000 {
if minX < 0 {
minX = x
}
maxX = x
break
}
}
}
if minX < 0 {
t.Fatalf("%q: nothing drawn", text)
}
if center := (minX + maxX) / 2; abs(center-cx) > 3 {
t.Errorf("%q: ink center %d, want %d (±3)", text, center, cx)
}
if maxX > QRCardX+QRCardW || minX < QRCardX {
t.Errorf("%q: ink [%d,%d] escapes card [%d,%d]", text, minX, maxX, QRCardX, QRCardX+QRCardW)
}
}
}
// 内嵌头像不能吃掉静默区(否则扫码器找不到边界),且必须真的画在中心。
func TestGenerateQRWithLogo(t *testing.T) {
logo := image.NewRGBA(image.Rect(0, 0, 64, 40))
draw.Draw(logo, logo.Bounds(), &image.Uniform{color.RGBA{200, 40, 40, 255}}, image.Point{}, draw.Src)
img, err := generateQR("https://box.shiroko.one/_/tamakyi", logo, QRCodeSize)
if err != nil {
t.Fatal(err)
}
r, _, _, _ := img.At(QRCodeSize/2, QRCodeSize/2).RGBA()
if r < 0x8000 || r > 0xf000 {
t.Errorf("center pixel should be the logo color, got %#x", r)
}
for _, p := range []image.Point{{0, 0}, {QRCodeSize - 1, 0}, {0, QRCodeSize - 1}, {QRCodeSize - 1, QRCodeSize - 1}} {
r, g, b, _ := img.At(p.X, p.Y).RGBA()
if r != 0xffff || g != 0xffff || b != 0xffff {
t.Errorf("quiet zone at %v is not white: %#x %#x %#x", p, r, g, b)
}
}
}
func abs(v int) int {
if v < 0 {
return -v
}
return v
}
// 二维码必须按模块整数倍绘制:任何宽度落差的游程都意味着模块被拉伸,
// 小尺寸(微信/QQ 二次压缩后)最容易出现「扫不动」。
func TestGenerateQRIsModuleAligned(t *testing.T) {
const url = "https://box.shiroko.one/_/tamakyi"
for _, size := range []int{QRCodeSize, QQRSize} {
img, err := generateQR(url, nil, size)
if err != nil {
t.Fatal(err)
}
if got := img.Bounds().Dx(); got != size {
t.Fatalf("size %d: got width %d", size, got)
}
probe, err := qrcode.New(url, qrcode.High)
if err != nil {
t.Fatal(err)
}
modules := len(probe.Bitmap())
perModule := size / modules
if perModule < 1 {
t.Fatalf("size %d cannot hold %d modules", size, modules)
}
start := (size - modules*perModule) / 2
// 中间一行:所有黑白游程(限定在符号区域内)都必须是模块宽度的整数倍
y := size / 2
runLen := 0
for x := start; x < start+modules*perModule; x++ {
r, _, _, _ := img.At(x, y).RGBA()
black := r < 0x8000
if x == start {
runLen = 1
continue
}
prevR, _, _, _ := img.At(x-1, y).RGBA()
if (prevR < 0x8000) != black {
if runLen%perModule != 0 {
t.Fatalf("size %d: run of %dpx at x=%d is not a multiple of module %d",
size, runLen, x-runLen, perModule)
}
runLen = 1
continue
}
runLen++
}
if runLen%perModule != 0 {
t.Fatalf("size %d: trailing run %dpx not a multiple of %d", size, runLen, perModule)
}
}
}
// 视觉自检:TEST_PREVIEW=1 时把链接区渲成 PNG,人工确认断行与对齐。
func TestShareCardLinkPreview(t *testing.T) {
if os.Getenv("TEST_PREVIEW") == "" {
t.Skip("set TEST_PREVIEW=1 to write preview images")
}
requireFont(t)
outDir := os.Getenv("TEST_PREVIEW_DIR")
if outDir == "" {
outDir = filepath.Join("..", "..", "outputs", "sharecard-preview")
}
if err := os.MkdirAll(outDir, 0o755); err != nil {
t.Fatal(err)
}
cases := map[string]string{
"short": "box.shiroko.one/_/tamakyi",
"dev": "box-dev-api.337845818.best/_/tamakyi",
"long": "ask.some-quite-long-domain-name.example.com/_/tamakyi",
"verylong": "questions.tamabox-community.example.org/anon/box/_/a-rather-long-handle-name",
}
for name, display := range cases {
canvas := image.NewRGBA(image.Rect(0, 0, QRCardW, QRCardH))
draw.Draw(canvas, canvas.Bounds(), &image.Uniform{color.NRGBA{246, 246, 246, 255}}, image.Point{}, draw.Src)
drawRoundedRect(canvas, canvas.Bounds(), ColorWhite, 18)
fctx := freetype.NewContext()
fctx.SetFont(requireFont(t))
fctx.SetDPI(72)
lines, size := layoutLink(display)
const qrToHintGap, hintLineHeight, hintToSepGap, sepHeight, sepToLinkGap, linkLineHeight = 26, 17, 21, 1, 21, 15
total := QRCodeSize + qrToHintGap + hintLineHeight + hintToSepGap + sepHeight + sepToLinkGap + linkLineHeight*len(lines)
startY := (QRCardH - total) / 2
qr, err := generateQR("https://"+display, nil, QRCodeSize)
if err != nil {
t.Fatal(err)
}
draw.Draw(canvas, image.Rect(QRCodeX, startY, QRCodeX+QRCodeSize, startY+QRCodeSize), qr, image.Point{}, draw.Over)
hintY := startY + QRCodeSize + qrToHintGap + hintLineHeight
drawTextCentered(canvas, "扫码向我匿名提问", QRCardW/2, hintY, FontSizeQRHint, ColorHintGray, fctx)
sepY := hintY + hintToSepGap
drawLine(canvas, QRCardW/2-90, sepY, QRCardW/2+90, sepY, color.NRGBA{200, 200, 200, 180})
linkY := sepY + sepToLinkGap + linkLineHeight
for i, line := range lines {
drawTextCentered(canvas, line, QRCardW/2, linkY+i*linkLineHeight, size, ColorDarkText, fctx)
}
f, err := os.Create(filepath.Join(outDir, name+".png"))
if err != nil {
t.Fatal(err)
}
if err := png.Encode(f, canvas); err != nil {
t.Fatal(err)
}
f.Close()
}
}