Best Karate code snippet using com.intuit.karate.driver.DevToolsWait.DevToolsWait
Source:DevToolsDriver.java
...58 protected final Command command;59 protected WebSocketOptions wsOptions;60 protected WebSocketClient client;61 private boolean terminated;62 private final DevToolsWait wait;63 protected final String rootFrameId;64 private Integer windowId;65 private String windowState;66 private Integer executionContextId;67 protected String sessionId;68 protected boolean domContentEventFired;69 protected final Set<String> framesStillLoading = new HashSet();70 private final Map<String, String> frameSessions = new HashMap();71 private boolean submit;72 protected String currentDialogText;73 private int nextId;74 public int nextId() {75 return ++nextId;76 }77 private MockHandler mockHandler;78 protected final Logger logger;79 protected DevToolsDriver(DriverOptions options, Command command, String webSocketUrl) {80 logger = options.driverLogger;81 this.options = options;82 this.command = command;83 this.wait = new DevToolsWait(this, options);84 int pos = webSocketUrl.lastIndexOf('/');85 rootFrameId = webSocketUrl.substring(pos + 1);86 logger.debug("root frame id: {}", rootFrameId);87 wsOptions = new WebSocketOptions(webSocketUrl);88 wsOptions.setMaxPayloadSize(options.maxPayloadSize);89 wsOptions.setTextConsumer(text -> {90 if (logger.isTraceEnabled()) {91 logger.trace("<< {}", text);92 } else {93 // to avoid swamping the console when large base64 encoded binary responses happen94 logger.debug("<< {}", StringUtils.truncate(text, 1024, true));95 }96 Map<String, Object> map = Json.of(text).value();97 DevToolsMessage dtm = new DevToolsMessage(this, map);98 receive(dtm);99 });100 client = new WebSocketClient(wsOptions, logger);101 }102 public void reconnect(String url) {103 if (client != null) {104 client.close();105 }106 WebSocketOptions newWsOptions = new WebSocketOptions(url);107 newWsOptions.setMaxPayloadSize(wsOptions.getMaxPayloadSize());108 newWsOptions.setTextHandler(wsOptions.getTextHandler());109 wsOptions = newWsOptions;110 client = new WebSocketClient(wsOptions, logger);111 }112 @Override113 public Driver timeout(Integer millis) {114 options.setTimeout(millis);115 return this;116 }117 @Override118 public Driver timeout() {119 return timeout(null);120 }121 public DevToolsMessage method(String method) {122 return new DevToolsMessage(this, method);123 }124 // this can be used for exploring / sending any raw message !125 public Map<String, Object> send(Map<String, Object> map) {126 DevToolsMessage dtm = new DevToolsMessage(this, map);127 dtm.setId(nextId());128 return sendAndWait(dtm, null).toMap();129 }130 public void send(DevToolsMessage dtm) {131 String json = JsonUtils.toJson(dtm.toMap());132 logger.debug(">> {}", json);133 client.send(json);134 }135 public DevToolsMessage sendAndWait(DevToolsMessage dtm, Predicate<DevToolsMessage> condition) {136 boolean wasSubmit = submit;137 if (condition == null && submit) {138 submit = false;139 condition = DevToolsWait.ALL_FRAMES_LOADED;140 }141 // do stuff inside wait to avoid missing messages142 DevToolsMessage result = wait.send(dtm, condition);143 if (result == null && !wasSubmit) {144 throw new RuntimeException("failed to get reply for: " + dtm);145 }146 return result;147 }148 public void receive(DevToolsMessage dtm) {149 if (dtm.methodIs("Page.domContentEventFired")) {150 domContentEventFired = true;151 logger.trace("** set dom ready flag to true");152 }153 if (dtm.methodIs("Page.javascriptDialogOpening")) {154 currentDialogText = dtm.getParam("message");155 // this will stop waiting NOW156 wait.setCondition(DevToolsWait.DIALOG_OPENING);157 }158 if (dtm.methodIs("Page.frameStartedLoading")) {159 String frameLoadingId = dtm.getParam("frameId");160 if (rootFrameId.equals(frameLoadingId)) { // root page is loading161 domContentEventFired = false;162 framesStillLoading.clear();163 frameSessions.clear();164 logger.trace("** root frame started loading, cleared all page state: {}", frameLoadingId);165 } else {166 framesStillLoading.add(frameLoadingId);167 logger.trace("** frame started loading, added to in-progress list: {}", framesStillLoading);168 }169 }170 if (dtm.methodIs("Page.frameStoppedLoading")) {171 String frameLoadedId = dtm.getParam("frameId");172 framesStillLoading.remove(frameLoadedId);173 logger.trace("** frame stopped loading: {}, remaining in-progress: {}", frameLoadedId, framesStillLoading);174 }175 if (dtm.methodIs("Target.attachedToTarget")) {176 frameSessions.put(dtm.getParam("targetInfo.targetId"), dtm.getParam("sessionId"));177 logger.trace("** added frame session: {}", frameSessions);178 }179 if (dtm.methodIs("Fetch.requestPaused")) {180 handleInterceptedRequest(dtm);181 }182 // all needed state is set above before we get into conditional checks183 wait.receive(dtm);184 }185 private void handleInterceptedRequest(DevToolsMessage dtm) {186 String requestId = dtm.getParam("requestId");187 String requestUrl = dtm.getParam("request.url");188 if (mockHandler != null) {189 String method = dtm.getParam("request.method");190 Map<String, String> headers = dtm.getParam("request.headers");191 String postData = dtm.getParam("request.postData");192 logger.debug("intercepting request for url: {}", requestUrl);193 HttpRequest request = new HttpRequest();194 request.setUrl(requestUrl);195 request.setMethod(method);196 headers.forEach((k, v) -> request.putHeader(k, v));197 if (postData != null) {198 request.setBody(FileUtils.toBytes(postData));199 } else {200 request.setBody(Constants.ZERO_BYTES);201 }202 Response response = mockHandler.handle(request.toRequest());203 String responseBody = response.getBody() == null ? "" : Base64.getEncoder().encodeToString(response.getBody());204 List<Map> responseHeaders = new ArrayList();205 Map<String, List<String>> map = response.getHeaders();206 if (map != null) {207 map.forEach((k, v) -> {208 if (v != null && !v.isEmpty()) {209 Map<String, Object> nv = new HashMap(2);210 nv.put("name", k);211 nv.put("value", v.get(0));212 responseHeaders.add(nv);213 }214 });215 }216 method("Fetch.fulfillRequest")217 .param("requestId", requestId)218 .param("responseCode", response.getStatus())219 .param("responseHeaders", responseHeaders)220 .param("body", responseBody).sendWithoutWaiting();221 } else {222 logger.warn("no mock server, continuing paused request to url: {}", requestUrl);223 method("Fetch.continueRequest").param("requestId", requestId).sendWithoutWaiting();224 }225 }226 //==========================================================================227 //228 private DevToolsMessage evalOnce(String expression, boolean quickly, boolean fireAndForget) {229 DevToolsMessage toSend = method("Runtime.evaluate")230 .param("expression", expression).param("returnByValue", true);231 if (executionContextId != null) {232 toSend.param("contextId", executionContextId);233 }234 if (quickly) {235 toSend.setTimeout(options.getRetryInterval());236 }237 if (fireAndForget) {238 toSend.sendWithoutWaiting();239 return null;240 }241 return toSend.send();242 }243 protected DevToolsMessage eval(String expression) {244 return eval(expression, false);245 }246 private DevToolsMessage eval(String expression, boolean quickly) {247 DevToolsMessage dtm = evalOnce(expression, quickly, false);248 if (dtm.isResultError()) {249 String message = "js eval failed once:" + expression250 + ", error: " + dtm.getResult().getAsString();251 logger.warn(message);252 options.sleep();253 dtm = evalOnce(expression, quickly, false); // no wait condition for the re-try254 if (dtm.isResultError()) {255 message = "js eval failed twice:" + expression256 + ", error: " + dtm.getResult().getAsString();257 logger.error(message);258 throw new RuntimeException(message);259 }260 }261 return dtm;262 }263 protected void retryIfEnabled(String locator) {264 if (options.isRetryEnabled()) {265 waitFor(locator); // will throw exception if not found266 }267 if (options.highlight) {268 // highlight(locator, options.highlightDuration); // instead of this269 String highlightJs = options.highlight(locator, options.highlightDuration);270 evalOnce(highlightJs, true, true); // do it safely, i.e. fire and forget271 }272 }273 protected int getRootNodeId() {274 return method("DOM.getDocument").param("depth", 0).send().getResult("root.nodeId", Integer.class);275 }276 @Override277 public Integer elementId(String locator) {278 DevToolsMessage dtm = method("DOM.querySelector")279 .param("nodeId", getRootNodeId())280 .param("selector", locator).send();281 if (dtm.isResultError()) {282 return null;283 }284 return dtm.getResult("nodeId").getAsInt();285 }286 @Override287 public List elementIds(String locator) {288 if (locator.startsWith("/")) { // special handling for xpath289 getRootNodeId(); // just so that DOM.getDocument is called else DOM.performSearch fails290 DevToolsMessage dtm = method("DOM.performSearch").param("query", locator).send();291 String searchId = dtm.getResult("searchId", String.class);292 int resultCount = dtm.getResult("resultCount", Integer.class);293 dtm = method("DOM.getSearchResults")294 .param("searchId", searchId)295 .param("fromIndex", 0).param("toIndex", resultCount).send();296 return dtm.getResult("nodeIds", List.class);297 }298 DevToolsMessage dtm = method("DOM.querySelectorAll")299 .param("nodeId", getRootNodeId())300 .param("selector", locator).send();301 if (dtm.isResultError()) {302 return Collections.EMPTY_LIST;303 }304 return dtm.getResult("nodeIds").getValue();305 }306 @Override307 public DriverOptions getOptions() {308 return options;309 }310 @Override311 public void activate() {312 method("Target.activateTarget").param("targetId", rootFrameId).send();313 }314 protected void initWindowIdAndState() {315 DevToolsMessage dtm = method("Browser.getWindowForTarget").param("targetId", rootFrameId).send();316 if (!dtm.isResultError()) {317 windowId = dtm.getResult("windowId").getValue();318 windowState = (String) dtm.getResult("bounds").<Map> getValue().get("windowState");319 }320 }321 @Override322 public Map<String, Object> getDimensions() {323 DevToolsMessage dtm = method("Browser.getWindowForTarget").param("targetId", rootFrameId).send();324 Map<String, Object> map = dtm.getResult("bounds").getValue();325 Integer x = (Integer) map.remove("left");326 Integer y = (Integer) map.remove("top");327 map.put("x", x);328 map.put("y", y);329 return map;330 }331 @Override332 public void setDimensions(Map<String, Object> map) {333 Integer left = (Integer) map.remove("x");334 Integer top = (Integer) map.remove("y");335 map.put("left", left);336 map.put("top", top);337 Map temp = getDimensions();338 temp.putAll(map);339 temp.remove("windowState");340 method("Browser.setWindowBounds")341 .param("windowId", windowId)342 .param("bounds", temp).send();343 }344 public void emulateDevice(int width, int height, String userAgent) {345 logger.info("Setting deviceMetrics width={}, height={}, userAgent={}", width, height, userAgent);346 method("Network.setUserAgentOverride").param("userAgent", userAgent).send();347 method("Emulation.setDeviceMetricsOverride")348 .param("width", width)349 .param("height", height)350 .param("deviceScaleFactor", 1)351 .param("mobile", true)352 .send();353 }354 @Override355 public void close() {356 method("Page.close").sendWithoutWaiting();357 }358 @Override359 public void quit() {360 if (terminated) {361 return;362 }363 terminated = true;364 // don't wait, may fail and hang365 method("Target.closeTarget").param("targetId", rootFrameId).sendWithoutWaiting();366 // method("Browser.close").send();367 client.close();368 if (command != null) {369 command.close(true);370 }371 }372 @Override373 public boolean isTerminated() {374 return terminated;375 }376 @Override377 public void setUrl(String url) {378 method("Page.navigate").param("url", url)379 .send(DevToolsWait.ALL_FRAMES_LOADED);380 }381 @Override382 public void refresh() {383 method("Page.reload").send(DevToolsWait.ALL_FRAMES_LOADED);384 }385 @Override386 public void reload() {387 method("Page.reload").param("ignoreCache", true).send();388 }389 private void history(int delta) {390 DevToolsMessage dtm = method("Page.getNavigationHistory").send();391 int currentIndex = dtm.getResult("currentIndex").getValue();392 List<Map> list = dtm.getResult("entries").getValue();393 int targetIndex = currentIndex + delta;394 if (targetIndex < 0 || targetIndex == list.size()) {395 return;396 }397 Map<String, Object> entry = list.get(targetIndex);398 Integer id = (Integer) entry.get("id");399 method("Page.navigateToHistoryEntry").param("entryId", id).send(DevToolsWait.ALL_FRAMES_LOADED);400 }401 @Override402 public void back() {403 history(-1);404 }405 @Override406 public void forward() {407 history(1);408 }409 private void setWindowState(String state) {410 if (!"normal".equals(windowState)) {411 method("Browser.setWindowBounds")412 .param("windowId", windowId)413 .param("bounds", Collections.singletonMap("windowState", "normal"))...
Source:DevToolsWait.java
...27/**28 *29 * @author pthomas330 */31public class DevToolsWait {32 private final DriverOptions options;33 private final DevToolsDriver driver;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());38 39 public static final Predicate<DevToolsMessage> FRAME_RESIZED = forEvent("Page.frameResized");40 public static final Predicate<DevToolsMessage> INSPECTOR_DETACHED = forEvent("Inspector.detached");41 public static final Predicate<DevToolsMessage> DIALOG_OPENING = forEvent("Page.javascriptDialogOpening");42 43 public static final Predicate<DevToolsMessage> ALL_FRAMES_LOADED = m -> {44 // page is considered ready only when the dom is ready45 // AND all child frames that STARTED loading BEFORE the dom became ready46 if (m.methodIs("Page.domContentEventFired")) {47 if (m.driver.framesStillLoading.isEmpty()) {48 m.driver.logger.trace("** dom ready, and no frames loading, wait done");49 return true;50 } else {51 m.driver.logger.trace("** dom ready, but frames still loading, will wait: {}", m.driver.framesStillLoading);52 return false;53 }54 }55 if (m.methodIs("Page.frameStoppedLoading")) {56 if (!m.driver.domContentEventFired) {57 m.driver.logger.trace("** dom not ready, will wait, and frames loading: {}", m.driver.framesStillLoading);58 return false;59 }60 if (m.driver.framesStillLoading.isEmpty()) {61 m.driver.logger.trace("** dom ready, and no frames loading, wait done");62 return true;63 } else {64 m.driver.logger.trace("** dom ready, but frames still loading, will wait: {}", m.driver.framesStillLoading);65 }66 }67 return false;68 };69 public static Predicate<DevToolsMessage> forEvent(String name) {70 return m -> name.equals(m.getMethod());71 }72 public DevToolsWait(DevToolsDriver driver, DriverOptions options) {73 this.driver = driver;74 this.options = options;75 logger = options.driverLogger;76 }77 // mutable when driver logger is swapped78 private Logger logger;79 public void setLogger(Logger logger) {80 this.logger = logger;81 }82 public void setCondition(Predicate<DevToolsMessage> condition) {83 this.condition = condition;84 }85 public DevToolsMessage send(DevToolsMessage dtm, Predicate<DevToolsMessage> condition) {86 lastReceived = null;...
DevToolsWait
Using AI Code Generation
1package demo;2import com.intuit.karate.junit5.Karate;3class 4 {4 Karate testAll() {5 return Karate.run().relativeTo(getClass());6 }7}8 * def driver = { driver: 'webdriver.chrome.driver', path: 'C:/chromedriver.exe' }9 * def options = { args: ['headless', 'disable-gpu', 'no-sandbox', 'disable-dev-shm-usage'] }10 * def driverOptions = { driver: driver, options: options }11 * def driver = { driver: 'com.intuit.karate.driver.DevToolsDriver', options: driverOptions }12 * def driverOptions = { driver: driver }13 * def config = { driver: driverOptions }14 * def driver = karate.driver('chrome', config)15 * driver.get('
DevToolsWait
Using AI Code Generation
1import com.intuit.karate.driver.DevToolsWait;2import com.intuit.karate.driver.DevToolsDriver;3import com.intuit.karate.driver.DevToolsOptions;4import com.intuit.karate.driver.DevToolsNetwork;5import com.intuit.karate.driver.DevToolsPage;6import com.intuit.karate.driver.DevToolsConsole;7import com.intuit.karate.driver.DevToolsTarget;8import com.intuit.karate.driver.DevToolsRuntime;9import com.intuit.karate.driver.DevToolsEmulation;10import com.intuit.karate.driver.DevToolsSecurity;11import com.intuit.karate.driver.DevToolsNetwork;12import com.intuit.karate.driver.DevToolsPerformance;13import com.intuit.karate.driver.DevToolsDebugger;14import com.intuit.karate.driver.DevToolsMemory;15import com.intuit.karate.driver.DevToolsLog;16import com.intuit.karate.driver.DevToolsInput;17import com.intuit.karate.driver.DevToolsBrowser;18import com.intuit.karate.driver.DevToolsApplicationCache;19import com.intuit.karate.driver.DevToolsAccessibility;20import com.intuit.karate.driver.DevToolsAnimation;21import com.intuit.karate.driver.DevToolsAudits;22import com.intuit.karate.driver.DevToolsBackgroundService;23import com.intuit.karate.driver.DevToolsCSS;24import com.intuit.karate.driver.DevToolsCast;25import com.intuit.karate.driver.DevToolsDOM;26import com.intuit.karate.driver.DevToolsDOMDebugger;27import com.intuit.karate.driver.DevToolsDOMSnapshot;28import com.intuit.karate.driver.DevToolsDOMStorage;29import com.intuit.karate.driver.DevToolsDatabase;30import com.intuit.karate.driver.DevToolsDeviceOrientation;31import com.intuit.karate.driver.DevToolsEmulation;32import com.intuit.karate.driver.DevToolsHeapProfiler;33import com.intuit.karate.driver.DevToolsIndexedDB;34import com.intuit.karate.driver.DevToolsIO;35import com.intuit.karate.driver.DevToolsInspector;36import com.intuit.karate.driver.DevToolsLayerTree;37import com.intuit.karate.driver.DevToolsLog;38import com.intuit.karate.driver.DevToolsMedia;39import com.intuit.karate.driver.DevToolsMemory;40import com.intuit.karate.driver.DevToolsOverlay;41import com.intuit.kar
DevToolsWait
Using AI Code Generation
1import com.intuit.karate.driver.DevToolsWait;2import com.intuit.karate.driver.DevToolsWait;3public class 4 {4public static void main(String[] args) throws Exception {5DevToolsWait devToolsWait = new DevToolsWait();6devToolsWait.waitUntil(30000, "return document.readyState == 'complete';");7}8}
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!!