Files
dxdesigner-part-replacement/tests/ui/test_pr10_review_edges.py
T
阿白叔 f8f07d30d2
Core regression / Python core, intervention UI and release configuration (push) Failing after 2m42s
Core regression / JavaScript syntax (push) Successful in 6s
Core regression / Python core, intervention UI and release configuration (pull_request) Canceled after 1m17s
Core regression / JavaScript syntax (pull_request) Canceled after 0s
merge(main): resolve PR19 review conflicts and run intervention regressions in CI
2026-11-09 11:35:29 +08:00

316 lines
16 KiB
Python

"""Exercise PR #10 review boundaries through the real service and protocol parser."""
import json
from pathlib import Path
import subprocess
from threading import Event
from types import SimpleNamespace
import pytest
pytestmark = pytest.mark.usefixtures('ai_ready')
from PySide6.QtCore import Signal
from PySide6.QtWidgets import QMessageBox,QWidget
def test_project_plan_discard_is_safe_after_qt_reclaims_report_control(ui, qtbot):
"""Fixture cleanup must tolerate a child control reclaimed during window teardown."""
import shiboken6
report_toggle = ui.window.plan_panel.report_toggle
shiboken6.delete(report_toggle)
ui.window.plan_panel.discard_all()
@pytest.mark.parametrize('scope',['single','batch'])
@pytest.mark.parametrize('stop_kind',['none','pause','force','pause_then_reauthorize'])
def test_last_failed_item_keeps_stop_intent_in_automatic_diagnosis(ui,qtbot,monkeypatch,scope,stop_kind):
from dx_productivity.trial_task_center.ui import dsh_automation
from dx_productivity.trial_task_center import task_queue
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow
from dx_productivity.dsh import execution_runs
ui.settle()
window=ui.window;task=ui.tasks[0]
project = ui.service.projects(task.task_id)[0].path
target = ComponentTarget(project, 'MAIN', '1', 'controlled-uid', 'R1', 'OLD', '10K')
ui.store.record_target_inventory(task.task_id, (target,))
ui.store.replace_target_plan(task.task_id, (TargetPlanRow(target, True, 'NEW'),))
ui.open(task)
ui.settle()
window._tasks=(task,)
window._quick_run_confirmer=lambda *args:True
window._update_gates()
calls=[];outcomes=[];controls=[]
def executor(command,timeout):
calls.append(command[-1])
if len(calls)==1:
controls.append(window._batch_stop)
if stop_kind in {'pause','pause_then_reauthorize'}:window._pause_queue()
elif stop_kind=='force':window._force_batch_stop()
failure_count=2 if stop_kind=='pause_then_reauthorize'else 1
if len(calls)<=failure_count:
return subprocess.CompletedProcess(command,2,'','Controlled prewrite attachment failure')
with (Path(command[3])/'status.tsv').open('a',encoding='utf8')as stream:
stream.write(f'{command[-1]}\tno_match\tbatch_closed\tControlled result\n')
return subprocess.CompletedProcess(command,0,'','')
execute_queue = task_queue.execute_task_queue
def primary_pass(*args, **kwargs):
# Leave the one safe component replay to DSH so this tests its stop handoff.
kwargs['defer_problem_pass'] = True
return execute_queue(*args, **kwargs)
monkeypatch.setattr(task_queue, 'execute_task_queue', primary_pass)
monkeypatch.setattr(execution_runs, 'execute_task_queue', primary_pass)
# Keep the real service, queue, persistence, IncidentRunner and Qt handoff;
# replace only external CAD/model/issue transports and background dispatch.
monkeypatch.setattr(ui.service.for_project_task(task.task_id)._quick_run_preparer,'_process_runner',executor)
monkeypatch.setattr(QMessageBox,'question',lambda *args:QMessageBox.StandardButton.Yes)
def dispatch(operation,callback,*args,**kwargs):
result=operation();outcomes.append(result);callback(result)
monkeypatch.setattr(window,'_run_async',dispatch)
monkeypatch.setattr(window,'_open_dsh',lambda:None)
automation=dsh_automation.DshAutomation(window)
window._dsh_automation=automation
analyzed = Event()
def analyze(*args):
analyzed.set()
return {'reply':json.dumps({'summary':'Retry suggestion','action':'retry_failed'})}
monkeypatch.setattr(automation,'_analyze',analyze)
def wait_for_diagnosis(previous_run=None):
def finished():
record = automation.latest
assert (analyzed.is_set() and automation.worker is None and
record.get('status') in {'resolved','pending_issue','escalated'} and
(previous_run is None or record.get('run_id') != previous_run and
record.get('status') == 'resolved')), (
f'{scope}/{stop_kind}: worker={automation.worker!r}, pending={automation.pending!r}, '
f'latest={record!r}, loading={window._loading}, workers={window._workers!r}, '
f'context_busy={window._context_query.busy}, operations_busy={window._dsh_operations.busy}, '
f'readiness={window._dsh_status.availability!r}')
qtbot.waitUntil(finished,timeout=10000)
monkeypatch.setattr(dsh_automation,'GitIssuePublisher',lambda *args:lambda *args:{'status':'unavailable'})
if scope=='single':window._prepare_quick_run()
else:window._execute_project_tasks()
assert len(outcomes)==1
# This is the review's edge: the queue is exhausted, so paused is False
# even though the original control may carry a stop/force request.
# DSH persists a receipt for single runs and returns (queue, receipt) for
# grouped runs. Observe the real result without replacing its executor.
result = outcomes[0][0] if isinstance(outcomes[0], tuple) else outcomes[0]
assert (result['paused'] if isinstance(result, dict) else result.paused) is False
wait_for_diagnosis()
ui.settle()
record=automation.latest
assert len(calls)==(2 if stop_kind=='none'else 1)
assert record['gates']['not_stopped']is (stop_kind=='none')
assert record['attempts']==(1 if stop_kind=='none'else 0)
if stop_kind=='force':assert controls[0].force_event.is_set()
if stop_kind!='none':
assert controls[0].is_set()
assert not list((ui.data/'dsh/retry-budget').glob('*.json'))
if stop_kind=='pause_then_reauthorize':
original_run=record['run_id']
analyzed.clear()
window._retry_failed();ui.settle()
window._tasks=(ui.service.get_task(task.task_id),)
window._update_gates()
if scope=='single':window._prepare_quick_run()
else:window._execute_project_tasks()
wait_for_diagnosis(original_run)
ui.settle()
assert len(calls)==3
assert automation.latest['gates']['not_stopped']
assert controls[0].is_set() # New authorization never clears old intent.
class ProtocolSignals(QWidget):
ready=Signal()
task_creation_requested=Signal(object)
diagnosis_event=Signal(object)
task_creation_cancelled=Signal(object)
action_requested=Signal(object)
lifecycle_requested=Signal(object)
lifecycle_cancelled=Signal(object)
def protocol_state(qtbot):
from dx_productivity.trial_task_center.ui.dsh_native import NativeHarnessView
sink=ProtocolSignals();qtbot.addWidget(sink)
chunks=[]
state=SimpleNamespace(_signal_owner=sink,
process=SimpleNamespace(readAllStandardOutput=lambda:chunks.pop(0)),
task_creation_requested=sink.task_creation_requested,diagnosis_event=sink.diagnosis_event,
ready=sink.ready,
task_creation_cancelled=sink.task_creation_cancelled,action_requested=sink.action_requested,
lifecycle_requested=sink.lifecycle_requested,lifecycle_cancelled=sink.lifecycle_cancelled,
context={'task_id':'t','revision':'rev'},last_error='')
state._reset_output=lambda:NativeHarnessView._reset_output(state)
state._reset_output()
return state,chunks
@pytest.mark.parametrize('prefix,signal', [('DX_DSH_LIFECYCLE_REQUEST', 'lifecycle_requested'),
('DX_DSH_LIFECYCLE_CANCEL', 'lifecycle_cancelled')])
def test_lifecycle_protocol_survives_invalid_lines_and_split_utf8(qtbot, prefix, signal):
from dx_productivity.trial_task_center.ui.dsh_native import NativeHarnessView
state,chunks=protocol_state(qtbot)
received=[]
getattr(state,signal).connect(received.append)
payload={'request_id':'b'*32,'spec':{'operation':'reconcile_schedule','title':'核对排期🔧'}}
invalid=(prefix+' {invalid private-diagnostic\n'+prefix+' []\n').encode('utf8')
valid=(prefix+' '+json.dumps(payload,ensure_ascii=False)+'\n').encode('utf8')
split=valid.index('核'.encode('utf8'))+1
chunks.extend([invalid+valid[:split],valid[split:]])
NativeHarnessView._stdout(state)
assert not received
NativeHarnessView._stdout(state)
assert received==[payload]
assert 'private-diagnostic' not in state.last_error
@pytest.mark.parametrize('stop_kind',['none','pause','force'])
def test_worker_exception_handoff_keeps_original_run_control(ui,qtbot,monkeypatch,stop_kind):
from dx_productivity.trial_task_center.errors import TaskCenterError
window=ui.window;task_id=window._task_id
captured=[]
window._dsh_automation=SimpleNamespace(can_cancel=False,cancel=lambda:None,
enqueue=lambda *args,**kwargs:captured.append(kwargs)or True)
window._dsh_authorized_tasks.add(task_id)
window._begin_run(task_id)
control=window._batch_stop;run_id=window._dsh_run_id
started,release=Event(),Event()
def fail():
started.set()
assert release.wait(5)
raise TaskCenterError('worker_error','Controlled final-step failure')
monkeypatch.setattr(QMessageBox,'question',lambda *args:QMessageBox.StandardButton.Yes)
try:
window._run_async(fail,lambda _:None,expected_task_id=task_id)
qtbot.waitUntil(started.is_set)
if stop_kind=='pause':window._pause_queue()
elif stop_kind=='force':window._force_batch_stop()
finally:
release.set()
ui.settle()
assert len(captured)==1
assert captured[0]['stop_event'] is control
assert captured[0]['stop_event'].is_set()is (stop_kind!='none')
assert captured[0]['execution_authorized']
assert captured[0]['run_id']==run_id
def test_protocol_preserves_utf8_at_every_byte_boundary(qtbot):
from dx_productivity.trial_task_center.ui.dsh_native import NativeHarnessView
state,chunks=protocol_state(qtbot)
received=[];state.task_creation_requested.connect(received.append)
payload={'request_id':'a'*32,'spec':{'name':'电阻替换🔧','directory_hint':'C:/工程/主板',
'rules':[{'old_part_number':'旧料号','new_part_number':'新料号','custom_value':'电容值μF'}]}}
line=('DX_DSH_CREATE_REQUEST '+json.dumps(payload,ensure_ascii=False)+'\n').encode('utf8')
# Includes splits inside each Chinese character, the emoji and JSON syntax.
for split in range(1,len(line)):
chunks.append(line[:split]);NativeHarnessView._stdout(state)
chunks.append(line[split:]);NativeHarnessView._stdout(state)
assert received[-1]==payload
assert len(received)==len(line)-1
def test_protocol_preserves_multiple_event_lines_in_single_byte_chunks(qtbot):
from dx_productivity.trial_task_center.ui.dsh_native import NativeHarnessView
state,chunks=protocol_state(qtbot)
received=[];state.diagnosis_event.connect(received.append)
values=[{'reply':'诊断结论:电阻值正常'},{'reply':'复盘:无需替换'}]
stream=''.join('DX_DSH_DIAGNOSIS '+json.dumps(v,ensure_ascii=False)+'\n'for v in values).encode('utf8')
for byte in stream:
chunks.append(bytes([byte]));NativeHarnessView._stdout(state)
assert received==values
def test_runtime_restart_discards_partial_protocol_and_utf8_characters(qtbot,tmp_path,monkeypatch):
from dx_productivity.trial_task_center.ui import dsh_native
state,chunks=protocol_state(qtbot)
received=[];state.task_creation_requested.connect(received.append)
old=('DX_DSH_CREATE_REQUEST '+json.dumps({'name':'旧请求'},ensure_ascii=False)+'\n').encode('utf8')
chunks.append(old[:old.index('旧'.encode('utf8'))+1]);dsh_native.NativeHarnessView._stdout(state)
assert not received
state.process.readAllStandardError=lambda:'电'.encode('utf8')[:1]
dsh_native.NativeHarnessView._stderr(state)
for method in ('setProcessEnvironment','setWorkingDirectory','setProgram','setArguments','start'):
setattr(state.process,method,lambda *args:None)
state.is_running=False
state.data_root=tmp_path
state.status=SimpleNamespace(setText=lambda *args:None,show=lambda:None,hide=lambda:None)
state._show_official_loading=lambda root:None
state.retry=SimpleNamespace(hide=lambda:None)
state.timeout=SimpleNamespace(start=lambda *args:None)
package=tmp_path/'node_modules/@deepseek-ai/dsh/package.json'
package.parent.mkdir(parents=True);package.write_text('{}')
monkeypatch.setattr(dsh_native,'integration_root',lambda:tmp_path)
monkeypatch.setattr(dsh_native,'node_executable',lambda:'test-node')
state.window=lambda:None
monkeypatch.setattr(dsh_native,'launch_environment',lambda *args,**kwargs:{})
dsh_native.NativeHarnessView.start(state)
new={'name':'新请求'}
chunks.append(('DX_DSH_CREATE_REQUEST '+json.dumps(new,ensure_ascii=False)+'\n').encode('utf8'))
dsh_native.NativeHarnessView._stdout(state)
assert received==[new]
state.process.readAllStandardError=lambda:'正常'.encode('utf8')
dsh_native.NativeHarnessView._stderr(state)
assert state.last_error=='正常'
def test_stderr_preserves_utf8_across_process_chunks(qtbot):
from dx_productivity.trial_task_center.ui.dsh_native import NativeHarnessView
state,chunks=protocol_state(qtbot)
state.process.readAllStandardError=lambda:chunks.pop(0)
message='运行时诊断:电阻替换🔧'
for byte in message.encode('utf8'):
chunks.append(bytes([byte]));NativeHarnessView._stderr(state)
assert state.last_error==message
@pytest.mark.parametrize('prefix',['READY','DIAGNOSIS','CREATE_REQUEST','CREATE_CANCEL','ACTION'])
@pytest.mark.parametrize('invalid',['{broken JSON','null','[]','"wrong shape"'])
def test_bad_protocol_line_preserves_following_valid_messages(qtbot,prefix,invalid):
from dx_productivity.trial_task_center.ui.dsh_native import NativeHarnessView
state,chunks=protocol_state(qtbot)
requests=[];diagnoses=[]
state.task_creation_requested.connect(requests.append)
state.diagnosis_event.connect(diagnoses.append)
valid={'request_id':'a'*32,'spec':{'name':'电阻替换'}}
diagnostic={'reply':'后续诊断正常'}
first='DX_DSH_CREATE_REQUEST '+json.dumps(valid,ensure_ascii=False)+'\n'
last='DX_DSH_DIAGNOSIS '+json.dumps(diagnostic,ensure_ascii=False)+'\n'
chunks.append((first+f'DX_DSH_{prefix} {invalid}\n'+last).encode('utf8'))
NativeHarnessView._stdout(state)
assert requests==[valid]
assert diagnoses==[diagnostic]
assert 'DSH protocol'in state.last_error
assert invalid not in state.last_error # Never persist the raw malformed payload.
@pytest.mark.parametrize('payload',[{}, {'url':None}, {'url':[]}])
def test_incomplete_ready_line_does_not_drop_later_diagnosis(qtbot,payload):
from dx_productivity.trial_task_center.ui.dsh_native import NativeHarnessView
state,chunks=protocol_state(qtbot)
diagnoses=[];state.diagnosis_event.connect(diagnoses.append)
chunks.append(('DX_DSH_READY '+json.dumps(payload)+'\nDX_DSH_DIAGNOSIS {"status":"completed"}\n').encode('utf8'))
NativeHarnessView._stdout(state)
assert diagnoses==[{'status':'completed'}]
def test_bad_line_does_not_block_following_local_runtime_handshake(qtbot):
from dx_productivity.trial_task_center.ui.dsh_native import NativeHarnessView
state,chunks=protocol_state(qtbot)
loaded=[];ready=[]
page=SimpleNamespace(allowed_port=None)
settings_calls=[]
state.web=SimpleNamespace(page=lambda:page,load=loaded.append,
settings=lambda:SimpleNamespace(setAttribute=lambda *args:settings_calls.append(args)))
state.timeout=SimpleNamespace(stop=lambda:None)
state.status=SimpleNamespace(hide=lambda:None)
state._diagnosis_queue=[]
state.ready.connect(lambda:ready.append(True))
chunks.append(b'DX_DSH_CREATE_REQUEST {bad}\nDX_DSH_READY {"url":"http://127.0.0.1:12345/"}\n')
NativeHarnessView._stdout(state)
assert state._started and ready==[True]
assert page.allowed_port==12345
assert settings_calls[-1][1] is False
assert [url.toString()for url in loaded]==['http://127.0.0.1:12345/']