package web
import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
)
// homeRepos is twelve repositories the reader holds: ten native (every
// third one private) and two mirrors, all admin but one writer, so the
// first eight by activity are not the whole account.
func homeRepos() []map[string]any {
var rows []map[string]any
for i := 0; i < 10; i++ {
row := map[string]any{"name": fmt.Sprintf("repo%02d", i), "role": "admin"}
if i%3 == 0 {
row["private"] = true
}
rows = append(rows, row)
}
rows[9]["role"] = "writer"
rows = append(rows,
map[string]any{"name": "mirror-a", "role": "admin", "mirror": true},
map[string]any{"name": "mirror-b", "role": "admin", "mirror": true, "private": true})
return rows
}
// listed is the repository names the dashboard's own list shows, in order.
func listed(body string) []string {
var names []string
i := strings.Index(body, `data-hook="dash-repos"`)
if i < 0 {
return nil
}
rest := body[i:]
if j := strings.Index(rest, `</ul>`); j >= 0 {
rest = rest[:j]
}
for _, part := range strings.Split(rest, `class="dash-title" href="/r/`)[1:] {
names = append(names, part[:strings.Index(part, `"`)])
}
return names
}
func listHas(names []string, want string) bool {
for _, n := range names {
if n == want {
return true
}
}
return false
}
func fragGet(hh *homeHarness, path string, cookie bool) (int, string, string) {
req := httptest.NewRequest("GET", path, nil)
if cookie {
req.AddCookie(&http.Cookie{Name: sessionCookie, Value: "good"})
}
w := httptest.NewRecorder()
hh.h.ServeHTTP(w, req)
return w.Code, w.Body.String(), w.Header().Get("Content-Type")
}
// Mirrors are somebody else's code kept current here; the list of your
// repositories leads with what is yours, and says so with kind=all.
func TestHomeListHidesMirrorsUnlessAsked(t *testing.T) {
hh := newHomeHarness(t, 0)
hh.repos = homeRepos()
_, body, _, _ := hh.get(t, "/?repos=all")
if got := listed(body); len(got) != 10 || listHas(got, "mirror-a") {
t.Errorf("FAIL: default list is %v, want the ten native repositories", got)
}
_, body, _, _ = hh.get(t, "/?kind=all")
if got := listed(body); len(got) != 12 || !listHas(got, "mirror-a") || !listHas(got, "mirror-b") {
t.Errorf("FAIL: kind=all lists %v, want all twelve", got)
}
_, body, _, _ = hh.get(t, "/?kind=mirror")
if got := listed(body); len(got) != 2 || !listHas(got, "mirror-a") {
t.Errorf("FAIL: kind=mirror lists %v, want the two mirrors", got)
}
if !strings.Contains(body, `data-hook="dash-mirror"`) {
t.Error("FAIL: a mirror row carries no dash-mirror mark")
}
fmt.Println("ok: native by default, kind=all and kind=mirror widen it")
}
func TestHomeListFiltersByVisibility(t *testing.T) {
hh := newHomeHarness(t, 0)
hh.repos = homeRepos()
_, body, _, _ := hh.get(t, "/?vis=private")
got := listed(body)
if len(got) != 4 || !listHas(got, "repo00") || listHas(got, "repo01") {
t.Errorf("FAIL: vis=private lists %v, want the four native private ones", got)
}
if n := strings.Count(body, `data-hook="dash-private"`); n != 4 {
t.Errorf("FAIL: %d private marks, want 4", n)
}
_, body, _, _ = hh.get(t, "/?vis=public&kind=all")
got = listed(body)
if len(got) != 7 || listHas(got, "repo00") || !listHas(got, "mirror-a") {
t.Errorf("FAIL: vis=public&kind=all lists %v", got)
}
if strings.Contains(body, `data-hook="dash-private"`) {
t.Error("FAIL: a public list carries a private mark")
}
fmt.Println("ok: vis narrows to private or public")
}
// The filter reads the whole account, not the eight rows the page leads
// with, and a filtered list is whole rather than capped.
func TestHomeFilterReachesPastTheFirstEight(t *testing.T) {
hh := newHomeHarness(t, 0)
hh.repos = homeRepos()
_, body, _, _ := hh.get(t, "/")
if got := listed(body); len(got) != 8 || listHas(got, "repo09") {
t.Fatalf("FAIL: unfiltered list is %v, want the first eight", got)
}
_, body, _, _ = hh.get(t, "/?find=REPO09")
if got := listed(body); len(got) != 1 || got[0] != "repo09" {
t.Errorf("FAIL: find=REPO09 lists %v, want repo09 alone (case-folded, past the eighth)", got)
}
_, body, _, _ = hh.get(t, "/?find=repo")
if got := listed(body); len(got) != 10 {
t.Errorf("FAIL: find=repo lists %d, want all ten, uncapped", len(got))
}
fmt.Println("ok: find searches every repository, case-folded")
}
func TestHomeListHasItsControls(t *testing.T) {
hh := newHomeHarness(t, 0)
hh.repos = homeRepos()
_, body, _, _ := hh.get(t, "/")
for _, want := range []string{`data-hook="dash-find"`, `data-hook="dash-vis"`, `data-hook="dash-kind"`,
`name="find"`, `data-on:input__debounce.300ms="@get('/home/repos.frag', {contentType: 'form'})"`,
`data-hook="dash-count"`, `role="status"`, `id="dash-repolist"`, dashNavURL} {
if !strings.Contains(body, want) {
t.Errorf("FAIL: the home page has no %s", want)
}
}
if n := strings.Count(body, `type="radio" name="vis"`); n != 3 {
t.Errorf("FAIL: %d visibility radios, want 3", n)
}
if !strings.Contains(body, `<option value="native" selected>`) {
t.Error("FAIL: the kind selector does not start on native")
}
// The live attributes are on the controls that change the list.
if n := strings.Count(body, `data-on:change="@get('/home/repos.frag', {contentType: 'form'})"`); n != 2 {
t.Errorf("FAIL: %d live change handlers, want the radio group and the select", n)
}
_, body, _, _ = hh.get(t, "/?vis=private&kind=all")
if !strings.Contains(body, `<option value="all" selected>`) || !strings.Contains(body, `value="private" checked`) {
t.Error("FAIL: the controls do not show the view they are in")
}
// Any repository at all brings the filter: it is also the way to
// the mirrors the default hides.
hh.repos = homeRepos()[:1]
if _, body, _, _ = hh.get(t, "/"); !strings.Contains(body, `data-hook="dash-find"`) ||
!strings.Contains(body, `data-hook="dash-kind"`) || !strings.Contains(body, `data-hook="dash-vis"`) {
t.Error("FAIL: a single repository is not offered the filter")
}
hh.repos = []map[string]any{}
if _, body, _, _ = hh.get(t, "/"); strings.Contains(body, `data-hook="dash-find"`) {
t.Error("FAIL: an account with no repository is offered a filter")
}
}
// What the filter's own request answers is the list and nothing else,
// as a patch of the element the page marks.
func TestHomeRepoFragment(t *testing.T) {
hh := newHomeHarness(t, 0)
hh.repos = homeRepos()
code, body, ct := fragGet(hh, "/home/repos.frag?find=repo09&vis=&kind=native", true)
if code != http.StatusOK || !strings.HasPrefix(ct, "text/event-stream") {
t.Fatalf("FAIL: fragment answered %d as %q", code, ct)
}
if !strings.Contains(body, "event: datastar-patch-elements") || !strings.Contains(body, `id="dash-repolist"`) {
t.Errorf("FAIL: the fragment is not a patch of the list:\n%s", body)
}
if got := listed(strings.ReplaceAll(body, "data: elements ", "")); len(got) != 1 || got[0] != "repo09" {
t.Errorf("FAIL: the fragment lists %v, want repo09", got)
}
if strings.Contains(body, `data-hook="dash-find"`) || strings.Contains(body, "<html") {
t.Error("FAIL: the fragment carries more than the list (it would reset the box being typed in)")
}
if !strings.Contains(body, `data-hook="dash-count"`) {
t.Error("FAIL: the fragment has no count to announce")
}
// The same view as the page, row for row.
_, page, _, _ := hh.get(t, "/?"+url.Values{"vis": {"private"}, "kind": {"all"}}.Encode())
_, frag, _ := fragGet(hh, "/home/repos.frag?vis=private&kind=all", true)
pg, fg := listed(page), listed(strings.ReplaceAll(frag, "data: elements ", ""))
if len(pg) == 0 || strings.Join(pg, ",") != strings.Join(fg, ",") {
t.Errorf("FAIL: page lists %v, fragment lists %v", pg, fg)
}
}
// Somebody else's repositories are not shown to a caller who is not
// signed in: the fragment is the reader's own list.
func TestHomeRepoFragmentRefusesTheSignedOut(t *testing.T) {
hh := newHomeHarness(t, 0)
hh.repos = homeRepos()
code, body, _ := fragGet(hh, "/home/repos.frag", false)
if code != http.StatusUnauthorized {
t.Errorf("FAIL: signed out, the fragment answered %d", code)
}
if strings.Contains(body, "repo00") || strings.Contains(body, `data-hook="dash-repos"`) {
t.Error("FAIL: the signed-out answer carries a repository list")
}
}
// A role held on nearly every repository is the page's background; the
// chip is for the repository where the reader is something else.
func TestHomeRoleChipOnlyWhereItDiffers(t *testing.T) {
d := dashData{User: "dan", Repos: []dashRepoRow{
{Name: "a", Role: "admin"}, {Name: "b", Role: "admin"}, {Name: "c", Role: "admin"},
}}
shapeDashRepos(&d, url.Values{})
if got := renderDash(t, d); strings.Contains(got, `class="chip role"`) || strings.Contains(got, "t-team") {
t.Errorf("FAIL: an account that is admin everywhere sees role chips")
}
d = dashData{User: "dan", Repos: []dashRepoRow{
{Name: "a", Role: "admin"}, {Name: "b", Role: "admin"}, {Name: "c", Role: "reader"}, {Name: "d"},
}}
shapeDashRepos(&d, url.Values{})
if d.CommonRole != "admin" {
t.Fatalf("FAIL: common role is %q, want admin", d.CommonRole)
}
got := renderDash(t, d)
if n := strings.Count(got, `class="chip role"`); n != 1 {
t.Errorf("FAIL: %d role chips, want the one reader row", n)
}
if n := strings.Count(got, `class="chip role t-team"`); n != 1 {
t.Errorf("FAIL: %d team chips, want the one team row", n)
}
// The ordinary role is read from the whole account, not from the
// rows the filter leaves.
shapeDashRepos(&d, url.Values{"find": {"c"}})
if d.CommonRole != "admin" {
t.Errorf("FAIL: a filter changed the ordinary role to %q", d.CommonRole)
}
}
func TestHomeCountAndEmptyState(t *testing.T) {
hh := newHomeHarness(t, 0)
hh.repos = homeRepos()
_, body, _, _ := hh.get(t, "/")
if !strings.Contains(body, `data-hook="dash-count"`) {
t.Error("FAIL: the count is not on the page before a filter is typed")
}
if i := strings.Index(body, `data-hook="dash-count"`); i >= 0 {
if rest := body[i:]; !strings.HasPrefix(rest[strings.Index(rest, ">")+1:], "</p>") {
t.Error("FAIL: the count says something while nothing is filtered")
}
}
_, body, _, _ = hh.get(t, "/?find=repo0")
if i := strings.Index(body, `data-hook="dash-count"`); i < 0 ||
strings.HasPrefix(body[i+strings.Index(body[i:], ">")+1:], "</p>") {
t.Error("FAIL: a filtered list has an empty count")
}
if strings.Contains(body, `data-hook="dash-empty"`) {
t.Error("FAIL: a list with matches shows the empty state")
}
_, body, _, _ = hh.get(t, "/?find=nonesuch")
for _, want := range []string{`data-hook="dash-empty"`, `data-hook="dash-clear"`, "nonesuch"} {
if !strings.Contains(body, want) {
t.Errorf("FAIL: the empty state has no %s", want)
}
}
if strings.Contains(body, `data-hook="dash-repos"`) {
t.Error("FAIL: an empty result still draws the list")
}
// A name that only a mirror answers to says so, since mirrors are
// hidden by default, and the clear link and the hint agree on where
// the rest is.
_, body, _, _ = hh.get(t, "/?find=mirror-a")
if !strings.Contains(body, `data-hook="dash-empty"`) || !strings.Contains(body, `data-hook="dash-hidden-mirrors"`) {
t.Error("FAIL: a search only a hidden mirror answers gives no way to it")
}
if !strings.Contains(body, `href="/?find=mirror-a&kind=all" data-hook="dash-hidden-mirrors"`) {
t.Errorf("FAIL: the hidden-mirrors link drops the name filter")
}
if !strings.Contains(body, `href="/" data-hook="dash-clear"`) {
t.Error("FAIL: the clear link leaves the default kind")
}
// Cleared from kind=all it stays on every kind.
_, body, _, _ = hh.get(t, "/?kind=all&find=nonesuch")
if !strings.Contains(body, `href="/?kind=all" data-hook="dash-clear"`) {
t.Error("FAIL: clearing a kind=all search leaves kind=all")
}
// Mirrors hidden by the default are said to exist, unfiltered too.
_, body, _, _ = hh.get(t, "/")
if !strings.Contains(body, `href="/?kind=all" data-hook="dash-hidden-mirrors"`) {
t.Error("FAIL: the default view does not say mirrors are hidden")
}
if _, body, _, _ = hh.get(t, "/?kind=all"); strings.Contains(body, `data-hook="dash-hidden-mirrors"`) {
t.Error("FAIL: kind=all says mirrors are hidden")
}
// An account whose every repository is a mirror is sent to all of
// them, not back to the empty default.
hh.repos = []map[string]any{{"name": "m1", "role": "admin", "mirror": true}}
if _, body, _, _ = hh.get(t, "/?find=zz"); !strings.Contains(body, `href="/?kind=all" data-hook="dash-clear"`) {
t.Error("FAIL: a mirror-only account's clear link leads back to an empty list")
}
hh.repos = homeRepos()
// An account with nothing at all is not told its filter is empty.
hh.repos = []map[string]any{}
if _, body, _, _ = hh.get(t, "/"); strings.Contains(body, `data-hook="dash-empty"`) {
t.Error("FAIL: an account with no repositories sees the filter's empty state")
}
}
// The activity feed's old home addresses still arrive at the activity
// page; the list's own kind values do not.
func TestHomeKindIsTheListsOwnSelector(t *testing.T) {
hh := newHomeHarness(t, 0)
for _, k := range []string{"native", "mirror", "all"} {
if code, _, _, _ := hh.get(t, "/?kind="+k); code != http.StatusOK {
t.Errorf("FAIL: /?kind=%s answered %d", k, code)
}
}
// A feed kind is still the old address of the activity page.
for _, k := range []string{"ci", "t", "w"} {
req := httptest.NewRequest("GET", "/?kind="+k, nil)
req.AddCookie(&http.Cookie{Name: sessionCookie, Value: "good"})
w := httptest.NewRecorder()
hh.h.ServeHTTP(w, req)
if w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/activity?kind="+k {
t.Errorf("FAIL: /?kind=%s answered %d to %q", k, w.Code, w.Header().Get("Location"))
}
}
}
// Stacked, what is waiting on you comes before your repositories in the
// document itself, so the reading and focus order are the visual one;
// side by side the grid puts the repositories in the first column.
func TestDashboardStacksTicketsFirstOnANarrowScreen(t *testing.T) {
hh := newHomeHarness(t, 1)
hh.repos = homeRepos()
_, body, _, _ := hh.get(t, "/")
tickets, side := strings.Index(body, `data-hook="dash-tickets"`), strings.Index(body, `data-hook="dash-side"`)
if tickets < 0 || side < 0 || tickets > side {
t.Errorf("FAIL: tickets at %d, repositories at %d: not tickets first", tickets, side)
}
if strings.Contains(styleSource, "order: -1") && strings.Contains(styleSource, ".dash-main") {
t.Error("FAIL: the dashboard reorders visually what the document does not")
}
i := strings.Index(styleSource, ".dash-home > .dash-side { grid-column: 1;")
if i < 0 {
t.Fatal("FAIL: no rule places the repositories in the first column")
}
open := strings.LastIndex(styleSource[:i], "@media")
if open < 0 || !strings.HasPrefix(styleSource[open:], "@media (min-width: 64rem)") {
t.Error("FAIL: the column placement is not confined to the wide layout")
}
}