@webship-js/django-steps 0.0.0-stage → 2.0.1

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,626 @@
1
+ 'use strict';
2
+
3
+ // The add and change forms: opening them, every kind of field by its label (a
4
+ // text, a list, a box, a date and time, an autocomplete field, a two-list
5
+ // selector), read-only fields, the sections (fieldsets) and the ones that fold,
6
+ // saving with the three buttons, the messages after saving, the errors of a
7
+ // refused form, and the view-only form.
8
+
9
+ const { When, Then } = require('@cucumber/cucumber');
10
+ const { friendly } = require('webship-js/tests/step-definitions/webship');
11
+ const {
12
+ budget,
13
+ clean,
14
+ normal,
15
+ listed,
16
+ escapeRegExp,
17
+ absolute,
18
+ hintFor,
19
+ open,
20
+ afterNavigation,
21
+ heading,
22
+ pageSummary,
23
+ eventually,
24
+ messages,
25
+ formErrors,
26
+ modelListUrl,
27
+ findObjects,
28
+ fieldOrFail,
29
+ mainForm,
30
+ setField,
31
+ readField,
32
+ selectorParts,
33
+ optionTexts,
34
+ moveInSelector,
35
+ } = require('./django-helpers');
36
+
37
+ /** Fail unless the page shows a form of the admin (an add, change or view form). */
38
+ async function formOrFail(world) {
39
+ const form = mainForm(world.page);
40
+ if (await world.page.locator('body.change-form').count()) return form;
41
+ throw friendly({ message: `The page is no add or change form of the admin: ${await pageSummary(world)}.`, hint: hintFor(world, 'Open one first: When I open the add form of "Questions", or When I open "What\'s up?" in the "Questions" list') });
42
+ }
43
+
44
+ /**
45
+ * Open the add form of a model, by the model's plural name as the admin index
46
+ * shows it ("Questions").
47
+ *
48
+ * Example #1: When I open the add form of "Questions"
49
+ * Example #2: When we open the add form of "Tags"
50
+ * Example #3: And I open the add form of "Groups"
51
+ * Example #4: When I open the add form of "Categories"
52
+ * Example #5: Given I open the add form of "Questions"
53
+ */
54
+ When(/^(I |we )*open the add form of "([^"]*)"$/, async function (pronounCase, model) {
55
+ const list = await modelListUrl(this, model);
56
+ const response = await open(this, list + 'add/');
57
+ if (response && response.status() >= 400) {
58
+ throw friendly({ message: `The add form of "${model}" answered with HTTP ${response.status()}: ${await pageSummary(this)}.`, hint: 'The account that is logged in may not add to this list.' });
59
+ }
60
+ });
61
+
62
+ /**
63
+ * Open an object's page from the change list on screen: its link in the
64
+ * first column (the change form, or the view form for an account that may
65
+ * only view).
66
+ *
67
+ * Example #1: When I open "Which river is the longest?" from the list
68
+ * Example #2: When we open "editor" from the list
69
+ * Example #3: And I open "What's up?" from the list
70
+ * Example #4: When I open "Science" from the list
71
+ * Example #5: And we open "Which breakfast keeps you going?" from the list
72
+ */
73
+ When(/^(I |we )*open "([^"]*)" from the list$/, async function (pronounCase, object) {
74
+ const page = this.page;
75
+ const link = page.locator('#result_list tbody tr').locator('th a, td.field-__str__ a').filter({ hasText: new RegExp('^\\s*' + escapeRegExp(clean(object)) + '\\s*$') });
76
+ if (!(await link.count())) {
77
+ const shown = (await page.locator('#result_list tbody tr').evaluateAll((rows) => rows.map((r) => ((r.querySelector('th') || r).textContent || '').replace(/\s+/g, ' ').trim()))).filter(Boolean);
78
+ throw friendly({ message: `The list has no row "${object}" on this page. It shows: ${listed(shown)}.`, hint: hintFor(this, 'Search for the row, or go to its page, first.') });
79
+ }
80
+ await afterNavigation(this, () => link.first().click());
81
+ });
82
+
83
+ /**
84
+ * Open an object's page from a model's list, by the object's text: the list
85
+ * is searched for it as a person would, then its link followed.
86
+ *
87
+ * Example #1: When I open "What's up?" in the "Questions" list
88
+ * Example #2: When we open "editor" in the "Users" list
89
+ * Example #3: And I open "Editors" in the "Groups" list
90
+ * Example #4: Given I open "Science" in the "Categories" list
91
+ * Example #5: When I open "Which river is the longest?" in the "Questions" list
92
+ */
93
+ When(/^(I |we )*open "([^"]*)" in the "([^"]*)" list$/, async function (pronounCase, object, model) {
94
+ const urls = await findObjects(this, model, object);
95
+ if (!urls.length) {
96
+ throw friendly({ message: `The "${model}" list has no "${object}".`, hint: 'Write the object as its list shows it in the first column.' });
97
+ }
98
+ const response = await open(this, urls[0]);
99
+ if (response && response.status() >= 400) {
100
+ throw friendly({ message: `The page of "${object}" answered with HTTP ${response.status()}: ${await pageSummary(this)}.`, hint: 'The account that is logged in may not see this object.' });
101
+ }
102
+ });
103
+
104
+ /**
105
+ * Set a field of the form, found by its label as the form shows it (the colon
106
+ * left out), whatever its kind: a text; a list (the option's text); a box
107
+ * ("yes" or "no"); a date ("2026-01-15", "today"); a time ("10:30:00",
108
+ * "now"); a date and time ("2026-01-15 10:30:00", or "now" for the
109
+ * shortcuts "Today" and "Now"); an autocomplete field (the object's text: the
110
+ * step types it and chooses the answer); a two-list selector ("Fun, Serious":
111
+ * exactly those chosen).
112
+ *
113
+ * Example #1: When I set "Question text" to "Who is there?"
114
+ * Example #2: When I set "Date published" to "2026-01-15 10:30:00"
115
+ * Example #3: And I set "Category" to "Science"
116
+ * Example #4: And we set "Tags" to "Fun, Serious"
117
+ * Example #5: When I set "Date published" to "now"
118
+ */
119
+ When(/^(I |we )*set "([^"]*)" to "([^"]*)"$/, { timeout: 60000 }, async function (pronounCase, label, value) {
120
+ const form = await formOrFail(this);
121
+ await setField(this, form, label, value);
122
+ });
123
+
124
+ /**
125
+ * Set several fields of the form at once, from a table of labels and values
126
+ * (see "I set "…" to "…"" for the values each kind of field takes).
127
+ *
128
+ * Example #1: When I set these fields:
129
+ * Example #2: And I set these fields:
130
+ * Example #3: When we set these fields:
131
+ * Example #4: And we set these fields:
132
+ * Example #5: Given I set these fields:
133
+ */
134
+ When(/^(I |we )*set these fields:$/, { timeout: 120000 }, async function (pronounCase, table) {
135
+ const form = await formOrFail(this);
136
+ for (const [label, value] of table.raw()) {
137
+ await setField(this, form, label, value);
138
+ }
139
+ });
140
+
141
+ /**
142
+ * Assert what a field of the form holds, found by its label: the text, the
143
+ * chosen option, "yes" or "no" for a box, "2026-01-15 10:30:00" for a date
144
+ * and time, the chosen object of an autocomplete field, "Fun, Serious" for a
145
+ * selector's chosen options, the text of a read-only field.
146
+ *
147
+ * Example #1: Then "Question text" should be set to "Who is there?"
148
+ * Example #2: Then "Category" should be set to "Science"
149
+ * Example #3: And "Tags" should be set to "Fun, Serious"
150
+ * Example #4: Then "Staff status" should be set to "yes"
151
+ * Example #5: And "Date published" should be set to "2025-01-06 09:00:00"
152
+ */
153
+ Then(/^"([^"]*)" should be set to "([^"]*)"$/, async function (label, expected) {
154
+ const form = await formOrFail(this);
155
+ await eventually(this, () => readField(this, form, label), (value) => normal(value) === normal(expected),
156
+ (value) => ({ message: `The field "${label}" holds "${value}", not "${expected}".`, hint: 'A list of options reads "A, B"; a box reads "yes" or "no".' }), 3000);
157
+ });
158
+
159
+ /**
160
+ * Assert that a field of the form is read-only (the admin shows its value as
161
+ * text, with no input), and with "and show" what it shows.
162
+ *
163
+ * Example #1: Then "Total votes" should be read-only
164
+ * Example #2: Then "Total votes" should be read-only and show "0"
165
+ * Example #3: And "Total votes" should be read-only and show "8"
166
+ * Example #4: Then "Question text" should be read-only and show "What's up?"
167
+ * Example #5: And "Category" should be read-only and show "Food"
168
+ */
169
+ Then(/^"([^"]*)" should be read-only(?: and show "([^"]*)")?$/, async function (label, expected) {
170
+ const form = await formOrFail(this);
171
+ const field = await fieldOrFail(this, form, label);
172
+ if (field.kind !== 'readonly') {
173
+ throw friendly({ message: `The field "${label}" is not read-only: it is an input (${field.kind}).`, hint: 'The admin shows a read-only field (readonly_fields, or a form the account may only view) as text.' });
174
+ }
175
+ if (expected !== null && expected !== undefined) {
176
+ const shown = clean(await field.box.locator('.readonly').first().innerText());
177
+ if (normal(shown) !== normal(expected)) {
178
+ throw friendly({ message: `The read-only field "${label}" shows "${shown}", not "${expected}".`, hint: 'An empty value shows as "-".' });
179
+ }
180
+ }
181
+ });
182
+
183
+ /** The sections (fieldsets) of the form: their headings and whether each folds and is open. */
184
+ async function sections(page) {
185
+ return page.evaluate(() => [...document.querySelectorAll('#content-main form fieldset.module')]
186
+ .filter((f) => !f.closest('.inline-group'))
187
+ .map((f) => {
188
+ const h = f.querySelector(':scope > h2, :scope > details > summary h2, :scope > details > summary');
189
+ const details = f.querySelector(':scope > details');
190
+ return {
191
+ title: h ? h.textContent.replace(/\s+/g, ' ').trim() : '',
192
+ folds: f.classList.contains('collapse'),
193
+ open: details ? details.open : true,
194
+ fields: [...f.querySelectorAll('label, legend')].filter((l) => !l.closest('p.datetime, .selector, .help, .datetimeshortcuts'))
195
+ .map((l) => l.textContent.replace(/\s+/g, ' ').trim().replace(/\s*:$/, '')).filter(Boolean),
196
+ };
197
+ })).catch(() => []);
198
+ }
199
+
200
+ /**
201
+ * Assert that the form has (or does not have) a section, by its heading.
202
+ *
203
+ * Example #1: Then the form should have the section "Classification"
204
+ * Example #2: Then the form should have the section "Date information"
205
+ * Example #3: And the form should not have the section "Advanced options"
206
+ * Example #4: Then the form should have the section "Personal info"
207
+ * Example #5: And the form should have the section "Permissions"
208
+ */
209
+ Then(/^the form should( not)* have the section "([^"]*)"$/, async function (notCase, title) {
210
+ await formOrFail(this);
211
+ const all = await sections(this.page);
212
+ const has = all.some((s) => normal(s.title) === normal(title));
213
+ if (has === !!notCase) {
214
+ throw friendly({ message: notCase ? `The form has the section "${title}".` : `The form has no section "${title}". Its sections: ${listed(all.map((s) => s.title))}.`, hint: 'The sections are the model admin\'s fieldsets; the first often has no heading.' });
215
+ }
216
+ });
217
+
218
+ /**
219
+ * Assert that a section of the form has (or does not have) a field, by its
220
+ * label.
221
+ *
222
+ * Example #1: Then the section "Classification" should have the field "Category"
223
+ * Example #2: Then the section "Date information" should have the field "Date published"
224
+ * Example #3: And the section "Classification" should not have the field "Question text"
225
+ * Example #4: Then the section "Permissions" should have the field "Groups"
226
+ * Example #5: And the section "Results" should have the field "Total votes"
227
+ */
228
+ Then(/^the section "([^"]*)" should( not)* have the field "([^"]*)"$/, async function (title, notCase, label) {
229
+ await formOrFail(this);
230
+ const all = await sections(this.page);
231
+ const section = all.find((s) => normal(s.title) === normal(title));
232
+ if (!section) {
233
+ throw friendly({ message: `The form has no section "${title}". Its sections: ${listed(all.map((s) => s.title))}.`, hint: 'Name a section by its heading.' });
234
+ }
235
+ const has = section.fields.some((f) => normal(f) === normal(label));
236
+ if (has === !!notCase) {
237
+ throw friendly({ message: notCase ? `The section "${title}" has the field "${label}".` : `The section "${title}" has no field "${label}". Its fields: ${listed(section.fields)}.`, hint: 'Name a field by its label, without the colon.' });
238
+ }
239
+ });
240
+
241
+ /**
242
+ * Open or close a section of the form that folds (a fieldset with the class
243
+ * "collapse"), with its heading, as a person does.
244
+ *
245
+ * Example #1: When I open the section "Date information"
246
+ * Example #2: When I close the section "Date information"
247
+ * Example #3: And we open the section "Date information"
248
+ * Example #4: When we close the section "Date information"
249
+ * Example #5: And I open the section "Date information"
250
+ */
251
+ When(/^(I |we )*(open|close) the section "([^"]*)"$/, async function (pronounCase, verb, title) {
252
+ await formOrFail(this);
253
+ const page = this.page;
254
+ const all = await sections(page);
255
+ const section = all.find((s) => normal(s.title) === normal(title));
256
+ if (!section) {
257
+ throw friendly({ message: `The form has no section "${title}". Its sections: ${listed(all.map((s) => s.title))}.`, hint: 'Name a section by its heading.' });
258
+ }
259
+ if (!section.folds) {
260
+ throw friendly({ message: `The section "${title}" does not fold: it is always open.`, hint: 'A section folds when its fieldset has the class "collapse".' });
261
+ }
262
+ if (section.open === (verb === 'open')) return;
263
+ const summary = page.locator('#content-main form fieldset.collapse > details > summary').filter({ hasText: new RegExp('^\\s*' + escapeRegExp(clean(title)) + '\\s*$') });
264
+ if (!(await summary.count())) {
265
+ throw friendly({ message: `The section "${title}" shows open and cannot be folded now (a section with an error stays open).`, hint: 'The admin opens a folded section when a field in it has an error.' });
266
+ }
267
+ await summary.first().click();
268
+ await eventually(this, async () => (await sections(page)).find((s) => normal(s.title) === normal(title)), (s) => s && s.open === (verb === 'open'),
269
+ () => ({ message: `The section "${title}" did not ${verb}.`, hint: 'The heading of a folding section opens and closes it.' }), 3000);
270
+ });
271
+
272
+ /**
273
+ * Assert that a section of the form that folds is open or closed.
274
+ *
275
+ * Example #1: Then the section "Date information" should be closed
276
+ * Example #2: Then the section "Date information" should be open
277
+ * Example #3: And the section "Date information" should be closed
278
+ * Example #4: Then the section "Classification" should be open
279
+ * Example #5: And the section "Date information" should be open
280
+ */
281
+ Then(/^the section "([^"]*)" should be (open|closed)$/, async function (title, state) {
282
+ await formOrFail(this);
283
+ const all = await sections(this.page);
284
+ const section = all.find((s) => normal(s.title) === normal(title));
285
+ if (!section) {
286
+ throw friendly({ message: `The form has no section "${title}". Its sections: ${listed(all.map((s) => s.title))}.`, hint: 'Name a section by its heading.' });
287
+ }
288
+ if (section.open !== (state === 'open')) {
289
+ throw friendly({ message: `The section "${title}" is ${section.open ? 'open' : 'closed'}, not ${state}.`, hint: `It folds with its heading: When I ${state === 'open' ? 'open' : 'close'} the section "${title}"` });
290
+ }
291
+ });
292
+
293
+ /** An autocomplete field of the form, by its label, or a failure. */
294
+ async function autocompleteField(world, label) {
295
+ const form = await formOrFail(world);
296
+ const field = await fieldOrFail(world, form, label);
297
+ if (field.kind !== 'autocomplete') {
298
+ throw friendly({ message: `The field "${label}" is no autocomplete field (it is ${field.kind}).`, hint: 'An autocomplete field is a box that searches as you type (autocomplete_fields).' });
299
+ }
300
+ return field;
301
+ }
302
+
303
+ /**
304
+ * Type a text in an autocomplete field, without choosing: the field opens its
305
+ * list of answers and the step waits for the admin's answer to that text.
306
+ * Check the answers with the next step.
307
+ *
308
+ * Example #1: When I type "Sci" in the "Category" autocomplete
309
+ * Example #2: When we type "Tra" in the "Category" autocomplete
310
+ * Example #3: And I type "zzz" in the "Category" autocomplete
311
+ * Example #4: When I type "S" in the "Category" autocomplete
312
+ * Example #5: And we type "Food" in the "Category" autocomplete
313
+ */
314
+ When(/^(I |we )*type "([^"]*)" in the "([^"]*)" autocomplete$/, async function (pronounCase, text, label) {
315
+ const field = await autocompleteField(this, label);
316
+ const page = this.page;
317
+ const id = await field.box.locator('select.admin-autocomplete').first().getAttribute('id');
318
+ if (!(await page.locator('.select2-container--open .select2-search__field').count())) await field.box.locator('.select2-selection').first().click();
319
+ const search = page.locator('.select2-container--open .select2-search__field');
320
+ await search.waitFor({ state: 'visible', timeout: budget(this) });
321
+ const answered = page.waitForResponse((r) => {
322
+ try { const u = new URL(r.url()); return /\/autocomplete\/?$/.test(u.pathname) && u.searchParams.get('term') === text; } catch { return false; }
323
+ }, { timeout: budget(this) }).catch(() => null);
324
+ await search.fill(text);
325
+ await answered;
326
+ await page.waitForFunction((rid) => { const l = document.getElementById(rid); return !!l && !l.querySelector('.loading-results'); }, `select2-${id}-results`, { timeout: budget(this) }).catch(() => {});
327
+ this.__autocompleteOpen = id;
328
+ });
329
+
330
+ /**
331
+ * Assert that the open autocomplete field offers (or does not offer) an
332
+ * answer, after "I type "…" in the "…" autocomplete".
333
+ *
334
+ * Example #1: Then the "Category" autocomplete should offer "Science"
335
+ * Example #2: Then the "Category" autocomplete should not offer "Travel"
336
+ * Example #3: And the "Category" autocomplete should offer "Travel"
337
+ * Example #4: Then the "Category" autocomplete should not offer "Science"
338
+ * Example #5: And the "Category" autocomplete should offer "Food"
339
+ */
340
+ Then(/^the "([^"]*)" autocomplete should( not)* offer "([^"]*)"$/, async function (label, notCase, value) {
341
+ const field = await autocompleteField(this, label);
342
+ const id = await field.box.locator('select.admin-autocomplete').first().getAttribute('id');
343
+ const offered = (await this.page.locator(`#select2-${id}-results li.select2-results__option`).allTextContents().catch(() => [])).map(clean);
344
+ const has = offered.some((o) => normal(o) === normal(value));
345
+ if (has === !!notCase) {
346
+ throw friendly({ message: notCase ? `The "${label}" autocomplete offers "${value}".` : `The "${label}" autocomplete does not offer "${value}". It offers: ${listed(offered)}.`, hint: `Type in it first: When I type "${value.slice(0, 3)}" in the "${label}" autocomplete` });
347
+ }
348
+ });
349
+
350
+ /**
351
+ * Choose an object in an autocomplete field, by its text: the step opens the
352
+ * field, types the text, waits for the admin's answer and chooses the answer
353
+ * that is exactly that text.
354
+ *
355
+ * Example #1: When I choose "Science" in the "Category" autocomplete
356
+ * Example #2: When we choose "Travel" in the "Category" autocomplete
357
+ * Example #3: And I choose "Food" in the "Category" autocomplete
358
+ * Example #4: When I choose "Music" in the "Category" autocomplete
359
+ * Example #5: And we choose "Sport" in the "Category" autocomplete
360
+ */
361
+ When(/^(I |we )*choose "([^"]*)" in the "([^"]*)" autocomplete$/, { timeout: 60000 }, async function (pronounCase, value, label) {
362
+ await autocompleteField(this, label);
363
+ const form = mainForm(this.page);
364
+ if (await this.page.locator('.select2-container--open').count()) await this.page.keyboard.press('Escape');
365
+ await setField(this, form, label, value);
366
+ });
367
+
368
+ /** A two-list selector of the form, by its label ("Tags", "Permissions"), or a failure. */
369
+ async function selectorField(world, label) {
370
+ const form = await formOrFail(world);
371
+ const field = await fieldOrFail(world, form, label);
372
+ if (field.kind !== 'selector') {
373
+ throw friendly({ message: `The field "${label}" is no two-list selector (it is ${field.kind}).`, hint: 'A two-list selector has the lists "Available …" and "Chosen …" (filter_horizontal, filter_vertical).' });
374
+ }
375
+ return field;
376
+ }
377
+
378
+ /**
379
+ * Move options of a two-list selector, by their texts ("Fun", or "Fun,
380
+ * Serious"): "choose" from the available list to the chosen one with the
381
+ * "Choose" button, "remove" from the chosen list with the "Remove" button.
382
+ *
383
+ * Example #1: When I choose "Fun" in the "Tags" selector
384
+ * Example #2: When I remove "Fun" from the "Tags" selector
385
+ * Example #3: And we choose "Fun, Serious" in the "Tags" selector
386
+ * Example #4: When I choose "Polls | question | Can change question" in the "Permissions" selector
387
+ * Example #5: And I remove "Serious" from the "Tags" selector
388
+ */
389
+ When(/^(I |we )*(?:choose "([^"]*)" in|remove "([^"]*)" from) the "([^"]*)" selector$/, async function (pronounCase, chosen, removed, label) {
390
+ const field = await selectorField(this, label);
391
+ // Cucumber gives null for the half of the phrase that is not there.
392
+ const choosing = chosen !== null && chosen !== undefined;
393
+ const values = String(choosing ? chosen : removed).split(',').map(clean).filter(Boolean);
394
+ await moveInSelector(this, field.box, values, choosing ? 'choose' : 'remove', label);
395
+ });
396
+
397
+ /**
398
+ * Move every option of a two-list selector at once, with its "Choose all" or
399
+ * "Remove all" button.
400
+ *
401
+ * Example #1: When I choose all in the "Tags" selector
402
+ * Example #2: When I remove all from the "Tags" selector
403
+ * Example #3: And we choose all in the "Tags" selector
404
+ * Example #4: When we remove all from the "Tags" selector
405
+ * Example #5: And I remove all from the "Tags" selector
406
+ */
407
+ When(/^(I |we )*(choose all in|remove all from) the "([^"]*)" selector$/, async function (pronounCase, verb, label) {
408
+ const field = await selectorField(this, label);
409
+ const parts = selectorParts(field.box);
410
+ const all = verb.startsWith('choose');
411
+ const button = all ? parts.addAll : parts.removeAll;
412
+ if (await button.isDisabled().catch(() => false)) return; // nothing to move
413
+ await button.click();
414
+ await eventually(this, () => optionTexts(all ? parts.from : parts.to), (left) => left.length === 0,
415
+ (left) => ({ message: `After "${all ? 'Choose all' : 'Remove all'}" the ${all ? 'available' : 'chosen'} "${label}" still list ${listed(left)}.`, hint: 'The button moves the options the filter shows.' }), 3000);
416
+ });
417
+
418
+ /**
419
+ * Filter the available list of a two-list selector with its filter box: it
420
+ * shows only the options with the text.
421
+ *
422
+ * Example #1: When I filter the available "Tags" with "Fu"
423
+ * Example #2: When we filter the available "Permissions" with "question"
424
+ * Example #3: And I filter the available "Tags" with ""
425
+ * Example #4: When I filter the available "Groups" with "Edit"
426
+ * Example #5: And we filter the available "Tags" with "Ser"
427
+ */
428
+ When(/^(I |we )*filter the available "([^"]*)" with "([^"]*)"$/, async function (pronounCase, label, text) {
429
+ const field = await selectorField(this, label);
430
+ const parts = selectorParts(field.box);
431
+ await parts.filter.fill('');
432
+ if (text) await parts.filter.pressSequentially(text);
433
+ else await parts.filter.press('Backspace').catch(() => {});
434
+ });
435
+
436
+ /**
437
+ * Assert where an option of a two-list selector is: in the "chosen" list or
438
+ * the "available" one (as its filter shows it).
439
+ *
440
+ * Example #1: Then the "Tags" selector should have "Fun" chosen
441
+ * Example #2: Then the "Tags" selector should have "Long" available
442
+ * Example #3: And the "Tags" selector should not have "Fun" available
443
+ * Example #4: Then the "Permissions" selector should have "Polls | question | Can change question" chosen
444
+ * Example #5: And the "Tags" selector should not have "Serious" chosen
445
+ */
446
+ Then(/^the "([^"]*)" selector should( not)* have "([^"]*)" (chosen|available)$/, async function (label, notCase, value, list) {
447
+ const field = await selectorField(this, label);
448
+ const parts = selectorParts(field.box);
449
+ const options = await (list === 'chosen' ? parts.to : parts.from).locator('option').evaluateAll((opts) => opts.filter((o) => o.style.display !== 'none' && !o.hidden).map((o) => o.textContent.replace(/\s+/g, ' ').trim()));
450
+ const has = options.some((o) => normal(o) === normal(value));
451
+ if (has === !!notCase) {
452
+ throw friendly({ message: notCase ? `The ${list} "${label}" list "${value}".` : `The ${list} "${label}" do not list "${value}". They list: ${listed(options)}.`, hint: list === 'available' ? 'The filter box of the available list hides the options without its text.' : 'Choose it with: When I choose "' + value + '" in the "' + label + '" selector' });
453
+ }
454
+ });
455
+
456
+ /**
457
+ * Save the form with one of its three buttons: "Save" (back to the list),
458
+ * "Save and add another" (a new add form) or "Save and continue editing"
459
+ * (the same form again). The step waits for the next page; a form the admin
460
+ * refuses comes back with its errors (check them with the error steps).
461
+ *
462
+ * Example #1: When I save the form
463
+ * Example #2: When I save the form and add another
464
+ * Example #3: When I save the form and continue editing
465
+ * Example #4: And we save the form
466
+ * Example #5: And we save the form and continue editing
467
+ */
468
+ When(/^(I |we )*save the form( and add another| and continue editing)?$/, async function (pronounCase, which) {
469
+ await formOrFail(this);
470
+ const page = this.page;
471
+ const name = !which ? '_save' : which.includes('another') ? '_addanother' : '_continue';
472
+ const button = page.locator(`.submit-row [name="${name}"]`);
473
+ if (!(await button.count())) {
474
+ const offered = await page.locator('.submit-row [type="submit"]').evaluateAll((bs) => bs.map((b) => b.value || b.textContent.trim()));
475
+ throw friendly({ message: `The form has no button "${!which ? 'Save' : which.includes('another') ? 'Save and add another' : 'Save and continue editing'}". Its buttons: ${listed(offered)}.`, hint: 'A form the account may only view has no save buttons.' });
476
+ }
477
+ await afterNavigation(this, () => button.first().click());
478
+ });
479
+
480
+ /**
481
+ * Assert that the last save went through: the admin shows its success
482
+ * message and no error.
483
+ *
484
+ * Example #1: Then the form should be saved
485
+ * Example #2: And the form should be saved
486
+ * Example #3: Then the form should be saved
487
+ * Example #4: And the form should be saved
488
+ * Example #5: Then the form should be saved
489
+ */
490
+ Then(/^the form should be saved$/, async function () {
491
+ const page = this.page;
492
+ const ok = await messages(page, 'success');
493
+ const errors = await formErrors(page);
494
+ if (!ok.length || errors.length) {
495
+ throw friendly({
496
+ message: errors.length ? `The admin refused the form: ${listed(errors)}.` : `The admin shows no success message: ${await pageSummary(this)}.`,
497
+ hint: hintFor(this, 'Save it first: When I save the form; the fields with an error say why.'),
498
+ });
499
+ }
500
+ });
501
+
502
+ /**
503
+ * Assert the messages the admin shows above a page after an action: success,
504
+ * warning, error or info, by their text or a part of it (straight quotes match
505
+ * the admin's typographic ones).
506
+ *
507
+ * Example #1: Then I should see the success message "The question “What is new?” was added successfully."
508
+ * Example #2: Then I should see the success message "was changed successfully"
509
+ * Example #3: And I should see the warning message "No action selected."
510
+ * Example #4: Then I should not see the error message "Please correct the error below."
511
+ * Example #5: And we should see the success message "Successfully deleted 2 questions."
512
+ */
513
+ Then(/^(I |we )*should( not)* see the (success|warning|error|info) message "([^"]*)"$/, async function (pronounCase, notCase, kind, expected) {
514
+ const page = this.page;
515
+ const read = () => messages(page, kind);
516
+ const has = (lines) => lines.some((line) => normal(line).includes(normal(expected)));
517
+ if (notCase) {
518
+ const lines = await read();
519
+ if (has(lines)) throw friendly({ message: `The admin shows the ${kind} message "${lines.find((l) => normal(l).includes(normal(expected)))}".`, hint: 'The messages show above the page after an action.' });
520
+ return;
521
+ }
522
+ await eventually(this, read, has, async (lines) => ({
523
+ message: `The admin shows no ${kind} message "${expected}". Its ${kind} messages: ${listed(lines)}; all messages: ${listed(await messages(page, 'any'))}.`,
524
+ hint: hintFor(this, 'The admin shows its messages above the page after an action.'),
525
+ }), 3000);
526
+ });
527
+
528
+ /**
529
+ * Assert the error of one field of a refused form, by the field's label (or a
530
+ * part of the error).
531
+ *
532
+ * Example #1: Then the field "Question text" should have the error "This field is required."
533
+ * Example #2: Then the field "Date published" should have the error "This field is required."
534
+ * Example #3: And the field "Name" should have the error "Group with this Name already exists."
535
+ * Example #4: Then the field "Question text" should not have the error "This field is required."
536
+ * Example #5: And the field "New password confirmation" should have the error "The two password fields didn’t match."
537
+ */
538
+ Then(/^the field "([^"]*)" should( not)* have the error "([^"]*)"$/, async function (label, notCase, expected) {
539
+ const page = this.page;
540
+ const form = mainForm(page);
541
+ const field = await fieldOrFail(this, form, label);
542
+ // The error list sits in the field's row, before or beside the input.
543
+ const row = field.box.locator('xpath=ancestor-or-self::*[contains(concat(" ", normalize-space(@class), " "), " form-row ")][1]');
544
+ const scope = (await row.count()) ? row : field.box;
545
+ const errors = (await scope.locator('ul.errorlist li').allTextContents().catch(() => [])).map(clean);
546
+ const has = errors.some((e) => normal(e).includes(normal(expected)));
547
+ if (has === !!notCase) {
548
+ throw friendly({ message: notCase ? `The field "${label}" has the error "${expected}".` : `The field "${label}" does not have the error "${expected}". Its errors: ${listed(errors)}.`, hint: 'The admin writes a field\'s errors in its row, after the form was sent.' });
549
+ }
550
+ });
551
+
552
+ /**
553
+ * Assert the error the admin writes above a refused form (its error note,
554
+ * "Please correct the error below.", or an error of the whole form).
555
+ *
556
+ * Example #1: Then the form should show the error "Please correct the errors below."
557
+ * Example #2: Then the form should show the error "Please correct the error below."
558
+ * Example #3: And the form should show the error "Please correct"
559
+ * Example #4: Then the form should not show the error "Please correct the errors below."
560
+ * Example #5: And the form should show the error "Please correct the errors below."
561
+ */
562
+ Then(/^the form should( not)* show the error "([^"]*)"$/, async function (notCase, expected) {
563
+ const errors = await formErrors(this.page);
564
+ const has = errors.some((e) => normal(e).includes(normal(expected)));
565
+ if (has === !!notCase) {
566
+ throw friendly({ message: notCase ? `The form shows the error "${expected}".` : `The form does not show the error "${expected}". Its errors: ${listed(errors)}; ${await pageSummary(this)}.`, hint: hintFor(this, 'Send the form first: When I save the form') });
567
+ }
568
+ });
569
+
570
+ /**
571
+ * Assert that the form on screen has no error at all.
572
+ *
573
+ * Example #1: Then the form should have no errors
574
+ * Example #2: And the form should have no errors
575
+ * Example #3: Then the form should have no errors
576
+ * Example #4: And the form should have no errors
577
+ * Example #5: Then the form should have no errors
578
+ */
579
+ Then(/^the form should have no errors$/, async function () {
580
+ const page = this.page;
581
+ const errors = [...await formErrors(page), ...(await page.locator('#content-main ul.errorlist li').allTextContents().catch(() => [])).map(clean)].filter(Boolean);
582
+ if (errors.length) {
583
+ throw friendly({ message: `The form has errors: ${listed(errors)}.`, hint: 'The fields with an error say why.' });
584
+ }
585
+ });
586
+
587
+ /**
588
+ * Assert which form of the admin the page is, by its heading ("Add question",
589
+ * "Change question", "View question"), and with "for" the object it is the
590
+ * form of.
591
+ *
592
+ * Example #1: Then I should see the "Add question" form
593
+ * Example #2: Then I should see the "Change question" form for "What's up?"
594
+ * Example #3: And I should see the "View question" form for "What's up?"
595
+ * Example #4: Then we should see the "Change user" form for "editor"
596
+ * Example #5: And I should see the "Add group" form
597
+ */
598
+ Then(/^(I |we )*should see the "([^"]*)" form(?: for "([^"]*)")?$/, async function (pronounCase, form, object) {
599
+ const page = this.page;
600
+ const read = async () => ({ h1: await heading(page), title: clean(await page.title()) });
601
+ await eventually(this, read, (v) => normal(v.h1) === normal(form) && (!object || normal(v.title).startsWith(normal(object) + ' |')),
602
+ async (v) => ({ message: `The page is ${v.h1 ? `the "${v.h1}" form` : 'no form'}${object ? ` (title "${v.title}")` : ''}, not the "${form}" form${object ? ` for "${object}"` : ''}: ${await pageSummary(this)}.`, hint: hintFor(this, 'The admin titles a form by what it does and the model: "Add question", "Change question", "View question".') }));
603
+ });
604
+
605
+ /**
606
+ * Assert that the form on screen is (or is not) read-only: a form the account
607
+ * may only view shows its values as text and has no save buttons.
608
+ *
609
+ * Example #1: Then the form should be read-only
610
+ * Example #2: Then the form should not be read-only
611
+ * Example #3: And the form should be read-only
612
+ * Example #4: Then the form should not be read-only
613
+ * Example #5: And the form should be read-only
614
+ */
615
+ Then(/^the form should( not)* be read-only$/, async function (notCase) {
616
+ await formOrFail(this);
617
+ const page = this.page;
618
+ const saves = await page.locator('.submit-row [name="_save"], .submit-row [name="_continue"], .submit-row [name="_addanother"]').count();
619
+ const inputs = await page.locator('#content-main form .form-row').locator('input:not([type=hidden]), select, textarea').count();
620
+ const readOnly = saves === 0 && inputs === 0;
621
+ if (readOnly === !!notCase) {
622
+ throw friendly({ message: notCase ? 'The form is read-only: no save button, no input.' : `The form is not read-only: ${saves} save button${saves === 1 ? '' : 's'}, ${inputs} input${inputs === 1 ? '' : 's'}.`, hint: 'An account with only the view permission gets the form as text, with a "Close" button.' });
623
+ }
624
+ });
625
+
626
+ module.exports = { formOrFail, absolute };