fix: improvate initFormCache test coverage

This commit is contained in:
Leonardo Araujo 2023-08-12 20:28:10 -03:00
parent a63d776dd4
commit 8d7e2a0bda
3 changed files with 68 additions and 0 deletions

View File

@ -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

View File

@ -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{

View File

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