diff --git a/acme/api/certificate_test.go b/acme/api/certificate_test.go index 9cdd2772..0d8911b8 100644 --- a/acme/api/certificate_test.go +++ b/acme/api/certificate_test.go @@ -74,8 +74,7 @@ rzFL1KZfz+HZdnFwFW2T2gVW8L3ii1l9AJDuKzlvjUH3p6bgihVq02sjT8mx+GM2 ` func TestCertificateService_Get_issuerRelUp(t *testing.T) { - mux, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() + mux, apiURL := tester.SetupFakeAPI(t) mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) { 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) { - mux, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() + mux, apiURL := tester.SetupFakeAPI(t) mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) { _, err := w.Write([]byte(certResponseMock)) diff --git a/acme/api/internal/nonces/nonce_manager_test.go b/acme/api/internal/nonces/nonce_manager_test.go index 63514ba2..905864ff 100644 --- a/acme/api/internal/nonces/nonce_manager_test.go +++ b/acme/api/internal/nonces/nonce_manager_test.go @@ -12,7 +12,7 @@ import ( ) 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) w.Header().Set("Replay-Nonce", "12345") w.Header().Set("Retry-After", "0") @@ -22,10 +22,10 @@ func TestNotHoldingLockWhileMakingHTTPRequests(t *testing.T) { return } })) - defer ts.Close() + t.Cleanup(server.Close) doer := sender.NewDoer(http.DefaultClient, "lego-test") - j := NewManager(doer, ts.URL) + j := NewManager(doer, server.URL) ch := make(chan bool) resultCh := make(chan bool) go func() { diff --git a/acme/api/internal/secure/jws_test.go b/acme/api/internal/secure/jws_test.go index 4c375b80..c09a8433 100644 --- a/acme/api/internal/secure/jws_test.go +++ b/acme/api/internal/secure/jws_test.go @@ -13,7 +13,7 @@ import ( ) 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) w.Header().Set("Replay-Nonce", "12345") w.Header().Set("Retry-After", "0") @@ -23,10 +23,10 @@ func TestNotHoldingLockWhileMakingHTTPRequests(t *testing.T) { return } })) - defer ts.Close() + t.Cleanup(server.Close) doer := sender.NewDoer(http.DefaultClient, "lego-test") - j := nonces.NewManager(doer, ts.URL) + j := nonces.NewManager(doer, server.URL) ch := make(chan bool) resultCh := make(chan bool) go func() { diff --git a/acme/api/internal/sender/sender_test.go b/acme/api/internal/sender/sender_test.go index 1a6d980e..2fd43c87 100644 --- a/acme/api/internal/sender/sender_test.go +++ b/acme/api/internal/sender/sender_test.go @@ -12,11 +12,11 @@ import ( func TestDo_UserAgentOnAllHTTPMethod(t *testing.T) { 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") method = r.Method })) - defer ts.Close() + t.Cleanup(server.Close) doer := NewDoer(http.DefaultClient, "") @@ -44,7 +44,7 @@ func TestDo_UserAgentOnAllHTTPMethod(t *testing.T) { for _, test := range testCases { t.Run(test.method, func(t *testing.T) { - _, err := test.call(ts.URL) + _, err := test.call(server.URL) require.NoError(t, err) assert.Equal(t, test.method, method) diff --git a/acme/api/order_test.go b/acme/api/order_test.go index 13211798..9f93b047 100644 --- a/acme/api/order_test.go +++ b/acme/api/order_test.go @@ -16,8 +16,7 @@ import ( ) func TestOrderService_New(t *testing.T) { - mux, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() + mux, apiURL := tester.SetupFakeAPI(t) // small value keeps test fast privateKey, errK := rsa.GenerateKey(rand.Reader, 512) diff --git a/certificate/certificates_test.go b/certificate/certificates_test.go index be75239f..73d7b430 100644 --- a/certificate/certificates_test.go +++ b/certificate/certificates_test.go @@ -154,8 +154,7 @@ Ob8VZRzI9neWagqNdwvYkQsEjgfbKbYK7p2CNTUQ ` func Test_checkResponse(t *testing.T) { - mux, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() + mux, apiURL := tester.SetupFakeAPI(t) mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) { _, err := w.Write([]byte(certResponseMock)) @@ -195,8 +194,7 @@ func Test_checkResponse(t *testing.T) { } func Test_checkResponse_issuerRelUp(t *testing.T) { - mux, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() + mux, apiURL := tester.SetupFakeAPI(t) mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) { 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) { - mux, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() + mux, apiURL := tester.SetupFakeAPI(t) mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) { _, err := w.Write([]byte(certResponseMock)) @@ -286,8 +283,7 @@ func Test_checkResponse_embeddedIssuer(t *testing.T) { } func Test_checkResponse_alternate(t *testing.T) { - mux, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() + mux, apiURL := tester.SetupFakeAPI(t) mux.HandleFunc("/certificate", func(w http.ResponseWriter, _ *http.Request) { 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) { - mux, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() + mux, apiURL := tester.SetupFakeAPI(t) mux.HandleFunc("/acme/cert/test-cert", func(w http.ResponseWriter, _ *http.Request) { _, err := w.Write([]byte(certResponseMock)) diff --git a/challenge/dns01/dns_challenge_test.go b/challenge/dns01/dns_challenge_test.go index 953b8b59..95318032 100644 --- a/challenge/dns01/dns_challenge_test.go +++ b/challenge/dns01/dns_challenge_test.go @@ -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 TestChallenge_PreSolve(t *testing.T) { - _, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() + _, apiURL := tester.SetupFakeAPI(t) privateKey, err := rsa.GenerateKey(rand.Reader, 512) require.NoError(t, err) @@ -115,8 +114,7 @@ func TestChallenge_PreSolve(t *testing.T) { } func TestChallenge_Solve(t *testing.T) { - _, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() + _, apiURL := tester.SetupFakeAPI(t) privateKey, err := rsa.GenerateKey(rand.Reader, 512) require.NoError(t, err) @@ -203,8 +201,7 @@ func TestChallenge_Solve(t *testing.T) { } func TestChallenge_CleanUp(t *testing.T) { - _, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() + _, apiURL := tester.SetupFakeAPI(t) privateKey, err := rsa.GenerateKey(rand.Reader, 512) require.NoError(t, err) diff --git a/challenge/http01/http_challenge_test.go b/challenge/http01/http_challenge_test.go index 62bf3abc..9866b2c1 100644 --- a/challenge/http01/http_challenge_test.go +++ b/challenge/http01/http_challenge_test.go @@ -18,8 +18,7 @@ import ( ) func TestChallenge(t *testing.T) { - _, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() + _, apiURL := tester.SetupFakeAPI(t) providerServer := NewProviderServer("", "23457") @@ -71,8 +70,7 @@ func TestChallenge(t *testing.T) { } func TestChallengeInvalidPort(t *testing.T) { - _, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() + _, apiURL := tester.SetupFakeAPI(t) privateKey, err := rsa.GenerateKey(rand.Reader, 128) 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) { t.Helper() - _, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() + _, apiURL := tester.SetupFakeAPI(t) providerServer := NewProviderServer("localhost", "23457") if header != nil { diff --git a/challenge/resolver/solver_manager_test.go b/challenge/resolver/solver_manager_test.go index 94085237..1b5a93d3 100644 --- a/challenge/resolver/solver_manager_test.go +++ b/challenge/resolver/solver_manager_test.go @@ -32,8 +32,7 @@ func TestByType(t *testing.T) { } func TestValidate(t *testing.T) { - mux, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() + mux, apiURL := tester.SetupFakeAPI(t) var statuses []string diff --git a/challenge/tlsalpn01/tls_alpn_challenge_test.go b/challenge/tlsalpn01/tls_alpn_challenge_test.go index 9bfe9366..4bfb47bf 100644 --- a/challenge/tlsalpn01/tls_alpn_challenge_test.go +++ b/challenge/tlsalpn01/tls_alpn_challenge_test.go @@ -19,8 +19,7 @@ import ( ) func TestChallenge(t *testing.T) { - _, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() + _, apiURL := tester.SetupFakeAPI(t) domain := "localhost:23457" @@ -89,8 +88,7 @@ func TestChallenge(t *testing.T) { } func TestChallengeInvalidPort(t *testing.T) { - _, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() + _, apiURL := tester.SetupFakeAPI(t) privateKey, err := rsa.GenerateKey(rand.Reader, 128) require.NoError(t, err, "Could not generate test key") diff --git a/lego/client_test.go b/lego/client_test.go index 36d43c96..7d2f514d 100644 --- a/lego/client_test.go +++ b/lego/client_test.go @@ -13,8 +13,7 @@ import ( ) func TestNewClient(t *testing.T) { - _, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() + _, apiURL := tester.SetupFakeAPI(t) keyBits := 32 // small value keeps test fast key, err := rsa.GenerateKey(rand.Reader, keyBits) diff --git a/platform/tester/api.go b/platform/tester/api.go index 8a7c4f12..97942750 100644 --- a/platform/tester/api.go +++ b/platform/tester/api.go @@ -4,14 +4,18 @@ import ( "encoding/json" "net/http" "net/http/httptest" + "testing" "github.com/go-acme/lego/v4/acme" ) // 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() - ts := httptest.NewServer(mux) + server := httptest.NewServer(mux) + t.Cleanup(server.Close) mux.HandleFunc("/dir", func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { @@ -20,11 +24,11 @@ func SetupFakeAPI() (*http.ServeMux, string, func()) { } err := WriteJSONResponse(w, acme.Directory{ - NewNonceURL: ts.URL + "/nonce", - NewAccountURL: ts.URL + "/account", - NewOrderURL: ts.URL + "/newOrder", - RevokeCertURL: ts.URL + "/revokeCert", - KeyChangeURL: ts.URL + "/keyChange", + NewNonceURL: server.URL + "/nonce", + NewAccountURL: server.URL + "/account", + NewOrderURL: server.URL + "/newOrder", + RevokeCertURL: server.URL + "/revokeCert", + KeyChangeURL: server.URL + "/keyChange", }) 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. diff --git a/providers/dns/arvancloud/internal/client_test.go b/providers/dns/arvancloud/internal/client_test.go index 3dfbef7a..f21311ae 100644 --- a/providers/dns/arvancloud/internal/client_test.go +++ b/providers/dns/arvancloud/internal/client_test.go @@ -15,6 +15,7 @@ import ( func TestClient_GetTxtRecord(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) + t.Cleanup(server.Close) const domain = "example.com" const apiKey = "myKeyA" @@ -55,6 +56,7 @@ func TestClient_GetTxtRecord(t *testing.T) { func TestClient_CreateRecord(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) + t.Cleanup(server.Close) const domain = "example.com" const apiKey = "myKeyB" @@ -119,6 +121,7 @@ func TestClient_CreateRecord(t *testing.T) { func TestClient_DeleteRecord(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) + t.Cleanup(server.Close) const domain = "example.com" const apiKey = "myKeyC" diff --git a/providers/dns/auroradns/auroradns_test.go b/providers/dns/auroradns/auroradns_test.go index 9c453e48..0a26b2ef 100644 --- a/providers/dns/auroradns/auroradns_test.go +++ b/providers/dns/auroradns/auroradns_test.go @@ -16,9 +16,12 @@ var envTest = tester.NewEnvTest( EnvUserID, EnvKey) -func setupTest() (*DNSProvider, *http.ServeMux, func()) { - handler := http.NewServeMux() - server := httptest.NewServer(handler) +func setupTest(t *testing.T) (*DNSProvider, *http.ServeMux) { + t.Helper() + + mux := http.NewServeMux() + server := httptest.NewServer(mux) + t.Cleanup(server.Close) config := NewDefaultConfig() config.UserID = "asdf1234" @@ -26,11 +29,9 @@ func setupTest() (*DNSProvider, *http.ServeMux, func()) { config.BaseURL = server.URL provider, err := NewDNSProviderConfig(config) - if err != nil { - panic(err) - } + require.NoError(t, err) - return provider, handler, server.Close + return provider, mux } func TestNewDNSProvider(t *testing.T) { @@ -146,8 +147,7 @@ func TestNewDNSProviderConfig(t *testing.T) { } func TestDNSProvider_Present(t *testing.T) { - provider, mux, tearDown := setupTest() - defer tearDown() + provider, mux := setupTest(t) mux.HandleFunc("/zones", func(w http.ResponseWriter, r *http.Request) { assert.Equal(t, http.MethodGet, r.Method, "method") @@ -181,8 +181,7 @@ func TestDNSProvider_Present(t *testing.T) { } func TestDNSProvider_CleanUp(t *testing.T) { - provider, mux, tearDown := setupTest() - defer tearDown() + provider, mux := setupTest(t) mux.HandleFunc("/zones", func(w http.ResponseWriter, r *http.Request) { assert.Equal(t, http.MethodGet, r.Method) diff --git a/providers/dns/azure/azure_test.go b/providers/dns/azure/azure_test.go index 18803a89..5fcbd94b 100644 --- a/providers/dns/azure/azure_test.go +++ b/providers/dns/azure/azure_test.go @@ -132,13 +132,14 @@ func TestNewDNSProviderConfig(t *testing.T) { config.TenantID = test.tenantID config.ResourceGroup = test.resourceGroup - handler := http.NewServeMux() - server := httptest.NewServer(handler) - defer server.Close() + mux := http.NewServeMux() + server := httptest.NewServer(mux) + t.Cleanup(server.Close) + if test.handler == nil { - handler.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {}) + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {}) } else { - handler.HandleFunc("/", test.handler) + mux.HandleFunc("/", test.handler) } config.MetadataEndpoint = server.URL diff --git a/providers/dns/checkdomain/client_test.go b/providers/dns/checkdomain/client_test.go index 959c3e08..9f13256f 100644 --- a/providers/dns/checkdomain/client_test.go +++ b/providers/dns/checkdomain/client_test.go @@ -18,19 +18,18 @@ import ( func setupTestProvider(t *testing.T) (*DNSProvider, *http.ServeMux) { t.Helper() - handler := http.NewServeMux() - svr := httptest.NewServer(handler) - - t.Cleanup(svr.Close) + mux := http.NewServeMux() + server := httptest.NewServer(mux) + t.Cleanup(server.Close) config := NewDefaultConfig() - config.Endpoint, _ = url.Parse(svr.URL) + config.Endpoint, _ = url.Parse(server.URL) config.Token = "secret" - prd, err := NewDNSProviderConfig(config) + p, err := NewDNSProviderConfig(config) require.NoError(t, err) - return prd, handler + return p, mux } func Test_getDomainIDByName(t *testing.T) { diff --git a/providers/dns/clouddns/internal/client_test.go b/providers/dns/clouddns/internal/client_test.go index b06637b0..68f500d8 100644 --- a/providers/dns/clouddns/internal/client_test.go +++ b/providers/dns/clouddns/internal/client_test.go @@ -46,9 +46,7 @@ func TestClient_AddRecord(t *testing.T) { }) server := httptest.NewServer(mux) - t.Cleanup(func() { - server.Close() - }) + t.Cleanup(server.Close) client := NewClient("clientID", "email@example.com", "secret", 300) client.apiBaseURL = server.URL + "/api" @@ -117,9 +115,7 @@ func TestClient_DeleteRecord(t *testing.T) { }) server := httptest.NewServer(mux) - t.Cleanup(func() { - server.Close() - }) + t.Cleanup(server.Close) client := NewClient("clientID", "email@example.com", "secret", 300) client.apiBaseURL = server.URL + "/api" diff --git a/providers/dns/cloudns/internal/client_test.go b/providers/dns/cloudns/internal/client_test.go index 5731833c..8a9c53b9 100644 --- a/providers/dns/cloudns/internal/client_test.go +++ b/providers/dns/cloudns/internal/client_test.go @@ -456,6 +456,7 @@ func TestClient_AddTxtRecord(t *testing.T) { handlerMock(http.MethodPost, []byte(test.apiResponse))(rw, req) })) + t.Cleanup(server.Close) client, err := NewClient(test.authID, test.subAuthID, "myAuthPassword") require.NoError(t, err) diff --git a/providers/dns/cloudxns/internal/client_test.go b/providers/dns/cloudxns/internal/client_test.go index dbf5de49..618ac027 100644 --- a/providers/dns/cloudxns/internal/client_test.go +++ b/providers/dns/cloudxns/internal/client_test.go @@ -107,6 +107,7 @@ func TestClientGetDomainInformation(t *testing.T) { for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { server := httptest.NewServer(handlerMock(http.MethodGet, test.response, test.data)) + t.Cleanup(server.Close) client, _ := NewClient("myKey", "mySecret") client.BaseURL = server.URL + "/" @@ -210,6 +211,7 @@ func TestClientFindTxtRecord(t *testing.T) { for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { server := httptest.NewServer(handlerMock(http.MethodGet, test.response, test.txtRecords)) + t.Cleanup(server.Close) client, _ := NewClient("myKey", "mySecret") client.BaseURL = server.URL + "/" @@ -274,6 +276,7 @@ func TestClientAddTxtRecord(t *testing.T) { handlerMock(http.MethodPost, response, nil).ServeHTTP(rw, req) })) + t.Cleanup(server.Close) client, _ := NewClient("myKey", "mySecret") client.BaseURL = server.URL + "/" diff --git a/providers/dns/conoha/internal/client_test.go b/providers/dns/conoha/internal/client_test.go index 46c98005..44f16b1c 100644 --- a/providers/dns/conoha/internal/client_test.go +++ b/providers/dns/conoha/internal/client_test.go @@ -6,23 +6,25 @@ import ( "net/http" "net/http/httptest" "testing" - "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -func setupClientTest() (*http.ServeMux, *Client, func()) { +func setupTest(t *testing.T) (*http.ServeMux, *Client) { + t.Helper() + mux := http.NewServeMux() server := httptest.NewServer(mux) + t.Cleanup(server.Close) client := &Client{ token: "secret", 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) { @@ -120,8 +122,7 @@ func TestClient_GetDomainID(t *testing.T) { for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { - mux, client, tearDown := setupClientTest() - defer tearDown() + mux, client := setupTest(t) mux.Handle("/v1/domains", test.handler) @@ -180,8 +181,7 @@ func TestClient_CreateRecord(t *testing.T) { for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { - mux, client, tearDown := setupClientTest() - defer tearDown() + mux, client := setupTest(t) mux.Handle("/v1/domains/lego/records", test.handler) diff --git a/providers/dns/constellix/internal/domains_test.go b/providers/dns/constellix/internal/domains_test.go index db16faec..5df3f423 100644 --- a/providers/dns/constellix/internal/domains_test.go +++ b/providers/dns/constellix/internal/domains_test.go @@ -11,21 +11,23 @@ import ( "github.com/stretchr/testify/require" ) -func setupAPIMock() (*Client, *http.ServeMux, func()) { - handler := http.NewServeMux() - svr := httptest.NewServer(handler) +func setupTest(t *testing.T) (*Client, *http.ServeMux) { + t.Helper() - client := NewClient(nil) - client.BaseURL = svr.URL + mux := http.NewServeMux() + 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) { - client, handler, tearDown := setupAPIMock() - defer tearDown() + client, mux := setupTest(t) - 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 { http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest) return @@ -59,10 +61,9 @@ func TestDomainService_GetAll(t *testing.T) { } func TestDomainService_Search(t *testing.T) { - client, handler, tearDown := setupAPIMock() - defer tearDown() + client, mux := setupTest(t) - 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 { http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest) return diff --git a/providers/dns/constellix/internal/txtrecords_test.go b/providers/dns/constellix/internal/txtrecords_test.go index b14980de..e0c4de6d 100644 --- a/providers/dns/constellix/internal/txtrecords_test.go +++ b/providers/dns/constellix/internal/txtrecords_test.go @@ -12,10 +12,9 @@ import ( ) func TestTxtRecordService_Create(t *testing.T) { - client, handler, tearDown := setupAPIMock() - defer tearDown() + client, mux := setupTest(t) - 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 { http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest) return @@ -48,10 +47,9 @@ func TestTxtRecordService_Create(t *testing.T) { } func TestTxtRecordService_GetAll(t *testing.T) { - client, handler, tearDown := setupAPIMock() - defer tearDown() + client, mux := setupTest(t) - 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 { http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest) return @@ -84,10 +82,9 @@ func TestTxtRecordService_GetAll(t *testing.T) { } func TestTxtRecordService_Get(t *testing.T) { - client, handler, tearDown := setupAPIMock() - defer tearDown() + client, mux := setupTest(t) - 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 { http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest) return @@ -133,10 +130,9 @@ func TestTxtRecordService_Get(t *testing.T) { } func TestTxtRecordService_Update(t *testing.T) { - client, handler, tearDown := setupAPIMock() - defer tearDown() + client, mux := setupTest(t) - 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 { http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest) return @@ -157,10 +153,9 @@ func TestTxtRecordService_Update(t *testing.T) { } func TestTxtRecordService_Delete(t *testing.T) { - client, handler, tearDown := setupAPIMock() - defer tearDown() + client, mux := setupTest(t) - 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 { http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest) return @@ -181,10 +176,9 @@ func TestTxtRecordService_Delete(t *testing.T) { } func TestTxtRecordService_Search(t *testing.T) { - client, handler, tearDown := setupAPIMock() - defer tearDown() + client, mux := setupTest(t) - 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 { http.Error(rw, "invalid method: "+req.Method, http.StatusBadRequest) return diff --git a/providers/dns/designate/designate_test.go b/providers/dns/designate/designate_test.go index 7ea3e49b..82a7063b 100644 --- a/providers/dns/designate/designate_test.go +++ b/providers/dns/designate/designate_test.go @@ -321,7 +321,6 @@ func setupTestProvider(t *testing.T) string { }) server := httptest.NewServer(mux) - t.Cleanup(server.Close) return server.URL diff --git a/providers/dns/digitalocean/digitalocean_test.go b/providers/dns/digitalocean/digitalocean_test.go index 9dd608d7..b46998f2 100644 --- a/providers/dns/digitalocean/digitalocean_test.go +++ b/providers/dns/digitalocean/digitalocean_test.go @@ -14,20 +14,22 @@ import ( var envTest = tester.NewEnvTest(EnvAuthToken) -func setupTest() (*DNSProvider, *http.ServeMux, func()) { - handler := http.NewServeMux() - server := httptest.NewServer(handler) +func setupTest(t *testing.T) (*DNSProvider, *http.ServeMux) { + t.Helper() + + mux := http.NewServeMux() + server := httptest.NewServer(mux) + t.Cleanup(server.Close) config := NewDefaultConfig() config.AuthToken = "asdf1234" config.BaseURL = server.URL + config.HTTPClient = server.Client() provider, err := NewDNSProviderConfig(config) - if err != nil { - panic(err) - } + require.NoError(t, err) - return provider, handler, server.Close + return provider, mux } func TestNewDNSProvider(t *testing.T) { @@ -108,8 +110,7 @@ func TestNewDNSProviderConfig(t *testing.T) { } func TestDNSProvider_Present(t *testing.T) { - provider, mux, tearDown := setupTest() - defer tearDown() + provider, mux := setupTest(t) mux.HandleFunc("/v2/domains/example.com/records", func(w http.ResponseWriter, r *http.Request) { assert.Equal(t, http.MethodPost, r.Method, "method") @@ -147,8 +148,7 @@ func TestDNSProvider_Present(t *testing.T) { } func TestDNSProvider_CleanUp(t *testing.T) { - provider, mux, tearDown := setupTest() - defer tearDown() + provider, mux := setupTest(t) mux.HandleFunc("/v2/domains/example.com/records/1234567", func(w http.ResponseWriter, r *http.Request) { assert.Equal(t, http.MethodDelete, r.Method, "method") diff --git a/providers/dns/dreamhost/dreamhost_test.go b/providers/dns/dreamhost/dreamhost_test.go index 2c288108..6d58a35e 100644 --- a/providers/dns/dreamhost/dreamhost_test.go +++ b/providers/dns/dreamhost/dreamhost_test.go @@ -23,20 +23,22 @@ const ( fakeKeyAuth = "w6uP8Tcg6K2QR905Rms8iXTlksL6OD1KOWBxTK7wxPI" ) -func setupTest() (*DNSProvider, *http.ServeMux, func()) { - handler := http.NewServeMux() - server := httptest.NewServer(handler) +func setupTest(t *testing.T) (*DNSProvider, *http.ServeMux) { + t.Helper() + + mux := http.NewServeMux() + server := httptest.NewServer(mux) + t.Cleanup(server.Close) config := NewDefaultConfig() config.APIKey = fakeAPIKey config.BaseURL = server.URL + config.HTTPClient = server.Client() provider, err := NewDNSProviderConfig(config) - if err != nil { - panic(err) - } + require.NoError(t, err) - return provider, handler, server.Close + return provider, mux } func TestNewDNSProvider(t *testing.T) { @@ -113,8 +115,7 @@ func TestNewDNSProviderConfig(t *testing.T) { } func TestDNSProvider_Present(t *testing.T) { - provider, mux, tearDown := setupTest() - defer tearDown() + provider, mux := setupTest(t) mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { assert.Equal(t, http.MethodGet, r.Method, "method") @@ -138,8 +139,7 @@ func TestDNSProvider_Present(t *testing.T) { } func TestDNSProvider_PresentFailed(t *testing.T) { - provider, mux, tearDown := setupTest() - defer tearDown() + provider, mux := setupTest(t) mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { assert.Equal(t, http.MethodGet, r.Method, "method") @@ -155,8 +155,7 @@ func TestDNSProvider_PresentFailed(t *testing.T) { } func TestDNSProvider_Cleanup(t *testing.T) { - provider, mux, tearDown := setupTest() - defer tearDown() + provider, mux := setupTest(t) mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { assert.Equal(t, http.MethodGet, r.Method, "method") diff --git a/providers/dns/dynu/internal/client_test.go b/providers/dns/dynu/internal/client_test.go index cf397b24..56eef940 100644 --- a/providers/dns/dynu/internal/client_test.go +++ b/providers/dns/dynu/internal/client_test.go @@ -12,9 +12,12 @@ import ( "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() server := httptest.NewServer(mux) + t.Cleanup(server.Close) mux.HandleFunc(pattern, func(rw http.ResponseWriter, req *http.Request) { if req.Method != method { @@ -39,6 +42,7 @@ func setupTest(method, pattern string, status int, file string) *Client { }) client := NewClient() + client.HTTPClient = server.Client() client.BaseURL = server.URL return client @@ -90,7 +94,7 @@ func TestGetRootDomain(t *testing.T) { t.Run(test.desc, func(t *testing.T) { 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") @@ -179,7 +183,7 @@ func TestGetRecords(t *testing.T) { t.Run(test.desc, func(t *testing.T) { 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") @@ -230,7 +234,7 @@ func TestAddNewRecord(t *testing.T) { t.Run(test.desc, func(t *testing.T) { 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{ Type: "TXT", @@ -288,7 +292,7 @@ func TestDeleteRecord(t *testing.T) { t.Run(test.desc, func(t *testing.T) { 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) diff --git a/providers/dns/easydns/easydns_test.go b/providers/dns/easydns/easydns_test.go index 984d8051..60a94461 100644 --- a/providers/dns/easydns/easydns_test.go +++ b/providers/dns/easydns/easydns_test.go @@ -22,26 +22,26 @@ var envTest = tester.NewEnvTest( EnvKey). WithDomain(envDomain) -func setup() (*DNSProvider, *http.ServeMux, func()) { - handler := http.NewServeMux() - server := httptest.NewServer(handler) +func setupTest(t *testing.T) (*DNSProvider, *http.ServeMux) { + t.Helper() + + mux := http.NewServeMux() + server := httptest.NewServer(mux) + t.Cleanup(server.Close) endpoint, err := url.Parse(server.URL) - if err != nil { - panic(err) - } + require.NoError(t, err) config := NewDefaultConfig() config.Token = "TOKEN" config.Key = "SECRET" config.Endpoint = endpoint + config.HTTPClient = server.Client() provider, err := NewDNSProviderConfig(config) - if err != nil { - panic(err) - } + require.NoError(t, err) - return provider, handler, server.Close + return provider, mux } func TestNewDNSProvider(t *testing.T) { @@ -143,8 +143,7 @@ func TestNewDNSProviderConfig(t *testing.T) { } func TestDNSProvider_Present(t *testing.T) { - provider, mux, tearDown := setup() - defer tearDown() + provider, mux := setupTest(t) mux.HandleFunc("/zones/records/add/example.com/TXT", func(w http.ResponseWriter, r *http.Request) { 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) { - provider, _, tearDown := setup() - defer tearDown() + provider, _ := setupTest(t) err := provider.CleanUp("example.com", "token", "keyAuth") require.NoError(t, err) } func TestDNSProvider_Cleanup_WhenRecordIdSet_DeletesTxtRecord(t *testing.T) { - provider, mux, tearDown := setup() - defer tearDown() + provider, mux := setupTest(t) mux.HandleFunc("/zones/records/example.com/123456", func(w http.ResponseWriter, r *http.Request) { 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) { - provider, mux, tearDown := setup() - defer tearDown() + provider, mux := setupTest(t) errorMessage := `{ "error": { diff --git a/providers/dns/epik/internal/client_test.go b/providers/dns/epik/internal/client_test.go index 3425faea..47159d24 100644 --- a/providers/dns/epik/internal/client_test.go +++ b/providers/dns/epik/internal/client_test.go @@ -18,6 +18,7 @@ func setupTest(t *testing.T) (*http.ServeMux, *Client) { t.Helper() mux := http.NewServeMux() server := httptest.NewServer(mux) + t.Cleanup(server.Close) client := NewClient("secret") client.HTTPClient = server.Client() diff --git a/providers/dns/gandi/gandi_test.go b/providers/dns/gandi/gandi_test.go index 4ee919e3..f53ef3c2 100644 --- a/providers/dns/gandi/gandi_test.go +++ b/providers/dns/gandi/gandi_test.go @@ -124,7 +124,7 @@ func TestDNSProvider(t *testing.T) { regexpDate := regexp.MustCompile(`\[ACME Challenge [^\]:]*:[^\]]*\]`) // 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") req, errS := io.ReadAll(r.Body) @@ -137,7 +137,7 @@ func TestDNSProvider(t *testing.T) { _, errS = io.Copy(w, strings.NewReader(resp)) require.NoError(t, errS) })) - defer fakeServer.Close() + t.Cleanup(server.Close) // define function to override findZoneByFqdn with fakeFindZoneByFqdn := func(fqdn string) (string, error) { @@ -145,7 +145,7 @@ func TestDNSProvider(t *testing.T) { } config := NewDefaultConfig() - config.BaseURL = fakeServer.URL + "/" + config.BaseURL = server.URL + "/" config.APIKey = "123412341234123412341234" provider, err := NewDNSProviderConfig(config) @@ -153,9 +153,9 @@ func TestDNSProvider(t *testing.T) { // override findZoneByFqdn function savedFindZoneByFqdn := provider.findZoneByFqdn - defer func() { + t.Cleanup(func() { provider.findZoneByFqdn = savedFindZoneByFqdn - }() + }) provider.findZoneByFqdn = fakeFindZoneByFqdn // run Present diff --git a/providers/dns/gandiv5/gandiv5_test.go b/providers/dns/gandiv5/gandiv5_test.go index d56733ff..31156e23 100644 --- a/providers/dns/gandiv5/gandiv5_test.go +++ b/providers/dns/gandiv5/gandiv5_test.go @@ -114,8 +114,8 @@ func TestDNSProvider(t *testing.T) { regexpToken := regexp.MustCompile(`"rrset_values":\[".+"\]`) // start fake RPC server - handler := http.NewServeMux() - handler.HandleFunc("/domains/example.com/records/_acme-challenge.abc.def/TXT", func(rw http.ResponseWriter, req *http.Request) { + mux := http.NewServeMux() + 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) if req.Header.Get(apiKeyHeader) == "" { @@ -150,13 +150,13 @@ func TestDNSProvider(t *testing.T) { 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) http.Error(rw, fmt.Sprintf(`{"message": "URL doesn't match: %s"}`, req.URL), http.StatusNotFound) }) - server := httptest.NewServer(handler) - defer server.Close() + server := httptest.NewServer(mux) + t.Cleanup(server.Close) // define function to override findZoneByFqdn with fakeFindZoneByFqdn := func(fqdn string) (string, error) { diff --git a/providers/dns/gcloud/googlecloud_test.go b/providers/dns/gcloud/googlecloud_test.go index e5554286..ae97d48e 100644 --- a/providers/dns/gcloud/googlecloud_test.go +++ b/providers/dns/gcloud/googlecloud_test.go @@ -206,6 +206,7 @@ func TestPresentNoExistingRR(t *testing.T) { }) server := httptest.NewServer(mux) + t.Cleanup(server.Close) config := NewDefaultConfig() config.HTTPClient = &http.Client{} @@ -306,6 +307,7 @@ func TestPresentWithExistingRR(t *testing.T) { }) server := httptest.NewServer(mux) + t.Cleanup(server.Close) config := NewDefaultConfig() config.HTTPClient = &http.Client{} @@ -369,6 +371,7 @@ func TestPresentSkipExistingRR(t *testing.T) { }) server := httptest.NewServer(mux) + t.Cleanup(server.Close) config := NewDefaultConfig() config.HTTPClient = &http.Client{} diff --git a/providers/dns/hetzner/internal/client_test.go b/providers/dns/hetzner/internal/client_test.go index efce8883..269f984a 100644 --- a/providers/dns/hetzner/internal/client_test.go +++ b/providers/dns/hetzner/internal/client_test.go @@ -15,6 +15,7 @@ import ( func TestClient_GetTxtRecord(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) + t.Cleanup(server.Close) const zoneID = "zoneA" const apiKey = "myKeyA" @@ -63,6 +64,7 @@ func TestClient_GetTxtRecord(t *testing.T) { func TestClient_CreateRecord(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) + t.Cleanup(server.Close) const zoneID = "zoneA" const apiKey = "myKeyB" @@ -111,6 +113,7 @@ func TestClient_CreateRecord(t *testing.T) { func TestClient_DeleteRecord(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) + t.Cleanup(server.Close) const apiKey = "myKeyC" @@ -137,6 +140,7 @@ func TestClient_DeleteRecord(t *testing.T) { func TestClient_GetZoneID(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) + t.Cleanup(server.Close) const apiKey = "myKeyD" mux.HandleFunc("/api/v1/zones", func(rw http.ResponseWriter, req *http.Request) { diff --git a/providers/dns/httpreq/httpreq_test.go b/providers/dns/httpreq/httpreq_test.go index 4632f2c3..c3f4b2a0 100644 --- a/providers/dns/httpreq/httpreq_test.go +++ b/providers/dns/httpreq/httpreq_test.go @@ -158,7 +158,9 @@ func TestNewDNSProvider_Present(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc(path.Join("/", test.pathPrefix, "present"), test.handler) + server := httptest.NewServer(mux) + t.Cleanup(server.Close) config := NewDefaultConfig() config.Endpoint = mustParse(server.URL + test.pathPrefix) @@ -233,7 +235,9 @@ func TestNewDNSProvider_Cleanup(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/cleanup", test.handler) + server := httptest.NewServer(mux) + t.Cleanup(server.Close) config := NewDefaultConfig() config.Endpoint = mustParse(server.URL) diff --git a/providers/dns/hyperone/internal/client_test.go b/providers/dns/hyperone/internal/client_test.go index 84c6afb6..2f503094 100644 --- a/providers/dns/hyperone/internal/client_test.go +++ b/providers/dns/hyperone/internal/client_test.go @@ -149,6 +149,7 @@ func setupTest(t *testing.T, method, path string, handlers ...assertHandler) *Cl mux := http.NewServeMux() server := httptest.NewServer(mux) + t.Cleanup(server.Close) mux.Handle(path, http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { 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{ SubjectID: "/iam/project/proj123/sa/xxxxxxx", } diff --git a/providers/dns/internal/rimuhosting/client_test.go b/providers/dns/internal/rimuhosting/client_test.go index bed718fc..76ba18d2 100644 --- a/providers/dns/internal/rimuhosting/client_test.go +++ b/providers/dns/internal/rimuhosting/client_test.go @@ -17,6 +17,7 @@ import ( func TestClient_FindTXTRecords(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) + t.Cleanup(server.Close) mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) { query := req.URL.Query() @@ -257,6 +258,7 @@ func TestClient_DoActions(t *testing.T) { t.Run(test.desc, func(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) + t.Cleanup(server.Close) mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) { query, err := url.QueryUnescape(req.URL.RawQuery) diff --git a/providers/dns/internal/selectel/client_test.go b/providers/dns/internal/selectel/client_test.go index 056d4259..c0bf3007 100644 --- a/providers/dns/internal/selectel/client_test.go +++ b/providers/dns/internal/selectel/client_test.go @@ -16,6 +16,7 @@ import ( func TestClient_ListRecords(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) + t.Cleanup(server.Close) mux.HandleFunc("/123/records/", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodGet { @@ -50,6 +51,7 @@ func TestClient_ListRecords(t *testing.T) { func TestClient_ListRecords_error(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) + t.Cleanup(server.Close) mux.HandleFunc("/123/records/", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodGet { @@ -77,6 +79,7 @@ func TestClient_ListRecords_error(t *testing.T) { func TestClient_GetDomainByName(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) + t.Cleanup(server.Close) mux.HandleFunc("/sub.sub.example.org", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodGet { @@ -128,6 +131,7 @@ func TestClient_GetDomainByName(t *testing.T) { func TestClient_AddRecord(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) + t.Cleanup(server.Close) mux.HandleFunc("/123/records/", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodPost { @@ -180,6 +184,7 @@ func TestClient_AddRecord(t *testing.T) { func TestClient_DeleteRecord(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) + t.Cleanup(server.Close) mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodDelete { diff --git a/providers/dns/joker/internal/svc/client_test.go b/providers/dns/joker/internal/svc/client_test.go index 422352e6..4ee037e5 100644 --- a/providers/dns/joker/internal/svc/client_test.go +++ b/providers/dns/joker/internal/svc/client_test.go @@ -13,6 +13,7 @@ import ( func TestClient_Send(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) + t.Cleanup(server.Close) mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodPost { @@ -47,6 +48,7 @@ func TestClient_Send(t *testing.T) { func TestClient_Send_empty(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) + t.Cleanup(server.Close) mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodPost { diff --git a/providers/dns/linode/linode_test.go b/providers/dns/linode/linode_test.go index 6d208e7a..0d003890 100644 --- a/providers/dns/linode/linode_test.go +++ b/providers/dns/linode/linode_test.go @@ -19,8 +19,10 @@ type MockResponseMap map[string]interface{} var envTest = tester.NewEnvTest(EnvToken) -func newMockServer(responses MockResponseMap) *httptest.Server { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { +func setupTest(t *testing.T, responses MockResponseMap) string { + t.Helper() + + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Ensure that we support the requested action. action := r.Method + ":" + r.URL.Path resp, ok := responses[action] @@ -51,10 +53,14 @@ func newMockServer(responses MockResponseMap) *httptest.Server { if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } - })) + }) + + server := httptest.NewServer(handler) + t.Cleanup(server.Close) time.Sleep(100 * time.Millisecond) - return srv + + return server.URL } func TestNewDNSProvider(t *testing.T) { @@ -207,11 +213,10 @@ func TestDNSProvider_Present(t *testing.T) { for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { - server := newMockServer(test.mockResponses) - defer server.Close() + serverURL := setupTest(t, test.mockResponses) assert.NotNil(t, p.client) - p.client.SetBaseURL(server.URL) + p.client.SetBaseURL(serverURL) err = p.Present(domain, "", keyAuth) if test.expectedError == "" { @@ -323,10 +328,9 @@ func TestDNSProvider_CleanUp(t *testing.T) { for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { - server := newMockServer(test.mockResponses) - defer server.Close() + serverURL := setupTest(t, test.mockResponses) - p.client.SetBaseURL(server.URL) + p.client.SetBaseURL(serverURL) err = p.CleanUp(domain, "", keyAuth) if test.expectedError == "" { diff --git a/providers/dns/liquidweb/liquidweb_test.go b/providers/dns/liquidweb/liquidweb_test.go index b0034aed..100a98d1 100644 --- a/providers/dns/liquidweb/liquidweb_test.go +++ b/providers/dns/liquidweb/liquidweb_test.go @@ -22,9 +22,12 @@ var envTest = tester.NewEnvTest( EnvZone). WithDomain(envDomain) -func setupTest() (*DNSProvider, *http.ServeMux, func()) { - handler := http.NewServeMux() - server := httptest.NewServer(handler) +func setupTest(t *testing.T) (*DNSProvider, *http.ServeMux) { + t.Helper() + + mux := http.NewServeMux() + server := httptest.NewServer(mux) + t.Cleanup(server.Close) config := NewDefaultConfig() config.Username = "blars" @@ -33,11 +36,9 @@ func setupTest() (*DNSProvider, *http.ServeMux, func()) { config.Zone = "tacoman.com" provider, err := NewDNSProviderConfig(config) - if err != nil { - panic(err) - } + require.NoError(t, err) - return provider, handler, server.Close + return provider, mux } func TestNewDNSProvider(t *testing.T) { @@ -173,8 +174,7 @@ func TestNewDNSProviderConfig(t *testing.T) { } func TestDNSProvider_Present(t *testing.T) { - provider, mux, tearDown := setupTest() - defer tearDown() + provider, mux := setupTest(t) mux.HandleFunc("/v1/Network/DNS/Record/create", func(w http.ResponseWriter, r *http.Request) { assert.Equal(t, http.MethodPost, r.Method) @@ -221,8 +221,7 @@ func TestDNSProvider_Present(t *testing.T) { } func TestDNSProvider_CleanUp(t *testing.T) { - provider, mux, tearDown := setupTest() - defer tearDown() + provider, mux := setupTest(t) mux.HandleFunc("/v1/Network/DNS/Record/delete", func(w http.ResponseWriter, r *http.Request) { assert.Equal(t, http.MethodPost, r.Method) diff --git a/providers/dns/loopia/internal/client_test.go b/providers/dns/loopia/internal/client_test.go index 1f75be98..67758177 100644 --- a/providers/dns/loopia/internal/client_test.go +++ b/providers/dns/loopia/internal/client_test.go @@ -304,7 +304,7 @@ func TestUnmarshallFaultyRecordObject(t *testing.T) { func createFakeServer(t *testing.T, serverResponses map[string]string) string { 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" { http.Error(w, fmt.Sprintf("invalid content type: %s", r.Header.Get("Content-Type")), http.StatusBadRequest) return @@ -327,8 +327,9 @@ func createFakeServer(t *testing.T, serverResponses map[string]string) string { http.Error(w, err.Error(), http.StatusInternalServerError) return } - })) + }) + server := httptest.NewServer(handler) t.Cleanup(server.Close) return server.URL diff --git a/providers/dns/namecheap/namecheap_test.go b/providers/dns/namecheap/namecheap_test.go index 0b8afb7a..6b2afb5b 100644 --- a/providers/dns/namecheap/namecheap_test.go +++ b/providers/dns/namecheap/namecheap_test.go @@ -21,14 +21,12 @@ const ( func TestDNSProvider_getHosts(t *testing.T) { for _, test := range testCases { t.Run(test.name, func(t *testing.T) { - serverURL := mockServer(t, &test) - - provider := mockDNSProvider(serverURL) + p := setupTest(t, &test) ch, err := newChallenge(test.domain, "") require.NoError(t, err) - hosts, err := provider.getHosts(ch.sld, ch.tld) + hosts, err := p.getHosts(ch.sld, ch.tld) if test.errString != "" { assert.EqualError(t, err, test.errString) } else { @@ -61,14 +59,12 @@ func TestDNSProvider_getHosts(t *testing.T) { func TestDNSProvider_setHosts(t *testing.T) { for _, test := range testCases { t.Run(test.name, func(t *testing.T) { - serverURL := mockServer(t, &test) - - prov := mockDNSProvider(serverURL) + p := setupTest(t, &test) ch, err := newChallenge(test.domain, "") require.NoError(t, err) - hosts, err := prov.getHosts(ch.sld, ch.tld) + hosts, err := p.getHosts(ch.sld, ch.tld) if test.errString != "" { assert.EqualError(t, err, test.errString) } else { @@ -78,7 +74,7 @@ func TestDNSProvider_setHosts(t *testing.T) { return } - err = prov.setHosts(ch.sld, ch.tld, hosts) + err = p.setHosts(ch.sld, ch.tld, hosts) require.NoError(t, err) }) } @@ -87,10 +83,9 @@ func TestDNSProvider_setHosts(t *testing.T) { func TestDNSProvider_Present(t *testing.T) { for _, test := range testCases { t.Run(test.name, func(t *testing.T) { - serverURL := mockServer(t, &test) + p := setupTest(t, &test) - prov := mockDNSProvider(serverURL) - err := prov.Present(test.domain, "", "dummyKey") + err := p.Present(test.domain, "", "dummyKey") if test.errString != "" { assert.EqualError(t, err, "namecheap: "+test.errString) } else { @@ -103,10 +98,9 @@ func TestDNSProvider_Present(t *testing.T) { func TestDNSProvider_CleanUp(t *testing.T) { for _, test := range testCases { t.Run(test.name, func(t *testing.T) { - serverURL := mockServer(t, &test) + p := setupTest(t, &test) - prov := mockDNSProvider(serverURL) - err := prov.CleanUp(test.domain, "", "dummyKey") + err := p.CleanUp(test.domain, "", "dummyKey") if test.errString != "" { assert.EqualError(t, err, "namecheap: "+test.errString) } else { @@ -179,10 +173,10 @@ func assertHdr(t *testing.T, tc *testCase, values *url.Values) { 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() - 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 { case http.MethodGet: values := r.URL.Query() @@ -216,14 +210,17 @@ func mockServer(t *testing.T, tc *testCase) string { default: t.Errorf("Unexpected http method: %s", r.Method) } - })) + }) + server := httptest.NewServer(handler) 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.BaseURL = baseURL config.APIUser = envTestUser @@ -232,9 +229,8 @@ func mockDNSProvider(baseURL string) *DNSProvider { config.HTTPClient = &http.Client{Timeout: 60 * time.Second} provider, err := NewDNSProviderConfig(config) - if err != nil { - panic(err) - } + require.NoError(t, err) + return provider } diff --git a/providers/dns/netcup/internal/client_test.go b/providers/dns/netcup/internal/client_test.go index fd28dca2..87dc1815 100644 --- a/providers/dns/netcup/internal/client_test.go +++ b/providers/dns/netcup/internal/client_test.go @@ -21,17 +21,20 @@ var envTest = tester.NewEnvTest( "NETCUP_API_PASSWORD"). WithDomain("NETCUP_DOMAIN") -func setupClientTest() (*Client, *http.ServeMux, func()) { - handler := http.NewServeMux() - server := httptest.NewServer(handler) +func setupTest(t *testing.T) (*Client, *http.ServeMux) { + t.Helper() + + mux := http.NewServeMux() + server := httptest.NewServer(mux) + t.Cleanup(server.Close) client, err := NewClient("a", "b", "c") - if err != nil { - panic(err) - } + require.NoError(t, err) + + client.HTTPClient = server.Client() client.BaseURL = server.URL - return client, handler, server.Close + return client, mux } func TestGetDNSRecordIdx(t *testing.T) { @@ -137,8 +140,7 @@ func TestGetDNSRecordIdx(t *testing.T) { } func TestClient_Login(t *testing.T) { - client, mux, tearDown := setupClientTest() - defer tearDown() + client, mux := setupTest(t) mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) { 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.Parallel() - client, mux, tearDown := setupClientTest() - defer tearDown() + client, mux := setupTest(t) mux.HandleFunc("/", test.handler) @@ -247,8 +248,7 @@ func TestClient_Login_errors(t *testing.T) { } func TestClient_Logout(t *testing.T) { - client, mux, tearDown := setupClientTest() - defer tearDown() + client, mux := setupTest(t) mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) { 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.Parallel() - client, mux, tearDown := setupClientTest() - defer tearDown() + client, mux := setupTest(t) mux.HandleFunc("/", test.handler) @@ -331,8 +330,7 @@ func TestClient_Logout_errors(t *testing.T) { } func TestClient_GetDNSRecords(t *testing.T) { - client, mux, tearDown := setupClientTest() - defer tearDown() + client, mux := setupTest(t) mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) { 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.Parallel() - client, mux, tearDown := setupClientTest() - defer tearDown() + client, mux := setupTest(t) mux.HandleFunc("/", test.handler) diff --git a/providers/dns/nifcloud/internal/client_test.go b/providers/dns/nifcloud/internal/client_test.go index 56f0e059..cc0ae5b0 100644 --- a/providers/dns/nifcloud/internal/client_test.go +++ b/providers/dns/nifcloud/internal/client_test.go @@ -10,12 +10,24 @@ import ( "github.com/stretchr/testify/require" ) -func runTestServer(responseBody string, statusCode int) *httptest.Server { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { +func setupTest(t *testing.T, responseBody string, statusCode int) *Client { + t.Helper() + + handler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(statusCode) - fmt.Fprintln(w, responseBody) - })) - return server + _, _ = fmt.Fprintln(w, responseBody) + }) + + 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) { @@ -28,16 +40,12 @@ func TestChangeResourceRecordSets(t *testing.T) { ` - server := runTestServer(responseBody, http.StatusOK) - defer server.Close() - client, err := NewClient("A", "B") - require.NoError(t, err) - - client.BaseURL = server.URL + client := setupTest(t, responseBody, http.StatusOK) res, err := client.ChangeResourceRecordSets("example.com", ChangeResourceRecordSetsRequest{}) require.NoError(t, err) + assert.Equal(t, "xxxxx", res.ChangeInfo.ID) assert.Equal(t, "INSYNC", res.ChangeInfo.Status) 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 { test := test t.Run(test.desc, func(t *testing.T) { - server := runTestServer(test.responseBody, test.statusCode) - defer server.Close() - - client, err := NewClient("A", "B") - require.NoError(t, err) - - client.BaseURL = server.URL + client := setupTest(t, test.responseBody, test.statusCode) res, err := client.ChangeResourceRecordSets("example.com", ChangeResourceRecordSetsRequest{}) assert.Nil(t, res) @@ -107,16 +109,11 @@ func TestGetChange(t *testing.T) { ` - server := runTestServer(responseBody, http.StatusOK) - defer server.Close() - - client, err := NewClient("A", "B") - require.NoError(t, err) - - client.BaseURL = server.URL + client := setupTest(t, responseBody, http.StatusOK) res, err := client.GetChange("12345") require.NoError(t, err) + assert.Equal(t, "xxxxx", res.ChangeInfo.ID) assert.Equal(t, "INSYNC", res.ChangeInfo.Status) 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 { test := test t.Run(test.desc, func(t *testing.T) { - server := runTestServer(test.responseBody, test.statusCode) - defer server.Close() - - client, err := NewClient("A", "B") - require.NoError(t, err) - - client.BaseURL = server.URL + client := setupTest(t, test.responseBody, test.statusCode) res, err := client.GetChange("12345") assert.Nil(t, res) diff --git a/providers/dns/rackspace/rackspace_test.go b/providers/dns/rackspace/rackspace_test.go index 0ad4940f..8cea7c44 100644 --- a/providers/dns/rackspace/rackspace_test.go +++ b/providers/dns/rackspace/rackspace_test.go @@ -22,8 +22,7 @@ var envTest = tester.NewEnvTest( WithDomain(envDomain) func TestNewDNSProviderConfig(t *testing.T) { - config, tearDown := setupTest() - defer tearDown() + config := setupTest(t) provider, err := NewDNSProviderConfig(config) require.NoError(t, err) @@ -38,8 +37,7 @@ func TestNewDNSProviderConfig_MissingCredErr(t *testing.T) { } func TestDNSProvider_Present(t *testing.T) { - config, tearDown := setupTest() - defer tearDown() + config := setupTest(t) provider, err := NewDNSProviderConfig(config) @@ -50,8 +48,7 @@ func TestDNSProvider_Present(t *testing.T) { } func TestDNSProvider_CleanUp(t *testing.T) { - config, tearDown := setupTest() - defer tearDown() + config := setupTest(t) provider, err := NewDNSProviderConfig(config) @@ -101,25 +98,22 @@ func TestLiveCleanUp(t *testing.T) { require.NoError(t, err) } -func setupTest() (*Config, func()) { - apiURL, tearDown := startTestServers() +func setupTest(t *testing.T) *Config { + t.Helper() + + dnsAPI := httptest.NewServer(dnsHandler()) + t.Cleanup(dnsAPI.Close) + + identityAPI := httptest.NewServer(identityHandler(dnsAPI.URL + "/123456")) + t.Cleanup(identityAPI.Close) config := NewDefaultConfig() config.APIUser = "testUser" config.APIKey = "testKey" - config.BaseURL = apiURL + config.HTTPClient = identityAPI.Client() + config.BaseURL = identityAPI.URL + "/" - 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() - } + return config } func identityHandler(dnsEndpoint string) http.Handler { diff --git a/providers/dns/route53/mock_test.go b/providers/dns/route53/mock_test.go index 3a1370e2..02276738 100644 --- a/providers/dns/route53/mock_test.go +++ b/providers/dns/route53/mock_test.go @@ -19,10 +19,10 @@ type MockResponse struct { // MockResponseMap maps request paths to responses. type MockResponseMap map[string]MockResponse -func newMockServer(t *testing.T, responses MockResponseMap) string { +func setupTest(t *testing.T, responses MockResponseMap) string { 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 resp, ok := responses[path] if !ok { @@ -40,8 +40,9 @@ func newMockServer(t *testing.T, responses MockResponseMap) string { http.Error(w, err.Error(), http.StatusInternalServerError) return } - })) + }) + server := httptest.NewServer(handler) t.Cleanup(server.Close) time.Sleep(100 * time.Millisecond) diff --git a/providers/dns/route53/route53_test.go b/providers/dns/route53/route53_test.go index ee040e3a..5f115695 100644 --- a/providers/dns/route53/route53_test.go +++ b/providers/dns/route53/route53_test.go @@ -28,7 +28,9 @@ var envTest = tester.NewEnvTest( WithDomain(envDomain). WithLiveTestRequirements(EnvAccessKeyID, EnvSecretAccessKey, EnvRegion, envDomain) -func makeTestProvider(serverURL string) *DNSProvider { +func makeTestProvider(t *testing.T, serverURL string) *DNSProvider { + t.Helper() + config := &aws.Config{ Credentials: credentials.NewStaticCredentials("abc", "123", " "), Endpoint: aws.String(serverURL), @@ -37,9 +39,7 @@ func makeTestProvider(serverURL string) *DNSProvider { } sess, err := session.NewSession(config) - if err != nil { - panic(err) - } + require.NoError(t, err) return &DNSProvider{ 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() envTest.ClearEnv() - provider := makeTestProvider(serverURL) + provider := makeTestProvider(t, serverURL) domain := "example.com" keyAuth := "123456d==" diff --git a/providers/dns/sakuracloud/client_test.go b/providers/dns/sakuracloud/client_test.go index e8a1c62a..26a1b82b 100644 --- a/providers/dns/sakuracloud/client_test.go +++ b/providers/dns/sakuracloud/client_test.go @@ -24,22 +24,26 @@ type apiQuery struct { } `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() server := httptest.NewServer(mux) + t.Cleanup(server.Close) mux.HandleFunc("/is1a/api/cloud/1.1/commonserviceitem/", handler) backup := api.SakuraCloudAPIRoot - api.SakuraCloudAPIRoot = server.URL - return func() { + t.Cleanup(func() { api.SakuraCloudAPIRoot = backup - } + }) + api.SakuraCloudAPIRoot = server.URL } func TestDNSProvider_addTXTRecord(t *testing.T) { searchResp := &api.SearchDNSResponse{} - tearDown := fakeAPIServer(func(rw http.ResponseWriter, req *http.Request) { + + handler := func(rw http.ResponseWriter, req *http.Request) { switch req.Method { case http.MethodGet: if len(searchResp.CommonServiceDNSItems) == 0 { @@ -78,8 +82,9 @@ func TestDNSProvider_addTXTRecord(t *testing.T) { default: http.Error(rw, "OOPS", http.StatusServiceUnavailable) } - }) - defer tearDown() + } + + setupTest(t, handler) config := NewDefaultConfig() config.Token = "token1" @@ -101,7 +106,7 @@ func TestDNSProvider_addTXTRecord(t *testing.T) { func TestDNSProvider_cleanupTXTRecord(t *testing.T) { searchResp := &api.SearchDNSResponse{} - tearDown := fakeAPIServer(func(rw http.ResponseWriter, req *http.Request) { + handler := func(rw http.ResponseWriter, req *http.Request) { switch req.Method { case http.MethodGet: if len(searchResp.CommonServiceDNSItems) == 0 { @@ -141,8 +146,9 @@ func TestDNSProvider_cleanupTXTRecord(t *testing.T) { default: http.Error(rw, "OOPS", http.StatusServiceUnavailable) } - }) - defer tearDown() + } + + setupTest(t, handler) config := NewDefaultConfig() config.Token = "token2" @@ -164,7 +170,7 @@ func TestDNSProvider_cleanupTXTRecord(t *testing.T) { func TestDNSProvider_addTXTRecord_concurrent(t *testing.T) { searchResp := &api.SearchDNSResponse{} - tearDown := fakeAPIServer(func(rw http.ResponseWriter, req *http.Request) { + handler := func(rw http.ResponseWriter, req *http.Request) { switch req.Method { case http.MethodGet: if len(searchResp.CommonServiceDNSItems) == 0 { @@ -203,8 +209,9 @@ func TestDNSProvider_addTXTRecord_concurrent(t *testing.T) { default: http.Error(rw, "OOPS", http.StatusServiceUnavailable) } - }) - defer tearDown() + } + + setupTest(t, handler) dummyRecordCount := 10 @@ -251,7 +258,7 @@ func TestDNSProvider_cleanupTXTRecord_concurrent(t *testing.T) { 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 { case http.MethodGet: if err := json.NewEncoder(rw).Encode(searchResp); err != nil { @@ -279,8 +286,9 @@ func TestDNSProvider_cleanupTXTRecord_concurrent(t *testing.T) { default: http.Error(rw, "OOPS", http.StatusServiceUnavailable) } - }) - defer tearDown() + } + + setupTest(t, handler) fakeZone := sacloud.CreateNewDNS("example.com") fakeZone.ID = 123456789012 diff --git a/providers/dns/servercow/internal/client_test.go b/providers/dns/servercow/internal/client_test.go index f44082d9..1c880973 100644 --- a/providers/dns/servercow/internal/client_test.go +++ b/providers/dns/servercow/internal/client_test.go @@ -12,19 +12,21 @@ import ( "github.com/stretchr/testify/require" ) -func setupAPIMock() (*Client, *http.ServeMux, func()) { - handler := http.NewServeMux() - svr := httptest.NewServer(handler) +func setupTest(t *testing.T) (*Client, *http.ServeMux) { + t.Helper() + + mux := http.NewServeMux() + server := httptest.NewServer(mux) + t.Cleanup(server.Close) client := NewClient("", "") - client.BaseURL = svr.URL + client.BaseURL = server.URL - return client, handler, svr.Close + return client, mux } func TestClient_GetRecords(t *testing.T) { - client, handler, tearDown := setupAPIMock() - defer tearDown() + client, handler := setupTest(t) handler.HandleFunc("/lego.wtf", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodGet { @@ -59,8 +61,7 @@ func TestClient_GetRecords(t *testing.T) { } func TestClient_GetRecords_error(t *testing.T) { - client, handler, tearDown := setupAPIMock() - defer tearDown() + client, handler := setupTest(t) handler.HandleFunc("/lego.wtf", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodGet { @@ -82,8 +83,7 @@ func TestClient_GetRecords_error(t *testing.T) { } func TestClient_CreateUpdateRecord(t *testing.T) { - client, handler, tearDown := setupAPIMock() - defer tearDown() + client, handler := setupTest(t) handler.HandleFunc("/lego.wtf", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodPost { @@ -126,8 +126,7 @@ func TestClient_CreateUpdateRecord(t *testing.T) { } func TestClient_CreateUpdateRecord_error(t *testing.T) { - client, handler, tearDown := setupAPIMock() - defer tearDown() + client, handler := setupTest(t) handler.HandleFunc("/lego.wtf", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodPost { @@ -153,8 +152,7 @@ func TestClient_CreateUpdateRecord_error(t *testing.T) { } func TestClient_DeleteRecord(t *testing.T) { - client, handler, tearDown := setupAPIMock() - defer tearDown() + client, handler := setupTest(t) handler.HandleFunc("/lego.wtf", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodDelete { @@ -195,8 +193,7 @@ func TestClient_DeleteRecord(t *testing.T) { } func TestClient_DeleteRecord_error(t *testing.T) { - client, handler, tearDown := setupAPIMock() - defer tearDown() + client, handler := setupTest(t) handler.HandleFunc("/lego.wtf", func(rw http.ResponseWriter, req *http.Request) { if req.Method != http.MethodDelete { diff --git a/providers/dns/stackpath/stackpath_test.go b/providers/dns/stackpath/stackpath_test.go index bcb7ddbc..1a575bbf 100644 --- a/providers/dns/stackpath/stackpath_test.go +++ b/providers/dns/stackpath/stackpath_test.go @@ -135,9 +135,12 @@ func TestNewDNSProviderConfig(t *testing.T) { } } -func setupMockAPITest() (*DNSProvider, *http.ServeMux, func()) { - apiHandler := http.NewServeMux() - server := httptest.NewServer(apiHandler) +func setupTest(t *testing.T) (*DNSProvider, *http.ServeMux) { + t.Helper() + + mux := http.NewServeMux() + server := httptest.NewServer(mux) + t.Cleanup(server.Close) config := NewDefaultConfig() config.ClientID = "CLIENT_ID" @@ -145,19 +148,16 @@ func setupMockAPITest() (*DNSProvider, *http.ServeMux, func()) { config.StackID = "STACK_ID" provider, err := NewDNSProviderConfig(config) - if err != nil { - panic(err) - } + require.NoError(t, err) provider.client = http.DefaultClient provider.BaseURL, _ = url.Parse(server.URL + "/") - return provider, apiHandler, server.Close + return provider, mux } func TestDNSProvider_getZoneRecords(t *testing.T) { - provider, mux, tearDown := setupMockAPITest() - defer tearDown() + provider, mux := setupTest(t) mux.HandleFunc("/STACK_ID/zones/A/records", func(w http.ResponseWriter, _ *http.Request) { content := ` @@ -187,8 +187,7 @@ func TestDNSProvider_getZoneRecords(t *testing.T) { } func TestDNSProvider_getZoneRecords_apiError(t *testing.T) { - provider, mux, tearDown := setupMockAPITest() - defer tearDown() + provider, mux := setupTest(t) mux.HandleFunc("/STACK_ID/zones/A/records", func(w http.ResponseWriter, _ *http.Request) { content := ` @@ -212,8 +211,7 @@ func TestDNSProvider_getZoneRecords_apiError(t *testing.T) { } func TestDNSProvider_getZones(t *testing.T) { - provider, mux, tearDown := setupMockAPITest() - defer tearDown() + provider, mux := setupTest(t) mux.HandleFunc("/STACK_ID/zones", func(w http.ResponseWriter, _ *http.Request) { content := ` diff --git a/providers/dns/vegadns/vegadns_test.go b/providers/dns/vegadns/vegadns_test.go index a789c919..4e82da45 100644 --- a/providers/dns/vegadns/vegadns_test.go +++ b/providers/dns/vegadns/vegadns_test.go @@ -28,8 +28,7 @@ func TestDNSProvider_TimeoutSuccess(t *testing.T) { defer envTest.RestoreEnv() envTest.ClearEnv() - tearDown := startTestServer(muxSuccess()) - defer tearDown() + setupTest(t, muxSuccess()) provider, err := NewDNSProvider() require.NoError(t, err) @@ -66,8 +65,7 @@ func TestDNSProvider_Present(t *testing.T) { defer envTest.RestoreEnv() envTest.ClearEnv() - tearDown := startTestServer(test.handler) - defer tearDown() + setupTest(t, test.handler) provider, err := NewDNSProvider() require.NoError(t, err) @@ -109,8 +107,7 @@ func TestDNSProvider_CleanUp(t *testing.T) { defer envTest.RestoreEnv() envTest.ClearEnv() - tearDown := startTestServer(test.handler) - defer tearDown() + setupTest(t, test.handler) provider, err := NewDNSProvider() require.NoError(t, err) @@ -273,16 +270,15 @@ func muxFailToGetRecordID() *http.ServeMux { return mux } -func startTestServer(handler http.Handler) func() { - ts := httptest.NewServer(handler) +func setupTest(t *testing.T, mux http.Handler) { + t.Helper() + + server := httptest.NewServer(mux) + t.Cleanup(server.Close) envTest.Apply(map[string]string{ EnvKey: "key", EnvSecret: "secret", - EnvURL: ts.URL, + EnvURL: server.URL, }) - - return func() { - ts.Close() - } } diff --git a/providers/dns/versio/versio_test.go b/providers/dns/versio/versio_test.go index 2e2163e0..026a20d4 100644 --- a/providers/dns/versio/versio_test.go +++ b/providers/dns/versio/versio_test.go @@ -148,8 +148,7 @@ func TestDNSProvider_Present(t *testing.T) { defer envTest.RestoreEnv() envTest.ClearEnv() - baseURL, tearDown := startTestServer(test.handler) - defer tearDown() + baseURL := setupTest(t, test.handler) envTest.Apply(map[string]string{ EnvUsername: "me@example.com", @@ -191,8 +190,7 @@ func TestDNSProvider_CleanUp(t *testing.T) { defer envTest.RestoreEnv() envTest.ClearEnv() - baseURL, tearDown := startTestServer(test.handler) - defer tearDown() + baseURL := setupTest(t, test.handler) envTest.Apply(map[string]string{ EnvUsername: "me@example.com", @@ -272,11 +270,13 @@ func muxFailToCreateTXT() *http.ServeMux { return mux } -func startTestServer(handler http.Handler) (string, func()) { - ts := httptest.NewServer(handler) - return ts.URL, func() { - ts.Close() - } +func setupTest(t *testing.T, handler http.Handler) string { + t.Helper() + + server := httptest.NewServer(handler) + t.Cleanup(server.Close) + + return server.URL } func TestLivePresent(t *testing.T) { diff --git a/providers/dns/yandex/internal/client_test.go b/providers/dns/yandex/internal/client_test.go index ce0e9a8f..9dca11b9 100644 --- a/providers/dns/yandex/internal/client_test.go +++ b/providers/dns/yandex/internal/client_test.go @@ -10,17 +10,20 @@ import ( "github.com/stretchr/testify/require" ) -func setupClientTest() (*http.ServeMux, *Client, func()) { +func setupTest(t *testing.T) (*http.ServeMux, *Client) { + t.Helper() + mux := http.NewServeMux() server := httptest.NewServer(mux) + t.Cleanup(server.Close) client, err := NewClient("lego") - if err != nil { - panic(err) - } + require.NoError(t, err) + client.HTTPClient = server.Client() client.BaseURL = server.URL - return mux, client, server.Close + + return mux, client } func TestAddRecord(t *testing.T) { @@ -107,8 +110,7 @@ func TestAddRecord(t *testing.T) { for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { - mux, client, tearDown := setupClientTest() - defer tearDown() + mux, client := setupTest(t) mux.HandleFunc("/add", test.handler) @@ -195,8 +197,7 @@ func TestRemoveRecord(t *testing.T) { for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { - mux, client, tearDown := setupClientTest() - defer tearDown() + mux, client := setupTest(t) mux.HandleFunc("/del", test.handler) @@ -287,8 +288,7 @@ func TestGetRecords(t *testing.T) { test := test t.Run(test.desc, func(t *testing.T) { t.Parallel() - mux, client, tearDown := setupClientTest() - defer tearDown() + mux, client := setupTest(t) mux.HandleFunc("/list", test.handler) diff --git a/providers/dns/zoneee/zoneee_test.go b/providers/dns/zoneee/zoneee_test.go index 09ae33e1..fa5133a8 100644 --- a/providers/dns/zoneee/zoneee_test.go +++ b/providers/dns/zoneee/zoneee_test.go @@ -186,6 +186,7 @@ func TestDNSProvider_Present(t *testing.T) { } server := httptest.NewServer(mux) + t.Cleanup(server.Close) config := NewDefaultConfig() config.Endpoint = mustParse(server.URL) @@ -276,6 +277,7 @@ func TestDNSProvider_Cleanup(t *testing.T) { } server := httptest.NewServer(mux) + t.Cleanup(server.Close) config := NewDefaultConfig() config.Endpoint = mustParse(server.URL) diff --git a/registration/registar_test.go b/registration/registar_test.go index a5f3e607..efbc4f6f 100644 --- a/registration/registar_test.go +++ b/registration/registar_test.go @@ -14,8 +14,7 @@ import ( ) func TestRegistrar_ResolveAccountByKey(t *testing.T) { - mux, apiURL, tearDown := tester.SetupFakeAPI() - defer tearDown() + mux, apiURL := tester.SetupFakeAPI(t) mux.HandleFunc("/account", func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Location", apiURL+"/account")