Skip to content

Commit

Permalink
[PHEE-296A] Email Api Tc
Browse files Browse the repository at this point in the history
  • Loading branch information
ankita10r committed Jun 12, 2024
1 parent abab0a9 commit f93df2b
Show file tree
Hide file tree
Showing 6 changed files with 201 additions and 0 deletions.
1 change: 1 addition & 0 deletions .jit/jit-integration.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ dependencies {
testImplementation 'org.apache.commons:commons-csv:1.5'
testImplementation 'org.awaitility:awaitility:4.2.0'
implementation 'commons-validator:commons-validator:1.7'
testImplementation 'com.icegreen:greenmail-junit5:1.6.1'
}

tasks.named('test') {
Expand Down
19 changes: 19 additions & 0 deletions src/main/resources/application.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -271,3 +271,22 @@ fspconfig:
payerfsp2: "gorilla"

totalvouchers: 30


messageGateway:
contactpoint: "https://messagegateway.sandbox.fynarfin.io"
endpoint:
email: "/emails"

spring:
mail:
host: ${MY_POD_IP:localhost}
port: 3025
username: greenmail
password: greenmail
properties:
mail:
smtp:
auth: false
starttls:
enable: false
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package org.mifos.integrationtest.common.dto;

import java.util.List;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class EmailRequestDTO {

private List<String> to;
private String subject;
private String body;

public EmailRequestDTO(List<String> to, String subject, String body) {
this.to = to;
this.subject = subject;
this.body = body;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
package org.mifos.integrationtest.cucumber.stepdef;

import static com.github.tomakehurst.wiremock.client.WireMock.getAllServeEvents;
import static com.google.common.truth.Truth.assertThat;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.awaitility.Awaitility.await;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.tomakehurst.wiremock.stubbing.ServeEvent;
import com.icegreen.greenmail.util.GreenMail;
import com.icegreen.greenmail.util.GreenMailUtil;
import com.icegreen.greenmail.util.ServerSetupTest;
import io.cucumber.core.internal.com.fasterxml.jackson.databind.JsonNode;
import io.cucumber.datatable.DataTable;
import io.cucumber.java.Before;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import io.restassured.RestAssured;
import io.restassured.builder.ResponseSpecBuilder;
import io.restassured.specification.RequestSpecification;

import java.io.IOException;
import java.util.List;
import java.util.Objects;
import org.mifos.integrationtest.common.Utils;
import org.mifos.integrationtest.common.dto.EmailRequestDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;

public class EmailStepDef extends BaseStepDef {

@Value("${callback_url}")
private String callbackURL;

@Value("${messageGateway.contactpoint}")
private String messageGatewayHost;

@Value("${messageGateway.endpoint.email}")
private String mgMail;
@Value("${spring.mail.host}")
private String smtpHost;

@Value("${spring.mail.port}")
private int smtpPort;

@Autowired
private Environment env;

private GreenMail greenMail;

@Before
public void setUp() {

int port = Integer.parseInt(Objects.requireNonNull(env.getProperty("spring.mail.port")));
greenMail = new GreenMail(ServerSetupTest.SMTP);
greenMail.setUser("greenmail", "greenmail");
greenMail.start();
}

@Given("the email service is running")
public void theEmailServiceIsRunning() {

}

@When("I send an email to the following recipients with subject {string} and body {string} with callbackurl as {string} and get {int}")
public void iSendAnEmailToWithSubjectAndBody(String subject, String body, String url, int expectedStatus, DataTable dataTable)
throws JsonProcessingException {
List<String> to = dataTable.asList(String.class);
EmailRequestDTO emailRequest = new EmailRequestDTO(to, subject, body);

// Convert the payload to JSON
ObjectMapper objectMapper = new ObjectMapper();
String jsonPayload = objectMapper.writeValueAsString(emailRequest);

// Get the default request specification
RequestSpecification requestSpec = Utils.getDefaultSpec();

// Send the POST request and get the response
scenarioScopeState.response = RestAssured.given(requestSpec).header("Content-Type", "application/json")
.header("X-CallbackUrl", callbackURL + url).header("Correlation-Id", scenarioScopeState.clientCorrelationId)
.header("Platform-Tenant-Id", scenarioScopeState.tenant).baseUri(messageGatewayHost).body(jsonPayload).expect()
.spec(new ResponseSpecBuilder().expectStatusCode(expectedStatus).build()).when().post(mgMail).andReturn().asString();

logger.info("Mail Response {}", scenarioScopeState.response);

}

@Then("the email should be sent to all recipients with subject {string} and body {string}")
public void theEmailShouldBeSentToWithSubjectAndBody(String subject, String body) throws Exception {
await().atMost(awaitMost, SECONDS).pollInterval(pollInterval, SECONDS).untilAsserted(() -> {
logger.info(String.valueOf(greenMail.getReceivedMessages().length));
assertThat(greenMail.getReceivedMessages().length == 1).isTrue();

String receivedTo = GreenMailUtil.getAddressList(greenMail.getReceivedMessages()[0].getAllRecipients());
String receivedSubject = greenMail.getReceivedMessages()[0].getSubject();
String receivedBody = GreenMailUtil.getBody(greenMail.getReceivedMessages()[0]);

assertThat(receivedTo).isNotNull();
assertThat(subject.equals(receivedSubject)).isTrue();
assertThat(body.equals(receivedBody)).isTrue();
});
}
@Then("I should be able to extract error from response")
public void iShouldBeAbleToExtractErrorFromResponse() {
assertThat(scenarioScopeState.response).isNotNull();
assertThat(scenarioScopeState.response).containsMatch("Bad Request");
}

@And("I can verify callback recieved with value")
public void iCanVerifyCallbackRecievedWithValue() {
await().atMost(awaitMost, SECONDS).pollInterval(pollInterval, SECONDS).untilAsserted(() -> {
boolean flag = false;
List<ServeEvent> allServeEvents = getAllServeEvents();
for (int i = allServeEvents.size() - 1; i >= 0; i--) {
ServeEvent request = allServeEvents.get(i);
if (!(request.getRequest().getBodyAsString()).isEmpty() && request.getRequest().getUrl().equals("/sendMail")) {
JsonNode rootNode = null;
try {
rootNode = objectMapper.readTree(request.getRequest().getBody());
logger.info("Rootnode value:" + rootNode);
assertThat(rootNode.toString().contains("Email sent successfully"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

});
}
}
26 changes: 26 additions & 0 deletions src/test/java/resources/email.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
Feature: Send Email

@gov
Scenario: Sending an email to the recipient with success
Given I can inject MockServer
And I can start mock server
And I can register the stub with "/sendMail" endpoint for "POST" request with status of 200
And the email service is running
And I have tenant as "paymentBB2"
And I generate clientCorrelationId
When I send an email to the following recipients with subject "Test Email" and body "This is a test email" with callbackurl as "/sendMail" and get 202
| recipient1@example.com |
And I can verify callback recieved with value
Then the email should be sent to all recipients with subject "Test Email" and body "This is a test email"

@gov
Scenario: Sending an email to the recipient
Given I can inject MockServer
And I can start mock server
And I can register the stub with "/sendMail" endpoint for "POST" request with status of 200
And the email service is running
And I have tenant as "paymentBB2"
And I generate clientCorrelationId
When I send an email to the following recipients with subject "" and body "This is a test email" with callbackurl as "/sendMail" and get 400
| recipient1@example.com |
Then I should be able to extract error from response

0 comments on commit f93df2b

Please sign in to comment.