package clean import ( "net/url" "strings" "testing" "golang.org/x/net/html" ) var base, _ = url.Parse("https://example.com/posts/article") // body parses markup as the children of a
, like extracted content. func body(t *testing.T, markup string) *html.Node { t.Helper() doc, err := html.Parse(strings.NewReader("" + markup + "")) if err != nil { t.Fatal(err) } return doc.FirstChild.LastChild // html > body } func cleanString(t *testing.T, markup string) string { t.Helper() cleaned, err := Content(body(t, markup), base) if err != nil { t.Fatalf("Content(%q): %v", markup, err) } out, err := Render(cleaned) if err != nil { t.Fatalf("Render(%q): %v", markup, err) } if err := WellFormed("Hello there you.
`, `Hello there you.
`}, {"drops scripts and their content", `a
b
`, `a
b
`}, {"drops styles and their content", `a
`, `a
`}, {"drops event handlers, classes, ids and inline styles", `a
`, `a
`}, {"drops forms but keeps their text", ``, `Sign up
Go`}, {"drops iframes and objects", `a
`, `a
`}, {"drops javascript links but keeps the text", ``, `click
`}, {"makes relative links absolute", ``, ``}, {"keeps mailto links", ``, ``}, {"keeps valid table spans and drops invalid ones", `| a |
| a |
a
b
`, `a
b
`}, {"keeps images in paragraphs and makes their src absolute", `a

a

a
a
`}, {"removes empty paragraphs", `a
b
`, `a
b
`}, {"repairs mailto and tel links mangled by go-trafilatura", ``, ``}, {"restores code blocks from go-trafilatura's block code", "a = 1\nb = 2\nafter
", "a = 1\nb = 2\nafter
"}, {"restores multi-line code inside a list item", "x\nyx\nyRun make\nbuild now.
Run make\nbuild now.
if a < b {
return
}`,
"if a < b {\n\treturn\n}"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := cleanString(t, tt.in); got != tt.want {
t.Errorf("got %q\nwant %q", got, tt.want)
}
})
}
}
func TestContentRepairsNesting(t *testing.T) {
// Each of these is invalid HTML that must still come out well-formed.
for _, in := range []string{
`a
loose
| no row |
unclosed emphasis next`,
` a b © — <tag> & a b © — <tag> & no headings no headings a & < > " ' unclosed`, ` a`, ` a
b
c
`, `a
b
c
`},
{`a
b
`, `a
b
`},
{`a
b
`, `a
b
`},
{`a
b
c
`, `a
b
c
`},
{`
`}
for _, s := range good {
if err := WellFormed(s); err != nil {
t.Errorf("WellFormed(%q) = %v, want nil", s, err)
}
}
for _, s := range bad {
if err := WellFormed(s); err == nil {
t.Errorf("WellFormed(%q) = nil, want an error", s)
}
}
}