How to use extractOriginalValue method of org.testingisdocumenting.webtau.http.Http class

Best Webtau code snippet using org.testingisdocumenting.webtau.http.Http.extractOriginalValue

Source:Http.java Github

copy

Full Screen

...814 // we still validate status code to make sure user is aware of the status code problem815 try {816 R extracted = ExpectationHandlers.withAdditionalHandler(recordAndThrowHandler, () -> {817 Object returnedValue = validator.validate(header, body);818 return (R) extractOriginalValue(returnedValue);819 });820 ExpectationHandlers.withAdditionalHandler(recordAndThrowHandler, () -> {821 validateStatusCode(validationResult);822 return null;823 });824 HttpValidationHandlers.validate(validationResult);825 return extracted;826 } catch (Throwable e) {827 ExpectationHandlers.withAdditionalHandler(new ExpectationHandler() {828 @Override829 public Flow onValueMismatch(ValueMatcher valueMatcher, ActualPath actualPath, Object actualValue, String message) {830 validationResult.addMismatch(message);831 // another assertion happened before status code check832 // we discard it and throw status code instead833 if (e instanceof AssertionError) {834 throw new AssertionError('\n' + message);835 }836 // originally an exception happened,837 // so we combine its message with status code failure838 throw new AssertionError('\n' + message +839 "\n\nadditional exception message:\n" + e.getMessage(), e);840 }841 }, () -> {842 validateErrorsOnlyStatusCode(validationResult);843 return null;844 });845 throw e;846 }847 }848 private DataNode createBodyDataNodeAndMarkResponseInvalidWhenParsingError(HttpValidationResult validationResult) {849 DataNodeId id = new DataNodeId("body");850 HttpResponse response = validationResult.getResponse();851 if (!response.isBinary() && response.nullOrEmptyTextContent()) {852 return new StructuredDataNode(id, new TraceableValue(null));853 }854 if (response.isText()) {855 return new StructuredDataNode(id, new TraceableValue(response.getTextContent()));856 }857 if (response.isJson()) {858 return tryParseJsonAndReturnTextIfFails(validationResult, id, response.getTextContent());859 }860 return new StructuredDataNode(id, new TraceableValue(response.getBinaryContent()));861 }862 private DataNode tryParseJsonAndReturnTextIfFails(HttpValidationResult validationResult,863 DataNodeId id,864 String textContent) {865 try {866 Object object = JsonUtils.deserialize(textContent);867 return DataNodeBuilder.fromValue(id, object);868 } catch (JsonParseException e) {869 validationResult.setBodyParseErrorMessage(e.getMessage());870 validationResult.addMismatch("can't parse JSON response of " + validationResult.getFullUrl()871 + ": " + e.getMessage());872 return new StructuredDataNode(id,873 new TraceableValue("invalid JSON:\n" + textContent));874 }875 }876 private void validateStatusCode(HttpValidationResult validationResult) {877 DataNode statusCode = validationResult.getHeaderNode().statusCode;878 if (statusCode.getTraceableValue().getCheckLevel() != CheckLevel.None) {879 return;880 }881 statusCode.should(equal(defaultExpectedStatusCodeByRequest(validationResult)));882 }883 private void validateErrorsOnlyStatusCode(HttpValidationResult validationResult) {884 DataNode statusCode = validationResult.getHeaderNode().statusCode;885 if (statusCode.getTraceableValue().getCheckLevel() != CheckLevel.None) {886 return;887 }888 Integer statusCodeValue = (Integer) statusCode.getTraceableValue().getValue();889 if (statusCodeValue >= 200 && statusCodeValue < 300) {890 return;891 }892 statusCode.should(equal(defaultExpectedStatusCodeByRequest(validationResult)));893 }894 private Integer defaultExpectedStatusCodeByRequest(HttpValidationResult validationResult) {895 switch (validationResult.getRequestMethod()) {896 case "POST":897 return 201;898 case "PUT":899 case "DELETE":900 case "PATCH":901 return validationResult.hasResponseContent() ? 200 : 204;902 case "GET":903 default:904 return 200;905 }906 }907 private HttpResponse request(String method, String fullUrl,908 HttpHeader requestHeader,909 HttpRequestBody requestBody) {910 if (requestHeader == null) {911 throw new IllegalArgumentException("Request header is null, check your header provider is not returning null");912 }913 try {914 HttpURLConnection connection = createConnection(fullUrl);915 connection.setInstanceFollowRedirects(false);916 setRequestMethod(method, connection);917 connection.setConnectTimeout(getCfg().getHttpTimeout());918 connection.setReadTimeout(getCfg().getHttpTimeout());919 connection.setRequestProperty("Content-Type", requestBody.type());920 connection.setRequestProperty("Accept", requestBody.type());921 connection.setRequestProperty("User-Agent", getCfg().getUserAgent());922 requestHeader.forEachProperty(connection::setRequestProperty);923 if (! (requestBody instanceof EmptyRequestBody)) {924 validateRequestContent(requestBody);925 connection.setDoOutput(true);926 if (requestBody.isBinary()) {927 connection.getOutputStream().write(requestBody.asBytes());928 } else {929 IOUtils.write(requestBody.asString(), connection.getOutputStream(), UTF_8);930 }931 }932 return extractHttpResponse(connection);933 } catch (IOException e) {934 throw new RuntimeException("couldn't " + method + ": " + fullUrl, e);935 }936 }937 private void validateRequestContent(HttpRequestBody requestBody) {938 if (requestBody.type().contains("/json")) {939 validateJsonRequestContent(requestBody.asString());940 }941 }942 private void validateJsonRequestContent(String json) {943 JsonUtils.deserialize(json);944 }945 private HttpURLConnection createConnection(String fullUrl) {946 try {947 if (getCfg().isHttpProxySet()) {948 HostPort hostPort = new HostPort(getCfg().getHttpProxyConfigValue().getAsString());949 return (HttpURLConnection) new URL(fullUrl).openConnection(new Proxy(Proxy.Type.HTTP,950 new InetSocketAddress(hostPort.host, hostPort.port)));951 }952 return (HttpURLConnection) new URL(fullUrl).openConnection();953 } catch (IOException e) {954 throw new UncheckedIOException(e);955 }956 }957 private void setRequestMethod(String method, HttpURLConnection connection) throws ProtocolException {958 if (method.equals("PATCH")) {959 // Http(s)UrlConnection does not recognize PATCH, unfortunately, nor will it be added, see960 // https://bugs.openjdk.java.net/browse/JDK-8207840 .961 // The Oracle-recommended solution requires JDK 11's new java.net.http package.962 try {963 Object connectionTarget = connection;964 if (connection instanceof HttpsURLConnection) {965 final Field delegateField = HttpsURLConnectionImpl.class.getDeclaredField("delegate");966 delegateField.setAccessible(true);967 connectionTarget = delegateField.get(connection);968 }969 final Field f = HttpURLConnection.class.getDeclaredField("method");970 f.setAccessible(true);971 f.set(connectionTarget, "PATCH");972 } catch (IllegalAccessException | NoSuchFieldException e) {973 throw new RuntimeException("Failed to enable PATCH on HttpUrlConnection", e);974 }975 } else {976 connection.setRequestMethod(method);977 }978 }979 private HttpResponse extractHttpResponse(HttpURLConnection connection) throws IOException {980 HttpResponse httpResponse = new HttpResponse();981 populateResponseHeader(httpResponse, connection);982 InputStream inputStream = getInputStream(connection);983 httpResponse.setStatusCode(connection.getResponseCode());984 httpResponse.setContentType(connection.getContentType() != null ? connection.getContentType() : "");985 if (!httpResponse.isBinary()) {986 httpResponse.setTextContent(inputStream != null ? IOUtils.toString(inputStream, StandardCharsets.UTF_8) : "");987 } else {988 httpResponse.setBinaryContent(inputStream != null ? IOUtils.toByteArray(inputStream) : new byte[0]);989 }990 return httpResponse;991 }992 private InputStream getInputStream(HttpURLConnection connection) throws IOException {993 InputStream inputStream = connection.getResponseCode() < 400 ? connection.getInputStream() : connection.getErrorStream();994 if ("gzip".equals(connection.getContentEncoding())) {995 inputStream = new GZIPInputStream(inputStream);996 }997 return inputStream;998 }999 private void populateResponseHeader(HttpResponse httpResponse, HttpURLConnection connection) {1000 Map<CharSequence, CharSequence> header = new LinkedHashMap<>();1001 connection.getHeaderFields().forEach((key, values) -> {1002 if (!values.isEmpty()) {1003 header.put(key, values.get(0));1004 }1005 });1006 httpResponse.addHeader(header);1007 }1008 /**1009 * Response consist of DataNode and Traceable values, but we need to return a simple value that can be used for1010 * regular calculations and to drive test flow1011 *1012 * @param v value returned from a validation callback1013 * @return extracted regular value1014 */1015 private Object extractOriginalValue(Object v) {1016 if (v instanceof DataNode) {1017 return ((DataNode) v).get();1018 }1019 if (v instanceof TraceableValue) {1020 return ((TraceableValue) v).getValue();1021 }1022 if (v instanceof List) {1023 return ((List<?>) v).stream().map(this::extractOriginalValue).collect(toList());1024 }1025 return v;1026 }1027 private interface HttpCall {1028 HttpResponse execute(String fullUrl, HttpHeader fullHeader);1029 }1030 private static class HostPort {1031 private final String host;1032 private final int port;1033 private HostPort(String hostPort) {1034 String[] parts = hostPort.split(":");1035 if (parts.length != 2) {1036 throw new IllegalArgumentException("expect host:port format for proxy, given: " + hostPort);1037 }...

Full Screen

Full Screen

extractOriginalValue

Using AI Code Generation

copy

Full Screen

1import org.testingisdocumenting.webtau.http.Http2import org.testingisdocumenting.webtau.http.datanode.DataNode3import org.testingisdocumenting.webtau.utils.JsonUtils4import org.testingisdocumenting.webtau.utils.JsonUtils.jsonToMap5Http.http.get("/json") {6 val json = extractOriginalValue()7 val map = JsonUtils.jsonToMap(json)8 map.get("a") should be "b"9}10import org.testingisdocumenting.webtau.http.datanode.DataNode11import org.testingisdocumenting.webtau.utils.JsonUtils12import org.testingisdocumenting.webtau.utils.JsonUtils.jsonToMap13Http.http.get("/json") {14 val json = extractOriginalValue()15 val map = JsonUtils.jsonToMap(json)16 map.get("a") should be "b"17}18import org.testingisdocumenting.webtau.http.Http19import org.testingisdocumenting.webtau.http.datanode.DataNode20import org.testingisdocumenting.webtau.utils.JsonUtils21import org.testingisdocumenting.webtau.utils.JsonUtils.jsonToMap22Http.http.get("/json") {23 val json = json()24 json.get("a") should be "b"25}26import org.testingisdocumenting.webtau.http.datanode.DataNode27import org.testingisdocumenting.webtau.utils.JsonUtils28import org.testingisdocumenting.webtau.utils.JsonUtils.jsonToMap29Http.http.get("/json") {30 val json = json()31 json.get("a") should be "b"32}

Full Screen

Full Screen

extractOriginalValue

Using AI Code Generation

copy

Full Screen

1import org.testingisdocumenting.webtau.Ddjt2import org.testingisdocumenting.webtau.http.Http3Http.get("/api/employees/1") {4 Ddjt.verify(Http.extractOriginalValue(it), "employee id is 1")5}6import org.testingisdocumenting.webtau.Ddjt7import org.testingisdocumenting.webtau.http.Http8Http.get("/api/employees/1") {9 Ddjt.verify(Http.extractOriginalValue(it), "employee id is 1")10}11import org.testingisdocumenting.webtau.Ddjt12import org.testingisdocumenting.webtau.http.Http13Http.get("/api/employees/1") {14 Ddjt.verify(Http.extractOriginalValue(it), "employee id is 1")15}16import org.testingisdocumenting.webtau.Ddjt17import org.testingisdocumenting.webtau.http.Http18Http.get("/api/employees/1") {19 Ddjt.verify(Http.extractOriginalValue(it), "employee id is 1")20}21import org.testingisdocumenting.webtau.Ddjt22import org.testingisdocumenting.webtau.http.Http23Http.get("/api/employees/1") {24 Ddjt.verify(Http.extractOriginalValue(it), "employee id is 1")25}

Full Screen

Full Screen

extractOriginalValue

Using AI Code Generation

copy

Full Screen

1import org.testingisdocumenting.webtau.Ddjt.*2import org.testingisdocumenting.webtau.http.Http3Http.get("/api/users/1") {4 body should equalJson {5 }6 val userId = extractOriginalValue("id")7 Http.get("/api/users/${userId}/friends") {8 body should equalJson {9 - { name: "Alice" }10 - { name: "Bob" }11 }12 }13}14import org.testingisdocumenting.webtau.Ddjt.*15import org.testingisdocumenting.webtau.http.Http16Http.get("/api/users/1") {17 body should equalJson {18 }19 val userId = extractOriginalValue("id")20 Http.get("/api/users/${userId}/friends") {21 body should equalJson {22 - { name: "Alice" }23 - { name: "Bob" }24 }25 }26}27import org.testingisdocumenting.webtau.Ddjt.*28import org.testingisdocumenting.webtau.http.Http29Http.get("/api/users/1") {30 body should equalJson {31 }32 val userId = extractOriginalValue("id")33 Http.get("/api/users/${userId}/friends") {34 body should equalJson {35 - { name: "Alice" }36 - { name: "Bob" }37 }38 }39}

Full Screen

Full Screen

extractOriginalValue

Using AI Code Generation

copy

Full Screen

1import org.testingisdocumenting.webtau.http.Http2Http.get("/api/v1/thing")3 .extractOriginalValue("id", "thingId")4 .get("/api/v1/thing/${thingId}")5 .statusCode should be(200)6import org.testingisdocumenting.webtau.http.Http7Http.get("/api/v1/thing")8 .extractOriginalValue("id", "thingId")9 .get("/api/v1/thing/${thingId}")10 .extractOriginalValue("name", "thingName")11 .get("/api/v1/thing/${thingName}")12 .statusCode should be(200)13import org.testingisdocumenting.webtau.http.Http14Http.get("/api/v1/thing")15 .extractOriginalValue("id", "thingId")16 .get("/api/v1/thing/${thingId}")17 .extractOriginalValue("name", "thingName")18 .get("/api/v1/thing/${thingName}")19 .extractOriginalValue("description", "thingDescription")20 .get("/api/v1/thing/${thingDescription}")21 .statusCode should be(200)

Full Screen

Full Screen

extractOriginalValue

Using AI Code Generation

copy

Full Screen

1import org.testingisdocumenting.webtau.http.Http2def id = Http.extractOriginalValue("id", resp)3Http.put("/api/v1/employees/${id}", employeeData)4Http.get("/api/v1/employees/${id}")5Http.delete("/api/v1/employees/${id}")6import org.testingisdocumenting.webtau.http.Http7def id = Http.extractOriginalValue("id", resp)8Http.put("/api/v1/employees/${id}", employeeData)9Http.get("/api/v1/employees/${id}")10Http.delete("/api/v1/employees/${id}")11import org.testingisdocumenting.webtau.http.Http12val id = Http.extractOriginalValue("id", resp)13Http.put("/api/v1/employees/${id}", employeeData)14Http.get("/api/v1/employees/${id}")15Http.delete("/api/v1/employees/${id}")16import org.testingisdocumenting.webtau.http.Http;17Object id = Http.extractOriginalValue("id", resp);18Http.put("/api/v1/employees/" + id, employeeData);19Http.get("/api/v1/employees/" + id);20Http.delete("/api/v1/employees/" + id);

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful