package autoconfig import ( "context" "fmt" "io" "net" "net/http" "strings" "testing" "time" "github.com/stretchr/testify/assert" ) func TestAutoconfig(t *testing.T) { tests := []struct { address string correctConfig *Config }{ { address: "mailbox.org", correctConfig: &Config{ Found: ProtocolIMAP, IMAP: Credentials{ Encryption: EncryptionTLS, Address: "imap.mailbox.org", Port: 993, Username: "john@mailbox.org", }, SMTP: Credentials{ Encryption: EncryptionSTARTTLS, Address: "smtp.mailbox.org", Port: 587, Username: "john@mailbox.org", }, }, }, { address: "poldi1405.srht.site", correctConfig: &Config{ Found: ProtocolIMAP, IMAP: Credentials{ Encryption: EncryptionSTARTTLS, Address: "mail.example.com", Port: 143, Username: "your-username", }, SMTP: Credentials{ Encryption: EncryptionSTARTTLS, Address: "mail.example.com", Port: 587, Username: "your-username", }, }, }, { address: "timeout", correctConfig: nil, }, } httpGet = autoconfigTestGet lookupSRV = customLookupSRV defer func() { httpGet = http.Get lookupSRV = net.LookupSRV }() for _, test := range tests { t.Run(test.address, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) defer cancel() result := make(chan *Config) go getFromAutoconfig(ctx, "john", test.address, result) res := <-result assert.Equal(t, test.correctConfig, res) }) } } func autoconfigTestGet(url string) (*http.Response, error) { switch url { case "https://autoconfig.mailbox.org/mail/config-v1.1.xml?emailaddress=john%40mailbox.org": return &http.Response{ StatusCode: 200, Body: io.NopCloser(strings.NewReader(mailboxAutoconf)), }, nil case "https://poldi1405.srht.site/.well-known/autoconfig/mail/config-v1.1.xml?emailaddress=john%40poldi1405.srht.site": return &http.Response{ StatusCode: 200, Body: io.NopCloser(strings.NewReader(srhtAutoconf)), }, nil case "https://timeout/.well-known/autoconfig/mail/config-v1.1.xml?emailaddress=john%40timeout": <-time.After(5 * time.Minute) return nil, nil default: return nil, fmt.Errorf("%q not prepared", url) } } const ( mailboxAutoconf = ` mailbox.org mailbox.org -- damit Privates privat bleibt mailbox.org imap.mailbox.org 993 SSL password-cleartext %EMAILADDRESS% imap.mailbox.org 143 STARTTLS password-cleartext %EMAILADDRESS% pop3.mailbox.org 995 SSL password-cleartext %EMAILADDRESS% pop3.mailbox.org 110 STARTTLS password-cleartext %EMAILADDRESS% smtp.mailbox.org 465 SSL password-cleartext %EMAILADDRESS% smtp.mailbox.org 587 STARTTLS password-cleartext %EMAILADDRESS% FAQ und Support-Datenbank Frequently Asked Questions (FAQ) ` srhtAutoconf = ` example.com Not valid Not valid mail.example.com 143 STARTTLS your-username password-cleartext mail.example.com 587 STARTTLS your-username password-cleartext ` )