From c52ee9050c8717b13d64c69042c9ff54223f6d61 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Mon, 2 Nov 2026 19:25:02 +0800 Subject: [PATCH 01/12] Split composite test assertions so a failure names the condition that broke Sonar S9073: an assert joining several conditions with 'and' reports only that the whole expression was false. One assert per condition keeps the failing check visible in the pytest output. --- .../unit_test/headless/test_action_journal.py | 30 ++++--- .../headless/test_action_journal_capture.py | 33 ++++--- .../headless/test_agent_android_adapter.py | 18 ++-- .../headless/test_agent_android_fixture.py | 18 ++-- .../headless/test_agent_android_hierarchy.py | 12 ++- .../headless/test_agent_android_scope.py | 9 +- .../headless/test_agent_android_semantic.py | 12 ++- .../test_agent_browser_environment.py | 18 ++-- .../test_agent_browser_webrunner_contract.py | 21 +++-- .../headless/test_agent_budget_clock.py | 3 +- .../test_agent_completion_admission.py | 6 +- .../test_agent_completion_authorization.py | 12 ++- ...gent_completion_authorization_consumers.py | 6 +- ...test_agent_completion_authorization_dag.py | 3 +- ...test_agent_completion_authorization_gui.py | 3 +- ...gent_completion_authorization_lifecycle.py | 6 +- ...st_agent_completion_authorization_roles.py | 3 +- ...agent_completion_authorization_surfaces.py | 3 +- .../headless/test_agent_completion_gui.py | 6 +- .../headless/test_agent_completion_handoff.py | 10 ++- .../test_agent_completion_handoff_gui.py | 3 +- ...test_agent_completion_handoff_lifecycle.py | 6 +- .../test_agent_completion_handoff_mixed.py | 3 +- .../test_agent_completion_handoff_surfaces.py | 3 +- .../test_agent_completion_recovery.py | 18 ++-- .../test_agent_completion_security.py | 21 +++-- .../test_agent_completion_surfaces.py | 3 +- .../headless/test_agent_crash_recovery.py | 9 +- .../headless/test_agent_dag_background.py | 36 +++++--- .../test_agent_dag_background_crash.py | 9 +- .../headless/test_agent_dag_background_gui.py | 3 +- .../headless/test_agent_dag_batch_loopback.py | 9 +- .../headless/test_agent_dag_batch_surfaces.py | 9 +- .../headless/test_agent_dag_batches.py | 6 +- .../test_agent_dag_connection_binding.py | 11 ++- .../headless/test_agent_dag_continuation.py | 21 +++-- .../test_agent_dag_continuation_guards.py | 15 ++-- .../test_agent_dag_continuation_gui.py | 4 +- .../headless/test_agent_dag_inspection.py | 24 +++-- .../headless/test_agent_dag_local_tasks.py | 26 ++++-- .../headless/test_agent_dag_matching.py | 18 ++-- .../headless/test_agent_dag_retention.py | 9 +- .../headless/test_agent_desktop_continuity.py | 6 +- .../headless/test_agent_dialog_scope.py | 6 +- .../headless/test_agent_dynamic_recovery.py | 38 +++++--- .../test_agent_evidence_cache_legacy.py | 3 +- .../test_agent_evidence_cache_ownership.py | 3 +- .../test_agent_evidence_cache_paths.py | 6 +- .../headless/test_agent_evidence_handoff.py | 9 +- .../test_agent_evidence_handoff_files.py | 3 +- .../test_agent_evidence_handoff_gui.py | 6 +- .../test_agent_evidence_handoff_lifecycle.py | 4 +- .../test_agent_evidence_handoff_surfaces.py | 3 +- .../headless/test_agent_helper_owner_linux.py | 46 ++++++---- .../headless/test_agent_maintenance_lease.py | 21 +++-- .../headless/test_agent_model_grounding.py | 10 ++- .../headless/test_agent_native_channel.py | 6 +- .../headless/test_agent_native_job.py | 31 ++++--- .../headless/test_agent_observation_gui.py | 3 +- .../headless/test_agent_observed_targets.py | 6 +- .../headless/test_agent_operation_context.py | 6 +- .../headless/test_agent_origin_policy.py | 9 +- .../test_agent_owned_channel_factory.py | 20 +++-- .../test_agent_owner_service_nested.py | 6 +- .../headless/test_agent_presence_binding.py | 12 ++- .../headless/test_agent_presence_broker.py | 18 ++-- .../test_agent_presence_channel_guards.py | 3 +- .../headless/test_agent_presence_handshake.py | 40 ++++++--- .../headless/test_agent_presence_pipe.py | 28 ++++-- .../headless/test_agent_presence_pool.py | 60 +++++++++---- .../headless/test_agent_presence_pool_ipc.py | 16 ++-- .../headless/test_agent_presence_quartz.py | 6 +- .../headless/test_agent_presence_reader.py | 53 +++++++---- .../test_agent_presence_reader_ipc.py | 22 +++-- .../headless/test_agent_presence_runtime.py | 44 +++++++--- .../test_agent_presence_runtime_ipc.py | 44 +++++++--- .../headless/test_agent_presence_security.py | 31 ++++--- .../headless/test_agent_presence_server.py | 15 ++-- .../test_agent_presence_service_ipc.py | 15 ++-- .../test_agent_presence_service_linux.py | 3 +- .../headless/test_agent_presence_session.py | 9 +- .../headless/test_agent_presence_transport.py | 21 +++-- .../headless/test_agent_presence_worker.py | 9 +- .../headless/test_agent_presence_x11.py | 21 +++-- .../headless/test_agent_readiness.py | 6 +- .../test_agent_readonly_completion.py | 19 ++-- .../headless/test_agent_reauthorization.py | 13 ++- .../test_agent_reauthorization_surfaces.py | 3 +- .../headless/test_agent_recovery_ownership.py | 22 +++-- .../headless/test_agent_recovery_surfaces.py | 3 +- .../headless/test_agent_remote_effect.py | 3 +- .../headless/test_agent_remote_worker.py | 12 ++- .../headless/test_agent_request_lookup.py | 18 ++-- .../headless/test_agent_request_match.py | 25 ++++-- .../test_agent_retained_browser_collection.py | 12 ++- .../test_agent_retained_browser_detach.py | 21 +++-- .../test_agent_retained_browser_lifecycle.py | 6 +- .../test_agent_retained_browser_sdk.py | 30 ++++--- .../headless/test_agent_role_boundaries.py | 15 ++-- .../headless/test_agent_screen_evidence.py | 6 +- ...test_agent_skill_authorization_surfaces.py | 6 +- .../headless/test_agent_skill_completion.py | 15 ++-- .../test_agent_skill_completion_surfaces.py | 3 +- .../headless/test_agent_skill_execution.py | 24 +++-- .../test_agent_skill_execution_gui.py | 3 +- .../test_agent_skill_execution_security.py | 3 +- .../test_agent_skill_execution_surfaces.py | 6 +- .../test_agent_skill_reauthorization.py | 9 +- .../test_agent_skill_recording_completion.py | 22 +++-- .../test_agent_skill_recording_surfaces.py | 3 +- .../headless/test_agent_skill_versions.py | 9 +- .../test_agent_stop_completion_race.py | 6 +- .../headless/test_agent_task_handoff.py | 24 +++-- .../headless/test_agent_task_handoff_gui.py | 6 +- .../test_agent_task_handoff_lifecycle.py | 9 +- .../headless/test_agent_task_handoff_mixed.py | 9 +- .../test_agent_task_handoff_revocation.py | 3 +- .../test_agent_task_handoff_surfaces.py | 3 +- .../headless/test_agent_task_recovery.py | 18 ++-- .../headless/test_agent_task_triggers.py | 3 +- .../headless/test_agent_tasks_gui.py | 21 +++-- .../headless/test_agent_transfer_adoption.py | 9 +- ..._agent_transfer_adoption_active_restart.py | 9 +- .../test_agent_transfer_adoption_restart.py | 9 +- .../test_agent_transfer_cold_lifecycle.py | 3 +- .../test_agent_transfer_diagnostics.py | 10 ++- .../headless/test_agent_transfer_evidence.py | 16 ++-- .../test_agent_transfer_evidence_expiry.py | 6 +- .../test_agent_transfer_evidence_remote.py | 13 ++- .../headless/test_agent_transfer_gui.py | 21 +++-- .../test_agent_transfer_import_integrity.py | 3 +- .../test_agent_transfer_import_lifecycle.py | 3 +- .../test_agent_transfer_import_restart.py | 3 +- .../headless/test_agent_transfer_payloads.py | 3 +- .../test_agent_transfer_private_sources.py | 3 +- .../test_agent_transfer_reader_evidence.py | 15 ++-- .../test_agent_transfer_registered.py | 3 +- .../test_agent_transfer_routed_evidence.py | 33 ++++--- .../headless/test_agent_transfer_routing.py | 25 ++++-- .../test_agent_transfer_skill_evidence.py | 38 +++++--- .../headless/test_agent_transfer_source.py | 4 +- .../test_agent_transfer_source_expiry.py | 9 +- .../test_agent_transfer_source_lifecycle.py | 12 ++- .../test_agent_transfer_source_readonly.py | 7 +- .../headless/test_agent_transfer_staging.py | 3 +- .../headless/test_agent_transfer_surfaces.py | 15 ++-- .../headless/test_agent_transport_boundary.py | 3 +- ...st_agent_trigger_authorization_surfaces.py | 15 ++-- .../test_agent_trigger_reauthorization.py | 22 +++-- .../headless/test_agent_worker_shutdown.py | 6 +- .../headless/test_agent_workspace_lifetime.py | 3 +- ...ackground_restart_keeps_old_run_stopped.py | 3 +- .../test_cancellable_diagnostics_example.py | 7 +- .../headless/test_cancellable_wayland_io.py | 15 ++-- .../headless/test_cancellation_token.py | 10 ++- .../test_capability_diagnostics_gui.py | 7 +- .../headless/test_capability_surfaces.py | 3 +- .../headless/test_ci_native_diagnostics.py | 27 ++++-- .../headless/test_codegen_from_journal.py | 3 +- .../headless/test_codegen_journal_gui.py | 12 ++- test/unit_test/headless/test_config_sync.py | 3 +- .../test_config_sync_causal_client.py | 43 ++++++--- .../test_config_sync_causal_guards.py | 19 ++-- .../test_config_sync_causal_http_surfaces.py | 9 +- .../headless/test_config_sync_causal_store.py | 28 ++++-- .../test_config_sync_causal_surfaces.py | 9 +- .../headless/test_config_sync_convergence.py | 6 +- .../headless/test_config_sync_gui.py | 43 ++++++--- .../headless/test_config_sync_outbox.py | 21 +++-- .../headless/test_config_sync_peer_control.py | 51 +++++++---- .../test_config_sync_peer_control_surfaces.py | 4 +- .../headless/test_config_sync_persistence.py | 3 +- .../test_config_sync_store_surfaces.py | 3 +- test/unit_test/headless/test_dag_authority.py | 4 +- .../headless/test_dag_host_registration.py | 6 +- .../headless/test_dag_managed_gui.py | 6 +- .../headless/test_dag_managed_loopback.py | 3 +- .../headless/test_dag_managed_tasks.py | 3 +- .../headless/test_diagnostics_cancellable.py | 15 ++-- .../test_diagnostics_interruptions.py | 6 +- .../headless/test_diagnostics_tab_idle.py | 27 ++++-- .../test_diagnostics_task_lifecycle.py | 18 ++-- .../headless/test_ei_native_verification.py | 21 +++-- .../headless/test_file_receive_receipts.py | 31 ++++--- .../headless/test_folder_sync_checkpoint.py | 9 +- .../headless/test_folder_sync_receipts.py | 3 +- .../headless/test_gui_lazy_registry.py | 15 ++-- .../headless/test_gui_registry_close.py | 21 +++-- .../headless/test_gui_slots_menu_audit.py | 6 +- .../headless/test_gui_task_lifecycle.py | 87 +++++++++++++------ .../headless/test_gui_workspace_layout.py | 6 +- .../headless/test_history_interruption.py | 22 +++-- .../headless/test_journal_browser_gui.py | 67 +++++++++----- .../headless/test_journal_commands.py | 21 +++-- .../headless/test_journal_history_links.py | 9 +- .../headless/test_journal_observation.py | 27 ++++-- .../headless/test_journal_public_cli.py | 36 +++++--- .../unit_test/headless/test_manual_history.py | 38 +++++--- .../test_manual_history_entrypoints.py | 47 ++++++---- .../headless/test_manual_history_gui.py | 24 +++-- test/unit_test/headless/test_mcp_cli.py | 6 +- .../headless/test_mcp_disclosure_policy.py | 21 +++-- .../headless/test_mcp_discovery_gui.py | 6 +- .../headless/test_mcp_discovery_index.py | 3 +- test/unit_test/headless/test_mcp_journal.py | 43 ++++++--- .../headless/test_mcp_progressive_sessions.py | 13 ++- .../headless/test_rbac_deferred_callbacks.py | 3 +- .../test_rbac_sensitive_read_tools.py | 6 +- .../headless/test_rbac_server_wiring.py | 3 +- .../test_remote_clipboard_delivery_gui.py | 9 +- .../test_remote_clipboard_lifecycle.py | 25 ++++-- .../headless/test_remote_host_access_audit.py | 3 +- .../headless/test_rest_auth_compatibility.py | 6 +- .../test_runtime_secret_boundaries.py | 15 ++-- .../headless/test_runtime_secret_callbacks.py | 15 ++-- .../headless/test_runtime_secret_logs.py | 9 +- .../headless/test_scoped_transport_io.py | 9 +- .../headless/test_self_healing_boundaries.py | 3 +- .../headless/test_self_healing_evaluation.py | 27 ++++-- .../test_self_healing_evaluation_gui.py | 9 +- .../test_self_healing_evaluation_surfaces.py | 7 +- .../test_self_healing_run_surfaces.py | 13 ++- .../test_self_healing_runtime_frame.py | 76 ++++++++++------ .../headless/test_self_healing_runtime_gui.py | 12 ++- .../headless/test_self_healing_source.py | 13 ++- .../test_self_healing_verification.py | 39 ++++++--- .../headless/test_sync_adapter_surfaces.py | 3 +- test/unit_test/headless/test_sync_adapters.py | 18 ++-- .../headless/test_sync_asset_store.py | 3 +- .../headless/test_sync_asset_surfaces.py | 3 +- test/unit_test/headless/test_sync_assets.py | 3 +- .../headless/test_sync_profile_gui.py | 31 ++++--- .../headless/test_sync_profile_integrity.py | 9 +- .../headless/test_sync_profile_load.py | 12 ++- .../headless/test_sync_profile_surfaces.py | 3 +- .../unit_test/headless/test_sync_workspace.py | 19 ++-- .../headless/test_sync_workspace_assets.py | 19 ++-- .../test_sync_workspace_preferences.py | 15 ++-- .../headless/test_template_candidate_gui.py | 27 ++++-- .../test_template_candidate_surfaces.py | 3 +- .../headless/test_template_candidates.py | 22 +++-- .../headless/test_vlm_logical_capture.py | 12 ++- .../test_wayland_capability_states.py | 54 ++++++++---- .../headless/test_wayland_input_authority.py | 15 ++-- test/unit_test/headless/test_wayland_libei.py | 3 +- .../headless/test_wayland_portal_lifecycle.py | 28 ++++-- .../headless/test_wayland_region_authority.py | 15 ++-- .../headless/test_webrtc_file_commit.py | 40 ++++++--- .../headless/test_webrtc_file_delivery.py | 46 ++++++---- .../test_webrtc_file_receive_lifecycle.py | 20 +++-- .../headless/test_webrtc_folder_io.py | 16 ++-- .../headless/test_webrtc_folder_reconnect.py | 16 ++-- test/unit_test/headless/test_work_queue.py | 9 +- 253 files changed, 2519 insertions(+), 1208 deletions(-) diff --git a/test/unit_test/headless/test_action_journal.py b/test/unit_test/headless/test_action_journal.py index e4b56e509..ceee2bec3 100644 --- a/test/unit_test/headless/test_action_journal.py +++ b/test/unit_test/headless/test_action_journal.py @@ -22,8 +22,10 @@ def test_event_is_frozen_and_unfinished_is_not_success(tmp_path): journal = ActionJournal(tmp_path / "events.jsonl") journal.append(event) loaded = read_events(journal.path) - assert loaded[0].status == "incomplete" and loaded[0].finished_at is None - assert loaded[0].schema_version == 1 and loaded[0].sequence == 1 + assert loaded[0].status == "incomplete" + assert loaded[0].finished_at is None + assert loaded[0].schema_version == 1 + assert loaded[0].sequence == 1 def test_redaction_precedes_append_and_keeps_secret_references(tmp_path, monkeypatch): @@ -33,7 +35,8 @@ def test_redaction_precedes_append_and_keeps_secret_references(tmp_path, monkeyp def append(path, line): seen.append(line) - assert "literal-password" not in line and "literal-token" not in line + assert "literal-password" not in line + assert "literal-token" not in line original(path, line) monkeypatch.setattr(store, "append_json_line", append) @@ -41,7 +44,8 @@ def append(path, line): event = _event(parameters={"password": "literal-password", "headers": {"Authorization": "literal-token"}, "text": "${secrets.LOGIN}"}) journal.append(event) - assert seen and "${secrets.LOGIN}" in seen[0] + assert seen + assert "${secrets.LOGIN}" in seen[0] assert event.parameters["password"] == "literal-password" assert read_events(journal.path)[0].parameters["password"] == "***" @@ -53,7 +57,8 @@ def test_secret_command_outcome_and_error_are_not_persisted(tmp_path): status="error", finished_at=2.0)) assert "hidden" not in journal.path.read_text(encoding="utf-8") event = read_events(journal.path)[0] - assert event.outcome == "***" and event.error == "***" + assert event.outcome == "***" + assert event.error == "***" assert event.non_replayable @@ -70,9 +75,11 @@ def test_opaque_outcome_keys_cannot_leak_credentials(tmp_path): journal.append(_event(outcome={"private-result": {"another-credential": "anything"}}, status="ok", finished_at=2.0)) text = journal.path.read_text(encoding="utf-8") - assert "private-result" not in text and "another-credential" not in text + assert "private-result" not in text + assert "another-credential" not in text event = read_events(journal.path)[0] - assert "redacted_outcome" in event.non_replayable and event.outcome_type == "object" + assert "redacted_outcome" in event.non_replayable + assert event.outcome_type == "object" def test_sensitive_fields_can_retain_explicit_secret_references(tmp_path): @@ -103,7 +110,8 @@ def __repr__(self): journal = ActionJournal(tmp_path / "events.jsonl") journal.append(_event(parameters={"payload": Payload()})) event = read_events(journal.path)[0] - assert event.non_replayable and "unsupported" in str(event.parameters) + assert event.non_replayable + assert "unsupported" in str(event.parameters) def test_run_filter_and_parent_links_survive_round_trip(tmp_path): @@ -136,9 +144,11 @@ def write(index): thread.start() for thread in threads: thread.join(timeout=15) - assert not any(thread.is_alive() for thread in threads) and failures == [] + assert not any(thread.is_alive() for thread in threads) + assert failures == [] events = read_events(path) - assert len(events) == 32 and [event.sequence for event in events] == list(range(1, 33)) + assert len(events) == 32 + assert [event.sequence for event in events] == list(range(1, 33)) assert all(event.run_id == "run" and event.parent_id == "parent" for event in events) diff --git a/test/unit_test/headless/test_action_journal_capture.py b/test/unit_test/headless/test_action_journal_capture.py index 6797a25ce..7946c2169 100644 --- a/test/unit_test/headless/test_action_journal_capture.py +++ b/test/unit_test/headless/test_action_journal_capture.py @@ -30,7 +30,8 @@ def test_scoped_capture_preserves_source_refs_and_never_writes_resolved_secrets( monkeypatch.setattr(default_secret_manager, "get", lambda name: "resolved-private-value") path = tmp_path / "events.jsonl" result = execute_action_with_journal([[PROBE, {"value": "${secrets.LOGIN}"}]], path, run_id="run") - assert result["run_id"] == "run" and result["failed_actions"] == 0 + assert result["run_id"] == "run" + assert result["failed_actions"] == 0 assert seen == ["resolved-private-value"] assert "resolved-private-value" not in path.read_text(encoding="utf-8") events = read_events(path) @@ -47,9 +48,12 @@ def test_loop_children_share_run_and_point_to_the_observed_parent(tmp_path, seen completed = _completed(path) parent = next(event for event in completed if event.command == "AC_loop") children = [event for event in completed if event.command == PROBE] - assert len(children) == 2 and len({event.step_id for event in children}) == 2 + assert len(children) == 2 + assert len({event.step_id for event in children}) == 2 assert all(event.run_id == "loop" and event.parent_id == parent.step_id for event in children) - assert parent.parent_id is None and parent.status == "ok" and seen == ["child", "child"] + assert parent.parent_id is None + assert parent.status == "ok" + assert seen == ["child", "child"] assert all(event.sequence < parent.sequence for event in children) @@ -68,7 +72,8 @@ def test_worker_actions_retain_parent_and_identity(tmp_path, seen, block): completed = _completed(path) parent = next(event for event in completed if event.command == parent_command) children = [event for event in completed if event.command == PROBE] - assert sorted(seen) == ["left", "right"] and len(children) == 2 + assert sorted(seen) == ["left", "right"] + assert len(children) == 2 assert all(event.parent_id == parent.step_id for event in children) assert all((event.run_id, event.device_id, event.session_id) == ("workers", "device", "session") for event in read_events(path)) @@ -118,7 +123,8 @@ def test_dry_run_is_labelled_and_invokes_no_handler(tmp_path, seen): path = tmp_path / "events.jsonl" execute_action_with_journal([[PROBE, {"value": "never"}]], path, dry_run=True) event = _completed(path)[0] - assert event.status == "dry_run" and "not_executed" in event.non_replayable + assert event.status == "dry_run" + assert "not_executed" in event.non_replayable assert seen == [] @@ -130,15 +136,18 @@ def test_nested_scopes_restore_parent_and_isolate_seeded_variables(tmp_path, see variables={"owner": "inner"}, run_id="inner") assert current_journal() is binding executor.execute_action([[PROBE, {"value": "${owner}"}]]) - assert seen == ["inner", "outer"] and current_journal() is None + assert seen == ["inner", "outer"] + assert current_journal() is None assert {event.run_id for event in read_events(outer)} == {"outer"} assert {event.run_id for event in read_events(inner)} == {"inner"} def test_plain_execution_keeps_its_existing_result_contract(tmp_path, seen): record = executor.execute_action([[PROBE, {"value": "plain"}]]) - assert list(record.values()) == ["plain"] and seen == ["plain"] - assert list(tmp_path.iterdir()) == [] and current_journal() is None + assert list(record.values()) == ["plain"] + assert seen == ["plain"] + assert list(tmp_path.iterdir()) == [] + assert current_journal() is None @pytest.mark.parametrize("strict", [False, True]) @@ -174,7 +183,9 @@ def stopped(_action): with pytest.raises(KeyboardInterrupt): with journal_scope(ActionJournal(path)): executor.execute_action([[PROBE, {"value": "never"}]], step_callback=stopped) - assert not path.exists() and seen == [] and current_journal() is None + assert not path.exists() + assert seen == [] + assert current_journal() is None def test_process_exit_during_a_command_preserves_only_its_incomplete_start(tmp_path): @@ -193,4 +204,6 @@ def test_process_exit_during_a_command_preserves_only_its_incomplete_start(tmp_p ) assert done.returncode == 23, done.stderr events = read_events(path) - assert len(events) == 1 and events[0].run_id == "crashed" and events[0].status == "incomplete" + assert len(events) == 1 + assert events[0].run_id == "crashed" + assert events[0].status == "incomplete" diff --git a/test/unit_test/headless/test_agent_android_adapter.py b/test/unit_test/headless/test_agent_android_adapter.py index 4f14e883c..6478a5368 100644 --- a/test/unit_test/headless/test_agent_android_adapter.py +++ b/test/unit_test/headless/test_agent_android_adapter.py @@ -110,12 +110,14 @@ def test_actual_worker_and_sdk_only_invoke_finite_input_after_durable_begin_ack( assert adapter.ready(spec) == (True, '') observed = adapter.observe() assert observed['identity']['physical_id'] == DEVICE - assert observed['elements'] == [] and observed['text'] == '' + assert observed['elements'] == [] + assert observed['text'] == '' assert not any('/system/bin/input -d 0 ' in command for command in sdk.services) assert adapter.perform('AC_android_tap', {'x': 10, 'y': 20}) == { 'android_phase': 'input_returned', 'may_have_effect': True} assert (sdk.directory / 'actions').read_text().splitlines() == ['-d', '0', 'tap', '10', '20'] - assert not adapter._journal.pending and adapter._journal.sequence == 2 + assert not adapter._journal.pending + assert adapter._journal.sequence == 2 assert json.loads((sdk.directory / 'fence.json').read_text())['active'] is False assert not sdk.errors finally: @@ -146,7 +148,8 @@ def test_bad_independent_settlement_keeps_effect_quarantined(android_sdk, flag): with pytest.raises(AgentTaskError): adapter.perform('AC_android_tap', {'x': 10, 'y': 20}) assert (sdk.directory / 'actions').exists() - assert adapter._journal.pending and adapter._channel.retired + assert adapter._journal.pending + assert adapter._channel.retired finally: release_fixture(adapter) @@ -161,7 +164,8 @@ def test_lost_shell_exit_stays_unknown_even_after_fixture_writer_settles(android with pytest.raises(AgentTaskError): adapter.perform('AC_android_tap', {'x': 10, 'y': 20}) assert json.loads((sdk.directory / 'settlement.json').read_text())['queue_empty'] is True - assert adapter._journal.pending and adapter._channel.retired + assert adapter._journal.pending + assert adapter._channel.retired finally: release_fixture(adapter) @@ -180,7 +184,8 @@ def test_stale_scope_or_unmatched_lease_cannot_begin_input(android_sdk, change): (sdk.directory / 'wrong_lease').touch() with pytest.raises(AgentTaskError): adapter.perform('AC_android_tap', {'x': 10, 'y': 20}) - assert not adapter._journal.pending and not (sdk.directory / 'actions').exists() + assert not adapter._journal.pending + assert not (sdk.directory / 'actions').exists() assert not any('/system/bin/input -d 0 ' in command for command in sdk.services) finally: release_fixture(adapter) @@ -275,6 +280,7 @@ def revoke(journal, event): adapter.perform('AC_android_tap', {'x': 10, 'y': 20}) assert not (sdk.directory / 'actions').exists() assert not any('/system/bin/input -d 0 ' in command for command in sdk.services) - assert adapter._journal.pending and adapter._channel.retired + assert adapter._journal.pending + assert adapter._channel.retired finally: release_fixture(adapter) diff --git a/test/unit_test/headless/test_agent_android_fixture.py b/test/unit_test/headless/test_agent_android_fixture.py index 1c5701cee..b32a9258a 100644 --- a/test/unit_test/headless/test_agent_android_fixture.py +++ b/test/unit_test/headless/test_agent_android_fixture.py @@ -15,7 +15,8 @@ def test_focus_guard_accepts_all_field_orders_without_normalizing_values(run_gua lines = WM.splitlines(keepends=True) (tmp_path / "wm").write_text("".join(lines[index] for index in order), encoding="utf-8", newline="") result = run_guard() - assert result.returncode == 0 and (tmp_path / "actions").read_text().splitlines().count("tap") == 1 + assert result.returncode == 0 + assert (tmp_path / "actions").read_text().splitlines().count("tap") == 1 @pytest.mark.parametrize("data", [b"", b"line\n\n", b"no-final-newline", b"a\x00b\x00\x00", b"\xff\xfe\n\\ \r\n"]) @@ -25,7 +26,8 @@ def test_fast_fixture_reader_preserves_exact_bytes_including_nulls_and_newlines( (tmp_path / "device").write_bytes(data) prefix = "unset BASH_VERSION; " if fallback else "" result = fixture.run(prefix + "/system/bin/getprop ro.serialno") - assert result.returncode == 0 and result.stdout == data + assert result.returncode == 0 + assert result.stdout == data def test_fixture_timeout_diagnostic_has_phase_and_duration_but_no_command_or_output(tmp_path, snapshot, monkeypatch): @@ -37,9 +39,11 @@ def test_fixture_timeout_diagnostic_has_phase_and_duration_but_no_command_or_out fixture.run("/system/bin/input -d 0 text " + secret) assert str(error.value) == "Android fixture action shell exceeded its five-second deadline" diagnostics = fixture.diagnostics() - assert diagnostics[-1]["phase"] == "action" and diagnostics[-1]["outcome"] == "timeout" + assert diagnostics[-1]["phase"] == "action" + assert diagnostics[-1]["outcome"] == "timeout" assert isinstance(diagnostics[-1]["seconds"], float) - assert secret not in repr(diagnostics) and "private" not in repr(diagnostics) + assert secret not in repr(diagnostics) + assert "private" not in repr(diagnostics) assert run.call_args.kwargs["timeout"] == 5 @@ -61,7 +65,8 @@ def test_duplicate_focus_fields_including_empty_values_fail_on_the_correct_side_ def test_raw_labels_cannot_replace_a_missing_native_focus_field(run_guard, tmp_path): missing = WM.replace("mTopFocusedDisplayId=0", "display=0") (tmp_path / "wm").write_text(missing, encoding="utf-8", newline="") - assert run_guard().returncode == 93 and not (tmp_path / "actions").exists() + assert run_guard().returncode == 93 + assert not (tmp_path / "actions").exists() def test_shell_metacharacters_and_globs_in_current_focus_cannot_match_or_execute(tmp_path, snapshot): @@ -69,5 +74,6 @@ def test_shell_metacharacters_and_globs_in_current_focus_cannot_match_or_execute hostile = WM.replace(snapshot.window, "Window{[a]* $(touch injected) 'quoted'}") (tmp_path / "wm").write_text(hostile, encoding="utf-8", newline="") result = fixture.run(compile_android_action(snapshot, "AC_android_tap", {"x": 1, "y": 2})) - assert result.returncode == 93 and not (tmp_path / "injected").exists() + assert result.returncode == 93 + assert not (tmp_path / "injected").exists() assert not (tmp_path / "actions").exists() diff --git a/test/unit_test/headless/test_agent_android_hierarchy.py b/test/unit_test/headless/test_agent_android_hierarchy.py index 875a60298..0d69c142e 100644 --- a/test/unit_test/headless/test_agent_android_hierarchy.py +++ b/test/unit_test/headless/test_agent_android_hierarchy.py @@ -65,12 +65,14 @@ def semantic_tree(): def test_no_plain_xml_text_is_authorized_and_review_cannot_reveal_password_or_editable_values(): raw = semantic_tree() hidden = parse(sample(raw)) - assert hidden.text == '' and all(item['name'] == '' for item in hidden.elements) + assert hidden.text == '' + assert all(item['name'] == '' for item in hidden.elements) reviewed = parse(sample(raw, grants=('0/0', '0/1', '0/2'))) result = reviewed.to_dict() assert result['text'] == 'Save' assert result['elements'][1]['bounds'] == [10, 10, 30, 30] - assert result['elements'][1]['role'] == 'button' and result['elements'][1]['actionable'] is True + assert result['elements'][1]['role'] == 'button' + assert result['elements'][1]['actionable'] is True assert all(item['sensitive'] for item in result['elements'][2:]) assert not any(item['actionable'] for item in result['elements'][2:]) assert 'private-' not in json.dumps(result) @@ -81,7 +83,8 @@ def test_foreign_packages_and_descendants_never_escape_the_owned_app_scope(): foreign = node({'index': '1', 'package': 'org.foreign.app', 'text': 'foreign-secret'}, [ node({'package': PACKAGE, 'text': 'smuggled-own-package-secret'})]) view = parse(sample(document(node(children=[node({'text': 'own label'}), foreign])), grants=('0/0',))) - assert len(view.elements) == 2 and view.text == 'own label' + assert len(view.elements) == 2 + assert view.text == 'own label' assert 'secret' not in json.dumps(view.to_dict()) with pytest.raises(AgentTaskError): parse(sample(document(node(children=[foreign])), grants=('0/1',))) @@ -90,7 +93,8 @@ def test_foreign_packages_and_descendants_never_escape_the_owned_app_scope(): def test_sensitive_ancestor_overrides_descendant_text_grants(): raw = document(node({'password': 'true'}, [node({'text': 'protected-child', 'clickable': 'true'})])) view = parse(sample(raw, grants=('0/0',))) - assert view.text == '' and all(item['sensitive'] for item in view.elements) + assert view.text == '' + assert all(item['sensitive'] for item in view.elements) assert not any(item['actionable'] for item in view.elements) diff --git a/test/unit_test/headless/test_agent_android_scope.py b/test/unit_test/headless/test_agent_android_scope.py index 0361cac78..18c16f959 100644 --- a/test/unit_test/headless/test_agent_android_scope.py +++ b/test/unit_test/headless/test_agent_android_scope.py @@ -156,7 +156,8 @@ def test_identity_failure_after_input_never_masquerades_as_pre_input_refusal(run result = run_guard() assert result.returncode == code parsed = parse_android_action_result(AdbShellResult(result.stdout, result.stderr, result.returncode)) - assert parsed.phase == "post_input_refused" and parsed.may_have_effect + assert parsed.phase == "post_input_refused" + assert parsed.may_have_effect assert (tmp_path / "actions").read_text().splitlines().count("tap") == 1 @@ -376,7 +377,8 @@ def test_concurrent_inspection_cannot_commit_two_different_boots_into_one_sessio class ConcurrentServer(Server): def shell(self, transport, command, **_kwargs): - assert transport == 42 and command == IDENTITY_PROBE + assert transport == 42 + assert command == IDENTITY_PROBE boot = BOOT if threading.current_thread().name == "old-boot" else BOOT.replace("1", "2") return AdbShellResult(evidence(boot=boot), b"", 0) @@ -569,7 +571,8 @@ def test_same_command_connection_refuses_changed_native_input_before_any_write(r result = run_guard(input_evidence=proof) assert result.returncode == 95 parsed = parse_android_action_result(AdbShellResult(result.stdout, result.stderr, result.returncode)) - assert parsed.phase == "pre_input_refused" and not parsed.may_have_effect + assert parsed.phase == "pre_input_refused" + assert not parsed.may_have_effect assert not (tmp_path / "actions").exists() diff --git a/test/unit_test/headless/test_agent_android_semantic.py b/test/unit_test/headless/test_agent_android_semantic.py index 5551d84d1..ed4669cdb 100644 --- a/test/unit_test/headless/test_agent_android_semantic.py +++ b/test/unit_test/headless/test_agent_android_semantic.py @@ -29,11 +29,13 @@ def test_semantic_observation_is_stable_masked_and_resolves_reviewed_tap(android adapter.ready(current) first, second = adapter.observe(), adapter.observe() assert first == second - assert first['text'] == 'Save' and 'private-' not in json.dumps(first) + assert first['text'] == 'Save' + assert 'private-' not in json.dumps(first) args, _ground = resolve_action('AC_android_tap', {}, {'element_index': 1}, first) adapter.perform('AC_android_tap', args) assert (sdk.directory / 'actions').read_text().splitlines() == ['-d', '0', 'tap', '25', '25'] - assert not adapter._journal.pending and not sdk.errors + assert not adapter._journal.pending + assert not sdk.errors finally: release_fixture(adapter) @@ -53,7 +55,8 @@ def test_changed_semantic_content_or_capture_identity_refuses_input_before_begin (sdk.directory / 'hierarchy.xml').write_bytes(semantic_tree().replace(old, new)) with pytest.raises(AgentTaskError): adapter.perform('AC_android_tap', {'x': 25, 'y': 25}) - assert not (sdk.directory / 'actions').exists() and not adapter._journal.pending + assert not (sdk.directory / 'actions').exists() + assert not adapter._journal.pending finally: release_fixture(adapter) @@ -76,7 +79,8 @@ def change(journal, event): with pytest.raises(AgentTaskError): adapter.perform('AC_android_tap', {'x': 25, 'y': 25}) assert not (sdk.directory / 'actions').exists() - assert adapter._journal.pending and adapter._channel.retired + assert adapter._journal.pending + assert adapter._channel.retired finally: release_fixture(adapter) diff --git a/test/unit_test/headless/test_agent_browser_environment.py b/test/unit_test/headless/test_agent_browser_environment.py index 8520c7a1c..4b03ae508 100644 --- a/test/unit_test/headless/test_agent_browser_environment.py +++ b/test/unit_test/headless/test_agent_browser_environment.py @@ -25,7 +25,8 @@ def test_reviewed_helper_interpreter_selects_isolated_installed_modules(): assert target._argv[0] == configuration.settings["helper_python"] assert "-I" in target._argv assert target._argv[-1] == "je_auto_control.utils.agent_runtime.native_worker" - assert target._channel is None and target._resource is None + assert target._channel is None + assert target._resource is None def test_target_probe_uses_existing_host_management_and_does_not_enable_target(tmp_path, monkeypatch): @@ -81,8 +82,10 @@ def test_worker_probe_imports_without_starting_sdk_or_playwright(monkeypatch): worker = NativeWorker(io.BytesIO(), io.BytesIO()) report = worker._dispatch("probe_browser", {"transfer": True}) assert report["status"] == "python_dependencies_ready" - assert report["browser_launch"] == "not_probed" and report["native_evidence"] == "not_recorded" - assert worker._spec is None and worker._activity is None + assert report["browser_launch"] == "not_probed" + assert report["native_evidence"] == "not_recorded" + assert worker._spec is None + assert worker._activity is None sdk.open.assert_not_called() require_runtime.assert_called_once() runtime.assert_not_called() @@ -130,7 +133,8 @@ def test_dependency_reply_cannot_claim_native_success_or_include_unknown_metadat channel = SimpleNamespace(request=Mock(side_effect=[{"protocol": 1}, report]), close=Mock()) monkeypatch.setattr(helper_environment, "owned_channel", Mock(return_value=channel)) result = helper_environment.probe_browser_helper((sys.executable,), transfer=True) - assert result["status"] == "unknown" and result["native_evidence"] == "not_recorded" + assert result["status"] == "unknown" + assert result["native_evidence"] == "not_recorded" channel.close.assert_called_once() @@ -153,8 +157,10 @@ def test_default_environment_probe_does_not_acquire_target_input_or_start_a_brow target = build_target(profile()) result = target.probe() assert result["status"] in {"python_dependencies_ready", "dependency_missing", "incompatible"} - assert result["native_evidence"] == "not_recorded" and result["browser_launch"] == "not_probed" - assert target._channel is None and target._resource is None + assert result["native_evidence"] == "not_recorded" + assert result["browser_launch"] == "not_probed" + assert target._channel is None + assert target._resource is None def test_cli_and_command_schema_offer_the_same_host_probe_operation(): diff --git a/test/unit_test/headless/test_agent_browser_webrunner_contract.py b/test/unit_test/headless/test_agent_browser_webrunner_contract.py index 8221779bb..2390349f7 100644 --- a/test/unit_test/headless/test_agent_browser_webrunner_contract.py +++ b/test/unit_test/headless/test_agent_browser_webrunner_contract.py @@ -140,7 +140,8 @@ def test_hung_sdk_effect_reaps_only_owned_helper_and_preserves_uncertainty(tmp_p result = run_task(runtime, handle.task_id) assert result.state == "waiting_user" receipts = runtime.store.actions(handle.task_id) - assert len(receipts) == 1 and receipts[0]["status"] == "uncertain" + assert len(receipts) == 1 + assert receipts[0]["status"] == "uncertain" assert adapter._channel is None assert adapter._ledger.empty finally: @@ -279,8 +280,10 @@ def test_owned_browser_helper_refuses_cold_skill_prefix_before_relaunch(tmp_path assert adapter._channel is None runtime.resume(handle.task_id) outcome = run_task(runtime, handle.task_id) - assert outcome.state == "waiting_user" and "browser context" in outcome.reason - assert adapter._channel is None and adapter._resource is None + assert outcome.state == "waiting_user" + assert "browser context" in outcome.reason + assert adapter._channel is None + assert adapter._resource is None assert len(runtime.store.actions(handle.task_id)) == 2 finally: runtime.close() @@ -295,8 +298,10 @@ def test_dependency_probe_uses_real_sdk_loader_without_starting_its_factory(monk monkeypatch.setattr(playwright_wrapper, "_require_playwright", loader) report = inspect_browser_dependencies(True) assert report["status"] == "python_dependencies_ready" - assert report["readback_contract"] and report["transfer_contract"] - assert report["browser_launch"] == "not_probed" and report["native_evidence"] == "not_recorded" + assert report["readback_contract"] + assert report["transfer_contract"] + assert report["browser_launch"] == "not_probed" + assert report["native_evidence"] == "not_recorded" loader.assert_called_once() factory.assert_not_called() @@ -308,6 +313,8 @@ def test_dependency_probe_contains_the_real_sdk_missing_runtime_error(monkeypatc loader = Mock(side_effect=playwright_wrapper.PlaywrightBackendError("private fixture diagnostic")) monkeypatch.setattr(playwright_wrapper, "_require_playwright", loader) report = inspect_browser_dependencies(True) - assert report["status"] == "dependency_missing" and report["playwright"] is False - assert report["browser_launch"] == "not_probed" and report["native_evidence"] == "not_recorded" + assert report["status"] == "dependency_missing" + assert report["playwright"] is False + assert report["browser_launch"] == "not_probed" + assert report["native_evidence"] == "not_recorded" assert "private fixture diagnostic" not in str(report) diff --git a/test/unit_test/headless/test_agent_budget_clock.py b/test/unit_test/headless/test_agent_budget_clock.py index 97c085051..66d5e7fe2 100644 --- a/test/unit_test/headless/test_agent_budget_clock.py +++ b/test/unit_test/headless/test_agent_budget_clock.py @@ -71,7 +71,8 @@ def read(): finally: release.set() worker.join(timeout=3) - assert not worker.is_alive() and not failures + assert not worker.is_alive() + assert not failures assert result == [280] finally: release.set() diff --git a/test/unit_test/headless/test_agent_completion_admission.py b/test/unit_test/headless/test_agent_completion_admission.py index 1589150c0..f3dfe02cd 100644 --- a/test/unit_test/headless/test_agent_completion_admission.py +++ b/test/unit_test/headless/test_agent_completion_admission.py @@ -83,8 +83,10 @@ def test_dynamic_confirmed_effects_can_be_completed_by_fresh_independent_criteri connection.execute('UPDATE agent_tasks SET spec=? WHERE id=?', (json.dumps(spec), completed.task_id)) identifier = child(completed) result = runtime.finish(identifier) - assert result.state == 'succeeded' and len(result.verification) == 1 - assert runtime.store.get(identifier)['spec']['mode'] == 'external' and runtime.store.actions(identifier) == [] + assert result.state == 'succeeded' + assert len(result.verification) == 1 + assert runtime.store.get(identifier)['spec']['mode'] == 'external' + assert runtime.store.actions(identifier) == [] def test_missing_source_capture_is_a_typed_review_refusal_not_an_unhandled_lookup(completed): diff --git a/test/unit_test/headless/test_agent_completion_authorization.py b/test/unit_test/headless/test_agent_completion_authorization.py index cfbfedf06..669a07ab8 100644 --- a/test/unit_test/headless/test_agent_completion_authorization.py +++ b/test/unit_test/headless/test_agent_completion_authorization.py @@ -115,18 +115,22 @@ def test_explicit_renewal_finishes_real_files_without_reviving_the_original_orig with pytest.raises(AgentTaskError, match='managed origin'): runtime.recovery.control('preview_completion', {'task_id': source}) preview, request = reviewed(renewal) - assert preview['approval_required'] is True and preview['source_completion_inherited'] is False + assert preview['approval_required'] is True + assert preview['source_completion_inherited'] is False assert preview['verification_spec']['actions'] == [] assert preview['verification_spec']['roots'] == [str(renewal.reports)] assert preview['authorization']['replaced_origins'] == [renewal.old.identifier] child = runtime.recovery.control('create_authorized_completion', request)['task_id'] runtime.observe(child) result = runtime.finish(child) - assert result.state == 'succeeded' and result.metadata['input_released'] is True + assert result.state == 'succeeded' + assert result.metadata['input_released'] is True assert result.metadata['completion_contract'] == 1 assert [report['status'] for report in result.verification] == ['passed', 'passed', 'passed'] - assert runtime.get(source).state == 'paused' and runtime.store.actions(source) == historical - assert runtime.store.actions(child) == [] and renewal.manifest.read_bytes() == manifest + assert runtime.get(source).state == 'paused' + assert runtime.store.actions(source) == historical + assert runtime.store.actions(child) == [] + assert renewal.manifest.read_bytes() == manifest assert origin_policy._path(renewal.old.identifier).read_bytes() == revoked assert runtime.store.get(source)['spec']['roots'] == [str(renewal.allowed)] assert runtime.store.get(child)['spec']['roots'] == [str(renewal.reports)] diff --git a/test/unit_test/headless/test_agent_completion_authorization_consumers.py b/test/unit_test/headless/test_agent_completion_authorization_consumers.py index acd5dd3a6..9d7e1de6a 100644 --- a/test/unit_test/headless/test_agent_completion_authorization_consumers.py +++ b/test/unit_test/headless/test_agent_completion_authorization_consumers.py @@ -28,7 +28,8 @@ def test_recording_uses_reviewed_scope_and_still_requires_its_own_fresh_validati before = renewal.manifest.read_bytes() candidate = renewal.runtime.skills.control('record', {'task_id': renewal.source, 'completion_task_id': child, 'name': 'Explicitly renewed file workflow'}) - assert candidate['state'] == 'draft' and candidate['version'] == 0 + assert candidate['state'] == 'draft' + assert candidate['version'] == 0 assert candidate['spec']['roots'] == [str(renewal.reports)] assert candidate['spec']['actions'] == [renewal.action] assert renewal.old.identifier not in candidate['spec']['options']['origin_policies'] @@ -44,4 +45,5 @@ def test_recording_uses_reviewed_scope_and_still_requires_its_own_fresh_validati assert run_task(renewal.runtime, trial['task_id']).state == 'succeeded' accepted = renewal.runtime.skills.control('accept', {'candidate_id': candidate['id'], 'task_id': trial['task_id'], 'expected_version': 0, 'note': 'Accepted only the separately executed current-scope trial'}) - assert accepted['version'] == 1 and renewal.runtime.get(renewal.source).state == 'paused' + assert accepted['version'] == 1 + assert renewal.runtime.get(renewal.source).state == 'paused' diff --git a/test/unit_test/headless/test_agent_completion_authorization_dag.py b/test/unit_test/headless/test_agent_completion_authorization_dag.py index 0695ab2b5..cfb0fdbf9 100644 --- a/test/unit_test/headless/test_agent_completion_authorization_dag.py +++ b/test/unit_test/headless/test_agent_completion_authorization_dag.py @@ -30,7 +30,8 @@ def test_original_batch_adoption_is_invalidated_when_renewed_evidence_loses_auth assert connection.execute('SELECT phase FROM agent_dag_nodes WHERE batch_id=?', (renewal.batch_id,)).fetchone()[0] == 'unknown' assert renewal.runtime.get(renewal.source).state == 'paused' - assert len(renewal.runtime.store.actions(renewal.source)) == 1 and renewal.runtime.store.actions(child) == [] + assert len(renewal.runtime.store.actions(renewal.source)) == 1 + assert renewal.runtime.store.actions(child) == [] @pytest.mark.parametrize('renewal', ['named_dag'], indirect=True) diff --git a/test/unit_test/headless/test_agent_completion_authorization_gui.py b/test/unit_test/headless/test_agent_completion_authorization_gui.py index be07a2ea0..f0a4fbfff 100644 --- a/test/unit_test/headless/test_agent_completion_authorization_gui.py +++ b/test/unit_test/headless/test_agent_completion_authorization_gui.py @@ -27,7 +27,8 @@ def test_readonly_renewal_actions_use_the_shared_recovery_protocol(monkeypatch, actions = dict(tab.menu_actions()) assert action in actions actions[action]() - assert requests[0][0] == 'recovery' and requests[0][1]['operation'] == operation + assert requests[0][0] == 'recovery' + assert requests[0][1]['operation'] == operation expected = {'task_id': 'original-workflow'} if operation.startswith('review') else request assert requests[0][1]['request'] == expected finally: diff --git a/test/unit_test/headless/test_agent_completion_authorization_lifecycle.py b/test/unit_test/headless/test_agent_completion_authorization_lifecycle.py index f546b3476..7bc81f5f3 100644 --- a/test/unit_test/headless/test_agent_completion_authorization_lifecycle.py +++ b/test/unit_test/headless/test_agent_completion_authorization_lifecycle.py @@ -29,7 +29,8 @@ def test_private_renewal_survives_runtime_restart_with_the_same_readonly_limits( try: assert reopened.finish(child).state == 'succeeded' assert reopened.store.get(child)['spec']['roots'] == [str(renewal.reports)] - assert reopened.store.actions(child) == [] and reopened.get(renewal.source).state == 'paused' + assert reopened.store.actions(child) == [] + assert reopened.get(renewal.source).state == 'paused' finally: reopened.close() @@ -43,7 +44,8 @@ def test_sixteen_real_readonly_links_succeed_and_a_seventeenth_is_refused(renewa assert renewal.runtime.finish(parent).state == 'succeeded' with pytest.raises(AgentTaskError, match='sixteen'): reviewed(renewal, parent) - assert renewal.runtime.store.actions(parent) == [] and len(renewal.runtime.list()) == 17 + assert renewal.runtime.store.actions(parent) == [] + assert len(renewal.runtime.list()) == 17 def test_source_change_inside_final_completion_sql_cannot_publish_stale_success(renewal): diff --git a/test/unit_test/headless/test_agent_completion_authorization_roles.py b/test/unit_test/headless/test_agent_completion_authorization_roles.py index 8cea8ba19..522f3762f 100644 --- a/test/unit_test/headless/test_agent_completion_authorization_roles.py +++ b/test/unit_test/headless/test_agent_completion_authorization_roles.py @@ -38,7 +38,8 @@ def test_actual_renewal_reviewer_revocation_invalidates_current_completion_evide assert renewal.runtime.get(child).metadata['completion_contract'] == 1 renewal.users.remove_user('reviewer') result = renewal.runtime.get(child) - assert result.state == 'succeeded' and result.metadata['completion_contract'] == 0 + assert result.state == 'succeeded' + assert result.metadata['completion_contract'] == 0 @pytest.mark.parametrize('renewal', ['named'], indirect=True) diff --git a/test/unit_test/headless/test_agent_completion_authorization_surfaces.py b/test/unit_test/headless/test_agent_completion_authorization_surfaces.py index 1ceaec5ed..7f16c409c 100644 --- a/test/unit_test/headless/test_agent_completion_authorization_surfaces.py +++ b/test/unit_test/headless/test_agent_completion_authorization_surfaces.py @@ -32,6 +32,7 @@ def test_shared_surfaces_renew_only_the_reviewed_independent_completion(renewal, metadata = renewal.runtime.get(child).metadata assert metadata['completion_contract'] == 1 assert metadata['recovery']['reauthorization']['actor'] == 'owner' - assert renewal.runtime.store.actions(child) == [] and renewal.runtime.get(renewal.source).state == 'paused' + assert renewal.runtime.store.actions(child) == [] + assert renewal.runtime.get(renewal.source).state == 'paused' finally: server.stop() diff --git a/test/unit_test/headless/test_agent_completion_gui.py b/test/unit_test/headless/test_agent_completion_gui.py index 2ab8db658..ea3170fb9 100644 --- a/test/unit_test/headless/test_agent_completion_gui.py +++ b/test/unit_test/headless/test_agent_completion_gui.py @@ -30,8 +30,10 @@ def test_actions_preserve_exact_completion_review_without_creating_an_executable response['ownership'] = {'review': 'b' * 64} tab._present_result(response) approved = json.loads(tab._remainder_request.toPlainText()) - assert approved['task_id'] == 'source-task' and approved['snapshot'] == 'a' * 64 - assert 'spec' not in approved and approved['note'] == '' + assert approved['task_id'] == 'source-task' + assert approved['snapshot'] == 'a' * 64 + assert 'spec' not in approved + assert approved['note'] == '' approved['note'] = 'Reviewed independently' tab._remainder_request.setPlainText(json.dumps(approved)) actions['agent_completion_create']() diff --git a/test/unit_test/headless/test_agent_completion_handoff.py b/test/unit_test/headless/test_agent_completion_handoff.py index 9b4a079bc..ec11dfdcb 100644 --- a/test/unit_test/headless/test_agent_completion_handoff.py +++ b/test/unit_test/headless/test_agent_completion_handoff.py @@ -50,7 +50,9 @@ def forbidden(*_args, **_kwargs): assert authorization['approved_root_count'] == 1 assert completed.old.identifier in authorization['replaced_origins'] public = json.dumps([review, grant]) - assert 'store_path' not in public and 'arguments' not in public and str(completed.reports) not in public + assert 'store_path' not in public + assert 'arguments' not in public + assert str(completed.reports) not in public with authorization_scope(completed.reviewer): assert runtime.recovery.control('create_handoff', request)['handoff']['id'] == grant['id'] with pytest.raises(AgentTaskError, match='another caller'): @@ -68,8 +70,10 @@ def forbidden(*_args, **_kwargs): validation = {'batch_id': completed.batch_id, 'node_id': 'a', 'attempt': started['attempt']} assert runtime.batches.control('validate_node', validation)['outcome'] == 'completed' assert runtime.get(completed.source).state == 'paused' - assert runtime.store.actions(completed.source) == before and runtime.store.actions(completed.child) == [] - assert completed.manifest.read_bytes() == manifest and old_path.read_bytes() == old_bytes + assert runtime.store.actions(completed.source) == before + assert runtime.store.actions(completed.child) == [] + assert completed.manifest.read_bytes() == manifest + assert old_path.read_bytes() == old_bytes runtime.recovery.control('revoke_handoff', {'handoff_id': grant['id']}) with pytest.raises(AgentTaskError): runtime.batches.control('validate_node', validation) diff --git a/test/unit_test/headless/test_agent_completion_handoff_gui.py b/test/unit_test/headless/test_agent_completion_handoff_gui.py index d56bb93e5..89c05e0a7 100644 --- a/test/unit_test/headless/test_agent_completion_handoff_gui.py +++ b/test/unit_test/headless/test_agent_completion_handoff_gui.py @@ -28,7 +28,8 @@ def test_existing_handoff_action_and_result_keep_the_renewed_review_explicit(mon 'approved_root_count': 1, 'replaced_origins': ['expired-origin']}}} tab._completed(SimpleNamespace(task_id='review', status='ok', value=result)) assert json.loads(tab._output.toPlainText()) == result - assert json.loads(tab._handoff_request.toPlainText()) == request and len(requests) == 1 + assert json.loads(tab._handoff_request.toPlainText()) == request + assert len(requests) == 1 finally: tab.close() shiboken6.delete(tab) diff --git a/test/unit_test/headless/test_agent_completion_handoff_lifecycle.py b/test/unit_test/headless/test_agent_completion_handoff_lifecycle.py index b2cf34068..a9de02d52 100644 --- a/test/unit_test/headless/test_agent_completion_handoff_lifecycle.py +++ b/test/unit_test/headless/test_agent_completion_handoff_lifecycle.py @@ -23,7 +23,8 @@ def test_real_reader_chain_keeps_successful_intermediate_readers_and_sixteen_lin assert len(review['evidence']['segments']) == count reply, chain = completed.runtime.recovery.handoff_evidence(completed.batch_id, 'a', completed.source, completed.child, grant['id']) - assert reply['state'] == 'succeeded' and len(chain) == count + assert reply['state'] == 'succeeded' + assert len(chain) == count assert all(not completed.runtime.store.actions(item['task_id']) for item in chain) @@ -34,7 +35,8 @@ def test_existing_renewed_grant_survives_real_runtime_restart(completed): try: reply, _chain = reopened.recovery.handoff_evidence(completed.batch_id, 'a', completed.source, completed.child, grant['id']) - assert reply['state'] == 'succeeded' and reopened.get(completed.source).state == 'paused' + assert reply['state'] == 'succeeded' + assert reopened.get(completed.source).state == 'paused' with pytest.raises(AgentTaskError, match='another caller'): reopened.get(completed.child) finally: diff --git a/test/unit_test/headless/test_agent_completion_handoff_mixed.py b/test/unit_test/headless/test_agent_completion_handoff_mixed.py index 6fe6d2c41..465d96314 100644 --- a/test/unit_test/headless/test_agent_completion_handoff_mixed.py +++ b/test/unit_test/headless/test_agent_completion_handoff_mixed.py @@ -37,7 +37,8 @@ def test_mixed_executable_and_renewed_reader_chain_adopts_all_original_confirmed _review, _request, grant = issue(mixed) reply, chain = mixed.runtime.recovery.handoff_evidence(mixed.batch_id, 'a', mixed.source, mixed.child, grant['id']) - assert reply['state'] == 'succeeded' and len(chain) == 2 + assert reply['state'] == 'succeeded' + assert len(chain) == 2 assert len(mixed.runtime.store.actions(mixed.source)) == 1 assert len(mixed.runtime.store.actions(mixed.execution_child)) == 1 assert mixed.runtime.store.actions(mixed.child) == [] diff --git a/test/unit_test/headless/test_agent_completion_handoff_surfaces.py b/test/unit_test/headless/test_agent_completion_handoff_surfaces.py index 223dedc06..e748f74aa 100644 --- a/test/unit_test/headless/test_agent_completion_handoff_surfaces.py +++ b/test/unit_test/headless/test_agent_completion_handoff_surfaces.py @@ -32,7 +32,8 @@ def test_shared_surfaces_review_issue_inspect_and_revoke_the_exact_renewed_reade assert preview['evidence']['completion_authorization']['completion_task'] == completed.child grant = invoke(surface, connection, tmp_path, 'create_handoff', {**request_for(completed), 'review': preview['handoff_review'], 'note': 'Explicit current read-only evidence handoff'})['handoff'] - assert grant['evidence_only'] is True and grant['input_authorized'] is False + assert grant['evidence_only'] is True + assert grant['input_authorized'] is False listed = invoke(surface, connection, tmp_path, 'list_handoffs', {'batch_id': completed.batch_id, 'node_id': 'a'}) assert [item['id'] for item in listed['handoffs']] == [grant['id']] diff --git a/test/unit_test/headless/test_agent_completion_recovery.py b/test/unit_test/headless/test_agent_completion_recovery.py index 2a5eaa364..78b2c8324 100644 --- a/test/unit_test/headless/test_agent_completion_recovery.py +++ b/test/unit_test/headless/test_agent_completion_recovery.py @@ -43,7 +43,8 @@ def forbidden(*_args, **_kwargs): def approval(value, task_id=None): identifier = task_id or value.task_id review = value.runtime.recovery.control('preview_completion', {'task_id': identifier}) - assert review['approval_required'] is True and review['source_completion_inherited'] is False + assert review['approval_required'] is True + assert review['source_completion_inherited'] is False return {'task_id': identifier, 'snapshot': review['snapshot'], 'note': 'Reviewed confirmed effects and criteria'} @@ -55,14 +56,17 @@ def test_reviewed_completion_verifies_fresh_file_without_replaying_a_confirmed_a runtime, source = completed.runtime, completed.task_id historical = runtime.store.actions(source) ordinary = runtime.recovery.control('preview', {'task_id': source}) - assert ordinary['draft'] is None and 'no_remaining_actions' in ordinary['issues'] + assert ordinary['draft'] is None + assert 'no_remaining_actions' in ordinary['issues'] identifier = child(completed) result = runtime.finish(identifier) assert result.state == 'succeeded' - assert result.metadata['input_released'] is True and result.metadata['completion_contract'] == 1 + assert result.metadata['input_released'] is True + assert result.metadata['completion_contract'] == 1 assert [item['status'] for item in result.verification] == ['passed', 'passed'] assert runtime.store.actions(identifier) == [] - assert runtime.get(source).state == 'paused' and runtime.store.actions(source) == historical + assert runtime.get(source).state == 'paused' + assert runtime.store.actions(source) == historical def test_source_changes_during_reader_retirement_cannot_publish_stale_success(completed, monkeypatch): @@ -75,7 +79,8 @@ def changed(adapter): with pytest.raises(AgentTaskError, match='snapshot'): runtime.finish(identifier) result = runtime.get(identifier) - assert result.state != 'succeeded' and result.metadata['completion_contract'] == 0 + assert result.state != 'succeeded' + assert result.metadata['completion_contract'] == 0 def test_observe_then_finish_reuses_the_same_readonly_authority_without_reconfiguration(completed): @@ -84,7 +89,8 @@ def test_observe_then_finish_reuses_the_same_readonly_authority_without_reconfig assert frame.data['identity'] == 'local-files' assert runtime.get(identifier).metadata['input_released'] is False result = runtime.finish(identifier) - assert result.state == 'succeeded' and result.metadata['input_released'] is True + assert result.state == 'succeeded' + assert result.metadata['input_released'] is True assert runtime.store.actions(identifier) == [] diff --git a/test/unit_test/headless/test_agent_completion_security.py b/test/unit_test/headless/test_agent_completion_security.py index 9289bdd16..6935d5bd4 100644 --- a/test/unit_test/headless/test_agent_completion_security.py +++ b/test/unit_test/headless/test_agent_completion_security.py @@ -24,7 +24,8 @@ def changed(adapter): with pytest.raises(AgentTaskError, match='snapshot'): runtime.finish(identifier) result = runtime.get(identifier) - assert result.state == 'waiting_user' and result.metadata['input_released'] is True + assert result.state == 'waiting_user' + assert result.metadata['input_released'] is True assert result.metadata['completion_contract'] == 0 @@ -50,7 +51,8 @@ def test_fresh_criteria_fail_then_resume_reads_current_files_without_source_repl runtime, identifier = completed.runtime, child(completed) completed.output.write_text('missing marker', encoding='utf-8') result = runtime.finish(identifier) - assert result.state == 'waiting_user' and result.metadata['input_released'] is True + assert result.state == 'waiting_user' + assert result.metadata['input_released'] is True assert [item['status'] for item in result.verification] == ['passed', 'failed'] completed.output.write_text('complete', encoding='utf-8') runtime.resume(identifier) @@ -84,7 +86,8 @@ def cancelled(adapter): with pytest.raises(CancelledError): runtime.finish(identifier) result = runtime.get(identifier) - assert result.state == 'cancelled' and result.metadata['input_released'] is True + assert result.state == 'cancelled' + assert result.metadata['input_released'] is True assert result.metadata['completion_contract'] == 0 @@ -100,7 +103,8 @@ def test_restart_requires_explicit_resume_and_new_independent_evidence(completed restored.finish(identifier) restored.resume(identifier) result = restored.finish(identifier) - assert result.state == 'waiting_user' and result.metadata['completion_contract'] == 0 + assert result.state == 'waiting_user' + assert result.metadata['completion_contract'] == 0 assert result.metadata['input_released'] is True finally: restored.close() @@ -143,9 +147,11 @@ def test_cancelled_readonly_child_can_only_create_another_reviewed_readonly_succ runtime.cancel(identifier) retry = child(completed, identifier) result = runtime.finish(retry) - assert result.state == 'succeeded' and result.metadata['completion_review']['effect_task'] == completed.task_id + assert result.state == 'succeeded' + assert result.metadata['completion_review']['effect_task'] == completed.task_id assert result.metadata['recovery']['source_task'] == identifier - assert runtime.get(identifier).state == 'cancelled' and runtime.store.actions(retry) == [] + assert runtime.get(identifier).state == 'cancelled' + assert runtime.store.actions(retry) == [] @pytest.mark.parametrize('revoked', ['owner', 'reviewer']) @@ -171,5 +177,6 @@ def test_source_owned_completion_keeps_both_principals_live_during_maintenance(c users.set_role(revoked, 'viewer') runtime.maintain() result = runtime.get(identifier) - assert result.state == 'cancelled' and result.metadata['input_released'] is True + assert result.state == 'cancelled' + assert result.metadata['input_released'] is True assert result.metadata['completion_contract'] == 0 diff --git a/test/unit_test/headless/test_agent_completion_surfaces.py b/test/unit_test/headless/test_agent_completion_surfaces.py index 53944667e..ce0ba13a4 100644 --- a/test/unit_test/headless/test_agent_completion_surfaces.py +++ b/test/unit_test/headless/test_agent_completion_surfaces.py @@ -79,4 +79,5 @@ def test_fenced_dag_adopts_readonly_successor_without_replaying_the_last_action( approved['note'] = 'Reviewed independent completion after the fenced finite action' result = run_dag(definition, batch_id=batch['batch_id'], recovery=approved) assert result.succeeded, result.to_dict() - assert runtime.get(source).state == 'paused' and runtime.store.actions(successor) == [] + assert runtime.get(source).state == 'paused' + assert runtime.store.actions(successor) == [] diff --git a/test/unit_test/headless/test_agent_crash_recovery.py b/test/unit_test/headless/test_agent_crash_recovery.py index 684fb4baa..f0f663e2a 100644 --- a/test/unit_test/headless/test_agent_crash_recovery.py +++ b/test/unit_test/headless/test_agent_crash_recovery.py @@ -22,7 +22,8 @@ def test_unfinished_host_ownership_requires_explicit_recovery(tmp_path): replacement.acquire() probes = [] result = replacement.recover("Operator released held inputs and reviewed effects", lambda: probes.append(1), "host") - assert result["recovered"] and probes == [1] + assert result["recovered"] + assert probes == [1] assert replacement.read()["held"] == {} replacement.acquire() replacement.release() @@ -74,10 +75,12 @@ def test_durable_witness_is_written_before_native_ack(tmp_path): runtime.act(task.task_id, {"tool": "AC_increment", "arguments": {"hold": True}, "observation_id": frame.observation_id}) data = json.loads((tmp_path / "input.lock.journal").read_text(encoding="utf-8")) - assert data["owner"] and data["held"]["keys"] == [{"keycode": 65, "is_shift": False}] + assert data["owner"] + assert data["held"]["keys"] == [{"keycode": 65, "is_shift": False}] runtime.pause(task.task_id) data = json.loads((tmp_path / "input.lock.journal").read_text(encoding="utf-8")) - assert not data["owner"] and not data["held"] + assert not data["owner"] + assert not data["held"] finally: runtime.close() diff --git a/test/unit_test/headless/test_agent_dag_background.py b/test/unit_test/headless/test_agent_dag_background.py index 6cd186915..a232f9c02 100644 --- a/test/unit_test/headless/test_agent_dag_background.py +++ b/test/unit_test/headless/test_agent_dag_background.py @@ -50,8 +50,10 @@ def test_service_runs_without_any_default_client_connection_file(service, monkey accepted = submit(client, batch, definition) assert accepted["background"]["state"] in {"new", "in_progress", "success"} result = until(lambda: finished(instance, batch)) - assert result["state"] == "succeeded" and result["background"]["state"] == "success" - assert target.count == 2 and all(node["phase"] == "confirmed" for node in result["nodes"]) + assert result["state"] == "succeeded" + assert result["background"]["state"] == "success" + assert target.count == 2 + assert all(node["phase"] == "confirmed" for node in result["nodes"]) with instance.runtime.store.connection() as connection: data = json.loads(connection.execute("SELECT data FROM work_items WHERE queue='agent_dag'").fetchone()[0]) assert data["started"]["max_parallel"] == 2 @@ -67,7 +69,8 @@ def test_admin_dispatch_refreshes_actor_but_destination_tasks_belong_to_original with authorization_scope(AuthorizationContext("reviewer", "admin")): submit(client, batch, graph()) result = until(lambda: finished(instance, batch)) - assert result["state"] == "succeeded" and target.count == 2 + assert result["state"] == "succeeded" + assert target.count == 2 for node in result["nodes"]: assert instance.runtime.store.get(node["receipt"]["task_id"])["owner"]["user_id"] == "alice" @@ -78,7 +81,8 @@ def test_approved_continuation_runs_in_background_without_redispatching_complete approved = client.call("dag", {"operation": "approve_continuation", "request": request}) submit(client, batch, definition, approval_id=approved["approval_id"]) result = until(lambda: finished(instance, batch)) - assert result["state"] == "succeeded" and target.count == 2 + assert result["state"] == "succeeded" + assert target.count == 2 assert result["continuations"][0]["state"] == "used" with pytest.raises(AgentTaskError, match="consumed"): submit(client, batch, definition, approval_id=approved["approval_id"]) @@ -90,7 +94,8 @@ def test_failed_queue_acceptance_fences_attempt_without_input(service, monkeypat monkeypatch.setattr(instance._dag_jobs.queue, "add", Mock(side_effect=AgentTaskError("fixture queue failure"))) with pytest.raises(AgentTaskError, match="fixture queue failure"): submit(client, batch, graph()) - assert read(instance, batch)["state"] == "waiting_review" and target.count == 0 + assert read(instance, batch)["state"] == "waiting_review" + assert target.count == 0 def test_background_requires_an_explicit_service_and_never_runs_on_import(tmp_path): @@ -120,11 +125,14 @@ def test_shutdown_and_restart_do_not_replay_a_queued_delivery_or_reset_a_claim(s try: restarted.start() record = read(restarted, batch) - assert record["state"] == "waiting_review" and record["background"]["state"] == "failed" - assert record["nodes"][0]["phase"] == "claimed" and target.count == 0 + assert record["state"] == "waiting_review" + assert record["background"]["state"] == "failed" + assert record["nodes"][0]["phase"] == "claimed" + assert target.count == 0 inspected = restarted.runtime.batches.control("review_continuation", { "batch_id": batch["batch_id"], "definition": graph()}) - assert not inspected["can_approve"] and target.count == 0 + assert not inspected["can_approve"] + assert target.count == 0 finally: restarted.close() @@ -153,7 +161,8 @@ def delayed(worker): users.set_role(revoked, "viewer") proceed.set() result = until(lambda: finished(instance, batch)) - assert result["state"] == "waiting_review" and target.count == 0 + assert result["state"] == "waiting_review" + assert target.count == 0 assert all(node["phase"] == "pending" for node in result["nodes"]) finally: proceed.set() @@ -177,7 +186,8 @@ def delayed(worker): client.call("stop_all", {}) proceed.set() result = until(lambda: finished(instance, batch)) - assert result["state"] == "waiting_review" and target.count == 0 + assert result["state"] == "waiting_review" + assert target.count == 0 finally: proceed.set() @@ -197,10 +207,12 @@ def test_service_background_keeps_local_ownership_and_never_forwards_it_to_remot batch = client.call("dag", {"operation": "register", "request": {"definition": definition}}) submit(client, batch, definition) result = until(lambda: finished(local, batch)) - assert result["state"] == "succeeded" and target.count == remote_target.count == 1 + assert result["state"] == "succeeded" + assert target.count == remote_target.count == 1 local_row = local.runtime.store.get(result["nodes"][0]["receipt"]["task_id"]) remote_row = remote.runtime.store.get(result["nodes"][1]["receipt"]["task_id"]) - assert local_row["owner"]["user_id"] == "source-admin" and remote_row["owner"] == {} + assert local_row["owner"]["user_id"] == "source-admin" + assert remote_row["owner"] == {} assert "origin_policies" not in remote_row["spec"]["options"] finally: remote.close() diff --git a/test/unit_test/headless/test_agent_dag_background_crash.py b/test/unit_test/headless/test_agent_dag_background_crash.py index d004191ba..d2bf4705b 100644 --- a/test/unit_test/headless/test_agent_dag_background_crash.py +++ b/test/unit_test/headless/test_agent_dag_background_crash.py @@ -46,11 +46,14 @@ def test_process_death_retires_old_delivery_and_preserves_unknown_claim(tmp_path try: service.start() result = service.runtime.batches.control('get', {'batch_id': batch['batch_id']}) - assert result['state'] == 'waiting_review' and result['background']['state'] == 'failed' - assert result['nodes'][0]['phase'] == 'claimed' and service.runtime.list() == [] + assert result['state'] == 'waiting_review' + assert result['background']['state'] == 'failed' + assert result['nodes'][0]['phase'] == 'claimed' + assert service.runtime.list() == [] review = service.runtime.batches.control('review_continuation', { 'batch_id': batch['batch_id'], 'definition': graph()}) - assert not review['can_approve'] and review['decisions'][0]['action'] == 'wait' + assert not review['can_approve'] + assert review['decisions'][0]['action'] == 'wait' finally: service.close() finally: diff --git a/test/unit_test/headless/test_agent_dag_background_gui.py b/test/unit_test/headless/test_agent_dag_background_gui.py index e0a96ddac..36a869410 100644 --- a/test/unit_test/headless/test_agent_dag_background_gui.py +++ b/test/unit_test/headless/test_agent_dag_background_gui.py @@ -57,7 +57,8 @@ def accepted_and_view_worker_finished(): tab.close() proceed.set() result = until(lambda: finished(instance, batch)) - assert result["state"] == "succeeded" and target.count == 2 + assert result["state"] == "succeeded" + assert target.count == 2 finally: proceed.set() tab.close() diff --git a/test/unit_test/headless/test_agent_dag_batch_loopback.py b/test/unit_test/headless/test_agent_dag_batch_loopback.py index fa5182515..63ee225b3 100644 --- a/test/unit_test/headless/test_agent_dag_batch_loopback.py +++ b/test/unit_test/headless/test_agent_dag_batch_loopback.py @@ -52,7 +52,8 @@ def test_bound_graph_executes_once_and_independent_receipts_release_dependencies result = run_dag(definition, batch_id=registered["batch_id"]) assert result.succeeded, result.to_dict() batch = client.call("dag", {"operation": "get", "request": {"batch_id": registered["batch_id"]}}) - assert batch["state"] == "succeeded" and target.count == 2 + assert batch["state"] == "succeeded" + assert target.count == 2 assert all(node["phase"] == "confirmed" for node in batch["nodes"]) for node in batch["nodes"]: task = instance.runtime.store.get(node["receipt"]["task_id"]) @@ -82,7 +83,8 @@ def lost_reply(operation, body, timeout): monkeypatch.setattr(managed_tasks, "_connection", connection) result = run_dag(graph(), batch_id=registered["batch_id"]) - assert not result.succeeded and target.performed.wait(5) + assert not result.succeeded + assert target.performed.wait(5) batch = client.call("dag", {"operation": "get", "request": {"batch_id": registered["batch_id"]}}) assert batch["state"] == "waiting_review" assert [node["phase"] for node in batch["nodes"]] == ["unknown", "pending"] @@ -120,7 +122,8 @@ def test_two_host_batch_tags_match_without_forwarding_local_principal_or_origins assert metadata["token"] not in str(saved) remote_row = remote.runtime.store.get(result.nodes["b"].result["task_id"]) local_row = local.runtime.store.get(result.nodes["a"].result["task_id"]) - assert remote_row["owner"] == {} and local_row["owner"]["user_id"] == "local-admin" + assert remote_row["owner"] == {} + assert local_row["owner"]["user_id"] == "local-admin" assert "origin_policies" not in remote_row["spec"]["options"] assert remote_row["spec"]["options"]["dag_batch"]["batch_id"] == registered["batch_id"] finally: diff --git a/test/unit_test/headless/test_agent_dag_batch_surfaces.py b/test/unit_test/headless/test_agent_dag_batch_surfaces.py index b8fa259db..50bfd6ef9 100644 --- a/test/unit_test/headless/test_agent_dag_batch_surfaces.py +++ b/test/unit_test/headless/test_agent_dag_batch_surfaces.py @@ -27,11 +27,13 @@ def test_versioned_api_and_catalog_expose_the_same_managed_batch_protocol(): from je_auto_control.utils.agent_runtime.commands import CATALOG assert root.manage_agent_dag is api.manage_agent_dag is core.manage_agent_dag function, fields, required, _read_only, _host_management = CATALOG["AC_agent_dag"] - assert function is root.manage_agent_dag and required == ("operation",) + assert function is root.manage_agent_dag + assert required == ("operation",) assert fields["operation"]["enum"] == list(OPERATIONS) for operation in OPERATIONS: parsed = build_parser().parse_args(["agent-task", "dag", operation, "request.json"]) - assert parsed.dag_operation == operation and parsed.request == "request.json" + assert parsed.dag_operation == operation + assert parsed.request == "request.json" def test_gui_registers_only_on_action_and_discards_graph_or_batch_selection_changes(monkeypatch): @@ -52,7 +54,8 @@ def test_gui_registers_only_on_action_and_discards_graph_or_batch_selection_chan tab._inspection_source = tab._editor.toPlainText() tab.setProperty("dag_batch_source", "") tab._on_batch_finished({"batch_id": "registered", "nodes": []}) - assert tab._batch_id.text() == "registered" and len(requests) == 1 + assert tab._batch_id.text() == "registered" + assert len(requests) == 1 tab._batch_id.setText("other-batch") tab._on_batch_finished({"batch_id": "late-old", "nodes": []}) assert tab._batch_id.text() == "other-batch" diff --git a/test/unit_test/headless/test_agent_dag_batches.py b/test/unit_test/headless/test_agent_dag_batches.py index 973f5d0e5..f0fc45048 100644 --- a/test/unit_test/headless/test_agent_dag_batches.py +++ b/test/unit_test/headless/test_agent_dag_batches.py @@ -27,7 +27,8 @@ def runtime(tmp_path): def test_registered_batch_is_durable_and_does_not_dispatch(runtime): value = runtime.batches.control("register", {"definition": graph()}) - assert value["state"] == "registered" and runtime.list() == [] + assert value["state"] == "registered" + assert runtime.list() == [] assert value["definition"]["nodes"][1]["depends_on"] == ["a"] assert value["resume_permitted"] is False assert runtime.batches.control("get", {"batch_id": value["batch_id"]}) == value @@ -135,7 +136,8 @@ def test_claim_survives_restart_and_never_becomes_proof_of_non_delivery(runtime) restored = AgentRuntime(runtime.store.path, targets={"fixture": object()}) try: current = restored.batches.control("get", {"batch_id": value["batch_id"]}) - assert current["state"] == "waiting_review" and current["nodes"][0]["phase"] == "claimed" + assert current["state"] == "waiting_review" + assert current["nodes"][0]["phase"] == "claimed" assert not current["resume_permitted"] with pytest.raises(AgentTaskError, match="inactive"): restored.batches.control("claim", {"batch_id": value["batch_id"], diff --git a/test/unit_test/headless/test_agent_dag_connection_binding.py b/test/unit_test/headless/test_agent_dag_connection_binding.py index ae29149a2..9eab0d5f0 100644 --- a/test/unit_test/headless/test_agent_dag_connection_binding.py +++ b/test/unit_test/headless/test_agent_dag_connection_binding.py @@ -32,7 +32,9 @@ def after_first_record(self, operation, body=None, **kwargs): monkeypatch.setattr(AgentRuntimeClient, "call", after_first_record) result = run_dag(graph(), batch_id=batch["batch_id"]) assert result.succeeded, result.to_dict() - assert target.count == 2 and other_target.count == 0 and other.runtime.list() == [] + assert target.count == 2 + assert other_target.count == 0 + assert other.runtime.list() == [] assert source.runtime.batches.control("get", {"batch_id": batch["batch_id"]})["state"] == "succeeded" finally: other.close() @@ -61,7 +63,9 @@ def after_first_record(self, operation, body=None, **kwargs): batch = client.call("dag", {"operation": "register", "request": {"definition": graph()}}) monkeypatch.setattr(AgentRuntimeClient, "call", after_first_record) result = run_dag(graph(), batch_id=batch["batch_id"]) - assert not result.succeeded and target.count == 1 and other_target.count == 0 + assert not result.succeeded + assert target.count == 1 + assert other_target.count == 0 assert other.runtime.list() == [] saved = source.runtime.batches.control("get", {"batch_id": batch["batch_id"]}) assert [row["phase"] for row in saved["nodes"]] == ["confirmed", "pending"] @@ -88,7 +92,8 @@ def test_admin_inspection_uses_original_owners_keys_on_the_owning_runtime(servic monkeypatch.setattr("je_auto_control.utils.agent_runtime.client.default_connection_path", lambda: other.directory / "agent_runtime.json") result = client.call("dag", {"operation": "inspect", "request": {"batch_id": batch["batch_id"]}}) - assert target.count == 2 and other.runtime.list() == [] + assert target.count == 2 + assert other.runtime.list() == [] assert all(node["recorded_completion"] is True for node in result["nodes"]) assert all(node["request_match"] == "matches" for node in result["nodes"]) finally: diff --git a/test/unit_test/headless/test_agent_dag_continuation.py b/test/unit_test/headless/test_agent_dag_continuation.py index b89c14740..482db73ca 100644 --- a/test/unit_test/headless/test_agent_dag_continuation.py +++ b/test/unit_test/headless/test_agent_dag_continuation.py @@ -32,7 +32,8 @@ def after_first_record(self, operation, body=None, **kwargs): monkeypatch.setattr(AgentRuntimeClient, "call", after_first_record) result = run_dag(definition, batch_id=batch["batch_id"], stop_event=stop) - assert not result.succeeded and target.count == 1 + assert not result.succeeded + assert target.count == 1 return client, instance, target, batch, definition @@ -49,8 +50,10 @@ def approval(value): def test_explicit_whole_graph_continuation_adopts_parent_and_dispatches_only_pending_child(stopped): client, _instance, target, batch, definition = stopped value = review(client, batch, definition) - assert value["can_approve"] and [item["action"] for item in value["decisions"]] == ["adopt", "dispatch"] - assert target.count == 1 and not value["resume_permitted"] + assert value["can_approve"] + assert [item["action"] for item in value["decisions"]] == ["adopt", "dispatch"] + assert target.count == 1 + assert not value["resume_permitted"] request = approval(value) recorded = client.call("dag", {"operation": "approve_continuation", "request": request}) assert target.count == 1 @@ -73,7 +76,8 @@ def test_lookup_absence_never_turns_a_claimed_node_back_into_dispatch(service): "batch_id": batch["batch_id"], "attempt": started["attempt"], "node_id": "a"}}) client.call("dag", {"operation": "pause_batch", "request": {"batch_id": batch["batch_id"]}}) value = review(client, batch, definition) - assert not value["can_approve"] and value["decisions"][0]["action"] == "wait" + assert not value["can_approve"] + assert value["decisions"][0]["action"] == "wait" value["decisions"][0] = {"node_id": "a", "action": "dispatch", "spec": definition["nodes"][0]["task"]["spec"]} with pytest.raises(AgentTaskError, match="evidence or decisions changed"): client.call("dag", {"operation": "approve_continuation", "request": approval(value)}) @@ -158,14 +162,16 @@ def test_successor_adoption_uses_real_recovery_provenance_and_fresh_completion(s "max_parallel": 4}}) result = client.call("dag", {"operation": "validate_node", "request": { "batch_id": batch["batch_id"], "attempt": begun["attempt"], "node_id": "a"}}) - assert result["task_id"] == child and target.count == 2 + assert result["task_id"] == child + assert target.count == 2 unrelated = instance.runtime.submit(graph()["nodes"][1]["task"]["spec"]) assert run_task(instance.runtime, unrelated.task_id).state == "succeeded" client.call("dag", {"operation": "pause_batch", "request": {"batch_id": batch["batch_id"]}}) value = review(client, batch, definition) value["decisions"][0] = {"node_id": "a", "action": "successor", "task_id": unrelated.task_id} value = review(client, batch, definition, decisions=value["decisions"]) - assert not value["can_approve"] and target.count == 3 + assert not value["can_approve"] + assert target.count == 3 def test_expired_origin_can_be_replaced_only_for_never_dispatched_scoped_work(service, monkeypatch, tmp_path): @@ -200,4 +206,5 @@ def after_first(self, operation, body=None, **kwargs): result = run_dag(definition, batch_id=batch["batch_id"], recovery=approval(value)) assert result.succeeded, result.to_dict() child = instance.runtime.store.get(result.nodes["b"].result["task_id"]) - assert child["spec"]["roots"] == [str(narrow)] and target.count == 2 + assert child["spec"]["roots"] == [str(narrow)] + assert target.count == 2 diff --git a/test/unit_test/headless/test_agent_dag_continuation_guards.py b/test/unit_test/headless/test_agent_dag_continuation_guards.py index 0578d3291..1c6baa6fb 100644 --- a/test/unit_test/headless/test_agent_dag_continuation_guards.py +++ b/test/unit_test/headless/test_agent_dag_continuation_guards.py @@ -43,7 +43,8 @@ def test_lost_adoption_evidence_after_start_cannot_publish_false_batch_success(s "batch_id": batch["batch_id"], "attempt": started["attempt"], "node_id": "a"}}) finished = client.call("dag", {"operation": "finish", "request": { "batch_id": batch["batch_id"], "attempt": started["attempt"]}}) - assert finished["state"] == "waiting_review" and finished["nodes"][0]["phase"] == "unknown" + assert finished["state"] == "waiting_review" + assert finished["nodes"][0]["phase"] == "unknown" assert target.count == 1 @@ -61,7 +62,8 @@ def consume(_index): with ThreadPoolExecutor(max_workers=2) as workers: results = list(workers.map(consume, (0, 1))) - assert sum(value is not None for value in results) == 1 and target.count == 1 + assert sum(value is not None for value in results) == 1 + assert target.count == 1 def test_another_admin_cannot_reuse_an_actors_review_and_audit_keeps_the_real_actor(stopped): @@ -73,7 +75,8 @@ def test_another_admin_cannot_reuse_an_actors_review_and_audit_keeps_the_real_ac approve(client, batch, definition) current = client.call("dag", {"operation": "get", "request": {"batch_id": batch["batch_id"]}}) assert current["continuations"][0]["actor"] == "reviewer" - assert current["continuations"][0]["note"] and target.count == 1 + assert current["continuations"][0]["note"] + assert target.count == 1 @pytest.mark.parametrize("fault", ["missing", "duplicate", "unknown", "extra", "null"]) @@ -112,7 +115,8 @@ def test_tagged_submission_witness_is_atomic_and_legacy_retries_never_backfill(s connection.execute("DROP TRIGGER fail_admission") task = instance.runtime.submit(data, idempotency_key="tagged") metadata = instance.runtime.get(task.task_id).metadata - assert metadata["submission_contract"] == 1 and metadata["submitted_spec_digest"] == submitted_digest(data) + assert metadata["submission_contract"] == 1 + assert metadata["submitted_spec_digest"] == submitted_digest(data) legacy = instance.runtime._create_task(instance.runtime._validated_spec(data), "legacy-tagged") assert instance.runtime.submit(data, idempotency_key="legacy-tagged").task_id == legacy.task_id assert "submission_contract" not in instance.runtime.get(legacy.task_id).metadata @@ -127,4 +131,5 @@ def test_fencing_a_started_continuation_rejects_its_next_claim(stopped): client.call("dag", {"operation": "claim", "request": { "batch_id": batch["batch_id"], "attempt": started["attempt"], "node_id": "b"}}) current = client.call("dag", {"operation": "get", "request": {"batch_id": batch["batch_id"]}}) - assert current["nodes"][1]["phase"] == "pending" and target.count == 1 + assert current["nodes"][1]["phase"] == "pending" + assert target.count == 1 diff --git a/test/unit_test/headless/test_agent_dag_continuation_gui.py b/test/unit_test/headless/test_agent_dag_continuation_gui.py index d9999bb88..bbc7d7ef4 100644 --- a/test/unit_test/headless/test_agent_dag_continuation_gui.py +++ b/test/unit_test/headless/test_agent_dag_continuation_gui.py @@ -29,7 +29,9 @@ def test_review_and_run_actions_preserve_source_selection_and_do_not_auto_execut tab._on_batch_finished({"batch_id": "batch-a", "definition": graph(), "snapshot": "a" * 64, "decisions": [{"node_id": "a", "action": "wait"}], "nodes": []}) request = json.loads(tab._continuation_request.toPlainText()) - assert request["note"] == "" and tab._editor.toPlainText() == ordinary and dispatched == [] + assert request["note"] == "" + assert tab._editor.toPlainText() == ordinary + assert dispatched == [] actions["dag_continuation_run_btn"]() assert dispatched.pop()[1] == {"inspect_only": False, "batch_operation": "run_continuation"} tab._batch_id.setText("batch-b") diff --git a/test/unit_test/headless/test_agent_dag_inspection.py b/test/unit_test/headless/test_agent_dag_inspection.py index be1b2a1c8..2e3cf79a9 100644 --- a/test/unit_test/headless/test_agent_dag_inspection.py +++ b/test/unit_test/headless/test_agent_dag_inspection.py @@ -25,13 +25,17 @@ def call(operation, body, timeout): monkeypatch.setattr(managed_tasks, "_connection", connection) result = inspect_agent_dag(definition()) - assert result["inspection_only"] is True and result["resume_permitted"] is False + assert result["inspection_only"] is True + assert result["resume_permitted"] is False first, second = result["nodes"] - assert first["task_id"] == "task-one" and first["lookup"] == "found" - assert first["recorded_completion"] is True and first["request_match"] == "unverified" + assert first["task_id"] == "task-one" + assert first["lookup"] == "found" + assert first["recorded_completion"] is True + assert first["request_match"] == "unverified" assert second["lookup"] == "not_managed" assert "private-remote-path" not in str(result) - assert len(calls) == 1 and calls[0][0:2] == ("lookup", {"idempotency_key": "reviewed-one"}) + assert len(calls) == 1 + assert calls[0][0:2] == ("lookup", {"idempotency_key": "reviewed-one"}) assert 0 < calls[0][2] <= 5 @@ -195,12 +199,16 @@ def request(url, **kwargs): with authorization_scope(AuthorizationContext("local-admin", "admin")): result = inspect_agent_dag(graph) first = result["nodes"][0] - assert first["task_id"] == accepted.task_id and first["recorded_completion"] is True - assert first["request_match"] == "differs" and result["resume_permitted"] is False - assert len(calls) == 2 and all(call[0].endswith("/agent/lookup") for call in calls) + assert first["task_id"] == accepted.task_id + assert first["recorded_completion"] is True + assert first["request_match"] == "differs" + assert result["resume_permitted"] is False + assert len(calls) == 2 + assert all(call[0].endswith("/agent/lookup") for call in calls) assert calls[0][1]["body"] == {"idempotency_key": "reviewed-one"} assert set(calls[1][1]["body"]) == {"idempotency_key", "spec"} - assert target.calls == ["AC_increment"] and len(service.runtime.list()) == 1 + assert target.calls == ["AC_increment"] + assert len(service.runtime.list()) == 1 assert "history_path" not in str(result) finally: service.close() diff --git a/test/unit_test/headless/test_agent_dag_local_tasks.py b/test/unit_test/headless/test_agent_dag_local_tasks.py index 640eebea1..6c5733b56 100644 --- a/test/unit_test/headless/test_agent_dag_local_tasks.py +++ b/test/unit_test/headless/test_agent_dag_local_tasks.py @@ -64,8 +64,10 @@ def test_admin_caller_executes_all_nodes_under_original_owner_and_records_actual row = connection.execute("SELECT actor FROM agent_dag_local_tasks WHERE task_id=?", (task_id,)).fetchone() assert json.loads(row["actor"])["user_id"] == "reviewer" visible = instance.runtime.get(task_id).metadata["local_dag_admission"] - assert visible["actor"] == "reviewer" and visible["contract"] == 1 - assert "store_path" not in visible and "attempt" not in visible + assert visible["actor"] == "reviewer" + assert visible["contract"] == 1 + assert "store_path" not in visible + assert "attempt" not in visible def test_local_admission_is_idempotent_and_cannot_bind_an_unrelated_task(owned, monkeypatch): @@ -76,7 +78,8 @@ def test_local_admission_is_idempotent_and_cannot_bind_an_unrelated_task(owned, assert local(owned, started, "submit", submission(node)) == first with pytest.raises(AgentTaskError, match="identity or admitting actor"): local(owned, started, "get", {"task_id": "unrelated-task"}) - assert len(instance.runtime.list()) == 1 and target.count == 0 + assert len(instance.runtime.list()) == 1 + assert target.count == 0 @pytest.mark.parametrize("fault", ["goal", "key", "extra", "operation", "task_id"]) @@ -97,7 +100,8 @@ def test_local_transport_rejects_changed_contracts_and_unbounded_operations(owne operation, body = "get", {"task_id": []} with pytest.raises(AgentTaskError): local(owned, started, operation, body) - assert instance.runtime.list() == [] and target.count == 0 + assert instance.runtime.list() == [] + assert target.count == 0 def test_preexisting_request_without_admission_witness_is_never_backfilled(owned, monkeypatch): @@ -111,7 +115,8 @@ def test_preexisting_request_without_admission_witness_is_never_backfilled(owned with instance.runtime.store.connection() as connection: assert connection.execute("SELECT 1 FROM agent_dag_local_tasks WHERE task_id=?", (task.task_id,)).fetchone() is None - assert target.count == 0 and len(instance.runtime.list()) == 1 + assert target.count == 0 + assert len(instance.runtime.list()) == 1 def test_admission_failure_rolls_back_task_key_and_both_witnesses(owned, monkeypatch): @@ -154,7 +159,9 @@ def test_fenced_attempt_can_retire_only_its_admitted_task_after_original_owner_l with authorization_scope(actor): client.call("dag", {"operation": "pause_batch", "request": {"batch_id": batch["batch_id"]}}) paused = local(owned, started, "pause", {"task_id": task["task_id"]}) - assert paused["state"] == "paused" and paused["metadata"]["input_released"] is True and target.count == 0 + assert paused["state"] == "paused" + assert paused["metadata"]["input_released"] is True + assert target.count == 0 def test_maintenance_retires_lease_when_admin_loses_cross_owner_authority(owned, monkeypatch): @@ -170,7 +177,9 @@ def test_maintenance_retires_lease_when_admin_loses_cross_owner_authority(owned, # cancelling and a later one settles it. until(lambda: runtime.maintain() or runtime.get(task["task_id"]).state != "cancelling") result = runtime.get(task["task_id"]) - assert result.state == "cancelled" and result.metadata["input_released"] is True and target.count == 0 + assert result.state == "cancelled" + assert result.metadata["input_released"] is True + assert target.count == 0 def test_revocation_during_grounding_is_refused_before_the_target_input_call(owned, monkeypatch): @@ -191,4 +200,5 @@ def revoke_during_grounding(): with pytest.raises(AuthorizationError): instance.runtime.act(task["task_id"], {"tool": "AC_increment", "observation_id": frame.observation_id}) receipts = instance.runtime.store.actions(task["task_id"]) - assert target.count == 0 and [item["status"] for item in receipts] == ["failed"] + assert target.count == 0 + assert [item["status"] for item in receipts] == ["failed"] diff --git a/test/unit_test/headless/test_agent_dag_matching.py b/test/unit_test/headless/test_agent_dag_matching.py index 2153ffa7e..bc54a7836 100644 --- a/test/unit_test/headless/test_agent_dag_matching.py +++ b/test/unit_test/headless/test_agent_dag_matching.py @@ -62,7 +62,8 @@ def call(operation, body, _timeout): monkeypatch.setattr(managed_tasks, "_connection", lambda _host: call) result = inspect_agent_dag(definition()) assert result["nodes"][0]["request_match"] == "unverified" - assert len(calls) == 1 and set(calls[0][1]) == {"idempotency_key"} + assert len(calls) == 1 + assert set(calls[0][1]) == {"idempotency_key"} @pytest.mark.parametrize("changed", ["removed", "replaced"]) @@ -80,9 +81,12 @@ def call(operation, body, _timeout): monkeypatch.setattr(managed_tasks, "_connection", lambda _host: call) result = inspect_agent_dag(definition()) node = result["nodes"][0] - assert node["lookup"] == "unavailable" and node["request_match"] == "unverifiable" - assert node["recorded_completion"] is None and node["input_released"] is None - assert result["resume_permitted"] is False and calls == ["lookup", "lookup"] + assert node["lookup"] == "unavailable" + assert node["request_match"] == "unverifiable" + assert node["recorded_completion"] is None + assert node["input_released"] is None + assert result["resume_permitted"] is False + assert calls == ["lookup", "lookup"] def test_remote_matching_never_sends_local_origin_witnesses(monkeypatch): @@ -143,10 +147,12 @@ def test_real_destination_matches_the_reviewed_skill_without_repeating_effects(t changed["nodes"][0]["task"]["spec"]["goal"] = "changed reviewed goal" different = inspect_agent_dag(changed) first = result["nodes"][0] - assert first["request_match"] == "matches" and first["recorded_completion"] is True + assert first["request_match"] == "matches" + assert first["recorded_completion"] is True assert different["nodes"][0]["request_match"] == "differs" assert result["resume_permitted"] is False - assert target.calls == ["AC_increment"] and len(service.runtime.list()) == 1 + assert target.calls == ["AC_increment"] + assert len(service.runtime.list()) == 1 assert not service.runtime._leases finally: service.close() diff --git a/test/unit_test/headless/test_agent_dag_retention.py b/test/unit_test/headless/test_agent_dag_retention.py index 3169a54bb..2cf0e83cc 100644 --- a/test/unit_test/headless/test_agent_dag_retention.py +++ b/test/unit_test/headless/test_agent_dag_retention.py @@ -90,7 +90,8 @@ def test_completed_batch_expires_with_owned_evidence_and_completed_delivery(serv age(host.runtime, batch["batch_id"]) result = client.call("prune", {"keep_days": 30}) assert result["deleted_batches"] == [batch["batch_id"]] - assert set(result["deleted"]) == set(task_ids) and result["deleted_dag_deliveries"] == 1 + assert set(result["deleted"]) == set(task_ids) + assert result["deleted_dag_deliveries"] == 1 assert target.count == 2 with host.runtime.store.connection() as connection: for table in ("agent_dag_batches", "agent_dag_nodes", "agent_dag_inputs", "agent_dag_local_tasks"): @@ -153,7 +154,8 @@ def test_completed_batch_keeps_its_gate_when_related_work_is_unsettled(service, connection.execute("UPDATE agent_dag_nodes SET phase='unknown' WHERE batch_id=?", (batch["batch_id"],)) try: result = instance.prune() - assert result["deleted_batches"] == [] and result["deleted"] == [] + assert result["deleted_batches"] == [] + assert result["deleted"] == [] with instance.store.connection() as connection: assert connection.execute("SELECT 1 FROM agent_dag_local_tasks WHERE task_id=?", (task_id,)).fetchone() finally: @@ -198,5 +200,6 @@ def notice_lock(identifier): assert selected.wait(5) runtime.batches.control("begin", {"batch_id": batch["batch_id"], "definition": graph(), "max_parallel": 4}) worker.join(5) - assert not worker.is_alive() and results[0]["deleted_batches"] == [] + assert not worker.is_alive() + assert results[0]["deleted_batches"] == [] assert runtime.batches.control("get", {"batch_id": batch["batch_id"]})["state"] == "running" diff --git a/test/unit_test/headless/test_agent_desktop_continuity.py b/test/unit_test/headless/test_agent_desktop_continuity.py index d3d7d8e86..0fe313ac4 100644 --- a/test/unit_test/headless/test_agent_desktop_continuity.py +++ b/test/unit_test/headless/test_agent_desktop_continuity.py @@ -45,7 +45,8 @@ def test_retired_desktop_context_cannot_submit_an_edited_form_after_pause(tmp_pa target.values["Field"] = "changed while paused" runtime.resume(task.task_id) outcome = run_task(runtime, task.task_id) - assert outcome.state == "waiting_user" and "desktop context" in outcome.reason + assert outcome.state == "waiting_user" + assert "desktop context" in outcome.reason assert target.submissions == 0 assert len(runtime.store.actions(task.task_id)) == 1 @@ -56,7 +57,8 @@ def test_profiled_desktop_prefix_is_refused_before_any_helper_launch(): target = NativeDesktopTarget(profile=profile.to_dict()) with pytest.raises(AgentHumanReview, match="desktop context"): target.check_resume(form(), [{"status": "confirmed"}]) - assert target._channel is None and target._resource is None + assert target._channel is None + assert target._resource is None def test_uninterrupted_desktop_skill_keeps_its_context(tmp_path): diff --git a/test/unit_test/headless/test_agent_dialog_scope.py b/test/unit_test/headless/test_agent_dialog_scope.py index 69f990447..b0277d1a6 100644 --- a/test/unit_test/headless/test_agent_dialog_scope.py +++ b/test/unit_test/headless/test_agent_dialog_scope.py @@ -113,7 +113,8 @@ def observe(): with pytest.raises(AgentHumanReview): runtime.observe(task.task_id) assert runtime.get(task.task_id).state == "waiting_user" - assert not runtime._leases and cleanup + assert not runtime._leases + assert cleanup assert runtime.store.actions(task.task_id) == [] runtime.resume(task.task_id) assert runtime.get(task.task_id).state == "queued" @@ -158,7 +159,8 @@ def test_file_dialog_rebinds_only_to_confirmed_own_foreground_and_canonicalizes_ with operation_scope(TaskOperation(spec, lambda: None, None)): with file_dialog_scope.scoped_file_dialog(target, 11, 7, {}): assert handle_file_dialog("report.txt")["handled"] - assert focus == [20] and target._action_identity == (20, 7) + assert focus == [20] + assert target._action_identity == (20, 7) assert input_calls == [str((tmp_path / "report.txt").resolve()), "enter"] diff --git a/test/unit_test/headless/test_agent_dynamic_recovery.py b/test/unit_test/headless/test_agent_dynamic_recovery.py index 1bb5dde91..fbfe91ad7 100644 --- a/test/unit_test/headless/test_agent_dynamic_recovery.py +++ b/test/unit_test/headless/test_agent_dynamic_recovery.py @@ -45,12 +45,17 @@ def test_preview_does_not_invent_remaining_actions_or_contact_a_model(dynamic_so network = Mock(side_effect=AssertionError("preview contacted a model")) monkeypatch.setattr("je_auto_control.utils.agent_runtime.ollama.request_json", network) view = runtime.recovery.control("preview", {"task_id": source}) - assert view["source_mode"] == mode and view["draft"] is None - assert view["completed_steps"] is None and view["attempted_steps"] == 1 - assert view["remaining_actions"] == [] and view["rows"] == [] + assert view["source_mode"] == mode + assert view["draft"] is None + assert view["completed_steps"] is None + assert view["attempted_steps"] == 1 + assert view["remaining_actions"] == [] + assert view["rows"] == [] assert view["issues"] == ["new_plan_required"] template = view["review_template"] - assert template["goal"] == "" and template["mode"] == mode and template["actions"] == [] + assert template["goal"] == "" + assert template["mode"] == mode + assert template["actions"] == [] assert template["options"] == runtime.store.get(source)["spec"]["options"] assert target.calls == ["AC_increment"] assert (runtime.store.get(source), runtime.receipts(source)) == before @@ -77,8 +82,10 @@ def decide(self, _observation, history, **_kwargs): if not history else {"stop": True}) assert run_task(runtime, child, backend=Model()).state == "succeeded" - assert histories[0] == [] and len(histories[1]) == 1 - assert len(target.calls) == 2 and runtime.get(source).state == "paused" + assert histories[0] == [] + assert len(histories[1]) == 1 + assert len(target.calls) == 2 + assert runtime.get(source).state == "paused" assert runtime.get(child).metadata["recovery"]["source_task"] == source assert runtime.recovery.control("create", request)["task_id"] == child with pytest.raises(AgentTaskError, match="reviewed successor"): @@ -103,7 +110,8 @@ def test_dynamic_approval_requires_a_new_goal_without_switching_execution_author request["spec"]["options"]["endpoint"] = "http://unapproved.invalid" with pytest.raises(AgentTaskError): runtime.recovery.control("create", request) - assert len(runtime.list()) == 1 and runtime.get(source).state == "paused" + assert len(runtime.list()) == 1 + assert runtime.get(source).state == "paused" def test_explicit_approval_can_retain_goal_wording_without_inheriting_source_progress(dynamic_source): @@ -113,7 +121,8 @@ def test_explicit_approval_can_retain_goal_wording_without_inheriting_source_pro request["note"] = "Reviewed the same overall goal with a new application context and no receipt inheritance" child = runtime.recovery.control("create", request)["task_id"] assert runtime.store.actions(child) == [] - assert runtime.get(child).state == "queued" and runtime.get(source).state == "paused" + assert runtime.get(child).state == "queued" + assert runtime.get(source).state == "paused" def test_new_dynamic_goal_is_not_accepted_while_source_effects_are_unknown(dynamic_source): @@ -139,7 +148,9 @@ def test_dormant_dynamic_action_arrays_do_not_claim_finite_progress(dynamic_sour with runtime.store.connection(write=True) as connection: connection.execute("UPDATE agent_tasks SET spec=? WHERE id=?", (json.dumps(data), source)) view = runtime.recovery.control("preview", {"task_id": source}) - assert view["completed_steps"] is None and view["rows"] == [] and view["remaining_actions"] == [] + assert view["completed_steps"] is None + assert view["rows"] == [] + assert view["remaining_actions"] == [] assert view["review_template"]["actions"] == [] @@ -154,7 +165,8 @@ def test_finish_without_new_results_cannot_inherit_a_matching_source_result(dyna result = run_task(runtime, child, backend=stop) else: result = runtime.finish(child) - assert result.state == "waiting_user" and result.verification[0]["status"] == "unknown" + assert result.state == "waiting_user" + assert result.verification[0]["status"] == "unknown" assert runtime.store.actions(child) == [] assert runtime.store.actions(source)[0]["result"] == {"value": 3} @@ -213,9 +225,11 @@ def test_explicit_local_replan_uses_the_pinned_http_model_with_fresh_goal_and_hi assert all(body["model"] == "fixture-tools" for _, body in server.calls) first = json.loads(server.calls[1][1]["messages"][1]["content"]) second = json.loads(server.calls[2][1]["messages"][1]["content"]) - assert first["goal"] == reviewed["goal"] and first["recent_results"] == [] + assert first["goal"] == reviewed["goal"] + assert first["recent_results"] == [] assert len(second["recent_results"]) == 1 - assert len(runtime.store.actions(child)) == 1 and len(runtime.store.actions(source.task_id)) == 1 + assert len(runtime.store.actions(child)) == 1 + assert len(runtime.store.actions(source.task_id)) == 1 assert runtime.get(source.task_id).state == "paused" finally: jobs.close() diff --git a/test/unit_test/headless/test_agent_evidence_cache_legacy.py b/test/unit_test/headless/test_agent_evidence_cache_legacy.py index 64570950e..5430e7ee3 100644 --- a/test/unit_test/headless/test_agent_evidence_cache_legacy.py +++ b/test/unit_test/headless/test_agent_evidence_cache_legacy.py @@ -54,7 +54,8 @@ def current_only(path): with monkeypatch.context() as scoped: scoped.setattr(Path, 'iterdir', current_only) result = legacy.runtime.get(legacy.task) - assert result.state == 'succeeded' and result.metadata['artifact_cache_state'] == 'historical' + assert result.state == 'succeeded' + assert result.metadata['artifact_cache_state'] == 'historical' assert result.metadata['journal_path'] == str(legacy.directory / 'journal.jsonl') assert result.to_dict()['metadata']['artifacts'] == [] assert not legacy.runtime.evidence.directory(legacy.task).exists() diff --git a/test/unit_test/headless/test_agent_evidence_cache_ownership.py b/test/unit_test/headless/test_agent_evidence_cache_ownership.py index 8be30e0cc..d43721c5a 100644 --- a/test/unit_test/headless/test_agent_evidence_cache_ownership.py +++ b/test/unit_test/headless/test_agent_evidence_cache_ownership.py @@ -78,7 +78,8 @@ def test_backup_publication_creates_own_segment_without_mutating_original_histor assert Path(new_link['journal_path']).parent == backup.evidence.directory(source.task) assert backup.evidence.directory(source.task) != source.runtime.evidence.directory(source.task) runs = backup.evidence.history.list_runs() - assert len(runs) == 2 and old_run in runs + assert len(runs) == 2 + assert old_run in runs old_journals = backup.evidence.history.journals_for_run(old_run.id) assert [item.journal_path for item in old_journals] == [old_link['journal_path']] backup.evidence.publish(source.task) diff --git a/test/unit_test/headless/test_agent_evidence_cache_paths.py b/test/unit_test/headless/test_agent_evidence_cache_paths.py index b77e717ac..32a894f71 100644 --- a/test/unit_test/headless/test_agent_evidence_cache_paths.py +++ b/test/unit_test/headless/test_agent_evidence_cache_paths.py @@ -20,7 +20,8 @@ def test_directory_redirection_preserves_foreign_files(source, kind): sentinel = foreign / 'report.json' sentinel.write_bytes(b'foreign bytes must not change') assert link.resolve().is_relative_to(source.root.resolve()) - assert holding.resolve().is_relative_to(source.root.resolve()) and not holding.exists() + assert holding.resolve().is_relative_to(source.root.resolve()) + assert not holding.exists() link.rename(holding) _junction(link, foreign) try: @@ -48,7 +49,8 @@ def test_hardlinked_artifact_refuses_mutation_and_cleanup(source, name, operatio expire(source.runtime, source.task) with pytest.raises(AgentTaskError, match='ownership'): source.runtime.prune() if operation == 'prune' else source.runtime.evidence.publish(source.task) - assert foreign.read_bytes() == b'keep this separate file' and path.exists() + assert foreign.read_bytes() == b'keep this separate file' + assert path.exists() assert source.runtime.store.get(source.task)['state'] == 'succeeded' diff --git a/test/unit_test/headless/test_agent_evidence_handoff.py b/test/unit_test/headless/test_agent_evidence_handoff.py index 74561b66a..fffb7e3c2 100644 --- a/test/unit_test/headless/test_agent_evidence_handoff.py +++ b/test/unit_test/headless/test_agent_evidence_handoff.py @@ -110,7 +110,8 @@ def forbidden(*_args, **_kwargs): assert review['approval_required'] is True grant = runtime.recovery.control('create_handoff', {**request_for(handoff), 'review': review['handoff_review'], 'note': 'Share only this original DAG completion evidence'})['handoff'] - assert 'store_path' not in json.dumps(review) and 'arguments' not in json.dumps(grant) + assert 'store_path' not in json.dumps(review) + assert 'arguments' not in json.dumps(grant) with pytest.raises(AgentTaskError, match='another caller'): runtime.get(handoff.child) decision = {'node_id': 'a', 'action': 'successor', 'task_id': handoff.child, 'handoff_id': grant['id']} @@ -124,8 +125,10 @@ def forbidden(*_args, **_kwargs): 'definition': handoff.definition, 'approval_id': approved['approval_id'], 'max_parallel': 4}) completed = runtime.batches.control('validate_node', {'batch_id': handoff.batch_id, 'node_id': 'a', 'attempt': started['attempt']}) - assert completed['outcome'] == 'completed' and completed['task_id'] == handoff.child - assert runtime.get(handoff.source).state == 'paused' and handoff.target.calls == calls + assert completed['outcome'] == 'completed' + assert completed['task_id'] == handoff.child + assert runtime.get(handoff.source).state == 'paused' + assert handoff.target.calls == calls for operation in (runtime.get, runtime.receipts, runtime.observe, runtime.resume): with pytest.raises(AgentTaskError, match='another caller'): operation(handoff.child) diff --git a/test/unit_test/headless/test_agent_evidence_handoff_files.py b/test/unit_test/headless/test_agent_evidence_handoff_files.py index a8b9ac6a9..973319da8 100644 --- a/test/unit_test/headless/test_agent_evidence_handoff_files.py +++ b/test/unit_test/headless/test_agent_evidence_handoff_files.py @@ -92,6 +92,7 @@ def forbidden(*_args, **_kwargs): assert files.runtime.store.get(files.child)['owner']['user_id'] == 'reviewer' with pytest.raises(AgentTaskError, match='another caller'): files.runtime.get(files.child) - assert files.manifest.read_bytes() == before and files.runtime.store.actions(files.child) == [] + assert files.manifest.read_bytes() == before + assert files.runtime.store.actions(files.child) == [] finally: server.stop() diff --git a/test/unit_test/headless/test_agent_evidence_handoff_gui.py b/test/unit_test/headless/test_agent_evidence_handoff_gui.py index 0fcda9897..2b4e2eebc 100644 --- a/test/unit_test/headless/test_agent_evidence_handoff_gui.py +++ b/test/unit_test/headless/test_agent_evidence_handoff_gui.py @@ -22,9 +22,11 @@ def test_actions_only_prepare_explicit_handoff_requests(monkeypatch, operation): assert request == {'handoff_id': ''} else: assert request['task_id'] == '' - assert request['batch_id'] == '' and request['node_id'] == '' + assert request['batch_id'] == '' + assert request['node_id'] == '' if operation == 'create_handoff': - assert request['review'] == '' and request['note'] == '' + assert request['review'] == '' + assert request['note'] == '' assert tab._pages.currentIndex() == tab._page_keys.index('agent_page_handoffs') finally: tab.close() diff --git a/test/unit_test/headless/test_agent_evidence_handoff_lifecycle.py b/test/unit_test/headless/test_agent_evidence_handoff_lifecycle.py index f4e79a213..2da6ff309 100644 --- a/test/unit_test/headless/test_agent_evidence_handoff_lifecycle.py +++ b/test/unit_test/headless/test_agent_evidence_handoff_lifecycle.py @@ -97,7 +97,9 @@ def test_completion_projection_and_public_consent_omit_private_task_fields(hando grant = grant_for(handoff) result = consume(handoff, grant['id']) combined = json.dumps([grant, result]) - assert secret not in combined and 'store_path' not in combined and 'arguments' not in combined + assert secret not in combined + assert 'store_path' not in combined + assert 'arguments' not in combined assert all(set(report) == {'kind', 'status'} for report in result[0]['verification']) diff --git a/test/unit_test/headless/test_agent_evidence_handoff_surfaces.py b/test/unit_test/headless/test_agent_evidence_handoff_surfaces.py index 5d62f8a6d..50862c19e 100644 --- a/test/unit_test/headless/test_agent_evidence_handoff_surfaces.py +++ b/test/unit_test/headless/test_agent_evidence_handoff_surfaces.py @@ -49,7 +49,8 @@ def test_shared_surfaces_review_issue_inspect_and_revoke_only_the_exact_handoff( review = invoke(surface, connection, tmp_path, 'review_handoff', request_for(handoff)) grant = invoke(surface, connection, tmp_path, 'create_handoff', {**request_for(handoff), 'review': review['handoff_review'], 'note': 'Explicit immutable evidence-only consent'})['handoff'] - assert grant['evidence_only'] is True and grant['input_authorized'] is False + assert grant['evidence_only'] is True + assert grant['input_authorized'] is False assert invoke(surface, connection, tmp_path, 'get_handoff', {'handoff_id': grant['id']})['handoff'] == grant listed = invoke(surface, connection, tmp_path, 'list_handoffs', {'batch_id': handoff.batch_id, 'node_id': 'a'}) assert [item['id'] for item in listed['handoffs']] == [grant['id']] diff --git a/test/unit_test/headless/test_agent_helper_owner_linux.py b/test/unit_test/headless/test_agent_helper_owner_linux.py index 3da6699df..5463091ee 100644 --- a/test/unit_test/headless/test_agent_helper_owner_linux.py +++ b/test/unit_test/headless/test_agent_helper_owner_linux.py @@ -179,7 +179,8 @@ def _until(predicate, seconds=3.0): def test_wire_layout_matches_the_native_frames(): assert (wire.REQUEST_SIZE, wire.REPLY_SIZE) == (9384, 8312) - assert wire.REQUEST_OFFSETS["data"] == 1188 and wire.REPLY_OFFSETS["data"] == 120 + assert wire.REQUEST_OFFSETS["data"] == 1188 + assert wire.REPLY_OFFSETS["data"] == 120 frame = wire.ServiceRequest(wire.OP_WRITE, (1, 2), ticket=((3, 4), (5, 6)), data=b"abc").pack() assert len(frame) == wire.REQUEST_SIZE assert frame[wire.REQUEST_OFFSETS["ticket"]:wire.REQUEST_OFFSETS["ticket"] + 8] == struct.pack("= 1 + assert not channel.retired + assert service.calls.count(wire.OP_CLOSE) >= 1 with pytest.raises(AgentTaskError, match="unknown start"): channel.close() assert not channel.retired @@ -425,7 +438,8 @@ def test_connection_turned_away_before_a_lease_is_busy_not_broken(): channel = OwnerServiceChannel(service, 1) with pytest.raises(AgentControlBusy, match="turned the connection away"): channel.request("echo", 1, timeout=5) - assert channel.retired and not service.calls + assert channel.retired + assert not service.calls def test_renewer_survives_a_failed_connection_without_a_thread_error(monkeypatch): @@ -437,7 +451,8 @@ def test_renewer_survives_a_failed_connection_without_a_thread_error(monkeypatch channel = OwnerServiceChannel(service, 1) assert channel.request("echo", 1, timeout=5) == 1 assert _until(lambda: not channel._renewer.is_alive()) - assert not raised and channel._lease_lost + assert not raised + assert channel._lease_lost def test_close_learns_a_lost_start_ticket_by_replay_and_retires(): @@ -449,4 +464,5 @@ def test_close_learns_a_lost_start_ticket_by_replay_and_retires(): assert not channel.retired service.drop_always = set() # The service answers again: the replay returns the kept ticket. channel.close() - assert channel.retired and wire.OP_OBSERVE in service.calls + assert channel.retired + assert wire.OP_OBSERVE in service.calls diff --git a/test/unit_test/headless/test_agent_maintenance_lease.py b/test/unit_test/headless/test_agent_maintenance_lease.py index fd5ec5995..5887716c0 100644 --- a/test/unit_test/headless/test_agent_maintenance_lease.py +++ b/test/unit_test/headless/test_agent_maintenance_lease.py @@ -59,7 +59,8 @@ def maintain(): users.set_role("owner", "viewer") proceed.set() watcher.join(5) - assert not watcher.is_alive() and not failures + assert not watcher.is_alive() + assert not failures assert runtime.store.get(task) == before, "A stale watcher cannot rewrite retired recovery evidence" assert target.calls == [] finally: @@ -76,7 +77,8 @@ def test_current_input_owner_still_retires_on_expiry_or_revocation(owned, monkey users.set_role("owner", "viewer") runtime.maintain() assert runtime.store.get(task)["state"] == ("timed_out" if cause == "expired" else "cancelled") - assert task not in runtime._leases and target.calls == [] + assert task not in runtime._leases + assert target.calls == [] @pytest.mark.parametrize("reacquire", [False, True]) @@ -105,9 +107,11 @@ def changed(identifier, state, **options): monkeypatch.setattr(runtime.clock, "remaining", expired_once) monkeypatch.setattr(runtime.store, "request_stop", changed) runtime.maintain() - assert snapshots and runtime.store.get(task) == snapshots[0] + assert snapshots + assert runtime.store.get(task) == snapshots[0] if reacquire: - assert task in runtime._leases and not runtime._token(task).is_cancelled + assert task in runtime._leases + assert not runtime._token(task).is_cancelled else: assert task not in runtime._leases assert target.calls == [] @@ -158,8 +162,10 @@ def pause(): finally: proceed.set() worker.join(5) - assert not worker.is_alive() and not failures - assert results[0].state == "paused" and task not in runtime._leases + assert not worker.is_alive() + assert not failures + assert results[0].state == "paused" + assert task not in runtime._leases def test_revocation_reason_is_final_when_cancellation_is_published(owned, monkeypatch): @@ -176,5 +182,6 @@ def capture(identifier, expected, state, **options): monkeypatch.setattr(runtime.store, "transition", capture) users.set_role("owner", "viewer") runtime.maintain() - assert published and published[0]["reason"] == "owner authorization or origin scope requires review" + assert published + assert published[0]["reason"] == "owner authorization or origin scope requires review" assert runtime.store.get(task) == published[0], "Terminal publication must leave a stable recovery snapshot" diff --git a/test/unit_test/headless/test_agent_model_grounding.py b/test/unit_test/headless/test_agent_model_grounding.py index e19eaf84e..0650ac2c0 100644 --- a/test/unit_test/headless/test_agent_model_grounding.py +++ b/test/unit_test/headless/test_agent_model_grounding.py @@ -64,7 +64,8 @@ def transport(call): assert content["observation"]["image_geometry"]["original_size"] == [400, 200] assert "data" not in content["observation"]["image_geometry"] offered = payload["tools"][0]["function"]["parameters"]["properties"] - assert "observed_target" in offered and "observed_target" not in original[0]["function"]["parameters"]["properties"] + assert "observed_target" in offered + assert "observed_target" not in original[0]["function"]["parameters"]["properties"] def test_model_reference_is_resolved_once_by_shared_runtime(tmp_path): @@ -96,7 +97,9 @@ def test_continuous_geometry_change_exhausts_retries_without_preparing_any_effec try: task = runtime.submit(specification()) assert run_task(runtime, task.task_id, backend=backend).state == "waiting_user" - assert backend.decisions == 3 and target.calls == [] and runtime.store.actions(task.task_id) == [] + assert backend.decisions == 3 + assert target.calls == [] + assert runtime.store.actions(task.task_id) == [] finally: runtime.close() @@ -107,7 +110,8 @@ def test_adapter_without_safe_reobservation_does_not_replan_past_held_input(tmp_ try: task = runtime.submit(specification()) assert run_task(runtime, task.task_id, backend=backend).state == "waiting_user" - assert backend.decisions == 1 and target.calls == [] + assert backend.decisions == 1 + assert target.calls == [] finally: runtime.close() diff --git a/test/unit_test/headless/test_agent_native_channel.py b/test/unit_test/headless/test_agent_native_channel.py index 7d0d01807..25aa75f53 100644 --- a/test/unit_test/headless/test_agent_native_channel.py +++ b/test/unit_test/headless/test_agent_native_channel.py @@ -103,7 +103,8 @@ def wait_for_reply(): waiter.join(timeout=5) assert not waiter.is_alive() assert closed_after < 5 - assert "result" not in outcome and "closed" in str(outcome["error"]) + assert "result" not in outcome + assert "closed" in str(outcome["error"]) assert worker.retired @@ -131,7 +132,8 @@ def close_once_reply_is_dequeued(): with pytest.raises(AgentTaskError, match="closed"): worker.request("echo", {"value": 1}, timeout=5, check=close_once_reply_is_dequeued) - assert closers and worker.retired + assert closers + assert worker.retired def test_closed_channel_refuses_new_requests(): diff --git a/test/unit_test/headless/test_agent_native_job.py b/test/unit_test/headless/test_agent_native_job.py index a0af028a4..1086c04e6 100644 --- a/test/unit_test/headless/test_agent_native_job.py +++ b/test/unit_test/headless/test_agent_native_job.py @@ -60,13 +60,16 @@ def CloseHandle(self, handle): return self.close_ok def OpenProcess(self, access, inherit, pid): - assert access == 0x101000 and not inherit and pid in self.processes + assert access == 0x101000 + assert not inherit + assert pid in self.processes handle = 0x200000000 + pid self.handles[handle] = pid return handle def IsProcessInJob(self, process, job, pointer): - assert process in self.handles and job == 0x100000001 + assert process in self.handles + assert job == 0x100000001 ctypes.cast(pointer, ctypes.POINTER(ctypes.c_int)).contents.value = self.belongs return True @@ -117,8 +120,10 @@ def sleep(delay): monkeypatch.setattr(module, 'time', SimpleNamespace(monotonic=lambda: now[0], sleep=sleep), raising=False) with pytest.raises(AgentTaskError): job.close(timeout=0.03) - assert now[0] <= 0.03 and sleeps - assert job._handle == 0x100000001 and 'close' not in kernel.events + assert now[0] <= 0.03 + assert sleeps + assert job._handle == 0x100000001 + assert 'close' not in kernel.events kernel.counts = [0] job.close() assert job._handle is None @@ -161,13 +166,15 @@ def test_process_objects_must_signal_even_after_the_job_reports_no_active_proces kernel.signals[202] = 258 with pytest.raises(AgentTaskError): job.close(timeout=0.03) - assert job._handle == 0x100000001 and 'close' not in kernel.events + assert job._handle == 0x100000001 + assert 'close' not in kernel.events assert any(event[:2] == ('process-wait', 202) for event in kernel.events if isinstance(event, tuple)) assert kernel.handles kernel.processes = [] kernel.signals[202] = 0 job.close() - assert job._handle is None and not kernel.handles + assert job._handle is None + assert not kernel.handles def test_process_object_queries_may_never_select_a_process_outside_the_actual_owned_job(monkeypatch): @@ -175,7 +182,8 @@ def test_process_object_queries_may_never_select_a_process_outside_the_actual_ow kernel.processes, kernel.belongs = [201], False with pytest.raises(AgentTaskError): job.close() - assert 'terminate' in kernel.events and 'close' not in kernel.events + assert 'terminate' in kernel.events + assert 'close' not in kernel.events assert not kernel.handles @@ -193,8 +201,10 @@ def delayed(*args): monkeypatch.setattr(module, 'time', SimpleNamespace(monotonic=lambda: now[0])) with pytest.raises(AgentTaskError): job.close(timeout=0.03) - assert now[0] <= 0.03 and 'terminate' in kernel.events - assert job._handle is not None and 'close' not in kernel.events + assert now[0] <= 0.03 + assert 'terminate' in kernel.events + assert job._handle is not None + assert 'close' not in kernel.events def test_already_exhausted_deadline_still_terminates_only_the_owned_job(monkeypatch): @@ -202,5 +212,6 @@ def test_already_exhausted_deadline_still_terminates_only_the_owned_job(monkeypa kernel.counts = [1] with pytest.raises(AgentTaskError): job.close(timeout=0) - assert 'terminate' in kernel.events and 'close' not in kernel.events + assert 'terminate' in kernel.events + assert 'close' not in kernel.events assert job._handle == 0x100000001 diff --git a/test/unit_test/headless/test_agent_observation_gui.py b/test/unit_test/headless/test_agent_observation_gui.py index fc60e6fc8..ec1d715f0 100644 --- a/test/unit_test/headless/test_agent_observation_gui.py +++ b/test/unit_test/headless/test_agent_observation_gui.py @@ -66,7 +66,8 @@ def test_android_semantic_selection_uses_the_shared_action_without_native_input( tab._present_result(frame) tab._observation._elements.cellClicked.emit(0, 0) action = json.loads(tab._action.toPlainText()) - assert action['tool'] == 'AC_android_tap' and action['arguments'] == {} + assert action['tool'] == 'AC_android_tap' + assert action['arguments'] == {} assert calls == [] resolved, _ground = resolve_action(action['tool'], action['arguments'], action['reference'], frame['data']) assert resolved == {'x': 25, 'y': 40} diff --git a/test/unit_test/headless/test_agent_observed_targets.py b/test/unit_test/headless/test_agent_observed_targets.py index 57f1f2ea7..cb2aae742 100644 --- a/test/unit_test/headless/test_agent_observed_targets.py +++ b/test/unit_test/headless/test_agent_observed_targets.py @@ -80,7 +80,8 @@ def test_invalid_or_outside_observation_references_never_dispatch(managed, refer with pytest.raises(AgentTaskError): runtime.act(task_id, {"tool": "AC_click_mouse", "reference": reference, "observation_id": frame.observation_id}) - assert target.calls == [] and runtime.store.actions(task_id) == [] + assert target.calls == [] + assert runtime.store.actions(task_id) == [] def test_reference_and_explicit_coordinates_cannot_conflict(managed): @@ -124,7 +125,8 @@ def test_image_metadata_cannot_supply_a_different_scale_from_the_actual_pixels(m with pytest.raises(AgentTaskError, match="actual pixels"): runtime.act(task_id, {"tool": "AC_click_mouse", "arguments": {"mouse_keycode": "left"}, "reference": {"image_point": [10, 5]}, "observation_id": frame.observation_id}) - assert target.calls == [] and runtime.store.actions(task_id) == [] + assert target.calls == [] + assert runtime.store.actions(task_id) == [] def test_legacy_explicit_coordinates_are_preserved(managed): diff --git a/test/unit_test/headless/test_agent_operation_context.py b/test/unit_test/headless/test_agent_operation_context.py index 1167de1a0..3eecf86a4 100644 --- a/test/unit_test/headless/test_agent_operation_context.py +++ b/test/unit_test/headless/test_agent_operation_context.py @@ -74,7 +74,8 @@ def request(*_args, **_options): assert context.current_takeover() is parent.takeover captured() assert calls == ["bound"] - assert context.current_operation() is None and context.current_takeover() is None + assert context.current_operation() is None + assert context.current_takeover() is None def test_nested_operation_cannot_borrow_outer_readiness_callback(): @@ -110,7 +111,8 @@ def ready(self, _spec): with context.operation_scope(parent): with pytest.raises(AgentTaskError, match="owned failure"): context.ready_with_takeover(Target(), spec, lambda: None) - assert context.current_operation() is parent and context.current_takeover() is parent.takeover + assert context.current_operation() is parent + assert context.current_takeover() is parent.takeover assert context.current_takeover() is None diff --git a/test/unit_test/headless/test_agent_origin_policy.py b/test/unit_test/headless/test_agent_origin_policy.py index 20c764a7e..d1533718c 100644 --- a/test/unit_test/headless/test_agent_origin_policy.py +++ b/test/unit_test/headless/test_agent_origin_policy.py @@ -30,7 +30,8 @@ def test_removed_origin_root_pauses_before_the_next_action(tmp_path): with pytest.raises(AgentTaskError, match="origin roots changed"): runtime.act(task.task_id, {"tool": "AC_increment", "observation_id": frame.observation_id}) assert target.calls == [] - assert runtime.get(task.task_id).state == "paused" and not runtime._leases + assert runtime.get(task.task_id).state == "paused" + assert not runtime._leases assert "scope requires review" in runtime.get(task.task_id).reason finally: runtime.close() @@ -45,7 +46,8 @@ def test_origin_revocation_retires_active_input_between_requests(tmp_path): runtime.observe(task.task_id) policy.revoke_managed_origin() runtime.maintain() - assert runtime.get(task.task_id).state == "cancelled" and not runtime._leases + assert runtime.get(task.task_id).state == "cancelled" + assert not runtime._leases finally: runtime.close() @@ -181,7 +183,8 @@ def test_legacy_mcp_tool_cannot_submit_a_task_beyond_its_path_ceiling(tmp_path): context = ToolCallContext(1, path_policy=PathPolicy([allowed])) with pytest.raises(AgentTaskError, match="origin roots changed"): tool.invoke({}, ctx=context) - assert runtime.list() == [] and origin_policy.current_origin() is None + assert runtime.list() == [] + assert origin_policy.current_origin() is None finally: runtime.close() diff --git a/test/unit_test/headless/test_agent_owned_channel_factory.py b/test/unit_test/headless/test_agent_owned_channel_factory.py index d7cb4a426..22030c19c 100644 --- a/test/unit_test/headless/test_agent_owned_channel_factory.py +++ b/test/unit_test/headless/test_agent_owned_channel_factory.py @@ -69,7 +69,9 @@ def test_linux_binding_launches_only_through_the_owner_service(monkeypatch, tmp_ monkeypatch.setattr(helper_owner_linux, "SeqpacketTransport", FakeTransport) channel = factory.owned_channel(ARGV) assert isinstance(channel, helper_owner_linux.OwnerServiceChannel) - assert channel._transport.endpoint == VALID["endpoint"] and channel._policy == 3 and channel._arguments == () + assert channel._transport.endpoint == VALID["endpoint"] + assert channel._policy == 3 + assert channel._arguments == () assert not local.calls @@ -110,7 +112,8 @@ def test_untrusted_binding_refuses(monkeypatch, tmp_path): def test_valid_binding_parses_exact_rows(monkeypatch, tmp_path): path = bind(monkeypatch, tmp_path, VALID) binding = factory.load_binding(str(path)) - assert binding.endpoint == VALID["endpoint"] and binding.policies == {tuple(ARGV): 3} + assert binding.endpoint == VALID["endpoint"] + assert binding.policies == {tuple(ARGV): 3} def test_every_consumer_obtains_its_channel_through_the_factory(): @@ -118,7 +121,8 @@ def test_every_consumer_obtains_its_channel_through_the_factory(): for name in ("helper_environment.py", "native_target.py", "remote_target.py", "presence_pool.py", "presence_worker.py"): source = (package / name).read_text(encoding="utf-8") - assert "owned_channel" in source and "OwnedChannel(" not in source, name + assert "owned_channel" in source, name + assert "OwnedChannel(" not in source, name def test_nested_grant_reaches_the_service_channel_and_refuses_elsewhere(monkeypatch, tmp_path, local): @@ -152,12 +156,15 @@ def test_containment_status_on_linux_never_claims_native_evidence(monkeypatch, t assert factory.helper_containment()["status"] == "not_configured" bind(monkeypatch, tmp_path, {"endpoint": "relative"}) refused = factory.helper_containment() - assert refused["status"] == "binding_refused" and refused["mode"] == "owner_service" and refused["reason"] + assert refused["status"] == "binding_refused" + assert refused["mode"] == "owner_service" + assert refused["reason"] bind(monkeypatch, tmp_path, VALID) for reachable, status in ((False, "unreachable"), (True, "reachable_unverified")): monkeypatch.setattr(factory, "_endpoint_reachable", lambda _endpoint, value=reachable: value) result = factory.helper_containment() - assert result["status"] == status and result["policies"] == 1 + assert result["status"] == status + assert result["policies"] == 1 assert result["native_evidence"] == "not_recorded" @@ -165,7 +172,8 @@ def test_runtime_status_carries_the_containment_section(monkeypatch, tmp_path): from je_auto_control.utils.agent_runtime import api monkeypatch.setattr(api, "default_connection_path", lambda: tmp_path / "absent.json") status = api.agent_runtime_status() - assert status["configured"] is False and status["helper_containment"]["native_evidence"] == "not_recorded" + assert status["configured"] is False + assert status["helper_containment"]["native_evidence"] == "not_recorded" def test_binding_under_a_writable_directory_refuses(monkeypatch, tmp_path): diff --git a/test/unit_test/headless/test_agent_owner_service_nested.py b/test/unit_test/headless/test_agent_owner_service_nested.py index 1ebd88816..a762e3d78 100644 --- a/test/unit_test/headless/test_agent_owner_service_nested.py +++ b/test/unit_test/headless/test_agent_owner_service_nested.py @@ -28,10 +28,12 @@ def test_frame_layout_matches_the_native_record(): def test_valid_frame_is_read_once_and_its_descriptor_closed(): fd = piped(frame()) grant = nested.read_nested_bootstrap(fd) - assert grant.parent == ((142, 1), (0, 3)) and grant.capability == CAPABILITY + assert grant.parent == ((142, 1), (0, 3)) + assert grant.capability == CAPABILITY with pytest.raises(OSError): os.fstat(fd) - assert "capability=<32 bytes>" in repr(grant) and str(CAPABILITY[0]) not in repr(grant).split("capability")[1] + assert "capability=<32 bytes>" in repr(grant) + assert str(CAPABILITY[0]) not in repr(grant).split("capability")[1] def test_absent_descriptor_means_not_nested(): diff --git a/test/unit_test/headless/test_agent_presence_binding.py b/test/unit_test/headless/test_agent_presence_binding.py index 3f6fb159c..8315c3c27 100644 --- a/test/unit_test/headless/test_agent_presence_binding.py +++ b/test/unit_test/headless/test_agent_presence_binding.py @@ -70,7 +70,8 @@ def test_repeated_configure_reuses_one_reader_and_never_acquires_a_new_capabilit assert worker._dispatch('configure', payload())['ready'] assert worker._dispatch('configure', payload())['ready'] assert len(Gate.instances) == 1 - assert Gate.instances[0].binding == BINDING and Gate.instances[0].readies == 2 + assert Gate.instances[0].binding == BINDING + assert Gate.instances[0].readies == 2 @pytest.mark.parametrize('change', ['binding', 'spec', 'owner']) @@ -85,13 +86,15 @@ def test_configured_reader_cannot_change_capability_or_host_scope_without_retire altered['owner'] = {'user_id': 'other', 'role': 'admin', 'store_path': 'not-an-authority'} with pytest.raises(AgentTaskError): worker._dispatch('configure', altered) - assert len(Gate.instances) == 1 and Gate.instances[0].binding == BINDING + assert len(Gate.instances) == 1 + assert Gate.instances[0].binding == BINDING def test_release_only_cleanup_retires_reader_and_notice_thread_without_rearming(worker): worker._dispatch('configure', payload()) assert worker._release_owned({'keys': [], 'buttons': []}) == {'cleaned': True} - assert Gate.instances[0].retired and not worker._notice_thread.is_alive() + assert Gate.instances[0].retired + assert not worker._notice_thread.is_alive() with pytest.raises(AgentTaskError): worker._dispatch('configure', payload()) assert len(Gate.instances) == 1 @@ -100,7 +103,8 @@ def test_release_only_cleanup_retires_reader_and_notice_thread_without_rearming( def test_owner_eof_closes_actual_worker_reader_and_notice_lifetime(worker): worker._dispatch('configure', payload()) worker.run() - assert Gate.instances[0].retired and not worker._notice_thread.is_alive() + assert Gate.instances[0].retired + assert not worker._notice_thread.is_alive() def test_notice_start_failure_is_typed_and_closes_unstarted_reader_without_rearming(worker, monkeypatch): diff --git a/test/unit_test/headless/test_agent_presence_broker.py b/test/unit_test/headless/test_agent_presence_broker.py index 3b8738b6a..443c0fb64 100644 --- a/test/unit_test/headless/test_agent_presence_broker.py +++ b/test/unit_test/headless/test_agent_presence_broker.py @@ -92,7 +92,8 @@ def test_constructor_close_and_unbound_requests_never_discover_or_launch(monkeyp with pytest.raises(AgentTaskError): broker.request('inspect', {}) broker.close() - assert not pipe.calls and not children + assert not pipe.calls + assert not children def test_missing_source_launches_once_and_busy_is_normal_without_resetting_generation(monkeypatch): @@ -100,9 +101,11 @@ def test_missing_source_launches_once_and_busy_is_normal_without_resetting_gener broker = create() try: ready = broker.bootstrap() - assert ready['ready'] and len(children) == 1 + assert ready['ready'] + assert len(children) == 1 assert broker.request('acquire', {})['status'] == 'busy' - assert broker.bootstrap() == ready and not children[0].closed + assert broker.bootstrap() == ready + assert not children[0].closed source.advance(60) assert broker.request('acquire', {})['result']['generation'] == ready['generation'] assert len(children) == 1 @@ -180,7 +183,8 @@ def request(operation, body): broker = create() try: assert broker.bootstrap() == {'ready': False, 'status': 'busy'} - assert len(children) == 1 and not children[0].closed + assert len(children) == 1 + assert not children[0].closed assert broker.bootstrap()['generation'] == source.status()['generation'] assert len(children) == 1 finally: @@ -194,7 +198,8 @@ def test_wire_bootstrap_cannot_select_namespace_role_process_or_source(monkeypat with pytest.raises(AgentTaskError): broker.dispatch('bootstrap', payload) broker.close() - assert not pipe.calls and not children + assert not pipe.calls + assert not children @pytest.mark.parametrize('mutation', [{'request_id': True}, {'status': 'ok', 'result': {'generation': 'x'}}, @@ -211,4 +216,5 @@ def mutate(value): with pytest.raises(AgentTaskError): broker.request('inspect', {}) broker.close() - assert children[0].closed and len(children) == 1 + assert children[0].closed + assert len(children) == 1 diff --git a/test/unit_test/headless/test_agent_presence_channel_guards.py b/test/unit_test/headless/test_agent_presence_channel_guards.py index 02680ee5b..f13942045 100644 --- a/test/unit_test/headless/test_agent_presence_channel_guards.py +++ b/test/unit_test/headless/test_agent_presence_channel_guards.py @@ -10,7 +10,8 @@ @pytest.mark.parametrize('platform', ['linux', 'darwin', 'freebsd']) def test_transport_types_do_not_enable_non_windows_presence_or_input(monkeypatch, platform): - assert LinuxChannel.connect and LinuxListener.create + assert LinuxChannel.connect + assert LinuxListener.create monkeypatch.setattr(sys, 'platform', platform) with pytest.raises(AgentControlBusy, match='Windows console session'): presence_host.require_windows() diff --git a/test/unit_test/headless/test_agent_presence_handshake.py b/test/unit_test/headless/test_agent_presence_handshake.py index 8d693fa0c..a62d7939a 100644 --- a/test/unit_test/headless/test_agent_presence_handshake.py +++ b/test/unit_test/headless/test_agent_presence_handshake.py @@ -50,7 +50,8 @@ def fileno(self): def send_bytes(self, raw): self.security.events.append('send') - assert isinstance(raw, bytes) and len(raw) <= 4096 + assert isinstance(raw, bytes) + assert len(raw) <= 4096 self.sent.append(json.loads(raw)) def recv_bytes(self, maximum): @@ -87,25 +88,33 @@ def test_client_opens_actual_peer_before_read_and_retains_query_handle_through_b security = Security() channel = Channel(security, [hello(), client_final]) generation, peer = module().client_handshake(channel, security) - assert generation == GENERATION and peer is security.process + assert generation == GENERATION + assert peer is security.process assert security.events[0] == ('peer-open', False) - assert not peer.closed and not channel.closed + assert not peer.closed + assert not channel.closed assert len(channel.sent) == 1 proof, = channel.sent assert set(proof) == {'protocol', 'server_challenge', 'challenge', 'birth'} - assert proof['protocol'] == 1 and proof['birth'] == 11 and proof['server_challenge'] == REMOTE_NONCE - assert len(proof['challenge']) == 32 and proof['challenge'] != REMOTE_NONCE + assert proof['protocol'] == 1 + assert proof['birth'] == 11 + assert proof['server_challenge'] == REMOTE_NONCE + assert len(proof['challenge']) == 32 + assert proof['challenge'] != REMOTE_NONCE def test_server_opens_actual_peer_before_issuing_challenge_and_echoes_only_fresh_client_proof(): security = Security() channel = Channel(security, [server_proof]) peer = module().server_handshake(channel, security, GENERATION) - assert peer is security.process and not peer.closed and not channel.closed + assert peer is security.process + assert not peer.closed + assert not channel.closed assert security.events[0] == ('peer-open', True) first, last = channel.sent assert set(first) == set(last) == {'protocol', 'challenge', 'birth', 'generation'} - assert first['challenge'] != REMOTE_NONCE and len(first['challenge']) == 32 + assert first['challenge'] != REMOTE_NONCE + assert len(first['challenge']) == 32 assert first['birth'] == last['birth'] == 11 assert first['generation'] == last['generation'] == GENERATION assert last['challenge'] == REMOTE_NONCE @@ -120,7 +129,9 @@ def test_client_refuses_invalid_first_frame_without_disclosing_proof(field, valu channel = Channel(security, [frame]) with pytest.raises(AgentTaskError): module().client_handshake(channel, security) - assert not channel.sent and channel.closed and security.process.closed + assert not channel.sent + assert channel.closed + assert security.process.closed @pytest.mark.parametrize('field,value', [('challenge', REMOTE_NONCE), ('birth', 23), @@ -136,7 +147,8 @@ def forged(channel): channel = Channel(security, [hello(), forged]) with pytest.raises(AgentTaskError): module().client_handshake(channel, security) - assert channel.closed and security.process.closed + assert channel.closed + assert security.process.closed @pytest.mark.parametrize('field,value', [('server_challenge', REMOTE_NONCE), ('birth', 23), @@ -152,7 +164,9 @@ def forged(channel): channel = Channel(security, [forged]) with pytest.raises(AgentTaskError): module().server_handshake(channel, security, GENERATION) - assert len(channel.sent) == 1 and channel.closed and security.process.closed + assert len(channel.sent) == 1 + assert channel.closed + assert security.process.closed @pytest.mark.parametrize('server', [True, False]) @@ -169,7 +183,8 @@ def dying(channel): module().server_handshake(channel, security, GENERATION) else: module().client_handshake(channel, security) - assert channel.closed and security.process.closed + assert channel.closed + assert security.process.closed @pytest.mark.parametrize('raw', [b'\xff', b'{"protocol":1,"protocol":1}', b' ' * 4097], @@ -179,4 +194,5 @@ def test_handshake_uses_closed_bounded_json_frames_and_closes_on_parse_failure(r channel = Channel(security, [raw]) with pytest.raises(AgentTaskError): module().client_handshake(channel, security) - assert channel.closed and security.process.closed + assert channel.closed + assert security.process.closed diff --git a/test/unit_test/headless/test_agent_presence_pipe.py b/test/unit_test/headless/test_agent_presence_pipe.py index 5ab2915b2..c30b3cc9b 100644 --- a/test/unit_test/headless/test_agent_presence_pipe.py +++ b/test/unit_test/headless/test_agent_presence_pipe.py @@ -53,7 +53,9 @@ def allocate(self): def create(self, *args): from je_auto_control.utils.agent_runtime.presence_security_windows import _SecurityAttributes attributes = ctypes.cast(args[-1], ctypes.POINTER(_SecurityAttributes)).contents - assert self.security.active and attributes.descriptor == 12345 and attributes.inherit == 0 + assert self.security.active + assert attributes.descriptor == 12345 + assert attributes.inherit == 0 self.calls.append('create') return ctypes.c_void_p(-1).value if self.fail_create else self.allocate() @@ -75,7 +77,8 @@ def close(self, handle): return True def connect(self, handle, *, overlapped): - assert handle in self.handles and overlapped is True + assert handle in self.handles + assert overlapped is True self.calls.append(('accept', handle)) def wait(block): @@ -107,13 +110,15 @@ def factory(monkeypatch): def test_constructor_is_inert_and_first_instance_uses_actual_noninheritable_descriptor(monkeypatch): api, native, security = factory(monkeypatch) - assert not native.calls and not security.names + assert not native.calls + assert not security.names listener = api.listen() try: args, = native.kernel.CreateNamedPipeW.calls assert args[0] == r'\\.\pipe\je-auto-presence-v1-test' assert args[1:7] == (0x40080003, 14, 17, 4096, 4096, 0) - assert security.names == ['a' * 32] and not security.active + assert security.names == ['a' * 32] + assert not security.active assert native.kernel.CreateNamedPipeW.restype is ctypes.c_void_p finally: listener.close() @@ -126,7 +131,8 @@ def test_accept_reserves_next_instance_before_wait_and_transfers_only_connected_ connection = listener.accept() assert native.calls[:3] == ['create', 'create', ('accept', 0x100000001)] assert native.kernel.CreateNamedPipeW.calls[1][1] == 0x40000003 - assert connection.fileno() == 0x100000001 and len(native.handles) == 2 + assert connection.fileno() == 0x100000001 + assert len(native.handles) == 2 listener.close() listener.close() assert native.handles == {0x100000001} @@ -154,7 +160,8 @@ def test_only_verified_missing_endpoint_may_be_reported_as_absent(monkeypatch): api, native, _security = factory(monkeypatch) native.fail_create, native.error = True, 2 assert api.connect_if_present() is None - assert len(native.kernel.CreateFileW.calls) == 1 and not native.handles + assert len(native.kernel.CreateFileW.calls) == 1 + assert not native.handles @pytest.mark.parametrize('error,kind', [(5, AgentTaskError), (231, AgentControlBusy), (53, AgentTaskError)]) @@ -163,7 +170,8 @@ def test_denied_busy_or_unknown_endpoint_is_never_reported_missing(monkeypatch, native.fail_create, native.error = True, error with pytest.raises(kind): api.connect_if_present() - assert len(native.kernel.CreateFileW.calls) == 1 and not native.handles + assert len(native.kernel.CreateFileW.calls) == 1 + assert not native.handles @pytest.mark.parametrize('listen', [True, False]) @@ -174,7 +182,8 @@ def test_open_failure_never_wraps_or_borrows_a_foreign_handle(monkeypatch, liste with pytest.raises(AgentControlBusy if listen else AgentTaskError): api.listen() if listen else api.connect() assert len(native.kernel.CreateNamedPipeW.calls if listen else native.kernel.CreateFileW.calls) == 1 - assert not native.handles and not native.async_api.ConnectNamedPipe.calls + assert not native.handles + assert not native.async_api.ConnectNamedPipe.calls @pytest.mark.parametrize('failure', ['fail_state', 'fail_wrap']) @@ -248,7 +257,8 @@ def test_connection_only_sends_bounded_immutable_bytes(monkeypatch, raw): with pytest.raises(AgentTaskError): connection.send_bytes(raw) assert not any(isinstance(item, tuple) and item[0] == 'send' for item in native.calls) - assert not hasattr(connection, 'send') and not hasattr(connection, 'recv') + assert not hasattr(connection, 'send') + assert not hasattr(connection, 'recv') connection.send_bytes(b'{}') assert ('send', b'{}') in native.calls assert len(connection.recv_bytes(4096)) == 4096 diff --git a/test/unit_test/headless/test_agent_presence_pool.py b/test/unit_test/headless/test_agent_presence_pool.py index 26007b9f2..a16b5e458 100644 --- a/test/unit_test/headless/test_agent_presence_pool.py +++ b/test/unit_test/headless/test_agent_presence_pool.py @@ -58,11 +58,13 @@ def test_pool_reference_status_and_unstarted_close_do_not_create_any_helper(): calls = [] instance = pool(lambda _argv: calls.append('created')) first, second = instance.reference(), instance.reference() - assert instance.status()['state'] == 'not_started' and not calls + assert instance.status()['state'] == 'not_started' + assert not calls first.close() assert not calls second.close() - assert instance.retired and not calls + assert instance.retired + assert not calls def test_two_references_share_one_broker_and_closing_one_keeps_the_other_lease(): @@ -78,10 +80,12 @@ def create(argv): first, second = instance.reference(), instance.reference() try: left, right = first.acquire(noop, 2), second.acquire(noop, 2) - assert left['generation'] == right['generation'] and len(channels) == 1 + assert left['generation'] == right['generation'] + assert len(channels) == 1 first.close() another = second.acquire(noop, 2) - assert another['generation'] == right['generation'] and not channels[0].retired + assert another['generation'] == right['generation'] + assert not channels[0].retired assert channels[0].source.released.wait(1) assert len(channels[0].threads) == 1 with pytest.raises(AgentTaskError): @@ -89,7 +93,8 @@ def create(argv): finally: first.close() second.close() - assert channels[0].retired and instance.retired + assert channels[0].retired + assert instance.retired def test_busy_acquisition_does_not_retire_or_restart_the_source(): @@ -129,7 +134,8 @@ def check(): channel.allow.set() token = second.acquire(noop, 2) assert channel.source.released.wait(1) - assert token['generation'] == channel.protocol.generation and not channel.retired + assert token['generation'] == channel.protocol.generation + assert not channel.retired finally: channel.allow.set() first.close() @@ -145,7 +151,8 @@ def test_individual_wait_deadline_abandons_late_grant_without_killing_shared_sou started = time.monotonic() with pytest.raises(AgentTaskError, match='deadline'): first.acquire(noop, 0.1) - assert time.monotonic() - started < 0.5 and not channel.retired + assert time.monotonic() - started < 0.5 + assert not channel.retired channel.allow.set() assert second.acquire(noop, 2)['generation'] == channel.protocol.generation assert channel.source.released.wait(1) @@ -165,7 +172,9 @@ def test_last_close_cancels_shared_lifetime_and_proves_owned_thread_retirement() assert channel.entered.wait(1) started = time.monotonic() reference.close() - assert time.monotonic() - started < 3 and channel.retired and instance.retired + assert time.monotonic() - started < 3 + assert channel.retired + assert instance.retired with pytest.raises(AgentTaskError): waiting.result(timeout=1) with pytest.raises(AgentTaskError): @@ -195,7 +204,9 @@ def create(_argv): closing.result(timeout=3) with pytest.raises(AgentTaskError): acquiring.result(timeout=1) - assert channel.retired and not channel.calls and instance.retired + assert channel.retired + assert not channel.calls + assert instance.retired def test_fatal_source_rpc_does_not_rearm_an_existing_reference(): @@ -236,10 +247,12 @@ def close(): reference.acquire(noop, 2) with pytest.raises(AgentTaskError): reference.close() - assert not instance.retired and not channel.retired + assert not instance.retired + assert not channel.retired fail[0] = False reference.close() - assert instance.retired and channel.retired + assert instance.retired + assert channel.retired with pytest.raises(AgentTaskError): reference.acquire(noop, 2) @@ -257,7 +270,8 @@ def fail_start(_thread): with pytest.raises(AgentTaskError, match='thread'): reference.acquire(noop, 2) reference.close() - assert instance.retired and not calls + assert instance.retired + assert not calls with pytest.raises(AgentTaskError): reference.acquire(noop, 2) @@ -283,10 +297,12 @@ def fail_start(_thread): patch.setattr(threading.Thread, 'start', fail_start) with pytest.raises(AgentTaskError, match='thread'): reference.close() - assert not instance.retired and not channel.retired + assert not instance.retired + assert not channel.retired channel.close = original reference.close() - assert instance.retired and channel.retired + assert instance.retired + assert channel.retired def registry(monkeypatch, channels): @@ -308,10 +324,12 @@ def create(): def test_shared_registry_is_passive_and_replaces_only_a_retired_closed_lifetime(monkeypatch): channels = [Channel(), Channel()] module, pools = registry(monkeypatch, channels) - assert module.shared_status()['state'] == 'not_started' and not pools + assert module.shared_status()['state'] == 'not_started' + assert not pools first, second = module.shared_reference(), module.shared_reference() try: - assert len(pools) == 1 and not channels[0].calls + assert len(pools) == 1 + assert not channels[0].calls old = first.acquire(noop, 2) first.close() assert second.acquire(noop, 2)['generation'] == old['generation'] @@ -321,7 +339,8 @@ def test_shared_registry_is_passive_and_replaces_only_a_retired_closed_lifetime( second.close() fresh = module.shared_reference() try: - assert len(pools) == 2 and pools[0].retired + assert len(pools) == 2 + assert pools[0].retired assert fresh.acquire(noop, 2)['generation'] != old['generation'] first.close() second.close() @@ -374,12 +393,15 @@ def fail_close(): old.close() with pytest.raises(AgentTaskError): module.shared_reference() - assert len(pools) == 1 and not channels[0].retired and not channels[1].calls + assert len(pools) == 1 + assert not channels[0].retired + assert not channels[1].calls finally: channels[0].close = original old.close() fresh = module.shared_reference() try: - assert len(pools) == 2 and pools[0].retired + assert len(pools) == 2 + assert pools[0].retired finally: fresh.close() diff --git a/test/unit_test/headless/test_agent_presence_pool_ipc.py b/test/unit_test/headless/test_agent_presence_pool_ipc.py index f213756f7..4dc22535f 100644 --- a/test/unit_test/headless/test_agent_presence_pool_ipc.py +++ b/test/unit_test/headless/test_agent_presence_pool_ipc.py @@ -47,7 +47,9 @@ def test_actual_pool_retains_one_source_across_reference_and_borrower_replacemen wait_lost(verifier, left) assert verifier.request('check', right, timeout=3)['status'] == 'ok' other.close() - assert borrower.retired and channels[1].retired and not channels[0].retired + assert borrower.retired + assert channels[1].retired + assert not channels[0].retired wait_lost(verifier, borrowed) fresh = instance(namespace, clock, instances, channels).reference() try: @@ -61,7 +63,8 @@ def test_actual_pool_retains_one_source_across_reference_and_borrower_replacemen second.close() if verifier is not None: verifier.close() - assert owner.retired and all(channel.retired for channel in channels) + assert owner.retired + assert all(channel.retired for channel in channels) def test_actual_pool_owner_loss_never_rearms_old_reference_or_imports_old_idle(tmp_path): @@ -81,7 +84,8 @@ def test_actual_pool_owner_loss_never_rearms_old_reference_or_imports_old_idle(t borrower.acquire(noop, 3) with pytest.raises(AgentTaskError): borrower.acquire(noop, 3) - assert len(channels) == 2 and all(channel.retired for channel in channels) + assert len(channels) == 2 + assert all(channel.retired for channel in channels) replacement = instance(namespace, clock, instances, channels).reference() with pytest.raises(AgentControlBusy): replacement.acquire(noop, 15) @@ -128,11 +132,13 @@ def check(): verifier = create(namespace, clock, instances) verifier.request('bootstrap', {}, timeout=15) assert verifier.request('check', original, timeout=3)['status'] == 'ok' - assert len(instances.read_text().splitlines()) == 1 and len(channels) == 1 + assert len(instances.read_text().splitlines()) == 1 + assert len(channels) == 1 finally: gate.unlink(missing_ok=True) first.close() second.close() if verifier is not None: verifier.close() - assert shared.retired and channels[0].retired + assert shared.retired + assert channels[0].retired diff --git a/test/unit_test/headless/test_agent_presence_quartz.py b/test/unit_test/headless/test_agent_presence_quartz.py index c3b70c614..5501f4880 100644 --- a/test/unit_test/headless/test_agent_presence_quartz.py +++ b/test/unit_test/headless/test_agent_presence_quartz.py @@ -90,7 +90,8 @@ def test_only_a_process_posting_from_a_non_hid_state_counts_as_injected(pid, sta def test_hardware_events_count_and_track_held_keys_and_buttons(opened): api, quartz, physical = opened quartz.pending[:] = [event(10, keycode=4), event(1)] - assert api.poll(0) == (True, True) and physical == [1, 1] + assert api.poll(0) == (True, True) + assert physical == [1, 1] quartz.pending[:] = [event(11, keycode=4), event(2)] assert api.poll(0) == (True, False) @@ -98,7 +99,8 @@ def test_hardware_events_count_and_track_held_keys_and_buttons(opened): def test_events_a_process_posted_never_count(opened): api, quartz, physical = opened quartz.pending[:] = [event(10, pid=4242, state=0, keycode=4), event(5, pid=4242, state=-1)] - assert api.poll(0) == (True, False) and physical == [] + assert api.poll(0) == (True, False) + assert physical == [] def test_a_key_down_before_the_tap_started_still_counts_as_held(opened): diff --git a/test/unit_test/headless/test_agent_presence_reader.py b/test/unit_test/headless/test_agent_presence_reader.py index 4beaf84be..a962627da 100644 --- a/test/unit_test/headless/test_agent_presence_reader.py +++ b/test/unit_test/headless/test_agent_presence_reader.py @@ -118,7 +118,8 @@ def test_reader_construction_status_check_before_ready_and_unstarted_close_are_i reader.close() with pytest.raises(AgentTaskError): reader.ready() - assert not harness.events and reader.retired + assert not harness.events + assert reader.retired @pytest.mark.parametrize('binding', [{}, {'generation': 'a' * 32}, {'generation': True, 'lease_id': 'b' * 32}, @@ -140,8 +141,11 @@ def test_each_ready_and_check_is_fresh_serial_io_for_the_same_detached_capabilit assert [item['request_id'] for item in harness.sent] == list(range(1, len(harness.sent) + 1)) assert all(item['operation'] == 'check' and item['body'] == original for item in harness.sent) harness.reader.close() - assert len(harness.threads) == 1 and threading.get_ident() not in harness.threads - assert harness.reader.retired and harness.peer_closed and harness.connection_closed + assert len(harness.threads) == 1 + assert threading.get_ident() not in harness.threads + assert harness.reader.retired + assert harness.peer_closed + assert harness.connection_closed assert not harness.notice.is_set() assert harness.issuer.request({'request_id': 2, 'operation': 'check', 'body': original})['status'] == 'ok' @@ -155,7 +159,8 @@ def test_physical_revision_revokes_reader_between_actions_and_never_rearms(harne harness.reader.check() with pytest.raises(AgentTaskError): harness.reader.ready() - assert harness.events.count('notice') == 1 and harness.events.count('connect') == 1 + assert harness.events.count('notice') == 1 + assert harness.events.count('connect') == 1 def mutate(value, change): @@ -187,7 +192,8 @@ def test_gate_refuses_revoked_malformed_stale_or_changed_source_replies_once(har harness.transform = lambda value: value with pytest.raises(AgentTaskError): harness.reader.ready() - assert harness.events.count('notice') == 1 and harness.events.count('connect') == 1 + assert harness.events.count('notice') == 1 + assert harness.events.count('connect') == 1 def test_existing_lease_may_keep_its_owned_held_input_without_new_acquisition(harness): @@ -208,8 +214,10 @@ def test_first_bind_blocks_are_bounded_and_late_replies_never_authorize(harness, start = time.monotonic() with pytest.raises(AgentTaskError): harness.reader.ready() - assert time.monotonic() - start < 0.7 and harness.entered.is_set() - assert harness.notice.wait(0.3) and not harness.reader.retired + assert time.monotonic() - start < 0.7 + assert harness.entered.is_set() + assert harness.notice.wait(0.3) + assert not harness.reader.retired start = time.monotonic() with pytest.raises(AgentTaskError): harness.reader.close() @@ -246,8 +254,10 @@ def test_close_during_late_connect_retires_only_owned_resources_without_handshak with pytest.raises(AgentTaskError): waiting.result(timeout=1) harness.reader.close() - assert harness.reader.retired and harness.connection_closed - assert 'handshake' not in harness.events and not harness.sent + assert harness.reader.retired + assert harness.connection_closed + assert 'handshake' not in harness.events + assert not harness.sent def test_failed_native_close_retains_handle_and_explicit_retry_never_reconnects(harness): @@ -255,10 +265,14 @@ def test_failed_native_close_retains_handle_and_explicit_retry_never_reconnects( harness.fail_close = True with pytest.raises(AgentTaskError): harness.reader.close() - assert harness.connection_closed and not harness.peer_closed and not harness.reader.retired + assert harness.connection_closed + assert not harness.peer_closed + assert not harness.reader.retired harness.fail_close = False harness.reader.close() - assert harness.peer_closed and harness.reader.retired and harness.events.count('connect') == 1 + assert harness.peer_closed + assert harness.reader.retired + assert harness.events.count('connect') == 1 assert not harness.notice.is_set() @@ -276,7 +290,9 @@ def start(thread): with pytest.raises(AgentTaskError, match='thread'): harness.reader.ready() harness.reader.close() - assert harness.reader.retired and not harness.sent and harness.events.count('notice') == 1 + assert harness.reader.retired + assert not harness.sent + assert harness.events.count('notice') == 1 def test_cleanup_thread_start_failure_retains_unknown_query_handle_for_explicit_retry(harness, monkeypatch): @@ -293,9 +309,11 @@ def start(_thread): patch.setattr(threading.Thread, 'start', start) with pytest.raises(AgentTaskError, match='thread'): harness.reader.close() - assert not harness.reader.retired and not harness.peer_closed + assert not harness.reader.retired + assert not harness.peer_closed harness.reader.close() - assert harness.reader.retired and harness.events.count('connect') == 1 + assert harness.reader.retired + assert harness.events.count('connect') == 1 def test_reader_checks_actual_peer_liveness_without_connecting_to_another_process(harness): @@ -304,7 +322,8 @@ def test_reader_checks_actual_peer_liveness_without_connecting_to_another_proces with pytest.raises(AgentTaskError): harness.reader.check() assert harness.notice.wait(0.3) - assert harness.events.count('notice') == 1 and harness.events.count('connect') == 1 + assert harness.events.count('notice') == 1 + assert harness.events.count('connect') == 1 @pytest.mark.parametrize('boundary_name', ['on_ack', 'on_prepare']) @@ -330,6 +349,8 @@ def test_reader_loss_does_not_block_worker_owned_release_only_ack_cleanup(harnes harness.source.state.physical() assert harness.notice.wait(0.6) result = boundary.worker._release_owned({'keys': [{'keycode': 65, 'is_shift': False}], 'buttons': []}) - assert result == {'cleaned': True} and 'released' in boundary.events and 'cleaned' in boundary.events + assert result == {'cleaned': True} + assert 'released' in boundary.events + assert 'cleaned' in boundary.events with pytest.raises(AgentTaskError): harness.reader.check() diff --git a/test/unit_test/headless/test_agent_presence_reader_ipc.py b/test/unit_test/headless/test_agent_presence_reader_ipc.py index 7570984fe..9c90cb04f 100644 --- a/test/unit_test/headless/test_agent_presence_reader_ipc.py +++ b/test/unit_test/headless/test_agent_presence_reader_ipc.py @@ -123,7 +123,9 @@ def test_actual_reader_replacement_checks_same_capability_and_never_releases_iss for child in (first, second, owner): if child is not None: child.close() - assert first.retired and second.retired and owner.retired + assert first.retired + assert second.retired + assert owner.retired @pytest.mark.parametrize('mode', ['send', 'receive']) @@ -138,9 +140,12 @@ def test_actual_blocked_watch_retires_owned_reader_job_without_stopping_source(t gate.write_text('block', encoding='utf-8') assert not wait_notice(child)['retired'] closing = child.request('close', {}, timeout=3) - assert not closing['ok'] and not closing['retired'] and closing['elapsed'] < 0.7 + assert not closing['ok'] + assert not closing['retired'] + assert closing['elapsed'] < 0.7 child.close() - assert child.retired and not owner.retired + assert child.retired + assert not owner.retired assert owner.request('check', binding, timeout=3)['status'] == 'ok' assert len(instances.read_text().splitlines()) == 1 finally: @@ -159,12 +164,17 @@ def test_actual_first_bind_and_uncertain_handoff_never_claim_reader_retirement(t gate.write_text('block', encoding='utf-8') child = reader(namespace, gate, mode) initial = child.request('bootstrap', binding, timeout=15) - assert not initial['ok'] and initial['notice'] and initial['elapsed'] < 0.7 + assert not initial['ok'] + assert initial['notice'] + assert initial['elapsed'] < 0.7 assert not initial['retired'] closing = child.request('close', {}, timeout=3) - assert not closing['ok'] and not closing['retired'] and closing['elapsed'] < 0.7 + assert not closing['ok'] + assert not closing['retired'] + assert closing['elapsed'] < 0.7 child.close() - assert child.retired and not owner.retired + assert child.retired + assert not owner.retired assert owner.request('check', binding, timeout=3)['status'] == 'ok' finally: if child is not None: diff --git a/test/unit_test/headless/test_agent_presence_runtime.py b/test/unit_test/headless/test_agent_presence_runtime.py index ff1ac2856..8ce50c083 100644 --- a/test/unit_test/headless/test_agent_presence_runtime.py +++ b/test/unit_test/headless/test_agent_presence_runtime.py @@ -73,12 +73,14 @@ def test_two_runtime_databases_keep_one_source_across_input_task_and_borrower_re first, second = fixture.runtime('one'), fixture.runtime('two') try: left, right = first.submit(spec()), second.submit(spec()) - assert not fixture.source.calls and not fixture.helpers + assert not fixture.source.calls + assert not fixture.helpers first.observe(left.task_id) first.pause(left.task_id) second.observe(right.task_id) bindings = fixture.bindings() - assert len(bindings) == 2 and bindings[0]['generation'] == bindings[1]['generation'] + assert len(bindings) == 2 + assert bindings[0]['generation'] == bindings[1]['generation'] assert bindings[0]['lease_id'] != bindings[1]['lease_id'] assert sum(name == 'bootstrap' for name, _body in fixture.source.calls) == 1 first.close() @@ -89,7 +91,9 @@ def test_two_runtime_databases_keep_one_source_across_input_task_and_borrower_re finally: first.close() second.close() - assert fixture.source.retired and fixture.pool.retired and all(helper.retired for helper in fixture.helpers) + assert fixture.source.retired + assert fixture.pool.retired + assert all(helper.retired for helper in fixture.helpers) def test_new_task_uses_a_new_lease_without_resetting_runtime_source_idle(fixture): @@ -100,8 +104,10 @@ def test_new_task_uses_a_new_lease_without_resetting_runtime_source_idle(fixture second = runtime.submit(spec()) runtime.observe(second.task_id) left, right = fixture.bindings() - assert left['generation'] == right['generation'] and left['lease_id'] != right['lease_id'] - assert len(fixture.helpers) == 2 and fixture.helpers[0].retired + assert left['generation'] == right['generation'] + assert left['lease_id'] != right['lease_id'] + assert len(fixture.helpers) == 2 + assert fixture.helpers[0].retired def test_custom_reviewed_worker_and_passive_runtime_paths_never_bind_presence(fixture): @@ -110,7 +116,8 @@ def test_custom_reviewed_worker_and_passive_runtime_paths_never_bind_presence(fi runtime.list() runtime.get(task.task_id) runtime.observe(task.task_id) - assert not fixture.source.calls and not fixture.bindings() + assert not fixture.source.calls + assert not fixture.bindings() def test_failed_source_retirement_keeps_runtime_and_store_owned_for_explicit_retry(fixture, monkeypatch): @@ -127,14 +134,16 @@ def fail(): monkeypatch.setattr(reference, 'close', fail) with pytest.raises(AgentTaskError, match='unproven'): runtime.close() - assert not runtime._closed and not runtime._leases + assert not runtime._closed + assert not runtime._leases assert all(helper.retired for helper in fixture.helpers) with pytest.raises(AgentControlBusy): fixture.runtime('one') finally: monkeypatch.setattr(reference, 'close', original) runtime.close() - assert runtime._closed and fixture.pool.retired + assert runtime._closed + assert fixture.pool.retired def test_runtime_close_during_first_acquire_cancels_caller_before_final_source_closure(fixture): @@ -149,11 +158,13 @@ def test_runtime_close_during_first_acquire_cancels_caller_before_final_source_c runtime.close() with pytest.raises(CancelledError): waiting.result(timeout=1) - assert not fixture.source.retired and not runtime._closed + assert not fixture.source.retired + assert not runtime._closed finally: fixture.source.allow.set() runtime.close() - assert fixture.pool.retired and all(helper.retired for helper in fixture.helpers) + assert fixture.pool.retired + assert all(helper.retired for helper in fixture.helpers) def test_cancelled_host_scope_never_opens_input_resource_or_helper_before_bind(fixture): @@ -167,7 +178,9 @@ def cancelled(): with pytest.raises(CancelledError): adapter.ready(definition) try: - assert adapter._resource is None and adapter._channel is None and not fixture.helpers + assert adapter._resource is None + assert adapter._channel is None + assert not fixture.helpers assert not fixture.source.calls finally: adapter.cleanup() @@ -178,7 +191,8 @@ def test_passive_target_description_exposes_coarse_presence_without_creating_a_s summary, = runtime.target_profiles.describe()['targets'] assert summary['presence']['state'] in {'not_bound', 'not_supported'} assert summary['presence']['native_evidence'] == 'not_recorded' - assert not fixture.source.calls and not fixture.helpers + assert not fixture.source.calls + assert not fixture.helpers def test_unsupported_default_desktop_refuses_before_helper_or_input_journal(fixture, monkeypatch): @@ -189,7 +203,8 @@ def test_unsupported_default_desktop_refuses_before_helper_or_input_journal(fixt task = runtime.submit(spec()) with pytest.raises(AgentControlBusy, match='Windows'): runtime.observe(task.task_id) - assert not fixture.helpers and not fixture.source.calls + assert not fixture.helpers + assert not fixture.source.calls def test_named_owner_takeover_is_negative_only_and_old_helper_notice_cannot_stop_resumed_lease(fixture): @@ -211,7 +226,8 @@ def test_named_owner_takeover_is_negative_only_and_old_helper_notice_cannot_stop deadline = time.monotonic() + 1 while runtime.get(task.task_id).state != 'paused' and time.monotonic() < deadline: time.sleep(0.01) - assert runtime.get(task.task_id).state == 'paused' and not runtime._leases + assert runtime.get(task.task_id).state == 'paused' + assert not runtime._leases def test_task_options_cannot_select_source_provider_or_presence_capability(fixture): diff --git a/test/unit_test/headless/test_agent_presence_runtime_ipc.py b/test/unit_test/headless/test_agent_presence_runtime_ipc.py index 8f067685c..deba4f669 100644 --- a/test/unit_test/headless/test_agent_presence_runtime_ipc.py +++ b/test/unit_test/headless/test_agent_presence_runtime_ipc.py @@ -118,14 +118,17 @@ def test_actual_two_runtime_databases_and_standard_helpers_share_idle_and_source second, right_target = fixture.runtime('two') try: left, right = first.submit(spec()), second.submit(spec()) - assert not fixture.sources and not fixture.helpers + assert not fixture.sources + assert not fixture.helpers fixture.first_observation(first, left) old = dict(left_target._presence._grant.binding) first.pause(left.task_id) second.observe(right.task_id) current = dict(right_target._presence._grant.binding) - assert current['generation'] == old['generation'] and current['lease_id'] != old['lease_id'] - assert len(fixture.sources) == 1 and len(fixture.instances.read_text().splitlines()) == 1 + assert current['generation'] == old['generation'] + assert current['lease_id'] != old['lease_id'] + assert len(fixture.sources) == 1 + assert len(fixture.instances.read_text().splitlines()) == 1 first.close() assert not fixture.sources[0].retired second.observe(right.task_id) @@ -148,8 +151,10 @@ def test_actual_worker_watch_notice_pauses_and_explicit_resume_waits_fresh_idle( deadline = time.monotonic() + 3 while runtime.get(task.task_id).state != 'paused' and time.monotonic() < deadline: time.sleep(0.01) - assert runtime.get(task.task_id).state == 'paused' and not runtime._leases - assert target._channel is None and target._ledger.empty + assert runtime.get(task.task_id).state == 'paused' + assert not runtime._leases + assert target._channel is None + assert target._ledger.empty assert not fixture.sources[0].retired runtime.resume(task.task_id) with pytest.raises(AgentControlBusy): @@ -157,8 +162,10 @@ def test_actual_worker_watch_notice_pauses_and_explicit_resume_waits_fresh_idle( fixture.clock.write_text('120', encoding='utf-8') runtime.observe(task.task_id) current = target._presence._grant.binding - assert current['generation'] == original['generation'] and current['lease_id'] != original['lease_id'] - assert len(fixture.sources) == 1 and len(fixture.instances.read_text().splitlines()) == 1 + assert current['generation'] == original['generation'] + assert current['lease_id'] != original['lease_id'] + assert len(fixture.sources) == 1 + assert len(fixture.instances.read_text().splitlines()) == 1 assert fixture.retired() @@ -174,15 +181,18 @@ def test_actual_source_owner_loss_requires_new_generation_and_explicit_fresh_idl while (runtime.get(task.task_id).state != 'paused' or not fixture.pools[0].retired ) and time.monotonic() < deadline: time.sleep(0.01) - assert runtime.get(task.task_id).state == 'paused' and fixture.pools[0].retired - assert len(fixture.sources) == 1 and target._channel is None + assert runtime.get(task.task_id).state == 'paused' + assert fixture.pools[0].retired + assert len(fixture.sources) == 1 + assert target._channel is None runtime.resume(task.task_id) with pytest.raises(AgentControlBusy): runtime.observe(task.task_id) fixture.clock.write_text('120', encoding='utf-8') runtime.observe(task.task_id) assert target._presence._grant.binding['generation'] != previous['generation'] - assert len(fixture.sources) == 2 and len(fixture.instances.read_text().splitlines()) == 2 + assert len(fixture.sources) == 2 + assert len(fixture.instances.read_text().splitlines()) == 2 assert fixture.retired() @@ -202,12 +212,15 @@ def test_actual_reader_loss_cannot_release_input_lease_until_owned_ack_cleanup_s deadline = time.monotonic() + 3 while (target._channel is not None and not target._channel.retired) and time.monotonic() < deadline: time.sleep(0.01) - assert runtime.get(task.task_id).state == 'pausing' and runtime._leases + assert runtime.get(task.task_id).state == 'pausing' + assert runtime._leases deadline = time.monotonic() + 1 while target.presence_status['takeover']['cleanup_error'] is None and time.monotonic() < deadline: time.sleep(0.01) assert target.presence_status['takeover']['cleanup_error'] == 'AgentTaskError' - assert not target._ledger.empty and target._resource is not None and target._presence._grant is not None + assert not target._ledger.empty + assert target._resource is not None + assert target._presence._grant is not None with pytest.raises(AgentTaskError): runtime.resume(task.task_id) other = runtime.submit(spec()) @@ -215,8 +228,11 @@ def test_actual_reader_loss_cannot_release_input_lease_until_owned_ack_cleanup_s runtime.observe(other.task_id) failed.unlink() runtime.pause(task.task_id) - assert runtime.get(task.task_id).state == 'paused' and not runtime._leases and target._ledger.empty - assert target._resource is None and target._presence._grant is None + assert runtime.get(task.task_id).state == 'paused' + assert not runtime._leases + assert target._ledger.empty + assert target._resource is None + assert target._presence._grant is None fixture.clock.write_text('120', encoding='utf-8') runtime.observe(other.task_id) assert (tmp_path / 'input-events.txt').read_text().splitlines() == ['pressed', 'released'] diff --git a/test/unit_test/headless/test_agent_presence_security.py b/test/unit_test/headless/test_agent_presence_security.py index 95798dd94..ce748c786 100644 --- a/test/unit_test/headless/test_agent_presence_security.py +++ b/test/unit_test/headless/test_agent_presence_security.py @@ -38,7 +38,8 @@ def __init__(self, module): ConvertStringSecurityDescriptorToSecurityDescriptorW=Function(self.descriptor)) def open(self, access, inherit, pid): - assert access == 0x101000 and not inherit + assert access == 0x101000 + assert not inherit handle = 0x100000000 + pid self.handles[handle] = pid return handle @@ -114,7 +115,8 @@ def test_constructor_is_inert_and_current_identity_releases_all_query_handles(): assert not fake.kernel.OpenProcess.calls value = api.current() assert (value.pid, value.sid, value.session, value.birth) == (10, fake.sid, 2, (1 << 32) + 10) - assert not fake.handles and not fake.buffers + assert not fake.handles + assert not fake.buffers assert fake.kernel.OpenProcess.restype is ctypes.c_void_p @@ -122,7 +124,8 @@ def test_constructor_is_inert_and_current_identity_releases_all_query_handles(): def test_peer_identity_comes_from_connected_pipe_and_only_owned_handles_are_closed(server): api, fake = native() peer = api.peer(999, server=server) - assert peer.identity.pid == 11 and peer.identity.birth == (1 << 32) + 11 + assert peer.identity.pid == 11 + assert peer.identity.birth == (1 << 32) + 11 assert peer.alive() getter = fake.kernel.GetNamedPipeClientProcessId if server else fake.kernel.GetNamedPipeServerProcessId assert len(getter.calls) == 1 @@ -130,7 +133,8 @@ def test_peer_identity_comes_from_connected_pipe_and_only_owned_handles_are_clos peer.close() peer.close() assert not peer.alive() - assert not fake.handles and not fake.buffers + assert not fake.handles + assert not fake.buffers @pytest.mark.parametrize('attribute,value', [('peer_sid', 'S-1-5-21-2'), ('peer_session', 3), ('live', False)]) @@ -139,7 +143,8 @@ def test_wrong_os_user_session_or_dead_peer_is_refused_without_process_terminati setattr(fake, attribute, value) with pytest.raises(AgentTaskError): api.peer(999, server=False) - assert not fake.handles and not fake.buffers + assert not fake.handles + assert not fake.buffers @pytest.mark.parametrize('attribute,value', [('token_ok', False), ('info_ok', False), @@ -149,7 +154,8 @@ def test_invalid_token_data_cannot_select_endpoint_or_descriptor_and_keeps_no_ha setattr(fake, attribute, value) with pytest.raises(AgentTaskError): api.current() - assert not fake.handles and not fake.buffers + assert not fake.handles + assert not fake.buffers assert not fake.advapi.ConvertStringSecurityDescriptorToSecurityDescriptorW.calls @@ -157,11 +163,13 @@ def test_pipe_security_descriptor_grants_only_current_user_system_and_is_not_inh api, fake = native() with api.attributes() as value: assert value.length == ctypes.sizeof(type(value)) - assert value.inherit == 0 and value.descriptor + assert value.inherit == 0 + assert value.descriptor assert len(fake.buffers) == 1 text = fake.advapi.ConvertStringSecurityDescriptorToSecurityDescriptorW.calls[0][0] assert text == 'D:P(A;;GA;;;SY)(A;;GA;;;S-1-5-21-1)' - assert not fake.handles and not fake.buffers + assert not fake.handles + assert not fake.buffers def test_endpoint_is_derived_from_actual_sid_session_and_survives_process_restart(): @@ -182,6 +190,9 @@ def test_real_current_process_identity_is_query_only_and_never_starts_observatio api = WindowsPresenceSecurity() value = api.current() assert value.pid == os.getpid() - assert value.sid.startswith('S-1-') and value.birth > 0 and value.session >= 0 + assert value.sid.startswith('S-1-') + assert value.birth > 0 + assert value.session >= 0 with api.attributes() as attributes: - assert attributes.descriptor and not attributes.inherit + assert attributes.descriptor + assert not attributes.inherit diff --git a/test/unit_test/headless/test_agent_presence_server.py b/test/unit_test/headless/test_agent_presence_server.py index c26b4a7cd..b7f48957e 100644 --- a/test/unit_test/headless/test_agent_presence_server.py +++ b/test/unit_test/headless/test_agent_presence_server.py @@ -86,7 +86,8 @@ def connected(pipe): def test_constructor_close_and_status_do_not_reserve_or_construct_an_observer(monkeypatch): server, _source, _pipe, events = service(monkeypatch) - assert not server.status()['running'] and not events + assert not server.status()['running'] + assert not events server.close() assert not events with pytest.raises(AgentTaskError): @@ -107,7 +108,8 @@ def test_reservation_precedes_observation_and_failed_start_keeps_no_ready_servic with pytest.raises(AgentTaskError): server.start() assert events[:3] == ['reserve', 'construct', 'start'] - assert 'listener-close' in events and 'source-close' in events + assert 'listener-close' in events + assert 'source-close' in events assert not server.status()['running'] @@ -122,10 +124,12 @@ def test_busy_preserves_shared_source_and_disconnect_revokes_only_issued_tokens( assert lease['generation'] == ready['generation'] assert second.request(1, 'check', lease)['status'] == 'ok' first.close() - assert source.released.wait(1) and first.peer_closed.wait(1) + assert source.released.wait(1) + assert first.peer_closed.wait(1) assert second.request(2, 'check', lease)['status'] == 'lease_lost' assert second.request(3, 'inspect')['result']['generation'] == ready['generation'] - assert 'source-close' not in events and server.status()['running'] + assert 'source-close' not in events + assert server.status()['running'] finally: server.close() @@ -172,7 +176,8 @@ def test_close_fences_leases_and_retires_only_this_server_resources(monkeypatch) server.close() server.close() assert time.monotonic() - started < 2 - assert client.closed.is_set() and 'listener-close' in events + assert client.closed.is_set() + assert 'listener-close' in events assert not server.status()['running'] with pytest.raises(AgentTaskError): source.state.check(**lease) diff --git a/test/unit_test/headless/test_agent_presence_service_ipc.py b/test/unit_test/headless/test_agent_presence_service_ipc.py index 337b86ef5..765b2db01 100644 --- a/test/unit_test/headless/test_agent_presence_service_ipc.py +++ b/test/unit_test/headless/test_agent_presence_service_ipc.py @@ -102,7 +102,8 @@ def test_two_actual_brokers_share_generation_busy_and_borrower_only_token_cleanu ready = owner.request('bootstrap', {}, timeout=15) assert borrower.request('bootstrap', {}, timeout=15) == ready assert owner.request('acquire', {}, timeout=3)['status'] == 'busy' - assert not owner.retired and len(instances.read_text().splitlines()) == 1 + assert not owner.retired + assert len(instances.read_text().splitlines()) == 1 clock.write_text('60', encoding='utf-8') first = owner.request('acquire', {}, timeout=3)['result'] second = borrower.request('acquire', {}, timeout=3)['result'] @@ -115,7 +116,8 @@ def test_two_actual_brokers_share_generation_busy_and_borrower_only_token_cleanu finally: borrower.close() owner.close() - assert borrower.retired and owner.retired + assert borrower.retired + assert owner.retired def test_actual_owner_loss_refuses_old_leases_and_replacement_observes_fresh_idle(tmp_path): @@ -130,7 +132,8 @@ def test_actual_owner_loss_refuses_old_leases_and_replacement_observes_fresh_idl owner.close() with pytest.raises(AgentTaskError): borrower.request('check', old, timeout=3) - assert borrower.retired and len(instances.read_text().splitlines()) == 1 + assert borrower.retired + assert len(instances.read_text().splitlines()) == 1 replacement = create(namespace, clock, instances) new = replacement.request('bootstrap', {}, timeout=15) assert new['generation'] != ready['generation'] @@ -155,7 +158,8 @@ def test_concurrent_actual_startup_constructs_only_the_first_instance_source(tmp right = pool.submit(second.request, 'bootstrap', {}, timeout=15) assert left.result(timeout=16) == right.result(timeout=16) records = [json.loads(line) for line in instances.read_text().splitlines()] - assert len(records) == 1 and records[0]['generation'] == left.result()['generation'] + assert len(records) == 1 + assert records[0]['generation'] == left.result()['generation'] assert first.request('acquire', {}, timeout=3)['status'] == 'busy' assert second.request('acquire', {}, timeout=3)['status'] == 'busy' finally: @@ -187,7 +191,8 @@ def test_borrower_lost_during_acquire_revokes_late_token_without_stopping_the_ow wait_file(tmp_path / 'acquire-entered') with pytest.raises(AgentTaskError, match='deadline'): waiting.result(timeout=4) - assert borrower.retired and not owner.retired + assert borrower.retired + assert not owner.retired gate.unlink() wait_file(tmp_path / 'releases.txt') assert owner.request('check', lease, timeout=3)['status'] == 'ok' diff --git a/test/unit_test/headless/test_agent_presence_service_linux.py b/test/unit_test/headless/test_agent_presence_service_linux.py index a258ee4f2..81bb28dca 100644 --- a/test/unit_test/headless/test_agent_presence_service_linux.py +++ b/test/unit_test/headless/test_agent_presence_service_linux.py @@ -119,7 +119,8 @@ def test_an_owned_worker_hands_its_endpoint_to_the_broker_and_serves_presence(tm broker = OwnedChannel([sys.executable, '-u', '-c', _broker_script(clock)]) try: ready = broker.request('bootstrap', {}, timeout=15) - assert ready['ready'] is True and len(ready['generation']) == 32, json.dumps(ready) + assert ready['ready'] is True, json.dumps(ready) + assert len(ready['generation']) == 32, json.dumps(ready) assert broker.request('acquire', {}, timeout=3)['status'] == 'busy' clock.write_text('60', encoding='utf-8') lease = broker.request('acquire', {}, timeout=3)['result'] diff --git a/test/unit_test/headless/test_agent_presence_session.py b/test/unit_test/headless/test_agent_presence_session.py index 83ab5f84a..84fd8e6d6 100644 --- a/test/unit_test/headless/test_agent_presence_session.py +++ b/test/unit_test/headless/test_agent_presence_session.py @@ -29,7 +29,8 @@ def metric(self, code): return self.metric_remote if code == 0x1000 else self.metric_shadow def query(self, server, session, info, pointer, count): - assert server is None and session == 0xFFFFFFFF + assert server is None + assert session == 0xFFFFFFFF value = ctypes.c_uint16(self.protocol) if info == 16 else ctypes.c_int32( self.remote if info == 29 else self.state) assert info in (16, 29, 8) @@ -52,7 +53,8 @@ def console(native): def test_console_guard_construction_is_inert_and_all_checks_use_current_local_session_queries(): native = Native() guard = console(native) - assert not native.kernel.GetCurrentProcessId.calls and not native.freed + assert not native.kernel.GetCurrentProcessId.calls + assert not native.freed guard.check() guard.check() assert [row[2] for row in native.wts.WTSQuerySessionInformationW.calls] == [16, 29, 8] * 2 @@ -101,7 +103,8 @@ def refuse(): api._support.session = refuse with pytest.raises(AgentTaskError, match='console'): api.open(lambda: None) - assert not native.user.CreateWindowExW.calls and not native.user.RegisterClassW.calls + assert not native.user.CreateWindowExW.calls + assert not native.user.RegisterClassW.calls def test_observer_rechecks_supported_session_for_every_fresh_poll(monkeypatch): diff --git a/test/unit_test/headless/test_agent_presence_transport.py b/test/unit_test/headless/test_agent_presence_transport.py index 09d52270d..c5d027104 100644 --- a/test/unit_test/headless/test_agent_presence_transport.py +++ b/test/unit_test/headless/test_agent_presence_transport.py @@ -85,7 +85,8 @@ def listening(namespace): try: ready = server.request('listen', {'namespace': namespace}, timeout=15) expected = Path(__file__).resolve().parents[3] / 'je_auto_control/utils/agent_runtime/presence_pipe_windows.py' - assert ready['ready'] and Path(ready['origin']) == expected + assert ready['ready'] + assert Path(ready['origin']) == expected return server, ready except BaseException: server.close() @@ -111,7 +112,8 @@ def pair(): finally: client.close() server.close() - assert client.retired and server.retired + assert client.retired + assert server.retired def test_actual_background_peer_challenges_and_bounded_bytes_round_trip(pair): @@ -131,7 +133,8 @@ def test_actual_first_instance_rejects_contender_without_retiring_existing_owner try: with pytest.raises(AgentControlBusy): contender.request('listen', {'namespace': namespace}, timeout=15) - assert contender.retired and not server.retired + assert contender.retired + assert not server.retired assert connect(server, client, namespace) == ready['generation'] finally: client.close() @@ -145,7 +148,8 @@ def test_blocked_actual_read_or_write_retires_only_that_owned_helper(pair, opera started = time.monotonic() with pytest.raises(AgentTaskError, match='deadline'): client.request(operation, {}, timeout=0.25) - assert client.retired and time.monotonic() - started < 5 + assert client.retired + assert time.monotonic() - started < 5 assert server.request('alive', {}, timeout=3) == {'alive': False} assert not server.retired @@ -157,7 +161,8 @@ def test_blocked_actual_accept_retires_owner_and_allows_new_first_instance(): started = time.monotonic() with pytest.raises(AgentTaskError, match='deadline'): server.request('accept', {}, timeout=0.25) - assert server.retired and time.monotonic() - started < 5 + assert server.retired + assert time.monotonic() - started < 5 replacement, new = listening(namespace) try: assert new['generation'] != old['generation'] @@ -183,11 +188,13 @@ def test_actual_half_handshake_is_bounded_by_owned_process_retirement(waiting_se with pytest.raises(AgentTaskError, match='deadline'): client.request('connect', {'namespace': namespace}, timeout=3) assert accepted.result(timeout=16) - assert client.retired and not server.retired + assert client.retired + assert not server.retired return with pytest.raises(AgentTaskError, match='deadline'): waiting.request(operation, payload, timeout=0.25) - assert waiting.retired and not client.retired + assert waiting.retired + assert not client.retired finally: client.close() server.close() diff --git a/test/unit_test/headless/test_agent_presence_worker.py b/test/unit_test/headless/test_agent_presence_worker.py index 1d1709d48..3c853ce8e 100644 --- a/test/unit_test/headless/test_agent_presence_worker.py +++ b/test/unit_test/headless/test_agent_presence_worker.py @@ -36,9 +36,11 @@ def transport(*, namespace): module().run(io.BytesIO(packet()), output, source_factory=construct, pipe_factory=transport) response, = [json.loads(line) for line in output.getvalue().splitlines()] - assert response['id'] == 'a' * 32 and response['result']['ready'] is True + assert response['id'] == 'a' * 32 + assert response['result']['ready'] is True assert events[:3] == ['reserve', 'construct', 'start'] - assert 'source-close' in events and 'listener-close' in events + assert 'source-close' in events + assert 'listener-close' in events def test_worker_does_nothing_before_bootstrap_or_when_endpoint_is_already_owned(): @@ -62,7 +64,8 @@ def test_worker_rejects_untrusted_fields_before_any_transport_or_source_is_const calls, output = [], io.BytesIO() module().run(io.BytesIO(packet(payload)), output, source_factory=lambda: calls.append('source'), pipe_factory=lambda **_kwargs: calls.append('pipe')) - assert not calls and json.loads(output.getvalue())['error_type'] == 'AgentTaskError' + assert not calls + assert json.loads(output.getvalue())['error_type'] == 'AgentTaskError' def test_source_process_is_inert_and_uses_fixed_owned_channel_argv_before_bootstrap(): diff --git a/test/unit_test/headless/test_agent_presence_x11.py b/test/unit_test/headless/test_agent_presence_x11.py index 50f3afef6..d16d556be 100644 --- a/test/unit_test/headless/test_agent_presence_x11.py +++ b/test/unit_test/headless/test_agent_presence_x11.py @@ -93,9 +93,11 @@ def test_xtest_events_never_count_as_physical(opened): def test_real_device_events_count_and_track_what_is_held(opened): api, display, physical = opened display.queue[:] = [raw(13, KEYBOARD, 38)] - assert api.poll(0) == (True, True) and physical == [1] + assert api.poll(0) == (True, True) + assert physical == [1] display.queue[:] = [raw(14, KEYBOARD, 38)] - assert api.poll(0) == (True, False) and physical == [1, 1] + assert api.poll(0) == (True, False) + assert physical == [1, 1] def test_core_state_counts_as_held_even_without_a_tracked_press(opened): @@ -111,7 +113,8 @@ def test_an_unknown_source_refreshes_devices_and_counts_once_it_is_a_real_slave( display.devices.append(SimpleNamespace(deviceid=12, use=3, name='USB mouse')) display.queue[:] = [raw(17, 12)] api.poll(0) - assert physical == [1] and display.queries == 2 + assert physical == [1] + assert display.queries == 2 def test_a_master_device_is_never_a_source(opened): @@ -156,9 +159,11 @@ def foreign_close(): worker = threading.Thread(target=foreign_close) worker.start() worker.join() - assert outcome == ['refused'] and not display.closed + assert outcome == ['refused'] + assert not display.closed api.close() - assert display.selected[-1] == [(0, 0)] and display.closed + assert display.selected[-1] == [(0, 0)] + assert display.closed with pytest.raises(AgentTaskError): api.poll(0) @@ -199,13 +204,15 @@ def test_logind_is_queried_with_a_fixed_argv_and_cached_for_its_interval(monkeyp monkeypatch.setattr(presence_x11.shutil, 'which', lambda _name: '/usr/bin/loginctl') calls, now = [], [0.0] session = LogindSession('c2', runner=_runner('Active=yes\nLockedHint=no', calls=calls), clock=lambda: now[0]) - assert session.interactive() and session.interactive() + assert session.interactive() + assert session.interactive() now[0] = 1.5 session.interactive() assert len(calls) == 2 argv, kwargs = calls[0] assert argv == ['/usr/bin/loginctl', 'show-session', 'c2', '-p', 'Active', '-p', 'LockedHint'] - assert kwargs['shell'] is False and kwargs['timeout'] == 1 + assert kwargs['shell'] is False + assert kwargs['timeout'] == 1 @pytest.mark.skipif(not sys.platform.startswith('linux') or not os.environ.get('DISPLAY'), diff --git a/test/unit_test/headless/test_agent_readiness.py b/test/unit_test/headless/test_agent_readiness.py index b9f864291..3d54f83de 100644 --- a/test/unit_test/headless/test_agent_readiness.py +++ b/test/unit_test/headless/test_agent_readiness.py @@ -25,7 +25,8 @@ def test_every_area_uses_the_closed_vocabulary_and_records_no_native_evidence(): ('linux', {'WAYLAND_DISPLAY': 'wayland-0', 'XDG_SESSION_TYPE': 'wayland'}), ('sunos5', {})): report = _report(platform, environ) - assert report['passive'] is True and report['states'] == list(readiness.STATES) + assert report['passive'] is True + assert report['states'] == list(readiness.STATES) assert {item['state'] for item in report['areas']} <= set(readiness.STATES) assert all(item['native_evidence'] == 'not_recorded' for item in report['areas']) assert 'measured' not in {item['state'] for item in report['areas']} @@ -68,7 +69,8 @@ def test_only_a_platform_with_a_presence_source_reports_one(platform, environ, s def test_a_local_capability_observation_maps_without_becoming_measured(observed, state): status = CapabilityStatus('input', observed, 'win32', 'observed locally', 'none', True) area = _area(_report(input_state=status), 'desktop_input') - assert area['state'] == state and area['observed'] == observed + assert area['state'] == state + assert area['observed'] == observed def test_the_report_never_contacts_a_device_or_imports_the_browser_package(): diff --git a/test/unit_test/headless/test_agent_readonly_completion.py b/test/unit_test/headless/test_agent_readonly_completion.py index ff6d0b57c..30453b420 100644 --- a/test/unit_test/headless/test_agent_readonly_completion.py +++ b/test/unit_test/headless/test_agent_readonly_completion.py @@ -29,15 +29,19 @@ def test_standard_file_reader_is_fresh_scope_bound_and_retires_without_calling_o parent = TaskOperation(definition, lambda: None, None) with operation_scope(parent): with source.completion_reader(definition) as reader: - assert reader.observe()["identity"] == "local-files" and not reader.retired + assert reader.observe()["identity"] == "local-files" + assert not reader.retired with operation_scope(TaskOperation(definition, lambda: None, None)), pytest.raises(AgentTaskError): reader.observe() assert reader.retired with pytest.raises(AgentTaskError, match="closed"): reader.observe() - assert source._channel is None and source._resource is None + assert source._channel is None + assert source._resource is None witness = InputJournal(tmp_path / "input.lock").read() - assert witness["owner"] is None and witness["held"] == {} and witness["in_flight"] is None + assert witness["owner"] is None + assert witness["held"] == {} + assert witness["in_flight"] is None source.observe.assert_not_called() source.perform.assert_not_called() @@ -72,7 +76,8 @@ def test_worker_refuses_native_ack_and_nonempty_cleanup_without_any_target_call( worker._input({"kind": "mouse_press", "x": 1, "y": 2}) with pytest.raises(AgentTaskError, match="cleanup input"): worker._dispatch("cleanup", {"keys": [{"keycode": 65}], "buttons": []}) - assert sink.getvalue() == b"" and not target.method_calls + assert sink.getvalue() == b"" + assert not target.method_calls HELPER = ''' @@ -104,7 +109,8 @@ def test_unexpected_input_from_a_helper_is_not_acked_and_retains_quarantine(tmp_ with pytest.raises(AgentTaskError, match="closed"): reader.observe() witness = InputJournal(path).read() - assert witness["owner"] and witness["in_flight"] == "readonly_input_violation" + assert witness["owner"] + assert witness["in_flight"] == "readonly_input_violation" assert json.loads(path.with_suffix(".lock.journal").read_text())["owner"] @@ -166,7 +172,8 @@ def supports_readonly_completion(self): try: report = runtime.target_profiles.describe()["targets"][0] assert report["readonly_completion"] == {"status": "not_supported"} - assert report["readiness"] == "not_probed" and report["native_evidence"] == "not_recorded" + assert report["readiness"] == "not_probed" + assert report["native_evidence"] == "not_recorded" finally: runtime.close() diff --git a/test/unit_test/headless/test_agent_reauthorization.py b/test/unit_test/headless/test_agent_reauthorization.py index 5c0ccaee9..1baa26585 100644 --- a/test/unit_test/headless/test_agent_reauthorization.py +++ b/test/unit_test/headless/test_agent_reauthorization.py @@ -152,7 +152,8 @@ def test_host_reapproval_without_a_client_origin_is_explicit_and_still_source_bo assert "origin_policies" not in request["spec"]["options"] child = runtime.recovery.control("create_authorized", request)["task_id"] proof = runtime.get(child).metadata["recovery"]["reauthorization"] - assert proof["actor"] == "local" and list(proof["context"]["current_origins"]) == [] + assert proof["actor"] == "local" + assert list(proof["context"]["current_origins"]) == [] assert list(proof["context"]["replaced_origins"]) == [old_id] @@ -273,9 +274,12 @@ def test_dynamic_tasks_reauthorize_without_inventing_steps_or_contacting_a_model monkeypatch.setattr("je_auto_control.utils.agent_runtime.ollama.request_json", network) with origin_scope(current_id): view = runtime.recovery.control("review_authorization", {"task_id": source}) - assert view["draft"] is None and view["completed_steps"] is None and view["remaining_actions"] == [] + assert view["draft"] is None + assert view["completed_steps"] is None + assert view["remaining_actions"] == [] spec = view["review_template"] - assert spec["goal"] == "" and spec["mode"] == mode + assert spec["goal"] == "" + assert spec["mode"] == mode spec["goal"] = "Process only the remaining field under the new report scope" child = runtime.recovery.control("create_authorized", {"task_id": source, "snapshot": view["snapshot"], "authorization_review": view["authorization_review"], "spec": spec, "note": "Reviewed the new source"}) @@ -291,7 +295,8 @@ def test_inaccessible_completion_scope_produces_no_runnable_authorization_draft( connection.execute("UPDATE agent_tasks SET spec=? WHERE id=?", (json.dumps(data), source)) with origin_scope(current_id): view = runtime.recovery.control("review_authorization", {"task_id": source}) - assert view["draft"] is None and view["review_template"] is None + assert view["draft"] is None + assert view["review_template"] is None assert view["issues"] == ["authorization_scope_unavailable"] assert len(runtime.list()) == 1 diff --git a/test/unit_test/headless/test_agent_reauthorization_surfaces.py b/test/unit_test/headless/test_agent_reauthorization_surfaces.py index 9eab882ff..18175b567 100644 --- a/test/unit_test/headless/test_agent_reauthorization_surfaces.py +++ b/test/unit_test/headless/test_agent_reauthorization_surfaces.py @@ -16,7 +16,8 @@ def test_cli_exposes_distinct_review_and_approval_operations_without_startup(): parser = build_parser() for operation in ("review_authorization", "create_authorized"): parsed = parser.parse_args(["agent-task", "recovery", operation, "review.json"]) - assert parsed.recovery_operation == operation and parsed.request == "review.json" + assert parsed.recovery_operation == operation + assert parsed.request == "review.json" def test_authenticated_http_reapproval_keeps_owner_and_scope_bound(service, tmp_path, monkeypatch): diff --git a/test/unit_test/headless/test_agent_recovery_ownership.py b/test/unit_test/headless/test_agent_recovery_ownership.py index 8648390dd..773af2ba6 100644 --- a/test/unit_test/headless/test_agent_recovery_ownership.py +++ b/test/unit_test/headless/test_agent_recovery_ownership.py @@ -63,7 +63,8 @@ def owned_request(stopped, *, reauthorize=False): def test_admin_source_owned_child_is_adopted_without_broadening_reads(stopped, monkeypatch): client, host, target, _users, owner, actor, batch, definition, _source = stopped value, request = owned_request(stopped) - assert value["ownership"]["owner"] == "owner" and value["ownership"]["actor"] == "reviewer" + assert value["ownership"]["owner"] == "owner" + assert value["ownership"]["actor"] == "reviewer" assert "store_path" not in str(value["ownership"]) child = recovery(stopped, "create", request)["task_id"] assert recovery(stopped, "create", request)["task_id"] == child @@ -79,7 +80,8 @@ def test_admin_source_owned_child_is_adopted_without_broadening_reads(stopped, m selected = review(client, batch, definition, decisions=selected["decisions"]) assert selected["can_approve"] result = run_dag(definition, batch_id=batch["batch_id"], recovery=approval(selected)) - assert result.succeeded and target.count == 3 + assert result.succeeded + assert target.count == 3 def test_default_admin_recovery_keeps_legacy_caller_ownership(stopped): @@ -105,7 +107,8 @@ def test_owned_recovery_rejects_unreviewed_and_caller_authored_identity(stopped, request.pop("owner_policy") with pytest.raises(AgentTaskError): recovery(stopped, "create", request) - assert len(stopped[1].runtime.list()) == 1 and stopped[2].count == 1 + assert len(stopped[1].runtime.list()) == 1 + assert stopped[2].count == 1 @pytest.mark.parametrize("user,role", [("owner", "viewer"), ("reviewer", "viewer"), ("reviewer", "operator")]) @@ -129,7 +132,9 @@ def test_maintenance_retires_owned_successor_when_reviewer_loses_cross_owner_aut # cancelling and a later one settles it. until(lambda: runtime.maintain() or runtime.get(child).state != "cancelling") result = runtime.get(child) - assert result.state == "cancelled" and result.metadata["input_released"] is True and stopped[2].count == 1 + assert result.state == "cancelled" + assert result.metadata["input_released"] is True + assert stopped[2].count == 1 def test_revocation_during_grounding_cannot_reach_successor_input(stopped, monkeypatch): @@ -150,7 +155,8 @@ def revoked(): # successor's input is refused before dispatch, which is what the assertions below hold. with pytest.raises((AuthorizationError, CancelledError)): instance.act(child, {"tool": "AC_increment", "observation_id": frame.observation_id}) - assert target.count == 1 and [item["status"] for item in instance.store.actions(child)] == ["failed"] + assert target.count == 1 + assert [item["status"] for item in instance.store.actions(child)] == ["failed"] @pytest.mark.parametrize("reauthorize", [False, True]) @@ -164,7 +170,8 @@ def test_owned_admission_failure_rolls_back_task_lineage_and_both_audits(stopped with stopped[1].runtime.store.connection() as connection: for table in ("agent_task_recoveries", "agent_task_authorizations", "agent_recovery_owners"): assert connection.execute("SELECT COUNT(*) FROM " + table).fetchone()[0] == 0 - assert len(stopped[1].runtime.list()) == 1 and stopped[2].count == 1 + assert len(stopped[1].runtime.list()) == 1 + assert stopped[2].count == 1 def test_owned_and_default_recovery_retries_cannot_switch_accepted_policy(stopped): @@ -220,7 +227,8 @@ def test_changed_live_owner_role_requires_a_fresh_ownership_review_even_when_inp recovery(stopped, "create", request) _value, fresh = owned_request(stopped) assert fresh["ownership_review"] != request["ownership_review"] - assert recovery(stopped, "create", fresh)["state"] == "queued" and stopped[2].count == 1 + assert recovery(stopped, "create", fresh)["state"] == "queued" + assert stopped[2].count == 1 def test_ownership_audit_outlives_child_retention_until_source_retention_cascades_it(standalone): diff --git a/test/unit_test/headless/test_agent_recovery_surfaces.py b/test/unit_test/headless/test_agent_recovery_surfaces.py index 5e8b655a3..abe280ea4 100644 --- a/test/unit_test/headless/test_agent_recovery_surfaces.py +++ b/test/unit_test/headless/test_agent_recovery_surfaces.py @@ -72,7 +72,8 @@ def test_http_dynamic_replan_preserves_scope_and_waits_for_new_results(service, client.call("pause", {"task_id": source.task_id}) view = client.call("recovery", {"operation": "preview", "request": {"task_id": source.task_id}}) instance.runtime.background.start.assert_not_called() - assert view["draft"] is None and view["review_template"]["goal"] == "" + assert view["draft"] is None + assert view["review_template"]["goal"] == "" reviewed = view["review_template"] reviewed["goal"] = "Process only the remaining field and read its final value" child = client.call("recovery", {"operation": "create", "request": {"task_id": source.task_id, diff --git a/test/unit_test/headless/test_agent_remote_effect.py b/test/unit_test/headless/test_agent_remote_effect.py index 16a39bf22..2a461d5d8 100644 --- a/test/unit_test/headless/test_agent_remote_effect.py +++ b/test/unit_test/headless/test_agent_remote_effect.py @@ -130,7 +130,8 @@ def test_child_configuration_cannot_equate_json_boolean_or_float_to_integer(valu sink, adapter = io.BytesIO(), Adapter() RemoteWorker(source, sink, adapter).run() replies = [json.loads(line) for line in sink.getvalue().splitlines()] - assert replies[0]['result']['ready'] is True and 'error' in replies[1] + assert replies[0]['result']['ready'] is True + assert 'error' in replies[1] assert not adapter.calls diff --git a/test/unit_test/headless/test_agent_remote_worker.py b/test/unit_test/headless/test_agent_remote_worker.py index cc1a5c9ba..653c17f44 100644 --- a/test/unit_test/headless/test_agent_remote_worker.py +++ b/test/unit_test/headless/test_agent_remote_worker.py @@ -91,7 +91,8 @@ def test_real_worker_brackets_single_sdk_calls_and_refreshes_sequence(tmp_path, assert adapter.ready(fixture_scope) == (True, '') assert adapter.perform('AC_increment', {}) == {'value': 1} assert (tmp_path / 'effects').read_text().splitlines() == ['invoke', 'invoke'] - assert adapter._journal.sequence == 3 and not adapter._journal.pending + assert adapter._journal.sequence == 3 + assert not adapter._journal.pending assert adapter.observe() == {'user': None, 'role': None} finally: release_fixture(adapter) @@ -127,7 +128,8 @@ def test_local_return_or_failure_cannot_clear_unproved_remote_effect(tmp_path, f adapter.perform('AC_increment', {'mode': mode}) assert 'private-password-and-command' not in str(error.value) assert (tmp_path / 'effects').read_text().splitlines() == ['invoke'] - assert adapter._channel.retired and adapter._journal.pending + assert adapter._channel.retired + assert adapter._journal.pending with pytest.raises(AgentTaskError, match='quarantined'): adapter.cleanup() finally: @@ -162,7 +164,8 @@ def checkpoint(): with pytest.raises((CancelledError, AgentTaskError)): adapter.perform('AC_increment', {'mode': 'hang'}) assert (tmp_path / 'effects').read_text().splitlines() == ['invoke'] - assert adapter._journal.pending and adapter._channel.retired + assert adapter._journal.pending + assert adapter._channel.retired assert not adapter.can_reobserve finally: release_fixture(adapter) @@ -239,6 +242,7 @@ def revoke(journal, event): with pytest.raises(AgentTaskError): adapter.perform('AC_increment', {}) assert not (tmp_path / 'effects').exists() - assert adapter._journal.pending and adapter._channel.retired + assert adapter._journal.pending + assert adapter._channel.retired finally: release_fixture(adapter) diff --git a/test/unit_test/headless/test_agent_request_lookup.py b/test/unit_test/headless/test_agent_request_lookup.py index 109a4f791..b90e50aaa 100644 --- a/test/unit_test/headless/test_agent_request_lookup.py +++ b/test/unit_test/headless/test_agent_request_lookup.py @@ -21,9 +21,11 @@ def test_lookup_miss_then_late_acceptance_does_not_create_or_dispatch_work(tmp_p assert runtime.list() == [] task = runtime.submit(specification(), idempotency_key="late-key") result = runtime.lookup("late-key") - assert result["found"] is True and result["task"]["task_id"] == task.task_id + assert result["found"] is True + assert result["task"]["task_id"] == task.task_id assert result["task"]["state"] == "queued" - assert target.calls == [] and not runtime._leases + assert target.calls == [] + assert not runtime._leases assert runtime.store.actions(task.task_id) == [] finally: runtime.close() @@ -89,7 +91,8 @@ def test_accepted_key_survives_service_restart_without_resume(tmp_path): replacement = AgentRuntime(tmp_path / "tasks.sqlite", targets={"fixture": FakeTarget()}) try: found = replacement.lookup("stable-key") - assert found["task"]["task_id"] == task.task_id and found["task"]["state"] == "queued" + assert found["task"]["task_id"] == task.task_id + assert found["task"]["state"] == "queued" assert not replacement._leases finally: replacement.close() @@ -118,9 +121,11 @@ def lose_submit(url, **kwargs): with pytest.raises(AgentTaskError, match="lost accepted reply"): client.call("submit", {"spec": specification().to_dict(), "idempotency_key": "lost-reply"}) result = client.call("lookup", {"idempotency_key": "lost-reply"}) - assert result["found"] is True and result["task"]["state"] == "queued" + assert result["found"] is True + assert result["task"]["state"] == "queued" assert calls == ["submit", "lookup"] - assert len(service.runtime.list()) == 1 and not service.runtime._leases + assert len(service.runtime.list()) == 1 + assert not service.runtime._leases assert target.calls == [] with authorization_scope(AuthorizationContext("bob", "operator")): assert client.call("lookup", {"idempotency_key": "lost-reply"})["found"] is False @@ -143,7 +148,8 @@ def test_public_command_mcp_and_api_share_read_only_lookup_contract(): assert ac.lookup_agent_task is api.lookup_agent_task is core.lookup_agent_task is task_api.lookup_agent_task entry = CATALOG["AC_agent_task_lookup"] - assert entry[0] is ac.lookup_agent_task and entry[3] is True + assert entry[0] is ac.lookup_agent_task + assert entry[3] is True registry = build_default_tool_registry() tool = next((tool for tool in registry if tool.name == "ac_agent_task_lookup"), None) assert tool is not None diff --git a/test/unit_test/headless/test_agent_request_match.py b/test/unit_test/headless/test_agent_request_match.py index 46d671a35..ea826991d 100644 --- a/test/unit_test/headless/test_agent_request_match.py +++ b/test/unit_test/headless/test_agent_request_match.py @@ -23,9 +23,11 @@ def test_matching_normalizes_defaults_and_destination_roots_without_dispatch(tmp expected["roots"] = [str(root / "child" / "..")] expected = dict(reversed(list(expected.items()))) match = runtime.lookup("key", expected) - assert match["spec_match_contract"] == 1 and match["spec_match"] == "matches" + assert match["spec_match_contract"] == 1 + assert match["spec_match"] == "matches" assert match["task"]["task_id"] == accepted.task_id - assert target.calls == [] and not runtime._leases + assert target.calls == [] + assert not runtime._leases assert len(runtime.list()) == 1 finally: runtime.close() @@ -51,9 +53,12 @@ def test_changed_reviewed_spec_is_reported_without_resubmission(tmp_path, change else: expected["success_criteria"][0]["value"] = 2 result = runtime.lookup("key", expected) - assert result["found"] is True and result["spec_match"] == "differs" + assert result["found"] is True + assert result["spec_match"] == "differs" assert result["task"]["task_id"] == accepted.task_id - assert target.calls == [] and not runtime._leases and len(runtime.list()) == 1 + assert target.calls == [] + assert not runtime._leases + assert len(runtime.list()) == 1 finally: runtime.close() @@ -66,7 +71,8 @@ def test_lookup_remains_readable_but_matching_is_unverifiable_when_target_is_abs replacement = AgentRuntime(path, targets={}) try: result = replacement.lookup("key", specification()) - assert result["found"] is True and result["task"]["task_id"] == accepted.task_id + assert result["found"] is True + assert result["task"]["task_id"] == accepted.task_id assert result["spec_match"] == "unverifiable" assert not replacement._leases finally: @@ -80,7 +86,8 @@ def test_spec_match_does_not_search_another_owner_or_create_missing_requests(tmp runtime.submit(specification(), idempotency_key="key") with authorization_scope(AuthorizationContext("bob", "operator")): result = runtime.lookup("key", specification()) - assert result["found"] is False and result["spec_match"] == "not_found" + assert result["found"] is False + assert result["spec_match"] == "not_found" assert len(runtime.list()) == 1 finally: runtime.close() @@ -94,8 +101,10 @@ def test_http_spec_match_is_closed_and_never_dispatches(tmp_path): original = specification().to_dict() accepted = client.call("submit", {"spec": original, "idempotency_key": "key"}) result = client.call("lookup", {"idempotency_key": "key", "spec": original}) - assert result["spec_match"] == "matches" and result["task"]["task_id"] == accepted["task_id"] - assert not service.runtime._leases and service.runtime.store.actions(accepted["task_id"]) == [] + assert result["spec_match"] == "matches" + assert result["task"]["task_id"] == accepted["task_id"] + assert not service.runtime._leases + assert service.runtime.store.actions(accepted["task_id"]) == [] for invalid in (None, [], {"unknown": True}): with pytest.raises(AgentTaskError): client.call("lookup", {"idempotency_key": "key", "spec": invalid}) diff --git a/test/unit_test/headless/test_agent_retained_browser_collection.py b/test/unit_test/headless/test_agent_retained_browser_collection.py index 511e57c86..ab005537f 100644 --- a/test/unit_test/headless/test_agent_retained_browser_collection.py +++ b/test/unit_test/headless/test_agent_retained_browser_collection.py @@ -56,7 +56,8 @@ def test_distinct_effect_tasks_keep_their_own_process_on_one_profile(): assert pool.require(source("second")) is second assert first.channel is not second.channel pool.discard("first") - assert first.channel.retired and not second.channel.retired + assert first.channel.retired + assert not second.channel.retired with pytest.raises(AgentTaskError, match="unavailable"): pool.require(source()) pool.close() @@ -111,7 +112,8 @@ def test_capacity_counts_pending_reservations_and_never_evicts_a_borrower(): entries = [retain(pool, source(str(index))) for index in range(15)] borrowed = pool.borrow(source("0")) with pool.reserve(source("pending")) as pending: - assert pending is not None and pool.full + assert pending is not None + assert pool.full with pool.reserve(source("overflow")) as refused: assert refused is None assert not borrowed.channel.retired @@ -135,7 +137,8 @@ def test_unconfirmed_reaping_stays_tracked_unavailable_and_counts_against_capaci entry.channel.failure = False entry.channel.confirmed = True pool.close() - assert entry.channel.retired and not pool.full + assert entry.channel.retired + assert not pool.full def test_collection_close_invalidates_borrow_and_closes_other_owned_processes_after_a_failure(): @@ -229,7 +232,8 @@ def test_failed_detached_transfer_has_one_cleanup_owner_and_can_be_reaped_after_ assert pool.sources() == [row] process.failure = False maintain_retained(runtime) - assert process.retired and pool.sources() == [] + assert process.retired + assert pool.sources() == [] finally: process.failure = False pool.close() diff --git a/test/unit_test/headless/test_agent_retained_browser_detach.py b/test/unit_test/headless/test_agent_retained_browser_detach.py index 65e078ca3..50940dfbf 100644 --- a/test/unit_test/headless/test_agent_retained_browser_detach.py +++ b/test/unit_test/headless/test_agent_retained_browser_detach.py @@ -24,7 +24,8 @@ def request(self, operation, payload, **_options): if operation == "bootstrap": assert payload == {} return self.bootstrap - assert operation == "retire_browser" and payload == {} + assert operation == "retire_browser" + assert payload == {} if isinstance(self.response, Exception): raise self.response return self.response @@ -45,11 +46,13 @@ def close(self): def test_detach_transfers_actual_channel_after_proof_and_releases_only_input_resources(owned): channel, proof = owned.target.detach_readonly() - assert channel is owned.channel and proof == PROOF + assert channel is owned.channel + assert proof == PROOF assert owned.events == ["bootstrap", "journal-update", "retire_browser", "journal-release", "resource-close"] assert not channel.retired assert owned.target._channel is None - assert owned.target._resource is None and owned.target._journal is None + assert owned.target._resource is None + assert owned.target._journal is None assert owned.target._pending is None @@ -73,9 +76,11 @@ def test_unsettled_input_cannot_be_detached_or_falsely_released(owned, damage): def test_unsupported_sdk_keeps_original_normal_cleanup_owner(owned): owned.channel.response = {"supported": False} assert owned.target.detach_readonly() is None - assert owned.target._channel is owned.channel and not owned.channel.retired + assert owned.target._channel is owned.channel + assert not owned.channel.retired assert owned.target._pending is None - assert "journal-release" not in owned.events and "resource-close" not in owned.events + assert "journal-release" not in owned.events + assert "resource-close" not in owned.events @pytest.mark.parametrize("response", [ @@ -88,7 +93,8 @@ def test_failed_or_forged_retirement_preserves_source_ownership_and_prevents_fre with pytest.raises(AgentTaskError): owned.target.detach_readonly() assert owned.target._channel is owned.channel - assert owned.target._resource is not None and owned.target._journal is not None + assert owned.target._resource is not None + assert owned.target._journal is not None assert owned.target._pending == "retire_browser" before = list(owned.events) owned.channel.response = dict(PROOF) @@ -112,4 +118,5 @@ def test_legacy_helper_capability_does_not_break_normal_browser_cleanup(owned, v assert owned.target.detach_readonly() is None assert owned.events == ["bootstrap"] assert owned.target._pending is None - assert owned.target._channel is owned.channel and not owned.channel.retired + assert owned.target._channel is owned.channel + assert not owned.channel.retired diff --git a/test/unit_test/headless/test_agent_retained_browser_lifecycle.py b/test/unit_test/headless/test_agent_retained_browser_lifecycle.py index 434e2b37d..1f4282f87 100644 --- a/test/unit_test/headless/test_agent_retained_browser_lifecycle.py +++ b/test/unit_test/headless/test_agent_retained_browser_lifecycle.py @@ -41,11 +41,13 @@ def test_failed_retained_reaping_keeps_runtime_open_and_service_ownership_until_ try: with pytest.raises(AgentTaskError): runtime.close() - assert runtime._closed is False and not process.retired + assert runtime._closed is False + assert not process.retired finally: process.failure = False runtime.close() - assert runtime._closed is True and process.retired + assert runtime._closed is True + assert process.retired def test_nonbrowser_input_retirement_survives_unreadable_action_evidence(tmp_path, monkeypatch): diff --git a/test/unit_test/headless/test_agent_retained_browser_sdk.py b/test/unit_test/headless/test_agent_retained_browser_sdk.py index 78496198d..3da0c20d5 100644 --- a/test/unit_test/headless/test_agent_retained_browser_sdk.py +++ b/test/unit_test/headless/test_agent_retained_browser_sdk.py @@ -85,7 +85,8 @@ def test_input_lease_releases_while_runtime_still_owns_the_original_readonly_pro source = live.runtime.submit(live.definition).task_id assert run_task(live.runtime, source).state == "waiting_user" assert source not in live.runtime._leases - assert len(live.processes) == 1 and live.processes[0].poll() is None + assert len(live.processes) == 1 + assert live.processes[0].poll() is None live.runtime.close() assert live.processes[0].poll() is not None @@ -110,7 +111,8 @@ def test_older_sdk_closes_normally_but_cannot_create_a_completion_context(live): assert live.processes[0].poll() is not None with pytest.raises(AgentTaskError, match="context.*unavailable"): completion(live.runtime, source) - assert len(live.processes) == 1 and source not in live.runtime._leases + assert len(live.processes) == 1 + assert source not in live.runtime._leases def test_expired_context_is_reaped_without_replacement_or_historical_fallback(live, monkeypatch): @@ -119,7 +121,8 @@ def test_expired_context_is_reaped_without_replacement_or_historical_fallback(li monkeypatch.setattr(live.runtime._retained_browsers, "_clock", lambda: float("inf")) with pytest.raises(AgentTaskError, match="context.*unavailable"): completion(live.runtime, source) - assert live.processes[0].poll() is not None and len(live.processes) == 1 + assert live.processes[0].poll() is not None + assert len(live.processes) == 1 def test_disabled_target_maintenance_retires_the_original_owned_context(live): @@ -145,7 +148,8 @@ def test_forged_live_capability_description_cannot_revive_a_reaped_context(live, monkeypatch.setattr(entry.channel, "request", original) with pytest.raises(AgentTaskError, match="unavailable"): completion(runtime, source) - assert live.processes[0].poll() is not None and len(live.processes) == 1 + assert live.processes[0].poll() is not None + assert len(live.processes) == 1 def test_source_snapshot_change_during_live_read_cannot_publish_completion(live, monkeypatch): @@ -189,7 +193,8 @@ def cancelled(operation, payload, **options): with pytest.raises(CancelledError): runtime.finish(child) assert runtime.get(child).state == "cancelled" - assert live.processes[0].poll() is not None and len(live.processes) == 1 + assert live.processes[0].poll() is not None + assert len(live.processes) == 1 @pytest.fixture @@ -232,7 +237,8 @@ def test_skill_publication_uses_actual_trial_and_separate_same_context_completio accepted = runtime.skills.control("accept", { "candidate_id": value.candidate["id"], "task_id": value.trial, "completion_task_id": value.trial_reader, "expected_version": 0, "note": "Reviewed actual new trial and original-context independent evidence"}) - assert accepted["version"] == 1 and accepted["state"] == "accepted" + assert accepted["version"] == 1 + assert accepted["state"] == "accepted" assert accepted["publication"]["task_id"] == value.trial assert accepted["publication"]["completion_review"]["task_id"] == value.trial_reader assert runtime.store.actions(value.trial) == before @@ -264,7 +270,8 @@ def test_dead_source_helper_is_refused_by_actual_probe_without_new_process(live) live.processes[0].wait(timeout=3) with pytest.raises(AgentTaskError): completion(live.runtime, source) - assert live.processes[0].poll() is not None and len(live.processes) == 1 + assert live.processes[0].poll() is not None + assert len(live.processes) == 1 def test_explicit_private_scope_renewal_reads_original_context_without_reviving_old_origin(live, tmp_path): @@ -308,7 +315,8 @@ def test_exact_creation_retry_returns_existing_task_after_context_retirement_wit runtime._retained_browsers.discard(source) assert runtime.recovery.control("create_completion", request)["task_id"] == child assert runtime.get(child).state == "queued" - assert len(live.processes) == 1 and live.processes[0].poll() is not None + assert len(live.processes) == 1 + assert live.processes[0].poll() is not None def test_source_change_during_admission_probe_rolls_back_the_private_completion_task(live, monkeypatch): @@ -365,9 +373,11 @@ def test_public_surfaces_verify_the_actual_retained_browser_without_replaying_in assert run_tool_call("AC_agent_task_recovery", { "operation": "create_completion", "request": request})["task_id"] == child result = AgentRuntimeClient(connection).call("finish", {"task_id": child}) - assert result["state"] == "succeeded" and result["metadata"]["input_released"] is True + assert result["state"] == "succeeded" + assert result["metadata"]["input_released"] is True assert result["metadata"]["completion_review"]["effect_task"] == source - assert runtime.store.actions(source) == original and runtime.store.actions(child) == [] + assert runtime.store.actions(source) == original + assert runtime.store.actions(child) == [] assert len(live.processes) == 1 finally: server.stop() diff --git a/test/unit_test/headless/test_agent_role_boundaries.py b/test/unit_test/headless/test_agent_role_boundaries.py index e9ed321f8..e1f72ca99 100644 --- a/test/unit_test/headless/test_agent_role_boundaries.py +++ b/test/unit_test/headless/test_agent_role_boundaries.py @@ -68,7 +68,8 @@ def test_an_injected_tool_outside_the_reviewed_scope_is_refused_before_dispatch( handle = runtime.submit(spec()) model = ObedientModel({"tool": "AC_shell_command", "arguments": {"command": "whoami"}}) assert run_task(runtime, handle.task_id, backend=model).state == "waiting_user" - assert target.calls == [] and INJECTION in model.seen + assert target.calls == [] + assert INJECTION in model.seen def test_scope_fields_smuggled_into_a_proposal_never_reach_the_spec_or_the_target(managed): @@ -79,16 +80,19 @@ def test_scope_fields_smuggled_into_a_proposal_never_reach_the_spec_or_the_targe run_task(runtime, handle.task_id, backend=model) assert target.calls == [("AC_increment", {})] stored = runtime.store.get(handle.task_id)["spec"] - assert stored["allowed_tools"] == ["AC_increment"] and stored["roots"] == [] + assert stored["allowed_tools"] == ["AC_increment"] + assert stored["roots"] == [] def test_a_planner_claiming_completion_is_not_evidence(managed): runtime, target = managed handle = runtime.submit(spec()) result = run_task(runtime, handle.task_id, backend=ObedientModel({"stop": True, "message": "task complete"})) - assert result.state == "waiting_user" and target.calls == [] + assert result.state == "waiting_user" + assert target.calls == [] reports = runtime.get(handle.task_id).verification - assert reports and all(item["status"] != "passed" for item in reports) + assert reports + assert all(item["status"] != "passed" for item in reports) def test_a_path_outside_the_reviewed_roots_is_refused_even_when_the_page_names_it(tmp_path): @@ -119,5 +123,6 @@ def forbidden(*_args, **_kwargs): "allowed_origins": ["https://allowed.test"], "url": "https://allowed.test/form", "fields": [{"column": "name", "selector": "#field"}], "new_record_selector": "#new", "submit_selector": "#save", "confirmation_selector": "#confirmation", "confirmation_value": "saved"}) - assert isinstance(draft, dict) and draft + assert isinstance(draft, dict) + assert draft assert not list(tmp_path.glob("*.sqlite*")) diff --git a/test/unit_test/headless/test_agent_screen_evidence.py b/test/unit_test/headless/test_agent_screen_evidence.py index 631715835..ab2f606f0 100644 --- a/test/unit_test/headless/test_agent_screen_evidence.py +++ b/test/unit_test/headless/test_agent_screen_evidence.py @@ -89,7 +89,8 @@ def test_bounded_desktop_labels_keep_safe_matches_and_exclude_mask_placeholders( monkeypatch.setattr(target, "_check_foreground", lambda: (1, "Owned", 2)) monkeypatch.setattr(accessibility_api, "list_accessibility_elements", lambda **_kwargs: controls) observation = target.observe() - assert observation["semantic_observation"] is True and observation["text_redacted"] is True + assert observation["semantic_observation"] is True + assert observation["text_redacted"] is True assert len(observation["elements"]) == 2 assert "SECRET" not in str(observation) assert status(observation, {"text_present": "Saved"}) == "passed" @@ -105,7 +106,8 @@ def test_bounded_browser_previews_never_prove_global_absence(frames): "elements": [{"selector": "#save", "text": "Saved", "is_visible": True, "is_enabled": True}, {"selector": "#hidden", "text": "Hidden", "is_visible": False}]}) observation = target.observe() - assert observation["semantic_observation"] is True and observation["text_redacted"] is True + assert observation["semantic_observation"] is True + assert observation["text_redacted"] is True assert status(observation, {"text_present": "Saved"}) == "passed" assert status(observation, {"text_absent": "Saved"}) == "failed" for text in ("Missing", "Other body text", "Hidden"): diff --git a/test/unit_test/headless/test_agent_skill_authorization_surfaces.py b/test/unit_test/headless/test_agent_skill_authorization_surfaces.py index ac166d25f..a5b4ca29b 100644 --- a/test/unit_test/headless/test_agent_skill_authorization_surfaces.py +++ b/test/unit_test/headless/test_agent_skill_authorization_surfaces.py @@ -20,7 +20,8 @@ def test_cli_exposes_explicit_skill_authorization_operations(): parser = build_parser() for operation in ("review_authorization", "create_authorized"): parsed = parser.parse_args(["agent-task", "skill", operation, "review.json"]) - assert parsed.skill_operation == operation and parsed.request == "review.json" + assert parsed.skill_operation == operation + assert parsed.request == "review.json" def test_authenticated_http_can_review_and_create_without_executing_or_publishing(published, monkeypatch): @@ -42,7 +43,8 @@ def test_authenticated_http_can_review_and_create_without_executing_or_publishin request = {"candidate_id": parent["id"], "snapshot": view["snapshot"], "spec": view["spec"], "authorization_review": view["authorization_review"], "note": "Reviewed report-root candidate"} child = client.call("skill", {"operation": "create_authorized", "request": request}) - assert child["state"] == "draft" and child["version"] == 0 + assert child["state"] == "draft" + assert child["version"] == 0 assert child["provenance"]["reauthorization"]["actor"] == "alice" start.assert_not_called() with origin_scope(current_id), authorization_scope(AuthorizationContext("bob", "operator")): diff --git a/test/unit_test/headless/test_agent_skill_completion.py b/test/unit_test/headless/test_agent_skill_completion.py index 6e7662259..a62401e0f 100644 --- a/test/unit_test/headless/test_agent_skill_completion.py +++ b/test/unit_test/headless/test_agent_skill_completion.py @@ -84,12 +84,15 @@ def test_publish_keeps_actual_validation_trial_and_separate_completion_provenanc receipts = runtime.store.actions(trial.task_id) manifest = trial.manifest.read_bytes() accepted = runtime.skills.control('accept', acceptance(trial)) - assert accepted['state'] == 'accepted' and accepted['version'] == 1 + assert accepted['state'] == 'accepted' + assert accepted['version'] == 1 assert accepted['publication']['task_id'] == trial.task_id review = accepted['publication']['completion_review'] - assert review['task_id'] == trial.child_id and review['effect_task'] == trial.task_id + assert review['task_id'] == trial.child_id + assert review['effect_task'] == trial.task_id assert runtime.get(trial.task_id).state == 'paused' - assert runtime.store.actions(trial.task_id) == receipts and runtime.store.actions(trial.child_id) == [] + assert runtime.store.actions(trial.task_id) == receipts + assert runtime.store.actions(trial.child_id) == [] assert trial.manifest.read_bytes() == manifest assert runtime.get(trial.child_id).metadata['completion_contract'] == 1 with runtime.store.connection() as connection: @@ -121,14 +124,16 @@ def changed(*, write=False): state = connection.execute('SELECT state FROM agent_skill_candidates WHERE id=?', (trial.candidate['id'],)).fetchone()[0] publications = connection.execute('SELECT COUNT(*) FROM agent_skill_publications').fetchone()[0] - assert state == 'draft' and publications == 0 + assert state == 'draft' + assert publications == 0 @pytest.mark.parametrize('trial', ['retry'], indirect=True) def test_retried_reader_chain_retains_the_original_execution_trial(trial): value = trial.runtime.skills.control('accept', acceptance(trial)) review = value['publication']['completion_review'] - assert review['effect_task'] == trial.task_id and review['source_task'] != trial.task_id + assert review['effect_task'] == trial.task_id + assert review['source_task'] != trial.task_id assert trial.runtime.get(review['source_task']).state == 'cancelled' assert value['publication']['task_id'] == trial.task_id diff --git a/test/unit_test/headless/test_agent_skill_completion_surfaces.py b/test/unit_test/headless/test_agent_skill_completion_surfaces.py index 2c9efe198..1554a5583 100644 --- a/test/unit_test/headless/test_agent_skill_completion_surfaces.py +++ b/test/unit_test/headless/test_agent_skill_completion_surfaces.py @@ -41,7 +41,8 @@ def test_shared_surfaces_publish_the_original_trial_with_explicit_completion(tri value = tools['ac_agent_skill'].invoke({'operation': 'accept', 'request': request}) else: value = AgentRuntimeClient(connection).call('skill', {'operation': 'accept', 'request': request}) - assert value['publication']['task_id'] == trial.task_id and value['version'] == 1 + assert value['publication']['task_id'] == trial.task_id + assert value['version'] == 1 assert value['publication']['completion_review']['task_id'] == trial.child_id assert trial.runtime.get(trial.task_id).state == 'paused' assert 'accept' in tools['ac_agent_skill'].input_schema['properties']['operation']['enum'] diff --git a/test/unit_test/headless/test_agent_skill_execution.py b/test/unit_test/headless/test_agent_skill_execution.py index a253fc0f1..a5718607f 100644 --- a/test/unit_test/headless/test_agent_skill_execution.py +++ b/test/unit_test/headless/test_agent_skill_execution.py @@ -76,7 +76,8 @@ def execution(tmp_path, request): with authorization_scope(reviewer): if kind.startswith('capture'): preview = runtime.recovery.control('preview', {'task_id': trial['task_id']}) - assert preview['draft'] is None and 'fresh_capture_required' in preview['issues'] + assert preview['draft'] is None + assert 'fresh_capture_required' in preview['issues'] reviewed = runtime.store.get(trial['task_id'])['spec'] reviewed['options'].pop('skill_pin') reviewed['actions'] = [edit('Last', 'different' if kind == 'capture_mismatch' else 'first')] @@ -116,17 +117,23 @@ def forbidden(*_args, **_kwargs): monkeypatch.setattr(execution.target, 'perform', forbidden) request = review_request(execution) review = runtime.skills.control('review_execution', request) - assert review['approval_required'] is True and review['publication_inherited'] is False + assert review['approval_required'] is True + assert review['publication_inherited'] is False assert runtime.skills.control('get', {'candidate_id': execution.candidate['id']})['state'] == 'draft' accepted = runtime.skills.control('accept', {**request, 'execution_review': review['execution_review'], 'expected_version': 0, 'note': 'Reviewed the exact full semantic effect chain'}) - assert accepted['version'] == 1 and accepted['publication']['task_id'] == execution.task_id + assert accepted['version'] == 1 + assert accepted['publication']['task_id'] == execution.task_id proof = accepted['publication']['execution_review'] - assert proof['task_id'] == execution.child_id and proof['source_task'] == execution.task_id - assert proof['verification_task'] == execution.child_id and len(proof['segments']) == 1 - assert 'store_path' not in json.dumps(proof) and 'arguments' not in json.dumps(proof) + assert proof['task_id'] == execution.child_id + assert proof['source_task'] == execution.task_id + assert proof['verification_task'] == execution.child_id + assert len(proof['segments']) == 1 + assert 'store_path' not in json.dumps(proof) + assert 'arguments' not in json.dumps(proof) assert runtime.get(execution.task_id).state == 'paused' - assert runtime.store.actions(execution.task_id) == receipts and execution.target.calls == calls + assert runtime.store.actions(execution.task_id) == receipts + assert execution.target.calls == calls with runtime.store.connection() as connection: trials = connection.execute('SELECT task_id FROM agent_skill_trials').fetchall() assert [row[0] for row in trials] == [execution.task_id] @@ -142,7 +149,8 @@ def accept_request(value, **changes): def test_multiple_real_recovery_segments_match_the_complete_original_plan(execution): accepted = execution.runtime.skills.control('accept', accept_request(execution)) proof = accepted['publication']['execution_review'] - assert len(proof['segments']) == 2 and proof['source_task'] == execution.task_id + assert len(proof['segments']) == 2 + assert proof['source_task'] == execution.task_id assert accepted['publication']['task_id'] == execution.task_id diff --git a/test/unit_test/headless/test_agent_skill_execution_gui.py b/test/unit_test/headless/test_agent_skill_execution_gui.py index 063fead90..3331c76f5 100644 --- a/test/unit_test/headless/test_agent_skill_execution_gui.py +++ b/test/unit_test/headless/test_agent_skill_execution_gui.py @@ -24,7 +24,8 @@ def test_gui_prepares_original_trial_and_separate_execution_without_dispatch(mon 'execution_task_id': 'actual-final-executable-successor'} if operation == 'accept': expected.update(execution_review='', expected_version=0, note='') - assert request == expected and tab._skill_operation.currentData() == operation + assert request == expected + assert tab._skill_operation.currentData() == operation assert tab._pages.currentIndex() == tab._page_keys.index('agent_page_skills') finally: tab.close() diff --git a/test/unit_test/headless/test_agent_skill_execution_security.py b/test/unit_test/headless/test_agent_skill_execution_security.py index cb7581fb4..719a4612c 100644 --- a/test/unit_test/headless/test_agent_skill_execution_security.py +++ b/test/unit_test/headless/test_agent_skill_execution_security.py @@ -26,7 +26,8 @@ def assert_unpublished(value): def test_zero_effect_original_trial_can_adopt_its_complete_actual_successor(execution): assert execution.runtime.store.actions(execution.task_id) == [] accepted = execution.runtime.skills.control('accept', accept_request(execution)) - assert accepted['publication']['task_id'] == execution.task_id and accepted['version'] == 1 + assert accepted['publication']['task_id'] == execution.task_id + assert accepted['version'] == 1 @pytest.mark.parametrize('execution', ['named'], indirect=True) diff --git a/test/unit_test/headless/test_agent_skill_execution_surfaces.py b/test/unit_test/headless/test_agent_skill_execution_surfaces.py index fb473b16a..81f217009 100644 --- a/test/unit_test/headless/test_agent_skill_execution_surfaces.py +++ b/test/unit_test/headless/test_agent_skill_execution_surfaces.py @@ -46,11 +46,13 @@ def test_shared_surfaces_review_then_accept_complete_recovered_trial(execution, monkeypatch.setattr('je_auto_control.utils.agent_runtime.client.default_connection_path', lambda: connection) request = review_request(execution) review = invoke(surface, connection, tmp_path, 'review_execution', request) - assert review['approval_required'] is True and review['publication_inherited'] is False + assert review['approval_required'] is True + assert review['publication_inherited'] is False accepted = invoke(surface, connection, tmp_path, 'accept', {**request, 'execution_review': review['execution_review'], 'expected_version': 0, 'note': 'Reviewed exact full original execution chain'}) - assert accepted['publication']['task_id'] == execution.task_id and accepted['version'] == 1 + assert accepted['publication']['task_id'] == execution.task_id + assert accepted['version'] == 1 assert accepted['publication']['execution_review']['task_id'] == execution.child_id assert execution.runtime.get(execution.task_id).state == 'paused' finally: diff --git a/test/unit_test/headless/test_agent_skill_reauthorization.py b/test/unit_test/headless/test_agent_skill_reauthorization.py index d722f4f87..5da18965e 100644 --- a/test/unit_test/headless/test_agent_skill_reauthorization.py +++ b/test/unit_test/headless/test_agent_skill_reauthorization.py @@ -61,7 +61,8 @@ def test_renewal_requires_fresh_trial_and_publication_without_mutating_old_versi request = approval(runtime, parent) assert request["spec"]["roots"] == [str(narrow)] candidate = runtime.skills.control("create_authorized", request) - assert candidate["state"] == "draft" and candidate["version"] == 0 + assert candidate["state"] == "draft" + assert candidate["version"] == 0 assert candidate["parameters"] == parent["parameters"] assert candidate["spec"]["actions"] == parent["spec"]["actions"] assert candidate["provenance"]["reauthorization"]["context"]["replaced_origins"] == [old_id] @@ -262,6 +263,8 @@ def test_narrowed_scope_never_drops_an_inaccessible_completion_criterion(publish runtime, parent, _old_id, current_id, _allowed, _narrow = published with origin_scope(current_id): view = runtime.skills.control("review_authorization", {"candidate_id": parent["id"]}) - assert view["spec"] is None and view["issues"] == ["authorization_scope_unavailable"] - assert view["approval_required"] and view["validation_required"] + assert view["spec"] is None + assert view["issues"] == ["authorization_scope_unavailable"] + assert view["approval_required"] + assert view["validation_required"] assert runtime.skills.control("get", {"candidate_id": parent["id"]}) == parent diff --git a/test/unit_test/headless/test_agent_skill_recording_completion.py b/test/unit_test/headless/test_agent_skill_recording_completion.py index cbc7e8eeb..289786dec 100644 --- a/test/unit_test/headless/test_agent_skill_recording_completion.py +++ b/test/unit_test/headless/test_agent_skill_recording_completion.py @@ -85,14 +85,19 @@ def test_record_original_semantic_actions_without_replay_or_trial_fabrication(re receipts = runtime.store.actions(recording.task_id) manifest = recording.manifest.read_bytes() candidate = runtime.skills.control('record', request_for(recording)) - assert candidate['state'] == 'draft' and candidate['version'] == 0 and candidate['publication'] is None - assert candidate['spec']['mode'] == 'skill' and candidate['spec']['actions'] == [recording.action] + assert candidate['state'] == 'draft' + assert candidate['version'] == 0 + assert candidate['publication'] is None + assert candidate['spec']['mode'] == 'skill' + assert candidate['spec']['actions'] == [recording.action] assert candidate['provenance']['source_task'] == recording.task_id proof = candidate['provenance']['completion_review'] - assert proof['task_id'] == recording.child_id and proof['effect_task'] == recording.task_id + assert proof['task_id'] == recording.child_id + assert proof['effect_task'] == recording.task_id assert 'skill_pin' not in candidate['spec']['options'] assert runtime.get(recording.task_id).state == 'paused' - assert runtime.store.actions(recording.task_id) == receipts and runtime.store.actions(recording.child_id) == [] + assert runtime.store.actions(recording.task_id) == receipts + assert runtime.store.actions(recording.child_id) == [] assert recording.manifest.read_bytes() == manifest with runtime.store.connection() as connection: assert connection.execute('SELECT COUNT(*) FROM agent_skill_trials').fetchone()[0] == 0 @@ -128,7 +133,8 @@ def test_draft_publishes_only_after_its_own_new_validation(recording, monkeypatc assert run_task(runtime, trial['task_id']).state == 'succeeded' accepted = runtime.skills.control('accept', {'candidate_id': candidate['id'], 'task_id': trial['task_id'], 'expected_version': 0, 'note': 'Reviewed the new exact trial'}) - assert accepted['version'] == 1 and accepted['publication']['task_id'] == trial['task_id'] + assert accepted['version'] == 1 + assert accepted['publication']['task_id'] == trial['task_id'] assert runtime.get(recording.task_id).state == 'paused' with runtime.store.connection() as connection: identifiers = connection.execute('SELECT task_id FROM agent_skill_trials').fetchall() @@ -140,7 +146,8 @@ def test_added_criteria_do_not_inherit_the_readers_verified_result(recording, mo runtime = recording.runtime candidate = runtime.skills.control('record', request_for(recording, validation_criteria=[ {'kind': 'file_text', 'path': str(recording.output), 'value': 'not independently verified'}])) - assert runtime.get(recording.child_id).state == 'succeeded' and candidate['publication'] is None + assert runtime.get(recording.child_id).state == 'succeeded' + assert candidate['publication'] is None trial = runtime.skills.control('validate', {'candidate_id': candidate['id']}) monkeypatch.undo() assert run_task(runtime, trial['task_id']).state != 'succeeded' @@ -162,7 +169,8 @@ def test_reader_retention_and_restart_preserve_only_historical_draft_provenance( reopened = AgentRuntime(runtime.store.path, targets={'local-files': NativeDesktopTarget()}) try: current = reopened.skills.control('get', {'candidate_id': candidate['id']}) - assert current['state'] == 'draft' and current['provenance']['completion_review'] == proof + assert current['state'] == 'draft' + assert current['provenance']['completion_review'] == proof fresh = reopened.skills.control('validate', {'candidate_id': candidate['id']}) assert reopened.store.actions(fresh['task_id']) == [] with pytest.raises(AgentTaskError): diff --git a/test/unit_test/headless/test_agent_skill_recording_surfaces.py b/test/unit_test/headless/test_agent_skill_recording_surfaces.py index 9a06240a2..6d0bf4808 100644 --- a/test/unit_test/headless/test_agent_skill_recording_surfaces.py +++ b/test/unit_test/headless/test_agent_skill_recording_surfaces.py @@ -43,7 +43,8 @@ def test_shared_surfaces_record_original_actions_as_an_unpublished_draft(recordi value = tools['ac_agent_skill'].invoke({'operation': 'record', 'request': request}) else: value = AgentRuntimeClient(connection).call('skill', {'operation': 'record', 'request': request}) - assert value['state'] == 'draft' and value['publication'] is None + assert value['state'] == 'draft' + assert value['publication'] is None assert value['provenance']['source_task'] == recording.task_id assert value['provenance']['completion_review']['task_id'] == recording.child_id assert value['spec']['actions'] == [recording.action] diff --git a/test/unit_test/headless/test_agent_skill_versions.py b/test/unit_test/headless/test_agent_skill_versions.py index c10247ac1..e5d4308a0 100644 --- a/test/unit_test/headless/test_agent_skill_versions.py +++ b/test/unit_test/headless/test_agent_skill_versions.py @@ -68,9 +68,11 @@ def test_record_preview_validate_accept_and_run_pinned_version(managed): preview = runtime.skills.control("preview", {"candidate_id": candidate["id"], "parameters": {"value": "Ada"}}) assert preview["spec"]["actions"][0]["arguments"]["value"] == "Ada" assert candidate["spec"]["actions"][0]["arguments"]["value"] == "done" - assert candidate["state"] == "draft" and candidate["version"] == 0 + assert candidate["state"] == "draft" + assert candidate["version"] == 0 accepted = publish(runtime, candidate) - assert accepted["version"] == 1 and accepted["digest"] == candidate["digest"] + assert accepted["version"] == 1 + assert accepted["digest"] == candidate["digest"] assert accepted["publication"]["note"] == "Reviewed exact candidate trial" task = runtime.skills.control("run", {"skill_id": accepted["skill_id"], "version": 1, "parameters": {"value": "Grace"}}) @@ -281,6 +283,7 @@ def test_public_skill_api_and_http_service_share_verified_publication(tmp_path, threading.Event().wait(0.1) # At most 50 polls within the live service's request budget. accepted = api.manage_agent_skill("accept", {"candidate_id": candidate["id"], "task_id": trial["task_id"], "expected_version": 0, "note": "Reviewed HTTP fake-target evidence"}) - assert accepted["version"] == 1 and accepted["publication"]["task_id"] == trial["task_id"] + assert accepted["version"] == 1 + assert accepted["publication"]["task_id"] == trial["task_id"] finally: service.close() diff --git a/test/unit_test/headless/test_agent_stop_completion_race.py b/test/unit_test/headless/test_agent_stop_completion_race.py index 93b756bfc..e109c3a9b 100644 --- a/test/unit_test/headless/test_agent_stop_completion_race.py +++ b/test/unit_test/headless/test_agent_stop_completion_race.py @@ -38,5 +38,7 @@ def stop_after_read(): finally: published.set() result = pending.result(timeout=5) - assert result.state == "succeeded" and result.verification == completed.verification - assert result.metadata["input_released"] is True and target.calls == ["AC_increment"] + assert result.state == "succeeded" + assert result.verification == completed.verification + assert result.metadata["input_released"] is True + assert target.calls == ["AC_increment"] diff --git a/test/unit_test/headless/test_agent_task_handoff.py b/test/unit_test/headless/test_agent_task_handoff.py index d0c95f26c..22e276b2d 100644 --- a/test/unit_test/headless/test_agent_task_handoff.py +++ b/test/unit_test/headless/test_agent_task_handoff.py @@ -16,7 +16,8 @@ def issue(value, source, leaf): with authorization_scope(value.reviewer): review = value.runtime.recovery.control('review_handoff', request) assert review['evidence']['source_task'] == source - assert 'batch_id' not in review['evidence'] and 'node_id' not in review['evidence'] + assert 'batch_id' not in review['evidence'] + assert 'node_id' not in review['evidence'] created = {**request, 'review': review['handoff_review'], 'note': 'Explicitly adopt only this actual non-DAG completion evidence'} return value.runtime.recovery.control('create_handoff', created)['handoff'] @@ -43,13 +44,16 @@ def test_source_owner_records_other_caller_completion_only_with_an_explicit_task grant = issue(recording, recording.task_id, recording.child_id) candidate = runtime.skills.control('record', request_for(recording, handoff_id=grant['id'])) assert candidate['owner']['user_id'] == 'owner' - assert candidate['state'] == 'draft' and candidate['publication'] is None + assert candidate['state'] == 'draft' + assert candidate['publication'] is None proof = candidate['provenance']['completion_review'] - assert proof['task_id'] == recording.child_id and proof['effect_task'] == recording.task_id + assert proof['task_id'] == recording.child_id + assert proof['effect_task'] == recording.task_id assert proof['evidence_handoff']['id'] == grant['id'] assert runtime.get(recording.task_id).state == 'paused' assert runtime.store.get(recording.child_id)['owner']['user_id'] == 'reviewer' - assert runtime.store.actions(recording.task_id) == before and recording.manifest.read_bytes() == manifest + assert runtime.store.actions(recording.task_id) == before + assert recording.manifest.read_bytes() == manifest with pytest.raises(AgentTaskError, match='another caller'): runtime.get(recording.child_id) assert_no_dag(runtime) @@ -69,12 +73,16 @@ def test_original_validation_trial_publishes_with_other_caller_task_evidence_wit monkeypatch.setattr(NativeDesktopTarget, '_launch', no_helper) grant = issue(trial, trial.task_id, trial.child_id) result = runtime.skills.control('accept', {**acceptance(trial), 'handoff_id': grant['id']}) - assert result['state'] == 'accepted' and result['version'] == 1 - assert result['owner']['user_id'] == 'owner' and result['publication']['task_id'] == trial.task_id + assert result['state'] == 'accepted' + assert result['version'] == 1 + assert result['owner']['user_id'] == 'owner' + assert result['publication']['task_id'] == trial.task_id proof = result['publication']['completion_review'] - assert proof['task_id'] == trial.child_id and proof['effect_task'] == trial.task_id + assert proof['task_id'] == trial.child_id + assert proof['effect_task'] == trial.task_id assert proof['evidence_handoff']['id'] == grant['id'] - assert runtime.get(trial.task_id).state == 'paused' and runtime.store.actions(trial.task_id) == before + assert runtime.get(trial.task_id).state == 'paused' + assert runtime.store.actions(trial.task_id) == before assert runtime.store.get(trial.child_id)['owner']['user_id'] == 'reviewer' assert trial.manifest.read_bytes() == manifest with pytest.raises(AgentTaskError, match='another caller'): diff --git a/test/unit_test/headless/test_agent_task_handoff_gui.py b/test/unit_test/headless/test_agent_task_handoff_gui.py index 806bf6791..8498e8f0d 100644 --- a/test/unit_test/headless/test_agent_task_handoff_gui.py +++ b/test/unit_test/headless/test_agent_task_handoff_gui.py @@ -36,7 +36,8 @@ def test_explicit_task_source_mode_prepares_a_real_source_request_without_fabric assert calls == [] monkeypatch.setattr('je_auto_control.gui.agent_tasks_tab._translate', lambda key: 'translated:' + key) widget.retranslate() - assert mode.currentData() == 'task' and mode.currentText().startswith('translated:') + assert mode.currentData() == 'task' + assert mode.currentText().startswith('translated:') request['source_task'] = 'actual-original-task' widget._handoff_request.setPlainText(json.dumps(request)) actions['agent_handoff_apply']() @@ -56,5 +57,6 @@ def test_skill_actions_prepare_selected_grant_adoption_without_issuing_or_publis actions[name]() request = json.loads(widget._skill_request.toPlainText()) assert widget._skill_operation.currentData() == operation - assert request['handoff_id'] == '' and request[selected] == 'reviewed-evidence-task' + assert request['handoff_id'] == '' + assert request[selected] == 'reviewed-evidence-task' assert calls == [] diff --git a/test/unit_test/headless/test_agent_task_handoff_lifecycle.py b/test/unit_test/headless/test_agent_task_handoff_lifecycle.py index f5fab5bf4..b01e1b32c 100644 --- a/test/unit_test/headless/test_agent_task_handoff_lifecycle.py +++ b/test/unit_test/headless/test_agent_task_handoff_lifecycle.py @@ -61,7 +61,8 @@ def test_actual_grant_retry_and_other_caller_completion_survive_runtime_restart( candidate = reopened.skills.control('record', request_for(recording, handoff_id=grant['id'])) assert candidate['state'] == 'draft' assert candidate['provenance']['completion_review']['evidence_handoff']['id'] == grant['id'] - assert reopened.get(recording.task_id).state == 'paused' and recording.manifest.read_bytes() == before + assert reopened.get(recording.task_id).state == 'paused' + assert recording.manifest.read_bytes() == before with pytest.raises(AgentTaskError, match='another caller'): reopened.get(recording.child_id) finally: @@ -84,10 +85,12 @@ def test_sixteen_real_renewed_readers_grant_completion_without_an_extra_link_or_ monkeypatch.setattr(NativeDesktopTarget, '_launch', no_helper) grant = issue(completed, completed.source, parent) access = runtime.recovery.task_handoff_evidence(completed.source, parent, grant['id']) - assert len(access.links) == 16 and len(access.rows) == 17 + assert len(access.links) == 16 + assert len(access.rows) == 17 candidate = runtime.skills.control('record', {'task_id': completed.source, 'completion_task_id': parent, 'handoff_id': grant['id'], 'name': 'Sixteen actual reviewed readers'}) - assert candidate['state'] == 'draft' and candidate['publication'] is None + assert candidate['state'] == 'draft' + assert candidate['publication'] is None assert candidate['provenance']['completion_review']['task_id'] == parent assert runtime.get(completed.source).state == 'paused' assert origin_policy._path(completed.old.identifier).read_bytes() == witness diff --git a/test/unit_test/headless/test_agent_task_handoff_mixed.py b/test/unit_test/headless/test_agent_task_handoff_mixed.py index dc4d6fb88..1e889e828 100644 --- a/test/unit_test/headless/test_agent_task_handoff_mixed.py +++ b/test/unit_test/headless/test_agent_task_handoff_mixed.py @@ -124,8 +124,10 @@ def test_actual_renewed_mixed_file_chain_keeps_original_trial_and_old_witness_wi 'execution_task_id': value.child_id, 'completion_task_id': value.reader, 'handoff_id': grant['id']} accepted = publish(value, request) proof = accepted['publication']['execution_review'] - assert accepted['publication']['task_id'] == value.task_id and accepted['version'] == 1 - assert proof['task_id'] == value.child_id and proof['verification_task'] == value.reader + assert accepted['publication']['task_id'] == value.task_id + assert accepted['version'] == 1 + assert proof['task_id'] == value.child_id + assert proof['verification_task'] == value.reader assert proof['completion_review']['effect_task'] == value.child_id assert proof['evidence_handoff']['id'] == grant['id'] assert runtime.get(value.task_id).state == 'paused' @@ -133,7 +135,8 @@ def test_actual_renewed_mixed_file_chain_keeps_original_trial_and_old_witness_wi assert runtime.store.actions(value.reader) == [] assert [path.read_bytes() for path in value.manifests] == before assert origin_policy._path(value.old.identifier).read_bytes() == witness - assert 'arguments' not in json.dumps(proof) and 'store_path' not in json.dumps(proof) + assert 'arguments' not in json.dumps(proof) + assert 'store_path' not in json.dumps(proof) with pytest.raises(AgentTaskError, match='another caller'): runtime.get(value.child_id) with pytest.raises(AgentTaskError, match='managed origin'): diff --git a/test/unit_test/headless/test_agent_task_handoff_revocation.py b/test/unit_test/headless/test_agent_task_handoff_revocation.py index cb90bee8f..cf5bafecd 100644 --- a/test/unit_test/headless/test_agent_task_handoff_revocation.py +++ b/test/unit_test/headless/test_agent_task_handoff_revocation.py @@ -63,7 +63,8 @@ def test_revocation_inside_publication_sql_rolls_back_acceptance_and_its_provena with pytest.raises(AgentTaskError, match='revoked'): runtime.skills.control('accept', {**acceptance(trial), 'handoff_id': grant['id']}) candidate = runtime.skills.control('get', {'candidate_id': trial.candidate['id']}) - assert candidate['state'] == 'draft' and candidate['publication'] is None + assert candidate['state'] == 'draft' + assert candidate['publication'] is None with runtime.store.connection() as connection: for table in ('agent_skill_publications', 'agent_skill_completions', 'agent_task_handoff_revocations'): assert connection.execute(f'SELECT COUNT(*) FROM {table}').fetchone()[0] == 0 diff --git a/test/unit_test/headless/test_agent_task_handoff_surfaces.py b/test/unit_test/headless/test_agent_task_handoff_surfaces.py index 1ff823a3c..beb8dec3b 100644 --- a/test/unit_test/headless/test_agent_task_handoff_surfaces.py +++ b/test/unit_test/headless/test_agent_task_handoff_surfaces.py @@ -69,7 +69,8 @@ def exercise(value, surface, operation, adoption, monkeypatch, temporary): result = invoke(surface, 'skill', operation, {**adoption, 'handoff_id': grant['id']}, connection, temporary) reviewed = (result['provenance']['completion_review'] if operation == 'record' else result['publication']['completion_review']) - assert reviewed['evidence_handoff']['id'] == grant['id'] and result['owner']['user_id'] == 'owner' + assert reviewed['evidence_handoff']['id'] == grant['id'] + assert result['owner']['user_id'] == 'owner' assert runtime.get(value.task_id).state == 'paused' with pytest.raises(AgentTaskError): AgentRuntimeClient(connection).call('get', {'task_id': value.child_id}) diff --git a/test/unit_test/headless/test_agent_task_recovery.py b/test/unit_test/headless/test_agent_task_recovery.py index 23fe58845..5c09a248c 100644 --- a/test/unit_test/headless/test_agent_task_recovery.py +++ b/test/unit_test/headless/test_agent_task_recovery.py @@ -46,10 +46,12 @@ def test_preview_is_passive_reports_progress_and_does_not_reuse_receipts(stopped monkeypatch.setattr(target, "ready", Mock(side_effect=AssertionError("target probe"))) first = preview(runtime, source) assert first == preview(runtime, source) - assert first["completed_steps"] == 1 and first["issues"] == [] + assert first["completed_steps"] == 1 + assert first["issues"] == [] assert first["draft"]["actions"] == [{"tool": "AC_increment", "arguments": {"amount": 2}, "expect_result": {"value": 3}}] - assert first["approval_required"] is True and first["source_completion_inherited"] is False + assert first["approval_required"] is True + assert first["source_completion_inherited"] is False assert first["source_receipts"][0]["status"] == "confirmed" assert (runtime.store.get(source), runtime.store.actions(source)) == before assert target.calls == ["AC_increment"] @@ -64,7 +66,8 @@ def test_new_successor_executes_only_reviewed_remaining_steps_and_keeps_parent_s assert child["recovery"]["source_task"] == source assert run_task(runtime, child["task_id"]).state == "succeeded" assert len(target.calls) == 2 - assert runtime.get(source).state == "paused" and runtime.receipts(source) == before + assert runtime.get(source).state == "paused" + assert runtime.receipts(source) == before with pytest.raises(AgentTaskError, match="reviewed successor"): runtime.resume(source) assert runtime.get(child["task_id"]).metadata["recovery"]["snapshot"] == request["snapshot"] @@ -117,7 +120,8 @@ def test_unknown_effects_must_be_reconciled_and_are_never_discarded(stopped): with runtime.store.connection(write=True) as connection: connection.execute("UPDATE agent_actions SET status='uncertain' WHERE id=?", (action["id"],)) view = preview(runtime, source) - assert view["draft"] is None and "unknown_source_effects" in view["issues"] + assert view["draft"] is None + assert "unknown_source_effects" in view["issues"] request = {"task_id": source, "snapshot": view["snapshot"], "spec": deepcopy(runtime.store.get(source)["spec"]), "note": "Must not erase unknown input"} with pytest.raises(AgentTaskError, match="reconcile unknown"): @@ -142,7 +146,8 @@ def test_old_capture_values_and_observation_indexes_are_not_transplanted(stopped import json connection.execute("UPDATE agent_tasks SET spec=? WHERE id=?", (json.dumps(data), source)) view = preview(runtime, source) - assert issue in view["issues"] and view["draft"] is None + assert issue in view["issues"] + assert view["draft"] is None request = {"task_id": source, "snapshot": view["snapshot"], "spec": data, "note": "review"} with pytest.raises(AgentTaskError, match="fresh semantic actions"): runtime.recovery.control("create", request) @@ -270,5 +275,6 @@ def test_caller_request_keys_cannot_preclaim_or_supply_a_recovery_successor(stop verification=[{"kind": "actions_complete", "status": "passed"}]) child = runtime.recovery.control("create", request) assert child["task_id"] != preclaimed.task_id - assert child["state"] == "queued" and runtime.store.actions(child["task_id"]) == [] + assert child["state"] == "queued" + assert runtime.store.actions(child["task_id"]) == [] assert child["recovery"]["source_task"] == source diff --git a/test/unit_test/headless/test_agent_task_triggers.py b/test/unit_test/headless/test_agent_task_triggers.py index f2c1dbd3a..1fe754abe 100644 --- a/test/unit_test/headless/test_agent_task_triggers.py +++ b/test/unit_test/headless/test_agent_task_triggers.py @@ -192,7 +192,8 @@ def counted(**kwargs): monkeypatch.setattr(runtime.store, "connection", counted) result = runtime.stop_all() assert len(reads) <= 6 - assert result["requested"] == 5 and all(item["state"] == "cancelled" for item in result["tasks"]) + assert result["requested"] == 5 + assert all(item["state"] == "cancelled" for item in result["tasks"]) def test_canonical_root_replacement_requires_scope_review_before_target_acquisition(runtime, tmp_path): diff --git a/test/unit_test/headless/test_agent_tasks_gui.py b/test/unit_test/headless/test_agent_tasks_gui.py index 4c4fdea54..b932c36a6 100644 --- a/test/unit_test/headless/test_agent_tasks_gui.py +++ b/test/unit_test/headless/test_agent_tasks_gui.py @@ -138,12 +138,14 @@ def test_remainder_preview_is_passive_bound_to_selected_task_and_requires_explic tab._task_id.setText("other-task") tab._completed(TaskOutcome(42, "ok", {"source_task": "source-task", "snapshot": "a" * 64, "draft": {"goal": "review remaining actions"}})) - assert len(requests) == 1 and tab._scope.toPlainText() == original_scope + assert len(requests) == 1 + assert tab._scope.toPlainText() == original_scope review = json.loads(tab._remainder_request.toPlainText()) if change_task: assert review == {} return - assert review["task_id"] == "source-task" and review["note"] == "" + assert review["task_id"] == "source-task" + assert review["note"] == "" handle.outcome = "finished" review["note"] = "Reviewed remaining actions in the new context" tab._remainder_request.setPlainText(json.dumps(review)) @@ -170,9 +172,11 @@ def test_dynamic_review_template_requires_manual_goal_and_note_without_submittin template = {"goal": "", "mode": "ollama", "options": {"model": "fixture-tools"}, "actions": []} tab._present_result({"source_task": "source-task", "source_mode": "ollama", "snapshot": "a" * 64, "draft": None, "review_template": template, "issues": ["new_plan_required"]}) - assert submitted == [] and tab._scope.toPlainText() == original_scope + assert submitted == [] + assert tab._scope.toPlainText() == original_scope request = json.loads(tab._remainder_request.toPlainText()) - assert request["spec"]["goal"] == "" and request["note"] == "" + assert request["spec"]["goal"] == "" + assert request["note"] == "" request["spec"]["goal"] = "Read only the remaining field" request["note"] = "Reviewed the new plan" tab._remainder_request.setPlainText(json.dumps(request)) @@ -198,7 +202,8 @@ def test_authorization_review_and_creation_are_distinct_explicit_actions(monkeyp "draft": {"goal": "reviewed remaining work", "roots": ["D:/reports"]}, "issues": []}) assert len(submitted) == 1 request = json.loads(tab._remainder_request.toPlainText()) - assert request["authorization_review"] == "b" * 64 and request["note"] == "" + assert request["authorization_review"] == "b" * 64 + assert request["note"] == "" request["note"] = "Reviewed the new report root" tab._remainder_request.setPlainText(json.dumps(request)) dict(tab.menu_actions())["agent_reauthorize_create"]() @@ -257,7 +262,8 @@ def test_source_owner_recovery_requires_its_preview_and_cannot_reuse_another_own result["authorization_review"] = "c" * 64 tab._present_remainder(result) request = json.loads(tab._remainder_request.toPlainText()) - assert request["owner_policy"] == "source_owner" and request["ownership_review"] == "b" * 64 + assert request["owner_policy"] == "source_owner" + assert request["ownership_review"] == "b" * 64 request["note"] = "Reviewed original ownership and remainder" tab._remainder_request.setPlainText(json.dumps(request)) create = "create_authorized" if reauthorize else "create" @@ -265,7 +271,8 @@ def test_source_owner_recovery_requires_its_preview_and_cannot_reuse_another_own assert submitted[-1] == ("recovery", {"operation": create, "request": request}) tab._owner_policy.setCurrentIndex(0) tab._create_remainder(create) - assert len(submitted) == 2 and "selection changed" in tab._status.text() + assert len(submitted) == 2 + assert "selection changed" in tab._status.text() finally: tab.close() shiboken6.delete(tab) diff --git a/test/unit_test/headless/test_agent_transfer_adoption.py b/test/unit_test/headless/test_agent_transfer_adoption.py index a4704d03c..56c1efac3 100644 --- a/test/unit_test/headless/test_agent_transfer_adoption.py +++ b/test/unit_test/headless/test_agent_transfer_adoption.py @@ -58,7 +58,8 @@ def test_actual_coordinator_adopts_another_remote_owners_leaf_without_read_or_in running = start(value, reviewed, approved) result = value.coordinator.batches.control('validate_node', {'batch_id': reviewed['batch_id'], 'node_id': 'remote-file', 'attempt': running['attempt']}) - assert result['outcome'] == 'completed' and result['task_id'] == value.child + assert result['outcome'] == 'completed' + assert result['task_id'] == value.child with authorization_scope(value.owner), pytest.raises(AgentTaskError, match='another caller'): value.runtime.get(value.child) assert value.runtime.store.actions(value.child) == before @@ -126,7 +127,8 @@ def claim(connection, batch, request): status, absent = post(value.server, '/agent/lookup', {'idempotency_key': next( node['task']['idempotency_key'] for node in running['definition']['nodes'] if node['id'] == 'downstream')}, token=value.owner_token) - assert status == 200 and absent['found'] is False + assert status == 200 + assert absent['found'] is False @pytest.mark.parametrize('lost_ack', [False, True]) @@ -225,7 +227,8 @@ def interrupted(*_args): assert original['state'] == 'provisional' assert connection.execute('SELECT count(*) FROM agent_dag_adoptions').fetchone()[0] == 0 approved = approve(value, reviewed) - assert approved['approval_id'] == original['id'] and approved['approval_state'] == 'ready' + assert approved['approval_id'] == original['id'] + assert approved['approval_state'] == 'ready' with value.coordinator.store.connection() as connection: assert connection.execute('SELECT count(*) FROM agent_dag_approvals').fetchone()[0] == 1 diff --git a/test/unit_test/headless/test_agent_transfer_adoption_active_restart.py b/test/unit_test/headless/test_agent_transfer_adoption_active_restart.py index 11e4d623c..0c6cbe93f 100644 --- a/test/unit_test/headless/test_agent_transfer_adoption_active_restart.py +++ b/test/unit_test/headless/test_agent_transfer_adoption_active_restart.py @@ -79,15 +79,18 @@ def response(operation, body, timeout): value.coordinator.close() value.coordinator = AgentRuntime(path, targets={}) current = value.coordinator.batches.control('get', {'batch_id': reviewed['batch_id']}) - assert current['state'] == 'waiting_review' and not future.done() + assert current['state'] == 'waiting_review' + assert not future.done() node = next(row for row in current['nodes'] if row['id'] == 'downstream') assert node['phase'] == 'unknown' assert node['receipt'] == {'outcome': 'requires_review', 'task_id': dependent} with authorization_scope(value.owner): stopped = value.runtime.get(dependent) - assert stopped.state == 'pausing' and stopped.metadata['input_released'] is False + assert stopped.state == 'pausing' + assert stopped.metadata['input_released'] is False assert value.runtime.store.get(independent)['state'] == previous - assert effect.read_bytes() == original_bytes and calls == ['AC_workflow_manifest'] + assert effect.read_bytes() == original_bytes + assert calls == ['AC_workflow_manifest'] finally: release.set() try: diff --git a/test/unit_test/headless/test_agent_transfer_adoption_restart.py b/test/unit_test/headless/test_agent_transfer_adoption_restart.py index 76dfbe230..ccbf5ff1e 100644 --- a/test/unit_test/headless/test_agent_transfer_adoption_restart.py +++ b/test/unit_test/headless/test_agent_transfer_adoption_restart.py @@ -63,11 +63,13 @@ def test_actual_coordinator_reopen_preserves_consent_identity_and_revalidates_re if change == 'none': if phase == 'provisional': approved = approve(value, reviewed) - assert approved['approval_id'] == stored['id'] and approved['approval_state'] == 'ready' + assert approved['approval_id'] == stored['id'] + assert approved['approval_state'] == 'ready' running = start(value, reviewed, approved) result = value.coordinator.batches.control('validate_node', {'batch_id': reviewed['batch_id'], 'node_id': 'remote-file', 'attempt': running['attempt']}) - assert result['outcome'] == 'completed' and result['task_id'] == value.child + assert result['outcome'] == 'completed' + assert result['task_id'] == value.child with value.runtime.store.connection() as database: record = value.runtime.transfers.source.records.find(database, identifier) assert record['expires'] == expires, 'Coordinator restart cannot renew the source evidence deadline' @@ -81,5 +83,6 @@ def test_actual_coordinator_reopen_preserves_consent_identity_and_revalidates_re assert database.execute('SELECT state FROM agent_dag_batches').fetchone()[0] != 'running' with value.coordinator.store.connection() as database: assert database.execute('SELECT count(*) FROM agent_dag_approvals').fetchone()[0] == 1 - assert value.coordinator.list() == [] and value.runtime.store.actions(value.child) == actions + assert value.coordinator.list() == [] + assert value.runtime.store.actions(value.child) == actions assert value.output.read_bytes() == value.body diff --git a/test/unit_test/headless/test_agent_transfer_cold_lifecycle.py b/test/unit_test/headless/test_agent_transfer_cold_lifecycle.py index d6356f5a1..25d59d339 100644 --- a/test/unit_test/headless/test_agent_transfer_cold_lifecycle.py +++ b/test/unit_test/headless/test_agent_transfer_cold_lifecycle.py @@ -116,7 +116,8 @@ def confined(database): reopened.maintain() with reopened.store.connection() as connection: retained = reopened.transfers.source.records.find(connection, record['id']) - assert retained['state'] == 'revoked' and retained['held'] is True + assert retained['state'] == 'revoked' + assert retained['held'] is True assert retained['expires'] == record['expires'] assert foreign.path.read_bytes() == before assert foreign.store.read_chunk(record['account'], digest) == foreign_body diff --git a/test/unit_test/headless/test_agent_transfer_diagnostics.py b/test/unit_test/headless/test_agent_transfer_diagnostics.py index 9ade75a05..92cd73837 100644 --- a/test/unit_test/headless/test_agent_transfer_diagnostics.py +++ b/test/unit_test/headless/test_agent_transfer_diagnostics.py @@ -18,7 +18,9 @@ def forbidden(*_args, **_kwargs): monkeypatch.setattr('je_auto_control.utils.agent_runtime.transport.request_json', forbidden) before = set(tmp_path.rglob('*')) result = check() - assert result.name == 'agent_transfer_contract' and result.ok and result.severity == 'info' + assert result.name == 'agent_transfer_contract' + assert result.ok + assert result.severity == 'info' assert result.extra == {'contract': TransferManifest.contract, 'operations': list(OPERATIONS), 'max_manifest_bytes': MAX_MANIFEST_BYTES, 'max_transfer_bytes': MAX_TRANSFER_BYTES, 'max_files': 500, 'state': 'contract_only', 'authority_granted': False, @@ -41,5 +43,7 @@ def test_existing_shared_diagnostics_surface_reports_only_contract_availability( report = run_tool_call('AC_diagnose', {}) assert report['count'] == 1 extra = report['checks'][0]['extra'] - assert extra['state'] == 'contract_only' and extra['authority_granted'] is False - assert extra['remote_verified'] is False and extra['native_verified'] is False + assert extra['state'] == 'contract_only' + assert extra['authority_granted'] is False + assert extra['remote_verified'] is False + assert extra['native_verified'] is False diff --git a/test/unit_test/headless/test_agent_transfer_evidence.py b/test/unit_test/headless/test_agent_transfer_evidence.py index acd620a66..0c4c2d4f8 100644 --- a/test/unit_test/headless/test_agent_transfer_evidence.py +++ b/test/unit_test/headless/test_agent_transfer_evidence.py @@ -66,18 +66,24 @@ def test_actual_local_dag_recovery_resolves_only_the_reviewed_portable_proof(tmp binding = actual_binding(runtime, source) status, proof = evidence_read(server, grant, binding) assert status == 200, proof - assert proof['source_task'] == source and proof['task_id'] == child - assert proof['grant_id'] == grant and proof['evidence_only'] is True and proof['input_authorized'] is False + assert proof['source_task'] == source + assert proof['task_id'] == child + assert proof['grant_id'] == grant + assert proof['evidence_only'] is True + assert proof['input_authorized'] is False assert proof['submitted_spec_digest'] == binding['submitted_spec_digest'] expected = {'key_hash': binding['request_key_hash'], 'submitted_spec_digest': binding['submitted_spec_digest']} digest = sha256(json.dumps(expected, sort_keys=True, separators=(',', ':')).encode()).hexdigest() assert proof['node']['request_digest'] == digest - assert len(proof['chain']) == 1 and proof['chain'][0]['source_task'] == source + assert len(proof['chain']) == 1 + assert proof['chain'][0]['source_task'] == source assert str(tmp_path) not in json.dumps(proof) - assert runtime.store.actions(child) == before and output.read_bytes() == body + assert runtime.store.actions(child) == before + assert output.read_bytes() == body status, again = evidence_create(server, reviewed) - assert status == 200 and again == created + assert status == 200 + assert again == created @pytest.mark.parametrize('boundary', ['create', 'resolve']) diff --git a/test/unit_test/headless/test_agent_transfer_evidence_expiry.py b/test/unit_test/headless/test_agent_transfer_evidence_expiry.py index 920648dd9..de4c60d88 100644 --- a/test/unit_test/headless/test_agent_transfer_evidence_expiry.py +++ b/test/unit_test/headless/test_agent_transfer_evidence_expiry.py @@ -25,7 +25,8 @@ def test_evidence_expiry_preserves_later_artifact_grant_and_all_user_output(tmp_ expiry = created['evidence']['summary']['expires'] with runtime.store.connection() as connection: original = runtime.store.read_task(connection, source) - assert original['state'] == 'cancelled' and expiry == original['updated'] + 30 * 86400 + assert original['state'] == 'cancelled' + assert expiry == original['updated'] + 30 * 86400 intent = dict(connection.execute('SELECT * FROM agent_transfer_intents WHERE id=?', (grant,)).fetchone()) assert exported['manifest']['expires'] > expiry + 100 binding = actual_binding(runtime, source) @@ -55,7 +56,8 @@ def test_evidence_expiry_preserves_later_artifact_grant_and_all_user_output(tmp_ assert dict(retained) == intent assert connection.execute('SELECT 1 FROM agent_transfer_revocations WHERE id=?', (grant,)).fetchone() artifact = runtime.transfers.source.records.find(connection, exported['export_id']) - assert artifact['state'] == 'active' and artifact['held'] is True + assert artifact['state'] == 'active' + assert artifact['held'] is True assert runtime.transfers.peer('export', {'export_id': exported['export_id']}) == exported['manifest'] assert output.read_bytes() == body finally: diff --git a/test/unit_test/headless/test_agent_transfer_evidence_remote.py b/test/unit_test/headless/test_agent_transfer_evidence_remote.py index fc66495ee..ce075e34d 100644 --- a/test/unit_test/headless/test_agent_transfer_evidence_remote.py +++ b/test/unit_test/headless/test_agent_transfer_evidence_remote.py @@ -83,7 +83,8 @@ def test_registered_http_peer_resolves_other_owner_completion_without_general_ta binding = actual_binding(value.runtime, value.source) host_binding = value.coordinator.batches.transfer_binding('source') proof = resolve_remote_evidence(value.coordinator.transfers.remote, 'source', host_binding, identifier, binding) - assert proof['task_id'] == value.child and proof['node']['node_id'] == 'remote-file' + assert proof['task_id'] == value.child + assert proof['node']['node_id'] == 'remote-file' assert value.runtime.store.get(value.child)['owner']['user_id'] == 'reviewer' assert value.output.read_bytes() == value.body status, denied = post(value.server, '/agent/transfer/peer', {'operation': 'evidence', 'request': { @@ -143,7 +144,9 @@ def test_keyed_standalone_recovery_resolves_without_a_fabricated_dag_admission(t binding = actual_binding(value.runtime, source) proof = resolve_remote_evidence(value.coordinator.transfers.remote, 'source', value.coordinator.batches.transfer_binding('source'), created['evidence']['grant_id'], binding) - assert proof['source_task'] == source and proof['task_id'] == child and 'node' not in proof + assert proof['source_task'] == source + assert proof['task_id'] == child + assert 'node' not in proof with value.runtime.store.connection() as connection: assert connection.execute('SELECT count(*) FROM agent_dag_local_tasks').fetchone()[0] == 0 submitted = connection.execute('SELECT 1 FROM agent_task_submissions WHERE task_id=?', (source,)) @@ -159,7 +162,8 @@ def test_revoked_wire_consent_never_recreates_wire_authority(tmp_path, monkeypat identifier = created['evidence']['grant_id'] status, revoked = post(value.server, '/agent/transfer', {'operation': 'revoke_evidence', 'request': {'grant_id': identifier}}, token=value.owner_token) - assert status == 200 and revoked['evidence']['state'] == 'revoked' + assert status == 200 + assert revoked['evidence']['state'] == 'revoked' status, denied = evidence_create(value.server, reviewed, token=value.reviewer_token) assert status == 409, denied with pytest.raises(AgentTaskError): @@ -168,4 +172,5 @@ def test_revoked_wire_consent_never_recreates_wire_authority(tmp_path, monkeypat actual_binding(value.runtime, value.source)) with value.runtime.store.connection() as connection: record = value.runtime.transfers.source.records.find(connection, identifier) - assert record['state'] == 'revoked' and record['held'] is False + assert record['state'] == 'revoked' + assert record['held'] is False diff --git a/test/unit_test/headless/test_agent_transfer_gui.py b/test/unit_test/headless/test_agent_transfer_gui.py index 29943a582..ea46198ca 100644 --- a/test/unit_test/headless/test_agent_transfer_gui.py +++ b/test/unit_test/headless/test_agent_transfer_gui.py @@ -41,8 +41,10 @@ def test_examples_prepare_explicit_source_destination_and_grant_selection(tab, m actions['agent_transfer_example_' + example]() assert view._operation.currentData() == operation request = json.loads(view._request.toPlainText()) - assert set(request) == fields and request['idempotency_key'] == '' - assert tab._pages.currentWidget() is view and tab.findChildren(QPushButton) == [] + assert set(request) == fields + assert request['idempotency_key'] == '' + assert tab._pages.currentWidget() is view + assert tab.findChildren(QPushButton) == [] tab.retranslate() assert json.loads(view._request.toPlainText()) == request @@ -91,7 +93,8 @@ def test_review_only_prepares_approval_after_an_explicit_action_preserving_key_a actions = dict(tab.menu_actions()) actions['agent_transfer_apply']() view._completed(TaskOutcome(41, 'ok', {'review': 'a' * 64, 'approval_required': True})) - assert view._operation.currentData() == 'review_export' and len(calls) == 1 + assert view._operation.currentData() == 'review_export' + assert len(calls) == 1 assert json.loads(view._request.toPlainText()) == request actions['agent_transfer_prepare_approval']() assert view._operation.currentData() == 'create_export' @@ -103,7 +106,8 @@ def test_review_only_prepares_approval_after_an_explicit_action_preserving_key_a view._request.setPlainText(json.dumps(prepared)) handle.outcome = 'finished' actions['agent_transfer_apply']() - assert len(calls) == 2 and calls[1].args == ('create_export', prepared) + assert len(calls) == 2 + assert calls[1].args == ('create_export', prepared) @pytest.mark.parametrize('language', ['english', 'traditional_chinese', 'simplified_chinese', 'japanese']) @@ -129,7 +133,8 @@ def test_create_rejects_missing_blank_or_nontext_approval_before_dispatch(tab, m view._operation.setCurrentIndex(view._operation.findData('create_evidence')) view._request.setPlainText(json.dumps({'review': 'a' * 64, 'idempotency_key': 'key', 'note': note})) dict(tab.menu_actions())['agent_transfer_apply']() - assert calls == [] and view._status.text() + assert calls == [] + assert view._status.text() def test_closed_transfer_gui_leaves_the_actual_accepted_import_owned_by_the_service(tab, tmp_path, monkeypatch): @@ -181,8 +186,10 @@ def paused(*args): assert (Path(current['files_directory']) / 'report.txt').read_bytes() == body with host.runtime.store.connection() as database: after = host.runtime.transfers.source.records.find(database, identifier) - assert before['scope'] == after['scope'] and before['expires'] == after['expires'] - assert view._result.toPlainText() == '' and host.runtime.list() == [] + assert before['scope'] == after['scope'] + assert before['expires'] == after['expires'] + assert view._result.toPlainText() == '' + assert host.runtime.list() == [] finally: release.set() deadline = time.monotonic() + 5 diff --git a/test/unit_test/headless/test_agent_transfer_import_integrity.py b/test/unit_test/headless/test_agent_transfer_import_integrity.py index 66baa7092..c000936b7 100644 --- a/test/unit_test/headless/test_agent_transfer_import_integrity.py +++ b/test/unit_test/headless/test_agent_transfer_import_integrity.py @@ -61,7 +61,8 @@ def source_reply(importer, *args): status, accepted = operation(server, token, 'create_import', review(server, exported, token, root)) assert status == 200, accepted current = wait_import(server, token, accepted['import']['import_id']) - assert len(publications) == 1 and changed == [True] + assert len(publications) == 1 + assert changed == [True] if fault == 'none': assert current['state'] == 'published', current assert sha256((publications[0] / 'report.txt').read_bytes()).hexdigest() == ( diff --git a/test/unit_test/headless/test_agent_transfer_import_lifecycle.py b/test/unit_test/headless/test_agent_transfer_import_lifecycle.py index 73fe4e8c4..6a572c481 100644 --- a/test/unit_test/headless/test_agent_transfer_import_lifecycle.py +++ b/test/unit_test/headless/test_agent_transfer_import_lifecycle.py @@ -169,7 +169,8 @@ def observed(importer, identifier, *args): delivered = host.runtime.transfers._life.importer._state.jobs.ledger.read(connection, identifier) assert delivered['generation'] == before['generation'] assert delivered['queue_id'] == before['queue_id'] - assert after['scope'] == original['scope'] and after['expires'] == original['expires'] + assert after['scope'] == original['scope'] + assert after['expires'] == original['expires'] assert host.runtime.list() == [] finally: release.set() diff --git a/test/unit_test/headless/test_agent_transfer_import_restart.py b/test/unit_test/headless/test_agent_transfer_import_restart.py index 01725e0cd..cc260e009 100644 --- a/test/unit_test/headless/test_agent_transfer_import_restart.py +++ b/test/unit_test/headless/test_agent_transfer_import_restart.py @@ -244,7 +244,8 @@ def observed(peer, source_host, binding, name, request, timeout): current = wait_import(named, token, identifier) assert current['state'] == 'published', current assert (Path(current['files_directory']) / 'report.txt').read_bytes() == body - assert 'export' in calls and 'chunk' not in calls, 'resume rechecks the real grant and owned cached bytes' + assert 'export' in calls, 'resume rechecks the real grant and owned cached bytes' + assert 'chunk' not in calls, 'resume rechecks the real grant and owned cached bytes' with restarted.runtime.store.connection() as connection: after = restarted.runtime.transfers.source.records.find(connection, identifier) delivery = connection.execute('SELECT queue_id,generation FROM agent_transfer_deliveries WHERE id=?', diff --git a/test/unit_test/headless/test_agent_transfer_payloads.py b/test/unit_test/headless/test_agent_transfer_payloads.py index 9d1b1254a..be9584008 100644 --- a/test/unit_test/headless/test_agent_transfer_payloads.py +++ b/test/unit_test/headless/test_agent_transfer_payloads.py @@ -75,7 +75,8 @@ def transport(batches, host, binding, path, body, timeout): with import_hosts(tmp_path, monkeypatch, source_context=manifest_source, selection=selection) as values: host, server, exported, bodies, token, root, _actor = values manifests = {item['name']: item for item in exported['manifest']['files']} - assert manifests['empty.bin']['size'] == 0 and manifests['empty.bin']['chunks'] == [] + assert manifests['empty.bin']['size'] == 0 + assert manifests['empty.bin']['chunks'] == [] if 'large.bin' in manifests: assert len(manifests['large.bin']['chunks']) == 3 status, reply = operation(server, token, 'create_import', review(server, exported, token, root)) diff --git a/test/unit_test/headless/test_agent_transfer_private_sources.py b/test/unit_test/headless/test_agent_transfer_private_sources.py index d78140830..c513377a7 100644 --- a/test/unit_test/headless/test_agent_transfer_private_sources.py +++ b/test/unit_test/headless/test_agent_transfer_private_sources.py @@ -36,7 +36,8 @@ def test_actual_private_file_is_refused_before_opening_selected_bytes(tmp_path, 'evidence': runtime.evidence.directory(initial) / 'report.json', 'cache': runtime.transfers.source._cache.path} private = paths[kind] - assert private.is_file() and private.stat().st_size > 0 + assert private.is_file() + assert private.stat().st_size > 0 task = completed_file(runtime, tmp_path, private) actual_open = transfer_files.os.open diff --git a/test/unit_test/headless/test_agent_transfer_reader_evidence.py b/test/unit_test/headless/test_agent_transfer_reader_evidence.py index 6d9aecd12..54af01e76 100644 --- a/test/unit_test/headless/test_agent_transfer_reader_evidence.py +++ b/test/unit_test/headless/test_agent_transfer_reader_evidence.py @@ -41,10 +41,14 @@ def test_actual_renewed_reader_exports_only_evidence_without_reviving_old_input( binding = actual_binding(value.runtime, value.source) status, proof = evidence_read(server, identifier, binding, token=owner_token) assert status == 200, proof - assert proof['task_id'] == child and proof['source_task'] == value.source - assert proof['evidence_only'] is True and proof['input_authorized'] is False - assert 'owner' not in proof and str(value.reports) not in json.dumps(proof) - assert value.runtime.store.actions(value.source) == actions and value.manifest.read_bytes() == output + assert proof['task_id'] == child + assert proof['source_task'] == value.source + assert proof['evidence_only'] is True + assert proof['input_authorized'] is False + assert 'owner' not in proof + assert str(value.reports) not in json.dumps(proof) + assert value.runtime.store.actions(value.source) == actions + assert value.manifest.read_bytes() == output assert value.runtime.store.actions(child) == [] with authorization_scope(value.owner), pytest.raises(AgentTaskError, match='another caller'): value.runtime.get(child) @@ -92,7 +96,8 @@ def test_lost_actual_reader_authority_cannot_create_or_resolve_a_portable_grant( status, result = evidence_read(server, identifier, binding, token=owner_token) assert status == 409, result assert value.runtime.store.actions(value.source) == before - assert value.runtime.store.actions(child) == [] and value.manifest.read_bytes() == output + assert value.runtime.store.actions(child) == [] + assert value.manifest.read_bytes() == output def test_retained_readonly_consent_still_requires_the_original_batch_issuance_state(renewal, monkeypatch): diff --git a/test/unit_test/headless/test_agent_transfer_registered.py b/test/unit_test/headless/test_agent_transfer_registered.py index ee6a72a12..ffe2738a5 100644 --- a/test/unit_test/headless/test_agent_transfer_registered.py +++ b/test/unit_test/headless/test_agent_transfer_registered.py @@ -67,7 +67,8 @@ def test_another_real_clients_persisted_replacement_refuses_the_old_binding_befo else: other.add_host('source', server.base_url + '/changed' if change == 'endpoint' else server.base_url, 'replacement-credential' if change == 'token' else token) - assert book.list_hosts()[0].token == token and book.list_hosts()[0].base_url == server.base_url + assert book.list_hosts()[0].token == token + assert book.list_hosts()[0].base_url == server.base_url def forbidden(*_args, **_kwargs): raise AssertionError('replaced registration must fail before network dispatch') monkeypatch.setattr(transport, 'request_json', forbidden) diff --git a/test/unit_test/headless/test_agent_transfer_routed_evidence.py b/test/unit_test/headless/test_agent_transfer_routed_evidence.py index 04d79913c..8a4742812 100644 --- a/test/unit_test/headless/test_agent_transfer_routed_evidence.py +++ b/test/unit_test/headless/test_agent_transfer_routed_evidence.py @@ -23,7 +23,8 @@ def routed(tmp_path, monkeypatch): wire, invoke = [], transport.request_json def observe(url, **kwargs): if url == value.server.base_url + '/agent/transfer': - assert kwargs['token'] == value.reviewer_token and kwargs.get('delegate_local') is False + assert kwargs['token'] == value.reviewer_token + assert kwargs.get('delegate_local') is False record = deepcopy(kwargs['body']) wire.append(record) result = invoke(url, **kwargs) @@ -62,23 +63,28 @@ def test_named_coordinator_reviews_creates_lists_and_revokes_one_actual_source_e control = value.coordinator.transfers.control reviewed = review(value) assert reviewed['review'] != value.wire[-1]['reply']['review'] - assert reviewed['evidence']['task_id'] == value.child and count_grants(value) == 0 + assert reviewed['evidence']['task_id'] == value.child + assert count_grants(value) == 0 request = approval(reviewed) created = control('create_evidence', request)['evidence'] - assert created['summary'] == reviewed['evidence'] and created['state'] == 'active' + assert created['summary'] == reviewed['evidence'] + assert created['state'] == 'active' assert control('create_evidence', request)['evidence'] == created assert control('get_evidence', {'host': 'source', 'grant_id': created['grant_id']})['evidence'] == created listed = control('list_evidence', {'host': 'source', 'source_task': value.source})['evidence'] assert listed == [created] revoked = control('revoke_evidence', {'host': 'source', 'grant_id': created['grant_id']})['evidence'] - assert revoked['state'] == 'revoked' and revoked['summary'] == created['summary'] + assert revoked['state'] == 'revoked' + assert revoked['summary'] == created['summary'] with pytest.raises(AgentTaskError): control('create_evidence', request) - assert count_grants(value) == 1 and value.coordinator.list() == [] + assert count_grants(value) == 1 + assert value.coordinator.list() == [] with authorization_scope(value.owner), pytest.raises(AgentTaskError, match='another caller'): value.runtime.get(value.child) encoded = json.dumps(value.wire) - assert str(value.coordinator_users.path) not in encoded and value.owner_token not in encoded + assert str(value.coordinator_users.path) not in encoded + assert value.owner_token not in encoded assert all('host' not in item['request'] and 'owner' not in item['request'] for item in value.wire) assert value.output.read_bytes() == value.body @@ -110,13 +116,17 @@ def ambiguous(url, **kwargs): value.coordinator.close() value.coordinator = AgentRuntime(path, targets={}) current = value.coordinator.transfers.control('create_evidence', request)['evidence'] - assert current['summary'] == reviewed['evidence'] and current['state'] == 'active' - assert count_grants(value) == 1 and len(dropped) == 1 + assert current['summary'] == reviewed['evidence'] + assert current['state'] == 'active' + assert count_grants(value) == 1 + assert len(dropped) == 1 with value.coordinator.store.connection() as database: records = value.coordinator.transfers.source.records routes = records.entries(database, 'route') - assert len(routes) == 1 and routes[0]['scope']['evidence'] == reviewed['evidence'] - assert 'manifest' not in routes[0]['scope'] and routes[0]['account'] is None + assert len(routes) == 1 + assert routes[0]['scope']['evidence'] == reviewed['evidence'] + assert 'manifest' not in routes[0]['scope'] + assert routes[0]['account'] is None @pytest.mark.parametrize('change', ['host', 'actor', 'key', 'issuer-role']) @@ -134,4 +144,5 @@ def test_changed_host_identity_key_or_source_role_cannot_mint_a_routed_grant(rou if change == 'actor' else value.actor) with authorization_scope(actor), pytest.raises(AgentTaskError): value.coordinator.transfers.control('create_evidence', request) - assert count_grants(value) == 0 and value.output.read_bytes() == value.body + assert count_grants(value) == 0 + assert value.output.read_bytes() == value.body diff --git a/test/unit_test/headless/test_agent_transfer_routing.py b/test/unit_test/headless/test_agent_transfer_routing.py index a311690ac..87d7ae49e 100644 --- a/test/unit_test/headless/test_agent_transfer_routing.py +++ b/test/unit_test/headless/test_agent_transfer_routing.py @@ -74,11 +74,13 @@ def create(routed, reviewed, **changes): def test_real_routed_consent_returns_a_local_token_and_exact_source_bytes(routed): reviewed = review(routed) peer_review = routed.wire[-1]['reply']['review'] - assert reviewed['review'] != peer_review and reviewed['approval_required'] is True + assert reviewed['review'] != peer_review + assert reviewed['approval_required'] is True assert reviewed['digest'] == routed.wire[-1]['reply']['digest'] assert 'host' not in routed.wire[-1]['request'] created = create(routed, reviewed)['export'] - assert created['manifest'] == reviewed['manifest'] and created['state'] == 'active' + assert created['manifest'] == reviewed['manifest'] + assert created['state'] == 'active' assert routed.wire[-1]['request']['review'] == peer_review pin = routed.runtime.batches.transfer_binding('source') digest = created['manifest']['files'][0]['chunks'][0] @@ -89,7 +91,8 @@ def test_real_routed_consent_returns_a_local_token_and_exact_source_bytes(routed with pytest.raises(AgentTaskError): routed.runtime.get(routed.task) encoded = json.dumps(reviewed) - assert str(routed.users.path) not in encoded and routed.actor.user_id not in encoded + assert str(routed.users.path) not in encoded + assert routed.actor.user_id not in encoded with routed.source.store.connection() as connection: scope = json.loads(connection.execute('SELECT payload FROM agent_transfer_grants').fetchone()[0])['scope'] assert scope['issuer']['user_id'] == scope['recipient']['user_id'] == 'owner' @@ -102,7 +105,8 @@ def test_routed_management_get_list_and_revoke_use_the_actual_source(routed): assert controller.control('get_export', {'host': 'source', 'export_id': created['export_id']})['export'] == created assert controller.control('list_exports', {'host': 'source', 'source_task': routed.task})['exports'] == [created] revoked = controller.control('revoke_export', {'host': 'source', 'export_id': created['export_id']})['export'] - assert revoked['state'] == 'revoked' and revoked['cleanup_pending'] is False + assert revoked['state'] == 'revoked' + assert revoked['cleanup_pending'] is False assert routed.runtime.list() == [] @@ -116,7 +120,9 @@ def lose_ack(url, **kwargs): if envelope.get('operation') == 'create_export': with routed.runtime.store.connection() as connection: rows = connection.execute('SELECT state,note_hash FROM agent_transfer_routed_reviews').fetchall() - assert len(rows) == 1 and rows[0]['state'] == 'active' and rows[0]['note_hash'] + assert len(rows) == 1 + assert rows[0]['state'] == 'active' + assert rows[0]['note_hash'] sent.append(deepcopy(envelope)) reply = original(url, **kwargs) if len(sent) == 1: @@ -133,7 +139,8 @@ def lose_ack(url, **kwargs): routed.runtime.close() routed.runtime = AgentRuntime(path, targets={}) created = create(routed, reviewed)['export'] - assert created['export_id'] == identifier and sent[0] == sent[1] + assert created['export_id'] == identifier + assert sent[0] == sent[1] with routed.source.store.connection() as connection: assert connection.execute('SELECT count(*) FROM agent_transfer_grants').fetchone()[0] == 1 @@ -143,7 +150,8 @@ def test_routed_recipient_policy_derives_only_the_sources_actual_identities(rout created = create(routed, review(routed, recipient_policy='source_owner'))['export'] with routed.source.store.connection() as connection: scope = json.loads(connection.execute('SELECT payload FROM agent_transfer_grants').fetchone()[0])['scope'] - assert scope['issuer']['user_id'] == 'reviewer' and scope['recipient']['user_id'] == 'owner' + assert scope['issuer']['user_id'] == 'reviewer' + assert scope['recipient']['user_id'] == 'owner' pin = routed.runtime.batches.transfer_binding('source') with pytest.raises(AgentTaskError): routed.runtime.transfers.remote.call('source', pin, 'export', {'export_id': created['export_id']}, 3) @@ -331,7 +339,8 @@ def limited(url, **kwargs): monkeypatch.setattr(controller._routing, '_prepare', elapsed) monkeypatch.setattr(transport, 'request_json', limited) - assert review(routed)['approval_required'] is True and len(observed) == 1 + assert review(routed)['approval_required'] is True + assert len(observed) == 1 def test_pending_route_cap_refuses_more_source_requests(routed, monkeypatch): diff --git a/test/unit_test/headless/test_agent_transfer_skill_evidence.py b/test/unit_test/headless/test_agent_transfer_skill_evidence.py index 4b9f2c984..f6b5c582d 100644 --- a/test/unit_test/headless/test_agent_transfer_skill_evidence.py +++ b/test/unit_test/headless/test_agent_transfer_skill_evidence.py @@ -36,13 +36,17 @@ def test_portable_consent_records_only_real_original_actions_without_fabricating with pytest.raises(AgentTaskError, match='another caller'): runtime.get(value.child_id) candidate = runtime.skills.control('record', request_for(value, handoff_id=identifier)) - assert candidate['state'] == 'draft' and candidate['version'] == 0 and candidate['publication'] is None + assert candidate['state'] == 'draft' + assert candidate['version'] == 0 + assert candidate['publication'] is None assert candidate['spec']['actions'] == [value.action] assert candidate['provenance']['source_task'] == value.task_id proof = candidate['provenance']['completion_review'] - assert proof['task_id'] == value.child_id and proof['effect_task'] == value.task_id + assert proof['task_id'] == value.child_id + assert proof['effect_task'] == value.task_id assert proof['evidence_handoff']['id'] == identifier - assert runtime.store.actions(value.task_id) == receipts and value.manifest.read_bytes() == manifest + assert runtime.store.actions(value.task_id) == receipts + assert value.manifest.read_bytes() == manifest assert runtime.store.actions(value.child_id) == [] with runtime.store.connection() as connection: assert connection.execute('SELECT count(*) FROM agent_skill_trials').fetchone()[0] == 0 @@ -61,12 +65,15 @@ def test_portable_completion_publishes_the_real_trial_and_preserves_its_original receipts = runtime.store.actions(trial.task_id) manifest = trial.manifest.read_bytes() accepted = runtime.skills.control('accept', {**acceptance(trial), 'handoff_id': identifier}) - assert accepted['state'] == 'accepted' and accepted['version'] == 1 + assert accepted['state'] == 'accepted' + assert accepted['version'] == 1 assert accepted['publication']['task_id'] == trial.task_id proof = accepted['publication']['completion_review'] - assert proof['task_id'] == trial.child_id and proof['effect_task'] == trial.task_id + assert proof['task_id'] == trial.child_id + assert proof['effect_task'] == trial.task_id assert proof['evidence_handoff']['id'] == identifier - assert runtime.store.actions(trial.task_id) == receipts and trial.manifest.read_bytes() == manifest + assert runtime.store.actions(trial.task_id) == receipts + assert trial.manifest.read_bytes() == manifest assert runtime.store.actions(trial.child_id) == [] with runtime.store.connection() as connection: tasks = connection.execute('SELECT task_id,purpose FROM agent_skill_trials').fetchall() @@ -111,7 +118,9 @@ def test_revocation_inside_publication_rolls_back_version_and_completion_adoptio with pytest.raises(AgentTaskError): runtime.skills.control('accept', {**acceptance(trial), 'handoff_id': identifier}) candidate = runtime.skills.control('get', {'candidate_id': trial.candidate['id']}) - assert candidate['state'] == 'draft' and candidate['version'] == 0 and candidate['publication'] is None + assert candidate['state'] == 'draft' + assert candidate['version'] == 0 + assert candidate['publication'] is None with runtime.store.connection() as connection: assert connection.execute('SELECT count(*) FROM agent_skill_completions').fetchone()[0] == 0 assert connection.execute('SELECT count(*) FROM agent_skill_publications').fetchone()[0] == 0 @@ -145,7 +154,8 @@ def test_authenticated_source_service_records_portable_completion_and_rejects_re request = {'operation': 'record', 'request': request_for(value, handoff_id=identifier)} status, draft = post(server, '/agent/skill', request, token=token) assert status == 200, draft - assert draft['state'] == 'draft' and draft['spec']['actions'] == [value.action] + assert draft['state'] == 'draft' + assert draft['spec']['actions'] == [value.action] assert draft['provenance']['completion_review']['task_id'] == value.child_id status, revoked = post(server, '/agent/transfer', {'operation': 'revoke_evidence', 'request': {'grant_id': identifier}}, token=token) @@ -165,9 +175,11 @@ def test_portable_executable_chain_retains_original_trial_effects_and_explicit_r reviewed = runtime.skills.control('review_execution', request) accepted = runtime.skills.control('accept', {**request, 'execution_review': reviewed['execution_review'], 'expected_version': 0, 'note': 'Review exact original effects and the granted completed successor'}) - assert accepted['version'] == 1 and accepted['publication']['task_id'] == value.task_id + assert accepted['version'] == 1 + assert accepted['publication']['task_id'] == value.task_id proof = accepted['publication']['execution_review'] - assert proof['source_task'] == value.task_id and proof['task_id'] == value.child_id + assert proof['source_task'] == value.task_id + assert proof['task_id'] == value.child_id assert proof['evidence_handoff']['id'] == identifier assert value.target.calls == calls with runtime.store.connection() as connection: @@ -195,7 +207,8 @@ def during_write(*args, **kwargs): monkeypatch.setattr(runtime.skills, '_record_publication', during_write) result = runtime.skills.control('accept', {**request, 'execution_review': reviewed['execution_review'], 'expected_version': 0, 'note': 'Retain the original owner through publication'}) - assert result['version'] == 1 and result['publication']['task_id'] == value.task_id + assert result['version'] == 1 + assert result['publication']['task_id'] == value.task_id with runtime.store.connection() as connection: assert connection.execute('SELECT count(*) FROM agent_skill_publications').fetchone()[0] == 1 runtime.close() @@ -220,7 +233,8 @@ def during_write(*args, **kwargs): monkeypatch.setattr(runtime.skills, '_insert_candidate', during_write) result = runtime.skills.control('record', request_for(value, handoff_id=identifier)) - assert result['state'] == 'draft' and result['publication'] is None + assert result['state'] == 'draft' + assert result['publication'] is None runtime.close() reopened = AgentRuntime(runtime.store.path, targets={}) reopened.close() diff --git a/test/unit_test/headless/test_agent_transfer_source.py b/test/unit_test/headless/test_agent_transfer_source.py index 174507f8d..5c0a15eb1 100644 --- a/test/unit_test/headless/test_agent_transfer_source.py +++ b/test/unit_test/headless/test_agent_transfer_source.py @@ -180,7 +180,9 @@ def test_source_bytes_changed_after_review_never_publish_and_user_file_is_preser assert output.read_bytes() == b'changed after review' with runtime.store.connection() as connection: rows = runtime.transfers.source.records.entries(connection, 'export') - assert len(rows) == 1 and rows[0]['state'] == 'revoked' and rows[0]['held'] is False + assert len(rows) == 1 + assert rows[0]['state'] == 'revoked' + assert rows[0]['held'] is False @pytest.mark.parametrize('operation', [[], {}]) diff --git a/test/unit_test/headless/test_agent_transfer_source_expiry.py b/test/unit_test/headless/test_agent_transfer_source_expiry.py index 354d34077..23e86349b 100644 --- a/test/unit_test/headless/test_agent_transfer_source_expiry.py +++ b/test/unit_test/headless/test_agent_transfer_source_expiry.py @@ -42,7 +42,8 @@ def failed(account): runtime.transfers.maintain() with runtime.store.connection() as connection: retained = source.records.find(connection, exported['export_id']) - assert retained['state'] == 'revoked' and retained['held'] is True + assert retained['state'] == 'revoked' + assert retained['held'] is True assert source._cache.store.status(original['account'])['chunks'] > 0 runtime.maintain() with runtime.store.connection() as connection: @@ -51,7 +52,8 @@ def failed(account): (exported['export_id'],)).fetchone() is not None assert connection.execute('SELECT 1 FROM agent_transfer_revocations WHERE id=?', (exported['export_id'],)).fetchone() is not None - assert retained['state'] == 'revoked' and retained['held'] is False + assert retained['state'] == 'revoked' + assert retained['held'] is False assert retained['expires'] == original['expires'] assert retained['scope'] == original['scope'] assert source._cache.store.status(original['account']) == {'bytes': 0, 'chunks': 0, 'blobs': 0} @@ -145,7 +147,8 @@ def test_source_expiry_does_not_retire_another_live_export_of_the_same_bytes(tmp assert runtime.transfers.peer('export', {'export_id': second['export_id']}) == second['manifest'] with runtime.store.connection() as connection: retained = source.records.find(connection, second['export_id']) - assert retained['held'] is True and retained['state'] == 'active' + assert retained['held'] is True + assert retained['state'] == 'active' assert retained['expires'] == live['expires'] assert output.read_bytes() == body diff --git a/test/unit_test/headless/test_agent_transfer_source_lifecycle.py b/test/unit_test/headless/test_agent_transfer_source_lifecycle.py index 43b388c49..66ddfda3e 100644 --- a/test/unit_test/headless/test_agent_transfer_source_lifecycle.py +++ b/test/unit_test/headless/test_agent_transfer_source_lifecycle.py @@ -168,12 +168,14 @@ def failed(_account): runtime.transfers.control('revoke_export', request) with runtime.store.connection() as connection: retained = source.records.find(connection, exported['export_id']) - assert retained['state'] == 'revoked' and retained['held'] + assert retained['state'] == 'revoked' + assert retained['held'] with pytest.raises(AgentTaskError): runtime.transfers.peer('export', request) monkeypatch.setattr(source._cache, 'delete_account', original) revoked = runtime.transfers.control('revoke_export', request)['export'] - assert revoked['state'] == 'revoked' and not revoked['cleanup_pending'] + assert revoked['state'] == 'revoked' + assert not revoked['cleanup_pending'] assert output.read_bytes() == body @@ -201,7 +203,8 @@ def test_artifact_expiry_uses_its_actual_completed_source_not_an_older_terminal_ with runtime.store.connection() as connection: ancestor = runtime.store.read_task(connection, source) leaf = runtime.store.read_task(connection, child) - assert ancestor['state'] == 'cancelled' and leaf['updated'] - ancestor['updated'] >= 120 + assert ancestor['state'] == 'cancelled' + assert leaf['updated'] - ancestor['updated'] >= 120 exported = create_for(runtime, review_for(runtime, child)) assert exported['manifest']['expires'] == leaf['updated'] + 30 * 86400 @@ -272,7 +275,8 @@ def lost_reply(*args, **kwargs): create_for(runtime, review) with runtime.store.connection() as connection: committed = source.records.entries(connection, 'export') - assert len(committed) == 1 and committed[0]['state'] == 'active' + assert len(committed) == 1 + assert committed[0]['state'] == 'active' recovered = create_for(runtime, review) assert recovered['export_id'] == committed[0]['id'] with runtime.store.connection() as connection: diff --git a/test/unit_test/headless/test_agent_transfer_source_readonly.py b/test/unit_test/headless/test_agent_transfer_source_readonly.py index 65e07db81..1e7d2a217 100644 --- a/test/unit_test/headless/test_agent_transfer_source_readonly.py +++ b/test/unit_test/headless/test_agent_transfer_source_readonly.py @@ -34,9 +34,12 @@ def test_actual_renewed_reader_exports_only_the_selected_file_with_old_input_sti child, exported = export_reader(renewal, monkeypatch) with authorization_scope(renewal.reviewer): manifest = renewal.runtime.transfers.peer('export', {'export_id': exported['export_id']}) - assert manifest['source_task'] == child and manifest['files'][0]['name'] == renewal.output.name + assert manifest['source_task'] == child + assert manifest['files'][0]['name'] == renewal.output.name public = json.dumps(exported) - assert str(renewal.reports) not in public and 'store_path' not in public and 'origin_policies' not in public + assert str(renewal.reports) not in public + assert 'store_path' not in public + assert 'origin_policies' not in public assert renewal.runtime.store.actions(renewal.source) == before assert renewal.old.identifier not in renewal.runtime.store.get(child)['spec']['options']['origin_policies'] diff --git a/test/unit_test/headless/test_agent_transfer_staging.py b/test/unit_test/headless/test_agent_transfer_staging.py index e5b4fd3b3..66a573b5c 100644 --- a/test/unit_test/headless/test_agent_transfer_staging.py +++ b/test/unit_test/headless/test_agent_transfer_staging.py @@ -138,7 +138,8 @@ def test_staging_cleanup_refuses_unrecognized_or_replaced_objects(tmp_path, chan unexpected.write_bytes(b'preserve unrelated data') assert unexpected.read_bytes() == b'preserve unrelated data' assert retired == [] - assert journal and journal[0]['cleaned'] is False + assert journal + assert journal[0]['cleaned'] is False @pytest.mark.parametrize('cancelled', [False, True]) diff --git a/test/unit_test/headless/test_agent_transfer_surfaces.py b/test/unit_test/headless/test_agent_transfer_surfaces.py index fb975ff31..2150bd032 100644 --- a/test/unit_test/headless/test_agent_transfer_surfaces.py +++ b/test/unit_test/headless/test_agent_transfer_surfaces.py @@ -55,7 +55,8 @@ def test_shared_transfer_surfaces_list_the_actual_source_without_creating_a_gran result = AgentRuntimeClient(value.connection).call('transfer', { 'operation': 'list_exports', 'request': request}) assert result == {'exports': []} - assert value.runtime.get(value.source).state == 'succeeded' and value.runtime.store.actions(value.source) == [] + assert value.runtime.get(value.source).state == 'succeeded' + assert value.runtime.store.actions(value.source) == [] assert value.output.read_bytes() == value.body with value.runtime.store.connection() as database: assert database.execute('SELECT count(*) FROM agent_transfer_grants').fetchone()[0] == 0 @@ -75,8 +76,10 @@ def test_public_api_names_and_builder_fields_share_the_same_management_contract( for module in (ac, api, core, agent_runtime): assert 'manage_agent_transfer' in module.__all__ function, fields, required, readonly, management = CATALOG['AC_agent_transfer'] - assert function is ac.manage_agent_transfer and required == ('operation',) - assert readonly is False and management is False + assert function is ac.manage_agent_transfer + assert required == ('operation',) + assert readonly is False + assert management is False assert fields['operation']['enum'] == list(OPERATIONS) assert not {'export', 'chunk', 'evidence'} & set(fields['operation']['enum']) specification = COMMAND_SPECS['AC_agent_transfer'] @@ -110,7 +113,8 @@ def test_public_creation_requires_its_review_and_keeps_peer_reads_on_the_separat 'idempotency_key': 'public-consent-flow'} first = ac.manage_agent_transfer('create_export', request) second = ac.manage_agent_transfer('create_export', request) - assert first == second and first['export']['state'] == 'active' + assert first == second + assert first['export']['state'] == 'active' manifest = first['export']['manifest'] assert manifest['files'][0]['sha256'] == sha256(value.body).hexdigest() identifier = first['export']['export_id'] @@ -119,4 +123,5 @@ def test_public_creation_requires_its_review_and_keeps_peer_reads_on_the_separat assert value.runtime.transfers.peer('export', {'export_id': identifier}) == manifest with value.runtime.store.connection() as database: assert database.execute('SELECT count(*) FROM agent_transfer_grants').fetchone()[0] == 1 - assert value.output.read_bytes() == value.body and value.runtime.store.actions(value.source) == [] + assert value.output.read_bytes() == value.body + assert value.runtime.store.actions(value.source) == [] diff --git a/test/unit_test/headless/test_agent_transport_boundary.py b/test/unit_test/headless/test_agent_transport_boundary.py index eebf48511..787059e94 100644 --- a/test/unit_test/headless/test_agent_transport_boundary.py +++ b/test/unit_test/headless/test_agent_transport_boundary.py @@ -52,7 +52,8 @@ def test_explicit_local_service_delegation_preserves_principal_and_live_roots(ca request_json("http://127.0.0.1:1234/agent/tasks", token="fixture-token", delegate_local=True) headers = calls[0]["headers"] principal = verify_principal(headers[PRINCIPAL_HEADER], "fixture-token", "/agent/tasks") - assert principal.user_id == "fixture-user" and principal.role == "operator" + assert principal.user_id == "fixture-user" + assert principal.role == "operator" assert headers[ORIGIN_HEADER] == identifier finally: policy.revoke_managed_origin() diff --git a/test/unit_test/headless/test_agent_trigger_authorization_surfaces.py b/test/unit_test/headless/test_agent_trigger_authorization_surfaces.py index 7d630eeab..f8f09baef 100644 --- a/test/unit_test/headless/test_agent_trigger_authorization_surfaces.py +++ b/test/unit_test/headless/test_agent_trigger_authorization_surfaces.py @@ -18,7 +18,8 @@ def test_cli_exposes_review_and_explicit_creation(): for operation in ("review_authorization", "create_authorized"): parsed = build_parser().parse_args(["agent-task", "trigger", operation, "review.json"]) - assert parsed.trigger_operation == operation and parsed.request == "review.json" + assert parsed.trigger_operation == operation + assert parsed.request == "review.json" def test_authenticated_http_preserves_owner_and_does_not_dispatch_inherited_queued_tasks(retired_trigger, monkeypatch): @@ -42,7 +43,8 @@ def test_authenticated_http_preserves_owner_and_does_not_dispatch_inherited_queu start.assert_not_called() duplicate = client.call("trigger", {"operation": "fire", "request": {"trigger_id": child, "event_key": "old-event", "payload": {"row": 1}}}) - assert duplicate["duplicate"] and duplicate["task_id"] == old_task + assert duplicate["duplicate"] + assert duplicate["task_id"] == old_task start.assert_not_called() proof = client.call("trigger", {"operation": "get", "request": {"trigger_id": child}}) assert proof["trigger"]["reauthorization"]["actor"] == "alice" @@ -72,14 +74,17 @@ def test_gui_review_prepares_separate_explicit_request_and_refuses_wrong_selecti tab._present_result({"trigger_id": "source-a", "snapshot": "a" * 64, "authorization_review": "b" * 64, "spec": {"goal": "future only"}, "approval_required": True}) request = json.loads(tab._trigger_config.toPlainText()) - assert request["note"] == "" and request["authorization_review"] == "b" * 64 - assert tab._scope.toPlainText() == original_scope and calls == [] + assert request["note"] == "" + assert request["authorization_review"] == "b" * 64 + assert tab._scope.toPlainText() == original_scope + assert calls == [] tab._trigger_operation.setCurrentIndex(tab._trigger_operation.findData("create_authorized")) dict(tab.menu_actions())["agent_trigger_apply"]() assert calls.pop() == ("trigger", {"operation": "create_authorized", "request": request}) tab._trigger_id.setText("source-b") dict(tab.menu_actions())["agent_trigger_apply"]() - assert calls == [] and "selected registration" in tab._status.text() + assert calls == [] + assert "selected registration" in tab._status.text() tab._view_task = "trigger:source-a" tab._handle = None tab._completed(TaskOutcome(100, "ok", {"trigger_id": "late-created"})) diff --git a/test/unit_test/headless/test_agent_trigger_reauthorization.py b/test/unit_test/headless/test_agent_trigger_reauthorization.py index dac1ee591..d74ffd470 100644 --- a/test/unit_test/headless/test_agent_trigger_reauthorization.py +++ b/test/unit_test/headless/test_agent_trigger_reauthorization.py @@ -65,7 +65,8 @@ def test_renewal_preserves_event_dedup_and_pending_limit_without_dispatching_old start.assert_not_called() assert runtime.triggers.control("create_authorized", request)["trigger_id"] == child duplicate = fire(runtime, child, "old-event", {"row": 1}) - assert duplicate["duplicate"] and duplicate["task_id"] == old_task + assert duplicate["duplicate"] + assert duplicate["task_id"] == old_task start.assert_not_called() with pytest.raises(AgentTaskError, match="different payload"): fire(runtime, child, "old-event", {"row": 2}) @@ -75,13 +76,15 @@ def test_renewal_preserves_event_dedup_and_pending_limit_without_dispatching_old assert fresh["task_id"] != old_task start.assert_called_once_with(fresh["task_id"]) assert fire(runtime, child, "future-event")["duplicate"] - assert start.call_count == 2 and start.call_args.args == (fresh["task_id"],) + assert start.call_count == 2 + assert start.call_args.args == (fresh["task_id"],) assert runtime.store.get(fresh["task_id"])["spec"]["roots"] == [str(narrow)] with pytest.raises(AgentTaskError, match="replacement"): runtime.triggers.control("enable", {"trigger_id": source}) after = runtime.triggers._row(source) assert not after["enabled"] - assert after["spec"] == original["spec"] and after["spec"]["roots"] == [str(allowed)] + assert after["spec"] == original["spec"] + assert after["spec"]["roots"] == [str(allowed)] @pytest.mark.parametrize("change", ["root", "actions", "tools", "criteria", "options", "snapshot", "digest"]) @@ -151,7 +154,9 @@ def test_three_generations_share_dedup_pending_and_do_not_resurrect_a_removed_ch assert fire(runtime, grandchild, "future-event")["deferred"] runtime.triggers.control("remove", {"trigger_id": grandchild}) repeat = runtime.triggers.control("create_authorized", second) - assert repeat["trigger_id"] == grandchild and repeat["retired"] and not repeat["enabled"] + assert repeat["trigger_id"] == grandchild + assert repeat["retired"] + assert not repeat["enabled"] assert runtime.triggers.control("review_authorization", {"trigger_id": child})["spec"] is None with pytest.raises(AgentTaskError, match="replacement"): runtime.triggers.control("enable", {"trigger_id": child}) @@ -219,7 +224,8 @@ def test_schedule_renewal_starts_in_the_future_without_replaying_missed_slots(re with origin_scope(current_id): child = runtime.triggers.control("create_authorized", approval(runtime, source))["trigger_id"] row = runtime.triggers._row(child) - assert row["next_run"] > time.time() + 50 and row["config"] == {"seconds": 60} + assert row["next_run"] > time.time() + 50 + assert row["config"] == {"seconds": 60} runtime.triggers.poll() assert len(runtime.store.list()) == 1 @@ -256,7 +262,8 @@ def create(_index): with ThreadPoolExecutor(max_workers=2) as workers: results = list(workers.map(create, (0, 1))) - assert results[0] == results[1] and len(runtime.triggers.list()["triggers"]) == 2 + assert results[0] == results[1] + assert len(runtime.triggers.list()["triggers"]) == 2 def test_new_event_history_failure_rolls_back_task_and_local_event_together(retired_trigger): @@ -290,4 +297,5 @@ def test_unavailable_fixed_watch_path_withholds_runnable_review(retired_trigger) path.write_text(json.dumps(data)) with origin_scope(current_id): view = runtime.triggers.control("review_authorization", {"trigger_id": source}) - assert view["spec"] is None and view["issues"] == ["authorization_scope_unavailable"] + assert view["spec"] is None + assert view["issues"] == ["authorization_scope_unavailable"] diff --git a/test/unit_test/headless/test_agent_worker_shutdown.py b/test/unit_test/headless/test_agent_worker_shutdown.py index 17e02e17d..f81e96aab 100644 --- a/test/unit_test/headless/test_agent_worker_shutdown.py +++ b/test/unit_test/headless/test_agent_worker_shutdown.py @@ -25,11 +25,13 @@ def __init__(self, _spec): try: task = runtime.submit(specification(mode="ollama")) jobs.start(task.task_id) - assert entered.wait(3) and not runtime._leases + assert entered.wait(3) + assert not runtime._leases assert runtime.get(task.task_id).state == "queued" jobs.close() assert runtime.get(task.task_id).state == "cancelled" - assert not jobs._running and all(not thread.is_alive() for thread in jobs._workers) + assert not jobs._running + assert all(not thread.is_alive() for thread in jobs._workers) finally: jobs.close() runtime.close() diff --git a/test/unit_test/headless/test_agent_workspace_lifetime.py b/test/unit_test/headless/test_agent_workspace_lifetime.py index c8c4f5237..146b731dd 100644 --- a/test/unit_test/headless/test_agent_workspace_lifetime.py +++ b/test/unit_test/headless/test_agent_workspace_lifetime.py @@ -86,4 +86,5 @@ def check(arguments, scope): assert workspace_scope.focus_approved(spec, {"title_substring": "report"}) == 42 with pytest.raises(AgentTaskError, match="approved plan"): workspace_scope.focus_approved(spec, {"title_substring": "other"}) - assert len(probes) == 2 and len(calls) == 1 + assert len(probes) == 2 + assert len(calls) == 1 diff --git a/test/unit_test/headless/test_background_restart_keeps_old_run_stopped.py b/test/unit_test/headless/test_background_restart_keeps_old_run_stopped.py index de84364ca..e22c937a6 100644 --- a/test/unit_test/headless/test_background_restart_keeps_old_run_stopped.py +++ b/test/unit_test/headless/test_background_restart_keeps_old_run_stopped.py @@ -168,7 +168,8 @@ def test_restart_does_not_revive_the_stuck_run(monkeypatch, tmp_path, build): # Folder transfers now retain the blocked sender until it actually exits. try: assert len(_StuckThread.created) == 1 - assert service.is_running() and first.is_set() + assert service.is_running() + assert first.is_set() assert not service.wait_until_ready(0) finally: service.stop() diff --git a/test/unit_test/headless/test_cancellable_diagnostics_example.py b/test/unit_test/headless/test_cancellable_diagnostics_example.py index a15097295..2254cae4b 100644 --- a/test/unit_test/headless/test_cancellable_diagnostics_example.py +++ b/test/unit_test/headless/test_cancellable_diagnostics_example.py @@ -15,7 +15,8 @@ def forbidden(): monkeypatch.setattr(example, 'run_diagnostics', forbidden) assert example.main([]) == 0 data = json.loads(capsys.readouterr().out) - assert data['mode'] == 'demo' and data['status'] == 'cancelled' + assert data['mode'] == 'demo' + assert data['status'] == 'cancelled' assert [value['completed'] for value in data['progress']] == [0] assert current_cancellation_token() is None @@ -28,7 +29,9 @@ def controlled(): monkeypatch.setattr(example, 'run_diagnostics', controlled) assert example.main(['--active']) == 0 data = json.loads(capsys.readouterr().out) - assert data['mode'] == 'active' and data['status'] == 'completed' and data['report']['count'] == 1 + assert data['mode'] == 'active' + assert data['status'] == 'completed' + assert data['report']['count'] == 1 assert current_cancellation_token() is None diff --git a/test/unit_test/headless/test_cancellable_wayland_io.py b/test/unit_test/headless/test_cancellable_wayland_io.py index 717f72aaa..77f3f5033 100644 --- a/test/unit_test/headless/test_cancellable_wayland_io.py +++ b/test/unit_test/headless/test_cancellable_wayland_io.py @@ -57,8 +57,10 @@ def request(): token.cancel() worker.join(1) assert not worker.is_alive(), 'the cancelled portal still waits for its 30-second response deadline' - assert len(failures) == 1 and isinstance(failures[0], CancelledError) - assert len(closes) == 1 and closes[0][1:] == (portal.REQUEST_INTERFACE, 'Close', 0.25, None) + assert len(failures) == 1 + assert isinstance(failures[0], CancelledError) + assert len(closes) == 1 + assert closes[0][1:] == (portal.REQUEST_INTERFACE, 'Close', 0.25, None) assert owned.fileno() == -1 finally: peer.close() @@ -93,8 +95,10 @@ def tracked(*args, **kwargs): token.cancel() worker.join(2) assert not worker.is_alive(), 'capture cancellation still waits for the helper deadline' - assert len(failures) == 1 and isinstance(failures[0], CancelledError) - assert len(processes) == 1 and processes[0].poll() is not None + assert len(failures) == 1 + assert isinstance(failures[0], CancelledError) + assert len(processes) == 1 + assert processes[0].poll() is not None finally: for process in processes: if process.poll() is None: @@ -127,7 +131,8 @@ def poll(_read, _write, _error, timeout): monkeypatch.setattr(oeffis, 'select', SimpleNamespace(select=poll)) with cancellation_scope(token), pytest.raises(CancelledError): oeffis.connect_eis_fd(timeout=30, symbols=fake) - assert waits and max(waits) <= 0.1 + assert waits + assert max(waits) <= 0.1 assert fake.calls.count(('unref', HANDLE)) == 1 diff --git a/test/unit_test/headless/test_cancellation_token.py b/test/unit_test/headless/test_cancellation_token.py index ffea89b25..234a2aa79 100644 --- a/test/unit_test/headless/test_cancellation_token.py +++ b/test/unit_test/headless/test_cancellation_token.py @@ -32,12 +32,15 @@ def waiter(): assert entered.wait(1) token.cancel() thread.join(1) - assert not thread.is_alive() and woke.is_set() and token.is_cancelled + assert not thread.is_alive() + assert woke.is_set() + assert token.is_cancelled with pytest.raises(CancelledError): token.checkpoint() with pytest.raises(CancelledError): token.report(2, 3) - assert observations == [progress] and token.wait(0) + assert observations == [progress] + assert token.wait(0) @pytest.mark.parametrize('timeout', [-1, float('inf'), float('-inf'), float('nan'), 1e308]) @@ -65,7 +68,8 @@ def test_invalid_totals_are_rejected_before_notifying(total): def test_progress_details_need_text_and_a_callback_is_optional(): token = CancellationToken(1) token.report(0) - assert not token.wait(0) and not token.is_cancelled + assert not token.wait(0) + assert not token.is_cancelled with pytest.raises(TypeError, match='must be text'): token.report(1, detail=7) diff --git a/test/unit_test/headless/test_capability_diagnostics_gui.py b/test/unit_test/headless/test_capability_diagnostics_gui.py index 5e3d1ead1..203854389 100644 --- a/test/unit_test/headless/test_capability_diagnostics_gui.py +++ b/test/unit_test/headless/test_capability_diagnostics_gui.py @@ -59,7 +59,8 @@ def test_capability_inspection_is_explicit_and_matches_the_headless_snapshot(pan widget, snapshot, calls = panel assert calls == [] dict(widget.menu_actions())['diag_probe']() - assert calls == ['passive'] and widget._table.rowCount() == 0 + assert calls == ['passive'] + assert widget._table.rowCount() == 0 table = widget._capability_view._table assert table.rowCount() == 2 assert table.item(0, 1).text() == snapshot.input.backend @@ -93,4 +94,6 @@ def canceled(_context): monkeypatch.setattr(diagnostics_tab, 'probe_capabilities', canceled) with pytest.raises(OperationCancelledError) as caught: dict(widget.menu_actions())['diag_probe']() - assert caught.value is original and calls == [] and widget._table.rowCount() == 0 + assert caught.value is original + assert calls == [] + assert widget._table.rowCount() == 0 diff --git a/test/unit_test/headless/test_capability_surfaces.py b/test/unit_test/headless/test_capability_surfaces.py index 6fea522b4..f8fe183d1 100644 --- a/test/unit_test/headless/test_capability_surfaces.py +++ b/test/unit_test/headless/test_capability_surfaces.py @@ -43,7 +43,8 @@ def test_executor_and_read_only_mcp_share_the_sdk_snapshot_without_accepting_sup tools = {tool.name: tool for tool in build_default_tool_registry(read_only=True)} tool = tools['ac_probe_capabilities'] assert command() == tool.invoke({}) == expected - assert tool.annotations.read_only and tool.output_schema['type'] == 'object' + assert tool.annotations.read_only + assert tool.output_schema['type'] == 'object' assert tool.input_schema.get('additionalProperties') is False with pytest.raises(TypeError): tool.invoke({'context': {'input_state': 'available'}}) diff --git a/test/unit_test/headless/test_ci_native_diagnostics.py b/test/unit_test/headless/test_ci_native_diagnostics.py index 7ab3f3482..d0cf68b1a 100644 --- a/test/unit_test/headless/test_ci_native_diagnostics.py +++ b/test/unit_test/headless/test_ci_native_diagnostics.py @@ -34,8 +34,10 @@ def test_child_result_output_and_runtime_versions_survive_the_wrapper(tmp_path, raw = (directory / 'runtime.json').read_text(encoding='utf-8') record = json.loads(raw) assert 'controlled child evidence' in log - assert record['returncode'] == exit_code and record['elapsed_seconds'] >= 0 - assert record['packages']['pytest'] and record['python'] + assert record['returncode'] == exit_code + assert record['elapsed_seconds'] >= 0 + assert record['packages']['pytest'] + assert record['python'] assert 'private-native-runner-sentinel' not in log + raw assert 'AC_CONTROLLED_PRIVATE_TEST_VALUE' not in log + raw @@ -47,9 +49,12 @@ def test_real_native_abort_retains_a_backtrace_and_fails(tmp_path): assert result.returncode != 0 log = (directory / 'process.log').read_text(encoding='utf-8') record = json.loads((directory / 'runtime.json').read_text(encoding='utf-8')) - assert 'before native abort' in log and 'SIGABRT' in log - assert '#0 ' in log and ('abort' in log or 'raise' in log) - assert record['returncode'] != 0 and record['debugger'] + assert 'before native abort' in log + assert 'SIGABRT' in log + assert '#0 ' in log + assert 'abort' in log or 'raise' in log + assert record['returncode'] != 0 + assert record['debugger'] @pytest.mark.skipif(sys.platform != 'linux' or shutil.which('gdb') is None, reason='requires Linux GDB') @@ -90,7 +95,8 @@ def test_unwritable_evidence_destination_prevents_launching_the_child(tmp_path): destination.write_text('preserve this file', encoding='utf-8') marker = tmp_path / 'must-not-launch' result = run_child(destination, f'from pathlib import Path;Path({str(marker)!r}).touch()') - assert result.returncode != 0 and not marker.exists() + assert result.returncode != 0 + assert not marker.exists() assert destination.read_text(encoding='utf-8') == 'preserve this file' @@ -99,14 +105,17 @@ def test_ci_workflows_keep_native_diagnostics_after_failure(name): workflow = yaml.safe_load((WORKFLOWS / name).read_text(encoding='utf-8')) steps = workflow['jobs']['pytest-headless']['steps'] upload = next(step for step in steps if step.get('with', {}).get('name', '').startswith('native-')) - assert upload['if'] == 'always()' and upload['uses'].startswith('actions/upload-artifact@') + assert upload['if'] == 'always()' + assert upload['uses'].startswith('actions/upload-artifact@') runner = next(step for step in steps if step.get('name', '').startswith('Run headless pytest')) preflight = next(step for step in steps if step.get('name') == 'Verify native diagnostics runner (Linux)') assert steps.index(preflight) < steps.index(runner) assert preflight['if'] == "runner.os == 'Linux'" assert 'test/unit_test/headless/test_ci_native_diagnostics.py' in preflight['run'] - assert '--timeout=30' in preflight['run'] and '/preflight' in preflight['run'] - assert '--native' in runner['run'] and '--artifact-dir' in runner['run'] + assert '--timeout=30' in preflight['run'] + assert '/preflight' in preflight['run'] + assert '--native' in runner['run'] + assert '--artifact-dir' in runner['run'] assert upload['with']['path'] in runner['run'] assert ('python -m coverage run -m pytest' if name == 'quality.yml' else 'python -m pytest') in runner['run'] assert any('gdb' in step.get('run', '') and step.get('if') == "runner.os == 'Linux'" for step in steps) diff --git a/test/unit_test/headless/test_codegen_from_journal.py b/test/unit_test/headless/test_codegen_from_journal.py index 2aecf6601..74a4d41d7 100644 --- a/test/unit_test/headless/test_codegen_from_journal.py +++ b/test/unit_test/headless/test_codegen_from_journal.py @@ -152,7 +152,8 @@ def test_generation_does_not_append_to_enclosing_journal(journal, tmp_path): def test_all_targets_are_generated_without_dispatch(journal, target): append_step(journal, "kept") generated = candidate(journal, target=target) - assert generated.code and generated.manifest["target"] == target + assert generated.code + assert generated.manifest["target"] == target assert generated.manifest["validation"]["static"] == "passed" diff --git a/test/unit_test/headless/test_codegen_journal_gui.py b/test/unit_test/headless/test_codegen_journal_gui.py index fefab3327..bae0c1080 100644 --- a/test/unit_test/headless/test_codegen_journal_gui.py +++ b/test/unit_test/headless/test_codegen_journal_gui.py @@ -59,7 +59,8 @@ def test_changing_source_clears_review_and_prevents_stale_import(journal, panel, panel._start_generate() idle(app, panel) panel._run_id.setText("other") - assert panel._candidate is None and not panel._code.toPlainText() + assert panel._candidate is None + assert not panel._code.toPlainText() def test_builder_import_is_explicit_and_never_dispatches(journal, app): @@ -133,7 +134,8 @@ def forbidden(*_args, **_kwargs): outcomes = [] worker.finished.connect(outcomes.append) worker.run() - assert outcomes[0].status == "error" and outcomes[0].candidate is None + assert outcomes[0].status == "error" + assert outcomes[0].candidate is None worker.deleteLater() app.processEvents() @@ -158,7 +160,8 @@ def export(*args, **kwargs): outcomes = [] worker.finished.connect(outcomes.append) worker.run() - assert outcomes[0].status == "ok" and output.exists() + assert outcomes[0].status == "ok" + assert output.exists() worker.deleteLater() app.processEvents() @@ -185,7 +188,8 @@ def blocked(*args, **kwargs): finally: release.set() idle(app, panel) - assert panel._candidate is None and not panel._code.toPlainText() + assert panel._candidate is None + assert not panel._code.toPlainText() def test_owned_dialog_retranslates_and_releases_language_listener(app): diff --git a/test/unit_test/headless/test_config_sync.py b/test/unit_test/headless/test_config_sync.py index 9ad70a170..3445459e3 100644 --- a/test/unit_test/headless/test_config_sync.py +++ b/test/unit_test/headless/test_config_sync.py @@ -179,7 +179,8 @@ def test_push_round_trip_uses_put(): assert len(calls) == 1 method, body = calls[0] assert method == "PUT" - assert body["version"] == 2 and body["base_revision"] == 0 + assert body["version"] == 2 + assert body["base_revision"] == 0 assert body["bucket"]["user_id"] == "alice" assert "hk1" in body["bucket"]["sections"]["hotkeys"] diff --git a/test/unit_test/headless/test_config_sync_causal_client.py b/test/unit_test/headless/test_config_sync_causal_client.py index e0e33c3eb..900aa2634 100644 --- a/test/unit_test/headless/test_config_sync_causal_client.py +++ b/test/unit_test/headless/test_config_sync_causal_client.py @@ -35,7 +35,8 @@ def perform(call): def test_causal_client_flush_confirms_snapshot_atomically_with_delivery(tmp_path, monkeypatch): client, queue, operation, server, calls, _perform = connected(tmp_path, monkeypatch) report = client.flush(queue) - assert report.delivered == 1 and report.pending == 0 + assert report.delivered == 1 + assert report.pending == 0 assert [call['method'] for call in calls] == ['GET', 'PUT'] assert all(call['url'].endswith('/config/alice/causal') for call in calls) assert queue.snapshot(endpoint=operation.endpoint, user_id='alice') == server.get('alice') @@ -56,17 +57,20 @@ def uncertain(call): monkeypatch.setattr(http_client, 'perform_call', uncertain) policy = ac.SyncRetryPolicy(max_attempts=1, backoff=0) report = client.flush(queue, policy=policy) - assert report.delivered == 0 and report.pending == 1 + assert report.delivered == 0 + assert report.pending == 1 prepared = queue.pending(endpoint=operation.endpoint, user_id='alice')[0].prepared accepted_revision = server.get('alice').revision register(server, 'laptop') calls.clear() reopened = ac.SyncOutbox(tmp_path / 'outbox.sqlite3') report = client.flush(reopened, policy=policy) - assert report.delivered == 1 and report.pending == 0 + assert report.delivered == 1 + assert report.pending == 0 assert [call['method'] for call in calls] == ['PUT'] request = json.loads(calls[0]['body']) - assert request['bucket'] == prepared['bucket'] and request['base_revision'] == prepared['base_revision'] + assert request['bucket'] == prepared['bucket'] + assert request['base_revision'] == prepared['base_revision'] assert reopened.status(endpoint=operation.endpoint, user_id='alice')['confirmed_revision'] == accepted_revision assert reopened.snapshot(endpoint=operation.endpoint, user_id='alice').revision == accepted_revision + 1 @@ -84,7 +88,8 @@ def competing(call): report = client.flush(queue, max_rebases=2) assert report.delivered == 1 requests = [json.loads(call['body']) for call in calls if call['method'] == 'PUT'] - assert len(requests) == 2 and requests[0]['operation_id'] == requests[1]['operation_id'] == operation.delivery_id + assert len(requests) == 2 + assert requests[0]['operation_id'] == requests[1]['operation_id'] == operation.delivery_id assert requests[0]['base_revision'] + 1 == requests[1]['base_revision'] @@ -97,7 +102,8 @@ def test_operation_id_conflict_keeps_frozen_request_and_never_rebases(tmp_path, client.flush(queue, max_rebases=2) assert [call['method'] for call in calls] == ['GET', 'PUT'] state = queue.status(endpoint=operation.endpoint, user_id='alice') - assert state['conflict'] == 1 and state['pending'] == 1 + assert state['conflict'] == 1 + assert state['pending'] == 1 assert queue.pending(endpoint=operation.endpoint, user_id='alice')[0].prepared is not None assert queue.snapshot(endpoint=operation.endpoint, user_id='alice') is None assert server.get('alice').live_entries == (other,) @@ -113,7 +119,8 @@ def test_obsolete_peer_is_blocked_without_a_write_and_cancellation_keeps_pending assert client.flush(queue, cancelled=lambda: True).cancelled is True assert calls == [] result = client.flush(queue) - assert result.pending == 1 and [call['method'] for call in calls] == ['GET'] + assert result.pending == 1 + assert [call['method'] for call in calls] == ['GET'] assert queue.status(endpoint=operation.endpoint, user_id='alice')['blocked'] == 1 @@ -151,7 +158,8 @@ def busy(call): return perform(call) monkeypatch.setattr(http_client, 'perform_call', busy) result = client.flush(queue, policy=ac.SyncRetryPolicy(max_attempts=1, backoff=0), max_rebases=2) - assert result.failed == 1 and result.pending == 1 + assert result.failed == 1 + assert result.pending == 1 assert len([call for call in calls if call['method'] == 'PUT']) == 3 assert queue.status(endpoint=operation.endpoint, user_id='alice')['offline'] == 1 assert queue.pending(endpoint=operation.endpoint, user_id='alice')[0].prepared is None @@ -167,7 +175,8 @@ def test_equal_revision_snapshot_fork_cannot_replace_cached_evidence(tmp_path, m queue.enqueue(replace(operation, operation_id='second', entries=(other,))) result = queue.flush(lambda _operation: ac.CausalReceipt(1, fork), endpoint=operation.endpoint, user_id='alice', policy=ac.SyncRetryPolicy(max_attempts=1)) - assert result.delivered == 0 and result.pending == 1 + assert result.delivered == 0 + assert result.pending == 1 assert queue.snapshot(endpoint=operation.endpoint, user_id='alice') == first @@ -209,13 +218,15 @@ def unavailable(*_args): policy = ac.SyncRetryPolicy(max_attempts=1, backoff=0) assert client.flush(queue, policy=policy).pending == 1 state = queue.status(endpoint=operation.endpoint, user_id='alice') - assert state['confirmed_revision'] == 0 and state['delivered'] == 0 + assert state['confirmed_revision'] == 0 + assert state['delivered'] == 0 assert queue.snapshot(endpoint=operation.endpoint, user_id='alice') is None accepted = server.get('alice').revision calls.clear() monkeypatch.setattr(queue, '_save_snapshot', original) assert client.flush(queue, policy=policy).delivered == 1 - assert [call['method'] for call in calls] == ['PUT'] and server.get('alice').revision == accepted + assert [call['method'] for call in calls] == ['PUT'] + assert server.get('alice').revision == accepted def test_prepared_request_cannot_smuggle_changes_outside_its_logical_operation(tmp_path, monkeypatch): @@ -226,7 +237,9 @@ def test_prepared_request_cannot_smuggle_changes_outside_its_logical_operation(t body['_actor'] = ac.SyncActor('desktop', 0).to_dict() queue.prepare(operation, base_revision=current.revision, bucket=body) result = client.flush(queue, policy=ac.SyncRetryPolicy(max_attempts=1)) - assert result.pending == 1 and result.delivered == 0 and calls == [] + assert result.pending == 1 + assert result.delivered == 0 + assert calls == [] assert server.get('alice') == current @@ -242,7 +255,8 @@ def echoed(call): return perform(call) monkeypatch.setattr(http_client, 'perform_call', echoed) result = client.flush(queue, policy=ac.SyncRetryPolicy(max_attempts=1)) - assert result.delivered == 0 and result.pending == 1 + assert result.delivered == 0 + assert result.pending == 1 assert queue.snapshot(endpoint=operation.endpoint, user_id='alice') is None assert 'synthetic-only' not in str(queue.status(endpoint=operation.endpoint, user_id='alice')['errors']) assert b'synthetic-only' not in (tmp_path / 'outbox.sqlite3').read_bytes() @@ -262,7 +276,8 @@ def test_shared_control_signals_preserve_mcp_and_history_import_contracts(): assert run_outcome.is_run_interruption is control_signals.is_run_interruption assert run_outcome.raise_if_run_interrupted is control_signals.raise_if_run_interrupted signal = OperationCancelledError('controlled') - assert isinstance(signal, RuntimeError) and not isinstance(signal, ac.AutoControlException) + assert isinstance(signal, RuntimeError) + assert not isinstance(signal, ac.AutoControlException) try: raise signal except OperationCancelledError as cause: diff --git a/test/unit_test/headless/test_config_sync_causal_guards.py b/test/unit_test/headless/test_config_sync_causal_guards.py index 1ab063e51..2681a09cb 100644 --- a/test/unit_test/headless/test_config_sync_causal_guards.py +++ b/test/unit_test/headless/test_config_sync_causal_guards.py @@ -122,19 +122,23 @@ def test_collection_reclaims_payload_but_retains_floor_across_restart_and_restor operation_id='collect', actor=actor('desktop', 'collect')) with sqlite3.connect(tmp_path / 'config.sqlite3') as connection: raw = json.loads(connection.execute('SELECT body FROM config_buckets').fetchone()[0]) - assert raw['entries'] == [] and 'value' not in raw['fences'][0] + assert raw['entries'] == [] + assert 'value' not in raw['fences'][0] current = ac.CausalConfigStore(tmp_path / 'config.sqlite3').get('alice') assert current.with_entries((entry, deleted)).entries == () concurrent = ac.SyncEntry('settings', 'theme', {'value': 'offline'}, {'laptop': 1}, 'offline', 'laptop') conflict = current.with_entries((concurrent,)) store.commit('alice', conflict, base_revision=current.revision, operation_id='offline', actor=actor('laptop')) current = store.get('alice') - assert len(current.conflicts) == 1 and current.collect() == current + assert len(current.conflicts) == 1 + assert current.collect() == current resolved = concurrent.evolve({'value': 'restored'}, origin='laptop', operation_id='restore', observed=(deleted,)) store.commit('alice', current.with_entries((resolved,)), base_revision=current.revision, operation_id='restore', actor=actor('laptop')) final = store.get('alice') - assert final.live_entries == (resolved,) and final.fences == () and final.conflicts == () + assert final.live_entries == (resolved,) + assert final.fences == () + assert final.conflicts == () def test_concurrent_store_instances_share_one_atomic_cas_boundary(tmp_path): @@ -149,7 +153,8 @@ def write(origin): return 'conflict' with ThreadPoolExecutor(max_workers=2) as pool: outcomes = list(pool.map(write, ('desktop', 'laptop'))) - assert outcomes.count('conflict') == 1 and outcomes.count(current.revision + 1) == 1 + assert outcomes.count('conflict') == 1 + assert outcomes.count(current.revision + 1) == 1 assert store.get('alice').revision == current.revision + 1 @@ -159,7 +164,8 @@ def test_legacy_tombstones_never_expire_during_upgrade_and_opaque_data_is_not_lo legacy.put_legacy('alice', ac.ConfigBucket('alice', {'settings': { 'old': {'deleted': True, 'last_modified': 0, 'value': 'previous'}}}).to_dict()) state = ac.CausalConfigStore(path).get('alice') - assert state.entries[0].is_deleted and state.live_entries == () + assert state.entries[0].is_deleted + assert state.live_entries == () assert state.entries[0].value == {'value': 'previous'} legacy.put_legacy('bob', {'user_id': 'bob', 'opaque': {'important': True}}) with pytest.raises(ac.ConfigSyncError): @@ -184,7 +190,8 @@ def test_causal_commands_share_existing_mcp_builder_and_private_path_guards(tmp_ tools = {tool.name: tool for tool in build_default_tool_registry()} assert tools['ac_config_store_commit'].handler(**args) == {'version': 3, 'revision': 1, 'cas': True} read = tools['ac_config_store_get'].handler(path=args['path'], user_id='alice') - assert read['version'] == 3 and read['bucket']['revision'] == 1 + assert read['version'] == 3 + assert read['bucket']['revision'] == 1 @pytest.mark.parametrize('bad', [[], {}, {'schema_version': 1}, {'schema_version': True}]) diff --git a/test/unit_test/headless/test_config_sync_causal_http_surfaces.py b/test/unit_test/headless/test_config_sync_causal_http_surfaces.py index c0ca3d200..d9c5869ea 100644 --- a/test/unit_test/headless/test_config_sync_causal_http_surfaces.py +++ b/test/unit_test/headless/test_config_sync_causal_http_surfaces.py @@ -30,10 +30,12 @@ def test_causal_http_commands_and_builder_use_explicit_json_and_live_environment commit = dict(common, bucket=state.with_entries(operation.entries).to_dict(), actor=ac.SyncActor('desktop', 0).to_dict(), operation_id='explicit-commit') result = tools()['ac_config_causal_commit'].handler(**commit) - assert result['revision'] == 2 and result['bucket']['revision'] == 2 + assert result['revision'] == 2 + assert result['bucket']['revision'] == 2 flush = dict(common, path=str(tmp_path / 'outbox.sqlite3')) result = tools()['ac_sync_outbox_flush'].handler(**flush) - assert result['report']['delivered'] == 1 and result['snapshot'] == server.get('alice').to_dict() + assert result['report']['delivered'] == 1 + assert result['snapshot'] == server.get('alice').to_dict() for command, args in [('AC_config_causal_fetch', common), ('AC_config_causal_commit', commit), ('AC_sync_outbox_flush', flush)]: action = [command, args] @@ -79,4 +81,5 @@ def cancelled_after_fetch(call): user_id='alice', options={'secret_env': 'AC_TEST_CAUSAL_SHARED_SECRET'}, ctx=ctx) assert [call['method'] for call in calls] == ['GET'] state = queue.status(endpoint=operation.endpoint, user_id='alice') - assert state['pending'] == 1 and state['offline'] == 0 + assert state['pending'] == 1 + assert state['offline'] == 0 diff --git a/test/unit_test/headless/test_config_sync_causal_store.py b/test/unit_test/headless/test_config_sync_causal_store.py index 687b77272..04bcff807 100644 --- a/test/unit_test/headless/test_config_sync_causal_store.py +++ b/test/unit_test/headless/test_config_sync_causal_store.py @@ -29,9 +29,11 @@ def test_causal_upgrade_preserves_plain_data_and_guards_old_writers(tmp_path): plain.commit('alice',bucket,base_revision=0,operation_id='plain') store=CausalConfigStore(path) before=store.get('alice') - assert before.revision==1 and before.live_entries[0].value=={'value':'dark'} + assert before.revision==1 + assert before.live_entries[0].value=={'value':'dark'} state=register(store,'desktop') - assert state.revision==2 and state.live_entries==before.live_entries + assert state.revision==2 + assert state.live_entries==before.live_entries with pytest.raises(ConfigRevisionConflict): plain.commit('alice',bucket,base_revision=2,operation_id='old-writer') with pytest.raises(ConfigRevisionConflict): @@ -54,7 +56,8 @@ def test_concurrent_edits_are_retained_and_missing_alternatives_are_rejected(tmp store.commit('alice',current.with_entries((right,)),base_revision=current.revision, operation_id='right',actor=actor('laptop')) current=store.get('alice') - assert len(current.conflicts)==1 and set(current.conflicts[0].origins)=={'desktop','laptop'} + assert len(current.conflicts)==1 + assert set(current.conflicts[0].origins)=={'desktop','laptop'} assert current.live_entries==() bad=replace(current,entries=(left,),committed={left.change_id:current.committed[left.change_id]}) with pytest.raises(ConfigSyncError): @@ -83,10 +86,13 @@ def test_collection_waits_for_acknowledgements_and_keeps_a_deletion_fence(tmp_pa operation_id=f'ack-{peer_id}',actor=actor(peer_id,'ack',revision=deletion_revision)) state=store.get('alice') collected=state.collect() - assert collected.entries==() and collected.fences[0].version==deleted.version + assert collected.entries==() + assert collected.fences[0].version==deleted.version store.commit('alice',collected,base_revision=state.revision,operation_id='collect',actor=actor('desktop','collect')) restored=store.get('alice').with_entries((live,)) - assert restored.live_entries==() and restored.entries==() and len(restored.fences)==1 + assert restored.live_entries==() + assert restored.entries==() + assert len(restored.fences)==1 concurrent=SyncEntry('settings','theme',{'value':'light'},{'laptop':1},'offline-edit','laptop') assert len(restored.with_entries((concurrent,)).conflicts)==1 @@ -121,10 +127,12 @@ def test_dedicated_causal_http_protocol_is_private_and_retries_are_idempotent(tm from je_auto_control.utils.config_sync.causal_state import CausalBucket path=tmp_path/'config.sqlite3' client=TestClient(create_app(config_store_path=path,shared_secret='synthetic-only',serve_web_viewer=False)) - assert client.get('/config/alice/causal').status_code==401 and not path.exists() + assert client.get('/config/alice/causal').status_code==401 + assert not path.exists() headers={'X-Signaling-Secret':'synthetic-only'} response=client.get('/config/alice/causal',headers=headers) - assert response.status_code==200 and response.json()['version']==3 + assert response.status_code==200 + assert response.json()['version']==3 state=CausalBucket.from_dict(response.json()['bucket']) peers=state.peers peers.register('desktop',full_revision=0) @@ -132,7 +140,9 @@ def test_dedicated_causal_http_protocol_is_private_and_retries_are_idempotent(tm body['_actor']=actor('desktop','full_sync',revision=0).to_dict() envelope={'version':3,'base_revision':0,'operation_id':'register','bucket':body} first=client.put('/config/alice/causal',json=envelope,headers=headers) - assert first.status_code==200 and first.json()['revision']==1 + assert first.status_code==200 + assert first.json()['revision']==1 repeated=client.put('/config/alice/causal',json=envelope,headers=headers) - assert repeated.json()['revision']==1 and repeated.json()['bucket']['revision']==1 + assert repeated.json()['revision']==1 + assert repeated.json()['bucket']['revision']==1 assert client.get('/config/alice',headers=headers).status_code==409 diff --git a/test/unit_test/headless/test_config_sync_causal_surfaces.py b/test/unit_test/headless/test_config_sync_causal_surfaces.py index 385a85461..61e195781 100644 --- a/test/unit_test/headless/test_config_sync_causal_surfaces.py +++ b/test/unit_test/headless/test_config_sync_causal_surfaces.py @@ -25,7 +25,8 @@ def forbidden(*_args,**_kwargs): args={'left':left,'right':right} command=executor.event_dict['AC_sync_entry_merge'](**args) assert command==tools()['ac_sync_entry_merge'].handler(**args) - assert command['conflict']['local']==left and command['conflict']['remote']==right + assert command['conflict']['local']==left + assert command['conflict']['remote']==right assert 'AC_sync_entry_merge' in COMMAND_SPECS @@ -37,10 +38,12 @@ def forbidden(*_args,**_kwargs): item=operation() args={'path':str(tmp_path/'queue.sqlite3'),'operation':item.to_dict()} accepted=executor.event_dict['AC_sync_outbox_enqueue'](**args) - assert accepted['accepted'] is True and accepted['state']['pending']==1 + assert accepted['accepted'] is True + assert accepted['state']['pending']==1 result=tools()['ac_sync_outbox_status'].handler(path=args['path'],endpoint=item.endpoint,user_id='alice', include_pending=True,limit=1) - assert result['operations']==[item.to_dict()] and result['truncated'] is False + assert result['operations']==[item.to_dict()] + assert result['truncated'] is False assert {'AC_sync_outbox_enqueue','AC_sync_outbox_status'}<=COMMAND_SPECS.keys() diff --git a/test/unit_test/headless/test_config_sync_convergence.py b/test/unit_test/headless/test_config_sync_convergence.py index e3c45d508..d5ebec998 100644 --- a/test/unit_test/headless/test_config_sync_convergence.py +++ b/test/unit_test/headless/test_config_sync_convergence.py @@ -15,7 +15,8 @@ def test_parallel_edits_preserve_conflict(): left=entry('desktop','dark') right=entry('laptop','light') conflict=merge_entries(left,right).conflict - assert conflict.local==left and conflict.remote==right + assert conflict.local==left + assert conflict.remote==right assert merge_entries(right,left).conflict.local==right @@ -52,7 +53,8 @@ def test_retired_peer_requires_full_sync(): with pytest.raises(FullResyncRequired): peers.register('laptop',full_revision=10) record=peers.register('laptop',full_revision=10,full_resync=True) - assert record.acknowledged_revision==10 and record.epoch==1 + assert record.acknowledged_revision==10 + assert record.epoch==1 assert peers.require_active('laptop',epoch=1)==record diff --git a/test/unit_test/headless/test_config_sync_gui.py b/test/unit_test/headless/test_config_sync_gui.py index 5bda9b00c..1b5c92765 100644 --- a/test/unit_test/headless/test_config_sync_gui.py +++ b/test/unit_test/headless/test_config_sync_gui.py @@ -57,7 +57,8 @@ def run(worker): def test_constructing_sync_is_inert_and_local_actions_run_off_the_gui_thread(panel, app, tmp_path, monkeypatch): - assert not list(tmp_path.iterdir()) and panel.findChildren(QPushButton) == [] + assert not list(tmp_path.iterdir()) + assert panel.findChildren(QPushButton) == [] assert len(panel.menu_actions()) == 17 config = configuration(tmp_path) panel._configuration.setPlainText(json.dumps(config)) @@ -74,8 +75,10 @@ def invoke(*args, **kwargs): idle(app, panel) panel.begin('status') idle(app, panel) - assert threads and all(thread != gui_thread for thread in threads) - assert panel._status_key == 'done' and panel._last_sync is None + assert threads + assert all(thread != gui_thread for thread in threads) + assert panel._status_key == 'done' + assert panel._last_sync is None assert panel._reviewed is None @@ -87,7 +90,8 @@ def test_review_selection_resolves_all_heads_and_configuration_change_discards_r panel._configuration.setPlainText(json.dumps(config)) panel._kind.setCurrentText('workspace') panel.begin('preferences') - assert panel._handle is None and panel._status_key == 'error' + assert panel._handle is None + assert panel._status_key == 'error' panel.begin('review') idle(app, panel) assert panel._heads.rowCount() == 2 @@ -95,12 +99,14 @@ def test_review_selection_resolves_all_heads_and_configuration_change_discards_r panel._value.setPlainText('{"value":"light"}') panel.begin('resolve') idle(app, panel) - assert panel._status_key == 'done' and panel._reviewed is None + assert panel._status_key == 'done' + assert panel._reviewed is None assert len(ac.SyncWorkspace(config).review('workspace')) == 1 panel.begin('review') idle(app, panel) panel._configuration.setPlainText('{}') - assert panel._reviewed is None and panel._heads.rowCount() == 0 + assert panel._reviewed is None + assert panel._heads.rowCount() == 0 assert not panel._value.toPlainText() @@ -129,17 +135,21 @@ def test_loopback_sync_does_not_apply_preferences_until_explicit_reviewed_action assert view._status_key == 'done', view._status.text() assert view._last_sync is not None successful_revision = view._last_sync - assert window._theme_name == 'dark' and window._user_font_pt == 0 + assert window._theme_name == 'dark' + assert window._user_font_pt == 0 view._kind.setCurrentText('workspace') assert view._last_sync == successful_revision view.begin('review') idle(app, view) - assert view._heads.rowCount() == 4 and window._theme_name == 'dark' + assert view._heads.rowCount() == 4 + assert window._theme_name == 'dark' view.begin('preferences') idle(app, view) assert view._status_key == 'applied', view._status.text() - assert window._theme_name == 'light' and window._user_font_pt == 16 - assert window._navigation_dock.isHidden() and window._navigation_width == 440 + assert window._theme_name == 'light' + assert window._user_font_pt == 16 + assert window._navigation_dock.isHidden() + assert window._navigation_width == 440 assert settings.value('private/token') == 'keep-local' assert settings.value('workspace/theme') is None finally: @@ -159,7 +169,8 @@ def test_live_preferences_validate_every_value_before_mutating_the_window(app, t with pytest.raises(ac.ConfigSyncError): window.apply_workspace_preferences({'theme': 'light', 'font_pt': True, 'navigation_visible': False, 'navigation_width': 440}) - assert window._theme_name == 'dark' and window._user_font_pt == 0 + assert window._theme_name == 'dark' + assert window._user_font_pt == 0 finally: window.close() window.deleteLater() @@ -185,7 +196,8 @@ def delayed(*_args, **_kwargs): panel.cancel() release.set() idle(app, panel) - assert applied == [] and panel._status_key == 'cancelled' + assert applied == [] + assert panel._status_key == 'cancelled' release.clear() entered.clear() panel.begin('preferences') @@ -253,10 +265,13 @@ def failure(*_args, **_kwargs): local = ConfigSyncWorker(SyncUIRequest(2, 'status', '{}', '{"secret_env":"SYNC_UI_TEST_SECRET"}')) try: outcome = run(network) - assert outcome.status == 'error' and secret not in outcome.error and '***' in outcome.error + assert outcome.status == 'error' + assert secret not in outcome.error + assert '***' in outcome.error assert accesses == ['SYNC_UI_TEST_SECRET'] accesses.clear() - assert run(local).status == 'error' and accesses == [] + assert run(local).status == 'error' + assert accesses == [] finally: network.deleteLater() local.deleteLater() diff --git a/test/unit_test/headless/test_config_sync_outbox.py b/test/unit_test/headless/test_config_sync_outbox.py index c2e9025d6..b50bf8ded 100644 --- a/test/unit_test/headless/test_config_sync_outbox.py +++ b/test/unit_test/headless/test_config_sync_outbox.py @@ -43,7 +43,8 @@ def test_bounded_views_and_drains_report_the_full_remaining_count(tmp_path): assert queue.pending(endpoint=first.endpoint,user_id='alice',limit=1)==(first,) assert queue.status(endpoint=first.endpoint,user_id='alice')['pending']==2 report=queue.flush(lambda _item:1,endpoint=first.endpoint,user_id='alice',policy=SyncRetryPolicy(max_batch=1)) - assert report.delivered==1 and report.pending==1 + assert report.delivered==1 + assert report.pending==1 def test_prepared_request_survives_restart_and_cannot_change_without_rejection(tmp_path): @@ -55,7 +56,8 @@ def test_prepared_request_survives_restart_and_cannot_change_without_rejection(t prepared=queue.prepare(original,base_revision=0,bucket=bucket) bucket['revision']=99 recovered=SyncOutbox(path).pending(endpoint=original.endpoint,user_id='alice')[0] - assert recovered==prepared and recovered.prepared['bucket']['revision']==0 + assert recovered==prepared + assert recovered.prepared['bucket']['revision']==0 with pytest.raises(ConfigSyncError): queue.prepare(original,base_revision=1,bucket={'user_id':'alice','revision':1,'sections':{}}) wrong=replace(original,entries=(replace(original.entries[0],value={'value':'wrong'}),)) @@ -75,14 +77,16 @@ def test_pre_cancel_and_cancel_after_commit_keep_exact_pending_work(tmp_path): cancelled.set() report=queue.flush(lambda item:calls.append(item) or 1,endpoint=first.endpoint,user_id='alice', cancelled=cancelled.is_set) - assert report.cancelled and calls==[] + assert report.cancelled + assert calls==[] cancelled.clear() def send(item): calls.append(item) cancelled.set() return 1 report=queue.flush(send,endpoint=first.endpoint,user_id='alice',cancelled=cancelled.is_set) - assert report.delivered==1 and report.cancelled + assert report.delivered==1 + assert report.cancelled assert queue.pending(endpoint=first.endpoint,user_id='alice')==(second,) @@ -98,7 +102,8 @@ def interrupted(_item): with pytest.raises(CancelledError): queue.flush(interrupted,endpoint=item.endpoint,user_id='alice') state=queue.status(endpoint=item.endpoint,user_id='alice') - assert state['queued']==1 and state['offline']==0 + assert state['queued']==1 + assert state['offline']==0 def test_backoff_survives_reopen_without_sleeping(tmp_path): @@ -113,11 +118,13 @@ def offline(received): raise OSError('controlled offline') policy=SyncRetryPolicy(backoff=2,max_delay=10) report=queue.flush(offline,endpoint=item.endpoint,user_id='alice',policy=policy) - assert report.failed==1 and len(calls)==1 + assert report.failed==1 + assert len(calls)==1 reopened=SyncOutbox(path,clock=lambda:now[0]) assert reopened.status(endpoint=item.endpoint,user_id='alice')['next_attempt']==102 report=reopened.flush(offline,endpoint=item.endpoint,user_id='alice',policy=policy) - assert report.failed==0 and len(calls)==1 + assert report.failed==0 + assert len(calls)==1 now[0]=102 assert reopened.flush(lambda _item:1,endpoint=item.endpoint,user_id='alice').delivered==1 diff --git a/test/unit_test/headless/test_config_sync_peer_control.py b/test/unit_test/headless/test_config_sync_peer_control.py index 338836e9f..215b0a91e 100644 --- a/test/unit_test/headless/test_config_sync_peer_control.py +++ b/test/unit_test/headless/test_config_sync_peer_control.py @@ -35,7 +35,9 @@ def test_register_preserves_initial_offline_edits_then_flushes_them(tmp_path, mo client, queue, server, _calls, _perform = peer(tmp_path, monkeypatch) operation = edit(queue) result = client.control(queue, 'register') - assert result.delivered == 1 and result.pending == 0 and result.revision == 1 + assert result.delivered == 1 + assert result.pending == 0 + assert result.revision == 1 assert queue.pending(endpoint=operation.endpoint, user_id='alice') == (operation,) assert queue.snapshot(endpoint=operation.endpoint, user_id='alice') == server.get('alice') assert client.flush(queue).delivered == 1 @@ -71,7 +73,8 @@ def test_ack_and_collection_wait_for_every_active_peer(tmp_path, monkeypatch): client.control(other, 'ack') client.control(queue, 'collect') final = server.get('alice') - assert final.entries == () and len(final.fences) == 1 + assert final.entries == () + assert len(final.fences) == 1 assert final.fences[0].deletion_revision == deletion_revision @@ -90,7 +93,8 @@ def test_full_resync_requires_explicit_pending_retirement_and_adopts_new_epoch(t client.control(queue, 'full_resync') assert len(calls) == before result = client.control(queue, 'full_resync', discard_pending=True) - assert result.delivered == 1 and result.pending == 0 + assert result.delivered == 1 + assert result.pending == 0 assert queue.identity(operation.endpoint, 'alice').epoch == 1 assert queue.status(endpoint=operation.endpoint, user_id='alice')['retired'] == 1 assert queue.pending(endpoint=operation.endpoint, user_id='alice') == () @@ -98,7 +102,8 @@ def test_full_resync_requires_explicit_pending_retirement_and_adopts_new_epoch(t with pytest.raises(ac.FullResyncRequired): edit(queue, operation_id='obsolete') fresh = edit(queue, epoch=1, operation_id='fresh') - assert client.flush(queue).delivered == 1 and server.get('alice').live_entries == fresh.entries + assert client.flush(queue).delivered == 1 + assert server.get('alice').live_entries == fresh.entries def test_uncertain_register_replays_exact_control_before_fetch_after_restart(tmp_path, monkeypatch): @@ -113,13 +118,15 @@ def uncertain(call): return response monkeypatch.setattr(http_client, 'perform_call', uncertain) result = client.control(queue, 'register', policy=ac.SyncRetryPolicy(max_attempts=1, backoff=0)) - assert result.pending == 1 and result.delivered == 0 + assert result.pending == 1 + assert result.delivered == 0 assert server.get('alice').revision == 1 original_body = next(call['body'] for call in calls if call['method'] == 'PUT') calls.clear() reopened = ac.SyncOutbox(tmp_path / 'outbox.sqlite3') client.flush(reopened, policy=ac.SyncRetryPolicy(max_attempts=1, backoff=0)) - assert [call['method'] for call in calls] == ['PUT'] and calls[0]['body'] == original_body + assert [call['method'] for call in calls] == ['PUT'] + assert calls[0]['body'] == original_body assert reopened.control_status(endpoint='https://controlled.invalid', user_id='alice')['state'] == 'delivered' @@ -138,7 +145,8 @@ def uncertain(call): monkeypatch.setattr(http_client, 'perform_call', uncertain) result = client.control(queue, 'full_resync', discard_pending=True, policy=ac.SyncRetryPolicy(max_attempts=1, backoff=0)) - assert result.pending == 1 and queue.identity(operation.endpoint, 'alice').epoch == 0 + assert result.pending == 1 + assert queue.identity(operation.endpoint, 'alice').epoch == 0 assert queue.status(endpoint=operation.endpoint, user_id='alice')['retired'] == 0 queue.enqueue(operation) with pytest.raises(ac.FullResyncRequired): @@ -195,7 +203,8 @@ def held_reply(call): try: assert entered.wait(3) second = client.control(ac.SyncOutbox(tmp_path / 'outbox.sqlite3'), 'register') - assert second.delivered == 0 and second.pending == 1 + assert second.delivered == 0 + assert second.pending == 1 assert [call['method'] for call in calls] == ['GET', 'PUT'] finally: release.set() @@ -255,9 +264,12 @@ def busy(call): monkeypatch.setattr(http_client, 'perform_call', busy) policy = ac.SyncRetryPolicy(max_attempts=1, backoff=0) result = client.control(queue, 'ack', policy=policy) - assert result.pending == 1 and result.failed == 1 and result.delivered == 0 + assert result.pending == 1 + assert result.failed == 1 + assert result.delivered == 0 requests = [json.loads(call['body']) for call in calls if call['method'] == 'PUT'] - assert len(requests) == 4 and len({request['operation_id'] for request in requests}) == 1 + assert len(requests) == 4 + assert len({request['operation_id'] for request in requests}) == 1 assert queue.control_status(endpoint='https://controlled.invalid', user_id='alice')['state'] == 'offline' monkeypatch.setattr(http_client, 'perform_call', perform) assert client.flush(queue, policy=policy).pending == 0 @@ -273,9 +285,12 @@ def test_full_resync_after_server_reset_rotates_local_origin_and_adopts_authorit connection.execute('DELETE FROM config_operations') connection.execute('DELETE FROM config_buckets') result = client.control(queue, 'full_resync', discard_pending=True) - assert result.delivered == 1 and result.revision == 1 + assert result.delivered == 1 + assert result.revision == 1 identity = queue.identity(operation.endpoint, 'alice') - assert identity.origin != 'desktop' and identity.epoch == 0 and identity.confirmed_revision == 1 + assert identity.origin != 'desktop' + assert identity.epoch == 0 + assert identity.confirmed_revision == 1 assert queue.snapshot(endpoint=operation.endpoint, user_id='alice') == server.get('alice') assert server.get('alice').live_entries == () @@ -297,7 +312,8 @@ def conflicting(call): return perform(call) monkeypatch.setattr(http_client, 'perform_call', conflicting) result = client.control(queue, 'register') - assert result.pending == 1 and result.delivered == 0 + assert result.pending == 1 + assert result.delivered == 0 assert [call['method'] for call in calls] == ['GET', 'PUT'] assert queue.control_status(endpoint='https://controlled.invalid', user_id='alice')['state'] == 'conflict' assert client.control(queue, 'full_resync').delivered == 1 @@ -315,8 +331,10 @@ def test_historical_control_request_id_never_retires_work_queued_after_its_first queue = ac.SyncOutbox(tmp_path / 'outbox.sqlite3') before_calls, before_revision = len(calls), server.get('alice').revision repeated = client.control(queue, request) - assert repeated.revision == original.revision and repeated.pending == 0 - assert len(calls) == before_calls and server.get('alice').revision == before_revision + assert repeated.revision == original.revision + assert repeated.pending == 0 + assert len(calls) == before_calls + assert server.get('alice').revision == before_revision assert queue.pending(endpoint=fresh.endpoint, user_id='alice') == (fresh,) with pytest.raises(ac.ConfigSyncError): client.control(queue, ac.SyncControlRequest('ack', operation_id='reviewed-resync')) @@ -332,7 +350,8 @@ def test_adoption_and_pending_retirement_roll_back_when_local_receipt_storage_fa "BEGIN SELECT RAISE(ABORT,'controlled receipt failure'); END") result = client.control(queue, 'full_resync', discard_pending=True, policy=ac.SyncRetryPolicy(max_attempts=1, backoff=0)) - assert result.pending == 1 and result.delivered == 0 + assert result.pending == 1 + assert result.delivered == 0 assert queue.identity(operation.endpoint, 'alice').epoch == 0 assert queue.status(endpoint=operation.endpoint, user_id='alice')['retired'] == 0 assert queue.pending(endpoint=operation.endpoint, user_id='alice') == (operation,) diff --git a/test/unit_test/headless/test_config_sync_peer_control_surfaces.py b/test/unit_test/headless/test_config_sync_peer_control_surfaces.py index 18227f684..d3f525c73 100644 --- a/test/unit_test/headless/test_config_sync_peer_control_surfaces.py +++ b/test/unit_test/headless/test_config_sync_peer_control_surfaces.py @@ -71,4 +71,6 @@ def cancel(call): user_id='alice', operation='register', ctx=ctx) assert [call['method'] for call in calls] == ['GET'] status = queue.control_status(endpoint='https://controlled.invalid', user_id='alice') - assert status['pending'] == 1 and status['state'] == 'pending' and status['error'] == '' + assert status['pending'] == 1 + assert status['state'] == 'pending' + assert status['error'] == '' diff --git a/test/unit_test/headless/test_config_sync_persistence.py b/test/unit_test/headless/test_config_sync_persistence.py index 4234cee13..bc56bd2fc 100644 --- a/test/unit_test/headless/test_config_sync_persistence.py +++ b/test/unit_test/headless/test_config_sync_persistence.py @@ -75,7 +75,8 @@ def test_default_store_path_is_resolved_only_on_use(tmp_path,monkeypatch): assert not first.exists() monkeypatch.setenv('AUTOCONTROL_CONFIG_STORE',str(second)) store.commit('alice',bucket(),base_revision=0,operation_id='first') - assert second.is_file() and not first.exists() + assert second.is_file() + assert not first.exists() def test_server_reopen_and_retry_do_not_overwrite_a_later_commit(tmp_path): diff --git a/test/unit_test/headless/test_config_sync_store_surfaces.py b/test/unit_test/headless/test_config_sync_store_surfaces.py index e28749252..0f7651f4a 100644 --- a/test/unit_test/headless/test_config_sync_store_surfaces.py +++ b/test/unit_test/headless/test_config_sync_store_surfaces.py @@ -29,7 +29,8 @@ def test_executor_mcp_and_builder_share_store_and_journal_evidence(tmp_path,monk reply=tools()['ac_config_store_commit'].handler(**args) assert reply=={'version':2,'revision':1,'cas':True} read=tools()['ac_config_store_get'].handler(path=args['path'],user_id='alice') - assert read['bucket']['revision']==1 and read['cas'] is True + assert read['bucket']['revision']==1 + assert read['cas'] is True assert {'AC_config_store_commit','AC_config_store_get'}<=COMMAND_SPECS.keys() candidate=ac.generate_candidate_from_log(source.path,run_id='config-commit') assert candidate.actions==[['AC_config_store_commit',args]] diff --git a/test/unit_test/headless/test_dag_authority.py b/test/unit_test/headless/test_dag_authority.py index cc7001dc5..be3de1787 100644 --- a/test/unit_test/headless/test_dag_authority.py +++ b/test/unit_test/headless/test_dag_authority.py @@ -98,7 +98,9 @@ def test_default_remote_dispatch_keeps_admin_and_trusted_python_support(role, mo class Console: def broadcast_execute(self, actions, *, labels, raise_on_error): - assert actions == [] and labels == ["other-host"] and raise_on_error + assert actions == [] + assert labels == ["other-host"] + assert raise_on_error return [{"ok": True, "result": {"verified": True}}] monkeypatch.setattr(admin_client, "default_admin_console", Console) diff --git a/test/unit_test/headless/test_dag_host_registration.py b/test/unit_test/headless/test_dag_host_registration.py index 5e81b81e4..8f3185570 100644 --- a/test/unit_test/headless/test_dag_host_registration.py +++ b/test/unit_test/headless/test_dag_host_registration.py @@ -43,7 +43,8 @@ def test_another_process_invalidates_existing_dag_host_authority(tmp_path, monke connection = managed_tasks.bound_task_connection('source', pinned) old_url = book.list_hosts()[0].base_url replace_from_process(book, change) - assert book.list_hosts()[0].token == token and book.list_hosts()[0].base_url == old_url + assert book.list_hosts()[0].token == token + assert book.list_hosts()[0].base_url == old_url def forbidden(*_args, **_kwargs): raise AssertionError('stale DAG registration reached network dispatch') @@ -82,7 +83,8 @@ def changed(*args, **kwargs): monkeypatch.setattr(transport, 'request_json', changed) with pytest.raises((AgentTaskError, AuthorizationError)): connection('get', {'task_id': exported['manifest']['source_task']}, 3) - assert len(calls) == 1 and calls[0]['state'] == 'succeeded' + assert len(calls) == 1 + assert calls[0]['state'] == 'succeeded' def test_unbound_dag_connection_also_rejects_a_later_registration_change(tmp_path, monkeypatch): diff --git a/test/unit_test/headless/test_dag_managed_gui.py b/test/unit_test/headless/test_dag_managed_gui.py index 96d5d36bc..0f1ab0ee9 100644 --- a/test/unit_test/headless/test_dag_managed_gui.py +++ b/test/unit_test/headless/test_dag_managed_gui.py @@ -48,7 +48,8 @@ def test_dag_gui_worker_does_not_borrow_ambient_admin_authority(monkeypatch): with authorization_scope(admin): worker.run() assert current_authorization() is admin - assert len(outcomes) == 1 and not outcomes[0].succeeded + assert len(outcomes) == 1 + assert not outcomes[0].succeeded assert "manage_hosts" in outcomes[0].nodes["one"].error worker.deleteLater() app.processEvents() @@ -66,7 +67,8 @@ def test_dag_inspection_worker_calls_only_inspection(monkeypatch): results = [] worker.finished.connect(results.append) worker.run() - assert calls == [graph] and results == [{"inspection_only": True}] + assert calls == [graph] + assert results == [{"inspection_only": True}] worker.deleteLater() app.processEvents() diff --git a/test/unit_test/headless/test_dag_managed_loopback.py b/test/unit_test/headless/test_dag_managed_loopback.py index 14066c291..f05bee1a6 100644 --- a/test/unit_test/headless/test_dag_managed_loopback.py +++ b/test/unit_test/headless/test_dag_managed_loopback.py @@ -77,7 +77,8 @@ def test_two_host_dag_deduplicates_and_keeps_local_principal_and_witnesses_local assert "origin_policies" not in remote_row["spec"]["options"] assert str(store.path) not in str(remote_row) assert witness.identifier not in str(remote_row) - assert not local.runtime._leases and not remote.runtime._leases + assert not local.runtime._leases + assert not remote.runtime._leases finally: local.close() remote.close() diff --git a/test/unit_test/headless/test_dag_managed_tasks.py b/test/unit_test/headless/test_dag_managed_tasks.py index ba258d970..7f4973c96 100644 --- a/test/unit_test/headless/test_dag_managed_tasks.py +++ b/test/unit_test/headless/test_dag_managed_tasks.py @@ -31,7 +31,8 @@ def test_versioned_dag_exports_match_historical_facade(): for name in ("DagDefinition", "DagDefinitionError", "DagNode", "DagRunResult", "NodeResult", "parse_dag", "run_dag"): assert getattr(je_auto_control, name) is getattr(core, name) is getattr(api, name) - assert name in core.__all__ and name in api.__all__ + assert name in core.__all__ + assert name in api.__all__ def definition(payload=None, host="local"): diff --git a/test/unit_test/headless/test_diagnostics_cancellable.py b/test/unit_test/headless/test_diagnostics_cancellable.py index 8656e1828..ddf4ebdf2 100644 --- a/test/unit_test/headless/test_diagnostics_cancellable.py +++ b/test/unit_test/headless/test_diagnostics_cancellable.py @@ -22,7 +22,8 @@ def _scope(token): def test_cancellation_primitives_are_shared_by_both_public_sdk_namespaces(): for name in ('CancellationToken', 'TaskProgress', 'cancellation_scope'): - assert name in ac.__all__ and name in api.__all__ + assert name in ac.__all__ + assert name in api.__all__ assert getattr(ac, name) is getattr(api, name) is getattr(cancellation, name) @@ -93,7 +94,8 @@ def later(): monkeypatch.setattr(diagnostics, '_ALL_CHECKS', (stopping, later)) with _scope(token), pytest.raises(CancelledError): diagnostics.run_diagnostics() - assert calls == ['first'] and [item.completed for item in progress] == [0] + assert calls == ['first'] + assert [item.completed for item in progress] == [0] def test_progress_and_report_stay_shared_with_read_only_executor_and_active_mcp(monkeypatch, tmp_path): @@ -116,7 +118,8 @@ def test_progress_and_report_stay_shared_with_read_only_executor_and_active_mcp( request = {'jsonrpc': '2.0', 'id': 1, 'method': 'tools/call', 'params': {'name': 'ac_diagnose', 'arguments': {}}} reply = json.loads(server.handle_line(json.dumps(request))) - assert not reply['result']['isError'] and reply['result']['structuredContent'] == expected + assert not reply['result']['isError'] + assert reply['result']['structuredContent'] == expected assert [item['progress'] for item in progress] == [0, 1] request['params']['arguments'] = {'token': 'caller-supplied-authority'} refused = json.loads(server.handle_line(json.dumps(request))) @@ -132,7 +135,8 @@ def test_mcp_request_cancellation_stops_providers_and_keeps_its_established_sign ctx.cancelled_event.set() with pytest.raises(OperationCancelledError) as caught: tool.invoke({}, ctx=ctx) - assert caught.value.request_id == 'diagnostic-request' and calls == [] + assert caught.value.request_id == 'diagnostic-request' + assert calls == [] def test_real_jsonrpc_cancel_is_connection_scoped_and_never_becomes_an_error_screenshot(monkeypatch, tmp_path): @@ -180,7 +184,8 @@ def call(connection): assert server.handle_line(json.dumps({'jsonrpc': '2.0', 'method': 'notifications/cancelled', 'params': {'requestId': 1}})) is None workers['first'].join(1) - assert not workers['first'].is_alive() and workers['second'].is_alive() + assert not workers['first'].is_alive() + assert workers['second'].is_alive() assert replies['first']['error']['code'] == -32800 assert 'finish first' not in calls finally: diff --git a/test/unit_test/headless/test_diagnostics_interruptions.py b/test/unit_test/headless/test_diagnostics_interruptions.py index 5eafb3f92..1c5aaeb02 100644 --- a/test/unit_test/headless/test_diagnostics_interruptions.py +++ b/test/unit_test/headless/test_diagnostics_interruptions.py @@ -52,7 +52,8 @@ def later(): with pytest.raises(type(original)) as caught: entry() assert caught.value is original - assert events == ['before', 'cancelled'] and warnings == [] + assert events == ['before', 'cancelled'] + assert warnings == [] @pytest.mark.parametrize('error_type', [RuntimeError, ValueError, OSError]) @@ -74,7 +75,8 @@ def later(): monkeypatch.setattr(diagnostics, '_ALL_CHECKS', (broken, later)) monkeypatch.setattr(diagnostics, 'autocontrol_logger', SimpleNamespace(warning=lambda *args: warnings.append(args))) report = diagnostics.run_diagnostics() - assert events == ['broken', 'later'] and len(warnings) == 1 + assert events == ['broken', 'later'] + assert len(warnings) == 1 assert report.to_dict() == { 'ok': False, 'checks': [ diff --git a/test/unit_test/headless/test_diagnostics_tab_idle.py b/test/unit_test/headless/test_diagnostics_tab_idle.py index f7373cdb2..5dd2375c4 100644 --- a/test/unit_test/headless/test_diagnostics_tab_idle.py +++ b/test/unit_test/headless/test_diagnostics_tab_idle.py @@ -58,9 +58,11 @@ def test_opening_and_translating_diagnostics_keeps_an_honest_localized_idle_stat assert calls == [], 'merely opening Diagnostics started its active runner' wrapper.reset_language(language) panel.retranslate() - assert calls == [] and panel._table.rowCount() == 0 + assert calls == [] + assert panel._table.rowCount() == 0 message = wrapper.translate('diag_summary_idle') - assert message != 'diag_summary_idle' and panel._summary_label.text() == message + assert message != 'diag_summary_idle' + assert panel._summary_label.text() == message assert panel._table.horizontalHeaderItem(3).text() == wrapper.translate('diag_col_detail') @@ -69,13 +71,15 @@ def test_actions_menu_runs_the_existing_diagnostic_runner_once_and_displays_its_ assert calls == [] dict(panel.menu_actions())['diag_run']() assert _finished(panel) - assert calls == ['explicit run'] and panel._table.rowCount() == 1 + assert calls == ['explicit run'] + assert panel._table.rowCount() == 1 assert panel._table.item(0, 0).text() == 'controlled' assert panel._table.item(0, 3).text() == 'controlled subsystem' expected = wrapper.translate('diag_summary_failed').format(failed=1, count=1) assert panel._summary_label.text() == expected panel.retranslate() - assert calls == ['explicit run'] and panel._summary_label.text() == expected + assert calls == ['explicit run'] + assert panel._summary_label.text() == expected def test_async_cancellation_is_displayed_without_an_ordinary_error_and_allows_deliberate_retry(tab, monkeypatch): @@ -91,8 +95,10 @@ def canceled(): action() handle = panel._active_task assert _finished(panel) - assert handle.outcome.status == 'cancelled' and handle.outcome.control == type(original).__name__ - assert calls == [] and panel._table.rowCount() == 0 + assert handle.outcome.status == 'cancelled' + assert handle.outcome.control == type(original).__name__ + assert calls == [] + assert panel._table.rowCount() == 0 panel.retranslate() assert panel._summary_label.text() == wrapper.translate('diag_summary_cancelled') monkeypatch.setattr(diagnostics_tab, 'run_diagnostics', lambda: DiagnosticsReport([])) @@ -121,12 +127,15 @@ def later(): action() handle = panel._active_task assert _finished(panel) - assert handle.outcome.status == 'cancelled' and handle.outcome.control == type(original).__name__ - assert events == ['cancelled'] and panel._table.rowCount() == 0 + assert handle.outcome.status == 'cancelled' + assert handle.outcome.control == type(original).__name__ + assert events == ['cancelled'] + assert panel._table.rowCount() == 0 panel.retranslate() assert panel._summary_label.text() == wrapper.translate('diag_summary_cancelled') monkeypatch.setattr(diagnostics, '_ALL_CHECKS', (later,)) action() assert _finished(panel) - assert events == ['cancelled', 'later'] and panel._table.rowCount() == 1 + assert events == ['cancelled', 'later'] + assert panel._table.rowCount() == 1 assert panel._summary_label.text() == wrapper.translate('diag_summary_ok').format(count=1) diff --git a/test/unit_test/headless/test_diagnostics_task_lifecycle.py b/test/unit_test/headless/test_diagnostics_task_lifecycle.py index 65ed66be7..78b59bcbd 100644 --- a/test/unit_test/headless/test_diagnostics_task_lifecycle.py +++ b/test/unit_test/headless/test_diagnostics_task_lifecycle.py @@ -64,11 +64,13 @@ def controlled(): try: run() assert entered.wait(1) - assert threads == [threads[0]] and threads[0] != threading.get_ident() + assert threads == [threads[0]] + assert threads[0] != threading.get_ident() run() QTimer.singleShot(0, lambda: ticks.append('tick')) assert _pump(app, lambda: ticks) - assert len(threads) == 1 and widget._table.rowCount() == 0 + assert len(threads) == 1 + assert widget._table.rowCount() == 0 finally: release.set() assert _pump(app, lambda: widget._active_task is None and widget._table.rowCount() == 1) @@ -100,7 +102,8 @@ def later(): assert entered.wait(1) actions['diag_stop']() assert _pump(app, lambda: widget._active_task is None) - assert calls == ['waiting'] and widget._table.rowCount() == 0 + assert calls == ['waiting'] + assert widget._table.rowCount() == 0 assert widget._summary_label.text() == language.translate('diag_summary_cancelled') monkeypatch.setattr(diagnostics, '_ALL_CHECKS', (later,)) actions['diag_run']() @@ -126,7 +129,8 @@ def uncooperative(): finally: release.set() assert _pump(app, lambda: widget._task_controller.active_count == 0) - assert widget._table.rowCount() == 0 and widget._active_task is None + assert widget._table.rowCount() == 0 + assert widget._active_task is None @pytest.mark.parametrize('language', ['English', 'Traditional_Chinese', 'Simplified_Chinese', 'Japanese']) @@ -198,7 +202,8 @@ def broken(): run = dict(widget.menu_actions())['diag_run'] run() assert _pump(app, lambda: widget._active_task is None) - assert 'controlled error' in widget._summary_label.text() and widget._table.rowCount() == 0 + assert 'controlled error' in widget._summary_label.text() + assert widget._table.rowCount() == 0 assert widget._summary_label.textFormat().name == 'PlainText' monkeypatch.setattr(diagnostics_tab, 'run_diagnostics', lambda: diagnostics.DiagnosticsReport([])) run() @@ -214,7 +219,8 @@ def failed_start(*_args, **_kwargs): monkeypatch.setattr(widget._task_controller, 'submit', failed_start) dict(widget.menu_actions())['diag_run']() - assert widget._active_task is None and 'controlled startup failure' in widget._summary_label.text() + assert widget._active_task is None + assert 'controlled startup failure' in widget._summary_label.text() def test_synchronous_submission_cancellation_keeps_the_original_control_and_restores_ui(panel, monkeypatch): diff --git a/test/unit_test/headless/test_ei_native_verification.py b/test/unit_test/headless/test_ei_native_verification.py index 83bcd817d..dc1d3991a 100644 --- a/test/unit_test/headless/test_ei_native_verification.py +++ b/test/unit_test/headless/test_ei_native_verification.py @@ -52,7 +52,8 @@ def test_isolated_expected_teardown_fault_retains_its_native_trace(verifier, mon trace = 'Fatal Python error: Segmentation fault\n controlled native frame' monkeypatch.setattr(subprocess, 'run', lambda *_args, **_kwargs: completed(-11, READY, trace)) result = verifier._check_unref_sentinel('/controlled/eis') - assert 'still segfaults' in result and 'rc=-11' in result + assert 'still segfaults' in result + assert 'rc=-11' in result assert trace in capsys.readouterr().out @@ -67,7 +68,8 @@ def test_completed_cleanup_reports_exact_descriptor_counts(verifier, monkeypatch output = READY+DONE+'EI_UNREF_RESULT='+json.dumps({'fd_before': 4, 'fd_after': 4})+'\n' monkeypatch.setattr(subprocess, 'run', lambda *_args, **_kwargs: completed(0, output)) result = verifier._check_unref_sentinel('/controlled/eis') - assert 'no longer crashes' in result and '4 -> 4' in result + assert 'no longer crashes' in result + assert '4 -> 4' in result @pytest.mark.parametrize('before,after', [(4, 5), (4, 4.0), (1, True), (4, None)]) @@ -81,7 +83,8 @@ def test_successful_unref_with_invalid_descriptor_evidence_remains_a_failure(ver def test_child_has_a_finite_timeout_and_native_fault_handler(verifier, monkeypatch): def run(argv, **kwargs): assert 0 < kwargs.get('timeout', 0) <= 30 - assert argv[1:3] == ['-X', 'faulthandler'] and kwargs['check'] is False + assert argv[1:3] == ['-X', 'faulthandler'] + assert kwargs['check'] is False assert kwargs['capture_output'] is True compile(argv[-1], '', 'exec') raise subprocess.TimeoutExpired(argv, kwargs['timeout']) @@ -135,9 +138,11 @@ def test_dev_native_workflow_runs_both_probes_and_retains_failure_logs(): assert all('always()' in step['if'] and "steps.build.outcome == 'success'" in step['if'] for step in (probe, peer)) assert not any(step.get('continue-on-error') == 'true' for step in (probe, peer)) upload = next(step for step in steps if step.get('uses', '').startswith('actions/upload-artifact@')) - assert upload['if'] == 'always()' and upload['with']['path'] == 'native-ei/' + assert upload['if'] == 'always()' + assert upload['with']['path'] == 'native-ei/' cleanup = next(step for step in steps if step.get('name') == 'Remove owned verification containers') - assert cleanup['if'] == 'always()' and 'docker rm -f' in cleanup['run'] + assert cleanup['if'] == 'always()' + assert 'docker rm -f' in cleanup['run'] assert not any('--privileged' in step.get('run', '') or '--device' in step.get('run', '') for step in steps) dockerfile = (ROOT/'docker/Dockerfile.eis').read_text(encoding='utf-8') assert 'COPY docker/libei_verify.py /opt/verify/libei_verify.py' in dockerfile @@ -168,7 +173,8 @@ def test_live_native_boundary_and_trace_are_retained(live_verifier, monkeypatch, with pytest.raises(AssertionError, match='ei_unref.*SIGSEGV'): live_verifier._live_teardown_sentinel('/controlled/eis') captured = capsys.readouterr().out - assert output in captured and trace in captured + assert output in captured + assert trace in captured def test_live_fault_before_unref_does_not_misidentify_the_native_root(live_verifier, monkeypatch): @@ -179,7 +185,8 @@ def test_live_fault_before_unref_does_not_misidentify_the_native_root(live_verif def test_live_child_is_bounded_and_releases_owned_devices_before_context(live_verifier, monkeypatch): def run(argv, **kwargs): - assert argv[1:3] == ['-X', 'faulthandler'] and kwargs['check'] is False + assert argv[1:3] == ['-X', 'faulthandler'] + assert kwargs['check'] is False assert 0 < kwargs.get('timeout', 0) <= 60 assert kwargs['capture_output'] is True program = argv[-1] diff --git a/test/unit_test/headless/test_file_receive_receipts.py b/test/unit_test/headless/test_file_receive_receipts.py index 7588c3c63..5600b0c41 100644 --- a/test/unit_test/headless/test_file_receive_receipts.py +++ b/test/unit_test/headless/test_file_receive_receipts.py @@ -30,8 +30,10 @@ def test_receipt_is_frozen_and_describes_received_content_after_atomic_publicati receive(receiver, content, receipts, done=lambda path: done.append(path.read_bytes())) receipt, = receipts assert receipt.path == tmp_path / 'shared.bin' - assert receipt.sha256 == hashlib.sha256(content).hexdigest() and receipt.size == len(content) - assert done == [content] and receipt.path.read_bytes() == content + assert receipt.sha256 == hashlib.sha256(content).hexdigest() + assert receipt.size == len(content) + assert done == [content] + assert receipt.path.read_bytes() == content with pytest.raises(FrozenInstanceError): receipt.sha256 = '0' * 64 @@ -89,7 +91,9 @@ def failed(*_args): receiver.handle_message(b'part' if boundary != 'truncated' else b'x', on_error=errors.append) kind = 'file_abort' if boundary == 'abort' else 'file_end' receiver.handle_message(json.dumps({'type': kind}), on_receipt=receipts.append, on_error=errors.append) - assert errors and receipts == [] and target.read_bytes() == b'previous' + assert errors + assert receipts == [] + assert target.read_bytes() == b'previous' assert sorted(p.name for p in tmp_path.iterdir()) == ['shared.bin'] @@ -111,7 +115,8 @@ def test_receipt_cannot_register_an_unselected_or_missing_path(tmp_path, placeme target.write_bytes(b'received') engine = FolderSyncEngine(watch_dir=watch, sender=lambda *_args: None) receipt = FileReceiveReceipt(target, hashlib.sha256(b'received').hexdigest(), 8) - assert not engine.record_receipt(receipt) and engine._content.snapshot == {} + assert not engine.record_receipt(receipt) + assert engine._content.snapshot == {} @pytest.mark.parametrize('digest,size', [('bad', 1), ('G' * 64, 1), ('0' * 64, -1), ('0' * 64, True), @@ -150,8 +155,10 @@ def test_relative_inbox_remains_bound_when_another_operation_changes_cwd(tmp_pat receipts = [] receiver.handle_message(b'data') receiver.handle_message(json.dumps({'type': 'file_end'}), on_receipt=receipts.append) - assert len(receipts) == 1 and receipts[0].path == tmp_path / 'inbox' / 'shared.bin' - assert receipts[0].path.read_bytes() == b'data' and list(changed.iterdir()) == [] + assert len(receipts) == 1 + assert receipts[0].path == tmp_path / 'inbox' / 'shared.bin' + assert receipts[0].path.read_bytes() == b'data' + assert list(changed.iterdir()) == [] def test_relative_watch_keeps_its_original_selected_root_when_cwd_changes(tmp_path, monkeypatch): @@ -171,7 +178,8 @@ def test_relative_watch_keeps_its_original_selected_root_when_cwd_changes(tmp_pa assert engine.record_receipt(receipts[0]) (watch / 'shared.bin').write_bytes(b'original watch edit') loop(engine, lambda: None) - assert sent == [b'original watch edit'] and sentinel.read_bytes() == b'unselected content' + assert sent == [b'original watch edit'] + assert sentinel.read_bytes() == b'unselected content' @pytest.fixture(params=['host', 'viewer']) @@ -207,7 +215,8 @@ def test_native_receipt_listener_can_be_replaced_and_cleared_without_changing_pa native_deliver(channel, b'second') owner.set_file_receipt_callback(None) native_deliver(channel, b'third') - assert len(first) == len(second) == 1 and len(paths) == 3 + assert len(first) == len(second) == 1 + assert len(paths) == 3 assert first[0].sha256 == hashlib.sha256(b'first').hexdigest() assert second[0].sha256 == hashlib.sha256(b'second').hexdigest() assert (inbox / 'shared.bin').read_bytes() == b'third' @@ -223,7 +232,8 @@ def failed(_receipt): owner.set_file_receipt_callback(failed) owner.set_file_received_callback(paths.append) native_deliver(channel) - assert paths == [inbox / 'shared.bin'] and paths[0].read_bytes() == b'bytes' + assert paths == [inbox / 'shared.bin'] + assert paths[0].read_bytes() == b'bytes' @pytest.mark.parametrize('signal', [KeyboardInterrupt, SystemExit, asyncio.CancelledError, @@ -238,5 +248,6 @@ def failed(_receipt): owner.set_file_receipt_callback(failed) with pytest.raises(signal) as caught: native_deliver(channel) - assert caught.value is original and (inbox / 'shared.bin').read_bytes() == b'bytes' + assert caught.value is original + assert (inbox / 'shared.bin').read_bytes() == b'bytes' assert list(inbox.glob('*.part')) == [] diff --git a/test/unit_test/headless/test_folder_sync_checkpoint.py b/test/unit_test/headless/test_folder_sync_checkpoint.py index 093f406dd..d4eecbe39 100644 --- a/test/unit_test/headless/test_folder_sync_checkpoint.py +++ b/test/unit_test/headless/test_folder_sync_checkpoint.py @@ -29,7 +29,8 @@ def failed(*_args): guard.setattr(Path, 'stat', lambda *_args, **_kwargs: pytest.fail('checkpoint accessed the filesystem')) checkpoint = old.checkpoint() replacement = FolderSyncEngine(watch_dir=tmp_path, sender=lambda *_args: None, checkpoint=checkpoint) - assert checkpoint.baselined and dict(checkpoint.entries) == old._content.snapshot + assert checkpoint.baselined + assert dict(checkpoint.entries) == old._content.snapshot assert 'pending.bin' not in dict(checkpoint.entries) existing.write_bytes(b'offline edit') sent = [] @@ -60,13 +61,15 @@ def blocked(*_args): assert entered.wait(5) worker = engine._thread engine.stop() - assert engine.is_running() and engine.stop_requested + assert engine.is_running() + assert engine.stop_requested with pytest.raises(FolderSyncStateError, match='retired'): engine.checkpoint() finally: release.set() engine.stop() - assert worker is not None and not worker.is_alive() + assert worker is not None + assert not worker.is_alive() assert 'pending.bin' in dict(engine.checkpoint().entries) diff --git a/test/unit_test/headless/test_folder_sync_receipts.py b/test/unit_test/headless/test_folder_sync_receipts.py index 95a4da594..459f906cd 100644 --- a/test/unit_test/headless/test_folder_sync_receipts.py +++ b/test/unit_test/headless/test_folder_sync_receipts.py @@ -32,7 +32,8 @@ def send(path, _name): engine = FolderSyncEngine(watch_dir=tmp_path, sender=send) loop(engine, lambda: target.write_bytes(b'old local'), lambda: None) - assert sent == [b'old local'] and target.read_bytes() == b'newer remote' + assert sent == [b'old local'] + assert target.read_bytes() == b'newer remote' def test_receive_during_initial_scan_is_not_overwritten_by_the_older_baseline(tmp_path, monkeypatch): diff --git a/test/unit_test/headless/test_gui_lazy_registry.py b/test/unit_test/headless/test_gui_lazy_registry.py index f711236c0..9ba35ea20 100644 --- a/test/unit_test/headless/test_gui_lazy_registry.py +++ b/test/unit_test/headless/test_gui_lazy_registry.py @@ -41,7 +41,8 @@ def test_importing_the_registry_loads_no_qt(): def test_every_lazy_tab_names_a_class_that_exists(spec): """Read, not imported: a typo here would otherwise surface when a user opens the tab.""" found = importlib.util.find_spec(spec.module) - assert found is not None and found.origin, spec.module + assert found is not None, spec.module + assert found.origin, spec.module source = pathlib.Path(found.origin).read_text(encoding="utf-8") assert (f"class {spec.class_name}(" in source or f"import {spec.class_name}" in source or f"{spec.class_name}," in source or f'"{spec.class_name}"' in source), (spec.module, spec.class_name) @@ -55,10 +56,13 @@ def factory(): return built[-1] entry = TabEntry("k", "tab_k", factory, on_build=adopted.append) - assert not entry.built and built == [] + assert not entry.built + assert built == [] first = entry.widget - assert entry.built and entry.widget is first - assert built == [first] and adopted == [first] + assert entry.built + assert entry.widget is first + assert built == [first] + assert adopted == [first] def test_a_lazy_factory_imports_at_call_time(): @@ -143,7 +147,8 @@ def test_opening_builds_the_tab_and_reopening_reuses_it(report): assert report["variables_imported_after_open"] assert report["current_after_open"] == "variables" assert report["hidden_is_owned"] - assert report["activated"] and report["same_widget_on_reopen"] + assert report["activated"] + assert report["same_widget_on_reopen"] # Registration order, not opening order: Variables sits between Script Builder and Remote Desktop. assert report["tab_order"] == ["record", "script_builder", "variables", "remote_desktop"] diff --git a/test/unit_test/headless/test_gui_registry_close.py b/test/unit_test/headless/test_gui_registry_close.py index 9247240cd..9272c2548 100644 --- a/test/unit_test/headless/test_gui_registry_close.py +++ b/test/unit_test/headless/test_gui_registry_close.py @@ -32,14 +32,17 @@ def factory(): entry = TabEntry("feature", "feature", factory) registry = TabRegistry([entry], on_close=closed.append) registry.close("feature") - assert not entry.built and built == [] + assert not entry.built + assert built == [] first = registry.open("feature") assert registry.open("feature") is first registry.close("feature") - assert not entry.built and closed == [first] + assert not entry.built + assert closed == [first] _flush(qapp) second = registry.open("feature") - assert second is not first and second.tab_key == first.tab_key + assert second is not first + assert second.tab_key == first.tab_key registry.close("feature") _flush(qapp) @@ -57,7 +60,8 @@ def closeEvent(self, event): registry = TabRegistry([entry], on_close=closed.append) page = registry.open("unsaved") registry.close("unsaved") - assert entry.built and registry.open("unsaved") is page + assert entry.built + assert registry.open("unsaved") is page assert closed == [] page.deleteLater() @@ -90,7 +94,8 @@ def test_close_button_releases_presence_listener_and_reopen_resubscribes(workspa _flush(qapp) assert len(registry._listeners) == baseline workspace.show_tab("presence") - assert entry.widget is not first and len(registry._listeners) == baseline + 1 + assert entry.widget is not first + assert len(registry._listeners) == baseline + 1 def test_close_detaches_hud_log_tail(workspace, qapp): @@ -102,7 +107,8 @@ def test_close_detaches_hud_log_tail(workspace, qapp): assert tail in autocontrol_logger.handlers workspace.close_tab("live_hud") _flush(qapp) - assert not entry.built and tail not in autocontrol_logger.handlers + assert not entry.built + assert tail not in autocontrol_logger.handlers def test_hide_still_reuses_a_panel_and_explicit_close_can_release_it(workspace, qapp): @@ -133,6 +139,7 @@ def test_legacy_form_and_remote_session_owner_are_retained_on_close(workspace, k entry = workspace._find_entry(key) first = entry.widget workspace.close_tab(key) - assert entry.built and workspace.tabs.indexOf(first) == -1 + assert entry.built + assert workspace.tabs.indexOf(first) == -1 workspace.show_tab(key) assert entry.widget is first diff --git a/test/unit_test/headless/test_gui_slots_menu_audit.py b/test/unit_test/headless/test_gui_slots_menu_audit.py index 17a5c65e1..b504b4918 100644 --- a/test/unit_test/headless/test_gui_slots_menu_audit.py +++ b/test/unit_test/headless/test_gui_slots_menu_audit.py @@ -54,7 +54,8 @@ def test_a_zero_interval_is_refused(monkeypatch): stub = types.SimpleNamespace(interval_input=_Text("0"), timer=types.SimpleNamespace(start=lambda: started.append(1))) tab.AutoClickTabMixin._start_auto_click(stub) - assert warned and not started + assert warned + assert not started def test_an_assertion_backend_error_is_shown_once_the_run_is_delivered(monkeypatch): @@ -156,7 +157,8 @@ def test_a_recording_that_does_not_start_is_reported(monkeypatch): monkeypatch.setattr(tab, "record", lambda: False) stub = types.SimpleNamespace(_record_status_key="record_idle", _apply_record_status_label=lambda: None) tab.RecordTabMixin._start_record(stub) - assert warned and stub._record_status_key == "record_idle" + assert warned + assert stub._record_status_key == "record_idle" def test_a_template_is_cropped_into_a_non_ascii_folder(monkeypatch, tmp_path): diff --git a/test/unit_test/headless/test_gui_task_lifecycle.py b/test/unit_test/headless/test_gui_task_lifecycle.py index 56633ae08..e22cc1258 100644 --- a/test/unit_test/headless/test_gui_task_lifecycle.py +++ b/test/unit_test/headless/test_gui_task_lifecycle.py @@ -70,13 +70,16 @@ def work(_token): assert entered.wait(1) QTimer.singleShot(0, lambda: ticks.append('tick')) assert _pump(app, lambda: ticks) - assert not results and handle.is_running + assert not results + assert handle.is_running finally: release.set() assert _pump(app, lambda: results and controller.active_count == 0) outcome, callback_thread = results[0] - assert outcome.status == 'ok' and outcome.task_id == handle.task_id - assert outcome.value != threading.get_ident() and callback_thread == threading.get_ident() + assert outcome.status == 'ok' + assert outcome.task_id == handle.task_id + assert outcome.value != threading.get_ident() + assert callback_thread == threading.get_ident() def test_cancel_releases_session(tasks): @@ -99,7 +102,9 @@ def work(token): handle.cancel() assert _pump(app, lambda: handle.outcome is not None and controller.active_count == 0) assert handle.outcome.status == 'cancelled' - assert released.is_set() and sessions == [] and not handle.is_running + assert released.is_set() + assert sessions == [] + assert not handle.is_running def test_owner_death_drops_result(tasks): @@ -121,7 +126,9 @@ def ignores_cancel(_token): finally: release.set() assert _pump(app, lambda: controller.active_count == 0) - assert received == [] and handle.outcome is None and handle.is_cancelled + assert received == [] + assert handle.outcome is None + assert handle.is_cancelled def test_no_worker_touches_widget(tasks): @@ -155,8 +162,11 @@ def test_submission_captures_context_and_viewer_authority_without_drive_privileg assert _pump(app, lambda: handle.outcome is not None and controller.active_count == 0) assert handle.outcome.status == 'ok' value, authority = handle.outcome.value - assert value == 'registrant' and authority.user_id == 'reader' and authority.role == 'viewer' - assert current_authorization() is None and marker.get() == 'ambient' + assert value == 'registrant' + assert authority.user_id == 'reader' + assert authority.role == 'viewer' + assert current_authorization() is None + assert marker.get() == 'ambient' @pytest.mark.parametrize('kind', ['keyboard', 'exit', 'generator', 'async', 'future', 'operation']) @@ -174,7 +184,8 @@ def work(_token): handle = controller.submit(work, owner=owner) assert _pump(app, lambda: handle.outcome is not None and controller.active_count == 0) - assert handle.outcome.status == 'cancelled' and handle.outcome.error == '' + assert handle.outcome.status == 'cancelled' + assert handle.outcome.error == '' def test_an_ordinary_error_finishes_once_and_does_not_block_a_later_task(tasks): @@ -187,11 +198,14 @@ def broken(_token): handle = controller.submit(broken, owner=owner) handle.finished.connect(outcomes.append) assert _pump(app, lambda: handle.outcome is not None and controller.active_count == 0) - assert handle.outcome.status == 'error' and 'controlled failure' in handle.outcome.error + assert handle.outcome.status == 'error' + assert 'controlled failure' in handle.outcome.error assert len(outcomes) == 1 later = controller.submit(lambda _token: 42, owner=owner) assert _pump(app, lambda: later.outcome is not None and controller.active_count == 0) - assert later.outcome.status == 'ok' and later.outcome.value == 42 and later.task_id != handle.task_id + assert later.outcome.status == 'ok' + assert later.outcome.value == 42 + assert later.task_id != handle.task_id def test_start_failure_does_not_leak_worker_or_controller_job(tasks, monkeypatch): @@ -208,7 +222,8 @@ def failed_start(_thread): with pytest.raises(RuntimeError) as caught: controller.submit(lambda _token: None, owner=owner) assert caught.value is original - assert controller.active_count == 0 and set(_worker_thread._RUNNING) == previous + assert controller.active_count == 0 + assert set(_worker_thread._RUNNING) == previous finally: # A failed pre-fix run must not leave an unstarted thread for atexit to join. for handle in set(_worker_thread._RUNNING)-previous: @@ -253,7 +268,8 @@ def work(_token): finally: release.set() assert _pump(app, lambda: handle.outcome is not None and controller.active_count == 0) - assert handle.outcome.status == 'error' and calls == [] + assert handle.outcome.status == 'error' + assert calls == [] def test_destroying_one_owner_does_not_cancel_another_owners_work(tasks): @@ -274,14 +290,17 @@ def second_work(_token): first = controller.submit(first_work, owner=first_owner) second = controller.submit(second_work, owner=second_owner) try: - assert first_entered.wait(1) and second_entered.wait(1) + assert first_entered.wait(1) + assert second_entered.wait(1) first_owner.deleteLater() QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete) - assert first.is_cancelled and not second.is_cancelled + assert first.is_cancelled + assert not second.is_cancelled finally: release.set() assert _pump(app, lambda: second.outcome is not None and controller.active_count == 0) - assert first.outcome is None and second.outcome.value == 'second owner' + assert first.outcome is None + assert second.outcome.value == 'second owner' second_owner.deleteLater() @@ -301,7 +320,9 @@ def work(token): controller.deleteLater() QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete) assert _pump(app, lambda: controller.active_count == 0) - assert handle.is_cancelled and handle.outcome is None and outcomes == [] + assert handle.is_cancelled + assert handle.outcome is None + assert outcomes == [] def test_discarding_a_handle_does_not_retain_it_through_worker_callbacks(tasks): @@ -339,7 +360,8 @@ def work(token): gc.collect() assert owner_ref() is None assert _pump(app, lambda: controller.active_count == 0) - assert handle.outcome is None and handle.is_cancelled + assert handle.outcome is None + assert handle.is_cancelled def test_foreign_and_late_progress_or_results_cannot_replace_this_tasks_outcome(tasks): @@ -357,13 +379,15 @@ def work(_token): try: handle.complete(TaskOutcome(handle.task_id+1, 'ok', 'foreign')) handle.forward_progress(TaskProgress(handle.task_id+1, 1)) - assert handle.outcome is None and progress == [] + assert handle.outcome is None + assert progress == [] finally: release.set() assert _pump(app, lambda: handle.outcome is not None and controller.active_count == 0) handle.complete(TaskOutcome(handle.task_id, 'error', error='late')) handle.forward_progress(TaskProgress(handle.task_id, 2)) - assert handle.outcome.value == 'correct' and progress == [] + assert handle.outcome.value == 'correct' + assert progress == [] def test_late_cooperative_stop_does_not_relabel_successful_committed_work(tasks): @@ -379,7 +403,9 @@ def work(token): assert entered.wait(1) handle.cancel() assert _pump(app, lambda: handle.outcome is not None and controller.active_count == 0) - assert handle.is_cancelled and handle.outcome.status == 'ok' and handle.outcome.value == 'committed' + assert handle.is_cancelled + assert handle.outcome.status == 'ok' + assert handle.outcome.value == 'committed' @pytest.mark.parametrize('operation', ['submit', 'close']) @@ -399,7 +425,9 @@ def off_thread(): thread = threading.Thread(target=off_thread) thread.start() thread.join(1) - assert not thread.is_alive() and len(errors) == 1 and controller.active_count == 0 + assert not thread.is_alive() + assert len(errors) == 1 + assert controller.active_count == 0 def test_failure_cause_tracebacks_are_released_before_outcome_delivery(tasks): @@ -415,7 +443,8 @@ def work(_token): handle = controller.submit(work, owner=owner) assert _pump(app, lambda: handle.outcome is not None and controller.active_count == 0) assert handle.outcome.status == 'error' - assert original.__traceback__ is None and wrapper.__traceback__ is None + assert original.__traceback__ is None + assert wrapper.__traceback__ is None def test_worker_progress_and_error_text_use_the_captured_secret_scope(tasks): @@ -435,8 +464,12 @@ def work(token): handle.progress.connect(progress.append) release.set() assert _pump(app, lambda: handle.outcome is not None and controller.active_count == 0) - assert len(progress) == 1 and secret not in progress[0].detail and '***' in progress[0].detail - assert handle.outcome.status == 'error' and secret not in handle.outcome.error and '***' in handle.outcome.error + assert len(progress) == 1 + assert secret not in progress[0].detail + assert '***' in progress[0].detail + assert handle.outcome.status == 'error' + assert secret not in handle.outcome.error + assert '***' in handle.outcome.error @pytest.mark.parametrize('kind', ['ordinary', 'keyboard', 'exit', 'generator', 'async', 'future', 'operation']) @@ -456,9 +489,11 @@ def work(_token): handle = controller.submit(work, owner=owner) assert _pump(app, lambda: handle.outcome is not None and controller.active_count == 0) if kind == 'ordinary': - assert handle.outcome.status == 'error' and 'detail unavailable' in handle.outcome.error + assert handle.outcome.status == 'error' + assert 'detail unavailable' in handle.outcome.error else: - assert handle.outcome.status == 'cancelled' and handle.outcome.error == '' + assert handle.outcome.status == 'cancelled' + assert handle.outcome.error == '' def test_retiring_tasks_disconnects_owner_notifications_instead_of_accumulating_them(tasks): diff --git a/test/unit_test/headless/test_gui_workspace_layout.py b/test/unit_test/headless/test_gui_workspace_layout.py index af601c156..3aafc4cb1 100644 --- a/test/unit_test/headless/test_gui_workspace_layout.py +++ b/test/unit_test/headless/test_gui_workspace_layout.py @@ -56,7 +56,8 @@ def test_narrow_content_scrolls_without_changing_the_tab_widget_contract(qapp): qapp.processEvents() try: assert tabs.indexOf(page) == 0 - assert tabs.widget(0) is page and tabs.currentWidget() is page + assert tabs.widget(0) is page + assert tabs.currentWidget() is page scroll = tabs.scroll_area(0) assert scroll.widget() is page assert scroll.horizontalScrollBar().maximum() > 0 @@ -69,7 +70,8 @@ def test_narrow_content_scrolls_without_changing_the_tab_widget_contract(qapp): tabs.removeTab(0) assert tabs.indexOf(page) == -1 tabs.insertTab(0, page, "Wide again") - assert tabs.widget(0) is page and tabs.count() == 2 + assert tabs.widget(0) is page + assert tabs.count() == 2 assert len(tabs.findChildren(type(scroll))) == 2 finally: tabs.close() diff --git a/test/unit_test/headless/test_history_interruption.py b/test/unit_test/headless/test_history_interruption.py index 9a646c86c..61d68b0a8 100644 --- a/test/unit_test/headless/test_history_interruption.py +++ b/test/unit_test/headless/test_history_interruption.py @@ -91,8 +91,10 @@ def test_interruption_records_failure_and_never_captures_or_runs_the_next_action else: fire() row = history.list_runs()[0] - assert row.status == STATUS_ERROR and type(failure).__name__ in row.error_text - assert snapshots == [] and reached == [] + assert row.status == STATUS_ERROR + assert type(failure).__name__ in row.error_text + assert snapshots == [] + assert reached == [] assert len(history.journals_for_run(row.id)) == 1 assert read_events(path)[-1].status == "cancelled" @@ -109,7 +111,9 @@ def unavailable(*_args, **_kwargs): _fire(kind, script, execute)() assert raised.value is failure assert history.list_runs()[0].status == STATUS_RUNNING - assert snapshots == [] and reached == [] and read_events(path)[-1].status == "cancelled" + assert snapshots == [] + assert reached == [] + assert read_events(path)[-1].status == "cancelled" @pytest.mark.parametrize("kind", KINDS) @@ -124,12 +128,14 @@ def test_ordinary_soft_failures_still_capture_and_keep_their_existing_containmen else: fire() assert history.list_runs()[0].status == STATUS_ERROR - assert len(snapshots) == 1 and reached == [True] + assert len(snapshots) == 1 + assert reached == [True] def test_mcp_cancellation_keeps_its_deliberate_control_signal_contract(): failure = OperationCancelledError("controlled") - assert isinstance(failure, RuntimeError) and not isinstance(failure, AutoControlException) + assert isinstance(failure, RuntimeError) + assert not isinstance(failure, AutoControlException) @pytest.mark.parametrize("block", ["parallel", "dag"]) @@ -152,7 +158,8 @@ def test_worker_interruptions_reach_the_owner_without_becoming_success_or_an_ord else: fire() assert history.list_runs()[0].status == STATUS_ERROR - assert snapshots == [] and reached == [] + assert snapshots == [] + assert reached == [] assert read_events(path)[-1].status == "cancelled" @@ -200,5 +207,6 @@ def invoke(): script.write_text(json.dumps(actions), encoding="utf-8") _fire("scheduler", script, execute)() assert history.list_runs()[0].status == STATUS_ERROR - assert snapshots == [] and reached == [] + assert snapshots == [] + assert reached == [] assert read_events(path)[-1].status == "cancelled" diff --git a/test/unit_test/headless/test_journal_browser_gui.py b/test/unit_test/headless/test_journal_browser_gui.py index efb4766ca..5fd85d340 100644 --- a/test/unit_test/headless/test_journal_browser_gui.py +++ b/test/unit_test/headless/test_journal_browser_gui.py @@ -70,15 +70,18 @@ def inspect(path, **_kwargs): finally: release.set() _until(app, lambda: browser._handle is None) - assert calls == ["old.jsonl"] and browser._events == [] + assert calls == ["old.jsonl"] + assert browser._events == [] if next_action == "viewer": assert browser._status_key == "journal_error" def test_browser_has_only_inputs_and_views_until_an_action(browser): assert browser.findChildren(QPushButton) == [] - assert browser._handle is None and browser._table.rowCount() == 0 - assert browser._limit.minimum() == 1 and browser._limit.maximum() == 10000 + assert browser._handle is None + assert browser._table.rowCount() == 0 + assert browser._limit.minimum() == 1 + assert browser._limit.maximum() == 10000 assert browser._limit.value() == 100 @@ -101,13 +104,15 @@ def test_links_select_run_without_automatic_file_io(browser, app, tmp_path): _journal(path, "one") _journal(path, "two") browser.set_links([JournalLink(1, str(path), "one"), JournalLink(1, str(path), "two")]) - assert browser._handle is None and browser._table.rowCount() == 0 + assert browser._handle is None + assert browser._table.rowCount() == 0 browser._links.setCurrentIndex(2) assert browser._run_id.text() == "two" browser._limit.setValue(1) browser.read() _until(app, lambda: browser._handle is None) - assert len(browser._events) == 1 and browser._events[0]["run_id"] == "two" + assert len(browser._events) == 1 + assert browser._events[0]["run_id"] == "two" assert browser._events[0]["status"] == "incomplete" @@ -120,7 +125,8 @@ def forbidden(*args, **kwargs): worker.finished.connect(outcomes.append) worker.request_stop() worker.run() - assert outcomes[0].status == "cancelled" and outcomes[0].events == [] + assert outcomes[0].status == "cancelled" + assert outcomes[0].events == [] worker.deleteLater() @@ -132,7 +138,8 @@ def test_worker_rechecks_captured_viewer_authority(app, monkeypatch): outcomes = [] worker.finished.connect(outcomes.append) worker.run() - assert outcomes[0].status == "error" and calls == [] + assert outcomes[0].status == "error" + assert calls == [] worker.deleteLater() @@ -144,7 +151,8 @@ def test_worker_retains_enclosing_path_policy(app, tmp_path): outcomes = [] worker.finished.connect(outcomes.append) worker.run() - assert outcomes[0].status == "error" and "PathNotAllowedError" in outcomes[0].error + assert outcomes[0].status == "error" + assert "PathNotAllowedError" in outcomes[0].error worker.deleteLater() @@ -161,7 +169,8 @@ def inspect(path, **kwargs): outcomes = [] worker.finished.connect(outcomes.append) worker.run() - assert outcomes[0].status == "cancelled" and max(scanned) <= 101 + assert outcomes[0].status == "cancelled" + assert max(scanned) <= 101 worker.deleteLater() @@ -187,7 +196,8 @@ def test_cancel_does_not_block_gui(browser, app, monkeypatch): finally: release.set() _until(app, lambda: browser._handle is None) - assert browser._events == [] and browser._status_key == "journal_cancelled" + assert browser._events == [] + assert browser._status_key == "journal_cancelled" def test_changing_target_discards_stale_completion(browser, app, monkeypatch): @@ -200,8 +210,10 @@ def test_changing_target_discards_stale_completion(browser, app, monkeypatch): finally: release.set() _until(app, lambda: browser._handle is None) - assert browser._path.text() == "new" and browser._run_id.text() == "new-run" - assert browser._events == [] and browser._status_key == "journal_idle" + assert browser._path.text() == "new" + assert browser._run_id.text() == "new-run" + assert browser._events == [] + assert browser._status_key == "journal_idle" def test_destroying_owner_requests_stop_and_drops_late_results(app, monkeypatch): @@ -225,7 +237,8 @@ def test_viewer_is_refused_before_worker_creation(browser): browser._path.setText("private.jsonl") with authorization_scope(AuthorizationContext("viewer", Role.VIEWER)): browser.read() - assert browser._handle is None and browser._status_key == "journal_error" + assert browser._handle is None + assert browser._status_key == "journal_error" def test_corrupt_read_clears_previous_snapshots(browser, app, tmp_path): @@ -238,7 +251,8 @@ def test_corrupt_read_clears_previous_snapshots(browser, app, tmp_path): path.write_text("invalid\n", encoding="utf-8") browser.read() _until(app, lambda: browser._handle is None) - assert browser._events == [] and browser._table.rowCount() == 0 + assert browser._events == [] + assert browser._table.rowCount() == 0 assert browser._status_key == "journal_error" @@ -253,10 +267,13 @@ def test_history_menu_loads_links_without_reading(app, monkeypatch, tmp_path): tab._timer.stop() tab._table.selectRow(0) actions = dict(tab.menu_actions()) - assert "journal_selected_run" in actions and "journal_read" in actions and "journal_cancel" in actions + assert "journal_selected_run" in actions + assert "journal_read" in actions + assert "journal_cancel" in actions actions["journal_selected_run"]() assert tab._journal._path.text() == str(tmp_path / "events.jsonl") - assert tab._journal._run_id.text() == "chosen" and tab._journal._handle is None + assert tab._journal._run_id.text() == "chosen" + assert tab._journal._handle is None finally: tab.deleteLater() store.close() @@ -294,7 +311,8 @@ def forbidden(*args, **kwargs): outcomes = [] worker.finished.connect(outcomes.append) worker.run() - assert outcomes[0].status == "error" and outcomes[0].events == [] + assert outcomes[0].status == "error" + assert outcomes[0].events == [] worker.deleteLater() @@ -345,7 +363,8 @@ def forbidden(*args, **kwargs): monkeypatch.setattr("je_auto_control.gui.journal_browser.QFileDialog.getOpenFileName", forbidden) with authorization_scope(AuthorizationContext("viewer", Role.VIEWER)): browser.browse() - assert browser._status_key == "journal_error" and browser._handle is None + assert browser._status_key == "journal_error" + assert browser._handle is None def test_worker_masks_errors_in_active_captured_context(app, monkeypatch): @@ -360,7 +379,8 @@ def fail(*args, **kwargs): worker = JournalReadWorker(JournalReadRequest(1, "unused", None, 100)) worker.finished.connect(outcomes.append) worker.run() - assert outcomes[0].status == "error" and secret not in outcomes[0].error + assert outcomes[0].status == "error" + assert secret not in outcomes[0].error assert "***" in outcomes[0].error worker.deleteLater() @@ -387,7 +407,8 @@ def inspect(path, **kwargs): browser._path.setText("unused") browser.read() _until(app, lambda: browser._handle is None) - assert calls and set(calls) == {gui_ident} + assert calls + assert set(calls) == {gui_ident} def test_history_close_cancels_its_child_reader(app, monkeypatch, tmp_path): @@ -402,7 +423,8 @@ def test_history_close_cancels_its_child_reader(app, monkeypatch, tmp_path): try: assert entered.wait(2) tab.close() - assert tab._journal._worker._stop.is_set() and not tab._timer.isActive() + assert tab._journal._worker._stop.is_set() + assert not tab._timer.isActive() finally: release.set() assert handle.wait(5) @@ -421,5 +443,6 @@ def test_lookup_error_invalidates_an_older_read(browser, app, monkeypatch): finally: release.set() _until(app, lambda: browser._handle is None) - assert browser._events == [] and browser._status_key == "journal_error" + assert browser._events == [] + assert browser._status_key == "journal_error" assert "new history lookup failed" in browser._status.text() diff --git a/test/unit_test/headless/test_journal_commands.py b/test/unit_test/headless/test_journal_commands.py index 674985718..01e5730b0 100644 --- a/test/unit_test/headless/test_journal_commands.py +++ b/test/unit_test/headless/test_journal_commands.py @@ -27,9 +27,11 @@ def test_capture_defers_body_variables_and_preserves_owner_scope(tmp_path): result = executor.execute_action([_capture(path, body, run_id="nested")], raise_on_error=True) assert executor.variables.get("message") == "after" summary = next(iter(result.values())) - assert summary["run_id"] == "nested" and summary["failed_actions"] == 0 + assert summary["run_id"] == "nested" + assert summary["failed_actions"] == 0 assert "after" in summary["record"].values() - assert body[-1][1]["name"] == "${variable_name}" and current_journal() is None + assert body[-1][1]["name"] == "${variable_name}" + assert current_journal() is None assert [event.command for event in read_events(path) if event.status == "ok"] == ["AC_set_var", "AC_get_var"] @@ -63,7 +65,8 @@ def test_nested_validation_rejects_unknown_body_before_prior_actions(tmp_path, m actions = [["AC_journal_command_probe"], _capture(tmp_path / "invalid.jsonl", [["AC_unknown_journal_body"]])] with pytest.raises(AutoControlActionException, match="unknown command"): executor.execute_action(actions, raise_on_error=True) - assert seen == [] and not (tmp_path / "invalid.jsonl").exists() + assert seen == [] + assert not (tmp_path / "invalid.jsonl").exists() @pytest.mark.parametrize("strict", [False, True]) @@ -97,14 +100,16 @@ def cancel(): cancelled = tmp_path / "cancelled.jsonl" with pytest.raises(asyncio.CancelledError) as caught: executor.execute_action([_capture(cancelled, [["AC_journal_command_probe"]])]) - assert caught.value is signal and current_journal() is None + assert caught.value is signal + assert current_journal() is None assert [event.status for event in read_events(cancelled)] == ["incomplete", "cancelled"] def test_capture_is_inert_during_outer_dry_run(tmp_path): path = tmp_path / "dry.jsonl" result = executor.execute_action([_capture(path, [["AC_screen_size"]])], dry_run=True) - assert any("dry-run" in key for key in result) and not path.exists() + assert any("dry-run" in key for key in result) + assert not path.exists() @pytest.mark.parametrize("name", ["AC_journal_capture", "AC_journal_read"]) @@ -124,8 +129,10 @@ def test_read_command_returns_sanitized_bounded_snapshots(tmp_path): result = executor.execute_action([["AC_journal_read", {"path": str(path), "run_id": "first", "limit": 1}]], raise_on_error=True) payload = next(iter(result.values())) - assert len(payload) == 1 and payload[0]["run_id"] == "first" - assert payload[0]["status"] == "incomplete" and path.read_bytes() == before + assert len(payload) == 1 + assert payload[0]["run_id"] == "first" + assert payload[0]["status"] == "incomplete" + assert path.read_bytes() == before def test_schema_exposes_capture_body_and_linter_checks_it(tmp_path): diff --git a/test/unit_test/headless/test_journal_history_links.py b/test/unit_test/headless/test_journal_history_links.py index 4637e6b6b..fb76b781e 100644 --- a/test/unit_test/headless/test_journal_history_links.py +++ b/test/unit_test/headless/test_journal_history_links.py @@ -30,7 +30,8 @@ def test_multiple_journals_attach_to_one_history_run_idempotently(store, tmp_pat assert [(item.run_id, item.journal_path, item.journal_run_id) for item in links] == [ (run, first, "one"), (run, second, "two"), ] - assert not Path(first).exists() and not Path(second).exists() + assert not Path(first).exists() + assert not Path(second).exists() assert store.journals_for_run(run + 1) == [] assert not store.attach_journal(run + 1, first, "unknown") @@ -107,7 +108,8 @@ def close(self): try: with pytest.raises(HistoryStoreError, match="controlled schema failure"): store.attach_journal(1, "unused.jsonl", "unused") - assert connection.closed and store._conn is None + assert connection.closed + assert store._conn is None finally: connection.close() @@ -213,6 +215,7 @@ def capture(): trigger = owner.add("imap.invalid", "user", "unused", str(script)) owner._execute_with_history(trigger, {}) rows = store.list_runs() - assert len(rows) == 1 and rows[0].status == STATUS_OK + assert len(rows) == 1 + assert rows[0].status == STATUS_OK links = store.journals_for_run(rows[0].id) assert [(item.journal_path, item.journal_run_id) for item in links] == [(str(path.resolve()), "background")] diff --git a/test/unit_test/headless/test_journal_observation.py b/test/unit_test/headless/test_journal_observation.py index 313176bc4..b6499f260 100644 --- a/test/unit_test/headless/test_journal_observation.py +++ b/test/unit_test/headless/test_journal_observation.py @@ -21,8 +21,10 @@ def observe(status): options = ac.JournalRunOptions(variables=variables, run_id="observed", observer=observe) result = ac.execute_journal_run([["AC_set_var", {"name": "message", "value": "after"}]], path, options=options) - assert statuses == ["incomplete", "ok"] and result["run_id"] == "observed" - assert variables == {"message": "before"} and current_journal() is None + assert statuses == ["incomplete", "ok"] + assert result["run_id"] == "observed" + assert variables == {"message": "before"} + assert current_journal() is None @pytest.mark.parametrize("worker", ["loop", "parallel", "dag", "capture"]) @@ -55,7 +57,9 @@ def observe(_status): with pytest.raises(asyncio.CancelledError) as caught: ac.execute_journal_run([["AC_set_var", {"name": "x", "value": 1}]], path, options=ac.JournalRunOptions(observer=observe)) - assert caught.value is signal and not path.exists() and current_journal() is None + assert caught.value is signal + assert not path.exists() + assert current_journal() is None @pytest.mark.parametrize("signal", [ValueError("original"), KeyboardInterrupt(), asyncio.CancelledError()]) @@ -69,7 +73,8 @@ def observe(status): with pytest.raises(type(signal)) as caught: with ac.journal_scope(ac.ActionJournal(tmp_path / "failure.jsonl"), observer=observe): executor.execute_action([["AC_observed_failure"]], raise_on_error=True) - assert caught.value is signal and current_journal() is None + assert caught.value is signal + assert current_journal() is None def test_observer_failure_after_success_leaves_a_durable_success(tmp_path): @@ -100,7 +105,8 @@ def test_nested_controls_compose_without_relaxing_or_duplicating(tmp_path): pytest.fail("nested policy relaxed its enclosing roots") with pytest.raises(PathNotAllowedError): ac.inspect_journal(outside / "absent.jsonl", path_policy=PathPolicy()) - assert statuses == ["incomplete", "ok"] and list(outside.iterdir()) == [] + assert statuses == ["incomplete", "ok"] + assert list(outside.iterdir()) == [] @pytest.mark.parametrize("worker", ["direct", "parallel", "dag"]) @@ -117,7 +123,8 @@ def test_dynamic_nested_journal_paths_cannot_escape_captured_roots(tmp_path, wor assert not outside.exists() if worker == "dag": outcome = next(iter(result["record"].values())) - assert outcome["succeeded"] is False and outcome["nodes"]["one"]["status"] == "failed" + assert outcome["succeeded"] is False + assert outcome["nodes"]["one"]["status"] == "failed" assert "PathNotAllowedError" in outcome["nodes"]["one"]["error"] else: assert result["failed_actions"] > 0 @@ -173,7 +180,9 @@ def observe(_count): monkeypatch.setattr(Path, "open", track) with pytest.raises(asyncio.CancelledError) as caught: ac.inspect_journal(path, observer=observe) - assert caught.value is signal and opened and all(handle.closed for handle in opened) + assert caught.value is signal + assert opened + assert all(handle.closed for handle in opened) def test_reader_observes_all_validated_records_before_filtering(tmp_path): @@ -182,4 +191,6 @@ def test_reader_observes_all_validated_records_before_filtering(tmp_path): ac.execute_action_with_journal([["AC_set_var", {"name": "x", "value": 1}]], path, run_id=run_id) seen = [] payload = ac.inspect_journal(path, run_id="two", limit=1, observer=seen.append) - assert seen == [1, 2, 3, 4] and len(payload) == 1 and payload[0]["run_id"] == "two" + assert seen == [1, 2, 3, 4] + assert len(payload) == 1 + assert payload[0]["run_id"] == "two" diff --git a/test/unit_test/headless/test_journal_public_cli.py b/test/unit_test/headless/test_journal_public_cli.py index 6a393bda5..8c8ffdb0a 100644 --- a/test/unit_test/headless/test_journal_public_cli.py +++ b/test/unit_test/headless/test_journal_public_cli.py @@ -22,14 +22,19 @@ def test_facade_capture_and_filtered_read_keep_original_results(tmp_path, monkey path = tmp_path / "public.jsonl" actions = [["AC_public_journal_probe", {"value": "${message}"}]] result = ac.execute_action_with_journal(actions, path, variables={"message": "hello"}, run_id="public") - assert seen == ["hello"] and result["failed_actions"] == 0 - assert result["record"] and result["run_id"] == "public" + assert seen == ["hello"] + assert result["failed_actions"] == 0 + assert result["record"] + assert result["run_id"] == "public" assert ac.read_events(path, run_id="other") == [] assert [event.status for event in ac.read_events(path, run_id="public")] == ["incomplete", "ok"] - assert actions[0][1]["value"] == "${message}" and current_journal() is None + assert actions[0][1]["value"] == "${message}" + assert current_journal() is None for name in action_journal.__all__: - assert name in ac.__all__ and getattr(ac, name) is getattr(action_journal, name) - assert ac.JournalLink is JournalLink and "JournalLink" in ac.__all__ + assert name in ac.__all__ + assert getattr(ac, name) is getattr(action_journal, name) + assert ac.JournalLink is JournalLink + assert "JournalLink" in ac.__all__ def _script(tmp_path, actions): @@ -46,7 +51,8 @@ def test_cli_capture_keeps_stdout_and_variable_execution(tmp_path, monkeypatch, assert main(["run", script, "--var", "message=hello", "--journal", str(path), "--journal-run-id", "cli"]) == 0 payload = json.loads(capsys.readouterr().out) - assert "journal_path" not in payload and seen == ["hello"] + assert "journal_path" not in payload + assert seen == ["hello"] events = action_journal.read_events(path) assert [event.status for event in events] == ["incomplete", "ok"] assert all(event.run_id == "cli" for event in events) @@ -82,8 +88,10 @@ def test_cli_foreign_destination_is_preserved_before_effects(tmp_path, monkeypat path = tmp_path / "foreign.txt" path.write_bytes(b"leave this file intact\n") assert main(["run", script, "--journal", str(path)]) == 1 - assert seen == [] and path.read_bytes() == b"leave this file intact\n" - assert "error:" in capsys.readouterr().err and current_journal() is None + assert seen == [] + assert path.read_bytes() == b"leave this file intact\n" + assert "error:" in capsys.readouterr().err + assert current_journal() is None def test_cli_run_id_requires_capture(tmp_path, capsys): @@ -123,7 +131,8 @@ def cancel(): path = tmp_path / "cancelled.jsonl" with pytest.raises(asyncio.CancelledError) as caught: main(["run", script, "--journal", str(path)]) - assert caught.value is signal and current_journal() is None + assert caught.value is signal + assert current_journal() is None assert [event.status for event in action_journal.read_events(path)] == ["incomplete", "cancelled"] @@ -139,13 +148,15 @@ def test_cli_journal_corruption_never_prints_raw_input(tmp_path, capsys): path.write_text('{"password":"fake-private-value"}\n', encoding="utf-8") assert main(["journal", str(path)]) == 1 captured = capsys.readouterr() - assert captured.out == "" and "fake-private-value" not in captured.err + assert captured.out == "" + assert "fake-private-value" not in captured.err def test_cli_journal_missing_path_is_empty_without_creation(tmp_path, capsys): path = tmp_path / "absent.jsonl" assert main(["journal", str(path)]) == 0 - assert json.loads(capsys.readouterr().out) == [] and not path.exists() + assert json.loads(capsys.readouterr().out) == [] + assert not path.exists() @pytest.mark.parametrize("command", ["run", "journal"]) @@ -158,7 +169,8 @@ def test_cli_journal_paths_use_allowed_roots(tmp_path, monkeypatch, capsys, comm args = ["journal", str(path)] if command == "journal" else [ "run", _script(tmp_path, [["AC_screen_size"]]), "--journal", str(path)] assert main(args) == 1 - assert "error:" in capsys.readouterr().err and not path.exists() + assert "error:" in capsys.readouterr().err + assert not path.exists() def test_public_and_cli_journals_work_without_qt_or_sqlite(tmp_path): diff --git a/test/unit_test/headless/test_manual_history.py b/test/unit_test/headless/test_manual_history.py index fccebec43..36ac434be 100644 --- a/test/unit_test/headless/test_manual_history.py +++ b/test/unit_test/headless/test_manual_history.py @@ -30,12 +30,18 @@ def test_scope_preserves_existing_variables_results_and_owner(store): assert ac.manual_history_scope is manual_module.manual_history_scope with execution_scope({"message": "before"}): with ac.manual_history_scope(store=store, source_id="editor", script_path="") as binding: - assert isinstance(binding, ac.HistoryBinding) and current_history() is binding + assert isinstance(binding, ac.HistoryBinding) + assert current_history() is binding result = executor.execute_action([["AC_set_var", {"name": "message", "value": "after"}]]) - assert executor.variables.get("message") == "after" and result + assert executor.variables.get("message") == "after" + assert result row = store.get_run(binding.run_id) - assert row.source_type == "manual" and row.source_id == "editor" and row.script_path == "" - assert row.status == "ok" and row.finished_at is not None and row.artifact_path is None + assert row.source_type == "manual" + assert row.source_id == "editor" + assert row.script_path == "" + assert row.status == "ok" + assert row.finished_at is not None + assert row.artifact_path is None assert current_history() is None @@ -47,7 +53,8 @@ def fail(): before = recorded_failures() with ac.manual_history_scope(store=store) as clean: executor.execute_action([["AC_set_var", {"name": "x", "value": 1}]]) - assert store.get_run(clean.run_id).status == "ok" and recorded_failures() == before + assert store.get_run(clean.run_id).status == "ok" + assert recorded_failures() == before with ac.manual_history_scope(store=store) as failed: result = executor.execute_action([["AC_manual_failure"]]) assert any("controlled failure" in str(value) for value in result.values()) @@ -64,7 +71,8 @@ def test_original_signal_is_retained_and_history_is_error(store, signal): with pytest.raises(type(signal)) as caught: with ac.manual_history_scope(store=store) as binding: raise signal - assert caught.value is signal and current_history() is None + assert caught.value is signal + assert current_history() is None assert store.get_run(binding.run_id).status == "error" @@ -76,7 +84,8 @@ def fail(*args, **kwargs): with pytest.raises(type(signal)) as caught: with ac.manual_history_scope(store=store) as binding: raise signal - assert caught.value is signal and store.get_run(binding.run_id).status == "running" + assert caught.value is signal + assert store.get_run(binding.run_id).status == "running" def test_failed_completion_without_original_signal_propagates(store, monkeypatch): @@ -137,7 +146,8 @@ def test_worker_captures_link_to_the_manual_owner(store, tmp_path, worker): actions = [["AC_run_dag", {"definition": {"nodes": [{"id": "one", "actions": body}]}}]] with ac.manual_history_scope(store=store) as owner: executor.execute_action(actions, raise_on_error=True) - assert len(store.journals_for_run(owner.run_id)) == 1 and path.exists() + assert len(store.journals_for_run(owner.run_id)) == 1 + assert path.exists() def test_metadata_and_failure_text_are_masked_before_sqlite(store): @@ -148,7 +158,8 @@ def test_metadata_and_failure_text_are_masked_before_sqlite(store): with ac.manual_history_scope(store=store, source_id=secret, script_path=secret) as owner: raise ValueError(secret) row = store.get_run(owner.run_id) - assert row.source_id == row.script_path == "***" and secret not in row.error_text + assert row.source_id == row.script_path == "***" + assert secret not in row.error_text def test_ambient_journal_policy_is_checked_before_linking(store, tmp_path): @@ -159,7 +170,8 @@ def test_ambient_journal_policy_is_checked_before_linking(store, tmp_path): with pytest.raises(ac.PathNotAllowedError): with ac.manual_history_scope(store=store): pytest.fail("body executed outside active roots") - assert store.list_runs()[0].status == "error" and store.journals_for_run(store.list_runs()[0].id) == [] + assert store.list_runs()[0].status == "error" + assert store.journals_for_run(store.list_runs()[0].id) == [] def test_viewer_is_refused_before_store_effects(store, monkeypatch): @@ -200,7 +212,8 @@ def test_existing_journal_secret_metadata_is_refused_before_link(store, tmp_path with ac.manual_history_scope(store=store): pytest.fail("unsafe provenance reached body") row = store.list_runs()[0] - assert row.status == "error" and store.journals_for_run(row.id) == [] + assert row.status == "error" + assert store.journals_for_run(row.id) == [] assert secret not in row.error_text @@ -220,7 +233,8 @@ def __repr__(self): with pytest.raises(BrokenError) as caught: with ac.manual_history_scope(store=store) as owner: raise original - assert caught.value is original and store.get_run(owner.run_id).status == "error" + assert caught.value is original + assert store.get_run(owner.run_id).status == "error" def test_public_binding_annotations_resolve_at_runtime(): diff --git a/test/unit_test/headless/test_manual_history_entrypoints.py b/test/unit_test/headless/test_manual_history_entrypoints.py index b8900058a..c338ef83a 100644 --- a/test/unit_test/headless/test_manual_history_entrypoints.py +++ b/test/unit_test/headless/test_manual_history_entrypoints.py @@ -29,10 +29,14 @@ def test_cli_history_and_journal_preserve_stdout_and_link(tmp_path, store, capsy journal = tmp_path / "events.jsonl" assert main(["run", script, "--history", "--var", "seed=hello", "--journal", str(journal)]) == 0 payload = json.loads(capsys.readouterr().out) - assert "history_id" not in payload and "journal_path" not in payload + assert "history_id" not in payload + assert "journal_path" not in payload rows = store.list_runs() - assert len(rows) == 1 and rows[0].source_type == "manual" and rows[0].script_path == script - assert rows[0].status == "ok" and len(store.journals_for_run(rows[0].id)) == 1 + assert len(rows) == 1 + assert rows[0].source_type == "manual" + assert rows[0].script_path == script + assert rows[0].status == "ok" + assert len(store.journals_for_run(rows[0].id)) == 1 def test_cli_custom_history_database_is_explicit(tmp_path, store, capsys): @@ -42,7 +46,8 @@ def test_cli_custom_history_database_is_explicit(tmp_path, store, capsys): capsys.readouterr() check = ac.HistoryStore(custom) try: - assert check.list_runs()[0].status == "ok" and store.list_runs() == [] + assert check.list_runs()[0].status == "ok" + assert store.list_runs() == [] finally: check.close() @@ -64,7 +69,8 @@ def fail(): script = _script(tmp_path, [["AC_manual_cli_fail"]]) assert main(["run", script, "--history"]) == 1 output = capsys.readouterr() - assert json.loads(output.out) and "1 action(s) failed" in output.err + assert json.loads(output.out) + assert "1 action(s) failed" in output.err assert store.list_runs()[0].status == "error" @@ -74,7 +80,8 @@ def fail(): monkeypatch.setitem(executor.event_dict, "AC_manual_cli_preview", fail) script = _script(tmp_path, [["AC_manual_cli_preview"]]) assert main(["run", script, "--history", "--dry-run"]) == 0 - assert "dry-run" in capsys.readouterr().out and store.list_runs()[0].status == "ok" + assert "dry-run" in capsys.readouterr().out + assert store.list_runs()[0].status == "ok" assert store.list_runs()[0].source_id == "cli.preview" @@ -83,7 +90,9 @@ def test_cli_history_database_requires_opt_in(tmp_path, store, capsys, monkeypat monkeypatch.setitem(executor.event_dict, "AC_manual_cli_probe", lambda: effects.append(1)) script = _script(tmp_path, [["AC_manual_cli_probe"]]) assert main(["run", script, "--history-db", str(tmp_path / "unused.sqlite")]) == 1 - assert "requires --history" in capsys.readouterr().err and effects == [] and store._conn is None + assert "requires --history" in capsys.readouterr().err + assert effects == [] + assert store._conn is None def test_named_history_body_defers_values_and_keeps_private_executor(store): @@ -93,8 +102,10 @@ def test_named_history_body_defers_values_and_keeps_private_executor(store): result = private.execute_action([["AC_history_capture", {"body": body, "source_id": "nested"}]], raise_on_error=True) summary = next(iter(result.values())) - assert private.variables.get("message") == "after" and "after" in summary["record"].values() - assert store.get_run(summary["history_id"]).status == "ok" and summary["failed_actions"] == 0 + assert private.variables.get("message") == "after" + assert "after" in summary["record"].values() + assert store.get_run(summary["history_id"]).status == "ok" + assert summary["failed_actions"] == 0 def test_history_command_validation_is_before_any_prior_action(store, monkeypatch): @@ -103,7 +114,8 @@ def test_history_command_validation_is_before_any_prior_action(store, monkeypatc with pytest.raises(ac.AutoControlActionException, match="unknown command"): executor.execute_action([["AC_manual_command_probe"], ["AC_history_capture", {"body": [["AC_unknown_manual_body"]]}]], raise_on_error=True) - assert effects == [] and store._conn is None + assert effects == [] + assert store._conn is None def test_positional_capture_is_rejected_without_body_effects(store): @@ -134,7 +146,8 @@ def test_command_body_data_is_interpolated_once(store, monkeypatch): with execution_scope({"message": "${secrets.PRIVATE}"}): executor.execute_action([["AC_history_capture", {"body": [ ["AC_manual_data_probe", {"value": "${message}"}]]}]], raise_on_error=True) - assert seen == ["${secrets.PRIVATE}"] and store.list_runs()[0].status == "ok" + assert seen == ["${secrets.PRIVATE}"] + assert store.list_runs()[0].status == "ok" def test_mcp_generic_execute_rejects_admin_body_before_manual_history(store): @@ -146,7 +159,8 @@ def test_mcp_generic_execute_rejects_admin_body_before_manual_history(store): "name": tool.name, "arguments": {"actions": [["AC_history_capture", {"body": [["AC_admin_list_hosts"]]}]]}}} with authorization_scope(AuthorizationContext("operator", Role.OPERATOR)): reply = json.loads(server.handle_line(json.dumps(request))) - assert "error" in reply and store._conn is None + assert "error" in reply + assert store._conn is None @pytest.mark.parametrize("signal,rows", [("AC_break", 1), ("AC_continue", 3)]) @@ -155,7 +169,8 @@ def test_normal_loop_signals_do_not_mark_manual_history_failed(store, signal, ro ["AC_history_capture", {"body": [[signal]]}]]}]] executor.execute_action(actions, raise_on_error=True) history = store.list_runs() - assert len(history) == rows and all(row.status == "ok" for row in history) + assert len(history) == rows + assert all(row.status == "ok" for row in history) def test_loop_signal_keeps_preceding_recorded_failure(store, monkeypatch): @@ -164,7 +179,8 @@ def fail(): monkeypatch.setitem(executor.event_dict, "AC_manual_command_fail", fail) executor.execute_action([["AC_loop", {"times": 2, "body": [ ["AC_history_capture", {"body": [["AC_manual_command_fail"], ["AC_break"]]}]]}]]) - assert len(store.list_runs()) == 1 and store.list_runs()[0].status == "error" + assert len(store.list_runs()) == 1 + assert store.list_runs()[0].status == "error" def test_mcp_generic_execute_records_an_explicit_manual_owner(store): @@ -180,4 +196,5 @@ def test_mcp_generic_execute_records_an_explicit_manual_owner(store): assert reply["result"]["isError"] is False data = json.loads(reply["result"]["content"][0]["text"]) assert "history_id" in json.dumps(data) - assert store.list_runs()[0].status == "ok" and store.list_runs()[0].source_type == "manual" + assert store.list_runs()[0].status == "ok" + assert store.list_runs()[0].source_type == "manual" diff --git a/test/unit_test/headless/test_manual_history_gui.py b/test/unit_test/headless/test_manual_history_gui.py index 0fda5cf09..9795fa2e8 100644 --- a/test/unit_test/headless/test_manual_history_gui.py +++ b/test/unit_test/headless/test_manual_history_gui.py @@ -40,7 +40,8 @@ def store(tmp_path, monkeypatch): def test_controls_default_to_no_recording_or_database(app, store): controls = ManualRunControls() try: - assert not controls.record_history.isChecked() and controls.journal_path.text() == "" + assert not controls.record_history.isChecked() + assert controls.journal_path.text() == "" with controls.capture(source_id="test", script_path=""): pass assert store._conn is None @@ -59,11 +60,13 @@ def test_editor_capture_preserves_result_and_links_opted_in_owner(app, store, tm host = _host(output, script_editor=editor, script_history_controls=controls) try: ScriptTabMixin._execute_manual_script(host) - assert json.loads(output.toPlainText()) and len(ac.read_events(journal)) == 2 + assert json.loads(output.toPlainText()) + assert len(ac.read_events(journal)) == 2 rows = store.list_runs() assert len(rows) == int(enabled) if enabled: - assert rows[0].status == "ok" and len(store.journals_for_run(rows[0].id)) == 1 + assert rows[0].status == "ok" + assert len(store.journals_for_run(rows[0].id)) == 1 finally: controls.deleteLater() editor.deleteLater() @@ -96,9 +99,11 @@ def test_builder_records_with_optional_journal_without_result_wrapper(app, store builder._on_run() assert settle(builder._runs, "task") result = json.loads(builder._result.toPlainText()) - assert result and "history_id" not in result + assert result + assert "history_id" not in result row = store.list_runs()[0] - assert row.status == "ok" and len(store.journals_for_run(row.id)) == 1 + assert row.status == "ok" + assert len(store.journals_for_run(row.id)) == 1 finally: builder.deleteLater() @@ -113,7 +118,8 @@ def test_capture_command_form_keeps_body_when_metadata_changes(app): form.load_step(step) form._editors["source_id"].setText("after") result = step_to_action(step) - assert result[1]["source_id"] == "after" and result[1]["body"] == body + assert result[1]["source_id"] == "after" + assert result[1]["body"] == body finally: form.deleteLater() @@ -133,7 +139,8 @@ def test_directory_execution_records_one_batch_and_all_snapshots(app, store, tmp try: ScriptTabMixin._execute_dir(host) assert len(json.loads(output.toPlainText())) == 2 - assert len(store.list_runs()) == 1 and len(ac.read_events(journal)) == 4 + assert len(store.list_runs()) == 1 + assert len(ac.read_events(journal)) == 4 assert store.list_runs()[0].script_path == str(directory) finally: for widget in (controls, source, output): @@ -150,7 +157,8 @@ def test_manual_controls_retranslate_without_resetting_options(app): language_wrapper.reset_language("Japanese") controls.retranslate() assert controls.record_history.text() == "実行履歴に記録" - assert controls.record_history.isChecked() and controls.journal_path.text() == "events.jsonl" + assert controls.record_history.isChecked() + assert controls.journal_path.text() == "events.jsonl" finally: language_wrapper.reset_language(old) controls.deleteLater() diff --git a/test/unit_test/headless/test_mcp_cli.py b/test/unit_test/headless/test_mcp_cli.py index c45725378..ccfcb4946 100644 --- a/test/unit_test/headless/test_mcp_cli.py +++ b/test/unit_test/headless/test_mcp_cli.py @@ -32,10 +32,12 @@ def test_list_tools_with_read_only_drops_destructive(monkeypatch): def test_search_and_single_schema_flags_do_not_start_the_server(monkeypatch): results = json.loads(_capture(monkeypatch, ["--search-tools", "ac_mcp_tool_schema", "--limit", "1"])) - assert len(results) == 1 and results[0]["name"] == "ac_mcp_tool_schema" + assert len(results) == 1 + assert results[0]["name"] == "ac_mcp_tool_schema" assert "inputSchema" not in results[0] schema = json.loads(_capture(monkeypatch, ["--tool-schema", "ac_mcp_tool_schema"])) - assert schema["name"] == "ac_mcp_tool_schema" and "inputSchema" in schema + assert schema["name"] == "ac_mcp_tool_schema" + assert "inputSchema" in schema def test_list_resources_emits_json(monkeypatch): diff --git a/test/unit_test/headless/test_mcp_disclosure_policy.py b/test/unit_test/headless/test_mcp_disclosure_policy.py index edbfbf06e..fb8c80edf 100644 --- a/test/unit_test/headless/test_mcp_disclosure_policy.py +++ b/test/unit_test/headless/test_mcp_disclosure_policy.py @@ -64,7 +64,8 @@ def test_plugin_list_changes_reach_all_open_http_session_streams_once(): try: first, second = host.sessions.create(), host.sessions.create() left, right = [], [] - assert first.attach_stream(left.append) and second.attach_stream(right.append) + assert first.attach_stream(left.append) + assert second.attach_stream(right.append) bridge.register_tool(MCPTool("fixture", "Read", {}, lambda: None, MCPToolAnnotations(read_only=True))) assert len(left) == len(right) == 1 assert json.loads(left[0])["method"] == "notifications/tools/list_changed" @@ -84,7 +85,8 @@ def test_closed_async_acceptance_does_not_recreate_a_session_view(): with server.connection_scope(connection_id="second"): callback() assert server._connection_id == "second" - assert "error" in json.loads(replies[0]) and calls == [] + assert "error" in json.loads(replies[0]) + assert calls == [] assert "first" not in server._disclosure_views server.stop() @@ -109,13 +111,15 @@ def test_targeted_http_notifications_are_not_broadcast_or_duplicated(): try: first, second = host.sessions.create(), host.sessions.create() left, right = [], [] - assert first.attach_stream(left.append) and second.attach_stream(right.append) + assert first.attach_stream(left.append) + assert second.attach_stream(right.append) with bridge.connection_scope(connection_id=first.id, notifier=lambda method, params: left.append( json.dumps({"jsonrpc": "2.0", "method": method, "params": params}))): reply = bridge.handle_line(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "ac_mcp_tools_enable", "arguments": {"names": ["fixture"]}}})) assert json.loads(reply)["result"]["isError"] is False - assert len(left) == 1 and right == [] + assert len(left) == 1 + assert right == [] finally: host.stop() assert bridge._tool_change_sinks == {} @@ -144,7 +148,8 @@ def test_core_discovery_shortcut_still_checks_the_actual_readonly_annotation(): server.configure_tool_disclosure("progressive", read_only=True) reply = server.handle_line(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "ac_mcp_tool_search"}})) - assert "error" in json.loads(reply) and calls == [] + assert "error" in json.loads(reply) + assert calls == [] server.stop() @@ -219,7 +224,8 @@ def test_discovered_call_uses_existing_policy(tmp_path, monkeypatch): assert _call(server, "fixture", {"path": str(tmp_path / "denied.txt")})["result"]["isError"] is True assert _call(server, "fixture", {"reference": "env://FIXTURE_DENIED"})["result"]["isError"] is True assert calls == [{"path": str((root / "ok.txt").resolve())}] - assert confirmations == ["ac_mcp_tools_enable", "fixture"] and len(rate_checks) == 2 + assert confirmations == ["ac_mcp_tools_enable", "fixture"] + assert len(rate_checks) == 2 server.stop() @@ -244,7 +250,8 @@ def test_removed_tool_cannot_run(): server.configure_tool_disclosure("progressive") assert _call(server, "ac_mcp_tools_enable", {"names": ["fixture"]})["result"]["isError"] is False server.unregister_tool("fixture") - assert "error" in _call(server, "fixture") and calls == [] + assert "error" in _call(server, "fixture") + assert calls == [] server.stop() diff --git a/test/unit_test/headless/test_mcp_discovery_gui.py b/test/unit_test/headless/test_mcp_discovery_gui.py index dd647bb5c..d616349b5 100644 --- a/test/unit_test/headless/test_mcp_discovery_gui.py +++ b/test/unit_test/headless/test_mcp_discovery_gui.py @@ -21,7 +21,8 @@ def test_metadata_controls_only_scan_through_actions(monkeypatch): tab = DiagnosticsTab() try: view = tab._mcp_discovery - assert calls == [] and view.findChildren(QPushButton) == [] + assert calls == [] + assert view.findChildren(QPushButton) == [] view.query.setText("fixture") view.read_only.setChecked(True) actions = dict(tab.menu_actions()) @@ -35,7 +36,8 @@ def test_metadata_controls_only_scan_through_actions(monkeypatch): view.profile.setText("ac_screen_size") actions["mcp_disclosure_plan"]() plan = json.loads(view.output.toPlainText()) - assert plan["mode"] == "static" and plan["read_only"] is True + assert plan["mode"] == "static" + assert plan["read_only"] is True assert plan["names"] == ["ac_screen_size"] finally: tab.close() diff --git a/test/unit_test/headless/test_mcp_discovery_index.py b/test/unit_test/headless/test_mcp_discovery_index.py index fc61b4c6a..86330cc4c 100644 --- a/test/unit_test/headless/test_mcp_discovery_index.py +++ b/test/unit_test/headless/test_mcp_discovery_index.py @@ -42,7 +42,8 @@ def test_schema_lookup_is_single_tool_and_detached(): index = ToolIndex(tools) tools[0].input_schema["changed"] = True descriptor = index.get_schema("ac_read") - assert descriptor["name"] == "ac_read" and "changed" not in descriptor["inputSchema"] + assert descriptor["name"] == "ac_read" + assert "changed" not in descriptor["inputSchema"] descriptor["inputSchema"]["corrupt"] = True assert "corrupt" not in index.get_schema("ac_read")["inputSchema"] assert index.snapshot_id == ToolIndex(catalog()).snapshot_id diff --git a/test/unit_test/headless/test_mcp_journal.py b/test/unit_test/headless/test_mcp_journal.py index 718c6daea..5b48c8215 100644 --- a/test/unit_test/headless/test_mcp_journal.py +++ b/test/unit_test/headless/test_mcp_journal.py @@ -34,10 +34,13 @@ def _data(reply): def test_tools_expose_capture_and_sensitive_read_hints(): capture, reader = _tool("ac_journal_capture"), _tool("ac_journal_read") - assert capture.annotations.destructive and not capture.annotations.read_only - assert reader.annotations.read_only and reader.annotations.idempotent + assert capture.annotations.destructive + assert not capture.annotations.read_only + assert reader.annotations.read_only + assert reader.annotations.idempotent readonly = {tool.name for tool in build_default_tool_registry(read_only=True, aliases=False)} - assert reader.name in readonly and capture.name not in readonly + assert reader.name in readonly + assert capture.name not in readonly for tool in (capture, reader): assert tool.input_schema["properties"]["path"]["format"] == "path" @@ -50,13 +53,16 @@ def test_rpc_capture_read_and_metadata_round_trip(tmp_path): "actions": [["AC_get_var", {"name": "message"}]]}) assert captured["result"]["isError"] is False result = _data(captured) - assert result["run_id"] == "rpc" and result["failed_actions"] == 0 + assert result["run_id"] == "rpc" + assert result["failed_actions"] == 0 assert "hello" in result["record"].values() reply = _rpc(server, "ac_journal_read", {"path": str(path), "run_id": "rpc", "limit": 1}) assert reply["result"]["isError"] is False events = _data(reply)["events"] - assert len(events) == 1 and events[0]["status"] == "incomplete" - assert events[0]["device_id"] == "device" and events[0]["session_id"] == "session" + assert len(events) == 1 + assert events[0]["status"] == "incomplete" + assert events[0]["device_id"] == "device" + assert events[0]["session_id"] == "session" def test_recorded_failures_are_tool_errors_with_structured_run_metadata(tmp_path, monkeypatch): @@ -68,8 +74,10 @@ def fail(): reply = _rpc(server, "ac_journal_capture", {"path": str(path), "actions": [["AC_mcp_journal_failure"]]}) assert reply["result"]["isError"] is True result = reply["result"]["structuredContent"] - assert result["failed_actions"] == 1 and result["journal_path"] == str(path.resolve()) - assert result["run_id"] and _data(reply) == result + assert result["failed_actions"] == 1 + assert result["journal_path"] == str(path.resolve()) + assert result["run_id"] + assert _data(reply) == result assert [event.status for event in ac.read_events(path)] == ["incomplete", "error"] @@ -82,7 +90,8 @@ def test_viewers_cannot_list_or_call_private_journal_operations(tmp_path, name): with authorization_scope(AuthorizationContext("viewer", Role.VIEWER)): listed = json.loads(server.handle_line('{"jsonrpc":"2.0","id":2,"method":"tools/list"}')) reply = _rpc(server, name, args) - assert listed["result"]["tools"] == [] and "error" in reply + assert listed["result"]["tools"] == [] + assert "error" in reply assert not (tmp_path / "refused.jsonl").exists() @@ -108,7 +117,8 @@ def test_server_passes_its_policy_to_dynamic_nested_captures(tmp_path): reply = _rpc(server, "ac_journal_capture", {"path": str(allowed / "outer.jsonl"), "variables": {"destination": str(outside)}, "actions": [["AC_journal_capture", { "path": "${destination}", "body": [["AC_set_var", {"name": "x", "value": 1}]]}]]}) - assert reply["result"]["isError"] is True and not outside.exists() + assert reply["result"]["isError"] is True + assert not outside.exists() assert _data(reply)["failed_actions"] == 1 @@ -163,7 +173,8 @@ def test_invalid_fields_are_rejected_before_effects(tmp_path, extra): if name.endswith("capture"): args["actions"] = [["AC_set_var", {"name": "x", "value": 1}]] reply = _rpc(MCPServer(tools=[_tool(name)]), name, args) - assert reply["result"]["isError"] is True and not path.exists() + assert reply["result"]["isError"] is True + assert not path.exists() def test_explicit_object_results_signal_errors_without_changing_json_data(): @@ -171,7 +182,8 @@ def test_explicit_object_results_signal_errors_without_changing_json_data(): assert json.loads(json.dumps(result)) == {"value": 3} tool = MCPTool(name="controlled", description="controlled result", input_schema=schema({}), handler=lambda: result) reply = _rpc(MCPServer(tools=[tool]), "controlled", {}) - assert reply["result"]["isError"] is True and _data(reply) == {"value": 3} + assert reply["result"]["isError"] is True + assert _data(reply) == {"value": 3} plain = MCPTool(name="ordinary", description="ordinary data", input_schema=schema({}), handler=lambda: {"is_error": True}) assert _rpc(MCPServer(tools=[plain]), "ordinary", {})["result"]["isError"] is False @@ -184,7 +196,9 @@ def test_operator_cannot_hide_administration_inside_capture(tmp_path, monkeypatc server = MCPServer(tools=[_tool("ac_journal_capture")]) with authorization_scope(AuthorizationContext("operator", Role.OPERATOR)): reply = _rpc(server, "ac_journal_capture", {"path": str(path), "actions": [["AC_secret_init", {}]]}) - assert "error" in reply and not effects and not path.exists() + assert "error" in reply + assert not effects + assert not path.exists() def test_stdio_capture_uses_the_same_typed_journal_result(tmp_path): @@ -196,5 +210,6 @@ def test_stdio_capture_uses_the_same_typed_journal_result(tmp_path): server = MCPServer(tools=[_tool("ac_journal_capture")]) server.serve_stdio(stdin=io.StringIO(json.dumps(request) + "\n"), stdout=output) reply = next(json.loads(line) for line in output.getvalue().splitlines() if json.loads(line).get("id") == 44) - assert reply["result"]["isError"] is False and reply["result"]["structuredContent"]["run_id"] == "stdio" + assert reply["result"]["isError"] is False + assert reply["result"]["structuredContent"]["run_id"] == "stdio" assert [event.status for event in ac.read_events(path)] == ["incomplete", "ok"] diff --git a/test/unit_test/headless/test_mcp_progressive_sessions.py b/test/unit_test/headless/test_mcp_progressive_sessions.py index bc43a109f..32e156be9 100644 --- a/test/unit_test/headless/test_mcp_progressive_sessions.py +++ b/test/unit_test/headless/test_mcp_progressive_sessions.py @@ -26,7 +26,8 @@ def test_enable_is_session_local_and_emits_one_change(): first.enable(["fixture_0"]) first.enable(["fixture_0"]) assert first.state()["enabled"] == ["fixture_0"] - assert second.state()["enabled"] == [] and events == ["changed"] + assert second.state()["enabled"] == [] + assert events == ["changed"] assert first.state()["snapshot_id"] != second.state()["snapshot_id"] @@ -128,7 +129,8 @@ def test_stateless_requests_use_a_fixed_profile_and_create_no_session_views(): page = request(server, "tools/list", {"_meta": meta})["result"] assert "fixture_0" in {item["name"] for item in page["tools"]} assert "fixture_1" not in {item["name"] for item in page["tools"]} - assert "nextCursor" not in page and server._disclosure_views == {} + assert "nextCursor" not in page + assert server._disclosure_views == {} result = request(server, "tools/call", {"_meta": meta, "name": "ac_mcp_tools_enable", "arguments": {"names": ["fixture_1"]}}) assert result["result"]["isError"] is True @@ -160,7 +162,9 @@ def rpc(method, params=None, session=None): try: first, _ = rpc("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}}) second, _ = rpc("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}}) - assert first and second and first != second + assert first + assert second + assert first != second _, enabled = rpc("tools/call", {"name": "ac_mcp_tools_enable", "arguments": {"names": ["fixture_0"]}}, first) assert enabled["result"]["isError"] is False @@ -168,7 +172,8 @@ def rpc(method, params=None, session=None): _, second_page = rpc("tools/list", session=second) assert "fixture_0" in {item["name"] for item in first_page["result"]["tools"]} assert "fixture_0" not in {item["name"] for item in second_page["result"]["tools"]} - assert first in bridge._disclosure_views and second in bridge._disclosure_views + assert first in bridge._disclosure_views + assert second in bridge._disclosure_views finally: server.stop() assert bridge._disclosure_views == {} diff --git a/test/unit_test/headless/test_rbac_deferred_callbacks.py b/test/unit_test/headless/test_rbac_deferred_callbacks.py index d23d805ae..9f7a925ba 100644 --- a/test/unit_test/headless/test_rbac_deferred_callbacks.py +++ b/test/unit_test/headless/test_rbac_deferred_callbacks.py @@ -94,7 +94,8 @@ def test_callback_runs_have_fresh_variables_and_clear_unscoped_authority(kind, c fire() assert len(seen) == 1 assert seen[0][0] is None - assert seen[0][1] is not None and seen[0][1] is not outer + assert seen[0][1] is not None + assert seen[0][1] is not outer @pytest.mark.parametrize("kind", KINDS) diff --git a/test/unit_test/headless/test_rbac_sensitive_read_tools.py b/test/unit_test/headless/test_rbac_sensitive_read_tools.py index 2d1f745d0..d111e569d 100644 --- a/test/unit_test/headless/test_rbac_sensitive_read_tools.py +++ b/test/unit_test/headless/test_rbac_sensitive_read_tools.py @@ -66,7 +66,8 @@ def test_sensitive_read_call_is_refused_before_handler_invocation(name): assert reply["error"]["code"] == FORBIDDEN_CODE assert called == [] else: - assert names == [name] and "result" in reply + assert names == [name] + assert "result" in reply assert called == [True, True] @@ -109,7 +110,8 @@ def test_http_user_tokens_cannot_bypass_sensitive_tool_policy(tmp_path): assert response.status == 200 reply = json.loads(response.read()) if role == Role.VIEWER: - assert reply["error"]["code"] == FORBIDDEN_CODE and called == [] + assert reply["error"]["code"] == FORBIDDEN_CODE + assert called == [] else: assert "result" in reply finally: diff --git a/test/unit_test/headless/test_rbac_server_wiring.py b/test/unit_test/headless/test_rbac_server_wiring.py index 68f705422..03cd8907e 100644 --- a/test/unit_test/headless/test_rbac_server_wiring.py +++ b/test/unit_test/headless/test_rbac_server_wiring.py @@ -441,4 +441,5 @@ def test_default_registry_offers_a_viewer_only_read_only_tools(users): and capability_for_tool(tool.name, True) == Capability.READ_SCREEN} assert {"ac_get_mouse_position", "ac_screen_size"} <= names assert not {"ac_get_clipboard", "ac_sql_query", "ac_load_dotenv", "ac_jwt_encode"} & names - assert "ac_execute_actions" not in names and "ac_click_mouse" not in names + assert "ac_execute_actions" not in names + assert "ac_click_mouse" not in names diff --git a/test/unit_test/headless/test_remote_clipboard_delivery_gui.py b/test/unit_test/headless/test_remote_clipboard_delivery_gui.py index 61c336832..b552f7362 100644 --- a/test/unit_test/headless/test_remote_clipboard_delivery_gui.py +++ b/test/unit_test/headless/test_remote_clipboard_delivery_gui.py @@ -122,7 +122,8 @@ def set(self, content): try: enqueue(peer, kind, value) qapp.processEvents() - assert applied == [(kind, value)] and sent == [] + assert applied == [(kind, value)] + assert sent == [] native.text_value = 'deliberate repeat' native.dataChanged.emit() assert sent == [] @@ -171,7 +172,8 @@ def interrupted(_value): delivery = ClipboardDelivery(panel._own_viewer(), 'text', 'controlled', DeferredAuthorization.capture()) with pytest.raises(type(original)) as caught: panel._on_clipboard_main(delivery) - assert caught.value is original and applied == [] + assert caught.value is original + assert applied == [] finally: panel._disconnect() panel.deleteLater() @@ -244,7 +246,8 @@ def registered(panel, *args, **kwargs): QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete) qapp.processEvents() gc.collect() - assert created and created[0]() is None, 'the parametrized exception retained a deleted native Qt panel' + assert created, 'the parametrized exception retained a deleted native Qt panel' + assert created[0]() is None, 'the parametrized exception retained a deleted native Qt panel' def test_disconnected_clipboard_callback_does_not_retain_its_own_viewer_until_gc(qapp): diff --git a/test/unit_test/headless/test_remote_clipboard_lifecycle.py b/test/unit_test/headless/test_remote_clipboard_lifecycle.py index cf11608e1..2e59cefee 100644 --- a/test/unit_test/headless/test_remote_clipboard_lifecycle.py +++ b/test/unit_test/headless/test_remote_clipboard_lifecycle.py @@ -50,9 +50,11 @@ def test_buffered_old_viewer_clipboard_is_rejected_after_disconnect_or_reconnect finally: channel.release.set() worker.join(5) - assert not worker.is_alive() and channel.closed + assert not worker.is_alive() + assert channel.closed assert applied == [], 'old buffered clipboard reached the replacement/current callback' - assert results == [False] and viewer.connected is replacement + assert results == [False] + assert viewer.connected is replacement def host_handler(payload, applied): @@ -106,7 +108,8 @@ def test_clipboard_receiver_does_not_own_its_peer_without_a_queued_delivery(): receiver.bind(peer) reference = weakref.ref(peer) del peer - assert reference() is None and pending == [] + assert reference() is None + assert pending == [] receiver('text', 'retired') assert pending == [] @@ -123,9 +126,11 @@ def test_queued_clipboard_receiver_keeps_the_original_peer_and_authority_until_d receiver.bind(peer) reference = weakref.ref(peer) receiver('text', 'original') - assert pending[0].peer is peer and pending[0].authority is authority + assert pending[0].peer is peer + assert pending[0].authority is authority del peer - assert reference() is not None and pending[0].data == 'original' + assert reference() is not None + assert pending[0].data == 'original' pending.clear() assert reference() is None @@ -186,7 +191,8 @@ def replaced(data): monkeypatch.setattr(viewer_module, 'encode_' + kind, replaced) with pytest.raises(ConnectionError): getattr(viewer, 'send_clipboard_' + kind)(value) - assert old == [] and new == [], 'a clipboard send adopted the replacement transport' + assert old == [], 'a clipboard send adopted the replacement transport' + assert new == [], 'a clipboard send adopted the replacement transport' @pytest.mark.parametrize('kind,value', [('text', 'text'), ('image', b'image')]) @@ -263,7 +269,9 @@ def broadcast(kind, payload): for _ in range(2): assert getattr(host, 'broadcast_clipboard_' + kind)(value) == 2 assert first[1] == second[1] == [(kind, value)] * 2 - assert applied == [(kind, value)] * 2 and len(first[2]) == 2 and second[2] == [] + assert applied == [(kind, value)] * 2 + assert len(first[2]) == 2 + assert second[2] == [] assert len(first[3]) == len(second[3]) == 2 @@ -279,4 +287,5 @@ def failed(*_args): receiver = host_handler(encode_text('text'), []) receiver._host._apply_clipboard = failed receiver._handle_clipboard_payload(encode_text('text')) - assert 'clipboard' in caplog.text and str(error) in caplog.text + assert 'clipboard' in caplog.text + assert str(error) in caplog.text diff --git a/test/unit_test/headless/test_remote_host_access_audit.py b/test/unit_test/headless/test_remote_host_access_audit.py index 8bb7bdb10..95ab51aee 100644 --- a/test/unit_test/headless/test_remote_host_access_audit.py +++ b/test/unit_test/headless/test_remote_host_access_audit.py @@ -90,7 +90,8 @@ def hold_after_terminal_reply(channel, kind, payload): kind, _payload = read_message(first) else: first, kind = _connect(host, token='wrong-token' if reason == 'bad_token' else TOKEN) - assert kind is MessageType.AUTH_FAIL and entered.wait(5) + assert kind is MessageType.AUTH_FAIL + assert entered.wait(5) host._on_pending_viewer = None second, kind = _connect(host) assert kind is MessageType.AUTH_OK diff --git a/test/unit_test/headless/test_rest_auth_compatibility.py b/test/unit_test/headless/test_rest_auth_compatibility.py index 0a0a2ee72..eb9321758 100644 --- a/test/unit_test/headless/test_rest_auth_compatibility.py +++ b/test/unit_test/headless/test_rest_auth_compatibility.py @@ -88,7 +88,8 @@ def test_registry_reports_environment_configured_rbac(tmp_path, monkeypatch): registry = _RestApiRegistry() try: status = registry.start(port=0, enable_audit=False) - assert status["rbac_enabled"] is True and status["token"] is None + assert status["rbac_enabled"] is True + assert status["token"] is None finally: registry.stop() @@ -130,7 +131,8 @@ def test_gui_restores_shared_token_controls_after_rbac_stops(qapp, monkeypatch): assert not tab._token_input.isEnabled() status.update(running=False, rbac_enabled=False) tab._refresh_status() - assert tab._token_input.isEnabled() and tab._token_value.text() == "-" + assert tab._token_input.isEnabled() + assert tab._token_value.text() == "-" status.update(running=True, token="new-shared") tab._refresh_status() assert tab._token_value.text() == "new-shared" diff --git a/test/unit_test/headless/test_runtime_secret_boundaries.py b/test/unit_test/headless/test_runtime_secret_boundaries.py index 461d7acd5..55cab7d31 100644 --- a/test/unit_test/headless/test_runtime_secret_boundaries.py +++ b/test/unit_test/headless/test_runtime_secret_boundaries.py @@ -71,7 +71,8 @@ def test_cli_errors_are_masked_through_the_outer_error_handler(legacy, output, s from je_auto_control.cli import main assert main(["run", str(script)]) == 1 error = capsys.readouterr().err - assert FAKE not in output.getvalue() and FAKE not in error + assert FAKE not in output.getvalue() + assert FAKE not in error assert "private failure: ***" in error @@ -88,7 +89,8 @@ def test_real_local_rest_request_keeps_the_mask_until_error_handling_finishes(ou payload = json.loads(response.read()) assert response.status == (200 if strict else 500) if strict: - assert payload["ok"] is False and FAKE in payload["error"] + assert payload["ok"] is False + assert FAKE in payload["error"] assert FAKE not in output.getvalue() finally: connection.close() @@ -171,7 +173,8 @@ def test_background_run_owner_masks_history_and_outer_error_logs(kind, output, s assert FAKE not in trigger.last_error row = history.list_runs()[0] assert row.status == STATUS_ERROR - assert FAKE not in row.error_text and "***" in row.error_text + assert FAKE not in row.error_text + assert "***" in row.error_text assert FAKE not in output.getvalue() @@ -195,7 +198,8 @@ def probe(value): monkeypatch.setattr(test_record_instance, "init_record", True) monkeypatch.setattr(test_record_instance, "test_record_list", []) result = executor.execute_action(ACTIONS) - assert list(result.values()) == [FAKE] and source == {"value": FAKE} + assert list(result.values()) == [FAKE] + assert source == {"value": FAKE} assert FAKE not in json.dumps(test_record_instance.test_record_list) assert test_record_instance.test_record_list[0]["local_param"]["value"] == "***" @@ -213,7 +217,8 @@ def __repr__(self): result = scrub_secret_data(source) assert result == {"value": "***", "opaque": "", "tuple": ("***", 1, True, None), "cycle": "", "": "visible"} - assert source["value"] == FAKE and source["cycle"] is source + assert source["value"] == FAKE + assert source["cycle"] is source assert FAKE not in json.dumps(result) diff --git a/test/unit_test/headless/test_runtime_secret_callbacks.py b/test/unit_test/headless/test_runtime_secret_callbacks.py index 5bb720c41..e47e0776c 100644 --- a/test/unit_test/headless/test_runtime_secret_callbacks.py +++ b/test/unit_test/headless/test_runtime_secret_callbacks.py @@ -42,7 +42,8 @@ def test_watchdog_masks_both_detection_and_action_failures(output, phase): owner = PopupWatchdog() owner.add_rule(WatchdogRule("private", _fail if phase == "matcher" else lambda: True, _fail)) assert owner.check_once() == 0 - assert FAKE not in output.getvalue() and "private callback failure: ***" in output.getvalue() + assert FAKE not in output.getvalue() + assert "private callback failure: ***" in output.getvalue() @pytest.mark.parametrize("phase", ["predicate", "handler"]) @@ -52,7 +53,8 @@ def test_observer_masks_predicate_and_handler_failures(output, phase): owner.add("private", _fail if phase == "predicate" else lambda: True, _fail) events = owner.poll_once() assert len(events) == (0 if phase == "predicate" else 1) - assert FAKE not in output.getvalue() and "private callback failure: ***" in output.getvalue() + assert FAKE not in output.getvalue() + assert "private callback failure: ***" in output.getvalue() @pytest.mark.parametrize("phase", ["trigger", "callback"]) @@ -64,7 +66,8 @@ def callback(): raise RuntimeError("private callback failure: " + FAKE) result = owner.callback_function("AC_probe", callback) assert result == (None if phase == "trigger" else FAKE) - assert FAKE not in output.getvalue() and "private callback failure: ***" in output.getvalue() + assert FAKE not in output.getvalue() + assert "private callback failure: ***" in output.getvalue() def test_callback_calls_do_not_retain_an_earlier_invocations_mask(output): @@ -103,7 +106,8 @@ def test_direct_observer_callback_boundary_also_masks_its_own_error(output): from je_auto_control.utils.observer.observer import ScreenObserver, WatchRule owner = ScreenObserver() owner._fire(WatchRule("private", lambda: True, _fail), "appear", True) - assert FAKE not in output.getvalue() and "private callback failure: ***" in output.getvalue() + assert FAKE not in output.getvalue() + assert "private callback failure: ***" in output.getvalue() @pytest.mark.parametrize("kind", ["watchdog", "observer"]) @@ -120,4 +124,5 @@ def later_failure(*_args): owner = ScreenObserver() owner.add("private", _resolve, later_failure) assert len(owner.poll_once()) == 1 - assert FAKE not in output.getvalue() and "later callback failure: ***" in output.getvalue() + assert FAKE not in output.getvalue() + assert "later callback failure: ***" in output.getvalue() diff --git a/test/unit_test/headless/test_runtime_secret_logs.py b/test/unit_test/headless/test_runtime_secret_logs.py index 08badd58e..543c8579e 100644 --- a/test/unit_test/headless/test_runtime_secret_logs.py +++ b/test/unit_test/headless/test_runtime_secret_logs.py @@ -56,7 +56,8 @@ def fail(value): else: assert FAKE in next(iter(executor.execute_action(actions).values())) assert FAKE not in output.getvalue() - assert "Traceback" in output.getvalue() and "ValueError" in output.getvalue() + assert "Traceback" in output.getvalue() + assert "ValueError" in output.getvalue() @pytest.mark.parametrize("block", ["loop", "parallel", "dag"]) @@ -138,7 +139,8 @@ def test_closed_mask_cannot_retain_values_via_an_inherited_binding(): scope = current_secret_scope() remember_secret(FAKE) assert scope.scrub(FAKE) == "***" - assert not scope.active and not scope.has_values + assert not scope.active + assert not scope.has_values with bound_secret_scope(scope): remember_secret("later-private-value") assert current_secret_scope() is None @@ -163,7 +165,8 @@ def test_filter_masks_cached_exception_stack_and_unformattable_records(): record.stack_info = "stack " + FAKE assert SecretLogFilter().filter(record) assert record.getMessage() == "" - assert record.exc_text == "cached ***" and record.stack_info == "stack ***" + assert record.exc_text == "cached ***" + assert record.stack_info == "stack ***" def test_an_unformattable_outcome_cannot_abort_execution(output, monkeypatch): diff --git a/test/unit_test/headless/test_scoped_transport_io.py b/test/unit_test/headless/test_scoped_transport_io.py index d1d43a15e..b0e384d0e 100644 --- a/test/unit_test/headless/test_scoped_transport_io.py +++ b/test/unit_test/headless/test_scoped_transport_io.py @@ -43,7 +43,8 @@ def test_scoped_read_retains_fragmented_message_bytes_across_poll_timeouts(): reader._socket = incoming with cancellation_scope(CancellationToken(1)): message = reader.read_message(time.monotonic()+1) - assert message.body == ['controlled payload'] and reader._buffer == b'' + assert message.body == ['controlled payload'] + assert reader._buffer == b'' assert all(0 < value <= 0.1 for value in incoming.timeouts) @@ -71,7 +72,8 @@ def send(self, data): with cancellation_scope(CancellationToken(1)): cancellable_io.send(sender, b'abcdef') assert b''.join(sent) == b'abcdef' - assert attempted == [b'abcdef', b'cdef', b'cdef'] and sender.timeout == 1.0 + assert attempted == [b'abcdef', b'cdef', b'cdef'] + assert sender.timeout == 1.0 def test_repeated_receive_polls_do_not_restart_the_total_deadline(monkeypatch): @@ -142,7 +144,8 @@ def communicate(self, timeout): with cancellation_scope(CancellationToken(1)), pytest.raises(CancelledError) as caught: cancellable_process.run_capture_helper(['controlled'], 10) assert caught.value is primary - assert calls == ['signal', 'reaped', 'close'] and process.stderr.closed + assert calls == ['signal', 'reaped', 'close'] + assert process.stderr.closed finally: primary.__traceback__ = None diff --git a/test/unit_test/headless/test_self_healing_boundaries.py b/test/unit_test/headless/test_self_healing_boundaries.py index 1738e6453..37fe9ce41 100644 --- a/test/unit_test/headless/test_self_healing_boundaries.py +++ b/test/unit_test/headless/test_self_healing_boundaries.py @@ -125,7 +125,8 @@ def image(*_args, **_kwargs): with secret_log_scope(): remember_secret(secret) outcome = self_heal_locate(template_path=secret, description=secret, log=log) - assert outcome.found and outcome.coordinates == (4, 5) + assert outcome.found + assert outcome.coordinates == (4, 5) assert outcome.template_path == outcome.description == secret assert secret in outcome.image_error stored = log.list_events()[0] diff --git a/test/unit_test/headless/test_self_healing_evaluation.py b/test/unit_test/headless/test_self_healing_evaluation.py index 864f1a7f8..bd751d7f6 100644 --- a/test/unit_test/headless/test_self_healing_evaluation.py +++ b/test/unit_test/headless/test_self_healing_evaluation.py @@ -87,7 +87,8 @@ def test_real_template_dataset_and_versioned_acceptance(): assert actual.recovery.value is None attempt = next(row for row in report.attempts if row.version == "new" and row.sample_id.startswith("negative")) assert attempt.candidate.coordinates == (-66, -29) - assert attempt.correct is True and attempt.step_id == "scaled-submit" + assert attempt.correct is True + assert attempt.step_id == "scaled-submit" def test_image_miss_and_vlm_use_same_crop_and_transform_without_capture(monkeypatch): @@ -114,8 +115,10 @@ def forbidden(*_args, **_kwargs): vlm = VLMFrameLocator(Backend(), "submit", model="fake") image = TemplateFrameLocator((DATASET / "fixtures/old.png").read_bytes(), .99, vlm) result = image.locate(sample) - assert result.coordinates == (-66, -29) and result.method == "vlm" - assert result.verified is None and result.fallback_used + assert result.coordinates == (-66, -29) + assert result.method == "vlm" + assert result.verified is None + assert result.fallback_used assert [name for name, _ in result.timings_ms] == ["image", "fallback.vlm"] with Image.open(io.BytesIO(frame)) as original, Image.open(io.BytesIO(seen[0])) as actual: assert actual.size == (24, 20) @@ -128,8 +131,10 @@ def test_measured_percentiles_costs_and_verified_recovery(monkeypatch): locator = FixedLocator(LocatorCandidate((4, 5), "vlm", fallback_used=True, verified=True, cost=.01)) samples = [EvaluationSample(str(index), png(), expected_box=(0, 0, 10, 10)) for index in range(2)] version = evaluate_locators(samples, {"v1": locator}).versions["v1"] - assert version.p50_ms == 1500 and version.p95_ms == 1950 - assert version.cost_total == .02 and version.cost_known == 2 + assert version.p50_ms == 1500 + assert version.p95_ms == 1950 + assert version.cost_total == .02 + assert version.cost_known == 2 assert version.recovery.to_dict() == {"numerator": 2, "denominator": 2, "value": 1} @@ -157,10 +162,12 @@ def locate(self, sample): samples = [EvaluationSample("first", png()), EvaluationSample("second", png())] with pytest.raises(RuntimeError) as caught: evaluate_locators(samples, {"v1": Failure()}) - assert caught.value is signal and seen == ["first"] + assert caught.value is signal + assert seen == ["first"] with pytest.raises(RuntimeError) as caught: evaluate_locators(samples, {"v1": Failure()}, observer=lambda _: (_ for _ in ()).throw(signal)) - assert caught.value is signal and seen == ["first"] + assert caught.value is signal + assert seen == ["first"] def test_exports_escape_html_and_contain_provenance_without_images(tmp_path): @@ -169,9 +176,11 @@ def test_exports_escape_html_and_contain_provenance_without_images(tmp_path): json_path = write_healing_report(report, tmp_path / "report.json") html_path = write_healing_report(report, tmp_path / "report.html") payload = json.loads(json_path.read_text(encoding="utf-8")) - assert payload["attempts"][0]["run_id"] == "run" and "frame" not in payload["attempts"][0] + assert payload["attempts"][0]["run_id"] == "run" + assert "frame" not in payload["attempts"][0] html = html_path.read_text(encoding="utf-8") - assert "