zoukankan      html  css  js  c++  java
  • Wiser的Junit测试用法

      1 package org.jbpm.process.workitem.email;
      2 
      3 import static org.junit.Assert.assertEquals;
      4 import static org.junit.Assert.assertNotNull;
      5 import static org.junit.Assert.assertTrue;
      6 import java.util.Arrays;
      7 import java.util.List;
      8 import java.util.Random;
      9 import javax.mail.AuthenticationFailedException;
     10 import javax.mail.BodyPart;
     11 import javax.mail.Message.RecipientType;
     12 import javax.mail.Multipart;
     13 import javax.mail.Part;
     14 import javax.mail.internet.InternetAddress;
     15 import javax.mail.internet.MimeMessage;
     16 import org.drools.core.process.instance.impl.DefaultWorkItemManager;
     17 import org.drools.core.process.instance.impl.WorkItemImpl;
     18 import org.jbpm.test.util.AbstractBaseTest;
     19 import org.junit.After;
     20 import org.junit.Before;
     21 import org.junit.Test;
     22 import org.kie.api.runtime.process.WorkItemManager;
     23 import org.slf4j.Logger;
     24 import org.slf4j.LoggerFactory;
     25 import org.subethamail.smtp.AuthenticationHandler;
     26 import org.subethamail.smtp.AuthenticationHandlerFactory;
     27 import org.subethamail.smtp.auth.LoginAuthenticationHandlerFactory;
     28 import org.subethamail.smtp.auth.LoginFailedException;
     29 import org.subethamail.smtp.auth.MultipleAuthenticationHandlerFactory;
     30 import org.subethamail.smtp.auth.PlainAuthenticationHandlerFactory;
     31 import org.subethamail.smtp.auth.UsernamePasswordValidator;
     32 import org.subethamail.wiser.Wiser;
     33 import org.subethamail.wiser.WiserMessage;
     34 
     35 public class SendHtmlTest extends AbstractBaseTest {
     36     private static final Logger logger = LoggerFactory
     37             .getLogger(SendHtmlTest.class);
     38     private Wiser wiser;
     39     private String emailHost;
     40     private String emailPort;
     41     private static String authUsername = "cpark";
     42     private static String authPassword = "yourbehindwhat?";
     43     private Random random = new Random();
     44     private int uniqueTestNum = -1;
     45 
     46     @Before
     47     public void setUp() throws Exception {
     48         uniqueTestNum = random.nextInt(Integer.MAX_VALUE);
     49         emailHost = "localhost";
     50         int emailPortInt;
     51         do {
     52             emailPortInt = random.nextInt((2 * Short.MAX_VALUE - 1));
     53         } while (emailPortInt < 4096);
     54         emailPort = Integer.toString(emailPortInt);
     55         wiser = new Wiser(Integer.parseInt(emailPort));
     56         wiser.start();
     57     }
     58 
     59     @After
     60     public void tearDown() throws Exception {
     61         if (wiser != null) {
     62             wiser.getMessages().clear();
     63             wiser.stop();
     64             wiser = null;
     65         }
     66     }
     67 
     68     @SuppressWarnings("unused")
     69     private class ExtendedConnection extends Connection {
     70         private String extraField;
     71     }
     72 
     73     @Test
     74     public void testConnectionEquals() {
     75         Connection connA = new Connection();
     76         Connection connB = new Connection();
     77         // null test
     78         assertTrue(!connA.equals(null));
     79         // different class test
     80         assertTrue(!connA.equals("og"));
     81         // extended class test
     82         ExtendedConnection connExt = new ExtendedConnection();
     83         assertTrue(!connA.equals(connExt));
     84         // null fields test
     85         assertTrue(connA.equals(connB));
     86         // all null vs filled field test
     87         connA.setHost("Human");
     88         connA.setPort("Skin");
     89         connA.setUserName("Viral");
     90         connA.setPassword("Protein Gate");
     91         assertTrue(!connA.equals(connB));
     92         // filled field test
     93         connB.setHost(connA.getHost());
     94         connB.setPort(new String(connA.getPort()));
     95         connB.setUserName(connA.getUserName());
     96         connB.setPassword(connA.getPassword());
     97         assertTrue(connA.equals(connB));
     98         // some null vs filled field test
     99         connA.setPassword(null);
    100         connB.setPassword(null);
    101         assertTrue(connA.equals(connB));
    102         // boolean
    103         connA.setStartTls(true);
    104         assertTrue(!connA.equals(connB));
    105         connB.setStartTls(true);
    106         assertTrue(connA.equals(connB));
    107         connB.setStartTls(false);
    108         assertTrue(!connA.equals(connB));
    109     }
    110 
    111     @Test
    112     public void verifyWiserServerWorks() throws Exception {
    113         // Input
    114         String testMethodName = Thread.currentThread().getStackTrace()[1]
    115                 .getMethodName();
    116         String toAddress = "boyd@crowdergang.org";
    117         String fromAddress = "rgivens@kty.us.gov";
    118         // Setup email
    119         WorkItemImpl workItem = createEmailWorkItem(toAddress, fromAddress,
    120                 testMethodName);
    121         Connection connection = new Connection(emailHost, emailPort);
    122         sendAndCheckThatMessagesAreSent(workItem, connection);
    123     }
    124 
    125     @Test
    126     public void sendHtmlWithAuthentication() throws Exception {
    127         // Add authentication to Wiser SMTP server
    128         wiser.getServer().setAuthenticationHandlerFactory(
    129                 new TestAuthHandlerFactory());
    130         // Input
    131         String testMethodName = Thread.currentThread().getStackTrace()[1]
    132                 .getMethodName();
    133         String toAddress = "rgivens@kty.us.gov";
    134         String fromAddress = "whawkins@kty.us.gov";
    135         // Setup email
    136         WorkItemImpl workItem = createEmailWorkItem(toAddress, fromAddress,
    137                 testMethodName);
    138         Connection connection = new Connection(emailHost, emailPort,
    139                 authUsername, authPassword);
    140         sendAndCheckThatMessagesAreSent(workItem, connection);
    141     }
    142 
    143     @Test
    144     public void sendHtmlWithAuthenticationAndAttachments() throws Exception {
    145         // Add authentication to Wiser SMTP server
    146         wiser.getServer().setAuthenticationHandlerFactory(
    147                 new TestAuthHandlerFactory());
    148         // Input
    149         String testMethodName = Thread.currentThread().getStackTrace()[1]
    150                 .getMethodName();
    151         String toAddress = "rgivens@kty.us.gov";
    152         String fromAddress = "whawkins@kty.us.gov";
    153         // Setup email
    154         WorkItemImpl workItem = createEmailWorkItemWithAttachment(toAddress,
    155                 fromAddress, testMethodName);
    156         Connection connection = new Connection(emailHost, emailPort,
    157                 authUsername, authPassword);
    158         // send email
    159         Email email = EmailWorkItemHandler.createEmail(workItem, connection);
    160         SendHtml.sendHtml(email, connection);
    161         List<WiserMessage> messages = wiser.getMessages();
    162         assertEquals(1, messages.size());
    163         MimeMessage message = messages.get(0).getMimeMessage();
    164         assertEquals(workItem.getParameter("Subject"), message.getSubject());
    165         assertTrue(Arrays.equals(
    166                 InternetAddress.parse((String) workItem.getParameter("To")),
    167                 message.getRecipients(RecipientType.TO)));
    168         assertTrue(message.getContent() instanceof Multipart);
    169         Multipart multipart = (Multipart) message.getContent();
    170         assertEquals(2, multipart.getCount());
    171         for (int i = 0; i < multipart.getCount(); i++) {
    172             BodyPart bodyPart = multipart.getBodyPart(i);
    173             if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
    174                 continue;
    175                 // dealing with attachments only
    176             }
    177             assertEquals("email.gif", bodyPart.getFileName());
    178         }
    179     }
    180 
    181     @Test
    182     public void sendHtmlWithBadAuthentication() throws Exception {
    183         // Add authentication to Wiser SMTP server
    184         wiser.getServer().setAuthenticationHandlerFactory(
    185                 new TestAuthHandlerFactory());
    186         // Input
    187         String testMethodName = Thread.currentThread().getStackTrace()[1]
    188                 .getMethodName();
    189         String toAddress = "mags@bennetstore.com";
    190         String fromAddress = "rgivens@kty.us.gov";
    191         checkBadAuthentication(toAddress, fromAddress, testMethodName,
    192                 authUsername, "bad password");
    193         checkBadAuthentication(toAddress, fromAddress, testMethodName,
    194                 "badUserName", authPassword);
    195     }
    196 
    197     @Test
    198     public void useEmailWorkItemHandlerWithAuthentication() throws Exception {
    199         // Add authentication to Wiser SMTP server
    200         wiser.getServer().setAuthenticationHandlerFactory(
    201                 new TestAuthHandlerFactory());
    202         // Input
    203         String testMethodName = Thread.currentThread().getStackTrace()[1]
    204                 .getMethodName();
    205         String toAddress = "rgivens@yahoo.com";
    206         String fromAddress = "rgivens@kty.us.gov";
    207         EmailWorkItemHandler handler = new EmailWorkItemHandler();
    208         handler.setConnection(emailHost, emailPort, authUsername, authPassword);
    209         WorkItemImpl workItem = new WorkItemImpl();
    210         workItem.setParameter("To", toAddress);
    211         workItem.setParameter("From", fromAddress);
    212         workItem.setParameter("Reply-To", fromAddress);
    213         workItem.setParameter("Subject", "Test mail for " + testMethodName);
    214         workItem.setParameter("Body",
    215                 "Don't forget to check on Boyd later today.");
    216         WorkItemManager manager = new DefaultWorkItemManager(null);
    217         handler.executeWorkItem(workItem, manager);
    218         List<WiserMessage> messages = wiser.getMessages();
    219         assertEquals(1, messages.size());
    220         for (WiserMessage wiserMessage : messages) {
    221             MimeMessage message = wiserMessage.getMimeMessage();
    222             assertEquals(workItem.getParameter("Subject"), message.getSubject());
    223             assertTrue(Arrays.equals(InternetAddress.parse(toAddress),
    224                     message.getRecipients(RecipientType.TO)));
    225         }
    226     }
    227 
    228     /** * Helper methods */
    229     private void sendAndCheckThatMessagesAreSent(WorkItemImpl workItem,
    230             Connection connection) throws Exception {
    231         // send email
    232         Email email = EmailWorkItemHandler.createEmail(workItem, connection);
    233         SendHtml.sendHtml(email, connection);
    234         List<WiserMessage> messages = wiser.getMessages();
    235         assertEquals(1, messages.size());
    236         for (WiserMessage wiserMessage : messages) {
    237             MimeMessage message = wiserMessage.getMimeMessage();
    238             assertEquals(workItem.getParameter("Subject"), message.getSubject());
    239             assertTrue(Arrays
    240                     .equals(InternetAddress.parse((String) workItem
    241                             .getParameter("To")), message
    242                             .getRecipients(RecipientType.TO)));
    243         }
    244     }
    245 
    246     private void checkBadAuthentication(String toAddress, String fromAddress,
    247             String testMethodName, String username, String password) {
    248         // Setup email
    249         WorkItemImpl workItem = createEmailWorkItem(toAddress, fromAddress,
    250                 testMethodName);
    251         Connection connection = new Connection(emailHost, emailPort, username,
    252                 password);
    253         // send email
    254         Email email = EmailWorkItemHandler.createEmail(workItem, connection);
    255         try {
    256             SendHtml.sendHtml(email, connection);
    257         } catch (Throwable t) {
    258             assertTrue("Unexpected exception of type "
    259                     + t.getClass().getSimpleName() + ", not "
    260                     + t.getClass().getSimpleName(),
    261                     (t instanceof RuntimeException));
    262             assertNotNull("Expected RuntimeException to have a cause.",
    263                     t.getCause());
    264             Throwable cause = t.getCause();
    265             assertNotNull("Expected cause to have a cause.", cause.getCause());
    266             cause = cause.getCause();
    267             assertTrue("Unexpected exception of type "
    268                     + cause.getClass().getSimpleName() + ", not "
    269                     + cause.getClass().getSimpleName(),
    270                     (cause instanceof AuthenticationFailedException));
    271         }
    272     }
    273 
    274     private WorkItemImpl createEmailWorkItem(String toAddress,
    275             String fromAddress, String testMethodName) {
    276         WorkItemImpl workItem = new WorkItemImpl();
    277         workItem.setParameter("To", toAddress);
    278         workItem.setParameter("From", fromAddress);
    279         workItem.setParameter("Reply-To", fromAddress);
    280         String subject = this.getClass().getSimpleName() + " test message ["
    281                 + uniqueTestNum + "]";
    282         String body = "
    This is the test message generated by the "
    283                 + testMethodName + " test (" + uniqueTestNum + ").
    ";
    284         workItem.setParameter("Subject", subject);
    285         workItem.setParameter("Body", body);
    286         return workItem;
    287     }
    288 
    289     private WorkItemImpl createEmailWorkItemWithAttachment(String toAddress,
    290             String fromAddress, String testMethodName) {
    291         WorkItemImpl workItem = new WorkItemImpl();
    292         workItem.setParameter("To", toAddress);
    293         workItem.setParameter("From", fromAddress);
    294         workItem.setParameter("Reply-To", fromAddress);
    295         String subject = this.getClass().getSimpleName() + " test message ["
    296                 + uniqueTestNum + "]";
    297         String body = "
    This is the test message generated by the "
    298                 + testMethodName + " test (" + uniqueTestNum + ").
    ";
    299         workItem.setParameter("Subject", subject);
    300         workItem.setParameter("Body", body);
    301         workItem.setParameter("Attachments", "classpath:/icons/email.gif");
    302         return workItem;
    303     }
    304 
    305     private static class TestAuthHandlerFactory implements
    306             AuthenticationHandlerFactory {
    307         MultipleAuthenticationHandlerFactory authHandleFactory = new MultipleAuthenticationHandlerFactory();
    308 
    309         public TestAuthHandlerFactory() {
    310             UsernamePasswordValidator validator = new UsernamePasswordValidator() {
    311                 public void login(String username, String password)
    312                         throws LoginFailedException {
    313                     if (!authUsername.equals(username)
    314                             || !authPassword.equals(password)) {
    315                         logger.debug(
    316                                 "Tried to login with user/password [{}/{}]",
    317                                 username, password);
    318                         throw new LoginFailedException(
    319                                 "Incorrect password for user " + authUsername);
    320                     }
    321                 }
    322             };
    323             authHandleFactory.addFactory(new LoginAuthenticationHandlerFactory(
    324                     validator));
    325             authHandleFactory.addFactory(new PlainAuthenticationHandlerFactory(
    326                     validator));
    327         }
    328 
    329         public AuthenticationHandler create() {
    330             return authHandleFactory.create();
    331         }
    332 
    333         public List<String> getAuthenticationMechanisms() {
    334             return authHandleFactory.getAuthenticationMechanisms();
    335         }
    336     }
    337 }


    关于javamail的Junit测试,找了很久才找到如何测试验证SMTP服务器。

  • 相关阅读:
    Django ORM多表操作
    Django 单表查询作业-笔记
    python 2 编码问题
    HTML-Bootstrap下载和基本使用
    Django ORM单表操作之增删改查
    Django ORM简介和单表创建的设置和过程
    Django --总结 之URL路由控制 视图相应,视图请求,和模板语法
    Django URL控制器
    JAVA编程
    UMI 的原理分析带有 UMI 的数据
  • 原文地址:https://www.cnblogs.com/winnersalp/p/3466770.html
Copyright © 2011-2022 走看看