How to use retryIfEnabled method of com.intuit.karate.driver.WebDriver class

Best Karate code snippet using com.intuit.karate.driver.WebDriver.retryIfEnabled

Source:WebDriver.java Github

copy

Full Screen

...86 }87 private String getSubmitHash() {88 return getUrl() + elementId("html");89 }90 protected <T> T retryIfEnabled(String locator, Supplier<T> action) {91 if (options.isRetryEnabled()) {92 waitFor(locator); // will throw exception if not found93 }94 if (options.highlight) {95 highlight(locator, options.highlightDuration);96 }97 String before = options.getPreSubmitHash();98 if (before != null) {99 logger.trace("submit requested, will wait for page load after next action on : {}", locator);100 options.setPreSubmitHash(null); // clear the submit flag101 T result = action.get();102 Integer retryInterval = options.getRetryInterval();103 options.setRetryInterval(500); // reduce retry interval for this special case104 options.retry(() -> getSubmitHash(), hash -> !before.equals(hash), "waiting for document to change", false);105 options.setRetryInterval(retryInterval); // restore106 return result;107 } else {108 return action.get();109 }110 }111 protected boolean isJavaScriptError(Response res) {112 return res.getStatus() != 200113 && !res.json().<String>get("value").contains("unexpected alert open");114 }115 protected boolean isLocatorError(Response res) {116 return res.getStatus() != 200;117 }118 protected boolean isCookieError(Response res) {119 return res.getStatus() != 200;120 }121 private Element evalLocator(String locator, String dotExpression) {122 eval(prefixReturn(DriverOptions.selector(locator) + "." + dotExpression));123 // if the js above did not throw an exception, the element exists124 return DriverElement.locatorExists(this, locator);125 }126 private Element evalFocus(String locator) {127 eval(options.focusJs(locator));128 // if the js above did not throw an exception, the element exists129 return DriverElement.locatorExists(this, locator);130 }131 protected Variable eval(String expression, List args) {132 Json json = Json.object().set("script", expression).set("args", (args == null) ? Collections.EMPTY_LIST : args);133 Response res = http.path("execute", "sync").post(json);134 if (isJavaScriptError(res)) {135 logger.warn("javascript failed, will retry once: {}", res.getBodyAsString());136 options.sleep();137 res = http.path("execute", "sync").post(json);138 if (isJavaScriptError(res)) {139 String message = "javascript failed twice: " + res.getBodyAsString();140 logger.error(message);141 throw new RuntimeException(message);142 }143 }144 return new Variable(res.json().get("value"));145 }146 protected Variable eval(String expression) {147 return eval(expression, null);148 }149 protected List<String> getElementKeys() {150 // "element-6066-11e4-a52e-4f735466cecf" is the key to element in the W3C WebDriver standard151 // "ELEMENT" is a deviation from the W3C standard152 // explanation can be found here: https://github.com/karatelabs/karate/issues/1840#issuecomment-974688715153 return Arrays.asList("element-6066-11e4-a52e-4f735466cecf", "ELEMENT");154 }155 protected String getJsonForInput(String text) {156 return Json.object().set("text", text).toString();157 }158 protected String getJsonForLegacyInput(String text) {159 return Json.of("{ value: [ '" + text + "' ] }").toString();160 }161 protected String getJsonForHandle(String text) {162 return Json.object().set("handle", text).toString();163 }164 protected String getJsonForFrame(String text) {165 return Json.object().set("id", text).toString();166 }167 protected String selectorPayload(String locator) {168 if (locator.startsWith("{")) {169 locator = DriverOptions.preProcessWildCard(locator);170 }171 Json json = Json.object();172 if (locator.startsWith("/")) {173 json.set("using", "xpath").set("value", locator);174 } else {175 json.set("using", "css selector").set("value", locator);176 }177 return json.toString();178 }179 @Override180 public String elementId(String locator) {181 String json = selectorPayload(locator);182 Response res = http.path("element").postJson(json);183 if (isLocatorError(res)) {184 logger.warn("locator failed, will retry once: {}", res.getBodyAsString());185 options.sleep();186 res = http.path("element").postJson(json);187 if (isLocatorError(res)) {188 String message = "locator failed twice: " + res.getBodyAsString();189 logger.error(message);190 throw new RuntimeException(message);191 }192 }193 List<String> resultElements = res.json().<List<String>>get("$..", getElementKeys()).stream()194 .flatMap(List::stream)195 .collect(Collectors.toList());196 String resultElement = resultElements != null && !resultElements.isEmpty() ? resultElements.get(0) : null;197 if (resultElement == null) {198 String message = "locator failed to retrieve element returned by target driver: " + res.getBodyAsString();199 logger.error(message);200 throw new RuntimeException(message);201 }202 return resultElement;203 }204 @Override205 public List<String> elementIds(String locator) {206 return http.path("elements")207 .postJson(selectorPayload(locator)).json()208 .<List<String>>get("$..", getElementKeys()).stream()209 .flatMap(List::stream)210 .collect(Collectors.toList());211 }212 @Override213 public DriverOptions getOptions() {214 return options;215 }216 @Override217 public void setUrl(String url) {218 Json json = Json.object().set("url", url);219 http.path("url").post(json);220 }221 @Override222 public Map<String, Object> getDimensions() {223 return http.path("window", "rect").get().json().get("value");224 }225 @Override226 public void setDimensions(Map<String, Object> map) {227 http.path("window", "rect").post(map);228 }229 @Override230 public void refresh() {231 http.path("refresh").postJson("{}");232 }233 @Override234 public void reload() {235 // not supported by webdriver236 refresh();237 }238 @Override239 public void back() {240 http.path("back").postJson("{}");241 }242 @Override243 public void forward() {244 http.path("forward").postJson("{}");245 }246 @Override247 public void maximize() {248 http.path("window", "maximize").postJson("{}");249 }250 @Override251 public void minimize() {252 http.path("window", "minimize").postJson("{}");253 }254 @Override255 public void fullscreen() {256 http.path("window", "fullscreen").postJson("{}");257 }258 @Override259 public Element focus(String locator) {260 return retryIfEnabled(locator, () -> evalFocus(locator));261 }262 @Override263 public Element clear(String locator) {264 return retryIfEnabled(locator, () -> evalLocator(locator, "value = ''"));265 }266 @Override267 public Element input(String locator, String value) {268 return retryIfEnabled(locator, () -> {269 String elementId;270 if (locator.startsWith("(")) {271 evalFocus(locator);272 List<String> elements = http.path("element", "active").get()273 .json().<List<String>>get("$..", getElementKeys()).stream()274 .flatMap(List::stream)275 .collect(Collectors.toList());;276 elementId = elements != null && !elements.isEmpty() ? elements.get(0) : null;277 } else {278 elementId = elementId(locator);279 }280 Response response = http.path("element", elementId, "value").postJson(isSpecCompliant() ? getJsonForInput(value) : getJsonForLegacyInput(value));281 if (checkForSpecCompliance()) {282 if (response.json().get("$.value") != null) {283 String responseMessage = response.json().get("$.value.message");284 if (responseMessage.contains("invalid argument: 'value' must be a list")) {285 http.path("element", elementId, "value").postJson(getJsonForLegacyInput(value));286 specCompliant = false;287 } else {288 specCompliant = true;289 }290 } else {291 // did not complain that value should be a list so assume W3C WebDriver compliant moving forward292 specCompliant = true;293 }294 }295 return DriverElement.locatorExists(this, locator);296 });297 }298 @Override299 public Element click(String locator) {300 return retryIfEnabled(locator, () -> evalLocator(locator, "click()"));301 }302 @Override303 public Driver submit() {304 options.setPreSubmitHash(getSubmitHash());305 return this;306 }307 @Override308 public Element select(String locator, String text) {309 return retryIfEnabled(locator, () -> {310 eval(options.optionSelector(locator, text));311 // if the js above did not throw an exception, the element exists312 return DriverElement.locatorExists(this, locator);313 });314 }315 @Override316 public Element select(String locator, int index) {317 return retryIfEnabled(locator, () -> {318 eval(options.optionSelector(locator, index));319 // if the js above did not throw an exception, the element exists320 return DriverElement.locatorExists(this, locator);321 });322 }323 @Override324 public void actions(List<Map<String, Object>> actions) {325 http.path("actions").post(Collections.singletonMap("actions", actions));326 }327 @Override328 public void close() {329 http.path("window").delete();330 open = false;331 }332 @Override333 public boolean isTerminated() {334 return terminated;335 }336 public boolean isSpecCompliant() {337 return specCompliant == null || specCompliant;338 }339 public boolean checkForSpecCompliance() {340 return specCompliant == null;341 }342 @Override343 public void quit() {344 if (terminated) {345 return;346 }347 terminated = true;348 if (open) {349 close();350 }351 // delete session352 try {353 http.delete();354 } catch (Exception e) {355 logger.warn("session delete failed: {}", e.getMessage());356 }357 if (command != null) {358 command.close(true);359 }360 }361 @Override362 public String getUrl() {363 return http.path("url").get().json().get("value");364 }365 private String evalReturn(String locator, String dotExpression) {366 return eval("return " + DriverOptions.selector(locator) + "." + dotExpression).getAsString();367 }368 @Override369 public String html(String locator) {370 return retryIfEnabled(locator, () -> evalReturn(locator, "outerHTML"));371 }372 @Override373 public String text(String locator) {374 return retryIfEnabled(locator, () -> evalReturn(locator, "textContent"));375 }376 @Override377 public String value(String locator) {378 return retryIfEnabled(locator, () -> evalReturn(locator, "value"));379 }380 @Override381 public Element value(String locator, String value) {382 return retryIfEnabled(locator, () -> evalLocator(locator, "value = '" + value + "'"));383 }384 @Override385 public String attribute(String locator, String name) {386 return retryIfEnabled(locator, () -> evalReturn(locator, "getAttribute('" + name + "')"));387 }388 @Override389 public String property(String locator, String name) {390 return retryIfEnabled(locator, () -> evalReturn(locator, name));391 }392 @Override393 public Map<String, Object> position(String locator) {394 return position(locator, false);395 }396 @Override397 public Map<String, Object> position(String locator, boolean relative) {398 return retryIfEnabled(locator, ()399 -> eval("return " + DriverOptions.selector(locator) + ".getBoundingClientRect()").getValue());400 }401 @Override402 public boolean enabled(String locator) {403 return retryIfEnabled(locator, ()404 -> eval("return !" + DriverOptions.selector(locator) + ".disabled").isTrue());405 }406 private String prefixReturn(String expression) {407 return expression.startsWith("return ") ? expression : "return " + expression;408 }409 @Override410 public boolean waitUntil(String expression) {411 return options.retry(() -> {412 try {413 return eval(prefixReturn(expression)).isTrue();414 } catch (Exception e) {415 logger.warn("waitUntil evaluate failed: {}", e.getMessage());416 return false;417 }418 }, b -> b, "waitUntil (js)", true);419 }420 @Override421 public Object script(String expression) {422 expression = prefixReturn(expression);423 return eval(expression).getValue();424 }425 @Override426 public String getTitle() {427 return http.path("title").get().json().get("value");428 }429 @Override430 public List<Map> getCookies() {431 return http.path("cookie").get().json().get("value");432 }433 @Override434 public Map<String, Object> cookie(String name) {435 return http.path("cookie", name).get().json().get("value");436 }437 @Override438 public void cookie(Map<String, Object> cookie) {439 Response res = http.path("cookie").post(Collections.singletonMap("cookie", cookie));440 if (isCookieError(res)) {441 throw new RuntimeException("set-cookie failed: " + res.getBodyAsString());442 }443 }444 @Override445 public void deleteCookie(String name) {446 http.path("cookie", name).delete();447 }448 @Override449 public void clearCookies() {450 http.path("cookie").delete();451 }452 @Override453 public void dialog(boolean accept) {454 dialog(accept, null);455 }456 @Override457 public String getDialogText() {458 return http.path("alert", "text").get().json().get("value");459 }460 @Override461 public void dialog(boolean accept, String text) {462 if (text == null) {463 http.path("alert", accept ? "accept" : "dismiss").postJson("{}");464 } else {465 http.path("alert", "text").post(Collections.singletonMap("text", text));466 http.path("alert", "accept").postJson("{}");467 }468 }469 @Override470 public byte[] screenshot(boolean embed) {471 return screenshot(null, embed);472 }473 @Override474 public byte[] screenshot(String locator, boolean embed) {475 String temp;476 if (locator == null) {477 temp = http.path("screenshot").get().json().get("value");478 } else {479 temp = retryIfEnabled(locator, () -> {480 String id = elementId(locator);481 return http.path("element", id, "screenshot").get().json().get("value");482 });483 }484 byte[] bytes = getDecoder().decode(temp);485 if (embed) {486 getRuntime().embed(bytes, ResourceType.PNG);487 }488 return bytes;489 }490 @Override491 public List<String> getPages() {492 return http.path("window", "handles").get().json().get("value");493 }494 @Override495 public void switchPage(String titleOrUrl) {496 if (titleOrUrl == null) {497 return;498 }499 options.retry(() -> {500 for (String handle : getPages()) {501 http.path("window").postJson(getJsonForHandle(handle));502 String title = getTitle();503 if (title != null && title.contains(titleOrUrl)) {504 return true;505 }506 String url = getUrl();507 if (url != null && url.contains(titleOrUrl)) {508 return true;509 }510 }511 return false;512 }, returned -> returned, "waiting to switch to tab: " + titleOrUrl, true);513 }514 @Override515 public void switchPage(int index) {516 if (index == -1) {517 return;518 }519 String json = Json.object().set("id", index).toString();520 http.path("window").postJson(json);521 }522 @Override523 public void switchFrame(int index) {524 if (index == -1) {525 http.path("frame", "parent").postJson("{}");526 return;527 }528 String json = Json.object().set("id", index).toString();529 http.path("frame").postJson(json);530 }531 @Override532 public void switchFrame(String locator) {533 if (locator == null) { // reset to parent frame534 http.path("frame", "parent").postJson("{}");535 return;536 }537 retryIfEnabled(locator, () -> {538 String frameId = elementId(locator);539 if (frameId == null) {540 return null;541 }542 List<String> ids = elementIds("iframe,frame");543 for (int i = 0; i < ids.size(); i++) {544 String id = ids.get(i);545 if (frameId.equals(id)) {546 switchFrame(i);547 break;548 }549 }550 return null;551 });...

Full Screen

Full Screen

retryIfEnabled

Using AI Code Generation

copy

Full Screen

1* def driver = { karate.callSingle('classpath:com/intuit/karate/driver/driver.feature') }2* def retryIfEnabled = { driver.retryIfEnabled() }3* def driver = { karate.callSingle('classpath:com/intuit/karate/driver/driver.feature') }4* def retryIfEnabled = { driver.retryIfEnabled() }5* def driver = { karate.callSingle('classpath:com/intuit/karate/driver/driver.feature') }6* def retryIfEnabled = { driver.retryIfEnabled() }7* def driver = { karate.callSingle('classpath:com/intuit/karate/driver/driver.feature') }8* def retryIfEnabled = { driver.retryIfEnabled() }9* def driver = { karate.callSingle('classpath:com/intuit/karate/driver/driver.feature') }10* def retryIfEnabled = { driver.retryIfEnabled() }11* def driver = { karate.callSingle('classpath:com/intuit/karate/driver/driver.feature') }12* def retryIfEnabled = { driver.retryIfEnabled() }13* def driver = { karate.callSingle('classpath:com/intuit/karate/driver/driver.feature') }14* def retryIfEnabled = { driver.retryIfEnabled() }15* def driver = { karate.callSingle('classpath:com/intuit/karate/driver/driver.feature') }16* def retryIfEnabled = { driver.retryIfEnabled() }17* def driver = { karate.callSingle('classpath:com/intuit/karate/driver/driver.feature') }18* def retryIfEnabled = { driver.retryIfEnabled() }19* def driver = { karate.callSingle('classpath:com/intuit/karate/driver/driver.feature') }20* def retryIfEnabled = { driver.retryIfEnabled() }21* def driver = { karate.callSingle('classpath:com/intuit/karate/driver/driver.feature') }22* def retryIfEnabled = { driver.retryIfEnabled() }23* def driver = { karate.callSingle('classpath:com/intuit/karate/driver/driver.feature') }24* def retryIfEnabled = { driver.retryIfEnabled() }25* def driver = { karate.callSingle('classpath:com/intuit/karate/driver/driver.feature') }26* def retryIfEnabled = { driver.retryIfEnabled() }

Full Screen

Full Screen

retryIfEnabled

Using AI Code Generation

copy

Full Screen

1def config = read('classpath:karate-config.js')2def driver = Java.type('com.intuit.karate.driver.WebDriver').start(config)3def config = read('classpath:karate-config.js')4def driver = Java.type('com.intuit.karate.driver.AppiumDriver').start(config)5def config = read('classpath:karate-config.js')6def driver = Java.type('com.intuit.karate.driver.SelenoidDriver').start(config)7def config = read('classpath:karate-config.js')8def driver = Java.type('com.intuit.karate.driver.SelenoidMobileDriver').start(config)9def config = read('classpath:karate-config.js')10def driver = Java.type('com.intuit.karate.driver.TestObjectDriver').start(config)11def config = read('classpath:karate-config.js')12def driver = Java.type('com.intuit.karate.driver.TestObjectMobileDriver').start(config)13def config = read('classpath:karate-config.js')14def driver = Java.type('com.intuit.karate.driver.SauceLabsDriver').start(config)15def config = read('classpath:karate-config.js')16def driver = Java.type('com.intuit.karate.driver.SauceLabsMobileDriver').start(config)

Full Screen

Full Screen

retryIfEnabled

Using AI Code Generation

copy

Full Screen

1* def driver = karate.getWebDriver()2* retryIfEnabled(3, { driver.findElement({ name: 'q' }).sendKeys('karate') })3* retryIfEnabled(3, { driver.findElement({ name: 'btnK' }).click() })4* retryIfEnabled(3, { driver.findElement({ id: 'resultStats' }) })5* retryIfEnabled(3, { driver.quit() })6def driver = karate.getWebDriver()7retryIfEnabled(3, { driver.findElement({ name: 'q' }).sendKeys('karate') })8retryIfEnabled(3, { driver.findElement({ name: 'btnK' }).click() })9retryIfEnabled(3, { driver.findElement({ id: 'resultStats' }) })10retryIfEnabled(3, { driver.quit() })11function fn() {12 var driver = karate.getWebDriver()13 retryIfEnabled(3, { driver.findElement({ name: 'q' }).sendKeys('karate') })14 retryIfEnabled(3, { driver.findElement({ name: 'btnK' }).click() })15 retryIfEnabled(3, { driver.findElement({ id: 'resultStats' }) })16 retryIfEnabled(3, { driver.quit() })17}18function fn() {19 var driver = karate.getWebDriver()

Full Screen

Full Screen

retryIfEnabled

Using AI Code Generation

copy

Full Screen

1* driver.retryIfEnabled()2* driver.retryIfEnabled()3* driver.retryIfEnabled()4* driver.retryIfEnabled()5* driver.retryIfEnabled()6* driver.retryIfEnabled()7* driver.retryIfEnabled()8* driver.retryIfEnabled()9* driver.retryIfEnabled()10* driver.retryIfEnabled()11* driver.retryIfEnabled()

Full Screen

Full Screen

retryIfEnabled

Using AI Code Generation

copy

Full Screen

1* def driver = karate.driver('chrome')2* driver.findElement('name', 'q').sendKeys('karate')3* driver.findElement('name', 'btnK').click()4* driver.findElement('id', 'resultStats').text contains 'About'5* driver.quit()6* def driver = karate.driver('chrome')7* driver.findElement('name', 'q').sendKeys('karate')8* driver.findElement('name', 'btnK').click()9* driver.findElement('id', 'resultStats').text contains 'About'10* driver.quit()11* def driver = karate.driver('chrome')12* driver.findElement('name', 'q').sendKeys('karate')13* driver.findElement('name', 'btnK').click()14* driver.findElement('id', 'resultStats').text contains 'About'15* driver.quit()16* def driver = karate.driver('chrome')17* driver.findElement('name', 'q').sendKeys('karate')18* driver.findElement('name', 'btnK').click()19* driver.findElement('id', 'resultStats').text contains 'About'20* driver.quit()21* def driver = karate.driver('chrome')22* driver.findElement('name', 'q').sendKeys('karate')

Full Screen

Full Screen

retryIfEnabled

Using AI Code Generation

copy

Full Screen

1* retryIfEnabled(2) { 2}3* retryIfEnabled(2) { 4 * retryIfEnabled(2) { 5 }6}7* retryIfEnabled(2) { 8 * retryIfEnabled(2) { 9 }10}11* retryIfEnabled(2) { 12 * retryIfEnabled(2) { 13 }14}

Full Screen

Full Screen

retryIfEnabled

Using AI Code Generation

copy

Full Screen

1* def driver = { WebDriver driver ->2 driver.retryIfEnabled { WebElement element ->3 }4}5* def driver = { WebDriver driver ->6 driver.retryIfEnabled { WebElement element ->7 }8}9* def driver = { WebDriver driver ->10 driver.retryIfEnabled { WebElement element ->11 }12}13* def driver = { WebDriver driver ->14 driver.retryIfEnabled { WebElement element ->15 }16}17* def driver = { WebDriver driver ->18 driver.retryIfEnabled { WebElement element ->19 }20}21* def driver = { WebDriver driver ->22 driver.retryIfEnabled { WebElement element ->23 }24}25* def driver = { WebDriver driver ->26 driver.retryIfEnabled { WebElement element ->27 }28}29* def driver = { WebDriver driver ->30 driver.retryIfEnabled { WebElement element ->31 }32}33* def driver = { WebDriver driver ->34 driver.retryIfEnabled { WebElement element ->35 }36}37* def driver = { WebDriver driver ->38 driver.retryIfEnabled { WebElement element ->39 }40}41* def driver = { WebDriver driver ->42 driver.retryIfEnabled { WebElement element ->43 }44}45* def driver = { WebDriver driver ->46 driver.retryIfEnabled { WebElement element ->47 }48}49* def driver = { WebDriver driver ->50 driver.retryIfEnabled { WebElement element ->

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful