Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test(cors): enhance CORS wildcard handling tests #145

Merged
merged 1 commit into from
Mar 6, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions cors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -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)
}
})
}
}
Loading