Skip to content

Commit

Permalink
fix: improvate initFormCache test coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
araujo88 committed Aug 12, 2023
1 parent a63d776 commit 8d7e2a0
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
1 change: 1 addition & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -551,6 +551,7 @@ func (c *Context) initFormCache() {
if err := c.Request.ParseMultipartForm(c.engine.MaxMultipartMemory); err != nil {
if !errors.Is(err, http.ErrNotMultipart) {
debugPrint("error on parse multipart form array: %v", err)
return
}
}
c.formCache = c.Request.PostForm
Expand Down
53 changes: 53 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -672,6 +672,59 @@ func TestContextPostFormMultipart(t *testing.T) {
assert.Equal(t, 0, len(dicts))
}

func TestInitFormCache(t *testing.T) {
tests := []struct {
name string
cacheEnabled bool
existingCache bool
request *http.Request
expectFormCache bool
}{
{"Cache disabled", false, false, nil, false},
{"Existing cache", true, true, nil, false},
{"Nil request", true, false, nil, false},
{"Successful parsing", true, false, &http.Request{Method: "POST"}, true},
}

// Create a specific request with an error other than ErrNotMultipart
req, err := http.NewRequest("POST", "/", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Content-Type", "multipart/form-data")
tests = append(tests, struct {
name string
cacheEnabled bool
existingCache bool
request *http.Request
expectFormCache bool
}{"Error other than ErrNotMultipart", true, false, req, false})

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
engine := &Engine{
cacheConfig: CacheConfig{EnableFormCache: tt.cacheEnabled},
}

c := &Context{
engine: engine,
}

if tt.existingCache {
c.formCache = make(url.Values)
}

c.Request = tt.request

c.initFormCache()

if tt.expectFormCache && c.formCache == nil {
t.Errorf("Expected formCache to be initialized, but it was nil")
}
})
}
}

func TestSetForm(t *testing.T) {
req, _ := http.NewRequest("POST", "/", nil)
c := &Context{
Expand Down
14 changes: 14 additions & 0 deletions gin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -696,3 +696,17 @@ func assertRoutePresent(t *testing.T, gotRoutes RoutesInfo, wantRoute RouteInfo)

func handlerTest1(c *Context) {}
func handlerTest2(c *Context) {}

func TestSetCacheConfig(t *testing.T) {
engine := &Engine{}
config := CacheConfig{
EnableFormCache: true,
// Other fields can be filled as needed
}

engine.SetCacheConfig(config)

if !reflect.DeepEqual(engine.cacheConfig, config) {
t.Errorf("Expected engine.cacheConfig to be %v, but got %v", config, engine.cacheConfig)
}
}

0 comments on commit 8d7e2a0

Please sign in to comment.