chore: homogeneous tests setup and close servers. (#1520)

This commit is contained in:
Ludovic Fernandez 2021-11-02 00:52:38 +01:00 committed by GitHub
parent 15f3a45342
commit e719fabe96
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
54 changed files with 371 additions and 387 deletions

View file

@ -74,8 +74,7 @@ rzFL1KZfz+HZdnFwFW2T2gVW8L3ii1l9AJDuKzlvjUH3p6bgihVq02sjT8mx+GM2
` `
func TestCertificateService_Get_issuerRelUp(t *testing.T) { func TestCertificateService_Get_issuerRelUp(t *testing.T) {
mux, apiURL, tearDown := tester.SetupFakeAPI() mux, apiURL := tester.SetupFakeAPI(t)
defer tearDown()
mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) { mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Link", "<"+apiURL+`/issuer>; rel="up"`) w.Header().Set("Link", "<"+apiURL+`/issuer>; rel="up"`)
@ -106,8 +105,7 @@ func TestCertificateService_Get_issuerRelUp(t *testing.T) {
} }
func TestCertificateService_Get_embeddedIssuer(t *testing.T) { func TestCertificateService_Get_embeddedIssuer(t *testing.T) {
mux, apiURL, tearDown := tester.SetupFakeAPI() mux, apiURL := tester.SetupFakeAPI(t)
defer tearDown()
mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) { mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) {
_, err := w.Write([]byte(certResponseMock)) _, err := w.Write([]byte(certResponseMock))

View file

@ -12,7 +12,7 @@ import (
) )
func TestNotHoldingLockWhileMakingHTTPRequests(t *testing.T) { func TestNotHoldingLockWhileMakingHTTPRequests(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
time.Sleep(250 * time.Millisecond) time.Sleep(250 * time.Millisecond)
w.Header().Set("Replay-Nonce", "12345") w.Header().Set("Replay-Nonce", "12345")
w.Header().Set("Retry-After", "0") w.Header().Set("Retry-After", "0")
@ -22,10 +22,10 @@ func TestNotHoldingLockWhileMakingHTTPRequests(t *testing.T) {
return return
} }
})) }))
defer ts.Close() t.Cleanup(server.Close)
doer := sender.NewDoer(http.DefaultClient, "lego-test") doer := sender.NewDoer(http.DefaultClient, "lego-test")
j := NewManager(doer, ts.URL) j := NewManager(doer, server.URL)
ch := make(chan bool) ch := make(chan bool)
resultCh := make(chan bool) resultCh := make(chan bool)
go func() { go func() {

View file

@ -13,7 +13,7 @@ import (
) )
func TestNotHoldingLockWhileMakingHTTPRequests(t *testing.T) { func TestNotHoldingLockWhileMakingHTTPRequests(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
time.Sleep(250 * time.Millisecond) time.Sleep(250 * time.Millisecond)
w.Header().Set("Replay-Nonce", "12345") w.Header().Set("Replay-Nonce", "12345")
w.Header().Set("Retry-After", "0") w.Header().Set("Retry-After", "0")
@ -23,10 +23,10 @@ func TestNotHoldingLockWhileMakingHTTPRequests(t *testing.T) {
return return
} }
})) }))
defer ts.Close() t.Cleanup(server.Close)
doer := sender.NewDoer(http.DefaultClient, "lego-test") doer := sender.NewDoer(http.DefaultClient, "lego-test")
j := nonces.NewManager(doer, ts.URL) j := nonces.NewManager(doer, server.URL)
ch := make(chan bool) ch := make(chan bool)
resultCh := make(chan bool) resultCh := make(chan bool)
go func() { go func() {

View file

@ -12,11 +12,11 @@ import (
func TestDo_UserAgentOnAllHTTPMethod(t *testing.T) { func TestDo_UserAgentOnAllHTTPMethod(t *testing.T) {
var ua, method string var ua, method string
ts := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
ua = r.Header.Get("User-Agent") ua = r.Header.Get("User-Agent")
method = r.Method method = r.Method
})) }))
defer ts.Close() t.Cleanup(server.Close)
doer := NewDoer(http.DefaultClient, "") doer := NewDoer(http.DefaultClient, "")
@ -44,7 +44,7 @@ func TestDo_UserAgentOnAllHTTPMethod(t *testing.T) {
for _, test := range testCases { for _, test := range testCases {
t.Run(test.method, func(t *testing.T) { t.Run(test.method, func(t *testing.T) {
_, err := test.call(ts.URL) _, err := test.call(server.URL)
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, test.method, method) assert.Equal(t, test.method, method)

View file

@ -16,8 +16,7 @@ import (
) )
func TestOrderService_New(t *testing.T) { func TestOrderService_New(t *testing.T) {
mux, apiURL, tearDown := tester.SetupFakeAPI() mux, apiURL := tester.SetupFakeAPI(t)
defer tearDown()
// small value keeps test fast // small value keeps test fast
privateKey, errK := rsa.GenerateKey(rand.Reader, 512) privateKey, errK := rsa.GenerateKey(rand.Reader, 512)

View file

@ -154,8 +154,7 @@ Ob8VZRzI9neWagqNdwvYkQsEjgfbKbYK7p2CNTUQ
` `
func Test_checkResponse(t *testing.T) { func Test_checkResponse(t *testing.T) {
mux, apiURL, tearDown := tester.SetupFakeAPI() mux, apiURL := tester.SetupFakeAPI(t)
defer tearDown()
mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) { mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) {
_, err := w.Write([]byte(certResponseMock)) _, err := w.Write([]byte(certResponseMock))
@ -195,8 +194,7 @@ func Test_checkResponse(t *testing.T) {
} }
func Test_checkResponse_issuerRelUp(t *testing.T) { func Test_checkResponse_issuerRelUp(t *testing.T) {
mux, apiURL, tearDown := tester.SetupFakeAPI() mux, apiURL := tester.SetupFakeAPI(t)
defer tearDown()
mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) { mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Link", "<"+apiURL+`/issuer>; rel="up"`) w.Header().Set("Link", "<"+apiURL+`/issuer>; rel="up"`)
@ -245,8 +243,7 @@ func Test_checkResponse_issuerRelUp(t *testing.T) {
} }
func Test_checkResponse_embeddedIssuer(t *testing.T) { func Test_checkResponse_embeddedIssuer(t *testing.T) {
mux, apiURL, tearDown := tester.SetupFakeAPI() mux, apiURL := tester.SetupFakeAPI(t)
defer tearDown()
mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) { mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) {
_, err := w.Write([]byte(certResponseMock)) _, err := w.Write([]byte(certResponseMock))
@ -286,8 +283,7 @@ func Test_checkResponse_embeddedIssuer(t *testing.T) {
} }
func Test_checkResponse_alternate(t *testing.T) { func Test_checkResponse_alternate(t *testing.T) {
mux, apiURL, tearDown := tester.SetupFakeAPI() mux, apiURL := tester.SetupFakeAPI(t)
defer tearDown()
mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) { mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Add("Link", fmt.Sprintf(`<%s/certificate/1>;title="foo";rel="alternate"`, apiURL)) w.Header().Add("Link", fmt.Sprintf(`<%s/certificate/1>;title="foo";rel="alternate"`, apiURL))
@ -339,8 +335,7 @@ func Test_checkResponse_alternate(t *testing.T) {
} }
func Test_Get(t *testing.T) { func Test_Get(t *testing.T) {
mux, apiURL, tearDown := tester.SetupFakeAPI() mux, apiURL := tester.SetupFakeAPI(t)
defer tearDown()
mux.HandleFunc("/acme/cert/test-cert", func(w http.ResponseWriter, _ *http.Request) { mux.HandleFunc("/acme/cert/test-cert", func(w http.ResponseWriter, _ *http.Request) {
_, err := w.Write([]byte(certResponseMock)) _, err := w.Write([]byte(certResponseMock))

View file

@ -32,8 +32,7 @@ func (p *providerTimeoutMock) CleanUp(domain, token, keyAuth string) error { ret
func (p *providerTimeoutMock) Timeout() (time.Duration, time.Duration) { return p.timeout, p.interval } func (p *providerTimeoutMock) Timeout() (time.Duration, time.Duration) { return p.timeout, p.interval }
func TestChallenge_PreSolve(t *testing.T) { func TestChallenge_PreSolve(t *testing.T) {
_, apiURL, tearDown := tester.SetupFakeAPI() _, apiURL := tester.SetupFakeAPI(t)
defer tearDown()
privateKey, err := rsa.GenerateKey(rand.Reader, 512) privateKey, err := rsa.GenerateKey(rand.Reader, 512)
require.NoError(t, err) require.NoError(t, err)
@ -115,8 +114,7 @@ func TestChallenge_PreSolve(t *testing.T) {
} }
func TestChallenge_Solve(t *testing.T) { func TestChallenge_Solve(t *testing.T) {
_, apiURL, tearDown := tester.SetupFakeAPI() _, apiURL := tester.SetupFakeAPI(t)
defer tearDown()
privateKey, err := rsa.GenerateKey(rand.Reader, 512) privateKey, err := rsa.GenerateKey(rand.Reader, 512)
require.NoError(t, err) require.NoError(t, err)
@ -203,8 +201,7 @@ func TestChallenge_Solve(t *testing.T) {
} }
func TestChallenge_CleanUp(t *testing.T) { func TestChallenge_CleanUp(t *testing.T) {
_, apiURL, tearDown := tester.SetupFakeAPI() _, apiURL := tester.SetupFakeAPI(t)
defer tearDown()
privateKey, err := rsa.GenerateKey(rand.Reader, 512) privateKey, err := rsa.GenerateKey(rand.Reader, 512)
require.NoError(t, err) require.NoError(t, err)

View file

@ -18,8 +18,7 @@ import (
) )
func TestChallenge(t *testing.T) { func TestChallenge(t *testing.T) {
_, apiURL, tearDown := tester.SetupFakeAPI() _, apiURL := tester.SetupFakeAPI(t)
defer tearDown()
providerServer := NewProviderServer("", "23457") providerServer := NewProviderServer("", "23457")
@ -71,8 +70,7 @@ func TestChallenge(t *testing.T) {
} }
func TestChallengeInvalidPort(t *testing.T) { func TestChallengeInvalidPort(t *testing.T) {
_, apiURL, tearDown := tester.SetupFakeAPI() _, apiURL := tester.SetupFakeAPI(t)
defer tearDown()
privateKey, err := rsa.GenerateKey(rand.Reader, 128) privateKey, err := rsa.GenerateKey(rand.Reader, 128)
require.NoError(t, err, "Could not generate test key") require.NoError(t, err, "Could not generate test key")
@ -255,8 +253,7 @@ func TestChallengeWithProxy(t *testing.T) {
func testServeWithProxy(t *testing.T, header, extra *testProxyHeader, expectError bool) { func testServeWithProxy(t *testing.T, header, extra *testProxyHeader, expectError bool) {
t.Helper() t.Helper()
_, apiURL, tearDown := tester.SetupFakeAPI() _, apiURL := tester.SetupFakeAPI(t)
defer tearDown()
providerServer := NewProviderServer("localhost", "23457") providerServer := NewProviderServer("localhost", "23457")
if header != nil { if header != nil {

View file

@ -32,8 +32,7 @@ func TestByType(t *testing.T) {
} }
func TestValidate(t *testing.T) { func TestValidate(t *testing.T) {
mux, apiURL, tearDown := tester.SetupFakeAPI() mux, apiURL := tester.SetupFakeAPI(t)
defer tearDown()
var statuses []string var statuses []string

View file

@ -19,8 +19,7 @@ import (
) )
func TestChallenge(t *testing.T) { func TestChallenge(t *testing.T) {
_, apiURL, tearDown := tester.SetupFakeAPI() _, apiURL := tester.SetupFakeAPI(t)
defer tearDown()
domain := "localhost:23457" domain := "localhost:23457"
@ -89,8 +88,7 @@ func TestChallenge(t *testing.T) {
} }
func TestChallengeInvalidPort(t *testing.T) { func TestChallengeInvalidPort(t *testing.T) {
_, apiURL, tearDown := tester.SetupFakeAPI() _, apiURL := tester.SetupFakeAPI(t)
defer tearDown()
privateKey, err := rsa.GenerateKey(rand.Reader, 128) privateKey, err := rsa.GenerateKey(rand.Reader, 128)
require.NoError(t, err, "Could not generate test key") require.NoError(t, err, "Could not generate test key")

View file

@ -13,8 +13,7 @@ import (
) )
func TestNewClient(t *testing.T) { func TestNewClient(t *testing.T) {
_, apiURL, tearDown := tester.SetupFakeAPI() _, apiURL := tester.SetupFakeAPI(t)
defer tearDown()
keyBits := 32 // small value keeps test fast keyBits := 32 // small value keeps test fast
key, err := rsa.GenerateKey(rand.Reader, keyBits) key, err := rsa.GenerateKey(rand.Reader, keyBits)

View file

@ -4,14 +4,18 @@ import (
"encoding/json" "encoding/json"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"testing"
"github.com/go-acme/lego/v4/acme" "github.com/go-acme/lego/v4/acme"
) )
// SetupFakeAPI Minimal stub ACME server for validation. // SetupFakeAPI Minimal stub ACME server for validation.
func SetupFakeAPI() (*http.ServeMux, string, func()) { func SetupFakeAPI(t *testing.T) (*http.ServeMux, string) {
t.Helper()
mux := http.NewServeMux() mux := http.NewServeMux()
ts := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
mux.HandleFunc("/dir", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("/dir", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet { if r.Method != http.MethodGet {
@ -20,11 +24,11 @@ func SetupFakeAPI() (*http.ServeMux, string, func()) {
} }
err := WriteJSONResponse(w, acme.Directory{ err := WriteJSONResponse(w, acme.Directory{
NewNonceURL: ts.URL + "/nonce", NewNonceURL: server.URL + "/nonce",
NewAccountURL: ts.URL + "/account", NewAccountURL: server.URL + "/account",
NewOrderURL: ts.URL + "/newOrder", NewOrderURL: server.URL + "/newOrder",
RevokeCertURL: ts.URL + "/revokeCert", RevokeCertURL: server.URL + "/revokeCert",
KeyChangeURL: ts.URL + "/keyChange", KeyChangeURL: server.URL + "/keyChange",
}) })
mux.HandleFunc("/nonce", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("/nonce", func(w http.ResponseWriter, r *http.Request) {
@ -43,7 +47,7 @@ func SetupFakeAPI() (*http.ServeMux, string, func()) {
} }
}) })
return mux, ts.URL, ts.Close return mux, server.URL
} }
// WriteJSONResponse marshals the body as JSON and writes it to the response. // WriteJSONResponse marshals the body as JSON and writes it to the response.

View file

@ -15,6 +15,7 @@ import (
func TestClient_GetTxtRecord(t *testing.T) { func TestClient_GetTxtRecord(t *testing.T) {
mux := http.NewServeMux() mux := http.NewServeMux()
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
const domain = "example.com" const domain = "example.com"
const apiKey = "myKeyA" const apiKey = "myKeyA"
@ -55,6 +56,7 @@ func TestClient_GetTxtRecord(t *testing.T) {
func TestClient_CreateRecord(t *testing.T) { func TestClient_CreateRecord(t *testing.T) {
mux := http.NewServeMux() mux := http.NewServeMux()
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
const domain = "example.com" const domain = "example.com"
const apiKey = "myKeyB" const apiKey = "myKeyB"
@ -119,6 +121,7 @@ func TestClient_CreateRecord(t *testing.T) {
func TestClient_DeleteRecord(t *testing.T) { func TestClient_DeleteRecord(t *testing.T) {
mux := http.NewServeMux() mux := http.NewServeMux()
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
const domain = "example.com" const domain = "example.com"
const apiKey = "myKeyC" const apiKey = "myKeyC"

View file

@ -16,9 +16,12 @@ var envTest = tester.NewEnvTest(
EnvUserID, EnvUserID,
EnvKey) EnvKey)
func setupTest() (*DNSProvider, *http.ServeMux, func()) { func setupTest(t *testing.T) (*DNSProvider, *http.ServeMux) {
handler := http.NewServeMux() t.Helper()
server := httptest.NewServer(handler)
mux := http.NewServeMux()
server := httptest.NewServer(mux)
t.Cleanup(server.Close)
config := NewDefaultConfig() config := NewDefaultConfig()
config.UserID = "asdf1234" config.UserID = "asdf1234"
@ -26,11 +29,9 @@ func setupTest() (*DNSProvider, *http.ServeMux, func()) {
config.BaseURL = server.URL config.BaseURL = server.URL
provider, err := NewDNSProviderConfig(config) provider, err := NewDNSProviderConfig(config)
if err != nil { require.NoError(t, err)
panic(err)
}
return provider, handler, server.Close return provider, mux
} }
func TestNewDNSProvider(t *testing.T) { func TestNewDNSProvider(t *testing.T) {
@ -146,8 +147,7 @@ func TestNewDNSProviderConfig(t *testing.T) {
} }
func TestDNSProvider_Present(t *testing.T) { func TestDNSProvider_Present(t *testing.T) {
provider, mux, tearDown := setupTest() provider, mux := setupTest(t)
defer tearDown()
mux.HandleFunc("/zones", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("/zones", func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodGet, r.Method, "method") assert.Equal(t, http.MethodGet, r.Method, "method")
@ -181,8 +181,7 @@ func TestDNSProvider_Present(t *testing.T) {
} }
func TestDNSProvider_CleanUp(t *testing.T) { func TestDNSProvider_CleanUp(t *testing.T) {
provider, mux, tearDown := setupTest() provider, mux := setupTest(t)
defer tearDown()
mux.HandleFunc("/zones", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("/zones", func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodGet, r.Method) assert.Equal(t, http.MethodGet, r.Method)

View file

@ -132,13 +132,14 @@ func TestNewDNSProviderConfig(t *testing.T) {
config.TenantID = test.tenantID config.TenantID = test.tenantID
config.ResourceGroup = test.resourceGroup config.ResourceGroup = test.resourceGroup
handler := http.NewServeMux() mux := http.NewServeMux()
server := httptest.NewServer(handler) server := httptest.NewServer(mux)
defer server.Close() t.Cleanup(server.Close)
if test.handler == nil { if test.handler == nil {
handler.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {}) mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {})
} else { } else {
handler.HandleFunc("/", test.handler) mux.HandleFunc("/", test.handler)
} }
config.MetadataEndpoint = server.URL config.MetadataEndpoint = server.URL

View file

@ -18,19 +18,18 @@ import (
func setupTestProvider(t *testing.T) (*DNSProvider, *http.ServeMux) { func setupTestProvider(t *testing.T) (*DNSProvider, *http.ServeMux) {
t.Helper() t.Helper()
handler := http.NewServeMux() mux := http.NewServeMux()
svr := httptest.NewServer(handler) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
t.Cleanup(svr.Close)
config := NewDefaultConfig() config := NewDefaultConfig()
config.Endpoint, _ = url.Parse(svr.URL) config.Endpoint, _ = url.Parse(server.URL)
config.Token = "secret" config.Token = "secret"
prd, err := NewDNSProviderConfig(config) p, err := NewDNSProviderConfig(config)
require.NoError(t, err) require.NoError(t, err)
return prd, handler return p, mux
} }
func Test_getDomainIDByName(t *testing.T) { func Test_getDomainIDByName(t *testing.T) {

View file

@ -46,9 +46,7 @@ func TestClient_AddRecord(t *testing.T) {
}) })
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(func() { t.Cleanup(server.Close)
server.Close()
})
client := NewClient("clientID", "email@example.com", "secret", 300) client := NewClient("clientID", "email@example.com", "secret", 300)
client.apiBaseURL = server.URL + "/api" client.apiBaseURL = server.URL + "/api"
@ -117,9 +115,7 @@ func TestClient_DeleteRecord(t *testing.T) {
}) })
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(func() { t.Cleanup(server.Close)
server.Close()
})
client := NewClient("clientID", "email@example.com", "secret", 300) client := NewClient("clientID", "email@example.com", "secret", 300)
client.apiBaseURL = server.URL + "/api" client.apiBaseURL = server.URL + "/api"

View file

@ -456,6 +456,7 @@ func TestClient_AddTxtRecord(t *testing.T) {
handlerMock(http.MethodPost, []byte(test.apiResponse))(rw, req) handlerMock(http.MethodPost, []byte(test.apiResponse))(rw, req)
})) }))
t.Cleanup(server.Close)
client, err := NewClient(test.authID, test.subAuthID, "myAuthPassword") client, err := NewClient(test.authID, test.subAuthID, "myAuthPassword")
require.NoError(t, err) require.NoError(t, err)

View file

@ -107,6 +107,7 @@ func TestClientGetDomainInformation(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 := httptest.NewServer(handlerMock(http.MethodGet, test.response, test.data)) server := httptest.NewServer(handlerMock(http.MethodGet, test.response, test.data))
t.Cleanup(server.Close)
client, _ := NewClient("myKey", "mySecret") client, _ := NewClient("myKey", "mySecret")
client.BaseURL = server.URL + "/" client.BaseURL = server.URL + "/"
@ -210,6 +211,7 @@ func TestClientFindTxtRecord(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 := httptest.NewServer(handlerMock(http.MethodGet, test.response, test.txtRecords)) server := httptest.NewServer(handlerMock(http.MethodGet, test.response, test.txtRecords))
t.Cleanup(server.Close)
client, _ := NewClient("myKey", "mySecret") client, _ := NewClient("myKey", "mySecret")
client.BaseURL = server.URL + "/" client.BaseURL = server.URL + "/"
@ -274,6 +276,7 @@ func TestClientAddTxtRecord(t *testing.T) {
handlerMock(http.MethodPost, response, nil).ServeHTTP(rw, req) handlerMock(http.MethodPost, response, nil).ServeHTTP(rw, req)
})) }))
t.Cleanup(server.Close)
client, _ := NewClient("myKey", "mySecret") client, _ := NewClient("myKey", "mySecret")
client.BaseURL = server.URL + "/" client.BaseURL = server.URL + "/"

View file

@ -6,23 +6,25 @@ import (
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"testing" "testing"
"time"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
func setupClientTest() (*http.ServeMux, *Client, func()) { func setupTest(t *testing.T) (*http.ServeMux, *Client) {
t.Helper()
mux := http.NewServeMux() mux := http.NewServeMux()
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
client := &Client{ client := &Client{
token: "secret", token: "secret",
endpoint: server.URL, endpoint: server.URL,
httpClient: &http.Client{Timeout: 5 * time.Second}, httpClient: server.Client(),
} }
return mux, client, server.Close return mux, client
} }
func TestClient_GetDomainID(t *testing.T) { func TestClient_GetDomainID(t *testing.T) {
@ -120,8 +122,7 @@ func TestClient_GetDomainID(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) {
mux, client, tearDown := setupClientTest() mux, client := setupTest(t)
defer tearDown()
mux.Handle("/v1/domains", test.handler) mux.Handle("/v1/domains", test.handler)
@ -180,8 +181,7 @@ func TestClient_CreateRecord(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) {
mux, client, tearDown := setupClientTest() mux, client := setupTest(t)
defer tearDown()
mux.Handle("/v1/domains/lego/records", test.handler) mux.Handle("/v1/domains/lego/records", test.handler)

View file

@ -11,21 +11,23 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
func setupAPIMock() (*Client, *http.ServeMux, func()) { func setupTest(t *testing.T) (*Client, *http.ServeMux) {
handler := http.NewServeMux() t.Helper()
svr := httptest.NewServer(handler)
client := NewClient(nil) mux := http.NewServeMux()
client.BaseURL = svr.URL server := httptest.NewServer(mux)
t.Cleanup(server.Close)
return client, handler, svr.Close client := NewClient(server.Client())
client.BaseURL = server.URL
return client, mux
} }
func TestDomainService_GetAll(t *testing.T) { func TestDomainService_GetAll(t *testing.T) {
client, handler, tearDown := setupAPIMock() client, mux := setupTest(t)
defer tearDown()
handler.HandleFunc("/v1/domains", func(rw http.ResponseWriter, req *http.Request) { mux.HandleFunc("/v1/domains", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodGet { if req.Method != http.MethodGet {
http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest) http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest)
return return
@ -59,10 +61,9 @@ func TestDomainService_GetAll(t *testing.T) {
} }
func TestDomainService_Search(t *testing.T) { func TestDomainService_Search(t *testing.T) {
client, handler, tearDown := setupAPIMock() client, mux := setupTest(t)
defer tearDown()
handler.HandleFunc("/v1/domains/search", func(rw http.ResponseWriter, req *http.Request) { mux.HandleFunc("/v1/domains/search", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodGet { if req.Method != http.MethodGet {
http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest) http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest)
return return

View file

@ -12,10 +12,9 @@ import (
) )
func TestTxtRecordService_Create(t *testing.T) { func TestTxtRecordService_Create(t *testing.T) {
client, handler, tearDown := setupAPIMock() client, mux := setupTest(t)
defer tearDown()
handler.HandleFunc("/v1/domains/12345/records/txt", func(rw http.ResponseWriter, req *http.Request) { mux.HandleFunc("/v1/domains/12345/records/txt", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost { if req.Method != http.MethodPost {
http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest) http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest)
return return
@ -48,10 +47,9 @@ func TestTxtRecordService_Create(t *testing.T) {
} }
func TestTxtRecordService_GetAll(t *testing.T) { func TestTxtRecordService_GetAll(t *testing.T) {
client, handler, tearDown := setupAPIMock() client, mux := setupTest(t)
defer tearDown()
handler.HandleFunc("/v1/domains/12345/records/txt", func(rw http.ResponseWriter, req *http.Request) { mux.HandleFunc("/v1/domains/12345/records/txt", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodGet { if req.Method != http.MethodGet {
http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest) http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest)
return return
@ -84,10 +82,9 @@ func TestTxtRecordService_GetAll(t *testing.T) {
} }
func TestTxtRecordService_Get(t *testing.T) { func TestTxtRecordService_Get(t *testing.T) {
client, handler, tearDown := setupAPIMock() client, mux := setupTest(t)
defer tearDown()
handler.HandleFunc("/v1/domains/12345/records/txt/6789", func(rw http.ResponseWriter, req *http.Request) { mux.HandleFunc("/v1/domains/12345/records/txt/6789", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodGet { if req.Method != http.MethodGet {
http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest) http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest)
return return
@ -133,10 +130,9 @@ func TestTxtRecordService_Get(t *testing.T) {
} }
func TestTxtRecordService_Update(t *testing.T) { func TestTxtRecordService_Update(t *testing.T) {
client, handler, tearDown := setupAPIMock() client, mux := setupTest(t)
defer tearDown()
handler.HandleFunc("/v1/domains/12345/records/txt/6789", func(rw http.ResponseWriter, req *http.Request) { mux.HandleFunc("/v1/domains/12345/records/txt/6789", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPut { if req.Method != http.MethodPut {
http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest) http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest)
return return
@ -157,10 +153,9 @@ func TestTxtRecordService_Update(t *testing.T) {
} }
func TestTxtRecordService_Delete(t *testing.T) { func TestTxtRecordService_Delete(t *testing.T) {
client, handler, tearDown := setupAPIMock() client, mux := setupTest(t)
defer tearDown()
handler.HandleFunc("/v1/domains/12345/records/txt/6789", func(rw http.ResponseWriter, req *http.Request) { mux.HandleFunc("/v1/domains/12345/records/txt/6789", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodDelete { if req.Method != http.MethodDelete {
http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest) http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest)
return return
@ -181,10 +176,9 @@ func TestTxtRecordService_Delete(t *testing.T) {
} }
func TestTxtRecordService_Search(t *testing.T) { func TestTxtRecordService_Search(t *testing.T) {
client, handler, tearDown := setupAPIMock() client, mux := setupTest(t)
defer tearDown()
handler.HandleFunc("/v1/domains/12345/records/txt/search", func(rw http.ResponseWriter, req *http.Request) { mux.HandleFunc("/v1/domains/12345/records/txt/search", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodGet { if req.Method != http.MethodGet {
http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest) http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest)
return return

View file

@ -321,7 +321,6 @@ func setupTestProvider(t *testing.T) string {
}) })
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close) t.Cleanup(server.Close)
return server.URL return server.URL

View file

@ -14,20 +14,22 @@ import (
var envTest = tester.NewEnvTest(EnvAuthToken) var envTest = tester.NewEnvTest(EnvAuthToken)
func setupTest() (*DNSProvider, *http.ServeMux, func()) { func setupTest(t *testing.T) (*DNSProvider, *http.ServeMux) {
handler := http.NewServeMux() t.Helper()
server := httptest.NewServer(handler)
mux := http.NewServeMux()
server := httptest.NewServer(mux)
t.Cleanup(server.Close)
config := NewDefaultConfig() config := NewDefaultConfig()
config.AuthToken = "asdf1234" config.AuthToken = "asdf1234"
config.BaseURL = server.URL config.BaseURL = server.URL
config.HTTPClient = server.Client()
provider, err := NewDNSProviderConfig(config) provider, err := NewDNSProviderConfig(config)
if err != nil { require.NoError(t, err)
panic(err)
}
return provider, handler, server.Close return provider, mux
} }
func TestNewDNSProvider(t *testing.T) { func TestNewDNSProvider(t *testing.T) {
@ -108,8 +110,7 @@ func TestNewDNSProviderConfig(t *testing.T) {
} }
func TestDNSProvider_Present(t *testing.T) { func TestDNSProvider_Present(t *testing.T) {
provider, mux, tearDown := setupTest() provider, mux := setupTest(t)
defer tearDown()
mux.HandleFunc("/v2/domains/example.com/records", func(w http.ResponseWriter, r *http.Request) { 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")
@ -147,8 +148,7 @@ func TestDNSProvider_Present(t *testing.T) {
} }
func TestDNSProvider_CleanUp(t *testing.T) { func TestDNSProvider_CleanUp(t *testing.T) {
provider, mux, tearDown := setupTest() provider, mux := setupTest(t)
defer tearDown()
mux.HandleFunc("/v2/domains/example.com/records/1234567", func(w http.ResponseWriter, r *http.Request) { 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")

View file

@ -23,20 +23,22 @@ const (
fakeKeyAuth = "w6uP8Tcg6K2QR905Rms8iXTlksL6OD1KOWBxTK7wxPI" fakeKeyAuth = "w6uP8Tcg6K2QR905Rms8iXTlksL6OD1KOWBxTK7wxPI"
) )
func setupTest() (*DNSProvider, *http.ServeMux, func()) { func setupTest(t *testing.T) (*DNSProvider, *http.ServeMux) {
handler := http.NewServeMux() t.Helper()
server := httptest.NewServer(handler)
mux := http.NewServeMux()
server := httptest.NewServer(mux)
t.Cleanup(server.Close)
config := NewDefaultConfig() config := NewDefaultConfig()
config.APIKey = fakeAPIKey config.APIKey = fakeAPIKey
config.BaseURL = server.URL config.BaseURL = server.URL
config.HTTPClient = server.Client()
provider, err := NewDNSProviderConfig(config) provider, err := NewDNSProviderConfig(config)
if err != nil { require.NoError(t, err)
panic(err)
}
return provider, handler, server.Close return provider, mux
} }
func TestNewDNSProvider(t *testing.T) { func TestNewDNSProvider(t *testing.T) {
@ -113,8 +115,7 @@ func TestNewDNSProviderConfig(t *testing.T) {
} }
func TestDNSProvider_Present(t *testing.T) { func TestDNSProvider_Present(t *testing.T) {
provider, mux, tearDown := setupTest() provider, mux := setupTest(t)
defer tearDown()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodGet, r.Method, "method") assert.Equal(t, http.MethodGet, r.Method, "method")
@ -138,8 +139,7 @@ func TestDNSProvider_Present(t *testing.T) {
} }
func TestDNSProvider_PresentFailed(t *testing.T) { func TestDNSProvider_PresentFailed(t *testing.T) {
provider, mux, tearDown := setupTest() provider, mux := setupTest(t)
defer tearDown()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodGet, r.Method, "method") assert.Equal(t, http.MethodGet, r.Method, "method")
@ -155,8 +155,7 @@ func TestDNSProvider_PresentFailed(t *testing.T) {
} }
func TestDNSProvider_Cleanup(t *testing.T) { func TestDNSProvider_Cleanup(t *testing.T) {
provider, mux, tearDown := setupTest() provider, mux := setupTest(t)
defer tearDown()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodGet, r.Method, "method") assert.Equal(t, http.MethodGet, r.Method, "method")

View file

@ -12,9 +12,12 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
func setupTest(method, pattern string, status int, file string) *Client { func setupTest(t *testing.T, method, pattern string, status int, file string) *Client {
t.Helper()
mux := http.NewServeMux() mux := http.NewServeMux()
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
mux.HandleFunc(pattern, func(rw http.ResponseWriter, req *http.Request) { mux.HandleFunc(pattern, func(rw http.ResponseWriter, req *http.Request) {
if req.Method != method { if req.Method != method {
@ -39,6 +42,7 @@ func setupTest(method, pattern string, status int, file string) *Client {
}) })
client := NewClient() client := NewClient()
client.HTTPClient = server.Client()
client.BaseURL = server.URL client.BaseURL = server.URL
return client return client
@ -90,7 +94,7 @@ func TestGetRootDomain(t *testing.T) {
t.Run(test.desc, func(t *testing.T) { t.Run(test.desc, func(t *testing.T) {
t.Parallel() t.Parallel()
client := setupTest(http.MethodGet, test.pattern, test.status, test.file) client := setupTest(t, http.MethodGet, test.pattern, test.status, test.file)
domain, err := client.GetRootDomain("test.lego.freeddns.org") domain, err := client.GetRootDomain("test.lego.freeddns.org")
@ -179,7 +183,7 @@ func TestGetRecords(t *testing.T) {
t.Run(test.desc, func(t *testing.T) { t.Run(test.desc, func(t *testing.T) {
t.Parallel() t.Parallel()
client := setupTest(http.MethodGet, test.pattern, test.status, test.file) client := setupTest(t, http.MethodGet, test.pattern, test.status, test.file)
records, err := client.GetRecords("_acme-challenge.lego.freeddns.org", "TXT") records, err := client.GetRecords("_acme-challenge.lego.freeddns.org", "TXT")
@ -230,7 +234,7 @@ func TestAddNewRecord(t *testing.T) {
t.Run(test.desc, func(t *testing.T) { t.Run(test.desc, func(t *testing.T) {
t.Parallel() t.Parallel()
client := setupTest(http.MethodPost, test.pattern, test.status, test.file) client := setupTest(t, http.MethodPost, test.pattern, test.status, test.file)
record := DNSRecord{ record := DNSRecord{
Type: "TXT", Type: "TXT",
@ -288,7 +292,7 @@ func TestDeleteRecord(t *testing.T) {
t.Run(test.desc, func(t *testing.T) { t.Run(test.desc, func(t *testing.T) {
t.Parallel() t.Parallel()
client := setupTest(http.MethodDelete, test.pattern, test.status, test.file) client := setupTest(t, http.MethodDelete, test.pattern, test.status, test.file)
err := client.DeleteRecord(9007481, 6041418) err := client.DeleteRecord(9007481, 6041418)

View file

@ -22,26 +22,26 @@ var envTest = tester.NewEnvTest(
EnvKey). EnvKey).
WithDomain(envDomain) WithDomain(envDomain)
func setup() (*DNSProvider, *http.ServeMux, func()) { func setupTest(t *testing.T) (*DNSProvider, *http.ServeMux) {
handler := http.NewServeMux() t.Helper()
server := httptest.NewServer(handler)
mux := http.NewServeMux()
server := httptest.NewServer(mux)
t.Cleanup(server.Close)
endpoint, err := url.Parse(server.URL) endpoint, err := url.Parse(server.URL)
if err != nil { require.NoError(t, err)
panic(err)
}
config := NewDefaultConfig() config := NewDefaultConfig()
config.Token = "TOKEN" config.Token = "TOKEN"
config.Key = "SECRET" config.Key = "SECRET"
config.Endpoint = endpoint config.Endpoint = endpoint
config.HTTPClient = server.Client()
provider, err := NewDNSProviderConfig(config) provider, err := NewDNSProviderConfig(config)
if err != nil { require.NoError(t, err)
panic(err)
}
return provider, handler, server.Close return provider, mux
} }
func TestNewDNSProvider(t *testing.T) { func TestNewDNSProvider(t *testing.T) {
@ -143,8 +143,7 @@ func TestNewDNSProviderConfig(t *testing.T) {
} }
func TestDNSProvider_Present(t *testing.T) { func TestDNSProvider_Present(t *testing.T) {
provider, mux, tearDown := setup() provider, mux := setupTest(t)
defer tearDown()
mux.HandleFunc("/zones/records/add/example.com/TXT", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("/zones/records/add/example.com/TXT", func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodPut, r.Method, "method") assert.Equal(t, http.MethodPut, r.Method, "method")
@ -188,16 +187,14 @@ func TestDNSProvider_Present(t *testing.T) {
} }
func TestDNSProvider_Cleanup_WhenRecordIdNotSet_NoOp(t *testing.T) { func TestDNSProvider_Cleanup_WhenRecordIdNotSet_NoOp(t *testing.T) {
provider, _, tearDown := setup() provider, _ := setupTest(t)
defer tearDown()
err := provider.CleanUp("example.com", "token", "keyAuth") err := provider.CleanUp("example.com", "token", "keyAuth")
require.NoError(t, err) require.NoError(t, err)
} }
func TestDNSProvider_Cleanup_WhenRecordIdSet_DeletesTxtRecord(t *testing.T) { func TestDNSProvider_Cleanup_WhenRecordIdSet_DeletesTxtRecord(t *testing.T) {
provider, mux, tearDown := setup() provider, mux := setupTest(t)
defer tearDown()
mux.HandleFunc("/zones/records/example.com/123456", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("/zones/records/example.com/123456", func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodDelete, r.Method, "method") assert.Equal(t, http.MethodDelete, r.Method, "method")
@ -224,8 +221,7 @@ func TestDNSProvider_Cleanup_WhenRecordIdSet_DeletesTxtRecord(t *testing.T) {
} }
func TestDNSProvider_Cleanup_WhenHttpError_ReturnsError(t *testing.T) { func TestDNSProvider_Cleanup_WhenHttpError_ReturnsError(t *testing.T) {
provider, mux, tearDown := setup() provider, mux := setupTest(t)
defer tearDown()
errorMessage := `{ errorMessage := `{
"error": { "error": {

View file

@ -18,6 +18,7 @@ func setupTest(t *testing.T) (*http.ServeMux, *Client) {
t.Helper() t.Helper()
mux := http.NewServeMux() mux := http.NewServeMux()
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
client := NewClient("secret") client := NewClient("secret")
client.HTTPClient = server.Client() client.HTTPClient = server.Client()

View file

@ -124,7 +124,7 @@ func TestDNSProvider(t *testing.T) {
regexpDate := regexp.MustCompile(`\[ACME Challenge [^\]:]*:[^\]]*\]`) regexpDate := regexp.MustCompile(`\[ACME Challenge [^\]:]*:[^\]]*\]`)
// start fake RPC server // start fake RPC server
fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
require.Equal(t, "text/xml", r.Header.Get("Content-Type"), "invalid content type") require.Equal(t, "text/xml", r.Header.Get("Content-Type"), "invalid content type")
req, errS := io.ReadAll(r.Body) req, errS := io.ReadAll(r.Body)
@ -137,7 +137,7 @@ func TestDNSProvider(t *testing.T) {
_, errS = io.Copy(w, strings.NewReader(resp)) _, errS = io.Copy(w, strings.NewReader(resp))
require.NoError(t, errS) require.NoError(t, errS)
})) }))
defer fakeServer.Close() t.Cleanup(server.Close)
// define function to override findZoneByFqdn with // define function to override findZoneByFqdn with
fakeFindZoneByFqdn := func(fqdn string) (string, error) { fakeFindZoneByFqdn := func(fqdn string) (string, error) {
@ -145,7 +145,7 @@ func TestDNSProvider(t *testing.T) {
} }
config := NewDefaultConfig() config := NewDefaultConfig()
config.BaseURL = fakeServer.URL + "/" config.BaseURL = server.URL + "/"
config.APIKey = "123412341234123412341234" config.APIKey = "123412341234123412341234"
provider, err := NewDNSProviderConfig(config) provider, err := NewDNSProviderConfig(config)
@ -153,9 +153,9 @@ func TestDNSProvider(t *testing.T) {
// override findZoneByFqdn function // override findZoneByFqdn function
savedFindZoneByFqdn := provider.findZoneByFqdn savedFindZoneByFqdn := provider.findZoneByFqdn
defer func() { t.Cleanup(func() {
provider.findZoneByFqdn = savedFindZoneByFqdn provider.findZoneByFqdn = savedFindZoneByFqdn
}() })
provider.findZoneByFqdn = fakeFindZoneByFqdn provider.findZoneByFqdn = fakeFindZoneByFqdn
// run Present // run Present

View file

@ -114,8 +114,8 @@ func TestDNSProvider(t *testing.T) {
regexpToken := regexp.MustCompile(`"rrset_values":\[".+"\]`) regexpToken := regexp.MustCompile(`"rrset_values":\[".+"\]`)
// start fake RPC server // start fake RPC server
handler := http.NewServeMux() mux := http.NewServeMux()
handler.HandleFunc("/domains/example.com/records/_acme-challenge.abc.def/TXT", func(rw http.ResponseWriter, req *http.Request) { mux.HandleFunc("/domains/example.com/records/_acme-challenge.abc.def/TXT", func(rw http.ResponseWriter, req *http.Request) {
log.Infof("request: %s %s", req.Method, req.URL) log.Infof("request: %s %s", req.Method, req.URL)
if req.Header.Get(apiKeyHeader) == "" { if req.Header.Get(apiKeyHeader) == "" {
@ -150,13 +150,13 @@ func TestDNSProvider(t *testing.T) {
return return
} }
}) })
handler.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) { mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
log.Infof("request: %s %s", req.Method, req.URL) log.Infof("request: %s %s", req.Method, req.URL)
http.Error(rw, fmt.Sprintf(`{"message": "URL doesn't match: %s"}`, req.URL), http.StatusNotFound) http.Error(rw, fmt.Sprintf(`{"message": "URL doesn't match: %s"}`, req.URL), http.StatusNotFound)
}) })
server := httptest.NewServer(handler) server := httptest.NewServer(mux)
defer server.Close() t.Cleanup(server.Close)
// define function to override findZoneByFqdn with // define function to override findZoneByFqdn with
fakeFindZoneByFqdn := func(fqdn string) (string, error) { fakeFindZoneByFqdn := func(fqdn string) (string, error) {

View file

@ -206,6 +206,7 @@ func TestPresentNoExistingRR(t *testing.T) {
}) })
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
config := NewDefaultConfig() config := NewDefaultConfig()
config.HTTPClient = &http.Client{} config.HTTPClient = &http.Client{}
@ -306,6 +307,7 @@ func TestPresentWithExistingRR(t *testing.T) {
}) })
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
config := NewDefaultConfig() config := NewDefaultConfig()
config.HTTPClient = &http.Client{} config.HTTPClient = &http.Client{}
@ -369,6 +371,7 @@ func TestPresentSkipExistingRR(t *testing.T) {
}) })
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
config := NewDefaultConfig() config := NewDefaultConfig()
config.HTTPClient = &http.Client{} config.HTTPClient = &http.Client{}

View file

@ -15,6 +15,7 @@ import (
func TestClient_GetTxtRecord(t *testing.T) { func TestClient_GetTxtRecord(t *testing.T) {
mux := http.NewServeMux() mux := http.NewServeMux()
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
const zoneID = "zoneA" const zoneID = "zoneA"
const apiKey = "myKeyA" const apiKey = "myKeyA"
@ -63,6 +64,7 @@ func TestClient_GetTxtRecord(t *testing.T) {
func TestClient_CreateRecord(t *testing.T) { func TestClient_CreateRecord(t *testing.T) {
mux := http.NewServeMux() mux := http.NewServeMux()
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
const zoneID = "zoneA" const zoneID = "zoneA"
const apiKey = "myKeyB" const apiKey = "myKeyB"
@ -111,6 +113,7 @@ func TestClient_CreateRecord(t *testing.T) {
func TestClient_DeleteRecord(t *testing.T) { func TestClient_DeleteRecord(t *testing.T) {
mux := http.NewServeMux() mux := http.NewServeMux()
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
const apiKey = "myKeyC" const apiKey = "myKeyC"
@ -137,6 +140,7 @@ func TestClient_DeleteRecord(t *testing.T) {
func TestClient_GetZoneID(t *testing.T) { func TestClient_GetZoneID(t *testing.T) {
mux := http.NewServeMux() mux := http.NewServeMux()
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
const apiKey = "myKeyD" const apiKey = "myKeyD"
mux.HandleFunc("/api/v1/zones", func(rw http.ResponseWriter, req *http.Request) { mux.HandleFunc("/api/v1/zones", func(rw http.ResponseWriter, req *http.Request) {

View file

@ -158,7 +158,9 @@ func TestNewDNSProvider_Present(t *testing.T) {
mux := http.NewServeMux() mux := http.NewServeMux()
mux.HandleFunc(path.Join("/", test.pathPrefix, "present"), test.handler) mux.HandleFunc(path.Join("/", test.pathPrefix, "present"), test.handler)
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
config := NewDefaultConfig() config := NewDefaultConfig()
config.Endpoint = mustParse(server.URL + test.pathPrefix) config.Endpoint = mustParse(server.URL + test.pathPrefix)
@ -233,7 +235,9 @@ func TestNewDNSProvider_Cleanup(t *testing.T) {
mux := http.NewServeMux() mux := http.NewServeMux()
mux.HandleFunc("/cleanup", test.handler) mux.HandleFunc("/cleanup", test.handler)
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
config := NewDefaultConfig() config := NewDefaultConfig()
config.Endpoint = mustParse(server.URL) config.Endpoint = mustParse(server.URL)

View file

@ -149,6 +149,7 @@ func setupTest(t *testing.T, method, path string, handlers ...assertHandler) *Cl
mux := http.NewServeMux() mux := http.NewServeMux()
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
mux.Handle(path, http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { mux.Handle(path, http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
if req.Method != method { if req.Method != method {
@ -167,8 +168,6 @@ func setupTest(t *testing.T, method, path string, handlers ...assertHandler) *Cl
} }
})) }))
t.Cleanup(server.Close)
passport := &Passport{ passport := &Passport{
SubjectID: "/iam/project/proj123/sa/xxxxxxx", SubjectID: "/iam/project/proj123/sa/xxxxxxx",
} }

View file

@ -17,6 +17,7 @@ import (
func TestClient_FindTXTRecords(t *testing.T) { func TestClient_FindTXTRecords(t *testing.T) {
mux := http.NewServeMux() mux := http.NewServeMux()
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) { mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
query := req.URL.Query() query := req.URL.Query()
@ -257,6 +258,7 @@ func TestClient_DoActions(t *testing.T) {
t.Run(test.desc, func(t *testing.T) { t.Run(test.desc, func(t *testing.T) {
mux := http.NewServeMux() mux := http.NewServeMux()
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) { mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
query, err := url.QueryUnescape(req.URL.RawQuery) query, err := url.QueryUnescape(req.URL.RawQuery)

View file

@ -16,6 +16,7 @@ import (
func TestClient_ListRecords(t *testing.T) { func TestClient_ListRecords(t *testing.T) {
mux := http.NewServeMux() mux := http.NewServeMux()
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
mux.HandleFunc("/123/records/", func(rw http.ResponseWriter, req *http.Request) { mux.HandleFunc("/123/records/", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodGet { if req.Method != http.MethodGet {
@ -50,6 +51,7 @@ func TestClient_ListRecords(t *testing.T) {
func TestClient_ListRecords_error(t *testing.T) { func TestClient_ListRecords_error(t *testing.T) {
mux := http.NewServeMux() mux := http.NewServeMux()
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
mux.HandleFunc("/123/records/", func(rw http.ResponseWriter, req *http.Request) { mux.HandleFunc("/123/records/", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodGet { if req.Method != http.MethodGet {
@ -77,6 +79,7 @@ func TestClient_ListRecords_error(t *testing.T) {
func TestClient_GetDomainByName(t *testing.T) { func TestClient_GetDomainByName(t *testing.T) {
mux := http.NewServeMux() mux := http.NewServeMux()
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
mux.HandleFunc("/sub.sub.example.org", func(rw http.ResponseWriter, req *http.Request) { mux.HandleFunc("/sub.sub.example.org", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodGet { if req.Method != http.MethodGet {
@ -128,6 +131,7 @@ func TestClient_GetDomainByName(t *testing.T) {
func TestClient_AddRecord(t *testing.T) { func TestClient_AddRecord(t *testing.T) {
mux := http.NewServeMux() mux := http.NewServeMux()
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
mux.HandleFunc("/123/records/", func(rw http.ResponseWriter, req *http.Request) { mux.HandleFunc("/123/records/", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost { if req.Method != http.MethodPost {
@ -180,6 +184,7 @@ func TestClient_AddRecord(t *testing.T) {
func TestClient_DeleteRecord(t *testing.T) { func TestClient_DeleteRecord(t *testing.T) {
mux := http.NewServeMux() mux := http.NewServeMux()
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) { mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodDelete { if req.Method != http.MethodDelete {

View file

@ -13,6 +13,7 @@ import (
func TestClient_Send(t *testing.T) { func TestClient_Send(t *testing.T) {
mux := http.NewServeMux() mux := http.NewServeMux()
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) { mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost { if req.Method != http.MethodPost {
@ -47,6 +48,7 @@ func TestClient_Send(t *testing.T) {
func TestClient_Send_empty(t *testing.T) { func TestClient_Send_empty(t *testing.T) {
mux := http.NewServeMux() mux := http.NewServeMux()
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) { mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost { if req.Method != http.MethodPost {

View file

@ -19,8 +19,10 @@ type MockResponseMap map[string]interface{}
var envTest = tester.NewEnvTest(EnvToken) var envTest = tester.NewEnvTest(EnvToken)
func newMockServer(responses MockResponseMap) *httptest.Server { func setupTest(t *testing.T, responses MockResponseMap) string {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { t.Helper()
handler := 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]
@ -51,10 +53,14 @@ func newMockServer(responses MockResponseMap) *httptest.Server {
if err != nil { if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
} }
})) })
server := httptest.NewServer(handler)
t.Cleanup(server.Close)
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
return srv
return server.URL
} }
func TestNewDNSProvider(t *testing.T) { func TestNewDNSProvider(t *testing.T) {
@ -207,11 +213,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) serverURL := setupTest(t, test.mockResponses)
defer server.Close()
assert.NotNil(t, p.client) assert.NotNil(t, p.client)
p.client.SetBaseURL(server.URL) p.client.SetBaseURL(serverURL)
err = p.Present(domain, "", keyAuth) err = p.Present(domain, "", keyAuth)
if test.expectedError == "" { if test.expectedError == "" {
@ -323,10 +328,9 @@ 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) {
server := newMockServer(test.mockResponses) serverURL := setupTest(t, test.mockResponses)
defer server.Close()
p.client.SetBaseURL(server.URL) p.client.SetBaseURL(serverURL)
err = p.CleanUp(domain, "", keyAuth) err = p.CleanUp(domain, "", keyAuth)
if test.expectedError == "" { if test.expectedError == "" {

View file

@ -22,9 +22,12 @@ var envTest = tester.NewEnvTest(
EnvZone). EnvZone).
WithDomain(envDomain) WithDomain(envDomain)
func setupTest() (*DNSProvider, *http.ServeMux, func()) { func setupTest(t *testing.T) (*DNSProvider, *http.ServeMux) {
handler := http.NewServeMux() t.Helper()
server := httptest.NewServer(handler)
mux := http.NewServeMux()
server := httptest.NewServer(mux)
t.Cleanup(server.Close)
config := NewDefaultConfig() config := NewDefaultConfig()
config.Username = "blars" config.Username = "blars"
@ -33,11 +36,9 @@ func setupTest() (*DNSProvider, *http.ServeMux, func()) {
config.Zone = "tacoman.com" config.Zone = "tacoman.com"
provider, err := NewDNSProviderConfig(config) provider, err := NewDNSProviderConfig(config)
if err != nil { require.NoError(t, err)
panic(err)
}
return provider, handler, server.Close return provider, mux
} }
func TestNewDNSProvider(t *testing.T) { func TestNewDNSProvider(t *testing.T) {
@ -173,8 +174,7 @@ func TestNewDNSProviderConfig(t *testing.T) {
} }
func TestDNSProvider_Present(t *testing.T) { func TestDNSProvider_Present(t *testing.T) {
provider, mux, tearDown := setupTest() provider, mux := setupTest(t)
defer tearDown()
mux.HandleFunc("/v1/Network/DNS/Record/create", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("/v1/Network/DNS/Record/create", func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodPost, r.Method) assert.Equal(t, http.MethodPost, r.Method)
@ -221,8 +221,7 @@ func TestDNSProvider_Present(t *testing.T) {
} }
func TestDNSProvider_CleanUp(t *testing.T) { func TestDNSProvider_CleanUp(t *testing.T) {
provider, mux, tearDown := setupTest() provider, mux := setupTest(t)
defer tearDown()
mux.HandleFunc("/v1/Network/DNS/Record/delete", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("/v1/Network/DNS/Record/delete", func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodPost, r.Method) assert.Equal(t, http.MethodPost, r.Method)

View file

@ -304,7 +304,7 @@ func TestUnmarshallFaultyRecordObject(t *testing.T) {
func createFakeServer(t *testing.T, serverResponses map[string]string) string { func createFakeServer(t *testing.T, serverResponses map[string]string) string {
t.Helper() t.Helper()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Content-Type") != "text/xml" { if r.Header.Get("Content-Type") != "text/xml" {
http.Error(w, fmt.Sprintf("invalid content type: %s", r.Header.Get("Content-Type")), http.StatusBadRequest) http.Error(w, fmt.Sprintf("invalid content type: %s", r.Header.Get("Content-Type")), http.StatusBadRequest)
return return
@ -327,8 +327,9 @@ func createFakeServer(t *testing.T, serverResponses map[string]string) string {
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
return return
} }
})) })
server := httptest.NewServer(handler)
t.Cleanup(server.Close) t.Cleanup(server.Close)
return server.URL return server.URL

View file

@ -21,14 +21,12 @@ const (
func TestDNSProvider_getHosts(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) {
serverURL := mockServer(t, &test) p := setupTest(t, &test)
provider := mockDNSProvider(serverURL)
ch, err := newChallenge(test.domain, "") ch, err := newChallenge(test.domain, "")
require.NoError(t, err) require.NoError(t, err)
hosts, err := provider.getHosts(ch.sld, ch.tld) hosts, err := p.getHosts(ch.sld, ch.tld)
if test.errString != "" { if test.errString != "" {
assert.EqualError(t, err, test.errString) assert.EqualError(t, err, test.errString)
} else { } else {
@ -61,14 +59,12 @@ func TestDNSProvider_getHosts(t *testing.T) {
func TestDNSProvider_setHosts(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) {
serverURL := mockServer(t, &test) p := setupTest(t, &test)
prov := mockDNSProvider(serverURL)
ch, err := newChallenge(test.domain, "") ch, err := newChallenge(test.domain, "")
require.NoError(t, err) require.NoError(t, err)
hosts, err := prov.getHosts(ch.sld, ch.tld) hosts, err := p.getHosts(ch.sld, ch.tld)
if test.errString != "" { if test.errString != "" {
assert.EqualError(t, err, test.errString) assert.EqualError(t, err, test.errString)
} else { } else {
@ -78,7 +74,7 @@ func TestDNSProvider_setHosts(t *testing.T) {
return return
} }
err = prov.setHosts(ch.sld, ch.tld, hosts) err = p.setHosts(ch.sld, ch.tld, hosts)
require.NoError(t, err) require.NoError(t, err)
}) })
} }
@ -87,10 +83,9 @@ func TestDNSProvider_setHosts(t *testing.T) {
func TestDNSProvider_Present(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) {
serverURL := mockServer(t, &test) p := setupTest(t, &test)
prov := mockDNSProvider(serverURL) err := p.Present(test.domain, "", "dummyKey")
err := prov.Present(test.domain, "", "dummyKey")
if test.errString != "" { if test.errString != "" {
assert.EqualError(t, err, "namecheap: "+test.errString) assert.EqualError(t, err, "namecheap: "+test.errString)
} else { } else {
@ -103,10 +98,9 @@ func TestDNSProvider_Present(t *testing.T) {
func TestDNSProvider_CleanUp(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) {
serverURL := mockServer(t, &test) p := setupTest(t, &test)
prov := mockDNSProvider(serverURL) err := p.CleanUp(test.domain, "", "dummyKey")
err := prov.CleanUp(test.domain, "", "dummyKey")
if test.errString != "" { if test.errString != "" {
assert.EqualError(t, err, "namecheap: "+test.errString) assert.EqualError(t, err, "namecheap: "+test.errString)
} else { } else {
@ -179,10 +173,10 @@ func assertHdr(t *testing.T, tc *testCase, values *url.Values) {
assert.Equal(t, ch.tld, values.Get("TLD"), "TLD") assert.Equal(t, ch.tld, values.Get("TLD"), "TLD")
} }
func mockServer(t *testing.T, tc *testCase) string { func setupTest(t *testing.T, tc *testCase) *DNSProvider {
t.Helper() t.Helper()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method { switch r.Method {
case http.MethodGet: case http.MethodGet:
values := r.URL.Query() values := r.URL.Query()
@ -216,14 +210,17 @@ func mockServer(t *testing.T, tc *testCase) string {
default: default:
t.Errorf("Unexpected http method: %s", r.Method) t.Errorf("Unexpected http method: %s", r.Method)
} }
})) })
server := httptest.NewServer(handler)
t.Cleanup(server.Close) t.Cleanup(server.Close)
return server.URL return mockDNSProvider(t, server.URL)
} }
func mockDNSProvider(baseURL string) *DNSProvider { func mockDNSProvider(t *testing.T, baseURL string) *DNSProvider {
t.Helper()
config := NewDefaultConfig() config := NewDefaultConfig()
config.BaseURL = baseURL config.BaseURL = baseURL
config.APIUser = envTestUser config.APIUser = envTestUser
@ -232,9 +229,8 @@ func mockDNSProvider(baseURL string) *DNSProvider {
config.HTTPClient = &http.Client{Timeout: 60 * time.Second} config.HTTPClient = &http.Client{Timeout: 60 * time.Second}
provider, err := NewDNSProviderConfig(config) provider, err := NewDNSProviderConfig(config)
if err != nil { require.NoError(t, err)
panic(err)
}
return provider return provider
} }

View file

@ -21,17 +21,20 @@ var envTest = tester.NewEnvTest(
"NETCUP_API_PASSWORD"). "NETCUP_API_PASSWORD").
WithDomain("NETCUP_DOMAIN") WithDomain("NETCUP_DOMAIN")
func setupClientTest() (*Client, *http.ServeMux, func()) { func setupTest(t *testing.T) (*Client, *http.ServeMux) {
handler := http.NewServeMux() t.Helper()
server := httptest.NewServer(handler)
mux := http.NewServeMux()
server := httptest.NewServer(mux)
t.Cleanup(server.Close)
client, err := NewClient("a", "b", "c") client, err := NewClient("a", "b", "c")
if err != nil { require.NoError(t, err)
panic(err)
} client.HTTPClient = server.Client()
client.BaseURL = server.URL client.BaseURL = server.URL
return client, handler, server.Close return client, mux
} }
func TestGetDNSRecordIdx(t *testing.T) { func TestGetDNSRecordIdx(t *testing.T) {
@ -137,8 +140,7 @@ func TestGetDNSRecordIdx(t *testing.T) {
} }
func TestClient_Login(t *testing.T) { func TestClient_Login(t *testing.T) {
client, mux, tearDown := setupClientTest() client, mux := setupTest(t)
defer tearDown()
mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) { mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
raw, err := io.ReadAll(req.Body) raw, err := io.ReadAll(req.Body)
@ -234,8 +236,7 @@ func TestClient_Login_errors(t *testing.T) {
t.Run(test.desc, func(t *testing.T) { t.Run(test.desc, func(t *testing.T) {
t.Parallel() t.Parallel()
client, mux, tearDown := setupClientTest() client, mux := setupTest(t)
defer tearDown()
mux.HandleFunc("/", test.handler) mux.HandleFunc("/", test.handler)
@ -247,8 +248,7 @@ func TestClient_Login_errors(t *testing.T) {
} }
func TestClient_Logout(t *testing.T) { func TestClient_Logout(t *testing.T) {
client, mux, tearDown := setupClientTest() client, mux := setupTest(t)
defer tearDown()
mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) { mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
raw, err := io.ReadAll(req.Body) raw, err := io.ReadAll(req.Body)
@ -319,8 +319,7 @@ func TestClient_Logout_errors(t *testing.T) {
t.Run(test.desc, func(t *testing.T) { t.Run(test.desc, func(t *testing.T) {
t.Parallel() t.Parallel()
client, mux, tearDown := setupClientTest() client, mux := setupTest(t)
defer tearDown()
mux.HandleFunc("/", test.handler) mux.HandleFunc("/", test.handler)
@ -331,8 +330,7 @@ func TestClient_Logout_errors(t *testing.T) {
} }
func TestClient_GetDNSRecords(t *testing.T) { func TestClient_GetDNSRecords(t *testing.T) {
client, mux, tearDown := setupClientTest() client, mux := setupTest(t)
defer tearDown()
mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) { mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
raw, err := io.ReadAll(req.Body) raw, err := io.ReadAll(req.Body)
@ -476,8 +474,7 @@ func TestClient_GetDNSRecords_errors(t *testing.T) {
t.Run(test.desc, func(t *testing.T) { t.Run(test.desc, func(t *testing.T) {
t.Parallel() t.Parallel()
client, mux, tearDown := setupClientTest() client, mux := setupTest(t)
defer tearDown()
mux.HandleFunc("/", test.handler) mux.HandleFunc("/", test.handler)

View file

@ -10,12 +10,24 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
func runTestServer(responseBody string, statusCode int) *httptest.Server { func setupTest(t *testing.T, responseBody string, statusCode int) *Client {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { t.Helper()
handler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(statusCode) w.WriteHeader(statusCode)
fmt.Fprintln(w, responseBody) _, _ = fmt.Fprintln(w, responseBody)
})) })
return server
server := httptest.NewServer(handler)
t.Cleanup(server.Close)
client, err := NewClient("A", "B")
require.NoError(t, err)
client.HTTPClient = server.Client()
client.BaseURL = server.URL
return client
} }
func TestChangeResourceRecordSets(t *testing.T) { func TestChangeResourceRecordSets(t *testing.T) {
@ -28,16 +40,12 @@ func TestChangeResourceRecordSets(t *testing.T) {
</ChangeInfo> </ChangeInfo>
</ChangeResourceRecordSetsResponse> </ChangeResourceRecordSetsResponse>
` `
server := runTestServer(responseBody, http.StatusOK)
defer server.Close()
client, err := NewClient("A", "B") client := setupTest(t, responseBody, http.StatusOK)
require.NoError(t, err)
client.BaseURL = server.URL
res, err := client.ChangeResourceRecordSets("example.com", ChangeResourceRecordSetsRequest{}) res, err := client.ChangeResourceRecordSets("example.com", ChangeResourceRecordSetsRequest{})
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, "xxxxx", res.ChangeInfo.ID) assert.Equal(t, "xxxxx", res.ChangeInfo.ID)
assert.Equal(t, "INSYNC", res.ChangeInfo.Status) assert.Equal(t, "INSYNC", res.ChangeInfo.Status)
assert.Equal(t, "2015-08-05T00:00:00.000Z", res.ChangeInfo.SubmittedAt) assert.Equal(t, "2015-08-05T00:00:00.000Z", res.ChangeInfo.SubmittedAt)
@ -81,13 +89,7 @@ func TestChangeResourceRecordSetsErrors(t *testing.T) {
for _, test := range testCases { for _, test := range testCases {
test := test test := test
t.Run(test.desc, func(t *testing.T) { t.Run(test.desc, func(t *testing.T) {
server := runTestServer(test.responseBody, test.statusCode) client := setupTest(t, test.responseBody, test.statusCode)
defer server.Close()
client, err := NewClient("A", "B")
require.NoError(t, err)
client.BaseURL = server.URL
res, err := client.ChangeResourceRecordSets("example.com", ChangeResourceRecordSetsRequest{}) res, err := client.ChangeResourceRecordSets("example.com", ChangeResourceRecordSetsRequest{})
assert.Nil(t, res) assert.Nil(t, res)
@ -107,16 +109,11 @@ func TestGetChange(t *testing.T) {
</GetChangeResponse> </GetChangeResponse>
` `
server := runTestServer(responseBody, http.StatusOK) client := setupTest(t, responseBody, http.StatusOK)
defer server.Close()
client, err := NewClient("A", "B")
require.NoError(t, err)
client.BaseURL = server.URL
res, err := client.GetChange("12345") res, err := client.GetChange("12345")
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, "xxxxx", res.ChangeInfo.ID) assert.Equal(t, "xxxxx", res.ChangeInfo.ID)
assert.Equal(t, "INSYNC", res.ChangeInfo.Status) assert.Equal(t, "INSYNC", res.ChangeInfo.Status)
assert.Equal(t, "2015-08-05T00:00:00.000Z", res.ChangeInfo.SubmittedAt) assert.Equal(t, "2015-08-05T00:00:00.000Z", res.ChangeInfo.SubmittedAt)
@ -160,13 +157,7 @@ func TestGetChangeErrors(t *testing.T) {
for _, test := range testCases { for _, test := range testCases {
test := test test := test
t.Run(test.desc, func(t *testing.T) { t.Run(test.desc, func(t *testing.T) {
server := runTestServer(test.responseBody, test.statusCode) client := setupTest(t, test.responseBody, test.statusCode)
defer server.Close()
client, err := NewClient("A", "B")
require.NoError(t, err)
client.BaseURL = server.URL
res, err := client.GetChange("12345") res, err := client.GetChange("12345")
assert.Nil(t, res) assert.Nil(t, res)

View file

@ -22,8 +22,7 @@ var envTest = tester.NewEnvTest(
WithDomain(envDomain) WithDomain(envDomain)
func TestNewDNSProviderConfig(t *testing.T) { func TestNewDNSProviderConfig(t *testing.T) {
config, tearDown := setupTest() config := setupTest(t)
defer tearDown()
provider, err := NewDNSProviderConfig(config) provider, err := NewDNSProviderConfig(config)
require.NoError(t, err) require.NoError(t, err)
@ -38,8 +37,7 @@ func TestNewDNSProviderConfig_MissingCredErr(t *testing.T) {
} }
func TestDNSProvider_Present(t *testing.T) { func TestDNSProvider_Present(t *testing.T) {
config, tearDown := setupTest() config := setupTest(t)
defer tearDown()
provider, err := NewDNSProviderConfig(config) provider, err := NewDNSProviderConfig(config)
@ -50,8 +48,7 @@ func TestDNSProvider_Present(t *testing.T) {
} }
func TestDNSProvider_CleanUp(t *testing.T) { func TestDNSProvider_CleanUp(t *testing.T) {
config, tearDown := setupTest() config := setupTest(t)
defer tearDown()
provider, err := NewDNSProviderConfig(config) provider, err := NewDNSProviderConfig(config)
@ -101,25 +98,22 @@ func TestLiveCleanUp(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
} }
func setupTest() (*Config, func()) { func setupTest(t *testing.T) *Config {
apiURL, tearDown := startTestServers() t.Helper()
dnsAPI := httptest.NewServer(dnsHandler())
t.Cleanup(dnsAPI.Close)
identityAPI := httptest.NewServer(identityHandler(dnsAPI.URL + "/123456"))
t.Cleanup(identityAPI.Close)
config := NewDefaultConfig() config := NewDefaultConfig()
config.APIUser = "testUser" config.APIUser = "testUser"
config.APIKey = "testKey" config.APIKey = "testKey"
config.BaseURL = apiURL config.HTTPClient = identityAPI.Client()
config.BaseURL = identityAPI.URL + "/"
return config, tearDown return config
}
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 {

View file

@ -19,10 +19,10 @@ type MockResponse struct {
// MockResponseMap maps request paths to responses. // MockResponseMap maps request paths to responses.
type MockResponseMap map[string]MockResponse type MockResponseMap map[string]MockResponse
func newMockServer(t *testing.T, responses MockResponseMap) string { func setupTest(t *testing.T, responses MockResponseMap) string {
t.Helper() t.Helper()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path path := r.URL.Path
resp, ok := responses[path] resp, ok := responses[path]
if !ok { if !ok {
@ -40,8 +40,9 @@ func newMockServer(t *testing.T, responses MockResponseMap) string {
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
return return
} }
})) })
server := httptest.NewServer(handler)
t.Cleanup(server.Close) t.Cleanup(server.Close)
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)

View file

@ -28,7 +28,9 @@ var envTest = tester.NewEnvTest(
WithDomain(envDomain). WithDomain(envDomain).
WithLiveTestRequirements(EnvAccessKeyID, EnvSecretAccessKey, EnvRegion, envDomain) WithLiveTestRequirements(EnvAccessKeyID, EnvSecretAccessKey, EnvRegion, envDomain)
func makeTestProvider(serverURL string) *DNSProvider { func makeTestProvider(t *testing.T, serverURL string) *DNSProvider {
t.Helper()
config := &aws.Config{ config := &aws.Config{
Credentials: credentials.NewStaticCredentials("abc", "123", " "), Credentials: credentials.NewStaticCredentials("abc", "123", " "),
Endpoint: aws.String(serverURL), Endpoint: aws.String(serverURL),
@ -37,9 +39,7 @@ func makeTestProvider(serverURL string) *DNSProvider {
} }
sess, err := session.NewSession(config) sess, err := session.NewSession(config)
if err != nil { require.NoError(t, err)
panic(err)
}
return &DNSProvider{ return &DNSProvider{
client: route53.New(sess), client: route53.New(sess),
@ -165,11 +165,11 @@ func TestDNSProvider_Present(t *testing.T) {
}, },
} }
serverURL := newMockServer(t, mockResponses) serverURL := setupTest(t, mockResponses)
defer envTest.RestoreEnv() defer envTest.RestoreEnv()
envTest.ClearEnv() envTest.ClearEnv()
provider := makeTestProvider(serverURL) provider := makeTestProvider(t, serverURL)
domain := "example.com" domain := "example.com"
keyAuth := "123456d==" keyAuth := "123456d=="

View file

@ -24,22 +24,26 @@ type apiQuery struct {
} `json:"Filter"` } `json:"Filter"`
} }
func fakeAPIServer(handler func(rw http.ResponseWriter, req *http.Request)) func() { func setupTest(t *testing.T, handler http.HandlerFunc) {
t.Helper()
mux := http.NewServeMux() mux := http.NewServeMux()
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
mux.HandleFunc("/is1a/api/cloud/1.1/commonserviceitem/", handler) mux.HandleFunc("/is1a/api/cloud/1.1/commonserviceitem/", handler)
backup := api.SakuraCloudAPIRoot backup := api.SakuraCloudAPIRoot
api.SakuraCloudAPIRoot = server.URL t.Cleanup(func() {
return func() {
api.SakuraCloudAPIRoot = backup api.SakuraCloudAPIRoot = backup
} })
api.SakuraCloudAPIRoot = server.URL
} }
func TestDNSProvider_addTXTRecord(t *testing.T) { func TestDNSProvider_addTXTRecord(t *testing.T) {
searchResp := &api.SearchDNSResponse{} searchResp := &api.SearchDNSResponse{}
tearDown := fakeAPIServer(func(rw http.ResponseWriter, req *http.Request) {
handler := func(rw http.ResponseWriter, req *http.Request) {
switch req.Method { switch req.Method {
case http.MethodGet: case http.MethodGet:
if len(searchResp.CommonServiceDNSItems) == 0 { if len(searchResp.CommonServiceDNSItems) == 0 {
@ -78,8 +82,9 @@ func TestDNSProvider_addTXTRecord(t *testing.T) {
default: default:
http.Error(rw, "OOPS", http.StatusServiceUnavailable) http.Error(rw, "OOPS", http.StatusServiceUnavailable)
} }
}) }
defer tearDown()
setupTest(t, handler)
config := NewDefaultConfig() config := NewDefaultConfig()
config.Token = "token1" config.Token = "token1"
@ -101,7 +106,7 @@ func TestDNSProvider_addTXTRecord(t *testing.T) {
func TestDNSProvider_cleanupTXTRecord(t *testing.T) { func TestDNSProvider_cleanupTXTRecord(t *testing.T) {
searchResp := &api.SearchDNSResponse{} searchResp := &api.SearchDNSResponse{}
tearDown := fakeAPIServer(func(rw http.ResponseWriter, req *http.Request) { handler := func(rw http.ResponseWriter, req *http.Request) {
switch req.Method { switch req.Method {
case http.MethodGet: case http.MethodGet:
if len(searchResp.CommonServiceDNSItems) == 0 { if len(searchResp.CommonServiceDNSItems) == 0 {
@ -141,8 +146,9 @@ func TestDNSProvider_cleanupTXTRecord(t *testing.T) {
default: default:
http.Error(rw, "OOPS", http.StatusServiceUnavailable) http.Error(rw, "OOPS", http.StatusServiceUnavailable)
} }
}) }
defer tearDown()
setupTest(t, handler)
config := NewDefaultConfig() config := NewDefaultConfig()
config.Token = "token2" config.Token = "token2"
@ -164,7 +170,7 @@ func TestDNSProvider_cleanupTXTRecord(t *testing.T) {
func TestDNSProvider_addTXTRecord_concurrent(t *testing.T) { func TestDNSProvider_addTXTRecord_concurrent(t *testing.T) {
searchResp := &api.SearchDNSResponse{} searchResp := &api.SearchDNSResponse{}
tearDown := fakeAPIServer(func(rw http.ResponseWriter, req *http.Request) { handler := func(rw http.ResponseWriter, req *http.Request) {
switch req.Method { switch req.Method {
case http.MethodGet: case http.MethodGet:
if len(searchResp.CommonServiceDNSItems) == 0 { if len(searchResp.CommonServiceDNSItems) == 0 {
@ -203,8 +209,9 @@ func TestDNSProvider_addTXTRecord_concurrent(t *testing.T) {
default: default:
http.Error(rw, "OOPS", http.StatusServiceUnavailable) http.Error(rw, "OOPS", http.StatusServiceUnavailable)
} }
}) }
defer tearDown()
setupTest(t, handler)
dummyRecordCount := 10 dummyRecordCount := 10
@ -251,7 +258,7 @@ func TestDNSProvider_cleanupTXTRecord_concurrent(t *testing.T) {
searchResp := &api.SearchDNSResponse{CommonServiceDNSItems: []sacloud.DNS{*baseFakeZone}} searchResp := &api.SearchDNSResponse{CommonServiceDNSItems: []sacloud.DNS{*baseFakeZone}}
tearDown := fakeAPIServer(func(rw http.ResponseWriter, req *http.Request) { handler := func(rw http.ResponseWriter, req *http.Request) {
switch req.Method { switch req.Method {
case http.MethodGet: case http.MethodGet:
if err := json.NewEncoder(rw).Encode(searchResp); err != nil { if err := json.NewEncoder(rw).Encode(searchResp); err != nil {
@ -279,8 +286,9 @@ func TestDNSProvider_cleanupTXTRecord_concurrent(t *testing.T) {
default: default:
http.Error(rw, "OOPS", http.StatusServiceUnavailable) http.Error(rw, "OOPS", http.StatusServiceUnavailable)
} }
}) }
defer tearDown()
setupTest(t, handler)
fakeZone := sacloud.CreateNewDNS("example.com") fakeZone := sacloud.CreateNewDNS("example.com")
fakeZone.ID = 123456789012 fakeZone.ID = 123456789012

View file

@ -12,19 +12,21 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
func setupAPIMock() (*Client, *http.ServeMux, func()) { func setupTest(t *testing.T) (*Client, *http.ServeMux) {
handler := http.NewServeMux() t.Helper()
svr := httptest.NewServer(handler)
mux := http.NewServeMux()
server := httptest.NewServer(mux)
t.Cleanup(server.Close)
client := NewClient("", "") client := NewClient("", "")
client.BaseURL = svr.URL client.BaseURL = server.URL
return client, handler, svr.Close return client, mux
} }
func TestClient_GetRecords(t *testing.T) { func TestClient_GetRecords(t *testing.T) {
client, handler, tearDown := setupAPIMock() client, handler := setupTest(t)
defer tearDown()
handler.HandleFunc("/lego.wtf", func(rw http.ResponseWriter, req *http.Request) { handler.HandleFunc("/lego.wtf", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodGet { if req.Method != http.MethodGet {
@ -59,8 +61,7 @@ func TestClient_GetRecords(t *testing.T) {
} }
func TestClient_GetRecords_error(t *testing.T) { func TestClient_GetRecords_error(t *testing.T) {
client, handler, tearDown := setupAPIMock() client, handler := setupTest(t)
defer tearDown()
handler.HandleFunc("/lego.wtf", func(rw http.ResponseWriter, req *http.Request) { handler.HandleFunc("/lego.wtf", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodGet { if req.Method != http.MethodGet {
@ -82,8 +83,7 @@ func TestClient_GetRecords_error(t *testing.T) {
} }
func TestClient_CreateUpdateRecord(t *testing.T) { func TestClient_CreateUpdateRecord(t *testing.T) {
client, handler, tearDown := setupAPIMock() client, handler := setupTest(t)
defer tearDown()
handler.HandleFunc("/lego.wtf", func(rw http.ResponseWriter, req *http.Request) { handler.HandleFunc("/lego.wtf", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost { if req.Method != http.MethodPost {
@ -126,8 +126,7 @@ func TestClient_CreateUpdateRecord(t *testing.T) {
} }
func TestClient_CreateUpdateRecord_error(t *testing.T) { func TestClient_CreateUpdateRecord_error(t *testing.T) {
client, handler, tearDown := setupAPIMock() client, handler := setupTest(t)
defer tearDown()
handler.HandleFunc("/lego.wtf", func(rw http.ResponseWriter, req *http.Request) { handler.HandleFunc("/lego.wtf", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost { if req.Method != http.MethodPost {
@ -153,8 +152,7 @@ func TestClient_CreateUpdateRecord_error(t *testing.T) {
} }
func TestClient_DeleteRecord(t *testing.T) { func TestClient_DeleteRecord(t *testing.T) {
client, handler, tearDown := setupAPIMock() client, handler := setupTest(t)
defer tearDown()
handler.HandleFunc("/lego.wtf", func(rw http.ResponseWriter, req *http.Request) { handler.HandleFunc("/lego.wtf", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodDelete { if req.Method != http.MethodDelete {
@ -195,8 +193,7 @@ func TestClient_DeleteRecord(t *testing.T) {
} }
func TestClient_DeleteRecord_error(t *testing.T) { func TestClient_DeleteRecord_error(t *testing.T) {
client, handler, tearDown := setupAPIMock() client, handler := setupTest(t)
defer tearDown()
handler.HandleFunc("/lego.wtf", func(rw http.ResponseWriter, req *http.Request) { handler.HandleFunc("/lego.wtf", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodDelete { if req.Method != http.MethodDelete {

View file

@ -135,9 +135,12 @@ func TestNewDNSProviderConfig(t *testing.T) {
} }
} }
func setupMockAPITest() (*DNSProvider, *http.ServeMux, func()) { func setupTest(t *testing.T) (*DNSProvider, *http.ServeMux) {
apiHandler := http.NewServeMux() t.Helper()
server := httptest.NewServer(apiHandler)
mux := http.NewServeMux()
server := httptest.NewServer(mux)
t.Cleanup(server.Close)
config := NewDefaultConfig() config := NewDefaultConfig()
config.ClientID = "CLIENT_ID" config.ClientID = "CLIENT_ID"
@ -145,19 +148,16 @@ func setupMockAPITest() (*DNSProvider, *http.ServeMux, func()) {
config.StackID = "STACK_ID" config.StackID = "STACK_ID"
provider, err := NewDNSProviderConfig(config) provider, err := NewDNSProviderConfig(config)
if err != nil { require.NoError(t, err)
panic(err)
}
provider.client = http.DefaultClient provider.client = http.DefaultClient
provider.BaseURL, _ = url.Parse(server.URL + "/") provider.BaseURL, _ = url.Parse(server.URL + "/")
return provider, apiHandler, server.Close return provider, mux
} }
func TestDNSProvider_getZoneRecords(t *testing.T) { func TestDNSProvider_getZoneRecords(t *testing.T) {
provider, mux, tearDown := setupMockAPITest() provider, mux := setupTest(t)
defer tearDown()
mux.HandleFunc("/STACK_ID/zones/A/records", func(w http.ResponseWriter, _ *http.Request) { mux.HandleFunc("/STACK_ID/zones/A/records", func(w http.ResponseWriter, _ *http.Request) {
content := ` content := `
@ -187,8 +187,7 @@ func TestDNSProvider_getZoneRecords(t *testing.T) {
} }
func TestDNSProvider_getZoneRecords_apiError(t *testing.T) { func TestDNSProvider_getZoneRecords_apiError(t *testing.T) {
provider, mux, tearDown := setupMockAPITest() provider, mux := setupTest(t)
defer tearDown()
mux.HandleFunc("/STACK_ID/zones/A/records", func(w http.ResponseWriter, _ *http.Request) { mux.HandleFunc("/STACK_ID/zones/A/records", func(w http.ResponseWriter, _ *http.Request) {
content := ` content := `
@ -212,8 +211,7 @@ func TestDNSProvider_getZoneRecords_apiError(t *testing.T) {
} }
func TestDNSProvider_getZones(t *testing.T) { func TestDNSProvider_getZones(t *testing.T) {
provider, mux, tearDown := setupMockAPITest() provider, mux := setupTest(t)
defer tearDown()
mux.HandleFunc("/STACK_ID/zones", func(w http.ResponseWriter, _ *http.Request) { mux.HandleFunc("/STACK_ID/zones", func(w http.ResponseWriter, _ *http.Request) {
content := ` content := `

View file

@ -28,8 +28,7 @@ func TestDNSProvider_TimeoutSuccess(t *testing.T) {
defer envTest.RestoreEnv() defer envTest.RestoreEnv()
envTest.ClearEnv() envTest.ClearEnv()
tearDown := startTestServer(muxSuccess()) setupTest(t, muxSuccess())
defer tearDown()
provider, err := NewDNSProvider() provider, err := NewDNSProvider()
require.NoError(t, err) require.NoError(t, err)
@ -66,8 +65,7 @@ func TestDNSProvider_Present(t *testing.T) {
defer envTest.RestoreEnv() defer envTest.RestoreEnv()
envTest.ClearEnv() envTest.ClearEnv()
tearDown := startTestServer(test.handler) setupTest(t, test.handler)
defer tearDown()
provider, err := NewDNSProvider() provider, err := NewDNSProvider()
require.NoError(t, err) require.NoError(t, err)
@ -109,8 +107,7 @@ func TestDNSProvider_CleanUp(t *testing.T) {
defer envTest.RestoreEnv() defer envTest.RestoreEnv()
envTest.ClearEnv() envTest.ClearEnv()
tearDown := startTestServer(test.handler) setupTest(t, test.handler)
defer tearDown()
provider, err := NewDNSProvider() provider, err := NewDNSProvider()
require.NoError(t, err) require.NoError(t, err)
@ -273,16 +270,15 @@ func muxFailToGetRecordID() *http.ServeMux {
return mux return mux
} }
func startTestServer(handler http.Handler) func() { func setupTest(t *testing.T, mux http.Handler) {
ts := httptest.NewServer(handler) t.Helper()
server := httptest.NewServer(mux)
t.Cleanup(server.Close)
envTest.Apply(map[string]string{ envTest.Apply(map[string]string{
EnvKey: "key", EnvKey: "key",
EnvSecret: "secret", EnvSecret: "secret",
EnvURL: ts.URL, EnvURL: server.URL,
}) })
return func() {
ts.Close()
}
} }

View file

@ -148,8 +148,7 @@ func TestDNSProvider_Present(t *testing.T) {
defer envTest.RestoreEnv() defer envTest.RestoreEnv()
envTest.ClearEnv() envTest.ClearEnv()
baseURL, tearDown := startTestServer(test.handler) baseURL := setupTest(t, test.handler)
defer tearDown()
envTest.Apply(map[string]string{ envTest.Apply(map[string]string{
EnvUsername: "me@example.com", EnvUsername: "me@example.com",
@ -191,8 +190,7 @@ func TestDNSProvider_CleanUp(t *testing.T) {
defer envTest.RestoreEnv() defer envTest.RestoreEnv()
envTest.ClearEnv() envTest.ClearEnv()
baseURL, tearDown := startTestServer(test.handler) baseURL := setupTest(t, test.handler)
defer tearDown()
envTest.Apply(map[string]string{ envTest.Apply(map[string]string{
EnvUsername: "me@example.com", EnvUsername: "me@example.com",
@ -272,11 +270,13 @@ func muxFailToCreateTXT() *http.ServeMux {
return mux return mux
} }
func startTestServer(handler http.Handler) (string, func()) { func setupTest(t *testing.T, handler http.Handler) string {
ts := httptest.NewServer(handler) t.Helper()
return ts.URL, func() {
ts.Close() server := httptest.NewServer(handler)
} t.Cleanup(server.Close)
return server.URL
} }
func TestLivePresent(t *testing.T) { func TestLivePresent(t *testing.T) {

View file

@ -10,17 +10,20 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
func setupClientTest() (*http.ServeMux, *Client, func()) { func setupTest(t *testing.T) (*http.ServeMux, *Client) {
t.Helper()
mux := http.NewServeMux() mux := http.NewServeMux()
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
client, err := NewClient("lego") client, err := NewClient("lego")
if err != nil { require.NoError(t, err)
panic(err)
}
client.HTTPClient = server.Client()
client.BaseURL = server.URL client.BaseURL = server.URL
return mux, client, server.Close
return mux, client
} }
func TestAddRecord(t *testing.T) { func TestAddRecord(t *testing.T) {
@ -107,8 +110,7 @@ func TestAddRecord(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) {
mux, client, tearDown := setupClientTest() mux, client := setupTest(t)
defer tearDown()
mux.HandleFunc("/add", test.handler) mux.HandleFunc("/add", test.handler)
@ -195,8 +197,7 @@ func TestRemoveRecord(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) {
mux, client, tearDown := setupClientTest() mux, client := setupTest(t)
defer tearDown()
mux.HandleFunc("/del", test.handler) mux.HandleFunc("/del", test.handler)
@ -287,8 +288,7 @@ func TestGetRecords(t *testing.T) {
test := test test := test
t.Run(test.desc, func(t *testing.T) { t.Run(test.desc, func(t *testing.T) {
t.Parallel() t.Parallel()
mux, client, tearDown := setupClientTest() mux, client := setupTest(t)
defer tearDown()
mux.HandleFunc("/list", test.handler) mux.HandleFunc("/list", test.handler)

View file

@ -186,6 +186,7 @@ func TestDNSProvider_Present(t *testing.T) {
} }
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
config := NewDefaultConfig() config := NewDefaultConfig()
config.Endpoint = mustParse(server.URL) config.Endpoint = mustParse(server.URL)
@ -276,6 +277,7 @@ func TestDNSProvider_Cleanup(t *testing.T) {
} }
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close)
config := NewDefaultConfig() config := NewDefaultConfig()
config.Endpoint = mustParse(server.URL) config.Endpoint = mustParse(server.URL)

View file

@ -14,8 +14,7 @@ import (
) )
func TestRegistrar_ResolveAccountByKey(t *testing.T) { func TestRegistrar_ResolveAccountByKey(t *testing.T) {
mux, apiURL, tearDown := tester.SetupFakeAPI() mux, apiURL := tester.SetupFakeAPI(t)
defer tearDown()
mux.HandleFunc("/account", func(w http.ResponseWriter, _ *http.Request) { mux.HandleFunc("/account", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Location", apiURL+"/account") w.Header().Set("Location", apiURL+"/account")