Files
company-ai-platform/tests/test_personnel_role_content.py
T
2026-11-24 09:12:15 +08:00

355 lines
19 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.
import pytest
from app.modules.work_assistant.personnel_profile import (
Decision, ProfileRequest, KEYS, DETAIL_SECTIONS, generation_schema, validate,
)
def fixture():
evidence = [
dict(id='duty', kind='duty', subject='测试交付', actor_id='', at='', relation='requirement', content='测试报告须完成评审并归档。'),
dict(id='work', kind='feedback', subject='报告评审', actor_id='103', at='2026-11-16', relation='self', content='已提交测试报告,评审意见要求补充边界用例。'),
]
entry = ProfileRequest(person_id='103', name='测试人员', department_id='1', department='测试部', posts='测试经理',
begin='2026-11-01', end='2026-11-18', evidence=evidence, coverage=[], limits=[])
result = {section: [] for section in DETAIL_SECTIONS}
result['findings'] = [dict(key=key, status='review_required' if key=='assignment' else 'insufficient',
headline='测试交付待核对', finding='已提交报告,评审后的补充情况待核对。', action='',
basis=[dict(evidence_id='work', quote=evidence[1]['content'])]) for key in KEYS]
result['findings'][3]['headline']='适合侧重测试报告修订'
result['findings'][4]['headline']='建议承担报告修订'
result['findings'][4]['basis'].append(dict(evidence_id='duty',quote=evidence[0]['content']))
return entry, result
def test_role_judgment_requires_the_actual_role_requirement():
entry, result = fixture()
fit = result['findings'][1]
fit['status'] = 'attention'
with pytest.raises(ValueError, match='岗位适配'):
validate(entry,result)
fit['basis'].append(dict(evidence_id='duty',quote=entry.evidence[0].content))
assert validate(entry,result)['heading_review_version']==3
def test_person_portrait_retains_specific_work_and_requires_actual_evidence():
entry, result = fixture()
row = dict(topic='报告交付与修订推进', record=entry.evidence[1].content,
assessment='已有报告提交记录,评审后的边界用例补充结果仍需核对。', action='',
basis=[dict(evidence_id='work', quote=entry.evidence[1].content)])
result['portrait'] = [row]
validated = validate(entry, result)
assert validated['detail_review_version'] == 1
assert validated['portrait'][0]['assessment'] == row['assessment']
entry.evidence = [e for e in entry.evidence if e.kind != 'duty']
result['findings'][4]['basis'] = [row['basis'][0]]
assert validate(entry, result)['portrait']
row['basis'][0]['quote'] = '不存在的工作成果'
with pytest.raises(ValueError):
validate(entry, result)
def test_portrait_is_backward_compatible_but_duties_alone_cannot_describe_person():
entry, result = fixture()
result.pop('portrait')
assert validate(entry, result)['portrait'] == []
result['portrait'] = [dict(topic='报告提交', record='岗位要求提交报告', assessment='需要核对实际提交情况',
action='', basis=[dict(evidence_id='duty', quote=entry.evidence[0].content)])]
with pytest.raises(ValueError):
validate(entry, result)
def test_portrait_has_detail_specific_space_without_expanding_roster_summaries():
schema = generation_schema(Decision.model_json_schema(), 3, 3, True)
assert schema['properties']['portrait']['maxItems'] == 3
assert schema['$defs']['PortraitRow']['properties']['record']['maxLength'] == 240
assert schema['$defs']['PortraitRow']['properties']['assessment']['maxLength'] == 240
assert schema['$defs']['DetailRow']['properties']['record']['maxLength'] == 160
@pytest.mark.parametrize('claim',['高频完成商务工作','完成了20余项商务任务','展现了良好的多任务处理能力'])
def test_portrait_does_not_turn_activity_counts_into_ability_ratings(claim):
entry,result=fixture()
result['portrait']=[dict(topic='工作表现',record=claim,assessment='报告已提交,后续修订结果待核对。',action='',
basis=[dict(evidence_id='work',quote=entry.evidence[1].content)])]
with pytest.raises(ValueError,match='任务数量'):
validate(entry,result)
def test_assignment_cannot_be_replaced_by_a_description_of_current_problems():
entry,result=fixture()
result['findings'][4]['headline']='项目有推进但材料缺失'
result['findings'][4]['finding']='已提交报告,后续材料尚未取得。'
with pytest.raises(ValueError,match='具体分工建议'):
validate(entry,result)
def test_future_deliverable_is_not_mistaken_for_an_already_completed_result():
from app.modules.work_assistant.personnel_profile import review_requires_repair
row={'key':'assignment','status':'review_required','headline':'建议负责人员辅导',
'finding':'负责未达标人员谈话,输出后续改进计划,由主管复核。',
'basis':[{'source_role':'本人','quote':'未达标人员谈话记录已提交。'}]}
assert not review_requires_repair(row,'原文未提及已制定改进计划,未来分工缺少依据。')
assert review_requires_repair(row,'所建议分工与岗位职责不符,属于转岗。')
row['finding']='已制定改进计划,建议负责人员辅导。'
assert review_requires_repair(row,'原文未提及已制定改进计划。')
def test_duty_details_require_a_traceable_requirement():
entry, result = fixture()
row = dict(topic='报告归档',record='提交报告',assessment='归档情况待核对',action='',
basis=[dict(evidence_id='work',quote=entry.evidence[1].content)])
result['duties']=[row]
with pytest.raises(ValueError,match='岗位职责原文'):
validate(entry,result)
row['basis'].append(dict(evidence_id='duty',quote=entry.evidence[0].content))
assert len(validate(entry,result)['duties'])==1
def test_missing_work_is_allowed_as_an_explicit_unverified_duty():
entry,result=fixture()
result['duties']=[dict(topic='报告归档',record='未取得归档记录',assessment='归档结果待核对',action='',
basis=[dict(evidence_id='duty',quote=entry.evidence[0].content)])]
assert len(validate(entry,result)['duties'])==1
def test_role_details_are_not_truncated_to_two_items():
schema=Decision.model_json_schema()
schema['properties']['duties']['maxItems']=9
generated=generation_schema(schema,2,2,True)
assert generated['properties']['duties']['maxItems']==9
assert generated['properties']['development']['maxItems']==2
def test_optional_sections_do_not_force_irrelevant_details():
entry,result=fixture()
entry.evidence.append(entry.evidence[1].model_copy(update={'id':'task','kind':'task','relation':'requirement','state':'unfinished'}))
assert validate(entry,result)['progress']==[]
def test_forged_duty_quote_is_rejected():
entry,result=fixture()
result['findings'][1]['basis']=[dict(evidence_id='duty',quote='所有职责均已完成')]
with pytest.raises(ValueError,match='原始资料'):
validate(entry,result)
def test_task_quality_without_duties_survives_validation_and_normalization():
from app.modules.work_assistant.personnel_profile import normalize_scope
entry,result=fixture()
entry.evidence=[e for e in entry.evidence if e.kind!='duty']
result['findings'][4]['basis']=result['findings'][4]['basis'][:1]
fit=result['findings'][1]
fit.update(status='attention',headline='报告已提交,边界用例仍需补充',
finding='本人反馈已提交测试报告,评审要求补充边界用例;交付动作已记录,当前报告仍有明确修改项。')
result['duties']=[dict(topic='测试报告交付与评审',record='本人反馈已提交测试报告。',
assessment='评审要求补充边界用例,当前交付尚有修改项。',action='补充用例后交审核人复核。',basis=fit['basis'])]
validated=validate(entry,normalize_scope(result,False))
assert validated['assessment_scope']=='tasks'
assert validated['findings'][1]==fit
assert validated['duties']==result['duties']
def test_task_registration_alone_cannot_prove_quality():
entry,result=fixture()
entry.evidence=[entry.evidence[1].model_copy(update={'kind':'task','relation':'requirement','state':'complete'})]
result['findings'][4]['basis']=result['findings'][4]['basis'][:1]
result['findings'][1].update(status='supported',headline='交付合格',finding='任务已登记完成。')
with pytest.raises(ValueError,match='缺少实际工作'):
validate(entry,result)
def test_one_actual_inspection_can_support_a_task_result_without_role_document():
entry,result=fixture()
entry.evidence=[entry.evidence[1].model_copy(update={'kind':'review','relation':'reviewer','content':'测试报告边界用例齐全,本次检查合格。'})]
for row in result['findings']:
row['basis']=[dict(evidence_id='work',quote=entry.evidence[0].content)]
row['finding']='本次检查确认测试报告边界用例齐全。'
result['findings'][1].update(status='supported',headline='测试报告本次检查合格')
validated=validate(entry,result)
assert validated['findings'][1]['status']=='supported'
assert validated['assessment_scope']=='tasks'
def test_expanded_generation_contract_keeps_explanations_and_citations():
from app.modules.work_assistant.personnel_profile import prompt_contract
schema=generation_schema(Decision.model_json_schema(),4,4,True)
assert schema['properties']['directions']['maxItems']==4
for variant in schema['$defs']['Finding']['anyOf']:
assert variant['properties']['finding']['maxLength']==220
assert variant['properties']['basis']['maxItems']==6
prompt=prompt_contract(schema)
for name in ('DetailRow','DirectionRow','ProgressRow','ResponseRow'):
assert prompt['$defs'][name]['properties']['assessment']['maxLength']==160
assert prompt['$defs'][name]['properties']['record']['maxLength']==160
def test_hidden_attendance_section_does_not_require_an_impossible_row():
from app.modules.work_assistant.personnel_profile import attendance_schema
schema=Decision.model_json_schema()
schema['properties']['followups']['maxItems']=0
result=attendance_schema(schema,[0],['attendance'],[])
assert result['properties']['followups'].get('minItems',0)==0
def test_split_finding_generation_with_attendance_does_not_require_followups():
from app.modules.work_assistant.personnel_profile import attendance_schema
schema=Decision.model_json_schema()
schema['properties']={'findings':schema['properties']['findings']}
assert attendance_schema(schema,[0],['attendance'],[])==schema
@pytest.mark.parametrize('text',[
'完成了大连、沈阳等20余项任务的定稿。',
'已完成报名,需核实是否因迟到影响报名。',
'未见具体分析内容,履职深度不足。',
'任务12735未完成。',
])
def test_expanded_analysis_does_not_invent_counts_or_unsupported_deficiencies(text):
from app.modules.work_assistant.personnel_profile import unsupported_work_claim
assert unsupported_work_claim(text,'本人反馈:大连项目标书定稿。')
def test_missing_duties_fit_describes_task_results_not_ability():
entry,result=fixture()
entry.evidence=[e for e in entry.evidence if e.kind!='duty']
result['findings'][4]['basis']=result['findings'][4]['basis'][:1]
result['findings'][1].update(status='attention',headline='具备测试报告编制能力')
with pytest.raises(ValueError,match='任务执行及交付质量'):
validate(entry,result)
def test_unread_attachments_do_not_replace_the_work_assessment():
entry,result=fixture()
entry.evidence=[e for e in entry.evidence if e.kind!='duty']
result['findings'][4]['basis']=result['findings'][4]['basis'][:1]
result['findings'][1].update(status='attention',headline='交付质量待核实',finding='附件无法读取,正文未提取,无法核实验收状态。')
with pytest.raises(ValueError,match='不能用附件无法读取替代'):
validate(entry,result)
def test_empty_period_returns_honest_content_without_invented_model_citations():
from app.modules.work_assistant.personnel_profile import review_profile
entry,_=fixture();entry.evidence=[]
def never(*args,**kwargs):raise AssertionError('Empty records must not call the model')
result=review_profile(entry,invoke=never)
assert result['assessment_scope']=='tasks'
assert all(not row['basis'] for row in result['findings'])
assert result['findings'][1]['status']=='insufficient'
@pytest.mark.parametrize('phrase',['任务均登记完成。','任务完成登记。','系统登记状态为完成。'])
def test_feedback_alone_cannot_be_presented_as_system_completion(phrase):
entry,result=fixture()
result['findings'][0]['finding']=phrase
with pytest.raises(ValueError,match='登记完成须引用'):
validate(entry,result)
@pytest.mark.parametrize('state',['complete','unfinished'])
def test_registered_completion_links_actual_task_record_without_inventing_its_state(state):
from copy import deepcopy
from app.modules.work_assistant.personnel_profile import attach_task_basis,material,Evidence
entry,result=fixture();entry.evidence[1].task_id='T'
entry.evidence.append(Evidence(id='task',kind='task',subject='报告',actor_id='',at='',relation='requirement',
task_id='T',state=state,content='当前状态:'+('登记完成' if state=='complete' else '尚未登记完成')))
entry.evidence.append(Evidence(id='unrelated',kind='task',subject='另一份报告',actor_id='',at='',relation='requirement',
task_id='U',state='complete',content='当前状态:登记完成'))
result['findings'][0]['finding']='报告任务登记完成。'
original=deepcopy(result);_,excerpts=material(entry)
linked=attach_task_basis(result,entry,excerpts)
assert result==original
assert {ref['evidence_id'] for ref in linked['findings'][0]['basis']}=={'work','task'}
if state=='complete':assert validate(entry,linked)['findings'][0]['finding']=='报告任务登记完成。'
else:
with pytest.raises(ValueError,match='登记完成须引用'):
validate(entry,linked)
@pytest.mark.parametrize('key,summary',[
('recent','本周成果合格率100%,综合评估扣0.5%。'),
('development','本周完成率100%,适合承担流程统筹。'),
('fit','学习任务与周目标职责性质不同,不能混淆。'),
])
def test_business_summary_does_not_publish_statistics_or_repair_explanations(key,summary):
entry,result=fixture()
next(row for row in result['findings'] if row['key']==key)['finding']=summary
with pytest.raises(ValueError,match=key+':'):
validate(entry,result)
def test_internal_reference_adjacent_to_chinese_is_rejected():
entry,result=fixture()
result['findings'][4]['finding']='建议负责报告修订,对应职责e17,由主管复核。'
with pytest.raises(ValueError,match='内部规则或编号'):
validate(entry,result)
def test_parenthetical_internal_citation_is_removed_without_losing_business_content():
from app.modules.work_assistant.personnel_profile import normalize_scope
entry,result=fixture()
result['findings'][4]['finding']='建议负责报告修订(对应职责e17),提交修订稿由主管复核。'
normalized=normalize_scope(result,True)
assert normalized['findings'][4]['finding']=='建议负责报告修订,提交修订稿由主管复核。'
assert normalized['findings'][4]['basis']==result['findings'][4]['basis']
validate(entry,normalized)
def test_long_inspection_text_remains_generatable_in_a_concise_response_row():
from app.modules.work_assistant.personnel_profile import linked_schema
schema=generation_schema(Decision.model_json_schema(),2,2,True)
review=dict(review='e1',record='检查发现材料缺失,需补充原始记录。'*8,responses=[],refs=['e1'])
output=linked_schema(schema,[],[review])
props=output['properties']['responses']['prefixItems'][0]['properties']
assert props['record']['enum'][0]==review['record'][:160]
assert len(props['record']['enum'][0])<=props['record']['maxLength']
def test_focused_repair_preserves_quoted_text_without_unrelated_passages():
from app.modules.work_assistant.personnel_profile import trim_shared_text
data={'evidence':[['e1','@t1']], 'shared_text':{'@t1':'已提交谈话记录','@t2':'另一个任务台账未更新'}}
assert trim_shared_text(data)['shared_text']=={'@t1':'已提交谈话记录'}
def test_repair_can_find_actual_work_beyond_a_rejected_citation():
from app.modules.work_assistant.personnel_profile import material,pack_material,cited_material
entry,_=fixture()
data,excerpts=material(entry)
data=pack_material(data)
candidate={section:[] for section in ('findings',)+DETAIL_SECTIONS}
candidate['findings']=[{'basis':[{'evidence_id':'duty','quote':entry.evidence[0].content}]}]
assert len(cited_material(data,candidate,excerpts)['evidence'])==1
assert len(cited_material(data,candidate,excerpts,related=True)['evidence'])==2
@pytest.mark.parametrize('gateway', [False, True])
def test_personnel_stop_boundary_preserves_json_validation(monkeypatch, gateway):
import json
from types import SimpleNamespace
import httpx
from app.modules.work_assistant import model_gateway as model
settings=SimpleNamespace(work_assistant_model_enabled=True,
work_assistant_model_control_url='http://model.invalid' if gateway else '',
work_assistant_model_control_api_key='', direct_llm_api_key='test',
direct_llm_model='test', direct_llm_base_url='http://model.invalid/v1')
monkeypatch.setattr(model,'get_settings',lambda:settings)
answer={'content':'{"value": "complete"}'}
finish={'reason':'stop'}
def post(*args, **kwargs):
assert kwargs['json']['stop']==['\n```']
return httpx.Response(200,json={'choices':[{'finish_reason':finish['reason'],'message':dict(answer)}]})
monkeypatch.setattr(model,'_model_client',lambda:SimpleNamespace(post=post))
assert model._complete_json('one object',{},stop=['\n```'])=={'value':'complete'}
answer['content']='{"value":'
with pytest.raises(json.JSONDecodeError):
model._complete_json('one object',{},stop=['\n```'])
finish['reason']='length'
answer['content']='{"value":"complete"}\n```json\n{"value":'
assert model._complete_json('one object',{},stop=['\n```'],single_object=True)=={'value':'complete'}
with pytest.raises(model.ModelUnavailable,match='output_truncated'):
model._complete_json('one object',{},stop=['\n```'])
answer['content']='{"value":'
with pytest.raises(model.ModelUnavailable,match='output_truncated'):
model._complete_json('one object',{},stop=['\n```'],single_object=True)