use of io.irontest.models.teststep.HTTPHeader in project irontest by zheng-wang.
the class SOAPTeststepRunner method run.
protected BasicTeststepRun run(Teststep teststep) throws Exception {
BasicTeststepRun basicTeststepRun = new BasicTeststepRun();
Endpoint endpoint = teststep.getEndpoint();
// set request HTTP headers
HttpPost httpPost = new HttpPost(endpoint.getUrl());
SOAPTeststepProperties otherProperties = (SOAPTeststepProperties) teststep.getOtherProperties();
if (otherProperties != null) {
for (HTTPHeader httpHeader : otherProperties.getHttpHeaders()) {
httpPost.setHeader(httpHeader.getName(), httpHeader.getValue());
}
}
// set HTTP basic auth
if (!"".equals(StringUtils.trimToEmpty(endpoint.getUsername()))) {
String auth = endpoint.getUsername() + ":" + getDecryptedEndpointPassword();
String encodedAuth = Base64.encodeBase64String(auth.getBytes());
String authHeader = "Basic " + encodedAuth;
httpPost.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
}
// set request HTTP body
httpPost.setEntity(new StringEntity((String) teststep.getRequest(), "UTF-8"));
final SOAPAPIResponse apiResponse = new SOAPAPIResponse();
ResponseHandler<Void> responseHandler = new ResponseHandler<Void>() {
public Void handleResponse(final HttpResponse httpResponse) throws IOException {
LOGGER.info(httpResponse.toString());
apiResponse.getHttpHeaders().add(new HTTPHeader("*Status-Line*", httpResponse.getStatusLine().toString()));
Header[] headers = httpResponse.getAllHeaders();
for (Header header : headers) {
apiResponse.getHttpHeaders().add(new HTTPHeader(header.getName(), header.getValue()));
}
HttpEntity entity = httpResponse.getEntity();
apiResponse.setHttpBody(entity != null ? EntityUtils.toString(entity) : null);
return null;
}
};
// build HTTP Client instance
// trust all SSL certificates
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(new TrustStrategy() {
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build();
HttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build();
// invoke the web service
httpClient.execute(httpPost, responseHandler);
basicTeststepRun.setResponse(apiResponse);
return basicTeststepRun;
}
use of io.irontest.models.teststep.HTTPHeader in project irontest by zheng-wang.
the class IronTestUtils method invokeHTTPAPI.
/**
* This method trusts all SSL certificates exposed by the API.
*
* @param url
* @param username
* @param password
* @param httpMethod
* @param httpHeaders
* @param httpBody
* @return
* @throws Exception
*/
public static HTTPAPIResponse invokeHTTPAPI(String url, String username, String password, HTTPMethod httpMethod, List<HTTPHeader> httpHeaders, String httpBody) throws Exception {
UrlValidator urlValidator = new UrlValidator(new String[] { "http", "https" }, UrlValidator.ALLOW_LOCAL_URLS);
if (!urlValidator.isValid(url)) {
throw new RuntimeException("Invalid URL");
}
// to allow special characters like whitespace in query parameters
String safeUrl = UrlEscapers.urlFragmentEscaper().escape(url);
// create HTTP request object and set body if applicable
HttpUriRequest httpRequest;
switch(httpMethod) {
case GET:
httpRequest = new HttpGet(safeUrl);
break;
case POST:
HttpPost httpPost = new HttpPost(safeUrl);
// StringEntity doesn't accept null string (exception is thrown)
httpPost.setEntity(httpBody == null ? null : new StringEntity(httpBody, "UTF-8"));
httpRequest = httpPost;
break;
case PUT:
HttpPut httpPut = new HttpPut(safeUrl);
// StringEntity doesn't accept null string (exception is thrown)
httpPut.setEntity(httpBody == null ? null : new StringEntity(httpBody, "UTF-8"));
httpRequest = httpPut;
break;
case DELETE:
httpRequest = new HttpDelete(safeUrl);
break;
default:
throw new IllegalArgumentException("Unrecognized HTTP method " + httpMethod);
}
// set request HTTP headers
for (HTTPHeader httpHeader : httpHeaders) {
httpRequest.setHeader(httpHeader.getName(), httpHeader.getValue());
}
// set HTTP basic auth
if (!"".equals(StringUtils.trimToEmpty(username))) {
String auth = username + ":" + password;
String encodedAuth = Base64.encodeBase64String(auth.getBytes());
String authHeader = "Basic " + encodedAuth;
httpRequest.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
}
final HTTPAPIResponse apiResponse = new HTTPAPIResponse();
final AtomicReference<Date> responseReceivedTime = new AtomicReference<>();
ResponseHandler<Void> responseHandler = httpResponse -> {
responseReceivedTime.set(new Date());
apiResponse.setStatusCode(httpResponse.getStatusLine().getStatusCode());
apiResponse.getHttpHeaders().add(new HTTPHeader("*Status-Line*", httpResponse.getStatusLine().toString()));
Header[] headers = httpResponse.getAllHeaders();
for (Header header : headers) {
apiResponse.getHttpHeaders().add(new HTTPHeader(header.getName(), header.getValue()));
}
HttpEntity entity = httpResponse.getEntity();
apiResponse.setHttpBody(entity != null ? EntityUtils.toString(entity) : null);
return null;
};
// build HTTP Client instance, trusting all SSL certificates, using system HTTP proxy if needed and exists
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial((TrustStrategy) (chain, authType) -> true).build();
HostnameVerifier allowAllHosts = new NoopHostnameVerifier();
SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, allowAllHosts);
HttpClientBuilder httpClientBuilder = HttpClients.custom().setSSLSocketFactory(connectionFactory);
InetAddress urlHost = InetAddress.getByName(new URL(url).getHost());
if (!(urlHost.isLoopbackAddress() || urlHost.isSiteLocalAddress())) {
// only use system proxy for external address
Proxy systemHTTPProxy = getSystemHTTPProxy();
if (systemHTTPProxy != null) {
InetSocketAddress addr = (InetSocketAddress) systemHTTPProxy.address();
httpClientBuilder.setProxy(new HttpHost(addr.getHostName(), addr.getPort()));
}
}
HttpClient httpClient = httpClientBuilder.build();
// invoke the API
Date invocationStartTime = new Date();
try {
httpClient.execute(httpRequest, responseHandler);
} catch (ClientProtocolException e) {
throw new RuntimeException(e.getCause().getMessage(), e);
}
long responseTime = responseReceivedTime.get().getTime() - invocationStartTime.getTime();
apiResponse.setResponseTime(responseTime);
return apiResponse;
}
use of io.irontest.models.teststep.HTTPHeader in project irontest by zheng-wang.
the class TestcaseRunner method extractPropertiesOutOfAPIResponse.
/**
* Extract properties out of API response, and make the properties visible to the next test step run.
*/
private Map<String, String> extractPropertiesOutOfAPIResponse(String teststepType, List<PropertyExtractor> propertyExtractors, Object apiResponse, Map<String, String> referenceableStringProperties) throws Exception {
Map<String, String> extractedProperties = new HashMap<>();
for (PropertyExtractor propertyExtractor : propertyExtractors) {
String propertyExtractionInput = null;
if (Teststep.TYPE_HTTP.equals(teststepType)) {
HTTPAPIResponse httpApiResponse = (HTTPAPIResponse) apiResponse;
if (PropertyExtractor.TYPE_COOKIE.equals(propertyExtractor.getType())) {
Optional<HTTPHeader> setCookieHeader = httpApiResponse.getHttpHeaders().stream().filter(httpHeader -> HttpHeader.SET_COOKIE.asString().equals(httpHeader.getName())).findFirst();
propertyExtractionInput = setCookieHeader.isPresent() ? setCookieHeader.get().getValue() : null;
} else {
propertyExtractionInput = httpApiResponse.getHttpBody();
}
}
PropertyExtractorRunner propertyExtractorRunner = PropertyExtractorRunnerFactory.getInstance().create(propertyExtractor, referenceableStringProperties);
String propertyValue = propertyExtractorRunner.extract(propertyExtractionInput);
extractedProperties.put(propertyExtractor.getPropertyName(), propertyValue);
}
return extractedProperties;
}
Aggregations