clndr/api/test/models/db_test.go

73 lines
1.3 KiB
Go
Raw Normal View History

2022-12-18 00:42:21 +00:00
package models_test
import (
"magmise/models"
"testing"
)
type Test struct {
Name string
}
func TestDB(t *testing.T) {
// Create table
models.DB().AutoMigrate(&models.User{})
user := models.User{Username: "test"}
//Create
if err := models.Create(&user); err != nil {
t.Fatal(err)
}
t.Log("\033[33mShould error with unique contraint\033[0m")
if err := models.Create(&user); err == nil {
t.Fatal(err)
}
// Read
if err := models.Read(&user); err != nil {
t.Fatal(err)
}
// Create more rows
user = models.User{Username: "test2"}
models.Create(&user)
user = models.User{Username: "test3"}
models.Create(&user)
user = models.User{Username: "test4"}
models.Create(&user)
// Get second and third row
var users []models.User
if err := models.ReadAll(&users, 1, 2); err != nil {
t.Fatal(err)
}
if users[0].Username != "test2" {
t.Fatal("Offset failed\n", users)
}
if len(users) != 2 {
t.Fatal("Limit failed\n", users)
}
// Update
user.Password = "b"
if err := models.Update(&user, "username", user.Username); err != nil {
t.Fatal(err)
}
// Check Update
if err := models.Read(&user); err != nil {
t.Fatal(err)
}
if user.Password != "b" {
t.Fatal("failed update")
}
// Delete
if err := models.Delete(&user); err != nil {
t.Fatal(err)
}
models.DB().Migrator().DropTable(&models.User{})
}