From 90a7c66401d66f6c7ac120dbe1ae7b63e7e4271f Mon Sep 17 00:00:00 2001 From: Bo-Yi Wu Date: Wed, 6 Mar 2024 14:29:04 +0800 Subject: [PATCH] test(cors): enhance CORS wildcard handling tests (#145) - Import the `reflect` package in `cors_test.go` - Add new test cases for parsing wildcard rules in CORS configuration - Implement tests to check for panic on multiple wildcards and validate expected results for various wildcard scenarios ref: #106 Signed-off-by: Bo-Yi Wu --- cors_test.go | 91 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) 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) + } + }) + } +}