Skip to content

PostgreSQL backup tool with Point-In-Time-Recovery and restore verification

2.8 KB
Raw Blame
package smtp_transport

import (
	"testing"

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

func Test_ParseSender_WithSupportedAndUnsupportedForms_ParsesOrRejects(t *testing.T) {
	testCases := []struct {
		value           string
		expectedName    string
		expectedAddress string
		isRejected      bool
	}{
		{"[email protected]", "Databasus", "[email protected]", false},
		{"Acme Backups <[email protected]>", "Acme Backups", "[email protected]", false},
		{`"Acme, Inc." <[email protected]>`, "Acme, Inc.", "[email protected]", false},
		{"ops at example", "", "", true},
		{"noreply at example.com", "", "", true},
		{"[email protected], [email protected]", "", "", true},
		{"", "", "", true},
	}

	for _, testCase := range testCases {
		t.Run(testCase.value, func(t *testing.T) {
			sender, err := ParseSender(testCase.value)

			if testCase.isRejected {
				require.ErrorIs(t, err, ErrInvalidSender)
				return
			}

			require.NoError(t, err)
			assert.Equal(t, testCase.expectedName, sender.Name)
			assert.Equal(t, testCase.expectedAddress, sender.Address)
		})
	}
}

func Test_ResolveSender_FallsBackFromSenderToAddressUsernameToHost(t *testing.T) {
	testCases := []struct {
		name            string
		from            string
		username        string
		expectedAddress string
	}{
		{"explicit sender wins", "Ops <[email protected]>", "[email protected]", "[email protected]"},
		{"username that is an address", "", "[email protected]", "[email protected]"},
		{"username apikey", "", "apikey", "[email protected]"},
		{"access key ID username", "", "AKIAIOSFODNN7EXAMPLE", "[email protected]"},
		{"username with a display name", "", "Mailer <[email protected]>", "[email protected]"},
		{"no username", "", "", "[email protected]"},
	}

	for _, testCase := range testCases {
		t.Run(testCase.name, func(t *testing.T) {
			sender, err := ResolveSender(testCase.from, testCase.username, "smtp.sendgrid.net")

			require.NoError(t, err)
			assert.Equal(t, testCase.expectedAddress, sender.Address)
		})
	}
}

func Test_ResolveSender_WithUnreadableExplicitSender_Fails(t *testing.T) {
	_, err := ResolveSender("ops at example", "[email protected]", "smtp.example.com")

	require.ErrorIs(t, err, ErrInvalidSender)
}

func Test_ParseRecipient_AcceptsOnlyBareAddress(t *testing.T) {
	testCases := []struct {
		value      string
		isRejected bool
	}{
		{"[email protected]", false},
		{"Admin <[email protected]>", true},
		{"ops at example", true},
		{"[email protected], [email protected]", true},
		{"[email protected]\r\nBcc: [email protected]", true},
	}

	for _, testCase := range testCases {
		t.Run(testCase.value, func(t *testing.T) {
			_, err := ParseRecipient(testCase.value)

			if testCase.isRejected {
				require.ErrorIs(t, err, ErrInvalidRecipient)
				return
			}

			require.NoError(t, err)
		})
	}
}