ovh-dns-update/main_test.go

99 lines
2.6 KiB
Go
Raw Normal View History

2023-08-18 05:40:33 -04:00
// SPDX-FileCopyrightText: 2023 Olivier Charvin
// SPDX-License-Identifier: CC0-1.0
package main
import (
"encoding/json"
"fmt"
2023-08-18 05:40:33 -04:00
"io"
"net/http"
"net/http/httptest"
"os"
2023-08-18 05:40:33 -04:00
"testing"
"github.com/sethvargo/go-githubactions"
)
func TestRun(t *testing.T) {
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
default:
msg := fmt.Sprintf("unexpected request on %s", r.URL.Path)
http.Error(w, msg, http.StatusBadRequest)
t.Error(msg)
2023-08-18 05:40:33 -04:00
case "/auth/time":
case "/domain/zone/FAKEVALUE-INPUT_DOMAIN/record/FAKEVALUE-INPUT_RECORD-ID":
buf, err := io.ReadAll(r.Body)
if err != nil {
msg := fmt.Sprintf("could not read request body: %v", err)
http.Error(w, msg, http.StatusBadRequest)
t.Error(msg)
2023-08-18 05:40:33 -04:00
}
if string(buf) != `{"subDomain":"FAKEVALUE-INPUT_SUBDOMAIN","target":"\"FAKEVALUE-INPUT_VALUE\""}` {
msg := fmt.Sprintf("unexpected body: %s", string(buf))
http.Error(w, msg, http.StatusBadRequest)
t.Error(msg)
2023-08-18 05:40:33 -04:00
}
}
}))
t.Cleanup(s.Close)
action := githubactions.New(githubactions.WithGetenv(func(key string) string {
switch key {
case "INPUT_OVH-ENDPOINT":
return "http://" + s.Listener.Addr().String()
}
return "FAKEVALUE-" + key
}))
err := run(action)
if err != nil {
t.Fatal(err)
}
// for action testing (see .forgejo/workflows/pr.yml)
if os.Getenv("ACTION_TESTING") == "1" {
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
default:
msg := fmt.Sprintf("unexpected request on %s", r.URL.Path)
http.Error(w, msg, http.StatusBadRequest)
t.Error(msg)
return
case "/auth/time":
case "/domain/zone/example.org/record/12345":
var body struct {
SubDomain string `json:"subDomain"`
Target string `json:"target"`
}
err := json.NewDecoder(r.Body).Decode(&body)
if err != nil {
msg := fmt.Sprintf("could not decode request body: %v", err)
http.Error(w, msg, http.StatusBadRequest)
t.Error(msg)
return
}
if body.SubDomain != "_release" {
msg := fmt.Sprintf("unexpected subdomain: %s", body.SubDomain)
http.Error(w, msg, http.StatusBadRequest)
t.Error(msg)
return
}
err = os.WriteFile("dns.txt", []byte(body.Target), 0o644)
if err != nil {
msg := fmt.Sprintf("could write dns.txt: %v", err)
http.Error(w, msg, http.StatusInternalServerError)
t.Error(msg)
return
}
}
}))
t.Cleanup(s.Close)
githubactions.SetOutput("OVH_ENDPOINT", "http://"+s.Listener.Addr().String())
err = os.Remove("delete_me_when_ready")
if err != nil {
t.Fatal(err)
}
select {}
}
2023-08-18 05:40:33 -04:00
}