v0.23.0 333c710

home_test.go RawHistoryFolder

1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package web
4
5import (
6	"bytes"
7	"context"
8	"errors"
9	"fmt"
10	"net/http"
11	"net/http/httptest"
12	"strings"
13	"sync/atomic"
14	"testing"
15	"time"
16
17	"github.com/stretchr/testify/assert"
18	"github.com/stretchr/testify/mock"
19	"github.com/stretchr/testify/require"
20
21	"bnema.dev/ermite/internal/domain"
22	"bnema.dev/ermite/internal/ports"
23	"bnema.dev/ermite/internal/ports/mocks"
24)
25
26// pushedRepo is a public repository that was pushed to.
27func pushedRepo(t testing.TB, name string) ports.RepoView {
28	t.Helper()
29	v := publicRepo(t, name)
30	v.PushedAt = time.Now().Add(-time.Hour)
31	return v
32}
33
34// homeCommits are n commits, newest first, with distinct ids and subjects.
35func homeCommits(t testing.TB, n int) []domain.Commit {
36	t.Helper()
37	var out []domain.Commit
38	for i := n; i >= 1; i-- {
39		out = append(out, domain.Commit{
40			ID:        objectID(t, fmt.Sprintf("%040x", i)),
41			Summary:   fmt.Sprintf("subject number %d", i),
42			Committer: domain.Signature{Time: time.Now().Add(-time.Duration(i) * time.Minute)},
43		})
44	}
45	return out
46}
47
48// homeBrowse is a BrowseService whose figures are always there: 1234
49// commits, 7 of them recent, no tag. Tests that care set their own.
50func homeBrowse(t *testing.T) *mocks.BrowseService {
51	t.Helper()
52	b := mocks.NewBrowseService(t)
53	b.EXPECT().RepoStats(mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).
54		Return(ports.RepoStats{Commits: 1234, Recent: 7}, nil).Maybe()
55	return b
56}
57
58// Each row shows the figures of its repository: commits, recent commits,
59// latest tag and last activity; no branch name.
60func TestHomeRowFigures(t *testing.T) {
61	t.Parallel()
62	repo := repoName(t, "proj")
63	head := objectID(t, fmt.Sprintf("%040x", 2))
64	now := time.Now()
65	browse := mocks.NewBrowseService(t)
66	browse.EXPECT().ListCommits(mock.Anything, mock.Anything, repo, mock.Anything).Return(ports.HistoryPage{Commits: homeCommits(t, 2)}, nil)
67	browse.EXPECT().RepoStats(mock.Anything, mock.Anything, repo, head, now).Return(ports.RepoStats{
68		Commits: 12345, Recent: 42, LatestTag: &domain.TagInfo{Name: "v1.2.0", At: now.Add(-3 * time.Hour), CommitID: head},
69	}, nil).Once()
70	srv := newTestServer(t, Config{Repos: reposServing(t, pushedRepo(t, "proj")), Browse: browse})
71
72	row := srv.homeRowOf(context.Background(), pushedRepo(t, "proj"), now, false)
73	require.NotNil(t, row.Stats)
74	out := renderRow(t, row)
75	assert.Contains(t, out, "<dt>commits</dt><dd>12\u202f345</dd>")
76	assert.Contains(t, out, "<dt>last 30 days</dt><dd>42</dd>")
77	assert.Contains(t, out, `<a href="/proj/tree/`+head.String()+`" title="made 3h ago">v1.2.0</a>`, "by its commit: a branch may share its name")
78	assert.Contains(t, out, "<dt>last activity</dt>")
79	assert.NotContains(t, out, "i-branch", "the default branch is not shown")
80	assert.NotContains(t, out, "pushed")
81
82	// A failed read leaves the figures out, not the row.
83	browse.EXPECT().RepoStats(mock.Anything, mock.Anything, repo, head, now).Return(ports.RepoStats{}, errors.New("boom")).Once()
84	row = srv.homeRowOf(context.Background(), pushedRepo(t, "proj"), now, false)
85	assert.Nil(t, row.Stats)
86	assert.Len(t, row.Commits, 2)
87	assert.NotContains(t, renderRow(t, row), "<dt>commits</dt>")
88}
89
90func TestGrouped(t *testing.T) {
91	t.Parallel()
92	for n, want := range map[int]string{0: "0", 999: "999", 1000: "1\u202f000", 1234567: "1\u202f234\u202f567"} {
93		assert.Equal(t, want, grouped(n), n)
94	}
95}
96
97func renderRow(t testing.TB, r HomeRow) string {
98	t.Helper()
99	var b bytes.Buffer
100	require.NoError(t, HomeRowView(r).Render(context.Background(), &b))
101	return b.String()
102}
103
104func mustRevision(t testing.TB, s string) domain.Revision {
105	t.Helper()
106	r, err := domain.ParseRevision(s)
107	require.NoError(t, err)
108	return r
109}
110
111// Each row lists at most five commits of the default branch, read by the full
112// name of the branch.
113func TestHomeRowShowsFiveCommits(t *testing.T) {
114	t.Parallel()
115	browse := homeBrowse(t)
116	browse.EXPECT().ListCommits(mock.Anything, mock.Anything, repoName(t, "proj"), ports.ListCommitsParams{
117		Revision: mustRevision(t, "refs/heads/main"), PageSize: homeRecent,
118	}).Return(ports.HistoryPage{Commits: homeCommits(t, 7)}, nil).Once()
119	srv := newTestServer(t, Config{Repos: reposServing(t, pushedRepo(t, "proj")), Browse: browse})
120
121	row := srv.homeRowOf(context.Background(), pushedRepo(t, "proj"), time.Now(), false)
122	require.Len(t, row.Commits, homeRecent)
123	assert.Equal(t, "subject number 7", row.Commits[0].Subject)
124	assert.False(t, row.NoCommits)
125	assert.Nil(t, row.CI, "a server without CI shows no state")
126
127	out := renderRow(t, row)
128	assert.Equal(t, homeRecent, strings.Count(out, `class="rc-sha"`))
129	assert.Contains(t, out, `href="/proj/commit/`+fmt.Sprintf("%040x", 7)+`"`)
130	assert.Contains(t, out, `aria-label="Recent commits of proj"`)
131	assert.NotContains(t, out, `class="repo-ci"`)
132}
133
134func TestHomeRowEmptyRepository(t *testing.T) {
135	t.Parallel()
136	// Never pushed: nothing is read.
137	srv := newTestServer(t, Config{Repos: reposServing(t, publicRepo(t, "new")), Browse: mocks.NewBrowseService(t), Runs: mocks.NewRunService(t)})
138	row := srv.homeRowOf(context.Background(), publicRepo(t, "new"), time.Now(), false)
139	assert.True(t, row.NoCommits)
140	out := renderRow(t, row)
141	assert.Contains(t, out, "no commits yet")
142	assert.Contains(t, out, `<dt>last activity</dt><dd class="mute">never</dd>`)
143	assert.NotContains(t, out, "<dt>commits</dt>", "no figures without a commit")
144	assert.NotContains(t, out, "repo-commits\" aria-label")
145}
146
147func TestHomeRowCI(t *testing.T) {
148	t.Parallel()
149	repo := repoName(t, "proj")
150	head := fmt.Sprintf("%040x", 2) // the newest of homeCommits(t, 2)
151	check := func(run int64, status domain.CIStatus, c domain.CIConclusion) ports.CheckView {
152		return ports.CheckView{CICheck: domain.CICheck{Repo: repo, Sha: head, Name: "ci / test", RunID: run, Status: status, Conclusion: c}}
153	}
154	tests := []struct {
155		name   string
156		checks []ports.CheckView
157		err    error
158		label  string // "" when no state is shown
159		href   string
160	}{
161		{"passing", []ports.CheckView{check(9, domain.CICompleted, domain.CISuccess)}, nil, "passing", "/proj/actions/runs/9"},
162		{"failing", []ports.CheckView{check(9, domain.CICompleted, domain.CISuccess), check(9, domain.CICompleted, domain.CIFailure)}, nil, "failing", "/proj/actions/runs/9"},
163		{"running", []ports.CheckView{check(9, domain.CIInProgress, "")}, nil, "running", "/proj/actions/runs/9"},
164		{"several runs link the commit", []ports.CheckView{check(9, domain.CICompleted, domain.CISuccess), check(10, domain.CICompleted, domain.CISuccess)}, nil, "passing", "/proj/commit/" + head},
165		{"no check on the head", nil, nil, "", ""},
166		{"the viewer cannot read CI", nil, domain.ErrNotFound, "", ""},
167		{"the read fails", nil, errors.New("boom"), "", ""},
168	}
169	for _, tt := range tests {
170		t.Run(tt.name, func(t *testing.T) {
171			t.Parallel()
172			browse := homeBrowse(t)
173			browse.EXPECT().ListCommits(mock.Anything, mock.Anything, repo, mock.Anything).Return(ports.HistoryPage{Commits: homeCommits(t, 2)}, nil)
174			runs := mocks.NewRunService(t)
175			runs.EXPECT().ListChecks(mock.Anything, mock.Anything, repo, head).
176				Return(ports.ChecksResult{Checks: tt.checks}, tt.err).Once()
177			srv := newTestServer(t, Config{Repos: reposServing(t, pushedRepo(t, "proj")), Browse: browse, Runs: runs})
178
179			row := srv.homeRowOf(context.Background(), pushedRepo(t, "proj"), time.Now(), false)
180			require.Len(t, row.Commits, 2, "the commits do not depend on CI")
181			out := renderRow(t, row)
182			if tt.label == "" {
183				assert.Nil(t, row.CI)
184				assert.NotContains(t, out, "repo-ci")
185				return
186			}
187			require.NotNil(t, row.CI)
188			assert.Contains(t, out, `class="repo-ci" href="`+tt.href+`"`)
189			assert.Contains(t, out, tt.label, "the state has a word, not only a mark")
190			assert.Contains(t, out, `<span class="sr">CI: </span>`)
191		})
192	}
193}
194
195// The private badge is for the signed-in owner only.
196func TestHomeRowPrivateBadge(t *testing.T) {
197	t.Parallel()
198	priv := pushedRepo(t, "secret")
199	priv.Visibility = domain.VisibilityPrivate
200	browse := homeBrowse(t)
201	browse.EXPECT().ListCommits(mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(ports.HistoryPage{}, nil).Maybe()
202	srv := newTestServer(t, Config{Repos: reposServing(t, priv, pushedRepo(t, "open")), Browse: browse})
203
204	signed := context.WithValue(context.Background(), signedInKey{}, struct{}{})
205	assert.Contains(t, renderRow(t, srv.homeRowOf(signed, priv, time.Now(), false)), `<span class="pill">private</span>`)
206	assert.NotContains(t, renderRow(t, srv.homeRowOf(context.Background(), priv, time.Now(), false)), "private")
207	assert.NotContains(t, renderRow(t, srv.homeRowOf(signed, pushedRepo(t, "open"), time.Now(), false)), "private")
208}
209
210// A run update re-renders the home row, so its CI state follows the run.
211func TestRunUpdatedRefreshesTheHomeRow(t *testing.T) {
212	t.Parallel()
213	repo := repoName(t, "proj")
214	head := fmt.Sprintf("%040x", 2)
215	browse := homeBrowse(t)
216	browse.EXPECT().ListCommits(mock.Anything, mock.Anything, repo, mock.Anything).Return(ports.HistoryPage{Commits: homeCommits(t, 2)}, nil)
217	runs := mocks.NewRunService(t)
218	runs.EXPECT().ListChecks(mock.Anything, mock.Anything, repo, head).Return(ports.ChecksResult{Checks: []ports.CheckView{
219		{CICheck: domain.CICheck{Repo: repo, Sha: head, RunID: 9, Status: domain.CICompleted, Conclusion: domain.CISuccess}},
220	}}, nil).Once()
221	srv := newTestServer(t, Config{Repos: reposServing(t, pushedRepo(t, "proj")), Browse: browse, Runs: runs})
222
223	got, err := (&liveStream{s: srv}).render(t.Context(), ports.WatchEvent{Event: domain.RunUpdated{Run: domain.CIRun{Repo: repo, ID: 9}}})
224	require.NoError(t, err)
225	require.Len(t, got, 1)
226	assert.Equal(t, "home-list", got[0].event)
227	assert.Contains(t, got[0].html, `id="repo-proj"`)
228	assert.Contains(t, got[0].html, "passing")
229	assert.NotContains(t, got[0].html, "new push", "a run is not a push")
230
231	// A job that ended refreshes the row too; one in progress does not.
232	got, err = (&liveStream{s: srv}).render(t.Context(), ports.WatchEvent{Event: domain.JobUpdated{Job: domain.CIJob{Repo: repo, Phase: domain.CIPhaseRunning}}})
233	require.NoError(t, err)
234	assert.Empty(t, got)
235	runs.EXPECT().ListChecks(mock.Anything, mock.Anything, repo, head).Return(ports.ChecksResult{Checks: []ports.CheckView{
236		{CICheck: domain.CICheck{Repo: repo, Sha: head, RunID: 9, Status: domain.CICompleted, Conclusion: domain.CIFailure}},
237		{CICheck: domain.CICheck{Repo: repo, Sha: head, RunID: 9, Status: domain.CIInProgress}},
238	}}, nil).Once()
239	got, err = (&liveStream{s: srv}).render(t.Context(), ports.WatchEvent{Event: domain.JobUpdated{Job: domain.CIJob{Repo: repo, Phase: domain.CIPhaseEnded}}})
240	require.NoError(t, err)
241	require.Len(t, got, 1)
242	assert.Contains(t, got[0].html, "failing", "a failed job shows before its run ends")
243}
244
245// A repository whose commits cannot be read keeps its row, and the page is
246// served; the others are not affected.
247func TestHomeSurvivesABrokenRepository(t *testing.T) {
248	t.Parallel()
249	browse := homeBrowse(t)
250	browse.EXPECT().ListCommits(mock.Anything, mock.Anything, repoName(t, "broken"), mock.Anything).
251		Return(ports.HistoryPage{}, errors.New("git exploded")).Once()
252	browse.EXPECT().ListCommits(mock.Anything, mock.Anything, repoName(t, "fine"), mock.Anything).
253		Return(ports.HistoryPage{Commits: homeCommits(t, 3)}, nil).Once()
254	srv := newTestServer(t, Config{Repos: reposServing(t, pushedRepo(t, "broken"), pushedRepo(t, "fine")), Browse: browse})
255
256	rec := httptest.NewRecorder()
257	srv.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/?sort=name", nil))
258	require.Equal(t, http.StatusOK, rec.Code)
259	body := rec.Body.String()
260	assert.Contains(t, body, `id="repo-broken"`)
261	assert.Contains(t, body, `id="repo-fine"`)
262	assert.Equal(t, 3, strings.Count(body, `class="rc-sha"`), "only the readable repository lists commits")
263	assert.NotContains(t, body, "no commits yet", "a failed read is not an empty branch")
264}
265
266// The rows are read a few at a time, in the order of the list.
267func TestHomeRowsAreBoundedAndOrdered(t *testing.T) {
268	t.Parallel()
269	const n = 40
270	var views []ports.RepoView
271	for i := range n {
272		views = append(views, pushedRepo(t, fmt.Sprintf("r%02d", i)))
273	}
274	var running, peak atomic.Int32
275	browse := homeBrowse(t)
276	browse.EXPECT().ListCommits(mock.Anything, mock.Anything, mock.Anything, mock.Anything).RunAndReturn(
277		func(context.Context, domain.Principal, domain.RepoName, ports.ListCommitsParams) (ports.HistoryPage, error) {
278			cur := running.Add(1)
279			for p := peak.Load(); cur > p && !peak.CompareAndSwap(p, cur); p = peak.Load() {
280			}
281			time.Sleep(2 * time.Millisecond)
282			running.Add(-1)
283			return ports.HistoryPage{Commits: homeCommits(t, 1)}, nil
284		})
285	srv := newTestServer(t, Config{Repos: reposServing(t, views...), Browse: browse})
286
287	rows := srv.homeRows(context.Background(), views, time.Now())
288	require.Len(t, rows, n)
289	for i, r := range rows {
290		assert.Equal(t, fmt.Sprintf("r%02d", i), r.Name)
291		assert.Len(t, r.Commits, 1)
292	}
293	assert.True(t, rows[0].Cursor)
294	assert.LessOrEqual(t, int(peak.Load()), homeWorkers)
295	assert.Greater(t, int(peak.Load()), 1, "the reads overlap")
296}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 4

Tags 45

↑↓ moveenter openesc close