Best Karate code snippet using com.intuit.karate.http.Request
Source:MockHttpClient.java
...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 }...
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}...
Request
Using AI Code Generation
1import com.intuit.karate.http.HttpResponse;2import com.intuit.karate.http.Request;3import com.intuit.karate.http.Response;4Request request = Request.builder()5 .build();6Response response = request.get();7System.out.println("Response code: " + response.getStatus());8System.out.println("Response body: " + response.getBodyAsString());9Response body: {"message":"Hello World!"}10Request request = Request.builder()11 .build();12Response response = request.get();13System.out.println("Response code: " + response.getStatus());14System.out.println("Response body: " + response.getBodyAsString());15Response body: {"message":"Hello World!"}16Request request = Request.builder()17 .build();18Response response = request.get();19System.out.println("Response code: " + response.getStatus());20System.out.println("Response body: " + response.getBodyAsString());21Response body: {"message":"Hello World!"}22Request request = Request.builder()23 .build();24Response response = request.get();25System.out.println("Response code: " + response.getStatus());26System.out.println("Response body: " + response.getBodyAsString());27Response body: {"message":"Hello World!"}28Request request = Request.builder()29 .build();30Response response = request.get();31System.out.println("Response code: " + response.getStatus());32System.out.println("Response body: " + response.getBodyAsString());33Response body: {"message":"Hello World!"}34Request request = Request.builder()35 .build();36Response response = request.get();37System.out.println("Response code: " + response.getStatus());38System.out.println("Response body: " + response.getBodyAsString());39Response body: {"message":"Hello World!"}40Request request = Request.builder()41 .build();42Response response = request.get();43System.out.println("Response code: " + response.getStatus());44System.out.println("Response body: " + response.getBodyAsString());
Request
Using AI Code Generation
1import com.intuit.karate.http.Request2Request request = new Request()3request.setMethod('POST')4request.addHeader('Content-Type', 'application/json')5request.setBody('{ "firstName": "John", "lastName": "Doe" }')6Response response = request.send()7import com.intuit.karate.Request8Request request = new Request()9request.setMethod('POST')10request.addHeader('Content-Type', 'application/json')11request.setBody('{ "firstName": "John", "lastName": "Doe" }')12Response response = request.send()13import com.intuit.karate.http.Request14Request request = new Request()15request.setMethod('POST')16request.addHeader('Content-Type', 'application/json')17request.setBody('{ "firstName": "John", "lastName": "Doe" }')18Response response = request.send()19import com.intuit.karate.Request20Request request = new Request()21request.setMethod('POST')22request.addHeader('Content-Type', 'application/json')23request.setBody('{ "firstName": "John", "lastName": "Doe" }')24Response response = request.send()25import com.intuit.karate.http.Request26Request request = new Request()27request.setMethod('POST')28request.addHeader('Content-Type', 'application/json')29request.setBody('{ "firstName": "John", "lastName": "Doe" }')30Response response = request.send()31import com.intuit.karate.Request
Request
Using AI Code Generation
1import com.intuit.karate.http.Request2Request request = new Request()3request.setMethod('GET')4request.addHeader('Content-Type', 'application/json')5request.setBody('{"name": "karate"}')6def response = request.send()7import com.intuit.karate.http.Request8Request request = new Request()9request.setMethod('GET')10request.addHeader('Content-Type', 'application/json')11request.setBody('{"name": "karate"}')12def response = request.send()13import com.intuit.karate.http.Request14Request request = new Request()15request.setMethod('GET')16request.addHeader('Content-Type', 'application/json')17request.setBody('{"name": "karate"}')18def response = request.send()19import com.intuit.karate.http.Request20Request request = new Request()21request.setMethod('GET')22request.addHeader('Content-Type', 'application/json')23request.setBody('{"name": "karate"}')24def response = request.send()25import com.intuit.karate.http.Request26Request request = new Request()27request.setMethod('GET')28request.addHeader('Content-Type', 'application/json')29request.setBody('{"name": "karate"}')30def response = request.send()31import com.intuit.karate.http.Request32Request request = new Request()33request.setMethod('GET')34request.addHeader('Content-Type', 'application/json')
Request
Using AI Code Generation
1import com.intuit.karate.http.Request2Request req = new Request()3def res = req.send()4import com.intuit.karate.http.Request5Request req = new Request()6def res = req.send()7import com.intuit.karate.http.Request8Request req = new Request()9def res = req.send()10import com.intuit.karate.http.Request11Request req = new Request()12def res = req.send()13import com.intuit.karate.http.Request14Request req = new Request()15def res = req.send()16import com.intuit.karate.http.Request17Request req = new Request()
Request
Using AI Code Generation
1import com.intuit.karate.http.Request2Request request = new Request()3request.setMethod('get')4request.setBody('hello world')5request.addHeader('Content-Type', 'text/plain')6request.addHeader('Accept', 'text/plain')7request.addHeader('Accept', 'application/json')8request.addHeader('Accept', 'application/xml')9request.addHeader('Accept', '*/*')10request.addHeader('Accept-Encoding', 'gzip, deflate, br')11request.addHeader('Accept-Language', 'en-US,en;q=0.9')12request.addHeader('Connection', 'keep-alive')13request.addHeader('Host', 'localhost:8080')14request.addHeader('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36')15request.addHeader('X-Forwarded-For', '
Request
Using AI Code Generation
1import com.intuit.karate.http.Request;2Request request = new Request();3request.setMethod("get");4request.addHeader("Content-Type","application/json");5request.setBody("{ \"hello\" : \"world\" }");6Response response = request.send();7println response;8import com.intuit.karate.http.Request;9Request request = new Request();10request.setMethod("get");11request.addHeader("Content-Type","application/json");12request.setBody("{ \"hello\" : \"world\" }");13Response response = request.send();14println response;15import com.intuit.karate.http.Request;16Request request = new Request();17request.setMethod("get");18request.addHeader("Content-Type","application/json");19request.setBody("{ \"hello\" : \"world\" }");20Response response = request.send();21println response;22import com.intuit.karate.http.Request;23Request request = new Request();24request.setMethod("get");25request.addHeader("Content-Type","application/json");26request.setBody("{ \"hello\" : \"world\" }");27Response response = request.send();28println response;29import com.intuit.karate.http.Request;30Request request = new Request();31request.setMethod("get");32request.addHeader("Content-Type","application/json");33request.setBody("{ \"hello\" : \"world\" }");34Response response = request.send();35println response;36import com.intuit.karate.http.Request;37Request request = new Request();38request.setMethod("get");39request.addHeader("Content-Type","application/json");40request.setBody("{ \"hello\" : \"world\" }");41Response response = request.send();42println response;43import com.intuit.karate.http.Request;44Request request = new Request();
Request
Using AI Code Generation
1import com.intuit.karate.http.Request2request.setBody('test')3request.addHeader('test', 'test')4request.addCookie('test', 'test')5request.setProxy('test')6request.setTimeout(10000)7request.setFollowRedirects(true)
Request
Using AI Code Generation
1import com.intuit.karate.http.*;2Request request = new Request();3System.out.println(response);4System.out.println(response.getBody());5System.out.println(response.getStatus());6System.out.println(response.getHeaders());7System.out.println(response.getCookies());8System.out.println(response.getTime());9System.out.println(response.getContentType());10System.out.println(response.getContentLength());11System.out.println(response.getContentEncoding());12System.out.println(response.getContentDisposition());13System.out.println(response.getContentLocation());14System.out.println(response.getContentLanguage());15System.out.println(response.getContentMD5());16System.out.println(response.getContentExpires());17System.out.println(response.getContentCharset());18System.out.println(response.getContentType());19System.out.println(response.getContentLength());20System.out.println(response.getContentEncoding());21System.out.println(response.getContentDisposition());22System.out.println(response.getContentLocation());23System.out.println(response.getContentLanguage());24System.out.println(response.getContentMD5());25System.out.println(response.getContentExpires());26System.out.println(response.getContentCharset());27System.out.println(response.getContentType());28System.out.println(response.getContentLength());29System.out.println(response.getContentEncoding());30System.out.println(response.getContentDisposition());31System.out.println(response.getContentLocation());32System.out.println(response.getContentLanguage());33System.out.println(response.getContentMD5());
Request
Using AI Code Generation
1import com.intuit.karate.http.Request;2import com.intuit.karate.http.Response;3import java.io.File;4import java.util.Map;5import java.util.List;6public class 4 {7 public static void main(String[] args) {8 System.out.println(response);9 System.out.println(response.getStatus());10 System.out.println(response.getBody());11 System.out.println(response.getHeaders());12 System.out.println(response.getCookies());13 System.out.println(response.getTime());14 System.out.println(response.getBodyAsString());15 System.out.println(response.getBodyAsJson());16 System.out.println(response.getBodyAsXml());17 System.out.println(response.getBodyAsBytes());18 System.out.println(response.getBodyAsFile(new File("4.html")));19 System.out.println(response.getBodyAsImage());20 }21}
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!!