How to use send method of com.intuit.karate.driver.DevToolsMessage class

Best Karate code snippet using com.intuit.karate.driver.DevToolsMessage.send

Source:DevToolsDriver.java Github

copy

Full Screen

...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();870 executionContextId = dtm.getResult("executionContextId").getValue(Integer.class);871 if (executionContextId == null) {872 logger.warn("execution context is null, unable to switch frame by locator: {}", locator);873 }874 }875 public void enableNetworkEvents() {876 method("Network.enable").send();877 }878 public void enablePageEvents() {879 method("Page.enable").send();880 }881 public void enableRuntimeEvents() {882 method("Runtime.enable").send();883 }884 public void enableTargetEvents() {885 method("Target.setAutoAttach")886 .param("autoAttach", true)887 .param("waitForDebuggerOnStart", false)888 .param("flatten", true).send();889 }890 public void intercept(Map<String, Object> config) {891 config = new ScriptValue(config).getAsMap(); // ensure js is pre-processed, TODO graal892 List<String> patterns = (List) config.get("patterns");893 if (patterns == null) {894 throw new RuntimeException("missing array argument 'patterns': " + config);895 }896 if (backend != null) {897 throw new RuntimeException("'intercept()' can be called only once");898 }899 ScenarioContext context = getOptions().getContext();900 String mock = (String) config.get("mock");901 if (mock == null) {902 throw new RuntimeException("missing argument 'mock': " + config);903 }904 ScriptValue mockSv = FileUtils.readFile(mock, context);905 if (!mockSv.isFeature()) {906 throw new RuntimeException("'mock' is not a feature file: " + config + ", " + mockSv);907 }908 Feature feature = mockSv.getValue(Feature.class);909 backend = new FeaturesBackend(feature);910 method("Fetch.enable").param("patterns", patterns).send();911 }912 public void inputFile(String locator, String... relativePaths) {913 List<String> files = new ArrayList(relativePaths.length);914 ScriptBridge bridge = options.getContext().bindings.bridge;915 for (String p : relativePaths) {916 files.add(bridge.toAbsolutePath(p));917 }918 Integer nodeId = elementId(locator);919 method("DOM.setFileInputFiles").param("files", files).param("nodeId", nodeId).send();920 }921}...

Full Screen

Full Screen

send

Using AI Code Generation

copy

Full Screen

1* def driver = karate.call('classpath:com/intuit/karate/driver/devtools/get-driver.feature').driver2* def response = devTools.send(message)3* def driver = karate.call('classpath:com/intuit/karate/driver/devtools/get-driver.feature').driver4* def driver = karate.call('classpath:com/intuit/karate/driver/devtools/get-driver.feature').driver5* def driver = karate.call('classpath:com/intuit/karate/driver/devtools/get-driver.feature').driver6* def driver = karate.call('classpath:com/intuit/karate/driver/devtools/get-driver.feature').driver

Full Screen

Full Screen

send

Using AI Code Generation

copy

Full Screen

1* def message = com.intuit.karate.driver.DevToolsMessage.builder()2* .setMethod('Network.enable')3* .build()4* def response = driver.send(message)5* def message = com.intuit.karate.driver.DevToolsMessage.builder()6* .setMethod('Network.disable')7* .build()8* def response = driver.send(message)9* def message = com.intuit.karate.driver.DevToolsMessage.builder()10* .setMethod('Network.enable')11* .build()12* def response = driver.send(message)13* def message = com.intuit.karate.driver.DevToolsMessage.builder()14* .setMethod('Network.getResponseBody')15* .setParams({ 'requestId': '1234' })16* .build()17* def response = driver.send(message)18* def message = com.intuit.karate.driver.DevToolsMessage.builder()19* .setMethod('Network.setCacheDisabled')20* .setParams({ 'cacheDisabled': true })21* .build()22* def response = driver.send(message)23* def message = com.intuit.karate.driver.DevToolsMessage.builder()24* .setMethod('Network.setExtraHTTPHeaders')25* .setParams({ 'headers': { 'foo': 'bar' } })26* .build()27* def response = driver.send(message)28* def message = com.intuit.karate.driver.DevToolsMessage.builder()29* .setMethod('Network.setUserAgentOverride')30* .setParams({ 'userAgent': 'foo' })31* .build()32* def response = driver.send(message)33* def message = com.intuit.karate.driver.DevToolsMessage.builder()34* .setMethod('Network.setBypassServiceWorker')35* .setParams({ 'bypass': true })36* .build()37* def response = driver.send(message)38* def message = com.intuit.karate.driver.DevToolsMessage.builder()39* .setMethod('Network.setBlockedURLs')40* .setParams({ 'urls': [ 'foo', 'bar' ] })41* .build()42* def response = driver.send(message)

Full Screen

Full Screen

send

Using AI Code Generation

copy

Full Screen

1def devTools = driver.devTools()2def response = devTools.send('Page.captureScreenshot', {format: 'png'})3def file = new File('screenshot.png')4file.write bytes.decodeBase64()5def devTools = driver.devTools()6def response = devTools.send('Page.captureScreenshot', {format: 'png'})7def file = new File('screenshot.png')8file.write bytes.decodeBase64()9def devTools = driver.devTools()10def response = devTools.send('Page.captureScreenshot', {format: 'png'})11def file = new File('screenshot.png')12file.write bytes.decodeBase64()13def devTools = driver.devTools()14def response = devTools.send('Page.captureScreenshot', {format: 'png'})15def file = new File('screenshot.png')16file.write bytes.decodeBase64()17def devTools = driver.devTools()18def response = devTools.send('Page.captureScreenshot', {format: 'png'})19def file = new File('screenshot.png')20file.write bytes.decodeBase64()21def devTools = driver.devTools()22def response = devTools.send('Page.captureScreenshot', {format: 'png'})23def file = new File('screenshot.png')24file.write bytes.decodeBase64()25def devTools = driver.devTools()26def response = devTools.send('Page.captureScreenshot', {format: 'png'})27def file = new File('screenshot.png')28file.write bytes.decodeBase64()29def devTools = driver.devTools()30def response = devTools.send('Page.captureScreenshot', {format: 'png'})

Full Screen

Full Screen

send

Using AI Code Generation

copy

Full Screen

1def devTools = com.intuit.karate.driver.DevToolsDriver()2devTools.connect()3devTools.send(message)4def devTools = com.intuit.karate.driver.DevToolsDriver()5devTools.connect()6devTools.send(message)7def devTools = com.intuit.karate.driver.DevToolsDriver()8devTools.connect()9devTools.send(message)10def devTools = com.intuit.karate.driver.DevToolsDriver()11devTools.connect()12devTools.send(message)13def devTools = com.intuit.karate.driver.DevToolsDriver()14devTools.connect()15devTools.send(message)16def devTools = com.intuit.karate.driver.DevToolsDriver()17devTools.connect()18devTools.send(message)19def devTools = com.intuit.karate.driver.DevToolsDriver()20devTools.connect()21devTools.send(message)22def devTools = com.intuit.karate.driver.DevToolsDriver()23devTools.connect()24def message = devTools.createMessage('Page.navigate', { 'url': 'http

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.

Run Karate automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful