vcom/internal/preview/preview_test.go
vrubelroman 5d36b76bbe feat(preview): pure Build over vfs with limits, tools timeout and fast highlighting (5B)
Build(ctx, req) never opens FIFOs, sockets or devices (Kind=Special;
U-P1-10), reads at most MaxBytes, keeps at most DirLimit directory entries
and MaxLines text lines, and honours ctx in reads, tools and highlighting.
pdftotext/pdfinfo/ffprobe run in their own process group with a 3 s timeout
and are killed with their children. A chroma formatter writes foreground
SGR only (no background, no regexp post-processing); the first
HighlightLines (400) lines are highlighted, so 64 KiB of Go takes ~20 ms
(was 190). Remote images are downloaded to an LRU cache only up to
max_remote_image_bytes (N-P1-16); a 32-entry result cache avoids rebuilds.
theme.ChromaStyle maps every built-in theme (U-P2); KindLabel fixes the
inverted label (U-P2).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 08:57:15 +03:00

387 lines
12 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package preview
import (
"bytes"
"context"
"errors"
"fmt"
"image"
"image/color"
"image/png"
"os"
"path/filepath"
"strings"
"syscall"
"testing"
"time"
"vcom/internal/testutil/fstree"
"vcom/internal/theme"
"vcom/internal/vfs"
"vcom/internal/vfs/localfs"
"vcom/internal/vfs/vfstest"
)
var (
bg = context.Background()
local = localfs.New()
)
func at(p string) vfs.Location { return vfs.Location{FS: local, Path: p} }
func pngBytes(t testing.TB, w, h int) []byte {
img := image.NewRGBA(image.Rect(0, 0, w, h))
img.Set(0, 0, color.RGBA{255, 0, 0, 255})
var b bytes.Buffer
if err := png.Encode(&b, img); err != nil {
t.Fatal(err)
}
return b.Bytes()
}
func TestFifoNotRead(t *testing.T) {
dir := t.TempDir()
fstree.Build(t, dir, fstree.Spec{fstree.FIFO("pipe"), fstree.Symlink("ln", "pipe")})
for _, name := range []string{"pipe", "ln"} {
t0 := time.Now()
res := Build(bg, Request{Loc: at(filepath.Join(dir, name))})
if el := time.Since(t0); el > 50*time.Millisecond {
t.Fatalf("%s: took %v (U-P1-10: a FIFO must not be opened)", name, el)
}
if res.Kind != Special || res.Err != nil {
t.Fatalf("%s: %+v", name, res)
}
}
if res := Build(bg, Request{Loc: at("/dev/zero")}); res.Kind != Special {
t.Fatalf("/dev/zero: %v", res.Kind)
}
}
// fakeTool writes an executable shell script.
func fakeTool(t *testing.T, body string) string {
p := filepath.Join(t.TempDir(), "tool")
if err := os.WriteFile(p, []byte("#!/bin/sh\n"+body+"\n"), 0o755); err != nil {
t.Fatal(err)
}
return p
}
func TestToolTimeout(t *testing.T) {
dir := t.TempDir()
pdf := filepath.Join(dir, "doc.pdf")
_ = os.WriteFile(pdf, []byte("%PDF-1.4 not really"), 0o644)
// The script's child (sleep) keeps stdout open: only a group kill ends it.
tools := &Tools{PdfToText: fakeTool(t, "sleep 10 & wait"), Timeout: 3 * time.Second}
t0 := time.Now()
res := Build(bg, Request{Loc: at(pdf), Tools: tools})
el := time.Since(t0)
if el > 3500*time.Millisecond {
t.Fatalf("returned after %v", el)
}
if res.Kind != Error || !errors.Is(res.Err, ErrToolTimeout) {
t.Fatalf("%+v", res)
}
// A working tool: output is used and capped.
tools = &Tools{PdfToText: fakeTool(t, `yes "page text" | head -c 100000`), Timeout: 3 * time.Second}
res = Build(bg, Request{Loc: at(pdf), Tools: tools, MaxBytes: 1000})
if res.Kind != PDF || len(strings.Join(res.Plain, "\n")) > 1000 || res.Plain[0] != "page text" {
t.Fatalf("pdf %v %d lines err=%v", res.Kind, len(res.Plain), res.Err)
}
}
func TestBuildCancelled(t *testing.T) {
dir := t.TempDir()
fstree.Build(t, dir, fstree.Spec{fstree.File("a.go", "package a\n")})
ctx, cancel := context.WithCancel(bg)
cancel()
res := Build(ctx, Request{Loc: at(filepath.Join(dir, "a.go"))})
if res.Kind != Error || !errors.Is(res.Err, context.Canceled) {
t.Fatalf("%+v", res)
}
// Cancel during a slow read.
ctx, cancel = context.WithCancel(bg)
slow := &vfstest.FaultFS{FS: local, Hook: func(op vfstest.Op, _ string) error {
if op == vfstest.OpRead {
cancel()
time.Sleep(10 * time.Millisecond)
}
return nil
}}
res = Build(ctx, Request{Loc: vfs.Location{FS: slow, Path: filepath.Join(dir, "a.go")}})
if !errors.Is(res.Err, context.Canceled) {
t.Fatalf("mid-read: %+v", res)
}
// Cancel during highlighting of a big file.
src := strings.Repeat("func f() { x := 1; _ = x }\n", 3000)
ctx, cancel = context.WithCancel(bg)
time.AfterFunc(time.Millisecond, cancel)
if _, err := Highlight(ctx, "big.go", src, "nord"); err != nil && !errors.Is(err, context.Canceled) {
t.Fatal(err)
}
}
func TestHighlightNoBackgroundSGR(t *testing.T) {
src := "package main\n\n// comment\nfunc main() {\n\tprintln(\"hi\", 42)\n}\n"
plain, _ := textLines(src, 100)
for _, th := range theme.Names() {
lines, err := Highlight(bg, "main.go", strings.Join(plain, "\n"), th)
if err != nil {
t.Fatal(err)
}
joined := strings.Join(lines, "\n")
if !strings.Contains(joined, "\x1b[") {
t.Fatalf("%s: nothing highlighted", th)
}
for _, seq := range strings.Split(joined, "\x1b[")[1:] {
params := strings.Split(seq[:strings.IndexByte(seq, 'm')], ";")
for i := 0; i < len(params); i++ {
switch p := params[i]; {
case p == "38" && i+1 < len(params) && params[i+1] == "2":
i += 4 // 38;2;r;g;b
case p == "38":
i += 2 // 38;5;n
case p == "48" || p == "49" || (len(p) == 2 && p[0] == '4') || (len(p) == 3 && p[:2] == "10"):
t.Fatalf("%s: background SGR %q", th, params)
}
}
}
if len(lines) != len(plain) {
t.Fatalf("%s: %d lines for %d", th, len(lines), len(plain))
}
}
// Lines and Plain match line by line.
dir := t.TempDir()
fstree.Build(t, dir, fstree.Spec{fstree.File("m.go", src)})
res := Build(bg, Request{Loc: at(filepath.Join(dir, "m.go")), Theme: "dracula"})
if res.Kind != Text || len(res.Lines) != len(res.Plain) || res.Plain[4] != " println(\"hi\", 42)" {
t.Fatalf("%+v", res.Plain)
}
}
func goSource(tb testing.TB) string {
b, err := os.ReadFile("highlight.go")
if err != nil {
tb.Fatal(err)
}
var s strings.Builder
for s.Len() < 64<<10 {
s.Write(b)
}
return s.String()[:64<<10]
}
func BenchmarkPreviewGo64K(b *testing.B) {
dir := b.TempDir()
p := filepath.Join(dir, "big.go")
_ = os.WriteFile(p, []byte(goSource(b)), 0o644)
b.ResetTimer()
for range b.N {
if res := Build(bg, Request{Loc: at(p), Theme: "github-dark"}); res.Kind != Text {
b.Fatal(res.Kind)
}
}
}
// A loose gate for the benchmark (target ≤ 40 ms, measured ~20 ms; was
// 190 ms). The margin covers -race (≈ ×8).
func TestPreviewGo64KFast(t *testing.T) {
if testing.Short() {
t.Skip()
}
r := testing.Benchmark(BenchmarkPreviewGo64K)
if per := time.Duration(r.NsPerOp()); per > 400*time.Millisecond {
t.Fatalf("Build on 64 KiB of Go: %v per op", per)
}
}
// remote makes a local FS look remote (no tools, no direct image path).
type remote struct{ vfs.FS }
func (remote) Kind() vfs.Kind { return vfs.KindSFTP }
func (remote) Volume() vfs.VolumeID { return "ssh:test" }
func TestRemoteImageSizeLimit(t *testing.T) {
dir := t.TempDir()
small := filepath.Join(dir, "small.png")
_ = os.WriteFile(small, pngBytes(t, 40, 30), 0o644)
big := filepath.Join(dir, "big.png")
data := pngBytes(t, 40, 30)
_ = os.WriteFile(big, append(data, make([]byte, 50000)...), 0o644) // decodable header, large file
cacheDir := filepath.Join(t.TempDir(), "img")
cache, err := NewImageCache(cacheDir, 0)
if err != nil {
t.Fatal(err)
}
opens := 0
rfs := remote{&vfstest.FaultFS{FS: local, Hook: func(op vfstest.Op, _ string) error {
if op == vfstest.OpOpen {
opens++
}
return nil
}}}
res := Build(bg, Request{Loc: vfs.Location{FS: rfs, Path: big}, Images: cache, MaxRemoteImageBytes: 10000})
if res.Kind != Image || res.Image == nil || !res.Image.TooLarge || res.Image.Local != "" {
t.Fatalf("big: %+v", res.Image)
}
if ents, _ := os.ReadDir(cacheDir); len(ents) != 0 {
t.Fatal("a too large remote image was downloaded (N-P1-16)")
}
res = Build(bg, Request{Loc: vfs.Location{FS: rfs, Path: small}, Images: cache, MaxRemoteImageBytes: 10000})
if res.Image == nil || res.Image.Local == "" || res.Meta.Width != 40 || res.Meta.Height != 30 {
t.Fatalf("small: %+v %v", res.Image, res.Err)
}
if b, _ := os.ReadFile(res.Image.Local); !bytes.Equal(b, pngBytes(t, 40, 30)) {
t.Fatal("cached copy differs")
}
before := opens
again := Build(bg, Request{Loc: vfs.Location{FS: rfs, Path: small}, Images: cache, MaxRemoteImageBytes: 10000})
if again.Image.Local != res.Image.Local || opens-before != 1 { // head read only, no second download
t.Fatalf("cache miss: opens %d", opens-before)
}
// Local images are referenced in place.
if r := Build(bg, Request{Loc: at(small)}); r.Image == nil || r.Image.Local != small {
t.Fatalf("local: %+v", r.Image)
}
}
func TestImageCacheEvicts(t *testing.T) {
dir := t.TempDir()
src := t.TempDir()
c, err := NewImageCache(filepath.Join(dir, "c"), 2500)
if err != nil {
t.Fatal(err)
}
var paths []string
for i := range 3 {
p := filepath.Join(src, fmt.Sprintf("%d.png", i))
_ = os.WriteFile(p, make([]byte, 1000), 0o644)
lp, err := c.Fetch(bg, remote{local}, p, 1000, time.Unix(int64(i), 0))
if err != nil {
t.Fatal(err)
}
paths = append(paths, lp)
}
if _, err := os.Stat(paths[0]); !os.IsNotExist(err) {
t.Fatal("oldest entry not evicted")
}
if _, err := os.Stat(paths[2]); err != nil {
t.Fatal(err)
}
// Reopened: kept within the budget.
c2, err := NewImageCache(filepath.Join(dir, "c"), 1500)
if err != nil || c2.total > 1500 {
t.Fatalf("%v total=%d", err, c2.total)
}
}
func TestDirPreviewLimited(t *testing.T) {
dir := t.TempDir()
var spec fstree.Spec
for i := range 100 {
spec = append(spec, fstree.File(fmt.Sprintf("f%03d", i), ""))
}
spec = append(spec, fstree.Dir("zdir"), fstree.File(".hidden", ""), fstree.Symlink("alink", "zdir"))
fstree.Build(t, dir, spec)
res := Build(bg, Request{Loc: at(dir), DirLimit: 10})
if res.Kind != Directory || len(res.Dir) != 10 || !res.Truncated {
t.Fatalf("%v %d %v", res.Kind, len(res.Dir), res.Truncated)
}
if res.Dir[0].Name != "alink" || res.Dir[1].Name != "zdir" || res.Dir[2].Name != "f000" {
t.Fatalf("order %s %s %s", res.Dir[0].Name, res.Dir[1].Name, res.Dir[2].Name)
}
for _, e := range res.Dir {
if e.Name == ".hidden" {
t.Fatal("hidden shown")
}
}
if cap(res.Dir) > 10 {
t.Fatalf("result pins the full listing: cap %d", cap(res.Dir))
}
if res := Build(bg, Request{Loc: at(dir), DirLimit: 1000, ShowHidden: true}); len(res.Dir) != 103 || res.Truncated {
t.Fatalf("all: %d", len(res.Dir))
}
}
func TestKindLabel(t *testing.T) {
cases := map[string]vfs.FileInfo{
"directory": {Name: "src", Mode: os.ModeDir},
"symlink": {Name: "l.go", Mode: os.ModeSymlink},
"fifo": {Name: "p", Mode: os.ModeNamedPipe},
"socket": {Name: "s", Mode: os.ModeSocket},
"device": {Name: "zero", Mode: os.ModeDevice | os.ModeCharDevice},
"go": {Name: "main.go"},
"tar.gz": {Name: "a.TAR.GZ"},
"file": {Name: "Makefile"},
}
for want, fi := range cases {
if got := KindLabel(fi); got != want {
t.Errorf("KindLabel(%q) = %q, want %q", fi.Name, got, want)
}
}
if KindLabel(vfs.FileInfo{Name: ".bashrc"}) != "file" {
t.Error("dot-file")
}
}
func TestBuildKinds(t *testing.T) {
dir := t.TempDir()
fstree.Build(t, dir, fstree.Spec{
fstree.File("empty", ""),
fstree.File("bin", "a\x00b\x00c"),
fstree.File("long.txt", strings.Repeat("line\n", 5000)),
fstree.Symlink("broken", "nowhere"),
fstree.File("song.mp3", "ID3 not really"),
})
_ = os.WriteFile(filepath.Join(dir, "pic.png"), pngBytes(t, 7, 5), 0o644)
kinds := map[string]Kind{"empty": Empty, "bin": Binary, "long.txt": Text, "broken": Special, "pic.png": Image, "song.mp3": Audio}
for name, want := range kinds {
res := Build(bg, Request{Loc: at(filepath.Join(dir, name)), MaxLines: 100})
if res.Kind != want {
t.Errorf("%s: kind %v (%v), want %v", name, res.Kind, res.Err, want)
}
if name == "long.txt" && (len(res.Lines) != 100 || !res.Truncated) {
t.Errorf("long: %d lines truncated=%v", len(res.Lines), res.Truncated)
}
}
if res := Build(bg, Request{Loc: at(filepath.Join(dir, "broken"))}); res.Meta.LinkTarget != "nowhere" {
t.Error("link target")
}
// The result cache returns the same result without rebuilding.
c := NewCache(2)
opens := 0
cfs := &vfstest.FaultFS{FS: local, Hook: func(op vfstest.Op, _ string) error {
if op == vfstest.OpOpen {
opens++
}
return nil
}}
loc := vfs.Location{FS: cfs, Path: filepath.Join(dir, "long.txt")}
r1 := c.Build(bg, Request{Loc: loc})
r2 := c.Build(bg, Request{Loc: loc})
if opens != 1 || len(r1.Lines) != len(r2.Lines) {
t.Fatalf("cache: opens=%d", opens)
}
if res := c.Build(bg, Request{Loc: vfs.Location{FS: local, Path: "/nonexistent"}}); !errors.Is(res.Err, syscall.ENOENT) {
t.Fatalf("missing: %v", res.Err)
}
}
func TestHighlightWindow(t *testing.T) {
dir := t.TempDir()
p := filepath.Join(dir, "big.go")
_ = os.WriteFile(p, []byte(goSource(t)), 0o644)
res := Build(bg, Request{Loc: at(p), HighlightLines: 50})
if res.Highlighted != 50 || !strings.Contains(res.Lines[10]+res.Lines[0], "\x1b[") {
t.Fatalf("highlighted %d", res.Highlighted)
}
for i := 50; i < len(res.Lines); i++ {
if res.Lines[i] != res.Plain[i] {
t.Fatalf("line %d highlighted beyond the window", i)
}
}
full := Build(bg, Request{Loc: at(p), HighlightLines: 3000})
if full.Highlighted != len(full.Plain) {
t.Fatalf("full: %d of %d", full.Highlighted, len(full.Plain))
}
}