chore: update linter. (#1325)

This commit is contained in:
Ludovic Fernandez 2020-12-28 23:39:00 +01:00 committed by GitHub
parent 3efb14404a
commit af01844596
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
14 changed files with 107 additions and 87 deletions

View file

@ -15,7 +15,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
env: env:
GO_VERSION: 1.15 GO_VERSION: 1.15
GOLANGCI_LINT_VERSION: v1.33.0 GOLANGCI_LINT_VERSION: v1.34.0
HUGO_VERSION: 0.54.0 HUGO_VERSION: 0.54.0
SEIHON_VERSION: v0.5.1 SEIHON_VERSION: v0.5.1
CGO_ENABLED: 0 CGO_ENABLED: 0

View file

@ -43,6 +43,8 @@
"tparallel", # not relevant "tparallel", # not relevant
"paralleltest", # not relevant "paralleltest", # not relevant
"exhaustivestruct", # too many false-positive "exhaustivestruct", # too many false-positive
"makezero", # not relevant
"forbidigo", # not relevant
] ]
[issues] [issues]

View file

@ -15,10 +15,14 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
func setupTestProvider(t *testing.T) (*DNSProvider, *http.ServeMux, func()) { func setupTestProvider(t *testing.T) (*DNSProvider, *http.ServeMux) {
t.Helper()
handler := http.NewServeMux() handler := http.NewServeMux()
svr := httptest.NewServer(handler) svr := httptest.NewServer(handler)
t.Cleanup(svr.Close)
config := NewDefaultConfig() config := NewDefaultConfig()
config.Endpoint, _ = url.Parse(svr.URL) config.Endpoint, _ = url.Parse(svr.URL)
config.Token = "secret" config.Token = "secret"
@ -26,12 +30,11 @@ func setupTestProvider(t *testing.T) (*DNSProvider, *http.ServeMux, func()) {
prd, err := NewDNSProviderConfig(config) prd, err := NewDNSProviderConfig(config)
require.NoError(t, err) require.NoError(t, err)
return prd, handler, svr.Close return prd, handler
} }
func Test_getDomainIDByName(t *testing.T) { func Test_getDomainIDByName(t *testing.T) {
prd, handler, tearDown := setupTestProvider(t) prd, handler := setupTestProvider(t)
defer tearDown()
handler.HandleFunc("/v1/domains", func(rw http.ResponseWriter, req *http.Request) { handler.HandleFunc("/v1/domains", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodGet { if req.Method != http.MethodGet {
@ -59,8 +62,7 @@ func Test_getDomainIDByName(t *testing.T) {
} }
func Test_checkNameservers(t *testing.T) { func Test_checkNameservers(t *testing.T) {
prd, handler, tearDown := setupTestProvider(t) prd, handler := setupTestProvider(t)
defer tearDown()
handler.HandleFunc("/v1/domains/1/nameservers", func(rw http.ResponseWriter, req *http.Request) { handler.HandleFunc("/v1/domains/1/nameservers", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodGet { if req.Method != http.MethodGet {
@ -87,8 +89,7 @@ func Test_checkNameservers(t *testing.T) {
} }
func Test_createRecord(t *testing.T) { func Test_createRecord(t *testing.T) {
prd, handler, tearDown := setupTestProvider(t) prd, handler := setupTestProvider(t)
defer tearDown()
handler.HandleFunc("/v1/domains/1/nameservers/records", func(rw http.ResponseWriter, req *http.Request) { handler.HandleFunc("/v1/domains/1/nameservers/records", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost { if req.Method != http.MethodPost {
@ -119,8 +120,7 @@ func Test_createRecord(t *testing.T) {
} }
func Test_deleteTXTRecord(t *testing.T) { func Test_deleteTXTRecord(t *testing.T) {
prd, handler, tearDown := setupTestProvider(t) prd, handler := setupTestProvider(t)
defer tearDown()
domainName := "lego.test" domainName := "lego.test"
recordValue := "test" recordValue := "test"

View file

@ -31,7 +31,7 @@ var envTest = tester.NewEnvTest(
WithDomain(envDomain) WithDomain(envDomain)
func TestNewDNSProvider_fromEnv(t *testing.T) { func TestNewDNSProvider_fromEnv(t *testing.T) {
server := getServer(t) serverURL := setupTestProvider(t)
testCases := []struct { testCases := []struct {
desc string desc string
@ -41,7 +41,7 @@ func TestNewDNSProvider_fromEnv(t *testing.T) {
{ {
desc: "success", desc: "success",
envVars: map[string]string{ envVars: map[string]string{
EnvAuthURL: server.URL + "/v2.0/", EnvAuthURL: serverURL + "/v2.0/",
EnvUsername: "B", EnvUsername: "B",
EnvPassword: "C", EnvPassword: "C",
EnvRegionName: "D", EnvRegionName: "D",
@ -71,7 +71,7 @@ func TestNewDNSProvider_fromEnv(t *testing.T) {
{ {
desc: "missing username", desc: "missing username",
envVars: map[string]string{ envVars: map[string]string{
EnvAuthURL: server.URL + "/v2.0/", EnvAuthURL: serverURL + "/v2.0/",
EnvUsername: "", EnvUsername: "",
EnvPassword: "C", EnvPassword: "C",
EnvRegionName: "D", EnvRegionName: "D",
@ -81,7 +81,7 @@ func TestNewDNSProvider_fromEnv(t *testing.T) {
{ {
desc: "missing password", desc: "missing password",
envVars: map[string]string{ envVars: map[string]string{
EnvAuthURL: server.URL + "/v2.0/", EnvAuthURL: serverURL + "/v2.0/",
EnvUsername: "B", EnvUsername: "B",
EnvPassword: "", EnvPassword: "",
EnvRegionName: "D", EnvRegionName: "D",
@ -91,7 +91,7 @@ func TestNewDNSProvider_fromEnv(t *testing.T) {
{ {
desc: "missing region name", desc: "missing region name",
envVars: map[string]string{ envVars: map[string]string{
EnvAuthURL: server.URL + "/v2.0/", EnvAuthURL: serverURL + "/v2.0/",
EnvUsername: "B", EnvUsername: "B",
EnvPassword: "C", EnvPassword: "C",
EnvRegionName: "", EnvRegionName: "",
@ -121,7 +121,7 @@ func TestNewDNSProvider_fromEnv(t *testing.T) {
} }
func TestNewDNSProvider_fromCloud(t *testing.T) { func TestNewDNSProvider_fromCloud(t *testing.T) {
server := getServer(t) serverURL := setupTestProvider(t)
testCases := []struct { testCases := []struct {
desc string desc string
@ -134,7 +134,7 @@ func TestNewDNSProvider_fromCloud(t *testing.T) {
osCloud: "good_cloud", osCloud: "good_cloud",
cloud: clientconfig.Cloud{ cloud: clientconfig.Cloud{
AuthInfo: &clientconfig.AuthInfo{ AuthInfo: &clientconfig.AuthInfo{
AuthURL: server.URL + "/v2.0/", AuthURL: serverURL + "/v2.0/",
Username: "B", Username: "B",
Password: "C", Password: "C",
ProjectName: "E", ProjectName: "E",
@ -162,7 +162,7 @@ func TestNewDNSProvider_fromCloud(t *testing.T) {
osCloud: "missing_username", osCloud: "missing_username",
cloud: clientconfig.Cloud{ cloud: clientconfig.Cloud{
AuthInfo: &clientconfig.AuthInfo{ AuthInfo: &clientconfig.AuthInfo{
AuthURL: server.URL + "/v2.0/", AuthURL: serverURL + "/v2.0/",
Password: "C", Password: "C",
ProjectName: "E", ProjectName: "E",
ProjectID: "F", ProjectID: "F",
@ -176,7 +176,7 @@ func TestNewDNSProvider_fromCloud(t *testing.T) {
osCloud: "missing_auth_url", osCloud: "missing_auth_url",
cloud: clientconfig.Cloud{ cloud: clientconfig.Cloud{
AuthInfo: &clientconfig.AuthInfo{ AuthInfo: &clientconfig.AuthInfo{
AuthURL: server.URL + "/v2.0/", AuthURL: serverURL + "/v2.0/",
Username: "B", Username: "B",
ProjectName: "E", ProjectName: "E",
ProjectID: "F", ProjectID: "F",
@ -211,7 +211,7 @@ func TestNewDNSProvider_fromCloud(t *testing.T) {
} }
func TestNewDNSProviderConfig(t *testing.T) { func TestNewDNSProviderConfig(t *testing.T) {
server := getServer(t) serverURL := setupTestProvider(t)
testCases := []struct { testCases := []struct {
desc string desc string
@ -226,15 +226,15 @@ func TestNewDNSProviderConfig(t *testing.T) {
tenantName: "A", tenantName: "A",
password: "B", password: "B",
userName: "C", userName: "C",
authURL: server.URL + "/v2.0/", authURL: serverURL + "/v2.0/",
}, },
{ {
desc: "wrong auth url", desc: "wrong auth url",
tenantName: "A", tenantName: "A",
password: "B", password: "B",
userName: "C", userName: "C",
authURL: server.URL, authURL: serverURL,
expected: "designate: failed to authenticate: No supported version available from endpoint " + server.URL + "/", expected: "designate: failed to authenticate: No supported version available from endpoint " + serverURL + "/",
}, },
} }
@ -261,6 +261,8 @@ func TestNewDNSProviderConfig(t *testing.T) {
// createCloudsYaml creates a temporary cloud file for testing purpose. // createCloudsYaml creates a temporary cloud file for testing purpose.
func createCloudsYaml(t *testing.T, cloudName string, cloud clientconfig.Cloud) string { func createCloudsYaml(t *testing.T, cloudName string, cloud clientconfig.Cloud) string {
t.Helper()
file, err := ioutil.TempFile("", "lego_test") file, err := ioutil.TempFile("", "lego_test")
require.NoError(t, err) require.NoError(t, err)
@ -278,7 +280,9 @@ func createCloudsYaml(t *testing.T, cloudName string, cloud clientconfig.Cloud)
return file.Name() return file.Name()
} }
func getServer(t *testing.T) *httptest.Server { func setupTestProvider(t *testing.T) string {
t.Helper()
mux := http.NewServeMux() mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) { mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{ _, _ = w.Write([]byte(`{
@ -317,7 +321,7 @@ func getServer(t *testing.T) *httptest.Server {
t.Cleanup(server.Close) t.Cleanup(server.Close)
return server return server.URL
} }
func TestLivePresent(t *testing.T) { func TestLivePresent(t *testing.T) {

View file

@ -146,6 +146,8 @@ func TestClient_GetZones(t *testing.T) {
} }
func setupTest(t *testing.T, method, path string, handlers ...assertHandler) *Client { func setupTest(t *testing.T, method, path string, handlers ...assertHandler) *Client {
t.Helper()
mux := http.NewServeMux() mux := http.NewServeMux()
server := httptest.NewServer(mux) server := httptest.NewServer(mux)

View file

@ -12,6 +12,8 @@ import (
) )
func setupTest(t *testing.T) (*Client, *http.ServeMux) { func setupTest(t *testing.T) (*Client, *http.ServeMux) {
t.Helper()
mux := http.NewServeMux() mux := http.NewServeMux()
server := httptest.NewServer(mux) server := httptest.NewServer(mux)
t.Cleanup(server.Close) t.Cleanup(server.Close)

View file

@ -24,6 +24,8 @@ const (
) )
func setup(t *testing.T) (*http.ServeMux, string) { func setup(t *testing.T) (*http.ServeMux, string) {
t.Helper()
mux := http.NewServeMux() mux := http.NewServeMux()
server := httptest.NewServer(mux) server := httptest.NewServer(mux)

View file

@ -1,7 +1,6 @@
package lightsail package lightsail
import ( import (
"net/http/httptest"
"os" "os"
"testing" "testing"
@ -30,10 +29,10 @@ var envTest = tester.NewEnvTest(
WithDomain(EnvDNSZone). WithDomain(EnvDNSZone).
WithLiveTestRequirements(envAwsAccessKeyID, envAwsSecretAccessKey, EnvDNSZone) WithLiveTestRequirements(envAwsAccessKeyID, envAwsSecretAccessKey, EnvDNSZone)
func makeProvider(ts *httptest.Server) (*DNSProvider, error) { func makeProvider(serverURL string) (*DNSProvider, error) {
config := &aws.Config{ config := &aws.Config{
Credentials: credentials.NewStaticCredentials("abc", "123", " "), Credentials: credentials.NewStaticCredentials("abc", "123", " "),
Endpoint: aws.String(ts.URL), Endpoint: aws.String(serverURL),
Region: aws.String("mock-region"), Region: aws.String("mock-region"),
MaxRetries: aws.Int(1), MaxRetries: aws.Int(1),
} }
@ -53,9 +52,9 @@ func TestCredentialsFromEnv(t *testing.T) {
defer envTest.RestoreEnv() defer envTest.RestoreEnv()
envTest.ClearEnv() envTest.ClearEnv()
os.Setenv(envAwsAccessKeyID, "123") _ = os.Setenv(envAwsAccessKeyID, "123")
os.Setenv(envAwsSecretAccessKey, "123") _ = os.Setenv(envAwsSecretAccessKey, "123")
os.Setenv(envAwsRegion, "us-east-1") _ = os.Setenv(envAwsRegion, "us-east-1")
config := &aws.Config{ config := &aws.Config{
CredentialsChainVerboseErrors: aws.Bool(true), CredentialsChainVerboseErrors: aws.Bool(true),
@ -73,10 +72,9 @@ func TestDNSProvider_Present(t *testing.T) {
"/": {StatusCode: 200, Body: ""}, "/": {StatusCode: 200, Body: ""},
} }
ts := newMockServer(t, mockResponses) serverURL := newMockServer(t, mockResponses)
defer ts.Close()
provider, err := makeProvider(ts) provider, err := makeProvider(serverURL)
require.NoError(t, err) require.NoError(t, err)
domain := "example.com" domain := "example.com"

View file

@ -16,8 +16,10 @@ type MockResponse struct {
Body string Body string
} }
func newMockServer(t *testing.T, responses map[string]MockResponse) *httptest.Server { func newMockServer(t *testing.T, responses map[string]MockResponse) string {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { t.Helper()
server := httptest.NewServer(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 {
@ -34,6 +36,9 @@ func newMockServer(t *testing.T, responses map[string]MockResponse) *httptest.Se
} }
})) }))
t.Cleanup(server.Close)
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
return ts
return server.URL
} }

View file

@ -20,7 +20,7 @@ func TestClient_AddZoneRecord(t *testing.T) {
addZoneRecordEmptyResponse: "", addZoneRecordEmptyResponse: "",
} }
server := createFakeServer(t, serverResponses) serverURL := createFakeServer(t, serverResponses)
testCases := []struct { testCases := []struct {
desc string desc string
@ -56,8 +56,7 @@ func TestClient_AddZoneRecord(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) {
client := NewClient("apiuser", test.password) client := NewClient("apiuser", test.password)
client.BaseURL = server.URL + "/" client.BaseURL = serverURL + "/"
client.HTTPClient = server.Client()
err := client.AddTXTRecord(test.domain, exampleSubDomain, 123, "TXTrecord") err := client.AddTXTRecord(test.domain, exampleSubDomain, 123, "TXTrecord")
if len(test.err) == 0 { if len(test.err) == 0 {
@ -78,7 +77,7 @@ func TestClient_RemoveSubdomain(t *testing.T) {
removeSubdomainEmptyResponse: "", removeSubdomainEmptyResponse: "",
} }
server := createFakeServer(t, serverResponses) serverURL := createFakeServer(t, serverResponses)
testCases := []struct { testCases := []struct {
desc string desc string
@ -114,8 +113,7 @@ func TestClient_RemoveSubdomain(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) {
client := NewClient("apiuser", test.password) client := NewClient("apiuser", test.password)
client.BaseURL = server.URL + "/" client.BaseURL = serverURL + "/"
client.HTTPClient = server.Client()
err := client.RemoveSubdomain(test.domain, exampleSubDomain) err := client.RemoveSubdomain(test.domain, exampleSubDomain)
if len(test.err) == 0 { if len(test.err) == 0 {
@ -136,7 +134,7 @@ func TestClient_RemoveZoneRecord(t *testing.T) {
removeRecordEmptyResponse: "", removeRecordEmptyResponse: "",
} }
server := createFakeServer(t, serverResponses) serverURL := createFakeServer(t, serverResponses)
testCases := []struct { testCases := []struct {
desc string desc string
@ -172,8 +170,7 @@ func TestClient_RemoveZoneRecord(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) {
client := NewClient("apiuser", test.password) client := NewClient("apiuser", test.password)
client.BaseURL = server.URL + "/" client.BaseURL = serverURL + "/"
client.HTTPClient = server.Client()
err := client.RemoveTXTRecord(test.domain, exampleSubDomain, 12345678) err := client.RemoveTXTRecord(test.domain, exampleSubDomain, 12345678)
if len(test.err) == 0 { if len(test.err) == 0 {
@ -191,11 +188,10 @@ func TestClient_GetZoneRecord(t *testing.T) {
getZoneRecords: getZoneRecordsResponse, getZoneRecords: getZoneRecordsResponse,
} }
server := createFakeServer(t, serverResponses) serverURL := createFakeServer(t, serverResponses)
client := NewClient("apiuser", "goodpassword") client := NewClient("apiuser", "goodpassword")
client.BaseURL = server.URL + "/" client.BaseURL = serverURL + "/"
client.HTTPClient = server.Client()
recordObjs, err := client.GetTXTRecords(exampleDomain, exampleSubDomain) recordObjs, err := client.GetTXTRecords(exampleDomain, exampleSubDomain)
require.NoError(t, err) require.NoError(t, err)
@ -240,7 +236,6 @@ func TestClient_rpcCall_404(t *testing.T) {
client := NewClient("apiuser", "apipassword") client := NewClient("apiuser", "apipassword")
client.BaseURL = server.URL + "/" client.BaseURL = server.URL + "/"
client.HTTPClient = server.Client()
err := client.rpcCall(call, &responseString{}) err := client.rpcCall(call, &responseString{})
assert.EqualError(t, err, "HTTP Post Error: 404") assert.EqualError(t, err, "HTTP Post Error: 404")
@ -272,7 +267,6 @@ func TestClient_rpcCall_RPCError(t *testing.T) {
client := NewClient("apiuser", "apipassword") client := NewClient("apiuser", "apipassword")
client.BaseURL = server.URL + "/" client.BaseURL = server.URL + "/"
client.HTTPClient = server.Client()
err := client.rpcCall(call, &responseString{}) err := client.rpcCall(call, &responseString{})
assert.EqualError(t, err, "RPC Error: (201) Method signature error: 42") assert.EqualError(t, err, "RPC Error: (201) Method signature error: 42")
@ -307,7 +301,9 @@ func TestUnmarshallFaultyRecordObject(t *testing.T) {
} }
} }
func createFakeServer(t *testing.T, serverResponses map[string]string) *httptest.Server { func createFakeServer(t *testing.T, serverResponses map[string]string) string {
t.Helper()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { server := httptest.NewServer(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)
@ -335,5 +331,5 @@ func createFakeServer(t *testing.T, serverResponses map[string]string) *httptest
t.Cleanup(server.Close) t.Cleanup(server.Close)
return server return server.URL
} }

View file

@ -21,10 +21,9 @@ 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) {
mock := httptest.NewServer(mockServer(&test, t)) serverURL := mockServer(t, &test)
defer mock.Close()
provider := mockDNSProvider(mock.URL) provider := mockDNSProvider(serverURL)
ch, err := newChallenge(test.domain, "") ch, err := newChallenge(test.domain, "")
require.NoError(t, err) require.NoError(t, err)
@ -62,10 +61,9 @@ 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) {
mock := httptest.NewServer(mockServer(&test, t)) serverURL := mockServer(t, &test)
defer mock.Close()
prov := mockDNSProvider(mock.URL) prov := mockDNSProvider(serverURL)
ch, err := newChallenge(test.domain, "") ch, err := newChallenge(test.domain, "")
require.NoError(t, err) require.NoError(t, err)
@ -89,10 +87,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) {
mock := httptest.NewServer(mockServer(&test, t)) serverURL := mockServer(t, &test)
defer mock.Close()
prov := mockDNSProvider(mock.URL) prov := mockDNSProvider(serverURL)
err := prov.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)
@ -106,10 +103,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) {
mock := httptest.NewServer(mockServer(&test, t)) serverURL := mockServer(t, &test)
defer mock.Close()
prov := mockDNSProvider(mock.URL) prov := mockDNSProvider(serverURL)
err := prov.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)
@ -171,7 +167,7 @@ func TestDomainSplit(t *testing.T) {
} }
} }
func assertHdr(tc *testCase, t *testing.T, values *url.Values) { func assertHdr(t *testing.T, tc *testCase, values *url.Values) {
t.Helper() t.Helper()
ch, _ := newChallenge(tc.domain, "") ch, _ := newChallenge(tc.domain, "")
@ -183,15 +179,17 @@ func assertHdr(tc *testCase, t *testing.T, values *url.Values) {
assert.Equal(t, ch.tld, values.Get("TLD"), "TLD") assert.Equal(t, ch.tld, values.Get("TLD"), "TLD")
} }
func mockServer(tc *testCase, t *testing.T) http.Handler { func mockServer(t *testing.T, tc *testCase) string {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { t.Helper()
server := httptest.NewServer(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()
cmd := values.Get("Command") cmd := values.Get("Command")
switch cmd { switch cmd {
case "namecheap.domains.dns.getHosts": case "namecheap.domains.dns.getHosts":
assertHdr(tc, t, &values) assertHdr(t, tc, &values)
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
fmt.Fprint(w, tc.getHostsResponse) fmt.Fprint(w, tc.getHostsResponse)
default: default:
@ -208,7 +206,7 @@ func mockServer(tc *testCase, t *testing.T) http.Handler {
cmd := values.Get("Command") cmd := values.Get("Command")
switch cmd { switch cmd {
case "namecheap.domains.dns.setHosts": case "namecheap.domains.dns.setHosts":
assertHdr(tc, t, &values) assertHdr(t, tc, &values)
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
fmt.Fprint(w, tc.setHostsResponse) fmt.Fprint(w, tc.setHostsResponse)
default: default:
@ -218,7 +216,11 @@ func mockServer(tc *testCase, t *testing.T) http.Handler {
default: default:
t.Errorf("Unexpected http method: %s", r.Method) t.Errorf("Unexpected http method: %s", r.Method)
} }
}) }))
t.Cleanup(server.Close)
return server.URL
} }
func mockDNSProvider(url string) *DNSProvider { func mockDNSProvider(url string) *DNSProvider {

View file

@ -21,6 +21,8 @@ type DNSServerMock struct {
// NewDNSServerMock create a new DNSServerMock. // NewDNSServerMock create a new DNSServerMock.
func NewDNSServerMock(t *testing.T) *DNSServerMock { func NewDNSServerMock(t *testing.T) *DNSServerMock {
t.Helper()
mux := http.NewServeMux() mux := http.NewServeMux()
return &DNSServerMock{ return &DNSServerMock{

View file

@ -19,8 +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) *httptest.Server { func newMockServer(t *testing.T, responses MockResponseMap) string {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { t.Helper()
server := httptest.NewServer(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,6 +42,9 @@ func newMockServer(t *testing.T, responses MockResponseMap) *httptest.Server {
} }
})) }))
t.Cleanup(server.Close)
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
return ts
return server.URL
} }

View file

@ -1,7 +1,6 @@
package route53 package route53
import ( import (
"net/http/httptest"
"os" "os"
"testing" "testing"
"time" "time"
@ -29,10 +28,10 @@ var envTest = tester.NewEnvTest(
WithDomain(envDomain). WithDomain(envDomain).
WithLiveTestRequirements(EnvAccessKeyID, EnvSecretAccessKey, EnvRegion, envDomain) WithLiveTestRequirements(EnvAccessKeyID, EnvSecretAccessKey, EnvRegion, envDomain)
func makeTestProvider(ts *httptest.Server) *DNSProvider { func makeTestProvider(serverURL string) *DNSProvider {
config := &aws.Config{ config := &aws.Config{
Credentials: credentials.NewStaticCredentials("abc", "123", " "), Credentials: credentials.NewStaticCredentials("abc", "123", " "),
Endpoint: aws.String(ts.URL), Endpoint: aws.String(serverURL),
Region: aws.String("mock-region"), Region: aws.String("mock-region"),
MaxRetries: aws.Int(1), MaxRetries: aws.Int(1),
} }
@ -41,18 +40,20 @@ func makeTestProvider(ts *httptest.Server) *DNSProvider {
if err != nil { if err != nil {
panic(err) panic(err)
} }
client := route53.New(sess)
cfg := NewDefaultConfig() return &DNSProvider{
return &DNSProvider{client: client, config: cfg} client: route53.New(sess),
config: NewDefaultConfig(),
}
} }
func Test_loadCredentials_FromEnv(t *testing.T) { func Test_loadCredentials_FromEnv(t *testing.T) {
defer envTest.RestoreEnv() defer envTest.RestoreEnv()
envTest.ClearEnv() envTest.ClearEnv()
os.Setenv(EnvAccessKeyID, "123") _ = os.Setenv(EnvAccessKeyID, "123")
os.Setenv(EnvSecretAccessKey, "456") _ = os.Setenv(EnvSecretAccessKey, "456")
os.Setenv(EnvRegion, "us-east-1") _ = os.Setenv(EnvRegion, "us-east-1")
config := &aws.Config{ config := &aws.Config{
CredentialsChainVerboseErrors: aws.Bool(true), CredentialsChainVerboseErrors: aws.Bool(true),
@ -164,12 +165,11 @@ func TestDNSProvider_Present(t *testing.T) {
}, },
} }
ts := newMockServer(t, mockResponses) serverURL := newMockServer(t, mockResponses)
defer ts.Close()
defer envTest.RestoreEnv() defer envTest.RestoreEnv()
envTest.ClearEnv() envTest.ClearEnv()
provider := makeTestProvider(ts) provider := makeTestProvider(serverURL)
domain := "example.com" domain := "example.com"
keyAuth := "123456d==" keyAuth := "123456d=="