Homogenization of the DNS provider tests (#671)

* refactor: min TTL
* refactor: sandbox.
* refactor: tests homogenization.
* refactor: missing require.
This commit is contained in:
Ludovic Fernandez 2018-10-12 19:29:18 +02:00 committed by GitHub
parent 01c63ec08d
commit 122c354163
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
61 changed files with 4730 additions and 1810 deletions

View file

@ -7,9 +7,11 @@ const (
// HTTP01 is the "http-01" ACME challenge https://github.com/ietf-wg-acme/acme/blob/master/draft-ietf-acme-acme.md#http // HTTP01 is the "http-01" ACME challenge https://github.com/ietf-wg-acme/acme/blob/master/draft-ietf-acme-acme.md#http
// Note: HTTP01ChallengePath returns the URL path to fulfill this challenge // Note: HTTP01ChallengePath returns the URL path to fulfill this challenge
HTTP01 = Challenge("http-01") HTTP01 = Challenge("http-01")
// DNS01 is the "dns-01" ACME challenge https://github.com/ietf-wg-acme/acme/blob/master/draft-ietf-acme-acme.md#dns // DNS01 is the "dns-01" ACME challenge https://github.com/ietf-wg-acme/acme/blob/master/draft-ietf-acme-acme.md#dns
// Note: DNS01Record returns a DNS record which will fulfill this challenge // Note: DNS01Record returns a DNS record which will fulfill this challenge
DNS01 = Challenge("dns-01") DNS01 = Challenge("dns-01")
// TLSALPN01 is the "tls-alpn-01" ACME challenge https://tools.ietf.org/html/draft-ietf-acme-tls-alpn-01 // TLSALPN01 is the "tls-alpn-01" ACME challenge https://tools.ietf.org/html/draft-ietf-acme-tls-alpn-01
TLSALPN01 = Challenge("tls-alpn-01") TLSALPN01 = Challenge("tls-alpn-01")
) )

View file

@ -412,7 +412,7 @@ DNSNames:
// the whole certificate will fail. // the whole certificate will fail.
func (c *Client) ObtainCertificate(domains []string, bundle bool, privKey crypto.PrivateKey, mustStaple bool) (*CertificateResource, error) { func (c *Client) ObtainCertificate(domains []string, bundle bool, privKey crypto.PrivateKey, mustStaple bool) (*CertificateResource, error) {
if len(domains) == 0 { if len(domains) == 0 {
return nil, errors.New("No domains to obtain a certificate for") return nil, errors.New("no domains to obtain a certificate for")
} }
if bundle { if bundle {

View file

@ -217,7 +217,7 @@ func TestValidate(t *testing.T) {
err := validate(j, "example.com", ts.URL, challenge{Type: "http-01", Token: "token"}) err := validate(j, "example.com", ts.URL, challenge{Type: "http-01", Token: "token"})
if test.want == "" { if test.want == "" {
assert.NoError(t, err) require.NoError(t, err)
} else { } else {
assert.Error(t, err) assert.Error(t, err)
assert.Contains(t, err.Error(), test.want) assert.Contains(t, err.Error(), test.want)
@ -262,7 +262,7 @@ func TestGetChallenges(t *testing.T) {
require.NoError(t, err, "Could not create client") require.NoError(t, err, "Could not create client")
_, err = client.createOrderForIdentifiers([]string{"example.com"}) _, err = client.createOrderForIdentifiers([]string{"example.com"})
assert.NoError(t, err) require.NoError(t, err)
} }
func TestResolveAccountByKey(t *testing.T) { func TestResolveAccountByKey(t *testing.T) {

View file

@ -48,7 +48,7 @@ func TestHTTPChallenge(t *testing.T) {
clientChallenge := challenge{Type: string(HTTP01), Token: "http1"} clientChallenge := challenge{Type: string(HTTP01), Token: "http1"}
err = solver.Solve(clientChallenge, "localhost:23457") err = solver.Solve(clientChallenge, "localhost:23457")
assert.NoError(t, err) require.NoError(t, err)
} }
func TestHTTPChallengeInvalidPort(t *testing.T) { func TestHTTPChallengeInvalidPort(t *testing.T) {

View file

@ -20,7 +20,7 @@ func TestTLSALPNChallenge(t *testing.T) {
conn, err := tls.Dial("tcp", domain, &tls.Config{ conn, err := tls.Dial("tcp", domain, &tls.Config{
InsecureSkipVerify: true, InsecureSkipVerify: true,
}) })
assert.NoError(t, err, "Expected to connect to challenge server without an error") require.NoError(t, err, "Expected to connect to challenge server without an error")
// Expect the server to only return one certificate // Expect the server to only return one certificate
connState := conn.ConnectionState() connState := conn.ConnectionState()
@ -67,7 +67,7 @@ func TestTLSALPNChallenge(t *testing.T) {
clientChallenge := challenge{Type: string(TLSALPN01), Token: "tlsalpn1"} clientChallenge := challenge{Type: string(TLSALPN01), Token: "tlsalpn1"}
err = solver.Solve(clientChallenge, domain) err = solver.Solve(clientChallenge, domain)
assert.NoError(t, err) require.NoError(t, err)
} }
func TestTLSALPNChallengeInvalidPort(t *testing.T) { func TestTLSALPNChallengeInvalidPort(t *testing.T) {

4
cli.go
View file

@ -87,7 +87,7 @@ func main() {
{ {
Name: "dnshelp", Name: "dnshelp",
Usage: "Shows additional help for the --dns global option", Usage: "Shows additional help for the --dns global option",
Action: dnshelp, Action: dnsHelp,
}, },
} }
@ -187,7 +187,7 @@ func main() {
} }
} }
func dnshelp(c *cli.Context) error { func dnsHelp(_ *cli.Context) error {
fmt.Printf( fmt.Printf(
`Credentials for DNS providers must be passed through environment variables. `Credentials for DNS providers must be passed through environment variables.

View file

@ -5,91 +5,171 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/require"
) )
var ( var (
alidnsLiveTest bool liveTest bool
alidnsAPIKey string envTestAPIKey string
alidnsSecretKey string envTestSecretKey string
alidnsDomain string envTestDomain string
) )
func init() { func init() {
alidnsAPIKey = os.Getenv("ALICLOUD_ACCESS_KEY") envTestAPIKey = os.Getenv("ALICLOUD_ACCESS_KEY")
alidnsSecretKey = os.Getenv("ALICLOUD_SECRET_KEY") envTestSecretKey = os.Getenv("ALICLOUD_SECRET_KEY")
alidnsDomain = os.Getenv("ALIDNS_DOMAIN") envTestDomain = os.Getenv("ALIDNS_DOMAIN")
if len(alidnsAPIKey) > 0 && len(alidnsSecretKey) > 0 && len(alidnsDomain) > 0 { if len(envTestAPIKey) > 0 && len(envTestSecretKey) > 0 && len(envTestDomain) > 0 {
alidnsLiveTest = true liveTest = true
} }
} }
func restoreEnv() { func restoreEnv() {
os.Setenv("ALICLOUD_ACCESS_KEY", alidnsAPIKey) os.Setenv("ALICLOUD_ACCESS_KEY", envTestAPIKey)
os.Setenv("ALICLOUD_SECRET_KEY", alidnsSecretKey) os.Setenv("ALICLOUD_SECRET_KEY", envTestSecretKey)
} }
func TestNewDNSProviderValid(t *testing.T) { func TestNewDNSProvider(t *testing.T) {
defer restoreEnv() testCases := []struct {
os.Setenv("ALICLOUD_ACCESS_KEY", "") desc string
os.Setenv("ALICLOUD_SECRET_KEY", "") envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
"ALICLOUD_ACCESS_KEY": "123",
"ALICLOUD_SECRET_KEY": "456",
},
},
{
desc: "missing credentials",
envVars: map[string]string{
"ALICLOUD_ACCESS_KEY": "",
"ALICLOUD_SECRET_KEY": "",
},
expected: "alicloud: some credentials information are missing: ALICLOUD_ACCESS_KEY,ALICLOUD_SECRET_KEY",
},
{
desc: "missing access key",
envVars: map[string]string{
"ALICLOUD_ACCESS_KEY": "",
"ALICLOUD_SECRET_KEY": "456",
},
expected: "alicloud: some credentials information are missing: ALICLOUD_ACCESS_KEY",
},
{
desc: "missing secret key",
envVars: map[string]string{
"ALICLOUD_ACCESS_KEY": "123",
"ALICLOUD_SECRET_KEY": "",
},
expected: "alicloud: some credentials information are missing: ALICLOUD_SECRET_KEY",
},
}
config := NewDefaultConfig() for _, test := range testCases {
config.APIKey = "123" t.Run(test.desc, func(t *testing.T) {
config.SecretKey = "123" defer restoreEnv()
for key, value := range test.envVars {
if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
}
_, err := NewDNSProviderConfig(config) p, err := NewDNSProvider()
assert.NoError(t, err)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
} }
func TestNewDNSProviderValidEnv(t *testing.T) { func TestNewDNSProviderConfig(t *testing.T) {
defer restoreEnv() testCases := []struct {
os.Setenv("ALICLOUD_ACCESS_KEY", "123") desc string
os.Setenv("ALICLOUD_SECRET_KEY", "123") apiKey string
secretKey string
expected string
}{
{
desc: "success",
apiKey: "123",
secretKey: "456",
},
{
desc: "missing credentials",
expected: "alicloud: credentials missing",
},
{
desc: "missing api key",
secretKey: "456",
expected: "alicloud: credentials missing",
},
{
desc: "missing secret key",
apiKey: "123",
expected: "alicloud: credentials missing",
},
}
_, err := NewDNSProvider() for _, test := range testCases {
assert.NoError(t, err) t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
os.Unsetenv("ALICLOUD_ACCESS_KEY")
os.Unsetenv("ALICLOUD_SECRET_KEY")
config := NewDefaultConfig()
config.APIKey = test.apiKey
config.SecretKey = test.secretKey
p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
} }
func TestNewDNSProviderMissingCredErr(t *testing.T) { func TestLivePresent(t *testing.T) {
defer restoreEnv() if !liveTest {
os.Setenv("ALICLOUD_ACCESS_KEY", "")
os.Setenv("ALICLOUD_SECRET_KEY", "")
_, err := NewDNSProvider()
assert.EqualError(t, err, "alicloud: some credentials information are missing: ALICLOUD_ACCESS_KEY,ALICLOUD_SECRET_KEY")
}
func TestCloudXNSPresent(t *testing.T) {
if !alidnsLiveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
config := NewDefaultConfig() restoreEnv()
config.APIKey = alidnsAPIKey provider, err := NewDNSProvider()
config.SecretKey = alidnsSecretKey require.NoError(t, err)
provider, err := NewDNSProviderConfig(config) err = provider.Present(envTestDomain, "", "123d==")
assert.NoError(t, err) require.NoError(t, err)
err = provider.Present(alidnsDomain, "", "123d==")
assert.NoError(t, err)
} }
func TestLivednspodCleanUp(t *testing.T) { func TestLiveCleanUp(t *testing.T) {
if !alidnsLiveTest { if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
time.Sleep(time.Second * 1) restoreEnv()
provider, err := NewDNSProvider()
require.NoError(t, err)
config := NewDefaultConfig() time.Sleep(1 * time.Second)
config.APIKey = alidnsAPIKey
config.SecretKey = alidnsSecretKey
provider, err := NewDNSProviderConfig(config) err = provider.CleanUp(envTestDomain, "", "123d==")
assert.NoError(t, err) require.NoError(t, err)
err = provider.CleanUp(alidnsDomain, "", "123d==")
assert.NoError(t, err)
} }

View file

@ -5,36 +5,185 @@ import (
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"os"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
var fakeAuroraDNSUserID = "asdf1234" var (
var fakeAuroraDNSKey = "key" envTestUserID string
envTestKey string
)
func TestAuroraDNSPresent(t *testing.T) { func init() {
var requestReceived bool envTestUserID = os.Getenv("AURORA_USER_ID")
envTestKey = os.Getenv("AURORA_KEY")
}
mock := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { func restoreEnv() {
if r.Method == http.MethodGet && r.URL.Path == "/zones" { os.Setenv("AURORA_USER_ID", envTestUserID)
w.WriteHeader(http.StatusCreated) os.Setenv("AURORA_KEY", envTestKey)
fmt.Fprintf(w, `[{ }
func setupTest() (*DNSProvider, *http.ServeMux, func()) {
handler := http.NewServeMux()
server := httptest.NewServer(handler)
config := NewDefaultConfig()
config.UserID = "asdf1234"
config.Key = "key"
config.BaseURL = server.URL
provider, err := NewDNSProviderConfig(config)
if err != nil {
panic(err)
}
return provider, handler, server.Close
}
func TestNewDNSProvider(t *testing.T) {
testCases := []struct {
desc string
envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
"AURORA_USER_ID": "123",
"AURORA_KEY": "456",
},
},
{
desc: "missing credentials",
envVars: map[string]string{
"AURORA_USER_ID": "",
"AURORA_KEY": "",
},
expected: "aurora: some credentials information are missing: AURORA_USER_ID,AURORA_KEY",
},
{
desc: "missing user id",
envVars: map[string]string{
"AURORA_USER_ID": "",
"AURORA_KEY": "456",
},
expected: "aurora: some credentials information are missing: AURORA_USER_ID",
},
{
desc: "missing key",
envVars: map[string]string{
"AURORA_USER_ID": "123",
"AURORA_KEY": "",
},
expected: "aurora: some credentials information are missing: AURORA_KEY",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
for key, value := range test.envVars {
if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
}
p, err := NewDNSProvider()
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
func TestNewDNSProviderConfig(t *testing.T) {
testCases := []struct {
desc string
userID string
key string
expected string
}{
{
desc: "success",
userID: "123",
key: "456",
},
{
desc: "missing credentials",
userID: "",
key: "",
expected: "aurora: some credentials information are missing",
},
{
desc: "missing user id",
userID: "",
key: "456",
expected: "aurora: some credentials information are missing",
},
{
desc: "missing key",
userID: "123",
key: "",
expected: "aurora: some credentials information are missing",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
os.Unsetenv("AURORA_USER_ID")
os.Unsetenv("AURORA_KEY")
config := NewDefaultConfig()
config.UserID = test.userID
config.Key = test.key
p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
func TestDNSProvider_Present(t *testing.T) {
provider, mux, tearDown := setupTest()
defer tearDown()
mux.HandleFunc("/zones", func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodGet, r.Method, "method")
w.WriteHeader(http.StatusCreated)
fmt.Fprintf(w, `[{
"id": "c56a4180-65aa-42ec-a945-5fd21dec0538", "id": "c56a4180-65aa-42ec-a945-5fd21dec0538",
"name": "example.com" "name": "example.com"
}]`) }]`)
return })
}
requestReceived = true mux.HandleFunc("/zones/c56a4180-65aa-42ec-a945-5fd21dec0538/records", func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodPost, r.Method)
assert.Equal(t, http.MethodPost, r.Method, "method")
assert.Equal(t, "/zones/c56a4180-65aa-42ec-a945-5fd21dec0538/records", r.URL.Path, "Path")
assert.Equal(t, "application/json", r.Header.Get("Content-Type"), "Content-Type") assert.Equal(t, "application/json", r.Header.Get("Content-Type"), "Content-Type")
reqBody, err := ioutil.ReadAll(r.Body) reqBody, err := ioutil.ReadAll(r.Body)
require.NoError(t, err, "reading request body") require.NoError(t, err)
assert.Equal(t, `{"type":"TXT","name":"_acme-challenge","content":"w6uP8Tcg6K2QR905Rms8iXTlksL6OD1KOWBxTK7wxPI","ttl":300}`, string(reqBody)) assert.Equal(t, `{"type":"TXT","name":"_acme-challenge","content":"w6uP8Tcg6K2QR905Rms8iXTlksL6OD1KOWBxTK7wxPI","ttl":300}`, string(reqBody))
w.WriteHeader(http.StatusCreated) w.WriteHeader(http.StatusCreated)
@ -44,74 +193,50 @@ func TestAuroraDNSPresent(t *testing.T) {
"name": "_acme-challenge", "name": "_acme-challenge",
"ttl": 300 "ttl": 300
}`) }`)
})) })
defer mock.Close() err := provider.Present("example.com", "", "foobar")
config := NewDefaultConfig()
config.UserID = fakeAuroraDNSUserID
config.Key = fakeAuroraDNSKey
config.BaseURL = mock.URL
provider, err := NewDNSProviderConfig(config)
require.NoError(t, err)
require.NotNil(t, provider)
err = provider.Present("example.com", "", "foobar")
require.NoError(t, err, "fail to create TXT record") require.NoError(t, err, "fail to create TXT record")
assert.True(t, requestReceived, "Expected request to be received by mock backend, but it wasn't")
} }
func TestAuroraDNSCleanUp(t *testing.T) { func TestDNSProvider_CleanUp(t *testing.T) {
var requestReceived bool provider, mux, tearDown := setupTest()
defer tearDown()
mock := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("/zones", func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet && r.URL.Path == "/zones" { assert.Equal(t, http.MethodGet, r.Method)
w.WriteHeader(http.StatusCreated)
fmt.Fprintf(w, `[{ w.WriteHeader(http.StatusCreated)
fmt.Fprintf(w, `[{
"id": "c56a4180-65aa-42ec-a945-5fd21dec0538", "id": "c56a4180-65aa-42ec-a945-5fd21dec0538",
"name": "example.com" "name": "example.com"
}]`) }]`)
return })
}
if r.Method == http.MethodPost && r.URL.Path == "/zones/c56a4180-65aa-42ec-a945-5fd21dec0538/records" { mux.HandleFunc("/zones/c56a4180-65aa-42ec-a945-5fd21dec0538/records", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusCreated) assert.Equal(t, http.MethodPost, r.Method)
fmt.Fprintf(w, `{
w.WriteHeader(http.StatusCreated)
fmt.Fprintf(w, `{
"id": "ec56a4180-65aa-42ec-a945-5fd21dec0538", "id": "ec56a4180-65aa-42ec-a945-5fd21dec0538",
"type": "TXT", "type": "TXT",
"name": "_acme-challenge", "name": "_acme-challenge",
"ttl": 300 "ttl": 300
}`) }`)
return })
}
requestReceived = true mux.HandleFunc("/zones/c56a4180-65aa-42ec-a945-5fd21dec0538/records/ec56a4180-65aa-42ec-a945-5fd21dec0538", func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodDelete, r.Method)
assert.Equal(t, http.MethodDelete, r.Method, "method")
assert.Equal(t, "/zones/c56a4180-65aa-42ec-a945-5fd21dec0538/records/ec56a4180-65aa-42ec-a945-5fd21dec0538", r.URL.Path, "Path")
assert.Equal(t, "application/json", r.Header.Get("Content-Type"), "Content-Type") assert.Equal(t, "application/json", r.Header.Get("Content-Type"), "Content-Type")
w.WriteHeader(http.StatusCreated) w.WriteHeader(http.StatusCreated)
fmt.Fprintf(w, `{}`) fmt.Fprintf(w, `{}`)
})) })
defer mock.Close()
config := NewDefaultConfig() err := provider.Present("example.com", "", "foobar")
config.UserID = fakeAuroraDNSUserID
config.Key = fakeAuroraDNSKey
config.BaseURL = mock.URL
provider, err := NewDNSProviderConfig(config)
require.NoError(t, err)
require.NotNil(t, provider)
err = provider.Present("example.com", "", "foobar")
require.NoError(t, err, "fail to create TXT record") require.NoError(t, err, "fail to create TXT record")
err = provider.CleanUp("example.com", "", "foobar") err = provider.CleanUp("example.com", "", "foobar")
require.NoError(t, err, "fail to remove TXT record") require.NoError(t, err, "fail to remove TXT record")
assert.True(t, requestReceived, "Expected request to be received by mock backend, but it wasn't")
} }

View file

@ -5,112 +5,270 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/require"
) )
var ( var (
azureLiveTest bool liveTest bool
azureClientID string envTestClientID string
azureClientSecret string envTestClientSecret string
azureSubscriptionID string envTestSubscriptionID string
azureTenantID string envTestTenantID string
azureResourceGroup string envTestResourceGroup string
azureDomain string envTestDomain string
) )
func init() { func init() {
azureClientID = os.Getenv("AZURE_CLIENT_ID") envTestClientID = os.Getenv("AZURE_CLIENT_ID")
azureClientSecret = os.Getenv("AZURE_CLIENT_SECRET") envTestClientSecret = os.Getenv("AZURE_CLIENT_SECRET")
azureSubscriptionID = os.Getenv("AZURE_SUBSCRIPTION_ID") envTestSubscriptionID = os.Getenv("AZURE_SUBSCRIPTION_ID")
azureTenantID = os.Getenv("AZURE_TENANT_ID") envTestTenantID = os.Getenv("AZURE_TENANT_ID")
azureResourceGroup = os.Getenv("AZURE_RESOURCE_GROUP") envTestResourceGroup = os.Getenv("AZURE_RESOURCE_GROUP")
azureDomain = os.Getenv("AZURE_DOMAIN") envTestDomain = os.Getenv("AZURE_DOMAIN")
if len(azureClientID) > 0 && len(azureClientSecret) > 0 {
azureLiveTest = true if len(envTestClientID) > 0 && len(envTestClientSecret) > 0 {
liveTest = true
} }
} }
func restoreEnv() { func restoreEnv() {
os.Setenv("AZURE_CLIENT_ID", azureClientID) os.Setenv("AZURE_CLIENT_ID", envTestClientID)
os.Setenv("AZURE_SUBSCRIPTION_ID", azureSubscriptionID) os.Setenv("AZURE_CLIENT_SECRET", envTestClientSecret)
os.Setenv("AZURE_SUBSCRIPTION_ID", envTestSubscriptionID)
os.Setenv("AZURE_TENANT_ID", envTestTenantID)
os.Setenv("AZURE_RESOURCE_GROUP", envTestResourceGroup)
} }
func TestNewDNSProviderValid(t *testing.T) { func TestNewDNSProvider(t *testing.T) {
if !azureLiveTest { testCases := []struct {
t.Skip("skipping live test (requires credentials)") desc string
envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
"AZURE_CLIENT_ID": "A",
"AZURE_CLIENT_SECRET": "B",
"AZURE_SUBSCRIPTION_ID": "C",
"AZURE_TENANT_ID": "D",
"AZURE_RESOURCE_GROUP": "E",
},
},
{
desc: "missing credentials",
envVars: map[string]string{
"AZURE_CLIENT_ID": "",
"AZURE_CLIENT_SECRET": "",
"AZURE_SUBSCRIPTION_ID": "",
"AZURE_TENANT_ID": "",
"AZURE_RESOURCE_GROUP": "",
},
expected: "azure: some credentials information are missing: AZURE_CLIENT_ID,AZURE_CLIENT_SECRET,AZURE_SUBSCRIPTION_ID,AZURE_TENANT_ID,AZURE_RESOURCE_GROUP",
},
{
desc: "missing client id",
envVars: map[string]string{
"AZURE_CLIENT_ID": "",
"AZURE_CLIENT_SECRET": "B",
"AZURE_SUBSCRIPTION_ID": "C",
"AZURE_TENANT_ID": "D",
"AZURE_RESOURCE_GROUP": "E",
},
expected: "azure: some credentials information are missing: AZURE_CLIENT_ID",
},
{
desc: "missing client secret",
envVars: map[string]string{
"AZURE_CLIENT_ID": "A",
"AZURE_CLIENT_SECRET": "",
"AZURE_SUBSCRIPTION_ID": "C",
"AZURE_TENANT_ID": "D",
"AZURE_RESOURCE_GROUP": "E",
},
expected: "azure: some credentials information are missing: AZURE_CLIENT_SECRET",
},
{
desc: "missing subscription id",
envVars: map[string]string{
"AZURE_CLIENT_ID": "A",
"AZURE_CLIENT_SECRET": "B",
"AZURE_SUBSCRIPTION_ID": "",
"AZURE_TENANT_ID": "D",
"AZURE_RESOURCE_GROUP": "E",
},
expected: "azure: some credentials information are missing: AZURE_SUBSCRIPTION_ID",
},
{
desc: "missing tenant id",
envVars: map[string]string{
"AZURE_CLIENT_ID": "A",
"AZURE_CLIENT_SECRET": "B",
"AZURE_SUBSCRIPTION_ID": "C",
"AZURE_TENANT_ID": "",
"AZURE_RESOURCE_GROUP": "E",
},
expected: "azure: some credentials information are missing: AZURE_TENANT_ID",
},
{
desc: "missing resource group",
envVars: map[string]string{
"AZURE_CLIENT_ID": "A",
"AZURE_CLIENT_SECRET": "B",
"AZURE_SUBSCRIPTION_ID": "C",
"AZURE_TENANT_ID": "D",
"AZURE_RESOURCE_GROUP": "",
},
expected: "azure: some credentials information are missing: AZURE_RESOURCE_GROUP",
},
} }
defer restoreEnv() for _, test := range testCases {
os.Setenv("AZURE_CLIENT_ID", "") t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
for key, value := range test.envVars {
if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
}
config := NewDefaultConfig() p, err := NewDNSProvider()
config.ClientID = azureClientID
config.ClientSecret = azureClientSecret
config.SubscriptionID = azureSubscriptionID
config.TenantID = azureTenantID
config.ResourceGroup = azureResourceGroup
_, err := NewDNSProviderConfig(config) if len(test.expected) == 0 {
assert.NoError(t, err) require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
} else {
require.EqualError(t, err, test.expected)
}
})
}
} }
func TestNewDNSProviderValidEnv(t *testing.T) { func TestNewDNSProviderConfig(t *testing.T) {
if !azureLiveTest { testCases := []struct {
t.Skip("skipping live test (requires credentials)") desc string
clientID string
clientSecret string
subscriptionID string
tenantID string
resourceGroup string
expected string
}{
{
desc: "success",
clientID: "A",
clientSecret: "B",
subscriptionID: "C",
tenantID: "D",
resourceGroup: "E",
},
{
desc: "missing credentials",
expected: "azure: some credentials information are missing",
},
{
desc: "missing client id",
clientID: "",
clientSecret: "B",
subscriptionID: "C",
tenantID: "D",
resourceGroup: "E",
expected: "azure: some credentials information are missing",
},
{
desc: "missing client secret",
clientID: "A",
clientSecret: "",
subscriptionID: "C",
tenantID: "D",
resourceGroup: "E",
expected: "azure: some credentials information are missing",
},
{
desc: "missing subscription id",
clientID: "A",
clientSecret: "B",
subscriptionID: "",
tenantID: "D",
resourceGroup: "E",
expected: "azure: some credentials information are missing",
},
{
desc: "missing tenant id",
clientID: "A",
clientSecret: "B",
subscriptionID: "C",
tenantID: "",
resourceGroup: "E",
expected: "azure: some credentials information are missing",
},
{
desc: "missing resource group",
clientID: "A",
clientSecret: "B",
subscriptionID: "C",
tenantID: "D",
resourceGroup: "",
expected: "azure: some credentials information are missing",
},
} }
defer restoreEnv() for _, test := range testCases {
os.Setenv("AZURE_CLIENT_ID", "other") t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
os.Unsetenv("AZURE_CLIENT_ID")
os.Unsetenv("AZURE_CLIENT_SECRET")
os.Unsetenv("AZURE_SUBSCRIPTION_ID")
os.Unsetenv("AZURE_TENANT_ID")
os.Unsetenv("AZURE_RESOURCE_GROUP")
_, err := NewDNSProvider() config := NewDefaultConfig()
assert.NoError(t, err) config.ClientID = test.clientID
config.ClientSecret = test.clientSecret
config.SubscriptionID = test.subscriptionID
config.TenantID = test.tenantID
config.ResourceGroup = test.resourceGroup
p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
} else {
require.EqualError(t, err, test.expected)
}
})
}
} }
func TestNewDNSProviderMissingCredErr(t *testing.T) { func TestLivePresent(t *testing.T) {
defer restoreEnv() if !liveTest {
os.Setenv("AZURE_SUBSCRIPTION_ID", "")
_, err := NewDNSProvider()
assert.EqualError(t, err, "azure: some credentials information are missing: AZURE_CLIENT_ID,AZURE_CLIENT_SECRET,AZURE_SUBSCRIPTION_ID,AZURE_TENANT_ID,AZURE_RESOURCE_GROUP")
}
func TestLiveAzurePresent(t *testing.T) {
if !azureLiveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
config := NewDefaultConfig() restoreEnv()
config.ClientID = azureClientID provider, err := NewDNSProvider()
config.ClientSecret = azureClientSecret require.NoError(t, err)
config.SubscriptionID = azureSubscriptionID
config.TenantID = azureTenantID
config.ResourceGroup = azureResourceGroup
provider, err := NewDNSProviderConfig(config) err = provider.Present(envTestDomain, "", "123d==")
assert.NoError(t, err) require.NoError(t, err)
err = provider.Present(azureDomain, "", "123d==")
assert.NoError(t, err)
} }
func TestLiveAzureCleanUp(t *testing.T) { func TestLiveCleanUp(t *testing.T) {
if !azureLiveTest { if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
config := NewDefaultConfig() restoreEnv()
config.ClientID = azureClientID provider, err := NewDNSProvider()
config.ClientSecret = azureClientSecret require.NoError(t, err)
config.SubscriptionID = azureSubscriptionID
config.TenantID = azureTenantID
config.ResourceGroup = azureResourceGroup
provider, err := NewDNSProviderConfig(config) time.Sleep(1 * time.Second)
time.Sleep(time.Second * 1) err = provider.CleanUp(envTestDomain, "", "123d==")
require.NoError(t, err)
assert.NoError(t, err)
err = provider.CleanUp(azureDomain, "", "123d==")
assert.NoError(t, err)
} }

View file

@ -3,61 +3,277 @@ package bluecat
import ( import (
"os" "os"
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/require"
) )
var ( var (
bluecatLiveTest bool liveTest bool
bluecatServer string envTestServer string
bluecatUserName string envTestUserName string
bluecatPassword string envTestPassword string
bluecatConfigName string envTestConfigName string
bluecatDNSView string envTestDNSView string
bluecatDomain string envTestDomain string
) )
func init() { func init() {
bluecatServer = os.Getenv("BLUECAT_SERVER_URL") envTestServer = os.Getenv("BLUECAT_SERVER_URL")
bluecatUserName = os.Getenv("BLUECAT_USER_NAME") envTestUserName = os.Getenv("BLUECAT_USER_NAME")
bluecatPassword = os.Getenv("BLUECAT_PASSWORD") envTestPassword = os.Getenv("BLUECAT_PASSWORD")
bluecatDomain = os.Getenv("BLUECAT_DOMAIN") envTestDomain = os.Getenv("BLUECAT_DOMAIN")
bluecatConfigName = os.Getenv("BLUECAT_CONFIG_NAME") envTestConfigName = os.Getenv("BLUECAT_CONFIG_NAME")
bluecatDNSView = os.Getenv("BLUECAT_DNS_VIEW") envTestDNSView = os.Getenv("BLUECAT_DNS_VIEW")
if len(bluecatServer) > 0 &&
len(bluecatDomain) > 0 && if len(envTestServer) > 0 &&
len(bluecatUserName) > 0 && len(envTestDomain) > 0 &&
len(bluecatPassword) > 0 && len(envTestUserName) > 0 &&
len(bluecatConfigName) > 0 && len(envTestPassword) > 0 &&
len(bluecatDNSView) > 0 { len(envTestConfigName) > 0 &&
bluecatLiveTest = true len(envTestDNSView) > 0 {
liveTest = true
} }
} }
func TestLiveBluecatPresent(t *testing.T) { func restoreEnv() {
if !bluecatLiveTest { os.Setenv("BLUECAT_SERVER_URL", envTestServer)
os.Setenv("BLUECAT_USER_NAME", envTestUserName)
os.Setenv("BLUECAT_PASSWORD", envTestPassword)
os.Setenv("BLUECAT_CONFIG_NAME", envTestConfigName)
os.Setenv("BLUECAT_DNS_VIEW", envTestDNSView)
}
func TestNewDNSProvider(t *testing.T) {
testCases := []struct {
desc string
envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
"BLUECAT_SERVER_URL": "http://localhost",
"BLUECAT_USER_NAME": "A",
"BLUECAT_PASSWORD": "B",
"BLUECAT_CONFIG_NAME": "C",
"BLUECAT_DNS_VIEW": "D",
},
},
{
desc: "missing credentials",
envVars: map[string]string{
"BLUECAT_SERVER_URL": "",
"BLUECAT_USER_NAME": "",
"BLUECAT_PASSWORD": "",
"BLUECAT_CONFIG_NAME": "",
"BLUECAT_DNS_VIEW": "",
},
expected: "bluecat: some credentials information are missing: BLUECAT_SERVER_URL,BLUECAT_USER_NAME,BLUECAT_PASSWORD,BLUECAT_CONFIG_NAME,BLUECAT_DNS_VIEW",
},
{
desc: "missing server url",
envVars: map[string]string{
"BLUECAT_SERVER_URL": "",
"BLUECAT_USER_NAME": "A",
"BLUECAT_PASSWORD": "B",
"BLUECAT_CONFIG_NAME": "C",
"BLUECAT_DNS_VIEW": "D",
},
expected: "bluecat: some credentials information are missing: BLUECAT_SERVER_URL",
},
{
desc: "missing username",
envVars: map[string]string{
"BLUECAT_SERVER_URL": "http://localhost",
"BLUECAT_USER_NAME": "",
"BLUECAT_PASSWORD": "B",
"BLUECAT_CONFIG_NAME": "C",
"BLUECAT_DNS_VIEW": "D",
},
expected: "bluecat: some credentials information are missing: BLUECAT_USER_NAME",
},
{
desc: "missing password",
envVars: map[string]string{
"BLUECAT_SERVER_URL": "http://localhost",
"BLUECAT_USER_NAME": "A",
"BLUECAT_PASSWORD": "",
"BLUECAT_CONFIG_NAME": "C",
"BLUECAT_DNS_VIEW": "D",
},
expected: "bluecat: some credentials information are missing: BLUECAT_PASSWORD",
},
{
desc: "missing config name",
envVars: map[string]string{
"BLUECAT_SERVER_URL": "http://localhost",
"BLUECAT_USER_NAME": "A",
"BLUECAT_PASSWORD": "B",
"BLUECAT_CONFIG_NAME": "",
"BLUECAT_DNS_VIEW": "D",
},
expected: "bluecat: some credentials information are missing: BLUECAT_CONFIG_NAME",
},
{
desc: "missing DNS view",
envVars: map[string]string{
"BLUECAT_SERVER_URL": "http://localhost",
"BLUECAT_USER_NAME": "A",
"BLUECAT_PASSWORD": "B",
"BLUECAT_CONFIG_NAME": "C",
"BLUECAT_DNS_VIEW": "",
},
expected: "bluecat: some credentials information are missing: BLUECAT_DNS_VIEW",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
for key, value := range test.envVars {
if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
}
p, err := NewDNSProvider()
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
func TestNewDNSProviderConfig(t *testing.T) {
testCases := []struct {
desc string
baseURL string
userName string
password string
configName string
dnsView string
expected string
}{
{
desc: "success",
baseURL: "http://localhost",
userName: "A",
password: "B",
configName: "C",
dnsView: "D",
},
{
desc: "missing credentials",
expected: "bluecat: credentials missing",
},
{
desc: "missing base URL",
baseURL: "",
userName: "A",
password: "B",
configName: "C",
dnsView: "D",
expected: "bluecat: credentials missing",
},
{
desc: "missing username",
baseURL: "http://localhost",
userName: "",
password: "B",
configName: "C",
dnsView: "D",
expected: "bluecat: credentials missing",
},
{
desc: "missing password",
baseURL: "http://localhost",
userName: "A",
password: "",
configName: "C",
dnsView: "D",
expected: "bluecat: credentials missing",
},
{
desc: "missing config name",
baseURL: "http://localhost",
userName: "A",
password: "B",
configName: "",
dnsView: "D",
expected: "bluecat: credentials missing",
},
{
desc: "missing DNS view",
baseURL: "http://localhost",
userName: "A",
password: "B",
configName: "C",
dnsView: "",
expected: "bluecat: credentials missing",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
os.Unsetenv("BLUECAT_SERVER_URL")
os.Unsetenv("BLUECAT_USER_NAME")
os.Unsetenv("BLUECAT_PASSWORD")
os.Unsetenv("BLUECAT_CONFIG_NAME")
os.Unsetenv("BLUECAT_DNS_VIEW")
config := NewDefaultConfig()
config.BaseURL = test.baseURL
config.UserName = test.userName
config.Password = test.password
config.ConfigName = test.configName
config.DNSView = test.dnsView
p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
func TestLivePresent(t *testing.T) {
if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
restoreEnv()
provider, err := NewDNSProvider() provider, err := NewDNSProvider()
assert.NoError(t, err) require.NoError(t, err)
err = provider.Present(bluecatDomain, "", "123d==") err = provider.Present(envTestDomain, "", "123d==")
assert.NoError(t, err) require.NoError(t, err)
} }
func TestLiveBluecatCleanUp(t *testing.T) { func TestLiveCleanUp(t *testing.T) {
if !bluecatLiveTest { if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
restoreEnv()
provider, err := NewDNSProvider()
require.NoError(t, err)
time.Sleep(time.Second * 1) time.Sleep(time.Second * 1)
provider, err := NewDNSProvider() err = provider.CleanUp(envTestDomain, "", "123d==")
assert.NoError(t, err) require.NoError(t, err)
err = provider.CleanUp(bluecatDomain, "", "123d==")
assert.NoError(t, err)
} }

View file

@ -10,24 +10,24 @@ import (
) )
var ( var (
cflareLiveTest bool liveTest bool
cflareEmail string envTestEmail string
cflareAPIKey string envTestAPIKey string
cflareDomain string envTestDomain string
) )
func init() { func init() {
cflareEmail = os.Getenv("CLOUDFLARE_EMAIL") envTestEmail = os.Getenv("CLOUDFLARE_EMAIL")
cflareAPIKey = os.Getenv("CLOUDFLARE_API_KEY") envTestAPIKey = os.Getenv("CLOUDFLARE_API_KEY")
cflareDomain = os.Getenv("CLOUDFLARE_DOMAIN") envTestDomain = os.Getenv("CLOUDFLARE_DOMAIN")
if len(cflareEmail) > 0 && len(cflareAPIKey) > 0 && len(cflareDomain) > 0 { if len(envTestEmail) > 0 && len(envTestAPIKey) > 0 && len(envTestDomain) > 0 {
cflareLiveTest = true liveTest = true
} }
} }
func restoreEnv() { func restoreEnv() {
os.Setenv("CLOUDFLARE_EMAIL", cflareEmail) os.Setenv("CLOUDFLARE_EMAIL", envTestEmail)
os.Setenv("CLOUDFLARE_API_KEY", cflareAPIKey) os.Setenv("CLOUDFLARE_API_KEY", envTestAPIKey)
} }
func TestNewDNSProvider(t *testing.T) { func TestNewDNSProvider(t *testing.T) {
@ -83,8 +83,10 @@ func TestNewDNSProvider(t *testing.T) {
p, err := NewDNSProvider() p, err := NewDNSProvider()
if len(test.expected) == 0 { if len(test.expected) == 0 {
assert.NoError(t, err) require.NoError(t, err)
assert.NotNil(t, p) require.NotNil(t, p)
assert.NotNil(t, p.config)
assert.NotNil(t, p.client)
} else { } else {
require.EqualError(t, err, test.expected) require.EqualError(t, err, test.expected)
} }
@ -133,8 +135,10 @@ func TestNewDNSProviderConfig(t *testing.T) {
p, err := NewDNSProviderConfig(config) p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 { if len(test.expected) == 0 {
assert.NoError(t, err) require.NoError(t, err)
assert.NotNil(t, p) require.NotNil(t, p)
assert.NotNil(t, p.config)
assert.NotNil(t, p.client)
} else { } else {
require.EqualError(t, err, test.expected) require.EqualError(t, err, test.expected)
} }
@ -142,36 +146,36 @@ func TestNewDNSProviderConfig(t *testing.T) {
} }
} }
func TestCloudFlarePresent(t *testing.T) { func TestPresent(t *testing.T) {
if !cflareLiveTest { if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
config := NewDefaultConfig() config := NewDefaultConfig()
config.AuthEmail = cflareEmail config.AuthEmail = envTestEmail
config.AuthKey = cflareAPIKey config.AuthKey = envTestAPIKey
provider, err := NewDNSProviderConfig(config) provider, err := NewDNSProviderConfig(config)
require.NoError(t, err) require.NoError(t, err)
err = provider.Present(cflareDomain, "", "123d==") err = provider.Present(envTestDomain, "", "123d==")
require.NoError(t, err) require.NoError(t, err)
} }
func TestCloudFlareCleanUp(t *testing.T) { func TestCleanUp(t *testing.T) {
if !cflareLiveTest { if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
time.Sleep(time.Second * 2) time.Sleep(time.Second * 2)
config := NewDefaultConfig() config := NewDefaultConfig()
config.AuthEmail = cflareEmail config.AuthEmail = envTestEmail
config.AuthKey = cflareAPIKey config.AuthKey = envTestAPIKey
provider, err := NewDNSProviderConfig(config) provider, err := NewDNSProviderConfig(config)
require.NoError(t, err) require.NoError(t, err)
err = provider.CleanUp(cflareDomain, "", "123d==") err = provider.CleanUp(envTestDomain, "", "123d==")
require.NoError(t, err) require.NoError(t, err)
} }

View file

@ -5,79 +5,169 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/require"
) )
var ( var (
cxLiveTest bool liveTest bool
cxAPIKey string envTestAPIKey string
cxSecretKey string envTestSecretKey string
cxDomain string envTestDomain string
) )
func init() { func init() {
cxAPIKey = os.Getenv("CLOUDXNS_API_KEY") envTestAPIKey = os.Getenv("CLOUDXNS_API_KEY")
cxSecretKey = os.Getenv("CLOUDXNS_SECRET_KEY") envTestSecretKey = os.Getenv("CLOUDXNS_SECRET_KEY")
cxDomain = os.Getenv("CLOUDXNS_DOMAIN") envTestDomain = os.Getenv("CLOUDXNS_DOMAIN")
if len(cxAPIKey) > 0 && len(cxSecretKey) > 0 && len(cxDomain) > 0 {
cxLiveTest = true if len(envTestAPIKey) > 0 && len(envTestSecretKey) > 0 && len(envTestDomain) > 0 {
liveTest = true
} }
} }
func restoreEnv() { func restoreEnv() {
os.Setenv("CLOUDXNS_API_KEY", cxAPIKey) os.Setenv("CLOUDXNS_API_KEY", envTestAPIKey)
os.Setenv("CLOUDXNS_SECRET_KEY", cxSecretKey) os.Setenv("CLOUDXNS_SECRET_KEY", envTestSecretKey)
} }
func TestNewDNSProviderValid(t *testing.T) { func TestNewDNSProvider(t *testing.T) {
defer restoreEnv() testCases := []struct {
os.Setenv("CLOUDXNS_API_KEY", "") desc string
os.Setenv("CLOUDXNS_SECRET_KEY", "") envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
"CLOUDXNS_API_KEY": "123",
"CLOUDXNS_SECRET_KEY": "456",
},
},
{
desc: "missing credentials",
envVars: map[string]string{
"CLOUDXNS_API_KEY": "",
"CLOUDXNS_SECRET_KEY": "",
},
expected: "CloudXNS: some credentials information are missing: CLOUDXNS_API_KEY,CLOUDXNS_SECRET_KEY",
},
{
desc: "missing API key",
envVars: map[string]string{
"CLOUDXNS_API_KEY": "",
"CLOUDXNS_SECRET_KEY": "456",
},
expected: "CloudXNS: some credentials information are missing: CLOUDXNS_API_KEY",
},
{
desc: "missing secret key",
envVars: map[string]string{
"CLOUDXNS_API_KEY": "123",
"CLOUDXNS_SECRET_KEY": "",
},
expected: "CloudXNS: some credentials information are missing: CLOUDXNS_SECRET_KEY",
},
}
_, err := NewDNSProviderCredentials("123", "123") for _, test := range testCases {
assert.NoError(t, err) t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
for key, value := range test.envVars {
if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
}
p, err := NewDNSProvider()
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
} }
func TestNewDNSProviderValidEnv(t *testing.T) { func TestNewDNSProviderConfig(t *testing.T) {
defer restoreEnv() testCases := []struct {
os.Setenv("CLOUDXNS_API_KEY", "123") desc string
os.Setenv("CLOUDXNS_SECRET_KEY", "123") apiKey string
secretKey string
expected string
}{
{
desc: "success",
apiKey: "123",
secretKey: "456",
},
{
desc: "missing credentials",
expected: "CloudXNS: credentials missing: apiKey",
},
{
desc: "missing api key",
secretKey: "456",
expected: "CloudXNS: credentials missing: apiKey",
},
{
desc: "missing secret key",
apiKey: "123",
expected: "CloudXNS: credentials missing: secretKey",
},
}
_, err := NewDNSProvider() for _, test := range testCases {
assert.NoError(t, err) t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
os.Unsetenv("CLOUDXNS_API_KEY")
os.Unsetenv("CLOUDXNS_SECRET_KEY")
config := NewDefaultConfig()
config.APIKey = test.apiKey
config.SecretKey = test.secretKey
p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
} }
func TestNewDNSProviderMissingCredErr(t *testing.T) { func TestPresent(t *testing.T) {
defer restoreEnv() if !liveTest {
os.Setenv("CLOUDXNS_API_KEY", "")
os.Setenv("CLOUDXNS_SECRET_KEY", "")
_, err := NewDNSProvider()
assert.EqualError(t, err, "CloudXNS: some credentials information are missing: CLOUDXNS_API_KEY,CLOUDXNS_SECRET_KEY")
}
func TestCloudXNSPresent(t *testing.T) {
if !cxLiveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
provider, err := NewDNSProviderCredentials(cxAPIKey, cxSecretKey) provider, err := NewDNSProviderCredentials(envTestAPIKey, envTestSecretKey)
assert.NoError(t, err) require.NoError(t, err)
err = provider.Present(cxDomain, "", "123d==") err = provider.Present(envTestDomain, "", "123d==")
assert.NoError(t, err) require.NoError(t, err)
} }
func TestCloudXNSCleanUp(t *testing.T) { func TestCleanUp(t *testing.T) {
if !cxLiveTest { if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
time.Sleep(time.Second * 2) time.Sleep(time.Second * 2)
provider, err := NewDNSProviderCredentials(cxAPIKey, cxSecretKey) provider, err := NewDNSProviderCredentials(envTestAPIKey, envTestSecretKey)
assert.NoError(t, err) require.NoError(t, err)
err = provider.CleanUp(cxDomain, "", "123d==") err = provider.CleanUp(envTestDomain, "", "123d==")
assert.NoError(t, err) require.NoError(t, err)
} }

View file

@ -5,31 +5,146 @@ import (
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"os"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
var fakeDigitalOceanAuth = "asdf1234" var (
envTestAuthToken string
)
func TestDigitalOceanPresent(t *testing.T) { func init() {
var requestReceived bool envTestAuthToken = os.Getenv("DO_AUTH_TOKEN")
}
mock := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { func restoreEnv() {
requestReceived = true os.Setenv("DO_AUTH_TOKEN", envTestAuthToken)
}
func setupTest() (*DNSProvider, *http.ServeMux, func()) {
handler := http.NewServeMux()
server := httptest.NewServer(handler)
config := NewDefaultConfig()
config.AuthToken = "asdf1234"
config.BaseURL = server.URL
provider, err := NewDNSProviderConfig(config)
if err != nil {
panic(err)
}
return provider, handler, server.Close
}
func TestNewDNSProvider(t *testing.T) {
testCases := []struct {
desc string
envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
"DO_AUTH_TOKEN": "123",
},
},
{
desc: "missing credentials",
envVars: map[string]string{
"DO_AUTH_TOKEN": "",
},
expected: "digitalocean: some credentials information are missing: DO_AUTH_TOKEN",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
for key, value := range test.envVars {
if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
}
p, err := NewDNSProvider()
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.recordIDs)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
func TestNewDNSProviderConfig(t *testing.T) {
testCases := []struct {
desc string
authToken string
expected string
}{
{
desc: "success",
authToken: "123",
},
{
desc: "missing credentials",
expected: "digitalocean: credentials missing",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
os.Unsetenv("DO_AUTH_TOKEN")
os.Unsetenv("ALICLOUD_SECRET_KEY")
config := NewDefaultConfig()
config.AuthToken = test.authToken
p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.recordIDs)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
func TestDNSProvider_Present(t *testing.T) {
provider, mux, tearDown := setupTest()
defer tearDown()
mux.HandleFunc("/v2/domains/example.com/records", func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodPost, r.Method, "method") assert.Equal(t, http.MethodPost, r.Method, "method")
assert.Equal(t, "/v2/domains/example.com/records", r.URL.Path, "Path")
assert.Equal(t, "application/json", r.Header.Get("Content-Type"), "Content-Type") assert.Equal(t, "application/json", r.Header.Get("Content-Type"), "Content-Type")
assert.Equal(t, "Bearer asdf1234", r.Header.Get("Authorization"), "Authorization") assert.Equal(t, "Bearer asdf1234", r.Header.Get("Authorization"), "Authorization")
reqBody, err := ioutil.ReadAll(r.Body) reqBody, err := ioutil.ReadAll(r.Body)
require.NoError(t, err, "reading request body") if err != nil {
assert.Equal(t, `{"type":"TXT","name":"_acme-challenge.example.com.","data":"w6uP8Tcg6K2QR905Rms8iXTlksL6OD1KOWBxTK7wxPI","ttl":30}`, string(reqBody)) http.Error(w, err.Error(), http.StatusInternalServerError)
}
expectedReqBody := `{"type":"TXT","name":"_acme-challenge.example.com.","data":"w6uP8Tcg6K2QR905Rms8iXTlksL6OD1KOWBxTK7wxPI","ttl":30}`
assert.Equal(t, expectedReqBody, string(reqBody))
w.WriteHeader(http.StatusCreated) w.WriteHeader(http.StatusCreated)
fmt.Fprintf(w, `{ _, err = fmt.Fprintf(w, `{
"domain_record": { "domain_record": {
"id": 1234567, "id": 1234567,
"type": "TXT", "type": "TXT",
@ -40,53 +155,35 @@ func TestDigitalOceanPresent(t *testing.T) {
"weight": null "weight": null
} }
}`) }`)
})) if err != nil {
defer mock.Close() http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
config := NewDefaultConfig() err := provider.Present("example.com", "", "foobar")
config.AuthToken = fakeDigitalOceanAuth
config.BaseURL = mock.URL
provider, err := NewDNSProviderConfig(config)
require.NoError(t, err) require.NoError(t, err)
require.NotNil(t, provider)
err = provider.Present("example.com", "", "foobar")
require.NoError(t, err, "fail to create TXT record")
assert.True(t, requestReceived, "Expected request to be received by mock backend, but it wasn't")
} }
func TestDigitalOceanCleanUp(t *testing.T) { func TestDNSProvider_CleanUp(t *testing.T) {
var requestReceived bool provider, mux, tearDown := setupTest()
defer tearDown()
mock := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestReceived = true
mux.HandleFunc("/v2/domains/example.com/records/1234567", func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodDelete, r.Method, "method") assert.Equal(t, http.MethodDelete, r.Method, "method")
assert.Equal(t, "/v2/domains/example.com/records/1234567", r.URL.Path, "Path") assert.Equal(t, "/v2/domains/example.com/records/1234567", r.URL.Path, "Path")
// NOTE: Even though the body is empty, DigitalOcean API docs still show setting this Content-Type... // NOTE: Even though the body is empty, DigitalOcean API docs still show setting this Content-Type...
assert.Equal(t, "application/json", r.Header.Get("Content-Type"), "Content-Type") assert.Equal(t, "application/json", r.Header.Get("Content-Type"), "Content-Type")
assert.Equal(t, "Bearer asdf1234", r.Header.Get("Authorization"), "Authorization") assert.Equal(t, "Bearer asdf1234", r.Header.Get("Authorization"), "Authorization")
w.WriteHeader(http.StatusNoContent) w.WriteHeader(http.StatusNoContent)
})) })
defer mock.Close()
config := NewDefaultConfig()
config.AuthToken = fakeDigitalOceanAuth
config.BaseURL = mock.URL
provider, err := NewDNSProviderConfig(config)
require.NoError(t, err)
require.NotNil(t, provider)
provider.recordIDsMu.Lock() provider.recordIDsMu.Lock()
provider.recordIDs["_acme-challenge.example.com."] = 1234567 provider.recordIDs["_acme-challenge.example.com."] = 1234567
provider.recordIDsMu.Unlock() provider.recordIDsMu.Unlock()
err = provider.CleanUp("example.com", "", "") err := provider.CleanUp("example.com", "", "")
require.NoError(t, err, "fail to remove TXT record") require.NoError(t, err, "fail to remove TXT record")
assert.True(t, requestReceived, "Expected request to be received by mock backend, but it wasn't")
} }

View file

@ -5,6 +5,7 @@ import (
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/xenolf/lego/providers/dns/exoscale" "github.com/xenolf/lego/providers/dns/exoscale"
) )
@ -29,7 +30,7 @@ func TestKnownDNSProviderSuccess(t *testing.T) {
os.Setenv("EXOSCALE_API_SECRET", "123") os.Setenv("EXOSCALE_API_SECRET", "123")
provider, err := NewDNSChallengeProviderByName("exoscale") provider, err := NewDNSChallengeProviderByName("exoscale")
assert.NoError(t, err) require.NoError(t, err)
assert.NotNil(t, provider) assert.NotNil(t, provider)
assert.IsType(t, &exoscale.DNSProvider{}, provider, "Not loaded correct DNS provider") assert.IsType(t, &exoscale.DNSProvider{}, provider, "Not loaded correct DNS provider")

View file

@ -11,31 +11,31 @@ import (
) )
var ( var (
dnsimpleLiveTest bool liveTest bool
dnsimpleOauthToken string envTestOauthToken string
dnsimpleDomain string envTestDomain string
dnsimpleBaseURL string envTestBaseURL string
) )
func init() { func init() {
dnsimpleOauthToken = os.Getenv("DNSIMPLE_OAUTH_TOKEN") envTestOauthToken = os.Getenv("DNSIMPLE_OAUTH_TOKEN")
dnsimpleDomain = os.Getenv("DNSIMPLE_DOMAIN") envTestDomain = os.Getenv("DNSIMPLE_DOMAIN")
dnsimpleBaseURL = "https://api.sandbox.dnsimple.com" envTestBaseURL = "https://api.sandbox.fake.com"
if len(dnsimpleOauthToken) > 0 && len(dnsimpleDomain) > 0 { if len(envTestOauthToken) > 0 && len(envTestDomain) > 0 {
baseURL := os.Getenv("DNSIMPLE_BASE_URL") baseURL := os.Getenv("DNSIMPLE_BASE_URL")
if baseURL != "" { if baseURL != "" {
dnsimpleBaseURL = baseURL envTestBaseURL = baseURL
} }
dnsimpleLiveTest = true liveTest = true
} }
} }
func restoreEnv() { func restoreEnv() {
os.Setenv("DNSIMPLE_OAUTH_TOKEN", dnsimpleOauthToken) os.Setenv("DNSIMPLE_OAUTH_TOKEN", envTestOauthToken)
os.Setenv("DNSIMPLE_BASE_URL", dnsimpleBaseURL) os.Setenv("DNSIMPLE_BASE_URL", envTestBaseURL)
} }
func TestNewDNSProvider(t *testing.T) { func TestNewDNSProvider(t *testing.T) {
@ -159,44 +159,30 @@ func TestNewDNSProviderConfig(t *testing.T) {
} }
} }
// func TestLivePresent(t *testing.T) {
// Present if !liveTest {
//
func TestLiveDNSimplePresent(t *testing.T) {
if !dnsimpleLiveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
config := NewDefaultConfig() restoreEnv()
config.AccessToken = dnsimpleOauthToken provider, err := NewDNSProvider()
config.BaseURL = dnsimpleBaseURL require.NoError(t, err)
provider, err := NewDNSProviderConfig(config) err = provider.Present(envTestDomain, "", "123d==")
assert.NoError(t, err) require.NoError(t, err)
err = provider.Present(dnsimpleDomain, "", "123d==")
assert.NoError(t, err)
} }
// func TestLiveCleanUp(t *testing.T) {
// Cleanup if !liveTest {
//
func TestLiveDNSimpleCleanUp(t *testing.T) {
if !dnsimpleLiveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
time.Sleep(time.Second * 1) restoreEnv()
provider, err := NewDNSProvider()
require.NoError(t, err)
config := NewDefaultConfig() time.Sleep(1 * time.Second)
config.AccessToken = dnsimpleOauthToken
config.BaseURL = dnsimpleBaseURL
provider, err := NewDNSProviderConfig(config) err = provider.CleanUp(envTestDomain, "", "123d==")
assert.NoError(t, err) require.NoError(t, err)
err = provider.CleanUp(dnsimpleDomain, "", "123d==")
assert.NoError(t, err)
} }

View file

@ -38,11 +38,11 @@ type Client struct {
// NewClient creates a DNSMadeEasy client // NewClient creates a DNSMadeEasy client
func NewClient(apiKey string, apiSecret string) (*Client, error) { func NewClient(apiKey string, apiSecret string) (*Client, error) {
if apiKey == "" { if apiKey == "" {
return nil, fmt.Errorf("DNSMadeEasy: credentials missing: API key") return nil, fmt.Errorf("credentials missing: API key")
} }
if apiSecret == "" { if apiSecret == "" {
return nil, fmt.Errorf("DNSMadeEasy: credentials missing: API secret") return nil, fmt.Errorf("credentials missing: API secret")
} }
return &Client{ return &Client{

View file

@ -5,7 +5,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"net/http" "net/http"
"strconv"
"strings" "strings"
"time" "time"
@ -18,6 +17,7 @@ type Config struct {
BaseURL string BaseURL string
APIKey string APIKey string
APISecret string APISecret string
Sandbox bool
HTTPClient *http.Client HTTPClient *http.Client
PropagationTimeout time.Duration PropagationTimeout time.Duration
PollingInterval time.Duration PollingInterval time.Duration
@ -55,15 +55,8 @@ func NewDNSProvider() (*DNSProvider, error) {
return nil, fmt.Errorf("dnsmadeeasy: %v", err) return nil, fmt.Errorf("dnsmadeeasy: %v", err)
} }
var baseURL string
if sandbox, _ := strconv.ParseBool(env.GetOrFile("DNSMADEEASY_SANDBOX")); sandbox {
baseURL = "https://api.sandbox.dnsmadeeasy.com/V2.0"
} else {
baseURL = "https://api.dnsmadeeasy.com/V2.0"
}
config := NewDefaultConfig() config := NewDefaultConfig()
config.BaseURL = baseURL config.Sandbox = env.GetOrDefaultBool("DNSMADEEASY_SANDBOX", false)
config.APIKey = values["DNSMADEEASY_API_KEY"] config.APIKey = values["DNSMADEEASY_API_KEY"]
config.APISecret = values["DNSMADEEASY_API_SECRET"] config.APISecret = values["DNSMADEEASY_API_SECRET"]
@ -88,8 +81,15 @@ func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
return nil, errors.New("dnsmadeeasy: the configuration of the DNS provider is nil") return nil, errors.New("dnsmadeeasy: the configuration of the DNS provider is nil")
} }
if config.BaseURL == "" { var baseURL string
return nil, fmt.Errorf("dnsmadeeasy: base URL missing") if config.Sandbox {
baseURL = "https://api.sandbox.dnsmadeeasy.com/V2.0"
} else {
if len(config.BaseURL) > 0 {
baseURL = config.BaseURL
} else {
baseURL = "https://api.dnsmadeeasy.com/V2.0"
}
} }
client, err := NewClient(config.APIKey, config.APISecret) client, err := NewClient(config.APIKey, config.APISecret)
@ -98,7 +98,7 @@ func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
} }
client.HTTPClient = config.HTTPClient client.HTTPClient = config.HTTPClient
client.BaseURL = config.BaseURL client.BaseURL = baseURL
return &DNSProvider{ return &DNSProvider{
client: client, client: client,

View file

@ -4,35 +4,159 @@ import (
"os" "os"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/require"
) )
var ( var (
testLive bool liveTest bool
testAPIKey string envTestAPIKey string
testAPISecret string envTestAPISecret string
testDomain string envTestDomain string
) )
func init() { func init() {
testAPIKey = os.Getenv("DNSMADEEASY_API_KEY") envTestAPIKey = os.Getenv("DNSMADEEASY_API_KEY")
testAPISecret = os.Getenv("DNSMADEEASY_API_SECRET") envTestAPISecret = os.Getenv("DNSMADEEASY_API_SECRET")
testDomain = os.Getenv("DNSMADEEASY_DOMAIN") envTestDomain = os.Getenv("DNSMADEEASY_DOMAIN")
os.Setenv("DNSMADEEASY_SANDBOX", "true") os.Setenv("DNSMADEEASY_SANDBOX", "true")
testLive = len(testAPIKey) > 0 && len(testAPISecret) > 0
liveTest = len(envTestAPIKey) > 0 && len(envTestAPISecret) > 0
} }
func TestPresentAndCleanup(t *testing.T) { func restoreEnv() {
if !testLive { os.Setenv("DNSMADEEASY_API_KEY", envTestAPIKey)
os.Setenv("DNSMADEEASY_API_SECRET", envTestAPISecret)
}
func TestNewDNSProvider(t *testing.T) {
testCases := []struct {
desc string
envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
"DNSMADEEASY_API_KEY": "123",
"DNSMADEEASY_API_SECRET": "456",
},
},
{
desc: "missing credentials",
envVars: map[string]string{
"DNSMADEEASY_API_KEY": "",
"DNSMADEEASY_API_SECRET": "",
},
expected: "dnsmadeeasy: some credentials information are missing: DNSMADEEASY_API_KEY,DNSMADEEASY_API_SECRET",
},
{
desc: "missing access key",
envVars: map[string]string{
"DNSMADEEASY_API_KEY": "",
"DNSMADEEASY_API_SECRET": "456",
},
expected: "dnsmadeeasy: some credentials information are missing: DNSMADEEASY_API_KEY",
},
{
desc: "missing secret key",
envVars: map[string]string{
"DNSMADEEASY_API_KEY": "123",
"DNSMADEEASY_API_SECRET": "",
},
expected: "dnsmadeeasy: some credentials information are missing: DNSMADEEASY_API_SECRET",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
for key, value := range test.envVars {
if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
}
p, err := NewDNSProvider()
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
func TestNewDNSProviderConfig(t *testing.T) {
testCases := []struct {
desc string
apiKey string
apiSecret string
expected string
}{
{
desc: "success",
apiKey: "123",
apiSecret: "456",
},
{
desc: "missing credentials",
expected: "dnsmadeeasy: credentials missing: API key",
},
{
desc: "missing api key",
apiSecret: "456",
expected: "dnsmadeeasy: credentials missing: API key",
},
{
desc: "missing secret key",
apiKey: "123",
expected: "dnsmadeeasy: credentials missing: API secret",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
os.Unsetenv("DNSMADEEASY_API_KEY")
os.Unsetenv("DNSMADEEASY_API_SECRET")
config := NewDefaultConfig()
config.APIKey = test.apiKey
config.APISecret = test.apiSecret
p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
func TestLivePresentAndCleanup(t *testing.T) {
if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
restoreEnv()
provider, err := NewDNSProvider() provider, err := NewDNSProvider()
assert.NoError(t, err) require.NoError(t, err)
err = provider.Present(testDomain, "", "123d==") err = provider.Present(envTestDomain, "", "123d==")
assert.NoError(t, err) require.NoError(t, err)
err = provider.CleanUp(testDomain, "", "123d==") err = provider.CleanUp(envTestDomain, "", "123d==")
assert.NoError(t, err) require.NoError(t, err)
} }

View file

@ -5,81 +5,136 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/require"
) )
var ( var (
dnspodLiveTest bool liveTest bool
dnspodAPIKey string envTestAPIKey string
dnspodDomain string envTestDomain string
) )
func init() { func init() {
dnspodAPIKey = os.Getenv("DNSPOD_API_KEY") envTestAPIKey = os.Getenv("DNSPOD_API_KEY")
dnspodDomain = os.Getenv("DNSPOD_DOMAIN") envTestDomain = os.Getenv("DNSPOD_DOMAIN")
if len(dnspodAPIKey) > 0 && len(dnspodDomain) > 0 {
dnspodLiveTest = true if len(envTestAPIKey) > 0 && len(envTestDomain) > 0 {
liveTest = true
} }
} }
func restoreEnv() { func restoreEnv() {
os.Setenv("DNSPOD_API_KEY", dnspodAPIKey) os.Setenv("DNSPOD_API_KEY", envTestAPIKey)
} }
func TestNewDNSProviderValid(t *testing.T) { func TestNewDNSProvider(t *testing.T) {
defer restoreEnv() testCases := []struct {
os.Setenv("DNSPOD_API_KEY", "") desc string
envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
"DNSPOD_API_KEY": "123",
},
},
{
desc: "missing api key",
envVars: map[string]string{
"DNSPOD_API_KEY": "",
},
expected: "dnspod: some credentials information are missing: DNSPOD_API_KEY",
},
}
config := NewDefaultConfig() for _, test := range testCases {
config.LoginToken = "123" t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
for key, value := range test.envVars {
if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
}
_, err := NewDNSProviderConfig(config) p, err := NewDNSProvider()
assert.NoError(t, err)
}
func TestNewDNSProviderValidEnv(t *testing.T) {
defer restoreEnv()
os.Setenv("DNSPOD_API_KEY", "123")
_, err := NewDNSProvider() if len(test.expected) == 0 {
assert.NoError(t, err) require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
} }
func TestNewDNSProviderMissingCredErr(t *testing.T) { func TestNewDNSProviderConfig(t *testing.T) {
defer restoreEnv() testCases := []struct {
os.Setenv("DNSPOD_API_KEY", "") desc string
loginToken string
expected string
}{
{
desc: "success",
loginToken: "123",
},
{
desc: "missing credentials",
expected: "dnspod: credentials missing",
},
}
_, err := NewDNSProvider() for _, test := range testCases {
assert.EqualError(t, err, "dnspod: some credentials information are missing: DNSPOD_API_KEY") t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
os.Unsetenv("DNSPOD_API_KEY")
config := NewDefaultConfig()
config.LoginToken = test.loginToken
p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
} }
func TestLivednspodPresent(t *testing.T) { func TestLivePresent(t *testing.T) {
if !dnspodLiveTest { if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
config := NewDefaultConfig() restoreEnv()
config.LoginToken = dnspodAPIKey provider, err := NewDNSProvider()
require.NoError(t, err)
provider, err := NewDNSProviderConfig(config) err = provider.Present(envTestDomain, "", "123d==")
assert.NoError(t, err) require.NoError(t, err)
err = provider.Present(dnspodDomain, "", "123d==")
assert.NoError(t, err)
} }
func TestLivednspodCleanUp(t *testing.T) { func TestLiveCleanUp(t *testing.T) {
if !dnspodLiveTest { if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
time.Sleep(time.Second * 1) restoreEnv()
provider, err := NewDNSProvider()
require.NoError(t, err)
config := NewDefaultConfig() time.Sleep(1 * time.Second)
config.LoginToken = dnspodAPIKey
provider, err := NewDNSProviderConfig(config) err = provider.CleanUp(envTestDomain, "", "123d==")
assert.NoError(t, err) require.NoError(t, err)
err = provider.CleanUp(dnspodDomain, "", "123d==")
assert.NoError(t, err)
} }

View file

@ -5,65 +5,133 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/require"
) )
var ( var (
duckdnsLiveTest bool liveTest bool
duckdnsToken string envTestToken string
duckdnsDomain string envTestDomain string
) )
func init() { func init() {
duckdnsToken = os.Getenv("DUCKDNS_TOKEN") envTestToken = os.Getenv("DUCKDNS_TOKEN")
duckdnsDomain = os.Getenv("DUCKDNS_DOMAIN") envTestDomain = os.Getenv("DUCKDNS_DOMAIN")
if len(duckdnsToken) > 0 && len(duckdnsDomain) > 0 { if len(envTestToken) > 0 && len(envTestDomain) > 0 {
duckdnsLiveTest = true liveTest = true
} }
} }
func restoreEnv() { func restoreEnv() {
os.Setenv("DUCKDNS_TOKEN", duckdnsToken) os.Setenv("DUCKDNS_TOKEN", envTestToken)
} }
func TestNewDNSProviderValidEnv(t *testing.T) { func TestNewDNSProvider(t *testing.T) {
defer restoreEnv() testCases := []struct {
os.Setenv("DUCKDNS_TOKEN", "123") desc string
envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
"DUCKDNS_TOKEN": "123",
},
},
{
desc: "missing api key",
envVars: map[string]string{
"DUCKDNS_TOKEN": "",
},
expected: "duckdns: some credentials information are missing: DUCKDNS_TOKEN",
},
}
_, err := NewDNSProvider() for _, test := range testCases {
assert.NoError(t, err) t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
for key, value := range test.envVars {
if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
}
p, err := NewDNSProvider()
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
} else {
require.EqualError(t, err, test.expected)
}
})
}
} }
func TestNewDNSProviderMissingCredErr(t *testing.T) { func TestNewDNSProviderConfig(t *testing.T) {
defer restoreEnv() testCases := []struct {
os.Setenv("DUCKDNS_TOKEN", "") desc string
token string
expected string
}{
{
desc: "success",
token: "123",
},
{
desc: "missing credentials",
expected: "duckdns: credentials missing",
},
}
_, err := NewDNSProvider() for _, test := range testCases {
assert.EqualError(t, err, "duckdns: some credentials information are missing: DUCKDNS_TOKEN") t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
os.Unsetenv("DUCKDNS_TOKEN")
config := NewDefaultConfig()
config.Token = test.token
p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
} else {
require.EqualError(t, err, test.expected)
}
})
}
} }
func TestLiveDuckdnsPresent(t *testing.T) { func TestLivePresent(t *testing.T) {
if !duckdnsLiveTest { if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
restoreEnv()
provider, err := NewDNSProvider() provider, err := NewDNSProvider()
assert.NoError(t, err) require.NoError(t, err)
err = provider.Present(duckdnsDomain, "", "123d==") err = provider.Present(envTestDomain, "", "123d==")
assert.NoError(t, err) require.NoError(t, err)
} }
func TestLiveDuckdnsCleanUp(t *testing.T) { func TestLiveCleanUp(t *testing.T) {
if !duckdnsLiveTest { if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
time.Sleep(time.Second * 10) restoreEnv()
provider, err := NewDNSProvider() provider, err := NewDNSProvider()
assert.NoError(t, err) require.NoError(t, err)
err = provider.CleanUp(duckdnsDomain, "", "123d==") time.Sleep(10 * time.Second)
assert.NoError(t, err)
err = provider.CleanUp(envTestDomain, "", "123d==")
require.NoError(t, err)
} }

View file

@ -5,50 +5,198 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
var ( var (
dynLiveTest bool liveTest bool
dynCustomerName string envTestCustomerName string
dynUserName string envTestUserName string
dynPassword string envTestPassword string
dynDomain string envTestDomain string
) )
func init() { func init() {
dynCustomerName = os.Getenv("DYN_CUSTOMER_NAME") envTestCustomerName = os.Getenv("DYN_CUSTOMER_NAME")
dynUserName = os.Getenv("DYN_USER_NAME") envTestUserName = os.Getenv("DYN_USER_NAME")
dynPassword = os.Getenv("DYN_PASSWORD") envTestPassword = os.Getenv("DYN_PASSWORD")
dynDomain = os.Getenv("DYN_DOMAIN") envTestDomain = os.Getenv("DYN_DOMAIN")
if len(dynCustomerName) > 0 && len(dynUserName) > 0 && len(dynPassword) > 0 && len(dynDomain) > 0 {
dynLiveTest = true if len(envTestCustomerName) > 0 && len(envTestUserName) > 0 && len(envTestPassword) > 0 && len(envTestDomain) > 0 {
liveTest = true
} }
} }
func TestLiveDynPresent(t *testing.T) { func restoreEnv() {
if !dynLiveTest { os.Setenv("DYN_CUSTOMER_NAME", envTestCustomerName)
os.Setenv("DYN_USER_NAME", envTestUserName)
os.Setenv("DYN_PASSWORD", envTestPassword)
}
func TestNewDNSProvider(t *testing.T) {
testCases := []struct {
desc string
envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
"DYN_CUSTOMER_NAME": "A",
"DYN_USER_NAME": "B",
"DYN_PASSWORD": "C",
},
},
{
desc: "missing credentials",
envVars: map[string]string{
"DYN_CUSTOMER_NAME": "",
"DYN_USER_NAME": "",
"DYN_PASSWORD": "",
},
expected: "dyn: some credentials information are missing: DYN_CUSTOMER_NAME,DYN_USER_NAME,DYN_PASSWORD",
},
{
desc: "missing customer name",
envVars: map[string]string{
"DYN_CUSTOMER_NAME": "",
"DYN_USER_NAME": "B",
"DYN_PASSWORD": "C",
},
expected: "dyn: some credentials information are missing: DYN_CUSTOMER_NAME",
},
{
desc: "missing password",
envVars: map[string]string{
"DYN_CUSTOMER_NAME": "A",
"DYN_USER_NAME": "",
"DYN_PASSWORD": "C",
},
expected: "dyn: some credentials information are missing: DYN_USER_NAME",
},
{
desc: "missing username",
envVars: map[string]string{
"DYN_CUSTOMER_NAME": "A",
"DYN_USER_NAME": "B",
"DYN_PASSWORD": "",
},
expected: "dyn: some credentials information are missing: DYN_PASSWORD",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
for key, value := range test.envVars {
if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
}
p, err := NewDNSProvider()
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
func TestNewDNSProviderConfig(t *testing.T) {
testCases := []struct {
desc string
customerName string
password string
userName string
expected string
}{
{
desc: "success",
customerName: "A",
password: "B",
userName: "C",
},
{
desc: "missing credentials",
expected: "dyn: credentials missing",
},
{
desc: "missing customer name",
customerName: "",
password: "B",
userName: "C",
expected: "dyn: credentials missing",
},
{
desc: "missing password",
customerName: "A",
password: "",
userName: "C",
expected: "dyn: credentials missing",
},
{
desc: "missing username",
customerName: "A",
password: "B",
userName: "",
expected: "dyn: credentials missing",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
os.Unsetenv("DNSPOD_API_KEY")
config := NewDefaultConfig()
config.CustomerName = test.customerName
config.Password = test.password
config.UserName = test.userName
p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
func TestLivePresent(t *testing.T) {
if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
restoreEnv()
provider, err := NewDNSProvider() provider, err := NewDNSProvider()
require.NoError(t, err) require.NoError(t, err)
err = provider.Present(dynDomain, "", "123d==") err = provider.Present(envTestDomain, "", "123d==")
assert.NoError(t, err) require.NoError(t, err)
} }
func TestLiveDynCleanUp(t *testing.T) { func TestLiveCleanUp(t *testing.T) {
if !dynLiveTest { if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
time.Sleep(time.Second * 1) restoreEnv()
provider, err := NewDNSProvider() provider, err := NewDNSProvider()
assert.NoError(t, err) require.NoError(t, err)
err = provider.CleanUp(dynDomain, "", "123d==") time.Sleep(1 * time.Second)
assert.NoError(t, err)
err = provider.CleanUp(envTestDomain, "", "123d==")
require.NoError(t, err)
} }

View file

@ -10,55 +10,141 @@ import (
) )
var ( var (
exoscaleLiveTest bool liveTest bool
exoscaleAPIKey string envTestAPIKey string
exoscaleAPISecret string envTestAPISecret string
exoscaleDomain string envTestDomain string
) )
func init() { func init() {
exoscaleAPISecret = os.Getenv("EXOSCALE_API_SECRET") envTestAPISecret = os.Getenv("EXOSCALE_API_SECRET")
exoscaleAPIKey = os.Getenv("EXOSCALE_API_KEY") envTestAPIKey = os.Getenv("EXOSCALE_API_KEY")
exoscaleDomain = os.Getenv("EXOSCALE_DOMAIN") envTestDomain = os.Getenv("EXOSCALE_DOMAIN")
if len(exoscaleAPIKey) > 0 && len(exoscaleAPISecret) > 0 && len(exoscaleDomain) > 0 {
exoscaleLiveTest = true if len(envTestAPIKey) > 0 && len(envTestAPISecret) > 0 && len(envTestDomain) > 0 {
liveTest = true
} }
} }
func restoreEnv() { func restoreEnv() {
os.Setenv("EXOSCALE_API_KEY", exoscaleAPIKey) os.Setenv("EXOSCALE_API_KEY", envTestAPIKey)
os.Setenv("EXOSCALE_API_SECRET", exoscaleAPISecret) os.Setenv("EXOSCALE_API_SECRET", envTestAPISecret)
} }
func TestNewDNSProviderValid(t *testing.T) { func TestNewDNSProvider(t *testing.T) {
defer restoreEnv() testCases := []struct {
os.Setenv("EXOSCALE_API_KEY", "") desc string
os.Setenv("EXOSCALE_API_SECRET", "") envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
"EXOSCALE_API_KEY": "123",
"EXOSCALE_API_SECRET": "456",
},
},
{
desc: "missing credentials",
envVars: map[string]string{
"EXOSCALE_API_KEY": "",
"EXOSCALE_API_SECRET": "",
},
expected: "exoscale: some credentials information are missing: EXOSCALE_API_KEY,EXOSCALE_API_SECRET",
},
{
desc: "missing access key",
envVars: map[string]string{
"EXOSCALE_API_KEY": "",
"EXOSCALE_API_SECRET": "456",
},
expected: "exoscale: some credentials information are missing: EXOSCALE_API_KEY",
},
{
desc: "missing secret key",
envVars: map[string]string{
"EXOSCALE_API_KEY": "123",
"EXOSCALE_API_SECRET": "",
},
expected: "exoscale: some credentials information are missing: EXOSCALE_API_SECRET",
},
}
config := NewDefaultConfig() for _, test := range testCases {
config.APIKey = "example@example.com" t.Run(test.desc, func(t *testing.T) {
config.APISecret = "123" defer restoreEnv()
for key, value := range test.envVars {
if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
}
_, err := NewDNSProviderConfig(config) p, err := NewDNSProvider()
require.NoError(t, err)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
} }
func TestNewDNSProviderValidEnv(t *testing.T) { func TestNewDNSProviderConfig(t *testing.T) {
defer restoreEnv() testCases := []struct {
os.Setenv("EXOSCALE_API_KEY", "example@example.com") desc string
os.Setenv("EXOSCALE_API_SECRET", "123") apiKey string
apiSecret string
expected string
}{
{
desc: "success",
apiKey: "123",
apiSecret: "456",
},
{
desc: "missing credentials",
expected: "exoscale: credentials missing",
},
{
desc: "missing api key",
apiSecret: "456",
expected: "exoscale: credentials missing",
},
{
desc: "missing secret key",
apiKey: "123",
expected: "exoscale: credentials missing",
},
}
_, err := NewDNSProvider() for _, test := range testCases {
require.NoError(t, err) t.Run(test.desc, func(t *testing.T) {
} defer restoreEnv()
os.Unsetenv("EXOSCALE_API_KEY")
os.Unsetenv("EXOSCALE_API_SECRET")
func TestNewDNSProviderMissingCredErr(t *testing.T) { config := NewDefaultConfig()
os.Setenv("EXOSCALE_API_KEY", "") config.APIKey = test.apiKey
os.Setenv("EXOSCALE_API_SECRET", "") config.APISecret = test.apiSecret
defer restoreEnv()
_, err := NewDNSProvider() p, err := NewDNSProviderConfig(config)
assert.EqualError(t, err, "exoscale: some credentials information are missing: EXOSCALE_API_KEY,EXOSCALE_API_SECRET")
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
} }
func TestDNSProvider_FindZoneAndRecordName(t *testing.T) { func TestDNSProvider_FindZoneAndRecordName(t *testing.T) {
@ -113,40 +199,34 @@ func TestDNSProvider_FindZoneAndRecordName(t *testing.T) {
} }
} }
func TestLiveExoscalePresent(t *testing.T) { func TestLivePresent(t *testing.T) {
if !exoscaleLiveTest { if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
config := NewDefaultConfig() restoreEnv()
config.APIKey = exoscaleAPIKey provider, err := NewDNSProvider()
config.APISecret = exoscaleAPISecret
provider, err := NewDNSProviderConfig(config)
require.NoError(t, err) require.NoError(t, err)
err = provider.Present(exoscaleDomain, "", "123d==") err = provider.Present(envTestDomain, "", "123d==")
require.NoError(t, err) require.NoError(t, err)
// Present Twice to handle create / update // Present Twice to handle create / update
err = provider.Present(exoscaleDomain, "", "123d==") err = provider.Present(envTestDomain, "", "123d==")
require.NoError(t, err) require.NoError(t, err)
} }
func TestLiveExoscaleCleanUp(t *testing.T) { func TestLiveCleanUp(t *testing.T) {
if !exoscaleLiveTest { if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
time.Sleep(time.Second * 1) restoreEnv()
provider, err := NewDNSProvider()
config := NewDefaultConfig()
config.APIKey = exoscaleAPIKey
config.APISecret = exoscaleAPISecret
provider, err := NewDNSProviderConfig(config)
require.NoError(t, err) require.NoError(t, err)
err = provider.CleanUp(exoscaleDomain, "", "123d==") time.Sleep(1 * time.Second)
err = provider.CleanUp(envTestDomain, "", "123d==")
require.NoError(t, err) require.NoError(t, err)
} }

View file

@ -77,7 +77,7 @@ func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
} }
if config.ClientToken == "" || config.ClientSecret == "" || config.AccessToken == "" || config.Host == "" { if config.ClientToken == "" || config.ClientSecret == "" || config.AccessToken == "" || config.Host == "" {
return nil, fmt.Errorf("FastDNS credentials are missing") return nil, fmt.Errorf("fastdns: credentials are missing")
} }
return &DNSProvider{config: config}, nil return &DNSProvider{config: config}, nil

View file

@ -10,92 +10,203 @@ import (
) )
var ( var (
fastdnsLiveTest bool liveTest bool
host string envTestHost string
clientToken string envTestClientToken string
clientSecret string envTestClientSecret string
accessToken string envTestAccessToken string
testDomain string envTestDomain string
) )
func init() { func init() {
host = os.Getenv("AKAMAI_HOST") envTestHost = os.Getenv("AKAMAI_HOST")
clientToken = os.Getenv("AKAMAI_CLIENT_TOKEN") envTestClientToken = os.Getenv("AKAMAI_CLIENT_TOKEN")
clientSecret = os.Getenv("AKAMAI_CLIENT_SECRET") envTestClientSecret = os.Getenv("AKAMAI_CLIENT_SECRET")
accessToken = os.Getenv("AKAMAI_ACCESS_TOKEN") envTestAccessToken = os.Getenv("AKAMAI_ACCESS_TOKEN")
testDomain = os.Getenv("AKAMAI_TEST_DOMAIN") envTestDomain = os.Getenv("AKAMAI_TEST_DOMAIN")
if len(host) > 0 && len(clientToken) > 0 && len(clientSecret) > 0 && len(accessToken) > 0 { if len(envTestHost) > 0 && len(envTestClientToken) > 0 && len(envTestClientSecret) > 0 && len(envTestAccessToken) > 0 {
fastdnsLiveTest = true liveTest = true
} }
} }
func restoreEnv() { func restoreEnv() {
os.Setenv("AKAMAI_HOST", host) os.Setenv("AKAMAI_HOST", envTestHost)
os.Setenv("AKAMAI_CLIENT_TOKEN", clientToken) os.Setenv("AKAMAI_CLIENT_TOKEN", envTestClientToken)
os.Setenv("AKAMAI_CLIENT_SECRET", clientSecret) os.Setenv("AKAMAI_CLIENT_SECRET", envTestClientSecret)
os.Setenv("AKAMAI_ACCESS_TOKEN", accessToken) os.Setenv("AKAMAI_ACCESS_TOKEN", envTestAccessToken)
} }
func TestNewDNSProviderValid(t *testing.T) { func TestNewDNSProvider(t *testing.T) {
defer restoreEnv() testCases := []struct {
os.Setenv("AKAMAI_HOST", "") desc string
os.Setenv("AKAMAI_CLIENT_TOKEN", "") envVars map[string]string
os.Setenv("AKAMAI_CLIENT_SECRET", "") expected string
os.Setenv("AKAMAI_ACCESS_TOKEN", "") }{
{
config := NewDefaultConfig() desc: "success",
config.Host = "somehost" envVars: map[string]string{
config.ClientToken = "someclienttoken" "AKAMAI_HOST": "A",
config.ClientSecret = "someclientsecret" "AKAMAI_CLIENT_TOKEN": "B",
config.AccessToken = "someaccesstoken" "AKAMAI_CLIENT_SECRET": "C",
"AKAMAI_ACCESS_TOKEN": "D",
_, err := NewDNSProviderConfig(config) },
require.NoError(t, err) },
} {
desc: "missing credentials",
func TestNewDNSProviderValidEnv(t *testing.T) { envVars: map[string]string{
defer restoreEnv() "AKAMAI_HOST": "",
os.Setenv("AKAMAI_HOST", "somehost") "AKAMAI_CLIENT_TOKEN": "",
os.Setenv("AKAMAI_CLIENT_TOKEN", "someclienttoken") "AKAMAI_CLIENT_SECRET": "",
os.Setenv("AKAMAI_CLIENT_SECRET", "someclientsecret") "AKAMAI_ACCESS_TOKEN": "",
os.Setenv("AKAMAI_ACCESS_TOKEN", "someaccesstoken") },
expected: "fastdns: some credentials information are missing: AKAMAI_HOST,AKAMAI_CLIENT_TOKEN,AKAMAI_CLIENT_SECRET,AKAMAI_ACCESS_TOKEN",
_, err := NewDNSProvider() },
require.NoError(t, err) {
} desc: "missing host",
envVars: map[string]string{
func TestNewDNSProviderMissingCredErr(t *testing.T) { "AKAMAI_HOST": "",
defer restoreEnv() "AKAMAI_CLIENT_TOKEN": "B",
os.Setenv("AKAMAI_HOST", "") "AKAMAI_CLIENT_SECRET": "C",
os.Setenv("AKAMAI_CLIENT_TOKEN", "") "AKAMAI_ACCESS_TOKEN": "D",
os.Setenv("AKAMAI_CLIENT_SECRET", "") },
os.Setenv("AKAMAI_ACCESS_TOKEN", "") expected: "fastdns: some credentials information are missing: AKAMAI_HOST",
},
_, err := NewDNSProvider() {
assert.EqualError(t, err, "fastdns: some credentials information are missing: AKAMAI_HOST,AKAMAI_CLIENT_TOKEN,AKAMAI_CLIENT_SECRET,AKAMAI_ACCESS_TOKEN") desc: "missing client token",
} envVars: map[string]string{
"AKAMAI_HOST": "A",
func TestLiveFastdnsPresent(t *testing.T) { "AKAMAI_CLIENT_TOKEN": "",
if !fastdnsLiveTest { "AKAMAI_CLIENT_SECRET": "C",
t.Skip("skipping live test") "AKAMAI_ACCESS_TOKEN": "D",
},
expected: "fastdns: some credentials information are missing: AKAMAI_CLIENT_TOKEN",
},
{
desc: "missing client secret",
envVars: map[string]string{
"AKAMAI_HOST": "A",
"AKAMAI_CLIENT_TOKEN": "B",
"AKAMAI_CLIENT_SECRET": "",
"AKAMAI_ACCESS_TOKEN": "D",
},
expected: "fastdns: some credentials information are missing: AKAMAI_CLIENT_SECRET",
},
{
desc: "missing access token",
envVars: map[string]string{
"AKAMAI_HOST": "A",
"AKAMAI_CLIENT_TOKEN": "B",
"AKAMAI_CLIENT_SECRET": "C",
"AKAMAI_ACCESS_TOKEN": "",
},
expected: "fastdns: some credentials information are missing: AKAMAI_ACCESS_TOKEN",
},
} }
config := NewDefaultConfig() for _, test := range testCases {
config.Host = host t.Run(test.desc, func(t *testing.T) {
config.ClientToken = clientToken defer restoreEnv()
config.ClientSecret = clientSecret for key, value := range test.envVars {
config.AccessToken = accessToken if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
}
provider, err := NewDNSProviderConfig(config) p, err := NewDNSProvider()
require.NoError(t, err)
err = provider.Present(testDomain, "", "123d==") if len(test.expected) == 0 {
require.NoError(t, err) require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
// Present Twice to handle create / update func TestNewDNSProviderConfig(t *testing.T) {
err = provider.Present(testDomain, "", "123d==") testCases := []struct {
require.NoError(t, err) desc string
host string
clientToken string
clientSecret string
accessToken string
expected string
}{
{
desc: "success",
host: "A",
clientToken: "B",
clientSecret: "C",
accessToken: "D",
},
{
desc: "missing credentials",
expected: "fastdns: credentials are missing",
},
{
desc: "missing host",
host: "",
clientToken: "B",
clientSecret: "C",
accessToken: "D",
expected: "fastdns: credentials are missing",
},
{
desc: "missing client token",
host: "A",
clientToken: "",
clientSecret: "C",
accessToken: "D",
expected: "fastdns: credentials are missing",
},
{
desc: "missing client secret",
host: "A",
clientToken: "B",
clientSecret: "",
accessToken: "B",
expected: "fastdns: credentials are missing",
},
{
desc: "missing access token",
host: "A",
clientToken: "B",
clientSecret: "C",
accessToken: "",
expected: "fastdns: credentials are missing",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
os.Unsetenv("AKAMAI_HOST")
os.Unsetenv("AKAMAI_CLIENT_TOKEN")
os.Unsetenv("AKAMAI_CLIENT_SECRET")
os.Unsetenv("AKAMAI_ACCESS_TOKEN")
config := NewDefaultConfig()
config.ClientToken = test.clientToken
config.ClientSecret = test.clientSecret
config.Host = test.host
config.AccessToken = test.accessToken
p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
} else {
require.EqualError(t, err, test.expected)
}
})
}
} }
func TestDNSProvider_findZoneAndRecordName(t *testing.T) { func TestDNSProvider_findZoneAndRecordName(t *testing.T) {
@ -152,22 +263,39 @@ func TestDNSProvider_findZoneAndRecordName(t *testing.T) {
} }
} }
func TestLiveFastdnsCleanUp(t *testing.T) { func TestLivePresent(t *testing.T) {
if !fastdnsLiveTest { if !liveTest {
t.Skip("skipping live test")
}
restoreEnv()
provider, err := NewDNSProvider()
require.NoError(t, err)
err = provider.Present(envTestDomain, "", "123d==")
require.NoError(t, err)
// Present Twice to handle create / update
err = provider.Present(envTestDomain, "", "123d==")
require.NoError(t, err)
}
func TestLiveCleanUp(t *testing.T) {
if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
time.Sleep(time.Second * 1) time.Sleep(time.Second * 1)
config := NewDefaultConfig() config := NewDefaultConfig()
config.Host = host config.Host = envTestHost
config.ClientToken = clientToken config.ClientToken = envTestClientToken
config.ClientSecret = clientSecret config.ClientSecret = envTestClientSecret
config.AccessToken = accessToken config.AccessToken = envTestAccessToken
provider, err := NewDNSProviderConfig(config) provider, err := NewDNSProviderConfig(config)
require.NoError(t, err) require.NoError(t, err)
err = provider.CleanUp(testDomain, "", "123d==") err = provider.CleanUp(envTestDomain, "", "123d==")
require.NoError(t, err) require.NoError(t, err)
} }

View file

@ -5,6 +5,7 @@ import (
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"os"
"regexp" "regexp"
"strings" "strings"
"testing" "testing"
@ -12,6 +13,104 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
var (
envTestAPIKey string
)
func init() {
envTestAPIKey = os.Getenv("GANDI_API_KEY")
}
func restoreEnv() {
os.Setenv("GANDI_API_KEY", envTestAPIKey)
}
func TestNewDNSProvider(t *testing.T) {
testCases := []struct {
desc string
envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
"GANDI_API_KEY": "123",
},
},
{
desc: "missing api key",
envVars: map[string]string{
"GANDI_API_KEY": "",
},
expected: "gandi: some credentials information are missing: GANDI_API_KEY",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
for key, value := range test.envVars {
if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
}
p, err := NewDNSProvider()
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.inProgressFQDNs)
require.NotNil(t, p.inProgressAuthZones)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
func TestNewDNSProviderConfig(t *testing.T) {
testCases := []struct {
desc string
apiKey string
expected string
}{
{
desc: "success",
apiKey: "123",
},
{
desc: "missing credentials",
expected: "gandi: no API Key given",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
os.Unsetenv("GANDI_API_KEY")
config := NewDefaultConfig()
config.APIKey = test.apiKey
p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.inProgressFQDNs)
require.NotNil(t, p.inProgressAuthZones)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
// TestDNSProvider runs Present and CleanUp against a fake Gandi RPC // TestDNSProvider runs Present and CleanUp against a fake Gandi RPC
// Server, whose responses are predetermined for particular requests. // Server, whose responses are predetermined for particular requests.
func TestDNSProvider(t *testing.T) { func TestDNSProvider(t *testing.T) {

View file

@ -102,6 +102,10 @@ func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
config.BaseURL = defaultBaseURL config.BaseURL = defaultBaseURL
} }
if config.TTL < minTTL {
return nil, fmt.Errorf("gandiv5: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL)
}
return &DNSProvider{ return &DNSProvider{
config: config, config: config,
inProgressFQDNs: make(map[string]inProgressInfo), inProgressFQDNs: make(map[string]inProgressInfo),
@ -112,10 +116,6 @@ func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
func (d *DNSProvider) Present(domain, token, keyAuth string) error { func (d *DNSProvider) Present(domain, token, keyAuth string) error {
fqdn, value, _ := acme.DNS01Record(domain, keyAuth) fqdn, value, _ := acme.DNS01Record(domain, keyAuth)
if d.config.TTL < minTTL {
d.config.TTL = minTTL // 300 is gandi minimum value for ttl
}
// find authZone // find authZone
authZone, err := findZoneByFqdn(fqdn, acme.RecursiveNameservers) authZone, err := findZoneByFqdn(fqdn, acme.RecursiveNameservers)
if err != nil { if err != nil {

View file

@ -5,14 +5,110 @@ import (
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"os"
"regexp" "regexp"
"testing" "testing"
"github.com/xenolf/lego/log"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/xenolf/lego/log"
) )
var (
envTestAPIKey string
)
func init() {
envTestAPIKey = os.Getenv("GANDIV5_API_KEY")
}
func restoreEnv() {
os.Setenv("GANDIV5_API_KEY", envTestAPIKey)
}
func TestNewDNSProvider(t *testing.T) {
testCases := []struct {
desc string
envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
"GANDIV5_API_KEY": "123",
},
},
{
desc: "missing api key",
envVars: map[string]string{
"GANDIV5_API_KEY": "",
},
expected: "gandi: some credentials information are missing: GANDIV5_API_KEY",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
for key, value := range test.envVars {
if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
}
p, err := NewDNSProvider()
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.inProgressFQDNs)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
func TestNewDNSProviderConfig(t *testing.T) {
testCases := []struct {
desc string
apiKey string
expected string
}{
{
desc: "success",
apiKey: "123",
},
{
desc: "missing credentials",
expected: "gandiv5: no API Key given",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
os.Unsetenv("GANDIV5_API_KEY")
config := NewDefaultConfig()
config.APIKey = test.apiKey
p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.inProgressFQDNs)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
// TestDNSProvider runs Present and CleanUp against a fake Gandi RPC // TestDNSProvider runs Present and CleanUp against a fake Gandi RPC
// Server, whose responses are predetermined for particular requests. // Server, whose responses are predetermined for particular requests.
func TestDNSProvider(t *testing.T) { func TestDNSProvider(t *testing.T) {

View file

@ -0,0 +1,11 @@
{
"project_id": "A",
"type": "service_account",
"client_email": "foo@bar.com",
"private_key_id": "pki",
"private_key": "pk",
"token_uri": "/token",
"client_secret": "secret",
"client_id": "C",
"refresh_token": "D"
}

View file

@ -5,7 +5,6 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"golang.org/x/net/context" "golang.org/x/net/context"
"golang.org/x/oauth2/google" "golang.org/x/oauth2/google"
@ -13,93 +12,168 @@ import (
) )
var ( var (
gcloudLiveTest bool liveTest bool
gcloudProject string envTestProject string
gcloudDomain string envTestServiceAccountFile string
envTestGoogleApplicationCredentials string
envTestDomain string
) )
func init() { func init() {
gcloudProject = os.Getenv("GCE_PROJECT") envTestProject = os.Getenv("GCE_PROJECT")
gcloudDomain = os.Getenv("GCE_DOMAIN") envTestServiceAccountFile = os.Getenv("GCE_SERVICE_ACCOUNT_FILE")
envTestGoogleApplicationCredentials = os.Getenv("GOOGLE_APPLICATION_CREDENTIALS")
envTestDomain = os.Getenv("GCE_DOMAIN")
_, err := google.DefaultClient(context.Background(), dns.NdevClouddnsReadwriteScope) _, err := google.DefaultClient(context.Background(), dns.NdevClouddnsReadwriteScope)
if err == nil && len(gcloudProject) > 0 && len(gcloudDomain) > 0 { if err == nil && len(envTestProject) > 0 && len(envTestDomain) > 0 {
gcloudLiveTest = true liveTest = true
} }
} }
func restoreEnv() { func restoreEnv() {
os.Setenv("GCE_PROJECT", gcloudProject) os.Setenv("GCE_PROJECT", envTestProject)
os.Setenv("GCE_SERVICE_ACCOUNT_FILE", envTestServiceAccountFile)
os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", envTestGoogleApplicationCredentials)
} }
func TestNewDNSProviderValid(t *testing.T) { func TestNewDNSProvider(t *testing.T) {
if !gcloudLiveTest { testCases := []struct {
t.Skip("skipping live test (requires credentials)") desc string
envVars map[string]string
expected string
}{
{
desc: "invalid credentials",
envVars: map[string]string{
"GCE_PROJECT": "123",
"GCE_SERVICE_ACCOUNT_FILE": "",
// as Travis run on GCE, we have to alter env
"GOOGLE_APPLICATION_CREDENTIALS": "not-a-secret-file",
},
expected: "googlecloud: unable to get Google Cloud client: google: error getting credentials using GOOGLE_APPLICATION_CREDENTIALS environment variable: open not-a-secret-file: no such file or directory",
},
{
desc: "missing project",
envVars: map[string]string{
"GCE_PROJECT": "",
"GCE_SERVICE_ACCOUNT_FILE": "",
},
expected: "googlecloud: project name missing",
},
{
desc: "success",
envVars: map[string]string{
"GCE_PROJECT": "",
"GCE_SERVICE_ACCOUNT_FILE": "fixtures/gce_account_service_file.json",
},
},
} }
defer restoreEnv() for _, test := range testCases {
os.Setenv("GCE_PROJECT", "") t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
_, err := NewDNSProviderCredentials("my-project") for key, value := range test.envVars {
require.NoError(t, err) if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
}
p, err := NewDNSProvider()
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
} }
func TestNewDNSProviderValidEnv(t *testing.T) { func TestNewDNSProviderConfig(t *testing.T) {
if !gcloudLiveTest { testCases := []struct {
t.Skip("skipping live test (requires credentials)") desc string
project string
expected string
}{
{
desc: "invalid project",
project: "123",
expected: "googlecloud: unable to create Google Cloud DNS service: client is nil",
},
{
desc: "missing project",
expected: "googlecloud: unable to create Google Cloud DNS service: client is nil",
},
} }
defer restoreEnv() for _, test := range testCases {
os.Setenv("GCE_PROJECT", "my-project") t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
os.Unsetenv("GCE_PROJECT")
os.Unsetenv("GCE_SERVICE_ACCOUNT_FILE")
_, err := NewDNSProvider() config := NewDefaultConfig()
require.NoError(t, err) config.Project = test.project
p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
} }
func TestNewDNSProviderMissingCredErr(t *testing.T) { func TestLivePresent(t *testing.T) {
defer restoreEnv() if !liveTest {
os.Setenv("GCE_PROJECT", "")
_, err := NewDNSProvider()
assert.EqualError(t, err, "googlecloud: project name missing")
}
func TestLiveGoogleCloudPresent(t *testing.T) {
if !gcloudLiveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
provider, err := NewDNSProviderCredentials(gcloudProject) provider, err := NewDNSProviderCredentials(envTestProject)
require.NoError(t, err) require.NoError(t, err)
err = provider.Present(gcloudDomain, "", "123d==") err = provider.Present(envTestDomain, "", "123d==")
require.NoError(t, err) require.NoError(t, err)
} }
func TestLiveGoogleCloudPresentMultiple(t *testing.T) { func TestLivePresentMultiple(t *testing.T) {
if !gcloudLiveTest { if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
provider, err := NewDNSProviderCredentials(gcloudProject) provider, err := NewDNSProviderCredentials(envTestProject)
require.NoError(t, err) require.NoError(t, err)
// Check that we're able to create multiple entries // Check that we're able to create multiple entries
err = provider.Present(gcloudDomain, "1", "123d==") err = provider.Present(envTestDomain, "1", "123d==")
require.NoError(t, err) require.NoError(t, err)
err = provider.Present(gcloudDomain, "2", "123d==")
err = provider.Present(envTestDomain, "2", "123d==")
require.NoError(t, err) require.NoError(t, err)
} }
func TestLiveGoogleCloudCleanUp(t *testing.T) { func TestLiveCleanUp(t *testing.T) {
if !gcloudLiveTest { if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
time.Sleep(time.Second * 1) provider, err := NewDNSProviderCredentials(envTestProject)
provider, err := NewDNSProviderCredentials(gcloudProject)
require.NoError(t, err) require.NoError(t, err)
err = provider.CleanUp(gcloudDomain, "", "123d==") time.Sleep(1 * time.Second)
err = provider.CleanUp(envTestDomain, "", "123d==")
require.NoError(t, err) require.NoError(t, err)
} }

View file

@ -93,6 +93,10 @@ func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
return nil, fmt.Errorf("glesys: incomplete credentials provided") return nil, fmt.Errorf("glesys: incomplete credentials provided")
} }
if config.TTL < minTTL {
return nil, fmt.Errorf("glesys: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL)
}
return &DNSProvider{ return &DNSProvider{
config: config, config: config,
activeRecords: make(map[string]int), activeRecords: make(map[string]int),
@ -103,9 +107,6 @@ func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
func (d *DNSProvider) Present(domain, token, keyAuth string) error { func (d *DNSProvider) Present(domain, token, keyAuth string) error {
fqdn, value, _ := acme.DNS01Record(domain, keyAuth) fqdn, value, _ := acme.DNS01Record(domain, keyAuth)
if d.config.TTL < minTTL {
d.config.TTL = minTTL // 60 is GleSYS minimum value for ttl
}
// find authZone // find authZone
authZone, err := acme.FindZoneByFqdn(fqdn, acme.RecursiveNameservers) authZone, err := acme.FindZoneByFqdn(fqdn, acme.RecursiveNameservers)
if err != nil { if err != nil {

View file

@ -4,58 +4,170 @@ import (
"os" "os"
"testing" "testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
var ( var (
glesysAPIUser string liveTest bool
glesysAPIKey string envTestAPIUser string
glesysDomain string envTestAPIKey string
glesysLiveTest bool envTestDomain string
) )
func init() { func init() {
glesysAPIUser = os.Getenv("GLESYS_API_USER") envTestAPIUser = os.Getenv("GLESYS_API_USER")
glesysAPIKey = os.Getenv("GLESYS_API_KEY") envTestAPIKey = os.Getenv("GLESYS_API_KEY")
glesysDomain = os.Getenv("GLESYS_DOMAIN")
if len(glesysAPIUser) > 0 && len(glesysAPIKey) > 0 && len(glesysDomain) > 0 { if len(envTestAPIUser) > 0 && len(envTestAPIKey) > 0 && len(envTestDomain) > 0 {
glesysLiveTest = true liveTest = true
} }
} }
func restoreEnv() {
os.Setenv("GLESYS_API_USER", envTestAPIUser)
os.Setenv("GLESYS_API_KEY", envTestAPIKey)
}
func TestNewDNSProvider(t *testing.T) { func TestNewDNSProvider(t *testing.T) {
provider, err := NewDNSProvider() testCases := []struct {
desc string
envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
"GLESYS_API_USER": "A",
"GLESYS_API_KEY": "B",
},
},
{
desc: "missing credentials",
envVars: map[string]string{
"GLESYS_API_USER": "",
"GLESYS_API_KEY": "",
},
expected: "glesys: some credentials information are missing: GLESYS_API_USER,GLESYS_API_KEY",
},
{
desc: "missing api user",
envVars: map[string]string{
"GLESYS_API_USER": "",
"GLESYS_API_KEY": "B",
},
expected: "glesys: some credentials information are missing: GLESYS_API_USER",
},
{
desc: "missing api key",
envVars: map[string]string{
"GLESYS_API_USER": "A",
"GLESYS_API_KEY": "",
},
expected: "glesys: some credentials information are missing: GLESYS_API_KEY",
},
}
if !glesysLiveTest { for _, test := range testCases {
assert.Error(t, err) t.Run(test.desc, func(t *testing.T) {
} else { defer restoreEnv()
assert.NotNil(t, provider) for key, value := range test.envVars {
assert.NoError(t, err) if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
}
p, err := NewDNSProvider()
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.activeRecords)
} else {
require.EqualError(t, err, test.expected)
}
})
} }
} }
func TestDNSProvider_Present(t *testing.T) { func TestNewDNSProviderConfig(t *testing.T) {
if !glesysLiveTest { testCases := []struct {
desc string
apiUser string
apiKey string
expected string
}{
{
desc: "success",
apiUser: "A",
apiKey: "B",
},
{
desc: "missing credentials",
expected: "glesys: incomplete credentials provided",
},
{
desc: "missing api user",
apiUser: "",
apiKey: "B",
expected: "glesys: incomplete credentials provided",
},
{
desc: "missing api key",
apiUser: "A",
apiKey: "",
expected: "glesys: incomplete credentials provided",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
os.Unsetenv("GLESYS_API_USER")
os.Unsetenv("GLESYS_API_KEY")
config := NewDefaultConfig()
config.APIKey = test.apiKey
config.APIUser = test.apiUser
p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.activeRecords)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
func TestLivePresent(t *testing.T) {
if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
restoreEnv()
provider, err := NewDNSProvider() provider, err := NewDNSProvider()
require.NoError(t, err) require.NoError(t, err)
err = provider.Present(glesysDomain, "", "123d==") err = provider.Present(envTestDomain, "", "123d==")
require.NoError(t, err) require.NoError(t, err)
} }
func TestDNSProvider_CleanUp(t *testing.T) { func TestLiveCleanUp(t *testing.T) {
if !glesysLiveTest { if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
restoreEnv()
provider, err := NewDNSProvider() provider, err := NewDNSProvider()
require.NoError(t, err) require.NoError(t, err)
err = provider.CleanUp(glesysDomain, "", "123d==") err = provider.CleanUp(envTestDomain, "", "123d==")
require.NoError(t, err) require.NoError(t, err)
} }

View file

@ -4,57 +4,167 @@ import (
"os" "os"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/require"
) )
var ( var (
godaddyAPIKey string liveTest bool
godaddyAPISecret string envTestAPIKey string
godaddyDomain string envTestAPISecret string
godaddyLiveTest bool envTestDomain string
) )
func init() { func init() {
godaddyAPIKey = os.Getenv("GODADDY_API_KEY") envTestAPIKey = os.Getenv("GODADDY_API_KEY")
godaddyAPISecret = os.Getenv("GODADDY_API_SECRET") envTestAPISecret = os.Getenv("GODADDY_API_SECRET")
godaddyDomain = os.Getenv("GODADDY_DOMAIN") envTestDomain = os.Getenv("GODADDY_DOMAIN")
if len(godaddyAPIKey) > 0 && len(godaddyAPISecret) > 0 && len(godaddyDomain) > 0 { if len(envTestAPIKey) > 0 && len(envTestAPISecret) > 0 && len(envTestDomain) > 0 {
godaddyLiveTest = true liveTest = true
} }
} }
func restoreEnv() {
os.Setenv("GODADDY_API_KEY", envTestAPIKey)
os.Setenv("GODADDY_API_SECRET", envTestAPISecret)
}
func TestNewDNSProvider(t *testing.T) { func TestNewDNSProvider(t *testing.T) {
provider, err := NewDNSProvider() testCases := []struct {
desc string
envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
"GODADDY_API_KEY": "123",
"GODADDY_API_SECRET": "456",
},
},
{
desc: "missing credentials",
envVars: map[string]string{
"GODADDY_API_KEY": "",
"GODADDY_API_SECRET": "",
},
expected: "godaddy: some credentials information are missing: GODADDY_API_KEY,GODADDY_API_SECRET",
},
{
desc: "missing access key",
envVars: map[string]string{
"GODADDY_API_KEY": "",
"GODADDY_API_SECRET": "456",
},
expected: "godaddy: some credentials information are missing: GODADDY_API_KEY",
},
{
desc: "missing secret key",
envVars: map[string]string{
"GODADDY_API_KEY": "123",
"GODADDY_API_SECRET": "",
},
expected: "godaddy: some credentials information are missing: GODADDY_API_SECRET",
},
}
if !godaddyLiveTest { for _, test := range testCases {
assert.Error(t, err) t.Run(test.desc, func(t *testing.T) {
} else { defer restoreEnv()
assert.NotNil(t, provider) for key, value := range test.envVars {
assert.NoError(t, err) if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
}
p, err := NewDNSProvider()
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
} else {
require.EqualError(t, err, test.expected)
}
})
} }
} }
func TestDNSProvider_Present(t *testing.T) { func TestNewDNSProviderConfig(t *testing.T) {
if !godaddyLiveTest { testCases := []struct {
desc string
apiKey string
apiSecret string
expected string
}{
{
desc: "success",
apiKey: "123",
apiSecret: "456",
},
{
desc: "missing credentials",
expected: "godaddy: credentials missing",
},
{
desc: "missing api key",
apiSecret: "456",
expected: "godaddy: credentials missing",
},
{
desc: "missing secret key",
apiKey: "123",
expected: "godaddy: credentials missing",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
os.Unsetenv("GODADDY_API_KEY")
os.Unsetenv("GODADDY_API_SECRET")
config := NewDefaultConfig()
config.APIKey = test.apiKey
config.APISecret = test.apiSecret
p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
func TestLivePresent(t *testing.T) {
if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
restoreEnv()
provider, err := NewDNSProvider() provider, err := NewDNSProvider()
assert.NoError(t, err) require.NoError(t, err)
err = provider.Present(godaddyDomain, "", "123d==") err = provider.Present(envTestDomain, "", "123d==")
assert.NoError(t, err) require.NoError(t, err)
} }
func TestDNSProvider_CleanUp(t *testing.T) { func TestLiveCleanUp(t *testing.T) {
if !godaddyLiveTest { if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
restoreEnv()
provider, err := NewDNSProvider() provider, err := NewDNSProvider()
assert.NoError(t, err) require.NoError(t, err)
err = provider.CleanUp(godaddyDomain, "", "123d==") err = provider.CleanUp(envTestDomain, "", "123d==")
assert.NoError(t, err) require.NoError(t, err)
} }

View file

@ -5,100 +5,170 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
var ( var (
hostingdeLiveTest bool liveTest bool
hostingdeAPIKey string envTestAPIKey string
hostingdeZone string envTestZone string
hostingdeDomain string envTestDomain string
) )
func init() { func init() {
hostingdeAPIKey = os.Getenv("HOSTINGDE_API_KEY") envTestAPIKey = os.Getenv("HOSTINGDE_API_KEY")
hostingdeZone = os.Getenv("HOSTINGDE_ZONE_NAME") envTestZone = os.Getenv("HOSTINGDE_ZONE_NAME")
hostingdeDomain = os.Getenv("HOSTINGDE_DOMAIN") envTestDomain = os.Getenv("HOSTINGDE_DOMAIN")
if len(hostingdeZone) > 0 && len(hostingdeAPIKey) > 0 && len(hostingdeDomain) > 0 { if len(envTestZone) > 0 && len(envTestAPIKey) > 0 && len(envTestDomain) > 0 {
hostingdeLiveTest = true liveTest = true
} }
} }
func restoreEnv() { func restoreEnv() {
os.Setenv("HOSTINGDE_ZONE_NAME", hostingdeZone) os.Setenv("HOSTINGDE_ZONE_NAME", envTestZone)
os.Setenv("HOSTINGDE_API_KEY", hostingdeAPIKey) os.Setenv("HOSTINGDE_API_KEY", envTestAPIKey)
} }
func TestNewDNSProviderValid(t *testing.T) { func TestNewDNSProvider(t *testing.T) {
os.Setenv("HOSTINGDE_ZONE_NAME", "") testCases := []struct {
os.Setenv("HOSTINGDE_API_KEY", "") desc string
defer restoreEnv() envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
"HOSTINGDE_API_KEY": "123",
"HOSTINGDE_ZONE_NAME": "456",
},
},
{
desc: "missing credentials",
envVars: map[string]string{
"HOSTINGDE_API_KEY": "",
"HOSTINGDE_ZONE_NAME": "",
},
expected: "hostingde: some credentials information are missing: HOSTINGDE_API_KEY,HOSTINGDE_ZONE_NAME",
},
{
desc: "missing access key",
envVars: map[string]string{
"HOSTINGDE_API_KEY": "",
"HOSTINGDE_ZONE_NAME": "456",
},
expected: "hostingde: some credentials information are missing: HOSTINGDE_API_KEY",
},
{
desc: "missing zone name",
envVars: map[string]string{
"HOSTINGDE_API_KEY": "123",
"HOSTINGDE_ZONE_NAME": "",
},
expected: "hostingde: some credentials information are missing: HOSTINGDE_ZONE_NAME",
},
}
config := NewDefaultConfig() for _, test := range testCases {
config.APIKey = "123" t.Run(test.desc, func(t *testing.T) {
config.ZoneName = "example.com" defer restoreEnv()
for key, value := range test.envVars {
if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
}
_, err := NewDNSProviderConfig(config) p, err := NewDNSProvider()
assert.NoError(t, err)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.recordIDs)
} else {
require.EqualError(t, err, test.expected)
}
})
}
} }
func TestNewDNSProviderValidEnv(t *testing.T) { func TestNewDNSProviderConfig(t *testing.T) {
defer restoreEnv() testCases := []struct {
os.Setenv("HOSTINGDE_ZONE_NAME", "example.com") desc string
os.Setenv("HOSTINGDE_API_KEY", "123") apiKey string
zoneName string
expected string
}{
{
desc: "success",
apiKey: "123",
zoneName: "456",
},
{
desc: "missing credentials",
expected: "hostingde: API key missing",
},
{
desc: "missing api key",
zoneName: "456",
expected: "hostingde: API key missing",
},
{
desc: "missing zone name",
apiKey: "123",
expected: "hostingde: Zone Name missing",
},
}
_, err := NewDNSProvider() for _, test := range testCases {
assert.NoError(t, err) t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
os.Unsetenv("HOSTINGDE_API_KEY")
os.Unsetenv("HOSTINGDE_ZONE_NAME")
config := NewDefaultConfig()
config.APIKey = test.apiKey
config.ZoneName = test.zoneName
p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.recordIDs)
} else {
require.EqualError(t, err, test.expected)
}
})
}
} }
func TestNewDNSProviderMissingCredErr(t *testing.T) { func TestLivePresent(t *testing.T) {
defer restoreEnv() if !liveTest {
os.Setenv("HOSTINGDE_ZONE_NAME", "")
os.Setenv("HOSTINGDE_API_KEY", "")
_, err := NewDNSProvider()
assert.EqualError(t, err, "hostingde: some credentials information are missing: HOSTINGDE_API_KEY,HOSTINGDE_ZONE_NAME")
}
func TestNewDNSProviderMissingCredErrSingle(t *testing.T) {
defer restoreEnv()
os.Setenv("HOSTINGDE_ZONE_NAME", "example.com")
_, err := NewDNSProvider()
assert.EqualError(t, err, "hostingde: some credentials information are missing: HOSTINGDE_API_KEY")
}
func TestHostingdePresent(t *testing.T) {
if !hostingdeLiveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
config := NewDefaultConfig() restoreEnv()
config.APIKey = hostingdeZone provider, err := NewDNSProvider()
config.ZoneName = hostingdeAPIKey
provider, err := NewDNSProviderConfig(config)
require.NoError(t, err) require.NoError(t, err)
err = provider.Present(hostingdeDomain, "", "123d==") err = provider.Present(envTestDomain, "", "123d==")
assert.NoError(t, err) require.NoError(t, err)
} }
func TestHostingdeCleanUp(t *testing.T) { func TestLiveCleanUp(t *testing.T) {
if !hostingdeLiveTest { if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
time.Sleep(time.Second * 2) restoreEnv()
provider, err := NewDNSProvider()
config := NewDefaultConfig()
config.APIKey = hostingdeZone
config.ZoneName = hostingdeAPIKey
provider, err := NewDNSProviderConfig(config)
require.NoError(t, err) require.NoError(t, err)
err = provider.CleanUp(hostingdeDomain, "", "123d==") time.Sleep(2 * time.Second)
assert.NoError(t, err)
err = provider.CleanUp(envTestDomain, "", "123d==")
require.NoError(t, err)
} }

View file

@ -9,30 +9,173 @@ import (
) )
var ( var (
apiAccessKeyEnv string liveTest bool
apiSecretKeyEnv string envTestAPIAccessKey string
doServiceCodeEnv string envTestAPISecretKeyEnv string
testDomain string envTestDoServiceCodeEnv string
liveTest bool envTestDomain string
) )
func init() { func init() {
apiAccessKeyEnv = os.Getenv("IIJ_API_ACCESS_KEY") envTestAPIAccessKey = os.Getenv("IIJ_API_ACCESS_KEY")
apiSecretKeyEnv = os.Getenv("IIJ_API_SECRET_KEY") envTestAPISecretKeyEnv = os.Getenv("IIJ_API_SECRET_KEY")
doServiceCodeEnv = os.Getenv("IIJ_DO_SERVICE_CODE") envTestDoServiceCodeEnv = os.Getenv("IIJ_DO_SERVICE_CODE")
testDomain = os.Getenv("IIJ_API_TESTDOMAIN") envTestDomain = os.Getenv("IIJ_API_TESTDOMAIN")
if len(apiAccessKeyEnv) > 0 && len(apiSecretKeyEnv) > 0 && len(doServiceCodeEnv) > 0 && len(testDomain) > 0 { if len(envTestAPIAccessKey) > 0 && len(envTestAPISecretKeyEnv) > 0 && len(envTestDoServiceCodeEnv) > 0 && len(envTestDomain) > 0 {
liveTest = true liveTest = true
} }
} }
func restoreEnv() { func restoreEnv() {
os.Setenv("IIJ_API_ACCESS_KEY", apiAccessKeyEnv) os.Setenv("IIJ_API_ACCESS_KEY", envTestAPIAccessKey)
os.Setenv("IIJ_API_SECRET_KEY", apiSecretKeyEnv) os.Setenv("IIJ_API_SECRET_KEY", envTestAPISecretKeyEnv)
os.Setenv("IIJ_DO_SERVICE_CODE", doServiceCodeEnv) os.Setenv("IIJ_DO_SERVICE_CODE", envTestDoServiceCodeEnv)
os.Setenv("IIJ_API_TESTDOMAIN", testDomain) }
func TestNewDNSProvider(t *testing.T) {
testCases := []struct {
desc string
envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
"IIJ_API_ACCESS_KEY": "A",
"IIJ_API_SECRET_KEY": "B",
"IIJ_DO_SERVICE_CODE": "C",
},
},
{
desc: "missing credentials",
envVars: map[string]string{
"IIJ_API_ACCESS_KEY": "",
"IIJ_API_SECRET_KEY": "",
"IIJ_DO_SERVICE_CODE": "",
},
expected: "iij: some credentials information are missing: IIJ_API_ACCESS_KEY,IIJ_API_SECRET_KEY,IIJ_DO_SERVICE_CODE",
},
{
desc: "missing api access key",
envVars: map[string]string{
"IIJ_API_ACCESS_KEY": "",
"IIJ_API_SECRET_KEY": "B",
"IIJ_DO_SERVICE_CODE": "C",
},
expected: "iij: some credentials information are missing: IIJ_API_ACCESS_KEY",
},
{
desc: "missing secret key",
envVars: map[string]string{
"IIJ_API_ACCESS_KEY": "A",
"IIJ_API_SECRET_KEY": "",
"IIJ_DO_SERVICE_CODE": "C",
},
expected: "iij: some credentials information are missing: IIJ_API_SECRET_KEY",
},
{
desc: "missing do service code",
envVars: map[string]string{
"IIJ_API_ACCESS_KEY": "A",
"IIJ_API_SECRET_KEY": "B",
"IIJ_DO_SERVICE_CODE": "",
},
expected: "iij: some credentials information are missing: IIJ_DO_SERVICE_CODE",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
for key, value := range test.envVars {
if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
}
p, err := NewDNSProvider()
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.api)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
func TestNewDNSProviderConfig(t *testing.T) {
testCases := []struct {
desc string
accessKey string
secretKey string
doServiceCode string
expected string
}{
{
desc: "success",
accessKey: "A",
secretKey: "B",
doServiceCode: "C",
},
{
desc: "missing credentials",
expected: "iij: credentials missing",
},
{
desc: "missing access key",
accessKey: "",
secretKey: "B",
doServiceCode: "C",
expected: "iij: credentials missing",
},
{
desc: "missing secret key",
accessKey: "A",
secretKey: "",
doServiceCode: "C",
expected: "iij: credentials missing",
},
{
desc: "missing do service code",
accessKey: "A",
secretKey: "B",
doServiceCode: "",
expected: "iij: credentials missing",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
os.Unsetenv("IIJ_API_ACCESS_KEY")
os.Unsetenv("IIJ_API_SECRET_KEY")
os.Unsetenv("IIJ_DO_SERVICE_CODE")
config := NewDefaultConfig()
config.AccessKey = test.accessKey
config.SecretKey = test.secretKey
config.DoServiceCode = test.doServiceCode
p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.api)
} else {
require.EqualError(t, err, test.expected)
}
})
}
} }
func TestSplitDomain(t *testing.T) { func TestSplitDomain(t *testing.T) {
@ -88,45 +231,28 @@ func TestSplitDomain(t *testing.T) {
} }
func TestNewDNSProviderMissingCredErr(t *testing.T) { func TestLivePresent(t *testing.T) {
defer restoreEnv()
os.Setenv("IIJ_API_ACCESS_KEY", "")
os.Setenv("IIJ_API_SECRET_KEY", "")
os.Setenv("IIJ_DO_SERVICE_CODE", "")
_, err := NewDNSProvider()
assert.EqualError(t, err, "iij: some credentials information are missing: IIJ_API_ACCESS_KEY,IIJ_API_SECRET_KEY,IIJ_DO_SERVICE_CODE")
}
func TestNewDNSProvider(t *testing.T) {
if !liveTest {
t.Skip("skipping live test")
}
_, err := NewDNSProvider()
assert.NoError(t, err)
}
func TestDNSProvider_Present(t *testing.T) {
if !liveTest { if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
restoreEnv()
provider, err := NewDNSProvider() provider, err := NewDNSProvider()
assert.NoError(t, err) require.NoError(t, err)
err = provider.Present(testDomain, "", "123d==") err = provider.Present(envTestDomain, "", "123d==")
assert.NoError(t, err) require.NoError(t, err)
} }
func TestDNSProvider_CleanUp(t *testing.T) { func TestLiveCleanUp(t *testing.T) {
if !liveTest { if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
restoreEnv()
provider, err := NewDNSProvider() provider, err := NewDNSProvider()
assert.NoError(t, err) require.NoError(t, err)
err = provider.CleanUp(testDomain, "", "123d==") err = provider.CleanUp(envTestDomain, "", "123d==")
assert.NoError(t, err) require.NoError(t, err)
} }

View file

@ -11,7 +11,7 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
func TestLightsailTTL(t *testing.T) { func TestLiveTTL(t *testing.T) {
m, err := testGetAndPreCheck() m, err := testGetAndPreCheck()
if err != nil { if err != nil {
t.Skip(err.Error()) t.Skip(err.Error())
@ -20,14 +20,14 @@ func TestLightsailTTL(t *testing.T) {
provider, err := NewDNSProvider() provider, err := NewDNSProvider()
require.NoError(t, err) require.NoError(t, err)
lightsailDomain := m["lightsailDomain"] domain := m["lightsailDomain"]
err = provider.Present(lightsailDomain, "foo", "bar") err = provider.Present(domain, "foo", "bar")
require.NoError(t, err) require.NoError(t, err)
// we need a separate Lightshail client here as the one in the DNS provider is // we need a separate Lightsail client here as the one in the DNS provider is
// unexported. // unexported.
fqdn := "_acme-challenge." + lightsailDomain fqdn := "_acme-challenge." + domain
sess, err := session.NewSession() sess, err := session.NewSession()
require.NoError(t, err) require.NoError(t, err)
@ -35,14 +35,14 @@ func TestLightsailTTL(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
defer func() { defer func() {
errC := provider.CleanUp(lightsailDomain, "foo", "bar") errC := provider.CleanUp(domain, "foo", "bar")
if errC != nil { if errC != nil {
t.Log(errC) t.Log(errC)
} }
}() }()
params := &lightsail.GetDomainInput{ params := &lightsail.GetDomainInput{
DomainName: aws.String(lightsailDomain), DomainName: aws.String(domain),
} }
resp, err := svc.GetDomain(params) resp, err := svc.GetDomain(params)
@ -55,7 +55,7 @@ func TestLightsailTTL(t *testing.T) {
} }
} }
t.Fatalf("Could not find a TXT record for _acme-challenge.%s", lightsailDomain) t.Fatalf("Could not find a TXT record for _acme-challenge.%s", domain)
} }
func testGetAndPreCheck() (map[string]string, error) { func testGetAndPreCheck() (map[string]string, error) {

View file

@ -13,24 +13,24 @@ import (
) )
var ( var (
lightsailSecret string envTestSecret string
lightsailKey string envTestKey string
lightsailZone string envTestZone string
) )
func init() { func init() {
lightsailKey = os.Getenv("AWS_ACCESS_KEY_ID") envTestKey = os.Getenv("AWS_ACCESS_KEY_ID")
lightsailSecret = os.Getenv("AWS_SECRET_ACCESS_KEY") envTestSecret = os.Getenv("AWS_SECRET_ACCESS_KEY")
} }
func restoreEnv() { func restoreEnv() {
os.Setenv("AWS_ACCESS_KEY_ID", lightsailKey) os.Setenv("AWS_ACCESS_KEY_ID", envTestKey)
os.Setenv("AWS_SECRET_ACCESS_KEY", lightsailSecret) os.Setenv("AWS_SECRET_ACCESS_KEY", envTestSecret)
os.Setenv("AWS_REGION", "us-east-1") os.Setenv("AWS_REGION", "us-east-1")
os.Setenv("AWS_HOSTED_ZONE_ID", lightsailZone) os.Setenv("AWS_HOSTED_ZONE_ID", envTestZone)
} }
func makeLightsailProvider(ts *httptest.Server) (*DNSProvider, error) { func makeProvider(ts *httptest.Server) (*DNSProvider, error) {
config := &aws.Config{ config := &aws.Config{
Credentials: credentials.NewStaticCredentials("abc", "123", " "), Credentials: credentials.NewStaticCredentials("abc", "123", " "),
Endpoint: aws.String(ts.URL), Endpoint: aws.String(ts.URL),
@ -66,7 +66,7 @@ func TestCredentialsFromEnv(t *testing.T) {
require.NoError(t, err, "Expected credentials to be set from environment") require.NoError(t, err, "Expected credentials to be set from environment")
} }
func TestLightsailPresent(t *testing.T) { func TestDNSProvider_Present(t *testing.T) {
mockResponses := map[string]MockResponse{ mockResponses := map[string]MockResponse{
"/": {StatusCode: 200, Body: ""}, "/": {StatusCode: 200, Body: ""},
} }
@ -74,7 +74,7 @@ func TestLightsailPresent(t *testing.T) {
ts := newMockServer(t, mockResponses) ts := newMockServer(t, mockResponses)
defer ts.Close() defer ts.Close()
provider, err := makeLightsailProvider(ts) provider, err := makeProvider(ts)
require.NoError(t, err) require.NoError(t, err)
domain := "example.com" domain := "example.com"

View file

@ -16,7 +16,7 @@ import (
) )
type ( type (
LinodeResponse struct { apiResponse struct {
Action string `json:"ACTION"` Action string `json:"ACTION"`
Data interface{} `json:"DATA"` Data interface{} `json:"DATA"`
Errors []linode.ResponseError `json:"ERRORARRAY"` Errors []linode.ResponseError `json:"ERRORARRAY"`
@ -29,38 +29,41 @@ type (
) )
var ( var (
apiKey string apiKey string
isTestLive bool liveTest bool
) )
func init() { func init() {
apiKey = os.Getenv("LINODE_API_KEY") apiKey = os.Getenv("LINODE_API_KEY")
isTestLive = len(apiKey) != 0
liveTest = len(apiKey) != 0
} }
func restoreEnv() { func restoreEnv() {
os.Setenv("LINODE_API_KEY", apiKey) os.Setenv("LINODE_API_KEY", apiKey)
} }
func newMockServer(t *testing.T, responses MockResponseMap) *httptest.Server { func newMockServer(responses MockResponseMap) *httptest.Server {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Ensure that we support the requested action. // Ensure that we support the requested action.
action := r.URL.Query().Get("api_action") action := r.URL.Query().Get("api_action")
resp, ok := responses[action] resp, ok := responses[action]
if !ok { if !ok {
require.FailNowf(t, "Unsupported mock action: %q", action) http.Error(w, fmt.Sprintf("Unsupported mock action: %q", action), http.StatusInternalServerError)
return
} }
// Build the response that the server will return. // Build the response that the server will return.
linodeResponse := LinodeResponse{ response := apiResponse{
Action: action, Action: action,
Data: resp.Response, Data: resp.Response,
Errors: resp.Errors, Errors: resp.Errors,
} }
rawResponse, err := json.Marshal(linodeResponse)
rawResponse, err := json.Marshal(response)
if err != nil { if err != nil {
msg := fmt.Sprintf("Failed to JSON encode response: %v", err) http.Error(w, fmt.Sprintf("Failed to JSON encode response: %v", err), http.StatusInternalServerError)
require.FailNow(t, msg) return
} }
// Send the response. // Send the response.
@ -77,35 +80,88 @@ func newMockServer(t *testing.T, responses MockResponseMap) *httptest.Server {
return srv return srv
} }
func TestNewDNSProviderWithEnv(t *testing.T) { func TestNewDNSProvider(t *testing.T) {
defer restoreEnv() testCases := []struct {
os.Setenv("LINODE_API_KEY", "testing") desc string
envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
"LINODE_API_KEY": "123",
},
},
{
desc: "missing api key",
envVars: map[string]string{
"LINODE_API_KEY": "",
},
expected: "linode: some credentials information are missing: LINODE_API_KEY",
},
}
_, err := NewDNSProvider() for _, test := range testCases {
require.NoError(t, err) t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
for key, value := range test.envVars {
if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
}
p, err := NewDNSProvider()
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
} }
func TestNewDNSProviderWithoutEnv(t *testing.T) { func TestNewDNSProviderConfig(t *testing.T) {
defer restoreEnv() testCases := []struct {
os.Setenv("LINODE_API_KEY", "") desc string
apiKey string
expected string
}{
{
desc: "success",
apiKey: "123",
},
{
desc: "missing credentials",
expected: "linode: credentials missing",
},
}
_, err := NewDNSProvider() for _, test := range testCases {
assert.EqualError(t, err, "linode: some credentials information are missing: LINODE_API_KEY") t.Run(test.desc, func(t *testing.T) {
} defer restoreEnv()
os.Unsetenv("LINODE_API_KEY")
func TestNewDNSProviderWithKey(t *testing.T) { config := NewDefaultConfig()
config := NewDefaultConfig() config.APIKey = test.apiKey
config.APIKey = "testing"
_, err := NewDNSProviderConfig(config) p, err := NewDNSProviderConfig(config)
require.NoError(t, err)
}
func TestNewDNSProviderWithoutKey(t *testing.T) { if len(test.expected) == 0 {
config := NewDefaultConfig() require.NoError(t, err)
require.NotNil(t, p)
_, err := NewDNSProviderConfig(config) require.NotNil(t, p.config)
assert.EqualError(t, err, "linode: credentials missing") require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
} }
func TestDNSProvider_Present(t *testing.T) { func TestDNSProvider_Present(t *testing.T) {
@ -180,11 +236,10 @@ func TestDNSProvider_Present(t *testing.T) {
for _, test := range testCases { for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) { t.Run(test.desc, func(t *testing.T) {
server := newMockServer(test.mockResponses)
defer server.Close()
mockSrv := newMockServer(t, test.mockResponses) p.client.ToLinode().SetEndpoint(server.URL)
defer mockSrv.Close()
p.client.ToLinode().SetEndpoint(mockSrv.URL)
err = p.Present(domain, "", keyAuth) err = p.Present(domain, "", keyAuth)
if len(test.expectedError) == 0 { if len(test.expectedError) == 0 {
@ -196,13 +251,6 @@ func TestDNSProvider_Present(t *testing.T) {
} }
} }
func TestDNSProvider_PresentLive(t *testing.T) {
if !isTestLive {
t.Skip("Skipping live test")
}
// TODO implement this test
}
func TestDNSProvider_CleanUp(t *testing.T) { func TestDNSProvider_CleanUp(t *testing.T) {
defer restoreEnv() defer restoreEnv()
os.Setenv("LINODE_API_KEY", "testing") os.Setenv("LINODE_API_KEY", "testing")
@ -299,10 +347,10 @@ func TestDNSProvider_CleanUp(t *testing.T) {
for _, test := range testCases { for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) { t.Run(test.desc, func(t *testing.T) {
mockSrv := newMockServer(t, test.mockResponses) server := newMockServer(test.mockResponses)
defer mockSrv.Close() defer server.Close()
p.client.ToLinode().SetEndpoint(mockSrv.URL) p.client.ToLinode().SetEndpoint(server.URL)
err = p.CleanUp(domain, "", keyAuth) err = p.CleanUp(domain, "", keyAuth)
if len(test.expectedError) == 0 { if len(test.expectedError) == 0 {
@ -313,3 +361,17 @@ func TestDNSProvider_CleanUp(t *testing.T) {
}) })
} }
} }
func TestLivePresent(t *testing.T) {
if !liveTest {
t.Skip("Skipping live test")
}
// TODO implement this test
}
func TestLiveCleanUp(t *testing.T) {
if !liveTest {
t.Skip("Skipping live test")
}
// TODO implement this test
}

View file

@ -19,32 +19,34 @@ type (
) )
var ( var (
apiToken string liveTest bool
isTestLive bool envTestAPIToken string
) )
func init() { func init() {
apiToken = os.Getenv("LINODE_TOKEN") envTestAPIToken = os.Getenv("LINODE_TOKEN")
isTestLive = len(apiToken) != 0
liveTest = len(envTestAPIToken) != 0
} }
func restoreEnv() { func restoreEnv() {
os.Setenv("LINODE_TOKEN", apiToken) os.Setenv("LINODE_TOKEN", envTestAPIToken)
} }
func newMockServer(t *testing.T, responses MockResponseMap) *httptest.Server { func newMockServer(responses MockResponseMap) *httptest.Server {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Ensure that we support the requested action. // Ensure that we support the requested action.
action := r.Method + ":" + r.URL.Path action := r.Method + ":" + r.URL.Path
resp, ok := responses[action] resp, ok := responses[action]
if !ok { if !ok {
require.FailNowf(t, "Unsupported mock", "action: %s", action) http.Error(w, fmt.Sprintf("Unsupported mock action: %q", action), http.StatusInternalServerError)
return
} }
rawResponse, err := json.Marshal(resp) rawResponse, err := json.Marshal(resp)
if err != nil { if err != nil {
msg := fmt.Sprintf("Failed to JSON encode response: %v", err) http.Error(w, fmt.Sprintf("Failed to JSON encode response: %v", err), http.StatusInternalServerError)
require.FailNow(t, msg) return
} }
// Send the response. // Send the response.
@ -69,36 +71,88 @@ func newMockServer(t *testing.T, responses MockResponseMap) *httptest.Server {
return srv return srv
} }
func TestNewDNSProviderWithEnv(t *testing.T) { func TestNewDNSProvider(t *testing.T) {
defer restoreEnv() testCases := []struct {
os.Setenv("LINODE_TOKEN", "testing") desc string
envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
"LINODE_TOKEN": "123",
},
},
{
desc: "missing api key",
envVars: map[string]string{
"LINODE_TOKEN": "",
},
expected: "linodev4: some credentials information are missing: LINODE_TOKEN",
},
}
_, err := NewDNSProvider() for _, test := range testCases {
assert.NoError(t, err) t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
for key, value := range test.envVars {
if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
}
p, err := NewDNSProvider()
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
} }
func TestNewDNSProviderWithoutEnv(t *testing.T) { func TestNewDNSProviderConfig(t *testing.T) {
defer restoreEnv() testCases := []struct {
os.Setenv("LINODE_TOKEN", "") desc string
apiKey string
expected string
}{
{
desc: "success",
apiKey: "123",
},
{
desc: "missing credentials",
expected: "linodev4: Linode Access Token missing",
},
}
_, err := NewDNSProvider() for _, test := range testCases {
assert.EqualError(t, err, "linodev4: some credentials information are missing: LINODE_TOKEN") t.Run(test.desc, func(t *testing.T) {
} defer restoreEnv()
os.Unsetenv("LINODE_TOKEN")
func TestNewDNSProviderWithKey(t *testing.T) { config := NewDefaultConfig()
config := NewDefaultConfig() config.Token = test.apiKey
config.Token = "testing"
_, err := NewDNSProviderConfig(config) p, err := NewDNSProviderConfig(config)
assert.NoError(t, err)
}
func TestNewDNSProviderWithoutKey(t *testing.T) { if len(test.expected) == 0 {
config := NewDefaultConfig() require.NoError(t, err)
config.Token = "" require.NotNil(t, p)
require.NotNil(t, p.config)
_, err := NewDNSProviderConfig(config) require.NotNil(t, p.client)
assert.EqualError(t, err, "linodev4: Linode Access Token missing") } else {
require.EqualError(t, err, test.expected)
}
})
}
} }
func TestDNSProvider_Present(t *testing.T) { func TestDNSProvider_Present(t *testing.T) {
@ -175,11 +229,11 @@ func TestDNSProvider_Present(t *testing.T) {
for _, test := range testCases { for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) { t.Run(test.desc, func(t *testing.T) {
mockSrv := newMockServer(t, test.mockResponses) server := newMockServer(test.mockResponses)
defer mockSrv.Close() defer server.Close()
assert.NotNil(t, p.client) assert.NotNil(t, p.client)
p.client.SetBaseURL(mockSrv.URL) p.client.SetBaseURL(server.URL)
err = p.Present(domain, "", keyAuth) err = p.Present(domain, "", keyAuth)
if len(test.expectedError) == 0 { if len(test.expectedError) == 0 {
@ -191,13 +245,6 @@ func TestDNSProvider_Present(t *testing.T) {
} }
} }
func TestDNSProvider_PresentLive(t *testing.T) {
if !isTestLive {
t.Skip("Skipping live test")
}
// TODO implement this test
}
func TestDNSProvider_CleanUp(t *testing.T) { func TestDNSProvider_CleanUp(t *testing.T) {
defer restoreEnv() defer restoreEnv()
os.Setenv("LINODE_TOKEN", "testing") os.Setenv("LINODE_TOKEN", "testing")
@ -298,10 +345,10 @@ func TestDNSProvider_CleanUp(t *testing.T) {
for _, test := range testCases { for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) { t.Run(test.desc, func(t *testing.T) {
mockSrv := newMockServer(t, test.mockResponses) server := newMockServer(test.mockResponses)
defer mockSrv.Close() defer server.Close()
p.client.SetBaseURL(mockSrv.URL) p.client.SetBaseURL(server.URL)
err = p.CleanUp(domain, "", keyAuth) err = p.CleanUp(domain, "", keyAuth)
if len(test.expectedError) == 0 { if len(test.expectedError) == 0 {
@ -312,3 +359,17 @@ func TestDNSProvider_CleanUp(t *testing.T) {
}) })
} }
} }
func TestLivePresent(t *testing.T) {
if !liveTest {
t.Skip("Skipping live test")
}
// TODO implement this test
}
func TestLiveCleanUp(t *testing.T) {
if !liveTest {
t.Skip("Skipping live test")
}
// TODO implement this test
}

View file

@ -13,9 +13,9 @@ import (
) )
var ( var (
fakeUser = "foo" envTestUser = "foo"
fakeKey = "bar" envTestKey = "bar"
fakeClientIP = "10.0.0.1" envTestClientIP = "10.0.0.1"
tlds = map[string]string{ tlds = map[string]string{
"com.au": "com.au", "com.au": "com.au",
@ -28,24 +28,13 @@ var (
} }
) )
func TestGetHosts(t *testing.T) { func TestDNSProvider_getHosts(t *testing.T) {
for _, test := range testCases { for _, test := range testCases {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
mock := httptest.NewServer(http.HandlerFunc( mock := httptest.NewServer(mockServer(&test, t))
func(w http.ResponseWriter, r *http.Request) {
mockServer(&test, t, w, r)
}))
defer mock.Close() defer mock.Close()
config := NewDefaultConfig() provider := mockDNSProvider(mock.URL)
config.BaseURL = mock.URL
config.APIUser = fakeUser
config.APIKey = fakeKey
config.ClientIP = fakeClientIP
config.HTTPClient = &http.Client{Timeout: 60 * time.Second}
provider, err := NewDNSProviderConfig(config)
require.NoError(t, err)
ch, err := newChallenge(test.domain, "", tlds) ch, err := newChallenge(test.domain, "", tlds)
require.NoError(t, err) require.NoError(t, err)
@ -80,13 +69,10 @@ func TestGetHosts(t *testing.T) {
} }
} }
func TestSetHosts(t *testing.T) { func TestDNSProvider_setHosts(t *testing.T) {
for _, test := range testCases { for _, test := range testCases {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
mock := httptest.NewServer(http.HandlerFunc( mock := httptest.NewServer(mockServer(&test, t))
func(w http.ResponseWriter, r *http.Request) {
mockServer(&test, t, w, r)
}))
defer mock.Close() defer mock.Close()
prov := mockDNSProvider(mock.URL) prov := mockDNSProvider(mock.URL)
@ -110,13 +96,10 @@ func TestSetHosts(t *testing.T) {
} }
} }
func TestPresent(t *testing.T) { func TestDNSProvider_Present(t *testing.T) {
for _, test := range testCases { for _, test := range testCases {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
mock := httptest.NewServer(http.HandlerFunc( mock := httptest.NewServer(mockServer(&test, t))
func(w http.ResponseWriter, r *http.Request) {
mockServer(&test, t, w, r)
}))
defer mock.Close() defer mock.Close()
prov := mockDNSProvider(mock.URL) prov := mockDNSProvider(mock.URL)
@ -130,13 +113,10 @@ func TestPresent(t *testing.T) {
} }
} }
func TestCleanUp(t *testing.T) { func TestDNSProvider_CleanUp(t *testing.T) {
for _, test := range testCases { for _, test := range testCases {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
mock := httptest.NewServer(http.HandlerFunc( mock := httptest.NewServer(mockServer(&test, t))
func(w http.ResponseWriter, r *http.Request) {
mockServer(&test, t, w, r)
}))
defer mock.Close() defer mock.Close()
prov := mockDNSProvider(mock.URL) prov := mockDNSProvider(mock.URL)
@ -210,60 +190,61 @@ func assertEq(t *testing.T, variable, got, want string) {
func assertHdr(tc *testCase, t *testing.T, values *url.Values) { func assertHdr(tc *testCase, t *testing.T, values *url.Values) {
ch, _ := newChallenge(tc.domain, "", tlds) ch, _ := newChallenge(tc.domain, "", tlds)
assertEq(t, "ApiUser", values.Get("ApiUser"), fakeUser) assertEq(t, "ApiUser", values.Get("ApiUser"), envTestUser)
assertEq(t, "ApiKey", values.Get("ApiKey"), fakeKey) assertEq(t, "ApiKey", values.Get("ApiKey"), envTestKey)
assertEq(t, "UserName", values.Get("UserName"), fakeUser) assertEq(t, "UserName", values.Get("UserName"), envTestUser)
assertEq(t, "ClientIp", values.Get("ClientIp"), fakeClientIP) assertEq(t, "ClientIp", values.Get("ClientIp"), envTestClientIP)
assertEq(t, "SLD", values.Get("SLD"), ch.sld) assertEq(t, "SLD", values.Get("SLD"), ch.sld)
assertEq(t, "TLD", values.Get("TLD"), ch.tld) assertEq(t, "TLD", values.Get("TLD"), ch.tld)
} }
func mockServer(tc *testCase, t *testing.T, w http.ResponseWriter, r *http.Request) { func mockServer(tc *testCase, t *testing.T) http.Handler {
switch r.Method { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
values := r.URL.Query()
cmd := values.Get("Command")
switch cmd {
case "namecheap.domains.dns.getHosts":
assertHdr(tc, t, &values)
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, tc.getHostsResponse)
case "namecheap.domains.getTldList":
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, responseGetTlds)
default:
t.Errorf("Unexpected GET command: %s", cmd)
}
case http.MethodPost:
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
values := r.Form
cmd := values.Get("Command")
switch cmd {
case "namecheap.domains.dns.setHosts":
assertHdr(tc, t, &values)
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, tc.setHostsResponse)
default:
t.Errorf("Unexpected POST command: %s", cmd)
}
case http.MethodGet:
values := r.URL.Query()
cmd := values.Get("Command")
switch cmd {
case "namecheap.domains.dns.getHosts":
assertHdr(tc, t, &values)
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, tc.getHostsResponse)
case "namecheap.domains.getTldList":
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, responseGetTlds)
default: default:
t.Errorf("Unexpected GET command: %s", cmd) t.Errorf("Unexpected http method: %s", r.Method)
} }
})
case http.MethodPost:
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
values := r.Form
cmd := values.Get("Command")
switch cmd {
case "namecheap.domains.dns.setHosts":
assertHdr(tc, t, &values)
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, tc.setHostsResponse)
default:
t.Errorf("Unexpected POST command: %s", cmd)
}
default:
t.Errorf("Unexpected http method: %s", r.Method)
}
} }
func mockDNSProvider(url string) *DNSProvider { func mockDNSProvider(url string) *DNSProvider {
config := NewDefaultConfig() config := NewDefaultConfig()
config.BaseURL = url config.BaseURL = url
config.APIUser = fakeUser config.APIUser = envTestUser
config.APIKey = fakeKey config.APIKey = envTestKey
config.ClientIP = fakeClientIP config.ClientIP = envTestClientIP
config.HTTPClient = &http.Client{Timeout: 60 * time.Second} config.HTTPClient = &http.Client{Timeout: 60 * time.Second}
provider, err := NewDNSProviderConfig(config) provider, err := NewDNSProviderConfig(config)

View file

@ -9,60 +9,169 @@ import (
) )
var ( var (
namedotcomLiveTest bool liveTest bool
namedotcomUsername string envTestUsername string
namedotcomAPIToken string envTestAPIToken string
namedotcomDomain string envTestDomain string
namedotcomServer string
) )
func init() { func init() {
namedotcomUsername = os.Getenv("NAMEDOTCOM_USERNAME") envTestUsername = os.Getenv("NAMECOM_USERNAME")
namedotcomAPIToken = os.Getenv("NAMEDOTCOM_API_TOKEN") envTestAPIToken = os.Getenv("NAMECOM_API_TOKEN")
namedotcomDomain = os.Getenv("NAMEDOTCOM_DOMAIN") envTestDomain = os.Getenv("NAMEDOTCOM_DOMAIN")
namedotcomServer = os.Getenv("NAMEDOTCOM_SERVER")
if len(namedotcomAPIToken) > 0 && len(namedotcomUsername) > 0 && len(namedotcomDomain) > 0 { if len(envTestAPIToken) > 0 && len(envTestUsername) > 0 && len(envTestDomain) > 0 {
namedotcomLiveTest = true liveTest = true
} }
} }
func TestLiveNamedotcomPresent(t *testing.T) { func restoreEnv() {
if !namedotcomLiveTest { os.Setenv("NAMECOM_USERNAME", envTestUsername)
os.Setenv("NAMECOM_API_TOKEN", envTestAPIToken)
}
func TestNewDNSProvider(t *testing.T) {
testCases := []struct {
desc string
envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
"NAMECOM_USERNAME": "A",
"NAMECOM_API_TOKEN": "B",
},
},
{
desc: "missing credentials",
envVars: map[string]string{
"NAMECOM_USERNAME": "",
"NAMECOM_API_TOKEN": "",
},
expected: "namedotcom: some credentials information are missing: NAMECOM_USERNAME,NAMECOM_API_TOKEN",
},
{
desc: "missing username",
envVars: map[string]string{
"NAMECOM_USERNAME": "",
"NAMECOM_API_TOKEN": "B",
},
expected: "namedotcom: some credentials information are missing: NAMECOM_USERNAME",
},
{
desc: "missing api token",
envVars: map[string]string{
"NAMECOM_USERNAME": "A",
"NAMECOM_API_TOKEN": "",
},
expected: "namedotcom: some credentials information are missing: NAMECOM_API_TOKEN",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
for key, value := range test.envVars {
if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
}
p, err := NewDNSProvider()
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
func TestNewDNSProviderConfig(t *testing.T) {
testCases := []struct {
desc string
apiToken string
username string
expected string
}{
{
desc: "success",
apiToken: "A",
username: "B",
},
{
desc: "missing credentials",
expected: "namedotcom: username is required",
},
{
desc: "missing API token",
apiToken: "",
username: "B",
expected: "namedotcom: API token is required",
},
{
desc: "missing username",
apiToken: "A",
username: "",
expected: "namedotcom: username is required",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
os.Unsetenv("NAMECOM_USERNAME")
os.Unsetenv("NAMECOM_API_TOKEN")
config := NewDefaultConfig()
config.Username = test.username
config.APIToken = test.apiToken
p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
func TestLivePresent(t *testing.T) {
if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
config := NewDefaultConfig() restoreEnv()
config.Username = namedotcomUsername provider, err := NewDNSProvider()
config.APIToken = namedotcomAPIToken
config.Server = namedotcomServer
provider, err := NewDNSProviderConfig(config)
require.NoError(t, err) require.NoError(t, err)
err = provider.Present(namedotcomDomain, "", "123d==") err = provider.Present(envTestDomain, "", "123d==")
require.NoError(t, err) require.NoError(t, err)
} }
// func TestLiveCleanUp(t *testing.T) {
// Cleanup if !liveTest {
//
func TestLiveNamedotcomCleanUp(t *testing.T) {
if !namedotcomLiveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
time.Sleep(time.Second * 1) restoreEnv()
provider, err := NewDNSProvider()
config := NewDefaultConfig()
config.Username = namedotcomUsername
config.APIToken = namedotcomAPIToken
config.Server = namedotcomServer
provider, err := NewDNSProviderConfig(config)
require.NoError(t, err) require.NoError(t, err)
err = provider.CleanUp(namedotcomDomain, "", "123d==") time.Sleep(1 * time.Second)
err = provider.CleanUp(envTestDomain, "", "123d==")
require.NoError(t, err) require.NoError(t, err)
} }

View file

@ -6,16 +6,17 @@ import (
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/xenolf/lego/acme" "github.com/xenolf/lego/acme"
) )
func TestClientAuth(t *testing.T) { func TestLiveClientAuth(t *testing.T) {
if !testLive { if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
// Setup // Setup
client := NewClient(testCustomerNumber, testAPIKey, testAPIPassword) client := NewClient(envTestCustomerNumber, envTestAPIKey, envTestAPIPassword)
for i := 1; i < 4; i++ { for i := 1; i < 4; i++ {
i := i i := i
@ -23,57 +24,57 @@ func TestClientAuth(t *testing.T) {
t.Parallel() t.Parallel()
sessionID, err := client.Login() sessionID, err := client.Login()
assert.NoError(t, err) require.NoError(t, err)
err = client.Logout(sessionID) err = client.Logout(sessionID)
assert.NoError(t, err) require.NoError(t, err)
}) })
} }
} }
func TestClientGetDnsRecords(t *testing.T) { func TestLiveClientGetDnsRecords(t *testing.T) {
if !testLive { if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
client := NewClient(testCustomerNumber, testAPIKey, testAPIPassword) client := NewClient(envTestCustomerNumber, envTestAPIKey, envTestAPIPassword)
// Setup // Setup
sessionID, err := client.Login() sessionID, err := client.Login()
assert.NoError(t, err) require.NoError(t, err)
fqdn, _, _ := acme.DNS01Record(testDomain, "123d==") fqdn, _, _ := acme.DNS01Record(envTestDomain, "123d==")
zone, err := acme.FindZoneByFqdn(fqdn, acme.RecursiveNameservers) zone, err := acme.FindZoneByFqdn(fqdn, acme.RecursiveNameservers)
assert.NoError(t, err, "error finding DNSZone") require.NoError(t, err, "error finding DNSZone")
zone = acme.UnFqdn(zone) zone = acme.UnFqdn(zone)
// TestMethod // TestMethod
_, err = client.GetDNSRecords(zone, sessionID) _, err = client.GetDNSRecords(zone, sessionID)
assert.NoError(t, err) require.NoError(t, err)
// Tear down // Tear down
err = client.Logout(sessionID) err = client.Logout(sessionID)
assert.NoError(t, err) require.NoError(t, err)
} }
func TestClientUpdateDnsRecord(t *testing.T) { func TestLiveClientUpdateDnsRecord(t *testing.T) {
if !testLive { if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
// Setup // Setup
client := NewClient(testCustomerNumber, testAPIKey, testAPIPassword) client := NewClient(envTestCustomerNumber, envTestAPIKey, envTestAPIPassword)
sessionID, err := client.Login() sessionID, err := client.Login()
assert.NoError(t, err) require.NoError(t, err)
fqdn, _, _ := acme.DNS01Record(testDomain, "123d==") fqdn, _, _ := acme.DNS01Record(envTestDomain, "123d==")
zone, err := acme.FindZoneByFqdn(fqdn, acme.RecursiveNameservers) zone, err := acme.FindZoneByFqdn(fqdn, acme.RecursiveNameservers)
assert.NoError(t, err, fmt.Errorf("error finding DNSZone, %v", err)) require.NoError(t, err, fmt.Errorf("error finding DNSZone, %v", err))
hostname := strings.Replace(fqdn, "."+zone, "", 1) hostname := strings.Replace(fqdn, "."+zone, "", 1)
@ -83,13 +84,13 @@ func TestClientUpdateDnsRecord(t *testing.T) {
zone = acme.UnFqdn(zone) zone = acme.UnFqdn(zone)
err = client.UpdateDNSRecord(sessionID, zone, record) err = client.UpdateDNSRecord(sessionID, zone, record)
assert.NoError(t, err) require.NoError(t, err)
records, err := client.GetDNSRecords(zone, sessionID) records, err := client.GetDNSRecords(zone, sessionID)
assert.NoError(t, err) require.NoError(t, err)
recordIdx, err := GetDNSRecordIdx(records, record) recordIdx, err := GetDNSRecordIdx(records, record)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, record.Hostname, records[recordIdx].Hostname) assert.Equal(t, record.Hostname, records[recordIdx].Hostname)
assert.Equal(t, record.RecordType, records[recordIdx].RecordType) assert.Equal(t, record.RecordType, records[recordIdx].RecordType)
@ -99,11 +100,11 @@ func TestClientUpdateDnsRecord(t *testing.T) {
records[recordIdx].DeleteRecord = true records[recordIdx].DeleteRecord = true
// Tear down // Tear down
err = client.UpdateDNSRecord(sessionID, testDomain, records[recordIdx]) err = client.UpdateDNSRecord(sessionID, envTestDomain, records[recordIdx])
assert.NoError(t, err, "Did not remove record! Please do so yourself.") require.NoError(t, err, "Did not remove record! Please do so yourself.")
err = client.Logout(sessionID) err = client.Logout(sessionID)
assert.NoError(t, err) require.NoError(t, err)
} }
func TestClientGetDnsRecordIdx(t *testing.T) { func TestClientGetDnsRecordIdx(t *testing.T) {

View file

@ -5,41 +5,192 @@ import (
"os" "os"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/require"
"github.com/xenolf/lego/acme" "github.com/xenolf/lego/acme"
) )
var ( var (
testLive bool liveTest bool
testCustomerNumber string envTestCustomerNumber string
testAPIKey string envTestAPIKey string
testAPIPassword string envTestAPIPassword string
testDomain string envTestDomain string
) )
func init() { func init() {
testCustomerNumber = os.Getenv("NETCUP_CUSTOMER_NUMBER") envTestCustomerNumber = os.Getenv("NETCUP_CUSTOMER_NUMBER")
testAPIKey = os.Getenv("NETCUP_API_KEY") envTestAPIKey = os.Getenv("NETCUP_API_KEY")
testAPIPassword = os.Getenv("NETCUP_API_PASSWORD") envTestAPIPassword = os.Getenv("NETCUP_API_PASSWORD")
testDomain = os.Getenv("NETCUP_DOMAIN") envTestDomain = os.Getenv("NETCUP_DOMAIN")
if len(testCustomerNumber) > 0 && len(testAPIKey) > 0 && len(testAPIPassword) > 0 && len(testDomain) > 0 { if len(envTestCustomerNumber) > 0 && len(envTestAPIKey) > 0 && len(envTestAPIPassword) > 0 && len(envTestDomain) > 0 {
testLive = true liveTest = true
} }
} }
func TestDNSProviderPresentAndCleanup(t *testing.T) { func restoreEnv() {
if !testLive { os.Setenv("NETCUP_CUSTOMER_NUMBER", envTestCustomerNumber)
os.Setenv("NETCUP_API_KEY", envTestAPIKey)
os.Setenv("NETCUP_API_PASSWORD", envTestAPIPassword)
}
func TestNewDNSProvider(t *testing.T) {
testCases := []struct {
desc string
envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
"NETCUP_CUSTOMER_NUMBER": "A",
"NETCUP_API_KEY": "B",
"NETCUP_API_PASSWORD": "C",
},
},
{
desc: "missing credentials",
envVars: map[string]string{
"NETCUP_CUSTOMER_NUMBER": "",
"NETCUP_API_KEY": "",
"NETCUP_API_PASSWORD": "",
},
expected: "netcup: some credentials information are missing: NETCUP_CUSTOMER_NUMBER,NETCUP_API_KEY,NETCUP_API_PASSWORD",
},
{
desc: "missing customer number",
envVars: map[string]string{
"NETCUP_CUSTOMER_NUMBER": "",
"NETCUP_API_KEY": "B",
"NETCUP_API_PASSWORD": "C",
},
expected: "netcup: some credentials information are missing: NETCUP_CUSTOMER_NUMBER",
},
{
desc: "missing API key",
envVars: map[string]string{
"NETCUP_CUSTOMER_NUMBER": "A",
"NETCUP_API_KEY": "",
"NETCUP_API_PASSWORD": "C",
},
expected: "netcup: some credentials information are missing: NETCUP_API_KEY",
},
{
desc: "missing api password",
envVars: map[string]string{
"NETCUP_CUSTOMER_NUMBER": "A",
"NETCUP_API_KEY": "B",
"NETCUP_API_PASSWORD": "",
},
expected: "netcup: some credentials information are missing: NETCUP_API_PASSWORD",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
for key, value := range test.envVars {
if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
}
p, err := NewDNSProvider()
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
func TestNewDNSProviderConfig(t *testing.T) {
testCases := []struct {
desc string
customer string
key string
password string
expected string
}{
{
desc: "success",
customer: "A",
key: "B",
password: "C",
},
{
desc: "missing credentials",
expected: "netcup: netcup credentials missing",
},
{
desc: "missing customer",
customer: "",
key: "B",
password: "C",
expected: "netcup: netcup credentials missing",
},
{
desc: "missing key",
customer: "A",
key: "",
password: "C",
expected: "netcup: netcup credentials missing",
},
{
desc: "missing password",
customer: "A",
key: "B",
password: "",
expected: "netcup: netcup credentials missing",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
os.Unsetenv("NETCUP_CUSTOMER_NUMBER")
os.Unsetenv("NETCUP_API_KEY")
os.Unsetenv("NETCUP_API_PASSWORD")
config := NewDefaultConfig()
config.Customer = test.customer
config.Key = test.key
config.Password = test.password
p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
func TestLivePresentAndCleanup(t *testing.T) {
if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
restoreEnv()
p, err := NewDNSProvider() p, err := NewDNSProvider()
assert.NoError(t, err) require.NoError(t, err)
fqdn, _, _ := acme.DNS01Record(testDomain, "123d==") fqdn, _, _ := acme.DNS01Record(envTestDomain, "123d==")
zone, err := acme.FindZoneByFqdn(fqdn, acme.RecursiveNameservers) zone, err := acme.FindZoneByFqdn(fqdn, acme.RecursiveNameservers)
assert.NoError(t, err, "error finding DNSZone") require.NoError(t, err, "error finding DNSZone")
zone = acme.UnFqdn(zone) zone = acme.UnFqdn(zone)
@ -53,10 +204,10 @@ func TestDNSProviderPresentAndCleanup(t *testing.T) {
for _, tc := range testCases { for _, tc := range testCases {
t.Run(fmt.Sprintf("domain(%s)", tc), func(t *testing.T) { t.Run(fmt.Sprintf("domain(%s)", tc), func(t *testing.T) {
err = p.Present(tc, "987d", "123d==") err = p.Present(tc, "987d", "123d==")
assert.NoError(t, err) require.NoError(t, err)
err = p.CleanUp(tc, "987d", "123d==") err = p.CleanUp(tc, "987d", "123d==")
assert.NoError(t, err, "Did not clean up! Please remove record yourself.") require.NoError(t, err, "Did not clean up! Please remove record yourself.")
}) })
} }
} }

View file

@ -89,13 +89,17 @@ type ChangeInfo struct {
} }
// NewClient Creates a new client of NIFCLOUD DNS // NewClient Creates a new client of NIFCLOUD DNS
func NewClient(accessKey string, secretKey string) *Client { func NewClient(accessKey string, secretKey string) (*Client, error) {
if len(accessKey) == 0 || len(secretKey) == 0 {
return nil, errors.New("credentials missing")
}
return &Client{ return &Client{
accessKey: accessKey, accessKey: accessKey,
secretKey: secretKey, secretKey: secretKey,
BaseURL: defaultBaseURL, BaseURL: defaultBaseURL,
HTTPClient: &http.Client{}, HTTPClient: &http.Client{},
} }, nil
} }
// Client client of NIFCLOUD DNS // Client client of NIFCLOUD DNS

View file

@ -31,7 +31,9 @@ func TestChangeResourceRecordSets(t *testing.T) {
server := runTestServer(responseBody, http.StatusOK) server := runTestServer(responseBody, http.StatusOK)
defer server.Close() defer server.Close()
client := NewClient("", "") client, err := NewClient("A", "B")
require.NoError(t, err)
client.BaseURL = server.URL client.BaseURL = server.URL
res, err := client.ChangeResourceRecordSets("example.com", ChangeResourceRecordSetsRequest{}) res, err := client.ChangeResourceRecordSets("example.com", ChangeResourceRecordSetsRequest{})
@ -83,7 +85,9 @@ func TestChangeResourceRecordSetsErrors(t *testing.T) {
server := runTestServer(test.responseBody, test.statusCode) server := runTestServer(test.responseBody, test.statusCode)
defer server.Close() defer server.Close()
client := NewClient("", "") client, err := NewClient("A", "B")
require.NoError(t, err)
client.BaseURL = server.URL client.BaseURL = server.URL
res, err := client.ChangeResourceRecordSets("example.com", ChangeResourceRecordSetsRequest{}) res, err := client.ChangeResourceRecordSets("example.com", ChangeResourceRecordSetsRequest{})
@ -107,7 +111,9 @@ func TestGetChange(t *testing.T) {
server := runTestServer(responseBody, http.StatusOK) server := runTestServer(responseBody, http.StatusOK)
defer server.Close() defer server.Close()
client := NewClient("", "") client, err := NewClient("A", "B")
require.NoError(t, err)
client.BaseURL = server.URL client.BaseURL = server.URL
res, err := client.GetChange("12345") res, err := client.GetChange("12345")
@ -159,7 +165,9 @@ func TestGetChangeErrors(t *testing.T) {
server := runTestServer(test.responseBody, test.statusCode) server := runTestServer(test.responseBody, test.statusCode)
defer server.Close() defer server.Close()
client := NewClient("", "") client, err := NewClient("A", "B")
require.NoError(t, err)
client.BaseURL = server.URL client.BaseURL = server.URL
res, err := client.GetChange("12345") res, err := client.GetChange("12345")

View file

@ -77,7 +77,10 @@ func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
return nil, errors.New("nifcloud: the configuration of the DNS provider is nil") return nil, errors.New("nifcloud: the configuration of the DNS provider is nil")
} }
client := NewClient(config.AccessKey, config.SecretKey) client, err := NewClient(config.AccessKey, config.SecretKey)
if err != nil {
return nil, fmt.Errorf("nifcloud: %v", err)
}
if config.HTTPClient != nil { if config.HTTPClient != nil {
client.HTTPClient = config.HTTPClient client.HTTPClient = config.HTTPClient

View file

@ -9,44 +9,167 @@ import (
) )
var ( var (
nifcloudLiveTest bool liveTest bool
nifcloudAccessKey string envTestAccessKey string
nifcloudSecretKey string envTestSecretKey string
nifcloudDomain string envTestDomain string
) )
func init() { func init() {
nifcloudAccessKey = os.Getenv("NIFCLOUD_ACCESS_KEY_ID") envTestAccessKey = os.Getenv("NIFCLOUD_ACCESS_KEY_ID")
nifcloudSecretKey = os.Getenv("NIFCLOUD_SECRET_ACCESS_KEY") envTestSecretKey = os.Getenv("NIFCLOUD_SECRET_ACCESS_KEY")
nifcloudDomain = os.Getenv("NIFCLOUD_DOMAIN") envTestDomain = os.Getenv("NIFCLOUD_DOMAIN")
if len(nifcloudAccessKey) > 0 && len(nifcloudSecretKey) > 0 && len(nifcloudDomain) > 0 { if len(envTestAccessKey) > 0 && len(envTestSecretKey) > 0 && len(envTestDomain) > 0 {
nifcloudLiveTest = true liveTest = true
} }
} }
func TestLivenifcloudPresent(t *testing.T) { func restoreEnv() {
if !nifcloudLiveTest { os.Setenv("NIFCLOUD_ACCESS_KEY_ID", envTestAccessKey)
os.Setenv("NIFCLOUD_SECRET_ACCESS_KEY", envTestSecretKey)
}
func TestNewDNSProvider(t *testing.T) {
testCases := []struct {
desc string
envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
"NIFCLOUD_ACCESS_KEY_ID": "123",
"NIFCLOUD_SECRET_ACCESS_KEY": "456",
},
},
{
desc: "missing credentials",
envVars: map[string]string{
"NIFCLOUD_ACCESS_KEY_ID": "",
"NIFCLOUD_SECRET_ACCESS_KEY": "",
},
expected: "nifcloud: some credentials information are missing: NIFCLOUD_ACCESS_KEY_ID,NIFCLOUD_SECRET_ACCESS_KEY",
},
{
desc: "missing access key",
envVars: map[string]string{
"NIFCLOUD_ACCESS_KEY_ID": "",
"NIFCLOUD_SECRET_ACCESS_KEY": "456",
},
expected: "nifcloud: some credentials information are missing: NIFCLOUD_ACCESS_KEY_ID",
},
{
desc: "missing secret key",
envVars: map[string]string{
"NIFCLOUD_ACCESS_KEY_ID": "123",
"NIFCLOUD_SECRET_ACCESS_KEY": "",
},
expected: "nifcloud: some credentials information are missing: NIFCLOUD_SECRET_ACCESS_KEY",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
for key, value := range test.envVars {
if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
}
p, err := NewDNSProvider()
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
func TestNewDNSProviderConfig(t *testing.T) {
testCases := []struct {
desc string
accessKey string
secretKey string
expected string
}{
{
desc: "success",
accessKey: "123",
secretKey: "456",
},
{
desc: "missing credentials",
expected: "nifcloud: credentials missing",
},
{
desc: "missing api key",
secretKey: "456",
expected: "nifcloud: credentials missing",
},
{
desc: "missing secret key",
accessKey: "123",
expected: "nifcloud: credentials missing",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
os.Unsetenv("NIFCLOUD_ACCESS_KEY_ID")
os.Unsetenv("NIFCLOUD_SECRET_ACCESS_KEY")
config := NewDefaultConfig()
config.AccessKey = test.accessKey
config.SecretKey = test.secretKey
p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
func TestLivePresent(t *testing.T) {
if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
restoreEnv()
provider, err := NewDNSProvider() provider, err := NewDNSProvider()
require.NoError(t, err) require.NoError(t, err)
err = provider.Present(nifcloudDomain, "", "123d==") err = provider.Present(envTestDomain, "", "123d==")
require.NoError(t, err) require.NoError(t, err)
} }
func TestLivenifcloudCleanUp(t *testing.T) { func TestLiveCleanUp(t *testing.T) {
if !nifcloudLiveTest { if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
time.Sleep(time.Second * 1) restoreEnv()
provider, err := NewDNSProvider() provider, err := NewDNSProvider()
require.NoError(t, err) require.NoError(t, err)
err = provider.CleanUp(nifcloudDomain, "", "123d==") time.Sleep(1 * time.Second)
err = provider.CleanUp(envTestDomain, "", "123d==")
require.NoError(t, err) require.NoError(t, err)
} }

View file

@ -10,21 +10,105 @@ import (
) )
var ( var (
liveTest bool liveTest bool
apiKey string envTestAPIKey string
domain string envTestDomain string
) )
func init() { func init() {
apiKey = os.Getenv("NS1_API_KEY") envTestAPIKey = os.Getenv("NS1_API_KEY")
domain = os.Getenv("NS1_DOMAIN") envTestDomain = os.Getenv("NS1_DOMAIN")
if len(apiKey) > 0 && len(domain) > 0 { if len(envTestAPIKey) > 0 && len(envTestDomain) > 0 {
liveTest = true liveTest = true
} }
} }
func restoreEnv() { func restoreEnv() {
os.Setenv("NS1_API_KEY", apiKey) os.Setenv("NS1_API_KEY", envTestAPIKey)
}
func TestNewDNSProvider(t *testing.T) {
testCases := []struct {
desc string
envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
"NS1_API_KEY": "123",
},
},
{
desc: "missing api key",
envVars: map[string]string{
"NS1_API_KEY": "",
},
expected: "ns1: some credentials information are missing: NS1_API_KEY",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
for key, value := range test.envVars {
if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
}
p, err := NewDNSProvider()
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
func TestNewDNSProviderConfig(t *testing.T) {
testCases := []struct {
desc string
apiKey string
expected string
}{
{
desc: "success",
apiKey: "123",
},
{
desc: "missing credentials",
expected: "ns1: credentials missing",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
os.Unsetenv("NS1_API_KEY")
config := NewDefaultConfig()
config.APIKey = test.apiKey
p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
} }
func Test_getAuthZone(t *testing.T) { func Test_getAuthZone(t *testing.T) {
@ -78,37 +162,16 @@ func Test_getAuthZone(t *testing.T) {
} }
} }
func TestNewDNSProviderValid(t *testing.T) {
defer restoreEnv()
os.Setenv("NS1_API_KEY", "")
config := NewDefaultConfig()
config.APIKey = "123"
_, err := NewDNSProviderConfig(config)
require.NoError(t, err)
}
func TestNewDNSProviderMissingCredErr(t *testing.T) {
defer restoreEnv()
os.Setenv("NS1_API_KEY", "")
_, err := NewDNSProvider()
assert.EqualError(t, err, "ns1: some credentials information are missing: NS1_API_KEY")
}
func TestLivePresent(t *testing.T) { func TestLivePresent(t *testing.T) {
if !liveTest { if !liveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
config := NewDefaultConfig() restoreEnv()
config.APIKey = apiKey provider, err := NewDNSProvider()
provider, err := NewDNSProviderConfig(config)
require.NoError(t, err) require.NoError(t, err)
err = provider.Present(domain, "", "123d==") err = provider.Present(envTestDomain, "", "123d==")
require.NoError(t, err) require.NoError(t, err)
} }
@ -117,14 +180,12 @@ func TestLiveCleanUp(t *testing.T) {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
time.Sleep(time.Second * 1) restoreEnv()
provider, err := NewDNSProvider()
config := NewDefaultConfig()
config.APIKey = apiKey
provider, err := NewDNSProviderConfig(config)
require.NoError(t, err) require.NoError(t, err)
err = provider.CleanUp(domain, "", "123d==") time.Sleep(1 * time.Second)
err = provider.CleanUp(envTestDomain, "", "123d==")
require.NoError(t, err) require.NoError(t, err)
} }

View file

@ -6,30 +6,30 @@ import (
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
) )
type OTCDNSTestSuite struct { type TestSuite struct {
suite.Suite suite.Suite
Mock *DNSMock Mock *DNSMock
} }
func (s *OTCDNSTestSuite) TearDownSuite() { func (s *TestSuite) TearDownSuite() {
s.Mock.ShutdownServer() s.Mock.ShutdownServer()
} }
func (s *OTCDNSTestSuite) SetupTest() { func (s *TestSuite) SetupTest() {
s.Mock = NewDNSMock(s.T()) s.Mock = NewDNSMock(s.T())
s.Mock.Setup() s.Mock.Setup()
s.Mock.HandleAuthSuccessfully() s.Mock.HandleAuthSuccessfully()
} }
func TestOTCDNSTestSuite(t *testing.T) { func TestTestSuite(t *testing.T) {
suite.Run(t, new(OTCDNSTestSuite)) suite.Run(t, new(TestSuite))
} }
func (s *OTCDNSTestSuite) createDNSProvider() (*DNSProvider, error) { func (s *TestSuite) createDNSProvider() (*DNSProvider, error) {
url := fmt.Sprintf("%s/v3/auth/token", s.Mock.Server.URL) url := fmt.Sprintf("%s/v3/auth/token", s.Mock.Server.URL)
config := NewDefaultConfig() config := NewDefaultConfig()
@ -42,7 +42,17 @@ func (s *OTCDNSTestSuite) createDNSProvider() (*DNSProvider, error) {
return NewDNSProviderConfig(config) return NewDNSProviderConfig(config)
} }
func (s *OTCDNSTestSuite) TestOTCDNSLoginEnv() { func (s *TestSuite) TestLogin() {
provider, err := s.createDNSProvider()
require.NoError(s.T(), err)
err = provider.loginRequest()
require.NoError(s.T(), err)
assert.Equal(s.T(), provider.baseURL, fmt.Sprintf("%s/v2", s.Mock.Server.URL))
assert.Equal(s.T(), fakeOTCToken, provider.token)
}
func (s *TestSuite) TestLoginEnv() {
defer os.Clearenv() defer os.Clearenv()
os.Setenv("OTC_DOMAIN_NAME", "unittest1") os.Setenv("OTC_DOMAIN_NAME", "unittest1")
@ -52,7 +62,7 @@ func (s *OTCDNSTestSuite) TestOTCDNSLoginEnv() {
os.Setenv("OTC_IDENTITY_ENDPOINT", "unittest5") os.Setenv("OTC_IDENTITY_ENDPOINT", "unittest5")
provider, err := NewDNSProvider() provider, err := NewDNSProvider()
assert.Nil(s.T(), err) require.NoError(s.T(), err)
assert.Equal(s.T(), provider.config.DomainName, "unittest1") assert.Equal(s.T(), provider.config.DomainName, "unittest1")
assert.Equal(s.T(), provider.config.UserName, "unittest2") assert.Equal(s.T(), provider.config.UserName, "unittest2")
assert.Equal(s.T(), provider.config.Password, "unittest3") assert.Equal(s.T(), provider.config.Password, "unittest3")
@ -62,60 +72,58 @@ func (s *OTCDNSTestSuite) TestOTCDNSLoginEnv() {
os.Setenv("OTC_IDENTITY_ENDPOINT", "") os.Setenv("OTC_IDENTITY_ENDPOINT", "")
provider, err = NewDNSProvider() provider, err = NewDNSProvider()
assert.Nil(s.T(), err) require.NoError(s.T(), err)
assert.Equal(s.T(), provider.config.IdentityEndpoint, "https://iam.eu-de.otc.t-systems.com:443/v3/auth/tokens") assert.Equal(s.T(), provider.config.IdentityEndpoint, "https://iam.eu-de.otc.t-systems.com:443/v3/auth/tokens")
} }
func (s *OTCDNSTestSuite) TestOTCDNSLoginEnvEmpty() { func (s *TestSuite) TestLoginEnvEmpty() {
defer os.Clearenv() defer os.Clearenv()
_, err := NewDNSProvider() _, err := NewDNSProvider()
assert.EqualError(s.T(), err, "otc: some credentials information are missing: OTC_DOMAIN_NAME,OTC_USER_NAME,OTC_PASSWORD,OTC_PROJECT_NAME") assert.EqualError(s.T(), err, "otc: some credentials information are missing: OTC_DOMAIN_NAME,OTC_USER_NAME,OTC_PASSWORD,OTC_PROJECT_NAME")
} }
func (s *OTCDNSTestSuite) TestOTCDNSLogin() { func (s *TestSuite) TestDNSProvider_Present() {
otcProvider, err := s.createDNSProvider() s.Mock.HandleListZonesSuccessfully()
s.Mock.HandleListRecordsetsSuccessfully()
assert.Nil(s.T(), err) provider, err := s.createDNSProvider()
err = otcProvider.loginRequest() require.NoError(s.T(), err)
assert.Nil(s.T(), err)
assert.Equal(s.T(), otcProvider.baseURL, fmt.Sprintf("%s/v2", s.Mock.Server.URL)) err = provider.Present("example.com", "", "foobar")
assert.Equal(s.T(), fakeOTCToken, otcProvider.token) require.NoError(s.T(), err)
} }
func (s *OTCDNSTestSuite) TestOTCDNSEmptyZone() { func (s *TestSuite) TestDNSProvider_Present_EmptyZone() {
s.Mock.HandleListZonesEmpty() s.Mock.HandleListZonesEmpty()
s.Mock.HandleListRecordsetsSuccessfully() s.Mock.HandleListRecordsetsSuccessfully()
otcProvider, _ := s.createDNSProvider() provider, err := s.createDNSProvider()
err := otcProvider.Present("example.com", "", "foobar") require.NoError(s.T(), err)
err = provider.Present("example.com", "", "foobar")
assert.NotNil(s.T(), err) assert.NotNil(s.T(), err)
} }
func (s *OTCDNSTestSuite) TestOTCDNSEmptyRecordset() { func (s *TestSuite) TestDNSProvider_CleanUp() {
s.Mock.HandleListZonesSuccessfully()
s.Mock.HandleListRecordsetsEmpty()
otcProvider, _ := s.createDNSProvider()
err := otcProvider.CleanUp("example.com", "", "foobar")
assert.NotNil(s.T(), err)
}
func (s *OTCDNSTestSuite) TestOTCDNSPresent() {
s.Mock.HandleListZonesSuccessfully()
s.Mock.HandleListRecordsetsSuccessfully()
otcProvider, _ := s.createDNSProvider()
err := otcProvider.Present("example.com", "", "foobar")
assert.Nil(s.T(), err)
}
func (s *OTCDNSTestSuite) TestOTCDNSCleanup() {
s.Mock.HandleListZonesSuccessfully() s.Mock.HandleListZonesSuccessfully()
s.Mock.HandleListRecordsetsSuccessfully() s.Mock.HandleListRecordsetsSuccessfully()
s.Mock.HandleDeleteRecordsetsSuccessfully() s.Mock.HandleDeleteRecordsetsSuccessfully()
otcProvider, _ := s.createDNSProvider() provider, err := s.createDNSProvider()
err := otcProvider.CleanUp("example.com", "", "foobar") require.NoError(s.T(), err)
assert.Nil(s.T(), err)
err = provider.CleanUp("example.com", "", "foobar")
require.NoError(s.T(), err)
}
func (s *TestSuite) TestDNSProvider_CleanUp_EmptyRecordset() {
s.Mock.HandleListZonesSuccessfully()
s.Mock.HandleListRecordsetsEmpty()
provider, err := s.createDNSProvider()
require.NoError(s.T(), err)
err = provider.CleanUp("example.com", "", "foobar")
require.Error(s.T(), err)
} }

View file

@ -5,95 +5,52 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
var ( var (
liveTest bool liveTest bool
apiEndpoint string envTestAPIEndpoint string
applicationKey string envTestApplicationKey string
applicationSecret string envTestApplicationSecret string
consumerKey string envTestConsumerKey string
domain string envTestDomain string
) )
func init() { func init() {
apiEndpoint = os.Getenv("OVH_ENDPOINT") envTestAPIEndpoint = os.Getenv("OVH_ENDPOINT")
applicationKey = os.Getenv("OVH_APPLICATION_KEY") envTestApplicationKey = os.Getenv("OVH_APPLICATION_KEY")
applicationSecret = os.Getenv("OVH_APPLICATION_SECRET") envTestApplicationSecret = os.Getenv("OVH_APPLICATION_SECRET")
consumerKey = os.Getenv("OVH_CONSUMER_KEY") envTestConsumerKey = os.Getenv("OVH_CONSUMER_KEY")
liveTest = len(apiEndpoint) > 0 && len(applicationKey) > 0 && len(applicationSecret) > 0 && len(consumerKey) > 0 envTestDomain = os.Getenv("OVH_DOMAIN")
liveTest = len(envTestAPIEndpoint) > 0 && len(envTestApplicationKey) > 0 && len(envTestApplicationSecret) > 0 && len(envTestConsumerKey) > 0
} }
func restoreEnv() { func restoreEnv() {
os.Setenv("OVH_ENDPOINT", apiEndpoint) os.Setenv("OVH_ENDPOINT", envTestAPIEndpoint)
os.Setenv("OVH_APPLICATION_KEY", applicationKey) os.Setenv("OVH_APPLICATION_KEY", envTestApplicationKey)
os.Setenv("OVH_APPLICATION_SECRET", applicationSecret) os.Setenv("OVH_APPLICATION_SECRET", envTestApplicationSecret)
os.Setenv("OVH_CONSUMER_KEY", consumerKey) os.Setenv("OVH_CONSUMER_KEY", envTestConsumerKey)
} }
func TestNewDNSProviderValidEnv(t *testing.T) { func TestNewDNSProvider(t *testing.T) {
defer restoreEnv()
os.Setenv("OVH_ENDPOINT", "ovh-eu")
os.Setenv("OVH_APPLICATION_KEY", "1234")
os.Setenv("OVH_APPLICATION_SECRET", "5678")
os.Setenv("OVH_CONSUMER_KEY", "abcde")
_, err := NewDNSProvider()
require.NoError(t, err)
}
func TestNewDNSProviderMissingCredErr(t *testing.T) {
defer restoreEnv()
testCases := []struct { testCases := []struct {
desc string desc string
envVars map[string]string envVars map[string]string
expected string expected string
}{ }{
{ {
desc: "missing OVH_ENDPOINT", desc: "success",
envVars: map[string]string{
"OVH_ENDPOINT": "",
"OVH_APPLICATION_KEY": "1234",
"OVH_APPLICATION_SECRET": "5678",
"OVH_CONSUMER_KEY": "abcde",
},
expected: "ovh: some credentials information are missing: OVH_ENDPOINT",
},
{
desc: "missing OVH_APPLICATION_KEY",
envVars: map[string]string{ envVars: map[string]string{
"OVH_ENDPOINT": "ovh-eu", "OVH_ENDPOINT": "ovh-eu",
"OVH_APPLICATION_KEY": "", "OVH_APPLICATION_KEY": "B",
"OVH_APPLICATION_SECRET": "5678", "OVH_APPLICATION_SECRET": "C",
"OVH_CONSUMER_KEY": "abcde", "OVH_CONSUMER_KEY": "D",
}, },
expected: "ovh: some credentials information are missing: OVH_APPLICATION_KEY",
}, },
{ {
desc: "missing OVH_APPLICATION_SECRET", desc: "missing credentials",
envVars: map[string]string{
"OVH_ENDPOINT": "ovh-eu",
"OVH_APPLICATION_KEY": "1234",
"OVH_APPLICATION_SECRET": "",
"OVH_CONSUMER_KEY": "abcde",
},
expected: "ovh: some credentials information are missing: OVH_APPLICATION_SECRET",
},
{
desc: "missing OVH_CONSUMER_KEY",
envVars: map[string]string{
"OVH_ENDPOINT": "ovh-eu",
"OVH_APPLICATION_KEY": "1234",
"OVH_APPLICATION_SECRET": "5678",
"OVH_CONSUMER_KEY": "",
},
expected: "ovh: some credentials information are missing: OVH_CONSUMER_KEY",
},
{
desc: "all missing",
envVars: map[string]string{ envVars: map[string]string{
"OVH_ENDPOINT": "", "OVH_ENDPOINT": "",
"OVH_APPLICATION_KEY": "", "OVH_APPLICATION_KEY": "",
@ -102,18 +59,171 @@ func TestNewDNSProviderMissingCredErr(t *testing.T) {
}, },
expected: "ovh: some credentials information are missing: OVH_ENDPOINT,OVH_APPLICATION_KEY,OVH_APPLICATION_SECRET,OVH_CONSUMER_KEY", expected: "ovh: some credentials information are missing: OVH_ENDPOINT,OVH_APPLICATION_KEY,OVH_APPLICATION_SECRET,OVH_CONSUMER_KEY",
}, },
{
desc: "missing endpoint",
envVars: map[string]string{
"OVH_ENDPOINT": "",
"OVH_APPLICATION_KEY": "B",
"OVH_APPLICATION_SECRET": "C",
"OVH_CONSUMER_KEY": "D",
},
expected: "ovh: some credentials information are missing: OVH_ENDPOINT",
},
{
desc: "missing invalid endpoint",
envVars: map[string]string{
"OVH_ENDPOINT": "foobar",
"OVH_APPLICATION_KEY": "B",
"OVH_APPLICATION_SECRET": "C",
"OVH_CONSUMER_KEY": "D",
},
expected: "ovh: unknown endpoint 'foobar', consider checking 'Endpoints' list of using an URL",
},
{
desc: "missing application key",
envVars: map[string]string{
"OVH_ENDPOINT": "ovh-eu",
"OVH_APPLICATION_KEY": "",
"OVH_APPLICATION_SECRET": "C",
"OVH_CONSUMER_KEY": "D",
},
expected: "ovh: some credentials information are missing: OVH_APPLICATION_KEY",
},
{
desc: "missing application secret",
envVars: map[string]string{
"OVH_ENDPOINT": "ovh-eu",
"OVH_APPLICATION_KEY": "B",
"OVH_APPLICATION_SECRET": "",
"OVH_CONSUMER_KEY": "D",
},
expected: "ovh: some credentials information are missing: OVH_APPLICATION_SECRET",
},
{
desc: "missing consumer key",
envVars: map[string]string{
"OVH_ENDPOINT": "ovh-eu",
"OVH_APPLICATION_KEY": "B",
"OVH_APPLICATION_SECRET": "C",
"OVH_CONSUMER_KEY": "",
},
expected: "ovh: some credentials information are missing: OVH_CONSUMER_KEY",
},
} }
for _, test := range testCases { for _, test := range testCases {
test := test
t.Run(test.desc, func(t *testing.T) { t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
for key, value := range test.envVars { for key, value := range test.envVars {
os.Setenv(key, value) if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
} }
_, err := NewDNSProvider() p, err := NewDNSProvider()
assert.EqualError(t, err, test.expected)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
require.NotNil(t, p.recordIDs)
} else {
require.EqualError(t, err, test.expected)
}
})
}
}
func TestNewDNSProviderConfig(t *testing.T) {
testCases := []struct {
desc string
apiEndpoint string
applicationKey string
applicationSecret string
consumerKey string
expected string
}{
{
desc: "success",
apiEndpoint: "ovh-eu",
applicationKey: "B",
applicationSecret: "C",
consumerKey: "D",
},
{
desc: "missing credentials",
expected: "ovh: credentials missing",
},
{
desc: "missing api endpoint",
apiEndpoint: "",
applicationKey: "B",
applicationSecret: "C",
consumerKey: "D",
expected: "ovh: credentials missing",
},
{
desc: "missing invalid api endpoint",
apiEndpoint: "foobar",
applicationKey: "B",
applicationSecret: "C",
consumerKey: "D",
expected: "ovh: unknown endpoint 'foobar', consider checking 'Endpoints' list of using an URL",
},
{
desc: "missing application key",
apiEndpoint: "ovh-eu",
applicationKey: "",
applicationSecret: "C",
consumerKey: "D",
expected: "ovh: credentials missing",
},
{
desc: "missing application secret",
apiEndpoint: "ovh-eu",
applicationKey: "B",
applicationSecret: "",
consumerKey: "D",
expected: "ovh: credentials missing",
},
{
desc: "missing consumer key",
apiEndpoint: "ovh-eu",
applicationKey: "B",
applicationSecret: "C",
consumerKey: "",
expected: "ovh: credentials missing",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
os.Unsetenv("OVH_ENDPOINT")
os.Unsetenv("OVH_APPLICATION_KEY")
os.Unsetenv("OVH_APPLICATION_SECRET")
os.Unsetenv("OVH_CONSUMER_KEY")
config := NewDefaultConfig()
config.APIEndpoint = test.apiEndpoint
config.ApplicationKey = test.applicationKey
config.ApplicationSecret = test.applicationSecret
config.ConsumerKey = test.consumerKey
p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
require.NotNil(t, p.recordIDs)
} else {
require.EqualError(t, err, test.expected)
}
}) })
} }
} }
@ -123,10 +233,11 @@ func TestLivePresent(t *testing.T) {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
restoreEnv()
provider, err := NewDNSProvider() provider, err := NewDNSProvider()
require.NoError(t, err) require.NoError(t, err)
err = provider.Present(domain, "", "123d==") err = provider.Present(envTestDomain, "", "123d==")
require.NoError(t, err) require.NoError(t, err)
} }
@ -135,11 +246,12 @@ func TestLiveCleanUp(t *testing.T) {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
time.Sleep(time.Second * 1) restoreEnv()
provider, err := NewDNSProvider() provider, err := NewDNSProvider()
require.NoError(t, err) require.NoError(t, err)
err = provider.CleanUp(domain, "", "123d==") time.Sleep(1 * time.Second)
err = provider.CleanUp(envTestDomain, "", "123d==")
require.NoError(t, err) require.NoError(t, err)
} }

View file

@ -5,90 +5,164 @@ import (
"os" "os"
"testing" "testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
var ( var (
pdnsLiveTest bool liveTest bool
pdnsURL *url.URL envTestAPIURL *url.URL
pdnsURLStr string envTestAPIKey string
pdnsAPIKey string envTestDomain string
pdnsDomain string
) )
func init() { func init() {
pdnsURLStr = os.Getenv("PDNS_API_URL") envTestAPIURL, _ = url.Parse(os.Getenv("PDNS_API_URL"))
pdnsURL, _ = url.Parse(pdnsURLStr) envTestAPIKey = os.Getenv("PDNS_API_KEY")
pdnsAPIKey = os.Getenv("PDNS_API_KEY") envTestDomain = os.Getenv("PDNS_DOMAIN")
pdnsDomain = os.Getenv("PDNS_DOMAIN")
if len(pdnsURLStr) > 0 && len(pdnsAPIKey) > 0 && len(pdnsDomain) > 0 { if len(envTestAPIURL.String()) > 0 && len(envTestAPIKey) > 0 && len(envTestDomain) > 0 {
pdnsLiveTest = true liveTest = true
} }
} }
func restoreEnv() { func restoreEnv() {
os.Setenv("PDNS_API_URL", pdnsURLStr) os.Setenv("PDNS_API_URL", envTestAPIURL.String())
os.Setenv("PDNS_API_KEY", pdnsAPIKey) os.Setenv("PDNS_API_KEY", envTestAPIKey)
} }
func TestNewDNSProviderValid(t *testing.T) { func TestNewDNSProvider(t *testing.T) {
defer restoreEnv() testCases := []struct {
os.Setenv("PDNS_API_URL", "") desc string
os.Setenv("PDNS_API_KEY", "") envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
"PDNS_API_KEY": "123",
"PDNS_API_URL": "http://example.com",
},
},
{
desc: "missing credentials",
envVars: map[string]string{
"PDNS_API_KEY": "",
"PDNS_API_URL": "",
},
expected: "pdns: some credentials information are missing: PDNS_API_KEY,PDNS_API_URL",
},
{
desc: "missing api key",
envVars: map[string]string{
"PDNS_API_KEY": "",
"PDNS_API_URL": "http://example.com",
},
expected: "pdns: some credentials information are missing: PDNS_API_KEY",
},
{
desc: "missing API URL",
envVars: map[string]string{
"PDNS_API_KEY": "123",
"PDNS_API_URL": "",
},
expected: "pdns: some credentials information are missing: PDNS_API_URL",
},
}
tmpURL, _ := url.Parse("http://localhost:8081") for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
for key, value := range test.envVars {
if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
}
config := NewDefaultConfig() p, err := NewDNSProvider()
config.Host = tmpURL
config.APIKey = "123"
_, err := NewDNSProviderConfig(config) if len(test.expected) == 0 {
require.NoError(t, err) require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
} else {
require.EqualError(t, err, test.expected)
}
})
}
} }
func TestNewDNSProviderValidEnv(t *testing.T) { func TestNewDNSProviderConfig(t *testing.T) {
defer restoreEnv() testCases := []struct {
os.Setenv("PDNS_API_URL", "http://localhost:8081") desc string
os.Setenv("PDNS_API_KEY", "123") apiKey string
host *url.URL
expected string
}{
{
desc: "success",
apiKey: "123",
host: func() *url.URL {
u, _ := url.Parse("http://example.com")
return u
}(),
},
{
desc: "missing credentials",
expected: "pdns: API key missing",
},
{
desc: "missing API key",
apiKey: "",
host: func() *url.URL {
u, _ := url.Parse("http://example.com")
return u
}(),
expected: "pdns: API key missing",
},
{
desc: "missing host",
apiKey: "123",
expected: "pdns: API URL missing",
},
}
_, err := NewDNSProvider() for _, test := range testCases {
require.NoError(t, err) t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
os.Unsetenv("PDNS_API_KEY")
os.Unsetenv("PDNS_API_URL")
config := NewDefaultConfig()
config.APIKey = test.apiKey
config.Host = test.host
p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
} else {
require.EqualError(t, err, test.expected)
}
})
}
} }
func TestNewDNSProviderMissingHostErr(t *testing.T) { func TestLivePresentAndCleanup(t *testing.T) {
defer restoreEnv() if !liveTest {
os.Setenv("PDNS_API_URL", "")
os.Setenv("PDNS_API_KEY", "123")
_, err := NewDNSProvider()
assert.EqualError(t, err, "pdns: some credentials information are missing: PDNS_API_URL")
}
func TestNewDNSProviderMissingKeyErr(t *testing.T) {
defer restoreEnv()
os.Setenv("PDNS_API_URL", pdnsURLStr)
os.Setenv("PDNS_API_KEY", "")
_, err := NewDNSProvider()
assert.EqualError(t, err, "pdns: some credentials information are missing: PDNS_API_KEY,PDNS_API_URL")
}
func TestPdnsPresentAndCleanup(t *testing.T) {
if !pdnsLiveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
config := NewDefaultConfig() restoreEnv()
config.Host = pdnsURL provider, err := NewDNSProvider()
config.APIKey = pdnsAPIKey
provider, err := NewDNSProviderConfig(config)
require.NoError(t, err) require.NoError(t, err)
err = provider.Present(pdnsDomain, "", "123d==") err = provider.Present(envTestDomain, "", "123d==")
require.NoError(t, err) require.NoError(t, err)
err = provider.CleanUp(pdnsDomain, "", "123d==") err = provider.CleanUp(envTestDomain, "", "123d==")
require.NoError(t, err) require.NoError(t, err)
} }

View file

@ -16,20 +16,44 @@ type AuthData struct {
Auth `json:"auth"` Auth `json:"auth"`
} }
// Identity Identity // Identity Identity
type Identity struct { type Identity struct {
Access struct { Access Access `json:"access"`
ServiceCatalog []struct { }
Endpoints []struct {
PublicURL string `json:"publicURL"` // Access Access
TenantID string `json:"tenantId"` type Access struct {
} `json:"endpoints"` ServiceCatalog []ServiceCatalog `json:"serviceCatalog"`
Name string `json:"name"` Token Token `json:"token"`
} `json:"serviceCatalog"` }
Token struct {
ID string `json:"id"` // Token Token
} `json:"token"` type Token struct {
} `json:"access"` ID string `json:"id"`
}
// ServiceCatalog ServiceCatalog
type ServiceCatalog struct {
Endpoints []Endpoint `json:"endpoints"`
Name string `json:"name"`
}
// Endpoint Endpoint
type Endpoint struct {
PublicURL string `json:"publicURL"`
TenantID string `json:"tenantId"`
}
// ZoneSearchResponse represents the response when querying Rackspace DNS zones
type ZoneSearchResponse struct {
TotalEntries int `json:"totalEntries"`
HostedZones []HostedZone `json:"domains"`
}
// HostedZone HostedZone
type HostedZone struct {
ID int `json:"id"`
Name string `json:"name"`
} }
// Records is the list of records sent/received from the DNS API // Records is the list of records sent/received from the DNS API

View file

@ -89,39 +89,7 @@ func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
return nil, fmt.Errorf("rackspace: credentials missing") return nil, fmt.Errorf("rackspace: credentials missing")
} }
authData := AuthData{ identity, err := login(config)
Auth: Auth{
APIKeyCredentials: APIKeyCredentials{
Username: config.APIUser,
APIKey: config.APIKey,
},
},
}
body, err := json.Marshal(authData)
if err != nil {
return nil, err
}
req, err := http.NewRequest(http.MethodPost, config.BaseURL, bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
// client := &http.Client{Timeout: 30 * time.Second}
resp, err := config.HTTPClient.Do(req)
if err != nil {
return nil, fmt.Errorf("rackspace: error querying Identity API: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("rackspace: authentication failed: response code: %d", resp.StatusCode)
}
var identity Identity
err = json.NewDecoder(resp.Body).Decode(&identity)
if err != nil { if err != nil {
return nil, fmt.Errorf("rackspace: %v", err) return nil, fmt.Errorf("rackspace: %v", err)
} }
@ -134,6 +102,7 @@ func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
break break
} }
} }
if dnsEndpoint == "" { if dnsEndpoint == "" {
return nil, fmt.Errorf("rackspace: failed to populate DNS endpoint, check Rackspace API for changes") return nil, fmt.Errorf("rackspace: failed to populate DNS endpoint, check Rackspace API for changes")
} }
@ -149,6 +118,7 @@ func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
// Present creates a TXT record to fulfill the dns-01 challenge // Present creates a TXT record to fulfill the dns-01 challenge
func (d *DNSProvider) Present(domain, token, keyAuth string) error { func (d *DNSProvider) Present(domain, token, keyAuth string) error {
fqdn, value, _ := acme.DNS01Record(domain, keyAuth) fqdn, value, _ := acme.DNS01Record(domain, keyAuth)
zoneID, err := d.getHostedZoneID(fqdn) zoneID, err := d.getHostedZoneID(fqdn)
if err != nil { if err != nil {
return fmt.Errorf("rackspace: %v", err) return fmt.Errorf("rackspace: %v", err)
@ -178,6 +148,7 @@ func (d *DNSProvider) Present(domain, token, keyAuth string) error {
// CleanUp removes the TXT record matching the specified parameters // CleanUp removes the TXT record matching the specified parameters
func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error {
fqdn, _, _ := acme.DNS01Record(domain, keyAuth) fqdn, _, _ := acme.DNS01Record(domain, keyAuth)
zoneID, err := d.getHostedZoneID(fqdn) zoneID, err := d.getHostedZoneID(fqdn)
if err != nil { if err != nil {
return fmt.Errorf("rackspace: %v", err) return fmt.Errorf("rackspace: %v", err)
@ -204,15 +175,6 @@ func (d *DNSProvider) Timeout() (timeout, interval time.Duration) {
// getHostedZoneID performs a lookup to get the DNS zone which needs // getHostedZoneID performs a lookup to get the DNS zone which needs
// modifying for a given FQDN // modifying for a given FQDN
func (d *DNSProvider) getHostedZoneID(fqdn string) (int, error) { func (d *DNSProvider) getHostedZoneID(fqdn string) (int, error) {
// HostedZones represents the response when querying Rackspace DNS zones
type ZoneSearchResponse struct {
TotalEntries int `json:"totalEntries"`
HostedZones []struct {
ID int `json:"id"`
Name string `json:"name"`
} `json:"domains"`
}
authZone, err := acme.FindZoneByFqdn(fqdn, acme.RecursiveNameservers) authZone, err := acme.FindZoneByFqdn(fqdn, acme.RecursiveNameservers)
if err != nil { if err != nil {
return 0, err return 0, err
@ -250,8 +212,7 @@ func (d *DNSProvider) findTxtRecord(fqdn string, zoneID int) (*Record, error) {
return nil, err return nil, err
} }
recordsLength := len(records.Record) switch len(records.Record) {
switch recordsLength {
case 1: case 1:
case 0: case 0:
return nil, fmt.Errorf("no TXT record found for %s", fqdn) return nil, fmt.Errorf("no TXT record found for %s", fqdn)
@ -265,6 +226,7 @@ func (d *DNSProvider) findTxtRecord(fqdn string, zoneID int) (*Record, error) {
// makeRequest is a wrapper function used for making DNS API requests // makeRequest is a wrapper function used for making DNS API requests
func (d *DNSProvider) makeRequest(method, uri string, body io.Reader) (json.RawMessage, error) { func (d *DNSProvider) makeRequest(method, uri string, body io.Reader) (json.RawMessage, error) {
url := d.cloudDNSEndpoint + uri url := d.cloudDNSEndpoint + uri
req, err := http.NewRequest(method, url, body) req, err := http.NewRequest(method, url, body)
if err != nil { if err != nil {
return nil, err return nil, err
@ -292,3 +254,44 @@ func (d *DNSProvider) makeRequest(method, uri string, body io.Reader) (json.RawM
return r, nil return r, nil
} }
func login(config *Config) (*Identity, error) {
authData := AuthData{
Auth: Auth{
APIKeyCredentials: APIKeyCredentials{
Username: config.APIUser,
APIKey: config.APIKey,
},
},
}
body, err := json.Marshal(authData)
if err != nil {
return nil, err
}
req, err := http.NewRequest(http.MethodPost, config.BaseURL, bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := config.HTTPClient.Do(req)
if err != nil {
return nil, fmt.Errorf("error querying Identity API: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("authentication failed: response code: %d", resp.StatusCode)
}
var identity Identity
err = json.NewDecoder(resp.Body).Decode(&identity)
if err != nil {
return nil, err
}
return &identity, nil
}

View file

@ -15,45 +15,117 @@ import (
) )
var ( var (
rackspaceLiveTest bool liveTest bool
rackspaceUser string envTestUser string
rackspaceAPIKey string envTestAPIKey string
rackspaceDomain string envTestDomain string
testAPIURL string
) )
func init() { func init() {
rackspaceUser = os.Getenv("RACKSPACE_USER") envTestUser = os.Getenv("RACKSPACE_USER")
rackspaceAPIKey = os.Getenv("RACKSPACE_API_KEY") envTestAPIKey = os.Getenv("RACKSPACE_API_KEY")
rackspaceDomain = os.Getenv("RACKSPACE_DOMAIN") envTestDomain = os.Getenv("RACKSPACE_DOMAIN")
if len(rackspaceUser) > 0 && len(rackspaceAPIKey) > 0 && len(rackspaceDomain) > 0 {
rackspaceLiveTest = true if len(envTestUser) > 0 && len(envTestAPIKey) > 0 && len(envTestDomain) > 0 {
liveTest = true
} }
} }
func testRackspaceEnv() { func TestNewDNSProviderConfig(t *testing.T) {
os.Setenv("RACKSPACE_USER", "testUser") config, tearDown := setupTest()
os.Setenv("RACKSPACE_API_KEY", "testKey") defer tearDown()
provider, err := NewDNSProviderConfig(config)
require.NoError(t, err)
assert.NotNil(t, provider.config)
assert.Equal(t, provider.token, "testToken", "The token should match")
} }
func liveRackspaceEnv() { func TestNewDNSProviderConfig_MissingCredErr(t *testing.T) {
os.Setenv("RACKSPACE_USER", rackspaceUser) _, err := NewDNSProviderConfig(NewDefaultConfig())
os.Setenv("RACKSPACE_API_KEY", rackspaceAPIKey) assert.EqualError(t, err, "rackspace: credentials missing")
} }
func startTestServers() (*httptest.Server, *httptest.Server) { func TestDNSProvider_Present(t *testing.T) {
dnsAPI := httptest.NewServer(dnsMux()) config, tearDown := setupTest()
dnsEndpoint := dnsAPI.URL + "/123456" defer tearDown()
identityAPI := httptest.NewServer(identityHandler(dnsEndpoint)) provider, err := NewDNSProviderConfig(config)
testAPIURL = identityAPI.URL + "/"
return identityAPI, dnsAPI if assert.NoError(t, err) {
err = provider.Present("example.com", "token", "keyAuth")
require.NoError(t, err)
}
} }
func closeTestServers(identityAPI, dnsAPI *httptest.Server) { func TestDNSProvider_CleanUp(t *testing.T) {
identityAPI.Close() config, tearDown := setupTest()
dnsAPI.Close() defer tearDown()
provider, err := NewDNSProviderConfig(config)
if assert.NoError(t, err) {
err = provider.CleanUp("example.com", "token", "keyAuth")
require.NoError(t, err)
}
}
func TestLiveNewDNSProvider_ValidEnv(t *testing.T) {
if !liveTest {
t.Skip("skipping live test")
}
provider, err := NewDNSProvider()
require.NoError(t, err)
assert.Contains(t, provider.cloudDNSEndpoint, "https://dns.api.rackspacecloud.com/v1.0/", "The endpoint URL should contain the base")
}
func TestLivePresent(t *testing.T) {
if !liveTest {
t.Skip("skipping live test")
}
provider, err := NewDNSProvider()
require.NoError(t, err)
err = provider.Present(envTestDomain, "", "112233445566==")
require.NoError(t, err)
}
func TestLiveCleanUp(t *testing.T) {
if !liveTest {
t.Skip("skipping live test")
}
time.Sleep(time.Second * 15)
provider, err := NewDNSProvider()
require.NoError(t, err)
err = provider.CleanUp(envTestDomain, "", "112233445566==")
require.NoError(t, err)
}
func setupTest() (*Config, func()) {
apiURL, tearDown := startTestServers()
config := NewDefaultConfig()
config.APIUser = "testUser"
config.APIKey = "testKey"
config.BaseURL = apiURL
return config, tearDown
}
func startTestServers() (string, func()) {
dnsAPI := httptest.NewServer(dnsHandler())
identityAPI := httptest.NewServer(identityHandler(dnsAPI.URL + "/123456"))
return identityAPI.URL + "/", func() {
identityAPI.Close()
dnsAPI.Close()
}
} }
func identityHandler(dnsEndpoint string) http.Handler { func identityHandler(dnsEndpoint string) http.Handler {
@ -63,18 +135,20 @@ func identityHandler(dnsEndpoint string) http.Handler {
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
return return
} }
resp, found := jsonMap[string(reqBody)] resp, found := jsonMap[string(reqBody)]
if !found { if !found {
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
return return
} }
resp = strings.Replace(resp, "https://dns.api.rackspacecloud.com/v1.0/123456", dnsEndpoint, 1) resp = strings.Replace(resp, "https://dns.api.rackspacecloud.com/v1.0/123456", dnsEndpoint, 1)
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, resp) fmt.Fprintf(w, resp)
}) })
} }
func dnsMux() *http.ServeMux { func dnsHandler() *http.ServeMux {
mux := http.NewServeMux() mux := http.NewServeMux()
// Used by `getHostedZoneID()` finding `zoneID` "?name=example.com" // Used by `getHostedZoneID()` finding `zoneID` "?name=example.com"
@ -93,7 +167,7 @@ func dnsMux() *http.ServeMux {
case http.MethodPost: case http.MethodPost:
reqBody, err := ioutil.ReadAll(r.Body) reqBody, err := ioutil.ReadAll(r.Body)
if err != nil { if err != nil {
w.WriteHeader(http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
return return
} }
resp, found := jsonMap[string(reqBody)] resp, found := jsonMap[string(reqBody)]
@ -103,7 +177,7 @@ func dnsMux() *http.ServeMux {
} }
w.WriteHeader(http.StatusAccepted) w.WriteHeader(http.StatusAccepted)
fmt.Fprintf(w, resp) fmt.Fprintf(w, resp)
// Used by `findTxtRecord()` finding `record.ID` "?type=TXT&name=_acme-challenge.example.com" // Used by `findTxtRecord()` finding `record.ID` "?type=TXT&name=_acme-challenge.example.com"
case http.MethodGet: case http.MethodGet:
if r.URL.Query().Get("type") == "TXT" && r.URL.Query().Get("name") == "_acme-challenge.example.com" { if r.URL.Query().Get("type") == "TXT" && r.URL.Query().Get("name") == "_acme-challenge.example.com" {
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
@ -112,7 +186,7 @@ func dnsMux() *http.ServeMux {
} }
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
return return
// Used by `CleanUp()` deleting the TXT record "?id=445566" // Used by `CleanUp()` deleting the TXT record "?id=445566"
case http.MethodDelete: case http.MethodDelete:
if r.URL.Query().Get("id") == "TXT-654321" { if r.URL.Query().Get("id") == "TXT-654321" {
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
@ -131,104 +205,6 @@ func dnsMux() *http.ServeMux {
return mux return mux
} }
func TestNewDNSProviderMissingCredErr(t *testing.T) {
testRackspaceEnv()
_, err := NewDNSProviderConfig(&Config{})
assert.EqualError(t, err, "rackspace: credentials missing")
}
func TestOfflineRackspaceValid(t *testing.T) {
testRackspaceEnv()
config := NewDefaultConfig()
config.BaseURL = testAPIURL
config.APIKey = os.Getenv("RACKSPACE_API_KEY")
config.APIUser = os.Getenv("RACKSPACE_USER")
provider, err := NewDNSProviderConfig(config)
require.NoError(t, err)
assert.Equal(t, provider.token, "testToken", "The token should match")
}
func TestOfflineRackspacePresent(t *testing.T) {
testRackspaceEnv()
config := NewDefaultConfig()
config.APIUser = os.Getenv("RACKSPACE_USER")
config.APIKey = os.Getenv("RACKSPACE_API_KEY")
config.BaseURL = testAPIURL
provider, err := NewDNSProviderConfig(config)
if assert.NoError(t, err) {
err = provider.Present("example.com", "token", "keyAuth")
require.NoError(t, err)
}
}
func TestOfflineRackspaceCleanUp(t *testing.T) {
testRackspaceEnv()
config := NewDefaultConfig()
config.APIUser = os.Getenv("RACKSPACE_USER")
config.APIKey = os.Getenv("RACKSPACE_API_KEY")
config.BaseURL = testAPIURL
provider, err := NewDNSProviderConfig(config)
if assert.NoError(t, err) {
err = provider.CleanUp("example.com", "token", "keyAuth")
require.NoError(t, err)
}
}
func TestNewDNSProviderValidEnv(t *testing.T) {
if !rackspaceLiveTest {
t.Skip("skipping live test")
}
liveRackspaceEnv()
provider, err := NewDNSProvider()
require.NoError(t, err)
assert.Contains(t, provider.cloudDNSEndpoint, "https://dns.api.rackspacecloud.com/v1.0/", "The endpoint URL should contain the base")
}
func TestRackspacePresent(t *testing.T) {
if !rackspaceLiveTest {
t.Skip("skipping live test")
}
liveRackspaceEnv()
provider, err := NewDNSProvider()
require.NoError(t, err)
err = provider.Present(rackspaceDomain, "", "112233445566==")
require.NoError(t, err)
}
func TestRackspaceCleanUp(t *testing.T) {
if !rackspaceLiveTest {
t.Skip("skipping live test")
}
time.Sleep(time.Second * 15)
liveRackspaceEnv()
provider, err := NewDNSProvider()
require.NoError(t, err)
err = provider.CleanUp(rackspaceDomain, "", "112233445566==")
require.NoError(t, err)
}
func TestMain(m *testing.M) {
identityAPI, dnsAPI := startTestServers()
defer closeTestServers(identityAPI, dnsAPI)
os.Exit(m.Run())
}
var jsonMap = map[string]string{ var jsonMap = map[string]string{
`{"auth":{"RAX-KSKEY:apiKeyCredentials":{"username":"testUser","apiKey":"testKey"}}}`: `{"access":{"token":{"id":"testToken","expires":"1970-01-01T00:00:00.000Z","tenant":{"id":"123456","name":"123456"},"RAX-AUTH:authenticatedBy":["APIKEY"]},"serviceCatalog":[{"type":"rax:dns","endpoints":[{"publicURL":"https://dns.api.rackspacecloud.com/v1.0/123456","tenantId":"123456"}],"name":"cloudDNS"}],"user":{"id":"fakeUseID","name":"testUser"}}}`, `{"auth":{"RAX-KSKEY:apiKeyCredentials":{"username":"testUser","apiKey":"testKey"}}}`: `{"access":{"token":{"id":"testToken","expires":"1970-01-01T00:00:00.000Z","tenant":{"id":"123456","name":"123456"},"RAX-AUTH:authenticatedBy":["APIKEY"]},"serviceCatalog":[{"type":"rax:dns","endpoints":[{"publicURL":"https://dns.api.rackspacecloud.com/v1.0/123456","tenantId":"123456"}],"name":"cloudDNS"}],"user":{"id":"fakeUseID","name":"testUser"}}}`,
"zoneDetails": `{"domains":[{"name":"example.com","id":112233,"emailAddress":"hostmaster@example.com","updated":"1970-01-01T00:00:00.000+0000","created":"1970-01-01T00:00:00.000+0000"}],"totalEntries":1}`, "zoneDetails": `{"domains":[{"name":"example.com","id":112233,"emailAddress":"hostmaster@example.com","updated":"1970-01-01T00:00:00.000+0000","created":"1970-01-01T00:00:00.000+0000"}],"totalEntries":1}`,

View file

@ -16,38 +16,33 @@ import (
) )
var ( var (
rfc2136TestDomain = "123456789.www.example.com" envTestDomain = "123456789.www.example.com"
rfc2136TestKeyAuth = "123d==" envTestKeyAuth = "123d=="
rfc2136TestValue = "Now36o-3BmlB623-0c1qCIUmgWVVmDJb88KGl24pqpo" envTestValue = "Now36o-3BmlB623-0c1qCIUmgWVVmDJb88KGl24pqpo"
rfc2136TestFqdn = "_acme-challenge.123456789.www.example.com." envTestFqdn = "_acme-challenge.123456789.www.example.com."
rfc2136TestZone = "example.com." envTestZone = "example.com."
rfc2136TestTTL = 120 envTestTTL = 120
rfc2136TestTsigKey = "example.com." envTestTsigKey = "example.com."
rfc2136TestTsigSecret = "IwBTJx9wrDp4Y1RyC3H0gA==" envTestTsigSecret = "IwBTJx9wrDp4Y1RyC3H0gA=="
) )
var reqChan = make(chan *dns.Msg, 10) var reqChan = make(chan *dns.Msg, 10)
func TestRFC2136CanaryLocalTestServer(t *testing.T) { func TestCanaryLocalTestServer(t *testing.T) {
acme.ClearFqdnCache() acme.ClearFqdnCache()
dns.HandleFunc("example.com.", serverHandlerHello) dns.HandleFunc("example.com.", serverHandlerHello)
defer dns.HandleRemove("example.com.") defer dns.HandleRemove("example.com.")
server, addrstr, err := runLocalDNSTestServer(false) server, addr, err := runLocalDNSTestServer(false)
require.NoError(t, err, "Failed to start test server") require.NoError(t, err, "Failed to start test server")
defer func() { defer func() { _ = server.Shutdown() }()
errS := server.Shutdown()
if errS != nil {
t.Log(errS)
}
}()
c := new(dns.Client) c := new(dns.Client)
m := new(dns.Msg) m := new(dns.Msg)
m.SetQuestion("example.com.", dns.TypeTXT) m.SetQuestion("example.com.", dns.TypeTXT)
r, _, err := c.Exchange(m, addrstr) r, _, err := c.Exchange(m, addr)
require.NoError(t, err, "Failed to communicate with test server") require.NoError(t, err, "Failed to communicate with test server")
assert.Len(t, r.Extra, 1, "Failed to communicate with test server") assert.Len(t, r.Extra, 1, "Failed to communicate with test server")
@ -55,115 +50,95 @@ func TestRFC2136CanaryLocalTestServer(t *testing.T) {
assert.Equal(t, "Hello world", txt) assert.Equal(t, "Hello world", txt)
} }
func TestRFC2136ServerSuccess(t *testing.T) { func TestServerSuccess(t *testing.T) {
acme.ClearFqdnCache() acme.ClearFqdnCache()
dns.HandleFunc(rfc2136TestZone, serverHandlerReturnSuccess) dns.HandleFunc(envTestZone, serverHandlerReturnSuccess)
defer dns.HandleRemove(rfc2136TestZone) defer dns.HandleRemove(envTestZone)
server, addrstr, err := runLocalDNSTestServer(false) server, addr, err := runLocalDNSTestServer(false)
require.NoError(t, err, "Failed to start test server") require.NoError(t, err, "Failed to start test server")
defer func() { defer func() { _ = server.Shutdown() }()
errS := server.Shutdown()
if errS != nil {
t.Log(errS)
}
}()
config := NewDefaultConfig() config := NewDefaultConfig()
config.Nameserver = addrstr config.Nameserver = addr
provider, err := NewDNSProviderConfig(config) provider, err := NewDNSProviderConfig(config)
require.NoError(t, err) require.NoError(t, err)
err = provider.Present(rfc2136TestDomain, "", rfc2136TestKeyAuth) err = provider.Present(envTestDomain, "", envTestKeyAuth)
require.NoError(t, err) require.NoError(t, err)
} }
func TestRFC2136ServerError(t *testing.T) { func TestServerError(t *testing.T) {
acme.ClearFqdnCache() acme.ClearFqdnCache()
dns.HandleFunc(rfc2136TestZone, serverHandlerReturnErr) dns.HandleFunc(envTestZone, serverHandlerReturnErr)
defer dns.HandleRemove(rfc2136TestZone) defer dns.HandleRemove(envTestZone)
server, addrstr, err := runLocalDNSTestServer(false) server, addr, err := runLocalDNSTestServer(false)
require.NoError(t, err, "Failed to start test server") require.NoError(t, err, "Failed to start test server")
defer func() { defer func() { _ = server.Shutdown() }()
errS := server.Shutdown()
if errS != nil {
t.Log(errS)
}
}()
config := NewDefaultConfig() config := NewDefaultConfig()
config.Nameserver = addrstr config.Nameserver = addr
provider, err := NewDNSProviderConfig(config) provider, err := NewDNSProviderConfig(config)
require.NoError(t, err) require.NoError(t, err)
err = provider.Present(rfc2136TestDomain, "", rfc2136TestKeyAuth) err = provider.Present(envTestDomain, "", envTestKeyAuth)
require.Error(t, err) require.Error(t, err)
if !strings.Contains(err.Error(), "NOTZONE") { if !strings.Contains(err.Error(), "NOTZONE") {
t.Errorf("Expected Present() to return an error with the 'NOTZONE' rcode string but it did not: %v", err) t.Errorf("Expected Present() to return an error with the 'NOTZONE' rcode string but it did not: %v", err)
} }
} }
func TestRFC2136TsigClient(t *testing.T) { func TestTsigClient(t *testing.T) {
acme.ClearFqdnCache() acme.ClearFqdnCache()
dns.HandleFunc(rfc2136TestZone, serverHandlerReturnSuccess) dns.HandleFunc(envTestZone, serverHandlerReturnSuccess)
defer dns.HandleRemove(rfc2136TestZone) defer dns.HandleRemove(envTestZone)
server, addrstr, err := runLocalDNSTestServer(true) server, addr, err := runLocalDNSTestServer(true)
require.NoError(t, err, "Failed to start test server") require.NoError(t, err, "Failed to start test server")
defer func() { defer func() { _ = server.Shutdown() }()
errS := server.Shutdown()
if errS != nil {
t.Log(errS)
}
}()
config := NewDefaultConfig() config := NewDefaultConfig()
config.Nameserver = addrstr config.Nameserver = addr
config.TSIGKey = rfc2136TestTsigKey config.TSIGKey = envTestTsigKey
config.TSIGSecret = rfc2136TestTsigSecret config.TSIGSecret = envTestTsigSecret
provider, err := NewDNSProviderConfig(config) provider, err := NewDNSProviderConfig(config)
require.NoError(t, err) require.NoError(t, err)
err = provider.Present(rfc2136TestDomain, "", rfc2136TestKeyAuth) err = provider.Present(envTestDomain, "", envTestKeyAuth)
require.NoError(t, err) require.NoError(t, err)
} }
func TestRFC2136ValidUpdatePacket(t *testing.T) { func TestValidUpdatePacket(t *testing.T) {
acme.ClearFqdnCache() acme.ClearFqdnCache()
dns.HandleFunc(rfc2136TestZone, serverHandlerPassBackRequest) dns.HandleFunc(envTestZone, serverHandlerPassBackRequest)
defer dns.HandleRemove(rfc2136TestZone) defer dns.HandleRemove(envTestZone)
server, addrstr, err := runLocalDNSTestServer(false) server, addr, err := runLocalDNSTestServer(false)
require.NoError(t, err, "Failed to start test server") require.NoError(t, err, "Failed to start test server")
defer func() { defer func() { _ = server.Shutdown() }()
errS := server.Shutdown()
if errS != nil {
t.Log(errS)
}
}()
txtRR, _ := dns.NewRR(fmt.Sprintf("%s %d IN TXT %s", rfc2136TestFqdn, rfc2136TestTTL, rfc2136TestValue)) txtRR, _ := dns.NewRR(fmt.Sprintf("%s %d IN TXT %s", envTestFqdn, envTestTTL, envTestValue))
rrs := []dns.RR{txtRR} rrs := []dns.RR{txtRR}
m := new(dns.Msg) m := new(dns.Msg)
m.SetUpdate(rfc2136TestZone) m.SetUpdate(envTestZone)
m.RemoveRRset(rrs) m.RemoveRRset(rrs)
m.Insert(rrs) m.Insert(rrs)
expectstr := m.String() expectStr := m.String()
expect, err := m.Pack() expect, err := m.Pack()
require.NoError(t, err, "error packing") require.NoError(t, err, "error packing")
config := NewDefaultConfig() config := NewDefaultConfig()
config.Nameserver = addrstr config.Nameserver = addr
provider, err := NewDNSProviderConfig(config) provider, err := NewDNSProviderConfig(config)
require.NoError(t, err) require.NoError(t, err)
err = provider.Present(rfc2136TestDomain, "", "1234d==") err = provider.Present(envTestDomain, "", "1234d==")
require.NoError(t, err) require.NoError(t, err)
rcvMsg := <-reqChan rcvMsg := <-reqChan
@ -177,7 +152,7 @@ func TestRFC2136ValidUpdatePacket(t *testing.T) {
if err := tmp.Unpack(actual); err != nil { if err := tmp.Unpack(actual); err != nil {
t.Fatalf("Error unpacking actual msg: %v", err) t.Fatalf("Error unpacking actual msg: %v", err)
} }
t.Errorf("Expected msg:\n%s", expectstr) t.Errorf("Expected msg:\n%s", expectStr)
t.Errorf("Actual msg:\n%v", tmp) t.Errorf("Actual msg:\n%v", tmp)
} }
} }
@ -187,9 +162,10 @@ func runLocalDNSTestServer(tsig bool) (*dns.Server, string, error) {
if err != nil { if err != nil {
return nil, "", err return nil, "", err
} }
server := &dns.Server{PacketConn: pc, ReadTimeout: time.Hour, WriteTimeout: time.Hour} server := &dns.Server{PacketConn: pc, ReadTimeout: time.Hour, WriteTimeout: time.Hour}
if tsig { if tsig {
server.TsigSecret = map[string]string{rfc2136TestTsigKey: rfc2136TestTsigSecret} server.TsigSecret = map[string]string{envTestTsigKey: envTestTsigSecret}
} }
waitLock := sync.Mutex{} waitLock := sync.Mutex{}
@ -221,14 +197,14 @@ func serverHandlerReturnSuccess(w dns.ResponseWriter, req *dns.Msg) {
m.SetReply(req) m.SetReply(req)
if req.Opcode == dns.OpcodeQuery && req.Question[0].Qtype == dns.TypeSOA && req.Question[0].Qclass == dns.ClassINET { if req.Opcode == dns.OpcodeQuery && req.Question[0].Qtype == dns.TypeSOA && req.Question[0].Qclass == dns.ClassINET {
// Return SOA to appease findZoneByFqdn() // Return SOA to appease findZoneByFqdn()
soaRR, _ := dns.NewRR(fmt.Sprintf("%s %d IN SOA ns1.%s admin.%s 2016022801 28800 7200 2419200 1200", rfc2136TestZone, rfc2136TestTTL, rfc2136TestZone, rfc2136TestZone)) soaRR, _ := dns.NewRR(fmt.Sprintf("%s %d IN SOA ns1.%s admin.%s 2016022801 28800 7200 2419200 1200", envTestZone, envTestTTL, envTestZone, envTestZone))
m.Answer = []dns.RR{soaRR} m.Answer = []dns.RR{soaRR}
} }
if t := req.IsTsig(); t != nil { if t := req.IsTsig(); t != nil {
if w.TsigStatus() == nil { if w.TsigStatus() == nil {
// Validated // Validated
m.SetTsig(rfc2136TestZone, dns.HmacMD5, 300, time.Now().Unix()) m.SetTsig(envTestZone, dns.HmacMD5, 300, time.Now().Unix())
} }
} }
@ -246,14 +222,14 @@ func serverHandlerPassBackRequest(w dns.ResponseWriter, req *dns.Msg) {
m.SetReply(req) m.SetReply(req)
if req.Opcode == dns.OpcodeQuery && req.Question[0].Qtype == dns.TypeSOA && req.Question[0].Qclass == dns.ClassINET { if req.Opcode == dns.OpcodeQuery && req.Question[0].Qtype == dns.TypeSOA && req.Question[0].Qclass == dns.ClassINET {
// Return SOA to appease findZoneByFqdn() // Return SOA to appease findZoneByFqdn()
soaRR, _ := dns.NewRR(fmt.Sprintf("%s %d IN SOA ns1.%s admin.%s 2016022801 28800 7200 2419200 1200", rfc2136TestZone, rfc2136TestTTL, rfc2136TestZone, rfc2136TestZone)) soaRR, _ := dns.NewRR(fmt.Sprintf("%s %d IN SOA ns1.%s admin.%s 2016022801 28800 7200 2419200 1200", envTestZone, envTestTTL, envTestZone, envTestZone))
m.Answer = []dns.RR{soaRR} m.Answer = []dns.RR{soaRR}
} }
if t := req.IsTsig(); t != nil { if t := req.IsTsig(); t != nil {
if w.TsigStatus() == nil { if w.TsigStatus() == nil {
// Validated // Validated
m.SetTsig(rfc2136TestZone, dns.HmacMD5, 300, time.Now().Unix()) m.SetTsig(envTestZone, dns.HmacMD5, 300, time.Now().Unix())
} }
} }

View file

@ -10,7 +10,7 @@ import (
"github.com/xenolf/lego/platform/config/env" "github.com/xenolf/lego/platform/config/env"
) )
func TestRoute53TTL(t *testing.T) { func TestLiveTTL(t *testing.T) {
config, err := env.Get("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_REGION", "R53_DOMAIN") config, err := env.Get("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_REGION", "R53_DOMAIN")
if err != nil { if err != nil {
t.Skip(err.Error()) t.Skip(err.Error())
@ -19,19 +19,19 @@ func TestRoute53TTL(t *testing.T) {
provider, err := NewDNSProvider() provider, err := NewDNSProvider()
require.NoError(t, err) require.NoError(t, err)
r53Domain := config["R53_DOMAIN"] domain := config["R53_DOMAIN"]
err = provider.Present(r53Domain, "foo", "bar") err = provider.Present(domain, "foo", "bar")
require.NoError(t, err) require.NoError(t, err)
// we need a separate R53 client here as the one in the DNS provider is unexported. // we need a separate R53 client here as the one in the DNS provider is unexported.
fqdn := "_acme-challenge." + r53Domain + "." fqdn := "_acme-challenge." + domain + "."
sess, err := session.NewSession() sess, err := session.NewSession()
require.NoError(t, err) require.NoError(t, err)
svc := route53.New(sess) svc := route53.New(sess)
defer func() { defer func() {
errC := provider.CleanUp(r53Domain, "foo", "bar") errC := provider.CleanUp(domain, "foo", "bar")
if errC != nil { if errC != nil {
t.Log(errC) t.Log(errC)
} }
@ -52,5 +52,5 @@ func TestRoute53TTL(t *testing.T) {
} }
} }
t.Fatalf("Could not find a TXT record for _acme-challenge.%s with a TTL of 10", r53Domain) t.Fatalf("Could not find a TXT record for _acme-challenge.%s with a TTL of 10", domain)
} }

View file

@ -15,39 +15,39 @@ import (
) )
var ( var (
r53AwsSecretAccessKey string envTestAwsSecretAccessKey string
r53AwsAccessKeyID string envTestAwsAccessKeyID string
r53AwsRegion string envTestAwsRegion string
r53AwsHostedZoneID string envTestAwsHostedZoneID string
r53AwsMaxRetries string envTestAwsMaxRetries string
r53AwsTTL string envTestAwsTTL string
r53AwsPropagationTimeout string envTestAwsPropagationTimeout string
r53AwsPollingInterval string envTestAwsPollingInterval string
) )
func init() { func init() {
r53AwsAccessKeyID = os.Getenv("AWS_ACCESS_KEY_ID") envTestAwsAccessKeyID = os.Getenv("AWS_ACCESS_KEY_ID")
r53AwsSecretAccessKey = os.Getenv("AWS_SECRET_ACCESS_KEY") envTestAwsSecretAccessKey = os.Getenv("AWS_SECRET_ACCESS_KEY")
r53AwsRegion = os.Getenv("AWS_REGION") envTestAwsRegion = os.Getenv("AWS_REGION")
r53AwsHostedZoneID = os.Getenv("AWS_HOSTED_ZONE_ID") envTestAwsHostedZoneID = os.Getenv("AWS_HOSTED_ZONE_ID")
r53AwsMaxRetries = os.Getenv("AWS_MAX_RETRIES") envTestAwsMaxRetries = os.Getenv("AWS_MAX_RETRIES")
r53AwsTTL = os.Getenv("AWS_TTL") envTestAwsTTL = os.Getenv("AWS_TTL")
r53AwsPropagationTimeout = os.Getenv("AWS_PROPAGATION_TIMEOUT") envTestAwsPropagationTimeout = os.Getenv("AWS_PROPAGATION_TIMEOUT")
r53AwsPollingInterval = os.Getenv("AWS_POLLING_INTERVAL") envTestAwsPollingInterval = os.Getenv("AWS_POLLING_INTERVAL")
} }
func restoreEnv() { func restoreEnv() {
os.Setenv("AWS_ACCESS_KEY_ID", r53AwsAccessKeyID) os.Setenv("AWS_ACCESS_KEY_ID", envTestAwsAccessKeyID)
os.Setenv("AWS_SECRET_ACCESS_KEY", r53AwsSecretAccessKey) os.Setenv("AWS_SECRET_ACCESS_KEY", envTestAwsSecretAccessKey)
os.Setenv("AWS_REGION", r53AwsRegion) os.Setenv("AWS_REGION", envTestAwsRegion)
os.Setenv("AWS_HOSTED_ZONE_ID", r53AwsHostedZoneID) os.Setenv("AWS_HOSTED_ZONE_ID", envTestAwsHostedZoneID)
os.Setenv("AWS_MAX_RETRIES", r53AwsMaxRetries) os.Setenv("AWS_MAX_RETRIES", envTestAwsMaxRetries)
os.Setenv("AWS_TTL", r53AwsTTL) os.Setenv("AWS_TTL", envTestAwsTTL)
os.Setenv("AWS_PROPAGATION_TIMEOUT", r53AwsPropagationTimeout) os.Setenv("AWS_PROPAGATION_TIMEOUT", envTestAwsPropagationTimeout)
os.Setenv("AWS_POLLING_INTERVAL", r53AwsPollingInterval) os.Setenv("AWS_POLLING_INTERVAL", envTestAwsPollingInterval)
} }
func cleanEnv() { func cleanEnv() {
@ -62,7 +62,7 @@ func cleanEnv() {
os.Unsetenv("AWS_POLLING_INTERVAL") os.Unsetenv("AWS_POLLING_INTERVAL")
} }
func makeRoute53Provider(ts *httptest.Server) *DNSProvider { func makeTestProvider(ts *httptest.Server) *DNSProvider {
config := &aws.Config{ config := &aws.Config{
Credentials: credentials.NewStaticCredentials("abc", "123", " "), Credentials: credentials.NewStaticCredentials("abc", "123", " "),
Endpoint: aws.String(ts.URL), Endpoint: aws.String(ts.URL),
@ -93,7 +93,7 @@ func Test_loadCredentials_FromEnv(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
value, err := sess.Config.Credentials.Get() value, err := sess.Config.Credentials.Get()
assert.NoError(t, err, "Expected credentials to be set from environment") require.NoError(t, err, "Expected credentials to be set from environment")
expected := credentials.Value{ expected := credentials.Value{
AccessKeyID: "123", AccessKeyID: "123",
@ -123,10 +123,10 @@ func Test_getHostedZoneID_FromEnv(t *testing.T) {
os.Setenv("AWS_HOSTED_ZONE_ID", expectedZoneID) os.Setenv("AWS_HOSTED_ZONE_ID", expectedZoneID)
provider, err := NewDNSProvider() provider, err := NewDNSProvider()
assert.NoError(t, err) require.NoError(t, err)
hostedZoneID, err := provider.getHostedZoneID("whatever") hostedZoneID, err := provider.getHostedZoneID("whatever")
assert.NoError(t, err, "HostedZoneID") require.NoError(t, err, "HostedZoneID")
assert.Equal(t, expectedZoneID, hostedZoneID) assert.Equal(t, expectedZoneID, hostedZoneID)
} }
@ -181,7 +181,7 @@ func TestNewDefaultConfig(t *testing.T) {
} }
} }
func TestRoute53Present(t *testing.T) { func TestDNSProvider_Present(t *testing.T) {
mockResponses := MockResponseMap{ mockResponses := MockResponseMap{
"/2013-04-01/hostedzonesbyname": {StatusCode: 200, Body: ListHostedZonesByNameResponse}, "/2013-04-01/hostedzonesbyname": {StatusCode: 200, Body: ListHostedZonesByNameResponse},
"/2013-04-01/hostedzone/ABCDEFG/rrset/": {StatusCode: 200, Body: ChangeResourceRecordSetsResponse}, "/2013-04-01/hostedzone/ABCDEFG/rrset/": {StatusCode: 200, Body: ChangeResourceRecordSetsResponse},
@ -195,11 +195,11 @@ func TestRoute53Present(t *testing.T) {
ts := newMockServer(t, mockResponses) ts := newMockServer(t, mockResponses)
defer ts.Close() defer ts.Close()
provider := makeRoute53Provider(ts) provider := makeTestProvider(ts)
domain := "example.com" domain := "example.com"
keyAuth := "123456d==" keyAuth := "123456d=="
err := provider.Present(domain, "", keyAuth) err := provider.Present(domain, "", keyAuth)
assert.NoError(t, err, "Expected Present to return no error") require.NoError(t, err, "Expected Present to return no error")
} }

View file

@ -5,121 +5,171 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/xenolf/lego/acme"
) )
var ( var (
sakuracloudLiveTest bool liveTest bool
sakuracloudAccessToken string envTestAccessToken string
sakuracloudAccessSecret string envTestAccessSecret string
sakuracloudDomain string envTestDomain string
) )
func init() { func init() {
sakuracloudAccessToken = os.Getenv("SAKURACLOUD_ACCESS_TOKEN") envTestAccessToken = os.Getenv("SAKURACLOUD_ACCESS_TOKEN")
sakuracloudAccessSecret = os.Getenv("SAKURACLOUD_ACCESS_TOKEN_SECRET") envTestAccessSecret = os.Getenv("SAKURACLOUD_ACCESS_TOKEN_SECRET")
sakuracloudDomain = os.Getenv("SAKURACLOUD_DOMAIN") envTestDomain = os.Getenv("SAKURACLOUD_DOMAIN")
if len(sakuracloudAccessToken) > 0 && len(sakuracloudAccessSecret) > 0 && len(sakuracloudDomain) > 0 { if len(envTestAccessToken) > 0 && len(envTestAccessSecret) > 0 && len(envTestDomain) > 0 {
sakuracloudLiveTest = true liveTest = true
} }
} }
func restoreEnv() { func restoreEnv() {
os.Setenv("SAKURACLOUD_ACCESS_TOKEN", sakuracloudAccessToken) os.Setenv("SAKURACLOUD_ACCESS_TOKEN", envTestAccessToken)
os.Setenv("SAKURACLOUD_ACCESS_TOKEN_SECRET", sakuracloudAccessSecret) os.Setenv("SAKURACLOUD_ACCESS_TOKEN_SECRET", envTestAccessSecret)
} }
// func TestNewDNSProvider(t *testing.T) {
// NewDNSProvider testCases := []struct {
// desc string
envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
"SAKURACLOUD_ACCESS_TOKEN": "123",
"SAKURACLOUD_ACCESS_TOKEN_SECRET": "456",
},
},
{
desc: "missing credentials",
envVars: map[string]string{
"SAKURACLOUD_ACCESS_TOKEN": "",
"SAKURACLOUD_ACCESS_TOKEN_SECRET": "",
},
expected: "sakuracloud: some credentials information are missing: SAKURACLOUD_ACCESS_TOKEN,SAKURACLOUD_ACCESS_TOKEN_SECRET",
},
{
desc: "missing access token",
envVars: map[string]string{
"SAKURACLOUD_ACCESS_TOKEN": "",
"SAKURACLOUD_ACCESS_TOKEN_SECRET": "456",
},
expected: "sakuracloud: some credentials information are missing: SAKURACLOUD_ACCESS_TOKEN",
},
{
desc: "missing token secret",
envVars: map[string]string{
"SAKURACLOUD_ACCESS_TOKEN": "123",
"SAKURACLOUD_ACCESS_TOKEN_SECRET": "",
},
expected: "sakuracloud: some credentials information are missing: SAKURACLOUD_ACCESS_TOKEN_SECRET",
},
}
func TestNewDNSProviderValid(t *testing.T) { for _, test := range testCases {
defer restoreEnv() t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
for key, value := range test.envVars {
if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
}
os.Setenv("SAKURACLOUD_ACCESS_TOKEN", "123") p, err := NewDNSProvider()
os.Setenv("SAKURACLOUD_ACCESS_TOKEN_SECRET", "456")
provider, err := NewDNSProvider()
assert.NotNil(t, provider) if len(test.expected) == 0 {
assert.Equal(t, acme.UserAgent, provider.client.UserAgent) require.NoError(t, err)
require.NoError(t, err) require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
} }
func TestNewDNSProviderInvalidWithMissingAccessToken(t *testing.T) { func TestNewDNSProviderConfig(t *testing.T) {
defer restoreEnv() testCases := []struct {
desc string
token string
secret string
expected string
}{
{
desc: "success",
token: "123",
secret: "456",
},
{
desc: "missing credentials",
expected: "sakuracloud: AccessToken is missing",
},
{
desc: "missing token",
secret: "456",
expected: "sakuracloud: AccessToken is missing",
},
{
desc: "missing secret",
token: "123",
expected: "sakuracloud: AccessSecret is missing",
},
}
os.Setenv("SAKURACLOUD_ACCESS_TOKEN", "") for _, test := range testCases {
provider, err := NewDNSProvider() t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
os.Unsetenv("SAKURACLOUD_ACCESS_TOKEN")
os.Unsetenv("SAKURACLOUD_ACCESS_TOKEN_SECRET")
assert.Nil(t, provider) config := NewDefaultConfig()
assert.EqualError(t, err, "sakuracloud: some credentials information are missing: SAKURACLOUD_ACCESS_TOKEN,SAKURACLOUD_ACCESS_TOKEN_SECRET") config.Token = test.token
config.Secret = test.secret
p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
} }
// func TestLivePresent(t *testing.T) {
// NewDNSProviderCredentials if !liveTest {
//
func TestNewDNSProviderCredentialsValid(t *testing.T) {
config := NewDefaultConfig()
config.Token = "123"
config.Secret = "456"
provider, err := NewDNSProviderConfig(config)
require.NoError(t, err)
assert.NotNil(t, provider)
assert.Equal(t, acme.UserAgent, provider.client.UserAgent)
}
func TestNewDNSProviderCredentialsInvalidWithMissingAccessToken(t *testing.T) {
config := NewDefaultConfig()
provider, err := NewDNSProviderConfig(config)
assert.Nil(t, provider)
assert.EqualError(t, err, "sakuracloud: AccessToken is missing")
}
//
// Present
//
func TestLiveSakuraCloudPresent(t *testing.T) {
if !sakuracloudLiveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
config := NewDefaultConfig() restoreEnv()
config.Token = sakuracloudAccessToken provider, err := NewDNSProvider()
config.Secret = sakuracloudAccessSecret
provider, err := NewDNSProviderConfig(config)
require.NoError(t, err) require.NoError(t, err)
err = provider.Present(sakuracloudDomain, "", "123d==") err = provider.Present(envTestDomain, "", "123d==")
require.NoError(t, err) require.NoError(t, err)
} }
// func TestLiveCleanUp(t *testing.T) {
// Cleanup if !liveTest {
//
func TestLiveSakuraCloudCleanUp(t *testing.T) {
if !sakuracloudLiveTest {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
time.Sleep(time.Second * 1) restoreEnv()
provider, err := NewDNSProvider()
config := NewDefaultConfig()
config.Token = sakuracloudAccessToken
config.Secret = sakuracloudAccessSecret
provider, err := NewDNSProviderConfig(config)
require.NoError(t, err) require.NoError(t, err)
err = provider.CleanUp(sakuracloudDomain, "", "123d==") time.Sleep(1 * time.Second)
err = provider.CleanUp(envTestDomain, "", "123d==")
require.NoError(t, err) require.NoError(t, err)
} }

View file

@ -13,58 +13,32 @@ import (
) )
var ( var (
stackpathLiveTest bool liveTest bool
stackpathClientID string envTestClientID string
stackpathClientSecret string envTestClientSecret string
stackpathStackID string envTestStackID string
stackpathDomain string envTestDomain string
) )
func init() { func init() {
stackpathClientID = os.Getenv("STACKPATH_CLIENT_ID") envTestClientID = os.Getenv("STACKPATH_CLIENT_ID")
stackpathClientSecret = os.Getenv("STACKPATH_CLIENT_SECRET") envTestClientSecret = os.Getenv("STACKPATH_CLIENT_SECRET")
stackpathStackID = os.Getenv("STACKPATH_STACK_ID") envTestStackID = os.Getenv("STACKPATH_STACK_ID")
stackpathDomain = os.Getenv("STACKPATH_DOMAIN") envTestDomain = os.Getenv("STACKPATH_DOMAIN")
if len(stackpathClientID) > 0 && if len(envTestClientID) > 0 &&
len(stackpathClientSecret) > 0 && len(envTestClientSecret) > 0 &&
len(stackpathStackID) > 0 && len(envTestStackID) > 0 &&
len(stackpathDomain) > 0 { len(envTestDomain) > 0 {
stackpathLiveTest = true liveTest = true
} }
} }
func restoreEnv() { func restoreEnv() {
os.Setenv("STACKPATH_CLIENT_ID", stackpathClientID) os.Setenv("STACKPATH_CLIENT_ID", envTestClientID)
os.Setenv("STACKPATH_CLIENT_SECRET", stackpathClientSecret) os.Setenv("STACKPATH_CLIENT_SECRET", envTestClientSecret)
os.Setenv("STACKPATH_STACK_ID", stackpathStackID) os.Setenv("STACKPATH_STACK_ID", envTestStackID)
os.Setenv("STACKPATH_DOMAIN", stackpathDomain) os.Setenv("STACKPATH_DOMAIN", envTestDomain)
}
func TestLivePresent(t *testing.T) {
if !stackpathLiveTest {
t.Skip("skipping live test")
}
provider, err := NewDNSProvider()
require.NoError(t, err)
err = provider.Present(stackpathDomain, "", "123d==")
require.NoError(t, err)
}
func TestLiveCleanUp(t *testing.T) {
if !stackpathLiveTest {
t.Skip("skipping live test")
}
time.Sleep(time.Second * 1)
provider, err := NewDNSProvider()
require.NoError(t, err)
err = provider.CleanUp(stackpathDomain, "", "123d==")
require.NoError(t, err)
} }
func TestNewDNSProvider(t *testing.T) { func TestNewDNSProvider(t *testing.T) {
@ -133,7 +107,7 @@ func TestNewDNSProvider(t *testing.T) {
p, err := NewDNSProvider() p, err := NewDNSProvider()
if len(test.expected) == 0 { if len(test.expected) == 0 {
assert.NoError(t, err) require.NoError(t, err)
assert.NotNil(t, p) assert.NotNil(t, p)
} else { } else {
require.EqualError(t, err, test.expected) require.EqualError(t, err, test.expected)
@ -313,3 +287,31 @@ func TestDNSProvider_getZones(t *testing.T) {
assert.Equal(t, expected, zone) assert.Equal(t, expected, zone)
} }
func TestLivePresent(t *testing.T) {
if !liveTest {
t.Skip("skipping live test")
}
restoreEnv()
provider, err := NewDNSProvider()
require.NoError(t, err)
err = provider.Present(envTestDomain, "", "123d==")
require.NoError(t, err)
}
func TestLiveCleanUp(t *testing.T) {
if !liveTest {
t.Skip("skipping live test")
}
restoreEnv()
provider, err := NewDNSProvider()
require.NoError(t, err)
time.Sleep(1 * time.Second)
err = provider.CleanUp(envTestDomain, "", "123d==")
require.NoError(t, err)
}

View file

@ -103,14 +103,14 @@ var jsonMap = map[string]string{
type muxCallback func() *http.ServeMux type muxCallback func() *http.ServeMux
func TestVegaDNSNewDNSProviderFail(t *testing.T) { func TestNewDNSProvider_Fail(t *testing.T) {
os.Setenv("VEGADNS_URL", "") os.Setenv("VEGADNS_URL", "")
_, err := NewDNSProvider() _, err := NewDNSProvider()
assert.Error(t, err, "VEGADNS_URL env missing") assert.Error(t, err, "VEGADNS_URL env missing")
} }
func TestVegaDNSTimeoutSuccess(t *testing.T) { func TestDNSProvider_TimeoutSuccess(t *testing.T) {
ts, err := startTestServer(vegaDNSMuxSuccess) ts, err := startTestServer(muxSuccess)
require.NoError(t, err) require.NoError(t, err)
defer ts.Close() defer ts.Close()
@ -132,16 +132,16 @@ func TestDNSProvider_Present(t *testing.T) {
}{ }{
{ {
desc: "Success", desc: "Success",
callback: vegaDNSMuxSuccess, callback: muxSuccess,
}, },
{ {
desc: "FailToFindZone", desc: "FailToFindZone",
callback: vegaDNSMuxFailToFindZone, callback: muxFailToFindZone,
expectedError: "vegadns: can't find Authoritative Zone for _acme-challenge.example.com. in Present: Unable to find auth zone for fqdn _acme-challenge.example.com", expectedError: "vegadns: can't find Authoritative Zone for _acme-challenge.example.com. in Present: Unable to find auth zone for fqdn _acme-challenge.example.com",
}, },
{ {
desc: "FailToCreateTXT", desc: "FailToCreateTXT",
callback: vegaDNSMuxFailToCreateTXT, callback: muxFailToCreateTXT,
expectedError: "vegadns: Got bad answer from VegaDNS on CreateTXT. Code: 400. Message: ", expectedError: "vegadns: Got bad answer from VegaDNS on CreateTXT. Code: 400. Message: ",
}, },
} }
@ -175,16 +175,16 @@ func TestDNSProvider_CleanUp(t *testing.T) {
}{ }{
{ {
desc: "Success", desc: "Success",
callback: vegaDNSMuxSuccess, callback: muxSuccess,
}, },
{ {
desc: "FailToFindZone", desc: "FailToFindZone",
callback: vegaDNSMuxFailToFindZone, callback: muxFailToFindZone,
expectedError: "vegadns: can't find Authoritative Zone for _acme-challenge.example.com. in CleanUp: Unable to find auth zone for fqdn _acme-challenge.example.com", expectedError: "vegadns: can't find Authoritative Zone for _acme-challenge.example.com. in CleanUp: Unable to find auth zone for fqdn _acme-challenge.example.com",
}, },
{ {
desc: "FailToGetRecordID", desc: "FailToGetRecordID",
callback: vegaDNSMuxFailToGetRecordID, callback: muxFailToGetRecordID,
expectedError: "vegadns: couldn't get Record ID in CleanUp: Got bad answer from VegaDNS on GetRecordID. Code: 404. Message: ", expectedError: "vegadns: couldn't get Record ID in CleanUp: Got bad answer from VegaDNS on GetRecordID. Code: 404. Message: ",
}, },
} }
@ -210,7 +210,7 @@ func TestDNSProvider_CleanUp(t *testing.T) {
} }
} }
func vegaDNSMuxSuccess() *http.ServeMux { func muxSuccess() *http.ServeMux {
mux := http.NewServeMux() mux := http.NewServeMux()
mux.HandleFunc("/1.0/token", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("/1.0/token", func(w http.ResponseWriter, r *http.Request) {
@ -268,7 +268,7 @@ func vegaDNSMuxSuccess() *http.ServeMux {
return mux return mux
} }
func vegaDNSMuxFailToFindZone() *http.ServeMux { func muxFailToFindZone() *http.ServeMux {
mux := http.NewServeMux() mux := http.NewServeMux()
mux.HandleFunc("/1.0/token", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("/1.0/token", func(w http.ResponseWriter, r *http.Request) {
@ -288,7 +288,7 @@ func vegaDNSMuxFailToFindZone() *http.ServeMux {
return mux return mux
} }
func vegaDNSMuxFailToCreateTXT() *http.ServeMux { func muxFailToCreateTXT() *http.ServeMux {
mux := http.NewServeMux() mux := http.NewServeMux()
mux.HandleFunc("/1.0/token", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("/1.0/token", func(w http.ResponseWriter, r *http.Request) {
@ -330,7 +330,7 @@ func vegaDNSMuxFailToCreateTXT() *http.ServeMux {
return mux return mux
} }
func vegaDNSMuxFailToGetRecordID() *http.ServeMux { func muxFailToGetRecordID() *http.ServeMux {
mux := http.NewServeMux() mux := http.NewServeMux()
mux.HandleFunc("/1.0/token", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("/1.0/token", func(w http.ResponseWriter, r *http.Request) {

View file

@ -5,40 +5,108 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
var ( var (
liveTest bool liveTest bool
apiKey string envTestAPIKey string
domain string envTestDomain string
) )
func init() { func init() {
apiKey = os.Getenv("VULTR_API_KEY") envTestAPIKey = os.Getenv("VULTR_API_KEY")
domain = os.Getenv("VULTR_TEST_DOMAIN") envTestDomain = os.Getenv("VULTR_TEST_DOMAIN")
liveTest = len(apiKey) > 0 && len(domain) > 0
liveTest = len(envTestAPIKey) > 0 && len(envTestDomain) > 0
} }
func restoreEnv() { func restoreEnv() {
os.Setenv("VULTR_API_KEY", apiKey) os.Setenv("VULTR_API_KEY", envTestAPIKey)
} }
func TestNewDNSProviderValidEnv(t *testing.T) { func TestNewDNSProvider(t *testing.T) {
defer restoreEnv() testCases := []struct {
os.Setenv("VULTR_API_KEY", "123") desc string
envVars map[string]string
expected string
}{
{
desc: "success",
envVars: map[string]string{
"VULTR_API_KEY": "123",
},
},
{
desc: "missing api key",
envVars: map[string]string{
"VULTR_API_KEY": "",
},
expected: "vultr: some credentials information are missing: VULTR_API_KEY",
},
}
_, err := NewDNSProvider() for _, test := range testCases {
require.NoError(t, err) t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
for key, value := range test.envVars {
if len(value) == 0 {
os.Unsetenv(key)
} else {
os.Setenv(key, value)
}
}
p, err := NewDNSProvider()
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
} }
func TestNewDNSProviderMissingCredErr(t *testing.T) { func TestNewDNSProviderConfig(t *testing.T) {
defer restoreEnv() testCases := []struct {
os.Setenv("VULTR_API_KEY", "") desc string
apiKey string
expected string
}{
{
desc: "success",
apiKey: "123",
},
{
desc: "missing credentials",
expected: "vultr: credentials missing",
},
}
_, err := NewDNSProvider() for _, test := range testCases {
assert.EqualError(t, err, "vultr: some credentials information are missing: VULTR_API_KEY") t.Run(test.desc, func(t *testing.T) {
defer restoreEnv()
os.Unsetenv("VULTR_API_KEY")
config := NewDefaultConfig()
config.APIKey = test.apiKey
p, err := NewDNSProviderConfig(config)
if len(test.expected) == 0 {
require.NoError(t, err)
require.NotNil(t, p)
require.NotNil(t, p.config)
require.NotNil(t, p.client)
} else {
require.EqualError(t, err, test.expected)
}
})
}
} }
func TestLivePresent(t *testing.T) { func TestLivePresent(t *testing.T) {
@ -46,10 +114,11 @@ func TestLivePresent(t *testing.T) {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
restoreEnv()
provider, err := NewDNSProvider() provider, err := NewDNSProvider()
require.NoError(t, err) require.NoError(t, err)
err = provider.Present(domain, "", "123d==") err = provider.Present(envTestDomain, "", "123d==")
require.NoError(t, err) require.NoError(t, err)
} }
@ -58,11 +127,12 @@ func TestLiveCleanUp(t *testing.T) {
t.Skip("skipping live test") t.Skip("skipping live test")
} }
time.Sleep(time.Second * 1) restoreEnv()
provider, err := NewDNSProvider() provider, err := NewDNSProvider()
require.NoError(t, err) require.NoError(t, err)
err = provider.CleanUp(domain, "", "123d==") time.Sleep(1 * time.Second)
err = provider.CleanUp(envTestDomain, "", "123d==")
require.NoError(t, err) require.NoError(t, err)
} }