@webship-js/django-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,383 @@
1
+ 'use strict';
2
+
3
+ // The admin around the forms and lists: the index with its apps and models and
4
+ // what an account may do with each, the recent actions, the breadcrumbs, the
5
+ // navigation sidebar, the colour theme, the lists opened by a model's name, and
6
+ // the pages an account is refused.
7
+
8
+ const { Given, When, Then } = require('@cucumber/cucumber');
9
+ const { friendly } = require('webship-js/tests/step-definitions/webship');
10
+ const {
11
+ budget,
12
+ clean,
13
+ normal,
14
+ listed,
15
+ escapeRegExp,
16
+ adminUrl,
17
+ absolute,
18
+ hintFor,
19
+ open,
20
+ afterNavigation,
21
+ pageSummary,
22
+ eventually,
23
+ modelListUrl,
24
+ } = require('./django-helpers');
25
+
26
+ /** Open the admin index unless the page already is it. */
27
+ async function onIndex(world) {
28
+ if (!(await world.page.locator('body.dashboard').count())) await open(world, adminUrl(world));
29
+ if (!(await world.page.locator('body.dashboard').count())) {
30
+ throw friendly({ message: `The admin index did not open: ${await pageSummary(world)}.`, hint: hintFor(world, 'Log in first: Given I am a logged in user with the "editor" user') });
31
+ }
32
+ }
33
+
34
+ /** The apps and models the admin index shows, with the links of each model. */
35
+ async function indexModels(page) {
36
+ return page.evaluate(() => [...document.querySelectorAll('#content-main [class^="app-"].module, #content-main .module[class*=" app-"]')].map((m) => ({
37
+ app: (m.querySelector('caption') || {}).textContent ? m.querySelector('caption').textContent.replace(/\s+/g, ' ').trim() : '',
38
+ models: [...m.querySelectorAll('tr[class^="model-"], tr[class*=" model-"]')].map((tr) => ({
39
+ name: (tr.querySelector('th') || {}).textContent ? tr.querySelector('th').textContent.replace(/\s+/g, ' ').trim() : '',
40
+ add: !!tr.querySelector('a.addlink'),
41
+ change: !!tr.querySelector('a.changelink'),
42
+ view: !!tr.querySelector('a.viewlink'),
43
+ })),
44
+ })));
45
+ }
46
+
47
+ /**
48
+ * Open the admin index (the site administration page), or be on it.
49
+ *
50
+ * Example #1: Given I am on the admin index
51
+ * Example #2: When I open the admin index
52
+ * Example #3: Given we are on the admin index
53
+ * Example #4: And I open the admin index
54
+ * Example #5: When we open the admin index
55
+ */
56
+ Given(/^(?:I am on|we are on|(?:I |we )?open) the admin index$/, async function () {
57
+ await open(this, adminUrl(this));
58
+ });
59
+
60
+ /**
61
+ * Assert that the admin index lists (or does not list) an app, by its name as
62
+ * the index shows it. An account sees only the apps it has a permission in.
63
+ *
64
+ * Example #1: Then the admin index should list the app "Polls"
65
+ * Example #2: Then the admin index should not list the app "Authentication and Authorization"
66
+ * Example #3: And the admin index should list the app "Authentication and Authorization"
67
+ * Example #4: Then the admin index should list the app "Polls"
68
+ * Example #5: And the admin index should not list the app "Polls"
69
+ */
70
+ Then(/^the admin index should( not)* list the app "([^"]*)"$/, async function (notCase, app) {
71
+ await onIndex(this);
72
+ const apps = (await indexModels(this.page)).map((a) => a.app);
73
+ const listedApp = apps.some((a) => normal(a) === normal(app));
74
+ if (listedApp === !!notCase) {
75
+ throw friendly({
76
+ message: notCase ? `The admin index lists the app "${app}".` : `The admin index does not list the app "${app}". It lists: ${listed(apps)}.`,
77
+ hint: 'The index lists the apps in which the account has at least one permission.',
78
+ });
79
+ }
80
+ });
81
+
82
+ /**
83
+ * Assert that an app of the admin index lists (or does not list) a model, by
84
+ * the model's plural name as the index shows it.
85
+ *
86
+ * Example #1: Then the app "Polls" should list the model "Questions"
87
+ * Example #2: Then the app "Authentication and Authorization" should list the model "Users"
88
+ * Example #3: And the app "Polls" should list the model "Tags"
89
+ * Example #4: Then the app "Polls" should not list the model "Choices"
90
+ * Example #5: And the app "Authentication and Authorization" should not list the model "Questions"
91
+ */
92
+ Then(/^the app "([^"]*)" should( not)* list the model "([^"]*)"$/, async function (app, notCase, model) {
93
+ await onIndex(this);
94
+ const apps = await indexModels(this.page);
95
+ const entry = apps.find((a) => normal(a.app) === normal(app));
96
+ if (!entry) {
97
+ throw friendly({ message: `The admin index does not list the app "${app}". It lists: ${listed(apps.map((a) => a.app))}.`, hint: 'Write the app as the index shows it, such as "Polls".' });
98
+ }
99
+ const has = entry.models.some((m) => normal(m.name) === normal(model));
100
+ if (has === !!notCase) {
101
+ throw friendly({
102
+ message: notCase ? `The app "${app}" lists the model "${model}".` : `The app "${app}" does not list the model "${model}". It lists: ${listed(entry.models.map((m) => m.name))}.`,
103
+ hint: 'A model is listed when the admin registers it and the account has a permission on it.',
104
+ });
105
+ }
106
+ });
107
+
108
+ /**
109
+ * Assert what the account may do with a model, as the admin index shows it:
110
+ * "add" (the "Add" link), "change" (the "Change" link) or "view" (the "View"
111
+ * link, or "Change", which includes viewing).
112
+ *
113
+ * Example #1: Then I should be able to add "Questions"
114
+ * Example #2: Then I should not be able to add "Questions"
115
+ * Example #3: And we should be able to change "Tags"
116
+ * Example #4: Then I should not be able to change "Categories"
117
+ * Example #5: And I should be able to view "Questions"
118
+ */
119
+ Then(/^(I |we )*should( not)* be able to (add|change|view) "([^"]*)"$/, async function (pronounCase, notCase, what, model) {
120
+ await onIndex(this);
121
+ const apps = await indexModels(this.page);
122
+ const rows = apps.flatMap((a) => a.models.map((m) => ({ ...m, app: a.app }))).filter((m) => normal(m.name) === normal(model));
123
+ const can = rows.some((m) => (what === 'add' ? m.add : what === 'change' ? m.change : m.view || m.change));
124
+ if (can === !!notCase) {
125
+ const offered = rows.length ? rows.map((m) => [m.add && 'add', m.change && 'change', m.view && 'view'].filter(Boolean).join(', ') || 'nothing').join('; ') : null;
126
+ throw friendly({
127
+ message: notCase
128
+ ? `The admin index offers to ${what} "${model}".`
129
+ : (rows.length ? `The admin index does not offer to ${what} "${model}": it offers ${offered}.` : `The admin index does not list "${model}" for this account.`),
130
+ hint: 'The index shows "Add", "Change" or "View" by the permissions of the account that is logged in.',
131
+ });
132
+ }
133
+ });
134
+
135
+ /**
136
+ * Open the list of a model (its change list), by the model's plural name as
137
+ * the admin index shows it; with "of", the app's name too, when two apps have
138
+ * a model of that name.
139
+ *
140
+ * Example #1: When I open the "Questions" list
141
+ * Example #2: Given I am on the "Users" list
142
+ * Example #3: When we open the "Tags" list of "Polls"
143
+ * Example #4: Given we are on the "Questions" list
144
+ * Example #5: And I open the "Groups" list
145
+ */
146
+ Given(/^(?:I am on|we are on|(?:I |we )?open) the "([^"]*)" list(?: of "([^"]*)")?$/, async function (model, app) {
147
+ const url = await modelListUrl(this, model, app);
148
+ const response = await open(this, url);
149
+ if (response && response.status() >= 400) {
150
+ throw friendly({
151
+ message: `The "${model}" list answered with HTTP ${response.status()}: ${await pageSummary(this)}.`,
152
+ hint: 'The account that is logged in may not see this list: check its permissions, or log in as another account.',
153
+ });
154
+ }
155
+ });
156
+
157
+ /**
158
+ * Assert that the page is the list of a model: the admin's change list, with
159
+ * the model's name at the end of its breadcrumbs.
160
+ *
161
+ * Example #1: Then I should be on the "Questions" list
162
+ * Example #2: Then we should be on the "Users" list
163
+ * Example #3: And I should be on the "Tags" list
164
+ * Example #4: Then I should be on the "Categories" list
165
+ * Example #5: And we should be on the "Questions" list
166
+ */
167
+ Then(/^(I |we )*should be on the "([^"]*)" list$/, async function (pronounCase, model) {
168
+ const page = this.page;
169
+ const read = async () => ({
170
+ list: (await page.locator('body.change-list').count()) > 0,
171
+ crumb: clean(await page.locator('.breadcrumbs').first().evaluate((b) => {
172
+ const last = b.querySelector('[aria-current="page"]');
173
+ if (last) return last.textContent;
174
+ return (b.textContent.split('›').pop() || '');
175
+ }).catch(() => '')),
176
+ });
177
+ await eventually(this, read, (v) => v.list && normal(v.crumb) === normal(model), async (v) => ({
178
+ message: v.list ? `The page is the "${v.crumb}" list, not the "${model}" list.` : `The page is not a list of the admin: ${await pageSummary(this)}.`,
179
+ hint: hintFor(this, `Open it with: When I open the "${model}" list`),
180
+ }));
181
+ });
182
+
183
+ /**
184
+ * Assert that the recent actions of the admin index ("My actions") list (or
185
+ * do not list) an object; "as added", "as changed" or "as deleted" says what
186
+ * the account did with it.
187
+ *
188
+ * Example #1: Then my recent actions should list "Recent action question"
189
+ * Example #2: Then my recent actions should list "Recent action question" as added
190
+ * Example #3: And my recent actions should list "Recent action question" as deleted
191
+ * Example #4: Then my recent actions should not list "Recent action question"
192
+ * Example #5: And my recent actions should list "Recent action question" as changed
193
+ */
194
+ Then(/^my recent actions should( not)* list "([^"]*)"(?: as (added|changed|deleted))?$/, async function (notCase, object, kind) {
195
+ await onIndex(this);
196
+ const entries = await this.page.evaluate(() => [...document.querySelectorAll('#recent-actions-module ul.actionlist li')].map((li) => {
197
+ const kind = li.classList.contains('addlink') ? 'added' : li.classList.contains('deletelink') ? 'deleted' : li.classList.contains('changelink') ? 'changed' : '';
198
+ const hidden = li.querySelector('.visually-hidden');
199
+ const type = li.querySelector('.mini');
200
+ let text = li.textContent;
201
+ if (hidden) text = text.replace(hidden.textContent, '');
202
+ if (type) text = text.replace(type.textContent, '');
203
+ return { kind, object: text.replace(/\s+/g, ' ').trim() };
204
+ }));
205
+ const hit = entries.some((e) => normal(e.object) === normal(object) && (!kind || e.kind === kind));
206
+ if (hit === !!notCase) {
207
+ throw friendly({
208
+ message: notCase
209
+ ? `My recent actions list "${object}"${kind ? ` as ${kind}` : ''}.`
210
+ : `My recent actions do not list "${object}"${kind ? ` as ${kind}` : ''}. They list: ${listed(entries.map((e) => `${e.object} (${e.kind})`))}.`,
211
+ hint: 'The admin index lists the last ten actions of the account that is logged in, newest first.',
212
+ });
213
+ }
214
+ });
215
+
216
+ /**
217
+ * Assert the breadcrumbs of an admin page, from "Home" to the page: the
218
+ * crumbs separated by "›" (or ">").
219
+ *
220
+ * Example #1: Then the breadcrumbs should read "Home › Polls › Questions"
221
+ * Example #2: Then the breadcrumbs should read "Home › Polls › Questions › Add question"
222
+ * Example #3: And the breadcrumbs should read "Home > Authentication and Authorization > Users"
223
+ * Example #4: Then the breadcrumbs should read "Home › Polls"
224
+ * Example #5: And the breadcrumbs should read "Home › Change password"
225
+ */
226
+ Then(/^the breadcrumbs should read "([^"]*)"$/, async function (expected) {
227
+ const page = this.page;
228
+ const read = async () => page.locator('.breadcrumbs').first().evaluate((b) => {
229
+ const items = b.querySelectorAll('li');
230
+ if (items.length) return [...items].map((li) => li.textContent.replace(/\s+/g, ' ').trim());
231
+ return b.textContent.split('›').map((t) => t.replace(/\s+/g, ' ').trim());
232
+ }).catch(() => []);
233
+ const want = expected.split(/\s*[›>]\s*/).map(normal);
234
+ await eventually(this, read, (crumbs) => crumbs.length === want.length && crumbs.every((c, i) => normal(c) === want[i]),
235
+ async (crumbs) => ({ message: `The breadcrumbs read ${crumbs.length ? `"${crumbs.join(' › ')}"` : '(none)'}, not "${expected}": ${await pageSummary(this)}.`, hint: 'Write every crumb from "Home", separated by "›" or ">".' }), 3000);
236
+ });
237
+
238
+ /**
239
+ * Follow a crumb of the breadcrumbs, by its text.
240
+ *
241
+ * Example #1: When I follow "Polls" in the breadcrumbs
242
+ * Example #2: When I follow "Home" in the breadcrumbs
243
+ * Example #3: And we follow "Questions" in the breadcrumbs
244
+ * Example #4: When we follow "Authentication and Authorization" in the breadcrumbs
245
+ * Example #5: And I follow "Users" in the breadcrumbs
246
+ */
247
+ When(/^(I |we )*follow "([^"]*)" in the breadcrumbs$/, async function (pronounCase, crumb) {
248
+ const page = this.page;
249
+ const link = page.locator('.breadcrumbs a').filter({ hasText: new RegExp('^\\s*' + escapeRegExp(clean(crumb)) + '\\s*$') });
250
+ if (!(await link.count())) {
251
+ const crumbs = await page.locator('.breadcrumbs a').allTextContents().catch(() => []);
252
+ throw friendly({ message: `The breadcrumbs have no link "${crumb}". Their links: ${listed(crumbs)}.`, hint: 'The last crumb is the page itself and is no link.' });
253
+ }
254
+ await afterNavigation(this, () => link.first().click());
255
+ });
256
+
257
+ /**
258
+ * Filter the navigation sidebar of the admin's pages (the box "Start typing to
259
+ * filter…"): it shows only the models whose name has the text.
260
+ *
261
+ * Example #1: When I filter the navigation sidebar with "quest"
262
+ * Example #2: When we filter the navigation sidebar with "user"
263
+ * Example #3: And I filter the navigation sidebar with "Tag"
264
+ * Example #4: When I filter the navigation sidebar with ""
265
+ * Example #5: And we filter the navigation sidebar with "no such model"
266
+ */
267
+ When(/^(I |we )*filter the navigation sidebar with "([^"]*)"$/, async function (pronounCase, text) {
268
+ const page = this.page;
269
+ const box = page.locator('#nav-filter');
270
+ if (!(await box.count())) {
271
+ throw friendly({ message: `The page has no navigation sidebar: ${await pageSummary(this)}.`, hint: 'The admin draws the sidebar on its pages other than the index and the login page, when the site keeps it on (admin.site.enable_nav_sidebar).' });
272
+ }
273
+ await box.fill(text || '');
274
+ });
275
+
276
+ /**
277
+ * Assert that the navigation sidebar shows (or does not show) a model, by its
278
+ * plural name: after a filter, only the models whose name has the text show.
279
+ *
280
+ * Example #1: Then the navigation sidebar should show "Questions"
281
+ * Example #2: Then the navigation sidebar should not show "Tags"
282
+ * Example #3: And the navigation sidebar should show "Users"
283
+ * Example #4: Then the navigation sidebar should not show "Groups"
284
+ * Example #5: And the navigation sidebar should show "Categories"
285
+ */
286
+ Then(/^the navigation sidebar should( not)* show "([^"]*)"$/, async function (notCase, model) {
287
+ const page = this.page;
288
+ const read = () => page.evaluate(() => [...document.querySelectorAll('#nav-sidebar tr[class^="model-"], #nav-sidebar tr[class*=" model-"]')]
289
+ .filter((tr) => getComputedStyle(tr).display !== 'none')
290
+ .map((tr) => (tr.querySelector('th') || tr).textContent.replace(/\s+/g, ' ').trim())).catch(() => []);
291
+ await eventually(this, read, (shown) => shown.some((m) => normal(m) === normal(model)) === !notCase,
292
+ async (shown) => ({ message: notCase ? `The navigation sidebar shows "${model}".` : `The navigation sidebar does not show "${model}". It shows: ${listed(shown)}.`, hint: hintFor(this, 'The sidebar shows the models the account may see; its filter hides the others.') }), 3000);
293
+ });
294
+
295
+ /**
296
+ * Open the list of a model from the navigation sidebar, by its plural name.
297
+ *
298
+ * Example #1: When I open "Tags" from the navigation sidebar
299
+ * Example #2: When we open "Questions" from the navigation sidebar
300
+ * Example #3: And I open "Users" from the navigation sidebar
301
+ * Example #4: When I open "Categories" from the navigation sidebar
302
+ * Example #5: And we open "Groups" from the navigation sidebar
303
+ */
304
+ When(/^(I |we )*open "([^"]*)" from the navigation sidebar$/, async function (pronounCase, model) {
305
+ const page = this.page;
306
+ const link = page.locator('#nav-sidebar tr[class*="model-"] th a').filter({ hasText: new RegExp('^\\s*' + escapeRegExp(clean(model)) + '\\s*$', 'i') });
307
+ if (!(await link.count())) {
308
+ const shown = await page.locator('#nav-sidebar tr[class*="model-"] th').allTextContents().catch(() => []);
309
+ throw friendly({ message: `The navigation sidebar has no "${model}". It has: ${listed(shown)}.`, hint: hintFor(this, 'The sidebar is on the admin\'s pages other than the index.') });
310
+ }
311
+ await afterNavigation(this, () => link.first().click());
312
+ });
313
+
314
+ /**
315
+ * Switch the admin's colour theme with the theme button of its header, to
316
+ * "light", "dark" or "auto" (the browser's own choice). The admin keeps the
317
+ * choice for the next pages.
318
+ *
319
+ * Example #1: When I switch the admin theme to "dark"
320
+ * Example #2: When I switch the admin theme to "light"
321
+ * Example #3: And we switch the admin theme to "auto"
322
+ * Example #4: When we switch the admin theme to "dark"
323
+ * Example #5: And I switch the admin theme to "light"
324
+ */
325
+ When(/^(I |we )*switch the admin theme to "(light|dark|auto)"$/, async function (pronounCase, theme) {
326
+ const page = this.page;
327
+ const button = page.locator('#header button.theme-toggle, header button.theme-toggle').first();
328
+ if (!(await button.count())) {
329
+ throw friendly({ message: `The page has no theme button: ${await pageSummary(this)}.`, hint: 'The admin draws the theme button in its header on every page.' });
330
+ }
331
+ for (let i = 0; i < 3; i += 1) {
332
+ const now = await page.evaluate(() => document.documentElement.dataset.theme || 'auto');
333
+ if (now === theme) return;
334
+ await button.click();
335
+ }
336
+ const now = await page.evaluate(() => document.documentElement.dataset.theme || 'auto');
337
+ if (now !== theme) {
338
+ throw friendly({ message: `The theme button went round its three themes without "${theme}": the theme is "${now}".`, hint: 'The button cycles through auto, dark and light.' });
339
+ }
340
+ });
341
+
342
+ /**
343
+ * Assert the admin's colour theme: "light", "dark" or "auto".
344
+ *
345
+ * Example #1: Then the admin theme should be "dark"
346
+ * Example #2: Then the admin theme should be "light"
347
+ * Example #3: And the admin theme should be "auto"
348
+ * Example #4: Then the admin theme should be "auto"
349
+ * Example #5: And the admin theme should be "dark"
350
+ */
351
+ Then(/^the admin theme should be "(light|dark|auto)"$/, async function (theme) {
352
+ const page = this.page;
353
+ await eventually(this, () => page.evaluate(() => document.documentElement.dataset.theme || 'auto'), (now) => now === theme,
354
+ (now) => ({ message: `The admin theme is "${now}", not "${theme}".`, hint: 'Switch it with: When I switch the admin theme to "dark"' }), 3000);
355
+ });
356
+
357
+ /**
358
+ * Assert that the account that is logged in may (or may not) open an address
359
+ * of the site: a refused page answers 403 (or sends a visitor to the login
360
+ * page); an allowed one is the page itself.
361
+ *
362
+ * Example #1: Then I should not be allowed to open "/admin/auth/user/"
363
+ * Example #2: Then I should be allowed to open "/admin/polls/question/"
364
+ * Example #3: And we should not be allowed to open "/admin/polls/question/add/"
365
+ * Example #4: Then I should be allowed to open "/admin/"
366
+ * Example #5: And I should not be allowed to open "/admin/auth/group/"
367
+ */
368
+ Then(/^(I |we )*should( not)* be allowed to open "([^"]*)"$/, async function (pronounCase, notCase, path) {
369
+ const response = await open(this, absolute(this, path));
370
+ const status = response ? response.status() : 0;
371
+ const login = (await this.page.locator('#login-form').count()) > 0 && !String(path).match(/login/);
372
+ const allowed = status > 0 && status < 400 && !login;
373
+ if (allowed === !!notCase) {
374
+ throw friendly({
375
+ message: notCase
376
+ ? `The site opened "${path}" (HTTP ${status}): ${await pageSummary(this)}.`
377
+ : `The site refused "${path}" (HTTP ${status}${login ? ', the login page' : ''}): ${await pageSummary(this)}.`,
378
+ hint: hintFor(this, 'The admin answers 403 when the account lacks the permission, and sends a visitor to its login page.'),
379
+ });
380
+ }
381
+ });
382
+
383
+ module.exports = { indexModels, onIndex, budget };
@@ -0,0 +1,182 @@
1
+ 'use strict';
2
+
3
+ // Test data: a scenario makes the objects it needs, and the steps delete them
4
+ // after it, whatever happens in it. An object is made through the model's add
5
+ // form, as the data administrator of the users registry, in a browser page of
6
+ // its own (the scenario's session is never touched); an object is deleted
7
+ // through its delete page. The objects a scenario adds through the forms on
8
+ // screen are deleted after it too: the admin's message after an add links the
9
+ // new object.
10
+ //
11
+ // No step makes or deletes an account: accounts are configuration.
12
+
13
+ const { Given, Then, After, AfterAll, BeforeStep, AfterStep } = require('@cucumber/cucumber');
14
+ const { friendly } = require('webship-js/tests/step-definitions/webship');
15
+ const {
16
+ budget,
17
+ normal,
18
+ listed,
19
+ absolute,
20
+ withoutQuery,
21
+ adminReady,
22
+ modelListUrl,
23
+ dataClient,
24
+ dataAdminHandle,
25
+ findObjects,
26
+ deleteObject,
27
+ deleteObjectsNamed,
28
+ cleansUp,
29
+ afterScenario,
30
+ setField,
31
+ formErrors,
32
+ closeClients,
33
+ } = require('./django-helpers');
34
+
35
+ /** Delete the object at an address after the scenario. */
36
+ function deleteAfter(world, url) {
37
+ if (!cleansUp(world)) return;
38
+ afterScenario(world, `object:${withoutQuery(url)}`, async () => { await deleteObject(world, url); });
39
+ }
40
+
41
+ /** Delete the objects of a model with a text after the scenario. */
42
+ function deleteNamedAfter(world, model, text) {
43
+ if (!cleansUp(world)) return;
44
+ afterScenario(world, `named:${normal(model)}|${normal(text)}`, async () => { await deleteObjectsNamed(world, model, text); });
45
+ }
46
+
47
+ /**
48
+ * Make sure a model's list has no object with that text: delete it, as the
49
+ * data administrator, when it is there (a run stopped half way can leave
50
+ * one), and again after the scenario, whatever happens in it.
51
+ *
52
+ * Example #1: Given there is no "Data step question" in the "Questions" list
53
+ * Example #2: Given there is no "Reviewers" in the "Groups" list
54
+ * Example #3: And there is no "Delete test question" in the "Questions" list
55
+ * Example #4: Given there is no "Test tag" in the "Tags" list
56
+ * Example #5: And there is no "Inline test question" in the "Questions" list
57
+ */
58
+ Given(/^there is no "([^"]*)" in the "([^"]*)" list$/, { timeout: 120000 }, async function (object, model) {
59
+ if (normal(model) === 'users') {
60
+ throw friendly({ message: 'The steps never delete an account.', hint: 'Accounts are configuration: the build of the site makes them, and a suite never creates or deletes one.' });
61
+ }
62
+ await deleteObjectsNamed(this, model, object);
63
+ deleteNamedAfter(this, model, object);
64
+ });
65
+
66
+ /**
67
+ * Make an object through its model's add form, as the data administrator, in
68
+ * a browser page of its own, from a table of labels and values (see "I set
69
+ * "…" to "…"" for the values each kind of field takes). An object of that
70
+ * text that a stopped run left is deleted first; the new one is deleted after
71
+ * the scenario.
72
+ *
73
+ * Example #1: Given there is a "Data step question" in the "Questions" list with:
74
+ * Example #2: Given there is a "Test tag" in the "Tags" list with:
75
+ * Example #3: And there is a "History test question" in the "Questions" list with:
76
+ * Example #4: Given there is a "Reviewers" in the "Groups" list with:
77
+ * Example #5: And there is a "Delete test question" in the "Questions" list with:
78
+ */
79
+ Given(/^there is an? "([^"]*)" in the "([^"]*)" list with:$/, { timeout: 180000 }, async function (object, model, table) {
80
+ if (normal(model) === 'users') {
81
+ throw friendly({ message: 'The steps never create an account.', hint: 'Accounts are configuration: the build of the site makes them, and a suite never creates or deletes one.' });
82
+ }
83
+ await deleteObjectsNamed(this, model, object);
84
+ deleteNamedAfter(this, model, object);
85
+ const client = await dataClient(this);
86
+ const list = await modelListUrl(this, model);
87
+ const browser = this.playwrightBrowser;
88
+ if (!browser) throw friendly({ message: 'The browser of the scenario is not open.', hint: 'The test-data steps open a page of their own in the browser of the scenario.' });
89
+ const context = await browser.newContext({ ignoreHTTPSErrors: true, storageState: await client.context.storageState() });
90
+ try {
91
+ const page = await context.newPage();
92
+ const own = { page, minWaitTime: this.minWaitTime, parameters: this.parameters, launchUrl: this.launchUrl };
93
+ await page.goto(list + 'add/', { waitUntil: 'domcontentloaded' });
94
+ await adminReady(page, budget(this));
95
+ if (!(await page.locator('body.change-form').count())) {
96
+ throw friendly({ message: `The add form of "${model}" did not open for the data administrator (${page.url()}).`, hint: `worldParameters.dataAdmin ("${dataAdminHandle(this)}") must be a superuser.` });
97
+ }
98
+ const form = page.locator('#content-main form').first();
99
+ for (const [label, value] of table.raw()) await setField(own, form, label, value, `The add form of "${model}"`);
100
+ await Promise.all([
101
+ page.waitForNavigation({ timeout: budget(this), waitUntil: 'load' }).catch(() => {}),
102
+ page.locator('.submit-row [name="_save"]').first().click(),
103
+ ]);
104
+ const errors = await formErrors(page);
105
+ if (errors.length || (await page.locator('#content-main ul.errorlist li').count())) {
106
+ const fields = await page.locator('#content-main ul.errorlist li').allTextContents().catch(() => []);
107
+ throw friendly({ message: `The add form of "${model}" refused the test object "${object}": ${listed([...errors, ...fields])}.`, hint: 'Give the fields the form requires in the table of the step.' });
108
+ }
109
+ const link = page.locator('ul.messagelist li.success a').first();
110
+ if (await link.count()) deleteAfter(this, absolute(this, await link.getAttribute('href')));
111
+ } finally {
112
+ await context.close().catch(() => {});
113
+ }
114
+ const made = await findObjects(this, model, object);
115
+ if (!made.length) {
116
+ throw friendly({ message: `After the add form was saved, the "${model}" list has no "${object}".`, hint: 'The object\'s text in the list is what its model shows for it (its __str__): make the table give the field that text.' });
117
+ }
118
+ });
119
+
120
+ /**
121
+ * Assert, as the data administrator, that a model's list has (or has no)
122
+ * object with that text, whatever the account on screen may see.
123
+ *
124
+ * Example #1: Then there should be a "Data step question" in the "Questions" list
125
+ * Example #2: Then there should be no "Delete test question" in the "Questions" list
126
+ * Example #3: And there should be an "Inline test question" in the "Questions" list
127
+ * Example #4: Then there should be no "Reviewers" in the "Groups" list
128
+ * Example #5: And there should be a "Test tag" in the "Tags" list
129
+ */
130
+ Then(/^there should be (a|an|no) "([^"]*)" in the "([^"]*)" list$/, { timeout: 60000 }, async function (article, object, model) {
131
+ const urls = await findObjects(this, model, object);
132
+ const want = article !== 'no';
133
+ if ((urls.length > 0) !== want) {
134
+ throw friendly({ message: want ? `The "${model}" list has no "${object}".` : `The "${model}" list has "${object}" (${urls.length}).`, hint: 'The step searches the list as the data administrator.' });
135
+ }
136
+ // An object the scenario made through a form, that the step now sees, is deleted after it.
137
+ if (want) for (const url of urls) deleteAfter(this, url);
138
+ });
139
+
140
+ // ---------------------------------------------------------------------------
141
+ // The objects a scenario adds through the forms on screen
142
+ // ---------------------------------------------------------------------------
143
+
144
+ BeforeStep(function () {
145
+ if (this.page) {
146
+ try { this.__djangoBeforeUrl = this.page.url(); } catch { this.__djangoBeforeUrl = ''; }
147
+ }
148
+ });
149
+
150
+ AfterStep(async function () {
151
+ if (!this.page || !cleansUp(this)) return;
152
+ let before;
153
+ try { before = new URL(this.__djangoBeforeUrl || ''); } catch { return; }
154
+ // A save from an add form: the admin's success message links the new object.
155
+ if (!/\/add\/$/.test(before.pathname)) return;
156
+ const links = await this.page.locator('ul.messagelist li.success a[href]').evaluateAll((as) => as.map((a) => a.getAttribute('href'))).catch(() => []);
157
+ for (const href of links) {
158
+ if (/\/add\/?$/.test(withoutQuery(href))) continue;
159
+ deleteAfter(this, absolute(this, href));
160
+ }
161
+ });
162
+
163
+ After({ timeout: 180000 }, async function (scope) {
164
+ const todo = (this.__djangoCleanUp || []).slice().reverse();
165
+ this.__djangoCleanUp = [];
166
+ const failed = [];
167
+ for (const item of todo) {
168
+ try {
169
+ await item.fn();
170
+ } catch (err) {
171
+ failed.push(`${item.label}: ${String((err && err.message) || err).split('\n')[0]}`);
172
+ }
173
+ }
174
+ if (failed.length) {
175
+ const status = scope && scope.result && scope.result.status;
176
+ process.stderr.write(`\n[django-steps] The clean-up after "${scope && scope.pickle ? scope.pickle.name : 'the scenario'}" left: ${failed.join('; ')}${status ? ` (the scenario ${String(status).toLowerCase()})` : ''}\n`);
177
+ }
178
+ });
179
+
180
+ AfterAll(async function () {
181
+ await closeClients();
182
+ });