Best Karate code snippet using com.intuit.karate.driver.Keys.code
Source:ScenarioContext.java
...320 client = HttpClient.construct(config, this);321 bindings = new ScriptBindings(this);322 // TODO improve bindings re-use323 // for call + ui tests, extra step has to be done after bindings set324 // note that the below code depends on bindings inited with things like the "karate" and "read" variable325 if (call.context != null) {326 if (call.context.driver != null) {327 setDriver(call.context.driver);328 } // TODO refactor plugin start329 if (call.context.robot != null) {330 setRobot(call.context.robot);331 }332 }333 if (call.context == null && call.evalKarateConfig) {334 // base config is only looked for in the classpath335 try {336 Script.callAndUpdateConfigAndAlsoVarsIfMapReturned(false, ScriptBindings.READ_KARATE_CONFIG_BASE, null, this);337 } catch (Exception e) {338 if (e instanceof KarateFileNotFoundException) {339 logger.trace("skipping 'classpath:karate-base.js': {}", e.getMessage());340 } else {341 throw new RuntimeException("evaluation of 'classpath:karate-base.js' failed", e);342 }343 }344 String configDir = System.getProperty(ScriptBindings.KARATE_CONFIG_DIR);345 String configScript = ScriptBindings.readKarateConfigForEnv(true, configDir, null);346 try {347 Script.callAndUpdateConfigAndAlsoVarsIfMapReturned(false, configScript, null, this);348 } catch (Exception e) {349 if (e instanceof KarateFileNotFoundException) {350 logger.warn("skipping bootstrap configuration: {}", e.getMessage());351 } else {352 String message = "evaluation of 'karate-config.js' failed: " + e.getMessage();353 logger.error("{}", message);354 throw new RuntimeException(message, e);355 }356 }357 if (featureContext.env != null) {358 configScript = ScriptBindings.readKarateConfigForEnv(false, configDir, featureContext.env);359 try {360 Script.callAndUpdateConfigAndAlsoVarsIfMapReturned(false, configScript, null, this);361 } catch (Exception e) {362 if (e instanceof KarateFileNotFoundException) {363 logger.trace("skipping bootstrap configuration for env: {} - {}", featureContext.env, e.getMessage());364 } else {365 throw new RuntimeException("evaluation of 'karate-config-" + featureContext.env + ".js' failed", e);366 }367 }368 }369 }370 if (call.callArg != null) { // if call.reuseParentContext is true, arg will clobber parent context371 call.callArg.forEach((k, v) -> vars.put(k, v));372 vars.put(Script.VAR_ARG, call.callArg);373 vars.put(Script.VAR_LOOP, call.loopIndex);374 } else if (call.context != null) {375 vars.put(Script.VAR_ARG, ScriptValue.NULL);376 vars.put(Script.VAR_LOOP, -1);377 }378 logger.trace("karate context init - initial properties: {}", vars);379 }380 private static ClassLoader resolveClassLoader(CallContext call) {381 if (call.context == null) {382 return Thread.currentThread().getContextClassLoader();383 }384 return call.context.classLoader;385 }386 public ScenarioContext copy() {387 return new ScenarioContext(this);388 }389 private ScenarioContext(ScenarioContext sc) {390 featureContext = sc.featureContext;391 classLoader = sc.classLoader;392 logger = sc.logger;393 appender = sc.appender;394 callDepth = sc.callDepth;395 reuseParentContext = sc.reuseParentContext;396 parentContext = sc.parentContext;397 executionHooks = sc.executionHooks;398 perfMode = sc.perfMode;399 tags = sc.tags;400 scenario = sc.scenario;401 tagValues = sc.tagValues;402 vars = sc.vars.copy(true); // deep / snap-shot copy403 config = new Config(sc.config); // safe copy404 rootFeatureContext = sc.rootFeatureContext;405 client = HttpClient.construct(config, this);406 bindings = new ScriptBindings(this);407 // state408 request = sc.request.copy();409 prevRequest = sc.prevRequest;410 prevResponse = sc.prevResponse;411 prevPerfEvent = sc.prevPerfEvent;412 callResults = sc.callResults;413 prevEmbeds = sc.prevEmbeds;414 webSocketClients = sc.webSocketClients;415 signalResult = sc.signalResult;416 // plugin TODO make better417 if (sc.driver != null) {418 setDriver(sc.driver);419 }420 if (sc.robot != null) {421 setRobot(sc.robot);422 }423 }424 public void configure(Config config) {425 this.config = config;426 client = HttpClient.construct(config, this);427 }428 public void configure(String key, ScriptValue value) { // TODO use enum429 key = StringUtils.trimToEmpty(key);430 // if next line returns true, http-client needs re-building431 if (config.configure(key, value)) {432 if (key.startsWith("httpClient")) { // special case433 client = HttpClient.construct(config, this);434 } else {435 client.configure(config, this);436 }437 }438 }439 private List<String> evalList(List<String> values) {440 List<String> list = new ArrayList(values.size());441 try {442 for (String value : values) {443 ScriptValue temp = Script.evalKarateExpression(value, this);444 list.add(temp.getAsString());445 }446 } catch (Exception e) { // hack. for e.g. json with commas would land here447 String joined = StringUtils.join(values, ',');448 ScriptValue temp = Script.evalKarateExpression(joined, this);449 if (temp.isListLike()) {450 return temp.getAsList();451 } else {452 return Collections.singletonList(temp.getAsString());453 }454 }455 return list;456 }457 private Map<String, Object> evalMapExpr(String expr) {458 ScriptValue value = Script.evalKarateExpression(expr, this);459 if (!value.isMapLike()) {460 throw new KarateException("cannot convert to map: " + expr);461 }462 return value.getAsMap();463 }464 private String getVarAsString(String name) {465 ScriptValue sv = vars.get(name);466 if (sv == null) {467 throw new RuntimeException("no variable found with name: " + name);468 }469 return sv.getAsString();470 }471 private static String asString(Map<String, Object> map, String key) {472 Object o = map.get(key);473 return o == null ? null : o.toString();474 }475 public void updateResponseVars() {476 vars.put(ScriptValueMap.VAR_RESPONSE_STATUS, prevResponse.getStatus());477 vars.put(ScriptValueMap.VAR_REQUEST_TIME_STAMP, prevResponse.getStartTime());478 vars.put(ScriptValueMap.VAR_RESPONSE_TIME, prevResponse.getResponseTime());479 vars.put(ScriptValueMap.VAR_RESPONSE_COOKIES, prevResponse.getCookies());480 MultiValuedMap responseHeaders = prevResponse.getHeaders();481 if (config.isLowerCaseResponseHeaders() && responseHeaders != null) {482 responseHeaders = responseHeaders.tolowerCaseKeys();483 }484 vars.put(ScriptValueMap.VAR_RESPONSE_HEADERS, responseHeaders);485 byte[] responseBytes = prevResponse.getBody();486 bindings.putAdditionalVariable(ScriptValueMap.VAR_RESPONSE_BYTES, responseBytes);487 String responseString = FileUtils.toString(responseBytes);488 Object responseBody = responseString;489 responseString = StringUtils.trimToEmpty(responseString);490 if (Script.isJson(responseString)) {491 try {492 responseBody = JsonUtils.toJsonDocStrict(responseString);493 vars.put(ScriptValueMap.VAR_RESPONSE_TYPE, "json");494 } catch (Exception e) {495 vars.put(ScriptValueMap.VAR_RESPONSE_TYPE, "string");496 logger.warn("json parsing failed, response data type set to string: {}", e.getMessage());497 }498 } else if (Script.isXml(responseString)) {499 try {500 responseBody = XmlUtils.toXmlDoc(responseString);501 vars.put(ScriptValueMap.VAR_RESPONSE_TYPE, "xml");502 } catch (Exception e) {503 vars.put(ScriptValueMap.VAR_RESPONSE_TYPE, "string");504 logger.warn("xml parsing failed, response data type set to string: {}", e.getMessage());505 }506 } else {507 vars.put(ScriptValueMap.VAR_RESPONSE_TYPE, "string");508 }509 vars.put(ScriptValueMap.VAR_RESPONSE, responseBody);510 }511 public void invokeAfterHookIfConfigured(boolean afterFeature) {512 if (callDepth > 0) {513 return;514 }515 ScriptValue sv = afterFeature ? config.getAfterFeature() : config.getAfterScenario();516 if (sv.isFunction()) {517 try {518 Engine.THREAD_CONTEXT.set(this);519 sv.invokeFunction(this, null);520 Engine.THREAD_CONTEXT.set(null);521 } catch (Exception e) {522 String prefix = afterFeature ? "afterFeature" : "afterScenario";523 logger.warn("{} hook failed: {}", prefix, e.getMessage());524 }525 }526 }527 public Result evalAsStep(String expression) {528 Scenario scenario = executionUnit.scenario;529 Step evalStep = new Step(scenario.getFeature(), scenario, scenario.getIndex() + 1);530 try {531 FeatureParser.updateStepFromText(evalStep, expression);532 } catch (Exception e) {533 return Result.failed(0, e, evalStep);534 }535 Actions evalActions = new StepActions(this);536 return Engine.executeStep(evalStep, evalActions);537 }538 //==========================================================================539 //540 public void configure(String key, String exp) {541 configure(key, Script.evalKarateExpression(exp, this));542 }543 public void url(String expression) {544 String temp = Script.evalKarateExpression(expression, this).getAsString();545 request.setUrl(temp);546 }547 public void path(List<String> paths) {548 for (String path : paths) {549 ScriptValue temp = Script.evalKarateExpression(path, this);550 if (temp.isListLike()) {551 List list = temp.getAsList();552 for (Object o : list) {553 if (o == null) {554 continue;555 }556 request.addPath(o.toString());557 }558 } else {559 request.addPath(temp.getAsString());560 }561 }562 }563 public void param(String name, List<String> values) {564 request.setParam(name, evalList(values));565 }566 public void params(String expr) {567 Map<String, Object> map = evalMapExpr(expr);568 for (Map.Entry<String, Object> entry : map.entrySet()) {569 String key = entry.getKey();570 Object temp = entry.getValue();571 if (temp == null) {572 request.removeParam(key);573 } else {574 if (temp instanceof List) {575 request.setParam(key, (List) temp);576 } else {577 request.setParam(key, temp.toString());578 }579 }580 }581 }582 public void cookie(String name, String value) {583 ScriptValue sv = Script.evalKarateExpression(value, this);584 Cookie cookie;585 if (sv.isMapLike()) {586 cookie = new Cookie((Map) sv.getAsMap());587 cookie.put(Cookie.NAME, name);588 } else {589 cookie = new Cookie(name, sv.getAsString());590 }591 request.setCookie(cookie);592 }593 public void cookies(String expr) {594 Map<String, Object> map = evalMapExpr(expr);595 for (Map.Entry<String, Object> entry : map.entrySet()) {596 String key = entry.getKey();597 Object temp = entry.getValue();598 if (temp == null) {599 request.removeCookie(key);600 } else {601 request.setCookie(new Cookie(key, temp.toString()));602 }603 }604 }605 public void header(String name, List<String> values) {606 request.setHeader(name, evalList(values));607 }608 public void headers(String expr) {609 Map<String, Object> map = evalMapExpr(expr);610 for (Map.Entry<String, Object> entry : map.entrySet()) {611 String key = entry.getKey();612 Object temp = entry.getValue();613 if (temp == null) {614 request.removeHeader(key);615 } else {616 if (temp instanceof List) {617 request.setHeader(key, (List) temp);618 } else {619 request.setHeader(key, temp.toString());620 }621 }622 }623 }624 public void formField(String name, List<String> values) {625 request.setFormField(name, evalList(values));626 }627 public void formFields(String expr) {628 Map<String, Object> map = evalMapExpr(expr);629 for (Map.Entry<String, Object> entry : map.entrySet()) {630 String key = entry.getKey();631 Object temp = entry.getValue();632 if (temp == null) {633 request.removeFormField(key);634 } else {635 if (temp instanceof List) {636 request.setFormField(key, (List) temp);637 } else {638 request.setFormField(key, temp.toString());639 }640 }641 }642 }643 public void request(ScriptValue body) {644 request.setBody(body);645 }646 public void request(String requestBody) {647 ScriptValue temp = Script.evalKarateExpression(requestBody, this);648 request(temp);649 }650 public void table(String name, List<Map<String, String>> table) {651 int pos = name.indexOf('='); // backward compatibility, we used to require this till v0.5.0652 if (pos != -1) {653 name = name.substring(0, pos);654 }655 List<Map<String, Object>> list = Script.evalTable(table, this);656 DocumentContext doc = JsonPath.parse(list);657 vars.put(name.trim(), doc);658 }659 public void replace(String name, List<Map<String, String>> table) {660 name = name.trim();661 String text = getVarAsString(name);662 String replaced = Script.replacePlaceholders(text, table, this);663 vars.put(name, replaced);664 }665 public void replace(String name, String token, String value) {666 name = name.trim();667 String text = getVarAsString(name);668 String replaced = Script.replacePlaceholderText(text, token, value, this);669 vars.put(name, replaced);670 }671 public void assign(AssignType assignType, String name, String exp) {672 Script.assign(assignType, name, exp, this, true);673 }674 public void assertTrue(String expression) {675 AssertionResult ar = Script.assertBoolean(expression, this);676 if (!ar.pass) {677 logger.error("{}", ar);678 throw new KarateException(ar.message);679 }680 }681 private void clientInvoke() {682 try {683 prevResponse = client.invoke(request, this);684 updateResponseVars();685 } catch (Exception e) {686 String message = e.getMessage();687 logger.error("http request failed: {}", message);688 throw new KarateException(message); // reduce log verbosity689 }690 }691 private void clientInvokeWithRetries() {692 int maxRetries = config.getRetryCount();693 int sleep = config.getRetryInterval();694 int retryCount = 0;695 while (true) {696 if (retryCount == maxRetries) {697 throw new KarateException("too many retry attempts: " + maxRetries);698 }699 if (retryCount > 0) {700 try {701 logger.debug("sleeping before retry #{}", retryCount);702 Thread.sleep(sleep);703 } catch (Exception e) {704 throw new RuntimeException(e);705 }706 }707 clientInvoke();708 ScriptValue sv;709 try {710 sv = Script.evalKarateExpression(request.getRetryUntil(), this);711 } catch (Exception e) {712 logger.warn("retry condition evaluation failed: {}", e.getMessage());713 sv = ScriptValue.NULL;714 }715 if (sv.isBooleanTrue()) {716 if (retryCount > 0) {717 logger.debug("retry condition satisfied");718 }719 break;720 } else {721 logger.debug("retry condition not satisfied: {}", request.getRetryUntil());722 }723 retryCount++;724 }725 }726 public void method(String method) {727 if (!HttpUtils.HTTP_METHODS.contains(method.toUpperCase())) { // support expressions also728 method = Script.evalKarateExpression(method, this).getAsString();729 }730 request.setMethod(method);731 if (request.isRetry()) {732 clientInvokeWithRetries();733 } else {734 clientInvoke();735 }736 String prevUrl = request.getUrl();737 request = new HttpRequestBuilder();738 request.setUrl(prevUrl);739 }740 public void retry(String expression) {741 request.setRetryUntil(expression);742 }743 public void soapAction(String action) {744 action = Script.evalKarateExpression(action, this).getAsString();745 if (action == null) {746 action = "";747 }748 request.setHeader("SOAPAction", action);749 request.setHeader("Content-Type", "text/xml");750 method("post");751 }752 public void multipartField(String name, String value) {753 ScriptValue sv = Script.evalKarateExpression(value, this);754 request.addMultiPartItem(name, sv);755 }756 public void multipartFields(String expr) {757 Map<String, Object> map = evalMapExpr(expr);758 map.forEach((k, v) -> {759 ScriptValue sv = new ScriptValue(v);760 request.addMultiPartItem(k, sv);761 });762 }763 public void multipartFile(String name, String value) {764 name = name.trim();765 ScriptValue sv = Script.evalKarateExpression(value, this);766 if (!sv.isMapLike()) {767 throw new RuntimeException("mutipart file value should be json");768 }769 ScriptValue fileValue;770 Map<String, Object> map = sv.getAsMap();771 String read = asString(map, "read");772 if (read == null) {773 Object o = map.get("value");774 fileValue = o == null ? null : new ScriptValue(o);775 } else {776 fileValue = FileUtils.readFile(read, this);777 }778 if (fileValue == null) {779 throw new RuntimeException("mutipart file json should have a value for 'read' or 'value'");780 }781 MultiPartItem item = new MultiPartItem(name, fileValue);782 String filename = asString(map, "filename");783 item.setFilename(filename);784 String contentType = asString(map, "contentType");785 if (contentType != null) {786 item.setContentType(contentType);787 }788 request.addMultiPartItem(item);789 }790 public void multipartFiles(String expr) {791 Map<String, Object> map = evalMapExpr(expr);792 map.forEach((k, v) -> {793 ScriptValue sv = new ScriptValue(v);794 multipartFile(k, sv.getAsString());795 });796 }797 public void print(List<String> exps) {798 if (isPrintEnabled()) {799 String prev = ""; // handle rogue commas embedded in string literals800 StringBuilder sb = new StringBuilder();801 sb.append("[print]");802 for (String exp : exps) {803 if (!prev.isEmpty()) {804 exp = prev + StringUtils.trimToNull(exp);805 }806 if (exp == null) {807 sb.append("null");808 } else {809 ScriptValue sv = Script.getIfVariableReference(exp.trim(), this); // trim is important810 if (sv == null) {811 try {812 sv = Script.evalJsExpression(exp, this);813 prev = ""; // evalKarateExpression success, reset rogue comma detector814 } catch (Exception e) {815 prev = exp + ", ";816 continue;817 }818 }819 sb.append(' ').append(sv.getAsPrettyString());820 }821 }822 logger.info("{}", sb);823 }824 }825 public void status(int status) {826 if (status != prevResponse.getStatus()) {827 String rawResponse = vars.get(ScriptValueMap.VAR_RESPONSE).getAsString();828 String responseTime = vars.get(ScriptValueMap.VAR_RESPONSE_TIME).getAsString();829 String message = "status code was: " + prevResponse.getStatus() + ", expected: " + status830 + ", response time: " + responseTime + ", url: " + prevResponse.getUri() + ", response: " + rawResponse;831 logger.error(message);832 throw new KarateException(message);833 }834 }835 public void match(MatchType matchType, String name, String path, String expected) {836 AssertionResult ar = Script.matchNamed(matchType, name, path, expected, this);837 if (!ar.pass) {838 logger.error("{}", ar);839 throw new KarateException(ar.message);840 }841 }842 public void set(String name, String path, String value) {843 Script.setValueByPath(name, path, value, this);...
Source:DevToolsDriver.java
...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"))414 .send();415 windowState = "normal";416 }417 if (!state.equals(windowState)) {418 method("Browser.setWindowBounds")419 .param("windowId", windowId)420 .param("bounds", Collections.singletonMap("windowState", state))421 .send();422 windowState = state;423 }424 }425 @Override426 public void maximize() {427 setWindowState("maximized");428 }429 @Override430 public void minimize() {431 setWindowState("minimized");432 }433 @Override434 public void fullscreen() {435 setWindowState("fullscreen");436 }437 @Override438 public Element click(String locator) {439 retryIfEnabled(locator);440 eval(DriverOptions.selector(locator) + ".click()");441 return DriverElement.locatorExists(this, locator);442 }443 @Override444 public Element select(String locator, String text) {445 retryIfEnabled(locator);446 eval(options.optionSelector(locator, text));447 return DriverElement.locatorExists(this, locator);448 }449 @Override450 public Element select(String locator, int index) {451 retryIfEnabled(locator);452 eval(options.optionSelector(locator, index));453 return DriverElement.locatorExists(this, locator);454 }455 @Override456 public Driver submit() {457 submit = true;458 return this;459 }460 @Override461 public Element focus(String locator) {462 retryIfEnabled(locator);463 eval(options.focusJs(locator));464 return DriverElement.locatorExists(this, locator);465 }466 @Override467 public Element clear(String locator) {468 eval(DriverOptions.selector(locator) + ".value = ''");469 return DriverElement.locatorExists(this, locator);470 }471 private void sendKey(char c, int modifiers, String type, Integer keyCode) {472 DevToolsMessage dtm = method("Input.dispatchKeyEvent")473 .param("modifiers", modifiers)474 .param("type", type);475 if (keyCode == null) {476 dtm.param("text", c + "");477 } else {478 switch (keyCode) {479 case 13:480 dtm.param("text", "\r"); // important ! \n does NOT work for chrome481 break;482 case 9: // TAB483 if ("char".equals(type)) {484 return; // special case485 }486 dtm.param("text", "");487 break;488 case 46: // DOT489 if ("rawKeyDown".equals(type)) {490 dtm.param("type", "keyDown"); // special case491 }492 dtm.param("text", ".");493 break;494 default:495 dtm.param("text", c + "");496 }497 dtm.param("windowsVirtualKeyCode", keyCode);498 }499 dtm.send();500 }501 @Override502 public Element input(String locator, String value) {503 retryIfEnabled(locator);504 // focus505 eval(options.focusJs(locator));506 Input input = new Input(value);507 while (input.hasNext()) {508 char c = input.next();509 int modifiers = input.getModifierFlags();510 Integer keyCode = Keys.code(c);511 if (keyCode != null) {512 sendKey(c, modifiers, "rawKeyDown", keyCode);513 sendKey(c, modifiers, "char", keyCode);514 sendKey(c, modifiers, "keyUp", keyCode);515 } else {516 logger.warn("unknown character / key code: {}", c);517 sendKey(c, modifiers, "char", null);518 }519 }520 return DriverElement.locatorExists(this, locator);521 }522 protected int currentMouseXpos;523 protected int currentMouseYpos;524 @Override525 public void actions(List<Map<String, Object>> sequence) {526 boolean submitRequested = submit;527 submit = false; // make sure only LAST action is handled as a submit()528 for (Map<String, Object> map : sequence) {529 List<Map<String, Object>> actions = (List) map.get("actions");530 if (actions == null) {531 logger.warn("no actions property found: {}", sequence);532 return;533 }534 Iterator<Map<String, Object>> iterator = actions.iterator();535 while (iterator.hasNext()) {536 Map<String, Object> action = iterator.next();537 String type = (String) action.get("type");538 if (type == null) {539 logger.warn("no type property found: {}", action);540 continue;541 }542 String chromeType;543 switch (type) {544 case "pointerMove":545 chromeType = "mouseMoved";546 break;547 case "pointerDown":548 chromeType = "mousePressed";549 break;550 case "pointerUp":551 chromeType = "mouseReleased";552 break;553 default:554 logger.warn("unexpected action type: {}", action);555 continue;556 }557 Integer x = (Integer) action.get("x");558 Integer y = (Integer) action.get("y");559 if (x != null) {560 currentMouseXpos = x;561 }562 if (y != null) {563 currentMouseYpos = y;564 }565 Integer duration = (Integer) action.get("duration");566 DevToolsMessage toSend = method("Input.dispatchMouseEvent")567 .param("type", chromeType)568 .param("x", currentMouseXpos).param("y", currentMouseYpos);569 if ("mousePressed".equals(chromeType) || "mouseReleased".equals(chromeType)) {570 toSend.param("button", "left").param("clickCount", 1);571 }572 if (!iterator.hasNext() && submitRequested) {573 submit = true;574 }575 toSend.send();576 if (duration != null) {577 options.sleep(duration);578 }579 }580 }581 }582 @Override583 public String text(String id) {584 return property(id, "textContent");585 }586 @Override587 public String html(String id) {588 return property(id, "outerHTML");589 }590 @Override591 public String value(String locator) {592 return property(locator, "value");593 }594 @Override595 public Element value(String locator, String value) {596 retryIfEnabled(locator);597 eval(DriverOptions.selector(locator) + ".value = '" + value + "'");598 return DriverElement.locatorExists(this, locator);599 }600 @Override601 public String attribute(String id, String name) {602 retryIfEnabled(id);603 DevToolsMessage dtm = eval(DriverOptions.selector(id) + ".getAttribute('" + name + "')");604 return dtm.getResult().getAsString();605 }606 @Override607 public String property(String id, String name) {608 retryIfEnabled(id);609 DevToolsMessage dtm = eval(DriverOptions.selector(id) + "['" + name + "']");610 return dtm.getResult().getAsString();611 }612 @Override613 public boolean enabled(String id) {614 retryIfEnabled(id);615 DevToolsMessage dtm = eval(DriverOptions.selector(id) + ".disabled");616 return !dtm.getResult().isTrue();617 }618 @Override619 public boolean waitUntil(String expression) {620 return options.retry(() -> {621 try {622 return eval(expression, true).getResult().isTrue();623 } catch (Exception e) {624 logger.warn("waitUntil evaluate failed: {}", e.getMessage());625 return false;626 }627 }, b -> b, "waitUntil (js)", true);628 }629 @Override630 public Object script(String expression) {631 return eval(expression).getResult().getValue();632 }633 @Override634 public String getTitle() {635 return eval("document.title").getResult().getAsString();636 }637 @Override638 public String getUrl() {639 return eval("document.location.href").getResult().getAsString();640 }641 @Override642 public List<Map> getCookies() {643 DevToolsMessage dtm = method("Network.getAllCookies").send();644 return dtm.getResult("cookies").getValue();645 }646 @Override647 public Map<String, Object> cookie(String name) {648 List<Map> list = getCookies();649 if (list == null) {650 return null;651 }652 for (Map<String, Object> map : list) {653 if (map != null && name.equals(map.get("name"))) {654 return map;655 }656 }657 return null;658 }659 @Override660 public void cookie(Map<String, Object> cookie) {661 if (cookie.get("url") == null && cookie.get("domain") == null) {662 cookie = new HashMap(cookie); // don't mutate test663 cookie.put("url", getUrl());664 }665 method("Network.setCookie").params(cookie).send();666 }667 @Override668 public void deleteCookie(String name) {669 method("Network.deleteCookies").param("name", name).param("url", getUrl()).send();670 }671 @Override672 public void clearCookies() {673 method("Network.clearBrowserCookies").send();674 }675 @Override676 public void dialog(boolean accept) {677 dialog(accept, null);678 }679 @Override680 public void dialog(boolean accept, String text) {681 DevToolsMessage temp = method("Page.handleJavaScriptDialog").param("accept", accept);682 if (text == null) {683 temp.send();684 } else {685 temp.param("promptText", text).send();686 }687 }688 @Override689 public String getDialogText() {690 return currentDialogText;691 }692 @Override693 public byte[] pdf(Map<String, Object> options) {694 DevToolsMessage dtm = method("Page.printToPDF").params(options).send();695 String temp = dtm.getResult("data").getAsString();696 return Base64.getDecoder().decode(temp);697 }698 @Override699 public byte[] screenshot(boolean embed) {700 return screenshot(null, embed);701 }702 @Override703 public Map<String, Object> position(String locator) {704 boolean submitTemp = submit; // in case we are prepping for a submit().mouse(locator).click()705 submit = false;706 retryIfEnabled(locator);707 Map<String, Object> map = eval(DriverOptions.getPositionJs(locator)).getResult().getValue();708 submit = submitTemp;709 return map;710 }711 @Override712 public byte[] screenshot(String id, boolean embed) {713 DevToolsMessage dtm;714 if (id == null) {715 dtm = method("Page.captureScreenshot").send();716 } else {717 Map<String, Object> map = position(id);718 map.put("scale", 1);719 dtm = method("Page.captureScreenshot").param("clip", map).send();720 }721 String temp = dtm.getResult("data").getAsString();722 byte[] bytes = Base64.getDecoder().decode(temp);723 if (embed) {724 getRuntime().embed(bytes, ResourceType.PNG);725 }726 return bytes;727 }728 // chrome only729 public byte[] screenshotFull() {730 DevToolsMessage layout = method("Page.getLayoutMetrics").send();731 Map<String, Object> size = layout.getResult("contentSize").getValue();732 Map<String, Object> map = options.newMapWithSelectedKeys(size, "height", "width");733 map.put("x", 0);734 map.put("y", 0);735 map.put("scale", 1);736 DevToolsMessage dtm = method("Page.captureScreenshot").param("clip", map).send();737 if (dtm.isResultError()) {738 logger.error("unable to capture screenshot: {}", dtm);739 return new byte[0];740 }741 String temp = dtm.getResult("data").getAsString();742 return Base64.getDecoder().decode(temp);743 }744 @Override745 public List<String> getPages() {746 DevToolsMessage dtm = method("Target.getTargets").send();747 return dtm.getResult("targetInfos.targetId").getValue();748 }749 @Override750 public void switchPage(String titleOrUrl) {751 if (titleOrUrl == null) {752 return;753 }754 DevToolsMessage dtm = method("Target.getTargets").send();755 List<Map> targets = dtm.getResult("targetInfos").getValue();756 String targetId = null;...
Source:Chrome.java
...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() {...
code
Using AI Code Generation
1import com.intuit.karate.driver.Keys;2import com.intuit.karate.junit5.Karate;3class 4 {4 Karate testAll() {5 return Karate.run().relativeTo(getClass());6 }7}8import com.intuit.karate.driver.Keys;9import com.intuit.karate.junit5.Karate;10class 5 {11 Karate testAll() {12 return Karate.run().relativeTo(getClass());13 }14}15import com.intuit.karate.driver.Keys;16import com.intuit.karate.junit5.Karate;17class 6 {18 Karate testAll() {19 return Karate.run().relativeTo(getClass());20 }21}22import com.intuit.karate.driver.Keys;23import com.intuit.karate.junit5.Karate;24class 7 {25 Karate testAll() {26 return Karate.run().relativeTo(getClass());27 }28}29import com.intuit.karate.driver.Keys;30import com.intuit.karate.junit5.Karate;31class 8 {32 Karate testAll() {33 return Karate.run().relativeTo(getClass());34 }35}36import com.intuit.karate.driver.Keys;37import com.intuit.karate.junit5.Karate;38class 9 {39 Karate testAll() {40 return Karate.run().relativeTo(getClass());41 }42}43import com.intuit.karate.driver.Keys;44import com.intuit.karate.junit5.Karate;45class 10 {
code
Using AI Code Generation
1package demo;2import com.intuit.karate.junit5.Karate;3public class 4 {4 Karate testAll() {5 return Karate.run().relativeTo(getClass());6 }7}8 * def driver = { driver: 'chrome' }9 * def driverOptions = { args: ['--start-maximized'] }10 * driver = driver(driver)11 * driver sendKeys { id: 'lst-ib' } 'hello' code: com.intuit.karate.driver.Keys.ENTER12function() {13 var driver = karate.driver('chrome');14 var driverOptions = { args: ['--start-maximized'] };15 driver.driverOptions = driverOptions;16 driver = driver(driver);17 driver.sendKeys({ id: 'lst-ib' }, 'hello', { code: com.intuit.karate.driver.Keys.ENTER });18 driver.quit();19}20{21 "driverOptions": {22 }23}24package demo;25import com.intuit.karate.junit5.Karate;26public class 5 {27 Karate testAll() {28 return Karate.run().relativeTo(getClass());29 }30}
code
Using AI Code Generation
1import com.intuit.karate.driver.Keys;2import com.intuit.karate.driver.AppiumDriver;3import com.intuit.karate.driver.AppiumOptions;4import org.junit.jupiter.api.Test;5import static org.junit.jupiter.api.Assertions.*;6class AppiumTest {7 void testAppium() {8 AppiumOptions options = new AppiumOptions();9 options.setCapability("platformName", "Android");10 options.setCapability("deviceName", "emulator-5554");
code
Using AI Code Generation
1import com.intuit.karate.driver.Keys;2import com.intuit.karate.driver.AppiumDriver;3import com.intuit.karate.driver.WebDriver;4import com.intuit.karate.driver.appium.AppiumDriverBuilder;5import com.intuit.karate.driver.appium.AppiumOptions;6import com.intuit.karate.driver.appium.AppiumOptionsBuilder;7import com.intuit.karate.driver.web.WebDriverBuilder;8import com.intuit.karate.driver.web.WebDriverOptions;9import com.intuit.karate.driver.web.WebDriverOptionsBuilder;10import org.openqa.selenium.By;11import org.openqa.selenium.WebElement;12import org.openqa.selenium.remote.DesiredCapabilities;13import org.openqa.selenium.support.ui.ExpectedConditions;14import org.openqa.selenium.support.ui.WebDriverWait;15import java.util.concurrent.TimeUnit;16public class 4 {17 public static void main(String[] args) {18 DesiredCapabilities caps = new DesiredCapabilities();19 caps.setCapability("platformName", "Android");20 caps.setCapability("platformVersion", "10");21 caps.setCapability("deviceName", "Samsung Galaxy S10");22 caps.setCapability("automationName", "UiAutomator2");23 caps.setCapability("appPackage", "com.android.calculator2");24 caps.setCapability("appActivity", "com.android.calculator2.Calculator");25 AppiumOptions options = AppiumOptionsBuilder.with(caps).build();26 AppiumDriver driver = AppiumDriverBuilder.forAppium(options).build();27 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);28 WebElement one = driver.findElement(By.id("com.android.calculator2:id/digit_1"));29 WebElement plus = driver.findElement(By.id("com.android.calculator2:id/op_add"));30 WebElement two = driver.findElement(By.id("com.android.calculator2:id/digit_2"));31 WebElement equal = driver.findElement(By.id("com.android.calculator2:id/eq"));32 one.click();33 plus.click();34 two.click();35 equal.click();36 WebElement result = driver.findElement(By.id("com.android.calculator2:id/result"));37 System.out.println(result.getText());38 driver.quit();39 }40}41import com.intuit.karate.driver.Keys;42import com.intuit.karate.driver.AppiumDriver;43import com.intuit.karate.driver.WebDriver;44import com.intuit.k
code
Using AI Code Generation
1def driver = karate.getWebDriver()2driver.findElement(By.name('q')).sendKeys('karate', Keys.ENTER)3driver.quit()4def driver = karate.getWebDriver()5driver.findElement(By.name('q')).sendKeys('karate', Keys.ENTER)6driver.quit()7def driver = karate.getWebDriver()8driver.findElement(By.name('q')).sendKeys('karate', Keys.ENTER)9driver.quit()10def driver = karate.getWebDriver()11driver.findElement(By.name('q')).sendKeys('karate', Keys.ENTER)12driver.quit()13def driver = karate.getWebDriver()14driver.findElement(By.name('q')).sendKeys('karate', Keys.ENTER)15driver.quit()16def driver = karate.getWebDriver()17driver.findElement(By.name('q')).sendKeys('karate', Keys.ENTER)18driver.quit()19def driver = karate.getWebDriver()20driver.findElement(By.name('q')).sendKeys('karate', Keys.ENTER)21driver.quit()22def driver = karate.getWebDriver()23driver.findElement(By.name('q')).sendKeys('karate', Keys.ENTER)24driver.quit()25def driver = karate.getWebDriver()26driver.findElement(By.name('q')).sendKeys('
code
Using AI Code Generation
1package demo;2import com.intuit.karate.driver.Keys;3import com.intuit.karate.junit5.Karate;4class DemoJava {5 Karate testSample() {6 return Karate.run("sample").tags("@demo").relativeTo(getClass());7 }8 Karate testKeys() {9 Keys keys = new Keys();10 String text = keys.code("ctrl", "a", "delete");11 return Karate.run("keys").tags("@demo").relativeTo(getClass());12 }13}14 * driver.type('#lst-ib', 'karate')15 * driver.sendKeys('#lst-ib', code('ctrl', 'a', 'delete'))16 * driver.sendKeys('#lst-ib', code('ctrl', 'v'))17 * driver.sendKeys('#lst-ib', code('ctrl', 'a', 'delete'))18 * driver.sendKeys('#lst-ib', 'karate')19 * driver.sendKeys('#lst-ib', code('enter'))20 * driver.type('#lst-ib', 'karate')21 * driver.sendKeys('#lst-ib', code('ctrl', 'a', 'delete'))22 * driver.sendKeys('#lst-ib', code('ctrl', 'v'))23 * driver.sendKeys('#lst-ib', code('ctrl', 'a', 'delete'))24 * driver.sendKeys('#lst-ib', 'karate')25 * driver.sendKeys('#lst-ib', code('enter'))
code
Using AI Code Generation
1import com.intuit.karate.driver.Keys;2import com.intuit.karate.KarateOptions;3@KarateOptions(tags = "@code")4public class 4 {5 public static void main(String[] args) {6 Keys.code("Hello World");7 }8}9import com.intuit.karate.driver.Keys;10import com.intuit.karate.KarateOptions;11@KarateOptions(tags = "@code")12public class 5 {13 public static void main(String[] args) {14 Keys.code("Hello World");15 }16}17import com.intuit.karate.driver.Keys;18import com.intuit.karate.KarateOptions;19@KarateOptions(tags = "@code")20public class 6 {21 public static void main(String[] args) {22 Keys.code("Hello World");23 }24}25import com.intuit.karate.driver.Keys;26import com.intuit.karate.KarateOptions;27@KarateOptions(tags = "@code")28public class 7 {29 public static void main(String[] args) {30 Keys.code("Hello World");31 }32}33import com.intuit.karate.driver.Keys;34import com.intuit.karate.KarateOptions;35@KarateOptions(tags = "@code")36public class 8 {37 public static void main(String[] args) {38 Keys.code("Hello World");39 }40}41import com.intuit.karate.driver.Keys;42import com.intuit.karate.KarateOptions;43@KarateOptions(tags = "@code")44public class 9 {45 public static void main(String[] args) {46 Keys.code("Hello World");47 }48}
code
Using AI Code Generation
1* def driver = { driver: 'chrome', headless: false }2* def driver = { driver: 'chrome', headless: false }3* def driver = { driver: 'chrome', headless: false }4* def element = driver.findElement(By.name('q'))5* def element = driver.findElement(By.name('q'))6* def element = driver.findElement(By.name('q'))7* element.sendKeys(Keys.code('hello'))
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!!