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

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

Source:MockHandler.java Github

copy

Full Screen

...54 private static final String REQUEST_PARAMS = "requestParams";55 private static final String REQUEST_PARTS = "requestParts";56 private static final String RESPONSE_DELAY = "responseDelay";57 private static final String PATH_MATCHES = "pathMatches";58 private static final String METHOD_IS = "methodIs";59 private static final String TYPE_CONTAINS = "typeContains";60 private static final String ACCEPT_CONTAINS = "acceptContains";61 private static final String HEADER_CONTAINS = "headerContains";62 private static final String PARAM_VALUE = "paramValue";63 private static final String PARAM_EXISTS = "paramExists";64 private static final String PATH_PARAMS = "pathParams";65 private static final String BODY_PATH = "bodyPath";66 private final List<Feature> featureList;67 private final Map<String, Object> args;68 private final LinkedHashMap<Feature, ScenarioRuntime> features = new LinkedHashMap<>(); // feature + holds global config and vars69 private final Map<String, Variable> globals = new HashMap<>();70 private boolean corsEnabled;71 protected static final ThreadLocal<Request> LOCAL_REQUEST = new ThreadLocal<>();72 private String prefix = null;73 private List<MockHandlerHook> handlerHooks = new ArrayList<>();74 public MockHandler(Feature feature) {75 this(feature, null);76 }77 public MockHandler(Feature feature, Map<String, Object> args) {78 this(Collections.singletonList(feature), args);79 }80 public MockHandler(List<Feature> features) {81 this(features, null);82 }83 public MockHandler(List<Feature> features, Map<String, Object> args) {84 this.featureList = features;85 this.args = args;86 }87 public MockHandler withPrefix(String prefix) {88 this.prefix = "/".equals(prefix) ? null : prefix;89 return this;90 }91 public MockHandler withHandlerHooks(List<MockHandlerHook> handlerHooks) {92 this.handlerHooks = handlerHooks;93 return this;94 }95 public MockHandler start() {96 reload();97 return this;98 }99 private static Suite forTempUse(HttpClientFactory hcf) {100 try {101 return Suite.forTempUse(hcf);102 } catch (Throwable e) {103 try {104 return (Suite) Suite.class.getMethod("forTempUse").invoke(null);105 } catch (Exception ex) {106 logger.error("Unknown version of karate, couldn't find Suite.forTempUse() method");107 throw new RuntimeException("Unknown version of karate, couldn't find Suite.forTempUse() method", ex);108 }109 }110 }111 public void reload() {112 for (MockHandlerHook hook : handlerHooks) {113 hook.reload();114 }115 this.featureList.replaceAll(feature -> Feature.read(feature.getResource()));116 for (Feature feature : featureList) {117 FeatureRuntime featureRuntime = FeatureRuntime.of(forTempUse(HttpClientFactory.DEFAULT), feature, args);118 Scenario dummy = createDummyScenario(feature);119 ScenarioRuntime runtime = new ScenarioRuntime(featureRuntime, dummy);120 initRuntime(runtime);121 if (feature.isBackgroundPresent()) {122 // if we are within a scenario already e.g. karate.start(), preserve context123 ScenarioEngine prevEngine = ScenarioEngine.get();124 try {125 ScenarioEngine.set(runtime.engine);126 for (Step step : feature.getBackground().getSteps()) {127 Result result = StepRuntime.execute(step, runtime.actions);128 if (result.isFailed()) {129 String message = "mock-server background failed - " + feature + ":" + step.getLine();130 runtime.logger.error(message);131 throw new KarateException(message, result.getError());132 }133 }134 } finally {135 ScenarioEngine.set(prevEngine);136 }137 }138 corsEnabled = corsEnabled || runtime.engine.getConfig().isCorsEnabled();139 globals.putAll(runtime.engine.detachVariables());140 runtime.logger.info("mock server initialized: {}", feature);141 this.features.put(feature, runtime);142 }143 for (MockHandlerHook hook : handlerHooks) {144 hook.onSetup(features, globals);145 }146 }147 public static Scenario createDummyScenario(Feature feature) {148 FeatureSection section = new FeatureSection();149 section.setIndex(-1);150 Scenario dummy = new Scenario(feature, section, -1);151 section.setScenario(dummy);152 return dummy;153 }154 private void initRuntime(ScenarioRuntime runtime) {155 runtime.engine.setVariable(PATH_MATCHES, (Function<String, Boolean>) this::pathMatches);156 runtime.engine.setVariable(PARAM_EXISTS, (Function<String, Boolean>) this::paramExists);157 runtime.engine.setVariable(PARAM_VALUE, (Function<String, String>) this::paramValue);158 runtime.engine.setVariable(METHOD_IS, (Function<String, Boolean>) this::methodIs);159 runtime.engine.setVariable(TYPE_CONTAINS, (Function<String, Boolean>) this::typeContains);160 runtime.engine.setVariable(ACCEPT_CONTAINS, (Function<String, Boolean>) this::acceptContains);161 runtime.engine.setVariable(HEADER_CONTAINS, (BiFunction<String, String, Boolean>) this::headerContains);162 runtime.engine.setVariable(BODY_PATH, (Function<String, Object>) this::bodyPath);163 runtime.engine.init();164 }165 private static final Result PASSED = Result.passed(0);166 private static final String ALLOWED_METHODS = "GET, HEAD, POST, PUT, DELETE, PATCH";167 @Override168 public synchronized Response handle(Request req) { // note the [synchronized]169 if (corsEnabled && "OPTIONS".equals(req.getMethod())) {170 Response response = new Response(200);171 response.setHeader("Allow", ALLOWED_METHODS);172 response.setHeader("Access-Control-Allow-Origin", "*");173 response.setHeader("Access-Control-Allow-Methods", ALLOWED_METHODS);174 List<String> requestHeaders = req.getHeaderValues("Access-Control-Request-Headers");175 if (requestHeaders != null) {176 response.setHeader("Access-Control-Allow-Headers", requestHeaders);177 }178 return response;179 }180 String path = ("/" + req.getPath()).replaceFirst("^//", "/");181 if (prefix != null && path.startsWith(prefix)) {182 req.setPath(path.substring(prefix.length()));183 }184 // rare case when http-client is active within same jvm185 // snapshot existing thread-local to restore186 ScenarioEngine prevEngine = ScenarioEngine.get();187 for (MockHandlerHook hook : this.handlerHooks) {188 Response response = hook.beforeRequest(req);189 if(response != null){190 logger.info("Returning response on 'beforeRequest' from hook: {}", hook);191 return response;192 }193 }194 for (Map.Entry<Feature, ScenarioRuntime> entry : this.features.entrySet()) {195 Feature feature = entry.getKey();196 ScenarioRuntime runtime = entry.getValue();197 // important for graal to work properly198 Thread.currentThread().setContextClassLoader(runtime.featureRuntime.suite.classLoader);199 LOCAL_REQUEST.set(req);200 req.processBody();201 ScenarioEngine engine = createScenarioEngine(req, runtime);202 Map<String, List<Map<String, Object>>> parts = req.getMultiParts();203 if (parts != null) {204 engine.setHiddenVariable(REQUEST_PARTS, parts);205 }206 for (FeatureSection fs : feature.getSections()) {207 if (fs.isOutline()) {208 runtime.logger.warn("skipping scenario outline - {}:{}", feature, fs.getScenarioOutline().getLine());209 break;210 }211 Scenario scenario = fs.getScenario();212 if (isMatchingScenario(scenario, engine)) {213 for (MockHandlerHook hook : this.handlerHooks) {214 Response response = hook.beforeScenario(req, engine);215 if(response != null){216 logger.info("Returning response on 'beforeScenario' from hook: {}", hook);217 return response;218 }219 }220 Map<String, Object> configureHeaders;221 Variable response, responseStatus, responseHeaders, responseDelay;222 ScenarioActions actions = new ScenarioActions(engine);223 Result result = PASSED;224 result = executeScenarioSteps(feature, runtime, scenario, actions, result);225 engine.mockAfterScenario();226 configureHeaders = engine.mockConfigureHeaders();227 response = engine.vars.remove(ScenarioEngine.RESPONSE);228 responseStatus = engine.vars.remove(ScenarioEngine.RESPONSE_STATUS);229 responseHeaders = engine.vars.remove(ScenarioEngine.RESPONSE_HEADERS);230 responseDelay = engine.vars.remove(RESPONSE_DELAY);231 globals.putAll(engine.detachVariables());232 Response res = new Response(200);233 if (result.isFailed()) {234 response = new Variable(result.getError().getMessage());235 responseStatus = new Variable(500);236 } else {237 if (corsEnabled) {238 res.setHeader("Access-Control-Allow-Origin", "*");239 }240 res.setHeaders(configureHeaders);241 if (responseHeaders != null && responseHeaders.isMap()) {242 res.setHeaders(responseHeaders.getValue());243 }244 if (responseDelay != null) {245 res.setDelay(responseDelay.getAsInt());246 }247 }248 if (response != null && !response.isNull()) {249 res.setBody(response.getAsByteArray());250 if (res.getContentType() == null) {251 ResourceType rt = ResourceType.fromObject(response.getValue());252 if (rt != null) {253 res.setContentType(rt.contentType);254 }255 }256 }257 if (responseStatus != null) {258 res.setStatus(responseStatus.getAsInt());259 }260 if (prevEngine != null) {261 ScenarioEngine.set(prevEngine);262 }263 if(result.isFailed()) {264 for (MockHandlerHook hook : this.handlerHooks) {265 logger.trace("Running 'afterScenarioFailure' from hook: {}", hook);266 res = hook.afterScenarioFailure(req, res, engine);267 }268 } else {269 for (MockHandlerHook hook : this.handlerHooks) {270 logger.trace("Running 'afterScenarioSuccess' from hook: {}", hook);271 res = hook.afterScenarioSuccess(req, res, engine);272 }273 }274 return res;275 }276 }277 }278 Response res = new Response(404);279 for (MockHandlerHook hook : this.handlerHooks) {280 logger.info("Returning response on 'noMatchingScenario' from hook: {}", hook);281 ScenarioRuntime runtime = features.values().stream().findFirst().get();282 res = hook.noMatchingScenario(req, res, createScenarioEngine(req, runtime));283 }284 logger.warn("no scenarios matched, returning 404: {}", req); // NOTE: not logging with engine.logger285 if (prevEngine != null) {286 ScenarioEngine.set(prevEngine);287 }288 return res;289 }290 private Result executeScenarioSteps(Feature feature, ScenarioRuntime runtime, Scenario scenario, ScenarioActions actions, Result result) {291 for (Step step : scenario.getSteps()) {292 result = StepRuntime.execute(step, actions);293 if (result.isAborted()) {294 runtime.logger.debug("abort at {}:{}", feature, step.getLine());295 break;296 }297 if (result.isFailed()) {298 String message = "server-side scenario failed, " + feature + ":" + step.getLine()299 + "\n" + step.toString() + "\n" + result.getError().getMessage();300 runtime.logger.error(message);301 break;302 }303 }304 return result;305 }306 private ScenarioEngine createScenarioEngine(Request req, ScenarioRuntime runtime) {307 ScenarioEngine engine = new ScenarioEngine(runtime, new HashMap<>(globals));308 ScenarioEngine.set(engine);309 engine.init();310 engine.setVariable(ScenarioEngine.REQUEST_URL_BASE, req.getUrlBase());311 engine.setVariable(ScenarioEngine.REQUEST_URI, req.getPath());312 engine.setVariable(ScenarioEngine.REQUEST_METHOD, req.getMethod());313 engine.setVariable(ScenarioEngine.REQUEST_HEADERS, req.getHeaders());314 engine.setVariable(ScenarioEngine.REQUEST, req.getBodyConverted());315 engine.setVariable(REQUEST_PARAMS, req.getParams());316 engine.setVariable(REQUEST_BYTES, req.getBody());317 return engine;318 }319 private boolean isMatchingScenario(Scenario scenario, ScenarioEngine engine) {320 String expression = StringUtils.trimToNull(scenario.getName() + scenario.getDescription());321 if (expression == null) {322 engine.logger.debug("default scenario matched at line: {} - {}", scenario.getLine(), engine.getVariable(ScenarioEngine.REQUEST_URI));323 return true;324 }325 try {326 Variable v = engine.evalJs(expression);327 if (v.isTrue()) {328 engine.logger.debug("scenario matched at {} line {}: {}", scenario.getFeature().getResource().getFile(), scenario.getLine(), expression);329 return true;330 } else {331 engine.logger.trace("scenario skipped at {} line {}: {}", scenario.getFeature().getResource().getFile(), scenario.getLine(), expression);332 return false;333 }334 } catch (Exception e) {335 engine.logger.warn("scenario match evaluation failed at {} line {}: {} - {}", scenario.getFeature().getResource().getFile(), scenario.getLine(), expression, e + "");336 return false;337 }338 }339 public boolean pathMatches(String pattern) {340 String uri = LOCAL_REQUEST.get().getPath();341 if (uri.equals(pattern)) {342 return true;343 }344 Map<String, String> pathParams = HttpUtils.parseUriPattern(pattern, uri);345 if (pathParams == null) {346 return false;347 } else {348 ScenarioEngine.get().setVariable(PATH_PARAMS, pathParams);349 return true;350 }351 }352 public boolean paramExists(String name) {353 Map<String, List<String>> params = LOCAL_REQUEST.get().getParams();354 return params != null && params.containsKey(name);355 }356 public String paramValue(String name) {357 return LOCAL_REQUEST.get().getParam(name);358 }359 public boolean methodIs(String name) { // TODO no more supporting array arg360 return LOCAL_REQUEST.get().getMethod().equalsIgnoreCase(name);361 }362 public boolean typeContains(String text) {363 String contentType = LOCAL_REQUEST.get().getContentType();364 return contentType != null && contentType.contains(text);365 }366 public boolean acceptContains(String text) {367 String acceptHeader = LOCAL_REQUEST.get().getHeader("Accept");368 return acceptHeader != null && acceptHeader.contains(text);369 }370 public boolean headerContains(String name, String value) {371 List<String> values = LOCAL_REQUEST.get().getHeaderValues(name);372 if (values != null) {373 for (String v : values) {...

Full Screen

Full Screen

Source:OpenApiExamplesHook.java Github

copy

Full Screen

1package io.github.apimock;2import com.fasterxml.jackson.core.JsonProcessingException;3import com.fasterxml.jackson.databind.ObjectMapper;4import com.intuit.karate.Json;5import com.intuit.karate.JsonUtils;6import com.intuit.karate.core.Feature;7import com.intuit.karate.core.MockHandlerHook;8import com.intuit.karate.core.ScenarioEngine;9import com.intuit.karate.core.ScenarioRuntime;10import com.intuit.karate.core.Variable;11import com.intuit.karate.http.HttpUtils;12import com.intuit.karate.http.Request;13import com.intuit.karate.http.Response;14import org.openapi4j.parser.model.v3.Example;15import org.openapi4j.parser.model.v3.MediaType;16import org.openapi4j.parser.model.v3.OpenApi3;17import org.openapi4j.parser.model.v3.Operation;18import org.slf4j.Logger;19import org.slf4j.LoggerFactory;20import java.text.SimpleDateFormat;21import java.util.AbstractMap;22import java.util.ArrayList;23import java.util.Calendar;24import java.util.Collections;25import java.util.Date;26import java.util.GregorianCalendar;27import java.util.HashMap;28import java.util.List;29import java.util.Map;30import java.util.function.BiFunction;31import java.util.function.Function;32import java.util.function.Supplier;33import java.util.regex.Matcher;34import java.util.regex.Pattern;35/**36 *37 * @author ivangsa38 */39public class OpenApiExamplesHook implements MockHandlerHook {40 private Logger logger = LoggerFactory.getLogger(getClass());41 private final OpenApiValidator4Karate openApiValidator;42 private OpenApi3 api;43 private ObjectMapper jacksonMapper = new ObjectMapper();44 public OpenApiExamplesHook(OpenApiValidator4Karate openApiValidator) {45 super();46 this.openApiValidator = openApiValidator;47 this.api = openApiValidator.getApi();48 }49 @Override50 public void reload() {51 openApiValidator.reload();52 this.api = openApiValidator.getApi();53 sequenceNext = 0;54 }55 @Override56 public void onSetup(Map<Feature, ScenarioRuntime> features, Map<String, Variable> globals) {57 if(!globals.containsKey(UUID)) {58 globals.put(UUID, new Variable((Supplier<String>) this::uuid));59 }60 if(!globals.containsKey(SEQUENCE_NEXT)) {61 globals.put(SEQUENCE_NEXT, new Variable((Supplier<Integer>) this::sequenceNext));62 }63 if(!globals.containsKey(NOW)) {64 globals.put(NOW, new Variable((Function<String,String>) this::now));65 }66 if(!globals.containsKey(DATE)) {67 globals.put(DATE, new Variable((BiFunction<String, String, String>) this::date));68 }69 if(api.getComponents() != null && api.getComponents().getExamples() != null) {70 ScenarioEngine engine = new ScenarioEngine(features.values().stream().findFirst().get(), new HashMap<>(globals));71 engine.init();72 for (Example example : api.getComponents().getExamples().values()) {73 String karateVar = (String) firstNotNull(example.getExtensions(), Collections.emptyMap()).get("x-apimock-karate-var");74 if(isNotEmpty(karateVar)) {75 Object seeds = firstNotNull(firstNotNull(example.getExtensions(), Collections.emptyMap()).get("x-apimock-seed"), 1);76 Map<String, Object> seedsMap = seeds instanceof Integer? defaultRootSeed((Integer) seeds): (Map<String, Object>) seeds;77 Object seededExample = seed(example.getValue(), seedsMap);78 try {79 Map<String, String> transforms = (Map) firstNotNull(example.getExtensions(), Collections.emptyMap()).get("x-apimock-transform");80 String json = processObjectDynamicProperties(engine, transforms, seededExample);81 Variable exampleVariable = new Variable(Json.of(json).value());82 addExamplesVariableToKarateGlobals(globals, karateVar, exampleVariable);83 } catch (Exception e) {84 logger.error("Error setting openapi examples {} into karate globals ({})", karateVar, e.getMessage(), e);85 }86 }87 }88 }89 }90 private Map<String, Object> defaultRootSeed(Integer seed) {91 Map<String, Object> seedMap = new HashMap<>();92 seedMap.put("$", seed);93 return seedMap;94 }95 private Object seed(Object value, Map<String, Object> seedsMap) {96 Json json = Json.of(value);97 for (Map.Entry<String, Object> seedEntry : seedsMap.entrySet()) {98 int seed = (Integer) seedEntry.getValue();99 if(seed == 1) {100 continue;101 }102 String seedPath = String.valueOf(seedEntry.getKey());103 Object inner = json.get(seedPath);104 Object seeded = seedValue(inner, seed);105 json = replace(json, seedPath, seeded);106 }107 return json.get("$");108 }109 private List seedValue(Object value, int seed) {110 List seeded = new ArrayList();111 for (int i = 0; i < seed; i++) {112 if(value instanceof List) {113 seeded.addAll((List) JsonUtils.deepCopy(value));114 } else {115 seeded.add(JsonUtils.deepCopy(value));116 }117 }118 return seeded;119 }120 private Json replace(Json json, String path, Object replacement) {121 if("$".equals(path)) {122 return Json.of(replacement);123 }124 json.set(path, replacement);125 return json;126 }127 private void addExamplesVariableToKarateGlobals(Map<String, Variable> globals, String karateVar, Variable examplesVariable) {128 if(!globals.containsKey(karateVar)) {129 globals.put(karateVar, examplesVariable);130 } else {131 Variable karateVariable = globals.get(karateVar);132 if(karateVariable.isList()) {133 if(examplesVariable.isList()) {134 ((List)karateVariable.getValue()).addAll(examplesVariable.getValue());135 } else {136 ((List)karateVariable.getValue()).add(examplesVariable.getValue());137 }138 }139 if(karateVariable.isMap() && examplesVariable.isMap()) {140 ((Map)karateVariable.getValue()).putAll(examplesVariable.getValue());141 }142 }143 }144 @Override145 public Response noMatchingScenario(Request req, Response response, ScenarioEngine engine) {146 Operation operation = OpenApiValidator4Karate.findOperation(req.getMethod(), req.getPath(), api);147 if(operation == null) {148 logger.debug("Operation not found for {}", req.getPath());149 return response;150 }151 logger.debug("Searching examples in openapi definition for operationId {}", operation.getOperationId());152 Map<String, org.openapi4j.parser.model.v3.Response> responses = OpenApiValidator4Karate.find2xxResponses(operation);153 loadPathParams(req.getPath(), (String) operation.getExtensions().get("x-apimock-internal-path"), engine);154 if(!responses.isEmpty()) {155 String status = responses.keySet().stream().findFirst().get();156 org.openapi4j.parser.model.v3.Response oasRespose = responses.get(status);157 // match media type from request158 String contentType = getContentType(req);159 Map.Entry<String, MediaType> mediaTypeEntry = oasRespose.getContentMediaTypes().entrySet().stream()160 .filter(e -> e.getKey().startsWith(contentType))161 .findFirst().orElse(new AbstractMap.SimpleEntry("", new MediaType()));162 if(mediaTypeEntry.getValue().getExamples() == null && mediaTypeEntry.getValue().getExample() != null) {163 logger.debug("Returning default example in openapi for operationId {}", operation.getOperationId());164 response = new Response(Integer.valueOf(status.toLowerCase().replaceAll("x", "0")));165 response.setBody(processObjectDynamicProperties(engine, null, mediaTypeEntry.getValue().getExample()));166 response.setContentType(mediaTypeEntry.getKey());167 response.setHeader("access-control-allow-origin", "*");168 unloadPathParams(engine);169 return response;170 }171 for (Map.Entry<String, Example> exampleEntry: mediaTypeEntry.getValue().getExamples().entrySet()) {172 Map<String, Object> extensions = exampleEntry.getValue().getExtensions();173 if(extensions == null) {174 continue;175 }176 Object when = extensions.get("x-apimock-when");177 Map<String, String> generators = (Map<String, String>) extensions.get("x-apimock-transform");178 if(when != null) {179 if(evalBooleanJs(engine, when.toString())) {180 logger.debug("Found example[{}] for x-apimock-when {} in openapi for operationId {}", exampleEntry.getKey(), when, operation.getOperationId());181 Example example = exampleEntry.getValue();182 Object seeds = firstNotNull(firstNotNull(example.getExtensions(), Collections.emptyMap()).get("x-apimock-seed"), 1);183 Map<String, Object> seedsMap = seeds instanceof Integer? defaultRootSeed((Integer) seeds): (Map<String, Object>) seeds;184 Object seededExample = seed(example.getValue(), seedsMap);185 logger.debug("Returning example in openapi for operationId {}", operation.getOperationId());186 response = new Response(Integer.valueOf(status.toLowerCase().replaceAll("x", "0")));187 response.setBody(processObjectDynamicProperties(engine, generators, seededExample));188 response.setContentType(mediaTypeEntry.getKey());189 response.setHeader("access-control-allow-origin", "*");190 break;191 }192 }193 }194 }195 unloadPathParams(engine);196 return response;197 }198 private String getContentType(Request req) {199 String contentType = firstNotNull(req.getContentType(), "application/json");200 return contentType.contains(";")? contentType.substring(0, contentType.indexOf(";")) : contentType;201 }202 protected void evaluateJsAndReplacePath(ScenarioEngine engine, Json json, String path, String js) {203 Object replacement = evalJsAsObject(engine, js);204 try {205 if (replacement != null) {206 json.set(path, replacement);207 }208 } catch (Exception e) {209 logger.error("Error replacing jsonPath: {} ({})", path, e.getMessage());210 }211 }212 Pattern generatorsPattern = Pattern.compile("\\{\\{(.+)\\}\\}");213 protected String processObjectDynamicProperties(ScenarioEngine engine, Map<String, String> generators, Object value) {214 if(value == null) {215 return null;216 }217 Json json = Json.of(value);218 if(generators != null) {219 for (Map.Entry<String, String> entry: generators.entrySet()){220 if(entry.getKey().startsWith("$[*]") && json.isArray()) {221 List list = json.asList();222 for(int i = 0; i < list.size(); i++) {223 evaluateJsAndReplacePath(engine, json, entry.getKey().replace("$[*]", "$[" + i + "]"), entry.getValue());224 }225 } else {226 evaluateJsAndReplacePath(engine, json, entry.getKey(), entry.getValue());227 }228 }229 }230 String jsonString = toJsonPrettyString(json);231 final Matcher matcher = generatorsPattern.matcher(jsonString);232 while (matcher.find()) {233 String match = matcher.group(0);234 String script = matcher.group(1);235 logger.trace("Processing inline replacement for script: {}", script);236 String replacement = evalJsAsString(engine, script);237 if(replacement != null) {238 jsonString = jsonString.replace(match, replacement);239 }240 }241 return JsonUtils.toStrictJson(jsonString);242 }243 private String toJsonPrettyString(Json json) {244 try {245 return jacksonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(json.value());246 } catch (JsonProcessingException e) {247 return json.toStringPretty();248 }249 }250 private void loadPathParams(String uri, String pattern, ScenarioEngine engine) {251 Map<String, String> pathParams = HttpUtils.parseUriPattern(pattern, uri);252 if (pathParams != null) {253 engine.setVariable("pathParams", pathParams);254 }255 }256 private void unloadPathParams(ScenarioEngine engine) {257 engine.setVariable("pathParams", null);258 }259 private boolean evalBooleanJs(ScenarioEngine engine, String js) {260 try {261 return engine.evalJs(js).isTrue();262 } catch (Exception e) {263 logger.error("Error evaluating boolean script: '{}' ({})", js, e.getMessage());264 return false;265 }266 }267 private String evalJsAsString(ScenarioEngine engine, String js) {268 try {269 return engine.evalJs(js).getAsString();270 } catch (Exception e) {271 logger.error("Error evaluating string script: '{}' ({})", js, e.getMessage());272 return null;273 }274 }275 private Object evalJsAsObject(ScenarioEngine engine, String js) {276 try {277 Object result = engine.evalJs(js).getValue();278 return result != null? result : "";279 } catch (Exception e) {280 logger.error("Error evaluating script: '{}' ({})", js, e.getMessage());281 return null;282 }283 }284 private String uuid() {285 return java.util.UUID.randomUUID().toString();286 }287 private int sequenceNext = 0;288 private int sequenceNext() {289 return sequenceNext++;290 }291 private String now(String format) {292 Date now = new Date();293 return new SimpleDateFormat(format).format(now);294 }295 private String date(String format, String intervalExpression) {296 int length = intervalExpression.length();297 String intervalString = intervalExpression.trim().substring(0, length - 1);298 String range = intervalExpression.trim().substring(length);299 int amount = Integer.parseInt(intervalString);300 int field = Calendar.DATE;301 if(range.equalsIgnoreCase("d")) {302 field = Calendar.DATE;303 }304 if(range.equalsIgnoreCase("h")) {305 field = Calendar.HOUR;306 }307 if(range.equalsIgnoreCase("s")) {308 field = Calendar.SECOND;309 }310 GregorianCalendar calendar = new GregorianCalendar();311 calendar.setTime(new Date());312 calendar.add(field, amount);313 return new SimpleDateFormat(format).format(calendar.getTime());314 }315 private <T> T firstNotNull(T one, T two) {316 return one != null? one : two;317 }318 private boolean isNotEmpty(String str) {319 return str != null && !str.trim().equals("");320 }321 private static final String UUID = "uuid";322 private static final String SEQUENCE_NEXT = "sequenceNext";323 private static final String NOW = "now";324 private static final String DATE = "date";325}...

Full Screen

Full Screen

method

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.core.ScenarioEngine;2import com.intuit.karate.core.Feature;3import com.intuit.karate.core.FeatureContext;4import com.intuit.karate.core.ScenarioContext;5import com.intuit.karate.core.ScenarioRuntime;6import com.intuit.karate.core.FeatureRuntime;7import com.intuit.karate.core.Scenario;8import com.intuit.karate.core.FeatureRuntimeBuilder;9import com.intuit.karate.core.ScenarioRuntimeBuilder;10import com.intuit.karate.core.ScenarioResult;11import com.intuit.karate.core.FeatureResult;12import com.intuit.karate.core.FeatureResultBuilder;13import com.intuit.karate.core.ScenarioResultBuilder;14import com.intuit.karate.core.FeatureRuntimeBuilder;15import com.intuit.karate.core.ScenarioRuntimeBuilder;16import com.intuit.karate.core.FeatureContext;17import com.intuit.karate.core.ScenarioContext;18import com.intuit.karate.core.FeatureResult;19import com.intuit.karate.core.ScenarioResult;20import com.intuit.karate.core.FeatureResultBuilder;21import com.intuit.karate.core.ScenarioResultBuilder;22import com.intuit.karate.core.FeatureRuntime;23import com.intuit.karate.core.ScenarioRuntime;24import com.intuit.karate.core.Feature;25import com.intuit.karate.core.Scenario;26import java.util.Map;27import java.util.HashMap;28import java.util.List;29import java.util.ArrayList;30import java.util.Arrays;31import java.util.Iterator;32import java.util.Set;33import java.util.HashSet;34import java.util.Collection;35import java.util.Collections;36import java.util.LinkedHashMap;37import java.util.LinkedHashSet;38import java.util.stream.Collectors;39import java.util.function.Consumer;40import java.util.concurrent.TimeUnit;41import java.util.concurrent.Callable;42import java.util.concurrent.Future;43import java.util.concurrent.ExecutorService;44import java.util.concurrent.Executors;45import java.util.concurrent.ExecutionException;46import java.util.concurrent.TimeoutException;47import java.util.concurrent.atomic.AtomicInteger;48import java.util.concurrent.atomic.AtomicBoolean;49import java.util.concurrent.atomic.AtomicReference;50import java.util.concurrent.atomic.AtomicLong;51import java.util.concurrent.atomic.AtomicIntegerArray;52import java.util.concurrent.atomic.AtomicLongArray;53import java.util.concurrent.atomic.AtomicReferenceArray;54import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;55import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;56import java.util.concurrent.atomic.AtomicLong

Full Screen

Full Screen

method

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.core.ScenarioEngine;2import com.intuit.karate.core.Feature;3import com.intuit.karate.core.FeatureResult;4import com.intuit.karate.core.ScenarioResult;5import java.util.List;6import java.io.File;7import java.io.IOException;8import java.util.ArrayList;9import java.util.Arrays;10import java.util.HashMap;11import java.util.Map;12import java.util.concurrent.Callable;13import java.util.concurrent.ExecutorService;14import java.util.concurrent.Executors;15import java.util.concurrent.Future;16import java.util.concurrent.TimeUnit;17public class 4 {18 public static void main(String[] args) throws Exception {19 List<String> features = new ArrayList<>();20 features.add("/home/username/feature1.feature");21 features.add("/home/username/feature2.feature");22 List<String> tags = new ArrayList<>();23 tags.add("@tag1");24 tags.add("@tag2");25 Map<String, Object> env = new HashMap<>();26 env.put("env", "dev");27 List<String> excludeTags = new ArrayList<>();28 excludeTags.add("@tag3");29 excludeTags.add("@tag4");30 Map<String, Object> sysProps = new HashMap<>();31 sysProps.put("sysProp1", "sysProp1Value");32 sysProps.put("sysProp2", "sysProp2Value");33 Map<String, Object> vars = new HashMap<>();34 vars.put("var1", "var1Value");35 vars.put("var2", "var2Value");36 List<String> includeTags = new ArrayList<>();37 includeTags.add("@tag5");38 includeTags.add("@tag6");39 Map<String, Object> sysProps = new HashMap<>();40 sysProps.put("sysProp1", "sysProp1Value");41 sysProps.put("sysProp2", "sysProp2Value");

Full Screen

Full Screen

method

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.core.ScenarioEngine;2import com.intuit.karate.core.Scenario;3import com.intuit.karate.core.Feature;4public class 4 {5 public static void main(String[] args) {6 ScenarioEngine engine = new ScenarioEngine();7 Scenario scenario = engine.scenario("path/to/file.feature", "scenario name");8 scenario.run();9 }10}11import com.intuit.karate.core.FeatureEngine;12import com.intuit.karate.core.Feature;13public class 5 {14 public static void main(String[] args) {15 FeatureEngine engine = new FeatureEngine();16 Feature feature = engine.feature("path/to/file.feature");17 feature.run();18 }19}20import com.intuit.karate.core.Feature;21import com.intuit.karate.core.Scenario;22public class 6 {23 public static void main(String[] args) {24 Feature feature = Feature.read("path/to/file.feature");25 Scenario scenario = feature.getScenario("scenario name");26 scenario.run();27 }28}29import com.intuit.karate.core.Scenario;30public class 7 {31 public static void main(String[] args) {32 Scenario scenario = Scenario.read("path/to/file.feature", "scenario name");33 scenario.run();34 }35}36import com.intuit.karate.core.FeatureBuilder;37import com.intuit.karate.core.Feature;38import com.intuit.karate.core.Scenario;39public class 8 {40 public static void main(String[] args) {41 FeatureBuilder builder = new FeatureBuilder();42 Feature feature = builder.build("path/to/file.feature");43 Scenario scenario = feature.getScenario("scenario name");44 scenario.run();45 }46}47import com.intuit.karate.core.ScenarioBuilder;48import com.intuit.karate.core.Scenario;

Full Screen

Full Screen

method

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.core.ScenarioEngine;2import com.intuit.karate.core.Feature;3import com.intuit.karate.core.FeatureResult;4import com.intuit.karate.core.FeatureRuntime;5import com.intuit.karate.core.FeatureRuntimeOptions;6import java.io.File;7import java.io.IOException;8import java.util.ArrayList;9import java.util.List;10import java.util.Map;11import org.apache.commons.io.FileUtils;12import org.apache.commons.io.FilenameUtils;13import org.apache.commons.lang3.StringUtils;14import org.slf4j.Logger;15import org.slf4j.LoggerFactory;16public class KarateRunner {17 private static final Logger logger = LoggerFactory.getLogger(KarateRunner.class);18 private static final String KARATE_FEATURE_FILE_EXTENSION = "feature";19 private static final String KARATE_FEATURE_FILE_EXTENSION_WITH_DOT = "." + KARATE_FEATURE_FILE_EXTENSION;20 private static final String KARATE_JSON_FILE_EXTENSION = "json";21 private static final String KARATE_JSON_FILE_EXTENSION_WITH_DOT = "." + KARATE_JSON_FILE_EXTENSION;22 private static final String KARATE_HTML_FILE_EXTENSION = "html";23 private static final String KARATE_HTML_FILE_EXTENSION_WITH_DOT = "." + KARATE_HTML_FILE_EXTENSION;24 public static void main(String[] args) throws IOException {25 String featureFilePath = "C:\\Users\\sudheer.kumar\\Desktop\\karate\\karate\\src\\test\\java\\com\\intuit\\karate\\demo\\karate-demo1.feature";

Full Screen

Full Screen

method

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.core.ScenarioEngine;2public class 4{3 public static void main(String[] args) {4 ScenarioEngine.method();5 }6}

Full Screen

Full Screen

method

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.core.ScenarioEngine;2import com.intuit.karate.core.Feature;3import com.intuit.karate.core.FeatureResult;4import java.io.File;5import java.io.IOException;6import java.util.List;7import java.util.Map;8import java.util.HashMap;9import org.slf4j.Logger;10import org.slf4j.LoggerFactory;11public class 4 {12 public static void main(String[] args) {13 try {14 ScenarioEngine engine = new ScenarioEngine();15 Feature feature = new Feature(new File("4.feature"));16 FeatureResult result = new FeatureResult(feature);17 Map<String, Object> vars = new HashMap();18 List<String> tags = new ArrayList();19 engine.executeFeature(feature, result, vars, tags);20 } catch (IOException e) {21 e.printStackTrace();22 }23 }24}25import com.intuit.karate.core.ScenarioEngine;26import com.intuit.karate.core.Feature;27import com.intuit.karate.core.FeatureResult;28import java.io.File;29import java.io.IOException;30import java.util.List;31import java.util.Map;32import java.util.HashMap;33import org.slf4j.Logger;34import org.slf4j.LoggerFactory;35public class 4 {36 public static void main(String[] args) {37 try {38 ScenarioEngine engine = new ScenarioEngine();39 Feature feature = new Feature(new File("4.feature"));40 FeatureResult result = new FeatureResult(feature);41 Map<String, Object> vars = new HashMap();42 List<String> tags = new ArrayList();43 engine.executeFeature(feature, result, vars, tags);44 } catch

Full Screen

Full Screen

method

Using AI Code Generation

copy

Full Screen

1package com.intuit.karate;2import java.util.Map;3public class 4 {4 public static void main(String[] args) {5 ScenarioEngine engine = ScenarioEngine.instance();6 Map<String, Object> result = engine.method("com.intuit.karate.core.ScenarioEngine", "method", "foo", "bar");7 System.out.println(result);8 }9}10{foo=bar}11You can also use the method() method from a JavaScript test. See the example below:12function() {13 var engine = karate.get('engine');14 var result = engine.method('com.intuit.karate.core.ScenarioEngine', 'method', 'foo', 'bar');15 karate.log(result);16}17{foo=bar}18package com.intuit.karate;19import java.util.Map;20public class 6 {21 public static void main(String[] args) {22 ScenarioEngine engine = ScenarioEngine.instance();23 Map<String, Object> result = engine.method("com.intuit.karate.core.ScenarioEngine", "method", "foo", "bar");24 System.out.println(result);25 }26}27{foo=bar}28package com.intuit.karate;29import java.util.Map;30public class 7 {31 public static void main(String[] args) {32 ScenarioEngine engine = ScenarioEngine.instance();33 Map<String, Object> result = engine.method("com.intuit.karate.core.ScenarioEngine", "

Full Screen

Full Screen

method

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.core.ScenarioEngine;2public class 4 {3public static void main(String[] args) {4ScenarioEngine se = new ScenarioEngine();5se.method();6}7}8at 4.main(4.java:8)9at java.net.URLClassLoader.findClass(URLClassLoader.java:381)10at java.lang.ClassLoader.loadClass(ClassLoader.java:424)11at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)12at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

Full Screen

Full Screen

method

Using AI Code Generation

copy

Full Screen

1package com.intuit.karate.core;2import com.intuit.karate.core.ScenarioEngine;3import com.intuit.karate.core.Feature;4import java.io.File;5import java.util.HashMap;6import java.util.Map;7import java.util.List;8import java.util.ArrayList;9import java.util.Iterator;10import com.intuit.karate.core.ScenarioResult;11import com.intuit.karate.core.Scenario;12import com.intuit.karate.core.Feature;13import com.intuit.karate.core.FeatureRuntime;14import java.io.File;15import java.util.HashMap;16import java.util.Map;17import java.util.List;18import java.util.ArrayList;19import java.util.Iterator;20import com.intuit.karate.core.ScenarioResult;21import com.intuit.karate.core.Scenario;22import com.intuit.karate.core.Feature;23import com.intuit.karate.core.FeatureRuntime;24import java.io.File;25import java.util.HashMap;26import java.util.Map;27import java.util.List;28import java.util.ArrayList;29import java.util.Iterator;30import com.intuit.karate.core.ScenarioResult;31import com.intuit.karate.core.Scenario;32import com.intuit.karate.core.Feature;33import com.intuit.karate.core.FeatureRuntime;34import java.io.File;35import java.util.HashMap;36import java.util.Map;37import java.util.List;38import java.util.ArrayList;39import java.util.Iterator;40import com.intuit.karate.core.ScenarioResult;41import com.intuit.karate.core.Scenario;42import com.intuit.karate.core.Feature;43import com.intuit.karate.core.FeatureRuntime;44import java.io.File;45import java.util.HashMap;46import java.util.Map;47import java.util.List;48import java.util.ArrayList;49import java.util.Iterator;50import com.intuit.karate.core.ScenarioResult;51import com.intuit.karate.core.Scenario;52import com.intuit.karate.core.Feature;53import com.intuit.karate.core.FeatureRuntime;54import java.io.File;55import java.util.HashMap;56import java.util.Map;57import java.util.List;58import java.util.ArrayList;59import java.util.Iterator;60import com.intuit.karate.core.ScenarioResult;61import com.intuit.karate.core.Scenario;62import com.intuit.karate.core.Feature;63import com.intuit.karate.core.FeatureRuntime;64import java.io.File;65import java.util.HashMap;66import

Full Screen

Full Screen

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

Run Karate automation tests on LambdaTest cloud grid

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

Most used method in ScenarioEngine

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful