mirror of
https://github.com/google/nomulus.git
synced 2025-08-05 09:21:49 +02:00
Refactor common email sending utility
The main thrust of this is to create a common POJO that contains email content in a simple way, then have one class that converts that to an email and sends it. Any class that uses email should only have to deal with creating that POJO. ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=237883643
This commit is contained in:
parent
9823ee7fcf
commit
50e0a9b532
35 changed files with 773 additions and 614 deletions
|
@ -15,132 +15,94 @@
|
|||
package google.registry.reporting.billing;
|
||||
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static com.google.common.truth.Truth.assertWithMessage;
|
||||
import static com.google.common.truth.Truth8.assertThat;
|
||||
import static google.registry.testing.JUnitBackports.assertThrows;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.appengine.tools.cloudstorage.GcsFilename;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.net.MediaType;
|
||||
import google.registry.gcs.GcsUtils;
|
||||
import google.registry.testing.FakeClock;
|
||||
import google.registry.testing.FakeSleeper;
|
||||
import google.registry.util.Retrier;
|
||||
import google.registry.util.EmailMessage;
|
||||
import google.registry.util.EmailMessage.Attachment;
|
||||
import google.registry.util.SendEmailService;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Properties;
|
||||
import javax.mail.BodyPart;
|
||||
import javax.mail.Message;
|
||||
import javax.mail.MessagingException;
|
||||
import javax.mail.Multipart;
|
||||
import javax.mail.Session;
|
||||
import javax.mail.internet.InternetAddress;
|
||||
import javax.mail.internet.MimeMessage;
|
||||
import org.joda.time.YearMonth;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
/** Unit tests for {@link google.registry.reporting.billing.BillingEmailUtils}. */
|
||||
@RunWith(JUnit4.class)
|
||||
public class BillingEmailUtilsTest {
|
||||
|
||||
private static final int RETRY_COUNT = 2;
|
||||
|
||||
private SendEmailService emailService;
|
||||
private BillingEmailUtils emailUtils;
|
||||
private GcsUtils gcsUtils;
|
||||
private ArgumentCaptor<Message> msgCaptor;
|
||||
private ArgumentCaptor<EmailMessage> contentCaptor;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
public void setUp() throws Exception {
|
||||
emailService = mock(SendEmailService.class);
|
||||
when(emailService.createMessage())
|
||||
.thenReturn(new MimeMessage(Session.getDefaultInstance(new Properties(), null)));
|
||||
gcsUtils = mock(GcsUtils.class);
|
||||
when(gcsUtils.openInputStream(new GcsFilename("test-bucket", "results/REG-INV-2017-10.csv")))
|
||||
.thenReturn(
|
||||
new ByteArrayInputStream("test,data\nhello,world".getBytes(StandardCharsets.UTF_8)));
|
||||
msgCaptor = ArgumentCaptor.forClass(Message.class);
|
||||
contentCaptor = ArgumentCaptor.forClass(EmailMessage.class);
|
||||
|
||||
emailUtils =
|
||||
new BillingEmailUtils(
|
||||
emailService,
|
||||
new YearMonth(2017, 10),
|
||||
"my-sender@test.com",
|
||||
"my-receiver@test.com",
|
||||
ImmutableList.of("hello@world.com", "hola@mundo.com"),
|
||||
new InternetAddress("my-sender@test.com"),
|
||||
new InternetAddress("my-receiver@test.com"),
|
||||
ImmutableList.of(
|
||||
new InternetAddress("hello@world.com"), new InternetAddress("hola@mundo.com")),
|
||||
"test-bucket",
|
||||
"REG-INV",
|
||||
"results/",
|
||||
gcsUtils,
|
||||
new Retrier(new FakeSleeper(new FakeClock()), RETRY_COUNT));
|
||||
gcsUtils);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSuccess_emailOverallInvoice() throws MessagingException, IOException {
|
||||
public void testSuccess_emailOverallInvoice() throws MessagingException {
|
||||
emailUtils.emailOverallInvoice();
|
||||
// We inspect individual parameters because Message doesn't implement equals().
|
||||
verify(emailService).sendMessage(msgCaptor.capture());
|
||||
Message expectedMsg = msgCaptor.getValue();
|
||||
assertThat(expectedMsg.getFrom())
|
||||
.asList()
|
||||
.containsExactly(new InternetAddress("my-sender@test.com"));
|
||||
assertThat(expectedMsg.getAllRecipients())
|
||||
.asList()
|
||||
.containsExactly(
|
||||
new InternetAddress("hello@world.com"), new InternetAddress("hola@mundo.com"));
|
||||
assertThat(expectedMsg.getSubject()).isEqualTo("Domain Registry invoice data 2017-10");
|
||||
assertThat(expectedMsg.getContent()).isInstanceOf(Multipart.class);
|
||||
Multipart contents = (Multipart) expectedMsg.getContent();
|
||||
assertThat(contents.getCount()).isEqualTo(2);
|
||||
assertThat(contents.getBodyPart(0)).isInstanceOf(BodyPart.class);
|
||||
BodyPart textPart = contents.getBodyPart(0);
|
||||
assertThat(textPart.getContentType()).isEqualTo("text/plain; charset=us-ascii");
|
||||
assertThat(textPart.getContent().toString())
|
||||
.isEqualTo("Attached is the 2017-10 invoice for the domain registry.");
|
||||
assertThat(contents.getBodyPart(1)).isInstanceOf(BodyPart.class);
|
||||
BodyPart attachmentPart = contents.getBodyPart(1);
|
||||
assertThat(attachmentPart.getContentType()).endsWith("name=REG-INV-2017-10.csv");
|
||||
assertThat(attachmentPart.getContent().toString()).isEqualTo("test,data\nhello,world");
|
||||
|
||||
verify(emailService).sendEmail(contentCaptor.capture());
|
||||
EmailMessage emailMessage = contentCaptor.getValue();
|
||||
EmailMessage expectedContent =
|
||||
EmailMessage.newBuilder()
|
||||
.setFrom(new InternetAddress("my-sender@test.com"))
|
||||
.setRecipients(
|
||||
ImmutableList.of(
|
||||
new InternetAddress("hello@world.com"), new InternetAddress("hola@mundo.com")))
|
||||
.setSubject("Domain Registry invoice data 2017-10")
|
||||
.setBody("Attached is the 2017-10 invoice for the domain registry.")
|
||||
.setAttachment(
|
||||
Attachment.newBuilder()
|
||||
.setContent("test,data\nhello,world")
|
||||
.setContentType(MediaType.CSV_UTF_8)
|
||||
.setFilename("REG-INV-2017-10.csv")
|
||||
.build())
|
||||
.build();
|
||||
assertThat(emailMessage).isEqualTo(expectedContent);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFailure_tooManyRetries_emailsAlert() throws MessagingException, IOException {
|
||||
// This message throws whenever it tries to set content, to force the overall invoice to fail.
|
||||
Message throwingMessage = mock(Message.class);
|
||||
doThrow(new MessagingException("expected"))
|
||||
.when(throwingMessage)
|
||||
.setContent(any(Multipart.class));
|
||||
when(emailService.createMessage()).thenAnswer(
|
||||
new Answer<Message>() {
|
||||
private int count = 0;
|
||||
|
||||
@Override
|
||||
public Message answer(InvocationOnMock invocation) {
|
||||
// Once we've failed the retry limit for the original invoice, return a normal message
|
||||
// so we can properly check its contents.
|
||||
if (count < RETRY_COUNT) {
|
||||
count++;
|
||||
return throwingMessage;
|
||||
} else if (count == RETRY_COUNT) {
|
||||
return new MimeMessage(Session.getDefaultInstance(new Properties(), null));
|
||||
} else {
|
||||
assertWithMessage("Attempted to generate too many messages!").fail();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
public void testFailure_emailsAlert() throws MessagingException {
|
||||
doThrow(new RuntimeException(new MessagingException("expected")))
|
||||
.doNothing()
|
||||
.when(emailService)
|
||||
.sendEmail(contentCaptor.capture());
|
||||
RuntimeException thrown =
|
||||
assertThrows(RuntimeException.class, () -> emailUtils.emailOverallInvoice());
|
||||
assertThat(thrown).hasMessageThat().isEqualTo("Emailing invoice failed");
|
||||
|
@ -149,26 +111,24 @@ public class BillingEmailUtilsTest {
|
|||
.hasMessageThat()
|
||||
.isEqualTo("javax.mail.MessagingException: expected");
|
||||
// Verify we sent an e-mail alert
|
||||
verify(emailService).sendMessage(msgCaptor.capture());
|
||||
validateAlertMessage(msgCaptor.getValue(), "Emailing invoice failed due to expected");
|
||||
verify(emailService, times(2)).sendEmail(contentCaptor.capture());
|
||||
validateAlertMessage(contentCaptor.getValue(), "Emailing invoice failed due to expected");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSuccess_sendAlertEmail() throws MessagingException, IOException {
|
||||
public void testSuccess_sendAlertEmail() throws MessagingException {
|
||||
emailUtils.sendAlertEmail("Alert!");
|
||||
verify(emailService).sendMessage(msgCaptor.capture());
|
||||
validateAlertMessage(msgCaptor.getValue(), "Alert!");
|
||||
verify(emailService).sendEmail(contentCaptor.capture());
|
||||
validateAlertMessage(contentCaptor.getValue(), "Alert!");
|
||||
}
|
||||
|
||||
private void validateAlertMessage(Message msg, String body)
|
||||
throws MessagingException, IOException {
|
||||
assertThat(msg.getFrom()).hasLength(1);
|
||||
assertThat(msg.getFrom()[0]).isEqualTo(new InternetAddress("my-sender@test.com"));
|
||||
assertThat(msg.getAllRecipients())
|
||||
.asList()
|
||||
private void validateAlertMessage(EmailMessage emailMessage, String body)
|
||||
throws MessagingException {
|
||||
assertThat(emailMessage.from()).isEqualTo(new InternetAddress("my-sender@test.com"));
|
||||
assertThat(emailMessage.recipients())
|
||||
.containsExactly(new InternetAddress("my-receiver@test.com"));
|
||||
assertThat(msg.getSubject()).isEqualTo("Billing Pipeline Alert: 2017-10");
|
||||
assertThat(msg.getContentType()).isEqualTo("text/plain");
|
||||
assertThat(msg.getContent().toString()).isEqualTo(body);
|
||||
assertThat(emailMessage.subject()).isEqualTo("Billing Pipeline Alert: 2017-10");
|
||||
assertThat(emailMessage.contentType()).isEmpty();
|
||||
assertThat(emailMessage.body()).isEqualTo(body);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -33,8 +33,11 @@ import google.registry.testing.FakeClock;
|
|||
import google.registry.testing.FakeResponse;
|
||||
import google.registry.testing.FakeSleeper;
|
||||
import google.registry.testing.TaskQueueHelper.TaskMatcher;
|
||||
import google.registry.util.EmailMessage;
|
||||
import google.registry.util.Retrier;
|
||||
import google.registry.util.SendEmailService;
|
||||
import java.util.Optional;
|
||||
import javax.mail.internet.InternetAddress;
|
||||
import org.joda.time.YearMonth;
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
|
@ -48,7 +51,6 @@ public class IcannReportingStagingActionTest {
|
|||
|
||||
FakeResponse response = new FakeResponse();
|
||||
IcannReportingStager stager = mock(IcannReportingStager.class);
|
||||
ReportingEmailUtils emailUtils = mock(ReportingEmailUtils.class);
|
||||
YearMonth yearMonth = new YearMonth(2017, 6);
|
||||
String subdir = "default/dir";
|
||||
IcannReportingStagingAction action;
|
||||
|
@ -69,7 +71,9 @@ public class IcannReportingStagingActionTest {
|
|||
action.response = response;
|
||||
action.stager = stager;
|
||||
action.retrier = new Retrier(new FakeSleeper(new FakeClock()), 3);
|
||||
action.emailUtils = emailUtils;
|
||||
action.sender = new InternetAddress("sender@example.com");
|
||||
action.recipient = new InternetAddress("recipient@example.com");
|
||||
action.emailService = mock(SendEmailService.class);
|
||||
|
||||
when(stager.stageReports(yearMonth, subdir, ReportType.ACTIVITY))
|
||||
.thenReturn(ImmutableList.of("a", "b"));
|
||||
|
@ -92,10 +96,13 @@ public class IcannReportingStagingActionTest {
|
|||
action.run();
|
||||
verify(stager).stageReports(yearMonth, subdir, ReportType.ACTIVITY);
|
||||
verify(stager).createAndUploadManifest(subdir, ImmutableList.of("a", "b"));
|
||||
verify(emailUtils)
|
||||
.emailResults(
|
||||
"ICANN Monthly report staging summary [SUCCESS]",
|
||||
"Completed staging the following 2 ICANN reports:\na\nb");
|
||||
verify(action.emailService)
|
||||
.sendEmail(
|
||||
EmailMessage.create(
|
||||
"ICANN Monthly report staging summary [SUCCESS]",
|
||||
"Completed staging the following 2 ICANN reports:\na\nb",
|
||||
new InternetAddress("recipient@example.com"),
|
||||
new InternetAddress("sender@example.com")));
|
||||
assertUploadTaskEnqueued("default/dir");
|
||||
}
|
||||
|
||||
|
@ -105,10 +112,13 @@ public class IcannReportingStagingActionTest {
|
|||
verify(stager).stageReports(yearMonth, subdir, ReportType.ACTIVITY);
|
||||
verify(stager).stageReports(yearMonth, subdir, ReportType.TRANSACTIONS);
|
||||
verify(stager).createAndUploadManifest(subdir, ImmutableList.of("a", "b", "c", "d"));
|
||||
verify(emailUtils)
|
||||
.emailResults(
|
||||
"ICANN Monthly report staging summary [SUCCESS]",
|
||||
"Completed staging the following 4 ICANN reports:\na\nb\nc\nd");
|
||||
verify(action.emailService)
|
||||
.sendEmail(
|
||||
EmailMessage.create(
|
||||
"ICANN Monthly report staging summary [SUCCESS]",
|
||||
"Completed staging the following 4 ICANN reports:\na\nb\nc\nd",
|
||||
new InternetAddress("recipient@example.com"),
|
||||
new InternetAddress("sender@example.com")));
|
||||
assertUploadTaskEnqueued("default/dir");
|
||||
}
|
||||
|
||||
|
@ -121,10 +131,13 @@ public class IcannReportingStagingActionTest {
|
|||
verify(stager, times(2)).stageReports(yearMonth, subdir, ReportType.ACTIVITY);
|
||||
verify(stager, times(2)).stageReports(yearMonth, subdir, ReportType.TRANSACTIONS);
|
||||
verify(stager).createAndUploadManifest(subdir, ImmutableList.of("a", "b", "c", "d"));
|
||||
verify(emailUtils)
|
||||
.emailResults(
|
||||
"ICANN Monthly report staging summary [SUCCESS]",
|
||||
"Completed staging the following 4 ICANN reports:\na\nb\nc\nd");
|
||||
verify(action.emailService)
|
||||
.sendEmail(
|
||||
EmailMessage.create(
|
||||
"ICANN Monthly report staging summary [SUCCESS]",
|
||||
"Completed staging the following 4 ICANN reports:\na\nb\nc\nd",
|
||||
new InternetAddress("recipient@example.com"),
|
||||
new InternetAddress("sender@example.com")));
|
||||
assertUploadTaskEnqueued("default/dir");
|
||||
}
|
||||
|
||||
|
@ -138,11 +151,14 @@ public class IcannReportingStagingActionTest {
|
|||
assertThat(thrown).hasMessageThat().isEqualTo("Staging action failed.");
|
||||
assertThat(thrown).hasCauseThat().hasMessageThat().isEqualTo("Expected failure");
|
||||
verify(stager, times(3)).stageReports(yearMonth, subdir, ReportType.ACTIVITY);
|
||||
verify(emailUtils)
|
||||
.emailResults(
|
||||
"ICANN Monthly report staging summary [FAILURE]",
|
||||
"Staging failed due to BigqueryJobFailureException: Expected failure,"
|
||||
+ " check logs for more details.");
|
||||
verify(action.emailService)
|
||||
.sendEmail(
|
||||
EmailMessage.create(
|
||||
"ICANN Monthly report staging summary [FAILURE]",
|
||||
"Staging failed due to BigqueryJobFailureException: Expected failure,"
|
||||
+ " check logs for more details.",
|
||||
new InternetAddress("recipient@example.com"),
|
||||
new InternetAddress("sender@example.com")));
|
||||
// Assert no upload task enqueued
|
||||
assertNoTasksEnqueued("retryable-cron-tasks");
|
||||
}
|
||||
|
|
|
@ -32,8 +32,11 @@ import google.registry.testing.AppEngineRule;
|
|||
import google.registry.testing.FakeClock;
|
||||
import google.registry.testing.FakeResponse;
|
||||
import google.registry.testing.FakeSleeper;
|
||||
import google.registry.util.EmailMessage;
|
||||
import google.registry.util.Retrier;
|
||||
import google.registry.util.SendEmailService;
|
||||
import java.io.IOException;
|
||||
import javax.mail.internet.InternetAddress;
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
|
@ -51,18 +54,20 @@ public class IcannReportingUploadActionTest {
|
|||
private static final byte[] MANIFEST_PAYLOAD =
|
||||
"test-transactions-201706.csv\na-activity-201706.csv\n".getBytes(UTF_8);
|
||||
private final IcannHttpReporter mockReporter = mock(IcannHttpReporter.class);
|
||||
private final ReportingEmailUtils emailUtils = mock(ReportingEmailUtils.class);
|
||||
private final SendEmailService emailService = mock(SendEmailService.class);
|
||||
private final FakeResponse response = new FakeResponse();
|
||||
private final GcsService gcsService = GcsServiceFactory.createGcsService();
|
||||
|
||||
private IcannReportingUploadAction createAction() {
|
||||
private IcannReportingUploadAction createAction() throws Exception {
|
||||
IcannReportingUploadAction action = new IcannReportingUploadAction();
|
||||
action.icannReporter = mockReporter;
|
||||
action.gcsUtils = new GcsUtils(gcsService, 1024);
|
||||
action.retrier = new Retrier(new FakeSleeper(new FakeClock()), 3);
|
||||
action.subdir = "icann/monthly/2017-06";
|
||||
action.reportingBucket = "basin";
|
||||
action.emailUtils = emailUtils;
|
||||
action.emailService = emailService;
|
||||
action.sender = new InternetAddress("sender@example.com");
|
||||
action.recipient = new InternetAddress("recipient@example.com");
|
||||
action.response = response;
|
||||
return action;
|
||||
}
|
||||
|
@ -94,12 +99,15 @@ public class IcannReportingUploadActionTest {
|
|||
verifyNoMoreInteractions(mockReporter);
|
||||
assertThat(((FakeResponse) action.response).getPayload())
|
||||
.isEqualTo("OK, attempted uploading 2 reports");
|
||||
verify(emailUtils)
|
||||
.emailResults(
|
||||
"ICANN Monthly report upload summary: 1/2 succeeded",
|
||||
"Report Filename - Upload status:\n"
|
||||
+ "test-transactions-201706.csv - SUCCESS\n"
|
||||
+ "a-activity-201706.csv - FAILURE");
|
||||
verify(emailService)
|
||||
.sendEmail(
|
||||
EmailMessage.create(
|
||||
"ICANN Monthly report upload summary: 1/2 succeeded",
|
||||
"Report Filename - Upload status:\n"
|
||||
+ "test-transactions-201706.csv - SUCCESS\n"
|
||||
+ "a-activity-201706.csv - FAILURE",
|
||||
new InternetAddress("recipient@example.com"),
|
||||
new InternetAddress("sender@example.com")));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -114,12 +122,15 @@ public class IcannReportingUploadActionTest {
|
|||
verifyNoMoreInteractions(mockReporter);
|
||||
assertThat(((FakeResponse) action.response).getPayload())
|
||||
.isEqualTo("OK, attempted uploading 2 reports");
|
||||
verify(emailUtils)
|
||||
.emailResults(
|
||||
"ICANN Monthly report upload summary: 1/2 succeeded",
|
||||
"Report Filename - Upload status:\n"
|
||||
+ "test-transactions-201706.csv - SUCCESS\n"
|
||||
+ "a-activity-201706.csv - FAILURE");
|
||||
verify(emailService)
|
||||
.sendEmail(
|
||||
EmailMessage.create(
|
||||
"ICANN Monthly report upload summary: 1/2 succeeded",
|
||||
"Report Filename - Upload status:\n"
|
||||
+ "test-transactions-201706.csv - SUCCESS\n"
|
||||
+ "a-activity-201706.csv - FAILURE",
|
||||
new InternetAddress("recipient@example.com"),
|
||||
new InternetAddress("sender@example.com")));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -133,15 +144,18 @@ public class IcannReportingUploadActionTest {
|
|||
verifyNoMoreInteractions(mockReporter);
|
||||
assertThat(((FakeResponse) action.response).getPayload())
|
||||
.isEqualTo("OK, attempted uploading 2 reports");
|
||||
verify(emailUtils)
|
||||
.emailResults(
|
||||
"ICANN Monthly report upload summary: 0/2 succeeded",
|
||||
"Report Filename - Upload status:\n"
|
||||
+ "test-transactions-201706.csv - FAILURE\n"
|
||||
+ "a-activity-201706.csv - FAILURE");
|
||||
verify(emailService)
|
||||
.sendEmail(
|
||||
EmailMessage.create(
|
||||
"ICANN Monthly report upload summary: 0/2 succeeded",
|
||||
"Report Filename - Upload status:\n"
|
||||
+ "test-transactions-201706.csv - FAILURE\n"
|
||||
+ "a-activity-201706.csv - FAILURE",
|
||||
new InternetAddress("recipient@example.com"),
|
||||
new InternetAddress("sender@example.com")));
|
||||
}
|
||||
@Test
|
||||
public void testFail_FileNotFound() {
|
||||
public void testFail_FileNotFound() throws Exception {
|
||||
IcannReportingUploadAction action = createAction();
|
||||
action.subdir = "somewhere/else";
|
||||
IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, action::run);
|
||||
|
|
|
@ -1,68 +0,0 @@
|
|||
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package google.registry.reporting.icann;
|
||||
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import google.registry.util.SendEmailService;
|
||||
import java.util.Properties;
|
||||
import javax.mail.Message;
|
||||
import javax.mail.Message.RecipientType;
|
||||
import javax.mail.Session;
|
||||
import javax.mail.internet.InternetAddress;
|
||||
import javax.mail.internet.MimeMessage;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
/** Unit tests for {@link google.registry.reporting.icann.ReportingEmailUtils}. */
|
||||
@RunWith(JUnit4.class)
|
||||
public class ReportingEmailUtilsTest {
|
||||
private Message msg;
|
||||
private final SendEmailService emailService = mock(SendEmailService.class);
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
msg = new MimeMessage(Session.getDefaultInstance(new Properties(), null));
|
||||
when(emailService.createMessage()).thenReturn(msg);
|
||||
}
|
||||
|
||||
private ReportingEmailUtils createEmailUtil() {
|
||||
ReportingEmailUtils emailUtils = new ReportingEmailUtils();
|
||||
emailUtils.sender = "test-project.appspotmail.com";
|
||||
emailUtils.recipient = "email@example.com";
|
||||
emailUtils.emailService = emailService;
|
||||
return emailUtils;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSuccess_sendsEmail() throws Exception {
|
||||
ReportingEmailUtils emailUtils = createEmailUtil();
|
||||
emailUtils.emailResults("Subject", "Body");
|
||||
|
||||
assertThat(msg.getFrom()).hasLength(1);
|
||||
assertThat(msg.getFrom()[0])
|
||||
.isEqualTo(new InternetAddress("test-project.appspotmail.com"));
|
||||
assertThat(msg.getRecipients(RecipientType.TO)).hasLength(1);
|
||||
assertThat(msg.getRecipients(RecipientType.TO)[0])
|
||||
.isEqualTo(new InternetAddress("email@example.com"));
|
||||
assertThat(msg.getSubject()).isEqualTo("Subject");
|
||||
assertThat(msg.getContentType()).isEqualTo("text/plain");
|
||||
assertThat(msg.getContent().toString()).isEqualTo("Body");
|
||||
}
|
||||
}
|
|
@ -15,10 +15,8 @@
|
|||
package google.registry.reporting.spec11;
|
||||
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static com.google.common.truth.Truth.assertWithMessage;
|
||||
import static google.registry.reporting.spec11.Spec11RegistrarThreatMatchesParserTest.sampleThreatMatches;
|
||||
import static google.registry.testing.JUnitBackports.assertThrows;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
|
@ -26,63 +24,47 @@ import static org.mockito.Mockito.verify;
|
|||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.net.MediaType;
|
||||
import google.registry.reporting.spec11.soy.Spec11EmailSoyInfo;
|
||||
import google.registry.testing.FakeClock;
|
||||
import google.registry.testing.FakeSleeper;
|
||||
import google.registry.util.Retrier;
|
||||
import google.registry.util.EmailMessage;
|
||||
import google.registry.util.SendEmailService;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.mail.Message;
|
||||
import javax.mail.Message.RecipientType;
|
||||
import java.util.Optional;
|
||||
import javax.mail.MessagingException;
|
||||
import javax.mail.Session;
|
||||
import javax.mail.internet.InternetAddress;
|
||||
import javax.mail.internet.MimeMessage;
|
||||
import org.joda.time.LocalDate;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
/** Unit tests for {@link Spec11EmailUtils}. */
|
||||
@RunWith(JUnit4.class)
|
||||
public class Spec11EmailUtilsTest {
|
||||
|
||||
private static final int RETRY_COUNT = 2;
|
||||
private static final ImmutableList<String> FAKE_RESOURCES = ImmutableList.of("foo");
|
||||
|
||||
private SendEmailService emailService;
|
||||
private Spec11EmailUtils emailUtils;
|
||||
private Spec11RegistrarThreatMatchesParser parser;
|
||||
private ArgumentCaptor<Message> gotMessage;
|
||||
private ArgumentCaptor<EmailMessage> contentCaptor;
|
||||
private final LocalDate date = new LocalDate(2018, 7, 15);
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
emailService = mock(SendEmailService.class);
|
||||
when(emailService.createMessage())
|
||||
.thenAnswer((args) -> new MimeMessage(Session.getInstance(new Properties(), null)));
|
||||
|
||||
parser = mock(Spec11RegistrarThreatMatchesParser.class);
|
||||
when(parser.getRegistrarThreatMatches(date)).thenReturn(sampleThreatMatches());
|
||||
|
||||
gotMessage = ArgumentCaptor.forClass(Message.class);
|
||||
|
||||
contentCaptor = ArgumentCaptor.forClass(EmailMessage.class);
|
||||
emailUtils =
|
||||
new Spec11EmailUtils(
|
||||
emailService,
|
||||
"my-sender@test.com",
|
||||
"my-receiver@test.com",
|
||||
"my-reply-to@test.com",
|
||||
new InternetAddress("my-sender@test.com"),
|
||||
new InternetAddress("my-receiver@test.com"),
|
||||
new InternetAddress("my-reply-to@test.com"),
|
||||
FAKE_RESOURCES,
|
||||
"Super Cool Registry",
|
||||
new Retrier(new FakeSleeper(new FakeClock()), RETRY_COUNT));
|
||||
"Super Cool Registry");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -93,8 +75,8 @@ public class Spec11EmailUtilsTest {
|
|||
"Super Cool Registry Monthly Threat Detector [2018-07-15]",
|
||||
sampleThreatMatches());
|
||||
// We inspect individual parameters because Message doesn't implement equals().
|
||||
verify(emailService, times(3)).sendMessage(gotMessage.capture());
|
||||
List<Message> capturedMessages = gotMessage.getAllValues();
|
||||
verify(emailService, times(3)).sendEmail(contentCaptor.capture());
|
||||
List<EmailMessage> capturedContents = contentCaptor.getAllValues();
|
||||
String emailFormat =
|
||||
"Dear registrar partner,<p>Super Cool Registry previously notified you when the following "
|
||||
+ "domains managed by your registrar were flagged for potential security concerns."
|
||||
|
@ -113,31 +95,31 @@ public class Spec11EmailUtilsTest {
|
|||
+ "uestions regarding this notice, please contact my-reply-to@test.com.</p>";
|
||||
|
||||
validateMessage(
|
||||
capturedMessages.get(0),
|
||||
capturedContents.get(0),
|
||||
"my-sender@test.com",
|
||||
"a@fake.com",
|
||||
"my-reply-to@test.com",
|
||||
Optional.of("my-reply-to@test.com"),
|
||||
"Super Cool Registry Monthly Threat Detector [2018-07-15]",
|
||||
String.format(emailFormat, "<tr><td>a.com</td><td>MALWARE</td></tr>"),
|
||||
"text/html");
|
||||
Optional.of(MediaType.HTML_UTF_8));
|
||||
validateMessage(
|
||||
capturedMessages.get(1),
|
||||
capturedContents.get(1),
|
||||
"my-sender@test.com",
|
||||
"b@fake.com",
|
||||
"my-reply-to@test.com",
|
||||
Optional.of("my-reply-to@test.com"),
|
||||
"Super Cool Registry Monthly Threat Detector [2018-07-15]",
|
||||
String.format(
|
||||
emailFormat,
|
||||
"<tr><td>b.com</td><td>MALWARE</td></tr><tr><td>c.com</td><td>MALWARE</td></tr>"),
|
||||
"text/html");
|
||||
Optional.of(MediaType.HTML_UTF_8));
|
||||
validateMessage(
|
||||
capturedMessages.get(2),
|
||||
capturedContents.get(2),
|
||||
"my-sender@test.com",
|
||||
"my-receiver@test.com",
|
||||
null,
|
||||
Optional.empty(),
|
||||
"Spec11 Pipeline Success 2018-07-15",
|
||||
"Spec11 reporting completed successfully.",
|
||||
"text/plain");
|
||||
Optional.empty());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -148,8 +130,8 @@ public class Spec11EmailUtilsTest {
|
|||
"Super Cool Registry Daily Threat Detector [2018-07-15]",
|
||||
sampleThreatMatches());
|
||||
// We inspect individual parameters because Message doesn't implement equals().
|
||||
verify(emailService, times(3)).sendMessage(gotMessage.capture());
|
||||
List<Message> capturedMessages = gotMessage.getAllValues();
|
||||
verify(emailService, times(3)).sendEmail(contentCaptor.capture());
|
||||
List<EmailMessage> capturedMessages = contentCaptor.getAllValues();
|
||||
String emailFormat =
|
||||
"Dear registrar partner,<p>"
|
||||
+ "Super Cool Registry conducts a daily analysis of all domains registered in its TLDs "
|
||||
|
@ -172,54 +154,36 @@ public class Spec11EmailUtilsTest {
|
|||
capturedMessages.get(0),
|
||||
"my-sender@test.com",
|
||||
"a@fake.com",
|
||||
"my-reply-to@test.com",
|
||||
Optional.of("my-reply-to@test.com"),
|
||||
"Super Cool Registry Daily Threat Detector [2018-07-15]",
|
||||
String.format(emailFormat, "<tr><td>a.com</td><td>MALWARE</td></tr>"),
|
||||
"text/html");
|
||||
Optional.of(MediaType.HTML_UTF_8));
|
||||
validateMessage(
|
||||
capturedMessages.get(1),
|
||||
"my-sender@test.com",
|
||||
"b@fake.com",
|
||||
"my-reply-to@test.com",
|
||||
Optional.of("my-reply-to@test.com"),
|
||||
"Super Cool Registry Daily Threat Detector [2018-07-15]",
|
||||
String.format(
|
||||
emailFormat,
|
||||
"<tr><td>b.com</td><td>MALWARE</td></tr><tr><td>c.com</td><td>MALWARE</td></tr>"),
|
||||
"text/html");
|
||||
Optional.of(MediaType.HTML_UTF_8));
|
||||
validateMessage(
|
||||
capturedMessages.get(2),
|
||||
"my-sender@test.com",
|
||||
"my-receiver@test.com",
|
||||
null,
|
||||
Optional.empty(),
|
||||
"Spec11 Pipeline Success 2018-07-15",
|
||||
"Spec11 reporting completed successfully.",
|
||||
"text/plain");
|
||||
Optional.empty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFailure_tooManyRetries_emailsAlert() throws MessagingException, IOException {
|
||||
Message throwingMessage = mock(Message.class);
|
||||
doThrow(new MessagingException("expected")).when(throwingMessage).setSubject(any(String.class));
|
||||
// Only return the throwingMessage enough times to force failure. The last invocation will
|
||||
// be for the alert e-mail we're looking to verify.
|
||||
when(emailService.createMessage())
|
||||
.thenAnswer(
|
||||
new Answer<Message>() {
|
||||
private int count = 0;
|
||||
|
||||
@Override
|
||||
public Message answer(InvocationOnMock invocation) {
|
||||
if (count < RETRY_COUNT) {
|
||||
count++;
|
||||
return throwingMessage;
|
||||
} else if (count == RETRY_COUNT) {
|
||||
return new MimeMessage(Session.getDefaultInstance(new Properties(), null));
|
||||
} else {
|
||||
assertWithMessage("Attempted to generate too many messages!").fail();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
});
|
||||
public void testFailure_emailsAlert() throws MessagingException {
|
||||
doThrow(new RuntimeException(new MessagingException("expected")))
|
||||
.doNothing()
|
||||
.when(emailService)
|
||||
.sendEmail(contentCaptor.capture());
|
||||
RuntimeException thrown =
|
||||
assertThrows(
|
||||
RuntimeException.class,
|
||||
|
@ -231,57 +195,52 @@ public class Spec11EmailUtilsTest {
|
|||
.hasCauseThat()
|
||||
.hasMessageThat()
|
||||
.isEqualTo("javax.mail.MessagingException: expected");
|
||||
// We should have created RETRY_COUNT failing messages and one final alert message
|
||||
verify(emailService, times(RETRY_COUNT + 1)).createMessage();
|
||||
// Verify we sent an e-mail alert
|
||||
verify(emailService).sendMessage(gotMessage.capture());
|
||||
verify(emailService, times(2)).sendEmail(contentCaptor.capture());
|
||||
validateMessage(
|
||||
gotMessage.getValue(),
|
||||
contentCaptor.getValue(),
|
||||
"my-sender@test.com",
|
||||
"my-receiver@test.com",
|
||||
null,
|
||||
Optional.empty(),
|
||||
"Spec11 Emailing Failure 2018-07-15",
|
||||
"Emailing spec11 reports failed due to expected",
|
||||
"text/plain");
|
||||
Optional.empty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSuccess_sendAlertEmail() throws MessagingException, IOException {
|
||||
public void testSuccess_sendAlertEmail() throws MessagingException {
|
||||
emailUtils.sendAlertEmail("Spec11 Pipeline Alert: 2018-07", "Alert!");
|
||||
verify(emailService).sendMessage(gotMessage.capture());
|
||||
verify(emailService).sendEmail(contentCaptor.capture());
|
||||
validateMessage(
|
||||
gotMessage.getValue(),
|
||||
contentCaptor.getValue(),
|
||||
"my-sender@test.com",
|
||||
"my-receiver@test.com",
|
||||
null,
|
||||
Optional.empty(),
|
||||
"Spec11 Pipeline Alert: 2018-07",
|
||||
"Alert!",
|
||||
"text/plain");
|
||||
Optional.empty());
|
||||
}
|
||||
|
||||
private void validateMessage(
|
||||
Message message,
|
||||
EmailMessage message,
|
||||
String from,
|
||||
String recipient,
|
||||
@Nullable String replyTo,
|
||||
Optional<String> replyTo,
|
||||
String subject,
|
||||
String body,
|
||||
String contentType)
|
||||
throws MessagingException, IOException {
|
||||
assertThat(message.getFrom()).asList().containsExactly(new InternetAddress(from));
|
||||
assertThat(message.getRecipients(RecipientType.TO))
|
||||
.asList()
|
||||
.containsExactly(new InternetAddress(recipient));
|
||||
if (replyTo == null) {
|
||||
assertThat(message.getRecipients(RecipientType.BCC)).isNull();
|
||||
} else {
|
||||
assertThat(message.getRecipients(RecipientType.BCC))
|
||||
.asList()
|
||||
.containsExactly(new InternetAddress(replyTo));
|
||||
Optional<MediaType> contentType)
|
||||
throws MessagingException {
|
||||
EmailMessage.Builder expectedContentBuilder =
|
||||
EmailMessage.newBuilder()
|
||||
.setFrom(new InternetAddress(from))
|
||||
.addRecipient(new InternetAddress(recipient))
|
||||
.setSubject(subject)
|
||||
.setBody(body);
|
||||
|
||||
if (replyTo.isPresent()) {
|
||||
expectedContentBuilder.setBcc(new InternetAddress(replyTo.get()));
|
||||
}
|
||||
assertThat(message.getRecipients(RecipientType.CC)).isNull();
|
||||
assertThat(message.getSubject()).isEqualTo(subject);
|
||||
assertThat(message.getContentType()).isEqualTo(contentType);
|
||||
assertThat(message.getContent()).isEqualTo(body);
|
||||
contentType.ifPresent(expectedContentBuilder::setContentType);
|
||||
assertThat(message).isEqualTo(expectedContentBuilder.build());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -20,41 +20,28 @@ import static org.mockito.Mockito.doThrow;
|
|||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import google.registry.util.EmailMessage;
|
||||
import google.registry.util.SendEmailService;
|
||||
import java.util.Properties;
|
||||
import javax.mail.Message;
|
||||
import javax.mail.Message.RecipientType;
|
||||
import javax.mail.MessagingException;
|
||||
import javax.mail.Session;
|
||||
import javax.mail.internet.InternetAddress;
|
||||
import javax.mail.internet.MimeMessage;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
/** Unit tests for {@link SendEmailUtils}. */
|
||||
@RunWith(JUnit4.class)
|
||||
public class SendEmailUtilsTest {
|
||||
|
||||
private final SendEmailService emailService = mock(SendEmailService.class);
|
||||
|
||||
private Message message;
|
||||
private SendEmailUtils sendEmailUtils;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
message = new MimeMessage(Session.getDefaultInstance(new Properties(), null));
|
||||
when(emailService.createMessage()).thenReturn(message);
|
||||
}
|
||||
|
||||
private void setRecipients(ImmutableList<String> recipients) {
|
||||
private void setRecipients(ImmutableList<String> recipients) throws Exception {
|
||||
sendEmailUtils =
|
||||
new SendEmailUtils(
|
||||
"outgoing@registry.example",
|
||||
new InternetAddress("outgoing@registry.example"),
|
||||
"outgoing display name",
|
||||
recipients,
|
||||
emailService);
|
||||
|
@ -69,11 +56,7 @@ public class SendEmailUtilsTest {
|
|||
"Welcome to the Internet",
|
||||
"It is a dark and scary place."))
|
||||
.isTrue();
|
||||
verifyMessageSent();
|
||||
assertThat(message.getRecipients(RecipientType.TO)).asList()
|
||||
.containsExactly(new InternetAddress("johnny@fakesite.tld"));
|
||||
assertThat(message.getAllRecipients()).asList()
|
||||
.containsExactly(new InternetAddress("johnny@fakesite.tld"));
|
||||
verifyMessageSent("johnny@fakesite.tld");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -85,10 +68,7 @@ public class SendEmailUtilsTest {
|
|||
"Welcome to the Internet",
|
||||
"It is a dark and scary place."))
|
||||
.isTrue();
|
||||
verifyMessageSent();
|
||||
assertThat(message.getAllRecipients()).asList().containsExactly(
|
||||
new InternetAddress("foo@example.com"),
|
||||
new InternetAddress("bar@example.com"));
|
||||
verifyMessageSent("foo@example.com", "bar@example.com");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -100,9 +80,7 @@ public class SendEmailUtilsTest {
|
|||
"Welcome to the Internet",
|
||||
"It is a dark and scary place."))
|
||||
.isTrue();
|
||||
verifyMessageSent();
|
||||
assertThat(message.getAllRecipients()).asList()
|
||||
.containsExactly(new InternetAddress("foo@example.com"));
|
||||
verifyMessageSent("foo@example.com");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -114,7 +92,7 @@ public class SendEmailUtilsTest {
|
|||
"Welcome to the Internet",
|
||||
"It is a dark and scary place."))
|
||||
.isFalse();
|
||||
verify(emailService, never()).sendMessage(any(Message.class));
|
||||
verify(emailService, never()).sendEmail(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -126,23 +104,22 @@ public class SendEmailUtilsTest {
|
|||
"Welcome to the Internet",
|
||||
"It is a dark and scary place."))
|
||||
.isFalse();
|
||||
verify(emailService, never()).sendMessage(any(Message.class));
|
||||
verify(emailService, never()).sendEmail(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFailure_exceptionThrownDuringSend() throws Exception {
|
||||
setRecipients(ImmutableList.of("foo@example.com"));
|
||||
assertThat(sendEmailUtils.hasRecipients()).isTrue();
|
||||
doThrow(new MessagingException()).when(emailService).sendMessage(any(Message.class));
|
||||
doThrow(new RuntimeException(new MessagingException("expected")))
|
||||
.when(emailService)
|
||||
.sendEmail(any());
|
||||
assertThat(
|
||||
sendEmailUtils.sendEmail(
|
||||
"Welcome to the Internet",
|
||||
"It is a dark and scary place."))
|
||||
.isFalse();
|
||||
verifyMessageSent();
|
||||
assertThat(message.getAllRecipients())
|
||||
.asList()
|
||||
.containsExactly(new InternetAddress("foo@example.com"));
|
||||
verifyMessageSent("foo@example.com");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -155,13 +132,7 @@ public class SendEmailUtilsTest {
|
|||
"It is a dark and scary place.",
|
||||
ImmutableList.of("bar@example.com", "baz@example.com")))
|
||||
.isTrue();
|
||||
verifyMessageSent();
|
||||
assertThat(message.getAllRecipients())
|
||||
.asList()
|
||||
.containsExactly(
|
||||
new InternetAddress("foo@example.com"),
|
||||
new InternetAddress("bar@example.com"),
|
||||
new InternetAddress("baz@example.com"));
|
||||
verifyMessageSent("foo@example.com", "bar@example.com", "baz@example.com");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -174,16 +145,24 @@ public class SendEmailUtilsTest {
|
|||
"It is a dark and scary place.",
|
||||
ImmutableList.of("bar@example.com", "baz@example.com")))
|
||||
.isTrue();
|
||||
verifyMessageSent();
|
||||
assertThat(message.getAllRecipients())
|
||||
.asList()
|
||||
.containsExactly(
|
||||
new InternetAddress("bar@example.com"), new InternetAddress("baz@example.com"));
|
||||
verifyMessageSent("bar@example.com", "baz@example.com");
|
||||
}
|
||||
|
||||
private void verifyMessageSent() throws Exception {
|
||||
verify(emailService).sendMessage(message);
|
||||
assertThat(message.getSubject()).isEqualTo("Welcome to the Internet");
|
||||
assertThat(message.getContent()).isEqualTo("It is a dark and scary place.");
|
||||
private void verifyMessageSent(String... expectedRecipients) throws Exception {
|
||||
ArgumentCaptor<EmailMessage> contentCaptor = ArgumentCaptor.forClass(EmailMessage.class);
|
||||
verify(emailService).sendEmail(contentCaptor.capture());
|
||||
EmailMessage emailMessage = contentCaptor.getValue();
|
||||
ImmutableList.Builder<InternetAddress> recipientBuilder = ImmutableList.builder();
|
||||
for (String expectedRecipient : expectedRecipients) {
|
||||
recipientBuilder.add(new InternetAddress(expectedRecipient));
|
||||
}
|
||||
EmailMessage expectedContent =
|
||||
EmailMessage.newBuilder()
|
||||
.setSubject("Welcome to the Internet")
|
||||
.setBody("It is a dark and scary place.")
|
||||
.setFrom(new InternetAddress("outgoing@registry.example"))
|
||||
.setRecipients(recipientBuilder.build())
|
||||
.build();
|
||||
assertThat(emailMessage).isEqualTo(expectedContent);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -21,6 +21,7 @@ import static google.registry.model.registrar.Registrar.loadByClientId;
|
|||
import static google.registry.testing.DatastoreHelper.persistPremiumList;
|
||||
import static google.registry.testing.JUnitBackports.assertThrows;
|
||||
import static javax.servlet.http.HttpServletResponse.SC_MOVED_TEMPORARILY;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.appengine.api.users.User;
|
||||
|
@ -40,18 +41,17 @@ import google.registry.testing.DeterministicStringGenerator;
|
|||
import google.registry.testing.FakeClock;
|
||||
import google.registry.testing.FakeResponse;
|
||||
import google.registry.ui.server.SendEmailUtils;
|
||||
import google.registry.util.EmailMessage;
|
||||
import google.registry.util.SendEmailService;
|
||||
import java.util.Optional;
|
||||
import java.util.Properties;
|
||||
import javax.mail.Message;
|
||||
import javax.mail.Session;
|
||||
import javax.mail.internet.MimeMessage;
|
||||
import javax.mail.internet.InternetAddress;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnit;
|
||||
import org.mockito.junit.MockitoRule;
|
||||
|
@ -72,10 +72,9 @@ public final class ConsoleOteSetupActionTest {
|
|||
|
||||
@Mock HttpServletRequest request;
|
||||
@Mock SendEmailService emailService;
|
||||
Message message;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
public void setUp() throws Exception {
|
||||
persistPremiumList("default_sandbox_list", "sandbox,USD 1000");
|
||||
|
||||
action.req = request;
|
||||
|
@ -90,7 +89,7 @@ public final class ConsoleOteSetupActionTest {
|
|||
action.registryEnvironment = RegistryEnvironment.UNITTEST;
|
||||
action.sendEmailUtils =
|
||||
new SendEmailUtils(
|
||||
"outgoing@registry.example",
|
||||
new InternetAddress("outgoing@registry.example"),
|
||||
"UnitTest Registry",
|
||||
ImmutableList.of("notification@test.example", "notification2@test.example"),
|
||||
emailService);
|
||||
|
@ -101,9 +100,6 @@ public final class ConsoleOteSetupActionTest {
|
|||
|
||||
action.optionalPassword = Optional.empty();
|
||||
action.passwordGenerator = new DeterministicStringGenerator("abcdefghijklmnopqrstuvwxyz");
|
||||
|
||||
message = new MimeMessage(Session.getDefaultInstance(new Properties(), null));
|
||||
when(emailService.createMessage()).thenReturn(message);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -136,7 +132,7 @@ public final class ConsoleOteSetupActionTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void testPost_authorized() throws Exception {
|
||||
public void testPost_authorized() {
|
||||
action.clientId = Optional.of("myclientid");
|
||||
action.email = Optional.of("contact@registry.example");
|
||||
action.method = Method.POST;
|
||||
|
@ -150,8 +146,12 @@ public final class ConsoleOteSetupActionTest {
|
|||
.isEqualTo("contact@registry.example");
|
||||
assertThat(response.getPayload())
|
||||
.contains("<h1>OT&E successfully created for registrar myclientid!</h1>");
|
||||
assertThat(message.getSubject()).isEqualTo("OT&E for registrar myclientid created in unittest");
|
||||
assertThat(message.getContent())
|
||||
ArgumentCaptor<EmailMessage> contentCaptor = ArgumentCaptor.forClass(EmailMessage.class);
|
||||
verify(emailService).sendEmail(contentCaptor.capture());
|
||||
EmailMessage emailMessage = contentCaptor.getValue();
|
||||
assertThat(emailMessage.subject())
|
||||
.isEqualTo("OT&E for registrar myclientid created in unittest");
|
||||
assertThat(emailMessage.body())
|
||||
.isEqualTo(
|
||||
""
|
||||
+ "The following entities were created in unittest by TestUserId:\n"
|
||||
|
@ -163,7 +163,7 @@ public final class ConsoleOteSetupActionTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void testPost_authorized_setPassword() throws Exception {
|
||||
public void testPost_authorized_setPassword() {
|
||||
action.clientId = Optional.of("myclientid");
|
||||
action.email = Optional.of("contact@registry.example");
|
||||
action.optionalPassword = Optional.of("SomePassword");
|
||||
|
|
|
@ -20,6 +20,7 @@ import static google.registry.model.common.GaeUserIdConverter.convertEmailAddres
|
|||
import static google.registry.model.registrar.Registrar.loadByClientId;
|
||||
import static google.registry.testing.DatastoreHelper.persistPremiumList;
|
||||
import static javax.servlet.http.HttpServletResponse.SC_MOVED_TEMPORARILY;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.appengine.api.users.User;
|
||||
|
@ -41,12 +42,10 @@ import google.registry.testing.DeterministicStringGenerator;
|
|||
import google.registry.testing.FakeClock;
|
||||
import google.registry.testing.FakeResponse;
|
||||
import google.registry.ui.server.SendEmailUtils;
|
||||
import google.registry.util.EmailMessage;
|
||||
import google.registry.util.SendEmailService;
|
||||
import java.util.Optional;
|
||||
import java.util.Properties;
|
||||
import javax.mail.Message;
|
||||
import javax.mail.Session;
|
||||
import javax.mail.internet.MimeMessage;
|
||||
import javax.mail.internet.InternetAddress;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import org.joda.money.CurrencyUnit;
|
||||
import org.junit.Before;
|
||||
|
@ -54,6 +53,7 @@ import org.junit.Rule;
|
|||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnit;
|
||||
import org.mockito.junit.MockitoRule;
|
||||
|
@ -74,10 +74,9 @@ public final class ConsoleRegistrarCreatorActionTest {
|
|||
|
||||
@Mock HttpServletRequest request;
|
||||
@Mock SendEmailService emailService;
|
||||
Message message;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
public void setUp() throws Exception {
|
||||
persistPremiumList("default_sandbox_list", "sandbox,USD 1000");
|
||||
|
||||
action.req = request;
|
||||
|
@ -92,7 +91,7 @@ public final class ConsoleRegistrarCreatorActionTest {
|
|||
action.registryEnvironment = RegistryEnvironment.UNITTEST;
|
||||
action.sendEmailUtils =
|
||||
new SendEmailUtils(
|
||||
"outgoing@registry.example",
|
||||
new InternetAddress("outgoing@registry.example"),
|
||||
"UnitTest Registry",
|
||||
ImmutableList.of("notification@test.example", "notification2@test.example"),
|
||||
emailService);
|
||||
|
@ -120,9 +119,6 @@ public final class ConsoleRegistrarCreatorActionTest {
|
|||
|
||||
action.passwordGenerator = new DeterministicStringGenerator("abcdefghijklmnopqrstuvwxyz");
|
||||
action.passcodeGenerator = new DeterministicStringGenerator("314159265");
|
||||
|
||||
message = new MimeMessage(Session.getDefaultInstance(new Properties(), null));
|
||||
when(emailService.createMessage()).thenReturn(message);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -156,7 +152,7 @@ public final class ConsoleRegistrarCreatorActionTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void testPost_authorized_minimalAddress() throws Exception {
|
||||
public void testPost_authorized_minimalAddress() {
|
||||
action.clientId = Optional.of("myclientid");
|
||||
action.name = Optional.of("registrar name");
|
||||
action.billingAccount = Optional.of("USD=billing-account");
|
||||
|
@ -176,8 +172,11 @@ public final class ConsoleRegistrarCreatorActionTest {
|
|||
assertThat(response.getPayload())
|
||||
.contains("<h1>Successfully created Registrar myclientid</h1>");
|
||||
|
||||
assertThat(message.getSubject()).isEqualTo("Registrar myclientid created in unittest");
|
||||
assertThat(message.getContent())
|
||||
ArgumentCaptor<EmailMessage> contentCaptor = ArgumentCaptor.forClass(EmailMessage.class);
|
||||
verify(emailService).sendEmail(contentCaptor.capture());
|
||||
EmailMessage emailMessage = contentCaptor.getValue();
|
||||
assertThat(emailMessage.subject()).isEqualTo("Registrar myclientid created in unittest");
|
||||
assertThat(emailMessage.body())
|
||||
.isEqualTo(
|
||||
""
|
||||
+ "The following registrar was created in unittest by TestUserId:\n"
|
||||
|
@ -221,7 +220,7 @@ public final class ConsoleRegistrarCreatorActionTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void testPost_authorized_allAddress() throws Exception {
|
||||
public void testPost_authorized_allAddress() {
|
||||
action.clientId = Optional.of("myclientid");
|
||||
action.name = Optional.of("registrar name");
|
||||
action.billingAccount = Optional.of("USD=billing-account");
|
||||
|
@ -257,7 +256,7 @@ public final class ConsoleRegistrarCreatorActionTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void testPost_authorized_multipleBillingLines() throws Exception {
|
||||
public void testPost_authorized_multipleBillingLines() {
|
||||
action.clientId = Optional.of("myclientid");
|
||||
action.name = Optional.of("registrar name");
|
||||
action.ianaId = Optional.of(12321);
|
||||
|
@ -294,7 +293,7 @@ public final class ConsoleRegistrarCreatorActionTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void testPost_authorized_repeatingCurrency_fails() throws Exception {
|
||||
public void testPost_authorized_repeatingCurrency_fails() {
|
||||
action.clientId = Optional.of("myclientid");
|
||||
action.name = Optional.of("registrar name");
|
||||
action.ianaId = Optional.of(12321);
|
||||
|
@ -322,7 +321,7 @@ public final class ConsoleRegistrarCreatorActionTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void testPost_authorized_badCurrency_fails() throws Exception {
|
||||
public void testPost_authorized_badCurrency_fails() {
|
||||
action.clientId = Optional.of("myclientid");
|
||||
action.name = Optional.of("registrar name");
|
||||
action.ianaId = Optional.of(12321);
|
||||
|
@ -349,7 +348,7 @@ public final class ConsoleRegistrarCreatorActionTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void testPost_authorized_badBillingLine_fails() throws Exception {
|
||||
public void testPost_authorized_badBillingLine_fails() {
|
||||
action.clientId = Optional.of("myclientid");
|
||||
action.name = Optional.of("registrar name");
|
||||
action.ianaId = Optional.of(12321);
|
||||
|
@ -378,7 +377,7 @@ public final class ConsoleRegistrarCreatorActionTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void testPost_authorized_setPassword() throws Exception {
|
||||
public void testPost_authorized_setPassword() {
|
||||
action.clientId = Optional.of("myclientid");
|
||||
action.name = Optional.of("registrar name");
|
||||
action.billingAccount = Optional.of("USD=billing-account");
|
||||
|
|
|
@ -37,6 +37,7 @@ import google.registry.request.auth.AuthenticatedRegistrarAccessor.Role;
|
|||
import google.registry.testing.CertificateSamples;
|
||||
import google.registry.testing.TaskQueueHelper.TaskMatcher;
|
||||
import google.registry.util.CidrAddressBlock;
|
||||
import google.registry.util.EmailMessage;
|
||||
import java.util.Map;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Function;
|
||||
|
@ -45,6 +46,7 @@ import org.json.simple.parser.ParseException;
|
|||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
/** Tests for {@link RegistrarSettingsAction}. */
|
||||
@RunWith(JUnit4.class)
|
||||
|
@ -56,7 +58,9 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
|
|||
action.handleJsonRequest(readJsonFromFile("update_registrar.json", getLastUpdateTime()));
|
||||
verify(rsp, never()).setStatus(anyInt());
|
||||
verifyContactsNotified();
|
||||
assertThat(message.getContent()).isEqualTo(expectedEmailBody);
|
||||
ArgumentCaptor<EmailMessage> contentCaptor = ArgumentCaptor.forClass(EmailMessage.class);
|
||||
verify(emailService).sendEmail(contentCaptor.capture());
|
||||
assertThat(contentCaptor.getValue().body()).isEqualTo(expectedEmailBody);
|
||||
assertTasksEnqueued("sheet", new TaskMatcher()
|
||||
.url(SyncRegistrarsSheetAction.PATH)
|
||||
.method("GET")
|
||||
|
|
|
@ -44,14 +44,11 @@ import google.registry.testing.FakeClock;
|
|||
import google.registry.testing.InjectRule;
|
||||
import google.registry.ui.server.SendEmailUtils;
|
||||
import google.registry.util.AppEngineServiceUtils;
|
||||
import google.registry.util.EmailMessage;
|
||||
import google.registry.util.SendEmailService;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.util.Properties;
|
||||
import javax.mail.Message;
|
||||
import javax.mail.Session;
|
||||
import javax.mail.internet.InternetAddress;
|
||||
import javax.mail.internet.MimeMessage;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import org.joda.time.DateTime;
|
||||
|
@ -60,6 +57,7 @@ import org.junit.Before;
|
|||
import org.junit.Rule;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnit;
|
||||
import org.mockito.junit.MockitoRule;
|
||||
|
@ -81,9 +79,6 @@ public class RegistrarSettingsActionTestCase {
|
|||
@Mock HttpServletRequest req;
|
||||
@Mock HttpServletResponse rsp;
|
||||
@Mock SendEmailService emailService;
|
||||
final User user = new User("user", "gmail.com");
|
||||
|
||||
Message message;
|
||||
|
||||
final RegistrarSettingsAction action = new RegistrarSettingsAction();
|
||||
final StringWriter writer = new StringWriter();
|
||||
|
@ -115,8 +110,6 @@ public class RegistrarSettingsActionTestCase {
|
|||
AuthLevel.USER,
|
||||
UserAuthInfo.create(new User("user@email.com", "email.com", "12345"), false));
|
||||
inject.setStaticField(Ofy.class, "clock", clock);
|
||||
message = new MimeMessage(Session.getDefaultInstance(new Properties(), null));
|
||||
when(emailService.createMessage()).thenReturn(message);
|
||||
when(req.getMethod()).thenReturn("POST");
|
||||
when(rsp.getWriter()).thenReturn(new PrintWriter(writer));
|
||||
when(req.getContentType()).thenReturn("application/json");
|
||||
|
@ -128,7 +121,7 @@ public class RegistrarSettingsActionTestCase {
|
|||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
public void tearDown() {
|
||||
assertThat(RegistrarConsoleMetrics.settingsRequestMetric).hasNoOtherValues();
|
||||
}
|
||||
|
||||
|
@ -162,10 +155,9 @@ public class RegistrarSettingsActionTestCase {
|
|||
|
||||
/** Verifies that the original contact of TheRegistrar is among those notified of a change. */
|
||||
protected void verifyContactsNotified() throws Exception {
|
||||
verify(emailService).createMessage();
|
||||
verify(emailService).sendMessage(message);
|
||||
Truth.assertThat(message.getAllRecipients())
|
||||
.asList()
|
||||
ArgumentCaptor<EmailMessage> captor = ArgumentCaptor.forClass(EmailMessage.class);
|
||||
verify(emailService).sendEmail(captor.capture());
|
||||
Truth.assertThat(captor.getValue().recipients())
|
||||
.containsExactly(
|
||||
new InternetAddress("notification@test.example"),
|
||||
new InternetAddress("notification2@test.example"),
|
||||
|
|
162
javatests/google/registry/util/SendEmailServiceTest.java
Normal file
162
javatests/google/registry/util/SendEmailServiceTest.java
Normal file
|
@ -0,0 +1,162 @@
|
|||
// Copyright 2019 The Nomulus Authors. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package google.registry.util;
|
||||
|
||||
import static com.google.common.truth.Truth.assertThat;
|
||||
import static google.registry.testing.JUnitBackports.assertThrows;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import com.google.common.net.MediaType;
|
||||
import google.registry.testing.FakeClock;
|
||||
import google.registry.testing.FakeSleeper;
|
||||
import google.registry.util.EmailMessage.Attachment;
|
||||
import javax.mail.BodyPart;
|
||||
import javax.mail.Message;
|
||||
import javax.mail.Message.RecipientType;
|
||||
import javax.mail.MessagingException;
|
||||
import javax.mail.internet.InternetAddress;
|
||||
import javax.mail.internet.MimeMultipart;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Captor;
|
||||
import org.mockito.junit.MockitoJUnit;
|
||||
import org.mockito.junit.MockitoRule;
|
||||
|
||||
/** Unit tests for {@link SendEmailService}. */
|
||||
@RunWith(JUnit4.class)
|
||||
public class SendEmailServiceTest {
|
||||
|
||||
@Rule
|
||||
public final MockitoRule mocks = MockitoJUnit.rule();
|
||||
|
||||
private final Retrier retrier = new Retrier(new FakeSleeper(new FakeClock()), 2);
|
||||
private final TransportEmailSender wrapper = mock(TransportEmailSender.class);
|
||||
private final SendEmailService sendEmailService = new SendEmailService(retrier, wrapper);
|
||||
|
||||
@Captor private ArgumentCaptor<Message> messageCaptor;
|
||||
|
||||
@Test
|
||||
public void testSuccess_simple() throws Exception {
|
||||
EmailMessage content = createBuilder().build();
|
||||
sendEmailService.sendEmail(content);
|
||||
Message message = getMessage();
|
||||
assertThat(message.getAllRecipients())
|
||||
.asList()
|
||||
.containsExactly(new InternetAddress("fake@example.com"));
|
||||
assertThat(message.getFrom())
|
||||
.asList()
|
||||
.containsExactly(new InternetAddress("registry@example.com"));
|
||||
assertThat(message.getRecipients(RecipientType.BCC)).isNull();
|
||||
assertThat(message.getSubject()).isEqualTo("Subject");
|
||||
assertThat(message.getContentType()).startsWith("multipart/mixed");
|
||||
assertThat(getInternalContent(message).getContent().toString()).isEqualTo("body");
|
||||
assertThat(getInternalContent(message).getContentType()).isEqualTo("text/plain; charset=utf-8");
|
||||
assertThat(((MimeMultipart) message.getContent()).getCount()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSuccess_bcc() throws Exception {
|
||||
EmailMessage content = createBuilder().setBcc(new InternetAddress("bcc@example.com")).build();
|
||||
sendEmailService.sendEmail(content);
|
||||
Message message = getMessage();
|
||||
assertThat(message.getRecipients(RecipientType.BCC))
|
||||
.asList()
|
||||
.containsExactly(new InternetAddress("bcc@example.com"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSuccess_contentType() throws Exception {
|
||||
EmailMessage content = createBuilder().setContentType(MediaType.HTML_UTF_8).build();
|
||||
sendEmailService.sendEmail(content);
|
||||
Message message = getMessage();
|
||||
assertThat(getInternalContent(message).getContentType())
|
||||
.isEqualTo("text/html; charset=utf-8");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSuccess_attachment() throws Exception {
|
||||
EmailMessage content =
|
||||
createBuilder()
|
||||
.setAttachment(
|
||||
Attachment.newBuilder()
|
||||
.setFilename("filename")
|
||||
.setContent("foo,bar\nbaz,qux")
|
||||
.setContentType(MediaType.CSV_UTF_8)
|
||||
.build())
|
||||
.build();
|
||||
sendEmailService.sendEmail(content);
|
||||
Message message = getMessage();
|
||||
assertThat(((MimeMultipart) message.getContent()).getCount()).isEqualTo(2);
|
||||
BodyPart attachment = ((MimeMultipart) message.getContent()).getBodyPart(1);
|
||||
assertThat(attachment.getContent()).isEqualTo("foo,bar\nbaz,qux");
|
||||
assertThat(attachment.getContentType()).endsWith("name=filename");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSuccess_retry() throws Exception {
|
||||
doThrow(new MessagingException("hi"))
|
||||
.doNothing()
|
||||
.when(wrapper)
|
||||
.sendMessage(messageCaptor.capture());
|
||||
EmailMessage content = createBuilder().build();
|
||||
sendEmailService.sendEmail(content);
|
||||
assertThat(messageCaptor.getValue().getSubject()).isEqualTo("Subject");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFailure_wrongExceptionType() throws Exception {
|
||||
doThrow(new RuntimeException("this is a runtime exception")).when(wrapper).sendMessage(any());
|
||||
EmailMessage content = createBuilder().build();
|
||||
RuntimeException thrown =
|
||||
assertThrows(RuntimeException.class, () -> sendEmailService.sendEmail(content));
|
||||
assertThat(thrown).hasMessageThat().isEqualTo("this is a runtime exception");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFailure_tooManyTries() throws Exception {
|
||||
doThrow(new MessagingException("hi"))
|
||||
.doThrow(new MessagingException("second"))
|
||||
.when(wrapper)
|
||||
.sendMessage(any());
|
||||
EmailMessage content = createBuilder().build();
|
||||
RuntimeException thrown =
|
||||
assertThrows(RuntimeException.class, () -> sendEmailService.sendEmail(content));
|
||||
assertThat(thrown).hasCauseThat().hasMessageThat().isEqualTo("second");
|
||||
assertThat(thrown).hasCauseThat().isInstanceOf(MessagingException.class);
|
||||
}
|
||||
|
||||
private EmailMessage.Builder createBuilder() throws Exception {
|
||||
return EmailMessage.newBuilder()
|
||||
.setFrom(new InternetAddress("registry@example.com"))
|
||||
.addRecipient(new InternetAddress("fake@example.com"))
|
||||
.setSubject("Subject")
|
||||
.setBody("body");
|
||||
}
|
||||
|
||||
private Message getMessage() throws MessagingException {
|
||||
verify(wrapper).sendMessage(messageCaptor.capture());
|
||||
return messageCaptor.getValue();
|
||||
}
|
||||
|
||||
private BodyPart getInternalContent(Message message) throws Exception {
|
||||
return ((MimeMultipart) message.getContent()).getBodyPart(0);
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue