Archived
Add mock-backed integration testing tier and fake Dynu API
This commit is contained in:
1 parent
7f161fb19b
commit
293fe7af28
10 files changed
+564
-154
No files matched your search
@@ -1,27 +1,19 @@
|
||||
package dynuclient
|
||||
package dynuclient_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"github.com/dynu/terraform-provider-dynu/internal/dynuclient"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/dynu/terraform-provider-dynu/internal/testutil/fakedynu"
|
||||
)
|
||||
|
||||
func TestClientListDomainsSuccess(t *testing.T) {
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/dns" {
|
||||
t.Fatalf("unexpected path: %s", r.URL.Path)
|
||||
}
|
||||
if got := r.Header.Get("API-Key"); got != "test-key" {
|
||||
t.Fatalf("unexpected api key header: %s", got)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"statusCode":200,"domains":[{"id":2,"name":"z.example.com"},{"id":1,"name":"a.example.com"}]}`))
|
||||
}))
|
||||
defer ts.Close()
|
||||
fake := fakedynu.NewServer()
|
||||
defer fake.Close()
|
||||
|
||||
client := New("test-key", WithBaseURL(ts.URL), WithHTTPClient(ts.Client()))
|
||||
client := dynuclient.New("test-key", dynuclient.WithBaseURL(fake.BaseURL()), dynuclient.WithHTTPClient(fake.Client()))
|
||||
domains, err := client.ListDomains(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("ListDomains() error = %v", err)
|
||||
@@ -32,13 +24,11 @@ func TestClientListDomainsSuccess(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestClientDoGetNon2xxStatus(t *testing.T) {
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_, _ = w.Write([]byte(`{"message":"nope"}`))
|
||||
}))
|
||||
defer ts.Close()
|
||||
fake := fakedynu.NewServer()
|
||||
defer fake.Close()
|
||||
fake.SetRawResponse("/dns", 401, `{"message":"nope"}`)
|
||||
|
||||
client := New("test-key", WithBaseURL(ts.URL), WithHTTPClient(ts.Client()))
|
||||
client := dynuclient.New("test-key", dynuclient.WithBaseURL(fake.BaseURL()), dynuclient.WithHTTPClient(fake.Client()))
|
||||
_, err := client.ListDomains(context.Background())
|
||||
if err == nil || !strings.Contains(err.Error(), "status 401") {
|
||||
t.Fatalf("expected status error, got %v", err)
|
||||
@@ -46,13 +36,11 @@ func TestClientDoGetNon2xxStatus(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestClientDoGetAPIExceptionPayload(t *testing.T) {
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"statusCode":200,"exception":{"statusCode":400,"type":"Validation Exception","message":"bad hostname"}}`))
|
||||
}))
|
||||
defer ts.Close()
|
||||
fake := fakedynu.NewServer()
|
||||
defer fake.Close()
|
||||
fake.SetAPIError("/dns", fakedynu.APIError{HTTPStatus: 400, StatusCode: 400, Type: "Validation Exception", Message: "bad hostname"})
|
||||
|
||||
client := New("test-key", WithBaseURL(ts.URL), WithHTTPClient(ts.Client()))
|
||||
client := dynuclient.New("test-key", dynuclient.WithBaseURL(fake.BaseURL()), dynuclient.WithHTTPClient(fake.Client()))
|
||||
_, err := client.ListDomains(context.Background())
|
||||
if err == nil || !strings.Contains(err.Error(), "Validation Exception") {
|
||||
t.Fatalf("expected API exception error, got %v", err)
|
||||
@@ -60,13 +48,11 @@ func TestClientDoGetAPIExceptionPayload(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestClientDoGetMalformedJSON(t *testing.T) {
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"statusCode":200,"domains":[`))
|
||||
}))
|
||||
defer ts.Close()
|
||||
fake := fakedynu.NewServer()
|
||||
defer fake.Close()
|
||||
fake.SetRawResponse("/dns", 200, `{"statusCode":200,"domains":[`)
|
||||
|
||||
client := New("test-key", WithBaseURL(ts.URL), WithHTTPClient(ts.Client()))
|
||||
client := dynuclient.New("test-key", dynuclient.WithBaseURL(fake.BaseURL()), dynuclient.WithHTTPClient(fake.Client()))
|
||||
_, err := client.ListDomains(context.Background())
|
||||
if err == nil || !strings.Contains(err.Error(), "failed to decode dynu API response") {
|
||||
t.Fatalf("expected decode error, got %v", err)
|
||||
@@ -74,31 +60,25 @@ func TestClientDoGetMalformedJSON(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestClientGetRootDomainIncompleteResponse(t *testing.T) {
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"statusCode":200,"id":0,"domainName":""}`))
|
||||
}))
|
||||
defer ts.Close()
|
||||
fake := fakedynu.NewServer()
|
||||
defer fake.Close()
|
||||
fake.SetRawResponse("/dns/getroot/www.a.example.com", 200, `{"statusCode":200,"id":0,"domainName":""}`)
|
||||
|
||||
client := New("test-key", WithBaseURL(ts.URL), WithHTTPClient(ts.Client()))
|
||||
_, _, err := client.GetRootDomain(context.Background(), "www.example.com")
|
||||
client := dynuclient.New("test-key", dynuclient.WithBaseURL(fake.BaseURL()), dynuclient.WithHTTPClient(fake.Client()))
|
||||
_, _, err := client.GetRootDomain(context.Background(), "www.a.example.com")
|
||||
if err == nil || !strings.Contains(err.Error(), "incomplete root domain response") {
|
||||
t.Fatalf("expected incomplete response error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientGetRootDomainEscapesHostname(t *testing.T) {
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !strings.Contains(r.RequestURI, "spaces%20in%20name.example.com") {
|
||||
t.Fatalf("expected escaped hostname path, got %s", r.RequestURI)
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"statusCode":200,"id":123,"domainName":"example.com"}`))
|
||||
}))
|
||||
defer ts.Close()
|
||||
fake := fakedynu.NewServer()
|
||||
defer fake.Close()
|
||||
fake.SetAPIError("/dns/getroot/spaces%20in%20name.example.com", fakedynu.APIError{HTTPStatus: 404, StatusCode: 404, Type: "Not Found", Message: "hostname not found"})
|
||||
|
||||
client := New("test-key", WithBaseURL(ts.URL), WithHTTPClient(ts.Client()))
|
||||
client := dynuclient.New("test-key", dynuclient.WithBaseURL(fake.BaseURL()), dynuclient.WithHTTPClient(fake.Client()))
|
||||
_, _, err := client.GetRootDomain(context.Background(), "spaces in name.example.com")
|
||||
if err != nil {
|
||||
t.Fatalf("expected nil error, got %v", err)
|
||||
if err == nil || !strings.Contains(err.Error(), "hostname not found") {
|
||||
t.Fatalf("expected hostname not found error, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -100,18 +100,20 @@ func (d *dnsRecordsDataSource) Configure(_ context.Context, req datasource.Confi
|
||||
}
|
||||
|
||||
func (d *dnsRecordsDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
|
||||
var state dnsRecordsDataSourceModel
|
||||
resp.Diagnostics.Append(req.Config.Get(ctx, &state)...)
|
||||
var config struct {
|
||||
Hostname types.String `tfsdk:"hostname"`
|
||||
}
|
||||
resp.Diagnostics.Append(req.Config.Get(ctx, &config)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
if state.Hostname.IsUnknown() || state.Hostname.IsNull() {
|
||||
if config.Hostname.IsUnknown() || config.Hostname.IsNull() {
|
||||
resp.Diagnostics.AddAttributeError(path.Root("hostname"), "Invalid hostname", "The hostname must be known and non-null.")
|
||||
return
|
||||
}
|
||||
|
||||
domainID, domainName, err := d.clientProvider.client.GetRootDomain(ctx, state.Hostname.ValueString())
|
||||
domainID, domainName, err := d.clientProvider.client.GetRootDomain(ctx, config.Hostname.ValueString())
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Unable to resolve Dynu domain from hostname", err.Error())
|
||||
return
|
||||
@@ -125,9 +127,12 @@ func (d *dnsRecordsDataSource) Read(ctx context.Context, req datasource.ReadRequ
|
||||
|
||||
sortDNSRecords(records)
|
||||
|
||||
state.DomainID = types.Int64Value(domainID)
|
||||
state.DomainName = types.StringValue(domainName)
|
||||
state.Records = make([]dnsRecordStateItem, 0, len(records))
|
||||
state := dnsRecordsDataSourceModel{
|
||||
Hostname: config.Hostname,
|
||||
DomainID: types.Int64Value(domainID),
|
||||
DomainName: types.StringValue(domainName),
|
||||
Records: make([]dnsRecordStateItem, 0, len(records)),
|
||||
}
|
||||
for _, record := range records {
|
||||
state.Records = append(state.Records, dnsRecordStateItem{
|
||||
ID: types.Int64Value(record.ID),
|
||||
|
||||
@@ -73,18 +73,20 @@ func (d *domainDataSource) Configure(_ context.Context, req datasource.Configure
|
||||
}
|
||||
|
||||
func (d *domainDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
|
||||
var state domainDataSourceModel
|
||||
resp.Diagnostics.Append(req.Config.Get(ctx, &state)...)
|
||||
var config struct {
|
||||
Hostname types.String `tfsdk:"hostname"`
|
||||
}
|
||||
resp.Diagnostics.Append(req.Config.Get(ctx, &config)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
if state.Hostname.IsUnknown() || state.Hostname.IsNull() {
|
||||
if config.Hostname.IsUnknown() || config.Hostname.IsNull() {
|
||||
resp.Diagnostics.AddAttributeError(path.Root("hostname"), "Invalid hostname", "The hostname must be known and non-null.")
|
||||
return
|
||||
}
|
||||
|
||||
domainID, _, err := d.clientProvider.client.GetRootDomain(ctx, state.Hostname.ValueString())
|
||||
domainID, _, err := d.clientProvider.client.GetRootDomain(ctx, config.Hostname.ValueString())
|
||||
if err != nil {
|
||||
resp.Diagnostics.AddError("Unable to resolve Dynu domain from hostname", err.Error())
|
||||
return
|
||||
@@ -101,7 +103,10 @@ func (d *domainDataSource) Read(ctx context.Context, req datasource.ReadRequest,
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
state.Domain = domainObject
|
||||
state := domainDataSourceModel{
|
||||
Hostname: config.Hostname,
|
||||
Domain: domainObject,
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/dynu/terraform-provider-dynu/internal/testutil/fakedynu"
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/path"
|
||||
"github.com/hashicorp/terraform-plugin-framework/tfsdk"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/hashicorp/terraform-plugin-go/tftypes"
|
||||
)
|
||||
|
||||
func TestIntegrationDataSourceDomains(t *testing.T) {
|
||||
fake := fakedynu.NewServer()
|
||||
defer fake.Close()
|
||||
|
||||
ds := NewDomainsDataSource().(*domainsDataSource)
|
||||
configureDataSource(t, ds, fake.BaseURL())
|
||||
|
||||
var schemaResp datasource.SchemaResponse
|
||||
ds.Schema(context.Background(), datasource.SchemaRequest{}, &schemaResp)
|
||||
|
||||
resp := datasource.ReadResponse{State: tfsdk.State{Schema: schemaResp.Schema}}
|
||||
ds.Read(context.Background(), datasource.ReadRequest{}, &resp)
|
||||
if resp.Diagnostics.HasError() {
|
||||
t.Fatalf("unexpected diagnostics: %v", resp.Diagnostics)
|
||||
}
|
||||
|
||||
var state domainsDataSourceModel
|
||||
diags := resp.State.Get(context.Background(), &state)
|
||||
if diags.HasError() {
|
||||
t.Fatalf("state get diagnostics: %v", diags)
|
||||
}
|
||||
|
||||
if len(state.Domains) != 2 {
|
||||
t.Fatalf("expected 2 domains, got %d", len(state.Domains))
|
||||
}
|
||||
if state.Domains[0].Name.ValueString() != "a.example.com" {
|
||||
t.Fatalf("expected sorted domain a.example.com first, got %q", state.Domains[0].Name.ValueString())
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationDataSourceDomain(t *testing.T) {
|
||||
fake := fakedynu.NewServer()
|
||||
defer fake.Close()
|
||||
|
||||
ds := NewDomainDataSource().(*domainDataSource)
|
||||
configureDataSource(t, ds, fake.BaseURL())
|
||||
|
||||
var schemaResp datasource.SchemaResponse
|
||||
ds.Schema(context.Background(), datasource.SchemaRequest{}, &schemaResp)
|
||||
|
||||
req := datasource.ReadRequest{
|
||||
Config: tfsdk.Config{
|
||||
Schema: schemaResp.Schema,
|
||||
Raw: tftypes.NewValue(tftypes.Object{AttributeTypes: map[string]tftypes.Type{
|
||||
"hostname": tftypes.String,
|
||||
}}, map[string]tftypes.Value{
|
||||
"hostname": tftypes.NewValue(tftypes.String, "www.a.example.com"),
|
||||
}),
|
||||
},
|
||||
}
|
||||
resp := datasource.ReadResponse{State: tfsdk.State{Schema: schemaResp.Schema}}
|
||||
ds.Read(context.Background(), req, &resp)
|
||||
if resp.Diagnostics.HasError() {
|
||||
t.Fatalf("unexpected diagnostics: %v", resp.Diagnostics)
|
||||
}
|
||||
|
||||
var state domainDataSourceModel
|
||||
diags := resp.State.Get(context.Background(), &state)
|
||||
if diags.HasError() {
|
||||
t.Fatalf("state get diagnostics: %v", diags)
|
||||
}
|
||||
|
||||
var domainID int64
|
||||
diags = resp.State.GetAttribute(context.Background(), path.Root("domain").AtName("id"), &domainID)
|
||||
if diags.HasError() {
|
||||
t.Fatalf("domain.id decode diagnostics: %v", diags)
|
||||
}
|
||||
var domainName string
|
||||
diags = resp.State.GetAttribute(context.Background(), path.Root("domain").AtName("name"), &domainName)
|
||||
if diags.HasError() {
|
||||
t.Fatalf("domain.name decode diagnostics: %v", diags)
|
||||
}
|
||||
if domainID != 1001 || domainName != "a.example.com" {
|
||||
t.Fatalf("unexpected domain state: id=%d name=%q", domainID, domainName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationDataSourceDNSRecords(t *testing.T) {
|
||||
fake := fakedynu.NewServer()
|
||||
defer fake.Close()
|
||||
|
||||
ds := NewDNSRecordsDataSource().(*dnsRecordsDataSource)
|
||||
configureDataSource(t, ds, fake.BaseURL())
|
||||
|
||||
var schemaResp datasource.SchemaResponse
|
||||
ds.Schema(context.Background(), datasource.SchemaRequest{}, &schemaResp)
|
||||
|
||||
req := datasource.ReadRequest{
|
||||
Config: tfsdk.Config{
|
||||
Schema: schemaResp.Schema,
|
||||
Raw: tftypes.NewValue(tftypes.Object{AttributeTypes: map[string]tftypes.Type{
|
||||
"hostname": tftypes.String,
|
||||
}}, map[string]tftypes.Value{
|
||||
"hostname": tftypes.NewValue(tftypes.String, "www.a.example.com"),
|
||||
}),
|
||||
},
|
||||
}
|
||||
resp := datasource.ReadResponse{State: tfsdk.State{Schema: schemaResp.Schema}}
|
||||
ds.Read(context.Background(), req, &resp)
|
||||
if resp.Diagnostics.HasError() {
|
||||
t.Fatalf("unexpected diagnostics: %v", resp.Diagnostics)
|
||||
}
|
||||
|
||||
var state dnsRecordsDataSourceModel
|
||||
diags := resp.State.Get(context.Background(), &state)
|
||||
if diags.HasError() {
|
||||
t.Fatalf("state get diagnostics: %v", diags)
|
||||
}
|
||||
|
||||
if state.DomainID.ValueInt64() != 1001 || state.DomainName.ValueString() != "a.example.com" {
|
||||
t.Fatalf("unexpected domain resolution: domain_id=%d domain_name=%q", state.DomainID.ValueInt64(), state.DomainName.ValueString())
|
||||
}
|
||||
if len(state.Records) != 2 || state.Records[0].ID.ValueInt64() != 10 {
|
||||
t.Fatalf("unexpected records state: %#v", state.Records)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationDataSourceDiagnosticsFromAPIError(t *testing.T) {
|
||||
fake := fakedynu.NewServer()
|
||||
defer fake.Close()
|
||||
fake.SetAPIError("/dns/getroot/www.a.example.com", fakedynu.APIError{HTTPStatus: 400, StatusCode: 400, Type: "Validation Exception", Message: "bad hostname"})
|
||||
|
||||
ds := NewDomainDataSource().(*domainDataSource)
|
||||
configureDataSource(t, ds, fake.BaseURL())
|
||||
|
||||
var schemaResp datasource.SchemaResponse
|
||||
ds.Schema(context.Background(), datasource.SchemaRequest{}, &schemaResp)
|
||||
|
||||
req := datasource.ReadRequest{Config: tfsdk.Config{
|
||||
Schema: schemaResp.Schema,
|
||||
Raw: tftypes.NewValue(tftypes.Object{AttributeTypes: map[string]tftypes.Type{"hostname": tftypes.String}}, map[string]tftypes.Value{
|
||||
"hostname": tftypes.NewValue(tftypes.String, "www.a.example.com"),
|
||||
}),
|
||||
}}
|
||||
resp := datasource.ReadResponse{State: tfsdk.State{Schema: schemaResp.Schema}}
|
||||
ds.Read(context.Background(), req, &resp)
|
||||
if !resp.Diagnostics.HasError() {
|
||||
t.Fatal("expected diagnostics error")
|
||||
}
|
||||
if !strings.Contains(resp.Diagnostics[0].Summary(), "Unable to resolve Dynu domain from hostname") {
|
||||
t.Fatalf("unexpected diagnostics summary: %s", resp.Diagnostics[0].Summary())
|
||||
}
|
||||
}
|
||||
|
||||
func configureDataSource(t *testing.T, ds datasource.DataSourceWithConfigure, baseURL string) {
|
||||
t.Helper()
|
||||
resp := datasource.ConfigureResponse{}
|
||||
ds.Configure(context.Background(), datasource.ConfigureRequest{
|
||||
ProviderData: &providerData{client: newDynuClient("dummy-local-key", types.StringValue(baseURL))},
|
||||
}, &resp)
|
||||
if resp.Diagnostics.HasError() {
|
||||
t.Fatalf("configure diagnostics: %v", resp.Diagnostics)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package fakedynu
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/dynu/terraform-provider-dynu/internal/dynuclient"
|
||||
)
|
||||
|
||||
type RootDomain struct {
|
||||
ID int64
|
||||
Hostname string
|
||||
DomainName string
|
||||
Node string
|
||||
}
|
||||
|
||||
type APIError struct {
|
||||
HTTPStatus int
|
||||
StatusCode int
|
||||
Type string
|
||||
Message string
|
||||
}
|
||||
|
||||
type Fixture struct {
|
||||
Domains []dynuclient.Domain
|
||||
RootsByHostname map[string]RootDomain
|
||||
RecordsByDomain map[int64][]dynuclient.DNSRecord
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
*httptest.Server
|
||||
|
||||
mu sync.RWMutex
|
||||
fixture Fixture
|
||||
errors map[string]APIError
|
||||
rawPayload map[string]rawResponse
|
||||
}
|
||||
|
||||
type rawResponse struct {
|
||||
httpStatus int
|
||||
body string
|
||||
}
|
||||
|
||||
func NewServer() *Server {
|
||||
s := &Server{
|
||||
errors: map[string]APIError{},
|
||||
rawPayload: map[string]rawResponse{},
|
||||
fixture: Fixture{
|
||||
Domains: []dynuclient.Domain{
|
||||
{ID: 2002, Name: "z.example.com", UnicodeName: "z.example.com", TTL: 60, CreatedOn: "2024-01-03T00:00:00", UpdatedOn: "2024-01-04T00:00:00"},
|
||||
{ID: 1001, Name: "a.example.com", UnicodeName: "a.example.com", TTL: 120, CreatedOn: "2024-01-01T00:00:00", UpdatedOn: "2024-01-02T00:00:00"},
|
||||
},
|
||||
RootsByHostname: map[string]RootDomain{
|
||||
"www.a.example.com": {ID: 1001, Hostname: "www.a.example.com", DomainName: "a.example.com", Node: "www"},
|
||||
"api.a.example.com": {ID: 1001, Hostname: "api.a.example.com", DomainName: "a.example.com", Node: "api"},
|
||||
},
|
||||
RecordsByDomain: map[int64][]dynuclient.DNSRecord{
|
||||
1001: {
|
||||
{ID: 20, DomainID: 1001, DomainName: "a.example.com", NodeName: "www", Hostname: "www.a.example.com", RecordType: "TXT", TTL: 90, State: true, Content: "v=spf1", UpdatedOn: "2024-01-03T11:00:00"},
|
||||
{ID: 10, DomainID: 1001, DomainName: "a.example.com", NodeName: "www", Hostname: "www.a.example.com", RecordType: "A", TTL: 30, State: true, Content: "203.0.113.5", UpdatedOn: "2024-01-03T10:00:00"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
s.Server = httptest.NewServer(http.HandlerFunc(s.serveHTTP))
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Server) BaseURL() string {
|
||||
return s.URL
|
||||
}
|
||||
|
||||
func (s *Server) SetFixture(fixture Fixture) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.fixture = fixture
|
||||
}
|
||||
|
||||
func (s *Server) SetAPIError(path string, apiErr APIError) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.errors[path] = apiErr
|
||||
}
|
||||
|
||||
func (s *Server) SetRawResponse(path string, httpStatus int, body string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.rawPayload[path] = rawResponse{httpStatus: httpStatus, body: body}
|
||||
}
|
||||
|
||||
func (s *Server) serveHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
if raw, ok := s.rawPayload[r.URL.Path]; ok {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(raw.httpStatus)
|
||||
_, _ = w.Write([]byte(raw.body))
|
||||
return
|
||||
}
|
||||
|
||||
if apiErr, ok := s.errors[r.URL.Path]; ok {
|
||||
s.writeAPIError(w, apiErr)
|
||||
return
|
||||
}
|
||||
|
||||
switch {
|
||||
case r.URL.Path == "/dns":
|
||||
s.writeJSON(w, http.StatusOK, map[string]any{"statusCode": 200, "domains": s.fixture.Domains})
|
||||
return
|
||||
case strings.HasPrefix(r.URL.Path, "/dns/getroot/"):
|
||||
hostname := strings.TrimPrefix(r.URL.Path, "/dns/getroot/")
|
||||
root, ok := s.fixture.RootsByHostname[hostname]
|
||||
if !ok {
|
||||
s.writeAPIError(w, APIError{HTTPStatus: http.StatusNotFound, StatusCode: 404, Type: "Not Found", Message: "hostname not found"})
|
||||
return
|
||||
}
|
||||
s.writeJSON(w, http.StatusOK, map[string]any{
|
||||
"statusCode": 200,
|
||||
"id": root.ID,
|
||||
"hostname": root.Hostname,
|
||||
"domainName": root.DomainName,
|
||||
"node": root.Node,
|
||||
})
|
||||
return
|
||||
case strings.HasSuffix(r.URL.Path, "/record"):
|
||||
domainID, err := domainIDFromPath(strings.TrimSuffix(r.URL.Path, "/record"))
|
||||
if err != nil {
|
||||
s.writeAPIError(w, APIError{HTTPStatus: http.StatusBadRequest, StatusCode: 400, Type: "Validation Exception", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
records, ok := s.fixture.RecordsByDomain[domainID]
|
||||
if !ok {
|
||||
records = []dynuclient.DNSRecord{}
|
||||
}
|
||||
s.writeJSON(w, http.StatusOK, map[string]any{"statusCode": 200, "dnsRecords": records})
|
||||
return
|
||||
default:
|
||||
domainID, err := domainIDFromPath(r.URL.Path)
|
||||
if err != nil {
|
||||
s.writeAPIError(w, APIError{HTTPStatus: http.StatusNotFound, StatusCode: 404, Type: "Not Found", Message: "endpoint not found"})
|
||||
return
|
||||
}
|
||||
for _, domain := range s.fixture.Domains {
|
||||
if domain.ID == domainID {
|
||||
payload := map[string]any{"statusCode": 200}
|
||||
b, _ := json.Marshal(domain)
|
||||
_ = json.Unmarshal(b, &payload)
|
||||
s.writeJSON(w, http.StatusOK, payload)
|
||||
return
|
||||
}
|
||||
}
|
||||
s.writeAPIError(w, APIError{HTTPStatus: http.StatusNotFound, StatusCode: 404, Type: "Not Found", Message: "domain not found"})
|
||||
}
|
||||
}
|
||||
|
||||
func domainIDFromPath(path string) (int64, error) {
|
||||
trimmed := strings.TrimPrefix(path, "/dns/")
|
||||
if trimmed == path {
|
||||
return 0, fmt.Errorf("invalid domain path: %s", path)
|
||||
}
|
||||
|
||||
id, err := strconv.ParseInt(trimmed, 10, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("invalid domain id: %s", trimmed)
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (s *Server) writeAPIError(w http.ResponseWriter, apiErr APIError) {
|
||||
if apiErr.HTTPStatus == 0 {
|
||||
apiErr.HTTPStatus = http.StatusBadRequest
|
||||
}
|
||||
if apiErr.StatusCode == 0 {
|
||||
apiErr.StatusCode = apiErr.HTTPStatus
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(apiErr.HTTPStatus)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"statusCode": apiErr.StatusCode,
|
||||
"exception": map[string]any{
|
||||
"statusCode": apiErr.StatusCode,
|
||||
"type": apiErr.Type,
|
||||
"message": apiErr.Message,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) writeJSON(w http.ResponseWriter, status int, payload any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(payload)
|
||||
}
|
||||
Reference in new issue
Block a user