@webship-js/meilisearch-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,163 @@
1
+ 'use strict';
2
+
3
+ // The search engine's own dashboard (its mini-dashboard, served at / in development mode): opened with the master
4
+ // key (handed to the page in memory, never typed in a step's words), an index chosen, a search typed, its hits read,
5
+ // and the requests it sent. The dashboard logs a few errors of its own at known moments; each step allows only those of
6
+ // its own moment, and counts them in the report: every other browser error still fails the scenario.
7
+
8
+ const { Given, When, Then } = require('@cucumber/cucumber');
9
+ const { gotoUrl } = require('webship-js/tests/step-definitions/webship');
10
+ const h = require('./meilisearch-support');
11
+
12
+ // What the dashboard says when a search finds nothing: one line to change when its wording changes.
13
+ const NO_RESULTS = 'Sorry mate, no result';
14
+
15
+ // The dashboard's own errors before the key is entered: its first calls answered 401.
16
+ const BEFORE_THE_KEY = [
17
+ /^Failed to load resource: the server responded with a status of 401 \([^)]*\) @ [^ ]+\/(?:indexes|stats|version|multi-search)(?:[?:][^ ]*)?$/,
18
+ /^MeilisearchApiError: The Authorization header is missing\. It must use the bearer authorization method\./,
19
+ ];
20
+ // Before an index is chosen: its search of no index answered 400.
21
+ const BEFORE_THE_INDEX = [
22
+ /^Failed to load resource: the server responded with a status of 400 \([^)]*\) @ [^ ]+\/multi-search(?:[?:][^ ]*)?$/,
23
+ /^MeilisearchApiError: Invalid value at `\.queries\[0\]\.indexUid`: `` is not a valid index uid\./,
24
+ ];
25
+
26
+ /**
27
+ * Open the dashboard and give it the master key (in memory, never in the step's words), then wait until it lists the
28
+ * indexes. The errors it logs before the key is in are allowed here only.
29
+ *
30
+ * Example #1: Given I am on the search engine's dashboard with the master key
31
+ * Example #2: Given we are on the search engine's dashboard with the master key
32
+ * Example #3: And I am on the search engine's dashboard with the master key
33
+ * Example #4: When I am on the search engine's dashboard with the master key
34
+ * Example #5: * I am on the search engine's dashboard with the master key
35
+ *
36
+ */
37
+ Given(/^(?:I am|we are) on the search engine's dashboard with the master key$/, async function () {
38
+ const page = this.page;
39
+ const since = (this._jsErrors || []).length;
40
+ this.meiliDashboardSince = since;
41
+ await gotoUrl(page, `${h.base(this)}/`);
42
+ // (The page holds two such fields, one hidden: the visible one is the dialog's.)
43
+ const field = page.locator('input[name=apiKey]:visible').first();
44
+ try {
45
+ await field.waitFor({ timeout: h.WAIT.element });
46
+ } catch (e) {
47
+ throw h.failure(page, 'The search engine shows no dashboard at its address, or does not ask for a key.', {
48
+ hint: 'The dashboard is served in development mode (MEILI_ENV=development); production mode turns it off.',
49
+ });
50
+ }
51
+ await field.evaluate((input, key) => {
52
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set.call(input, key);
53
+ input.dispatchEvent(new Event('input', { bubbles: true }));
54
+ }, h.masterKey(this));
55
+ await page.getByRole('button', { name: 'Go', exact: true }).click();
56
+ try {
57
+ await page.getByRole('button', { name: /Select an index|\d+$/ }).first().waitFor({ timeout: h.WAIT.element });
58
+ await page.waitForFunction(() => !document.querySelector('[aria-label=ask-for-api-key]') || !document.querySelector('[aria-label=ask-for-api-key]').offsetParent, null, { timeout: h.WAIT.element });
59
+ } catch (e) {
60
+ throw h.failure(page, 'The search engine\'s dashboard did not take the master key.', { hint: 'Check worldParameters.meilisearch.masterKey (MEILISEARCH_MASTER_KEY): the key the server was started with.' });
61
+ }
62
+ await page.waitForTimeout(500);
63
+ h.allowErrors(this, since, BEFORE_THE_KEY, 'before the key');
64
+ });
65
+
66
+ /**
67
+ * Choose an index in the dashboard's index list; the dashboard then searches it. Its 400 for a search of no index,
68
+ * logged since the dashboard opened, is allowed here only.
69
+ *
70
+ * Example #1: When I choose the index "books" in the search engine's dashboard
71
+ * Example #2: When we choose the index "webship-books" in the search engine's dashboard
72
+ * Example #3: And I choose the index "movies" in the search engine's dashboard
73
+ * Example #4: Given I choose the index "books" in the search engine's dashboard
74
+ * Example #5: And we choose the index "products" in the search engine's dashboard
75
+ *
76
+ */
77
+ When(/^(?:I|we) choose the index "([^"]+)" in the search engine's dashboard$/, async function (uid) {
78
+ const page = this.page;
79
+ const since = this.meiliDashboardSince || 0;
80
+ await page.getByRole('button', { name: /Select an index|\S+\s*\d+$/ }).first().click();
81
+ const option = page.getByText(new RegExp(`^\\s*${uid.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*$`)).first();
82
+ if (!(await option.isVisible({ timeout: 0 }).catch(() => false)) && !(await option.waitFor({ timeout: h.WAIT.element }).then(() => true, () => false))) {
83
+ throw h.failure(page, `The search engine's dashboard lists no index "${uid}".`, { hint: 'Make it first: Given the search engine has the index "…" with the documents of "…"' });
84
+ }
85
+ await option.click();
86
+ await page.waitForTimeout(800);
87
+ h.allowErrors(this, since, BEFORE_THE_INDEX, 'before the index');
88
+ });
89
+
90
+ /**
91
+ * Type a search in the dashboard's search box, and wait for its answer.
92
+ *
93
+ * Example #1: When I search the search engine's dashboard for "lighthous"
94
+ * Example #2: When we search the search engine's dashboard for "garden"
95
+ * Example #3: And I search the search engine's dashboard for "zzzqqxx"
96
+ * Example #4: Given I search the search engine's dashboard for "harbour"
97
+ * Example #5: And we search the search engine's dashboard for "archive"
98
+ *
99
+ */
100
+ When(/^(?:I|we) search the search engine's dashboard for "([^"]*)"$/, async function (q) {
101
+ const page = this.page;
102
+ const box = page.getByPlaceholder('Search something');
103
+ await box.fill(q);
104
+ await page.waitForResponse((r) => /\/multi-search/.test(r.url()) && r.request().method() === 'POST', { timeout: h.WAIT.element }).catch(() => {});
105
+ await page.waitForTimeout(500);
106
+ });
107
+
108
+ /**
109
+ * The dashboard shows a hit with a title (or any field's value, as a whole).
110
+ *
111
+ * Example #1: Then the search engine's dashboard should show the hit "The Winter Lighthouse"
112
+ * Example #2: And the search engine's dashboard should show the hit "The Quiet Garden"
113
+ * Example #3: Then the search engine's dashboard should show the hit "The Copper Harbour"
114
+ * Example #4: And the search engine's dashboard should show the hit "The Paper Archive"
115
+ * Example #5: * the search engine's dashboard should show the hit "The Open Lighthouse"
116
+ *
117
+ */
118
+ Then(/^the search engine's dashboard should show the hit "([^"]+)"$/, async function (value) {
119
+ const page = this.page;
120
+ const hit = page.getByText(value, { exact: true }).first();
121
+ if (!(await hit.waitFor({ timeout: h.WAIT.element }).then(() => true, () => false))) {
122
+ const texts = (await page.locator('body').innerText()).replace(/\s+/g, ' ').slice(0, 200);
123
+ throw h.failure(page, `The search engine's dashboard shows no hit "${value}": ${texts}…`, { hint: 'Choose the index first, then search: When I choose the index "…" in the search engine\'s dashboard' });
124
+ }
125
+ });
126
+
127
+ /**
128
+ * The dashboard says its search found nothing.
129
+ *
130
+ * Example #1: Then the search engine's dashboard should show no results
131
+ * Example #2: And the search engine's dashboard should show no results
132
+ * Example #3: Then the search engine's dashboard should show no results
133
+ * Example #4: And the search engine's dashboard should show no results
134
+ * Example #5: * the search engine's dashboard should show no results
135
+ *
136
+ */
137
+ Then(/^the search engine's dashboard should show no results$/, async function () {
138
+ const page = this.page;
139
+ if (!(await page.getByText(NO_RESULTS).first().waitFor({ timeout: h.WAIT.element }).then(() => true, () => false))) {
140
+ throw h.failure(page, `The search engine's dashboard does not say it found nothing ("${NO_RESULTS}").`, { hint: 'Search for a text no document has.' });
141
+ }
142
+ });
143
+
144
+ /**
145
+ * Every request the page sent in the scenario went to the search engine's own address: nothing to another site (its
146
+ * links to a cloud service, a data export and a newsletter are never followed).
147
+ *
148
+ * Example #1: Then the search engine's dashboard should have sent no request outside its address
149
+ * Example #2: And the search engine's dashboard should have sent no request outside its address
150
+ * Example #3: Then the search engine's dashboard should have sent no request outside its address
151
+ * Example #4: And the search engine's dashboard should have sent no request outside its address
152
+ * Example #5: * the search engine's dashboard should have sent no request outside its address
153
+ *
154
+ */
155
+ Then(/^the search engine's dashboard should have sent no request outside its address$/, async function () {
156
+ const origin = new URL(h.base(this)).origin;
157
+ const outside = (this.meiliRequests || []).filter((u) => /^https?:/.test(u) && new URL(u).origin !== origin);
158
+ if (outside.length) {
159
+ throw h.failure(this.page, `The search engine's dashboard sent ${outside.length} request(s) outside ${origin}: ${[...new Set(outside.map((u) => new URL(u).origin))].join(', ')}.`, {
160
+ hint: 'A search is answered by the search engine itself; a request elsewhere is a link or an asset of another site.',
161
+ });
162
+ }
163
+ });
@@ -0,0 +1,213 @@
1
+ 'use strict';
2
+
3
+ // Indexes: made with the documents of a JSON file (deleted at the scenario's end), deleted, read, and their settings;
4
+ // and searches through the REST API: hits, filters, sort, facets and highlighting. Every write is a task of the search
5
+ // engine, waited for before anything is read.
6
+
7
+ const fs = require('fs');
8
+ const path = require('path');
9
+ const { Given, When, Then } = require('@cucumber/cucumber');
10
+ const h = require('./meilisearch-support');
11
+
12
+ /**
13
+ * The search engine has an index with the documents of a JSON file (an array of documents, its path from the project's
14
+ * root), made afresh and waited for; it is deleted at the scenario's end.
15
+ *
16
+ * Example #1: Given the search engine has the index "books" with the documents of "demo/books.json"
17
+ * Example #2: And the search engine has the index "webship-books" with the documents of "demo/books.json"
18
+ * Example #3: Given the search engine has the index "movies" with the documents of "tests/data/movies.json"
19
+ * Example #4: And the search engine has the index "products" with the documents of "fixtures/products.json"
20
+ * Example #5: * the search engine has the index "books" with the documents of "demo/books.json"
21
+ *
22
+ */
23
+ Given(/^the search engine has the index "([^"]+)" with the documents of "([^"]+)"$/, async function (uid, file) {
24
+ const where = path.resolve(process.cwd(), file);
25
+ if (!fs.existsSync(where)) {
26
+ throw h.friendly({ message: `There is no file ${file} (from ${process.cwd()}).`, hint: 'Name a JSON file of documents (an array), its path from the project\'s root.' });
27
+ }
28
+ let docs;
29
+ try { docs = JSON.parse(fs.readFileSync(where, 'utf8')); } catch (e) { throw h.friendly({ message: `${file} is not JSON: ${e.message}`, hint: 'The file is an array of documents.' }); }
30
+ if ((await h.api(this, 'GET', `/indexes/${encodeURIComponent(uid)}`)).status === 200) {
31
+ await h.waitTask(this, await h.api(this, 'DELETE', `/indexes/${encodeURIComponent(uid)}`), `deleting the index ${uid}`);
32
+ }
33
+ this.meiliIndexes.add(uid);
34
+ await h.waitTask(this, await h.api(this, 'POST', `/indexes/${encodeURIComponent(uid)}/documents`, { body: docs }), `adding ${docs.length} documents to ${uid}`);
35
+ });
36
+
37
+ /**
38
+ * Delete an index, and wait for its task.
39
+ *
40
+ * Example #1: When I delete the index "books" from the search engine
41
+ * Example #2: When we delete the index "webship-books" from the search engine
42
+ * Example #3: And I delete the index "movies" from the search engine
43
+ * Example #4: Given I delete the index "products" from the search engine
44
+ * Example #5: And we delete the index "books" from the search engine
45
+ *
46
+ */
47
+ When(/^(?:I|we) delete the index "([^"]+)" from the search engine$/, async function (uid) {
48
+ if ((await h.api(this, 'GET', `/indexes/${encodeURIComponent(uid)}`)).status !== 200) {
49
+ throw h.failure(this.page, `The search engine has no index "${uid}" to delete.`, { hint: 'Make it first: Given the search engine has the index "…" with the documents of "…"' });
50
+ }
51
+ await h.waitTask(this, await h.api(this, 'DELETE', `/indexes/${encodeURIComponent(uid)}`), `deleting the index ${uid}`);
52
+ });
53
+
54
+ /**
55
+ * The search engine has an index, with so many documents when said, or has not.
56
+ *
57
+ * Example #1: Then the search engine should have the index "books"
58
+ * Example #2: Then the search engine should have the index "books" with 50 documents
59
+ * Example #3: Then the search engine should not have the index "books"
60
+ * Example #4: And the search engine should have the index "movies" with 12 documents
61
+ * Example #5: * the search engine should not have the index "products"
62
+ *
63
+ */
64
+ Then(/^the search engine should (not )?have the index "([^"]+)"(?: with (\d+) documents)?$/, async function (not, uid, count) {
65
+ const a = await h.api(this, 'GET', `/indexes/${encodeURIComponent(uid)}/stats`);
66
+ if (not) {
67
+ if (a.status !== 404) throw h.failure(this.page, `The search engine still has the index "${uid}".`, { hint: 'Delete it first: When I delete the index "…" from the search engine' });
68
+ return;
69
+ }
70
+ if (a.status !== 200) throw h.failure(this.page, `The search engine has no index "${uid}" (it answered ${a.status}).`, { hint: 'Make it first: Given the search engine has the index "…" with the documents of "…"' });
71
+ if (count !== undefined && count !== null && a.body.numberOfDocuments !== Number(count)) {
72
+ throw h.failure(this.page, `The search engine's index "${uid}" has ${a.body.numberOfDocuments} documents, not ${count}.`, { hint: 'A write is a task: the step that made it waited for it.' });
73
+ }
74
+ });
75
+
76
+ /**
77
+ * An index's filterable, sortable or searchable attributes, set and waited for.
78
+ *
79
+ * Example #1: Given the search engine's index "books" has the filterable attributes "genre, year"
80
+ * Example #2: And the search engine's index "books" has the sortable attributes "year, rating"
81
+ * Example #3: Given the search engine's index "books" has the searchable attributes "title, blurb"
82
+ * Example #4: And the search engine's index "movies" has the filterable attributes "genre"
83
+ * Example #5: * the search engine's index "books" has the sortable attributes "pages"
84
+ *
85
+ */
86
+ Given(/^the search engine's index "([^"]+)" has the (filterable|sortable|searchable) attributes "([^"]+)"$/, async function (uid, kind, attrs) {
87
+ const key = `${kind}Attributes`;
88
+ await h.waitTask(this, await h.api(this, 'PATCH', `/indexes/${encodeURIComponent(uid)}/settings`, { body: { [key]: h.list(attrs) } }), `setting the ${kind} attributes of ${uid}`);
89
+ });
90
+
91
+ /**
92
+ * An index's synonyms: a word and the words it stands for (both ways when they say each other), set and waited for.
93
+ *
94
+ * Example #1: Given the search engine's index "books" has the synonyms "tale" for "story, fable"
95
+ * Example #2: And the search engine's index "books" has the synonyms "lantern" for "lamp"
96
+ * Example #3: Given the search engine's index "movies" has the synonyms "film" for "movie"
97
+ * Example #4: And the search engine's index "books" has the synonyms "harbour" for "harbor, port"
98
+ * Example #5: * the search engine's index "books" has the synonyms "kitchen" for "cookery"
99
+ *
100
+ */
101
+ Given(/^the search engine's index "([^"]+)" has the synonyms "([^"]+)" for "([^"]+)"$/, async function (uid, word, words) {
102
+ await h.waitTask(this, await h.api(this, 'PATCH', `/indexes/${encodeURIComponent(uid)}/settings`, { body: { synonyms: { [word]: h.list(words) } } }), `setting the synonyms of ${uid}`);
103
+ });
104
+
105
+ /**
106
+ * Search an index through the REST API: a query, with a filter, a sort and facets when said; every attribute
107
+ * highlighted. The answer is read by the next steps.
108
+ *
109
+ * Example #1: When I search the search engine's index "books" for "lighthouse"
110
+ * Example #2: When I search the search engine's index "books" for "harbour" filtered by "genre = mystery"
111
+ * Example #3: And I search the search engine's index "books" for "" sorted by "year:desc"
112
+ * Example #4: When I search the search engine's index "books" for "" with the facets "genre"
113
+ * Example #5: When we search the search engine's index "books" for "garden" filtered by "year > 2000" sorted by "rating:desc"
114
+ *
115
+ */
116
+ When(/^(?:I|we) search the search engine's index "([^"]+)" for "([^"]*)"(?: filtered by "([^"]+)")?(?: sorted by "([^"]+)")?(?: with the facets "([^"]+)")?$/, async function (uid, q, filter, sort, facets) {
117
+ const body = { q, attributesToHighlight: ['*'], limit: 100 };
118
+ if (filter) body.filter = filter;
119
+ if (sort) body.sort = h.list(sort);
120
+ if (facets) body.facets = h.list(facets);
121
+ const a = await h.api(this, 'POST', `/indexes/${encodeURIComponent(uid)}/search`, { body });
122
+ if (a.status !== 200) {
123
+ throw h.failure(this.page, `The search engine refused the search of "${uid}": ${a.status} ${(a.body && a.body.message) || ''}`, {
124
+ hint: 'A filter or a sort names attributes the index has as filterable or sortable: Given the search engine\'s index "…" has the filterable attributes "…"',
125
+ });
126
+ }
127
+ this.meiliSearch = a.body;
128
+ });
129
+
130
+ function searched(world) {
131
+ if (!world.meiliSearch) {
132
+ throw h.friendly({ message: 'No search of the search engine was made in this scenario.', hint: 'Search first: When I search the search engine\'s index "books" for "…"' });
133
+ }
134
+ return world.meiliSearch;
135
+ }
136
+
137
+ /**
138
+ * The last search found a document whose field has a value (as a whole), or found nothing, or so many documents.
139
+ *
140
+ * Example #1: Then the search engine should find "The Winter Lighthouse" in its "title"
141
+ * Example #2: Then the search engine should find nothing
142
+ * Example #3: Then the search engine should find 4 documents
143
+ * Example #4: And the search engine should find "mystery" in its "genre"
144
+ * Example #5: * the search engine should find 50 documents
145
+ *
146
+ */
147
+ Then(/^the search engine should find (?:"([^"]+)" in its "([^"]+)"|nothing|(\d+) documents?)$/, async function (value, field, count) {
148
+ const s = searched(this);
149
+ const hits = s.hits || [];
150
+ const total = s.estimatedTotalHits !== undefined ? s.estimatedTotalHits : s.totalHits;
151
+ if (value !== undefined && value !== null) {
152
+ if (!hits.some((d) => String(d[field]) === value)) {
153
+ throw h.failure(this.page, `The search engine did not find "${value}" in "${field}": it found ${hits.slice(0, 5).map((d) => `"${d[field]}"`).join(', ') || 'nothing'}.`, { hint: 'A search is typo-tolerant but reads only the searchable attributes; check the query and the filter.' });
154
+ }
155
+ return;
156
+ }
157
+ const want = count !== undefined && count !== null ? Number(count) : 0;
158
+ if (total !== want) {
159
+ throw h.failure(this.page, `The search engine found ${total} documents, not ${want === 0 ? 'none' : want}.`, { hint: 'estimatedTotalHits counts every document the query and filter match.' });
160
+ }
161
+ });
162
+
163
+ /**
164
+ * The first hit of the last search, by a field's value in order: the sort read from the hits.
165
+ *
166
+ * Example #1: Then the search engine's first hit should have "2026" in its "year"
167
+ * Example #2: And the search engine's first hit should have "5" in its "rating"
168
+ * Example #3: Then the search engine's first hit should have "The Winter Lighthouse" in its "title"
169
+ * Example #4: And the search engine's first hit should have "mystery" in its "genre"
170
+ * Example #5: * the search engine's first hit should have "1990" in its "year"
171
+ *
172
+ */
173
+ Then(/^the search engine's first hit should have "([^"]+)" in its "([^"]+)"$/, async function (value, field) {
174
+ const first = (searched(this).hits || [])[0];
175
+ if (!first || String(first[field]) !== value) {
176
+ throw h.failure(this.page, `The search engine's first hit has ${first ? `"${first[field]}"` : 'nothing'} in "${field}", not "${value}".`, { hint: 'A sort names a sortable attribute and a direction: sorted by "year:desc".' });
177
+ }
178
+ });
179
+
180
+ /**
181
+ * The facets of the last search count so many documents for a value.
182
+ *
183
+ * Example #1: Then the search engine's facet "genre" should count 7 for "mystery"
184
+ * Example #2: And the search engine's facet "genre" should count 3 for "poetry"
185
+ * Example #3: Then the search engine's facet "year" should count 2 for "2001"
186
+ * Example #4: And the search engine's facet "genre" should count 0 for "opera"
187
+ * Example #5: * the search engine's facet "genre" should count 5 for "travel"
188
+ *
189
+ */
190
+ Then(/^the search engine's facet "([^"]+)" should count (\d+) for "([^"]+)"$/, async function (facet, count, value) {
191
+ const dist = (searched(this).facetDistribution || {})[facet];
192
+ if (!dist) throw h.failure(this.page, `The last search counted no facet "${facet}".`, { hint: 'Ask for it: When I search the search engine\'s index "…" for "" with the facets "…"; the attribute must be filterable.' });
193
+ const got = dist[value] || 0;
194
+ if (got !== Number(count)) throw h.failure(this.page, `The search engine's facet "${facet}" counts ${got} for "${value}", not ${count}.`, { hint: 'A facet counts the documents the query and the filter match.' });
195
+ });
196
+
197
+ /**
198
+ * The last search highlighted a text in a field of a hit (<em>…</em> in its _formatted copy).
199
+ *
200
+ * Example #1: Then the search engine should highlight "Lighthouse" in its "title"
201
+ * Example #2: And the search engine should highlight "garden" in its "blurb"
202
+ * Example #3: Then the search engine should highlight "Harbour" in its "title"
203
+ * Example #4: And the search engine should highlight "mystery" in its "genre"
204
+ * Example #5: * the search engine should highlight "Archive" in its "title"
205
+ *
206
+ */
207
+ Then(/^the search engine should highlight "([^"]+)" in its "([^"]+)"$/, async function (text, field) {
208
+ const hits = searched(this).hits || [];
209
+ const mark = `<em>${text}</em>`;
210
+ if (!hits.some((d) => d._formatted && String(d._formatted[field] || '').includes(mark))) {
211
+ throw h.failure(this.page, `The search engine did not highlight "${text}" in "${field}".`, { hint: 'A highlight wraps the matched words of the query in <em>; the text is the word as the document has it.' });
212
+ }
213
+ });
@@ -0,0 +1,122 @@
1
+ 'use strict';
2
+
3
+ // API keys and the server: a key made with limited actions and indexes (its value kept in memory, never shown, the key
4
+ // deleted at the scenario's end), requests sent with it, with the master key or with none, the answer's status and
5
+ // error code, and the server's health and version.
6
+
7
+ const { Given, When, Then } = require('@cucumber/cucumber');
8
+ const h = require('./meilisearch-support');
9
+
10
+ /**
11
+ * The search engine has a key that may only do some actions on some indexes, made with the master key; its value is
12
+ * kept in memory for the scenario and never shown, and the key is deleted at the scenario's end.
13
+ *
14
+ * Example #1: Given the search engine has a key "reader" that may only "search" on "books"
15
+ * Example #2: And the search engine has a key "writer" that may only "documents.add, documents.delete" on "books"
16
+ * Example #3: Given the search engine has a key "stats" that may only "stats.get" on "*"
17
+ * Example #4: And the search engine has a key "movies-reader" that may only "search" on "movies"
18
+ * Example #5: * the search engine has a key "reader" that may only "search, documents.get" on "books, movies"
19
+ *
20
+ */
21
+ Given(/^the search engine has a key "([^"]+)" that may only "([^"]+)" on "([^"]+)"$/, async function (name, actions, indexes) {
22
+ const a = await h.api(this, 'POST', '/keys', { body: { name: `webship ${name}`, actions: h.list(actions), indexes: h.list(indexes), expiresAt: null } });
23
+ if (a.status !== 201 || !a.body || !a.body.key) {
24
+ throw h.failure(this.page, `The search engine did not make the key "${name}": ${a.status} ${(a.body && a.body.message) || ''}`, {
25
+ hint: 'A key\'s actions are the search engine\'s own names: search, documents.add, indexes.create, stats.get, … ("*" for all).',
26
+ });
27
+ }
28
+ this.meiliKeys[name] = { uid: a.body.uid, key: a.body.key };
29
+ });
30
+
31
+ /** A body of a step, as JSON; for a search with none, an empty query. */
32
+ function bodyOf(method, where, raw) {
33
+ if (raw !== undefined && raw !== null) {
34
+ try { return JSON.parse(raw.replace(/\\"/g, '"')); } catch (e) { throw h.friendly({ message: `The body is not JSON: ${raw}`, hint: 'Write it as JSON, its quotes escaped: and the body "{\\"q\\": \\"garden\\"}"' }); }
35
+ }
36
+ return method === 'POST' && /\/search$/.test(where) ? { q: '' } : undefined;
37
+ }
38
+
39
+ /**
40
+ * Send the search engine a request with a key the scenario made (by its name); the answer is read by the next step. A
41
+ * body, when given, is JSON.
42
+ *
43
+ * Example #1: When I send the search engine "POST /indexes/books/search" with the key "reader"
44
+ * Example #2: When I send the search engine "DELETE /indexes/books" with the key "reader"
45
+ * Example #3: When we send the search engine "GET /stats" with the key "stats"
46
+ * Example #4: And I send the search engine "POST /indexes/books/documents" with the key "reader" and the body "[]"
47
+ * Example #5: When I send the search engine "POST /indexes/books/search" with the key "reader" and the body "{\"q\": \"garden\"}"
48
+ *
49
+ */
50
+ When(/^(?:I|we) send the search engine "(GET|POST|PUT|PATCH|DELETE) (\/[^"]*)" with the key "([^"]+)"(?: and the body "((?:[^"\\]|\\.)*)")?$/, async function (method, where, name, raw) {
51
+ await h.api(this, method, where, { body: bodyOf(method, where, raw), key: name });
52
+ });
53
+
54
+ /**
55
+ * Send the search engine a request with its master key, or with no key at all; the answer is read by the next step.
56
+ *
57
+ * Example #1: When I send the search engine "GET /indexes" without a key
58
+ * Example #2: When I send the search engine "GET /stats" with the master key
59
+ * Example #3: And we send the search engine "GET /keys" without a key
60
+ * Example #4: When I send the search engine "POST /indexes/books/search" without a key
61
+ * Example #5: When we send the search engine "GET /version" with the master key
62
+ *
63
+ */
64
+ When(/^(?:I|we) send the search engine "(GET|POST|PUT|PATCH|DELETE) (\/[^"]*)" (with the master key|without a key)$/, async function (method, where, how) {
65
+ await h.api(this, method, where, { body: bodyOf(method, where), key: how === 'without a key' ? null : undefined });
66
+ });
67
+
68
+ /**
69
+ * The last answer of the search engine: its status, and its error code when said.
70
+ *
71
+ * Example #1: Then the search engine should answer 401 "missing_authorization_header"
72
+ * Example #2: Then the search engine should answer 403 "invalid_api_key"
73
+ * Example #3: Then the search engine should answer 200
74
+ * Example #4: And the search engine should answer 202
75
+ * Example #5: * the search engine should answer 404 "index_not_found"
76
+ *
77
+ */
78
+ Then(/^the search engine should answer (\d{3})(?: "([^"]+)")?$/, async function (status, code) {
79
+ const a = this.meiliAnswer;
80
+ if (!a) throw h.friendly({ message: 'No request was sent to the search engine in this scenario.', hint: 'Send one first: When I send the search engine "GET /indexes" without a key' });
81
+ const got = a.body && typeof a.body === 'object' ? a.body.code : undefined;
82
+ if (a.status !== Number(status) || (code && got !== code)) {
83
+ throw h.failure(this.page, `The search engine answered ${a.method} ${a.path} with ${a.status}${got ? ` "${got}"` : ''}, not ${status}${code ? ` "${code}"` : ''}.`, {
84
+ hint: 'Without a key it answers 401 "missing_authorization_header"; with a key outside its rights, 403 "invalid_api_key".',
85
+ });
86
+ }
87
+ });
88
+
89
+ /**
90
+ * The search engine answers its health check: available.
91
+ *
92
+ * Example #1: Then the search engine should be available
93
+ * Example #2: And the search engine should be available
94
+ * Example #3: Given the search engine should be available
95
+ * Example #4: Then the search engine should be available
96
+ * Example #5: * the search engine should be available
97
+ *
98
+ */
99
+ Then(/^the search engine should be available$/, async function () {
100
+ const a = await h.api(this, 'GET', '/health', { key: null });
101
+ if (a.status !== 200 || !a.body || a.body.status !== 'available') {
102
+ throw h.failure(this.page, `The search engine's health check answered ${a.status} ${h.hide(this, JSON.stringify(a.body)).slice(0, 100)}.`, { hint: 'Check that it is up at the launch URL.' });
103
+ }
104
+ });
105
+
106
+ /**
107
+ * The search engine's version starts with a line ("1.59" or "1.59.0").
108
+ *
109
+ * Example #1: Then the search engine's version should be "1.59"
110
+ * Example #2: And the search engine's version should be "1.55.1"
111
+ * Example #3: Then the search engine's version should be "1"
112
+ * Example #4: And the search engine's version should be "1.59.0"
113
+ * Example #5: * the search engine's version should be "1.55"
114
+ *
115
+ */
116
+ Then(/^the search engine's version should be "([^"]+)"$/, async function (line) {
117
+ const a = await h.api(this, 'GET', '/version');
118
+ const v = a.body && a.body.pkgVersion;
119
+ if (!v || !(v === line || v.startsWith(`${line}.`))) {
120
+ throw h.failure(this.page, `The search engine's version is ${v || 'unknown'}, not ${line}.`, { hint: 'GET /version answers pkgVersion; LINE picks the demo\'s line.' });
121
+ }
122
+ });