main pico / cmd / scripts / sync-certs / main_test.go
Eric Bower  ·  2026-09-10
 1package main
 2
 3import (
 4	"encoding/json"
 5	"os"
 6	"path/filepath"
 7	"testing"
 8	"time"
 9)
10
11func TestSplitDirectoryKey(t *testing.T) {
12	tests := []struct {
13		key       string
14		baseIsDir bool
15		wantDir   string
16		wantBase  string
17	}{
18		{
19			key:       "caddy/certificates/acme.org/site.com/site.com.crt",
20			baseIsDir: false,
21			wantDir:   "caddy/certificates/acme.org/site.com",
22			wantBase:  "site.com.crt",
23		},
24		{
25			key:       "caddy/certificates/acme.org/site.com",
26			baseIsDir: true,
27			wantDir:   "caddy/certificates/acme.org",
28			wantBase:  "site.com/",
29		},
30		{
31			key:       "caddy",
32			baseIsDir: true,
33			wantDir:   ".",
34			wantBase:  "caddy/",
35		},
36	}
37
38	for _, tt := range tests {
39		gotDir, gotBase := splitDirectoryKey(tt.key, tt.baseIsDir)
40		if gotDir != tt.wantDir || gotBase != tt.wantBase {
41			t.Errorf("splitDirectoryKey(%q, %v) = (%q, %q), want (%q, %q)",
42				tt.key, tt.baseIsDir, gotDir, gotBase, tt.wantDir, tt.wantBase)
43		}
44	}
45}
46
47func TestStorageDataJSON(t *testing.T) {
48	now := time.Now().UTC().Truncate(time.Second)
49	sd := StorageData{
50		Value:       []byte("test-cert-data"),
51		Modified:    now,
52		Size:        14,
53		Compression: 0,
54		Encryption:  0,
55	}
56
57	data, err := json.Marshal(sd)
58	if err != nil {
59		t.Fatalf("marshal error: %v", err)
60	}
61
62	var parsed map[string]any
63	if err := json.Unmarshal(data, &parsed); err != nil {
64		t.Fatalf("unmarshal error: %v", err)
65	}
66
67	// In Go json.Marshal, []byte encodes as base64 string
68	if val, ok := parsed["value"].(string); !ok || val == "" {
69		t.Errorf("expected base64 string for value, got: %v", parsed["value"])
70	}
71	if size, ok := parsed["size"].(float64); !ok || int64(size) != 14 {
72		t.Errorf("expected size 14, got: %v", parsed["size"])
73	}
74}
75
76func TestFindCaddyRoots(t *testing.T) {
77	tmp := t.TempDir()
78
79	// 1. Root with certificates/
80	caddy1 := filepath.Join(tmp, "caddy1")
81	if err := os.MkdirAll(filepath.Join(caddy1, "certificates"), 0755); err != nil {
82		t.Fatal(err)
83	}
84
85	// 2. Nested with data/caddy/acme/
86	service2 := filepath.Join(tmp, "service2", "data", "caddy")
87	if err := os.MkdirAll(filepath.Join(service2, "acme"), 0755); err != nil {
88		t.Fatal(err)
89	}
90
91	roots := findCaddyRoots(tmp)
92	if len(roots) != 2 {
93		t.Errorf("expected 2 roots, got %d: %v", len(roots), roots)
94	}
95}