|
| 1 | +package users_router |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + "net/http/httptest" |
| 6 | + "net/url" |
| 7 | + "strings" |
| 8 | + "testing" |
| 9 | + |
| 10 | + "golang.org/x/crypto/bcrypt" |
| 11 | + |
| 12 | + mocket "github.com/selvatico/go-mocket" |
| 13 | + "github.com/stretchr/testify/assert" |
| 14 | +) |
| 15 | + |
| 16 | +func TestGetLogin(t *testing.T) { |
| 17 | + provider, _, _ := BuildTest() |
| 18 | + rec := httptest.NewRecorder() |
| 19 | + req, _ := http.NewRequest(http.MethodGet, "/login", nil) |
| 20 | + provider.Router.GetLogin(rec, req) |
| 21 | + |
| 22 | + assert.Equal(t, http.StatusOK, rec.Code) |
| 23 | +} |
| 24 | + |
| 25 | +func TestPostLogin(t *testing.T) { |
| 26 | + mocket.Catcher.Logging = true |
| 27 | + |
| 28 | + tests := []struct { |
| 29 | + name string |
| 30 | + urlValues url.Values |
| 31 | + mock func() |
| 32 | + expectedCode int |
| 33 | + }{ |
| 34 | + { |
| 35 | + name: "successful logged", |
| 36 | + urlValues: url.Values{"email": {"test_email"}, "password": {"test_password"}}, |
| 37 | + mock: func() { |
| 38 | + ePassword, e := bcrypt.GenerateFromPassword([]byte("test_password"), 8) |
| 39 | + assert.Nil(t, e, "Password is correct") |
| 40 | + reply := []map[string]interface{}{{"id": 1, "email": "test_email", "encrypted_password": ePassword}} |
| 41 | + mocket.Catcher.Reset().NewMock().WithQuery(`WHERE (users.email = $1) LIMIT 1`).WithArgs("test_email").WithReply(reply) |
| 42 | + }, |
| 43 | + expectedCode: http.StatusFound, |
| 44 | + }, |
| 45 | + { |
| 46 | + name: "user does not exist", |
| 47 | + urlValues: url.Values{"email": {"test_email"}, "password": {"test_password"}}, |
| 48 | + mock: func() {}, |
| 49 | + expectedCode: http.StatusNotFound, |
| 50 | + }, |
| 51 | + } |
| 52 | + |
| 53 | + for _, test := range tests { |
| 54 | + t.Run(test.name, func(t *testing.T) { |
| 55 | + mocket.Catcher.Reset() |
| 56 | + test.mock() |
| 57 | + |
| 58 | + provider, _, e := BuildTest() |
| 59 | + assert.Nil(t, e, "err should be nil") |
| 60 | + |
| 61 | + rec := httptest.NewRecorder() |
| 62 | + req, _ := http.NewRequest(http.MethodPost, "/login", strings.NewReader(test.urlValues.Encode())) |
| 63 | + req.Header.Add("Content-Type", "application/x-www-form-urlencoded") |
| 64 | + provider.Router.PostLogin(rec, req) |
| 65 | + |
| 66 | + assert.Equal(t, test.expectedCode, rec.Code) |
| 67 | + }) |
| 68 | + } |
| 69 | +} |
0 commit comments