Skip to content

Commit

Permalink
Merge pull request #5058 from alphagov/PP-12302-stop-using-dropwizard…
Browse files Browse the repository at this point in the history
…-junit-runner

PP-12302 Refactor integration tests to use JUnit5 with custom ConnectorApp extensions
  • Loading branch information
DomBelcher authored Mar 28, 2024
2 parents f6a4415 + 646175d commit 91be65e
Show file tree
Hide file tree
Showing 6 changed files with 93 additions and 132 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,13 @@ public class AppWithPostgresAndSqsExtension implements BeforeEachCallback, Befor
private final int wireMockPort = PortFactory.findFreePort();
private final int worldpayWireMockPort = PortFactory.findFreePort();
private final int ledgerWireMockPort = PortFactory.findFreePort();
private final int stripeWireMockPort = PortFactory.findFreePort();

protected static DatabaseTestHelper databaseTestHelper;
protected static WireMockServer wireMockServer;
protected static WireMockServer worldpayWireMockServer;
protected static WireMockServer ledgerWireMockServer;
protected static WireMockServer stripeWireMockServer;
protected static WorldpayMockClient worldpayMockClient;
protected static StripeMockClient stripeMockClient;
protected static LedgerStub ledgerStub;
Expand All @@ -68,10 +70,18 @@ public class AppWithPostgresAndSqsExtension implements BeforeEachCallback, Befor
protected DatabaseFixtures databaseFixtures;

public AppWithPostgresAndSqsExtension() {
this(new ConfigOverride[0]);
this(ConnectorApp.class, new ConfigOverride[0]);
}


public AppWithPostgresAndSqsExtension(Class CustomConnectorClass) {
this(CustomConnectorClass, new ConfigOverride[0]);
}

public AppWithPostgresAndSqsExtension(ConfigOverride... configOverrides) {
this(ConnectorApp.class, configOverrides);
}

public AppWithPostgresAndSqsExtension(Class CustomConnectorClass, ConfigOverride... configOverrides) {
getOrCreate();

sqsClient = SqsTestDocker.initialise(List.of("capture-queue", "event-queue", "tasks-queue", "reconcile-queue"));
Expand All @@ -80,7 +90,7 @@ public AppWithPostgresAndSqsExtension(ConfigOverride... configOverrides) {
newConfigOverrides = overrideEndpointConfig(newConfigOverrides);
newConfigOverrides = overrideSqsConfig(newConfigOverrides);

dropwizardAppExtension = new DropwizardAppExtension<>(ConnectorApp.class,
dropwizardAppExtension = new DropwizardAppExtension<>(CustomConnectorClass,
CONFIG_PATH, newConfigOverrides);

try {
Expand All @@ -99,13 +109,15 @@ public AppWithPostgresAndSqsExtension(ConfigOverride... configOverrides) {
wireMockServer.start();
worldpayWireMockServer = new WireMockServer(wireMockConfig().port(worldpayWireMockPort));
worldpayWireMockServer.start();
stripeWireMockServer = new WireMockServer(wireMockConfig().port(stripeWireMockPort));
stripeWireMockServer.start();

databaseTestHelper = new DatabaseTestHelper(jdbi);

connectorRestApiClient = new RestAssuredClient(getLocalPort(), accountId);

worldpayMockClient = new WorldpayMockClient(worldpayWireMockServer);
stripeMockClient = new StripeMockClient(wireMockServer);
stripeMockClient = new StripeMockClient(stripeWireMockServer);

ledgerWireMockServer = new WireMockServer(wireMockConfig().port(ledgerWireMockPort));
ledgerWireMockServer.start();
Expand All @@ -120,6 +132,7 @@ public void resetWireMockServer() {
wireMockServer.resetAll();
worldpayWireMockServer.resetAll();
ledgerWireMockServer.resetAll();
stripeWireMockServer.resetAll();
ledgerStub.acceptPostEvent();
}

Expand Down Expand Up @@ -160,7 +173,7 @@ private ConfigOverride[] overrideEndpointConfig(ConfigOverride[] configOverrides
List<ConfigOverride> newConfigOverride = newArrayList(configOverrides);
newConfigOverride.add(config("worldpay.urls.test", "http://localhost:" + worldpayWireMockPort + "/jsp/merchant/xml/paymentService.jsp"));
newConfigOverride.add(config("worldpay.threeDsFlexDdcUrls.test", "http://localhost:" + worldpayWireMockPort + "/shopper/3ds/ddc.html"));
newConfigOverride.add(config("stripe.url", "http://localhost:" + wireMockPort));
newConfigOverride.add(config("stripe.url", "http://localhost:" + stripeWireMockPort));
newConfigOverride.add(config("ledgerBaseURL", "http://localhost:" + ledgerWireMockPort));
newConfigOverride.add(config("cardidBaseURL", "http://localhost:" + wireMockPort));
return newConfigOverride.toArray(new ConfigOverride[0]);
Expand Down Expand Up @@ -215,6 +228,10 @@ public AmazonSQS getSqsClient() {
public static WireMockServer getWireMockServer() {
return wireMockServer;
}

public static WireMockServer getStripeWireMockServer() {
return stripeWireMockServer;
}

public DatabaseTestHelper getDatabaseTestHelper() {
return databaseTestHelper;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,11 +123,21 @@ public ChargingITestBaseExtension(String paymentProvider) {
this.paymentProvider = paymentProvider;
}

public ChargingITestBaseExtension(String paymentProvider, Class CustomConnectorClass) {
super(CustomConnectorClass);
this.paymentProvider = paymentProvider;
}

public ChargingITestBaseExtension(String paymentProvider, ConfigOverride... configOverrides) {
super(configOverrides);
this.paymentProvider = paymentProvider;
}

public ChargingITestBaseExtension(String paymentProvider, Class CustomConnectorClass, ConfigOverride... configOverrides) {
super(CustomConnectorClass, configOverrides);
this.paymentProvider = paymentProvider;
}

private void setUpBase() {
resetDatabase(); // tests will break if setUpBase is called twice without this
if (paymentProvider.equals(STRIPE.getName())) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
package uk.gov.pay.connector.it.resources.stripe;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.stripe.exception.StripeException;
import com.stripe.model.Refund;
import io.dropwizard.setup.Environment;
import io.restassured.http.ContentType;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.RegisterExtension;
import uk.gov.pay.connector.app.ConnectorApp;
import uk.gov.pay.connector.app.ConnectorConfiguration;
import uk.gov.pay.connector.app.ConnectorModule;
Expand All @@ -21,144 +19,91 @@
import uk.gov.pay.connector.gateway.PaymentGatewayName;
import uk.gov.pay.connector.gateway.stripe.StripeSdkClient;
import uk.gov.pay.connector.gateway.stripe.StripeSdkClientFactory;
import uk.gov.pay.connector.junit.DropwizardConfig;
import uk.gov.pay.connector.junit.DropwizardJUnitRunner;
import uk.gov.pay.connector.junit.DropwizardTestContext;
import uk.gov.pay.connector.junit.TestContext;
import uk.gov.pay.connector.rules.LedgerStub;
import uk.gov.pay.connector.util.DatabaseTestHelper;

import uk.gov.pay.connector.it.base.ChargingITestBaseExtension;

import javax.ws.rs.core.Response;
import java.util.Map;


import static io.restassured.RestAssured.given;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static uk.gov.pay.connector.model.domain.LedgerTransactionFixture.aValidLedgerTransaction;
import static uk.gov.pay.connector.util.AddGatewayAccountParams.AddGatewayAccountParamsBuilder.anAddGatewayAccountParams;

// TODO implement overriding
@RunWith(DropwizardJUnitRunner.class)
@DropwizardConfig(app = RefundReversalResourceIT.ConnectorAppWithCustomInjector.class, config = "config/test-it-config.yaml")
public class RefundReversalResourceIT {


@DropwizardTestContext
protected TestContext testContext;
private static StripeSdkClientFactory mockStripeSdkClientFactory = mock(StripeSdkClientFactory.class);
private static StripeSdkClient mockStripeSdkClient = mock(StripeSdkClient.class);
private static final long GATEWAY_ACCOUNT_ID = 42;
private static final StripeSdkClientFactory mockStripeSdkClientFactory = mock(StripeSdkClientFactory.class);
private static final StripeSdkClient mockStripeSdkClient = mock(StripeSdkClient.class);

@RegisterExtension
public static ChargingITestBaseExtension app = new ChargingITestBaseExtension("stripe", RefundReversalResourceIT.ConnectorAppWithCustomInjector.class);
private static final String CHARGE_EXTERNAL_ID = "charge-external-id";
private static final String REFUND_EXTERNAL_ID = "refund-external-id";
private static final String STRIPE_REFUND_ID = "stripe-refund-id";


private final String accountId = String.valueOf(GATEWAY_ACCOUNT_ID);
private static DatabaseTestHelper databaseTestHelper;


private WireMockServer wireMockServer;
private LedgerStub ledgerStub;


private LedgerTransaction charge;
private LedgerTransaction refund;
private Refund mockStripeRefund = mock(Refund.class);
private final Refund mockStripeRefund = mock(Refund.class);


@BeforeClass
@BeforeAll
public static void before() {
when(mockStripeSdkClientFactory.getInstance()).thenReturn(mockStripeSdkClient);
}


@Before

@BeforeEach
public void setUp() {
databaseTestHelper = testContext.getDatabaseTestHelper();


databaseTestHelper.addGatewayAccount(anAddGatewayAccountParams()
.withAccountId(accountId)
.withPaymentGateway(PaymentGatewayName.STRIPE.getName())
.withCredentials(Map.of())
.build());


wireMockServer = testContext.getWireMockServer();


ledgerStub = new LedgerStub(wireMockServer);

charge = aValidLedgerTransaction()
.withExternalId(CHARGE_EXTERNAL_ID)
.withGatewayAccountId(GATEWAY_ACCOUNT_ID)
.withGatewayAccountId(Long.parseLong(app.getAccountId()))
.withAmount(1000L)
.withRefundSummary(new ChargeResponse.RefundSummary())
.withPaymentProvider(PaymentGatewayName.STRIPE.getName())
.build();


}

@After
public void tearDown() {
databaseTestHelper.truncateAllData();
}


@Test
public void shouldSuccessfullyGetRefundFromStripe() throws JsonProcessingException, StripeException {

refund = aValidLedgerTransaction()
.withExternalId(REFUND_EXTERNAL_ID)
.withGatewayAccountId(GATEWAY_ACCOUNT_ID)
.withGatewayAccountId(Long.parseLong(app.getAccountId()))
.withParentTransactionId(CHARGE_EXTERNAL_ID)
.withStatus(ExternalRefundStatus.EXTERNAL_SUCCESS.getStatus())
.withPaymentProvider(PaymentGatewayName.STRIPE.getName())
.withGatewayTransactionId(STRIPE_REFUND_ID)
.build();
}


ledgerStub.returnLedgerTransaction(CHARGE_EXTERNAL_ID, charge);
ledgerStub.returnLedgerTransaction(REFUND_EXTERNAL_ID, refund);
@Test
public void shouldSuccessfullyGetRefundFromStripe() throws JsonProcessingException, StripeException {
app.getLedgerStub().returnLedgerTransaction(CHARGE_EXTERNAL_ID, charge);
app.getLedgerStub().returnLedgerTransaction(REFUND_EXTERNAL_ID, refund);

when(mockStripeSdkClient.getRefund(eq(STRIPE_REFUND_ID), anyBoolean())).thenReturn(mockStripeRefund);


app.getStripeMockClient().mockRefund();
when(mockStripeRefund.getStatus()).thenReturn("failed");


given().port(testContext.getPort())

ValidatableResponse response = given().port(app.getLocalPort())
.accept(ContentType.JSON)
.contentType(ContentType.JSON)
.post("/v1/api/accounts/{gatewayAccountId}/charges/{chargeId}/refunds/{refundId}/reverse-failed"
.replace("{gatewayAccountId}", accountId)
.replace("{gatewayAccountId}", app.getAccountId())
.replace("{chargeId}", CHARGE_EXTERNAL_ID)
.replace("{refundId}", REFUND_EXTERNAL_ID))
.then()
.statusCode(Response.Status.OK.getStatusCode());
.then();
response.statusCode(Response.Status.OK.getStatusCode());
}


@Test
public void shouldReturnInternalErrorWhenRefundNotFoundFromStripe() throws JsonProcessingException, StripeException {


ledgerStub.returnLedgerTransaction(CHARGE_EXTERNAL_ID, charge);
ledgerStub.returnLedgerTransaction(REFUND_EXTERNAL_ID, refund);
app.getLedgerStub().returnLedgerTransaction(CHARGE_EXTERNAL_ID, charge);
app.getLedgerStub().returnLedgerTransaction(REFUND_EXTERNAL_ID, refund);

when(mockStripeSdkClient.getRefund(eq(STRIPE_REFUND_ID), anyBoolean())).thenReturn(null);
app.getStripeMockClient().mockRefund();


given().port(testContext.getPort())
given().port(app.getLocalPort())
.accept(ContentType.JSON)
.contentType(ContentType.JSON)
.post("/v1/api/accounts/{gatewayAccountId}/charges/{chargeId}/refunds/{refundId}/reverse-failed"
.replace("{gatewayAccountId}", accountId)
.replace("{gatewayAccountId}", app.getAccountId())
.replace("{chargeId}", CHARGE_EXTERNAL_ID)
.replace("{refundId}", REFUND_EXTERNAL_ID))
.then()
Expand All @@ -167,15 +112,12 @@ public void shouldReturnInternalErrorWhenRefundNotFoundFromStripe() throws JsonP


public static class ConnectorAppWithCustomInjector extends ConnectorApp {


@Override
protected ConnectorModule getModule(ConnectorConfiguration configuration, Environment environment) {
return new ConnectorModuleWithOverrides(configuration, environment);
}
}



private static class ConnectorModuleWithOverrides extends ConnectorModule {

public ConnectorModuleWithOverrides(ConnectorConfiguration configuration, Environment environment) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ void authoriseCharge() {
.body("status", is(AUTHORISATION_SUCCESS.toString()))
.statusCode(OK_200);

app.getWiremockserver().verify(postRequestedFor(urlEqualTo("/v1/payment_methods"))
app.getStripeWireMockServer().verify(postRequestedFor(urlEqualTo("/v1/payment_methods"))
.withHeader("Content-Type", equalTo(APPLICATION_FORM_URLENCODED)));

verifyPaymentMethodRequest();
Expand All @@ -191,10 +191,10 @@ void shouldAuthoriseChargeWithoutBillingAddress() {
.body("status", is(AUTHORISATION_SUCCESS.toString()))
.statusCode(OK_200);

app.getWiremockserver().verify(postRequestedFor(urlEqualTo("/v1/payment_methods"))
app.getStripeWireMockServer().verify(postRequestedFor(urlEqualTo("/v1/payment_methods"))
.withHeader("Content-Type", equalTo(APPLICATION_FORM_URLENCODED)));

app.getWiremockserver().verify(postRequestedFor(urlEqualTo("/v1/payment_intents"))
app.getStripeWireMockServer().verify(postRequestedFor(urlEqualTo("/v1/payment_intents"))
.withHeader("Content-Type", equalTo(APPLICATION_FORM_URLENCODED)));

}
Expand All @@ -219,7 +219,7 @@ void authoriseChargeToSetUpRecurringPaymentAgreement() throws Exception {
.statusCode(OK_200)
.body("status", is(AUTHORISATION_SUCCESS.toString()));

app.getWiremockserver().verify(postRequestedFor(urlEqualTo("/v1/payment_methods"))
app.getStripeWireMockServer().verify(postRequestedFor(urlEqualTo("/v1/payment_methods"))
.withHeader("Content-Type", equalTo(APPLICATION_FORM_URLENCODED)));

verifyPaymentMethodRequest();
Expand Down Expand Up @@ -515,15 +515,15 @@ private void assertFrontendChargeStatusIs(String chargeId, String status) {
}

private void verifyCustomerRequest() {
app.getWiremockserver().verify(postRequestedFor(urlEqualTo("/v1/customers"))
app.getStripeWireMockServer().verify(postRequestedFor(urlEqualTo("/v1/customers"))
.withHeader("Content-Type", equalTo(APPLICATION_FORM_URLENCODED))
.withHeader("Authorization", equalTo("Bearer sk_test"))
.withRequestBody(containing(queryParamWithValue("name", CARD_HOLDER_NAME)))
.withRequestBody(containing(queryParamWithValue("description", AGREEMENT_DESCRIPTION))));
}

private void verifyPaymentIntentRequest(String externalChargeId, String stripeAccountId) {
app.getWiremockserver().verify(postRequestedFor(urlEqualTo("/v1/payment_intents"))
app.getStripeWireMockServer().verify(postRequestedFor(urlEqualTo("/v1/payment_intents"))
.withHeader("Content-Type", equalTo(APPLICATION_FORM_URLENCODED))
.withHeader("Authorization", equalTo("Bearer sk_test"))
.withRequestBody(containing(queryParamWithValue("amount", "6234")))
Expand All @@ -541,7 +541,7 @@ private void verifyPaymentIntentRequest(String externalChargeId, String stripeAc
}

private void verifyPaymentMethodRequest() {
app.getWiremockserver().verify(postRequestedFor(urlEqualTo("/v1/payment_methods"))
app.getStripeWireMockServer().verify(postRequestedFor(urlEqualTo("/v1/payment_methods"))
.withHeader("Content-Type", equalTo(APPLICATION_FORM_URLENCODED))
.withHeader("Authorization", equalTo("Bearer sk_test"))
.withRequestBody(containing(queryParamWithValue("billing_details[name]", "Scrooge McDuck")))
Expand Down
Loading

0 comments on commit 91be65e

Please sign in to comment.