package web
import (
"regexp"
"strings"
"testing"
)
func TestSearchPattern(t *testing.T) {
for q, want := range map[string]string{
"go tem": "go.*tem",
" a.b (c) ": `a\.b.*\(c\)`,
"one": "one",
" ": "",
"": "",
} {
if got := searchPattern(q); got != want {
t.Errorf("searchPattern(%q) = %q, want %q", q, got, want)
}
}
// The pattern is what Postgres gets, and also what Go runs for the snippet.
re := regexp.MustCompile("(?is)" + searchPattern("go tem"))
if !re.MatchString("Go\ntemplates") || re.MatchString("templates for go") {
t.Error("words match in order, across lines, any case")
}
}
func TestSearchSnippet(t *testing.T) {
re := regexp.MustCompile("(?is)" + searchPattern("tem"))
got := string(searchSnippet("Go Templates\n\nare fine.", re))
if got != "Go <b>Templates</b> are fine." {
t.Errorf("snippet: %q", got)
}
// Long bodies are trimmed around the match, rune by rune.
body := strings.Repeat("α", 200) + " tem " + strings.Repeat("ω", 200)
got = string(searchSnippet(body, re))
if !strings.HasPrefix(got, "…"+strings.Repeat("α", 79)+" tem ") || !strings.HasSuffix(got, strings.Repeat("ω", 79)+"…") {
t.Errorf("trimmed snippet: %q", got)
}
// Only the title matched: the body's start, no mark.
if got := string(searchSnippet("Nothing here.", re)); got != "Nothing here." {
t.Errorf("title-only snippet: %q", got)
}
}