smtp2shoutrrr/backend_test.go
2025-02-21 09:59:12 +01:00

85 lines
1.9 KiB
Go

package smtp2shoutrrr
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/smtp"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestEmailForwarding(t *testing.T) {
// Start mock ntfy server
notifications := make([]string, 0)
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
// Read body and log
body, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
notifications = append(notifications, string(body))
w.WriteHeader(http.StatusOK)
}))
defer mockServer.Close()
// Configure the SMTP server
config := &Config{
Port: 2525,
Username: "testuser",
Password: "testpass",
Recipients: []ConfigRecipient{
{
Addresses: []string{"test@example.com"},
Target: "generic+" + mockServer.URL + "/?template=json",
},
},
}
ctx := context.Background()
smtpServer := NewSMTPServer(config)
// Start the server
go func() {
if err := smtpServer.Start(ctx); err != nil {
t.Errorf("failed to start server: %v", err)
}
}()
// Give the server time to start
time.Sleep(100 * time.Millisecond)
defer func() {
if err := smtpServer.Stop(ctx); err != nil {
t.Errorf("failed to stop server: %v", err)
}
}()
// Send test email
auth := smtp.PlainAuth("", config.Username, config.Password, "localhost")
err := smtp.SendMail(
fmt.Sprintf("localhost:%d", config.Port),
auth,
"sender@example.com",
[]string{"test@example.com"},
[]byte("Subject: Test Email\r\n\r\nThis is a test email body"),
)
require.NoError(t, err)
// Give some time for the notification to be processed
time.Sleep(100 * time.Millisecond)
// Verify the notification was received
require.Len(t, notifications, 1)
require.Contains(t, notifications[0], "This is a test email body")
}