Skip to content
This repository was archived by the owner on Mar 11, 2022. It is now read-only.

Commit 62b5690

Browse files
committed
Test updates for exception throwing
1 parent 8a4caea commit 62b5690

3 files changed

Lines changed: 51 additions & 76 deletions

File tree

cloudant-client/src/test/java/com/cloudant/tests/HttpIamTest.java

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@
3232
import static org.hamcrest.CoreMatchers.containsString;
3333
import static org.hamcrest.MatcherAssert.assertThat;
3434
import static org.junit.jupiter.api.Assertions.assertEquals;
35-
import static org.junit.jupiter.api.Assertions.fail;
35+
import static org.junit.jupiter.api.Assertions.assertThrows;
36+
import static org.junit.jupiter.api.Assertions.assertTrue;
3637

3738
import com.cloudant.client.api.CloudantClient;
3839
import com.cloudant.client.org.lightcouch.CouchDbException;
@@ -282,8 +283,8 @@ public void iamTokenAndCookieWithExpirySuccessful() throws Exception {
282283
* - Cookie jar empty, so get IAM token followed by session cookie
283284
* - GET now proceeds as normal, expected cookie value is sent in header
284285
* - second GET on cloudant server, re-using session cookie
285-
* - third GET on cloudant server, cookie expired, subsequent IAM token fails, no more requests
286-
* are made
286+
* - third GET on cloudant server, cookie expired, subsequent IAM token fails
287+
* - exception is thrown
287288
*
288289
* @throws Exception
289290
*/
@@ -317,12 +318,13 @@ public void iamRenewalFailureOnIamToken() throws Exception {
317318
// this never gets a response because the token failure stops the playback - this is
318319
// correct because the underlying stream has now been closed but the exception is a bit
319320
// unhelpful
320-
try {
321-
c.executeRequest(Http.GET(c.getBaseUri())).responseAsString();
322-
fail("Should get CouchDbException when trying to get response");
323-
} catch (CouchDbException cdbe) {
324-
;
325-
}
321+
CouchDbException re =
322+
assertThrows(CouchDbException.class,
323+
() -> c.executeRequest(Http.GET(c.getBaseUri())).responseAsString(),
324+
"Failure to get a token should throw a CouchDbException.");
325+
re.printStackTrace();
326+
assertTrue(re.getMessage().startsWith("HTTP response error getting session"), "The " +
327+
"exception should have been for a HTTP response error.");
326328

327329
// cloudant mock server
328330

@@ -372,7 +374,7 @@ public void iamRenewalFailureOnIamToken() throws Exception {
372374
* - GET now proceeds as normal, expected cookie value is sent in header
373375
* - second GET on cloudant server, re-using session cookie
374376
* - third GET on cloudant server, cookie expired, get IAM token, subsequent session cookie
375-
* request fails, no more requests are made
377+
* request fails, CouchDbException
376378
*
377379
* @throws Exception
378380
*/
@@ -404,15 +406,10 @@ public void iamRenewalFailureOnSessionCookie() throws Exception {
404406
String response2 = c.executeRequest(Http.GET(c.getBaseUri())).responseAsString();
405407
assertEquals(hello, response2, "The expected response should be received");
406408

407-
// this never gets a response because the token failure stops the playback - this is
408-
// correct because the underlying stream has now been closed but the exception is a bit
409-
// unhelpful
410-
try {
411-
c.executeRequest(Http.GET(c.getBaseUri())).responseAsString();
412-
fail("Should get CouchDbException when trying to get response");
413-
} catch (CouchDbException cdbe) {
414-
;
415-
}
409+
assertThrows(CouchDbException.class,
410+
() -> c.executeRequest(Http.GET(c.getBaseUri())).responseAsString(), "Should get " +
411+
"a CouchDbException when _iam_session renewal fails.");
412+
416413
// cloudant mock server
417414

418415
// assert that there were 5 calls

cloudant-client/src/test/java/com/cloudant/tests/HttpTest.java

Lines changed: 23 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@
1414
package com.cloudant.tests;
1515

1616
import static com.cloudant.tests.util.MockWebServerResources.EXPECTED_OK_COOKIE;
17+
import static com.cloudant.tests.util.MockWebServerResources.EXPECTED_OK_COOKIE_2;
18+
import static com.cloudant.tests.util.MockWebServerResources.OK_COOKIE;
19+
import static com.cloudant.tests.util.MockWebServerResources.OK_COOKIE_2;
1720
import static org.hamcrest.CoreMatchers.anyOf;
1821
import static org.hamcrest.CoreMatchers.containsString;
1922
import static org.hamcrest.MatcherAssert.assertThat;
@@ -262,7 +265,7 @@ public void testCookieAuthWithoutRetry() throws IOException {
262265
@TestTemplate
263266
public void testCookieAuthWithPath() throws Exception {
264267
MockWebServer mockWebServer = new MockWebServer();
265-
mockWebServer.enqueue(MockWebServerResources.OK_COOKIE);
268+
mockWebServer.enqueue(OK_COOKIE);
266269
mockWebServer.enqueue(MockWebServerResources.JSON_OK);
267270
CloudantClient client = ClientBuilder.url(mockWebServer.url("/pathex").url())
268271
.username("user")
@@ -331,7 +334,7 @@ public void cookieInterceptorURLEncoding() throws Exception {
331334
String mockPass = "?&=NotAsStrangeInAPassword";
332335

333336
//expect a cookie request then a GET
334-
mockWebServer.enqueue(MockWebServerResources.OK_COOKIE);
337+
mockWebServer.enqueue(OK_COOKIE);
335338
mockWebServer.enqueue(new MockResponse());
336339

337340
CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer)
@@ -369,7 +372,7 @@ public void cookieRenewal() throws Exception {
369372
// _session request to get Cookie
370373
// GET request -> 200 with a Set-Cookie
371374
// GET replay -> 200
372-
mockWebServer.enqueue(MockWebServerResources.OK_COOKIE);
375+
mockWebServer.enqueue(OK_COOKIE);
373376
mockWebServer.enqueue(new MockResponse().setResponseCode(200).addHeader("Set-Cookie",
374377
MockWebServerResources.authSessionCookie(renewalCookieToken, null))
375378
.setBody(hello));
@@ -478,7 +481,7 @@ public void handleNonExpiry403NullReason() throws Exception {
478481
*/
479482
private void basic403Test(String error, String reason, int expectedRequests) throws
480483
Exception {
481-
mockWebServer.enqueue(MockWebServerResources.OK_COOKIE);
484+
mockWebServer.enqueue(OK_COOKIE);
482485
JsonObject responseBody = new JsonObject();
483486
responseBody.add("error", new JsonPrimitive(error));
484487
JsonElement jsonReason;
@@ -493,7 +496,7 @@ private void basic403Test(String error, String reason, int expectedRequests) thr
493496
}
494497
mockWebServer.enqueue(new MockResponse().setResponseCode(403).setBody(responseBody
495498
.toString()));
496-
mockWebServer.enqueue(MockWebServerResources.OK_COOKIE);
499+
mockWebServer.enqueue(OK_COOKIE);
497500
mockWebServer.enqueue(new MockResponse());
498501

499502
CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer)
@@ -667,10 +670,10 @@ private void testInputStreamRetry(HttpConnection request, byte[] expectedContent
667670
@TestTemplate
668671
public void testCookieRenewOnPost() throws Exception {
669672

670-
mockWebServer.enqueue(MockWebServerResources.OK_COOKIE);
673+
mockWebServer.enqueue(OK_COOKIE);
671674
mockWebServer.enqueue(new MockResponse().setResponseCode(403).setBody
672675
("{\"error\":\"credentials_expired\", \"reason\":\"Session expired\"}\r\n"));
673-
mockWebServer.enqueue(MockWebServerResources.OK_COOKIE);
676+
mockWebServer.enqueue(OK_COOKIE);
674677
mockWebServer.enqueue(new MockResponse());
675678

676679
CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer)
@@ -976,7 +979,7 @@ public void execute() throws Throwable {
976979
*/
977980
@TestTemplate
978981
public void cookieAppliedToDifferentURL() throws Exception {
979-
mockWebServer.enqueue(MockWebServerResources.OK_COOKIE);
982+
mockWebServer.enqueue(OK_COOKIE);
980983
mockWebServer.enqueue(new MockResponse().setBody("first"));
981984
mockWebServer.enqueue(new MockResponse().setBody("second"));
982985

@@ -1023,54 +1026,26 @@ public void cookieAppliedToDifferentURL() throws Exception {
10231026
}
10241027

10251028
/**
1026-
* Test that cookie authentication is stopped if the credentials were bad.
1029+
* Test that cookie authentication throws a CouchDbException if the credentials were bad.
10271030
*
10281031
* @throws Exception
10291032
*/
10301033
@TestTemplate
1031-
public void badCredsDisablesCookie() throws Exception {
1032-
mockWebServer.setDispatcher(new Dispatcher() {
1033-
private int counter = 0;
1034-
1035-
@Override
1036-
public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
1037-
counter++;
1038-
// Return a 401 for the first _session request, after that return 200 OKs
1039-
if (counter == 1) {
1040-
return new MockResponse().setResponseCode(401);
1041-
} else {
1042-
return new MockResponse().setBody("TEST");
1043-
}
1044-
}
1045-
});
1034+
public void badCredsCookieThrows() {
1035+
mockWebServer.enqueue(new MockResponse().setResponseCode(401));
10461036

10471037
CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer)
10481038
.username("bad")
10491039
.password("worse")
10501040
.build();
10511041

1052-
String response = c.executeRequest(Http.GET(c.getBaseUri())).responseAsString();
1053-
assertEquals("TEST", response, "The expected response body should be received");
1042+
CouchDbException re =
1043+
assertThrows(CouchDbException.class,
1044+
() -> c.executeRequest(Http.GET(c.getBaseUri())).responseAsString(),
1045+
"Bad credentials should throw a CouchDbException.");
10541046

1055-
// There should only be two requests: an initial auth failure followed by an ok response.
1056-
// If the cookie interceptor keeps trying then there will be more _session requests.
1057-
assertEquals(2, mockWebServer.getRequestCount(), "There should be 2 requests");
1058-
1059-
assertEquals("/_session",
1060-
MockWebServerResources.takeRequestWithTimeout(mockWebServer).getPath(), "The " +
1061-
"first request should have been for a cookie");
1062-
assertEquals("/",
1063-
MockWebServerResources.takeRequestWithTimeout(mockWebServer).getPath(), "The " +
1064-
"second request should have been for /");
1065-
1066-
response = c.executeRequest(Http.GET(c.getBaseUri())).responseAsString();
1067-
assertEquals("TEST", response, "The expected response body should be received");
1068-
1069-
// Make another request, the cookie interceptor should not try again so there should only be
1070-
// one more request.
1071-
assertEquals(3, mockWebServer.getRequestCount(), "There should be 3 requests");
1072-
assertEquals("/", MockWebServerResources.takeRequestWithTimeout(mockWebServer).getPath(),
1073-
"The third request should have been for /");
1047+
assertTrue(re.getMessage().startsWith("Credentials are incorrect for server"), "The " +
1048+
"exception should have been for bad creds.");
10741049
}
10751050

10761051
/**
@@ -1087,7 +1062,7 @@ public void noErrorStream403() throws Exception {
10871062
public void execute() throws Throwable {
10881063

10891064
// Respond with a cookie init to the first request to _session
1090-
mockWebServer.enqueue(MockWebServerResources.OK_COOKIE);
1065+
mockWebServer.enqueue(OK_COOKIE);
10911066
// Respond to the executeRequest GET of / with a 403 with no body
10921067
mockWebServer.enqueue(new MockResponse().setResponseCode(403));
10931068
CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer)
@@ -1111,11 +1086,11 @@ public void execute() throws Throwable {
11111086
public void noErrorStream401() throws Exception {
11121087

11131088
// Respond with a cookie init to the first request to _session
1114-
mockWebServer.enqueue(MockWebServerResources.OK_COOKIE);
1089+
mockWebServer.enqueue(OK_COOKIE);
11151090
// Respond to the executeRequest GET of / with a 401 with no body
11161091
mockWebServer.enqueue(new MockResponse().setResponseCode(401));
11171092
// 401 triggers a renewal so respond with a new cookie for renewal request to _session
1118-
mockWebServer.enqueue(MockWebServerResources.OK_COOKIE);
1093+
mockWebServer.enqueue(OK_COOKIE);
11191094
// Finally respond 200 OK with body of "TEST" to the replay of GET to /
11201095
mockWebServer.enqueue(new MockResponse().setBody("TEST"));
11211096

cloudant-client/src/test/java/com/cloudant/tests/SslAuthenticationTest.java

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright © 2015, 2018 IBM Corp. All rights reserved.
2+
* Copyright © 2015, 2019 IBM Corp. All rights reserved.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
55
* except in compliance with the License. You may obtain a copy of the License at
@@ -17,7 +17,6 @@
1717
import static org.junit.jupiter.api.Assertions.assertNotNull;
1818
import static org.junit.jupiter.api.Assertions.assertThrows;
1919
import static org.junit.jupiter.api.Assertions.assertTrue;
20-
import static org.junit.jupiter.api.Assertions.fail;
2120

2221
import com.cloudant.client.api.CloudantClient;
2322
import com.cloudant.client.org.lightcouch.CouchDbException;
@@ -41,6 +40,7 @@
4140
import okhttp3.mockwebserver.MockResponse;
4241
import okhttp3.mockwebserver.MockWebServer;
4342

43+
import java.io.IOException;
4444
import java.util.Collections;
4545
import java.util.List;
4646
import java.util.stream.Stream;
@@ -120,7 +120,13 @@ public void beforeEach() {
120120
*/
121121
private static void validateClientAuthenticationException(CouchDbException e) {
122122
assertNotNull(e, "Expected CouchDbException but got null");
123-
Throwable t = e.getCause();
123+
Throwable t;
124+
t = e.getCause();
125+
if (!(t instanceof SSLHandshakeException) && (t instanceof IOException)) {
126+
// In the case of a SSLException from the cookie interceptor
127+
// we will have an IOException first, get the cause of that to check
128+
t = t.getCause();
129+
}
124130
assertTrue(t instanceof SSLHandshakeException, "Expected SSLHandshakeException caused by " +
125131
"client certificate check but got " + t.getClass());
126132
}
@@ -277,12 +283,9 @@ public void localSSLAuthenticationEnabledWithCookieAuth() throws Exception {
277283
.password("password")
278284
.build();
279285

280-
try {
281-
dbClient.getAllDbs();
282-
fail("The SSL authentication failure should result in a CouchDbException");
283-
} catch (CouchDbException e) {
284-
validateClientAuthenticationException(e);
285-
}
286+
CouchDbException e = assertThrows(CouchDbException.class, () -> dbClient.getAllDbs(),
287+
"The SSL authentication failure should result in a RuntimeException.");
288+
validateClientAuthenticationException(e);
286289
}
287290

288291
}

0 commit comments

Comments
 (0)