Aded test coverage for form submissions. Added validator as a service.

This commit is contained in:
mikestefanello 2021-12-25 00:11:59 -05:00
parent cc2f25431b
commit 6501621136
8 changed files with 111 additions and 30 deletions

View file

@ -63,8 +63,8 @@ func TestController_RenderPage(t *testing.T) {
p.Name = "home" p.Name = "home"
p.Layout = "main" p.Layout = "main"
p.Cache.Enabled = false p.Cache.Enabled = false
p.Headers["a"] = "b" p.Headers["A"] = "b"
p.Headers["c"] = "d" p.Headers["C"] = "d"
p.StatusCode = http.StatusCreated p.StatusCode = http.StatusCreated
return ctx, rec, ctr, p return ctx, rec, ctr, p
} }
@ -89,7 +89,7 @@ func TestController_RenderPage(t *testing.T) {
} }
// Check the template cache // Check the template cache
parsed, err := c.TemplateRenderer.Load("controller", p.Name) parsed, err := c.TemplateRenderer.Load("page", p.Name)
assert.NoError(t, err) assert.NoError(t, err)
// Check that all expected templates were parsed. // Check that all expected templates were parsed.

View file

@ -6,24 +6,29 @@ import (
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
) )
// FormSubmission represents the state of the submission of a form, not including the form itself
type FormSubmission struct { type FormSubmission struct {
// IsSubmitted indicates if the form has been submitted
IsSubmitted bool IsSubmitted bool
// Errors stores a slice of error message strings keyed by form struct field name
Errors map[string][]string Errors map[string][]string
} }
// Process processes a submission for a form
func (f *FormSubmission) Process(ctx echo.Context, form interface{}) error { func (f *FormSubmission) Process(ctx echo.Context, form interface{}) error {
f.Errors = make(map[string][]string) f.Errors = make(map[string][]string)
f.IsSubmitted = true f.IsSubmitted = true
// Validate the form // Validate the form
if err := ctx.Validate(form); err != nil { if err := ctx.Validate(form); err != nil {
f.setErrorMessages(form, err) f.setErrorMessages(err)
} }
return nil return nil
} }
// HasErrors indicates if the submission has any validation errors
func (f FormSubmission) HasErrors() bool { func (f FormSubmission) HasErrors() bool {
if f.Errors == nil { if f.Errors == nil {
return false return false
@ -31,10 +36,12 @@ func (f FormSubmission) HasErrors() bool {
return len(f.Errors) > 0 return len(f.Errors) > 0
} }
// FieldHasErrors indicates if a given field on the form has any validation errors
func (f FormSubmission) FieldHasErrors(fieldName string) bool { func (f FormSubmission) FieldHasErrors(fieldName string) bool {
return len(f.GetFieldErrors(fieldName)) > 0 return len(f.GetFieldErrors(fieldName)) > 0
} }
// SetFieldError sets an error message for a given field name
func (f *FormSubmission) SetFieldError(fieldName string, message string) { func (f *FormSubmission) SetFieldError(fieldName string, message string) {
if f.Errors == nil { if f.Errors == nil {
f.Errors = make(map[string][]string) f.Errors = make(map[string][]string)
@ -42,19 +49,15 @@ func (f *FormSubmission) SetFieldError(fieldName string, message string) {
f.Errors[fieldName] = append(f.Errors[fieldName], message) f.Errors[fieldName] = append(f.Errors[fieldName], message)
} }
// GetFieldErrors gets the errors for a given field name
func (f FormSubmission) GetFieldErrors(fieldName string) []string { func (f FormSubmission) GetFieldErrors(fieldName string) []string {
if f.Errors == nil { if f.Errors == nil {
return []string{} return []string{}
} }
return f.Errors[fieldName]
errors, has := f.Errors[fieldName]
if !has {
return []string{}
}
return errors
} }
// GetFieldStatusClass returns an HTML class based on the status of the field
func (f FormSubmission) GetFieldStatusClass(fieldName string) string { func (f FormSubmission) GetFieldStatusClass(fieldName string) string {
if f.IsSubmitted { if f.IsSubmitted {
if f.FieldHasErrors(fieldName) { if f.FieldHasErrors(fieldName) {
@ -65,11 +68,14 @@ func (f FormSubmission) GetFieldStatusClass(fieldName string) string {
return "" return ""
} }
// IsDone indicates if the submission is considered done which is when it has been submitted
// and there are no errors.
func (f FormSubmission) IsDone() bool { func (f FormSubmission) IsDone() bool {
return f.IsSubmitted && !f.HasErrors() return f.IsSubmitted && !f.HasErrors()
} }
func (f *FormSubmission) setErrorMessages(form interface{}, err error) { // setErrorMessages sets errors messages on the submission for all fields that failed validation
func (f *FormSubmission) setErrorMessages(err error) {
// Only this is supported right now // Only this is supported right now
ves, ok := err.(validator.ValidationErrors) ves, ok := err.(validator.ValidationErrors)
if !ok { if !ok {

36
controller/form_test.go Normal file
View file

@ -0,0 +1,36 @@
package controller
import (
"testing"
"goweb/tests"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestFormSubmission(t *testing.T) {
type formTest struct {
Name string `validate:"required"`
Email string `validate:"required,email"`
Submission FormSubmission
}
ctx, _ := tests.NewContext(c.Web, "/")
form := formTest{
Name: "",
Email: "a@a.com",
}
err := form.Submission.Process(ctx, form)
assert.NoError(t, err)
assert.True(t, form.Submission.HasErrors())
assert.True(t, form.Submission.FieldHasErrors("Name"))
assert.False(t, form.Submission.FieldHasErrors("Email"))
require.Len(t, form.Submission.GetFieldErrors("Name"), 1)
assert.Len(t, form.Submission.GetFieldErrors("Email"), 0)
assert.Equal(t, "This field is required.", form.Submission.GetFieldErrors("Name")[0])
assert.Equal(t, "is-danger", form.Submission.GetFieldStatusClass("Name"))
assert.Equal(t, "is-success", form.Submission.GetFieldStatusClass("Email"))
assert.False(t, form.Submission.IsDone())
}

View file

@ -8,8 +8,6 @@ import (
"goweb/middleware" "goweb/middleware"
"goweb/services" "goweb/services"
"github.com/go-playground/validator/v10"
"github.com/gorilla/sessions" "github.com/gorilla/sessions"
"github.com/labstack/echo-contrib/session" "github.com/labstack/echo-contrib/session"
@ -17,19 +15,6 @@ import (
echomw "github.com/labstack/echo/v4/middleware" echomw "github.com/labstack/echo/v4/middleware"
) )
type Validator struct {
validator *validator.Validate
}
func (v *Validator) Validate(i interface{}) error {
if err := v.validator.Struct(i); err != nil {
return err
}
return nil
}
// TODO: This is doing more than building the router
func BuildRouter(c *services.Container) { func BuildRouter(c *services.Container) {
// Static files with proper cache control // Static files with proper cache control
// funcmap.File() should be used in templates to append a cache key to the URL in order to break cache // funcmap.File() should be used in templates to append a cache key to the URL in order to break cache
@ -73,9 +58,6 @@ func BuildRouter(c *services.Container) {
err := Error{Controller: ctr} err := Error{Controller: ctr}
c.Web.HTTPErrorHandler = err.Get c.Web.HTTPErrorHandler = err.Get
// Validator
c.Web.Validator = &Validator{validator: validator.New()}
// Routes // Routes
navRoutes(c, g, ctr) navRoutes(c, g, ctr)
userRoutes(c, g, ctr) userRoutes(c, g, ctr)

View file

@ -21,6 +21,9 @@ import (
// Container contains all services used by the application and provides an easy way to handle dependency // Container contains all services used by the application and provides an easy way to handle dependency
// injection including within tests // injection including within tests
type Container struct { type Container struct {
// Validator stores a validator
Validator *Validator
// Web stores the web framework // Web stores the web framework
Web *echo.Echo Web *echo.Echo
@ -53,6 +56,7 @@ type Container struct {
func NewContainer() *Container { func NewContainer() *Container {
c := new(Container) c := new(Container)
c.initConfig() c.initConfig()
c.initValidator()
c.initWeb() c.initWeb()
c.initCache() c.initCache()
c.initDatabase() c.initDatabase()
@ -87,6 +91,11 @@ func (c *Container) initConfig() {
c.Config = &cfg c.Config = &cfg
} }
// initValidator initializes the validator
func (c *Container) initValidator() {
c.Validator = NewValidator()
}
// initWeb initializes the web framework // initWeb initializes the web framework
func (c *Container) initWeb() { func (c *Container) initWeb() {
c.Web = echo.New() c.Web = echo.New()
@ -98,6 +107,8 @@ func (c *Container) initWeb() {
default: default:
c.Web.Logger.SetLevel(log.DEBUG) c.Web.Logger.SetLevel(log.DEBUG)
} }
c.Web.Validator = c.Validator
} }
// initCache initializes the cache // initCache initializes the cache

View file

@ -9,6 +9,7 @@ import (
func TestNewContainer(t *testing.T) { func TestNewContainer(t *testing.T) {
assert.NotNil(t, c.Web) assert.NotNil(t, c.Web)
assert.NotNil(t, c.Config) assert.NotNil(t, c.Config)
assert.NotNil(t, c.Validator)
assert.NotNil(t, c.Cache) assert.NotNil(t, c.Cache)
assert.NotNil(t, c.Database) assert.NotNil(t, c.Database)
assert.NotNil(t, c.ORM) assert.NotNil(t, c.ORM)

26
services/validator.go Normal file
View file

@ -0,0 +1,26 @@
package services
import (
"github.com/go-playground/validator/v10"
)
// Validator provides validation mainly validating structs within the web context
type Validator struct {
// validator stores the underlying validator
validator *validator.Validate
}
// NewValidator creats a new Validator
func NewValidator() *Validator {
return &Validator{
validator: validator.New(),
}
}
// Validate validates a struct
func (v *Validator) Validate(i interface{}) error {
if err := v.validator.Struct(i); err != nil {
return err
}
return nil
}

View file

@ -0,0 +1,19 @@
package services
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestValidator(t *testing.T) {
type example struct {
Value string `validate:"required"`
}
e := example{}
err := c.Validator.Validate(e)
assert.Error(t, err)
e.Value = "a"
err = c.Validator.Validate(e)
assert.NoError(t, err)
}