Files
syops/backend/tests/services/admin/test_department_service.py
T

181 lines
8.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
tests/services/admin/test_department_service.py
用途:department_service 部门树 CRUD、树组装、成员口径单元测试。
覆盖:父子挂接 / 同级查重 / 编码唯一 / 防成环 / 删除保护(有下级、有员工)/ 成员数含下级汇总。
"""
import pytest
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import Department, User
from app.services.admin.department_service import (
create_department,
delete_department,
list_department_members,
list_department_tree,
list_departments,
update_department,
)
def test_department_crud_with_parent(app):
"""断言:父子挂接进树、字段可更新、有下级禁删、无下级可删。"""
with app.app_context():
parent = create_department({'name': '品保部', 'code': 'QA', 'company': 'HX'})
child = create_department({'name': '品保课', 'code': 'QA1', 'parent_id': parent['id'], 'sort_order': 2})
assert child['name'] == '品保课'
items = list_departments()
assert any(item['code'] == 'QA1' and item['parent_id'] == parent['id'] for item in items)
update_department(child['id'], {'sort_order': 9, 'is_hidden': True})
dept = db.session.get(Department, child['id'])
assert dept.sort_order == 9
assert dept.is_hidden is True
# 分支测试意图:存在下级部门时删除必须被 HAS_CHILDREN 拦截
with pytest.raises(ConflictError, match='child'):
delete_department(parent['id'])
delete_department(child['id'])
delete_department(parent['id'])
assert db.session.get(Department, parent['id']) is None
def test_create_department_rejects_same_parent_duplicate_name(app):
"""断言:同一上级下同名部门被拒(同级查重)。"""
with app.app_context():
create_department({'name': 'Sales'})
with pytest.raises(ValidationError) as exc_info:
create_department({'name': 'Sales'})
# 断言业务错误码而非消息文本(str(exc) 仅含 message,不含 code)
assert exc_info.value.code == 'DEPT.NAME_EXISTS'
def test_create_department_allows_same_name_under_different_parents(app):
"""断言:不同分支(多公司)允许同名部门——name 全局唯一已放开。"""
with app.app_context():
root_a = create_department({'name': '和信', 'company': '和信'})
root_b = create_department({'name': '泰国合欣', 'company': '泰国合欣'})
create_department({'name': '管理部', 'parent_id': root_a['id']})
create_department({'name': '管理部', 'parent_id': root_b['id']})
tree = list_department_tree()
assert len(tree) == 2
assert all(len([c for c in root['children'] if c['name'] == '管理部']) == 1 for root in tree)
def test_create_department_allows_same_name_root_across_companies(app):
"""分支测试意图:两家公司的顶级部门允许同名(按 company 分桶查重),同公司顶级同名仍拒绝。"""
with app.app_context():
create_department({'name': '管理部', 'company': '苏州和信'})
create_department({'name': '管理部', 'company': '泰国合欣'})
with pytest.raises(ValidationError) as exc_info:
create_department({'name': '管理部', 'company': '苏州和信'})
assert exc_info.value.code == 'DEPT.NAME_EXISTS'
def test_create_department_inherits_company_from_parent(app):
"""断言:未填公司时继承上级部门 company(公司虚拟分组依赖)。"""
with app.app_context():
root = create_department({'name': '和信', 'company': '苏州和信'})
child = create_department({'name': '财务部', 'parent_id': root['id']})
dept = db.session.get(Department, child['id'])
assert dept.company == '苏州和信'
def test_create_department_rejects_duplicate_code(app):
"""断言:部门编码全局唯一。"""
with app.app_context():
create_department({'name': 'A', 'code': 'C1'})
with pytest.raises(ValidationError) as exc_info:
create_department({'name': 'B', 'code': 'C1'})
assert exc_info.value.code == 'DEPT.CODE_EXISTS'
def test_update_parent_cycle_rejected(app):
"""分支测试意图:把部门挂到自己或自己的子孙下必须被 CYCLE_FORBIDDEN 拦截。"""
with app.app_context():
root = create_department({'name': 'Root'})
child = create_department({'name': 'Child', 'parent_id': root['id']})
grand = create_department({'name': 'Grand', 'parent_id': child['id']})
assert grand['name'] == 'Grand'
with pytest.raises(ValidationError) as exc_info:
update_department(root['id'], {'parent_id': grand['id']})
assert exc_info.value.code == 'DEPT.CYCLE_FORBIDDEN'
with pytest.raises(ValidationError) as exc_info:
update_department(root['id'], {'parent_id': root['id']})
assert exc_info.value.code == 'DEPT.CYCLE_FORBIDDEN'
def test_update_department_not_found(app):
with app.app_context():
with pytest.raises(NotFoundError):
update_department(99999, {'name': 'X'})
def test_delete_department_with_members_rejected(app):
"""断言:名下仍有员工(users.department 文本命中)时删除被 HAS_MEMBERS 拦截。"""
with app.app_context():
dept = create_department({'name': '品保部'})
db.session.add(User(username='u1', email='u1@example.com', department='品保部', role='user', status='active'))
db.session.commit()
with pytest.raises(ConflictError, match='members'):
delete_department(dept['id'])
def test_member_count_tree_rollup_and_members_scope(app):
"""断言:树节点 member_count 为直属人数、total_member_count 递归含下级;成员接口按口径过滤。"""
with app.app_context():
root = create_department({'name': '物料部'})
child = create_department({'name': '仓储课', 'parent_id': root['id']})
db.session.add_all([
User(username='r1', email='r1@example.com', department='物料部', role='user', status='active'),
User(username='c1', email='c1@example.com', department='仓储课', role='user', status='active'),
User(username='c2', email='c2@example.com', department='仓储课', role='user', status='active'),
])
db.session.commit()
tree = list_department_tree()
node = tree[0]
assert node['member_count'] == 1
assert node['total_member_count'] == 3
assert node['children'][0]['total_member_count'] == 2
direct = list_department_members(child['id'])
assert direct['total'] == 2
subtree = list_department_members(root['id'], include_descendants=True)
assert subtree['total'] == 3
assert all(member.get('department') in ('物料部', '仓储课') for member in subtree['members'])
def test_members_keyword_search_and_pagination(app):
"""分支测试意图:成员接口按 姓名/工号/手机 模糊搜索,并按 page/page_size 分页。"""
with app.app_context():
dept = create_department({'name': '品保部'})
db.session.add_all([
User(username='u1', real_name='张一', employee_id='E001', phone_number='13800000001',
email='u1@example.com', department='品保部', role='user', status='active'),
User(username='u2', real_name='张二', employee_id='E002', phone_number='13800000002',
email='u2@example.com', department='品保部', role='user', status='active'),
User(username='u3', real_name='李三', employee_id='E003', phone_number='13800000003',
email='u3@example.com', department='品保部', role='user', status='active'),
])
db.session.commit()
# 关键词命中工号
by_emp = list_department_members(dept['id'], keyword='E003')
assert by_emp['total'] == 1
assert by_emp['members'][0]['real_name'] == '李三'
# 关键词命中手机号
by_phone = list_department_members(dept['id'], keyword='13800000002')
assert by_phone['total'] == 1
assert by_phone['members'][0]['username'] == 'u2'
# 关键词命中姓名(同姓两人)
by_name = list_department_members(dept['id'], keyword='张')
assert by_name['total'] == 2
# 分页:page_size=2 时第 2 页只剩 1 条
paged = list_department_members(dept['id'], page=2, page_size=2)
assert paged['total'] == 3
assert paged['page'] == 2
assert len(paged['members']) == 1