| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "os" |
| 6 | "path/filepath" |
| 7 | "regexp" |
| 8 | "strings" |
| 9 | "testing" |
| 10 | |
| 11 | "amadan.net/rastrillo/fiesta" |
| 12 | "amadan.net/rastrillo/fiesta/internal/gallery" |
| 13 | ) |
| 14 | |
| 15 | // TestGalleryWritesTheTreeAtItsMount: `fiesta gallery -out DIR -mount |
| 16 | // /x` writes gallery.Render's tree for /x into DIR itself, file for |
| 17 | // file, stamps DIR as its own, and the flags fail as build's do. |
| 18 | func TestGalleryWritesTheTreeAtItsMount(t *testing.T) { |
| 19 | out := filepath.Join(t.TempDir(), "site", "gallery") |
| 20 | var stderr bytes.Buffer |
| 21 | if err := run([]string{"gallery", "-out", out, "-mount", "/x"}, &stderr); err != nil { |
| 22 | t.Fatalf("fiesta gallery: %v", err) |
| 23 | } |
| 24 | files, err := gallery.Render(fiesta.FS(), gallery.Options{Mount: "/x"}) |
| 25 | if err != nil { |
| 26 | t.Fatal(err) |
| 27 | } |
| 28 | if len(files) == 0 { |
| 29 | t.Fatal("the render is empty") |
| 30 | } |
| 31 | for name, want := range files { |
| 32 | got, err := os.ReadFile(filepath.Join(out, filepath.FromSlash(name))) |
| 33 | if err != nil { |
| 34 | t.Errorf("the gallery did not write %s: %v", name, err) |
| 35 | continue |
| 36 | } |
| 37 | if !bytes.Equal(got, want) { |
| 38 | t.Errorf("%s on disk differs from the render", name) |
| 39 | } |
| 40 | } |
| 41 | index, err := os.ReadFile(filepath.Join(out, "index.html")) |
| 42 | if err != nil || !regexp.MustCompile(`href="/x/assets/gallery\.[0-9a-f]{16}\.css"`).Match(index) { |
| 43 | t.Errorf("index.html does not link the gallery's hashed stylesheet under /x: %v", err) |
| 44 | } |
| 45 | if b, err := os.ReadFile(filepath.Join(out, stampName)); err != nil || string(b) != stampBody("fiesta gallery") { |
| 46 | t.Errorf("the stamp is not fiesta gallery's: %q, %v", b, err) |
| 47 | } |
| 48 | var written int |
| 49 | err = filepath.WalkDir(out, func(p string, d os.DirEntry, err error) error { |
| 50 | if err == nil && !d.IsDir() && filepath.Base(p) != stampName { |
| 51 | written++ |
| 52 | } |
| 53 | return err |
| 54 | }) |
| 55 | if err != nil { |
| 56 | t.Fatal(err) |
| 57 | } |
| 58 | if written != len(files) { |
| 59 | t.Errorf("%s holds %d files besides the stamp, the render has %d", out, written, len(files)) |
| 60 | } |
| 61 | |
| 62 | if err := run([]string{"gallery"}, &stderr); err == nil || !strings.Contains(err.Error(), "-out") { |
| 63 | t.Errorf("gallery with no -out: %v", err) |
| 64 | } |
| 65 | if err := run([]string{"gallery", "-out", out, "extra"}, &stderr); err == nil || !strings.Contains(err.Error(), "extra") { |
| 66 | t.Errorf("gallery with a stray argument: %v", err) |
| 67 | } |
| 68 | } |
| 69 | |