forked from baron/baron-sso
98 lines
2.6 KiB
Go
98 lines
2.6 KiB
Go
package repository
|
|
|
|
import (
|
|
"baron-sso-backend/internal/domain"
|
|
"context"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
)
|
|
|
|
func TestUserRepository(t *testing.T) {
|
|
repo := NewUserRepository(testDB)
|
|
ctx := context.Background()
|
|
|
|
// Ensure User table exists and clean for tests
|
|
_ = testDB.AutoMigrate(&domain.User{})
|
|
|
|
t.Run("Create and FindByEmail", func(t *testing.T) {
|
|
user := &domain.User{
|
|
Email: "test@example.com",
|
|
Name: "Test User",
|
|
Role: "user",
|
|
}
|
|
|
|
err := repo.Create(ctx, user)
|
|
assert.NoError(t, err)
|
|
assert.NotEmpty(t, user.ID)
|
|
|
|
found, err := repo.FindByEmail(ctx, "test@example.com")
|
|
assert.NoError(t, err)
|
|
assert.Equal(t, user.ID, found.ID)
|
|
assert.Equal(t, "Test User", found.Name)
|
|
})
|
|
|
|
t.Run("Update User Info", func(t *testing.T) {
|
|
user := &domain.User{
|
|
Email: "update@example.com",
|
|
Name: "Before Update",
|
|
Role: "user",
|
|
}
|
|
_ = repo.Create(ctx, user)
|
|
|
|
user.Name = "After Update"
|
|
user.Phone = "010-1234-5678"
|
|
err := repo.Update(ctx, user)
|
|
assert.NoError(t, err)
|
|
|
|
found, err := repo.FindByEmail(ctx, "update@example.com")
|
|
assert.NoError(t, err)
|
|
assert.Equal(t, "After Update", found.Name)
|
|
assert.Equal(t, "010-1234-5678", found.Phone)
|
|
})
|
|
|
|
t.Run("List Users with Search", func(t *testing.T) {
|
|
// Add some users
|
|
_ = repo.Create(ctx, &domain.User{Email: "alice@test.com", Name: "Alice", Role: "user"})
|
|
_ = repo.Create(ctx, &domain.User{Email: "bob@test.com", Name: "Bob", Role: "user"})
|
|
|
|
users, total, err := repo.List(ctx, 0, 10, "Alice", "")
|
|
assert.NoError(t, err)
|
|
assert.True(t, total >= 1)
|
|
assert.Equal(t, "Alice", users[0].Name)
|
|
})
|
|
|
|
t.Run("Delete User", func(t *testing.T) {
|
|
user := &domain.User{Email: "delete@example.com", Name: "To Delete"}
|
|
_ = repo.Create(ctx, user)
|
|
|
|
err := repo.Delete(ctx, user.ID)
|
|
assert.NoError(t, err)
|
|
|
|
found, err := repo.FindByEmail(ctx, "delete@example.com")
|
|
assert.Error(t, err) // Should not be found
|
|
assert.Nil(t, found)
|
|
})
|
|
|
|
t.Run("CountByCompanyCodes", func(t *testing.T) {
|
|
// Clean start for this subtest
|
|
testDB.Exec("DELETE FROM users")
|
|
|
|
users := []domain.User{
|
|
{Email: "u1@a.com", Name: "U1", CompanyCode: "tenant-a"},
|
|
{Email: "u2@a.com", Name: "U2", CompanyCode: "tenant-a"},
|
|
{Email: "u3@b.com", Name: "U3", CompanyCode: "tenant-b"},
|
|
{Email: "u4@none.com", Name: "U4", CompanyCode: ""},
|
|
}
|
|
for _, u := range users {
|
|
_ = repo.Create(ctx, &u)
|
|
}
|
|
|
|
counts, err := repo.CountByCompanyCodes(ctx, []string{"tenant-a", "tenant-b", "tenant-c"})
|
|
assert.NoError(t, err)
|
|
assert.Equal(t, int64(2), counts["tenant-a"])
|
|
assert.Equal(t, int64(1), counts["tenant-b"])
|
|
assert.Equal(t, int64(0), counts["tenant-c"])
|
|
})
|
|
}
|