embeds_test.go 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package clean
  2. import (
  3. "strings"
  4. "testing"
  5. "golang.org/x/net/html"
  6. )
  7. func prepareString(t *testing.T, markup string) string {
  8. t.Helper()
  9. doc, err := html.Parse(strings.NewReader("<body>" + markup + "</body>"))
  10. if err != nil {
  11. t.Fatal(err)
  12. }
  13. Prepare(doc, base)
  14. restoreImageSources(doc) // show real URLs rather than stand-ins
  15. var b strings.Builder
  16. body := doc.FirstChild.LastChild
  17. for c := body.FirstChild; c != nil; c = c.NextSibling {
  18. html.Render(&b, c)
  19. }
  20. return b.String()
  21. }
  22. func TestPrepareReplacesVideoEmbeds(t *testing.T) {
  23. tests := []struct{ name, in, want string }{
  24. {"YouTube with title",
  25. `<iframe src="https://www.youtube.com/embed/dQw4w9WgXcQ?si=abc" title="Never Gonna Give You Up"></iframe>`,
  26. `<p>▶ Video: <a href="https://www.youtube.com/watch?v=dQw4w9WgXcQ">Never Gonna Give You Up</a></p>`},
  27. {"YouTube without title",
  28. `<iframe src="https://www.youtube.com/embed/dQw4w9WgXcQ"></iframe>`,
  29. `<p>▶ Video: <a href="https://www.youtube.com/watch?v=dQw4w9WgXcQ">https://www.youtube.com/watch?v=dQw4w9WgXcQ</a></p>`},
  30. {"YouTube no-cookie, protocol-relative",
  31. `<iframe src="//www.youtube-nocookie.com/embed/abcDEF12345"></iframe>`,
  32. `<p>▶ Video: <a href="https://www.youtube.com/watch?v=abcDEF12345">https://www.youtube.com/watch?v=abcDEF12345</a></p>`},
  33. {"Vimeo",
  34. `<iframe src="https://player.vimeo.com/video/76979871?h=8272103f6e" title="The New Vimeo Player"></iframe>`,
  35. `<p>▶ Video: <a href="https://vimeo.com/76979871">The New Vimeo Player</a></p>`},
  36. {"other iframes are left alone",
  37. `<iframe src="https://ads.example.com/banner"></iframe>`,
  38. `<iframe src="https://ads.example.com/banner"></iframe>`},
  39. {"lookalike hosts are left alone",
  40. `<iframe src="https://youtube.com.evil.example/embed/dQw4w9WgXcQ"></iframe>`,
  41. `<iframe src="https://youtube.com.evil.example/embed/dQw4w9WgXcQ"></iframe>`},
  42. }
  43. for _, tt := range tests {
  44. t.Run(tt.name, func(t *testing.T) {
  45. if got := prepareString(t, tt.in); got != tt.want {
  46. t.Errorf("got %q\nwant %q", got, tt.want)
  47. }
  48. })
  49. }
  50. }
  51. func TestPrepareResolvesLinks(t *testing.T) {
  52. // base is https://example.com/posts/article; relative links resolve
  53. // against its folder, /posts/.
  54. got := prepareString(t, `<p><a href="../faq#restart">a</a> <a href="other">b</a> <a href="/root">c</a> <a href="https://x.example/">d</a></p>`)
  55. want := `<p><a href="https://example.com/faq#restart">a</a> <a href="https://example.com/posts/other">b</a> <a href="https://example.com/root">c</a> <a href="https://x.example/">d</a></p>`
  56. if got != want {
  57. t.Errorf("got %q\nwant %q", got, want)
  58. }
  59. }