v0.35.2 80d5067

export_test.go RawHistoryFolder

1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package usecase
4
5import (
6	"context"
7	"crypto/rsa"
8	"slices"
9	"strconv"
10	"time"
11
12	"bnema.dev/ermite-actions/expr"
13	"bnema.dev/ermite-actions/template"
14	"bnema.dev/ermite-actions/workflow"
15	"bnema.dev/ermite/internal/domain"
16	"bnema.dev/ermite/internal/ports"
17)
18
19// Sweep exposes the daily sweep to the tests.
20func (c *CI) Sweep(ctx context.Context) { c.sweep(ctx) }
21
22// TouchPushedAt exposes touchPushedAt to the tests.
23func TouchPushedAt(ctx context.Context, meta ports.RepoMetaStore, name domain.RepoName, now time.Time) (domain.Repo, error) {
24	return touchPushedAt(ctx, meta, name, now)
25}
26
27// TouchActiveAt exposes touchActiveAt to the tests.
28func TouchActiveAt(ctx context.Context, meta ports.RepoMetaStore, name domain.RepoName, now time.Time) (domain.Repo, error) {
29	return touchActiveAt(ctx, meta, name, now)
30}
31
32// RunTitle gives the title of a run as startRun sets it: the evaluated
33// run-name, else commitTitle.
34func (c *CI) RunTitle(ctx context.Context, wf *workflow.Workflow, githubJSON, commitTitle string) string {
35	if name, ok := c.evalRunName(ctx, wf, githubJSON, expr.NewDictionary()); ok {
36		return name
37	}
38	return commitTitle
39}
40
41// CheckRunID exposes checkRunID to the tests.
42func CheckRunID(ctx context.Context, run domain.CIRun, index, combo int) int64 {
43	return checkRunID(ctx, run, index, combo)
44}
45
46// SecretUse is the result of SecretsUsedBy.
47type SecretUse = secretUse
48
49// SecretsUsedBy exposes secretsUsedBy to the tests.
50func SecretsUsedBy(workflowYAML, jobID string) SecretUse {
51	return secretsUsedBy(workflowYAML, jobID)
52}
53
54// SecretWalks is the number of YAML walks made so far.
55func SecretWalks() int64 { return secretWalks.Load() }
56
57// SecretUseCache is a wfCache exposed to the tests.
58type SecretUseCache struct{ c *wfCache }
59
60// NewSecretUseCache builds a cache for up to max runs.
61func NewSecretUseCache(max int) *SecretUseCache { return &SecretUseCache{newWfCache(max)} }
62
63// Use is wfCache.secretUse.
64func (s *SecretUseCache) Use(runID int64, yaml, jobKey string) SecretUse {
65	return s.c.secretUse(runID, yaml, jobKey)
66}
67
68// Drop is wfCache.drop.
69func (s *SecretUseCache) Drop(runID int64) { s.c.drop(runID) }
70
71// EvalConcurrency exposes evalConcurrency to the tests.
72func EvalConcurrency(ctx context.Context, tok template.Token, env template.Env) (domain.CIConcurrency, error) {
73	return evalConcurrency(ctx, tok, env)
74}
75
76// MatchPullRequest exposes the pull_request filter to the tests.
77func MatchPullRequest(wf *workflow.Workflow, action, base string, files []string, truncated bool) bool {
78	return matchPullRequest(wf, "pull_request", action, base, files, truncated)
79}
80
81// MatchPullRequestTarget exposes the pull_request_target filter to the tests.
82func MatchPullRequestTarget(wf *workflow.Workflow, action, base string, files []string, truncated bool) bool {
83	return matchPullRequest(wf, "pull_request_target", action, base, files, truncated)
84}
85
86// MatchWorkflowRun exposes the workflow_run filter to the tests.
87func MatchWorkflowRun(wf *workflow.Workflow, name, action, headBranch string) bool {
88	return matchWorkflowRun(wf, name, action, headBranch)
89}
90
91// ResolveDispatchInputs exposes resolveDispatchInputs to the tests.
92func ResolveDispatchInputs(defs []workflow.Input, given map[string]string) (map[string]string, error) {
93	return resolveDispatchInputs(defs, given)
94}
95
96// PullFilesLink exposes the Link header of the files endpoint to the tests.
97func PullFilesLink(base string, page, perPage, total int) string {
98	return pullFilesLink(base, page, perPage, total)
99}
100
101// FilePatch exposes the patch text of a file of the files endpoint to the tests.
102func FilePatch(f domain.FileDiff) (string, bool) { return filePatch(f) }
103
104// PullTipsTrusted exposes the trust check of an activity of a merge request to
105// the tests, on a CI that has cfg and no workers.
106func PullTipsTrusted(ctx context.Context, cfg CIConfig, repo domain.RepoName, ev ports.PullRequestEvent) (bool, domain.ObjectID) {
107	return (&CI{cfg: cfg}).pullTipsTrusted(ctx, repo, ev)
108}
109
110// Thumbprint exposes thumbprint to the tests.
111func Thumbprint(pub *rsa.PublicKey) string { return thumbprint(pub) }
112
113// IDTokenClaims gives the claims idTokenClaims builds, decoded.
114func IDTokenClaims(contextsJSON, environment, issuer, audience string, at time.Time) (map[string]any, []string, error) {
115	claims, err := idTokenClaims(contextsJSON, environment, idTokenMeta{issuer: issuer, audience: audience, jti: "jti", now: at})
116	if err != nil {
117		return nil, nil, err
118	}
119	out := make(map[string]any, len(claims))
120	keys := make([]string, 0, len(claims))
121	for _, p := range claims {
122		out[p.k] = p.v
123		keys = append(keys, p.k)
124	}
125	return out, keys, nil
126}
127
128// SignForTest signs claims (in the order of their keys) with the signing key.
129func (o *OIDC) SignForTest(claims map[string]any) (string, error) {
130	keys := make([]string, 0, len(claims))
131	for k := range claims {
132		keys = append(keys, k)
133	}
134	slices.Sort(keys)
135	out := make(ordered, 0, len(keys))
136	for _, k := range keys {
137		out = append(out, pair{k, claims[k]})
138	}
139	return o.sign(out)
140}
141
142// DifficultyFor exposes the adaptive difficulty with the production base and
143// cap to the tests.
144func DifficultyFor(perAddr, global int) int {
145	return difficultyFor(baseDifficulty, maxDifficulty, perAddr, global)
146}
147
148// Production parameters of the submission, for the tests.
149const (
150	BaseDifficulty = baseDifficulty
151	MaxDifficulty  = maxDifficulty
152	MinFillTime    = minFillTime
153	ChallengeTTL   = challengeTTL
154)
155
156// SpentLen is the number of nonces the submission remembers as spent.
157func (s *IssueSubmissions) SpentLen() int {
158	s.mu.Lock()
159	defer s.mu.Unlock()
160	return len(s.spent)
161}
162
163// FillSpent fills the spent set with n unexpired nonces.
164func (s *IssueSubmissions) FillSpent(n int, exp time.Time) {
165	s.mu.Lock()
166	defer s.mu.Unlock()
167	for i := range n {
168		s.spent["fill"+strconv.Itoa(i)] = exp
169	}
170}
171
172// MaxSpent is the bound of the spent set.
173const MaxSpent = maxSpent
174
175// SetAfterMergeGate makes the post-merge goroutine of m run f before anything
176// else, to place a test between a merge and its side effects.
177func (m *MergeRequests) SetAfterMergeGate(f func()) { m.afterGate = f }
178
179// ScheduledRetries gives the number of retries waiting in the scheduler.
180func (s *Mergeability) ScheduledRetries() int {
181	s.retryMu.Lock()
182	defer s.retryMu.Unlock()
183	return len(s.heap)
184}
185
186// RetryAttempts gives the number of repositories whose
187// failed attempts are counted.
188func (s *Mergeability) RetryAttempts() int {
189	s.retryMu.Lock()
190	defer s.retryMu.Unlock()
191	return len(s.retries)
192}
193
194// ReconcileForTest runs a repository pass synchronously without workers.
195func (s *Mergeability) ReconcileForTest(repo domain.RepoName) bool { return s.reconcile(repo) }
196
197// RetryForTest schedules a retry of repo as a failed pass does.
198func (s *Mergeability) RetryForTest(repo domain.RepoName) { s.retry(repo) }
199
200// RetryDoneForTest forgets the retries of repo as a successful pass does.
201func (s *Mergeability) RetryDoneForTest(repo domain.RepoName) { s.retryDone(repo) }
202
203// RetryDueForTest gives the deadline of the retry scheduled for repo.
204func (s *Mergeability) RetryDueForTest(repo domain.RepoName) (time.Time, bool) {
205	s.retryMu.Lock()
206	defer s.retryMu.Unlock()
207	for _, it := range s.heap {
208		if it.key == repo {
209			return it.due, true
210		}
211	}
212	return time.Time{}, false
213}
214
215// PopDueForTest is the scheduler step taken when the timer armed for the
216// retry (repo, due) fires. It gives the repositories it released.
217func (s *Mergeability) PopDueForTest(repo domain.RepoName, due time.Time) []domain.RepoName {
218	return s.popDue(retryItem{key: repo, due: due})
219}
220
221// WindowLimits exposes windowLimits to the tests.
222var WindowLimits = windowLimits
223
224// SetChecks installs a checks reader before starting a test evaluator.
225func (m *MergeRequests) SetChecks(checks ports.CIChecksReader) { m.checks = checks }
226
227// Evaluate exposes a single synchronous pass without starting workers.
228func (s *AutoMerge) Evaluate(repo domain.RepoName) bool { return s.evaluate(repo) }
229
230// QueuePush exposes the normal trigger queue for activity accounting tests.
231func (c *CI) QueuePush(ctx context.Context, repo domain.RepoName) {
232	c.enqueue(ctx, repo, []domain.RefUpdate{{Ref: "refs/heads/main"}}, "owner", domain.PusherOf(domain.Root()), true)
233}
234
235// PlanQueuedPush handles the next queued trigger without starting workers.
236func (c *CI) PlanQueuedPush() { c.planPush(<-c.queue) }
237
238// QueuePull exposes the pull activity queue for accounting tests.
239func (c *CI) QueuePull(repo domain.RepoName, number int64) {
240	c.queuePullEvent(pullEvent{repo: repo, number: number})
241}
242
243// FinishQueuedPull completes one test activity without planning workflows.
244func (c *CI) FinishQueuedPull() {
245	e := <-c.pull.events
246	c.finishPull(pullKey{repo: e.repo, number: e.number})
247	c.kickAutoMerge(c.ctx, e.repo)
248}
249
250// SetWorkflowTrigger installs the merge hook before evaluation.
251func (m *MergeRequests) SetWorkflowTrigger(t ports.WorkflowTrigger) { m.ci = t }
252
253// UnderRunLock exposes the production run lock to test nonblocking triggers.
254func (c *CI) UnderRunLock(id int64, fn func()) {
255	lock := c.runLock(id)
256	lock.Lock()
257	defer lock.Unlock()
258	fn()
259}
260
261// UnderRepoLock holds the production merge lock while a test interleaves a kick.
262func (m *MergeRequests) UnderRepoLock(ctx context.Context, repo domain.RepoName, fn func()) error {
263	unlock, err := m.lockRepo(ctx, repo)
264	if err != nil {
265		return err
266	}
267	defer unlock()
268	fn()
269	return nil
270}

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 2

Tags 45

↑↓ moveenter openesc close