Search in sources :

Example 1 with HTTPHeader

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;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) SOAPTeststepProperties(io.irontest.models.teststep.SOAPTeststepProperties) ResponseHandler(org.apache.http.client.ResponseHandler) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) SSLContext(javax.net.ssl.SSLContext) StringEntity(org.apache.http.entity.StringEntity) Endpoint(io.irontest.models.endpoint.Endpoint) Header(org.apache.http.Header) HTTPHeader(io.irontest.models.teststep.HTTPHeader) HttpClient(org.apache.http.client.HttpClient) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) HTTPHeader(io.irontest.models.teststep.HTTPHeader)

Example 2 with HTTPHeader

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;
}
Also used : SSLContext(javax.net.ssl.SSLContext) Metadata.metadata(com.github.tomakehurst.wiremock.common.Metadata.metadata) XPathExpressionException(javax.xml.xpath.XPathExpressionException) DefaultArtifactVersion(org.apache.maven.artifact.versioning.DefaultArtifactVersion) io.irontest.models.mixin(io.irontest.models.mixin) StringUtils(org.apache.commons.lang3.StringUtils) Header(org.apache.http.Header) Base64(org.apache.commons.codec.binary.Base64) EntityUtils(org.apache.http.util.EntityUtils) WireMockServer(com.github.tomakehurst.wiremock.WireMockServer) io.irontest.models(io.irontest.models) java.net(java.net) Document(org.w3c.dom.Document) ResultSet(java.sql.ResultSet) org.apache.http.client.methods(org.apache.http.client.methods) HTTPAPIResponse(io.irontest.core.teststep.HTTPAPIResponse) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) HostnameVerifier(javax.net.ssl.HostnameVerifier) WIREMOCK_STUB_METADATA_ATTR_NAME_IRON_TEST_ID(io.irontest.IronTestConstants.WIREMOCK_STUB_METADATA_ATTR_NAME_IRON_TEST_ID) PlainTextStubNotMatchedRenderer(com.github.tomakehurst.wiremock.verification.notmatched.PlainTextStubNotMatchedRenderer) HttpHeaders(org.apache.http.HttpHeaders) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) LoggedRequest(com.github.tomakehurst.wiremock.verification.LoggedRequest) UrlEscapers(com.google.common.net.UrlEscapers) HttpEntity(org.apache.http.HttpEntity) StringEntity(org.apache.http.entity.StringEntity) WIREMOCK_STUB_METADATA_ATTR_NAME_IRON_TEST_NUMBER(io.irontest.IronTestConstants.WIREMOCK_STUB_METADATA_ATTR_NAME_IRON_TEST_NUMBER) UrlValidator(org.apache.commons.validator.routines.UrlValidator) HTTPHeader(io.irontest.models.teststep.HTTPHeader) LoggedResponse(com.github.tomakehurst.wiremock.http.LoggedResponse) MQRFH2Folder(io.irontest.models.teststep.MQRFH2Folder) HttpClients(org.apache.http.impl.client.HttpClients) ResultSetMetaData(java.sql.ResultSetMetaData) ClientProtocolException(org.apache.http.client.ClientProtocolException) java.util(java.util) SQLStatementType(io.irontest.db.SQLStatementType) TransformerException(javax.xml.transform.TransformerException) ANTLRStringStream(org.antlr.runtime.ANTLRStringStream) AtomicReference(java.util.concurrent.atomic.AtomicReference) Encoding(com.github.tomakehurst.wiremock.common.Encoding) SQLException(java.sql.SQLException) HttpClient(org.apache.http.client.HttpClient) ResponseDefinition(com.github.tomakehurst.wiremock.http.ResponseDefinition) StubMapping(com.github.tomakehurst.wiremock.stubbing.StubMapping) Jdbi(org.jdbi.v3.core.Jdbi) JsonParser(com.fasterxml.jackson.core.JsonParser) TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) ServeEvent(com.github.tomakehurst.wiremock.stubbing.ServeEvent) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) SqlScriptParser(org.jdbi.v3.core.internal.SqlScriptParser) IOException(java.io.IOException) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) com.github.tomakehurst.wiremock.matching(com.github.tomakehurst.wiremock.matching) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) ResponseHandler(org.apache.http.client.ResponseHandler) HttpHost(org.apache.http.HttpHost) TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) HTTPAPIResponse(io.irontest.core.teststep.HTTPAPIResponse) HttpEntity(org.apache.http.HttpEntity) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ClientProtocolException(org.apache.http.client.ClientProtocolException) StringEntity(org.apache.http.entity.StringEntity) HttpHost(org.apache.http.HttpHost) UrlValidator(org.apache.commons.validator.routines.UrlValidator) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) AtomicReference(java.util.concurrent.atomic.AtomicReference) SSLContext(javax.net.ssl.SSLContext) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) HostnameVerifier(javax.net.ssl.HostnameVerifier) Header(org.apache.http.Header) HTTPHeader(io.irontest.models.teststep.HTTPHeader) HttpClient(org.apache.http.client.HttpClient) HTTPHeader(io.irontest.models.teststep.HTTPHeader)

Example 3 with HTTPHeader

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;
}
Also used : PropertyExtractorRunner(io.irontest.core.propertyextractor.PropertyExtractorRunner) java.util(java.util) TestResult(io.irontest.models.TestResult) HTTPStubMapping(io.irontest.models.HTTPStubMapping) io.irontest.models.assertion(io.irontest.models.assertion) WireMockServer(com.github.tomakehurst.wiremock.WireMockServer) PropertyExtractor(io.irontest.models.propertyextractor.PropertyExtractor) HttpHeader(org.eclipse.jetty.http.HttpHeader) IronTestConstants(io.irontest.IronTestConstants) TestcaseRun(io.irontest.models.testrun.TestcaseRun) Testcase(io.irontest.models.Testcase) TeststepRun(io.irontest.models.testrun.TeststepRun) HTTPStubsSetupTeststepProperties(io.irontest.models.teststep.HTTPStubsSetupTeststepProperties) Logger(org.slf4j.Logger) Endpoint(io.irontest.models.endpoint.Endpoint) AssertionVerifier(io.irontest.core.assertion.AssertionVerifier) IOException(java.io.IOException) UtilsDAO(io.irontest.db.UtilsDAO) AssertionVerifierFactory(io.irontest.core.assertion.AssertionVerifierFactory) io.irontest.core.teststep(io.irontest.core.teststep) PropertyExtractorRunnerFactory(io.irontest.core.propertyextractor.PropertyExtractorRunnerFactory) HTTPHeader(io.irontest.models.teststep.HTTPHeader) IronTestUtils(io.irontest.utils.IronTestUtils) Teststep(io.irontest.models.teststep.Teststep) TestcaseRunDAO(io.irontest.db.TestcaseRunDAO) PropertyExtractor(io.irontest.models.propertyextractor.PropertyExtractor) PropertyExtractorRunner(io.irontest.core.propertyextractor.PropertyExtractorRunner) HTTPHeader(io.irontest.models.teststep.HTTPHeader)

Aggregations

HTTPHeader (io.irontest.models.teststep.HTTPHeader)3 WireMockServer (com.github.tomakehurst.wiremock.WireMockServer)2 Endpoint (io.irontest.models.endpoint.Endpoint)2 IOException (java.io.IOException)2 java.util (java.util)2 SSLContext (javax.net.ssl.SSLContext)2 Header (org.apache.http.Header)2 HttpEntity (org.apache.http.HttpEntity)2 HttpClient (org.apache.http.client.HttpClient)2 ResponseHandler (org.apache.http.client.ResponseHandler)2 TrustStrategy (org.apache.http.conn.ssl.TrustStrategy)2 StringEntity (org.apache.http.entity.StringEntity)2 SSLContextBuilder (org.apache.http.ssl.SSLContextBuilder)2 JsonParser (com.fasterxml.jackson.core.JsonParser)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 Encoding (com.github.tomakehurst.wiremock.common.Encoding)1 Metadata.metadata (com.github.tomakehurst.wiremock.common.Metadata.metadata)1 LoggedResponse (com.github.tomakehurst.wiremock.http.LoggedResponse)1 ResponseDefinition (com.github.tomakehurst.wiremock.http.ResponseDefinition)1 com.github.tomakehurst.wiremock.matching (com.github.tomakehurst.wiremock.matching)1