Added owlbot.testing package with pytest plugin, event factories, and recording Owncast stubs for module tests.
Audit / Dependencies (push) Successful in 8s
CI / Formatting (push) Successful in 5s
CI / Linting (push) Successful in 5s
CI / Tests (Python 3.12) (push) Successful in 19s
CI / Tests (Python 3.13) (push) Successful in 19s
CI / Tests (Python 3.14) (push) Successful in 16s
CI / Type Checking (push) Successful in 11s
CI / Spelling (push) Successful in 9s

- owlbot.testing.plugin: fixtures that mirror ModuleLoader's wiring (module_context, module_lifecycle, command/event/route dispatchers, in-memory storage, real Config on a tmp YAML, HttpClient with aioresponses interception, and an aiohttp route_client).
- owlbot.testing.helpers: make_user, make_chat_event, and factories for every Owncast event type, with sensible defaults.
- owlbot.testing.stubs: RecordingOwncastClient and RecordingOwncastAdminClient that log each call to a .calls list in place of hitting the API.
- pyproject.toml: added a 'testing' extra for downstream module authors (pytest, pytest-asyncio, pytest-aiohttp, aioresponses).
- tests: migrated in-tree tests to the new helpers, moved module tests under tests/builtin_modules/, and swapped freezegun for time-machine.
This commit is contained in:
2026-04-22 21:49:16 -04:00
parent 32e21a6f9d
commit a671541b13
25 changed files with 8195 additions and 3093 deletions
+1
View File
@@ -0,0 +1 @@
"""Tests for built-in Owlbot modules."""
@@ -0,0 +1 @@
"""Tests for the custom_commands built-in module."""
File diff suppressed because it is too large Load Diff
@@ -25,7 +25,7 @@ from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any
import pytest
from freezegun import freeze_time
import time_machine
from owlbot.builtin_modules.custom_commands.placeholder_handlers import _format_duration
from owlbot.builtin_modules.custom_commands.placeholders import process_placeholders
@@ -612,7 +612,7 @@ class TestCountdownCountup:
self, placeholder_storage: ModuleStorage
) -> None:
"""$(countdown) with a future date returns the formatted duration."""
with freeze_time("2026-06-15 12:00:00", tz_offset=0):
with time_machine.travel("2026-06-15 12:00:00+00:00", tick=False):
now = datetime.now(UTC)
# Dec 25 2099 00:00:00 EST = Dec 25 2099 05:00:00 UTC
target = datetime(2099, 12, 25, 5, 0, 0, tzinfo=UTC)
@@ -624,7 +624,7 @@ class TestCountdownCountup:
async def test_countup_past_date(self, placeholder_storage: ModuleStorage) -> None:
"""$(countup) with a past date returns the formatted elapsed duration."""
with freeze_time("2026-06-15 12:00:00", tz_offset=0):
with time_machine.travel("2026-06-15 12:00:00+00:00", tick=False):
now = datetime.now(UTC)
target = datetime(2020, 1, 1, 0, 0, 0, tzinfo=UTC)
expected = _format_duration(int((now - target).total_seconds()))
@@ -673,7 +673,7 @@ class TestCountdownCountup:
self, placeholder_storage: ModuleStorage
) -> None:
"""Fractional offset like IST (+5:30) is applied.""" # codespell:ignore ist
with freeze_time("2026-06-15 12:00:00", tz_offset=0):
with time_machine.travel("2026-06-15 12:00:00+00:00", tick=False):
now = datetime.now(UTC)
# IST = Dec 31 2019 18:30:00 UTC # codespell:ignore ist
target = datetime(2019, 12, 31, 18, 30, 0, tzinfo=UTC)
@@ -939,7 +939,7 @@ class TestCaseInsensitivity:
self, placeholder_storage: ModuleStorage
) -> None:
"""$(COUNTUP) resolves the same as $(countup)."""
with freeze_time("2026-06-15 12:00:00", tz_offset=0):
with time_machine.travel("2026-06-15 12:00:00+00:00", tick=False):
now = datetime.now(UTC)
target = datetime(2020, 1, 1, 0, 0, 0, tzinfo=UTC)
expected = _format_duration(int((now - target).total_seconds()))
+513
View File
@@ -0,0 +1,513 @@
# Copyright 2026 Logan Fick
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for the quotes module."""
from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
from owlbot.api.event_types import EventType
from owlbot.builtin_modules import quotes as quotes_pkg
from owlbot.builtin_modules.quotes import setup, teardown
from owlbot.builtin_modules.quotes.manager import QuoteManager, get_manager
from owlbot.builtin_modules.quotes.repository import QuoteRepository
from owlbot.builtin_modules.quotes.types import (
Quote,
QuoteError,
QuoteNotFoundError,
)
from owlbot.testing import make_chat_event, make_user
if TYPE_CHECKING:
from types import ModuleType
from typing import Any
from aiohttp.test_utils import TestClient
from owlbot.api.context import ModuleContext
from owlbot.api.storage import ModuleStorage
from owlbot.registries.events import EventDispatcher
from owlbot.testing import RecordingOwncastClient
@pytest.fixture
def module_pkg() -> ModuleType:
"""Auto-wire module_name, templates, and handler registration for quotes."""
return quotes_pkg
@pytest.fixture
async def repo(storage: ModuleStorage) -> QuoteRepository:
"""QuoteRepository backed by storage, with schema initialized."""
repo = QuoteRepository(storage)
await repo.setup()
return repo
@pytest.fixture
def manager(module_context: ModuleContext, repo: QuoteRepository) -> QuoteManager:
"""QuoteManager built directly for unit tests; does not run @on_setup."""
return QuoteManager(module_context, repo)
class TestTypes:
"""Quote dataclass conversion, date formatting, and domain errors."""
def test_builds_from_row(self) -> None:
"""Quote.from_row constructs a Quote with correct field values."""
row = {
"id": 5,
"text": "Test quote",
"added_by": "someone",
"created_at": "2026-03-15T10:00:00+00:00",
}
quote = Quote.from_row(row) # type: ignore[arg-type]
assert quote.id == 5
assert quote.text == "Test quote"
assert quote.added_by == "someone"
assert quote.created_at == "2026-03-15T10:00:00+00:00"
@pytest.mark.parametrize(
("created_at", "expected"),
[
pytest.param("2026-03-15T10:00:00+00:00", "2026-03-15", id="utc"),
pytest.param(
"2026-03-15T01:00:00+05:30",
"2026-03-15",
id="local-date-preserved-across-utc-boundary",
),
],
)
def test_date(self, created_at: str, expected: str) -> None:
"""Quote.date returns the local calendar date, not the UTC date."""
quote = Quote(id=1, text="t", added_by="a", created_at=created_at)
assert quote.date == expected
def test_not_found_inherits_from_quote_error(self) -> None:
"""QuoteNotFoundError is a QuoteError."""
assert issubclass(QuoteNotFoundError, QuoteError)
def test_not_found_stores_quote_id(self) -> None:
"""QuoteNotFoundError stores the quote ID on .quote_id."""
err = QuoteNotFoundError(42)
assert err.quote_id == 42
def test_not_found_str_contains_id(self) -> None:
"""QuoteNotFoundError's str contains the quote ID."""
err = QuoteNotFoundError(42)
assert "42" in str(err)
class TestRepository:
"""QuoteRepository CRUD behavior against real storage."""
async def test_create_returns_quote(self, repo: QuoteRepository) -> None:
"""Create returns a populated Quote snapshot."""
quote = await repo.create("Hello, world!", "tester")
assert quote.id == 1
assert quote.text == "Hello, world!"
assert quote.added_by == "tester"
assert quote.created_at is not None
async def test_create_auto_increments(self, repo: QuoteRepository) -> None:
"""Sequential creates get sequential IDs."""
q1 = await repo.create("First", "tester")
q2 = await repo.create("Second", "tester")
assert q2.id == q1.id + 1
async def test_get_existing(self, repo: QuoteRepository) -> None:
"""Get returns the matching quote."""
created = await repo.create("Test", "tester")
fetched = await repo.get(created.id)
assert fetched.id == created.id
assert fetched.text == "Test"
async def test_get_not_found(self, repo: QuoteRepository) -> None:
"""Get raises QuoteNotFoundError for an unknown ID."""
with pytest.raises(QuoteNotFoundError) as exc_info:
await repo.get(999)
assert exc_info.value.quote_id == 999
async def test_get_random_returns_quote(self, repo: QuoteRepository) -> None:
"""get_random returns the lone quote when the table has one row."""
await repo.create("Only quote", "tester")
quote = await repo.get_random()
assert quote is not None
assert quote.text == "Only quote"
async def test_get_random_empty(self, repo: QuoteRepository) -> None:
"""get_random returns None when the table is empty."""
assert await repo.get_random() is None
async def test_delete_returns_quote(self, repo: QuoteRepository) -> None:
"""Delete returns the deleted snapshot."""
created = await repo.create("Doomed", "tester")
deleted = await repo.delete(created.id)
assert deleted.id == created.id
assert deleted.text == "Doomed"
async def test_delete_removes_from_db(self, repo: QuoteRepository) -> None:
"""A deleted quote is no longer retrievable."""
created = await repo.create("Doomed", "tester")
await repo.delete(created.id)
with pytest.raises(QuoteNotFoundError):
await repo.get(created.id)
async def test_delete_not_found(self, repo: QuoteRepository) -> None:
"""Delete raises QuoteNotFoundError for an unknown ID."""
with pytest.raises(QuoteNotFoundError) as exc_info:
await repo.delete(999)
assert exc_info.value.quote_id == 999
async def test_list_all(self, repo: QuoteRepository) -> None:
"""list_all returns quotes ordered by ID."""
await repo.create("First", "alice")
await repo.create("Second", "bob")
result = await repo.list_all()
assert len(result) == 2
assert result[0].text == "First"
assert result[1].text == "Second"
async def test_list_all_empty(self, repo: QuoteRepository) -> None:
"""list_all returns an empty list when no quotes exist."""
assert await repo.list_all() == []
class TestManager:
"""QuoteManager forwarding behavior and the get_manager helper."""
async def test_add_quote(self, manager: QuoteManager) -> None:
"""add_quote returns a populated Quote with correct fields."""
quote = await manager.add_quote("Test quote", "tester")
assert quote.id == 1
assert quote.text == "Test quote"
assert quote.added_by == "tester"
async def test_delete_quote(self, manager: QuoteManager) -> None:
"""delete_quote removes the quote and returns its snapshot."""
created = await manager.add_quote("Doomed", "tester")
deleted = await manager.delete_quote(created.id)
assert deleted.id == created.id
assert deleted.text == "Doomed"
assert await manager.list_quotes() == []
async def test_delete_quote_not_found(self, manager: QuoteManager) -> None:
"""delete_quote raises QuoteNotFoundError for an unknown ID."""
with pytest.raises(QuoteNotFoundError):
await manager.delete_quote(999)
async def test_get_quote(self, manager: QuoteManager) -> None:
"""get_quote returns the matching quote."""
created = await manager.add_quote("Test", "tester")
fetched = await manager.get_quote(created.id)
assert fetched.id == created.id
assert fetched.text == "Test"
async def test_get_quote_not_found(self, manager: QuoteManager) -> None:
"""get_quote raises QuoteNotFoundError for an unknown ID."""
with pytest.raises(QuoteNotFoundError):
await manager.get_quote(999)
async def test_get_random_quote(self, manager: QuoteManager) -> None:
"""get_random_quote returns a quote when quotes exist."""
await manager.add_quote("Only one", "tester")
quote = await manager.get_random_quote()
assert quote is not None
assert quote.text == "Only one"
async def test_get_random_quote_empty(self, manager: QuoteManager) -> None:
"""get_random_quote returns None when no quotes exist."""
assert await manager.get_random_quote() is None
async def test_list_quotes(self, manager: QuoteManager) -> None:
"""list_quotes returns all quotes ordered by ID."""
await manager.add_quote("First", "alice")
await manager.add_quote("Second", "bob")
result = await manager.list_quotes()
assert len(result) == 2
assert result[0].text == "First"
assert result[1].text == "Second"
async def test_list_quotes_empty(self, manager: QuoteManager) -> None:
"""list_quotes returns an empty list when no quotes exist."""
assert await manager.list_quotes() == []
def test_get_manager_returns_stored_manager(
self, module_context: ModuleContext, repo: QuoteRepository
) -> None:
"""get_manager returns the QuoteManager stored in ctx.state."""
mgr = QuoteManager(module_context, repo)
module_context.state["manager"] = mgr
assert get_manager(module_context) is mgr
def test_get_manager_raises_if_not_initialized(
self, module_context: ModuleContext
) -> None:
"""get_manager raises RuntimeError when manager is missing."""
with pytest.raises(RuntimeError, match="QuoteManager is not initialized"):
get_manager(module_context)
class TestModuleLifecycle:
"""@on_setup and @on_teardown hooks."""
async def test_setup_creates_table_and_manager(
self, module_context: ModuleContext, storage: ModuleStorage
) -> None:
"""Setup creates the quotes table and stashes a QuoteManager in state."""
await setup(module_context)
row = await storage.fetch_one(
"SELECT name FROM sqlite_master WHERE type='table' AND name='quotes'"
)
assert row is not None
assert row["name"] == "quotes"
mgr = module_context.state["manager"]
assert isinstance(mgr, QuoteManager)
async def test_teardown_clears_manager(self, module_context: ModuleContext) -> None:
"""Teardown clears the manager from state."""
await setup(module_context)
await teardown(module_context)
assert module_context.state["manager"] is None
@pytest.mark.usefixtures("module_lifecycle")
class TestQuoteCommand:
"""!quote command handler."""
async def test_quote_empty_db(
self,
event_dispatcher: EventDispatcher,
owncast_client: RecordingOwncastClient,
) -> None:
"""!quote with no stored quotes reports empty."""
event = make_chat_event(raw_body="!quote")
await event_dispatcher.dispatch(EventType.CHAT, event)
assert (
owncast_client.calls[0].kwargs["body"] == "No quotes have been added yet."
)
async def test_quote_random(
self,
module_context: ModuleContext,
event_dispatcher: EventDispatcher,
owncast_client: RecordingOwncastClient,
) -> None:
"""!quote with no ID returns a random quote."""
await get_manager(module_context).add_quote("The only one", "tester")
event = make_chat_event(raw_body="!quote")
await event_dispatcher.dispatch(EventType.CHAT, event)
assert owncast_client.calls[0].kwargs["body"] == '"The only one" (#1)'
async def test_quote_by_id(
self,
module_context: ModuleContext,
event_dispatcher: EventDispatcher,
owncast_client: RecordingOwncastClient,
) -> None:
"""!quote <id> returns the formatted detail for that quote."""
seeded = await get_manager(module_context).add_quote("Hello", "ModUser")
event = make_chat_event(raw_body="!quote 1")
await event_dispatcher.dispatch(EventType.CHAT, event)
assert owncast_client.calls[0].kwargs["body"] == (
f'Quote #1: "Hello" - Added by ModUser on {seeded.date}'
)
async def test_quote_not_found(
self,
event_dispatcher: EventDispatcher,
owncast_client: RecordingOwncastClient,
) -> None:
"""!quote <unknown-id> reports not found."""
event = make_chat_event(raw_body="!quote 999")
await event_dispatcher.dispatch(EventType.CHAT, event)
assert owncast_client.calls[0].kwargs["body"] == "Quote #999 not found."
async def test_quote_invalid_id(
self,
event_dispatcher: EventDispatcher,
owncast_client: RecordingOwncastClient,
) -> None:
"""!quote <non-int> sends usage."""
event = make_chat_event(raw_body="!quote abc")
await event_dispatcher.dispatch(EventType.CHAT, event)
assert owncast_client.calls[0].kwargs["body"] == "Usage: !quote [id]"
@pytest.mark.usefixtures("module_lifecycle")
class TestAddQuoteCommand:
"""!addquote command handler."""
async def test_addquote_attributes_to_user(
self,
module_context: ModuleContext,
event_dispatcher: EventDispatcher,
owncast_client: RecordingOwncastClient,
) -> None:
"""!addquote creates the quote attributed to the moderator's display name."""
user = make_user(display_name="ModUser", is_moderator=True)
event = make_chat_event(raw_body="!addquote Hello there", user=user)
await event_dispatcher.dispatch(EventType.CHAT, event)
assert owncast_client.calls[0].kwargs["body"] == "Quote #1 added."
stored = await get_manager(module_context).list_quotes()
assert len(stored) == 1
assert stored[0].text == "Hello there"
assert stored[0].added_by == "ModUser"
async def test_addquote_no_text(
self,
event_dispatcher: EventDispatcher,
owncast_client: RecordingOwncastClient,
) -> None:
"""!addquote with no text sends usage."""
user = make_user(is_moderator=True)
event = make_chat_event(raw_body="!addquote", user=user)
await event_dispatcher.dispatch(EventType.CHAT, event)
assert owncast_client.calls[0].kwargs["body"] == "Usage: !addquote <quote text>"
@pytest.mark.usefixtures("module_lifecycle")
class TestDeleteQuoteCommand:
"""!deletequote command handler."""
async def test_deletequote_removes(
self,
module_context: ModuleContext,
event_dispatcher: EventDispatcher,
owncast_client: RecordingOwncastClient,
) -> None:
"""!deletequote <id> removes the quote and confirms."""
manager = get_manager(module_context)
await manager.add_quote("Doomed", "tester")
user = make_user(is_moderator=True)
event = make_chat_event(raw_body="!deletequote 1", user=user)
await event_dispatcher.dispatch(EventType.CHAT, event)
assert owncast_client.calls[0].kwargs["body"] == "Quote #1 deleted."
assert await manager.list_quotes() == []
async def test_deletequote_no_args(
self,
event_dispatcher: EventDispatcher,
owncast_client: RecordingOwncastClient,
) -> None:
"""!deletequote with no args sends usage."""
user = make_user(is_moderator=True)
event = make_chat_event(raw_body="!deletequote", user=user)
await event_dispatcher.dispatch(EventType.CHAT, event)
assert owncast_client.calls[0].kwargs["body"] == "Usage: !deletequote <id>"
async def test_deletequote_invalid_id(
self,
event_dispatcher: EventDispatcher,
owncast_client: RecordingOwncastClient,
) -> None:
"""!deletequote <non-int> sends usage."""
user = make_user(is_moderator=True)
event = make_chat_event(raw_body="!deletequote abc", user=user)
await event_dispatcher.dispatch(EventType.CHAT, event)
assert owncast_client.calls[0].kwargs["body"] == "Usage: !deletequote <id>"
async def test_deletequote_not_found(
self,
event_dispatcher: EventDispatcher,
owncast_client: RecordingOwncastClient,
) -> None:
"""!deletequote <unknown-id> reports not found."""
user = make_user(is_moderator=True)
event = make_chat_event(raw_body="!deletequote 999", user=user)
await event_dispatcher.dispatch(EventType.CHAT, event)
assert owncast_client.calls[0].kwargs["body"] == "Quote #999 not found."
@pytest.mark.usefixtures("module_lifecycle")
class TestListQuotesCommand:
"""!listquotes command handler."""
async def test_listquotes_sends_url(
self,
event_dispatcher: EventDispatcher,
owncast_client: RecordingOwncastClient,
) -> None:
"""!listquotes sends the public URL of the /list route."""
event = make_chat_event(raw_body="!listquotes")
await event_dispatcher.dispatch(EventType.CHAT, event)
assert (
owncast_client.calls[0].kwargs["body"]
== "Quotes: http://localhost:8081/owlbot/quotes/list"
)
@pytest.mark.usefixtures("module_lifecycle")
class TestQuotesListRoute:
"""/list HTML route."""
async def test_list_empty(
self,
route_client: TestClient[Any, Any],
) -> None:
"""GET /list with no quotes serves the empty-state message."""
resp = await route_client.get("/owlbot/quotes/list")
assert resp.status == 200
assert resp.content_type == "text/html"
body = await resp.text()
assert "No quotes have been added yet." in body
async def test_list_populated(
self,
module_context: ModuleContext,
route_client: TestClient[Any, Any],
) -> None:
"""GET /list with quotes includes each quote's text and attribution."""
manager = get_manager(module_context)
await manager.add_quote("First quote", "alice")
await manager.add_quote("Second quote", "bob")
resp = await route_client.get("/owlbot/quotes/list")
assert resp.status == 200
body = await resp.text()
assert "First quote" in body
assert "Second quote" in body
assert "alice" in body
assert "bob" in body
@pytest.mark.usefixtures("module_lifecycle")
class TestModeratorPermissions:
"""Moderator-required commands deny non-moderators."""
@pytest.mark.parametrize("command", ["addquote", "deletequote"])
async def test_non_moderator_denied(
self,
command: str,
event_dispatcher: EventDispatcher,
owncast_client: RecordingOwncastClient,
) -> None:
"""Non-moderator invocation triggers the dispatcher denial."""
user = make_user(is_moderator=False)
event = make_chat_event(raw_body=f"!{command}", user=user)
await event_dispatcher.dispatch(EventType.CHAT, event)
denials = [
c.kwargs["body"]
for c in owncast_client.calls
if c.name == "send_system_message_to_client"
]
assert denials == [f"Only moderators can use !{command}."]
File diff suppressed because it is too large Load Diff
+6 -35
View File
@@ -12,41 +12,12 @@
# See the License for the specific language governing permissions and
# limitations under the License.
"""Shared test fixtures for the Owlbot test suite."""
"""Shared test fixtures for the Owlbot test suite.
The ``storage`` fixture is provided by the ``owlbot.testing`` pytest plugin,
loaded via ``pytest_plugins`` below.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
from owlbot.api.context import ModuleContext
from owlbot.api.storage import ModuleStorage
if TYPE_CHECKING:
from collections.abc import AsyncIterator
def make_module_context(
storage: ModuleStorage | None = None, module_name: str = "mod_a"
) -> ModuleContext:
"""Build a stub ModuleContext backed by real or None storage."""
return ModuleContext(
module_name=module_name,
config=None, # type: ignore[arg-type]
owncast_client=None, # type: ignore[arg-type]
storage=storage, # type: ignore[arg-type]
commands=None, # type: ignore[arg-type]
events=None, # type: ignore[arg-type]
routes=None, # type: ignore[arg-type]
http=None, # type: ignore[arg-type]
templates=None, # type: ignore[arg-type]
admin_client=None,
)
@pytest.fixture
async def storage() -> AsyncIterator[ModuleStorage]:
"""Yield an open in-memory ModuleStorage."""
async with ModuleStorage(None, "test_module") as s:
yield s
pytest_plugins = ["owlbot.testing.plugin", "pytester"]
+189 -186
View File
@@ -32,72 +32,19 @@ import pytest
from owlbot.api.commands import CommandEvent, CommandInfo, CommandMark, on_command
from owlbot.api.context import CommandContext, EventContext
from owlbot.api.event_types import ChatEvent, User
from owlbot.registries.commands import (
CommandDispatcher,
CommandRegistry,
ModuleCommands,
)
from tests.conftest import make_module_context
from owlbot.testing import RecordingOwncastClient, make_chat_event, make_user
if TYPE_CHECKING:
from owlbot.api.context import ModuleContext
from owlbot.api.event_types import ChatEvent
from owlbot.api.storage import ModuleStorage
def _make_user(
*,
user_id: str = "user-1",
display_name: str = "Alice",
is_authenticated: bool = False,
scopes: frozenset[str] | None = None,
) -> User:
"""Build a minimal User for test events."""
return User(
id=user_id,
display_name=display_name,
display_color=0,
created_at=None,
previous_names=[],
name_changed_at=None,
is_bot=False,
is_authenticated=is_authenticated,
scopes=scopes or frozenset(),
)
def _make_chat_event(
*,
body: str = "hello",
user: User | None = None,
client_id: int = 42,
) -> ChatEvent:
"""Build a minimal ChatEvent for test dispatches."""
return ChatEvent(
user=user or _make_user(),
client_id=client_id,
body=body,
raw_body=body,
message_id="msg-001",
is_visible=True,
timestamp=None,
)
class _StubOwncastClient:
"""Recording stub for OwncastClient used in dispatcher tests."""
def __init__(self) -> None:
self.system_messages: list[tuple[int, str]] = []
self.messages: list[str] = []
async def send_system_message_to_client(self, client_id: int, body: str) -> None:
self.system_messages.append((client_id, body))
async def send_message(self, body: str) -> None:
self.messages.append(body)
class TestOnCommandDecorator:
"""Tests the @on_command decorator from owlbot.api.commands."""
@@ -155,7 +102,7 @@ class TestCommandEvent:
def test_fields_accessible(self) -> None:
"""Construct with known values; assert each field matches."""
event = _make_chat_event()
event = make_chat_event(client_id=42)
cmd_event = CommandEvent(
command="greet",
args="hello world",
@@ -492,36 +439,33 @@ class TestCommandDispatcherDispatch:
def _make_dispatcher(
self,
storage: ModuleStorage,
module_context: ModuleContext,
*,
owncast_client: _StubOwncastClient | None = None,
owncast_client: RecordingOwncastClient | None = None,
handler_timeout: float = 5.0,
command_prefix: str = "!",
module_name: str = "mod_a",
) -> tuple[CommandDispatcher, ModuleContext, _StubOwncastClient]:
"""Build a CommandDispatcher with a real storage-backed ModuleContext."""
stub = owncast_client or _StubOwncastClient()
module_ctx = make_module_context(storage, module_name)
) -> tuple[CommandDispatcher, ModuleContext, RecordingOwncastClient]:
"""Build a CommandDispatcher wired to the given ModuleContext."""
stub = owncast_client or RecordingOwncastClient()
dispatcher = CommandDispatcher(
get_module_context=lambda _name: module_ctx,
owncast_client=stub, # type: ignore[arg-type]
get_module_context=lambda _name: module_context,
owncast_client=stub,
handler_timeout=handler_timeout,
loaded_modules=set(),
command_prefix=command_prefix,
)
return dispatcher, module_ctx, stub
return dispatcher, module_context, stub
async def test_dispatches_command(self, storage: ModuleStorage) -> None:
async def test_dispatches_command(self, module_context: ModuleContext) -> None:
"""Handler receives a CommandContext with correct command and chat_event."""
captured: list[CommandContext] = []
async def handler(ctx: CommandContext) -> None:
captured.append(ctx)
dispatcher, _, _ = self._make_dispatcher(storage)
dispatcher, _, _ = self._make_dispatcher(module_context)
dispatcher.register("ping", handler, module_name="mod_a")
event = _make_chat_event(body="!ping")
event = make_chat_event(client_id=42, raw_body="!ping")
await dispatcher.dispatch(event)
assert len(captured) == 1
@@ -529,34 +473,38 @@ class TestCommandDispatcherDispatch:
assert captured[0].args == ""
assert captured[0].chat_event is event
async def test_dispatches_with_args(self, storage: ModuleStorage) -> None:
async def test_dispatches_with_args(self, module_context: ModuleContext) -> None:
"""Handler receives parsed args and args_list."""
captured: list[CommandContext] = []
async def handler(ctx: CommandContext) -> None:
captured.append(ctx)
dispatcher, _, _ = self._make_dispatcher(storage)
dispatcher, _, _ = self._make_dispatcher(module_context)
dispatcher.register("greet", handler, module_name="mod_a")
await dispatcher.dispatch(_make_chat_event(body="!greet hello world"))
await dispatcher.dispatch(
make_chat_event(client_id=42, raw_body="!greet hello world")
)
assert captured[0].args == "hello world"
assert captured[0].args_list == ["hello", "world"]
async def test_dispatches_via_alias(self, storage: ModuleStorage) -> None:
async def test_dispatches_via_alias(self, module_context: ModuleContext) -> None:
"""Alias resolves to canonical name in ctx.command."""
captured: list[CommandContext] = []
async def handler(ctx: CommandContext) -> None:
captured.append(ctx)
dispatcher, _, _ = self._make_dispatcher(storage)
dispatcher, _, _ = self._make_dispatcher(module_context)
dispatcher.register("ping", handler, aliases=["p"], module_name="mod_a")
await dispatcher.dispatch(_make_chat_event(body="!p"))
await dispatcher.dispatch(make_chat_event(client_id=42, raw_body="!p"))
assert captured[0].command == "ping"
async def test_non_command_message_ignored(self, storage: ModuleStorage) -> None:
async def test_non_command_message_ignored(
self, module_context: ModuleContext
) -> None:
"""A regular message does not invoke the handler."""
called = False
@@ -564,14 +512,16 @@ class TestCommandDispatcherDispatch:
nonlocal called
called = True
dispatcher, _, _ = self._make_dispatcher(storage)
dispatcher, _, _ = self._make_dispatcher(module_context)
dispatcher.register("ping", handler, module_name="mod_a")
await dispatcher.dispatch(_make_chat_event(body="hello everyone"))
await dispatcher.dispatch(
make_chat_event(client_id=42, raw_body="hello everyone")
)
assert called is False
async def test_unknown_command_ignored(
self, storage: ModuleStorage, caplog: pytest.LogCaptureFixture
self, module_context: ModuleContext, caplog: pytest.LogCaptureFixture
) -> None:
"""An unknown command is ignored and logged at DEBUG level."""
called = False
@@ -580,15 +530,19 @@ class TestCommandDispatcherDispatch:
nonlocal called
called = True
dispatcher, _, _ = self._make_dispatcher(storage)
dispatcher, _, _ = self._make_dispatcher(module_context)
dispatcher.register("ping", handler, module_name="mod_a")
with caplog.at_level(logging.DEBUG, logger="owlbot.commands"):
await dispatcher.dispatch(_make_chat_event(body="!nonexistent"))
await dispatcher.dispatch(
make_chat_event(client_id=42, raw_body="!nonexistent")
)
assert called is False
assert "Unknown command: nonexistent" in caplog.text
async def test_requires_authenticated_allowed(self, storage: ModuleStorage) -> None:
async def test_requires_authenticated_allowed(
self, module_context: ModuleContext
) -> None:
"""Authenticated user can invoke a requires_authenticated command."""
called = False
@@ -596,17 +550,19 @@ class TestCommandDispatcherDispatch:
nonlocal called
called = True
dispatcher, _, _ = self._make_dispatcher(storage)
dispatcher, _, _ = self._make_dispatcher(module_context)
dispatcher.register(
"ping", handler, requires_authenticated=True, module_name="mod_a"
)
user = _make_user(is_authenticated=True)
await dispatcher.dispatch(_make_chat_event(body="!ping", user=user))
user = make_user(is_authenticated=True)
await dispatcher.dispatch(
make_chat_event(client_id=42, raw_body="!ping", user=user)
)
assert called is True
async def test_requires_authenticated_denied(
self, storage: ModuleStorage, caplog: pytest.LogCaptureFixture
self, module_context: ModuleContext, caplog: pytest.LogCaptureFixture
) -> None:
"""Unauthenticated user is denied and gets a system message."""
called = False
@@ -615,22 +571,30 @@ class TestCommandDispatcherDispatch:
nonlocal called
called = True
dispatcher, _, stub = self._make_dispatcher(storage)
dispatcher, _, stub = self._make_dispatcher(module_context)
dispatcher.register(
"ping", handler, requires_authenticated=True, module_name="mod_a"
)
user = _make_user(is_authenticated=False)
user = make_user(display_name="Alice", is_authenticated=False)
with caplog.at_level(logging.INFO, logger="owlbot.commands"):
await dispatcher.dispatch(_make_chat_event(body="!ping", user=user))
await dispatcher.dispatch(
make_chat_event(client_id=42, raw_body="!ping", user=user)
)
assert called is False
assert stub.system_messages[0] == (
42,
"You must be authenticated to use !ping.",
assert stub.calls[0] == (
"send_system_message_to_client",
{
"client_id": 42,
"body": "You must be authenticated to use !ping.",
"unsanitized": False,
},
)
assert "Command 'ping' denied for Alice: authentication required" in caplog.text
async def test_requires_moderator_allowed(self, storage: ModuleStorage) -> None:
async def test_requires_moderator_allowed(
self, module_context: ModuleContext
) -> None:
"""Moderator user can invoke a requires_moderator command."""
called = False
@@ -638,17 +602,19 @@ class TestCommandDispatcherDispatch:
nonlocal called
called = True
dispatcher, _, _ = self._make_dispatcher(storage)
dispatcher, _, _ = self._make_dispatcher(module_context)
dispatcher.register(
"ban", handler, requires_moderator=True, module_name="mod_a"
)
user = _make_user(scopes=frozenset({"MODERATOR"}))
await dispatcher.dispatch(_make_chat_event(body="!ban", user=user))
user = make_user(scopes=frozenset({"MODERATOR"}))
await dispatcher.dispatch(
make_chat_event(client_id=42, raw_body="!ban", user=user)
)
assert called is True
async def test_requires_moderator_denied(
self, storage: ModuleStorage, caplog: pytest.LogCaptureFixture
self, module_context: ModuleContext, caplog: pytest.LogCaptureFixture
) -> None:
"""Non-moderator user is denied and gets a system message."""
called = False
@@ -657,19 +623,30 @@ class TestCommandDispatcherDispatch:
nonlocal called
called = True
dispatcher, _, stub = self._make_dispatcher(storage)
dispatcher, _, stub = self._make_dispatcher(module_context)
dispatcher.register(
"ping", handler, requires_moderator=True, module_name="mod_a"
)
user = _make_user(scopes=frozenset())
user = make_user(display_name="Alice", scopes=frozenset())
with caplog.at_level(logging.INFO, logger="owlbot.commands"):
await dispatcher.dispatch(_make_chat_event(body="!ping", user=user))
await dispatcher.dispatch(
make_chat_event(client_id=42, raw_body="!ping", user=user)
)
assert called is False
assert stub.system_messages[0] == (42, "Only moderators can use !ping.")
assert stub.calls[0] == (
"send_system_message_to_client",
{
"client_id": 42,
"body": "Only moderators can use !ping.",
"unsanitized": False,
},
)
assert "Command 'ping' denied for Alice: moderator required" in caplog.text
async def test_cooldown_allows_first_call(self, storage: ModuleStorage) -> None:
async def test_cooldown_allows_first_call(
self, module_context: ModuleContext
) -> None:
"""First invocation of a command with cooldown is allowed."""
called = False
@@ -677,14 +654,14 @@ class TestCommandDispatcherDispatch:
nonlocal called
called = True
dispatcher, _, _ = self._make_dispatcher(storage)
dispatcher, _, _ = self._make_dispatcher(module_context)
dispatcher.register("ping", handler, cooldown=60, module_name="mod_a")
await dispatcher.dispatch(_make_chat_event(body="!ping"))
await dispatcher.dispatch(make_chat_event(client_id=42, raw_body="!ping"))
assert called is True
async def test_cooldown_blocks_second_call(
self, storage: ModuleStorage, caplog: pytest.LogCaptureFixture
self, module_context: ModuleContext, caplog: pytest.LogCaptureFixture
) -> None:
"""Second invocation within cooldown is blocked with a message."""
call_count = 0
@@ -693,19 +670,22 @@ class TestCommandDispatcherDispatch:
nonlocal call_count
call_count += 1
dispatcher, _, stub = self._make_dispatcher(storage)
dispatcher, _, stub = self._make_dispatcher(module_context)
dispatcher.register("ping", handler, cooldown=60, module_name="mod_a")
await dispatcher.dispatch(_make_chat_event(body="!ping"))
await dispatcher.dispatch(make_chat_event(client_id=42, raw_body="!ping"))
with caplog.at_level(logging.INFO, logger="owlbot.commands"):
await dispatcher.dispatch(_make_chat_event(body="!ping"))
await dispatcher.dispatch(make_chat_event(client_id=42, raw_body="!ping"))
assert call_count == 1
assert len(stub.system_messages) == 1
assert "!ping can be used every 60s" in stub.system_messages[0][1]
assert len(stub.calls) == 1
assert stub.calls[0].name == "send_system_message_to_client"
assert "!ping can be used every 60s" in stub.calls[0].kwargs["body"]
assert "on cooldown" in caplog.text
async def test_cooldown_zero_no_throttle(self, storage: ModuleStorage) -> None:
async def test_cooldown_zero_no_throttle(
self, module_context: ModuleContext
) -> None:
"""Commands with cooldown=0 are never throttled."""
call_count = 0
@@ -713,15 +693,17 @@ class TestCommandDispatcherDispatch:
nonlocal call_count
call_count += 1
dispatcher, _, _ = self._make_dispatcher(storage)
dispatcher, _, _ = self._make_dispatcher(module_context)
dispatcher.register("ping", handler, cooldown=0, module_name="mod_a")
await dispatcher.dispatch(_make_chat_event(body="!ping"))
await dispatcher.dispatch(_make_chat_event(body="!ping"))
await dispatcher.dispatch(make_chat_event(client_id=42, raw_body="!ping"))
await dispatcher.dispatch(make_chat_event(client_id=42, raw_body="!ping"))
assert call_count == 2
async def test_success_commits(self, storage: ModuleStorage) -> None:
async def test_success_commits(
self, module_context: ModuleContext, storage: ModuleStorage
) -> None:
"""A successful handler's database changes are committed."""
async def handler(ctx: CommandContext) -> None:
@@ -732,16 +714,19 @@ class TestCommandDispatcherDispatch:
"INSERT INTO items (id, name) VALUES (?, ?)", (1, "apple")
)
dispatcher, _, _ = self._make_dispatcher(storage)
dispatcher, _, _ = self._make_dispatcher(module_context)
dispatcher.register("add", handler, module_name="mod_a")
await dispatcher.dispatch(_make_chat_event(body="!add"))
await dispatcher.dispatch(make_chat_event(client_id=42, raw_body="!add"))
row = await storage.fetch_one("SELECT * FROM items WHERE id = ?", (1,))
assert row is not None
assert row["name"] == "apple"
async def test_exception_does_not_roll_back_committed_writes(
self, storage: ModuleStorage, caplog: pytest.LogCaptureFixture
self,
module_context: ModuleContext,
storage: ModuleStorage,
caplog: pytest.LogCaptureFixture,
) -> None:
"""A handler that raises does not undo already-committed writes."""
await storage.execute(
@@ -754,10 +739,10 @@ class TestCommandDispatcherDispatch:
)
raise RuntimeError("boom")
dispatcher, _, _ = self._make_dispatcher(storage)
dispatcher, _, _ = self._make_dispatcher(module_context)
dispatcher.register("add", handler, module_name="mod_a")
with caplog.at_level(logging.ERROR, logger="owlbot.commands"):
await dispatcher.dispatch(_make_chat_event(body="!add"))
await dispatcher.dispatch(make_chat_event(client_id=42, raw_body="!add"))
row = await storage.fetch_one("SELECT * FROM items WHERE id = ?", (1,))
assert row is not None
@@ -765,17 +750,17 @@ class TestCommandDispatcherDispatch:
assert "raised exception." in caplog.text
async def test_timeout_is_logged(
self, storage: ModuleStorage, caplog: pytest.LogCaptureFixture
self, module_context: ModuleContext, caplog: pytest.LogCaptureFixture
) -> None:
"""A timed-out handler is cancelled and logged."""
async def handler(ctx: CommandContext) -> None:
await asyncio.sleep(10)
dispatcher, _, _ = self._make_dispatcher(storage, handler_timeout=0.05)
dispatcher, _, _ = self._make_dispatcher(module_context, handler_timeout=0.05)
dispatcher.register("slow", handler, module_name="mod_a")
with caplog.at_level(logging.WARNING, logger="owlbot.commands"):
await dispatcher.dispatch(_make_chat_event(body="!slow"))
await dispatcher.dispatch(make_chat_event(client_id=42, raw_body="!slow"))
assert any(
"cancelled after" in r.message and "timeout" in r.message
@@ -783,7 +768,7 @@ class TestCommandDispatcherDispatch:
)
async def test_timeout_does_not_roll_back_committed_writes(
self, storage: ModuleStorage
self, module_context: ModuleContext, storage: ModuleStorage
) -> None:
"""A timed-out handler's already-committed writes persist."""
await storage.execute(
@@ -796,16 +781,16 @@ class TestCommandDispatcherDispatch:
)
await asyncio.sleep(10)
dispatcher, _, _ = self._make_dispatcher(storage, handler_timeout=0.05)
dispatcher, _, _ = self._make_dispatcher(module_context, handler_timeout=0.05)
dispatcher.register("slow", handler, module_name="mod_a")
await dispatcher.dispatch(_make_chat_event(body="!slow"))
await dispatcher.dispatch(make_chat_event(client_id=42, raw_body="!slow"))
row = await storage.fetch_one("SELECT * FROM items WHERE id = ?", (1,))
assert row is not None
assert row["name"] == "apple"
async def test_timeout_rolls_back_explicit_transaction(
self, storage: ModuleStorage
self, module_context: ModuleContext, storage: ModuleStorage
) -> None:
"""A timed-out handler's uncommitted transaction is rolled back."""
await storage.execute(
@@ -819,23 +804,25 @@ class TestCommandDispatcherDispatch:
)
await asyncio.sleep(10)
dispatcher, _, _ = self._make_dispatcher(storage, handler_timeout=0.05)
dispatcher, _, _ = self._make_dispatcher(module_context, handler_timeout=0.05)
dispatcher.register("slow", handler, module_name="mod_a")
await dispatcher.dispatch(_make_chat_event(body="!slow"))
await dispatcher.dispatch(make_chat_event(client_id=42, raw_body="!slow"))
row = await storage.fetch_one("SELECT * FROM items WHERE id = ?", (1,))
assert row is None
async def test_builtin_command_dispatched(self, storage: ModuleStorage) -> None:
async def test_builtin_command_dispatched(
self, module_context: ModuleContext
) -> None:
"""A built-in command receives (event, owncast_client)."""
captured: list[tuple[Any, Any]] = []
async def handler(event: ChatEvent, owncast_client: Any) -> None:
captured.append((event, owncast_client))
dispatcher, _, stub = self._make_dispatcher(storage)
dispatcher, _, stub = self._make_dispatcher(module_context)
dispatcher.register_builtin("test", handler)
event = _make_chat_event(body="!test")
event = make_chat_event(client_id=42, raw_body="!test")
await dispatcher.dispatch(event)
assert len(captured) == 1
@@ -843,48 +830,48 @@ class TestCommandDispatcherDispatch:
assert captured[0][1] is stub
async def test_builtin_command_exception_caught(
self, storage: ModuleStorage, caplog: pytest.LogCaptureFixture
self, module_context: ModuleContext, caplog: pytest.LogCaptureFixture
) -> None:
"""A built-in handler that raises does not propagate the exception."""
async def handler(event: ChatEvent, owncast_client: Any) -> None:
raise RuntimeError("builtin-fail")
dispatcher, _, _ = self._make_dispatcher(storage)
dispatcher, _, _ = self._make_dispatcher(module_context)
dispatcher.register_builtin("test", handler)
with caplog.at_level(logging.ERROR, logger="owlbot.commands"):
await dispatcher.dispatch(_make_chat_event(body="!test"))
await dispatcher.dispatch(make_chat_event(client_id=42, raw_body="!test"))
assert "raised exception." in caplog.text
async def test_builtin_command_timeout(
self, storage: ModuleStorage, caplog: pytest.LogCaptureFixture
self, module_context: ModuleContext, caplog: pytest.LogCaptureFixture
) -> None:
"""A built-in handler that times out is cancelled and logged."""
async def handler(event: ChatEvent, owncast_client: Any) -> None:
await asyncio.sleep(10)
dispatcher, _, _ = self._make_dispatcher(storage, handler_timeout=0.05)
dispatcher, _, _ = self._make_dispatcher(module_context, handler_timeout=0.05)
dispatcher.register_builtin("test", handler)
with caplog.at_level(logging.WARNING, logger="owlbot.commands"):
await dispatcher.dispatch(_make_chat_event(body="!test"))
await dispatcher.dispatch(make_chat_event(client_id=42, raw_body="!test"))
assert any(
"cancelled after" in r.message and "timeout" in r.message
for r in caplog.records
)
async def test_command_event_fields(self, storage: ModuleStorage) -> None:
async def test_command_event_fields(self, module_context: ModuleContext) -> None:
"""Dispatched CommandContext carries correct CommandEvent fields."""
captured: list[CommandContext] = []
async def handler(ctx: CommandContext) -> None:
captured.append(ctx)
dispatcher, _, _ = self._make_dispatcher(storage)
dispatcher, _, _ = self._make_dispatcher(module_context)
dispatcher.register("greet", handler, module_name="mod_a")
event = _make_chat_event(body="!greet world")
event = make_chat_event(client_id=42, raw_body="!greet world")
await dispatcher.dispatch(event)
assert captured[0].command_event.command == "greet"
@@ -899,43 +886,53 @@ class TestModuleCommands:
def _make_dispatcher_and_mod_cmds(
self,
module_context: ModuleContext,
*module_names: str,
) -> tuple[CommandDispatcher, dict[str, ModuleCommands]]:
"""Build a dispatcher and ModuleCommands wrappers for given modules."""
stub = _StubOwncastClient()
"""Build a dispatcher and ModuleCommands wrappers for given modules.
These tests exercise registration and ownership only; commands are
never dispatched, so a single ``module_context`` is reused for every
lookup.
"""
stub = RecordingOwncastClient()
dispatcher = CommandDispatcher(
get_module_context=lambda name: make_module_context(None, name),
owncast_client=stub, # type: ignore[arg-type]
get_module_context=lambda _name: module_context,
owncast_client=stub,
handler_timeout=5.0,
loaded_modules=set(),
)
mod_cmds = {name: ModuleCommands(dispatcher, name) for name in module_names}
return dispatcher, mod_cmds
def test_register_auto_supplies_module_name(self) -> None:
def test_register_auto_supplies_module_name(
self, module_context: ModuleContext
) -> None:
"""ModuleCommands.register auto-supplies module_name."""
async def handler(ctx: CommandContext) -> None:
pass
dispatcher, mod_cmds = self._make_dispatcher_and_mod_cmds("mod_a")
dispatcher, mod_cmds = self._make_dispatcher_and_mod_cmds(
module_context, "mod_a"
)
mod_cmds["mod_a"].register("ping", handler)
info = dispatcher.get("ping")
assert info is not None
assert info.module_name == "mod_a"
def test_prefix_property(self) -> None:
def test_prefix_property(self, module_context: ModuleContext) -> None:
"""ModuleCommands.prefix delegates to the dispatcher's prefix."""
_, mod_cmds = self._make_dispatcher_and_mod_cmds("mod_a")
_, mod_cmds = self._make_dispatcher_and_mod_cmds(module_context, "mod_a")
assert mod_cmds["mod_a"].prefix == "!"
def test_module_commands_property(self) -> None:
def test_module_commands_property(self, module_context: ModuleContext) -> None:
"""module_commands returns dict with both registered commands."""
async def handler(ctx: CommandContext) -> None:
pass
_, mod_cmds = self._make_dispatcher_and_mod_cmds("mod_a")
_, mod_cmds = self._make_dispatcher_and_mod_cmds(module_context, "mod_a")
mod_cmds["mod_a"].register("ping", handler)
mod_cmds["mod_a"].register("pong", handler)
result = mod_cmds["mod_a"].module_commands
@@ -943,9 +940,11 @@ class TestModuleCommands:
assert "pong" in result
assert len(result) == 2
def test_module_commands_property_empty(self) -> None:
def test_module_commands_property_empty(
self, module_context: ModuleContext
) -> None:
"""module_commands returns empty dict when nothing registered."""
_, mod_cmds = self._make_dispatcher_and_mod_cmds("mod_a")
_, mod_cmds = self._make_dispatcher_and_mod_cmds(module_context, "mod_a")
assert mod_cmds["mod_a"].module_commands == {}
@pytest.mark.parametrize(
@@ -960,6 +959,7 @@ class TestModuleCommands:
)
def test_unregister(
self,
module_context: ModuleContext,
owner: str,
other_setup: str | None,
call_module: str,
@@ -975,7 +975,7 @@ class TestModuleCommands:
modules = [owner]
if other_setup:
modules.append(other_setup)
_, mod_cmds = self._make_dispatcher_and_mod_cmds(*modules)
_, mod_cmds = self._make_dispatcher_and_mod_cmds(module_context, *modules)
mod_cmds[owner].register("ping", handler)
if other_setup:
@@ -983,40 +983,44 @@ class TestModuleCommands:
assert mod_cmds[call_module].unregister(trigger) is expected
def test_get_own_command(self) -> None:
def test_get_own_command(self, module_context: ModuleContext) -> None:
"""get() returns CommandInfo for own commands."""
async def handler(ctx: CommandContext) -> None:
pass
_, mod_cmds = self._make_dispatcher_and_mod_cmds("mod_a")
_, mod_cmds = self._make_dispatcher_and_mod_cmds(module_context, "mod_a")
mod_cmds["mod_a"].register("ping", handler)
info = mod_cmds["mod_a"].get("ping")
assert info is not None
assert info.name == "ping"
def test_get_other_modules_command(self) -> None:
def test_get_other_modules_command(self, module_context: ModuleContext) -> None:
"""get() returns None for another module's command."""
async def handler(ctx: CommandContext) -> None:
pass
_, mod_cmds = self._make_dispatcher_and_mod_cmds("mod_a", "mod_b")
_, mod_cmds = self._make_dispatcher_and_mod_cmds(
module_context, "mod_a", "mod_b"
)
mod_cmds["mod_b"].register("quote", handler)
assert mod_cmds["mod_a"].get("quote") is None
def test_get_unknown(self) -> None:
def test_get_unknown(self, module_context: ModuleContext) -> None:
"""get() returns None for unknown commands."""
_, mod_cmds = self._make_dispatcher_and_mod_cmds("mod_a")
_, mod_cmds = self._make_dispatcher_and_mod_cmds(module_context, "mod_a")
assert mod_cmds["mod_a"].get("nope") is None
def test_exists_sees_all_modules(self) -> None:
def test_exists_sees_all_modules(self, module_context: ModuleContext) -> None:
"""exists() checks across all modules, not scoped to own."""
async def handler(ctx: CommandContext) -> None:
pass
_, mod_cmds = self._make_dispatcher_and_mod_cmds("mod_a", "mod_b")
_, mod_cmds = self._make_dispatcher_and_mod_cmds(
module_context, "mod_a", "mod_b"
)
mod_cmds["mod_b"].register("quote", handler)
assert mod_cmds["mod_a"].exists("quote") is True
@@ -1026,11 +1030,10 @@ class TestCommandContext:
def _make_command_context(
self,
storage: ModuleStorage,
) -> tuple[CommandContext, ModuleContext, CommandEvent, EventContext[ChatEvent]]:
"""Build a CommandContext with all stub parts."""
module_ctx = make_module_context(storage, "mod_a")
event = _make_chat_event(body="!greet world")
module_ctx: ModuleContext,
) -> tuple[CommandContext, CommandEvent, EventContext[ChatEvent]]:
"""Build a CommandContext wrapping the given ModuleContext."""
event = make_chat_event(client_id=42, raw_body="!greet world")
cmd_event = CommandEvent(
command="greet",
args="world",
@@ -1046,7 +1049,7 @@ class TestCommandContext:
event_context=event_ctx,
module=module_ctx,
)
return cmd_ctx, module_ctx, cmd_event, event_ctx
return cmd_ctx, cmd_event, event_ctx
@pytest.mark.parametrize(
("prop", "use_is"),
@@ -1061,48 +1064,48 @@ class TestCommandContext:
],
)
def test_property_proxying(
self, storage: ModuleStorage, prop: str, *, use_is: bool
self, module_context: ModuleContext, prop: str, *, use_is: bool
) -> None:
"""CommandContext properties proxy to the underlying ModuleContext."""
cmd_ctx, module_ctx, _, _ = self._make_command_context(storage)
cmd_ctx, _, _ = self._make_command_context(module_context)
ctx_val = getattr(cmd_ctx, prop)
mod_val = getattr(module_ctx, prop)
mod_val = getattr(module_context, prop)
if use_is:
assert ctx_val is mod_val
else:
assert ctx_val == mod_val
def test_command_property(self, storage: ModuleStorage) -> None:
def test_command_property(self, module_context: ModuleContext) -> None:
"""ctx.command matches the CommandEvent's command."""
cmd_ctx, _, cmd_event, _ = self._make_command_context(storage)
cmd_ctx, cmd_event, _ = self._make_command_context(module_context)
assert cmd_ctx.command == cmd_event.command
def test_args_property(self, storage: ModuleStorage) -> None:
def test_args_property(self, module_context: ModuleContext) -> None:
"""ctx.args matches the CommandEvent's args."""
cmd_ctx, _, cmd_event, _ = self._make_command_context(storage)
cmd_ctx, cmd_event, _ = self._make_command_context(module_context)
assert cmd_ctx.args == cmd_event.args
def test_args_list_property(self, storage: ModuleStorage) -> None:
def test_args_list_property(self, module_context: ModuleContext) -> None:
"""ctx.args_list matches the CommandEvent's args_list."""
cmd_ctx, _, cmd_event, _ = self._make_command_context(storage)
cmd_ctx, cmd_event, _ = self._make_command_context(module_context)
assert cmd_ctx.args_list == cmd_event.args_list
def test_prefix_property(self, storage: ModuleStorage) -> None:
def test_prefix_property(self, module_context: ModuleContext) -> None:
"""ctx.prefix matches the CommandEvent's prefix."""
cmd_ctx, _, cmd_event, _ = self._make_command_context(storage)
cmd_ctx, cmd_event, _ = self._make_command_context(module_context)
assert cmd_ctx.prefix == cmd_event.prefix
def test_chat_event_property(self, storage: ModuleStorage) -> None:
def test_chat_event_property(self, module_context: ModuleContext) -> None:
"""ctx.chat_event is the CommandEvent's chat_event."""
cmd_ctx, _, cmd_event, _ = self._make_command_context(storage)
cmd_ctx, cmd_event, _ = self._make_command_context(module_context)
assert cmd_ctx.chat_event is cmd_event.chat_event
def test_user_property(self, storage: ModuleStorage) -> None:
def test_user_property(self, module_context: ModuleContext) -> None:
"""ctx.user is the chat_event's user."""
cmd_ctx, _, cmd_event, _ = self._make_command_context(storage)
cmd_ctx, cmd_event, _ = self._make_command_context(module_context)
assert cmd_ctx.user is cmd_event.chat_event.user
def test_event_context_attribute(self, storage: ModuleStorage) -> None:
def test_event_context_attribute(self, module_context: ModuleContext) -> None:
"""ctx.event_context is the EventContext passed at construction."""
cmd_ctx, _, _, event_ctx = self._make_command_context(storage)
cmd_ctx, _, event_ctx = self._make_command_context(module_context)
assert cmd_ctx.event_context is event_ctx
-991
View File
@@ -1,991 +0,0 @@
# Copyright 2026 Logan Fick
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for the custom_commands module: types, repository, and manager."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
import pytest
from owlbot.api.context import ModuleContext
from owlbot.api.storage import ModuleStorage, StorageError
from owlbot.builtin_modules.custom_commands.manager import (
CommandManager,
get_manager,
)
from owlbot.builtin_modules.custom_commands.repository import CommandRepository
from owlbot.builtin_modules.custom_commands.types import (
NAME_RE,
AliasAlreadyExistsError,
AliasIsCanonicalNameError,
CannotDeleteByAliasError,
Command,
CommandAlreadyExistsError,
CommandError,
CommandNotFoundError,
InvalidNameError,
NotCustomCommandError,
)
class TestCommandFromRow:
"""Command.from_row() database row conversion."""
def test_builds_from_row(self) -> None:
"""from_row constructs a Command with correct field values."""
row = {
"name": "greet",
"response": "Hello $(user)!",
"use_count": 5,
"created_at": "2026-01-01T00:00:00+00:00",
"updated_at": "2026-01-02T00:00:00+00:00",
"requires_moderator": 0,
"cooldown": 10,
}
cmd = Command.from_row(row) # type: ignore[arg-type]
assert cmd.name == "greet"
assert cmd.response == "Hello $(user)!"
assert cmd.use_count == 5
assert cmd.requires_moderator is False
assert cmd.cooldown == 10
assert cmd.aliases == frozenset()
def test_builds_with_aliases(self) -> None:
"""from_row populates aliases and coerces requires_moderator to bool."""
row = {
"name": "greet",
"response": "Hello!",
"use_count": 0,
"created_at": "2026-01-01T00:00:00+00:00",
"updated_at": "2026-01-01T00:00:00+00:00",
"requires_moderator": 1,
"cooldown": 0,
}
aliases = frozenset({"hi", "hey"})
cmd = Command.from_row(row, aliases) # type: ignore[arg-type]
assert cmd.requires_moderator is True
assert cmd.aliases == {"hi", "hey"}
def test_frozen(self) -> None:
"""Command instances are immutable (frozen dataclass)."""
row = {
"name": "x",
"response": "y",
"use_count": 0,
"created_at": "",
"updated_at": "",
"requires_moderator": 0,
"cooldown": 0,
}
cmd = Command.from_row(row) # type: ignore[arg-type]
with pytest.raises(AttributeError):
cmd.name = "z" # type: ignore[misc]
class TestCommandErrors:
"""Domain error hierarchy and stored context."""
def test_all_inherit_from_command_error(self) -> None:
"""All domain errors are subclasses of CommandError."""
assert issubclass(CommandNotFoundError, CommandError)
assert issubclass(InvalidNameError, CommandError)
assert issubclass(CommandAlreadyExistsError, CommandError)
assert issubclass(NotCustomCommandError, CommandError)
assert issubclass(AliasAlreadyExistsError, CommandError)
assert issubclass(AliasIsCanonicalNameError, CommandError)
assert issubclass(CannotDeleteByAliasError, CommandError)
def test_not_found_stores_identifier(self) -> None:
"""CommandNotFoundError stores the identifier and includes it in str."""
err = CommandNotFoundError("greet")
assert err.identifier == "greet"
assert "greet" in str(err)
def test_invalid_name_stores_name(self) -> None:
"""InvalidNameError stores the invalid name."""
err = InvalidNameError("BAD NAME!")
assert err.name == "BAD NAME!"
def test_already_exists_stores_name(self) -> None:
"""CommandAlreadyExistsError stores the conflicting name."""
err = CommandAlreadyExistsError("greet")
assert err.name == "greet"
def test_not_custom_stores_name(self) -> None:
"""NotCustomCommandError stores the built-in command name."""
err = NotCustomCommandError("about")
assert err.name == "about"
def test_alias_already_exists_stores_context(self) -> None:
"""AliasAlreadyExistsError stores alias and owner."""
err = AliasAlreadyExistsError("hi", "greet")
assert err.alias == "hi"
assert err.owner == "greet"
def test_alias_is_canonical_stores_alias(self) -> None:
"""AliasIsCanonicalNameError stores the alias."""
err = AliasIsCanonicalNameError("greet")
assert err.alias == "greet"
def test_cannot_delete_alias_stores_context(self) -> None:
"""CannotDeleteByAliasError stores alias and canonical name."""
err = CannotDeleteByAliasError("hi", "greet")
assert err.alias == "hi"
assert err.canonical == "greet"
class TestNamePattern:
"""NAME_RE validates identifiers."""
@pytest.mark.parametrize(
"name",
[
pytest.param("greet", id="alpha"),
pytest.param("hello_world", id="underscore"),
pytest.param("cmd1", id="trailing_digit"),
pytest.param("a", id="single_char"),
pytest.param("test_123", id="mixed"),
],
)
def test_valid_names(self, name: str) -> None:
"""NAME_RE matches valid lowercase alphanumeric identifiers."""
assert NAME_RE.match(name) is not None
@pytest.mark.parametrize(
"name",
[
pytest.param("", id="empty"),
pytest.param("Hello", id="uppercase"),
pytest.param("has space", id="space"),
pytest.param("special!", id="special_char"),
pytest.param("with-dash", id="dash"),
pytest.param("UPPER", id="all_upper"),
],
)
def test_invalid_names(self, name: str) -> None:
"""NAME_RE rejects names with invalid characters or patterns."""
assert NAME_RE.match(name) is None
if TYPE_CHECKING:
from collections.abc import AsyncIterator
# ---- Repository fixtures ----
@pytest.fixture
async def cmd_storage() -> AsyncIterator[ModuleStorage]:
"""Yield an open in-memory ModuleStorage."""
async with ModuleStorage(None, "custom_commands") as storage:
yield storage
@pytest.fixture
async def repo(cmd_storage: ModuleStorage) -> CommandRepository:
"""CommandRepository backed by cmd_storage, with schema initialized."""
r = CommandRepository(cmd_storage)
await r.setup()
return r
# ---- Repository command tests ----
class TestRepositoryCreate:
"""CommandRepository.create() inserts new commands."""
async def test_create_returns_command(self, repo: CommandRepository) -> None:
"""create() returns a Command snapshot with correct fields."""
cmd = await repo.create("greet", "Hello!", 5)
assert cmd.name == "greet"
assert cmd.response == "Hello!"
assert cmd.use_count == 0
assert cmd.requires_moderator is False
assert cmd.cooldown == 5
assert cmd.aliases == frozenset()
assert cmd.created_at is not None
assert cmd.updated_at is not None
async def test_create_duplicate_raises(self, repo: CommandRepository) -> None:
"""create() raises on duplicate command name."""
await repo.create("greet", "Hello!", 5)
with pytest.raises(StorageError, match="UNIQUE constraint"):
await repo.create("greet", "Hi!", 5)
class TestRepositoryGet:
"""CommandRepository.get() fetches by name or alias."""
async def test_get_by_name(self, repo: CommandRepository) -> None:
"""get() retrieves a command by its canonical name."""
await repo.create("greet", "Hello!", 5)
cmd = await repo.get("greet")
assert cmd.name == "greet"
assert cmd.response == "Hello!"
async def test_get_not_found(self, repo: CommandRepository) -> None:
"""get() raises CommandNotFoundError for missing commands."""
with pytest.raises(CommandNotFoundError) as exc_info:
await repo.get("nonexistent")
assert exc_info.value.identifier == "nonexistent"
class TestRepositoryDelete:
"""CommandRepository.delete() removes commands."""
async def test_delete_returns_command(self, repo: CommandRepository) -> None:
"""delete() returns the deleted command snapshot."""
await repo.create("greet", "Hello!", 5)
deleted = await repo.delete("greet")
assert deleted.name == "greet"
async def test_delete_removes_from_db(self, repo: CommandRepository) -> None:
"""delete() makes the command unreachable via get()."""
await repo.create("greet", "Hello!", 5)
await repo.delete("greet")
with pytest.raises(CommandNotFoundError):
await repo.get("greet")
async def test_delete_not_found(self, repo: CommandRepository) -> None:
"""delete() raises CommandNotFoundError for missing commands."""
with pytest.raises(CommandNotFoundError):
await repo.delete("nonexistent")
class TestRepositoryUpdateResponse:
"""CommandRepository.update_response() changes a command's response."""
async def test_update_response(self, repo: CommandRepository) -> None:
"""update_response() returns updated Command with new response."""
await repo.create("greet", "Hello!", 5)
updated = await repo.update_response("greet", "Hi there!")
assert updated.response == "Hi there!"
assert updated.name == "greet"
async def test_update_response_changes_updated_at(
self, repo: CommandRepository
) -> None:
"""update_response() bumps updated_at timestamp."""
created = await repo.create("greet", "Hello!", 5)
updated = await repo.update_response("greet", "Hi!")
assert updated.updated_at != created.updated_at
async def test_update_response_not_found(self, repo: CommandRepository) -> None:
"""update_response() raises CommandNotFoundError for missing commands."""
with pytest.raises(CommandNotFoundError):
await repo.update_response("nonexistent", "Hi!")
class TestRepositoryUpdateModeratorFlag:
"""CommandRepository.update_moderator_flag() changes the mod-only flag."""
async def test_enable(self, repo: CommandRepository) -> None:
"""update_moderator_flag() sets requires_moderator to True."""
await repo.create("greet", "Hello!", 5)
updated = await repo.update_moderator_flag("greet", enabled=True)
assert updated.requires_moderator is True
assert updated.cooldown == 5
async def test_disable(self, repo: CommandRepository) -> None:
"""update_moderator_flag() sets requires_moderator to False."""
await repo.create("greet", "Hello!", 5)
await repo.update_moderator_flag("greet", enabled=True)
updated = await repo.update_moderator_flag("greet", enabled=False)
assert updated.requires_moderator is False
async def test_not_found(self, repo: CommandRepository) -> None:
"""update_moderator_flag() raises CommandNotFoundError for missing commands."""
with pytest.raises(CommandNotFoundError):
await repo.update_moderator_flag("nonexistent", enabled=True)
class TestRepositoryUpdateCooldown:
"""CommandRepository.update_cooldown() changes the cooldown duration."""
async def test_update(self, repo: CommandRepository) -> None:
"""update_cooldown() sets the cooldown value."""
await repo.create("greet", "Hello!", 5)
updated = await repo.update_cooldown("greet", seconds=30)
assert updated.cooldown == 30
assert updated.requires_moderator is False
async def test_not_found(self, repo: CommandRepository) -> None:
"""update_cooldown() raises CommandNotFoundError for missing commands."""
with pytest.raises(CommandNotFoundError):
await repo.update_cooldown("nonexistent", seconds=5)
class TestRepositoryResetUseCount:
"""CommandRepository.reset_use_count() zeroes the counter."""
async def test_reset_use_count(self, repo: CommandRepository) -> None:
"""reset_use_count() sets use_count back to 0."""
await repo.create("greet", "Hello!", 5)
await repo.increment_use_count("greet")
await repo.increment_use_count("greet")
reset = await repo.reset_use_count("greet")
assert reset.use_count == 0
async def test_reset_not_found(self, repo: CommandRepository) -> None:
"""reset_use_count() raises CommandNotFoundError for missing commands."""
with pytest.raises(CommandNotFoundError):
await repo.reset_use_count("nonexistent")
class TestRepositoryIncrementUseCount:
"""CommandRepository.increment_use_count() bumps the counter."""
async def test_increment(self, repo: CommandRepository) -> None:
"""increment_use_count() increases use_count by 1 each call."""
await repo.create("greet", "Hello!", 5)
cmd = await repo.increment_use_count("greet")
assert cmd.use_count == 1
cmd = await repo.increment_use_count("greet")
assert cmd.use_count == 2
async def test_increment_not_found(self, repo: CommandRepository) -> None:
"""increment_use_count() raises CommandNotFoundError for missing commands."""
with pytest.raises(CommandNotFoundError):
await repo.increment_use_count("nonexistent")
class TestRepositoryListAll:
"""CommandRepository.list_all() returns all commands."""
async def test_list_all(self, repo: CommandRepository) -> None:
"""list_all() returns commands sorted by name."""
await repo.create("bravo", "B", 5)
await repo.create("alpha", "A", 5)
result = await repo.list_all()
assert len(result) == 2
assert result[0].name == "alpha"
assert result[1].name == "bravo"
async def test_list_all_empty(self, repo: CommandRepository) -> None:
"""list_all() returns empty list when no commands exist."""
assert await repo.list_all() == []
# ---- Repository alias tests ----
class TestRepositoryGetByAlias:
"""CommandRepository.get() resolves aliases."""
async def test_get_by_alias(self, repo: CommandRepository) -> None:
"""get() resolves an alias to its canonical command."""
await repo.create("greet", "Hello!", 5)
await repo.add_alias("greet", "hi")
cmd = await repo.get("hi")
assert cmd.name == "greet"
assert "hi" in cmd.aliases
class TestRepositoryAddAlias:
"""CommandRepository.add_alias() adds aliases."""
async def test_add_alias(self, repo: CommandRepository) -> None:
"""add_alias() adds an alias and returns refreshed command."""
await repo.create("greet", "Hello!", 5)
cmd = await repo.add_alias("greet", "hi")
assert "hi" in cmd.aliases
async def test_add_multiple_aliases(self, repo: CommandRepository) -> None:
"""add_alias() accumulates multiple aliases."""
await repo.create("greet", "Hello!", 5)
await repo.add_alias("greet", "hi")
cmd = await repo.add_alias("greet", "hey")
assert cmd.aliases == frozenset({"hi", "hey"})
async def test_add_alias_duplicate(self, repo: CommandRepository) -> None:
"""add_alias() raises AliasAlreadyExistsError for duplicate aliases."""
await repo.create("greet", "Hello!", 5)
await repo.add_alias("greet", "hi")
with pytest.raises(AliasAlreadyExistsError) as exc_info:
await repo.add_alias("greet", "hi")
assert exc_info.value.alias == "hi"
assert exc_info.value.owner == "greet"
class TestRepositoryRemoveAlias:
"""CommandRepository.remove_alias() removes aliases."""
async def test_remove_alias(self, repo: CommandRepository) -> None:
"""remove_alias() removes the alias and returns refreshed command."""
await repo.create("greet", "Hello!", 5)
await repo.add_alias("greet", "hi")
alias, cmd = await repo.remove_alias("hi")
assert alias == "hi"
assert "hi" not in cmd.aliases
async def test_remove_alias_not_found(self, repo: CommandRepository) -> None:
"""remove_alias() raises CommandNotFoundError for missing aliases."""
with pytest.raises(CommandNotFoundError):
await repo.remove_alias("nonexistent")
class TestRepositoryDeleteCascade:
"""Deleting a command cascades to its aliases."""
async def test_delete_cascades_aliases(self, repo: CommandRepository) -> None:
"""delete() removes associated aliases via CASCADE."""
await repo.create("greet", "Hello!", 5)
await repo.add_alias("greet", "hi")
await repo.delete("greet")
with pytest.raises(CommandNotFoundError):
await repo.get("hi")
class TestRepositoryListAllWithAliases:
"""CommandRepository.list_all() includes aliases."""
async def test_list_all_includes_aliases(self, repo: CommandRepository) -> None:
"""list_all() populates alias sets for each command."""
await repo.create("greet", "Hello!", 5)
await repo.add_alias("greet", "hi")
await repo.add_alias("greet", "hey")
result = await repo.list_all()
assert len(result) == 1
assert result[0].aliases == frozenset({"hi", "hey"})
# ---- Repository counter tests ----
class TestRepositoryGetCounter:
"""CommandRepository.get_counter() reads counter values."""
async def test_get_counter_missing(self, repo: CommandRepository) -> None:
"""get_counter() returns 0 for nonexistent counters."""
assert await repo.get_counter("deaths") == 0
async def test_get_counter_existing(self, repo: CommandRepository) -> None:
"""get_counter() returns the stored value."""
await repo.set_counter("deaths", 10)
assert await repo.get_counter("deaths") == 10
class TestRepositorySetCounter:
"""CommandRepository.set_counter() sets absolute values."""
async def test_set_counter_new(self, repo: CommandRepository) -> None:
"""set_counter() inserts a new counter with the given value."""
result = await repo.set_counter("deaths", 42)
assert result == 42
assert await repo.get_counter("deaths") == 42
async def test_set_counter_overwrite(self, repo: CommandRepository) -> None:
"""set_counter() overwrites an existing counter."""
await repo.set_counter("deaths", 10)
result = await repo.set_counter("deaths", 99)
assert result == 99
class TestRepositoryUpdateCounter:
"""CommandRepository.update_counter() applies relative deltas."""
async def test_update_counter_new(self, repo: CommandRepository) -> None:
"""update_counter() creates a counter if it does not exist."""
result = await repo.update_counter("deaths", 5)
assert result == 5
async def test_update_counter_increment(self, repo: CommandRepository) -> None:
"""update_counter() adds a positive delta to existing value."""
await repo.set_counter("deaths", 10)
result = await repo.update_counter("deaths", 3)
assert result == 13
async def test_update_counter_decrement(self, repo: CommandRepository) -> None:
"""update_counter() subtracts a negative delta from existing value."""
await repo.set_counter("deaths", 10)
result = await repo.update_counter("deaths", -3)
assert result == 7
# ---- Manager stubs and fixtures ----
class _StubModuleCommands:
"""Minimal ModuleCommands stand-in that tracks registrations."""
def __init__(self, prefix: str = "!") -> None:
self.prefix = prefix
self._registered: dict[str, dict[str, Any]] = {}
self._all_triggers: set[str] = set()
self._external_triggers: set[str] = set()
def seed_external(self, name: str) -> None:
"""Pre-register a trigger as belonging to another module."""
self._external_triggers.add(name)
def register(
self,
name: str,
handler: Any,
*,
aliases: list[str] | tuple[str, ...] | None = None,
requires_authenticated: bool = False,
requires_moderator: bool = False,
cooldown: int = 0,
) -> None:
all_new = {name} | set(aliases or [])
for trigger in all_new:
if trigger in self._all_triggers or trigger in self._external_triggers:
raise ValueError(
f"Command trigger '{trigger}' conflicts with existing command"
)
self._registered[name] = {
"handler": handler,
"aliases": set(aliases or []),
"requires_authenticated": requires_authenticated,
"requires_moderator": requires_moderator,
"cooldown": cooldown,
}
self._all_triggers.update(all_new)
def unregister(self, name: str) -> bool:
if name not in self._registered:
return False
info = self._registered.pop(name)
self._all_triggers.discard(name)
for a in info["aliases"]:
self._all_triggers.discard(a)
return True
def exists(self, trigger: str) -> bool:
return trigger in self._all_triggers or trigger in self._external_triggers
class _StubConfig:
"""Minimal ModuleConfig stand-in."""
def __init__(self, values: dict[str, Any] | None = None) -> None:
self._values: dict[str, Any] = values or {}
def get(self, key: str, default: Any = None) -> Any:
return self._values.get(key, default)
def register_defaults(self, defaults: dict[str, Any]) -> None:
for key, value in defaults.items():
self._values.setdefault(key, value)
@pytest.fixture
def stub_commands() -> _StubModuleCommands:
"""Return a fresh stub command registry."""
return _StubModuleCommands()
@pytest.fixture
def cmd_ctx(
cmd_storage: ModuleStorage, stub_commands: _StubModuleCommands
) -> ModuleContext:
"""ModuleContext with real storage and stub commands/config."""
return ModuleContext(
module_name="custom_commands",
config=_StubConfig({"default_cooldown": 5, "max_nesting_depth": 4}), # type: ignore[arg-type]
owncast_client=None, # type: ignore[arg-type]
storage=cmd_storage,
commands=stub_commands, # type: ignore[arg-type]
events=None, # type: ignore[arg-type]
routes=None, # type: ignore[arg-type]
http=None, # type: ignore[arg-type]
templates=None, # type: ignore[arg-type]
admin_client=None,
)
@pytest.fixture
def manager(cmd_ctx: ModuleContext, repo: CommandRepository) -> CommandManager:
"""CommandManager backed by real repo and stub commands."""
return CommandManager(cmd_ctx, repo)
# ---- Manager tests ----
class TestManagerLoadAll:
"""CommandManager.load_all() loads commands into the registry."""
async def test_load_all(
self,
manager: CommandManager,
repo: CommandRepository,
stub_commands: _StubModuleCommands,
) -> None:
"""load_all registers all commands from the database."""
await repo.create("greet", "Hello!", 5)
await repo.create("bye", "Goodbye!", 0)
await manager.load_all()
assert stub_commands.exists("greet")
assert stub_commands.exists("bye")
async def test_load_all_skips_conflicts(
self,
manager: CommandManager,
repo: CommandRepository,
stub_commands: _StubModuleCommands,
) -> None:
"""load_all skips commands that conflict with existing triggers."""
stub_commands.seed_external("greet")
await repo.create("greet", "Hello!", 5)
await repo.create("bye", "Goodbye!", 0)
await manager.load_all()
assert not stub_commands._registered.get("greet")
assert stub_commands.exists("bye")
async def test_load_all_with_aliases(
self,
manager: CommandManager,
repo: CommandRepository,
stub_commands: _StubModuleCommands,
) -> None:
"""load_all registers commands together with their aliases."""
await repo.create("greet", "Hello!", 5)
await repo.add_alias("greet", "hi")
await manager.load_all()
assert stub_commands.exists("greet")
assert stub_commands.exists("hi")
async def test_load_all_empty(
self, manager: CommandManager, stub_commands: _StubModuleCommands
) -> None:
"""load_all does nothing when the database is empty."""
await manager.load_all()
assert len(stub_commands._registered) == 0
class TestManagerCreateCommand:
"""CommandManager.create_command() creates and registers commands."""
async def test_create_command(
self, manager: CommandManager, stub_commands: _StubModuleCommands
) -> None:
"""create_command creates and registers a command."""
cmd = await manager.create_command("greet", "Hello!")
assert cmd.name == "greet"
assert cmd.response == "Hello!"
assert cmd.cooldown == 5 # default_cooldown from config
assert stub_commands.exists("greet")
async def test_create_rejects_invalid_name(self, manager: CommandManager) -> None:
"""create_command raises InvalidNameError for bad names."""
with pytest.raises(InvalidNameError):
await manager.create_command("BAD!", "Hello!")
async def test_create_rejects_conflict(
self,
manager: CommandManager,
stub_commands: _StubModuleCommands,
) -> None:
"""create_command raises CommandAlreadyExistsError on conflict."""
stub_commands.seed_external("about")
with pytest.raises(CommandAlreadyExistsError) as exc_info:
await manager.create_command("about", "Info")
assert exc_info.value.name == "about"
async def test_create_rollback_on_db_failure(
self,
cmd_ctx: ModuleContext,
stub_commands: _StubModuleCommands,
) -> None:
"""If DB insert fails, the command is not registered."""
# Create a manager with a repo whose storage is closed.
closed_storage = ModuleStorage(None, "closed")
bad_repo = CommandRepository(closed_storage)
mgr = CommandManager(cmd_ctx, bad_repo)
with pytest.raises((StorageError, AttributeError)):
await mgr.create_command("greet", "Hello!")
assert not stub_commands.exists("greet")
class TestManagerEditCommand:
"""CommandManager.edit_command() updates a command's response."""
async def test_edit_command(self, manager: CommandManager) -> None:
"""edit_command updates the response text."""
await manager.create_command("greet", "Hello!")
updated = await manager.edit_command("greet", "Hi there!")
assert updated.response == "Hi there!"
async def test_edit_resolves_alias(self, manager: CommandManager) -> None:
"""edit_command resolves an alias to the canonical command."""
await manager.create_command("greet", "Hello!")
await manager.add_alias("greet", "hi")
updated = await manager.edit_command("hi", "Hi there!")
assert updated.name == "greet"
assert updated.response == "Hi there!"
async def test_edit_not_found(self, manager: CommandManager) -> None:
"""edit_command raises CommandNotFoundError for missing commands."""
with pytest.raises(CommandNotFoundError):
await manager.edit_command("nonexistent", "Hi!")
async def test_edit_not_custom(
self,
manager: CommandManager,
stub_commands: _StubModuleCommands,
) -> None:
"""edit_command raises NotCustomCommandError for built-in commands."""
stub_commands.seed_external("about")
with pytest.raises(NotCustomCommandError):
await manager.edit_command("about", "Hacked!")
class TestManagerDeleteCommand:
"""CommandManager.delete_command() deletes and unregisters commands."""
async def test_delete_command(
self, manager: CommandManager, stub_commands: _StubModuleCommands
) -> None:
"""delete_command removes the command and unregisters its trigger."""
await manager.create_command("greet", "Hello!")
deleted = await manager.delete_command("greet")
assert deleted.name == "greet"
assert not stub_commands.exists("greet")
async def test_delete_rejects_alias(self, manager: CommandManager) -> None:
"""delete_command raises CannotDeleteByAliasError for aliases."""
await manager.create_command("greet", "Hello!")
await manager.add_alias("greet", "hi")
with pytest.raises(CannotDeleteByAliasError) as exc_info:
await manager.delete_command("hi")
assert exc_info.value.alias == "hi"
assert exc_info.value.canonical == "greet"
async def test_delete_not_found(self, manager: CommandManager) -> None:
"""delete_command raises CommandNotFoundError for missing commands."""
with pytest.raises(CommandNotFoundError):
await manager.delete_command("nonexistent")
class TestManagerSetModOnly:
"""CommandManager.set_mod_only() updates moderator access."""
async def test_set_mod_only_on(
self, manager: CommandManager, stub_commands: _StubModuleCommands
) -> None:
"""set_mod_only enables moderator-only access."""
await manager.create_command("greet", "Hello!")
updated = await manager.set_mod_only("greet", enabled=True)
assert updated.requires_moderator is True
assert stub_commands._registered["greet"]["requires_moderator"] is True
async def test_set_mod_only_off(self, manager: CommandManager) -> None:
"""set_mod_only disables moderator-only access."""
await manager.create_command("greet", "Hello!")
await manager.set_mod_only("greet", enabled=True)
updated = await manager.set_mod_only("greet", enabled=False)
assert updated.requires_moderator is False
class TestManagerSetCooldown:
"""CommandManager.set_cooldown() updates cooldown."""
async def test_set_cooldown(
self, manager: CommandManager, stub_commands: _StubModuleCommands
) -> None:
"""set_cooldown updates the cooldown and re-registers the command."""
await manager.create_command("greet", "Hello!")
updated = await manager.set_cooldown("greet", 30)
assert updated.cooldown == 30
assert stub_commands._registered["greet"]["cooldown"] == 30
async def test_set_cooldown_zero(self, manager: CommandManager) -> None:
"""set_cooldown accepts zero to disable cooldown."""
await manager.create_command("greet", "Hello!")
updated = await manager.set_cooldown("greet", 0)
assert updated.cooldown == 0
class TestManagerResetUseCount:
"""CommandManager.reset_use_count() zeroes the counter."""
async def test_reset_use_count(self, manager: CommandManager) -> None:
"""reset_use_count sets the counter back to zero."""
await manager.create_command("greet", "$(count)")
await manager.execute_command("greet", [], "tester")
reset = await manager.reset_use_count("greet")
assert reset.use_count == 0
class TestManagerAddAlias:
"""CommandManager.add_alias() adds and re-registers aliases."""
async def test_add_alias(
self, manager: CommandManager, stub_commands: _StubModuleCommands
) -> None:
"""add_alias registers a new alias for the command."""
await manager.create_command("greet", "Hello!")
cmd = await manager.add_alias("greet", "hi")
assert "hi" in cmd.aliases
assert stub_commands.exists("hi")
async def test_add_alias_rejects_canonical(self, manager: CommandManager) -> None:
"""add_alias raises AliasIsCanonicalNameError for the canonical name."""
await manager.create_command("greet", "Hello!")
with pytest.raises(AliasIsCanonicalNameError):
await manager.add_alias("greet", "greet")
async def test_add_alias_rejects_conflict(
self,
manager: CommandManager,
stub_commands: _StubModuleCommands,
) -> None:
"""add_alias raises CommandAlreadyExistsError on trigger conflict."""
stub_commands.seed_external("about")
await manager.create_command("greet", "Hello!")
with pytest.raises(CommandAlreadyExistsError):
await manager.add_alias("greet", "about")
async def test_add_alias_invalid_name(self, manager: CommandManager) -> None:
"""add_alias raises InvalidNameError for bad alias names."""
await manager.create_command("greet", "Hello!")
with pytest.raises(InvalidNameError):
await manager.add_alias("greet", "BAD!")
class TestManagerRemoveAlias:
"""CommandManager.remove_alias() removes and re-registers aliases."""
async def test_remove_alias(
self, manager: CommandManager, stub_commands: _StubModuleCommands
) -> None:
"""remove_alias removes the alias and keeps the canonical command."""
await manager.create_command("greet", "Hello!")
await manager.add_alias("greet", "hi")
cmd = await manager.remove_alias("hi")
assert "hi" not in cmd.aliases
assert not stub_commands.exists("hi")
assert stub_commands.exists("greet")
async def test_remove_alias_not_found(self, manager: CommandManager) -> None:
"""remove_alias raises CommandNotFoundError for missing aliases."""
with pytest.raises(CommandNotFoundError):
await manager.remove_alias("nonexistent")
class TestManagerExecuteCommand:
"""CommandManager.execute_command() increments count and processes response."""
async def test_execute_plain(self, manager: CommandManager) -> None:
"""execute_command returns the plain response text."""
await manager.create_command("greet", "Hello!")
response = await manager.execute_command("greet", [], "tester")
assert response == "Hello!"
async def test_execute_increments_use_count(self, manager: CommandManager) -> None:
"""execute_command increments use_count on each call."""
await manager.create_command("greet", "Count: $(count)")
r1 = await manager.execute_command("greet", [], "tester")
assert r1 == "Count: 1"
r2 = await manager.execute_command("greet", [], "tester")
assert r2 == "Count: 2"
async def test_execute_user_placeholder(self, manager: CommandManager) -> None:
"""execute_command substitutes the $(user) placeholder."""
await manager.create_command("greet", "Hello $(user)!")
response = await manager.execute_command("greet", [], "Alice")
assert response == "Hello Alice!"
async def test_execute_not_found(self, manager: CommandManager) -> None:
"""execute_command raises CommandNotFoundError for missing commands."""
with pytest.raises(CommandNotFoundError):
await manager.execute_command("nonexistent", [], "tester")
class TestManagerEditCounter:
"""CommandManager.edit_counter() sets/adjusts named counters."""
async def test_edit_counter_absolute(self, manager: CommandManager) -> None:
"""edit_counter sets an absolute counter value."""
result = await manager.edit_counter("deaths", value=42, relative=False)
assert result == 42
async def test_edit_counter_relative_increment(
self, manager: CommandManager
) -> None:
"""edit_counter increments a counter with a positive delta."""
await manager.edit_counter("deaths", value=10, relative=False)
result = await manager.edit_counter("deaths", value=5, relative=True)
assert result == 15
async def test_edit_counter_relative_decrement(
self, manager: CommandManager
) -> None:
"""edit_counter decrements a counter with a negative delta."""
await manager.edit_counter("deaths", value=10, relative=False)
result = await manager.edit_counter("deaths", value=-3, relative=True)
assert result == 7
async def test_edit_counter_invalid_name(self, manager: CommandManager) -> None:
"""edit_counter raises InvalidNameError for bad counter names."""
with pytest.raises(InvalidNameError):
await manager.edit_counter("BAD!", value=5, relative=False)
class TestManagerCounterAccessor:
"""CommandManager as CounterAccessor protocol for placeholders."""
async def test_get_counter(self, manager: CommandManager) -> None:
"""Return 0 for missing counter, correct value for existing."""
assert await manager.get_counter("deaths") == 0
await manager.set_counter("deaths", 10)
assert await manager.get_counter("deaths") == 10
async def test_set_counter(self, manager: CommandManager) -> None:
"""Set a counter to an absolute value."""
result = await manager.set_counter("deaths", 42)
assert result == 42
async def test_adjust_counter(self, manager: CommandManager) -> None:
"""Adjust a counter by a relative delta."""
await manager.set_counter("deaths", 10)
result = await manager.adjust_counter("deaths", 5)
assert result == 15
async def test_execute_with_named_counter(self, manager: CommandManager) -> None:
"""Execute a command that uses a named counter placeholder."""
await manager.create_command("deaths", "Deaths: $(count deaths)")
r1 = await manager.execute_command("deaths", [], "tester")
assert r1 == "Deaths: 1"
r2 = await manager.execute_command("deaths", [], "tester")
assert r2 == "Deaths: 2"
async def test_execute_with_getcount(self, manager: CommandManager) -> None:
"""Execute a command that reads a named counter."""
await manager.create_command("show", "Deaths: $(getcount deaths)")
await manager.set_counter("deaths", 42)
response = await manager.execute_command("show", [], "tester")
assert response == "Deaths: 42"
class TestGetManager:
"""get_manager() helper."""
def test_returns_manager(
self, cmd_ctx: ModuleContext, repo: CommandRepository
) -> None:
"""get_manager returns the manager stored in context state."""
mgr = CommandManager(cmd_ctx, repo)
cmd_ctx.state["manager"] = mgr
assert get_manager(cmd_ctx) is mgr
def test_raises_if_not_initialized(self, cmd_ctx: ModuleContext) -> None:
"""get_manager raises RuntimeError when no manager is stored."""
with pytest.raises(RuntimeError, match="CommandManager is not initialized"):
get_manager(cmd_ctx)
+22 -93
View File
@@ -41,6 +41,17 @@ from owlbot.api.event_types import (
log_event,
parse_event,
)
from owlbot.testing import (
make_chat_event,
make_name_changed_event,
make_stream_started_event,
make_stream_stopped_event,
make_stream_title_updated_event,
make_user,
make_user_joined_event,
make_user_parted_event,
make_visibility_update_event,
)
def _user_dict(
@@ -596,148 +607,66 @@ class TestLogEvent:
[
pytest.param(
EventType.CHAT,
ChatEvent(
user=User(
id="abc123",
display_name="Alice",
display_color=3,
created_at=None,
previous_names=[],
name_changed_at=None,
is_bot=False,
is_authenticated=False,
scopes=frozenset(),
),
client_id=1,
make_chat_event(
user=make_user(display_name="Alice"),
body="Hello",
raw_body="<p>Hello</p>",
message_id="msg-001",
is_visible=True,
timestamp=None,
),
"[CHAT] Alice (msg-001): Hello",
id="chat",
),
pytest.param(
EventType.USER_JOINED,
UserJoinedEvent(
user=User(
id="bob456",
display_name="Bob",
display_color=0,
created_at=None,
previous_names=[],
name_changed_at=None,
is_bot=False,
is_authenticated=False,
scopes=frozenset(),
),
client_id=1,
event_id="evt-001",
timestamp=None,
),
make_user_joined_event(user=make_user(display_name="Bob")),
"[USER_JOINED] Bob joined.",
id="user-joined",
),
pytest.param(
EventType.USER_PARTED,
UserPartedEvent(
user=User(
id="carol789",
display_name="Carol",
display_color=0,
created_at=None,
previous_names=[],
name_changed_at=None,
is_bot=False,
is_authenticated=False,
scopes=frozenset(),
),
client_id=1,
event_id="evt-002",
timestamp=None,
),
make_user_parted_event(user=make_user(display_name="Carol")),
"[USER_PARTED] Carol parted.",
id="user-parted",
),
pytest.param(
EventType.NAME_CHANGE,
NameChangedEvent(
user=User(
id="abc123",
display_name="OldName",
display_color=0,
created_at=None,
previous_names=[],
name_changed_at=None,
is_bot=False,
is_authenticated=False,
scopes=frozenset(),
),
client_id=1,
make_name_changed_event(
user=make_user(display_name="OldName"),
new_name="NewName",
event_id="evt-003",
timestamp=None,
),
"[NAME_CHANGE] OldName changed name to NewName.",
id="name-change",
),
pytest.param(
EventType.STREAM_STARTED,
StreamStartedEvent(
server_id="srv-001",
server_name="My Stream",
stream_title="Playing Minecraft",
summary="A fun stream",
timestamp=None,
),
make_stream_started_event(stream_title="Playing Minecraft"),
'[STREAM_STARTED] Stream started: "Playing Minecraft"',
id="stream-started",
),
pytest.param(
EventType.STREAM_STOPPED,
StreamStoppedEvent(
server_id="srv-001",
server_name="My Stream",
stream_title="Playing Minecraft",
summary="A fun stream",
timestamp=None,
),
make_stream_stopped_event(),
"[STREAM_STOPPED] Stream ended.",
id="stream-stopped",
),
pytest.param(
EventType.STREAM_TITLE_UPDATED,
StreamTitleUpdatedEvent(
server_id="srv-001",
server_name="My Stream",
stream_title="New Title",
summary="",
status=None,
timestamp=None,
),
make_stream_title_updated_event(stream_title="New Title"),
'[STREAM_TITLE_UPDATED] Title changed to "New Title"',
id="stream-title-updated",
),
pytest.param(
EventType.VISIBILITY_UPDATE,
VisibilityUpdateEvent(
event_id="evt-004",
make_visibility_update_event(
message_ids=["msg-1", "msg-2"],
is_visible=True,
timestamp=None,
),
"[VISIBILITY-UPDATE] 2 message(s) shown: msg-1, msg-2",
id="visibility-shown",
),
pytest.param(
EventType.VISIBILITY_UPDATE,
VisibilityUpdateEvent(
event_id="evt-005",
message_ids=["msg-3"],
is_visible=False,
timestamp=None,
),
make_visibility_update_event(message_ids=["msg-3"]),
"[VISIBILITY-UPDATE] 1 message(s) hidden: msg-3",
id="visibility-hidden",
),
+89 -161
View File
@@ -33,8 +33,6 @@ from owlbot.api.context import EventContext, PropagationState
from owlbot.api.event_types import (
ChatEvent,
EventType,
User,
UserJoinedEvent,
)
from owlbot.api.events import EventMark, Priority, on_event
from owlbot.registries.events import (
@@ -43,49 +41,13 @@ from owlbot.registries.events import (
HandlerEntry,
ModuleEvents,
)
from tests.conftest import make_module_context
from owlbot.testing import make_chat_event, make_user_joined_event
if TYPE_CHECKING:
from owlbot.api.context import ModuleContext
from owlbot.api.storage import ModuleStorage
def _make_user(
*,
user_id: str = "user-1",
display_name: str = "TestUser",
) -> User:
"""Build a minimal User for test events."""
return User(
id=user_id,
display_name=display_name,
display_color=0,
created_at=None,
previous_names=[],
name_changed_at=None,
is_bot=False,
is_authenticated=False,
scopes=frozenset(),
)
def _make_chat_event(
*,
body: str = "hello",
user: User | None = None,
) -> ChatEvent:
"""Build a minimal ChatEvent for test dispatches."""
return ChatEvent(
user=user or _make_user(),
client_id=1,
body=body,
raw_body=f"<p>{body}</p>",
message_id="msg-001",
is_visible=True,
timestamp=None,
)
def _unused_get_module_context(name: str) -> ModuleContext:
"""Stub for EventDispatcher tests that never invoke get_module_context."""
raise AssertionError("get_module_context should not be called")
@@ -424,30 +386,28 @@ class TestEventRegistry:
class TestEventDispatcherDispatch:
"""Tests dispatch() from EventDispatcher."""
async def test_calls_handler(self, storage: ModuleStorage) -> None:
async def test_calls_handler(self, module_context: ModuleContext) -> None:
"""Handler receives an EventContext where ctx.event is the dispatched event."""
received: list[Any] = []
async def handler(ctx: EventContext[Any]) -> None:
received.append(ctx.event)
module_ctx = make_module_context(storage, "mod_a")
async def command_dispatch(event: ChatEvent) -> None:
pass
dispatcher = EventDispatcher(
command_dispatch=command_dispatch,
get_module_context=lambda _name: module_ctx,
get_module_context=lambda _name: module_context,
handler_timeout=5.0,
)
dispatcher.register(handler, (EventType.CHAT,), "mod_a")
event = _make_chat_event()
event = make_chat_event()
await dispatcher.dispatch(EventType.CHAT, event)
assert len(received) == 1
assert received[0] is event
async def test_priority_order(self, storage: ModuleStorage) -> None:
async def test_priority_order(self, module_context: ModuleContext) -> None:
"""Handlers execute in priority order: HIGH before NORMAL before LOW."""
call_order: list[str] = []
@@ -460,23 +420,23 @@ class TestEventDispatcherDispatch:
async def low_handler(ctx: EventContext[Any]) -> None:
call_order.append("low")
module_ctx = make_module_context(storage, "mod_a")
async def command_dispatch(event: ChatEvent) -> None:
pass
dispatcher = EventDispatcher(
command_dispatch=command_dispatch,
get_module_context=lambda _name: module_ctx,
get_module_context=lambda _name: module_context,
handler_timeout=5.0,
)
dispatcher.register(high_handler, (EventType.CHAT,), "mod_a", Priority.HIGH)
dispatcher.register(normal_handler, (EventType.CHAT,), "mod_a", Priority.NORMAL)
dispatcher.register(low_handler, (EventType.CHAT,), "mod_a", Priority.LOW)
await dispatcher.dispatch(EventType.CHAT, _make_chat_event())
await dispatcher.dispatch(EventType.CHAT, make_chat_event())
assert call_order == ["high", "normal", "low"]
async def test_stable_order_same_priority(self, storage: ModuleStorage) -> None:
async def test_stable_order_same_priority(
self, module_context: ModuleContext
) -> None:
"""Handlers at the same priority run in registration order."""
call_order: list[str] = []
@@ -486,71 +446,64 @@ class TestEventDispatcherDispatch:
async def second(ctx: EventContext[Any]) -> None:
call_order.append("second")
module_ctx = make_module_context(storage, "mod_a")
async def command_dispatch(event: ChatEvent) -> None:
pass
dispatcher = EventDispatcher(
command_dispatch=command_dispatch,
get_module_context=lambda _name: module_ctx,
get_module_context=lambda _name: module_context,
handler_timeout=5.0,
)
dispatcher.register(first, (EventType.CHAT,), "mod_a", Priority.NORMAL)
dispatcher.register(second, (EventType.CHAT,), "mod_a", Priority.NORMAL)
await dispatcher.dispatch(EventType.CHAT, _make_chat_event())
await dispatcher.dispatch(EventType.CHAT, make_chat_event())
assert call_order == ["first", "second"]
async def test_no_handlers(
self, storage: ModuleStorage, caplog: pytest.LogCaptureFixture
self, module_context: ModuleContext, caplog: pytest.LogCaptureFixture
) -> None:
"""Dispatch with no handlers does not raise; debug log emitted."""
async def command_dispatch(event: ChatEvent) -> None:
pass
module_ctx = make_module_context(storage, "mod_a")
dispatcher = EventDispatcher(
command_dispatch=command_dispatch,
get_module_context=lambda _name: module_ctx,
get_module_context=lambda _name: module_context,
handler_timeout=5.0,
)
with caplog.at_level(logging.DEBUG, logger="owlbot.events"):
await dispatcher.dispatch(
EventType.USER_JOINED,
UserJoinedEvent(
user=_make_user(),
client_id=1,
event_id="evt-001",
timestamp=None,
),
make_user_joined_event(client_id=1, event_id="evt-001"),
)
assert any(
"No handlers registered for event type" in r.message for r in caplog.records
)
async def test_logs_event(
self, storage: ModuleStorage, caplog: pytest.LogCaptureFixture
self, module_context: ModuleContext, caplog: pytest.LogCaptureFixture
) -> None:
"""Dispatch logs the event via log_event() at INFO level."""
async def command_dispatch(event: ChatEvent) -> None:
pass
module_ctx = make_module_context(storage, "mod_a")
dispatcher = EventDispatcher(
command_dispatch=command_dispatch,
get_module_context=lambda _name: module_ctx,
get_module_context=lambda _name: module_context,
handler_timeout=5.0,
)
chat_event = _make_chat_event(body="hello")
chat_event = make_chat_event(raw_body="hello")
with caplog.at_level(logging.INFO, logger="owlbot.events"):
await dispatcher.dispatch(EventType.CHAT, chat_event)
assert any(
r.message == "[CHAT] TestUser (msg-001): hello" for r in caplog.records
r.message == "[CHAT] TestUser (test-msg-id): hello" for r in caplog.records
)
async def test_propagation_stops_remaining(self, storage: ModuleStorage) -> None:
async def test_propagation_stops_remaining(
self, module_context: ModuleContext
) -> None:
"""Handler A stops propagation; handler B is never called."""
call_order: list[str] = []
@@ -561,23 +514,21 @@ class TestEventDispatcherDispatch:
async def handler_b(ctx: EventContext[Any]) -> None:
call_order.append("b")
module_ctx = make_module_context(storage, "mod_a")
async def command_dispatch(event: ChatEvent) -> None:
pass
dispatcher = EventDispatcher(
command_dispatch=command_dispatch,
get_module_context=lambda _name: module_ctx,
get_module_context=lambda _name: module_context,
handler_timeout=5.0,
)
dispatcher.register(handler_a, (EventType.CHAT,), "mod_a", Priority.HIGH)
dispatcher.register(handler_b, (EventType.CHAT,), "mod_a", Priority.NORMAL)
await dispatcher.dispatch(EventType.CHAT, _make_chat_event())
await dispatcher.dispatch(EventType.CHAT, make_chat_event())
assert call_order == ["a"]
async def test_propagation_reason_logged(
self, storage: ModuleStorage, caplog: pytest.LogCaptureFixture
self, module_context: ModuleContext, caplog: pytest.LogCaptureFixture
) -> None:
"""Propagation stop reason appears in debug log."""
@@ -587,23 +538,21 @@ class TestEventDispatcherDispatch:
async def handler_b(ctx: EventContext[Any]) -> None:
pass
module_ctx = make_module_context(storage, "mod_a")
async def command_dispatch(event: ChatEvent) -> None:
pass
dispatcher = EventDispatcher(
command_dispatch=command_dispatch,
get_module_context=lambda _name: module_ctx,
get_module_context=lambda _name: module_context,
handler_timeout=5.0,
)
dispatcher.register(handler_a, (EventType.CHAT,), "mod_a", Priority.HIGH)
dispatcher.register(handler_b, (EventType.CHAT,), "mod_a", Priority.NORMAL)
with caplog.at_level(logging.DEBUG, logger="owlbot.events"):
await dispatcher.dispatch(EventType.CHAT, _make_chat_event())
await dispatcher.dispatch(EventType.CHAT, make_chat_event())
assert any("Propagation stopped: blocked" in r.message for r in caplog.records)
async def test_independent_dispatches(self, storage: ModuleStorage) -> None:
async def test_independent_dispatches(self, module_context: ModuleContext) -> None:
"""Stop propagation in first dispatch; second dispatch runs all."""
call_order: list[str] = []
stop_once = True
@@ -618,31 +567,31 @@ class TestEventDispatcherDispatch:
async def follower(ctx: EventContext[Any]) -> None:
call_order.append("follower")
module_ctx = make_module_context(storage, "mod_a")
async def command_dispatch(event: ChatEvent) -> None:
pass
dispatcher = EventDispatcher(
command_dispatch=command_dispatch,
get_module_context=lambda _name: module_ctx,
get_module_context=lambda _name: module_context,
handler_timeout=5.0,
)
dispatcher.register(stopper, (EventType.CHAT,), "mod_a", Priority.HIGH)
dispatcher.register(follower, (EventType.CHAT,), "mod_a", Priority.NORMAL)
await dispatcher.dispatch(EventType.CHAT, _make_chat_event())
await dispatcher.dispatch(EventType.CHAT, make_chat_event())
assert call_order == ["stopper"]
call_order.clear()
await dispatcher.dispatch(EventType.CHAT, _make_chat_event())
await dispatcher.dispatch(EventType.CHAT, make_chat_event())
assert call_order == ["stopper", "follower"]
class TestEventDispatcherStorage:
"""Tests _call_handler() storage behaviour in EventDispatcher."""
"""Tests _call_handler() storage behavior in EventDispatcher."""
async def test_success_commits(self, storage: ModuleStorage) -> None:
async def test_success_commits(
self, module_context: ModuleContext, storage: ModuleStorage
) -> None:
"""A successful handler's database changes are committed."""
async def handler(ctx: EventContext[Any]) -> None:
@@ -651,25 +600,26 @@ class TestEventDispatcherStorage:
"INSERT INTO test_tbl (val) VALUES (?)", ("committed",)
)
module_ctx = make_module_context(storage, "mod_a")
async def command_dispatch(event: ChatEvent) -> None:
pass
dispatcher = EventDispatcher(
command_dispatch=command_dispatch,
get_module_context=lambda _name: module_ctx,
get_module_context=lambda _name: module_context,
handler_timeout=5.0,
)
dispatcher.register(handler, (EventType.CHAT,), "mod_a")
await dispatcher.dispatch(EventType.CHAT, _make_chat_event())
await dispatcher.dispatch(EventType.CHAT, make_chat_event())
row = await storage.fetch_one("SELECT val FROM test_tbl")
assert row is not None
assert row[0] == "committed"
async def test_exception_does_not_roll_back_committed_writes(
self, storage: ModuleStorage, caplog: pytest.LogCaptureFixture
self,
module_context: ModuleContext,
storage: ModuleStorage,
caplog: pytest.LogCaptureFixture,
) -> None:
"""A handler that raises does not undo already-committed writes."""
# Pre-create the table outside the handler.
@@ -681,19 +631,17 @@ class TestEventDispatcherStorage:
)
raise RuntimeError("boom")
module_ctx = make_module_context(storage, "mod_a")
async def command_dispatch(event: ChatEvent) -> None:
pass
dispatcher = EventDispatcher(
command_dispatch=command_dispatch,
get_module_context=lambda _name: module_ctx,
get_module_context=lambda _name: module_context,
handler_timeout=5.0,
)
dispatcher.register(handler, (EventType.CHAT,), "mod_a")
with caplog.at_level(logging.ERROR, logger="owlbot.events"):
await dispatcher.dispatch(EventType.CHAT, _make_chat_event())
await dispatcher.dispatch(EventType.CHAT, make_chat_event())
row = await storage.fetch_one("SELECT val FROM test_tbl")
assert row is not None
@@ -701,7 +649,7 @@ class TestEventDispatcherStorage:
assert any("raised exception." in r.message for r in caplog.records)
async def test_exception_does_not_stop_next_handler(
self, storage: ModuleStorage
self, module_context: ModuleContext
) -> None:
"""A handler that raises does not prevent subsequent handlers from running."""
call_order: list[str] = []
@@ -713,49 +661,45 @@ class TestEventDispatcherStorage:
async def second_handler(ctx: EventContext[Any]) -> None:
call_order.append("second")
module_ctx = make_module_context(storage, "mod_a")
async def command_dispatch(event: ChatEvent) -> None:
pass
dispatcher = EventDispatcher(
command_dispatch=command_dispatch,
get_module_context=lambda _name: module_ctx,
get_module_context=lambda _name: module_context,
handler_timeout=5.0,
)
dispatcher.register(failing_handler, (EventType.CHAT,), "mod_a", Priority.HIGH)
dispatcher.register(second_handler, (EventType.CHAT,), "mod_a", Priority.NORMAL)
await dispatcher.dispatch(EventType.CHAT, _make_chat_event())
await dispatcher.dispatch(EventType.CHAT, make_chat_event())
assert call_order == ["failing", "second"]
async def test_timeout_is_logged(
self, storage: ModuleStorage, caplog: pytest.LogCaptureFixture
self, module_context: ModuleContext, caplog: pytest.LogCaptureFixture
) -> None:
"""A handler that exceeds the timeout is cancelled and logged."""
async def slow_handler(ctx: EventContext[Any]) -> None:
await asyncio.sleep(10)
module_ctx = make_module_context(storage, "mod_a")
async def command_dispatch(event: ChatEvent) -> None:
pass
dispatcher = EventDispatcher(
command_dispatch=command_dispatch,
get_module_context=lambda _name: module_ctx,
get_module_context=lambda _name: module_context,
handler_timeout=0.05,
)
dispatcher.register(slow_handler, (EventType.CHAT,), "mod_a")
with caplog.at_level(logging.WARNING, logger="owlbot.events"):
await dispatcher.dispatch(EventType.CHAT, _make_chat_event())
await dispatcher.dispatch(EventType.CHAT, make_chat_event())
assert any(
"cancelled after" in r.message and "0.05s timeout" in r.message
for r in caplog.records
)
async def test_timeout_does_not_roll_back_committed_writes(
self, storage: ModuleStorage
self, module_context: ModuleContext, storage: ModuleStorage
) -> None:
"""A timed-out handler's already-committed writes persist."""
await storage.execute("CREATE TABLE IF NOT EXISTS test_tbl (val TEXT)")
@@ -766,25 +710,23 @@ class TestEventDispatcherStorage:
)
await asyncio.sleep(10)
module_ctx = make_module_context(storage, "mod_a")
async def command_dispatch(event: ChatEvent) -> None:
pass
dispatcher = EventDispatcher(
command_dispatch=command_dispatch,
get_module_context=lambda _name: module_ctx,
get_module_context=lambda _name: module_context,
handler_timeout=0.05,
)
dispatcher.register(slow_handler, (EventType.CHAT,), "mod_a")
await dispatcher.dispatch(EventType.CHAT, _make_chat_event())
await dispatcher.dispatch(EventType.CHAT, make_chat_event())
row = await storage.fetch_one("SELECT val FROM test_tbl")
assert row is not None
assert row[0] == "persisted"
async def test_timeout_rolls_back_explicit_transaction(
self, storage: ModuleStorage
self, module_context: ModuleContext, storage: ModuleStorage
) -> None:
"""A timed-out handler's uncommitted transaction is rolled back."""
await storage.execute("CREATE TABLE IF NOT EXISTS test_tbl (val TEXT)")
@@ -796,18 +738,16 @@ class TestEventDispatcherStorage:
)
await asyncio.sleep(10)
module_ctx = make_module_context(storage, "mod_a")
async def command_dispatch(event: ChatEvent) -> None:
pass
dispatcher = EventDispatcher(
command_dispatch=command_dispatch,
get_module_context=lambda _name: module_ctx,
get_module_context=lambda _name: module_context,
handler_timeout=0.05,
)
dispatcher.register(slow_handler, (EventType.CHAT,), "mod_a")
await dispatcher.dispatch(EventType.CHAT, _make_chat_event())
await dispatcher.dispatch(EventType.CHAT, make_chat_event())
row = await storage.fetch_one("SELECT val FROM test_tbl")
assert row is None
@@ -821,18 +761,13 @@ class TestCommandDispatchPhase:
[
pytest.param(
EventType.CHAT,
_make_chat_event,
make_chat_event,
1,
id="chat-triggers",
),
pytest.param(
EventType.USER_JOINED,
lambda: UserJoinedEvent(
user=_make_user(),
client_id=1,
event_id="evt-001",
timestamp=None,
),
lambda: make_user_joined_event(client_id=1, event_id="evt-001"),
0,
id="non-chat-skips",
),
@@ -840,7 +775,7 @@ class TestCommandDispatchPhase:
)
async def test_command_dispatch_trigger(
self,
storage: ModuleStorage,
module_context: ModuleContext,
event_type: EventType,
event_factory: Any,
expected_calls: int,
@@ -851,10 +786,9 @@ class TestCommandDispatchPhase:
async def command_dispatch(event: ChatEvent) -> None:
command_calls.append(event)
module_ctx = make_module_context(storage, "mod_a")
dispatcher = EventDispatcher(
command_dispatch=command_dispatch,
get_module_context=lambda _name: module_ctx,
get_module_context=lambda _name: module_context,
handler_timeout=5.0,
)
event = event_factory()
@@ -864,7 +798,7 @@ class TestCommandDispatchPhase:
assert command_calls[0] is event
async def test_propagation_skips_commands(
self, storage: ModuleStorage, caplog: pytest.LogCaptureFixture
self, module_context: ModuleContext, caplog: pytest.LogCaptureFixture
) -> None:
"""Stopped propagation skips command dispatch."""
command_calls: list[Any] = []
@@ -875,36 +809,34 @@ class TestCommandDispatchPhase:
async def stopper(ctx: EventContext[Any]) -> None:
ctx.stop_propagation("spam")
module_ctx = make_module_context(storage, "mod_a")
dispatcher = EventDispatcher(
command_dispatch=command_dispatch,
get_module_context=lambda _name: module_ctx,
get_module_context=lambda _name: module_context,
handler_timeout=5.0,
)
dispatcher.register(stopper, (EventType.CHAT,), "mod_a")
with caplog.at_level(logging.DEBUG, logger="owlbot.events"):
await dispatcher.dispatch(EventType.CHAT, _make_chat_event())
await dispatcher.dispatch(EventType.CHAT, make_chat_event())
assert command_calls == []
assert any(
"Command dispatch skipped: spam" in r.message for r in caplog.records
)
async def test_command_dispatch_exception_caught(
self, storage: ModuleStorage, caplog: pytest.LogCaptureFixture
self, module_context: ModuleContext, caplog: pytest.LogCaptureFixture
) -> None:
"""An exception in command_dispatch is caught and logged, not propagated."""
async def command_dispatch(event: ChatEvent) -> None:
raise RuntimeError("fail")
module_ctx = make_module_context(storage, "mod_a")
dispatcher = EventDispatcher(
command_dispatch=command_dispatch,
get_module_context=lambda _name: module_ctx,
get_module_context=lambda _name: module_context,
handler_timeout=5.0,
)
with caplog.at_level(logging.ERROR, logger="owlbot.events"):
await dispatcher.dispatch(EventType.CHAT, _make_chat_event())
await dispatcher.dispatch(EventType.CHAT, make_chat_event())
assert any("Command dispatch failed." in r.message for r in caplog.records)
@@ -1062,80 +994,76 @@ class TestEventContext:
],
)
def test_property_proxying(
self, storage: ModuleStorage, prop: str, *, use_is: bool
self, module_context: ModuleContext, prop: str, *, use_is: bool
) -> None:
"""EventContext properties proxy to the underlying ModuleContext."""
module_ctx = make_module_context(storage, "mod_a")
event = _make_chat_event()
ctx: EventContext[ChatEvent] = EventContext(event=event, module=module_ctx)
event = make_chat_event()
ctx: EventContext[ChatEvent] = EventContext(event=event, module=module_context)
ctx_val = getattr(ctx, prop)
mod_val = getattr(module_ctx, prop)
mod_val = getattr(module_context, prop)
if use_is:
assert ctx_val is mod_val
else:
assert ctx_val == mod_val
def test_event_attribute(self) -> None:
def test_event_attribute(self, module_context: ModuleContext) -> None:
"""ctx.event is the event object passed at construction."""
module_ctx = make_module_context(None, "mod_a")
event = _make_chat_event()
ctx: EventContext[ChatEvent] = EventContext(event=event, module=module_ctx)
event = make_chat_event()
ctx: EventContext[ChatEvent] = EventContext(event=event, module=module_context)
assert ctx.event is event
def test_propagation_stopped_default(self) -> None:
def test_propagation_stopped_default(self, module_context: ModuleContext) -> None:
"""propagation_stopped is False by default."""
module_ctx = make_module_context(None, "mod_a")
ctx: EventContext[ChatEvent] = EventContext(
event=_make_chat_event(), module=module_ctx
event=make_chat_event(), module=module_context
)
assert ctx.propagation_stopped is False
def test_stop_propagation(self) -> None:
def test_stop_propagation(self, module_context: ModuleContext) -> None:
"""After stop_propagation(), propagation_stopped is True."""
module_ctx = make_module_context(None, "mod_a")
ctx: EventContext[ChatEvent] = EventContext(
event=_make_chat_event(), module=module_ctx
event=make_chat_event(), module=module_context
)
ctx.stop_propagation()
assert ctx.propagation_stopped is True
def test_stop_propagation_stores_reason(self) -> None:
def test_stop_propagation_stores_reason(
self, module_context: ModuleContext
) -> None:
"""stop_propagation() stores the reason string."""
module_ctx = make_module_context(None, "mod_a")
ctx: EventContext[ChatEvent] = EventContext(
event=_make_chat_event(), module=module_ctx
event=make_chat_event(), module=module_context
)
ctx.stop_propagation("blocked")
assert ctx._propagation.reason == "blocked"
def test_first_reason_wins(self) -> None:
def test_first_reason_wins(self, module_context: ModuleContext) -> None:
"""Only the first non-empty reason is stored."""
module_ctx = make_module_context(None, "mod_a")
ctx: EventContext[ChatEvent] = EventContext(
event=_make_chat_event(), module=module_ctx
event=make_chat_event(), module=module_context
)
ctx.stop_propagation("first")
ctx.stop_propagation("second")
assert ctx._propagation.reason == "first"
def test_none_reason_leaves_empty(self) -> None:
def test_none_reason_leaves_empty(self, module_context: ModuleContext) -> None:
"""stop_propagation(None) leaves reason as empty string."""
module_ctx = make_module_context(None, "mod_a")
ctx: EventContext[ChatEvent] = EventContext(
event=_make_chat_event(), module=module_ctx
event=make_chat_event(), module=module_context
)
ctx.stop_propagation(None)
assert ctx._propagation.reason == ""
def test_shared_propagation_across_contexts(self) -> None:
def test_shared_propagation_across_contexts(
self, module_context: ModuleContext
) -> None:
"""Two contexts sharing a PropagationState see each other's mutations."""
module_ctx = make_module_context(None, "mod_a")
propagation = PropagationState()
ctx_a: EventContext[ChatEvent] = EventContext(
event=_make_chat_event(), module=module_ctx, _propagation=propagation
event=make_chat_event(), module=module_context, _propagation=propagation
)
ctx_b: EventContext[ChatEvent] = EventContext(
event=_make_chat_event(), module=module_ctx, _propagation=propagation
event=make_chat_event(), module=module_context, _propagation=propagation
)
ctx_a.stop_propagation("blocked")
assert ctx_b.propagation_stopped is True
-282
View File
@@ -1,282 +0,0 @@
# Copyright 2026 Logan Fick
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for the quotes module: types, repository, and manager."""
from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
from owlbot.api.storage import ModuleStorage
from owlbot.builtin_modules.quotes.manager import QuoteManager, get_manager
from owlbot.builtin_modules.quotes.repository import QuoteRepository
from owlbot.builtin_modules.quotes.types import (
Quote,
QuoteError,
QuoteNotFoundError,
)
from tests.conftest import make_module_context
if TYPE_CHECKING:
from collections.abc import AsyncIterator
from owlbot.api.context import ModuleContext
@pytest.fixture
async def quote_storage() -> AsyncIterator[ModuleStorage]:
"""Yield an open in-memory ModuleStorage."""
async with ModuleStorage(None, "quotes") as storage:
yield storage
@pytest.fixture
async def repo(quote_storage: ModuleStorage) -> QuoteRepository:
"""QuoteRepository backed by quote_storage, with schema initialized."""
r = QuoteRepository(quote_storage)
await r.setup()
return r
@pytest.fixture
def quote_ctx(quote_storage: ModuleStorage) -> ModuleContext:
"""ModuleContext backed by quote_storage."""
return make_module_context(storage=quote_storage, module_name="quotes")
@pytest.fixture
def manager(quote_ctx: ModuleContext, repo: QuoteRepository) -> QuoteManager:
"""QuoteManager backed by real repo."""
return QuoteManager(quote_ctx, repo)
class TestQuoteFromRow:
"""Quote.from_row() database row conversion."""
async def test_builds_from_row(self) -> None:
"""from_row constructs a Quote with correct field values."""
row = {
"id": 5,
"text": "Test quote",
"added_by": "someone",
"created_at": "2026-03-15T10:00:00+00:00",
}
quote = Quote.from_row(row) # type: ignore[arg-type]
assert quote.id == 5
assert quote.text == "Test quote"
assert quote.added_by == "someone"
assert quote.created_at == "2026-03-15T10:00:00+00:00"
class TestQuoteErrors:
"""Quote domain error classes."""
def test_base_error_hierarchy(self) -> None:
"""All quote errors inherit from QuoteError."""
assert issubclass(QuoteNotFoundError, QuoteError)
def test_not_found_stores_quote_id(self) -> None:
"""QuoteNotFoundError stores the quote ID."""
err = QuoteNotFoundError(42)
assert err.quote_id == 42
assert "42" in str(err)
class TestRepositoryCreate:
"""QuoteRepository.create() inserts new quotes."""
async def test_create_returns_quote(self, repo: QuoteRepository) -> None:
"""Creating a quote returns a Quote snapshot with correct fields."""
quote = await repo.create("Hello, world!", "tester")
assert quote.id == 1
assert quote.text == "Hello, world!"
assert quote.added_by == "tester"
assert quote.created_at is not None
async def test_create_auto_increments(self, repo: QuoteRepository) -> None:
"""Each created quote gets a sequential ID."""
q1 = await repo.create("First", "tester")
q2 = await repo.create("Second", "tester")
assert q2.id == q1.id + 1
class TestRepositoryGet:
"""QuoteRepository.get() fetches by ID."""
async def test_get_existing(self, repo: QuoteRepository) -> None:
"""Fetches a quote by its ID."""
created = await repo.create("Test", "tester")
fetched = await repo.get(created.id)
assert fetched.id == created.id
assert fetched.text == "Test"
async def test_get_not_found(self, repo: QuoteRepository) -> None:
"""Raises QuoteNotFoundError for an unknown ID."""
with pytest.raises(QuoteNotFoundError) as exc_info:
await repo.get(999)
assert exc_info.value.quote_id == 999
class TestRepositoryGetRandom:
"""QuoteRepository.get_random() fetches a random quote."""
async def test_get_random_returns_quote(self, repo: QuoteRepository) -> None:
"""Returns a quote when the table is not empty."""
await repo.create("Only quote", "tester")
quote = await repo.get_random()
assert quote is not None
assert quote.text == "Only quote"
async def test_get_random_empty_table(self, repo: QuoteRepository) -> None:
"""Returns None when no quotes exist."""
result = await repo.get_random()
assert result is None
class TestRepositoryDelete:
"""QuoteRepository.delete() removes records."""
async def test_delete_returns_quote(self, repo: QuoteRepository) -> None:
"""Deleting a quote returns its snapshot."""
created = await repo.create("Doomed", "tester")
deleted = await repo.delete(created.id)
assert deleted.id == created.id
assert deleted.text == "Doomed"
async def test_delete_removes_from_db(self, repo: QuoteRepository) -> None:
"""Deleted quote is no longer retrievable."""
created = await repo.create("Doomed", "tester")
await repo.delete(created.id)
with pytest.raises(QuoteNotFoundError):
await repo.get(created.id)
async def test_delete_not_found(self, repo: QuoteRepository) -> None:
"""Raises QuoteNotFoundError for an unknown ID."""
with pytest.raises(QuoteNotFoundError) as exc_info:
await repo.delete(999)
assert exc_info.value.quote_id == 999
class TestRepositoryListAll:
"""QuoteRepository.list_all() returns all quotes."""
async def test_list_all(self, repo: QuoteRepository) -> None:
"""Returns all quotes ordered by ID."""
await repo.create("First", "alice")
await repo.create("Second", "bob")
result = await repo.list_all()
assert len(result) == 2
assert result[0].text == "First"
assert result[1].text == "Second"
async def test_list_all_empty(self, repo: QuoteRepository) -> None:
"""Returns an empty list when no quotes exist."""
assert await repo.list_all() == []
class TestQuoteManagerAddQuote:
"""QuoteManager.add_quote() creates quotes."""
async def test_add_quote(self, manager: QuoteManager) -> None:
"""add_quote creates a quote and returns its snapshot."""
quote = await manager.add_quote("Test quote", "tester")
assert quote.id == 1
assert quote.text == "Test quote"
assert quote.added_by == "tester"
class TestQuoteManagerDeleteQuote:
"""QuoteManager.delete_quote() removes quotes."""
async def test_delete_quote(self, manager: QuoteManager) -> None:
"""delete_quote removes the quote and returns its snapshot."""
created = await manager.add_quote("Doomed", "tester")
deleted = await manager.delete_quote(created.id)
assert deleted.id == created.id
assert deleted.text == "Doomed"
assert await manager.list_quotes() == []
async def test_delete_quote_not_found(self, manager: QuoteManager) -> None:
"""delete_quote raises QuoteNotFoundError for unknown ID."""
with pytest.raises(QuoteNotFoundError):
await manager.delete_quote(999)
class TestQuoteManagerGetQuote:
"""QuoteManager.get_quote() fetches by ID."""
async def test_get_quote(self, manager: QuoteManager) -> None:
"""get_quote returns the matching quote."""
created = await manager.add_quote("Test", "tester")
fetched = await manager.get_quote(created.id)
assert fetched.id == created.id
assert fetched.text == "Test"
async def test_get_quote_not_found(self, manager: QuoteManager) -> None:
"""get_quote raises QuoteNotFoundError for unknown ID."""
with pytest.raises(QuoteNotFoundError):
await manager.get_quote(999)
class TestQuoteManagerGetRandomQuote:
"""QuoteManager.get_random_quote() fetches random quotes."""
async def test_get_random_quote(self, manager: QuoteManager) -> None:
"""get_random_quote returns a quote when quotes exist."""
await manager.add_quote("Only one", "tester")
quote = await manager.get_random_quote()
assert quote is not None
assert quote.text == "Only one"
async def test_get_random_quote_empty(self, manager: QuoteManager) -> None:
"""get_random_quote returns None when no quotes exist."""
result = await manager.get_random_quote()
assert result is None
class TestQuoteManagerListQuotes:
"""QuoteManager.list_quotes() returns all quotes."""
async def test_list_quotes(self, manager: QuoteManager) -> None:
"""list_quotes returns all quotes ordered by ID."""
await manager.add_quote("First", "alice")
await manager.add_quote("Second", "bob")
result = await manager.list_quotes()
assert len(result) == 2
assert result[0].text == "First"
assert result[1].text == "Second"
async def test_list_quotes_empty(self, manager: QuoteManager) -> None:
"""list_quotes returns an empty list when no quotes exist."""
assert await manager.list_quotes() == []
class TestGetManager:
"""get_manager() helper."""
def test_returns_manager(self) -> None:
"""get_manager returns the QuoteManager from ctx.state."""
ctx = make_module_context()
repo_stub = QuoteRepository(ctx.storage)
mgr = QuoteManager(ctx, repo_stub)
ctx.state["manager"] = mgr
assert get_manager(ctx) is mgr
def test_raises_if_not_initialized(self) -> None:
"""get_manager raises RuntimeError when manager is missing."""
ctx = make_module_context()
with pytest.raises(RuntimeError, match="QuoteManager is not initialized"):
get_manager(ctx)
+130 -101
View File
@@ -34,18 +34,18 @@ from aiohttp.test_utils import make_mocked_request
from owlbot.api.context import RouteContext
from owlbot.api.routes import RouteInfo, RouteMark, on_route
from owlbot.registries.routes import ModuleRoutes, RouteDispatcher, RouteRegistry
from tests.conftest import make_module_context
if TYPE_CHECKING:
from owlbot.api.context import ModuleContext
def _make_dispatcher(
module_context: ModuleContext,
handler_timeout: float = 0.1,
) -> RouteDispatcher:
"""Build a RouteDispatcher with a controllable timeout."""
"""Build a RouteDispatcher wired to the given ModuleContext."""
return RouteDispatcher(
get_module_context=lambda name: make_module_context(module_name=name),
get_module_context=lambda _name: module_context,
handler_timeout=handler_timeout,
)
@@ -494,13 +494,13 @@ class TestRouteRegistry:
class TestRouteDispatcherDispatch:
"""Tests RouteDispatcher.dispatch() from owlbot.registries.routes."""
async def test_dispatch_dict_response(self) -> None:
async def test_dispatch_dict_response(self, module_context: ModuleContext) -> None:
"""Handler returning dict produces JSON 200 response."""
async def handler(ctx: RouteContext) -> dict[str, str]:
return {"status": "ok"}
dispatcher = _make_dispatcher()
dispatcher = _make_dispatcher(module_context)
dispatcher.register("/api", handler, module_name="mod")
request = make_mocked_request("GET", "/owlbot/mod/api")
@@ -511,13 +511,13 @@ class TestRouteDispatcherDispatch:
assert response.status == HTTPStatus.OK
assert response.content_type == "application/json"
async def test_dispatch_web_response(self) -> None:
async def test_dispatch_web_response(self, module_context: ModuleContext) -> None:
"""Handler returning web.Response is passed through."""
async def handler(ctx: RouteContext) -> web.Response:
return web.Response(text="hello", status=201)
dispatcher = _make_dispatcher()
dispatcher = _make_dispatcher(module_context)
dispatcher.register("/page", handler, module_name="mod")
request = make_mocked_request("GET", "/owlbot/mod/page")
@@ -527,13 +527,13 @@ class TestRouteDispatcherDispatch:
response = await dispatcher.dispatch(request)
assert response.status == HTTPStatus.CREATED
async def test_dispatch_none_response(self) -> None:
async def test_dispatch_none_response(self, module_context: ModuleContext) -> None:
"""Handler returning None produces 204 No Content."""
async def handler(ctx: RouteContext) -> None:
pass
dispatcher = _make_dispatcher()
dispatcher = _make_dispatcher(module_context)
dispatcher.register("/hook", handler, methods=["POST"], module_name="mod")
request = make_mocked_request("POST", "/owlbot/mod/hook")
@@ -543,9 +543,9 @@ class TestRouteDispatcherDispatch:
response = await dispatcher.dispatch(request)
assert response.status == HTTPStatus.NO_CONTENT
async def test_dispatch_404(self) -> None:
async def test_dispatch_404(self, module_context: ModuleContext) -> None:
"""Dispatch to unregistered path returns 404."""
dispatcher = _make_dispatcher()
dispatcher = _make_dispatcher(module_context)
request = make_mocked_request("GET", "/owlbot/mod/nope")
request.match_info["module_name"] = "mod"
@@ -554,9 +554,9 @@ class TestRouteDispatcherDispatch:
response = await dispatcher.dispatch(request)
assert response.status == HTTPStatus.NOT_FOUND
async def test_dispatch_405(self) -> None:
async def test_dispatch_405(self, module_context: ModuleContext) -> None:
"""Dispatch with wrong method returns 405 with Allow header."""
dispatcher = _make_dispatcher()
dispatcher = _make_dispatcher(module_context)
dispatcher.register("/data", _noop, methods=["GET"], module_name="mod")
request = make_mocked_request("POST", "/owlbot/mod/data")
@@ -567,13 +567,15 @@ class TestRouteDispatcherDispatch:
assert response.status == HTTPStatus.METHOD_NOT_ALLOWED
assert "GET" in response.headers["Allow"]
async def test_dispatch_handler_exception(self) -> None:
async def test_dispatch_handler_exception(
self, module_context: ModuleContext
) -> None:
"""Handler that raises returns 500."""
async def bad_handler(ctx: RouteContext) -> web.Response:
raise RuntimeError("boom")
dispatcher = _make_dispatcher()
dispatcher = _make_dispatcher(module_context)
dispatcher.register("/bad", bad_handler, module_name="mod")
request = make_mocked_request("GET", "/owlbot/mod/bad")
@@ -583,13 +585,15 @@ class TestRouteDispatcherDispatch:
response = await dispatcher.dispatch(request)
assert response.status == HTTPStatus.INTERNAL_SERVER_ERROR
async def test_dispatch_unsupported_return_type(self) -> None:
async def test_dispatch_unsupported_return_type(
self, module_context: ModuleContext
) -> None:
"""Handler returning unsupported type produces 500."""
async def bad_return(ctx: RouteContext) -> str:
return "not a valid return type"
dispatcher = _make_dispatcher()
dispatcher = _make_dispatcher(module_context)
dispatcher.register("/bad", bad_return, module_name="mod") # type: ignore[arg-type]
request = make_mocked_request("GET", "/owlbot/mod/bad")
@@ -599,14 +603,14 @@ class TestRouteDispatcherDispatch:
response = await dispatcher.dispatch(request)
assert response.status == HTTPStatus.INTERNAL_SERVER_ERROR
async def test_dispatch_timeout(self) -> None:
async def test_dispatch_timeout(self, module_context: ModuleContext) -> None:
"""Non-streaming handler exceeding timeout returns 500."""
async def slow(ctx: RouteContext) -> web.Response:
await asyncio.sleep(0.3)
return web.Response(text="done")
dispatcher = _make_dispatcher(handler_timeout=0.1)
dispatcher = _make_dispatcher(module_context, handler_timeout=0.1)
dispatcher.register("/slow", slow, module_name="mod")
request = make_mocked_request("GET", "/owlbot/mod/slow")
@@ -616,14 +620,16 @@ class TestRouteDispatcherDispatch:
response = await dispatcher.dispatch(request)
assert response.status == HTTPStatus.INTERNAL_SERVER_ERROR
async def test_dispatch_streaming_bypasses_timeout(self) -> None:
async def test_dispatch_streaming_bypasses_timeout(
self, module_context: ModuleContext
) -> None:
"""Streaming handler exceeding timeout is not cancelled."""
async def slow_stream(ctx: RouteContext) -> web.Response:
await asyncio.sleep(0.3)
return web.Response(text="done")
dispatcher = _make_dispatcher(handler_timeout=0.1)
dispatcher = _make_dispatcher(module_context, handler_timeout=0.1)
dispatcher.register("/stream", slow_stream, module_name="mod", streaming=True)
request = make_mocked_request("GET", "/owlbot/mod/stream")
@@ -633,13 +639,15 @@ class TestRouteDispatcherDispatch:
response = await dispatcher.dispatch(request)
assert response.status == HTTPStatus.OK
async def test_dispatch_streaming_exception(self) -> None:
async def test_dispatch_streaming_exception(
self, module_context: ModuleContext
) -> None:
"""Streaming handler that raises returns 500."""
async def bad_stream(ctx: RouteContext) -> web.Response:
raise RuntimeError("stream broke")
dispatcher = _make_dispatcher()
dispatcher = _make_dispatcher(module_context)
dispatcher.register("/bad", bad_stream, module_name="mod", streaming=True)
request = make_mocked_request("GET", "/owlbot/mod/bad")
@@ -649,13 +657,15 @@ class TestRouteDispatcherDispatch:
response = await dispatcher.dispatch(request)
assert response.status == HTTPStatus.INTERNAL_SERVER_ERROR
async def test_dispatch_streaming_normal_return(self) -> None:
async def test_dispatch_streaming_normal_return(
self, module_context: ModuleContext
) -> None:
"""Streaming handler returning dict produces JSON response."""
async def fast_stream(ctx: RouteContext) -> dict[str, str]:
return {"status": "ok"}
dispatcher = _make_dispatcher()
dispatcher = _make_dispatcher(module_context)
dispatcher.register("/fast", fast_stream, module_name="mod", streaming=True)
request = make_mocked_request("GET", "/owlbot/mod/fast")
@@ -665,14 +675,14 @@ class TestRouteDispatcherDispatch:
response = await dispatcher.dispatch(request)
assert response.status == HTTPStatus.OK
async def test_dispatch_path_params(self) -> None:
async def test_dispatch_path_params(self, module_context: ModuleContext) -> None:
"""Path parameters are populated in RouteContext.match_info."""
captured: list[dict[str, str]] = []
async def handler(ctx: RouteContext) -> None:
captured.append(dict(ctx.match_info))
dispatcher = _make_dispatcher()
dispatcher = _make_dispatcher(module_context)
dispatcher.register("/users/{id}", handler, module_name="mod")
request = make_mocked_request("GET", "/owlbot/mod/users/42")
@@ -683,13 +693,13 @@ class TestRouteDispatcherDispatch:
assert len(captured) == 1
assert captured[0]["id"] == "42"
async def test_dispatch_root_path(self) -> None:
async def test_dispatch_root_path(self, module_context: ModuleContext) -> None:
"""Dispatch to module root (no path segment) works."""
async def handler(ctx: RouteContext) -> dict[str, str]:
return {"root": "yes"}
dispatcher = _make_dispatcher()
dispatcher = _make_dispatcher(module_context)
dispatcher.register("/", handler, module_name="mod")
request = make_mocked_request("GET", "/owlbot/mod/")
@@ -703,7 +713,9 @@ class TestRouteDispatcherDispatch:
class TestRouteDispatcherDrainHandlers:
"""Tests RouteDispatcher.drain_handlers() from owlbot.registries.routes."""
async def test_drain_handlers_cancels_active_handler(self) -> None:
async def test_drain_handlers_cancels_active_handler(
self, module_context: ModuleContext
) -> None:
"""drain_handlers() cancels a running streaming handler."""
entered = asyncio.Event()
@@ -712,7 +724,7 @@ class TestRouteDispatcherDrainHandlers:
await asyncio.sleep(3600)
return web.Response(text="done")
dispatcher = _make_dispatcher()
dispatcher = _make_dispatcher(module_context)
dispatcher.register(
"/stream", forever_stream, module_name="mod", streaming=True
)
@@ -733,19 +745,23 @@ class TestRouteDispatcherDrainHandlers:
with pytest.raises(asyncio.CancelledError):
await task
async def test_drain_handlers_noop_when_empty(self) -> None:
async def test_drain_handlers_noop_when_empty(
self, module_context: ModuleContext
) -> None:
"""drain_handlers() with no active handlers completes immediately."""
dispatcher = _make_dispatcher()
dispatcher = _make_dispatcher(module_context)
await dispatcher.drain_handlers()
assert len(dispatcher._streaming_tasks) == 0
async def test_streaming_task_cleaned_up_on_normal_return(self) -> None:
async def test_streaming_task_cleaned_up_on_normal_return(
self, module_context: ModuleContext
) -> None:
"""Streaming task is removed from tracking after normal completion."""
async def quick_stream(ctx: RouteContext) -> dict[str, str]:
return {"ok": "true"}
dispatcher = _make_dispatcher()
dispatcher = _make_dispatcher(module_context)
dispatcher.register("/quick", quick_stream, module_name="mod", streaming=True)
request = make_mocked_request("GET", "/owlbot/mod/quick")
@@ -755,13 +771,15 @@ class TestRouteDispatcherDrainHandlers:
await dispatcher.dispatch(request)
assert len(dispatcher._streaming_tasks) == 0
async def test_streaming_task_cleaned_up_on_exception(self) -> None:
async def test_streaming_task_cleaned_up_on_exception(
self, module_context: ModuleContext
) -> None:
"""Streaming task is removed from tracking after handler exception."""
async def bad_stream(ctx: RouteContext) -> web.Response:
raise RuntimeError("boom")
dispatcher = _make_dispatcher()
dispatcher = _make_dispatcher(module_context)
dispatcher.register("/bad", bad_stream, module_name="mod", streaming=True)
request = make_mocked_request("GET", "/owlbot/mod/bad")
@@ -771,7 +789,9 @@ class TestRouteDispatcherDrainHandlers:
await dispatcher.dispatch(request)
assert len(dispatcher._streaming_tasks) == 0
async def test_drain_handlers_multiple_handlers(self) -> None:
async def test_drain_handlers_multiple_handlers(
self, module_context: ModuleContext
) -> None:
"""drain_handlers() cancels all active streaming handlers."""
entered = asyncio.Event()
count = 0
@@ -784,7 +804,7 @@ class TestRouteDispatcherDrainHandlers:
await asyncio.sleep(3600)
return web.Response(text="done")
dispatcher = _make_dispatcher()
dispatcher = _make_dispatcher(module_context)
dispatcher.register("/s1", forever_stream, module_name="mod", streaming=True)
dispatcher.register("/s2", forever_stream, module_name="mod", streaming=True)
@@ -808,13 +828,15 @@ class TestRouteDispatcherDrainHandlers:
with pytest.raises(asyncio.CancelledError):
await task2
async def test_nonstreaming_task_tracked_and_cleaned_up(self) -> None:
async def test_nonstreaming_task_tracked_and_cleaned_up(
self, module_context: ModuleContext
) -> None:
"""Non-streaming handler tasks are tracked and cleaned up."""
async def handler(ctx: RouteContext) -> dict[str, str]:
return {"ok": "true"}
dispatcher = _make_dispatcher()
dispatcher = _make_dispatcher(module_context)
dispatcher.register("/api", handler, module_name="mod")
request = make_mocked_request("GET", "/owlbot/mod/api")
@@ -824,7 +846,9 @@ class TestRouteDispatcherDrainHandlers:
await dispatcher.dispatch(request)
assert len(dispatcher._handler_tasks) == 0
async def test_drain_handlers_waits_for_nonstreaming_first(self) -> None:
async def test_drain_handlers_waits_for_nonstreaming_first(
self, module_context: ModuleContext
) -> None:
"""drain_handlers() waits for non-streaming handlers before cancelling."""
order: list[str] = []
handler_entered = asyncio.Event()
@@ -845,7 +869,7 @@ class TestRouteDispatcherDrainHandlers:
raise
return web.Response(text="done")
dispatcher = _make_dispatcher(handler_timeout=5.0)
dispatcher = _make_dispatcher(module_context, handler_timeout=5.0)
dispatcher.register("/api", slow_handler, module_name="mod")
dispatcher.register(
"/stream", forever_stream, module_name="mod", streaming=True
@@ -875,37 +899,37 @@ class TestRouteDispatcherDrainHandlers:
class TestRouteDispatcherDelegation:
"""Tests RouteDispatcher delegation methods from owlbot.registries.routes."""
def test_unregister(self) -> None:
def test_unregister(self, module_context: ModuleContext) -> None:
"""RouteDispatcher.unregister() delegates to registry."""
dispatcher = _make_dispatcher()
dispatcher = _make_dispatcher(module_context)
dispatcher.register("/x", _noop, module_name="mod")
assert dispatcher.unregister("/owlbot/mod/x") is True
assert dispatcher.unregister("/owlbot/mod/x") is False
def test_get_no_method(self) -> None:
def test_get_no_method(self, module_context: ModuleContext) -> None:
"""RouteDispatcher.get() without method returns list."""
dispatcher = _make_dispatcher()
dispatcher = _make_dispatcher(module_context)
dispatcher.register("/x", _noop, module_name="mod")
result = dispatcher.get("/owlbot/mod/x")
assert isinstance(result, list)
assert len(result) == 1
def test_get_with_method(self) -> None:
def test_get_with_method(self, module_context: ModuleContext) -> None:
"""RouteDispatcher.get() with method returns RouteInfo or None."""
dispatcher = _make_dispatcher()
dispatcher = _make_dispatcher(module_context)
dispatcher.register("/x", _noop, module_name="mod")
assert dispatcher.get("/owlbot/mod/x", method="GET") is not None
assert dispatcher.get("/owlbot/mod/x", method="POST") is None
def test_get_by_module(self) -> None:
def test_get_by_module(self, module_context: ModuleContext) -> None:
"""RouteDispatcher.get_by_module() delegates to registry."""
dispatcher = _make_dispatcher()
dispatcher = _make_dispatcher(module_context)
dispatcher.register("/a", _noop, module_name="mod_a")
dispatcher.register("/b", _noop, module_name="mod_b")
result = dispatcher.get_by_module("mod_a")
assert len(result) == 1
def test_register_from_module(self) -> None:
def test_register_from_module(self, module_context: ModuleContext) -> None:
"""RouteDispatcher.register_from_module() delegates to registry."""
@on_route("/scan")
@@ -915,13 +939,13 @@ class TestRouteDispatcherDelegation:
mod = types.ModuleType("fake")
mod.handler = handler # type: ignore[attr-defined]
dispatcher = _make_dispatcher()
dispatcher = _make_dispatcher(module_context)
dispatcher.register_from_module(mod, "fake")
assert len(dispatcher.get_by_module("fake")) == 1
def test_unregister_by_module(self) -> None:
def test_unregister_by_module(self, module_context: ModuleContext) -> None:
"""RouteDispatcher.unregister_by_module() delegates to registry."""
dispatcher = _make_dispatcher()
dispatcher = _make_dispatcher(module_context)
dispatcher.register("/a", _noop, module_name="mod")
dispatcher.register("/b", _noop, module_name="mod")
assert dispatcher.unregister_by_module("mod") == 2
@@ -932,75 +956,77 @@ class TestModuleRoutes:
"""Tests ModuleRoutes from owlbot.registries.routes."""
def _make_mod_routes(
self, *module_names: str
self, module_context: ModuleContext, *module_names: str
) -> tuple[RouteDispatcher, dict[str, ModuleRoutes]]:
"""Build a dispatcher and ModuleRoutes wrappers for given modules."""
dispatcher = _make_dispatcher(handler_timeout=5.0)
dispatcher = _make_dispatcher(module_context, handler_timeout=5.0)
mod_routes = {
name: ModuleRoutes(dispatcher, name, "https://example.com")
for name in module_names
}
return dispatcher, mod_routes
def test_register_auto_supplies_module_name(self) -> None:
def test_register_auto_supplies_module_name(
self, module_context: ModuleContext
) -> None:
"""ModuleRoutes.register() auto-supplies module_name."""
_, mod_routes = self._make_mod_routes("mod_a")
_, mod_routes = self._make_mod_routes(module_context, "mod_a")
info = mod_routes["mod_a"].register("/stats", _noop)
assert info.module_name == "mod_a"
assert info.full_path == "/owlbot/mod_a/stats"
def test_register_streaming(self) -> None:
def test_register_streaming(self, module_context: ModuleContext) -> None:
"""ModuleRoutes.register() passes streaming through."""
_, mod_routes = self._make_mod_routes("mod_a")
_, mod_routes = self._make_mod_routes(module_context, "mod_a")
info = mod_routes["mod_a"].register("/sse", _noop, streaming=True)
assert info.streaming is True
def test_register_methods(self) -> None:
def test_register_methods(self, module_context: ModuleContext) -> None:
"""ModuleRoutes.register() passes methods through."""
_, mod_routes = self._make_mod_routes("mod_a")
_, mod_routes = self._make_mod_routes(module_context, "mod_a")
info = mod_routes["mod_a"].register("/data", _noop, methods=["GET", "POST"])
assert info.methods == frozenset({"GET", "POST"})
def test_unregister_by_path(self) -> None:
def test_unregister_by_path(self, module_context: ModuleContext) -> None:
"""ModuleRoutes.unregister() removes all handlers at path."""
_, mod_routes = self._make_mod_routes("mod_a")
_, mod_routes = self._make_mod_routes(module_context, "mod_a")
mod_routes["mod_a"].register("/stats", _noop)
assert mod_routes["mod_a"].unregister("/stats") is True
assert mod_routes["mod_a"].get("/stats") == []
def test_unregister_by_method(self) -> None:
def test_unregister_by_method(self, module_context: ModuleContext) -> None:
"""ModuleRoutes.unregister() with method removes only that handler."""
_, mod_routes = self._make_mod_routes("mod_a")
_, mod_routes = self._make_mod_routes(module_context, "mod_a")
mod_routes["mod_a"].register("/data", _noop, methods=["GET"])
mod_routes["mod_a"].register("/data", _noop, methods=["POST"])
assert mod_routes["mod_a"].unregister("/data", method="GET") is True
remaining = mod_routes["mod_a"].get("/data")
assert len(remaining) == 1
def test_unregister_unknown(self) -> None:
def test_unregister_unknown(self, module_context: ModuleContext) -> None:
"""ModuleRoutes.unregister() returns False for unknown path."""
_, mod_routes = self._make_mod_routes("mod_a")
_, mod_routes = self._make_mod_routes(module_context, "mod_a")
assert mod_routes["mod_a"].unregister("/nope") is False
def test_get_no_method(self) -> None:
def test_get_no_method(self, module_context: ModuleContext) -> None:
"""ModuleRoutes.get() without method returns list."""
_, mod_routes = self._make_mod_routes("mod_a")
_, mod_routes = self._make_mod_routes(module_context, "mod_a")
mod_routes["mod_a"].register("/data", _noop, methods=["GET"])
mod_routes["mod_a"].register("/data", _noop, methods=["POST"])
result = mod_routes["mod_a"].get("/data")
assert isinstance(result, list)
assert len(result) == 2
def test_get_with_method(self) -> None:
def test_get_with_method(self, module_context: ModuleContext) -> None:
"""ModuleRoutes.get() with method returns RouteInfo or None."""
_, mod_routes = self._make_mod_routes("mod_a")
_, mod_routes = self._make_mod_routes(module_context, "mod_a")
mod_routes["mod_a"].register("/data", _noop, methods=["GET"])
assert mod_routes["mod_a"].get("/data", method="GET") is not None
assert mod_routes["mod_a"].get("/data", method="POST") is None
def test_get_unknown_path(self) -> None:
def test_get_unknown_path(self, module_context: ModuleContext) -> None:
"""ModuleRoutes.get() for unknown path returns empty list."""
_, mod_routes = self._make_mod_routes("mod_a")
_, mod_routes = self._make_mod_routes(module_context, "mod_a")
assert mod_routes["mod_a"].get("/nope") == []
@pytest.mark.parametrize(
@@ -1014,13 +1040,14 @@ class TestModuleRoutes:
)
def test_exists(
self,
module_context: ModuleContext,
*,
register: bool,
check_method: str | None,
expected: bool,
) -> None:
"""ModuleRoutes.exists() checks for route presence."""
_, mod_routes = self._make_mod_routes("mod_a")
_, mod_routes = self._make_mod_routes(module_context, "mod_a")
if register:
mod_routes["mod_a"].register("/data", _noop)
if check_method is not None:
@@ -1028,30 +1055,30 @@ class TestModuleRoutes:
else:
assert mod_routes["mod_a"].exists("/data") is expected
def test_url_for(self) -> None:
def test_url_for(self, module_context: ModuleContext) -> None:
"""ModuleRoutes.url_for() builds correct public URL."""
_, mod_routes = self._make_mod_routes("mod_a")
_, mod_routes = self._make_mod_routes(module_context, "mod_a")
url = mod_routes["mod_a"].url_for("/list")
assert url == "https://example.com/owlbot/mod_a/list"
def test_url_for_normalizes_path(self) -> None:
def test_url_for_normalizes_path(self, module_context: ModuleContext) -> None:
"""ModuleRoutes.url_for() adds leading slash if missing."""
_, mod_routes = self._make_mod_routes("mod_a")
_, mod_routes = self._make_mod_routes(module_context, "mod_a")
url = mod_routes["mod_a"].url_for("list")
assert url == "https://example.com/owlbot/mod_a/list"
def test_module_routes_property(self) -> None:
def test_module_routes_property(self, module_context: ModuleContext) -> None:
"""module_routes returns only this module's routes."""
_, mod_routes = self._make_mod_routes("mod_a", "mod_b")
_, mod_routes = self._make_mod_routes(module_context, "mod_a", "mod_b")
mod_routes["mod_a"].register("/a", _noop)
mod_routes["mod_b"].register("/b", _noop)
routes = mod_routes["mod_a"].module_routes
assert len(routes) == 1
assert routes[0].module_name == "mod_a"
def test_module_routes_property_empty(self) -> None:
def test_module_routes_property_empty(self, module_context: ModuleContext) -> None:
"""module_routes returns empty list when nothing registered."""
_, mod_routes = self._make_mod_routes("mod_a")
_, mod_routes = self._make_mod_routes(module_context, "mod_a")
assert mod_routes["mod_a"].module_routes == []
@@ -1060,16 +1087,15 @@ class TestRouteContext:
def _make_route_context(
self,
) -> tuple[RouteContext, ModuleContext]:
"""Build a RouteContext with stub parts."""
module_ctx = make_module_context(module_name="mod_a")
request = make_mocked_request("GET", "/owlbot/mod_a/test")
ctx = RouteContext(
module_ctx: ModuleContext,
) -> RouteContext:
"""Build a RouteContext wrapping the given ModuleContext."""
request = make_mocked_request("GET", f"/owlbot/{module_ctx.module_name}/test")
return RouteContext(
request=request,
module=module_ctx,
match_info={"id": "42"},
)
return ctx, module_ctx
@pytest.mark.parametrize(
("prop", "use_is"),
@@ -1087,30 +1113,33 @@ class TestRouteContext:
pytest.param("templates", True, id="templates"),
],
)
def test_property_proxying(self, prop: str, *, use_is: bool) -> None:
def test_property_proxying(
self, module_context: ModuleContext, prop: str, *, use_is: bool
) -> None:
"""RouteContext properties proxy to the underlying ModuleContext."""
ctx, module_ctx = self._make_route_context()
ctx = self._make_route_context(module_context)
ctx_val = getattr(ctx, prop)
mod_val = getattr(module_ctx, prop)
mod_val = getattr(module_context, prop)
if use_is:
assert ctx_val is mod_val
else:
assert ctx_val == mod_val
def test_request_accessible(self) -> None:
def test_request_accessible(self, module_context: ModuleContext) -> None:
"""RouteContext.request is the aiohttp Request."""
ctx, _ = self._make_route_context()
ctx = self._make_route_context(module_context)
assert ctx.request is not None
assert ctx.request.method == "GET"
def test_match_info_accessible(self) -> None:
def test_match_info_accessible(self, module_context: ModuleContext) -> None:
"""RouteContext.match_info contains path parameters."""
ctx, _ = self._make_route_context()
ctx = self._make_route_context(module_context)
assert ctx.match_info == {"id": "42"}
def test_match_info_defaults_empty(self) -> None:
def test_match_info_defaults_empty(self, module_context: ModuleContext) -> None:
"""RouteContext.match_info defaults to empty dict."""
module_ctx = make_module_context(module_name="mod_a")
request = make_mocked_request("GET", "/owlbot/mod_a/test")
ctx = RouteContext(request=request, module=module_ctx)
request = make_mocked_request(
"GET", f"/owlbot/{module_context.module_name}/test"
)
ctx = RouteContext(request=request, module=module_context)
assert ctx.match_info == {}
+521
View File
@@ -0,0 +1,521 @@
# Copyright 2026 Logan Fick
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for owlbot.testing helper factory functions."""
from __future__ import annotations
import dataclasses
import re
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any
import pytest
from owlbot import testing as testing_pkg
from owlbot.api.event_types import (
_EVENT_TYPE_MAP,
ChatEvent,
NameChangedEvent,
StreamStartedEvent,
StreamStatus,
StreamStoppedEvent,
StreamTitleUpdatedEvent,
User,
UserJoinedEvent,
UserPartedEvent,
VisibilityUpdateEvent,
)
from owlbot.testing import (
make_chat_event,
make_name_changed_event,
make_stream_started_event,
make_stream_status,
make_stream_stopped_event,
make_stream_title_updated_event,
make_user,
make_user_joined_event,
make_user_parted_event,
make_visibility_update_event,
)
if TYPE_CHECKING:
from collections.abc import Callable
class TestMakeUser:
"""Exercises the make_user() factory function."""
def test_defaults(self) -> None:
"""All default values produce a valid User with expected fields."""
user = make_user()
assert isinstance(user, User)
assert user.id == "test-user-id"
assert user.display_name == "TestUser"
assert user.display_color == 0
assert user.created_at is None
assert user.previous_names == []
assert user.name_changed_at is None
assert user.is_bot is False
assert user.is_authenticated is False
assert user.scopes == frozenset()
assert user.is_moderator is False
def test_is_authenticated_flag(self) -> None:
"""is_authenticated=True sets is_authenticated on the User."""
user = make_user(is_authenticated=True)
assert user.is_authenticated is True
def test_is_moderator_shorthand(self) -> None:
"""is_moderator=True adds MODERATOR to scopes."""
user = make_user(is_moderator=True)
assert user.is_moderator is True
assert "MODERATOR" in user.scopes
def test_is_moderator_with_explicit_scopes(self) -> None:
"""is_moderator=True unions with explicitly provided scopes."""
user = make_user(is_moderator=True, scopes=frozenset({"CUSTOM"}))
assert user.scopes == frozenset({"MODERATOR", "CUSTOM"})
assert user.is_moderator is True
def test_explicit_scopes_without_is_moderator(self) -> None:
"""Explicit scopes without is_moderator=True are used as-is."""
user = make_user(scopes=frozenset({"CUSTOM"}))
assert user.scopes == frozenset({"CUSTOM"})
assert user.is_moderator is False
def test_custom_overrides(self) -> None:
"""All parameters can be overridden."""
user = make_user(
id="custom-id",
display_name="CustomUser",
display_color=5,
is_bot=True,
previous_names=["OldName"],
)
assert user.id == "custom-id"
assert user.display_name == "CustomUser"
assert user.display_color == 5
assert user.is_bot is True
assert user.previous_names == ["OldName"]
class TestMakeChatEvent:
"""Exercises the make_chat_event() factory function."""
def test_defaults(self) -> None:
"""All default values produce a valid ChatEvent."""
event = make_chat_event()
assert isinstance(event, ChatEvent)
assert isinstance(event.user, User)
assert event.body == "test message"
assert event.raw_body == "test message"
assert event.client_id == 0
assert event.message_id == "test-msg-id"
assert event.is_visible is True
assert event.timestamp is None
def test_body_defaults_to_raw_body(self) -> None:
"""When body is unspecified, it mirrors the raw_body value."""
event = make_chat_event(raw_body="custom body")
assert event.raw_body == "custom body"
assert event.body == "custom body"
def test_body_explicit(self) -> None:
"""An explicit body overrides the raw_body mirror."""
event = make_chat_event(raw_body="rendered", body="<p>rendered</p>")
assert event.raw_body == "rendered"
assert event.body == "<p>rendered</p>"
def test_custom_user(self) -> None:
"""A custom User object is used instead of the default."""
custom_user = make_user(display_name="Alice")
event = make_chat_event(user=custom_user)
assert event.user.display_name == "Alice"
def test_custom_overrides(self) -> None:
"""All parameters can be overridden."""
ts = datetime(2026, 1, 1, tzinfo=UTC)
event = make_chat_event(
raw_body="hello",
client_id=42,
message_id="msg-42",
is_visible=False,
timestamp=ts,
)
assert event.raw_body == "hello"
assert event.body == "hello"
assert event.client_id == 42
assert event.message_id == "msg-42"
assert event.is_visible is False
assert event.timestamp == ts
class TestMakeUserJoinedEvent:
"""Exercises the make_user_joined_event() factory function."""
def test_defaults(self) -> None:
"""All default values produce a valid UserJoinedEvent."""
event = make_user_joined_event()
assert isinstance(event, UserJoinedEvent)
assert isinstance(event.user, User)
assert event.client_id == 0
assert event.event_id == "test-join-id"
assert event.timestamp is None
def test_custom_overrides(self) -> None:
"""All parameters can be overridden."""
custom_user = make_user(display_name="Bob")
ts = datetime(2026, 3, 1, tzinfo=UTC)
event = make_user_joined_event(
user=custom_user,
client_id=7,
event_id="custom-join",
timestamp=ts,
)
assert event.user.display_name == "Bob"
assert event.client_id == 7
assert event.event_id == "custom-join"
assert event.timestamp == ts
class TestMakeUserPartedEvent:
"""Exercises the make_user_parted_event() factory function."""
def test_defaults(self) -> None:
"""All default values produce a valid UserPartedEvent."""
event = make_user_parted_event()
assert isinstance(event, UserPartedEvent)
assert isinstance(event.user, User)
assert event.client_id == 0
assert event.event_id == "test-part-id"
assert event.timestamp is None
def test_custom_overrides(self) -> None:
"""All parameters can be overridden."""
custom_user = make_user(display_name="Carol")
ts = datetime(2026, 4, 1, tzinfo=UTC)
event = make_user_parted_event(
user=custom_user,
client_id=9,
event_id="custom-part",
timestamp=ts,
)
assert event.user.display_name == "Carol"
assert event.client_id == 9
assert event.event_id == "custom-part"
assert event.timestamp == ts
class TestMakeNameChangedEvent:
"""Exercises the make_name_changed_event() factory function."""
def test_defaults(self) -> None:
"""All default values produce a valid NameChangedEvent."""
event = make_name_changed_event()
assert isinstance(event, NameChangedEvent)
assert isinstance(event.user, User)
assert event.client_id == 0
assert event.new_name == "NewName"
assert event.event_id == "test-name-change-id"
assert event.timestamp is None
def test_custom_overrides(self) -> None:
"""All parameters can be overridden."""
custom_user = make_user(display_name="OldName")
ts = datetime(2026, 5, 1, tzinfo=UTC)
event = make_name_changed_event(
user=custom_user,
client_id=5,
new_name="BrandNew",
event_id="custom-name-change",
timestamp=ts,
)
assert event.user.display_name == "OldName"
assert event.new_name == "BrandNew"
assert event.client_id == 5
assert event.event_id == "custom-name-change"
assert event.timestamp == ts
class TestMakeStreamStartedEvent:
"""Exercises the make_stream_started_event() factory function."""
def test_defaults(self) -> None:
"""All default values produce a valid StreamStartedEvent."""
event = make_stream_started_event()
assert isinstance(event, StreamStartedEvent)
assert event.server_id == "test-server-id"
assert event.server_name == "Test Server"
assert event.stream_title == "Test Stream"
assert event.summary == ""
assert event.timestamp is None
def test_custom_overrides(self) -> None:
"""All parameters can be overridden."""
ts = datetime(2026, 6, 1, tzinfo=UTC)
event = make_stream_started_event(
server_id="srv-42",
server_name="My Server",
stream_title="Playing Games",
summary="A fun stream",
timestamp=ts,
)
assert event.server_id == "srv-42"
assert event.server_name == "My Server"
assert event.stream_title == "Playing Games"
assert event.summary == "A fun stream"
assert event.timestamp == ts
class TestMakeStreamStoppedEvent:
"""Exercises the make_stream_stopped_event() factory function."""
def test_defaults(self) -> None:
"""All default values produce a valid StreamStoppedEvent."""
event = make_stream_stopped_event()
assert isinstance(event, StreamStoppedEvent)
assert event.server_id == "test-server-id"
assert event.server_name == "Test Server"
assert event.stream_title == "Test Stream"
assert event.summary == ""
assert event.timestamp is None
def test_custom_overrides(self) -> None:
"""All parameters can be overridden."""
ts = datetime(2026, 7, 1, tzinfo=UTC)
event = make_stream_stopped_event(
server_id="srv-99",
server_name="Other Server",
stream_title="Done Streaming",
summary="It was great",
timestamp=ts,
)
assert event.server_id == "srv-99"
assert event.server_name == "Other Server"
assert event.stream_title == "Done Streaming"
assert event.summary == "It was great"
assert event.timestamp == ts
class TestMakeStreamStatus:
"""Exercises the make_stream_status() factory function."""
def test_defaults(self) -> None:
"""All default values produce a valid StreamStatus."""
status = make_stream_status()
assert isinstance(status, StreamStatus)
assert status.last_connect_time is None
assert status.last_disconnect_time is None
assert status.version_number == ""
assert status.stream_title == "Test Stream"
assert status.viewer_count == 0
assert status.overall_max_viewer_count == 0
assert status.session_max_viewer_count == 0
assert status.is_online is False
def test_custom_overrides(self) -> None:
"""All parameters can be overridden."""
connect_ts = datetime(2026, 1, 1, tzinfo=UTC)
disconnect_ts = datetime(2026, 1, 2, tzinfo=UTC)
status = make_stream_status(
last_connect_time=connect_ts,
last_disconnect_time=disconnect_ts,
version_number="0.2.0",
stream_title="Playing Games",
viewer_count=42,
overall_max_viewer_count=100,
session_max_viewer_count=75,
is_online=True,
)
assert status.last_connect_time == connect_ts
assert status.last_disconnect_time == disconnect_ts
assert status.version_number == "0.2.0"
assert status.stream_title == "Playing Games"
assert status.viewer_count == 42
assert status.overall_max_viewer_count == 100
assert status.session_max_viewer_count == 75
assert status.is_online is True
class TestMakeStreamTitleUpdatedEvent:
"""Exercises the make_stream_title_updated_event() factory function."""
def test_defaults(self) -> None:
"""All default values produce a valid StreamTitleUpdatedEvent."""
event = make_stream_title_updated_event()
assert isinstance(event, StreamTitleUpdatedEvent)
assert event.server_id == "test-server-id"
assert event.server_name == "Test Server"
assert event.stream_title == "Test Stream"
assert event.summary == ""
assert event.status is None
assert event.timestamp is None
def test_custom_overrides(self) -> None:
"""All parameters can be overridden."""
ts = datetime(2026, 6, 15, tzinfo=UTC)
status = StreamStatus(
last_connect_time=ts,
last_disconnect_time=None,
version_number="0.2.0",
stream_title="Playing Games",
viewer_count=10,
overall_max_viewer_count=50,
session_max_viewer_count=20,
is_online=True,
)
event = make_stream_title_updated_event(
server_id="srv-42",
server_name="My Server",
stream_title="Playing Games",
summary="A fun stream",
status=status,
timestamp=ts,
)
assert event.server_id == "srv-42"
assert event.server_name == "My Server"
assert event.stream_title == "Playing Games"
assert event.summary == "A fun stream"
assert event.status is status
assert event.timestamp == ts
class TestMakeVisibilityUpdateEvent:
"""Exercises the make_visibility_update_event() factory function."""
def test_defaults(self) -> None:
"""All default values produce a valid VisibilityUpdateEvent."""
event = make_visibility_update_event()
assert isinstance(event, VisibilityUpdateEvent)
assert event.event_id == "test-vis-id"
assert event.message_ids == []
assert event.is_visible is False
assert event.timestamp is None
def test_custom_overrides(self) -> None:
"""All parameters can be overridden."""
ts = datetime(2026, 8, 1, tzinfo=UTC)
event = make_visibility_update_event(
event_id="vis-42",
message_ids=["msg-1", "msg-2"],
is_visible=True,
timestamp=ts,
)
assert event.event_id == "vis-42"
assert event.message_ids == ["msg-1", "msg-2"]
assert event.is_visible is True
assert event.timestamp == ts
class TestDefaultsMatchFromDict:
"""Non-identifier factory defaults match each dataclass's from_dict({})."""
@pytest.mark.parametrize(
("factory", "dataclass_cls", "identifier_fields"),
[
pytest.param(make_user, User, {"id", "display_name"}, id="user"),
pytest.param(
make_chat_event,
ChatEvent,
{"body", "raw_body", "message_id", "user"},
id="chat-event",
),
pytest.param(
make_user_joined_event,
UserJoinedEvent,
{"event_id", "user"},
id="user-joined-event",
),
pytest.param(
make_user_parted_event,
UserPartedEvent,
{"event_id", "user"},
id="user-parted-event",
),
pytest.param(
make_name_changed_event,
NameChangedEvent,
{"event_id", "new_name", "user"},
id="name-changed-event",
),
pytest.param(
make_stream_started_event,
StreamStartedEvent,
{"server_id", "server_name", "stream_title"},
id="stream-started-event",
),
pytest.param(
make_stream_stopped_event,
StreamStoppedEvent,
{"server_id", "server_name", "stream_title"},
id="stream-stopped-event",
),
pytest.param(
make_stream_status,
StreamStatus,
{"stream_title"},
id="stream-status",
),
pytest.param(
make_stream_title_updated_event,
StreamTitleUpdatedEvent,
{"server_id", "server_name", "stream_title"},
id="stream-title-updated-event",
),
pytest.param(
make_visibility_update_event,
VisibilityUpdateEvent,
{"event_id"},
id="visibility-update-event",
),
],
)
def test_defaults_match(
self,
factory: Callable[..., Any],
dataclass_cls: Any,
identifier_fields: set[str],
) -> None:
"""Every non-identifier default must equal dataclass_cls.from_dict({})."""
from_factory = factory()
from_empty_dict = dataclass_cls.from_dict({})
for field in dataclasses.fields(dataclass_cls):
if field.name in identifier_fields:
continue
assert getattr(from_factory, field.name) == getattr(
from_empty_dict, field.name
), f"{dataclass_cls.__name__}.{field.name}"
class TestEventTypeFactoryCoverage:
"""Guards against EventType additions without a matching owlbot.testing factory."""
def test_every_event_type_has_a_factory(self) -> None:
"""Every EventType must map to a ``make_<snake_case_dataclass>`` factory.
Derives the expected factory name from the dataclass name
(``StreamStartedEvent`` -> ``make_stream_started_event``) so no
separate lookup table has to stay in sync.
"""
missing: list[str] = []
for event_type, dataclass_cls in _EVENT_TYPE_MAP.items():
snake = re.sub(r"(?<!^)(?=[A-Z])", "_", dataclass_cls.__name__).lower()
factory_name = f"make_{snake}"
if not hasattr(testing_pkg, factory_name):
missing.append(
f"{event_type.name} -> {dataclass_cls.__name__}: "
f"no {factory_name!r} in owlbot.testing"
)
assert not missing, "Missing factories:\n " + "\n ".join(missing)
+620
View File
@@ -0,0 +1,620 @@
# Copyright 2026 Logan Fick
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for owlbot.testing.plugin fixtures."""
from __future__ import annotations
import types
from typing import TYPE_CHECKING, Any
import pytest
from aiohttp import ClientConnectionError
from owlbot.api.config import Config, ModuleConfig
from owlbot.api.event_types import EventType
from owlbot.api.events import Priority
from owlbot.api.http_client import HttpClient
from owlbot.api.storage import ModuleStorage
from owlbot.api.templates import ModuleTemplates
from owlbot.builtin_modules import quotes as quotes_pkg
from owlbot.registries.events import EventDispatcher
from owlbot.testing import (
make_chat_event,
make_user,
make_user_joined_event,
)
from owlbot.testing.stubs import (
RecordingOwncastAdminClient,
RecordingOwncastClient,
)
if TYPE_CHECKING:
from pathlib import Path
from types import ModuleType
from aiohttp.test_utils import TestClient
from aioresponses import aioresponses
from owlbot.api.context import CommandContext, EventContext, ModuleContext
from owlbot.api.event_types import UserJoinedEvent
from owlbot.registries.commands import CommandDispatcher
from owlbot.registries.routes import RouteDispatcher
class TestConfigurationFixtures:
"""Verify default values of overridable configuration fixtures."""
def test_module_pkg_default(self, module_pkg: ModuleType | None) -> None:
"""module_pkg defaults to None."""
assert module_pkg is None
def test_admin_client_enabled_default(self, *, admin_client_enabled: bool) -> None:
"""admin_client_enabled defaults to False."""
assert admin_client_enabled is False
def test_command_prefix_default(self, command_prefix: str) -> None:
"""command_prefix defaults to '!'."""
assert command_prefix == "!"
def test_handler_timeout_default(self, handler_timeout: float) -> None:
"""handler_timeout defaults to 30.0."""
assert handler_timeout == 30.0
def test_config_data_default(self, config_data: dict[str, Any]) -> None:
"""Config_data seeds owncast.url and a public_base_url matching Owlbot."""
assert config_data == {
"owncast": {"url": "http://localhost:8080"},
"owlbot": {"public_base_url": "http://localhost:8081"},
}
class TestConfigFixtures:
"""Verify the config_path / config fixture chain."""
def test_config_path_file_exists(self, config_path: Path) -> None:
"""config_path writes the seed YAML to a real file."""
assert config_path.is_file()
assert config_path.read_text().strip()
def test_config_is_real_instance(self, config: Config) -> None:
"""Config fixture returns a real Config backed by config_path."""
assert isinstance(config, Config)
assert config.owncast_url == "http://localhost:8080"
def test_module_config_set_persists_to_disk(
self, module_config: ModuleConfig, config_path: Path
) -> None:
"""module_config.set writes through to the backing YAML file."""
module_config.set("greeting", "hi")
assert "greeting: hi" in config_path.read_text()
class TestConfigDataOverride:
"""Overriding config_data flows into the real Config + ModuleConfig."""
@pytest.fixture
def config_data(self) -> dict[str, Any]:
"""Override config_data to set a custom public_base_url."""
return {
"owncast": {"url": "http://localhost:8080"},
"owlbot": {"public_base_url": "https://bot.example.com"},
}
def test_module_config_reads_override(self, module_config: ModuleConfig) -> None:
"""module_config.public_base_url reflects the seeded YAML value."""
assert module_config.public_base_url == "https://bot.example.com"
def test_module_context_routes_use_override(
self, module_context: ModuleContext
) -> None:
"""ModuleRoutes.url_for builds URLs from the overridden base."""
assert module_context.routes.url_for("list").startswith(
"https://bot.example.com/"
)
class TestOwncastClientBaseUrl:
"""owncast_client.base_url tracks config.owncast_url, including overrides."""
def test_default_matches_default_config(
self, owncast_client: RecordingOwncastClient, config: Config
) -> None:
"""With default config_data, stub base_url equals config.owncast_url."""
assert owncast_client.base_url == config.owncast_url
class TestWithOverride:
"""Overriding config_data.owncast.url propagates to the stub."""
@pytest.fixture
def config_data(self) -> dict[str, Any]:
"""Override owncast.url to a distinct value."""
return {
"owncast": {"url": "https://stream.example.com"},
"owlbot": {"public_base_url": "http://localhost:8081"},
}
def test_stub_base_url_follows_override(
self, owncast_client: RecordingOwncastClient
) -> None:
"""Stub base_url reflects the overridden owncast.url."""
assert owncast_client.base_url == "https://stream.example.com"
class TestTrailingSlashStripped:
"""Stub strips trailing slashes from owncast_url, matching the real client."""
@pytest.fixture
def config_data(self) -> dict[str, Any]:
"""Seed owncast.url with a trailing slash."""
return {
"owncast": {"url": "https://stream.example.com/"},
"owlbot": {"public_base_url": "http://localhost:8081"},
}
def test_stub_strips_trailing_slash(
self, owncast_client: RecordingOwncastClient
) -> None:
"""Stub base_url drops the trailing slash like OwncastClient does."""
assert owncast_client.base_url == "https://stream.example.com"
class TestModulePkgDerivation:
"""Overriding module_pkg auto-wires derived fixtures."""
@pytest.fixture
def module_pkg(self) -> ModuleType:
"""Override module_pkg with the quotes package."""
return quotes_pkg
def test_module_name_derives_from_module_pkg(
self, module_context: ModuleContext
) -> None:
"""module_context.module_name is the last segment of the package name."""
assert module_context.module_name == "quotes"
def test_templates_renders_module_template(
self, module_context: ModuleContext
) -> None:
"""module_context.templates resolves module-specific files."""
page = module_context.templates.render("list.html", quotes=[])
assert "No quotes have been added yet." in page
class TestTemplatesFallsBackToCore:
"""A module without its own templates/ directory still renders core templates."""
@pytest.fixture
def module_pkg(self, tmp_path: Any) -> ModuleType:
"""Override module_pkg with a fake package pointing at an empty tmp_path."""
fake = types.ModuleType("fake_module_no_templates")
fake.__file__ = str(tmp_path / "__init__.py")
return fake
def test_renders_core_template(self, templates: ModuleTemplates) -> None:
"""base.html resolves from the core templates directory."""
assert templates.render("base.html")
class TestFixturesValidateConfiguration:
"""Fixtures raise pytest.UsageError when their prerequisite knobs are unset.
Each test spins up a nested pytest run via ``pytester`` so the failure
surfaces through the real fixture resolution path instead of calling the
fixture function directly.
"""
def _run_plugin_test(
self, pytester: pytest.Pytester, body: str, *, asyncio_mode: bool = False
) -> pytest.RunResult:
"""Run a one-test pytester session that loads the Owlbot testing plugin."""
ini = "[pytest]\n"
if asyncio_mode:
ini += "asyncio_mode = auto\n"
pytester.makeini(ini)
pytester.makeconftest('pytest_plugins = ["owlbot.testing.plugin"]\n')
pytester.makepyfile(body)
return pytester.runpytest()
def test_registered_handlers_raises_without_module_pkg(
self, pytester: pytest.Pytester
) -> None:
"""registered_handlers raises pytest.UsageError when module_pkg is None."""
result = self._run_plugin_test(
pytester,
"""
def test_uses_handlers(registered_handlers):
pass
""",
)
result.assert_outcomes(errors=1)
assert "module_pkg" in result.stdout.str()
def test_module_lifecycle_raises_without_module_pkg(
self, pytester: pytest.Pytester
) -> None:
"""module_lifecycle raises pytest.UsageError when module_pkg is None."""
result = self._run_plugin_test(
pytester,
"""
async def test_uses_lifecycle(module_lifecycle):
pass
""",
asyncio_mode=True,
)
result.assert_outcomes(errors=1)
assert "module_pkg" in result.stdout.str()
def test_admin_client_raises_when_disabled(self, pytester: pytest.Pytester) -> None:
"""admin_client raises pytest.UsageError when admin_client_enabled is False."""
result = self._run_plugin_test(
pytester,
"""
def test_uses_admin_client(admin_client):
pass
""",
)
result.assert_outcomes(errors=1)
assert "admin_client_enabled" in result.stdout.str()
@pytest.mark.usefixtures("registered_handlers")
class TestRegisteredHandlersWithPkg:
"""With module_pkg set, registered_handlers registers everything."""
@pytest.fixture
def module_pkg(self) -> ModuleType:
"""Override module_pkg with the quotes package."""
return quotes_pkg
def test_commands_registered(self, command_dispatcher: CommandDispatcher) -> None:
"""Quotes module commands are registered."""
registered = command_dispatcher.get_by_module("quotes")
assert "quote" in registered
def test_routes_registered(self, route_dispatcher: RouteDispatcher) -> None:
"""Quotes module routes are registered."""
assert route_dispatcher.get_by_module("quotes") != []
def test_state_not_populated(self, module_context: ModuleContext) -> None:
"""registered_handlers skips @on_setup; ctx.state stays empty."""
assert "manager" not in module_context.state
@pytest.mark.usefixtures("module_lifecycle")
class TestModuleLifecycleWithPkg:
"""With module_pkg set, module_lifecycle runs handlers + @on_setup."""
@pytest.fixture
def module_pkg(self) -> ModuleType:
"""Override module_pkg with the quotes package."""
return quotes_pkg
def test_commands_registered(self, command_dispatcher: CommandDispatcher) -> None:
"""Decorator-registered commands are wired (via registered_handlers)."""
assert "quote" in command_dispatcher.get_by_module("quotes")
def test_setup_populates_state(self, module_context: ModuleContext) -> None:
"""@on_setup ran and populated ctx.state."""
assert module_context.state.get("manager") is not None
class TestBuildingBlockFixtures:
"""Verify building block fixtures produce usable instances."""
async def test_storage_is_open_and_usable(self, storage: ModuleStorage) -> None:
"""Storage fixture yields an open in-memory database."""
await storage.execute("CREATE TABLE t (id INTEGER PRIMARY KEY, val TEXT)")
await storage.execute("INSERT INTO t (val) VALUES (?)", ("hello",))
row = await storage.fetch_one("SELECT val FROM t WHERE id = 1")
assert row is not None
assert row[0] == "hello"
def test_owncast_client_is_recording(
self, owncast_client: RecordingOwncastClient
) -> None:
"""owncast_client fixture returns a RecordingOwncastClient with empty calls."""
assert isinstance(owncast_client, RecordingOwncastClient)
assert owncast_client.calls == []
def test_module_config_is_real_instance(self, module_config: ModuleConfig) -> None:
"""module_config fixture returns a real ModuleConfig with enabled=True."""
assert isinstance(module_config, ModuleConfig)
assert module_config.enabled is True
class TestModuleContext:
"""Verify the module_context fixture wires everything together."""
def test_module_name_defaults_to_test_module(
self, module_context: ModuleContext
) -> None:
"""module_context.module_name is 'test_module' when no module_pkg is set."""
assert module_context.module_name == "test_module"
def test_storage_is_wired(self, module_context: ModuleContext) -> None:
"""module_context.storage is a ModuleStorage instance."""
assert isinstance(module_context.storage, ModuleStorage)
def test_owncast_client_is_recording(self, module_context: ModuleContext) -> None:
"""module_context.owncast_client is a RecordingOwncastClient."""
assert isinstance(module_context.owncast_client, RecordingOwncastClient)
def test_config_is_real_module_config(self, module_context: ModuleContext) -> None:
"""module_context.config is a real ModuleConfig."""
assert isinstance(module_context.config, ModuleConfig)
def test_admin_client_none_by_default(self, module_context: ModuleContext) -> None:
"""admin_client is None when admin_client_enabled is False."""
assert module_context.admin_client is None
def test_templates_is_core_only_renderer_by_default(
self, module_context: ModuleContext
) -> None:
"""module_context.templates is a core-only renderer without module_pkg."""
assert isinstance(module_context.templates, ModuleTemplates)
# Core layout should resolve even without a module package.
assert module_context.templates.env.get_template("base.html") is not None
def test_state_is_empty_dict(self, module_context: ModuleContext) -> None:
"""module_context.state starts as an empty dict."""
assert module_context.state == {}
def test_commands_wired(self, module_context: ModuleContext) -> None:
"""module_context.commands is not None."""
assert module_context.commands is not None
def test_events_wired(self, module_context: ModuleContext) -> None:
"""module_context.events is not None."""
assert module_context.events is not None
def test_routes_wired(self, module_context: ModuleContext) -> None:
"""module_context.routes is not None."""
assert module_context.routes is not None
def test_event_dispatcher_available(
self, event_dispatcher: EventDispatcher
) -> None:
"""event_dispatcher fixture is an EventDispatcher instance."""
assert isinstance(event_dispatcher, EventDispatcher)
class TestAdminClientEnabled:
"""Tests that admin_client_enabled=True wires the admin client."""
@pytest.fixture
def admin_client_enabled(self) -> bool:
"""Override admin_client_enabled to True."""
return True
def test_admin_client_wired(self, module_context: ModuleContext) -> None:
"""admin_client is a RecordingOwncastAdminClient when enabled."""
assert module_context.admin_client is not None
assert isinstance(module_context.admin_client, RecordingOwncastAdminClient)
class TestHttpFixtures:
"""Tests for the http and mocked_http fixtures."""
async def test_http_is_httpclient(self, http: HttpClient) -> None:
"""The http fixture yields a started HttpClient."""
assert isinstance(http, HttpClient)
assert not http.session.closed
async def test_module_context_http_is_wired(
self, module_context: ModuleContext, http: HttpClient
) -> None:
"""module_context.http is the same HttpClient as the http fixture."""
assert module_context.http is http
async def test_mocked_response_is_returned(
self, http: HttpClient, mocked_http: aioresponses
) -> None:
"""Registered URLs return the canned response."""
mocked_http.get("https://example.test/data", payload={"ok": True})
async with http.get("https://example.test/data") as resp:
assert resp.status == 200
assert await resp.json() == {"ok": True}
async def test_unregistered_url_raises_connection_error(
self, http: HttpClient
) -> None:
"""Unregistered URLs raise ClientConnectionError rather than hitting the net."""
with pytest.raises(ClientConnectionError):
async with http.get("https://unregistered.test/data"):
pass
class TestEventDispatcher:
"""Integration tests exercising the full event dispatch pipeline."""
async def test_command_dispatch_through_events(
self,
module_context: ModuleContext,
event_dispatcher: EventDispatcher,
owncast_client: RecordingOwncastClient,
) -> None:
"""Dispatch a CHAT event for a registered command; verify it ran."""
async def handler(ctx: CommandContext) -> None:
await ctx.owncast_client.send_message("pong")
module_context.commands.register("ping", handler)
event = make_chat_event(raw_body="!ping")
await event_dispatcher.dispatch(EventType.CHAT, event)
assert len(owncast_client.calls) == 1
assert owncast_client.calls[0][0] == "send_message"
assert owncast_client.calls[0][1]["body"] == "pong"
async def test_event_handler_receives_event(
self,
module_context: ModuleContext,
event_dispatcher: EventDispatcher,
) -> None:
"""Register an event handler for USER_JOINED, verify it receives the event."""
received: list[UserJoinedEvent] = []
async def handler(ctx: EventContext[UserJoinedEvent]) -> None:
received.append(ctx.event)
module_context.events.register(handler, (EventType.USER_JOINED,))
event = make_user_joined_event()
await event_dispatcher.dispatch(EventType.USER_JOINED, event)
assert len(received) == 1
assert received[0] is event
async def test_propagation_stops_command_dispatch(
self,
module_context: ModuleContext,
event_dispatcher: EventDispatcher,
owncast_client: RecordingOwncastClient,
) -> None:
"""A HIGHEST-priority event handler that stops propagation blocks commands."""
async def blocker(ctx: EventContext[object]) -> None:
ctx.stop_propagation("blocked")
module_context.events.register(
blocker, (EventType.CHAT,), priority=Priority.HIGHEST
)
async def cmd_handler(ctx: CommandContext) -> None:
await ctx.owncast_client.send_message("should not run")
module_context.commands.register("test", cmd_handler)
event = make_chat_event(raw_body="!test")
await event_dispatcher.dispatch(EventType.CHAT, event)
assert owncast_client.calls == []
async def test_permission_denied_sends_system_message(
self,
module_context: ModuleContext,
event_dispatcher: EventDispatcher,
owncast_client: RecordingOwncastClient,
) -> None:
"""Authenticated-only command from unauth user sends denial."""
async def handler(ctx: CommandContext) -> None:
await ctx.owncast_client.send_message("should not run")
module_context.commands.register("secret", handler, requires_authenticated=True)
user = make_user(is_authenticated=False)
event = make_chat_event(raw_body="!secret", user=user, client_id=42)
await event_dispatcher.dispatch(EventType.CHAT, event)
assert len(owncast_client.calls) == 1
assert owncast_client.calls[0][0] == "send_system_message_to_client"
class TestRouteClient:
"""Integration tests exercising the route_client fixture."""
async def test_get_registered_route(
self,
module_context: ModuleContext,
route_client: TestClient[Any, Any],
) -> None:
"""GET a registered route; verify 200 and JSON body."""
async def handler(ctx: Any) -> dict[str, int]:
return {"total": 42}
module_context.routes.register("/stats", handler, methods=["GET"])
resp = await route_client.get("/owlbot/test_module/stats")
assert resp.status == 200
body = await resp.json()
assert body == {"total": 42}
async def test_unregistered_route_returns_404(
self,
route_client: TestClient[Any, Any],
) -> None:
"""GET a path with no registered handler; verify 404."""
resp = await route_client.get("/owlbot/test_module/nonexistent")
assert resp.status == 404
async def test_module_root_reachable_without_trailing_slash(
self,
module_context: ModuleContext,
route_client: TestClient[Any, Any],
) -> None:
"""A root-registered handler is reachable via /owlbot/{module_name}.
Production registers two aiohttp routes for the catch-all so that
root handlers respond to both ``/owlbot/{module_name}`` and
``/owlbot/{module_name}/``; the plugin must mirror that or modules
with root routes will silently 404 in tests but work in production.
"""
async def handler(ctx: Any) -> dict[str, str]:
return {"status": "root"}
module_context.routes.register("/", handler, methods=["GET"])
resp = await route_client.get("/owlbot/test_module")
assert resp.status == 200
body = await resp.json()
assert body == {"status": "root"}
async def test_post_route(
self,
module_context: ModuleContext,
route_client: TestClient[Any, Any],
) -> None:
"""POST to a registered route; verify 200."""
async def handler(ctx: Any) -> dict[str, str]:
return {"status": "created"}
module_context.routes.register("/items", handler, methods=["POST"])
resp = await route_client.post("/owlbot/test_module/items")
assert resp.status == 200
async def test_method_not_allowed(
self,
module_context: ModuleContext,
route_client: TestClient[Any, Any],
) -> None:
"""Register a POST-only route, GET it; verify 405."""
async def handler(ctx: Any) -> dict[str, str]:
return {"status": "ok"}
module_context.routes.register("/submit", handler, methods=["POST"])
resp = await route_client.get("/owlbot/test_module/submit")
assert resp.status == 405
async def test_none_response_returns_204(
self,
module_context: ModuleContext,
route_client: TestClient[Any, Any],
) -> None:
"""Handler returning None; verify 204."""
async def handler(ctx: Any) -> None:
return None
module_context.routes.register("/noop", handler, methods=["GET"])
resp = await route_client.get("/owlbot/test_module/noop")
assert resp.status == 204
+392
View File
@@ -0,0 +1,392 @@
# Copyright 2026 Logan Fick
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for owlbot.testing recording stubs and stub config."""
from __future__ import annotations
import inspect
from typing import Any, get_origin, get_type_hints
import pytest
from owlbot.api.owncast_admin_client import OwncastAdminClient
from owlbot.api.owncast_client import OwncastClient
from owlbot.testing.stubs import (
RecordedCall,
RecordingOwncastAdminClient,
RecordingOwncastClient,
)
def _public_async_methods(cls: type) -> set[str]:
"""Return the set of public (non-underscore) async method names on cls."""
return {
name
for name, method in inspect.getmembers(cls, predicate=inspect.isfunction)
if not name.startswith("_") and inspect.iscoroutinefunction(method)
}
def _synthesize_value(param_name: str, annotation: Any) -> Any:
"""Build a distinct, type-appropriate value for a parameter.
Values differ per parameter so that a transposed key or value inside a
stub's ``RecordedCall`` dict literal is caught by equality against the
originally-passed kwargs.
"""
origin = get_origin(annotation)
if origin is list:
return []
if origin is dict:
return {}
if annotation is str:
return f"stub:{param_name}"
if annotation is int:
return hash(param_name) & 0xFFFF
if annotation is bool:
return True
msg = f"Unsupported annotation {annotation!r} for parameter {param_name!r}"
raise TypeError(msg)
@pytest.mark.parametrize(
("source", "stub"),
[
pytest.param(OwncastClient, RecordingOwncastClient, id="owncast-client"),
pytest.param(
OwncastAdminClient, RecordingOwncastAdminClient, id="owncast-admin-client"
),
],
)
class TestStubClientParity:
"""Guards against drift between real clients and their recording stubs.
These tests fail when the real client gains, loses, or changes a public
async method without a matching update to the stub. The stub is meant
to be a hand-written 1:1 mirror; CI enforces that invariant here.
"""
def test_stub_covers_every_public_async_method(
self, source: type, stub: type
) -> None:
"""Every public async method on the source must exist on the stub."""
missing = _public_async_methods(source) - _public_async_methods(stub)
assert not missing, f"Stub missing methods: {sorted(missing)}"
def test_stub_has_no_extra_public_async_methods(
self, source: type, stub: type
) -> None:
"""The stub must not expose methods the real client does not have."""
extra = _public_async_methods(stub) - _public_async_methods(source)
assert not extra, f"Stub has extra methods: {sorted(extra)}"
def test_stub_signatures_match(self, source: type, stub: type) -> None:
"""Each stub method's signature must match the source's exactly."""
mismatches: list[str] = []
for name in sorted(_public_async_methods(source)):
source_sig = inspect.signature(getattr(source, name))
stub_sig = inspect.signature(getattr(stub, name))
if source_sig != stub_sig:
mismatches.append(
f" {name}:\n source: {source_sig}\n stub: {stub_sig}"
)
assert not mismatches, "Signature mismatches:\n" + "\n".join(mismatches)
@pytest.mark.parametrize(
("source", "stub"),
[
pytest.param(OwncastClient, RecordingOwncastClient, id="owncast-client"),
pytest.param(
OwncastAdminClient, RecordingOwncastAdminClient, id="owncast-admin-client"
),
],
)
class TestStubRecordingFidelity:
"""Ensures each stub method records the exact args it received.
``TestStubClientParity`` guards method signatures. These tests guard the
hand-written ``RecordedCall(name, {...})`` literals inside each stub body:
call every public async method with distinct synthesized kwargs and
confirm the recorded call name and kwargs dict match exactly. Catches
typos in keys (``"user": user_id`` vs ``"user_id": user_id``) and value
transpositions that signature parity cannot see.
"""
async def test_every_method_records_passed_kwargs_faithfully(
self, source: type, stub: type
) -> None:
"""Every public async method records its method name and kwargs."""
instance = stub()
mismatches: list[str] = []
for name in sorted(_public_async_methods(source)):
hints = get_type_hints(getattr(source, name))
sig = inspect.signature(getattr(source, name))
kwargs = {
p_name: _synthesize_value(p_name, hints[p_name])
for p_name in sig.parameters
if p_name != "self"
}
instance.calls.clear()
await getattr(instance, name)(**kwargs)
if len(instance.calls) != 1:
mismatches.append(
f"{name}: expected 1 recorded call, got {len(instance.calls)}"
)
continue
call = instance.calls[0]
if call.name != name:
mismatches.append(f"{name}: recorded under wrong name {call.name!r}")
if call.kwargs != kwargs:
mismatches.append(
f"{name}:\n expected: {kwargs}\n recorded: {call.kwargs}"
)
assert not mismatches, "Recording fidelity failures:\n" + "\n".join(mismatches)
class TestRecordingOwncastClient:
"""Exercises the RecordingOwncastClient stub."""
async def test_send_message_records_call(self) -> None:
"""send_message appends the method name and all args to calls."""
client = RecordingOwncastClient()
result = await client.send_message("hello")
assert result == ""
assert client.calls == [
("send_message", {"body": "hello", "unsanitized": False})
]
async def test_unsanitized_true_is_recorded(self) -> None:
"""unsanitized=True is included in the kwargs dict."""
client = RecordingOwncastClient()
await client.send_message("hello", unsanitized=True)
assert client.calls == [
("send_message", {"body": "hello", "unsanitized": True})
]
async def test_unsanitized_false_is_recorded(self) -> None:
"""unsanitized=False (the default) is recorded explicitly."""
client = RecordingOwncastClient()
await client.send_message("hello", unsanitized=False)
assert client.calls == [
("send_message", {"body": "hello", "unsanitized": False})
]
async def test_send_system_message_to_client_records_args(self) -> None:
"""send_system_message_to_client records all arguments."""
client = RecordingOwncastClient()
result = await client.send_system_message_to_client(42, "whisper")
assert result == ""
assert client.calls == [
(
"send_system_message_to_client",
{"client_id": 42, "body": "whisper", "unsanitized": False},
)
]
async def test_multiple_calls_recorded_in_order(self) -> None:
"""Multiple calls are recorded in the order they happen."""
client = RecordingOwncastClient()
await client.send_message("first")
await client.send_system_message("second")
await client.send_action("third")
assert len(client.calls) == 3
assert client.calls[0] == (
"send_message",
{"body": "first", "unsanitized": False},
)
assert client.calls[1] == (
"send_system_message",
{"body": "second", "unsanitized": False},
)
assert client.calls[2] == (
"send_action",
{"body": "third", "unsanitized": False},
)
async def test_get_chat_history_returns_empty_list(self) -> None:
"""get_chat_history returns [] and records the call."""
client = RecordingOwncastClient()
result = await client.get_chat_history()
assert result == []
assert client.calls == [("get_chat_history", {})]
async def test_get_connected_clients_returns_empty_list(self) -> None:
"""get_connected_clients returns [] and records the call."""
client = RecordingOwncastClient()
result = await client.get_connected_clients()
assert result == []
assert client.calls == [("get_connected_clients", {})]
async def test_get_status_returns_empty_dict(self) -> None:
"""get_status returns {} and records the call."""
client = RecordingOwncastClient()
result = await client.get_status()
assert result == {}
assert client.calls == [("get_status", {})]
async def test_post_methods_return_empty_string(self) -> None:
"""All post-style methods return empty string."""
client = RecordingOwncastClient()
assert await client.send_message("x") == ""
assert await client.send_system_message("x") == ""
assert await client.send_action("x") == ""
assert await client.send_system_message_to_client(1, "x") == ""
assert await client.set_message_visibility(["a"], visible=True) == ""
assert await client.set_stream_title("t") == ""
def test_base_url_property(self) -> None:
"""base_url returns the stub default."""
client = RecordingOwncastClient()
assert client.base_url == "http://localhost:8080"
async def test_set_message_visibility_records_args(self) -> None:
"""set_message_visibility records message_ids and visible."""
client = RecordingOwncastClient()
await client.set_message_visibility(["msg-1", "msg-2"], visible=False)
assert client.calls == [
(
"set_message_visibility",
{"message_ids": ["msg-1", "msg-2"], "visible": False},
)
]
async def test_set_stream_title_records_args(self) -> None:
"""set_stream_title records the title argument."""
client = RecordingOwncastClient()
await client.set_stream_title("New Title")
assert client.calls == [("set_stream_title", {"title": "New Title"})]
async def test_send_system_message_records_call(self) -> None:
"""send_system_message records body."""
client = RecordingOwncastClient()
await client.send_system_message("sys msg")
assert client.calls == [
("send_system_message", {"body": "sys msg", "unsanitized": False})
]
async def test_send_action_records_call(self) -> None:
"""send_action records body."""
client = RecordingOwncastClient()
await client.send_action("does a thing")
assert client.calls == [
("send_action", {"body": "does a thing", "unsanitized": False})
]
async def test_recorded_call_exposes_name_and_kwargs_attributes(self) -> None:
"""Recorded calls expose .name and .kwargs for attribute-style access."""
client = RecordingOwncastClient()
await client.send_message("hello")
call = client.calls[0]
assert call.name == "send_message"
assert call.kwargs == {"body": "hello", "unsanitized": False}
def test_recorded_call_equals_plain_tuple(self) -> None:
"""RecordedCall compares equal to a (name, kwargs) tuple, per its docstring.
Many tests assert against tuple literals
(e.g. ``client.calls == [("send_message", {...})]``); this test locks
the contract directly so a refactor of RecordedCall surfaces here
rather than as scattered per-method failures.
"""
assert RecordedCall("x", {"a": 1}) == ("x", {"a": 1})
assert RecordedCall("x", {}) != ("x", {"a": 1})
assert RecordedCall("x", {"a": 1}) != ("y", {"a": 1})
class TestRecordingOwncastAdminClient:
"""Exercises the RecordingOwncastAdminClient stub."""
async def test_get_status_records_and_returns_dict(self) -> None:
"""get_status records the call and returns {}."""
client = RecordingOwncastAdminClient()
result = await client.get_status()
assert result == {}
assert client.calls == [("get_status", {})]
async def test_set_user_enabled_records_args(self) -> None:
"""set_user_enabled records user_id and enabled."""
client = RecordingOwncastAdminClient()
await client.set_user_enabled("user-123", enabled=False)
assert client.calls == [
("set_user_enabled", {"user_id": "user-123", "enabled": False})
]
async def test_set_user_moderator_records_args(self) -> None:
"""set_user_moderator records user_id and is_mod."""
client = RecordingOwncastAdminClient()
await client.set_user_moderator("user-456", is_mod=True)
assert client.calls == [
("set_user_moderator", {"user_id": "user-456", "is_mod": True})
]
def test_base_url_property(self) -> None:
"""base_url returns the stub default."""
client = RecordingOwncastAdminClient()
assert client.base_url == "http://localhost:8080"
async def test_get_active_viewers_returns_empty_list(self) -> None:
"""get_active_viewers returns [] and records the call."""
client = RecordingOwncastAdminClient()
result = await client.get_active_viewers()
assert result == []
assert client.calls == [("get_active_viewers", {})]
async def test_get_hardware_stats_returns_empty_dict(self) -> None:
"""get_hardware_stats returns {} and records the call."""
client = RecordingOwncastAdminClient()
result = await client.get_hardware_stats()
assert result == {}
assert client.calls == [("get_hardware_stats", {})]
async def test_get_server_config_returns_empty_dict(self) -> None:
"""get_server_config returns {} and records the call."""
client = RecordingOwncastAdminClient()
result = await client.get_server_config()
assert result == {}
assert client.calls == [("get_server_config", {})]
async def test_ban_ip_address_records_args(self) -> None:
"""ban_ip_address records the ip argument."""
client = RecordingOwncastAdminClient()
await client.ban_ip_address("192.168.1.1")
assert client.calls == [("ban_ip_address", {"ip": "192.168.1.1"})]
async def test_unban_ip_address_records_args(self) -> None:
"""unban_ip_address records the ip argument."""
client = RecordingOwncastAdminClient()
await client.unban_ip_address("10.0.0.1")
assert client.calls == [("unban_ip_address", {"ip": "10.0.0.1"})]
async def test_disconnect_stream_returns_empty_dict(self) -> None:
"""disconnect_stream returns {} and records the call."""
client = RecordingOwncastAdminClient()
result = await client.disconnect_stream()
assert result == {}
assert client.calls == [("disconnect_stream", {})]
async def test_get_logs_returns_empty_list(self) -> None:
"""get_logs returns [] and records the call."""
client = RecordingOwncastAdminClient()
result = await client.get_logs()
assert result == []
assert client.calls == [("get_logs", {})]
async def test_get_warnings_returns_empty_list(self) -> None:
"""get_warnings returns [] and records the call."""
client = RecordingOwncastAdminClient()
result = await client.get_warnings()
assert result == []
assert client.calls == [("get_warnings", {})]
-1003
View File
File diff suppressed because it is too large Load Diff