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

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

Source:ScenarioBridge.java Github

copy

Full Screen

1/*2 * The MIT License3 *4 * Copyright 2020 Intuit Inc.5 *6 * Permission is hereby granted, free of charge, to any person obtaining a copy7 * of this software and associated documentation files (the "Software"), to deal8 * in the Software without restriction, including without limitation the rights9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell10 * copies of the Software, and to permit persons to whom the Software is11 * furnished to do so, subject to the following conditions:12 *13 * The above copyright notice and this permission notice shall be included in14 * all copies or substantial portions of the Software.15 *16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN22 * THE SOFTWARE.23 */24package com.intuit.karate.core;25import com.intuit.karate.EventContext;26import com.intuit.karate.FileUtils;27import com.intuit.karate.Json;28import com.intuit.karate.JsonUtils;29import com.intuit.karate.KarateException;30import com.intuit.karate.Logger;31import com.intuit.karate.Match;32import com.intuit.karate.MatchStep;33import com.intuit.karate.PerfContext;34import com.intuit.karate.StringUtils;35import com.intuit.karate.XmlUtils;36import com.intuit.karate.graal.JsEngine;37import com.intuit.karate.graal.JsLambda;38import com.intuit.karate.graal.JsList;39import com.intuit.karate.graal.JsMap;40import com.intuit.karate.graal.JsValue;41import com.intuit.karate.http.HttpClient;42import com.intuit.karate.http.HttpRequest;43import com.intuit.karate.http.HttpRequestBuilder;44import com.intuit.karate.http.ResourceType;45import com.intuit.karate.http.WebSocketClient;46import com.intuit.karate.http.WebSocketOptions;47import com.intuit.karate.shell.Command;48import java.io.File;49import java.net.URLDecoder;50import java.net.URLEncoder;51import java.util.ArrayList;52import java.util.Collections;53import java.util.HashMap;54import java.util.LinkedHashMap;55import java.util.LinkedHashSet;56import java.util.List;57import java.util.Map;58import java.util.Set;59import java.util.TreeMap;60import java.util.function.Function;61import java.util.regex.Matcher;62import java.util.regex.Pattern;63import org.graalvm.polyglot.Value;64/**65 *66 * @author pthomas367 */68public class ScenarioBridge implements PerfContext, EventContext {69 private final ScenarioEngine ENGINE;70 protected ScenarioBridge(ScenarioEngine engine) {71 ENGINE = engine;72 }73 public void abort() {74 getEngine().setAborted(true);75 }76 public Object append(Value... vals) {77 List list = new ArrayList();78 JsList jsList = new JsList(list);79 if (vals.length == 0) {80 return jsList;81 }82 Value val = vals[0];83 if (val.hasArrayElements()) {84 list.addAll(val.as(List.class));85 } else {86 list.add(val.as(Object.class));87 }88 if (vals.length == 1) {89 return jsList;90 }91 for (int i = 1; i < vals.length; i++) {92 Value v = vals[i];93 if (v.hasArrayElements()) {94 list.addAll(v.as(List.class));95 } else {96 list.add(v.as(Object.class));97 }98 }99 return jsList;100 }101 private Object appendToInternal(String varName, Value... vals) {102 ScenarioEngine engine = getEngine();103 Variable var = engine.vars.get(varName);104 if (!var.isList()) {105 return null;106 }107 List list = var.getValue();108 for (Value v : vals) {109 if (v.hasArrayElements()) {110 list.addAll(v.as(List.class));111 } else {112 Object temp = v.as(Object.class);113 list.add(temp);114 }115 }116 engine.setVariable(varName, list);117 return new JsList(list);118 }119 public Object appendTo(Value ref, Value... vals) {120 if (ref.isString()) {121 return appendToInternal(ref.asString(), vals);122 }123 List list;124 if (ref.hasArrayElements()) {125 list = new JsValue(ref).getAsList(); // make sure we unwrap the "original" list126 } else {127 list = new ArrayList();128 }129 for (Value v : vals) {130 if (v.hasArrayElements()) {131 list.addAll(v.as(List.class));132 } else {133 Object temp = v.as(Object.class);134 list.add(temp);135 }136 }137 return new JsList(list);138 }139 public Object call(String fileName) {140 return call(false, fileName, null);141 }142 public Object call(String fileName, Value arg) {143 return call(false, fileName, arg);144 }145 public Object call(boolean sharedScope, String fileName) {146 return call(sharedScope, fileName, null);147 }148 public Object call(boolean sharedScope, String fileName, Value arg) {149 ScenarioEngine engine = getEngine();150 Variable called = new Variable(engine.fileReader.readFile(fileName));151 Variable result = engine.call(called, arg == null ? null : new Variable(arg), sharedScope);152 return JsValue.fromJava(result.getValue());153 }154 private static Object callSingleResult(ScenarioEngine engine, Object o) throws Exception {155 if (o instanceof Exception) {156 engine.logger.warn("callSingle() cached result is an exception");157 throw (Exception) o;158 }159 // if we don't clone, an attach operation would update the tree within the cached value160 // causing future cache hit + attach attempts to fail !161 o = engine.recurseAndAttachAndShallowClone(o);162 return JsValue.fromJava(o);163 }164 public Object callSingle(String fileName) throws Exception {165 return callSingle(fileName, null);166 }167 public Object callSingle(String fileName, Value arg) throws Exception {168 ScenarioEngine engine = getEngine();169 final Map<String, Object> CACHE = engine.runtime.featureRuntime.suite.callSingleCache;170 int minutes = engine.getConfig().getCallSingleCacheMinutes();171 if ((minutes == 0) && CACHE.containsKey(fileName)) {172 engine.logger.trace("callSingle cache hit: {}", fileName);173 return callSingleResult(engine, CACHE.get(fileName));174 }175 long startTime = System.currentTimeMillis();176 engine.logger.trace("callSingle waiting for lock: {}", fileName);177 synchronized (CACHE) { // lock178 if ((minutes == 0) && CACHE.containsKey(fileName)) { // retry179 long endTime = System.currentTimeMillis() - startTime;180 engine.logger.warn("this thread waited {} milliseconds for callSingle lock: {}", endTime, fileName);181 return callSingleResult(engine, CACHE.get(fileName));182 }183 // this thread is the 'winner'184 engine.logger.info(">> lock acquired, begin callSingle: {}", fileName);185 Object result = null;186 File cacheFile = null;187 if (minutes > 0) {188 String cleanedName = StringUtils.toIdString(fileName);189 String cacheFileName = engine.getConfig().getCallSingleCacheDir() + File.separator + cleanedName + ".txt";190 cacheFile = new File(cacheFileName);191 long since = System.currentTimeMillis() - minutes * 60 * 1000;192 if (cacheFile.exists()) {193 long lastModified = cacheFile.lastModified();194 if (lastModified > since) {195 String json = FileUtils.toString(cacheFile);196 result = JsonUtils.fromJson(json);197 engine.logger.info("callSingleCache hit: {}", cacheFile);198 } else {199 engine.logger.info("callSingleCache stale, last modified {} - is before {} (minutes: {})",200 lastModified, since, minutes);201 }202 } else {203 engine.logger.info("callSingleCache file does not exist, will create: {}", cacheFile);204 }205 }206 if (result == null) {207 Variable called = new Variable(read(fileName));208 Variable argVar;209 if (arg == null || arg.isNull()) {210 argVar = null;211 } else {212 argVar = new Variable(arg);213 }214 Variable resultVar;215 try {216 resultVar = engine.call(called, argVar, false);217 } catch (Exception e) {218 // don't retain any vestiges of graal-js 219 RuntimeException re = new RuntimeException(e.getMessage());220 // we do this so that an exception is also "cached"221 resultVar = new Variable(re); // will be thrown at end222 engine.logger.warn("callSingle() will cache an exception");223 }224 if (minutes > 0) { // cacheFile will be not null225 if (resultVar.isMapOrList()) {226 String json = resultVar.getAsString();227 FileUtils.writeToFile(cacheFile, json);228 engine.logger.info("callSingleCache write: {}", cacheFile);229 } else {230 engine.logger.warn("callSingleCache write failed, not json-like: {}", resultVar);231 }232 }233 // functions have to be detached so that they can be re-hydrated in another js context234 result = engine.recurseAndDetachAndShallowClone(resultVar.getValue());235 }236 CACHE.put(fileName, result);237 engine.logger.info("<< lock released, cached callSingle: {}", fileName);238 return callSingleResult(engine, result);239 }240 }241 public Object callonce(String path) {242 return callonce(false, path);243 }244 public Object callonce(boolean sharedScope, String path) {245 String exp = "read('" + path + "')";246 Variable v = getEngine().call(true, exp, sharedScope);247 return JsValue.fromJava(v.getValue());248 }249 @Override250 public void capturePerfEvent(String name, long startTime, long endTime) {251 PerfEvent event = new PerfEvent(startTime, endTime, name, 200);252 getEngine().capturePerfEvent(event);253 }254 public void configure(String key, Value value) {255 getEngine().configure(key, new Variable(value));256 }257 public Object distinct(Value o) {258 if (!o.hasArrayElements()) {259 return JsList.EMPTY;260 }261 long count = o.getArraySize();262 Set<Object> set = new LinkedHashSet();263 for (int i = 0; i < count; i++) {264 Object value = JsValue.toJava(o.getArrayElement(i));265 set.add(value);266 }267 return JsValue.fromJava(new ArrayList(set));268 }269 public String doc(Value v) {270 Map<String, Object> arg;271 if (v.isString()) {272 arg = Collections.singletonMap("read", v.asString());273 } else if (v.hasMembers()) {274 arg = new JsValue(v).getAsMap();275 } else {276 getEngine().logger.warn("doc - unexpected argument: {}", v);277 return null;278 }279 return getEngine().docInternal(arg);280 }281 public void embed(Object o, String contentType) {282 ResourceType resourceType;283 if (contentType == null) {284 resourceType = ResourceType.fromObject(o, ResourceType.BINARY);285 } else {286 resourceType = ResourceType.fromContentType(contentType);287 }288 getEngine().runtime.embed(JsValue.toBytes(o), resourceType);289 }290 public Object eval(String exp) {291 Variable result = getEngine().evalJs(exp);292 return JsValue.fromJava(result.getValue());293 }294 public String exec(Value value) {295 if (value.isString()) {296 return execInternal(Collections.singletonMap("line", value.asString()));297 } else if (value.hasArrayElements()) {298 List args = new JsValue(value).getAsList();299 return execInternal(Collections.singletonMap("args", args));300 } else {301 return execInternal(new JsValue(value).getAsMap());302 }303 }304 private String execInternal(Map<String, Object> options) {305 Command command = getEngine().fork(false, options);306 command.waitSync();307 return command.getAppender().collect();308 }309 public String extract(String text, String regex, int group) {310 Pattern pattern = Pattern.compile(regex);311 Matcher matcher = pattern.matcher(text);312 if (!matcher.find()) {313 getEngine().logger.warn("failed to find pattern: {}", regex);314 return null;315 }316 return matcher.group(group);317 }318 public List<String> extractAll(String text, String regex, int group) {319 Pattern pattern = Pattern.compile(regex);320 Matcher matcher = pattern.matcher(text);321 List<String> list = new ArrayList();322 while (matcher.find()) {323 list.add(matcher.group(group));324 }325 return list;326 }327 public void fail(String reason) {328 getEngine().setFailedReason(new KarateException(reason));329 }330 public Object filter(Value o, Value f) {331 if (!o.hasArrayElements()) {332 return JsList.EMPTY;333 }334 assertIfJsFunction(f);335 long count = o.getArraySize();336 List list = new ArrayList();337 for (int i = 0; i < count; i++) {338 Value v = o.getArrayElement(i);339 Value res = JsEngine.execute(f, v, i);340 if (res.isBoolean() && res.asBoolean()) {341 list.add(new JsValue(v).getValue());342 }343 }344 return new JsList(list);345 }346 public Object filterKeys(Value o, Value... args) {347 if (!o.hasMembers() || args.length == 0) {348 return JsMap.EMPTY;349 }350 List<String> keys = new ArrayList();351 if (args.length == 1) {352 if (args[0].isString()) {353 keys.add(args[0].asString());354 } else if (args[0].hasArrayElements()) {355 long count = args[0].getArraySize();356 for (int i = 0; i < count; i++) {357 keys.add(args[0].getArrayElement(i).toString());358 }359 } else if (args[0].hasMembers()) {360 for (String s : args[0].getMemberKeys()) {361 keys.add(s);362 }363 }364 } else {365 for (Value v : args) {366 keys.add(v.toString());367 }368 }369 Map map = new LinkedHashMap(keys.size());370 for (String key : keys) {371 if (key == null) {372 continue;373 }374 Value v = o.getMember(key);375 if (v != null) {376 map.put(key, v.as(Object.class));377 }378 }379 return new JsMap(map);380 }381 public void forEach(Value o, Value f) {382 assertIfJsFunction(f);383 if (o.hasArrayElements()) {384 long count = o.getArraySize();385 for (int i = 0; i < count; i++) {386 Value v = o.getArrayElement(i);387 f.executeVoid(v, i);388 }389 } else if (o.hasMembers()) { //map390 int i = 0;391 for (String k : o.getMemberKeys()) {392 Value v = o.getMember(k);393 f.executeVoid(k, v, i++);394 }395 } else {396 throw new RuntimeException("not an array or object: " + o);397 }398 }399 public Command fork(Value value) {400 if (value.isString()) {401 return getEngine().fork(true, value.asString());402 } else if (value.hasArrayElements()) {403 List args = new JsValue(value).getAsList();404 return getEngine().fork(true, args);405 } else {406 return getEngine().fork(true, new JsValue(value).getAsMap());407 }408 }409 // TODO breaking returns actual object not wrapper410 // and fromObject() has been removed411 // use new typeOf() method to find type412 public Object fromString(String exp) {413 ScenarioEngine engine = getEngine();414 try {415 Variable result = engine.evalKarateExpression(exp);416 return JsValue.fromJava(result.getValue());417 } catch (Exception e) {418 engine.setFailedReason(null); // special case419 engine.logger.warn("auto evaluation failed: {}", e.getMessage());420 return exp;421 }422 }423 public Object get(String exp) {424 ScenarioEngine engine = getEngine();425 Variable v;426 try {427 v = engine.evalKarateExpression(exp); // even json path expressions will work428 } catch (Exception e) {429 engine.logger.trace("karate.get failed for expression: '{}': {}", exp, e.getMessage());430 engine.setFailedReason(null); // special case !431 return null;432 }433 if (v != null) {434 return JsValue.fromJava(v.getValue());435 } else {436 return null;437 }438 }439 public Object get(String exp, Object defaultValue) {440 Object result = get(exp);441 return result == null ? defaultValue : result;442 }443 // getters =================================================================444 // TODO migrate these to functions not properties445 //446 public ScenarioEngine getEngine() {447 ScenarioEngine engine = ScenarioEngine.get();448 return engine == null ? ENGINE : engine;449 }450 public String getEnv() {451 return getEngine().runtime.featureRuntime.suite.env;452 }453 public Object getFeature() {454 return new JsMap(getEngine().runtime.featureRuntime.result.toInfoJson());455 }456 public Object getInfo() { // TODO deprecate457 return new JsMap(getEngine().runtime.getScenarioInfo());458 }459 private LogFacade logFacade;460 public Object getLogger() {461 if (logFacade == null) {462 logFacade = new LogFacade();463 }464 return logFacade;465 }466 public Object getOs() {467 String name = FileUtils.getOsName();468 String type = FileUtils.getOsType(name).toString().toLowerCase();469 Map<String, Object> map = new HashMap(2);470 map.put("name", name);471 map.put("type", type);472 return new JsMap(map);473 }474 // TODO breaking uri has been renamed to url475 public Object getPrevRequest() {476 HttpRequest hr = getEngine().getRequest();477 if (hr == null) {478 return null;479 }480 Map<String, Object> map = new HashMap();481 map.put("method", hr.getMethod());482 map.put("url", hr.getUrl());483 map.put("headers", hr.getHeaders());484 map.put("body", hr.getBody());485 return JsValue.fromJava(map);486 }487 public Object getProperties() {488 return new JsMap(getEngine().runtime.featureRuntime.suite.systemProperties);489 }490 public Object getScenario() {491 return new JsMap(getEngine().runtime.result.toKarateJson());492 }493 public Object getTags() {494 return JsValue.fromJava(getEngine().runtime.tags.getTags());495 }496 public Object getTagValues() {497 return JsValue.fromJava(getEngine().runtime.tags.getTagValues());498 }499 //==========================================================================500 //501 public HttpRequestBuilder http(String url) {502 ScenarioEngine engine = getEngine();503 HttpClient client = engine.runtime.featureRuntime.suite.clientFactory.create(engine);504 return new HttpRequestBuilder(client).url(url);505 }506 public Object jsonPath(Object o, String exp) {507 Json json = Json.of(o);508 return JsValue.fromJava(json.get(exp));509 }510 public Object keysOf(Value o) {511 return new JsList(o.getMemberKeys());512 }513 public void log(Value... values) {514 ScenarioEngine engine = getEngine();515 if (engine.getConfig().isPrintEnabled()) {516 engine.logger.info("{}", new LogWrapper(values));517 }518 }519 public Object lowerCase(Object o) {520 Variable var = new Variable(o);521 return JsValue.fromJava(var.toLowerCase().getValue());522 }523 public Object map(Value o, Value f) {524 if (!o.hasArrayElements()) {525 return JsList.EMPTY;526 }527 assertIfJsFunction(f);528 long count = o.getArraySize();529 List list = new ArrayList();530 for (int i = 0; i < count; i++) {531 Value v = o.getArrayElement(i);532 Value res = JsEngine.execute(f, v, i);533 list.add(new JsValue(res).getValue());534 }535 return new JsList(list);536 }537 public Object mapWithKey(Value v, String key) {538 if (!v.hasArrayElements()) {539 return JsList.EMPTY;540 }541 long count = v.getArraySize();542 List list = new ArrayList();543 for (int i = 0; i < count; i++) {544 Map map = new LinkedHashMap();545 Value res = v.getArrayElement(i);546 map.put(key, res.as(Object.class));547 list.add(map);548 }549 return new JsList(list);550 }551 public Object match(Object actual, Object expected) {552 Match.Result mr = getEngine().match(Match.Type.EQUALS, actual, expected);553 return JsValue.fromJava(mr.toMap());554 }555 public Object match(String exp) {556 MatchStep ms = new MatchStep(exp);557 Match.Result mr = getEngine().match(ms.type, ms.name, ms.path, ms.expected);558 return JsValue.fromJava(mr.toMap());559 }560 public Object merge(Value... vals) {561 if (vals.length == 0) {562 return null;563 }564 if (vals.length == 1) {565 return vals[0];566 }567 Map map = new HashMap(vals[0].as(Map.class));568 for (int i = 1; i < vals.length; i++) {569 map.putAll(vals[i].as(Map.class));570 }571 return new JsMap(map);572 }573 public void pause(Value value) {574 ScenarioEngine engine = getEngine();575 if (!value.isNumber()) {576 engine.logger.warn("pause argument is not a number:", value);577 return;578 }579 if (engine.runtime.perfMode) {580 engine.runtime.featureRuntime.perfHook.pause(value.asInt());581 } else if (engine.getConfig().isPauseIfNotPerf()) {582 try {583 Thread.sleep(value.asInt());584 } catch (Exception e) {585 throw new RuntimeException(e);586 }587 }588 }589 public String pretty(Object o) {590 Variable v = new Variable(o);591 return v.getAsPrettyString();592 }593 public String prettyXml(Object o) {594 Variable v = new Variable(o);595 return v.getAsPrettyXmlString();596 }597 public void proceed() {598 proceed(null);599 }600 public void proceed(String requestUrlBase) {601 getEngine().mockProceed(requestUrlBase);602 }603 public Object range(int start, int end) {604 return range(start, end, 1);605 }606 public Object range(int start, int end, int interval) {607 if (interval <= 0) {608 throw new RuntimeException("interval must be a positive integer");609 }610 List<Integer> list = new ArrayList();611 if (start <= end) {612 for (int i = start; i <= end; i += interval) {613 list.add(i);614 }615 } else {616 for (int i = start; i >= end; i -= interval) {617 list.add(i);618 }619 }620 return JsValue.fromJava(list);621 }622 public Object read(String name) {623 Object result = getEngine().fileReader.readFile(name);624 return JsValue.fromJava(result);625 }626 public String readAsString(String fileName) {627 return getEngine().fileReader.readFileAsString(fileName);628 }629 public void remove(String name, String path) {630 getEngine().remove(name, path);631 }632 public Object repeat(int n, Value f) {633 assertIfJsFunction(f);634 List list = new ArrayList(n);635 for (int i = 0; i < n; i++) {636 Value v = JsEngine.execute(f, i);637 list.add(new JsValue(v).getValue());638 }639 return new JsList(list);640 }641 // set multiple variables in one shot642 public void set(Map<String, Object> map) {643 getEngine().setVariables(map);644 }645 public void set(String name, Value value) {646 getEngine().setVariable(name, new Variable(value));647 }648 // this makes sense mainly for xpath manipulation from within js649 public void set(String name, String path, Object value) {650 getEngine().set(name, path, new Variable(value));651 }652 public void setXml(String name, String xml) {653 getEngine().setVariable(name, XmlUtils.toXmlDoc(xml));654 }655 // this makes sense mainly for xpath manipulation from within js656 public void setXml(String name, String path, String xml) {657 getEngine().set(name, path, new Variable(XmlUtils.toXmlDoc(xml)));658 }659 @Override660 public void signal(Object o) {661 Value v = Value.asValue(o);662 getEngine().signal(JsValue.toJava(v));663 }664 public Object sizeOf(Value v) {665 if (v.hasArrayElements()) {666 return v.getArraySize();667 } else if (v.hasMembers()) {668 return v.getMemberKeys().size();669 } else {670 return -1;671 }672 }673 public Object sort(Value o) {674 return sort(o, getEngine().JS.evalForValue("x => x"));675 }676 public Object sort(Value o, Value f) {677 if (!o.hasArrayElements()) {678 return JsList.EMPTY;679 }680 assertIfJsFunction(f);681 long count = o.getArraySize();682 Map<Object, Object> map = new TreeMap();683 for (int i = 0; i < count; i++) {684 Object item = JsValue.toJava(o.getArrayElement(i));685 Value key = JsEngine.execute(f, item, i);686 if (key.isNumber()) {687 map.put(key.as(Number.class), item);688 } else {689 map.put(key.asString(), item);690 }691 }692 return JsValue.fromJava(new ArrayList(map.values()));693 }694 public MockServer start(Value value) {695 if (value.isString()) {696 return startInternal(Collections.singletonMap("mock", value.asString()));697 } else {698 return startInternal(new JsValue(value).getAsMap());699 }700 }701 private MockServer startInternal(Map<String, Object> config) {702 String mock = (String) config.get("mock");703 if (mock == null) {704 throw new RuntimeException("'mock' is missing: " + config);705 }706 File feature = toJavaFile(mock);707 MockServer.Builder builder = MockServer.feature(feature);708 String certFile = (String) config.get("cert");709 if (certFile != null) {710 builder.certFile(toJavaFile(certFile));711 }712 String keyFile = (String) config.get("key");713 if (keyFile != null) {714 builder.keyFile(toJavaFile(keyFile));715 }716 Boolean ssl = (Boolean) config.get("ssl");717 if (ssl == null) {718 ssl = false;719 }720 Integer port = (Integer) config.get("port");721 if (port == null) {722 port = 0;723 }724 Map<String, Object> arg = (Map) config.get("arg");725 builder.args(arg);726 if (ssl) {727 builder.https(port);728 } else {729 builder.http(port);730 }731 return builder.build();732 }733 public void stop(int port) {734 Command.waitForSocket(port);735 }736 public String toAbsolutePath(String relativePath) {737 return getEngine().fileReader.toAbsolutePath(relativePath);738 }739 public Object toBean(Object o, String className) {740 Json json = Json.of(o);741 Object bean = JsonUtils.fromJson(json.toString(), className);742 return JsValue.fromJava(bean);743 }744 public String toCsv(Object o) {745 Variable v = new Variable(o);746 if (!v.isList()) {747 throw new RuntimeException("not a json array: " + v);748 }749 List<Map<String, Object>> list = v.getValue();750 return JsonUtils.toCsv(list);751 }752 public Object toJava(Value value) {753 if (value.canExecute()) {754 JsEngine copy = getEngine().JS.copy();755 return new JsLambda(copy.attach(value));756 } else {757 return new JsValue(value).getValue();758 }759 }760 private File toJavaFile(String path) {761 return getEngine().fileReader.toResource(path).getFile();762 }763 public Object toJson(Value value) {764 return toJson(value, false);765 }766 public Object toJson(Value value, boolean removeNulls) {767 JsValue jv = new JsValue(value);768 String json = JsonUtils.toJson(jv.getValue());769 Object result = Json.of(json).value();770 if (removeNulls) {771 JsonUtils.removeKeysWithNullValues(result);772 }773 return JsValue.fromJava(result);774 }775 // TODO deprecate776 public Object toList(Value value) {777 return new JsValue(value).getValue();778 }779 // TODO deprecate780 public Object toMap(Value value) {781 return new JsValue(value).getValue();782 }783 public String toString(Object o) {784 Variable v = new Variable(o);785 return v.getAsString();786 }787 public String trim(String s) {788 return s == null ? null : s.trim();789 }790 public String typeOf(Value value) {791 Variable v = new Variable(value);792 return v.getTypeString();793 }794 public String urlEncode(String s) {795 try {796 return URLEncoder.encode(s, "UTF-8");797 } catch (Exception e) {798 getEngine().logger.warn("url encode failed: {}", e.getMessage());799 return s;800 }801 }802 public String urlDecode(String s) {803 try {804 return URLDecoder.decode(s, "UTF-8");805 } catch (Exception e) {806 getEngine().logger.warn("url encode failed: {}", e.getMessage());807 return s;808 }809 }810 public Object valuesOf(Value v) {811 if (v.hasArrayElements()) {812 return v;813 } else if (v.hasMembers()) {814 List list = new ArrayList();815 for (String k : v.getMemberKeys()) {816 Value res = v.getMember(k);817 list.add(res.as(Object.class));818 }819 return new JsList(list);820 } else {821 return null;822 }823 }824 public boolean waitForHttp(String url) {825 return Command.waitForHttp(url);826 }827 public boolean waitForPort(String host, int port) {828 return new Command().waitForPort(host, port);829 }830 public WebSocketClient webSocket(String url) {831 return webSocket(url, null, null);832 }833 public WebSocketClient webSocket(String url, Value value) {834 return webSocket(url, value, null);835 }836 public WebSocketClient webSocket(String url, Value listener, Value value) {837 Function<String, Boolean> handler;838 ScenarioEngine engine = getEngine();839 if (listener == null || !listener.canExecute()) {840 handler = m -> true;841 } else {842 JsEngine copy = engine.JS.copy();843 handler = new JsLambda(copy.attach(listener));844 }845 WebSocketOptions options = new WebSocketOptions(url, value == null ? null : new JsValue(value).getValue());846 options.setTextHandler(handler);847 return engine.webSocket(options);848 }849 public WebSocketClient webSocketBinary(String url) {850 return webSocketBinary(url, null, null);851 }852 public WebSocketClient webSocketBinary(String url, Value value) {853 return webSocketBinary(url, value, null);854 }855 public WebSocketClient webSocketBinary(String url, Value listener, Value value) {856 Function<byte[], Boolean> handler;857 ScenarioEngine engine = getEngine();858 if (listener == null || !listener.canExecute()) {859 handler = m -> true;860 } else {861 JsEngine copy = engine.JS.copy();862 handler = new JsLambda(copy.attach(listener));863 }864 WebSocketOptions options = new WebSocketOptions(url, value == null ? null : new JsValue(value).getValue());865 options.setBinaryHandler(handler);866 return engine.webSocket(options);867 }868 public File write(Object o, String path) {869 ScenarioEngine engine = getEngine();870 path = engine.runtime.featureRuntime.suite.buildDir + File.separator + path;871 File file = new File(path);872 FileUtils.writeToFile(file, JsValue.toBytes(o));873 engine.logger.debug("write to file: {}", file);874 return file;875 }876 public Object xmlPath(Object o, String path) {877 Variable var = new Variable(o);878 Variable res = ScenarioEngine.evalXmlPath(var, path);879 return JsValue.fromJava(res.getValue());880 }881 // helpers =================================================================882 //883 private static void assertIfJsFunction(Value f) {884 if (!f.canExecute()) {885 throw new RuntimeException("not a js function: " + f);886 }887 }888 // make sure log() toString() is lazy889 static class LogWrapper {890 final Value[] values;891 LogWrapper(Value... values) {892 // sometimes a null array gets passed in, graal weirdness893 this.values = values == null ? new Value[0] : values;894 }895 @Override896 public String toString() {897 StringBuilder sb = new StringBuilder();898 for (Value v : values) {899 Variable var = new Variable(v);900 sb.append(var.getAsPrettyString()).append(' ');901 }902 return sb.toString();903 }904 }905 public static class LogFacade {906 private static Logger getLogger() {907 return ScenarioEngine.get().logger;908 }909 private static String wrap(Value... values) {910 return new LogWrapper(values).toString();911 }912 public void debug(Value... values) {913 getLogger().debug(wrap(values));914 }915 public void info(Value... values) {916 getLogger().info(wrap(values));917 }918 public void trace(Value... values) {919 getLogger().trace(wrap(values));920 }921 public void warn(Value... values) {922 getLogger().warn(wrap(values));923 }924 public void error(Value... values) {925 getLogger().error(wrap(values));926 }927 }928}...

Full Screen

Full Screen

Source:ScenarioActions.java Github

copy

Full Screen

1/*2 * The MIT License3 *4 * Copyright 2020 Intuit Inc.5 *6 * Permission is hereby granted, free of charge, to any person obtaining a copy7 * of this software and associated documentation files (the "Software"), to deal8 * in the Software without restriction, including without limitation the rights9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell10 * copies of the Software, and to permit persons to whom the Software is11 * furnished to do so, subject to the following conditions:12 *13 * The above copyright notice and this permission notice shall be included in14 * all copies or substantial portions of the Software.15 *16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN22 * THE SOFTWARE.23 */24package com.intuit.karate;25import java.util.List;26import java.util.Map;27import org.slf4j.Logger;28import org.slf4j.LoggerFactory;29import com.intuit.karate.core.Action;30import com.intuit.karate.core.AssignType;31import com.intuit.karate.core.ScenarioEngine;32import com.intuit.karate.core.ScenarioEngine.NewDriver;33import com.intuit.karate.core.Variable;34import com.intuit.karate.driver.Driver;35import com.intuit.karate.driver.chrome.Chrome;36import cucumber.api.DataTable;37import cucumber.api.java.en.When;38/**39 * @author pthomas340 */41public class ScenarioActions implements Actions {42 private static Logger logger = LoggerFactory.getLogger(ScenarioActions.class);43 public static void loadOverride() {44 logger.info("use override ScenarioActions");45 }46 private final ScenarioEngine engine;47 public ScenarioActions(ScenarioEngine engine) {48 this.engine = engine;49 }50 @Override51 public boolean isFailed() {52 return engine.isFailed();53 }54 @Override55 public Throwable getFailedReason() {56 return engine.getFailedReason();57 }58 @Override59 public boolean isAborted() {60 return engine.isAborted();61 }62 @Override63 @When("^configure ([^\\s]+) =$")64 public void configureDocstring(String key, String exp) {65 engine.configure(key, exp);66 }67 @Override68 @When("^configure ([^\\s]+) = (.+)")69 public void configure(String key, String exp) {70 engine.configure(key, exp);71 }72 @Override73 @When("^url (.+)")74 public void url(String exp) {75 engine.url(exp);76 }77 @Override78 @When("^path (.+)")79 public void path(String exp) {80 engine.path(exp);81 }82 @Override83 @When("^param ([^\\s]+) = (.+)")84 public void param(String name, String exp) {85 engine.param(name, exp);86 }87 @Override88 @When("^params (.+)")89 public void params(String exp) {90 engine.params(exp);91 }92 @Override93 @When("^cookie ([^\\s]+) = (.+)")94 public void cookie(String name, String value) {95 engine.cookie(name, value);96 }97 @Override98 @When("^cookies (.+)")99 public void cookies(String exp) {100 engine.cookies(exp);101 }102 @Override103 @When("^csv (.+) = (.+)")104 public void csv(String name, String exp) {105 engine.assign(AssignType.CSV, name, exp);106 }107 @Override108 @When("^header ([^\\s]+) = (.+)")109 public void header(String name, String exp) {110 engine.header(name, exp);111 }112 @Override113 @When("^headers (.+)")114 public void headers(String exp) {115 engine.headers(exp);116 }117 @Override118 @When("^form field ([^\\s]+) = (.+)")119 public void formField(String name, String exp) {120 engine.formField(name, exp);121 }122 @Override123 @When("^form fields (.+)")124 public void formFields(String exp) {125 engine.formFields(exp);126 }127 @Override128 @When("^request$")129 public void requestDocstring(String body) {130 engine.request(body);131 }132 @Override133 @When("^request (.+)")134 public void request(String body) {135 engine.request(body);136 }137 @When("^table (.+)")138 public void table(String name, DataTable table) {139 table(name, table.asMaps(String.class, String.class));140 }141 @Override142 @Action("^table (.+)")143 public void table(String name, List<Map<String, String>> table) {144 engine.table(name, table);145 }146 @When("^replace (\\w+)$")147 public void replace(String name, DataTable table) {148 replace(name, table.asMaps(String.class, String.class));149 }150 @Override151 @Action("^replace (\\w+)$")152 public void replace(String name, List<Map<String, String>> table) {153 engine.replaceTable(name, table);154 }155 @Override156 @When("^replace (\\w+).([^\\s]+) = (.+)")157 public void replace(String name, String token, String value) {158 engine.replace(name, token, value);159 }160 @Override161 @When("^def (.+) =$")162 public void defDocstring(String name, String exp) {163 engine.assign(AssignType.AUTO, name, exp);164 }165 @Override166 @When("^def (\\w+) = (.+)")167 public void def(String name, String exp) {168 engine.assign(AssignType.AUTO, name, exp);169 }170 @Override171 @When("^text (.+) =$")172 public void text(String name, String exp) {173 engine.assign(AssignType.TEXT, name, exp);174 }175 @Override176 @When("^yaml (.+) = (.+)")177 public void yaml(String name, String exp) {178 engine.assign(AssignType.YAML, name, exp);179 }180 @Override181 @When("^copy (.+) = (.+)")182 public void copy(String name, String exp) {183 engine.assign(AssignType.COPY, name, exp);184 }185 @Override186 @When("^json (.+) = (.+)")187 public void json(String name, String exp) {188 engine.assign(AssignType.JSON, name, exp);189 }190 @Override191 @When("^string (.+) = (.+)")192 public void string(String name, String exp) {193 engine.assign(AssignType.STRING, name, exp);194 }195 @Override196 @When("^xml (.+) = (.+)")197 public void xml(String name, String exp) {198 engine.assign(AssignType.XML, name, exp);199 }200 @Override201 @When("^xmlstring (.+) = (.+)")202 public void xmlstring(String name, String exp) {203 engine.assign(AssignType.XML_STRING, name, exp);204 }205 @Override206 @When("^bytes (.+) = (.+)")207 public void bytes(String name, String exp) {208 engine.assign(AssignType.BYTE_ARRAY, name, exp);209 }210 @Override211 @When("^assert (.+)")212 public void assertTrue(String exp) {213 engine.assertTrue(exp);214 }215 @Override216 @When("^method (\\w+)")217 public void method(String method) {218 engine.method(method);219 }220 @Override221 @When("^retry until (.+)")222 public void retry(String until) {223 engine.retry(until);224 }225 @Override226 @When("^soap action( .+)?")227 public void soapAction(String action) {228 engine.soapAction(action);229 }230 @Override231 @When("^multipart entity (.+)")232 public void multipartEntity(String value) {233 engine.multipartField(null, value);234 }235 @Override236 @When("^multipart field (.+) = (.+)")237 public void multipartField(String name, String value) {238 engine.multipartField(name, value);239 }240 @Override241 @When("^multipart fields (.+)")242 public void multipartFields(String exp) {243 engine.multipartFields(exp);244 }245 @Override246 @When("^multipart file (.+) = (.+)")247 public void multipartFile(String name, String value) {248 engine.multipartFile(name, value);249 }250 @Override251 @When("^multipart files (.+)")252 public void multipartFiles(String exp) {253 engine.multipartFiles(exp);254 }255 @Override256 @When("^print (.+)")257 public void print(String exp) {258 engine.print(exp);259 }260 @Override261 @When("^status (\\d+)")262 public void status(int status) {263 engine.status(status);264 }265 @Override266 @When("^match (.+)(=|contains|any|only|deep)(.*)")267 public void match(String exp, String op1, String op2, String rhs) {268 if (op2 == null) {269 op2 = "";270 }271 if (rhs == null) {272 rhs = "";273 }274 MatchStep m = new MatchStep(exp + op1 + op2 + rhs);275 engine.matchResult(m.type, m.name, m.path, m.expected);276 }277 @Override278 @When("^set ([^\\s]+)( .+)? =$")279 public void setDocstring(String name, String path, String value) {280 engine.set(name, path, value);281 }282 @Override283 @When("^set ([^\\s]+)( .+)? = (.+)")284 public void set(String name, String path, String value) {285 engine.set(name, path, value);286 }287 @When("^set ([^\\s]+)( [^=]+)?$")288 public void set(String name, String path, DataTable table) {289 set(name, path, table.asMaps(String.class, String.class));290 }291 @Override292 @Action("^set ([^\\s]+)( [^=]+)?$")293 public void set(String name, String path, List<Map<String, String>> table) {294 engine.setViaTable(name, path, table);295 }296 @Override297 @When("^remove ([^\\s]+)( .+)?")298 public void remove(String name, String path) {299 engine.remove(name, path);300 }301 @Override302 @When("^call (.+)")303 public void call(String line) {304 engine.call(false, line, true);305 }306 @Override307 @When("^callonce (.+)")308 public void callonce(String line) {309 engine.call(true, line, true);310 }311 @Override312 @When("^eval (.+)")313 public Object eval(String exp) {314 return engine.evalJs(exp).getValue();315 }316 @Override317 @When("^eval$")318 public Object evalDocstring(String exp) {319 return engine.evalJs(exp).getValue();320 }321 @Override322 @When("^([\\w]+)([^\\s^\\w])(.+)")323 public Object eval(String name, String dotOrParen, String exp) {324 return engine.evalJs(name + dotOrParen + exp).getValue();325 }326 @Override327 @When("^if (.+)")328 public Object evalIf(String exp) {329 return engine.evalJs("if " + exp).getValue();330 }331 @Override332 @When("^listen (.+)")333 public void listen(String body) {334 engine.listen(body);335 }336 @Override337 @When("^doc (.+)")338 public void doc(String exp) {339 engine.doc(exp);340 }341 //==========================================================================342 //343 @Override344 @When("^driver (.+)")345 public void driver(String exp) {346 engine.driver(exp);347 }348 @Override349 @When("^robot (.+)")350 public void robot(String exp) {351 engine.robot(exp);352 }353 // 自定义354 @When("^打开 (.+) 网页$")355 public void openPage(String exp) {356 engine.driver(exp);357 }358 @When("^点击 (.+) 元素$")359 public void clickLocator(String exp) {360 engine.evalJs("click(" + exp + ")");361 }362 @When("^在 (.+) 元素输入 (.+)$")363 public void inputAt(String locator, String value) {364 engine.evalJs("input(" + locator + "," + value + ")");365 }366 @When("^等待 (.+) 秒$")367 public void delaySeconds(String exp) {368 engine.evalJs("delay(" + exp + "000)");369 }370 @When("^use driver (.+)")371 public void useDriver(String exp) {372 String name = extractStrExp(exp);373 if (engine.newDrivers.containsKey(name)) {374 NewDriver newDriver = engine.newDrivers.get(name);375 engine.getConfig().configure("driver", new Variable(newDriver.options));376 engine.setDriver(newDriver.driver);377 } else {378 throw new RuntimeException("driver(" + name + ") not exists");379 }380 }381 @When("^open new (.+)")382 public void openNewPage(String exp) {383 String url = extractStrExp(exp);384 Driver driver = engine.getDriver();385 if (driver != null && driver instanceof Chrome) {386 ((Chrome) driver).openNewPage(url);387 } else {388 throw new RuntimeException("only Chrome support this step");389 }390 }391 @When("^goto top")392 public void gotoTop() {393 Map<String, Object> driverOptions = engine.getConfig().getDriverOptions();394 NewDriver currentDriver = engine.getCurrentChrome();395 if (driverOptions != null && currentDriver != null) {396 ((Chrome) currentDriver.driver).goToTop(0);397 } else {398 throw new RuntimeException("default driver not configured");399 }400 }401 @When("^switch page (.+)")402 public void switchPage(String exp) {403 String urlOrTitle = extractStrExp(exp);404 NewDriver currentDriver = engine.getCurrentChrome();405 if (currentDriver != null) {406 ((Chrome) currentDriver.driver).switchPage2(urlOrTitle);407 } else {408 throw new RuntimeException("default driver not configured");409 }410 }411 private String extractStrExp(String exp) {412 int start = 0;413 int end = 0;414 char first = exp.charAt(0);415 if (first == '\'' || first == '"') {416 start = 1;417 }418 char last = exp.charAt(exp.length() - 1);419 if (last == '\'' || last == '"') {420 end = exp.length() - 1;421 }422 if (start > 0 || end > 0) {423 return exp.substring(start, end);424 } else {425 return exp;426 }427 }428}...

Full Screen

Full Screen

callOnce

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.core.ScenarioEngine;2import com.intuit.karate.http.HttpClient;3import com.intuit.karate.http.HttpRequest;4import com.intuit.karate.http.HttpResponse;5import com.intuit.karate.http.HttpUtils;6import com.intuit.karate.http.HttpUtils.HttpMethod;7import com.intuit.karate.http.HttpUtils.HttpStatusCode;8import com.intuit.karate.http.MultiValuedMap;9import java.util.Map;10import java.util.HashMap;11import java.util.List;12import java.util.ArrayList;13import java.util.Collections;14import java.util.concurrent.TimeUnit;15import java.util.concurrent.atomic.AtomicInteger;16import java.util.concurrent.atomic.AtomicLong;17import java.util.concurrent.atomic.AtomicBoolean;18import java.util.concurrent.Executors;19import java.util.concurrent.ScheduledExecutorService;20import java.util.concurrent.ScheduledFuture;21import java.util.concurrent.ThreadFactory;22import java.util.concurrent.ThreadLocalRandom;23import java.util.concurrent.ThreadPoolExecutor;24import java.util.concurrent.TimeUnit;25import java.util.concurrent.TimeoutException;26import java.util.concurrent.atomic.AtomicInteger;27import java.util.concurrent.atomic.AtomicLong;28import java.util.concurrent.atomic.AtomicReference;29import java.util.concurrent.locks.Lock;30import java.util.concurrent.locks.ReentrantLock;31import java.util.function.Function;32import java.util.stream.Collectors;33import java.util.stream.Stream;34import org.slf4j.Logger;35import org.slf4j.LoggerFactory;36import org.slf4j.MDC;37import org.w3c.dom.Document;38import org.w3c.dom.Element;39import org.w3c.dom.Node;40import org.w3c.dom.NodeList;41import org.w3c.dom.Text;42import org.xml.sax.SAXException;43import org.xml.sax.SAXParseException;44import org.xml.sax.helpers.DefaultHandler;45import org.xml.sax.helpers.De

Full Screen

Full Screen

callOnce

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.Feature;5import com.intuit.karate.core.FeatureRuntime;6import com.intuit.karate.core.FeatureContext;7import com.intuit.karate.core.FeatureRuntime;8import com.intuit.karate.core.FeatureContext;9import com.intuit.karate.core.Feature;10import java.util.Map;11import java.util.HashMap;12public class 4 {13 public static void main(String[] args) {14 Feature feature = Feature.read("classpath:4.feature");15 FeatureContext featureContext = new FeatureContext();16 FeatureRuntime featureRuntime = new FeatureRuntime(feature, featureContext);17 ScenarioEngine scenarioEngine = new ScenarioEngine(featureRuntime);18 ScenarioContext scenarioContext = new ScenarioContext();19 ScenarioRuntime scenarioRuntime = new ScenarioRuntime(featureRuntime, scenarioEngine, scenarioContext);20 Map<String, Object> vars = new HashMap();21 vars.put("x", 1);22 scenarioRuntime.callOnce("add 1", vars);23 vars.put("x", 2);24 scenarioRuntime.callOnce("add 1", vars);25 vars.put("x", 3);26 scenarioRuntime.callOnce("add 1", vars);27 System.out.println("x = " + vars.get("x"));28 }29}30* def x = callonce read('classpath:4.js')31function(){32 var x = karate.get('x');33 x = x + 1;34 karate.set('x', x);35 return x;36}37* def x = callonce read('classpath:5.js')38* def x = callonce read('classpath:5.js')39* def x = callonce read('classpath:5.js')40function(){41 var x = karate.get('x');42 x = x + 1;43 karate.set('x', x);44 return x;45}

Full Screen

Full Screen

callOnce

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.core.ScenarioEngine;2public class 4 {3 public static void main(String[] args) {4 ScenarioEngine.callOnce();5 }6}7import com.intuit.karate.core.ScenarioEngine;8public class 5 {9 public static void main(String[] args) {10 ScenarioEngine.callOnce();11 }12}13import com.intuit.karate.core.ScenarioEngine;14public class 6 {15 public static void main(String[] args) {16 ScenarioEngine.callOnce();17 }18}19import com.intuit.karate.core.ScenarioEngine;20public class 7 {21 public static void main(String[] args) {22 ScenarioEngine.callOnce();23 }24}25import com.intuit.karate.core.ScenarioEngine;26public class 8 {27 public static void main(String[] args) {28 ScenarioEngine.callOnce();29 }30}31import com.intuit.karate.core.ScenarioEngine;32public class 9 {33 public static void main(String[] args) {34 ScenarioEngine.callOnce();35 }36}37import com.intuit.karate.core.ScenarioEngine;38public class 10 {39 public static void main(String[] args) {40 ScenarioEngine.callOnce();41 }42}43import com.intuit.karate.core.ScenarioEngine;44public class 11 {45 public static void main(String[] args) {46 ScenarioEngine.callOnce();47 }48}

Full Screen

Full Screen

callOnce

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.core.ScenarioEngine;2import com.intuit.karate.core.ScenarioResult;3import com.intuit.karate.core.ScenarioContext;4import com.intuit.karate.core.Feature;5import com.intuit.karate.core.FeatureResult;6import com.intuit.karate.core.FeatureRuntime;7import com.intuit.karate.core.FeatureRuntimeBuilder;8import com.intuit.karate.core.FeatureRuntimeOptions;9public class 4 {10 public static void main(String[] args) {11 String featurePath = "classpath:4.feature";12 FeatureRuntimeOptions options = new FeatureRuntimeOptions();13 options.setTags("~@ignore");14 FeatureRuntimeBuilder builder = FeatureRuntime.builder();15 FeatureRuntime runtime = builder.options(options).build();16 Feature feature = runtime.readFeature(featurePath);17 ScenarioEngine engine = runtime.getEngine();18 ScenarioContext context = new ScenarioContext(feature, 0);19 ScenarioResult result = engine.callOnce(context);20 FeatureResult featureResult = new FeatureResult(feature, result);21 System.out.println("result: " + featureResult.isPassed());22 }23}24import com.intuit.karate.core.ScenarioEngine;25import com.intuit.karate.core.ScenarioResult;26import com.intuit.karate.core.ScenarioContext;27import com.intuit.karate.core.Feature;28import com.intuit.karate.core.FeatureResult;29import com.intuit.karate.core.FeatureRuntime;30import com.intuit.karate.core.FeatureRuntimeBuilder;31import com.intuit.karate.core.FeatureRuntimeOptions;32public class 5 {33 public static void main(String[] args) {34 String featurePath = "classpath:5.feature";35 FeatureRuntimeOptions options = new FeatureRuntimeOptions();36 options.setTags("~@ignore");37 FeatureRuntimeBuilder builder = FeatureRuntime.builder();38 FeatureRuntime runtime = builder.options(options).build();39 Feature feature = runtime.readFeature(featurePath);40 ScenarioEngine engine = runtime.getEngine();41 ScenarioContext context = new ScenarioContext(feature, 0);42 ScenarioResult result = engine.callOnce(context

Full Screen

Full Screen

callOnce

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.core.ScenarioEngine;2import java.util.HashMap;3import java.util.Map;4public class 4 {5 public static void main(String[] args) {6 Map<String, Object> map = new HashMap();7 map.put("foo", "bar");8 ScenarioEngine.callOnce("classpath:4.feature", map);9 }10}11import com.intuit.karate.core.ScenarioEngine;12import java.util.HashMap;13import java.util.Map;14public class 4 {15 public static void main(String[] args) {16 Map<String, Object> map = new HashMap();17 map.put("foo", "bar");18 ScenarioEngine.callOnce("classpath:4.feature", map);19 }20}21import com.intuit.karate.core.ScenarioEngine;22import java.util.HashMap;23import java.util.Map;24public class 4 {25 public static void main(String[] args) {26 Map<String, Object> map = new HashMap();27 map.put("foo", "bar");28 ScenarioEngine.callOnce("classpath:4.feature", map);29 }30}31import com.intuit.karate.core.ScenarioEngine;32import java.util.HashMap;33import java.util.Map;34public class 4 {35 public static void main(String[] args) {

Full Screen

Full Screen

callOnce

Using AI Code Generation

copy

Full Screen

1package demo;2import com.intuit.karate.FileUtils;3import com.intuit.karate.core.ScenarioEngine;4import com.intuit.karate.http.HttpClient;5import com.intuit.karate.http.HttpClientFactory;6import com.intuit.karate.http.HttpConfig;7import com.intuit.karate.http.HttpRequest;8import com.intuit.karate.http.HttpResponse;9import com.intuit.karate.http.HttpUtils;10import java.io.File;11import java.util.ArrayList;12import java.util.List;13import java.util.Map;14import java.util.concurrent.Callable;15import java.util.concurrent.ExecutorService;16import java.util.concurrent.Executors;17import java.util.concurrent.Future;18public class Main {19 public static void main(String[] args) throws Exception {20 File file = new File("demo.feature");21 byte[] bytes = FileUtils.toBytes(file);22 String text = new String(bytes);23 Map<String, Object> map = HttpUtils.toMap(text);24 List<Map<String, Object>> list = (List<Map<String, Object>>) map.get("scenario");25 List<Callable<HttpResponse>> callables = new ArrayList(list.size());26 for (Map<String, Object> map1 : list) {27 String name = (String) map1.get("name");28 String method = (String) map1.get("method");29 String url = (String) map1.get("url");30 Map<String, Object> headers = (Map<String, Object>) map1.get("headers");31 Map<String, Object> params = (Map<String, Object>) map1.get("params");32 Map<String, Object> formParams = (Map<String, Object>) map1.get("formParams");33 Map<String, Object> body = (Map<String, Object>) map1.get("body");34 HttpRequest request = new HttpRequest();35 request.setUrl(url);36 request.setMethod(method);37 request.setHeaders(headers);38 request.setParams(params);39 request.setFormParams(formParams);40 request.setBody(body);41 callables.add(new Callable<HttpResponse>() {42 public HttpResponse call() throws Exception {43 HttpClientFactory factory = new HttpClientFactory();44 HttpConfig config = new HttpConfig();

Full Screen

Full Screen

callOnce

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.core.ScenarioEngine;2import com.intuit.karate.core.ScenarioResult;3import com.intuit.karate.core.ScenarioRuntime;4import com.intuit.karate.core.ScenarioContext;5import com.intuit.karate.core.Scenario;6import com.intuit.karate.core.Feature;7import com.intuit.karate.core.FeatureRuntime;8import com.intuit.karate.core.FeatureContext;9import com.intuit.karate.core.FeatureResult;10import java.io.File;11import java.io.IOException;12import java.util.Map;13import java.util.HashMap;14import java.util.List;15import java.util.ArrayList;16import java.util.Arrays;17import java.util.concurrent.TimeUnit;18import java.util.concurrent.CountDownLatch;19import java.util.concurrent.ExecutorService;20import java.util.concurrent.Executors;21import java.util.concurrent.Future;22import java.util.concurrent.Callable;23import java.util.concurrent.atomic.AtomicInteger;24import java.util.concurrent.atomic.AtomicReference;25import org.slf4j.Logger;26import org.slf4j.LoggerFactory;27public class 4 {28 private static final Logger logger = LoggerFactory.getLogger(4.class);29 public static void main(String[] args) throws Exception {30 File file = new File("4.feature");31 String featureString = FileUtils.readFileToString(file, "UTF-8");32 String result = ScenarioEngine.callOnce(featureString, "4.feature", null, null);33 System.out.println(result);34 }35}36import com.intuit.karate.core.ScenarioEngine;37import com.intuit.karate.core.ScenarioResult;38import com.intuit.karate.core.ScenarioRuntime;39import com.intuit.karate.core.ScenarioContext;40import com.intuit.karate.core.Scenario;41import com.intuit.karate.core.Feature;42import com.intuit.karate.core.FeatureRuntime;43import com.intuit.karate.core.FeatureContext;44import com.intuit.karate.core.FeatureResult;45import java.io.File;46import java.io.IOException;47import java.util.Map;48import java.util.HashMap;49import java.util.List;50import java

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