How to use methodIs method of com.intuit.karate.core.MockHandler class

Best Karate code snippet using com.intuit.karate.core.MockHandler.methodIs

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

methodIs

Using AI Code Generation

copy

Full Screen

1 def mockHandler = new com.intuit.karate.core.MockHandler()2 def mockRequest = new com.intuit.karate.core.MockRequest()3 mockHandler.methodIs(mockRequest)4 mockHandler.methodIs('GET')5 mockHandler.pathIs('/test')6 mockHandler.pathIs('/test', '/test2')7 mockHandler.bodyContains('body')8 mockHandler.bodyContains('body', 'body2')9 mockHandler.bodyContains('body', 'body2', 'body3')10 mockHandler.bodyContains('body', 'body2', 'body3', 'body4')11 mockHandler.headerContains('Content-Type', 'application/json')12 mockHandler.headerContains('Content-Type', 'application/json', 'application/json2')13 mockHandler.headerContains('Content-Type', 'application/json', 'application/json2', 'application/json3')14 mockHandler.headerContains('Content-Type', 'application/json', 'application/json2', 'application/json3', 'application/json4')15 mockHandler.headerContains('Content-Type', 'application/json', 'application/json2', 'application/json3', 'application/json4', 'application/json5')16 mockHandler.headerContains('Content-Type', 'application/json', 'application/json2', 'application/json3', 'application/json4', 'application/json5', 'application/json6')17 mockHandler.headerContains('Content-Type', 'application/json', 'application/json2', 'application/json3', 'application/json4', 'application/json5', 'application/json6', 'application/json7')18 mockHandler.headerContains('Content-Type', 'application/json', 'application/json2', 'application/json3', 'application/json4', 'application/json5', 'application/json6', 'application/json7', 'application/json8')19 mockHandler.headerContains('Content-Type', 'application/json', 'application/json2', 'application/json3', 'application/json4', 'application/json5', 'application/json6', 'application/json7', 'application/json8', 'application/json9')20 mockHandler.headerContains('Content-Type', 'application/json', 'application/json2', 'application/json3', 'application/json4', 'application/json5', 'application/json6', 'application/json

Full Screen

Full Screen

methodIs

Using AI Code Generation

copy

Full Screen

1* def mockHandler = new com.intuit.karate.core.MockHandler()2* def methodIsGet = mockHandler.methodIs('GET')3* def methodIsPost = mockHandler.methodIs('POST')4* def mockHandler = new com.intuit.karate.core.MockHandler()5* def methodIsPost = mockHandler.methodIs('POST')6* def mockHandler = new com.intuit.karate.core.MockHandler()7* def methodIsPut = mockHandler.methodIs('PUT')8* def mockHandler = new com.intuit.karate.core.MockHandler()9* def methodIsDelete = mockHandler.methodIs('DELETE')10* def mockHandler = new com.intuit.karate.core.MockHandler()11* def methodIsPatch = mockHandler.methodIs('PATCH')12* def mockHandler = new com.intuit.karate.core.MockHandler()13* def methodIsHead = mockHandler.methodIs('HEAD')14* def mockHandler = new com.intuit.karate.core.MockHandler()15* def methodIsOptions = mockHandler.methodIs('OPTIONS')

Full Screen

Full Screen

methodIs

Using AI Code Generation

copy

Full Screen

1 * def mockHandler = com.intuit.karate.core.MockHandler()2 * def mock = mockHandler.mock(com.intuit.karate.core.MockHandlerTest)3 * mock.methodIs('mockMethod', 'mocked method')4 * match mock.mockMethod() == 'mocked method'5 * def mockHandler = com.intuit.karate.core.MockHandler()6 * def mock = mockHandler.mock(com.intuit.karate.core.MockHandlerTest)7 * mock.methodIs('mockMethod', 'mocked method', 'arg1')8 * match mock.mockMethod('arg1') == 'mocked method'9 * def mockHandler = com.intuit.karate.core.MockHandler()10 * def mock = mockHandler.mock(com.intuit.karate.core.MockHandlerTest)11 * mock.methodIs('mockMethod', 'mocked method', 'arg1')12 * match mock.mockMethod('arg1') == 'mocked method'13 * def mockHandler = com.intuit.karate.core.MockHandler()14 * def mock = mockHandler.mock(com.intuit.karate.core.MockHandlerTest)15 * mock.methodIs('mockMethod', 'mocked method', 'arg1')16 * match mock.mockMethod('arg1') == 'mocked method'17 * def mockHandler = com.intuit.karate.core.MockHandler()18 * def mock = mockHandler.mock(com.intuit.karate.core.MockHandlerTest)

Full Screen

Full Screen

methodIs

Using AI Code Generation

copy

Full Screen

1def mockHandler = karate.getMockHandler()2def isPost = mockHandler.methodIs('POST')3if(isPost){4}5def isUsers = mockHandler.pathIs('/users')6if(isUsers){7}8def isUsers1 = mockHandler.pathIs('/users/1')9if(isUsers1){10}11def isUsers = mockHandler.pathStartsWith('/users')12if(isUsers){13}14def isUsers1 = mockHandler.pathEndsWith('/1')15if(isUsers1){16}17def isUsers = mockHandler.pathContains('/users')18if(isUsers){19}20def isName = mockHandler.queryParamIs('name')21if(isName){22}23def isName = mockHandler.queryParamIs('name', 'John')24if(isName){25}26def isName = mockHandler.queryParamIs('name', ['John', 'Doe'])27if(isName){28}

Full Screen

Full Screen

methodIs

Using AI Code Generation

copy

Full Screen

1def mockHandler = new com.intuit.karate.core.MockHandler()2def response = mockHandler.methodIs('com.intuit.karate.core.MockHandler', 'methodIs', ['java.lang.String', 'java.lang.String', 'java.lang.Object[]'], ['com.intuit.karate.core.MockHandler', 'methodIs', ['java.lang.String', 'java.lang.String', 'java.lang.Object[]']])3def mockHandler = new com.intuit.karate.core.MockHandler()4def response = mockHandler.methodIs('com.intuit.karate.core.MockHandler', 'methodIs', ['java.lang.String', 'java.lang.String', 'java.lang.Object[]'], ['com.intuit.karate.core.MockHandler', 'methodIs', ['java.lang.String', 'java.lang.String', 'java.lang.Object[]']])5def mockHandler = new com.intuit.karate.core.MockHandler()6def response = mockHandler.methodIs('com.intuit.karate.core.MockHandler', 'methodIs', ['java.lang.String', 'java.lang.String', 'java.lang.Object[]'], ['com.intuit.karate.core.MockHandler', 'methodIs', ['java.lang.String', 'java.lang.String', 'java.lang.Object[]']])7def mockHandler = new com.intuit.karate.core.MockHandler()8def response = mockHandler.methodIs('com.intuit

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