diff --git a/cors_test.go b/cors_test.go index a6c69ad..687ac0d 100644 --- a/cors_test.go +++ b/cors_test.go @@ -4,6 +4,7 @@ import ( "context" "net/http" "net/http/httptest" + "reflect" "strings" "testing" "time" @@ -462,3 +463,93 @@ func TestParseWildcardRules_InvalidWildcard(t *testing.T) { config.parseWildcardRules() }) } + +func TestParseWildcardRules(t *testing.T) { + tests := []struct { + name string + config Config + expectedResult [][]string + expectPanic bool + }{ + { + name: "Wildcard not allowed", + config: Config{ + AllowWildcard: false, + AllowOrigins: []string{"http://example.com", "https://*.domain.com"}, + }, + expectedResult: nil, + expectPanic: false, + }, + { + name: "No wildcards", + config: Config{ + AllowWildcard: true, + AllowOrigins: []string{"http://example.com", "https://example.com"}, + }, + expectedResult: nil, + expectPanic: false, + }, + { + name: "Single wildcard at the end", + config: Config{ + AllowWildcard: true, + AllowOrigins: []string{"http://*.example.com"}, + }, + expectedResult: [][]string{{"http://", ".example.com"}}, + expectPanic: false, + }, + { + name: "Single wildcard at the beginning", + config: Config{ + AllowWildcard: true, + AllowOrigins: []string{"*.example.com"}, + }, + expectedResult: [][]string{{"*", ".example.com"}}, + expectPanic: false, + }, + { + name: "Single wildcard in the middle", + config: Config{ + AllowWildcard: true, + AllowOrigins: []string{"http://example.*.com"}, + }, + expectedResult: [][]string{{"http://example.", ".com"}}, + expectPanic: false, + }, + { + name: "Multiple wildcards should panic", + config: Config{ + AllowWildcard: true, + AllowOrigins: []string{"http://*.*.com"}, + }, + expectedResult: nil, + expectPanic: true, + }, + { + name: "Single wildcard in the end", + config: Config{ + AllowWildcard: true, + AllowOrigins: []string{"http://example.com/*"}, + }, + expectedResult: [][]string{{"http://example.com/", "*"}}, + expectPanic: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if tt.expectPanic { + defer func() { + if r := recover(); r == nil { + t.Errorf("The code did not panic") + } + }() + } + + result := tt.config.parseWildcardRules() + if !tt.expectPanic && !reflect.DeepEqual(result, tt.expectedResult) { + t.Errorf("Name: %v, Expected %v, got %v", tt.name, tt.expectedResult, result) + } + }) + } +}