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:
376
tests/integration/account_role_test.go
Normal file
376
tests/integration/account_role_test.go
Normal file
@@ -0,0 +1,376 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/testcontainers/testcontainers-go"
|
||||
testcontainers_postgres "github.com/testcontainers/testcontainers-go/modules/postgres"
|
||||
testcontainers_redis "github.com/testcontainers/testcontainers-go/modules/redis"
|
||||
"github.com/testcontainers/testcontainers-go/wait"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
accountService "github.com/break/junhong_cmp_fiber/internal/service/account"
|
||||
postgresStore "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"
|
||||
)
|
||||
|
||||
// TestAccountRoleAssociation_AssignRoles 测试账号角色分配功能
|
||||
func TestAccountRoleAssociation_AssignRoles(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
// 启动 PostgreSQL 容器
|
||||
pgContainer, err := testcontainers_postgres.Run(ctx,
|
||||
"postgres:14-alpine",
|
||||
testcontainers_postgres.WithDatabase("testdb"),
|
||||
testcontainers_postgres.WithUsername("postgres"),
|
||||
testcontainers_postgres.WithPassword("password"),
|
||||
testcontainers.WithWaitStrategy(
|
||||
wait.ForLog("database system is ready to accept connections").
|
||||
WithOccurrence(2).
|
||||
WithStartupTimeout(30*time.Second),
|
||||
),
|
||||
)
|
||||
require.NoError(t, err, "启动 PostgreSQL 容器失败")
|
||||
defer func() { _ = pgContainer.Terminate(ctx) }()
|
||||
|
||||
pgConnStr, err := pgContainer.ConnectionString(ctx, "sslmode=disable")
|
||||
require.NoError(t, err)
|
||||
|
||||
// 启动 Redis 容器
|
||||
redisContainer, err := testcontainers_redis.Run(ctx,
|
||||
"redis:6-alpine",
|
||||
)
|
||||
require.NoError(t, err, "启动 Redis 容器失败")
|
||||
defer func() { _ = redisContainer.Terminate(ctx) }()
|
||||
|
||||
redisHost, _ := redisContainer.Host(ctx)
|
||||
redisPort, _ := redisContainer.MappedPort(ctx, "6379")
|
||||
|
||||
// 连接数据库
|
||||
db, err := gorm.Open(postgres.Open(pgConnStr), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// 自动迁移
|
||||
err = db.AutoMigrate(
|
||||
&model.Account{},
|
||||
&model.Role{},
|
||||
&model.AccountRole{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 连接 Redis
|
||||
redisClient := redis.NewClient(&redis.Options{
|
||||
Addr: redisHost + ":" + redisPort.Port(),
|
||||
})
|
||||
|
||||
// 初始化 Store 和 Service
|
||||
accountStore := postgresStore.NewAccountStore(db, redisClient)
|
||||
roleStore := postgresStore.NewRoleStore(db)
|
||||
accountRoleStore := postgresStore.NewAccountRoleStore(db)
|
||||
accService := accountService.New(accountStore, roleStore, accountRoleStore)
|
||||
|
||||
// 创建测试用户上下文
|
||||
userCtx := middleware.SetUserContext(ctx, 1, constants.UserTypeRoot, 0)
|
||||
|
||||
t.Run("成功分配单个角色", func(t *testing.T) {
|
||||
// 创建测试账号
|
||||
account := &model.Account{
|
||||
Username: "single_role_test",
|
||||
Phone: "13800000100",
|
||||
Password: "hashedpassword",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(account)
|
||||
|
||||
// 创建测试角色
|
||||
role := &model.Role{
|
||||
RoleName: "单角色测试",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(role)
|
||||
|
||||
// 分配角色
|
||||
ars, err := accService.AssignRoles(userCtx, account.ID, []uint{role.ID})
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, ars, 1)
|
||||
assert.Equal(t, account.ID, ars[0].AccountID)
|
||||
assert.Equal(t, role.ID, ars[0].RoleID)
|
||||
})
|
||||
|
||||
t.Run("成功分配多个角色", func(t *testing.T) {
|
||||
// 创建测试账号
|
||||
account := &model.Account{
|
||||
Username: "multi_role_test",
|
||||
Phone: "13800000101",
|
||||
Password: "hashedpassword",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(account)
|
||||
|
||||
// 创建多个测试角色
|
||||
roles := make([]*model.Role, 3)
|
||||
roleIDs := make([]uint, 3)
|
||||
for i := 0; i < 3; i++ {
|
||||
roles[i] = &model.Role{
|
||||
RoleName: "多角色测试_" + string(rune('A'+i)),
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(roles[i])
|
||||
roleIDs[i] = roles[i].ID
|
||||
}
|
||||
|
||||
// 分配角色
|
||||
ars, err := accService.AssignRoles(userCtx, account.ID, roleIDs)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, ars, 3)
|
||||
})
|
||||
|
||||
t.Run("获取账号的角色列表", func(t *testing.T) {
|
||||
// 创建测试账号
|
||||
account := &model.Account{
|
||||
Username: "get_roles_test",
|
||||
Phone: "13800000102",
|
||||
Password: "hashedpassword",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(account)
|
||||
|
||||
// 创建并分配角色
|
||||
role := &model.Role{
|
||||
RoleName: "获取角色列表测试",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(role)
|
||||
|
||||
_, err := accService.AssignRoles(userCtx, account.ID, []uint{role.ID})
|
||||
require.NoError(t, err)
|
||||
|
||||
// 获取角色列表
|
||||
roles, err := accService.GetRoles(userCtx, account.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, roles, 1)
|
||||
assert.Equal(t, role.ID, roles[0].ID)
|
||||
})
|
||||
|
||||
t.Run("移除账号的角色", func(t *testing.T) {
|
||||
// 创建测试账号
|
||||
account := &model.Account{
|
||||
Username: "remove_role_test",
|
||||
Phone: "13800000103",
|
||||
Password: "hashedpassword",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(account)
|
||||
|
||||
// 创建并分配角色
|
||||
role := &model.Role{
|
||||
RoleName: "移除角色测试",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(role)
|
||||
|
||||
_, err := accService.AssignRoles(userCtx, account.ID, []uint{role.ID})
|
||||
require.NoError(t, err)
|
||||
|
||||
// 移除角色
|
||||
err = accService.RemoveRole(userCtx, account.ID, role.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 验证角色已被软删除
|
||||
var ar model.AccountRole
|
||||
err = db.Unscoped().Where("account_id = ? AND role_id = ?", account.ID, role.ID).First(&ar).Error
|
||||
require.NoError(t, err)
|
||||
assert.NotNil(t, ar.DeletedAt)
|
||||
})
|
||||
|
||||
t.Run("重复分配角色不会创建重复记录", func(t *testing.T) {
|
||||
// 创建测试账号
|
||||
account := &model.Account{
|
||||
Username: "duplicate_role_test",
|
||||
Phone: "13800000104",
|
||||
Password: "hashedpassword",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(account)
|
||||
|
||||
// 创建测试角色
|
||||
role := &model.Role{
|
||||
RoleName: "重复分配测试",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(role)
|
||||
|
||||
// 第一次分配
|
||||
_, err := accService.AssignRoles(userCtx, account.ID, []uint{role.ID})
|
||||
require.NoError(t, err)
|
||||
|
||||
// 第二次分配相同角色
|
||||
_, err = accService.AssignRoles(userCtx, account.ID, []uint{role.ID})
|
||||
require.NoError(t, err)
|
||||
|
||||
// 验证只有一条记录
|
||||
var count int64
|
||||
db.Model(&model.AccountRole{}).Where("account_id = ? AND role_id = ?", account.ID, role.ID).Count(&count)
|
||||
assert.Equal(t, int64(1), count)
|
||||
})
|
||||
|
||||
t.Run("账号不存在时分配角色失败", func(t *testing.T) {
|
||||
role := &model.Role{
|
||||
RoleName: "账号不存在测试",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(role)
|
||||
|
||||
_, err := accService.AssignRoles(userCtx, 99999, []uint{role.ID})
|
||||
assert.Error(t, err)
|
||||
})
|
||||
|
||||
t.Run("角色不存在时分配失败", func(t *testing.T) {
|
||||
account := &model.Account{
|
||||
Username: "role_not_exist_test",
|
||||
Phone: "13800000105",
|
||||
Password: "hashedpassword",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(account)
|
||||
|
||||
_, err := accService.AssignRoles(userCtx, account.ID, []uint{99999})
|
||||
assert.Error(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
// TestAccountRoleAssociation_SoftDelete 测试软删除对账号角色关联的影响
|
||||
func TestAccountRoleAssociation_SoftDelete(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
// 启动容器
|
||||
pgContainer, err := testcontainers_postgres.Run(ctx,
|
||||
"postgres:14-alpine",
|
||||
testcontainers_postgres.WithDatabase("testdb"),
|
||||
testcontainers_postgres.WithUsername("postgres"),
|
||||
testcontainers_postgres.WithPassword("password"),
|
||||
testcontainers.WithWaitStrategy(
|
||||
wait.ForLog("database system is ready to accept connections").
|
||||
WithOccurrence(2).
|
||||
WithStartupTimeout(30*time.Second),
|
||||
),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = pgContainer.Terminate(ctx) }()
|
||||
|
||||
pgConnStr, _ := pgContainer.ConnectionString(ctx, "sslmode=disable")
|
||||
|
||||
redisContainer, err := testcontainers_redis.Run(ctx,
|
||||
"redis:6-alpine",
|
||||
)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = redisContainer.Terminate(ctx) }()
|
||||
|
||||
redisHost, _ := redisContainer.Host(ctx)
|
||||
redisPort, _ := redisContainer.MappedPort(ctx, "6379")
|
||||
|
||||
// 设置环境
|
||||
db, _ := gorm.Open(postgres.Open(pgConnStr), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
_ = db.AutoMigrate(&model.Account{}, &model.Role{}, &model.AccountRole{})
|
||||
|
||||
redisClient := redis.NewClient(&redis.Options{
|
||||
Addr: redisHost + ":" + redisPort.Port(),
|
||||
})
|
||||
|
||||
accountStore := postgresStore.NewAccountStore(db, redisClient)
|
||||
roleStore := postgresStore.NewRoleStore(db)
|
||||
accountRoleStore := postgresStore.NewAccountRoleStore(db)
|
||||
accService := accountService.New(accountStore, roleStore, accountRoleStore)
|
||||
|
||||
userCtx := middleware.SetUserContext(ctx, 1, constants.UserTypeRoot, 0)
|
||||
|
||||
t.Run("软删除角色后重新分配可以恢复", func(t *testing.T) {
|
||||
// 创建测试数据
|
||||
account := &model.Account{
|
||||
Username: "restore_role_test",
|
||||
Phone: "13800000200",
|
||||
Password: "hashedpassword",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(account)
|
||||
|
||||
role := &model.Role{
|
||||
RoleName: "恢复角色测试",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(role)
|
||||
|
||||
// 分配角色
|
||||
_, err := accService.AssignRoles(userCtx, account.ID, []uint{role.ID})
|
||||
require.NoError(t, err)
|
||||
|
||||
// 移除角色
|
||||
err = accService.RemoveRole(userCtx, account.ID, role.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 重新分配角色
|
||||
ars, err := accService.AssignRoles(userCtx, account.ID, []uint{role.ID})
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, ars, 1)
|
||||
|
||||
// 验证关联已恢复
|
||||
roles, err := accService.GetRoles(userCtx, account.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, roles, 1)
|
||||
})
|
||||
}
|
||||
632
tests/integration/account_test.go
Normal file
632
tests/integration/account_test.go
Normal file
@@ -0,0 +1,632 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/testcontainers/testcontainers-go"
|
||||
testcontainers_postgres "github.com/testcontainers/testcontainers-go/modules/postgres"
|
||||
testcontainers_redis "github.com/testcontainers/testcontainers-go/modules/redis"
|
||||
"github.com/testcontainers/testcontainers-go/wait"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/handler"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/routes"
|
||||
accountService "github.com/break/junhong_cmp_fiber/internal/service/account"
|
||||
postgresStore "github.com/break/junhong_cmp_fiber/internal/store/postgres"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/middleware"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/response"
|
||||
)
|
||||
|
||||
// testEnv 测试环境
|
||||
type testEnv struct {
|
||||
db *gorm.DB
|
||||
redisClient *redis.Client
|
||||
app *fiber.App
|
||||
accountService *accountService.Service
|
||||
postgresCleanup func()
|
||||
redisCleanup func()
|
||||
}
|
||||
|
||||
// setupTestEnv 设置测试环境
|
||||
func setupTestEnv(t *testing.T) *testEnv {
|
||||
t.Helper()
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// 启动 PostgreSQL 容器
|
||||
pgContainer, err := testcontainers_postgres.Run(ctx,
|
||||
"postgres:14-alpine",
|
||||
testcontainers_postgres.WithDatabase("testdb"),
|
||||
testcontainers_postgres.WithUsername("postgres"),
|
||||
testcontainers_postgres.WithPassword("password"),
|
||||
testcontainers.WithWaitStrategy(
|
||||
wait.ForLog("database system is ready to accept connections").
|
||||
WithOccurrence(2).
|
||||
WithStartupTimeout(30*time.Second),
|
||||
),
|
||||
)
|
||||
require.NoError(t, err, "启动 PostgreSQL 容器失败")
|
||||
|
||||
pgConnStr, err := pgContainer.ConnectionString(ctx, "sslmode=disable")
|
||||
require.NoError(t, err)
|
||||
|
||||
// 启动 Redis 容器
|
||||
redisContainer, err := testcontainers_redis.Run(ctx,
|
||||
"redis:6-alpine",
|
||||
)
|
||||
require.NoError(t, err, "启动 Redis 容器失败")
|
||||
|
||||
redisHost, err := redisContainer.Host(ctx)
|
||||
require.NoError(t, err)
|
||||
redisPort, err := redisContainer.MappedPort(ctx, "6379")
|
||||
require.NoError(t, err)
|
||||
|
||||
// 连接数据库
|
||||
db, err := gorm.Open(postgres.Open(pgConnStr), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// 自动迁移
|
||||
err = db.AutoMigrate(
|
||||
&model.Account{},
|
||||
&model.Role{},
|
||||
&model.Permission{},
|
||||
&model.AccountRole{},
|
||||
&model.RolePermission{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 连接 Redis
|
||||
redisClient := redis.NewClient(&redis.Options{
|
||||
Addr: fmt.Sprintf("%s:%s", redisHost, redisPort.Port()),
|
||||
})
|
||||
|
||||
// 初始化 Store
|
||||
accountStore := postgresStore.NewAccountStore(db, redisClient)
|
||||
roleStore := postgresStore.NewRoleStore(db)
|
||||
accountRoleStore := postgresStore.NewAccountRoleStore(db)
|
||||
|
||||
// 初始化 Service
|
||||
accService := accountService.New(accountStore, roleStore, accountRoleStore)
|
||||
|
||||
// 初始化 Handler
|
||||
accountHandler := handler.NewAccountHandler(accService)
|
||||
|
||||
// 创建 Fiber App
|
||||
app := fiber.New(fiber.Config{
|
||||
ErrorHandler: func(c *fiber.Ctx, err error) error {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
},
|
||||
})
|
||||
|
||||
// 注册路由
|
||||
services := &routes.Services{
|
||||
AccountHandler: accountHandler,
|
||||
}
|
||||
routes.RegisterRoutes(app, services)
|
||||
|
||||
return &testEnv{
|
||||
db: db,
|
||||
redisClient: redisClient,
|
||||
app: app,
|
||||
accountService: accService,
|
||||
postgresCleanup: func() {
|
||||
if err := pgContainer.Terminate(ctx); err != nil {
|
||||
t.Logf("终止 PostgreSQL 容器失败: %v", err)
|
||||
}
|
||||
},
|
||||
redisCleanup: func() {
|
||||
if err := redisContainer.Terminate(ctx); err != nil {
|
||||
t.Logf("终止 Redis 容器失败: %v", err)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// teardownTestEnv 清理测试环境
|
||||
func (e *testEnv) teardown() {
|
||||
if e.postgresCleanup != nil {
|
||||
e.postgresCleanup()
|
||||
}
|
||||
if e.redisCleanup != nil {
|
||||
e.redisCleanup()
|
||||
}
|
||||
}
|
||||
|
||||
// createTestAccount 创建测试账号并返回,用于设置测试上下文
|
||||
func createTestAccount(t *testing.T, db *gorm.DB, account *model.Account) *model.Account {
|
||||
t.Helper()
|
||||
err := db.Create(account).Error
|
||||
require.NoError(t, err)
|
||||
return account
|
||||
}
|
||||
|
||||
// TestAccountAPI_Create 测试创建账号 API
|
||||
func TestAccountAPI_Create(t *testing.T) {
|
||||
env := setupTestEnv(t)
|
||||
defer env.teardown()
|
||||
|
||||
// 创建一个测试用的中间件来设置用户上下文
|
||||
testUserID := uint(1)
|
||||
env.app.Use(func(c *fiber.Ctx) error {
|
||||
ctx := middleware.SetUserContext(c.UserContext(), testUserID, constants.UserTypeRoot, 0)
|
||||
c.SetUserContext(ctx)
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// 创建一个 root 账号作为创建者
|
||||
rootAccount := &model.Account{
|
||||
Username: "root",
|
||||
Phone: "13800000000",
|
||||
Password: "hashedpassword",
|
||||
UserType: constants.UserTypeRoot,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
createTestAccount(t, env.db, rootAccount)
|
||||
|
||||
t.Run("成功创建平台账号", func(t *testing.T) {
|
||||
reqBody := model.CreateAccountRequest{
|
||||
Username: "platform_user",
|
||||
Phone: "13800000001",
|
||||
Password: "Password123",
|
||||
UserType: constants.UserTypePlatform,
|
||||
ParentID: &rootAccount.ID,
|
||||
}
|
||||
|
||||
jsonBody, _ := json.Marshal(reqBody)
|
||||
req := httptest.NewRequest("POST", "/api/v1/accounts", bytes.NewReader(jsonBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
|
||||
var result response.Response
|
||||
err = json.NewDecoder(resp.Body).Decode(&result)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 0, result.Code)
|
||||
|
||||
// 验证数据库中账号已创建
|
||||
var count int64
|
||||
env.db.Model(&model.Account{}).Where("username = ?", "platform_user").Count(&count)
|
||||
assert.Equal(t, int64(1), count)
|
||||
})
|
||||
|
||||
t.Run("用户名重复时返回错误", func(t *testing.T) {
|
||||
// 先创建一个账号
|
||||
existingAccount := &model.Account{
|
||||
Username: "existing_user",
|
||||
Phone: "13800000002",
|
||||
Password: "hashedpassword",
|
||||
UserType: constants.UserTypePlatform,
|
||||
ParentID: &rootAccount.ID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
createTestAccount(t, env.db, existingAccount)
|
||||
|
||||
// 尝试创建同名账号
|
||||
reqBody := model.CreateAccountRequest{
|
||||
Username: "existing_user",
|
||||
Phone: "13800000003",
|
||||
Password: "Password123",
|
||||
UserType: constants.UserTypePlatform,
|
||||
ParentID: &rootAccount.ID,
|
||||
}
|
||||
|
||||
jsonBody, _ := json.Marshal(reqBody)
|
||||
req := httptest.NewRequest("POST", "/api/v1/accounts", bytes.NewReader(jsonBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
|
||||
var result response.Response
|
||||
err = json.NewDecoder(resp.Body).Decode(&result)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, errors.CodeUsernameExists, result.Code)
|
||||
})
|
||||
|
||||
t.Run("非root用户缺少parent_id时返回错误", func(t *testing.T) {
|
||||
reqBody := model.CreateAccountRequest{
|
||||
Username: "no_parent_user",
|
||||
Phone: "13800000004",
|
||||
Password: "Password123",
|
||||
UserType: constants.UserTypePlatform,
|
||||
// 没有提供 ParentID
|
||||
}
|
||||
|
||||
jsonBody, _ := json.Marshal(reqBody)
|
||||
req := httptest.NewRequest("POST", "/api/v1/accounts", bytes.NewReader(jsonBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
|
||||
var result response.Response
|
||||
err = json.NewDecoder(resp.Body).Decode(&result)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, errors.CodeParentIDRequired, result.Code)
|
||||
})
|
||||
}
|
||||
|
||||
// TestAccountAPI_Get 测试获取账号详情 API
|
||||
func TestAccountAPI_Get(t *testing.T) {
|
||||
env := setupTestEnv(t)
|
||||
defer env.teardown()
|
||||
|
||||
// 添加测试中间件
|
||||
testUserID := uint(1)
|
||||
env.app.Use(func(c *fiber.Ctx) error {
|
||||
ctx := middleware.SetUserContext(c.UserContext(), testUserID, constants.UserTypeRoot, 0)
|
||||
c.SetUserContext(ctx)
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// 创建测试账号
|
||||
testAccount := &model.Account{
|
||||
Username: "test_user",
|
||||
Phone: "13800000010",
|
||||
Password: "hashedpassword",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
createTestAccount(t, env.db, testAccount)
|
||||
|
||||
t.Run("成功获取账号详情", func(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d", testAccount.ID), nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
|
||||
var result response.Response
|
||||
err = json.NewDecoder(resp.Body).Decode(&result)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 0, result.Code)
|
||||
})
|
||||
|
||||
t.Run("账号不存在时返回错误", func(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/api/v1/accounts/99999", nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
|
||||
var result response.Response
|
||||
err = json.NewDecoder(resp.Body).Decode(&result)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, errors.CodeAccountNotFound, result.Code)
|
||||
})
|
||||
|
||||
t.Run("无效ID返回错误", func(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/api/v1/accounts/invalid", nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
|
||||
var result response.Response
|
||||
err = json.NewDecoder(resp.Body).Decode(&result)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, errors.CodeInvalidParam, result.Code)
|
||||
})
|
||||
}
|
||||
|
||||
// TestAccountAPI_Update 测试更新账号 API
|
||||
func TestAccountAPI_Update(t *testing.T) {
|
||||
env := setupTestEnv(t)
|
||||
defer env.teardown()
|
||||
|
||||
// 添加测试中间件
|
||||
testUserID := uint(1)
|
||||
env.app.Use(func(c *fiber.Ctx) error {
|
||||
ctx := middleware.SetUserContext(c.UserContext(), testUserID, constants.UserTypeRoot, 0)
|
||||
c.SetUserContext(ctx)
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// 创建测试账号
|
||||
testAccount := &model.Account{
|
||||
Username: "update_test",
|
||||
Phone: "13800000020",
|
||||
Password: "hashedpassword",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
createTestAccount(t, env.db, testAccount)
|
||||
|
||||
t.Run("成功更新账号", func(t *testing.T) {
|
||||
newUsername := "updated_user"
|
||||
reqBody := model.UpdateAccountRequest{
|
||||
Username: &newUsername,
|
||||
}
|
||||
|
||||
jsonBody, _ := json.Marshal(reqBody)
|
||||
req := httptest.NewRequest("PUT", fmt.Sprintf("/api/v1/accounts/%d", testAccount.ID), bytes.NewReader(jsonBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
|
||||
// 验证数据库已更新
|
||||
var updated model.Account
|
||||
env.db.First(&updated, testAccount.ID)
|
||||
assert.Equal(t, newUsername, updated.Username)
|
||||
})
|
||||
}
|
||||
|
||||
// TestAccountAPI_Delete 测试删除账号 API
|
||||
func TestAccountAPI_Delete(t *testing.T) {
|
||||
env := setupTestEnv(t)
|
||||
defer env.teardown()
|
||||
|
||||
// 添加测试中间件
|
||||
testUserID := uint(1)
|
||||
env.app.Use(func(c *fiber.Ctx) error {
|
||||
ctx := middleware.SetUserContext(c.UserContext(), testUserID, constants.UserTypeRoot, 0)
|
||||
c.SetUserContext(ctx)
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
t.Run("成功软删除账号", func(t *testing.T) {
|
||||
// 创建测试账号
|
||||
testAccount := &model.Account{
|
||||
Username: "delete_test",
|
||||
Phone: "13800000030",
|
||||
Password: "hashedpassword",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
createTestAccount(t, env.db, testAccount)
|
||||
|
||||
req := httptest.NewRequest("DELETE", fmt.Sprintf("/api/v1/accounts/%d", testAccount.ID), nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
|
||||
// 验证账号已软删除
|
||||
var deleted model.Account
|
||||
err = env.db.Unscoped().First(&deleted, testAccount.ID).Error
|
||||
require.NoError(t, err)
|
||||
assert.NotNil(t, deleted.DeletedAt)
|
||||
})
|
||||
}
|
||||
|
||||
// TestAccountAPI_List 测试账号列表 API
|
||||
func TestAccountAPI_List(t *testing.T) {
|
||||
env := setupTestEnv(t)
|
||||
defer env.teardown()
|
||||
|
||||
// 添加测试中间件
|
||||
testUserID := uint(1)
|
||||
env.app.Use(func(c *fiber.Ctx) error {
|
||||
ctx := middleware.SetUserContext(c.UserContext(), testUserID, constants.UserTypeRoot, 0)
|
||||
c.SetUserContext(ctx)
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// 创建多个测试账号
|
||||
for i := 1; i <= 5; i++ {
|
||||
account := &model.Account{
|
||||
Username: fmt.Sprintf("list_test_%d", i),
|
||||
Phone: fmt.Sprintf("1380000004%d", i),
|
||||
Password: "hashedpassword",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
createTestAccount(t, env.db, account)
|
||||
}
|
||||
|
||||
t.Run("成功获取账号列表", func(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/api/v1/accounts?page=1&page_size=10", nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
|
||||
var result response.Response
|
||||
err = json.NewDecoder(resp.Body).Decode(&result)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 0, result.Code)
|
||||
})
|
||||
|
||||
t.Run("分页功能正常", func(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/api/v1/accounts?page=1&page_size=2", nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
})
|
||||
}
|
||||
|
||||
// TestAccountAPI_AssignRoles 测试分配角色 API
|
||||
func TestAccountAPI_AssignRoles(t *testing.T) {
|
||||
env := setupTestEnv(t)
|
||||
defer env.teardown()
|
||||
|
||||
// 添加测试中间件
|
||||
testUserID := uint(1)
|
||||
env.app.Use(func(c *fiber.Ctx) error {
|
||||
ctx := middleware.SetUserContext(c.UserContext(), testUserID, constants.UserTypeRoot, 0)
|
||||
c.SetUserContext(ctx)
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// 创建测试账号
|
||||
testAccount := &model.Account{
|
||||
Username: "role_test",
|
||||
Phone: "13800000050",
|
||||
Password: "hashedpassword",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
createTestAccount(t, env.db, testAccount)
|
||||
|
||||
// 创建测试角色
|
||||
testRole := &model.Role{
|
||||
RoleName: "测试角色",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(testRole)
|
||||
|
||||
t.Run("成功分配角色", func(t *testing.T) {
|
||||
reqBody := model.AssignRolesRequest{
|
||||
RoleIDs: []uint{testRole.ID},
|
||||
}
|
||||
|
||||
jsonBody, _ := json.Marshal(reqBody)
|
||||
req := httptest.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/%d/roles", testAccount.ID), bytes.NewReader(jsonBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
|
||||
// 验证关联已创建
|
||||
var count int64
|
||||
env.db.Model(&model.AccountRole{}).Where("account_id = ? AND role_id = ?", testAccount.ID, testRole.ID).Count(&count)
|
||||
assert.Equal(t, int64(1), count)
|
||||
})
|
||||
}
|
||||
|
||||
// TestAccountAPI_GetRoles 测试获取账号角色 API
|
||||
func TestAccountAPI_GetRoles(t *testing.T) {
|
||||
env := setupTestEnv(t)
|
||||
defer env.teardown()
|
||||
|
||||
// 添加测试中间件
|
||||
testUserID := uint(1)
|
||||
env.app.Use(func(c *fiber.Ctx) error {
|
||||
ctx := middleware.SetUserContext(c.UserContext(), testUserID, constants.UserTypeRoot, 0)
|
||||
c.SetUserContext(ctx)
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// 创建测试账号
|
||||
testAccount := &model.Account{
|
||||
Username: "get_roles_test",
|
||||
Phone: "13800000060",
|
||||
Password: "hashedpassword",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
createTestAccount(t, env.db, testAccount)
|
||||
|
||||
// 创建并分配角色
|
||||
testRole := &model.Role{
|
||||
RoleName: "获取角色测试",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(testRole)
|
||||
|
||||
accountRole := &model.AccountRole{
|
||||
AccountID: testAccount.ID,
|
||||
RoleID: testRole.ID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(accountRole)
|
||||
|
||||
t.Run("成功获取账号角色", func(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/roles", testAccount.ID), nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
|
||||
var result response.Response
|
||||
err = json.NewDecoder(resp.Body).Decode(&result)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 0, result.Code)
|
||||
})
|
||||
}
|
||||
|
||||
// TestAccountAPI_RemoveRole 测试移除角色 API
|
||||
func TestAccountAPI_RemoveRole(t *testing.T) {
|
||||
env := setupTestEnv(t)
|
||||
defer env.teardown()
|
||||
|
||||
// 添加测试中间件
|
||||
testUserID := uint(1)
|
||||
env.app.Use(func(c *fiber.Ctx) error {
|
||||
ctx := middleware.SetUserContext(c.UserContext(), testUserID, constants.UserTypeRoot, 0)
|
||||
c.SetUserContext(ctx)
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// 创建测试账号
|
||||
testAccount := &model.Account{
|
||||
Username: "remove_role_test",
|
||||
Phone: "13800000070",
|
||||
Password: "hashedpassword",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
createTestAccount(t, env.db, testAccount)
|
||||
|
||||
// 创建并分配角色
|
||||
testRole := &model.Role{
|
||||
RoleName: "移除角色测试",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(testRole)
|
||||
|
||||
accountRole := &model.AccountRole{
|
||||
AccountID: testAccount.ID,
|
||||
RoleID: testRole.ID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(accountRole)
|
||||
|
||||
t.Run("成功移除角色", func(t *testing.T) {
|
||||
req := httptest.NewRequest("DELETE", fmt.Sprintf("/api/v1/accounts/%d/roles/%d", testAccount.ID, testRole.ID), nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
|
||||
// 验证关联已软删除
|
||||
var ar model.AccountRole
|
||||
err = env.db.Unscoped().Where("account_id = ? AND role_id = ?", testAccount.ID, testRole.ID).First(&ar).Error
|
||||
require.NoError(t, err)
|
||||
assert.NotNil(t, ar.DeletedAt)
|
||||
})
|
||||
}
|
||||
405
tests/integration/api_regression_test.go
Normal file
405
tests/integration/api_regression_test.go
Normal file
@@ -0,0 +1,405 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/testcontainers/testcontainers-go"
|
||||
testcontainers_postgres "github.com/testcontainers/testcontainers-go/modules/postgres"
|
||||
testcontainers_redis "github.com/testcontainers/testcontainers-go/modules/redis"
|
||||
"github.com/testcontainers/testcontainers-go/wait"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/handler"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/routes"
|
||||
accountService "github.com/break/junhong_cmp_fiber/internal/service/account"
|
||||
permissionService "github.com/break/junhong_cmp_fiber/internal/service/permission"
|
||||
roleService "github.com/break/junhong_cmp_fiber/internal/service/role"
|
||||
postgresStore "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"
|
||||
)
|
||||
|
||||
// regressionTestEnv 回归测试环境
|
||||
type regressionTestEnv struct {
|
||||
db *gorm.DB
|
||||
redisClient *redis.Client
|
||||
app *fiber.App
|
||||
postgresCleanup func()
|
||||
redisCleanup func()
|
||||
}
|
||||
|
||||
// setupRegressionTestEnv 设置回归测试环境
|
||||
func setupRegressionTestEnv(t *testing.T) *regressionTestEnv {
|
||||
t.Helper()
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// 启动 PostgreSQL 容器
|
||||
pgContainer, err := testcontainers_postgres.RunContainer(ctx,
|
||||
testcontainers.WithImage("postgres:14-alpine"),
|
||||
testcontainers_postgres.WithDatabase("testdb"),
|
||||
testcontainers_postgres.WithUsername("postgres"),
|
||||
testcontainers_postgres.WithPassword("password"),
|
||||
testcontainers.WithWaitStrategy(
|
||||
wait.ForLog("database system is ready to accept connections").
|
||||
WithOccurrence(2).
|
||||
WithStartupTimeout(30*time.Second),
|
||||
),
|
||||
)
|
||||
require.NoError(t, err, "启动 PostgreSQL 容器失败")
|
||||
|
||||
pgConnStr, err := pgContainer.ConnectionString(ctx, "sslmode=disable")
|
||||
require.NoError(t, err)
|
||||
|
||||
// 启动 Redis 容器
|
||||
redisContainer, err := testcontainers_redis.RunContainer(ctx,
|
||||
testcontainers.WithImage("redis:6-alpine"),
|
||||
)
|
||||
require.NoError(t, err, "启动 Redis 容器失败")
|
||||
|
||||
redisHost, err := redisContainer.Host(ctx)
|
||||
require.NoError(t, err)
|
||||
redisPort, err := redisContainer.MappedPort(ctx, "6379")
|
||||
require.NoError(t, err)
|
||||
|
||||
// 连接数据库
|
||||
db, err := gorm.Open(postgres.Open(pgConnStr), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// 自动迁移
|
||||
err = db.AutoMigrate(
|
||||
&model.Account{},
|
||||
&model.Role{},
|
||||
&model.Permission{},
|
||||
&model.AccountRole{},
|
||||
&model.RolePermission{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 连接 Redis
|
||||
redisClient := redis.NewClient(&redis.Options{
|
||||
Addr: fmt.Sprintf("%s:%s", redisHost, redisPort.Port()),
|
||||
})
|
||||
|
||||
// 初始化所有 Store
|
||||
accountStore := postgresStore.NewAccountStore(db, redisClient)
|
||||
roleStore := postgresStore.NewRoleStore(db)
|
||||
permStore := postgresStore.NewPermissionStore(db)
|
||||
accountRoleStore := postgresStore.NewAccountRoleStore(db)
|
||||
rolePermStore := postgresStore.NewRolePermissionStore(db)
|
||||
|
||||
// 初始化所有 Service
|
||||
accService := accountService.New(accountStore, roleStore, accountRoleStore)
|
||||
roleSvc := roleService.New(roleStore, permStore, rolePermStore)
|
||||
permSvc := permissionService.New(permStore)
|
||||
|
||||
// 初始化所有 Handler
|
||||
accountHandler := handler.NewAccountHandler(accService)
|
||||
roleHandler := handler.NewRoleHandler(roleSvc)
|
||||
permHandler := handler.NewPermissionHandler(permSvc)
|
||||
|
||||
// 创建 Fiber App
|
||||
app := fiber.New(fiber.Config{
|
||||
ErrorHandler: func(c *fiber.Ctx, err error) error {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
},
|
||||
})
|
||||
|
||||
// 添加测试中间件设置用户上下文
|
||||
app.Use(func(c *fiber.Ctx) error {
|
||||
ctx := middleware.SetUserContext(c.UserContext(), 1, constants.UserTypeRoot, 0)
|
||||
c.SetUserContext(ctx)
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// 注册所有路由
|
||||
services := &routes.Services{
|
||||
AccountHandler: accountHandler,
|
||||
RoleHandler: roleHandler,
|
||||
PermissionHandler: permHandler,
|
||||
}
|
||||
routes.RegisterRoutes(app, services)
|
||||
|
||||
return ®ressionTestEnv{
|
||||
db: db,
|
||||
redisClient: redisClient,
|
||||
app: app,
|
||||
postgresCleanup: func() {
|
||||
if err := pgContainer.Terminate(ctx); err != nil {
|
||||
t.Logf("终止 PostgreSQL 容器失败: %v", err)
|
||||
}
|
||||
},
|
||||
redisCleanup: func() {
|
||||
if err := redisContainer.Terminate(ctx); err != nil {
|
||||
t.Logf("终止 Redis 容器失败: %v", err)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPIRegression_AllEndpointsAccessible 测试所有 API 端点在重构后仍可访问
|
||||
func TestAPIRegression_AllEndpointsAccessible(t *testing.T) {
|
||||
env := setupRegressionTestEnv(t)
|
||||
defer env.postgresCleanup()
|
||||
defer env.redisCleanup()
|
||||
|
||||
// 定义所有需要测试的端点
|
||||
endpoints := []struct {
|
||||
method string
|
||||
path string
|
||||
name string
|
||||
}{
|
||||
// Health endpoints
|
||||
{"GET", "/health", "Health check"},
|
||||
{"GET", "/health/ready", "Readiness check"},
|
||||
|
||||
// Account endpoints
|
||||
{"GET", "/api/v1/accounts", "List accounts"},
|
||||
{"GET", "/api/v1/accounts/1", "Get account"},
|
||||
|
||||
// Role endpoints
|
||||
{"GET", "/api/v1/roles", "List roles"},
|
||||
{"GET", "/api/v1/roles/1", "Get role"},
|
||||
|
||||
// Permission endpoints
|
||||
{"GET", "/api/v1/permissions", "List permissions"},
|
||||
{"GET", "/api/v1/permissions/1", "Get permission"},
|
||||
{"GET", "/api/v1/permissions/tree", "Get permission tree"},
|
||||
}
|
||||
|
||||
for _, ep := range endpoints {
|
||||
t.Run(ep.name, func(t *testing.T) {
|
||||
req := httptest.NewRequest(ep.method, ep.path, nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 验证端点可访问(状态码不是 404 或 500)
|
||||
assert.NotEqual(t, fiber.StatusNotFound, resp.StatusCode,
|
||||
"端点 %s %s 应该存在", ep.method, ep.path)
|
||||
assert.NotEqual(t, fiber.StatusInternalServerError, resp.StatusCode,
|
||||
"端点 %s %s 不应该返回 500 错误", ep.method, ep.path)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPIRegression_RouteModularization 测试路由模块化后功能正常
|
||||
func TestAPIRegression_RouteModularization(t *testing.T) {
|
||||
env := setupRegressionTestEnv(t)
|
||||
defer env.postgresCleanup()
|
||||
defer env.redisCleanup()
|
||||
|
||||
t.Run("账号模块路由正常", func(t *testing.T) {
|
||||
// 创建测试数据
|
||||
account := &model.Account{
|
||||
Username: "regression_test",
|
||||
Phone: "13800000300",
|
||||
Password: "hashedpassword",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(account)
|
||||
|
||||
// 测试获取账号
|
||||
req := httptest.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d", account.ID), nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
|
||||
// 测试获取角色列表
|
||||
req = httptest.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/roles", account.ID), nil)
|
||||
resp, err = env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
})
|
||||
|
||||
t.Run("角色模块路由正常", func(t *testing.T) {
|
||||
// 创建测试数据
|
||||
role := &model.Role{
|
||||
RoleName: "回归测试角色",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(role)
|
||||
|
||||
// 测试获取角色
|
||||
req := httptest.NewRequest("GET", fmt.Sprintf("/api/v1/roles/%d", role.ID), nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
|
||||
// 测试获取权限列表
|
||||
req = httptest.NewRequest("GET", fmt.Sprintf("/api/v1/roles/%d/permissions", role.ID), nil)
|
||||
resp, err = env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
})
|
||||
|
||||
t.Run("权限模块路由正常", func(t *testing.T) {
|
||||
// 创建测试数据
|
||||
perm := &model.Permission{
|
||||
PermName: "回归测试权限",
|
||||
PermCode: "regression:test:perm",
|
||||
PermType: constants.PermissionTypeMenu,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(perm)
|
||||
|
||||
// 测试获取权限
|
||||
req := httptest.NewRequest("GET", fmt.Sprintf("/api/v1/permissions/%d", perm.ID), nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
|
||||
// 测试获取权限树
|
||||
req = httptest.NewRequest("GET", "/api/v1/permissions/tree", nil)
|
||||
resp, err = env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
})
|
||||
}
|
||||
|
||||
// TestAPIRegression_ErrorHandling 测试错误处理在重构后仍正常
|
||||
func TestAPIRegression_ErrorHandling(t *testing.T) {
|
||||
env := setupRegressionTestEnv(t)
|
||||
defer env.postgresCleanup()
|
||||
defer env.redisCleanup()
|
||||
|
||||
t.Run("资源不存在返回正确错误码", func(t *testing.T) {
|
||||
// 账号不存在
|
||||
req := httptest.NewRequest("GET", "/api/v1/accounts/99999", nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
// 应该返回业务错误,不是 404
|
||||
assert.NotEqual(t, fiber.StatusNotFound, resp.StatusCode)
|
||||
|
||||
// 角色不存在
|
||||
req = httptest.NewRequest("GET", "/api/v1/roles/99999", nil)
|
||||
resp, err = env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.NotEqual(t, fiber.StatusNotFound, resp.StatusCode)
|
||||
|
||||
// 权限不存在
|
||||
req = httptest.NewRequest("GET", "/api/v1/permissions/99999", nil)
|
||||
resp, err = env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.NotEqual(t, fiber.StatusNotFound, resp.StatusCode)
|
||||
})
|
||||
|
||||
t.Run("无效参数返回正确错误码", func(t *testing.T) {
|
||||
// 无效账号 ID
|
||||
req := httptest.NewRequest("GET", "/api/v1/accounts/invalid", nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.NotEqual(t, fiber.StatusInternalServerError, resp.StatusCode)
|
||||
})
|
||||
}
|
||||
|
||||
// TestAPIRegression_Pagination 测试分页功能在重构后仍正常
|
||||
func TestAPIRegression_Pagination(t *testing.T) {
|
||||
env := setupRegressionTestEnv(t)
|
||||
defer env.postgresCleanup()
|
||||
defer env.redisCleanup()
|
||||
|
||||
// 创建测试数据
|
||||
for i := 1; i <= 25; i++ {
|
||||
account := &model.Account{
|
||||
Username: fmt.Sprintf("pagination_test_%d", i),
|
||||
Phone: fmt.Sprintf("138000004%02d", i),
|
||||
Password: "hashedpassword",
|
||||
UserType: constants.UserTypePlatform,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(account)
|
||||
}
|
||||
|
||||
t.Run("分页参数正常工作", func(t *testing.T) {
|
||||
// 第一页
|
||||
req := httptest.NewRequest("GET", "/api/v1/accounts?page=1&page_size=10", nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
|
||||
// 第二页
|
||||
req = httptest.NewRequest("GET", "/api/v1/accounts?page=2&page_size=10", nil)
|
||||
resp, err = env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
})
|
||||
|
||||
t.Run("默认分页参数工作", func(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/api/v1/accounts", nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
})
|
||||
}
|
||||
|
||||
// TestAPIRegression_ResponseFormat 测试响应格式在重构后保持一致
|
||||
func TestAPIRegression_ResponseFormat(t *testing.T) {
|
||||
env := setupRegressionTestEnv(t)
|
||||
defer env.postgresCleanup()
|
||||
defer env.redisCleanup()
|
||||
|
||||
t.Run("成功响应包含正确字段", func(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/api/v1/accounts", nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
|
||||
// 响应应该是 JSON
|
||||
assert.Contains(t, resp.Header.Get("Content-Type"), "application/json")
|
||||
})
|
||||
|
||||
t.Run("健康检查端点响应正常", func(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/health", nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
})
|
||||
}
|
||||
|
||||
// TestAPIRegression_ServicesIntegration 测试服务集成在重构后仍正常
|
||||
func TestAPIRegression_ServicesIntegration(t *testing.T) {
|
||||
env := setupRegressionTestEnv(t)
|
||||
defer env.postgresCleanup()
|
||||
defer env.redisCleanup()
|
||||
|
||||
t.Run("Services 容器正确初始化", func(t *testing.T) {
|
||||
// 验证所有模块路由都已注册
|
||||
endpoints := []string{
|
||||
"/health",
|
||||
"/api/v1/accounts",
|
||||
"/api/v1/roles",
|
||||
"/api/v1/permissions",
|
||||
}
|
||||
|
||||
for _, ep := range endpoints {
|
||||
req := httptest.NewRequest("GET", ep, nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.NotEqual(t, fiber.StatusNotFound, resp.StatusCode,
|
||||
"端点 %s 应该已注册", ep)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -103,7 +103,7 @@ func TestKeyAuthMiddleware_ValidToken(t *testing.T) {
|
||||
// Execute request
|
||||
resp, err := app.Test(req, -1)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
// Assertions
|
||||
assert.Equal(t, 200, resp.StatusCode, "Expected status 200 for valid token")
|
||||
@@ -125,7 +125,7 @@ func TestKeyAuthMiddleware_MissingToken(t *testing.T) {
|
||||
Addr: "localhost:6379",
|
||||
DB: 1,
|
||||
})
|
||||
defer rdb.Close()
|
||||
defer func() { _ = rdb.Close() }()
|
||||
|
||||
// Check Redis availability
|
||||
ctx := context.Background()
|
||||
@@ -142,7 +142,7 @@ func TestKeyAuthMiddleware_MissingToken(t *testing.T) {
|
||||
// Execute request
|
||||
resp, err := app.Test(req, -1)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
// Assertions
|
||||
assert.Equal(t, 401, resp.StatusCode, "Expected status 401 for missing token")
|
||||
@@ -165,7 +165,7 @@ func TestKeyAuthMiddleware_InvalidToken(t *testing.T) {
|
||||
Addr: "localhost:6379",
|
||||
DB: 1,
|
||||
})
|
||||
defer rdb.Close()
|
||||
defer func() { _ = rdb.Close() }()
|
||||
|
||||
// Check Redis availability
|
||||
ctx := context.Background()
|
||||
@@ -186,7 +186,7 @@ func TestKeyAuthMiddleware_InvalidToken(t *testing.T) {
|
||||
// Execute request
|
||||
resp, err := app.Test(req, -1)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
// Assertions
|
||||
assert.Equal(t, 401, resp.StatusCode, "Expected status 401 for invalid token")
|
||||
@@ -209,7 +209,7 @@ func TestKeyAuthMiddleware_ExpiredToken(t *testing.T) {
|
||||
Addr: "localhost:6379",
|
||||
DB: 1,
|
||||
})
|
||||
defer rdb.Close()
|
||||
defer func() { _ = rdb.Close() }()
|
||||
|
||||
// Check Redis availability
|
||||
ctx := context.Background()
|
||||
@@ -239,7 +239,7 @@ func TestKeyAuthMiddleware_ExpiredToken(t *testing.T) {
|
||||
// Execute request
|
||||
resp, err := app.Test(req, -1)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
// Assertions
|
||||
assert.Equal(t, 401, resp.StatusCode, "Expected status 401 for expired token")
|
||||
@@ -261,7 +261,7 @@ func TestKeyAuthMiddleware_RedisDown(t *testing.T) {
|
||||
DialTimeout: 100 * time.Millisecond,
|
||||
ReadTimeout: 100 * time.Millisecond,
|
||||
})
|
||||
defer rdb.Close()
|
||||
defer func() { _ = rdb.Close() }()
|
||||
|
||||
// Create test app with unavailable Redis
|
||||
app := setupAuthTestApp(t, rdb)
|
||||
@@ -273,7 +273,7 @@ func TestKeyAuthMiddleware_RedisDown(t *testing.T) {
|
||||
// Execute request
|
||||
resp, err := app.Test(req, -1)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
// Assertions - should fail closed with 503
|
||||
assert.Equal(t, 503, resp.StatusCode, "Expected status 503 when Redis is unavailable")
|
||||
@@ -296,7 +296,7 @@ func TestKeyAuthMiddleware_UserIDPropagation(t *testing.T) {
|
||||
Addr: "localhost:6379",
|
||||
DB: 1,
|
||||
})
|
||||
defer rdb.Close()
|
||||
defer func() { _ = rdb.Close() }()
|
||||
|
||||
// Check Redis availability
|
||||
ctx := context.Background()
|
||||
@@ -364,7 +364,7 @@ func TestKeyAuthMiddleware_UserIDPropagation(t *testing.T) {
|
||||
// Execute request
|
||||
resp, err := app.Test(req, -1)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
// Assertions
|
||||
assert.Equal(t, 200, resp.StatusCode)
|
||||
@@ -378,7 +378,7 @@ func TestKeyAuthMiddleware_MultipleRequests(t *testing.T) {
|
||||
Addr: "localhost:6379",
|
||||
DB: 1,
|
||||
})
|
||||
defer rdb.Close()
|
||||
defer func() { _ = rdb.Close() }()
|
||||
|
||||
// Check Redis availability
|
||||
ctx := context.Background()
|
||||
@@ -412,7 +412,7 @@ func TestKeyAuthMiddleware_MultipleRequests(t *testing.T) {
|
||||
|
||||
resp, err := app.Test(req, -1)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
assert.Equal(t, 200, resp.StatusCode)
|
||||
|
||||
|
||||
325
tests/integration/data_permission_test.go
Normal file
325
tests/integration/data_permission_test.go
Normal file
@@ -0,0 +1,325 @@
|
||||
package integration
|
||||
|
||||
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"
|
||||
)
|
||||
|
||||
// TestDataPermission_HierarchicalFiltering 测试层级数据权限过滤
|
||||
func TestDataPermission_HierarchicalFiltering(t *testing.T) {
|
||||
store, cleanup := setupTestDB(t)
|
||||
defer cleanup()
|
||||
|
||||
ctx := context.Background()
|
||||
db := store.DB()
|
||||
|
||||
// 创建层级结构: 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)
|
||||
|
||||
shopID := uint(100)
|
||||
accountA.ShopID = &shopID
|
||||
require.NoError(t, db.Save(accountA).Error)
|
||||
|
||||
accountB := &model.Account{
|
||||
Username: "user_b",
|
||||
Phone: "13800000002",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypeAgent,
|
||||
ParentID: &accountA.ID,
|
||||
ShopID: &shopID,
|
||||
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.UserTypeEnterprise,
|
||||
ParentID: &accountB.ID,
|
||||
ShopID: &shopID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(accountC).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: accountB.ID, ShopID: 100},
|
||||
{Name: "data_c", OwnerID: accountC.ID, ShopID: 100},
|
||||
{Name: "data_other", OwnerID: 999, ShopID: 100},
|
||||
}
|
||||
require.NoError(t, db.Create(&testData).Error)
|
||||
|
||||
// 创建 AccountStore 用于递归查询
|
||||
accountStore := postgres.NewAccountStore(db, nil) // Redis 可选
|
||||
|
||||
t.Run("A 用户可以看到 A、B、C 的数据", func(t *testing.T) {
|
||||
ctxWithA := middleware.SetUserContext(ctx, accountA.ID, constants.UserTypePlatform, 100)
|
||||
var results []TestData
|
||||
err := db.WithContext(ctxWithA).
|
||||
Scopes(postgres.DataPermissionScope(ctxWithA, accountStore)).
|
||||
Find(&results).Error
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, results, 3)
|
||||
})
|
||||
|
||||
t.Run("B 用户可以看到 B、C 的数据", func(t *testing.T) {
|
||||
ctxWithB := middleware.SetUserContext(ctx, accountB.ID, constants.UserTypeAgent, 100)
|
||||
var results []TestData
|
||||
err := db.WithContext(ctxWithB).
|
||||
Scopes(postgres.DataPermissionScope(ctxWithB, accountStore)).
|
||||
Find(&results).Error
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, results, 2)
|
||||
})
|
||||
|
||||
t.Run("C 用户只能看到自己的数据", func(t *testing.T) {
|
||||
ctxWithC := middleware.SetUserContext(ctx, accountC.ID, constants.UserTypeEnterprise, 100)
|
||||
var results []TestData
|
||||
err := db.WithContext(ctxWithC).
|
||||
Scopes(postgres.DataPermissionScope(ctxWithC, accountStore)).
|
||||
Find(&results).Error
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, results, 1)
|
||||
assert.Equal(t, "data_c", results[0].Name)
|
||||
})
|
||||
}
|
||||
|
||||
// TestDataPermission_WithoutDataFilter 测试 WithoutDataFilter 选项
|
||||
func TestDataPermission_WithoutDataFilter(t *testing.T) {
|
||||
store, cleanup := setupTestDB(t)
|
||||
defer cleanup()
|
||||
|
||||
ctx := context.Background()
|
||||
db := store.DB()
|
||||
|
||||
// 创建测试账号
|
||||
shopID := uint(100)
|
||||
accountA := &model.Account{
|
||||
Username: "user_a",
|
||||
Phone: "13800000001",
|
||||
Password: "hashed_password",
|
||||
UserType: constants.UserTypePlatform,
|
||||
ShopID: &shopID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
require.NoError(t, db.Create(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},
|
||||
{Name: "data_c", OwnerID: 888, ShopID: 200},
|
||||
}
|
||||
require.NoError(t, db.Create(&testData).Error)
|
||||
|
||||
// 创建 AccountStore
|
||||
accountStore := postgres.NewAccountStore(db, nil)
|
||||
|
||||
t.Run("正常查询应该过滤数据", func(t *testing.T) {
|
||||
ctxWithA := middleware.SetUserContext(ctx, accountA.ID, constants.UserTypePlatform, 100)
|
||||
var results []TestData
|
||||
err := db.WithContext(ctxWithA).
|
||||
Scopes(postgres.DataPermissionScope(ctxWithA, accountStore)).
|
||||
Find(&results).Error
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, results, 1)
|
||||
})
|
||||
|
||||
t.Run("不带用户上下文时返回空数据", func(t *testing.T) {
|
||||
var results []TestData
|
||||
err := db.WithContext(ctx).
|
||||
Scopes(postgres.DataPermissionScope(ctx, accountStore)).
|
||||
Find(&results).Error
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, results, 0)
|
||||
})
|
||||
}
|
||||
|
||||
// TestDataPermission_CrossShopIsolation 测试跨店铺数据隔离
|
||||
func TestDataPermission_CrossShopIsolation(t *testing.T) {
|
||||
store, cleanup := setupTestDB(t)
|
||||
defer cleanup()
|
||||
|
||||
ctx := context.Background()
|
||||
db := store.DB()
|
||||
|
||||
// 创建两个不同店铺的账号
|
||||
shopID100 := uint(100)
|
||||
accountA := &model.Account{
|
||||
Username: "user_shop100",
|
||||
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_shop200",
|
||||
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_1", OwnerID: accountA.ID, ShopID: 100},
|
||||
{Name: "data_shop100_2", OwnerID: accountA.ID, ShopID: 100},
|
||||
{Name: "data_shop200_1", OwnerID: accountB.ID, ShopID: 200},
|
||||
{Name: "data_shop200_2", OwnerID: accountB.ID, ShopID: 200},
|
||||
}
|
||||
require.NoError(t, db.Create(&testData).Error)
|
||||
|
||||
// 创建 AccountStore
|
||||
accountStore := postgres.NewAccountStore(db, nil)
|
||||
|
||||
t.Run("店铺 100 用户只能看到店铺 100 的数据", func(t *testing.T) {
|
||||
ctxWithA := middleware.SetUserContext(ctx, accountA.ID, constants.UserTypePlatform, 100)
|
||||
var results []TestData
|
||||
err := db.WithContext(ctxWithA).
|
||||
Scopes(postgres.DataPermissionScope(ctxWithA, accountStore)).
|
||||
Find(&results).Error
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, results, 2)
|
||||
for _, r := range results {
|
||||
assert.Equal(t, uint(100), r.ShopID)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("店铺 200 用户只能看到店铺 200 的数据", func(t *testing.T) {
|
||||
ctxWithB := middleware.SetUserContext(ctx, accountB.ID, constants.UserTypePlatform, 200)
|
||||
var results []TestData
|
||||
err := db.WithContext(ctxWithB).
|
||||
Scopes(postgres.DataPermissionScope(ctxWithB, accountStore)).
|
||||
Find(&results).Error
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, results, 2)
|
||||
for _, r := range results {
|
||||
assert.Equal(t, uint(200), r.ShopID)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("店铺 100 用户看不到店铺 200 的数据", func(t *testing.T) {
|
||||
ctxWithA := middleware.SetUserContext(ctx, accountA.ID, constants.UserTypePlatform, 100)
|
||||
var results []TestData
|
||||
err := db.WithContext(ctxWithA).
|
||||
Scopes(postgres.DataPermissionScope(ctxWithA, accountStore)).
|
||||
Where("shop_id = ?", 200). // 尝试查询店铺 200 的数据
|
||||
Find(&results).Error
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, results, 0, "不应该看到其他店铺的数据")
|
||||
})
|
||||
}
|
||||
|
||||
// TestDataPermission_RootUserBypass 测试 root 用户跳过数据权限过滤
|
||||
func TestDataPermission_RootUserBypass(t *testing.T) {
|
||||
store, cleanup := setupTestDB(t)
|
||||
defer cleanup()
|
||||
|
||||
ctx := context.Background()
|
||||
db := store.DB()
|
||||
|
||||
// 创建 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{}))
|
||||
|
||||
// 插入不同店铺、不同用户的数据
|
||||
testData := []TestData{
|
||||
{Name: "data_1", OwnerID: 1, ShopID: 100},
|
||||
{Name: "data_2", OwnerID: 2, ShopID: 200},
|
||||
{Name: "data_3", OwnerID: 3, ShopID: 300},
|
||||
{Name: "data_4", OwnerID: 4, ShopID: 400},
|
||||
}
|
||||
require.NoError(t, db.Create(&testData).Error)
|
||||
|
||||
// 创建 AccountStore
|
||||
accountStore := postgres.NewAccountStore(db, nil)
|
||||
|
||||
t.Run("root 用户可以看到所有数据", func(t *testing.T) {
|
||||
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, 4, "root 用户应该看到所有数据")
|
||||
})
|
||||
}
|
||||
@@ -82,11 +82,11 @@ func setupTestDB(t *testing.T) (*postgres.Store, func()) {
|
||||
if err := m.Down(); err != nil && err != migrate.ErrNoChange {
|
||||
t.Logf("清理迁移失败: %v", err)
|
||||
}
|
||||
m.Close()
|
||||
_, _ = m.Close()
|
||||
|
||||
sqlDB, _ := db.DB()
|
||||
if sqlDB != nil {
|
||||
sqlDB.Close()
|
||||
_ = sqlDB.Close()
|
||||
}
|
||||
if err := postgresContainer.Terminate(ctx); err != nil {
|
||||
t.Logf("终止容器失败: %v", err)
|
||||
|
||||
@@ -85,7 +85,7 @@ func TestErrorHandler_ValidationError_Returns400(t *testing.T) {
|
||||
|
||||
resp, err := app.Test(req, -1)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
// 验证 HTTP 状态码
|
||||
assert.Equal(t, 400, resp.StatusCode, "参数验证失败应返回 400 状态码")
|
||||
@@ -129,7 +129,7 @@ func TestErrorHandler_ResourceNotFound_Returns404(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/api/test/users/99999", nil)
|
||||
resp, err := app.Test(req, -1)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
// 验证 HTTP 状态码
|
||||
assert.Equal(t, 404, resp.StatusCode, "资源未找到应返回 404 状态码")
|
||||
@@ -172,7 +172,7 @@ func TestErrorHandler_AuthenticationFailed_Returns401(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/api/test/protected", nil)
|
||||
resp, err := app.Test(req, -1)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
// 验证 HTTP 状态码
|
||||
assert.Equal(t, 401, resp.StatusCode, "认证失败应返回 401 状态码")
|
||||
@@ -293,7 +293,7 @@ func TestErrorHandler_ResponseFormatConsistency(t *testing.T) {
|
||||
|
||||
resp, err := app.Test(req, -1)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
// 验证 HTTP 状态码
|
||||
assert.Equal(t, tc.expectedHTTP, resp.StatusCode,
|
||||
@@ -354,7 +354,7 @@ func TestPanic_BasicPanicRecovery(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/api/test/panic", nil)
|
||||
resp, err := app.Test(req, -1)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
// 验证 panic 被捕获并转换为 500 错误
|
||||
assert.Equal(t, 500, resp.StatusCode, "panic 应返回 500 状态码")
|
||||
@@ -401,14 +401,14 @@ func TestPanic_ServiceContinuesAfterRecovery(t *testing.T) {
|
||||
panicReq := httptest.NewRequest("GET", "/api/test/panic-endpoint", nil)
|
||||
panicResp, err := app.Test(panicReq, -1)
|
||||
require.NoError(t, err)
|
||||
panicResp.Body.Close()
|
||||
_ = panicResp.Body.Close()
|
||||
assert.Equal(t, 500, panicResp.StatusCode, "panic 应返回 500")
|
||||
|
||||
// 第二次请求:验证服务仍然正常运行
|
||||
normalReq := httptest.NewRequest("GET", "/api/test/normal-endpoint", nil)
|
||||
normalResp, err := app.Test(normalReq, -1)
|
||||
require.NoError(t, err)
|
||||
defer normalResp.Body.Close()
|
||||
defer func() { _ = normalResp.Body.Close() }()
|
||||
|
||||
// 验证正常请求仍然成功
|
||||
assert.Equal(t, 200, normalResp.StatusCode, "panic 后正常请求应成功")
|
||||
@@ -452,7 +452,7 @@ func TestPanic_ConcurrentPanicHandling(t *testing.T) {
|
||||
results <- 0
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
results <- resp.StatusCode
|
||||
}(i)
|
||||
}
|
||||
@@ -490,7 +490,7 @@ func TestPanic_StackTraceLogging(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/api/test/panic-with-stack", nil)
|
||||
resp, err := app.Test(req, -1)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
// 验证 panic 被捕获
|
||||
assert.Equal(t, 500, resp.StatusCode, "panic 应返回 500 状态码")
|
||||
@@ -536,7 +536,7 @@ func TestPanic_NilPointerDereference(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/api/test/nil-pointer", nil)
|
||||
resp, err := app.Test(req, -1)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
assert.Equal(t, 500, resp.StatusCode, "空指针 panic 应返回 500")
|
||||
|
||||
@@ -556,7 +556,7 @@ func TestPanic_ArrayOutOfBounds(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/api/test/out-of-bounds", nil)
|
||||
resp, err := app.Test(req, -1)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
assert.Equal(t, 500, resp.StatusCode, "数组越界 panic 应返回 500")
|
||||
|
||||
@@ -580,7 +580,7 @@ func TestErrorClassification_ValidationError_WarnLevel(t *testing.T) {
|
||||
|
||||
resp, err := app.Test(req, -1)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
// 验证 HTTP 状态码
|
||||
assert.Equal(t, 400, resp.StatusCode, "参数验证失败应返回 400")
|
||||
@@ -614,7 +614,7 @@ func TestErrorClassification_PermissionDenied_WarnLevel(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/api/test/permission-warn", nil)
|
||||
resp, err := app.Test(req, -1)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
// 验证 HTTP 状态码
|
||||
assert.Equal(t, 403, resp.StatusCode, "权限不足应返回 403")
|
||||
@@ -650,7 +650,7 @@ func TestErrorClassification_DatabaseError_ErrorLevel(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/api/test/database-error", nil)
|
||||
resp, err := app.Test(req, -1)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
// 验证 HTTP 状态码
|
||||
assert.Equal(t, 500, resp.StatusCode, "数据库错误应返回 500")
|
||||
@@ -735,7 +735,7 @@ func TestErrorClassification_SensitiveInfoHidden(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", tc.path, nil)
|
||||
resp, err := app.Test(req, -1)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
assert.Equal(t, tc.expectedStatus, resp.StatusCode, "HTTP 状态码应正确")
|
||||
|
||||
@@ -777,7 +777,7 @@ func TestErrorClassification_RateLimitExceeded_Returns429(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/api/test/rate-limit", nil)
|
||||
resp, err := app.Test(req, -1)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
// 验证 HTTP 状态码
|
||||
assert.Equal(t, 429, resp.StatusCode, "限流应返回 429 状态码")
|
||||
@@ -834,7 +834,7 @@ func TestErrorClassification_ServiceUnavailable_Returns503(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/api/test/service-unavailable", nil)
|
||||
resp, err := app.Test(req, -1)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
// 验证 HTTP 状态码
|
||||
assert.Equal(t, 503, resp.StatusCode, "服务不可用应返回 503 状态码")
|
||||
@@ -878,7 +878,7 @@ func TestErrorTracking_LogCompleteness_IncludesRequestID(t *testing.T) {
|
||||
|
||||
resp, err := app.Test(req, -1)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
// 验证响应包含 Request ID
|
||||
responseRequestID := resp.Header.Get("X-Request-ID")
|
||||
@@ -922,7 +922,7 @@ func TestErrorTracking_RequestContext_AllFields(t *testing.T) {
|
||||
|
||||
resp, err := app.Test(req, -1)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
// 验证响应
|
||||
assert.Equal(t, 400, resp.StatusCode, "应返回 400 错误")
|
||||
@@ -953,7 +953,7 @@ func TestErrorTracking_PanicStackTrace_IncludesLocation(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/api/test/panic-stack-trace", nil)
|
||||
resp, err := app.Test(req, -1)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
// 验证 panic 被捕获
|
||||
assert.Equal(t, 500, resp.StatusCode, "panic 应返回 500 状态码")
|
||||
@@ -1052,7 +1052,7 @@ func TestErrorTracking_RequestIDTracing_EndToEnd(t *testing.T) {
|
||||
|
||||
resp, err := app.Test(req, -1)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
// 验证 HTTP 状态码
|
||||
assert.Equal(t, tc.expectedStatus, resp.StatusCode,
|
||||
|
||||
@@ -29,7 +29,7 @@ func TestHealthCheckNormal(t *testing.T) {
|
||||
Addr: "localhost:6379",
|
||||
DB: 0,
|
||||
})
|
||||
defer rdb.Close()
|
||||
defer func() { _ = rdb.Close() }()
|
||||
|
||||
// 创建 Fiber 应用
|
||||
app := fiber.New()
|
||||
@@ -70,7 +70,7 @@ func TestHealthCheckDatabaseDown(t *testing.T) {
|
||||
Addr: "localhost:6379",
|
||||
DB: 0,
|
||||
})
|
||||
defer rdb.Close()
|
||||
defer func() { _ = rdb.Close() }()
|
||||
|
||||
// 创建 Fiber 应用
|
||||
app := fiber.New()
|
||||
@@ -103,7 +103,7 @@ func TestHealthCheckRedisDown(t *testing.T) {
|
||||
Addr: "localhost:9999", // 无效端口
|
||||
DB: 0,
|
||||
})
|
||||
defer rdb.Close()
|
||||
defer func() { _ = rdb.Close() }()
|
||||
|
||||
// 创建 Fiber 应用
|
||||
app := fiber.New()
|
||||
@@ -136,7 +136,7 @@ func TestHealthCheckDetailed(t *testing.T) {
|
||||
Addr: "localhost:6379",
|
||||
DB: 0,
|
||||
})
|
||||
defer rdb.Close()
|
||||
defer func() { _ = rdb.Close() }()
|
||||
|
||||
// 测试 Redis 连接
|
||||
ctx := context.Background()
|
||||
|
||||
@@ -106,7 +106,7 @@ func TestLoggerMiddleware(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to initialize loggers: %v", err)
|
||||
}
|
||||
defer logger.Sync()
|
||||
defer func() { _ = logger.Sync() }()
|
||||
|
||||
// 创建应用
|
||||
app := fiber.New()
|
||||
@@ -171,7 +171,7 @@ func TestLoggerMiddleware(t *testing.T) {
|
||||
}
|
||||
|
||||
// 刷新日志缓冲区
|
||||
logger.Sync()
|
||||
_ = logger.Sync()
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
// 验证访问日志文件存在且有内容
|
||||
@@ -236,7 +236,7 @@ func TestRequestIDPropagation(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to initialize loggers: %v", err)
|
||||
}
|
||||
defer logger.Sync()
|
||||
defer func() { _ = logger.Sync() }()
|
||||
|
||||
// 创建应用
|
||||
app := fiber.New()
|
||||
@@ -416,7 +416,7 @@ func TestLoggerMiddlewareWithUserID(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to initialize loggers: %v", err)
|
||||
}
|
||||
defer logger.Sync()
|
||||
defer func() { _ = logger.Sync() }()
|
||||
|
||||
// 创建应用
|
||||
app := fiber.New()
|
||||
@@ -449,7 +449,7 @@ func TestLoggerMiddlewareWithUserID(t *testing.T) {
|
||||
resp.Body.Close()
|
||||
|
||||
// 刷新日志缓冲区
|
||||
logger.Sync()
|
||||
_ = logger.Sync()
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
// 验证访问日志包含 user_id
|
||||
|
||||
234
tests/integration/migration_test.go
Normal file
234
tests/integration/migration_test.go
Normal file
@@ -0,0 +1,234 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/golang-migrate/migrate/v4"
|
||||
_ "github.com/golang-migrate/migrate/v4/database/postgres"
|
||||
_ "github.com/golang-migrate/migrate/v4/source/file"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/testcontainers/testcontainers-go"
|
||||
testcontainers_postgres "github.com/testcontainers/testcontainers-go/modules/postgres"
|
||||
"github.com/testcontainers/testcontainers-go/wait"
|
||||
postgresDriver "gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
// TestMigration_UpAndDown 测试迁移脚本的向上和向下迁移
|
||||
func TestMigration_UpAndDown(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
// 启动 PostgreSQL 容器
|
||||
postgresContainer, err := testcontainers_postgres.RunContainer(ctx,
|
||||
testcontainers.WithImage("postgres:14-alpine"),
|
||||
testcontainers_postgres.WithDatabase("testdb"),
|
||||
testcontainers_postgres.WithUsername("postgres"),
|
||||
testcontainers_postgres.WithPassword("password"),
|
||||
testcontainers.WithWaitStrategy(
|
||||
wait.ForLog("database system is ready to accept connections").
|
||||
WithOccurrence(2).
|
||||
WithStartupTimeout(30*time.Second),
|
||||
),
|
||||
)
|
||||
require.NoError(t, err, "启动 PostgreSQL 容器失败")
|
||||
defer func() {
|
||||
if err := postgresContainer.Terminate(ctx); err != nil {
|
||||
t.Logf("终止容器失败: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
// 获取连接字符串
|
||||
connStr, err := postgresContainer.ConnectionString(ctx, "sslmode=disable")
|
||||
require.NoError(t, err, "获取数据库连接字符串失败")
|
||||
|
||||
// 应用数据库迁移
|
||||
migrationsPath := getMigrationsPath(t)
|
||||
m, err := migrate.New(
|
||||
fmt.Sprintf("file://%s", migrationsPath),
|
||||
connStr,
|
||||
)
|
||||
require.NoError(t, err, "创建迁移实例失败")
|
||||
defer func() { _, _ = m.Close() }()
|
||||
|
||||
t.Run("向上迁移", func(t *testing.T) {
|
||||
err := m.Up()
|
||||
require.NoError(t, err, "执行向上迁移失败")
|
||||
|
||||
// 验证表已创建
|
||||
db, err := gorm.Open(postgresDriver.Open(connStr), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
require.NoError(t, err, "连接数据库失败")
|
||||
|
||||
// 检查 RBAC 表存在
|
||||
tables := []string{
|
||||
"tb_account",
|
||||
"tb_role",
|
||||
"tb_permission",
|
||||
"tb_account_role",
|
||||
"tb_role_permission",
|
||||
}
|
||||
|
||||
for _, table := range tables {
|
||||
var exists bool
|
||||
err := db.Raw("SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = ?)", table).Scan(&exists).Error
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, exists, "表 %s 应该存在", table)
|
||||
}
|
||||
|
||||
// 检查索引
|
||||
var indexCount int64
|
||||
err = db.Raw(`
|
||||
SELECT COUNT(*) FROM pg_indexes
|
||||
WHERE tablename = 'tb_account'
|
||||
AND indexname LIKE 'idx_account_%'
|
||||
`).Scan(&indexCount).Error
|
||||
assert.NoError(t, err)
|
||||
assert.Greater(t, indexCount, int64(0), "tb_account 表应该有索引")
|
||||
|
||||
sqlDB, _ := db.DB()
|
||||
if sqlDB != nil {
|
||||
_ = sqlDB.Close()
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("向下迁移", func(t *testing.T) {
|
||||
err := m.Down()
|
||||
require.NoError(t, err, "执行向下迁移失败")
|
||||
|
||||
// 验证表已删除
|
||||
db, err := gorm.Open(postgresDriver.Open(connStr), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
require.NoError(t, err, "连接数据库失败")
|
||||
|
||||
// 检查 RBAC 表已删除
|
||||
tables := []string{
|
||||
"tb_account",
|
||||
"tb_role",
|
||||
"tb_permission",
|
||||
"tb_account_role",
|
||||
"tb_role_permission",
|
||||
}
|
||||
|
||||
for _, table := range tables {
|
||||
var exists bool
|
||||
err := db.Raw("SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = ?)", table).Scan(&exists).Error
|
||||
assert.NoError(t, err)
|
||||
assert.False(t, exists, "表 %s 应该已删除", table)
|
||||
}
|
||||
|
||||
sqlDB, _ := db.DB()
|
||||
if sqlDB != nil {
|
||||
_ = sqlDB.Close()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestMigration_NoForeignKeys 验证迁移脚本不包含外键约束
|
||||
func TestMigration_NoForeignKeys(t *testing.T) {
|
||||
// 获取迁移目录
|
||||
migrationsPath := getMigrationsPath(t)
|
||||
|
||||
// 读取所有迁移文件
|
||||
files, err := filepath.Glob(filepath.Join(migrationsPath, "*.up.sql"))
|
||||
require.NoError(t, err)
|
||||
|
||||
forbiddenKeywords := []string{
|
||||
"FOREIGN KEY",
|
||||
"REFERENCES",
|
||||
"ON DELETE CASCADE",
|
||||
"ON UPDATE CASCADE",
|
||||
}
|
||||
|
||||
for _, file := range files {
|
||||
content, err := os.ReadFile(file)
|
||||
require.NoError(t, err)
|
||||
|
||||
for _, keyword := range forbiddenKeywords {
|
||||
assert.NotContains(t, string(content), keyword,
|
||||
"迁移文件 %s 不应包含外键约束关键字: %s", filepath.Base(file), keyword)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestMigration_SoftDeleteSupport 验证表支持软删除
|
||||
func TestMigration_SoftDeleteSupport(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
// 启动 PostgreSQL 容器
|
||||
postgresContainer, err := testcontainers_postgres.RunContainer(ctx,
|
||||
testcontainers.WithImage("postgres:14-alpine"),
|
||||
testcontainers_postgres.WithDatabase("testdb"),
|
||||
testcontainers_postgres.WithUsername("postgres"),
|
||||
testcontainers_postgres.WithPassword("password"),
|
||||
testcontainers.WithWaitStrategy(
|
||||
wait.ForLog("database system is ready to accept connections").
|
||||
WithOccurrence(2).
|
||||
WithStartupTimeout(30*time.Second),
|
||||
),
|
||||
)
|
||||
require.NoError(t, err, "启动 PostgreSQL 容器失败")
|
||||
defer func() {
|
||||
if err := postgresContainer.Terminate(ctx); err != nil {
|
||||
t.Logf("终止容器失败: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
// 获取连接字符串
|
||||
connStr, err := postgresContainer.ConnectionString(ctx, "sslmode=disable")
|
||||
require.NoError(t, err, "获取数据库连接字符串失败")
|
||||
|
||||
// 应用迁移
|
||||
migrationsPath := getMigrationsPath(t)
|
||||
m, err := migrate.New(
|
||||
fmt.Sprintf("file://%s", migrationsPath),
|
||||
connStr,
|
||||
)
|
||||
require.NoError(t, err, "创建迁移实例失败")
|
||||
defer func() { _, _ = m.Close() }()
|
||||
|
||||
err = m.Up()
|
||||
require.NoError(t, err, "执行向上迁移失败")
|
||||
|
||||
// 连接数据库验证
|
||||
db, err := gorm.Open(postgresDriver.Open(connStr), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
require.NoError(t, err, "连接数据库失败")
|
||||
defer func() {
|
||||
sqlDB, _ := db.DB()
|
||||
if sqlDB != nil {
|
||||
_ = sqlDB.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
// 检查每个表都有 deleted_at 列和索引
|
||||
tables := []string{
|
||||
"tb_account",
|
||||
"tb_role",
|
||||
"tb_permission",
|
||||
"tb_account_role",
|
||||
"tb_role_permission",
|
||||
}
|
||||
|
||||
for _, table := range tables {
|
||||
// 检查 deleted_at 列存在
|
||||
var columnExists bool
|
||||
err := db.Raw(`
|
||||
SELECT EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = ? AND column_name = 'deleted_at'
|
||||
)
|
||||
`, table).Scan(&columnExists).Error
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, columnExists, "表 %s 应该有 deleted_at 列", table)
|
||||
}
|
||||
}
|
||||
455
tests/integration/permission_test.go
Normal file
455
tests/integration/permission_test.go
Normal file
@@ -0,0 +1,455 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/testcontainers/testcontainers-go"
|
||||
testcontainers_postgres "github.com/testcontainers/testcontainers-go/modules/postgres"
|
||||
"github.com/testcontainers/testcontainers-go/wait"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/handler"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/routes"
|
||||
permissionService "github.com/break/junhong_cmp_fiber/internal/service/permission"
|
||||
postgresStore "github.com/break/junhong_cmp_fiber/internal/store/postgres"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/middleware"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/response"
|
||||
)
|
||||
|
||||
// permTestEnv 权限测试环境
|
||||
type permTestEnv struct {
|
||||
db *gorm.DB
|
||||
app *fiber.App
|
||||
permissionService *permissionService.Service
|
||||
cleanup func()
|
||||
}
|
||||
|
||||
// setupPermTestEnv 设置权限测试环境
|
||||
func setupPermTestEnv(t *testing.T) *permTestEnv {
|
||||
t.Helper()
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// 启动 PostgreSQL 容器
|
||||
pgContainer, err := testcontainers_postgres.RunContainer(ctx,
|
||||
testcontainers.WithImage("postgres:14-alpine"),
|
||||
testcontainers_postgres.WithDatabase("testdb"),
|
||||
testcontainers_postgres.WithUsername("postgres"),
|
||||
testcontainers_postgres.WithPassword("password"),
|
||||
testcontainers.WithWaitStrategy(
|
||||
wait.ForLog("database system is ready to accept connections").
|
||||
WithOccurrence(2).
|
||||
WithStartupTimeout(30*time.Second),
|
||||
),
|
||||
)
|
||||
require.NoError(t, err, "启动 PostgreSQL 容器失败")
|
||||
|
||||
pgConnStr, err := pgContainer.ConnectionString(ctx, "sslmode=disable")
|
||||
require.NoError(t, err)
|
||||
|
||||
// 连接数据库
|
||||
db, err := gorm.Open(postgres.Open(pgConnStr), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// 自动迁移
|
||||
err = db.AutoMigrate(
|
||||
&model.Permission{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 初始化 Store
|
||||
permStore := postgresStore.NewPermissionStore(db)
|
||||
|
||||
// 初始化 Service
|
||||
permSvc := permissionService.New(permStore)
|
||||
|
||||
// 初始化 Handler
|
||||
permHandler := handler.NewPermissionHandler(permSvc)
|
||||
|
||||
// 创建 Fiber App
|
||||
app := fiber.New(fiber.Config{
|
||||
ErrorHandler: func(c *fiber.Ctx, err error) error {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
},
|
||||
})
|
||||
|
||||
// 注册路由
|
||||
services := &routes.Services{
|
||||
PermissionHandler: permHandler,
|
||||
}
|
||||
routes.RegisterRoutes(app, services)
|
||||
|
||||
return &permTestEnv{
|
||||
db: db,
|
||||
app: app,
|
||||
permissionService: permSvc,
|
||||
cleanup: func() {
|
||||
if err := pgContainer.Terminate(ctx); err != nil {
|
||||
t.Logf("终止 PostgreSQL 容器失败: %v", err)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// TestPermissionAPI_Create 测试创建权限 API
|
||||
func TestPermissionAPI_Create(t *testing.T) {
|
||||
env := setupPermTestEnv(t)
|
||||
defer env.cleanup()
|
||||
|
||||
// 添加测试中间件
|
||||
testUserID := uint(1)
|
||||
env.app.Use(func(c *fiber.Ctx) error {
|
||||
ctx := middleware.SetUserContext(c.UserContext(), testUserID, constants.UserTypeRoot, 0)
|
||||
c.SetUserContext(ctx)
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
t.Run("成功创建权限", func(t *testing.T) {
|
||||
reqBody := model.CreatePermissionRequest{
|
||||
PermName: "用户管理",
|
||||
PermCode: "user:manage",
|
||||
PermType: constants.PermissionTypeMenu,
|
||||
URL: "/admin/users",
|
||||
}
|
||||
|
||||
jsonBody, _ := json.Marshal(reqBody)
|
||||
req := httptest.NewRequest("POST", "/api/v1/permissions", bytes.NewReader(jsonBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
|
||||
var result response.Response
|
||||
err = json.NewDecoder(resp.Body).Decode(&result)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 0, result.Code)
|
||||
|
||||
// 验证数据库中权限已创建
|
||||
var count int64
|
||||
env.db.Model(&model.Permission{}).Where("perm_code = ?", "user:manage").Count(&count)
|
||||
assert.Equal(t, int64(1), count)
|
||||
})
|
||||
|
||||
t.Run("权限编码重复时返回错误", func(t *testing.T) {
|
||||
// 先创建一个权限
|
||||
existingPerm := &model.Permission{
|
||||
PermName: "已存在权限",
|
||||
PermCode: "existing:perm",
|
||||
PermType: constants.PermissionTypeMenu,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(existingPerm)
|
||||
|
||||
// 尝试创建相同编码的权限
|
||||
reqBody := model.CreatePermissionRequest{
|
||||
PermName: "新权限",
|
||||
PermCode: "existing:perm",
|
||||
PermType: constants.PermissionTypeMenu,
|
||||
}
|
||||
|
||||
jsonBody, _ := json.Marshal(reqBody)
|
||||
req := httptest.NewRequest("POST", "/api/v1/permissions", bytes.NewReader(jsonBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
|
||||
var result response.Response
|
||||
err = json.NewDecoder(resp.Body).Decode(&result)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, errors.CodePermCodeExists, result.Code)
|
||||
})
|
||||
|
||||
t.Run("创建子权限", func(t *testing.T) {
|
||||
// 先创建父权限
|
||||
parentPerm := &model.Permission{
|
||||
PermName: "系统管理",
|
||||
PermCode: "system:manage",
|
||||
PermType: constants.PermissionTypeMenu,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(parentPerm)
|
||||
|
||||
// 创建子权限
|
||||
reqBody := model.CreatePermissionRequest{
|
||||
PermName: "用户列表",
|
||||
PermCode: "system:user:list",
|
||||
PermType: constants.PermissionTypeButton,
|
||||
ParentID: &parentPerm.ID,
|
||||
}
|
||||
|
||||
jsonBody, _ := json.Marshal(reqBody)
|
||||
req := httptest.NewRequest("POST", "/api/v1/permissions", bytes.NewReader(jsonBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
|
||||
// 验证父权限ID已设置
|
||||
var child model.Permission
|
||||
env.db.Where("perm_code = ?", "system:user:list").First(&child)
|
||||
assert.NotNil(t, child.ParentID)
|
||||
assert.Equal(t, parentPerm.ID, *child.ParentID)
|
||||
})
|
||||
}
|
||||
|
||||
// TestPermissionAPI_Get 测试获取权限详情 API
|
||||
func TestPermissionAPI_Get(t *testing.T) {
|
||||
env := setupPermTestEnv(t)
|
||||
defer env.cleanup()
|
||||
|
||||
// 添加测试中间件
|
||||
testUserID := uint(1)
|
||||
env.app.Use(func(c *fiber.Ctx) error {
|
||||
ctx := middleware.SetUserContext(c.UserContext(), testUserID, constants.UserTypeRoot, 0)
|
||||
c.SetUserContext(ctx)
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// 创建测试权限
|
||||
testPerm := &model.Permission{
|
||||
PermName: "获取测试权限",
|
||||
PermCode: "get:test:perm",
|
||||
PermType: constants.PermissionTypeMenu,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(testPerm)
|
||||
|
||||
t.Run("成功获取权限详情", func(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", fmt.Sprintf("/api/v1/permissions/%d", testPerm.ID), nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
|
||||
var result response.Response
|
||||
err = json.NewDecoder(resp.Body).Decode(&result)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 0, result.Code)
|
||||
})
|
||||
|
||||
t.Run("权限不存在时返回错误", func(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/api/v1/permissions/99999", nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
|
||||
var result response.Response
|
||||
err = json.NewDecoder(resp.Body).Decode(&result)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, errors.CodePermissionNotFound, result.Code)
|
||||
})
|
||||
}
|
||||
|
||||
// TestPermissionAPI_Update 测试更新权限 API
|
||||
func TestPermissionAPI_Update(t *testing.T) {
|
||||
env := setupPermTestEnv(t)
|
||||
defer env.cleanup()
|
||||
|
||||
// 添加测试中间件
|
||||
testUserID := uint(1)
|
||||
env.app.Use(func(c *fiber.Ctx) error {
|
||||
ctx := middleware.SetUserContext(c.UserContext(), testUserID, constants.UserTypeRoot, 0)
|
||||
c.SetUserContext(ctx)
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// 创建测试权限
|
||||
testPerm := &model.Permission{
|
||||
PermName: "更新测试权限",
|
||||
PermCode: "update:test:perm",
|
||||
PermType: constants.PermissionTypeMenu,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(testPerm)
|
||||
|
||||
t.Run("成功更新权限", func(t *testing.T) {
|
||||
newName := "更新后权限"
|
||||
reqBody := model.UpdatePermissionRequest{
|
||||
PermName: &newName,
|
||||
}
|
||||
|
||||
jsonBody, _ := json.Marshal(reqBody)
|
||||
req := httptest.NewRequest("PUT", fmt.Sprintf("/api/v1/permissions/%d", testPerm.ID), bytes.NewReader(jsonBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
|
||||
// 验证数据库已更新
|
||||
var updated model.Permission
|
||||
env.db.First(&updated, testPerm.ID)
|
||||
assert.Equal(t, newName, updated.PermName)
|
||||
})
|
||||
}
|
||||
|
||||
// TestPermissionAPI_Delete 测试删除权限 API
|
||||
func TestPermissionAPI_Delete(t *testing.T) {
|
||||
env := setupPermTestEnv(t)
|
||||
defer env.cleanup()
|
||||
|
||||
// 添加测试中间件
|
||||
testUserID := uint(1)
|
||||
env.app.Use(func(c *fiber.Ctx) error {
|
||||
ctx := middleware.SetUserContext(c.UserContext(), testUserID, constants.UserTypeRoot, 0)
|
||||
c.SetUserContext(ctx)
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
t.Run("成功软删除权限", func(t *testing.T) {
|
||||
// 创建测试权限
|
||||
testPerm := &model.Permission{
|
||||
PermName: "删除测试权限",
|
||||
PermCode: "delete:test:perm",
|
||||
PermType: constants.PermissionTypeMenu,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(testPerm)
|
||||
|
||||
req := httptest.NewRequest("DELETE", fmt.Sprintf("/api/v1/permissions/%d", testPerm.ID), nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
|
||||
// 验证权限已软删除
|
||||
var deleted model.Permission
|
||||
err = env.db.Unscoped().First(&deleted, testPerm.ID).Error
|
||||
require.NoError(t, err)
|
||||
assert.NotNil(t, deleted.DeletedAt)
|
||||
})
|
||||
}
|
||||
|
||||
// TestPermissionAPI_List 测试权限列表 API
|
||||
func TestPermissionAPI_List(t *testing.T) {
|
||||
env := setupPermTestEnv(t)
|
||||
defer env.cleanup()
|
||||
|
||||
// 添加测试中间件
|
||||
testUserID := uint(1)
|
||||
env.app.Use(func(c *fiber.Ctx) error {
|
||||
ctx := middleware.SetUserContext(c.UserContext(), testUserID, constants.UserTypeRoot, 0)
|
||||
c.SetUserContext(ctx)
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// 创建多个测试权限
|
||||
for i := 1; i <= 5; i++ {
|
||||
perm := &model.Permission{
|
||||
PermName: fmt.Sprintf("列表测试权限_%d", i),
|
||||
PermCode: fmt.Sprintf("list:test:perm:%d", i),
|
||||
PermType: constants.PermissionTypeMenu,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(perm)
|
||||
}
|
||||
|
||||
t.Run("成功获取权限列表", func(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/api/v1/permissions?page=1&page_size=10", nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
|
||||
var result response.Response
|
||||
err = json.NewDecoder(resp.Body).Decode(&result)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 0, result.Code)
|
||||
})
|
||||
|
||||
t.Run("按类型过滤权限", func(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", fmt.Sprintf("/api/v1/permissions?perm_type=%d", constants.PermissionTypeMenu), nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
})
|
||||
}
|
||||
|
||||
// TestPermissionAPI_GetTree 测试获取权限树 API
|
||||
func TestPermissionAPI_GetTree(t *testing.T) {
|
||||
env := setupPermTestEnv(t)
|
||||
defer env.cleanup()
|
||||
|
||||
// 添加测试中间件
|
||||
testUserID := uint(1)
|
||||
env.app.Use(func(c *fiber.Ctx) error {
|
||||
ctx := middleware.SetUserContext(c.UserContext(), testUserID, constants.UserTypeRoot, 0)
|
||||
c.SetUserContext(ctx)
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// 创建层级权限结构
|
||||
// 根权限
|
||||
rootPerm := &model.Permission{
|
||||
PermName: "系统管理",
|
||||
PermCode: "system",
|
||||
PermType: constants.PermissionTypeMenu,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(rootPerm)
|
||||
|
||||
// 子权限
|
||||
childPerm := &model.Permission{
|
||||
PermName: "用户管理",
|
||||
PermCode: "system:user",
|
||||
PermType: constants.PermissionTypeMenu,
|
||||
ParentID: &rootPerm.ID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(childPerm)
|
||||
|
||||
// 孙子权限
|
||||
grandchildPerm := &model.Permission{
|
||||
PermName: "用户列表",
|
||||
PermCode: "system:user:list",
|
||||
PermType: constants.PermissionTypeButton,
|
||||
ParentID: &childPerm.ID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(grandchildPerm)
|
||||
|
||||
t.Run("成功获取权限树", func(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/api/v1/permissions/tree", nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
|
||||
var result response.Response
|
||||
err = json.NewDecoder(resp.Body).Decode(&result)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 0, result.Code)
|
||||
})
|
||||
}
|
||||
@@ -44,7 +44,7 @@ func TestPanicRecovery(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to initialize loggers: %v", err)
|
||||
}
|
||||
defer logger.Sync()
|
||||
defer func() { _ = logger.Sync() }()
|
||||
|
||||
appLogger := logger.GetAppLogger()
|
||||
|
||||
@@ -157,7 +157,7 @@ func TestPanicLogging(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to initialize loggers: %v", err)
|
||||
}
|
||||
defer logger.Sync()
|
||||
defer func() { _ = logger.Sync() }()
|
||||
|
||||
appLogger := logger.GetAppLogger()
|
||||
|
||||
@@ -294,7 +294,7 @@ func TestSubsequentRequestsAfterPanic(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to initialize loggers: %v", err)
|
||||
}
|
||||
defer logger.Sync()
|
||||
defer func() { _ = logger.Sync() }()
|
||||
|
||||
appLogger := logger.GetAppLogger()
|
||||
|
||||
@@ -392,7 +392,7 @@ func TestPanicWithRequestID(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to initialize loggers: %v", err)
|
||||
}
|
||||
defer logger.Sync()
|
||||
defer func() { _ = logger.Sync() }()
|
||||
|
||||
appLogger := logger.GetAppLogger()
|
||||
|
||||
@@ -485,7 +485,7 @@ func TestConcurrentPanics(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to initialize loggers: %v", err)
|
||||
}
|
||||
defer logger.Sync()
|
||||
defer func() { _ = logger.Sync() }()
|
||||
|
||||
appLogger := logger.GetAppLogger()
|
||||
|
||||
@@ -564,7 +564,7 @@ func TestRecoverMiddlewareOrder(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to initialize loggers: %v", err)
|
||||
}
|
||||
defer logger.Sync()
|
||||
defer func() { _ = logger.Sync() }()
|
||||
|
||||
appLogger := logger.GetAppLogger()
|
||||
|
||||
|
||||
458
tests/integration/role_permission_test.go
Normal file
458
tests/integration/role_permission_test.go
Normal file
@@ -0,0 +1,458 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/testcontainers/testcontainers-go"
|
||||
testcontainers_postgres "github.com/testcontainers/testcontainers-go/modules/postgres"
|
||||
"github.com/testcontainers/testcontainers-go/wait"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
roleService "github.com/break/junhong_cmp_fiber/internal/service/role"
|
||||
postgresStore "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"
|
||||
)
|
||||
|
||||
// TestRolePermissionAssociation_AssignPermissions 测试角色权限分配功能
|
||||
func TestRolePermissionAssociation_AssignPermissions(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
// 启动 PostgreSQL 容器
|
||||
pgContainer, err := testcontainers_postgres.RunContainer(ctx,
|
||||
testcontainers.WithImage("postgres:14-alpine"),
|
||||
testcontainers_postgres.WithDatabase("testdb"),
|
||||
testcontainers_postgres.WithUsername("postgres"),
|
||||
testcontainers_postgres.WithPassword("password"),
|
||||
testcontainers.WithWaitStrategy(
|
||||
wait.ForLog("database system is ready to accept connections").
|
||||
WithOccurrence(2).
|
||||
WithStartupTimeout(30*time.Second),
|
||||
),
|
||||
)
|
||||
require.NoError(t, err, "启动 PostgreSQL 容器失败")
|
||||
defer func() { _ = pgContainer.Terminate(ctx) }()
|
||||
|
||||
pgConnStr, err := pgContainer.ConnectionString(ctx, "sslmode=disable")
|
||||
require.NoError(t, err)
|
||||
|
||||
// 连接数据库
|
||||
db, err := gorm.Open(postgres.Open(pgConnStr), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// 自动迁移
|
||||
err = db.AutoMigrate(
|
||||
&model.Role{},
|
||||
&model.Permission{},
|
||||
&model.RolePermission{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 初始化 Store 和 Service
|
||||
roleStore := postgresStore.NewRoleStore(db)
|
||||
permStore := postgresStore.NewPermissionStore(db)
|
||||
rolePermStore := postgresStore.NewRolePermissionStore(db)
|
||||
roleSvc := roleService.New(roleStore, permStore, rolePermStore)
|
||||
|
||||
// 创建测试用户上下文
|
||||
userCtx := middleware.SetUserContext(ctx, 1, constants.UserTypeRoot, 0)
|
||||
|
||||
t.Run("成功分配单个权限", func(t *testing.T) {
|
||||
// 创建测试角色
|
||||
role := &model.Role{
|
||||
RoleName: "单权限测试角色",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(role)
|
||||
|
||||
// 创建测试权限
|
||||
perm := &model.Permission{
|
||||
PermName: "单权限测试",
|
||||
PermCode: "single:perm:test",
|
||||
PermType: constants.PermissionTypeMenu,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(perm)
|
||||
|
||||
// 分配权限
|
||||
rps, err := roleSvc.AssignPermissions(userCtx, role.ID, []uint{perm.ID})
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, rps, 1)
|
||||
assert.Equal(t, role.ID, rps[0].RoleID)
|
||||
assert.Equal(t, perm.ID, rps[0].PermID)
|
||||
})
|
||||
|
||||
t.Run("成功分配多个权限", func(t *testing.T) {
|
||||
// 创建测试角色
|
||||
role := &model.Role{
|
||||
RoleName: "多权限测试角色",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(role)
|
||||
|
||||
// 创建多个测试权限
|
||||
permIDs := make([]uint, 3)
|
||||
for i := 0; i < 3; i++ {
|
||||
perm := &model.Permission{
|
||||
PermName: "多权限测试_" + string(rune('A'+i)),
|
||||
PermCode: "multi:perm:test:" + string(rune('a'+i)),
|
||||
PermType: constants.PermissionTypeMenu,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(perm)
|
||||
permIDs[i] = perm.ID
|
||||
}
|
||||
|
||||
// 分配权限
|
||||
rps, err := roleSvc.AssignPermissions(userCtx, role.ID, permIDs)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, rps, 3)
|
||||
})
|
||||
|
||||
t.Run("获取角色的权限列表", func(t *testing.T) {
|
||||
// 创建测试角色
|
||||
role := &model.Role{
|
||||
RoleName: "获取权限列表测试角色",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(role)
|
||||
|
||||
// 创建并分配权限
|
||||
perm := &model.Permission{
|
||||
PermName: "获取权限列表测试",
|
||||
PermCode: "get:perm:list:test",
|
||||
PermType: constants.PermissionTypeMenu,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(perm)
|
||||
|
||||
_, err := roleSvc.AssignPermissions(userCtx, role.ID, []uint{perm.ID})
|
||||
require.NoError(t, err)
|
||||
|
||||
// 获取权限列表
|
||||
perms, err := roleSvc.GetPermissions(userCtx, role.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, perms, 1)
|
||||
assert.Equal(t, perm.ID, perms[0].ID)
|
||||
})
|
||||
|
||||
t.Run("移除角色的权限", func(t *testing.T) {
|
||||
// 创建测试角色
|
||||
role := &model.Role{
|
||||
RoleName: "移除权限测试角色",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(role)
|
||||
|
||||
// 创建并分配权限
|
||||
perm := &model.Permission{
|
||||
PermName: "移除权限测试",
|
||||
PermCode: "remove:perm:test",
|
||||
PermType: constants.PermissionTypeMenu,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(perm)
|
||||
|
||||
_, err := roleSvc.AssignPermissions(userCtx, role.ID, []uint{perm.ID})
|
||||
require.NoError(t, err)
|
||||
|
||||
// 移除权限
|
||||
err = roleSvc.RemovePermission(userCtx, role.ID, perm.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 验证权限已被软删除
|
||||
var rp model.RolePermission
|
||||
err = db.Unscoped().Where("role_id = ? AND perm_id = ?", role.ID, perm.ID).First(&rp).Error
|
||||
require.NoError(t, err)
|
||||
assert.NotNil(t, rp.DeletedAt)
|
||||
})
|
||||
|
||||
t.Run("重复分配权限不会创建重复记录", func(t *testing.T) {
|
||||
// 创建测试角色
|
||||
role := &model.Role{
|
||||
RoleName: "重复权限测试角色",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(role)
|
||||
|
||||
// 创建测试权限
|
||||
perm := &model.Permission{
|
||||
PermName: "重复权限测试",
|
||||
PermCode: "duplicate:perm:test",
|
||||
PermType: constants.PermissionTypeMenu,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(perm)
|
||||
|
||||
// 第一次分配
|
||||
_, err := roleSvc.AssignPermissions(userCtx, role.ID, []uint{perm.ID})
|
||||
require.NoError(t, err)
|
||||
|
||||
// 第二次分配相同权限
|
||||
_, err = roleSvc.AssignPermissions(userCtx, role.ID, []uint{perm.ID})
|
||||
require.NoError(t, err)
|
||||
|
||||
// 验证只有一条记录
|
||||
var count int64
|
||||
db.Model(&model.RolePermission{}).Where("role_id = ? AND perm_id = ?", role.ID, perm.ID).Count(&count)
|
||||
assert.Equal(t, int64(1), count)
|
||||
})
|
||||
|
||||
t.Run("角色不存在时分配权限失败", func(t *testing.T) {
|
||||
perm := &model.Permission{
|
||||
PermName: "角色不存在测试",
|
||||
PermCode: "role:not:exist:test",
|
||||
PermType: constants.PermissionTypeMenu,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(perm)
|
||||
|
||||
_, err := roleSvc.AssignPermissions(userCtx, 99999, []uint{perm.ID})
|
||||
assert.Error(t, err)
|
||||
})
|
||||
|
||||
t.Run("权限不存在时分配失败", func(t *testing.T) {
|
||||
role := &model.Role{
|
||||
RoleName: "权限不存在测试角色",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(role)
|
||||
|
||||
_, err := roleSvc.AssignPermissions(userCtx, role.ID, []uint{99999})
|
||||
assert.Error(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
// TestRolePermissionAssociation_SoftDelete 测试软删除对角色权限关联的影响
|
||||
func TestRolePermissionAssociation_SoftDelete(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
// 启动容器
|
||||
pgContainer, err := testcontainers_postgres.RunContainer(ctx,
|
||||
testcontainers.WithImage("postgres:14-alpine"),
|
||||
testcontainers_postgres.WithDatabase("testdb"),
|
||||
testcontainers_postgres.WithUsername("postgres"),
|
||||
testcontainers_postgres.WithPassword("password"),
|
||||
testcontainers.WithWaitStrategy(
|
||||
wait.ForLog("database system is ready to accept connections").
|
||||
WithOccurrence(2).
|
||||
WithStartupTimeout(30*time.Second),
|
||||
),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = pgContainer.Terminate(ctx) }()
|
||||
|
||||
pgConnStr, _ := pgContainer.ConnectionString(ctx, "sslmode=disable")
|
||||
|
||||
// 设置环境
|
||||
db, _ := gorm.Open(postgres.Open(pgConnStr), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
_ = db.AutoMigrate(&model.Role{}, &model.Permission{}, &model.RolePermission{})
|
||||
|
||||
roleStore := postgresStore.NewRoleStore(db)
|
||||
permStore := postgresStore.NewPermissionStore(db)
|
||||
rolePermStore := postgresStore.NewRolePermissionStore(db)
|
||||
roleSvc := roleService.New(roleStore, permStore, rolePermStore)
|
||||
|
||||
userCtx := middleware.SetUserContext(ctx, 1, constants.UserTypeRoot, 0)
|
||||
|
||||
t.Run("软删除权限后重新分配可以恢复", func(t *testing.T) {
|
||||
// 创建测试数据
|
||||
role := &model.Role{
|
||||
RoleName: "恢复权限测试角色",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(role)
|
||||
|
||||
perm := &model.Permission{
|
||||
PermName: "恢复权限测试",
|
||||
PermCode: "restore:perm:test",
|
||||
PermType: constants.PermissionTypeMenu,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(perm)
|
||||
|
||||
// 分配权限
|
||||
_, err := roleSvc.AssignPermissions(userCtx, role.ID, []uint{perm.ID})
|
||||
require.NoError(t, err)
|
||||
|
||||
// 移除权限
|
||||
err = roleSvc.RemovePermission(userCtx, role.ID, perm.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 重新分配权限
|
||||
rps, err := roleSvc.AssignPermissions(userCtx, role.ID, []uint{perm.ID})
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, rps, 1)
|
||||
|
||||
// 验证关联已恢复
|
||||
perms, err := roleSvc.GetPermissions(userCtx, role.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, perms, 1)
|
||||
})
|
||||
|
||||
t.Run("批量分配和移除权限", func(t *testing.T) {
|
||||
// 创建测试角色
|
||||
role := &model.Role{
|
||||
RoleName: "批量权限测试角色",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(role)
|
||||
|
||||
// 创建多个权限
|
||||
permIDs := make([]uint, 5)
|
||||
for i := 0; i < 5; i++ {
|
||||
perm := &model.Permission{
|
||||
PermName: "批量权限测试_" + string(rune('A'+i)),
|
||||
PermCode: "batch:perm:test:" + string(rune('a'+i)),
|
||||
PermType: constants.PermissionTypeMenu,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(perm)
|
||||
permIDs[i] = perm.ID
|
||||
}
|
||||
|
||||
// 批量分配
|
||||
_, err := roleSvc.AssignPermissions(userCtx, role.ID, permIDs)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 验证分配成功
|
||||
perms, err := roleSvc.GetPermissions(userCtx, role.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, perms, 5)
|
||||
|
||||
// 移除部分权限
|
||||
for i := 0; i < 3; i++ {
|
||||
err = roleSvc.RemovePermission(userCtx, role.ID, permIDs[i])
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// 验证剩余权限
|
||||
perms, err = roleSvc.GetPermissions(userCtx, role.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, perms, 2)
|
||||
})
|
||||
}
|
||||
|
||||
// TestRolePermissionAssociation_Cascade 测试级联行为
|
||||
func TestRolePermissionAssociation_Cascade(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
// 启动容器
|
||||
pgContainer, err := testcontainers_postgres.RunContainer(ctx,
|
||||
testcontainers.WithImage("postgres:14-alpine"),
|
||||
testcontainers_postgres.WithDatabase("testdb"),
|
||||
testcontainers_postgres.WithUsername("postgres"),
|
||||
testcontainers_postgres.WithPassword("password"),
|
||||
testcontainers.WithWaitStrategy(
|
||||
wait.ForLog("database system is ready to accept connections").
|
||||
WithOccurrence(2).
|
||||
WithStartupTimeout(30*time.Second),
|
||||
),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = pgContainer.Terminate(ctx) }()
|
||||
|
||||
pgConnStr, _ := pgContainer.ConnectionString(ctx, "sslmode=disable")
|
||||
|
||||
// 设置环境
|
||||
db, _ := gorm.Open(postgres.Open(pgConnStr), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
_ = db.AutoMigrate(&model.Role{}, &model.Permission{}, &model.RolePermission{})
|
||||
|
||||
t.Run("验证无外键约束(关联表独立)", func(t *testing.T) {
|
||||
// 创建角色和权限
|
||||
role := &model.Role{
|
||||
RoleName: "级联测试角色",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(role)
|
||||
|
||||
perm := &model.Permission{
|
||||
PermName: "级联测试权限",
|
||||
PermCode: "cascade:test:perm",
|
||||
PermType: constants.PermissionTypeMenu,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(perm)
|
||||
|
||||
// 创建关联
|
||||
rp := &model.RolePermission{
|
||||
RoleID: role.ID,
|
||||
PermID: perm.ID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
db.Create(rp)
|
||||
|
||||
// 删除角色(软删除)
|
||||
db.Delete(role)
|
||||
|
||||
// 验证关联记录仍然存在(无外键约束)
|
||||
var count int64
|
||||
db.Model(&model.RolePermission{}).Where("role_id = ?", role.ID).Count(&count)
|
||||
assert.Equal(t, int64(1), count, "关联记录应该仍然存在,因为没有外键约束")
|
||||
|
||||
// 验证可以独立查询关联记录
|
||||
var rpRecord model.RolePermission
|
||||
err := db.Where("role_id = ? AND perm_id = ?", role.ID, perm.ID).First(&rpRecord).Error
|
||||
assert.NoError(t, err, "应该能查询到关联记录")
|
||||
})
|
||||
}
|
||||
541
tests/integration/role_test.go
Normal file
541
tests/integration/role_test.go
Normal file
@@ -0,0 +1,541 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/testcontainers/testcontainers-go"
|
||||
testcontainers_postgres "github.com/testcontainers/testcontainers-go/modules/postgres"
|
||||
testcontainers_redis "github.com/testcontainers/testcontainers-go/modules/redis"
|
||||
"github.com/testcontainers/testcontainers-go/wait"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/handler"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/routes"
|
||||
roleService "github.com/break/junhong_cmp_fiber/internal/service/role"
|
||||
postgresStore "github.com/break/junhong_cmp_fiber/internal/store/postgres"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/middleware"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/response"
|
||||
)
|
||||
|
||||
// roleTestEnv 角色测试环境
|
||||
type roleTestEnv struct {
|
||||
db *gorm.DB
|
||||
redisClient *redis.Client
|
||||
app *fiber.App
|
||||
roleService *roleService.Service
|
||||
postgresCleanup func()
|
||||
redisCleanup func()
|
||||
}
|
||||
|
||||
// setupRoleTestEnv 设置角色测试环境
|
||||
func setupRoleTestEnv(t *testing.T) *roleTestEnv {
|
||||
t.Helper()
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// 启动 PostgreSQL 容器
|
||||
pgContainer, err := testcontainers_postgres.RunContainer(ctx,
|
||||
testcontainers.WithImage("postgres:14-alpine"),
|
||||
testcontainers_postgres.WithDatabase("testdb"),
|
||||
testcontainers_postgres.WithUsername("postgres"),
|
||||
testcontainers_postgres.WithPassword("password"),
|
||||
testcontainers.WithWaitStrategy(
|
||||
wait.ForLog("database system is ready to accept connections").
|
||||
WithOccurrence(2).
|
||||
WithStartupTimeout(30*time.Second),
|
||||
),
|
||||
)
|
||||
require.NoError(t, err, "启动 PostgreSQL 容器失败")
|
||||
|
||||
pgConnStr, err := pgContainer.ConnectionString(ctx, "sslmode=disable")
|
||||
require.NoError(t, err)
|
||||
|
||||
// 启动 Redis 容器
|
||||
redisContainer, err := testcontainers_redis.RunContainer(ctx,
|
||||
testcontainers.WithImage("redis:6-alpine"),
|
||||
)
|
||||
require.NoError(t, err, "启动 Redis 容器失败")
|
||||
|
||||
redisHost, err := redisContainer.Host(ctx)
|
||||
require.NoError(t, err)
|
||||
redisPort, err := redisContainer.MappedPort(ctx, "6379")
|
||||
require.NoError(t, err)
|
||||
|
||||
// 连接数据库
|
||||
db, err := gorm.Open(postgres.Open(pgConnStr), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// 自动迁移
|
||||
err = db.AutoMigrate(
|
||||
&model.Account{},
|
||||
&model.Role{},
|
||||
&model.Permission{},
|
||||
&model.AccountRole{},
|
||||
&model.RolePermission{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 连接 Redis
|
||||
redisClient := redis.NewClient(&redis.Options{
|
||||
Addr: fmt.Sprintf("%s:%s", redisHost, redisPort.Port()),
|
||||
})
|
||||
|
||||
// 初始化 Store
|
||||
roleStore := postgresStore.NewRoleStore(db)
|
||||
permissionStore := postgresStore.NewPermissionStore(db)
|
||||
rolePermissionStore := postgresStore.NewRolePermissionStore(db)
|
||||
|
||||
// 初始化 Service
|
||||
roleSvc := roleService.New(roleStore, permissionStore, rolePermissionStore)
|
||||
|
||||
// 初始化 Handler
|
||||
roleHandler := handler.NewRoleHandler(roleSvc)
|
||||
|
||||
// 创建 Fiber App
|
||||
app := fiber.New(fiber.Config{
|
||||
ErrorHandler: func(c *fiber.Ctx, err error) error {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
|
||||
},
|
||||
})
|
||||
|
||||
// 注册路由
|
||||
services := &routes.Services{
|
||||
RoleHandler: roleHandler,
|
||||
}
|
||||
routes.RegisterRoutes(app, services)
|
||||
|
||||
return &roleTestEnv{
|
||||
db: db,
|
||||
redisClient: redisClient,
|
||||
app: app,
|
||||
roleService: roleSvc,
|
||||
postgresCleanup: func() {
|
||||
if err := pgContainer.Terminate(ctx); err != nil {
|
||||
t.Logf("终止 PostgreSQL 容器失败: %v", err)
|
||||
}
|
||||
},
|
||||
redisCleanup: func() {
|
||||
if err := redisContainer.Terminate(ctx); err != nil {
|
||||
t.Logf("终止 Redis 容器失败: %v", err)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// teardown 清理测试环境
|
||||
func (e *roleTestEnv) teardown() {
|
||||
if e.postgresCleanup != nil {
|
||||
e.postgresCleanup()
|
||||
}
|
||||
if e.redisCleanup != nil {
|
||||
e.redisCleanup()
|
||||
}
|
||||
}
|
||||
|
||||
// TestRoleAPI_Create 测试创建角色 API
|
||||
func TestRoleAPI_Create(t *testing.T) {
|
||||
env := setupRoleTestEnv(t)
|
||||
defer env.teardown()
|
||||
|
||||
// 添加测试中间件
|
||||
testUserID := uint(1)
|
||||
env.app.Use(func(c *fiber.Ctx) error {
|
||||
ctx := middleware.SetUserContext(c.UserContext(), testUserID, constants.UserTypeRoot, 0)
|
||||
c.SetUserContext(ctx)
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
t.Run("成功创建角色", func(t *testing.T) {
|
||||
reqBody := model.CreateRoleRequest{
|
||||
RoleName: "测试角色",
|
||||
RoleDesc: "这是一个测试角色",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
}
|
||||
|
||||
jsonBody, _ := json.Marshal(reqBody)
|
||||
req := httptest.NewRequest("POST", "/api/v1/roles", bytes.NewReader(jsonBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
|
||||
var result response.Response
|
||||
err = json.NewDecoder(resp.Body).Decode(&result)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 0, result.Code)
|
||||
|
||||
// 验证数据库中角色已创建
|
||||
var count int64
|
||||
env.db.Model(&model.Role{}).Where("role_name = ?", "测试角色").Count(&count)
|
||||
assert.Equal(t, int64(1), count)
|
||||
})
|
||||
|
||||
t.Run("缺少必填字段返回错误", func(t *testing.T) {
|
||||
reqBody := map[string]interface{}{
|
||||
"role_desc": "缺少名称",
|
||||
}
|
||||
|
||||
jsonBody, _ := json.Marshal(reqBody)
|
||||
req := httptest.NewRequest("POST", "/api/v1/roles", bytes.NewReader(jsonBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
|
||||
var result response.Response
|
||||
err = json.NewDecoder(resp.Body).Decode(&result)
|
||||
require.NoError(t, err)
|
||||
assert.NotEqual(t, 0, result.Code)
|
||||
})
|
||||
}
|
||||
|
||||
// TestRoleAPI_Get 测试获取角色详情 API
|
||||
func TestRoleAPI_Get(t *testing.T) {
|
||||
env := setupRoleTestEnv(t)
|
||||
defer env.teardown()
|
||||
|
||||
// 添加测试中间件
|
||||
testUserID := uint(1)
|
||||
env.app.Use(func(c *fiber.Ctx) error {
|
||||
ctx := middleware.SetUserContext(c.UserContext(), testUserID, constants.UserTypeRoot, 0)
|
||||
c.SetUserContext(ctx)
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// 创建测试角色
|
||||
testRole := &model.Role{
|
||||
RoleName: "获取测试角色",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(testRole)
|
||||
|
||||
t.Run("成功获取角色详情", func(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", fmt.Sprintf("/api/v1/roles/%d", testRole.ID), nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
|
||||
var result response.Response
|
||||
err = json.NewDecoder(resp.Body).Decode(&result)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 0, result.Code)
|
||||
})
|
||||
|
||||
t.Run("角色不存在时返回错误", func(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/api/v1/roles/99999", nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
|
||||
var result response.Response
|
||||
err = json.NewDecoder(resp.Body).Decode(&result)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, errors.CodeRoleNotFound, result.Code)
|
||||
})
|
||||
}
|
||||
|
||||
// TestRoleAPI_Update 测试更新角色 API
|
||||
func TestRoleAPI_Update(t *testing.T) {
|
||||
env := setupRoleTestEnv(t)
|
||||
defer env.teardown()
|
||||
|
||||
// 添加测试中间件
|
||||
testUserID := uint(1)
|
||||
env.app.Use(func(c *fiber.Ctx) error {
|
||||
ctx := middleware.SetUserContext(c.UserContext(), testUserID, constants.UserTypeRoot, 0)
|
||||
c.SetUserContext(ctx)
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// 创建测试角色
|
||||
testRole := &model.Role{
|
||||
RoleName: "更新测试角色",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(testRole)
|
||||
|
||||
t.Run("成功更新角色", func(t *testing.T) {
|
||||
newName := "更新后角色"
|
||||
reqBody := model.UpdateRoleRequest{
|
||||
RoleName: &newName,
|
||||
}
|
||||
|
||||
jsonBody, _ := json.Marshal(reqBody)
|
||||
req := httptest.NewRequest("PUT", fmt.Sprintf("/api/v1/roles/%d", testRole.ID), bytes.NewReader(jsonBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
|
||||
// 验证数据库已更新
|
||||
var updated model.Role
|
||||
env.db.First(&updated, testRole.ID)
|
||||
assert.Equal(t, newName, updated.RoleName)
|
||||
})
|
||||
}
|
||||
|
||||
// TestRoleAPI_Delete 测试删除角色 API
|
||||
func TestRoleAPI_Delete(t *testing.T) {
|
||||
env := setupRoleTestEnv(t)
|
||||
defer env.teardown()
|
||||
|
||||
// 添加测试中间件
|
||||
testUserID := uint(1)
|
||||
env.app.Use(func(c *fiber.Ctx) error {
|
||||
ctx := middleware.SetUserContext(c.UserContext(), testUserID, constants.UserTypeRoot, 0)
|
||||
c.SetUserContext(ctx)
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
t.Run("成功软删除角色", func(t *testing.T) {
|
||||
// 创建测试角色
|
||||
testRole := &model.Role{
|
||||
RoleName: "删除测试角色",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(testRole)
|
||||
|
||||
req := httptest.NewRequest("DELETE", fmt.Sprintf("/api/v1/roles/%d", testRole.ID), nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
|
||||
// 验证角色已软删除
|
||||
var deleted model.Role
|
||||
err = env.db.Unscoped().First(&deleted, testRole.ID).Error
|
||||
require.NoError(t, err)
|
||||
assert.NotNil(t, deleted.DeletedAt)
|
||||
})
|
||||
}
|
||||
|
||||
// TestRoleAPI_List 测试角色列表 API
|
||||
func TestRoleAPI_List(t *testing.T) {
|
||||
env := setupRoleTestEnv(t)
|
||||
defer env.teardown()
|
||||
|
||||
// 添加测试中间件
|
||||
testUserID := uint(1)
|
||||
env.app.Use(func(c *fiber.Ctx) error {
|
||||
ctx := middleware.SetUserContext(c.UserContext(), testUserID, constants.UserTypeRoot, 0)
|
||||
c.SetUserContext(ctx)
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// 创建多个测试角色
|
||||
for i := 1; i <= 5; i++ {
|
||||
role := &model.Role{
|
||||
RoleName: fmt.Sprintf("列表测试角色_%d", i),
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(role)
|
||||
}
|
||||
|
||||
t.Run("成功获取角色列表", func(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", "/api/v1/roles?page=1&page_size=10", nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
|
||||
var result response.Response
|
||||
err = json.NewDecoder(resp.Body).Decode(&result)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 0, result.Code)
|
||||
})
|
||||
}
|
||||
|
||||
// TestRoleAPI_AssignPermissions 测试分配权限 API
|
||||
func TestRoleAPI_AssignPermissions(t *testing.T) {
|
||||
env := setupRoleTestEnv(t)
|
||||
defer env.teardown()
|
||||
|
||||
// 添加测试中间件
|
||||
testUserID := uint(1)
|
||||
env.app.Use(func(c *fiber.Ctx) error {
|
||||
ctx := middleware.SetUserContext(c.UserContext(), testUserID, constants.UserTypeRoot, 0)
|
||||
c.SetUserContext(ctx)
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// 创建测试角色
|
||||
testRole := &model.Role{
|
||||
RoleName: "权限分配测试角色",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(testRole)
|
||||
|
||||
// 创建测试权限
|
||||
testPerm := &model.Permission{
|
||||
PermName: "测试权限",
|
||||
PermCode: "test:permission",
|
||||
PermType: constants.PermissionTypeMenu,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(testPerm)
|
||||
|
||||
t.Run("成功分配权限", func(t *testing.T) {
|
||||
reqBody := model.AssignPermissionsRequest{
|
||||
PermIDs: []uint{testPerm.ID},
|
||||
}
|
||||
|
||||
jsonBody, _ := json.Marshal(reqBody)
|
||||
req := httptest.NewRequest("POST", fmt.Sprintf("/api/v1/roles/%d/permissions", testRole.ID), bytes.NewReader(jsonBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
|
||||
// 验证关联已创建
|
||||
var count int64
|
||||
env.db.Model(&model.RolePermission{}).Where("role_id = ? AND perm_id = ?", testRole.ID, testPerm.ID).Count(&count)
|
||||
assert.Equal(t, int64(1), count)
|
||||
})
|
||||
}
|
||||
|
||||
// TestRoleAPI_GetPermissions 测试获取角色权限 API
|
||||
func TestRoleAPI_GetPermissions(t *testing.T) {
|
||||
env := setupRoleTestEnv(t)
|
||||
defer env.teardown()
|
||||
|
||||
// 添加测试中间件
|
||||
testUserID := uint(1)
|
||||
env.app.Use(func(c *fiber.Ctx) error {
|
||||
ctx := middleware.SetUserContext(c.UserContext(), testUserID, constants.UserTypeRoot, 0)
|
||||
c.SetUserContext(ctx)
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// 创建测试角色
|
||||
testRole := &model.Role{
|
||||
RoleName: "获取权限测试角色",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(testRole)
|
||||
|
||||
// 创建并分配权限
|
||||
testPerm := &model.Permission{
|
||||
PermName: "获取权限测试",
|
||||
PermCode: "get:permission:test",
|
||||
PermType: constants.PermissionTypeMenu,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(testPerm)
|
||||
|
||||
rolePerm := &model.RolePermission{
|
||||
RoleID: testRole.ID,
|
||||
PermID: testPerm.ID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(rolePerm)
|
||||
|
||||
t.Run("成功获取角色权限", func(t *testing.T) {
|
||||
req := httptest.NewRequest("GET", fmt.Sprintf("/api/v1/roles/%d/permissions", testRole.ID), nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
|
||||
var result response.Response
|
||||
err = json.NewDecoder(resp.Body).Decode(&result)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 0, result.Code)
|
||||
})
|
||||
}
|
||||
|
||||
// TestRoleAPI_RemovePermission 测试移除权限 API
|
||||
func TestRoleAPI_RemovePermission(t *testing.T) {
|
||||
env := setupRoleTestEnv(t)
|
||||
defer env.teardown()
|
||||
|
||||
// 添加测试中间件
|
||||
testUserID := uint(1)
|
||||
env.app.Use(func(c *fiber.Ctx) error {
|
||||
ctx := middleware.SetUserContext(c.UserContext(), testUserID, constants.UserTypeRoot, 0)
|
||||
c.SetUserContext(ctx)
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// 创建测试角色
|
||||
testRole := &model.Role{
|
||||
RoleName: "移除权限测试角色",
|
||||
RoleType: constants.RoleTypeSuper,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(testRole)
|
||||
|
||||
// 创建并分配权限
|
||||
testPerm := &model.Permission{
|
||||
PermName: "移除权限测试",
|
||||
PermCode: "remove:permission:test",
|
||||
PermType: constants.PermissionTypeMenu,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(testPerm)
|
||||
|
||||
rolePerm := &model.RolePermission{
|
||||
RoleID: testRole.ID,
|
||||
PermID: testPerm.ID,
|
||||
Status: constants.StatusEnabled,
|
||||
Creator: 1,
|
||||
Updater: 1,
|
||||
}
|
||||
env.db.Create(rolePerm)
|
||||
|
||||
t.Run("成功移除权限", func(t *testing.T) {
|
||||
req := httptest.NewRequest("DELETE", fmt.Sprintf("/api/v1/roles/%d/permissions/%d", testRole.ID, testPerm.ID), nil)
|
||||
resp, err := env.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
|
||||
|
||||
// 验证关联已软删除
|
||||
var rp model.RolePermission
|
||||
err = env.db.Unscoped().Where("role_id = ? AND perm_id = ?", testRole.ID, testPerm.ID).First(&rp).Error
|
||||
require.NoError(t, err)
|
||||
assert.NotNil(t, rp.DeletedAt)
|
||||
})
|
||||
}
|
||||
@@ -29,7 +29,7 @@ func TestTaskSubmit(t *testing.T) {
|
||||
redisClient := redis.NewClient(&redis.Options{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer redisClient.Close()
|
||||
defer func() { _ = redisClient.Close() }()
|
||||
|
||||
// 清理测试数据
|
||||
ctx := context.Background()
|
||||
@@ -39,7 +39,7 @@ func TestTaskSubmit(t *testing.T) {
|
||||
client := asynq.NewClient(asynq.RedisClientOpt{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer client.Close()
|
||||
defer func() { _ = client.Close() }()
|
||||
|
||||
// 构造任务载荷
|
||||
payload := &EmailPayload{
|
||||
@@ -72,7 +72,7 @@ func TestTaskPriority(t *testing.T) {
|
||||
redisClient := redis.NewClient(&redis.Options{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer redisClient.Close()
|
||||
defer func() { _ = redisClient.Close() }()
|
||||
|
||||
ctx := context.Background()
|
||||
redisClient.FlushDB(ctx)
|
||||
@@ -81,7 +81,7 @@ func TestTaskPriority(t *testing.T) {
|
||||
client := asynq.NewClient(asynq.RedisClientOpt{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer client.Close()
|
||||
defer func() { _ = client.Close() }()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -118,7 +118,7 @@ func TestTaskRetry(t *testing.T) {
|
||||
redisClient := redis.NewClient(&redis.Options{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer redisClient.Close()
|
||||
defer func() { _ = redisClient.Close() }()
|
||||
|
||||
ctx := context.Background()
|
||||
redisClient.FlushDB(ctx)
|
||||
@@ -126,7 +126,7 @@ func TestTaskRetry(t *testing.T) {
|
||||
client := asynq.NewClient(asynq.RedisClientOpt{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer client.Close()
|
||||
defer func() { _ = client.Close() }()
|
||||
|
||||
payload := &EmailPayload{
|
||||
RequestID: "retry-test-001",
|
||||
@@ -155,7 +155,7 @@ func TestTaskIdempotency(t *testing.T) {
|
||||
redisClient := redis.NewClient(&redis.Options{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer redisClient.Close()
|
||||
defer func() { _ = redisClient.Close() }()
|
||||
|
||||
ctx := context.Background()
|
||||
redisClient.FlushDB(ctx)
|
||||
@@ -190,7 +190,7 @@ func TestTaskStatusTracking(t *testing.T) {
|
||||
redisClient := redis.NewClient(&redis.Options{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer redisClient.Close()
|
||||
defer func() { _ = redisClient.Close() }()
|
||||
|
||||
ctx := context.Background()
|
||||
redisClient.FlushDB(ctx)
|
||||
@@ -222,7 +222,7 @@ func TestQueueInspection(t *testing.T) {
|
||||
redisClient := redis.NewClient(&redis.Options{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer redisClient.Close()
|
||||
defer func() { _ = redisClient.Close() }()
|
||||
|
||||
ctx := context.Background()
|
||||
redisClient.FlushDB(ctx)
|
||||
@@ -230,7 +230,7 @@ func TestQueueInspection(t *testing.T) {
|
||||
client := asynq.NewClient(asynq.RedisClientOpt{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer client.Close()
|
||||
defer func() { _ = client.Close() }()
|
||||
|
||||
// 提交多个任务
|
||||
for i := 0; i < 5; i++ {
|
||||
@@ -253,7 +253,7 @@ func TestQueueInspection(t *testing.T) {
|
||||
inspector := asynq.NewInspector(asynq.RedisClientOpt{
|
||||
Addr: "localhost:6379",
|
||||
})
|
||||
defer inspector.Close()
|
||||
defer func() { _ = inspector.Close() }()
|
||||
|
||||
// 获取队列信息
|
||||
info, err := inspector.GetQueueInfo(constants.QueueDefault)
|
||||
|
||||
Reference in New Issue
Block a user