// SPDX-License-Identifier: GPL-3.0-or-later package model import ( "context" "os" "path/filepath" "strings" "testing" ) // TestPreviewKinds: a text file comes back as text, a picture as a picture, // and something krino cannot show says so instead of guessing. func TestPreviewKinds(t *testing.T) { dir := t.TempDir() write := func(name string, body []byte) string { p := filepath.Join(dir, name) if err := os.WriteFile(p, body, 0o644); err != nil { t.Fatal(err) } return p } text := write("notes.txt", []byte("first line\nsecond line\n")) png := write("a.png", []byte("\x89PNG\r\n\x1a\nnot really, but the name is what counts here")) binary := write("a.bin", []byte{0, 1, 2, 3, 0}) tmp := t.TempDir() if p := MakePreview(context.Background(), text, tmp); p.Kind != PreviewText || !strings.Contains(p.Text, "second line") { t.Errorf("text preview = %+v", p) } if p := MakePreview(context.Background(), png, tmp); p.Kind != PreviewImage || p.Image != png { t.Errorf("image preview = %+v", p) } if p := MakePreview(context.Background(), binary, tmp); p.Kind != PreviewNone || !strings.Contains(p.Note, "no preview") { t.Errorf("binary preview = %+v", p) } if p := MakePreview(context.Background(), filepath.Join(dir, "gone.txt"), tmp); p.Kind != PreviewNone { t.Errorf("a missing file = %+v", p) } if p := MakePreview(context.Background(), dir, tmp); p.Kind != PreviewNone { t.Errorf("a directory = %+v", p) } } // TestPreviewReadsOnly: looking at a file changes nothing about it, and // nothing is left beside it. func TestPreviewReadsOnly(t *testing.T) { dir := t.TempDir() p := filepath.Join(dir, "notes.txt") body := []byte("one\ntwo\n") if err := os.WriteFile(p, body, 0o644); err != nil { t.Fatal(err) } before, err := os.Stat(p) if err != nil { t.Fatal(err) } MakePreview(context.Background(), p, t.TempDir()) after, err := os.Stat(p) if err != nil { t.Fatal(err) } if !before.ModTime().Equal(after.ModTime()) || before.Size() != after.Size() { t.Error("the file changed") } if entries, _ := os.ReadDir(dir); len(entries) != 1 { t.Errorf("the directory holds %d files, want the one", len(entries)) } if on, _ := os.ReadFile(p); string(on) != string(body) { t.Error("the contents changed") } } // TestPreviewShowsOnlyTheHead: a long file is cut, and says it was. func TestPreviewShowsOnlyTheHead(t *testing.T) { dir := t.TempDir() p := filepath.Join(dir, "long.txt") var b strings.Builder for i := 0; i < previewLines*2; i++ { b.WriteString("line\n") } if err := os.WriteFile(p, []byte(b.String()), 0o644); err != nil { t.Fatal(err) } pv := MakePreview(context.Background(), p, t.TempDir()) if pv.Kind != PreviewText { t.Fatalf("preview = %+v", pv) } if n := strings.Count(pv.Text, "\n"); n > previewLines+1 { t.Errorf("%d lines shown, want at most %d", n, previewLines) } if !strings.HasSuffix(pv.Text, "...") { t.Error("a cut file does not say it was cut") } }