automation_model 1.0.613-dev → 1.0.613-stage

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.
@@ -10,18 +10,23 @@ import { getDateTimeValue } from "./date_time.js";
10
10
  import drawRectangle from "./drawRect.js";
11
11
  //import { closeUnexpectedPopups } from "./popups.js";
12
12
  import { getTableCells, getTableData } from "./table_analyze.js";
13
- import { _convertToRegexQuery, _copyContext, _fixLocatorUsingParams, _fixUsingParams, _getServerUrl, extractStepExampleParameters, KEYBOARD_EVENTS, maskValue, replaceWithLocalTestData, scrollPageToLoadLazyElements, unEscapeString, _getDataFile, } from "./utils.js";
13
+ import { _convertToRegexQuery, _copyContext, _fixLocatorUsingParams, _fixUsingParams, _getServerUrl, extractStepExampleParameters, KEYBOARD_EVENTS, maskValue, replaceWithLocalTestData, scrollPageToLoadLazyElements, unEscapeString, _getDataFile, testForRegex, performAction, } from "./utils.js";
14
14
  import csv from "csv-parser";
15
15
  import { Readable } from "node:stream";
16
16
  import readline from "readline";
17
- import { getContext } from "./init_browser.js";
17
+ import { getContext, refreshBrowser } from "./init_browser.js";
18
+ import { getTestData } from "./auto_page.js";
18
19
  import { locate_element } from "./locate_element.js";
19
20
  import { randomUUID } from "crypto";
20
21
  import { _commandError, _commandFinally, _preCommand, _validateSelectors, _screenshot, _reportToWorld, } from "./command_common.js";
21
22
  import { registerDownloadEvent, registerNetworkEvents } from "./network.js";
22
23
  import { LocatorLog } from "./locator_log.js";
24
+ import axios from "axios";
25
+ import { _findCellArea, findElementsInArea } from "./table_helper.js";
26
+ import { loadBrunoParams } from "./bruno.js";
23
27
  export const Types = {
24
28
  CLICK: "click_element",
29
+ WAIT_ELEMENT: "wait_element",
25
30
  NAVIGATE: "navigate",
26
31
  FILL: "fill_element",
27
32
  EXECUTE: "execute_page_method",
@@ -43,6 +48,7 @@ export const Types = {
43
48
  UNCHECK: "uncheck_element",
44
49
  EXTRACT: "extract_attribute",
45
50
  CLOSE_PAGE: "close_page",
51
+ TABLE_OPERATION: "table_operation",
46
52
  SET_DATE_TIME: "set_date_time",
47
53
  SET_VIEWPORT: "set_viewport",
48
54
  VERIFY_VISUAL: "verify_visual",
@@ -51,6 +57,9 @@ export const Types = {
51
57
  WAIT_FOR_TEXT_TO_DISAPPEAR: "wait_for_text_to_disappear",
52
58
  VERIFY_ATTRIBUTE: "verify_element_attribute",
53
59
  VERIFY_TEXT_WITH_RELATION: "verify_text_with_relation",
60
+ BRUNO: "bruno",
61
+ VERIFY_FILE_EXISTS: "verify_file_exists",
62
+ SET_INPUT_FILES: "set_input_files",
54
63
  };
55
64
  export const apps = {};
56
65
  const formatElementName = (elementName) => {
@@ -69,6 +78,7 @@ class StableBrowser {
69
78
  appName = "main";
70
79
  tags = null;
71
80
  isRecording = false;
81
+ initSnapshotTaken = false;
72
82
  constructor(browser, page, logger = null, context = null, world = null) {
73
83
  this.browser = browser;
74
84
  this.page = page;
@@ -175,6 +185,30 @@ class StableBrowser {
175
185
  await this.waitForPageLoad();
176
186
  }
177
187
  }
188
+ async switchTab(tabTitleOrIndex) {
189
+ // first check if the tabNameOrIndex is a number
190
+ let index = parseInt(tabTitleOrIndex);
191
+ if (!isNaN(index)) {
192
+ if (index >= 0 && index < this.context.pages.length) {
193
+ this.page = this.context.pages[index];
194
+ this.context.page = this.page;
195
+ await this.page.bringToFront();
196
+ return;
197
+ }
198
+ }
199
+ // if the tabNameOrIndex is a string, find the tab by name
200
+ for (let i = 0; i < this.context.pages.length; i++) {
201
+ let page = this.context.pages[i];
202
+ let title = await page.title();
203
+ if (title.includes(tabTitleOrIndex)) {
204
+ this.page = page;
205
+ this.context.page = this.page;
206
+ await this.page.bringToFront();
207
+ return;
208
+ }
209
+ }
210
+ throw new Error("Tab not found: " + tabTitleOrIndex);
211
+ }
178
212
  registerConsoleLogListener(page, context) {
179
213
  if (!this.context.webLogger) {
180
214
  this.context.webLogger = [];
@@ -270,7 +304,7 @@ class StableBrowser {
270
304
  _commandError(state, error, this);
271
305
  }
272
306
  finally {
273
- _commandFinally(state, this);
307
+ await _commandFinally(state, this);
274
308
  }
275
309
  }
276
310
  async _getLocator(locator, scope, _params) {
@@ -351,7 +385,7 @@ class StableBrowser {
351
385
  return resultCss;
352
386
  }
353
387
  async _locateElementByText(scope, text1, tag1, regex1 = false, partial1, ignoreCase = true, _params) {
354
- const query = _convertToRegexQuery(text1, regex1, !partial1, ignoreCase);
388
+ const query = `${_convertToRegexQuery(text1, regex1, !partial1, ignoreCase)}`;
355
389
  const locator = scope.locator(query);
356
390
  const count = await locator.count();
357
391
  if (!tag1) {
@@ -371,6 +405,12 @@ class StableBrowser {
371
405
  if (!el.setAttribute) {
372
406
  el = el.parentElement;
373
407
  }
408
+ // remove any attributes start with data-blinq-id
409
+ // for (let i = 0; i < el.attributes.length; i++) {
410
+ // if (el.attributes[i].name.startsWith("data-blinq-id")) {
411
+ // el.removeAttribute(el.attributes[i].name);
412
+ // }
413
+ // }
374
414
  el.setAttribute("data-blinq-id-" + randomToken, "");
375
415
  return true;
376
416
  }, [tag1, randomToken]))) {
@@ -557,9 +597,24 @@ class StableBrowser {
557
597
  element.evaluate((el, randomToken) => {
558
598
  el.setAttribute("data-blinq-id-" + randomToken, "");
559
599
  }, randomToken);
600
+ // if (element._frame) {
601
+ // return element;
602
+ // }
560
603
  const scope = element._frame ?? element.page();
561
- const newSelector = scope.locator("[data-blinq-id-" + randomToken + "]");
562
- return newSelector;
604
+ let newElementSelector = "[data-blinq-id-" + randomToken + "]";
605
+ let prefixSelector = "";
606
+ const frameControlSelector = " >> internal:control=enter-frame";
607
+ const frameSelectorIndex = element._selector.lastIndexOf(frameControlSelector);
608
+ if (frameSelectorIndex !== -1) {
609
+ // remove everything after the >> internal:control=enter-frame
610
+ const frameSelector = element._selector.substring(0, frameSelectorIndex);
611
+ prefixSelector = frameSelector + " >> internal:control=enter-frame >>";
612
+ }
613
+ // if (element?._frame?._selector) {
614
+ // prefixSelector = element._frame._selector + " >> " + prefixSelector;
615
+ // }
616
+ const newSelector = prefixSelector + newElementSelector;
617
+ return scope.locator(newSelector);
563
618
  }
564
619
  }
565
620
  throw new Error("unable to locate element " + JSON.stringify(selectors));
@@ -711,14 +766,9 @@ class StableBrowser {
711
766
  // info.log += "scanning locators in priority 2" + "\n";
712
767
  result = await this._scanLocatorsGroup(locatorsByPriority["2"], scope, _params, info, visibleOnly, allowDisabled, selectors?.element_name);
713
768
  }
714
- if (result.foundElements.length === 0 && onlyPriority3) {
769
+ if (result.foundElements.length === 0 && (onlyPriority3 || !highPriorityOnly)) {
715
770
  result = await this._scanLocatorsGroup(locatorsByPriority["3"], scope, _params, info, visibleOnly, allowDisabled, selectors?.element_name);
716
771
  }
717
- else {
718
- if (result.foundElements.length === 0 && !highPriorityOnly) {
719
- result = await this._scanLocatorsGroup(locatorsByPriority["3"], scope, _params, info, visibleOnly, allowDisabled, selectors?.element_name);
720
- }
721
- }
722
772
  let foundElements = result.foundElements;
723
773
  if (foundElements.length === 1 && foundElements[0].unique) {
724
774
  info.box = foundElements[0].box;
@@ -773,6 +823,11 @@ class StableBrowser {
773
823
  visibleOnly = false;
774
824
  }
775
825
  await new Promise((resolve) => setTimeout(resolve, 1000));
826
+ // sheck of more of half of the timeout has passed
827
+ if (Date.now() - startTime > timeout / 2) {
828
+ highPriorityOnly = false;
829
+ visibleOnly = false;
830
+ }
776
831
  }
777
832
  this.logger.debug("unable to locate unique element, total elements found " + locatorsCount);
778
833
  // if (info.locatorLog) {
@@ -819,9 +874,40 @@ class StableBrowser {
819
874
  result.locatorIndex = i;
820
875
  }
821
876
  if (foundLocators.length > 1) {
822
- info.failCause.foundMultiple = true;
823
- if (info.locatorLog) {
824
- info.locatorLog.setLocatorSearchStatus(JSON.stringify(locatorsGroup[i]), "FOUND_NOT_UNIQUE");
877
+ // remove elements that consume the same space with 10 pixels tolerance
878
+ const boxes = [];
879
+ for (let j = 0; j < foundLocators.length; j++) {
880
+ boxes.push({ box: await foundLocators[j].boundingBox(), locator: foundLocators[j] });
881
+ }
882
+ for (let j = 0; j < boxes.length; j++) {
883
+ for (let k = 0; k < boxes.length; k++) {
884
+ if (j === k) {
885
+ continue;
886
+ }
887
+ // check if x, y, width, height are the same with 10 pixels tolerance
888
+ if (Math.abs(boxes[j].box.x - boxes[k].box.x) < 10 &&
889
+ Math.abs(boxes[j].box.y - boxes[k].box.y) < 10 &&
890
+ Math.abs(boxes[j].box.width - boxes[k].box.width) < 10 &&
891
+ Math.abs(boxes[j].box.height - boxes[k].box.height) < 10) {
892
+ // as the element is not unique, will remove it
893
+ boxes.splice(k, 1);
894
+ k--;
895
+ }
896
+ }
897
+ }
898
+ if (boxes.length === 1) {
899
+ result.foundElements.push({
900
+ locator: boxes[0].locator.first(),
901
+ box: boxes[0].box,
902
+ unique: true,
903
+ });
904
+ result.locatorIndex = i;
905
+ }
906
+ else {
907
+ info.failCause.foundMultiple = true;
908
+ if (info.locatorLog) {
909
+ info.locatorLog.setLocatorSearchStatus(JSON.stringify(locatorsGroup[i]), "FOUND_NOT_UNIQUE");
910
+ }
825
911
  }
826
912
  }
827
913
  }
@@ -869,7 +955,7 @@ class StableBrowser {
869
955
  await _commandError(state, "timeout looking for " + elementDescription, this);
870
956
  }
871
957
  finally {
872
- _commandFinally(state, this);
958
+ await _commandFinally(state, this);
873
959
  }
874
960
  }
875
961
  }
@@ -918,7 +1004,7 @@ class StableBrowser {
918
1004
  await _commandError(state, "timeout looking for " + elementDescription, this);
919
1005
  }
920
1006
  finally {
921
- _commandFinally(state, this);
1007
+ await _commandFinally(state, this);
922
1008
  }
923
1009
  }
924
1010
  }
@@ -932,25 +1018,14 @@ class StableBrowser {
932
1018
  options,
933
1019
  world,
934
1020
  text: "Click element",
1021
+ _text: "Click on " + selectors.element_name,
935
1022
  type: Types.CLICK,
936
1023
  operation: "click",
937
1024
  log: "***** click on " + selectors.element_name + " *****\n",
938
1025
  };
939
1026
  try {
940
1027
  await _preCommand(state, this);
941
- // if (state.options && state.options.context) {
942
- // state.selectors.locators[0].text = state.options.context;
943
- // }
944
- try {
945
- await state.element.click();
946
- // await new Promise((resolve) => setTimeout(resolve, 1000));
947
- }
948
- catch (e) {
949
- // await this.closeUnexpectedPopups();
950
- state.element = await this._locate(selectors, state.info, _params);
951
- await state.element.dispatchEvent("click");
952
- // await new Promise((resolve) => setTimeout(resolve, 1000));
953
- }
1028
+ await performAction("click", state.element, options, this, state, _params);
954
1029
  await this.waitForPageLoad();
955
1030
  return state.info;
956
1031
  }
@@ -958,9 +1033,41 @@ class StableBrowser {
958
1033
  await _commandError(state, e, this);
959
1034
  }
960
1035
  finally {
961
- _commandFinally(state, this);
1036
+ await _commandFinally(state, this);
962
1037
  }
963
1038
  }
1039
+ async waitForElement(selectors, _params, options = {}, world = null) {
1040
+ const timeout = this._getFindElementTimeout(options);
1041
+ const state = {
1042
+ selectors,
1043
+ _params,
1044
+ options,
1045
+ world,
1046
+ text: "Wait for element",
1047
+ _text: "Wait for " + selectors.element_name,
1048
+ type: Types.WAIT_ELEMENT,
1049
+ operation: "waitForElement",
1050
+ log: "***** wait for " + selectors.element_name + " *****\n",
1051
+ };
1052
+ let found = false;
1053
+ try {
1054
+ await _preCommand(state, this);
1055
+ // if (state.options && state.options.context) {
1056
+ // state.selectors.locators[0].text = state.options.context;
1057
+ // }
1058
+ await state.element.waitFor({ timeout: timeout });
1059
+ found = true;
1060
+ // await new Promise((resolve) => setTimeout(resolve, 1000));
1061
+ }
1062
+ catch (e) {
1063
+ console.error("Error on waitForElement", e);
1064
+ // await _commandError(state, e, this);
1065
+ }
1066
+ finally {
1067
+ await _commandFinally(state, this);
1068
+ }
1069
+ return found;
1070
+ }
964
1071
  async setCheck(selectors, checked = true, _params, options = {}, world = null) {
965
1072
  const state = {
966
1073
  selectors,
@@ -969,6 +1076,7 @@ class StableBrowser {
969
1076
  world,
970
1077
  type: checked ? Types.CHECK : Types.UNCHECK,
971
1078
  text: checked ? `Check element` : `Uncheck element`,
1079
+ _text: checked ? `Check ${selectors.element_name}` : `Uncheck ${selectors.element_name}`,
972
1080
  operation: "setCheck",
973
1081
  log: "***** check " + selectors.element_name + " *****\n",
974
1082
  };
@@ -980,7 +1088,7 @@ class StableBrowser {
980
1088
  try {
981
1089
  // if (world && world.screenshot && !world.screenshotPath) {
982
1090
  // console.log(`Highlighting while running from recorder`);
983
- await this._highlightElements(element);
1091
+ await this._highlightElements(state.element);
984
1092
  await state.element.setChecked(checked);
985
1093
  await new Promise((resolve) => setTimeout(resolve, 1000));
986
1094
  // await this._unHighlightElements(element);
@@ -1007,7 +1115,7 @@ class StableBrowser {
1007
1115
  await _commandError(state, e, this);
1008
1116
  }
1009
1117
  finally {
1010
- _commandFinally(state, this);
1118
+ await _commandFinally(state, this);
1011
1119
  }
1012
1120
  }
1013
1121
  async hover(selectors, _params, options = {}, world = null) {
@@ -1018,24 +1126,13 @@ class StableBrowser {
1018
1126
  world,
1019
1127
  type: Types.HOVER,
1020
1128
  text: `Hover element`,
1129
+ _text: `Hover on ${selectors.element_name}`,
1021
1130
  operation: "hover",
1022
1131
  log: "***** hover " + selectors.element_name + " *****\n",
1023
1132
  };
1024
1133
  try {
1025
1134
  await _preCommand(state, this);
1026
- try {
1027
- await state.element.hover();
1028
- // await _screenshot(state, this);
1029
- await new Promise((resolve) => setTimeout(resolve, 1000));
1030
- }
1031
- catch (e) {
1032
- //await this.closeUnexpectedPopups();
1033
- state.info.log += "hover failed, will try again" + "\n";
1034
- state.element = await this._locate(selectors, state.info, _params);
1035
- await state.element.hover({ timeout: 10000 });
1036
- // await _screenshot(state, this);
1037
- await new Promise((resolve) => setTimeout(resolve, 1000));
1038
- }
1135
+ await performAction("hover", state.element, options, this, state, _params);
1039
1136
  await _screenshot(state, this);
1040
1137
  await this.waitForPageLoad();
1041
1138
  return state.info;
@@ -1044,7 +1141,7 @@ class StableBrowser {
1044
1141
  await _commandError(state, e, this);
1045
1142
  }
1046
1143
  finally {
1047
- _commandFinally(state, this);
1144
+ await _commandFinally(state, this);
1048
1145
  }
1049
1146
  }
1050
1147
  async selectOption(selectors, values, _params = null, options = {}, world = null) {
@@ -1059,6 +1156,7 @@ class StableBrowser {
1059
1156
  value: values.toString(),
1060
1157
  type: Types.SELECT,
1061
1158
  text: `Select option: ${values}`,
1159
+ _text: `Select option: ${values} on ${selectors.element_name}`,
1062
1160
  operation: "selectOption",
1063
1161
  log: "***** select option " + selectors.element_name + " *****\n",
1064
1162
  };
@@ -1079,7 +1177,7 @@ class StableBrowser {
1079
1177
  await _commandError(state, e, this);
1080
1178
  }
1081
1179
  finally {
1082
- _commandFinally(state, this);
1180
+ await _commandFinally(state, this);
1083
1181
  }
1084
1182
  }
1085
1183
  async type(_value, _params = null, options = {}, world = null) {
@@ -1093,6 +1191,7 @@ class StableBrowser {
1093
1191
  highlight: false,
1094
1192
  type: Types.TYPE_PRESS,
1095
1193
  text: `Type value: ${_value}`,
1194
+ _text: `Type value: ${_value}`,
1096
1195
  operation: "type",
1097
1196
  log: "",
1098
1197
  };
@@ -1124,7 +1223,7 @@ class StableBrowser {
1124
1223
  await _commandError(state, e, this);
1125
1224
  }
1126
1225
  finally {
1127
- _commandFinally(state, this);
1226
+ await _commandFinally(state, this);
1128
1227
  }
1129
1228
  }
1130
1229
  async setInputValue(selectors, value, _params = null, options = {}, world = null) {
@@ -1160,7 +1259,7 @@ class StableBrowser {
1160
1259
  await _commandError(state, e, this);
1161
1260
  }
1162
1261
  finally {
1163
- _commandFinally(state, this);
1262
+ await _commandFinally(state, this);
1164
1263
  }
1165
1264
  }
1166
1265
  async setDateTime(selectors, value, format = null, enter = false, _params = null, options = {}, world = null) {
@@ -1172,6 +1271,7 @@ class StableBrowser {
1172
1271
  world,
1173
1272
  type: Types.SET_DATE_TIME,
1174
1273
  text: `Set date time value: ${value}`,
1274
+ _text: `Set date time value: ${value} on ${selectors.element_name}`,
1175
1275
  operation: "setDateTime",
1176
1276
  log: "***** set date time value " + selectors.element_name + " *****\n",
1177
1277
  throwError: false,
@@ -1179,7 +1279,7 @@ class StableBrowser {
1179
1279
  try {
1180
1280
  await _preCommand(state, this);
1181
1281
  try {
1182
- await state.element.click();
1282
+ await performAction("click", state.element, options, this, state, _params);
1183
1283
  await new Promise((resolve) => setTimeout(resolve, 500));
1184
1284
  if (format) {
1185
1285
  state.value = dayjs(state.value).format(format);
@@ -1228,7 +1328,7 @@ class StableBrowser {
1228
1328
  await _commandError(state, e, this);
1229
1329
  }
1230
1330
  finally {
1231
- _commandFinally(state, this);
1331
+ await _commandFinally(state, this);
1232
1332
  }
1233
1333
  }
1234
1334
  async clickType(selectors, _value, enter = false, _params = null, options = {}, world = null) {
@@ -1243,9 +1343,13 @@ class StableBrowser {
1243
1343
  world,
1244
1344
  type: Types.FILL,
1245
1345
  text: `Click type input with value: ${_value}`,
1346
+ _text: "Fill " + selectors.element_name + " with value " + maskValue(_value),
1246
1347
  operation: "clickType",
1247
1348
  log: "***** clickType on " + selectors.element_name + " with value " + maskValue(_value) + "*****\n",
1248
1349
  };
1350
+ if (!options) {
1351
+ options = {};
1352
+ }
1249
1353
  if (newValue !== _value) {
1250
1354
  //this.logger.info(_value + "=" + newValue);
1251
1355
  _value = newValue;
@@ -1253,7 +1357,7 @@ class StableBrowser {
1253
1357
  try {
1254
1358
  await _preCommand(state, this);
1255
1359
  state.info.value = _value;
1256
- if (options === null || options === undefined || !options.press) {
1360
+ if (!options.press) {
1257
1361
  try {
1258
1362
  let currentValue = await state.element.inputValue();
1259
1363
  if (currentValue) {
@@ -1264,13 +1368,9 @@ class StableBrowser {
1264
1368
  this.logger.info("unable to clear input value");
1265
1369
  }
1266
1370
  }
1267
- if (options === null || options === undefined || options.press) {
1268
- try {
1269
- await state.element.click({ timeout: 5000 });
1270
- }
1271
- catch (e) {
1272
- await state.element.dispatchEvent("click");
1273
- }
1371
+ if (options.press) {
1372
+ options.timeout = 5000;
1373
+ await performAction("click", state.element, options, this, state, _params);
1274
1374
  }
1275
1375
  else {
1276
1376
  try {
@@ -1328,7 +1428,7 @@ class StableBrowser {
1328
1428
  await _commandError(state, e, this);
1329
1429
  }
1330
1430
  finally {
1331
- _commandFinally(state, this);
1431
+ await _commandFinally(state, this);
1332
1432
  }
1333
1433
  }
1334
1434
  async fill(selectors, value, enter = false, _params = null, options = {}, world = null) {
@@ -1358,13 +1458,49 @@ class StableBrowser {
1358
1458
  await _commandError(state, e, this);
1359
1459
  }
1360
1460
  finally {
1361
- _commandFinally(state, this);
1461
+ await _commandFinally(state, this);
1462
+ }
1463
+ }
1464
+ async setInputFiles(selectors, files, _params = null, options = {}, world = null) {
1465
+ const state = {
1466
+ selectors,
1467
+ _params,
1468
+ files,
1469
+ value: '"' + files.join('", "') + '"',
1470
+ options,
1471
+ world,
1472
+ type: Types.SET_INPUT_FILES,
1473
+ text: `Set input files`,
1474
+ _text: `Set input files on ${selectors.element_name}`,
1475
+ operation: "setInputFiles",
1476
+ log: "***** set input files " + selectors.element_name + " *****\n",
1477
+ };
1478
+ const uploadsFolder = this.configuration.uploadsFolder ?? "data/uploads";
1479
+ try {
1480
+ await _preCommand(state, this);
1481
+ for (let i = 0; i < files.length; i++) {
1482
+ const file = files[i];
1483
+ const filePath = path.join(uploadsFolder, file);
1484
+ if (!fs.existsSync(filePath)) {
1485
+ throw new Error(`File not found: ${filePath}`);
1486
+ }
1487
+ state.files[i] = filePath;
1488
+ }
1489
+ await state.element.setInputFiles(files);
1490
+ return state.info;
1491
+ }
1492
+ catch (e) {
1493
+ await _commandError(state, e, this);
1494
+ }
1495
+ finally {
1496
+ await _commandFinally(state, this);
1362
1497
  }
1363
1498
  }
1364
1499
  async getText(selectors, _params = null, options = {}, info = {}, world = null) {
1365
1500
  return await this._getText(selectors, 0, _params, options, info, world);
1366
1501
  }
1367
1502
  async _getText(selectors, climb, _params = null, options = {}, info = {}, world = null) {
1503
+ const timeout = this._getFindElementTimeout(options);
1368
1504
  _validateSelectors(selectors);
1369
1505
  let screenshotId = null;
1370
1506
  let screenshotPath = null;
@@ -1374,7 +1510,7 @@ class StableBrowser {
1374
1510
  }
1375
1511
  info.operation = "getText";
1376
1512
  info.selectors = selectors;
1377
- let element = await this._locate(selectors, info, _params);
1513
+ let element = await this._locate(selectors, info, _params, timeout);
1378
1514
  if (climb > 0) {
1379
1515
  const climbArray = [];
1380
1516
  for (let i = 0; i < climb; i++) {
@@ -1441,6 +1577,7 @@ class StableBrowser {
1441
1577
  highlight: false,
1442
1578
  type: Types.VERIFY_ELEMENT_CONTAINS_TEXT,
1443
1579
  text: `Verify element contains pattern: ${pattern}`,
1580
+ _text: "Verify element " + selectors.element_name + " contains pattern " + pattern,
1444
1581
  operation: "containsPattern",
1445
1582
  log: "***** verify element " + selectors.element_name + " contains pattern " + pattern + " *****\n",
1446
1583
  };
@@ -1472,10 +1609,12 @@ class StableBrowser {
1472
1609
  await _commandError(state, e, this);
1473
1610
  }
1474
1611
  finally {
1475
- _commandFinally(state, this);
1612
+ await _commandFinally(state, this);
1476
1613
  }
1477
1614
  }
1478
1615
  async containsText(selectors, text, climb, _params = null, options = {}, world = null) {
1616
+ const timeout = this._getFindElementTimeout(options);
1617
+ const startTime = Date.now();
1479
1618
  const state = {
1480
1619
  selectors,
1481
1620
  _params,
@@ -1502,44 +1641,52 @@ class StableBrowser {
1502
1641
  }
1503
1642
  let foundObj = null;
1504
1643
  try {
1505
- await _preCommand(state, this);
1506
- foundObj = await this._getText(selectors, climb, _params, options, state.info, world);
1507
- if (foundObj && foundObj.element) {
1508
- await this.scrollIfNeeded(foundObj.element, state.info);
1509
- }
1510
- await _screenshot(state, this);
1511
- const dateAlternatives = findDateAlternatives(text);
1512
- const numberAlternatives = findNumberAlternatives(text);
1513
- if (dateAlternatives.date) {
1514
- for (let i = 0; i < dateAlternatives.dates.length; i++) {
1515
- if (foundObj?.text.includes(dateAlternatives.dates[i]) ||
1516
- foundObj?.value?.includes(dateAlternatives.dates[i])) {
1517
- return state.info;
1644
+ while (Date.now() - startTime < timeout) {
1645
+ try {
1646
+ await _preCommand(state, this);
1647
+ foundObj = await this._getText(selectors, climb, _params, { timeout: 3000 }, state.info, world);
1648
+ if (foundObj && foundObj.element) {
1649
+ await this.scrollIfNeeded(foundObj.element, state.info);
1518
1650
  }
1519
- }
1520
- throw new Error("element doesn't contain text " + text);
1521
- }
1522
- else if (numberAlternatives.number) {
1523
- for (let i = 0; i < numberAlternatives.numbers.length; i++) {
1524
- if (foundObj?.text.includes(numberAlternatives.numbers[i]) ||
1525
- foundObj?.value?.includes(numberAlternatives.numbers[i])) {
1651
+ await _screenshot(state, this);
1652
+ const dateAlternatives = findDateAlternatives(text);
1653
+ const numberAlternatives = findNumberAlternatives(text);
1654
+ if (dateAlternatives.date) {
1655
+ for (let i = 0; i < dateAlternatives.dates.length; i++) {
1656
+ if (foundObj?.text.includes(dateAlternatives.dates[i]) ||
1657
+ foundObj?.value?.includes(dateAlternatives.dates[i])) {
1658
+ return state.info;
1659
+ }
1660
+ }
1661
+ }
1662
+ else if (numberAlternatives.number) {
1663
+ for (let i = 0; i < numberAlternatives.numbers.length; i++) {
1664
+ if (foundObj?.text.includes(numberAlternatives.numbers[i]) ||
1665
+ foundObj?.value?.includes(numberAlternatives.numbers[i])) {
1666
+ return state.info;
1667
+ }
1668
+ }
1669
+ }
1670
+ else if (foundObj?.text.includes(text) || foundObj?.value?.includes(text)) {
1526
1671
  return state.info;
1527
1672
  }
1528
1673
  }
1529
- throw new Error("element doesn't contain text " + text);
1530
- }
1531
- else if (!foundObj?.text.includes(text) && !foundObj?.value?.includes(text)) {
1532
- state.info.foundText = foundObj?.text;
1533
- state.info.value = foundObj?.value;
1534
- throw new Error("element doesn't contain text " + text);
1674
+ catch (e) {
1675
+ // Log error but continue retrying until timeout is reached
1676
+ this.logger.warn("Retrying containsText due to: " + e.message);
1677
+ }
1678
+ await new Promise((resolve) => setTimeout(resolve, 1000)); // Wait 1 second before retrying
1535
1679
  }
1536
- return state.info;
1680
+ state.info.foundText = foundObj?.text;
1681
+ state.info.value = foundObj?.value;
1682
+ throw new Error("element doesn't contain text " + text);
1537
1683
  }
1538
1684
  catch (e) {
1539
1685
  await _commandError(state, e, this);
1686
+ throw e;
1540
1687
  }
1541
1688
  finally {
1542
- _commandFinally(state, this);
1689
+ await _commandFinally(state, this);
1543
1690
  }
1544
1691
  }
1545
1692
  async waitForUserInput(message, world = null) {
@@ -1577,6 +1724,15 @@ class StableBrowser {
1577
1724
  // save the data to the file
1578
1725
  fs.writeFileSync(dataFile, JSON.stringify(data, null, 2));
1579
1726
  }
1727
+ overwriteTestData(testData, world = null) {
1728
+ if (!testData) {
1729
+ return;
1730
+ }
1731
+ // if data file exists, load it
1732
+ const dataFile = _getDataFile(world, this.context, this);
1733
+ // save the data to the file
1734
+ fs.writeFileSync(dataFile, JSON.stringify(testData, null, 2));
1735
+ }
1580
1736
  _getDataFilePath(fileName) {
1581
1737
  let dataFile = path.join(this.project_path, "data", fileName);
1582
1738
  if (fs.existsSync(dataFile)) {
@@ -1829,7 +1985,7 @@ class StableBrowser {
1829
1985
  await _commandError(state, e, this);
1830
1986
  }
1831
1987
  finally {
1832
- _commandFinally(state, this);
1988
+ await _commandFinally(state, this);
1833
1989
  }
1834
1990
  }
1835
1991
  async extractAttribute(selectors, attribute, variable, _params = null, options = {}, world = null) {
@@ -1842,6 +1998,7 @@ class StableBrowser {
1842
1998
  world,
1843
1999
  type: Types.EXTRACT,
1844
2000
  text: `Extract attribute from element`,
2001
+ _text: `Extract attribute ${attribute} from ${selectors.element_name}`,
1845
2002
  operation: "extractAttribute",
1846
2003
  log: "***** extract attribute " + attribute + " from " + selectors.element_name + " *****\n",
1847
2004
  allowDisabled: true,
@@ -1859,10 +2016,31 @@ class StableBrowser {
1859
2016
  case "value":
1860
2017
  state.value = await state.element.inputValue();
1861
2018
  break;
2019
+ case "text":
2020
+ state.value = await state.element.textContent();
2021
+ break;
1862
2022
  default:
1863
2023
  state.value = await state.element.getAttribute(attribute);
1864
2024
  break;
1865
2025
  }
2026
+ if (options !== null) {
2027
+ if (options.regex && options.regex !== "") {
2028
+ // Construct a regex pattern from the provided string
2029
+ const regex = options.regex.slice(1, -1);
2030
+ const regexPattern = new RegExp(regex, "g");
2031
+ const matches = state.value.match(regexPattern);
2032
+ if (matches) {
2033
+ let newValue = "";
2034
+ for (const match of matches) {
2035
+ newValue += match;
2036
+ }
2037
+ state.value = newValue;
2038
+ }
2039
+ }
2040
+ if (options.trimSpaces && options.trimSpaces === true) {
2041
+ state.value = state.value.trim();
2042
+ }
2043
+ }
1866
2044
  state.info.value = state.value;
1867
2045
  this.setTestData({ [variable]: state.value }, world);
1868
2046
  this.logger.info("set test data: " + variable + "=" + state.value);
@@ -1873,7 +2051,7 @@ class StableBrowser {
1873
2051
  await _commandError(state, e, this);
1874
2052
  }
1875
2053
  finally {
1876
- _commandFinally(state, this);
2054
+ await _commandFinally(state, this);
1877
2055
  }
1878
2056
  }
1879
2057
  async verifyAttribute(selectors, attribute, value, _params = null, options = {}, world = null) {
@@ -1888,6 +2066,7 @@ class StableBrowser {
1888
2066
  highlight: true,
1889
2067
  screenshot: true,
1890
2068
  text: `Verify element attribute`,
2069
+ _text: `Verify attribute ${attribute} from ${selectors.element_name} is ${value}`,
1891
2070
  operation: "verifyAttribute",
1892
2071
  log: "***** verify attribute " + attribute + " from " + selectors.element_name + " *****\n",
1893
2072
  allowDisabled: true,
@@ -1897,12 +2076,15 @@ class StableBrowser {
1897
2076
  let expectedValue;
1898
2077
  try {
1899
2078
  await _preCommand(state, this);
1900
- expectedValue = state.value;
2079
+ expectedValue = await replaceWithLocalTestData(state.value, world);
1901
2080
  state.info.expectedValue = expectedValue;
1902
2081
  switch (attribute) {
1903
2082
  case "innerText":
1904
2083
  val = String(await state.element.innerText());
1905
2084
  break;
2085
+ case "text":
2086
+ val = String(await state.element.textContent());
2087
+ break;
1906
2088
  case "value":
1907
2089
  val = String(await state.element.inputValue());
1908
2090
  break;
@@ -1942,7 +2124,7 @@ class StableBrowser {
1942
2124
  await _commandError(state, e, this);
1943
2125
  }
1944
2126
  finally {
1945
- _commandFinally(state, this);
2127
+ await _commandFinally(state, this);
1946
2128
  }
1947
2129
  }
1948
2130
  async extractEmailData(emailAddress, options, world) {
@@ -2194,6 +2376,69 @@ class StableBrowser {
2194
2376
  _reportToWorld(world, {
2195
2377
  type: Types.VERIFY_PAGE_PATH,
2196
2378
  text: "Verify page path",
2379
+ _text: "Verify the page path contains " + pathPart,
2380
+ screenshotId,
2381
+ result: error
2382
+ ? {
2383
+ status: "FAILED",
2384
+ startTime,
2385
+ endTime,
2386
+ message: error?.message,
2387
+ }
2388
+ : {
2389
+ status: "PASSED",
2390
+ startTime,
2391
+ endTime,
2392
+ },
2393
+ info: info,
2394
+ });
2395
+ }
2396
+ }
2397
+ async verifyPageTitle(title, options = {}, world = null) {
2398
+ const startTime = Date.now();
2399
+ let error = null;
2400
+ let screenshotId = null;
2401
+ let screenshotPath = null;
2402
+ await new Promise((resolve) => setTimeout(resolve, 2000));
2403
+ const info = {};
2404
+ info.log = "***** verify page title " + title + " *****\n";
2405
+ info.operation = "verifyPageTitle";
2406
+ const newValue = await this._replaceWithLocalData(title, world);
2407
+ if (newValue !== title) {
2408
+ this.logger.info(title + "=" + newValue);
2409
+ title = newValue;
2410
+ }
2411
+ info.title = title;
2412
+ try {
2413
+ for (let i = 0; i < 30; i++) {
2414
+ const foundTitle = await this.page.title();
2415
+ if (!foundTitle.includes(title)) {
2416
+ if (i === 29) {
2417
+ throw new Error(`url ${foundTitle} doesn't contain ${title}`);
2418
+ }
2419
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2420
+ continue;
2421
+ }
2422
+ ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2423
+ return info;
2424
+ }
2425
+ }
2426
+ catch (e) {
2427
+ //await this.closeUnexpectedPopups();
2428
+ this.logger.error("verify page title failed " + info.log);
2429
+ ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2430
+ info.screenshotPath = screenshotPath;
2431
+ Object.assign(e, { info: info });
2432
+ error = e;
2433
+ // throw e;
2434
+ await _commandError({ text: "verifyPageTitle", operation: "verifyPageTitle", title, info, throwError: true }, e, this);
2435
+ }
2436
+ finally {
2437
+ const endTime = Date.now();
2438
+ _reportToWorld(world, {
2439
+ type: Types.VERIFY_PAGE_PATH,
2440
+ text: "Verify page title",
2441
+ _text: "Verify the page title contains " + title,
2197
2442
  screenshotId,
2198
2443
  result: error
2199
2444
  ? {
@@ -2211,27 +2456,27 @@ class StableBrowser {
2211
2456
  });
2212
2457
  }
2213
2458
  }
2214
- async findTextInAllFrames(dateAlternatives, numberAlternatives, text, state) {
2459
+ async findTextInAllFrames(dateAlternatives, numberAlternatives, text, state, partial = true, ignoreCase = false) {
2215
2460
  const frames = this.page.frames();
2216
2461
  let results = [];
2217
- let ignoreCase = false;
2462
+ // let ignoreCase = false;
2218
2463
  for (let i = 0; i < frames.length; i++) {
2219
2464
  if (dateAlternatives.date) {
2220
2465
  for (let j = 0; j < dateAlternatives.dates.length; j++) {
2221
- const result = await this._locateElementByText(frames[i], dateAlternatives.dates[j], "*:not(script, style, head)", false, true, ignoreCase, {});
2466
+ const result = await this._locateElementByText(frames[i], dateAlternatives.dates[j], "*:not(script, style, head)", false, partial, ignoreCase, {});
2222
2467
  result.frame = frames[i];
2223
2468
  results.push(result);
2224
2469
  }
2225
2470
  }
2226
2471
  else if (numberAlternatives.number) {
2227
2472
  for (let j = 0; j < numberAlternatives.numbers.length; j++) {
2228
- const result = await this._locateElementByText(frames[i], numberAlternatives.numbers[j], "*:not(script, style, head)", false, true, ignoreCase, {});
2473
+ const result = await this._locateElementByText(frames[i], numberAlternatives.numbers[j], "*:not(script, style, head)", false, partial, ignoreCase, {});
2229
2474
  result.frame = frames[i];
2230
2475
  results.push(result);
2231
2476
  }
2232
2477
  }
2233
2478
  else {
2234
- const result = await this._locateElementByText(frames[i], text, "*:not(script, style, head)", false, true, ignoreCase, {});
2479
+ const result = await this._locateElementByText(frames[i], text, "*:not(script, style, head)", false, partial, ignoreCase, {});
2235
2480
  result.frame = frames[i];
2236
2481
  results.push(result);
2237
2482
  }
@@ -2250,11 +2495,15 @@ class StableBrowser {
2250
2495
  scroll: false,
2251
2496
  highlight: false,
2252
2497
  type: Types.VERIFY_PAGE_CONTAINS_TEXT,
2253
- text: `Verify text exists in page`,
2498
+ text: `Verify the text '${maskValue(text)}' exists in page`,
2499
+ _text: `Verify the text '${text}' exists in page`,
2254
2500
  operation: "verifyTextExistInPage",
2255
2501
  log: "***** verify text " + text + " exists in page *****\n",
2256
2502
  };
2257
- const timeout = this._getLoadTimeout(options);
2503
+ if (testForRegex(text)) {
2504
+ text = text.replace(/\\"/g, '"');
2505
+ }
2506
+ const timeout = this._getFindElementTimeout(options);
2258
2507
  await new Promise((resolve) => setTimeout(resolve, 2000));
2259
2508
  const newValue = await this._replaceWithLocalData(text, world);
2260
2509
  if (newValue !== text) {
@@ -2324,7 +2573,7 @@ class StableBrowser {
2324
2573
  await _commandError(state, e, this);
2325
2574
  }
2326
2575
  finally {
2327
- _commandFinally(state, this);
2576
+ await _commandFinally(state, this);
2328
2577
  }
2329
2578
  }
2330
2579
  async waitForTextToDisappear(text, options = {}, world = null) {
@@ -2337,11 +2586,15 @@ class StableBrowser {
2337
2586
  scroll: false,
2338
2587
  highlight: false,
2339
2588
  type: Types.WAIT_FOR_TEXT_TO_DISAPPEAR,
2340
- text: `Verify text does not exist in page`,
2589
+ text: `Verify the text '${maskValue(text)}' does not exist in page`,
2590
+ _text: `Verify the text '${text}' does not exist in page`,
2341
2591
  operation: "verifyTextNotExistInPage",
2342
2592
  log: "***** verify text " + text + " does not exist in page *****\n",
2343
2593
  };
2344
- const timeout = this._getLoadTimeout(options);
2594
+ if (testForRegex(text)) {
2595
+ text = text.replace(/\\"/g, '"');
2596
+ }
2597
+ const timeout = this._getFindElementTimeout(options);
2345
2598
  await new Promise((resolve) => setTimeout(resolve, 2000));
2346
2599
  const newValue = await this._replaceWithLocalData(text, world);
2347
2600
  if (newValue !== text) {
@@ -2377,7 +2630,7 @@ class StableBrowser {
2377
2630
  await _commandError(state, e, this);
2378
2631
  }
2379
2632
  finally {
2380
- _commandFinally(state, this);
2633
+ await _commandFinally(state, this);
2381
2634
  }
2382
2635
  }
2383
2636
  async verifyTextRelatedToText(textAnchor, climb, textToVerify, options = {}, world = null) {
@@ -2392,10 +2645,11 @@ class StableBrowser {
2392
2645
  highlight: false,
2393
2646
  type: Types.VERIFY_TEXT_WITH_RELATION,
2394
2647
  text: `Verify text with relation to another text`,
2648
+ _text: "Search for " + textAnchor + " climb " + climb + " and verify " + textToVerify + " found",
2395
2649
  operation: "verify_text_with_relation",
2396
2650
  log: "***** search for " + textAnchor + " climb " + climb + " and verify " + textToVerify + " found *****\n",
2397
2651
  };
2398
- const timeout = this._getLoadTimeout(options);
2652
+ const timeout = this._getFindElementTimeout(options);
2399
2653
  await new Promise((resolve) => setTimeout(resolve, 2000));
2400
2654
  let newValue = await this._replaceWithLocalData(textAnchor, world);
2401
2655
  if (newValue !== textAnchor) {
@@ -2418,7 +2672,7 @@ class StableBrowser {
2418
2672
  };
2419
2673
  while (true) {
2420
2674
  try {
2421
- resultWithElementsFound = await this.findTextInAllFrames(dateAlternatives, numberAlternatives, textAnchor, state);
2675
+ resultWithElementsFound = await this.findTextInAllFrames(findDateAlternatives(textAnchor), findNumberAlternatives(textAnchor), textAnchor, state, false);
2422
2676
  }
2423
2677
  catch (error) {
2424
2678
  // ignore
@@ -2446,7 +2700,7 @@ class StableBrowser {
2446
2700
  const count = await frame.locator(css).count();
2447
2701
  for (let j = 0; j < count; j++) {
2448
2702
  const continer = await frame.locator(css).nth(j);
2449
- const result = await this._locateElementByText(continer, textToVerify, "*", false, true, true, {});
2703
+ const result = await this._locateElementByText(continer, textToVerify, "*:not(script, style, head)", false, true, true, {});
2450
2704
  if (result.elementCount > 0) {
2451
2705
  const dataAttribute = "[data-blinq-id-" + result.randomToken + "]";
2452
2706
  await this._highlightElements(frame, dataAttribute);
@@ -2487,9 +2741,33 @@ class StableBrowser {
2487
2741
  await _commandError(state, e, this);
2488
2742
  }
2489
2743
  finally {
2490
- _commandFinally(state, this);
2744
+ await _commandFinally(state, this);
2491
2745
  }
2492
2746
  }
2747
+ async findRelatedTextInAllFrames(textAnchor, climb, textToVerify, params = {}, options = {}, world = null) {
2748
+ const frames = this.page.frames();
2749
+ let results = [];
2750
+ let ignoreCase = false;
2751
+ for (let i = 0; i < frames.length; i++) {
2752
+ const result = await this._locateElementByText(frames[i], textAnchor, "*:not(script, style, head)", false, true, ignoreCase, {});
2753
+ result.frame = frames[i];
2754
+ const climbArray = [];
2755
+ for (let i = 0; i < climb; i++) {
2756
+ climbArray.push("..");
2757
+ }
2758
+ let climbXpath = "xpath=" + climbArray.join("/");
2759
+ const newLocator = `[data-blinq-id-${result.randomToken}] ${climb > 0 ? ">> " + climbXpath : ""} >> internal:text=${testForRegex(textToVerify) ? textToVerify : unEscapeString(textToVerify)}`;
2760
+ const count = await frames[i].locator(newLocator).count();
2761
+ if (count > 0) {
2762
+ result.elementCount = count;
2763
+ result.locator = newLocator;
2764
+ results.push(result);
2765
+ }
2766
+ }
2767
+ // state.info.results = results;
2768
+ const resultWithElementsFound = results.filter((result) => result.elementCount > 0);
2769
+ return resultWithElementsFound;
2770
+ }
2493
2771
  async visualVerification(text, options = {}, world = null) {
2494
2772
  const startTime = Date.now();
2495
2773
  let error = null;
@@ -2508,10 +2786,13 @@ class StableBrowser {
2508
2786
  ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2509
2787
  info.screenshotPath = screenshotPath;
2510
2788
  const screenshot = await this.takeScreenshot();
2511
- const request = {
2512
- method: "POST",
2789
+ let request = {
2790
+ method: "post",
2791
+ maxBodyLength: Infinity,
2513
2792
  url: `${serviceUrl}/api/runs/screenshots/validate-screenshot`,
2514
2793
  headers: {
2794
+ "x-bvt-project-id": path.basename(this.project_path),
2795
+ "x-source": "aaa",
2515
2796
  "Content-Type": "application/json",
2516
2797
  Authorization: `Bearer ${process.env.TOKEN}`,
2517
2798
  },
@@ -2520,7 +2801,7 @@ class StableBrowser {
2520
2801
  screenshot: screenshot,
2521
2802
  }),
2522
2803
  };
2523
- let result = await this.context.api.request(request);
2804
+ const result = await axios.request(request);
2524
2805
  if (result.data.status !== true) {
2525
2806
  throw new Error("Visual validation failed");
2526
2807
  }
@@ -2548,6 +2829,7 @@ class StableBrowser {
2548
2829
  _reportToWorld(world, {
2549
2830
  type: Types.VERIFY_VISUAL,
2550
2831
  text: "Visual verification",
2832
+ _text: "Visual verification of " + text,
2551
2833
  screenshotId,
2552
2834
  result: error
2553
2835
  ? {
@@ -2814,6 +3096,15 @@ class StableBrowser {
2814
3096
  }
2815
3097
  return timeout;
2816
3098
  }
3099
+ _getFindElementTimeout(options) {
3100
+ if (options && options.timeout) {
3101
+ return options.timeout;
3102
+ }
3103
+ if (this.configuration.find_element_timeout) {
3104
+ return this.configuration.find_element_timeout;
3105
+ }
3106
+ return 30000;
3107
+ }
2817
3108
  async saveStoreState(path = null, world = null) {
2818
3109
  const storageState = await this.page.context().storageState();
2819
3110
  //const testDataFile = _getDataFile(world, this.context, this);
@@ -2825,6 +3116,15 @@ class StableBrowser {
2825
3116
  await this.setTestData({ storageState: storageState }, world);
2826
3117
  }
2827
3118
  }
3119
+ async restoreSaveState(path = null, world = null) {
3120
+ await refreshBrowser(this, path, world);
3121
+ this.registerEventListeners(this.context);
3122
+ registerNetworkEvents(this.world, this, this.context, this.page);
3123
+ registerDownloadEvent(this.page, this.world, this.context);
3124
+ if (this.onRestoreSaveState) {
3125
+ this.onRestoreSaveState(path);
3126
+ }
3127
+ }
2828
3128
  async waitForPageLoad(options = {}, world = null) {
2829
3129
  let timeout = this._getLoadTimeout(options);
2830
3130
  const promiseArray = [];
@@ -2892,6 +3192,7 @@ class StableBrowser {
2892
3192
  highlight: false,
2893
3193
  type: Types.CLOSE_PAGE,
2894
3194
  text: `Close page`,
3195
+ _text: `Close the page`,
2895
3196
  operation: "closePage",
2896
3197
  log: "***** close page *****\n",
2897
3198
  throwError: false,
@@ -2905,11 +3206,98 @@ class StableBrowser {
2905
3206
  await _commandError(state, e, this);
2906
3207
  }
2907
3208
  finally {
2908
- _commandFinally(state, this);
3209
+ await _commandFinally(state, this);
3210
+ }
3211
+ }
3212
+ async tableCellOperation(headerText, rowText, options, _params, world = null) {
3213
+ let operation = null;
3214
+ if (!options || !options.operation) {
3215
+ throw new Error("operation is not defined");
3216
+ }
3217
+ operation = options.operation;
3218
+ // validate operation is one of the supported operations
3219
+ if (operation != "click" && operation != "hover+click") {
3220
+ throw new Error("operation is not supported");
3221
+ }
3222
+ const state = {
3223
+ options,
3224
+ world,
3225
+ locate: false,
3226
+ scroll: false,
3227
+ highlight: false,
3228
+ type: Types.TABLE_OPERATION,
3229
+ text: `Table operation`,
3230
+ _text: `Table ${operation} operation`,
3231
+ operation: operation,
3232
+ log: "***** Table operation *****\n",
3233
+ };
3234
+ const timeout = this._getFindElementTimeout(options);
3235
+ try {
3236
+ await _preCommand(state, this);
3237
+ const start = Date.now();
3238
+ let cellArea = null;
3239
+ while (true) {
3240
+ try {
3241
+ cellArea = await _findCellArea(headerText, rowText, this, state);
3242
+ if (cellArea) {
3243
+ break;
3244
+ }
3245
+ }
3246
+ catch (e) {
3247
+ // ignore
3248
+ }
3249
+ if (Date.now() - start > timeout) {
3250
+ throw new Error(`Cell not found in table`);
3251
+ }
3252
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3253
+ }
3254
+ switch (operation) {
3255
+ case "click":
3256
+ if (!options.css) {
3257
+ // will click in the center of the cell
3258
+ let xOffset = 0;
3259
+ let yOffset = 0;
3260
+ if (options.xOffset) {
3261
+ xOffset = options.xOffset;
3262
+ }
3263
+ if (options.yOffset) {
3264
+ yOffset = options.yOffset;
3265
+ }
3266
+ await this.page.mouse.click(cellArea.x + cellArea.width / 2 + xOffset, cellArea.y + cellArea.height / 2 + yOffset);
3267
+ }
3268
+ else {
3269
+ const results = await findElementsInArea(options.css, cellArea, this, options);
3270
+ if (results.length === 0) {
3271
+ throw new Error(`Element not found in cell area`);
3272
+ }
3273
+ state.element = results[0];
3274
+ await performAction("click", state.element, options, this, state, _params);
3275
+ }
3276
+ break;
3277
+ case "hover+click":
3278
+ if (!options.css) {
3279
+ throw new Error("css is not defined");
3280
+ }
3281
+ const results = await findElementsInArea(options.css, cellArea, this, options);
3282
+ if (results.length === 0) {
3283
+ throw new Error(`Element not found in cell area`);
3284
+ }
3285
+ state.element = results[0];
3286
+ await performAction("hover+click", state.element, options, this, state, _params);
3287
+ break;
3288
+ default:
3289
+ throw new Error("operation is not supported");
3290
+ }
3291
+ }
3292
+ catch (e) {
3293
+ await _commandError(state, e, this);
3294
+ }
3295
+ finally {
3296
+ await _commandFinally(state, this);
2909
3297
  }
2910
3298
  }
2911
3299
  saveTestDataAsGlobal(options, world) {
2912
- const dataFile = this._getDataFile(world);
3300
+ const dataFile = _getDataFile(world, this.context, this);
2913
3301
  process.env.GLOBAL_TEST_DATA_FILE = dataFile;
2914
3302
  this.logger.info("Save the scenario test data as global for the following scenarios.");
2915
3303
  }
@@ -2939,6 +3327,7 @@ class StableBrowser {
2939
3327
  _reportToWorld(world, {
2940
3328
  type: Types.SET_VIEWPORT,
2941
3329
  text: "set viewport size to " + width + "x" + hight,
3330
+ _text: "Set the viewport size to " + width + "x" + hight,
2942
3331
  screenshotId,
2943
3332
  result: error
2944
3333
  ? {
@@ -3009,7 +3398,39 @@ class StableBrowser {
3009
3398
  console.log("#-#");
3010
3399
  }
3011
3400
  }
3401
+ async beforeScenario(world, scenario) {
3402
+ this.beforeScenarioCalled = true;
3403
+ if (scenario && scenario.pickle && scenario.pickle.name) {
3404
+ this.scenarioName = scenario.pickle.name;
3405
+ }
3406
+ if (scenario && scenario.gherkinDocument && scenario.gherkinDocument.feature) {
3407
+ this.featureName = scenario.gherkinDocument.feature.name;
3408
+ }
3409
+ if (this.context) {
3410
+ this.context.examplesRow = extractStepExampleParameters(scenario);
3411
+ }
3412
+ if (this.tags === null && scenario && scenario.pickle && scenario.pickle.tags) {
3413
+ this.tags = scenario.pickle.tags.map((tag) => tag.name);
3414
+ // check if @global_test_data tag is present
3415
+ if (this.tags.includes("@global_test_data")) {
3416
+ this.saveTestDataAsGlobal({}, world);
3417
+ }
3418
+ }
3419
+ // update test data based on feature/scenario
3420
+ let envName = null;
3421
+ if (this.context && this.context.environment) {
3422
+ envName = this.context.environment.name;
3423
+ }
3424
+ if (!process.env.TEMP_RUN) {
3425
+ await getTestData(envName, world, undefined, this.featureName, this.scenarioName);
3426
+ }
3427
+ await loadBrunoParams(this.context, this.context.environment.name);
3428
+ }
3429
+ async afterScenario(world, scenario) { }
3012
3430
  async beforeStep(world, step) {
3431
+ if (!this.beforeScenarioCalled) {
3432
+ this.beforeScenario(world, step);
3433
+ }
3013
3434
  if (this.stepIndex === undefined) {
3014
3435
  this.stepIndex = 0;
3015
3436
  }
@@ -3026,22 +3447,48 @@ class StableBrowser {
3026
3447
  else {
3027
3448
  this.stepName = "step " + this.stepIndex;
3028
3449
  }
3029
- if (this.context) {
3030
- this.context.examplesRow = extractStepExampleParameters(step);
3031
- }
3032
3450
  if (this.context && this.context.browserObject && this.context.browserObject.trace === true) {
3033
3451
  if (this.context.browserObject.context) {
3034
3452
  await this.context.browserObject.context.tracing.startChunk({ title: this.stepName });
3035
3453
  }
3036
3454
  }
3037
- if (this.tags === null && step && step.pickle && step.pickle.tags) {
3038
- this.tags = step.pickle.tags.map((tag) => tag.name);
3039
- // check if @global_test_data tag is present
3040
- if (this.tags.includes("@global_test_data")) {
3041
- this.saveTestDataAsGlobal({}, world);
3455
+ if (this.initSnapshotTaken === false) {
3456
+ this.initSnapshotTaken = true;
3457
+ if (world && world.attach && !process.env.DISABLE_SNAPSHOT) {
3458
+ const snapshot = await this.getAriaSnapshot();
3459
+ if (snapshot) {
3460
+ await world.attach(JSON.stringify(snapshot), "application/json+snapshot-before");
3461
+ }
3042
3462
  }
3043
3463
  }
3044
3464
  }
3465
+ async getAriaSnapshot() {
3466
+ try {
3467
+ // find the page url
3468
+ const url = await this.page.url();
3469
+ // extract the path from the url
3470
+ const path = new URL(url).pathname;
3471
+ // get the page title
3472
+ const title = await this.page.title();
3473
+ // go over other frams
3474
+ const frames = this.page.frames();
3475
+ const snapshots = [];
3476
+ const content = [`- path: ${path}`, `- title: ${title}`];
3477
+ const timeout = this.configuration.ariaSnapshotTimeout ? this.configuration.ariaSnapshotTimeout : 3000;
3478
+ for (let i = 0; i < frames.length; i++) {
3479
+ content.push(`- frame: ${i}`);
3480
+ const frame = frames[i];
3481
+ const snapshot = await frame.locator("body").ariaSnapshot({ timeout });
3482
+ content.push(snapshot);
3483
+ }
3484
+ return content.join("\n");
3485
+ }
3486
+ catch (e) {
3487
+ console.log("Error in getAriaSnapshot");
3488
+ console.debug(e);
3489
+ }
3490
+ return null;
3491
+ }
3045
3492
  async afterStep(world, step) {
3046
3493
  this.stepName = null;
3047
3494
  if (this.context && this.context.browserObject && this.context.browserObject.trace === true) {
@@ -3049,11 +3496,25 @@ class StableBrowser {
3049
3496
  await this.context.browserObject.context.tracing.stopChunk({
3050
3497
  path: path.join(this.context.browserObject.traceFolder, `trace-${this.stepIndex}.zip`),
3051
3498
  });
3499
+ if (world && world.attach) {
3500
+ await world.attach(JSON.stringify({
3501
+ type: "trace",
3502
+ traceFilePath: `trace-${this.stepIndex}.zip`,
3503
+ }), "application/json+trace");
3504
+ }
3505
+ // console.log("trace file created", `trace-${this.stepIndex}.zip`);
3052
3506
  }
3053
3507
  }
3054
3508
  if (this.context) {
3055
3509
  this.context.examplesRow = null;
3056
3510
  }
3511
+ if (world && world.attach && !process.env.DISABLE_SNAPSHOT) {
3512
+ const snapshot = await this.getAriaSnapshot();
3513
+ if (snapshot) {
3514
+ const obj = {};
3515
+ await world.attach(JSON.stringify(snapshot), "application/json+snapshot-after");
3516
+ }
3517
+ }
3057
3518
  }
3058
3519
  }
3059
3520
  function createTimedPromise(promise, label) {