Java源码示例:org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil

示例1
@SetEnvironment(executionEnvironments = {ExecutionEnvironment.STANDALONE})
@Test(groups = "wso2.esb", description = "POST request against REST endpoint where " +
                                         "body parameter name starts with digit")
public void testPostRequest() throws Exception {

    URL endpoint = new URL(getProxyServiceURLHttp("RestProxy"));
    try {
        Map<String, String> header = new HashMap<String, String>();
        header.put("Content-Type", "application/x-www-form-urlencoded");
        HttpRequestUtil.doPost(endpoint, "paramName=abc&2paramName=def&$paramName=ghi", header);

    } catch (Exception e){
        //ignore
    }

    String response = wireServer.getCapturedMessage();
    Assert.assertNotNull(response);
    Assert.assertTrue(response.contains("2paramName"), "POST request does not contain the " +
                                                       "body " +
                                                       "parameter name starts with digit " +
                                                       "specified");
    Assert.assertTrue(response.contains("$paramName"), "POST request does not contain the " +
                                                       "body " +
                                                       "parameter name starts with $ character " +
                                                       "specified");
}
 
示例2
@Test(groups = "wso2.esb", description = "Test to check whether location header value persists in the http response")
public void testForLocationHeaderInResponse() throws Exception {

    String proxyServiceUrl = getProxyServiceURLHttp("LocationHeaderTestProxy");

    String requestPayload = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
            + "   <soapenv:Header/>\n" + "   <soapenv:Body>\n" + "      <testBody>\n" + "      <foo/>\n"
            + "      </testBody>\n" + "   </soapenv:Body>\n" + "</soapenv:Envelope>\n";

    Map<String, String> headers = new HashMap<>();
    headers.put("SOAPAction", "urn:getQuote");

    HttpResponse response = HttpRequestUtil.doPost(new URL(proxyServiceUrl), requestPayload, headers);
    Map<String, String> responseHeaders = response.getHeaders();
    assertNotNull(responseHeaders, "Error in retrieving the response headers!");
    String locationHeaderValue = responseHeaders.get(LOCATION_HEADER_NAME);
    assertNotNull(locationHeaderValue, "Location header not set!");
    assertEquals(locationHeaderValue, EXPECTED_LOCATION_HEADER, "Incorrect location header!");
}
 
示例3
@Test(groups = { "wso2.esb" }, description = "Test for charset value in the Content-Type header "
        + "in response once message is built in out out sequence " + "with messageType")
public void charsetTestByChangingContentType() throws Exception {

    Map<String, String> headers = new HashMap<>();

    headers.put("Content-Type", "text/xml;charset=UTF-8");
    headers.put("SOAPAction", "urn:getQuote");

    HttpResponse response = HttpRequestUtil
            .doPost(new URL(getProxyServiceURLHttp("contentTypeCharsetProxy2")), messagePayload, headers);
    Assert.assertNotNull(response, "Response is null");
    Assert.assertTrue(response.getData().contains("WSO2 Company"), "Response not as expected " + response);

    String contentType = response.getHeaders().get("Content-Type");
    //Removing since a invalid scenario after the fix for https://wso2.org/jira/browse/ESBJAVA-1994
    //Assert.assertTrue(contentType.contains("application/xml"), "Content-Type is not changed " + contentType);
    Assert.assertEquals(StringUtils.countMatches(contentType, HTTPConstants.CHAR_SET_ENCODING), 1,
            "charset repeated in Content-Type header " + contentType);
}
 
示例4
@Test(groups = { "wso2.esb" }, description = "Test for charset value in the Content-Type header "
        + "in response once message is built in out out sequence " + "with messageType with charset")
public void charsetTestByChangingContentTypeWithCharset() throws Exception {

    Map<String, String> headers = new HashMap<>();

    headers.put("Content-Type", "text/xml;charset=UTF-8");
    headers.put("SOAPAction", "urn:getQuote");

    HttpResponse response = HttpRequestUtil
            .doPost(new URL(getProxyServiceURLHttp("contentTypeCharsetProxy3")), messagePayload, headers);
    Assert.assertNotNull(response, "Response is null");
    Assert.assertTrue(response.getData().contains("WSO2 Company"), "Response not as expected " + response);

    String contentType = response.getHeaders().get("Content-Type");
    //Removing Invalid scenario after the fix for https://wso2.org/jira/browse/ESBJAVA-1994
    //Assert.assertTrue(contentType.contains("application/xml"), "Content-Type is not changed " + contentType);
    Assert.assertEquals(StringUtils.countMatches(contentType, HTTPConstants.CHAR_SET_ENCODING), 1,
            "charset repeated in Content-Type header " + contentType);
}
 
示例5
@Test(groups = "wso2.esb", description = "Changing XML payload to JSON payload with simple Schema " +
        "stored in Local Entry")
public void testSimpleXMLToJsonWithSchemaLocalEntry() throws Exception {
    String payload = "<jsonObject>\n" +
            "    <fruit>12345</fruit>\n" +
            "    <price>7.5</price>\n" +
            "</jsonObject>";
    Map<String, String> httpHeaders = new HashMap<>();
    httpHeaders.put("Content-Type", "application/xml");
    String expectedOutput = "{\n" +
            "    \"fruit\": \"12345\",\n" +
            "    \"price\": 7.5\n" +
            "}";
    HttpResponse response = HttpRequestUtil.doPost(
            new URL(getProxyServiceURLHttp("transformMediatorSimpleXMLtoJSONWithSchemaLocalEntry")),
            payload, httpHeaders);
    assertEqualJsonObjects(response.getData(), expectedOutput,
            "Simple XML to JSON transformation with a simple schema did not happen properly");
}
 
示例6
@Test(groups = "wso2.esb",
      description = "Test cache mediator with  Json response having a single element array with PI enabled")
public void testJsonResponseWithCacheMediator() throws IOException, AutomationFrameworkException {

    Map<String, String> requestHeader = new HashMap<>();
    requestHeader.put("Content-type", "application/json");

    //will not be a cache hit
    HttpRequestUtil.doGet((getApiInvocationURL("cachingEnabledApi") + "/singleElementArrayBackend"), requestHeader);

    //will be a cache hit
    HttpResponse response = HttpRequestUtil.
            doGet((getApiInvocationURL("cachingEnabledApi") + "/singleElementArrayBackend"), requestHeader);

    //check if [] are preserved in response
    Assert.assertTrue(response.getData().contains("[ \"water\" ]"),
            "Expected response was not" + " received. Got " + response.getData());
}
 
示例7
@Test(groups = {
        "wso2.esb" }, dependsOnMethods = "addPeople", description = "Retrieving people from PeopleRestService")
public void getPeople() throws Exception {

    if (isTomcatServerRunning(tomcatServerManager, 5000)) {
        HttpResponse response1 = HttpRequestUtil
                .sendGetRequest(getApiInvocationURL("APIM1838getPerson") + "/[email protected]", null);
        assertEquals(response1.getResponseCode(), 200, "Response code mismatch");
        assertTrue(response1.getData().contains("John"), "Response message is not as expected.");
        assertTrue(response1.getData().contains("Doe"), "Response message is not as expected");

        HttpResponse response2 = HttpRequestUtil
                .sendGetRequest(getApiInvocationURL("APIM1838getPerson") + "/[email protected]", null);
        assertEquals(response2.getResponseCode(), 200, "Response code mismatch");
        assertTrue(response2.getData().contains("Jane"), "Response message is not as expected.");
        assertTrue(response2.getData().contains("Doe"), "Response message is not as expected");
    } else {
        Assert.fail("Jaxrs Service Startup failed");
    }
}
 
示例8
@Test(groups = { "wso2.esb" }, description = "Sending http request with a query param consist of"
        + " reserved + character ")
public void testURITemplateParameterDecodingPlusCharacterCase() throws Exception {
    carbonLogReader.clearLogs();
    boolean isPercentEncoded = false;
    boolean isMessageContextPropertyPercentDecoded = false;
    HttpResponse response = HttpRequestUtil
            .sendGetRequest(getApiInvocationURL("services/client/urlEncoded?queryParam=ESB+WSO2"), null);
    String decodedMessageContextProperty = "decodedQueryParamValue = ESB+WSO2";
    isMessageContextPropertyPercentDecoded =
            carbonLogReader.checkForLog(decodedMessageContextProperty, DEFAULT_TIMEOUT);
    isPercentEncoded = carbonLogReader.checkForLog("ESB%2BWSO2", DEFAULT_TIMEOUT);
    Assert.assertTrue(isMessageContextPropertyPercentDecoded,
            "Uri-Template parameters should be percent decoded at message context property");
    Assert.assertTrue(isPercentEncoded,
            "Reserved character should be percent encoded while uri-template expansion");
}
 
示例9
@Test(groups = { "wso2.esb" }, description = "Sending http request with a query param consist of"
        + " reserved + character ")
public void testURITemplateParameterDecodingWithPercentEncodingEscapedAtExpansion() throws Exception {
    carbonLogReader.clearLogs();
    boolean isPercentEncoded = false;
    boolean isMessageContextPropertyPercentDecoded = false;
    HttpResponse response = HttpRequestUtil
            .sendGetRequest(getApiInvocationURL("services/client/escapeUrlEncoded?queryParam=ESB+WSO2"), null);
    String decodedMessageContextProperty = "decodedQueryParamValue = ESB+WSO2";
    isMessageContextPropertyPercentDecoded = carbonLogReader.checkForLog(decodedMessageContextProperty, DEFAULT_TIMEOUT);
    isPercentEncoded = carbonLogReader.checkForLog("ESB%2BWSO2", DEFAULT_TIMEOUT);
    Assert.assertTrue(isMessageContextPropertyPercentDecoded,
            "Uri-Template parameters should be percent decoded at message context property");
    Assert.assertFalse(isPercentEncoded,
            "Reserved character should not be percent encoded while uri-template expansion");
}
 
示例10
@Test(groups = "wso2.esb", description = "Check whether JSON message formatting works properly in tenant mode")
public void testJSONFormattingInTenantMode() throws MalformedURLException, AutomationFrameworkException {
    String JSON_PAYLOAD = "{\"emails\": [{\"value\": \"[email protected]\"}]}";
    Map<String, String> headers = new HashMap<>();
    headers.put("Content-Type", "application/json");
    HttpResponse response = HttpRequestUtil
            .doPost(new URL("http://localhost:8480/json/payload"), JSON_PAYLOAD, headers);

    //checking whether JSON payload of wrong format is received
    assertFalse(response.getData().equals("{\"emails\":{\"value\":\"[email protected]\"}}"),
            "Incorrect format received!");

    //checking whether JSON payload of correct format is present
    assertTrue(response.getData().equals("{\"emails\": [{\"value\": \"[email protected]\"}]}"),
            "Expected format not received!");
}
 
示例11
@Test(groups = {
        "wso2.esb"}, description = "Sending a Message Via REST to test query param works with space character")
public void testPassParamsToEndpoint() throws InterruptedException {
    String requestString = "/context?queryParam=some%20value";
    boolean isSpaceCharacterEscaped;
    try {
        HttpRequestUtil.sendGetRequest(getApiInvocationURL("passParamsToEPTest") + requestString, null);
    } catch (Exception timeout) {
        //a timeout is expected
    }
    isSpaceCharacterEscaped = carbonLogReader.checkForLog("queryParam = some%20value", DEFAULT_TIMEOUT);
    carbonLogReader.stop();

    Assert.assertTrue(isSpaceCharacterEscaped,
            "Fail to send a message via REST when query parameter consist of space character");
}
 
示例12
@Test(groups = "wso2.esb", description = "Test cache mediator with  Json response having a single element array", enabled = false)
public void testJsonResponseWithCacheMediator() throws IOException, AutomationFrameworkException {

    Map<String, String> requestHeader = new HashMap<>();
    requestHeader.put("Content-type", "application/json");

    //will not be a cache hit
    HttpRequestUtil.doGet((getApiInvocationURL("cachingEnabledApi") + "/singleElementArrayBackend"), requestHeader);

    //will be a cache hit
    HttpResponse response = HttpRequestUtil.
            doGet((getApiInvocationURL("cachingEnabledApi") + "/singleElementArrayBackend"), requestHeader);

    //check if [] are preserved in response
    Assert.assertTrue(response.getData().contains("[ \"water\" ]"),
            "Expected response was not" + " received. Got " + response.getData());
}
 
示例13
@Test(groups = {"wso2.esb"}, description = "Test for charset value in the Content-Type header " +
                                           "in response once message is built in out out sequence " +
                                           "with messageType")
public void charsetTestByChangingContentType() throws Exception {

    Map<String, String> headers = new HashMap<>();

    headers.put("Content-Type", "text/xml;charset=UTF-8");
    headers.put("SOAPAction", "urn:getQuote");

    HttpResponse response = HttpRequestUtil.doPost(new URL(getProxyServiceURLHttp("contentTypeCharsetProxy2"))
            , messagePayload, headers);
    Assert.assertNotNull(response, "Response is null");
    Assert.assertTrue(response.getData().contains("WSO2 Company"), "Response not as expected " + response);

    String contentType = response.getHeaders().get("Content-Type");
    //Removing since a invalid scenario after the fix for https://wso2.org/jira/browse/ESBJAVA-1994
    //Assert.assertTrue(contentType.contains("application/xml"), "Content-Type is not changed " + contentType);
    Assert.assertEquals(StringUtils.countMatches(contentType, HTTPConstants.CHAR_SET_ENCODING), 1
            , "charset repeated in Content-Type header " + contentType);
}
 
示例14
@Test(groups = { "wso2.esb" }, description = "testManagedLifecycle")
public void testManagedLifecycle() throws Exception {

    Map<String, String> requestHeader = new HashMap<>();
    requestHeader.put("Content-Type", "text/xml");
    requestHeader.put("SOAPAction", "urn:mediate");
    String message = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
            + "   <soapenv:Header/>\n" + "   <soapenv:Body>\n" + "   <stock>\n" + "   <company>IBM</company>\n"
            + "   <company>SUN</company>\n" + "   </stock>\n" + "   </soapenv:Body>\n" + "</soapenv:Envelope>";

    HttpResponse response = HttpRequestUtil.
            doPost(new URL(getProxyServiceURLHttp("forEachManagedLifeCycleTestProxy")), message, requestHeader);

    Assert.assertTrue(response.getData().contains("Message mediation successful"),
            "Invalid response received. " + response.getData());
}
 
示例15
@Test(groups = {"wso2.esb"}, description = "Test XML to JSON conversion")
public void testXmlToJson() throws Exception {

    String xmlPayload = "<location>\n" +
            "               <name>Bermuda Triangle</name>\n" +
            "               <n>25.0000</n>\n" +
            "               <w>71.0000</w>\n" +
            "            </location>";
    Map<String, String> requestHeader = new HashMap<>();
    requestHeader.put("Content-Type", "text/xml");
    HttpResponse response = HttpRequestUtil.
            doPost(new URL(getProxyServiceURLHttp("xmlToJsonTestProxy")), xmlPayload, requestHeader);

    Assert.assertEquals(response.getData(), "{\"location\":{\"name\":\"Bermuda Triangle\",\"n\":25.0000,\"w\":71.0000}}",
            "Invalid XML to JSON conversion. " + response.getData());
}
 
示例16
/**
 * Test for use-existing-or-new action for using an existing transaction
 *
 * @throws Exception
 */
@Test(groups = "wso2.esb", description = "Test use-existing-or-new action for using an existing transaction")
public void useExistingTransactionTest() throws Exception {

    String expectedOutputForNick = "<response><table1>4</table1><table2>4</table2></response>";
    String expectedOutputForJohn = "<response><table1>5</table1><table2>5</table2></response>";

    HttpRequestUtil.doPost(new URL(API_URL + USE_EXISTING_NEW_CONTEXT + "?testEntry=John&entryId=5"), "");
    HttpResponse httpResponseForNick = HttpRequestUtil
            .doPost(new URL(API_URL + TEST_CONTEXT + "?testEntry=Nick"), "");
    HttpResponse httpResponseForJohn = HttpRequestUtil
            .doPost(new URL(API_URL + TEST_CONTEXT + "?testEntry=John"), "");

    boolean satisfyEntryNick = httpResponseForNick.getData().equals(expectedOutputForNick);
    boolean satisfyEntryJohn = httpResponseForJohn.getData().equals(expectedOutputForJohn);

    Assert.assertTrue(satisfyEntryJohn & satisfyEntryNick,
            "Use-existing-or-new action fails for using an existing transaction in transaction mediator");
}
 
示例17
/**
 * Test for invoking connector service.
 *
 * @throws Exception
 */
@Test(groups = "wso2.esb", description = "Test connector upload and invoke.")
public void invokeConnectorTest() throws Exception {

    String apiURI = "http://localhost:8480/library-service/get-message";
    String expectedOutput = "<message>Bob</message>";
    String expectedOutputAtDisable =
            "<message>Sequence template org.wso2.carbon.connector.hello.init cannot be found</message>";

    loadESBConfigurationFromClasspath(
            File.separator + "artifacts" + File.separator + "ESB" + File.separator + "connector" + File.separator +
                    "MediationLibraryServiceTestAPI.xml");

    HttpResponse httpResponse = HttpRequestUtil.doPost(new URL(apiURI), "");
    Assert.assertEquals(httpResponse.getData(), expectedOutput, "Invoking hello connector fails.");

    //disable the hello library and try to invoke
    updateConnectorStatus(HELLO_CONNECTOR_LIB_QNAME, HELLO_LIB_NAME, PACKAGE_NAME, DISABLED);
    HttpResponse httpResponseAtDisable = HttpRequestUtil.doPost(new URL(apiURI), "");
    Assert.assertEquals(httpResponseAtDisable.getData(), expectedOutputAtDisable,
                        "Invoking disabled hello connector test fails.");

    //enable back hello library for other tests
    updateConnectorStatus(HELLO_CONNECTOR_LIB_QNAME, HELLO_LIB_NAME, PACKAGE_NAME, ENABLED);
}
 
示例18
@Test(groups = "wso2.esb", description = "Test to check whether there are duplicate SOAPAction headers in the request to the service from callout mediator")
public void testCheckForDuplicateSOAPActionHeaders() throws Exception {

    String proxyServiceUrl = getProxyServiceURLHttp("DuplicateSOAPActionHeader");

    String requestPayload = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' >"
            + "<soapenv:Body xmlns:ser='http://services.samples' xmlns:xsd='http://services.samples/xsd'> "
            + "<ser:getQuote> <ser:request> <xsd:symbol>WSO2</xsd:symbol> </ser:request> </ser:getQuote> "
            + "</soapenv:Body></soapenv:Envelope> ";

    Map<String, String> headers = new HashMap<String, String>();
    headers.put("Soapaction", "urn:getQuote");

    HttpRequestUtil.doPost(new URL(proxyServiceUrl), requestPayload, headers);
    String capturedMsg = wireMonitorServer.getCapturedMessage();
 Assert.assertFalse(capturedMsg.contains("Soapaction"));
 Assert.assertTrue(capturedMsg.contains("SOAPAction"));
}
 
示例19
/**
 * Test response with 202 and body is built by ESB and responds client
 *
 * @throws AxisFault                    in case of an axis2 level issue when sending
 * @throws MalformedURLException        in case of url is malformed
 * @throws AutomationFrameworkException in case of any other test suite level issue
 */
@Test(groups = "wso2.esb", description = "Test response with 202 and body is built by ESB and responds client "
        + "properly")
public void testResponseWith202() throws AxisFault, MalformedURLException, AutomationFrameworkException {
    Map<String, String> requestHeader = new HashMap<>();
    requestHeader.put("Content-type", "text/xml");
    requestHeader.put("SOAPAction", "urn:mediate");
    String message = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap"
            + ".org/soap/envelope/\">\n"
            + "   <soapenv:Header/>\n"
            + "   <soapenv:Body/>\n"
            + "</soapenv:Envelope>";

    HttpResponse response = HttpRequestUtil.
            doPost(new URL(getProxyServiceURLHttp("mockProxy")), message, requestHeader);

    Assert.assertTrue(response.getData().contains("Hello World"), "Expected response was not"
            + " received. Got " + response.getData());
}
 
示例20
/**
 * Test for invalid JSON message with force.json.message.validation property.
 *
 * @throws Exception
 */
@Test(groups = "wso2.esb", description = "Test for invalid JSON payload with force.json.message.validation "
        + "property.")
public void testInvalidJSONMessage() throws Exception {
    logViewerClient.clearLogs();

    String inputPayload = "{\"abc\" :\"123\" } xyz";
    String expectedOutput = "Error while building the message.\n" + "{\"abc\" :\"123\" } xyz";

    Map<String, String> requestHeader = new HashMap<>();
    requestHeader.put("Content-type", "application/json");

    HttpRequestUtil.doPost(new URL(getApiInvocationURL(API_NAME)), inputPayload, requestHeader);

    Assert.assertTrue(Utils.assertIfSystemLogContains(logViewerClient, expectedOutput), "Test fails for forcing "
            + "JSON validation with force.json.message.validation passthru-http property.");
}
 
示例21
/**
 * This test case checks whether an Age header is returned with the response.
 *
 */
@SetEnvironment(executionEnvironments = {ExecutionEnvironment.STANDALONE})
@Test(groups = {"wso2.esb"}, description = "Testing with a large cache time out value for cache mediator")
public void testAgeHeader() throws Exception {
    String apiName = "includeAge";

    Map<String, String> headers = new HashMap<>();

    headers.put("Content-Type", "text/xml;charset=UTF-8");
    headers.put("SOAPAction", "urn:getQuote");

    //will not be a cache hit
    HttpRequestUtil.doPost(new URL(getApiInvocationURL(apiName)),
            messagePayload, headers);

    //will be a cache hit
    HttpResponse response2 = HttpRequestUtil.doPost(new URL(getApiInvocationURL(apiName)),
            messagePayload, headers);

    assertNotNull(response2.getHeaders().get("Age"), "Age header is not included");
}
 
示例22
/**
 * Test with UseTransaction flag. The transaction mediator is used to handle transactional behaviour.
 * The rollback operation is checked.
 *
 * @throws Exception
 */
@SetEnvironment(executionEnvironments = { ExecutionEnvironment.STANDALONE })
/*JIRA issue: https://wso2.org/jira/browse/ESBJAVA-1553*/
@Test(groups = "wso2.esb", description = "Test UseTransaction option ."
        + "Use in conjunction with Transaction mediator. Fail casse")
public void testDBmediatorFailCase() throws Exception {
    String sunStringtDB1, sunStringtDB2;
    sunStringtDB1 = getDatabaseResultsForDB1FailCase();
    assertTrue(sunStringtDB1.contains("SUN"), "Fault, invalid response");
    sunStringtDB2 = getDatabaseResultsForDB2FailCase();
    assertTrue(sunStringtDB2.contains("SUN"), "Fault, invalid response");
    HttpRequestUtil.doPost(new URL(getApiInvocationURL(API_URL + COMMIT_CONTEXT + "?nameEntry=SUN")), "");
    sunStringtDB1 = getDatabaseResultsForDB1FailCase();
    assertTrue(sunStringtDB1.contains("SUN"), "Fault, invalid response. Transaction is not rollbacked.");
    sunStringtDB2 = getDatabaseResultsForDB2FailCase();
    assertTrue(sunStringtDB2.contains("SUN"), "Fault, invalid response.Transaction is not rollbacked.");

}
 
示例23
@Test(groups = "wso2.esb", description = "Changing the JSON payload against a not existing registry schema")
public void testNotExistingJsonSchema() throws Exception {
    logViewer.clearLogs();
    String payload = "{\n" +
            "  \"fruit\"           : \"12345\",\n" +
            "  \"price\"           : \"7.5\",\n" +
            "  \"nestedObject\"    : {\"Lahiru\" :{\"age\":\"27\"},\"Nimal\" :{\"married\" :\"true\"}, \"Kamal\" " +
            ": {\"scores\": [\"24\",45,\"67\"]}},\n" +
            "  \"nestedArray\"     : [[12,\"23\",34],[\"true\",false],[\"Linking Park\",\"Coldplay\"]]\n" +
            "}";
    Map<String, String> httpHeaders = new HashMap<>();
    httpHeaders.put("Content-Type", "application/json");
    String expected_error = "Schema does not exist in the specified location : conf:/simpleSchemaNotexisting.json";
    HttpRequestUtil.doPost(
            new URL(getProxyServiceURLHttp("transformMediatorNotExistingSchema")), payload, httpHeaders);
    LogEvent[] logs = logViewer.getAllRemoteSystemLogs();
    boolean isErrorLogFound = false;
    for (LogEvent logEvent : logs) {
        if (logEvent.getMessage().contains(expected_error)) {
            isErrorLogFound = true;
            break;
        }
    }
    assertTrue(isErrorLogFound, "Expected error message not received when not existing schema is provided");
}
 
示例24
@Test(groups = {"wso2.dss"}, description = "Check swagger generation feature")
public void swaggerDataServiceWithResourcesTestCase() throws Exception {

    String serviceEndPoint = "http://localhost:8480/services/ResourcesServiceTest?swagger.json";
    HttpResponse response = HttpRequestUtil.doGet(serviceEndPoint, requestHeader);
    String responseString = response.getData();
    assertNotNull(responseString, "Failed to get the swagger response.");
    JSONObject result = new JSONObject(responseString);
    assertNotNull(result, "Response is null");
    assertTrue(result.has("paths"), "Swagger information should be available on all paths");
    String pathDetails = result.get("paths").toString();
    Assert.assertEquals(pathDetails, SWAGGER_RESPONSE, "Response mismatch");
}
 
示例25
@Test(groups = {"wso2.dss"}, description = "Check swagger generation for dataservice without resources")
public void swaggerDataServiceWithoutResourcesTestCase() throws Exception {

    String serviceEndPoint = "http://localhost:8480/services/CSVDataService?swagger.json";
    HttpResponse response = HttpRequestUtil.doGet(serviceEndPoint, requestHeader);
    String responseString = response.getData();
    assertNotNull(responseString, "Failed to get the swagger response.");
    JSONObject result = new JSONObject(responseString);
    assertNotNull(result, "Response is null");
    assertTrue(result.has("paths"), "Path section of the swagger definition is missing");
    String pathDetails = result.get("paths").toString();
    Assert.assertEquals(pathDetails, "{}", "Should not contain resource path details");
}
 
示例26
@Test(groups = {"wso2.esb"}, description = "Test JSON retry of message processor")
public void testMessageProcessorJSONRetry() throws Exception {

    // SEND THE REQUEST
    String addUrl = getProxyServiceURLHttp("MSMPRetrytest");
    String payload = "{\"name\":\"Jack\"}";

    Map<String, String>   headers = new HashMap<String, String>();
    headers.put("Content-Type", "application/json");

    HttpResponse response = HttpRequestUtil.doPost(new URL(addUrl), payload, headers );

    // IT HAS TO BE 202 ACCEPTED
    assertEquals(response.getResponseCode(), 202, "ESB failed to send 202 even after setting FORCE_SC_ACCEPTED");

    // WAIT FOR THE MESSAGE PROCESSOR TO TRIGGER
    Thread.sleep(5000);

    // START THE SERVER
    tomcatServerManager = new TomcatServerManager(
            CustomerConfig.class.getName(), TomcatServerType.jaxrs.name(), 8080);

    tomcatServerManager.startServer();  // staring tomcat server instance

    // ASSERT RESULTS
    LogViewerClient logViewerClient =
            new LogViewerClient(context.getContextUrls().getBackEndUrl(), getSessionCookie());
    boolean logFound = Utils.checkForLog(logViewerClient, "Jack", 10);
    assertTrue(logFound, "Message process retry does not work for json");
}
 
示例27
@Test(groups = "wso2.esb", description = "Inbound HTTP Super Tenant Sequence Dispatch")
public void inboundHttpSuperSequenceTest() throws Exception {

    HttpRequestUtil.doPost(new URL(urlContext), REQUEST_PAYLOAD, new HashMap<>());
    //this case matches with the regex but there is no api or proxy so dispatch to  super tenant main sequence
    Assert.assertTrue(carbonLogReader.checkForLog("main sequence executed for call to non-existent = /", DEFAULT_TIMEOUT));
    carbonLogReader.clearLogs();
}
 
示例28
private void executeSequenceAndAssertResponse(String apiName, String expectedOutput, String errorMessage)
        throws Exception {
    URL endpoint = new URL(getApiInvocationURL(apiName));

    Map<String, String> header = new HashMap<String, String>();
    header.put("Content-Type", "application/json");

    HttpResponse httpResponse = HttpRequestUtil.doPost(endpoint, input, header);

    assertEqualJsonObjects(httpResponse.getData(), expectedOutput, errorMessage);
}
 
示例29
/**
 * This test method verify last query param empty and missing equal sign return expected response for given
 * resource template
 * <p>
 * Resource - /pattern2*
 *
 * @throws Exception
 */
@Test(groups = { "wso2.esb" })
public void testResourcePattern2WithLastParameterEmptyAndMissingEqualSign() throws Exception {
    HttpResponse response = HttpRequestUtil
            .sendGetRequest(getApiInvocationURL("last-query-param-empty/pattern2?latitude=10&longitude=20&floor"),
                    null);
    Assert.assertNotNull(response);
    int responseCode = response.getResponseCode();
    String responseData = response.getData();
    Assert.assertEquals(responseCode, 200);
    Assert.assertEquals(responseData, "<m:checkQueryParam xmlns:m=\"http://services.samples/xsd\">"
                    + "<m:latitude>10</m:latitude><m:longitude>20&amp;floor</m:longitude><m:floor/></m:checkQueryParam>",
            "Query Parameter isn't evaluated according the standard");
}
 
示例30
/**
 * This test method verify last query param empty return expected response for given resource template
 * <p>
 * Resource - /pattern2*
 *
 * @throws Exception
 */
@Test(groups = { "wso2.esb" })
public void testResourcePattern2WithLastParameterEmpty() throws Exception {
    HttpResponse response = HttpRequestUtil
            .sendGetRequest(getApiInvocationURL("last-query-param-empty/pattern2?latitude=10&longitude=20&floor="),
                    null);
    Assert.assertNotNull(response);
    int responseCode = response.getResponseCode();
    String responseData = response.getData();
    Assert.assertEquals(responseCode, 200);
    Assert.assertEquals(responseData, "<m:checkQueryParam xmlns:m=\"http://services.samples/xsd\">"
            + "<m:latitude>10</m:latitude><m:longitude>20</m:longitude><m:floor/></m:checkQueryParam>");
}