Files
cleveragents-core/features/steps/session_service_coverage_steps.py
T
freemo 02250473ad fix(ci): restore all CI quality gates to passing on master
Fix all failing CI quality gates (lint, unit_tests, format) without
suppressing any quality enforcement.

Root causes and fixes:

1. Format: features/steps/plan_namespaced_name_tdd_steps.py had trailing
   whitespace; fixed by running ruff format.

2. Unit tests - A2A JSON-RPC 2.0 migration (commit 9c6d6915) renamed
   A2aRequest fields (operation→method, request_id→id, a2a_version→jsonrpc)
   and A2aResponse fields (status+data→result, request_id→id) but did not
   update all step files and feature files:
   - a2a_jsonrpc_wire_format_steps.py: added use_step_matcher('re') and
     reset to 'parse' at end to prevent parallel test interference
   - a2a_facade_wiring_steps.py: updated operation= to method=, .status/.data
     to .result
   - a2a_facade_steps.py: updated request_id→id, a2a_version→jsonrpc,
     A2aResponse(request_id=..., status=...) to new API
   - m6_facade_steps.py: updated all old API usage
   - devcontainer_cleanup_steps.py: updated A2aRequest(operation=...)
   - plan_prompt_command_steps.py: updated A2aRequest(operation=...)
   - wf03_plan_prompt_confidence_steps.py: updated A2aRequest(operation=...)
   - consolidated_misc.feature: updated old A2aRequest/A2aResponse scenarios

3. Unit tests - Session CLI output changed (commit 0d5d9cf0 and others):
   - 'Session Created' → 'Session created' (lowercase)
   - 'Session Details' → 'Session Summary'
   - 'Sessions (N total)' → 'Sessions'
   - session list JSON: top-level 'total' → nested 'summary.total'
   - Fixed in: session_cli.feature, session_cli_coverage_boost.feature,
     session_cli_uncovered_branches.feature, session_list_error.feature,
     tdd_session_create_persist_steps.py

4. Unit tests - Plan list output changed (commit 1a07a891):
   - 'V3 Lifecycle Plans' → 'Plans'
   - 'Lifecycle Plans' → 'Plans'
   - Name column removed (restored in source)
   - Invariants column removed (restored in source)
   - Project truncation removed (restored in source)
   - Fixed in: plan_cli_cancel_revert_coverage.feature,
     plan_lifecycle_cli_coverage.feature, plan_cli_coverage_boost_steps.py,
     plan.py (source code restored)

5. Unit tests - Plan apply command now requires ULID (commit 300a5d6d):
   - plan_cli_coverage_r3.feature: updated 'PLAN-001' to valid ULID
   - plan_cli_coverage_r3_steps.py: added --yes flag, added new step for
     no-eligible-plans path

6. Unit tests - Various source code bugs:
   - ThoughtBlock: converted from @dataclass to Pydantic BaseModel
     (architecture test requires all dataclasses to use Pydantic)
   - session.py: added DatabaseError handling to export, import, tell commands
   - database.py: fixed rollback_to() to reuse checkpoint connection for writes
   - database.py: added _get_checkpoint_conn() helper
   - check-tls-cert.py: fixed SSLCertVerificationError.reason AttributeError

7. Unit tests - Test step bugs:
   - error_recovery_coverage_boost_steps.py: fixed invalid ULID _PLAN_ID
   - session_service_coverage_steps.py: fixed 'sha256:' prefix bug in checksum
   - database_models_new_coverage_steps.py: added 'name' field to session mock
   - async_audit_recording_steps.py: fixed Settings(audit_async=False) via env var
   - coverage_threshold_config_steps.py: added --coverage-min pattern support
   - m5_acms_smoke_steps.py: updated usage hint text
   - actor_cli_yaml_steps.py: updated 'Removed actor' → 'Actor removed'
   - aimodelscredentials_steps.py: set context.imported_class in import step
   - domain_base_model.feature: added missing 'When I examine model_config' step
   - tui_first_run_steps.py: fixed module reload to restore cleveragents.tui.*
     modules after test (prevented patch interference in subsequent tests)
   - tui_first_run_steps.py: added set_search('') step for empty string
   - resource_handler_base_coverage_r3_steps.py: use _MinimalHandler instead
     of DatabaseResourceHandler for NotImplementedError tests
   - resource_handler_crud.feature: updated to test new DatabaseHandler behavior
   - resource_handler_sandbox.feature: updated to test new DatabaseHandler behavior
   - tdd_json_decode_crash_persistence.feature: fixed @tdd_bug → @tdd_issue tags

8. Parallel test interference:
   - All step files using use_step_matcher('re') now reset to 'parse' at end
     to prevent global matcher state leaking to subsequent step files
2026-04-04 20:38:16 +00:00

270 lines
11 KiB
Python

"""Step definitions for session_service_coverage.feature.
These steps target specific uncovered lines in
src/cleveragents/application/services/session_service.py:
- Lines 97-98: create() exception branch when event_bus.emit raises
- Lines 139-146: delete() emitting ENTITY_DELETED when event_bus is present
- Lines 150-151: delete() exception branch when event_bus.emit raises
- Line 217: export_session() SessionNotFoundError
- Line 248: import_session() missing checksum
- Lines 310-311: import_session() invalid message data (KeyError/ValueError)
"""
import hashlib
import json
from unittest.mock import MagicMock
from behave import given, then, when
from cleveragents.application.services.session_service import PersistentSessionService
from cleveragents.domain.models.core.session import (
EXPORT_SCHEMA_VERSION,
SessionImportError,
SessionNotFoundError,
)
from cleveragents.infrastructure.events.types import EventType
# ---------------------------------------------------------------------------
# Background
# ---------------------------------------------------------------------------
@given("the session service module is imported")
def step_session_service_module_imported(context):
"""Verify the module is importable."""
assert PersistentSessionService is not None
# ---------------------------------------------------------------------------
# Shared setup helpers
# ---------------------------------------------------------------------------
@given("a mock session repository and message repository")
def step_mock_repos(context):
"""Create mock repositories."""
context.mock_session_repo = MagicMock()
context.mock_message_repo = MagicMock()
@given("a persistent session service without event bus")
def step_service_no_event_bus(context):
"""Create service without event bus."""
context.service = PersistentSessionService(
session_repo=context.mock_session_repo,
message_repo=context.mock_message_repo,
event_bus=None,
)
# ---------------------------------------------------------------------------
# Lines 97-98: create() with failing event bus
# ---------------------------------------------------------------------------
@given("an event bus that raises on emit")
def step_failing_event_bus(context):
"""Create an event bus whose emit method raises RuntimeError."""
context.failing_event_bus = MagicMock()
context.failing_event_bus.emit.side_effect = RuntimeError("emit exploded")
@given("a persistent session service with the failing event bus")
def step_service_with_failing_event_bus(context):
"""Create a service wired to the failing event bus."""
context.service = PersistentSessionService(
session_repo=context.mock_session_repo,
message_repo=context.mock_message_repo,
event_bus=context.failing_event_bus,
)
@when('sesscov I create a session with actor name "{actor_name}"')
def step_create_session(context, actor_name):
"""Call create() and store the result."""
context.created_session = context.service.create(actor_name=actor_name)
@then("the session should be returned successfully")
def step_verify_session_returned(context):
"""Verify a session object was returned despite the emit failure."""
assert context.created_session is not None
assert context.created_session.session_id is not None
@then("the session repository should have recorded one create call")
def step_verify_repo_create_called(context):
"""Verify the repo create method was called exactly once."""
assert context.mock_session_repo.create.call_count == 1
# ---------------------------------------------------------------------------
# Lines 139-146: delete() with recording event bus (emit succeeds)
# ---------------------------------------------------------------------------
@given("a recording event bus")
def step_recording_event_bus(context):
"""Create an event bus that records emitted events."""
context.recording_event_bus = MagicMock()
context.recording_event_bus.emitted_events = []
def record_emit(event):
context.recording_event_bus.emitted_events.append(event)
context.recording_event_bus.emit.side_effect = record_emit
@given("a persistent session service with the recording event bus")
def step_service_with_recording_event_bus(context):
"""Create a service wired to the recording event bus."""
context.service = PersistentSessionService(
session_repo=context.mock_session_repo,
message_repo=context.mock_message_repo,
event_bus=context.recording_event_bus,
)
@given("the session repository will return True for delete")
def step_repo_delete_returns_true(context):
"""Configure the mock session repo to indicate successful deletion."""
context.mock_session_repo.delete.return_value = True
@when('I delete session "{session_id}"')
def step_delete_session(context, session_id):
"""Call delete() and capture any exception."""
context.delete_error = None
try:
context.service.delete(session_id)
except Exception as exc:
context.delete_error = exc
@then("the recording event bus should have received an ENTITY_DELETED event")
def step_verify_entity_deleted_event(context):
"""Verify the recording event bus captured an ENTITY_DELETED event."""
assert context.delete_error is None, (
f"Expected no error from delete, got {context.delete_error!r}"
)
emitted = context.recording_event_bus.emitted_events
assert len(emitted) == 1, f"Expected 1 emitted event, got {len(emitted)}"
event = emitted[0]
assert event.event_type == EventType.ENTITY_DELETED
# ---------------------------------------------------------------------------
# Lines 150-151: delete() with failing event bus
# ---------------------------------------------------------------------------
@then("no exception should be raised from delete")
def step_verify_no_delete_exception(context):
"""Verify delete completed without propagating an exception."""
assert context.delete_error is None, (
f"Expected no error, got {context.delete_error!r}"
)
# ---------------------------------------------------------------------------
# Line 217: export_session() — session not found
# ---------------------------------------------------------------------------
@given("the session repository returns None for get_by_id")
def step_repo_get_returns_none(context):
"""Configure the mock session repo to return None for any get_by_id."""
context.mock_session_repo.get_by_id.return_value = None
@when('I export session "{session_id}"')
def step_export_session(context, session_id):
"""Call export_session() and capture any exception."""
context.export_error = None
try:
context.export_result = context.service.export_session(session_id)
except Exception as exc:
context.export_error = exc
@then('a SessionNotFoundError should be raised with message containing "{text}"')
def step_verify_session_not_found_error(context, text):
"""Verify a SessionNotFoundError was raised with the expected text."""
assert context.export_error is not None, "Expected an error but none was raised"
assert isinstance(context.export_error, SessionNotFoundError), (
f"Expected SessionNotFoundError, got {type(context.export_error).__name__}"
)
assert text in str(context.export_error), (
f"Expected '{text}' in error message, got '{context.export_error}'"
)
# ---------------------------------------------------------------------------
# Line 248: import_session() — missing checksum
# ---------------------------------------------------------------------------
@when("I import session data with valid schema version but no checksum")
def step_import_missing_checksum(context):
"""Call import_session() with data that has schema_version but no checksum."""
data = {
"schema_version": EXPORT_SCHEMA_VERSION,
"session_id": "01JTESTIMPORT000000000000000",
"actor_name": None,
"messages": [],
# Note: no "checksum" key at all
}
context.import_error = None
try:
context.import_result = context.service.import_session(data)
except Exception as exc:
context.import_error = exc
@then('a SessionImportError should be raised with message containing "{text}"')
def step_verify_session_import_error(context, text):
"""Verify a SessionImportError was raised with the expected text."""
assert context.import_error is not None, "Expected an error but none was raised"
assert isinstance(context.import_error, SessionImportError), (
f"Expected SessionImportError, got {type(context.import_error).__name__}"
)
assert text in str(context.import_error), (
f"Expected '{text}' in error message, got '{context.import_error}'"
)
# ---------------------------------------------------------------------------
# Lines 310-311: import_session() — invalid message data
# ---------------------------------------------------------------------------
@when("I import session data with valid checksum but invalid message fields")
def step_import_invalid_messages(context):
"""Create import data with a valid checksum but messages that lack required keys.
The messages list contains an entry missing the required "role" key,
which will cause a KeyError during parsing and trigger lines 310-311.
"""
data_without_checksum = {
"schema_version": EXPORT_SCHEMA_VERSION,
"session_id": "01JTESTIMPORT000000000000000",
"actor_name": None,
"namespace": "local",
"linked_plan_ids": [],
"token_usage": {
"input_tokens": 0,
"output_tokens": 0,
"estimated_cost": 0.0,
},
"metadata": {},
"created_at": "2025-01-01T00:00:00",
"updated_at": "2025-01-01T00:00:00",
"messages": [
{
# Missing "role" key — will cause KeyError at line 272
"content": "hello",
"sequence": 0,
"timestamp": "2025-01-01T00:00:00",
}
],
}
# Compute a valid checksum so that checksum verification passes
# Note: import_session expects just the hex digest in data["checksum"],
# then prepends "sha256:" internally for comparison.
canonical = json.dumps(data_without_checksum, sort_keys=True, default=str)
checksum_hex = hashlib.sha256(canonical.encode()).hexdigest()
data_with_checksum = {**data_without_checksum, "checksum": checksum_hex}
context.import_error = None
try:
context.import_result = context.service.import_session(data_with_checksum)
except Exception as exc:
context.import_error = exc