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