Files
dxdesigner-part-replacement/tests/ui/test_dsh_blocker_sources.py
T
阿白叔 cf6e3f9d2a
Core regression / Python 3.12 core, intervention UI and release configuration (push) Failing after 21s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python 3.12 core, intervention UI and release configuration (pull_request) Failing after 21s
Core regression / JavaScript syntax (pull_request) Successful in 3s
feat(dsh): show AI readiness and prevent repeated intervention on status changes
2026-11-05 16:09:41 +08:00

315 lines
15 KiB
Python

from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center.bom_import_report import BomImportReport, BomRowResult
from dx_productivity.trial_task_center.errors import TaskCenterError
from .test_dsh_operations import setup_view
pytestmark = pytest.mark.usefixtures('ai_ready')
@pytest.fixture
def blockers(ui, monkeypatch):
events = []
spy = SimpleNamespace(
watched={}, check_stalled=lambda: None,
completed=lambda *args: None,
report=lambda *args, **kwargs: events.append(('report', args, kwargs)),
clear=lambda *args, **kwargs: events.append(('clear', args, kwargs)),
watch=lambda *args, **kwargs: events.append(('watch', args, kwargs)),
unwatch=lambda *args, **kwargs: events.append(('unwatch', args, kwargs)),
progress=lambda *args, **kwargs: events.append(('progress', args, kwargs)))
monkeypatch.setattr(ui.window, '_dsh_blockers', spy, raising=False)
return events
def reports(events):
return [event for event in events if event[0] == 'report']
def test_bom_validation_reports_original_owner_and_bounded_evidence(ui, blockers, monkeypatch):
from PySide6.QtWidgets import QFileDialog
panel = ui.window.plan_panel
owner = ui.tasks[0].task_id
pending = []
monkeypatch.setattr(QFileDialog, 'getOpenFileNames', lambda *args: (['bad.xlsx'], ''))
monkeypatch.setattr(panel, '_dispatch_cancellable', lambda operation, callback, button, **kwargs: pending.append(callback))
panel.import_bom()
ui.open(ui.tasks[1])
report = BomImportReport(tuple(BomRowResult(i, 'board.prj', 'Board', 'failed', 'R9 missing')
for i in range(2, 152)), (), errors=('bad header',) * 150)
pending[0](report)
event, args, options = reports(blockers)[-1]
assert args[1:3] == (owner, 'bom_validation_failed')
assert args[4]['total_rows'] == args[4]['failed_rows'] == 150
assert args[4]['rows'][0]['reason'] == 'R9 missing'
assert len(args[4]['rows']) <= 100 and len(args[4]['errors']) <= 100
assert options.get('read_only') is True
assert not ui.calls
def test_bom_new_attempt_clears_scope_but_cancelled_file_dialog_does_not(ui, blockers, monkeypatch):
from PySide6.QtWidgets import QFileDialog
panel = ui.window.plan_panel
scope = panel._report_scope(panel.task_id)
report = BomImportReport((BomRowResult(2, '', '', 'failed', 'invalid row'),), ())
panel._received_bom_report(report, scope=scope)
source = reports(blockers)[-1][1][0]
blockers.clear()
monkeypatch.setattr(QFileDialog, 'getOpenFileNames', lambda *args: ([], ''))
panel.import_bom()
assert not blockers
monkeypatch.setattr(QFileDialog, 'getOpenFileNames', lambda *args: (['new.xlsx'], ''))
monkeypatch.setattr(panel, '_dispatch', lambda *args, **kwargs: None)
panel.import_bom()
assert ('clear', (source,), {}) in blockers
panel.finish_operation()
def test_preflight_blockers_include_exact_task_evidence_and_clear_when_ready(ui, blockers, monkeypatch):
setup_view(ui, monkeypatch)
ctl = ui.window._dsh_lifecycle
ids = [ui.tasks[0].task_id, ui.tasks[1].task_id]
report = {'ready': False, 'tasks': [
{'task_id': ids[0], 'blockers': ['saved plan invalid']},
{'task_id': ids[1], 'blockers': ['project missing']}],
'impact': {'component_count': 3}, 'message': 'checked'}
ctl._preflight_ready('a' * 32, 'preflight', ids, report)
args = reports(blockers)[-1][1]
assert args[1:3] == (ids[0], 'preflight_blocked')
assert args[4]['tasks'] == report['tasks'] and args[4]['impact'] == report['impact']
assert 'saved plan invalid' in args[3] and 'project missing' in args[3]
ctl._preflight_ready('b' * 32, 'preflight', list(reversed(ids)), {**report, 'ready': True})
assert ('clear', (args[0],), {}) in blockers
assert not ui.calls
@pytest.mark.parametrize('kind', ['lifecycle', 'operations'])
def test_assistant_operation_failure_preserves_requested_task_owner(ui, blockers, monkeypatch, qtbot, kind):
setup_view(ui, monkeypatch)
ctl = getattr(ui.window, '_dsh_' + kind)
captured = []
monkeypatch.setattr(ctl, '_work', lambda *args, **kwargs: captured.append(args))
owner = ui.tasks[0].task_id
request = {'request_id': 'c' * 32, 'spec': {'task_ids': [owner]}}
if kind == 'lifecycle':
request['capability'] = 'preflight'
else:
request['spec']['operation'] = 'impact'
ctl.request(request)
ui.open(ui.tasks[1])
ctl._failed('c' * 32, TaskCenterError('plan_unavailable', 'Saved plan cannot be read'))
args = reports(blockers)[-1][1]
assert args[1:4] == (owner, 'plan_unavailable', 'Saved plan cannot be read')
assert not ui.calls
@pytest.mark.parametrize('code', ['operation_cancelled', 'schedule_blocked'])
def test_expected_cancellation_and_schedule_waiting_do_not_report(ui, blockers, monkeypatch, code):
setup_view(ui, monkeypatch)
ui.window._dsh_lifecycle._failed('d' * 32, TaskCenterError(code, 'Waiting or cancelled'))
ui.window._dsh_operations._failed('e' * 32, TaskCenterError(code, 'Waiting or cancelled'))
assert not reports(blockers)
def test_operations_read_error_reports_on_ui_thread_and_clears_on_recovery(ui, blockers, monkeypatch, qtbot):
setup_view(ui, monkeypatch)
ctl = ui.window._dsh_operations
original = ctl.schedules.events
monkeypatch.setattr(ctl.schedules, 'events', lambda: (_ for _ in ()).throw(OSError('unreadable')))
ctl.refresh()
qtbot.waitUntil(lambda: ctl.worker is None)
assert not reports(blockers)
qtbot.waitUntil(lambda: bool(reports(blockers)), timeout=3000)
event = next(row for row in reports(blockers) if row[1][2] == 'section_unavailable')
assert event[1][4]['section'] == 'schedule_events'
assert event[1][4]['consecutive_failures'] == 2
assert event[2].get('read_only') is True
monkeypatch.setattr(ctl.schedules, 'events', original)
ctl.refresh()
qtbot.waitUntil(lambda: ctl.worker is None)
assert ('clear', (event[1][0],), {}) in blockers
@pytest.mark.parametrize('kind', ['lifecycle', 'operations'])
def test_successful_assistant_request_clears_previous_scoped_error(ui, blockers, monkeypatch, kind):
setup_view(ui, monkeypatch)
ctl = getattr(ui.window, '_dsh_' + kind)
ctl.request_id = 'f' * 32
ctl._request_task_ids = (ui.tasks[0].task_id,)
ctl._failed('f' * 32, TaskCenterError('plan_unavailable', 'cannot read plan'))
source = reports(blockers)[-1][1][0]
ctl.request_id = 'a' * 32
ctl._respond('a' * 32, status='read')
assert ('clear', (source,), {}) in blockers
def test_schedule_plan_failure_is_reported_but_future_schedule_wait_is_not(ui, blockers, monkeypatch, qtbot):
setup_view(ui, monkeypatch)
ctl = ui.window._dsh_lifecycle
row = {'schedule_id': 'a' * 32, 'task_ids': [ui.tasks[0].task_id], 'ready': False,
'dispatchable': False, 'blockers': ['plan_changed']}
monkeypatch.setattr(ui.window._dsh_operations.schedules, 'evaluate', lambda _: [row])
ctl.start_schedule(row)
qtbot.waitUntil(lambda: ctl.worker is None)
args = reports(blockers)[-1][1]
assert args[2] == 'schedule_plan_blocked' and 'plan_changed' in args[3]
blockers.clear()
row['blockers'] = ['not_due']
ctl.start_schedule(row)
qtbot.waitUntil(lambda: ctl.worker is None)
assert not reports(blockers) and not ui.calls
def test_bom_operational_report_and_progress_keep_import_owner_after_selection_changes(ui, blockers, monkeypatch):
from dx_productivity.trial_task_center.bom_import_state import BomImportPhase
panel = ui.window.plan_panel
owner = panel.task_id
scope = panel._report_scope(owner)
worker = object()
monkeypatch.setattr(ui.window, '_operation_worker', worker, raising=False)
monkeypatch.setattr(panel, '_dispatch', lambda *args, **kwargs: None)
panel._dispatch_cancellable(lambda *args: None, lambda _: None, panel.import_bom_button, bom_scope=scope)
ui.open(ui.tasks[1])
panel._operation_phase(BomImportPhase.VALIDATING, 'Validating imported rows')
assert any(event[0] == 'progress' and event[1][0] == 'Validating imported rows'
and (event[1][1] if len(event[1]) > 1 else event[2].get('worker')) is worker
for event in blockers)
error = TaskCenterError('bom_read_failed', 'Project inventory unavailable')
error.bom_report = BomImportReport((BomRowResult(2, '', '', 'failed', 'inventory unavailable'),), ())
panel.finish_operation(error=error)
args = reports(blockers)[-1][1]
assert args[1] == owner and args[4]['failed_rows'] == 1
assert not ui.calls
@pytest.mark.parametrize('code', ['bom_import', 'project_binding'])
def test_bom_source_failure_without_report_keeps_readonly_scope_and_original_owner(ui, blockers, monkeypatch, code):
window = ui.window
panel = window.plan_panel
owner = panel.task_id
scope = panel._report_scope(owner)
window._dsh_authorized_tasks.add(owner)
window._dsh_run_id = 'previous-authorized-execution'
monkeypatch.setattr(panel, '_dispatch', lambda *args, **kwargs: None)
panel._dispatch_cancellable(lambda *args: None, lambda _: None, panel.import_bom_button, bom_scope=scope)
ui.open(ui.tasks[1])
monkeypatch.setattr(window, '_queue_dsh_incident', lambda *a: pytest.fail('BOM failure must not inherit CAD authorization'))
error = TaskCenterError(code, 'Source workbook validation failed')
window._show_error(error, owner_task_id=owner, operation_area='bom')
assert not reports(blockers)
panel.finish_operation(error=error)
args, options = reports(blockers)[-1][1:]
assert args[1:3] == (owner, code)
assert args[4]['scope'] == list(scope)
assert options['read_only'] is True
assert panel.bom_import_state.report is None
assert not ui.calls
def test_unrelated_query_error_during_bom_import_keeps_its_own_incident(ui, blockers, monkeypatch):
window = ui.window
panel = window.plan_panel
queued = []
monkeypatch.setattr(panel, '_dispatch', lambda *args, **kwargs: None)
panel._dispatch_cancellable(lambda *args: None, lambda _: None, panel.import_bom_button,
bom_scope=panel._report_scope(panel.task_id))
monkeypatch.setattr(window, '_queue_dsh_incident', lambda *args: queued.append(args) or True)
window._show_error(TaskCenterError('task_read_failed', 'Unrelated task list read failed'))
assert len(queued) == 1 and queued[0][1] == 'task_read_failed'
assert not reports(blockers)
panel.finish_operation(error=TaskCenterError('operation_cancelled', 'test cleanup'))
def test_lifecycle_direct_rejection_is_reported_once(ui, blockers, monkeypatch):
setup_view(ui, monkeypatch)
ctl = ui.window._dsh_lifecycle
ctl._respond('c' * 32, status='rejected', message='No matching active execution')
assert len(reports(blockers)) == 1
assert reports(blockers)[0][1][3] == 'No matching active execution'
blockers.clear()
ctl._respond('d' * 32, status='failed', queue_id='e' * 32, tasks=[])
assert not reports(blockers) # Execution receipts already report each failed task.
def test_background_operations_read_worker_is_watched_until_finished(ui, blockers, monkeypatch, qtbot):
setup_view(ui, monkeypatch)
ctl = ui.window._dsh_operations
ctl.refresh()
worker = ctl.worker
assert any(event[0] == 'watch' and event[1][0] is worker for event in blockers)
qtbot.waitUntil(lambda: ctl.worker is None)
assert any(event[0] == 'unwatch' and event[1][0] is worker for event in blockers)
def test_creation_validation_failure_reports_bounded_summary_without_watching_dialog(ui, blockers, monkeypatch):
setup_view(ui, monkeypatch)
ctl = ui.window._dsh_task_creation
ctl.request({'request_id': 'a' * 32, 'spec': {'name': 'A' * 1000, 'rules': []}})
args = reports(blockers)[-1][1]
assert args[0:2] == ('task-creation', '')
assert args[4]['phase'] == 'validation' and len(args[4]['name']) <= 120
assert not any(event[0] == 'watch' for event in blockers)
def test_creation_worker_failure_reports_and_success_clears_source(ui, blockers, monkeypatch, qtbot):
from .test_dsh_task_creation import request
setup_view(ui, monkeypatch)
ctl = ui.window._dsh_task_creation
original = ui.service.create_assistant_project_tasks
root = ui.data.parent / 'projects'
paths = (root / 'Board-A' / 'board.prj',)
monkeypatch.setattr(ui.service, 'create_assistant_project_tasks',
lambda *args: (_ for _ in ()).throw(TaskCenterError('creation_locked', 'Storage is locked')))
ctl.request(request('b'))
monkeypatch.setattr(ctl.dialog, 'values', lambda: (root, paths))
ctl._accepted('b' * 32, ctl.dialog.spec)
worker = ctl.worker
qtbot.waitUntil(lambda: ctl.worker is None)
args = reports(blockers)[-1][1]
assert args[0:4] == ('task-creation', '', 'creation_locked', 'Storage is locked')
assert args[4]['phase'] == 'creation' and args[4]['rule_count'] == 1
assert any(event[0] == 'watch' and event[1][0] is worker for event in blockers)
assert any(event[0] == 'unwatch' and event[1][0] is worker for event in blockers)
monkeypatch.setattr(ui.service, 'create_assistant_project_tasks', original)
ctl.request(request('c'))
monkeypatch.setattr(ctl.dialog, 'values', lambda: (root, paths))
ctl._accepted('c' * 32, ctl.dialog.spec)
qtbot.waitUntil(lambda: ctl.worker is None)
assert ('clear', ('task-creation',), {}) in blockers
assert not ui.calls
def test_transient_background_section_failure_recovers_on_quick_reread_without_ai(ui, blockers, monkeypatch, qtbot):
setup_view(ui, monkeypatch)
ctl = ui.window._dsh_operations
original = ctl.schedules.events
calls = []
def read():
calls.append(True)
if len(calls) == 1:
raise OSError('temporary read sharing violation')
return original()
monkeypatch.setattr(ctl.schedules, 'events', read)
ctl.refresh()
qtbot.waitUntil(lambda: len(calls) >= 2 and ctl.worker is None, timeout=3000)
assert not reports(blockers)
@pytest.mark.parametrize('scope', ['whole_read', 'decision_audit'])
def test_transient_background_read_failures_are_confirmed_by_actual_reads(ui, blockers, monkeypatch, qtbot, scope):
setup_view(ui, monkeypatch)
ctl = ui.window._dsh_operations
owner, method = (ctl, '_read') if scope == 'whole_read' else (ctl.decisions, 'list')
original = getattr(owner, method)
calls = []
def read(*args, **kwargs):
calls.append(True)
if len(calls) == 1:
raise OSError('temporary read unavailable')
return original(*args, **kwargs)
monkeypatch.setattr(owner, method, read)
ctl.refresh()
qtbot.waitUntil(lambda: len(calls) >= 2 and ctl.worker is None, timeout=3000)
assert not reports(blockers)