@webship-js/gitea-steps 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,499 @@
1
+ 'use strict';
2
+
3
+ // Shared helpers for the step files of this pack.
4
+ //
5
+ // Not a step file: it registers no step definitions and no hooks. It holds the plumbing the steps use and that
6
+ // another pack can require instead of copying: the wait budget, presence assertions with friendly errors, URL
7
+ // building, the users registry, signing in (the form, and a session put back), the forge's REST API as the managing
8
+ // account (the test content a scenario makes and removes), and the issues a scenario made, which go after it.
9
+ //
10
+ // One pack serves Gitea and Forgejo. Forgejo is a fork of Gitea that keeps its API, its addresses and most of its
11
+ // screens; where the two draw a control differently (Forgejo 17 is built on Gitea 1.22, Gitea 1.27 has a newer issue
12
+ // sidebar), the helpers below look for either, and CI runs every step on both.
13
+ //
14
+ // Everything here builds on webship-js's own helpers (`gotoUrl`, `smartSettle`, `waitForPageLoad`, `friendly`) so the
15
+ // steps behave like the core webship-js steps.
16
+
17
+ const { gotoUrl, smartSettle, waitForPageLoad, friendly } = require('webship-js/tests/step-definitions/webship');
18
+
19
+ let playwright;
20
+ try { playwright = require('playwright'); } catch { playwright = require(require.resolve('playwright', { paths: [require.resolve('webship-js/package.json')] })); }
21
+
22
+ /**
23
+ * The per-assertion wait budget: `minWaitTime.page` from cucumber.js, at least 10 seconds, so a slow page does not fail
24
+ * an assertion that would pass a moment later. Kept below webship-js's 45 second step timeout.
25
+ *
26
+ * @param {object} world
27
+ * @returns {number}
28
+ */
29
+ function budget(world) {
30
+ return Math.max((world && world.minWaitTime && world.minWaitTime.page) || 0, 10000);
31
+ }
32
+
33
+ /**
34
+ * Escape a literal string for use in a RegExp.
35
+ *
36
+ * @param {string} text
37
+ * @returns {string}
38
+ */
39
+ function escapeRegExp(text) {
40
+ return String(text).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
41
+ }
42
+
43
+ /**
44
+ * A RegExp that matches the whole text (ignoring surrounding space and case), for exact names and labels.
45
+ *
46
+ * @param {string} text
47
+ * @returns {RegExp}
48
+ */
49
+ function exactly(text) {
50
+ return new RegExp('^\\s*' + escapeRegExp(text) + '\\s*$', 'i');
51
+ }
52
+
53
+ /**
54
+ * Collapse runs of white space and trim.
55
+ *
56
+ * @param {string} text
57
+ * @returns {string}
58
+ */
59
+ function tidy(text) {
60
+ return String(text === null || text === undefined ? '' : text).replace(/\s+/g, ' ').trim();
61
+ }
62
+
63
+ /**
64
+ * Run an action and rethrow its failure as a friendly error (action, target, cause and a hint) instead of
65
+ * Playwright's raw timeout stack.
66
+ *
67
+ * @param {string} label
68
+ * @param {string} target
69
+ * @param {Function} fn
70
+ * @param {string} hint
71
+ */
72
+ async function actOrExplain(label, target, fn, hint) {
73
+ try {
74
+ return await fn();
75
+ } catch (err) {
76
+ if (err && err.stack === err.message && /Hint:/.test(err.message)) throw err;
77
+ throw friendly({ action: label, target, cause: err, hint });
78
+ }
79
+ }
80
+
81
+ /**
82
+ * Wait until a locator has (or, with `notCase`, no longer has) a visible match and fail with a friendly error
83
+ * otherwise: the wait and the assertion are one call, so content that arrives a moment late still passes.
84
+ *
85
+ * @param {import('playwright').Locator} locator
86
+ * @param {string|null|undefined} notCase
87
+ * @param {{label: string, hint: string, timeout: number}} options
88
+ */
89
+ async function assertPresence(locator, notCase, { label, hint, timeout }) {
90
+ try {
91
+ await locator.first().waitFor({ state: notCase ? 'hidden' : 'visible', timeout });
92
+ } catch {
93
+ throw friendly({
94
+ message: notCase ? `Expected not to see ${label}, but it is still on the page.` : `Expected to see ${label}, but it did not appear within ${timeout} ms.`,
95
+ hint,
96
+ });
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Poll a reader until its value satisfies a test, and return the last value read, so a value that changes a moment
102
+ * after the action (a status after a move) still passes.
103
+ *
104
+ * @param {Function} read - async () => value
105
+ * @param {Function} test - (value) => boolean
106
+ * @param {number} timeout
107
+ * @returns {Promise<{ok: boolean, value: *}>}
108
+ */
109
+ async function waitForValue(read, test, timeout) {
110
+ const deadline = Date.now() + timeout;
111
+ let value;
112
+ for (;;) {
113
+ try { value = await read(); } catch { value = undefined; }
114
+ if (value !== undefined && test(value)) return { ok: true, value };
115
+ if (Date.now() >= deadline) return { ok: false, value };
116
+ await new Promise((resolve) => setTimeout(resolve, 250));
117
+ }
118
+ }
119
+
120
+ /**
121
+ * The site root without a trailing slash.
122
+ *
123
+ * @param {object} world
124
+ * @returns {string}
125
+ */
126
+ function siteRoot(world) {
127
+ return String(world.launchUrl).replace(/\/+$/, '');
128
+ }
129
+
130
+ /**
131
+ * Join the site root and a path with exactly one slash. Absolute URLs pass through.
132
+ *
133
+ * @param {object} world
134
+ * @param {string} url
135
+ * @returns {string}
136
+ */
137
+ function siteUrl(world, url) {
138
+ if (!url) return siteRoot(world);
139
+ if (/^https?:\/\//i.test(url)) return url;
140
+ return siteRoot(world) + '/' + String(url).replace(/^\/+/, '');
141
+ }
142
+
143
+ /**
144
+ * Open a page of the site and wait for it to settle.
145
+ *
146
+ * @param {object} world
147
+ * @param {string} url
148
+ */
149
+ async function open(world, url) {
150
+ await gotoUrl(world.page, siteUrl(world, url));
151
+ await world.page.waitForSelector('body', { state: 'attached', timeout: budget(world) });
152
+ await waitForPageLoad(world.page, (world.minWaitTime && world.minWaitTime.page) || 3000);
153
+ }
154
+
155
+ /**
156
+ * A user of the `users` registry in cucumber.js (`worldParameters.users`).
157
+ *
158
+ * @param {object} world
159
+ * @param {string} handle
160
+ * @returns {{username: string, password: string, name: string}}
161
+ */
162
+ function resolveUser(world, handle) {
163
+ const users = (world.parameters && world.parameters.users) || {};
164
+ const entry = users[handle];
165
+ if (!entry) {
166
+ throw friendly({
167
+ message: `The account "${handle}" is not in the users registry. Known accounts: ${Object.keys(users).join(', ') || '(none)'}.`,
168
+ hint: `Add it to worldParameters.users in cucumber.js: users: { ${handle}: { username: '...', password: process.env.GITEA_${handle.toUpperCase()}_PASSWORD, name: '...' } }. The account itself is made once by the build of the site, never by a feature.`,
169
+ });
170
+ }
171
+ const username = entry.username || handle;
172
+ const password = typeof entry === 'string' ? entry : entry.password;
173
+ if (!password) {
174
+ throw friendly({
175
+ message: `The account "${handle}" has no password in the users registry.`,
176
+ hint: `Set worldParameters.users.${handle}.password in cucumber.js, from an environment variable.`,
177
+ });
178
+ }
179
+ return { username, password, name: entry.name || '' };
180
+ }
181
+
182
+ /**
183
+ * The front page as the browser's session sees it (the session's cookies, never a page change): its status and HTML.
184
+ *
185
+ * @param {object} world
186
+ * @returns {Promise<{status: number, html: string}>}
187
+ */
188
+ async function frontPage(world) {
189
+ const r = await world.context.request.get(siteUrl(world, '/'), { ignoreHTTPSErrors: true, failOnStatusCode: false }).catch(() => null);
190
+ if (!r) return { status: 0, html: '' };
191
+ return { status: r.status(), html: await r.text().catch(() => '') };
192
+ }
193
+
194
+ /**
195
+ * The login of the account the browser's session is of, from the forge's own account menu ("Signed in as <login>");
196
+ * an empty string for a visitor.
197
+ *
198
+ * @param {object} world
199
+ * @returns {Promise<string>}
200
+ */
201
+ async function currentUser(world) {
202
+ const { html } = await frontPage(world);
203
+ const m = html.match(/Signed in as\s*<strong>([^<]+)<\/strong>/);
204
+ return m ? m[1].trim() : '';
205
+ }
206
+
207
+ /**
208
+ * The name the forge shows for the account the browser's session is of: its full name, which the title of its own
209
+ * dashboard carries; an empty string for a visitor.
210
+ *
211
+ * @param {object} world
212
+ * @returns {Promise<string>}
213
+ */
214
+ async function currentName(world) {
215
+ const { html } = await frontPage(world);
216
+ if (!/Signed in as\s*<strong>/.test(html)) return '';
217
+ const m = html.match(/<title>\s*([^<]*?) - Dashboard - /);
218
+ return m ? tidy(m[1]) : '';
219
+ }
220
+
221
+ /**
222
+ * Forget the browser's session: the page is emptied first, so no request of the site brings a new session back.
223
+ *
224
+ * @param {object} world
225
+ */
226
+ async function dropSession(world) {
227
+ if (world.page.url() !== 'about:blank') await world.page.goto('about:blank').catch(() => {});
228
+ await world.context.clearCookies();
229
+ }
230
+
231
+ /**
232
+ * Fill and submit the login form with a login and a password. It asserts nothing.
233
+ *
234
+ * @param {object} world
235
+ * @param {string} username
236
+ * @param {string} password
237
+ */
238
+ async function submitLogin(world, username, password) {
239
+ const page = world.page;
240
+ await open(world, '/user/login');
241
+ await actOrExplain('fill in the login form for', username, async () => {
242
+ const form = page.locator('form:has(#user_name):has(#password)').last();
243
+ await form.locator('#user_name').waitFor({ state: 'visible', timeout: budget(world) });
244
+ await form.locator('#user_name').fill(username);
245
+ await form.locator('#password').fill(password);
246
+ await form.getByRole('button', { name: /^\s*sign in\s*$/i }).first().click();
247
+ }, 'The login form (#user_name, #password and its Sign In button) did not show at /user/login. A forge that signs in through another provider only has no such form, and a session that is already open is sent to its dashboard instead.');
248
+ await smartSettle(page, 2000);
249
+ }
250
+
251
+ const sessions = new Map();
252
+
253
+ /**
254
+ * Sign in with an account of the users registry and make sure the session is that account's. An account that is
255
+ * already signed in is kept; an account that signed in earlier in the run gets its session back; otherwise the account
256
+ * goes through the login form.
257
+ *
258
+ * @param {object} world
259
+ * @param {string} handle
260
+ */
261
+ async function signInAs(world, handle) {
262
+ const user = resolveUser(world, handle);
263
+ const key = siteRoot(world) + '|' + handle;
264
+ if ((await currentUser(world)) === user.username) {
265
+ if (world.page.url() === 'about:blank' || !world.page.url().startsWith(siteRoot(world))) await open(world, '/');
266
+ return;
267
+ }
268
+ await dropSession(world);
269
+ const saved = sessions.get(key);
270
+ if (saved) {
271
+ await world.context.addCookies(saved);
272
+ if ((await currentUser(world)) === user.username) {
273
+ await open(world, '/');
274
+ return;
275
+ }
276
+ sessions.delete(key);
277
+ await dropSession(world);
278
+ }
279
+ await submitLogin(world, user.username, user.password);
280
+ const result = await waitForValue(() => currentUser(world), (login) => login === user.username, budget(world));
281
+ if (!result.ok) {
282
+ const error = tidy(await world.page.locator('.flash-error').first().innerText({ timeout: 1500 }).catch(() => ''));
283
+ throw friendly({
284
+ message: `Logging in as "${handle}" (login "${user.username}") did not work${error ? `: the site says "${error}"` : `; the page is ${world.page.url()}`}.`,
285
+ hint: 'Check the login and the password of this account in worldParameters.users of cucumber.js, and that the account exists on the site and may log in.',
286
+ });
287
+ }
288
+ sessions.set(key, await world.context.cookies());
289
+ }
290
+
291
+ // ---------------------------------------------------------------------------
292
+ // The forge's REST API, as the managing account
293
+ // ---------------------------------------------------------------------------
294
+
295
+ const managers = new Map();
296
+
297
+ /** The managing accounts' request contexts of a run, all of them, and their end. */
298
+ const managerContexts = {
299
+ async dispose() {
300
+ for (const ctx of managers.values()) await ctx.dispose().catch(() => {});
301
+ managers.clear();
302
+ },
303
+ };
304
+
305
+ /**
306
+ * A request context of its own for the managing account (`worldParameters.manager`, a handle of the users registry),
307
+ * for the test content a scenario makes and removes: the REST API with the account's login and password (HTTP Basic,
308
+ * which the forge takes for an account without a second factor). It never touches the browser's session.
309
+ *
310
+ * @param {object} world
311
+ * @returns {Promise<import('playwright').APIRequestContext>}
312
+ */
313
+ async function managerContext(world) {
314
+ const handle = (world.parameters && world.parameters.manager) || 'owner';
315
+ const key = siteRoot(world) + '|' + handle;
316
+ if (managers.has(key)) return managers.get(key);
317
+ const user = resolveUser(world, handle);
318
+ const ctx = await playwright.request.newContext({
319
+ baseURL: siteRoot(world), ignoreHTTPSErrors: true,
320
+ extraHTTPHeaders: { Authorization: 'Basic ' + Buffer.from(`${user.username}:${user.password}`).toString('base64'), Accept: 'application/json' },
321
+ });
322
+ const me = await ctx.get('/api/v1/user', { failOnStatusCode: false });
323
+ const login = me.status() === 200 ? String((await me.json()).login || '') : '';
324
+ if (login !== user.username) {
325
+ await ctx.dispose();
326
+ throw friendly({
327
+ message: `The managing account "${handle}" could not use the REST API of ${siteRoot(world)} for the test content (it answered ${me.status()}).`,
328
+ hint: 'Check worldParameters.manager and the account in worldParameters.users of cucumber.js; an account with a second factor cannot use its password for the API.',
329
+ });
330
+ }
331
+ managers.set(key, ctx);
332
+ return ctx;
333
+ }
334
+
335
+ /**
336
+ * One call of the REST API as the managing account: its status and its JSON.
337
+ *
338
+ * @param {object} world
339
+ * @param {string} method
340
+ * @param {string} path - a path under /api/v1
341
+ * @param {object} [data]
342
+ * @returns {Promise<{status: number, data: *}>}
343
+ */
344
+ async function api(world, method, path, data) {
345
+ const ctx = await managerContext(world);
346
+ const r = await ctx.fetch('/api/v1' + path, {
347
+ method,
348
+ headers: data === undefined ? {} : { 'Content-Type': 'application/json' },
349
+ data: data === undefined ? undefined : JSON.stringify(data),
350
+ failOnStatusCode: false,
351
+ });
352
+ let body = null;
353
+ try { body = await r.json(); } catch { body = null; }
354
+ return { status: r.status(), data: body };
355
+ }
356
+
357
+ /**
358
+ * An answer of the API that is not a success, as a friendly error.
359
+ *
360
+ * @param {string} what
361
+ * @param {{status: number, data: *}} r
362
+ * @param {string} hint
363
+ */
364
+ function apiFailure(what, r, hint) {
365
+ const said = r.data && r.data.message ? ` (${r.data.message})` : '';
366
+ return friendly({ message: `Could not ${what}: the site answered ${r.status}${said}.`, hint });
367
+ }
368
+
369
+ /**
370
+ * A repository by owner/name, as the managing account sees it: { owner, name, path }. The step's repository, else the
371
+ * one of cucumber.js.
372
+ *
373
+ * @param {object} world
374
+ * @param {string} [which]
375
+ */
376
+ async function findRepository(world, which) {
377
+ const wanted = String(which || (world.parameters && world.parameters.repository) || '').trim().replace(/\.git$/, '');
378
+ if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(wanted)) {
379
+ throw friendly({ message: `"${wanted}" is not a repository: name it owner/name.`, hint: 'The sample repository is owner/webship-site; worldParameters.repository of cucumber.js is the one steps use when they name none.' });
380
+ }
381
+ const r = await api(world, 'GET', `/repos/${wanted}`);
382
+ if (r.status !== 200) throw apiFailure(`find the repository ${wanted}`, r, 'The managing account must be its owner or have access to it.');
383
+ return { owner: r.data.owner.login, name: r.data.name, path: r.data.full_name };
384
+ }
385
+
386
+ /**
387
+ * The issues of a repository whose title is the text, open or closed (pull requests left out). The list is read page
388
+ * by page, not searched: the forge's search reads an index that takes a moment to learn a new issue.
389
+ *
390
+ * @param {object} world
391
+ * @param {{path: string}} repo
392
+ * @param {string} title
393
+ * @returns {Promise<object[]>}
394
+ */
395
+ async function findIssues(world, repo, title) {
396
+ const found = [];
397
+ for (let page = 1; page <= 20; page += 1) {
398
+ const q = new URLSearchParams({ state: 'all', type: 'issues', limit: '50', page: String(page) });
399
+ const r = await api(world, 'GET', `/repos/${repo.path}/issues?${q.toString()}`);
400
+ if (r.status !== 200) throw apiFailure(`look for the issue "${title}"`, r, 'The managing account must see the repository\'s issues.');
401
+ const items = r.data || [];
402
+ found.push(...items.filter((i) => !i.pull_request && exactly(title).test(i.title)));
403
+ if (items.length < 50) break;
404
+ }
405
+ return found;
406
+ }
407
+
408
+ /**
409
+ * The one issue of a title in a repository (the step's, else the last one a scenario used).
410
+ *
411
+ * @param {object} world
412
+ * @param {string} title
413
+ * @param {string} [repoName]
414
+ * @returns {Promise<object>}
415
+ */
416
+ async function issueNamed(world, title, repoName) {
417
+ const repo = await findRepository(world, repoName || (world.gitea && world.gitea.repository));
418
+ const found = await findIssues(world, repo, title);
419
+ if (!found.length) throw friendly({ message: `There is no issue "${title}" in ${repo.path}.`, hint: 'Make it first with Given there is an issue "…" in the repository "…".' });
420
+ return Object.assign(found[0], { repository: repo.path });
421
+ }
422
+
423
+ /**
424
+ * Remember an issue a scenario made, so it goes after the scenario.
425
+ *
426
+ * @param {object} world
427
+ * @param {string} repoPath
428
+ * @param {number|string} number
429
+ */
430
+ function remember(world, repoPath, number) {
431
+ world.gitea = world.gitea || {};
432
+ world.gitea.made = world.gitea.made || new Set();
433
+ world.gitea.made.add(`${repoPath}#${number}`);
434
+ }
435
+
436
+ /**
437
+ * Remove an issue, as the managing account: the forge removes its comments and the time spent on it with it.
438
+ *
439
+ * @param {object} world
440
+ * @param {string} repoPath
441
+ * @param {number|string} number
442
+ */
443
+ async function removeIssue(world, repoPath, number) {
444
+ const r = await api(world, 'DELETE', `/repos/${repoPath}/issues/${number}`);
445
+ if (r.status !== 204 && r.status !== 200 && r.status !== 404) throw apiFailure(`remove the issue ${repoPath}#${number}`, r, 'The managing account must be allowed to delete the repository\'s issues (its owner or an administrator of it).');
446
+ }
447
+
448
+ /**
449
+ * Make an issue as the managing account, with a milestone when one is named.
450
+ *
451
+ * @param {object} world
452
+ * @param {{path: string}} repo
453
+ * @param {string} title
454
+ * @param {{milestone?: string}} [extra]
455
+ * @returns {Promise<object>}
456
+ */
457
+ async function makeIssue(world, repo, title, extra = {}) {
458
+ const body = { title, body: 'Made by a test scenario; it goes after the scenario.' };
459
+ if (extra.milestone) {
460
+ const m = await api(world, 'GET', `/repos/${repo.path}/milestones?state=all&name=${encodeURIComponent(extra.milestone)}`);
461
+ const found = ((m.data || [])).find((x) => exactly(extra.milestone).test(x.title));
462
+ if (!found) throw friendly({ message: `There is no milestone "${extra.milestone}" in ${repo.path}.`, hint: 'The sample content has the milestone Sprint 1.' });
463
+ body.milestone = found.id;
464
+ }
465
+ const r = await api(world, 'POST', `/repos/${repo.path}/issues`, body);
466
+ if (r.status !== 201) throw apiFailure(`make the issue "${title}"`, r, 'The managing account must be allowed to open issues in the repository.');
467
+ remember(world, repo.path, r.data.number);
468
+ return r.data;
469
+ }
470
+
471
+ module.exports = {
472
+ budget,
473
+ escapeRegExp,
474
+ exactly,
475
+ tidy,
476
+ actOrExplain,
477
+ assertPresence,
478
+ waitForValue,
479
+ siteRoot,
480
+ siteUrl,
481
+ open,
482
+ resolveUser,
483
+ frontPage,
484
+ currentUser,
485
+ currentName,
486
+ dropSession,
487
+ submitLogin,
488
+ signInAs,
489
+ managerContext,
490
+ managerContexts,
491
+ api,
492
+ apiFailure,
493
+ findRepository,
494
+ findIssues,
495
+ issueNamed,
496
+ remember,
497
+ removeIssue,
498
+ makeIssue,
499
+ };