How to use highlight method of com.intuit.karate.driver.DriverElement class

Best Karate code snippet using com.intuit.karate.driver.DriverElement.highlight

Source:DriverOptions.java Github

copy

Full Screen

...101 public final Target target;102 public final String beforeStart;103 public final String afterStop;104 public final String videoFile;105 public final boolean highlight;106 public final int highlightDuration;107 public final String attach;108 public final boolean screenshotOnFailure;109 public final String playwrightUrl;110 public final Map<String, Object> playwrightOptions;111 // mutable during a test112 private boolean retryEnabled;113 private Integer retryInterval = null;114 private Integer retryCount = null;115 private String preSubmitHash = null;116 private Integer timeoutOverride;117 public static final String SCROLL_JS_FUNCTION = "function(e){ var d = window.getComputedStyle(e).display;"118 + " while(d == 'none'){ e = e.parentElement; d = window.getComputedStyle(e).display }"119 + " e.scrollIntoView({block: 'center'}) }";120 public static final String KARATE_REF_GENERATOR = "function(e){"121 + " if (!document._karate) document._karate = { seq: (new Date()).getTime() };"122 + " var ref = 'ref' + document._karate.seq++; document._karate[ref] = e; return ref }";123 public boolean isRetryEnabled() {124 return retryEnabled;125 }126 public String getPreSubmitHash() {127 return preSubmitHash;128 }129 public void setPreSubmitHash(String preSubmitHash) {130 this.preSubmitHash = preSubmitHash;131 }132 private <T> T get(String key, T defaultValue) {133 T temp = (T) options.get(key);134 return temp == null ? defaultValue : temp;135 }136 public DriverOptions(Map<String, Object> options, ScenarioRuntime sr, int defaultPort, String defaultExecutable) {137 this.options = options;138 this.appender = sr.logAppender;139 logger = new Logger(getClass());140 logger.setAppender(appender);141 timeout = get("timeout", Config.DEFAULT_TIMEOUT);142 type = get("type", null);143 start = get("start", true);144 stop = get("stop", true);145 executable = get("executable", defaultExecutable);146 headless = get("headless", false);147 showProcessLog = get("showProcessLog", false);148 addOptions = get("addOptions", null);149 uniqueName = type + "_" + System.currentTimeMillis();150 String packageName = getClass().getPackage().getName();151 processLogger = showProcessLog ? logger : new Logger(packageName + "." + uniqueName);152 showDriverLog = get("showDriverLog", false);153 driverLogger = showDriverLog ? logger : new Logger(packageName + "." + uniqueName);154 if (executable != null) {155 if (executable.startsWith(".")) { // honor path even when we set working dir156 args.add(new File(executable).getAbsolutePath());157 } else {158 args.add(executable);159 }160 }161 userAgent = get("userAgent", null);162 if (options.containsKey("userDataDir")) {163 String temp = get("userDataDir", null);164 if (temp != null) {165 workingDir = new File(temp);166 userDataDir = workingDir.getAbsolutePath();167 } else { // special case allow user-specified null168 userDataDir = null;169 workingDir = null;170 }171 } else {172 workingDir = new File(sr.featureRuntime.suite.buildDir + File.separator + uniqueName);173 userDataDir = workingDir.getAbsolutePath();174 }175 if (workingDir == null) {176 processLogFile = sr.featureRuntime.suite.buildDir + File.separator + uniqueName + ".log";177 } else {178 processLogFile = workingDir.getPath() + File.separator + type + ".log";179 }180 maxPayloadSize = get("maxPayloadSize", Integer.MAX_VALUE);181 target = get("target", null);182 host = get("host", "localhost");183 webDriverUrl = get("webDriverUrl", null);184 webDriverPath = get("webDriverPath", null);185 webDriverSession = get("webDriverSession", null);186 httpConfig = get("httpConfig", null);187 beforeStart = get("beforeStart", null);188 afterStop = get("afterStop", null);189 videoFile = get("videoFile", null);190 pollAttempts = get("pollAttempts", 20);191 pollInterval = get("pollInterval", 250);192 highlight = get("highlight", false);193 highlightDuration = get("highlightDuration", Config.DEFAULT_HIGHLIGHT_DURATION);194 attach = get("attach", null);195 screenshotOnFailure = get("screenshotOnFailure", true);196 playwrightUrl = get("playwrightUrl", null);197 playwrightOptions = get("playwrightOptions", null);198 // do this last to ensure things like logger, start-flag, webDriverUrl etc. are set199 port = resolvePort(defaultPort);200 }201 private int resolvePort(int defaultPort) {202 if (webDriverUrl != null) {203 return 0;204 }205 int preferredPort = get("port", defaultPort);206 if (start) {207 int freePort = Command.getFreePort(preferredPort);208 if (preferredPort == 0) {209 logger.info("use a automatically allocated port number {}", freePort);210 } else if (freePort != preferredPort) {211 logger.warn("preferred port {} not available, will use: {}", preferredPort, freePort);212 }213 return freePort;214 }215 return preferredPort;216 }217 public Http getHttp() {218 Http http = Http.to(getUrlBase());219 http.setAppender(driverLogger.getAppender());220 if (httpConfig != null) {221 http.configure(httpConfig);222 }223 return http;224 }225 private String getUrlBase() {226 if (webDriverUrl != null) {227 return webDriverUrl;228 }229 String urlBase = "http://" + host + ":" + port;230 if (webDriverPath != null) {231 return urlBase + webDriverPath;232 }233 return urlBase;234 }235 public void arg(String arg) {236 args.add(arg);237 }238 public Command startProcess() {239 return startProcess(null);240 }241 public Command startProcess(Consumer<String> listener) {242 if (beforeStart != null) {243 Command.execLine(null, beforeStart);244 }245 Command command;246 if (target != null || !start) {247 command = null;248 } else {249 if (addOptions != null) {250 args.addAll(addOptions);251 }252 command = new Command(false, processLogger, uniqueName, processLogFile, workingDir, args.toArray(new String[args.size()]));253 if (listener != null) {254 command.setListener(listener);255 }256 command.setPollAttempts(pollAttempts);257 command.setPollInterval(pollInterval);258 command.start();259 }260 if (command != null) { // wait for a slow booting browser / driver process261 command.waitForPort(host, port);262 if (command.isFailed()) {263 throw new KarateException("start failed", command.getFailureReason());264 }265 }266 return command;267 }268 public static Driver startOrigin(Map<String, Object> options, ScenarioRuntime sr) {269 Target target = (Target) options.get("target");270 if (target != null) {271 sr.logger.debug("custom target configured, calling start()");272 Map<String, Object> map = target.start(sr);273 sr.logger.trace("custom target returned options: {}", map);274 options.putAll(map);275 }276 String type = (String) options.get("type");277 if (type == null) {278 sr.logger.warn("type was null, defaulting to 'chrome'");279 type = "chrome";280 options.put("type", type);281 }282 try { // to make troubleshooting errors easier283 switch (type) {284 case "chrome":285 return Chrome.start(options, sr);286 case "msedge":287 return EdgeChromium.start(options, sr);288 case "chromedriver":289 return ChromeWebDriver.start(options, sr);290 case "geckodriver":291 return GeckoWebDriver.start(options, sr);292 case "safaridriver":293 return SafariWebDriver.start(options, sr);294 case "msedgedriver":295 return MsEdgeDriver.start(options, sr);296 case "mswebdriver":297 return MsWebDriver.start(options, sr);298 case "iedriver":299 return IeWebDriver.start(options, sr);300 case "winappdriver":301 return WinAppDriver.start(options, sr);302 case "android":303 return AndroidDriver.start(options, sr);304 case "ios":305 return IosDriver.start(options, sr);306 case "playwright":307 return PlaywrightDriver.start(options, sr);308 case "indigo":309 return IndigoDriver.start(options, sr);310 case "electron":311 return Chrome.start(options, sr);312 default:313 sr.logger.warn("unknown driver type: {}, defaulting to 'chrome'", type);314 options.put("type", "chrome");315 return Chrome.start(options, sr);316 }317 } catch (Exception e) {318 String message = "driver config / start failed: " + e.getMessage() + ", options: " + options;319 sr.logger.error(message, e);320 if (target != null) {321 target.stop(sr);322 }323 throw new RuntimeException(message, e);324 }325 }326 public static Driver start(Map<String, Object> options, ScenarioRuntime sr) { // TODO unify logger327 DriverProvider driverProvider = getDriverProvider();328 if (driverProvider != null) {329 return driverProvider.get(options, sr);330 } else {331 return startOrigin(options, sr);332 }333 }334 private Map<String, Object> getSession(String browserName) {335 Map<String, Object> session = webDriverSession;336 if (session == null) {337 session = new HashMap();338 }339 Map<String, Object> capabilities = (Map) session.get("capabilities");340 if (capabilities == null) {341 capabilities = (Map) session.get("desiredCapabilities");342 }343 if (capabilities == null) {344 capabilities = new HashMap();345 session.put("capabilities", capabilities);346 Map<String, Object> alwaysMatch = new HashMap();347 capabilities.put("alwaysMatch", alwaysMatch);348 alwaysMatch.put("browserName", browserName);349 }350 return session;351 }352 // TODO abstract as method per implementation353 public Map<String, Object> getWebDriverSessionPayload() {354 switch (type) {355 case "chromedriver":356 return getSession("chrome");357 case "geckodriver":358 return getSession("firefox");359 case "safaridriver":360 return getSession("safari");361 case "msedgedriver":362 case "mswebdriver":363 return getSession("edge");364 case "iedriver":365 return getSession("internet explorer");366 default:367 // else user has to specify full payload via webDriverSession368 return getSession(type);369 }370 }371 public static String preProcessWildCard(String locator) {372 boolean contains;373 String tag, prefix, text;374 int index;375 int pos = locator.indexOf('}');376 if (pos == -1) {377 throw new RuntimeException("bad locator prefix: " + locator);378 }379 if (locator.charAt(1) == '^') {380 contains = true;381 prefix = locator.substring(2, pos);382 } else {383 contains = false;384 prefix = locator.substring(1, pos);385 }386 text = locator.substring(pos + 1);387 pos = prefix.indexOf(':');388 if (pos != -1) {389 String tagTemp = prefix.substring(0, pos);390 tag = tagTemp.isEmpty() ? "*" : tagTemp;391 String indexTemp = prefix.substring(pos + 1);392 if (indexTemp.isEmpty()) {393 index = 0;394 } else {395 try {396 index = Integer.valueOf(indexTemp);397 } catch (Exception e) {398 throw new RuntimeException("bad locator prefix: " + locator + ", " + e.getMessage());399 }400 }401 } else {402 tag = prefix.isEmpty() ? "*" : prefix;403 index = 0;404 }405 if (!tag.startsWith("/")) {406 tag = "//" + tag;407 }408 String xpath;409 if (contains) {410 xpath = tag + "[contains(normalize-space(text()),'" + text + "')]";411 } else {412 xpath = tag + "[normalize-space(text())='" + text + "']";413 }414 if (index == 0) {415 return xpath;416 }417 return "/(" + xpath + ")[" + index + "]";418 }419 private static final String DOCUMENT = "document";420 public static String selector(String locator) {421 return selector(locator, DOCUMENT);422 }423 public static String selector(String locator, String contextNode) {424 if (locator.startsWith("(")) {425 return locator; // pure js !426 }427 if (locator.startsWith("{")) {428 locator = preProcessWildCard(locator);429 }430 if (locator.startsWith("/")) { // XPathResult.FIRST_ORDERED_NODE_TYPE = 9431 if (locator.startsWith("/(")) { // hack for wildcard with index (see preProcessWildCard last line)432 if (DOCUMENT.equals(contextNode)) {433 locator = locator.substring(1);434 } else {435 locator = "(." + locator.substring(2);436 }437 } else if (!DOCUMENT.equals(contextNode)) {438 locator = "." + locator; // evaluate relative to this node not root439 }440 return "document.evaluate(\"" + locator + "\", " + contextNode + ", null, 9, null).singleNodeValue";441 }442 return contextNode + ".querySelector(\"" + locator + "\")";443 }444 public void setTimeout(Integer timeout) {445 this.timeoutOverride = timeout;446 }447 public int getTimeout() {448 if (timeoutOverride != null) {449 return timeoutOverride;450 }451 return timeout;452 }453 public void setRetryInterval(Integer retryInterval) {454 this.retryInterval = retryInterval;455 }456 public int getRetryInterval() {457 if (retryInterval != null) {458 return retryInterval;459 }460 ScenarioEngine engine = ScenarioEngine.get();461 if (engine == null) {462 return Config.DEFAULT_RETRY_INTERVAL;463 } else {464 return engine.getConfig().getRetryInterval();465 }466 }467 public int getRetryCount() {468 if (retryCount != null) {469 return retryCount;470 }471 ScenarioEngine engine = ScenarioEngine.get();472 if (engine == null) {473 return Config.DEFAULT_RETRY_COUNT;474 } else {475 return ScenarioEngine.get().getConfig().getRetryCount();476 }477 }478 public <T> T retry(Supplier<T> action, Predicate<T> condition, String logDescription, boolean failWithException) {479 long startTime = System.currentTimeMillis();480 int count = 0, max = getRetryCount();481 T result;482 boolean success;483 do {484 if (count > 0) {485 logger.debug("{} - retry #{}", logDescription, count);486 sleep();487 }488 result = action.get();489 success = condition.test(result);490 } while (!success && count++ < max);491 if (!success) {492 long elapsedTime = System.currentTimeMillis() - startTime;493 String message = logDescription + ": failed after " + (count - 1) + " retries and " + elapsedTime + " milliseconds";494 logger.warn(message);495 if (failWithException) {496 throw new RuntimeException(message);497 }498 }499 return result;500 }501 public static String wrapInFunctionInvoke(String text) {502 return "(function(){ " + text + " })()";503 }504 private static final String HIGHLIGHT_FN = "function(e){ var old = e.getAttribute('style');"505 + " e.setAttribute('style', 'background: yellow; border: 2px solid red;');"506 + " setTimeout(function(){ e.setAttribute('style', old) }, %d) }";507 private static String highlightFn(int millis) {508 return String.format(HIGHLIGHT_FN, millis);509 }510 public String highlight(String locator, int millis) {511 String e = selector(locator);512 String temp = "var e = " + e + "; var fun = " + highlightFn(millis) + "; fun(e)";513 return wrapInFunctionInvoke(temp);514 }515 public String highlightAll(String locator, int millis) {516 return scriptAllSelector(locator, highlightFn(millis));517 }518 public String optionSelector(String locator, String text) {519 boolean textEquals = text.startsWith("{}");520 boolean textContains = text.startsWith("{^}");521 String condition;522 if (textEquals || textContains) {523 text = text.substring(text.indexOf('}') + 1);524 condition = textContains ? "e.options[i].text.indexOf(t) !== -1" : "e.options[i].text === t";525 } else {526 condition = "e.options[i].value === t";527 }528 String e = selector(locator);529 String temp = "var e = " + e + "; var t = \"" + text + "\";"530 + " for (var i = 0; i < e.options.length; ++i)"...

Full Screen

Full Screen

Source:Driver.java Github

copy

Full Screen

...249 script(locator, DriverOptions.SCROLL_JS_FUNCTION);250 return DriverElement.locatorExists(this, locator);251 }252 @AutoDef253 default Element highlight(String locator) {254 return highlight(locator, Config.DEFAULT_HIGHLIGHT_DURATION);255 }256 default Element highlight(String locator, int millis) {257 script(getOptions().highlight(locator, millis));258 delay(millis);259 return DriverElement.locatorExists(this, locator);260 }261 @AutoDef262 default void highlightAll(String locator) {263 highlightAll(locator, Config.DEFAULT_HIGHLIGHT_DURATION);264 }265 default void highlightAll(String locator, int millis) {266 script(getOptions().highlightAll(locator, millis));267 delay(millis);268 }269 // friendly locators =======================================================270 //271 @AutoDef272 default Finder rightOf(String locator) {273 return new ElementFinder(this, locator, ElementFinder.Type.RIGHT);274 }275 @AutoDef276 default Finder leftOf(String locator) {277 return new ElementFinder(this, locator, ElementFinder.Type.LEFT);278 }279 @AutoDef280 default Finder above(String locator) {...

Full Screen

Full Screen

highlight

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.junit4.Karate;2import org.junit.runner.RunWith;3@RunWith(Karate.class)4public class 4 {5}6 * configure driver = { type: 'chrome' }

Full Screen

Full Screen

highlight

Using AI Code Generation

copy

Full Screen

1package demo;2import com.intuit.karate.driver.DriverOptions;3import com.intuit.karate.driver.Driver;4import com.intuit.karate.driver.DriverElement;5import com.intuit.karate.driver.DriverElementHighlightOptions;6import com.intuit.karate.driver.DriverElementHighlightOptions.Color;7import com.intuit.karate.driver.DriverElementHighlightOptions.Style;8import java.util.HashMap;9import java.util.Map;10public class HighlightElement {11 public static void main(String[] args) {12 Map<String, Object> options = new HashMap<>();13 options.put(DriverOptions.DRIVER, DriverOptions.DriverType.CHROME);14 Driver driver = new Driver(options);15 DriverElement element = driver.findElement("name", "q");16 Map<String, Object> highlightOptions = new HashMap<>();17 highlightOptions.put(DriverElementHighlightOptions.COLOR, Color.BLUE);18 highlightOptions.put(DriverElementHighlightOptions.STYLE, Style.SOLID);19 highlightOptions.put(DriverElementHighlightOptions.DURATION, 2);20 element.highlight(highlightOptions);21 driver.quit();22 }23}

Full Screen

Full Screen

highlight

Using AI Code Generation

copy

Full Screen

1package demo;2import com.intuit.karate.junit5.Karate;3class HighlightDemo {4 Karate testAll() {5 return Karate.run().relativeTo(getClass());6 }7}

Full Screen

Full Screen

highlight

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.driver.DriverElement;2WebElement element = driver.findElement(By.id("someId"));3DriverElement.highlight(element, 2, "yellow");4DriverElement.highlight(element, 5, "red");5DriverElement.highlight(element, 10, "green");6DriverElement.highlight(element, 3, "blue");7DriverElement.highlight(element, 4, "purple");8DriverElement.highlight(element, 6, "orange");9DriverElement.highlight(element, 7, "pink");10DriverElement.highlight(element, 8, "black");11DriverElement.highlight(element, 9, "white");12DriverElement.highlight(element, 11, "grey");13DriverElement.highlight(element, 12, "brown");14DriverElement.highlight(element, 13, "maroon");15DriverElement.highlight(element, 14, "turquoise");16DriverElement.highlight(element, 15, "lime");17DriverElement.highlight(element, 16, "navy");18DriverElement.highlight(element, 17, "olive");19DriverElement.highlight(element, 18, "teal");20DriverElement.highlight(element, 19, "silver");21DriverElement.highlight(element

Full Screen

Full Screen

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful