webship-js 2.0.10 → 2.0.12

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.
Files changed (248) hide show
  1. package/.circleci/config.yml +10 -1
  2. package/.drone.yml +7 -7
  3. package/.github/ISSUE_TEMPLATE/issue.md +37 -0
  4. package/.github/PULL_REQUEST_TEMPLATE.md +24 -0
  5. package/.github/workflows/github-actions.yml +101 -4
  6. package/.gitlab-ci.yml +9 -4
  7. package/.harness/webship-js-pipeline.yml +5 -6
  8. package/.semaphore/semaphore.yml +6 -9
  9. package/.teamcity/settings.kts +7 -6
  10. package/.travis.yml +6 -1
  11. package/AGENTS.md +1 -1
  12. package/CLAUDE.md +69 -24
  13. package/Jenkinsfile +5 -3
  14. package/README.md +13 -1
  15. package/azure-pipelines.yml +17 -8
  16. package/bamboo-specs/bamboo.yml +9 -15
  17. package/bin/generate-reports.js +51 -7
  18. package/bin/init-webship.js +127 -23
  19. package/bitbucket-pipelines.yml +5 -1
  20. package/buildspec.yml +6 -7
  21. package/cloudbuild.yaml +28 -12
  22. package/codefresh.yml +6 -6
  23. package/cucumber.js +46 -11
  24. package/docs/00-quick-start.md +38 -7
  25. package/docs/02-bbr-smart-waits.md +21 -10
  26. package/docs/03-selector-registry.md +24 -0
  27. package/docs/04-step-reference.md +53 -27
  28. package/docs/05-web-first-assertions.md +6 -0
  29. package/docs/07-auth-state.md +1 -1
  30. package/docs/08-clock-mocking.md +21 -2
  31. package/docs/09-api-testing.md +40 -2
  32. package/docs/10-accessibility.md +2 -0
  33. package/docs/11-debugging.md +24 -1
  34. package/docs/12-ai-agent-guide.md +8 -1
  35. package/docs/13-faq.md +75 -1
  36. package/docs/14-recipes-cookbook.md +2 -0
  37. package/docs/15-tag-conventions.md +5 -1
  38. package/docs/16-ci-cd.md +161 -124
  39. package/docs/README.md +5 -5
  40. package/docs/advanced-screenshots.md +3 -1
  41. package/docs/api-step-definitions.md +16 -2
  42. package/docs/global-settings.md +70 -18
  43. package/docs/install-webship-js/ddev-webship-js.md +3 -0
  44. package/docs/install-webship-js.md +16 -2
  45. package/docs/step-definitions/then-i-should-see.md +14 -1
  46. package/docs/step-definitions/then-item-checkbox.md +2 -0
  47. package/docs/step-definitions/when-i-fill.md +4 -0
  48. package/docs/step-definitions/when-i-select-option-select-list.md +2 -0
  49. package/examples/a11y-legacy-widget.html +34 -0
  50. package/examples/auth-state.html +42 -0
  51. package/examples/choice-controls.html +29 -0
  52. package/examples/clock.html +33 -0
  53. package/examples/datetime-fields.html +52 -0
  54. package/examples/downloads/webship-archive.zip +0 -0
  55. package/examples/downloads/webship-notes.txt +4 -0
  56. package/examples/downloads/webship-report.csv +4 -0
  57. package/examples/downloads.html +16 -0
  58. package/examples/element-selector-hint.html +16 -0
  59. package/examples/element-viewport.html +42 -0
  60. package/examples/field-states.html +27 -0
  61. package/examples/field-types.html +98 -0
  62. package/examples/fill-in-empty.html +26 -0
  63. package/examples/fill-unreachable.html +27 -0
  64. package/examples/iframe-inner.html +20 -0
  65. package/examples/iframe-nested.html +16 -0
  66. package/examples/iframe-newsletter.html +29 -0
  67. package/examples/iframe-order.html +26 -0
  68. package/examples/iframe-outer.html +15 -0
  69. package/examples/iframe.html +21 -0
  70. package/examples/javascript-errors.html +35 -0
  71. package/examples/links.html +1 -0
  72. package/examples/metatags.html +18 -0
  73. package/examples/mouse-and-pointer.html +83 -0
  74. package/examples/multi-value-fields.html +54 -0
  75. package/examples/native-dialogs.html +8 -0
  76. package/examples/network.html +83 -0
  77. package/examples/registered-names.html +15 -0
  78. package/examples/scroll-horizontal.html +50 -0
  79. package/examples/select-by-label.html +33 -0
  80. package/examples/selectors-position.html +29 -0
  81. package/examples/settle-budget.html +21 -0
  82. package/examples/sorted-tables.html +38 -0
  83. package/examples/storage.html +57 -0
  84. package/examples/text-matching.html +48 -0
  85. package/examples/text-order.html +25 -0
  86. package/examples/touch.html +22 -0
  87. package/examples/viewport-size.html +24 -0
  88. package/examples/viewport-top.html +36 -0
  89. package/examples/wait-conditions.html +69 -0
  90. package/examples/web-first.html +99 -0
  91. package/package.json +24 -2
  92. package/playwright.config.ts +3 -1
  93. package/tests/assets/catalog.xml +19 -0
  94. package/tests/assets/feed-namespaced.xml +13 -0
  95. package/tests/assets/sitemap.xml +14 -0
  96. package/tests/assets/webship-site-expected.yaml +21 -0
  97. package/tests/assets/webship-site.schema.json +46 -0
  98. package/tests/assets/webship-site.yaml +21 -0
  99. package/tests/check-api-launch-url.js +106 -0
  100. package/tests/check-assets.js +103 -0
  101. package/tests/check-attachments.js +105 -0
  102. package/tests/check-breakpoints.js +117 -0
  103. package/tests/check-clock.js +143 -0
  104. package/tests/check-config.js +90 -0
  105. package/tests/check-context.js +215 -0
  106. package/tests/check-dry-run.js +104 -0
  107. package/tests/check-examples.js +241 -0
  108. package/tests/check-exit-report.js +141 -0
  109. package/tests/check-javascript-errors.js +105 -0
  110. package/tests/check-must-fail.js +85 -0
  111. package/tests/check-paths.js +82 -0
  112. package/tests/check-report.js +119 -0
  113. package/tests/check-scaffold.js +246 -0
  114. package/tests/check-screenshots.js +117 -0
  115. package/tests/check-settle-verbs.js +137 -0
  116. package/tests/check-time-limit.js +104 -0
  117. package/tests/check-video.js +156 -0
  118. package/tests/check-world.js +167 -0
  119. package/tests/features/a11y.feature +18 -0
  120. package/tests/features/api-base-url.feature +25 -0
  121. package/tests/features/api-form-data.feature +18 -0
  122. package/tests/features/api-json-paths.feature +24 -0
  123. package/tests/features/api-response-contains.feature +21 -0
  124. package/tests/features/api-response-header-presence.feature +17 -0
  125. package/tests/features/api-response-header.feature +17 -0
  126. package/tests/features/api-saved-placeholders.feature +37 -0
  127. package/tests/features/api-step-definitions-individual.feature +1 -1
  128. package/tests/features/api-tables.feature +40 -0
  129. package/tests/features/auth-state.feature +32 -0
  130. package/tests/features/breakpoints.feature +25 -0
  131. package/tests/features/choice-controls.feature +35 -0
  132. package/tests/features/clock.feature +27 -0
  133. package/tests/features/complete-api-testing-examples.feature +1 -1
  134. package/tests/features/cookie.feature +9 -0
  135. package/tests/features/datetime-field-lookup.feature +29 -0
  136. package/tests/features/dialog.feature +27 -0
  137. package/tests/features/element-selector-hint.feature +14 -0
  138. package/tests/features/element.feature +47 -0
  139. package/tests/features/field-state.feature +21 -0
  140. package/tests/features/field.feature +104 -0
  141. package/tests/features/file-download.feature +64 -0
  142. package/tests/features/fill-in-empty-value.feature +41 -0
  143. package/tests/features/fill-reachable.feature +13 -0
  144. package/tests/features/iframe-nested.feature +43 -0
  145. package/tests/features/iframe.feature +83 -0
  146. package/tests/features/javascript-tolerated-errors.feature +20 -0
  147. package/tests/features/javascript.feature +47 -0
  148. package/tests/features/link.feature +11 -0
  149. package/tests/features/metatag.feature +38 -0
  150. package/tests/features/modal-open.feature +13 -0
  151. package/tests/features/mouse-and-pointer.feature +86 -0
  152. package/tests/features/multi-value-field-lookup.feature +30 -0
  153. package/tests/features/network-mocking.feature +80 -0
  154. package/tests/features/registered-names.feature +14 -0
  155. package/tests/features/responsive.feature +27 -0
  156. package/tests/features/scroll-horizontal.feature +55 -0
  157. package/tests/features/select-by-label.feature +31 -0
  158. package/tests/features/selector-files.feature +14 -0
  159. package/tests/features/selectors-position.feature +41 -0
  160. package/tests/features/selectors-table-header.feature +35 -0
  161. package/tests/features/settle-budget.feature +11 -0
  162. package/tests/features/sorted-tables.feature +19 -0
  163. package/tests/features/storage-quoted-values.feature +26 -0
  164. package/tests/features/storage.feature +98 -0
  165. package/tests/features/test--then--i-see-locator.feature +13 -0
  166. package/tests/features/test--then--i-should--see-text-in-element.feature +9 -1
  167. package/tests/features/test--then--the-field-should-contain-value.feature +8 -0
  168. package/tests/features/text-matching.feature +38 -0
  169. package/tests/features/text-order.feature +14 -0
  170. package/tests/features/touch.feature +21 -0
  171. package/tests/features/video.feature +1 -0
  172. package/tests/features/viewport-top.feature +13 -0
  173. package/tests/features/wait.feature +89 -0
  174. package/tests/features/web-first.feature +100 -0
  175. package/tests/features/xml-namespaces.feature +34 -0
  176. package/tests/features/xml.feature +96 -0
  177. package/tests/features/yaml.feature +75 -0
  178. package/tests/must-fail/api-json-paths.feature +21 -0
  179. package/tests/must-fail/api-response-contains.feature +23 -0
  180. package/tests/must-fail/api-response-header-presence.feature +17 -0
  181. package/tests/must-fail/api-response-header.feature +21 -0
  182. package/tests/must-fail/api-without-base-url.feature +11 -0
  183. package/tests/must-fail/assertions.feature +96 -0
  184. package/tests/must-fail/breakpoints.feature +15 -0
  185. package/tests/must-fail/choice-controls.feature +25 -0
  186. package/tests/must-fail/clock.feature +11 -0
  187. package/tests/must-fail/datetime-field.feature +10 -0
  188. package/tests/must-fail/element-selector-hint.feature +17 -0
  189. package/tests/must-fail/field-state.feature +20 -0
  190. package/tests/must-fail/fill-field.feature +30 -0
  191. package/tests/must-fail/iframe-text.feature +17 -0
  192. package/tests/must-fail/modal-open.feature +26 -0
  193. package/tests/must-fail/multi-value-field.feature +18 -0
  194. package/tests/must-fail/registered-names.feature +25 -0
  195. package/tests/must-fail/select-list.feature +15 -0
  196. package/tests/must-fail/selector-files.feature +10 -0
  197. package/tests/must-fail/sorted-tables.feature +20 -0
  198. package/tests/must-fail/storage-before-a-page.feature +13 -0
  199. package/tests/must-fail/text-matching.feature +16 -0
  200. package/tests/must-fail/text-order.feature +15 -0
  201. package/tests/must-fail/viewport-top.feature +20 -0
  202. package/tests/must-fail/waits.feature +51 -0
  203. package/tests/must-fail/yaml-numbers.feature +48 -0
  204. package/tests/reports/README.md +2 -2
  205. package/tests/step-definitions/a11y.steps.js +36 -23
  206. package/tests/step-definitions/action.steps.js +22 -8
  207. package/tests/step-definitions/api.steps.js +349 -67
  208. package/tests/step-definitions/assertion.steps.js +327 -63
  209. package/tests/step-definitions/auth.steps.js +15 -18
  210. package/tests/step-definitions/clock.steps.js +22 -0
  211. package/tests/step-definitions/debug.steps.js +8 -0
  212. package/tests/step-definitions/dialog.steps.js +9 -2
  213. package/tests/step-definitions/element.steps.js +135 -18
  214. package/tests/step-definitions/field.steps.js +523 -80
  215. package/tests/step-definitions/file-download.steps.js +74 -10
  216. package/tests/step-definitions/form.steps.js +76 -29
  217. package/tests/step-definitions/iframe.steps.js +89 -29
  218. package/tests/step-definitions/input.steps.js +26 -7
  219. package/tests/step-definitions/javascript.steps.js +64 -22
  220. package/tests/step-definitions/modal.steps.js +79 -13
  221. package/tests/step-definitions/navigation.steps.js +14 -0
  222. package/tests/step-definitions/network.steps.js +15 -5
  223. package/tests/step-definitions/response.steps.js +6 -4
  224. package/tests/step-definitions/responsive.steps.js +26 -33
  225. package/tests/step-definitions/screenshot.steps.js +26 -9
  226. package/tests/step-definitions/scroll.steps.js +20 -0
  227. package/tests/step-definitions/selectors.steps.js +104 -51
  228. package/tests/step-definitions/storage.steps.js +41 -16
  229. package/tests/step-definitions/table.steps.js +81 -6
  230. package/tests/step-definitions/video.steps.js +52 -55
  231. package/tests/step-definitions/wait.steps.js +209 -54
  232. package/tests/step-definitions/web-first.steps.js +69 -35
  233. package/tests/step-definitions/webship.js +807 -128
  234. package/tests/step-definitions/xml.steps.js +124 -28
  235. package/tests/step-definitions/yaml.steps.js +90 -46
  236. package/.scratch/commit.txt +0 -14
  237. package/.scratch/docs.py +0 -42
  238. package/.scratch/echo-server.js +0 -8
  239. package/.scratch/echo.js +0 -35
  240. package/.scratch/echo.pid +0 -1
  241. package/.scratch/features/cookies.feature +0 -22
  242. package/.scratch/http.pid +0 -1
  243. package/.scratch/https.pid +0 -1
  244. package/.scratch/issue.md +0 -49
  245. package/.scratch/one.js +0 -2
  246. package/.scratch/one.json +0 -280
  247. package/.scratch/patch.py +0 -163
  248. package/.scratch/pr.md +0 -30
@@ -1,13 +1,17 @@
1
1
  'use strict';
2
2
 
3
- const { friendly } = require('./webship');
3
+ const { friendly, resolveAssetFile } = require('./webship');
4
4
 
5
5
  // Parse and assert against an XML response loaded from a file or doc string.
6
+ //
7
+ // The XPath of a step reads like the XML does: a prefixed name such as
8
+ // //dc:creator resolves against the xmlns:dc="..." declarations of the
9
+ // document, and a name without a prefix such as /urlset/url also matches an
10
+ // element of the default namespace (xmlns="..."), as in a sitemap or a feed.
6
11
 
7
12
  const { Given, Then, When } = require('@cucumber/cucumber');
8
13
  const assert = require('assert');
9
14
  const fs = require('fs');
10
- const path = require('path');
11
15
 
12
16
  let DOMParser;
13
17
  try { ({ DOMParser } = require('@xmldom/xmldom')); }
@@ -16,18 +20,80 @@ catch (e) {
16
20
  catch (e2) { /* will throw on use */ }
17
21
  }
18
22
 
19
- function ensureXml(world) {
23
+ function requireParser() {
20
24
  if (!DOMParser) throw friendly('XML steps require an XML DOM parser. Install @xmldom/xmldom.');
25
+ }
26
+
27
+ function ensureXml(world) {
28
+ requireParser();
29
+ if (world._xmlParseError) throw friendly(`The response is not valid XML: ${world._xmlParseError}`);
21
30
  if (!world._xml) throw friendly('No XML response has been set.');
22
31
  return world._xml;
23
32
  }
24
33
 
34
+ // Parse without throwing and without printing: returns the document, or the
35
+ // reason the content is not well-formed XML.
36
+ function parseXml(content) {
37
+ requireParser();
38
+ const problems = [];
39
+ let doc = null;
40
+ try {
41
+ doc = new DOMParser({
42
+ onError: (level, message) => { if (level !== 'warning') problems.push(String(message).trim()); },
43
+ }).parseFromString(String(content), 'text/xml');
44
+ } catch (e) {
45
+ if (problems.length === 0) problems.push(e.message);
46
+ }
47
+ if (problems.length === 0 && (!doc || !doc.documentElement)) problems.push('missing root element');
48
+ return problems.length ? { doc: null, error: problems[0] } : { doc, error: null };
49
+ }
50
+
51
+ // Keep the raw content even when it is not XML, so that the two format steps
52
+ // ("should be" / "should not be in XML format") can judge it.
53
+ function setXmlResponse(world, content) {
54
+ const { doc, error } = parseXml(content);
55
+ world._rawResponse = content;
56
+ world._xml = doc;
57
+ world._xmlParseError = error;
58
+ }
59
+
60
+ // Every prefix the document declares (xmlns:dc="..."), wherever it is declared.
61
+ function declaredNamespaces(doc) {
62
+ const map = {};
63
+ const walk = (el) => {
64
+ for (const a of Array.from(el.attributes || [])) {
65
+ if (a.name.indexOf('xmlns:') === 0 && !(a.name.slice(6) in map)) map[a.name.slice(6)] = a.value;
66
+ }
67
+ for (const c of Array.from(el.childNodes || [])) if (c.nodeType === 1) walk(c);
68
+ };
69
+ if (doc && doc.documentElement) walk(doc.documentElement);
70
+ return map;
71
+ }
72
+
25
73
  function evalXPath(doc, xpath) {
26
74
  // Minimal XPath: support /a/b and /a/b[@attr] and /a/b/text()
27
75
  // For richer XPath, users can install xpath module.
28
76
  let xpathLib;
29
77
  try { xpathLib = require('xpath'); } catch (e) { xpathLib = null; }
30
- if (xpathLib) return xpathLib.select(xpath, doc);
78
+ if (xpathLib) {
79
+ // The XPath reads like the XML does: a prefixed name (//dc:creator)
80
+ // resolves against the prefixes the document itself declares, and a name
81
+ // without a prefix (/urlset/url) also matches an element of the default
82
+ // namespace (xmlns="..."), which every sitemap and Atom feed declares.
83
+ try {
84
+ return xpathLib.parse(xpath).select({
85
+ node: doc,
86
+ namespaces: declaredNamespaces(doc),
87
+ allowAnyNamespaceForNoPrefix: true,
88
+ });
89
+ } catch (e) {
90
+ throw friendly({
91
+ action: `evaluate the XPath "${xpath}"`,
92
+ cause: e,
93
+ hint: 'check the XPath syntax; a prefix (dc:creator) must be declared in the XML with xmlns:dc="...".',
94
+ });
95
+ }
96
+ }
31
97
  // Fallback simple traversal
32
98
  const parts = xpath.split('/').filter(Boolean);
33
99
  let nodes = [doc.documentElement].filter((n) => n && n.nodeName === parts[0]);
@@ -43,7 +109,8 @@ function evalXPath(doc, xpath) {
43
109
  }
44
110
 
45
111
  /**
46
- * Load XML response content from a file under `tests/assets/`.
112
+ * Load XML response content from a file under `tests/assets/` of the project,
113
+ * or from a path from the project root.
47
114
  *
48
115
  * Example #1: Given the response content from the file "feed.xml"
49
116
  * Example #2: Given the response content from the file "rss.xml"
@@ -53,10 +120,7 @@ function evalXPath(doc, xpath) {
53
120
  *
54
121
  */
55
122
  Given('the response content from the file {string}', async function (filename) {
56
- const p = path.isAbsolute(filename) ? filename : path.join(this.assetsFolder || './tests/assets', filename);
57
- const content = fs.readFileSync(p, 'utf-8');
58
- this._rawResponse = content;
59
- this._xml = new DOMParser().parseFromString(content, 'text/xml');
123
+ setXmlResponse(this, fs.readFileSync(resolveAssetFile(this, filename), 'utf-8'));
60
124
  });
61
125
 
62
126
  /**
@@ -85,8 +149,7 @@ Given('the response content from the file {string}', async function (filename) {
85
149
  *
86
150
  */
87
151
  Given('the response content is the following:', async function (docString) {
88
- this._rawResponse = docString;
89
- this._xml = new DOMParser().parseFromString(docString, 'text/xml');
152
+ setXmlResponse(this, docString);
90
153
  });
91
154
 
92
155
  /**
@@ -107,8 +170,8 @@ Given('the response content is the following:', async function (docString) {
107
170
  */
108
171
  Then('the response should be in XML format', async function () {
109
172
  assert.ok(this._rawResponse, 'No response content set.');
110
- const doc = new DOMParser().parseFromString(this._rawResponse, 'text/xml');
111
- assert.ok(doc && doc.documentElement, 'Response is not valid XML.');
173
+ const { error } = parseXml(this._rawResponse);
174
+ assert.ok(!error, `Response is not valid XML: ${error}`);
112
175
  });
113
176
 
114
177
  /**
@@ -131,11 +194,9 @@ Then('the response should be in XML format', async function () {
131
194
  *
132
195
  */
133
196
  Then('the response should not be in XML format', async function () {
134
- if (!this._rawResponse) return;
135
- try {
136
- const doc = new DOMParser().parseFromString(this._rawResponse, 'text/xml');
137
- assert.ok(!doc || !doc.documentElement || doc.getElementsByTagName('parsererror').length > 0, 'Response is XML.');
138
- } catch (e) { /* good */ }
197
+ assert.ok(this._rawResponse, 'No response content set.');
198
+ const { error } = parseXml(this._rawResponse);
199
+ assert.ok(error, 'Response is valid XML.');
139
200
  });
140
201
 
141
202
  /**
@@ -357,8 +418,34 @@ Then('the XML element {string} should have {int} element(s)', async function (xp
357
418
  assert.strictEqual((nodes || []).length, count);
358
419
  });
359
420
 
421
+ // Every namespace an XML document uses: each one an element declares
422
+ // (xmlns="..." or xmlns:p="..."), wherever it is declared, and the namespace
423
+ // of every element and attribute. Other attributes are values, not namespaces.
424
+ function usedNamespaces(doc) {
425
+ const found = new Set();
426
+ const walk = (el) => {
427
+ if (el.namespaceURI) found.add(el.namespaceURI);
428
+ for (const a of Array.from(el.attributes || [])) {
429
+ if (a.name === 'xmlns' || a.name.indexOf('xmlns:') === 0) {
430
+ if (a.value) found.add(a.value);
431
+ } else if (a.namespaceURI) {
432
+ found.add(a.namespaceURI);
433
+ }
434
+ }
435
+ for (const c of Array.from(el.childNodes || [])) if (c.nodeType === 1) walk(c);
436
+ };
437
+ if (doc && doc.documentElement) walk(doc.documentElement);
438
+ return found;
439
+ }
440
+
441
+ function listNamespaces(found) {
442
+ return found.size ? Array.from(found).map((ns) => `"${ns}"`).join(', ') : 'no namespace';
443
+ }
444
+
360
445
  /**
361
- * Assert the XML root declares an `xmlns:*` namespace URI.
446
+ * Assert the XML document uses a namespace: an element declares it
447
+ * (`xmlns="..."` or `xmlns:p="..."`) anywhere in the document, or an element
448
+ * or an attribute is in it.
362
449
  *
363
450
  * Example #1: Then the XML should use the namespace "http://www.w3.org/2005/Atom"
364
451
  * Example #2: Then the XML should use the namespace "http://www.sitemaps.org/schemas/sitemap/0.9"
@@ -368,14 +455,19 @@ Then('the XML element {string} should have {int} element(s)', async function (xp
368
455
  *
369
456
  */
370
457
  Then('the XML should use the namespace {string}', async function (ns) {
371
- const doc = ensureXml(this);
372
- const root = doc.documentElement;
373
- const found = Array.from(root.attributes || []).some((a) => a.value === ns);
374
- assert.ok(found, `Namespace "${ns}" not declared.`);
458
+ const found = usedNamespaces(ensureXml(this));
459
+ if (!found.has(ns)) {
460
+ throw friendly(
461
+ `The XML does not use the namespace "${ns}".\n` +
462
+ ` Found: ${listNamespaces(found)}\n` +
463
+ ' Hint: the step reads every xmlns declaration of the document, and the namespace of every element and attribute; the URI must match exactly.'
464
+ );
465
+ }
375
466
  });
376
467
 
377
468
  /**
378
- * Assert the XML root does NOT declare a namespace URI.
469
+ * Assert the XML document does NOT use a namespace: no element declares it
470
+ * and no element or attribute is in it.
379
471
  *
380
472
  * Example #1: Then the XML should not use the namespace "http://example.com/legacy"
381
473
  * Example #2: Then the XML should not use the namespace "http://example.com/internal"
@@ -385,10 +477,14 @@ Then('the XML should use the namespace {string}', async function (ns) {
385
477
  *
386
478
  */
387
479
  Then('the XML should not use the namespace {string}', async function (ns) {
388
- const doc = ensureXml(this);
389
- const root = doc.documentElement;
390
- const found = Array.from(root.attributes || []).some((a) => a.value === ns);
391
- assert.ok(!found, `Namespace "${ns}" should not be declared.`);
480
+ const found = usedNamespaces(ensureXml(this));
481
+ if (found.has(ns)) {
482
+ throw friendly(
483
+ `The XML uses the namespace "${ns}", but it should not.\n` +
484
+ ` Found: ${listNamespaces(found)}\n` +
485
+ ' Hint: the step reads every xmlns declaration of the document, and the namespace of every element and attribute.'
486
+ );
487
+ }
392
488
  });
393
489
 
394
490
  /**
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- const { friendly } = require('./webship');
3
+ const { friendly, failure, resolveAssetFile } = require('./webship');
4
4
 
5
5
  // Parse and assert against YAML response bodies.
6
6
  //
@@ -17,7 +17,6 @@ const { friendly } = require('./webship');
17
17
  const { Given, Then, When } = require('@cucumber/cucumber');
18
18
  const assert = require('assert');
19
19
  const fs = require('fs');
20
- const path = require('path');
21
20
 
22
21
  let YAML; try { YAML = require('js-yaml'); } catch { /* lazy */ }
23
22
  let Ajv; let addFormats;
@@ -31,10 +30,30 @@ function requireYaml() {
31
30
 
32
31
  function ensureLoaded(world) {
33
32
  requireYaml();
33
+ if (world._yamlParseError) {
34
+ throw friendly(`The response is not valid YAML: ${world._yamlParseError.message}`);
35
+ }
34
36
  if (world._yaml === undefined) throw friendly('No YAML response has been set.');
35
37
  return world._yaml;
36
38
  }
37
39
 
40
+ // Keep the raw content even when it does not parse, so that the two format
41
+ // steps ("should be" / "should not be in YAML format") can judge it.
42
+ function setYamlResponse(world, content) {
43
+ requireYaml();
44
+ world._rawYamlResponse = content;
45
+ world._yamlDocIndex = 0;
46
+ world._yamlParseError = null;
47
+ try {
48
+ world._yamlDocs = YAML.loadAll(content);
49
+ world._yaml = world._yamlDocs[0];
50
+ } catch (e) {
51
+ world._yamlDocs = [];
52
+ world._yaml = undefined;
53
+ world._yamlParseError = e;
54
+ }
55
+ }
56
+
38
57
  // Active document index for multi-document streams.
39
58
  function activeIndex(world) { return world._yamlDocIndex || 0; }
40
59
  function activeDoc(world) {
@@ -103,7 +122,8 @@ function typeOfNode(node) {
103
122
  // ---------------------------------------------------------------------------
104
123
 
105
124
  /**
106
- * Load YAML response content from a file under `tests/assets/`.
125
+ * Load YAML response content from a file under `tests/assets/` of the
126
+ * project, or from a path from the project root.
107
127
  *
108
128
  * Multi-document streams (`---`) are parsed via `loadAll`. The first document
109
129
  * becomes the default; switch with `Given the active YAML document is N`.
@@ -117,12 +137,7 @@ function typeOfNode(node) {
117
137
  */
118
138
  Given('the YAML response content from the file {string}', async function (filename) {
119
139
  requireYaml();
120
- const p = path.isAbsolute(filename) ? filename : path.join(this.assetsFolder || './tests/assets', filename);
121
- const content = fs.readFileSync(p, 'utf-8');
122
- this._rawYamlResponse = content;
123
- this._yamlDocs = YAML.loadAll(content);
124
- this._yaml = this._yamlDocs[0];
125
- this._yamlDocIndex = 0;
140
+ setYamlResponse(this, fs.readFileSync(resolveAssetFile(this, filename), 'utf-8'));
126
141
  });
127
142
 
128
143
  /**
@@ -162,11 +177,7 @@ Given('the YAML response content from the file {string}', async function (filena
162
177
  *
163
178
  */
164
179
  Given('the YAML response content is the following:', async function (docString) {
165
- requireYaml();
166
- this._rawYamlResponse = docString;
167
- this._yamlDocs = YAML.loadAll(docString);
168
- this._yaml = this._yamlDocs[0];
169
- this._yamlDocIndex = 0;
180
+ setYamlResponse(this, docString);
170
181
  });
171
182
 
172
183
  /**
@@ -236,12 +247,13 @@ Then('the response should be in YAML format', async function () {
236
247
  });
237
248
 
238
249
  /**
239
- * Assert the loaded response is NOT valid YAML.
250
+ * Assert the loaded response is NOT valid YAML. Fails when the content
251
+ * parses: a line of plain text or a JSON document is valid YAML too.
240
252
  *
241
253
  * Example #1: Then the response should not be in YAML format
242
254
  * Example #2: Given the YAML response content is the following:
243
255
  * """
244
- * <not> yaml </not>
256
+ * items: [one, two
245
257
  * """
246
258
  * Then the response should not be in YAML format
247
259
  * Example #3: And the response should not be in YAML format
@@ -255,9 +267,11 @@ Then('the response should be in YAML format', async function () {
255
267
  *
256
268
  */
257
269
  Then('the response should not be in YAML format', async function () {
258
- if (!this._rawYamlResponse || !YAML) return;
270
+ requireYaml();
271
+ assert.ok(this._rawYamlResponse, 'No YAML response content set.');
259
272
  try { YAML.loadAll(this._rawYamlResponse); }
260
273
  catch (e) { return; /* expected */ }
274
+ assert.fail('Response is valid YAML.');
261
275
  });
262
276
 
263
277
  /**
@@ -581,17 +595,41 @@ Then('the YAML value at {string} should not be empty', function (p) {
581
595
  // Numeric comparisons
582
596
  // ---------------------------------------------------------------------------
583
597
 
584
- function numAt(doc, p) {
598
+ // What a YAML value is, in the words of a failure message.
599
+ function describeValue(v) {
600
+ if (v === null || v === undefined) return 'null';
601
+ if (typeof v === 'string') return `the string "${v}"`;
602
+ if (typeof v === 'boolean') return `the boolean ${v}`;
603
+ if (Array.isArray(v)) return 'a list';
604
+ if (typeof v === 'object') return 'a mapping';
605
+ return String(v);
606
+ }
607
+
608
+ // The number at a path. Only a YAML number compares: a quoted "3", true or
609
+ // null is not one, whatever Number() would make of it.
610
+ function numAt(world, doc, p) {
585
611
  const nodes = evalPath(doc, p);
586
612
  if (nodes.length === 0) throw friendly(`YAML element "${p}" not found.`);
587
613
  const v = nodes[0];
588
- const n = typeof v === 'number' ? v : Number(v);
589
- if (!Number.isFinite(n)) throw friendly(`YAML value at "${p}" is not numeric: ${v}`);
590
- return n;
614
+ if (typeof v !== 'number' || !Number.isFinite(v)) {
615
+ throw failure(world.page, `The YAML value at "${p}" is ${describeValue(v)}, not ${typeof v === 'number' ? 'a finite number' : 'a number'}.`, {
616
+ hint: 'a number compares only with a YAML number: write it without quotes (replicas: 3, not replicas: "3").',
617
+ });
618
+ }
619
+ return v;
591
620
  }
592
621
 
622
+ // Fail a comparison that does not hold, with the value and the words of the step.
623
+ function expectNumber(world, p, v, holds, words, hint) {
624
+ if (!holds) throw failure(world.page, `The YAML value at "${p}" is ${v}, not ${words}.`, { hint });
625
+ }
626
+
627
+ const ABOVE_HINT = '"greater than" leaves the number itself out; "greater than or equal to" lets it in.';
628
+ const BELOW_HINT = '"less than" leaves the number itself out; "less than or equal to" lets it in.';
629
+
593
630
  /**
594
- * Assert a numeric YAML node is greater than a value.
631
+ * Assert a numeric YAML node is greater than a value. Only a YAML number
632
+ * compares: a quoted "3", true or null fails, as in every numeric step below.
595
633
  *
596
634
  * Example #1: Then the YAML value at "/spec/replicas" should be greater than 0
597
635
  * Example #2: Then the YAML value at "/timeout" should be greater than 5
@@ -602,7 +640,8 @@ function numAt(doc, p) {
602
640
  */
603
641
  Then('the YAML value at {string} should be greater than {float}', function (p, n) {
604
642
  const doc = activeDoc(this); ensureLoaded(this);
605
- assert.ok(numAt(doc, p) > n);
643
+ const v = numAt(this, doc, p);
644
+ expectNumber(this, p, v, v > n, `greater than ${n}`, ABOVE_HINT);
606
645
  });
607
646
 
608
647
  /**
@@ -617,7 +656,8 @@ Then('the YAML value at {string} should be greater than {float}', function (p, n
617
656
  */
618
657
  Then('the YAML value at {string} should be greater than or equal to {float}', function (p, n) {
619
658
  const doc = activeDoc(this); ensureLoaded(this);
620
- assert.ok(numAt(doc, p) >= n);
659
+ const v = numAt(this, doc, p);
660
+ expectNumber(this, p, v, v >= n, `greater than or equal to ${n}`, ABOVE_HINT);
621
661
  });
622
662
 
623
663
  /**
@@ -632,7 +672,8 @@ Then('the YAML value at {string} should be greater than or equal to {float}', fu
632
672
  */
633
673
  Then('the YAML value at {string} should be less than {float}', function (p, n) {
634
674
  const doc = activeDoc(this); ensureLoaded(this);
635
- assert.ok(numAt(doc, p) < n);
675
+ const v = numAt(this, doc, p);
676
+ expectNumber(this, p, v, v < n, `less than ${n}`, BELOW_HINT);
636
677
  });
637
678
 
638
679
  /**
@@ -647,7 +688,8 @@ Then('the YAML value at {string} should be less than {float}', function (p, n) {
647
688
  */
648
689
  Then('the YAML value at {string} should be less than or equal to {float}', function (p, n) {
649
690
  const doc = activeDoc(this); ensureLoaded(this);
650
- assert.ok(numAt(doc, p) <= n);
691
+ const v = numAt(this, doc, p);
692
+ expectNumber(this, p, v, v <= n, `less than or equal to ${n}`, BELOW_HINT);
651
693
  });
652
694
 
653
695
  /**
@@ -662,8 +704,8 @@ Then('the YAML value at {string} should be less than or equal to {float}', funct
662
704
  */
663
705
  Then('the YAML value at {string} should be between {float} and {float}', function (p, lo, hi) {
664
706
  const doc = activeDoc(this); ensureLoaded(this);
665
- const v = numAt(doc, p);
666
- assert.ok(v >= lo && v <= hi, `Value ${v} not in [${lo}, ${hi}].`);
707
+ const v = numAt(this, doc, p);
708
+ expectNumber(this, p, v, v >= lo && v <= hi, `between ${lo} and ${hi}`, '"between" includes both ends of the range.');
667
709
  });
668
710
 
669
711
  // ---------------------------------------------------------------------------
@@ -800,8 +842,7 @@ Then('the YAML at {string} should have keys {string}', function (p, csv) {
800
842
  Then('the YAML should match JSON Schema {string}', function (schemaFile) {
801
843
  if (!Ajv) throw friendly('Schema validation requires ajv. Install with: npm i ajv ajv-formats');
802
844
  const doc = activeDoc(this); ensureLoaded(this);
803
- const p = path.isAbsolute(schemaFile) ? schemaFile : path.join(this.assetsFolder || './tests/assets', schemaFile);
804
- const schema = JSON.parse(fs.readFileSync(p, 'utf-8'));
845
+ const schema = JSON.parse(fs.readFileSync(resolveAssetFile(this, schemaFile), 'utf-8'));
805
846
  const ajv = new Ajv({ allErrors: true, strict: false });
806
847
  if (addFormats) addFormats(ajv);
807
848
  const validate = ajv.compile(schema);
@@ -829,8 +870,7 @@ Then('the YAML should match JSON Schema {string}', function (schemaFile) {
829
870
  Then('the YAML should equal the file {string} ignoring keys {string}', function (file, ignoreCsv) {
830
871
  requireYaml();
831
872
  const doc = activeDoc(this); ensureLoaded(this);
832
- const p = path.isAbsolute(file) ? file : path.join(this.assetsFolder || './tests/assets', file);
833
- const expected = YAML.load(fs.readFileSync(p, 'utf-8'));
873
+ const expected = YAML.load(fs.readFileSync(resolveAssetFile(this, file), 'utf-8'));
834
874
  const ignore = ignoreCsv.split(',').map((s) => s.trim()).filter(Boolean);
835
875
  const stripAt = (root, ptr) => {
836
876
  const parts = ptr.split('/').filter(Boolean);
@@ -853,6 +893,17 @@ Then('the YAML should equal the file {string} ignoring keys {string}', function
853
893
  // Namespace + debug
854
894
  // ---------------------------------------------------------------------------
855
895
 
896
+ // One answer for both namespace steps: a top-level value equal to the
897
+ // namespace, or the namespace anywhere in the raw text.
898
+ function usesNamespace(world, ns) {
899
+ const doc = activeDoc(world);
900
+ if (doc && typeof doc === 'object') {
901
+ const values = Object.values(doc).map((v) => (v == null ? '' : String(v)));
902
+ if (values.includes(ns)) return true;
903
+ }
904
+ return (world._rawYamlResponse || '').indexOf(ns) !== -1;
905
+ }
906
+
856
907
  /**
857
908
  * Assert the YAML document declares a namespace value (mirrors xml.steps.js).
858
909
  * Checks top-level scalar values and falls back to a raw-text scan.
@@ -865,16 +916,14 @@ Then('the YAML should equal the file {string} ignoring keys {string}', function
865
916
  *
866
917
  */
867
918
  Then('the YAML should use the namespace {string}', function (ns) {
868
- const doc = activeDoc(this); ensureLoaded(this);
869
- if (doc && typeof doc === 'object') {
870
- const values = Object.values(doc).map((v) => (v == null ? '' : String(v)));
871
- if (values.includes(ns)) return;
872
- }
873
- assert.ok((this._rawYamlResponse || '').indexOf(ns) !== -1, `Namespace "${ns}" not declared.`);
919
+ ensureLoaded(this);
920
+ assert.ok(usesNamespace(this, ns), `Namespace "${ns}" not declared.`);
874
921
  });
875
922
 
876
923
  /**
877
- * Assert the YAML document does NOT declare a namespace value.
924
+ * Assert the YAML document does NOT declare a namespace value: the exact
925
+ * opposite of the step above (no top-level value equal to it, and the raw
926
+ * text does not carry it).
878
927
  *
879
928
  * Example #1: Then the YAML should not use the namespace "v0"
880
929
  * Example #2: Then the YAML should not use the namespace "internal/v1"
@@ -884,13 +933,8 @@ Then('the YAML should use the namespace {string}', function (ns) {
884
933
  *
885
934
  */
886
935
  Then('the YAML should not use the namespace {string}', function (ns) {
887
- const doc = activeDoc(this); ensureLoaded(this);
888
- if (doc && typeof doc === 'object') {
889
- const values = Object.values(doc).map((v) => (v == null ? '' : String(v)));
890
- assert.ok(!values.includes(ns), `Namespace "${ns}" should not be declared.`);
891
- return;
892
- }
893
- assert.ok((this._rawYamlResponse || '').indexOf(ns) === -1, `Namespace "${ns}" should not be declared.`);
936
+ ensureLoaded(this);
937
+ assert.ok(!usesNamespace(this, ns), `Namespace "${ns}" should not be declared.`);
894
938
  });
895
939
 
896
940
  /**
@@ -1,14 +0,0 @@
1
- Fix: send the REST and API requests with the HTTPS setting of the browser (#333)
2
-
3
- The REST and API request steps sent their request from Node with axios,
4
- outside the browser, so on HTTPS with a self-signed or locally issued
5
- certificate they failed with "self-signed certificate" although the
6
- browser itself opened the site.
7
-
8
- Both now use Playwright's request API. The REST steps go through the
9
- browser context and follow its cookies, credentials and HTTPS setting.
10
- The API steps keep their own base URL, authentication and headers: they
11
- use a request context of their own, with the HTTPS setting of the browser
12
- context and no cookie of the browser.
13
-
14
- Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
package/.scratch/docs.py DELETED
@@ -1,42 +0,0 @@
1
- p='docs/09-api-testing.md'
2
- s=open(p).read()
3
- old="Webship-js scenarios can talk to an HTTP API directly without leaving the cucumber-js runtime. The browser context's cookie jar is shared, so a UI login can be followed by REST-level assertions in the same scenario.\n"
4
- new="""Webship-js scenarios can talk to an HTTP API directly without leaving the cucumber-js runtime. Every request is sent with Playwright's request API and follows the HTTPS setting of the browser context (`ignoreHTTPSErrors` in `playwright.config.ts`), so a site served with a self-signed or locally issued certificate answers these steps the same way it answers the browser.
5
-
6
- There are two families of steps, and they differ in one point:
7
-
8
- | Steps | Sent | Cookies of the browser |
9
- | --- | --- | --- |
10
- | `I send a REST "<method>" request to "<url>"` (`rest.steps.js`) | through the browser context | shared: a UI login can be followed by REST-level assertions in the same scenario |
11
- | `I send a <METHOD> request to "<endpoint>"` (`api.steps.js`) | outside the browser session | not sent, and none comes back into the browser: the request carries only the base URL, the authentication and the headers the scenario set |
12
- """
13
- assert old in s; s=s.replace(old,new)
14
- old="A parallel short-form lives in `rest.steps.js` for quick smoke tests:\n"
15
- new="A parallel short-form lives in `rest.steps.js` for quick smoke tests. A path is joined to the launch URL, an absolute URL is requested as written, and the request goes through the browser context: it shares the session cookies and the HTTPS setting of the page.\n"
16
- assert old in s; s=s.replace(old,new)
17
- open(p,'w').write(s)
18
- p='docs/api-step-definitions.md'
19
- s=open(p).read()
20
- old="""webship-js ships native HTTP / REST API step definitions powered by
21
- Playwright's request fixture and `axios`. They share the browser
22
- context's cookie jar so the same scenario can mix UI actions and
23
- direct API calls.
24
- """
25
- new="""webship-js ships native HTTP / REST API step definitions powered by
26
- Playwright's request API, so the same scenario can mix UI actions and
27
- direct API calls.
28
-
29
- The API steps on this page send their requests outside the browser
30
- session: a request carries the base URL, the authentication and the
31
- headers the scenario set, and no cookie of the browser. They follow the
32
- HTTPS setting of the browser context (`ignoreHTTPSErrors` in
33
- `playwright.config.ts`), so an API served with a self-signed or locally
34
- issued certificate answers them the same way it answers the browser.
35
-
36
- To send a request with the cookies of the browser session, after a UI
37
- login for example, use the short-form REST steps
38
- (`When I send a REST "GET" request to "/api/me"`), which go through the
39
- browser context.
40
- """
41
- assert old in s; s=s.replace(old,new)
42
- open(p,'w').write(s)
@@ -1,8 +0,0 @@
1
- const http = require('http');
2
- http.createServer((req, res) => {
3
- let b = ''; req.on('data', c => b += c); req.on('end', () => {
4
- res.setHeader('content-type', 'application/json');
5
- res.setHeader('set-cookie', 'from_api=1; Path=/');
6
- res.end(JSON.stringify({ method: req.method, cookie: req.headers.cookie || 'none', auth: req.headers.authorization || 'none', type: req.headers['content-type'] || 'none', body: b }));
7
- });
8
- }).listen(8990);
package/.scratch/echo.js DELETED
@@ -1,35 +0,0 @@
1
- const http = require('http');
2
- const axios = require('axios');
3
- const { request } = require('playwright');
4
- const srv = http.createServer((req, res) => {
5
- let b = ''; req.on('data', c => b += c); req.on('end', () => {
6
- res.setHeader('content-type', 'application/json');
7
- res.end(JSON.stringify({ m: req.method, h: req.headers, b }));
8
- });
9
- }).listen(0, async () => {
10
- const u = `http://localhost:${srv.address().port}/x`;
11
- const cases = [
12
- ['GET nodata', { method: 'GET', url: u, headers: {}, data: null }],
13
- ['GET undefined', { method: 'GET', url: u, headers: {} }],
14
- ['GET obj', { method: 'GET', url: u, headers: {}, data: { a: 1 } }],
15
- ['POST null', { method: 'POST', url: u, headers: {}, data: null }],
16
- ['POST obj', { method: 'POST', url: u, headers: {}, data: { a: 1 } }],
17
- ['POST str json', { method: 'POST', url: u, headers: {}, data: '{"a": 1}' }],
18
- ['POST str json ct', { method: 'POST', url: u, headers: { 'Content-Type': 'application/json' }, data: '{"a":1}' }],
19
- ['POST str form', { method: 'POST', url: u, headers: {}, data: 'a=1&b=2' }],
20
- ['POST str ct json nonjson', { method: 'POST', url: u, headers: { 'Content-Type': 'application/json' }, data: JSON.stringify({a:'1'}) }],
21
- ['DELETE', { method: 'DELETE', url: u, headers: {} }],
22
- ['post lowercase', { method: 'post', url: u, headers: {}, data: 'x' }],
23
- ];
24
- const ctx = await request.newContext();
25
- for (const [n, c] of cases) {
26
- const r = await axios({ ...c, validateStatus: () => true });
27
- const d = r.data; delete d.h.host; delete d.h.connection;
28
- console.log('AX', n, JSON.stringify(d));
29
- const o = { method: c.method, headers: c.headers };
30
- if (c.data !== undefined && c.data !== null) o.data = c.data;
31
- const p = await ctx.fetch(u, o); const pj = await p.json(); delete pj.h.host; delete pj.h.connection;
32
- console.log('PW', n, JSON.stringify(pj));
33
- }
34
- await ctx.dispose(); srv.close();
35
- });
package/.scratch/echo.pid DELETED
@@ -1 +0,0 @@
1
- 2359762
@@ -1,22 +0,0 @@
1
- Feature: cookie check (not committed)
2
- Scenario: REST shares the browser cookies, API does not
3
- Given I am on "/about-us.html"
4
- And the cookie "session_id" is set to "abc123"
5
- Given the API base URL is "http://localhost:8990"
6
- And I am authenticating as "tester" with "secret" password
7
- When I send a POST request to "/echo" with body:
8
- """
9
- {"a": 1}
10
- """
11
- Then the JSON response should have "cookie" equal to "none"
12
- And the JSON response should have "auth" equal to "Basic dGVzdGVyOnNlY3JldA=="
13
- And the JSON response should have "type" equal to "application/json"
14
- And a cookie with the name "from_api" should not exist
15
- When I send a REST "POST" request to "http://localhost:8990/echo" with body:
16
- """
17
- a=1&b=2
18
- """
19
- Then the REST response should contain "session_id=abc123"
20
- And the REST response should contain "application/x-www-form-urlencoded"
21
- And the REST response should contain "a=1&b=2"
22
- And a cookie with the name "from_api" should exist
package/.scratch/http.pid DELETED
@@ -1 +0,0 @@
1
- 2324561
@@ -1 +0,0 @@
1
- 2324559