How to use getAsString method of com.intuit.karate.core.Embed class

Best Karate code snippet using com.intuit.karate.core.Embed.getAsString

Source:ScenarioContext.java Github

copy

Full Screen

...317 List<String> list = new ArrayList(values.size());318 try {319 for (String value : values) {320 ScriptValue temp = Script.evalKarateExpression(value, this);321 list.add(temp.getAsString());322 }323 } catch (Exception e) { // hack. for e.g. json with commas would land here324 String joined = StringUtils.join(values, ',');325 ScriptValue temp = Script.evalKarateExpression(joined, this);326 if (temp.isListLike()) {327 return temp.getAsList();328 } else {329 return Collections.singletonList(temp.getAsString());330 }331 }332 return list;333 }334 private Map<String, Object> evalMapExpr(String expr) {335 ScriptValue value = Script.evalKarateExpression(expr, this);336 if (!value.isMapLike()) {337 throw new KarateException("cannot convert to map: " + expr);338 }339 return value.getAsMap();340 }341 private String getVarAsString(String name) {342 ScriptValue sv = vars.get(name);343 if (sv == null) {344 throw new RuntimeException("no variable found with name: " + name);345 }346 return sv.getAsString();347 }348 private static String asString(Map<String, Object> map, String key) {349 Object o = map.get(key);350 return o == null ? null : o.toString();351 }352 public void updateResponseVars() {353 vars.put(ScriptValueMap.VAR_RESPONSE_STATUS, prevResponse.getStatus());354 vars.put(ScriptValueMap.VAR_REQUEST_TIME_STAMP, prevResponse.getStartTime());355 vars.put(ScriptValueMap.VAR_RESPONSE_TIME, prevResponse.getResponseTime());356 vars.put(ScriptValueMap.VAR_RESPONSE_COOKIES, prevResponse.getCookies());357 if (config.isLowerCaseResponseHeaders()) {358 Object temp = new ScriptValue(prevResponse.getHeaders()).toLowerCase();359 vars.put(ScriptValueMap.VAR_RESPONSE_HEADERS, temp);360 } else {361 vars.put(ScriptValueMap.VAR_RESPONSE_HEADERS, prevResponse.getHeaders());362 }363 byte[] responseBytes = prevResponse.getBody();364 bindings.putAdditionalVariable(ScriptValueMap.VAR_RESPONSE_BYTES, responseBytes);365 String responseString = FileUtils.toString(responseBytes);366 Object responseBody = responseString;367 responseString = StringUtils.trimToEmpty(responseString);368 if (Script.isJson(responseString)) {369 try {370 responseBody = JsonUtils.toJsonDoc(responseString);371 } catch (Exception e) {372 logger.warn("json parsing failed, response data type set to string: {}", e.getMessage());373 }374 } else if (Script.isXml(responseString)) {375 try {376 responseBody = XmlUtils.toXmlDoc(responseString);377 } catch (Exception e) {378 logger.warn("xml parsing failed, response data type set to string: {}", e.getMessage());379 }380 }381 vars.put(ScriptValueMap.VAR_RESPONSE, responseBody);382 }383 public void invokeAfterHookIfConfigured(boolean afterFeature) {384 if (callDepth > 0) {385 return;386 }387 ScriptValue sv = afterFeature ? config.getAfterFeature() : config.getAfterScenario();388 if (sv.isFunction()) {389 try {390 sv.invokeFunction(this, null);391 } catch (Exception e) {392 String prefix = afterFeature ? "afterFeature" : "afterScenario";393 logger.warn("{} hook failed: {}", prefix, e.getMessage());394 }395 }396 }397 //==========================================================================398 //399 public void configure(String key, String exp) {400 configure(key, Script.evalKarateExpression(exp, this));401 }402 public void url(String expression) {403 String temp = Script.evalKarateExpression(expression, this).getAsString();404 request.setUrl(temp);405 }406 public void path(List<String> paths) {407 for (String path : paths) {408 ScriptValue temp = Script.evalKarateExpression(path, this);409 if (temp.isListLike()) {410 List list = temp.getAsList();411 for (Object o : list) {412 if (o == null) {413 continue;414 }415 request.addPath(o.toString());416 }417 } else {418 request.addPath(temp.getAsString());419 }420 }421 }422 public void param(String name, List<String> values) {423 request.setParam(name, evalList(values));424 }425 public void params(String expr) {426 Map<String, Object> map = evalMapExpr(expr);427 for (Map.Entry<String, Object> entry : map.entrySet()) {428 String key = entry.getKey();429 Object temp = entry.getValue();430 if (temp == null) {431 request.removeParam(key);432 } else {433 if (temp instanceof List) {434 request.setParam(key, (List) temp);435 } else {436 request.setParam(key, temp.toString());437 }438 }439 }440 }441 public void cookie(String name, String value) {442 ScriptValue sv = Script.evalKarateExpression(value, this);443 Cookie cookie;444 if (sv.isMapLike()) {445 cookie = new Cookie((Map) sv.getAsMap());446 cookie.put(Cookie.NAME, name);447 } else {448 cookie = new Cookie(name, sv.getAsString());449 }450 request.setCookie(cookie);451 }452 public void cookies(String expr) {453 Map<String, Object> map = evalMapExpr(expr);454 for (Map.Entry<String, Object> entry : map.entrySet()) {455 String key = entry.getKey();456 Object temp = entry.getValue();457 if (temp == null) {458 request.removeCookie(key);459 } else {460 request.setCookie(new Cookie(key, temp.toString()));461 }462 }463 }464 public void header(String name, List<String> values) {465 request.setHeader(name, evalList(values));466 }467 public void headers(String expr) {468 Map<String, Object> map = evalMapExpr(expr);469 for (Map.Entry<String, Object> entry : map.entrySet()) {470 String key = entry.getKey();471 Object temp = entry.getValue();472 if (temp == null) {473 request.removeHeader(key);474 } else {475 if (temp instanceof List) {476 request.setHeader(key, (List) temp);477 } else {478 request.setHeader(key, temp.toString());479 }480 }481 }482 }483 public void formField(String name, List<String> values) {484 request.setFormField(name, evalList(values));485 }486 public void formFields(String expr) {487 Map<String, Object> map = evalMapExpr(expr);488 for (Map.Entry<String, Object> entry : map.entrySet()) {489 String key = entry.getKey();490 Object temp = entry.getValue();491 if (temp == null) {492 request.removeFormField(key);493 } else {494 if (temp instanceof List) {495 request.setFormField(key, (List) temp);496 } else {497 request.setFormField(key, temp.toString());498 }499 }500 }501 }502 public void request(ScriptValue body) {503 request.setBody(body);504 }505 public void request(String requestBody) {506 ScriptValue temp = Script.evalKarateExpression(requestBody, this);507 request(temp);508 }509 public void table(String name, List<Map<String, String>> table) {510 int pos = name.indexOf('='); // backward compatibility, we used to require this till v0.5.0511 if (pos != -1) {512 name = name.substring(0, pos);513 }514 List<Map<String, Object>> list = Script.evalTable(table, this);515 DocumentContext doc = JsonPath.parse(list);516 vars.put(name.trim(), doc);517 }518 public void replace(String name, List<Map<String, String>> table) {519 name = name.trim();520 String text = getVarAsString(name);521 String replaced = Script.replacePlaceholders(text, table, this);522 vars.put(name, replaced);523 }524 public void replace(String name, String token, String value) {525 name = name.trim();526 String text = getVarAsString(name);527 String replaced = Script.replacePlaceholderText(text, token, value, this);528 vars.put(name, replaced);529 }530 public void assign(AssignType assignType, String name, String exp) {531 Script.assign(assignType, name, exp, this, true);532 }533 public void assertTrue(String expression) {534 AssertionResult ar = Script.assertBoolean(expression, this);535 if (!ar.pass) {536 logger.error("{}", ar);537 throw new KarateException(ar.message);538 }539 }540 private void clientInvoke() {541 try {542 prevResponse = client.invoke(request, this);543 updateResponseVars();544 } catch (Exception e) {545 String message = e.getMessage();546 logger.error("http request failed: {}", message);547 throw new KarateException(message); // reduce log verbosity548 }549 }550 private void clientInvokeWithRetries() {551 int maxRetries = config.getRetryCount();552 int sleep = config.getRetryInterval();553 int retryCount = 0;554 while (true) {555 if (retryCount == maxRetries) {556 throw new KarateException("too many retry attempts: " + maxRetries);557 }558 if (retryCount > 0) {559 try {560 logger.debug("sleeping before retry #{}", retryCount);561 Thread.sleep(sleep);562 } catch (Exception e) {563 throw new RuntimeException(e);564 }565 }566 clientInvoke();567 ScriptValue sv;568 try {569 sv = Script.evalKarateExpression(request.getRetryUntil(), this);570 } catch (Exception e) {571 logger.warn("retry condition evaluation failed: {}", e.getMessage());572 sv = ScriptValue.NULL;573 }574 if (sv.isBooleanTrue()) {575 if (retryCount > 0) {576 logger.debug("retry condition satisfied");577 }578 break;579 } else {580 logger.debug("retry condition not satisfied: {}", request.getRetryUntil());581 }582 retryCount++;583 }584 }585 public void method(String method) {586 if (!HttpUtils.HTTP_METHODS.contains(method.toUpperCase())) { // support expressions also587 method = Script.evalKarateExpression(method, this).getAsString();588 }589 request.setMethod(method);590 if (request.isRetry()) {591 clientInvokeWithRetries();592 } else {593 clientInvoke();594 }595 String prevUrl = request.getUrl();596 request = new HttpRequestBuilder();597 request.setUrl(prevUrl);598 }599 public void retry(String expression) {600 request.setRetryUntil(expression);601 }602 public void soapAction(String action) {603 action = Script.evalKarateExpression(action, this).getAsString();604 if (action == null) {605 action = "";606 }607 request.setHeader("SOAPAction", action);608 request.setHeader("Content-Type", "text/xml");609 method("post");610 }611 public void multipartField(String name, String value) {612 ScriptValue sv = Script.evalKarateExpression(value, this);613 request.addMultiPartItem(name, sv);614 }615 public void multipartFields(String expr) {616 Map<String, Object> map = evalMapExpr(expr);617 map.forEach((k, v) -> {618 ScriptValue sv = new ScriptValue(v);619 request.addMultiPartItem(k, sv);620 });621 }622 public void multipartFile(String name, String value) {623 name = name.trim();624 ScriptValue sv = Script.evalKarateExpression(value, this);625 if (!sv.isMapLike()) {626 throw new RuntimeException("mutipart file value should be json");627 }628 ScriptValue fileValue;629 Map<String, Object> map = sv.getAsMap();630 String read = asString(map, "read");631 if (read == null) {632 Object o = map.get("value");633 fileValue = o == null ? null : new ScriptValue(o);634 } else {635 fileValue = FileUtils.readFile(read, this);636 }637 if (fileValue == null) {638 throw new RuntimeException("mutipart file json should have a value for 'read' or 'value'");639 }640 MultiPartItem item = new MultiPartItem(name, fileValue);641 String filename = asString(map, "filename");642 if (filename == null) {643 filename = name;644 }645 item.setFilename(filename);646 String contentType = asString(map, "contentType");647 if (contentType != null) {648 item.setContentType(contentType);649 }650 request.addMultiPartItem(item);651 }652 public void multipartFiles(String expr) {653 Map<String, Object> map = evalMapExpr(expr);654 map.forEach((k, v) -> {655 ScriptValue sv = new ScriptValue(v);656 multipartFile(k, sv.getAsString());657 });658 }659 public void print(List<String> exps) {660 if (isPrintEnabled()) {661 String prev = ""; // handle rogue commas embedded in string literals662 StringBuilder sb = new StringBuilder();663 sb.append("[print]");664 for (String exp : exps) {665 if (!prev.isEmpty()) {666 exp = prev + StringUtils.trimToNull(exp);667 }668 if (exp == null) {669 sb.append("null");670 } else {671 ScriptValue sv = Script.getIfVariableReference(exp, this);672 if (sv == null) {673 try {674 sv = Script.evalJsExpression(exp, this);675 prev = ""; // evalKarateExpression success, reset rogue comma detector676 } catch (Exception e) {677 prev = exp + ", ";678 continue;679 }680 }681 sb.append(' ').append(sv.getAsPrettyString());682 }683 }684 logger.info("{}", sb);685 }686 }687 public void status(int status) {688 if (status != prevResponse.getStatus()) {689 String rawResponse = vars.get(ScriptValueMap.VAR_RESPONSE).getAsString();690 String responseTime = vars.get(ScriptValueMap.VAR_RESPONSE_TIME).getAsString();691 String message = "status code was: " + prevResponse.getStatus() + ", expected: " + status692 + ", response time: " + responseTime + ", url: " + prevResponse.getUri() + ", response: " + rawResponse;693 logger.error(message);694 throw new KarateException(message);695 }696 }697 public void match(MatchType matchType, String name, String path, String expected) {698 AssertionResult ar = Script.matchNamed(matchType, name, path, expected, this);699 if (!ar.pass) {700 logger.error("{}", ar);701 throw new KarateException(ar.message);702 }703 }704 public void set(String name, String path, String value) {705 Script.setValueByPath(name, path, value, this);706 }707 public void set(String name, String path, List<Map<String, String>> table) {708 Script.setByPathTable(name, path, table, this);709 }710 public void remove(String name, String path) {711 Script.removeValueByPath(name, path, this);712 }713 public void call(boolean callonce, String name, String arg) {714 Script.callAndUpdateConfigAndAlsoVarsIfMapReturned(callonce, name, arg, this);715 }716 public void eval(String exp) {717 Script.evalJsExpression(exp, this);718 }719 public Embed getAndClearEmbed() {720 Embed temp = prevEmbed;721 prevEmbed = null;722 return temp;723 }724 public void embed(byte[] bytes, String contentType) {725 Embed embed = new Embed();726 embed.setBytes(bytes);727 embed.setMimeType(contentType);728 prevEmbed = embed;729 }730 public WebSocketClient webSocket(WebSocketOptions options) {731 WebSocketClient webSocketClient = new WebSocketClient(options);732 if (webSocketClients == null) {733 webSocketClients = new ArrayList();734 }735 webSocketClients.add(webSocketClient);736 return webSocketClient;737 }738 public void signal(Object result) {739 logger.trace("signal called: {}", result);740 synchronized (LOCK) {741 signalResult = result;742 LOCK.notify();743 }744 }745 public Object listen(long timeout, Runnable runnable) {746 if (runnable != null) {747 logger.trace("submitting listen function");748 new Thread(runnable).start();749 }750 synchronized (LOCK) {751 if (signalResult != null) {752 logger.debug("signal arrived early ! result: {}", signalResult);753 Object temp = signalResult;754 signalResult = null;755 return temp;756 }757 try {758 logger.trace("entered listen wait state");759 LOCK.wait(timeout);760 logger.trace("exit listen wait state, result: {}", signalResult);761 } catch (InterruptedException e) {762 logger.error("listen timed out: {}", e.getMessage());763 }764 Object temp = signalResult;765 signalResult = null;766 return temp;767 }768 }769 // driver ================================================================== 770 //771 private void setDriver(Driver driver) {772 this.driver = driver;773 bindings.putAdditionalVariable(ScriptBindings.DRIVER, driver);774 }775 public void driver(String expression) {776 ScriptValue sv = Script.evalKarateExpression(expression, this);777 if (driver == null) {778 Map<String, Object> options = config.getDriverOptions();779 if (options == null) {780 options = new HashMap();781 }782 if (sv.isMapLike()) {783 options.putAll(sv.getAsMap());784 }785 setDriver(DriverOptions.start(this, options, logger));786 }787 if (sv.isString()) {788 driver.setLocation(sv.getAsString());789 }790 }791 public void stop() {792 if (reuseParentContext) {793 if (driver != null) {794 parentContext.setDriver(driver);795 }796 parentContext.webSocketClients = webSocketClients;797 return;798 }799 if (webSocketClients != null) {800 webSocketClients.forEach(WebSocketClient::close);801 }802 if (driver != null) {...

Full Screen

Full Screen

getAsString

Using AI Code Generation

copy

Full Screen

1* def myEmbed = { "foo": "bar" }2* def embed = com.intuit.karate.core.Embed('application/json', myEmbed, 'myEmbed')3* embed.getAsString() == '{"foo":"bar"}'4* def embed2 = com.intuit.karate.core.Embed('application/json', myEmbed, 'myEmbed')5* embed2.getAsString() == '{"foo":"bar"}'6* def embed3 = com.intuit.karate.core.Embed('application/json', myEmbed, 'myEmbed')7* embed3.getAsString() == '{"foo":"bar"}'8* def embed4 = com.intuit.karate.core.Embed('application/json', myEmbed, 'myEmbed')9* embed4.getAsString() == '{"foo":"bar"}'10* def embed5 = com.intuit.karate.core.Embed('application/json', myEmbed, 'myEmbed')11* embed5.getAsString() == '{"foo":"bar"}'12* def embed6 = com.intuit.karate.core.Embed('application/json', myEmbed, 'myEmbed')13* embed6.getAsString() == '{"foo":"bar"}'14* def embed7 = com.intuit.karate.core.Embed('application/json', myEmbed, 'myEmbed')15* embed7.getAsString() == '{"foo":"bar"}'16* def embed8 = com.intuit.karate.core.Embed('application/json', myEmbed, 'myEmbed')17* embed8.getAsString() == '{"foo":"bar"}'18* def embed9 = com.intuit.karate.core.Embed('application/json', myEmbed, 'myEmbed')19* embed9.getAsString() == '{"foo":"bar"}'20* def embed10 = com.intuit.karate.core.Embed('application/json', myEmbed, 'myEmbed')21* embed10.getAsString() == '{"foo":"bar"}'22* def embed11 = com.intuit.karate.core.Embed('application/json', myEmbed, 'myEmbed')23* embed11.getAsString() == '{"foo":"bar"}'24* def embed12 = com.intuit.karate.core.Embed('application/json', myEmbed, 'myEmbed')25* embed12.getAsString() == '{"foo":"bar"}'26* def embed13 = com.intuit.karate.core.Embed('application/json', myEmbed, 'myEmbed')27* embed13.getAsString() == '{"foo":"bar"}'

Full Screen

Full Screen

getAsString

Using AI Code Generation

copy

Full Screen

1def embed = new com.intuit.karate.core.Embed('text/html', html)2embed.getAsString()3def embed = new com.intuit.karate.core.Embed('text/html', html)4embed.getAsBytes()5def embed = new com.intuit.karate.core.Embed('text/html', html)6embed.getAsString()7def embed = new com.intuit.karate.core.Embed('text/html', html)8embed.getAsBytes()

Full Screen

Full Screen

getAsString

Using AI Code Generation

copy

Full Screen

1def response = call read('classpath:hello.feature')2def text = embed.getAsString()3* def response = call read('classpath:hello.feature')4* def text = embed.getAsString()5def response = call read('classpath:hello.feature')6def bytes = embed.getAsBytes()7* def response = call read('classpath:hello.feature')8* def bytes = embed.getAsBytes()9def response = call read('classpath:hello.feature')10def inputStream = embed.getAsInputStream()11assert inputStream.readAllBytes() == [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]12* def response = call read('classpath:hello.feature')13* def inputStream = embed.getAsInputStream()14* assert inputStream.readAllBytes() == [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]15def response = call read('classpath:hello.feature')16def reader = embed.getAsReader()17assert reader.readAll() == 'hello world'18* def response = call read('classpath:hello.feature')19* def reader = embed.getAsReader()20* assert reader.readAll() == 'hello world'

Full Screen

Full Screen

getAsString

Using AI Code Generation

copy

Full Screen

1for (int i = 0; i < $karate.embeds.length; i++) {2 if (embed.type == 'text/html') {3 html += '<tr><td>' + embed.name + '</td><td>' + embed.getAsString() + '</td></tr>'4 }5}6$karate.write(html, 'target/my-report.html')7for (int i = 0; i < $karate.embeds.length; i++) {8 if (embed.type == 'text/html' && embed.name == 'HTML Report') {9 html += '<tr><td>' + embed.name + '</td><td>' + embed.getAsString() + '</td></tr>'10 }11}12$karate.write(html, 'target/my-report.html')

Full Screen

Full Screen

getAsString

Using AI Code Generation

copy

Full Screen

1def image = read('classpath:karate-logo.png')2def imageAsString = image.getAsString()3def imageAsString = image.getAsString('png')4def image = read('classpath:karate-logo.png')5def imageAsBytes = image.getAsBytes()6def imageAsBytes = image.getAsBytes('png')7def image = read('classpath:karate-logo.png')8def imageAsBase64 = image.getAsBase64()9def imageAsBase64 = image.getAsBase64('png')10def image = read('classpath:karate-logo.png')11def imageAsHtml = image.getAsHtml()12def imageAsHtml = image.getAsHtml('png')13def image = read('classpath:karate-logo.png')14def imageAsUri = image.getAsUri()15def imageAsUri = image.getAsUri('png')16def image = read('classpath:karate-logo.png')17def imageAsBase64 = image.getAsBase64()18def imageAsBase64 = image.getAsBase64('png')19def image = read('classpath:karate-logo.png')20def imageAsHtml = image.getAsHtml()21def imageAsHtml = image.getAsHtml('png')22def image = read('classpath:karate-logo.png')23def imageAsUri = image.getAsUri()24def imageAsUri = image.getAsUri('png')

Full Screen

Full Screen

getAsString

Using AI Code Generation

copy

Full Screen

1* def js = read('classpath:js/getAsString.js')2* def result = js.getAsString('<div>karate</div>')3function getAsString(input) {4 var embed = Java.type('com.intuit.karate.core.Embed')5 return embed.getAsString(input)6}

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful