Search in sources :

Example 1 with TestTemplate

use of org.junit.jupiter.api.TestTemplate in project java-cloudant by cloudant.

the class HttpProxyTest method proxiedRequest.

/**
 * This test validates that a request can successfully traverse a proxy to our mock server.
 */
@TestTemplate
public void proxiedRequest(final boolean okUsable, final boolean useSecureProxy, final boolean useHttpsServer, final boolean useProxyAuth) throws Exception {
    // mock a 200 OK
    server.setDispatcher(new Dispatcher() {

        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            return new MockResponse();
        }
    });
    InetSocketAddress address = proxy.getListenAddress();
    URL proxyUrl = new URL((useSecureProxy) ? "https" : "http", address.getHostName(), address.getPort(), "/");
    ClientBuilder builder = CloudantClientHelper.newMockWebServerClientBuilder(server).proxyURL(proxyUrl);
    if (useProxyAuth) {
        builder.proxyUser(mockProxyUser).proxyPassword(mockProxyPass);
    }
    // We don't use SSL authentication for this test
    CloudantClient client = builder.disableSSLAuthentication().build();
    String response = client.executeRequest(Http.GET(client.getBaseUri())).responseAsString();
    assertTrue(response.isEmpty(), "There should be no response body on the mock response");
    // if it wasn't a 20x then an exception should have been thrown by now
    RecordedRequest request = server.takeRequest(10, TimeUnit.SECONDS);
    assertNotNull(request);
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) CloudantClient(com.cloudant.client.api.CloudantClient) InetSocketAddress(java.net.InetSocketAddress) Dispatcher(okhttp3.mockwebserver.Dispatcher) URL(java.net.URL) ClientBuilder(com.cloudant.client.api.ClientBuilder) TestTemplate(org.junit.jupiter.api.TestTemplate)

Example 2 with TestTemplate

use of org.junit.jupiter.api.TestTemplate in project java-cloudant by cloudant.

the class HttpTest method badCredsDisablesCookie.

/**
 * Test that cookie authentication is stopped if the credentials were bad.
 *
 * @throws Exception
 */
@TestTemplate
public void badCredsDisablesCookie() throws Exception {
    mockWebServer.setDispatcher(new Dispatcher() {

        private int counter = 0;

        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            counter++;
            // Return a 401 for the first _session request, after that return 200 OKs
            if (counter == 1) {
                return new MockResponse().setResponseCode(401);
            } else {
                return new MockResponse().setBody("TEST");
            }
        }
    });
    CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer).username("bad").password("worse").build();
    String response = c.executeRequest(Http.GET(c.getBaseUri())).responseAsString();
    assertEquals("TEST", response, "The expected response body should be received");
    // There should only be two requests: an initial auth failure followed by an ok response.
    // If the cookie interceptor keeps trying then there will be more _session requests.
    assertEquals(2, mockWebServer.getRequestCount(), "There should be 2 requests");
    assertEquals("/_session", MockWebServerResources.takeRequestWithTimeout(mockWebServer).getPath(), "The " + "first request should have been for a cookie");
    assertEquals("/", MockWebServerResources.takeRequestWithTimeout(mockWebServer).getPath(), "The " + "second request should have been for /");
    response = c.executeRequest(Http.GET(c.getBaseUri())).responseAsString();
    assertEquals("TEST", response, "The expected response body should be received");
    // Make another request, the cookie interceptor should not try again so there should only be
    // one more request.
    assertEquals(3, mockWebServer.getRequestCount(), "There should be 3 requests");
    assertEquals("/", MockWebServerResources.takeRequestWithTimeout(mockWebServer).getPath(), "The third request should have been for /");
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) CloudantClient(com.cloudant.client.api.CloudantClient) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) Dispatcher(okhttp3.mockwebserver.Dispatcher) TestTemplate(org.junit.jupiter.api.TestTemplate)

Example 3 with TestTemplate

use of org.junit.jupiter.api.TestTemplate in project java-cloudant by cloudant.

the class HttpTest method testCookieAuthWithoutRetry.

// NOTE: This test doesn't work with specified couch servers,
// the URL will always include the creds specified for the test
// 
// A couchdb server needs to be set and running with the correct
// security settings, the database *must* not be public, it *must*
// be named cookie_test
// 
@TestTemplate
@RequiresCloudant
public void testCookieAuthWithoutRetry() throws IOException {
    CookieInterceptor interceptor = new CookieInterceptor(CloudantClientHelper.COUCH_USERNAME, CloudantClientHelper.COUCH_PASSWORD, clientResource.get().getBaseUri().toString());
    HttpConnection conn = new HttpConnection("POST", dbResource.get().getDBUri().toURL(), "application/json");
    conn.responseInterceptors.add(interceptor);
    conn.requestInterceptors.add(interceptor);
    ByteArrayInputStream bis = new ByteArrayInputStream(data.getBytes());
    // nothing read from stream
    assertEquals(data.getBytes().length, bis.available());
    conn.setRequestBody(bis);
    HttpConnection responseConn = conn.execute();
    // stream was read to end
    assertEquals(0, bis.available());
    assertEquals(2, responseConn.getConnection().getResponseCode() / 100);
    // check the json
    Gson gson = new Gson();
    InputStream is = responseConn.responseAsInputStream();
    try {
        JsonObject response = gson.fromJson(new InputStreamReader(is), JsonObject.class);
        assertTrue(response.has("ok"));
        assertTrue(response.get("ok").getAsBoolean());
        assertTrue(response.has("id"));
        assertTrue(response.has("rev"));
    } finally {
        is.close();
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) HttpConnection(com.cloudant.http.HttpConnection) ByteArrayInputStream(java.io.ByteArrayInputStream) CookieInterceptor(com.cloudant.http.internal.interceptors.CookieInterceptor) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) TestTemplate(org.junit.jupiter.api.TestTemplate) RequiresCloudant(com.cloudant.test.main.RequiresCloudant)

Example 4 with TestTemplate

use of org.junit.jupiter.api.TestTemplate in project java-cloudant by cloudant.

the class HttpTest method testChunking.

/**
 * Test that chunking is used when input stream length is not known.
 *
 * @throws Exception
 */
@TestTemplate
public void testChunking() throws Exception {
    mockWebServer.enqueue(new MockResponse());
    final int chunkSize = 1024 * 8;
    final int chunks = 50 * 4;
    CloudantClient client = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer).build();
    // POST some large random data
    String response = client.executeRequest(Http.POST(mockWebServer.url("/").url(), "text/plain").setRequestBody(new RandomInputStreamGenerator(chunks * chunkSize))).responseAsString();
    assertTrue(response.isEmpty(), "There should be no response body on the mock response");
    assertEquals(1, mockWebServer.getRequestCount(), "There should have been 1 request");
    RecordedRequest request = MockWebServerResources.takeRequestWithTimeout(mockWebServer);
    assertNotNull(request, "The recorded request should not be null");
    assertNull(request.getHeader("Content-Length"), "There should be no Content-Length header");
    assertEquals("chunked", request.getHeader("Transfer-Encoding"), "The Transfer-Encoding should be chunked");
    // It would be nice to assert that we got the chunk sizes we were expecting, but sadly the
    // HttpURLConnection and ChunkedOutputStream only use the chunkSize as a suggestion and seem
    // to use the buffer size instead. The best assertion we can make is that we did receive
    // multiple chunks.
    assertTrue(request.getChunkSizes().size() > 1, "There should have been at least 2 chunks");
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) CloudantClient(com.cloudant.client.api.CloudantClient) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) TestTemplate(org.junit.jupiter.api.TestTemplate)

Example 5 with TestTemplate

use of org.junit.jupiter.api.TestTemplate in project java-cloudant by cloudant.

the class HttpTest method inputStreamRetryBytes.

@TestTemplate
public void inputStreamRetryBytes() throws Exception {
    HttpConnection request = Http.POST(mockWebServer.url("/").url(), "application/json");
    byte[] content = "abcde".getBytes("UTF-8");
    request.setRequestBody(content);
    testInputStreamRetry(request, content);
}
Also used : HttpConnection(com.cloudant.http.HttpConnection) TestTemplate(org.junit.jupiter.api.TestTemplate)

Aggregations

TestTemplate (org.junit.jupiter.api.TestTemplate)51 CloudantClient (com.cloudant.client.api.CloudantClient)23 URI (java.net.URI)18 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)18 MockResponse (okhttp3.mockwebserver.MockResponse)16 HttpConnection (com.cloudant.http.HttpConnection)11 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)7 TreeMap (java.util.TreeMap)5 TestTimer (com.cloudant.tests.util.TestTimer)4 ByteArrayInputStream (java.io.ByteArrayInputStream)4 URL (java.net.URL)4 TooManyRequestsException (com.cloudant.client.org.lightcouch.TooManyRequestsException)3 Replay429Interceptor (com.cloudant.http.interceptors.Replay429Interceptor)3 CouchDbException (com.cloudant.client.org.lightcouch.CouchDbException)2 HttpConnectionInterceptorContext (com.cloudant.http.HttpConnectionInterceptorContext)2 RequiresCloudant (com.cloudant.test.main.RequiresCloudant)2 RequiresCloudantService (com.cloudant.test.main.RequiresCloudantService)2 Gson (com.google.gson.Gson)2 JsonObject (com.google.gson.JsonObject)2 IOException (java.io.IOException)2