Best Karate code snippet using com.intuit.karate.core.ScenarioEngine.CompletableFuture
Source:ScenarioEngine.java
...35import java.util.List;36import java.util.Map;37import java.util.Optional;38import java.util.Set;39import java.util.concurrent.CompletableFuture;40import java.util.concurrent.TimeUnit;41import java.util.function.BiConsumer;42import java.util.function.Function;43import java.util.regex.Matcher;44import java.util.regex.Pattern;45import org.graalvm.polyglot.Value;46import org.slf4j.LoggerFactory;47import org.w3c.dom.Attr;48import org.w3c.dom.Document;49import org.w3c.dom.NamedNodeMap;50import org.w3c.dom.Node;51import org.w3c.dom.NodeList;52import com.intuit.karate.FileUtils;53import com.intuit.karate.Json;54import com.intuit.karate.JsonUtils;55import com.intuit.karate.KarateException;56import com.intuit.karate.Logger;57import com.intuit.karate.Match;58import com.intuit.karate.RuntimeHook;59import com.intuit.karate.StringUtils;60import com.intuit.karate.XmlUtils;61import com.intuit.karate.driver.Driver;62import com.intuit.karate.driver.DriverOptions;63import com.intuit.karate.driver.Key;64import com.intuit.karate.driver.chrome.Chrome;65import com.intuit.karate.graal.JsEngine;66import com.intuit.karate.graal.JsFunction;67import com.intuit.karate.graal.JsValue;68import com.intuit.karate.http.ArmeriaHttpClient;69import com.intuit.karate.http.Cookies;70import com.intuit.karate.http.HttpClient;71import com.intuit.karate.http.HttpConstants;72import com.intuit.karate.http.HttpLogger;73import com.intuit.karate.http.HttpRequest;74import com.intuit.karate.http.HttpRequestBuilder;75import com.intuit.karate.http.Request;76import com.intuit.karate.http.ResourceType;77import com.intuit.karate.http.Response;78import com.intuit.karate.http.WebSocketClient;79import com.intuit.karate.http.WebSocketOptions;80import com.intuit.karate.shell.Command;81import com.intuit.karate.template.KarateTemplateEngine;82import com.intuit.karate.template.TemplateUtils;83import com.jayway.jsonpath.PathNotFoundException;84import asura.ui.karate.plugins.Img;85import asura.ui.karate.plugins.Ocr;86/**87 * @author pthomas388 */89public class ScenarioEngine {90 private static org.slf4j.Logger slf4jLogger = LoggerFactory.getLogger(ScenarioEngine.class);91 private static final String KARATE = "karate";92 private static final String READ = "read";93 private static final String DRIVER = "driver";94 private static final String ROBOT = "robot";95 private static final String KEY = "Key";96 public static final String RESPONSE = "response";97 public static final String RESPONSE_HEADERS = "responseHeaders";98 public static final String RESPONSE_STATUS = "responseStatus";99 private static final String RESPONSE_BYTES = "responseBytes";100 private static final String RESPONSE_COOKIES = "responseCookies";101 private static final String RESPONSE_TIME = "responseTime";102 private static final String RESPONSE_TYPE = "responseType";103 private static final String LISTEN_RESULT = "listenResult";104 public static final String REQUEST = "request";105 public static final String REQUEST_URL_BASE = "requestUrlBase";106 public static final String REQUEST_URI = "requestUri";107 private static final String REQUEST_PARAMS = "requestParams";108 public static final String REQUEST_METHOD = "requestMethod";109 public static final String REQUEST_HEADERS = "requestHeaders";110 private static final String REQUEST_TIME_STAMP = "requestTimeStamp";111 public final ScenarioRuntime runtime;112 public final ScenarioFileReader fileReader;113 public final Map<String, Variable> vars;114 public final Logger logger;115 private final Function<String, Object> readFunction;116 private final ScenarioBridge bridge;117 private final Collection<RuntimeHook> hooks;118 private boolean aborted;119 private Throwable failedReason;120 protected JsEngine JS;121 // only used by mock server122 public ScenarioEngine(ScenarioRuntime runtime, Map<String, Variable> vars) {123 this(runtime.engine.config, runtime, vars, runtime.logger);124 }125 public ScenarioEngine(Config config, ScenarioRuntime runtime, Map<String, Variable> vars, Logger logger) {126 this.config = config;127 this.runtime = runtime;128 hooks = runtime.featureRuntime.suite.hooks;129 fileReader = new ScenarioFileReader(this, runtime.featureRuntime);130 readFunction = s -> JsValue.fromJava(fileReader.readFile(s));131 bridge = new ScenarioBridge();132 this.vars = vars;133 this.logger = logger;134 }135 public static void loadOverride() {136 slf4jLogger.info("use override ScenarioEngine");137 }138 public static ScenarioEngine forTempUse() {139 FeatureRuntime fr = FeatureRuntime.forTempUse();140 ScenarioRuntime sr = new ScenarioIterator(fr).first();141 sr.engine.init();142 return sr.engine;143 }144 protected List<ScenarioEngine> children;145 private ScenarioEngine parent;146 // @FIXME override start147 public HashMap<String, NewDriver> newDrivers = new HashMap<>();148 public static class NewDriver {149 public String name;150 public Map<String, Object> options;151 public Driver driver;152 public NewDriver(String name, Map<String, Object> options, Driver driver) {153 this.name = name;154 this.options = options;155 this.driver = driver;156 }157 public boolean isStop() {158 return (boolean) options.getOrDefault("stop", true);159 }160 public boolean isRemote() {161 if (options.containsKey("host")) {162 String host = (String) options.get("host");163 if (host.equals("localhost") || host.startsWith("127.")) {164 return false;165 } else {166 return true;167 }168 } else {169 return false;170 }171 }172 public void stopDriver() {173 if (driver instanceof Chrome && isRemote()) {174 ((Chrome) driver).closeClient();175 } else {176 driver.quit();177 }178 }179 }180 // override end181 public ScenarioEngine child() {182 ScenarioEngine child = new ScenarioEngine(config, runtime, detachVariables(), logger);183 child.parent = this;184 if (children == null) {185 children = new ArrayList();186 }187 children.add(child);188 return child;189 }190 private static final ThreadLocal<ScenarioEngine> THREAD_LOCAL = new ThreadLocal<ScenarioEngine>();191 public static ScenarioEngine get() {192 return THREAD_LOCAL.get();193 }194 public static void set(ScenarioEngine se) {195 THREAD_LOCAL.set(se);196 }197 public static void remove() {198 THREAD_LOCAL.remove();199 }200 // engine ==================================================================201 //202 public boolean isAborted() {203 return aborted;204 }205 public void setAborted(boolean aborted) {206 this.aborted = aborted;207 }208 public boolean isFailed() {209 return failedReason != null;210 }211 public boolean isIgnoringStepErrors() {212 return !config.getContinueOnStepFailureMethods().isEmpty();213 }214 public void setFailedReason(Throwable failedReason) {215 this.failedReason = failedReason;216 }217 public Throwable getFailedReason() {218 return failedReason;219 }220 public void matchResult(Match.Type matchType, String expression, String path, String expected) {221 Match.Result mr = match(matchType, expression, path, expected);222 if (!mr.pass) {223 setFailedReason(new KarateException(mr.message));224 }225 }226 public void set(String name, String path, String exp) {227 set(name, path, exp, false, false);228 }229 public void remove(String name, String path) {230 set(name, path, null, true, false);231 }232 public void table(String name, List<Map<String, String>> rows) {233 List<Map<String, Object>> result = new ArrayList<>(rows.size());234 for (Map<String, String> map : rows) {235 Map<String, Object> row = new LinkedHashMap<>(map);236 List<String> toRemove = new ArrayList(map.size());237 for (Map.Entry<String, Object> entry : row.entrySet()) {238 String exp = (String) entry.getValue();239 Variable sv = evalKarateExpression(exp);240 if (sv.isNull() && !isWithinParentheses(241 exp)) { // by default empty / null will be stripped, force null like this: '(null)'242 toRemove.add(entry.getKey());243 } else {244 if (sv.isString()) {245 entry.setValue(sv.getAsString());246 } else { // map, list etc247 entry.setValue(sv.getValue());248 }249 }250 }251 for (String keyToRemove : toRemove) {252 row.remove(keyToRemove);253 }254 result.add(row);255 }256 setVariable(name.trim(), result);257 }258 public void replace(String name, String token, String value) {259 name = name.trim();260 Variable v = vars.get(name);261 if (v == null) {262 throw new RuntimeException("no variable found with name: " + name);263 }264 String text = v.getAsString();265 String replaced = replacePlaceholderText(text, token, value);266 setVariable(name, replaced);267 }268 public void assertTrue(String expression) {269 if (!evalJs(expression).isTrue()) {270 String message = "did not evaluate to 'true': " + expression;271 setFailedReason(new KarateException(message));272 }273 }274 public void print(String exp) {275 if (!config.isPrintEnabled()) {276 return;277 }278 evalJs("karate.log('[print]'," + exp + ")");279 }280 public void invokeAfterHookIfConfigured(boolean afterFeature) {281 if (runtime.caller.depth > 0) {282 return;283 }284 Variable v = afterFeature ? config.getAfterFeature() : config.getAfterScenario();285 if (v.isJsOrJavaFunction()) {286 if (afterFeature) {287 ScenarioEngine.set(this); // for any bridge / js to work288 }289 try {290 executeFunction(v);291 } catch (Exception e) {292 String prefix = afterFeature ? "afterFeature" : "afterScenario";293 logger.warn("{} hook failed: {}", prefix, e + "");294 }295 }296 }297 // gatling =================================================================298 //299 private PerfEvent prevPerfEvent;300 public void logLastPerfEvent(String failureMessage) {301 if (prevPerfEvent != null && runtime.perfMode) {302 if (failureMessage != null) {303 prevPerfEvent.setFailed(true);304 prevPerfEvent.setMessage(failureMessage);305 }306 runtime.featureRuntime.perfHook.reportPerfEvent(prevPerfEvent);307 }308 prevPerfEvent = null;309 }310 public void capturePerfEvent(PerfEvent event) {311 logLastPerfEvent(null);312 prevPerfEvent = event;313 }314 // http ====================================================================315 //316 private HttpRequestBuilder requestBuilder; // see init() method317 private HttpRequest request;318 private Response response;319 private Config config;320 public Config getConfig() {321 return config;322 }323 // important: use this to trigger client re-config324 // callonce routine is one example325 public void setConfig(Config config) {326 this.config = config;327 config.attach(JS);328 if (requestBuilder != null) {329 requestBuilder.client.setConfig(config);330 }331 }332 public HttpRequest getRequest() {333 return request;334 }335 public Response getResponse() {336 return response;337 }338 public HttpRequestBuilder getRequestBuilder() {339 return requestBuilder;340 }341 public void configure(String key, String exp) {342 Variable v = evalKarateExpression(exp);343 configure(key, v);344 }345 public Driver getDriver() {346 return this.driver;347 }348 public NewDriver getCurrentChrome() {349 if (driver != null && driver instanceof Chrome) {350 Optional<NewDriver> newDriver = newDrivers.values().stream().filter(item -> item.driver == driver).findFirst();351 if (newDriver.isPresent()) {352 return newDriver.get();353 } else {354 return new NewDriver(null, null, driver);355 }356 } else {357 return null;358 }359 }360 public void configure(String key, Variable v) {361 key = StringUtils.trimToEmpty(key);362 if (key.equals("newDriver")) {363 // @FIXME override start364 Map<String, Object> map = v.getValue();365 if (map.containsKey("name")) {366 String name = (String) map.get("name");367 validateVariableName(name);368 if (newDrivers.containsKey(name) || vars.containsKey(name)) {369 throw new RuntimeException("name: " + name + " already exists.");370 } else {371 Boolean isDefault = (boolean) map.getOrDefault("default", false);372 Driver newDriver = DriverOptions.start(map, runtime);373 newDrivers.put(name, new NewDriver(name, map, newDriver));374 if (isDefault) {375 config.configure("driver", v);376 setDriver(newDriver);377 }378 setVariable(name, newDriver);379 }380 } else {381 throw new RuntimeException("there must be a name when configure a new driver.");382 }383 // override end384 } else {385 // if next line returns true, config is http-client related386 if (config.configure(key, v)) {387 if (requestBuilder != null) {388 requestBuilder.client.setConfig(config);389 }390 }391 }392 }393 private void evalAsMap(String exp, BiConsumer<String, List<String>> fun) {394 Variable var = evalKarateExpression(exp);395 if (!var.isMap()) {396 logger.warn("did not evaluate to map {}: {}", exp, var);397 return;398 }399 Map<String, Object> map = var.getValue();400 map.forEach((k, v) -> {401 if (v instanceof List) {402 List list = (List) v;403 List<String> values = new ArrayList(list.size());404 for (Object o : list) { // support non-string values, e.g. numbers405 if (o != null) {406 values.add(o.toString());407 }408 }409 fun.accept(k, values);410 } else if (v != null) {411 fun.accept(k, Collections.singletonList(v.toString()));412 }413 });414 }415 public void url(String exp) {416 Variable var = evalKarateExpression(exp);417 requestBuilder.url(var.getAsString());418 }419 public void path(String exp) {420 List list = evalJs("[" + exp + "]").getValue();421 for (Object o : list) {422 if (o != null) {423 requestBuilder.path(o.toString());424 }425 }426 }427 // TODO document that for params and headers, lists are supported but428 // enclosed in square brackets429 public void param(String name, String exp) {430 Variable var = evalJs(exp);431 if (var.isList()) {432 requestBuilder.param(name, var.<List> getValue());433 } else {434 requestBuilder.param(name, var.getAsString());435 }436 }437 public void params(String expr) {438 evalAsMap(expr, (k, v) -> requestBuilder.param(k, v));439 }440 public void header(String name, String exp) {441 Variable var = evalKarateExpression(exp);442 if (var.isList()) {443 requestBuilder.header(name, var.<List> getValue());444 } else {445 requestBuilder.header(name, var.getAsString());446 }447 }448 public void headers(String expr) {449 evalAsMap(expr, (k, v) -> requestBuilder.header(k, v));450 }451 public void cookie(String name, String exp) {452 Variable var = evalKarateExpression(exp);453 if (var.isString()) {454 requestBuilder.cookie(name, var.getAsString());455 } else if (var.isMap()) {456 Map<String, Object> map = var.getValue();457 map.put("name", name);458 requestBuilder.cookie(map);459 }460 }461 // TODO document new options, [name = map | cookies listOfMaps]462 public void cookies(String exp) {463 Variable var = evalKarateExpression(exp);464 Map<String, Map> cookies = Cookies.normalize(var.getValue());465 requestBuilder.cookies(cookies.values());466 }467 private void updateConfigCookies(Map<String, Map> cookies) {468 if (cookies == null) {469 return;470 }471 if (config.getCookies().isNull()) {472 config.setCookies(new Variable(cookies));473 } else {474 Map<String, Map> map = getOrEvalAsMap(config.getCookies());475 map.putAll(cookies);476 config.setCookies(new Variable(map));477 }478 }479 public void formField(String name, String exp) {480 Variable var = evalKarateExpression(exp);481 if (var.isList()) {482 requestBuilder.formField(name, var.<List> getValue());483 } else {484 requestBuilder.formField(name, var.getAsString());485 }486 }487 public void formFields(String exp) {488 Variable var = evalKarateExpression(exp);489 if (var.isMap()) {490 Map<String, Object> map = var.getValue();491 map.forEach((k, v) -> {492 requestBuilder.formField(k, v);493 });494 } else {495 logger.warn("did not evaluate to map {}: {}", exp, var);496 }497 }498 public void multipartField(String name, String value) {499 multipartFile(name, value);500 }501 public void multipartFields(String exp) {502 multipartFiles(exp);503 }504 private void multiPartInternal(String name, Object value) {505 Map<String, Object> map = new HashMap();506 if (name != null) {507 map.put("name", name);508 }509 if (value instanceof Map) {510 map.putAll((Map) value);511 String toRead = (String) map.get("read");512 if (toRead != null) {513 File file = fileReader.relativePathToFile(toRead);514 map.put("value", file);515 }516 requestBuilder.multiPart(map);517 } else if (value instanceof String) {518 map.put("value", (String) value);519 multiPartInternal(name, map);520 } else if (value instanceof List) {521 List list = (List) value;522 for (Object o : list) {523 multiPartInternal(null, o);524 }525 } else if (logger.isTraceEnabled()) {526 logger.trace("did not evaluate to string, map or list {}: {}", name, value);527 }528 }529 public void multipartFile(String name, String exp) {530 Variable var = evalKarateExpression(exp);531 multiPartInternal(name, var.getValue());532 }533 public void multipartFiles(String exp) {534 Variable var = evalKarateExpression(exp);535 if (var.isMap()) {536 Map<String, Object> map = var.getValue();537 map.forEach((k, v) -> multiPartInternal(k, v));538 } else if (var.isList()) {539 List<Map> list = var.getValue();540 for (Map map : list) {541 multiPartInternal(null, map);542 }543 } else {544 logger.warn("did not evaluate to map or list {}: {}", exp, var);545 }546 }547 public void request(String body) {548 Variable v = evalKarateExpression(body);549 requestBuilder.body(v.getValue());550 }551 public void soapAction(String exp) {552 String action = evalKarateExpression(exp).getAsString();553 if (action == null) {554 action = "";555 }556 requestBuilder.header("SOAPAction", action);557 requestBuilder.contentType("text/xml");558 method("POST");559 }560 public void retry(String condition) {561 requestBuilder.setRetryUntil(condition);562 }563 public void method(String method) {564 if (!HttpConstants.HTTP_METHODS.contains(method.toUpperCase())) { // support expressions also565 method = evalKarateExpression(method).getAsString();566 }567 requestBuilder.method(method);568 httpInvoke();569 }570 // extracted for mock proceed()571 public Response httpInvoke() {572 if (requestBuilder.isRetry()) {573 httpInvokeWithRetries();574 } else {575 httpInvokeOnce();576 }577 requestBuilder.reset();578 return response;579 }580 private void httpInvokeOnce() {581 Map<String, Map> cookies = getOrEvalAsMap(config.getCookies());582 if (cookies != null) {583 requestBuilder.cookies(cookies.values());584 }585 Map<String, Object> headers;586 if (config.getHeaders().isJsOrJavaFunction()) {587 headers = getOrEvalAsMap(config.getHeaders(), requestBuilder.build());588 } else {589 headers = getOrEvalAsMap(config.getHeaders()); // avoid an extra http request build590 }591 if (headers != null) {592 requestBuilder.headers(headers);593 }594 request = requestBuilder.build();595 String perfEventName = null; // acts as a flag to report perf if not null596 if (runtime.perfMode) {597 perfEventName = runtime.featureRuntime.perfHook.getPerfEventName(request, runtime);598 }599 long startTime = System.currentTimeMillis();600 request.setStartTimeMillis(startTime); // this may be fine-adjusted by actual http client601 if (hooks != null) {602 hooks.forEach(h -> h.beforeHttpCall(request, runtime));603 }604 try {605 response = requestBuilder.client.invoke(request);606 } catch (Exception e) {607 long endTime = System.currentTimeMillis();608 long responseTime = endTime - startTime;609 String message = "http call failed after " + responseTime + " milliseconds for url: " + request.getUrl();610 logger.error(e.getMessage() + ", " + message);611 if (perfEventName != null) {612 PerfEvent pe = new PerfEvent(startTime, endTime, perfEventName, 0);613 capturePerfEvent(pe); // failure flag and message should be set by logLastPerfEvent()614 }615 throw new KarateException(message, e);616 }617 if (hooks != null) {618 hooks.forEach(h -> h.afterHttpCall(request, response, runtime));619 }620 byte[] bytes = response.getBody();621 Object body;622 String responseType;623 ResourceType resourceType = response.getResourceType();624 if (resourceType != null && resourceType.isBinary()) {625 responseType = "binary";626 body = bytes;627 } else {628 try {629 body = JsValue.fromBytes(bytes, true, resourceType);630 } catch (Exception e) {631 body = FileUtils.toString(bytes);632 logger.warn("auto-conversion of response failed: {}", e.getMessage());633 }634 if (body instanceof Map || body instanceof List) {635 responseType = "json";636 } else if (body instanceof Node) {637 responseType = "xml";638 } else {639 responseType = "string";640 }641 }642 setVariable(RESPONSE_STATUS, response.getStatus());643 setVariable(RESPONSE, body);644 if (config.isLowerCaseResponseHeaders()) {645 setVariable(RESPONSE_HEADERS, response.getHeadersWithLowerCaseNames());646 } else {647 setVariable(RESPONSE_HEADERS, response.getHeaders());648 }649 setHiddenVariable(RESPONSE_BYTES, bytes);650 setHiddenVariable(RESPONSE_TYPE, responseType);651 cookies = response.getCookies();652 updateConfigCookies(cookies);653 setHiddenVariable(RESPONSE_COOKIES, cookies);654 startTime = request.getStartTimeMillis(); // in case it was re-adjusted by http client655 long endTime = request.getEndTimeMillis();656 setHiddenVariable(REQUEST_TIME_STAMP, startTime);657 setHiddenVariable(RESPONSE_TIME, endTime - startTime);658 if (perfEventName != null) {659 PerfEvent pe = new PerfEvent(startTime, endTime, perfEventName, response.getStatus());660 capturePerfEvent(pe);661 }662 }663 private void httpInvokeWithRetries() {664 int maxRetries = config.getRetryCount();665 int sleep = config.getRetryInterval();666 int retryCount = 0;667 while (true) {668 if (retryCount == maxRetries) {669 throw new KarateException("too many retry attempts: " + maxRetries);670 }671 if (retryCount > 0) {672 try {673 logger.debug("sleeping before retry #{}", retryCount);674 Thread.sleep(sleep);675 } catch (Exception e) {676 throw new RuntimeException(e);677 }678 }679 httpInvokeOnce();680 Variable v;681 try {682 v = evalKarateExpression(requestBuilder.getRetryUntil());683 } catch (Exception e) {684 logger.warn("retry condition evaluation failed: {}", e.getMessage());685 v = Variable.NULL;686 }687 if (v.isTrue()) {688 if (retryCount > 0) {689 logger.debug("retry condition satisfied");690 }691 break;692 } else {693 logger.debug("retry condition not satisfied: {}", requestBuilder.getRetryUntil());694 }695 retryCount++;696 }697 }698 public void status(int status) {699 if (status != response.getStatus()) {700 // make sure log masking is applied701 String message = HttpLogger.getStatusFailureMessage(status, config, request, response);702 setFailedReason(new KarateException(message));703 }704 }705 public KeyStore getKeyStore(String trustStoreFile, String password, String type) {706 if (trustStoreFile == null) {707 return null;708 }709 char[] passwordChars = password == null ? null : password.toCharArray();710 if (type == null) {711 type = KeyStore.getDefaultType();712 }713 try {714 KeyStore keyStore = KeyStore.getInstance(type);715 InputStream is = fileReader.readFileAsStream(trustStoreFile);716 keyStore.load(is, passwordChars);717 logger.debug("key store key count for {}: {}", trustStoreFile, keyStore.size());718 return keyStore;719 } catch (Exception e) {720 logger.error("key store init failed: {}", e.getMessage());721 throw new RuntimeException(e);722 }723 }724 // http mock ===============================================================725 //726 public void mockProceed(String requestUrlBase) {727 String urlBase = requestUrlBase == null ? vars.get(REQUEST_URL_BASE).getValue() : requestUrlBase;728 String uri = vars.get(REQUEST_URI).getValue();729 String url = uri == null ? urlBase : urlBase + "/" + uri;730 requestBuilder.url(url);731 requestBuilder.params(vars.get(REQUEST_PARAMS).getValue());732 requestBuilder.method(vars.get(REQUEST_METHOD).getValue());733 requestBuilder.headers(vars.get(REQUEST_HEADERS).<Map> getValue());734 requestBuilder.removeHeader(HttpConstants.HDR_CONTENT_LENGTH);735 requestBuilder.body(vars.get(REQUEST).getValue());736 if (requestBuilder.client instanceof ArmeriaHttpClient) {737 Request mockRequest = MockHandler.LOCAL_REQUEST.get();738 if (mockRequest != null) {739 ArmeriaHttpClient client = (ArmeriaHttpClient) requestBuilder.client;740 client.setRequestContext(mockRequest.getRequestContext());741 }742 }743 httpInvoke();744 }745 public Map<String, Object> mockConfigureHeaders() {746 return getOrEvalAsMap(config.getResponseHeaders());747 }748 public void mockAfterScenario() {749 if (config.getAfterScenario().isJsOrJavaFunction()) {750 executeFunction(config.getAfterScenario());751 }752 }753 // websocket / async =======================================================754 //755 private List<WebSocketClient> webSocketClients;756 CompletableFuture SIGNAL = new CompletableFuture();757 public WebSocketClient webSocket(WebSocketOptions options) {758 WebSocketClient webSocketClient = new WebSocketClient(options, logger);759 if (webSocketClients == null) {760 webSocketClients = new ArrayList();761 }762 webSocketClients.add(webSocketClient);763 return webSocketClient;764 }765 public void signal(Object result) {766 logger.debug("signal called: {}", result);767 if (parent != null) {768 parent.signal(result);769 } else {770 synchronized (JS.context) {771 SIGNAL.complete(result);772 }773 }774 }775 public Object listen(String exp) {776 Variable v = evalKarateExpression(exp);777 int timeout = v.getAsInt();778 logger.debug("entered listen state with timeout: {}", timeout);779 Object listenResult = null;780 try {781 listenResult = SIGNAL.get(timeout, TimeUnit.MILLISECONDS);782 } catch (Exception e) {783 logger.error("listen timed out: {}", e + "");784 }785 synchronized (JS.context) {786 setHiddenVariable(LISTEN_RESULT, listenResult);787 logger.debug("exit listen state with result: {}", listenResult);788 SIGNAL = new CompletableFuture();789 return listenResult;790 }791 }792 public Command fork(boolean useLineFeed, List<String> args) {793 return fork(useLineFeed, Collections.singletonMap("args", args));794 }795 public Command fork(boolean useLineFeed, String line) {796 return fork(useLineFeed, Collections.singletonMap("line", line));797 }798 public Command fork(boolean useLineFeed, Map<String, Object> options) {799 Boolean useShell = (Boolean) options.get("useShell");800 if (useShell == null) {801 useShell = false;802 }...
CompletableFuture
Using AI Code Generation
1import com.intuit.karate.core.ScenarioEngine;2import com.intuit.karate.core.ScenarioRuntime;3import java.util.concurrent.CompletableFuture;4ScenarioRuntime runtime = ScenarioEngine.execute("classpath:sample.feature");5CompletableFuture<ScenarioRuntime> future = runtime.future();6ScenarioRuntime result = future.join();7result.writeTo("target/surefire-reports");8import com.intuit.karate.core.ScenarioRuntime;9import java.util.concurrent.CompletableFuture;10ScenarioRuntime runtime = ScenarioRuntime.of("classpath:sample.feature");11CompletableFuture<ScenarioRuntime> future = runtime.future();12ScenarioRuntime result = future.join();13result.writeTo("target/surefire-reports");14import com.intuit.karate.core.Scenario;15import java.util.concurrent.CompletableFuture;16Scenario scenario = Scenario.of("classpath:sample.feature");17CompletableFuture<Scenario> future = scenario.future();18Scenario result = future.join();19result.writeTo("target/surefire-reports");20import com.intuit.karate.core.Feature;21import java.util.concurrent.CompletableFuture;22Feature feature = Feature.of("classpath:sample.feature");23CompletableFuture<Feature> future = feature.future();24Feature result = future.join();25result.writeTo("target/surefire-reports");26import com.intuit.karate.core.FeatureRuntime;27import java.util.concurrent.CompletableFuture;28FeatureRuntime runtime = FeatureRuntime.of("classpath:sample.feature");29CompletableFuture<FeatureRuntime> future = runtime.future();30FeatureRuntime result = future.join();31result.writeTo("target/surefire-reports");32import com.intuit.karate.core.FeatureEngine;33import com.intuit.karate.core.FeatureRuntime;34import java.util.concurrent.CompletableFuture;35FeatureRuntime runtime = FeatureEngine.execute("classpath:sample.feature");36CompletableFuture<FeatureRuntime> future = runtime.future();37FeatureRuntime result = future.join();38result.writeTo("target/surefire-reports");39import com.intuit.karate.core
CompletableFuture
Using AI Code Generation
1def response = engine.run('features/feature1.feature', [name: 'John', age: 99])2def response = engine.run('features/feature1.feature', [name: 'John', age: 99], [timeout: 30000])3def response = engine.run('features/feature1.feature', [name: 'John', age: 99], [timeout: 30000, tags: '@smoke'])4def response = engine.run('features/feature1.feature', [name: 'John', age: 99], [timeout: 30000, tags: '@smoke', failFast: true])5def response = engine.run('features/feature1.feature', [name: 'John', age: 99], [timeout: 30000, tags: '@smoke', failFast: true, reportDir: 'target'])6def response = engine.run('features/feature1.feature', [name: 'John', age: 99], [timeout: 30000, tags: '@smoke', failFast: true, reportDir: 'target', reportName: 'myreport'])7def response = engine.run('features/feature1.feature', [name: 'John', age: 99], [timeout: 30000, tags: '@smoke', failFast: true, reportDir: 'target', reportName: 'myreport', reportTitle: 'My Report Title'])8def response = engine.run('features/feature1.feature', [name: 'John', age: 99], [timeout: 30000, tags: '@smoke', failFast: true, reportDir: 'target', reportName: 'myreport', reportTitle: 'My Report Title', reportTags: 'mytag1,mytag
CompletableFuture
Using AI Code Generation
1 * def engine = karate.getScenarioEngine()2 * def users = read('classpath:users.json')3 * def request = read('classpath:request.json')4 * def future = engine.run('classpath:com/intuit/karate/demo/reqres/create-user.feature', env, url, users[0])5 * def response = future.get()6 * def future = engine.run('classpath:com/intuit/karate/demo/reqres/get-user.feature', env, url, 2)7 * def response = future.get()8 * def future = engine.run('classpath:com/intuit/karate/demo/reqres/update-user.feature', env, url, 2, users[2])9 * def response = future.get()10 * def future = engine.run('classpath:com/intuit/karate/demo/reqres/delete-user.feature', env, url, 2)11 * def response = future.get()12 * def future = engine.run('classpath:com/intuit/karate/demo/reqres/get-user.feature', env, url, 2)13 * def response = future.get()14 * match response == {}15 * def users = read('classpath:users.json')16 * def request = read('classpath:request.json')17 * for (var i = 0; i < users.length; i++) { futures[i] = engine.run('classpath:com/intuit/karate/demo/reqres/create-user.feature', env, url, users[i]) }18 * def responses = futures.stream().map(f -> f.get()).toArray()19 * for (var i = 0; i < 3; i++) { futures[i] = engine.run('classpath:com
CompletableFuture
Using AI Code Generation
1def engine = karate.getScenarioEngine()2def results = engine.runParallel(2, [3results.forEach { result ->4}5def engine = karate.getScenarioEngine()6def results = engine.runParallel(4, [7results.forEach { result ->8}9def engine = karate.getScenarioEngine()10def results = engine.runParallel(2, [11results.forEach { result ->12}13def engine = karate.getScenarioEngine()14def results = engine.runParallel(2, [15results.forEach { result ->16}17def engine = karate.getScenarioEngine()18def results = engine.runParallel(2, [19results.forEach { result ->20}21def engine = karate.getScenarioEngine()22def results = engine.runParallel(2, [
CompletableFuture
Using AI Code Generation
1* def result = karate.callSingleAsync('classpath:features/endpoint.feature', { 2 request = { url: path }3 response = { response -> response }4 })5* def result = karate.callSingleAsync('classpath:features/endpoint.feature', { 6 request = { url: path }7 response = { response -> response }8 })9* def result = karate.callSingleAsync('classpath:features/endpoint.feature', { 10 request = { url: path }11 response = { response -> response }12 })13* result.thenApply(r -> r
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!!