You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
101 lines
2.4 KiB
101 lines
2.4 KiB
package models
|
|
|
|
import (
|
|
"database/sql"
|
|
"testing"
|
|
"time"
|
|
|
|
"git.devices.local/mawas/golang-api-skeleton/lib/cache"
|
|
"git.devices.local/mawas/golang-api-skeleton/lib/common"
|
|
"github.com/oklog/ulid/v2"
|
|
"gorm.io/driver/sqlite"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
const userID = "01F5Z7CFER2D9QH2VY2V7PVQHF"
|
|
|
|
func tokenmock(t *testing.T) (*gorm.DB, cache.Cache, Token) {
|
|
db, err := gorm.Open(
|
|
sqlite.Open(":memory:"),
|
|
&gorm.Config{DisableForeignKeyConstraintWhenMigrating: true},
|
|
)
|
|
if err != nil {
|
|
t.Error(err)
|
|
}
|
|
if err := db.AutoMigrate(&User{}); err != nil {
|
|
t.Error(err)
|
|
}
|
|
appCache, err := cache.Bootstrap()
|
|
if err != nil {
|
|
t.Error(err)
|
|
}
|
|
if err := appCache.Set("user:"+userID, username); err != nil {
|
|
t.Error(err)
|
|
}
|
|
if err := appCache.Set("user:"+username, userID); err != nil {
|
|
t.Error(err)
|
|
}
|
|
guid, err := common.StringToGUID(userID)
|
|
if err != nil {
|
|
t.Error(err)
|
|
}
|
|
return db, appCache, Token{UserID: guid}
|
|
}
|
|
|
|
func TestTokenBeforeCreate(t *testing.T) {
|
|
db, _, token := tokenmock(t)
|
|
err := token.BeforeCreate(db.Set("userID", userID))
|
|
if err != nil {
|
|
t.Error(err)
|
|
}
|
|
if token.CreatedByDB.String() != userID {
|
|
t.Error("Token BeforeCreate doesn't set CreatedByDB")
|
|
}
|
|
if token.UpdatedByDB.String() != userID {
|
|
t.Error("Token BeforeCreate doesn't set UpdatedByDB")
|
|
}
|
|
if _, err := ulid.Parse(token.Token.String()); err != nil {
|
|
t.Error("Token BeforeCreate doesn't set proper Token ->", err.Error())
|
|
}
|
|
}
|
|
|
|
func TestTokenAfterFind(t *testing.T) {
|
|
db, appCache, token := tokenmock(t)
|
|
defer appCache.Close()
|
|
now := time.Now()
|
|
token.CreatedByDB = token.UserID
|
|
token.UpdatedByDB = token.UserID
|
|
token.DeletedAtDB = gorm.DeletedAt{
|
|
Valid: true,
|
|
Time: now,
|
|
}
|
|
token.LastUsedDB = sql.NullTime{
|
|
Valid: true,
|
|
Time: now,
|
|
}
|
|
err := token.AfterFind(db.Set("cache", appCache))
|
|
if err != nil {
|
|
t.Error(err)
|
|
}
|
|
if token.DeletedAtJSON == nil {
|
|
t.Error("Token AfterFind doesn't set DeletedAtJSON")
|
|
}
|
|
if *token.DeletedAtJSON != now {
|
|
t.Error("Token AfterFind doesn't set DeletedAtJSON proper")
|
|
}
|
|
if token.LastUsedJSON == nil {
|
|
t.Error("Token AfterFind doesn't set LastUsedJSON")
|
|
}
|
|
if *token.LastUsedJSON != now {
|
|
t.Error("Token AfterFind doesn't proper set LastUsedJSON")
|
|
}
|
|
if token.CreatedByJSON != username {
|
|
t.Error("Token AfterFind doesn't set CreatedByJSON")
|
|
}
|
|
if token.UpdatedByJSON != username {
|
|
t.Error("Token AfterFind doesn't set UpdatedByJSON")
|
|
}
|
|
if token.Username != username {
|
|
t.Error("Token AfterFind doesn't set Username")
|
|
}
|
|
}
|