refactor(api): decouple onboarding and notification services (#40759)

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: hjlarry <hjlarry@163.com>
This commit is contained in:
authored and GitHub committed 2026-08-31 04:37:07 +00:00
1 parent c6ca395042
commit d25e2b51fc
21 files changed
+1305 -597

No files matched your search

@@ -238,6 +238,42 @@ def test_patch_union_schema_markdown_fills_regular_schema_union_property(tmp_pat
assert "| value | string<br>integer<br>number<br>boolean | | No |" in patched
def test_patch_union_schema_markdown_preserves_nullable_enum_values(tmp_path: Path):
module = _load_generate_swagger_markdown_docs_module()
spec_path = tmp_path / "console-openapi.json"
spec_path.write_text(
json.dumps(
{
"components": {
"schemas": {
"StepByStepTourStatePatchPayload": {
"properties": {
"task_id": {
"anyOf": [
{"enum": ["home", "studio"], "type": "string"},
{"type": "null"},
],
},
},
},
},
}
}
),
encoding="utf-8",
)
markdown = """#### StepByStepTourStatePatchPayload
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| task_id | string | Task ID | No |
"""
patched = module._patch_union_schema_markdown(markdown, spec_path)
assert '| task_id | string, <br>**Available values:** "home", "studio" | Task ID | No |' in patched
def test_patch_union_schema_markdown_fills_array_item_union_property(tmp_path: Path):
module = _load_generate_swagger_markdown_docs_module()
spec_path = tmp_path / "console-openapi.json"
@@ -0,0 +1,77 @@
from inspect import unwrap
from types import SimpleNamespace
from unittest.mock import Mock, patch
from controllers.console.notification import (
DismissNotificationPayload,
NotificationApi,
NotificationDismissApi,
)
from machinery.context import RequestContext
from services.entities.notification_entities import NotificationItem, NotificationResult
def _request_context() -> RequestContext:
return RequestContext(
request_id="request-1",
trace_id="trace-1",
account_id="account-1",
active_workspace_id="workspace-1",
)
def test_get_notification_delegates_and_serializes_result() -> None:
service = Mock()
service.get_active.return_value = NotificationResult(
should_show=True,
notifications=(
NotificationItem(
notification_id="notification-1",
frequency="once",
lang="en-US",
title="Title",
subtitle="Subtitle",
body="Body",
title_pic_url="https://example.com/title.png",
),
),
)
services = SimpleNamespace(notifications=service)
api = NotificationApi()
method = unwrap(api.get)
context = _request_context()
with patch("controllers.console.notification.application_services", return_value=services):
result, status = method(api, context)
assert status == 200
assert result == {
"should_show": True,
"notifications": [
{
"notification_id": "notification-1",
"frequency": "once",
"lang": "en-US",
"title": "Title",
"subtitle": "Subtitle",
"body": "Body",
"title_pic_url": "https://example.com/title.png",
}
],
}
service.get_active.assert_called_once_with(context)
def test_dismiss_notification_delegates_with_stable_account_context() -> None:
service = Mock()
services = SimpleNamespace(notifications=service)
api = NotificationDismissApi()
method = unwrap(api.post)
context = _request_context()
with patch("controllers.console.notification.application_services", return_value=services):
result, status = method(api, DismissNotificationPayload(notification_id="notification-1"), context)
assert status == 200
assert result == {"result": "success"}
service.dismiss.assert_called_once_with(context, "notification-1")
@@ -2,47 +2,48 @@ from __future__ import annotations
from datetime import UTC, datetime
from inspect import unwrap
from unittest.mock import Mock
from types import SimpleNamespace
from unittest.mock import Mock, patch
import pytest
from flask import Flask
from pydantic import ValidationError
from controllers.console.onboarding import (
StepByStepTourStateApi,
StepByStepTourStatePatchPayload,
StepByStepTourStateResponse,
)
from extensions.ext_database import db
from models.account import Account, AccountStatus
from services.step_by_step_tour_service import StepByStepTourService
from machinery.context import RequestContext
from services.entities.onboarding_entities import StepByStepTourPatch, StepByStepTourResult
def _account() -> Account:
account = Account(name="User", email="user@example.com", status=AccountStatus.ACTIVE)
account.id = "account-1"
return account
def _request_context() -> RequestContext:
return RequestContext(
request_id="request-1",
trace_id="trace-1",
account_id="account-1",
active_workspace_id="workspace-1",
)
def _state_response() -> dict[str, object]:
return {
"first_workspace_id": "workspace-1",
"skipped": False,
"completed_task_ids": ["home"],
"manually_enabled_workspace_ids": [],
"manually_disabled_workspace_ids": [],
"updated_at": datetime(2026, 6, 28, tzinfo=UTC),
}
def _state_result() -> StepByStepTourResult:
return StepByStepTourResult(
first_workspace_id="workspace-1",
completed_task_ids=("home",),
updated_at=datetime(2026, 6, 28, tzinfo=UTC),
)
def test_get_step_by_step_tour_state(app: Flask, monkeypatch: pytest.MonkeyPatch) -> None:
get_state = Mock(return_value=_state_response())
monkeypatch.setattr(StepByStepTourService, "get_state", get_state)
def test_get_step_by_step_tour_state_delegates_with_request_context() -> None:
service = Mock()
service.get_state.return_value = _state_result()
services = SimpleNamespace(step_by_step_tour=service)
api = StepByStepTourStateApi()
method = unwrap(api.get)
context = _request_context()
with app.test_request_context("/console/api/onboarding/step-by-step-tour/state", method="GET"):
result = method(api, "workspace-1", _account())
with patch("controllers.console.onboarding.application_services", return_value=services):
result = method(api, context)
assert result == {
"first_workspace_id": "workspace-1",
@@ -52,35 +53,26 @@ def test_get_step_by_step_tour_state(app: Flask, monkeypatch: pytest.MonkeyPatch
"manually_disabled_workspace_ids": [],
"updated_at": "2026-06-28T00:00:00Z",
}
get_state.assert_called_once()
assert get_state.call_args.kwargs["current_tenant_id"] == "workspace-1"
assert get_state.call_args.kwargs["session"] is db.session
service.get_state.assert_called_once_with(context)
def test_patch_step_by_step_tour_state_passes_action_payload(
app: Flask,
monkeypatch: pytest.MonkeyPatch,
) -> None:
patch_state = Mock(return_value=_state_response())
monkeypatch.setattr(StepByStepTourService, "patch_state", patch_state)
def test_patch_step_by_step_tour_state_maps_transport_payload_to_command() -> None:
service = Mock()
service.patch_state.return_value = _state_result()
services = SimpleNamespace(step_by_step_tour=service)
api = StepByStepTourStateApi()
method = unwrap(api.patch)
payload = {"action": "complete_task", "task_id": "studio"}
context = _request_context()
payload = StepByStepTourStatePatchPayload.model_validate({"action": "complete_task", "task_id": "studio"})
req_data = StepByStepTourStatePatchPayload.model_validate(payload)
with app.test_request_context(
"/console/api/onboarding/step-by-step-tour/state",
method="PATCH",
json=payload,
):
result = method(api, req_data, "workspace-1", _account())
with patch("controllers.console.onboarding.application_services", return_value=services):
result = method(api, payload, context)
assert result["completed_task_ids"] == ["home"]
patch_state.assert_called_once()
assert patch_state.call_args.kwargs["current_tenant_id"] == "workspace-1"
assert patch_state.call_args.kwargs["patch"] == payload
assert patch_state.call_args.kwargs["session"] is db.session
service.patch_state.assert_called_once_with(
context,
StepByStepTourPatch(action="complete_task", task_id="studio"),
)
def test_patch_payload_rejects_non_action_fields() -> None:
@@ -96,3 +88,21 @@ def test_patch_payload_rejects_task_id_without_task_action() -> None:
def test_patch_payload_requires_action() -> None:
with pytest.raises(ValidationError):
StepByStepTourStatePatchPayload.model_validate({"task_id": "home"})
def test_step_by_step_tour_schemas_preserve_enum_values() -> None:
patch_schema = StepByStepTourStatePatchPayload.model_json_schema()
action_schema = patch_schema["properties"]["action"]
task_id_schema = patch_schema["properties"]["task_id"]
task_id_values = next(candidate["enum"] for candidate in task_id_schema["anyOf"] if "enum" in candidate)
response_schema = StepByStepTourStateResponse.model_json_schema()
assert set(action_schema["enum"]) == {
"skip",
"complete_task",
"uncomplete_task",
"enable_current_workspace",
"disable_current_workspace",
}
assert set(task_id_values) == {"home", "studio", "knowledge", "integration"}
assert set(response_schema["properties"]["completed_task_ids"]["items"]["enum"]) == set(task_id_values)
@@ -382,6 +382,8 @@ def test_build_application_services_wires_account_profile_repository(
assert email_registration._registration._session_factory is sqlite_session_factory
assert services.accounts.education._accounts is accounts
assert services.accounts.deletion._accounts is accounts
assert services.notifications._accounts is accounts
assert services.step_by_step_tour._accounts is accounts
assert services.accounts.deletion._memberships is services.workspace_queries._workspaces
integrations = services.accounts.integrations._integrations
assert isinstance(integrations, SQLAlchemyAccountIntegrationRepository)
@@ -0,0 +1,171 @@
from contextlib import nullcontext
from dataclasses import replace
from datetime import datetime
from typing import cast
from unittest.mock import MagicMock, Mock
import pytest
from sqlalchemy.exc import IntegrityError, OperationalError
from sqlalchemy.orm import Session, sessionmaker
from models.onboarding import AccountStepByStepTourState
from repositories.step_by_step_tour_repository import (
SQLAlchemyStepByStepTourStateRepository,
_is_retryable_mysql_lock_error,
)
class _ErrnoOnlyError(Exception):
def __init__(self, errno: int | str) -> None:
super().__init__()
self.errno = errno
def test_mutate_creates_and_updates_state_in_repository_owned_transaction(
sqlite_session_factory: sessionmaker[Session],
) -> None:
repository = SQLAlchemyStepByStepTourStateRepository(sqlite_session_factory)
saved = repository.mutate(
"account-1",
lambda state: replace(state, completed_task_ids=("home",)),
)
reloaded = repository.get("account-1")
assert saved.first_workspace_id is None
assert saved.completed_task_ids == ("home",)
assert saved.updated_at is not None
assert reloaded == saved
def test_initialize_creates_state_with_first_workspace_atomically(
sqlite_session_factory: sessionmaker[Session],
) -> None:
repository = SQLAlchemyStepByStepTourStateRepository(sqlite_session_factory)
result = repository.initialize("account-1", "workspace-1")
assert result.first_workspace_id == "workspace-1"
assert repository.get("account-1") == result
def test_initialize_claims_empty_state_once_without_overwriting_winner(
sqlite_session_factory: sessionmaker[Session],
) -> None:
repository = SQLAlchemyStepByStepTourStateRepository(sqlite_session_factory)
with sqlite_session_factory() as session:
session.add(AccountStepByStepTourState(account_id="account-1"))
session.commit()
first = repository.initialize("account-1", "workspace-1")
second = repository.initialize("account-1", "workspace-2")
assert first.first_workspace_id == "workspace-1"
assert second.first_workspace_id == "workspace-1"
def test_mutate_cannot_clear_or_overwrite_first_workspace(
sqlite_session_factory: sessionmaker[Session],
) -> None:
repository = SQLAlchemyStepByStepTourStateRepository(sqlite_session_factory)
repository.initialize("account-1", "workspace-1")
result = repository.mutate(
"account-1",
lambda state: replace(state, first_workspace_id="workspace-2", skipped=True),
)
assert result.first_workspace_id == "workspace-1"
assert result.skipped is True
def test_sequential_mutations_replay_against_latest_state(
sqlite_session_factory: sessionmaker[Session],
) -> None:
repository = SQLAlchemyStepByStepTourStateRepository(sqlite_session_factory)
repository.mutate("account-1", lambda state: replace(state, completed_task_ids=("home",)))
result = repository.mutate(
"account-1",
lambda state: replace(state, completed_task_ids=(*state.completed_task_ids, "studio")),
)
assert result.completed_task_ids == ("home", "studio")
def test_mutate_replays_after_concurrent_create_conflict() -> None:
concurrent_state = AccountStepByStepTourState(account_id="account-1")
concurrent_state.completed_task_ids = ["home"]
concurrent_state.updated_at = datetime(2026, 8, 13)
session = MagicMock(spec=Session)
session.execute.return_value.scalar_one_or_none.side_effect = [None, concurrent_state]
session.flush.side_effect = IntegrityError("insert", {}, Exception("duplicate"))
factory = cast(sessionmaker[Session], Mock(return_value=nullcontext(session)))
repository = SQLAlchemyStepByStepTourStateRepository(factory)
result = repository.mutate(
"account-1",
lambda state: replace(state, completed_task_ids=(*state.completed_task_ids, "studio")),
)
assert result.completed_task_ids == ("home", "studio")
session.rollback.assert_called_once_with()
initial_probe = session.execute.call_args_list[0].args[0]
replay_statement = session.execute.call_args_list[1].args[0]
assert initial_probe._for_update_arg is None
assert replay_statement._for_update_arg is not None
def test_mutate_retries_mysql_deadlock_with_fresh_session() -> None:
concurrent_state = AccountStepByStepTourState(account_id="account-1")
concurrent_state.completed_task_ids = ["home"]
concurrent_state.updated_at = datetime(2026, 8, 13)
deadlocked_session = MagicMock(spec=Session)
deadlocked_session.execute.return_value.scalar_one_or_none.return_value = None
deadlocked_session.flush.side_effect = OperationalError(
"INSERT",
{},
Exception(1213, "Deadlock found when trying to get lock"),
)
retry_session = MagicMock(spec=Session)
retry_session.execute.return_value.scalar_one_or_none.side_effect = [concurrent_state, concurrent_state]
factory = Mock(side_effect=[nullcontext(deadlocked_session), nullcontext(retry_session)])
repository = SQLAlchemyStepByStepTourStateRepository(cast(sessionmaker[Session], factory))
result = repository.mutate(
"account-1",
lambda state: replace(state, completed_task_ids=(*state.completed_task_ids, "studio")),
)
assert result.completed_task_ids == ("home", "studio")
assert factory.call_count == 2
retry_lock_statement = retry_session.execute.call_args_list[1].args[0]
assert retry_lock_statement._for_update_arg is not None
@pytest.mark.parametrize(
("orig", "expected"),
[
pytest.param(_ErrnoOnlyError(1205), True, id="errno-attribute"),
pytest.param(Exception(1213, "deadlock"), True, id="integer-args-code"),
pytest.param(Exception("1213", "deadlock"), True, id="string-args-code"),
pytest.param(Exception(9999, "other error"), False, id="non-retryable-code"),
pytest.param(Exception(True), False, id="boolean-is-not-an-error-code"),
pytest.param(Exception(), False, id="missing-error-code"),
],
)
def test_mysql_lock_error_detection_preserves_errno_and_args_coverage(
orig: BaseException,
expected: bool,
) -> None:
exc = OperationalError("statement", {}, orig)
assert _is_retryable_mysql_lock_error(exc) is expected
def test_get_returns_none_for_unknown_account(
sqlite_session_factory: sessionmaker[Session],
) -> None:
assert SQLAlchemyStepByStepTourStateRepository(sqlite_session_factory).get("missing") is None
@@ -0,0 +1,63 @@
from unittest.mock import patch
from services.entities.notification_entities import NotificationContent
from services.notification_gateway import BillingNotificationGateway
def test_get_active_maps_billing_proto_json_contract() -> None:
payload = {
"shouldShow": True,
"notifications": [
{
"notificationId": "notification-1",
"frequency": "once",
"contents": {
"en-US": {
"lang": "en-US",
"title": "Title",
"subtitle": "Subtitle",
"body": "Body",
"titlePicUrl": "title.png",
}
},
}
],
}
with patch("services.notification_gateway.BillingService.get_account_notification", return_value=payload):
result = BillingNotificationGateway().get_active("account-1")
assert result.should_show is True
assert result.notifications[0].notification_id == "notification-1"
assert result.notifications[0].contents["en-US"].title_pic_url == "title.png"
def test_get_active_omits_empty_localized_content_so_service_can_fall_back() -> None:
empty_localized_content: dict[str, str] = {}
payload = {
"shouldShow": True,
"notifications": [
{
"notificationId": "notification-1",
"frequency": "once",
"contents": {
"zh-Hans": empty_localized_content,
"en-US": {"lang": "en-US", "title": "Title"},
},
}
],
}
with patch("services.notification_gateway.BillingService.get_account_notification", return_value=payload):
result = BillingNotificationGateway().get_active("account-1")
assert result.notifications[0].contents == {
"en-US": NotificationContent("en-US", "Title", "", "", ""),
}
def test_dismiss_delegates_to_billing_service() -> None:
with patch("services.notification_gateway.BillingService.dismiss_notification") as dismiss:
BillingNotificationGateway().dismiss("notification-1", "account-1")
dismiss.assert_called_once_with(notification_id="notification-1", account_id="account-1")
@@ -0,0 +1,138 @@
from datetime import datetime
from unittest.mock import Mock
import pytest
from machinery.context import RequestContext
from services.account_ports import AccountRepository
from services.entities.account_entities import AccountSnapshot
from services.entities.notification_entities import (
AccountNotification,
AccountNotificationBatch,
NotificationContent,
NotificationItem,
NotificationResult,
)
from services.notification_service import NotificationService
def _context() -> RequestContext:
return RequestContext(
request_id="request-1",
trace_id="trace-1",
account_id="account-1",
active_workspace_id="workspace-1",
)
class NotificationGatewayStub:
def __init__(self, batch: AccountNotificationBatch) -> None:
self.batch = batch
self.get_account_ids: list[str] = []
self.dismissals: list[tuple[str, str]] = []
def get_active(self, account_id: str) -> AccountNotificationBatch:
self.get_account_ids.append(account_id)
return self.batch
def dismiss(self, notification_id: str, account_id: str) -> None:
self.dismissals.append((notification_id, account_id))
def _account(language: str | None = "zh-Hans") -> AccountSnapshot:
return AccountSnapshot(
id="account-1",
name="Account",
email="account@example.com",
avatar=None,
is_password_set=False,
interface_language=language,
interface_theme="light",
timezone="UTC",
last_login_at=None,
last_login_ip=None,
status="active",
initialized_at=None,
created_at=datetime(2026, 1, 1),
)
def _accounts(account: AccountSnapshot | None) -> Mock:
accounts = Mock(spec=AccountRepository)
accounts.get.return_value = account
return accounts
def _notification(contents: dict[str, NotificationContent]) -> AccountNotification:
return AccountNotification(
notification_id="notification-1",
frequency="once",
contents=contents,
)
def test_get_active_localizes_notification_for_account_language() -> None:
chinese = NotificationContent("zh-Hans", "标题", "副标题", "正文", "zh.png")
english = NotificationContent("en-US", "Title", "Subtitle", "Body", "en.png")
gateway = NotificationGatewayStub(
AccountNotificationBatch(True, (_notification({"zh-Hans": chinese, "en-US": english}),))
)
service = NotificationService(accounts=_accounts(_account()), notifications=gateway)
result = service.get_active(_context())
assert result == NotificationResult(
should_show=True,
notifications=(NotificationItem("notification-1", "once", "zh-Hans", "标题", "副标题", "正文", "zh.png"),),
)
assert gateway.get_account_ids == ["account-1"]
def test_get_active_falls_back_to_english() -> None:
english = NotificationContent("en-US", "Title", "Subtitle", "Body", "en.png")
gateway = NotificationGatewayStub(AccountNotificationBatch(True, (_notification({"en-US": english}),)))
service = NotificationService(accounts=_accounts(_account("fr-FR")), notifications=gateway)
result = service.get_active(_context())
assert result.notifications[0].lang == "en-US"
assert result.notifications[0].title == "Title"
def test_get_active_skips_account_query_when_gateway_says_not_to_show() -> None:
accounts = _accounts(None)
service = NotificationService(
accounts=accounts,
notifications=NotificationGatewayStub(AccountNotificationBatch(False, ())),
)
result = service.get_active(_context())
assert result == NotificationResult(False, ())
accounts.get.assert_not_called()
def test_get_active_uses_empty_content_when_notification_has_no_translations() -> None:
gateway = NotificationGatewayStub(AccountNotificationBatch(True, (_notification({}),)))
service = NotificationService(accounts=_accounts(_account(None)), notifications=gateway)
result = service.get_active(_context())
assert result.notifications == (NotificationItem("notification-1", "once", "en-US", "", "", "", ""),)
def test_get_active_rejects_unknown_admitted_account() -> None:
gateway = NotificationGatewayStub(AccountNotificationBatch(True, (_notification({}),)))
service = NotificationService(accounts=_accounts(None), notifications=gateway)
with pytest.raises(RuntimeError, match="unknown account"):
service.get_active(_context())
def test_dismiss_delegates_identifiers_to_gateway() -> None:
gateway = NotificationGatewayStub(AccountNotificationBatch(False, ()))
service = NotificationService(accounts=_accounts(_account()), notifications=gateway)
service.dismiss(_context(), "notification-1")
assert gateway.dismissals == [("notification-1", "account-1")]
@@ -1,230 +1,213 @@
from __future__ import annotations
from datetime import UTC, datetime
from collections.abc import Callable
from dataclasses import replace
from datetime import datetime
from unittest.mock import Mock
import pytest
from sqlalchemy import event, select
from sqlalchemy.orm import Session, sessionmaker
from enums import DeploymentEdition
from models.account import Account, AccountStatus
from models.onboarding import AccountStepByStepTourState
from machinery.context import RequestContext
from services.account_ports import AccountRepository
from services.entities.account_entities import AccountSnapshot
from services.entities.onboarding_entities import StepByStepTourPatch, StepByStepTourResult, StepByStepTourState
from services.step_by_step_tour_service import StepByStepTourService
from tests.unit_tests.config_override import apply_config_overrides
def _account(*, initialized_at: datetime | None = None, created_at: datetime | None = None) -> Account:
account = Account(name="User", email="user@example.com", status=AccountStatus.ACTIVE)
account.id = "account-1"
account.initialized_at = initialized_at
account.created_at = created_at or datetime(2026, 6, 28)
return account
def _state() -> AccountStepByStepTourState:
state = AccountStepByStepTourState(account_id="account-1")
state.updated_at = datetime(2026, 6, 28, tzinfo=UTC)
return state
def _persist_state(session: Session, state: AccountStepByStepTourState) -> None:
session.add(state)
session.commit()
def _load_state(session: Session) -> AccountStepByStepTourState | None:
return session.scalar(
select(AccountStepByStepTourState).where(AccountStepByStepTourState.account_id == "account-1")
def _context(*, workspace_id: str | None = "workspace-1") -> RequestContext:
return RequestContext(
request_id="request-1",
trace_id="trace-1",
account_id="account-1",
active_workspace_id=workspace_id,
)
def _set_tour_config(monkeypatch: pytest.MonkeyPatch, *, enabled: bool, rollout_started_at: datetime | None) -> None:
apply_config_overrides(
monkeypatch,
ENABLE_STEP_BY_STEP_TOUR=enabled,
STEP_BY_STEP_TOUR_ROLLOUT_STARTED_AT=rollout_started_at,
class StateRepositoryStub:
def __init__(self, state: StepByStepTourState | None = None) -> None:
self.state = state
self.get_account_ids: list[str] = []
self.initialize_calls: list[tuple[str, str]] = []
self.mutation_account_ids: list[str] = []
def get(self, account_id: str) -> StepByStepTourState | None:
self.get_account_ids.append(account_id)
return self.state
def initialize(self, account_id: str, first_workspace_id: str) -> StepByStepTourState:
self.initialize_calls.append((account_id, first_workspace_id))
if self.state is None:
self.state = StepByStepTourState(account_id=account_id, first_workspace_id=first_workspace_id)
elif self.state.first_workspace_id is None:
self.state = replace(self.state, first_workspace_id=first_workspace_id)
return self.state
def mutate(
self,
account_id: str,
mutation: Callable[[StepByStepTourState], StepByStepTourState],
) -> StepByStepTourState:
self.mutation_account_ids.append(account_id)
if self.state is None:
self.state = StepByStepTourState(account_id=account_id)
self.state = mutation(self.state)
return self.state
def _account(*, started_at: datetime = datetime(2026, 6, 28)) -> AccountSnapshot:
return AccountSnapshot(
id="account-1",
name="Account",
email="account@example.com",
avatar=None,
is_password_set=False,
interface_language="en-US",
interface_theme="light",
timezone="UTC",
last_login_at=None,
last_login_ip=None,
status="active",
initialized_at=started_at,
created_at=started_at,
)
def test_get_state_creates_state_and_records_first_workspace_for_eligible_account(
monkeypatch: pytest.MonkeyPatch,
sqlite_session: Session,
sqlite_session_factory: sessionmaker[Session],
) -> None:
_set_tour_config(monkeypatch, enabled=True, rollout_started_at=datetime(2026, 6, 1))
def _accounts(account: AccountSnapshot | None) -> Mock:
accounts = Mock(spec=AccountRepository)
accounts.get.return_value = account
return accounts
result = StepByStepTourService.get_state(
account=_account(initialized_at=datetime(2026, 6, 28)),
current_tenant_id="workspace-1",
session=sqlite_session,
def _service(
*,
states: StateRepositoryStub,
account: AccountSnapshot | None = None,
enabled: bool = True,
rollout_started_at: datetime | None = datetime(2026, 6, 1),
) -> StepByStepTourService:
return StepByStepTourService(
accounts=_accounts(account or _account()),
states=states,
enabled=enabled,
rollout_started_at=rollout_started_at,
)
assert result["first_workspace_id"] == "workspace-1"
assert result["completed_task_ids"] == []
with sqlite_session_factory() as observer:
persisted = _load_state(observer)
assert persisted is not None
assert persisted.account_id == "account-1"
assert persisted.first_workspace_id == "workspace-1"
def test_get_state_creates_state_and_records_first_workspace_for_eligible_account() -> None:
states = StateRepositoryStub()
result = _service(states=states).get_state(_context())
assert result.first_workspace_id == "workspace-1"
assert states.get_account_ids == []
assert states.initialize_calls == [("account-1", "workspace-1")]
assert states.mutation_account_ids == []
def test_is_eligible_does_not_depend_on_cloud_edition(monkeypatch: pytest.MonkeyPatch) -> None:
_set_tour_config(monkeypatch, enabled=True, rollout_started_at=datetime(2026, 6, 1))
apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
def test_get_state_returns_existing_state_without_rewriting_first_workspace() -> None:
state = StepByStepTourState(account_id="account-1", first_workspace_id="workspace-original")
states = StateRepositoryStub(state)
result = StepByStepTourService.is_eligible(_account(initialized_at=datetime(2026, 6, 28)))
result = _service(states=states).get_state(_context(workspace_id="workspace-current"))
assert result is True
assert result.first_workspace_id == "workspace-original"
assert states.initialize_calls == [("account-1", "workspace-current")]
assert states.mutation_account_ids == []
def test_get_state_does_not_create_state_for_ineligible_account_without_existing_state(
monkeypatch: pytest.MonkeyPatch,
sqlite_session: Session,
sqlite_session_factory: sessionmaker[Session],
) -> None:
_set_tour_config(monkeypatch, enabled=True, rollout_started_at=datetime(2026, 6, 1))
def test_get_state_does_not_create_state_for_ineligible_account() -> None:
states = StateRepositoryStub()
service = _service(states=states, account=_account(started_at=datetime(2026, 5, 31)))
result = StepByStepTourService.get_state(
account=_account(initialized_at=datetime(2026, 5, 31)),
current_tenant_id="workspace-1",
session=sqlite_session,
result = service.get_state(_context())
assert result == StepByStepTourResult()
assert states.get_account_ids == ["account-1"]
assert states.mutation_account_ids == []
def test_get_state_does_not_create_state_when_tour_is_disabled() -> None:
states = StateRepositoryStub()
result = _service(states=states, enabled=False).get_state(_context())
assert result == StepByStepTourResult()
assert states.get_account_ids == ["account-1"]
def test_patch_state_persists_even_when_tour_is_disabled() -> None:
states = StateRepositoryStub()
service = _service(states=states, enabled=False)
result = service.patch_state(_context(workspace_id="workspace-2"), StepByStepTourPatch("enable_current_workspace"))
assert result.manually_enabled_workspace_ids == ("workspace-2",)
assert states.mutation_account_ids == ["account-1"]
def test_patch_state_skip_removes_current_workspace_enable() -> None:
states = StateRepositoryStub(
StepByStepTourState(
account_id="account-1",
manually_enabled_workspace_ids=("workspace-1", "workspace-2"),
)
)
assert result == {
"first_workspace_id": None,
"skipped": False,
"completed_task_ids": [],
"manually_enabled_workspace_ids": [],
"manually_disabled_workspace_ids": [],
"updated_at": None,
}
with sqlite_session_factory() as observer:
assert _load_state(observer) is None
result = _service(states=states).patch_state(_context(), StepByStepTourPatch("skip"))
assert result.skipped is True
assert result.manually_enabled_workspace_ids == ("workspace-2",)
def test_patch_state_persists_even_when_account_is_not_eligible(
monkeypatch: pytest.MonkeyPatch,
sqlite_session: Session,
sqlite_session_factory: sessionmaker[Session],
) -> None:
_set_tour_config(monkeypatch, enabled=False, rollout_started_at=datetime(2026, 6, 1))
result = StepByStepTourService.patch_state(
account=_account(initialized_at=datetime(2026, 6, 28)),
current_tenant_id="workspace-2",
patch={"action": "enable_current_workspace"},
session=sqlite_session,
def test_patch_state_disable_moves_current_workspace_to_disabled() -> None:
states = StateRepositoryStub(
StepByStepTourState(
account_id="account-1",
manually_enabled_workspace_ids=("workspace-1", "workspace-2"),
)
)
assert result["skipped"] is False
assert result["manually_enabled_workspace_ids"] == ["workspace-2"]
assert result["manually_disabled_workspace_ids"] == []
with sqlite_session_factory() as observer:
persisted = _load_state(observer)
assert persisted is not None
assert persisted.manually_enabled_workspace_ids == ["workspace-2"]
def test_patch_state_skip_action_sets_skipped_and_removes_current_workspace_enable(
monkeypatch: pytest.MonkeyPatch,
sqlite_session: Session,
) -> None:
_set_tour_config(monkeypatch, enabled=False, rollout_started_at=datetime(2026, 6, 1))
state = _state()
state.manually_enabled_workspace_ids = ["workspace-1", "workspace-2"]
_persist_state(sqlite_session, state)
result = StepByStepTourService.patch_state(
account=_account(initialized_at=datetime(2026, 6, 28)),
current_tenant_id="workspace-1",
patch={"action": "skip"},
session=sqlite_session,
result = _service(states=states).patch_state(
_context(),
StepByStepTourPatch("disable_current_workspace"),
)
assert result["skipped"] is True
assert result["manually_enabled_workspace_ids"] == ["workspace-2"]
assert result["manually_disabled_workspace_ids"] == []
assert _load_state(sqlite_session) is state
assert result.manually_enabled_workspace_ids == ("workspace-2",)
assert result.manually_disabled_workspace_ids == ("workspace-1",)
def test_patch_state_disable_action_moves_current_workspace_to_disabled(
monkeypatch: pytest.MonkeyPatch,
sqlite_session: Session,
) -> None:
_set_tour_config(monkeypatch, enabled=False, rollout_started_at=datetime(2026, 6, 1))
state = _state()
state.manually_enabled_workspace_ids = ["workspace-1", "workspace-2"]
_persist_state(sqlite_session, state)
def test_patch_state_complete_and_uncomplete_task() -> None:
states = StateRepositoryStub(StepByStepTourState(account_id="account-1", completed_task_ids=("home",)))
service = _service(states=states)
result = StepByStepTourService.patch_state(
account=_account(initialized_at=datetime(2026, 6, 28)),
current_tenant_id="workspace-1",
patch={"action": "disable_current_workspace"},
session=sqlite_session,
service.patch_state(_context(), StepByStepTourPatch("complete_task", "studio"))
result = service.patch_state(_context(), StepByStepTourPatch("uncomplete_task", "home"))
assert result.completed_task_ids == ("studio",)
def test_rejects_unsupported_task_id() -> None:
with pytest.raises(ValueError, match="Unsupported task_id"):
StepByStepTourService._require_task_id("unknown")
def test_rejects_missing_workspace_before_using_state_repository() -> None:
states = StateRepositoryStub()
with pytest.raises(RuntimeError, match="did not resolve an active workspace"):
_service(states=states).patch_state(_context(workspace_id=None), StepByStepTourPatch("skip"))
assert states.mutation_account_ids == []
def test_get_state_rejects_unknown_admitted_account() -> None:
states = StateRepositoryStub()
service = StepByStepTourService(
accounts=_accounts(None),
states=states,
enabled=True,
rollout_started_at=datetime(2026, 6, 1),
)
assert result["manually_enabled_workspace_ids"] == ["workspace-2"]
assert result["manually_disabled_workspace_ids"] == ["workspace-1"]
assert _load_state(sqlite_session) is state
def test_patch_state_complete_and_uncomplete_task(
monkeypatch: pytest.MonkeyPatch,
sqlite_session: Session,
) -> None:
_set_tour_config(monkeypatch, enabled=False, rollout_started_at=datetime(2026, 6, 1))
state = _state()
state.completed_task_ids = ["home"]
_persist_state(sqlite_session, state)
StepByStepTourService.patch_state(
account=_account(initialized_at=datetime(2026, 6, 28)),
current_tenant_id="workspace-1",
patch={"action": "complete_task", "task_id": "studio"},
session=sqlite_session,
)
result = StepByStepTourService.patch_state(
account=_account(initialized_at=datetime(2026, 6, 28)),
current_tenant_id="workspace-1",
patch={"action": "uncomplete_task", "task_id": "home"},
session=sqlite_session,
)
assert result["completed_task_ids"] == ["studio"]
def test_patch_state_recovers_when_concurrent_request_created_state(
monkeypatch: pytest.MonkeyPatch,
sqlite_session: Session,
sqlite_session_factory: sessionmaker[Session],
) -> None:
_set_tour_config(monkeypatch, enabled=False, rollout_started_at=datetime(2026, 6, 1))
existing_state = _state()
existing_state.manually_enabled_workspace_ids = ["workspace-1"]
lifecycle_events: list[str] = []
@event.listens_for(sqlite_session, "before_flush", once=True)
def add_conflicting_pending_state(session: Session, _flush_context, _instances) -> None:
lifecycle_events.append("before_flush")
session.add(AccountStepByStepTourState(account_id="account-1"))
@event.listens_for(sqlite_session, "after_soft_rollback", once=True)
def persist_winning_request(_session: Session, _previous_transaction) -> None:
lifecycle_events.append("after_soft_rollback")
with sqlite_session_factory() as winner:
winner.add(existing_state)
winner.commit()
result = StepByStepTourService.patch_state(
account=_account(initialized_at=datetime(2026, 6, 28)),
current_tenant_id="workspace-2",
patch={"action": "enable_current_workspace"},
session=sqlite_session,
)
assert result["manually_enabled_workspace_ids"] == ["workspace-1", "workspace-2"]
assert lifecycle_events == ["before_flush", "after_soft_rollback"]
with sqlite_session_factory() as observer:
persisted = _load_state(observer)
assert persisted is not None
assert persisted.manually_enabled_workspace_ids == ["workspace-1", "workspace-2"]
with pytest.raises(RuntimeError, match="unknown account"):
service.get_state(_context())