How to use WebSocketClient class of com.intuit.karate.http package

Best Karate code snippet using com.intuit.karate.http.WebSocketClient

Source:ScenarioContext.java Github

copy

Full Screen

...45import com.intuit.karate.http.HttpUtils;46import com.intuit.karate.http.MultiPartItem;47import com.intuit.karate.driver.Driver;48import com.intuit.karate.driver.DriverOptions;49import com.intuit.karate.netty.WebSocketClient;50import com.intuit.karate.netty.WebSocketOptions;51import com.jayway.jsonpath.DocumentContext;52import com.jayway.jsonpath.JsonPath;53import java.util.ArrayList;54import java.util.Collection;55import java.util.Collections;56import java.util.HashMap;57import java.util.List;58import java.util.Map;59import java.util.function.Function;60/**61 *62 * @author pthomas363 */64public class ScenarioContext {65 public final Logger logger;66 public final ScriptBindings bindings;67 public final int callDepth;68 public final boolean reuseParentContext;69 public final ScenarioContext parentContext;70 public final List<String> tags;71 public final Map<String, List<String>> tagValues;72 public final ScriptValueMap vars;73 public final FeatureContext rootFeatureContext;74 public final FeatureContext featureContext;75 public final Collection<ExecutionHook> executionHooks;76 public final boolean perfMode;77 public final ScenarioInfo scenarioInfo;78 public final Function<String, Object> read = s -> {79 ScriptValue sv = FileUtils.readFile(s, this);80 if (sv.isXml()) {81 return sv.getValue();82 } else { // json should behave like json within js / function83 return sv.getAfterConvertingFromJsonOrXmlIfNeeded();84 }85 };86 // these can get re-built or swapped, so cannot be final87 private Config config;88 private HttpClient client;89 private Driver driver;90 private HttpRequestBuilder request = new HttpRequestBuilder();91 // the actual http request/response last sent on the wire 92 private HttpRequest prevRequest;93 private HttpResponse prevResponse;94 // pass call result to engine via this variable (hack)95 private List<FeatureResult> callResults;96 // gatling integration 97 private PerfEvent prevPerfEvent;98 // report embed99 protected Embed prevEmbed;100 // ui support101 private Function<CallContext, FeatureResult> callable;102 // async103 private final Object LOCK = new Object();104 private Object signalResult;105 // websocket 106 private List<WebSocketClient> webSocketClients;107 public void logLastPerfEvent(String failureMessage) {108 if (prevPerfEvent != null && executionHooks != null) {109 if (failureMessage != null) {110 prevPerfEvent.setFailed(true);111 prevPerfEvent.setMessage(failureMessage);112 }113 executionHooks.forEach(h -> h.reportPerfEvent(prevPerfEvent));114 }115 prevPerfEvent = null;116 }117 public void capturePerfEvent(PerfEvent event) {118 logLastPerfEvent(null);119 prevPerfEvent = event;120 }121 public List<FeatureResult> getAndClearCallResults() {122 List<FeatureResult> temp = callResults;123 callResults = null;124 return temp;125 }126 public void addCallResult(FeatureResult callResult) {127 if (callResults == null) {128 callResults = new ArrayList();129 }130 callResults.add(callResult);131 }132 public void setScenarioError(Throwable error) {133 scenarioInfo.setErrorMessage(error.getMessage());134 }135 public void setPrevRequest(HttpRequest prevRequest) {136 this.prevRequest = prevRequest;137 }138 public void setPrevResponse(HttpResponse prevResponse) {139 this.prevResponse = prevResponse;140 }141 public HttpRequestBuilder getRequest() {142 return request;143 }144 public HttpRequest getPrevRequest() {145 return prevRequest;146 }147 public HttpClient getHttpClient() {148 return client;149 }150 public int getCallDepth() {151 return callDepth;152 }153 public FeatureContext getFeatureContext() {154 return featureContext;155 }156 public Config getConfig() {157 return config;158 }159 public void setCallable(Function<CallContext, FeatureResult> callable) {160 this.callable = callable;161 }162 public Function<CallContext, FeatureResult> getCallable() {163 return callable;164 }165 public void updateConfigCookies(Map<String, Cookie> cookies) {166 if (cookies == null) {167 return;168 }169 if (config.getCookies().isNull()) {170 config.setCookies(new ScriptValue(cookies));171 } else {172 Map<String, Object> map = config.getCookies().evalAsMap(this);173 map.putAll(cookies);174 config.setCookies(new ScriptValue(map));175 }176 }177 public boolean isPrintEnabled() {178 return config.isPrintEnabled();179 }180 public ScenarioContext(FeatureContext featureContext, CallContext call, Scenario scenario, Logger logger) {181 this.featureContext = featureContext;182 if (logger == null) { // ensure this.logger is set properly183 logger = new Logger();184 }185 this.logger = logger;186 callDepth = call.callDepth;187 reuseParentContext = call.reuseParentContext;188 executionHooks = call.executionHooks;189 perfMode = call.perfMode;190 if (scenario != null) {191 Tags tagsEffective = scenario.getTagsEffective();192 tags = tagsEffective.getTags();193 tagValues = tagsEffective.getTagValues();194 scenarioInfo = scenario.toInfo(featureContext.feature.getPath());195 } else {196 tags = null;197 tagValues = null;198 scenarioInfo = null;199 }200 if (reuseParentContext) {201 parentContext = call.context;202 vars = call.context.vars; // shared context !203 config = call.context.config;204 rootFeatureContext = call.context.rootFeatureContext;205 driver = call.context.driver;206 webSocketClients = call.context.webSocketClients;207 } else if (call.context != null) {208 parentContext = call.context;209 // complex objects like JSON and XML are "global by reference" TODO 210 vars = call.context.vars.copy(false);211 config = new Config(call.context.config);212 rootFeatureContext = call.context.rootFeatureContext;213 } else {214 parentContext = null;215 vars = new ScriptValueMap();216 config = new Config();217 config.setClientClass(call.httpClientClass);218 rootFeatureContext = featureContext;219 }220 client = HttpClient.construct(config, this);221 bindings = new ScriptBindings(this);222 if (call.context == null && call.evalKarateConfig) {223 // base config is only looked for in the classpath224 try {225 Script.callAndUpdateConfigAndAlsoVarsIfMapReturned(false, ScriptBindings.READ_KARATE_CONFIG_BASE, null, this);226 } catch (Exception e) {227 if (e instanceof KarateFileNotFoundException) {228 logger.trace("skipping 'classpath:karate-base.js': {}", e.getMessage());229 } else {230 throw new RuntimeException("evaluation of 'classpath:karate-base.js' failed", e);231 }232 }233 String configDir = System.getProperty(ScriptBindings.KARATE_CONFIG_DIR);234 String configScript = ScriptBindings.readKarateConfigForEnv(true, configDir, null);235 try {236 Script.callAndUpdateConfigAndAlsoVarsIfMapReturned(false, configScript, null, this);237 } catch (Exception e) {238 if (e instanceof KarateFileNotFoundException) {239 logger.warn("skipping bootstrap configuration: {}", e.getMessage());240 } else {241 String message = "evaluation of 'karate-config.js' failed: " + e.getMessage();242 logger.error("{}", message);243 throw new RuntimeException(message, e);244 }245 }246 if (featureContext.env != null) {247 configScript = ScriptBindings.readKarateConfigForEnv(false, configDir, featureContext.env);248 try {249 Script.callAndUpdateConfigAndAlsoVarsIfMapReturned(false, configScript, null, this);250 } catch (Exception e) {251 if (e instanceof KarateFileNotFoundException) {252 logger.trace("skipping bootstrap configuration for env: {} - {}", featureContext.env, e.getMessage());253 } else {254 throw new RuntimeException("evaluation of 'karate-config-" + featureContext.env + ".js' failed", e);255 }256 }257 }258 }259 if (call.callArg != null) { // if call.reuseParentContext is true, arg will clobber parent context260 call.callArg.forEach((k, v) -> vars.put(k, v));261 vars.put(Script.VAR_ARG, call.callArg);262 vars.put(Script.VAR_LOOP, call.loopIndex);263 } else if (call.context != null) {264 vars.put(Script.VAR_ARG, ScriptValue.NULL);265 vars.put(Script.VAR_LOOP, -1);266 }267 logger.trace("karate context init - initial properties: {}", vars);268 }269 public ScenarioContext copy(ScenarioInfo info, Logger logger) {270 return new ScenarioContext(this, info, logger);271 }272 public ScenarioContext copy() {273 return new ScenarioContext(this, scenarioInfo, logger);274 }275 private ScenarioContext(ScenarioContext sc, ScenarioInfo info, Logger logger) {276 featureContext = sc.featureContext;277 this.logger = logger;278 callDepth = sc.callDepth;279 reuseParentContext = sc.reuseParentContext;280 parentContext = sc.parentContext;281 executionHooks = sc.executionHooks;282 perfMode = sc.perfMode;283 tags = sc.tags;284 tagValues = sc.tagValues;285 scenarioInfo = info;286 vars = sc.vars.copy(true); // deep / snap-shot copy287 config = new Config(sc.config); // safe copy288 rootFeatureContext = sc.rootFeatureContext;289 client = HttpClient.construct(config, this);290 bindings = new ScriptBindings(this);291 // state292 request = sc.request.copy();293 driver = sc.driver;294 prevRequest = sc.prevRequest;295 prevResponse = sc.prevResponse;296 prevPerfEvent = sc.prevPerfEvent;297 callResults = sc.callResults;298 webSocketClients = sc.webSocketClients;299 signalResult = sc.signalResult;300 }301 public void configure(Config config) {302 this.config = config;303 client = HttpClient.construct(config, this);304 }305 public void configure(String key, ScriptValue value) { // TODO use enum306 key = StringUtils.trimToEmpty(key);307 // if next line returns true, http-client needs re-building308 if (config.configure(key, value)) {309 if (key.startsWith("httpClient")) { // special case310 client = HttpClient.construct(config, this);311 } else {312 client.configure(config, this);313 }314 }315 }316 private List<String> evalList(List<String> values) {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) {803 driver.quit();804 driver = null;805 }806 }807}...

Full Screen

Full Screen

Source:WebSocketClientRunner.java Github

copy

Full Screen

1package demo.websocket;2import com.intuit.karate.Logger;3import com.intuit.karate.http.WebSocketClient;4import com.intuit.karate.http.WebSocketOptions;5import demo.TestBase;6import static org.junit.Assert.*;7import org.junit.BeforeClass;8import org.junit.Test;9/**10 *11 * @author pthomas312 */13public class WebSocketClientRunner {14 private static final Logger logger = new Logger();15 private WebSocketClient client;16 private String result;17 @BeforeClass18 public static void beforeClass() throws Exception {19 TestBase.beforeClass();20 }21 @Test22 public void testWebSocketClient() throws Exception {23 String port = System.getProperty("demo.server.port");24 WebSocketOptions options = new WebSocketOptions("ws://localhost:" + port + "/websocket");25 options.setTextConsumer(text -> {26 logger.debug("websocket listener text: {}", text);27 synchronized (this) {28 result = text;29 notify();30 }31 });32 client = new WebSocketClient(options, logger);33 client.send("Billie");34 synchronized (this) {35 wait();36 }37 assertEquals("hello Billie !", result);38 }39}

Full Screen

Full Screen

Source:BaseTest.java Github

copy

Full Screen

1package automation;2import static org.junit.Assert.assertEquals;3import org.testng.annotations.BeforeSuite;4import com.intuit.karate.Logger;5import com.intuit.karate.http.WebSocketClient;6import com.intuit.karate.http.WebSocketOptions;7public class BaseTest {8 protected static final Logger logger = new Logger();9 protected WebSocketClient client;10 protected String result;11 WebSocketOptions options;12 @BeforeSuite13 public void testWebSocketClient() throws Exception {14 options = new WebSocketOptions("wss://api.staging.neontrading.com");15 options.setTextConsumer(text -> {16 logger.debug("websocket listener text: {}", text);17 synchronized (this) {18 result = text;19 notify();20 }21 });22 client = new WebSocketClient(options, logger);23 client.send(24 "connect 21 { \"device\": \"<deviceId>\", \"clientId\": \"cta\", \"clientVersion\": \"1.0.1\", \"platformId\": \"windows\", \"platformVersion\": \"10.2\", \"locale\": \"de\" }");25 synchronized (this) {26 wait();27 }28 assertEquals("connected", result);29 }30}...

Full Screen

Full Screen

WebSocketClient

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.http.WebSocketClient;2import com.intuit.karate.http.WebSocketMessage;3import java.util.concurrent.TimeUnit;4public class 4 {5 public static void main(String[] args) throws Exception {6 client.connect();7 WebSocketMessage message = client.receive();8 System.out.println(message);9 client.send("hello");10 client.close();11 }12}13WebSocketMessage{type=TEXT, text=hello, bytes=null, exception=null}14import com.intuit.karate.http.WebSocketClient;15import com.intuit.karate.http.WebSocketMessage;16import java.util.concurrent.TimeUnit;17public class 5 {18 public static void main(String[] args) throws Exception {19 client.connect();20 WebSocketMessage message = client.receive();21 System.out.println(message);22 client.send("hello".getBytes());23 client.close();24 }25}26WebSocketMessage{type=BINARY, text=null, bytes=[B@7f31245a, exception=null}27import com.intuit.karate.http.WebSocketClient;28import com.intuit.karate.http.WebSocketMessage;29import java.util.concurrent.TimeUnit;30public class 6 {31 public static void main(String[] args) throws Exception {32 client.connect();33 WebSocketMessage message = client.receive();34 System.out.println(message);35 client.ping("hello".getBytes());36 client.close();37 }38}39WebSocketMessage{type=BINARY, text=null, bytes=[B@7f31245a, exception=null}

Full Screen

Full Screen

WebSocketClient

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.http.WebSocketClient;2import com.intuit.karate.http.WebSocketMessage;3import com.intuit.karate.http.WebSocketOptions;4import com.intuit.karate.http.WebSocketListener;5import com.intuit.karate.http.WebSocketMessage;6import com.intuit.karate.http.WebSocketClient;7import com.intuit.karate.http.WebSocketMessage;8import com.intuit.karate.http.WebSocketOptions;9import com.intuit.karate.http.WebSocketListener;10import com.intuit.karate.http.WebSocketMessage;11WebSocketOptions options = new WebSocketOptions();12options.setListener(new WebSocketListener() {13 public void onConnect(WebSocketClient client) {14 System.out.println("connected");15 }16 public void onText(WebSocketClient client, WebSocketMessage message) {17 System.out.println("text received: " + message.getText());18 }19 public void onBinary(WebSocketClient client, WebSocketMessage message) {20 System.out.println("binary received: " + message.getBinary().length);21 }22 public void onClose(WebSocketClient client, WebSocketMessage message) {23 System.out.println("closed: " + message.getCloseReason());24 }25});26WebSocketClient client = new WebSocketClient(options);27client.connect();28client.sendText("hello world");29client.sendText("goodbye world");30client.close();31import com.intuit.karate.http.WebSocketClient;32import com.intuit.karate.http.WebSocketMessage;33import com.intuit.karate.http.WebSocketOptions;34import com.intuit.karate.http.WebSocketListener;35import com.intuit.karate.http.WebSocketMessage;36WebSocketOptions options = new WebSocketOptions();37options.setListener(new WebSocketListener() {38 public void onConnect(WebSocketClient client) {39 System.out.println("connected");40 }41 public void onText(WebSocketClient client, WebSocketMessage message) {42 System.out.println("text received: " + message.getText());43 }44 public void onBinary(WebSocketClient client, WebSocketMessage message) {45 System.out.println("binary

Full Screen

Full Screen

WebSocketClient

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.http.WebSocketClient;2import com.intuit.karate.http.WebSocketMessage;3import java.util.concurrent.TimeUnit;4public class 4 {5 public static void main(String[] args) throws Exception {6 client.connect();7 client.send("hello");8 WebSocketMessage msg = client.receive(10, TimeUnit.SECONDS);9 System.out.println("message received: " + msg.getText());10 client.disconnect();11 }12}13import com.intuit.karate.http.WebSocketMessage;14import com.intuit.karate.http.WebSocketClient;15import java.util.concurrent.TimeUnit;16public class 5 {17 public static void main(String[] args) throws Exception {18 client.connect();19 client.send("hello");20 WebSocketMessage msg = client.receive(10, TimeUnit.SECONDS);21 System.out.println("message received: " + msg.getText());22 client.disconnect();23 }24}25import com.intuit.karate.core.WebSocketMessage;26import com.intuit.karate.core.WebSocketClient;27import java.util.concurrent.TimeUnit;28public class 6 {29 public static void main(String[] args) throws Exception {30 client.connect();31 client.send("hello");32 WebSocketMessage msg = client.receive(10, TimeUnit.SECONDS);33 System.out.println("message received: " + msg.getText());34 client.disconnect();35 }36}37import com.intuit.karate.netty.WebSocketMessage;38import com.intuit.karate.netty.WebSocketClient;39import java.util.concurrent.TimeUnit;40public class 7 {41 public static void main(String[] args) throws Exception {42 client.connect();43 client.send("hello");44 WebSocketMessage msg = client.receive(10, TimeUnit.SECONDS);45 System.out.println("message received: " + msg.getText());

Full Screen

Full Screen

WebSocketClient

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.http.WebSocketClient;2import com.intuit.karate.http.WebSocketMessage;3import java.util.Map;4import java.util.concurrent.CountDownLatch;5import java.util.concurrent.TimeUnit;6import java.util.concurrent.atomic.AtomicReference;7import org.junit.Test;8import static org.junit.Assert.*;9public class 4 {10 public void test() throws Exception {11 client.connect();12 CountDownLatch latch = new CountDownLatch(1);13 AtomicReference<WebSocketMessage> ref = new AtomicReference();14 client.onTextMessage((message) -> {15 ref.set(message);16 latch.countDown();17 });18 String text = "hello";19 client.sendText(text);20 latch.await(5, TimeUnit.SECONDS);21 WebSocketMessage message = ref.get();22 assertNotNull(message);23 assertEquals(text, message.getText());24 }25}26import com.intuit.karate.http.WebSocketClient;27import com.intuit.karate.http.WebSocketMessage;28import java.util.Map;29import java.util.concurrent.CountDownLatch;30import java.util.concurrent.TimeUnit;31import java.util.concurrent.atomic.AtomicReference;32import org.junit.Test;33import static org.junit.Assert.*;34public class 5 {35 public void test() throws Exception {36 client.connect();37 CountDownLatch latch = new CountDownLatch(1);38 AtomicReference<WebSocketMessage> ref = new AtomicReference();39 client.onTextMessage((message) -> {40 ref.set(message);41 latch.countDown();42 });43 String text = "hello";44 client.sendText(text);45 latch.await(5, TimeUnit.SECONDS);46 WebSocketMessage message = ref.get();47 assertNotNull(message);48 assertEquals(text, message.getText());49 }50}51import com.intuit.karate.http.WebSocketClient;52import com.intuit.karate.http.WebSocketMessage;53import java.util.Map;54import java.util.concurrent.CountDownLatch;55import java.util.concurrent.TimeUnit;56import java.util.concurrent.atomic.AtomicReference;57import org.junit.Test;58import static org.junit.Assert.*;59public class 6 {60 public void test() throws

Full Screen

Full Screen

WebSocketClient

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.http.WebSocketClient2import com.intuit.karate.http.WebSocketFrame3import com.intuit.karate.http.WebSocketMessage4def frame = new WebSocketFrame()5frame.setPayload('Hello from Karate')6client.send(frame)7def message = client.receive()8println message.getPayload()9client.close()10import com.intuit.karate.http.WebSocketClient11import com.intuit.karate.http.WebSocketFrame12import com.intuit.karate.http.WebSocketMessage13def frame = new WebSocketFrame()14frame.setPayload('Hello from Karate')15client.send(frame)16def message = client.receive()17println message.getPayload()18client.close()19import com.intuit.karate.http.WebSocketClient20import com.intuit.karate.http.WebSocketFrame21import com.intuit.karate.http.WebSocketMessage22def frame = new WebSocketFrame()23frame.setPayload('Hello from Karate')24client.send(frame)25def message = client.receive()26println message.getPayload()27client.close()28import com.intuit.karate.http.WebSocketClient29import com.intuit.karate.http.WebSocketFrame30import com.intuit.karate.http.WebSocketMessage31def frame = new WebSocketFrame()32frame.setPayload('Hello from Karate')33client.send(frame)34def message = client.receive()35println message.getPayload()36client.close()37import com.intuit.karate.http.WebSocketClient38import com.intuit.karate.http.WebSocketFrame39import com.intuit.karate.http.WebSocketMessage40def frame = new WebSocketFrame()41frame.setPayload('Hello from Karate')

Full Screen

Full Screen

WebSocketClient

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.http.WebSocketClient;2import com.intuit.karate.http.WebSocketMessage;3import java.util.concurrent.TimeUnit;4import java.util.concurrent.CountDownLatch;5public class 4 {6 public static void main(String[] args) throws Exception {7 client.connect();8 CountDownLatch latch = new CountDownLatch(1);9 client.onMessage((WebSocketMessage message) -> {10 logger.info('received: ' + message.getPayload());11 latch.countDown();12 });13 client.sendText("hello");14 latch.await(10, TimeUnit.SECONDS);15 client.close();16 }17}18import com.intuit.karate.http.WebSocketClient;19import com.intuit.karate.http.WebSocketMessage;20import java.util.concurrent.TimeUnit;21import java.util.concurrent.CountDownLatch;22public class 5 {23 public static void main(String[] args) throws Exception {24 client.connect();25 CountDownLatch latch = new CountDownLatch(1);26 client.onMessage((WebSocketMessage message) -> {27 logger.info('received: ' + message.getPayload());28 latch.countDown();29 });30 client.sendBinary("hello".getBytes());31 latch.await(10, TimeUnit.SECONDS);32 client.close();33 }34}35import com.intuit.karate.http.WebSocketClient;36import com.intuit.karate.http.WebSocketMessage;37import java.util.concurrent.TimeUnit;38import java.util.concurrent.CountDownLatch;39public class 6 {40 public static void main(String[] args) throws Exception {41 client.connect();42 CountDownLatch latch = new CountDownLatch(1);43 client.onMessage((WebSocketMessage message) -> {44 logger.info('received: ' + message.getPayload());45 latch.countDown();46 });47 client.sendPing("hello");48 latch.await(10, TimeUnit.SECONDS);49 client.close();50 }51}52import com.intuit.karate.http.WebSocketClient;53import

Full Screen

Full Screen

WebSocketClient

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.http.WebSocketClient2import static org.junit.jupiter.api.Assertions.*3import java.util.concurrent.TimeUnit4import java.util.concurrent.atomic.AtomicInteger5def counter = new AtomicInteger()6def latch = new CountDownLatch(1)7client.onMessage = { msg ->8 counter.incrementAndGet()9 latch.countDown()10}11client.connect()12client.send("hello")13latch.await(10, TimeUnit.SECONDS)14client.close()15assertEquals(1, counter.get())16import com.intuit.karate.http.WebSocketClient17import static org.junit.jupiter.api.Assertions.*18import java.util.concurrent.TimeUnit19import java.util.concurrent.atomic.AtomicInteger20def counter = new AtomicInteger()21def latch = new CountDownLatch(1)22client.onMessage = { msg ->23 counter.incrementAndGet()24 latch.countDown()25}26client.connect()27client.send("hello")28latch.await(10, TimeUnit.SECONDS)29client.close()30assertEquals(1, counter.get())31import com.intuit.karate.http.WebSocketClient32import static org.junit.jupiter.api.Assertions.*33import java.util.concurrent.TimeUnit34import java.util.concurrent.atomic.AtomicInteger35def counter = new AtomicInteger()36def latch = new CountDownLatch(1)37client.onMessage = { msg ->38 counter.incrementAndGet()39 latch.countDown()40}41client.connect()42client.send("hello")43latch.await(10, TimeUnit.SECONDS)44client.close()45assertEquals(1, counter.get())46import com.intuit.karate.http.WebSocketClient47import static org.junit.jupiter.api.Assertions.*48import java.util.concurrent.TimeUnit49import java.util.concurrent.atomic.AtomicInteger50def counter = new AtomicInteger()51def latch = new CountDownLatch(1)52client.onMessage = { msg ->53 counter.incrementAndGet()54 latch.countDown()55}56client.connect()57client.send("hello")

Full Screen

Full Screen

WebSocketClient

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.http.WebSocketClient;2client.send("hello");3String response = client.receive();4client.close();5client = null;6ws.send("hello");7String response = ws.receive();8ws.close();9ws = null;10import com.intuit.karate.http.WebSocketClient;11client.send("hello");12String response = client.receive();13client.close();14client = null;15import com.intuit.karate.http.WebSocketClient;16client.send("hello");17String response = client.receive();18client.close();19client = null;20import com.intuit.karate.http.WebSocketClient;21client.send("hello");22String response = client.receive();23client.close();24client = null;25import com.intuit.karate.http.WebSocketClient;26client.send("hello");27String response = client.receive();28client.close();29client = null;30import com.intuit.karate.http.WebSocketClient;31client.send("hello");32String response = client.receive();33client.close();34client = null;35import com.intuit.karate.http.WebSocketClient;36client.send("hello");37String response = client.receive();38client.close();39client = null;40import com.intuit.karate.http.WebSocketClient;41client.send("hello");42String response = client.receive();43client.close();44client = null;45import com.intuit.karate.http.WebSocketClient;46client.send("hello");47String response = client.receive();48client.close();49client = null;

Full Screen

Full Screen

WebSocketClient

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.http.WebSocketClient;2WebSocketClient client = new WebSocketClient(url);3client.connect();4client.sendText("hello");5String text = client.receiveText();6client.sendText("world");7text = client.receiveText();8client.close();9import com.intuit.karate.http.WebSocketClient;10WebSocketClient client = new WebSocketClient(url);11client.connect();12client.sendBinary("hello".getBytes());13byte[] bytes = client.receiveBinary();14client.sendBinary("world".getBytes());15bytes = client.receiveBinary();16client.close();17import com.intuit.karate.http.WebSocketClient;18WebSocketClient client = new WebSocketClient(url);19client.connect();20client.sendPing("hello".getBytes());21byte[] bytes = client.receivePong();22client.sendPing("world".getBytes());23bytes = client.receivePong();24client.close();25import com.intuit.karate.http.WebSocketClient;26client.send("hello");27String response = client.receive();28client.close();29client = null;30import com.intuit.karate.http.WebSocketClient;31client.send("hello");32String response = client.receive();33client.close();34client = null;35import com.intuit.karate.http.WebSocketClient;36client.send("hello");37String response = client.receive();38client.close();39client = null;40import com.intuit.karate.http.WebSocketClient;41client.send("hello");42String response = client.receive();43client.close();44client = null;45import com.intuit.karate.http.WebSocketClient;46client.send("hello");47String response = client.receive();48client.close();49client = null;50import com.intuit.karate.http.WebSocketClient;51client.send("hello");52String response = client.receive();53client.close();54client = null;55import com.intuit.karate.http.WebSocketClient;56client.send("hello");57String response = client.receive();58client.close();59client = null;60import com.intuit.karate.http.WebSocketClient;61client.send("hello");62String response = client.receive();63client.close();64client = null;

Full Screen

Full Screen

WebSocketClient

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.http.WebSocketClient2import com.intuit.karate.http.WebSocketFrame3import com.intuit.karate.http.WebSocketMessage4def frame = new WebSocketFrame()5frame.setPayload('Hello from Karate')6client.send(frame)7def message = client.receive()8println message.getPayload()9client.close()10import com.intuit.karate.http.WebSocketClient11import com.intuit.karate.http.WebSocketFrame12import com.intuit.karate.http.WebSocketMessage13def frame = new WebSocketFrame()14frame.setPayload('Hello from Karate')15client.send(frame)16def message = client.receive()17println message.getPayload()18client.close()19import com.intuit.karate.http.WebSocketClient20import com.intuit.karate.http.WebSocketFrame21import com.intuit.karate.http.WebSocketMessage22def frame = new WebSocketFrame()23frame.setPayload('Hello from Karate')24client.send(frame)25def message = client.receive()26println message.getPayload()27client.close()28import com.intuit.karate.http.WebSocketClient29import com.intuit.karate.http.WebSocketFrame30import com.intuit.karate.http.WebSocketMessage31def frame = new WebSocketFrame()32frame.setPayload('Hello from Karate')33client.send(frame)34def message = client.receive()35println message.getPayload()36client.close()37import com.intuit.karate.http.WebSocketClient38import com.intuit.karate.http.WebSocketFrame39import com.intuit.karate.http.WebSocketMessage40def frame = new WebSocketFrame()41frame.setPayload('Hello from Karate')

Full Screen

Full Screen

WebSocketClient

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.http.WebSocketClient;2client.send("hello");3String response = client.receive();4client.close();5client = null;6ws.send("hello");7String response = ws.receive();8ws.close();9ws = null;10import com.intuit.karate.http.WebSocketClient;11client.send("hello");12String response = client.receive();13client.close();14client = null;15import com.intuit.karate.http.WebSocketClient;16client.send("hello");17String response = client.receive();18client.close();19client = null;20import com.intuit.karate.http.WebSocketClient;21client.send("hello");22String response = client.receive();23client.close();24client = null;25import com.intuit.karate.http.WebSocketClient;26client.send("hello");27String response = client.receive();28client.close();29client = null;30import com.intuit.karate.http.WebSocketClient;31client.send("hello");32String response = client.receive();33client.close();34client = null;35import com.intuit.karate.http.WebSocketClient;36client.send("hello");37String response = client.receive();38client.close();39client = null;40import com.intuit.karate.http.WebSocketClient;41client.send("hello");42String response = client.receive();43client.close();44client = null;45import com.intuit.karate.http.WebSocketClient;46client.send("hello");47String response = client.receive();48client.close();49client = null;

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.

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful