Merge pull request 'fix: DxDataBook 写入前加载、超时证据与有限重试(#33 D6)' (#37) from codex/issue33-d6 into main
This commit was merged in pull request #37.
This commit is contained in:
commit
c114db9f31
12 files changed
+802
-29
No files matched your search
@@ -0,0 +1,175 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.trial_task_center import native_helper as native
|
||||
from dx_productivity.trial_task_center.batch_attempt import prepare_attempt, read_attempt
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def attempt(tmp_path, monkeypatch):
|
||||
job = 'job'
|
||||
project = tmp_path / 'board.prj'
|
||||
record_path = tmp_path / 'attempt.json'
|
||||
snapshot = tmp_path / f'snapshot-{job}.tsv'
|
||||
snapshot.write_text(f'M\t{project}\tOLD\tNEW\tMAIN:1\nC\tuid\tR1\t0\t0\t0\t1\t\n', encoding='utf-8')
|
||||
(tmp_path / 'command.tsv').write_text(
|
||||
f'job_id\ttask_id\tproject_path\n{job}\ttask\t{project}\n', encoding='utf-8')
|
||||
record = prepare_attempt(record_path, session_id='session', generation=1,
|
||||
job_id=job, task_id='task', project_path=project)
|
||||
for name, value in {
|
||||
'DXPART_DESKTOP': 'dx-test',
|
||||
'DXPART_ATTEMPT_FILE': record_path,
|
||||
'DXPART_ATTEMPT_ID': record['attempt_id'],
|
||||
'DXPART_BATCH_GENERATION': record['generation'],
|
||||
'DXPART_BATCH_SESSION_ID': record['session_id'],
|
||||
}.items():
|
||||
monkeypatch.setenv(name, str(value))
|
||||
return snapshot, record_path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def clock(monkeypatch):
|
||||
now = [0.]
|
||||
monkeypatch.setattr(native, 'time', SimpleNamespace(
|
||||
monotonic=lambda: now[0], sleep=lambda seconds: now.__setitem__(0, now[0] + seconds)))
|
||||
return now
|
||||
|
||||
|
||||
def test_cold_list_recreation_reapplies_filter_and_uses_the_new_handle(attempt, clock):
|
||||
snapshot, record = attempt
|
||||
report, filtered = {}, []
|
||||
browsing = False
|
||||
|
||||
def browse():
|
||||
nonlocal browsing
|
||||
browsing = True
|
||||
|
||||
def controls():
|
||||
if browsing:
|
||||
return (10, 11) if clock[0] < .3 else (20, 21)
|
||||
return None
|
||||
|
||||
list_handle, rows = native.load_databook_target(snapshot, report, 'NEW',
|
||||
controls=controls, browse=browse, filter_part=lambda handle: filtered.append(handle),
|
||||
list_rows=lambda handle: [(handle, ['GATE', 'NEW', 'lib:SYM'])],
|
||||
dialogs=lambda: (), close_dialog=lambda handle: pytest.fail('unexpected close'))
|
||||
assert (list_handle, rows[0][0], filtered) == (20, 20, [11, 21])
|
||||
assert report['databook']['loads'][0]['mode'] == 'cold'
|
||||
assert read_attempt(record)['state'] == 'prepared'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('during', ['filter', 'rows'])
|
||||
def test_control_destroyed_between_discovery_and_access_is_reacquired(attempt, clock, during):
|
||||
snapshot, record = attempt
|
||||
state = {'controls': (10, 11)}
|
||||
visited = []
|
||||
|
||||
def destroyed():
|
||||
state['controls'] = (20, 21)
|
||||
error = OSError('stale DxDataBook control')
|
||||
if during == 'filter':
|
||||
error.winerror = 1400
|
||||
else:
|
||||
error.hresult = -2147220991
|
||||
raise error
|
||||
|
||||
def filter_part(handle):
|
||||
visited.append(handle)
|
||||
if during == 'filter' and handle == 11:
|
||||
destroyed()
|
||||
|
||||
def rows(handle):
|
||||
if during == 'rows' and handle == 10:
|
||||
destroyed()
|
||||
return [(handle, ['GATE', 'NEW', 'lib:SYM'])]
|
||||
|
||||
report = {}
|
||||
handle, _ = native.load_databook_target(snapshot, report, 'NEW',
|
||||
controls=lambda: state['controls'], browse=lambda: None, filter_part=filter_part,
|
||||
list_rows=rows, dialogs=lambda: (), close_dialog=lambda _: pytest.fail('unexpected close'))
|
||||
assert handle == 20 and visited == [11, 21]
|
||||
assert len(report['databook']['loads']) == 1
|
||||
assert read_attempt(record)['state'] == 'prepared'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('already_written', [False, True])
|
||||
def test_timeout_reissues_filter_once_only_with_bound_prepared_attempt(attempt, clock, already_written):
|
||||
snapshot, record = attempt
|
||||
if already_written:
|
||||
native.mark_snapshot_mutation(snapshot)
|
||||
report, filters = {}, []
|
||||
|
||||
def run():
|
||||
return native.load_databook_target(snapshot, report, 'NEW',
|
||||
controls=lambda: (10, 11), browse=lambda: None,
|
||||
filter_part=lambda handle: filters.append(handle), list_rows=lambda handle: [],
|
||||
dialogs=lambda: (), close_dialog=lambda handle: pytest.fail('unexpected close'))
|
||||
|
||||
with pytest.raises(TimeoutError, match='DxDataBook'):
|
||||
run()
|
||||
loads = report['databook']['loads']
|
||||
assert [load['mode'] for load in loads] == ['warm'] * (1 if already_written else 2)
|
||||
assert len(filters) == len(loads)
|
||||
assert read_attempt(record)['state'] == ('mutation_possible' if already_written else 'prepared')
|
||||
|
||||
|
||||
def test_retry_closes_only_new_owned_empty_dialog_and_persists_evidence_first(attempt, clock):
|
||||
snapshot, record = attempt
|
||||
report, closed = {}, []
|
||||
blank = {'hwnd': 19, 'owner': 7, 'title': '', 'children': [], 'dismissible': True}
|
||||
previous = dict(blank, hwnd=18)
|
||||
named = dict(blank, hwnd=20, title='Save', dismissible=False)
|
||||
|
||||
def dialogs():
|
||||
return [previous, named] if clock[0] == 0 else [previous, blank, named]
|
||||
|
||||
def close(row):
|
||||
import json
|
||||
|
||||
evidence = json.loads(snapshot.with_suffix('.tsv.native.json').read_bytes())
|
||||
assert evidence['databook']['loads'][0]['dialogs'][0]['hwnd'] == 19
|
||||
assert evidence['databook']['loads'][0]['attempt_state'] == 'prepared'
|
||||
closed.append(row['hwnd'])
|
||||
|
||||
native.load_databook_target(snapshot, report, 'NEW',
|
||||
controls=lambda: (10, 11), browse=lambda: None, filter_part=lambda handle: None,
|
||||
list_rows=lambda handle: [(handle, ['GATE', 'NEW', 'lib:SYM'])] if closed else [],
|
||||
dialogs=dialogs, close_dialog=close)
|
||||
assert closed == [19]
|
||||
assert len(report['databook']['loads']) == 2
|
||||
assert read_attempt(record)['state'] == 'prepared'
|
||||
|
||||
|
||||
def test_named_or_unowned_prompt_keeps_operator_handling(attempt, clock):
|
||||
snapshot, _ = attempt
|
||||
report = {}
|
||||
with pytest.raises(TimeoutError, match='DxDataBook'):
|
||||
native.load_databook_target(snapshot, report, 'NEW',
|
||||
controls=lambda: (10, 11), browse=lambda: None, filter_part=lambda handle: None,
|
||||
list_rows=lambda handle: [],
|
||||
dialogs=lambda: [{'hwnd': 20, 'dismissible': False}] if clock[0] else [],
|
||||
close_dialog=lambda row: pytest.fail('unrecognized prompt was closed'))
|
||||
assert len(report['databook']['loads']) == 1
|
||||
|
||||
|
||||
def test_dialog_fingerprint_requires_same_owner_pid_thread_and_empty_controls(monkeypatch):
|
||||
from dx_productivity.trial_task_center import cad_dialogs
|
||||
|
||||
owner, pid = 7, 8
|
||||
windows = {10: (1, pid, owner), 11: (1, pid, 99), 12: (2, pid, owner),
|
||||
13: (1, 99, owner), 14: (1, pid, owner), owner: (1, pid, 99)}
|
||||
monkeypatch.setattr(cad_dialogs, '_text', lambda hwnd: '')
|
||||
gui = SimpleNamespace(
|
||||
error=RuntimeError, IsWindowVisible=lambda hwnd: True, IsWindowEnabled=lambda hwnd: False,
|
||||
EnumWindows=lambda callback, _: [callback(hwnd, None) for hwnd in windows],
|
||||
GetWindow=lambda hwnd, _: windows[hwnd][2],
|
||||
EnumChildWindows=lambda hwnd, callback, _: callback(20, None) if hwnd == 14 else None,
|
||||
GetClassName=lambda hwnd: 'Button' if hwnd == 20 else '#32770',
|
||||
GetDlgCtrlID=lambda hwnd: 1, GetParent=lambda hwnd: 14,
|
||||
)
|
||||
process = SimpleNamespace(GetWindowThreadProcessId=lambda hwnd: windows[hwnd][:2])
|
||||
rows = native.databook_dialogs(gui, process, pid, owner, 99)
|
||||
assert [row['hwnd'] for row in rows] == [10, 11, 12, 14]
|
||||
assert [row['hwnd'] for row in rows if row['dismissible']] == [10]
|
||||
assert rows[-1]['children'] == [{'hwnd': 20, 'parent': 14, 'class': 'Button', 'id': 1}]
|
||||
@@ -3,7 +3,8 @@ import test_accuracy_vbs_guards as guards
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fault', ['', 'snapshot', 'identity', 'transaction', 'native',
|
||||
'save_requested', 'save_committed', 'close'])
|
||||
'native_unresolved', 'prior_staged_write', 'save_requested',
|
||||
'save_committed', 'close'])
|
||||
def test_safe_pause_cannot_interrupt_verified_failure_cleanup(tmp_path, fault):
|
||||
output = guards.run_vbs(tmp_path, ['QPProgress', 'QPDiscardFailedBatchProject',
|
||||
'QPCloseBatchProject', 'QPReadUtf8'], '''
|
||||
@@ -33,6 +34,8 @@ Set QP_Fso=CreateObject("Scripting.FileSystemObject")
|
||||
QP_Root="''' + str(tmp_path) + '''":QP_AttemptToken="token":QP_ProgressSequence=0
|
||||
QP_BatchMode=True:QP_OwnedProject=True:QP_OwnedProjectPath="board.prj"
|
||||
QP_NativeMutationPossible=''' + str(fault == 'native') + '''
|
||||
QP_NativeCallActive=''' + str(fault == 'native_unresolved') + '''
|
||||
If ''' + str(fault == 'prior_staged_write') + ''' Then QP_SessionItems.Add "previous-job", "restored_ok"
|
||||
QP_BatchSaveRequested=''' + str(fault == 'save_requested') + '''
|
||||
QP_BatchSaveCommitted=''' + str(fault == 'save_committed') + '''
|
||||
Class FakeApp
|
||||
@@ -85,8 +88,8 @@ End Sub
|
||||
Sub QPLog(ByVal Root,ByVal Level,ByVal Message)
|
||||
End Sub
|
||||
''')
|
||||
paused_before = fault != 'native'
|
||||
paused_after = fault not in {'native', 'transaction'}
|
||||
paused_before = fault not in {'native', 'native_unresolved'}
|
||||
paused_after = fault not in {'native', 'native_unresolved', 'transaction'}
|
||||
assert output.splitlines()[-1] == f'result:{paused_before}:{not fault}:{bool(fault)}:{paused_after}'
|
||||
|
||||
|
||||
|
||||
@@ -152,6 +152,7 @@ def test_native_catalog_checks_cannot_cold_read_or_submit_on_miss(tmp_path, monk
|
||||
elif code == 0xF5 and handle == 1695:
|
||||
submits.append(handle)
|
||||
raise RuntimeError('native submit reached')
|
||||
return 1, 1
|
||||
gui = SimpleNamespace(error=RuntimeError, GetAncestor=lambda *args: 1, EnumWindows=enum_windows,
|
||||
EnumChildWindows=lambda *args: None, IsWindowVisible=lambda handle: True,
|
||||
GetClassName=lambda handle: {2: '#32770', 3: 'SysListView32', 4: 'Edit'}.get(handle, 'Main'),
|
||||
@@ -179,7 +180,7 @@ def test_native_catalog_checks_cannot_cold_read_or_submit_on_miss(tmp_path, monk
|
||||
monkeypatch.setattr(native_helper, 'selection', lambda *args: None)
|
||||
monkeypatch.setattr(native_helper, 'replacement_command_from_resources', lambda *args: 33977)
|
||||
monkeypatch.setattr(native_helper, 'wait_for', lambda callback, *args, **kwargs: callback())
|
||||
monkeypatch.setattr(native_helper, 'wait_for_library_rows', lambda callback, *args: callback())
|
||||
monkeypatch.setattr(native_helper, 'wait_for_library_rows', lambda callback, *args, **kwargs: callback())
|
||||
monkeypatch.setattr(native_helper, 'wait_for_native_target', lambda callback, *args: callback())
|
||||
report = {}
|
||||
with pytest.raises(ValueError if fail_at else RuntimeError, match='重新读取目标封装' if fail_at else 'native submit reached'):
|
||||
|
||||
Reference in new issue
Block a user