summaryrefslogtreecommitdiff
path: root/internal/control/dns_test.go
blob: cf446396d91d43c6e9103722da3cd7844583e5d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package control

import (
	"context"
	"encoding/json"
	"io"
	"net/http"
	"strings"
	"testing"
)

func TestPorkbunEnsureRandomARecord(t *testing.T) {
	t.Parallel()

	retrieveCalls := 0
	client := &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
		recorder := map[string]any{}
		switch {
		case strings.Contains(r.URL.Path, "/dns/retrieveByNameType/"):
			retrieveCalls++
			recorder = map[string]any{
				"status":  "SUCCESS",
				"records": []map[string]any{},
			}
		case strings.Contains(r.URL.Path, "/dns/create/"):
			recorder = map[string]any{
				"status": "SUCCESS",
				"id":     "123",
			}
		default:
			t.Fatalf("unexpected path %s", r.URL.Path)
		}
		body, _ := json.Marshal(recorder)
		return &http.Response{
			StatusCode: http.StatusOK,
			Header:     make(http.Header),
			Body:       io.NopCloser(strings.NewReader(string(body))),
		}, nil
	})}

	clientAPI := PorkbunClient{APIKey: "a", SecretAPIKey: "b", HTTPClient: client}
	name, err := clientAPI.EnsureRandomARecord(context.Background(), "em-sysadmin.xyz", "vpn", "203.0.113.10", 600)
	if err != nil {
		t.Fatalf("EnsureRandomARecord error = %v", err)
	}
	if !strings.HasSuffix(name, ".em-sysadmin.xyz") {
		t.Fatalf("expected fqdn suffix, got %q", name)
	}
	if retrieveCalls == 0 {
		t.Fatal("expected retrieve call")
	}
}

type roundTripFunc func(*http.Request) (*http.Response, error)

func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) {
	return f(r)
}