diff --git a/bb-email/pom.xml b/bb-email/pom.xml index 5547b849..4517ea08 100644 --- a/bb-email/pom.xml +++ b/bb-email/pom.xml @@ -59,6 +59,11 @@ + + org.mockito + mockito-core + test + org.hamcrest hamcrest-core diff --git a/bb-email/src/main/java/com/cognifide/qa/bb/email/EmailClient.java b/bb-email/src/main/java/com/cognifide/qa/bb/email/EmailClient.java index be087c9c..cbf2bac4 100644 --- a/bb-email/src/main/java/com/cognifide/qa/bb/email/EmailClient.java +++ b/bb-email/src/main/java/com/cognifide/qa/bb/email/EmailClient.java @@ -19,15 +19,15 @@ */ package com.cognifide.qa.bb.email; -import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; import java.util.List; +import java.util.stream.Collectors; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; -import javax.mail.search.SubjectTerm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -67,36 +67,10 @@ public void connect() { } /** - * @param subject Email message subject. - * @return List of Messages with subject from parameter. - */ - protected List getMessageList(String subject) { - - Message[] messages = {}; - try { - messages = folder.search(new SubjectTerm(subject), folder.getMessages()); - } catch (MessagingException e) { - LOGGER.error("error when getting email messages", e); - } - return Arrays.asList(messages); - } - - /** - * @param limit Messages amount. - * @return Last n Messages from inbox as list. + * Closes connection with mailbox. */ - protected List getMessageList(int limit) { - Message[] messages = {}; - try { - int messageCount = folder.getMessageCount(); - if (messageCount < 1) { - return new ArrayList<>(); - } - messages = folder.getMessages(messageCount - limit + 1, messageCount); - } catch (MessagingException e) { - LOGGER.error("error when getting email messages", e); - } - return Arrays.asList(messages); + public void close() { + connection.close(); } /** @@ -104,7 +78,7 @@ protected List getMessageList(int limit) { * @return List of EmailData with subject from parameter. */ public List getLatest(String subject) { - List messageList = getMessageList(subject); + Collection messageList = getMessageList(subject); return createEmailDataList(messageList); } @@ -113,17 +87,10 @@ public List getLatest(String subject) { * @return Last n EmailData from inbox. */ public List getLatest(int limit) { - List messageList = getMessageList(limit); + Collection messageList = getMessageList(limit); return createEmailDataList(messageList); } - /** - * Closes connection with mailbox. - */ - public void close() { - connection.close(); - } - /** * Deletes all emails. */ @@ -135,35 +102,82 @@ public void removeAllEmails() { } } + /** + * Deletes all emails with subject. + * + * @param subject Subject of message. + */ + public void removeAllEmails(String subject) { + getMessageList(subject) + .forEach(this::removeEmail); + } + /** * Deletes last n emails. * * @param limit emails amount. */ public void removeLastEmails(int limit) { - List messages = getMessageList(limit); - for (Message message : messages) { - try { - message.setFlag(Flags.Flag.DELETED, true); - } catch (MessagingException e) { - LOGGER.error("error when removing emails from server", e); + getMessageList(limit) + .forEach(this::removeEmail); + } + + /** + * @param subject Email message subject. + * @return Array of Messages with subject from parameter. + */ + protected List getMessageList(String subject) { + + Message[] messages = {}; + try { + messages = folder.search(new SubjectSearchTerm(subject)); + } catch (MessagingException e) { + LOGGER.error("error when getting email messages", e); + } + return Arrays.asList(messages); + } + + /** + * @param limit Messages amount. + * @return Last n Messages from inbox as list. + */ + protected List getMessageList(int limit) { + Message[] messages = {}; + try { + int messageCount = folder.getMessageCount(); + if (messageCount > 0) { + int startIndex = messageCount - Math.min(limit, messageCount) + 1; + messages = folder.getMessages(startIndex, messageCount); } + } catch (MessagingException e) { + LOGGER.error("error when getting email messages", e); } + return Arrays.asList(messages); } /** * This method converts list of Message objects to list of EmailData. * - * @param messageList List of Messages. - * @return List of EmailData objects. + * @param messages List of Messages. + * @return Collection of EmailData objects. */ - private List createEmailDataList(List messageList) { - List emailDataList = new ArrayList<>(); - for (Message message : messageList) { - EmailData emailData = emailDataFactory.create(message); - emailDataList.add(emailData); + private List createEmailDataList(Collection messages) { + return messages.stream() + .map(emailDataFactory::create) + .collect(Collectors.toList()); + } + + /** + * This method deletes mail + * + * @param message Mail reference + */ + private void removeEmail(Message message) { + try { + message.setFlag(Flags.Flag.DELETED, true); + } catch (MessagingException e) { + LOGGER.error("error when removing emails from server", e); } - return emailDataList; } } diff --git a/bb-email/src/main/java/com/cognifide/qa/bb/email/SubjectSearchTerm.java b/bb-email/src/main/java/com/cognifide/qa/bb/email/SubjectSearchTerm.java new file mode 100644 index 00000000..34d8b5eb --- /dev/null +++ b/bb-email/src/main/java/com/cognifide/qa/bb/email/SubjectSearchTerm.java @@ -0,0 +1,59 @@ +/*- + * #%L + * Bobcat + * %% + * Copyright (C) 2016 Cognifide Ltd. + * %% + * 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. + * #L% + */ +package com.cognifide.qa.bb.email; + +import java.util.Optional; + +import javax.mail.Message; +import javax.mail.MessagingException; +import javax.mail.search.SearchTerm; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SubjectSearchTerm extends SearchTerm { + + private static final Logger LOGGER = LoggerFactory.getLogger(SubjectSearchTerm.class); + + private final String subject; + + public SubjectSearchTerm(String subject) { + this.subject = subject; + } + + @Override + public boolean match(Message msg) { + return Optional.ofNullable(msg) + .map(this::getSubjectFromMessage) + .map(emailSubject -> StringUtils.equals(emailSubject, subject)) + .orElse(false); + } + + private String getSubjectFromMessage(Message msg) { + String result = null; + try { + result = msg.getSubject(); + } catch (MessagingException e) { + LOGGER.error("error when getting email subject", e); + } + return result; + } +} diff --git a/bb-email/src/test/java/com/cognifide/qa/bb/email/EmailTest.java b/bb-email/src/test/java/com/cognifide/qa/bb/email/EmailTest.java index b0d0e810..66d199aa 100644 --- a/bb-email/src/test/java/com/cognifide/qa/bb/email/EmailTest.java +++ b/bb-email/src/test/java/com/cognifide/qa/bb/email/EmailTest.java @@ -22,6 +22,7 @@ import java.util.Arrays; import java.util.Collection; import java.util.List; +import java.util.stream.Collectors; import org.junit.After; import org.junit.Assert; @@ -60,7 +61,7 @@ public EmailTest(String propertiesFileName) { @Parameters public static Collection parameters() { - return Arrays.asList(new Object[][] { + return Arrays.asList(new Object[][]{ {"email.imap.properties"}, {"email.imaps.properties"}, {"email.pop3s.properties"}, @@ -84,9 +85,8 @@ public void tearDown() { public void canReceiveLatestEmails() { int emailsNumber = 5; List sentEmails = dataGenerator.generateEmailData(emailsNumber); - for (EmailData emailData : sentEmails) { - sender.sendEmail(emailData); - } + + sentEmails.forEach(sender::sendEmail); client.connect(); @@ -96,4 +96,103 @@ public void canReceiveLatestEmails() { Assert.assertTrue("email data objects should be equal", sentEmails.equals(receivedEmails)); } + + @Test + public void canReceiveMailBySubject() { + String subject = "test"; + EmailData sentEmail = dataGenerator.generateEmailData(subject); + + sender.sendEmail(sentEmail); + + int emailsNumber = 5; + List sentEmails = dataGenerator.generateEmailData(emailsNumber); + sentEmails.forEach(sender::sendEmail); + + client.connect(); + + List receivedEmail = client.getLatest(subject); + client.close(); + + Assert.assertTrue(receivedEmail.contains(sentEmail)); + + boolean topicMatches = receivedEmail.stream() + .map(EmailData::getSubject) + .allMatch(subject::equals); + + Assert.assertTrue(topicMatches); + } + + @Test + public void canRemoveAllMailsWithSubject() { + String subject = "test"; + EmailData subjectMail = dataGenerator.generateEmailData(subject); + sender.sendEmail(subjectMail); + + int emailsNumber = 5; + List sentEmails = dataGenerator.generateEmailData(emailsNumber); + sentEmails.forEach(sender::sendEmail); + + client.connect(); + + client.removeAllEmails(subject); + + //reconnect to apply delete of messages + client.close(); + client.connect(); + + List latest = client.getLatest(emailsNumber + 1); + + client.close(); + + Assert.assertFalse(latest.contains(subjectMail)); + Assert.assertTrue(latest.containsAll(sentEmails)); + } + + @Test + public void canRemoveLastEmails() { + int emailsNumber = 5; + int emailsToDelete = 2; + List sentEmails = dataGenerator.generateEmailData(emailsNumber); + sentEmails.forEach(sender::sendEmail); + + client.connect(); + + client.removeLastEmails(emailsToDelete); + + //reconnect to apply delete of messages + client.close(); + client.connect(); + + List latest = client.getLatest(emailsNumber); + + client.close(); + + List limitedList = + sentEmails.stream() + .limit(emailsNumber - emailsToDelete) + .collect(Collectors.toList()); + + Assert.assertEquals(latest, limitedList); + } + + @Test + public void canRemoveAllEmails() { + int emailsNumber = 5; + List sentEmails = dataGenerator.generateEmailData(emailsNumber); + sentEmails.forEach(sender::sendEmail); + + client.connect(); + + client.removeAllEmails(); + + //reconnect to apply delete of messages + client.close(); + client.connect(); + + List latest = client.getLatest(emailsNumber); + + client.close(); + + Assert.assertTrue(latest.isEmpty()); + } } diff --git a/bb-email/src/test/java/com/cognifide/qa/bb/email/SubjectSearchTermTest.java b/bb-email/src/test/java/com/cognifide/qa/bb/email/SubjectSearchTermTest.java new file mode 100644 index 00000000..4b043602 --- /dev/null +++ b/bb-email/src/test/java/com/cognifide/qa/bb/email/SubjectSearchTermTest.java @@ -0,0 +1,82 @@ +/*- + * #%L + * Bobcat + * %% + * Copyright (C) 2016 Cognifide Ltd. + * %% + * 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. + * #L% + */ +package com.cognifide.qa.bb.email; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.Collection; + +import javax.mail.Message; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; + +@RunWith(Parameterized.class) +public class SubjectSearchTermTest { + + public static final String VALID_SUBJECT = "valid"; + + public static final String INVALID_SUBJECT = "invalid"; + + private final boolean expected; + + private final String subject; + + @Rule + public final MockitoRule mockitoRule = MockitoJUnit.rule(); + + @Mock + private Message message; + + public SubjectSearchTermTest(String subject, boolean expected) { + this.expected = expected; + this.subject = subject; + } + + @Parameters + public static Collection parameters() { + return Arrays.asList(new Object[][] { + {VALID_SUBJECT, true}, + {INVALID_SUBJECT, false}, + {StringUtils.EMPTY, false}, + {null, false} + }); + } + + @Test + public void match() throws Exception { + + when(message.getSubject()).thenReturn(VALID_SUBJECT); + + boolean actual = new SubjectSearchTerm(subject).match(message); + + assertEquals(expected, actual); + } + +} \ No newline at end of file diff --git a/bb-email/src/test/java/com/cognifide/qa/bb/email/helpers/EmailDataGenerator.java b/bb-email/src/test/java/com/cognifide/qa/bb/email/helpers/EmailDataGenerator.java index e94d80db..c9ea6ace 100644 --- a/bb-email/src/test/java/com/cognifide/qa/bb/email/helpers/EmailDataGenerator.java +++ b/bb-email/src/test/java/com/cognifide/qa/bb/email/helpers/EmailDataGenerator.java @@ -48,18 +48,29 @@ public List generateEmailData(int number) { List result = new ArrayList<>(); for (int i = 0; i < number; i++) { - EmailData emailData = new EmailData(); - emailData.setAddressFrom(addressFrom); - emailData.setAddressTo(addressTo); - emailData.setMessageContent( - "this is bobcat test message [" + i + "]: " + getRandomString()); - emailData.setSubject("test message " + getRandomString()); + String message = "this is bobcat test message [" + i + "]: " + getRandomString(); + String subject = "test message " + getRandomString(); + EmailData emailData = createEmailData(subject, message); result.add(emailData); } return result; } + public EmailData generateEmailData(String subject) { + String message = "this is bobcat test message : " + getRandomString(); + return createEmailData(subject, message); + } + + private EmailData createEmailData(String subject, String message) { + EmailData emailData = new EmailData(); + emailData.setAddressFrom(addressFrom); + emailData.setAddressTo(addressTo); + emailData.setMessageContent(message); + emailData.setSubject(subject); + return emailData; + } + private String getRandomString() { SecureRandom random = new SecureRandom(); return new BigInteger(NUMBER_OF_BITS, random).toString(RADIX_FOR_RANDOM_STRING_GENERATION);