登录
首页 >  Golang >  Go问答

单元测试:SMTP模拟服务器,用于测试SMTP发送电子邮件

来源:stackoverflow

时间:2024-04-06 08:48:36 124浏览 收藏

怎么入门Golang编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《单元测试:SMTP模拟服务器,用于测试SMTP发送电子邮件》,涉及到,有需要的可以收藏一下

问题内容

我测试了电子邮件逻辑,用于发送电子邮件,工作正常。

现在为了进行单元测试,我从 https://golang.org/src/net/smtp/smtp_test.go 复制了模拟 smtp 服务器代码,第 639 行 function => testsendmailwithauth

有效的邮件代码:

  1. 使用的类型
type email struct {
    subject      string
    body         string
    templatefile string
    templatedata interface{}
}

type plugininput struct{
    smtpserver            string        
    username              string        
    password              string        
    from                  string        
    to                    string        
    cc                    string     
}

email := &email{
                subject:      "sendmail test",
                body:         `
                
                
                    idp execution summary email
                
                test email
                `,
            }
  1. 发送电子邮件的代码
func (email *email) sendmail(plugininput *plugininput) error {

    // connect to the remote smtp server.
    smtpclient, err := smtp.dial(plugininput.smtpserver)
    if err != nil {
        logger.error(err)
        return err
    }

    //smtpserverhost
    smtpserverhost, _, err := net.splithostport(plugininput.smtpserver)

    //start tls with no certificate check
    if ok, _ := smtpclient.extension("starttls"); ok {
        // #nosec g402
        config := &tls.config{servername: smtpserverhost, insecureskipverify: true}
        if err = smtpclient.starttls(config); err != nil {
            return err
        }
    }

    //set smtp client auth
    if ok, authmechanism := smtpclient.extension("auth"); ok {
        usernamewithoutdomain := strings.split(plugininput.username, "@")[0]
        switch authmechanism {
        case ``:
            err = smtpclient.auth(nil)
        case `login`:
            err = smtpclient.auth(loginauth(usernamewithoutdomain, plugininput.password))
        case `cram-md5`:
            err = smtpclient.auth(smtp.crammd5auth(usernamewithoutdomain, plugininput.password))
        case `plain`:
            err = smtpclient.auth(smtp.plainauth("", usernamewithoutdomain, plugininput.password, smtpserverhost))
        default:
            err = smtpclient.auth(smtp.plainauth("", usernamewithoutdomain, plugininput.password, smtpserverhost))
        }
        if err != nil {
            return err
        }
    }

    // from
    if err = smtpclient.mail(plugininput.username); err != nil {
        logger.error(err)
        return err
    }
    // to & cc
    toarr := strings.split(plugininput.to, ",")
    ccarr := strings.split(plugininput.cc, ",")
    toarr = append(toarr, ccarr...)
    for _, addr := range toarr {
        if err = smtpclient.rcpt(addr); err != nil {
            return err
        }
    }

    //body
    msg := "to: " + plugininput.to + "\r\n" +
        "cc: " + plugininput.cc + "\r\n" +
        "subject: " + email.subject + "\r\n" +
        mimeheaders + "\r\n" + email.body

    // send data command tp smtp server
    smtpwritercloser, err := smtpclient.data()
    if err != nil {
        return err
    }
    _, err = fmt.fprintf(smtpwritercloser, msg)
    if err != nil {
        return err
    }
    if err = smtpwritercloser.close(); err != nil {
        return err
    }

    //send quit command to smtp server
    if err = smtpclient.quit(); err != nil {
        return err
    }

    return nil
}
  1. 单元测试代码:
func TestEmail_SendMail(t *testing.T) {

    l, err := net.Listen("tcp", "127.0.0.1:0")
    if err != nil {
        t.Fatalf("Unable to create listener: %v", err)
    }
    defer l.Close()

    errCh := make(chan error)
    go func() {
        defer close(errCh)
        conn, err := l.Accept()
        if err != nil {
            errCh <- fmt.Errorf("Accept: %v", err)
            return
        }
        defer conn.Close()

        tc := textproto.NewConn(conn)
        tc.PrintfLine("220 hello world")
        msg, err := tc.ReadLine()
        if err != nil {
            errCh <- fmt.Errorf("ReadLine error: %v", err)
            return
        }
        const wantMsg = "EHLO localhost"
        if msg != wantMsg {
            errCh <- fmt.Errorf("unexpected response %q; want %q", msg, wantMsg)
            return
        }
        err = tc.PrintfLine("250 mx.google.com at your service")
        if err != nil {
            errCh <- fmt.Errorf("PrintfLine: %v", err)
            return
        }
    }()

    type fields struct {
        Subject      string
        Body         string
        TemplateFile string
        TemplateData interface{}
    }
    type args struct {
        pluginInput *PluginInput
    }
    tests := []struct {
        name    string
        fields  fields
        args    args
        wantErr bool
    }{
        {
            name: "without tls email send testing",
            fields: fields{
                Subject: "SendMail test",
                Body: `
                
                
                    IDP Execution Summary Email
                
                test email
                `,
            },
            args: args{&PluginInput{
                SMTPServer: l.Addr().String(),
                Username:   "[email protected]",
                To:         "[email protected]",
                Cc:         "[email protected]",
            }},
            wantErr: true,
        },
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            email := &Email{
                Subject:      tt.fields.Subject,
                Body:         tt.fields.Body,
                TemplateFile: tt.fields.TemplateFile,
                TemplateData: tt.fields.TemplateData,
            }
            if err := email.SendMail(tt.args.pluginInput); (err != nil) != tt.wantErr {
                log.Print(err)
                t.Errorf("Email.SendMail() error = %v, wantErr %v", err, tt.wantErr)
            }
        })
    }

    err = <-errCh
    if err != nil {
        t.Fatalf("server error: %v", err)
    }
}

运行单元测试后出现“eof”错误。

我不太确定模拟服务器,因为它没有根据客户端请求发送响应的开关。


解决方案


发生这种情况是因为您的实现不知道何时应该关闭活动连接。

看看 smtpmock 包:https://github.com/mocktools/go-smtp-mock。这个模拟服务器已经针对您的情况甚至更多情况设计了:)

好了,本文到此结束,带大家了解了《单元测试:SMTP模拟服务器,用于测试SMTP发送电子邮件》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>