Best Karate code snippet using com.intuit.karate.Http
Source:MockHttpClient.java
...28import static com.intuit.karate.http.Cookie.MAX_AGE;29import static com.intuit.karate.http.Cookie.PATH;30import static com.intuit.karate.http.Cookie.SECURE;31import static com.intuit.karate.http.Cookie.VERSION;32import com.intuit.karate.http.HttpBody;33import com.intuit.karate.http.HttpClient;34import com.intuit.karate.http.HttpConfig;35import com.intuit.karate.http.HttpRequest;36import com.intuit.karate.http.HttpRequestBuilder;37import com.intuit.karate.http.HttpResponse;38import com.intuit.karate.http.HttpUtils;39import com.intuit.karate.http.MultiPartItem;40import com.intuit.karate.http.MultiValuedMap;41import java.io.InputStream;42import java.net.URI;43import java.util.ArrayList;44import java.util.Collections;45import java.util.List;46import java.util.Map;47import java.util.Set;48import java.util.TreeSet;49import java.util.concurrent.atomic.AtomicInteger;50import javax.servlet.Servlet;51import javax.servlet.ServletContext;52import javax.servlet.http.Cookie;53import org.slf4j.Logger;54import org.slf4j.LoggerFactory;55import org.springframework.mock.web.MockHttpServletRequest;56import org.springframework.mock.web.MockHttpServletResponse;57import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;58import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.request;59/**60 *61 * @author pthomas362 */63public abstract class MockHttpClient extends HttpClient<HttpBody> {64 private static final Logger logger = LoggerFactory.getLogger(MockHttpClient.class);65 private URI uri;66 private MockHttpServletRequestBuilder requestBuilder;67 protected abstract Servlet getServlet(HttpRequestBuilder request);68 protected abstract ServletContext getServletContext();69 /**70 * this is guaranteed to be called if the zero-arg constructor is used, so71 * for advanced per-test set-up, over-ride this call-back and retrieve72 * custom data via config.getUserDefined() - refer to the documentation of73 * the 'configure userDefined' keyword74 */75 @Override76 public void configure(HttpConfig config, ScriptContext context) {77 }78 @Override79 protected HttpBody getEntity(List<MultiPartItem> items, String mediaType) {80 return HttpBody.multiPart(items, mediaType);81 }82 @Override83 protected HttpBody getEntity(MultiValuedMap formFields, String mediaType) {84 return HttpBody.formFields(formFields, mediaType);85 }86 @Override87 protected HttpBody getEntity(InputStream stream, String mediaType) {88 return HttpBody.stream(stream, mediaType);89 }90 @Override91 protected HttpBody getEntity(String content, String mediaType) {92 return HttpBody.string(content, mediaType);93 }94 @Override95 protected void buildUrl(String url) {96 String method = request.getMethod();97 try {98 uri = new URI(url);99 requestBuilder = request(method, uri);100 } catch (Exception e) {101 throw new RuntimeException(e);102 }103 }104 @Override105 protected void buildPath(String path) {106 String url = uri.toString();107 if (!url.endsWith("/")) {108 url = url + "/";109 }110 if (path.startsWith("/")) {111 path = path.substring(1);112 }113 buildUrl(url + path);114 }115 @Override116 protected void buildParam(String name, Object... values) {117 List<String> list = new ArrayList<>(values.length);118 for (Object o : values) {119 list.add(o == null ? null : o.toString());120 }121 requestBuilder.param(name, list.toArray(new String[]{}));122 }123 @Override124 protected void buildHeader(String name, Object value, boolean replace) {125 requestBuilder.header(name, value);126 }127 @Override128 protected void buildCookie(com.intuit.karate.http.Cookie c) {129 Cookie cookie = new Cookie(c.getName(), c.getValue());130 requestBuilder.cookie(cookie);131 for (Map.Entry<String, String> entry : c.entrySet()) {132 if (entry.getValue() != null) {133 switch (entry.getKey()) {134 case DOMAIN:135 cookie.setDomain(entry.getValue());136 break;137 case PATH:138 cookie.setPath(entry.getValue());139 break;140 }141 }142 }143 if (cookie.getDomain() == null) {144 cookie.setDomain(uri.getHost());145 }146 }147 @Override148 protected HttpResponse makeHttpRequest(HttpBody entity, ScriptContext context) {149 logger.info("making mock http client request: {} - {}", request.getMethod(), getRequestUri());150 MockHttpServletRequest req = requestBuilder.buildRequest(getServletContext());151 byte[] bytes;152 if (entity != null) {153 bytes = entity.getBytes();154 req.setContentType(entity.getContentType());155 if (entity.isMultiPart()) {156 for (MultiPartItem item : entity.getParts()) {157 MockMultiPart part = new MockMultiPart(item);158 req.addPart(part);159 if (!part.isFile()) {160 req.addParameter(part.getName(), part.getValue());161 }162 }163 } else if (entity.isUrlEncoded()) {164 req.addParameters(entity.getParameters());165 } else {166 req.setContent(bytes);167 }168 } else {169 bytes = null;170 }171 MockHttpServletResponse res = new MockHttpServletResponse();172 logRequest(req, bytes);173 long startTime = System.currentTimeMillis();174 try {175 getServlet(request).service(req, res);176 } catch (Exception e) {177 throw new RuntimeException(e);178 }179 HttpResponse response = new HttpResponse(startTime, System.currentTimeMillis());180 bytes = res.getContentAsByteArray();181 logResponse(res, bytes); 182 response.setUri(getRequestUri());183 response.setBody(bytes);184 response.setStatus(res.getStatus());185 for (Cookie c : res.getCookies()) {186 com.intuit.karate.http.Cookie cookie = new com.intuit.karate.http.Cookie(c.getName(), c.getValue());187 cookie.put(DOMAIN, c.getDomain());188 cookie.put(PATH, c.getPath());189 cookie.put(SECURE, c.getSecure() + "");190 cookie.put(MAX_AGE, c.getMaxAge() + "");191 cookie.put(VERSION, c.getVersion() + "");192 response.addCookie(cookie);193 }194 for (String headerName : res.getHeaderNames()) {195 response.putHeader(headerName, res.getHeaders(headerName));196 }197 return response;198 }199 @Override200 protected String getRequestUri() {201 return uri.toString();202 }203 private final AtomicInteger counter = new AtomicInteger();204 private void logRequest(MockHttpServletRequest req, byte[] bytes) {205 if (!logger.isDebugEnabled()) {206 return;207 }208 int id = counter.incrementAndGet();209 StringBuilder sb = new StringBuilder();210 sb.append('\n').append(id).append(" > ").append(req.getMethod()).append(' ')211 .append(req.getRequestURL()).append('\n');212 logRequestHeaders(sb, id, req);213 logBody(sb, bytes, req.getContentType());214 logger.debug(sb.toString());215 }216 private void logResponse(MockHttpServletResponse res, byte[] bytes) {217 if (!logger.isDebugEnabled()) {218 return;219 }220 int id = counter.get();221 StringBuilder sb = new StringBuilder();222 sb.append('\n').append(id).append(" < ").append(res.getStatus()).append('\n');223 logResponseHeaders(sb, id, res);224 logBody(sb, bytes, res.getContentType());225 logger.debug(sb.toString());226 }227 private static void logRequestHeaders(StringBuilder sb, int id, MockHttpServletRequest request) {228 Set<String> keys = new TreeSet(Collections.list(request.getHeaderNames()));229 for (String key : keys) {230 List<String> entries = Collections.list(request.getHeaders(key));231 sb.append(id).append(' ').append('>').append(' ')232 .append(key).append(": ").append(entries.size() == 1 ? entries.get(0) : entries).append('\n');233 }234 }235 private static void logResponseHeaders(StringBuilder sb, int id, MockHttpServletResponse response) {236 Set<String> keys = new TreeSet(response.getHeaderNames());237 for (String key : keys) {238 List<String> entries = response.getHeaders(key);239 sb.append(id).append(' ').append('<').append(' ')240 .append(key).append(": ").append(entries.size() == 1 ? entries.get(0) : entries).append('\n');241 }242 }243 private static void logBody(StringBuilder sb, byte[] bytes, String contentType) {244 if (bytes != null && HttpUtils.isPrintable(contentType)) {245 sb.append(FileUtils.toString(bytes));246 }247 }248}...
Source:TestRunner.java
...21import com.intuit.karate.core.ScenarioContext;22import com.intuit.karate.core.ScenarioResult;23import com.intuit.karate.core.Step;24import com.intuit.karate.core.StepResult;25import com.intuit.karate.http.HttpRequestBuilder;26import org.apache.commons.io.FileUtils;27import org.junit.Assert;28import org.junit.Test;29import net.masterthought.cucumber.Configuration;30import net.masterthought.cucumber.ReportBuilder;31import net.masterthought.cucumber.sorting.SortingMethod;32public class TestRunner {33 @Test34 public void testParallel() throws Exception {35 String retryPath = System.getProperty("user.dir") + "/target/test-classes/features";36 int retryCount = 3;37 // Run parallelly and retry according to retry count38 Results result = Runner.path("classpath:features").hook(new KarateExecutionHook()).tags("~@ignore")39 .parallel(10);40 if (result.getFailCount() > 0) {41 for (int i = 0; i < retryCount; i++) {42 PrintWriter pw = new PrintWriter(System.getProperty("user.dir") + "/target/karate.log");43 pw.close();44 System.out.println("====Retrying test====");45 result = Runner.path(retryPath).hook(new KarateExecutionHook()).tags("@retry","~@ignore").parallel(10);46 if(result.getFailCount() == 0)47 break;48 }49 }50 Assert.assertTrue(result.getErrorMessages(), result.getFailCount() == 0);51 }52 public static void generateReport(String karateOutputPath) throws Exception {53 Collection<File> jsonFiles = FileUtils.listFiles(new File(karateOutputPath), new String[] { "json" }, true);54 List<String> jsonPaths = new ArrayList<>(jsonFiles.size());55 jsonFiles.forEach(file -> jsonPaths.add(file.getAbsolutePath()));56 Configuration config = new Configuration(new File("target"), "karate-graphql");57 config.setSortingMethod(SortingMethod.ALPHABETICAL);58 ReportBuilder reportBuilder = new ReportBuilder(jsonPaths, config);59 reportBuilder.generateReports();60 }61}62class KarateExecutionHook implements ExecutionHook {63 @Override64 public boolean beforeScenario(Scenario scenario, ScenarioContext context) {65 return true;66 }67 @Override68 public void afterScenario(ScenarioResult result, ScenarioContext context) {69 }70 @Override71 public boolean beforeFeature(Feature feature, ExecutionContext context) {72 return true;73 }74 @Override75 public void afterFeature(FeatureResult result, ExecutionContext context) {76 File f = null;77 f = context.featureContext.feature.getPath().toFile();78 String filePath = f.toString();79 int line = 0;80 Path path = Paths.get(filePath);81 if (result.isFailed()) {82 try {83 String annotation = Files.readAllLines(path).get(line);84 if (!annotation.contains("@retry")) {85 List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);86 lines.add(line, "@retry");87 Files.write(path, lines, StandardCharsets.UTF_8);88 }89 } catch (Exception e) {90 e.printStackTrace();91 }92 } else {93 try {94 Charset charset = StandardCharsets.UTF_8;95 String content = new String(Files.readAllBytes(path), charset);96 String pattern = "@retry";97 content = content.replaceAll(pattern, "");98 Files.write(path, content.getBytes(charset));99 } catch (Exception e) {100 e.printStackTrace();101 }102 }103 }104 @Override105 public void beforeAll(Results results) {106 }107 @Override108 public void afterAll(Results results) {109 }110 @Override111 public boolean beforeStep(Step step, ScenarioContext context) {112 if (step.getText().trim().contains("request {")) {113 try {114 File dir = new File("GQL-Requests");115 dir.mkdirs();116 String rawQuery = context.vars.get("query").getValue().toString();117 String[] splittedQuery = rawQuery.split("\n", 2);118 String firstLineQuery = splittedQuery[0];119 String queryName = firstLineQuery.replace("query", "").replace("mutation", "")120 .replaceAll("\\(.*?\\{", "").replaceAll(" ", "") + ".graphql";121 File file = new File(dir, queryName);122 FileWriter myWriter = new FileWriter(file);123 myWriter.write(context.vars.get("query").getValue().toString());124 myWriter.close();125 } catch (IOException e) {126 e.printStackTrace();127 }128 }129 return true;130 }131 @Override132 public void afterStep(StepResult result, ScenarioContext context) {133 }134 @Override135 public String getPerfEventName(HttpRequestBuilder req, ScenarioContext context) {136 return null;137 }138 @Override139 public void reportPerfEvent(PerfEvent event) {140 }141}...
Source:KarateRuntimeOwn.java
...9import com.intuit.karate.cucumber.KarateBackend;10import com.intuit.karate.cucumber.KarateReporter;11import com.intuit.karate.cucumber.KarateRuntimeOptions;12import com.intuit.karate.cucumber.StepResult;13import com.intuit.karate.http.HttpConfig;14import cucumber.runtime.CucumberScenarioImpl;15import cucumber.runtime.CucumberStats;16import cucumber.runtime.Runtime;17import cucumber.runtime.RuntimeGlue;18import gherkin.I18n;19import gherkin.formatter.Reporter;20import gherkin.formatter.model.Match;21import gherkin.formatter.model.Result;22import gherkin.formatter.model.Scenario;23import gherkin.formatter.model.Step;24import gherkin.formatter.model.Tag;25public class KarateRuntimeOwn extends Runtime {26 private final KarateBackend backend;27 private final CucumberStats stats;28 private CucumberScenarioImpl scenarioResult;29 private boolean stopped;30 private boolean aborted;31 private ScriptContext prevContext;32 public KarateRuntimeOwn(KarateRuntimeOptionsOwn kro, KarateBackend backend, RuntimeGlue glue) {33 super(kro.getResourceLoader(), kro.getClassLoader(), Collections.singletonList(backend), kro.getRuntimeOptions(), glue);34 this.backend = backend;35 this.stats = new CucumberStats(kro.getRuntimeOptions().isMonochrome());36 }37 38 public Logger getLogger() {39 return backend.getEnv().logger;40 }41 private void addStepToCounterAndResult(Result result) {42 scenarioResult.add(result);43 stats.addStep(result);44 }45 @Override46 public void runStep(String featurePath, Step step, Reporter reporter, I18n i18n) {47 if (stopped) {48 Match match = Match.UNDEFINED;49 Result result = aborted ? StepResult.PASSED : Result.SKIPPED;50 if (reporter instanceof KarateReporter) { // simulate cucumber flow to keep json-formatter happy 51 ((KarateReporter) reporter).karateStep(step, match, result, backend.getCallContext(), backend.getStepDefs().getContext());52 }53 reporter.match(match);54 addStepToCounterAndResult(result);55 reporter.result(result);56 return;57 }58 StepResult result = CucumberUtils.runStep(step, reporter, i18n, backend);59 if (!result.isPass() || result.isAbort()) {60 if (!result.isAbort()) {61 addError(result.getError());62 backend.setScenarioError(result.getError());63 }64 prevContext = backend.getStepDefs().getContext();65 stopped = true; // skip remaining steps66 aborted = result.isAbort(); // if skipped steps are to be marked as PASSED67 }68 addStepToCounterAndResult(result.getResult());69 }70 @Override71 public void buildBackendWorlds(Reporter reporter, Set<Tag> tags, Scenario scenario) {72 backend.buildWorld();73 // tags only work at top-level, this does not apply to 'called' features74 CucumberUtils.resolveTagsAndTagValues(backend, tags);75 // 'karate.info' also does not apply to 'called' features76 CucumberUtils.initScenarioInfo(scenario, backend);77 scenarioResult = new CucumberScenarioImpl(reporter, tags, scenario);78 }79 @Override80 public void disposeBackendWorlds(String scenarioDesignation) {81 stats.addScenario(scenarioResult.getStatus(), scenarioDesignation);82 prevContext = backend.getStepDefs().getContext();83 invokeAfterHookIfConfigured(false);84 backend.disposeWorld();85 stopped = false; // else a failed scenario results in all remaining ones in the feature being skipped !86 }87 @Override88 public void printSummary() {89 stats.printStats(System.out, false);90 } 91 92 public void afterFeature() {93 invokeAfterHookIfConfigured(true);94 }95 96 private void invokeAfterHookIfConfigured(boolean afterFeature) {97 if (prevContext == null) { // edge case where there are zero scenarios, e.g. only a Background:98 ScriptEnv env = backend.getEnv();99 env.logger.warn("no runnable scenarios found: {}", env);100 return;101 }102 HttpConfig config = prevContext.getConfig();103 ScriptValue sv = afterFeature ? config.getAfterFeature() : config.getAfterScenario();104 if (sv.isFunction()) {105 try {106 sv.invokeFunction(prevContext);107 } catch (Exception e) {108 String prefix = afterFeature ? "afterFeature" : "afterScenario";109 prevContext.logger.warn("{} hook failed: {}", prefix, e.getMessage());110 }111 }112 }113}...
Source:KarateRunnerTest.java
...4import com.intuit.karate.RuntimeHook;5import com.intuit.karate.StringUtils;6import com.intuit.karate.cli.IdeMain;7import com.intuit.karate.core.ScenarioRuntime;8import com.intuit.karate.http.HttpRequest;9import com.intuit.karate.http.Response;10import org.junit.Assert;11import org.junit.Test;12import java.io.File;13import java.io.IOException;14import java.nio.file.Files;15import java.nio.file.Paths;16import java.nio.file.StandardCopyOption;17import java.util.ArrayList;18import java.util.Arrays;19import java.util.Collection;20import java.util.List;21import java.util.Optional;22import java.util.stream.Collectors;23public class KarateRunnerTest {24 private String classpath = "classpath:apis/";25 @Test26 public void run() throws Exception {27 String karateEnv = defaultString(System.getProperty("karate.env"), "local").toLowerCase();28 String launchCommand = defaultString(System.getProperty("KARATE_OPTIONS"), "-t ~@ignore " + classpath);29 com.intuit.karate.Main options = IdeMain.parseIdeCommandLine(launchCommand);30 Results results = Runner.path(Optional.ofNullable(options.getPaths()).orElse(Arrays.asList(classpath)))31 .hook(coverageRuntimeHook)32 .tags(options.getTags())33 .configDir(options.getConfigDir())34 .karateEnv(karateEnv)35 .outputHtmlReport(true)36 .outputCucumberJson(true)37 .outputJunitXml(true)38 .parallel(options.getThreads());39 moveJUnitReports(results.getReportDir(), "target/surefire-reports");40 // here you can analyze/process coverage41 System.out.println("SUCCESS ENDPOINTS");42 System.out.println(StringUtils.join(httpCalls, "\n"));43 System.out.println("FAILED ENDPOINTS");44 System.out.println(StringUtils.join(failedHttpCalls, "\n"));45 // Assert.assertEquals(0, results.getFailCount());46 }47 48 public static void moveJUnitReports(String karateReportDir, String surefireReportDir) throws IOException {49 new File(surefireReportDir).mkdirs();50 Collection<File> xmlFiles = Files.find(Paths.get(karateReportDir), Integer.MAX_VALUE,51 (filePath, fileAttr) -> fileAttr.isRegularFile() && filePath.toString().endsWith(".xml"))52 .map(p -> p.toFile()).collect(Collectors.toList());53 xmlFiles.forEach((x) -> {54 try {55 Files.copy(x.toPath(), Paths.get(surefireReportDir, "/TEST-" + x.getName()), StandardCopyOption.REPLACE_EXISTING);56 } catch (IOException var3) {57 var3.printStackTrace();58 }59 });60 }61 List<String> httpCalls = new ArrayList<>();62 List<String> failedHttpCalls = new ArrayList<>();63 private RuntimeHook coverageRuntimeHook = new RuntimeHook() {64 List<String> scenarioHttpCalls = null;65 @Override66 public boolean beforeScenario(ScenarioRuntime sr) {67 scenarioHttpCalls = new ArrayList<>();68 return true;69 }70 @Override71 public void afterHttpCall(HttpRequest request, Response response, ScenarioRuntime sr) {72 scenarioHttpCalls.add(String.format("%s %s %s", request.getMethod(), request.getUrl(), response.getStatus()));73 }74 @Override75 public void afterScenario(ScenarioRuntime sr) {76 (sr.isFailed()? failedHttpCalls : httpCalls).addAll(scenarioHttpCalls);77 }78 };79 private String defaultString(String value, String defaultValue) {80 return value == null ? defaultValue : value;81 }82}...
Source:VerifyMocksTest.java
...3import com.intuit.karate.Runner;4import com.intuit.karate.RuntimeHook;5import com.intuit.karate.cli.IdeMain;6import com.intuit.karate.core.ScenarioRuntime;7import com.intuit.karate.http.HttpRequest;8import com.intuit.karate.http.Response;9import io.github.apimock.MockServer;10import org.junit.AfterClass;11import org.junit.BeforeClass;12import org.junit.Test;13import java.util.ArrayList;14import java.util.Arrays;15import java.util.HashMap;16import java.util.List;17import java.util.Map;18import java.util.Optional;19import static com.intuit.karate.StringUtils.join;20public class VerifyMocksTest {21 static io.github.apimock.MockServer server;22 static Map<String, List> httpCallsMap = new HashMap<>();23 @BeforeClass24 public static void setup() throws Exception {25 server = MockServer.builder()26 .openapi("petstore-openapi.yml")27 .features("classpath:mocks/PetMock.feature")28 .pathPrefix("api/v3")29 .http(0).build();30 System.setProperty("karate.server.port", server.getPort() + "");31 }32 @AfterClass33 public static void tearDown() throws Exception {34 server.stop();35 // Here you can verify how your mock behaves compared to the live API and calculate the quality and coverage of your mocks36 System.out.println("Successful Http Calls to API Server:\n\t" + join(httpCallsMap.get("HttpCalls"), "\n\t"));37 System.out.println("Failed Http Calls to API Server:\n\t" + join(httpCallsMap.get("FailedHttpCalls"), "\n\t"));38 System.out.println("Successful Http Calls to Mock Server:\n\t" + join(httpCallsMap.get("mockHttpCalls"), "\n\t"));39 System.out.println("Failed Http Calls to Mock Server:\n\t" + join(httpCallsMap.get("mockFailedHttpCalls"), "\n\t"));40 }41 @Test42 public void verifyMockServer() throws Exception {43 verifyMocks("mock");44 }45 @Test46 public void verifyAPIServer() throws Exception {47 verifyMocks("");48 }49 public void verifyMocks(String karateEnv) throws Exception {50 CoverageRuntimeHook coverageRuntimeHook = new CoverageRuntimeHook();51 Results results = Runner.path(Arrays.asList("classpath:/mocks"))52 .hook(coverageRuntimeHook)53 .tags("@mock-validation")54 .karateEnv(karateEnv)55 .parallel(1);56 httpCallsMap.put(karateEnv + "HttpCalls", coverageRuntimeHook.httpCalls);57 httpCallsMap.put(karateEnv + "FailedHttpCalls", coverageRuntimeHook.failedHttpCalls);58 }59 /**60 * Accumulates successful and failed http calls.61 */62 private class CoverageRuntimeHook implements RuntimeHook {63 List<String> httpCalls = new ArrayList<>();64 List<String> failedHttpCalls = new ArrayList<>();65 List<String> scenarioHttpCalls = null;66 @Override67 public boolean beforeScenario(ScenarioRuntime sr) {68 scenarioHttpCalls = new ArrayList<>();69 return true;70 }71 @Override72 public void afterHttpCall(HttpRequest request, Response response, ScenarioRuntime sr) {73 scenarioHttpCalls.add(String.format("%s %s %s", request.getMethod(), request.getUrl(), response.getStatus()));74 }75 @Override76 public void afterScenario(ScenarioRuntime sr) {77 (sr.isFailed()? failedHttpCalls : httpCalls).addAll(scenarioHttpCalls);78 }79 };80}...
Source:MandatoryTagHook.java
...9import com.intuit.karate.core.ScenarioContext;10import com.intuit.karate.core.ScenarioResult;11import com.intuit.karate.core.Step;12import com.intuit.karate.core.StepResult;13import com.intuit.karate.http.HttpRequestBuilder;14/**15 *16 * @author pthomas317 */18public class MandatoryTagHook implements ExecutionHook {19 String Status, Error, Tags;20 public static InfluxDBCall influxDB = new InfluxDBCall();21 @Override22 public boolean beforeScenario(Scenario scenario, ScenarioContext context) {23 24 return true;25 }26 @Override27 public void afterScenario(ScenarioResult result, ScenarioContext context) {28 29 if(result.isFailed()) {30 Status = "Failed";31 }32 else {33 Status = "Passed";34 }35 36 if(result.getError()== null) {37 Error = "No Error";38 }39 else {40 Error = result.getError().toString();41 }42 43 Tags="";44 if(result.getScenario().getTags()== null) {45 Tags = "No Tags";46 }47 else {48 for(int z=0; z<result.getScenario().getTags().size(); z++) {49 50 Tags = Tags+result.getScenario().getTags().get(z)+",";51 }52 Tags = Tags.substring(0,Tags.length()-1);53 }54 55 influxDB.DBwrite(result.getScenario().getFeature().getName().trim(),56 Tags,57 result.getScenario().getName().trim(),58 context.getRequestBuilder().getUrlAndPath().trim(),59 Status, Error);60 61 System.out.println("This is into Hook, Feature Name is "+ result.getScenario().getFeature().getName());62 System.out.println("This is into Hook, scenario tags is "+ Tags);63 System.out.println("This is into Hook, scenario name is "+ result.getScenario().getName());64 System.out.println("This is into Hook, scenario EndPoint is "+ context.getRequestBuilder().getUrlAndPath());65 System.out.println("This is into Hook, scenario Method type is "+ context.getPrevRequest().getMethod());66 System.out.println("This is into Hook, scenario status is "+ Status);67 System.out.println("This is into Hook, scenario Error is "+ Error);68 } 69 @Override70 public boolean beforeFeature(Feature feature, ExecutionContext context) {71 return true;72 }73 @Override74 public void afterFeature(FeatureResult result, ExecutionContext context) {75 76 } 77 @Override78 public void beforeAll(Results results) {79 80 influxDB.DBConnection("http://localhost:8086", "root", "root");81 }82 @Override83 public void afterAll(Results results) {84 85 influxDB.connectionClose();86 } 87 @Override88 public boolean beforeStep(Step step, ScenarioContext context) {89 return true;90 }91 @Override92 public void afterStep(StepResult result, ScenarioContext context) {93 } 94 95 @Override96 public String getPerfEventName(HttpRequestBuilder req, ScenarioContext context) {97 return null;98 } 99 100 @Override101 public void reportPerfEvent(PerfEvent event) {102 103 104 }105}...
Http
Using AI Code Generation
1import com.intuit.karate.KarateOptions;2import com.intuit.karate.junit4.Karate;3import cucumber.api.CucumberOptions;4import org.junit.runner.RunWith;5@RunWith(Karate.class)6@KarateOptions(features = "classpath:com/intuit/karate/http/4.feature")7public class 4Runner {8}9 * def request = { "name": "morpheus", "job": "leader" }10{11 {12 "id": "4;4",13 {14 "id": "4;4;1",15 "match": {16 "location": "com.intuit.karate.StepDefs.url(java.lang.String)"17 },18 "result": {19 }20 },21 {22 "id": "4;4;2",23 "name": "def request = { \"name\": \"morpheus\", \"job\": \"leader\" }",24 "match": {25 "location": "com.intuit.karate.StepDefs.def(java.lang.String,java.lang.Object)"26 },27 "result": {28 }29 },30 {31 "id": "4;4;3",32 "match": {33 "location": "com.intuit.karate.StepDefs.def(java.lang.String,java.lang.Object)"34 },35 "result": {
Http
Using AI Code Generation
1import com.intuit.karate.http.Http;2import com.intuit.karate.http.HttpResponse;3import com.intuit.karate.http.HttpRequest;4import com.intuit.karate.http.HttpMethod;5import com.intuit.karate.http.HttpConfig;6import com.intuit.karate.http.HttpUtils;7Http http = HttpUtils.http();8HttpConfig config = HttpUtils.config();9config.setFollowRedirects(true);10config.addHeader("Accept", "application/json");11http.setConfig(config);12HttpRequest request = HttpUtils.request();13request.setMethod(HttpMethod.GET);14request.addHeader("Accept", "application/json");15HttpResponse response = http.call(request);16Http http = HttpUtils.http();17Http http = HttpUtils.http();18Http http = HttpUtils.http();19Http http = HttpUtils.http();20Http http = HttpUtils.http();
Http
Using AI Code Generation
1package demo;2import com.intuit.karate.junit5.Karate;3class MyRunner {4 Karate testUsers() {5 return Karate.run("users").relativeTo(getClass());6 }7}8package demo;9import com.intuit.karate.junit5.Karate;10class MyRunner {11 Karate testUsers() {12 return Karate.run("users").relativeTo(getClass());13 }14}15package demo;16import com.intuit.karate.junit5.Karate;17class MyRunner {18 Karate testUsers() {19 return Karate.run("users").relativeTo(getClass());20 }21}22package demo;23import com.intuit.karate.junit5.Karate;24class MyRunner {25 Karate testUsers() {26 return Karate.run("users").relativeTo(getClass());27 }28}29package demo;30import com.intuit.karate.junit5.Karate;31class MyRunner {32 Karate testUsers() {33 return Karate.run("users").relativeTo(getClass());34 }35}36package demo;37import com.intuit.karate.junit5.Karate;38class MyRunner {39 Karate testUsers() {40 return Karate.run("users").relativeTo(getClass());41 }42}43package demo;44import com.intuit.karate.junit5.Karate;45class MyRunner {46 Karate testUsers() {47 return Karate.run("users").relativeTo(getClass());48 }49}50package demo;51import com.intuit.k
Http
Using AI Code Generation
1import com.intuit.karate.gatling.PreDef._2import io.gatling.core.Predef._3import io.gatling.http.Predef._4class LoadTest extends Simulation {5 .acceptHeader("application/json")6 .contentTypeHeader("application/json")7 val scn = scenario("LoadTest")8 .exec(karateFeature("classpath:4.feature"))9 setUp(scn.inject(atOnceUsers(1))).protocols(httpProtocol)10}11 * def request = read('classpath:4.json')12{13}14import io.gatling.core.Predef._15import io.gatling.http.Predef._16import scala.concurrent.duration._17class LoadTest extends Simulation {18 .acceptHeader("application/json")19 .contentTypeHeader("application/json")20 val scn = scenario("LoadTest")21 .repeat(100) {22 exec(http("4")23 .post("/4")24 .body(StringBody("""{"id":"4","name":"4","description":"4","price":4}""")).asJson25 .check(status.is(200)))26 }27 setUp(scn.inject(rampUsers(100) during (10 seconds))).protocols(httpProtocol)28}29import io.gatling.core.Predef._30import io.gatling.http.Predef._31import scala.concurrent.duration._32class LoadTest extends Simulation {33 .acceptHeader("application/json")34 .contentTypeHeader("application/json")35 val scn = scenario("LoadTest")36 .exec(http("4")37 .post("/4")38 .body(StringBody("""{"id":"4","name":"4","description":"4","price":4}""")).asJson39 .check(status.is(200)))
Http
Using AI Code Generation
1import com.intuit.karate.*; 2import com.intuit.karate.http.*; 3import com.intuit.karate.http.Http; 4import com.intuit.karate.http.HttpResponse; 5import com.intuit.karate.http.HttpRequest; 6import com.intuit.karate.http.HttpMethod; 7import com.intuit.karate.http.HttpConfig; 8import com.intuit.karate.http.HttpUtils; 9import com.intuit.karate.http.HttpUtils; 10import java.util.Map; 11import java.util.HashMap; 12import java.util.List; 13import java.util.ArrayList; 14import java.util.Arrays; 15import java.util.Iterator; 16import java.util.Set; 17import java.util.HashSet; 18import java.util.Collections; 19import java.util.Comparator; 20import java.util.concurrent.atomic.AtomicInteger; 21import java.util.concurrent.atomic.AtomicLong; 22import java.util.concurrent.atomic.AtomicBoolean; 23import java.util.concurrent.TimeUnit; 24import java.util.concurrent.Callable; 25import java.util.concurrent.ExecutorService; 26import java.util.concurrent.Executors; 27import java.util.concurrent.Future; 28import java.util.concurrent.ThreadFactory; 29import java.util.concurrent.ThreadPoolExecutor; 30import java.util.concurrent.LinkedBlockingQueue; 31import java.util.concurrent.atomic.AtomicInteger; 32import java.util.concurrent.atomic.AtomicLong; 33import java.util.concurrent.atomic.AtomicBoolean; 34import java.util.concurrent.ThreadLocalRandom; 35import java.util.concurrent.Semaphore; 36import java.util.concurrent.ConcurrentHashMap; 37import java.util.concurrent.ConcurrentMap; 38import java.util.concurrent.ConcurrentLinkedQueue; 39import java.util.concurrent.ConcurrentLinkedDeque; 40import java.util.concurrent.ConcurrentSkipListSet; 41import java.util.concurrent.ConcurrentSkipListMap; 42import java.util.concurrent.CountDownLatch; 43import java.util.concurrent.CyclicBarrier; 44import java.util.concurrent.locks.ReentrantLock; 45import java.util.concurrent.locks.ReentrantReadWriteLock; 46import java.util.concurrent.locks.Lock; 47import java.util.concurrent.locks.ReadWriteLock; 48import java.util.concurrent.locks.Condition; 49import java.util.concurrent.locks.LockSupport; 50import java.util.concurrent.locks.AbstractQueuedSynchronizer; 51import java.util.concurrent.locks.StampedLock; 52import java.util.concurrent.atomic.AtomicReference; 53import java.util.concurrent.atomic.AtomicIntegerArray; 54import java.util.concurrent.atomic.AtomicLongArray; 55import java.util.concurrent.atomic.AtomicReferenceArray; 56import
Http
Using AI Code Generation
1import com.intuit.karate.junit4.Karate;2import org.junit.runner.RunWith;3@RunWith(Karate.class)4public class 4 {5}6 * def request = read('classpath:4.json')7 * def response = post('4', request)8{9 { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },10 { "name":"BMW", "models":[ "320", "X3", "X5" ] },11 { "name":"Fiat", "models":[ "500", "Panda" ] }12}13 * def request = read('classpath:4.json')14 * def response = post('4', request)15 * match response.jsonPath('$.cars[0].models[1]') == 'Focus'16 * def request = read('classpath:4.json')17 * def response = post('4', request)18 * match response.jsonPath('$.cars[0].models[1]') == 'Focus'19 * match response.jsonPath('$.cars[0].name') == 'Ford'20 * def request = read('classpath:4.json')21 * def response = post('4', request)22 * match response.jsonPath('$.cars[0].models[1]') == 'Focus'23 * match response.jsonPath('$.cars[0].name') == 'Ford'
Http
Using AI Code Generation
1import com.intuit.karate.http.Http;2import java.util.Map;3public class 4 {4public static void main(String[] args) {5System.out.println(request);6}7}8import com.intuit.karate.http.Http;9import java.util.Map;10public class 5 {11public static void main(String[] args) {12System.out.println(request);13}14}15import com.intuit.karate.http.Http;16import java.util.Map;17public class 6 {18public static void main(String[] args) {19System.out.println(request);20}21}22import com.intuit.karate.http.Http;23import java.util.Map;24public class 7 {25public static void main(String[] args) {26System.out.println(request);27}28}29import com.intuit.karate.http.Http;30import java.util.Map;31public class 8 {32public static void main(String[] args) {33System.out.println(request);34}35}
Http
Using AI Code Generation
1import com.intuit.karate.Http;2import com.intuit.karate.MatchType;3import com.intuit.karate.KarateOptions;4import com.intuit.karate.Results;5import com.intuit.karate.Runner;6import java.util.ArrayList;7import java.util.List;8import java.util.Map;9import org.junit.jupiter.api.Test;10import static org.junit.jupiter.api.Assertions.*;11import org.junit.jupiter.api.BeforeAll;12import org.junit.jupiter.api.BeforeEach;13import org.junit.jupiter.api.AfterAll;14import org.junit.jupiter.api.AfterEach;15public class TestRunner {16 public void testParallel() {17 Results results = Runner.path("classpath:karate")18 .tags("~@ignore")19 .outputCucumberJson(true)20 .parallel(5);21 assertEquals(0, results.getFailCount(), results.getErrorMessages());22 }23}24public class TestRunner {25 public void testParallel() {26 Results results = Runner.path("classpath:karate")27 .tags("~@ignore")28 .outputCucumberJson(true)29 .parallel(5);30 assertEquals(0, results.getFailCount(), results.getErrorMessages());31 }32}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!