package webtest
import (
"encoding/json"
"regexp"
"strings"
"testing"
"amadan.net/oficina/base/internal/equipo"
)
// replies are the Assistant's lines on a page, each whole, oldest first.
func replies(page string) []string {
return regexp.MustCompile(`(?s)
.*?`).FindAllString(page, -1)
}
// An open connect card is a button at the end of the Assistant's newest
// reply, after its words, never a bubble of its own above or below it:
// "Connect Oficina" with the Oficina mark, going to Base's own connect
// page in the same tab, and a line saying what it unlocks.
func TestAskConnectOfferFollowsItsReply(t *testing.T) {
a, f := newAskApp(t)
a.connectEquipo(f)
f.Say("Hello. What can I do?")
id := f.RaiseConnect("t_1", testOrigin+"/ask/oficina/connect")
f.Say("Connect your Oficina apps and I'll show you this week.")
page := a.get("/ask").Body
lines := replies(page)
if len(lines) != 2 {
t.Fatalf("%d replies:\n%s", len(lines), page)
}
if strings.Contains(lines[0], "connect-offer") {
t.Errorf("the older reply has the offer:\n%s", lines[0])
}
want := `Connect your Oficina apps and I'll show you this week.`) {
t.Errorf("the offer is not the end of the reply:\n%s", lines[1])
}
if strings.Contains(page, "card-connect") || strings.Contains(page, "Connect your Oficina apps") {
t.Errorf("the card was drawn on its own as well:\n%s", page)
}
// The panel's script gets the card as it is, to place the same way.
var st struct{ Cards []equipo.Card }
if r := a.get("/ask/state"); json.Unmarshal([]byte(r.Body), &st) != nil || len(st.Cards) != 1 || st.Cards[0].ID != id ||
st.Cards[0].Kind != "connect" || len(st.Cards[0].Links) != 1 || st.Cards[0].Links[0].Rel != "oficina_connect" {
t.Fatalf("state: %s", r.Body)
}
// A later reply takes it: the newest reply always ends with it.
f.Say("Sure, anything else?")
lines = replies(a.get("/ask").Body)
if len(lines) != 3 || strings.Contains(lines[1], "connect-offer") || !strings.Contains(lines[2], `
]+>Connect OficinaCalendar, Docs, Sheets and more
\s*`).MatchString(page) {
t.Errorf("no loose offer at the end:\n%s", page)
}
other := f.RaiseConnect("t_2", "https://evil.example/ask/oficina/connect")
page = a.get("/ask").Body
card := cardItem(t, page, other)
if !strings.Contains(card, `href="https://evil.example/ask/oficina/connect" target="_blank" rel="noopener">Connect`) || strings.Contains(card, "connect-btn") {
t.Errorf("a lookalike connect card got the button:\n%s", card)
}
}