package web
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"craftdesign.group/quarry/internal/ops"
)
type dashFeedIn struct {
Kind string `json:"kind"`
Find string `json:"find"`
Repo string `json:"repo"`
Offset int `json:"offset"`
}
type dashReposIn struct {
Find string `json:"find"`
}
type dashAcrossIn struct {
Awaiting bool `json:"awaiting"`
Mine bool `json:"mine"`
Yours bool `json:"yours"`
Brief bool `json:"brief"`
State string `json:"state"`
Limit int `json:"limit"`
}
type dashTeamsIn struct {
Mine bool `json:"mine"`
}
type dashListIn struct {
Q string `json:"q"`
Sort string `json:"sort"`
Kind string `json:"kind"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
type dashListOut struct {
Repos []map[string]any `json:"repos"`
Total int `json:"total"`
Served int `json:"served"`
}
type dashPeopleOut struct {
Total int `json:"total"`
}
// homeHarness is the home page over test doubles that count what the
// page asks for. yours is how many tickets ticket.across answers for the
// reader's own; every other ticket question answers one open ticket.
type homeHarness struct {
h http.Handler
mu sync.Mutex
feeds int
across []dashAcrossIn
// repos is what me.repos answers; nil is one repository, alpha.
repos []map[string]any
}
func newHomeHarness(t *testing.T, yours int) *homeHarness {
t.Helper()
hh := &homeHarness{}
r := ops.NewRegistry()
type empty struct{}
type tickets struct {
Tickets []map[string]any `json:"tickets"`
}
must := func(err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
must(ops.Register(r, ops.Op[dashFeedIn, struct {
Total int `json:"total"`
}]{Name: "me.feed", Doc: "test double", Kind: ops.Query, Auth: ops.Token, Route: "GET /api/v1/me/feed",
Run: func(context.Context, dashFeedIn) (struct {
Total int `json:"total"`
}, error) {
hh.mu.Lock()
hh.feeds++
hh.mu.Unlock()
return struct {
Total int `json:"total"`
}{}, nil
}}))
must(ops.Register(r, ops.Op[dashReposIn, struct {
Repos []map[string]any `json:"repos"`
}]{Name: "me.repos", Doc: "test double", Kind: ops.Query, Auth: ops.Token, Route: "GET /api/v1/me/repos",
Run: func(context.Context, dashReposIn) (struct {
Repos []map[string]any `json:"repos"`
}, error) {
return struct {
Repos []map[string]any `json:"repos"`
}{hh.rows()}, nil
}}))
must(ops.Register(r, ops.Op[dashAcrossIn, tickets]{Name: "ticket.across", Doc: "test double", Kind: ops.Query, Auth: ops.Token, Route: "GET /api/v1/me/tickets",
Run: func(_ context.Context, in dashAcrossIn) (tickets, error) {
hh.mu.Lock()
hh.across = append(hh.across, in)
hh.mu.Unlock()
n := 1
if in.Yours {
n = yours
}
var out tickets
for i := 0; i < n; i++ {
out.Tickets = append(out.Tickets, map[string]any{"repo": "alpha", "id": "abcdef0123456789",
"title": "a ticket", "status": "Open", "number": i + 1})
}
return out, nil
}}))
must(ops.Register(r, ops.Op[dashTeamsIn, struct {
Teams []struct{} `json:"teams"`
}]{Name: "team.list", Doc: "test double", Kind: ops.Query, Auth: ops.Token, Route: "GET /api/v1/teams",
Run: func(context.Context, dashTeamsIn) (struct {
Teams []struct{} `json:"teams"`
}, error) {
return struct {
Teams []struct{} `json:"teams"`
}{}, nil
}}))
must(ops.Register(r, ops.Op[dashListIn, dashListOut]{Name: "repo.list", Doc: "test double", Kind: ops.Query, Auth: ops.Anonymous, Route: "GET /api/v1/repos",
Run: func(context.Context, dashListIn) (dashListOut, error) {
return dashListOut{Repos: []map[string]any{{"name": "alpha"}}, Total: 1, Served: 1}, nil
}}))
must(ops.Register(r, ops.Op[dashListIn, dashPeopleOut]{Name: "people.list", Doc: "test double", Kind: ops.Query, Auth: ops.Anonymous, Route: "GET /api/v1/people",
Run: func(context.Context, dashListIn) (dashPeopleOut, error) {
return dashPeopleOut{Total: 1}, nil
}}))
must(ops.Register(r, ops.Op[empty, struct {
Version string `json:"version"`
}]{Name: "meta.version", Doc: "test double", Kind: ops.Query, Auth: ops.Anonymous, Route: "GET /api/v1/version",
Run: func(context.Context, empty) (struct {
Version string `json:"version"`
}, error) {
return struct {
Version string `json:"version"`
}{"t"}, nil
}}))
hh.h = HandlerWith(r, nil, nil, []Option{WithSessions(fakeSessions{user: "jan", roles: map[string]ops.Auth{"": ops.Token}})})
return hh
}
// get answers path as the signed-in reader, with what it asked for
// since the last call.
func (hh *homeHarness) get(t *testing.T, path string) (int, string, int, []dashAcrossIn) {
t.Helper()
hh.mu.Lock()
hh.feeds, hh.across = 0, nil
hh.mu.Unlock()
req := httptest.NewRequest("GET", path, nil)
req.AddCookie(&http.Cookie{Name: sessionCookie, Value: "good"})
w := httptest.NewRecorder()
hh.h.ServeHTTP(w, req)
hh.mu.Lock()
defer hh.mu.Unlock()
return w.Code, w.Body.String(), hh.feeds, hh.across
}
// The home page is where the reader works — repositories, teams,
// tickets — and none of it waits on the activity feed, which reads every
// event of every tracker the reader reaches. The feed follows the page
// in, behind a skeleton only script can show; without script the page
// links to the activity page instead.
func TestTheHomePageLeavesTheFeedForLater(t *testing.T) {
hh := newHomeHarness(t, 0)
code, body, feeds, across := hh.get(t, "/home")
if code != http.StatusOK {
t.Fatalf("FAIL: /home answered %d", code)
}
if feeds != 0 {
t.Errorf("FAIL: the home page asked for the feed %d times", feeds)
}
for _, want := range []string{`data-hook="dash-repos"`,
`data-init="@get('/activity?frag=recent')"`, `<noscript><p class="dash-more"><a href="/activity">`} {
if !strings.Contains(body, want) {
t.Errorf("FAIL: the home page has no %s", want)
}
}
// The skeleton is hidden until Datastar shows it.
if !strings.Contains(body, `style="display: none" data-show="true" aria-hidden="true" data-hook="dash-skeleton"`) {
t.Errorf("FAIL: the skeleton shows without script")
}
if len(across) != 0 {
t.Errorf("FAIL: the home page asked ticket.across: %+v", across)
}
// The rows arrive as one patch of the section, from the feed alone.
code, body, feeds, across = hh.get(t, "/activity?frag=recent")
if code != http.StatusOK || feeds != 1 || len(across) != 0 || !strings.Contains(body, `data-hook="dash-activity"`) {
t.Errorf("FAIL: ?frag=recent: %d, %d feeds, %d ticket asks", code, feeds, len(across))
}
// The band of tickets waiting on you leads the activity page's ticket
// changes, and is asked for there only.
if _, _, _, across = hh.get(t, "/activity?kind=t"); len(across) != 1 || !across[0].Awaiting {
t.Errorf("FAIL: ticket changes did not ask for the waiting band: %+v", across)
}
if _, _, _, across = hh.get(t, "/activity?kind=c"); len(across) != 0 {
t.Errorf("FAIL: check-ins asked for the waiting band")
}
}
// The feed as it was addressed on the home page arrives at the activity
// page, its filters kept.
func TestTheOldFeedAddressesArriveAtTheActivityPage(t *testing.T) {
hh := newHomeHarness(t, 0)
for path, want := range map[string]string{
"/?kind=t": "/activity?kind=t",
"/?offset=10&repo=x": "/activity?offset=10&repo=x",
"/?frag=1&kind=w": "/activity?kind=w",
} {
req := httptest.NewRequest("GET", path, 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") != want {
t.Errorf("FAIL: %s answered %d to %q, want %s", path, w.Code, w.Header().Get("Location"), want)
}
}
}
// The home lists no tickets: the reader's own are the bar's ticket
// button away, and what moved on them is in activity.
func TestTheHomeListsNoTickets(t *testing.T) {
_, body, _, across := newHomeHarness(t, 2).get(t, "/home")
if strings.Contains(body, `data-hook="dash-ticket"`) || len(across) != 0 {
t.Errorf("FAIL: the home page still lists tickets (%d asks)", len(across))
}
if !strings.Contains(body, `href="/tickets"`) {
t.Error("FAIL: no way to the reader's tickets")
}
}
func (hh *homeHarness) rows() []map[string]any {
if hh.repos != nil {
return hh.repos
}
return []map[string]any{{"name": "alpha", "role": "admin"}}
}
// A repository that is down and still the reader's is marked on their
// dashboard, by its strength, and one that is up carries no mark.
func TestTheDashboardMarksARepositoryThatIsDown(t *testing.T) {
hh := newHomeHarness(t, 0)
hh.repos = []map[string]any{
{"name": "alpha", "role": "admin"},
{"name": "beta", "role": "admin", "takenDown": "disabled"},
{"name": "gamma", "role": "admin", "takenDown": "hold"},
}
_, body, _, _ := hh.get(t, "/home")
if n := strings.Count(body, `data-hook="taken-down"`); n != 2 {
t.Errorf("FAIL: %d takedown marks on the dashboard, want 2", n)
}
if !t.Failed() {
t.Log("ok")
}
}
func (hh *homeHarness) redirect(t *testing.T, path string, signedIn bool) (int, string) {
t.Helper()
req := httptest.NewRequest("GET", path, nil)
if signedIn {
req.AddCookie(&http.Cookie{Name: sessionCookie, Value: "good"})
}
w := httptest.NewRecorder()
hh.h.ServeHTTP(w, req)
return w.Code, w.Header().Get("Location")
}
// The front page is one page for everyone. A signed-in reader's "/" is
// the forge's listing, and the filters the dashboard used to own go to
// /home with find and vis kept; repos=all is dropped, since the list is
// always whole.
func TestTheRootIsTheFrontPageForEveryone(t *testing.T) {
hh := newHomeHarness(t, 0)
for _, signedIn := range []bool{false, true} {
code, body, _ := fragGet(hh, "/", signedIn)
if code != http.StatusOK || !strings.Contains(body, `id="explore"`) || strings.Contains(body, `data-hook="dash-repos"`) {
t.Errorf("FAIL: / (signed in %v) answered %d and is not the listing", signedIn, code)
}
}
for path, want := range map[string]string{
"/?find=pi": "/home?find=pi",
"/?vis=private": "/home?vis=private",
"/?find=pi&vis=public&x=1": "/home?find=pi&vis=public",
"/?repos=all": "/home",
"/?repos=all&find=a%20b": "/home?find=a+b",
"/?find=pi&kind=mirror": "/home?find=pi",
"/?find=pi&repo=quarry": "/activity?find=pi&repo=quarry",
"/?kind=t": "/activity?kind=t",
"/?offset=10": "/activity?offset=10",
} {
if code, loc := hh.redirect(t, path, true); code != http.StatusSeeOther || loc != want {
t.Errorf("FAIL: signed in, %s answered %d to %q, want %s", path, code, loc, want)
}
}
// The front page's own parameters, and the alias, stay put.
for _, path := range []string{"/?view=explore", "/?q=pi", "/?sort=size", "/?kind=mirror", "/?kind=native", "/?kind=all", "/?find=x&view=explore"} {
if code, loc := hh.redirect(t, path, true); code != http.StatusOK {
t.Errorf("FAIL: signed in, %s answered %d to %q, want the listing", path, code, loc)
}
}
// A visitor is never sent anywhere by them.
if code, loc := hh.redirect(t, "/?find=pi", false); code != http.StatusOK {
t.Errorf("FAIL: signed out, /?find=pi answered %d to %q", code, loc)
}
if !t.Failed() {
t.Log("ok")
}
}
// /home is the reader's own page: a visitor is sent to sign in and back,
// the way /activity and /tickets send them, never shown the forge's list
// as if it were theirs.
func TestHomeSendsAVisitorToSignIn(t *testing.T) {
hh := newHomeHarness(t, 0)
if code, loc := hh.redirect(t, "/home", false); code != http.StatusSeeOther || loc != "/login?next=/home" {
t.Errorf("FAIL: /home signed out answered %d to %q", code, loc)
}
code, body, _ := fragGet(hh, "/home", true)
if code != http.StatusOK || !strings.Contains(body, `data-hook="dash-repos"`) {
t.Errorf("FAIL: /home signed in answered %d without the list", code)
}
}
// The house button: third in the bar after search and create, signed in
// only, and marked current on /home and on Activity, its tab.
func TestHouseButtonIsThirdAndLit(t *testing.T) {
hh := newHomeHarness(t, 0)
for path, lit := range map[string]bool{"/home": true, "/activity": true, "/": false, "/tickets": false} {
_, body, _ := fragGet(hh, path, true)
home := strings.Index(body, `data-hook="home-btn"`)
create, tickets := strings.Index(body, `popovertarget="create"`), strings.Index(body, `href="/tickets"`)
if home < 0 || !(strings.Index(body, `popovertarget="find"`) < create && create < home && home < tickets) {
t.Errorf("FAIL: %s: bar order is create %d, home %d, tickets %d", path, create, home, tickets)
continue
}
tag := body[strings.LastIndex(body[:home], "<a "):]
tag = tag[:strings.Index(tag, ">")]
if got := strings.Contains(tag, `aria-current="page"`); got != lit {
t.Errorf("FAIL: %s: house marked current = %v, want %v", path, got, lit)
}
}
if _, body, _ := fragGet(hh, "/", false); strings.Contains(body, `data-hook="home-btn"`) {
t.Error("FAIL: a visitor is shown the house button")
}
if !strings.Contains(styleSource, "@media (max-width: 30rem) { .topbar .site .wordmark { display: none; } }") {
t.Error("FAIL: the wordmark does not give way at 30rem")
}
}