package web
import (
"regexp"
"strings"
"testing"
)
// clearForm isolates the clear control from the panel's own filter box,
// which also carries a q field.
func clearForm(html string) string {
m := regexp.MustCompile(`(?s)<form method="post" action="/fleet/exceptions/clear".*?</form>`).FindString(html)
return m
}
// renderExceptions draws the panel around one journalled row.
func renderExceptions(t *testing.T, query string) string {
t.Helper()
var buf strings.Builder
err := exceptionsPage.ExecuteTemplate(&buf, "content", pageData{
Query: query,
ServerErrors: []errlogRow{{
Message: "disk on fire", Surface: "ingest", Path: "/ingest",
Count: 10000, First: "Fri", Last: "2 hours ago", Group: "7cef41e3",
}},
ErrorTotal: 10000, ErrorDistinct: 1,
})
if err != nil {
t.Fatal(err)
}
return buf.String()
}
// The panel must offer a way to finish with a row. Without one the only
// mechanism is time, and a signature at ten thousand occurrences keeps
// presenting ten thousand as the reason to look at it long after the
// fix landed.
func TestEveryExceptionOffersAClearControl(t *testing.T) {
got := renderExceptions(t, "")
if !strings.Contains(got, `action="/fleet/exceptions/clear"`) {
t.Fatal("FAIL: the exceptions panel has no clear control")
}
if !strings.Contains(got, `name="sig" value="7cef41e3"`) {
t.Error("FAIL: the clear control does not carry the signature it clears")
}
// A GET would let a link prefetcher or a crawler empty the journal
// by reading the page.
if !strings.Contains(got, `<form method="post" action="/fleet/exceptions/clear"`) {
t.Error("FAIL: clearing is not a POST")
}
}
// Clearing from a filtered view comes back to the filtered view. An
// operator working through a filter otherwise loses their place once
// per row, which is exactly when they are clearing several.
func TestClearingKeepsTheFilterItWasPressedUnder(t *testing.T) {
if got := clearForm(renderExceptions(t, "ingest")); !strings.Contains(got, `name="q" value="ingest"`) {
t.Errorf("FAIL: clearing under a filter does not carry the filter back: %s", got)
}
// And an unfiltered panel sends no empty parameter along.
if got := clearForm(renderExceptions(t, "")); strings.Contains(got, `name="q"`) {
t.Errorf("FAIL: an unfiltered panel sends an empty filter with the clear: %s", got)
}
}