Skip to content

Commit fe7b7f9

Browse files
committed
add middleware tests
fix OAuthMiddleware to reauthenticate on Exception
1 parent 455d6b3 commit fe7b7f9

File tree

7 files changed

+275
-4
lines changed

7 files changed

+275
-4
lines changed

commercetools/commercetools-sdk-java-api/src/integrationTest/java/commercetools/MiddlewareTest.java

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
import org.assertj.core.util.Lists;
1313
import org.junit.Test;
1414

15-
import java.util.List;
15+
import java.util.concurrent.atomic.AtomicInteger;
1616

1717
import static java.util.Collections.singletonList;
1818

@@ -23,14 +23,21 @@ public class MiddlewareTest {
2323
public void execute() {
2424
String projectKey = CommercetoolsTestUtils.getProjectKey();
2525

26+
AtomicInteger count = new AtomicInteger();
2627
ByProjectKeyRequestBuilder b = ApiFactory.createForProject(
2728
projectKey,
2829
ClientCredentials.of().withClientId(CommercetoolsTestUtils.getClientId())
2930
.withClientSecret(CommercetoolsTestUtils.getClientSecret())
3031
.build(),
3132
ServiceRegion.GCP_EUROPE_WEST1.getOAuthTokenUrl(),
3233
ServiceRegion.GCP_EUROPE_WEST1.getApiUrl(),
33-
Lists.newArrayList(new RetryMiddleware(3, singletonList(404)))
34+
Lists.newArrayList(
35+
(request, next) -> {
36+
count.getAndIncrement();
37+
return next.apply(request);
38+
},
39+
new RetryMiddleware(3, singletonList(404))
40+
)
3441
);
3542

3643

@@ -43,5 +50,6 @@ public void execute() {
4350
.executeBlocking().getBody();
4451
}
4552
);
53+
Assertions.assertThat(count.get()).isEqualTo(4);
4654
}
4755
}

rmf/rmf-java-base/build.gradle

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11

22
dependencies {
33
testImplementation "junit:junit:${versions.junit}"
4+
testImplementation "org.assertj:assertj-core:${versions.assertJ}"
5+
testImplementation "com.tngtech.junit.dataprovider:junit4-dataprovider:2.6"
6+
testImplementation "ch.qos.logback:logback-classic:${versions.logback}"
47

58
implementation "com.google.code.findbugs:jsr305:${versions.findbugs}"
69
implementation "com.fasterxml.jackson.core:jackson-databind:${versions.jackson}"

rmf/rmf-java-base/src/main/java/io/vrap/rmf/base/client/http/OAuthMiddleware.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,8 @@ public OAuthMiddleware(final OAuthHandler oAuthHandler)
2727
public OAuthMiddleware(final OAuthHandler oauthHandler, final Integer maxRetries) {
2828
RetryPolicy<ApiHttpResponse<byte[]>> retry = new RetryPolicy<ApiHttpResponse<byte[]>>()
2929
.handleIf((response, throwable) -> {
30-
if (throwable != null && throwable.getCause() instanceof UnauthorizedException) {
31-
return true;
30+
if (throwable != null) {
31+
return throwable instanceof UnauthorizedException;
3232
}
3333
return response.getStatusCode() == 401;
3434
})
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package io.vrap.rmf.base.client.http;
2+
3+
import com.tngtech.java.junit.dataprovider.DataProvider;
4+
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
5+
import com.tngtech.java.junit.dataprovider.UseDataProvider;
6+
import io.vrap.rmf.base.client.*;
7+
import io.vrap.rmf.base.client.error.*;
8+
import org.assertj.core.api.Assertions;
9+
import org.junit.Test;
10+
import org.junit.runner.RunWith;
11+
12+
import java.net.URI;
13+
import java.time.Duration;
14+
import java.util.concurrent.CompletableFuture;
15+
16+
import static io.vrap.rmf.base.client.utils.ClientUtils.blockingWait;
17+
18+
@RunWith(DataProviderRunner.class)
19+
public class ErrorMiddlewareTest {
20+
21+
22+
@DataProvider
23+
public static Object[][] exceptions() {
24+
return new Object[][] {
25+
{ 400, BadRequestException.class },
26+
{ 401, UnauthorizedException.class },
27+
{ 403, ForbiddenException.class },
28+
{ 404, NotFoundException.class },
29+
{ 409, ConcurrentModificationException.class },
30+
{ 499, ApiClientException.class },
31+
{ 500, InternalServerErrorException.class },
32+
{ 502, BadGatewayException.class },
33+
{ 503, ServiceUnavailableException.class },
34+
{ 504, GatewayTimeoutException.class },
35+
{ 599, ApiServerException.class },
36+
};
37+
}
38+
39+
@Test
40+
@UseDataProvider("exceptions")
41+
public void testError(int statusCode, Class<ApiHttpException> exceptionClass)
42+
{
43+
ErrorMiddleware middleware = new ErrorMiddleware();
44+
45+
final ApiHttpRequest request = new ApiHttpRequest(ApiHttpMethod.GET, URI.create("/"), new ApiHttpHeaders(), "".getBytes());
46+
47+
Assertions.assertThatExceptionOfType(exceptionClass).isThrownBy(() -> {
48+
blockingWait(middleware.invoke(request, request1 -> CompletableFuture.completedFuture(new ApiHttpResponse<>(statusCode, new ApiHttpHeaders(), "".getBytes()))), Duration.ofSeconds(1));
49+
}).matches(e -> e.getStatusCode() == statusCode);
50+
}
51+
}
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
package io.vrap.rmf.base.client.http;
2+
3+
import io.vrap.rmf.base.client.*;
4+
import io.vrap.rmf.base.client.error.UnauthorizedException;
5+
import io.vrap.rmf.base.client.oauth2.StaticTokenSupplier;
6+
import org.assertj.core.api.Assertions;
7+
import org.junit.Assert;
8+
import org.junit.Test;
9+
10+
import java.net.URI;
11+
import java.time.Duration;
12+
import java.util.concurrent.CompletableFuture;
13+
import java.util.concurrent.CompletionException;
14+
import java.util.concurrent.atomic.AtomicInteger;
15+
import java.util.concurrent.atomic.AtomicReference;
16+
17+
import static io.vrap.rmf.base.client.utils.ClientUtils.blockingWait;
18+
19+
public class OAuthMiddlewareTest {
20+
21+
@Test
22+
public void testAddToken()
23+
{
24+
AuthenticationToken token = new AuthenticationToken();
25+
token.setAccessToken("12345");
26+
27+
OAuthMiddleware middleware = new OAuthMiddleware(
28+
new OAuthHandler(new StaticTokenSupplier(token))
29+
);
30+
31+
final ApiHttpRequest request = new ApiHttpRequest(ApiHttpMethod.GET, URI.create("/"), new ApiHttpHeaders(), "".getBytes());
32+
33+
AtomicReference<String> authorizationHeader = new AtomicReference<>();
34+
blockingWait(
35+
middleware.invoke(request, request1 -> {
36+
authorizationHeader.set(request1.getHeaders().getHeaders(ApiHttpHeaders.AUTHORIZATION).get(0).getValue());
37+
return CompletableFuture.completedFuture(new ApiHttpResponse<>(200, new ApiHttpHeaders(), "".getBytes()));
38+
}),
39+
Duration.ofSeconds(1)
40+
);
41+
Assertions.assertThat(authorizationHeader.get()).isEqualTo("Bearer 12345");
42+
}
43+
44+
@Test
45+
public void testRetryWithStatusCode() {
46+
AuthenticationToken token = new AuthenticationToken();
47+
token.setAccessToken("12345");
48+
49+
OAuthMiddleware middleware = new OAuthMiddleware(
50+
new OAuthHandler(new StaticTokenSupplier(token))
51+
);
52+
53+
final ApiHttpRequest request = new ApiHttpRequest();
54+
AtomicInteger count = new AtomicInteger();
55+
56+
final ApiHttpResponse<byte[]> apiHttpResponse = blockingWait(middleware.invoke(request, request1 -> {
57+
count.getAndIncrement();
58+
return CompletableFuture.completedFuture(new ApiHttpResponse<>(401, null, null));
59+
}), Duration.ofSeconds(1));
60+
Assertions.assertThat(apiHttpResponse.getStatusCode()).isEqualTo(401);
61+
Assertions.assertThat(count.get()).isEqualTo(2);
62+
}
63+
64+
@Test
65+
public void testRetryWithCoveredException() {
66+
AuthenticationToken token = new AuthenticationToken();
67+
token.setAccessToken("12345");
68+
69+
OAuthMiddleware middleware = new OAuthMiddleware(
70+
new OAuthHandler(new StaticTokenSupplier(token))
71+
);
72+
73+
final ApiHttpRequest request = new ApiHttpRequest();
74+
AtomicInteger count = new AtomicInteger();
75+
76+
Assertions.assertThatExceptionOfType(UnauthorizedException.class).isThrownBy(() -> {
77+
blockingWait(middleware.invoke(request, request1 -> {
78+
count.getAndIncrement();
79+
return CompletableFuture.supplyAsync(() -> {
80+
throw new CompletionException(new UnauthorizedException(401, null, null, null, null));
81+
});
82+
}), Duration.ofSeconds(1));
83+
}).matches(e -> e.getStatusCode() == 401);
84+
Assertions.assertThat(count.get()).isEqualTo(2);
85+
}
86+
87+
@Test
88+
public void testRetryWithUncoveredException() {
89+
AuthenticationToken token = new AuthenticationToken();
90+
token.setAccessToken("12345");
91+
92+
OAuthMiddleware middleware = new OAuthMiddleware(
93+
new OAuthHandler(new StaticTokenSupplier(token))
94+
);
95+
96+
final ApiHttpRequest request = new ApiHttpRequest();
97+
AtomicInteger count = new AtomicInteger();
98+
99+
Assertions.assertThatExceptionOfType(ApiHttpException.class).isThrownBy(() -> {
100+
blockingWait(middleware.invoke(request, request1 -> {
101+
count.getAndIncrement();
102+
return CompletableFuture.supplyAsync(() -> {
103+
throw new CompletionException(new ApiHttpException(499, null, null, null, null));
104+
});
105+
}), Duration.ofSeconds(1));
106+
}).matches(e -> e.getStatusCode() == 499);
107+
Assertions.assertThat(count.get()).isEqualTo(1);
108+
}
109+
}
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
package io.vrap.rmf.base.client.http;
2+
3+
import io.vrap.rmf.base.client.ApiHttpException;
4+
import io.vrap.rmf.base.client.ApiHttpRequest;
5+
import io.vrap.rmf.base.client.ApiHttpResponse;
6+
import org.junit.Test;
7+
import org.assertj.core.api.Assertions;
8+
9+
import java.time.Duration;
10+
import java.util.concurrent.CompletableFuture;
11+
import java.util.concurrent.CompletionException;
12+
import java.util.concurrent.atomic.AtomicInteger;
13+
14+
import static io.vrap.rmf.base.client.utils.ClientUtils.blockingWait;
15+
16+
public class RetryMiddlewareTest {
17+
18+
@Test
19+
public void testWithStatusCode() {
20+
RetryMiddleware middleware = new RetryMiddleware(1);
21+
22+
final ApiHttpRequest request = new ApiHttpRequest();
23+
AtomicInteger count = new AtomicInteger();
24+
25+
final ApiHttpResponse<byte[]> apiHttpResponse = blockingWait(middleware.invoke(request, request1 -> {
26+
count.getAndIncrement();
27+
return CompletableFuture.completedFuture(new ApiHttpResponse<>(503, null, null));
28+
}), Duration.ofSeconds(1));
29+
Assertions.assertThat(apiHttpResponse.getStatusCode()).isEqualTo(503);
30+
Assertions.assertThat(count.get()).isEqualTo(2);
31+
}
32+
33+
@Test
34+
public void testWithCoveredException() {
35+
RetryMiddleware middleware = new RetryMiddleware(1);
36+
37+
final ApiHttpRequest request = new ApiHttpRequest();
38+
AtomicInteger count = new AtomicInteger();
39+
40+
Assertions.assertThatExceptionOfType(ApiHttpException.class).isThrownBy(() -> {
41+
blockingWait(middleware.invoke(request, request1 -> {
42+
count.getAndIncrement();
43+
return CompletableFuture.supplyAsync(() -> {
44+
throw new CompletionException(new ApiHttpException(503, null, null));
45+
});
46+
}), Duration.ofSeconds(1));
47+
}).matches(e -> e.getStatusCode() == 503);
48+
Assertions.assertThat(count.get()).isEqualTo(2);
49+
}
50+
51+
@Test
52+
public void testUncoveredException() {
53+
RetryMiddleware middleware = new RetryMiddleware(1);
54+
55+
final ApiHttpRequest request = new ApiHttpRequest();
56+
AtomicInteger count = new AtomicInteger();
57+
58+
Assertions.assertThatExceptionOfType(ApiHttpException.class).isThrownBy(() -> {
59+
blockingWait(middleware.invoke(request, request1 -> {
60+
count.getAndIncrement();
61+
return CompletableFuture.supplyAsync(() -> {
62+
throw new CompletionException(new ApiHttpException(504, null, null));
63+
});
64+
}), Duration.ofSeconds(1));
65+
}).matches(e -> e.getStatusCode() == 504);
66+
Assertions.assertThat(count.get()).isEqualTo(1);
67+
}
68+
69+
@Test
70+
public void testRetrySuccess() {
71+
RetryMiddleware middleware = new RetryMiddleware(1);
72+
73+
final ApiHttpRequest request = new ApiHttpRequest();
74+
AtomicInteger count = new AtomicInteger();
75+
76+
final ApiHttpResponse<byte[]> apiHttpResponse = blockingWait(middleware.invoke(request, request1 -> {
77+
count.getAndIncrement();
78+
return CompletableFuture.completedFuture(new ApiHttpResponse<>(200, null, null));
79+
}), Duration.ofSeconds(1));
80+
Assertions.assertThat(apiHttpResponse.getStatusCode()).isEqualTo(200);
81+
Assertions.assertThat(count.get()).isEqualTo(1);
82+
}
83+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<configuration debug="false">
2+
<contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
3+
<resetJUL>true</resetJUL>
4+
</contextListener>
5+
6+
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
7+
<encoder>
8+
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
9+
</encoder>
10+
</appender>
11+
12+
<logger name="commercetools" level="DEBUG"/>
13+
14+
<root level="DEBUG">
15+
<appender-ref ref="STDOUT" />
16+
</root>
17+
</configuration>

0 commit comments

Comments
 (0)