Implement claimOneTimePurchase in IAP processors

This commit is contained in:
Ravi Khadiwala authored and ravi-signal committed 2026-08-07 14:18:00 -05:00
1 parent 674d03ef0c
commit 894cd8e0a3
8 files changed
+561 -109

No files matched your search

@@ -5,11 +5,9 @@
package org.whispersystems.textsecuregcm.subscriptions;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatException;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@@ -23,15 +21,21 @@ import com.apple.itunes.storekit.model.JWSTransactionDecodedPayload;
import com.apple.itunes.storekit.model.LastTransactionsItem;
import com.apple.itunes.storekit.model.Status;
import com.apple.itunes.storekit.model.StatusResponse;
import com.apple.itunes.storekit.model.TransactionInfoResponse;
import com.apple.itunes.storekit.verification.SignedDataVerifier;
import com.apple.itunes.storekit.verification.VerificationException;
import java.io.IOException;
import java.io.UncheckedIOException;
import io.micrometer.core.instrument.Tags;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
class AppleAppStoreClientTest {
@@ -54,90 +58,139 @@ class AppleAppStoreClientTest {
sandboxSignedDataVerifier, sandboxClient, null);
}
@ParameterizedTest
@EnumSource(value = APIError.class, mode = EnumSource.Mode.EXCLUDE, names = "TRANSACTION_ID_NOT_FOUND")
public void noFallbackOnOtherErrors(APIError error) throws APIException, IOException {
@Test
public void getAllSubscriptions()
throws APIException, IOException, SubscriptionInvalidArgumentsException, SubscriptionNotFoundException, RateLimitExceededException {
when(productionClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
.thenThrow(new APIException(404, error, "test"));
.thenReturn(new StatusResponse().environment(Environment.PRODUCTION));
assertThat(apiWrapper.getAllSubscriptions(ORIGINAL_TX_ID, Tags.empty()).getEnvironment())
.isEqualTo(Environment.PRODUCTION);
}
assertThatException().isThrownBy(() -> apiWrapper.getAllSubscriptions(ORIGINAL_TX_ID, Tags.empty()));
verifyNoInteractions(sandboxClient);
@Test
public void getAllSubscriptionsFallback()
throws APIException, IOException, SubscriptionInvalidArgumentsException, SubscriptionNotFoundException, RateLimitExceededException {
when(productionClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
.thenThrow(new APIException(404, APIError.TRANSACTION_ID_NOT_FOUND, "test"));
when(sandboxClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
.thenReturn(new StatusResponse().environment(Environment.SANDBOX));
assertThat(apiWrapper.getAllSubscriptions(ORIGINAL_TX_ID, Tags.empty()).getEnvironment()).isEqualTo(Environment.SANDBOX);
}
public static Stream<Arguments> getAllSubscriptionsErrors() {
return Stream.of(
Arguments.of(new APIException(404, APIError.ORIGINAL_TRANSACTION_ID_NOT_FOUND, "test"), SubscriptionNotFoundException.class),
Arguments.of(new APIException(404, APIError.ACCOUNT_NOT_FOUND, "test"), SubscriptionNotFoundException.class),
Arguments.of(new APIException(429, APIError.RATE_LIMIT_EXCEEDED, "test"), RateLimitExceededException.class),
Arguments.of(new APIException(429, APIError.INVALID_ORIGINAL_TRANSACTION_ID, "test"), SubscriptionInvalidArgumentsException.class));
}
@ParameterizedTest
@EnumSource(mode = EnumSource.Mode.INCLUDE, names = {"TRANSACTION_ID_NOT_FOUND", "ORIGINAL_TRANSACTION_ID_NOT_FOUND", "ACCOUNT_NOT_FOUND"})
public void notFound(APIError error) throws APIException, IOException {
when(productionClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
.thenThrow(new APIException(404, error, "test"));
when(sandboxClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
.thenThrow(new APIException(404, error, "test"));
assertThatExceptionOfType(SubscriptionNotFoundException.class)
@MethodSource
public void getAllSubscriptionsErrors(final APIException error, final Class<? extends Exception> expected)
throws APIException, IOException {
when(productionClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{})).thenThrow(error);
assertThatExceptionOfType(expected)
.isThrownBy(() -> apiWrapper.getAllSubscriptions(ORIGINAL_TX_ID, Tags.empty()));
}
@Test
public void lookupTransaction()
throws APIException, IOException, RateLimitExceededException, VerificationException {
final JWSTransactionDecodedPayload expected = new JWSTransactionDecodedPayload();
when(productionClient.getTransactionInfo(ORIGINAL_TX_ID))
.thenReturn(new TransactionInfoResponse().signedTransactionInfo("signed"));
when(productionSignedDataVerifier.verifyAndDecodeTransaction("signed")).thenReturn(expected);
assertThat(apiWrapper.lookupTransaction(ORIGINAL_TX_ID, Tags.empty())).hasValue(expected);
}
@Test
public void lookupTransactionFallback()
throws APIException, IOException, RateLimitExceededException, VerificationException {
final JWSTransactionDecodedPayload expected = new JWSTransactionDecodedPayload();
when(productionClient.getTransactionInfo(ORIGINAL_TX_ID))
.thenThrow(new APIException(404, APIError.TRANSACTION_ID_NOT_FOUND, "test"));
when(sandboxClient.getTransactionInfo(ORIGINAL_TX_ID))
.thenReturn(new TransactionInfoResponse().signedTransactionInfo("signed"));
when(sandboxSignedDataVerifier.verifyAndDecodeTransaction("signed")).thenReturn(expected);
assertThat(apiWrapper.lookupTransaction(ORIGINAL_TX_ID, Tags.empty())).hasValue(expected);
verifyNoInteractions(productionSignedDataVerifier);
}
public static Stream<Arguments> lookupTransactionErrors() {
return Stream.of(
Arguments.of(new APIException(404, APIError.ORIGINAL_TRANSACTION_ID_NOT_FOUND, "test"), null),
Arguments.of(new APIException(404, APIError.ACCOUNT_NOT_FOUND, "test"), null),
Arguments.of(new APIException(400, APIError.INVALID_TRANSACTION_ID, "test"), null),
Arguments.of(new APIException(409, APIError.INVALID_ORIGINAL_TRANSACTION_ID, "test"), null),
Arguments.of(new APIException(429, APIError.RATE_LIMIT_EXCEEDED, "test"), RateLimitExceededException.class));
}
@ParameterizedTest
@MethodSource
public void lookupTransactionErrors(final APIException error, final Class<? extends Exception> expected)
throws APIException, IOException, RateLimitExceededException {
when(productionClient.getTransactionInfo(ORIGINAL_TX_ID)).thenThrow(error);
if (expected == null) {
assertThat(apiWrapper.lookupTransaction(ORIGINAL_TX_ID, Tags.empty())).isEmpty();
} else {
assertThatExceptionOfType(expected)
.isThrownBy(() -> apiWrapper.lookupTransaction(ORIGINAL_TX_ID, Tags.empty()));
}
}
@ParameterizedTest
@EnumSource(value = APIError.class, mode = EnumSource.Mode.EXCLUDE, names = "TRANSACTION_ID_NOT_FOUND")
public void noFallbackOnOtherErrors(APIError error) {
final ConfigurableFinder throwingFinder = new ConfigurableFinder(always(new APIException(404, error, "test")));
assertThatExceptionOfType(APIException.class).isThrownBy(() ->
apiWrapper.lookupByTransactionId(ORIGINAL_TX_ID, Tags.empty(), throwingFinder));
assertThat(throwingFinder.attempts).allMatch(Environment.PRODUCTION::equals);
}
@Test
public void fallbackOnNoTransactionFound()
throws APIException, IOException, SubscriptionInvalidArgumentsException, SubscriptionNotFoundException, RateLimitExceededException {
when(productionClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
.thenThrow(new APIException(404, APIError.TRANSACTION_ID_NOT_FOUND, "test"));
throws APIException, IOException {
final ConfigurableFinder finder =
new ConfigurableFinder(times(1, new APIException(404, APIError.TRANSACTION_ID_NOT_FOUND, "test")));
when(sandboxClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
.thenReturn(new StatusResponse().environment(Environment.SANDBOX));
final StatusResponse allSubscriptions = apiWrapper.getAllSubscriptions(ORIGINAL_TX_ID, Tags.empty());
assertThat(allSubscriptions.getEnvironment()).isEqualTo(Environment.SANDBOX);
verify(productionClient).getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{});
verify(sandboxClient).getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{});
assertThat(apiWrapper.lookupByTransactionId(ORIGINAL_TX_ID, Tags.empty(), finder)).isEqualTo(Environment.SANDBOX);
assertThat(finder.attempts).containsExactly(Environment.PRODUCTION, Environment.SANDBOX);
}
@Test
public void retryEventuallyWorks()
throws APIException, IOException, VerificationException, RateLimitExceededException, SubscriptionException {
throws APIException, IOException {
// Should retry up to 3 times
when(productionClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
.thenThrow(new APIException(404, APIError.ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE.errorCode(), "test"))
.thenThrow(new APIException(404, APIError.ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE.errorCode(), "test"))
.thenReturn(new StatusResponse().environment(Environment.PRODUCTION));
final StatusResponse statusResponse = apiWrapper.getAllSubscriptions(ORIGINAL_TX_ID, Tags.empty());
assertThat(statusResponse.getEnvironment()).isEqualTo(Environment.PRODUCTION);
verifyNoInteractions(sandboxClient);
final ConfigurableFinder finder = new ConfigurableFinder(
times(2, new APIException(404, APIError.ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE.errorCode(), "test")));
assertThat(apiWrapper.lookupByTransactionId(ORIGINAL_TX_ID, Tags.empty(), finder)).isEqualTo(Environment.PRODUCTION);
assertThat(finder.attempts).containsExactly(Environment.PRODUCTION, Environment.PRODUCTION, Environment.PRODUCTION);
}
@Test
public void retryEventuallyGivesUp() throws APIException, IOException, VerificationException {
public void retryEventuallyGivesUp() {
// Should retry up to 3 times
when(productionClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
.thenThrow(new APIException(404, APIError.ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE.errorCode(), "test"));
assertThatException()
.isThrownBy(() -> apiWrapper.getAllSubscriptions(ORIGINAL_TX_ID, Tags.empty()))
.isInstanceOf(UncheckedIOException.class)
.withRootCauseInstanceOf(APIException.class);
verify(productionClient, times(3)).getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{});
verifyNoInteractions(sandboxClient);
final ConfigurableFinder finder =
new ConfigurableFinder(always(new APIException(404, APIError.ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE.errorCode(), "test")));
assertThatExceptionOfType(APIException.class)
.isThrownBy(() -> apiWrapper.lookupByTransactionId(ORIGINAL_TX_ID, Tags.empty(), finder));
assertThat(finder.attempts).containsExactly(Environment.PRODUCTION, Environment.PRODUCTION, Environment.PRODUCTION);
}
@Test
public void sandboxDoesRetries()
throws APIException, IOException, SubscriptionInvalidArgumentsException, SubscriptionNotFoundException, RateLimitExceededException {
when(productionClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
.thenThrow(new APIException(404, APIError.TRANSACTION_ID_NOT_FOUND, "test"));
throws APIException, IOException {
final ConfigurableFinder finder = new ConfigurableFinder(
times(1, new APIException(404, APIError.TRANSACTION_ID_NOT_FOUND, "test")),
times(2, new APIException(404, APIError.ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE.errorCode(), "test")));
when(sandboxClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
.thenThrow(new APIException(404, APIError.ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE.errorCode(), "test"))
.thenThrow(new APIException(404, APIError.ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE.errorCode(), "test"))
.thenReturn(new StatusResponse().environment(Environment.SANDBOX));
final StatusResponse statusResponse = apiWrapper.getAllSubscriptions(ORIGINAL_TX_ID, Tags.empty());
assertThat(statusResponse.getEnvironment()).isEqualTo(Environment.SANDBOX);
verify(productionClient, times(3))
.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{});
verify(sandboxClient, times(3))
.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{});
assertThat(apiWrapper.lookupByTransactionId(ORIGINAL_TX_ID, Tags.empty(), finder)).isEqualTo(Environment.SANDBOX);
assertThat(finder.attempts).containsExactly(Environment.PRODUCTION, Environment.SANDBOX, Environment.SANDBOX, Environment.SANDBOX);
}
@ParameterizedTest
@@ -157,7 +210,7 @@ class AppleAppStoreClientTest {
when(expectedVerifier.verifyAndDecodeRenewalInfo(SIGNED_RENEWAL_INFO))
.thenReturn(new JWSRenewalInfoDecodedPayload());
apiWrapper.verify(environment, new LastTransactionsItem()
apiWrapper.verifySubscription(environment, new LastTransactionsItem()
.originalTransactionId(ORIGINAL_TX_ID)
.status(Status.ACTIVE)
.signedRenewalInfo(SIGNED_RENEWAL_INFO)
@@ -167,4 +220,53 @@ class AppleAppStoreClientTest {
verify(expectedVerifier).verifyAndDecodeRenewalInfo(SIGNED_RENEWAL_INFO);
verifyNoInteractions(unexpectedVerifier);
}
/// Indicates how many times to throw an exception on calls to [ConfigurableFinder#lookup]
private static class ExceptionConfig {
int numTimes;
final APIException exception;
ExceptionConfig(final int numTimes, final APIException exception) {
this.numTimes = numTimes;
this.exception = exception;
}
}
/// [ExceptionConfig] that indicates `exception` should be thrown on every call
private static ExceptionConfig always(final APIException exception) {
return new ExceptionConfig(-1, exception);
}
/// [ExceptionConfig] that indicates `exception` should be thrown `numTimes`
private static ExceptionConfig times(int numTimes, final APIException exception) {
return new ExceptionConfig(numTimes, exception);
}
/// TransactionFinder with configurable exception behavior
private static class ConfigurableFinder implements AppleAppStoreClient.TransactionFinder<Environment> {
private final ArrayDeque<ExceptionConfig> configs;
private final List<Environment> attempts = new ArrayList<>();
ConfigurableFinder(ExceptionConfig... configs) {
this.configs = new ArrayDeque<>(List.of(configs));
}
@Override
public Environment lookup(final Environment environment, final String transactionId) throws APIException {
attempts.add(environment);
if (configs.isEmpty()) {
return environment;
}
final ExceptionConfig first = configs.getFirst();
if (first.numTimes == 1) {
configs.removeFirst();
}
first.numTimes -= 1;
throw first.exception;
}
}
}
@@ -16,12 +16,15 @@ import com.apple.itunes.storekit.client.APIException;
import com.apple.itunes.storekit.client.AppStoreServerAPIClient;
import com.apple.itunes.storekit.model.AutoRenewStatus;
import com.apple.itunes.storekit.model.Environment;
import com.apple.itunes.storekit.model.InAppOwnershipType;
import com.apple.itunes.storekit.model.JWSRenewalInfoDecodedPayload;
import com.apple.itunes.storekit.model.JWSTransactionDecodedPayload;
import com.apple.itunes.storekit.model.LastTransactionsItem;
import com.apple.itunes.storekit.model.Status;
import com.apple.itunes.storekit.model.StatusResponse;
import com.apple.itunes.storekit.model.SubscriptionGroupIdentifierItem;
import com.apple.itunes.storekit.model.TransactionInfoResponse;
import com.apple.itunes.storekit.model.Type;
import com.apple.itunes.storekit.verification.SignedDataVerifier;
import com.apple.itunes.storekit.verification.VerificationException;
import java.io.IOException;
@@ -40,6 +43,7 @@ class AppleAppStoreManagerTest {
private final static long LEVEL = 123L;
private final static String ORIGINAL_TX_ID = "originalTxIdTest";
private final static String TRANSACTION_ID = "txIdTest";
private final static String SUBSCRIPTION_GROUP_ID = "subscriptionGroupIdTest";
private final static String SIGNED_RENEWAL_INFO = "signedRenewalInfoTest";
private final static String SIGNED_TX_INFO = "signedRenewalInfoTest";
@@ -190,6 +194,37 @@ class AppleAppStoreManagerTest {
assertDoesNotThrow(() -> appleAppStoreManager.cancelAllActiveSubscriptions(ORIGINAL_TX_ID));
}
@Test
public void getPaymentDetails()
throws APIException, IOException, VerificationException, SubscriptionException, RateLimitExceededException {
when(apiClient.getTransactionInfo(TRANSACTION_ID))
.thenReturn(new TransactionInfoResponse().signedTransactionInfo(SIGNED_TX_INFO));
final JWSTransactionDecodedPayload payload = new JWSTransactionDecodedPayload()
.transactionId(TRANSACTION_ID)
.productId(PRODUCT_ID)
.type(Type.CONSUMABLE)
.inAppOwnershipType(InAppOwnershipType.PURCHASED)
.purchaseDate(Instant.EPOCH.plus(Duration.ofDays(1)).toEpochMilli());
when(signedDataVerifier.verifyAndDecodeTransaction(SIGNED_TX_INFO)).thenReturn(payload);
{
// PURCHASED payment
final PaymentDetails paymentDetails = appleAppStoreManager.claimOneTimePurchase(TRANSACTION_ID).orElseThrow();
assertThat(paymentDetails.id()).isEqualTo(TRANSACTION_ID);
assertThat(paymentDetails.level()).isEqualTo(LEVEL);
assertThat(paymentDetails.created()).isEqualTo(Instant.EPOCH.plus(Duration.ofDays(1)));
assertThat(paymentDetails.chargeFailure()).isNull();
assertThat(paymentDetails.status()).isEqualTo(PaymentStatus.SUCCEEDED);
}
{
// REVOKED payment
payload.setRevocationDate(Instant.EPOCH.plus(Duration.ofDays(2)).toEpochMilli());
final PaymentDetails paymentDetails = appleAppStoreManager.claimOneTimePurchase(TRANSACTION_ID).orElseThrow();
assertThat(paymentDetails.status()).isEqualTo(PaymentStatus.FAILED);
}
}
private void mockSubscription(final Status status, final AutoRenewStatus autoRenewStatus)
throws APIException, IOException, VerificationException {
when(apiClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{}))
@@ -22,6 +22,10 @@ import com.google.api.services.androidpublisher.AndroidPublisher;
import com.google.api.services.androidpublisher.model.AutoRenewingPlan;
import com.google.api.services.androidpublisher.model.Money;
import com.google.api.services.androidpublisher.model.OfferDetails;
import com.google.api.services.androidpublisher.model.ProductLineItem;
import com.google.api.services.androidpublisher.model.ProductOfferDetails;
import com.google.api.services.androidpublisher.model.ProductPurchaseV2;
import com.google.api.services.androidpublisher.model.PurchaseStateContext;
import com.google.api.services.androidpublisher.model.SubscriptionPurchaseLineItem;
import com.google.api.services.androidpublisher.model.SubscriptionPurchaseV2;
import java.io.IOException;
@@ -31,12 +35,14 @@ import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.util.MockUtils;
import org.whispersystems.textsecuregcm.util.MutableClock;
@@ -60,13 +66,21 @@ class GooglePlayBillingManagerTest {
private final AndroidPublisher.Purchases.Subscriptions.Cancel cancel =
mock(AndroidPublisher.Purchases.Subscriptions.Cancel.class);
// Returned in response to a purchases.productsv2.getproductpurchasev2
private final AndroidPublisher.Purchases.Productsv2.Getproductpurchasev2 getProductPurchase =
mock(AndroidPublisher.Purchases.Productsv2.Getproductpurchasev2.class);
// Returned in response to a purchases.products.consume
private final AndroidPublisher.Purchases.Products.Consume consume =
mock(AndroidPublisher.Purchases.Products.Consume.class);
private final MutableClock clock = MockUtils.mutableClock(0L);
private GooglePlayBillingManager googlePlayBillingManager;
@BeforeEach
public void setup() throws IOException {
reset(subscriptionsv2Get);
reset(subscriptionsv2Get, getProductPurchase, consume);
clock.setTimeMillis(0L);
AndroidPublisher androidPublisher = mock(AndroidPublisher.class);
@@ -87,6 +101,14 @@ class GooglePlayBillingManagerTest {
when(subscriptions.cancel(PACKAGE_NAME, PRODUCT_ID, PURCHASE_TOKEN))
.thenReturn(cancel);
AndroidPublisher.Purchases.Productsv2 productsv2 = mock(AndroidPublisher.Purchases.Productsv2.class);
when(purchases.productsv2()).thenReturn(productsv2);
when(productsv2.getproductpurchasev2(PACKAGE_NAME, PURCHASE_TOKEN)).thenReturn(getProductPurchase);
AndroidPublisher.Purchases.Products products = mock(AndroidPublisher.Purchases.Products.class);
when(purchases.products()).thenReturn(products);
when(products.consume(PACKAGE_NAME, PRODUCT_ID, PURCHASE_TOKEN)).thenReturn(consume);
googlePlayBillingManager = new GooglePlayBillingManager(
androidPublisher, clock, PACKAGE_NAME, Map.of(PRODUCT_ID, 201L));
}
@@ -251,6 +273,89 @@ class GooglePlayBillingManagerTest {
}
private static ProductPurchaseV2 productPurchase(
final String purchaseState,
@Nullable final String consumptionState,
final Instant purchaseCompletionTime,
final String productId) {
final ProductLineItem lineItem = new ProductLineItem().setProductId(productId);
if (consumptionState != null) {
lineItem.setProductOfferDetails(new ProductOfferDetails().setConsumptionState(consumptionState));
}
return new ProductPurchaseV2()
.setOrderId(ORDER_ID)
.setPurchaseStateContext(new PurchaseStateContext().setPurchaseState(purchaseState))
.setPurchaseCompletionTime(purchaseCompletionTime.toString())
.setProductLineItem(List.of(lineItem));
}
@CartesianTest
public void getPaymentDetails(
@CartesianTest.Enum final GooglePlayBillingManager.PurchaseState purchaseState,
@CartesianTest.Enum final GooglePlayBillingManager.ConsumptionState consumptionState)
throws IOException, RateLimitExceededException, SubscriptionException {
when(getProductPurchase.execute()).thenReturn(productPurchase(
purchaseState.apiString(),
consumptionState.apiString(),
Instant.EPOCH.plus(Duration.ofDays(3)),
PRODUCT_ID));
final PaymentStatus expected = switch (purchaseState) {
case PURCHASED -> PaymentStatus.SUCCEEDED;
case PENDING -> PaymentStatus.PROCESSING;
case CANCELLED -> PaymentStatus.FAILED;
case PURCHASE_STATE_UNSPECIFIED -> PaymentStatus.UNKNOWN;
};
assertThat(googlePlayBillingManager.claimOneTimePurchase(PURCHASE_TOKEN)).hasValueSatisfying(details -> {
assertThat(details.status()).isEqualTo(expected);
assertThat(details.id()).isEqualTo(PURCHASE_TOKEN);
assertThat(details.level()).isEqualTo(201L);
});
final boolean expectConsume = purchaseState == GooglePlayBillingManager.PurchaseState.PURCHASED &&
consumptionState == GooglePlayBillingManager.ConsumptionState.YET_TO_BE_CONSUMED;
verify(consume, times(expectConsume ? 1 : 0)).execute();
}
public static Stream<Arguments> getPaymentDetailsErrors() {
return Stream.of(
Arguments.of(404, null),
Arguments.of(410, null),
Arguments.of(400, IOException.class),
Arguments.of(429, RateLimitExceededException.class)
);
}
@ParameterizedTest
@MethodSource
public void getPaymentDetailsErrors(final int httpStatus, final @Nullable Class<? extends Exception> expectedException)
throws IOException, SubscriptionInvalidArgumentsException, RateLimitExceededException {
final HttpResponseException mockException = mock(HttpResponseException.class);
when(mockException.getStatusCode()).thenReturn(httpStatus);
when(getProductPurchase.execute()).thenThrow(mockException);
if (expectedException == null) {
assertThat(googlePlayBillingManager.claimOneTimePurchase(PURCHASE_TOKEN)).isEmpty();
} else {
assertThatException()
.isThrownBy(() -> googlePlayBillingManager.claimOneTimePurchase(PURCHASE_TOKEN))
// Verify the exception or its leaf cause is an instanceof expected. withRootCauseInstanceOf almost does what we
// want, but fails if the outermost exception does not have a cause
.matches(e -> {
Throwable cause = e;
while (cause.getCause() != null) {
cause = cause.getCause();
}
return expectedException.isInstance(cause);
});
}
verifyNoInteractions(consume);
}
public static Stream<Arguments> tokenErrors() {
return Stream.of(
Arguments.of(404, SubscriptionNotFoundException.class),