Best Karate code snippet using com.intuit.karate.Match.getAsString
Source:ScriptBridge.java
...89 }90 91 public String toString(Object o) {92 ScriptValue sv = new ScriptValue(o);93 return sv.getAsString();94 }95 public String pretty(Object o) {96 ScriptValue sv = new ScriptValue(o);97 return sv.getAsPrettyString();98 }99 public String prettyXml(Object o) {100 ScriptValue sv = new ScriptValue(o);101 if (sv.isXml()) {102 Node node = sv.getValue(Node.class);103 return XmlUtils.toString(node, true);104 } else if (sv.isMapLike()) {105 Document doc = XmlUtils.fromMap(sv.getAsMap());106 return XmlUtils.toString(doc, true);107 } else {108 String xml = sv.getAsString();109 Document doc = XmlUtils.toXmlDoc(xml);110 return XmlUtils.toString(doc, true);111 }112 }113 public void set(String name, Object o) {114 context.vars.put(name, o);115 }116 public void setXml(String name, String xml) {117 context.vars.put(name, XmlUtils.toXmlDoc(xml));118 }119 // this makes sense mainly for xpath manipulation from within js120 public void set(String name, String path, Object value) {121 Script.setValueByPath(name, path, new ScriptValue(value), context);122 }123 // this makes sense mainly for xpath manipulation from within js124 public void setXml(String name, String path, String xml) {125 Script.setValueByPath(name, path, new ScriptValue(XmlUtils.toXmlDoc(xml)), context);126 }127 // set multiple variables in one shot128 public void set(Map<String, Object> map) {129 map.forEach((k, v) -> set(k, v));130 }131 // this makes sense for xml / xpath manipulation from within js132 public void remove(String name, String path) {133 Script.removeValueByPath(name, path, context);134 }135 public Object get(String exp) {136 ScriptValue sv;137 try {138 sv = Script.evalKarateExpression(exp, context); // even json path expressions will work139 } catch (Exception e) {140 context.logger.trace("karate.get failed for expression: '{}': {}", exp, e.getMessage());141 return null;142 }143 if (sv != null) {144 return sv.getAfterConvertingFromJsonOrXmlIfNeeded();145 } else {146 return null;147 }148 }149 public Object get(String exp, Object defaultValue) {150 Object result = get(exp);151 return result == null ? defaultValue : result;152 }153 public int sizeOf(Object o) {154 ScriptValue sv = new ScriptValue(o);155 if (sv.isMapLike()) {156 return sv.getAsMap().size();157 }158 if (sv.isListLike()) {159 return sv.getAsList().size();160 }161 return -1;162 }163 public List keysOf(Object o) {164 ScriptValue sv = new ScriptValue(o);165 if (sv.isMapLike()) {166 return new ArrayList(sv.getAsMap().keySet());167 }168 return null;169 }170 public List valuesOf(Object o) {171 ScriptValue sv = new ScriptValue(o);172 if (sv.isMapLike()) {173 return new ArrayList(sv.getAsMap().values());174 }175 if (sv.isListLike()) {176 return sv.getAsList();177 }178 return null;179 }180 public Map<String, Object> match(Object actual, Object expected) {181 AssertionResult ar = Script.matchNestedObject('.', "$", MatchType.EQUALS, actual, null, actual, expected, context);182 return ar.toMap();183 }184 public Map<String, Object> match(String exp) {185 MatchStep ms = new MatchStep(exp);186 AssertionResult ar = Script.matchNamed(ms.type, ms.name, ms.path, ms.expected, context);187 return ar.toMap();188 }189 public void forEach(Object o, ScriptObjectMirror som) {190 ScriptValue sv = new ScriptValue(o);191 if (!sv.isJsonLike()) {192 throw new RuntimeException("not map-like or list-like: " + o);193 }194 if (!som.isFunction()) {195 throw new RuntimeException("not a JS function: " + som);196 }197 if (sv.isListLike()) {198 List list = sv.getAsList();199 for (int i = 0; i < list.size(); i++) {200 som.call(som, list.get(i), i);201 }202 } else { //map203 Map map = sv.getAsMap();204 AtomicInteger i = new AtomicInteger();205 map.forEach((k, v) -> som.call(som, k, v, i.getAndIncrement()));206 }207 }208 public Object map(List list, ScriptObjectMirror som) {209 if (list == null) {210 return new ArrayList();211 }212 if (!som.isFunction()) {213 throw new RuntimeException("not a JS function: " + som);214 }215 List res = new ArrayList(list.size());216 for (int i = 0; i < list.size(); i++) {217 Object y = som.call(som, list.get(i), i);218 res.add(new ScriptValue(y).getValue()); // TODO graal219 }220 return res;221 }222 public Object filter(List list, ScriptObjectMirror som) {223 if (list == null) {224 return new ArrayList();225 }226 if (!som.isFunction()) {227 throw new RuntimeException("not a JS function: " + som);228 }229 List res = new ArrayList();230 for (int i = 0; i < list.size(); i++) {231 Object x = list.get(i);232 Object y = som.call(som, x, i);233 if (y instanceof Boolean) {234 if ((Boolean) y) {235 res.add(x);236 }237 } else if (y instanceof Number) { // support truthy numbers as a convenience238 String exp = y + " == 0";239 ScriptValue sv = Script.evalJsExpression(exp, null);240 if (!sv.isBooleanTrue()) {241 res.add(x);242 }243 }244 }245 return res;246 }247 public Object filterKeys(Object o, Map<String, Object> filter) {248 ScriptValue sv = new ScriptValue(o);249 if (!sv.isMapLike()) {250 return new LinkedHashMap();251 }252 Map map = sv.getAsMap();253 if (filter == null) {254 return map;255 }256 Map out = new LinkedHashMap(filter.size());257 filter.keySet().forEach(k -> {258 if (map.containsKey(k)) {259 out.put(k, map.get(k));260 }261 });262 return out;263 }264 public Object filterKeys(Object o, List keys) {265 return filterKeys(o, keys.toArray());266 }267 public Object filterKeys(Object o, Object... keys) {268 ScriptValue sv = new ScriptValue(o);269 if (!sv.isMapLike()) {270 return new LinkedHashMap();271 }272 Map map = sv.getAsMap();273 Map out = new LinkedHashMap(keys.length);274 for (Object key : keys) {275 if (map.containsKey(key)) {276 out.put(key, map.get(key));277 }278 }279 return out;280 }281 public Object repeat(int n, ScriptObjectMirror som) {282 if (!som.isFunction()) {283 throw new RuntimeException("not a JS function: " + som);284 }285 List res = new ArrayList();286 for (int i = 0; i < n; i++) {287 Object o = som.call(som, i);288 res.add(new ScriptValue(o).getValue()); // TODO graal289 }290 return res;291 }292 public Object mapWithKey(List list, String key) {293 if (list == null) {294 return new ArrayList();295 }296 List res = new ArrayList(list.size());297 for (Object o : list) {298 Map map = new LinkedHashMap();299 map.put(key, o);300 res.add(map);301 }302 return res;303 }304 public Object merge(Map... maps) {305 Map out = new LinkedHashMap();306 if (maps == null) {307 return out;308 }309 for (Map map : maps) {310 if (map == null) {311 continue;312 }313 out.putAll(map);314 }315 return out;316 }317 public Object append(Object... items) {318 List out = new ArrayList();319 if (items == null) {320 return out;321 }322 for (Object item : items) {323 if (item == null) {324 continue;325 }326 if (item instanceof ScriptObjectMirror) { // no need when graal327 ScriptObjectMirror som = (ScriptObjectMirror) item;328 if (som.isArray()) {329 out.addAll(som.values());330 } else {331 out.add(som);332 }333 } else if (item instanceof Collection) {334 out.addAll((Collection) item);335 } else {336 out.add(item);337 }338 }339 return out;340 }341 public List appendTo(String name, Object... values) {342 ScriptValue sv = context.vars.get(name);343 if (sv == null || !sv.isListLike()) {344 return Collections.EMPTY_LIST;345 }346 List list = appendTo(sv.getAsList(), values);347 context.vars.put(name, list);348 return list;349 }350 public List appendTo(List list, Object... values) {351 for (Object o : values) {352 if (o instanceof Collection) {353 list.addAll((Collection) o);354 } else {355 list.add(o);356 }357 }358 return list;359 }360 public Object jsonPath(Object o, String exp) {361 DocumentContext doc;362 if (o instanceof DocumentContext) {363 doc = (DocumentContext) o;364 } else {365 doc = JsonPath.parse(o);366 }367 return doc.read(exp);368 }369 public Object lowerCase(Object o) {370 ScriptValue sv = new ScriptValue(o);371 return sv.toLowerCase();372 }373 public Object xmlPath(Object o, String path) {374 if (!(o instanceof Node)) {375 if (o instanceof Map) {376 o = XmlUtils.fromMap((Map) o);377 } else {378 throw new RuntimeException("not XML or cannot convert: " + o);379 }380 }381 ScriptValue sv = Script.evalXmlPathOnXmlNode((Node) o, path);382 return sv.getValue();383 }384 public Object toBean(Object o, String className) {385 ScriptValue sv = new ScriptValue(o);386 DocumentContext doc = Script.toJsonDoc(sv, context);387 return JsonUtils.fromJson(doc.jsonString(), className);388 }389 public Object toMap(Object o) {390 if (o instanceof Map) {391 Map<String, Object> src = (Map) o;392 return new LinkedHashMap(src);393 }394 return o;395 }396 public Object toList(Object o) {397 if (o instanceof List) {398 List src = (List) o;399 return new ArrayList(src);400 }401 return o;402 }403 public Object toJson(Object o) {404 return toJson(o, false);405 }406 public Object toJson(Object o, boolean removeNulls) {407 Object result = JsonUtils.toJsonDoc(o).read("$");408 if (removeNulls) {409 JsonUtils.removeKeysWithNullValues(result);410 }411 return result;412 }413 public String toCsv(Object o) {414 ScriptValue sv = new ScriptValue(o);415 if (!sv.isListLike()) {416 throw new RuntimeException("not a list-like value:" + sv);417 }418 List<Map<String, Object>> list = sv.getAsList();419 return JsonUtils.toCsv(list);420 }421 public Object call(String fileName) {422 return call(false, fileName, null);423 }424 public Object call(String fileName, Object arg) {425 return call(false, fileName, arg);426 }427 public Object call(boolean sharedScope, String fileName) {428 return call(sharedScope, fileName, null);429 }430 // note that the implementation is subtly different from context.call()431 // because we are within a JS block432 public Object call(boolean sharedScope, String fileName, Object arg) {433 ScriptValue called = FileUtils.readFile(fileName, context);434 ScriptValue result;435 switch (called.getType()) {436 case FEATURE:437 Feature feature = called.getValue(Feature.class);438 // last param is for edge case where this.context is from function 439 // inited before call hierarchy was determined, see CallContext440 result = Script.evalFeatureCall(feature, arg, context, sharedScope);441 break;442 case JS_FUNCTION:443 ScriptObjectMirror som = called.getValue(ScriptObjectMirror.class);444 result = Script.evalJsFunctionCall(som, arg, context);445 break;446 default: // TODO remove ?447 context.logger.warn("not a js function or feature file: {} - {}", fileName, called);448 return null;449 }450 // if shared scope, a called feature would update the context directly451 if (sharedScope && !called.isFeature() && result.isMapLike()) {452 result.getAsMap().forEach((k, v) -> context.vars.put(k, v));453 }454 return result.getValue();455 }456 public Object callSingle(String fileName) {457 return callSingle(fileName, null);458 }459 public Object callSingle(String fileName, Object arg) {460 if (GLOBALS.containsKey(fileName)) {461 context.logger.trace("callSingle cache hit: {}", fileName);462 return GLOBALS.get(fileName);463 }464 long startTime = System.currentTimeMillis();465 context.logger.trace("callSingle waiting for lock: {}", fileName);466 synchronized (GLOBALS_LOCK) { // lock467 if (GLOBALS.containsKey(fileName)) { // retry468 long endTime = System.currentTimeMillis() - startTime;469 context.logger.warn("this thread waited {} milliseconds for callSingle lock: {}", endTime, fileName);470 return GLOBALS.get(fileName);471 }472 // this thread is the 'winner'473 context.logger.info(">> lock acquired, begin callSingle: {}", fileName);474 int minutes = context.getConfig().getCallSingleCacheMinutes();475 Object result = null;476 File cacheFile = null;477 if (minutes > 0) {478 String qualifiedFileName = FileUtils.toPackageQualifiedName(fileName);479 String cacheFileName = context.getConfig().getCallSingleCacheDir() + File.separator + qualifiedFileName + ".txt";480 cacheFile = new File(cacheFileName);481 long since = System.currentTimeMillis() - minutes * 60 * 1000;482 if (cacheFile.exists()) {483 long lastModified = cacheFile.lastModified();484 if (lastModified > since) {485 String json = FileUtils.toString(cacheFile);486 result = JsonUtils.toJsonDoc(json);487 context.logger.info("callSingleCache hit: {}", cacheFile);488 } else {489 context.logger.info("callSingleCache stale, last modified {} - is before {} (minutes: {})", lastModified, since,490 minutes);491 }492 } else {493 context.logger.info("callSingleCache file does not exist, will create: {}", cacheFile);494 }495 }496 if (result == null) {497 result = call(fileName, arg);498 if (minutes > 0) { // cacheFile will be not null499 ScriptValue cacheValue = new ScriptValue(result);500 if (cacheValue.isJsonLike()) {501 String json = cacheValue.getAsString();502 FileUtils.writeToFile(cacheFile, json);503 context.logger.info("callSingleCache write: {}", cacheFile);504 } else {505 context.logger.warn("callSingleCache write failed, not json-like: {}", cacheValue);506 }507 }508 }509 GLOBALS.put(fileName, result);510 context.logger.info("<< lock released, cached callSingle: {}", fileName);511 return result;512 }513 }514 public HttpRequest getPrevRequest() {515 return context.getPrevRequest();516 }517 public Object eval(String exp) {518 ScriptValue sv = Script.evalJsExpression(exp, context);519 return sv.getValue();520 }521 public ScriptValue fromString(String exp) {522 try {523 return Script.evalKarateExpression(exp, context);524 } catch (Exception e) {525 return new ScriptValue(exp);526 }527 }528 public ScriptValue fromObject(Object o) {529 return new ScriptValue(o);530 }531 public List<String> getTags() {532 return context.tags;533 }534 public Map<String, List<String>> getTagValues() {535 return context.tagValues;536 }537 public Map<String, Object> getInfo() {538 return context.getScenarioInfo();539 }540 public Scenario getScenario() {541 return context.getScenario();542 }543 public void proceed() {544 proceed(null);545 }546 public void proceed(String requestUrlBase) {547 HttpRequestBuilder request = new HttpRequestBuilder();548 String urlBase = requestUrlBase == null ? getAsString(ScriptValueMap.VAR_REQUEST_URL_BASE) : requestUrlBase;549 String uri = getAsString(ScriptValueMap.VAR_REQUEST_URI);550 String url = uri == null ? urlBase : urlBase + uri;551 request.setUrl(url);552 request.setMethod(getAsString(ScriptValueMap.VAR_REQUEST_METHOD));553 request.setHeaders(getValue(ScriptValueMap.VAR_REQUEST_HEADERS).getValue(MultiValuedMap.class));554 request.removeHeaderIgnoreCase(HttpUtils.HEADER_CONTENT_LENGTH);555 request.setBody(getValue(ScriptValueMap.VAR_REQUEST));556 HttpResponse response = context.getHttpClient().invoke(request, context);557 context.setPrevResponse(response);558 context.updateResponseVars();559 }560 public void embed(Object o, String contentType) {561 ScriptValue sv = new ScriptValue(o);562 if (contentType == null) {563 contentType = HttpUtils.getContentType(sv);564 }565 context.embed(sv.getAsByteArray(), contentType);566 }567 public File write(Object o, String path) {568 ScriptValue sv = new ScriptValue(o);569 path = FileUtils.getBuildDir() + File.separator + path;570 File file = new File(path);571 FileUtils.writeToFile(file, sv.getAsByteArray());572 return file;573 }574 public WebSocketClient webSocket(String url) {575 return webSocket(url, null, null);576 }577 public WebSocketClient webSocket(String url, Function<String, Boolean> handler) {578 return webSocket(url, handler, null);579 }580 public WebSocketClient webSocket(String url, Function<String, Boolean> handler, Map<String, Object> map) {581 if (handler == null) {582 handler = t -> true; // auto signal for websocket tests583 }584 WebSocketOptions options = new WebSocketOptions(url, map);585 options.setTextHandler(handler);586 return context.webSocket(options);587 }588 public WebSocketClient webSocketBinary(String url) {589 return webSocketBinary(url, null, null);590 }591 public WebSocketClient webSocketBinary(String url, Function<byte[], Boolean> handler) {592 return webSocketBinary(url, handler, null);593 }594 public WebSocketClient webSocketBinary(String url, Function<byte[], Boolean> handler, Map<String, Object> map) {595 if (handler == null) {596 handler = t -> true; // auto signal for websocket tests597 }598 WebSocketOptions options = new WebSocketOptions(url, map);599 options.setBinaryHandler(handler);600 return context.webSocket(options);601 }602 public void signal(Object result) {603 context.signal(result);604 }605 public Object listen(long timeout, ScriptObjectMirror som) {606 if (!som.isFunction()) {607 throw new RuntimeException("not a JS function: " + som);608 }609 return context.listen(timeout, () -> Script.evalJsFunctionCall(som, null, context));610 }611 public Object listen(long timeout) {612 return context.listen(timeout, null);613 }614 private ScriptValue getValue(String name) {615 ScriptValue sv = context.vars.get(name);616 return sv == null ? ScriptValue.NULL : sv;617 }618 private String getAsString(String name) {619 return getValue(name).getAsString();620 }621 public boolean pathMatches(String path) {622 String uri = getAsString(ScriptValueMap.VAR_REQUEST_URI);623 Map<String, String> pathParams = HttpUtils.parseUriPattern(path, uri);624 set(ScriptBindings.PATH_PARAMS, pathParams);625 boolean matched = pathParams != null;626 List<Integer> pathMatchScores = null;627 if (matched) {628 pathMatchScores = HttpUtils.calculatePathMatchScore(path);629 }630 set(ScriptBindings.PATH_MATCH_SCORES, pathMatchScores);631 return matched;632 }633 public boolean methodIs(String... methods) {634 String actual = getAsString(ScriptValueMap.VAR_REQUEST_METHOD);635 boolean match = Arrays.stream(methods).anyMatch((m) -> actual.equalsIgnoreCase(m));636 boolean existingValue = (Boolean) get(ScriptBindings.METHOD_MATCH, Boolean.FALSE);637 set(ScriptBindings.METHOD_MATCH, match || existingValue);638 return match;639 }640 public Object paramValue(String name) {641 List<String> list = paramValues(name);642 if (list == null) {643 return null;644 }645 if (list.size() == 1) {646 return list.get(0);647 }648 return list;...
Source:StepDefs.java
...87 context.configure(key, exp);88 }89 @When("^url (.+)")90 public void url(String expression) {91 String temp = Script.evalKarateExpression(expression, context).getAsString();92 request.setUrl(temp);93 }94 @When("^path (.+)")95 public void path(List<String> paths) {96 for (String path : paths) {97 ScriptValue temp = Script.evalKarateExpression(path, context);98 if (temp.isListLike()) {99 List list = temp.getAsList();100 for (Object o : list) {101 if (o == null) {102 continue;103 }104 request.addPath(o.toString());105 }106 } else {107 request.addPath(temp.getAsString());108 }109 }110 }111 private List<String> evalList(List<String> values) {112 List<String> list = new ArrayList(values.size());113 try {114 for (String value : values) {115 ScriptValue temp = Script.evalKarateExpression(value, context);116 list.add(temp.getAsString());117 }118 } catch (Exception e) { // hack. for e.g. json with commas would land here119 String joined = StringUtils.join(values, ',');120 ScriptValue temp = Script.evalKarateExpression(joined, context);121 if (temp.isListLike()) {122 return temp.getAsList();123 } else {124 return Collections.singletonList(temp.getAsString());125 }126 }127 return list;128 }129 @When("^param ([^\\s]+) = (.+)")130 public void param(String name, List<String> values) {131 List<String> list = evalList(values);132 request.setParam(name, list);133 }134 public Map<String, Object> evalMapExpr(String expr) {135 ScriptValue value = Script.evalKarateExpression(expr, context);136 if (!value.isMapLike()) {137 throw new KarateException("cannot convert to map: " + expr);138 }139 return value.getAsMap();140 }141 @When("^params (.+)")142 public void params(String expr) {143 Map<String, Object> map = evalMapExpr(expr);144 for (Map.Entry<String, Object> entry : map.entrySet()) {145 String key = entry.getKey();146 Object temp = entry.getValue();147 if (temp == null) {148 request.removeParam(key);149 } else {150 if (temp instanceof List) {151 request.setParam(key, (List) temp);152 } else {153 request.setParam(key, temp.toString());154 }155 }156 }157 }158 @When("^cookie ([^\\s]+) = (.+)")159 public void cookie(String name, String value) {160 ScriptValue sv = Script.evalKarateExpression(value, context);161 Cookie cookie;162 if (sv.isMapLike()) {163 cookie = new Cookie((Map) sv.getAsMap());164 cookie.put(Cookie.NAME, name);165 } else {166 cookie = new Cookie(name, sv.getAsString());167 }168 request.setCookie(cookie);169 }170 @When("^cookies (.+)")171 public void cookies(String expr) {172 Map<String, Object> map = evalMapExpr(expr);173 for (Map.Entry<String, Object> entry : map.entrySet()) {174 String key = entry.getKey();175 Object temp = entry.getValue();176 if (temp == null) {177 request.removeCookie(key);178 } else {179 request.setCookie(new Cookie(key, temp.toString()));180 }181 }182 }183 @When("^header ([^\\s]+) = (.+)")184 public void header(String name, List<String> values) {185 List<String> list = evalList(values);186 request.setHeader(name, list);187 }188 @When("^headers (.+)")189 public void headers(String expr) {190 Map<String, Object> map = evalMapExpr(expr);191 for (Map.Entry<String, Object> entry : map.entrySet()) {192 String key = entry.getKey();193 Object temp = entry.getValue();194 if (temp == null) {195 request.removeHeader(key);196 } else {197 if (temp instanceof List) {198 request.setHeader(key, (List) temp);199 } else {200 request.setHeader(key, temp.toString());201 }202 }203 }204 }205 @When("^form field ([^\\s]+) = (.+)")206 public void formField(String name, List<String> values) {207 List<String> list = evalList(values);208 request.setFormField(name, list);209 }210 @When("^form fields (.+)")211 public void formFields(String expr) {212 Map<String, Object> map = evalMapExpr(expr);213 for (Map.Entry<String, Object> entry : map.entrySet()) {214 String key = entry.getKey();215 Object temp = entry.getValue();216 if (temp == null) {217 request.removeFormField(key);218 } else {219 if (temp instanceof List) {220 request.setFormField(key, (List) temp);221 } else {222 request.setFormField(key, temp.toString());223 }224 }225 }226 }227 @When("^request$")228 public void requestDocString(String requestBody) {229 request(requestBody);230 }231 @When("^request (.+)")232 public void request(String requestBody) {233 ScriptValue temp = Script.evalKarateExpression(requestBody, context);234 request.setBody(temp);235 }236 @When("^table (.+)")237 public void table(String name, DataTable table) {238 int pos = name.indexOf('='); // backward compatibility, we used to require this till v0.5.0239 if (pos != -1) {240 name = name.substring(0, pos);241 }242 List<Map<String, Object>> list = table.asMaps(String.class, Object.class);243 list = Script.evalTable(list, context);244 DocumentContext doc = JsonPath.parse(list);245 context.vars.put(name.trim(), doc);246 }247 private String getVarAsString(String name) {248 ScriptValue sv = context.vars.get(name);249 if (sv == null) {250 throw new RuntimeException("no variable found with name: " + name);251 }252 return sv.getAsString();253 }254 @When("^replace (\\w+)$")255 public void replace(String name, DataTable table) {256 name = name.trim();257 String text = getVarAsString(name);258 List<Map<String, String>> list = table.asMaps(String.class, String.class);259 String replaced = Script.replacePlaceholders(text, list, context);260 context.vars.put(name, replaced);261 }262 @When("^replace (\\w+).([^\\s]+) = (.+)")263 public void replace(String name, String token, String value) {264 name = name.trim();265 String text = getVarAsString(name);266 String replaced = Script.replacePlaceholderText(text, token, value, context);267 context.vars.put(name, replaced);268 }269 270 @When("^def (.+) =$")271 public void defDocString(String name, String expression) {272 def(name, expression);273 }274 @When("^def (\\w+) = (.+)")275 public void def(String name, String expression) {276 Script.assign(name, expression, context, true);277 } 278 @When("^text (.+) =$")279 public void textDocString(String name, String expression) {280 Script.assignText(name, expression, context, true);281 }282 @When("^yaml (.+) =$")283 public void yamlDocString(String name, String expression) {284 Script.assignYaml(name, expression, context, true);285 }286 287 @When("^copy (.+) = (.+)")288 public void copy(String name, String expression) {289 Script.copy(name, expression, context, true);290 } 291 @When("^json (.+) = (.+)")292 public void castToJson(String name, String expression) {293 Script.assignJson(name, expression, context, true);294 }295 @When("^string (.+) = (.+)")296 public void castToString(String name, String expression) {297 Script.assignString(name, expression, context, true);298 }299 @When("^xml (.+) = (.+)")300 public void castToXml(String name, String expression) {301 Script.assignXml(name, expression, context, true);302 }303 @When("^xmlstring (.+) = (.+)")304 public void castToXmlString(String name, String expression) {305 Script.assignXmlString(name, expression, context, true);306 }307 @When("^assert (.+)")308 public void asssertBoolean(String expression) {309 try {310 AssertionResult ar = Script.assertBoolean(expression, context);311 handleFailure(ar);312 } catch (Exception e) {313 throw new KarateException(e.getMessage());314 }315 }316 @When("^method (\\w+)")317 public void method(String method) {318 if (!HttpUtils.HTTP_METHODS.contains(method.toUpperCase())) { // support expressions also319 method = Script.evalKarateExpression(method, context).getAsString();320 }321 request.setMethod(method);322 try {323 response = context.client.invoke(request, context);324 } catch (Exception e) {325 String message = e.getMessage();326 context.logger.error("http request failed: {}", message);327 throw new KarateException(message); // reduce log verbosity328 }329 HttpUtils.updateRequestVars(request, context.vars, context);330 HttpUtils.updateResponseVars(response, context.vars, context);331 String prevUrl = request.getUrl();332 request = new HttpRequestBuilder();333 request.setUrl(prevUrl);334 }335 @When("^soap action( .+)?")336 public void soapAction(String action) {337 action = Script.evalKarateExpression(action, context).getAsString();338 if (action == null) {339 action = "";340 }341 request.setHeader("SOAPAction", action);342 request.setHeader("Content-Type", "text/xml");343 method("post");344 }345 @When("^multipart entity (.+)")346 public void multiPartEntity(String value) {347 multiPart(null, value);348 }349 @When("^multipart field (.+) = (.+)")350 public void multiPartFormField(String name, String value) {351 multiPart(name, value);352 }353 354 @When("^multipart fields (.+)")355 public void multiPartFormFields(String expr) {356 Map<String, Object> map = evalMapExpr(expr);357 map.forEach((k, v)-> {358 ScriptValue sv = new ScriptValue(v);359 request.addMultiPartItem(k, sv); 360 });361 } 362 private static String asString(Map<String, Object> map, String key) {363 Object o = map.get(key);364 return o == null ? null : o.toString();365 }366 @When("^multipart file (.+) = (.+)")367 public void multiPartFile(String name, String value) {368 name = name.trim();369 ScriptValue sv = Script.evalKarateExpression(value, context);370 if (!sv.isMapLike()) {371 throw new RuntimeException("mutipart file value should be json");372 }373 Map<String, Object> map = sv.getAsMap();374 String read = asString(map, "read");375 if (read == null) {376 throw new RuntimeException("mutipart file json should have a value for 'read'");377 }378 ScriptValue fileValue = FileUtils.readFile(read, context);379 MultiPartItem item = new MultiPartItem(name, fileValue);380 String filename = asString(map, "filename");381 if (filename == null) {382 filename = name;383 }384 item.setFilename(filename);385 String contentType = asString(map, "contentType");386 if (contentType != null) {387 item.setContentType(contentType);388 }389 request.addMultiPartItem(item);390 }391 @When("^multipart files (.+)")392 public void multiPartFiles(String expr) {393 Map<String, Object> map = evalMapExpr(expr);394 map.forEach((k, v)-> {395 ScriptValue sv = new ScriptValue(v);396 multiPartFile(k, sv.getAsString()); 397 });398 }399 public void multiPart(String name, String value) {400 ScriptValue sv = Script.evalKarateExpression(value, context);401 request.addMultiPartItem(name, sv);402 }403 @When("^print (.+)")404 public void print(List<String> exps) {405 if (context.isPrintEnabled()) {406 String prev = ""; // handle rogue commas embedded in string literals407 StringBuilder sb = new StringBuilder();408 sb.append("[print]");409 for (String exp : exps) {410 if (!prev.isEmpty()) {411 exp = prev + exp;412 }413 exp = StringUtils.trimToNull(exp);414 if (exp == null) {415 sb.append("null");416 } else {417 ScriptValue sv = Script.getIfVariableReference(exp, context);418 if (sv == null) {419 try {420 sv = Script.evalJsExpression(exp, context);421 prev = ""; // evalKarateExpression success, reset rogue comma detector422 } catch (Exception e) {423 prev = exp + ", ";424 continue;425 }426 }427 sb.append(' ').append(sv.getAsPrettyString());428 }429 }430 context.logger.info("{}", sb);431 }432 }433 @When("^status (\\d+)")434 public void status(int status) {435 if (status != response.getStatus()) {436 String rawResponse = context.vars.get(ScriptValueMap.VAR_RESPONSE).getAsString();437 String responseTime = context.vars.get(ScriptValueMap.VAR_RESPONSE_TIME).getAsString();438 String message = "status code was: " + response.getStatus() + ", expected: " + status439 + ", response time: " + responseTime + ", url: " + response.getUri() + ", response: " + rawResponse;440 context.logger.error(message);441 throw new KarateException(message);442 }443 }444 private static MatchType toMatchType(String eqSymbol, String each, String notContains, String only, boolean contains) {445 boolean notEquals = eqSymbol.startsWith("!");446 if (each == null) {447 if (notContains != null) {448 return MatchType.NOT_CONTAINS;449 }450 if (only != null) {451 return only.contains("only") ? MatchType.CONTAINS_ONLY: MatchType.CONTAINS_ANY;...
Source:RegexValidator.java
...19 public ValidationResult validate(ScriptValue value) {20 if (!value.isStringOrStream()) {21 return ValidationResult.fail("not a string");22 }23 String strValue = value.getAsString();24 Matcher matcher = pattern.matcher(strValue);25 if (matcher.matches()) {26 return ValidationResult.PASS;27 }28 return ValidationResult.fail("regex match failed");29 }30 31}...
getAsString
Using AI Code Generation
1import com.intuit.karate.Match;2import com.intuit.karate.KarateOptions;3import com.intuit.karate.Runner;4import static org.junit.jupiter.api.Assertions.*;5import org.junit.jupiter.api.Test;6import java.util.HashMap;7import java.util.Map;8import java.util.List;9import java.util.ArrayList;10import java.util.Arrays;11import java.util.Collections;12import java.util.Comparator;13import java.util.Iterator;14import java.util.LinkedHashMap;15import java.util.Map;16import java.util.Set;17import java.util.TreeSet;18import java.util.regex.Matcher;19import java.util.regex.Pattern;20import java.util.stream.Collectors;21import java.util.stream.Stream;22import org.apache.commons.lang3.StringUtils;23import org.apache
getAsString
Using AI Code Generation
1import com.intuit.karate.junit5.Karate;2class MyRunner {3Karate testAll() {4 return Karate.run().relativeTo(getClass());5}6}7import com.intuit.karate.junit5.Karate;8class MyRunner {9Karate testAll() {10 return Karate.run().relativeTo(getClass());11}12}13import com.intuit.karate.junit5.Karate;14class MyRunner {15Karate testAll() {16 return Karate.run().relativeTo(getClass());17}18}19import com.intuit.karate.junit5.Karate;20class MyRunner {21Karate testAll() {22 return Karate.run().relativeTo(getClass());23}24}25import com.intuit.karate.junit5.Karate;26class MyRunner {27Karate testAll() {28 return Karate.run().relativeTo(getClass());29}30}31import com.intuit.karate.junit5.Karate;32class MyRunner {33Karate testAll() {34 return Karate.run().relativeTo(getClass());35}36}37import com.intuit.karate.junit5.Karate;38class MyRunner {39Karate testAll() {40 return Karate.run().relativeTo(getClass());41}42}43import com.intuit.karate.junit5.Karate;44class MyRunner {45Karate testAll() {46 return Karate.run().relativeTo(getClass());47}48}
getAsString
Using AI Code Generation
1package com.intuit.karate.demo;2import com.intuit.karate.Match;3import java.util.List;4import java.util.Map;5import org.junit.Test;6public class DemoTest {7 public void testDemo() {8 String json = "{ \"id\": 1, \"name\": \"John\", \"age\": 30, \"cars\": [\"Ford\", \"BMW\", \"Fiat\"] }";9 Match match = Match.of(json);10 int id = match.get("id").getAsInt();11 String name = match.get("name").getAsString();12 int age = match.get("age").getAsInt();13 List<String> cars = match.get("cars").getAsList();14 Map<String, Object> map = match.get().getAsMap();15 System.out.println("id: " + id);16 System.out.println("name: " + name);17 System.out.println("age: " + age);18 System.out.println("cars: " + cars);19 System.out.println("map: " + map);20 }21}22map: {id=1, name=John, age=30, cars=[Ford, BMW, Fiat]}23package com.intuit.karate.demo;24import com.intuit.karate.Match;25import java.util.List;26import java.util.Map;27import org.junit.Test;28public class DemoTest {29 public void testDemo() {30 String json = "{ \"id\": 1, \"name\": \"John\", \"age\": 30, \"cars\": [\"Ford\", \"BMW\", \"Fiat\"] }";31 Match match = Match.of(json);32 int id = match.get("id").getAsInt();33 String name = match.get("name").getAsString();34 int age = match.get("age").getAsInt();35 List<String> cars = match.get("cars").getAsList();36 Map<String, Object> map = match.get().getAsMap();37 System.out.println("id: " + id);38 System.out.println("name: " + name);39 System.out.println("age: " + age);40 System.out.println("cars: " + cars);
getAsString
Using AI Code Generation
1import com.intuit.karate.Match;2import com.intuit.karate.MatchType;3public class 4 {4 public static void main(String[] args) {5 Match match = new Match("123", MatchType.EQUALS);6 System.out.println(match.getAsString());7 }8}9import com.intuit.karate.Match;10import com.intuit.karate.MatchType;11public class 5 {12 public static void main(String[] args) {13 Match match = new Match("123", MatchType.EQUALS);14 System.out.println(match.getAsString());15 }16}17import com.intuit.karate.Match;18import com.intuit.karate.MatchType;19public class 6 {20 public static void main(String[] args) {21 Match match = new Match("123", MatchType.EQUALS);22 System.out.println(match.getAsString());23 }24}25import com.intuit.karate.Match;26import com.intuit.karate.MatchType;27public class 7 {28 public static void main(String[] args) {29 Match match = new Match("123", MatchType.EQUALS);30 System.out.println(match.getAsString());31 }32}33import com.intuit.karate.Match;34import com.intuit.karate.MatchType;35public class 8 {36 public static void main(String[] args) {37 Match match = new Match("123", MatchType.EQUALS);38 System.out.println(match.getAsString());39 }40}41import com.intuit.karate.Match;42import com.intuit.karate.MatchType;43public class 9 {44 public static void main(String[] args) {45 Match match = new Match("123",
getAsString
Using AI Code Generation
1import com.intuit.karate.Match;2import com.intuit.karate.FileUtils;3import com.intuit.karate.JsonUtils;4import java.util.Map;5String json = FileUtils.toString(new File('test.json'));6Match match = JsonUtils.toJsonDoc(json).read('$');7System.out.println(match.getAsString());8import com.intuit.karate.Match;9import com.intuit.karate.FileUtils;10import com.intuit.karate.JsonUtils;11import java.util.Map;12String json = FileUtils.toString(new File('test.json'));13Match match = JsonUtils.toJsonDoc(json).read('$');14System.out.println(match.getAsString());15import com.intuit.karate.Match;16import com.intuit.karate.FileUtils;17import com.intuit.karate.JsonUtils;18import java.util.Map;19String json = FileUtils.toString(new File('test.json'));20Match match = JsonUtils.toJsonDoc(json).read('$');21System.out.println(match.getAsString());22import com.intuit.karate.Match;23import com.intuit.karate.FileUtils;24import com.intuit.karate.JsonUtils;25import java.util.Map;26String json = FileUtils.toString(new File('test.json'));27Match match = JsonUtils.toJsonDoc(json).read('$');28System.out.println(match.getAsString());29import com.intuit.karate.Match;30import com.intuit.karate.FileUtils;31import com.intuit.karate.JsonUtils;32import java.util.Map;33String json = FileUtils.toString(new File
getAsString
Using AI Code Generation
1import com.intuit.karate.Match;2Match match = Match.of("foo");3match.getAsString()4import com.intuit.karate.Match;5Match match = Match.of("foo");6match.getAsMap()7import com.intuit.karate.Match;8Match match = Match.of("foo");9match.getAsList()10import com.intuit.karate.Match;11Match match = Match.of("foo");12match.getAsNumber()13import com.intuit.karate.Match;14Match match = Match.of("foo");15match.getAsBoolean()16import com.intuit.karate.Match;17Match match = Match.of("foo");18match.getAsByteArray()19import com.intuit.karate.Match;20Match match = Match.of("foo");21match.getAsJson()22import com.intuit.karate.Match;23Match match = Match.of("foo");24match.getAsXml()25import com.intuit.karate.Match;26Match match = Match.of("foo");27match.getAsXmlDocument()
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!