//go:build browser
package browsertest
import (
"context"
"encoding/json"
"os"
"path/filepath"
"strconv"
"testing"
"time"
"github.com/chromedp/chromedp"
"amadan.net/rastrillo/rastrillo/harness"
"amadan.net/oficina/base/internal/equipo"
)
// sameAsServer is every reply in the panel whose HTML differs from the
// same reply on /ask, drawn by the server; "" when they all match.
const sameAsServer = `(async () => {
const page = new DOMParser().parseFromString(await (await fetch("/ask")).text(), "text/html");
const out = [];
for (const m of document.querySelectorAll("#ask-panel .msg.coordinator")) {
const s = page.querySelector('.msg.coordinator[data-id="' + CSS.escape(m.dataset.id) + '"]');
if (!s) out.push(m.dataset.id + ": not on /ask");
else if (s.innerHTML !== m.innerHTML) out.push(JSON.stringify(m.textContent) + "\n script " + m.innerHTML + "\n server " + s.innerHTML);
}
return out.join("\n");
})()`
// sayLookups has the Assistant say each reply, with its lookups, while the
// panel is open, and waits for them all to be drawn.
func sayLookups(t *testing.T, replies map[string][]equipo.Lookup, order []string) *harness.Rig {
t.Helper()
rig, f := askBase(t)
openPanel(t, rig)
for _, text := range order {
f.SayWithLookups(text, replies[text]...)
}
drive(t, rig, chromedp.Poll[chromedp.Void](`document.querySelectorAll("#ask-panel .msg.coordinator").length === `+strconv.Itoa(len(order)),
chromedp.WithPollingTimeout(10*time.Second)))
return rig
}
// The panel draws a message event's lookups exactly as the server draws
// them on /ask: two lookups, a link in an answer, a multibyte title.
func TestAskLookupMatchesServer(t *testing.T) {
order := []string{"Here it is.", "Both of them.", ""}
rig := sayLookups(t, map[string][]equipo.Lookup{
"Here it is.": {{Answer: "**Rain** later, see [Met](https://met.test/x) & more.",
Sources: []equipo.Source{{URL: "https://www.met.test/dublin?d=1&e=2", Title: "Met Éireann · 日本 😀"}, {URL: "https://b.test/"}, {URL: "https://c.test/", Title: "Met\rNow\x00"}, {URL: "https://d.test/wiki/Foo_(bar)'s", Title: "Wiki"}}}},
"Both of them.": {
{Answer: "First:\n- one\n- *two*", Sources: []equipo.Source{{URL: "https://one.test/a", Title: "One"}}},
{Answer: "Second, https://two.test/x.", Sources: []equipo.Source{{URL: "https://two.test/", Title: "Two"}}},
},
"": {{Answer: "Only an answer.", Sources: []equipo.Source{{URL: "https://three.test/", Title: "Three"}}}},
}, order)
if got := harness.Evaluate[string](rig, sameAsServer, chromedp.EvalAwaitPromise); got != "" {
t.Errorf("the script and the server draw lookups differently:\n%s", got)
}
if n := harness.Evaluate[int](rig, `document.querySelectorAll("#ask-panel .lookup").length`); n != 4 {
t.Errorf("%d lookups drawn, want 4", n)
}
rig.Screen("#ask-panel", "a reply with lookups and their sources")
if dir := os.Getenv("BASE_BROWSER_ARTIFACTS"); dir != "" {
var png []byte
drive(t, rig, chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
var err error
png, err = chromedp.FullScreenshot(100)(ctx, target)
return err
}))
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "ask-lookups.png"), png, 0o644); err != nil {
t.Fatal(err)
}
}
}
// Every source opens in a new tab, and tells the page nothing of Base.
func TestAskLookupSourcesNewTab(t *testing.T) {
rig := sayLookups(t, map[string][]equipo.Lookup{"Here.": {{Answer: "Sunny.",
Sources: []equipo.Source{{URL: "https://met.test/", Title: "Met"}, {URL: "https://b.test/", Title: "B"}}}}}, []string{"Here."})
got := harness.Evaluate[string](rig, `[...document.querySelectorAll("#ask-panel .lookup-sources a")]
.map(a => a.target + " " + a.rel + " " + a.href).join("\n")`)
if want := "_blank noopener noreferrer nofollow https://met.test/\n_blank noopener noreferrer nofollow https://b.test/"; got != want {
t.Errorf("sources:\n%s\nwant\n%s", got, want)
}
}
// An answer's links, bare URLs, autolinks and markup are text; the
// sources are still links.
func TestAskLookupMarkdownNoLinks(t *testing.T) {
rig := sayLookups(t, map[string][]equipo.Lookup{"Look.": {{
Answer: "- [Click](https://evil.test/a)\n- https://evil.test/b\n- \n-
",
Sources: []equipo.Source{{URL: "https://good.test/", Title: "Good"}}}}}, []string{"Look."})
if n := harness.Evaluate[int](rig, `document.querySelectorAll("#ask-panel .lookup-answer a, #ask-panel .lookup-answer img, #ask-panel .lookup-answer script").length`); n != 0 {
t.Errorf("%d links or markup drawn in an answer", n)
}
if got := harness.Evaluate[string](rig, `[...document.querySelectorAll("#ask-panel .lookup-answer li")].map(l => l.textContent).join("|")`); got != "Click|https://evil.test/b||
" {
t.Errorf("answer text %q", got)
}
if n := harness.Evaluate[int](rig, `document.querySelectorAll('#ask-panel .lookup-sources a[href="https://good.test/"]').length`); n != 1 {
t.Errorf("the source is not a link")
}
if got := harness.Evaluate[string](rig, sameAsServer, chromedp.EvalAwaitPromise); got != "" {
t.Errorf("the script and the server draw differently:\n%s", got)
}
}
// With scripts, a held job that offers it shows Carry on now in its view,
// with no "other plan" line, and carries on in place (plan AD4).
func TestStoppedCarryOnDrawn(t *testing.T) {
rig, f := askBase(t)
openPanel(t, rig)
id := f.AskJob("Bakery website")
f.StopJob(id, "Stopped", "Building is on again. You can carry on with this, or drop it.", true)
job := `#ask-panel li.job[data-job="` + id + `"]`
drive(t, rig, chromedp.Poll[chromedp.Void](`document.querySelector(`+strconv.Quote(job)+`)?.dataset.state === "stopped" && document.querySelector(`+strconv.Quote(job+` .jv-act`)+`) !== null`,
chromedp.WithPollingTimeout(10*time.Second)))
if got := harness.Evaluate[string](rig, `(() => { const f = document.querySelector(`+strconv.Quote(job+` .jv-act`)+`);
return [f.querySelector("button").textContent, f.querySelectorAll("small").length].join("|"); })()`); got != "Carry on now|0" {
t.Errorf("the held job's Carry on now: %s", got)
}
drive(t, rig, chromedp.Click(chromedp.CSS(job+` summary`)), chromedp.Sleep(250*time.Millisecond),
chromedp.Click(chromedp.CSS(job+` .jv-act button`)))
drive(t, rig, chromedp.Poll[chromedp.Void](`document.querySelector(`+strconv.Quote(job)+`)?.dataset.state === "working"`, chromedp.WithPollingTimeout(10*time.Second)))
if n := len(f.Calls("/api/v1/assistant/cards/" + id + "/carry_on")); n != 1 {
t.Errorf("carry on went %d times", n)
}
}
// Every shared sample (internal/web/testdata/lookup.json, which the
// server's and the app's tests check too) is drawn by the script exactly
// as the server draws it: characters counted alike, whitespace read alike.
func TestAskLookupMarkdownFixtures(t *testing.T) {
raw, err := os.ReadFile("../web/testdata/lookup.json")
if err != nil {
t.Fatal(err)
}
var cases []struct{ Text, HTML string }
if err := json.Unmarshal(raw, &cases); err != nil {
t.Fatal(err)
}
replies, order := map[string][]equipo.Lookup{}, []string{}
for i, c := range cases {
text := "Sample " + strconv.Itoa(i)
replies[text] = []equipo.Lookup{{Answer: c.Text, Sources: []equipo.Source{{URL: "https://src.test/", Title: "Src"}}}}
order = append(order, text)
}
rig := sayLookups(t, replies, order)
if got := harness.Evaluate[string](rig, sameAsServer, chromedp.EvalAwaitPromise); got != "" {
t.Errorf("the script and the server draw the samples differently:\n%s", got)
}
}