Skip to content
quarry Artifact [156829126c]
Login

Artifact [156829126c]

Artifact 156829126cfe59880f02614b654f64a28b57c5d49c2f3bb4ffc09739ab3de442:


package notify

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

// An endpoint already carrying the forge's URL is left alone; nothing
// is created twice across restarts.
func TestEnsureReplyEndpointKeepsAnExistingOne(t *testing.T) {
	posts := 0
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch r.Method + " " + r.URL.Path {
		case "GET /v1/webhooks/endpoints":
			w.Write([]byte(`{"data":[{"id":"ep_7","url":"https://forge/api/v1/notify/events","active":true}]}`))
		case "POST /v1/webhooks/endpoints":
			posts++
			w.WriteHeader(http.StatusCreated)
		}
	}))
	t.Cleanup(srv.Close)
	ep, made, err := New(srv.URL, "k").EnsureReplyEndpoint(context.Background(),
		"https://forge/api/v1/notify/events", "s3cret")
	if err != nil || made || posts != 0 || ep.ID != "ep_7" {
		t.Fatalf("FAIL: made=%v posts=%d ep=%+v err=%v", made, posts, ep, err)
	}
	t.Log("ok: the existing endpoint is reused")
}

// A forge that has none registers one: active, at its own URL, with
// the secret it will verify against.
func TestEnsureReplyEndpointCreatesWithSecret(t *testing.T) {
	var got map[string]any
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch r.Method + " " + r.URL.Path {
		case "GET /v1/webhooks/endpoints":
			w.Write([]byte(`{"data":[]}`))
		case "POST /v1/webhooks/endpoints":
			b, _ := io.ReadAll(r.Body)
			json.Unmarshal(b, &got)
			w.WriteHeader(http.StatusCreated)
			w.Write([]byte(`{"id":"ep_1","url":"https://forge/api/v1/notify/events","active":true}`))
		}
	}))
	t.Cleanup(srv.Close)
	ep, made, err := New(srv.URL, "k").EnsureReplyEndpoint(context.Background(),
		"https://forge/api/v1/notify/events", "s3cret")
	if err != nil || !made || ep.ID != "ep_1" {
		t.Fatalf("FAIL: made=%v ep=%+v err=%v", made, ep, err)
	}
	if got["url"] != "https://forge/api/v1/notify/events" || got["active"] != true || got["secret"] != "s3cret" {
		t.Fatalf("FAIL: create request was %+v", got)
	}
	t.Log("ok: the endpoint is created active with the forge's secret")
}

// A disabled client registers nothing and says so quietly.
func TestEnsureReplyEndpointNilClient(t *testing.T) {
	var c *Client
	if _, made, err := c.EnsureReplyEndpoint(context.Background(), "https://forge/x", "s"); err != nil || made {
		t.Fatalf("FAIL: %v %v", made, err)
	}
	t.Log("ok: no notify, no endpoint")
}