package websource import ( "strings" "testing" ) func readableBase(t *testing.T) URL { t.Helper() u, err := Parse("https://news.example.org/today") if err != nil { t.Fatal(err) } return u } // A page's scripts and styles are never its text; its title is. func TestReadableDropsScript(t *testing.T) { page := `Dublin weather

Today

Rain, 11°C.

` title, text := Readable([]byte(page), "html", readableBase(t)) if title != "Dublin weather" { t.Errorf("title %q", title) } for _, bad := range []string{"alert", "steal", "injected", "color:red", "no js"} { if strings.Contains(text, bad) { t.Errorf("text holds %q: %q", bad, text) } } if !strings.Contains(text, "Today") || !strings.Contains(text, "Rain, 11°C.") { t.Errorf("text %q", text) } } // A feed gives its items' titles and summaries; JSON is pretty-printed; // XML gives its text; plain text is itself; anything else gives nothing. func TestReadableFeedItems(t *testing.T) { rss := `Met news Storm warningWinds up to <b>90 km/h</b>.https://x.example.org/1 Calm weekendSun on Saturday.` title, text := Readable([]byte(rss), "feed", readableBase(t)) if title != "Met news" || !strings.Contains(text, "Storm warning\nWinds up to 90 km/h.") || !strings.Contains(text, "Calm weekend\nSun on Saturday.") || strings.Contains(text, "") { t.Errorf("rss: %q %q", title, text) } atom := `ClubOpen lateUntil 22:00 on Fridays.` if title, text := Readable([]byte(atom), "feed", readableBase(t)); title != "Club" || !strings.Contains(text, "Open late\nUntil 22:00 on Fridays.") { t.Errorf("atom: %q %q", title, text) } if _, text := Readable([]byte(`{"temp":11,"sky":"rain"}`), "json", readableBase(t)); text != "{\n \"sky\": \"rain\",\n \"temp\": 11\n}" && text != "{\n \"temp\": 11,\n \"sky\": \"rain\"\n}" { t.Errorf("json: %q", text) } if _, text := Readable([]byte(`MondayRain`), "xml", readableBase(t)); text != "Monday\nRain" { t.Errorf("xml: %q", text) } if _, text := Readable([]byte("Open 9 to 5."), "text", readableBase(t)); text != "Open 9 to 5." { t.Errorf("text: %q", text) } if title, text := Readable([]byte{0x89, 'P', 'N', 'G'}, "unsupported", readableBase(t)); title != "" || text != "" { t.Errorf("unsupported: %q %q", title, text) } if _, text := Readable([]byte(strings.Repeat("a", 2*MaxReadable)), "text", readableBase(t)); len(text) != MaxReadable { t.Errorf("text not cut: %d", len(text)) } }