package dept import ( "context" "testing" "perms-system-server/internal/svc" "perms-system-server/internal/testutil" "perms-system-server/internal/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // TC-0098: 正常获取 func TestDeptTree_Normal(t *testing.T) { ctx := context.Background() svcCtx := svc.NewServiceContext(testutil.GetTestConfig()) conn := testutil.GetTestSqlConn() rootId, err := insertDeptRaw(ctx, svcCtx, 0, "tree_root_"+testutil.UniqueId(), "/") require.NoError(t, err) root, _ := svcCtx.SysDeptModel.FindOne(ctx, rootId) c1Id, err := insertDeptRaw(ctx, svcCtx, rootId, "tree_c1_"+testutil.UniqueId(), root.Path) require.NoError(t, err) c2Id, err := insertDeptRaw(ctx, svcCtx, rootId, "tree_c2_"+testutil.UniqueId(), root.Path) require.NoError(t, err) t.Cleanup(func() { testutil.CleanTable(ctx, conn, "`sys_dept`", c1Id, c2Id, rootId) }) treeLogic := NewDeptTreeLogic(ctx, svcCtx) tree, err := treeLogic.DeptTree() require.NoError(t, err) require.NotNil(t, tree) var rootNode *types.DeptItem for _, node := range tree { if node.Id == rootId { rootNode = node break } } require.NotNil(t, rootNode, "should find the test root node in tree") assert.Equal(t, int64(0), rootNode.ParentId) assert.Equal(t, "NORMAL", rootNode.DeptType) require.Len(t, rootNode.Children, 2) childIds := []int64{rootNode.Children[0].Id, rootNode.Children[1].Id} assert.ElementsMatch(t, []int64{c1Id, c2Id}, childIds) } // TC-0099: 空数据 func TestDeptTree_Empty(t *testing.T) { ctx := context.Background() svcCtx := svc.NewServiceContext(testutil.GetTestConfig()) treeLogic := NewDeptTreeLogic(ctx, svcCtx) tree, err := treeLogic.DeptTree() require.NoError(t, err) assert.NotNil(t, tree) // Known limitation: shared integration DB may hold rows from other tests or packages, // so we cannot assert len(tree)==0 here without isolating or truncating sys_dept. } // TC-0100: 孤儿节点 func TestDeptTree_OrphanBecomesRoot(t *testing.T) { ctx := context.Background() svcCtx := svc.NewServiceContext(testutil.GetTestConfig()) conn := testutil.GetTestSqlConn() parentId, err := insertDeptRaw(ctx, svcCtx, 0, "orphan_p_"+testutil.UniqueId(), "/") require.NoError(t, err) parent, _ := svcCtx.SysDeptModel.FindOne(ctx, parentId) childId, err := insertDeptRaw(ctx, svcCtx, parentId, "orphan_c_"+testutil.UniqueId(), parent.Path) require.NoError(t, err) testutil.CleanTable(ctx, conn, "`sys_dept`", parentId) t.Cleanup(func() { testutil.CleanTable(ctx, conn, "`sys_dept`", childId) }) treeLogic := NewDeptTreeLogic(ctx, svcCtx) tree, err := treeLogic.DeptTree() require.NoError(t, err) var orphanNode *types.DeptItem for _, node := range tree { if node.Id == childId { orphanNode = node break } } require.NotNil(t, orphanNode, "orphan node should appear as root") assert.Equal(t, parentId, orphanNode.ParentId) }