Files
Mateusz Gruszczyński 8c4d463f1e
Go quality gates / test (push) Waiting to run
first commit
2026-11-30 11:37:40 +01:00

102 lines
2.8 KiB
Go

package easydns
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
func TestGeneratedTokenAndETag(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "control.token")
if e := os.WriteFile(file, []byte("generated-test-token\n"), 0600); e != nil {
t.Fatal(e)
}
var got string
var match string
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got = r.Header.Get("Authorization")
match = r.Header.Get("If-Match")
if r.Method != http.MethodPut || r.URL.Path != "/api/v1/zones/example.com./records/record-id" {
t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
}
if got != "Bearer generated-test-token" {
t.Errorf("wrong bearer token: %q", got)
}
if match != "\"2026113001\"" {
t.Errorf("missing serial guard: %q", match)
}
var body struct {
Name string `json:"name"`
Type string `json:"type"`
TTL int `json:"ttl"`
Data string `json:"data"`
}
if e := json.NewDecoder(r.Body).Decode(&body); e != nil {
t.Error(e)
}
if body.Name != "www" || body.Type != "A" || body.TTL != 300 || body.Data != "192.0.2.10" {
t.Errorf("wrong payload: %+v", body)
}
w.Header().Set("ETag", "\"2026113002\"")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"ok":true}`))
}))
defer ts.Close()
c, e := New(ts.URL, file, "")
if e != nil {
t.Fatal(e)
}
var out struct {
OK bool `json:"ok"`
}
e = c.Write(context.Background(), "PUT", "/api/v1/zones/example.com./records/record-id", map[string]any{"name": "www", "type": "A", "ttl": 300, "data": "192.0.2.10"}, "\"2026113001\"", &out)
if e != nil {
t.Fatal(e)
}
if !out.OK {
t.Fatal("response not decoded")
}
if got == "" || match == "" {
t.Fatal("request not received")
}
}
func TestErrorEnvelope(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "control.token")
_ = os.WriteFile(file, []byte("a"), 0600)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(412)
_, _ = w.Write([]byte(`{"error":{"status":412,"message":"zone serial changed"}}`))
}))
defer ts.Close()
c, _ := New(ts.URL, file, "")
_, e := c.Get(context.Background(), "/api/v1/zones/example.com.", nil)
apiErr, ok := e.(*Error)
if !ok || apiErr.Status != 412 || !strings.Contains(apiErr.Message, "zone serial changed") {
t.Fatalf("wrong REST error: %#v", e)
}
}
func TestNoUnknownAPIPaths(t *testing.T) {
c, e := New("http://127.0.0.1:9953", "/does/not/matter", "")
if e != nil {
t.Fatal(e)
}
_, e = c.Get(context.Background(), "/new-not-real-endpoint", nil)
if e == nil || !strings.Contains(e.Error(), "not permitted") {
t.Fatalf("unexpected: %v", e)
}
}
func TestInvalidBaseURL(t *testing.T) {
_, e := New("file:///etc/shadow", "/tmp/token", "")
if e == nil {
t.Fatal("invalid URL accepted")
}
}