go-cook/internal/handlers/v1/auth_test.go

99 lines
2.0 KiB
Go

package v1_test
import (
"database/sql"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
v1 "git.jamestombleson.com/jtom38/go-cook/internal/handlers/v1"
"git.jamestombleson.com/jtom38/go-cook/internal/domain"
_ "github.com/glebarez/go-sqlite"
"github.com/labstack/echo/v4"
"github.com/pressly/goose/v3"
"github.com/stretchr/testify/assert"
)
func setupInMemoryDb() (*sql.DB, error) {
db, err := sql.Open("sqlite", ":memory:")
if err != nil {
return nil, err
}
err = goose.SetDialect("sqlite3")
if err != nil {
return nil, err
}
err = goose.Up(db, "../../migrations")
if err != nil {
return nil, err
}
return db, nil
}
func TestAuthCreateUser(t *testing.T) {
db, err := setupInMemoryDb()
if err != nil {
t.Error(err)
return
}
h := v1.NewHandler(db, domain.EnvConfig{
AdminToken: "lol",
JwtSecret: "lol",
})
e := echo.New()
form := make(url.Values)
form.Set("username", "test")
form.Set("password", "test1234!")
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/register", strings.NewReader(form.Encode()))
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationForm)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
if assert.NoError(t, h.AuthRegister(c)) {
assert.Equal(t, http.StatusCreated, rec.Code)
}
}
func TestAuthLoginUser(t *testing.T) {
db, err := setupInMemoryDb()
if err != nil {
t.Error(err)
return
}
h := v1.NewHandler(db, domain.EnvConfig{
AdminToken: "lol",
JwtSecret: "lol",
})
e := echo.New()
form := make(url.Values)
form.Set("username", "test")
form.Set("password", "test1234!")
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", strings.NewReader(form.Encode()))
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationForm)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
// create the user
err = h.AuthRegister(c)
if err != nil {
t.Error(err)
t.FailNow()
}
// now test to make sure it worked
if assert.NoError(t, h.AuthLogin(c)) {
assert.Equal(t, http.StatusOK, rec.Code)
}
}