Best Karate code snippet using com.intuit.karate.driver.DevToolsMessage.DevToolsMessage
Source:DevToolsDriver.java
...95 // to avoid swamping the console when large base64 encoded binary responses happen96 logger.debug("<< {}", StringUtils.truncate(text, 1024, true));97 }98 Map<String, Object> map = JsonUtils.toJsonDoc(text).read("$");99 DevToolsMessage dtm = new DevToolsMessage(this, map);100 receive(dtm);101 });102 client = new WebSocketClient(wsOptions, logger);103 }104 public int waitSync() {105 if (command == null) {106 return -1;107 }108 return command.waitSync();109 }110 @Override111 public Driver timeout(Integer millis) {112 options.setTimeout(millis);113 return this;114 }115 @Override116 public Driver timeout() {117 return timeout(null);118 }119 public DevToolsMessage method(String method) {120 return new DevToolsMessage(this, method);121 }122 // this can be used for exploring / sending any raw message !123 public Map<String, Object> send(Map<String, Object> map) {124 DevToolsMessage dtm = new DevToolsMessage(this, map);125 dtm.setId(nextId());126 return sendAndWait(dtm, null).toMap();127 }128 public void send(DevToolsMessage dtm) {129 String json = JsonUtils.toJson(dtm.toMap());130 logger.debug(">> {}", json);131 client.send(json);132 }133 public DevToolsMessage sendAndWait(DevToolsMessage dtm, Predicate<DevToolsMessage> condition) {134 boolean wasSubmit = submit;135 if (condition == null && submit) {136 submit = false;137 condition = DevToolsWait.ALL_FRAMES_LOADED;138 }139 //Do stuff inside wait to avoid missing messages140 DevToolsMessage result = wait.send(dtm, condition);141 if (result == null && !wasSubmit) {142 throw new RuntimeException("failed to get reply for: " + dtm);143 }144 return result;145 }146 public void receive(DevToolsMessage dtm) {147 if (dtm.methodIs("Page.domContentEventFired")) {148 domContentEventFired = true;149 logger.trace("** set dom ready flag to true");150 }151 if (dtm.methodIs("Page.javascriptDialogOpening")) {152 currentDialogText = dtm.getParam("message").getAsString();153 // this will stop waiting NOW154 wait.setCondition(DevToolsWait.DIALOG_OPENING);155 }156 if (dtm.methodIs("Page.frameNavigated")) {157 String frameNavId = dtm.get("frame.id", String.class);158 String frameNavUrl = dtm.get("frame.url", String.class);159 if (rootFrameId.equals(frameNavId)) { // root page navigated160 currentUrl = frameNavUrl;161 }162 }163 if (dtm.methodIs("Page.navigatedWithinDocument")) { // js variant of above (SPA, history nav)164 String frameNavId = dtm.get("frameId", String.class);165 String frameNavUrl = dtm.get("url", String.class);166 if (rootFrameId.equals(frameNavId)) { // root page navigated167 currentUrl = frameNavUrl;168 }169 }170 if (dtm.methodIs("Page.frameStartedLoading")) {171 String frameLoadingId = dtm.get("frameId", String.class);172 if (rootFrameId.equals(frameLoadingId)) { // root page is loading173 domContentEventFired = false;174 framesStillLoading.clear();175 frameSessions.clear();176 logger.trace("** root frame started loading, cleared all page state: {}", frameLoadingId);177 } else {178 framesStillLoading.add(frameLoadingId);179 logger.trace("** frame started loading, added to in-progress list: {}", framesStillLoading);180 }181 }182 if (dtm.methodIs("Page.frameStoppedLoading")) {183 String frameLoadedId = dtm.get("frameId", String.class);184 framesStillLoading.remove(frameLoadedId);185 logger.trace("** frame stopped loading: {}, remaining in-progress: {}", frameLoadedId, framesStillLoading);186 }187 if (dtm.methodIs("Target.attachedToTarget")) {188 frameSessions.put(dtm.get("targetInfo.targetId", String.class), dtm.get("sessionId", String.class));189 logger.trace("** added frame session: {}", frameSessions);190 }191 if (dtm.methodIs("Fetch.requestPaused")) {192 handleInterceptedRequest(dtm);193 }194 // all needed state is set above before we get into conditional checks195 wait.receive(dtm);196 }197 private void handleInterceptedRequest(DevToolsMessage dtm) {198 String requestId = dtm.get("requestId", String.class);199 String requestUrl = dtm.get("request.url", String.class);200 if (backend != null) {201 String method = dtm.get("request.method", String.class);202 Map<String, String> headers = dtm.get("request.headers", Map.class);203 String postData = dtm.get("request.postData", String.class);204 logger.debug("intercepting request for url: {}", requestUrl);205 HttpRequest request = new HttpRequest();206 // needed pre-processing for mock feature backend207 StringUtils.Pair pair = NettyUtils.parseUriIntoUrlBaseAndPath(requestUrl);208 request.setUrlBase(pair.left);209 request.setUri(pair.right);210 request.setMethod(method);211 String karateRequestId = System.identityHashCode(dtm) + "";212 MDC.put("karateRequestId", karateRequestId);213 request.setRequestId(karateRequestId);214 headers.forEach((k, v) -> request.addHeader(k, v));215 if (postData != null) {216 request.setBody(FileUtils.toBytes(postData));217 } else {218 request.setBody(FileUtils.EMPTY_BYTES);219 }220 HttpResponse response = backend.buildResponse(request, System.currentTimeMillis());221 String responseBody = response.getBody() == null ? "" : Base64.getEncoder().encodeToString(response.getBody());222 List<Map> responseHeaders = new ArrayList();223 MultiValuedMap mvm = response.getHeaders();224 if (mvm != null) {225 for (String name : mvm.keySet()) {226 Object value = mvm.getFirst(name);227 Map<String, Object> nv = new HashMap(2);228 nv.put("name", name);229 nv.put("value", value);230 responseHeaders.add(nv);231 }232 }233 method("Fetch.fulfillRequest")234 .param("requestId", requestId)235 .param("responseCode", response.getStatus())236 .param("responseHeaders", responseHeaders)237 .param("body", responseBody).sendWithoutWaiting();238 } else {239 logger.warn("no mock server, continuing paused request to url: {}", requestUrl);240 method("Fetch.continueRequest").param("requestId", requestId).sendWithoutWaiting();241 }242 }243 //==========================================================================244 //245 private DevToolsMessage evalOnce(String expression, boolean quickly, boolean fireAndForget) {246 DevToolsMessage toSend = method("Runtime.evaluate")247 .param("expression", expression).param("returnByValue", true);248 if (executionContextId != null) {249 toSend.param("contextId", executionContextId);250 }251 if (quickly) {252 toSend.setTimeout(options.getRetryInterval());253 }254 if (fireAndForget) {255 toSend.sendWithoutWaiting();256 return null;257 }258 return toSend.send();259 }260 protected DevToolsMessage eval(String expression) {261 return eval(expression, false);262 }263 private DevToolsMessage eval(String expression, boolean quickly) {264 DevToolsMessage dtm = evalOnce(expression, quickly, false);265 if (dtm.isResultError()) {266 String message = "js eval failed once:" + expression267 + ", error: " + dtm.getResult().getAsString();268 logger.warn(message);269 options.sleep();270 dtm = evalOnce(expression, quickly, false); // no wait condition for the re-try271 if (dtm.isResultError()) {272 message = "js eval failed twice:" + expression273 + ", error: " + dtm.getResult().getAsString();274 logger.error(message);275 throw new RuntimeException(message);276 }277 }278 return dtm;279 }280 protected void retryIfEnabled(String locator) {281 if (options.isRetryEnabled()) {282 waitFor(locator); // will throw exception if not found283 }284 if (options.highlight) {285 // highlight(locator, options.highlightDuration); // instead of this286 String highlightJs = options.highlight(locator, options.highlightDuration);287 evalOnce(highlightJs, true, true); // do it safely, i.e. fire and forget288 }289 }290 protected int getRootNodeId() {291 return method("DOM.getDocument").param("depth", 0).send().getResult("root.nodeId", Integer.class);292 }293 @Override294 public Integer elementId(String locator) {295 DevToolsMessage dtm = method("DOM.querySelector")296 .param("nodeId", getRootNodeId())297 .param("selector", locator).send();298 if (dtm.isResultError()) {299 return null;300 }301 return dtm.getResult("nodeId").getAsInt();302 }303 @Override304 public List elementIds(String locator) {305 if (locator.startsWith("/")) { // special handling for xpath306 getRootNodeId(); // just so that DOM.getDocument is called else DOM.performSearch fails307 DevToolsMessage dtm = method("DOM.performSearch").param("query", locator).send();308 String searchId = dtm.getResult("searchId", String.class);309 int resultCount = dtm.getResult("resultCount", Integer.class);310 dtm = method("DOM.getSearchResults")311 .param("searchId", searchId)312 .param("fromIndex", 0).param("toIndex", resultCount).send();313 return dtm.getResult("nodeIds", List.class);314 }315 DevToolsMessage dtm = method("DOM.querySelectorAll")316 .param("nodeId", getRootNodeId())317 .param("selector", locator).send();318 if (dtm.isResultError()) {319 return Collections.EMPTY_LIST;320 }321 return dtm.getResult("nodeIds").getAsList();322 }323 @Override324 public DriverOptions getOptions() {325 return options;326 }327 @Override328 public void activate() {329 method("Target.activateTarget").param("targetId", rootFrameId).send();330 }331 protected void initWindowIdAndState() {332 DevToolsMessage dtm = method("Browser.getWindowForTarget").param("targetId", rootFrameId).send();333 if (!dtm.isResultError()) {334 windowId = dtm.getResult("windowId").getValue(Integer.class);335 windowState = (String) dtm.getResult("bounds").getAsMap().get("windowState");336 }337 }338 @Override339 public Map<String, Object> getDimensions() {340 DevToolsMessage dtm = method("Browser.getWindowForTarget").param("targetId", rootFrameId).send();341 Map<String, Object> map = dtm.getResult("bounds").getAsMap();342 Integer x = (Integer) map.remove("left");343 Integer y = (Integer) map.remove("top");344 map.put("x", x);345 map.put("y", y);346 return map;347 }348 @Override349 public void setDimensions(Map<String, Object> map) {350 Integer left = (Integer) map.remove("x");351 Integer top = (Integer) map.remove("y");352 map.put("left", left);353 map.put("top", top);354 Map temp = getDimensions();355 temp.putAll(map);356 temp.remove("windowState");357 method("Browser.setWindowBounds")358 .param("windowId", windowId)359 .param("bounds", temp).send();360 }361 public void emulateDevice(int width, int height, String userAgent) {362 logger.info("Setting deviceMetrics width={}, height={}, userAgent={}", width, height, userAgent);363 method("Network.setUserAgentOverride").param("userAgent", userAgent).send();364 method("Emulation.setDeviceMetricsOverride")365 .param("width", width)366 .param("height", height)367 .param("deviceScaleFactor", 1)368 .param("mobile", true)369 .send();370 }371 @Override372 public void close() {373 method("Page.close").sendWithoutWaiting();374 }375 @Override376 public void quit() {377 if (terminated) {378 return;379 }380 terminated = true;381 // don't wait, may fail and hang382 method("Target.closeTarget").param("targetId", rootFrameId).sendWithoutWaiting();383 // method("Browser.close").send();384 client.close();385 if (command != null) {386 command.close(true);387 }388 }389 @Override390 public boolean isTerminated() {391 return terminated;392 }393 @Override394 public void setUrl(String url) {395 method("Page.navigate").param("url", url)396 .send(DevToolsWait.ALL_FRAMES_LOADED);397 }398 @Override399 public void refresh() {400 method("Page.reload").send(DevToolsWait.ALL_FRAMES_LOADED);401 }402 @Override403 public void reload() {404 method("Page.reload").param("ignoreCache", true).send();405 }406 private void history(int delta) {407 DevToolsMessage dtm = method("Page.getNavigationHistory").send();408 int currentIndex = dtm.getResult("currentIndex").getValue(Integer.class);409 List<Map> list = dtm.getResult("entries").getValue(List.class);410 int targetIndex = currentIndex + delta;411 if (targetIndex < 0 || targetIndex == list.size()) {412 return;413 }414 Map<String, Object> entry = list.get(targetIndex);415 Integer id = (Integer) entry.get("id");416 method("Page.navigateToHistoryEntry").param("entryId", id).send(DevToolsWait.ALL_FRAMES_LOADED);417 }418 @Override419 public void back() {420 history(-1);421 }422 @Override423 public void forward() {424 history(1);425 }426 private void setWindowState(String state) {427 if (!"normal".equals(windowState)) {428 method("Browser.setWindowBounds")429 .param("windowId", windowId)430 .param("bounds", Collections.singletonMap("windowState", "normal"))431 .send();432 windowState = "normal";433 }434 if (!state.equals(windowState)) {435 method("Browser.setWindowBounds")436 .param("windowId", windowId)437 .param("bounds", Collections.singletonMap("windowState", state))438 .send();439 windowState = state;440 }441 }442 @Override443 public void maximize() {444 setWindowState("maximized");445 }446 @Override447 public void minimize() {448 setWindowState("minimized");449 }450 @Override451 public void fullscreen() {452 setWindowState("fullscreen");453 }454 @Override455 public Element click(String locator) {456 retryIfEnabled(locator);457 eval(options.selector(locator) + ".click()");458 return DriverElement.locatorExists(this, locator);459 }460 @Override461 public Element select(String locator, String text) {462 retryIfEnabled(locator);463 eval(options.optionSelector(locator, text));464 return DriverElement.locatorExists(this, locator);465 }466 @Override467 public Element select(String locator, int index) {468 retryIfEnabled(locator);469 eval(options.optionSelector(locator, index));470 return DriverElement.locatorExists(this, locator);471 }472 @Override473 public Driver submit() {474 submit = true;475 return this;476 }477 @Override478 public Element focus(String locator) {479 retryIfEnabled(locator);480 eval(options.focusJs(locator));481 return DriverElement.locatorExists(this, locator);482 }483 @Override484 public Element clear(String locator) {485 eval(options.selector(locator) + ".value = ''");486 return DriverElement.locatorExists(this, locator);487 }488 private void sendKey(char c, int modifiers, String type, Integer keyCode) {489 DevToolsMessage dtm = method("Input.dispatchKeyEvent")490 .param("modifiers", modifiers)491 .param("type", type);492 if (keyCode == null) {493 dtm.param("text", c + "");494 } else {495 switch (keyCode) {496 case 13:497 dtm.param("text", "\r"); // important ! \n does NOT work for chrome498 break;499 case 9: // TAB500 if ("char".equals(type)) {501 return; // special case502 }503 dtm.param("text", "");504 break;505 case 46: // DOT506 if ("rawKeyDown".equals(type)) {507 dtm.param("type", "keyDown"); // special case508 }509 dtm.param("text", ".");510 break;511 default:512 dtm.param("text", c + "");513 }514 dtm.param("windowsVirtualKeyCode", keyCode);515 }516 dtm.send();517 }518 @Override519 public Element input(String locator, String value) {520 retryIfEnabled(locator);521 // focus522 eval(options.focusJs(locator));523 Input input = new Input(value);524 while (input.hasNext()) {525 char c = input.next();526 int modifiers = input.getModifierFlags();527 Integer keyCode = Keys.code(c);528 if (keyCode != null) {529 sendKey(c, modifiers, "rawKeyDown", keyCode);530 sendKey(c, modifiers, "char", keyCode);531 sendKey(c, modifiers, "keyUp", keyCode);532 } else {533 logger.warn("unknown character / key code: {}", c);534 sendKey(c, modifiers, "char", null);535 }536 }537 return DriverElement.locatorExists(this, locator);538 }539 @Override540 public void actions(List<Map<String, Object>> sequence) {541 boolean submitRequested = submit;542 submit = false; // make sure only LAST action is handled as a submit()543 for (Map<String, Object> map : sequence) {544 List<Map<String, Object>> actions = (List) map.get("actions");545 if (actions == null) {546 logger.warn("no actions property found: {}", sequence);547 return;548 }549 Iterator<Map<String, Object>> iterator = actions.iterator();550 while (iterator.hasNext()) {551 Map<String, Object> action = iterator.next();552 String type = (String) action.get("type");553 if (type == null) {554 logger.warn("no type property found: {}", action);555 continue;556 }557 String chromeType;558 switch (type) {559 case "pointerMove":560 chromeType = "mouseMoved";561 break;562 case "pointerDown":563 chromeType = "mousePressed";564 break;565 case "pointerUp":566 chromeType = "mouseReleased";567 break;568 default:569 chromeType = null;570 }571 if (chromeType == null) {572 logger.warn("unexpected action type: {}", action);573 continue;574 }575 Integer x = (Integer) action.get("x");576 Integer y = (Integer) action.get("y");577 if (x != null) {578 currentMouseXpos = x;579 }580 if (y != null) {581 currentMouseYpos = y;582 }583 Integer duration = (Integer) action.get("duration");584 DevToolsMessage toSend = method("Input.dispatchMouseEvent")585 .param("type", chromeType)586 .param("x", currentMouseXpos).param("y", currentMouseYpos);587 if ("mousePressed".equals(chromeType) || "mouseReleased".equals(chromeType)) {588 toSend.param("button", "left").param("clickCount", 1);589 }590 if (!iterator.hasNext() && submitRequested) {591 submit = true;592 }593 toSend.send();594 if (duration != null) {595 options.sleep(duration);596 }597 }598 }599 }600 @Override601 public String text(String id) {602 return property(id, "textContent");603 }604 private <T> T callFunctionOnNode(int nodeId, String function, Class<T> type) {605 DevToolsMessage dtm = method("DOM.resolveNode").param("nodeId", nodeId).send();606 String objectId = dtm.getResult("object.objectId", String.class);607 return callFunctionOnObject(objectId, function, type);608 }609 private <T> T callFunctionOnObject(String objectId, String function, Class<T> type) {610 DevToolsMessage dtm = method("Runtime.callFunctionOn")611 .param("objectId", objectId)612 .param("functionDeclaration", function)613 .send();614 return dtm.getResult().getValue(type);615 }616 @Override617 public String html(String id) {618 return property(id, "outerHTML");619 }620 @Override621 public String value(String locator) {622 return property(locator, "value");623 }624 @Override625 public Element value(String locator, String value) {626 retryIfEnabled(locator);627 eval(options.selector(locator) + ".value = '" + value + "'");628 return DriverElement.locatorExists(this, locator);629 }630 @Override631 public String attribute(String id, String name) {632 retryIfEnabled(id);633 DevToolsMessage dtm = eval(options.selector(id) + ".getAttribute('" + name + "')");634 return dtm.getResult().getAsString();635 }636 @Override637 public String property(String id, String name) {638 retryIfEnabled(id);639 DevToolsMessage dtm = eval(options.selector(id) + "['" + name + "']");640 return dtm.getResult().getAsString();641 }642 @Override643 public boolean enabled(String id) {644 retryIfEnabled(id);645 DevToolsMessage dtm = eval(options.selector(id) + ".disabled");646 return !dtm.getResult().isBooleanTrue();647 }648 @Override649 public boolean waitUntil(String expression) {650 return options.retry(() -> {651 try {652 return eval(expression, true).getResult().isBooleanTrue();653 } catch (Exception e) {654 logger.warn("waitUntil evaluate failed: {}", e.getMessage());655 return false;656 }657 }, b -> b, "waitUntil (js)", true);658 }659 @Override660 public Object script(String expression) {661 return eval(expression).getResult().getValue();662 }663 @Override664 public String getTitle() {665 DevToolsMessage dtm = eval("document.title");666 return dtm.getResult().getAsString();667 }668 @Override669 public String getUrl() {670 return currentUrl;671 }672 @Override673 public List<Map> getCookies() {674 DevToolsMessage dtm = method("Network.getAllCookies").send();675 return dtm.getResult("cookies").getAsList();676 }677 @Override678 public Map<String, Object> cookie(String name) {679 List<Map> list = getCookies();680 if (list == null) {681 return null;682 }683 for (Map<String, Object> map : list) {684 if (map != null && name.equals(map.get("name"))) {685 return map;686 }687 }688 return null;689 }690 @Override691 public void cookie(Map<String, Object> cookie) {692 if (cookie.get("url") == null && cookie.get("domain") == null) {693 cookie = new HashMap(cookie); // don't mutate test694 cookie.put("url", currentUrl);695 }696 method("Network.setCookie").params(cookie).send();697 }698 @Override699 public void deleteCookie(String name) {700 method("Network.deleteCookies").param("name", name).param("url", currentUrl).send();701 }702 @Override703 public void clearCookies() {704 method("Network.clearBrowserCookies").send();705 }706 @Override707 public void dialog(boolean accept) {708 dialog(accept, null);709 }710 @Override711 public void dialog(boolean accept, String text) {712 DevToolsMessage temp = method("Page.handleJavaScriptDialog").param("accept", accept);713 if (text == null) {714 temp.send();715 } else {716 temp.param("promptText", text).send();717 }718 }719 @Override720 public String getDialog() {721 return currentDialogText;722 }723 public byte[] pdf(Map<String, Object> options) {724 DevToolsMessage dtm = method("Page.printToPDF").params(options).send();725 String temp = dtm.getResult("data").getAsString();726 return Base64.getDecoder().decode(temp);727 }728 @Override729 public byte[] screenshot(boolean embed) {730 return screenshot(null, embed);731 }732 @Override733 public Map<String, Object> position(String locator) {734 boolean submitTemp = submit; // in case we are prepping for a submit().mouse(locator).click()735 submit = false;736 retryIfEnabled(locator);737 String expression = options.selector(locator) + ".getBoundingClientRect()";738 // important to not set returnByValue to true739 DevToolsMessage dtm = method("Runtime.evaluate").param("expression", expression).send();740 String objectId = dtm.getResult("objectId").getAsString();741 dtm = method("Runtime.getProperties").param("objectId", objectId).param("accessorPropertiesOnly", true).send();742 submit = submitTemp;743 return options.newMapWithSelectedKeys(dtm.getResult().getAsMap(), "x", "y", "width", "height");744 }745 @Override746 public byte[] screenshot(String id, boolean embed) {747 DevToolsMessage dtm;748 if (id == null) {749 dtm = method("Page.captureScreenshot").send();750 } else {751 Map<String, Object> map = position(id);752 map.put("scale", 1);753 dtm = method("Page.captureScreenshot").param("clip", map).send();754 }755 String temp = dtm.getResult("data").getAsString();756 byte[] bytes = Base64.getDecoder().decode(temp);757 if (embed) {758 options.embedPngImage(bytes);759 }760 return bytes;761 }762 // chrome only763 public byte[] screenshotFull() {764 DevToolsMessage layout = method("Page.getLayoutMetrics").send();765 Map<String, Object> size = layout.getResult("contentSize").getAsMap();766 Map<String, Object> map = options.newMapWithSelectedKeys(size, "height", "width");767 map.put("x", 0);768 map.put("y", 0);769 map.put("scale", 1);770 DevToolsMessage dtm = method("Page.captureScreenshot").param("clip", map).send();771 if (dtm.isResultError()) {772 logger.error("unable to capture screenshot: {}", dtm);773 return new byte[0];774 }775 String temp = dtm.getResult("data").getAsString();776 return Base64.getDecoder().decode(temp);777 }778 @Override779 public List<String> getPages() {780 DevToolsMessage dtm = method("Target.getTargets").send();781 return dtm.getResult("targetInfos.targetId").getAsList();782 }783 @Override784 public void switchPage(String titleOrUrl) {785 if (titleOrUrl == null) {786 return;787 }788 DevToolsMessage dtm = method("Target.getTargets").send();789 List<Map> targets = dtm.getResult("targetInfos").getAsList();790 String targetId = null;791 String targetUrl = null;792 for (Map map : targets) {793 String title = (String) map.get("title");794 String url = (String) map.get("url");795 if ((title != null && title.contains(titleOrUrl))796 || (url != null && url.contains(titleOrUrl))) {797 targetId = (String) map.get("targetId");798 targetUrl = url;799 break;800 }801 }802 if (targetId != null) {803 method("Target.activateTarget").param("targetId", targetId).send();804 currentUrl = targetUrl;805 } else {806 logger.warn("failed to switch page to {}", titleOrUrl);807 }808 }809 @Override810 public void switchPage(int index) {811 if (index == -1) {812 return;813 }814 DevToolsMessage dtm = method("Target.getTargets").send();815 List<Map> targets = dtm.getResult("targetInfos").getAsList();816 if (index < targets.size()) {817 Map target = targets.get(index);818 String targetId = (String) target.get("targetId");819 method("Target.activateTarget").param("targetId", targetId).send();820 currentUrl = (String) target.get("url");821 } else {822 logger.warn("failed to switch frame by index: {}", index);823 }824 }825 @Override826 public void switchFrame(int index) {827 if (index == -1) {828 executionContextId = null;829 sessionId = null;830 return;831 }832 List<Integer> ids = elementIds("iframe,frame");833 if (index < ids.size()) {834 Integer nodeId = ids.get(index);835 setExecutionContext(nodeId, index);836 } else {837 logger.warn("unable to switch frame by index: {}", index);838 }839 }840 @Override841 public void switchFrame(String locator) {842 if (locator == null) {843 executionContextId = null;844 sessionId = null;845 return;846 }847 retryIfEnabled(locator);848 Integer nodeId = elementId(locator);849 if (nodeId == null) {850 return;851 }852 setExecutionContext(nodeId, locator);853 }854 private void setExecutionContext(int nodeId, Object locator) {855 DevToolsMessage dtm = method("DOM.describeNode")856 .param("nodeId", nodeId)857 .param("depth", 0)858 .send();859 String frameId = dtm.getResult("node.frameId", String.class);860 if (frameId == null) {861 logger.warn("unable to find frame by nodeId: {}", locator);862 return;863 }864 sessionId = frameSessions.get(frameId);865 if (sessionId != null) {866 logger.trace("found out-of-process frame - session: {} - {}", frameId, sessionId);867 return;868 }869 dtm = method("Page.createIsolatedWorld").param("frameId", frameId).send();...
Source:WaitState.java
...30 */31public class WaitState {32 private final DriverOptions options;33 private final Logger logger;34 private DevToolsMessage lastSent;35 private Predicate<DevToolsMessage> condition;36 private DevToolsMessage lastReceived;37 private final Predicate<DevToolsMessage> DEFAULT = m -> lastSent.getId().equals(m.getId()) && m.getResult() != null;38 public static final Predicate<DevToolsMessage> CHROME_FRAME_RESIZED = forEvent("Page.frameResized");39 public static final Predicate<DevToolsMessage> CHROME_INSPECTOR_DETACHED = forEvent("Inspector.detached");40 public static final Predicate<DevToolsMessage> CHROME_DIALOG_OPENING = forEvent("Page.javascriptDialogOpening");41 public static final Predicate<DevToolsMessage> CHROME_DOM_CONTENT = forEvent("Page.domContentEventFired");42 public static Predicate<DevToolsMessage> forEvent(String name) {43 return m -> name.equals(m.getMethod());44 }45 public static final Predicate<DevToolsMessage> NO_WAIT = m -> true;46 public WaitState(DriverOptions options) {47 this.options = options;48 logger = options.driverLogger;49 }50 public DevToolsMessage waitAfterSend(DevToolsMessage dtm, Predicate<DevToolsMessage> condition) {51 lastReceived = null;52 lastSent = dtm;53 this.condition = condition == null ? DEFAULT : condition;54 synchronized (this) {55 logger.trace(">> wait: {}", dtm);56 try {57 wait(options.timeout);58 } catch (InterruptedException e) {59 logger.error("interrupted: {} wait: {}", e.getMessage(), dtm);60 }61 }62 if (lastReceived != null) {63 logger.trace("<< notified: {}", dtm);64 } else {65 logger.warn("<< timed out: {}", dtm);66 }67 return lastReceived;68 }69 public void receive(DevToolsMessage dtm) {70 synchronized (this) {71 if (condition.test(dtm)) {72 logger.trace("<< notify: {}", dtm);73 lastReceived = dtm;74 notify();75 } else {76 logger.trace("<< ignore: {}", dtm);77 }78 }79 }80}...
DevToolsMessage
Using AI Code Generation
1import com.intuit.karate.driver.DevToolsMessage;2import com.intuit.karate.driver.DevToolsService;3import com.intuit.karate.driver.DevToolsServiceBuilder;4import com.intuit.karate.driver.chrome.ChromeDevToolsService;5import com.intuit.karate.driver.chrome.ChromeDriverService;6import com.intuit.karate.driver.chrome.ChromeDriverServiceBuilder;7import com.intuit.karate.driver.chrome.ChromeOptions;8import com.intuit.karate.driver.chrome.ChromeSession;9public class Main {10 public static void main(String[] args) {11 ChromeDriverService service = new ChromeDriverServiceBuilder().build();12 ChromeOptions options = new ChromeOptions();13 options.setHeadless(true);14 ChromeSession session = service.startSession(options);15 DevToolsService devToolsService = new ChromeDevToolsService(session);16 devToolsService.send(message);17 devToolsService.close();18 service.close();19 }20}21import com.intuit.karate.driver.DevToolsMessage;22import com.intuit.karate.driver.DevToolsService;23import com.intuit.karate.driver.DevToolsServiceBuilder;24import com.intuit.karate.driver.chrome.ChromeDevToolsService;25import com.intuit.karate.driver.chrome.ChromeDriverService;26import com.intuit.karate.driver.chrome.ChromeDriverServiceBuilder;27import com.intuit.karate.driver.chrome.ChromeOptions;28import com.intuit.karate.driver.chrome.ChromeSession;29public class Main {30 public static void main(String[] args) {31 ChromeDriverService service = new ChromeDriverServiceBuilder().build();32 ChromeOptions options = new ChromeOptions();33 options.setHeadless(true);34 ChromeSession session = service.startSession(options);35 DevToolsService devToolsService = new ChromeDevToolsService(session);36 devToolsService.send(message);37 devToolsService.close();38 service.close();39 }40}41import com
DevToolsMessage
Using AI Code Generation
1import com.intuit.karate.driver.DevToolsMessage;2import com.intuit.karate.driver.DevToolsDriver;3import com.intuit.karate.driver.DevToolsService;4import com.intuit.karate.driver.chrome.ChromeDevToolsDriver;5import com.intuit.karate.driver.chrome.ChromeDevToolsService;6import com.intuit.karate.driver.chrome.ChromeDevToolsServiceOptions;7import com.intuit.karate.driver.chrome.ChromeDevToolsServiceBuilder;8import com.intuit.karate.driver.chrome.ChromeDevToolsServiceLauncher;9import com.intuit.karate.driver.chrome.ChromeDevToolsServiceLauncherFactory;10import com.intuit.karate.driver.chrome.ChromeDevToolsServiceLauncherOptions;11import com.intuit.karate.driver.chrome.ChromeDevToolsServiceLauncherBuilder;12import com.intuit.karate.driver.chrome.ChromeDevToolsServiceLauncherBuilder;13import com.intuit.karate.driver.chrome.ChromeDevToolsServiceLauncher;14import com.intuit.karate.driver.chrome.ChromeDevToolsServiceLauncherFactory;15import com.intuit.karate.driver.chrome.ChromeDevToolsServiceLauncherOptions;16import com.intuit.karate.driver.chrome.ChromeDevToolsServiceLauncherBuilder;17import com.intuit.karate.driver.chrome.ChromeDevToolsServiceLauncherBuilder;18import com.intuit.karate.driver.chrome.ChromeDevToolsServiceLauncher;19import com.intuit.karate.driver.chrome.ChromeDevToolsServiceLauncherFactory;20import com.intuit.karate.driver.chrome.ChromeDevToolsServiceLauncherOptions;21import com.intuit.karate.driver.chrome.ChromeDevToolsServiceLauncherBuilder;22import com.intuit.karate.driver.chrome.ChromeDevToolsServiceLauncherBuilder;23import com.intuit.karate.driver.chrome.ChromeDevToolsServiceLauncher;24import com.intuit.karate.driver.chrome.ChromeDevToolsServiceLauncherFactory;25import com.intuit.karate.driver.chrome.ChromeDevToolsServiceLauncherOptions;26import com.intuit.karate.driver.chrome.ChromeDevToolsServiceLauncherBuilder;27import com.intuit.karate.driver.chrome.ChromeDevToolsServiceLauncherBuilder;28import com.intuit.karate.driver.chrome.ChromeDevToolsServiceLauncher;29import com.intuit.karate.driver.chrome.ChromeDevToolsServiceLauncherFactory;30import com.intuit.karate.driver.chrome.ChromeDevToolsServiceLauncherOptions;31import com.intuit.karate.driver.chrome.ChromeDevToolsServiceLauncherBuilder;32import com.intuit.karate.driver.chrome.ChromeDevToolsServiceLauncherBuilder;33import com.intuit.karate.driver.chrome
DevToolsMessage
Using AI Code Generation
1package com.intuit.karate;2import com.intuit.karate.driver.DevToolsMessage;3import java.util.Map;4import java.util.HashMap;5import com.intuit.karate.driver.DevToolsDriver;6public class 4 {7 public static void main(String[] args) {8 DevToolsDriver driver = new DevToolsDriver();9 Map<String, Object> params = new HashMap();10 DevToolsMessage message = new DevToolsMessage("Page.navigate", params);11 driver.send(message);12 driver.close();13 }14}15package com.intuit.karate;16import com.intuit.karate.driver.DevToolsMessage;17import java.util.Map;18import java.util.HashMap;19import com.intuit.karate.driver.DevToolsDriver;20public class 5 {21 public static void main(String[] args) {22 DevToolsDriver driver = new DevToolsDriver();23 Map<String, Object> params = new HashMap();24 DevToolsMessage message = new DevToolsMessage("Page.navigate", params);25 driver.send(message);26 driver.close();27 }28}29package com.intuit.karate;30import com.intuit.karate.driver.DevToolsMessage;31import java.util.Map;32import java.util.HashMap;33import com.intuit.karate.driver.DevToolsDriver;34public class 6 {35 public static void main(String[] args) {36 DevToolsDriver driver = new DevToolsDriver();37 Map<String, Object> params = new HashMap();38 DevToolsMessage message = new DevToolsMessage("Page.navigate", params);39 driver.send(message);40 driver.close();41 }42}43package com.intuit.karate;44import com.intuit.karate.driver.DevToolsMessage;45import java.util.Map;46import java.util.HashMap;47import com.intuit.karate.driver.DevToolsDriver;48public class 7 {49 public static void main(String[]
DevToolsMessage
Using AI Code Generation
1package demo;2import com.intuit.karate.driver.DevToolsMessage;3import com.intuit.karate.driver.chrome.ChromeDriver;4import com.intuit.karate.driver.chrome.ChromeOptions;5import org.junit.Test;6import java.util.HashMap;7import java.util.Map;8public class DemoTest {9 public void testChrome() {10 ChromeOptions options = new ChromeOptions();11 options.setHeadless(true);12 ChromeDriver driver = new ChromeDriver(options);13 Map<String, Object> params = new HashMap<>();14 params.put("message", "Hello from Karate");15 DevToolsMessage message = new DevToolsMessage("Runtime.evaluate", params);16 message.send(driver);17 driver.quit();18 }19}20* def driver = { driver: 'chrome', headless: true }21* def options = { driver: driver }22* def driver = { driver: 'chrome', headless: true }23* def options = { driver: driver }24* def params = { message: 'Hello from Karate' }25* def message = { method: 'Runtime.evaluate', params: params }26* def message = message.send(driver)27* driver.quit()28package demo;29import com.intuit.karate.driver.DevToolsMessage;30import com.intuit.karate.driver.chrome.ChromeDriver;31import com.intuit.karate.driver.chrome.ChromeOptions;32import org.junit.Test;33public class DemoTest {34 public void testChrome() {35 ChromeOptions options = new ChromeOptions();36 options.setHeadless(true);37 ChromeDriver driver = new ChromeDriver(options);
DevToolsMessage
Using AI Code Generation
1package com.intuit.karate.driver;2import com.intuit.karate.driver.DevToolsMessage;3public class DevToolsMessageExample {4 public static void main(String[] args) {5 DevToolsMessage message = new DevToolsMessage();6 message.sendDevToolsMessage("Page.enable");7 }8}9package com.intuit.karate.driver;10import com.intuit.karate.driver.DevToolsMessage;11public class DevToolsMessageExample {12 public static void main(String[] args) {13 DevToolsMessage message = new DevToolsMessage();14 message.sendDevToolsMessage("Page.enable");15 }16}17package com.intuit.karate.driver;18import com.intuit.karate.driver.DevToolsMessage;19public class DevToolsMessageExample {20 public static void main(String[] args) {21 DevToolsMessage message = new DevToolsMessage();
DevToolsMessage
Using AI Code Generation
1import com.intuit.karate.driver.DevToolsMessage;2import com.intuit.karate.driver.DevTools;3import com.intuit.karate.driver.DevToolsDriver;4import com.intuit.karate.driver.DevToolsDriverOptions;5import com.intuit.karate.driver.chrome.ChromeDevToolsDriver;6import com.intuit.karate.driver.chrome.ChromeDevToolsDriverOptions;7import com.intuit.karate.driver.chrome.ChromeDevTools;8import com.intuit.karate.FileUtils;9import com.intuit.karate.Json;10import com.jayway.jsonpath.JsonPath;11import com.jayway.jsonpath.ReadContext;12import java.io.File;13import java.io.IOException;14import java.util.Map;15import java.util.List;16import java.util.Arrays;17import java.util.HashMap;18import java.util.ArrayList;19import java.util.Collection;20import java.util.Collections;21import java.util.Iterator;22import java.util.Set;23import java.util.HashSet;24import java.util.LinkedHashSet;25import java.util.LinkedHashMap;26import java.util.stream.Collectors;27public class 4 {28 public static void main(String[] args) throws IOException {29 DevToolsDriverOptions options = new ChromeDevToolsDriverOptions();30 DevToolsDriver driver = new ChromeDevToolsDriver(options);31 DevTools devTools = driver.getDevTools();32 devTools.send("Page.enable", null);33 devTools.send("Page.loadEventFired", null);34 DevToolsMessage response = devTools.send("Page.getResourceTree", null);35 String json = response.getJson();36 ReadContext ctx = JsonPath.parse(json);37 String str = ctx.read("result.frameTree.frame.id");38 System.out.println(str);39 String str1 = ctx.read("result.frameTree.frame.executionContextId");
DevToolsMessage
Using AI Code Generation
1package demo;2import com.intuit.karate.driver.DevToolsMessage;3import com.intuit.karate.junit5.Karate;4import static org.junit.jupiter.api.Assertions.*;5class DemoTest {6 Karate testDevTools() {7 .create("Network.enable")8 .send()9 .validate("$.result", true)10 .toString();11 System.out.println(response);12 return Karate.run("4").relativeTo(getClass());13 }14}15* def response = call read('classpath:demo/4.java')16package demo;17import com.intuit.karate.driver.DevToolsMessage;18import com.intuit.karate.junit5.Karate;19import static org.junit.jupiter.api.Assertions.*;20class DemoTest {21 Karate testDevTools() {22 .create("Network.enable")23 .send()24 .validate("$.result", true)25 .toString();26 System.out.println(response);27 return Karate.run("5").relativeTo(getClass());28 }29}30* def response = call read('classpath:demo/5.java')
DevToolsMessage
Using AI Code Generation
1import com.intuit.karate.driver.DevToolsMessage;2import com.intuit.karate.junit5.Karate;3class DevToolsMessageRunner {4 Karate testDevToolsMessage() {5 return Karate.run("devtoolsmessage").relativeTo(getClass());6 }7}8 * def devTools = driver.devTools()9 * def response = devTools.send(message)10import com.intuit.karate.driver.DevToolsMessage;11import com.intuit.karate.junit5.Karate;12class DevToolsMessageRunner {13 Karate testDevToolsMessage() {14 return Karate.run("devtoolsmessage").relativeTo(getClass());15 }16}17 * def devTools = driver.devTools()18 * def message = { "id
DevToolsMessage
Using AI Code Generation
1 * def message = devToolsMessage.create('Network.enable', null)2 * devTools.send(message)3 * def message = devToolsMessage.create('Network.setCacheDisabled', { cacheDisabled: true })4 * devTools.send(message)5 * def message = devToolsMessage.create('Network.clearBrowserCache', null)6 * devTools.send(message)7 * def message = devToolsMessage.create('Network.clearBrowserCookies', null)8 * devTools.send(message)9 * def message = devToolsMessage.create('Network.setBypassServiceWorker', { bypass: true })10 * devTools.send(message)11 * def message = devToolsMessage.create('Network.setExtraHTTPHeaders', { headers: { 'User-Agent': 'Karate' } })12 * devTools.send(message)13 * def message = devToolsMessage.create('Network.setAcceptLanguageOverride', { value: 'en-US' })14 * devTools.send(message)15 * devTools.send(message)16 * def message = devToolsMessage.create('Network.setUserAgentOverride', { userAgent: 'Karate' })17 * devTools.send(message)18 * def message = devToolsMessage.create('Network.setOfflineMode', { offline: false })19 * devTools.send(message)20 * def message = devToolsMessage.create('Network.enableRequestInterception', { patterns: [{ urlPattern: '*', interceptionStage: 'HeadersReceived' }] })21 * devTools.send(message)22 * def message = devToolsMessage.create('Network.setCacheDisabled', { cacheDisabled: true })23 * devTools.send(message)24 * def message = devToolsMessage.create('Network.setResourceC
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!