github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/log/smtp_test.go (about) 1 // Copyright 2023 The GitBundle Inc. All rights reserved. 2 // Copyright 2017 The Gitea Authors. All rights reserved. 3 // Use of this source code is governed by a MIT-style 4 // license that can be found in the LICENSE file. 5 6 package log 7 8 import ( 9 "fmt" 10 "net/smtp" 11 "strings" 12 "testing" 13 "time" 14 15 "github.com/stretchr/testify/assert" 16 ) 17 18 func TestSMTPLogger(t *testing.T) { 19 prefix := "TestPrefix " 20 level := INFO 21 flags := LstdFlags | LUTC | Lfuncname 22 username := "testuser" 23 password := "testpassword" 24 host := "testhost" 25 subject := "testsubject" 26 sendTos := []string{"testto1", "testto2"} 27 28 logger := NewSMTPLogger() 29 smtpLogger, ok := logger.(*SMTPLogger) 30 assert.True(t, ok) 31 32 err := logger.Init(fmt.Sprintf("{\"prefix\":\"%s\",\"level\":\"%s\",\"flags\":%d,\"username\":\"%s\",\"password\":\"%s\",\"host\":\"%s\",\"subject\":\"%s\",\"sendTos\":[\"%s\",\"%s\"]}", prefix, level.String(), flags, username, password, host, subject, sendTos[0], sendTos[1])) 33 assert.NoError(t, err) 34 35 assert.Equal(t, flags, smtpLogger.Flags) 36 assert.Equal(t, level, smtpLogger.Level) 37 assert.Equal(t, level, logger.GetLevel()) 38 39 location, _ := time.LoadLocation("EST") 40 41 date := time.Date(2019, time.January, 13, 22, 3, 30, 15, location) 42 43 dateString := date.UTC().Format("2006/01/02 15:04:05") 44 45 event := Event{ 46 level: INFO, 47 msg: "TEST MSG", 48 caller: "CALLER", 49 filename: "FULL/FILENAME", 50 line: 1, 51 time: date, 52 } 53 54 expected := fmt.Sprintf("%s%s %s:%d:%s [%c] %s\n", prefix, dateString, event.filename, event.line, event.caller, strings.ToUpper(event.level.String())[0], event.msg) 55 56 var envToHost string 57 var envFrom string 58 var envTo []string 59 var envMsg []byte 60 smtpLogger.sendMailFn = func(addr string, a smtp.Auth, from string, to []string, msg []byte) error { 61 envToHost = addr 62 envFrom = from 63 envTo = to 64 envMsg = msg 65 return nil 66 } 67 68 err = logger.LogEvent(&event) 69 assert.NoError(t, err) 70 assert.Equal(t, host, envToHost) 71 assert.Equal(t, username, envFrom) 72 assert.Equal(t, sendTos, envTo) 73 assert.Contains(t, string(envMsg), expected) 74 75 logger.Flush() 76 77 event.level = WARN 78 expected = fmt.Sprintf("%s%s %s:%d:%s [%c] %s\n", prefix, dateString, event.filename, event.line, event.caller, strings.ToUpper(event.level.String())[0], event.msg) 79 err = logger.LogEvent(&event) 80 assert.NoError(t, err) 81 assert.Equal(t, host, envToHost) 82 assert.Equal(t, username, envFrom) 83 assert.Equal(t, sendTos, envTo) 84 assert.Contains(t, string(envMsg), expected) 85 86 logger.Close() 87 }