59 lines
1.6 KiB
Go
59 lines
1.6 KiB
Go
package forms_test
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/url"
|
|
"strings"
|
|
"testing"
|
|
|
|
"git.tavo.one/tavo/axiom/forms"
|
|
)
|
|
|
|
func TestParseFormToStruct(t *testing.T) {
|
|
type MyForm struct {
|
|
Name string `form:"name" fmt:"trim" validate:"nonzero,minlen:5"`
|
|
Email string `form:"email" fmt:"trim,lower"`
|
|
Tags []string `form:"tags" fmt:"trim"`
|
|
Enabled bool `form:"enabled"`
|
|
Age int `form:"age"`
|
|
Scores []float64 `form:"scores"`
|
|
}
|
|
|
|
data := url.Values{}
|
|
data.Set("name", " Alice ")
|
|
data.Set("email", "ALICE@EXAMPLE.COM")
|
|
data.Add("tags", " go ")
|
|
data.Add("tags", "web")
|
|
data.Set("enabled", "true")
|
|
data.Set("age", "28")
|
|
data.Add("scores", "98.6")
|
|
data.Add("scores", "80.6")
|
|
|
|
r := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(data.Encode()))
|
|
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
|
|
form, err := forms.FormToStruct[MyForm](r)
|
|
if err != nil {
|
|
t.Fatalf("FormToStruct returned error: %v", err)
|
|
}
|
|
|
|
if form.Name != "Alice" {
|
|
t.Errorf("expected Name to be 'Alice', got '%s'", form.Name)
|
|
}
|
|
if form.Email != "alice@example.com" {
|
|
t.Errorf("expected Email to be 'alice@example.com', got '%s'", form.Email)
|
|
}
|
|
if len(form.Tags) != 2 || form.Tags[0] != "go" || form.Tags[1] != "web" {
|
|
t.Errorf("expected Tags to be ['go', 'web'], got %v", form.Tags)
|
|
}
|
|
if !form.Enabled {
|
|
t.Errorf("expected Enabled to be true")
|
|
}
|
|
if form.Age != 28 {
|
|
t.Errorf("expected Age to be 28, got %d", form.Age)
|
|
}
|
|
if len(form.Scores) != 2 || form.Scores[0] != 98.6 || form.Scores[1] != 80.6 {
|
|
t.Errorf("expected Scores to be [98.6, 80.6], got %v", form.Scores)
|
|
}
|
|
}
|