[#2763] fixed multipart/form-data array value bind

This commit is contained in:
Gani Georgiev
2023-06-26 12:30:51 +03:00
parent bd94940eef
commit 9cba6ac386
2 changed files with 101 additions and 24 deletions

View File

@@ -1,6 +1,7 @@
package rest_test
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
@@ -16,31 +17,40 @@ func TestBindBody(t *testing.T) {
scenarios := []struct {
body io.Reader
contentType string
result map[string]string
expectBody string
expectError bool
}{
{
strings.NewReader(""),
echo.MIMEApplicationJSON,
map[string]string{},
`{}`,
false,
},
{
strings.NewReader(`{"test":"invalid`),
echo.MIMEApplicationJSON,
map[string]string{},
`{}`,
true,
},
{
strings.NewReader(`{"test":"test123"}`),
strings.NewReader(`{"test":123}`),
echo.MIMEApplicationJSON,
map[string]string{"test": "test123"},
`{"test":123}`,
false,
},
{
strings.NewReader(url.Values{"test": []string{"test123"}}.Encode()),
strings.NewReader(
url.Values{
"string": []string{"str"},
"stings": []string{"str1", "str2"},
"number": []string{"123"},
"numbers": []string{"123", "456"},
"bool": []string{"true"},
"bools": []string{"true", "false"},
}.Encode(),
),
echo.MIMEApplicationForm,
map[string]string{"test": "test123"},
`{"bool":true,"bools":["true","false"],"number":123,"numbers":["123","456"],"stings":["str1","str2"],"string":"str"}`,
false,
},
}
@@ -52,25 +62,22 @@ func TestBindBody(t *testing.T) {
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
result := map[string]string{}
err := rest.BindBody(c, &result)
data := map[string]any{}
err := rest.BindBody(c, &data)
if err == nil && scenario.expectError {
t.Errorf("(%d) Expected error, got nil", i)
hasErr := err != nil
if hasErr != scenario.expectError {
t.Errorf("[%d] Expected hasErr %v, got %v", i, scenario.expectError, hasErr)
}
if err != nil && !scenario.expectError {
t.Errorf("(%d) Expected nil, got error %v", i, err)
rawBody, err := json.Marshal(data)
if err != nil {
t.Errorf("[%d] Failed to marshal binded body: %v", i, err)
}
if len(result) != len(scenario.result) {
t.Errorf("(%d) Expected %v, got %v", i, scenario.result, result)
}
for k, v := range result {
if sv, ok := scenario.result[k]; !ok || v != sv {
t.Errorf("(%d) Expected value %v for key %s, got %v", i, sv, k, v)
}
if scenario.expectBody != string(rawBody) {
t.Errorf("[%d] Expected body \n%s, \ngot \n%s", i, scenario.expectBody, rawBody)
}
}
}