package system import ( "context" "testing" "git.5iot.com/iotlcm-public/iotlcm-admin-svr/internal/model" ) func TestDeptHierarchyReadGuards(t *testing.T) { for _, tc := range []struct { name string depts []*model.SysDeptListModel invalid bool }{ {"normal", []*model.SysDeptListModel{{DeptId: 1}, {DeptId: 2, ParentId: 1}}, false}, {"orphan", []*model.SysDeptListModel{{DeptId: 2, ParentId: 99}}, false}, {"self", []*model.SysDeptListModel{{DeptId: 1, ParentId: 1}}, true}, {"cycle", []*model.SysDeptListModel{{DeptId: 1, ParentId: 2}, {DeptId: 2, ParentId: 1}}, true}, } { t.Run(tc.name, func(t *testing.T) { if err := validateDeptHierarchy(tc.depts); (err != nil) != tc.invalid { t.Fatalf("unexpected hierarchy error: %v", err) } var ids []int64 if err := NewSysDept().RecursionDeptIds(context.Background(), 1, tc.depts, &ids); (err != nil) != tc.invalid { t.Fatalf("unexpected traversal error: %v", err) } company := NewSysDept().getParentCompanyInfo(context.Background(), tc.depts, 1) if tc.invalid && company != nil { t.Fatal("cyclic company lookup must return nil") } }) } } func TestValidateDeptParent(t *testing.T) { depts := []*model.SysDeptViewModel{ {DeptId: 100, ParentId: 0}, {DeptId: 117, ParentId: 100}, {DeptId: 118, ParentId: 117}, {DeptId: 196, ParentId: 100}, } for _, test := range []struct { name string parentId int64 invalid bool }{ {"root", 0, false}, {"sibling", 196, false}, {"self", 117, true}, {"descendant", 118, true}, {"missing", 999, true}, {"negative", -1, true}, } { t.Run(test.name, func(t *testing.T) { err := validateDeptParent(117, test.parentId, depts) if (err != nil) != test.invalid { t.Fatalf("parent %d: unexpected error %v", test.parentId, err) } }) } cycle := []*model.SysDeptViewModel{{DeptId: 1, ParentId: 2}, {DeptId: 2, ParentId: 1}} if err := validateDeptParent(3, 1, cycle); err == nil { t.Fatal("existing cycle was not rejected") } } func TestGetParentIDAncestorsCycle(t *testing.T) { dept := NewSysDept() for _, test := range []struct { name string depts []*model.SysDeptViewModel parentId int64 expected string invalid bool }{ {"normal", []*model.SysDeptViewModel{{DeptId: 100}, {DeptId: 117, ParentId: 100}}, 117, "0,100,117,", false}, {"self", []*model.SysDeptViewModel{{DeptId: 117, ParentId: 117}}, 117, "", true}, {"cycle", []*model.SysDeptViewModel{{DeptId: 1, ParentId: 2}, {DeptId: 2, ParentId: 1}}, 1, "", true}, } { t.Run(test.name, func(t *testing.T) { var ancestors string err := dept.GetParentIDAncestors(context.Background(), test.depts, test.parentId, &ancestors) if (err != nil) != test.invalid || !test.invalid && ancestors != test.expected { t.Fatalf("ancestors=%q error=%v, expected=%q invalid=%v", ancestors, err, test.expected, test.invalid) } }) } }