feat: 实现 RBAC 权限系统和数据权限控制 (004-rbac-data-permission)
主要功能: - 实现完整的 RBAC 权限系统(账号、角色、权限的多对多关联) - 基于 owner_id + shop_id 的自动数据权限过滤 - 使用 PostgreSQL WITH RECURSIVE 查询下级账号 - Redis 缓存优化下级账号查询性能(30分钟过期) - 支持多租户数据隔离和层级权限管理 技术实现: - 新增 Account、Role、Permission 模型及关联关系表 - 实现 GORM Scopes 自动应用数据权限过滤 - 添加数据库迁移脚本(000002_rbac_data_permission、000003_add_owner_id_shop_id) - 完善错误码定义(1010-1027 为 RBAC 相关错误) - 重构 main.go 采用函数拆分提高可读性 测试覆盖: - 添加 Account、Role、Permission 的集成测试 - 添加数据权限过滤的单元测试和集成测试 - 添加下级账号查询和缓存的单元测试 - 添加 API 回归测试确保向后兼容 文档更新: - 更新 README.md 添加 RBAC 功能说明 - 更新 CLAUDE.md 添加技术栈和开发原则 - 添加 docs/004-rbac-data-permission/ 功能总结和使用指南 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
319
tests/unit/account_model_test.go
Normal file
319
tests/unit/account_model_test.go
Normal file
@@ -0,0 +1,319 @@
|
||||
package unit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/tests/testutils"
|
||||
)
|
||||
|
||||
// TestAccountModel_Create 测试创建账号
|
||||
func TestAccountModel_Create(t *testing.T) {
|
||||
db, redisClient := testutils.SetupTestDB(t)
|
||||
defer testutils.TeardownTestDB(t, db, redisClient)
|
||||
|
||||
store := postgres.NewAccountStore(db, redisClient)
|
||||
ctx := context.Background()
|
||||
|
||||
t.Run("创建 root 账号", func(t *testing.T) {
|
||||
account := &model.Account{
|
||||
Username: "root_user",
|
||||
Phone: "13800000001",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypeRoot,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
|
||||
err := store.Create(ctx, account)
|
||||
require.NoError(t, err)
|
||||
assert.NotZero(t, account.ID)
|
||||
assert.NotZero(t, account.CreatedAt)
|
||||
assert.NotZero(t, account.UpdatedAt)
|
||||
})
|
||||
|
||||
t.Run("创建带 parent_id 的账号", func(t *testing.T) {
|
||||
// 先创建父账号
|
||||
parent := &model.Account{
|
||||
Username: "parent_user",
|
||||
Phone: "13800000002",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
err := store.Create(ctx, parent)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 创建子账号
|
||||
child := &model.Account{
|
||||
Username: "child_user",
|
||||
Phone: "13800000003",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypeAgent,
|
||||
ParentID: &parent.ID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
err = store.Create(ctx, child)
|
||||
require.NoError(t, err)
|
||||
assert.NotZero(t, child.ID)
|
||||
assert.Equal(t, parent.ID, *child.ParentID)
|
||||
})
|
||||
|
||||
t.Run("创建带 shop_id 的账号", func(t *testing.T) {
|
||||
shopID := uint(100)
|
||||
account := &model.Account{
|
||||
Username: "shop_user",
|
||||
Phone: "13800000004",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypePlatform,
|
||||
ShopID: &shopID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
|
||||
err := store.Create(ctx, account)
|
||||
require.NoError(t, err)
|
||||
assert.NotNil(t, account.ShopID)
|
||||
assert.Equal(t, uint(100), *account.ShopID)
|
||||
})
|
||||
}
|
||||
|
||||
// TestAccountModel_GetByID 测试根据 ID 查询账号
|
||||
func TestAccountModel_GetByID(t *testing.T) {
|
||||
db, redisClient := testutils.SetupTestDB(t)
|
||||
defer testutils.TeardownTestDB(t, db, redisClient)
|
||||
|
||||
store := postgres.NewAccountStore(db, redisClient)
|
||||
ctx := context.Background()
|
||||
|
||||
// 创建测试账号
|
||||
account := &model.Account{
|
||||
Username: "test_user",
|
||||
Phone: "13800000001",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
err := store.Create(ctx, account)
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Run("查询存在的账号", func(t *testing.T) {
|
||||
found, err := store.GetByID(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, account.Username, found.Username)
|
||||
assert.Equal(t, account.Phone, found.Phone)
|
||||
assert.Equal(t, account.UserType, found.UserType)
|
||||
})
|
||||
|
||||
t.Run("查询不存在的账号", func(t *testing.T) {
|
||||
_, err := store.GetByID(ctx, 99999)
|
||||
assert.Error(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
// TestAccountModel_GetByUsername 测试根据用户名查询账号
|
||||
func TestAccountModel_GetByUsername(t *testing.T) {
|
||||
db, redisClient := testutils.SetupTestDB(t)
|
||||
defer testutils.TeardownTestDB(t, db, redisClient)
|
||||
|
||||
store := postgres.NewAccountStore(db, redisClient)
|
||||
ctx := context.Background()
|
||||
|
||||
// 创建测试账号
|
||||
account := &model.Account{
|
||||
Username: "unique_user",
|
||||
Phone: "13800000001",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
err := store.Create(ctx, account)
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Run("根据用户名查询", func(t *testing.T) {
|
||||
found, err := store.GetByUsername(ctx, "unique_user")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, account.ID, found.ID)
|
||||
})
|
||||
|
||||
t.Run("查询不存在的用户名", func(t *testing.T) {
|
||||
_, err := store.GetByUsername(ctx, "nonexistent")
|
||||
assert.Error(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
// TestAccountModel_GetByPhone 测试根据手机号查询账号
|
||||
func TestAccountModel_GetByPhone(t *testing.T) {
|
||||
db, redisClient := testutils.SetupTestDB(t)
|
||||
defer testutils.TeardownTestDB(t, db, redisClient)
|
||||
|
||||
store := postgres.NewAccountStore(db, redisClient)
|
||||
ctx := context.Background()
|
||||
|
||||
// 创建测试账号
|
||||
account := &model.Account{
|
||||
Username: "phone_user",
|
||||
Phone: "13800000001",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
err := store.Create(ctx, account)
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Run("根据手机号查询", func(t *testing.T) {
|
||||
found, err := store.GetByPhone(ctx, "13800000001")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, account.ID, found.ID)
|
||||
})
|
||||
|
||||
t.Run("查询不存在的手机号", func(t *testing.T) {
|
||||
_, err := store.GetByPhone(ctx, "99900000000")
|
||||
assert.Error(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
// TestAccountModel_Update 测试更新账号
|
||||
func TestAccountModel_Update(t *testing.T) {
|
||||
db, redisClient := testutils.SetupTestDB(t)
|
||||
defer testutils.TeardownTestDB(t, db, redisClient)
|
||||
|
||||
store := postgres.NewAccountStore(db, redisClient)
|
||||
ctx := context.Background()
|
||||
|
||||
// 创建测试账号
|
||||
account := &model.Account{
|
||||
Username: "update_user",
|
||||
Phone: "13800000001",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
err := store.Create(ctx, account)
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Run("更新账号状态", func(t *testing.T) {
|
||||
account.Status = constants.StatusDisabled
|
||||
account.Updater = 2
|
||||
err := store.Update(ctx, account)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 验证更新
|
||||
found, err := store.GetByID(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, constants.StatusDisabled, found.Status)
|
||||
assert.Equal(t, uint(2), found.Updater)
|
||||
})
|
||||
}
|
||||
|
||||
// TestAccountModel_List 测试查询账号列表
|
||||
func TestAccountModel_List(t *testing.T) {
|
||||
db, redisClient := testutils.SetupTestDB(t)
|
||||
defer testutils.TeardownTestDB(t, db, redisClient)
|
||||
|
||||
store := postgres.NewAccountStore(db, redisClient)
|
||||
ctx := context.Background()
|
||||
|
||||
// 创建多个测试账号
|
||||
for i := 1; i <= 5; i++ {
|
||||
account := &model.Account{
|
||||
Username: testutils.GenerateUsername("list_user", i),
|
||||
Phone: testutils.GeneratePhone("138", i),
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
err := store.Create(ctx, account)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
t.Run("分页查询", func(t *testing.T) {
|
||||
accounts, total, err := store.List(ctx, nil, nil)
|
||||
require.NoError(t, err)
|
||||
assert.GreaterOrEqual(t, len(accounts), 5)
|
||||
assert.GreaterOrEqual(t, total, int64(5))
|
||||
})
|
||||
|
||||
t.Run("带过滤条件查询", func(t *testing.T) {
|
||||
filters := map[string]interface{}{
|
||||
"user_type": constants.UserTypePlatform,
|
||||
}
|
||||
accounts, _, err := store.List(ctx, nil, filters)
|
||||
require.NoError(t, err)
|
||||
for _, acc := range accounts {
|
||||
assert.Equal(t, constants.UserTypePlatform, acc.UserType)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestAccountModel_UniqueConstraints 测试唯一约束
|
||||
func TestAccountModel_UniqueConstraints(t *testing.T) {
|
||||
db, redisClient := testutils.SetupTestDB(t)
|
||||
defer testutils.TeardownTestDB(t, db, redisClient)
|
||||
|
||||
store := postgres.NewAccountStore(db, redisClient)
|
||||
ctx := context.Background()
|
||||
|
||||
// 创建测试账号
|
||||
account := &model.Account{
|
||||
Username: "unique_test",
|
||||
Phone: "13800000001",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
err := store.Create(ctx, account)
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Run("重复用户名应失败", func(t *testing.T) {
|
||||
duplicate := &model.Account{
|
||||
Username: "unique_test", // 重复
|
||||
Phone: "13800000002",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
err := store.Create(ctx, duplicate)
|
||||
assert.Error(t, err)
|
||||
})
|
||||
|
||||
t.Run("重复手机号应失败", func(t *testing.T) {
|
||||
duplicate := &model.Account{
|
||||
Username: "unique_test2",
|
||||
Phone: "13800000001", // 重复
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
err := store.Create(ctx, duplicate)
|
||||
assert.Error(t, err)
|
||||
})
|
||||
}
|
||||
303
tests/unit/data_permission_scope_test.go
Normal file
303
tests/unit/data_permission_scope_test.go
Normal file
@@ -0,0 +1,303 @@
|
||||
package unit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/middleware"
|
||||
"github.com/break/junhong_cmp_fiber/tests/testutils"
|
||||
)
|
||||
|
||||
// TestDataPermissionScope_RootUser 测试 root 用户跳过数据权限过滤
|
||||
func TestDataPermissionScope_RootUser(t *testing.T) {
|
||||
db, redisClient := testutils.SetupTestDB(t)
|
||||
defer testutils.TeardownTestDB(t, db, redisClient)
|
||||
|
||||
accountStore := postgres.NewAccountStore(db, redisClient)
|
||||
ctx := context.Background()
|
||||
|
||||
// 创建 root 用户
|
||||
rootUser := &model.Account{
|
||||
Username: "root_user",
|
||||
Phone: "13800000000",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypeRoot,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(rootUser).Error)
|
||||
|
||||
// 创建测试数据表(模拟业务表)
|
||||
type TestData struct {
|
||||
ID uint `gorm:"primarykey"`
|
||||
Name string
|
||||
OwnerID uint
|
||||
ShopID uint
|
||||
}
|
||||
require.NoError(t, db.AutoMigrate(&TestData{}))
|
||||
|
||||
// 插入测试数据(不同的 owner_id 和 shop_id)
|
||||
testData := []TestData{
|
||||
{Name: "data1", OwnerID: 1, ShopID: 100},
|
||||
{Name: "data2", OwnerID: 2, ShopID: 200},
|
||||
{Name: "data3", OwnerID: 3, ShopID: 300},
|
||||
}
|
||||
require.NoError(t, db.Create(&testData).Error)
|
||||
|
||||
// 设置 root 用户上下文
|
||||
ctxWithRoot := middleware.SetUserContext(ctx, rootUser.ID, constants.UserTypeRoot, 100)
|
||||
|
||||
// 查询(应该返回所有数据,不过滤)
|
||||
var results []TestData
|
||||
err := db.WithContext(ctxWithRoot).
|
||||
Scopes(postgres.DataPermissionScope(ctxWithRoot, accountStore)).
|
||||
Find(&results).Error
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, results, 3, "root 用户应该看到所有数据")
|
||||
}
|
||||
|
||||
// TestDataPermissionScope_NormalUser 测试普通用户数据权限过滤
|
||||
func TestDataPermissionScope_NormalUser(t *testing.T) {
|
||||
db, redisClient := testutils.SetupTestDB(t)
|
||||
defer testutils.TeardownTestDB(t, db, redisClient)
|
||||
|
||||
accountStore := postgres.NewAccountStore(db, redisClient)
|
||||
ctx := context.Background()
|
||||
|
||||
// 创建账号层级: A -> B
|
||||
accountA := &model.Account{
|
||||
Username: "user_a",
|
||||
Phone: "13800000001",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(accountA).Error)
|
||||
|
||||
shopIDA := uint(100)
|
||||
accountA.ShopID = &shopIDA
|
||||
require.NoError(t, db.Save(accountA).Error)
|
||||
|
||||
accountB := &model.Account{
|
||||
Username: "user_b",
|
||||
Phone: "13800000002",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypeAgent,
|
||||
ParentID: &accountA.ID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(accountB).Error)
|
||||
|
||||
shopIDB := uint(100)
|
||||
accountB.ShopID = &shopIDB
|
||||
require.NoError(t, db.Save(accountB).Error)
|
||||
|
||||
// 创建测试数据表
|
||||
type TestData struct {
|
||||
ID uint `gorm:"primarykey"`
|
||||
Name string
|
||||
OwnerID uint
|
||||
ShopID uint
|
||||
}
|
||||
require.NoError(t, db.AutoMigrate(&TestData{}))
|
||||
|
||||
// 插入测试数据
|
||||
testData := []TestData{
|
||||
{Name: "data_a", OwnerID: accountA.ID, ShopID: 100}, // A 的数据
|
||||
{Name: "data_b", OwnerID: accountB.ID, ShopID: 100}, // B 的数据
|
||||
{Name: "data_c", OwnerID: 999, ShopID: 100}, // 其他用户数据(同店铺)
|
||||
{Name: "data_d", OwnerID: accountA.ID, ShopID: 200}, // A 的数据(不同店铺)
|
||||
}
|
||||
require.NoError(t, db.Create(&testData).Error)
|
||||
|
||||
// A 登录查询(应该看到 A 和 B 的数据,同店铺)
|
||||
ctxWithA := middleware.SetUserContext(ctx, accountA.ID, constants.UserTypePlatform, 100)
|
||||
var resultsA []TestData
|
||||
err := db.WithContext(ctxWithA).
|
||||
Scopes(postgres.DataPermissionScope(ctxWithA, accountStore)).
|
||||
Find(&resultsA).Error
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, resultsA, 2, "A 应该看到自己和下级 B 的数据")
|
||||
|
||||
// B 登录查询(只能看到自己的数据)
|
||||
ctxWithB := middleware.SetUserContext(ctx, accountB.ID, constants.UserTypeAgent, 100)
|
||||
var resultsB []TestData
|
||||
err = db.WithContext(ctxWithB).
|
||||
Scopes(postgres.DataPermissionScope(ctxWithB, accountStore)).
|
||||
Find(&resultsB).Error
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, resultsB, 1, "B 只能看到自己的数据")
|
||||
assert.Equal(t, "data_b", resultsB[0].Name)
|
||||
}
|
||||
|
||||
// TestDataPermissionScope_ShopIsolation 测试店铺隔离
|
||||
func TestDataPermissionScope_ShopIsolation(t *testing.T) {
|
||||
db, redisClient := testutils.SetupTestDB(t)
|
||||
defer testutils.TeardownTestDB(t, db, redisClient)
|
||||
|
||||
accountStore := postgres.NewAccountStore(db, redisClient)
|
||||
ctx := context.Background()
|
||||
|
||||
// 创建两个账号(同一层级,不同店铺)
|
||||
shopID100 := uint(100)
|
||||
accountA := &model.Account{
|
||||
Username: "user_a",
|
||||
Phone: "13800000001",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypePlatform,
|
||||
ShopID: &shopID100,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(accountA).Error)
|
||||
|
||||
shopID200 := uint(200)
|
||||
accountB := &model.Account{
|
||||
Username: "user_b",
|
||||
Phone: "13800000002",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypePlatform,
|
||||
ShopID: &shopID200,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(accountB).Error)
|
||||
|
||||
// 创建测试数据表
|
||||
type TestData struct {
|
||||
ID uint `gorm:"primarykey"`
|
||||
Name string
|
||||
OwnerID uint
|
||||
ShopID uint
|
||||
}
|
||||
require.NoError(t, db.AutoMigrate(&TestData{}))
|
||||
|
||||
// 插入测试数据
|
||||
testData := []TestData{
|
||||
{Name: "data_shop100", OwnerID: accountA.ID, ShopID: 100},
|
||||
{Name: "data_shop200", OwnerID: accountB.ID, ShopID: 200},
|
||||
}
|
||||
require.NoError(t, db.Create(&testData).Error)
|
||||
|
||||
// A 登录查询(只能看到店铺 100 的数据)
|
||||
ctxWithA := middleware.SetUserContext(ctx, accountA.ID, constants.UserTypePlatform, 100)
|
||||
var resultsA []TestData
|
||||
err := db.WithContext(ctxWithA).
|
||||
Scopes(postgres.DataPermissionScope(ctxWithA, accountStore)).
|
||||
Find(&resultsA).Error
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, resultsA, 1, "A 只能看到店铺 100 的数据")
|
||||
assert.Equal(t, "data_shop100", resultsA[0].Name)
|
||||
|
||||
// B 登录查询(只能看到店铺 200 的数据)
|
||||
ctxWithB := middleware.SetUserContext(ctx, accountB.ID, constants.UserTypePlatform, 200)
|
||||
var resultsB []TestData
|
||||
err = db.WithContext(ctxWithB).
|
||||
Scopes(postgres.DataPermissionScope(ctxWithB, accountStore)).
|
||||
Find(&resultsB).Error
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, resultsB, 1, "B 只能看到店铺 200 的数据")
|
||||
assert.Equal(t, "data_shop200", resultsB[0].Name)
|
||||
}
|
||||
|
||||
// TestDataPermissionScope_NoUserContext 测试无用户上下文时不过滤
|
||||
func TestDataPermissionScope_NoUserContext(t *testing.T) {
|
||||
db, redisClient := testutils.SetupTestDB(t)
|
||||
defer testutils.TeardownTestDB(t, db, redisClient)
|
||||
|
||||
accountStore := postgres.NewAccountStore(db, redisClient)
|
||||
ctx := context.Background()
|
||||
|
||||
// 创建测试数据表
|
||||
type TestData struct {
|
||||
ID uint `gorm:"primarykey"`
|
||||
Name string
|
||||
OwnerID uint
|
||||
ShopID uint
|
||||
}
|
||||
require.NoError(t, db.AutoMigrate(&TestData{}))
|
||||
|
||||
// 插入测试数据
|
||||
testData := []TestData{
|
||||
{Name: "data1", OwnerID: 1, ShopID: 100},
|
||||
{Name: "data2", OwnerID: 2, ShopID: 200},
|
||||
}
|
||||
require.NoError(t, db.Create(&testData).Error)
|
||||
|
||||
// 使用没有用户信息的上下文查询(不过滤,可能是系统任务)
|
||||
var results []TestData
|
||||
err := db.WithContext(ctx).
|
||||
Scopes(postgres.DataPermissionScope(ctx, accountStore)).
|
||||
Find(&results).Error
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, results, 0, "无用户上下文时应该返回空数据(根据 scopes.go 的实现)")
|
||||
}
|
||||
|
||||
// TestDataPermissionScope_ErrorHandling 测试查询下级 ID 失败时的降级策略
|
||||
func TestDataPermissionScope_ErrorHandling(t *testing.T) {
|
||||
db, redisClient := testutils.SetupTestDB(t)
|
||||
defer testutils.TeardownTestDB(t, db, redisClient)
|
||||
|
||||
accountStore := postgres.NewAccountStore(db, redisClient)
|
||||
ctx := context.Background()
|
||||
|
||||
// 创建测试账号
|
||||
accountA := &model.Account{
|
||||
Username: "user_a",
|
||||
Phone: "13800000001",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(accountA).Error)
|
||||
|
||||
shopIDA := uint(100)
|
||||
accountA.ShopID = &shopIDA
|
||||
require.NoError(t, db.Save(accountA).Error)
|
||||
|
||||
// 创建测试数据表
|
||||
type TestData struct {
|
||||
ID uint `gorm:"primarykey"`
|
||||
Name string
|
||||
OwnerID uint
|
||||
ShopID uint
|
||||
}
|
||||
require.NoError(t, db.AutoMigrate(&TestData{}))
|
||||
|
||||
// 插入测试数据
|
||||
testData := []TestData{
|
||||
{Name: "data_a", OwnerID: accountA.ID, ShopID: 100},
|
||||
{Name: "data_b", OwnerID: 999, ShopID: 100},
|
||||
}
|
||||
require.NoError(t, db.Create(&testData).Error)
|
||||
|
||||
// 关闭 Redis 连接以模拟错误(递归查询失败)
|
||||
redisClient.Close()
|
||||
|
||||
// 使用 A 的上下文查询(降级策略:只返回自己的数据)
|
||||
ctxWithA := middleware.SetUserContext(ctx, accountA.ID, constants.UserTypePlatform, 100)
|
||||
var resultsA []TestData
|
||||
err := db.WithContext(ctxWithA).
|
||||
Scopes(postgres.DataPermissionScope(ctxWithA, accountStore)).
|
||||
Find(&resultsA).Error
|
||||
require.NoError(t, err)
|
||||
|
||||
// 降级策略应该只返回自己的数据
|
||||
assert.Len(t, resultsA, 1, "查询下级 ID 失败时,应该降级为只返回自己的数据")
|
||||
assert.Equal(t, "data_a", resultsA[0].Name)
|
||||
}
|
||||
@@ -19,7 +19,7 @@ func TestQueueClientEnqueue(t *testing.T) {
|
||||
redisClient := redis.NewClient(&redis.Options{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer redisClient.Close()
|
||||
defer func() { _ = redisClient.Close() }()
|
||||
|
||||
ctx := context.Background()
|
||||
redisClient.FlushDB(ctx)
|
||||
@@ -27,7 +27,7 @@ func TestQueueClientEnqueue(t *testing.T) {
|
||||
client := asynq.NewClient(asynq.RedisClientOpt{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer client.Close()
|
||||
defer func() { _ = client.Close() }()
|
||||
|
||||
payload := map[string]string{
|
||||
"request_id": "test-001",
|
||||
@@ -50,7 +50,7 @@ func TestQueueClientEnqueueWithOptions(t *testing.T) {
|
||||
redisClient := redis.NewClient(&redis.Options{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer redisClient.Close()
|
||||
defer func() { _ = redisClient.Close() }()
|
||||
|
||||
ctx := context.Background()
|
||||
redisClient.FlushDB(ctx)
|
||||
@@ -58,7 +58,7 @@ func TestQueueClientEnqueueWithOptions(t *testing.T) {
|
||||
client := asynq.NewClient(asynq.RedisClientOpt{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer client.Close()
|
||||
defer func() { _ = client.Close() }()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -139,7 +139,7 @@ func TestQueueClientTaskUniqueness(t *testing.T) {
|
||||
redisClient := redis.NewClient(&redis.Options{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer redisClient.Close()
|
||||
defer func() { _ = redisClient.Close() }()
|
||||
|
||||
ctx := context.Background()
|
||||
redisClient.FlushDB(ctx)
|
||||
@@ -147,7 +147,7 @@ func TestQueueClientTaskUniqueness(t *testing.T) {
|
||||
client := asynq.NewClient(asynq.RedisClientOpt{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer client.Close()
|
||||
defer func() { _ = client.Close() }()
|
||||
|
||||
payload := map[string]string{
|
||||
"request_id": "unique-001",
|
||||
@@ -227,7 +227,7 @@ func TestTaskPayloadSizeLimit(t *testing.T) {
|
||||
redisClient := redis.NewClient(&redis.Options{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer redisClient.Close()
|
||||
defer func() { _ = redisClient.Close() }()
|
||||
|
||||
ctx := context.Background()
|
||||
redisClient.FlushDB(ctx)
|
||||
@@ -235,7 +235,7 @@ func TestTaskPayloadSizeLimit(t *testing.T) {
|
||||
client := asynq.NewClient(asynq.RedisClientOpt{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer client.Close()
|
||||
defer func() { _ = client.Close() }()
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
@@ -271,7 +271,7 @@ func TestTaskScheduling(t *testing.T) {
|
||||
redisClient := redis.NewClient(&redis.Options{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer redisClient.Close()
|
||||
defer func() { _ = redisClient.Close() }()
|
||||
|
||||
ctx := context.Background()
|
||||
redisClient.FlushDB(ctx)
|
||||
@@ -279,7 +279,7 @@ func TestTaskScheduling(t *testing.T) {
|
||||
client := asynq.NewClient(asynq.RedisClientOpt{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer client.Close()
|
||||
defer func() { _ = client.Close() }()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -323,7 +323,7 @@ func TestQueueInspectorStats(t *testing.T) {
|
||||
redisClient := redis.NewClient(&redis.Options{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer redisClient.Close()
|
||||
defer func() { _ = redisClient.Close() }()
|
||||
|
||||
ctx := context.Background()
|
||||
redisClient.FlushDB(ctx)
|
||||
@@ -331,7 +331,7 @@ func TestQueueInspectorStats(t *testing.T) {
|
||||
client := asynq.NewClient(asynq.RedisClientOpt{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer client.Close()
|
||||
defer func() { _ = client.Close() }()
|
||||
|
||||
// 提交一些任务
|
||||
for i := 0; i < 5; i++ {
|
||||
@@ -351,7 +351,7 @@ func TestQueueInspectorStats(t *testing.T) {
|
||||
inspector := asynq.NewInspector(asynq.RedisClientOpt{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer inspector.Close()
|
||||
defer func() { _ = inspector.Close() }()
|
||||
|
||||
info, err := inspector.GetQueueInfo(constants.QueueDefault)
|
||||
require.NoError(t, err)
|
||||
@@ -366,7 +366,7 @@ func TestTaskRetention(t *testing.T) {
|
||||
redisClient := redis.NewClient(&redis.Options{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer redisClient.Close()
|
||||
defer func() { _ = redisClient.Close() }()
|
||||
|
||||
ctx := context.Background()
|
||||
redisClient.FlushDB(ctx)
|
||||
@@ -374,7 +374,7 @@ func TestTaskRetention(t *testing.T) {
|
||||
client := asynq.NewClient(asynq.RedisClientOpt{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer client.Close()
|
||||
defer func() { _ = client.Close() }()
|
||||
|
||||
payload := map[string]string{
|
||||
"request_id": "retention-test-001",
|
||||
@@ -398,7 +398,7 @@ func TestQueueDraining(t *testing.T) {
|
||||
redisClient := redis.NewClient(&redis.Options{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer redisClient.Close()
|
||||
defer func() { _ = redisClient.Close() }()
|
||||
|
||||
ctx := context.Background()
|
||||
redisClient.FlushDB(ctx)
|
||||
@@ -406,7 +406,7 @@ func TestQueueDraining(t *testing.T) {
|
||||
inspector := asynq.NewInspector(asynq.RedisClientOpt{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer inspector.Close()
|
||||
defer func() { _ = inspector.Close() }()
|
||||
|
||||
// 暂停队列
|
||||
err := inspector.PauseQueue(constants.QueueDefault)
|
||||
@@ -432,7 +432,7 @@ func TestTaskCancellation(t *testing.T) {
|
||||
redisClient := redis.NewClient(&redis.Options{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer redisClient.Close()
|
||||
defer func() { _ = redisClient.Close() }()
|
||||
|
||||
ctx := context.Background()
|
||||
redisClient.FlushDB(ctx)
|
||||
@@ -440,7 +440,7 @@ func TestTaskCancellation(t *testing.T) {
|
||||
client := asynq.NewClient(asynq.RedisClientOpt{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer client.Close()
|
||||
defer func() { _ = client.Close() }()
|
||||
|
||||
payload := map[string]string{
|
||||
"request_id": "cancel-test-001",
|
||||
@@ -458,7 +458,7 @@ func TestTaskCancellation(t *testing.T) {
|
||||
inspector := asynq.NewInspector(asynq.RedisClientOpt{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer inspector.Close()
|
||||
defer func() { _ = inspector.Close() }()
|
||||
|
||||
err = inspector.DeleteTask(constants.QueueDefault, info.ID)
|
||||
require.NoError(t, err)
|
||||
@@ -474,7 +474,7 @@ func TestBatchTaskEnqueue(t *testing.T) {
|
||||
redisClient := redis.NewClient(&redis.Options{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer redisClient.Close()
|
||||
defer func() { _ = redisClient.Close() }()
|
||||
|
||||
ctx := context.Background()
|
||||
redisClient.FlushDB(ctx)
|
||||
@@ -482,7 +482,7 @@ func TestBatchTaskEnqueue(t *testing.T) {
|
||||
client := asynq.NewClient(asynq.RedisClientOpt{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer client.Close()
|
||||
defer func() { _ = client.Close() }()
|
||||
|
||||
// 批量创建任务
|
||||
batchSize := 100
|
||||
@@ -503,7 +503,7 @@ func TestBatchTaskEnqueue(t *testing.T) {
|
||||
inspector := asynq.NewInspector(asynq.RedisClientOpt{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer inspector.Close()
|
||||
defer func() { _ = inspector.Close() }()
|
||||
|
||||
info, err := inspector.GetQueueInfo(constants.QueueDefault)
|
||||
require.NoError(t, err)
|
||||
@@ -515,7 +515,7 @@ func TestTaskGrouping(t *testing.T) {
|
||||
redisClient := redis.NewClient(&redis.Options{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer redisClient.Close()
|
||||
defer func() { _ = redisClient.Close() }()
|
||||
|
||||
ctx := context.Background()
|
||||
redisClient.FlushDB(ctx)
|
||||
@@ -523,7 +523,7 @@ func TestTaskGrouping(t *testing.T) {
|
||||
client := asynq.NewClient(asynq.RedisClientOpt{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer client.Close()
|
||||
defer func() { _ = client.Close() }()
|
||||
|
||||
// 提交分组任务
|
||||
groupKey := "email-batch-001"
|
||||
@@ -547,7 +547,7 @@ func TestTaskGrouping(t *testing.T) {
|
||||
inspector := asynq.NewInspector(asynq.RedisClientOpt{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer inspector.Close()
|
||||
defer func() { _ = inspector.Close() }()
|
||||
|
||||
info, err := inspector.GetQueueInfo(constants.QueueDefault)
|
||||
require.NoError(t, err)
|
||||
|
||||
302
tests/unit/soft_delete_test.go
Normal file
302
tests/unit/soft_delete_test.go
Normal file
@@ -0,0 +1,302 @@
|
||||
package unit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/tests/testutils"
|
||||
)
|
||||
|
||||
// TestAccountSoftDelete 测试账号软删除功能
|
||||
func TestAccountSoftDelete(t *testing.T) {
|
||||
db, redisClient := testutils.SetupTestDB(t)
|
||||
defer testutils.TeardownTestDB(t, db, redisClient)
|
||||
|
||||
store := postgres.NewAccountStore(db, redisClient)
|
||||
ctx := context.Background()
|
||||
|
||||
// 创建测试账号
|
||||
account := &model.Account{
|
||||
Username: "soft_delete_user",
|
||||
Phone: "13800000001",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
err := store.Create(ctx, account)
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Run("软删除账号", func(t *testing.T) {
|
||||
err := store.Delete(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 正常查询应该找不到
|
||||
_, err = store.GetByID(ctx, account.ID)
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, gorm.ErrRecordNotFound, err)
|
||||
})
|
||||
|
||||
t.Run("使用 Unscoped 可以查到已删除账号", func(t *testing.T) {
|
||||
var found model.Account
|
||||
err := db.Unscoped().First(&found, account.ID).Error
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, account.Username, found.Username)
|
||||
assert.NotNil(t, found.DeletedAt)
|
||||
})
|
||||
|
||||
t.Run("软删除后可以重用用户名和手机号", func(t *testing.T) {
|
||||
// 创建同名账号(因为原账号已软删除)
|
||||
newAccount := &model.Account{
|
||||
Username: "soft_delete_user", // 重用已删除账号的用户名
|
||||
Phone: "13800000001", // 重用已删除账号的手机号
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
err := store.Create(ctx, newAccount)
|
||||
require.NoError(t, err)
|
||||
assert.NotEqual(t, account.ID, newAccount.ID)
|
||||
})
|
||||
}
|
||||
|
||||
// TestRoleSoftDelete 测试角色软删除功能
|
||||
func TestRoleSoftDelete(t *testing.T) {
|
||||
db, redisClient := testutils.SetupTestDB(t)
|
||||
defer testutils.TeardownTestDB(t, db, redisClient)
|
||||
|
||||
roleStore := postgres.NewRoleStore(db)
|
||||
ctx := context.Background()
|
||||
|
||||
// 创建测试角色
|
||||
role := &model.Role{
|
||||
RoleName: "test_role",
|
||||
RoleDesc: "测试角色",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
err := roleStore.Create(ctx, role)
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Run("软删除角色", func(t *testing.T) {
|
||||
err := roleStore.Delete(ctx, role.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 正常查询应该找不到
|
||||
_, err = roleStore.GetByID(ctx, role.ID)
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, gorm.ErrRecordNotFound, err)
|
||||
})
|
||||
|
||||
t.Run("使用 Unscoped 可以查到已删除角色", func(t *testing.T) {
|
||||
var found model.Role
|
||||
err := db.Unscoped().First(&found, role.ID).Error
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, role.RoleName, found.RoleName)
|
||||
assert.NotNil(t, found.DeletedAt)
|
||||
})
|
||||
}
|
||||
|
||||
// TestPermissionSoftDelete 测试权限软删除功能
|
||||
func TestPermissionSoftDelete(t *testing.T) {
|
||||
db, redisClient := testutils.SetupTestDB(t)
|
||||
defer testutils.TeardownTestDB(t, db, redisClient)
|
||||
|
||||
permissionStore := postgres.NewPermissionStore(db)
|
||||
ctx := context.Background()
|
||||
|
||||
// 创建测试权限
|
||||
permission := &model.Permission{
|
||||
PermName: "测试权限",
|
||||
PermCode: "test:permission",
|
||||
PermType: constants.PermissionTypeMenu,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
err := permissionStore.Create(ctx, permission)
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Run("软删除权限", func(t *testing.T) {
|
||||
err := permissionStore.Delete(ctx, permission.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 正常查询应该找不到
|
||||
_, err = permissionStore.GetByID(ctx, permission.ID)
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, gorm.ErrRecordNotFound, err)
|
||||
})
|
||||
|
||||
t.Run("软删除后可以重用权限码", func(t *testing.T) {
|
||||
newPermission := &model.Permission{
|
||||
PermName: "新测试权限",
|
||||
PermCode: "test:permission", // 重用已删除权限的 perm_code
|
||||
PermType: constants.PermissionTypeMenu,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
err := permissionStore.Create(ctx, newPermission)
|
||||
require.NoError(t, err)
|
||||
assert.NotEqual(t, permission.ID, newPermission.ID)
|
||||
})
|
||||
}
|
||||
|
||||
// TestAccountRoleSoftDelete 测试账号-角色关联软删除功能
|
||||
func TestAccountRoleSoftDelete(t *testing.T) {
|
||||
db, redisClient := testutils.SetupTestDB(t)
|
||||
defer testutils.TeardownTestDB(t, db, redisClient)
|
||||
|
||||
accountStore := postgres.NewAccountStore(db, redisClient)
|
||||
roleStore := postgres.NewRoleStore(db)
|
||||
accountRoleStore := postgres.NewAccountRoleStore(db)
|
||||
ctx := context.Background()
|
||||
|
||||
// 创建测试账号
|
||||
account := &model.Account{
|
||||
Username: "ar_user",
|
||||
Phone: "13800000001",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
err := accountStore.Create(ctx, account)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 创建测试角色
|
||||
role := &model.Role{
|
||||
RoleName: "ar_role",
|
||||
RoleDesc: "测试角色",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
err = roleStore.Create(ctx, role)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 创建关联
|
||||
accountRole := &model.AccountRole{
|
||||
AccountID: account.ID,
|
||||
RoleID: role.ID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
err = accountRoleStore.Create(ctx, accountRole)
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Run("软删除账号-角色关联", func(t *testing.T) {
|
||||
err := accountRoleStore.Delete(ctx, account.ID, role.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 查询应该找不到
|
||||
roles, err := accountRoleStore.GetByAccountID(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, roles, 0)
|
||||
})
|
||||
|
||||
t.Run("软删除后可以重新关联", func(t *testing.T) {
|
||||
newAccountRole := &model.AccountRole{
|
||||
AccountID: account.ID,
|
||||
RoleID: role.ID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
err := accountRoleStore.Create(ctx, newAccountRole)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 验证可以查询到
|
||||
roles, err := accountRoleStore.GetByAccountID(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, roles, 1)
|
||||
})
|
||||
}
|
||||
|
||||
// TestRolePermissionSoftDelete 测试角色-权限关联软删除功能
|
||||
func TestRolePermissionSoftDelete(t *testing.T) {
|
||||
db, redisClient := testutils.SetupTestDB(t)
|
||||
defer testutils.TeardownTestDB(t, db, redisClient)
|
||||
|
||||
roleStore := postgres.NewRoleStore(db)
|
||||
permissionStore := postgres.NewPermissionStore(db)
|
||||
rolePermissionStore := postgres.NewRolePermissionStore(db)
|
||||
ctx := context.Background()
|
||||
|
||||
// 创建测试角色
|
||||
role := &model.Role{
|
||||
RoleName: "rp_role",
|
||||
RoleDesc: "测试角色",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
err := roleStore.Create(ctx, role)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 创建测试权限
|
||||
permission := &model.Permission{
|
||||
PermName: "rp_permission",
|
||||
PermCode: "rp:permission",
|
||||
PermType: constants.PermissionTypeMenu,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
err = permissionStore.Create(ctx, permission)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 创建关联
|
||||
rolePermission := &model.RolePermission{
|
||||
RoleID: role.ID,
|
||||
PermID: permission.ID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
err = rolePermissionStore.Create(ctx, rolePermission)
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Run("软删除角色-权限关联", func(t *testing.T) {
|
||||
err := rolePermissionStore.Delete(ctx, role.ID, permission.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 查询应该找不到
|
||||
permissions, err := rolePermissionStore.GetByRoleID(ctx, role.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, permissions, 0)
|
||||
})
|
||||
|
||||
t.Run("软删除后可以重新关联", func(t *testing.T) {
|
||||
newRolePermission := &model.RolePermission{
|
||||
RoleID: role.ID,
|
||||
PermID: permission.ID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
err := rolePermissionStore.Create(ctx, newRolePermission)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 验证可以查询到
|
||||
permissions, err := rolePermissionStore.GetByRoleID(ctx, role.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, permissions, 1)
|
||||
})
|
||||
}
|
||||
294
tests/unit/subordinate_cache_test.go
Normal file
294
tests/unit/subordinate_cache_test.go
Normal file
@@ -0,0 +1,294 @@
|
||||
package unit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/bytedance/sonic"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/tests/testutils"
|
||||
)
|
||||
|
||||
// TestGetSubordinateIDs_CacheHit 测试 Redis 缓存命中
|
||||
func TestGetSubordinateIDs_CacheHit(t *testing.T) {
|
||||
db, redisClient := testutils.SetupTestDB(t)
|
||||
defer testutils.TeardownTestDB(t, db, redisClient)
|
||||
|
||||
store := postgres.NewAccountStore(db, redisClient)
|
||||
ctx := context.Background()
|
||||
|
||||
// 创建测试账号
|
||||
accountA := &model.Account{
|
||||
Username: "user_a",
|
||||
Phone: "13800000001",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(accountA).Error)
|
||||
|
||||
accountB := &model.Account{
|
||||
Username: "user_b",
|
||||
Phone: "13800000002",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypeAgent,
|
||||
ParentID: &accountA.ID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(accountB).Error)
|
||||
|
||||
// 第一次查询(缓存未命中,会写入缓存)
|
||||
ids1, err := store.GetSubordinateIDs(ctx, accountA.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, ids1, 2)
|
||||
|
||||
// 验证缓存已写入
|
||||
cacheKey := constants.RedisAccountSubordinatesKey(accountA.ID)
|
||||
cached, err := redisClient.Get(ctx, cacheKey).Result()
|
||||
require.NoError(t, err)
|
||||
var cachedIDs []uint
|
||||
require.NoError(t, sonic.Unmarshal([]byte(cached), &cachedIDs))
|
||||
assert.Equal(t, ids1, cachedIDs)
|
||||
|
||||
// 第二次查询(缓存命中,不查询数据库)
|
||||
ids2, err := store.GetSubordinateIDs(ctx, accountA.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, ids1, ids2)
|
||||
}
|
||||
|
||||
// TestGetSubordinateIDs_CacheExpiry 测试缓存过期
|
||||
func TestGetSubordinateIDs_CacheExpiry(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("跳过缓存过期测试")
|
||||
}
|
||||
|
||||
db, redisClient := testutils.SetupTestDB(t)
|
||||
defer testutils.TeardownTestDB(t, db, redisClient)
|
||||
|
||||
store := postgres.NewAccountStore(db, redisClient)
|
||||
ctx := context.Background()
|
||||
|
||||
// 创建测试账号
|
||||
accountA := &model.Account{
|
||||
Username: "user_a",
|
||||
Phone: "13800000001",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(accountA).Error)
|
||||
|
||||
// 第一次查询(写入缓存)
|
||||
ids1, err := store.GetSubordinateIDs(ctx, accountA.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 验证缓存 TTL(应该是 30 分钟)
|
||||
cacheKey := constants.RedisAccountSubordinatesKey(accountA.ID)
|
||||
ttl, err := redisClient.TTL(ctx, cacheKey).Result()
|
||||
require.NoError(t, err)
|
||||
assert.Greater(t, ttl, 29*time.Minute)
|
||||
assert.LessOrEqual(t, ttl, 30*time.Minute)
|
||||
|
||||
// 模拟缓存过期(手动删除)
|
||||
require.NoError(t, redisClient.Del(ctx, cacheKey).Err())
|
||||
|
||||
// 再次查询(缓存未命中,重新查询数据库)
|
||||
ids2, err := store.GetSubordinateIDs(ctx, accountA.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, ids1, ids2)
|
||||
|
||||
// 验证缓存已重新写入
|
||||
cached, err := redisClient.Get(ctx, cacheKey).Result()
|
||||
require.NoError(t, err)
|
||||
var cachedIDs []uint
|
||||
require.NoError(t, sonic.Unmarshal([]byte(cached), &cachedIDs))
|
||||
assert.Equal(t, ids2, cachedIDs)
|
||||
}
|
||||
|
||||
// TestClearSubordinatesCache 测试清除指定账号的缓存
|
||||
func TestClearSubordinatesCache(t *testing.T) {
|
||||
db, redisClient := testutils.SetupTestDB(t)
|
||||
defer testutils.TeardownTestDB(t, db, redisClient)
|
||||
|
||||
store := postgres.NewAccountStore(db, redisClient)
|
||||
ctx := context.Background()
|
||||
|
||||
// 创建测试账号
|
||||
accountA := &model.Account{
|
||||
Username: "user_a",
|
||||
Phone: "13800000001",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(accountA).Error)
|
||||
|
||||
// 查询以写入缓存
|
||||
_, err := store.GetSubordinateIDs(ctx, accountA.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 验证缓存存在
|
||||
cacheKey := constants.RedisAccountSubordinatesKey(accountA.ID)
|
||||
exists, err := redisClient.Exists(ctx, cacheKey).Result()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(1), exists)
|
||||
|
||||
// 清除缓存
|
||||
err = store.ClearSubordinatesCache(ctx, accountA.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 验证缓存已删除
|
||||
exists, err = redisClient.Exists(ctx, cacheKey).Result()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(0), exists)
|
||||
}
|
||||
|
||||
// TestClearSubordinatesCacheForParents 测试递归清除上级缓存
|
||||
func TestClearSubordinatesCacheForParents(t *testing.T) {
|
||||
db, redisClient := testutils.SetupTestDB(t)
|
||||
defer testutils.TeardownTestDB(t, db, redisClient)
|
||||
|
||||
store := postgres.NewAccountStore(db, redisClient)
|
||||
ctx := context.Background()
|
||||
|
||||
// 创建层级结构: A -> B -> C
|
||||
accountA := &model.Account{
|
||||
Username: "user_a",
|
||||
Phone: "13800000001",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(accountA).Error)
|
||||
|
||||
accountB := &model.Account{
|
||||
Username: "user_b",
|
||||
Phone: "13800000002",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypeAgent,
|
||||
ParentID: &accountA.ID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(accountB).Error)
|
||||
|
||||
accountC := &model.Account{
|
||||
Username: "user_c",
|
||||
Phone: "13800000003",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypeAgent,
|
||||
ParentID: &accountB.ID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(accountC).Error)
|
||||
|
||||
// 查询所有账号以写入缓存
|
||||
_, err := store.GetSubordinateIDs(ctx, accountA.ID)
|
||||
require.NoError(t, err)
|
||||
_, err = store.GetSubordinateIDs(ctx, accountB.ID)
|
||||
require.NoError(t, err)
|
||||
_, err = store.GetSubordinateIDs(ctx, accountC.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 验证所有缓存存在
|
||||
cacheKeyA := constants.RedisAccountSubordinatesKey(accountA.ID)
|
||||
cacheKeyB := constants.RedisAccountSubordinatesKey(accountB.ID)
|
||||
cacheKeyC := constants.RedisAccountSubordinatesKey(accountC.ID)
|
||||
|
||||
exists, _ := redisClient.Exists(ctx, cacheKeyA).Result()
|
||||
assert.Equal(t, int64(1), exists)
|
||||
exists, _ = redisClient.Exists(ctx, cacheKeyB).Result()
|
||||
assert.Equal(t, int64(1), exists)
|
||||
exists, _ = redisClient.Exists(ctx, cacheKeyC).Result()
|
||||
assert.Equal(t, int64(1), exists)
|
||||
|
||||
// 清除 C 的缓存(应该递归清除 B 和 A 的缓存)
|
||||
err = store.ClearSubordinatesCacheForParents(ctx, accountC.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 验证所有上级缓存已删除
|
||||
exists, _ = redisClient.Exists(ctx, cacheKeyA).Result()
|
||||
assert.Equal(t, int64(0), exists, "A 的缓存应该被清除")
|
||||
exists, _ = redisClient.Exists(ctx, cacheKeyB).Result()
|
||||
assert.Equal(t, int64(0), exists, "B 的缓存应该被清除")
|
||||
exists, _ = redisClient.Exists(ctx, cacheKeyC).Result()
|
||||
assert.Equal(t, int64(0), exists, "C 的缓存应该被清除")
|
||||
}
|
||||
|
||||
// TestCacheInvalidationOnCreate 测试创建账号时清除父账号缓存
|
||||
func TestCacheInvalidationOnCreate(t *testing.T) {
|
||||
db, redisClient := testutils.SetupTestDB(t)
|
||||
defer testutils.TeardownTestDB(t, db, redisClient)
|
||||
|
||||
store := postgres.NewAccountStore(db, redisClient)
|
||||
ctx := context.Background()
|
||||
|
||||
// 创建父账号
|
||||
accountA := &model.Account{
|
||||
Username: "user_a",
|
||||
Phone: "13800000001",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(accountA).Error)
|
||||
|
||||
// 查询 A 的下级(只有自己),写入缓存
|
||||
ids1, err := store.GetSubordinateIDs(ctx, accountA.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, ids1, 1)
|
||||
|
||||
// 验证缓存存在
|
||||
cacheKey := constants.RedisAccountSubordinatesKey(accountA.ID)
|
||||
exists, _ := redisClient.Exists(ctx, cacheKey).Result()
|
||||
assert.Equal(t, int64(1), exists)
|
||||
|
||||
// 创建子账号 B(应该清除 A 的缓存)
|
||||
accountB := &model.Account{
|
||||
Username: "user_b",
|
||||
Phone: "13800000002",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypeAgent,
|
||||
ParentID: &accountA.ID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(accountB).Error)
|
||||
|
||||
// 注意:缓存清除逻辑在 Service 层,这里模拟清除
|
||||
err = store.ClearSubordinatesCacheForParents(ctx, accountA.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 验证缓存已清除
|
||||
exists, _ = redisClient.Exists(ctx, cacheKey).Result()
|
||||
assert.Equal(t, int64(0), exists, "创建子账号后,父账号的缓存应该被清除")
|
||||
|
||||
// 再次查询(缓存未命中,重新查询数据库,应该包含 B)
|
||||
ids2, err := store.GetSubordinateIDs(ctx, accountA.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, ids2, 2, "应该包含 A 和 B")
|
||||
assert.Contains(t, ids2, accountA.ID)
|
||||
assert.Contains(t, ids2, accountB.ID)
|
||||
}
|
||||
280
tests/unit/subordinate_query_test.go
Normal file
280
tests/unit/subordinate_query_test.go
Normal file
@@ -0,0 +1,280 @@
|
||||
package unit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/tests/testutils"
|
||||
)
|
||||
|
||||
// TestGetSubordinateIDs_SingleLevel 测试单层下级查询
|
||||
func TestGetSubordinateIDs_SingleLevel(t *testing.T) {
|
||||
db, redisClient := testutils.SetupTestDB(t)
|
||||
defer testutils.TeardownTestDB(t, db, redisClient)
|
||||
|
||||
store := postgres.NewAccountStore(db, redisClient)
|
||||
ctx := context.Background()
|
||||
|
||||
// 创建层级结构: A -> B, C
|
||||
accountA := &model.Account{
|
||||
Username: "user_a",
|
||||
Phone: "13800000001",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(accountA).Error)
|
||||
|
||||
accountB := &model.Account{
|
||||
Username: "user_b",
|
||||
Phone: "13800000002",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypeAgent,
|
||||
ParentID: &accountA.ID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(accountB).Error)
|
||||
|
||||
accountC := &model.Account{
|
||||
Username: "user_c",
|
||||
Phone: "13800000003",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypeAgent,
|
||||
ParentID: &accountA.ID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(accountC).Error)
|
||||
|
||||
// 查询 A 的所有下级(应该包含 A, B, C)
|
||||
ids, err := store.GetSubordinateIDs(ctx, accountA.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, ids, 3)
|
||||
assert.Contains(t, ids, accountA.ID)
|
||||
assert.Contains(t, ids, accountB.ID)
|
||||
assert.Contains(t, ids, accountC.ID)
|
||||
}
|
||||
|
||||
// TestGetSubordinateIDs_MultiLevel 测试多层递归查询
|
||||
func TestGetSubordinateIDs_MultiLevel(t *testing.T) {
|
||||
db, redisClient := testutils.SetupTestDB(t)
|
||||
defer testutils.TeardownTestDB(t, db, redisClient)
|
||||
|
||||
store := postgres.NewAccountStore(db, redisClient)
|
||||
ctx := context.Background()
|
||||
|
||||
// 创建层级结构: A -> B -> C -> D -> E (5层)
|
||||
accountA := &model.Account{
|
||||
Username: "user_a",
|
||||
Phone: "13800000001",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(accountA).Error)
|
||||
|
||||
accountB := &model.Account{
|
||||
Username: "user_b",
|
||||
Phone: "13800000002",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypeAgent,
|
||||
ParentID: &accountA.ID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(accountB).Error)
|
||||
|
||||
accountC := &model.Account{
|
||||
Username: "user_c",
|
||||
Phone: "13800000003",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypeAgent,
|
||||
ParentID: &accountB.ID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(accountC).Error)
|
||||
|
||||
accountD := &model.Account{
|
||||
Username: "user_d",
|
||||
Phone: "13800000004",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypeEnterprise,
|
||||
ParentID: &accountC.ID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(accountD).Error)
|
||||
|
||||
accountE := &model.Account{
|
||||
Username: "user_e",
|
||||
Phone: "13800000005",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypeEnterprise,
|
||||
ParentID: &accountD.ID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(accountE).Error)
|
||||
|
||||
// 查询 A 的所有下级(应该包含所有 5 个账号)
|
||||
ids, err := store.GetSubordinateIDs(ctx, accountA.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, ids, 5)
|
||||
|
||||
// 查询 B 的所有下级(应该包含 B, C, D, E)
|
||||
ids, err = store.GetSubordinateIDs(ctx, accountB.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, ids, 4)
|
||||
|
||||
// 查询 E 的所有下级(只有自己)
|
||||
ids, err = store.GetSubordinateIDs(ctx, accountE.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, ids, 1)
|
||||
assert.Equal(t, accountE.ID, ids[0])
|
||||
}
|
||||
|
||||
// TestGetSubordinateIDs_WithSoftDeleted 测试包含软删除账号的递归查询
|
||||
func TestGetSubordinateIDs_WithSoftDeleted(t *testing.T) {
|
||||
db, redisClient := testutils.SetupTestDB(t)
|
||||
defer testutils.TeardownTestDB(t, db, redisClient)
|
||||
|
||||
store := postgres.NewAccountStore(db, redisClient)
|
||||
ctx := context.Background()
|
||||
|
||||
// 创建层级结构: A -> B -> C
|
||||
accountA := &model.Account{
|
||||
Username: "user_a",
|
||||
Phone: "13800000001",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(accountA).Error)
|
||||
|
||||
accountB := &model.Account{
|
||||
Username: "user_b",
|
||||
Phone: "13800000002",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypeAgent,
|
||||
ParentID: &accountA.ID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(accountB).Error)
|
||||
|
||||
accountC := &model.Account{
|
||||
Username: "user_c",
|
||||
Phone: "13800000003",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypeAgent,
|
||||
ParentID: &accountB.ID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(accountC).Error)
|
||||
|
||||
// 软删除 B
|
||||
require.NoError(t, db.Delete(accountB).Error)
|
||||
|
||||
// 查询 A 的所有下级(应该仍然包含 B 和 C,因为递归查询包含软删除账号)
|
||||
ids, err := store.GetSubordinateIDs(ctx, accountA.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, ids, 3)
|
||||
assert.Contains(t, ids, accountB.ID)
|
||||
assert.Contains(t, ids, accountC.ID)
|
||||
}
|
||||
|
||||
// TestGetSubordinateIDs_Performance 测试递归查询性能
|
||||
func TestGetSubordinateIDs_Performance(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("跳过性能测试")
|
||||
}
|
||||
|
||||
db, redisClient := testutils.SetupTestDB(t)
|
||||
defer testutils.TeardownTestDB(t, db, redisClient)
|
||||
|
||||
store := postgres.NewAccountStore(db, redisClient)
|
||||
ctx := context.Background()
|
||||
|
||||
// 创建 5 层层级,每层 3 个分支(共 121 个账号)
|
||||
// 层级 1: 1 个账号
|
||||
accountA := &model.Account{
|
||||
Username: "user_root",
|
||||
Phone: "13800000000",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypeRoot,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(accountA).Error)
|
||||
|
||||
// 层级 2: 3 个账号
|
||||
var level2IDs []uint
|
||||
for i := 1; i <= 3; i++ {
|
||||
acc := &model.Account{
|
||||
Username: testutils.GenerateUsername("level2", i),
|
||||
Phone: testutils.GeneratePhone("138", i),
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypePlatform,
|
||||
ParentID: &accountA.ID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(acc).Error)
|
||||
level2IDs = append(level2IDs, acc.ID)
|
||||
}
|
||||
|
||||
// 层级 3: 9 个账号
|
||||
var level3IDs []uint
|
||||
for _, parentID := range level2IDs {
|
||||
for i := 1; i <= 3; i++ {
|
||||
acc := &model.Account{
|
||||
Username: testutils.GenerateUsername("level3", int(parentID)*10+i),
|
||||
Phone: testutils.GeneratePhone("139", int(parentID)*10+i),
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypeAgent,
|
||||
ParentID: &parentID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(acc).Error)
|
||||
level3IDs = append(level3IDs, acc.ID)
|
||||
}
|
||||
}
|
||||
|
||||
// 测试查询性能(应该 < 50ms)
|
||||
start := testutils.Now()
|
||||
ids, err := store.GetSubordinateIDs(ctx, accountA.ID)
|
||||
duration := testutils.Since(start)
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.GreaterOrEqual(t, len(ids), 13) // 至少包含 1 + 3 + 9 个账号
|
||||
|
||||
// 验证性能要求
|
||||
assert.Less(t, duration.Milliseconds(), int64(50), "递归查询应在 50ms 内完成")
|
||||
}
|
||||
Reference in New Issue
Block a user