Skip to content

Commit

Permalink
test(cors): enhance CORS wildcard handling tests (#145)
Browse files Browse the repository at this point in the history
- 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 <appleboy.tw@gmail.com>
  • Loading branch information
appleboy authored Mar 6, 2024
1 parent d5002f2 commit 90a7c66
Showing 1 changed file with 91 additions and 0 deletions.
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"},

This comment has been minimized.

Copy link
@aleksasiriski

aleksasiriski Mar 6, 2024

It's not at the end...

},
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)
}
})
}
}

0 comments on commit 90a7c66

Please sign in to comment.