Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding tests for validation and login #15

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,15 @@ require (
)

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/go-playground/locales v0.14.0 // indirect
github.com/go-playground/universal-translator v0.18.0 // indirect
github.com/golang/mock v1.6.0 // indirect
github.com/leodido/go-urn v1.2.1 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/objx v0.5.0 // indirect
github.com/stretchr/testify v1.8.4 // indirect
gopkg.in/go-playground/assert.v1 v1.2.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
7 changes: 7 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,16 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/twilio/twilio-go v0.26.0 h1:wFW4oTe3/LKt6bvByP7eio8JsjtaLHjMQKOUEzQry7U=
github.com/twilio/twilio-go v0.26.0/go.mod h1:lz62Hopu4vicpQ056H5TJ0JE4AP0rS3sQ35/ejmgOwE=
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
Expand Down
1 change: 1 addition & 0 deletions http/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ func LoginUserHandler(w http.ResponseWriter, r *http.Request) {

if r.Body == nil {
http.Error(w, "Empty body", http.StatusBadRequest)
return
}

var user LoginUserPayload
Expand Down
83 changes: 83 additions & 0 deletions http/login_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package http

import (
"bytes"
"fmt"
"github.com/stretchr/testify/require"
"net/http"
"net/http/httptest"
"testing"
)

func TestLoginUserHandler(t *testing.T) {
t.Parallel()

t.Run("Errors", testLoginErrors)
t.Run("Success", testLoginSuccess)
}

func testLoginErrors(t *testing.T) {
t.Parallel()

methodsToTest := []string{http.MethodDelete, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodOptions}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Acho que assim ficaria mais fácil de entender. Pense no código como uma leitura, quanto mais claros os nomes das variáveis forem, menos contexto precisa ser carregado na cabeça pra entender o código.

Suggested change
methodsToTest := []string{http.MethodDelete, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodOptions}
forbiddenMethods := []string{http.MethodDelete, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodOptions}


for _, method := range methodsToTest {
t.Run(fmt.Sprintf("Method %s not allowed", method), func(t *testing.T) {
t.Parallel()
req, err := http.NewRequest(method, "/", nil)
require.NoError(t, err)

resp := assertResponseStatus(t, req, http.StatusMovedPermanently)
require.Equal(t, "", resp)
})
}

t.Run("Handle error reading request body", func(t *testing.T) {
jessicamosouza marked this conversation as resolved.
Show resolved Hide resolved
t.Parallel()
req, err := http.NewRequest(http.MethodGet, "/", &ErrorReader{})
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Como ErrorReader é usado só dentro deste mesmo pacote, não precisa exportar ele. :)

require.NoError(t, err)

resp := assertResponseStatus(t, req, http.StatusInternalServerError)
require.Equal(t, "Error unmarshalling request body\nemail validation failed: invalid email\n", resp)
})

t.Run("Empty body", func(t *testing.T) {
t.Parallel()
req, err := http.NewRequest(http.MethodGet, "/", nil)
require.NoError(t, err)

resp := assertResponseStatus(t, req, http.StatusBadRequest)
require.Equal(t, "Empty body\n", resp)
})

t.Run("Error finding user", func(t *testing.T) {
t.Parallel()
req, err := http.NewRequest(http.MethodGet, "/", bytes.NewBufferString(
`{"email":"maria@email.com", "password":"Password123!"}`))
require.NoError(t, err)

resp := assertResponseStatus(t, req, http.StatusBadRequest)
require.Equal(t, "[usermodels] user not found\n", resp)
})
}

func testLoginSuccess(t *testing.T) {
t.Parallel()

t.Run("Successful body read", func(t *testing.T) {
t.Parallel()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

C entendeu direitinho pra que o t.Parallel serve e como ele funciona?

req, err := http.NewRequest(http.MethodGet, "/",
bytes.NewBufferString(`{"email":"john@doe.com","password":"Password123!"}`))
require.NoError(t, err)

resp := assertResponseStatus(t, req, http.StatusOK)
require.Equal(t, "LoginUserPayload logged successfully!", resp)
})
}

func assertResponseStatus(t *testing.T, req *http.Request, status int) string {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Quando vc define alguma coisa em um arquivo de teste, essa parada fica disponível pra todos os testes que usem o mesmo pacote. Como essa função faz assertion do status HTTP da resposta de LoginUserHandler especificamente, vale um ou outro dos abaixo:

Um: Deixar claro no nome que a assertion é para LoginUserHandler.

Outro: Aceitar como parâmetro a função. Ficaria algo assim:

func assertResponseStatus(t *testing.T, fn http.HandleFunc, req *http.Request, status int) string {
  t.Helper()

	rec := httptest.NewRecorder()
	fn(rec, req)
	require.Equal(t, status, rec.Code)
	return rec.Body.String()
}

// Usado assim, por exemplo:
assertResponseStatus(t, LoginUserHandler, req, http.StatusOK)

Se você optar por outro, vale criar um arquivo shared_test.go pra centralizar esses helpers de teste.

Outra dica legal é usar t.Helper() em helper functions de teste. Isso faz com que, caso o teste falhe aqui (no require.Equal, por exemplo), o report de teste do Go vai mostrar que deu erro em quem chamou a função que usa t.Helper() ao invés de dentro da função que usa t.Helper().

rec := httptest.NewRecorder()
LoginUserHandler(rec, req)
require.Equal(t, status, rec.Code)
return rec.Body.String()
}
10 changes: 9 additions & 1 deletion uservalidation/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"net/mail"
"regexp"
"unicode"
)

Expand Down Expand Up @@ -34,10 +35,17 @@ func Validate(user User, isSignUp bool) error {
return nil
}

var re = regexp.MustCompile(`[^a-zA-ZäöüÄÖÜáéíóúÁÉÍÓÚàèìòùÀÈÌÒÙâêîôûÂÊÎÔÛãñõÃÑÕçÇ ^\p{L}'-]`)

func CheckName(name string) error {
if len(name) < 2 {
if name == "" {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tende a ser uma boa ideia sanitizar inputs string por espaços antes e depois do texto. É relativamente fácil em interfaces esquecer um espaço antes ou depois do valor de um campo e não perceber. strings.TrimSpace() tende a ser suficiente.

Suggested change
if name == "" {
sanitizedName := strings.TrimSpace(name)
if sanitizedName == "" {

return errors.New("name cannot be empty")
} else if len(name) < 2 {
return errors.New("name must contain at least 2 characters")
} else if re.MatchString(name) {
return errors.New("name cannot contain special characters")
}

return nil
}

Expand Down
Loading