@webship-js/codeigniter-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.
- package/LICENSE +21 -0
- package/README.md +448 -2
- package/package.json +62 -4
- package/tests/features/README.md +24 -0
- package/tests/features/access.feature +52 -0
- package/tests/features/accessibility.feature +32 -0
- package/tests/features/development.feature +59 -0
- package/tests/features/forgery.feature +36 -0
- package/tests/features/framework-pages.feature +42 -0
- package/tests/features/login-link.feature +43 -0
- package/tests/features/registration.feature +65 -0
- package/tests/features/session.feature +104 -0
- package/tests/step-definitions/README.md +37 -0
- package/tests/step-definitions/codeigniter-access.steps.js +122 -0
- package/tests/step-definitions/codeigniter-forms.steps.js +217 -0
- package/tests/step-definitions/codeigniter-helpers.js +702 -0
- package/tests/step-definitions/codeigniter-mail.steps.js +117 -0
- package/tests/step-definitions/codeigniter-pages.steps.js +209 -0
- package/tests/step-definitions/codeigniter-session.steps.js +277 -0
- package/tests/step-definitions/codeigniter-toolbar.steps.js +154 -0
|
@@ -0,0 +1,702 @@
|
|
|
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
|
|
6
|
+
// plumbing the steps use and that a project can require for its own steps:
|
|
7
|
+
// the wait budget and the settle on the page's own requests, the paths of the
|
|
8
|
+
// app, the users registry and the session cache, fields found by their label,
|
|
9
|
+
// the messages of a page (the error, success, warning and information lines a
|
|
10
|
+
// form or a redirect leaves), the answers the browser received on its way to
|
|
11
|
+
// a page, the mailbox of the test app, and the status of the page.
|
|
12
|
+
//
|
|
13
|
+
// The app is a server-rendered app: every action is a form sent or a link
|
|
14
|
+
// followed, and the answer is a new page (often after a redirect). Every
|
|
15
|
+
// lookup starts with what a person reads (a label, a role, a text) and falls
|
|
16
|
+
// back to the stable hooks of the pages (`role="alert"`, the contextual
|
|
17
|
+
// classes of a message, the name of a field).
|
|
18
|
+
//
|
|
19
|
+
// Everything builds on webship-js's own helpers (`gotoUrl`, `friendly`,
|
|
20
|
+
// `fillField`) so the steps fail the way the core webship-js steps do.
|
|
21
|
+
|
|
22
|
+
const { gotoUrl, friendly, fillField } = require('webship-js/tests/step-definitions/webship');
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The per-assertion wait budget: `minWaitTime.page` from cucumber.js, at least
|
|
26
|
+
* 10 seconds. Kept below webship-js's 45 second step timeout.
|
|
27
|
+
*
|
|
28
|
+
* @param {object} world
|
|
29
|
+
* @returns {number}
|
|
30
|
+
*/
|
|
31
|
+
function budget(world) {
|
|
32
|
+
return Math.max((world && world.minWaitTime && world.minWaitTime.page) || 0, 10000);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The settle budget after an action (`minWaitTime.page`, 3 seconds by default). */
|
|
36
|
+
function settleBudget(world) {
|
|
37
|
+
return (world && world.minWaitTime && world.minWaitTime.page) || 3000;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Escape a literal string for use in a RegExp. */
|
|
41
|
+
function escapeRegExp(text) {
|
|
42
|
+
return String(text).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** White space collapsed and trimmed. */
|
|
46
|
+
function clean(text) {
|
|
47
|
+
return String(text === null || text === undefined ? '' : text).replace(/\s+/g, ' ').trim();
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** A list for an error message: `"a", "b", "c"` or `(none)`. */
|
|
51
|
+
function listed(values) {
|
|
52
|
+
const items = [...new Set((values || []).map(clean).filter(Boolean))];
|
|
53
|
+
return items.length ? items.map((item) => `"${item}"`).join(', ') : '(none)';
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The site root without a trailing slash. */
|
|
57
|
+
function siteRoot(world) {
|
|
58
|
+
return String(world.launchUrl || (world.parameters && world.parameters.launchUrl) || '').replace(/\/+$/, '');
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Join the site root and a path with exactly one slash. Absolute URLs pass through. */
|
|
62
|
+
function siteUrl(world, url) {
|
|
63
|
+
if (!url) return siteRoot(world) + '/';
|
|
64
|
+
if (/^https?:\/\//i.test(url)) return url;
|
|
65
|
+
return siteRoot(world) + '/' + String(url).replace(/^\/+/, '');
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** A path of the app read from cucumber.js (`worldParameters.<key>`), or its default. */
|
|
69
|
+
function appPath(world, key, fallback) {
|
|
70
|
+
const value = world.parameters && world.parameters[key];
|
|
71
|
+
return '/' + String(value || fallback).replace(/^\/+/, '');
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The login page (`loginPath`, /login). */
|
|
75
|
+
function loginPath(world) {
|
|
76
|
+
return appPath(world, 'loginPath', '/login');
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The address that ends a session (`logoutPath`, /logout): a link a page offers, or the address itself. */
|
|
80
|
+
function logoutPath(world) {
|
|
81
|
+
return appPath(world, 'logoutPath', '/logout');
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The page that sends a login link by mail (`loginLinkPath`, /login/magic-link). */
|
|
85
|
+
function loginLinkPath(world) {
|
|
86
|
+
return appPath(world, 'loginLinkPath', '/login/magic-link');
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** A page that names the signed-in account (`accountPath`, /account on the test app). */
|
|
90
|
+
function accountPath(world) {
|
|
91
|
+
return appPath(world, 'accountPath', '/account');
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The path of the page the browser shows, without the query and the fragment. */
|
|
95
|
+
function currentPath(world) {
|
|
96
|
+
try {
|
|
97
|
+
return new URL(world.page.url()).pathname.replace(/\/+$/, '') || '/';
|
|
98
|
+
} catch {
|
|
99
|
+
return '';
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The path of an address, without the query, the fragment and a trailing slash. */
|
|
104
|
+
function pathOf(url) {
|
|
105
|
+
try {
|
|
106
|
+
return new URL(url, 'https://x.invalid').pathname.replace(/\/+$/, '') || '/';
|
|
107
|
+
} catch {
|
|
108
|
+
return String(url || '');
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Whether the browser shows the page of a path (trailing slashes ignored). */
|
|
113
|
+
function isOnPath(world, path) {
|
|
114
|
+
return currentPath(world) === (String(path).replace(/\/+$/, '') || '/');
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// ---------------------------------------------------------------------------
|
|
118
|
+
// Waiting on the page's own requests
|
|
119
|
+
// ---------------------------------------------------------------------------
|
|
120
|
+
|
|
121
|
+
const TRACKED = new WeakMap();
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* The background requests (XHR and fetch) of the page that are still running,
|
|
125
|
+
* how many started so far, and the answers to the documents the main frame
|
|
126
|
+
* loaded (each hop of a redirect included), newest last. The tracker is
|
|
127
|
+
* attached once per page.
|
|
128
|
+
*
|
|
129
|
+
* @returns {{pending: Set, started: number, documents: Array<{url: string, status: number, location: string, at: number}>}}
|
|
130
|
+
*/
|
|
131
|
+
function requests(world) {
|
|
132
|
+
const page = world.page;
|
|
133
|
+
let state = TRACKED.get(page);
|
|
134
|
+
if (!state) {
|
|
135
|
+
state = { pending: new Set(), started: 0, documents: [] };
|
|
136
|
+
TRACKED.set(page, state);
|
|
137
|
+
const background = (request) => ['xhr', 'fetch'].includes(request.resourceType());
|
|
138
|
+
page.on('request', (request) => {
|
|
139
|
+
if (!background(request)) return;
|
|
140
|
+
state.pending.add(request);
|
|
141
|
+
state.started += 1;
|
|
142
|
+
});
|
|
143
|
+
page.on('response', (response) => {
|
|
144
|
+
try {
|
|
145
|
+
const request = response.request();
|
|
146
|
+
if (!request.isNavigationRequest() || response.frame() !== page.mainFrame()) return;
|
|
147
|
+
const headers = response.headers();
|
|
148
|
+
state.documents.push({ url: response.url(), status: response.status(), location: headers.location || '', at: Date.now() });
|
|
149
|
+
if (state.documents.length > 50) state.documents.shift();
|
|
150
|
+
} catch (e) { /* a response of a frame that is gone */ }
|
|
151
|
+
});
|
|
152
|
+
const done = (request) => { state.pending.delete(request); };
|
|
153
|
+
page.on('requestfinished', done);
|
|
154
|
+
page.on('requestfailed', done);
|
|
155
|
+
// A navigation drops the requests of the page it leaves.
|
|
156
|
+
page.on('framenavigated', (frame) => { if (frame === page.mainFrame()) state.pending.clear(); });
|
|
157
|
+
}
|
|
158
|
+
return state;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Wait for the page to go quiet after an action: the document is loaded and no
|
|
163
|
+
* background request has been running for a moment. Returns as soon as that is
|
|
164
|
+
* true, and at the latest after `timeout` (the settle budget by default).
|
|
165
|
+
*/
|
|
166
|
+
async function settle(world, timeout) {
|
|
167
|
+
const state = requests(world);
|
|
168
|
+
const deadline = Date.now() + (timeout || settleBudget(world));
|
|
169
|
+
await world.page.waitForLoadState('domcontentloaded', { timeout: Math.max(deadline - Date.now(), 1) }).catch(() => {});
|
|
170
|
+
let quietSince = 0;
|
|
171
|
+
while (Date.now() < deadline) {
|
|
172
|
+
if (state.pending.size === 0) {
|
|
173
|
+
if (!quietSince) quietSince = Date.now();
|
|
174
|
+
if (Date.now() - quietSince >= 200) return;
|
|
175
|
+
} else {
|
|
176
|
+
quietSince = 0;
|
|
177
|
+
}
|
|
178
|
+
await world.page.waitForTimeout(40);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Run an action that sends a form or follows a link, and wait for the answer:
|
|
184
|
+
* the browser leaves the page it was on and the new page is loaded. Returns
|
|
185
|
+
* the answers the main frame received since the action, in order (a redirect
|
|
186
|
+
* is an answer of its own).
|
|
187
|
+
*/
|
|
188
|
+
async function afterNavigation(world, fn) {
|
|
189
|
+
const state = requests(world);
|
|
190
|
+
const before = state.documents.length;
|
|
191
|
+
const from = world.page.url();
|
|
192
|
+
await Promise.all([
|
|
193
|
+
world.page.waitForNavigation({ timeout: budget(world), waitUntil: 'load' }).catch(() => {}),
|
|
194
|
+
fn(),
|
|
195
|
+
]);
|
|
196
|
+
await world.page.waitForLoadState('load', { timeout: budget(world) }).catch(() => {});
|
|
197
|
+
await settle(world);
|
|
198
|
+
return { from, answers: state.documents.slice(before) };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Open a URL and wait for the page to settle. Returns the answers the main
|
|
203
|
+
* frame received on the way (a redirect is an answer of its own).
|
|
204
|
+
*/
|
|
205
|
+
async function open(world, url) {
|
|
206
|
+
const state = requests(world);
|
|
207
|
+
const before = state.documents.length;
|
|
208
|
+
try {
|
|
209
|
+
await gotoUrl(world.page, url);
|
|
210
|
+
} catch (err) {
|
|
211
|
+
// A network interface that comes or goes on the machine (a container starting next door) aborts the
|
|
212
|
+
// navigation once, with ERR_NETWORK_CHANGED or the browser's own error page: go again.
|
|
213
|
+
if (!/ERR_NETWORK_CHANGED|chrome-error:\/\/chromewebdata/.test(String(err && err.message))) throw err;
|
|
214
|
+
await world.page.waitForTimeout(500);
|
|
215
|
+
await gotoUrl(world.page, url);
|
|
216
|
+
}
|
|
217
|
+
await world.page.waitForSelector('body', { state: 'attached', timeout: budget(world) });
|
|
218
|
+
await world.page.waitForLoadState('load', { timeout: budget(world) }).catch(() => {});
|
|
219
|
+
await settle(world);
|
|
220
|
+
return state.documents.slice(before);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Wait until a locator has (or, with `notCase`, no longer has) a visible match
|
|
225
|
+
* and fail with a friendly error otherwise: the wait and the assertion are one
|
|
226
|
+
* call, so content that arrives a moment late still passes.
|
|
227
|
+
*/
|
|
228
|
+
async function assertPresence(locator, notCase, { label, hint, timeout, found }) {
|
|
229
|
+
try {
|
|
230
|
+
await locator.first().waitFor({ state: notCase ? 'hidden' : 'visible', timeout });
|
|
231
|
+
} catch {
|
|
232
|
+
const seen = found ? await found().catch(() => '') : '';
|
|
233
|
+
throw friendly({
|
|
234
|
+
message: (notCase ? `Expected not to see ${label}, but it is on the page.` : `Expected to see ${label}, but it did not appear within ${timeout} ms.`) + (seen ? ` ${seen}` : ''),
|
|
235
|
+
hint,
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Poll a reading until it satisfies a check, or fail with the last reading.
|
|
242
|
+
*
|
|
243
|
+
* @param {object} world
|
|
244
|
+
* @param {Function} read - async () => value
|
|
245
|
+
* @param {Function} check - (value) => boolean
|
|
246
|
+
* @param {Function} explain - (value) => {message, hint}
|
|
247
|
+
*/
|
|
248
|
+
async function eventually(world, read, check, explain, timeout) {
|
|
249
|
+
const deadline = Date.now() + (timeout || budget(world));
|
|
250
|
+
let value;
|
|
251
|
+
for (;;) {
|
|
252
|
+
value = await read();
|
|
253
|
+
if (check(value)) return value;
|
|
254
|
+
if (Date.now() > deadline) throw friendly(explain(value));
|
|
255
|
+
await world.page.waitForTimeout(200);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// ---------------------------------------------------------------------------
|
|
260
|
+
// Accounts
|
|
261
|
+
// ---------------------------------------------------------------------------
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* An account of the users registry in cucumber.js (`worldParameters.users`),
|
|
265
|
+
* by the handle a scenario names it with.
|
|
266
|
+
*
|
|
267
|
+
* @returns {{handle: string, email: string, username: (string|undefined), password: string}}
|
|
268
|
+
*/
|
|
269
|
+
function resolveUser(world, handle) {
|
|
270
|
+
const users = (world.parameters && world.parameters.users) || {};
|
|
271
|
+
const entry = users[handle];
|
|
272
|
+
if (!entry) {
|
|
273
|
+
throw friendly({
|
|
274
|
+
message: `The user "${handle}" is not in the users registry. Known users: ${Object.keys(users).join(', ') || '(none)'}.`,
|
|
275
|
+
hint: `Add it to worldParameters.users in cucumber.js: users: { ${handle}: { email: '${handle}@example.com', username: '${handle}', password: process.env.${String(handle).toUpperCase()}_PASSWORD } }. The account itself is created once by the build of the app, never by a feature.`,
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
if (!entry.email || !entry.password) {
|
|
279
|
+
throw friendly({
|
|
280
|
+
message: `The user "${handle}" has no ${entry.email ? 'password' : 'email address'} in the users registry.`,
|
|
281
|
+
hint: `Set worldParameters.users.${handle}.email and .password in cucumber.js, from environment variables.`,
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
return { handle, email: entry.email, username: entry.username, password: entry.password };
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** A handle of the users registry stands for its address; anything else is an address. */
|
|
288
|
+
function addressOf(world, who) {
|
|
289
|
+
const users = (world.parameters && world.parameters.users) || {};
|
|
290
|
+
return users[who] ? resolveUser(world, who).email : who;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// The sessions of the accounts that logged in during this run, by site and
|
|
294
|
+
// address: the cookies of the browser after a login through the form. A
|
|
295
|
+
// scenario that logs in as an account that already has a session takes it
|
|
296
|
+
// over instead of filling in the login form again, which is quicker.
|
|
297
|
+
// `worldParameters.reuseSessions: false` in cucumber.js turns it off.
|
|
298
|
+
const SESSIONS = new Map();
|
|
299
|
+
|
|
300
|
+
function sessionKey(world, email) {
|
|
301
|
+
return `${siteRoot(world)}|${String(email).toLowerCase()}`;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function reuseSessions(world) {
|
|
305
|
+
return !(world.parameters && world.parameters.reuseSessions === false);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// ---------------------------------------------------------------------------
|
|
309
|
+
// Fields
|
|
310
|
+
// ---------------------------------------------------------------------------
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* The visible form control a person means by `name`: its label exactly as
|
|
314
|
+
* written, then its `name` attribute, then the one label that starts with the
|
|
315
|
+
* text (letter case ignored), then its placeholder.
|
|
316
|
+
*
|
|
317
|
+
* @returns {Promise<import('playwright').Locator>} one element
|
|
318
|
+
*/
|
|
319
|
+
async function findField(world, name, { timeout } = {}) {
|
|
320
|
+
const page = world.page;
|
|
321
|
+
const deadline = Date.now() + (timeout || budget(world));
|
|
322
|
+
const candidates = () => [
|
|
323
|
+
page.getByLabel(name, { exact: true }),
|
|
324
|
+
page.locator(`[name="${String(name).replace(/["\\]/g, '\\$&')}"]`),
|
|
325
|
+
page.getByLabel(new RegExp('^\\s*' + escapeRegExp(name), 'i')),
|
|
326
|
+
page.getByPlaceholder(name, { exact: true }),
|
|
327
|
+
];
|
|
328
|
+
for (;;) {
|
|
329
|
+
for (const locator of candidates()) {
|
|
330
|
+
const count = await locator.count().catch(() => 0);
|
|
331
|
+
for (let i = 0; i < count; i += 1) {
|
|
332
|
+
const item = locator.nth(i);
|
|
333
|
+
if (await item.isVisible().catch(() => false)) return item;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
if (Date.now() > deadline) break;
|
|
337
|
+
await page.waitForTimeout(150);
|
|
338
|
+
}
|
|
339
|
+
const labels = await visibleFieldLabels(world);
|
|
340
|
+
throw friendly({
|
|
341
|
+
message: `No field "${name}" is on the page (${world.page.url()}). The fields are: ${listed(labels)}.`,
|
|
342
|
+
hint: 'Name the field by its label as the page writes it ("Email Address"), or by its name attribute ("email").',
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** The labels of the visible form controls of the page, for an error message. */
|
|
347
|
+
async function visibleFieldLabels(world) {
|
|
348
|
+
return world.page.evaluate(() => {
|
|
349
|
+
const out = [];
|
|
350
|
+
for (const el of document.querySelectorAll('input:not([type=hidden]), select, textarea')) {
|
|
351
|
+
const box = el.getBoundingClientRect();
|
|
352
|
+
if (!box.width && !box.height) continue;
|
|
353
|
+
const text = (el.labels && el.labels[0] && el.labels[0].textContent) || el.getAttribute('aria-label') || el.getAttribute('name') || '';
|
|
354
|
+
out.push(text.replace(/\s+/g, ' ').trim());
|
|
355
|
+
}
|
|
356
|
+
return out;
|
|
357
|
+
}).catch(() => []);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** Fill a field the way webship-js's "I fill in" does: by its exact label, placeholder or name. */
|
|
361
|
+
async function fillLikeABuiltIn(world, name, value) {
|
|
362
|
+
await fillField(world.page, name, value, world);
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// ---------------------------------------------------------------------------
|
|
366
|
+
// Messages
|
|
367
|
+
// ---------------------------------------------------------------------------
|
|
368
|
+
|
|
369
|
+
// The kinds of message a page shows, and how each is marked: the contextual
|
|
370
|
+
// classes of the message box (the auth pages use `alert-danger`,
|
|
371
|
+
// `alert-success`, …), else words in its classes.
|
|
372
|
+
const MESSAGE_KINDS = {
|
|
373
|
+
error: /\b(alert-danger|alert-error|text-bg-danger|is-danger|is-error|error|errors|danger)\b/i,
|
|
374
|
+
success: /\b(alert-success|text-bg-success|is-success|success)\b/i,
|
|
375
|
+
warning: /\b(alert-warning|text-bg-warning|is-warning|warning)\b/i,
|
|
376
|
+
info: /\b(alert-info|alert-primary|text-bg-info|is-info|info|notice)\b/i,
|
|
377
|
+
};
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* The messages the page shows, by kind: the visible message boxes
|
|
381
|
+
* (`role="alert"`, `role="status"`, `.alert`), each split into its lines (a box
|
|
382
|
+
* that lists several errors prints one per line). A box with no kind of its
|
|
383
|
+
* own counts as an error when its role is "alert", as information otherwise.
|
|
384
|
+
*
|
|
385
|
+
* @returns {Promise<Array<{kind: string, text: string}>>}
|
|
386
|
+
*/
|
|
387
|
+
async function pageMessages(world) {
|
|
388
|
+
const kinds = Object.fromEntries(Object.entries(MESSAGE_KINDS).map(([kind, re]) => [kind, re.source]));
|
|
389
|
+
return world.page.evaluate((patterns) => {
|
|
390
|
+
const out = [];
|
|
391
|
+
const boxes = [...document.querySelectorAll('[role="alert"], [role="status"], .alert')];
|
|
392
|
+
for (const box of boxes) {
|
|
393
|
+
if (boxes.some((other) => other !== box && other.contains(box))) continue;
|
|
394
|
+
const style = getComputedStyle(box);
|
|
395
|
+
const rect = box.getBoundingClientRect();
|
|
396
|
+
if (style.display === 'none' || style.visibility === 'hidden' || (!rect.width && !rect.height)) continue;
|
|
397
|
+
const classes = `${box.className || ''} ${box.parentElement ? box.parentElement.className || '' : ''}`;
|
|
398
|
+
let kind = Object.keys(patterns).find((k) => new RegExp(patterns[k], 'i').test(classes));
|
|
399
|
+
if (!kind) kind = box.getAttribute('role') === 'alert' ? 'error' : 'info';
|
|
400
|
+
for (const line of (box.innerText || '').split('\n')) {
|
|
401
|
+
const text = line.replace(/\s+/g, ' ').trim();
|
|
402
|
+
if (text && !/^[×✕x]$/.test(text)) out.push({ kind, text });
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
return out;
|
|
406
|
+
}, kinds).catch(() => []);
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// ---------------------------------------------------------------------------
|
|
410
|
+
// The mailbox of the test app
|
|
411
|
+
// ---------------------------------------------------------------------------
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* The address of the mailbox that catches the mail of the app
|
|
415
|
+
* (`worldParameters.mailUrl` in cucumber.js): a Mailpit, which every DDEV
|
|
416
|
+
* project has at port 8026.
|
|
417
|
+
*/
|
|
418
|
+
function mailUrl(world) {
|
|
419
|
+
const url = world.parameters && world.parameters.mailUrl;
|
|
420
|
+
if (!url) {
|
|
421
|
+
throw friendly({ message: 'No mailbox is configured.', hint: 'Set worldParameters.mailUrl in cucumber.js to the Mailpit of the app, for example https://your-app.ddev.site:8026.' });
|
|
422
|
+
}
|
|
423
|
+
return String(url).replace(/\/+$/, '');
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/** The messages of the mailbox to an address, newest first, as Mailpit lists them. */
|
|
427
|
+
async function mailList(world, address) {
|
|
428
|
+
const request = world.page.context().request;
|
|
429
|
+
const response = await request.get(`${mailUrl(world)}/api/v1/search?query=${encodeURIComponent('to:' + address)}`, { failOnStatusCode: false, ignoreHTTPSErrors: true });
|
|
430
|
+
if (!response.ok()) throw new Error(`the mailbox answered HTTP ${response.status()}`);
|
|
431
|
+
return (await response.json()).messages || [];
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* The newest e-mail to an address that arrived after a moment in time, once it
|
|
436
|
+
* is there (and, when `subject` is given, with that subject).
|
|
437
|
+
*
|
|
438
|
+
* @returns {Promise<{id: string, subject: string, text: string, html: string}>}
|
|
439
|
+
*/
|
|
440
|
+
async function mailTo(world, address, { since = 0, subject = null, timeout } = {}) {
|
|
441
|
+
const request = world.page.context().request;
|
|
442
|
+
const base = mailUrl(world);
|
|
443
|
+
const deadline = Date.now() + (timeout || budget(world) * 2);
|
|
444
|
+
let found = null;
|
|
445
|
+
let problem = '';
|
|
446
|
+
let subjects = [];
|
|
447
|
+
for (;;) {
|
|
448
|
+
try {
|
|
449
|
+
const messages = (await mailList(world, address)).filter((message) => !since || Date.parse(message.Created) >= since - 2000);
|
|
450
|
+
subjects = messages.map((message) => message.Subject);
|
|
451
|
+
found = messages.find((message) => !subject || clean(message.Subject) === clean(subject)) || null;
|
|
452
|
+
problem = messages.length ? `it has ${messages.length} for that address since the step that asked for it, none with the subject "${subject}"` : 'it has none for that address since the step that asked for it';
|
|
453
|
+
if (found) break;
|
|
454
|
+
} catch (err) {
|
|
455
|
+
problem = clean(err && err.message).split(' Call log')[0];
|
|
456
|
+
}
|
|
457
|
+
if (Date.now() > deadline) break;
|
|
458
|
+
await world.page.waitForTimeout(300);
|
|
459
|
+
}
|
|
460
|
+
if (!found) {
|
|
461
|
+
throw friendly({
|
|
462
|
+
message: `No e-mail${subject ? ` "${subject}"` : ''} to ${address} arrived in the mailbox at ${base} (${problem}).${subjects.length ? ` Subjects: ${listed(subjects)}.` : ''}`,
|
|
463
|
+
hint: 'The app must send its mail to this mailbox (the mail catcher of the container: the sendmail of the web container, or SMTP on port 1025), and the address must be the one of the account. Check worldParameters.mailUrl in cucumber.js.',
|
|
464
|
+
});
|
|
465
|
+
}
|
|
466
|
+
const message = await (await request.get(`${base}/api/v1/message/${found.ID}`, { ignoreHTTPSErrors: true })).json();
|
|
467
|
+
return { id: found.ID, subject: message.Subject || '', text: message.Text || '', html: message.HTML || '' };
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/**
|
|
471
|
+
* The address of a link of an e-mail, by the text a person clicks (the text
|
|
472
|
+
* of the button of the HTML version, or the label before the address in the
|
|
473
|
+
* text version: "Login: https://…").
|
|
474
|
+
*/
|
|
475
|
+
function mailLink(mail, label) {
|
|
476
|
+
const anchors = [...String(mail.html).matchAll(/<a\b[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/gi)]
|
|
477
|
+
.map((m) => ({ href: m[1].replace(/&/g, '&'), text: clean(m[2].replace(/<[^>]+>/g, ' ')) }));
|
|
478
|
+
const byText = anchors.find((a) => a.text.toLowerCase() === clean(label).toLowerCase());
|
|
479
|
+
if (byText) return { href: byText.href, anchors };
|
|
480
|
+
const line = String(mail.text).split('\n').map((l) => l.trim()).find((l) => l.toLowerCase().startsWith(clean(label).toLowerCase() + ':'));
|
|
481
|
+
const inLine = line && line.match(/https?:\/\/\S+/);
|
|
482
|
+
return { href: inLine ? inLine[0].replace(/[)\].,]+$/, '') : null, anchors };
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
// ---------------------------------------------------------------------------
|
|
486
|
+
// The page on screen
|
|
487
|
+
// ---------------------------------------------------------------------------
|
|
488
|
+
|
|
489
|
+
/**
|
|
490
|
+
* The status of the document the browser shows: the one webship-js recorded
|
|
491
|
+
* for the last navigation of the page (`_lastResponse`), else the one the
|
|
492
|
+
* browser keeps in its navigation timing.
|
|
493
|
+
*/
|
|
494
|
+
async function documentStatus(world) {
|
|
495
|
+
const last = world._lastResponse;
|
|
496
|
+
const strip = (url) => String(url || '').split('#')[0];
|
|
497
|
+
if (last && last.page === world.page && strip(last.url) === strip(world.page.url())) return last.status;
|
|
498
|
+
return world.page.evaluate(() => {
|
|
499
|
+
const entry = performance.getEntriesByType('navigation')[0];
|
|
500
|
+
return entry && typeof entry.responseStatus === 'number' && entry.responseStatus ? entry.responseStatus : null;
|
|
501
|
+
}).catch(() => null);
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/** The login form: the visible form that holds a password field and an address or user name field. */
|
|
505
|
+
function loginForm(world) {
|
|
506
|
+
return world.page.locator('form:has(input[type="password"]):has(input[name="email"], input[name="username"], input[type="email"])').filter({ visible: true }).first();
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/** What the page on screen says about itself: its address, status, title and main heading. */
|
|
510
|
+
async function pageSummary(world) {
|
|
511
|
+
const status = await documentStatus(world);
|
|
512
|
+
const title = clean(await world.page.title().catch(() => ''));
|
|
513
|
+
const heading = clean(await world.page.locator('h1').first().innerText({ timeout: 500 }).catch(() => ''));
|
|
514
|
+
const text = clean(await world.page.locator('body').innerText({ timeout: 1000 }).catch(() => ''));
|
|
515
|
+
return { path: currentPath(world), status, title, heading, text };
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
// ---------------------------------------------------------------------------
|
|
519
|
+
// Logging in
|
|
520
|
+
// ---------------------------------------------------------------------------
|
|
521
|
+
|
|
522
|
+
const LOGIN_HINT = 'The login form is at /login (worldParameters.loginPath): the fields "Email Address" and "Password", the "Remember me?" box and the "Login" button. Check launchUrl in cucumber.js.';
|
|
523
|
+
|
|
524
|
+
/** The address field of the login form: the field named email (or username), else the address field. */
|
|
525
|
+
async function identityField(world, user) {
|
|
526
|
+
const form = loginForm(world);
|
|
527
|
+
for (const name of ['email', 'username']) {
|
|
528
|
+
const field = form.locator(`input[name="${name}"]`);
|
|
529
|
+
if (await field.count()) return { field: field.first(), value: name === 'username' && user.username ? user.username : user.email };
|
|
530
|
+
}
|
|
531
|
+
return { field: form.locator('input[type="email"]').first(), value: user.email };
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/** Open the login page as a visitor: the browser forgets the session it had. */
|
|
535
|
+
async function openLoginForm(world) {
|
|
536
|
+
await world.page.context().clearCookies();
|
|
537
|
+
world.__sessionKey = null;
|
|
538
|
+
await open(world, siteUrl(world, loginPath(world)));
|
|
539
|
+
try {
|
|
540
|
+
await loginForm(world).waitFor({ state: 'visible', timeout: budget(world) });
|
|
541
|
+
} catch (err) {
|
|
542
|
+
throw friendly({ message: `The login form did not appear at ${siteUrl(world, loginPath(world))} (${world.page.url()}).`, cause: err, hint: LOGIN_HINT });
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/**
|
|
547
|
+
* Fill in and send the login form, then read its outcome: a page that is not
|
|
548
|
+
* the login page (the account is signed in), the error message of the login
|
|
549
|
+
* page, or the answer that there were too many attempts (HTTP 429, when the
|
|
550
|
+
* app limits the requests to its login page).
|
|
551
|
+
*
|
|
552
|
+
* @returns {Promise<{error: string, throttled: boolean, retryAfter: number}>}
|
|
553
|
+
*/
|
|
554
|
+
async function submitLogin(world, user, { remember = false } = {}) {
|
|
555
|
+
await openLoginForm(world);
|
|
556
|
+
const { field, value } = await identityField(world, user);
|
|
557
|
+
await field.fill(value);
|
|
558
|
+
await loginForm(world).locator('input[type="password"]').first().fill(user.password);
|
|
559
|
+
if (remember) {
|
|
560
|
+
let box = loginForm(world).locator('input[type="checkbox"][name="remember"]');
|
|
561
|
+
if (!(await box.count())) box = world.page.getByRole('checkbox', { name: /^\s*remember me\b/i });
|
|
562
|
+
if (!(await box.count())) {
|
|
563
|
+
throw friendly({ message: 'The login form has no "Remember me" box.', hint: LOGIN_HINT });
|
|
564
|
+
}
|
|
565
|
+
if (!(await box.first().isChecked())) await box.first().check();
|
|
566
|
+
}
|
|
567
|
+
const submit = loginForm(world).locator('button[type="submit"], input[type="submit"]').first();
|
|
568
|
+
const { answers } = await afterNavigation(world, () => submit.click());
|
|
569
|
+
const last = answers[answers.length - 1];
|
|
570
|
+
if (last && last.status === 429) {
|
|
571
|
+
const headers = (world._lastResponse && world._lastResponse.headers) || {};
|
|
572
|
+
return { error: 'Too Many Requests (HTTP 429)', throttled: true, retryAfter: Number(headers['retry-after']) || 60 };
|
|
573
|
+
}
|
|
574
|
+
if (!isOnPath(world, loginPath(world))) return { error: '', throttled: false, retryAfter: 0 };
|
|
575
|
+
const errors = (await pageMessages(world)).filter((m) => m.kind === 'error').map((m) => m.text);
|
|
576
|
+
return { error: errors.join(' ') || `the login page came back with no message (${world.page.url()})`, throttled: false, retryAfter: 0 };
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/**
|
|
580
|
+
* Log in through the form; when the app answers that there were too many
|
|
581
|
+
* attempts, wait the time its Retry-After header gives (a minute at most) and
|
|
582
|
+
* try once more.
|
|
583
|
+
*/
|
|
584
|
+
async function loginThroughTheForm(world, user, options) {
|
|
585
|
+
let outcome = await submitLogin(world, user, options);
|
|
586
|
+
if (outcome.throttled) {
|
|
587
|
+
const retry = Math.min(outcome.retryAfter, 65);
|
|
588
|
+
process.stderr.write(`\n[codeigniter-steps] the login of ${user.email} was refused for too many requests: waiting ${retry} s, as the app asks.\n`);
|
|
589
|
+
await world.page.waitForTimeout((retry + 1) * 1000);
|
|
590
|
+
outcome = await submitLogin(world, user, options);
|
|
591
|
+
}
|
|
592
|
+
return outcome;
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
/**
|
|
596
|
+
* Whether somebody is signed in: the app sends a signed-in account away from
|
|
597
|
+
* its login page, and shows the login form to a visitor.
|
|
598
|
+
*/
|
|
599
|
+
async function signedIn(world) {
|
|
600
|
+
await open(world, siteUrl(world, loginPath(world)));
|
|
601
|
+
if (!isOnPath(world, loginPath(world))) return true;
|
|
602
|
+
return !(await loginForm(world).isVisible().catch(() => false));
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
/** Take over the session an account opened earlier in this run. */
|
|
606
|
+
async function restoreSession(world, user) {
|
|
607
|
+
const key = sessionKey(world, user.email);
|
|
608
|
+
const cookies = SESSIONS.get(key);
|
|
609
|
+
if (!cookies || !reuseSessions(world)) return false;
|
|
610
|
+
const context = world.page.context();
|
|
611
|
+
await context.clearCookies();
|
|
612
|
+
await context.addCookies(cookies);
|
|
613
|
+
if (await signedIn(world)) {
|
|
614
|
+
world.__sessionKey = key;
|
|
615
|
+
return true;
|
|
616
|
+
}
|
|
617
|
+
// The session ended since (a logout, a timeout): log in again.
|
|
618
|
+
SESSIONS.delete(key);
|
|
619
|
+
await context.clearCookies();
|
|
620
|
+
return false;
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
/**
|
|
624
|
+
* Log in as an account of the users registry, by its handle: take over its
|
|
625
|
+
* session when it has one from earlier in the run, else log in through the
|
|
626
|
+
* form and keep the session for the next scenario.
|
|
627
|
+
*/
|
|
628
|
+
async function logInAs(world, handle) {
|
|
629
|
+
const user = resolveUser(world, handle);
|
|
630
|
+
if (await restoreSession(world, user)) return;
|
|
631
|
+
const outcome = await loginThroughTheForm(world, user);
|
|
632
|
+
if (outcome.error) {
|
|
633
|
+
throw friendly({
|
|
634
|
+
message: `Could not log in as "${handle}" (${user.email}): ${outcome.error}`,
|
|
635
|
+
hint: outcome.throttled
|
|
636
|
+
? 'The app limits the requests to its login page. Keep session reuse on (worldParameters.reuseSessions) and log in through the form only where a scenario tests the form.'
|
|
637
|
+
: 'Check the address and the password of the account in worldParameters.users, and that the build of the app created the account (and did not ban it).',
|
|
638
|
+
});
|
|
639
|
+
}
|
|
640
|
+
if (reuseSessions(world)) {
|
|
641
|
+
const key = sessionKey(world, user.email);
|
|
642
|
+
SESSIONS.set(key, await world.page.context().cookies());
|
|
643
|
+
world.__sessionKey = key;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/** Forget the session of the browser in the session cache: it ended (a logout, an expiry). */
|
|
648
|
+
function forgetSession(world) {
|
|
649
|
+
for (const key of [...SESSIONS.keys()]) {
|
|
650
|
+
if (key === world.__sessionKey) SESSIONS.delete(key);
|
|
651
|
+
}
|
|
652
|
+
world.__sessionKey = null;
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
module.exports = {
|
|
656
|
+
budget,
|
|
657
|
+
settleBudget,
|
|
658
|
+
escapeRegExp,
|
|
659
|
+
clean,
|
|
660
|
+
listed,
|
|
661
|
+
siteRoot,
|
|
662
|
+
siteUrl,
|
|
663
|
+
appPath,
|
|
664
|
+
loginPath,
|
|
665
|
+
logoutPath,
|
|
666
|
+
loginLinkPath,
|
|
667
|
+
accountPath,
|
|
668
|
+
currentPath,
|
|
669
|
+
pathOf,
|
|
670
|
+
isOnPath,
|
|
671
|
+
requests,
|
|
672
|
+
settle,
|
|
673
|
+
afterNavigation,
|
|
674
|
+
open,
|
|
675
|
+
assertPresence,
|
|
676
|
+
eventually,
|
|
677
|
+
resolveUser,
|
|
678
|
+
addressOf,
|
|
679
|
+
SESSIONS,
|
|
680
|
+
sessionKey,
|
|
681
|
+
reuseSessions,
|
|
682
|
+
findField,
|
|
683
|
+
visibleFieldLabels,
|
|
684
|
+
fillLikeABuiltIn,
|
|
685
|
+
MESSAGE_KINDS,
|
|
686
|
+
pageMessages,
|
|
687
|
+
mailUrl,
|
|
688
|
+
mailList,
|
|
689
|
+
mailTo,
|
|
690
|
+
mailLink,
|
|
691
|
+
documentStatus,
|
|
692
|
+
loginForm,
|
|
693
|
+
pageSummary,
|
|
694
|
+
LOGIN_HINT,
|
|
695
|
+
openLoginForm,
|
|
696
|
+
submitLogin,
|
|
697
|
+
loginThroughTheForm,
|
|
698
|
+
signedIn,
|
|
699
|
+
restoreSession,
|
|
700
|
+
logInAs,
|
|
701
|
+
forgetSession,
|
|
702
|
+
};
|