diff --git a/.github/check-sandbox-credentials.sh b/.github/check-sandbox-credentials.sh
new file mode 100644
index 0000000..c80a051
--- /dev/null
+++ b/.github/check-sandbox-credentials.sh
@@ -0,0 +1,15 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+if [[ "${GITHUB_EVENT_NAME:-}" != "push" || "${GITHUB_REF:-}" != "refs/heads/main" ]]; then
+ exit 0
+fi
+
+[[ "${CLIENT_ID:-}" =~ [^[:space:]] ]] || { echo "::error::Missing sandbox credential: CLIENT_ID"; exit 1; }
+[[ "${KID:-}" =~ [^[:space:]] ]] || { echo "::error::Missing sandbox credential: KID"; exit 1; }
+[[ "${PRIVATE_KEY:-}" =~ [^[:space:]] ]] || { echo "::error::Missing sandbox credential: PRIVATE_KEY"; exit 1; }
+[[ "${TOKEN_ENDPOINT:-}" =~ [^[:space:]] ]] || { echo "::error::Missing sandbox credential: TOKEN_ENDPOINT"; exit 1; }
+[[ "${ISSUER:-}" =~ [^[:space:]] ]] || { echo "::error::Missing sandbox credential: ISSUER"; exit 1; }
+[[ "${API_BASE_URL:-}" =~ [^[:space:]] ]] || { echo "::error::Missing sandbox credential: API_BASE_URL"; exit 1; }
+[[ "${READ_SCOPES:-}" =~ [^[:space:]] ]] || { echo "::error::Missing sandbox credential: READ_SCOPES"; exit 1; }
+[[ "${WRITE_SCOPES:-}" =~ [^[:space:]] ]] || { echo "::error::Missing sandbox credential: WRITE_SCOPES"; exit 1; }
diff --git a/.github/workflows/ci-apache-httpclient.yml b/.github/workflows/ci-apache-httpclient.yml
index 03cee66..186ca0e 100644
--- a/.github/workflows/ci-apache-httpclient.yml
+++ b/.github/workflows/ci-apache-httpclient.yml
@@ -10,6 +10,7 @@ on:
jobs:
build:
+ environment: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' && 'sandbox' || 'ci' }}
runs-on: ubuntu-latest
strategy:
matrix:
@@ -41,7 +42,7 @@ jobs:
${{ runner.os }}-maven-
- name: Build and run tests with Apache HttpClient ${{ matrix.httpclient-version }}
- run: mvn -B test "-Dtest=com.mastercard.developer.oauth2.http.apache.OAuth2HttpClientTest" "-Dsurefire.failIfNoSpecifiedTests=false" "-Dhttpclient.version=${{ matrix.httpclient-version }}" "-Dmaven.test.dependency.excludes=${{ env.OKHTTP }},${{ env.FEIGN }},${{ env.SPRING_WEB }},${{ env.SPRING_WEBFLUX }}"
+ run: bash .github/check-sandbox-credentials.sh && mvn -B test "-Dtest=com.mastercard.developer.oauth2.http.apache.OAuth2HttpClientTest" "-Dsurefire.failIfNoSpecifiedTests=false" "-Dhttpclient.version=${{ matrix.httpclient-version }}" "-Dmaven.test.dependency.excludes=${{ env.OKHTTP }},${{ env.FEIGN }},${{ env.SPRING_WEB }},${{ env.SPRING_WEBFLUX }}"
env:
CLIENT_ID: ${{ secrets.CLIENT_ID }}
KID: ${{ secrets.KID }}
diff --git a/.github/workflows/ci-feign.yml b/.github/workflows/ci-feign.yml
index 70d1de8..7313b44 100644
--- a/.github/workflows/ci-feign.yml
+++ b/.github/workflows/ci-feign.yml
@@ -10,6 +10,7 @@ on:
jobs:
build:
+ environment: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' && 'sandbox' || 'ci' }}
runs-on: ubuntu-latest
strategy:
matrix:
@@ -41,7 +42,7 @@ jobs:
${{ runner.os }}-maven-
- name: Build and run tests with Feign ${{ matrix.feign-version }}
- run: mvn -B test "-Dtest=com.mastercard.developer.oauth2.http.feign.OAuth2ClientTest" "-Dsurefire.failIfNoSpecifiedTests=false" "-Dfeign.version=${{ matrix.feign-version }}" "-Dmaven.test.dependency.excludes=${{ env.OKHTTP }},${{ env.SPRING_WEB }},${{ env.SPRING_WEBFLUX }}"
+ run: bash .github/check-sandbox-credentials.sh && mvn -B test "-Dtest=com.mastercard.developer.oauth2.http.feign.OAuth2ClientTest" "-Dsurefire.failIfNoSpecifiedTests=false" "-Dfeign.version=${{ matrix.feign-version }}" "-Dmaven.test.dependency.excludes=${{ env.OKHTTP }},${{ env.SPRING_WEB }},${{ env.SPRING_WEBFLUX }}"
env:
CLIENT_ID: ${{ secrets.CLIENT_ID }}
KID: ${{ secrets.KID }}
diff --git a/.github/workflows/ci-java-http-client.yml b/.github/workflows/ci-java-http-client.yml
index e15742e..6f8df8c 100644
--- a/.github/workflows/ci-java-http-client.yml
+++ b/.github/workflows/ci-java-http-client.yml
@@ -10,6 +10,7 @@ on:
jobs:
build:
+ environment: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' && 'sandbox' || 'ci' }}
runs-on: ubuntu-latest
strategy:
matrix:
@@ -40,7 +41,7 @@ jobs:
${{ runner.os }}-maven-
- name: Build and run tests with Java ${{ matrix.java-version }}
- run: mvn -B test "-Dtest=com.mastercard.developer.oauth2.http.java.OAuth2HttpClientTest" "-Dsurefire.failIfNoSpecifiedTests=false" "-Dmaven.test.dependency.excludes=${{ env.OKHTTP }},${{ env.FEIGN }},${{ env.SPRING_WEB }},${{ env.SPRING_WEBFLUX }}"
+ run: bash .github/check-sandbox-credentials.sh && mvn -B test "-Dtest=com.mastercard.developer.oauth2.http.java.OAuth2HttpClientTest" "-Dsurefire.failIfNoSpecifiedTests=false" "-Dmaven.test.dependency.excludes=${{ env.OKHTTP }},${{ env.FEIGN }},${{ env.SPRING_WEB }},${{ env.SPRING_WEBFLUX }}"
env:
CLIENT_ID: ${{ secrets.CLIENT_ID }}
KID: ${{ secrets.KID }}
diff --git a/.github/workflows/ci-java-lts.yml b/.github/workflows/ci-java-lts.yml
index e4da870..cdfe627 100644
--- a/.github/workflows/ci-java-lts.yml
+++ b/.github/workflows/ci-java-lts.yml
@@ -10,6 +10,7 @@ on:
jobs:
build:
+ environment: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' && 'sandbox' || 'ci' }}
runs-on: ubuntu-latest
strategy:
matrix:
@@ -34,7 +35,7 @@ jobs:
${{ runner.os }}-maven-
- name: Build and run tests
- run: mvn -B test
+ run: bash .github/check-sandbox-credentials.sh && mvn -B test
env:
CLIENT_ID: ${{ secrets.CLIENT_ID }}
KID: ${{ secrets.KID }}
diff --git a/.github/workflows/ci-okhttp.yml b/.github/workflows/ci-okhttp.yml
index e9bbf03..10b0a63 100644
--- a/.github/workflows/ci-okhttp.yml
+++ b/.github/workflows/ci-okhttp.yml
@@ -10,6 +10,7 @@ on:
jobs:
build:
+ environment: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' && 'sandbox' || 'ci' }}
runs-on: ubuntu-latest
strategy:
matrix:
@@ -41,7 +42,7 @@ jobs:
${{ runner.os }}-maven-
- name: Build and run tests with OkHttp ${{ matrix.okhttp-version }}
- run: mvn -B test "-Dtest=com.mastercard.developer.oauth2.http.okhttp3.OAuth2InterceptorTest" "-Dsurefire.failIfNoSpecifiedTests=false" "-Dokhttp.version=${{ matrix.okhttp-version }}" "-Dmaven.test.dependency.excludes=${{ env.FEIGN }},${{ env.SPRING_WEB }},${{ env.SPRING_WEBFLUX }}"
+ run: bash .github/check-sandbox-credentials.sh && mvn -B test "-Dtest=com.mastercard.developer.oauth2.http.okhttp3.OAuth2InterceptorTest" "-Dsurefire.failIfNoSpecifiedTests=false" "-Dokhttp.version=${{ matrix.okhttp-version }}" "-Dmaven.test.dependency.excludes=${{ env.FEIGN }},${{ env.SPRING_WEB }},${{ env.SPRING_WEBFLUX }}"
env:
CLIENT_ID: ${{ secrets.CLIENT_ID }}
KID: ${{ secrets.KID }}
diff --git a/.github/workflows/ci-spring-restclient.yml b/.github/workflows/ci-spring-restclient.yml
index 0dfc785..7f51d05 100644
--- a/.github/workflows/ci-spring-restclient.yml
+++ b/.github/workflows/ci-spring-restclient.yml
@@ -10,6 +10,7 @@ on:
jobs:
build:
+ environment: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' && 'sandbox' || 'ci' }}
runs-on: ubuntu-latest
strategy:
matrix:
@@ -41,7 +42,7 @@ jobs:
${{ runner.os }}-maven-
- name: Build and run tests with spring-web ${{ matrix.spring-web-version }}
- run: mvn -B test "-Dtest=com.mastercard.developer.oauth2.http.spring.restclient.OAuth2ClientHttpRequestInterceptorTest" "-Dsurefire.failIfNoSpecifiedTests=false" "-Dspring-web.version=${{ matrix.spring-web-version }}" "-Dmaven.test.dependency.excludes=${{ env.OKHTTP }},${{ env.FEIGN }},${{ env.SPRING_WEBFLUX }}"
+ run: bash .github/check-sandbox-credentials.sh && mvn -B test "-Dtest=com.mastercard.developer.oauth2.http.spring.restclient.OAuth2ClientHttpRequestInterceptorTest" "-Dsurefire.failIfNoSpecifiedTests=false" "-Dspring-web.version=${{ matrix.spring-web-version }}" "-Dmaven.test.dependency.excludes=${{ env.OKHTTP }},${{ env.FEIGN }},${{ env.SPRING_WEBFLUX }}"
env:
CLIENT_ID: ${{ secrets.CLIENT_ID }}
KID: ${{ secrets.KID }}
diff --git a/.github/workflows/ci-spring-webclient.yml b/.github/workflows/ci-spring-webclient.yml
index 3108771..06f7e8e 100644
--- a/.github/workflows/ci-spring-webclient.yml
+++ b/.github/workflows/ci-spring-webclient.yml
@@ -10,6 +10,7 @@ on:
jobs:
build:
+ environment: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' && 'sandbox' || 'ci' }}
runs-on: ubuntu-latest
strategy:
matrix:
@@ -51,7 +52,7 @@ jobs:
fi
- name: Build and run tests with spring-webflux ${{ matrix.spring-webflux-version }}
- run: mvn -B test "-Dtest=com.mastercard.developer.oauth2.http.spring.webclient.OAuth2FilterTest" "-Dsurefire.failIfNoSpecifiedTests=false" "-Dspring-webflux.version=${{ matrix.spring-webflux-version }}" "-Dspring-web.version=${{ matrix.spring-webflux-version }}" "-Duse-jakarta-ee=${{ steps.set-jakarta.outputs.use-jakarta-ee }}" "-Dmaven.test.dependency.excludes=${{ env.OKHTTP }},${{ env.FEIGN }}"
+ run: bash .github/check-sandbox-credentials.sh && mvn -B test "-Dtest=com.mastercard.developer.oauth2.http.spring.webclient.OAuth2FilterTest" "-Dsurefire.failIfNoSpecifiedTests=false" "-Dspring-webflux.version=${{ matrix.spring-webflux-version }}" "-Dspring-web.version=${{ matrix.spring-webflux-version }}" "-Duse-jakarta-ee=${{ steps.set-jakarta.outputs.use-jakarta-ee }}" "-Dmaven.test.dependency.excludes=${{ env.OKHTTP }},${{ env.FEIGN }}"
env:
CLIENT_ID: ${{ secrets.CLIENT_ID }}
KID: ${{ secrets.KID }}
diff --git a/README.md b/README.md
index 2800708..787bf3d 100644
--- a/README.md
+++ b/README.md
@@ -293,12 +293,10 @@ Running integration tests against a real Mastercard API requires API details and
#### GitHub Actions
-This repository is configured with the following secrets GitHub Actions automatically uses when running [workflows](https://github.com/mastercard/oauth2-client-java/actions):
+- Branches and pull requests run Java tests against fake servers, without sandbox credentials.
+- `main` also runs live tests. If a required credential is missing, the job fails.
-
-
-
-
+**Maintainers:** Keep sandbox credentials only in a `main`-restricted environment, not in repository or organization secrets accessible to this repo.
### Fake Servers
diff --git a/library/src/main/java/com/mastercard/developer/oauth2/core/OAuth2Handler.java b/library/src/main/java/com/mastercard/developer/oauth2/core/OAuth2Handler.java
index 905f571..b111329 100644
--- a/library/src/main/java/com/mastercard/developer/oauth2/core/OAuth2Handler.java
+++ b/library/src/main/java/com/mastercard/developer/oauth2/core/OAuth2Handler.java
@@ -112,7 +112,7 @@ private AccessTokenResult retrieveAccessToken(
Optional existingToken = tokenStore.get(filter);
if (existingToken.isPresent()) {
AccessToken accessToken = existingToken.get();
- logger.debug("Valid access token found: {}", accessToken);
+ logger.debug("Valid access token found (expires at {}, {} scopes)", accessToken.expiresAt(), accessToken.scopes().size());
return AccessTokenResult.from(accessToken);
}
@@ -140,7 +140,7 @@ private AccessTokenResult retrieveAccessToken(
adapter.close(tokenResponse);
AccessTokenResponse accessTokenResponse = parseAccessTokenJson(body);
var accessToken = new AccessToken(config.getClientId(), accessTokenResponse.scopes(), accessTokenResponse.expiry(), jkt, accessTokenResponse.tokenValue());
- logger.debug("Adding access token to store: {}", accessToken);
+ logger.debug("Adding access token to store (expires at {}, {} scopes)", accessToken.expiresAt(), accessToken.scopes().size());
tokenStore.put(accessToken);
return AccessTokenResult.from(accessToken);
}
@@ -153,13 +153,13 @@ private Response makeAccessTokenRequest(Request originalRequ
logger.debug("Creating token request DPoP proof (nonce: {})", logNonce(nonce));
}
String dpopProof = createTokenRequestDPoP(config, dpopKeyId, nonce);
- logger.debug("Token request DPoP proof: {}", dpopProof);
+ logger.debug("Token request DPoP proof: ");
var scope = String.join(" ", scopes);
logger.debug("Creating client assertion");
String clientAssertion = createClientAssertion(config);
- logger.debug("Client assertion: {}", clientAssertion);
+ logger.debug("Client assertion: ");
String formBody = createAccessTokenRequestBody(clientId, scope, clientAssertion);
- logger.debug("Sending access token request with body: {}", formBody);
+ logger.debug("Sending access token request with body: ");
var headers = new HttpHeaders()
.add(USER_AGENT, config.getUserAgent())
.add(CONTENT_TYPE, "application/x-www-form-urlencoded")
@@ -201,7 +201,7 @@ private Response makeResourceRequest(Request request, HttpAd
logger.debug("Creating resource request DPoP proof (nonce: {})", logNonce(nonce));
}
String dpopProof = createResourceRequestDPoP(config, dpopKeyId, method, resourceUrl, accessToken, nonce);
- logger.debug("Resource request DPoP proof: {}", dpopProof);
+ logger.debug("Resource request DPoP proof: ");
var headers = new HttpHeaders()
.add(USER_AGENT, config.getUserAgent())
.add(AUTHORIZATION, "DPoP " + accessToken)
@@ -450,7 +450,7 @@ private static boolean isSuccess(int statusCode) {
}
private static String logBody(String body) {
- return body == null || body.isEmpty() ? "" : body;
+ return body == null || body.isEmpty() ? "" : "";
}
private static String logNonce(String nonce) {
diff --git a/library/src/test/java/com/mastercard/developer/oauth2/core/OAuth2HandlerEndToEndTest.java b/library/src/test/java/com/mastercard/developer/oauth2/core/OAuth2HandlerEndToEndTest.java
index e449301..4a0d725 100644
--- a/library/src/test/java/com/mastercard/developer/oauth2/core/OAuth2HandlerEndToEndTest.java
+++ b/library/src/test/java/com/mastercard/developer/oauth2/core/OAuth2HandlerEndToEndTest.java
@@ -31,16 +31,6 @@ void setUp() {
httpClient = HttpClient.newBuilder().build();
}
- @BeforeAll
- static void beforeAll() {
- System.setProperty("jdk.httpclient.HttpClient.log", "all");
- }
-
- @AfterAll
- static void afterAll() {
- System.clearProperty("jdk.httpclient.HttpClient.log");
- }
-
@ParameterizedTest
@MethodSource("serverAndKeyProvider")
void callSequence_ShouldSucceed(Supplier configSupplier) throws Exception {
diff --git a/library/src/test/java/com/mastercard/developer/oauth2/core/OAuth2HandlerExecuteTest.java b/library/src/test/java/com/mastercard/developer/oauth2/core/OAuth2HandlerExecuteTest.java
index adf897d..0c76eb1 100644
--- a/library/src/test/java/com/mastercard/developer/oauth2/core/OAuth2HandlerExecuteTest.java
+++ b/library/src/test/java/com/mastercard/developer/oauth2/core/OAuth2HandlerExecuteTest.java
@@ -150,7 +150,7 @@ void execute_ShouldReturnErrorResponse_WhenAuthorizationServerError() throws Exc
verify(adapter).sendAccessTokenRequest(eq(requestObject), any(URL.class), anyString(), any(HttpHeaders.class));
verify(adapter, never()).sendResourceRequest(any(), any());
assertEquals(
- "Access token request failed (HTTP 500), body: {\"error\":\"internal_error\"}",
+ "Access token request failed (HTTP 500), body: ",
listAppender.list
.stream()
.filter(e -> e.getLevel() == Level.ERROR)
@@ -177,7 +177,7 @@ void execute_ShouldReturnErrorResponse_WhenResourceServerError() throws Exceptio
verify(adapter, times(2)).sendAccessTokenRequest(eq(requestObject), any(URL.class), anyString(), any(HttpHeaders.class));
verify(adapter).sendResourceRequest(eq(requestObject), any(HttpHeaders.class));
assertEquals(
- "API call failed (HTTP 500), body: {\"error\":\"internal_error\"}",
+ "API call failed (HTTP 500), body: ",
listAppender.list
.stream()
.filter(e -> e.getLevel() == Level.ERROR)
@@ -196,12 +196,6 @@ void execute_ShouldExecuteEntireFlow() throws Exception {
// THEN
assertEquals(responseObject, response);
- assertNotNull(
- listAppender.list
- .stream()
- .filter(e -> e.getLevel() == Level.DEBUG && "API call successful (HTTP 201), body: {\"success\":\"true\"}".equals(e.getFormattedMessage()))
- .findFirst()
- );
// Verify authorization server was called, request headers and DPoP nonces
var tokenRequestBodyCaptor = ArgumentCaptor.forClass(String.class);
@@ -225,6 +219,11 @@ void execute_ShouldExecuteEntireFlow() throws Exception {
var uniqueAssertions = new HashSet<>(clientAssertions);
assertEquals(clientAssertions.size(), uniqueAssertions.size());
+ String loggedMessages = listAppender.list.stream().map(ILoggingEvent::getFormattedMessage).collect(java.util.stream.Collectors.joining("\n"));
+ assertFalse(loggedMessages.contains(sampleAccessToken));
+ assertFalse(loggedMessages.contains(tokenRequestHeaders.get(0).get(DPOP.value()).get()));
+ assertFalse(loggedMessages.contains(clientAssertions.get(0)));
+
// Verify resource server was called, request headers and DPoP nonces
var resourceRequestHeadersCaptor = ArgumentCaptor.forClass(HttpHeaders.class);
verify(adapter, times(2)).sendResourceRequest(eq(requestObject), resourceRequestHeadersCaptor.capture());
diff --git a/library/src/test/java/com/mastercard/developer/oauth2/http/apache/OAuth2HttpClientTest.java b/library/src/test/java/com/mastercard/developer/oauth2/http/apache/OAuth2HttpClientTest.java
index a70ce67..a79af5e 100644
--- a/library/src/test/java/com/mastercard/developer/oauth2/http/apache/OAuth2HttpClientTest.java
+++ b/library/src/test/java/com/mastercard/developer/oauth2/http/apache/OAuth2HttpClientTest.java
@@ -1,20 +1,21 @@
package com.mastercard.developer.oauth2.http.apache;
import static com.mastercard.developer.oauth2.http.StandardHttpHeader.*;
+import static com.mastercard.developer.oauth2.test.fixtures.LiveResourceRetry.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import static org.skyscreamer.jsonassert.JSONAssert.*;
-import com.mastercard.developer.oauth2.test.fixtures.BaseClientTest;
+import com.mastercard.developer.oauth2.test.fixtures.BaseHttpClientTest;
import com.mastercard.developer.oauth2.test.fixtures.TestConfig;
import com.mastercard.developer.test.openapi_generator.fake.apache.api.ResourcesApi;
import com.mastercard.developer.test.openapi_generator.fake.apache.model.Resource;
+import com.mastercard.developer.test.openapi_generator.petstore.apache.ApiException;
import com.mastercard.developer.test.openapi_generator.petstore.apache.api.PetsApi;
import com.mastercard.developer.test.openapi_generator.petstore.apache.model.Dog;
import com.mastercard.developer.test.openapi_generator.petstore.apache.model.NewDog;
import com.mastercard.developer.test.openapi_generator.petstore.apache.model.PetStatus;
-import java.util.function.Supplier;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.core5.http.ClassicHttpRequest;
@@ -23,20 +24,16 @@
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;
import org.junit.jupiter.api.Test;
-import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.MethodSource;
-class OAuth2HttpClientTest extends BaseClientTest {
+class OAuth2HttpClientTest extends BaseHttpClientTest {
private static CloseableHttpClient httpClient(TestConfig testConfig) {
return new OAuth2HttpClient(testConfig.getOAuth2Config());
}
- @ParameterizedTest
- @MethodSource("testConfigProvider")
- void client_ShouldSucceed(Supplier configSupplier) throws Exception {
+ @Override
+ protected void clientShouldSucceed(TestConfig testConfig, boolean retryOn404) throws Exception {
// GIVEN
- TestConfig testConfig = configSupplier.get();
CloseableHttpClient httpClient = httpClient(testConfig);
try (httpClient) {
// WHEN: create resource
@@ -52,22 +49,31 @@ void client_ShouldSucceed(Supplier configSupplier) throws Exception
var resourceId = readResourceId(resource);
// WHEN: fetch resource
- var getRequest = createGetRequest(testConfig, resourceId);
- resource = httpClient.execute(getRequest, response -> {
- assertEquals(200, response.getCode());
- var entity = response.getEntity();
- return entity != null ? EntityUtils.toString(entity) : null;
+ resource = onNotFound(retryOn404, "GET", () -> {
+ var getRequest = createGetRequest(testConfig, resourceId);
+ return httpClient.execute(getRequest, response -> {
+ if (retryOn404) {
+ failIfNotFound(response.getCode());
+ }
+ assertEquals(200, response.getCode());
+ var entity = response.getEntity();
+ return entity != null ? EntityUtils.toString(entity) : null;
+ });
});
// THEN
assertNotNull(resource);
assertTrue(resource.contains("id")); // Resource fetched
// WHEN: delete resource
- var deleteRequest = createDeleteRequest(testConfig, resourceId);
- httpClient.execute(deleteRequest, response -> {
- // THEN
- assertEquals(204, response.getCode()); // Resource deleted
- return response;
+ onNotFound(retryOn404, "DELETE", () -> {
+ var deleteRequest = createDeleteRequest(testConfig, resourceId);
+ return httpClient.execute(deleteRequest, response -> {
+ if (retryOn404) {
+ failIfNotFound(response.getCode());
+ }
+ assertEquals(204, response.getCode()); // Resource deleted
+ return null;
+ });
});
}
}
@@ -119,13 +125,21 @@ void openapiGeneratorClient_ShouldSucceed_WhenMastercardApi() throws Exception {
assertNotNull(dog.getId());
// WHEN: fetch resource
- dog = api.getDog(dog.getId());
+ var dogId = dog.getId();
+ dog = onNotFound("GET", () -> api.getDog(dogId), error -> error instanceof ApiException ex && ex.getCode() == 404);
// THEN
assertNotNull(dog);
assertNotNull(dog.getId());
// WHEN / THEN: delete resource
- api.deleteDog(dog.getId());
+ onNotFound(
+ "DELETE",
+ () -> {
+ api.deleteDog(dogId);
+ return null;
+ },
+ error -> error instanceof ApiException ex && ex.getCode() == 404
+ );
}
@Test
diff --git a/library/src/test/java/com/mastercard/developer/oauth2/http/feign/OAuth2ClientTest.java b/library/src/test/java/com/mastercard/developer/oauth2/http/feign/OAuth2ClientTest.java
index 3188c98..3017bd4 100644
--- a/library/src/test/java/com/mastercard/developer/oauth2/http/feign/OAuth2ClientTest.java
+++ b/library/src/test/java/com/mastercard/developer/oauth2/http/feign/OAuth2ClientTest.java
@@ -1,10 +1,11 @@
package com.mastercard.developer.oauth2.http.feign;
import static com.mastercard.developer.oauth2.http.StandardHttpHeader.*;
+import static com.mastercard.developer.oauth2.test.fixtures.LiveResourceRetry.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
-import com.mastercard.developer.oauth2.test.fixtures.BaseClientTest;
+import com.mastercard.developer.oauth2.test.fixtures.BaseHttpClientTest;
import com.mastercard.developer.oauth2.test.fixtures.TestConfig;
import com.mastercard.developer.test.openapi_generator.fake.feign.api.ResourcesApi;
import com.mastercard.developer.test.openapi_generator.fake.feign.model.Resource;
@@ -16,19 +17,14 @@
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;
-import java.util.function.Supplier;
import org.junit.jupiter.api.Test;
-import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.MethodSource;
@SuppressWarnings("OptionalGetWithoutIsPresent") // Simpler assertions
-class OAuth2ClientTest extends BaseClientTest {
+class OAuth2ClientTest extends BaseHttpClientTest {
- @ParameterizedTest
- @MethodSource("testConfigProvider")
- void client_ShouldSucceed(Supplier configSupplier) throws Exception {
+ @Override
+ protected void clientShouldSucceed(TestConfig testConfig, boolean retryOn404) throws Exception {
// GIVEN
- TestConfig testConfig = configSupplier.get();
Client feignClient = new OAuth2Client(testConfig.getOAuth2Config());
// WHEN: create resource
@@ -44,21 +40,30 @@ void client_ShouldSucceed(Supplier configSupplier) throws Exception
}
// WHEN: fetch resource
- var getRequest = createGetRequest(testConfig, resourceId);
- try (Response getResponse = feignClient.execute(getRequest, new Request.Options())) {
- // THEN
- assertEquals(200, getResponse.status());
- assertNotNull(getResponse.body());
- String resource = Util.toString(getResponse.body().asReader(StandardCharsets.UTF_8));
- assertTrue(resource.contains("id")); // Resource fetched
- }
+ String resource = onNotFound(retryOn404, "GET", () -> {
+ var getRequest = createGetRequest(testConfig, resourceId);
+ try (Response getResponse = feignClient.execute(getRequest, new Request.Options())) {
+ if (retryOn404) {
+ failIfNotFound(getResponse.status());
+ }
+ assertEquals(200, getResponse.status());
+ assertNotNull(getResponse.body());
+ return Util.toString(getResponse.body().asReader(StandardCharsets.UTF_8));
+ }
+ });
+ assertTrue(resource.contains("id")); // Resource fetched
// WHEN: delete resource
- var deleteRequest = createDeleteRequest(testConfig, resourceId);
- try (Response deletetResponse = feignClient.execute(deleteRequest, new Request.Options())) {
- // THEN
- assertEquals(204, deletetResponse.status()); // Resource deleted
- }
+ onNotFound(retryOn404, "DELETE", () -> {
+ var deleteRequest = createDeleteRequest(testConfig, resourceId);
+ try (Response deleteResponse = feignClient.execute(deleteRequest, new Request.Options())) {
+ if (retryOn404) {
+ failIfNotFound(deleteResponse.status());
+ }
+ assertEquals(204, deleteResponse.status()); // Resource deleted
+ return null;
+ }
+ });
}
@Test
@@ -88,7 +93,7 @@ void openapiGeneratorClient_ShouldSucceed_WhenFakeServers() {
}
@Test
- void openapiGeneratorClient_ShouldSucceed_WhenMastercardApi() {
+ void openapiGeneratorClient_ShouldSucceed_WhenMastercardApi() throws Exception {
// GIVEN
TestConfig testConfig = getMastercardConfig();
Client feignClient = new OAuth2Client(testConfig.getOAuth2Config());
@@ -110,13 +115,21 @@ void openapiGeneratorClient_ShouldSucceed_WhenMastercardApi() {
assertNotNull(dog.getId());
// WHEN: fetch resource
- dog = api.getDog(dog.getId());
+ var dogId = dog.getId();
+ dog = onNotFound("GET", () -> api.getDog(dogId), error -> error instanceof FeignException ex && ex.status() == 404);
// THEN
assertNotNull(dog);
assertNotNull(dog.getId());
// WHEN / THEN: delete resource
- api.deleteDog(dog.getId());
+ onNotFound(
+ "DELETE",
+ () -> {
+ api.deleteDog(dogId);
+ return null;
+ },
+ error -> error instanceof FeignException ex && ex.status() == 404
+ );
}
@Test
diff --git a/library/src/test/java/com/mastercard/developer/oauth2/http/java/OAuth2HttpClientTest.java b/library/src/test/java/com/mastercard/developer/oauth2/http/java/OAuth2HttpClientTest.java
index ec1b4c4..f584f97 100644
--- a/library/src/test/java/com/mastercard/developer/oauth2/http/java/OAuth2HttpClientTest.java
+++ b/library/src/test/java/com/mastercard/developer/oauth2/http/java/OAuth2HttpClientTest.java
@@ -1,13 +1,15 @@
package com.mastercard.developer.oauth2.http.java;
import static com.mastercard.developer.oauth2.http.StandardHttpHeader.*;
+import static com.mastercard.developer.oauth2.test.fixtures.LiveResourceRetry.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.skyscreamer.jsonassert.JSONAssert.*;
-import com.mastercard.developer.oauth2.test.fixtures.BaseClientTest;
+import com.mastercard.developer.oauth2.test.fixtures.BaseHttpClientTest;
import com.mastercard.developer.oauth2.test.fixtures.TestConfig;
import com.mastercard.developer.test.openapi_generator.fake.java.api.ResourcesApi;
import com.mastercard.developer.test.openapi_generator.fake.java.model.Resource;
+import com.mastercard.developer.test.openapi_generator.petstore.java.ApiException;
import com.mastercard.developer.test.openapi_generator.petstore.java.api.PetsApi;
import com.mastercard.developer.test.openapi_generator.petstore.java.model.Dog;
import com.mastercard.developer.test.openapi_generator.petstore.java.model.NewDog;
@@ -20,38 +22,21 @@
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
-import org.junit.jupiter.api.AfterAll;
-import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
-import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.MethodSource;
@SuppressWarnings("resource") // On JDK 11–20, java.net.http.HttpClient does not implement AutoCloseable
-class OAuth2HttpClientTest extends BaseClientTest {
-
- @BeforeAll
- static void beforeAll() {
- System.setProperty("jdk.httpclient.HttpClient.log", "all");
- }
-
- @AfterAll
- static void afterAll() {
- System.clearProperty("jdk.httpclient.HttpClient.log");
- }
+class OAuth2HttpClientTest extends BaseHttpClientTest {
private static HttpClient.Builder httpClient(TestConfig testConfig) {
HttpClient.Builder baseBuilder = HttpClient.newBuilder();
return OAuth2HttpClient.newBuilder(testConfig.getOAuth2Config(), baseBuilder);
}
- @ParameterizedTest
- @MethodSource("testConfigProvider")
- void client_ShouldSucceed(Supplier configSupplier) throws Exception {
+ @Override
+ protected void clientShouldSucceed(TestConfig testConfig, boolean retryOn404) throws Exception {
// GIVEN
- TestConfig testConfig = configSupplier.get();
HttpClient client = httpClient(testConfig).build();
// WHEN: create resource
@@ -65,8 +50,13 @@ void client_ShouldSucceed(Supplier configSupplier) throws Exception
String resourceId = readResourceId(resource);
// WHEN: fetch resource
- HttpRequest getRequest = createGetRequest(testConfig, resourceId);
- HttpResponse getResponse = client.send(getRequest, HttpResponse.BodyHandlers.ofString());
+ HttpResponse getResponse = onNotFound(retryOn404, "GET", () -> {
+ HttpResponse response = client.send(createGetRequest(testConfig, resourceId), HttpResponse.BodyHandlers.ofString());
+ if (retryOn404) {
+ failIfNotFound(response.statusCode());
+ }
+ return response;
+ });
// THEN
assertEquals(200, getResponse.statusCode());
assertNotNull(getResponse.body());
@@ -74,8 +64,13 @@ void client_ShouldSucceed(Supplier configSupplier) throws Exception
assertTrue(resource.contains("id")); // Resource fetched
// WHEN: delete resource
- HttpRequest deleteRequest = createDeleteRequest(testConfig, resourceId);
- HttpResponse deleteResponse = client.send(deleteRequest, HttpResponse.BodyHandlers.discarding());
+ HttpResponse deleteResponse = onNotFound(retryOn404, "DELETE", () -> {
+ HttpResponse response = client.send(createDeleteRequest(testConfig, resourceId), HttpResponse.BodyHandlers.discarding());
+ if (retryOn404) {
+ failIfNotFound(response.statusCode());
+ }
+ return response;
+ });
// THEN
assertEquals(204, deleteResponse.statusCode()); // Resource deleted
}
@@ -128,13 +123,21 @@ void openapiGeneratorClient_ShouldSucceed_WhenMastercardApi() throws Exception {
assertNotNull(dog.getId());
// WHEN: fetch resource
- dog = api.getDog(dog.getId());
+ var dogId = dog.getId();
+ dog = onNotFound("GET", () -> api.getDog(dogId), error -> error instanceof ApiException ex && ex.getCode() == 404);
// THEN
assertNotNull(dog);
assertNotNull(dog.getId());
// WHEN / THEN: delete resource
- api.deleteDog(dog.getId());
+ onNotFound(
+ "DELETE",
+ () -> {
+ api.deleteDog(dogId);
+ return null;
+ },
+ error -> error instanceof ApiException ex && ex.getCode() == 404
+ );
}
}
diff --git a/library/src/test/java/com/mastercard/developer/oauth2/http/okhttp3/OAuth2InterceptorTest.java b/library/src/test/java/com/mastercard/developer/oauth2/http/okhttp3/OAuth2InterceptorTest.java
index 499c0af..5ee2829 100644
--- a/library/src/test/java/com/mastercard/developer/oauth2/http/okhttp3/OAuth2InterceptorTest.java
+++ b/library/src/test/java/com/mastercard/developer/oauth2/http/okhttp3/OAuth2InterceptorTest.java
@@ -1,38 +1,32 @@
package com.mastercard.developer.oauth2.http.okhttp3;
import static com.mastercard.developer.oauth2.http.StandardHttpHeader.*;
+import static com.mastercard.developer.oauth2.test.fixtures.LiveResourceRetry.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.skyscreamer.jsonassert.JSONAssert.*;
-import com.mastercard.developer.oauth2.test.fixtures.BaseClientTest;
+import com.mastercard.developer.oauth2.test.fixtures.BaseHttpClientTest;
import com.mastercard.developer.oauth2.test.fixtures.TestConfig;
import com.mastercard.developer.test.openapi_generator.fake.okhttp.api.ResourcesApi;
import com.mastercard.developer.test.openapi_generator.fake.okhttp.model.Resource;
+import com.mastercard.developer.test.openapi_generator.petstore.okhttp.ApiException;
import com.mastercard.developer.test.openapi_generator.petstore.okhttp.api.PetsApi;
import com.mastercard.developer.test.openapi_generator.petstore.okhttp.model.Dog;
import com.mastercard.developer.test.openapi_generator.petstore.okhttp.model.NewDog;
import com.mastercard.developer.test.openapi_generator.petstore.okhttp.model.PetStatus;
-import java.util.function.Supplier;
import okhttp3.*;
-import okhttp3.logging.HttpLoggingInterceptor;
import org.junit.jupiter.api.Test;
-import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.MethodSource;
-class OAuth2InterceptorTest extends BaseClientTest {
+class OAuth2InterceptorTest extends BaseHttpClientTest {
private static OkHttpClient clientWithInterceptors(TestConfig testConfig) {
- var loggingInterceptor = new HttpLoggingInterceptor(System.out::println);
- loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
- OkHttpClient baseClient = new OkHttpClient.Builder().addInterceptor(loggingInterceptor).build();
+ OkHttpClient baseClient = new OkHttpClient.Builder().build();
return baseClient.newBuilder().addInterceptor(new OAuth2Interceptor(testConfig.getOAuth2Config(), baseClient.newBuilder())).build();
}
- @ParameterizedTest
- @MethodSource("testConfigProvider")
- void client_ShouldSucceed(Supplier configSupplier) throws Exception {
+ @Override
+ protected void clientShouldSucceed(TestConfig testConfig, boolean retryOn404) throws Exception {
// GIVEN
- TestConfig testConfig = configSupplier.get();
OkHttpClient httpClient = clientWithInterceptors(testConfig);
// WHEN: create resource
@@ -49,23 +43,30 @@ void client_ShouldSucceed(Supplier configSupplier) throws Exception
}
// WHEN: fetch resource
- Request getRequest = createGetRequest(testConfig, resourceId);
- Call getCall = httpClient.newCall(getRequest);
- try (Response response = getCall.execute()) {
- // THEN
- assertEquals(200, response.code());
- assertNotNull(response.body());
- String resource = response.body().string();
- assertTrue(resource.contains("id")); // Resource fetched
- }
+ String resource = onNotFound(retryOn404, "GET", () -> {
+ Request getRequest = createGetRequest(testConfig, resourceId);
+ try (Response response = httpClient.newCall(getRequest).execute()) {
+ if (retryOn404) {
+ failIfNotFound(response.code());
+ }
+ assertEquals(200, response.code());
+ assertNotNull(response.body());
+ return response.body().string();
+ }
+ });
+ assertTrue(resource.contains("id")); // Resource fetched
// WHEN: delete resource
- Request deleteRequest = createDeleteRequest(testConfig, resourceId);
- Call deleteCall = httpClient.newCall(deleteRequest);
- try (Response response = deleteCall.execute()) {
- // THEN
- assertEquals(204, response.code()); // Resource deleted
- }
+ onNotFound(retryOn404, "DELETE", () -> {
+ Request deleteRequest = createDeleteRequest(testConfig, resourceId);
+ try (Response response = httpClient.newCall(deleteRequest).execute()) {
+ if (retryOn404) {
+ failIfNotFound(response.code());
+ }
+ assertEquals(204, response.code()); // Resource deleted
+ return null;
+ }
+ });
}
@Test
@@ -115,13 +116,21 @@ void openapiGeneratorClient_ShouldSucceed_WhenMastercardApi() throws Exception {
assertNotNull(dog.getId());
// WHEN: fetch resource
- dog = api.getDog(dog.getId());
+ var dogId = dog.getId();
+ dog = onNotFound("GET", () -> api.getDog(dogId), error -> error instanceof ApiException ex && ex.getCode() == 404);
// THEN
assertNotNull(dog);
assertNotNull(dog.getId());
// WHEN / THEN: delete resource
- api.deleteDog(dog.getId());
+ onNotFound(
+ "DELETE",
+ () -> {
+ api.deleteDog(dogId);
+ return null;
+ },
+ error -> error instanceof ApiException ex && ex.getCode() == 404
+ );
}
@Test
diff --git a/library/src/test/java/com/mastercard/developer/oauth2/http/spring/restclient/OAuth2ClientHttpRequestInterceptorTest.java b/library/src/test/java/com/mastercard/developer/oauth2/http/spring/restclient/OAuth2ClientHttpRequestInterceptorTest.java
index 1fa7db6..9ad5938 100644
--- a/library/src/test/java/com/mastercard/developer/oauth2/http/spring/restclient/OAuth2ClientHttpRequestInterceptorTest.java
+++ b/library/src/test/java/com/mastercard/developer/oauth2/http/spring/restclient/OAuth2ClientHttpRequestInterceptorTest.java
@@ -1,10 +1,11 @@
package com.mastercard.developer.oauth2.http.spring.restclient;
import static com.mastercard.developer.oauth2.http.StandardHttpHeader.*;
+import static com.mastercard.developer.oauth2.test.fixtures.LiveResourceRetry.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.skyscreamer.jsonassert.JSONAssert.*;
-import com.mastercard.developer.oauth2.test.fixtures.BaseClientTest;
+import com.mastercard.developer.oauth2.test.fixtures.BaseHttpClientTest;
import com.mastercard.developer.oauth2.test.fixtures.TestConfig;
import com.mastercard.developer.test.openapi_generator.fake.restclient.api.ResourcesApi;
import com.mastercard.developer.test.openapi_generator.fake.restclient.model.Resource;
@@ -16,28 +17,23 @@
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
-import java.util.function.Supplier;
import org.junit.jupiter.api.Test;
-import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.MethodSource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestClient;
-class OAuth2ClientHttpRequestInterceptorTest extends BaseClientTest {
+class OAuth2ClientHttpRequestInterceptorTest extends BaseHttpClientTest {
private static RestClient clientWithInterceptor(TestConfig testConfig) {
var interceptor = new OAuth2ClientHttpRequestInterceptor(testConfig.getOAuth2Config());
return RestClient.builder().requestInterceptor(interceptor).build();
}
- @ParameterizedTest
- @MethodSource("testConfigProvider")
- void client_ShouldSucceed(Supplier configSupplier) throws Exception {
+ @Override
+ protected void clientShouldSucceed(TestConfig testConfig, boolean retryOn404) throws Exception {
// GIVEN
- TestConfig testConfig = configSupplier.get();
RestClient restClient = clientWithInterceptor(testConfig);
// WHEN: create resource
@@ -51,14 +47,24 @@ void client_ShouldSucceed(Supplier configSupplier) throws Exception
var resourceId = readResourceId(resource);
// WHEN: fetch resource
- resource = createGetSpec(restClient, testConfig, resourceId).retrieve().body(String.class);
+ resource = onNotFound(
+ retryOn404,
+ "GET",
+ () -> createGetSpec(restClient, testConfig, resourceId).retrieve().body(String.class),
+ error -> error instanceof HttpClientErrorException ex && ex.getStatusCode().value() == 404
+ );
// THEN
assertNotNull(resource);
assertTrue(resource.contains("id")); // Resource fetched
// WHEN: delete resource
- ResponseEntity entity = createDeleteSpec(restClient, testConfig, resourceId).retrieve().toBodilessEntity();
+ ResponseEntity entity = onNotFound(
+ retryOn404,
+ "DELETE",
+ () -> createDeleteSpec(restClient, testConfig, resourceId).retrieve().toBodilessEntity(),
+ error -> error instanceof HttpClientErrorException ex && ex.getStatusCode().value() == 404
+ );
// THEN
assertEquals(HttpStatusCode.valueOf(204), entity.getStatusCode()); // Resource deleted
@@ -90,7 +96,7 @@ void openapiGeneratorClient_ShouldSucceed_WhenFakeServers() {
}
@Test
- void openapiGeneratorClient_ShouldSucceed_WhenMastercardApi() {
+ void openapiGeneratorClient_ShouldSucceed_WhenMastercardApi() throws Exception {
// GIVEN
TestConfig testConfig = getMastercardConfig();
RestClient restClient = clientWithInterceptor(testConfig);
@@ -112,13 +118,21 @@ void openapiGeneratorClient_ShouldSucceed_WhenMastercardApi() {
assertNotNull(dog.getId());
// WHEN: fetch resource
- dog = api.getDog(dog.getId());
+ var dogId = dog.getId();
+ dog = onNotFound("GET", () -> api.getDog(dogId), error -> error instanceof HttpClientErrorException ex && ex.getStatusCode().value() == 404);
// THEN
assertNotNull(dog);
assertNotNull(dog.getId());
// WHEN / THEN: delete resource
- api.deleteDog(dog.getId());
+ onNotFound(
+ "DELETE",
+ () -> {
+ api.deleteDog(dogId);
+ return null;
+ },
+ error -> error instanceof HttpClientErrorException ex && ex.getStatusCode().value() == 404
+ );
}
@Test
diff --git a/library/src/test/java/com/mastercard/developer/oauth2/http/spring/webclient/OAuth2FilterTest.java b/library/src/test/java/com/mastercard/developer/oauth2/http/spring/webclient/OAuth2FilterTest.java
index 2a9f841..b3fb012 100644
--- a/library/src/test/java/com/mastercard/developer/oauth2/http/spring/webclient/OAuth2FilterTest.java
+++ b/library/src/test/java/com/mastercard/developer/oauth2/http/spring/webclient/OAuth2FilterTest.java
@@ -1,10 +1,11 @@
package com.mastercard.developer.oauth2.http.spring.webclient;
import static com.mastercard.developer.oauth2.http.StandardHttpHeader.*;
+import static com.mastercard.developer.oauth2.test.fixtures.LiveResourceRetry.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.skyscreamer.jsonassert.JSONAssert.*;
-import com.mastercard.developer.oauth2.test.fixtures.BaseClientTest;
+import com.mastercard.developer.oauth2.test.fixtures.BaseHttpClientTest;
import com.mastercard.developer.oauth2.test.fixtures.TestConfig;
import com.mastercard.developer.test.openapi_generator.fake.webclient.api.ResourcesApi;
import com.mastercard.developer.test.openapi_generator.fake.webclient.model.Resource;
@@ -16,10 +17,7 @@
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
-import java.util.function.Supplier;
import org.junit.jupiter.api.Test;
-import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.MethodSource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
@@ -27,7 +25,7 @@
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Mono;
-class OAuth2FilterTest extends BaseClientTest {
+class OAuth2FilterTest extends BaseHttpClientTest {
private static WebClient clientWithFilter(TestConfig testConfig) {
WebClient.Builder baseBuilder = WebClient.builder();
@@ -35,11 +33,9 @@ private static WebClient clientWithFilter(TestConfig testConfig) {
return baseBuilder.filter(filter).build();
}
- @ParameterizedTest
- @MethodSource("testConfigProvider")
- void client_ShouldSucceed(Supplier configSupplier) throws Exception {
+ @Override
+ protected void clientShouldSucceed(TestConfig testConfig, boolean retryOn404) throws Exception {
// GIVEN
- TestConfig testConfig = configSupplier.get();
WebClient webClient = clientWithFilter(testConfig);
// WHEN: create resource
@@ -55,13 +51,23 @@ void client_ShouldSucceed(Supplier configSupplier) throws Exception
var resourceId = readResourceId(resource);
// WHEN: fetch resource
- resource = createGetSpec(webClient, testConfig, resourceId).retrieve().bodyToMono(String.class).block();
+ resource = onNotFound(
+ retryOn404,
+ "GET",
+ () -> createGetSpec(webClient, testConfig, resourceId).retrieve().bodyToMono(String.class).block(),
+ error -> error instanceof WebClientResponseException ex && ex.getStatusCode().value() == 404
+ );
// THEN
assertNotNull(resource);
assertTrue(resource.contains("id")); // Resource fetched
// WHEN: delete resource
- ResponseEntity entity = createDeleteSpec(webClient, testConfig, resourceId).retrieve().toBodilessEntity().block();
+ ResponseEntity entity = onNotFound(
+ retryOn404,
+ "DELETE",
+ () -> createDeleteSpec(webClient, testConfig, resourceId).retrieve().toBodilessEntity().block(),
+ error -> error instanceof WebClientResponseException ex && ex.getStatusCode().value() == 404
+ );
// THEN
assertNotNull(entity);
assertEquals(HttpStatusCode.valueOf(204), entity.getStatusCode()); // Resource deleted
@@ -93,7 +99,7 @@ void openapiGeneratorClient_ShouldSucceed_WhenFakeServers() {
}
@Test
- void openapiGeneratorClient_ShouldSucceed_WhenMastercardApi() {
+ void openapiGeneratorClient_ShouldSucceed_WhenMastercardApi() throws Exception {
{
// GIVEN
TestConfig testConfig = getMastercardConfig();
@@ -115,13 +121,14 @@ void openapiGeneratorClient_ShouldSucceed_WhenMastercardApi() {
assertNotNull(dog.getId());
// WHEN: fetch resource
- dog = api.getDog(dog.getId()).block();
+ var dogId = dog.getId();
+ dog = onNotFound("GET", () -> api.getDog(dogId).block(), error -> error instanceof WebClientResponseException ex && ex.getStatusCode().value() == 404);
// THEN
assertNotNull(dog);
assertNotNull(dog.getId());
// WHEN / THEN: delete resource
- api.deleteDog(dog.getId()).block();
+ onNotFound("DELETE", () -> api.deleteDog(dogId).block(), error -> error instanceof WebClientResponseException ex && ex.getStatusCode().value() == 404);
}
}
diff --git a/library/src/test/java/com/mastercard/developer/oauth2/test/fixtures/BaseClientTest.java b/library/src/test/java/com/mastercard/developer/oauth2/test/fixtures/BaseClientTest.java
index b85e653..2d95e91 100644
--- a/library/src/test/java/com/mastercard/developer/oauth2/test/fixtures/BaseClientTest.java
+++ b/library/src/test/java/com/mastercard/developer/oauth2/test/fixtures/BaseClientTest.java
@@ -53,13 +53,6 @@ protected void useInsufficientScopeScenario() {
resourceServer.useInsufficientScopeScenario();
}
- protected static Stream testConfigProvider() {
- return Stream.of(
- createConfigArgument("Mastercard API", BaseClientTest::getMastercardConfig),
- createConfigArgument("Fake authorization and resource servers", BaseClientTest::getFakeConfig)
- );
- }
-
protected static Stream serverAndKeyProvider() {
return Stream.of(
createConfigArgument("Mastercard API + EC DPoP key", BaseClientTest::getMastercardConfigWithEcKey),
diff --git a/library/src/test/java/com/mastercard/developer/oauth2/test/fixtures/BaseHttpClientTest.java b/library/src/test/java/com/mastercard/developer/oauth2/test/fixtures/BaseHttpClientTest.java
new file mode 100644
index 0000000..0ebd6d3
--- /dev/null
+++ b/library/src/test/java/com/mastercard/developer/oauth2/test/fixtures/BaseHttpClientTest.java
@@ -0,0 +1,18 @@
+package com.mastercard.developer.oauth2.test.fixtures;
+
+import org.junit.jupiter.api.Test;
+
+public abstract class BaseHttpClientTest extends BaseClientTest {
+
+ @Test
+ protected void client_ShouldSucceed_WhenFakeServers() throws Exception {
+ clientShouldSucceed(getFakeConfig(), false);
+ }
+
+ @Test
+ protected void client_ShouldSucceed_WhenMastercardApi() throws Exception {
+ clientShouldSucceed(getMastercardConfig(), true);
+ }
+
+ protected abstract void clientShouldSucceed(TestConfig testConfig, boolean retryOn404) throws Exception;
+}
diff --git a/library/src/test/java/com/mastercard/developer/oauth2/test/fixtures/LiveResourceRetry.java b/library/src/test/java/com/mastercard/developer/oauth2/test/fixtures/LiveResourceRetry.java
new file mode 100644
index 0000000..19ad599
--- /dev/null
+++ b/library/src/test/java/com/mastercard/developer/oauth2/test/fixtures/LiveResourceRetry.java
@@ -0,0 +1,61 @@
+package com.mastercard.developer.oauth2.test.fixtures;
+
+import java.util.concurrent.Callable;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Predicate;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public final class LiveResourceRetry {
+
+ private static final Logger logger = LoggerFactory.getLogger(LiveResourceRetry.class);
+ private static final int MAX_ATTEMPTS = 10;
+
+ private LiveResourceRetry() {
+ // Test utility
+ }
+
+ public static T onNotFound(String method, Callable request) throws Exception {
+ return onNotFound(method, request, error -> error instanceof NotFoundException);
+ }
+
+ public static T onNotFound(boolean retryOn404, String method, Callable request) throws Exception {
+ return retryOn404 ? onNotFound(method, request) : request.call();
+ }
+
+ public static T onNotFound(boolean retryOn404, String method, Callable request, Predicate isNotFound) throws Exception {
+ return retryOn404 ? onNotFound(method, request, isNotFound) : request.call();
+ }
+
+ public static T onNotFound(String method, Callable request, Predicate isNotFound) throws Exception {
+ for (int attempt = 1; ; attempt++) {
+ try {
+ return request.call();
+ } catch (Exception error) {
+ if (!isNotFound.test(error) || attempt == MAX_ATTEMPTS) {
+ throw error;
+ }
+ logger.info("{} returned 404; retrying (attempt {} of {})", method, attempt + 1, MAX_ATTEMPTS);
+ try {
+ TimeUnit.SECONDS.sleep(1);
+ } catch (InterruptedException interrupted) {
+ Thread.currentThread().interrupt();
+ throw interrupted;
+ }
+ }
+ }
+ }
+
+ public static void failIfNotFound(int status) {
+ if (status == 404) {
+ throw new NotFoundException();
+ }
+ }
+
+ private static final class NotFoundException extends RuntimeException {
+
+ private NotFoundException() {
+ super("Resource request returned HTTP 404");
+ }
+ }
+}
diff --git a/library/src/test/java/com/mastercard/developer/oauth2/test/fixtures/LiveResourceRetryTest.java b/library/src/test/java/com/mastercard/developer/oauth2/test/fixtures/LiveResourceRetryTest.java
new file mode 100644
index 0000000..7f08943
--- /dev/null
+++ b/library/src/test/java/com/mastercard/developer/oauth2/test/fixtures/LiveResourceRetryTest.java
@@ -0,0 +1,68 @@
+package com.mastercard.developer.oauth2.test.fixtures;
+
+import static com.mastercard.developer.oauth2.test.fixtures.LiveResourceRetry.*;
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.io.IOException;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.junit.jupiter.api.Test;
+
+class LiveResourceRetryTest {
+
+ @Test
+ void retriesNotFoundUntilSuccess() throws Exception {
+ var attempts = new AtomicInteger();
+
+ String result = onNotFound("GET", () -> {
+ if (attempts.incrementAndGet() == 1) {
+ failIfNotFound(404);
+ }
+ return "found";
+ });
+
+ assertEquals("found", result);
+ assertEquals(2, attempts.get());
+ }
+
+ @Test
+ void doesNotRetryOtherErrors() {
+ var attempts = new AtomicInteger();
+ var error = new IOException("Other failure");
+
+ assertSame(
+ error,
+ assertThrows(IOException.class, () ->
+ onNotFound(
+ "GET",
+ () -> {
+ attempts.incrementAndGet();
+ throw error;
+ },
+ exception -> false
+ )
+ )
+ );
+ assertEquals(1, attempts.get());
+ }
+
+ @Test
+ void failsWithLastNotFoundAfterTenAttempts() {
+ var attempts = new AtomicInteger();
+ var error = new IOException("HTTP 404");
+
+ assertSame(
+ error,
+ assertThrows(IOException.class, () ->
+ onNotFound(
+ "DELETE",
+ () -> {
+ attempts.incrementAndGet();
+ throw error;
+ },
+ exception -> exception == error
+ )
+ )
+ );
+ assertEquals(10, attempts.get());
+ }
+}