Files
sm-journal-plugin/classes/image_alt_test.go
Jakub Zych e7832a8d26 test: unit tests for heading conversion, image alt, content facts and related settings
- ConvertContentH1 and ConvertTranslationH1 for post bodies and category
  pillar text
- SetImageAlt with several matches, repeated alt attributes and markup
  that only looks like an img
- the content facts outline, images, decorative images and embeds
- the related-posts mode and count
2026-11-04 19:45:16 +01:00

48 lines
2.4 KiB
Go

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 = `<p class="a">x &amp; y</p><img src="https://cdn.example.test/a.jpg?x=1&amp;y=2"><img src="b.jpg" alt="old"/>`
out, n, old := SetImageAlt(doc, "https://cdn.example.test/a.jpg?x=1&y=2", `Lion's "mane" <b>`)
want := `<p class="a">x &amp; y</p><img src="https://cdn.example.test/a.jpg?x=1&amp;y=2" alt="Lion&#39;s &#34;mane&#34; &lt;b&gt;"><img src="b.jpg" alt="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 != `<p class="a">x &amp; y</p><img src="https://cdn.example.test/a.jpg?x=1&amp;y=2"><img src="b.jpg" alt=""/>` || 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 := `<img src="a.jpg" alt="one"><p>t</p><img alt="x" src="a.jpg" alt="y"><!-- <img src="a.jpg"> --><script>"<img src=a.jpg>"</script>`
out, n, old := SetImageAlt(doc, "a.jpg", "new")
if n != 2 || old == nil || *old != "one" {
t.Fatalf("n=%d old=%v", n, old)
}
want := `<img src="a.jpg" alt="new"><p>t</p><img alt="new" src="a.jpg"><!-- <img src="a.jpg"> --><script>"<img src=a.jpg>"</script>`
if out != want {
t.Fatalf("out = %q\nwant %q", out, want)
}
if out, n, _ := SetImageAlt(`<img src="a.jpg?x=1&amp;y=2">`, "a.jpg?x=1&amp;y=2", "z"); n != 0 || out != `<img src="a.jpg?x=1&amp;y=2">` {
t.Fatalf("escaped src matched: %q %d", out, n)
}
for _, tc := range []struct{ html, src string }{{`<img src="a.jpg">`, ""}, {`<p>no images</p>`, "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)
}
}
}