mirror of
https://github.com/rennf93/roboco.git
synced 2026-08-03 07:23:24 +02:00
W6: Telegram notifications bridge (V1) (#524)
* feat(gateway): reviewer/PM collision map (W5)
The collision surface (intends_to_touch / adds_migration / touches_shared)
is authored at delegate time, consumed once by SequencingService to wire
dependency edges, then never shown to a reviewer again. This surfaces it:
- Pure builder (services/gateway/choreographer/collision.py): for a task
under review, the surfaced siblings (same parent) that would collide —
file-overlap globs or a shared migration chain (both adds_migration) —
with the overlapping globs and a declared-vs-actual drift check. No
DB/IO; callers fetch siblings (one indexed get_subtasks query, mig 069)
+ actual files (git). Caps: 10 siblings, 5 globs.
- Evidence envelopes: collision_context block injected into QA
claim_review, PR-gate claim_gate_review (both carry real touched files
so drift is populated), and the PM i_will_plan briefing (no actual
files at plan time, drift omitted). Best-effort — a failure omits the
block, never breaks the verb/briefing. Empty block omitted (zero token
cost via _EVIDENCE_OMIT_WHEN_EMPTY).
- Panel: GET /api/tasks/{id}/collision-map (declared surface + sibling
overlap; no drift — the panel route resolves no workspace) + a Collision
tab on the task detail (8th tab). Mock-mode returns an empty map.
- docs/map added to the RAG auto-index dirs so the collision-map concept
is fleet-retrievable; skipped gracefully if the dir is absent.
19 new tests (15 unit on the pure builder + 4 integration on the route).
Gate green: ruff/mypy/xenon (module rank A)/pytest 13000/coverage 94.81%,
panel typecheck/lint/516 tests.
* [w6-telegram] Add Telegram notifications bridge (V1)
CEO-facing Telegram DM bridge, flag-gated off by default
(ROBOCO_TELEGRAM_ENABLED). Mirrors the X-credentials / X-client pattern:
- TelegramCredentialsTable (migration 073) — singleton Fernet-encrypted
bot_token + chat_id, all-or-nothing set/clear; API never returns plaintext.
- TelegramClient ABC / NullTelegramClient (no-op, configured->False, never
raises) / LiveTelegramClient (httpx POST sendMessage) / build_telegram_client
factory (Null when creds unset).
- /telegram/credentials CEO-only routes (write-only, guard-decorated).
- Best-effort _notify_telegram fan-out from the two CEO-notify producers
(notify_ceo_of_escalation, notify_ceo_of_completion) — guarded by the flag,
never raises into the producer, carries a panel deep-link when
panel_base_url is set.
- panel credentials card (2 fields) nested in the Telegram feature-flag row.
- panel_base_url + telegram_timeout_seconds config fields.
V1 scope only: credentials + flag + panel card + client + one-line fan-out.
Out of scope (V2): inbound commands, a TelegramEngine background loop, a
dedup ledger, a bus subscription.
* [w6-telegram] fix: slave mypy/xenon regression (product tests + helper extract)
Pre-existing on slave from prior session's merges — no PR's CI caught them
(squash merges don't re-CI the result; each branch was based on older slave).
- test_product: _product helper returned MagicMock -> list invariant error;
cast to ProductTable, move import under TYPE_CHECKING.
- test_usage: svc.session.execute (AsyncSession) has no call_args_list;
cast to MagicMock at the two call sites.
- product.progress_for_products: xenon rank C -> extract module-level
_project_to_products_map helper (repo pattern: helper-extract).
---------
Co-authored-by: Renn F <rennf93@users.noreply.github.com>
This commit is contained in:
@@ -0,0 +1,180 @@
|
||||
"""GET /api/tasks/{id}/collision-map — the reviewer/PM collision map route.
|
||||
|
||||
Read-only feed for the panel's Collision tab: the task's own declared
|
||||
surface plus the surfaced siblings (same parent) that would collide with
|
||||
it. Mirrors test_task_findings_route.py's fixture shape.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from http import HTTPStatus
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from fastapi import FastAPI
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from roboco.api.deps import get_agent_context, get_db
|
||||
from roboco.api.routes.tasks import router as tasks_router
|
||||
from roboco.db.tables import AgentTable, ProjectTable, TaskTable
|
||||
from roboco.models import AgentRole, AgentStatus, Team
|
||||
from roboco.models.base import TaskNature, TaskStatus, TaskType
|
||||
from roboco.models.permissions import AgentContext
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def collision_client(db_session: AsyncSession) -> AsyncIterator[dict]:
|
||||
pm = AgentTable(
|
||||
id=uuid4(),
|
||||
name="PM",
|
||||
slug=f"pm-{uuid4().hex[:8]}",
|
||||
role=AgentRole.MAIN_PM,
|
||||
team=None,
|
||||
status=AgentStatus.ACTIVE,
|
||||
model_config={},
|
||||
system_prompt="pm",
|
||||
capabilities=[],
|
||||
permissions={},
|
||||
metrics={},
|
||||
)
|
||||
db_session.add(pm)
|
||||
await db_session.flush()
|
||||
project = ProjectTable(
|
||||
id=uuid4(),
|
||||
name="CM-Proj",
|
||||
slug=f"cm-proj-{uuid4().hex[:6]}",
|
||||
git_url="https://example.com/cm.git",
|
||||
assigned_cell=Team.BACKEND,
|
||||
created_by=pm.id,
|
||||
)
|
||||
db_session.add(project)
|
||||
await db_session.flush()
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(tasks_router, prefix="/api/tasks")
|
||||
|
||||
async def _override_db() -> AsyncIterator[AsyncSession]:
|
||||
yield db_session
|
||||
|
||||
async def _override_agent() -> AgentContext:
|
||||
return AgentContext(
|
||||
agent_id=cast("UUID", pm.id), role=AgentRole.MAIN_PM, team=None
|
||||
)
|
||||
|
||||
app.dependency_overrides[get_db] = _override_db
|
||||
app.dependency_overrides[get_agent_context] = _override_agent
|
||||
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
yield {"client": client, "agent": pm, "project": project, "db": db_session}
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
def _task(setup: dict, **kw: Any) -> TaskTable:
|
||||
task = TaskTable(
|
||||
id=uuid4(),
|
||||
title=kw.pop("title", "t"),
|
||||
description=kw.pop("description", "d"),
|
||||
acceptance_criteria=["ac"],
|
||||
status=kw.pop("status", TaskStatus.IN_PROGRESS),
|
||||
priority=kw.pop("priority", 2),
|
||||
sequence=kw.pop("sequence", 0),
|
||||
task_type=TaskType.CODE,
|
||||
nature=TaskNature.TECHNICAL,
|
||||
project_id=setup["project"].id,
|
||||
created_by=setup["agent"].id,
|
||||
team=Team.BACKEND,
|
||||
**kw,
|
||||
)
|
||||
setup["db"].add(task)
|
||||
return task
|
||||
|
||||
|
||||
_HDR = {"X-Agent-ID": "ignored", "X-Agent-Role": "main_pm"}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_collision_map_404_for_missing_task(collision_client: dict) -> None:
|
||||
client = collision_client["client"]
|
||||
response = await client.get(f"/api/tasks/{uuid4()}/collision-map", headers=_HDR)
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_collision_map_empty_for_rootless_task(collision_client: dict) -> None:
|
||||
client = collision_client["client"]
|
||||
task = _task(collision_client, intends_to_touch=["roboco/services/git.py"])
|
||||
await collision_client["db"].flush()
|
||||
response = await client.get(f"/api/tasks/{task.id}/collision-map", headers=_HDR)
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
body = response.json()
|
||||
assert body["parent_task_id"] is None
|
||||
assert body["intends_to_touch"] == ["roboco/services/git.py"]
|
||||
assert body["siblings"] == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_collision_map_shows_overlapping_sibling(collision_client: dict) -> None:
|
||||
client = collision_client["client"]
|
||||
parent = _task(collision_client, title="parent", status=TaskStatus.PENDING)
|
||||
await collision_client["db"].flush()
|
||||
under = _task(
|
||||
collision_client,
|
||||
parent_task_id=parent.id,
|
||||
title="under review",
|
||||
intends_to_touch=["roboco/services/git.py"],
|
||||
sequence=0,
|
||||
)
|
||||
_task(
|
||||
collision_client,
|
||||
parent_task_id=parent.id,
|
||||
title="colliding sibling",
|
||||
intends_to_touch=["roboco/services/git.py", "roboco/services/x.py"],
|
||||
sequence=1,
|
||||
)
|
||||
await collision_client["db"].flush()
|
||||
|
||||
response = await client.get(f"/api/tasks/{under.id}/collision-map", headers=_HDR)
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
body = response.json()
|
||||
assert body["parent_task_id"] == str(parent.id)
|
||||
assert len(body["siblings"]) == 1
|
||||
sib_entry = body["siblings"][0]
|
||||
assert sib_entry["title"] == "colliding sibling"
|
||||
assert "roboco/services/git.py" in sib_entry["overlap"]
|
||||
# panel path carries no actual files → drift is empty (the QA/gate
|
||||
# evidence envelopes populate it; the panel schema defaults to []).
|
||||
assert sib_entry["undeclared"] == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_collision_map_omits_non_overlapping_sibling(
|
||||
collision_client: dict,
|
||||
) -> None:
|
||||
client = collision_client["client"]
|
||||
parent = _task(collision_client, title="parent", status=TaskStatus.PENDING)
|
||||
await collision_client["db"].flush()
|
||||
under = _task(
|
||||
collision_client,
|
||||
parent_task_id=parent.id,
|
||||
title="under review",
|
||||
intends_to_touch=["roboco/services/git.py"],
|
||||
)
|
||||
_task(
|
||||
collision_client,
|
||||
parent_task_id=parent.id,
|
||||
title="parallel sibling",
|
||||
intends_to_touch=["roboco/services/other.py"],
|
||||
)
|
||||
await collision_client["db"].flush()
|
||||
|
||||
response = await client.get(f"/api/tasks/{under.id}/collision-map", headers=_HDR)
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
body = response.json()
|
||||
assert body["siblings"] == [] # no overlap, no shared migration
|
||||
@@ -0,0 +1,93 @@
|
||||
"""TelegramCredentialsService coverage — encrypt/roundtrip, all-or-nothing set/clear.
|
||||
|
||||
Drives a real ``db_session`` via the project's Postgres-backed conftest. The
|
||||
service never returns plaintext to a caller other than ``get_decrypted`` (the
|
||||
server-side-only reader) — the API layer only ever sees ``has_credentials``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from roboco.db.tables import TelegramCredentialsTable
|
||||
from roboco.services.telegram_credentials import (
|
||||
TelegramCredentialsService,
|
||||
TelegramCredentialsValidationError,
|
||||
get_telegram_credentials_service,
|
||||
)
|
||||
from sqlalchemy import select
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
_CREDS = {"bot_token": "123456:ABC-bot-token", "chat_id": "987654321"}
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def svc(
|
||||
db_session: AsyncSession,
|
||||
) -> AsyncIterator[TelegramCredentialsService]:
|
||||
yield get_telegram_credentials_service(db_session)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unset_has_no_credentials(svc: TelegramCredentialsService) -> None:
|
||||
assert await svc.has_credentials() is False
|
||||
assert await svc.get_decrypted() is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_set_both_encrypts_and_roundtrips(
|
||||
svc: TelegramCredentialsService,
|
||||
) -> None:
|
||||
has_creds = await svc.set_credentials(**_CREDS)
|
||||
assert has_creds is True
|
||||
assert await svc.has_credentials() is True
|
||||
|
||||
decrypted = await svc.get_decrypted()
|
||||
assert decrypted is not None
|
||||
assert decrypted.bot_token == _CREDS["bot_token"]
|
||||
assert decrypted.chat_id == _CREDS["chat_id"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stored_row_never_holds_plaintext(
|
||||
svc: TelegramCredentialsService, db_session: AsyncSession
|
||||
) -> None:
|
||||
await svc.set_credentials(**_CREDS)
|
||||
result = await db_session.execute(select(TelegramCredentialsTable).limit(1))
|
||||
row = result.scalar_one_or_none()
|
||||
assert row is not None
|
||||
assert row.bot_token_encrypted != _CREDS["bot_token"]
|
||||
assert row.chat_id_encrypted != _CREDS["chat_id"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_clearing_both_removes_row(svc: TelegramCredentialsService) -> None:
|
||||
await svc.set_credentials(**_CREDS)
|
||||
has_creds = await svc.set_credentials(bot_token="", chat_id="")
|
||||
assert has_creds is False
|
||||
assert await svc.has_credentials() is False
|
||||
assert await svc.get_decrypted() is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_partial_set_is_rejected(svc: TelegramCredentialsService) -> None:
|
||||
with pytest.raises(TelegramCredentialsValidationError):
|
||||
await svc.set_credentials(bot_token="only-one", chat_id="")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_rotate_overwrites_previous_values(
|
||||
svc: TelegramCredentialsService,
|
||||
) -> None:
|
||||
await svc.set_credentials(**_CREDS)
|
||||
rotated = {k: f"{v}-rotated" for k, v in _CREDS.items()}
|
||||
await svc.set_credentials(**rotated)
|
||||
decrypted = await svc.get_decrypted()
|
||||
assert decrypted is not None
|
||||
assert decrypted.bot_token == rotated["bot_token"]
|
||||
@@ -0,0 +1,197 @@
|
||||
"""W5 collision map: the pure ``build_collision_context`` builder.
|
||||
|
||||
Pins the truth table — no parent → None, no surfaced siblings → None,
|
||||
file-overlap sibling shown, both-migration shown without file overlap,
|
||||
shared-only-without-overlap NOT shown, declared-vs-actual drift computed,
|
||||
and the caps respected. Pure (no DB, no IO): duck-typed task/sibling rows.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from uuid import uuid4
|
||||
|
||||
from roboco.services.gateway.choreographer.collision import (
|
||||
COLLISION_GLOB_CAP,
|
||||
COLLISION_SIBLING_CAP,
|
||||
build_collision_context,
|
||||
)
|
||||
|
||||
|
||||
def _task(
|
||||
*,
|
||||
parent_task_id: str | None = "p1",
|
||||
project_id: str = "proj",
|
||||
intends_to_touch: list[str] | None = None,
|
||||
adds_migration: bool = False,
|
||||
touches_shared: bool = False,
|
||||
priority: int = 2,
|
||||
sequence: int = 0,
|
||||
) -> SimpleNamespace:
|
||||
return SimpleNamespace(
|
||||
id=str(uuid4()),
|
||||
parent_task_id=parent_task_id,
|
||||
project_id=project_id,
|
||||
intends_to_touch=intends_to_touch,
|
||||
adds_migration=adds_migration,
|
||||
touches_shared=touches_shared,
|
||||
priority=priority,
|
||||
sequence=sequence,
|
||||
)
|
||||
|
||||
|
||||
def _sib(
|
||||
*,
|
||||
project_id: str = "proj",
|
||||
intends_to_touch: list[str] | None = None,
|
||||
adds_migration: bool = False,
|
||||
touches_shared: bool = False,
|
||||
priority: int = 2,
|
||||
sequence: int = 1,
|
||||
status: str = "in_progress",
|
||||
branch_name: str | None = "feature/x",
|
||||
pr_number: int | None = 7,
|
||||
) -> SimpleNamespace:
|
||||
return SimpleNamespace(
|
||||
id=str(uuid4()),
|
||||
project_id=project_id,
|
||||
intends_to_touch=intends_to_touch,
|
||||
adds_migration=adds_migration,
|
||||
touches_shared=touches_shared,
|
||||
priority=priority,
|
||||
sequence=sequence,
|
||||
status=status,
|
||||
branch_name=branch_name,
|
||||
pr_number=pr_number,
|
||||
title="sibling",
|
||||
)
|
||||
|
||||
|
||||
def test_no_parent_returns_none() -> None:
|
||||
task = _task(parent_task_id=None, intends_to_touch=["a.py"])
|
||||
assert build_collision_context(task=task, siblings=[_sib()]) is None
|
||||
|
||||
|
||||
def test_no_surfaced_siblings_returns_none() -> None:
|
||||
task = _task(intends_to_touch=["a.py"])
|
||||
# sibling with no collision surface at all
|
||||
assert (
|
||||
build_collision_context(task=task, siblings=[_sib(intends_to_touch=None)])
|
||||
is None
|
||||
)
|
||||
|
||||
|
||||
def test_file_overlap_sibling_shown() -> None:
|
||||
task = _task(intends_to_touch=["roboco/services/git.py"])
|
||||
sib = _sib(intends_to_touch=["roboco/services/git.py", "roboco/services/x.py"])
|
||||
ctx = build_collision_context(task=task, siblings=[sib])
|
||||
assert ctx is not None
|
||||
assert len(ctx) == 1
|
||||
assert "roboco/services/git.py" in ctx[0]["overlap"]
|
||||
|
||||
|
||||
def test_no_overlap_no_migration_not_shown() -> None:
|
||||
task = _task(intends_to_touch=["roboco/a.py"])
|
||||
sib = _sib(intends_to_touch=["roboco/b.py"])
|
||||
assert build_collision_context(task=task, siblings=[sib]) is None
|
||||
|
||||
|
||||
def test_both_migration_shown_without_file_overlap() -> None:
|
||||
task = _task(intends_to_touch=["roboco/a.py"], adds_migration=True)
|
||||
sib = _sib(intends_to_touch=["roboco/b.py"], adds_migration=True)
|
||||
ctx = build_collision_context(task=task, siblings=[sib])
|
||||
assert ctx is not None
|
||||
assert ctx[0]["adds_migration"] is True
|
||||
assert ctx[0]["overlap"] == []
|
||||
|
||||
|
||||
def test_one_migration_only_not_shown() -> None:
|
||||
# migration-chain needs BOTH adders; one alone is parallel.
|
||||
task = _task(intends_to_touch=["roboco/a.py"], adds_migration=True)
|
||||
sib = _sib(intends_to_touch=["roboco/b.py"], adds_migration=False)
|
||||
assert build_collision_context(task=task, siblings=[sib]) is None
|
||||
|
||||
|
||||
def test_shared_only_without_overlap_not_shown() -> None:
|
||||
# touches_shared alone is too broad; it rides the file-overlap path.
|
||||
task = _task(intends_to_touch=["roboco/a.py"], touches_shared=True)
|
||||
sib = _sib(intends_to_touch=["roboco/b.py"])
|
||||
assert build_collision_context(task=task, siblings=[sib]) is None
|
||||
|
||||
|
||||
def test_shared_with_overlap_shown_and_flagged() -> None:
|
||||
task = _task(intends_to_touch=["roboco/a.py"], touches_shared=True)
|
||||
sib = _sib(intends_to_touch=["roboco/a.py"], touches_shared=True)
|
||||
ctx = build_collision_context(task=task, siblings=[sib])
|
||||
assert ctx is not None
|
||||
assert ctx[0]["touches_shared"] is True
|
||||
|
||||
|
||||
def test_cross_project_sibling_not_shown() -> None:
|
||||
# collisions are repo-scoped; a sibling in another repo can't collide.
|
||||
task = _task(intends_to_touch=["a.py"], project_id="proj")
|
||||
sib = _sib(intends_to_touch=["a.py"], project_id="other")
|
||||
assert build_collision_context(task=task, siblings=[sib]) is None
|
||||
|
||||
|
||||
def test_self_excluded_from_siblings() -> None:
|
||||
task = _task(intends_to_touch=["a.py"])
|
||||
self_sib = _sib(intends_to_touch=["a.py"])
|
||||
self_sib.id = task.id
|
||||
assert build_collision_context(task=task, siblings=[self_sib]) is None
|
||||
|
||||
|
||||
def test_drift_undeclared_computed() -> None:
|
||||
task = _task(intends_to_touch=["roboco/a.py"])
|
||||
sib = _sib(intends_to_touch=["roboco/a.py"])
|
||||
ctx = build_collision_context(
|
||||
task=task,
|
||||
siblings=[sib],
|
||||
actual_files=["roboco/a.py", "roboco/secret.py"],
|
||||
)
|
||||
assert ctx is not None
|
||||
assert ctx[0]["undeclared"] == ["roboco/secret.py"]
|
||||
|
||||
|
||||
def test_drift_omitted_without_actual_files() -> None:
|
||||
task = _task(intends_to_touch=["roboco/a.py"])
|
||||
sib = _sib(intends_to_touch=["roboco/a.py"])
|
||||
ctx = build_collision_context(task=task, siblings=[sib])
|
||||
assert ctx is not None
|
||||
assert "undeclared" not in ctx[0]
|
||||
|
||||
|
||||
def test_sibling_cap() -> None:
|
||||
task = _task(intends_to_touch=["a.py"])
|
||||
sibs = [
|
||||
_sib(intends_to_touch=["a.py"], sequence=i)
|
||||
for i in range(COLLISION_SIBLING_CAP + 5)
|
||||
]
|
||||
ctx = build_collision_context(task=task, siblings=sibs)
|
||||
assert ctx is not None
|
||||
assert len(ctx) == COLLISION_SIBLING_CAP
|
||||
|
||||
|
||||
def test_glob_cap() -> None:
|
||||
task = _task(intends_to_touch=[f"f{i}.py" for i in range(COLLISION_GLOB_CAP + 5)])
|
||||
sib = _sib(intends_to_touch=[f"f{i}.py" for i in range(COLLISION_GLOB_CAP + 5)])
|
||||
ctx = build_collision_context(task=task, siblings=[sib])
|
||||
assert ctx is not None
|
||||
assert len(ctx[0]["overlap"]) <= COLLISION_GLOB_CAP
|
||||
assert len(ctx[0]["intends_to_touch"]) <= COLLISION_GLOB_CAP
|
||||
|
||||
|
||||
def test_sort_key_orders_by_priority_then_sequence() -> None:
|
||||
task = _task(intends_to_touch=["a.py"])
|
||||
low_prio = _sib(intends_to_touch=["a.py"], priority=3, sequence=0)
|
||||
high_prio = _sib(intends_to_touch=["a.py"], priority=1, sequence=5)
|
||||
mid = _sib(intends_to_touch=["a.py"], priority=2, sequence=1)
|
||||
ctx = build_collision_context(task=task, siblings=[low_prio, high_prio, mid])
|
||||
assert ctx is not None
|
||||
assert [e["sequence"] for e in ctx] == [5, 1, 0]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import pytest
|
||||
|
||||
pytest.main([__file__, "-q"])
|
||||
@@ -7,12 +7,16 @@ dedup of the same project across a product's cells).
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, cast
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
from uuid import UUID
|
||||
|
||||
import pytest
|
||||
from roboco.services.product import ProductService
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from roboco.db.tables import ProductTable
|
||||
|
||||
_PRODUCT_A = UUID("11111111-1111-1111-1111-111111111111")
|
||||
_PRODUCT_B = UUID("22222222-2222-2222-2222-222222222222")
|
||||
_PROJECT_1 = UUID("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")
|
||||
@@ -25,11 +29,11 @@ def _cell(project_id: UUID) -> MagicMock:
|
||||
return cell
|
||||
|
||||
|
||||
def _product(pid: UUID, project_ids: list[UUID]) -> MagicMock:
|
||||
def _product(pid: UUID, project_ids: list[UUID]) -> ProductTable:
|
||||
p = MagicMock()
|
||||
p.id = pid
|
||||
p.cells = [_cell(pid_proj) for pid_proj in project_ids]
|
||||
return p
|
||||
return cast("ProductTable", p)
|
||||
|
||||
|
||||
def _result_fetchall(rows: list[MagicMock]) -> MagicMock:
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
"""TelegramClient coverage: NullTelegramClient no-op, LiveTelegramClient calls."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from roboco.services.telegram_client import (
|
||||
LiveTelegramClient,
|
||||
NullTelegramClient,
|
||||
build_telegram_client,
|
||||
)
|
||||
from roboco.services.telegram_credentials import TelegramCredentialsData
|
||||
|
||||
_CREDS = TelegramCredentialsData(bot_token="123456:ABC", chat_id="987654321")
|
||||
|
||||
|
||||
def test_null_client_is_unconfigured() -> None:
|
||||
client = build_telegram_client(None, timeout=5.0)
|
||||
assert isinstance(client, NullTelegramClient)
|
||||
assert client.configured is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_null_client_send_message_is_a_noop() -> None:
|
||||
client: NullTelegramClient = NullTelegramClient()
|
||||
result = await client.send_message("hello")
|
||||
assert result.sent is False
|
||||
assert result.detail # non-empty reason
|
||||
|
||||
|
||||
def test_build_telegram_client_with_creds_returns_live_client() -> None:
|
||||
client = build_telegram_client(_CREDS, timeout=5.0)
|
||||
assert isinstance(client, LiveTelegramClient)
|
||||
assert client.configured is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_live_client_send_message_success() -> None:
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
assert request.url.path == "/bot123456:ABC/sendMessage"
|
||||
body = json.loads(request.content.decode())
|
||||
assert body == {"chat_id": _CREDS.chat_id, "text": "hi"}
|
||||
return httpx.Response(200, json={"ok": True, "result": {"message_id": 1}})
|
||||
|
||||
transport = httpx.MockTransport(handler)
|
||||
http_client = httpx.AsyncClient(transport=transport)
|
||||
client = LiveTelegramClient(_CREDS, timeout=5.0, client=http_client)
|
||||
result = await client.send_message("hi")
|
||||
assert result.sent is True
|
||||
await client.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_live_client_send_message_http_error_is_graceful() -> None:
|
||||
def handler(_request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(401, text="unauthorized")
|
||||
|
||||
transport = httpx.MockTransport(handler)
|
||||
http_client = httpx.AsyncClient(transport=transport)
|
||||
client = LiveTelegramClient(_CREDS, timeout=5.0, client=http_client)
|
||||
result = await client.send_message("hi")
|
||||
assert result.sent is False
|
||||
assert "401" in result.detail
|
||||
await client.close()
|
||||
@@ -13,6 +13,7 @@ verify the arithmetic / logic of each analytics method:
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
from typing import cast
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
from uuid import UUID
|
||||
|
||||
@@ -349,7 +350,7 @@ class TestGetTimeSeries:
|
||||
)
|
||||
svc = _service_with_execute(_result_fetchall([row]))
|
||||
await svc.get_time_series("7d", agent_slug="be-dev-1")
|
||||
stmt = svc.session.execute.call_args_list[0][0][0]
|
||||
stmt = cast("MagicMock", svc.session.execute).call_args_list[0][0][0]
|
||||
sql = str(stmt.compile(compile_kwargs={"literal_binds": True}))
|
||||
assert "be-dev-1" in sql
|
||||
|
||||
@@ -366,7 +367,7 @@ class TestGetTimeSeries:
|
||||
)
|
||||
svc = _service_with_execute(_result_fetchall([row]))
|
||||
await svc.get_time_series("7d")
|
||||
stmt = svc.session.execute.call_args_list[0][0][0]
|
||||
stmt = cast("MagicMock", svc.session.execute).call_args_list[0][0][0]
|
||||
sql = str(stmt.compile(compile_kwargs={"literal_binds": True}))
|
||||
assert "agent_slug" not in sql
|
||||
|
||||
|
||||
Reference in New Issue
Block a user