Starting API unit tests!.... yay

This commit is contained in:
James Tombleson 2024-04-05 17:50:04 -07:00
parent fc0140e5a4
commit 671ee21355
2 changed files with 106 additions and 5 deletions

View File

@ -2,10 +2,11 @@ package v1
import (
"errors"
"go-cook/api/domain"
"go-cook/api/repositories"
"net/http"
"git.jamestombleson.com/jtom38/go-cook/api/repositories"
"git.jamestombleson.com/jtom38/go-cook/api/domain"
"github.com/golang-jwt/jwt/v5"
"github.com/labstack/echo/v4"
)
@ -57,11 +58,13 @@ func (h *Handler) AuthRegister(c echo.Context) error {
})
}
return nil
return c.JSON(http.StatusCreated, domain.ErrorResponse{
Success: true,
})
}
func (h *Handler) AuthLogin(c echo.Context) error {
username := c.FormValue("name")
username := c.FormValue("username")
password := c.FormValue("password")
// Check to see if they are trying to login with the admin token

View File

@ -0,0 +1,98 @@
package v1_test
import (
"database/sql"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
v1 "git.jamestombleson.com/jtom38/go-cook/api/handlers/v1"
"git.jamestombleson.com/jtom38/go-cook/api/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)
}
}