From 2502a3bf679e323c4ae9279ad2debb5492270e00 Mon Sep 17 00:00:00 2001 From: Geno Date: Wed, 23 Jun 2021 22:55:53 +0200 Subject: [PATCH] test(mailer): improve - send and fetch mail --- mailer/main_test.go | 29 +++++++++++++++++++++++++++++ mailer/test.go | 37 ++++++++++++++++++++++++++++++++++--- 2 files changed, 63 insertions(+), 3 deletions(-) diff --git a/mailer/main_test.go b/mailer/main_test.go index 374bb39..d5ad93c 100644 --- a/mailer/main_test.go +++ b/mailer/main_test.go @@ -4,6 +4,8 @@ import ( "testing" "github.com/stretchr/testify/assert" + + "github.com/go-mail/mail" ) func TestSetupAndPing(t *testing.T) { @@ -23,3 +25,30 @@ func TestSetupAndPing(t *testing.T) { assert.Error(err) mock.Close() } + +func TestSend(t *testing.T) { + assert := assert.New(t) + + mock, s := NewFakeServer() + assert.NotNil(mock) + // correct setup + err := s.Setup() + assert.NoError(err) + + m := mail.NewMessage() + m.SetHeader("From", "alex@example.com") + m.SetHeader("To", "bob@example.com", "cora@example.com") + m.SetAddressHeader("Cc", "dan@example.com", "Dan") + m.SetHeader("Subject", "Hello!") + m.SetBody("text/plain", "Hello Bob and Cora!") + m.AddAlternative("text/html", "Hello Bob and Cora!") + + err = s.Dailer.DialAndSend(m) + assert.NoError(err) + + msg := <-mock.MSGS + mock.Close() + assert.Equal("alex@example.com", msg.Header["From"][0]) + assert.Contains(msg.Body, "Bob and Cora!") + +} diff --git a/mailer/test.go b/mailer/test.go index 60bc881..51fe70b 100644 --- a/mailer/test.go +++ b/mailer/test.go @@ -10,8 +10,14 @@ import ( ) type fakeServer struct { - s *Service - l net.Listener + s *Service + l net.Listener + MSGS chan msg +} + +type msg struct { + Header textproto.MIMEHeader + Body string } // NewFakeServer - to get mocked Service for mail-service @@ -28,7 +34,8 @@ func NewFakeServer() (*fakeServer, *Service) { func newFakeServer(s *Service) (*fakeServer, *Service) { fs := &fakeServer{ - s: s, + s: s, + MSGS: make(chan msg), } l, err := net.Listen("tcp", fmt.Sprintf("%s:%d", fs.s.SMTPHost, fs.s.SMTPPort)) if err != nil { @@ -84,6 +91,30 @@ func (fs *fakeServer) handle(conn net.Conn) { case "QUIT": c.Cmd("221 Bye") return + case "DATA": + c.Cmd("354 End data with .") + head, _ := c.ReadMIMEHeader() + data := "" + handleMsgData: + for { + s, _ := c.ReadLine() + switch s { + case ".": + break handleMsgData + default: + data = fmt.Sprintf("%s%s\n", data, s) + c.Cmd("250 Ok") + } + + } + fs.MSGS <- msg{ + Header: head, + Body: data, + } + default: + // fmt.Println(s) + // TODO : MAIL FROM: and RCPT TO: + c.Cmd("250 Ok") } } }