1
0
mirror of https://github.com/pocketbase/pocketbase.git synced 2025-03-20 06:21:06 +02:00
pocketbase/tests/mailer.go

82 lines
1.6 KiB
Go
Raw Normal View History

2022-07-07 00:19:05 +03:00
package tests
import (
2024-09-29 19:23:19 +03:00
"slices"
2024-07-01 20:53:48 +03:00
"sync"
2022-07-07 00:19:05 +03:00
"github.com/pocketbase/pocketbase/tools/mailer"
)
var _ mailer.Mailer = (*TestMailer)(nil)
2024-09-29 19:23:19 +03:00
// TestMailer is a mock [mailer.Mailer] implementation.
2022-07-07 00:19:05 +03:00
type TestMailer struct {
2024-09-29 19:23:19 +03:00
mux sync.Mutex
messages []*mailer.Message
}
2024-07-01 20:53:48 +03:00
2024-09-29 19:23:19 +03:00
// Send implements [mailer.Mailer] interface.
func (tm *TestMailer) Send(m *mailer.Message) error {
tm.mux.Lock()
defer tm.mux.Unlock()
2023-12-29 23:31:54 +02:00
2024-09-29 19:23:19 +03:00
tm.messages = append(tm.messages, m)
return nil
2022-07-07 00:19:05 +03:00
}
// Reset clears any previously test collected data.
func (tm *TestMailer) Reset() {
2024-07-01 20:53:48 +03:00
tm.mux.Lock()
defer tm.mux.Unlock()
2024-09-29 19:23:19 +03:00
tm.messages = nil
2022-07-07 00:19:05 +03:00
}
2024-09-29 19:23:19 +03:00
// TotalSend returns the total number of sent messages.
func (tm *TestMailer) TotalSend() int {
2024-07-01 20:53:48 +03:00
tm.mux.Lock()
defer tm.mux.Unlock()
2024-09-29 19:23:19 +03:00
return len(tm.messages)
}
2024-09-29 19:23:19 +03:00
// Messages returns a shallow copy of all of the collected test messages.
func (tm *TestMailer) Messages() []*mailer.Message {
tm.mux.Lock()
defer tm.mux.Unlock()
return slices.Clone(tm.messages)
}
// FirstMessage returns a shallow copy of the first sent message.
//
// Returns an empty mailer.Message struct if there are no sent messages.
func (tm *TestMailer) FirstMessage() mailer.Message {
tm.mux.Lock()
defer tm.mux.Unlock()
var m mailer.Message
if len(tm.messages) > 0 {
return *tm.messages[0]
}
return m
}
// LastMessage returns a shallow copy of the last sent message.
//
// Returns an empty mailer.Message struct if there are no sent messages.
func (tm *TestMailer) LastMessage() mailer.Message {
tm.mux.Lock()
defer tm.mux.Unlock()
var m mailer.Message
if len(tm.messages) > 0 {
return *tm.messages[len(tm.messages)-1]
}
return m
2022-07-07 00:19:05 +03:00
}