test(email): make SMTP failure test deterministic (#6113)

This commit is contained in:
Johnny 2026-07-25 09:33:00 +08:00 committed by GitHub
parent 03e34bd0da
commit 7cedcc9c22
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,17 +1,32 @@
package email package email
import ( import (
"net"
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/sync/errgroup" "golang.org/x/sync/errgroup"
) )
func TestSend(t *testing.T) { func TestSend(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
require.NoError(t, err)
defer listener.Close()
connectionClosed := make(chan struct{})
go func() {
defer close(connectionClosed)
conn, err := listener.Accept()
if err == nil {
_ = conn.Close()
}
}()
config := &Config{ config := &Config{
SMTPHost: "smtp.example.com", SMTPHost: "127.0.0.1",
SMTPPort: 587, SMTPPort: listener.Addr().(*net.TCPAddr).Port,
FromEmail: "test@example.com", FromEmail: "test@example.com",
} }
@ -21,12 +36,16 @@ func TestSend(t *testing.T) {
Body: "Test body", Body: "Test body",
} }
// This will fail to connect (no real server), but should validate inputs // The local server closes before sending an SMTP greeting, proving Send made
err := Send(config, message) // it through validation and attempted to create an SMTP client.
// We expect an error because there's no real SMTP server err = Send(config, message)
// But it should be a connection error, not a validation error select {
assert.Error(t, err) case <-connectionClosed:
assert.Contains(t, err.Error(), "dial") case <-time.After(time.Second):
t.Fatal("SMTP listener did not accept a connection")
}
require.Error(t, err)
assert.Contains(t, err.Error(), "failed to create SMTP client")
} }
func TestSendValidation(t *testing.T) { func TestSendValidation(t *testing.T) {