package classes import "testing" // TestSetImageAlt pins the alt rewrite: only the matching img tag is // rewritten from its token, the alt is escaped, a missing alt is added and // every other byte is kept (T-33-04). func TestSetImageAlt(t *testing.T) { const doc = `

x & y

old` out, n, old := SetImageAlt(doc, "https://cdn.example.test/a.jpg?x=1&y=2", `Lion's "mane" `) want := `

x & y

Lion's "mane" <b>old` if out != want || n != 1 || old != nil { t.Fatalf("SetImageAlt = %q, %d, %v; want %q, 1, nil", out, n, old, want) } out, n, old = SetImageAlt(doc, "b.jpg", "") if out != `

x & y

` || n != 1 || old == nil || *old != "old" { t.Fatalf("decorative = %q, %d, %v", out, n, old) } if out, n, _ := SetImageAlt(doc, "missing.jpg", "x"); out != doc || n != 0 { t.Fatalf("missing = %q, %d", out, n) } } // TestSetImageAltEdges pins the edges: every matching img is rewritten // and counted (the first one's old alt answered), repeated alt attributes // collapse to one, a src given escaped does not match the unescaped one, // an empty src and a body without img change nothing, and text that // looks like an img inside a comment or script is not touched. func TestSetImageAltEdges(t *testing.T) { doc := `one

t

x` out, n, old := SetImageAlt(doc, "a.jpg", "new") if n != 2 || old == nil || *old != "one" { t.Fatalf("n=%d old=%v", n, old) } want := `new

t

new` if out != want { t.Fatalf("out = %q\nwant %q", out, want) } if out, n, _ := SetImageAlt(``, "a.jpg?x=1&y=2", "z"); n != 0 || out != `` { t.Fatalf("escaped src matched: %q %d", out, n) } for _, tc := range []struct{ html, src string }{{``, ""}, {`

no images

`, "a.jpg"}, {"", "a.jpg"}} { if out, n, old := SetImageAlt(tc.html, tc.src, "x"); out != tc.html || n != 0 || old != nil { t.Errorf("SetImageAlt(%q, %q) = %q %d %v", tc.html, tc.src, out, n, old) } } }