From f281a1aebcc7f99e59dcdade02e46a808e569c4e Mon Sep 17 00:00:00 2001 From: chengkai3 Date: Wed, 17 Jun 2026 23:55:36 +0800 Subject: [PATCH] =?UTF-8?q?[fix]:[FL-168][=E6=96=B0=E5=BB=BA=E8=A7=92?= =?UTF-8?q?=E8=89=B2=E6=97=B6=E8=A7=92=E8=89=B2=E7=BC=96=E7=A0=81=E8=A6=81?= =?UTF-8?q?=E5=8A=A0=E5=94=AF=E4=B8=80=E6=80=A7=E6=A0=A1=E9=AA=8C]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 4.6 Co-authored-by: multica-agent --- api/app/api/v1/admin.py | 8 +++++++- api/test_role_uniqueness.py | 25 +++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 api/test_role_uniqueness.py diff --git a/api/app/api/v1/admin.py b/api/app/api/v1/admin.py index 48bc7c6..508b582 100644 --- a/api/app/api/v1/admin.py +++ b/api/app/api/v1/admin.py @@ -56,9 +56,15 @@ def create_role_endpoint( current_user: CurrentUser = Depends(require_permission("role.manage")), db: Session = Depends(get_db), ) -> RolePublic: + from sqlalchemy import text + # Check if role code already exists + existing = db.scalar(text("SELECT id FROM user_role WHERE id = :id"), {"id": payload.code.strip()}) + if existing: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="角色编码已存在,请使用其他编码") + created = create_role(db, payload, actor_user_id=current_user.user.id) if not created: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid role payload or duplicate role code") + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="创建角色失败,请检查菜单权限配置是否正确") return created diff --git a/api/test_role_uniqueness.py b/api/test_role_uniqueness.py new file mode 100644 index 0000000..d730a6d --- /dev/null +++ b/api/test_role_uniqueness.py @@ -0,0 +1,25 @@ +""" +临时测试:验证角色编码唯一性校验 +""" +from fastapi.testclient import TestClient +from app.main import app + +client = TestClient(app) + +def test_role_code_uniqueness(): + """测试角色编码唯一性校验""" + print("\n=== 测试角色编码唯一性校验 ===") + + # 注意:这是一个手动测试,需要有效的认证token + # 实际运行时需要替换为真实的token + print("此测试需要手动运行,需要:") + print("1. 有效的认证token") + print("2. role.manage权限") + print("3. 数据库连接") + print("\n预期行为:") + print("- 创建新角色成功") + print("- 使用相同编码再次创建时,返回 400 错误") + print("- 错误消息为:'角色编码已存在,请使用其他编码'") + +if __name__ == "__main__": + test_role_code_uniqueness()