Gitfed
bastien-mrq/gitfed / cmd / gitfed-install / manifests_test.go
package main

import (
	"encoding/json"
	"strings"
	"testing"
)

func TestRenderConfigMapEmbedsValidJSON(t *testing.T) {
	out, err := renderConfigMap(instanceConfig{Domain: "git.example.com", Contact: "admin@example.com"})
	if err != nil {
		t.Fatalf("render: %v", err)
	}
	if !strings.Contains(out, "git.example.com") {
		t.Errorf("rendered configmap missing domain:\n%s", out)
	}

	// Extract the embedded JSON block (everything after "gitfed.json: |")
	// and check it actually parses — a template typo here would otherwise
	// only surface once it's already been applied to a live cluster.
	_, block, ok := strings.Cut(out, "gitfed.json: |\n")
	if !ok {
		t.Fatalf("rendered configmap has no gitfed.json block:\n%s", out)
	}
	var lines []string
	for _, l := range strings.Split(block, "\n") {
		lines = append(lines, strings.TrimPrefix(l, "    "))
	}
	jsonText := strings.Join(lines, "\n")

	var cfg map[string]any
	if err := json.Unmarshal([]byte(jsonText), &cfg); err != nil {
		t.Fatalf("embedded gitfed.json doesn't parse: %v\n---\n%s", err, jsonText)
	}
	if cfg["domain"] != "git.example.com" {
		t.Errorf("domain = %v, want git.example.com", cfg["domain"])
	}
	if cfg["contact"] != "admin@example.com" {
		t.Errorf("contact = %v, want admin@example.com", cfg["contact"])
	}
}

func TestRenderIngressUsesDomainTwice(t *testing.T) {
	out, err := renderIngress(instanceConfig{Domain: "git.example.com"})
	if err != nil {
		t.Fatalf("render: %v", err)
	}
	// hosts: [...] and host: both need the real domain, not the template
	// placeholder — a missed substitution here would silently issue a
	// certificate for the wrong name (or none at all).
	if got := strings.Count(out, "git.example.com"); got != 2 {
		t.Errorf("domain appears %d times in rendered ingress, want 2:\n%s", got, out)
	}
	if strings.Contains(out, "{{") {
		t.Errorf("unrendered template placeholder left in output:\n%s", out)
	}
}

func TestRenderClusterIssuerName(t *testing.T) {
	out, err := renderClusterIssuer(instanceConfig{Contact: "admin@example.com"})
	if err != nil {
		t.Fatalf("render: %v", err)
	}
	// ingress.yaml.tmpl's annotation hardcodes this exact name — if this
	// ever drifted, cert-manager just wouldn't fire for the ingress, with
	// no error message pointing at why.
	if !strings.Contains(out, "name: letsencrypt-prod") {
		t.Errorf("ClusterIssuer name isn't letsencrypt-prod:\n%s", out)
	}
	if !strings.Contains(out, "email: admin@example.com") {
		t.Errorf("rendered issuer missing contact email:\n%s", out)
	}
}