arpb2 / C-3PO

REST API for the ARPB2 application

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

User input validations

saantiaguilera opened this issue · comments

Hacer algun pattern que nos permita agregar validations para mas de un controller en simultaneo.

Ejemplo:

  • Validacion para contrase;a de menos de N caracteres (post / put consumirian)
  • Validacion de usuario con fields faltantes (post consumiria)

Ejemplo de test para POST que hace romper:

func TestUserPostControllerBody_400OnParameterMissing(t *testing.T) {
	expectedUser := &model.AuthenticatedUser{
		User: &model.User{
			Id:      1000,
			Email:   "test@email.com",
			Surname: "TestSurname",
		},
		Password: "testpassword",
	}
	service := new(MockUserService)
	service.On("CreateUser", mock.MatchedBy(func(obj interface{}) bool {
		return true
	})).Return(expectedUser, nil).Once()

	body := user.CreatePostBody(service)

	reader := new(http_wrapper.TestReader)
	reader.On("ShouldBindJSON", mock.MatchedBy(func(obj *model.AuthenticatedUser) bool {
		return true
	})).Return(nil).Once()

	c, w := gin_wrapper.CreateTestContext()
	c.Reader = reader

	body(c)

	actual := bytes.TrimSpace([]byte(w.Body.String()))
	expected := golden.Get(t, actual, "bad_request.create_user.missing_parameter.golden.json")

	assert.Equal(t, http.StatusBadRequest, w.Code)
	assert.Equal(t, expected, actual)
	reader.AssertExpectations(t)
	service.AssertExpectations(t)
}

func TestUserPostControllerBody_400OnShortPassword(t *testing.T) {
	expectedUser := &model.AuthenticatedUser{
		User: &model.User{
			Id:      1000,
			Email:   "test@email.com",
			Name:    "TestName",
			Surname: "TestSurname",
		},
		Password: "test",
	}
	service := new(MockUserService)
	service.On("CreateUser", mock.MatchedBy(func(obj interface{}) bool {
		return true
	})).Return(expectedUser, nil).Once()

	body := user.CreatePostBody(service)

	reader := new(http_wrapper.TestReader)
	reader.On("ShouldBindJSON", mock.MatchedBy(func(obj *model.AuthenticatedUser) bool {
		return true
	})).Return(nil).Once()

	c, w := gin_wrapper.CreateTestContext()
	c.Reader = reader

	body(c)

	actual := bytes.TrimSpace([]byte(w.Body.String()))
	expected := golden.Get(t, actual, "bad_request.create_user.short_password.golden.json")

	assert.Equal(t, http.StatusBadRequest, w.Code)
	assert.Equal(t, expected, actual)
	reader.AssertExpectations(t)
	service.AssertExpectations(t)
}

@mastanca sabes si hay alguna forma out of the box con gin o alguien que te permita validar schemas? Creo haberlo hablado pero por las dudas

Si! Podes directamente hacer que lo chequee el model cuando bindeas, te paso la doc https://github.com/gin-gonic/gin#model-binding-and-validation fijate ahi las opciones que tiene el validator ese v10