Search in sources :

Example 1 with HttpRequest

use of kong.unirest.HttpRequest in project seleniumRobot by bhecquet.

the class ConnectorsTest method createServerMock.

protected HttpRequest createServerMock(String serverUrl, String requestType, String apiPath, int statusCode, final List<Object> replyData, String responseType) throws UnirestException {
    if (replyData.isEmpty()) {
        throw new TestConfigurationException("No replyData specified");
    }
    @SuppressWarnings("unchecked") HttpResponse<String> response = mock(HttpResponse.class);
    HttpResponse<JsonNode> jsonResponse = mock(HttpResponse.class);
    HttpResponse<File> streamResponse = mock(HttpResponse.class);
    HttpResponse<byte[]> bytestreamResponse = mock(HttpResponse.class);
    HttpRequest request = mock(HttpRequest.class);
    JsonNode json = mock(JsonNode.class);
    HttpRequestWithBody postRequest = spy(HttpRequestWithBody.class);
    // for asPaged method
    PagedList<JsonNode> pageList = new PagedList<>();
    when(request.getUrl()).thenReturn(serverUrl);
    if (replyData.get(0) instanceof String) {
        when(response.getStatus()).thenReturn(statusCode);
        // when(response.getBody()).thenReturn(replyData.toArray(new String[] {}));
        when(response.getBody()).then(new Answer<String>() {

            private int count = -1;

            public String answer(InvocationOnMock invocation) {
                count++;
                if (count >= replyData.size() - 1) {
                    return (String) replyData.get(replyData.size() - 1);
                } else {
                    return (String) replyData.get(count);
                }
            }
        });
        when(response.getStatusText()).thenReturn("TEXT");
        when(jsonResponse.getStatus()).thenReturn(statusCode);
        when(jsonResponse.getBody()).thenReturn(json);
        when(jsonResponse.getStatusText()).thenReturn("TEXT");
        try {
            // check data is compatible with JSON
            for (Object d : replyData) {
                if (((String) d).isEmpty()) {
                    d = "{}";
                }
                new JSONObject((String) d);
            }
            // JSONObject jsonReply = new JSONObject((String)replyData);
            // when(json.getObject()).thenReturn(jsonReply);
            when(json.getObject()).then(new Answer<JSONObject>() {

                private int count = -1;

                public JSONObject answer(InvocationOnMock invocation) {
                    count++;
                    String reply;
                    if (count >= replyData.size() - 1) {
                        reply = (String) replyData.get(replyData.size() - 1);
                    } else {
                        reply = (String) replyData.get(count);
                    }
                    if (reply.isEmpty()) {
                        reply = "{}";
                    }
                    return new JSONObject(reply);
                }
            });
            pageList = new PagedList<>();
            pageList.add(jsonResponse);
        } catch (JSONException e) {
        }
    } else if (replyData.get(0) instanceof File) {
        when(streamResponse.getStatus()).thenReturn(statusCode);
        when(streamResponse.getStatusText()).thenReturn("TEXT");
        when(streamResponse.getBody()).then(new Answer<File>() {

            private int count = -1;

            public File answer(InvocationOnMock invocation) {
                count++;
                if (count >= replyData.size() - 1) {
                    return (File) replyData.get(replyData.size() - 1);
                } else {
                    return (File) replyData.get(count);
                }
            }
        });
        // when(bytestreamResponse.getBody()).thenReturn(FileUtils.readFileToByteArray((File)replyData));
        when(bytestreamResponse.getBody()).then(new Answer<byte[]>() {

            private int count = -1;

            public byte[] answer(InvocationOnMock invocation) throws IOException {
                count++;
                if (count >= replyData.size() - 1) {
                    return (byte[]) FileUtils.readFileToByteArray((File) replyData.get(replyData.size() - 1));
                } else {
                    return (byte[]) FileUtils.readFileToByteArray((File) replyData.get(count));
                }
            }
        });
        when(bytestreamResponse.getStatus()).thenReturn(statusCode);
        when(bytestreamResponse.getStatusText()).thenReturn("BYTES");
    }
    switch(requestType) {
        case "GET":
            GetRequest getRequest = mock(GetRequest.class);
            when(Unirest.get(serverUrl + apiPath)).thenReturn(getRequest);
            when(getRequest.socketTimeout(anyInt())).thenReturn(getRequest);
            when(unirestInstance.get(serverUrl + apiPath)).thenReturn(getRequest);
            when(getRequest.header(anyString(), anyString())).thenReturn(getRequest);
            when(getRequest.asString()).thenReturn(response);
            when(getRequest.asJson()).thenReturn(jsonResponse);
            when(getRequest.asFile(anyString())).thenReturn(streamResponse);
            when(getRequest.asBytes()).thenReturn(bytestreamResponse);
            when(getRequest.queryString(anyString(), anyString())).thenReturn(getRequest);
            when(getRequest.queryString(anyString(), anyInt())).thenReturn(getRequest);
            when(getRequest.queryString(anyString(), anyBoolean())).thenReturn(getRequest);
            when(getRequest.queryString(anyString(), any(SessionId.class))).thenReturn(getRequest);
            when(getRequest.getUrl()).thenReturn(serverUrl);
            when(getRequest.basicAuth(anyString(), anyString())).thenReturn(getRequest);
            when(getRequest.headerReplace(anyString(), anyString())).thenReturn(getRequest);
            when(getRequest.asPaged(any(), (Function<HttpResponse<JsonNode>, String>) any(Function.class))).thenReturn(pageList);
            return getRequest;
        case "POST":
            when(Unirest.post(serverUrl + apiPath)).thenReturn(postRequest);
            when(unirestInstance.post(serverUrl + apiPath)).thenReturn(postRequest);
            return preparePostRequest(serverUrl, responseType, postRequest, response, jsonResponse);
        case "PATCH":
            when(Unirest.patch(serverUrl + apiPath)).thenReturn(postRequest);
            when(unirestInstance.patch(serverUrl + apiPath)).thenReturn(postRequest);
            return preparePostRequest(serverUrl, responseType, postRequest, response, jsonResponse);
        case "PUT":
            when(Unirest.put(serverUrl + apiPath)).thenReturn(postRequest);
            when(unirestInstance.put(serverUrl + apiPath)).thenReturn(postRequest);
            return preparePostRequest(serverUrl, responseType, postRequest, response, jsonResponse);
    }
    return null;
}
Also used : PagedList(kong.unirest.PagedList) JsonNode(kong.unirest.JsonNode) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) GetRequest(kong.unirest.GetRequest) TestConfigurationException(com.seleniumtests.ut.exceptions.TestConfigurationException) SessionId(org.openqa.selenium.remote.SessionId) HttpRequest(kong.unirest.HttpRequest) JSONException(kong.unirest.json.JSONException) HttpResponse(kong.unirest.HttpResponse) Point(org.openqa.selenium.Point) Answer(org.mockito.stubbing.Answer) JSONObject(kong.unirest.json.JSONObject) HttpRequestWithBody(kong.unirest.HttpRequestWithBody) InvocationOnMock(org.mockito.invocation.InvocationOnMock) JSONObject(kong.unirest.json.JSONObject) File(java.io.File)

Example 2 with HttpRequest

use of kong.unirest.HttpRequest in project seleniumRobot by bhecquet.

the class ConnectorsTest method createJsonServerMock.

protected OngoingStubbing<JsonNode> createJsonServerMock(String requestType, String apiPath, int statusCode, String... replyData) throws UnirestException {
    @SuppressWarnings("unchecked") HttpResponse<JsonNode> jsonResponse = mock(HttpResponse.class);
    HttpRequest request = mock(HttpRequest.class);
    MultipartBody requestMultipartBody = mock(MultipartBody.class);
    HttpRequestWithBody postRequest = mock(HttpRequestWithBody.class);
    when(request.getUrl()).thenReturn(SERVER_URL);
    when(jsonResponse.getStatus()).thenReturn(statusCode);
    OngoingStubbing<JsonNode> stub = when(jsonResponse.getBody()).thenReturn(new JsonNode(replyData[0]));
    for (String reply : Arrays.asList(replyData).subList(1, replyData.length)) {
        stub = stub.thenReturn(new JsonNode(reply));
    }
    switch(requestType) {
        case "GET":
            GetRequest getRequest = mock(GetRequest.class);
            when(Unirest.get(SERVER_URL + apiPath)).thenReturn(getRequest);
            when(getRequest.header(anyString(), anyString())).thenReturn(getRequest);
            when(getRequest.asJson()).thenReturn(jsonResponse);
            when(getRequest.queryString(anyString(), anyString())).thenReturn(getRequest);
            when(getRequest.queryString(anyString(), anyInt())).thenReturn(getRequest);
            when(getRequest.queryString(anyString(), anyBoolean())).thenReturn(getRequest);
            return stub;
        case "POST":
            when(Unirest.post(SERVER_URL + apiPath)).thenReturn(postRequest);
        case "PATCH":
            when(Unirest.patch(SERVER_URL + apiPath)).thenReturn(postRequest);
            when(postRequest.field(anyString(), anyString())).thenReturn(requestMultipartBody);
            when(postRequest.field(anyString(), anyInt())).thenReturn(requestMultipartBody);
            when(postRequest.field(anyString(), anyLong())).thenReturn(requestMultipartBody);
            when(postRequest.field(anyString(), any(File.class))).thenReturn(requestMultipartBody);
            when(postRequest.queryString(anyString(), anyString())).thenReturn(postRequest);
            when(postRequest.queryString(anyString(), anyInt())).thenReturn(postRequest);
            when(postRequest.queryString(anyString(), anyBoolean())).thenReturn(postRequest);
            when(postRequest.header(anyString(), anyString())).thenReturn(postRequest);
            when(requestMultipartBody.field(anyString(), anyString())).thenReturn(requestMultipartBody);
            when(requestMultipartBody.field(anyString(), any(File.class))).thenReturn(requestMultipartBody);
            return stub;
    }
    return null;
}
Also used : HttpRequest(kong.unirest.HttpRequest) MultipartBody(kong.unirest.MultipartBody) HttpRequestWithBody(kong.unirest.HttpRequestWithBody) GetRequest(kong.unirest.GetRequest) JsonNode(kong.unirest.JsonNode) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) File(java.io.File)

Example 3 with HttpRequest

use of kong.unirest.HttpRequest in project seleniumRobot by bhecquet.

the class TestSeleniumRobotVariableServerConnector method testFetchVariableWithNetworkError.

@Test(groups = { "ut" }, expectedExceptions = SeleniumRobotServerException.class)
public void testFetchVariableWithNetworkError() throws UnirestException {
    configureMockedVariableServerConnection();
    HttpRequest<HttpRequest> req = createServerMock(SERVER_URL, "GET", SeleniumRobotVariableServerConnector.VARIABLE_API_URL, 200, "{}");
    when(req.asString()).thenThrow(UnirestException.class);
    SeleniumRobotVariableServerConnector connector = new SeleniumRobotVariableServerConnector(true, SERVER_URL, "Test1", null);
    Map<String, TestVariable> variables = connector.getVariables();
    Assert.assertEquals(variables.get("key1").getValue(), "value1");
    Assert.assertEquals(variables.get("key2").getValue(), "value2");
}
Also used : HttpRequest(kong.unirest.HttpRequest) TestVariable(com.seleniumtests.core.TestVariable) SeleniumRobotVariableServerConnector(com.seleniumtests.connectors.selenium.SeleniumRobotVariableServerConnector) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Test(org.testng.annotations.Test) ConnectorsTest(com.seleniumtests.ConnectorsTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 4 with HttpRequest

use of kong.unirest.HttpRequest in project seleniumRobot by bhecquet.

the class TestSeleniumRobotSnapshotServerConnector method testCreateSnapshotInError.

@Test(groups = { "ut" }, expectedExceptions = SeleniumRobotServerException.class)
public void testCreateSnapshotInError() throws UnirestException {
    SeleniumRobotSnapshotServerConnector connector = configureMockedSnapshotServerConnection();
    HttpRequest<HttpRequest> req = createServerMock("POST", SeleniumRobotSnapshotServerConnector.SNAPSHOT_API_URL, 200, "{'id': '9'}", "body");
    when(req.asString()).thenThrow(UnirestException.class);
    Integer sessionId = connector.createSession("Session1");
    Integer testCaseId = connector.createTestCase("Test 1");
    Integer testCaseInSessionId = connector.createTestCaseInSession(sessionId, testCaseId, "Test 1");
    Integer testStepId = connector.createTestStep("Step 1", testCaseInSessionId);
    Integer stepResultId = connector.recordStepResult(true, "", 1, sessionId, testCaseInSessionId, testStepId);
    Integer snapshotId = connector.createSnapshot(snapshot, sessionId, testCaseInSessionId, stepResultId);
    Assert.assertNull(snapshotId);
}
Also used : HttpRequest(kong.unirest.HttpRequest) SeleniumRobotSnapshotServerConnector(com.seleniumtests.connectors.selenium.SeleniumRobotSnapshotServerConnector) Test(org.testng.annotations.Test) ConnectorsTest(com.seleniumtests.ConnectorsTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 5 with HttpRequest

use of kong.unirest.HttpRequest in project seleniumRobot by bhecquet.

the class TestSeleniumRobotGridConnector method testLeftClickNoConnection.

/**
 * Test left click when connection error occurs
 * @throws UnsupportedOperationException
 * @throws IOException
 * @throws UnirestException
 */
@Test(groups = { "ut" })
public void testLeftClickNoConnection() throws UnsupportedOperationException, IOException {
    HttpRequest<HttpRequest> req = createServerMock("POST", SeleniumRobotGridConnector.NODE_TASK_SERVLET, 500, "");
    when(req.asString()).thenThrow(new UnirestException("connection error"));
    connector.leftClic(0, 0);
    // error connecting to node
    verify(gridLogger).warn(anyString());
    verify(gridLogger, never()).error(anyString());
}
Also used : HttpRequest(kong.unirest.HttpRequest) UnirestException(kong.unirest.UnirestException) Test(org.testng.annotations.Test) ConnectorsTest(com.seleniumtests.ConnectorsTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

HttpRequest (kong.unirest.HttpRequest)32 ConnectorsTest (com.seleniumtests.ConnectorsTest)30 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)30 Test (org.testng.annotations.Test)30 SeleniumRobotSnapshotServerConnector (com.seleniumtests.connectors.selenium.SeleniumRobotSnapshotServerConnector)15 UnirestException (kong.unirest.UnirestException)13 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)4 File (java.io.File)3 SeleniumRobotVariableServerConnector (com.seleniumtests.connectors.selenium.SeleniumRobotVariableServerConnector)2 TestVariable (com.seleniumtests.core.TestVariable)2 GetRequest (kong.unirest.GetRequest)2 HttpRequestWithBody (kong.unirest.HttpRequestWithBody)2 JsonNode (kong.unirest.JsonNode)2 TestConfigurationException (com.seleniumtests.ut.exceptions.TestConfigurationException)1 Point (java.awt.Point)1 HttpResponse (kong.unirest.HttpResponse)1 MultipartBody (kong.unirest.MultipartBody)1 PagedList (kong.unirest.PagedList)1 JSONException (kong.unirest.json.JSONException)1 JSONObject (kong.unirest.json.JSONObject)1