Core regression / Python core and release configuration (push) Successful in 20s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python core and release configuration (pull_request) Successful in 15s
Core regression / JavaScript syntax (pull_request) Successful in 3s
281 lines
14 KiB
Python
281 lines
14 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
|
|
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
|
|
window=ui.window;task=ui.tasks[0]
|
|
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
|
|
state='batch_failed'if len(calls)<=failure_count else'no_match'
|
|
with (Path(command[3])/'status.tsv').open('a',encoding='utf8')as stream:
|
|
stream.write(f'{command[-1]}\t{state}\tbatch_closed\tControlled result\n')
|
|
return subprocess.CompletedProcess(command,0,'','')
|
|
# 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
|
|
monkeypatch.setattr(dsh_automation.QApplication,'platformName',lambda:'review-test')
|
|
monkeypatch.setattr(automation,'_analyze',lambda *args:{'reply':json.dumps({'summary':'Retry suggestion','action':'retry_failed'})})
|
|
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
|
|
qtbot.waitUntil(lambda:automation.worker is None and
|
|
automation.latest.get('status')in {'resolved','pending_issue','escalated'},timeout=10000)
|
|
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']
|
|
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()
|
|
qtbot.waitUntil(lambda:automation.worker is None and
|
|
automation.latest.get('run_id')!=original_run and
|
|
automation.latest.get('status')=='resolved',timeout=10000)
|
|
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(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')
|
|
monkeypatch.setattr(dsh_native,'launch_environment',lambda *args:{})
|
|
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/']
|