Best Karate code snippet using com.intuit.karate.driver.Keys.HashMap
Source:DriverOptions.java
...45import com.intuit.karate.shell.Command;46import java.io.File;47import java.util.ArrayList;48import java.util.Arrays;49import java.util.HashMap;50import java.util.Iterator;51import java.util.List;52import java.util.Map;53import java.util.function.Consumer;54import java.util.function.Predicate;55import java.util.function.Supplier;56import asura.ui.driver.DriverProvider;57/**58 *59 * @author pthomas360 */61public class DriverOptions {62 // injected63 private static DriverProvider driverProvider;64 public static DriverProvider getDriverProvider() {65 return driverProvider;66 }67 public static void setDriverProvider(DriverProvider driverProvider) {68 DriverOptions.driverProvider = driverProvider;69 }70 public static void loadOverride() {71 }72 public final Map<String, Object> options;73 public final int timeout;74 public final boolean start;75 public final boolean stop;76 public final String executable;77 public final String type;78 public final int port;79 public final String host;80 public final int pollAttempts;81 public final int pollInterval;82 public final boolean headless;83 public final boolean showProcessLog;84 public final boolean showDriverLog;85 public final Logger logger;86 public final LogAppender appender;87 public final Logger processLogger;88 public final Logger driverLogger;89 public final String uniqueName;90 public final File workingDir;91 public final String userAgent;92 public final String userDataDir;93 public final String processLogFile;94 public final int maxPayloadSize;95 public final List<String> addOptions;96 public final List<String> args = new ArrayList<>();97 public final String webDriverUrl;98 public final String webDriverPath;99 public final Map<String, Object> webDriverSession;100 public final Map<String, Object> httpConfig;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)"531 + " if (" + condition + ") { e.options[i].selected = true; e.dispatchEvent(new Event('change')) }";532 return wrapInFunctionInvoke(temp);533 }534 public String optionSelector(String id, int index) {535 String e = selector(id);536 String temp = "var e = " + e + "; var t = " + index + ";"537 + " for (var i = 0; i < e.options.length; ++i)"538 + " if (i === t) { e.options[i].selected = true; e.dispatchEvent(new Event('change')) }";539 return wrapInFunctionInvoke(temp);540 }541 private String fun(String expression) {542 char first = expression.charAt(0);543 return (first == '_' || first == '!') ? "function(_){ return " + expression + " }" : expression;544 }545 public String scriptSelector(String locator, String expression) {546 return scriptSelector(locator, expression, DOCUMENT);547 }548 public String scriptSelector(String locator, String expression, String contextNode) {549 String temp = "var fun = " + fun(expression) + "; var e = " + selector(locator, contextNode) + "; return fun(e)";550 return wrapInFunctionInvoke(temp);551 }552 public String scriptAllSelector(String locator, String expression) {553 return scriptAllSelector(locator, expression, DOCUMENT);554 }555 // the difference here from selector() is the use of querySelectorAll()556 // how the loop for XPath results has to be handled557 public String scriptAllSelector(String locator, String expression, String contextNode) {558 if (locator.startsWith("{")) {559 locator = preProcessWildCard(locator);560 }561 boolean isXpath = locator.startsWith("/");562 String selector;563 if (isXpath) { // XPathResult.ORDERED_NODE_ITERATOR_TYPE = 5564 selector = "document.evaluate(\"" + locator + "\", " + contextNode + ", null, 5, null)";565 } else {566 selector = contextNode + ".querySelectorAll(\"" + locator + "\")";567 }568 String temp = "var res = []; var fun = " + fun(expression) + "; var es = " + selector + "; ";569 if (isXpath) {570 temp = temp + "var e = null; while(e = es.iterateNext()) res.push(fun(e)); return res";571 } else {572 temp = temp + "es.forEach(function(e){ res.push(fun(e)) }); return res";573 }574 return wrapInFunctionInvoke(temp);575 }576 public void sleep() {577 sleep(getRetryInterval());578 }579 public void sleep(int millis) {580 if (millis == 0) {581 return;582 }583 try {584 processLogger.trace("sleeping for millis: {}", millis);585 Thread.sleep(millis);586 } catch (Exception e) {587 throw new RuntimeException(e);588 }589 }590 public static String getPositionJs(String locator) {591 String temp = "var r = " + selector(locator, DOCUMENT) + ".getBoundingClientRect();"592 + " var dx = window.scrollX; var dy = window.scrollY;"593 + " return { x: r.x + dx, y: r.y + dy, width: r.width + dx, height: r.height + dy }";594 return wrapInFunctionInvoke(temp);595 }596 public Map<String, Object> newMapWithSelectedKeys(Map<String, Object> map, String... keys) {597 Map<String, Object> out = new HashMap(keys.length);598 for (String key : keys) {599 Object o = map.get(key);600 if (o != null) {601 out.put(key, o);602 }603 }604 return out;605 }606 public void disableRetry() {607 retryEnabled = false;608 retryCount = null;609 retryInterval = null;610 }611 public void enableRetry(Integer count, Integer interval) {...
Source:Chrome.java
...22 * THE SOFTWARE.23 */24package com.intuit.karate.driver.chrome;25import java.util.Collections;26import java.util.HashMap;27import java.util.List;28import java.util.Map;29import java.util.function.Consumer;30import org.slf4j.Logger;31import org.slf4j.LoggerFactory;32import com.intuit.karate.FileUtils;33import com.intuit.karate.Http;34import com.intuit.karate.Json;35import com.intuit.karate.StringUtils;36import com.intuit.karate.core.ScenarioEngine;37import com.intuit.karate.core.ScenarioRuntime;38import com.intuit.karate.core.Variable;39import com.intuit.karate.driver.DevToolsDriver;40import com.intuit.karate.driver.DevToolsMessage;41import com.intuit.karate.driver.Driver;42import com.intuit.karate.driver.DriverOptions;43import com.intuit.karate.driver.Input;44import com.intuit.karate.driver.Keys;45import com.intuit.karate.http.Response;46import com.intuit.karate.shell.Command;47import asura.ui.driver.DriverProvider;48import asura.ui.karate.KarateRunner;49/**50 * @author pthomas351 */52public class Chrome extends DevToolsDriver {53 private static Logger logger = LoggerFactory.getLogger(Chrome.class);54 public static final String DEFAULT_PATH_MAC = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";55 public static final String DEFAULT_PATH_WIN = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe";56 public static final String DEFAULT_PATH_LINUX = "/usr/bin/google-chrome";57 public Driver parent; // used in 'DriverPoolActor'58 public ScenarioEngine engine;59 public Boolean inject;60 public Consumer<Map<String, Object>> filter;61 public Chrome(DriverOptions options, Command command, String webSocketUrl) {62 super(options, command, webSocketUrl);63 }64 // èªå®ä¹65 public Chrome(DriverOptions options, Command command, String webSocketUrl,66 ScenarioEngine engine, Boolean inject, Consumer<Map<String, Object>> filter67 ) {68 super(options, command, webSocketUrl);69 this.engine = engine;70 this.inject = inject;71 this.filter = filter;72 if (this.inject && this.engine != null) {73 this.engine.setDriver(this);74 }75 client.setTextHandler(text -> {76 Map<String, Object> map = Json.of(text).value();77 DevToolsMessage dtm = new DevToolsMessage(this, map);78 if (this.filter != null && !StringUtils.isBlank(dtm.getMethod())) {79 this.filter.accept(map);80 }81 receive(dtm);82 return false; // no async signalling, for normal use, e.g. chrome developer tools83 });84 }85 public void closeClient() {86 client.close();87 }88 public void enableLog() {89 method("Log.enable").send();90 }91 public void enableDom() {92 method("DOM.enable").send();93 }94 public void setDiscoverTargets() {95 method("Target.setDiscoverTargets").param("discover", true).send();96 }97 public String screenshotAsBase64() {98 Variable result = method("Page.captureScreenshot").send().getResult("data");99 if (result != null) {100 return result.getAsString();101 } else {102 return null;103 }104 }105 public DevToolsMessage openNewPage(String url) {106 return method("Target.createTarget")107 .param("url", url)108 .param("newWindow", false)109 .param("background", true)110 .send();111 }112 public List<Map<String, Object>> getJsonPageTargets() {113 Http http = options.getHttp();114 Command.waitForHttp(http.urlBase + "/json");115 Response res = http.path("json").get();116 List<Map<String, Object>> targets = res.json().asList();117 return targets;118 }119 public void goToTop(Integer idx) {120 List<Map<String, Object>> targets = getJsonPageTargets();121 if (targets.size() > idx) {122 Map<String, Object> target = targets.get(idx);123 reconnect((String) target.get("webSocketDebuggerUrl"));124 } else {125 throw new RuntimeException("only " + targets.size() + " pages.");126 }127 }128 public void switchPage2(String urlOrTitle) {129 if (urlOrTitle.matches("-?(0|[1-9]\\d*)")) { // nums130 goToTop(Integer.parseInt(urlOrTitle));131 } else {132 List<Map<String, Object>> targets = getJsonPageTargets();133 for (Map target : targets) {134 String targetUrl = (String) target.get("url");135 String targetTitle = (String) target.get("title");136 if (targetUrl.contains(urlOrTitle) || targetTitle.contains(urlOrTitle)) {137 reconnect((String) target.get("webSocketDebuggerUrl"));138 break;139 }140 }141 }142 }143 public void closeOthers() {144 DevToolsMessage dtm = method("Target.getTargets").send();145 List<Map> targets = dtm.getResult("targetInfos").getValue();146 if (targets != null) {147 targets.forEach(target -> {148 if ("page".equals(target.get("type"))) {149 String targetId = target.getOrDefault("targetId", "").toString();150 if (!rootFrameId.equals(targetId)) {151 method("Target.closeTarget").param("targetId", targetId).sendWithoutWaiting();152 }153 }154 });155 }156 }157 public void sendKey(char c, int modifiers, String type, Integer keyCode) {158 DevToolsMessage dtm = method("Input.dispatchKeyEvent")159 .param("modifiers", modifiers)160 .param("type", type);161 if (keyCode == null) {162 dtm.param("text", c + "");163 } else {164 switch (keyCode) {165 case 13:166 dtm.param("text", "\r"); // important ! \n does NOT work for chrome167 break;168 case 9: // TAB169 if ("char".equals(type)) {170 return; // special case171 }172 dtm.param("text", "");173 break;174 case 46: // DOT175 if ("rawKeyDown".equals(type)) {176 dtm.param("type", "keyDown"); // special case177 }178 dtm.param("text", ".");179 break;180 default:181 dtm.param("text", c + "");182 }183 dtm.param("windowsVirtualKeyCode", keyCode);184 }185 dtm.send();186 }187 public void input(String value) {188 Input input = new Input(value);189 while (input.hasNext()) {190 char c = input.next();191 int modifiers = input.getModifierFlags();192 Integer keyCode = Keys.code(c);193 if (keyCode != null) {194 sendKey(c, modifiers, "rawKeyDown", keyCode);195 sendKey(c, modifiers, "char", keyCode);196 sendKey(c, modifiers, "keyUp", keyCode);197 } else {198 sendKey(c, modifiers, "char", -1);199 }200 }201 }202 public static void loadOverride() {203 logger.info("use override chrome");204 }205 @Override206 public void quit() {207 DriverProvider provider = DriverOptions.getDriverProvider();208 if (provider != null) {209 provider.release(this);210 } else {211 super.quit();212 }213 }214 public void quit(Boolean force) {215 if (force) {216 super.quit();217 }218 }219 public static Chrome start(Map<String, Object> map, ScenarioRuntime sr) {220 DriverOptions options = new DriverOptions(map, sr, 9222,221 FileUtils.isOsWindows() ? DEFAULT_PATH_WIN : FileUtils.isOsMacOsX() ? DEFAULT_PATH_MAC : DEFAULT_PATH_LINUX);222 options.arg("--remote-debugging-port=" + options.port);223 options.arg("--no-first-run");224 options.arg("--disable-translate");225 options.arg("--disable-notifications");226 options.arg("--disable-infobars");227 options.arg("--disable-gpu");228 options.arg("--dbus-stub");229 options.arg("--disable-dev-shm-usage");230 if (options.userDataDir != null) {231 options.arg("--user-data-dir=" + options.userDataDir);232 }233 options.arg("--disable-popup-blocking");234 if (options.headless) {235 options.arg("--headless");236 }237 Command command = options.startProcess();238 String webSocketUrl = null;239 if (map.containsKey("debuggerUrl")) {240 webSocketUrl = (String) map.get("debuggerUrl");241 } else {242 Object targetId = map.get("targetId");243 Object startUrl = map.get("startUrl");244 Object top = map.get("top");245 Http http = options.getHttp();246 Command.waitForHttp(http.urlBase + "/json");247 Response res = http.path("json").get();248 if (res.json().asList().isEmpty()) {249 if (command != null) {250 command.close(true);251 }252 throw new RuntimeException("chrome server returned empty list from " + http.urlBase);253 }254 List<Map<String, Object>> targets = res.json().asList();255 for (Map<String, Object> target : targets) {256 String targetUrl = (String) target.get("url");257 if (targetUrl == null || targetUrl.startsWith("chrome-")) {258 continue;259 }260 if (top != null && top.equals(true)) {261 webSocketUrl = (String) target.get("webSocketDebuggerUrl");262 break;263 } else if (targetId != null) {264 if (targetId.equals(target.get("id"))) {265 webSocketUrl = (String) target.get("webSocketDebuggerUrl");266 break;267 }268 } else if (startUrl != null) {269 String targetTitle = (String) target.get("title");270 if (targetUrl.contains(startUrl.toString()) || targetTitle.contains(startUrl.toString())) {271 webSocketUrl = (String) target.get("webSocketDebuggerUrl");272 break;273 }274 } else {275 String targetType = (String) target.get("type");276 if (!"page".equals(targetType)) {277 continue;278 }279 webSocketUrl = (String) target.get("webSocketDebuggerUrl");280 if (options.attach == null) { // take the first281 break;282 }283 if (targetUrl.contains(options.attach)) {284 break;285 }286 }287 }288 }289 if (webSocketUrl == null) {290 throw new RuntimeException("failed to attach to chrome debug server");291 }292 Boolean inject = (Boolean) map.getOrDefault("_inject", false);293 Consumer<Map<String, Object>> filter = (Consumer<Map<String, Object>>) map.getOrDefault("_filter", null);294 Chrome chrome = new Chrome(options, command, webSocketUrl, sr.engine, inject, filter);295 chrome.activate();296 chrome.enablePageEvents();297 chrome.enableRuntimeEvents();298 chrome.enableTargetEvents();299 chrome.enableLog();300 chrome.setDiscoverTargets();301 if (!options.headless) {302 chrome.initWindowIdAndState();303 }304 return chrome;305 }306 public static Chrome start(Boolean start, Consumer<Map<String, Object>> filter, Boolean inject) {307 Map<String, Object> options = new HashMap();308 options.put("start", start);309 options.put("_inject", inject);310 options.put("_filter", filter);311 return Chrome.start(options, KarateRunner.buildScenarioEngine().runtime);312 }313 public static Chrome start(Map<String, Object> options, Consumer<Map<String, Object>> filter, Boolean inject) {314 options.put("_inject", inject);315 options.put("_filter", filter);316 return Chrome.start(options, KarateRunner.buildScenarioEngine().runtime);317 }318 public static Chrome start(Map<String, Object> options, ScenarioEngine engine, Consumer<Map<String, Object>> filter,319 Boolean inject) {320 options.put("_inject", inject);321 options.put("_filter", filter);322 return Chrome.start(options, engine.runtime);323 }324 public static Chrome start(String chromeExecutablePath, boolean headless) {325 Map<String, Object> options = new HashMap();326 options.put("executable", chromeExecutablePath);327 options.put("headless", headless);328 return Chrome.start(options, null);329 }330 public static Chrome start(Map<String, Object> options) {331 if (options == null) {332 options = new HashMap();333 }334 return Chrome.start(options, null);335 }336 public static Chrome start() {337 return start(null);338 }339 public static Chrome startHeadless() {340 return start(Collections.singletonMap("headless", true));341 }342}...
HashMap
Using AI Code Generation
1import com.intuit.karate.driver.Keys2import com.intuit.karate.driver.Keys.*3import com.intuit.karate.driver.Keys.Keys4import com.intuit.karate.driver.Keys.Keys.*5import com.intuit.karate.driver.Keys.Keys.Keys6import com.intuit.karate.driver.Keys.Keys.Keys.*7import com.intuit.karate.driver.Keys.Keys.Keys.Keys8import com.intuit.karate.driver.Keys.Keys.Keys.Keys.*9import com.intuit.karate.driver.Keys.Keys.Keys.Keys.Keys10import com.intuit.karate.driver.Keys.Keys.Keys.Keys.Keys.*11import com.intuit.karate.driver.Keys.Keys.Keys.Keys.Keys.Keys12import com.intuit.karate.driver.Keys.Keys.Keys.Keys.Keys.Keys.*13import com.intuit.karate.driver.Keys.Keys.Keys.Keys.Keys.Keys.Keys14import com.intuit.karate.driver.Keys.Keys.Keys.Keys.Keys.Keys.Keys.*15import com.intuit.karate.driver.Keys.Keys.Keys.Keys.Keys.Keys.Keys.Keys16import com.intuit.karate.driver.Keys.Keys.Keys.Keys.Keys.Keys.Keys.Keys.*17import com.intuit.karate.driver.Keys.Keys.Keys.Keys.Keys.Keys.Keys.Keys.Keys18import com.intuit.karate.driver.Keys.Keys.Keys.Keys.Keys.Keys.Keys.Keys.Keys.*19import com.intuit.karate.driver.Keys.Keys.Ke
HashMap
Using AI Code Generation
1import com.intuit.karate.driver.Keys;2import java.util.HashMap;3import java.util.Map;4import org.junit.Test;5public class 4 {6 public void test() {7 Map<String, Object> map = new HashMap();8 map.put("foo", "bar");9 map.put("baz", 123);10 Keys.set("map", map);11 }12}13import com.intuit.karate.driver.Keys;14import java.util.HashMap;15import java.util.Map;16import org.junit.Test;17public class 5 {18 public void test() {19 Map<String, Object> map = new HashMap();20 map.put("foo", "bar");21 map.put("baz", 123);22 Keys.set("map", map);23 }24}25import com.intuit.karate.driver.Keys;26import java.util.HashMap;27import java.util.Map;28import org.junit.Test;29public class 6 {30 public void test() {31 Map<String, Object> map = new HashMap();32 map.put("foo", "bar");33 map.put("baz", 123);34 Keys.set("map", map);35 }36}37import com.intuit.karate.driver.Keys;38import java.util.HashMap;39import java.util.Map;40import org.junit.Test;41public class 7 {42 public void test() {43 Map<String, Object> map = new HashMap();44 map.put("foo", "bar");45 map.put("baz", 123);46 Keys.set("map", map);47 }48}49import com.intuit.karate.driver.Keys;50import java.util.HashMap;51import java.util.Map;52import org.junit.Test;53public class 8 {54 public void test() {55 Map<String, Object> map = new HashMap();56 map.put("foo", "bar");57 map.put("baz", 123);58 Keys.set("map", map);59 }60}
HashMap
Using AI Code Generation
1import com.intuit.karate.driver.Keys2import com.intuit.karate.driver.Keys.*3def map = Keys.map()4map.put('a', 'b')5map.put('c', 'd')6map.put('e', 'f')7map.put('g', 'h')8map.put('i', 'j')9map.put('k', 'l')10map.put('m', 'n')11map.put('o', 'p')12map.put('q', 'r')13map.put('s', 't')14map.put('u', 'v')15map.put('w', 'x')16map.put('y', 'z')17map.put('A', 'B')18map.put('C', 'D')19map.put('E', 'F')20map.put('G', 'H')21map.put('I', 'J')22map.put('K', 'L')23map.put('M', 'N')24map.put('O', 'P')25map.put('Q', 'R')26map.put('S', 'T')27map.put('U', 'V')28map.put('W', 'X')29map.put('Y', 'Z')30map.put('1', '2')31map.put('3', '4')32map.put('5', '6')33map.put('7', '8')34map.put('9', '0')35map.put('!', '@')36map.put('#', '$')37map.put('%', '^')38map.put('&', '*')39map.put('(', ')')40map.put('-', '_')41map.put('=', '+')42map.put('[', '{')43map.put(']', '}')44map.put(';', ':')45map.put('\'', '"')46map.put(',', '<')47map.put('.', '>')48map.put('/', '?')49map.put('`', '~')50import com.intuit.karate.driver.Keys51import com.intuit.karate.driver.Keys.*52def map = Keys.map()53map.put('a', 'b')54map.put('c', 'd')55map.put('e', 'f')56map.put('g', 'h')57map.put('i', 'j')58map.put('k', 'l')59map.put('m', 'n')60map.put('o', 'p')61map.put('q', 'r')62map.put('s', 't')63map.put('u', '
HashMap
Using AI Code Generation
1import com.intuit.karate.driver.Keys;2import java.util.HashMap;3import java.util.Map;4import java.util.Set;5import org.junit.Test;6public class Demo {7public void testHashMap() {8Map<Character, Integer> map = new HashMap<>();9map.put('A', 65);10map.put('B', 66);11map.put('C', 67);12map.put('D', 68);13map.put('E', 69);14map.put('F', 70);15map.put('G', 71);16map.put('H', 72);17map.put('I', 73);18map.put('J', 74);19map.put('K', 75);20map.put('L', 76);21map.put('M', 77);22map.put('N', 78);23map.put('O', 79);24map.put('P', 80);25map.put('Q', 81);26map.put('R', 82);27map.put('S', 83);28map.put('T', 84);29map.put('U', 85);30map.put('V', 86);31map.put('W', 87);32map.put('X', 88);33map.put('Y', 89);34map.put('Z', 90);35map.put('a', 97);36map.put('b', 98);37map.put('c', 99);38map.put('d', 100);39map.put('e', 101);40map.put('f', 102);41map.put('g', 103);42map.put('h', 104);43map.put('i', 105);44map.put('j', 106);45map.put('k', 107);46map.put('l', 108);47map.put('m', 109);48map.put('n', 110);49map.put('o', 111);50map.put('p', 112);51map.put('q', 113);52map.put('r', 114);53map.put('s', 115);54map.put('t', 116);55map.put('u', 117);56map.put('v', 118);57map.put('w', 119);58map.put('x', 120);59map.put('y', 121);60map.put('z', 122);61map.put('0',
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!!