A community based topic aggregation platform built on atproto
1package did 2 3import ( 4 "strings" 5 "testing" 6) 7 8func TestGenerateCommunityDID(t *testing.T) { 9 tests := []struct { 10 name string 11 isDevEnv bool 12 plcDirectoryURL string 13 want string // prefix we expect 14 }{ 15 { 16 name: "generates did:plc in dev mode", 17 isDevEnv: true, 18 plcDirectoryURL: "https://plc.directory", 19 want: "did:plc:", 20 }, 21 { 22 name: "generates did:plc in prod mode", 23 isDevEnv: false, 24 plcDirectoryURL: "https://plc.directory", 25 want: "did:plc:", 26 }, 27 } 28 29 for _, tt := range tests { 30 t.Run(tt.name, func(t *testing.T) { 31 g := NewGenerator(tt.isDevEnv, tt.plcDirectoryURL) 32 did, err := g.GenerateCommunityDID() 33 34 if err != nil { 35 t.Fatalf("GenerateCommunityDID() error = %v", err) 36 } 37 38 if !strings.HasPrefix(did, tt.want) { 39 t.Errorf("GenerateCommunityDID() = %v, want prefix %v", did, tt.want) 40 } 41 42 // Verify it's a valid DID 43 if !ValidateDID(did) { 44 t.Errorf("Generated DID failed validation: %v", did) 45 } 46 }) 47 } 48} 49 50func TestGenerateCommunityDID_Uniqueness(t *testing.T) { 51 g := NewGenerator(true, "https://plc.directory") 52 53 // Generate 100 DIDs and ensure they're all unique 54 dids := make(map[string]bool) 55 for i := 0; i < 100; i++ { 56 did, err := g.GenerateCommunityDID() 57 if err != nil { 58 t.Fatalf("GenerateCommunityDID() error = %v", err) 59 } 60 61 if dids[did] { 62 t.Errorf("Duplicate DID generated: %v", did) 63 } 64 dids[did] = true 65 } 66} 67 68func TestValidateDID(t *testing.T) { 69 tests := []struct { 70 name string 71 did string 72 want bool 73 }{ 74 { 75 name: "valid did:plc", 76 did: "did:plc:z72i7hdynmk6r22z27h6tvur", 77 want: true, 78 }, 79 { 80 name: "valid did:plc with base32", 81 did: "did:plc:abc123xyz", 82 want: true, 83 }, 84 { 85 name: "valid did:web", 86 did: "did:web:coves.social", 87 want: true, 88 }, 89 { 90 name: "valid did:web with path", 91 did: "did:web:coves.social:community:gaming", 92 want: true, 93 }, 94 { 95 name: "invalid: missing prefix", 96 did: "plc:abc123", 97 want: false, 98 }, 99 { 100 name: "invalid: missing method", 101 did: "did::abc123", 102 want: false, 103 }, 104 { 105 name: "invalid: missing identifier", 106 did: "did:plc:", 107 want: false, 108 }, 109 { 110 name: "invalid: only did", 111 did: "did:", 112 want: false, 113 }, 114 { 115 name: "invalid: empty string", 116 did: "", 117 want: false, 118 }, 119 } 120 121 for _, tt := range tests { 122 t.Run(tt.name, func(t *testing.T) { 123 if got := ValidateDID(tt.did); got != tt.want { 124 t.Errorf("ValidateDID(%v) = %v, want %v", tt.did, got, tt.want) 125 } 126 }) 127 } 128}