Files
tenant-registry/internal/erpsetup/erpsetup_test.go
T
Sharang ParnerkarandClaude Opus 5.5 bcb0895480
ci / shared (pull_request) Successful in 12s
ci / test (pull_request) Successful in 23m1s
ci / image (pull_request) Skipped
feat(erp): erpsetup for live ERPNext, reserved tenant slugs
cmd/erpsetup applies what the registry expects in a live ERPNext:
tenant_id/tenant_slug custom fields on Customer and Lead, the Usage
Record doctype, and Frappe Webhooks (Sales Order submit, Sales
Invoice overdue, Payment Entry submit, Subscription cancelled) signed
with the registry's webhook secret. It checks before it creates, so it
can run again at any time, and -dry-run only reports. It ships in the
image as /erpsetup.

Tenant creation refuses slugs the portal serves itself (admin, start,
install, docs, …), mirroring the portal's signup check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-09-23 18:18:13 +02:00

185 lines
5.2 KiB
Go

package erpsetup
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"testing"
)
// fakeFrappe keeps named docs per doctype and a list of webhooks.
type fakeFrappe struct {
mu sync.Mutex
docs map[string]map[string]bool
webhooks []map[string]any
posts int
auth string
}
func newFake() *fakeFrappe { return &fakeFrappe{docs: map[string]map[string]bool{}} }
func (f *fakeFrappe) ServeHTTP(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
f.auth = r.Header.Get("Authorization")
if r.Header.Get("Authorization") != "token k:s" {
w.WriteHeader(http.StatusUnauthorized)
return
}
rest := strings.TrimPrefix(r.URL.Path, "/api/resource/")
parts := strings.SplitN(rest, "/", 2)
doctype, _ := url.PathUnescape(parts[0])
switch {
case doctype == "Webhook" && r.Method == http.MethodGet:
out := []map[string]any{}
for _, wh := range f.webhooks {
out = append(out, map[string]any{"name": wh["name"], "webhook_json": wh["webhook_json"]})
}
_ = json.NewEncoder(w).Encode(map[string]any{"data": out})
case doctype == "Webhook" && r.Method == http.MethodPost:
var doc map[string]any
_ = json.NewDecoder(r.Body).Decode(&doc)
doc["name"] = "HOOK-" + string(rune('A'+len(f.webhooks)))
f.webhooks = append(f.webhooks, doc)
f.posts++
_ = json.NewEncoder(w).Encode(map[string]any{"data": doc})
case r.Method == http.MethodGet && len(parts) == 2:
name, _ := url.PathUnescape(parts[1])
if f.docs[doctype][name] {
_, _ = io.WriteString(w, `{"data":{}}`)
return
}
w.WriteHeader(http.StatusNotFound)
case r.Method == http.MethodPost:
var doc map[string]any
_ = json.NewDecoder(r.Body).Decode(&doc)
if f.docs[doctype] == nil {
f.docs[doctype] = map[string]bool{}
}
f.docs[doctype][doc["name"].(string)] = true
f.posts++
_, _ = io.WriteString(w, `{"data":{}}`)
default:
w.WriteHeader(http.StatusTeapot)
}
}
func cfg(url string) Config {
return Config{BaseURL: url + "/", APIKey: "k", APISecret: "s", WebhookURL: "https://registry/v1/internal/erp/webhook", WebhookSecret: "whs"}
}
func TestRunCreatesThenIsIdempotent(t *testing.T) {
f := newFake()
srv := httptest.NewServer(f)
defer srv.Close()
steps, err := Run(context.Background(), cfg(srv.URL))
if err != nil {
t.Fatal(err)
}
if len(steps) != 9 || f.posts != 9 {
t.Fatalf("first run: %d steps, %d creates; want 9/9: %+v", len(steps), f.posts, steps)
}
for _, s := range steps {
if s.Result != "created" {
t.Errorf("%s: %s", s.What, s.Result)
}
}
hook := f.webhooks[0]
if hook["enable_security"] != float64(1) || hook["webhook_secret"] != "whs" || hook["request_url"] != "https://registry/v1/internal/erp/webhook" {
t.Errorf("webhook security/url not set: %v", hook)
}
steps, err = Run(context.Background(), cfg(srv.URL))
if err != nil {
t.Fatal(err)
}
if f.posts != 9 {
t.Fatalf("second run created %d more docs", f.posts-9)
}
for _, s := range steps {
if !strings.HasPrefix(s.Result, "exists") {
t.Errorf("second run %s: %s", s.What, s.Result)
}
}
}
func TestDryRunChangesNothing(t *testing.T) {
f := newFake()
srv := httptest.NewServer(f)
defer srv.Close()
c := cfg(srv.URL)
c.DryRun = true
var logged int
c.Log = func(string, ...any) { logged++ }
steps, err := Run(context.Background(), c)
if err != nil {
t.Fatal(err)
}
if f.posts != 0 || logged != len(steps) {
t.Fatalf("dry run posted %d docs, logged %d of %d", f.posts, logged, len(steps))
}
for _, s := range steps {
if s.Result != "would create" {
t.Errorf("%s: %s", s.What, s.Result)
}
}
}
func TestLeadDoctypeIsConfigurable(t *testing.T) {
f := newFake()
srv := httptest.NewServer(f)
defer srv.Close()
c := cfg(srv.URL)
c.LeadDoctype = "CRM Lead"
if _, err := Run(context.Background(), c); err != nil {
t.Fatal(err)
}
if !f.docs["Custom Field"]["CRM Lead-tenant_id"] {
t.Fatalf("no CRM Lead field: %v", f.docs["Custom Field"])
}
}
func TestRequiredConfigAndAuthErrors(t *testing.T) {
if _, err := Run(context.Background(), Config{}); err == nil {
t.Fatal("empty config accepted")
}
if _, err := Run(context.Background(), Config{BaseURL: "x", APIKey: "k", APISecret: "s"}); err == nil {
t.Fatal("missing webhook config accepted")
}
srv := httptest.NewServer(newFake())
defer srv.Close()
c := cfg(srv.URL)
c.APISecret = "wrong"
if _, err := Run(context.Background(), c); err == nil || !strings.Contains(err.Error(), "API key") {
t.Fatalf("want an auth error, got %v", err)
}
}
func TestUnexpectedStatusStops(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
_, _ = io.WriteString(w, strings.Repeat("x", 400))
}))
defer srv.Close()
if _, err := Run(context.Background(), cfg(srv.URL)); err == nil {
t.Fatal("500 accepted")
}
}
func TestWebhookBodiesAreValidJSONShapes(t *testing.T) {
for _, w := range webhooks("u", "s") {
if !strings.Contains(w.JSON, `"event":"`+w.Event+`"`) || !strings.Contains(w.JSON, `"modified":"{{ doc.modified }}"`) {
t.Errorf("%s: template lacks event or modified: %s", w.Event, w.JSON)
}
if w.URL != "u" || w.Secret != "s" {
t.Errorf("%s: url/secret not filled", w.Event)
}
}
}