2024-06-09 18:39:04 -07:00
|
|
|
package form
|
2021-12-24 21:11:59 -08:00
|
|
|
|
|
|
|
import (
|
2024-06-14 09:35:35 -07:00
|
|
|
"net/http"
|
|
|
|
"net/http/httptest"
|
|
|
|
"strings"
|
2021-12-24 21:11:59 -08:00
|
|
|
"testing"
|
|
|
|
|
2024-06-14 09:35:35 -07:00
|
|
|
"github.com/go-playground/validator/v10"
|
2024-06-09 18:39:04 -07:00
|
|
|
"github.com/labstack/echo/v4"
|
2021-12-24 21:11:59 -08:00
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
"github.com/stretchr/testify/require"
|
2024-07-09 17:57:05 -07:00
|
|
|
|
|
|
|
"git.grosinger.net/tgrosinger/saasitone/pkg/services"
|
2021-12-24 21:11:59 -08:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestFormSubmission(t *testing.T) {
|
|
|
|
type formTest struct {
|
2024-06-14 09:35:35 -07:00
|
|
|
Name string `form:"name" validate:"required"`
|
|
|
|
Email string `form:"email" validate:"required,email"`
|
|
|
|
Submission
|
2021-12-24 21:11:59 -08:00
|
|
|
}
|
|
|
|
|
2024-06-09 18:39:04 -07:00
|
|
|
e := echo.New()
|
|
|
|
e.Validator = services.NewValidator()
|
2024-06-14 09:35:35 -07:00
|
|
|
|
|
|
|
t.Run("valid request", func(t *testing.T) {
|
|
|
|
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader("email=a@a.com"))
|
|
|
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
|
|
ctx := e.NewContext(req, httptest.NewRecorder())
|
|
|
|
|
|
|
|
var form formTest
|
|
|
|
err := form.Submit(ctx, &form)
|
|
|
|
assert.IsType(t, validator.ValidationErrors{}, err)
|
|
|
|
|
|
|
|
assert.Empty(t, form.Name)
|
|
|
|
assert.Equal(t, "a@a.com", form.Email)
|
|
|
|
assert.False(t, form.IsValid())
|
|
|
|
assert.True(t, form.FieldHasErrors("Name"))
|
|
|
|
assert.False(t, form.FieldHasErrors("Email"))
|
|
|
|
require.Len(t, form.GetFieldErrors("Name"), 1)
|
|
|
|
assert.Len(t, form.GetFieldErrors("Email"), 0)
|
|
|
|
assert.Equal(t, "This field is required.", form.GetFieldErrors("Name")[0])
|
|
|
|
assert.Equal(t, "is-danger", form.GetFieldStatusClass("Name"))
|
|
|
|
assert.Equal(t, "is-success", form.GetFieldStatusClass("Email"))
|
|
|
|
assert.False(t, form.IsDone())
|
|
|
|
|
|
|
|
formInCtx := Get[formTest](ctx)
|
|
|
|
require.NotNil(t, formInCtx)
|
|
|
|
assert.Equal(t, form.Email, formInCtx.Email)
|
|
|
|
})
|
|
|
|
|
|
|
|
t.Run("invalid request", func(t *testing.T) {
|
|
|
|
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader("abc=abc"))
|
|
|
|
ctx := e.NewContext(req, httptest.NewRecorder())
|
|
|
|
var form formTest
|
|
|
|
err := form.Submit(ctx, &form)
|
|
|
|
assert.IsType(t, new(echo.HTTPError), err)
|
|
|
|
})
|
2021-12-24 21:11:59 -08:00
|
|
|
}
|