aboutsummaryrefslogtreecommitdiffstats
path: root/modules/log/smtp_test.go
blob: d7d28f28f83bdb7196d31af08acaae39ab9ab271 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Copyright 2019 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package log

import (
	"fmt"
	"net/smtp"
	"strings"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
)

func TestSMTPLogger(t *testing.T) {
	prefix := "TestPrefix "
	level := INFO
	flags := LstdFlags | LUTC | Lfuncname
	username := "testuser"
	password := "testpassword"
	host := "testhost"
	subject := "testsubject"
	sendTos := []string{"testto1", "testto2"}

	logger := NewSMTPLogger()
	smtpLogger, ok := logger.(*SMTPLogger)
	assert.True(t, ok)

	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]))
	assert.NoError(t, err)

	assert.Equal(t, flags, smtpLogger.Flags)
	assert.Equal(t, level, smtpLogger.Level)
	assert.Equal(t, level, logger.GetLevel())

	location, _ := time.LoadLocation("EST")

	date := time.Date(2019, time.January, 13, 22, 3, 30, 15, location)

	dateString := date.UTC().Format("2006/01/02 15:04:05")

	event := Event{
		level:    INFO,
		msg:      "TEST MSG",
		caller:   "CALLER",
		filename: "FULL/FILENAME",
		line:     1,
		time:     date,
	}

	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)

	var envToHost string
	var envFrom string
	var envTo []string
	var envMsg []byte
	smtpLogger.sendMailFn = func(addr string, a smtp.Auth, from string, to []string, msg []byte) error {
		envToHost = addr
		envFrom = from
		envTo = to
		envMsg = msg
		return nil
	}

	err = logger.LogEvent(&event)
	assert.NoError(t, err)
	assert.Equal(t, host, envToHost)
	assert.Equal(t, username, envFrom)
	assert.Equal(t, sendTos, envTo)
	assert.Contains(t, string(envMsg), expected)

	logger.Flush()

	event.level = WARN
	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)
	err = logger.LogEvent(&event)
	assert.NoError(t, err)
	assert.Equal(t, host, envToHost)
	assert.Equal(t, username, envFrom)
	assert.Equal(t, sendTos, envTo)
	assert.Contains(t, string(envMsg), expected)

	logger.Close()
}