How to use getOrEvalAsMap method of com.intuit.karate.core.ScenarioEngine class

Best Karate code snippet using com.intuit.karate.core.ScenarioEngine.getOrEvalAsMap

Source:ScenarioEngine.java Github

copy

Full Screen

...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 }803 List<String> list = (List) options.get("args");804 String[] args;805 if (list == null) {806 String line = (String) options.get("line");807 if (line == null) {808 throw new RuntimeException("'line' or 'args' is required");809 }810 args = Command.tokenize(line);811 } else {812 args = list.toArray(new String[list.size()]);813 }814 if (useShell) {815 args = Command.prefixShellArgs(args);816 }817 String workingDir = (String) options.get("workingDir");818 File workingFile = workingDir == null ? null : new File(workingDir);819 Command command = new Command(useLineFeed, logger, null, null, workingFile, args);820 Map env = (Map) options.get("env");821 if (env != null) {822 command.setEnvironment(env);823 }824 Boolean redirectErrorStream = (Boolean) options.get("redirectErrorStream");825 if (redirectErrorStream != null) {826 command.setRedirectErrorStream(redirectErrorStream);827 }828 Value funOut = (Value) options.get("listener");829 if (funOut != null && funOut.canExecute()) {830 ScenarioListener sl = new ScenarioListener(this, funOut);831 command.setListener(sl);832 }833 Value funErr = (Value) options.get("errorListener");834 if (funErr != null && funErr.canExecute()) {835 ScenarioListener sl = new ScenarioListener(this, funErr);836 command.setErrorListener(sl);837 }838 Boolean start = (Boolean) options.get("start");839 if (start == null) {840 start = true;841 }842 if (start) {843 command.start();844 }845 return command;846 }847 // ui driver / robot =======================================================848 //849 protected Driver driver;850 protected Plugin robot;851 private void autoDef(Plugin plugin, String instanceName) {852 for (String methodName : plugin.methodNames()) {853 String invoke = instanceName + "." + methodName;854 StringBuilder sb = new StringBuilder();855 sb.append("(function(){ if (arguments.length == 0) return ").append(invoke).append("();")856 .append(" if (arguments.length == 1) return ").append(invoke).append("(arguments[0]);")857 .append(" if (arguments.length == 2) return ").append(invoke).append("(arguments[0], arguments[1]);")858 .append(" if (arguments.length == 3) return ")859 .append(invoke).append("(arguments[0], arguments[1], arguments[2]);")860 .append(" if (arguments.length == 4) return ")861 .append(invoke).append("(arguments[0], arguments[1], arguments[2], arguments[3]);")862 .append(" if (arguments.length == 5) return ")863 .append(invoke).append("(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4]);")864 .append(" if (arguments.length == 6) return ")865 .append(invoke).append("(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]);")866 .append(" if (arguments.length == 7) return ")867 .append(invoke)868 .append("(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6]);")869 .append(" return ").append(invoke).append(870 "(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6], "871 + "arguments[7]) })");872 setHiddenVariable(methodName, evalJs(sb.toString()));873 }874 }875 public void driver(String exp) {876 Variable v = evalKarateExpression(exp);877 // re-create driver within a test if needed878 // but user is expected to call quit() OR use the driver keyword with a JSON argument879 if (driver == null || driver.isTerminated() || v.isMap()) {880 Map<String, Object> options = config.getDriverOptions();881 if (options == null) {882 options = new HashMap();883 }884 options.put("target", config.getDriverTarget());885 if (v.isMap()) {886 options.putAll(v.getValue());887 }888 setDriver(DriverOptions.start(options, runtime));889 }890 if (v.isString()) {891 driver.setUrl(v.getAsString());892 }893 }894 public void robot(String exp) {895 Variable v = evalKarateExpression(exp);896 if (robot == null) {897 Map<String, Object> options = config.getRobotOptions();898 if (options == null) {899 options = new HashMap();900 }901 if (v.isMap()) {902 options.putAll(v.getValue());903 } else if (v.isString()) {904 options.put("window", v.getAsString());905 }906 try {907 Class clazz = Class.forName("com.intuit.karate.robot.RobotFactory");908 PluginFactory factory = (PluginFactory) clazz.newInstance();909 robot = factory.create(runtime, options);910 } catch (KarateException ke) {911 throw ke;912 } catch (Exception e) {913 String message =914 "cannot instantiate robot, is 'karate-robot' included as a maven / gradle dependency ? " + e.getMessage();915 logger.error(message);916 throw new RuntimeException(message, e);917 }918 setRobot(robot);919 }920 }921 public void setDriver(Driver driver) {922 this.driver = driver;923 setHiddenVariable(DRIVER, driver);924 if (robot != null) {925 logger.warn("'robot' is active, use 'driver.' prefix for driver methods");926 return;927 }928 autoDef(driver, DRIVER);929 setHiddenVariable(KEY, Key.INSTANCE);930 Ocr ocr = new Ocr(driver);931 setHiddenVariable(Ocr.ENGINE_KEY(), ocr);932 Img img = new Img(driver, ocr);933 setHiddenVariable(Img.ENGINE_KEY(), img);934 asura.ui.karate.plugins.System sys = new asura.ui.karate.plugins.System(driver, ocr, img, true);935 setHiddenVariable(sys.ENGINE_KEY(), sys);936 }937 public void setRobot(Plugin robot) { // TODO unify938 this.robot = robot;939 // robot.setContext(this);940 setHiddenVariable(ROBOT, robot);941 if (driver != null) {942 logger.warn("'driver' is active, use 'robot.' prefix for robot methods");943 return;944 }945 autoDef(robot, ROBOT);946 setHiddenVariable(KEY, Key.INSTANCE);947 }948 public void stop(StepResult lastStepResult) {949 if (runtime.caller.isSharedScope()) {950 // TODO life-cycle this hand off951 ScenarioEngine caller = runtime.caller.parentRuntime.engine;952 if (driver != null) { // a called feature inited the driver953 caller.setDriver(driver);954 }955 if (robot != null) {956 caller.setRobot(robot);957 }958 caller.webSocketClients = webSocketClients;959 // return, don't kill driver just yet960 } else if (runtime.caller.depth == 0) { // end of top-level scenario (no caller)961 if (webSocketClients != null) {962 webSocketClients.forEach(WebSocketClient::close);963 }964 if (driver != null) { // TODO move this to Plugin.afterScenario()965 DriverOptions options = driver.getOptions();966 if (options.stop) {967 driver.quit();968 }969 if (options.target != null) {970 logger.debug("custom target configured, attempting stop()");971 Map<String, Object> map = options.target.stop(runtime);972 String video = (String) map.get("video");973 embedVideo(video);974 } else {975 if (options.afterStop != null) {976 Command.execLine(null, options.afterStop);977 }978 embedVideo(options.videoFile);979 }980 }981 // @FIXME override start982 if (!newDrivers.isEmpty()) {983 newDrivers.values().forEach(newDriver -> {984 if (newDriver.isStop()) {985 newDriver.stopDriver();986 }987 });988 }989 // override end990 if (robot != null) {991 robot.afterScenario();992 }993 }994 }995 private void embedVideo(String path) {996 if (path != null) {997 File videoFile = new File(path);998 if (videoFile.exists()) {999 Embed embed = runtime.embedVideo(videoFile);1000 logger.debug("appended video to report: {}", embed);1001 }1002 }1003 }1004 // doc =====================================================================1005 //1006 private KarateTemplateEngine templateEngine;1007 public void doc(String exp) {1008 if (runtime.reportDisabled) {1009 return;1010 }1011 String path;1012 Variable v = evalKarateExpression(exp);1013 if (v.isString()) {1014 path = v.getAsString();1015 } else if (v.isMap()) {1016 Map<String, Object> map = v.getValue();1017 path = (String) map.get("read");1018 if (path == null) {1019 logger.warn("doc json missing 'read' property: {}", v);1020 return;1021 }1022 } else {1023 logger.warn("doc is not string or json: {}", v);1024 return;1025 }1026 if (templateEngine == null) {1027 String prefixedPath = runtime.featureRuntime.rootFeature.feature.getResource().getPrefixedParentPath();1028 templateEngine = TemplateUtils.forResourcePath(JS, prefixedPath);1029 }1030 String html = templateEngine.process(path);1031 runtime.embed(FileUtils.toBytes(html), ResourceType.HTML);1032 }1033 //==========================================================================1034 //1035 public void init() { // not in constructor because it has to be on Runnable.run() thread1036 JS = JsEngine.local();1037 logger.trace("js context: {}", JS);1038 runtime.magicVariables.forEach((k, v) -> setHiddenVariable(k, v));1039 attachVariables(); // re-hydrate any functions from caller or background1040 setHiddenVariable(KARATE, bridge);1041 setHiddenVariable(READ, readFunction);1042 HttpClient client = runtime.featureRuntime.suite.clientFactory.create(this);1043 requestBuilder = new HttpRequestBuilder(client);1044 // TODO improve life cycle and concept of shared objects1045 if (!runtime.caller.isNone()) {1046 ScenarioEngine caller = runtime.caller.parentRuntime.engine;1047 if (caller.driver != null) {1048 setDriver(caller.driver);1049 }1050 if (caller.robot != null) {1051 setRobot(caller.robot);1052 }1053 }1054 }1055 private void attachVariables() {1056 vars.forEach((k, v) -> {1057 switch (v.type) {1058 case JS_FUNCTION:1059 Value value = attach(v.getValue());1060 v = new Variable(value);1061 vars.put(k, v);1062 break;1063 case MAP:1064 case LIST:1065 recurseAndAttach(v.getValue());1066 break;1067 case OTHER:1068 if (v.isJsFunctionWrapper()) {1069 JsFunction jf = v.getValue();1070 Value attached = attachSource(jf.source);1071 v = new Variable(attached);1072 vars.put(k, v);1073 }1074 break;1075 default:1076 // do nothing1077 }1078 JS.put(k, v.getValue());1079 });1080 }1081 public Map<String, Variable> detachVariables() {1082 Map<String, Variable> detached = new HashMap(vars.size());1083 vars.forEach((k, v) -> {1084 switch (v.type) {1085 case JS_FUNCTION:1086 JsFunction jf = new JsFunction(v.getValue());1087 v = new Variable(jf);1088 break;1089 case MAP:1090 case LIST:1091 recurseAndDetach(v.getValue());1092 break;1093 default:1094 // do nothing1095 }1096 detached.put(k, v);1097 });1098 return detached;1099 }1100 protected Object recurseAndAttach(Object o) {1101 if (o instanceof Value) {1102 Value value = (Value) o;1103 return value.canExecute() ? attach(value) : null;1104 } else if (o instanceof JsFunction) {1105 JsFunction jf = (JsFunction) o;1106 return attachSource(jf.source);1107 } else if (o instanceof List) {1108 List list = (List) o;1109 int count = list.size();1110 for (int i = 0; i < count; i++) {1111 Object child = list.get(i);1112 Object result = recurseAndAttach(child);1113 if (result != null) {1114 list.set(i, result);1115 }1116 }1117 return null;1118 } else if (o instanceof Map) {1119 Map<String, Object> map = (Map) o;1120 map.forEach((k, v) -> {1121 Object result = recurseAndAttach(v);1122 if (result != null) {1123 map.put(k, result);1124 }1125 });1126 return null;1127 } else {1128 return null;1129 }1130 }1131 protected Object recurseAndDetach(Object o) {1132 if (o instanceof Value) {1133 Value value = (Value) o;1134 return value.canExecute() ? new JsFunction(value) : null;1135 } else if (o instanceof List) {1136 List list = (List) o;1137 int count = list.size();1138 for (int i = 0; i < count; i++) {1139 Object child = list.get(i);1140 Object result = recurseAndDetach(child);1141 if (result != null) {1142 list.set(i, result);1143 }1144 }1145 return null;1146 } else if (o instanceof Map) {1147 Map<String, Object> map = (Map) o;1148 map.forEach((k, v) -> {1149 Object result = recurseAndDetach(v);1150 if (result != null) {1151 map.put(k, result);1152 }1153 });1154 return null;1155 } else {1156 return null;1157 }1158 }1159 public Value attachSource(CharSequence source) {1160 return JS.attachSource(source);1161 }1162 public Value attach(Value before) {1163 return JS.attach(before);1164 }1165 protected <T> Map<String, T> getOrEvalAsMap(Variable var, Object... args) {1166 if (var.isJsOrJavaFunction()) {1167 Variable res = executeFunction(var, args);1168 return res.isMap() ? res.getValue() : null;1169 } else {1170 return var.isMap() ? var.getValue() : null;1171 }1172 }1173 public Variable executeFunction(Variable var, Object... args) {1174 switch (var.type) {1175 case JS_FUNCTION:1176 Value jsFunction = var.getValue();1177 JsValue jsResult = executeJsValue(jsFunction, args);1178 return new Variable(jsResult);1179 case JAVA_FUNCTION: // definitely a "call" with a single argument...

Full Screen

Full Screen

Source:ScenarioRuntime.java Github

copy

Full Screen

...282 if (!fun.isJsFunction()) {283 logger.warn("not a valid js function: {}", displayName);284 return;285 }286 Map<String, Object> map = engine.getOrEvalAsMap(fun);287 engine.setVariables(map);288 } catch (Exception e) {289 String message = ">> " + scenario.getDebugInfo() + "\n>> " + displayName + " failed\n>> " + e.getMessage();290 error = JsEngine.fromJsEvalException(js, e, message);291 stopped = true;292 configFailed = true;293 }294 }295 private static boolean isSelectedForExecution(FeatureRuntime fr, Scenario scenario, Tags tags) {296 Feature feature = scenario.getFeature();297 int callLine = feature.getCallLine();298 if (callLine != -1) {299 int sectionLine = scenario.getSection().getLine();300 int scenarioLine = scenario.getLine();...

Full Screen

Full Screen

getOrEvalAsMap

Using AI Code Generation

copy

Full Screen

1package demo;2import com.intuit.karate.core.Feature;3import com.intuit.karate.core.FeatureRuntime;4import com.intuit.karate.core.Scenario;5import com.intuit.karate.core.ScenarioEngine;6import com.intuit.karate.core.ScenarioRuntime;7import com.intuit.karate.core.Variable;8import com.intuit.karate.core.VariableScope;9import java.util.Map;10public class Demo {11 public static void main(String[] args) {12 ScenarioEngine engine = new ScenarioEngine();13 Feature feature = Feature.read("classpath:demo.feature");14 FeatureRuntime fr = engine.createFeatureRuntime(feature);15 Scenario scenario = fr.getScenario("demo");16 ScenarioRuntime sr = fr.createScenarioRuntime(scenario);17 VariableScope scope = sr.getScope();18 Variable var = scope.getVariable("a");19 Map<String, Object> result = var.getOrEvalAsMap(sr);20 System.out.println(result);21 }22}23 Given def a = { foo: '#(1 + 2)', bar: '#(3 + 4)' }24{foo=3, bar=7}25package com.intuit.karate.core;26import com.intuit.karate.FileUtils;27import com.intuit.karate.ScriptValue;28import java.io.File;29import java.util.Map;30public class ScenarioEngine {31 public Map<String, Object> getOrEvalAsMap(String featurePath, String scenarioName) {32 Feature feature = Feature.read(FileUtils.getFileRelativeTo(featurePath, getClass()));33 FeatureRuntime fr = createFeatureRuntime(feature);34 Scenario scenario = fr.getScenario(scenarioName);35 ScenarioRuntime sr = fr.createScenarioRuntime(scenario);36 VariableScope scope = sr.getScope();37 Variable var = scope.getVariable("a");38 Map<String, Object> result = var.getOrEvalAsMap(sr);39 return result;40 }41}

Full Screen

Full Screen

getOrEvalAsMap

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.core.ScenarioEngine;2import com.intuit.karate.core.ScenarioRuntime;3import com.intuit.karate.core.ScenarioContext;4import com.intuit.karate.core.Scenario;5import com.intuit.karate.core.Feature;6import com.intuit.karate.core.FeatureRuntime;7import com.intuit.karate.core.FeatureContext;8import com.intuit.karate.core.FeatureResult;9import com.intuit.karate.core.FeatureRuntimeOptions;10import com.intuit.karate.core.FeatureRuntimeOptionsBuilder;11import com.intuit.karate.core.FeatureResult;12import com.intuit.karate.core.ScenarioResult;13import com.intuit.karate.core.ScenarioRuntimeOptions;14import com.intuit.karate.core.ScenarioRuntimeOptionsBuilder;15import com.intuit.karate.core.ScenarioResult;16import com.intuit.karate.core.ScenarioRuntime;17import com.intuit.karate.core.ScenarioContext;18import com.intuit.karate.core.Scenario;19import com.intuit.karate.core.Feature;20import com.intuit.karate.core.FeatureRuntime;21import com.intuit.karate.core.FeatureContext;22import com.intuit.karate.core.FeatureResult;23import com.intuit.karate.core.FeatureRuntimeOptions;24import com.intuit.karate.core.FeatureRuntimeOptionsBuilder;25import com.intuit.karate.core.FeatureResult;26import com.intuit.karate.core.ScenarioResult;27import com.intuit.karate.core.ScenarioRuntimeOptions;28import com.intuit.karate.core.ScenarioRuntimeOptionsBuilder;29import com.intuit.karate.core.ScenarioResult;30import com.intuit.karate.core.ScenarioRuntime;31import com.intuit.karate.core.ScenarioContext;32import com.intuit.karate.core.Scenario;33import com.intuit.karate.core.Feature;34import com.intuit.karate.core.FeatureRuntime;35import com.intuit.karate.core.FeatureContext;36import com.intuit.karate.core.FeatureResult;37import com.intuit.karate.core.FeatureRuntimeOptions;38import com.intuit.karate.core.FeatureRuntimeOptionsBuilder;39import com.intuit.karate.core.FeatureResult;40import com.intuit.karate.core.ScenarioResult;41import com.intuit.karate.core.ScenarioRuntimeOptions;42import com.intuit.karate.core.ScenarioRuntimeOptionsBuilder;43import com.int

Full Screen

Full Screen

getOrEvalAsMap

Using AI Code Generation

copy

Full Screen

1package demo;2import com.intuit.karate.core.ScenarioEngine;3import com.intuit.karate.core.ScenarioResult;4import com.intuit.karate.core.ScenarioRuntime;5import java.util.Map;6import org.slf4j.Logger;7import org.slf4j.LoggerFactory;8public class Demo {9 private static final Logger logger = LoggerFactory.getLogger(Demo.class);10 public static void main(String[] args) {11 ScenarioEngine engine = new ScenarioEngine();12 ScenarioResult result = engine.executeFeature("classpath:demo.feature", null, false);13 ScenarioRuntime runtime = result.getRuntime();14 Map<String, Object> map = runtime.getOrEvalAsMap("response");15 logger.debug("{}", map);16 }17}18 * configure headers = { 'Content-Type': 'application/json', 'Accept': 'application/json' }19 * def response = read('classpath:response.json')20{21}222018-09-11 14:31:20,035 [main] DEBUG demo.Demo - {id=1, name=Test}

Full Screen

Full Screen

getOrEvalAsMap

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.core.ScenarioEngine;2import com.intuit.karate.core.ScenarioContext;3import com.intuit.karate.core.ScenarioRuntime;4import java.util.Map;5import java.util.HashMap;6import com.intuit.karate.core.Scenario;7public class 4 {8public static void main(String[] args) {9ScenarioEngine engine = new ScenarioEngine();10ScenarioContext context = new ScenarioContext();11ScenarioRuntime runtime = new ScenarioRuntime(context);12Scenario scenario = new Scenario();13scenario.setEngine(engine);14scenario.setRuntime(runtime);15scenario.setContext(context);16Map<String, Object> map = new HashMap<String, Object>();17map.put("someVar", "someValue");18scenario.setVariables(map);19Map<String, Object> map1 = (Map<String, Object>) scenario.getOrEvalAsMap("someVar");20System.out.println(map1.get("someVar"));21}22}

Full Screen

Full Screen

getOrEvalAsMap

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.core.ScenarioEngine;2import com.intuit.karate.core.ScenarioContext;3import com.intuit.karate.core.ScenarioRuntime;4import com.intuit.karate.core.Scenario;5import com.intuit.karate.core.Feature;6import com.intuit.karate.core.FeatureRuntime;7import com.intuit.karate.core.FeatureContext;8import com.intuit.karate.core.FeatureResult;9import com.intuit.karate.core.FeatureWrapper;10import com.intuit.karate.core.FeatureRuntime;11import com.intuit.karate.core.FeatureContext;12import com.intuit.karate.core.FeatureResult;13import com.intuit.karate.core.FeatureWrapper;14import com.intuit.karate.core.FeatureRuntime;15import com.intuit.karate.core.FeatureContext;16import com.intuit.karate.core.FeatureResult;17import com.intuit.karate.core.FeatureWrapper;18import com.intuit.karate.core.FeatureRuntime;19import com.intuit.karate.core.FeatureContext;20import com.intuit.karate.core.FeatureResult;21import com.intuit.karate.core.FeatureWrapper;22import com.intuit.karate.core.FeatureRuntime;23import com.intuit.karate.core.FeatureContext;24import com.intuit.karate.core.FeatureResult;25import com.intuit.karate.core.FeatureWrapper;26import com.intuit.karate.core.FeatureRuntime;27import com.intuit.karate.core.FeatureContext;28import com.intuit.karate.core.FeatureResult;29import com.intuit.karate.core.FeatureWrapper;30import com.intuit.karate.core.FeatureRuntime;31import com.intuit.karate.core.FeatureContext;32import com.intuit.karate.core.FeatureResult;33import com.intuit.karate.core.FeatureWrapper;34import com.intuit.karate.core.FeatureRuntime;35import com.intuit.karate.core.FeatureContext;36import com.intuit.karate.core.FeatureResult;37import com.intuit.karate.core.FeatureWrapper;38import com.intuit.karate.core.FeatureRuntime;39import com.intuit.karate.core.FeatureContext;40import com.intuit.karate.core.FeatureResult;41import com.intuit.karate.core.FeatureWrapper;42import com.intuit.karate.core.FeatureRuntime;43import com.intuit.karate.core.FeatureContext;44import com.intuit.karate.core.FeatureResult;45import com

Full Screen

Full Screen

getOrEvalAsMap

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.core.ScenarioEngine;2import com.intuit.karate.core.ScenarioResult;3import java.util.Map;4public class 4 {5 public static void main(String[] args) {6 String featurePath = "classpath:4.feature";7 ScenarioResult result = ScenarioEngine.getOrEvalAsMap(featurePath, null, true);8 Map<String, Object> map = result.getResult();9 System.out.println(map);10 }11}12{response=I am fine, status=200, message=Hello}13import com.intuit.karate.core.ScenarioEngine;14import com.intuit.karate.core.ScenarioResult;15import java.util.Map;16public class 4 {17 public static void main(String[] args) {18 String featurePath = "classpath:4.feature";19 ScenarioResult result = ScenarioEngine.eval(featurePath, null, true);20 Map<String, Object> map = result.getResult();21 System.out.println(map);22 }23}24{response=I am fine, status=200, message=Hello}25import com.intuit.karate.core.ScenarioEngine;26import com.intuit.karate.core.ScenarioResult;27import java.util.Map;28public class 4 {29 public static void main(String[] args) {30 String featurePath = "classpath:4.feature";31 ScenarioResult result = ScenarioEngine.eval(featurePath, null, true);32 Map<String, Object> map = result.getResult();33 System.out.println(map);34 }35}36{response=I am fine, status=200, message=Hello}

Full Screen

Full Screen

getOrEvalAsMap

Using AI Code Generation

copy

Full Screen

1package com.intuit.karate;2import java.util.Map;3public class GetOrEvalAsMap {4 public static void main(String[] args) {5 ScenarioEngine engine = ScenarioEngine.start("classpath:4.feature");6 Map<String, Object> result = engine.getOrEvalAsMap("response");7 System.out.println(result);8 }9}10* def response = {a:1, b:2, c:3}11package com.intuit.karate;12import java.util.Map;13public class GetOrEvalAsMap {14 public static void main(String[] args) {15 ScenarioEngine engine = ScenarioEngine.start("classpath:4.feature");16 Map<String, Object> result = engine.getOrEvalAsMap("response");17 System.out.println(result);18 }19}20* def response = {a:1, b:2, c:3}21package com.intuit.karate;22import java.util.Map;23public class GetOrEvalAsMap {24 public static void main(String[] args) {25 ScenarioEngine engine = ScenarioEngine.start("classpath:4.feature");26 Map<String, Object> result = engine.getOrEvalAsMap("response");27 System.out.println(result);28 }29}30* def response = {a:1, b:2, c:3}31package com.intuit.karate;32import java.util.Map;33public class GetOrEvalAsMap {34 public static void main(String[] args

Full Screen

Full Screen

getOrEvalAsMap

Using AI Code Generation

copy

Full Screen

1package com.intuit.karate.core;2import com.intuit.karate.FileUtils;3import com.intuit.karate.KarateOptions;4import com.intuit.karate.ScriptContext;5import com.intuit.karate.ScriptValue;6import com.intuit.karate.core.Scenario;7import com.intuit.karate.core.ScenarioEngine;8import com.intuit.karate.core.ScenarioRuntime;9import com.intuit.karate.core.ScenarioUtils;10import java.io.File;11import java.util.Map;12import org.junit.Test;13import static org.junit.Assert.*;14import org.slf4j.Logger;15import org.slf4j.LoggerFactory;16public class ScenarioEngineTest {17 private static final Logger logger = LoggerFactory.getLogger(ScenarioEngineTest.class);18 public void testScenarioEngine() {19 File file = FileUtils.getFileRelativeTo(ScenarioEngineTest.class, "scenario-engine.feature");20 Scenario scenario = ScenarioUtils.parse(file);21 ScriptContext context = new ScriptContext();22 ScenarioRuntime runtime = new ScenarioRuntime(context);23 ScenarioEngine engine = new ScenarioEngine(runtime, scenario);24 ScriptValue value = engine.getOrEvalAsMap();25 Map<String, Object> map = value.getAsMap();26 assertEquals("value", map.get("key"));27 }28}29package com.intuit.karate.core;30import com.intuit.karate.FileUtils;31import com.intuit.karate.KarateOptions;32import com.intuit.karate.ScriptContext;33import com.intuit.karate.ScriptValue;34import com.intuit.karate.core.Scenario;35import com.intuit.karate.core.ScenarioEngine;36import com.intuit.karate.core.ScenarioRuntime;37import com.intuit.karate.core.ScenarioUtils;38import java.io.File;39import java.util.List;40import org.junit.Test;41import static org.junit.Assert.*;42import org.slf4j.Logger;43import org.slf4j.LoggerFactory;44public class ScenarioEngineTest {45 private static final Logger logger = LoggerFactory.getLogger(ScenarioEngineTest.class);46 public void testScenarioEngine() {47 File file = FileUtils.getFileRelativeTo(ScenarioEngineTest.class,

Full Screen

Full Screen

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

Run Karate automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in ScenarioEngine

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful