From 8d7e2a0bdad24c00e052b6888a81f889f09f73a9 Mon Sep 17 00:00:00 2001 From: Leonardo Araujo Date: Sat, 12 Aug 2023 20:28:10 -0300 Subject: [PATCH] fix: improvate initFormCache test coverage --- context.go | 1 + context_test.go | 53 +++++++++++++++++++++++++++++++++++++++++++++++++ gin_test.go | 14 +++++++++++++ 3 files changed, 68 insertions(+) diff --git a/context.go b/context.go index e3d7ed18..bab4cb46 100644 --- a/context.go +++ b/context.go @@ -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 diff --git a/context_test.go b/context_test.go index 85366ea0..4b26a700 100644 --- a/context_test.go +++ b/context_test.go @@ -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{ diff --git a/gin_test.go b/gin_test.go index 8825ac7e..a6429b03 100644 --- a/gin_test.go +++ b/gin_test.go @@ -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) + } +}