udemy-go-web-1/internal/forms/forms_test.go
2024-07-02 21:48:00 +02:00

132 lines
2.3 KiB
Go

package forms
import (
"net/http/httptest"
"net/url"
"testing"
)
func TestForms_Valid(t *testing.T) {
r := httptest.NewRequest("POST", "/test-url", nil)
form := New(r.PostForm)
isValid := form.Valid()
if !isValid {
t.Error("got invalid when should have been valid")
}
}
func TestForms_Required(t *testing.T) {
r := httptest.NewRequest("POST", "/test-url", nil)
form := New(r.PostForm)
form.Required("a", "b", "c")
if form.Valid() {
t.Error("required fields are not given, should be invalid")
}
postData := url.Values{}
postData.Add("a", "a")
postData.Add("b", "a")
postData.Add("c", "a")
r = httptest.NewRequest("POST", "/test-url", nil)
r.PostForm = postData
form = New(r.PostForm)
form.Required("a", "b", "c")
if !form.Valid() {
t.Error("required fields are given, should be valid")
}
}
func TestForms_Has(t *testing.T) {
postData := url.Values{}
form := New(postData)
if form.Has("a") {
t.Error("the field should not exist")
}
postData = url.Values{}
postData.Add("a", "a")
form = New(postData)
if !form.Has("a") {
t.Error("the field should exist")
}
}
func TestForms_MinLength(t *testing.T) {
postData := url.Values{}
form := New(postData)
if form.MinLength("a", 3) {
t.Error("the field should not exist")
}
errMsg := form.Errors.Get("a")
if errMsg != "This field must have at least 3 letters" {
t.Error("should have an errMsg")
}
if form.Valid() {
t.Error("should be invalid")
}
postData = url.Values{}
postData.Add("a", "ab")
postData.Add("b", "abc")
form = New(postData)
if form.MinLength("a", 3) {
t.Error("the field is shorter than 3 chars")
}
if !form.MinLength("b", 3) {
t.Error("the field is equal to 3 chars")
}
if form.Valid() {
t.Error("should be invalid")
}
}
func TestForms_IsEmail(t *testing.T) {
postData := url.Values{}
form := New(postData)
form.IsEmail("a")
if form.Valid() {
t.Error("email should not exit")
}
postData = url.Values{}
postData.Add("a", "a@a.com")
form = New(postData)
form.IsEmail("a")
errMsg := form.Errors.Get("a")
if errMsg != "" {
t.Error("should not have an errMsg")
}
if !form.Valid() {
t.Error("should be a valid email")
}
postData = url.Values{}
postData.Add("a", "a@.com")
form = New(postData)
form.IsEmail("a")
if form.Valid() {
t.Error("Should not be a valid email")
}
}