fix(dsh): isolate protocol errors and publish metadata atomically
This commit is contained in:
1 parent
0bc1f64edc
commit
dfbc14c081
6 files changed
+189
-26
No files matched your search
@@ -1,4 +1,7 @@
|
||||
from dx_productivity.dsh.provider_config import load_provider, save_provider
|
||||
import json
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
|
||||
def test_provider_key_is_encrypted_and_models_survive_reload(tmp_path):
|
||||
@@ -10,3 +13,52 @@ def test_provider_key_is_encrypted_and_models_survive_reload(tmp_path):
|
||||
assert restored['DSH_API_KEY'] == key
|
||||
assert restored['DSH_MODEL'] == 'b'
|
||||
assert restored['DSH_API_BASE'] == 'https://example.test/v1'
|
||||
|
||||
|
||||
def test_metadata_replace_failure_preserves_existing_json(tmp_path,monkeypatch):
|
||||
from dx_productivity.dsh import provider_config
|
||||
values=dict(base_url='https://example.test/v1',models=['old'],default_model='old',api_key='local-test-key')
|
||||
save_provider(tmp_path,**values)
|
||||
metadata=tmp_path/'provider.json';original=metadata.read_bytes()
|
||||
replace=provider_config.os.replace
|
||||
def fail_metadata(source,target):
|
||||
if Path(target)==metadata:
|
||||
assert metadata.read_bytes()==original
|
||||
assert json.loads(Path(source).read_text(encoding='utf8'))['default_model']=='新模型'
|
||||
raise OSError('Controlled interruption before metadata publication')
|
||||
return replace(source,target)
|
||||
monkeypatch.setattr(provider_config.os,'replace',fail_metadata)
|
||||
with pytest.raises(OSError,match='Controlled interruption'):
|
||||
save_provider(tmp_path,**(values|{'models':['新模型'],'default_model':'新模型'}))
|
||||
assert metadata.read_bytes()==original
|
||||
assert load_provider(tmp_path)['DSH_MODEL']=='old'
|
||||
assert not list(tmp_path.glob('provider.json*.tmp'))
|
||||
|
||||
|
||||
def test_metadata_flush_failure_preserves_existing_json(tmp_path,monkeypatch):
|
||||
from dx_productivity.dsh import provider_config
|
||||
values=dict(base_url='https://example.test/v1',models=['old'],default_model='old',api_key='local-test-key')
|
||||
save_provider(tmp_path,**values)
|
||||
metadata=tmp_path/'provider.json';original=metadata.read_bytes()
|
||||
def fail_flush(fd):raise OSError('Controlled metadata flush failure')
|
||||
monkeypatch.setattr(provider_config.os,'fsync',fail_flush)
|
||||
with pytest.raises(OSError,match='Controlled metadata flush failure'):
|
||||
save_provider(tmp_path,**(values|{'models':['new'],'default_model':'new'}))
|
||||
assert metadata.read_bytes()==original
|
||||
assert not list(tmp_path.glob('provider.json*.tmp'))
|
||||
|
||||
|
||||
def test_partial_metadata_write_never_truncates_published_json(tmp_path,monkeypatch):
|
||||
from dx_productivity.dsh import provider_config
|
||||
values=dict(base_url='https://example.test/v1',models=['old'],default_model='old',api_key='local-test-key')
|
||||
save_provider(tmp_path,**values)
|
||||
metadata=tmp_path/'provider.json';original=metadata.read_bytes()
|
||||
def incomplete_dump(value,stream,**kwargs):
|
||||
stream.write('{"base_url":')
|
||||
raise OSError('Controlled partial metadata write')
|
||||
monkeypatch.setattr(provider_config.json,'dump',incomplete_dump)
|
||||
with pytest.raises(OSError,match='Controlled partial metadata write'):
|
||||
save_provider(tmp_path,**(values|{'models':['new'],'default_model':'new'}))
|
||||
assert metadata.read_bytes()==original
|
||||
assert load_provider(tmp_path)['DSH_MODEL']=='old'
|
||||
assert not list(tmp_path.glob('provider.json*.tmp'))
|
||||
@@ -77,6 +77,7 @@ def test_last_failed_item_keeps_stop_intent_in_automatic_diagnosis(ui,qtbot,monk
|
||||
|
||||
|
||||
class ProtocolSignals(QWidget):
|
||||
ready=Signal()
|
||||
task_creation_requested=Signal(object)
|
||||
diagnosis_event=Signal(object)
|
||||
task_creation_cancelled=Signal(object)
|
||||
@@ -90,6 +91,7 @@ def protocol_state(qtbot):
|
||||
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,
|
||||
context={'task_id':'t','revision':'rev'},last_error='')
|
||||
state._reset_output=lambda:NativeHarnessView._reset_output(state)
|
||||
@@ -192,3 +194,50 @@ def test_stderr_preserves_utf8_across_process_chunks(qtbot):
|
||||
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)
|
||||
state.web=SimpleNamespace(page=lambda:page,load=loaded.append)
|
||||
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 [url.toString()for url in loaded]==['http://127.0.0.1:12345/']
|
||||
Reference in new issue
Block a user